memstead-base 0.22.0

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
//! The check operation and derived check state.
//!
//! `record_check` is the engine-recorded act of verification: it
//! appends one [`crate::check::CheckRecord`] — verdict, method note,
//! the entity's `content_hash` at check time, and plan-13 provenance
//! (actor, client, declared role) — to the workspace check ledger.
//! Checking mutates nothing: no entity write, no mem commit, no
//! `content_hash` change. That non-mutation is load-bearing — it is
//! what makes check-staleness derivable by hash comparison.
//!
//! `entity_check_state` derives never-checked | checked-ok |
//! check-failed | check-stale from the newest record against the
//! entity's current hash; the derivation lives in
//! [`crate::check::derive_state`] so surfaces and health share one
//! implementation.

use crate::check::{CheckKind, CheckLedger, CheckRecord, CheckState, Verdict, derive_state};
use crate::vcs::{Actor, ClientId};

use super::{Engine, error::EngineError};

impl Engine {
    /// Record a check of one entity. Refuses typed on unknown mem
    /// (quarantine included), unknown entity, read-only mounts, and
    /// on any persistence failure (`CHECK_NOT_RECORDED`) — recording
    /// is never best-effort, because a caller who believes an
    /// unrecorded check landed is the exact dishonesty this tier
    /// removes. The declared role rides engine session state
    /// ([`Engine::set_role`]), same as every mutation.
    ///
    /// `kind` selects the closed check-kind vocabulary. A
    /// `conformance` record is bound to the mem's schema pin, stamped
    /// HERE from the mount — never caller-supplied, so a verdict
    /// cannot claim a prose version the caller never read; a mem with
    /// no pin refuses (`INVALID_INPUT`), because a semantic judgment
    /// against no schema binds to nothing.
    #[allow(clippy::too_many_arguments)] // the record's own fields, no natural grouping
    pub fn record_check(
        &mut self,
        mem_name: &str,
        entity_id: &str,
        verdict: Verdict,
        kind: CheckKind,
        method: Option<&str>,
        actor: Actor,
        client: Option<&ClientId>,
    ) -> Result<CheckRecord, EngineError> {
        self.record_check_with(
            mem_name,
            entity_id,
            verdict,
            &crate::check::RecordKind::Engine(kind),
            method,
            None,
            actor,
            client,
        )
    }

    /// [`Self::record_check`] with the full record shape: a kind that may
    /// be a caller-declared foreign `x-<name>` kind (recorded verbatim,
    /// never interpreted — it stamps no schema pin and moves no state),
    /// and an optional structured finding (validated before anything is
    /// appended; a malformed one refuses `INVALID_CHECK_FINDING`).
    #[allow(clippy::too_many_arguments)]
    pub fn record_check_with(
        &mut self,
        mem_name: &str,
        entity_id: &str,
        verdict: Verdict,
        kind: &crate::check::RecordKind,
        method: Option<&str>,
        finding: Option<crate::check::CheckFinding>,
        actor: Actor,
        client: Option<&ClientId>,
    ) -> Result<CheckRecord, EngineError> {
        if let Some(f) = &finding {
            f.validate()
                .map_err(|reason| EngineError::InvalidCheckFinding { reason })?;
            // The code namespace: `UPPER_SNAKE` claims an engine health
            // condition (the acknowledgement `health --strict` honours),
            // so it must name one; a checker's own vocabulary keeps any
            // other spelling. An acknowledgement (a `failed` verdict on a
            // condition) names its owner and the closing plan in `method`.
            if crate::ops::strict::is_engine_code_shape(&f.code)
                && !crate::ops::strict::is_health_condition(&f.code)
            {
                return Err(EngineError::InvalidCheckFinding {
                    reason: format!(
                        "finding.code `{}` is spelled in the engine's UPPER_SNAKE namespace but \
                         names no health condition — an acknowledgement names one of: {}; a \
                         checker's own code takes another spelling (`hidden-premise`)",
                        f.code,
                        crate::ops::strict::HEALTH_CONDITIONS.join(", ")
                    ),
                });
            }
            if crate::ops::strict::is_health_condition(&f.code)
                && verdict == Verdict::Failed
                && method.is_none_or(|m| m.trim().is_empty())
            {
                return Err(EngineError::InvalidCheckFinding {
                    reason: format!(
                        "an acknowledgement of `{}` names its owner and the plan that closes it \
                         in `method`, and none was given",
                        f.code
                    ),
                });
            }
        }
        let mount_idx = self
            .mounts
            .iter()
            .position(|m| m.mount.mem == mem_name)
            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
        }
        let schema_ref = match kind.engine_kind() {
            None | Some(CheckKind::Verification) => None,
            Some(CheckKind::Conformance) => Some(
                self.mounts[mount_idx]
                    .mount
                    .schema
                    .as_ref()
                    .map(|s| s.as_display())
                    .ok_or_else(|| {
                        EngineError::InvalidInput(format!(
                            "a conformance check binds to the mem's schema pin, and mem \
                             `{mem_name}` declares none"
                        ))
                    })?,
            ),
        };
        let entity_hash = self
            .store
            .all_entities()
            .find(|e| e.mem == mem_name && e.id.0 == entity_id)
            .map(|e| e.content_hash.clone())
            .ok_or_else(|| EngineError::NotFound {
                id: entity_id.to_string(),
            })?;
        let Some(root) = self.workspace_root() else {
            return Err(EngineError::CheckNotRecorded {
                reason: "engine has no workspace root — no durable check store".to_string(),
            });
        };
        let ledger = CheckLedger::for_workspace(root);
        let record = CheckRecord {
            ts: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
            entity: entity_id.to_string(),
            verdict: verdict.as_str().to_string(),
            method: method
                .map(str::trim)
                .filter(|m| !m.is_empty())
                .map(str::to_string),
            entity_hash,
            actor: actor.as_trailer().to_string(),
            client: client.map(|c| format!("{}@{}", c.name, c.version)),
            role: self
                .current_role()
                .as_trailer()
                .unwrap_or("unspecified")
                .to_string(),
            // The caller-declared identity rides engine session state
            // ([`Engine::set_identity`]), same as the role — absence
            // records as absence (plan 15).
            identity: self.current_identity().map(str::to_string),
            // Verification records omit the kind entirely, so a
            // kind-omitted caller's ledger lines stay byte-identical
            // to the pre-kind shape.
            kind: match kind {
                crate::check::RecordKind::Engine(CheckKind::Verification) => None,
                other => Some(other.as_wire().to_string()),
            },
            schema_ref,
            finding,
            renamed_from: None,
            carried_from: None,
        };
        ledger
            .record(&record)
            .map_err(|e| EngineError::CheckNotRecorded {
                reason: format!("ledger append failed: {e}"),
            })?;
        Ok(record)
    }

    /// Carry the check ledger across a rename: every line recorded under
    /// `old` is appended again under `new`, marked `renamed_from`, so the
    /// renamed entity keeps its check history instead of reading
    /// `never_checked` while its record sits unreachable under an id
    /// nothing resolves any more. The carried lines keep their hash, so
    /// they derive `check_stale` against the renamed file — a rename is
    /// a content change (title, self-links), and the verdict is not
    /// re-asserted on content the checker never saw. An engine with no
    /// workspace root has no ledger and carries nothing. A failed
    /// append refuses, as recording does: the caller runs this before
    /// the rename commits.
    pub(crate) fn carry_checks_across_rename(
        &self,
        old: &crate::entity::EntityId,
        new: &crate::entity::EntityId,
    ) -> Result<usize, EngineError> {
        let Some(root) = self.workspace_root() else {
            return Ok(0);
        };
        CheckLedger::for_workspace(root)
            .carry_rename(old.as_ref(), new.as_ref())
            .map_err(|e| EngineError::CheckNotRecorded {
                reason: format!("ledger carry across rename {old} → {new} failed: {e}"),
            })
    }

    /// The `transition_requires_self_check` kinds a prepared write passes
    /// on the strength of a fresh, independent record: every such
    /// constraint of `type_def` whose gated value `next` holds and whose
    /// declared kind the provider confirms against `next.content_hash`
    /// (the PRE-write hash: the caller hands the composed entity before
    /// the store or disk moved). These are the records the write is
    /// about to stale; [`Self::carry_checks_across_transition`] carries
    /// them. Empty when the type declares no such gate or none passes.
    pub(crate) fn licensed_self_check_kinds(
        &self,
        next: &crate::entity::Entity,
        type_def: &memstead_schema::TypeDefinition,
    ) -> Vec<String> {
        let provider = self.check_standing_provider();
        let mut kinds: Vec<String> = Vec::new();
        for c in &type_def.constraints {
            let memstead_schema::ConstraintDef::TransitionRequiresSelfCheck {
                field,
                to_value,
                check_kind,
                ..
            } = c
            else {
                continue;
            };
            let triggered = next
                .metadata
                .get(field.as_str())
                .is_some_and(|v| v.to_frontmatter_string() == *to_value);
            if triggered && !kinds.contains(check_kind) && provider(next, check_kind).confirms() {
                kinds.push(check_kind.clone());
            }
        }
        kinds
    }

    /// Carry the records that licensed a gated transition across the
    /// write they licensed: for each wire kind in `kinds`, the newest
    /// record of `id` that is fresh at `pre_hash` and confirming is
    /// appended again keyed to `post_hash`, marked
    /// `carried_from: {hash, reason: "transition"}`
    /// ([`CheckLedger::carry_transition`]). Without this the write that
    /// a `transition_requires_self_check` gate admitted moves the
    /// entity's hash and stales the very record that admitted it, so the
    /// constraint reads unsatisfied the moment after it was satisfied.
    /// The carried line keeps the checker's identity: the writer is not
    /// the checker, and independence must go on reading it that way. A
    /// stale or failed record is not carried, it licensed nothing. An
    /// engine with no workspace root has no ledger and carries nothing.
    /// A failed append refuses, as recording does: the caller runs this
    /// before the write is staged. Returns the number of lines carried.
    pub(crate) fn carry_checks_across_transition(
        &self,
        id: &crate::entity::EntityId,
        kinds: &[String],
        pre_hash: &str,
        post_hash: &str,
    ) -> Result<usize, EngineError> {
        if kinds.is_empty() || pre_hash == post_hash {
            return Ok(0);
        }
        let Some(root) = self.workspace_root() else {
            return Ok(0);
        };
        let ledger = CheckLedger::for_workspace(root);
        let mut carried = 0;
        for kind in kinds {
            let moved = ledger
                .carry_transition(id.as_ref(), kind, pre_hash, post_hash)
                .map_err(|e| EngineError::CheckNotRecorded {
                    reason: format!(
                        "ledger carry of the `{kind}` record across the transition of {id} failed: {e}"
                    ),
                })?;
            carried += usize::from(moved);
        }
        Ok(carried)
    }

    /// The newest check record of one entity under one wire kind, from
    /// the one source the mount has: the sealed member for an archive
    /// mount (a workspace ledger beside it is never consulted, and an
    /// archive sealed without records has none), the workspace ledger
    /// for every other mount (a writable mem never reads a sealed
    /// member; an engine with no workspace root has no ledger). Every
    /// check-state read goes through here, so the derivation is the same
    /// whatever the mount.
    pub fn latest_check_record(
        &self,
        mem_name: &str,
        entity_id: &str,
        kind: &str,
    ) -> Option<CheckRecord> {
        if self.is_archive_mount(mem_name) {
            let path = crate::EntityId(entity_id.to_string());
            return self
                .archive_checks_for(mem_name)
                .and_then(|sealed| sealed.latest(path.path(), kind))
                .map(|sc| sc.to_record(entity_id, kind));
        }
        self.workspace_root()
            .map(CheckLedger::for_workspace)
            .and_then(|l| l.latest_for_wire_kind(entity_id, kind))
    }

    /// The newest record per foreign `x-<name>` kind of one entity, in
    /// kind order, from the same source as [`Self::latest_check_record`].
    /// Recorded, listed, never aggregated into a state.
    pub fn latest_foreign_checks(&self, mem_name: &str, entity_id: &str) -> Vec<CheckRecord> {
        if self.is_archive_mount(mem_name) {
            let path = crate::EntityId(entity_id.to_string());
            return self
                .archive_checks_for(mem_name)
                .map(|sealed| {
                    sealed
                        .kinds_of(path.path())
                        .filter(|(k, _)| k.starts_with(crate::check::FOREIGN_KIND_PREFIX))
                        .map(|(k, sc)| sc.to_record(entity_id, k))
                        .collect()
                })
                .unwrap_or_default();
        }
        let Some(ledger) = self.workspace_root().map(CheckLedger::for_workspace) else {
            return Vec::new();
        };
        let mut latest: std::collections::BTreeMap<String, CheckRecord> =
            std::collections::BTreeMap::new();
        for rec in ledger.all() {
            if rec.entity != entity_id {
                continue;
            }
            if let Some(k) = rec.foreign_kind() {
                latest.insert(k.to_string(), rec.clone());
            }
        }
        latest.into_values().collect()
    }

    /// Derive one entity's check state and newest check record.
    /// Refuses typed on unknown mem/entity; an engine with no
    /// workspace root has no check store and honestly derives
    /// `never_checked` (no recorded checks exist); an archive mount
    /// derives from its sealed member the same way.
    pub fn entity_check_state(
        &self,
        mem_name: &str,
        entity_id: &str,
    ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
        self.find_mount(mem_name)?;
        let current_hash = self
            .store
            .all_entities()
            .find(|e| e.mem == mem_name && e.id.0 == entity_id)
            .map(|e| e.content_hash.clone())
            .ok_or_else(|| EngineError::NotFound {
                id: entity_id.to_string(),
            })?;
        let latest =
            self.latest_check_record(mem_name, entity_id, CheckKind::Verification.as_str());
        Ok((derive_state(latest.as_ref(), &current_hash), latest))
    }

    /// Derive one entity's `conformance` state and newest conformance
    /// record: hash staleness plus pin staleness (a re-pinned or
    /// unpinned mem stales the verdict — the prose it judged against
    /// is no longer the prose in force). Same refusals as
    /// [`Self::entity_check_state`].
    pub fn entity_conformance_state(
        &self,
        mem_name: &str,
        entity_id: &str,
    ) -> Result<(CheckState, Option<CheckRecord>), EngineError> {
        let mount = self.find_mount(mem_name)?;
        let current_pin = mount.mount.schema.as_ref().map(|s| s.as_display());
        let current_hash = self
            .store
            .all_entities()
            .find(|e| e.mem == mem_name && e.id.0 == entity_id)
            .map(|e| e.content_hash.clone())
            .ok_or_else(|| EngineError::NotFound {
                id: entity_id.to_string(),
            })?;
        let latest = self.latest_check_record(mem_name, entity_id, CheckKind::Conformance.as_str());
        Ok((
            crate::check::derive_state_pinned(
                latest.as_ref(),
                &current_hash,
                current_pin.as_deref(),
            ),
            latest,
        ))
    }
}

#[cfg(test)]
mod tests {
    use crate::check::{CheckKind, CheckLedger, CheckRecord, CheckState, Verdict};
    use crate::vcs::Actor;
    use crate::workspace::MountCapability;

    /// A conformance check binds to the mem's schema pin; a mem that
    /// declares none cannot accept one. Today that refusal arrives as
    /// the quarantine gate (an unpinned mem quarantines at boot and
    /// serves nothing), which fires before the pin guard inside
    /// `record_check`; the guard's own `INVALID_INPUT` remains as
    /// defense in depth for any future backend that serves unpinned.
    #[test]
    fn conformance_refuses_without_a_schema_pin() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("anything.md"),
            "---\nid: anything\ntitle: Anything\ntype: note\n---\n\nBody.\n",
        )
        .unwrap();
        let mut mount = crate::engine::test_helpers::folder_mount("m", tmp.path().to_path_buf());
        mount.schema = None;
        let mut engine = crate::Engine::from_mounts(vec![(
            mount,
            Box::new(crate::storage::FilesystemBackend::new(
                tmp.path().to_path_buf(),
            )) as Box<dyn crate::backend::MemBackend>,
        )])
        .unwrap();
        let err = engine
            .record_check(
                "m",
                "m--anything",
                Verdict::Ok,
                CheckKind::Conformance,
                None,
                Actor::Cli,
                None,
            )
            .unwrap_err();
        assert_eq!(err.code(), "MEM_QUARANTINED");
    }

    // --- the licensing record carries across the transition it licensed ---

    /// A workspace-rooted folder mem `bundles` whose `plan` type gates
    /// `status: complete` on a fresh independent record of `check_kind`
    /// on the plan itself (`transition_requires_self_check`).
    fn self_check_gated_engine(tmp: &tempfile::TempDir, check_kind: &str) -> crate::Engine {
        // The workspace's fixed authored-schema location, so an export
        // of the mem finds the schema source to embed.
        let schemas_dir = tmp.path().join(".memstead").join("schemas");
        let pkg = schemas_dir.join("selfgate");
        std::fs::create_dir_all(pkg.join("types")).unwrap();
        std::fs::write(
            pkg.join("schema.yaml"),
            r#"name: selfgate
version: 0.1.0
description: self-check gate fixture
when_to_use: tests
types:
  - plan
relationships:
  mode: strict
  definitions:
    - name: PART_OF
      description: hier
      default_weight: 3.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#,
        )
        .unwrap();
        std::fs::write(
            pkg.join("types").join("plan.yaml"),
            format!(
                r#"name: plan
description: p
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields:
  - key: status
    description: s
    field_type: string
    default_value: draft
    enum_values: [draft, complete]
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
updatable_fields:
  - title
  - body
  - status
health_required_fields: []
staleness_threshold_days: 90
constraints:
  - kind: transition_requires_self_check
    field: status
    to_value: complete
    check_kind: {check_kind}
    severity: block
write_rules: []
"#
            ),
        )
        .unwrap();
        let mem_dir = tmp.path().join("bundles");
        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
        std::fs::write(
            mem_dir.join(".memstead").join("config.json"),
            r#"{"format": 1, "schema": "selfgate@0.1.0", "version": "1.0.0"}"#,
        )
        .unwrap();
        let writer = crate::storage::FilesystemBackend::new(mem_dir.clone());
        let mount = crate::workspace::Mount {
            mem: "bundles".to_string(),
            schema: Some(memstead_schema::SchemaRef::new(
                "selfgate",
                semver::Version::new(0, 1, 0),
            )),
            storage: crate::workspace::MountStorage::Folder { path: mem_dir },
            capability: crate::workspace::MountCapability::Write,
            lifecycle: crate::workspace::MountLifecycle::Eager,
            cross_linkable: true,
            migration_target: None,
        };
        let mut engine = crate::Engine::from_mounts_with_schemas_dir(
            vec![(
                mount,
                Box::new(writer) as Box<dyn crate::backend::MemBackend>,
            )],
            Some(&schemas_dir),
        )
        .unwrap();
        engine.set_workspace_root(tmp.path().to_path_buf());
        engine
    }

    fn create_plan(engine: &mut crate::Engine, title: &str) -> crate::entity::EntityId {
        let (actor, client) = crate::engine::test_helpers::cli_actor();
        let mut sections = indexmap::IndexMap::new();
        sections.insert("body".to_string(), "the plan body.".to_string());
        engine
            .create_entity(
                crate::engine::CreateEntityArgs {
                    anchors: Vec::new(),
                    mem: "bundles".to_string(),
                    title: title.to_string(),
                    entity_type: "plan".to_string(),
                    sections,
                    metadata: indexmap::IndexMap::new(),
                    relations: Vec::new(),
                    dry_run: false,
                },
                actor,
                Some(&client),
                None,
            )
            .unwrap()
            .id
    }

    fn set_status(
        engine: &mut crate::Engine,
        id: &crate::entity::EntityId,
        value: &str,
    ) -> Result<crate::engine::UpdateEntityOutcome, crate::engine::error::EngineError> {
        let (actor, client) = crate::engine::test_helpers::cli_actor();
        let current = engine.get_entity(id).unwrap().content_hash.clone();
        let mut metadata = indexmap::IndexMap::new();
        metadata.insert("status".to_string(), value.to_string());
        engine.update_entity(
            crate::engine::UpdateEntityArgs {
                anchors: Vec::new(),
                id: id.clone(),
                expected_hash: Some(current),
                sections: indexmap::IndexMap::new(),
                append_sections: indexmap::IndexMap::new(),
                patch_sections: indexmap::IndexMap::new(),
                sections_unset: Vec::new(),
                metadata,
                metadata_unset: Vec::new(),
                declare_relations: vec![],
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
    }

    fn append_body(engine: &mut crate::Engine, id: &crate::entity::EntityId) {
        let (actor, client) = crate::engine::test_helpers::cli_actor();
        let current = engine.get_entity(id).unwrap().content_hash.clone();
        let mut append = indexmap::IndexMap::new();
        append.insert("body".to_string(), "more.".to_string());
        engine
            .update_entity(
                crate::engine::UpdateEntityArgs {
                    anchors: Vec::new(),
                    id: id.clone(),
                    expected_hash: Some(current),
                    sections: indexmap::IndexMap::new(),
                    append_sections: append,
                    patch_sections: indexmap::IndexMap::new(),
                    sections_unset: Vec::new(),
                    metadata: indexmap::IndexMap::new(),
                    metadata_unset: Vec::new(),
                    declare_relations: vec![],
                    dry_run: false,
                    relations_unset: Vec::new(),
                    anchors_unset: Vec::new(),
                },
                actor,
                Some(&client),
                None,
            )
            .unwrap();
    }

    fn check_plan(
        engine: &mut crate::Engine,
        identity: &str,
        id: &crate::entity::EntityId,
        kind: &str,
    ) {
        check_plan_as(engine, identity, crate::vcs::Role::Checker, id, kind);
    }

    /// A check under `identity` declared in `role`: the walker's shape
    /// is `checker`; `author` and `unspecified` are the roles a gate
    /// refuses.
    fn check_plan_as(
        engine: &mut crate::Engine,
        identity: &str,
        role: crate::vcs::Role,
        id: &crate::entity::EntityId,
        kind: &str,
    ) {
        let (actor, client) = crate::engine::test_helpers::cli_actor();
        engine.set_identity(Some(identity.to_string()));
        engine.set_role(role);
        engine
            .record_check_with(
                "bundles",
                id.as_ref(),
                Verdict::Ok,
                &crate::check::RecordKind::from_wire(kind).unwrap(),
                Some("projection walked"),
                None,
                actor,
                Some(&client),
            )
            .unwrap();
        engine.set_role(crate::vcs::Role::Unspecified);
    }

    /// The defect: a bundle carries a fresh `x-projection` ok record under
    /// an independent identity, the author's `status: complete` passes
    /// the gate, and the write moves the hash; before the carry, the
    /// constraints axis reported the gate unsatisfied (`check_stale`) the
    /// moment after it admitted the write. Now the licensing record is
    /// carried to the post-write hash, marked, still the checker's; the
    /// constraints axis stays clean and the gate keeps holding across a
    /// later write to the complete plan.
    #[test]
    fn licensing_self_check_carries_across_the_transition_it_admitted() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = self_check_gated_engine(&tmp, "x-projection");
        engine.set_identity(Some("author-a".to_string()));
        let id = create_plan(&mut engine, "The Bundle");
        let hash_at_check = engine.get_entity(&id).unwrap().content_hash.clone();
        check_plan(&mut engine, "checker-c", &id, "x-projection");

        engine.set_identity(Some("author-a".to_string()));
        let outcome = set_status(&mut engine, &id, "complete").expect("the gate admits the write");
        assert_ne!(
            outcome.content_hash, hash_at_check,
            "the write moved the hash"
        );

        // The constraints axis reads no violation after the write.
        let findings = engine.constraint_findings(Some("bundles"));
        assert!(findings.is_empty(), "{findings:?}");

        // The carried line: post-write hash, marked, the checker's identity.
        let foreign = engine.latest_foreign_checks("bundles", id.as_ref());
        assert_eq!(foreign.len(), 1);
        let carried = &foreign[0];
        assert_eq!(carried.entity_hash, outcome.content_hash);
        assert_eq!(carried.identity.as_deref(), Some("checker-c"));
        assert_eq!(carried.method.as_deref(), Some("projection walked"));
        assert_eq!(
            carried.carried_from,
            Some(crate::check::CarriedFrom::transition(&hash_at_check))
        );
        // The gate's own reading of the carried record: fresh and independent.
        let entity = engine.get_entity(&id).unwrap().clone();
        let standing = (engine.check_standing_provider())(&entity, "x-projection");
        assert!(standing.confirms(), "{standing:?}");
        // Append-only: the checker's original line stays, unmarked.
        let ledger = CheckLedger::for_workspace(tmp.path());
        let lines: Vec<CheckRecord> = ledger
            .all()
            .into_iter()
            .filter(|r| r.entity == id.as_ref())
            .collect();
        assert_eq!(lines.len(), 2);
        assert!(lines[0].carried_from.is_none());
        assert_eq!(lines[0].entity_hash, hash_at_check);

        // A later write to the complete plan passes on the carried record
        // and carries it onward, so the gate keeps holding.
        engine.set_identity(Some("author-a".to_string()));
        append_body(&mut engine, &id);
        assert!(engine.constraint_findings(Some("bundles")).is_empty());
        let onward = &engine.latest_foreign_checks("bundles", id.as_ref())[0];
        assert_eq!(
            onward.entity_hash,
            engine.get_entity(&id).unwrap().content_hash
        );
        assert_eq!(
            onward.carried_from.as_ref().unwrap().hash,
            outcome.content_hash
        );
        // A write that leaves the gate unentered carries nothing: back to
        // draft, then an append, and the record is not moved again.
        set_status(&mut engine, &id, "draft").unwrap();
        let before = ledger.all().len();
        append_body(&mut engine, &id);
        assert_eq!(
            ledger.all().len(),
            before,
            "no gate passed, nothing carried"
        );
    }

    /// The `verification` kind through the same gate: after the write the
    /// entity's check state reads `checked_ok` and the health checks axis
    /// lists it `confirmed_independent`: the carried record stays the
    /// checker's, never the writer's.
    #[test]
    fn carried_verification_record_reads_checked_ok_and_independent() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = self_check_gated_engine(&tmp, "verification");
        engine.set_identity(Some("author-a".to_string()));
        let id = create_plan(&mut engine, "The Bundle");
        check_plan(&mut engine, "checker-c", &id, "verification");
        engine.set_identity(Some("author-a".to_string()));
        set_status(&mut engine, &id, "complete").expect("the gate admits the write");

        let (state, latest) = engine.entity_check_state("bundles", id.as_ref()).unwrap();
        assert_eq!(state, CheckState::CheckedOk);
        let latest = latest.unwrap();
        assert_eq!(latest.identity.as_deref(), Some("checker-c"));
        assert!(latest.carried_from.is_some());
        let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
        let independence = &axis["bundles"]["independence"];
        assert_eq!(
            independence["confirmed_independent"]["items"],
            serde_json::json!([id.as_ref()]),
            "{axis}"
        );
        assert_eq!(
            axis["bundles"]["checked_ok"],
            serde_json::json!(1),
            "{axis}"
        );
        assert!(engine.constraint_findings(Some("bundles")).is_empty());
    }

    /// The role is the gate's third condition, orthogonal to the reading.
    /// An independent identity's ok record declared in role `author`
    /// reads `confirmed_independent` on the checks axis (the identities
    /// differ, and the axis says so) and still refuses the gate under
    /// the label `role_author`; a record with no role refuses under
    /// `role_unspecified`; a `verifier` record confirms like a
    /// `checker`'s. The axis row carries the role and whether it
    /// confirms.
    #[test]
    fn a_record_in_role_author_or_without_a_role_does_not_close_the_gate() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = self_check_gated_engine(&tmp, "verification");
        engine.set_identity(Some("author-a".to_string()));
        let id = create_plan(&mut engine, "The Bundle");

        // An independent identity, declared as the author.
        check_plan_as(
            &mut engine,
            "checker-c",
            crate::vcs::Role::Author,
            &id,
            "verification",
        );
        let standing =
            (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
        assert_eq!(standing.state, CheckState::CheckedOk);
        assert_eq!(
            standing.independence,
            Some(crate::engine::independence::Independence::ConfirmedIndependent)
        );
        assert!(!standing.confirms(), "{standing:?}");
        assert_eq!(standing.label(), "role_author");
        engine.set_identity(Some("author-a".to_string()));
        let err = set_status(&mut engine, &id, "complete").unwrap_err();
        assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
        assert!(err.to_string().contains("role_author"), "{err}");
        let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
        let row = axis["bundles"]["independence"]["readings"][id.as_ref()]
            .as_array()
            .unwrap()
            .last()
            .unwrap();
        assert_eq!(row["reading"], "confirmed_independent", "{axis}");
        assert_eq!(row["role"], "author", "{axis}");
        assert_eq!(row["role_confirms"], false, "{axis}");

        // The same identity, no role declared.
        check_plan_as(
            &mut engine,
            "checker-c",
            crate::vcs::Role::Unspecified,
            &id,
            "verification",
        );
        let standing =
            (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
        assert!(!standing.confirms(), "{standing:?}");
        assert_eq!(standing.label(), "role_unspecified");
        engine.set_identity(Some("author-a".to_string()));
        let err = set_status(&mut engine, &id, "complete").unwrap_err();
        assert!(err.to_string().contains("role_unspecified"), "{err}");

        // A verifier's record confirms like a checker's.
        check_plan_as(
            &mut engine,
            "verifier-v",
            crate::vcs::Role::Verifier,
            &id,
            "verification",
        );
        let standing =
            (engine.check_standing_provider())(engine.get_entity(&id).unwrap(), "verification");
        assert!(standing.confirms(), "{standing:?}");
        engine.set_identity(Some("author-a".to_string()));
        set_status(&mut engine, &id, "complete").expect("a verifier's record closes the gate");
        let axis = crate::ops::health::health_checks_axis(&engine, Some("bundles"));
        let row = axis["bundles"]["independence"]["readings"][id.as_ref()]
            .as_array()
            .unwrap()
            .last()
            .unwrap();
        assert_eq!(row["role"], "verifier", "{axis}");
        assert_eq!(row["role_confirms"], true, "{axis}");
    }

    /// The gate on the archive mount. A complete plan exported to a
    /// `.mem` and mounted from bytes used to report
    /// `transition_requires_self_check` unsatisfied (`unconfirmable`):
    /// the mount has no provenance to derive independence from. The
    /// export seals the reading beside the record, so the mount's
    /// constraints axis is clean and its checks axis lists the plan
    /// `confirmed_independent`, exactly as the source engine did.
    #[test]
    fn sealed_independence_holds_the_transition_gate_on_the_archive_mount() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = self_check_gated_engine(&tmp, "verification");
        engine.set_identity(Some("author-a".to_string()));
        let id = create_plan(&mut engine, "The Bundle");
        check_plan(&mut engine, "checker-c", &id, "verification");
        engine.set_identity(Some("author-a".to_string()));
        set_status(&mut engine, &id, "complete").expect("the gate admits the write");
        assert!(engine.constraint_findings(Some("bundles")).is_empty());

        let bytes = engine.export_mem_to_bytes("bundles").unwrap();
        let mounted = crate::Engine::from_archive_bytes(bytes).unwrap();
        assert!(mounted.is_archive_mount("bundles"));
        let findings = mounted.constraint_findings(Some("bundles"));
        assert!(findings.is_empty(), "{findings:?}");
        let entity = mounted.get_entity(&id).unwrap();
        let standing = (mounted.check_standing_provider())(entity, "verification");
        assert!(standing.confirms(), "{standing:?}");
        let axis = crate::ops::health::health_checks_axis(&mounted, Some("bundles"));
        assert_eq!(
            axis["bundles"]["independence"]["confirmed_independent"]["items"],
            serde_json::json!([id.as_ref()]),
            "{axis}"
        );
        assert_eq!(
            axis["bundles"]["checked_ok"],
            serde_json::json!(1),
            "{axis}"
        );
    }

    /// A record already stale before the write licenses nothing: the
    /// write refuses as before, and the ledger gains no carried line.
    #[test]
    fn stale_self_check_is_not_carried_and_the_write_refuses() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = self_check_gated_engine(&tmp, "x-projection");
        engine.set_identity(Some("author-a".to_string()));
        let id = create_plan(&mut engine, "The Bundle");
        check_plan(&mut engine, "checker-c", &id, "x-projection");
        // The author edits after the check: the record goes stale.
        engine.set_identity(Some("author-a".to_string()));
        append_body(&mut engine, &id);
        let before = CheckLedger::for_workspace(tmp.path()).all().len();
        let err = set_status(&mut engine, &id, "complete").unwrap_err();
        assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED");
        assert!(err.to_string().contains("check_stale"), "{err}");
        assert_eq!(CheckLedger::for_workspace(tmp.path()).all().len(), before);
        assert_ne!(
            engine
                .get_entity(&id)
                .unwrap()
                .metadata
                .get("status")
                .map(|v| v.to_frontmatter_string())
                .as_deref(),
            Some("complete"),
            "the refused write left the entity as it was"
        );
    }

    /// Criterion 5 complement: a read-only mount refuses a check
    /// typed (`READ_ONLY_MOUNT`) — capability gating runs before the
    /// entity lookup, same as every mutation-shaped guard.
    #[test]
    fn check_refuses_read_only_mounts_typed() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut mount = crate::engine::test_helpers::folder_mount("ro", tmp.path().to_path_buf());
        mount.capability = MountCapability::ReadOnly;
        let mut engine = crate::Engine::from_mounts(vec![(
            mount,
            Box::new(crate::storage::FilesystemBackend::new(
                tmp.path().to_path_buf(),
            )) as Box<dyn crate::backend::MemBackend>,
        )])
        .unwrap();
        let err = engine
            .record_check(
                "ro",
                "ro--anything",
                Verdict::Ok,
                crate::check::CheckKind::Verification,
                None,
                Actor::Cli,
                None,
            )
            .unwrap_err();
        assert_eq!(err.code(), "READ_ONLY_MOUNT");
    }
}