Skip to main content

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. The MCP filesystem-mem server
6//! (`memstead_mcp::filesystem_server::FilesystemMcpServer`) and every CLI
7//! lean subcommand reach the
8//! engine through [`Engine::from_workspace_root`] (lean: folder +
9//! archive backends) or `memstead_git_branch::engine_from_workspace_root`
10//! (full: adds git-branch).
11//!
12//! ## Routing
13//!
14//! Each mount holds one mem. Lookup is by mem name: the first
15//! mount whose `mem` field equals the requested name wins. One mount
16//! per mem is enforced — duplicates are a configuration bug, not a
17//! feature, and the constructor rejects them.
18
19use std::cell::OnceCell;
20use std::collections::HashMap;
21use std::path::{Path, PathBuf};
22use std::sync::Arc;
23
24use memstead_schema::Schema;
25
26use crate::backend::{BackendError, MemBackend};
27use crate::graph::LouvainOutput;
28use crate::mem::MemRouterSnapshot;
29use crate::ops::WarningHint;
30#[cfg(not(target_arch = "wasm32"))]
31use crate::search_index::MemIndex;
32use crate::store::Store;
33use crate::workspace::{Mount, WorkspaceSettings};
34
35pub mod apply_commit;
36pub mod archive;
37pub mod boot;
38pub mod check_ops;
39pub mod conflicts;
40pub mod drift;
41pub mod due;
42pub mod error;
43pub mod events;
44pub mod export_html;
45pub mod export_llms_txt;
46#[cfg(feature = "file-watcher")]
47pub mod file_watcher;
48pub mod history;
49pub mod lifecycle;
50pub mod mutation;
51pub mod outcomes;
52pub mod query;
53pub mod review;
54
55pub use archive::FromArchiveBytesError;
56pub use error::{
57    BootError, EngineError, INLINE_LIST_CAP, MissingWikiLink, ReferrerInfo, SchemaSourceDiagnostic,
58    format_inline_list_overflow,
59};
60#[cfg(feature = "tokio")]
61pub use events::DEFAULT_BROADCAST_CAPACITY;
62pub use events::{EventCallback, MemChangedEvent, SubscriptionHandle};
63#[cfg(feature = "file-watcher")]
64pub use file_watcher::{FileWatcherError, MemRepoWatcher, watch_mem_repo};
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, RelateAction,
72    RelateEntityArgs, RelateEntityOutcome, RenameEntityArgs, RenameEntityOutcome, SetSchemaOutcome,
73    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    backend: Box<dyn MemBackend>,
87    /// Last cursor returned by `backend.current_head()`. Seeded in
88    /// [`Engine::from_mounts`]; refreshed by
89    /// [`Engine::reload_if_stale`] after a successful reload.
90    /// `None` means the backend doesn't track a head (folder /
91    /// archive) — drift detection is a no-op for this mount.
92    last_known_head: Option<String>,
93    /// Per-mem `.memstead/config.json` payload — surfaces via
94    /// [`Engine::mem_config_for`] for handlers that need
95    /// `write_guidance` / `extra` (`memstead_health
96    /// { include_config: true }`'s per-mem detail block).
97    ///
98    /// Loaded at construction for folder backends (read from
99    /// `<path>/.memstead/config.json`). Git-branch + archive backends
100    /// carry `None` for now — the read-from-storage-backend path
101    /// lifts in a follow-up session.
102    mem_config: Option<memstead_schema::config::MemConfig>,
103    /// Per-mem authoring-provenance payload read from the archive's
104    /// `.memstead/provenance.json` at construction (via
105    /// [`crate::backend::MemBackend::read_archive_provenance`]). `None`
106    /// when the backend carries no provenance member (a pre-provenance
107    /// archive, or a backend that does not surface one) — surfaced as
108    /// provenance-absent via [`Engine::archive_provenance_for`]. A
109    /// malformed payload is downgraded to `None` rather than failing the
110    /// mount: the member is additive.
111    archive_provenance: Option<memstead_schema::ArchiveProvenance>,
112    /// `true` while a [`MountLifecycle::Lazy`] mount's entities have not
113    /// been loaded into the store — the mount's metadata half (config,
114    /// schema pin, provenance) is resolved at boot, the entity load is
115    /// deferred to the first operation that needs the mem
116    /// ([`Engine::ensure_mems_loaded`]). Always `false` for eager
117    /// mounts, and permanently `false` once the deferred load lands.
118    /// A deferred mem is never absent: it stays on the mount roster
119    /// with its schema resolved, and every read surface either triggers
120    /// the load or reports the state — silence is the one forbidden
121    /// rendering.
122    ///
123    /// [`MountLifecycle::Lazy`]: crate::workspace::MountLifecycle::Lazy
124    deferred: bool,
125}
126
127/// One quarantined mem: the mem-level boot failure that took it out of
128/// service, and the retained mount record `reload` uses to re-attempt
129/// the attach after a repair. The reason code/message are plan-01
130/// typed material — the message's final clause names the repair
131/// command, so the roster entry is actionable as-is.
132#[derive(Debug, Clone)]
133pub struct QuarantinedMem {
134    /// The mount that failed to attach, retained verbatim for reload.
135    pub mount: crate::workspace::Mount,
136    /// Typed code of the underlying failure (e.g. `SCHEMA_NOT_FOUND`,
137    /// `MEM_CONFIG_INCOMPLETE`, `MEM_ERROR`).
138    pub reason_code: String,
139    /// Full message of the underlying failure, repair command
140    /// included.
141    pub reason_message: String,
142}
143
144/// Unified engine. Holds a list of mounted backends and routes
145/// mem-named operations to the right one.
146///
147/// `Send` so the engine can sit behind a `Mutex` (today's pattern
148/// in the MCP server). The trait object's `Send + Sync` bound on
149/// `MemBackend` keeps the inner backends thread-safe; the engine
150/// itself is single-threaded by design (the lazy memos are
151/// `OnceCell`, which is `!Sync`).
152///
153/// `Debug` is hand-written to avoid requiring `Debug` on the
154/// `dyn MemBackend` trait object — backend impls are free to
155/// stay non-`Debug`.
156///
157/// ## Load-on-init
158///
159/// `Engine::from_mounts` walks each backend at construction time
160/// (`list_entities` + `read_entity` + parse) and populates a single
161/// shared [`Store`] with entities and edges from every mount. Each
162/// mount's schema resolves from its own pin (the backend config's
163/// schema, or the mount-record assertion as fallback) through the
164/// `SchemaResolver`, so `schemas` holds genuinely heterogeneous
165/// schemas in a multi-schema workspace. Per-file errors don't fail
166/// construction; they collect into [`Engine::load_errors`] for the
167/// operator to inspect.
168pub struct Engine {
169    mounts: Vec<MountedBackend>,
170    store: Store,
171    schemas: HashMap<String, Arc<Schema>>,
172    /// Workspace-authored schemas loaded from
173    /// `WorkspaceSettings.schemas_dir` at construction. Distinct from
174    /// `schemas` (per-mem, only schemas pinned by a mount): this
175    /// catalogue carries every workspace-loaded schema regardless of
176    /// whether a mem pins it. Surfaced via
177    /// [`Self::workspace_schemas`] for handlers that need to enumerate
178    /// schemas referenced by `mem_create_rules.schemas[]` but not
179    /// pinned by any mem — `memstead_overview` lists them in `## Schemas`
180    /// so an agent sees what could be pinned. Empty when no
181    /// `schemas_dir` was passed.
182    workspace_schemas: Vec<Arc<Schema>>,
183    /// Embedded built-in schemas loaded once at boot from
184    /// `memstead_schema::builtins::load_builtin_schemas()`. The boot path
185    /// uses this catalogue to resolve each mount's schema pin; storing
186    /// it on the engine lets read handlers (MCP's `memstead_schema`,
187    /// `memstead_overview`'s `## Schemas` rendering) surface every built-in
188    /// without re-walking the embedded directory. Schemas declared in
189    /// `workspace_schemas` shadow built-ins on `(name, version)`
190    /// collision — handlers walking both lists must check workspace
191    /// first.
192    builtin_schemas: Vec<Arc<Schema>>,
193    load_errors: Vec<(PathBuf, String)>,
194    /// Lazily-computed Louvain community detection across the
195    /// engine-wide store. Populated on first call to
196    /// [`Self::communities`]; invalidated by
197    /// [`Self::invalidate_communities`] which every mutation method
198    /// calls after a successful write. `OnceCell` is `!Sync`; the
199    /// engine is `Send` (it is moved into a `Mutex` by every consumer)
200    /// but not `Sync`.
201    /// Generation-keyed (flywheel W8/01): the memo carries the store
202    /// generation it was computed at; the invalidation hook clears it
203    /// only when the store has actually moved past that generation —
204    /// which is what makes a rolled-back batch (store snapshot
205    /// restored, generation restored with it) keep serving the memo
206    /// its state was computed from, and makes it impossible for the
207    /// rolled-back interim state to be served as fresh.
208    community_memo: OnceCell<(DerivedKey, LouvainOutput)>,
209    /// Grounded-labelling memo — one `MemLabelling` per mem whose
210    /// schema declares `relationships.labelling`, computed on first
211    /// access and invalidated exactly where the community memo is
212    /// (the reset lives inside [`Self::invalidate_communities`], so
213    /// every mutation site, drift reload, quarantine attach/detach
214    /// and apply-commit invalidate both without a second call).
215    /// Generation-keyed like `community_memo`.
216    labelling_memo: OnceCell<(
217        DerivedKey,
218        HashMap<String, crate::ops::labelling::MemLabelling>,
219    )>,
220    /// Lazily-computed per-mem search index map. Built on first call
221    /// to [`Self::search_indexes`] via [`build_all`]; invalidated by
222    /// [`Self::invalidate_search_indexes`] alongside the community
223    /// cache so every mutation triggers a fresh build on the next
224    /// search. Absent on `wasm32` targets — search lives behind the
225    /// bridge (see `EngineError::SearchUnavailable`).
226    #[cfg(not(target_arch = "wasm32"))]
227    /// Generation-keyed like `community_memo`.
228    search_indexes_memo: OnceCell<(DerivedKey, HashMap<String, MemIndex>)>,
229    /// The second half of [`DerivedKey`]: bumped whenever the
230    /// `schemas` map changes (schema switch, mount register/remove).
231    /// Both derived structures depend on schemas as well as the store
232    /// — community weights and the index field set come from the
233    /// pinned schema — so a schema change must invalidate them even
234    /// though the STORE generation did not move (the schema-switch
235    /// staleness the whole-map drop used to mask).
236    schemas_epoch: u64,
237    /// Workspace-level operator policy — mem create/delete rules,
238    /// cross-mem link permissions. Defaults to empty; populated via
239    /// [`Self::set_settings`] when [`Self::from_workspace_root`] (or
240    /// the full counterpart) reads `.memstead/workspace.toml`. Surfaced
241    /// read-only via [`Self::settings`] for MCP handlers and other
242    /// consumers.
243    settings: WorkspaceSettings,
244    /// Lazily-compiled [`crate::mem_management::CreateRuleSet`] over
245    /// `settings.mem_create_rules`. Built on first
246    /// [`Self::cross_mem_link_allowed`] call that needs synthesis;
247    /// invalidated by [`Self::set_settings`] (so a fresh policy
248    /// re-compiles on the next call). Compilation errors are logged
249    /// and the cache stays empty — synthesis is best-effort, the
250    /// resolver falls back to explicit-policy resolution. Operators
251    /// who want hard validation pre-compile via
252    /// [`crate::mem_management::CreateRuleSet::new`] before passing
253    /// settings.
254    create_rule_set_memo: OnceCell<crate::mem_management::CreateRuleSet>,
255    /// Per-mem data-trust origin declared by the embedding deployment
256    /// (e.g. a curated hosted read tier vouching for a read-only mount as
257    /// first-party). A *composition* fact set through
258    /// [`Self::declare_mem_origin`] by the process that owns the engine —
259    /// never persisted with the mem, never derived from mem content, and
260    /// deliberately not reachable over MCP, so a publisher cannot forge
261    /// first-party. Empty by default; [`Self::mem_origin_class`] falls back
262    /// to the writability inference for undeclared mems.
263    declared_origins: HashMap<String, crate::render::OriginClass>,
264    /// Workspace root path — set when the engine boots from a
265    /// workspace store ([`Self::from_workspace_root`] or the full
266    /// counterpart). `None` for tests + ad-hoc consumers that build
267    /// the engine directly from a mount list. Surfaced via
268    /// [`Self::workspace_root`] for handlers that need filesystem
269    /// context (e.g. [`Self::health`]'s outer-repo .gitignore
270    /// check).
271    workspace_root: Option<PathBuf>,
272    /// The mount roster as this engine last read or last wrote it —
273    /// the baseline [`Engine::persist_state`] diffs against so a state
274    /// write publishes THIS engine's changes without republishing its
275    /// whole cached view over whatever a sibling process has since
276    /// registered. Interior mutability because `persist_state` takes
277    /// `&self`; the engine is already `!Sync`.
278    mounts_baseline: std::cell::RefCell<Vec<crate::workspace::Mount>>,
279    /// Typed warnings surfaced during mem load — drift findings
280    /// like [`WarningHint::SuspiciousNestedPrefix`] and
281    /// [`WarningHint::DuplicateSectionHeading`] that the loader
282    /// pipeline collects per entity. Empty for the V1 unified
283    /// engine; the field is in place so handlers and the health
284    /// surface can include them when the loader pipeline grows the
285    /// warning generators.
286    load_warnings: Vec<WarningHint>,
287    /// Mems that failed their mem-level boot step (unresolvable or
288    /// missing schema pin, backend instantiation or read failure) and
289    /// are quarantined instead of failing the whole workspace —
290    /// degrade, never disappear. A quarantined mem serves NOTHING:
291    /// operations naming it refuse with the typed `MEM_QUARANTINED`
292    /// code carrying the underlying reason (quarantine is not
293    /// tolerance — no partial data from a broken mem). The retained
294    /// [`Mount`] record lets `reload` re-attempt the attach after a
295    /// repair, without a process restart. Surfaced on overview and
296    /// health as the quarantine roster.
297    quarantined: Vec<QuarantinedMem>,
298    /// Workspace-level boot diagnosis carried by a diagnostic-shell
299    /// engine ([`Engine::diagnostic_shell`]): the typed reason the
300    /// REAL workspace could not boot at all (e.g. an unparseable
301    /// workspace store). `None` on every ordinarily booted engine.
302    /// Surfaced on overview and health so a session over a wholly
303    /// unbootable workspace can always ask WHY the graph is gone.
304    boot_diagnosis: Option<(String, String)>,
305    /// Pipeline configs (Medium / Facet / Projection / Ingest) loaded
306    /// from the workspace store at boot. Empty for engines built via
307    /// `from_mounts*` (tests, in-memory consumers) and for any workspace
308    /// that declares no pipelines; the workspace-root boot paths
309    /// (`from_workspace_root` and the full counterpart) populate it via
310    /// [`crate::pipeline_store::load_pipeline_configs`]. Read-only
311    /// runtime surface — exposed through [`Self::pipeline_configs`]; the
312    /// engine neither runs nor schedules pipelines (the ingest skill and
313    /// future consumers do).
314    pipeline_configs: crate::pipeline_store::BindingConfigs,
315    /// Runtime snapshot of writable / visible mems. Derived from
316    /// the mount list at construction: writable mounts
317    /// (`MountCapability::Write`) register via `add_writable` with
318    /// the storage's directory path (folder → `path`, git-branch →
319    /// None, archive shouldn't be writable); read-only mounts
320    /// register via `add_writable` (folder/git-branch) or
321    /// `add_read_only` (archive). Used by MCP handlers that need the
322    /// writable/visible roster + per-mem origin (`memstead_health
323    /// include_config: true`, `memstead_overview`'s mem list,
324    /// `memstead_mem_create`'s collision check).
325    ///
326    /// Wrapped in `Arc` so the COW-snapshot discipline — clone the
327    /// snapshot, mutate the clone, swap the `Arc` — keeps writers
328    /// and concurrent readers from contending on the live mount
329    /// list.
330    mem_router: Arc<MemRouterSnapshot>,
331    /// Backend factory — function pointer used by
332    /// [`crate::mem_management::create_mem`] (and future runtime
333    /// mount-add paths) to materialise a [`MemBackend`] from a
334    /// [`Mount`] declaration. Defaults to
335    /// [`crate::workspace_store::instantiate_lean_backend`] so lean
336    /// (folder + archive only) consumers work out of the box. Full
337    /// consumers swap in `memstead_git_branch::storage::instantiate_full_backend`
338    /// via [`Self::set_backend_factory`] after constructing the engine —
339    /// `engine_from_workspace_root` does this once at boot. Function
340    /// pointer (not `Box<dyn Fn>`) because the backend factory is
341    /// stateless, `Send + Sync + Copy`, and one less allocation on the
342    /// hot path matters for the multi-mem pattern this engine is
343    /// designed around.
344    backend_factory: BackendFactory,
345    /// Storage discovery for UNMOUNTED mems (flywheel W7/02) — set by
346    /// full boot, `None` in lean/embedded engines (which keep the
347    /// forward-reference mechanic unchanged for unmounted targets).
348    pub(crate) unmounted_storage_prober: Option<UnmountedStorageProber>,
349    /// Git-branch ops bundle — function pointers for the per-mount
350    /// operations whose implementations live in `memstead-git-branch`
351    /// (and therefore can't sit on the `MemBackend` trait without
352    /// inverting the crate dependency). Full boot
353    /// (`memstead_git_branch::engine_from_workspace_root`) installs the
354    /// bundle via [`Self::set_git_branch_ops`]; lean consumers leave
355    /// it `None` and `Engine::changes_since` / `Engine::export_mem`
356    /// fall through to the folder/archive-only branches.
357    git_branch_ops: Option<GitBranchOps>,
358    /// Per-mem subscriber registry for [`MemChangedEvent`]s. Held
359    /// behind `Arc<Mutex<_>>` so [`SubscriptionHandle`]s — which own
360    /// the consumer's view of the subscription lifetime — can call
361    /// back into the registry on `Drop` without a self-reference cycle
362    /// to the engine. The emit path (in `record_self_write`) snapshots
363    /// the per-mem callback list under the lock, releases the lock,
364    /// and then invokes the callbacks — so a callback that re-enters
365    /// the engine for a read does not deadlock against the registry.
366    event_subscribers: Arc<std::sync::Mutex<events::SubscriberRegistry>>,
367    /// Reload-before-operation notices accumulated by
368    /// [`Self::reload_if_stale`] when an operation triggered a mem
369    /// reload. Built at reload time — when the backend's current head
370    /// equals the head we reloaded to, *before* any mutation in the
371    /// same operation commits — so the delta describes only the
372    /// sibling's change, never the engine's own follow-on write. The
373    /// response layer drains them via
374    /// [`Self::take_mem_changed_notices`] and attaches the structured
375    /// `mem_changed` notice to the operation's response. Every entity
376    /// op that can reload drains after; an undrained accumulation would
377    /// leak into the next operation's response, so callers that reload
378    /// must take.
379    pending_mem_changed: Vec<crate::ops::MemChangedNotice>,
380    /// Timestamp source for engine-stamped mutation metadata
381    /// (`created_date` on create, `last_modified` on update/relate/
382    /// rename — every field the schema marks `init_timestamp` /
383    /// `auto_timestamp`). Defaults to the system clock; tests that
384    /// assert over canonical entity bytes pin it via
385    /// [`Self::set_mutation_clock`] so two engines stamp identical
386    /// values. A testability affordance, not a behaviour switch:
387    /// nothing in production swaps the default, and the stamped
388    /// format (second-granularity RFC 3339, see
389    /// `mutation::iso_from_system_time`) is unchanged.
390    mutation_clock: MutationClock,
391    /// The caller-declared role for mutations in this session
392    /// (agent-trust plan 13). Set by the surface before each mutation
393    /// (per-call parameter wins over the surface's session default);
394    /// `Unspecified` records as absence. Session state on the engine
395    /// — the `mutation_clock` precedent — so the role travels into
396    /// every commit context and provenance record without widening
397    /// every mutation signature.
398    current_role: crate::vcs::Role,
399}
400
401/// Clock the engine reads when stamping mutation timestamps. `Arc`'d
402/// closure rather than a trait so a test can pin a constant with one
403/// line: `engine.set_mutation_clock(Arc::new(|| some_time))`.
404pub type MutationClock = Arc<dyn Fn() -> std::time::SystemTime + Send + Sync>;
405
406/// Backend factory function pointer. Both flavours' existing
407/// `instantiate_*_backend` functions match this signature, so the
408/// type alias is what bridges the dependency direction (memstead-base
409/// can't depend on memstead-git-branch) without an extra trait.
410/// Stateless, `Send + Sync + Copy`.
411pub type BackendFactory =
412    fn(&Mount) -> Result<Box<dyn MemBackend>, crate::workspace_store::InstantiateError>;
413
414/// Discovered storage for a mem that has NO mount record — the
415/// unmounted half of flywheel W7/02's write-time cross-mem target
416/// verification. The workspace layer owns the discovery convention
417/// (the mem-repo's branch registry, which memstead-base cannot see
418/// without inverting the crate dependency) and hands back a transient
419/// backend to ask plus the mem's schema pin when its config declares
420/// one, so the cross-schema edge routing can keep its authority
421/// without a mount.
422/// The validity key for derived-structure memos (flywheel W8/01):
423/// the store generation (bumped by every store mutation, carried by
424/// `Store::clone` so batch rollback restores it) plus the schemas
425/// epoch (bumped by every change to the engine's schema map). A memo
426/// is current exactly while both halves still match.
427#[derive(Debug, Clone, Copy, PartialEq, Eq)]
428pub struct DerivedKey {
429    pub store_generation: u64,
430    pub schemas_epoch: u64,
431}
432
433pub struct UnmountedMemStorage {
434    /// Transient backend over the discovered storage. Used for the
435    /// cheap [`MemBackend::entity_exists`] probe and the one-blob
436    /// type read — never registered, never loaded.
437    pub backend: Box<dyn MemBackend>,
438    /// The mem's pinned schema, when its stored config declares one.
439    pub schema: Option<memstead_schema::SchemaRef>,
440}
441
442/// Discovery hook: mem name → its storage, when the workspace layer
443/// can find any (`None` = no discoverable storage; the
444/// forward-reference mechanic governs, exactly as before). Boxed
445/// closure rather than a function pointer because discovery needs the
446/// workspace root and gitdir captured at boot.
447pub type UnmountedStorageProber = Box<dyn Fn(&str) -> Option<UnmountedMemStorage> + Send + Sync>;
448
449/// `Engine::changes_since` dispatch for git-branch mounts.
450///
451/// Signature matches `memstead_git_branch::ops::changes::changes_since` after
452/// adapting the `Store` parameter away (the engine performs enrichment
453/// downstream) and the `head_ref` parameter (`refs/heads/<branch>` is
454/// constructed inside the impl from `branch`).
455pub type GitBranchChangesSinceFn = fn(
456    gitdir: &Path,
457    branch: &str,
458    mem: &str,
459    since: &str,
460    rename_similarity: f32,
461) -> Result<crate::ops::BackendChanges, BackendError>;
462
463/// `Engine::export_mem` dispatch for git-branch mounts.
464///
465/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch`.
466pub type GitBranchExportFn = fn(
467    gitdir: &Path,
468    branch: &str,
469    mem: &str,
470    config: &memstead_schema::MemConfig,
471    output_path: &Path,
472    workspace_root: Option<&Path>,
473    workspace_schemas_dir: Option<&Path>,
474    // Engine-sourced authoring-provenance payload bytes (from the mount's
475    // `read_provenance` log) to embed at `.memstead/provenance.json`.
476    // `None` when the mem carried no noted mutations.
477    provenance_bytes: Option<&[u8]>,
478    // Engine-sourced anchors sidecar bytes (from the mount's
479    // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
480    // when the mem carried no anchors. The engine reads the branch tip; the
481    // hook only embeds, keeping git tree-walking out of the fn-pointer.
482    anchors_bytes: Option<&[u8]>,
483) -> Result<crate::ops::MemExportResult, BackendError>;
484
485/// `Engine::export_mem_to_bytes` dispatch for git-branch mounts.
486///
487/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch_to_bytes`.
488/// Symmetric to `GitBranchExportFn`: same inputs minus the output path,
489/// returns archive bytes plus metadata instead of writing to disk.
490pub type GitBranchExportToBytesFn = fn(
491    gitdir: &Path,
492    branch: &str,
493    mem: &str,
494    config: &memstead_schema::MemConfig,
495    workspace_root: Option<&Path>,
496    workspace_schemas_dir: Option<&Path>,
497    // Pre-built authoring-provenance payload bytes the engine sourced from
498    // the mount's `read_provenance` log, to embed at
499    // `.memstead/provenance.json`. `None` when the mem carried no noted
500    // mutations. The engine sources it (it holds the backend); the hook
501    // only embeds, keeping git history-walking out of the fn-pointer.
502    provenance_bytes: Option<&[u8]>,
503    // Engine-sourced anchors sidecar bytes (from the mount's
504    // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
505    // when the mem carried no anchors. Symmetric with `provenance_bytes`:
506    // the engine reads the branch tip, the hook only embeds.
507    anchors_bytes: Option<&[u8]>,
508) -> Result<crate::ops::MemExportBytes, BackendError>;
509
510/// `Engine::diff` dispatch for git-branch mounts. Walks the two refs
511/// inside the workspace's mem-repo gitdir, produces a per-entity
512/// [`crate::ops::Diff`]. Refs are arbitrary `gix::rev_parse_single`
513/// inputs — branch names, commit SHAs, tag names. Resolves each
514/// independently so cross-branch (cross-mem) diffs work uniformly.
515/// `branch` is the mount's declared branch; a bare `HEAD` token in
516/// either ref re-anchors onto it.
517pub type GitBranchDiffFn = fn(
518    gitdir: &Path,
519    branch: &str,
520    mem: &str,
521    ref_a: &str,
522    ref_b: &str,
523    config: &crate::ops::DiffConfig,
524) -> Result<crate::ops::Diff, BackendError>;
525
526/// `Engine::fetch` dispatch for git-branch mounts.
527pub type GitBranchFetchFn = fn(
528    gitdir: &Path,
529    remote: &str,
530    refspecs: &[String],
531) -> Result<crate::ops::FetchOutcome, BackendError>;
532
533/// Read every `.md` blob at `ref_name` in `gitdir`, returning
534/// `(relative_path, utf8_content)` pairs. Skips `.memstead/` engine-internal
535/// entries and non-blob nodes. Used by the pre-merge schema-validation
536/// pass `Engine::pull` and `Engine::push` run before they advance the
537/// branch pointer / push to the remote.
538pub type GitBranchReadTreeFn =
539    fn(gitdir: &Path, ref_name: &str) -> Result<Vec<(String, String)>, BackendError>;
540
541/// `Engine::pull` dispatch for git-branch mounts. `branch` is the
542/// mount's declared branch — the single source of truth for both the
543/// local ref and the remote-tracking ref; `mem` labels the outcome
544/// only.
545pub type GitBranchPullFn = fn(
546    gitdir: &Path,
547    remote: &str,
548    branch: &str,
549    mem: &str,
550) -> Result<crate::ops::PullOutcome, BackendError>;
551
552/// `Engine::push` dispatch for git-branch mounts. `branch` is the
553/// mount's declared branch (see [`GitBranchPullFn`]); `mem` labels
554/// the outcome only.
555pub type GitBranchPushFn = fn(
556    gitdir: &Path,
557    remote: &str,
558    branch: &str,
559    mem: &str,
560    force: bool,
561) -> Result<crate::ops::PushOutcome, BackendError>;
562
563/// `Engine::remote_add` dispatch — configures a named remote on the
564/// mem-repo gitdir (upsert: add, or set-url when it already exists).
565pub type GitBranchRemoteAddFn =
566    fn(gitdir: &Path, name: &str, url: &str) -> Result<crate::ops::RemoteAddOutcome, BackendError>;
567
568/// `Engine::branch_reset` dispatch for git-branch mounts. Returns the
569/// outcome on success; surfaces `BackendError::Other` carrying an
570/// in-band marker (`UNKNOWN_REF:<raw>` or
571/// `PUSHED_COMMITS_PROTECTED:<sha,sha,...>`) the engine layer
572/// un-marshals into typed `EngineError`s.
573pub type GitBranchBranchResetFn = fn(
574    gitdir: &Path,
575    branch: &str,
576    target_sha: &str,
577    expected_head: Option<&str>,
578) -> Result<crate::ops::BranchResetOutcome, BackendError>;
579
580/// Residue-prune dispatch for git-branch mounts.
581/// The `create_mem` orchestrator calls this when
582/// `RecoveryAction::ForceOverwrite` is selected against pre-existing
583/// storage residue. Drops `refs/heads/<branch_full_path>` and the
584/// `__MEMSTEAD:mems/<branch_full_path>/config.json` blob in one
585/// ref-edit transaction (the same call the
586/// `MemBackend::delete_artifacts` impl wraps for delete-files
587/// flows). Surfaces as a function pointer so `memstead-engine` can
588/// drive a prune against an unmounted gitdir without depending on
589/// `memstead-git-branch`.
590pub type GitBranchPruneResidueFn =
591    fn(gitdir: &Path, branch_full_path: &str) -> Result<(), BackendError>;
592
593/// `rename_mem` dispatch for the git-branch backend: move the mem's
594/// content branch `refs/heads/<old>` to `refs/heads/<new>` at the same
595/// tip (history preserved) and relocate the `__MEMSTEAD:mems/<old>/`
596/// config blob to `mems/<new>/`, all in one ref-edit transaction.
597/// Refuses (no mutation) when the source branch is missing or the
598/// target branch already exists.
599pub type GitBranchRenameMemStorageFn =
600    fn(gitdir: &Path, old_leaf: &str, new_leaf: &str) -> Result<(), BackendError>;
601
602/// `Engine::install_schema` dispatch for the git-branch backend: write a
603/// schema package (`(relative-path, bytes)` pairs) onto the workspace's
604/// unified `__MEMSTEAD:schemas/<name>@<version>/` ref and return the
605/// resulting commit sha. Mirrors
606/// `memstead_git_branch::storage_memstead::write_schema_to_memstead_ref`.
607pub type GitBranchWriteSchemaFn = fn(
608    gitdir: &Path,
609    name: &str,
610    version: &str,
611    files: &[(String, Vec<u8>)],
612) -> Result<String, BackendError>;
613
614/// Read one file from a sealed schema package on the workspace's
615/// `__MEMSTEAD:schemas/<name>@<version>/` ref. `Ok(None)` when the
616/// ref, package, or file is absent — absence is a normal state (the
617/// install-provenance stamp only exists for path-sourced installs).
618/// Read-only; the authoring-drift health axis is the consumer.
619pub type GitBranchReadSchemaFileFn = fn(
620    gitdir: &Path,
621    name: &str,
622    version: &str,
623    rel: &str,
624) -> Result<Option<Vec<u8>>, BackendError>;
625
626/// Re-read every schema sealed on the workspace's
627/// `__MEMSTEAD:schemas/` ref (empty when the ref or subtree is
628/// absent). Read-only; `Engine::full_refresh` is the consumer — the
629/// warm-server path that makes an out-of-band `memstead schema
630/// install` resolvable without a process restart.
631pub type GitBranchReadRefSchemasFn =
632    fn(workspace_root: &Path) -> Result<Vec<Arc<memstead_schema::Schema>>, BackendError>;
633
634/// Bundle of git-branch-specific op dispatchers. Installed on the
635/// engine at full boot. Each field is one ops-method that previously
636/// lived on the `MemBackend` trait; moving them off the trait keeps
637/// the bytes-level primitive surface clean.
638#[derive(Clone, Copy)]
639pub struct GitBranchOps {
640    pub changes_since: GitBranchChangesSinceFn,
641    pub diff: GitBranchDiffFn,
642    pub branch_reset: GitBranchBranchResetFn,
643    pub fetch: GitBranchFetchFn,
644    pub pull: GitBranchPullFn,
645    pub push: GitBranchPushFn,
646    pub remote_add: GitBranchRemoteAddFn,
647    pub read_tree: GitBranchReadTreeFn,
648    pub export: GitBranchExportFn,
649    pub export_to_bytes: GitBranchExportToBytesFn,
650    pub prune_residue: GitBranchPruneResidueFn,
651    pub rename_mem_storage: GitBranchRenameMemStorageFn,
652    pub write_schema: GitBranchWriteSchemaFn,
653    pub read_schema_file: GitBranchReadSchemaFileFn,
654    pub read_ref_schemas: GitBranchReadRefSchemasFn,
655}
656
657impl std::fmt::Debug for Engine {
658    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
659        f.debug_struct("Engine")
660            .field(
661                "mems",
662                &self
663                    .mounts
664                    .iter()
665                    .map(|m| m.mount.mem.as_str())
666                    .collect::<Vec<_>>(),
667            )
668            .finish()
669    }
670}
671
672#[cfg(test)]
673mod in_memory_mem;
674
675#[cfg(test)]
676pub(super) mod test_helpers {
677    use std::io::Write as _;
678    use std::path::{Path, PathBuf};
679
680    use memstead_schema::SchemaRef;
681
682    use crate::backend::MemBackend;
683    use crate::storage::FilesystemMemWriter;
684    use crate::vcs::{Actor, ClientId};
685    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
686
687    use super::{CreateEntityArgs, CreateEntityOutcome, Engine, RelateEntityArgs};
688
689    use indexmap::IndexMap;
690    use tempfile::TempDir;
691
692    pub(crate) fn pin(name: &str) -> SchemaRef {
693        let version = match name {
694            "default" => semver::Version::new(1, 0, 0),
695            _ => semver::Version::new(0, 1, 0),
696        };
697        SchemaRef::new(name, version)
698    }
699
700    pub(crate) fn folder_mount(mem: &str, path: PathBuf) -> Mount {
701        Mount {
702            mem: mem.to_string(),
703            schema: Some(pin("default")),
704            storage: MountStorage::Folder { path },
705            capability: MountCapability::Write,
706            lifecycle: MountLifecycle::Eager,
707            cross_linkable: true,
708            migration_target: None,
709        }
710    }
711
712    pub(crate) fn in_memory_mount(mem: &str) -> Mount {
713        Mount {
714            mem: mem.to_string(),
715            schema: Some(pin("default")),
716            storage: MountStorage::InMemory,
717            capability: MountCapability::Write,
718            lifecycle: MountLifecycle::Eager,
719            cross_linkable: true,
720            migration_target: None,
721        }
722    }
723
724    pub(crate) fn archive_mount(mem: &str, path: PathBuf) -> Mount {
725        Mount {
726            mem: mem.to_string(),
727            schema: Some(pin("default")),
728            storage: MountStorage::Archive { path },
729            capability: MountCapability::ReadOnly,
730            // Eager, matching every production archive-mount site: these
731            // tests pin archive READ semantics over a loaded store. The
732            // lifecycle slot became real (flywheel W7/01) — a `Lazy`
733            // value here would defer the load these tests read through.
734            // The lazy behaviour has its own tests in `boot.rs`.
735            lifecycle: MountLifecycle::Eager,
736            cross_linkable: false,
737            migration_target: None,
738        }
739    }
740
741    /// Build a sealed archive at `tmp/<name>.mem` from
742    /// `(relative_path, bytes)` pairs and return the path.
743    pub(crate) fn build_archive(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
744        let path = tmp.join(format!("{name}.mem"));
745        let file = std::fs::File::create(&path).unwrap();
746        let mut writer = zip::ZipWriter::new(file);
747        let opts = zip::write::SimpleFileOptions::default();
748        for (rel, bytes) in entries {
749            writer.start_file(*rel, opts).unwrap();
750            writer.write_all(bytes).unwrap();
751        }
752        writer.finish().unwrap();
753        path
754    }
755
756    /// Write a schema manifest + minimal type bodies under
757    /// `<root>/<name>/`. Each type gets a body with a single
758    /// `body` section and `_default` hierarchy/no-self-loop lists — enough
759    /// to load and parse markdown that uses that type. Used by tests
760    /// that need a custom schema with shape or vocabulary constraints.
761    pub(crate) fn write_schema_files_with_default_type(
762        root: &Path,
763        name: &str,
764        manifest: &str,
765        types: &[&str],
766    ) {
767        const TYPE_BODY: &str = r#"description: t
768when_to_use: Here
769sections:
770  - key: body
771    heading: Body
772    required: true
773    search_weight: 10.0
774    catch_all: true
775    write_rules: []
776metadata_fields: []
777title_weight: 100.0
778text_fields:
779  - body
780hierarchy_relationship: _default
781no_self_loop_relationships: []
782updatable_fields:
783  - title
784  - body
785health_required_fields:
786  - body
787staleness_threshold_days: 90
788write_rules: []
789"#;
790        let dir = root.join(name);
791        std::fs::create_dir_all(dir.join("types")).unwrap();
792        std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
793        for type_name in types {
794            let body = format!("name: {type_name}\n{TYPE_BODY}");
795            std::fs::write(dir.join("types").join(format!("{type_name}.yaml")), body).unwrap();
796        }
797    }
798
799    pub(crate) fn empty_create_args(mem: &str, title: &str) -> CreateEntityArgs {
800        // The
801        // create path refuses on missing required sections. The
802        // default `spec` type requires `identity` + `purpose`. Seed
803        // both with a single space so the test fixture remains a
804        // valid creation request — every test that uses this helper
805        // as a fixture builder continues to work, and tests that
806        // specifically exercise the refusal supply an explicit
807        // empty-sections payload (see the dedicated refusal tests).
808        let mut sections = IndexMap::new();
809        sections.insert("identity".to_string(), "fixture identity body".to_string());
810        sections.insert("purpose".to_string(), "fixture purpose body".to_string());
811        CreateEntityArgs {
812            anchors: Vec::new(),
813            mem: mem.to_string(),
814            title: title.to_string(),
815            entity_type: "spec".to_string(),
816            sections,
817            metadata: IndexMap::new(),
818            relations: Vec::new(),
819            dry_run: false,
820        }
821    }
822
823    pub(crate) fn cli_actor() -> (Actor, ClientId) {
824        (
825            Actor::Cli,
826            ClientId {
827                name: "claude-code".to_string(),
828                version: "2.1.0".to_string(),
829            },
830        )
831    }
832
833    pub(crate) fn engine_with_seed(tmp: &TempDir, title: &str) -> (Engine, CreateEntityOutcome) {
834        let mem_dir = tmp.path().to_path_buf();
835        let writer = FilesystemMemWriter::new(mem_dir.clone());
836        let mut engine = Engine::from_mounts(vec![(
837            folder_mount("specs", mem_dir),
838            Box::new(writer) as Box<dyn MemBackend>,
839        )])
840        .unwrap();
841        let (actor, client) = cli_actor();
842        let outcome = engine
843            .create_entity(
844                empty_create_args("specs", title),
845                actor,
846                Some(&client),
847                None,
848            )
849            .unwrap();
850        (engine, outcome)
851    }
852    pub(crate) fn build_demo_engine(tmp: &TempDir) -> Engine {
853        let mem_dir = tmp.path().to_path_buf();
854        let writer = FilesystemMemWriter::new(mem_dir.clone());
855        let mut engine = Engine::from_mounts(vec![(
856            folder_mount("specs", mem_dir),
857            Box::new(writer) as Box<dyn MemBackend>,
858        )])
859        .unwrap();
860        let (actor, client) = cli_actor();
861        let source = engine
862            .create_entity(
863                empty_create_args("specs", "Source One"),
864                actor,
865                Some(&client),
866                None,
867            )
868            .unwrap();
869        let target = engine
870            .create_entity(
871                empty_create_args("specs", "Target Two"),
872                actor,
873                Some(&client),
874                None,
875            )
876            .unwrap();
877        engine
878            .create_entity(
879                empty_create_args("specs", "Lonely Three"),
880                actor,
881                Some(&client),
882                None,
883            )
884            .unwrap();
885        engine
886            .relate_entity(
887                RelateEntityArgs {
888                    source: source.id.clone(),
889                    expected_hash: Some(source.content_hash.clone()),
890                    rel_type: "USES".to_string(),
891                    target: target.id.clone(),
892                    remove: false,
893                    description: None,
894                    dry_run: false,
895                },
896                actor,
897                Some(&client),
898                None,
899            )
900            .unwrap();
901        engine
902    }
903}