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