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/// Mem-backend trait. Implementations live next to the backend's
35/// other code (folder under `crate::storage::filesystem`; git-branch
36/// in the renamed-from-`memstead-git-branch` crate; archive under the
37/// archive read-paths in `crate::entity` once that wiring lands).
38///
39/// Methods are not split into `Read` / `Write` sub-traits because
40/// the engine's mutation paths frequently need both surfaces on the
41/// same backend handle (read current bytes, validate, write new
42/// bytes). Backends that cannot write return [`BackendError::Sealed`]
43/// from the write methods — typed and stable so callers branch on
44/// the discriminant rather than parsing a message string.
45pub trait MemBackend: Send + Sync {
46    /// Mem-relative paths of every entity-bearing file the backend
47    /// holds. Order is not specified; callers that need stable
48    /// ordering sort.
49    fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError>;
50
51    /// Read raw bytes at `rel_path`. `Ok(None)` for a missing path
52    /// (idempotent reads); `Err` for IO or backend-specific failures.
53    fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError>;
54
55    /// Does storage hold an entity at `rel_path`? A pure existence
56    /// probe — the write-time cross-mem target check's primitive
57    /// (flywheel W7/02): callers verifying a reference into a mem that
58    /// is not loaded ask storage directly instead of forcing the mem's
59    /// full load. The answer observes the same pending-buffer
60    /// precedence as [`Self::read_entity`] (a staged upsert exists, a
61    /// staged delete does not).
62    ///
63    /// The default reads the bytes and drops them — correct
64    /// everywhere, cheap nowhere. Backends with a cheaper metadata
65    /// answer override it: the folder backend asks the filesystem
66    /// (`symlink_metadata`, no open), the git-branch backend stops at
67    /// the tree entry (`lookup_entry_by_path`, never the blob read —
68    /// the public listing walk reads every blob and is the wrong
69    /// primitive for this question).
70    fn entity_exists(&self, rel_path: &Path) -> Result<bool, BackendError> {
71        Ok(self.read_entity(rel_path)?.is_some())
72    }
73
74    /// Upsert `content` at `rel_path`. Pending until [`Self::commit`].
75    fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError>;
76
77    /// Remove `rel_path`. Idempotent: no-op when the path is already
78    /// absent. Pending until [`Self::commit`].
79    fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError>;
80
81    /// Rename `from` to `to`. Pending until [`Self::commit`]. Errors
82    /// when `to` already exists.
83    fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError>;
84
85    /// Discard every pending (uncommitted) mutation, returning the
86    /// staging buffer to empty *without* producing a commit. The
87    /// transactional escape hatch for stage-then-commit callers:
88    /// the atomic `batch_update` stages each item's write into the
89    /// pending set, and when a later item fails validation it calls
90    /// this to drop the already-staged writes rather than commit a
91    /// half-applied batch. Idempotent — discarding an empty buffer
92    /// is a no-op.
93    ///
94    /// Default impl is a no-op: backends that never stage writes
95    /// (archive / any sealed backend) have no buffer to clear. The
96    /// folder and git-branch backends override to clear their
97    /// pending buffer (the git-branch backend also drops the
98    /// captured parent snapshot, symmetric with what `commit` does
99    /// on success).
100    fn discard_pending(&self) -> Result<(), BackendError> {
101        Ok(())
102    }
103
104    /// Flush pending mutations into a single commit. Returns the
105    /// resulting opaque [`CommitId`]; backends without history
106    /// return a synthetic id (UNIX-nanos + counter, hex) so callers
107    /// always get a non-empty cursor.
108    fn commit(&self, message: &str, ctx: &CommitContext<'_>) -> Result<CommitId, BackendError>;
109
110    /// Commit pending mutations with a parent-ref pinning guard.
111    /// When `expected_parent` is `Some`, the backend MUST refuse the
112    /// commit (`Err(BackendError::ParentMismatch { ... })`) if its
113    /// current head no longer matches the supplied ref — a sibling
114    /// writer advanced the on-disk state between the snapshot the
115    /// caller pinned and now. When `expected_parent` is `None`, the
116    /// call is equivalent to [`Self::commit`].
117    ///
118    /// Used by atomic multi-file mutations (notably the planned
119    /// referrer-rewriting rename) to surface drift mid-operation
120    /// rather than between operations. Backends without history
121    /// (folder, archive) inherit the default impl: they ignore
122    /// `expected_parent` because there's no concept of a parent to
123    /// pin against — drift detection on those mounts is a no-op
124    /// today and stays a no-op here. The git-branch backend
125    /// overrides to check the per-mem branch tip and surfaces
126    /// the mismatch with a typed error the engine layer can map to
127    /// `MEM_RELOADED` / `RENAME_PARTIAL_FAILURE`.
128    ///
129    /// Default impl: ignore `expected_parent` and delegate to
130    /// [`Self::commit`]. Bisect-safe — existing callers using
131    /// `Self::commit` directly are unaffected.
132    fn commit_with_expected_parent(
133        &self,
134        message: &str,
135        ctx: &CommitContext<'_>,
136        _expected_parent: Option<&str>,
137    ) -> Result<CommitId, BackendError> {
138        self.commit(message, ctx)
139    }
140
141    /// Append a [`Provenance`] record to the backend's mutation log.
142    /// Persistence form differs per backend — JSONL line, commit
143    /// trailer, etc. — but the in-memory shape is identical.
144    fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError>;
145
146    /// Read provenance entries since `cursor` (opaque,
147    /// backend-defined: a commit SHA for git-branch, an RFC-3339
148    /// timestamp for folder, ignored for archive). `None` cursor
149    /// means "from the beginning".
150    fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError>;
151
152    /// Opaque cursor pointing at the backend's current state. The
153    /// engine compares against a per-mount cached cursor to detect
154    /// drift — a sibling writer (another `Engine` instance, an
155    /// out-of-band `git pull`, etc.) advancing the on-disk state past
156    /// what the engine last read. Backends without history (folder,
157    /// archive) inherit the default impl returning `Ok(None)`; the
158    /// engine treats `None` as "no drift signal available" and skips
159    /// drift detection for that mount. The git-branch backend
160    /// overrides to return the per-mem branch tip's commit SHA hex;
161    /// the filesystem backend overrides to return the changelog's
162    /// last-line timestamp cursor (folder mems with no changelog yet
163    /// keep `None`). Archive and in-memory backends stay on the
164    /// default.
165    ///
166    /// Returning `Err` is reserved for backend-internal failures
167    /// (refdb hiccup, archive read failure, etc.); the engine logs
168    /// the error and treats it as a transient None — drift detection
169    /// is best-effort and never blocks the read it accompanies.
170    fn current_head(&self) -> Result<Option<String>, BackendError> {
171        Ok(None)
172    }
173
174    /// Read the per-mem `.memstead/config.json` payload, if any.
175    ///
176    /// Returns the raw bytes the backend has for the mem's
177    /// config. The engine parses via
178    /// [`memstead_schema::config::parse_mem_config`] and stores the
179    /// result on the [`crate::Engine::mem_config_for`] accessor.
180    ///
181    /// Default impl returns `Ok(None)` — backends that don't
182    /// surface a config (or haven't yet implemented this primitive)
183    /// inherit and signal "no config available". The engine
184    /// treats `None` the same as a parse failure: `mem_config_for`
185    /// returns `None` for the affected mem, and consumers
186    /// (`memstead_health { include_config: true }`) emit empty
187    /// `writeGuidance` + `extra` blocks for that mem.
188    ///
189    /// Mirrors the pattern of [`Self::current_head`] —
190    /// backend-internal capability with a sensible no-op default.
191    ///
192    /// Implementations:
193    /// - Folder backend reads `<root>/.memstead/config.json`.
194    /// - Archive backend reads `.memstead/config.json` from inside the
195    ///   zip.
196    /// - Git-branch backend reads `__MEMSTEAD:mems/<mem>/config.json`.
197    fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
198        Ok(None)
199    }
200
201    /// Read the optional authoring-provenance payload
202    /// (`.memstead/provenance.json`) the archive carries, if any.
203    ///
204    /// Returns the raw bytes the engine parses into a
205    /// [`memstead_schema::ArchiveProvenance`] and surfaces via
206    /// [`crate::Engine::archive_provenance_for`]. Default impl returns
207    /// `Ok(None)` — a backend with no provenance member (a pre-provenance
208    /// archive, the folder/git-branch backends until their read paths
209    /// lift) inherits and signals "provenance absent". Mirrors
210    /// [`Self::read_mem_config`].
211    fn read_archive_provenance(&self) -> Result<Option<Vec<u8>>, BackendError> {
212        Ok(None)
213    }
214
215    /// Write the per-mem `.memstead/config.json` payload. Symmetric
216    /// counterpart to [`Self::read_mem_config`].
217    ///
218    /// Backends that cannot persist a config (today: archive)
219    /// inherit the default and return [`BackendError::Sealed`]. The
220    /// engine's create / migrate paths branch on the discriminant
221    /// before calling.
222    ///
223    /// Implementations:
224    /// - Folder backend writes `<root>/.memstead/config.json` to disk.
225    /// - Git-branch backend writes
226    ///   `__MEMSTEAD:mems/<mem>/config.json` (workspace-level ref) —
227    ///   its own commit, separate from any per-mem-branch
228    ///   mutation.
229    /// - Archive backend returns [`BackendError::Sealed`] — sealed
230    ///   archives never re-write configs.
231    ///
232    /// Mirrors the symmetry pattern of
233    /// [`Self::read_entity`] / [`Self::write_entity`]: the trait
234    /// surface stays balanced so the engine doesn't branch on
235    /// backend type for write paths.
236    fn write_mem_config(&self, _bytes: &[u8]) -> Result<(), BackendError> {
237        Err(BackendError::Sealed)
238    }
239
240    /// Like [`Self::write_mem_config`] but records `note` (an optional
241    /// agent/operator-supplied provenance reason) on the resulting
242    /// commit body. The default delegates to the note-less form, so
243    /// backends without a commit (folder) simply ignore the note; the
244    /// git-branch backend overrides this to thread `note` into the
245    /// `__MEMSTEAD`-ref commit. Lets `set_mem_version` carry a `--note`
246    /// like the other commit-producing mem-lifecycle operations.
247    fn write_mem_config_with_note(
248        &self,
249        bytes: &[u8],
250        _note: Option<&str>,
251    ) -> Result<(), BackendError> {
252        self.write_mem_config(bytes)
253    }
254
255    /// Record provenance for a pipeline-config edit (mediums / facets /
256    /// projections / ingests). The canonical pipeline config is a plain
257    /// JSON file under `.memstead/` on the workspace root — it has no
258    /// commit of its own — so backends with a commit timeline mirror the
259    /// edit into their provenance record; the commit is the audit trail,
260    /// the disk file stays the read path.
261    ///
262    /// `edits`: `(config_name, Some(bytes))` upserts the mirrored blob,
263    /// `(config_name, None)` removes it (a rename passes both). `kind`
264    /// is the primitive's plural (`mediums`, `facets`, `projections`,
265    /// `ingests`); `verb` names the operation for the commit subject.
266    ///
267    /// The default is a successful no-op: folder and archive backends
268    /// have no commit timeline, so the note is accepted and dropped —
269    /// the same posture as [`Self::write_mem_config_with_note`]. The
270    /// git-branch backend overrides this to commit the mirror under
271    /// `__MEMSTEAD:pipeline/<kind>/<mem>/<name>.json` with `note` on
272    /// the commit body.
273    fn record_pipeline_edit(
274        &self,
275        _kind: &str,
276        _edits: &[(String, Option<Vec<u8>>)],
277        _note: Option<&str>,
278        _verb: &str,
279    ) -> Result<(), BackendError> {
280        Ok(())
281    }
282
283    /// Read the engine-owned anchors sidecar
284    /// ([`crate::anchor::ANCHOR_SIDECAR_PATH`]) bytes, if any.
285    ///
286    /// The sidecar lives on the mem branch under the `.memstead/`
287    /// umbrella every external reader already filters, so it never
288    /// surfaces as an entity. Returns the raw bytes the engine parses via
289    /// [`crate::anchor::AnchorSidecar::from_bytes`]; `Ok(None)` for a mem
290    /// that has never written anchors.
291    ///
292    /// Default impl returns `Ok(None)` — a backend that does not persist
293    /// anchors (a pre-anchor archive, any read-only mount) inherits and
294    /// signals "no anchors". Mirrors [`Self::read_mem_config`]. The
295    /// git-branch and in-memory backends override to read the sidecar
296    /// from their store (pending-buffer precedence, so a staged sidecar
297    /// write is visible before its commit).
298    fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
299        Ok(None)
300    }
301
302    /// Stage a write of the engine-owned anchors sidecar so it rides the
303    /// **same commit** as the entity mutation that produced it — the
304    /// atomicity guarantee anchors depend on (rename's referrer-rewrite,
305    /// delete's anchor removal, and branch_reset's rewind all move
306    /// entity + anchor state together).
307    ///
308    /// Pending until the next [`Self::commit`] — callers stage the entity
309    /// write, then the sidecar write, then commit once. Backends that
310    /// cannot persist anchors (archive / any sealed backend) inherit the
311    /// default returning [`BackendError::Sealed`]; the engine's write
312    /// path branches on mount capability before calling. The git-branch
313    /// and in-memory backends override to buffer the sidecar under
314    /// [`crate::anchor::ANCHOR_SIDECAR_PATH`] in the same pending set the
315    /// entity write used.
316    fn write_anchors_sidecar(&self, _bytes: &[u8]) -> Result<(), BackendError> {
317        Err(BackendError::Sealed)
318    }
319
320    /// Drop every backend-side artifact for this mem — the
321    /// symmetric counterpart to the writes performed by
322    /// `memstead_mem_create` (entity-seed commit on the per-mem
323    /// branch + [`Self::write_mem_config`] on `__MEMSTEAD`). Called by
324    /// `memstead_mem_delete` orchestration when `delete_files=true` and
325    /// the delete rule matched, to give the backend a chance to
326    /// prune ref-store state the engine alone has the git authority
327    /// to touch.
328    ///
329    /// Idempotent: safe to call on a backend whose artifacts already
330    /// went away (a sibling engine pruned them, the branch was
331    /// deleted manually, etc.). The default impl returns `Ok(())` —
332    /// backends whose on-disk state is fully captured by the mem
333    /// directory (folder, archive) inherit the no-op. The
334    /// orchestrator handles its `remove_dir_all` separately at the
335    /// outer layer.
336    ///
337    /// Implementations:
338    /// - Folder backend keeps the default — its disk state is the
339    ///   mem directory, which the orchestrator rmdirs.
340    /// - Archive backend keeps the default — sealed archives have
341    ///   nothing additional to prune.
342    /// - Git-branch backend deletes `refs/heads/<branch_leaf>` and
343    ///   commits a tree edit on `refs/heads/__MEMSTEAD` that removes
344    ///   `mems/<branch_leaf>/config.json`. `<branch_leaf>` is the
345    ///   mem's full hierarchical path (e.g.
346    ///   `planning/plan-q4-revamp` or the bare `<name>` for flat
347    ///   layouts).
348    fn delete_artifacts(&self) -> Result<(), BackendError> {
349        Ok(())
350    }
351}
352
353/// Errors surfaced by [`MemBackend`].
354///
355/// The `Sealed` variant is the typed read-only signal — backends
356/// that physically cannot write (archive) return it from every
357/// mutating method. Callers (the engine's mutation pipeline) branch
358/// on the discriminant before reaching the backend; a `Sealed`
359/// reaching this layer is a programming error in the upstream
360/// capability check.
361#[derive(Debug, thiserror::Error)]
362pub enum BackendError {
363    /// Re-thrown from the existing [`MemWriterError`] surface so
364    /// folder-backend implementations can lift `MemWriter`
365    /// failures without lossy conversion.
366    #[error(transparent)]
367    MemWriter(#[from] MemWriterError),
368    /// Backend physically rejects writes. Returned by the archive
369    /// backend and any future read-only backend (e.g. registry pin).
370    #[error("backend is sealed (writes rejected)")]
371    Sealed,
372    /// Filesystem IO failure outside the [`MemWriterError`] path.
373    #[error("backend io error: {0}")]
374    Io(#[from] std::io::Error),
375    /// Backend-specific failure not modelled by the variants above.
376    /// Carries an agent-readable message; structured backend errors
377    /// add their own variant.
378    #[error("backend error: {0}")]
379    Other(String),
380    /// Parent-ref pinning guard tripped on
381    /// [`MemBackend::commit_with_expected_parent`] — the backend's
382    /// current head no longer matches the caller's `expected_parent`.
383    /// A sibling writer (another `Engine` instance, an out-of-band
384    /// `git pull`, a manual git operation) advanced the on-disk state
385    /// between the snapshot the caller pinned and now. The engine
386    /// layer maps this into `MEM_RELOADED` /
387    /// `RENAME_PARTIAL_FAILURE` depending on whether other mems
388    /// already committed in the same logical operation. Today only
389    /// the git-branch backend (planned override) produces this
390    /// variant; folder and archive backends inherit the default impl
391    /// of `commit_with_expected_parent` which delegates to `commit`
392    /// without parent checking.
393    #[error(
394        "parent-ref mismatch: expected {expected}, found {actual} — sibling writer advanced the mem"
395    )]
396    ParentMismatch { expected: String, actual: String },
397}