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