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    /// Upsert `content` at `rel_path`. Pending until [`Self::commit`].
56    fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError>;
57
58    /// Remove `rel_path`. Idempotent: no-op when the path is already
59    /// absent. Pending until [`Self::commit`].
60    fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError>;
61
62    /// Rename `from` to `to`. Pending until [`Self::commit`]. Errors
63    /// when `to` already exists.
64    fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError>;
65
66    /// Discard every pending (uncommitted) mutation, returning the
67    /// staging buffer to empty *without* producing a commit. The
68    /// transactional escape hatch for stage-then-commit callers:
69    /// the atomic `batch_update` stages each item's write into the
70    /// pending set, and when a later item fails validation it calls
71    /// this to drop the already-staged writes rather than commit a
72    /// half-applied batch. Idempotent — discarding an empty buffer
73    /// is a no-op.
74    ///
75    /// Default impl is a no-op: backends that never stage writes
76    /// (archive / any sealed backend) have no buffer to clear. The
77    /// folder and git-branch backends override to clear their
78    /// pending buffer (the git-branch backend also drops the
79    /// captured parent snapshot, symmetric with what `commit` does
80    /// on success).
81    fn discard_pending(&self) -> Result<(), BackendError> {
82        Ok(())
83    }
84
85    /// Flush pending mutations into a single commit. Returns the
86    /// resulting opaque [`CommitId`]; backends without history
87    /// return a synthetic id (UNIX-nanos + counter, hex) so callers
88    /// always get a non-empty cursor.
89    fn commit(&self, message: &str, ctx: &CommitContext<'_>) -> Result<CommitId, BackendError>;
90
91    /// Commit pending mutations with a parent-ref pinning guard.
92    /// When `expected_parent` is `Some`, the backend MUST refuse the
93    /// commit (`Err(BackendError::ParentMismatch { ... })`) if its
94    /// current head no longer matches the supplied ref — a sibling
95    /// writer advanced the on-disk state between the snapshot the
96    /// caller pinned and now. When `expected_parent` is `None`, the
97    /// call is equivalent to [`Self::commit`].
98    ///
99    /// Used by atomic multi-file mutations (notably the planned
100    /// referrer-rewriting rename) to surface drift mid-operation
101    /// rather than between operations. Backends without history
102    /// (folder, archive) inherit the default impl: they ignore
103    /// `expected_parent` because there's no concept of a parent to
104    /// pin against — drift detection on those mounts is a no-op
105    /// today and stays a no-op here. The git-branch backend
106    /// overrides to check the per-mem branch tip and surfaces
107    /// the mismatch with a typed error the engine layer can map to
108    /// `MEM_RELOADED` / `RENAME_PARTIAL_FAILURE`.
109    ///
110    /// Default impl: ignore `expected_parent` and delegate to
111    /// [`Self::commit`]. Bisect-safe — existing callers using
112    /// `Self::commit` directly are unaffected.
113    fn commit_with_expected_parent(
114        &self,
115        message: &str,
116        ctx: &CommitContext<'_>,
117        _expected_parent: Option<&str>,
118    ) -> Result<CommitId, BackendError> {
119        self.commit(message, ctx)
120    }
121
122    /// Append a [`Provenance`] record to the backend's mutation log.
123    /// Persistence form differs per backend — JSONL line, commit
124    /// trailer, etc. — but the in-memory shape is identical.
125    fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError>;
126
127    /// Read provenance entries since `cursor` (opaque,
128    /// backend-defined: a commit SHA for git-branch, an RFC-3339
129    /// timestamp for folder, ignored for archive). `None` cursor
130    /// means "from the beginning".
131    fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError>;
132
133    /// Opaque cursor pointing at the backend's current state. The
134    /// engine compares against a per-mount cached cursor to detect
135    /// drift — a sibling writer (another `Engine` instance, an
136    /// out-of-band `git pull`, etc.) advancing the on-disk state past
137    /// what the engine last read. Backends without history (folder,
138    /// archive) inherit the default impl returning `Ok(None)`; the
139    /// engine treats `None` as "no drift signal available" and skips
140    /// drift detection for that mount. The git-branch backend
141    /// overrides to return the per-mem branch tip's commit SHA hex.
142    ///
143    /// Returning `Err` is reserved for backend-internal failures
144    /// (refdb hiccup, archive read failure, etc.); the engine logs
145    /// the error and treats it as a transient None — drift detection
146    /// is best-effort and never blocks the read it accompanies.
147    fn current_head(&self) -> Result<Option<String>, BackendError> {
148        Ok(None)
149    }
150
151    /// Read the per-mem `.memstead/config.json` payload, if any.
152    ///
153    /// Returns the raw bytes the backend has for the mem's
154    /// config. The engine parses via
155    /// [`memstead_schema::config::parse_mem_config`] and stores the
156    /// result on the [`crate::Engine::mem_config_for`] accessor.
157    ///
158    /// Default impl returns `Ok(None)` — backends that don't
159    /// surface a config (or haven't yet implemented this primitive)
160    /// inherit and signal "no config available". The engine
161    /// treats `None` the same as a parse failure: `mem_config_for`
162    /// returns `None` for the affected mem, and consumers
163    /// (`memstead_health { include_config: true }`) emit empty
164    /// `writeGuidance` + `extra` blocks for that mem.
165    ///
166    /// Mirrors the pattern of [`Self::current_head`] —
167    /// backend-internal capability with a sensible no-op default.
168    ///
169    /// Implementations:
170    /// - Folder backend reads `<root>/.memstead/config.json`.
171    /// - Archive backend reads `.memstead/config.json` from inside the
172    ///   zip.
173    /// - Git-branch backend reads `__MEMSTEAD:mems/<mem>/config.json`.
174    fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
175        Ok(None)
176    }
177
178    /// Read the optional authoring-provenance payload
179    /// (`.memstead/provenance.json`) the archive carries, if any.
180    ///
181    /// Returns the raw bytes the engine parses into a
182    /// [`memstead_schema::ArchiveProvenance`] and surfaces via
183    /// [`crate::Engine::archive_provenance_for`]. Default impl returns
184    /// `Ok(None)` — a backend with no provenance member (a pre-provenance
185    /// archive, the folder/git-branch backends until their read paths
186    /// lift) inherits and signals "provenance absent". Mirrors
187    /// [`Self::read_mem_config`].
188    fn read_archive_provenance(&self) -> Result<Option<Vec<u8>>, BackendError> {
189        Ok(None)
190    }
191
192    /// Write the per-mem `.memstead/config.json` payload. Symmetric
193    /// counterpart to [`Self::read_mem_config`].
194    ///
195    /// Backends that cannot persist a config (today: archive)
196    /// inherit the default and return [`BackendError::Sealed`]. The
197    /// engine's create / migrate paths branch on the discriminant
198    /// before calling.
199    ///
200    /// Implementations:
201    /// - Folder backend writes `<root>/.memstead/config.json` to disk.
202    /// - Git-branch backend writes
203    ///   `__MEMSTEAD:mems/<mem>/config.json` (workspace-level ref) —
204    ///   its own commit, separate from any per-mem-branch
205    ///   mutation.
206    /// - Archive backend returns [`BackendError::Sealed`] — sealed
207    ///   archives never re-write configs.
208    ///
209    /// Mirrors the symmetry pattern of
210    /// [`Self::read_entity`] / [`Self::write_entity`]: the trait
211    /// surface stays balanced so the engine doesn't branch on
212    /// backend type for write paths.
213    fn write_mem_config(&self, _bytes: &[u8]) -> Result<(), BackendError> {
214        Err(BackendError::Sealed)
215    }
216
217    /// Like [`Self::write_mem_config`] but records `note` (an optional
218    /// agent/operator-supplied provenance reason) on the resulting
219    /// commit body. The default delegates to the note-less form, so
220    /// backends without a commit (folder) simply ignore the note; the
221    /// git-branch backend overrides this to thread `note` into the
222    /// `__MEMSTEAD`-ref commit. Lets `set_mem_version` carry a `--note`
223    /// like the other commit-producing mem-lifecycle operations.
224    fn write_mem_config_with_note(
225        &self,
226        bytes: &[u8],
227        _note: Option<&str>,
228    ) -> Result<(), BackendError> {
229        self.write_mem_config(bytes)
230    }
231
232    /// Drop every backend-side artifact for this mem — the
233    /// symmetric counterpart to the writes performed by
234    /// `memstead_mem_create` (entity-seed commit on the per-mem
235    /// branch + [`Self::write_mem_config`] on `__MEMSTEAD`). Called by
236    /// `memstead_mem_delete` orchestration when `delete_files=true` and
237    /// the delete rule matched, to give the backend a chance to
238    /// prune ref-store state the engine alone has the git authority
239    /// to touch.
240    ///
241    /// Idempotent: safe to call on a backend whose artifacts already
242    /// went away (a sibling engine pruned them, the branch was
243    /// deleted manually, etc.). The default impl returns `Ok(())` —
244    /// backends whose on-disk state is fully captured by the mem
245    /// directory (folder, archive) inherit the no-op. The
246    /// orchestrator handles its `remove_dir_all` separately at the
247    /// outer layer.
248    ///
249    /// Implementations:
250    /// - Folder backend keeps the default — its disk state is the
251    ///   mem directory, which the orchestrator rmdirs.
252    /// - Archive backend keeps the default — sealed archives have
253    ///   nothing additional to prune.
254    /// - Git-branch backend deletes `refs/heads/<branch_leaf>` and
255    ///   commits a tree edit on `refs/heads/__MEMSTEAD` that removes
256    ///   `mems/<branch_leaf>/config.json`. `<branch_leaf>` is the
257    ///   mem's full hierarchical path (e.g.
258    ///   `planning/plan-q4-revamp` or the bare `<name>` for flat
259    ///   layouts).
260    fn delete_artifacts(&self) -> Result<(), BackendError> {
261        Ok(())
262    }
263}
264
265/// Errors surfaced by [`MemBackend`].
266///
267/// The `Sealed` variant is the typed read-only signal — backends
268/// that physically cannot write (archive) return it from every
269/// mutating method. Callers (the engine's mutation pipeline) branch
270/// on the discriminant before reaching the backend; a `Sealed`
271/// reaching this layer is a programming error in the upstream
272/// capability check.
273#[derive(Debug, thiserror::Error)]
274pub enum BackendError {
275    /// Re-thrown from the existing [`MemWriterError`] surface so
276    /// folder-backend implementations can lift `MemWriter`
277    /// failures without lossy conversion.
278    #[error(transparent)]
279    MemWriter(#[from] MemWriterError),
280    /// Backend physically rejects writes. Returned by the archive
281    /// backend and any future read-only backend (e.g. registry pin).
282    #[error("backend is sealed (writes rejected)")]
283    Sealed,
284    /// Filesystem IO failure outside the [`MemWriterError`] path.
285    #[error("backend io error: {0}")]
286    Io(#[from] std::io::Error),
287    /// Backend-specific failure not modelled by the variants above.
288    /// Carries an agent-readable message; structured backend errors
289    /// add their own variant.
290    #[error("backend error: {0}")]
291    Other(String),
292    /// Parent-ref pinning guard tripped on
293    /// [`MemBackend::commit_with_expected_parent`] — the backend's
294    /// current head no longer matches the caller's `expected_parent`.
295    /// A sibling writer (another `Engine` instance, an out-of-band
296    /// `git pull`, a manual git operation) advanced the on-disk state
297    /// between the snapshot the caller pinned and now. The engine
298    /// layer maps this into `MEM_RELOADED` /
299    /// `RENAME_PARTIAL_FAILURE` depending on whether other mems
300    /// already committed in the same logical operation. Today only
301    /// the git-branch backend (planned override) produces this
302    /// variant; folder and archive backends inherit the default impl
303    /// of `commit_with_expected_parent` which delegates to `commit`
304    /// without parent checking.
305    #[error(
306        "parent-ref mismatch: expected {expected}, found {actual} — sibling writer advanced the mem"
307    )]
308    ParentMismatch { expected: String, actual: String },
309}