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