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//! This is the one write-side abstraction: the earlier writer
12//! trait (four write methods, its own error type) was folded into it on
13//! 2026-09-11, so a backend implements one trait and raises one error
14//! type, [`BackendError`].
15//!
16//! ## Per-backend write semantics
17//!
18//! - **Folder** — writes buffer in memory; commit lands them in the
19//! mem's directory behind one commit point (contents synced beside
20//! their targets, then a durable commit record, then the moves into
21//! place) and returns a synthetic id (no history). A commit that is
22//! cut off after its commit point is completed by the next load.
23//! - **Git-branch** — writes buffer in memory, commit produces a real
24//! git commit on the per-mem branch with the trailer block.
25//! - **Archive** — writes return [`BackendError::Sealed`] without
26//! touching disk. Read methods return live content from inside the
27//! sealed `.mem` zip.
28
29use std::path::{Path, PathBuf};
30
31use crate::provenance::Provenance;
32use crate::storage::CommitId;
33use crate::vcs::CommitContext;
34
35/// One row of [`MemBackend::read_all_entities`]: the mem-relative
36/// path and either its bytes or the failure reading them.
37pub type EntityRead = (PathBuf, Result<Vec<u8>, BackendError>);
38
39/// The per-path form of [`MemBackend::read_all_entities`]: list, then
40/// read each path through the backend's own `read_entity`, so the
41/// pending-buffer precedence and snapshot rules of that method hold
42/// row by row. The trait default, and the route a one-walk backend
43/// falls back to while a transaction is staged.
44pub fn read_entities_one_by_one<B: MemBackend + ?Sized>(
45 backend: &B,
46) -> Result<Vec<EntityRead>, BackendError> {
47 let paths = backend.list_entities()?;
48 let mut out = Vec::with_capacity(paths.len());
49 for path in paths {
50 match backend.read_entity(&path) {
51 Ok(Some(bytes)) => out.push((path, Ok(bytes))),
52 // Listed-but-absent: list/read race. Skip silently.
53 Ok(None) => {}
54 Err(e) => out.push((path, Err(e))),
55 }
56 }
57 Ok(out)
58}
59
60/// Mem-backend trait. Implementations live next to the backend's
61/// other code (folder under `crate::storage::filesystem`; git-branch
62/// in the renamed-from-`memstead-git-branch` crate; archive under the
63/// archive read-paths in `crate::entity` once that wiring lands).
64///
65/// Methods are not split into `Read` / `Write` sub-traits because
66/// the engine's mutation paths frequently need both surfaces on the
67/// same backend handle (read current bytes, validate, write new
68/// bytes). Backends that cannot write return [`BackendError::Sealed`]
69/// from the write methods — typed and stable so callers branch on
70/// the discriminant rather than parsing a message string.
71pub trait MemBackend: Send + Sync {
72 /// Mem-relative paths of every entity-bearing file the backend
73 /// holds. Order is not specified; callers that need stable
74 /// ordering sort.
75 fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError>;
76
77 /// Read raw bytes at `rel_path`. `Ok(None)` for a missing path
78 /// (idempotent reads); `Err` for IO or backend-specific failures.
79 fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError>;
80
81 /// Does storage hold an entity at `rel_path`? A pure existence
82 /// probe — the write-time cross-mem target check's primitive:
83 /// callers verifying a reference into a mem that
84 /// is not loaded ask storage directly instead of forcing the mem's
85 /// full load. The answer observes the same pending-buffer
86 /// precedence as [`Self::read_entity`] (a staged upsert exists, a
87 /// staged delete does not).
88 ///
89 /// The default reads the bytes and drops them — correct
90 /// everywhere, cheap nowhere. Backends with a cheaper metadata
91 /// answer override it: the folder backend asks the filesystem
92 /// (`symlink_metadata`, no open), the git-branch backend stops at
93 /// the tree entry (`lookup_entry_by_path`, never the blob read —
94 /// the public listing walk reads every blob and is the wrong
95 /// primitive for this question).
96 fn entity_exists(&self, rel_path: &Path) -> Result<bool, BackendError> {
97 Ok(self.read_entity(rel_path)?.is_some())
98 }
99
100 /// Every entity-bearing file with its bytes, in one pass — the
101 /// primitive a whole-mem load (boot, reload) asks for. One row per
102 /// listed path: `Ok(bytes)` or the per-path read failure, so a
103 /// caller can carry on past one unreadable entity; a path listed
104 /// but gone by read time is dropped (list/read race). The outer
105 /// `Err` is a listing failure. Order is not specified.
106 ///
107 /// The default walks `list_entities` and reads each path — correct
108 /// everywhere, and on a backend whose per-path read re-resolves
109 /// its snapshot it is quadratic: the git-branch backend's
110 /// `read_entity` opens the repository, peels the ref and inflates
111 /// the root tree on every call, so a 7,500-entity boot inflated a
112 /// 7,500-entry tree 7,500 times (96 % of the measured boot,
113 /// 2026-09-10). Backends with a one-walk answer override it.
114 fn read_all_entities(&self) -> Result<Vec<EntityRead>, BackendError> {
115 read_entities_one_by_one(self)
116 }
117
118 /// Does the storage location this backend names exist at all: the
119 /// branch ref, the folder, the archive file? Distinct from "holds
120 /// no entities": a mount whose branch was never created and a mount
121 /// whose branch is empty both list zero entities, and only this
122 /// probe tells them apart. Boot asks it to raise `MOUNT_UNBACKED`
123 /// with the right reason (`missing_ref` / `missing_path` versus
124 /// `empty`); before it existed, a mount pointing at a branch that
125 /// did not exist sat in the writable roster with zero entities and
126 /// no warning. The default says `true` (in-memory and test
127 /// backends have nothing to be missing).
128 fn storage_present(&self) -> Result<bool, BackendError> {
129 Ok(true)
130 }
131
132 /// Upsert `content` at `rel_path`. Pending until [`Self::commit`].
133 fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError>;
134
135 /// Remove `rel_path`. Idempotent: no-op when the path is already
136 /// absent. Pending until [`Self::commit`].
137 fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError>;
138
139 /// Rename `from` to `to`. Pending until [`Self::commit`]. Errors
140 /// when `to` already exists.
141 fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError>;
142
143 /// Discard every pending (uncommitted) mutation, returning the
144 /// staging buffer to empty *without* producing a commit. The
145 /// transactional escape hatch for stage-then-commit callers:
146 /// the atomic `batch_update` stages each item's write into the
147 /// pending set, and when a later item fails validation it calls
148 /// this to drop the already-staged writes rather than commit a
149 /// half-applied batch. Idempotent — discarding an empty buffer
150 /// is a no-op.
151 ///
152 /// Default impl is a no-op: backends that never stage writes
153 /// (archive / any sealed backend) have no buffer to clear. The
154 /// folder and git-branch backends override to clear their
155 /// pending buffer (the git-branch backend also drops the
156 /// captured parent snapshot, symmetric with what `commit` does
157 /// on success).
158 fn discard_pending(&self) -> Result<(), BackendError> {
159 Ok(())
160 }
161
162 /// Flush pending mutations into a single commit. Returns the
163 /// resulting opaque [`CommitId`]; backends without history
164 /// return a synthetic id (UNIX-nanos + counter, hex) so callers
165 /// always get a non-empty cursor.
166 fn commit(&self, message: &str, ctx: &CommitContext<'_>) -> Result<CommitId, BackendError>;
167
168 /// Commit pending mutations with a parent-ref pinning guard.
169 /// When `expected_parent` is `Some`, the backend MUST refuse the
170 /// commit (`Err(BackendError::ParentMismatch { ... })`) if its
171 /// current head no longer matches the supplied ref — a sibling
172 /// writer advanced the on-disk state between the snapshot the
173 /// caller pinned and now. When `expected_parent` is `None`, the
174 /// call is equivalent to [`Self::commit`].
175 ///
176 /// Used by atomic multi-file mutations (notably the planned
177 /// referrer-rewriting rename) to surface drift mid-operation
178 /// rather than between operations. Backends without history
179 /// (folder, archive) inherit the default impl: they ignore
180 /// `expected_parent` because there's no concept of a parent to
181 /// pin against — drift detection on those mounts is a no-op
182 /// today and stays a no-op here. The git-branch backend
183 /// overrides to check the per-mem branch tip and surfaces
184 /// the mismatch with a typed error the engine layer can map to
185 /// `MEM_RELOADED` / `RENAME_PARTIAL_FAILURE`.
186 ///
187 /// Default impl: ignore `expected_parent` and delegate to
188 /// [`Self::commit`]. Bisect-safe — existing callers using
189 /// `Self::commit` directly are unaffected.
190 fn commit_with_expected_parent(
191 &self,
192 message: &str,
193 ctx: &CommitContext<'_>,
194 _expected_parent: Option<&str>,
195 ) -> Result<CommitId, BackendError> {
196 self.commit(message, ctx)
197 }
198
199 /// Stage a [`Provenance`] record so it lands with the next
200 /// [`Self::commit`] and never without it: the record of a write
201 /// belongs to that write. Pending like the entity writes, and
202 /// dropped by [`Self::discard_pending`] and by a failed commit.
203 ///
204 /// Required, with no default, so a wrapping backend cannot forward
205 /// the entity writes and silently keep the record to itself.
206 /// Persistence form differs per backend: the folder backend lands
207 /// the ledger line inside the commit, the git-branch backend
208 /// accepts and drops the record because its commit object already
209 /// carries the same data.
210 fn stage_provenance(&self, record: &Provenance) -> Result<(), BackendError>;
211
212 /// Append a [`Provenance`] record to the backend's mutation log at
213 /// once, outside any commit: the form for an event that writes no
214 /// file (dropping a stub, a review mark). A record that describes a
215 /// commit goes through [`Self::stage_provenance`] instead.
216 /// Persistence form differs per backend — JSONL line, commit
217 /// trailer, etc. — but the in-memory shape is identical.
218 fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError>;
219
220 /// Bring storage to a whole state before it is read: finish a
221 /// commit that was decided and then cut off before every file was
222 /// in place, and remove what an attempt that never reached its
223 /// commit point left behind. Every load calls it first, so loading
224 /// a mem is the recovery and no half-applied commit is ever served.
225 ///
226 /// `Ok(Some(_))` names the commit that was completed; `Ok(None)`
227 /// means storage was whole already. The default is `Ok(None)`: a
228 /// backend whose commit is one indivisible step (the git-branch
229 /// ref update, the in-memory swap) has nothing to finish.
230 fn complete_interrupted_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
231 Ok(None)
232 }
233
234 /// How long a load or a direct read of this backend waits for the
235 /// mem's write lock while a decided commit is unapplied in storage:
236 /// the workspace's write-lock deadline, `None` to wait without
237 /// bound. The engine hands it to every backend it serves, before
238 /// the first load and whenever the setting changes. The default
239 /// ignores it: a backend whose commit is one indivisible step never
240 /// waits there.
241 fn set_lock_wait(&self, _limit: Option<std::time::Duration>) {}
242
243 /// The wait [`Self::set_lock_wait`] governs, as it stands: `None`
244 /// for a backend that never waits there, `Some(None)` for a wait
245 /// without bound, `Some(Some(limit))` otherwise.
246 fn lock_wait(&self) -> Option<Option<std::time::Duration>> {
247 None
248 }
249
250 /// Read provenance entries since `cursor` (opaque,
251 /// backend-defined: a commit SHA for git-branch, an RFC-3339
252 /// timestamp for folder, ignored for archive). `None` cursor
253 /// means "from the beginning".
254 fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError>;
255
256 /// Opaque cursor pointing at the backend's current state. The
257 /// engine compares against a per-mount cached cursor to detect
258 /// drift — a sibling writer (another `Engine` instance, an
259 /// out-of-band `git pull`, etc.) advancing the on-disk state past
260 /// what the engine last read. Backends without history (folder,
261 /// archive) inherit the default impl returning `Ok(None)`; the
262 /// engine treats `None` as "no drift signal available" and skips
263 /// drift detection for that mount. The git-branch backend
264 /// overrides to return the per-mem branch tip's commit SHA hex;
265 /// the filesystem backend overrides to return the changelog's
266 /// last-line timestamp cursor (folder mems with no changelog yet
267 /// keep `None`). Archive and in-memory backends stay on the
268 /// default.
269 ///
270 /// Returning `Err` is reserved for backend-internal failures
271 /// (refdb hiccup, archive read failure, etc.). A failed probe never
272 /// fails the read it accompanies, and it is never taken for "no
273 /// drift" either: the engine reloads the mem, and a write waits
274 /// until a reload has succeeded.
275 fn current_head(&self) -> Result<Option<String>, BackendError> {
276 Ok(None)
277 }
278
279 /// The file whose exclusive OS lock serialises writers to this mem
280 /// across processes. The engine holds it from the drift reload
281 /// through the hash compare to the commit, so a sibling process can
282 /// never land a write between this process's check and its own
283 /// write. Without it, two processes holding the same stale hash
284 /// could both pass the compare and the later commit would silently
285 /// overwrite the earlier one. `None` means the backend has no
286 /// shared on-disk state to protect (archive, in-memory); the
287 /// default.
288 fn write_lock_path(&self) -> Option<std::path::PathBuf> {
289 None
290 }
291
292 /// Read the per-mem `.memstead/config.json` payload, if any.
293 ///
294 /// Returns the raw bytes the backend has for the mem's
295 /// config. The engine parses via
296 /// [`memstead_schema::config::parse_mem_config`] and stores the
297 /// result on the [`crate::Engine::mem_config_for`] accessor.
298 ///
299 /// Default impl returns `Ok(None)` — backends that don't
300 /// surface a config (or haven't yet implemented this primitive)
301 /// inherit and signal "no config available". The engine
302 /// treats `None` the same as a parse failure: `mem_config_for`
303 /// returns `None` for the affected mem, and consumers
304 /// (`memstead_health { include_config: true }`) emit empty
305 /// `writeGuidance` + `extra` blocks for that mem.
306 ///
307 /// Mirrors the pattern of [`Self::current_head`] —
308 /// backend-internal capability with a sensible no-op default.
309 ///
310 /// Implementations:
311 /// - Folder backend reads `<root>/.memstead/config.json`.
312 /// - Archive backend reads `.memstead/config.json` from inside the
313 /// zip.
314 /// - Git-branch backend reads `__MEMSTEAD:mems/<mem>/config.json`.
315 fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
316 Ok(None)
317 }
318
319 /// Read the optional authoring-provenance payload
320 /// (`.memstead/provenance.json`) the archive carries, if any.
321 ///
322 /// Returns the raw bytes the engine parses into a
323 /// [`memstead_schema::ArchiveProvenance`] and surfaces via
324 /// [`crate::Engine::archive_provenance_for`]. Default impl returns
325 /// `Ok(None)` — a backend with no provenance member (a pre-provenance
326 /// archive, the folder/git-branch backends until their read paths
327 /// lift) inherits and signals "provenance absent". Mirrors
328 /// [`Self::read_mem_config`].
329 fn read_archive_provenance(&self) -> Result<Option<Vec<u8>>, BackendError> {
330 Ok(None)
331 }
332
333 /// Read the optional sealed check-records member
334 /// (`.memstead/checks.json`) the archive carries, if any.
335 ///
336 /// Returns the raw bytes the engine parses into a
337 /// [`crate::check::SealedChecks`] and derives check state from on an
338 /// archive mount ([`crate::Engine::archive_checks_for`]). Default
339 /// impl returns `Ok(None)`: a writable backend never carries the
340 /// member (its check state lives in the workspace ledger), and an
341 /// archive sealed without records signals "no records sealed".
342 fn read_archive_checks(&self) -> Result<Option<Vec<u8>>, BackendError> {
343 Ok(None)
344 }
345
346 /// Read the engine-owned proposal record
347 /// ([`crate::ops::proposal::PROPOSAL_RECORD_PATH`]) bytes, if any:
348 /// the sidecar a proposal merge writes on the target branch, keyed
349 /// by proposal id with every disposition. The default reads the
350 /// path through [`Self::read_entity`], which is the git-branch
351 /// backend's tree read; the archive backend overrides to read the
352 /// sealed member. `Ok(None)` for a mem no proposal was ever merged
353 /// into.
354 fn read_proposal_record(&self) -> Result<Option<Vec<u8>>, BackendError> {
355 self.read_entity(Path::new(crate::ops::proposal::PROPOSAL_RECORD_PATH))
356 }
357
358 /// Write the per-mem `.memstead/config.json` payload. Symmetric
359 /// counterpart to [`Self::read_mem_config`].
360 ///
361 /// Backends that cannot persist a config (today: archive)
362 /// inherit the default and return [`BackendError::Sealed`]. The
363 /// engine's create / migrate paths branch on the discriminant
364 /// before calling.
365 ///
366 /// Implementations:
367 /// - Folder backend writes `<root>/.memstead/config.json` to disk.
368 /// - Git-branch backend writes
369 /// `__MEMSTEAD:mems/<mem>/config.json` (workspace-level ref) —
370 /// its own commit, separate from any per-mem-branch
371 /// mutation.
372 /// - Archive backend returns [`BackendError::Sealed`] — sealed
373 /// archives never re-write configs.
374 ///
375 /// Mirrors the symmetry pattern of
376 /// [`Self::read_entity`] / [`Self::write_entity`]: the trait
377 /// surface stays balanced so the engine doesn't branch on
378 /// backend type for write paths.
379 fn write_mem_config(
380 &self,
381 _bytes: &[u8],
382 _ctx: &crate::vcs::CommitContext<'_>,
383 ) -> Result<(), BackendError> {
384 Err(BackendError::Sealed)
385 }
386
387 /// Compare-and-set the mem config: write `bytes` only if the stored
388 /// config is still byte-identical to `expected`. Returns `false` without
389 /// writing when it is not, so the caller can re-read, re-apply, and retry.
390 ///
391 /// WHY the trait carries this rather than the engine doing read-then-write
392 /// itself: on the git-branch backend the ref update already lands under a
393 /// compare-and-set against the observed tip, so a sibling's commit
394 /// survives. The folder backend had no such protection, and a plain
395 /// `fs::write` between another writer's read and its write is silent loss
396 /// with no history to recover from.
397 /// Closing that needs the check and the write to be one indivisible step,
398 /// which only the backend can arrange.
399 ///
400 /// `expected` of `None` means "write unconditionally" (a mem that has no
401 /// stored config yet). The default compares against
402 /// [`Self::read_mem_config`] and then writes, which honours `expected`
403 /// but is one step only for a backend with a single writer; every
404 /// shipped writable backend overrides it with a compare and a write that
405 /// are indivisible.
406 fn write_mem_config_cas(
407 &self,
408 expected: Option<&[u8]>,
409 bytes: &[u8],
410 ctx: &crate::vcs::CommitContext<'_>,
411 ) -> Result<bool, BackendError> {
412 if let Some(expected) = expected
413 && self.read_mem_config()?.as_deref() != Some(expected)
414 {
415 return Ok(false);
416 }
417 self.write_mem_config(bytes, ctx)?;
418 Ok(true)
419 }
420
421 /// Record provenance for a pipeline-config edit (mediums / facets /
422 /// projections / ingests). The canonical pipeline config is a plain
423 /// JSON file under `.memstead/` on the workspace root — it has no
424 /// commit of its own — so backends with a commit timeline mirror the
425 /// edit into their provenance record; the commit is the audit trail,
426 /// the disk file stays the read path.
427 ///
428 /// `edits`: `(config_name, Some(bytes))` upserts the mirrored blob,
429 /// `(config_name, None)` removes it (a rename passes both). `kind`
430 /// is the primitive's plural (`mediums`, `facets`, `projections`,
431 /// `ingests`); `verb` names the operation for the commit subject.
432 ///
433 /// The default is a successful no-op: folder and archive backends
434 /// have no commit timeline, so the note is accepted and dropped —
435 /// the same posture as [`Self::write_mem_config_with_note`]. The
436 /// git-branch backend overrides this to commit the mirror under
437 /// `__MEMSTEAD:pipeline/<kind>/<mem>/<name>.json` with `note` on
438 /// the commit body.
439 fn record_pipeline_edit(
440 &self,
441 _kind: &str,
442 _edits: &[(String, Option<Vec<u8>>)],
443 _ctx: &crate::vcs::CommitContext<'_>,
444 _verb: &str,
445 ) -> Result<(), BackendError> {
446 Ok(())
447 }
448
449 /// Read the engine-owned anchors sidecar
450 /// ([`crate::anchor::ANCHOR_SIDECAR_PATH`]) bytes, if any.
451 ///
452 /// The sidecar lives on the mem branch under the `.memstead/`
453 /// umbrella every external reader already filters, so it never
454 /// surfaces as an entity. Returns the raw bytes the engine parses via
455 /// [`crate::anchor::AnchorSidecar::from_bytes`]; `Ok(None)` for a mem
456 /// that has never written anchors.
457 ///
458 /// Default impl returns `Ok(None)` — a backend that does not persist
459 /// anchors (a pre-anchor archive, any read-only mount) inherits and
460 /// signals "no anchors". Mirrors [`Self::read_mem_config`]. The
461 /// git-branch and in-memory backends override to read the sidecar
462 /// from their store (pending-buffer precedence, so a staged sidecar
463 /// write is visible before its commit).
464 fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
465 Ok(None)
466 }
467
468 /// Stage a write of the engine-owned anchors sidecar so it rides the
469 /// **same commit** as the entity mutation that produced it — the
470 /// atomicity guarantee anchors depend on (rename's referrer-rewrite,
471 /// delete's anchor removal, and branch_reset's rewind all move
472 /// entity + anchor state together).
473 ///
474 /// Pending until the next [`Self::commit`] — callers stage the entity
475 /// write, then the sidecar write, then commit once. Backends that
476 /// cannot persist anchors (archive / any sealed backend) inherit the
477 /// default returning [`BackendError::Sealed`]; the engine's write
478 /// path branches on mount capability before calling. The git-branch
479 /// and in-memory backends override to buffer the sidecar under
480 /// [`crate::anchor::ANCHOR_SIDECAR_PATH`] in the same pending set the
481 /// entity write used.
482 fn write_anchors_sidecar(&self, _bytes: &[u8]) -> Result<(), BackendError> {
483 Err(BackendError::Sealed)
484 }
485
486 /// Drop every backend-side artifact for this mem — the
487 /// symmetric counterpart to the writes performed by
488 /// `memstead_mem_create` (entity-seed commit on the per-mem
489 /// branch + [`Self::write_mem_config`] on `__MEMSTEAD`). Called by
490 /// `memstead_mem_delete` orchestration when `delete_files=true` and
491 /// the delete rule matched, to give the backend a chance to
492 /// prune ref-store state the engine alone has the git authority
493 /// to touch.
494 ///
495 /// Idempotent: safe to call on a backend whose artifacts already
496 /// went away (a sibling engine pruned them, the branch was
497 /// deleted manually, etc.). The default impl returns `Ok(())` —
498 /// backends whose on-disk state is fully captured by the mem
499 /// directory (folder, archive) inherit the no-op. The
500 /// orchestrator handles its `remove_dir_all` separately at the
501 /// outer layer.
502 ///
503 /// `ctx` is the deletion's commit context — actor, client, tool,
504 /// the agent-authored note, role and identity — so the one commit
505 /// a deletion produces carries the same provenance every other
506 /// mutation's commit carries. A backend that produces no commit
507 /// ignores it.
508 ///
509 /// Implementations:
510 /// - Folder backend keeps the default — its disk state is the
511 /// mem directory, which the orchestrator rmdirs.
512 /// - Archive backend keeps the default — sealed archives have
513 /// nothing additional to prune.
514 /// - Git-branch backend deletes `refs/heads/<branch_leaf>` and
515 /// commits a tree edit on `refs/heads/__MEMSTEAD` that removes
516 /// `mems/<branch_leaf>/config.json`, with `ctx` formatted into
517 /// the prune commit's message. `<branch_leaf>` is the mem's
518 /// full hierarchical path (e.g. `planning/plan-q4-revamp` or
519 /// the bare `<name>` for flat layouts).
520 fn delete_artifacts(&self, ctx: &crate::vcs::CommitContext<'_>) -> Result<(), BackendError> {
521 let _ = ctx;
522 Ok(())
523 }
524}
525
526/// A commit [`MemBackend::complete_interrupted_commit`] finished: the
527/// mem-relative paths it brought into place, in the commit's order.
528#[derive(Debug, Clone, PartialEq, Eq)]
529pub struct CompletedCommit {
530 pub files: Vec<String>,
531}
532
533/// Errors surfaced by [`MemBackend`].
534///
535/// The `Sealed` variant is the typed read-only signal — backends
536/// that physically cannot write (archive) return it from every
537/// mutating method. Callers (the engine's mutation pipeline) branch
538/// on the discriminant before reaching the backend; a `Sealed`
539/// reaching this layer is a programming error in the upstream
540/// capability check.
541#[derive(Debug, thiserror::Error)]
542pub enum BackendError {
543 /// Backend physically rejects writes. Returned by the archive
544 /// backend and any future read-only backend (e.g. registry pin).
545 #[error("backend is sealed (writes rejected)")]
546 Sealed,
547 /// Filesystem IO failure.
548 #[error("backend io error: {0}")]
549 Io(#[from] std::io::Error),
550 /// Commit-time CAS conflict: the backend snapshotted parent commit
551 /// `X` at write time, but by commit time the underlying store has
552 /// advanced to `current`. Raised by backends that perform
553 /// commit-tip CAS (the git-tree backend); the engine maps it onto
554 /// its `HashMismatch` envelope so agents see one `HASH_MISMATCH`
555 /// code whether the conflict was detected at the entity-hash level
556 /// or at the commit level.
557 #[error("backend cas conflict: current commit is now {current}")]
558 HashMismatch {
559 /// New commit identifier observed when the CAS check failed.
560 /// Opaque to base callers; the git-tree backend populates it
561 /// with a hex commit object id.
562 current: CommitId,
563 },
564 /// Path-related rejection that does not map onto the IO case:
565 /// an empty relative path, a path that escapes the mem root, a
566 /// move whose source is missing or whose target is already pending.
567 #[error("backend path error: {0}")]
568 Path(String),
569 /// Backend-specific failure not modelled by the variants above.
570 /// Carries an agent-readable message; structured backend errors
571 /// add their own variant.
572 #[error("backend error: {0}")]
573 Other(String),
574 /// Parent-ref pinning guard tripped on
575 /// [`MemBackend::commit_with_expected_parent`] — the backend's
576 /// current head no longer matches the caller's `expected_parent`.
577 /// A sibling writer (another `Engine` instance, an out-of-band
578 /// `git pull`, a manual git operation) advanced the on-disk state
579 /// between the snapshot the caller pinned and now. The engine
580 /// layer maps this into `MEM_RELOADED` /
581 /// `RENAME_PARTIAL_FAILURE` depending on whether other mems
582 /// already committed in the same logical operation. Today only
583 /// the git-branch backend (planned override) produces this
584 /// variant; folder and archive backends inherit the default impl
585 /// of `commit_with_expected_parent` which delegates to `commit`
586 /// without parent checking.
587 #[error(
588 "parent-ref mismatch: expected {expected}, found {actual} — sibling writer advanced the mem"
589 )]
590 ParentMismatch { expected: String, actual: String },
591 /// The commit is decided and not yet applied: its record is durable,
592 /// and moving its files into place was cut off. Neither a failed
593 /// write (resending it would write twice) nor a finished one. The
594 /// next load of the mem completes it
595 /// ([`MemBackend::complete_interrupted_commit`]).
596 #[error(
597 "commit is decided and not yet applied; the next load of the mem completes it: {detail}"
598 )]
599 CommitNotApplied { detail: String },
600 /// The commit is in storage and a step the backend runs after it
601 /// failed (the git-branch backend's worktree refresh). The caller
602 /// reports the write as done and names the step.
603 #[error("commit {commit} landed; follow-up step {step} failed: {detail}")]
604 FollowUpFailed {
605 commit: CommitId,
606 step: &'static str,
607 detail: String,
608 },
609}