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 /// Read provenance entries since `cursor` (opaque,
235 /// backend-defined: a commit SHA for git-branch, an RFC-3339
236 /// timestamp for folder, ignored for archive). `None` cursor
237 /// means "from the beginning".
238 fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError>;
239
240 /// Opaque cursor pointing at the backend's current state. The
241 /// engine compares against a per-mount cached cursor to detect
242 /// drift — a sibling writer (another `Engine` instance, an
243 /// out-of-band `git pull`, etc.) advancing the on-disk state past
244 /// what the engine last read. Backends without history (folder,
245 /// archive) inherit the default impl returning `Ok(None)`; the
246 /// engine treats `None` as "no drift signal available" and skips
247 /// drift detection for that mount. The git-branch backend
248 /// overrides to return the per-mem branch tip's commit SHA hex;
249 /// the filesystem backend overrides to return the changelog's
250 /// last-line timestamp cursor (folder mems with no changelog yet
251 /// keep `None`). Archive and in-memory backends stay on the
252 /// default.
253 ///
254 /// Returning `Err` is reserved for backend-internal failures
255 /// (refdb hiccup, archive read failure, etc.). A failed probe never
256 /// fails the read it accompanies, and it is never taken for "no
257 /// drift" either: the engine reloads the mem, and a write waits
258 /// until a reload has succeeded.
259 fn current_head(&self) -> Result<Option<String>, BackendError> {
260 Ok(None)
261 }
262
263 /// The file whose exclusive OS lock serialises writers to this mem
264 /// across processes. The engine holds it from the drift reload
265 /// through the hash compare to the commit, so a sibling process can
266 /// never land a write between this process's check and its own
267 /// write. Without it, two processes holding the same stale hash
268 /// could both pass the compare and the later commit would silently
269 /// overwrite the earlier one. `None` means the backend has no
270 /// shared on-disk state to protect (archive, in-memory); the
271 /// default.
272 fn write_lock_path(&self) -> Option<std::path::PathBuf> {
273 None
274 }
275
276 /// Read the per-mem `.memstead/config.json` payload, if any.
277 ///
278 /// Returns the raw bytes the backend has for the mem's
279 /// config. The engine parses via
280 /// [`memstead_schema::config::parse_mem_config`] and stores the
281 /// result on the [`crate::Engine::mem_config_for`] accessor.
282 ///
283 /// Default impl returns `Ok(None)` — backends that don't
284 /// surface a config (or haven't yet implemented this primitive)
285 /// inherit and signal "no config available". The engine
286 /// treats `None` the same as a parse failure: `mem_config_for`
287 /// returns `None` for the affected mem, and consumers
288 /// (`memstead_health { include_config: true }`) emit empty
289 /// `writeGuidance` + `extra` blocks for that mem.
290 ///
291 /// Mirrors the pattern of [`Self::current_head`] —
292 /// backend-internal capability with a sensible no-op default.
293 ///
294 /// Implementations:
295 /// - Folder backend reads `<root>/.memstead/config.json`.
296 /// - Archive backend reads `.memstead/config.json` from inside the
297 /// zip.
298 /// - Git-branch backend reads `__MEMSTEAD:mems/<mem>/config.json`.
299 fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
300 Ok(None)
301 }
302
303 /// Read the optional authoring-provenance payload
304 /// (`.memstead/provenance.json`) the archive carries, if any.
305 ///
306 /// Returns the raw bytes the engine parses into a
307 /// [`memstead_schema::ArchiveProvenance`] and surfaces via
308 /// [`crate::Engine::archive_provenance_for`]. Default impl returns
309 /// `Ok(None)` — a backend with no provenance member (a pre-provenance
310 /// archive, the folder/git-branch backends until their read paths
311 /// lift) inherits and signals "provenance absent". Mirrors
312 /// [`Self::read_mem_config`].
313 fn read_archive_provenance(&self) -> Result<Option<Vec<u8>>, BackendError> {
314 Ok(None)
315 }
316
317 /// Read the optional sealed check-records member
318 /// (`.memstead/checks.json`) the archive carries, if any.
319 ///
320 /// Returns the raw bytes the engine parses into a
321 /// [`crate::check::SealedChecks`] and derives check state from on an
322 /// archive mount ([`crate::Engine::archive_checks_for`]). Default
323 /// impl returns `Ok(None)`: a writable backend never carries the
324 /// member (its check state lives in the workspace ledger), and an
325 /// archive sealed without records signals "no records sealed".
326 fn read_archive_checks(&self) -> Result<Option<Vec<u8>>, BackendError> {
327 Ok(None)
328 }
329
330 /// Read the engine-owned proposal record
331 /// ([`crate::ops::proposal::PROPOSAL_RECORD_PATH`]) bytes, if any:
332 /// the sidecar a proposal merge writes on the target branch, keyed
333 /// by proposal id with every disposition. The default reads the
334 /// path through [`Self::read_entity`], which is the git-branch
335 /// backend's tree read; the archive backend overrides to read the
336 /// sealed member. `Ok(None)` for a mem no proposal was ever merged
337 /// into.
338 fn read_proposal_record(&self) -> Result<Option<Vec<u8>>, BackendError> {
339 self.read_entity(Path::new(crate::ops::proposal::PROPOSAL_RECORD_PATH))
340 }
341
342 /// Write the per-mem `.memstead/config.json` payload. Symmetric
343 /// counterpart to [`Self::read_mem_config`].
344 ///
345 /// Backends that cannot persist a config (today: archive)
346 /// inherit the default and return [`BackendError::Sealed`]. The
347 /// engine's create / migrate paths branch on the discriminant
348 /// before calling.
349 ///
350 /// Implementations:
351 /// - Folder backend writes `<root>/.memstead/config.json` to disk.
352 /// - Git-branch backend writes
353 /// `__MEMSTEAD:mems/<mem>/config.json` (workspace-level ref) —
354 /// its own commit, separate from any per-mem-branch
355 /// mutation.
356 /// - Archive backend returns [`BackendError::Sealed`] — sealed
357 /// archives never re-write configs.
358 ///
359 /// Mirrors the symmetry pattern of
360 /// [`Self::read_entity`] / [`Self::write_entity`]: the trait
361 /// surface stays balanced so the engine doesn't branch on
362 /// backend type for write paths.
363 fn write_mem_config(
364 &self,
365 _bytes: &[u8],
366 _ctx: &crate::vcs::CommitContext<'_>,
367 ) -> Result<(), BackendError> {
368 Err(BackendError::Sealed)
369 }
370
371 /// Compare-and-set the mem config: write `bytes` only if the stored
372 /// config is still byte-identical to `expected`. Returns `false` without
373 /// writing when it is not, so the caller can re-read, re-apply, and retry.
374 ///
375 /// WHY the trait carries this rather than the engine doing read-then-write
376 /// itself: on the git-branch backend the ref update already lands under a
377 /// compare-and-set against the observed tip, so a sibling's commit
378 /// survives. The folder backend had no such protection, and a plain
379 /// `fs::write` between another writer's read and its write is silent loss
380 /// with no history to recover from.
381 /// Closing that needs the check and the write to be one indivisible step,
382 /// which only the backend can arrange.
383 ///
384 /// `expected` of `None` means "write unconditionally" (a mem that has no
385 /// stored config yet). The default compares against
386 /// [`Self::read_mem_config`] and then writes, which honours `expected`
387 /// but is one step only for a backend with a single writer; every
388 /// shipped writable backend overrides it with a compare and a write that
389 /// are indivisible.
390 fn write_mem_config_cas(
391 &self,
392 expected: Option<&[u8]>,
393 bytes: &[u8],
394 ctx: &crate::vcs::CommitContext<'_>,
395 ) -> Result<bool, BackendError> {
396 if let Some(expected) = expected
397 && self.read_mem_config()?.as_deref() != Some(expected)
398 {
399 return Ok(false);
400 }
401 self.write_mem_config(bytes, ctx)?;
402 Ok(true)
403 }
404
405 /// Record provenance for a pipeline-config edit (mediums / facets /
406 /// projections / ingests). The canonical pipeline config is a plain
407 /// JSON file under `.memstead/` on the workspace root — it has no
408 /// commit of its own — so backends with a commit timeline mirror the
409 /// edit into their provenance record; the commit is the audit trail,
410 /// the disk file stays the read path.
411 ///
412 /// `edits`: `(config_name, Some(bytes))` upserts the mirrored blob,
413 /// `(config_name, None)` removes it (a rename passes both). `kind`
414 /// is the primitive's plural (`mediums`, `facets`, `projections`,
415 /// `ingests`); `verb` names the operation for the commit subject.
416 ///
417 /// The default is a successful no-op: folder and archive backends
418 /// have no commit timeline, so the note is accepted and dropped —
419 /// the same posture as [`Self::write_mem_config_with_note`]. The
420 /// git-branch backend overrides this to commit the mirror under
421 /// `__MEMSTEAD:pipeline/<kind>/<mem>/<name>.json` with `note` on
422 /// the commit body.
423 fn record_pipeline_edit(
424 &self,
425 _kind: &str,
426 _edits: &[(String, Option<Vec<u8>>)],
427 _ctx: &crate::vcs::CommitContext<'_>,
428 _verb: &str,
429 ) -> Result<(), BackendError> {
430 Ok(())
431 }
432
433 /// Read the engine-owned anchors sidecar
434 /// ([`crate::anchor::ANCHOR_SIDECAR_PATH`]) bytes, if any.
435 ///
436 /// The sidecar lives on the mem branch under the `.memstead/`
437 /// umbrella every external reader already filters, so it never
438 /// surfaces as an entity. Returns the raw bytes the engine parses via
439 /// [`crate::anchor::AnchorSidecar::from_bytes`]; `Ok(None)` for a mem
440 /// that has never written anchors.
441 ///
442 /// Default impl returns `Ok(None)` — a backend that does not persist
443 /// anchors (a pre-anchor archive, any read-only mount) inherits and
444 /// signals "no anchors". Mirrors [`Self::read_mem_config`]. The
445 /// git-branch and in-memory backends override to read the sidecar
446 /// from their store (pending-buffer precedence, so a staged sidecar
447 /// write is visible before its commit).
448 fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
449 Ok(None)
450 }
451
452 /// Stage a write of the engine-owned anchors sidecar so it rides the
453 /// **same commit** as the entity mutation that produced it — the
454 /// atomicity guarantee anchors depend on (rename's referrer-rewrite,
455 /// delete's anchor removal, and branch_reset's rewind all move
456 /// entity + anchor state together).
457 ///
458 /// Pending until the next [`Self::commit`] — callers stage the entity
459 /// write, then the sidecar write, then commit once. Backends that
460 /// cannot persist anchors (archive / any sealed backend) inherit the
461 /// default returning [`BackendError::Sealed`]; the engine's write
462 /// path branches on mount capability before calling. The git-branch
463 /// and in-memory backends override to buffer the sidecar under
464 /// [`crate::anchor::ANCHOR_SIDECAR_PATH`] in the same pending set the
465 /// entity write used.
466 fn write_anchors_sidecar(&self, _bytes: &[u8]) -> Result<(), BackendError> {
467 Err(BackendError::Sealed)
468 }
469
470 /// Drop every backend-side artifact for this mem — the
471 /// symmetric counterpart to the writes performed by
472 /// `memstead_mem_create` (entity-seed commit on the per-mem
473 /// branch + [`Self::write_mem_config`] on `__MEMSTEAD`). Called by
474 /// `memstead_mem_delete` orchestration when `delete_files=true` and
475 /// the delete rule matched, to give the backend a chance to
476 /// prune ref-store state the engine alone has the git authority
477 /// to touch.
478 ///
479 /// Idempotent: safe to call on a backend whose artifacts already
480 /// went away (a sibling engine pruned them, the branch was
481 /// deleted manually, etc.). The default impl returns `Ok(())` —
482 /// backends whose on-disk state is fully captured by the mem
483 /// directory (folder, archive) inherit the no-op. The
484 /// orchestrator handles its `remove_dir_all` separately at the
485 /// outer layer.
486 ///
487 /// `ctx` is the deletion's commit context — actor, client, tool,
488 /// the agent-authored note, role and identity — so the one commit
489 /// a deletion produces carries the same provenance every other
490 /// mutation's commit carries. A backend that produces no commit
491 /// ignores it.
492 ///
493 /// Implementations:
494 /// - Folder backend keeps the default — its disk state is the
495 /// mem directory, which the orchestrator rmdirs.
496 /// - Archive backend keeps the default — sealed archives have
497 /// nothing additional to prune.
498 /// - Git-branch backend deletes `refs/heads/<branch_leaf>` and
499 /// commits a tree edit on `refs/heads/__MEMSTEAD` that removes
500 /// `mems/<branch_leaf>/config.json`, with `ctx` formatted into
501 /// the prune commit's message. `<branch_leaf>` is the mem's
502 /// full hierarchical path (e.g. `planning/plan-q4-revamp` or
503 /// the bare `<name>` for flat layouts).
504 fn delete_artifacts(&self, ctx: &crate::vcs::CommitContext<'_>) -> Result<(), BackendError> {
505 let _ = ctx;
506 Ok(())
507 }
508}
509
510/// A commit [`MemBackend::complete_interrupted_commit`] finished: the
511/// mem-relative paths it brought into place, in the commit's order.
512#[derive(Debug, Clone, PartialEq, Eq)]
513pub struct CompletedCommit {
514 pub files: Vec<String>,
515}
516
517/// Errors surfaced by [`MemBackend`].
518///
519/// The `Sealed` variant is the typed read-only signal — backends
520/// that physically cannot write (archive) return it from every
521/// mutating method. Callers (the engine's mutation pipeline) branch
522/// on the discriminant before reaching the backend; a `Sealed`
523/// reaching this layer is a programming error in the upstream
524/// capability check.
525#[derive(Debug, thiserror::Error)]
526pub enum BackendError {
527 /// Backend physically rejects writes. Returned by the archive
528 /// backend and any future read-only backend (e.g. registry pin).
529 #[error("backend is sealed (writes rejected)")]
530 Sealed,
531 /// Filesystem IO failure.
532 #[error("backend io error: {0}")]
533 Io(#[from] std::io::Error),
534 /// Commit-time CAS conflict: the backend snapshotted parent commit
535 /// `X` at write time, but by commit time the underlying store has
536 /// advanced to `current`. Raised by backends that perform
537 /// commit-tip CAS (the git-tree backend); the engine maps it onto
538 /// its `HashMismatch` envelope so agents see one `HASH_MISMATCH`
539 /// code whether the conflict was detected at the entity-hash level
540 /// or at the commit level.
541 #[error("backend cas conflict: current commit is now {current}")]
542 HashMismatch {
543 /// New commit identifier observed when the CAS check failed.
544 /// Opaque to base callers; the git-tree backend populates it
545 /// with a hex commit object id.
546 current: CommitId,
547 },
548 /// Path-related rejection that does not map onto the IO case:
549 /// an empty relative path, a path that escapes the mem root, a
550 /// move whose source is missing or whose target is already pending.
551 #[error("backend path error: {0}")]
552 Path(String),
553 /// Backend-specific failure not modelled by the variants above.
554 /// Carries an agent-readable message; structured backend errors
555 /// add their own variant.
556 #[error("backend error: {0}")]
557 Other(String),
558 /// Parent-ref pinning guard tripped on
559 /// [`MemBackend::commit_with_expected_parent`] — the backend's
560 /// current head no longer matches the caller's `expected_parent`.
561 /// A sibling writer (another `Engine` instance, an out-of-band
562 /// `git pull`, a manual git operation) advanced the on-disk state
563 /// between the snapshot the caller pinned and now. The engine
564 /// layer maps this into `MEM_RELOADED` /
565 /// `RENAME_PARTIAL_FAILURE` depending on whether other mems
566 /// already committed in the same logical operation. Today only
567 /// the git-branch backend (planned override) produces this
568 /// variant; folder and archive backends inherit the default impl
569 /// of `commit_with_expected_parent` which delegates to `commit`
570 /// without parent checking.
571 #[error(
572 "parent-ref mismatch: expected {expected}, found {actual} — sibling writer advanced the mem"
573 )]
574 ParentMismatch { expected: String, actual: String },
575 /// The commit is decided and not yet applied: its record is durable,
576 /// and moving its files into place was cut off. Neither a failed
577 /// write (resending it would write twice) nor a finished one. The
578 /// next load of the mem completes it
579 /// ([`MemBackend::complete_interrupted_commit`]).
580 #[error(
581 "commit is decided and not yet applied; the next load of the mem completes it: {detail}"
582 )]
583 CommitNotApplied { detail: String },
584 /// The commit is in storage and a step the backend runs after it
585 /// failed (the git-branch backend's worktree refresh). The caller
586 /// reports the write as done and names the step.
587 #[error("commit {commit} landed; follow-up step {step} failed: {detail}")]
588 FollowUpFailed {
589 commit: CommitId,
590 step: &'static str,
591 detail: String,
592 },
593}