memstead_base/engine/mod.rs
1//! Unified engine.
2//!
3//! **One [`Engine`] type, three storage backends**: the engine sits
4//! above [`MemBackend`] and routes reads / writes to the backend
5//! named by each mount's mem. Consumers reach the engine through
6//! [`Engine::from_workspace_root`] (folder + archive backends) or
7//! `memstead_git_branch::engine_from_workspace_root` (adds git-branch).
8//!
9//! ## Routing
10//!
11//! Each mount holds one mem. Lookup is by mem name: the first
12//! mount whose `mem` field equals the requested name wins. One mount
13//! per mem is enforced — duplicates are a configuration bug, not a
14//! feature, and the constructor rejects them.
15
16use std::cell::OnceCell;
17use std::collections::HashMap;
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20
21use memstead_schema::Schema;
22
23use crate::backend::{BackendError, MemBackend};
24use crate::graph::LouvainOutput;
25use crate::mem::MemRouterSnapshot;
26use crate::ops::WarningHint;
27#[cfg(not(target_arch = "wasm32"))]
28use crate::search_index::MemIndex;
29use crate::store::Store;
30use crate::workspace::{Mount, WorkspaceSettings};
31
32pub mod apply_commit;
33pub mod archive;
34pub mod boot;
35pub mod callers;
36pub mod check_ops;
37pub mod checks_transport;
38pub mod conflicts;
39pub mod drift;
40pub mod due;
41pub mod error;
42pub mod events;
43pub mod export_html;
44pub mod export_llms_txt;
45pub mod gates;
46pub mod history;
47pub mod independence;
48pub mod lifecycle;
49pub mod mutation;
50pub mod outcomes;
51pub mod proposal;
52pub mod query;
53pub mod review;
54pub mod roster;
55pub mod write_lock;
56
57pub use archive::FromArchiveBytesError;
58pub use error::{
59 BootError, EngineError, INLINE_LIST_CAP, MissingWikiLink, ReferrerInfo, SchemaSourceDiagnostic,
60 StaleCause, format_inline_list_overflow,
61};
62#[cfg(feature = "tokio")]
63pub use events::DEFAULT_BROADCAST_CAPACITY;
64pub use events::{EventCallback, MemChangedEvent, SubscriptionHandle};
65pub use history::{
66 EntityHistoryReport, EntityTouch, HISTORY_PAGE_DEFAULT, HISTORY_PAGE_MAX, StoryStart,
67};
68pub use mutation::delete::DeleteReferrers;
69pub use mutation::{PATCH_OLD_NOT_FOUND_CONTENT_CAP, RELATIONSHIP_CYCLE_PATH_CAP};
70pub use outcomes::{
71 CreateEntityArgs, CreateEntityOutcome, DeleteEntityArgs, DeleteEntityOutcome, ExpectedHash,
72 HashOverride, RelateAction, RelateEntityArgs, RelateEntityOutcome, RenameEntityArgs,
73 RenameEntityOutcome, RetypeEdge, RetypeEdgeDirection, RetypeEntityArgs, RetypeEntityOutcome,
74 RetypeProblem, SetSchemaOutcome, SetSchemaResult, UpdateEntityArgs, UpdateEntityOutcome,
75};
76pub use review::{ReviewMarkStatus, SetReviewMarkOutcome};
77
78pub use boot::{SchemaResolver, load_workspace_schemas, resolve_builtin_schema_pin_pub};
79pub use lifecycle::SchemaStaging;
80
81/// One mem attachment, paired with the backend that serves it.
82/// Constructed by [`Engine::from_mounts`] and held internally.
83/// `pub(crate)` only so the crate-internal `boot::build_mem_router_from_mounts`
84/// can name it in its signature — never re-exported.
85pub(crate) struct MountedBackend {
86 mount: Mount,
87 /// Shared so the write-lock guard can hold the backends it locked
88 /// and discard their staged writes when it drops
89 /// ([`write_lock::MemWriteGuard`]).
90 backend: std::sync::Arc<dyn MemBackend>,
91 /// Last cursor returned by `backend.current_head()`. Seeded in
92 /// [`Engine::from_mounts`]; refreshed by
93 /// [`Engine::reload_if_stale`] after a successful reload.
94 /// `None` means the backend doesn't track a head (folder /
95 /// archive) — drift detection is a no-op for this mount.
96 last_known_head: Option<String>,
97 /// Per-mem `.memstead/config.json` payload — surfaces via
98 /// [`Engine::mem_config_for`] for handlers that need
99 /// `write_guidance` / `extra` (`memstead_health
100 /// { include_config: true }`'s per-mem detail block).
101 ///
102 /// Read at construction through the backend's `read_mem_config`,
103 /// whatever the storage kind (folder: `<path>/.memstead/config.json`;
104 /// archive: the zip member; git-branch: the metadata branch's
105 /// `mems/<leaf>/config.json`). `None` when the backend has no config
106 /// or the payload does not parse.
107 mem_config: Option<memstead_schema::config::MemConfig>,
108 /// Per-mem authoring-provenance payload read from the archive's
109 /// `.memstead/provenance.json` at construction (via
110 /// [`crate::backend::MemBackend::read_archive_provenance`]). `None`
111 /// when the backend carries no provenance member (a pre-provenance
112 /// archive, or a backend that does not surface one) — surfaced as
113 /// provenance-absent via [`Engine::archive_provenance_for`]. A
114 /// malformed payload is downgraded to `None` rather than failing the
115 /// mount: the member is additive.
116 archive_provenance: Option<memstead_schema::ArchiveProvenance>,
117 /// The sealed check records an archive mount carries
118 /// (`.memstead/checks.json`), read at construction via
119 /// [`crate::backend::MemBackend::read_archive_checks`]. `None` on
120 /// every writable mount (their check state is the workspace
121 /// ledger's) and on an archive sealed without records; every
122 /// check-state read on an archive mount derives from this and never
123 /// from a workspace ledger ([`Engine::archive_checks_for`]).
124 archive_checks: Option<crate::check::SealedChecks>,
125 /// `true` while a [`MountLifecycle::Lazy`] mount's entities have not
126 /// been loaded into the store — the mount's metadata half (config,
127 /// schema pin, provenance) is resolved at boot, the entity load is
128 /// deferred to the first operation that needs the mem
129 /// ([`Engine::ensure_mems_loaded`]). Always `false` for eager
130 /// mounts, and permanently `false` once the deferred load lands.
131 /// A deferred mem is never absent: it stays on the mount roster
132 /// with its schema resolved, and every read surface either triggers
133 /// the load or reports the state — silence is the one forbidden
134 /// rendering.
135 ///
136 /// [`MountLifecycle::Lazy`]: crate::workspace::MountLifecycle::Lazy
137 deferred: bool,
138 /// Why the last drift reload of this mem failed, cleared by the next
139 /// reload that succeeds. While it is set the engine's view of the
140 /// mem is known to be behind storage: reads still serve it (a stale
141 /// whole state beats no answer), a write does not land on it
142 /// ([`Engine::commit_staged`] refuses), because a write computed
143 /// from a stale view overwrites what the view has not seen.
144 reload_failure: Option<ViewFailure>,
145 /// A discard on this mem's backend failed, so writes of a mutation
146 /// that did not commit may still be staged there. Set by the write
147 /// lock when it is released (it shares the flag, since it cannot
148 /// reach the engine then) and cleared by the discard the engine
149 /// runs before its next operation.
150 strays: std::sync::Arc<std::sync::atomic::AtomicBool>,
151}
152
153/// Why a mem's view cannot take a write, with what failed: the record a
154/// mount keeps until the next reload or discard that succeeds, and the
155/// cause and detail of the `MEM_VIEW_STALE` a write is refused with.
156#[derive(Debug, Clone)]
157pub(crate) struct ViewFailure {
158 pub(crate) cause: StaleCause,
159 pub(crate) detail: String,
160}
161
162impl ViewFailure {
163 /// The view is behind storage: a reload, a probe or a read failed.
164 pub(crate) fn drift(detail: impl Into<String>) -> Self {
165 Self {
166 cause: StaleCause::Drift,
167 detail: detail.into(),
168 }
169 }
170
171 /// The refusal of a write on this view, naming `mem`.
172 pub(crate) fn refusal(&self, mem: &str) -> EngineError {
173 EngineError::StaleView {
174 mem: mem.to_string(),
175 cause: self.cause,
176 detail: self.detail.clone(),
177 }
178 }
179}
180
181/// One quarantined mem: the mem-level boot failure that took it out of
182/// service, and the retained mount record `reload` uses to re-attempt
183/// the attach after a repair. The reason code/message are
184/// typed material — the message's final clause names the repair
185/// command, so the roster entry is actionable as-is.
186#[derive(Debug, Clone)]
187pub struct QuarantinedMem {
188 /// The mount that failed to attach, retained verbatim for reload.
189 pub mount: crate::workspace::Mount,
190 /// Typed code of the underlying failure (e.g. `SCHEMA_NOT_FOUND`,
191 /// `MEM_CONFIG_INCOMPLETE`, `MEM_ERROR`).
192 pub reason_code: String,
193 /// Full message of the underlying failure, repair command
194 /// included.
195 pub reason_message: String,
196}
197
198/// Unified engine. Holds a list of mounted backends and routes
199/// mem-named operations to the right one.
200///
201/// `Send` so the engine can sit behind a `Mutex` (today's pattern
202/// in the MCP server). The trait object's `Send + Sync` bound on
203/// `MemBackend` keeps the inner backends thread-safe; the engine
204/// itself is single-threaded by design (the lazy memos are
205/// `OnceCell`, which is `!Sync`).
206///
207/// `Debug` is hand-written to avoid requiring `Debug` on the
208/// `dyn MemBackend` trait object — backend impls are free to
209/// stay non-`Debug`.
210///
211/// ## Load-on-init
212///
213/// `Engine::from_mounts` walks each backend at construction time
214/// (`list_entities` + `read_entity` + parse) and populates a single
215/// shared [`Store`] with entities and edges from every mount. Each
216/// mount's schema resolves from its own pin (the backend config's
217/// schema, or the mount-record assertion as fallback) through the
218/// `SchemaResolver`, so `schemas` holds genuinely heterogeneous
219/// schemas in a multi-schema workspace. Per-file errors don't fail
220/// construction; they collect into [`Engine::load_errors`] for the
221/// operator to inspect.
222pub struct Engine {
223 mounts: Vec<MountedBackend>,
224 store: Store,
225 schemas: HashMap<String, Arc<Schema>>,
226 /// Workspace-authored schemas loaded from
227 /// `WorkspaceSettings.schemas_dir` at construction. Distinct from
228 /// `schemas` (per-mem, only schemas pinned by a mount): this
229 /// catalogue carries every workspace-loaded schema regardless of
230 /// whether a mem pins it. Surfaced via
231 /// [`Self::workspace_schemas`] for handlers that need to enumerate
232 /// schemas referenced by `mem_create_rules.schemas[]` but not
233 /// pinned by any mem — `memstead_overview` lists them in `## Schemas`
234 /// so an agent sees what could be pinned. Empty when no
235 /// `schemas_dir` was passed.
236 workspace_schemas: Vec<Arc<Schema>>,
237 /// Embedded built-in schemas loaded once at boot from
238 /// `memstead_schema::builtins::load_builtin_schemas()`. The boot path
239 /// uses this catalogue to resolve each mount's schema pin; storing
240 /// it on the engine lets read handlers (MCP's `memstead_schema`,
241 /// `memstead_overview`'s `## Schemas` rendering) surface every built-in
242 /// without re-walking the embedded directory. Schemas declared in
243 /// `workspace_schemas` shadow built-ins on `(name, version)`
244 /// collision — handlers walking both lists must check workspace
245 /// first.
246 builtin_schemas: Vec<Arc<Schema>>,
247 load_errors: Vec<(PathBuf, String)>,
248 /// Lazily-computed Louvain community detection across the
249 /// engine-wide store. Populated on first call to
250 /// [`Self::communities`]; invalidated by
251 /// [`Self::invalidate_communities`] which every mutation method
252 /// calls after a successful write. `OnceCell` is `!Sync`; the
253 /// engine is `Send` (it is moved into a `Mutex` by every consumer)
254 /// but not `Sync`.
255 /// Generation-keyed: the memo carries the store
256 /// generation it was computed at; the invalidation hook clears it
257 /// only when the store has actually moved past that generation —
258 /// which is what makes a rolled-back batch (store snapshot
259 /// restored, generation restored with it) keep serving the memo
260 /// its state was computed from, and makes it impossible for the
261 /// rolled-back interim state to be served as fresh.
262 community_memo: OnceCell<(DerivedKey, LouvainOutput)>,
263 /// Grounded-labelling memo — one `MemLabelling` per mem whose
264 /// schema declares `relationships.labelling`, computed on first
265 /// access and invalidated exactly where the community memo is
266 /// (the reset lives inside [`Self::invalidate_communities`], so
267 /// every mutation site, drift reload, quarantine attach/detach
268 /// and apply-commit invalidate both without a second call).
269 /// Generation-keyed like `community_memo`.
270 labelling_memo: OnceCell<(
271 DerivedKey,
272 HashMap<String, crate::ops::labelling::MemLabelling>,
273 )>,
274 /// Lazily-computed per-mem search index map. Built on first call
275 /// to [`Self::search_indexes`] via [`build_all`]; invalidated by
276 /// [`Self::invalidate_search_indexes`] alongside the community
277 /// cache so every mutation triggers a fresh build on the next
278 /// search. Absent on `wasm32` targets — search lives behind the
279 /// bridge (see `EngineError::SearchUnavailable`).
280 #[cfg(not(target_arch = "wasm32"))]
281 /// Generation-keyed like `community_memo`.
282 search_indexes_memo: OnceCell<(DerivedKey, HashMap<String, MemIndex>)>,
283 /// The second half of [`DerivedKey`]: bumped whenever the
284 /// `schemas` map changes (schema switch, mount register/remove).
285 /// Both derived structures depend on schemas as well as the store
286 /// — community weights and the index field set come from the
287 /// pinned schema — so a schema change must invalidate them even
288 /// though the STORE generation did not move (the schema-switch
289 /// staleness the whole-map drop used to mask).
290 schemas_epoch: u64,
291 /// Workspace-level operator policy — mem create/delete rules,
292 /// cross-mem link permissions. Defaults to empty; populated via
293 /// [`Self::set_settings`] when [`Self::from_workspace_root`] (or
294 /// the full counterpart) reads `.memstead/workspace.toml`. Surfaced
295 /// read-only via [`Self::settings`] for MCP handlers and other
296 /// consumers.
297 settings: WorkspaceSettings,
298 /// Lazily-compiled [`crate::mem_management::CreateRuleSet`] over
299 /// `settings.mem_create_rules`. Built on first
300 /// [`Self::cross_mem_link_allowed`] call that needs synthesis;
301 /// invalidated by [`Self::set_settings`] (so a fresh policy
302 /// re-compiles on the next call). Compilation errors are logged
303 /// and the cache stays empty — synthesis is best-effort, the
304 /// resolver falls back to explicit-policy resolution. Operators
305 /// who want hard validation pre-compile via
306 /// [`crate::mem_management::CreateRuleSet::new`] before passing
307 /// settings.
308 create_rule_set_memo: OnceCell<crate::mem_management::CreateRuleSet>,
309 /// Per-mem data-trust origin declared by the embedding deployment
310 /// (e.g. a curated hosted read tier vouching for a read-only mount as
311 /// first-party). A *composition* fact set through
312 /// [`Self::declare_mem_origin`] by the process that owns the engine —
313 /// never persisted with the mem, never derived from mem content, and
314 /// deliberately not reachable over MCP, so a publisher cannot forge
315 /// first-party. Empty by default; [`Self::mem_origin_class`] falls back
316 /// to the writability inference for undeclared mems.
317 declared_origins: HashMap<String, crate::render::OriginClass>,
318 /// The workspace's own writing identities, declared by the embedding
319 /// deployment through [`Self::declare_owner_identities`]. A
320 /// composition fact on the same terms as `declared_origins`: set by
321 /// the process that owns the engine, never persisted with a mem,
322 /// never reachable over MCP, so nothing that can write a mem-repo can
323 /// add itself. It classifies text a party OTHER than the workspace
324 /// authored into workspace state — a check row's method note and
325 /// finding message, written by whatever agent the owner pointed at
326 /// the ledger, under an identity the launching side assigned.
327 ///
328 /// Empty by default, and empty means undeclared: every ledger
329 /// identity then inherits its mem's class, which is what the engine
330 /// did before this field, so an existing deployment is byte-identical.
331 /// A declared set makes an identity outside it third-party; a row with
332 /// no identity at all stays unconfirmable and inherits, never guessed
333 /// third-party (the same reading the independence gate takes).
334 owner_identities: std::collections::BTreeSet<String>,
335 /// Lazy per-mem map of entities whose claim-carrying sections are a
336 /// contributor's bytes, read from each writable mem's proposal record:
337 /// slug → the mark the merge recorded. Generation-keyed and
338 /// invalidated exactly like `community_memo`, so a merge's own
339 /// invalidation refreshes it. See [`Self::entity_origin_class`].
340 foreign_entities_memo: OnceCell<(DerivedKey, ForeignMarks)>,
341 /// Workspace root path — set when the engine boots from a
342 /// workspace store ([`Self::from_workspace_root`] or the full
343 /// counterpart). `None` for tests + ad-hoc consumers that build
344 /// the engine directly from a mount list. Surfaced via
345 /// [`Self::workspace_root`] for handlers that need filesystem
346 /// context (e.g. [`Self::health`]'s outer-repo .gitignore
347 /// check).
348 workspace_root: Option<PathBuf>,
349 /// The mount roster as this engine last read or last wrote it —
350 /// the baseline [`Engine::persist_state`] diffs against so a state
351 /// write publishes THIS engine's changes without republishing its
352 /// whole cached view over whatever a sibling process has since
353 /// registered. Interior mutability because `persist_state` takes
354 /// `&self`; the engine is already `!Sync`.
355 mounts_baseline: std::cell::RefCell<Vec<crate::workspace::Mount>>,
356 /// Typed warnings surfaced during mem load — drift findings
357 /// like [`WarningHint::SuspiciousNestedPrefix`] and
358 /// [`WarningHint::DuplicateSectionHeading`] that the loader
359 /// pipeline collects per entity. Empty for the V1 unified
360 /// engine; the field is in place so handlers and the health
361 /// surface can include them when the loader pipeline grows the
362 /// warning generators.
363 load_warnings: Vec<WarningHint>,
364 /// Mems that failed their mem-level boot step (unresolvable or
365 /// missing schema pin, backend instantiation or read failure) and
366 /// are quarantined instead of failing the whole workspace —
367 /// degrade, never disappear. A quarantined mem serves NOTHING:
368 /// operations naming it refuse with the typed `MEM_QUARANTINED`
369 /// code carrying the underlying reason (quarantine is not
370 /// tolerance — no partial data from a broken mem). The retained
371 /// [`Mount`] record lets `reload` re-attempt the attach after a
372 /// repair, without a process restart. Surfaced on overview and
373 /// health as the quarantine roster.
374 quarantined: Vec<QuarantinedMem>,
375 /// Workspace-level boot diagnosis carried by a diagnostic-shell
376 /// engine ([`Engine::diagnostic_shell`]): the typed reason the
377 /// REAL workspace could not boot at all (e.g. an unparseable
378 /// workspace store). `None` on every ordinarily booted engine.
379 /// Surfaced on overview and health so a session over a wholly
380 /// unbootable workspace can always ask WHY the graph is gone.
381 boot_diagnosis: Option<(String, String)>,
382 /// Pipeline configs (Medium / Facet / Projection / Ingest) loaded
383 /// from the workspace store at boot. Empty for engines built via
384 /// `from_mounts*` (tests, in-memory consumers) and for any workspace
385 /// that declares no pipelines; the workspace-root boot paths
386 /// (`from_workspace_root` and the full counterpart) populate it via
387 /// [`crate::pipeline_store::load_pipeline_configs`]. Read-only
388 /// runtime surface — exposed through [`Self::pipeline_configs`]; the
389 /// engine neither runs nor schedules pipelines (the ingest skill and
390 /// future consumers do).
391 pipeline_configs: crate::pipeline_store::BindingConfigs,
392 /// Runtime snapshot of writable / visible mems. Derived from
393 /// the mount list at construction: writable mounts
394 /// (`MountCapability::Write`) register via `add_writable` with
395 /// the storage's directory path (folder → `path`, git-branch →
396 /// None, archive shouldn't be writable); read-only mounts
397 /// register via `add_writable` (folder/git-branch) or
398 /// `add_read_only` (archive). Used by MCP handlers that need the
399 /// writable/visible roster + per-mem origin (`memstead_health
400 /// include_config: true`, `memstead_overview`'s mem list,
401 /// `memstead_mem_create`'s collision check).
402 ///
403 /// Wrapped in `Arc` so the COW-snapshot discipline — clone the
404 /// snapshot, mutate the clone, swap the `Arc` — keeps writers
405 /// and concurrent readers from contending on the live mount
406 /// list.
407 mem_router: Arc<MemRouterSnapshot>,
408 /// Backend factory — function pointer used by
409 /// [`crate::mem_management::create_mem`] (and future runtime
410 /// mount-add paths) to materialise a [`MemBackend`] from a
411 /// [`Mount`] declaration. Defaults to
412 /// [`crate::workspace_store::instantiate_local_backend`] so
413 /// folder + archive only consumers work out of the box. Git-branch
414 /// consumers swap in `memstead_git_branch::storage::instantiate_full_backend`
415 /// via [`Self::set_backend_factory`] after constructing the engine —
416 /// `engine_from_workspace_root` does this once at boot. Function
417 /// pointer (not `Box<dyn Fn>`) because the backend factory is
418 /// stateless, `Send + Sync + Copy`, and one less allocation on the
419 /// hot path matters for the multi-mem pattern this engine is
420 /// designed around.
421 backend_factory: BackendFactory,
422 /// Storage discovery for UNMOUNTED mems: set by
423 /// the git-branch boot, `None` in embedded engines (which keep the
424 /// forward-reference mechanic unchanged for unmounted targets).
425 pub(crate) unmounted_storage_prober: Option<UnmountedStorageProber>,
426 /// Git-branch ops bundle — function pointers for the per-mount
427 /// operations whose implementations live in `memstead-git-branch`
428 /// (and therefore can't sit on the `MemBackend` trait without
429 /// inverting the crate dependency). Full boot
430 /// (`memstead_git_branch::engine_from_workspace_root`) installs the
431 /// bundle via [`Self::set_git_branch_ops`]; consumers without it leave
432 /// it `None` and `Engine::changes_since` / `Engine::export_mem`
433 /// fall through to the folder/archive-only branches.
434 git_branch_ops: Option<GitBranchOps>,
435 /// Set while a proposal merge prepares the landing and the amend of an
436 /// entity the owner amends: the merge is one write of that entity, so
437 /// the transition forms judge its net effect against the pre-merge
438 /// entity once, after both are prepared, and the per-step reading is
439 /// deferred ([`Self::gate_transition_forms`]).
440 pub(crate) defer_transition_gates: bool,
441 /// Per-mem subscriber registry for [`MemChangedEvent`]s. Held
442 /// behind `Arc<Mutex<_>>` so [`SubscriptionHandle`]s — which own
443 /// the consumer's view of the subscription lifetime — can call
444 /// back into the registry on `Drop` without a self-reference cycle
445 /// to the engine. The emit path (in `record_self_write`) snapshots
446 /// the per-mem callback list under the lock, releases the lock,
447 /// and then invokes the callbacks — so a callback that re-enters
448 /// the engine for a read does not deadlock against the registry.
449 event_subscribers: Arc<std::sync::Mutex<events::SubscriberRegistry>>,
450 /// Reload-before-operation notices recorded by
451 /// [`Self::reload_if_stale`] when an operation triggered a mem
452 /// reload. Built at reload time — when the backend's current head
453 /// equals the head we reloaded to, *before* any mutation in the
454 /// same operation commits — so the delta describes only the
455 /// sibling's change, never the engine's own follow-on write.
456 /// Reachable only through an [`drift::OperationScope`]: `begin`
457 /// clears, `finish` hands the notices out as a value, and a
458 /// dropped scope clears again, so no operation inherits another's
459 /// notice and nothing on the engine hands them out on demand.
460 pending_mem_changed: Vec<crate::ops::MemChangedNotice>,
461 /// What each caller last saw of each mem, and who the operation in
462 /// progress is for: the source of the notices above
463 /// ([`callers`]).
464 callers: callers::CallerCursors,
465 /// Whether the operation in progress has brought its caller up to
466 /// date (a reload ran), so that closing the operation may take the
467 /// heads it leaves as seen.
468 caller_synced: bool,
469 /// Whether the operation in progress is its caller's first contact:
470 /// such an operation hands out no notice, however many reloads it
471 /// runs, and leaves the caller's memory at the heads storage holds.
472 caller_first_contact: bool,
473 /// Mems whose head appeared where none was during the reload in
474 /// progress, with the entities that reload brought in: what the
475 /// notice for such a mem lists as added. Filled and emptied inside
476 /// one reload.
477 appeared_heads: std::collections::HashMap<String, Vec<crate::entity::EntityId>>,
478 /// Warnings for interrupted commits a load completed, waiting for
479 /// the next operation's response. Kept apart from the load warnings
480 /// of the reload that did the completing: that reload can still
481 /// fail after it, and the completion happened all the same.
482 completed_commits: Vec<crate::ops::WarningHint>,
483 /// The mount roster as last reconciled (`roster.rs`): `None` until the
484 /// first observation captures the baseline.
485 roster_fingerprint: Option<roster::RosterFingerprint>,
486 /// Subscribers to applied roster changes: `(next id, callbacks)`.
487 roster_subscribers: Arc<roster::RosterSubscribers>,
488 /// Mems that left the roster during this engine's lifetime and have
489 /// not returned — the memory behind the `MEM_UNMOUNTED` refusal.
490 recently_unmounted: std::collections::HashSet<String>,
491 /// Test-only: make the unmount of the named mem fail before it
492 /// touches any state, to prove the roster change stays unapplied.
493 #[cfg(test)]
494 pub(crate) inject_unmount_failure: Option<String>,
495 /// Timestamp source for engine-stamped mutation metadata
496 /// (`created_date` on create, `last_modified` on update/relate/
497 /// rename — every field the schema marks `init_timestamp` /
498 /// `auto_timestamp`). Defaults to the system clock; tests that
499 /// assert over canonical entity bytes pin it via
500 /// [`Self::set_mutation_clock`] so two engines stamp identical
501 /// values. A testability affordance, not a behaviour switch:
502 /// nothing in production swaps the default, and the stamped
503 /// format (second-granularity RFC 3339, see
504 /// `mutation::iso_from_system_time`) is unchanged.
505 mutation_clock: MutationClock,
506 /// The caller-declared role for mutations in this session.
507 /// Set by the surface before each mutation
508 /// (per-call parameter wins over the surface's session default);
509 /// `Unspecified` records as absence. Session state on the engine
510 /// — the `mutation_clock` precedent — so the role travels into
511 /// every commit context and provenance record without widening
512 /// every mutation signature.
513 current_role: crate::vcs::Role,
514 /// The caller-declared identity for mutations and checks in this
515 /// session. Same session-state pattern as
516 /// `current_role`: set by the surface before each operation
517 /// (per-call parameter wins over the surface's session default);
518 /// `None` records as absence. An opaque caller-chosen string —
519 /// the engine neither generates, interprets, nor enriches it.
520 current_identity: Option<String>,
521 /// The transport's actor for commits the session causes without a
522 /// per-call actor (config writes, sync-state stamps, the anchor
523 /// writers): `Cli` under the CLI, `Agent` under the MCP server.
524 current_actor: crate::vcs::Actor,
525 /// The transport's client id, when it has one (the MCP client).
526 current_client: Option<crate::vcs::ClientId>,
527}
528
529/// Clock the engine reads when stamping mutation timestamps. `Arc`'d
530/// closure rather than a trait so a test can pin a constant with one
531/// line: `engine.set_mutation_clock(Arc::new(|| some_time))`.
532pub type MutationClock = Arc<dyn Fn() -> std::time::SystemTime + Send + Sync>;
533
534/// Backend factory function pointer. Both crates' existing
535/// `instantiate_*_backend` functions match this signature, so the
536/// type alias is what bridges the dependency direction (memstead-base
537/// can't depend on memstead-git-branch) without an extra trait.
538/// Stateless, `Send + Sync + Copy`.
539pub type BackendFactory =
540 fn(&Mount) -> Result<Box<dyn MemBackend>, crate::workspace_store::InstantiateError>;
541
542/// Per mem, what the merges recorded about the bodies adopted into it, as
543/// the origin read consults them.
544pub(crate) type ForeignMarks = HashMap<String, MemForeignMarks>;
545
546/// One mem's foreign-content marks: per slug, one prepared hash per
547/// load-bearing section of the body a merge adopted there, as no later
548/// disposition retired it.
549#[derive(Debug, Clone, Default, PartialEq, Eq)]
550pub(crate) struct MemForeignMarks {
551 /// Slug → (section key → prepared hash).
552 pub(crate) by_slug:
553 std::collections::BTreeMap<String, std::collections::BTreeMap<String, String>>,
554 /// Why the mem's proposal record could not be read, when it could not.
555 /// The marks are then unknown rather than absent, so every entity of the
556 /// mem reads third-party: a trust label may not fail open on a file it
557 /// could not read. The reason is kept so the label can say why
558 /// ([`Engine::proposal_record_error`]); a conservative label with no
559 /// stated cause is indistinguishable from the engine calling the
560 /// operator's own mem a stranger's.
561 pub(crate) record_unreadable: Option<String>,
562}
563
564impl MemForeignMarks {
565 pub(crate) fn unreadable(reason: String) -> Self {
566 Self {
567 by_slug: std::collections::BTreeMap::new(),
568 record_unreadable: Some(reason),
569 }
570 }
571}
572
573/// The validity key for derived-structure memos:
574/// the store generation (bumped by every store mutation, carried by
575/// `Store::clone` so batch rollback restores it) plus the schemas
576/// epoch (bumped by every change to the engine's schema map). A memo
577/// is current exactly while both halves still match.
578///
579/// The foreign-mark memo additionally reads a mem's proposal record,
580/// which is in neither half; every act that changes a mark also mutates
581/// the store, so the key still covers it, and a writer outside the
582/// engine is the one case it would not.
583#[derive(Debug, Clone, Copy, PartialEq, Eq)]
584pub struct DerivedKey {
585 pub store_generation: u64,
586 pub schemas_epoch: u64,
587}
588
589/// Discovered storage for a mem that has NO mount record — the
590/// unmounted half of the write-time cross-mem target verification. The workspace layer owns the discovery convention
591/// (the mem-repo's branch registry, which memstead-base cannot see
592/// without inverting the crate dependency) and hands back a transient
593/// backend to ask plus the mem's schema pin when its config declares
594/// one, so the cross-schema edge routing can keep its authority
595/// without a mount.
596pub struct UnmountedMemStorage {
597 /// Transient backend over the discovered storage. Used for the
598 /// cheap [`MemBackend::entity_exists`] probe and the one-blob
599 /// type read — never registered, never loaded.
600 pub backend: Box<dyn MemBackend>,
601 /// The mem's pinned schema, when its stored config declares one.
602 pub schema: Option<memstead_schema::SchemaRef>,
603}
604
605/// Discovery hook: mem name → its storage, when the workspace layer
606/// can find any (`None` = no discoverable storage; the
607/// forward-reference mechanic governs, exactly as before). Boxed
608/// closure rather than a function pointer because discovery needs the
609/// workspace root and gitdir captured at boot.
610pub type UnmountedStorageProber = Box<dyn Fn(&str) -> Option<UnmountedMemStorage> + Send + Sync>;
611
612/// `Engine::changes_since` dispatch for git-branch mounts.
613///
614/// Signature matches `memstead_git_branch::ops::changes::changes_since` after
615/// adapting the `Store` parameter away (the engine performs enrichment
616/// downstream) and the `head_ref` parameter (`refs/heads/<branch>` is
617/// constructed inside the impl from `branch`).
618pub type GitBranchChangesSinceFn = fn(
619 gitdir: &Path,
620 branch: &str,
621 mem: &str,
622 since: &str,
623 rename_similarity: f32,
624) -> Result<crate::ops::BackendChanges, BackendError>;
625
626/// `Engine::export_mem` dispatch for git-branch mounts.
627///
628/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch`.
629pub type GitBranchExportFn = fn(
630 gitdir: &Path,
631 branch: &str,
632 mem: &str,
633 config: &memstead_schema::MemConfig,
634 output_path: &Path,
635 workspace_root: Option<&Path>,
636 workspace_schemas_dir: Option<&Path>,
637 // Engine-sourced authoring-provenance payload bytes (from the mount's
638 // `read_provenance` log) to embed at `.memstead/provenance.json`.
639 // `None` when the mem carried no noted mutations.
640 provenance_bytes: Option<&[u8]>,
641 // Engine-sourced anchors sidecar bytes (from the mount's
642 // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
643 // when the mem carried no anchors. The engine reads the branch tip; the
644 // hook only embeds, keeping git tree-walking out of the fn-pointer.
645 anchors_bytes: Option<&[u8]>,
646 // Engine-sourced sealed check records (from the workspace ledger) to
647 // embed at `.memstead/checks.json`. `None` when no record qualifies.
648 checks_bytes: Option<&[u8]>,
649) -> Result<crate::ops::MemExportResult, BackendError>;
650
651/// `Engine::export_mem_to_bytes` dispatch for git-branch mounts.
652///
653/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch_to_bytes`.
654/// Symmetric to `GitBranchExportFn`: same inputs minus the output path,
655/// returns archive bytes plus metadata instead of writing to disk.
656pub type GitBranchExportToBytesFn = fn(
657 gitdir: &Path,
658 branch: &str,
659 mem: &str,
660 config: &memstead_schema::MemConfig,
661 workspace_root: Option<&Path>,
662 workspace_schemas_dir: Option<&Path>,
663 // Pre-built authoring-provenance payload bytes the engine sourced from
664 // the mount's `read_provenance` log, to embed at
665 // `.memstead/provenance.json`. `None` when the mem carried no noted
666 // mutations. The engine sources it (it holds the backend); the hook
667 // only embeds, keeping git history-walking out of the fn-pointer.
668 provenance_bytes: Option<&[u8]>,
669 // Engine-sourced anchors sidecar bytes (from the mount's
670 // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
671 // when the mem carried no anchors. Symmetric with `provenance_bytes`:
672 // the engine reads the branch tip, the hook only embeds.
673 anchors_bytes: Option<&[u8]>,
674 // Engine-sourced sealed check records (from the workspace ledger) to
675 // embed at `.memstead/checks.json`. `None` when no record qualifies.
676 checks_bytes: Option<&[u8]>,
677) -> Result<crate::ops::MemExportBytes, BackendError>;
678
679/// `Engine::diff` dispatch for git-branch mounts. Walks the two refs
680/// inside the workspace's mem-repo gitdir, produces a per-entity
681/// [`crate::ops::Diff`]. Refs are arbitrary `gix::rev_parse_single`
682/// inputs — branch names, commit SHAs, tag names. Resolves each
683/// independently so cross-branch (cross-mem) diffs work uniformly.
684/// `branch` is the mount's declared branch; a bare `HEAD` token in
685/// either ref re-anchors onto it.
686pub type GitBranchDiffFn = fn(
687 gitdir: &Path,
688 branch: &str,
689 mem: &str,
690 ref_a: &str,
691 ref_b: &str,
692 config: &crate::ops::DiffConfig,
693) -> Result<crate::ops::Diff, BackendError>;
694
695/// `Engine::fetch` dispatch for git-branch mounts.
696pub type GitBranchFetchFn = fn(
697 gitdir: &Path,
698 remote: &str,
699 refspecs: &[String],
700) -> Result<crate::ops::FetchOutcome, BackendError>;
701
702/// Read every `.md` blob at `ref_name` in `gitdir`, returning
703/// `(relative_path, utf8_content)` pairs. Skips `.memstead/` engine-internal
704/// entries and non-blob nodes. Used by the pre-merge schema-validation
705/// pass `Engine::pull` and `Engine::push` run before they advance the
706/// branch pointer / push to the remote.
707pub type GitBranchReadTreeFn =
708 fn(gitdir: &Path, ref_name: &str) -> Result<Vec<(String, String)>, BackendError>;
709
710/// `Engine::pull` dispatch for git-branch mounts. `branch` is the
711/// mount's declared branch — the single source of truth for both the
712/// local ref and the remote-tracking ref; `mem` labels the outcome
713/// only.
714pub type GitBranchPullFn = fn(
715 gitdir: &Path,
716 remote: &str,
717 branch: &str,
718 mem: &str,
719) -> Result<crate::ops::PullOutcome, BackendError>;
720
721/// `Engine::push` dispatch for git-branch mounts. `branch` is the
722/// mount's declared branch (see [`GitBranchPullFn`]); `mem` labels
723/// the outcome only.
724pub type GitBranchPushFn = fn(
725 gitdir: &Path,
726 remote: &str,
727 branch: &str,
728 mem: &str,
729 force: bool,
730) -> Result<crate::ops::PushOutcome, BackendError>;
731
732/// `Engine::push_all` dispatch, first half: the remote's ref table
733/// in one round-trip (`git ls-remote --heads`), as `(full ref name,
734/// sha)` pairs. Lets the engine tell a lagging ref from one already
735/// in sync before it sends anything.
736pub type GitBranchLsRemoteFn =
737 fn(gitdir: &Path, remote: &str) -> Result<Vec<(String, String)>, BackendError>;
738
739/// `Engine::push_all` dispatch, second half: resolve one local ref
740/// to its SHA. `Ok(None)` when the ref does not exist (a fresh
741/// mem-repo legitimately has no `__MEMSTEAD` yet).
742pub type GitBranchResolveRefFn =
743 fn(gitdir: &Path, ref_name: &str) -> Result<Option<String>, BackendError>;
744
745/// `Engine::remote_status` dispatch: whether `ancestor` is reachable
746/// from `descendant` in the gitdir's history (`git merge-base
747/// --is-ancestor`). Read-only; tells local-ahead from behind from forked
748/// without moving a ref.
749pub type GitBranchIsAncestorFn =
750 fn(gitdir: &Path, ancestor: &str, descendant: &str) -> Result<bool, BackendError>;
751
752/// `Engine::pull_all` dispatch: whether the commit `sha` is a root
753/// commit (no parent) over the empty tree, the shape of a freshly
754/// bootstrapped schema-and-config ref that carries no state yet.
755/// Read-only.
756pub type GitBranchIsEmptyRootFn = fn(gitdir: &Path, sha: &str) -> Result<bool, BackendError>;
757
758/// The nearest common ancestor of two commits (`git merge-base`);
759/// `None` when they share no history. Read-only. The adopt form of
760/// `mem fork` reads the ancestor of a fork branch that arrived on a
761/// remote off it.
762pub type GitBranchMergeBaseFn =
763 fn(gitdir: &Path, a: &str, b: &str) -> Result<Option<String>, BackendError>;
764
765/// Merge two commits' trees path by path from their merge base, when no
766/// path changed on both sides: the paths only `theirs` changed are
767/// applied onto `ours`'s tree, and a commit with both parents (`ours`
768/// first) is written with `message`. No ref moves; the caller moves it.
769/// A path changed on both sides is a content decision the merge does
770/// not make: the answer names every such path and writes nothing.
771pub type GitBranchMergeDisjointFn = fn(
772 gitdir: &Path,
773 ours: &str,
774 theirs: &str,
775 message: &str,
776) -> Result<DisjointMerge, BackendError>;
777
778/// What a [`GitBranchMergeDisjointFn`] came to.
779#[derive(Debug, Clone, PartialEq, Eq)]
780pub enum DisjointMerge {
781 /// The merge commit, not yet on any ref.
782 Merged { commit: String },
783 /// Paths both sides changed since their merge base; nothing written.
784 Overlap { paths: Vec<String> },
785 /// The two commits share no history, so there is no base to merge
786 /// from; nothing written.
787 Unrelated,
788}
789
790/// Point `ref_name` at `sha`, under the precondition `previous` names.
791/// A move that decided on an observed tip pins it with
792/// [`RefPrevious::At`] (or [`RefPrevious::Absent`] for a ref it saw
793/// missing), so a commit that lands between the decision and the move
794/// makes the move fail instead of being dropped. [`RefPrevious::Any`] is
795/// for a ref the engine derives and owns outright (the check-ledger
796/// transport ref, re-derived from the workspace ledger before every
797/// publish).
798pub type GitBranchUpdateRefFn = fn(
799 gitdir: &Path,
800 ref_name: &str,
801 sha: &str,
802 previous: RefPrevious<'_>,
803) -> Result<(), BackendError>;
804
805/// The precondition of a [`GitBranchUpdateRefFn`] move.
806#[derive(Debug, Clone, Copy, PartialEq, Eq)]
807pub enum RefPrevious<'a> {
808 /// Move whatever the ref points at, or create it.
809 Any,
810 /// The ref must not exist.
811 Absent,
812 /// The ref must point at this commit.
813 At(&'a str),
814}
815
816/// `Engine::remote_add` dispatch — configures a named remote on the
817/// mem-repo gitdir (upsert: add, or set-url when it already exists).
818pub type GitBranchRemoteAddFn =
819 fn(gitdir: &Path, name: &str, url: &str) -> Result<crate::ops::RemoteAddOutcome, BackendError>;
820
821/// `Engine::branch_reset` dispatch for git-branch mounts. Returns the
822/// outcome on success; surfaces `BackendError::Other` carrying an
823/// in-band marker (`UNKNOWN_REF:<raw>` or
824/// `PUSHED_COMMITS_PROTECTED:<sha,sha,...>`) the engine layer
825/// un-marshals into typed `EngineError`s.
826pub type GitBranchBranchResetFn = fn(
827 gitdir: &Path,
828 branch: &str,
829 target_sha: &str,
830 expected_head: Option<&str>,
831) -> Result<crate::ops::BranchResetOutcome, BackendError>;
832
833/// Residue-prune dispatch for git-branch mounts.
834/// The `create_mem` orchestrator calls this when
835/// `RecoveryAction::ForceOverwrite` is selected against pre-existing
836/// storage residue. Drops `refs/heads/<branch_full_path>` and the
837/// `__MEMSTEAD:mems/<branch_full_path>/config.json` blob in one
838/// ref-edit transaction (the same call the
839/// `MemBackend::delete_artifacts` impl wraps for delete-files
840/// flows). Surfaces as a function pointer so `crate::mem_management`
841/// can drive a prune against an unmounted gitdir without depending on
842/// `memstead-git-branch`.
843pub type GitBranchPruneResidueFn = fn(
844 gitdir: &Path,
845 branch_full_path: &str,
846 ctx: &crate::vcs::CommitContext<'_>,
847) -> Result<(), BackendError>;
848
849/// Config-only prune: drop the mem's blobs on `__MEMSTEAD` and leave
850/// every content branch alone. `create_mem` rolls a failed seed commit
851/// back through it so no config outlives the mem it was written for;
852/// `delete_mem` removes a config left behind that way. Idempotent.
853pub type GitBranchPruneConfigBlobFn = fn(
854 gitdir: &Path,
855 branch_full_path: &str,
856 ctx: &crate::vcs::CommitContext<'_>,
857) -> Result<(), BackendError>;
858
859/// Ref-namespace probe: the local branches a new
860/// `refs/heads/<branch_full_path>` could not coexist with, because
861/// one is a path prefix of the other (git keeps refs as files in
862/// directories). `create_mem` asks before it writes anything.
863pub type GitBranchNamespaceConflictsFn =
864 fn(gitdir: &Path, branch_full_path: &str) -> Result<Vec<String>, BackendError>;
865
866/// `fork_mem` dispatch: create `refs/heads/<branch_full_path>` at
867/// `sha`, a full commit id already in the object store, in one
868/// ref-edit that refuses when the ref exists. The branch is the
869/// fork's lineage claim: its first commit is the source's, never a
870/// fresh seed.
871pub type GitBranchCreateBranchAtFn =
872 fn(gitdir: &Path, branch_full_path: &str, sha: &str) -> Result<(), BackendError>;
873
874/// `fork_mem` dispatch for the remote form: one mem's config blob
875/// (`mems/<mem>/config.json`) from the `__MEMSTEAD` tree at
876/// `ref_name`, the remote-tracking ref a fetch just placed
877/// (`refs/remotes/<remote>/__MEMSTEAD`), never the local
878/// `refs/heads/__MEMSTEAD`. `Ok(None)` when the ref or the blob is
879/// absent. Read-only.
880pub type GitBranchReadConfigAtRefFn =
881 fn(gitdir: &Path, ref_name: &str, mem: &str) -> Result<Option<Vec<u8>>, BackendError>;
882
883/// `rename_mem` dispatch for the git-branch backend: move the mem's
884/// content branch `refs/heads/<old>` to `refs/heads/<new>` at the same
885/// tip (history preserved) and relocate the `__MEMSTEAD:mems/<old>/`
886/// config blob to `mems/<new>/`, all in one ref-edit transaction.
887/// Refuses (no mutation) when the source branch is missing or the
888/// target branch already exists.
889pub type GitBranchRenameMemStorageFn = fn(
890 gitdir: &Path,
891 old_leaf: &str,
892 new_leaf: &str,
893 ctx: &crate::vcs::CommitContext<'_>,
894) -> Result<(), BackendError>;
895
896/// `Engine::install_schema` dispatch for the git-branch backend: write a
897/// schema package (`(relative-path, bytes)` pairs) onto the workspace's
898/// unified `__MEMSTEAD:schemas/<name>@<version>/` ref and return the
899/// resulting commit sha. Mirrors
900/// `memstead_git_branch::storage_memstead::write_schema_to_memstead_ref`.
901pub type GitBranchWriteSchemaFn = fn(
902 gitdir: &Path,
903 name: &str,
904 version: &str,
905 files: &[(String, Vec<u8>)],
906) -> Result<String, BackendError>;
907
908/// Read one file from a sealed schema package on the workspace's
909/// `__MEMSTEAD:schemas/<name>@<version>/` ref. `Ok(None)` when the
910/// ref, package, or file is absent — absence is a normal state (the
911/// install-provenance stamp only exists for path-sourced installs).
912/// Read-only; the authoring-drift health axis is the consumer.
913pub type GitBranchReadSchemaFileFn = fn(
914 gitdir: &Path,
915 name: &str,
916 version: &str,
917 rel: &str,
918) -> Result<Option<Vec<u8>>, BackendError>;
919
920/// Re-read every schema sealed on one git directory's
921/// `__MEMSTEAD:schemas/` ref (empty when the directory, the ref or the
922/// subtree is absent). Read-only; `Engine::full_refresh` is the
923/// consumer, the warm-server path that makes an out-of-band `memstead
924/// schema install` resolvable without a process restart. It calls this
925/// once per directory of [`crate::workspace::schema_registry_gitdirs`].
926pub type GitBranchReadRefSchemasFn =
927 fn(gitdir: &Path) -> Result<Vec<Arc<memstead_schema::Schema>>, BackendError>;
928
929/// Collect one pinned schema's raw source files (manifest, sealed
930/// format marker, type definitions) from one git directory's
931/// `__MEMSTEAD:schemas/<name>@<version>/` ref — the tree `memstead
932/// schema install` writes on the git-branch backend. `Ok(None)` when
933/// the directory, the ref, or the package is absent. Read-only;
934/// the consumer is the FOLDER-mount export path: a folder mem living
935/// in a mem-repo workspace pins a schema the installer sealed on the
936/// ref, so the archive assembler must read the same store the loader
937/// resolves from, or the mem loads but cannot export. The caller walks
938/// [`crate::workspace::schema_registry_gitdirs`] and takes the first
939/// directory that carries the package.
940pub type GitBranchCollectSchemaSourceFn =
941 fn(
942 gitdir: &Path,
943 schema_ref: &memstead_schema::SchemaRef,
944 ) -> Result<Option<Vec<memstead_schema::SchemaSourceFile>>, BackendError>;
945
946/// Bundle of git-branch-specific op dispatchers. Installed on the
947/// engine at full boot. Each field is one ops-method that previously
948/// lived on the `MemBackend` trait; moving them off the trait keeps
949/// the bytes-level primitive surface clean.
950#[derive(Clone, Copy)]
951pub struct GitBranchOps {
952 pub changes_since: GitBranchChangesSinceFn,
953 pub diff: GitBranchDiffFn,
954 pub branch_reset: GitBranchBranchResetFn,
955 pub fetch: GitBranchFetchFn,
956 pub pull: GitBranchPullFn,
957 pub push: GitBranchPushFn,
958 pub ls_remote: GitBranchLsRemoteFn,
959 pub resolve_ref: GitBranchResolveRefFn,
960 pub is_ancestor: GitBranchIsAncestorFn,
961 pub is_empty_root: GitBranchIsEmptyRootFn,
962 pub merge_base: GitBranchMergeBaseFn,
963 pub merge_disjoint: GitBranchMergeDisjointFn,
964 pub update_ref: GitBranchUpdateRefFn,
965 pub remote_add: GitBranchRemoteAddFn,
966 pub read_tree: GitBranchReadTreeFn,
967 pub export: GitBranchExportFn,
968 pub export_to_bytes: GitBranchExportToBytesFn,
969 pub prune_residue: GitBranchPruneResidueFn,
970 pub prune_config_blob: GitBranchPruneConfigBlobFn,
971 pub branch_namespace_conflicts: GitBranchNamespaceConflictsFn,
972 pub create_branch_at: GitBranchCreateBranchAtFn,
973 pub read_config_at_ref: GitBranchReadConfigAtRefFn,
974 pub rename_mem_storage: GitBranchRenameMemStorageFn,
975 pub write_schema: GitBranchWriteSchemaFn,
976 pub read_schema_file: GitBranchReadSchemaFileFn,
977 pub read_ref_schemas: GitBranchReadRefSchemasFn,
978 pub collect_ref_schema_source: GitBranchCollectSchemaSourceFn,
979}
980
981impl std::fmt::Debug for Engine {
982 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
983 f.debug_struct("Engine")
984 .field(
985 "mems",
986 &self
987 .mounts
988 .iter()
989 .map(|m| m.mount.mem.as_str())
990 .collect::<Vec<_>>(),
991 )
992 .finish()
993 }
994}
995
996#[cfg(test)]
997mod in_memory_mem;
998
999#[cfg(test)]
1000pub(super) mod test_helpers {
1001 use std::io::Write as _;
1002 use std::path::{Path, PathBuf};
1003
1004 use memstead_schema::SchemaRef;
1005
1006 use crate::backend::MemBackend;
1007 use crate::storage::FilesystemBackend;
1008 use crate::vcs::{Actor, ClientId};
1009 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
1010
1011 use super::{CreateEntityArgs, CreateEntityOutcome, Engine, RelateEntityArgs};
1012
1013 use indexmap::IndexMap;
1014 use tempfile::TempDir;
1015
1016 pub(crate) fn pin(name: &str) -> SchemaRef {
1017 let version = match name {
1018 "default" => semver::Version::new(1, 0, 0),
1019 _ => semver::Version::new(0, 1, 0),
1020 };
1021 SchemaRef::new(name, version)
1022 }
1023
1024 pub(crate) fn folder_mount(mem: &str, path: PathBuf) -> Mount {
1025 Mount {
1026 mem: mem.to_string(),
1027 schema: Some(pin("default")),
1028 storage: MountStorage::Folder { path },
1029 capability: MountCapability::Write,
1030 lifecycle: MountLifecycle::Eager,
1031 cross_linkable: true,
1032 migration_target: None,
1033 }
1034 }
1035
1036 pub(crate) fn in_memory_mount(mem: &str) -> Mount {
1037 Mount {
1038 mem: mem.to_string(),
1039 schema: Some(pin("default")),
1040 storage: MountStorage::InMemory,
1041 capability: MountCapability::Write,
1042 lifecycle: MountLifecycle::Eager,
1043 cross_linkable: true,
1044 migration_target: None,
1045 }
1046 }
1047
1048 pub(crate) fn archive_mount(mem: &str, path: PathBuf) -> Mount {
1049 Mount {
1050 mem: mem.to_string(),
1051 schema: Some(pin("default")),
1052 storage: MountStorage::Archive { path },
1053 capability: MountCapability::ReadOnly,
1054 // Eager, matching every production archive-mount site: these
1055 // tests pin archive READ semantics over a loaded store. A
1056 // `Lazy` value here would defer the load these tests read
1057 // through.
1058 // The lazy behaviour has its own tests in `boot.rs`.
1059 lifecycle: MountLifecycle::Eager,
1060 cross_linkable: false,
1061 migration_target: None,
1062 }
1063 }
1064
1065 /// Build a sealed archive at `tmp/<name>.mem` from
1066 /// `(relative_path, bytes)` pairs and return the path.
1067 pub(crate) fn build_archive(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
1068 let path = tmp.join(format!("{name}.mem"));
1069 let file = std::fs::File::create(&path).unwrap();
1070 let mut writer = zip::ZipWriter::new(file);
1071 let opts = zip::write::SimpleFileOptions::default();
1072 for (rel, bytes) in entries {
1073 writer.start_file(*rel, opts).unwrap();
1074 writer.write_all(bytes).unwrap();
1075 }
1076 writer.finish().unwrap();
1077 path
1078 }
1079
1080 /// Write a schema manifest + minimal type bodies under
1081 /// `<root>/<name>/`. Each type gets a body with a single
1082 /// `body` section and `_default` hierarchy/no-self-loop lists — enough
1083 /// to load and parse markdown that uses that type. Used by tests
1084 /// that need a custom schema with shape or vocabulary constraints.
1085 pub(crate) fn write_schema_files_with_default_type(
1086 root: &Path,
1087 name: &str,
1088 manifest: &str,
1089 types: &[&str],
1090 ) {
1091 const TYPE_BODY: &str = r#"description: t
1092when_to_use: Here
1093sections:
1094 - key: body
1095 heading: Body
1096 required: true
1097 search_weight: 10.0
1098 catch_all: true
1099 write_rules: []
1100metadata_fields: []
1101title_weight: 100.0
1102text_fields:
1103 - body
1104hierarchy_relationship: _default
1105no_self_loop_relationships: []
1106updatable_fields:
1107 - title
1108 - body
1109health_required_fields:
1110 - body
1111staleness_threshold_days: 90
1112write_rules: []
1113"#;
1114 let dir = root.join(name);
1115 std::fs::create_dir_all(dir.join("types")).unwrap();
1116 std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
1117 for type_name in types {
1118 let body = format!("name: {type_name}\n{TYPE_BODY}");
1119 std::fs::write(dir.join("types").join(format!("{type_name}.yaml")), body).unwrap();
1120 }
1121 }
1122
1123 pub(crate) fn empty_create_args(mem: &str, title: &str) -> CreateEntityArgs {
1124 // The
1125 // create path refuses on missing required sections. The
1126 // default `spec` type requires `identity` + `purpose`. Seed
1127 // both with a single space so the test fixture remains a
1128 // valid creation request — every test that uses this helper
1129 // as a fixture builder continues to work, and tests that
1130 // specifically exercise the refusal supply an explicit
1131 // empty-sections payload (see the dedicated refusal tests).
1132 let mut sections = IndexMap::new();
1133 sections.insert("identity".to_string(), "fixture identity body".to_string());
1134 sections.insert("purpose".to_string(), "fixture purpose body".to_string());
1135 CreateEntityArgs {
1136 anchors: Vec::new(),
1137 mem: mem.to_string(),
1138 title: title.to_string(),
1139 entity_type: "spec".to_string(),
1140 sections,
1141 metadata: IndexMap::new(),
1142 relations: Vec::new(),
1143 dry_run: false,
1144 }
1145 }
1146
1147 pub(crate) fn cli_actor() -> (Actor, ClientId) {
1148 (
1149 Actor::Cli,
1150 ClientId {
1151 name: "claude-code".to_string(),
1152 version: "2.1.0".to_string(),
1153 },
1154 )
1155 }
1156
1157 pub(crate) fn engine_with_seed(tmp: &TempDir, title: &str) -> (Engine, CreateEntityOutcome) {
1158 let mem_dir = tmp.path().to_path_buf();
1159 let writer = FilesystemBackend::new(mem_dir.clone());
1160 let mut engine = Engine::from_mounts(vec![(
1161 folder_mount("specs", mem_dir),
1162 Box::new(writer) as Box<dyn MemBackend>,
1163 )])
1164 .unwrap();
1165 let (actor, client) = cli_actor();
1166 let outcome = engine
1167 .create_entity(
1168 empty_create_args("specs", title),
1169 actor,
1170 Some(&client),
1171 None,
1172 )
1173 .unwrap();
1174 (engine, outcome)
1175 }
1176 pub(crate) fn build_demo_engine(tmp: &TempDir) -> Engine {
1177 let mem_dir = tmp.path().to_path_buf();
1178 let writer = FilesystemBackend::new(mem_dir.clone());
1179 let mut engine = Engine::from_mounts(vec![(
1180 folder_mount("specs", mem_dir),
1181 Box::new(writer) as Box<dyn MemBackend>,
1182 )])
1183 .unwrap();
1184 let (actor, client) = cli_actor();
1185 let source = engine
1186 .create_entity(
1187 empty_create_args("specs", "Source One"),
1188 actor,
1189 Some(&client),
1190 None,
1191 )
1192 .unwrap();
1193 let target = engine
1194 .create_entity(
1195 empty_create_args("specs", "Target Two"),
1196 actor,
1197 Some(&client),
1198 None,
1199 )
1200 .unwrap();
1201 engine
1202 .create_entity(
1203 empty_create_args("specs", "Lonely Three"),
1204 actor,
1205 Some(&client),
1206 None,
1207 )
1208 .unwrap();
1209 engine
1210 .relate_entity(
1211 RelateEntityArgs {
1212 source: source.id.clone(),
1213 expected_hash: Some(source.content_hash.clone()),
1214 rel_type: "USES".to_string(),
1215 target: target.id.clone(),
1216 remove: false,
1217 description: None,
1218 dry_run: false,
1219 },
1220 actor,
1221 Some(&client),
1222 None,
1223 )
1224 .unwrap();
1225 engine
1226 }
1227}