Skip to main content

memstead_base/
workspace_store.rs

1//! Persistence adapter — reads / writes the [`Workspace`] from disk
2//! (or other backing stores) so [`crate::Engine::from_mounts`] can
3//! consume an in-memory mount list without owning the disk format.
4//!
5//! ## Two-layer file adapter (default)
6//!
7//! [`FileWorkspaceStore`] is the default adapter. It splits the
8//! workspace's persisted state across two files under
9//! `<workspace>/.memstead/`:
10//!
11//! - `workspace.toml` — operator-edited. Carries the persistence-
12//!   adapter declaration plus (in later sessions) cross-mem
13//!   permissions, workspace-level policy, plugin hooks. The engine
14//!   never writes to this file.
15//! - `state/mounts.json` — engine-managed. Carries the mount list
16//!   (per-mount mem name, schema pin, capability, lifecycle,
17//!   cross-linkable flag, and the backend-specific storage reference
18//!   — folder path, gitdir+branch pair, or archive path). The
19//!   operator does not edit this file during normal operation.
20//!
21//! The split mirrors the natural authorship: the operator edits rules
22//! that change rarely; the engine writes mount-list entries that
23//! change often (planning mems, ingest scratch mems, …). Sharing
24//! one file would force two authors with different update frequencies
25//! through the same merge surface.
26//!
27//! ## Adapter trait
28//!
29//! [`WorkspaceStoreAdapter`] is the seam. Future adapters (SQLite,
30//! remote, in-memory test fixture) implement it without changing the
31//! engine API.
32//! The adapter is selected at startup via the persistence-adapter
33//! declaration in `workspace.toml` — the file adapter is the only
34//! built-in V1.
35//!
36//! ## Backend instantiation
37//!
38//! The adapter produces a [`Workspace`] (mount list + operator
39//! policy). Turning each [`Mount`]'s [`MountStorage`] into a
40//! `Box<dyn MemBackend>` is a separate concern — handled by
41//! [`instantiate_local_backend`] for folder + archive variants. The
42//! git-branch backend lives in the `memstead-git-branch` crate and is
43//! injected through the engine's backend factory; an engine without that
44//! factory cannot materialise a `MountStorage::GitBranch` mount and surfaces
45//! [`InstantiateError::GitBranchBackendUnavailable`].
46
47use std::path::{Path, PathBuf};
48
49use serde::{Deserialize, Serialize};
50
51use crate::backend::MemBackend;
52use crate::storage::{ArchiveBackend, FilesystemBackend, InMemoryBackend};
53use crate::workspace::{
54    McpSection, Mount, MountCapability, MountLifecycle, MountStorage, MutationsSection, Workspace,
55    WorkspaceSettings,
56};
57
58/// The engine-managed workspace store directory under the workspace
59/// root — `<workspace_root>/.memstead/` holds `workspace.toml` and
60/// `state/mounts.json`, the roster of everything this workspace
61/// mounts. Distinct from
62/// the per-mem meta directory
63/// ([`memstead_schema::MEM_META_DIR`], re-exported as
64/// `crate::mem::MEM_META_DIR`) and from the literal `".memstead/..."`
65/// member paths inside sealed archives, which are a separate on-disk
66/// format and never use this constant.
67pub const WORKSPACE_STORE_DIR: &str = ".memstead";
68
69/// Errors surfaced by [`WorkspaceStoreAdapter::load`] and
70/// [`WorkspaceStoreAdapter::save_state`]. Backend-specific failures
71/// surface as [`StoreError::Other`] with a string message; structured
72/// per-adapter errors can extend the enum later.
73#[derive(Debug, thiserror::Error)]
74pub enum StoreError {
75    /// Workspace root has no `.memstead/` directory or no recognised
76    /// adapter file inside it. Distinct from `Io` so callers can
77    /// distinguish "needs `memstead init`" from "permissions broke".
78    #[error("workspace store not found at {path} — run `memstead mem-repo init` first")]
79    NotInitialised { path: PathBuf },
80    /// IO failure reading or writing one of the adapter files.
81    #[error(
82        "workspace store io error at {path}: {source} — no memstead command repairs this; \
83         check filesystem permissions and disk state"
84    )]
85    Io {
86        path: PathBuf,
87        #[source]
88        source: std::io::Error,
89    },
90    /// TOML or JSON parse / serialise failure. The wrapped string is
91    /// the underlying serde error; the file is named so operators
92    /// know where to look.
93    #[error(
94        "workspace store parse error at {path}: {message} — no memstead command repairs this; \
95         fix the named file by hand or restore it from version control"
96    )]
97    Parse { path: PathBuf, message: String },
98    /// Format version mismatch — adapter understands a different
99    /// schema version than the file declares.
100    #[error(
101        "workspace store format mismatch at {path}: expected {expected}, found {found} — \
102         no memstead command repairs this; use an engine version whose format matches the file"
103    )]
104    FormatMismatch {
105        path: PathBuf,
106        expected: String,
107        found: String,
108    },
109    /// Pre-rename workspace layout. The unit-noun cut renamed every
110    /// on-disk shape with no dual-read; refusing keeps an old
111    /// workspace from booting empty, half-mounted, or silently
112    /// rewritten. The message names the one-shot migration steps.
113    #[error(
114        "pre-rename workspace layout at {path} (found format {found}): migrate the workspace \
115         state in place — rewrite mounts.json to memstead-mounts-3 (record field `mem`, storage \
116         paths under mem-repo/), workspace.toml to memstead-git-branch-2 (tables `mem_management`, \
117         `cross_mem_links`), rename the gitdir container to mem-repo/, and move the metadata \
118         branch tree to mems/ — then retry"
119    )]
120    LegacyLayout { path: PathBuf, found: String },
121    /// A `projections/` directory holds a file in a retired binding format:
122    /// either a version-less (gen-2 four-primitive) projection or a v1
123    /// binding of the retired three-file store. The loader serves only v2
124    /// (one record per pipeline) and the engine no longer converts the
125    /// retired formats; the binding is re-authored with `memstead projection
126    /// init`. [`StoreError::code`] maps this to the `PROJECTION_STORE_LEGACY`
127    /// token on every surface.
128    #[error(
129        "retired binding format at {path}: this file is a gen-2 (version-less) or v1 binding, \
130         a format this engine no longer converts; re-author the binding with \
131         `memstead projection init`"
132    )]
133    LegacyProjectionStore { path: PathBuf },
134    /// A binding file declares a `version` the loader does not understand
135    /// (only v2 = `2` is supported; v1 and version-less files surface
136    /// [`Self::LegacyProjectionStore`] instead). Refused, never reinterpreted.
137    #[error(
138        "unsupported binding format version {version} at {path}: this engine understands v2 (version 2)"
139    )]
140    UnknownBindingVersion { path: PathBuf, version: i64 },
141    /// Catch-all for adapter-specific failures. Carries an
142    /// agent-readable message; structured variants extend the enum.
143    #[error("workspace store error: {0}")]
144    Other(String),
145}
146
147impl StoreError {
148    /// Stable, surface-independent error code token, following the
149    /// [`crate::EngineError::code`] convention (UPPER_SNAKE). Boot
150    /// failures route through [`crate::engine::BootError::code`],
151    /// which delegates here — a store-layer failure carries the same
152    /// typed code on CLI stderr, `--json` envelopes, and the MCP
153    /// server's boot diagnostics.
154    pub fn code(&self) -> &'static str {
155        match self {
156            // Same token the CLI's setup layer uses for "no workspace
157            // marker found" — one condition, one code, regardless of
158            // whether the walk or the store load detected it.
159            StoreError::NotInitialised { .. } => "WORKSPACE_NOT_INITIALISED",
160            StoreError::Io { .. } => "WORKSPACE_STORE_IO",
161            StoreError::Parse { .. } => "WORKSPACE_STORE_PARSE",
162            StoreError::FormatMismatch { .. } => "WORKSPACE_STORE_FORMAT_MISMATCH",
163            StoreError::LegacyLayout { .. } => "LEGACY_WORKSPACE_LAYOUT",
164            StoreError::LegacyProjectionStore { .. } => "PROJECTION_STORE_LEGACY",
165            StoreError::UnknownBindingVersion { .. } => "UNKNOWN_BINDING_VERSION",
166            StoreError::Other(_) => "WORKSPACE_STORE_ERROR",
167        }
168    }
169}
170
171/// Adapter trait — the seam between the engine and the persisted
172/// workspace state. Implementations decide *where* the mount list
173/// lives (two files under `.memstead/`, a SQLite database, a remote
174/// service, an in-memory test fixture); the engine consumes the
175/// produced [`Workspace`] uniformly.
176pub trait WorkspaceStoreAdapter: Send + Sync {
177    /// Load the workspace from `workspace_root`. Implementations
178    /// resolve the adapter-specific files relative to this root
179    /// (e.g. the file adapter reads
180    /// `<workspace_root>/.memstead/workspace.toml` +
181    /// `<workspace_root>/.memstead/state/mounts.json`).
182    fn load(&self, workspace_root: &Path) -> Result<Workspace, StoreError>;
183
184    /// Persist the engine-managed slice of state (today: the mount
185    /// list). Operator-edited fields stay untouched — adapters that
186    /// share one file with operator content must not overwrite it
187    /// here. The two-layer file adapter writes only
188    /// `state/mounts.json`.
189    ///
190    /// Last-writer-wins. Prefer [`Self::save_state_cas`] whenever the
191    /// caller can name what it read: a long-lived process that dumps
192    /// its cached roster over this call drops every mount a sibling
193    /// process registered since the dump was taken.
194    fn save_state(&self, workspace_root: &Path, workspace: &Workspace) -> Result<(), StoreError>;
195
196    /// Raw bytes of the engine-managed state file, or `None` when it
197    /// does not exist yet. The compare token for
198    /// [`Self::save_state_cas`].
199    fn read_state_bytes(&self, workspace_root: &Path) -> Result<Option<Vec<u8>>, StoreError>;
200
201    /// Parse state bytes previously returned by
202    /// [`Self::read_state_bytes`] into the mount roster they carry.
203    fn parse_state_bytes(
204        &self,
205        workspace_root: &Path,
206        bytes: &[u8],
207    ) -> Result<Vec<Mount>, StoreError>;
208
209    /// Compare-and-set counterpart of [`Self::save_state`]: write only
210    /// when the on-disk state still equals `expected`, and report a
211    /// mismatch as `Ok(false)` rather than an error so the caller can
212    /// re-read, re-merge and retry. The check and the write are one
213    /// step under the adapter's own lock — a caller that reads, then
214    /// compares, then writes leaves exactly the window this exists to
215    /// close.
216    fn save_state_cas(
217        &self,
218        workspace_root: &Path,
219        workspace: &Workspace,
220        expected: Option<&[u8]>,
221    ) -> Result<bool, StoreError>;
222}
223
224/// Two-layer file adapter — the default. Reads
225/// `.memstead/workspace.toml` (operator) +
226/// `.memstead/state/mounts.json` (engine). Constructed without
227/// arguments; everything is keyed off the workspace root passed
228/// per-call.
229#[derive(Debug, Default, Clone, Copy)]
230pub struct FileWorkspaceStore;
231
232impl FileWorkspaceStore {
233    /// Construct the adapter. Stateless; safe to share across
234    /// engines, callers, and tests.
235    pub fn new() -> Self {
236        Self
237    }
238
239    /// Path of the operator-edited file.
240    pub fn workspace_toml_path(workspace_root: &Path) -> PathBuf {
241        workspace_root
242            .join(WORKSPACE_STORE_DIR)
243            .join("workspace.toml")
244    }
245
246    /// Path of the engine-managed state file.
247    pub fn mounts_json_path(workspace_root: &Path) -> PathBuf {
248        workspace_root
249            .join(WORKSPACE_STORE_DIR)
250            .join("state")
251            .join("mounts.json")
252    }
253}
254
255const WORKSPACE_TOML_FORMAT: &str = "memstead-git-branch-2";
256/// Pre-rename `workspace.toml` format. V1 carried the old unit-noun
257/// policy tables. Recognised only to refuse with
258/// [`StoreError::LegacyLayout`] — no dual-read.
259const WORKSPACE_TOML_FORMAT_LEGACY: &str = "memstead-git-branch-1";
260/// Current `mounts.json` format. V3 is the unit-noun cut: mount
261/// records carry a `"mem"` field and mem-repo path values. Like V2 it
262/// stores `gitdir` / `path` values relative to `workspace_root` when
263/// they live inside the workspace, so checked-in state survives a
264/// clone into a different home dir. Absolute paths are still accepted
265/// on write (and round-trip untouched) when the mount target sits
266/// outside `workspace_root` — e.g., an archive on a shared cache. The
267/// reader resolves relative values against `workspace_root` at load
268/// time.
269const MOUNTS_JSON_FORMAT_V3: &str = "memstead-mounts-3";
270/// V4 adds the `cached-archive` storage entry: a read-only mem installed
271/// into the engine's archive cache, recorded by its content-addressed
272/// file name instead of the absolute path of one machine's cache. A
273/// roster is written as V4 only when it carries such an entry, so a
274/// roster without one stays byte-identical V3; the reader accepts both.
275const MOUNTS_JSON_FORMAT_V4: &str = "memstead-mounts-4";
276
277/// The process's archive-cache directory, as the crate that owns the
278/// cache (memstead-git-branch) registers it. Unset in a build without
279/// that crate: a cached-archive entry then resolves to no file and its
280/// mem is quarantined `ARCHIVE_NOT_INSTALLED`, never mounted elsewhere.
281static MEM_CACHE_DIR_PROVIDER: std::sync::OnceLock<fn() -> PathBuf> = std::sync::OnceLock::new();
282
283/// Where a cached-archive entry points in a process with no archive
284/// cache: a directory that never holds the file, under the workspace's
285/// engine state, so the mem quarantines and the entry writes back as
286/// itself.
287const NO_ARCHIVE_CACHE_DIR: &str = "no-archive-cache";
288
289/// Register the function that names the archive-cache directory. The
290/// first registration wins; later calls are no-ops.
291pub fn set_mem_cache_dir_provider(provider: fn() -> PathBuf) {
292    let _ = MEM_CACHE_DIR_PROVIDER.set(provider);
293}
294
295/// The archive-cache directory of this process, when a provider is
296/// registered.
297pub fn registered_mem_cache_dir() -> Option<PathBuf> {
298    MEM_CACHE_DIR_PROVIDER.get().map(|f| f())
299}
300
301/// Whether `file` has the shape of an archive-cache file of `mem`:
302/// `<mem>-<16 lowercase hex>.mem`, the content-addressed name the cache
303/// gives every installed archive.
304pub fn is_cache_file_name(mem: &str, file: &str) -> bool {
305    file.strip_prefix(&format!("{mem}-"))
306        .and_then(|r| r.strip_suffix(".mem"))
307        .is_some_and(|key| {
308            key.len() == 16
309                && key
310                    .bytes()
311                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
312        })
313}
314
315/// The cache file name of an installed archive's mount path: a path
316/// directly in this process's archive cache, or the placeholder a
317/// cached-archive entry resolves to in a process with no cache.
318pub fn installed_archive_file(path: &Path) -> Option<String> {
319    cached_archive_file(path).or_else(|| {
320        let parent = path.parent()?;
321        let is_placeholder = parent
322            .file_name()
323            .is_some_and(|n| n == NO_ARCHIVE_CACHE_DIR)
324            && parent
325                .parent()
326                .and_then(|p| p.file_name())
327                .is_some_and(|n| n == WORKSPACE_STORE_DIR);
328        is_placeholder
329            .then(|| path.file_name().map(|n| n.to_string_lossy().into_owned()))
330            .flatten()
331    })
332}
333
334/// The cache file name of an archive mount path that lives directly in
335/// the archive cache, `None` for any other path.
336pub fn cached_archive_file(path: &Path) -> Option<String> {
337    let dir = registered_mem_cache_dir()?;
338    let parent = path.parent()?;
339    let same = parent == dir
340        || match (std::fs::canonicalize(parent), std::fs::canonicalize(&dir)) {
341            (Ok(a), Ok(b)) => a == b,
342            _ => false,
343        };
344    if !same {
345        return None;
346    }
347    path.file_name().map(|n| n.to_string_lossy().into_owned())
348}
349/// Pre-rename `mounts.json` formats (V1: absolute paths; V2: relative
350/// paths; both with the old unit-noun record field). Recognised only
351/// to refuse with [`StoreError::LegacyLayout`] — there is no
352/// dual-read; a one-shot migration rewrites state in place.
353const MOUNTS_JSON_FORMAT_LEGACY: [&str; 2] = ["memstead-mounts-1", "memstead-mounts-2"];
354
355/// Format-only probe for `mounts.json`, parsed before the full
356/// document so format refusals (legacy layout, unknown version)
357/// surface as typed errors rather than record-level parse failures.
358#[derive(Deserialize)]
359struct MountsFormatProbe {
360    format: String,
361}
362
363/// Shared `workspace.toml` format gate: current passes, the
364/// pre-rename V1 refuses as [`StoreError::LegacyLayout`], anything
365/// else as [`StoreError::FormatMismatch`].
366fn check_workspace_toml_format(format: &str, toml_path: &Path) -> Result<(), StoreError> {
367    if format == WORKSPACE_TOML_FORMAT {
368        return Ok(());
369    }
370    if format == WORKSPACE_TOML_FORMAT_LEGACY {
371        return Err(StoreError::LegacyLayout {
372            path: toml_path.to_path_buf(),
373            found: format.to_string(),
374        });
375    }
376    Err(StoreError::FormatMismatch {
377        path: toml_path.to_path_buf(),
378        expected: WORKSPACE_TOML_FORMAT.to_string(),
379        found: format.to_string(),
380    })
381}
382
383/// Resolve a path read from `mounts.json` against the workspace
384/// root. Absolute paths are returned untouched (they sit outside
385/// `workspace_root` by design — typically a shared archive cache);
386/// relative paths are joined against `workspace_root` so the
387/// in-memory `Mount` always carries an absolute path.
388fn absolutize_mount_path(value: PathBuf, workspace_root: &Path) -> PathBuf {
389    if value.is_absolute() {
390        value
391    } else {
392        workspace_root.join(value)
393    }
394}
395
396/// Normalise an absolute mount path for `mounts.json` serialisation.
397/// When the path sits inside `workspace_root`, strip the prefix so
398/// the on-disk form is portable. When it sits outside — an archive
399/// in a global cache, a mem on a separate filesystem — keep the
400/// absolute form; `strip_prefix` failure is the explicit fallback.
401fn relativize_mount_path(value: &Path, workspace_root: &Path) -> PathBuf {
402    match value.strip_prefix(workspace_root) {
403        Ok(rel) => rel.to_path_buf(),
404        Err(_) => value.to_path_buf(),
405    }
406}
407
408/// True when `dir` is a workspace root: it carries
409/// `.memstead/workspace.toml`. The shared recognition primitive for
410/// every workspace walk-up (MCP boot, CLI setup, per-command walkers)
411/// — keep them all on this helper so workspaces resolve uniformly.
412pub fn is_workspace_root(dir: &Path) -> bool {
413    FileWorkspaceStore::workspace_toml_path(dir).is_file()
414}
415
416/// True when the workspace root carries `mem-repo/.git/` — the
417/// multi-mem, git-backed shape. False for the single-mem, history-free
418/// filesystem-mem shape. The `.memstead/workspace.toml` marker is
419/// shape-neutral, so this directory probe is what distinguishes the two.
420///
421/// The shared shape primitive: the CLI's `WorkspaceShape` resolution,
422/// the mem-repo-only refusals, and the MCP boot line all route through
423/// here so no surface can name a shape the others disagree with.
424pub fn is_mem_repo_shaped(workspace_root: &Path) -> bool {
425    workspace_root.join("mem-repo").join(".git").is_dir()
426}
427
428/// The one spelling of a workspace's shape, for any surface that names
429/// it to a human or an agent: `"mem-repo"` or `"filesystem-mem"`. Both
430/// spellings match the vocabulary the refusals use
431/// (`UNSUPPORTED_WORKSPACE_SHAPE`) and the commands that create each
432/// shape (`memstead mem-repo init` / `memstead quickstart`).
433pub fn workspace_shape_label(workspace_root: &Path) -> &'static str {
434    if is_mem_repo_shaped(workspace_root) {
435        "mem-repo"
436    } else {
437        "filesystem-mem"
438    }
439}
440
441impl WorkspaceStoreAdapter for FileWorkspaceStore {
442    fn load(&self, workspace_root: &Path) -> Result<Workspace, StoreError> {
443        let memstead_dir = workspace_root.join(WORKSPACE_STORE_DIR);
444        if !memstead_dir.is_dir() {
445            return Err(StoreError::NotInitialised {
446                path: workspace_root.to_path_buf(),
447            });
448        }
449
450        // workspace.toml is required (carries the adapter declaration).
451        let toml_path = Self::workspace_toml_path(workspace_root);
452        let toml_text = std::fs::read_to_string(&toml_path).map_err(|e| {
453            if e.kind() == std::io::ErrorKind::NotFound {
454                StoreError::NotInitialised {
455                    path: workspace_root.to_path_buf(),
456                }
457            } else {
458                StoreError::Io {
459                    path: toml_path.clone(),
460                    source: e,
461                }
462            }
463        })?;
464        let toml_doc: WorkspaceTomlDoc =
465            toml::from_str(&toml_text).map_err(|e| StoreError::Parse {
466                path: toml_path.clone(),
467                message: e.to_string(),
468            })?;
469        check_workspace_toml_format(&toml_doc.format, &toml_path)?;
470
471        // state/mounts.json is optional — a fresh workspace has the
472        // adapter declaration but no mounts yet. Treat the missing
473        // file as "zero mounts".
474        let mounts_path = Self::mounts_json_path(workspace_root);
475        let mounts: Vec<Mount> = match std::fs::read_to_string(&mounts_path) {
476            Ok(text) => parse_mounts_text(&text, &mounts_path, workspace_root)?,
477            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
478            Err(e) => {
479                return Err(StoreError::Io {
480                    path: mounts_path,
481                    source: e,
482                });
483            }
484        };
485
486        warn_if_legacy_schemas_dir(toml_doc.schemas_dir.as_deref());
487        let settings = build_settings(
488            toml_doc.mem_management,
489            toml_doc.cross_mem_links,
490            toml_doc.mcp,
491            toml_doc.mutations,
492            toml_doc.plugin,
493        )?;
494        Ok(Workspace { mounts, settings })
495    }
496
497    fn save_state(&self, workspace_root: &Path, workspace: &Workspace) -> Result<(), StoreError> {
498        let mounts_path = Self::mounts_json_path(workspace_root);
499        ensure_state_dir(&mounts_path)?;
500        let text = render_mounts_text(workspace, workspace_root, &mounts_path)?;
501        std::fs::write(&mounts_path, text).map_err(|e| StoreError::Io {
502            path: mounts_path,
503            source: e,
504        })?;
505        Ok(())
506    }
507
508    fn read_state_bytes(&self, workspace_root: &Path) -> Result<Option<Vec<u8>>, StoreError> {
509        let mounts_path = Self::mounts_json_path(workspace_root);
510        match std::fs::read(&mounts_path) {
511            Ok(b) => Ok(Some(b)),
512            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
513            Err(e) => Err(StoreError::Io {
514                path: mounts_path,
515                source: e,
516            }),
517        }
518    }
519
520    fn parse_state_bytes(
521        &self,
522        workspace_root: &Path,
523        bytes: &[u8],
524    ) -> Result<Vec<Mount>, StoreError> {
525        let mounts_path = Self::mounts_json_path(workspace_root);
526        let text = std::str::from_utf8(bytes).map_err(|e| StoreError::Parse {
527            path: mounts_path.clone(),
528            message: e.to_string(),
529        })?;
530        parse_mounts_text(text, &mounts_path, workspace_root)
531    }
532
533    fn save_state_cas(
534        &self,
535        workspace_root: &Path,
536        workspace: &Workspace,
537        expected: Option<&[u8]>,
538    ) -> Result<bool, StoreError> {
539        let mounts_path = Self::mounts_json_path(workspace_root);
540        ensure_state_dir(&mounts_path)?;
541        let text = render_mounts_text(workspace, workspace_root, &mounts_path)?;
542
543        // Same lockfile shape the folder backend's config compare-and-set
544        // uses: hold an exclusive marker, compare, write, release on every
545        // exit path. 50 x 10ms, then the holder is presumed dead — a state
546        // write is milliseconds of work, so half a second of contention is
547        // not a busy writer.
548        let lock_path = mounts_path.with_extension("json.lock");
549        let mut held = None;
550        for attempt in 0..50 {
551            match std::fs::OpenOptions::new()
552                .write(true)
553                .create_new(true)
554                .open(&lock_path)
555            {
556                Ok(f) => {
557                    held = Some(f);
558                    break;
559                }
560                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
561                    if attempt == 49 {
562                        let _ = std::fs::remove_file(&lock_path);
563                    }
564                    std::thread::sleep(std::time::Duration::from_millis(10));
565                }
566                Err(e) => {
567                    return Err(StoreError::Io {
568                        path: lock_path,
569                        source: e,
570                    });
571                }
572            }
573        }
574        let _lock = match held {
575            Some(f) => f,
576            None => std::fs::OpenOptions::new()
577                .write(true)
578                .create(true)
579                .truncate(true)
580                .open(&lock_path)
581                .map_err(|e| StoreError::Io {
582                    path: lock_path.clone(),
583                    source: e,
584                })?,
585        };
586        let release = || {
587            let _ = std::fs::remove_file(&lock_path);
588        };
589
590        let current = match std::fs::read(&mounts_path) {
591            Ok(b) => Some(b),
592            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
593            Err(e) => {
594                release();
595                return Err(StoreError::Io {
596                    path: mounts_path,
597                    source: e,
598                });
599            }
600        };
601        if current.as_deref() != expected {
602            release();
603            return Ok(false);
604        }
605        let result = std::fs::write(&mounts_path, text).map_err(|e| StoreError::Io {
606            path: mounts_path,
607            source: e,
608        });
609        release();
610        result.map(|_| true)
611    }
612}
613
614/// Create the `state/` directory the mounts file lives in.
615fn ensure_state_dir(mounts_path: &Path) -> Result<(), StoreError> {
616    if let Some(parent) = mounts_path.parent() {
617        std::fs::create_dir_all(parent).map_err(|e| StoreError::Io {
618            path: parent.to_path_buf(),
619            source: e,
620        })?;
621    }
622    Ok(())
623}
624
625/// Render a workspace's mount roster as `mounts.json` text.
626fn render_mounts_text(
627    workspace: &Workspace,
628    workspace_root: &Path,
629    mounts_path: &Path,
630) -> Result<String, StoreError> {
631    let mounts: Vec<MountWire> = workspace
632        .mounts
633        .iter()
634        .map(|m| MountWire::from_mount(m, workspace_root))
635        .collect();
636    let format = if mounts
637        .iter()
638        .any(|m| matches!(m.storage, MountStorageWire::CachedArchive { .. }))
639    {
640        MOUNTS_JSON_FORMAT_V4
641    } else {
642        MOUNTS_JSON_FORMAT_V3
643    };
644    let doc = MountsJsonDoc {
645        format: format.to_string(),
646        mounts,
647    };
648    serde_json::to_string_pretty(&doc).map_err(|e| StoreError::Parse {
649        path: mounts_path.to_path_buf(),
650        message: e.to_string(),
651    })
652}
653
654/// Parse `mounts.json` text into the roster it carries, enforcing the
655/// format pin. Probes the format field before the full parse: a
656/// pre-rename file fails record deserialisation (old unit-noun field
657/// name), and the typed `LegacyLayout` refusal must win over that
658/// generic parse error.
659fn parse_mounts_text(
660    text: &str,
661    mounts_path: &Path,
662    workspace_root: &Path,
663) -> Result<Vec<Mount>, StoreError> {
664    let probe: MountsFormatProbe = serde_json::from_str(text).map_err(|e| StoreError::Parse {
665        path: mounts_path.to_path_buf(),
666        message: e.to_string(),
667    })?;
668    if MOUNTS_JSON_FORMAT_LEGACY.contains(&probe.format.as_str()) {
669        return Err(StoreError::LegacyLayout {
670            path: mounts_path.to_path_buf(),
671            found: probe.format,
672        });
673    }
674    if probe.format != MOUNTS_JSON_FORMAT_V3 && probe.format != MOUNTS_JSON_FORMAT_V4 {
675        return Err(StoreError::FormatMismatch {
676            path: mounts_path.to_path_buf(),
677            expected: MOUNTS_JSON_FORMAT_V4.to_string(),
678            found: probe.format,
679        });
680    }
681    let doc: MountsJsonDoc = serde_json::from_str(text).map_err(|e| StoreError::Parse {
682        path: mounts_path.to_path_buf(),
683        message: e.to_string(),
684    })?;
685    Ok(doc
686        .mounts
687        .into_iter()
688        .map(|w| w.into_mount(workspace_root))
689        .collect())
690}
691
692/// On-disk shape of `workspace.toml`. Operator-edited; engine never
693/// writes. V1 carries the adapter declaration, `[mem_management]`
694/// rule lists, and `[cross_mem_links]` permission policy. Plugin
695/// hooks land additively when consumers need them.
696#[derive(Debug, Serialize, Deserialize)]
697#[serde(deny_unknown_fields)]
698struct WorkspaceTomlDoc {
699    /// Schema version of the TOML file. Must equal
700    /// `memstead-git-branch-1` for V1; mismatch surfaces
701    /// [`StoreError::FormatMismatch`].
702    format: String,
703    /// Persistence-adapter declaration. Carries the adapter `name`
704    /// (default: `"file-two-layer"`); future adapters add their own
705    /// nested config blocks.
706    #[serde(default)]
707    persistence_adapter: PersistenceAdapterDecl,
708    /// `[mem_management]` rule lists. Both arrays default to empty
709    /// — an empty list means "no agent-driven mem create / delete
710    /// allowed" (mirrors full). Operators add `[[mem_management.create]]`
711    /// / `[[mem_management.delete]]` entries to opt in.
712    #[serde(default)]
713    mem_management: MemManagementWire,
714    /// `[cross_mem_links]` raw shape — `<mem> = "*"` (wildcard)
715    /// or `<mem> = ["target", ...]` (allowlist) per key. Parsed
716    /// post-decode via `memstead_schema::workspace_config::CrossLinkValue::parse_toml`
717    /// because the wildcard-or-list shape doesn't fit serde's
718    /// untagged-enum pattern. Empty when the section is absent;
719    /// interpreted as default-deny.
720    #[serde(default)]
721    cross_mem_links: toml::Table,
722    /// **Retired key.** The folder-backend authored-schema location is
723    /// fixed at `<workspace>/.memstead/schemas/`; this key is no longer
724    /// honoured. Kept here only so an older workspace.toml that still
725    /// carries it parses cleanly — `warn_if_legacy_schemas_dir` emits a
726    /// one-line warning and the value is dropped (never threaded into
727    /// `WorkspaceSettings`).
728    #[serde(default)]
729    schemas_dir: Option<std::path::PathBuf>,
730    /// `[mcp]` section — MCP-binary tuning. Absent → defaults
731    /// (`token_budget` falls back to the binary's compile-time
732    /// default, `disabled_tools` is empty).
733    #[serde(default)]
734    mcp: McpSection,
735    /// `[mutations]` section — engine-wide mutation policy. Absent →
736    /// `require_notes = None` (interpreted as `false`).
737    #[serde(default)]
738    mutations: MutationsSection,
739    /// `[plugin.*]` namespace — opaque pass-through map keyed by
740    /// plugin identifier. Values are raw TOML tables; the engine
741    /// never inspects them.
742    #[serde(default)]
743    plugin: std::collections::HashMap<String, toml::Table>,
744}
745
746/// Wire shape for the `[mem_management]` section. Both arrays
747/// default to empty so the section may be omitted from
748/// `workspace.toml` entirely.
749#[derive(Debug, Default, Serialize, Deserialize)]
750struct MemManagementWire {
751    #[serde(default)]
752    create: Vec<CreateRuleWire>,
753    #[serde(default)]
754    delete: Vec<DeleteRuleWire>,
755}
756
757/// Wire shape for one `[[mem_management.create]]` entry. Mirrors
758/// [`crate::workspace::CreateRuleSetting`] with serde defaults so
759/// `schemas` may be omitted (treated as the empty allowlist —
760/// effectively a deny rule, surfaced for parity with full).
761///
762/// `default_cross_links` is decoded as a raw `toml::Value` and lifted
763/// to `CrossLinkValue` post-decode via the same parser as the
764/// top-level `[cross_mem_links]` section, sharing the wildcard-vs-
765/// list-vs-mixed-rejection semantics.
766#[derive(Debug, Serialize, Deserialize)]
767struct CreateRuleWire {
768    pattern: String,
769    #[serde(default)]
770    schemas: Vec<String>,
771    #[serde(default)]
772    default_cross_links: Option<toml::Value>,
773}
774
775/// Wire shape for one `[[mem_management.delete]]` entry. Mirrors
776/// [`crate::workspace::DeleteRuleSetting`].
777#[derive(Debug, Serialize, Deserialize)]
778struct DeleteRuleWire {
779    pattern: String,
780}
781
782/// Parse the operator-edited `.memstead/workspace.toml` at `workspace_root`
783/// into a fresh `WorkspaceSettings`. Exposed so MCP- and CLI-driven
784/// policy-mutation tools (the `workspace_config_edit::{grant,revoke}_*`
785/// family) can refresh the engine's in-memory settings after writing
786/// to disk — closing the stale-cache footgun where the next call
787/// into the engine after a successful policy mutation still saw the
788/// pre-mutation policy.
789///
790/// Reads only `workspace.toml` — the engine-managed `mounts.json` is
791/// untouched. The function pays one file-read; the alternative
792/// (threading projections through the policy-mutation functions
793/// without an engine handle) was rejected for the coupling cost.
794///
795/// Errors mirror [`FileWorkspaceStore::load`]'s subset that touches
796/// `workspace.toml` only: `NotInitialised` (no `.memstead/` dir),
797/// `Io` / `Parse` (file read or TOML parse failure),
798/// `FormatMismatch` (unsupported `format` field).
799pub fn parse_workspace_settings(
800    workspace_root: &Path,
801) -> Result<crate::workspace::WorkspaceSettings, StoreError> {
802    let memstead_dir = workspace_root.join(WORKSPACE_STORE_DIR);
803    if !memstead_dir.is_dir() {
804        return Err(StoreError::NotInitialised {
805            path: workspace_root.to_path_buf(),
806        });
807    }
808    let toml_path = FileWorkspaceStore::workspace_toml_path(workspace_root);
809    let toml_text = std::fs::read_to_string(&toml_path).map_err(|e| {
810        if e.kind() == std::io::ErrorKind::NotFound {
811            StoreError::NotInitialised {
812                path: workspace_root.to_path_buf(),
813            }
814        } else {
815            StoreError::Io {
816                path: toml_path.clone(),
817                source: e,
818            }
819        }
820    })?;
821    let toml_doc: WorkspaceTomlDoc = toml::from_str(&toml_text).map_err(|e| StoreError::Parse {
822        path: toml_path.clone(),
823        message: e.to_string(),
824    })?;
825    check_workspace_toml_format(&toml_doc.format, &toml_path)?;
826    warn_if_legacy_schemas_dir(toml_doc.schemas_dir.as_deref());
827    build_settings(
828        toml_doc.mem_management,
829        toml_doc.cross_mem_links,
830        toml_doc.mcp,
831        toml_doc.mutations,
832        toml_doc.plugin,
833    )
834}
835
836/// Build a `WorkspaceSettings` from the raw wire shapes. Folds in
837/// the `[mem_management]` rules and the post-decoded
838/// `[cross_mem_links]` map; surfaces a typed parse error if any
839/// cross-link value violates the wildcard / list / non-empty
840/// invariants.
841fn build_settings(
842    vm: MemManagementWire,
843    cross_mem_links_raw: toml::Table,
844    mcp: McpSection,
845    mutations: MutationsSection,
846    plugin: std::collections::HashMap<String, toml::Table>,
847) -> Result<WorkspaceSettings, StoreError> {
848    let mut create_rules = Vec::with_capacity(vm.create.len());
849    for r in vm.create {
850        let default_cross_links = match r.default_cross_links {
851            None => None,
852            Some(value) => {
853                let location = format!(
854                    "[[mem_management.create]] pattern={}.default_cross_links",
855                    r.pattern
856                );
857                Some(parse_cross_link_value(&location, &value)?)
858            }
859        };
860        create_rules.push(crate::workspace::CreateRuleSetting {
861            pattern: r.pattern,
862            schemas: r.schemas,
863            default_cross_links,
864        });
865    }
866
867    let mut cross_mem_links = std::collections::BTreeMap::new();
868    for (mem, value) in &cross_mem_links_raw {
869        let location = format!("[cross_mem_links].{mem}");
870        let parsed = parse_cross_link_value(&location, value)?;
871        cross_mem_links.insert(mem.clone(), parsed);
872    }
873
874    Ok(WorkspaceSettings {
875        mem_create_rules: create_rules,
876        mem_delete_rules: vm
877            .delete
878            .into_iter()
879            .map(|r| crate::workspace::DeleteRuleSetting { pattern: r.pattern })
880            .collect(),
881        cross_mem_links,
882        mcp,
883        mutations,
884        plugin,
885    })
886}
887
888/// The folder-backend authored-schema location is fixed at
889/// `<workspace>/.memstead/schemas/` — the `schemas_dir` workspace.toml
890/// key is retired (no configurability without demonstrated need). A
891/// workspace.toml that still carries the key gets a one-line warning
892/// naming the fixed location; the key is otherwise ignored, never
893/// honoured. Called from both `workspace.toml` parse entry points.
894fn warn_if_legacy_schemas_dir(schemas_dir: Option<&std::path::Path>) {
895    if let Some(dir) = schemas_dir {
896        tracing::warn!(
897            "`schemas_dir` (= {:?}) in workspace.toml is retired and ignored — \
898             authored schemas are read from the fixed `<workspace>/.memstead/schemas/`. \
899             Remove the key to silence this warning.",
900            dir
901        );
902    }
903}
904
905/// Parse one cross-link value via `memstead_schema::workspace_config::CrossLinkValue::parse_toml`,
906/// lifting the schema-crate's `ConfigError` into a `StoreError::Parse` with
907/// the operator-facing TOML location prefix.
908fn parse_cross_link_value(
909    location: &str,
910    value: &toml::Value,
911) -> Result<memstead_schema::workspace_config::CrossLinkValue, StoreError> {
912    memstead_schema::workspace_config::CrossLinkValue::parse_toml(location, value).map_err(|e| {
913        StoreError::Parse {
914            path: std::path::PathBuf::from("workspace.toml"),
915            message: e.to_string(),
916        }
917    })
918}
919
920/// Persistence-adapter section of `workspace.toml`. Future adapters
921/// nest their config under this section.
922#[derive(Debug, Serialize, Deserialize)]
923struct PersistenceAdapterDecl {
924    name: String,
925}
926
927impl Default for PersistenceAdapterDecl {
928    fn default() -> Self {
929        Self {
930            name: "file-two-layer".to_string(),
931        }
932    }
933}
934
935/// On-disk shape of `state/mounts.json`. Engine-managed; operator
936/// does not edit during normal operation (lifecycle tools rewrite it
937/// after every mount-state mutation).
938#[derive(Debug, Serialize, Deserialize)]
939struct MountsJsonDoc {
940    format: String,
941    mounts: Vec<MountWire>,
942}
943
944/// Wire shape for one mount. Mirrors [`Mount`] with serializable
945/// fields. Schema pin serialises as a plain string (`"default"` or
946/// `"default@1.0.0"`); storage uses an internally-tagged enum
947/// (`type: "folder" | "git-branch" | "archive"`).
948#[derive(Debug, Serialize, Deserialize)]
949struct MountWire {
950    mem: String,
951    /// Optional schema-pin *expectation assertion* (`<name>@<version>`).
952    /// The authoritative pin is the mem's own `MemConfig.schema`;
953    /// this is a workspace-local cross-check. `default` on read keeps
954    /// older `mounts.json` files (which always carried the key) loading
955    /// as `Some`; skip-on-`None` omits the key for assertion-less mounts.
956    #[serde(default, skip_serializing_if = "Option::is_none")]
957    schema: Option<String>,
958    /// In-flight migration target (`<name>@<version>`), absent for
959    /// settled mems. `default` on read keeps pre-dual-pin
960    /// `mounts.json` files loading unchanged; skip-on-`None` keeps
961    /// settled mems' entries byte-identical to before.
962    #[serde(default, skip_serializing_if = "Option::is_none")]
963    migration_target: Option<String>,
964    storage: MountStorageWire,
965    capability: CapabilityWire,
966    lifecycle: LifecycleWire,
967    cross_linkable: bool,
968}
969
970#[derive(Debug, Serialize, Deserialize)]
971#[serde(tag = "type", rename_all = "kebab-case")]
972enum MountStorageWire {
973    Folder {
974        path: PathBuf,
975    },
976    GitBranch {
977        gitdir: PathBuf,
978        branch: String,
979    },
980    Archive {
981        path: PathBuf,
982    },
983    /// A read-only mem installed into the archive cache, by its
984    /// content-addressed file name (`<mem>-<content key>.mem`). It
985    /// resolves against the running machine's cache, so the tracked
986    /// roster names what was installed, never where one machine keeps it.
987    CachedArchive {
988        file: String,
989    },
990    /// In-memory backend. Carries no fields — it serialises as the
991    /// bare tag `{ "type": "in-memory" }`. Unambiguous against the
992    /// other three variants (each of which carries a `path` or
993    /// `gitdir`/`branch`), so a round-trip never confuses it for one
994    /// of them. Present for wire completeness; ephemeral session
995    /// mems are normally constructed via `Engine::from_mounts`
996    /// rather than persisted to `mounts.json`.
997    InMemory,
998}
999
1000#[derive(Debug, Serialize, Deserialize)]
1001#[serde(rename_all = "kebab-case")]
1002enum CapabilityWire {
1003    ReadOnly,
1004    Write,
1005}
1006
1007#[derive(Debug, Serialize, Deserialize)]
1008#[serde(rename_all = "kebab-case")]
1009enum LifecycleWire {
1010    Eager,
1011    Lazy,
1012}
1013
1014impl MountWire {
1015    fn from_mount(m: &Mount, workspace_root: &Path) -> Self {
1016        Self {
1017            mem: m.mem.clone(),
1018            schema: m.schema.as_ref().map(|s| s.to_string()),
1019            migration_target: m.migration_target.as_ref().map(|t| t.to_string()),
1020            storage: match &m.storage {
1021                MountStorage::Folder { path } => MountStorageWire::Folder {
1022                    path: relativize_mount_path(path, workspace_root),
1023                },
1024                MountStorage::GitBranch { gitdir, branch } => MountStorageWire::GitBranch {
1025                    gitdir: relativize_mount_path(gitdir, workspace_root),
1026                    branch: branch.clone(),
1027                },
1028                MountStorage::Archive { path } => match cached_archive_file(path).or_else(|| {
1029                    // The placeholder a cached-archive entry resolves to in
1030                    // a process with no archive cache writes back as the
1031                    // same entry, so the round trip stays faithful.
1032                    let placeholder = workspace_root
1033                        .join(WORKSPACE_STORE_DIR)
1034                        .join(NO_ARCHIVE_CACHE_DIR);
1035                    (path.parent() == Some(placeholder.as_path()))
1036                        .then(|| path.file_name().map(|n| n.to_string_lossy().into_owned()))
1037                        .flatten()
1038                }) {
1039                    Some(file) => MountStorageWire::CachedArchive { file },
1040                    None => MountStorageWire::Archive {
1041                        path: relativize_mount_path(path, workspace_root),
1042                    },
1043                },
1044                MountStorage::InMemory => MountStorageWire::InMemory,
1045            },
1046            capability: match m.capability {
1047                MountCapability::ReadOnly => CapabilityWire::ReadOnly,
1048                MountCapability::Write => CapabilityWire::Write,
1049            },
1050            lifecycle: match m.lifecycle {
1051                MountLifecycle::Eager => LifecycleWire::Eager,
1052                MountLifecycle::Lazy => LifecycleWire::Lazy,
1053            },
1054            cross_linkable: m.cross_linkable,
1055        }
1056    }
1057
1058    fn into_mount(self, workspace_root: &Path) -> Mount {
1059        let mem_name = self.mem.clone();
1060        Mount {
1061            mem: self.mem,
1062            schema: self.schema.map(|s| {
1063                s.parse()
1064                    .expect("schema pin on disk must be `<name>@<version>`")
1065            }),
1066            migration_target: self.migration_target.map(|t| {
1067                t.parse()
1068                    .expect("migration_target on disk must be `<name>@<version>`")
1069            }),
1070            storage: match self.storage {
1071                MountStorageWire::Folder { path } => MountStorage::Folder {
1072                    path: absolutize_mount_path(path, workspace_root),
1073                },
1074                MountStorageWire::GitBranch { gitdir, branch } => MountStorage::GitBranch {
1075                    gitdir: absolutize_mount_path(gitdir, workspace_root),
1076                    branch,
1077                },
1078                MountStorageWire::Archive { path } => {
1079                    let path = absolutize_mount_path(path, workspace_root);
1080                    // A roster written before identity entries existed, on
1081                    // another machine, names that machine's cache file. A
1082                    // missing path whose name is this mem's cache file name
1083                    // is read as that identity, so the clone heals: it
1084                    // resolves against this machine's cache and writes back
1085                    // as a cached-archive entry.
1086                    let file = path
1087                        .file_name()
1088                        .map(|n| n.to_string_lossy().into_owned())
1089                        .filter(|f| !path.exists() && is_cache_file_name(&mem_name, f));
1090                    match (file, registered_mem_cache_dir()) {
1091                        (Some(file), Some(dir)) => MountStorage::Archive {
1092                            path: dir.join(file),
1093                        },
1094                        _ => MountStorage::Archive { path },
1095                    }
1096                }
1097                MountStorageWire::CachedArchive { file } => MountStorage::Archive {
1098                    path: match registered_mem_cache_dir() {
1099                        Some(dir) => dir.join(file),
1100                        // No cache in this build: a path that holds no
1101                        // file, so the mem quarantines instead of loading.
1102                        None => workspace_root
1103                            .join(WORKSPACE_STORE_DIR)
1104                            .join(NO_ARCHIVE_CACHE_DIR)
1105                            .join(file),
1106                    },
1107                },
1108                MountStorageWire::InMemory => MountStorage::InMemory,
1109            },
1110            capability: match self.capability {
1111                CapabilityWire::ReadOnly => MountCapability::ReadOnly,
1112                CapabilityWire::Write => MountCapability::Write,
1113            },
1114            lifecycle: match self.lifecycle {
1115                LifecycleWire::Eager => MountLifecycle::Eager,
1116                LifecycleWire::Lazy => MountLifecycle::Lazy,
1117            },
1118            cross_linkable: self.cross_linkable,
1119        }
1120    }
1121}
1122
1123/// Errors surfaced by [`instantiate_local_backend`].
1124#[derive(Debug, thiserror::Error)]
1125pub enum InstantiateError {
1126    /// Mount declares a `MountStorage::GitBranch` storage variant but
1127    /// `memstead-base` alone cannot construct a git-branch backend —
1128    /// the implementation lives in the `memstead-git-branch` crate.
1129    ///
1130    /// The remedy text names the two real, published entry points and
1131    /// nothing else: an earlier revision pointed at a `mem-repo` Cargo
1132    /// feature that does not exist on the published crates and named
1133    /// `instantiate_full_backend` without saying how to wire it —
1134    /// a cold-start run burned its longest wall on exactly that.
1135    /// Keep this message in lockstep with the
1136    /// actual `memstead-git-branch` public API.
1137    #[error(
1138        "mem {mem}: git-branch storage needs the memstead-git-branch crate \
1139         (`cargo add memstead-git-branch`). Simplest: open the workspace with \
1140         `memstead_git_branch::workspace_store::engine_from_workspace_root(root)` \
1141         instead of the memstead-base constructor. Alternative, if you build the \
1142         Engine yourself: `engine.set_backend_factory(\
1143         memstead_git_branch::storage::instantiate_full_backend)` before mounting"
1144    )]
1145    GitBranchBackendUnavailable { mem: String },
1146    /// A git-branch mount whose mem-repo is not there: the gitdir the
1147    /// workspace names does not exist (a workspace copied without its
1148    /// `mem-repo/`, a clone of the outer repository, a deleted
1149    /// directory). The mem is quarantined with this code, and the
1150    /// message names the restore: the remote first, then `pull --all`.
1151    #[error(
1152        "mem {mem}: its mem-repo is missing ({gitdir} does not exist) — restore it from its remote: \
1153         `memstead mem-repo init --remote <url>`, then `memstead pull --all`"
1154    )]
1155    MemRepoMissing { mem: String, gitdir: String },
1156}
1157
1158impl InstantiateError {
1159    /// Stable, surface-independent error code token (UPPER_SNAKE, per
1160    /// the [`crate::EngineError::code`] convention). Reuses the CLI's
1161    /// existing `UNSUPPORTED_WORKSPACE_SHAPE` token: both fire when an
1162    /// engine without the git-branch factory meets a git-branch-shaped
1163    /// workspace, and the
1164    /// agent's next step is identical.
1165    pub fn code(&self) -> &'static str {
1166        match self {
1167            InstantiateError::GitBranchBackendUnavailable { .. } => "UNSUPPORTED_WORKSPACE_SHAPE",
1168            InstantiateError::MemRepoMissing { .. } => "MEM_REPO_MISSING",
1169        }
1170    }
1171}
1172
1173/// Materialise a [`MemBackend`] for `mount` using the local
1174/// backends (folder + archive). Returns an error for the git-branch
1175/// variant; `memstead-git-branch` handles that with its
1176/// `instantiate_full_backend` counterpart, installed through the backend
1177/// factory.
1178///
1179/// Lives in `memstead-base` because both folder and archive backends are
1180/// always-on; the function shape (one mount in, one boxed backend
1181/// out) stays uniform for both factories so the engine's
1182/// `from_mounts` glue is identical with and without the git-branch crate.
1183pub fn instantiate_local_backend(mount: &Mount) -> Result<Box<dyn MemBackend>, InstantiateError> {
1184    match &mount.storage {
1185        MountStorage::Folder { path } => Ok(Box::new(FilesystemBackend::new(path.clone()))),
1186        MountStorage::Archive { path } => Ok(Box::new(ArchiveBackend::new(path.clone()))),
1187        MountStorage::InMemory => Ok(Box::new(InMemoryBackend::new())),
1188        MountStorage::GitBranch { .. } => Err(InstantiateError::GitBranchBackendUnavailable {
1189            mem: mount.mem.clone(),
1190        }),
1191    }
1192}
1193
1194/// On-disk layout the workspace root carries today.
1195///
1196/// Drives [`Engine::from_workspace_root`](crate::Engine::from_workspace_root):
1197/// a workspace either carries the two-layer file adapter shape
1198/// (`Layout::New`) or it does not (`Layout::Empty`). Pre-rebuild
1199/// layouts are no longer recognised — operators run
1200/// `memstead mem-repo init` to bootstrap a fresh workspace.
1201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1202pub enum Layout {
1203    /// No `.memstead/workspace.toml` present — operator should run
1204    /// `memstead mem-repo init` to bootstrap.
1205    Empty,
1206    /// `.memstead/workspace.toml` present — workspace runs on the
1207    /// two-layer file adapter.
1208    New,
1209}
1210
1211/// Detect the on-disk layout at `workspace_root`. The returned
1212/// [`Layout`] discriminator is total: every workspace falls into
1213/// exactly one variant.
1214pub fn detect_layout(workspace_root: &Path) -> Layout {
1215    if is_workspace_root(workspace_root) {
1216        Layout::New
1217    } else {
1218        Layout::Empty
1219    }
1220}
1221
1222/// Synthesize a one-mount [`Workspace`] from a bare *standalone* folder
1223/// mem — a directory carrying `.memstead/config.json` but **no**
1224/// `.memstead/workspace.toml`. The mem root *is* the workspace root
1225/// (the collapsed single-mem form), so the lone mount is a folder
1226/// backend pointed at `workspace_root` itself.
1227///
1228/// Returns `None` when the directory is not a standalone mem — no
1229/// readable, schema-pinned `config.json` — so boot callers fall through
1230/// to [`crate::BootError::NotInitialised`] exactly as before. This is what
1231/// collapses the old separate standalone-mem boot path into the unified
1232/// roster+detail experience: a lone mem opens as a workspace with one
1233/// mount, no `workspace.toml` required.
1234///
1235/// The synthesized workspace carries default (empty) settings — a
1236/// standalone mem has no `[mem_management]` / `[cross_mem_links]`
1237/// policy — and the mount is writable, not cross-linkable (there is no
1238/// sibling to link to). The schema pin and name come from the mem's own
1239/// `config.json`; an engine-written config omits `name`, so the directory
1240/// basename is the fallback identity.
1241pub fn standalone_workspace(workspace_root: &Path) -> Option<Workspace> {
1242    let config = memstead_schema::config::load_and_validate(workspace_root).ok()?;
1243    let schema = config.schema.clone()?;
1244    let name = config.name.clone().unwrap_or_else(|| {
1245        workspace_root
1246            .file_name()
1247            .map(|n| n.to_string_lossy().to_string())
1248            .unwrap_or_else(|| "mem".to_string())
1249    });
1250    let mount = Mount {
1251        mem: name,
1252        schema: Some(schema),
1253        storage: MountStorage::Folder {
1254            path: workspace_root.to_path_buf(),
1255        },
1256        capability: MountCapability::Write,
1257        lifecycle: MountLifecycle::Eager,
1258        cross_linkable: false,
1259        migration_target: None,
1260    };
1261    Some(Workspace {
1262        mounts: vec![mount],
1263        settings: WorkspaceSettings::default(),
1264    })
1265}
1266
1267#[cfg(test)]
1268mod tests;