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    /// Typed warnings surfaced during mem load — drift findings
273    /// like [`WarningHint::SuspiciousNestedPrefix`] and
274    /// [`WarningHint::DuplicateSectionHeading`] that the loader
275    /// pipeline collects per entity. Empty for the V1 unified
276    /// engine; the field is in place so handlers and the health
277    /// surface can include them when the loader pipeline grows the
278    /// warning generators.
279    load_warnings: Vec<WarningHint>,
280    /// Mems that failed their mem-level boot step (unresolvable or
281    /// missing schema pin, backend instantiation or read failure) and
282    /// are quarantined instead of failing the whole workspace —
283    /// degrade, never disappear. A quarantined mem serves NOTHING:
284    /// operations naming it refuse with the typed `MEM_QUARANTINED`
285    /// code carrying the underlying reason (quarantine is not
286    /// tolerance — no partial data from a broken mem). The retained
287    /// [`Mount`] record lets `reload` re-attempt the attach after a
288    /// repair, without a process restart. Surfaced on overview and
289    /// health as the quarantine roster.
290    quarantined: Vec<QuarantinedMem>,
291    /// Workspace-level boot diagnosis carried by a diagnostic-shell
292    /// engine ([`Engine::diagnostic_shell`]): the typed reason the
293    /// REAL workspace could not boot at all (e.g. an unparseable
294    /// workspace store). `None` on every ordinarily booted engine.
295    /// Surfaced on overview and health so a session over a wholly
296    /// unbootable workspace can always ask WHY the graph is gone.
297    boot_diagnosis: Option<(String, String)>,
298    /// Pipeline configs (Medium / Facet / Projection / Ingest) loaded
299    /// from the workspace store at boot. Empty for engines built via
300    /// `from_mounts*` (tests, in-memory consumers) and for any workspace
301    /// that declares no pipelines; the workspace-root boot paths
302    /// (`from_workspace_root` and the full counterpart) populate it via
303    /// [`crate::pipeline_store::load_pipeline_configs`]. Read-only
304    /// runtime surface — exposed through [`Self::pipeline_configs`]; the
305    /// engine neither runs nor schedules pipelines (the ingest skill and
306    /// future consumers do).
307    pipeline_configs: crate::pipeline_store::BindingConfigs,
308    /// Runtime snapshot of writable / visible mems. Derived from
309    /// the mount list at construction: writable mounts
310    /// (`MountCapability::Write`) register via `add_writable` with
311    /// the storage's directory path (folder → `path`, git-branch →
312    /// None, archive shouldn't be writable); read-only mounts
313    /// register via `add_writable` (folder/git-branch) or
314    /// `add_read_only` (archive). Used by MCP handlers that need the
315    /// writable/visible roster + per-mem origin (`memstead_health
316    /// include_config: true`, `memstead_overview`'s mem list,
317    /// `memstead_mem_create`'s collision check).
318    ///
319    /// Wrapped in `Arc` so the COW-snapshot discipline — clone the
320    /// snapshot, mutate the clone, swap the `Arc` — keeps writers
321    /// and concurrent readers from contending on the live mount
322    /// list.
323    mem_router: Arc<MemRouterSnapshot>,
324    /// Backend factory — function pointer used by
325    /// [`crate::mem_management::create_mem`] (and future runtime
326    /// mount-add paths) to materialise a [`MemBackend`] from a
327    /// [`Mount`] declaration. Defaults to
328    /// [`crate::workspace_store::instantiate_lean_backend`] so lean
329    /// (folder + archive only) consumers work out of the box. Full
330    /// consumers swap in `memstead_git_branch::storage::instantiate_full_backend`
331    /// via [`Self::set_backend_factory`] after constructing the engine —
332    /// `engine_from_workspace_root` does this once at boot. Function
333    /// pointer (not `Box<dyn Fn>`) because the backend factory is
334    /// stateless, `Send + Sync + Copy`, and one less allocation on the
335    /// hot path matters for the multi-mem pattern this engine is
336    /// designed around.
337    backend_factory: BackendFactory,
338    /// Storage discovery for UNMOUNTED mems (flywheel W7/02) — set by
339    /// full boot, `None` in lean/embedded engines (which keep the
340    /// forward-reference mechanic unchanged for unmounted targets).
341    pub(crate) unmounted_storage_prober: Option<UnmountedStorageProber>,
342    /// Git-branch ops bundle — function pointers for the per-mount
343    /// operations whose implementations live in `memstead-git-branch`
344    /// (and therefore can't sit on the `MemBackend` trait without
345    /// inverting the crate dependency). Full boot
346    /// (`memstead_git_branch::engine_from_workspace_root`) installs the
347    /// bundle via [`Self::set_git_branch_ops`]; lean consumers leave
348    /// it `None` and `Engine::changes_since` / `Engine::export_mem`
349    /// fall through to the folder/archive-only branches.
350    git_branch_ops: Option<GitBranchOps>,
351    /// Per-mem subscriber registry for [`MemChangedEvent`]s. Held
352    /// behind `Arc<Mutex<_>>` so [`SubscriptionHandle`]s — which own
353    /// the consumer's view of the subscription lifetime — can call
354    /// back into the registry on `Drop` without a self-reference cycle
355    /// to the engine. The emit path (in `record_self_write`) snapshots
356    /// the per-mem callback list under the lock, releases the lock,
357    /// and then invokes the callbacks — so a callback that re-enters
358    /// the engine for a read does not deadlock against the registry.
359    event_subscribers: Arc<std::sync::Mutex<events::SubscriberRegistry>>,
360    /// Reload-before-operation notices accumulated by
361    /// [`Self::reload_if_stale`] when an operation triggered a mem
362    /// reload. Built at reload time — when the backend's current head
363    /// equals the head we reloaded to, *before* any mutation in the
364    /// same operation commits — so the delta describes only the
365    /// sibling's change, never the engine's own follow-on write. The
366    /// response layer drains them via
367    /// [`Self::take_mem_changed_notices`] and attaches the structured
368    /// `mem_changed` notice to the operation's response. Every entity
369    /// op that can reload drains after; an undrained accumulation would
370    /// leak into the next operation's response, so callers that reload
371    /// must take.
372    pending_mem_changed: Vec<crate::ops::MemChangedNotice>,
373    /// Timestamp source for engine-stamped mutation metadata
374    /// (`created_date` on create, `last_modified` on update/relate/
375    /// rename — every field the schema marks `init_timestamp` /
376    /// `auto_timestamp`). Defaults to the system clock; tests that
377    /// assert over canonical entity bytes pin it via
378    /// [`Self::set_mutation_clock`] so two engines stamp identical
379    /// values. A testability affordance, not a behaviour switch:
380    /// nothing in production swaps the default, and the stamped
381    /// format (second-granularity RFC 3339, see
382    /// `mutation::iso_from_system_time`) is unchanged.
383    mutation_clock: MutationClock,
384    /// The caller-declared role for mutations in this session
385    /// (agent-trust plan 13). Set by the surface before each mutation
386    /// (per-call parameter wins over the surface's session default);
387    /// `Unspecified` records as absence. Session state on the engine
388    /// — the `mutation_clock` precedent — so the role travels into
389    /// every commit context and provenance record without widening
390    /// every mutation signature.
391    current_role: crate::vcs::Role,
392}
393
394/// Clock the engine reads when stamping mutation timestamps. `Arc`'d
395/// closure rather than a trait so a test can pin a constant with one
396/// line: `engine.set_mutation_clock(Arc::new(|| some_time))`.
397pub type MutationClock = Arc<dyn Fn() -> std::time::SystemTime + Send + Sync>;
398
399/// Backend factory function pointer. Both flavours' existing
400/// `instantiate_*_backend` functions match this signature, so the
401/// type alias is what bridges the dependency direction (memstead-base
402/// can't depend on memstead-git-branch) without an extra trait.
403/// Stateless, `Send + Sync + Copy`.
404pub type BackendFactory =
405    fn(&Mount) -> Result<Box<dyn MemBackend>, crate::workspace_store::InstantiateError>;
406
407/// Discovered storage for a mem that has NO mount record — the
408/// unmounted half of flywheel W7/02's write-time cross-mem target
409/// verification. The workspace layer owns the discovery convention
410/// (the mem-repo's branch registry, which memstead-base cannot see
411/// without inverting the crate dependency) and hands back a transient
412/// backend to ask plus the mem's schema pin when its config declares
413/// one, so the cross-schema edge routing can keep its authority
414/// without a mount.
415/// The validity key for derived-structure memos (flywheel W8/01):
416/// the store generation (bumped by every store mutation, carried by
417/// `Store::clone` so batch rollback restores it) plus the schemas
418/// epoch (bumped by every change to the engine's schema map). A memo
419/// is current exactly while both halves still match.
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421pub struct DerivedKey {
422    pub store_generation: u64,
423    pub schemas_epoch: u64,
424}
425
426pub struct UnmountedMemStorage {
427    /// Transient backend over the discovered storage. Used for the
428    /// cheap [`MemBackend::entity_exists`] probe and the one-blob
429    /// type read — never registered, never loaded.
430    pub backend: Box<dyn MemBackend>,
431    /// The mem's pinned schema, when its stored config declares one.
432    pub schema: Option<memstead_schema::SchemaRef>,
433}
434
435/// Discovery hook: mem name → its storage, when the workspace layer
436/// can find any (`None` = no discoverable storage; the
437/// forward-reference mechanic governs, exactly as before). Boxed
438/// closure rather than a function pointer because discovery needs the
439/// workspace root and gitdir captured at boot.
440pub type UnmountedStorageProber = Box<dyn Fn(&str) -> Option<UnmountedMemStorage> + Send + Sync>;
441
442/// `Engine::changes_since` dispatch for git-branch mounts.
443///
444/// Signature matches `memstead_git_branch::ops::changes::changes_since` after
445/// adapting the `Store` parameter away (the engine performs enrichment
446/// downstream) and the `head_ref` parameter (`refs/heads/<branch>` is
447/// constructed inside the impl from `branch`).
448pub type GitBranchChangesSinceFn = fn(
449    gitdir: &Path,
450    branch: &str,
451    mem: &str,
452    since: &str,
453    rename_similarity: f32,
454) -> Result<crate::ops::BackendChanges, BackendError>;
455
456/// `Engine::export_mem` dispatch for git-branch mounts.
457///
458/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch`.
459pub type GitBranchExportFn = fn(
460    gitdir: &Path,
461    branch: &str,
462    mem: &str,
463    config: &memstead_schema::MemConfig,
464    output_path: &Path,
465    workspace_root: Option<&Path>,
466    workspace_schemas_dir: Option<&Path>,
467    // Engine-sourced authoring-provenance payload bytes (from the mount's
468    // `read_provenance` log) to embed at `.memstead/provenance.json`.
469    // `None` when the mem carried no noted mutations.
470    provenance_bytes: Option<&[u8]>,
471    // Engine-sourced anchors sidecar bytes (from the mount's
472    // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
473    // when the mem carried no anchors. The engine reads the branch tip; the
474    // hook only embeds, keeping git tree-walking out of the fn-pointer.
475    anchors_bytes: Option<&[u8]>,
476) -> Result<crate::ops::MemExportResult, BackendError>;
477
478/// `Engine::export_mem_to_bytes` dispatch for git-branch mounts.
479///
480/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch_to_bytes`.
481/// Symmetric to `GitBranchExportFn`: same inputs minus the output path,
482/// returns archive bytes plus metadata instead of writing to disk.
483pub type GitBranchExportToBytesFn = fn(
484    gitdir: &Path,
485    branch: &str,
486    mem: &str,
487    config: &memstead_schema::MemConfig,
488    workspace_root: Option<&Path>,
489    workspace_schemas_dir: Option<&Path>,
490    // Pre-built authoring-provenance payload bytes the engine sourced from
491    // the mount's `read_provenance` log, to embed at
492    // `.memstead/provenance.json`. `None` when the mem carried no noted
493    // mutations. The engine sources it (it holds the backend); the hook
494    // only embeds, keeping git history-walking out of the fn-pointer.
495    provenance_bytes: Option<&[u8]>,
496    // Engine-sourced anchors sidecar bytes (from the mount's
497    // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
498    // when the mem carried no anchors. Symmetric with `provenance_bytes`:
499    // the engine reads the branch tip, the hook only embeds.
500    anchors_bytes: Option<&[u8]>,
501) -> Result<crate::ops::MemExportBytes, BackendError>;
502
503/// `Engine::diff` dispatch for git-branch mounts. Walks the two refs
504/// inside the workspace's mem-repo gitdir, produces a per-entity
505/// [`crate::ops::Diff`]. Refs are arbitrary `gix::rev_parse_single`
506/// inputs — branch names, commit SHAs, tag names. Resolves each
507/// independently so cross-branch (cross-mem) diffs work uniformly.
508pub type GitBranchDiffFn = fn(
509    gitdir: &Path,
510    mem: &str,
511    ref_a: &str,
512    ref_b: &str,
513    config: &crate::ops::DiffConfig,
514) -> Result<crate::ops::Diff, BackendError>;
515
516/// `Engine::fetch` dispatch for git-branch mounts.
517pub type GitBranchFetchFn = fn(
518    gitdir: &Path,
519    remote: &str,
520    refspecs: &[String],
521) -> Result<crate::ops::FetchOutcome, BackendError>;
522
523/// Read every `.md` blob at `ref_name` in `gitdir`, returning
524/// `(relative_path, utf8_content)` pairs. Skips `.memstead/` engine-internal
525/// entries and non-blob nodes. Used by the pre-merge schema-validation
526/// pass `Engine::pull` and `Engine::push` run before they advance the
527/// branch pointer / push to the remote.
528pub type GitBranchReadTreeFn =
529    fn(gitdir: &Path, ref_name: &str) -> Result<Vec<(String, String)>, BackendError>;
530
531/// `Engine::pull` dispatch for git-branch mounts.
532pub type GitBranchPullFn =
533    fn(gitdir: &Path, remote: &str, mem: &str) -> Result<crate::ops::PullOutcome, BackendError>;
534
535/// `Engine::push` dispatch for git-branch mounts.
536pub type GitBranchPushFn = fn(
537    gitdir: &Path,
538    remote: &str,
539    mem: &str,
540    force: bool,
541) -> Result<crate::ops::PushOutcome, BackendError>;
542
543/// `Engine::remote_add` dispatch — configures a named remote on the
544/// mem-repo gitdir (upsert: add, or set-url when it already exists).
545pub type GitBranchRemoteAddFn =
546    fn(gitdir: &Path, name: &str, url: &str) -> Result<crate::ops::RemoteAddOutcome, BackendError>;
547
548/// `Engine::branch_reset` dispatch for git-branch mounts. Returns the
549/// outcome on success; surfaces `BackendError::Other` carrying an
550/// in-band marker (`UNKNOWN_REF:<raw>` or
551/// `PUSHED_COMMITS_PROTECTED:<sha,sha,...>`) the engine layer
552/// un-marshals into typed `EngineError`s.
553pub type GitBranchBranchResetFn = fn(
554    gitdir: &Path,
555    branch: &str,
556    target_sha: &str,
557    expected_head: Option<&str>,
558) -> Result<crate::ops::BranchResetOutcome, BackendError>;
559
560/// Residue-prune dispatch for git-branch mounts.
561/// The `create_mem` orchestrator calls this when
562/// `RecoveryAction::ForceOverwrite` is selected against pre-existing
563/// storage residue. Drops `refs/heads/<branch_full_path>` and the
564/// `__MEMSTEAD:mems/<branch_full_path>/config.json` blob in one
565/// ref-edit transaction (the same call the
566/// `MemBackend::delete_artifacts` impl wraps for delete-files
567/// flows). Surfaces as a function pointer so `memstead-engine` can
568/// drive a prune against an unmounted gitdir without depending on
569/// `memstead-git-branch`.
570pub type GitBranchPruneResidueFn =
571    fn(gitdir: &Path, branch_full_path: &str) -> Result<(), BackendError>;
572
573/// `rename_mem` dispatch for the git-branch backend: move the mem's
574/// content branch `refs/heads/<old>` to `refs/heads/<new>` at the same
575/// tip (history preserved) and relocate the `__MEMSTEAD:mems/<old>/`
576/// config blob to `mems/<new>/`, all in one ref-edit transaction.
577/// Refuses (no mutation) when the source branch is missing or the
578/// target branch already exists.
579pub type GitBranchRenameMemStorageFn =
580    fn(gitdir: &Path, old_leaf: &str, new_leaf: &str) -> Result<(), BackendError>;
581
582/// `Engine::install_schema` dispatch for the git-branch backend: write a
583/// schema package (`(relative-path, bytes)` pairs) onto the workspace's
584/// unified `__MEMSTEAD:schemas/<name>@<version>/` ref and return the
585/// resulting commit sha. Mirrors
586/// `memstead_git_branch::storage_memstead::write_schema_to_memstead_ref`.
587pub type GitBranchWriteSchemaFn = fn(
588    gitdir: &Path,
589    name: &str,
590    version: &str,
591    files: &[(String, Vec<u8>)],
592) -> Result<String, BackendError>;
593
594/// Read one file from a sealed schema package on the workspace's
595/// `__MEMSTEAD:schemas/<name>@<version>/` ref. `Ok(None)` when the
596/// ref, package, or file is absent — absence is a normal state (the
597/// install-provenance stamp only exists for path-sourced installs).
598/// Read-only; the authoring-drift health axis is the consumer.
599pub type GitBranchReadSchemaFileFn = fn(
600    gitdir: &Path,
601    name: &str,
602    version: &str,
603    rel: &str,
604) -> Result<Option<Vec<u8>>, BackendError>;
605
606/// Re-read every schema sealed on the workspace's
607/// `__MEMSTEAD:schemas/` ref (empty when the ref or subtree is
608/// absent). Read-only; `Engine::full_refresh` is the consumer — the
609/// warm-server path that makes an out-of-band `memstead schema
610/// install` resolvable without a process restart.
611pub type GitBranchReadRefSchemasFn =
612    fn(workspace_root: &Path) -> Result<Vec<Arc<memstead_schema::Schema>>, BackendError>;
613
614/// Bundle of git-branch-specific op dispatchers. Installed on the
615/// engine at full boot. Each field is one ops-method that previously
616/// lived on the `MemBackend` trait; moving them off the trait keeps
617/// the bytes-level primitive surface clean.
618#[derive(Clone, Copy)]
619pub struct GitBranchOps {
620    pub changes_since: GitBranchChangesSinceFn,
621    pub diff: GitBranchDiffFn,
622    pub branch_reset: GitBranchBranchResetFn,
623    pub fetch: GitBranchFetchFn,
624    pub pull: GitBranchPullFn,
625    pub push: GitBranchPushFn,
626    pub remote_add: GitBranchRemoteAddFn,
627    pub read_tree: GitBranchReadTreeFn,
628    pub export: GitBranchExportFn,
629    pub export_to_bytes: GitBranchExportToBytesFn,
630    pub prune_residue: GitBranchPruneResidueFn,
631    pub rename_mem_storage: GitBranchRenameMemStorageFn,
632    pub write_schema: GitBranchWriteSchemaFn,
633    pub read_schema_file: GitBranchReadSchemaFileFn,
634    pub read_ref_schemas: GitBranchReadRefSchemasFn,
635}
636
637impl std::fmt::Debug for Engine {
638    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
639        f.debug_struct("Engine")
640            .field(
641                "mems",
642                &self
643                    .mounts
644                    .iter()
645                    .map(|m| m.mount.mem.as_str())
646                    .collect::<Vec<_>>(),
647            )
648            .finish()
649    }
650}
651
652#[cfg(test)]
653mod in_memory_mem;
654
655#[cfg(test)]
656pub(super) mod test_helpers {
657    use std::io::Write as _;
658    use std::path::{Path, PathBuf};
659
660    use memstead_schema::SchemaRef;
661
662    use crate::backend::MemBackend;
663    use crate::storage::FilesystemMemWriter;
664    use crate::vcs::{Actor, ClientId};
665    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
666
667    use super::{CreateEntityArgs, CreateEntityOutcome, Engine, RelateEntityArgs};
668
669    use indexmap::IndexMap;
670    use tempfile::TempDir;
671
672    pub(crate) fn pin(name: &str) -> SchemaRef {
673        let version = match name {
674            "default" => semver::Version::new(1, 0, 0),
675            _ => semver::Version::new(0, 1, 0),
676        };
677        SchemaRef::new(name, version)
678    }
679
680    pub(crate) fn folder_mount(mem: &str, path: PathBuf) -> Mount {
681        Mount {
682            mem: mem.to_string(),
683            schema: Some(pin("default")),
684            storage: MountStorage::Folder { path },
685            capability: MountCapability::Write,
686            lifecycle: MountLifecycle::Eager,
687            cross_linkable: true,
688            migration_target: None,
689        }
690    }
691
692    pub(crate) fn in_memory_mount(mem: &str) -> Mount {
693        Mount {
694            mem: mem.to_string(),
695            schema: Some(pin("default")),
696            storage: MountStorage::InMemory,
697            capability: MountCapability::Write,
698            lifecycle: MountLifecycle::Eager,
699            cross_linkable: true,
700            migration_target: None,
701        }
702    }
703
704    pub(crate) fn archive_mount(mem: &str, path: PathBuf) -> Mount {
705        Mount {
706            mem: mem.to_string(),
707            schema: Some(pin("default")),
708            storage: MountStorage::Archive { path },
709            capability: MountCapability::ReadOnly,
710            // Eager, matching every production archive-mount site: these
711            // tests pin archive READ semantics over a loaded store. The
712            // lifecycle slot became real (flywheel W7/01) — a `Lazy`
713            // value here would defer the load these tests read through.
714            // The lazy behaviour has its own tests in `boot.rs`.
715            lifecycle: MountLifecycle::Eager,
716            cross_linkable: false,
717            migration_target: None,
718        }
719    }
720
721    /// Build a sealed archive at `tmp/<name>.mem` from
722    /// `(relative_path, bytes)` pairs and return the path.
723    pub(crate) fn build_archive(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
724        let path = tmp.join(format!("{name}.mem"));
725        let file = std::fs::File::create(&path).unwrap();
726        let mut writer = zip::ZipWriter::new(file);
727        let opts = zip::write::SimpleFileOptions::default();
728        for (rel, bytes) in entries {
729            writer.start_file(*rel, opts).unwrap();
730            writer.write_all(bytes).unwrap();
731        }
732        writer.finish().unwrap();
733        path
734    }
735
736    /// Write a schema manifest + minimal type bodies under
737    /// `<root>/<name>/`. Each type gets a body with a single
738    /// `body` section and `_default` hierarchy/no-self-loop lists — enough
739    /// to load and parse markdown that uses that type. Used by tests
740    /// that need a custom schema with shape or vocabulary constraints.
741    pub(crate) fn write_schema_files_with_default_type(
742        root: &Path,
743        name: &str,
744        manifest: &str,
745        types: &[&str],
746    ) {
747        const TYPE_BODY: &str = r#"description: t
748when_to_use: Here
749sections:
750  - key: body
751    heading: Body
752    required: true
753    search_weight: 10.0
754    catch_all: true
755    write_rules: []
756metadata_fields: []
757title_weight: 100.0
758text_fields:
759  - body
760hierarchy_relationship: _default
761no_self_loop_relationships: []
762updatable_fields:
763  - title
764  - body
765health_required_fields:
766  - body
767staleness_threshold_days: 90
768write_rules: []
769"#;
770        let dir = root.join(name);
771        std::fs::create_dir_all(dir.join("types")).unwrap();
772        std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
773        for type_name in types {
774            let body = format!("name: {type_name}\n{TYPE_BODY}");
775            std::fs::write(dir.join("types").join(format!("{type_name}.yaml")), body).unwrap();
776        }
777    }
778
779    pub(crate) fn empty_create_args(mem: &str, title: &str) -> CreateEntityArgs {
780        // The
781        // create path refuses on missing required sections. The
782        // default `spec` type requires `identity` + `purpose`. Seed
783        // both with a single space so the test fixture remains a
784        // valid creation request — every test that uses this helper
785        // as a fixture builder continues to work, and tests that
786        // specifically exercise the refusal supply an explicit
787        // empty-sections payload (see the dedicated refusal tests).
788        let mut sections = IndexMap::new();
789        sections.insert("identity".to_string(), "fixture identity body".to_string());
790        sections.insert("purpose".to_string(), "fixture purpose body".to_string());
791        CreateEntityArgs {
792            anchors: Vec::new(),
793            mem: mem.to_string(),
794            title: title.to_string(),
795            entity_type: "spec".to_string(),
796            sections,
797            metadata: IndexMap::new(),
798            relations: Vec::new(),
799            dry_run: false,
800        }
801    }
802
803    pub(crate) fn cli_actor() -> (Actor, ClientId) {
804        (
805            Actor::Cli,
806            ClientId {
807                name: "claude-code".to_string(),
808                version: "2.1.0".to_string(),
809            },
810        )
811    }
812
813    pub(crate) fn engine_with_seed(tmp: &TempDir, title: &str) -> (Engine, CreateEntityOutcome) {
814        let mem_dir = tmp.path().to_path_buf();
815        let writer = FilesystemMemWriter::new(mem_dir.clone());
816        let mut engine = Engine::from_mounts(vec![(
817            folder_mount("specs", mem_dir),
818            Box::new(writer) as Box<dyn MemBackend>,
819        )])
820        .unwrap();
821        let (actor, client) = cli_actor();
822        let outcome = engine
823            .create_entity(
824                empty_create_args("specs", title),
825                actor,
826                Some(&client),
827                None,
828            )
829            .unwrap();
830        (engine, outcome)
831    }
832    pub(crate) fn build_demo_engine(tmp: &TempDir) -> Engine {
833        let mem_dir = tmp.path().to_path_buf();
834        let writer = FilesystemMemWriter::new(mem_dir.clone());
835        let mut engine = Engine::from_mounts(vec![(
836            folder_mount("specs", mem_dir),
837            Box::new(writer) as Box<dyn MemBackend>,
838        )])
839        .unwrap();
840        let (actor, client) = cli_actor();
841        let source = engine
842            .create_entity(
843                empty_create_args("specs", "Source One"),
844                actor,
845                Some(&client),
846                None,
847            )
848            .unwrap();
849        let target = engine
850            .create_entity(
851                empty_create_args("specs", "Target Two"),
852                actor,
853                Some(&client),
854                None,
855            )
856            .unwrap();
857        engine
858            .create_entity(
859                empty_create_args("specs", "Lonely Three"),
860                actor,
861                Some(&client),
862                None,
863            )
864            .unwrap();
865        engine
866            .relate_entity(
867                RelateEntityArgs {
868                    source: source.id.clone(),
869                    expected_hash: Some(source.content_hash.clone()),
870                    rel_type: "USES".to_string(),
871                    target: target.id.clone(),
872                    remove: false,
873                    description: None,
874                    dry_run: false,
875                },
876                actor,
877                Some(&client),
878                None,
879            )
880            .unwrap();
881        engine
882    }
883}