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