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