memstead-base 0.27.1

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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
//! Unified engine.
//!
//! **One [`Engine`] type, three storage backends**: the engine sits
//! above [`MemBackend`] and routes reads / writes to the backend
//! named by each mount's mem. Consumers reach the engine through
//! [`Engine::from_workspace_root`] (folder + archive backends) or
//! `memstead_git_branch::engine_from_workspace_root` (adds git-branch).
//!
//! ## Routing
//!
//! Each mount holds one mem. Lookup is by mem name: the first
//! mount whose `mem` field equals the requested name wins. One mount
//! per mem is enforced — duplicates are a configuration bug, not a
//! feature, and the constructor rejects them.

use std::cell::OnceCell;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use memstead_schema::Schema;

use crate::backend::{BackendError, MemBackend};
use crate::graph::LouvainOutput;
use crate::mem::MemRouterSnapshot;
use crate::ops::WarningHint;
#[cfg(not(target_arch = "wasm32"))]
use crate::search_index::MemIndex;
use crate::store::Store;
use crate::workspace::{Mount, WorkspaceSettings};

pub mod apply_commit;
pub mod archive;
pub mod boot;
pub mod callers;
pub mod check_ops;
pub mod checks_transport;
pub mod conflicts;
pub mod drift;
pub mod due;
pub mod error;
pub mod events;
pub mod export_html;
pub mod export_llms_txt;
pub mod gates;
pub mod history;
pub mod independence;
pub mod lifecycle;
pub mod mutation;
pub mod outcomes;
pub mod proposal;
pub mod query;
pub mod review;
pub mod roster;
pub mod write_lock;

pub use archive::FromArchiveBytesError;
pub use error::{
    BootError, EngineError, INLINE_LIST_CAP, MissingWikiLink, ReferrerInfo, SchemaSourceDiagnostic,
    StaleCause, format_inline_list_overflow,
};
#[cfg(feature = "tokio")]
pub use events::DEFAULT_BROADCAST_CAPACITY;
pub use events::{EventCallback, MemChangedEvent, SubscriptionHandle};
pub use history::{
    EntityHistoryReport, EntityTouch, HISTORY_PAGE_DEFAULT, HISTORY_PAGE_MAX, StoryStart,
};
pub use mutation::delete::DeleteReferrers;
pub use mutation::{PATCH_OLD_NOT_FOUND_CONTENT_CAP, RELATIONSHIP_CYCLE_PATH_CAP};
pub use outcomes::{
    CreateEntityArgs, CreateEntityOutcome, DeleteEntityArgs, DeleteEntityOutcome, ExpectedHash,
    HashOverride, RelateAction, RelateEntityArgs, RelateEntityOutcome, RenameEntityArgs,
    RenameEntityOutcome, RetypeEdge, RetypeEdgeDirection, RetypeEntityArgs, RetypeEntityOutcome,
    RetypeProblem, SetSchemaOutcome, SetSchemaResult, UpdateEntityArgs, UpdateEntityOutcome,
};
pub use review::{ReviewMarkStatus, SetReviewMarkOutcome};

pub use boot::{SchemaResolver, load_workspace_schemas, resolve_builtin_schema_pin_pub};
pub use lifecycle::SchemaStaging;

/// One mem attachment, paired with the backend that serves it.
/// Constructed by [`Engine::from_mounts`] and held internally.
/// `pub(crate)` only so the crate-internal `boot::build_mem_router_from_mounts`
/// can name it in its signature — never re-exported.
pub(crate) struct MountedBackend {
    mount: Mount,
    /// Shared so the write-lock guard can hold the backends it locked
    /// and discard their staged writes when it drops
    /// ([`write_lock::MemWriteGuard`]).
    backend: std::sync::Arc<dyn MemBackend>,
    /// Last cursor returned by `backend.current_head()`. Seeded in
    /// [`Engine::from_mounts`]; refreshed by
    /// [`Engine::reload_if_stale`] after a successful reload.
    /// `None` means the backend doesn't track a head (folder /
    /// archive) — drift detection is a no-op for this mount.
    last_known_head: Option<String>,
    /// Per-mem `.memstead/config.json` payload — surfaces via
    /// [`Engine::mem_config_for`] for handlers that need
    /// `write_guidance` / `extra` (`memstead_health
    /// { include_config: true }`'s per-mem detail block).
    ///
    /// Read at construction through the backend's `read_mem_config`,
    /// whatever the storage kind (folder: `<path>/.memstead/config.json`;
    /// archive: the zip member; git-branch: the metadata branch's
    /// `mems/<leaf>/config.json`). `None` when the backend has no config
    /// or the payload does not parse.
    mem_config: Option<memstead_schema::config::MemConfig>,
    /// Per-mem authoring-provenance payload read from the archive's
    /// `.memstead/provenance.json` at construction (via
    /// [`crate::backend::MemBackend::read_archive_provenance`]). `None`
    /// when the backend carries no provenance member (a pre-provenance
    /// archive, or a backend that does not surface one) — surfaced as
    /// provenance-absent via [`Engine::archive_provenance_for`]. A
    /// malformed payload is downgraded to `None` rather than failing the
    /// mount: the member is additive.
    archive_provenance: Option<memstead_schema::ArchiveProvenance>,
    /// The sealed check records an archive mount carries
    /// (`.memstead/checks.json`), read at construction via
    /// [`crate::backend::MemBackend::read_archive_checks`]. `None` on
    /// every writable mount (their check state is the workspace
    /// ledger's) and on an archive sealed without records; every
    /// check-state read on an archive mount derives from this and never
    /// from a workspace ledger ([`Engine::archive_checks_for`]).
    archive_checks: Option<crate::check::SealedChecks>,
    /// `true` while a [`MountLifecycle::Lazy`] mount's entities have not
    /// been loaded into the store — the mount's metadata half (config,
    /// schema pin, provenance) is resolved at boot, the entity load is
    /// deferred to the first operation that needs the mem
    /// ([`Engine::ensure_mems_loaded`]). Always `false` for eager
    /// mounts, and permanently `false` once the deferred load lands.
    /// A deferred mem is never absent: it stays on the mount roster
    /// with its schema resolved, and every read surface either triggers
    /// the load or reports the state — silence is the one forbidden
    /// rendering.
    ///
    /// [`MountLifecycle::Lazy`]: crate::workspace::MountLifecycle::Lazy
    deferred: bool,
    /// Why the last drift reload of this mem failed, cleared by the next
    /// reload that succeeds. While it is set the engine's view of the
    /// mem is known to be behind storage: reads still serve it (a stale
    /// whole state beats no answer), a write does not land on it
    /// ([`Engine::commit_staged`] refuses), because a write computed
    /// from a stale view overwrites what the view has not seen.
    reload_failure: Option<ViewFailure>,
    /// A discard on this mem's backend failed, so writes of a mutation
    /// that did not commit may still be staged there. Set by the write
    /// lock when it is released (it shares the flag, since it cannot
    /// reach the engine then) and cleared by the discard the engine
    /// runs before its next operation.
    strays: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

/// Why a mem's view cannot take a write, with what failed: the record a
/// mount keeps until the next reload or discard that succeeds, and the
/// cause and detail of the `MEM_VIEW_STALE` a write is refused with.
#[derive(Debug, Clone)]
pub(crate) struct ViewFailure {
    pub(crate) cause: StaleCause,
    pub(crate) detail: String,
}

impl ViewFailure {
    /// The view is behind storage: a reload, a probe or a read failed.
    pub(crate) fn drift(detail: impl Into<String>) -> Self {
        Self {
            cause: StaleCause::Drift,
            detail: detail.into(),
        }
    }

    /// The refusal of a write on this view, naming `mem`.
    pub(crate) fn refusal(&self, mem: &str) -> EngineError {
        EngineError::StaleView {
            mem: mem.to_string(),
            cause: self.cause,
            detail: self.detail.clone(),
        }
    }
}

/// One quarantined mem: the mem-level boot failure that took it out of
/// service, and the retained mount record `reload` uses to re-attempt
/// the attach after a repair. The reason code/message are
/// typed material — the message's final clause names the repair
/// command, so the roster entry is actionable as-is.
#[derive(Debug, Clone)]
pub struct QuarantinedMem {
    /// The mount that failed to attach, retained verbatim for reload.
    pub mount: crate::workspace::Mount,
    /// Typed code of the underlying failure (e.g. `SCHEMA_NOT_FOUND`,
    /// `MEM_CONFIG_INCOMPLETE`, `MEM_ERROR`).
    pub reason_code: String,
    /// Full message of the underlying failure, repair command
    /// included.
    pub reason_message: String,
}

/// Unified engine. Holds a list of mounted backends and routes
/// mem-named operations to the right one.
///
/// `Send` so the engine can sit behind a `Mutex` (today's pattern
/// in the MCP server). The trait object's `Send + Sync` bound on
/// `MemBackend` keeps the inner backends thread-safe; the engine
/// itself is single-threaded by design (the lazy memos are
/// `OnceCell`, which is `!Sync`).
///
/// `Debug` is hand-written to avoid requiring `Debug` on the
/// `dyn MemBackend` trait object — backend impls are free to
/// stay non-`Debug`.
///
/// ## Load-on-init
///
/// `Engine::from_mounts` walks each backend at construction time
/// (`list_entities` + `read_entity` + parse) and populates a single
/// shared [`Store`] with entities and edges from every mount. Each
/// mount's schema resolves from its own pin (the backend config's
/// schema, or the mount-record assertion as fallback) through the
/// `SchemaResolver`, so `schemas` holds genuinely heterogeneous
/// schemas in a multi-schema workspace. Per-file errors don't fail
/// construction; they collect into [`Engine::load_errors`] for the
/// operator to inspect.
pub struct Engine {
    mounts: Vec<MountedBackend>,
    store: Store,
    schemas: HashMap<String, Arc<Schema>>,
    /// Workspace-authored schemas loaded from
    /// `WorkspaceSettings.schemas_dir` at construction. Distinct from
    /// `schemas` (per-mem, only schemas pinned by a mount): this
    /// catalogue carries every workspace-loaded schema regardless of
    /// whether a mem pins it. Surfaced via
    /// [`Self::workspace_schemas`] for handlers that need to enumerate
    /// schemas referenced by `mem_create_rules.schemas[]` but not
    /// pinned by any mem — `memstead_overview` lists them in `## Schemas`
    /// so an agent sees what could be pinned. Empty when no
    /// `schemas_dir` was passed.
    workspace_schemas: Vec<Arc<Schema>>,
    /// Embedded built-in schemas loaded once at boot from
    /// `memstead_schema::builtins::load_builtin_schemas()`. The boot path
    /// uses this catalogue to resolve each mount's schema pin; storing
    /// it on the engine lets read handlers (MCP's `memstead_schema`,
    /// `memstead_overview`'s `## Schemas` rendering) surface every built-in
    /// without re-walking the embedded directory. Schemas declared in
    /// `workspace_schemas` shadow built-ins on `(name, version)`
    /// collision — handlers walking both lists must check workspace
    /// first.
    builtin_schemas: Vec<Arc<Schema>>,
    load_errors: Vec<(PathBuf, String)>,
    /// Lazily-computed Louvain community detection across the
    /// engine-wide store. Populated on first call to
    /// [`Self::communities`]; invalidated by
    /// [`Self::invalidate_communities`] which every mutation method
    /// calls after a successful write. `OnceCell` is `!Sync`; the
    /// engine is `Send` (it is moved into a `Mutex` by every consumer)
    /// but not `Sync`.
    /// Generation-keyed: the memo carries the store
    /// generation it was computed at; the invalidation hook clears it
    /// only when the store has actually moved past that generation —
    /// which is what makes a rolled-back batch (store snapshot
    /// restored, generation restored with it) keep serving the memo
    /// its state was computed from, and makes it impossible for the
    /// rolled-back interim state to be served as fresh.
    community_memo: OnceCell<(DerivedKey, LouvainOutput)>,
    /// Grounded-labelling memo — one `MemLabelling` per mem whose
    /// schema declares `relationships.labelling`, computed on first
    /// access and invalidated exactly where the community memo is
    /// (the reset lives inside [`Self::invalidate_communities`], so
    /// every mutation site, drift reload, quarantine attach/detach
    /// and apply-commit invalidate both without a second call).
    /// Generation-keyed like `community_memo`.
    labelling_memo: OnceCell<(
        DerivedKey,
        HashMap<String, crate::ops::labelling::MemLabelling>,
    )>,
    /// Lazily-computed per-mem search index map. Built on first call
    /// to [`Self::search_indexes`] via [`build_all`]; invalidated by
    /// [`Self::invalidate_search_indexes`] alongside the community
    /// cache so every mutation triggers a fresh build on the next
    /// search. Absent on `wasm32` targets — search lives behind the
    /// bridge (see `EngineError::SearchUnavailable`).
    #[cfg(not(target_arch = "wasm32"))]
    /// Generation-keyed like `community_memo`.
    search_indexes_memo: OnceCell<(DerivedKey, HashMap<String, MemIndex>)>,
    /// The second half of [`DerivedKey`]: bumped whenever the
    /// `schemas` map changes (schema switch, mount register/remove).
    /// Both derived structures depend on schemas as well as the store
    /// — community weights and the index field set come from the
    /// pinned schema — so a schema change must invalidate them even
    /// though the STORE generation did not move (the schema-switch
    /// staleness the whole-map drop used to mask).
    schemas_epoch: u64,
    /// Workspace-level operator policy — mem create/delete rules,
    /// cross-mem link permissions. Defaults to empty; populated via
    /// [`Self::set_settings`] when [`Self::from_workspace_root`] (or
    /// the full counterpart) reads `.memstead/workspace.toml`. Surfaced
    /// read-only via [`Self::settings`] for MCP handlers and other
    /// consumers.
    settings: WorkspaceSettings,
    /// Lazily-compiled [`crate::mem_management::CreateRuleSet`] over
    /// `settings.mem_create_rules`. Built on first
    /// [`Self::cross_mem_link_allowed`] call that needs synthesis;
    /// invalidated by [`Self::set_settings`] (so a fresh policy
    /// re-compiles on the next call). Compilation errors are logged
    /// and the cache stays empty — synthesis is best-effort, the
    /// resolver falls back to explicit-policy resolution. Operators
    /// who want hard validation pre-compile via
    /// [`crate::mem_management::CreateRuleSet::new`] before passing
    /// settings.
    create_rule_set_memo: OnceCell<crate::mem_management::CreateRuleSet>,
    /// Per-mem data-trust origin declared by the embedding deployment
    /// (e.g. a curated hosted read tier vouching for a read-only mount as
    /// first-party). A *composition* fact set through
    /// [`Self::declare_mem_origin`] by the process that owns the engine —
    /// never persisted with the mem, never derived from mem content, and
    /// deliberately not reachable over MCP, so a publisher cannot forge
    /// first-party. Empty by default; [`Self::mem_origin_class`] falls back
    /// to the writability inference for undeclared mems.
    declared_origins: HashMap<String, crate::render::OriginClass>,
    /// The workspace's own writing identities, declared by the embedding
    /// deployment through [`Self::declare_owner_identities`]. A
    /// composition fact on the same terms as `declared_origins`: set by
    /// the process that owns the engine, never persisted with a mem,
    /// never reachable over MCP, so nothing that can write a mem-repo can
    /// add itself. It classifies text a party OTHER than the workspace
    /// authored into workspace state — a check row's method note and
    /// finding message, written by whatever agent the owner pointed at
    /// the ledger, under an identity the launching side assigned.
    ///
    /// Empty by default, and empty means undeclared: every ledger
    /// identity then inherits its mem's class, which is what the engine
    /// did before this field, so an existing deployment is byte-identical.
    /// A declared set makes an identity outside it third-party; a row with
    /// no identity at all stays unconfirmable and inherits, never guessed
    /// third-party (the same reading the independence gate takes).
    owner_identities: std::collections::BTreeSet<String>,
    /// Lazy per-mem map of entities whose claim-carrying sections are a
    /// contributor's bytes, read from each writable mem's proposal record:
    /// slug → the mark the merge recorded. Generation-keyed and
    /// invalidated exactly like `community_memo`, so a merge's own
    /// invalidation refreshes it. See [`Self::entity_origin_class`].
    foreign_entities_memo: OnceCell<(DerivedKey, ForeignMarks)>,
    /// Workspace root path — set when the engine boots from a
    /// workspace store ([`Self::from_workspace_root`] or the full
    /// counterpart). `None` for tests + ad-hoc consumers that build
    /// the engine directly from a mount list. Surfaced via
    /// [`Self::workspace_root`] for handlers that need filesystem
    /// context (e.g. [`Self::health`]'s outer-repo .gitignore
    /// check).
    workspace_root: Option<PathBuf>,
    /// The mount roster as this engine last read or last wrote it —
    /// the baseline [`Engine::persist_state`] diffs against so a state
    /// write publishes THIS engine's changes without republishing its
    /// whole cached view over whatever a sibling process has since
    /// registered. Interior mutability because `persist_state` takes
    /// `&self`; the engine is already `!Sync`.
    mounts_baseline: std::cell::RefCell<Vec<crate::workspace::Mount>>,
    /// Typed warnings surfaced during mem load — drift findings
    /// like [`WarningHint::SuspiciousNestedPrefix`] and
    /// [`WarningHint::DuplicateSectionHeading`] that the loader
    /// pipeline collects per entity. Empty for the V1 unified
    /// engine; the field is in place so handlers and the health
    /// surface can include them when the loader pipeline grows the
    /// warning generators.
    load_warnings: Vec<WarningHint>,
    /// Mems that failed their mem-level boot step (unresolvable or
    /// missing schema pin, backend instantiation or read failure) and
    /// are quarantined instead of failing the whole workspace —
    /// degrade, never disappear. A quarantined mem serves NOTHING:
    /// operations naming it refuse with the typed `MEM_QUARANTINED`
    /// code carrying the underlying reason (quarantine is not
    /// tolerance — no partial data from a broken mem). The retained
    /// [`Mount`] record lets `reload` re-attempt the attach after a
    /// repair, without a process restart. Surfaced on overview and
    /// health as the quarantine roster.
    quarantined: Vec<QuarantinedMem>,
    /// Workspace-level boot diagnosis carried by a diagnostic-shell
    /// engine ([`Engine::diagnostic_shell`]): the typed reason the
    /// REAL workspace could not boot at all (e.g. an unparseable
    /// workspace store). `None` on every ordinarily booted engine.
    /// Surfaced on overview and health so a session over a wholly
    /// unbootable workspace can always ask WHY the graph is gone.
    boot_diagnosis: Option<(String, String)>,
    /// Pipeline configs (Medium / Facet / Projection / Ingest) loaded
    /// from the workspace store at boot. Empty for engines built via
    /// `from_mounts*` (tests, in-memory consumers) and for any workspace
    /// that declares no pipelines; the workspace-root boot paths
    /// (`from_workspace_root` and the full counterpart) populate it via
    /// [`crate::pipeline_store::load_pipeline_configs`]. Read-only
    /// runtime surface — exposed through [`Self::pipeline_configs`]; the
    /// engine neither runs nor schedules pipelines (the ingest skill and
    /// future consumers do).
    pipeline_configs: crate::pipeline_store::BindingConfigs,
    /// Runtime snapshot of writable / visible mems. Derived from
    /// the mount list at construction: writable mounts
    /// (`MountCapability::Write`) register via `add_writable` with
    /// the storage's directory path (folder → `path`, git-branch →
    /// None, archive shouldn't be writable); read-only mounts
    /// register via `add_writable` (folder/git-branch) or
    /// `add_read_only` (archive). Used by MCP handlers that need the
    /// writable/visible roster + per-mem origin (`memstead_health
    /// include_config: true`, `memstead_overview`'s mem list,
    /// `memstead_mem_create`'s collision check).
    ///
    /// Wrapped in `Arc` so the COW-snapshot discipline — clone the
    /// snapshot, mutate the clone, swap the `Arc` — keeps writers
    /// and concurrent readers from contending on the live mount
    /// list.
    mem_router: Arc<MemRouterSnapshot>,
    /// Backend factory — function pointer used by
    /// [`crate::mem_management::create_mem`] (and future runtime
    /// mount-add paths) to materialise a [`MemBackend`] from a
    /// [`Mount`] declaration. Defaults to
    /// [`crate::workspace_store::instantiate_local_backend`] so
    /// folder + archive only consumers work out of the box. Git-branch
    /// consumers swap in `memstead_git_branch::storage::instantiate_full_backend`
    /// via [`Self::set_backend_factory`] after constructing the engine —
    /// `engine_from_workspace_root` does this once at boot. Function
    /// pointer (not `Box<dyn Fn>`) because the backend factory is
    /// stateless, `Send + Sync + Copy`, and one less allocation on the
    /// hot path matters for the multi-mem pattern this engine is
    /// designed around.
    backend_factory: BackendFactory,
    /// Storage discovery for UNMOUNTED mems: set by
    /// the git-branch boot, `None` in embedded engines (which keep the
    /// forward-reference mechanic unchanged for unmounted targets).
    pub(crate) unmounted_storage_prober: Option<UnmountedStorageProber>,
    /// Git-branch ops bundle — function pointers for the per-mount
    /// operations whose implementations live in `memstead-git-branch`
    /// (and therefore can't sit on the `MemBackend` trait without
    /// inverting the crate dependency). Full boot
    /// (`memstead_git_branch::engine_from_workspace_root`) installs the
    /// bundle via [`Self::set_git_branch_ops`]; consumers without it leave
    /// it `None` and `Engine::changes_since` / `Engine::export_mem`
    /// fall through to the folder/archive-only branches.
    git_branch_ops: Option<GitBranchOps>,
    /// Set while a proposal merge prepares the landing and the amend of an
    /// entity the owner amends: the merge is one write of that entity, so
    /// the transition forms judge its net effect against the pre-merge
    /// entity once, after both are prepared, and the per-step reading is
    /// deferred ([`Self::gate_transition_forms`]).
    pub(crate) defer_transition_gates: bool,
    /// Per-mem subscriber registry for [`MemChangedEvent`]s. Held
    /// behind `Arc<Mutex<_>>` so [`SubscriptionHandle`]s — which own
    /// the consumer's view of the subscription lifetime — can call
    /// back into the registry on `Drop` without a self-reference cycle
    /// to the engine. The emit path (in `record_self_write`) snapshots
    /// the per-mem callback list under the lock, releases the lock,
    /// and then invokes the callbacks — so a callback that re-enters
    /// the engine for a read does not deadlock against the registry.
    event_subscribers: Arc<std::sync::Mutex<events::SubscriberRegistry>>,
    /// Reload-before-operation notices recorded by
    /// [`Self::reload_if_stale`] when an operation triggered a mem
    /// reload. Built at reload time — when the backend's current head
    /// equals the head we reloaded to, *before* any mutation in the
    /// same operation commits — so the delta describes only the
    /// sibling's change, never the engine's own follow-on write.
    /// Reachable only through an [`drift::OperationScope`]: `begin`
    /// clears, `finish` hands the notices out as a value, and a
    /// dropped scope clears again, so no operation inherits another's
    /// notice and nothing on the engine hands them out on demand.
    pending_mem_changed: Vec<crate::ops::MemChangedNotice>,
    /// What each caller last saw of each mem, and who the operation in
    /// progress is for: the source of the notices above
    /// ([`callers`]).
    callers: callers::CallerCursors,
    /// Whether the operation in progress has brought its caller up to
    /// date (a reload ran), so that closing the operation may take the
    /// heads it leaves as seen.
    caller_synced: bool,
    /// Whether the operation in progress is its caller's first contact:
    /// such an operation hands out no notice, however many reloads it
    /// runs, and leaves the caller's memory at the heads storage holds.
    caller_first_contact: bool,
    /// Mems whose head appeared where none was during the reload in
    /// progress, with the entities that reload brought in: what the
    /// notice for such a mem lists as added. Filled and emptied inside
    /// one reload.
    appeared_heads: std::collections::HashMap<String, Vec<crate::entity::EntityId>>,
    /// Warnings for interrupted commits a load completed, waiting for
    /// the next operation's response. Kept apart from the load warnings
    /// of the reload that did the completing: that reload can still
    /// fail after it, and the completion happened all the same.
    completed_commits: Vec<crate::ops::WarningHint>,
    /// The mount roster as last reconciled (`roster.rs`): `None` until the
    /// first observation captures the baseline.
    roster_fingerprint: Option<roster::RosterFingerprint>,
    /// Subscribers to applied roster changes: `(next id, callbacks)`.
    roster_subscribers: Arc<roster::RosterSubscribers>,
    /// Mems that left the roster during this engine's lifetime and have
    /// not returned — the memory behind the `MEM_UNMOUNTED` refusal.
    recently_unmounted: std::collections::HashSet<String>,
    /// Test-only: make the unmount of the named mem fail before it
    /// touches any state, to prove the roster change stays unapplied.
    #[cfg(test)]
    pub(crate) inject_unmount_failure: Option<String>,
    /// Timestamp source for engine-stamped mutation metadata
    /// (`created_date` on create, `last_modified` on update/relate/
    /// rename — every field the schema marks `init_timestamp` /
    /// `auto_timestamp`). Defaults to the system clock; tests that
    /// assert over canonical entity bytes pin it via
    /// [`Self::set_mutation_clock`] so two engines stamp identical
    /// values. A testability affordance, not a behaviour switch:
    /// nothing in production swaps the default, and the stamped
    /// format (second-granularity RFC 3339, see
    /// `mutation::iso_from_system_time`) is unchanged.
    mutation_clock: MutationClock,
    /// The caller-declared role for mutations in this session.
    /// Set by the surface before each mutation
    /// (per-call parameter wins over the surface's session default);
    /// `Unspecified` records as absence. Session state on the engine
    /// — the `mutation_clock` precedent — so the role travels into
    /// every commit context and provenance record without widening
    /// every mutation signature.
    current_role: crate::vcs::Role,
    /// The caller-declared identity for mutations and checks in this
    /// session. Same session-state pattern as
    /// `current_role`: set by the surface before each operation
    /// (per-call parameter wins over the surface's session default);
    /// `None` records as absence. An opaque caller-chosen string —
    /// the engine neither generates, interprets, nor enriches it.
    current_identity: Option<String>,
    /// The transport's actor for commits the session causes without a
    /// per-call actor (config writes, sync-state stamps, the anchor
    /// writers): `Cli` under the CLI, `Agent` under the MCP server.
    current_actor: crate::vcs::Actor,
    /// The transport's client id, when it has one (the MCP client).
    current_client: Option<crate::vcs::ClientId>,
}

/// Clock the engine reads when stamping mutation timestamps. `Arc`'d
/// closure rather than a trait so a test can pin a constant with one
/// line: `engine.set_mutation_clock(Arc::new(|| some_time))`.
pub type MutationClock = Arc<dyn Fn() -> std::time::SystemTime + Send + Sync>;

/// Backend factory function pointer. Both crates' existing
/// `instantiate_*_backend` functions match this signature, so the
/// type alias is what bridges the dependency direction (memstead-base
/// can't depend on memstead-git-branch) without an extra trait.
/// Stateless, `Send + Sync + Copy`.
pub type BackendFactory =
    fn(&Mount) -> Result<Box<dyn MemBackend>, crate::workspace_store::InstantiateError>;

/// Per mem, what the merges recorded about the bodies adopted into it, as
/// the origin read consults them.
pub(crate) type ForeignMarks = HashMap<String, MemForeignMarks>;

/// One mem's foreign-content marks: per slug, one prepared hash per
/// load-bearing section of the body a merge adopted there, as no later
/// disposition retired it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct MemForeignMarks {
    /// Slug → (section key → prepared hash).
    pub(crate) by_slug:
        std::collections::BTreeMap<String, std::collections::BTreeMap<String, String>>,
    /// Why the mem's proposal record could not be read, when it could not.
    /// The marks are then unknown rather than absent, so every entity of the
    /// mem reads third-party: a trust label may not fail open on a file it
    /// could not read. The reason is kept so the label can say why
    /// ([`Engine::proposal_record_error`]); a conservative label with no
    /// stated cause is indistinguishable from the engine calling the
    /// operator's own mem a stranger's.
    pub(crate) record_unreadable: Option<String>,
}

impl MemForeignMarks {
    pub(crate) fn unreadable(reason: String) -> Self {
        Self {
            by_slug: std::collections::BTreeMap::new(),
            record_unreadable: Some(reason),
        }
    }
}

/// The validity key for derived-structure memos:
/// the store generation (bumped by every store mutation, carried by
/// `Store::clone` so batch rollback restores it) plus the schemas
/// epoch (bumped by every change to the engine's schema map). A memo
/// is current exactly while both halves still match.
///
/// The foreign-mark memo additionally reads a mem's proposal record,
/// which is in neither half; every act that changes a mark also mutates
/// the store, so the key still covers it, and a writer outside the
/// engine is the one case it would not.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DerivedKey {
    pub store_generation: u64,
    pub schemas_epoch: u64,
}

/// Discovered storage for a mem that has NO mount record — the
/// unmounted half of the write-time cross-mem target verification. The workspace layer owns the discovery convention
/// (the mem-repo's branch registry, which memstead-base cannot see
/// without inverting the crate dependency) and hands back a transient
/// backend to ask plus the mem's schema pin when its config declares
/// one, so the cross-schema edge routing can keep its authority
/// without a mount.
pub struct UnmountedMemStorage {
    /// Transient backend over the discovered storage. Used for the
    /// cheap [`MemBackend::entity_exists`] probe and the one-blob
    /// type read — never registered, never loaded.
    pub backend: Box<dyn MemBackend>,
    /// The mem's pinned schema, when its stored config declares one.
    pub schema: Option<memstead_schema::SchemaRef>,
}

/// Discovery hook: mem name → its storage, when the workspace layer
/// can find any (`None` = no discoverable storage; the
/// forward-reference mechanic governs, exactly as before). Boxed
/// closure rather than a function pointer because discovery needs the
/// workspace root and gitdir captured at boot.
pub type UnmountedStorageProber = Box<dyn Fn(&str) -> Option<UnmountedMemStorage> + Send + Sync>;

/// `Engine::changes_since` dispatch for git-branch mounts.
///
/// Signature matches `memstead_git_branch::ops::changes::changes_since` after
/// adapting the `Store` parameter away (the engine performs enrichment
/// downstream) and the `head_ref` parameter (`refs/heads/<branch>` is
/// constructed inside the impl from `branch`).
pub type GitBranchChangesSinceFn = fn(
    gitdir: &Path,
    branch: &str,
    mem: &str,
    since: &str,
    rename_similarity: f32,
) -> Result<crate::ops::BackendChanges, BackendError>;

/// `Engine::export_mem` dispatch for git-branch mounts.
///
/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch`.
pub type GitBranchExportFn = fn(
    gitdir: &Path,
    branch: &str,
    mem: &str,
    config: &memstead_schema::MemConfig,
    output_path: &Path,
    workspace_root: Option<&Path>,
    workspace_schemas_dir: Option<&Path>,
    // Engine-sourced authoring-provenance payload bytes (from the mount's
    // `read_provenance` log) to embed at `.memstead/provenance.json`.
    // `None` when the mem carried no noted mutations.
    provenance_bytes: Option<&[u8]>,
    // Engine-sourced anchors sidecar bytes (from the mount's
    // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
    // when the mem carried no anchors. The engine reads the branch tip; the
    // hook only embeds, keeping git tree-walking out of the fn-pointer.
    anchors_bytes: Option<&[u8]>,
    // Engine-sourced sealed check records (from the workspace ledger) to
    // embed at `.memstead/checks.json`. `None` when no record qualifies.
    checks_bytes: Option<&[u8]>,
) -> Result<crate::ops::MemExportResult, BackendError>;

/// `Engine::export_mem_to_bytes` dispatch for git-branch mounts.
///
/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch_to_bytes`.
/// Symmetric to `GitBranchExportFn`: same inputs minus the output path,
/// returns archive bytes plus metadata instead of writing to disk.
pub type GitBranchExportToBytesFn = fn(
    gitdir: &Path,
    branch: &str,
    mem: &str,
    config: &memstead_schema::MemConfig,
    workspace_root: Option<&Path>,
    workspace_schemas_dir: Option<&Path>,
    // Pre-built authoring-provenance payload bytes the engine sourced from
    // the mount's `read_provenance` log, to embed at
    // `.memstead/provenance.json`. `None` when the mem carried no noted
    // mutations. The engine sources it (it holds the backend); the hook
    // only embeds, keeping git history-walking out of the fn-pointer.
    provenance_bytes: Option<&[u8]>,
    // Engine-sourced anchors sidecar bytes (from the mount's
    // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
    // when the mem carried no anchors. Symmetric with `provenance_bytes`:
    // the engine reads the branch tip, the hook only embeds.
    anchors_bytes: Option<&[u8]>,
    // Engine-sourced sealed check records (from the workspace ledger) to
    // embed at `.memstead/checks.json`. `None` when no record qualifies.
    checks_bytes: Option<&[u8]>,
) -> Result<crate::ops::MemExportBytes, BackendError>;

/// `Engine::diff` dispatch for git-branch mounts. Walks the two refs
/// inside the workspace's mem-repo gitdir, produces a per-entity
/// [`crate::ops::Diff`]. A ref names the empty tree, or is anchored in
/// the history of `branch` or of one of `readable`, the declared
/// branches of the other mems the workspace mounts in the same git
/// directory: at one of those branches by name, at `HEAD`, or at a
/// commit hash of those histories, with `~n` and `^n` parent steps;
/// any other ref refuses `UNKNOWN_REF`, as a ref that names nothing
/// does. `branch` is the mount's declared branch; a
/// bare `HEAD` token in either ref re-anchors onto it.
pub type GitBranchDiffFn = fn(
    gitdir: &Path,
    branch: &str,
    readable: &[String],
    mem: &str,
    ref_a: &str,
    ref_b: &str,
    config: &crate::ops::DiffConfig,
) -> Result<crate::ops::Diff, BackendError>;

/// `Engine::fetch` dispatch for git-branch mounts.
pub type GitBranchFetchFn = fn(
    gitdir: &Path,
    remote: &str,
    refspecs: &[String],
) -> Result<crate::ops::FetchOutcome, BackendError>;

/// Read every `.md` blob at `ref_name` in `gitdir`, returning
/// `(relative_path, utf8_content)` pairs. Skips `.memstead/` engine-internal
/// entries and non-blob nodes. Used by the pre-merge schema-validation
/// pass `Engine::pull` and `Engine::push` run before they advance the
/// branch pointer / push to the remote.
pub type GitBranchReadTreeFn =
    fn(gitdir: &Path, ref_name: &str) -> Result<Vec<(String, String)>, BackendError>;

/// `Engine::pull` dispatch for git-branch mounts. `branch` is the
/// mount's declared branch — the single source of truth for both the
/// local ref and the remote-tracking ref; `mem` labels the outcome
/// only.
pub type GitBranchPullFn = fn(
    gitdir: &Path,
    remote: &str,
    branch: &str,
    mem: &str,
) -> Result<crate::ops::PullOutcome, BackendError>;

/// `Engine::push` dispatch for git-branch mounts. `branch` is the
/// mount's declared branch (see [`GitBranchPullFn`]); `mem` labels
/// the outcome only.
pub type GitBranchPushFn = fn(
    gitdir: &Path,
    remote: &str,
    branch: &str,
    mem: &str,
    force: bool,
) -> Result<crate::ops::PushOutcome, BackendError>;

/// `Engine::push_all` dispatch, first half: the remote's ref table
/// in one round-trip (`git ls-remote --heads`), as `(full ref name,
/// sha)` pairs. Lets the engine tell a lagging ref from one already
/// in sync before it sends anything.
pub type GitBranchLsRemoteFn =
    fn(gitdir: &Path, remote: &str) -> Result<Vec<(String, String)>, BackendError>;

/// `Engine::push_all` dispatch, second half: resolve one local ref
/// to its SHA. `Ok(None)` when the ref does not exist (a fresh
/// mem-repo legitimately has no `__MEMSTEAD` yet).
pub type GitBranchResolveRefFn =
    fn(gitdir: &Path, ref_name: &str) -> Result<Option<String>, BackendError>;

/// `Engine::remote_status` dispatch: whether `ancestor` is reachable
/// from `descendant` in the gitdir's history (`git merge-base
/// --is-ancestor`). Read-only; tells local-ahead from behind from forked
/// without moving a ref.
pub type GitBranchIsAncestorFn =
    fn(gitdir: &Path, ancestor: &str, descendant: &str) -> Result<bool, BackendError>;

/// `Engine::pull_all` dispatch: whether the commit `sha` is a root
/// commit (no parent) over the empty tree, the shape of a freshly
/// bootstrapped schema-and-config ref that carries no state yet.
/// Read-only.
pub type GitBranchIsEmptyRootFn = fn(gitdir: &Path, sha: &str) -> Result<bool, BackendError>;

/// The nearest common ancestor of two commits (`git merge-base`);
/// `None` when they share no history. Read-only. The adopt form of
/// `mem fork` reads the ancestor of a fork branch that arrived on a
/// remote off it.
pub type GitBranchMergeBaseFn =
    fn(gitdir: &Path, a: &str, b: &str) -> Result<Option<String>, BackendError>;

/// Merge two commits' trees path by path from their merge base, when no
/// path changed on both sides: the paths only `theirs` changed are
/// applied onto `ours`'s tree, and a commit with both parents (`ours`
/// first) is written with `message`. No ref moves; the caller moves it.
/// A path changed on both sides is a content decision the merge does
/// not make: the answer names every such path and writes nothing.
pub type GitBranchMergeDisjointFn = fn(
    gitdir: &Path,
    ours: &str,
    theirs: &str,
    message: &str,
) -> Result<DisjointMerge, BackendError>;

/// What a [`GitBranchMergeDisjointFn`] came to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DisjointMerge {
    /// The merge commit, not yet on any ref.
    Merged { commit: String },
    /// Paths both sides changed since their merge base; nothing written.
    Overlap { paths: Vec<String> },
    /// The two commits share no history, so there is no base to merge
    /// from; nothing written.
    Unrelated,
}

/// Point `ref_name` at `sha`, under the precondition `previous` names.
/// A move that decided on an observed tip pins it with
/// [`RefPrevious::At`] (or [`RefPrevious::Absent`] for a ref it saw
/// missing), so a commit that lands between the decision and the move
/// makes the move fail instead of being dropped. [`RefPrevious::Any`] is
/// for a ref the engine derives and owns outright (the check-ledger
/// transport ref, re-derived from the workspace ledger before every
/// publish).
pub type GitBranchUpdateRefFn = fn(
    gitdir: &Path,
    ref_name: &str,
    sha: &str,
    previous: RefPrevious<'_>,
) -> Result<(), BackendError>;

/// The precondition of a [`GitBranchUpdateRefFn`] move.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefPrevious<'a> {
    /// Move whatever the ref points at, or create it.
    Any,
    /// The ref must not exist.
    Absent,
    /// The ref must point at this commit.
    At(&'a str),
}

/// `Engine::remote_add` dispatch — configures a named remote on the
/// mem-repo gitdir (upsert: add, or set-url when it already exists).
pub type GitBranchRemoteAddFn =
    fn(gitdir: &Path, name: &str, url: &str) -> Result<crate::ops::RemoteAddOutcome, BackendError>;

/// `Engine::branch_reset` dispatch for git-branch mounts. Returns the
/// outcome on success; surfaces `BackendError::Other` carrying an
/// in-band marker (`UNKNOWN_REF:<raw>` or
/// `PUSHED_COMMITS_PROTECTED:<sha,sha,...>`) the engine layer
/// un-marshals into typed `EngineError`s.
pub type GitBranchBranchResetFn = fn(
    gitdir: &Path,
    branch: &str,
    target_sha: &str,
    expected_head: Option<&str>,
) -> Result<crate::ops::BranchResetOutcome, BackendError>;

/// Residue-prune dispatch for git-branch mounts.
/// The `create_mem` orchestrator calls this when
/// `RecoveryAction::ForceOverwrite` is selected against pre-existing
/// storage residue. Drops `refs/heads/<branch_full_path>` and the
/// `__MEMSTEAD:mems/<branch_full_path>/config.json` blob in one
/// ref-edit transaction (the same call the
/// `MemBackend::delete_artifacts` impl wraps for delete-files
/// flows). Surfaces as a function pointer so `crate::mem_management`
/// can drive a prune against an unmounted gitdir without depending on
/// `memstead-git-branch`.
pub type GitBranchPruneResidueFn = fn(
    gitdir: &Path,
    branch_full_path: &str,
    ctx: &crate::vcs::CommitContext<'_>,
) -> Result<(), BackendError>;

/// Config-only prune: drop the mem's blobs on `__MEMSTEAD` and leave
/// every content branch alone. `create_mem` rolls a failed seed commit
/// back through it so no config outlives the mem it was written for;
/// `delete_mem` removes a config left behind that way. Idempotent.
pub type GitBranchPruneConfigBlobFn = fn(
    gitdir: &Path,
    branch_full_path: &str,
    ctx: &crate::vcs::CommitContext<'_>,
) -> Result<(), BackendError>;

/// Ref-namespace probe: the local branches a new
/// `refs/heads/<branch_full_path>` could not coexist with, because
/// one is a path prefix of the other (git keeps refs as files in
/// directories). `create_mem` asks before it writes anything.
pub type GitBranchNamespaceConflictsFn =
    fn(gitdir: &Path, branch_full_path: &str) -> Result<Vec<String>, BackendError>;

/// `fork_mem` dispatch: create `refs/heads/<branch_full_path>` at
/// `sha`, a full commit id already in the object store, in one
/// ref-edit that refuses when the ref exists. The branch is the
/// fork's lineage claim: its first commit is the source's, never a
/// fresh seed.
pub type GitBranchCreateBranchAtFn =
    fn(gitdir: &Path, branch_full_path: &str, sha: &str) -> Result<(), BackendError>;

/// `fork_mem` dispatch for the remote form: one mem's config blob
/// (`mems/<mem>/config.json`) from the `__MEMSTEAD` tree at
/// `ref_name`, the remote-tracking ref a fetch just placed
/// (`refs/remotes/<remote>/__MEMSTEAD`), never the local
/// `refs/heads/__MEMSTEAD`. `Ok(None)` when the ref or the blob is
/// absent. Read-only.
pub type GitBranchReadConfigAtRefFn =
    fn(gitdir: &Path, ref_name: &str, mem: &str) -> Result<Option<Vec<u8>>, BackendError>;

/// `rename_mem` dispatch for the git-branch backend: move the mem's
/// content branch `refs/heads/<old>` to `refs/heads/<new>` at the same
/// tip (history preserved) and relocate the `__MEMSTEAD:mems/<old>/`
/// config blob to `mems/<new>/`, all in one ref-edit transaction.
/// Refuses (no mutation) when the source branch is missing or the
/// target branch already exists.
pub type GitBranchRenameMemStorageFn = fn(
    gitdir: &Path,
    old_leaf: &str,
    new_leaf: &str,
    ctx: &crate::vcs::CommitContext<'_>,
) -> Result<(), BackendError>;

/// `Engine::install_schema` dispatch for the git-branch backend: write a
/// schema package (`(relative-path, bytes)` pairs) onto the workspace's
/// unified `__MEMSTEAD:schemas/<name>@<version>/` ref and return the
/// resulting commit sha. Mirrors
/// `memstead_git_branch::storage_memstead::write_schema_to_memstead_ref`.
pub type GitBranchWriteSchemaFn = fn(
    gitdir: &Path,
    name: &str,
    version: &str,
    files: &[(String, Vec<u8>)],
) -> Result<String, BackendError>;

/// Read one file from a sealed schema package on the workspace's
/// `__MEMSTEAD:schemas/<name>@<version>/` ref. `Ok(None)` when the
/// ref, package, or file is absent — absence is a normal state (the
/// install-provenance stamp only exists for path-sourced installs).
/// Read-only; the authoring-drift health axis is the consumer.
pub type GitBranchReadSchemaFileFn = fn(
    gitdir: &Path,
    name: &str,
    version: &str,
    rel: &str,
) -> Result<Option<Vec<u8>>, BackendError>;

/// Re-read every schema sealed on one git directory's
/// `__MEMSTEAD:schemas/` ref (empty when the directory, the ref or the
/// subtree is absent). Read-only; `Engine::full_refresh` is the
/// consumer, the warm-server path that makes an out-of-band `memstead
/// schema install` resolvable without a process restart. It calls this
/// once per directory of [`crate::workspace::schema_registry_gitdirs`].
pub type GitBranchReadRefSchemasFn =
    fn(gitdir: &Path) -> Result<Vec<Arc<memstead_schema::Schema>>, BackendError>;

/// Collect one pinned schema's raw source files (manifest, sealed
/// format marker, type definitions) from one git directory's
/// `__MEMSTEAD:schemas/<name>@<version>/` ref — the tree `memstead
/// schema install` writes on the git-branch backend. `Ok(None)` when
/// the directory, the ref, or the package is absent. Read-only;
/// the consumer is the FOLDER-mount export path: a folder mem living
/// in a mem-repo workspace pins a schema the installer sealed on the
/// ref, so the archive assembler must read the same store the loader
/// resolves from, or the mem loads but cannot export. The caller walks
/// [`crate::workspace::schema_registry_gitdirs`] and takes the first
/// directory that carries the package.
pub type GitBranchCollectSchemaSourceFn =
    fn(
        gitdir: &Path,
        schema_ref: &memstead_schema::SchemaRef,
    ) -> Result<Option<Vec<memstead_schema::SchemaSourceFile>>, BackendError>;

/// Bundle of git-branch-specific op dispatchers. Installed on the
/// engine at full boot. Each field is one ops-method that previously
/// lived on the `MemBackend` trait; moving them off the trait keeps
/// the bytes-level primitive surface clean.
#[derive(Clone, Copy)]
pub struct GitBranchOps {
    pub changes_since: GitBranchChangesSinceFn,
    pub diff: GitBranchDiffFn,
    pub branch_reset: GitBranchBranchResetFn,
    pub fetch: GitBranchFetchFn,
    pub pull: GitBranchPullFn,
    pub push: GitBranchPushFn,
    pub ls_remote: GitBranchLsRemoteFn,
    pub resolve_ref: GitBranchResolveRefFn,
    pub is_ancestor: GitBranchIsAncestorFn,
    pub is_empty_root: GitBranchIsEmptyRootFn,
    pub merge_base: GitBranchMergeBaseFn,
    pub merge_disjoint: GitBranchMergeDisjointFn,
    pub update_ref: GitBranchUpdateRefFn,
    pub remote_add: GitBranchRemoteAddFn,
    pub read_tree: GitBranchReadTreeFn,
    pub export: GitBranchExportFn,
    pub export_to_bytes: GitBranchExportToBytesFn,
    pub prune_residue: GitBranchPruneResidueFn,
    pub prune_config_blob: GitBranchPruneConfigBlobFn,
    pub branch_namespace_conflicts: GitBranchNamespaceConflictsFn,
    pub create_branch_at: GitBranchCreateBranchAtFn,
    pub read_config_at_ref: GitBranchReadConfigAtRefFn,
    pub rename_mem_storage: GitBranchRenameMemStorageFn,
    pub write_schema: GitBranchWriteSchemaFn,
    pub read_schema_file: GitBranchReadSchemaFileFn,
    pub read_ref_schemas: GitBranchReadRefSchemasFn,
    pub collect_ref_schema_source: GitBranchCollectSchemaSourceFn,
}

impl std::fmt::Debug for Engine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Engine")
            .field(
                "mems",
                &self
                    .mounts
                    .iter()
                    .map(|m| m.mount.mem.as_str())
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

#[cfg(test)]
mod in_memory_mem;

#[cfg(test)]
pub(super) mod test_helpers {
    use std::io::Write as _;
    use std::path::{Path, PathBuf};

    use memstead_schema::SchemaRef;

    use crate::backend::MemBackend;
    use crate::storage::FilesystemBackend;
    use crate::vcs::{Actor, ClientId};
    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};

    use super::{CreateEntityArgs, CreateEntityOutcome, Engine, RelateEntityArgs};

    use indexmap::IndexMap;
    use tempfile::TempDir;

    pub(crate) fn pin(name: &str) -> SchemaRef {
        let version = match name {
            "default" => semver::Version::new(1, 0, 0),
            _ => semver::Version::new(0, 1, 0),
        };
        SchemaRef::new(name, version)
    }

    pub(crate) fn folder_mount(mem: &str, path: PathBuf) -> Mount {
        Mount {
            mem: mem.to_string(),
            schema: Some(pin("default")),
            storage: MountStorage::Folder { path },
            capability: MountCapability::Write,
            lifecycle: MountLifecycle::Eager,
            cross_linkable: true,
            migration_target: None,
        }
    }

    pub(crate) fn in_memory_mount(mem: &str) -> Mount {
        Mount {
            mem: mem.to_string(),
            schema: Some(pin("default")),
            storage: MountStorage::InMemory,
            capability: MountCapability::Write,
            lifecycle: MountLifecycle::Eager,
            cross_linkable: true,
            migration_target: None,
        }
    }

    pub(crate) fn archive_mount(mem: &str, path: PathBuf) -> Mount {
        Mount {
            mem: mem.to_string(),
            schema: Some(pin("default")),
            storage: MountStorage::Archive { path },
            capability: MountCapability::ReadOnly,
            // Eager, matching every production archive-mount site: these
            // tests pin archive READ semantics over a loaded store. A
            // `Lazy` value here would defer the load these tests read
            // through.
            // The lazy behaviour has its own tests in `boot.rs`.
            lifecycle: MountLifecycle::Eager,
            cross_linkable: false,
            migration_target: None,
        }
    }

    /// Build a sealed archive at `tmp/<name>.mem` from
    /// `(relative_path, bytes)` pairs and return the path.
    pub(crate) fn build_archive(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
        let path = tmp.join(format!("{name}.mem"));
        let file = std::fs::File::create(&path).unwrap();
        let mut writer = zip::ZipWriter::new(file);
        let opts = zip::write::SimpleFileOptions::default();
        for (rel, bytes) in entries {
            writer.start_file(*rel, opts).unwrap();
            writer.write_all(bytes).unwrap();
        }
        writer.finish().unwrap();
        path
    }

    /// Write a schema manifest + minimal type bodies under
    /// `<root>/<name>/`. Each type gets a body with a single
    /// `body` section and `_default` hierarchy/no-self-loop lists — enough
    /// to load and parse markdown that uses that type. Used by tests
    /// that need a custom schema with shape or vocabulary constraints.
    pub(crate) fn write_schema_files_with_default_type(
        root: &Path,
        name: &str,
        manifest: &str,
        types: &[&str],
    ) {
        const TYPE_BODY: &str = r#"description: t
when_to_use: Here
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields: []
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: _default
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
health_required_fields:
  - body
staleness_threshold_days: 90
write_rules: []
"#;
        let dir = root.join(name);
        std::fs::create_dir_all(dir.join("types")).unwrap();
        std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
        for type_name in types {
            let body = format!("name: {type_name}\n{TYPE_BODY}");
            std::fs::write(dir.join("types").join(format!("{type_name}.yaml")), body).unwrap();
        }
    }

    pub(crate) fn empty_create_args(mem: &str, title: &str) -> CreateEntityArgs {
        // The
        // create path refuses on missing required sections. The
        // default `spec` type requires `identity` + `purpose`. Seed
        // both with a single space so the test fixture remains a
        // valid creation request — every test that uses this helper
        // as a fixture builder continues to work, and tests that
        // specifically exercise the refusal supply an explicit
        // empty-sections payload (see the dedicated refusal tests).
        let mut sections = IndexMap::new();
        sections.insert("identity".to_string(), "fixture identity body".to_string());
        sections.insert("purpose".to_string(), "fixture purpose body".to_string());
        CreateEntityArgs {
            anchors: Vec::new(),
            mem: mem.to_string(),
            title: title.to_string(),
            entity_type: "spec".to_string(),
            sections,
            metadata: IndexMap::new(),
            relations: Vec::new(),
            dry_run: false,
        }
    }

    pub(crate) fn cli_actor() -> (Actor, ClientId) {
        (
            Actor::Cli,
            ClientId {
                name: "claude-code".to_string(),
                version: "2.1.0".to_string(),
            },
        )
    }

    pub(crate) fn engine_with_seed(tmp: &TempDir, title: &str) -> (Engine, CreateEntityOutcome) {
        let mem_dir = tmp.path().to_path_buf();
        let writer = FilesystemBackend::new(mem_dir.clone());
        let mut engine = Engine::from_mounts(vec![(
            folder_mount("specs", mem_dir),
            Box::new(writer) as Box<dyn MemBackend>,
        )])
        .unwrap();
        let (actor, client) = cli_actor();
        let outcome = engine
            .create_entity(
                empty_create_args("specs", title),
                actor,
                Some(&client),
                None,
            )
            .unwrap();
        (engine, outcome)
    }
    pub(crate) fn build_demo_engine(tmp: &TempDir) -> Engine {
        let mem_dir = tmp.path().to_path_buf();
        let writer = FilesystemBackend::new(mem_dir.clone());
        let mut engine = Engine::from_mounts(vec![(
            folder_mount("specs", mem_dir),
            Box::new(writer) as Box<dyn MemBackend>,
        )])
        .unwrap();
        let (actor, client) = cli_actor();
        let source = engine
            .create_entity(
                empty_create_args("specs", "Source One"),
                actor,
                Some(&client),
                None,
            )
            .unwrap();
        let target = engine
            .create_entity(
                empty_create_args("specs", "Target Two"),
                actor,
                Some(&client),
                None,
            )
            .unwrap();
        engine
            .create_entity(
                empty_create_args("specs", "Lonely Three"),
                actor,
                Some(&client),
                None,
            )
            .unwrap();
        engine
            .relate_entity(
                RelateEntityArgs {
                    source: source.id.clone(),
                    expected_hash: Some(source.content_hash.clone()),
                    rel_type: "USES".to_string(),
                    target: target.id.clone(),
                    remove: false,
                    description: None,
                    dry_run: false,
                },
                actor,
                Some(&client),
                None,
            )
            .unwrap();
        engine
    }
}