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, FilesystemMemWriter, 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(FilesystemMemWriter::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 {
1125    use super::*;
1126    use memstead_schema::SchemaRef;
1127    use std::io::Write as _;
1128    use tempfile::TempDir;
1129
1130    fn pin(s: &str) -> SchemaRef {
1131        s.parse().unwrap()
1132    }
1133
1134    fn folder_mount(mem: &str, path: PathBuf) -> Mount {
1135        Mount {
1136            mem: mem.to_string(),
1137            schema: Some(pin("default@1.0.0")),
1138            storage: MountStorage::Folder { path },
1139            capability: MountCapability::Write,
1140            lifecycle: MountLifecycle::Eager,
1141            cross_linkable: true,
1142            migration_target: None,
1143        }
1144    }
1145
1146    fn write_workspace_toml(workspace_root: &Path, body: &str) {
1147        let path = FileWorkspaceStore::workspace_toml_path(workspace_root);
1148        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1149        std::fs::write(path, body).unwrap();
1150    }
1151
1152    #[test]
1153    fn load_returns_not_initialised_when_memstead_dir_absent() {
1154        let tmp = TempDir::new().unwrap();
1155        let store = FileWorkspaceStore::new();
1156        let err = store.load(tmp.path()).unwrap_err();
1157        assert!(matches!(err, StoreError::NotInitialised { .. }));
1158    }
1159
1160    /// The [`parse_workspace_settings`] helper reads only
1161    /// `.memstead/workspace.toml` and returns a fresh `WorkspaceSettings`.
1162    /// MCP-driven policy mutations call this after writing to disk
1163    /// to refresh the engine's in-memory cache without re-loading
1164    /// the engine-managed `mounts.json`.
1165    #[test]
1166    fn parse_workspace_settings_reflects_cross_mem_links_edit() {
1167        let tmp = TempDir::new().unwrap();
1168        write_workspace_toml(
1169            tmp.path(),
1170            r#"
1171format = "memstead-git-branch-2"
1172
1173[persistence_adapter]
1174name = "file-two-layer"
1175
1176[cross_mem_links]
1177team-a = ["team-b"]
1178"#,
1179        );
1180        let settings = super::parse_workspace_settings(tmp.path()).unwrap();
1181        assert!(
1182            settings.cross_mem_links.contains_key("team-a"),
1183            "initial parse must surface the team-a grant; got {:?}",
1184            settings.cross_mem_links
1185        );
1186
1187        // Mutate the file (simulating `workspace_config_edit::revoke_cross_link`).
1188        write_workspace_toml(
1189            tmp.path(),
1190            r#"
1191format = "memstead-git-branch-2"
1192
1193[persistence_adapter]
1194name = "file-two-layer"
1195
1196[cross_mem_links]
1197"#,
1198        );
1199        let refreshed = super::parse_workspace_settings(tmp.path()).unwrap();
1200        assert!(
1201            refreshed.cross_mem_links.is_empty(),
1202            "refreshed parse must drop the team-a grant; got {:?}",
1203            refreshed.cross_mem_links
1204        );
1205    }
1206
1207    /// `parse_workspace_settings` surfaces
1208    /// `[[mem_management.create]]` / `[[mem_management.delete]]`
1209    /// rules so the engine's allowlist gate sees the post-mutation
1210    /// state immediately.
1211    #[test]
1212    fn parse_workspace_settings_reflects_allowlist_edit() {
1213        let tmp = TempDir::new().unwrap();
1214        write_workspace_toml(
1215            tmp.path(),
1216            r#"
1217format = "memstead-git-branch-2"
1218
1219[persistence_adapter]
1220name = "file-two-layer"
1221"#,
1222        );
1223        let initial = super::parse_workspace_settings(tmp.path()).unwrap();
1224        assert!(initial.mem_create_rules.is_empty());
1225
1226        // Mutate (simulating `workspace_config_edit::add_create_rule`).
1227        write_workspace_toml(
1228            tmp.path(),
1229            r#"
1230format = "memstead-git-branch-2"
1231
1232[persistence_adapter]
1233name = "file-two-layer"
1234
1235[[mem_management.create]]
1236pattern = "test-*"
1237schemas = ["default@1.0.0"]
1238"#,
1239        );
1240        let refreshed = super::parse_workspace_settings(tmp.path()).unwrap();
1241        assert_eq!(refreshed.mem_create_rules.len(), 1);
1242        assert_eq!(refreshed.mem_create_rules[0].pattern, "test-*");
1243    }
1244
1245    #[test]
1246    fn load_returns_not_initialised_when_workspace_toml_missing() {
1247        let tmp = TempDir::new().unwrap();
1248        std::fs::create_dir_all(tmp.path().join(".memstead")).unwrap();
1249        let store = FileWorkspaceStore::new();
1250        let err = store.load(tmp.path()).unwrap_err();
1251        assert!(matches!(err, StoreError::NotInitialised { .. }));
1252    }
1253
1254    #[test]
1255    fn load_with_no_mounts_yields_empty_mount_list() {
1256        let tmp = TempDir::new().unwrap();
1257        write_workspace_toml(
1258            tmp.path(),
1259            r#"
1260format = "memstead-git-branch-2"
1261
1262[persistence_adapter]
1263name = "file-two-layer"
1264"#,
1265        );
1266        let store = FileWorkspaceStore::new();
1267        let workspace = store.load(tmp.path()).unwrap();
1268        assert!(workspace.mounts.is_empty());
1269    }
1270
1271    #[test]
1272    fn load_with_no_mem_management_yields_empty_settings() {
1273        // Workspace.toml without a `[mem_management]` section
1274        // produces the default empty settings — mirrors full's
1275        // behaviour where missing rules mean "no agent-driven
1276        // mem create / delete allowed".
1277        let tmp = TempDir::new().unwrap();
1278        write_workspace_toml(
1279            tmp.path(),
1280            r#"
1281format = "memstead-git-branch-2"
1282
1283[persistence_adapter]
1284name = "file-two-layer"
1285"#,
1286        );
1287        let store = FileWorkspaceStore::new();
1288        let workspace = store.load(tmp.path()).unwrap();
1289        assert!(workspace.settings.mem_create_rules.is_empty());
1290        assert!(workspace.settings.mem_delete_rules.is_empty());
1291        assert!(workspace.settings.cross_mem_links.is_empty());
1292    }
1293
1294    #[test]
1295    fn load_picks_up_cross_mem_links_wildcard_and_list() {
1296        // [cross_mem_links] is parsed via CrossLinkValue::parse_toml
1297        // to handle the wildcard ("*") vs allowlist ([...]) shape that
1298        // serde untagged-enum decode can't express. Both shapes round
1299        // through to WorkspaceSettings.cross_mem_links.
1300        use memstead_schema::workspace_config::CrossLinkValue;
1301        let tmp = TempDir::new().unwrap();
1302        write_workspace_toml(
1303            tmp.path(),
1304            r#"
1305format = "memstead-git-branch-2"
1306
1307[persistence_adapter]
1308name = "file-two-layer"
1309
1310[cross_mem_links]
1311specs = "*"
1312engine = ["specs", "macos"]
1313locked = []
1314"#,
1315        );
1316        let store = FileWorkspaceStore::new();
1317        let workspace = store.load(tmp.path()).unwrap();
1318        let cvl = &workspace.settings.cross_mem_links;
1319        assert_eq!(cvl.len(), 3);
1320        assert_eq!(cvl.get("specs"), Some(&CrossLinkValue::Wildcard));
1321        assert_eq!(
1322            cvl.get("engine"),
1323            Some(&CrossLinkValue::List(vec![
1324                "specs".to_string(),
1325                "macos".to_string()
1326            ]))
1327        );
1328        assert_eq!(cvl.get("locked"), Some(&CrossLinkValue::List(vec![])));
1329    }
1330
1331    #[test]
1332    fn load_rejects_cross_mem_links_mixed_wildcard_and_names() {
1333        // The shared parser rejects `["*", "specs"]` — wildcard must
1334        // be the sole entry. The schema-crate's typed error lifts via
1335        // StoreError::Parse so the operator-facing error names the
1336        // exact key.
1337        let tmp = TempDir::new().unwrap();
1338        write_workspace_toml(
1339            tmp.path(),
1340            r#"
1341format = "memstead-git-branch-2"
1342
1343[persistence_adapter]
1344name = "file-two-layer"
1345
1346[cross_mem_links]
1347specs = ["*", "engine"]
1348"#,
1349        );
1350        let store = FileWorkspaceStore::new();
1351        let err = store.load(tmp.path()).unwrap_err();
1352        match err {
1353            StoreError::Parse { message, .. } => {
1354                assert!(message.contains("[cross_mem_links].specs"));
1355                assert!(message.contains("wildcard"));
1356            }
1357            other => panic!("expected StoreError::Parse, got {other:?}"),
1358        }
1359    }
1360
1361    #[test]
1362    fn load_picks_up_default_cross_links_on_create_rule() {
1363        // CreateRule.default_cross_links uses the same CrossLinkValue
1364        // parser. A rule with `default_cross_links = "*"` lifts to
1365        // CreateRuleSetting.default_cross_links = Some(Wildcard).
1366        use memstead_schema::workspace_config::CrossLinkValue;
1367        let tmp = TempDir::new().unwrap();
1368        write_workspace_toml(
1369            tmp.path(),
1370            r#"
1371format = "memstead-git-branch-2"
1372
1373[persistence_adapter]
1374name = "file-two-layer"
1375
1376[[mem_management.create]]
1377pattern = "exec-*"
1378schemas = ["default"]
1379default_cross_links = "*"
1380"#,
1381        );
1382        let store = FileWorkspaceStore::new();
1383        let workspace = store.load(tmp.path()).unwrap();
1384        let rule = &workspace.settings.mem_create_rules[0];
1385        assert_eq!(rule.pattern, "exec-*");
1386        assert_eq!(rule.default_cross_links, Some(CrossLinkValue::Wildcard));
1387    }
1388
1389    #[test]
1390    fn load_picks_up_mem_management_create_and_delete_rules() {
1391        // Operator-edited `[mem_management]` section flows through
1392        // FileWorkspaceStore::load into Workspace.settings; the
1393        // engine layer then propagates via Engine::set_settings.
1394        let tmp = TempDir::new().unwrap();
1395        write_workspace_toml(
1396            tmp.path(),
1397            r#"
1398format = "memstead-git-branch-2"
1399
1400[persistence_adapter]
1401name = "file-two-layer"
1402
1403[[mem_management.create]]
1404pattern = "exec-*"
1405schemas = ["default@1.0.0", "*"]
1406
1407[[mem_management.create]]
1408pattern = "scratch-*"
1409schemas = ["default"]
1410
1411[[mem_management.delete]]
1412pattern = "exec-*"
1413"#,
1414        );
1415        let store = FileWorkspaceStore::new();
1416        let workspace = store.load(tmp.path()).unwrap();
1417        assert_eq!(workspace.settings.mem_create_rules.len(), 2);
1418        assert_eq!(workspace.settings.mem_create_rules[0].pattern, "exec-*");
1419        assert_eq!(
1420            workspace.settings.mem_create_rules[0].schemas,
1421            vec!["default@1.0.0".to_string(), "*".to_string()]
1422        );
1423        assert_eq!(workspace.settings.mem_create_rules[1].pattern, "scratch-*");
1424        assert_eq!(workspace.settings.mem_delete_rules.len(), 1);
1425        assert_eq!(workspace.settings.mem_delete_rules[0].pattern, "exec-*");
1426    }
1427
1428    /// Dual-pin state survives the store round-trip: a mount carrying
1429    /// `migration_target` writes it to `mounts.json` and reads it
1430    /// back; settled mounts' entries stay byte-compatible (the key is
1431    /// skipped when `None`).
1432    #[test]
1433    fn save_state_round_trips_migration_target() {
1434        let tmp = TempDir::new().unwrap();
1435        write_workspace_toml(
1436            tmp.path(),
1437            "\nformat = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
1438        );
1439        let store = FileWorkspaceStore::new();
1440        let mut migrating = folder_mount("specs", PathBuf::from("/work/mem"));
1441        migrating.migration_target = Some(pin("mig-b@0.1.0"));
1442        let settled = folder_mount("other", PathBuf::from("/work/other"));
1443        let original = Workspace {
1444            mounts: vec![migrating, settled],
1445            settings: WorkspaceSettings::default(),
1446        };
1447        store.save_state(tmp.path(), &original).unwrap();
1448        let raw =
1449            std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
1450        assert!(
1451            raw.contains("mig-b@0.1.0"),
1452            "migration_target must persist: {raw}"
1453        );
1454        assert_eq!(
1455            raw.matches("migration_target").count(),
1456            1,
1457            "settled mounts must omit the key entirely: {raw}"
1458        );
1459        let loaded = store.load(tmp.path()).unwrap();
1460        assert_eq!(loaded.mounts[0].migration_target, Some(pin("mig-b@0.1.0")));
1461        assert_eq!(loaded.mounts[1].migration_target, None);
1462    }
1463
1464    #[test]
1465    fn save_state_then_load_round_trips_mount_list() {
1466        let tmp = TempDir::new().unwrap();
1467        write_workspace_toml(
1468            tmp.path(),
1469            r#"
1470format = "memstead-git-branch-2"
1471
1472[persistence_adapter]
1473name = "file-two-layer"
1474"#,
1475        );
1476        let store = FileWorkspaceStore::new();
1477        let original = Workspace {
1478            mounts: vec![
1479                folder_mount("specs", PathBuf::from("/work/mem")),
1480                Mount {
1481                    mem: "engine".to_string(),
1482                    schema: Some(pin("default@1.0.0")),
1483                    storage: MountStorage::GitBranch {
1484                        gitdir: PathBuf::from("/work/mem-repo/.git"),
1485                        branch: "engine".to_string(),
1486                    },
1487                    capability: MountCapability::Write,
1488                    lifecycle: MountLifecycle::Eager,
1489                    cross_linkable: true,
1490                    migration_target: None,
1491                },
1492                Mount {
1493                    mem: "external".to_string(),
1494                    schema: Some(pin("default@1.0.0")),
1495                    storage: MountStorage::Archive {
1496                        path: PathBuf::from("/deps/external.mem"),
1497                    },
1498                    capability: MountCapability::ReadOnly,
1499                    lifecycle: MountLifecycle::Lazy,
1500                    cross_linkable: false,
1501                    migration_target: None,
1502                },
1503            ],
1504            settings: WorkspaceSettings::default(),
1505        };
1506        store.save_state(tmp.path(), &original).unwrap();
1507
1508        // The mounts.json file lives where we expect.
1509        assert!(FileWorkspaceStore::mounts_json_path(tmp.path()).is_file());
1510
1511        let reloaded = store.load(tmp.path()).unwrap();
1512        assert_eq!(reloaded.mounts.len(), original.mounts.len());
1513        for (a, b) in reloaded.mounts.iter().zip(original.mounts.iter()) {
1514            assert_eq!(a.mem, b.mem);
1515            assert_eq!(a.schema, b.schema);
1516            assert_eq!(a.capability, b.capability);
1517            assert_eq!(a.lifecycle, b.lifecycle);
1518            assert_eq!(a.cross_linkable, b.cross_linkable);
1519            assert_eq!(a.storage, b.storage);
1520        }
1521    }
1522
1523    #[test]
1524    fn save_state_round_trips_unset_schema_assertion() {
1525        // `Mount.schema = None` (no expectation assertion) must survive a
1526        // mounts.json round-trip and omit the `schema` key on the wire —
1527        // the authoritative pin lives in the mem's backend config, not
1528        // in the mount record.
1529        let tmp = TempDir::new().unwrap();
1530        write_workspace_toml(
1531            tmp.path(),
1532            r#"
1533format = "memstead-git-branch-2"
1534
1535[persistence_adapter]
1536name = "file-two-layer"
1537"#,
1538        );
1539        let store = FileWorkspaceStore::new();
1540        let original = Workspace {
1541            mounts: vec![Mount {
1542                mem: "foreign".to_string(),
1543                schema: None,
1544                storage: MountStorage::Folder {
1545                    path: tmp.path().join("foreign"),
1546                },
1547                capability: MountCapability::ReadOnly,
1548                lifecycle: MountLifecycle::Eager,
1549                cross_linkable: false,
1550                migration_target: None,
1551            }],
1552            settings: WorkspaceSettings::default(),
1553        };
1554        store.save_state(tmp.path(), &original).unwrap();
1555
1556        // The wire form omits the `schema` key entirely (skip-on-None).
1557        let raw =
1558            std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
1559        assert!(
1560            !raw.contains("\"schema\""),
1561            "unset schema assertion must omit the key on the wire; got:\n{raw}"
1562        );
1563
1564        // And it reloads as `None`.
1565        let reloaded = store.load(tmp.path()).unwrap();
1566        assert_eq!(reloaded.mounts.len(), 1);
1567        assert_eq!(reloaded.mounts[0].schema, None);
1568    }
1569
1570    #[test]
1571    fn save_state_does_not_touch_workspace_toml() {
1572        let tmp = TempDir::new().unwrap();
1573        let original_body = r#"
1574format = "memstead-git-branch-2"
1575
1576[persistence_adapter]
1577name = "file-two-layer"
1578"#;
1579        write_workspace_toml(tmp.path(), original_body);
1580        let store = FileWorkspaceStore::new();
1581        let workspace = Workspace::default();
1582        store.save_state(tmp.path(), &workspace).unwrap();
1583        // Operator's TOML untouched.
1584        let toml_after =
1585            std::fs::read_to_string(FileWorkspaceStore::workspace_toml_path(tmp.path())).unwrap();
1586        assert_eq!(toml_after, original_body);
1587    }
1588
1589    #[test]
1590    fn save_state_writes_paths_relative_to_workspace_root() {
1591        let tmp = TempDir::new().unwrap();
1592        write_workspace_toml(
1593            tmp.path(),
1594            r#"
1595format = "memstead-git-branch-2"
1596
1597[persistence_adapter]
1598name = "file-two-layer"
1599"#,
1600        );
1601        let store = FileWorkspaceStore::new();
1602        let workspace = Workspace {
1603            mounts: vec![
1604                Mount {
1605                    mem: "engine".to_string(),
1606                    schema: Some(pin("default@1.0.0")),
1607                    storage: MountStorage::GitBranch {
1608                        gitdir: tmp.path().join("mem-repo").join(".git"),
1609                        branch: "engine".to_string(),
1610                    },
1611                    capability: MountCapability::Write,
1612                    lifecycle: MountLifecycle::Eager,
1613                    cross_linkable: true,
1614                    migration_target: None,
1615                },
1616                Mount {
1617                    mem: "external".to_string(),
1618                    schema: Some(pin("default@1.0.0")),
1619                    storage: MountStorage::Archive {
1620                        path: PathBuf::from("/global/cache/external.mem"),
1621                    },
1622                    capability: MountCapability::ReadOnly,
1623                    lifecycle: MountLifecycle::Lazy,
1624                    cross_linkable: false,
1625                    migration_target: None,
1626                },
1627            ],
1628            settings: WorkspaceSettings::default(),
1629        };
1630        store.save_state(tmp.path(), &workspace).unwrap();
1631
1632        let on_disk =
1633            std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
1634        // Format bumped to V2.
1635        assert!(on_disk.contains("\"memstead-mounts-3\""));
1636        // In-workspace path stored relative — no absolute prefix bake-in.
1637        assert!(
1638            on_disk.contains("\"mem-repo/.git\""),
1639            "expected relative gitdir, got: {on_disk}"
1640        );
1641        assert!(
1642            !on_disk.contains(tmp.path().to_str().unwrap()),
1643            "in-workspace path should not include the absolute tmp prefix: {on_disk}"
1644        );
1645        // Out-of-workspace path kept absolute (fallback for shared caches / external archives).
1646        assert!(on_disk.contains("\"/global/cache/external.mem\""));
1647
1648        // Re-load reconstructs absolute paths.
1649        let reloaded = store.load(tmp.path()).unwrap();
1650        match &reloaded.mounts[0].storage {
1651            MountStorage::GitBranch { gitdir, .. } => {
1652                assert_eq!(gitdir, &tmp.path().join("mem-repo").join(".git"));
1653            }
1654            other => panic!("expected GitBranch storage, got {other:?}"),
1655        }
1656        match &reloaded.mounts[1].storage {
1657            MountStorage::Archive { path } => {
1658                assert_eq!(path, &PathBuf::from("/global/cache/external.mem"));
1659            }
1660            other => panic!("expected Archive storage, got {other:?}"),
1661        }
1662    }
1663
1664    #[test]
1665    fn load_absolute_inside_root_path_then_save_rewrites_relative() {
1666        let tmp = TempDir::new().unwrap();
1667        write_workspace_toml(
1668            tmp.path(),
1669            r#"
1670format = "memstead-git-branch-2"
1671
1672[persistence_adapter]
1673name = "file-two-layer"
1674"#,
1675        );
1676        // Hand-write a mounts.json carrying an absolute gitdir that
1677        // lives inside this workspace_root — simulates the "committed
1678        // by another operator's home dir" failure mode that motivated
1679        // relative serialisation.
1680        let mounts_path = FileWorkspaceStore::mounts_json_path(tmp.path());
1681        std::fs::create_dir_all(mounts_path.parent().unwrap()).unwrap();
1682        let abs_gitdir = tmp.path().join("mem-repo").join(".git");
1683        let mounts_body = format!(
1684            r#"{{
1685  "format": "memstead-mounts-3",
1686  "mounts": [
1687    {{
1688      "mem": "engine",
1689      "schema": "default@1.0.0",
1690      "storage": {{
1691        "type": "git-branch",
1692        "gitdir": "{}",
1693        "branch": "engine"
1694      }},
1695      "capability": "write",
1696      "lifecycle": "eager",
1697      "cross_linkable": true
1698    }}
1699  ]
1700}}"#,
1701            abs_gitdir.to_str().unwrap()
1702        );
1703        std::fs::write(&mounts_path, &mounts_body).unwrap();
1704
1705        let store = FileWorkspaceStore::new();
1706        // The reader accepts the file; the absolute path round-trips
1707        // untouched (it's already absolute).
1708        let workspace = store.load(tmp.path()).unwrap();
1709        match &workspace.mounts[0].storage {
1710            MountStorage::GitBranch { gitdir, .. } => assert_eq!(gitdir, &abs_gitdir),
1711            other => panic!("expected GitBranch storage, got {other:?}"),
1712        }
1713
1714        // Saving the same workspace rewrites the file with a relative
1715        // path — self-healing, no explicit command needed.
1716        store.save_state(tmp.path(), &workspace).unwrap();
1717        let on_disk = std::fs::read_to_string(&mounts_path).unwrap();
1718        assert!(on_disk.contains("\"memstead-mounts-3\""));
1719        assert!(on_disk.contains("\"mem-repo/.git\""));
1720        assert!(!on_disk.contains(tmp.path().to_str().unwrap()));
1721    }
1722
1723    /// Item 03 round-trip: writing a `MountStorage::GitBranch` mount
1724    /// whose `branch` already carries the canonical `refs/heads/<leaf>`
1725    /// form serialises that exact string into `mounts.json` (no
1726    /// rewrite, no truncation), and reading the file back produces a
1727    /// `Mount` whose in-memory `branch` equals the input verbatim. The
1728    /// write path is the one source of truth for the on-disk shape — a
1729    /// regression that re-introduces short-form writes would surface
1730    /// here as a mismatch against `refs/heads/demo/engine`.
1731    #[test]
1732    fn save_state_preserves_refs_heads_branch_form() {
1733        let tmp = TempDir::new().unwrap();
1734        write_workspace_toml(
1735            tmp.path(),
1736            r#"
1737format = "memstead-git-branch-2"
1738
1739[persistence_adapter]
1740name = "file-two-layer"
1741"#,
1742        );
1743        let store = FileWorkspaceStore::new();
1744        let original = Workspace {
1745            mounts: vec![Mount {
1746                mem: "engine".to_string(),
1747                schema: Some(pin("default@1.0.0")),
1748                storage: MountStorage::GitBranch {
1749                    gitdir: tmp.path().join("mem-repo").join(".git"),
1750                    branch: "refs/heads/demo/engine".to_string(),
1751                },
1752                capability: MountCapability::Write,
1753                lifecycle: MountLifecycle::Eager,
1754                cross_linkable: true,
1755                migration_target: None,
1756            }],
1757            settings: WorkspaceSettings::default(),
1758        };
1759        store.save_state(tmp.path(), &original).unwrap();
1760
1761        let on_disk =
1762            std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
1763        assert!(
1764            on_disk.contains("\"branch\": \"refs/heads/demo/engine\""),
1765            "expected fully-qualified ref on disk, got: {on_disk}"
1766        );
1767
1768        let reloaded = store.load(tmp.path()).unwrap();
1769        match &reloaded.mounts[0].storage {
1770            MountStorage::GitBranch { branch, .. } => {
1771                assert_eq!(branch, "refs/heads/demo/engine");
1772            }
1773            other => panic!("expected GitBranch storage, got {other:?}"),
1774        }
1775    }
1776
1777    /// Item 03 reader tolerance: a hand-written legacy `mounts.json`
1778    /// whose `branch` field carries the short-form leaf (no
1779    /// `refs/heads/` prefix) loads without error, and the in-memory
1780    /// `Mount` carries the input string intact. The reader does not
1781    /// silently normalise — backend factories are responsible for
1782    /// fully-qualifying short forms at instantiation time. This pin
1783    /// guards against an over-eager normaliser landing on the read
1784    /// path and masking out the legacy shape that older committed
1785    /// `mounts.json` files used to carry.
1786    #[test]
1787    fn load_preserves_short_form_branch_without_rewrite() {
1788        let tmp = TempDir::new().unwrap();
1789        write_workspace_toml(
1790            tmp.path(),
1791            r#"
1792format = "memstead-git-branch-2"
1793
1794[persistence_adapter]
1795name = "file-two-layer"
1796"#,
1797        );
1798        let mounts_path = FileWorkspaceStore::mounts_json_path(tmp.path());
1799        std::fs::create_dir_all(mounts_path.parent().unwrap()).unwrap();
1800        std::fs::write(
1801            &mounts_path,
1802            r#"{
1803  "format": "memstead-mounts-3",
1804  "mounts": [
1805    {
1806      "mem": "engine",
1807      "schema": "default@1.0.0",
1808      "storage": {
1809        "type": "git-branch",
1810        "gitdir": "mem-repo/.git",
1811        "branch": "demo/engine"
1812      },
1813      "capability": "write",
1814      "lifecycle": "eager",
1815      "cross_linkable": true
1816    }
1817  ]
1818}"#,
1819        )
1820        .unwrap();
1821
1822        let store = FileWorkspaceStore::new();
1823        let workspace = store.load(tmp.path()).unwrap();
1824        match &workspace.mounts[0].storage {
1825            MountStorage::GitBranch { branch, .. } => {
1826                assert_eq!(
1827                    branch, "demo/engine",
1828                    "reader must not silently rewrite short-form branch"
1829                );
1830            }
1831            other => panic!("expected GitBranch storage, got {other:?}"),
1832        }
1833    }
1834
1835    #[test]
1836    fn load_rejects_format_version_mismatch_on_toml() {
1837        let tmp = TempDir::new().unwrap();
1838        write_workspace_toml(
1839            tmp.path(),
1840            r#"
1841format = "memstead-git-branch-99"
1842
1843[persistence_adapter]
1844name = "file-two-layer"
1845"#,
1846        );
1847        let store = FileWorkspaceStore::new();
1848        let err = store.load(tmp.path()).unwrap_err();
1849        match err {
1850            StoreError::FormatMismatch {
1851                expected, found, ..
1852            } => {
1853                assert_eq!(expected, "memstead-git-branch-2");
1854                assert_eq!(found, "memstead-git-branch-99");
1855            }
1856            other => panic!("expected FormatMismatch, got {other:?}"),
1857        }
1858    }
1859
1860    #[test]
1861    fn load_rejects_format_version_mismatch_on_mounts_json() {
1862        let tmp = TempDir::new().unwrap();
1863        write_workspace_toml(
1864            tmp.path(),
1865            r#"
1866format = "memstead-git-branch-2"
1867
1868[persistence_adapter]
1869name = "file-two-layer"
1870"#,
1871        );
1872        let mounts_path = FileWorkspaceStore::mounts_json_path(tmp.path());
1873        std::fs::create_dir_all(mounts_path.parent().unwrap()).unwrap();
1874        std::fs::write(
1875            &mounts_path,
1876            r#"{ "format": "memstead-mounts-99", "mounts": [] }"#,
1877        )
1878        .unwrap();
1879        let store = FileWorkspaceStore::new();
1880        let err = store.load(tmp.path()).unwrap_err();
1881        assert!(matches!(err, StoreError::FormatMismatch { .. }));
1882    }
1883
1884    /// A pre-rename workspace.toml (format V1) refuses with the typed
1885    /// LegacyLayout error — it must not boot empty or half-parsed.
1886    #[test]
1887    fn load_refuses_pre_rename_toml_as_legacy_layout() {
1888        let tmp = TempDir::new().unwrap();
1889        write_workspace_toml(
1890            tmp.path(),
1891            r#"
1892format = "memstead-git-branch-1"
1893
1894[persistence_adapter]
1895name = "file-two-layer"
1896"#,
1897        );
1898        let store = FileWorkspaceStore::new();
1899        let err = store.load(tmp.path()).unwrap_err();
1900        match err {
1901            StoreError::LegacyLayout { found, .. } => {
1902                assert_eq!(found, "memstead-git-branch-1");
1903            }
1904            other => panic!("expected LegacyLayout, got {other:?}"),
1905        }
1906    }
1907
1908    /// Pre-rename mounts.json formats refuse with LegacyLayout even
1909    /// though their records no longer deserialise (old unit-noun
1910    /// field name) — the format probe must win over the record-level
1911    /// parse error so the agent sees the migration hint, not a serde
1912    /// message. The fixture's record deliberately lacks the `mem`
1913    /// field to prove the full parse is never reached.
1914    #[test]
1915    fn load_refuses_pre_rename_mounts_json_as_legacy_layout() {
1916        for legacy in ["memstead-mounts-1", "memstead-mounts-2"] {
1917            let tmp = TempDir::new().unwrap();
1918            write_workspace_toml(
1919                tmp.path(),
1920                r#"
1921format = "memstead-git-branch-2"
1922
1923[persistence_adapter]
1924name = "file-two-layer"
1925"#,
1926            );
1927            let mounts_path = FileWorkspaceStore::mounts_json_path(tmp.path());
1928            std::fs::create_dir_all(mounts_path.parent().unwrap()).unwrap();
1929            std::fs::write(
1930                &mounts_path,
1931                format!(
1932                    r#"{{ "format": "{legacy}", "mounts": [{{ "unit": "notes", "storage": {{ "type": "folder", "path": "notes" }}, "capability": "write", "lifecycle": "eager", "cross_linkable": true }}] }}"#
1933                ),
1934            )
1935            .unwrap();
1936            let store = FileWorkspaceStore::new();
1937            let err = store.load(tmp.path()).unwrap_err();
1938            match err {
1939                StoreError::LegacyLayout { found, .. } => assert_eq!(found, legacy),
1940                other => panic!("expected LegacyLayout for {legacy}, got {other:?}"),
1941            }
1942        }
1943    }
1944
1945    #[test]
1946    fn load_rejects_invalid_toml() {
1947        let tmp = TempDir::new().unwrap();
1948        write_workspace_toml(tmp.path(), "this is not = valid = toml");
1949        let store = FileWorkspaceStore::new();
1950        let err = store.load(tmp.path()).unwrap_err();
1951        assert!(matches!(err, StoreError::Parse { .. }));
1952    }
1953
1954    #[test]
1955    fn load_rejects_unknown_top_level_key() {
1956        // The workspace config's contract (and its shipped example's
1957        // claim) is that typos never pass silently — at the top level,
1958        // not just inside [mcp]/[mutations].
1959        let tmp = TempDir::new().unwrap();
1960        write_workspace_toml(
1961            tmp.path(),
1962            "format = \"memstead-git-branch-2\"\nnonexistent_key = true\n",
1963        );
1964        let store = FileWorkspaceStore::new();
1965        let err = store.load(tmp.path()).unwrap_err();
1966        match err {
1967            StoreError::Parse { message, .. } => {
1968                assert!(
1969                    message.contains("nonexistent_key"),
1970                    "refusal must name the unknown key: {message}"
1971                );
1972            }
1973            other => panic!("expected Parse error, got {other:?}"),
1974        }
1975    }
1976
1977    #[test]
1978    fn instantiate_local_backend_handles_folder_archive_and_in_memory() {
1979        let tmp = TempDir::new().unwrap();
1980        let folder = folder_mount("local", tmp.path().to_path_buf());
1981        let archive_path = tmp.path().join("ext.mem");
1982        // Make a minimal valid zip so the archive backend can open it.
1983        let f = std::fs::File::create(&archive_path).unwrap();
1984        let mut w = zip::ZipWriter::new(f);
1985        w.start_file("a.md", zip::write::SimpleFileOptions::default())
1986            .unwrap();
1987        w.write_all(b"# a").unwrap();
1988        w.finish().unwrap();
1989        let archive = Mount {
1990            mem: "external".to_string(),
1991            schema: Some(pin("default@1.0.0")),
1992            storage: MountStorage::Archive { path: archive_path },
1993            capability: MountCapability::ReadOnly,
1994            lifecycle: MountLifecycle::Lazy,
1995            cross_linkable: false,
1996            migration_target: None,
1997        };
1998        let in_memory = Mount {
1999            mem: "session".to_string(),
2000            schema: Some(pin("default@1.0.0")),
2001            storage: MountStorage::InMemory,
2002            capability: MountCapability::Write,
2003            lifecycle: MountLifecycle::Eager,
2004            cross_linkable: true,
2005            migration_target: None,
2006        };
2007
2008        let _: Box<dyn MemBackend> = instantiate_local_backend(&folder).unwrap();
2009        let _: Box<dyn MemBackend> = instantiate_local_backend(&archive).unwrap();
2010        // The in-memory variant is a local backend: no factory needed,
2011        // no path, materialises directly.
2012        let _: Box<dyn MemBackend> = instantiate_local_backend(&in_memory).unwrap();
2013    }
2014
2015    /// AC3 (plan 01): the in-memory storage variant round-trips through
2016    /// `mounts.json` and its wire shape is unambiguous — it serialises
2017    /// as the bare `{"type":"in-memory"}` tag and never parses as one
2018    /// of the path-carrying variants, nor they as it.
2019    #[test]
2020    fn save_state_round_trips_in_memory_variant_unambiguously() {
2021        let tmp = TempDir::new().unwrap();
2022        write_workspace_toml(
2023            tmp.path(),
2024            r#"
2025format = "memstead-git-branch-2"
2026
2027[persistence_adapter]
2028name = "file-two-layer"
2029"#,
2030        );
2031        let store = FileWorkspaceStore::new();
2032        let original = Workspace {
2033            mounts: vec![
2034                folder_mount("local", PathBuf::from("/work/mem")),
2035                Mount {
2036                    mem: "session".to_string(),
2037                    schema: Some(pin("default@1.0.0")),
2038                    storage: MountStorage::InMemory,
2039                    capability: MountCapability::Write,
2040                    lifecycle: MountLifecycle::Eager,
2041                    cross_linkable: true,
2042                    migration_target: None,
2043                },
2044            ],
2045            settings: WorkspaceSettings::default(),
2046        };
2047        store.save_state(tmp.path(), &original).unwrap();
2048
2049        // On the wire it is the bare tag — no `path`, no `gitdir`.
2050        let raw =
2051            std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
2052        assert!(raw.contains("\"type\": \"in-memory\""), "got: {raw}");
2053
2054        let reloaded = store.load(tmp.path()).unwrap();
2055        assert_eq!(reloaded.mounts.len(), 2);
2056        // The in-memory mount round-trips back to exactly InMemory —
2057        // not silently reinterpreted as a folder/archive/git variant.
2058        let session = reloaded
2059            .mounts
2060            .iter()
2061            .find(|m| m.mem == "session")
2062            .expect("session mount survives reload");
2063        assert_eq!(session.storage, MountStorage::InMemory);
2064        // And the sibling folder mount is untouched — the two wire
2065        // shapes do not bleed into each other.
2066        let local = reloaded.mounts.iter().find(|m| m.mem == "local").unwrap();
2067        assert!(matches!(local.storage, MountStorage::Folder { .. }));
2068    }
2069
2070    #[test]
2071    fn instantiate_local_backend_rejects_git_branch_with_typed_error() {
2072        let mount = Mount {
2073            mem: "engine".to_string(),
2074            schema: Some(pin("default@1.0.0")),
2075            storage: MountStorage::GitBranch {
2076                gitdir: PathBuf::from("/some/path/.git"),
2077                branch: "engine".to_string(),
2078            },
2079            capability: MountCapability::Write,
2080            lifecycle: MountLifecycle::Eager,
2081            cross_linkable: true,
2082            migration_target: None,
2083        };
2084        // `unwrap_err()` requires Box<dyn MemBackend> to be Debug;
2085        // matching on the Result keeps the test gix-free of that
2086        // bound while still asserting the typed error.
2087        match instantiate_local_backend(&mount) {
2088            Err(InstantiateError::GitBranchBackendUnavailable { mem }) => {
2089                assert_eq!(mem, "engine");
2090            }
2091            Ok(_) => panic!("expected GitBranchBackendUnavailable, got Ok"),
2092        }
2093    }
2094
2095    #[test]
2096    fn detect_layout_returns_empty_for_unrecognised_workspace() {
2097        let tmp = TempDir::new().unwrap();
2098        assert_eq!(detect_layout(tmp.path()), Layout::Empty);
2099    }
2100    #[test]
2101    fn detect_layout_returns_new_when_workspace_toml_present() {
2102        let tmp = TempDir::new().unwrap();
2103        write_workspace_toml(
2104            tmp.path(),
2105            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2106        );
2107        assert_eq!(detect_layout(tmp.path()), Layout::New);
2108    }
2109}