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`]. A ref names the empty tree, or is anchored in
682/// the history of `branch` or of one of `readable`, the declared
683/// branches of the other mems the workspace mounts in the same git
684/// directory: at one of those branches by name, at `HEAD`, or at a
685/// commit hash of those histories, with `~n` and `^n` parent steps;
686/// any other ref refuses `UNKNOWN_REF`, as a ref that names nothing
687/// does. `branch` is the mount's declared branch; a
688/// bare `HEAD` token in either ref re-anchors onto it.
689pub type GitBranchDiffFn = fn(
690 gitdir: &Path,
691 branch: &str,
692 readable: &[String],
693 mem: &str,
694 ref_a: &str,
695 ref_b: &str,
696 config: &crate::ops::DiffConfig,
697) -> Result<crate::ops::Diff, BackendError>;
698
699/// `Engine::fetch` dispatch for git-branch mounts.
700pub type GitBranchFetchFn = fn(
701 gitdir: &Path,
702 remote: &str,
703 refspecs: &[String],
704) -> Result<crate::ops::FetchOutcome, BackendError>;
705
706/// Read every `.md` blob at `ref_name` in `gitdir`, returning
707/// `(relative_path, utf8_content)` pairs. Skips `.memstead/` engine-internal
708/// entries and non-blob nodes. Used by the pre-merge schema-validation
709/// pass `Engine::pull` and `Engine::push` run before they advance the
710/// branch pointer / push to the remote.
711pub type GitBranchReadTreeFn =
712 fn(gitdir: &Path, ref_name: &str) -> Result<Vec<(String, String)>, BackendError>;
713
714/// `Engine::pull` dispatch for git-branch mounts. `branch` is the
715/// mount's declared branch — the single source of truth for both the
716/// local ref and the remote-tracking ref; `mem` labels the outcome
717/// only.
718pub type GitBranchPullFn = fn(
719 gitdir: &Path,
720 remote: &str,
721 branch: &str,
722 mem: &str,
723) -> Result<crate::ops::PullOutcome, BackendError>;
724
725/// `Engine::push` dispatch for git-branch mounts. `branch` is the
726/// mount's declared branch (see [`GitBranchPullFn`]); `mem` labels
727/// the outcome only.
728pub type GitBranchPushFn = fn(
729 gitdir: &Path,
730 remote: &str,
731 branch: &str,
732 mem: &str,
733 force: bool,
734) -> Result<crate::ops::PushOutcome, BackendError>;
735
736/// `Engine::push_all` dispatch, first half: the remote's ref table
737/// in one round-trip (`git ls-remote --heads`), as `(full ref name,
738/// sha)` pairs. Lets the engine tell a lagging ref from one already
739/// in sync before it sends anything.
740pub type GitBranchLsRemoteFn =
741 fn(gitdir: &Path, remote: &str) -> Result<Vec<(String, String)>, BackendError>;
742
743/// `Engine::push_all` dispatch, second half: resolve one local ref
744/// to its SHA. `Ok(None)` when the ref does not exist (a fresh
745/// mem-repo legitimately has no `__MEMSTEAD` yet).
746pub type GitBranchResolveRefFn =
747 fn(gitdir: &Path, ref_name: &str) -> Result<Option<String>, BackendError>;
748
749/// `Engine::remote_status` dispatch: whether `ancestor` is reachable
750/// from `descendant` in the gitdir's history (`git merge-base
751/// --is-ancestor`). Read-only; tells local-ahead from behind from forked
752/// without moving a ref.
753pub type GitBranchIsAncestorFn =
754 fn(gitdir: &Path, ancestor: &str, descendant: &str) -> Result<bool, BackendError>;
755
756/// `Engine::pull_all` dispatch: whether the commit `sha` is a root
757/// commit (no parent) over the empty tree, the shape of a freshly
758/// bootstrapped schema-and-config ref that carries no state yet.
759/// Read-only.
760pub type GitBranchIsEmptyRootFn = fn(gitdir: &Path, sha: &str) -> Result<bool, BackendError>;
761
762/// The nearest common ancestor of two commits (`git merge-base`);
763/// `None` when they share no history. Read-only. The adopt form of
764/// `mem fork` reads the ancestor of a fork branch that arrived on a
765/// remote off it.
766pub type GitBranchMergeBaseFn =
767 fn(gitdir: &Path, a: &str, b: &str) -> Result<Option<String>, BackendError>;
768
769/// Merge two commits' trees path by path from their merge base, when no
770/// path changed on both sides: the paths only `theirs` changed are
771/// applied onto `ours`'s tree, and a commit with both parents (`ours`
772/// first) is written with `message`. No ref moves; the caller moves it.
773/// A path changed on both sides is a content decision the merge does
774/// not make: the answer names every such path and writes nothing.
775pub type GitBranchMergeDisjointFn = fn(
776 gitdir: &Path,
777 ours: &str,
778 theirs: &str,
779 message: &str,
780) -> Result<DisjointMerge, BackendError>;
781
782/// What a [`GitBranchMergeDisjointFn`] came to.
783#[derive(Debug, Clone, PartialEq, Eq)]
784pub enum DisjointMerge {
785 /// The merge commit, not yet on any ref.
786 Merged { commit: String },
787 /// Paths both sides changed since their merge base; nothing written.
788 Overlap { paths: Vec<String> },
789 /// The two commits share no history, so there is no base to merge
790 /// from; nothing written.
791 Unrelated,
792}
793
794/// Point `ref_name` at `sha`, under the precondition `previous` names.
795/// A move that decided on an observed tip pins it with
796/// [`RefPrevious::At`] (or [`RefPrevious::Absent`] for a ref it saw
797/// missing), so a commit that lands between the decision and the move
798/// makes the move fail instead of being dropped. [`RefPrevious::Any`] is
799/// for a ref the engine derives and owns outright (the check-ledger
800/// transport ref, re-derived from the workspace ledger before every
801/// publish).
802pub type GitBranchUpdateRefFn = fn(
803 gitdir: &Path,
804 ref_name: &str,
805 sha: &str,
806 previous: RefPrevious<'_>,
807) -> Result<(), BackendError>;
808
809/// The precondition of a [`GitBranchUpdateRefFn`] move.
810#[derive(Debug, Clone, Copy, PartialEq, Eq)]
811pub enum RefPrevious<'a> {
812 /// Move whatever the ref points at, or create it.
813 Any,
814 /// The ref must not exist.
815 Absent,
816 /// The ref must point at this commit.
817 At(&'a str),
818}
819
820/// `Engine::remote_add` dispatch — configures a named remote on the
821/// mem-repo gitdir (upsert: add, or set-url when it already exists).
822pub type GitBranchRemoteAddFn =
823 fn(gitdir: &Path, name: &str, url: &str) -> Result<crate::ops::RemoteAddOutcome, BackendError>;
824
825/// `Engine::branch_reset` dispatch for git-branch mounts. Returns the
826/// outcome on success; surfaces `BackendError::Other` carrying an
827/// in-band marker (`UNKNOWN_REF:<raw>` or
828/// `PUSHED_COMMITS_PROTECTED:<sha,sha,...>`) the engine layer
829/// un-marshals into typed `EngineError`s.
830pub type GitBranchBranchResetFn = fn(
831 gitdir: &Path,
832 branch: &str,
833 target_sha: &str,
834 expected_head: Option<&str>,
835) -> Result<crate::ops::BranchResetOutcome, BackendError>;
836
837/// Residue-prune dispatch for git-branch mounts.
838/// The `create_mem` orchestrator calls this when
839/// `RecoveryAction::ForceOverwrite` is selected against pre-existing
840/// storage residue. Drops `refs/heads/<branch_full_path>` and the
841/// `__MEMSTEAD:mems/<branch_full_path>/config.json` blob in one
842/// ref-edit transaction (the same call the
843/// `MemBackend::delete_artifacts` impl wraps for delete-files
844/// flows). Surfaces as a function pointer so `crate::mem_management`
845/// can drive a prune against an unmounted gitdir without depending on
846/// `memstead-git-branch`.
847pub type GitBranchPruneResidueFn = fn(
848 gitdir: &Path,
849 branch_full_path: &str,
850 ctx: &crate::vcs::CommitContext<'_>,
851) -> Result<(), BackendError>;
852
853/// Config-only prune: drop the mem's blobs on `__MEMSTEAD` and leave
854/// every content branch alone. `create_mem` rolls a failed seed commit
855/// back through it so no config outlives the mem it was written for;
856/// `delete_mem` removes a config left behind that way. Idempotent.
857pub type GitBranchPruneConfigBlobFn = fn(
858 gitdir: &Path,
859 branch_full_path: &str,
860 ctx: &crate::vcs::CommitContext<'_>,
861) -> Result<(), BackendError>;
862
863/// Ref-namespace probe: the local branches a new
864/// `refs/heads/<branch_full_path>` could not coexist with, because
865/// one is a path prefix of the other (git keeps refs as files in
866/// directories). `create_mem` asks before it writes anything.
867pub type GitBranchNamespaceConflictsFn =
868 fn(gitdir: &Path, branch_full_path: &str) -> Result<Vec<String>, BackendError>;
869
870/// `fork_mem` dispatch: create `refs/heads/<branch_full_path>` at
871/// `sha`, a full commit id already in the object store, in one
872/// ref-edit that refuses when the ref exists. The branch is the
873/// fork's lineage claim: its first commit is the source's, never a
874/// fresh seed.
875pub type GitBranchCreateBranchAtFn =
876 fn(gitdir: &Path, branch_full_path: &str, sha: &str) -> Result<(), BackendError>;
877
878/// `fork_mem` dispatch for the remote form: one mem's config blob
879/// (`mems/<mem>/config.json`) from the `__MEMSTEAD` tree at
880/// `ref_name`, the remote-tracking ref a fetch just placed
881/// (`refs/remotes/<remote>/__MEMSTEAD`), never the local
882/// `refs/heads/__MEMSTEAD`. `Ok(None)` when the ref or the blob is
883/// absent. Read-only.
884pub type GitBranchReadConfigAtRefFn =
885 fn(gitdir: &Path, ref_name: &str, mem: &str) -> Result<Option<Vec<u8>>, BackendError>;
886
887/// `rename_mem` dispatch for the git-branch backend: move the mem's
888/// content branch `refs/heads/<old>` to `refs/heads/<new>` at the same
889/// tip (history preserved) and relocate the `__MEMSTEAD:mems/<old>/`
890/// config blob to `mems/<new>/`, all in one ref-edit transaction.
891/// Refuses (no mutation) when the source branch is missing or the
892/// target branch already exists.
893pub type GitBranchRenameMemStorageFn = fn(
894 gitdir: &Path,
895 old_leaf: &str,
896 new_leaf: &str,
897 ctx: &crate::vcs::CommitContext<'_>,
898) -> Result<(), BackendError>;
899
900/// `Engine::install_schema` dispatch for the git-branch backend: write a
901/// schema package (`(relative-path, bytes)` pairs) onto the workspace's
902/// unified `__MEMSTEAD:schemas/<name>@<version>/` ref and return the
903/// resulting commit sha. Mirrors
904/// `memstead_git_branch::storage_memstead::write_schema_to_memstead_ref`.
905pub type GitBranchWriteSchemaFn = fn(
906 gitdir: &Path,
907 name: &str,
908 version: &str,
909 files: &[(String, Vec<u8>)],
910) -> Result<String, BackendError>;
911
912/// Read one file from a sealed schema package on the workspace's
913/// `__MEMSTEAD:schemas/<name>@<version>/` ref. `Ok(None)` when the
914/// ref, package, or file is absent — absence is a normal state (the
915/// install-provenance stamp only exists for path-sourced installs).
916/// Read-only; the authoring-drift health axis is the consumer.
917pub type GitBranchReadSchemaFileFn = fn(
918 gitdir: &Path,
919 name: &str,
920 version: &str,
921 rel: &str,
922) -> Result<Option<Vec<u8>>, BackendError>;
923
924/// Re-read every schema sealed on one git directory's
925/// `__MEMSTEAD:schemas/` ref (empty when the directory, the ref or the
926/// subtree is absent). Read-only; `Engine::full_refresh` is the
927/// consumer, the warm-server path that makes an out-of-band `memstead
928/// schema install` resolvable without a process restart. It calls this
929/// once per directory of [`crate::workspace::schema_registry_gitdirs`].
930pub type GitBranchReadRefSchemasFn =
931 fn(gitdir: &Path) -> Result<Vec<Arc<memstead_schema::Schema>>, BackendError>;
932
933/// Collect one pinned schema's raw source files (manifest, sealed
934/// format marker, type definitions) from one git directory's
935/// `__MEMSTEAD:schemas/<name>@<version>/` ref — the tree `memstead
936/// schema install` writes on the git-branch backend. `Ok(None)` when
937/// the directory, the ref, or the package is absent. Read-only;
938/// the consumer is the FOLDER-mount export path: a folder mem living
939/// in a mem-repo workspace pins a schema the installer sealed on the
940/// ref, so the archive assembler must read the same store the loader
941/// resolves from, or the mem loads but cannot export. The caller walks
942/// [`crate::workspace::schema_registry_gitdirs`] and takes the first
943/// directory that carries the package.
944pub type GitBranchCollectSchemaSourceFn =
945 fn(
946 gitdir: &Path,
947 schema_ref: &memstead_schema::SchemaRef,
948 ) -> Result<Option<Vec<memstead_schema::SchemaSourceFile>>, BackendError>;
949
950/// Bundle of git-branch-specific op dispatchers. Installed on the
951/// engine at full boot. Each field is one ops-method that previously
952/// lived on the `MemBackend` trait; moving them off the trait keeps
953/// the bytes-level primitive surface clean.
954#[derive(Clone, Copy)]
955pub struct GitBranchOps {
956 pub changes_since: GitBranchChangesSinceFn,
957 pub diff: GitBranchDiffFn,
958 pub branch_reset: GitBranchBranchResetFn,
959 pub fetch: GitBranchFetchFn,
960 pub pull: GitBranchPullFn,
961 pub push: GitBranchPushFn,
962 pub ls_remote: GitBranchLsRemoteFn,
963 pub resolve_ref: GitBranchResolveRefFn,
964 pub is_ancestor: GitBranchIsAncestorFn,
965 pub is_empty_root: GitBranchIsEmptyRootFn,
966 pub merge_base: GitBranchMergeBaseFn,
967 pub merge_disjoint: GitBranchMergeDisjointFn,
968 pub update_ref: GitBranchUpdateRefFn,
969 pub remote_add: GitBranchRemoteAddFn,
970 pub read_tree: GitBranchReadTreeFn,
971 pub export: GitBranchExportFn,
972 pub export_to_bytes: GitBranchExportToBytesFn,
973 pub prune_residue: GitBranchPruneResidueFn,
974 pub prune_config_blob: GitBranchPruneConfigBlobFn,
975 pub branch_namespace_conflicts: GitBranchNamespaceConflictsFn,
976 pub create_branch_at: GitBranchCreateBranchAtFn,
977 pub read_config_at_ref: GitBranchReadConfigAtRefFn,
978 pub rename_mem_storage: GitBranchRenameMemStorageFn,
979 pub write_schema: GitBranchWriteSchemaFn,
980 pub read_schema_file: GitBranchReadSchemaFileFn,
981 pub read_ref_schemas: GitBranchReadRefSchemasFn,
982 pub collect_ref_schema_source: GitBranchCollectSchemaSourceFn,
983}
984
985impl std::fmt::Debug for Engine {
986 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
987 f.debug_struct("Engine")
988 .field(
989 "mems",
990 &self
991 .mounts
992 .iter()
993 .map(|m| m.mount.mem.as_str())
994 .collect::<Vec<_>>(),
995 )
996 .finish()
997 }
998}
999
1000#[cfg(test)]
1001mod in_memory_mem;
1002
1003#[cfg(test)]
1004pub(super) mod test_helpers {
1005 use std::io::Write as _;
1006 use std::path::{Path, PathBuf};
1007
1008 use memstead_schema::SchemaRef;
1009
1010 use crate::backend::MemBackend;
1011 use crate::storage::FilesystemBackend;
1012 use crate::vcs::{Actor, ClientId};
1013 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
1014
1015 use super::{CreateEntityArgs, CreateEntityOutcome, Engine, RelateEntityArgs};
1016
1017 use indexmap::IndexMap;
1018 use tempfile::TempDir;
1019
1020 pub(crate) fn pin(name: &str) -> SchemaRef {
1021 let version = match name {
1022 "default" => semver::Version::new(1, 0, 0),
1023 _ => semver::Version::new(0, 1, 0),
1024 };
1025 SchemaRef::new(name, version)
1026 }
1027
1028 pub(crate) fn folder_mount(mem: &str, path: PathBuf) -> Mount {
1029 Mount {
1030 mem: mem.to_string(),
1031 schema: Some(pin("default")),
1032 storage: MountStorage::Folder { path },
1033 capability: MountCapability::Write,
1034 lifecycle: MountLifecycle::Eager,
1035 cross_linkable: true,
1036 migration_target: None,
1037 }
1038 }
1039
1040 pub(crate) fn in_memory_mount(mem: &str) -> Mount {
1041 Mount {
1042 mem: mem.to_string(),
1043 schema: Some(pin("default")),
1044 storage: MountStorage::InMemory,
1045 capability: MountCapability::Write,
1046 lifecycle: MountLifecycle::Eager,
1047 cross_linkable: true,
1048 migration_target: None,
1049 }
1050 }
1051
1052 pub(crate) fn archive_mount(mem: &str, path: PathBuf) -> Mount {
1053 Mount {
1054 mem: mem.to_string(),
1055 schema: Some(pin("default")),
1056 storage: MountStorage::Archive { path },
1057 capability: MountCapability::ReadOnly,
1058 // Eager, matching every production archive-mount site: these
1059 // tests pin archive READ semantics over a loaded store. A
1060 // `Lazy` value here would defer the load these tests read
1061 // through.
1062 // The lazy behaviour has its own tests in `boot.rs`.
1063 lifecycle: MountLifecycle::Eager,
1064 cross_linkable: false,
1065 migration_target: None,
1066 }
1067 }
1068
1069 /// Build a sealed archive at `tmp/<name>.mem` from
1070 /// `(relative_path, bytes)` pairs and return the path.
1071 pub(crate) fn build_archive(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
1072 let path = tmp.join(format!("{name}.mem"));
1073 let file = std::fs::File::create(&path).unwrap();
1074 let mut writer = zip::ZipWriter::new(file);
1075 let opts = zip::write::SimpleFileOptions::default();
1076 for (rel, bytes) in entries {
1077 writer.start_file(*rel, opts).unwrap();
1078 writer.write_all(bytes).unwrap();
1079 }
1080 writer.finish().unwrap();
1081 path
1082 }
1083
1084 /// Write a schema manifest + minimal type bodies under
1085 /// `<root>/<name>/`. Each type gets a body with a single
1086 /// `body` section and `_default` hierarchy/no-self-loop lists — enough
1087 /// to load and parse markdown that uses that type. Used by tests
1088 /// that need a custom schema with shape or vocabulary constraints.
1089 pub(crate) fn write_schema_files_with_default_type(
1090 root: &Path,
1091 name: &str,
1092 manifest: &str,
1093 types: &[&str],
1094 ) {
1095 const TYPE_BODY: &str = r#"description: t
1096when_to_use: Here
1097sections:
1098 - key: body
1099 heading: Body
1100 required: true
1101 search_weight: 10.0
1102 catch_all: true
1103 write_rules: []
1104metadata_fields: []
1105title_weight: 100.0
1106text_fields:
1107 - body
1108hierarchy_relationship: _default
1109no_self_loop_relationships: []
1110updatable_fields:
1111 - title
1112 - body
1113health_required_fields:
1114 - body
1115staleness_threshold_days: 90
1116write_rules: []
1117"#;
1118 let dir = root.join(name);
1119 std::fs::create_dir_all(dir.join("types")).unwrap();
1120 std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
1121 for type_name in types {
1122 let body = format!("name: {type_name}\n{TYPE_BODY}");
1123 std::fs::write(dir.join("types").join(format!("{type_name}.yaml")), body).unwrap();
1124 }
1125 }
1126
1127 pub(crate) fn empty_create_args(mem: &str, title: &str) -> CreateEntityArgs {
1128 // The
1129 // create path refuses on missing required sections. The
1130 // default `spec` type requires `identity` + `purpose`. Seed
1131 // both with a single space so the test fixture remains a
1132 // valid creation request — every test that uses this helper
1133 // as a fixture builder continues to work, and tests that
1134 // specifically exercise the refusal supply an explicit
1135 // empty-sections payload (see the dedicated refusal tests).
1136 let mut sections = IndexMap::new();
1137 sections.insert("identity".to_string(), "fixture identity body".to_string());
1138 sections.insert("purpose".to_string(), "fixture purpose body".to_string());
1139 CreateEntityArgs {
1140 anchors: Vec::new(),
1141 mem: mem.to_string(),
1142 title: title.to_string(),
1143 entity_type: "spec".to_string(),
1144 sections,
1145 metadata: IndexMap::new(),
1146 relations: Vec::new(),
1147 dry_run: false,
1148 }
1149 }
1150
1151 pub(crate) fn cli_actor() -> (Actor, ClientId) {
1152 (
1153 Actor::Cli,
1154 ClientId {
1155 name: "claude-code".to_string(),
1156 version: "2.1.0".to_string(),
1157 },
1158 )
1159 }
1160
1161 pub(crate) fn engine_with_seed(tmp: &TempDir, title: &str) -> (Engine, CreateEntityOutcome) {
1162 let mem_dir = tmp.path().to_path_buf();
1163 let writer = FilesystemBackend::new(mem_dir.clone());
1164 let mut engine = Engine::from_mounts(vec![(
1165 folder_mount("specs", mem_dir),
1166 Box::new(writer) as Box<dyn MemBackend>,
1167 )])
1168 .unwrap();
1169 let (actor, client) = cli_actor();
1170 let outcome = engine
1171 .create_entity(
1172 empty_create_args("specs", title),
1173 actor,
1174 Some(&client),
1175 None,
1176 )
1177 .unwrap();
1178 (engine, outcome)
1179 }
1180 pub(crate) fn build_demo_engine(tmp: &TempDir) -> Engine {
1181 let mem_dir = tmp.path().to_path_buf();
1182 let writer = FilesystemBackend::new(mem_dir.clone());
1183 let mut engine = Engine::from_mounts(vec![(
1184 folder_mount("specs", mem_dir),
1185 Box::new(writer) as Box<dyn MemBackend>,
1186 )])
1187 .unwrap();
1188 let (actor, client) = cli_actor();
1189 let source = engine
1190 .create_entity(
1191 empty_create_args("specs", "Source One"),
1192 actor,
1193 Some(&client),
1194 None,
1195 )
1196 .unwrap();
1197 let target = engine
1198 .create_entity(
1199 empty_create_args("specs", "Target Two"),
1200 actor,
1201 Some(&client),
1202 None,
1203 )
1204 .unwrap();
1205 engine
1206 .create_entity(
1207 empty_create_args("specs", "Lonely Three"),
1208 actor,
1209 Some(&client),
1210 None,
1211 )
1212 .unwrap();
1213 engine
1214 .relate_entity(
1215 RelateEntityArgs {
1216 source: source.id.clone(),
1217 expected_hash: Some(source.content_hash.clone()),
1218 rel_type: "USES".to_string(),
1219 target: target.id.clone(),
1220 remove: false,
1221 description: None,
1222 dry_run: false,
1223 },
1224 actor,
1225 Some(&client),
1226 None,
1227 )
1228 .unwrap();
1229 engine
1230 }
1231}