Skip to main content

memstead_base/
backend.rs

1//! `MemBackend` — uniform trait surface over folder, git-branch,
2//! and archive storage.
3//!
4//! Bytes-level: list / read / write / delete / move / commit /
5//! append-provenance / read-provenance. The one-engine architecture
6//! that the workspace-store rebuild produces sits above this trait;
7//! entity-mutation logic, validation, the in-memory store, and the
8//! search index live in one place regardless of which backend serves
9//! a given mount.
10//!
11//! Today's [`crate::storage::MemWriter`] is a write-side subset of
12//! this trait. As each backend gains its `MemBackend` impl the
13//! `MemWriter` references in that backend's call sites collapse
14//! into the unified surface; `MemWriter` stays in
15//! `crate::storage::filesystem` for now as the on-disk write helpers
16//! it embodies are reused by the folder-backend `MemBackend` impl.
17//!
18//! ## Per-backend write semantics
19//!
20//! - **Folder** — writes go to the workspace's mem subdirectory;
21//!   commit is a no-op CAS-token mint (no history).
22//! - **Git-branch** — writes buffer in memory, commit produces a real
23//!   git commit on the per-mem branch with the trailer block.
24//! - **Archive** — writes return [`BackendError::Sealed`] without
25//!   touching disk. Read methods return live content from inside the
26//!   sealed `.mem` zip.
27
28use std::path::{Path, PathBuf};
29
30use crate::provenance::Provenance;
31use crate::storage::{CommitId, MemWriterError};
32use crate::vcs::CommitContext;
33
34/// One row of [`MemBackend::read_all_entities`]: the mem-relative
35/// path and either its bytes or the failure reading them.
36pub type EntityRead = (PathBuf, Result<Vec<u8>, BackendError>);
37
38/// The per-path form of [`MemBackend::read_all_entities`]: list, then
39/// read each path through the backend's own `read_entity`, so the
40/// pending-buffer precedence and snapshot rules of that method hold
41/// row by row. The trait default, and the route a one-walk backend
42/// falls back to while a transaction is staged.
43pub fn read_entities_one_by_one<B: MemBackend + ?Sized>(
44    backend: &B,
45) -> Result<Vec<EntityRead>, BackendError> {
46    let paths = backend.list_entities()?;
47    let mut out = Vec::with_capacity(paths.len());
48    for path in paths {
49        match backend.read_entity(&path) {
50            Ok(Some(bytes)) => out.push((path, Ok(bytes))),
51            // Listed-but-absent: list/read race. Skip silently.
52            Ok(None) => {}
53            Err(e) => out.push((path, Err(e))),
54        }
55    }
56    Ok(out)
57}
58
59/// Mem-backend trait. Implementations live next to the backend's
60/// other code (folder under `crate::storage::filesystem`; git-branch
61/// in the renamed-from-`memstead-git-branch` crate; archive under the
62/// archive read-paths in `crate::entity` once that wiring lands).
63///
64/// Methods are not split into `Read` / `Write` sub-traits because
65/// the engine's mutation paths frequently need both surfaces on the
66/// same backend handle (read current bytes, validate, write new
67/// bytes). Backends that cannot write return [`BackendError::Sealed`]
68/// from the write methods — typed and stable so callers branch on
69/// the discriminant rather than parsing a message string.
70pub trait MemBackend: Send + Sync {
71    /// Mem-relative paths of every entity-bearing file the backend
72    /// holds. Order is not specified; callers that need stable
73    /// ordering sort.
74    fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError>;
75
76    /// Read raw bytes at `rel_path`. `Ok(None)` for a missing path
77    /// (idempotent reads); `Err` for IO or backend-specific failures.
78    fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError>;
79
80    /// Does storage hold an entity at `rel_path`? A pure existence
81    /// probe — the write-time cross-mem target check's primitive
82    /// (flywheel W7/02): callers verifying a reference into a mem that
83    /// is not loaded ask storage directly instead of forcing the mem's
84    /// full load. The answer observes the same pending-buffer
85    /// precedence as [`Self::read_entity`] (a staged upsert exists, a
86    /// staged delete does not).
87    ///
88    /// The default reads the bytes and drops them — correct
89    /// everywhere, cheap nowhere. Backends with a cheaper metadata
90    /// answer override it: the folder backend asks the filesystem
91    /// (`symlink_metadata`, no open), the git-branch backend stops at
92    /// the tree entry (`lookup_entry_by_path`, never the blob read —
93    /// the public listing walk reads every blob and is the wrong
94    /// primitive for this question).
95    fn entity_exists(&self, rel_path: &Path) -> Result<bool, BackendError> {
96        Ok(self.read_entity(rel_path)?.is_some())
97    }
98
99    /// Every entity-bearing file with its bytes, in one pass — the
100    /// primitive a whole-mem load (boot, reload) asks for. One row per
101    /// listed path: `Ok(bytes)` or the per-path read failure, so a
102    /// caller can carry on past one unreadable entity; a path listed
103    /// but gone by read time is dropped (list/read race). The outer
104    /// `Err` is a listing failure. Order is not specified.
105    ///
106    /// The default walks `list_entities` and reads each path — correct
107    /// everywhere, and on a backend whose per-path read re-resolves
108    /// its snapshot it is quadratic: the git-branch backend's
109    /// `read_entity` opens the repository, peels the ref and inflates
110    /// the root tree on every call, so a 7,500-entity boot inflated a
111    /// 7,500-entry tree 7,500 times (96 % of the measured boot,
112    /// 2026-09-10). Backends with a one-walk answer override it.
113    fn read_all_entities(&self) -> Result<Vec<EntityRead>, BackendError> {
114        read_entities_one_by_one(self)
115    }
116
117    /// Does the storage location this backend names exist at all: the
118    /// branch ref, the folder, the archive file? Distinct from "holds
119    /// no entities": a mount whose branch was never created and a mount
120    /// whose branch is empty both list zero entities, and only this
121    /// probe tells them apart. Boot asks it to raise `MOUNT_UNBACKED`
122    /// with the right reason (`missing_ref` / `missing_path` versus
123    /// `empty`); before it existed, a mount pointing at a branch that
124    /// did not exist sat in the writable roster with zero entities and
125    /// no warning. The default says `true` (in-memory and test
126    /// backends have nothing to be missing).
127    fn storage_present(&self) -> Result<bool, BackendError> {
128        Ok(true)
129    }
130
131    /// Upsert `content` at `rel_path`. Pending until [`Self::commit`].
132    fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError>;
133
134    /// Remove `rel_path`. Idempotent: no-op when the path is already
135    /// absent. Pending until [`Self::commit`].
136    fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError>;
137
138    /// Rename `from` to `to`. Pending until [`Self::commit`]. Errors
139    /// when `to` already exists.
140    fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError>;
141
142    /// Discard every pending (uncommitted) mutation, returning the
143    /// staging buffer to empty *without* producing a commit. The
144    /// transactional escape hatch for stage-then-commit callers:
145    /// the atomic `batch_update` stages each item's write into the
146    /// pending set, and when a later item fails validation it calls
147    /// this to drop the already-staged writes rather than commit a
148    /// half-applied batch. Idempotent — discarding an empty buffer
149    /// is a no-op.
150    ///
151    /// Default impl is a no-op: backends that never stage writes
152    /// (archive / any sealed backend) have no buffer to clear. The
153    /// folder and git-branch backends override to clear their
154    /// pending buffer (the git-branch backend also drops the
155    /// captured parent snapshot, symmetric with what `commit` does
156    /// on success).
157    fn discard_pending(&self) -> Result<(), BackendError> {
158        Ok(())
159    }
160
161    /// Flush pending mutations into a single commit. Returns the
162    /// resulting opaque [`CommitId`]; backends without history
163    /// return a synthetic id (UNIX-nanos + counter, hex) so callers
164    /// always get a non-empty cursor.
165    fn commit(&self, message: &str, ctx: &CommitContext<'_>) -> Result<CommitId, BackendError>;
166
167    /// Commit pending mutations with a parent-ref pinning guard.
168    /// When `expected_parent` is `Some`, the backend MUST refuse the
169    /// commit (`Err(BackendError::ParentMismatch { ... })`) if its
170    /// current head no longer matches the supplied ref — a sibling
171    /// writer advanced the on-disk state between the snapshot the
172    /// caller pinned and now. When `expected_parent` is `None`, the
173    /// call is equivalent to [`Self::commit`].
174    ///
175    /// Used by atomic multi-file mutations (notably the planned
176    /// referrer-rewriting rename) to surface drift mid-operation
177    /// rather than between operations. Backends without history
178    /// (folder, archive) inherit the default impl: they ignore
179    /// `expected_parent` because there's no concept of a parent to
180    /// pin against — drift detection on those mounts is a no-op
181    /// today and stays a no-op here. The git-branch backend
182    /// overrides to check the per-mem branch tip and surfaces
183    /// the mismatch with a typed error the engine layer can map to
184    /// `MEM_RELOADED` / `RENAME_PARTIAL_FAILURE`.
185    ///
186    /// Default impl: ignore `expected_parent` and delegate to
187    /// [`Self::commit`]. Bisect-safe — existing callers using
188    /// `Self::commit` directly are unaffected.
189    fn commit_with_expected_parent(
190        &self,
191        message: &str,
192        ctx: &CommitContext<'_>,
193        _expected_parent: Option<&str>,
194    ) -> Result<CommitId, BackendError> {
195        self.commit(message, ctx)
196    }
197
198    /// Append a [`Provenance`] record to the backend's mutation log.
199    /// Persistence form differs per backend — JSONL line, commit
200    /// trailer, etc. — but the in-memory shape is identical.
201    fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError>;
202
203    /// Read provenance entries since `cursor` (opaque,
204    /// backend-defined: a commit SHA for git-branch, an RFC-3339
205    /// timestamp for folder, ignored for archive). `None` cursor
206    /// means "from the beginning".
207    fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError>;
208
209    /// Opaque cursor pointing at the backend's current state. The
210    /// engine compares against a per-mount cached cursor to detect
211    /// drift — a sibling writer (another `Engine` instance, an
212    /// out-of-band `git pull`, etc.) advancing the on-disk state past
213    /// what the engine last read. Backends without history (folder,
214    /// archive) inherit the default impl returning `Ok(None)`; the
215    /// engine treats `None` as "no drift signal available" and skips
216    /// drift detection for that mount. The git-branch backend
217    /// overrides to return the per-mem branch tip's commit SHA hex;
218    /// the filesystem backend overrides to return the changelog's
219    /// last-line timestamp cursor (folder mems with no changelog yet
220    /// keep `None`). Archive and in-memory backends stay on the
221    /// default.
222    ///
223    /// Returning `Err` is reserved for backend-internal failures
224    /// (refdb hiccup, archive read failure, etc.); the engine logs
225    /// the error and treats it as a transient None — drift detection
226    /// is best-effort and never blocks the read it accompanies.
227    fn current_head(&self) -> Result<Option<String>, BackendError> {
228        Ok(None)
229    }
230
231    /// Read the per-mem `.memstead/config.json` payload, if any.
232    ///
233    /// Returns the raw bytes the backend has for the mem's
234    /// config. The engine parses via
235    /// [`memstead_schema::config::parse_mem_config`] and stores the
236    /// result on the [`crate::Engine::mem_config_for`] accessor.
237    ///
238    /// Default impl returns `Ok(None)` — backends that don't
239    /// surface a config (or haven't yet implemented this primitive)
240    /// inherit and signal "no config available". The engine
241    /// treats `None` the same as a parse failure: `mem_config_for`
242    /// returns `None` for the affected mem, and consumers
243    /// (`memstead_health { include_config: true }`) emit empty
244    /// `writeGuidance` + `extra` blocks for that mem.
245    ///
246    /// Mirrors the pattern of [`Self::current_head`] —
247    /// backend-internal capability with a sensible no-op default.
248    ///
249    /// Implementations:
250    /// - Folder backend reads `<root>/.memstead/config.json`.
251    /// - Archive backend reads `.memstead/config.json` from inside the
252    ///   zip.
253    /// - Git-branch backend reads `__MEMSTEAD:mems/<mem>/config.json`.
254    fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
255        Ok(None)
256    }
257
258    /// Read the optional authoring-provenance payload
259    /// (`.memstead/provenance.json`) the archive carries, if any.
260    ///
261    /// Returns the raw bytes the engine parses into a
262    /// [`memstead_schema::ArchiveProvenance`] and surfaces via
263    /// [`crate::Engine::archive_provenance_for`]. Default impl returns
264    /// `Ok(None)` — a backend with no provenance member (a pre-provenance
265    /// archive, the folder/git-branch backends until their read paths
266    /// lift) inherits and signals "provenance absent". Mirrors
267    /// [`Self::read_mem_config`].
268    fn read_archive_provenance(&self) -> Result<Option<Vec<u8>>, BackendError> {
269        Ok(None)
270    }
271
272    /// Write the per-mem `.memstead/config.json` payload. Symmetric
273    /// counterpart to [`Self::read_mem_config`].
274    ///
275    /// Backends that cannot persist a config (today: archive)
276    /// inherit the default and return [`BackendError::Sealed`]. The
277    /// engine's create / migrate paths branch on the discriminant
278    /// before calling.
279    ///
280    /// Implementations:
281    /// - Folder backend writes `<root>/.memstead/config.json` to disk.
282    /// - Git-branch backend writes
283    ///   `__MEMSTEAD:mems/<mem>/config.json` (workspace-level ref) —
284    ///   its own commit, separate from any per-mem-branch
285    ///   mutation.
286    /// - Archive backend returns [`BackendError::Sealed`] — sealed
287    ///   archives never re-write configs.
288    ///
289    /// Mirrors the symmetry pattern of
290    /// [`Self::read_entity`] / [`Self::write_entity`]: the trait
291    /// surface stays balanced so the engine doesn't branch on
292    /// backend type for write paths.
293    fn write_mem_config(&self, _bytes: &[u8]) -> Result<(), BackendError> {
294        Err(BackendError::Sealed)
295    }
296
297    /// Like [`Self::write_mem_config`] but records `note` (an optional
298    /// agent/operator-supplied provenance reason) on the resulting
299    /// commit body. The default delegates to the note-less form, so
300    /// backends without a commit (folder) simply ignore the note; the
301    /// git-branch backend overrides this to thread `note` into the
302    /// `__MEMSTEAD`-ref commit. Lets `set_mem_version` carry a `--note`
303    /// like the other commit-producing mem-lifecycle operations.
304    fn write_mem_config_with_note(
305        &self,
306        bytes: &[u8],
307        _note: Option<&str>,
308    ) -> Result<(), BackendError> {
309        self.write_mem_config(bytes)
310    }
311
312    /// Compare-and-set the mem config: write `bytes` only if the stored
313    /// config is still byte-identical to `expected`. Returns `false` without
314    /// writing when it is not, so the caller can re-read, re-apply, and retry.
315    ///
316    /// WHY the trait carries this rather than the engine doing read-then-write
317    /// itself: on the git-branch backend the ref update already lands under a
318    /// compare-and-set against the observed tip, so a sibling's commit
319    /// survives. The folder backend had no such protection, and a plain
320    /// `fs::write` between another writer's read and its write is silent loss
321    /// with no history to recover from.
322    /// Closing that needs the check and the write to be one indivisible step,
323    /// which only the backend can arrange.
324    ///
325    /// `expected` of `None` means "write unconditionally" (a mem that has no
326    /// stored config yet). The default implementation delegates to the
327    /// note-carrying write and reports success, which is correct for backends
328    /// whose write is already atomic against concurrent writers.
329    fn write_mem_config_cas(
330        &self,
331        _expected: Option<&[u8]>,
332        bytes: &[u8],
333        note: Option<&str>,
334    ) -> Result<bool, BackendError> {
335        self.write_mem_config_with_note(bytes, note)?;
336        Ok(true)
337    }
338
339    /// Record provenance for a pipeline-config edit (mediums / facets /
340    /// projections / ingests). The canonical pipeline config is a plain
341    /// JSON file under `.memstead/` on the workspace root — it has no
342    /// commit of its own — so backends with a commit timeline mirror the
343    /// edit into their provenance record; the commit is the audit trail,
344    /// the disk file stays the read path.
345    ///
346    /// `edits`: `(config_name, Some(bytes))` upserts the mirrored blob,
347    /// `(config_name, None)` removes it (a rename passes both). `kind`
348    /// is the primitive's plural (`mediums`, `facets`, `projections`,
349    /// `ingests`); `verb` names the operation for the commit subject.
350    ///
351    /// The default is a successful no-op: folder and archive backends
352    /// have no commit timeline, so the note is accepted and dropped —
353    /// the same posture as [`Self::write_mem_config_with_note`]. The
354    /// git-branch backend overrides this to commit the mirror under
355    /// `__MEMSTEAD:pipeline/<kind>/<mem>/<name>.json` with `note` on
356    /// the commit body.
357    fn record_pipeline_edit(
358        &self,
359        _kind: &str,
360        _edits: &[(String, Option<Vec<u8>>)],
361        _note: Option<&str>,
362        _verb: &str,
363    ) -> Result<(), BackendError> {
364        Ok(())
365    }
366
367    /// Read the engine-owned anchors sidecar
368    /// ([`crate::anchor::ANCHOR_SIDECAR_PATH`]) bytes, if any.
369    ///
370    /// The sidecar lives on the mem branch under the `.memstead/`
371    /// umbrella every external reader already filters, so it never
372    /// surfaces as an entity. Returns the raw bytes the engine parses via
373    /// [`crate::anchor::AnchorSidecar::from_bytes`]; `Ok(None)` for a mem
374    /// that has never written anchors.
375    ///
376    /// Default impl returns `Ok(None)` — a backend that does not persist
377    /// anchors (a pre-anchor archive, any read-only mount) inherits and
378    /// signals "no anchors". Mirrors [`Self::read_mem_config`]. The
379    /// git-branch and in-memory backends override to read the sidecar
380    /// from their store (pending-buffer precedence, so a staged sidecar
381    /// write is visible before its commit).
382    fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
383        Ok(None)
384    }
385
386    /// Stage a write of the engine-owned anchors sidecar so it rides the
387    /// **same commit** as the entity mutation that produced it — the
388    /// atomicity guarantee anchors depend on (rename's referrer-rewrite,
389    /// delete's anchor removal, and branch_reset's rewind all move
390    /// entity + anchor state together).
391    ///
392    /// Pending until the next [`Self::commit`] — callers stage the entity
393    /// write, then the sidecar write, then commit once. Backends that
394    /// cannot persist anchors (archive / any sealed backend) inherit the
395    /// default returning [`BackendError::Sealed`]; the engine's write
396    /// path branches on mount capability before calling. The git-branch
397    /// and in-memory backends override to buffer the sidecar under
398    /// [`crate::anchor::ANCHOR_SIDECAR_PATH`] in the same pending set the
399    /// entity write used.
400    fn write_anchors_sidecar(&self, _bytes: &[u8]) -> Result<(), BackendError> {
401        Err(BackendError::Sealed)
402    }
403
404    /// Drop every backend-side artifact for this mem — the
405    /// symmetric counterpart to the writes performed by
406    /// `memstead_mem_create` (entity-seed commit on the per-mem
407    /// branch + [`Self::write_mem_config`] on `__MEMSTEAD`). Called by
408    /// `memstead_mem_delete` orchestration when `delete_files=true` and
409    /// the delete rule matched, to give the backend a chance to
410    /// prune ref-store state the engine alone has the git authority
411    /// to touch.
412    ///
413    /// Idempotent: safe to call on a backend whose artifacts already
414    /// went away (a sibling engine pruned them, the branch was
415    /// deleted manually, etc.). The default impl returns `Ok(())` —
416    /// backends whose on-disk state is fully captured by the mem
417    /// directory (folder, archive) inherit the no-op. The
418    /// orchestrator handles its `remove_dir_all` separately at the
419    /// outer layer.
420    ///
421    /// Implementations:
422    /// - Folder backend keeps the default — its disk state is the
423    ///   mem directory, which the orchestrator rmdirs.
424    /// - Archive backend keeps the default — sealed archives have
425    ///   nothing additional to prune.
426    /// - Git-branch backend deletes `refs/heads/<branch_leaf>` and
427    ///   commits a tree edit on `refs/heads/__MEMSTEAD` that removes
428    ///   `mems/<branch_leaf>/config.json`. `<branch_leaf>` is the
429    ///   mem's full hierarchical path (e.g.
430    ///   `planning/plan-q4-revamp` or the bare `<name>` for flat
431    ///   layouts).
432    fn delete_artifacts(&self) -> Result<(), BackendError> {
433        Ok(())
434    }
435}
436
437/// Errors surfaced by [`MemBackend`].
438///
439/// The `Sealed` variant is the typed read-only signal — backends
440/// that physically cannot write (archive) return it from every
441/// mutating method. Callers (the engine's mutation pipeline) branch
442/// on the discriminant before reaching the backend; a `Sealed`
443/// reaching this layer is a programming error in the upstream
444/// capability check.
445#[derive(Debug, thiserror::Error)]
446pub enum BackendError {
447    /// Re-thrown from the existing [`MemWriterError`] surface so
448    /// folder-backend implementations can lift `MemWriter`
449    /// failures without lossy conversion.
450    #[error(transparent)]
451    MemWriter(#[from] MemWriterError),
452    /// Backend physically rejects writes. Returned by the archive
453    /// backend and any future read-only backend (e.g. registry pin).
454    #[error("backend is sealed (writes rejected)")]
455    Sealed,
456    /// Filesystem IO failure outside the [`MemWriterError`] path.
457    #[error("backend io error: {0}")]
458    Io(#[from] std::io::Error),
459    /// Backend-specific failure not modelled by the variants above.
460    /// Carries an agent-readable message; structured backend errors
461    /// add their own variant.
462    #[error("backend error: {0}")]
463    Other(String),
464    /// Parent-ref pinning guard tripped on
465    /// [`MemBackend::commit_with_expected_parent`] — the backend's
466    /// current head no longer matches the caller's `expected_parent`.
467    /// A sibling writer (another `Engine` instance, an out-of-band
468    /// `git pull`, a manual git operation) advanced the on-disk state
469    /// between the snapshot the caller pinned and now. The engine
470    /// layer maps this into `MEM_RELOADED` /
471    /// `RENAME_PARTIAL_FAILURE` depending on whether other mems
472    /// already committed in the same logical operation. Today only
473    /// the git-branch backend (planned override) produces this
474    /// variant; folder and archive backends inherit the default impl
475    /// of `commit_with_expected_parent` which delegates to `commit`
476    /// without parent checking.
477    #[error(
478        "parent-ref mismatch: expected {expected}, found {actual} — sibling writer advanced the mem"
479    )]
480    ParentMismatch { expected: String, actual: String },
481}