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