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 /// the filesystem backend overrides to return the changelog's
143 /// last-line timestamp cursor (folder mems with no changelog yet
144 /// keep `None`). Archive and in-memory backends stay on the
145 /// default.
146 ///
147 /// Returning `Err` is reserved for backend-internal failures
148 /// (refdb hiccup, archive read failure, etc.); the engine logs
149 /// the error and treats it as a transient None — drift detection
150 /// is best-effort and never blocks the read it accompanies.
151 fn current_head(&self) -> Result<Option<String>, BackendError> {
152 Ok(None)
153 }
154
155 /// Read the per-mem `.memstead/config.json` payload, if any.
156 ///
157 /// Returns the raw bytes the backend has for the mem's
158 /// config. The engine parses via
159 /// [`memstead_schema::config::parse_mem_config`] and stores the
160 /// result on the [`crate::Engine::mem_config_for`] accessor.
161 ///
162 /// Default impl returns `Ok(None)` — backends that don't
163 /// surface a config (or haven't yet implemented this primitive)
164 /// inherit and signal "no config available". The engine
165 /// treats `None` the same as a parse failure: `mem_config_for`
166 /// returns `None` for the affected mem, and consumers
167 /// (`memstead_health { include_config: true }`) emit empty
168 /// `writeGuidance` + `extra` blocks for that mem.
169 ///
170 /// Mirrors the pattern of [`Self::current_head`] —
171 /// backend-internal capability with a sensible no-op default.
172 ///
173 /// Implementations:
174 /// - Folder backend reads `<root>/.memstead/config.json`.
175 /// - Archive backend reads `.memstead/config.json` from inside the
176 /// zip.
177 /// - Git-branch backend reads `__MEMSTEAD:mems/<mem>/config.json`.
178 fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
179 Ok(None)
180 }
181
182 /// Read the optional authoring-provenance payload
183 /// (`.memstead/provenance.json`) the archive carries, if any.
184 ///
185 /// Returns the raw bytes the engine parses into a
186 /// [`memstead_schema::ArchiveProvenance`] and surfaces via
187 /// [`crate::Engine::archive_provenance_for`]. Default impl returns
188 /// `Ok(None)` — a backend with no provenance member (a pre-provenance
189 /// archive, the folder/git-branch backends until their read paths
190 /// lift) inherits and signals "provenance absent". Mirrors
191 /// [`Self::read_mem_config`].
192 fn read_archive_provenance(&self) -> Result<Option<Vec<u8>>, BackendError> {
193 Ok(None)
194 }
195
196 /// Write the per-mem `.memstead/config.json` payload. Symmetric
197 /// counterpart to [`Self::read_mem_config`].
198 ///
199 /// Backends that cannot persist a config (today: archive)
200 /// inherit the default and return [`BackendError::Sealed`]. The
201 /// engine's create / migrate paths branch on the discriminant
202 /// before calling.
203 ///
204 /// Implementations:
205 /// - Folder backend writes `<root>/.memstead/config.json` to disk.
206 /// - Git-branch backend writes
207 /// `__MEMSTEAD:mems/<mem>/config.json` (workspace-level ref) —
208 /// its own commit, separate from any per-mem-branch
209 /// mutation.
210 /// - Archive backend returns [`BackendError::Sealed`] — sealed
211 /// archives never re-write configs.
212 ///
213 /// Mirrors the symmetry pattern of
214 /// [`Self::read_entity`] / [`Self::write_entity`]: the trait
215 /// surface stays balanced so the engine doesn't branch on
216 /// backend type for write paths.
217 fn write_mem_config(&self, _bytes: &[u8]) -> Result<(), BackendError> {
218 Err(BackendError::Sealed)
219 }
220
221 /// Like [`Self::write_mem_config`] but records `note` (an optional
222 /// agent/operator-supplied provenance reason) on the resulting
223 /// commit body. The default delegates to the note-less form, so
224 /// backends without a commit (folder) simply ignore the note; the
225 /// git-branch backend overrides this to thread `note` into the
226 /// `__MEMSTEAD`-ref commit. Lets `set_mem_version` carry a `--note`
227 /// like the other commit-producing mem-lifecycle operations.
228 fn write_mem_config_with_note(
229 &self,
230 bytes: &[u8],
231 _note: Option<&str>,
232 ) -> Result<(), BackendError> {
233 self.write_mem_config(bytes)
234 }
235
236 /// Record provenance for a pipeline-config edit (mediums / facets /
237 /// projections / ingests). The canonical pipeline config is a plain
238 /// JSON file under `.memstead/` on the workspace root — it has no
239 /// commit of its own — so backends with a commit timeline mirror the
240 /// edit into their provenance record; the commit is the audit trail,
241 /// the disk file stays the read path.
242 ///
243 /// `edits`: `(config_name, Some(bytes))` upserts the mirrored blob,
244 /// `(config_name, None)` removes it (a rename passes both). `kind`
245 /// is the primitive's plural (`mediums`, `facets`, `projections`,
246 /// `ingests`); `verb` names the operation for the commit subject.
247 ///
248 /// The default is a successful no-op: folder and archive backends
249 /// have no commit timeline, so the note is accepted and dropped —
250 /// the same posture as [`Self::write_mem_config_with_note`]. The
251 /// git-branch backend overrides this to commit the mirror under
252 /// `__MEMSTEAD:pipeline/<kind>/<mem>/<name>.json` with `note` on
253 /// the commit body.
254 fn record_pipeline_edit(
255 &self,
256 _kind: &str,
257 _edits: &[(String, Option<Vec<u8>>)],
258 _note: Option<&str>,
259 _verb: &str,
260 ) -> Result<(), BackendError> {
261 Ok(())
262 }
263
264 /// Read the engine-owned anchors sidecar
265 /// ([`crate::anchor::ANCHOR_SIDECAR_PATH`]) bytes, if any.
266 ///
267 /// The sidecar lives on the mem branch under the `.memstead/`
268 /// umbrella every external reader already filters, so it never
269 /// surfaces as an entity. Returns the raw bytes the engine parses via
270 /// [`crate::anchor::AnchorSidecar::from_bytes`]; `Ok(None)` for a mem
271 /// that has never written anchors.
272 ///
273 /// Default impl returns `Ok(None)` — a backend that does not persist
274 /// anchors (a pre-anchor archive, any read-only mount) inherits and
275 /// signals "no anchors". Mirrors [`Self::read_mem_config`]. The
276 /// git-branch and in-memory backends override to read the sidecar
277 /// from their store (pending-buffer precedence, so a staged sidecar
278 /// write is visible before its commit).
279 fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
280 Ok(None)
281 }
282
283 /// Stage a write of the engine-owned anchors sidecar so it rides the
284 /// **same commit** as the entity mutation that produced it — the
285 /// atomicity guarantee anchors depend on (rename's referrer-rewrite,
286 /// delete's anchor removal, and branch_reset's rewind all move
287 /// entity + anchor state together).
288 ///
289 /// Pending until the next [`Self::commit`] — callers stage the entity
290 /// write, then the sidecar write, then commit once. Backends that
291 /// cannot persist anchors (archive / any sealed backend) inherit the
292 /// default returning [`BackendError::Sealed`]; the engine's write
293 /// path branches on mount capability before calling. The git-branch
294 /// and in-memory backends override to buffer the sidecar under
295 /// [`crate::anchor::ANCHOR_SIDECAR_PATH`] in the same pending set the
296 /// entity write used.
297 fn write_anchors_sidecar(&self, _bytes: &[u8]) -> Result<(), BackendError> {
298 Err(BackendError::Sealed)
299 }
300
301 /// Drop every backend-side artifact for this mem — the
302 /// symmetric counterpart to the writes performed by
303 /// `memstead_mem_create` (entity-seed commit on the per-mem
304 /// branch + [`Self::write_mem_config`] on `__MEMSTEAD`). Called by
305 /// `memstead_mem_delete` orchestration when `delete_files=true` and
306 /// the delete rule matched, to give the backend a chance to
307 /// prune ref-store state the engine alone has the git authority
308 /// to touch.
309 ///
310 /// Idempotent: safe to call on a backend whose artifacts already
311 /// went away (a sibling engine pruned them, the branch was
312 /// deleted manually, etc.). The default impl returns `Ok(())` —
313 /// backends whose on-disk state is fully captured by the mem
314 /// directory (folder, archive) inherit the no-op. The
315 /// orchestrator handles its `remove_dir_all` separately at the
316 /// outer layer.
317 ///
318 /// Implementations:
319 /// - Folder backend keeps the default — its disk state is the
320 /// mem directory, which the orchestrator rmdirs.
321 /// - Archive backend keeps the default — sealed archives have
322 /// nothing additional to prune.
323 /// - Git-branch backend deletes `refs/heads/<branch_leaf>` and
324 /// commits a tree edit on `refs/heads/__MEMSTEAD` that removes
325 /// `mems/<branch_leaf>/config.json`. `<branch_leaf>` is the
326 /// mem's full hierarchical path (e.g.
327 /// `planning/plan-q4-revamp` or the bare `<name>` for flat
328 /// layouts).
329 fn delete_artifacts(&self) -> Result<(), BackendError> {
330 Ok(())
331 }
332}
333
334/// Errors surfaced by [`MemBackend`].
335///
336/// The `Sealed` variant is the typed read-only signal — backends
337/// that physically cannot write (archive) return it from every
338/// mutating method. Callers (the engine's mutation pipeline) branch
339/// on the discriminant before reaching the backend; a `Sealed`
340/// reaching this layer is a programming error in the upstream
341/// capability check.
342#[derive(Debug, thiserror::Error)]
343pub enum BackendError {
344 /// Re-thrown from the existing [`MemWriterError`] surface so
345 /// folder-backend implementations can lift `MemWriter`
346 /// failures without lossy conversion.
347 #[error(transparent)]
348 MemWriter(#[from] MemWriterError),
349 /// Backend physically rejects writes. Returned by the archive
350 /// backend and any future read-only backend (e.g. registry pin).
351 #[error("backend is sealed (writes rejected)")]
352 Sealed,
353 /// Filesystem IO failure outside the [`MemWriterError`] path.
354 #[error("backend io error: {0}")]
355 Io(#[from] std::io::Error),
356 /// Backend-specific failure not modelled by the variants above.
357 /// Carries an agent-readable message; structured backend errors
358 /// add their own variant.
359 #[error("backend error: {0}")]
360 Other(String),
361 /// Parent-ref pinning guard tripped on
362 /// [`MemBackend::commit_with_expected_parent`] — the backend's
363 /// current head no longer matches the caller's `expected_parent`.
364 /// A sibling writer (another `Engine` instance, an out-of-band
365 /// `git pull`, a manual git operation) advanced the on-disk state
366 /// between the snapshot the caller pinned and now. The engine
367 /// layer maps this into `MEM_RELOADED` /
368 /// `RENAME_PARTIAL_FAILURE` depending on whether other mems
369 /// already committed in the same logical operation. Today only
370 /// the git-branch backend (planned override) produces this
371 /// variant; folder and archive backends inherit the default impl
372 /// of `commit_with_expected_parent` which delegates to `commit`
373 /// without parent checking.
374 #[error(
375 "parent-ref mismatch: expected {expected}, found {actual} — sibling writer advanced the mem"
376 )]
377 ParentMismatch { expected: String, actual: String },
378}