memstead_base/workspace.rs
1//! Workspace concept — first-class in `memstead-base` after the
2//! workspace-store rebuild.
3//!
4//! A [`Workspace`] is the operator-curated collection of mounts;
5//! each [`Mount`] attaches one mem to the workspace via a storage
6//! backend (folder / git-branch / archive). One mount = one mem:
7//! five mems living on five branches in one git-repo materialise as
8//! five mounts; the engine pools the gitdir handle internally for the
9//! shared backend rather than collapsing the conceptual mount.
10//!
11//! This module ships the data shapes only. The persistence adapter
12//! that materialises a `Workspace` from `.memstead/workspace.toml` +
13//! `.memstead/state/mounts.json` lands separately as the file-adapter
14//! sessions move forward; tests and in-memory builders construct
15//! `Workspace` directly without going through any adapter.
16//!
17//! Distinct from [`crate::mem::MemRouterSnapshot`], which is the
18//! engine's *runtime* snapshot of writable / visible mems. The
19//! engine derives a `MemRouterSnapshot` from a `Workspace` at boot;
20//! the two coexist while the rebuild is in flight.
21
22use std::collections::{BTreeMap, HashMap};
23use std::path::PathBuf;
24
25use memstead_schema::SchemaRef;
26use memstead_schema::workspace_config::CrossLinkValue;
27use serde::{Deserialize, Serialize};
28
29/// A single mem attachment in a [`Workspace`]. One mount = one
30/// mem. The schema pin is on the mount because per-mem schema
31/// resolution is fixed in code (local-storage → built-in → registry,
32/// with the storage layer owning where "local" lives — see the
33/// glossary's *Schema* entry); the mount carries which schema this
34/// mem expects, the backend resolves where the YAMLs come from.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Mount {
37 /// Operator-facing mem name within this workspace.
38 pub mem: String,
39 /// Optional *expectation assertion* about this mem's schema pin
40 /// (exact `<name>@<version>`). The authoritative pin is the mem's
41 /// own `MemConfig.schema` on its storage backend; boot/load
42 /// resolve from there. This field is a workspace-local cross-check —
43 /// useful for foreign or read-only mounts. `None` means "assert
44 /// nothing, trust the backend config". When `Some` and mismatching
45 /// the config pin, loading surfaces a `SchemaPinMismatch` finding
46 /// naming both values; neither is silently preferred. Resolution
47 /// falls back to this value only when the backend config carries no
48 /// pin.
49 pub schema: Option<SchemaRef>,
50 /// Backend-specific reference to the mem's content.
51 pub storage: MountStorage,
52 /// Read-only or writable attachment.
53 pub capability: MountCapability,
54 /// Eager (open the backend at engine start) or lazy (entity load
55 /// deferred to first read) — see [`MountLifecycle`] for the full
56 /// contract. Opt-in per mount.
57 pub lifecycle: MountLifecycle,
58 /// Whether other mounts in the same workspace may form
59 /// cross-mem edges into this mount. Workspace-level cross-mem
60 /// permission policy can override.
61 pub cross_linkable: bool,
62 /// In-flight schema migration target. `Some(target)` puts the
63 /// mem in dual-pin state: writes validate against `target`
64 /// (the engine's effective validation schema), reads stay
65 /// permissive, and `schema` remains the settled pin until every
66 /// entity is integral against the target — then the atomic
67 /// switch sets `schema = target` and clears this field in one
68 /// workspace-store write. Persisted so a long migration is
69 /// resumable across engine restarts.
70 pub migration_target: Option<SchemaRef>,
71}
72
73impl Mount {
74 /// Hierarchical organisational path for this mount, or `None` for
75 /// flat layout / non-hierarchical storage. Mirrors the
76 /// `MemCreateParams.path` create-side input — at delete time the
77 /// lifecycle candidate composes as `<mem_path>/<name>` (or
78 /// `<name>` alone when `None`) to match the create-side rule.
79 ///
80 /// Derivation: `MountStorage::GitBranch` carries the path in its
81 /// `branch` field. Tolerates both fully-qualified
82 /// `refs/heads/<mem_path>/<mem>` (the shape `create_mem`
83 /// produces) and bare `<mem_path>/<mem>` (the shape
84 /// `mounts.json` operator-edited entries carry) — full's
85 /// `instantiate_full_backend` already normalises both forms. Strip
86 /// the optional `refs/heads/` prefix and the trailing `<mem>`
87 /// leaf. `Folder` / `Archive` carry no hierarchical path on the
88 /// storage variant — runtime callers that know the create-time
89 /// `path` plumb it directly into the router via
90 /// `Engine::register_writable_mem`.
91 pub fn mem_path(&self) -> Option<String> {
92 match &self.storage {
93 MountStorage::GitBranch { branch, .. } => {
94 let leaf = branch
95 .strip_prefix("refs/heads/")
96 .unwrap_or(branch.as_str());
97 let after_leaf = leaf.strip_suffix(&self.mem)?;
98 let trimmed = after_leaf.trim_end_matches('/');
99 if trimmed.is_empty() {
100 None
101 } else {
102 Some(trimmed.to_string())
103 }
104 }
105 MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
106 None
107 }
108 }
109 }
110}
111
112/// Branch name of the mem-repo's unified engine ref — schemas plus
113/// per-mem configs in one tree. Not a mem: it has no mount, and the
114/// transport verbs that walk every ref (`push --all`) carry it by
115/// name.
116pub const MEMSTEAD_REF_BRANCH: &str = "__MEMSTEAD";
117
118/// Branch name of the mem-repo's check-ledger transport ref: one tree
119/// with `mems/<mem>/checks.jsonl` per mem, the mem's rows of the
120/// workspace check ledger as last published. Not a mem and not the
121/// ledger's home: the ledger stays the workspace file, and this ref
122/// is how its rows travel between machines with `push`, `fetch` and
123/// `pull` (the engine unions rows, never rewrites them). Never
124/// mounted; `status --remote` does not classify it.
125pub const MEMSTEAD_CHECKS_REF_BRANCH: &str = "__MEMSTEAD_CHECKS";
126
127/// The path of one mem's ledger rows on the checks transport ref.
128pub fn checks_ref_member_path(mem: &str) -> String {
129 format!("mems/{mem}/checks.jsonl")
130}
131
132/// A mount's declared branch as a fully-qualified local ref. The
133/// `branch` field tolerates both `refs/heads/<path>` (used verbatim,
134/// any `refs/` value is) and bare `<path>` (prefixed) — the same
135/// normalisation `instantiate_full_backend` applies. Every operation
136/// that needs the mem's local ref derives it from the declared branch
137/// through this function; nothing reconstructs a ref from the mem
138/// name.
139pub fn branch_full_ref(branch: &str) -> String {
140 if branch.starts_with("refs/") {
141 branch.to_string()
142 } else {
143 format!("refs/heads/{branch}")
144 }
145}
146
147/// A mount's declared branch as the short name remote-tracking refs
148/// use (`refs/remotes/<remote>/<short>`): the `refs/heads/` prefix
149/// stripped when present, the value verbatim otherwise.
150pub fn branch_short_name(branch: &str) -> &str {
151 branch.strip_prefix("refs/heads/").unwrap_or(branch)
152}
153
154/// Storage reference for a [`Mount`]. One variant per
155/// [`crate::backend::MemBackend`] implementation. New backends add
156/// a variant; the file-adapter learns to round-trip it.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum MountStorage {
159 /// Folder backend — mem lives as a directory tree on disk.
160 /// The mem root may be the workspace root itself (collapsed
161 /// single-mem form: `.memstead/config.json` at root, no `mems/`
162 /// subfolder) or a sibling mem subfolder.
163 Folder {
164 /// Absolute path to the mem root directory.
165 path: PathBuf,
166 },
167 /// Git-branch backend — mem lives as a branch in a mem-repo
168 /// gitdir. Multi-repo workspaces are supported by varying
169 /// `gitdir` across mounts (see the *Storage backend* glossary
170 /// entry's *per-mount git-repo* block for the trade-offs).
171 GitBranch {
172 /// Absolute path to the gitdir
173 /// (typically `<workspace>/mem-repo/.git`).
174 gitdir: PathBuf,
175 /// Branch name within the gitdir holding the mem content.
176 branch: String,
177 },
178 /// Archive backend — mem lives inside a sealed `.mem` zip archive.
179 /// Always read-only; mounts of this storage carry
180 /// [`MountCapability::ReadOnly`].
181 Archive {
182 /// Absolute path to the sealed archive file.
183 path: PathBuf,
184 },
185 /// In-memory backend — mem lives entirely in RAM, with no
186 /// filesystem path and no git. Created empty, dropped with the
187 /// engine, leaving no on-disk residue. Serves ephemeral
188 /// per-session playground mems. Carries no fields: there is
189 /// nothing to locate on disk, and the backend holds all state
190 /// itself (see [`crate::storage::InMemoryBackend`]).
191 InMemory,
192}
193
194impl MountStorage {
195 /// Stable kebab-case backend identifier surfaced in error envelopes
196 /// (e.g. `MARKDOWN_EXPORT_UNSUPPORTED_BACKEND`'s `active_backend`
197 /// detail) and in the on-disk `mounts.json` serialisation. The
198 /// kebab-case form matches the `MountStorageWire` `#[serde(tag,
199 /// rename_all = "kebab-case")]` tag.
200 pub fn backend_id(&self) -> &'static str {
201 match self {
202 MountStorage::Folder { .. } => "folder",
203 MountStorage::GitBranch { .. } => "git-branch",
204 MountStorage::Archive { .. } => "archive",
205 MountStorage::InMemory => "in-memory",
206 }
207 }
208
209 /// Whether writes (and, for read-only backends, the loaded content)
210 /// survive process restart / session-TTL eviction. `Folder`,
211 /// `GitBranch`, and `Archive` all live on disk and persist; only
212 /// `InMemory` is volatile — its state is dropped with the engine,
213 /// so a `write_id` it returns denotes nothing durable. This is the
214 /// fact the durability marker projects: derived from the storage
215 /// *kind*, not from `current_head()` (which is `None` for both
216 /// `Folder` and `InMemory` and so cannot tell them apart).
217 /// How the durability answer for this storage was arrived at.
218 ///
219 /// [`Self::is_durable`] answers from the storage KIND, which is a real
220 /// answer to a narrow question (does a write survive process restart)
221 /// and is routinely read as a broader one (is the write recorded
222 /// somewhere it could be recovered from). Callers cannot tell the two
223 /// apart from a bare boolean, so the basis travels with it.
224 /// The marker itself is unchanged and stays.
225 pub fn durability_basis(&self, head: Option<&str>) -> DurabilityBasis {
226 match self {
227 // A real commit object, named by a backend that HAS commits. The
228 // storage kind gates this on purpose: a folder backend's
229 // `current_head()` is its change ledger's last timestamp, not a
230 // commit, so keying only on "a head exists" reported `established`
231 // for every folder mem that had ever been written — strictly
232 // stronger than the mount-kind answer this field was added to
233 // qualify, which is the misreading it exists to prevent.
234 MountStorage::GitBranch { .. } if head.is_some_and(|h| !h.is_empty()) => {
235 DurabilityBasis::Established
236 }
237 _ => DurabilityBasis::InferredFromMountKind,
238 }
239 }
240
241 pub fn is_durable(&self) -> bool {
242 match self {
243 MountStorage::Folder { .. }
244 | MountStorage::GitBranch { .. }
245 | MountStorage::Archive { .. } => true,
246 MountStorage::InMemory => false,
247 }
248 }
249}
250
251/// Whether a durability answer was established or inferred.
252///
253/// The distinction exists because the engine's answer is derived from the
254/// mount kind, which is honest about surviving a restart and says nothing
255/// about the write having reached version control. A folder mem is the case
256/// that matters: its writes land on disk, so `durable` is true, and whether
257/// anything could recover them is a question the engine cannot answer at all.
258#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
259#[serde(rename_all = "kebab-case")]
260pub enum DurabilityBasis {
261 /// The backend named a real commit for this write, so it is recorded.
262 Established,
263 /// Read off the storage kind. True for surviving a restart; silent on
264 /// whether the write is recorded anywhere it could be recovered from.
265 InferredFromMountKind,
266}
267
268impl DurabilityBasis {
269 pub fn as_wire(&self) -> &'static str {
270 match self {
271 DurabilityBasis::Established => "established",
272 DurabilityBasis::InferredFromMountKind => "inferred-from-mount-kind",
273 }
274 }
275}
276
277/// What the workspace may do with a mount.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub enum MountCapability {
280 /// Mutations rejected — the engine surfaces a typed read-only
281 /// error before reaching the backend.
282 ReadOnly,
283 /// Full read + write.
284 Write,
285}
286
287/// When the mount's backend initialises.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub enum MountLifecycle {
290 /// Open the backend at engine start.
291 Eager,
292 /// Defer the ENTITY load until the first operation that needs the
293 /// mem. The metadata half (config, provenance, schema pin) still
294 /// resolves at boot, so the mem is on the roster with its pin —
295 /// present, never silently absent — and a broken pin quarantines at
296 /// boot exactly as an eager mount's would. The first read triggers
297 /// the load through the per-operation funnel
298 /// (`Engine::ensure_mems_loaded`, called by `reload_if_stale`),
299 /// running the same validation gauntlet an eager boot runs; a load
300 /// failure quarantines at that moment with the same typed
301 /// reporting. Opt-in per mount; nothing sets it by default.
302 Lazy,
303}
304
305/// Operator-curated workspace — the in-memory shape the engine
306/// receives.
307///
308/// The two-layer file adapter produces a `Workspace` by reading
309/// `.memstead/workspace.toml` (operator-edited rules) and
310/// `.memstead/state/mounts.json` (engine-managed mount list). Tests and
311/// in-memory builders construct `Workspace` directly.
312///
313/// V1 carries the mount list and operator policy. Plugin hooks and
314/// pipeline-config handles attach as additive fields — no breaking
315/// changes expected.
316#[derive(Debug, Clone, Default)]
317pub struct Workspace {
318 pub mounts: Vec<Mount>,
319 /// Workspace-level operator policy (mem create/delete rules,
320 /// cross-mem link permissions). Defaults to empty for tests
321 /// and in-memory builders; the file adapter
322 /// populates from `.memstead/workspace.toml`'s `[mem_management]`
323 /// and `[cross_mem_links]` sections. The unified engine reads
324 /// this via [`crate::Engine::settings`] after
325 /// [`crate::Engine::from_workspace_root`] threads it through
326 /// [`crate::Engine::set_settings`].
327 pub settings: WorkspaceSettings,
328}
329
330impl Workspace {
331 /// Empty workspace — zero mounts, default settings. Useful for
332 /// tests; production workspaces always carry at least one mount
333 /// (the engine rejects an empty `Workspace` at boot).
334 pub fn empty() -> Self {
335 Self {
336 mounts: Vec::new(),
337 settings: WorkspaceSettings::default(),
338 }
339 }
340}
341
342/// Workspace-level operator policy carried alongside the mount list.
343///
344/// Data carriers only — the matcher compilation lives in
345/// `crate::mem_management::CreateRuleSet`. The engine carries the
346/// raw settings so MCP handlers can surface them under `memstead_health
347/// { include_config: true }` and `memstead_overview`'s
348/// lifecycle-namespaces section.
349///
350/// `Default::default()` is a totally-empty policy: zero create rules,
351/// zero delete rules, no cross-mem link policy. The unified engine
352/// uses this as the bootstrap value at construction time; consumers
353/// that load a real policy call [`crate::Engine::set_settings`].
354#[derive(Debug, Clone, Default)]
355pub struct WorkspaceSettings {
356 /// Raw `[[mem_management.create]]` rules in declaration order.
357 /// Each entry carries a gitignore-style `pattern` matched against
358 /// the candidate mem path, an `schemas[]` allowlist, and an
359 /// optional `default_cross_links` synthesised cross-link
360 /// permission. Empty list means "no agent-driven mem creation
361 /// allowed" — `memstead_mem_create` rejects every candidate.
362 pub mem_create_rules: Vec<CreateRuleSetting>,
363 /// Raw `[[mem_management.delete]]` rules. Same first-match
364 /// semantics as [`Self::mem_create_rules`], minus the schema
365 /// dimension. Empty list means "no agent-driven mem deletion
366 /// allowed".
367 pub mem_delete_rules: Vec<DeleteRuleSetting>,
368 /// `[cross_mem_links]` policy — workspace-level cross-mem
369 /// edge permissions keyed by source mem. Empty map means
370 /// default-deny: every cross-mem edge fails until at least one
371 /// matching entry exists or a create-rule synthesised one.
372 pub cross_mem_links: BTreeMap<String, CrossLinkValue>,
373 /// `[mcp]` section — MCP-binary tuning knobs that operators set
374 /// per-workspace. The MCP binary reads this off
375 /// `Engine::settings()` at boot to size the response chunker
376 /// (`token_budget`) and filter the advertised tool surface
377 /// (`disabled_tools`). Defaulted when the section is absent.
378 pub mcp: McpSection,
379 /// `[mutations]` section — engine-wide mutation policy. The
380 /// `require_notes` field surfaces a `WarningHint::NoteMissing` on
381 /// mutation calls that omit a `note`. Default-zeroed when absent.
382 pub mutations: MutationsSection,
383 /// `[plugin.*]` namespace — opaque pass-through map keyed by
384 /// plugin identifier (`claude_code`, …). Values are raw
385 /// TOML tables the engine never inspects; named plugins read
386 /// their own sub-table via `memstead_health { include_config: true }`.
387 pub plugin: HashMap<String, toml::Table>,
388}
389
390/// `[mcp]` section — settings the MCP binary reads at boot. Carried
391/// on `WorkspaceSettings` so the MCP server sources its tuning from
392/// `Engine::settings()` instead of a parallel TOML parse.
393#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
394#[serde(deny_unknown_fields)]
395pub struct McpSection {
396 /// Per-response chunking budget in tokens. `None` → caller falls
397 /// back to the compile-time `DEFAULT_TOKEN_BUDGET`.
398 pub token_budget: Option<usize>,
399 /// Blocklist of tool names. Entries matching a compiled-in tool
400 /// are hidden from `tools/list` and rejected with `TOOL_DISABLED`
401 /// on direct invocation. Unknown entries log a warning and drop
402 /// from the effective set. Empty / absent → every compiled-in
403 /// tool is advertised.
404 pub disabled_tools: Option<Vec<String>>,
405}
406
407/// `[mutations]` section — engine-wide mutation policy. Carried on
408/// `WorkspaceSettings` so plugins can read the configured posture via
409/// `memstead_health { include_config: true }` without a round-trip.
410#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
411#[serde(deny_unknown_fields)]
412pub struct MutationsSection {
413 /// When `true`, a mutation call without a `note` field emits a
414 /// `WarningHint { code: "note_missing" }`. The mutation still
415 /// succeeds — provenance is best-effort.
416 pub require_notes: Option<bool>,
417 /// How many seconds a write waits for a mem's write lock before it
418 /// refuses `WRITE_LOCK_TIMEOUT`. Absent → 30. `0` waits without
419 /// bound. A value that is not a non-negative whole number refuses
420 /// when the configuration is loaded.
421 #[serde(default, skip_serializing_if = "Option::is_none")]
422 pub write_lock_timeout_secs: Option<u64>,
423}
424
425impl MutationsSection {
426 /// The default wait for a mem's write lock, in seconds.
427 pub const DEFAULT_WRITE_LOCK_TIMEOUT_SECS: u64 = 30;
428
429 /// The limit a write waits for a mem's write lock: `None` waits
430 /// without bound (the key set to `0`), otherwise the configured
431 /// seconds or the default.
432 pub fn write_lock_timeout(&self) -> Option<std::time::Duration> {
433 match self
434 .write_lock_timeout_secs
435 .unwrap_or(Self::DEFAULT_WRITE_LOCK_TIMEOUT_SECS)
436 {
437 0 => None,
438 secs => Some(std::time::Duration::from_secs(secs)),
439 }
440 }
441}
442
443/// One `[[mem_management.create]]` rule. Carries a glob `pattern`
444/// matched against the candidate mem path, the `schemas` allowlist
445/// (each entry an exact `name@x.y.z` pin or the literal `"*"` for
446/// any-schema), and an optional `default_cross_links` value applied
447/// to every mem the rule matches.
448#[derive(Debug, Clone, PartialEq, Eq)]
449pub struct CreateRuleSetting {
450 pub pattern: String,
451 pub schemas: Vec<String>,
452 pub default_cross_links: Option<CrossLinkValue>,
453}
454
455/// One `[[mem_management.delete]]` rule. Carries only a `pattern`;
456/// delete has no schema dimension.
457#[derive(Debug, Clone, PartialEq, Eq)]
458pub struct DeleteRuleSetting {
459 pub pattern: String,
460}
461
462/// The literal `"*"` schema-allowlist entry that admits any pinned
463/// schema. Consumed by the create-rule allowlist parser.
464pub const SCHEMA_WILDCARD: &str = "*";
465
466/// The git directories whose `__MEMSTEAD:schemas/` registry a workspace
467/// resolves schema pins from: the git directory of every git-branch
468/// mount, in mount order, then the workspace's own `mem-repo/.git` when
469/// it exists. Each directory appears once (compared after
470/// canonicalisation, so a mount that names the workspace's own mem-repo
471/// through another spelling does not double).
472///
473/// A git-branch mem's schema is sealed on the registry of the
474/// repository that holds the mem, which is the mount's git directory
475/// and need not be the mounting workspace's `mem-repo/`: a workspace
476/// may consist of engine state only and mount mems that live in
477/// another workspace's mem-repo. Every reader of the registry (boot,
478/// full refresh, below-boot repair, export, health) walks this list,
479/// so the place a schema is installed into is a place it is read from.
480/// On a name-and-version collision between two registries the earlier
481/// directory wins.
482pub fn schema_registry_gitdirs<'a>(
483 mounts: impl IntoIterator<Item = &'a Mount>,
484 workspace_root: Option<&std::path::Path>,
485) -> Vec<PathBuf> {
486 let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
487 let mut out: Vec<PathBuf> = Vec::new();
488 let own = workspace_root
489 .map(|root| root.join("mem-repo").join(".git"))
490 .filter(|gitdir| gitdir.is_dir());
491 let mounted = mounts.into_iter().filter_map(|m| match &m.storage {
492 MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
493 _ => None,
494 });
495 for gitdir in mounted.chain(own) {
496 let key = gitdir.canonicalize().unwrap_or_else(|_| gitdir.clone());
497 if seen.insert(key) {
498 out.push(gitdir);
499 }
500 }
501 out
502}
503
504#[cfg(test)]
505mod tests {
506 use super::*;
507
508 fn pin(name: &str) -> SchemaRef {
509 SchemaRef::new(name, semver::Version::new(1, 0, 0))
510 }
511
512 #[test]
513 fn empty_workspace_has_no_mounts() {
514 let ws = Workspace::empty();
515 assert!(ws.mounts.is_empty());
516 }
517
518 #[test]
519 fn durability_follows_storage_kind() {
520 // On-disk backends persist; only in-memory is volatile. This is
521 // the fact the durability marker projects across overview / health
522 // / mutation responses.
523 let folder = MountStorage::Folder {
524 path: PathBuf::from("/work/mem"),
525 };
526 let git = MountStorage::GitBranch {
527 gitdir: PathBuf::from("/work/mem-repo/.git"),
528 branch: "specs".into(),
529 };
530 let archive = MountStorage::Archive {
531 path: PathBuf::from("/work/curated.mem"),
532 };
533 let in_memory = MountStorage::InMemory;
534
535 assert!(folder.is_durable());
536 assert!(git.is_durable());
537 assert!(archive.is_durable());
538 assert!(!in_memory.is_durable());
539
540 // The backend_id kebab string the marker rides alongside.
541 assert_eq!(folder.backend_id(), "folder");
542 assert_eq!(git.backend_id(), "git-branch");
543 assert_eq!(archive.backend_id(), "archive");
544 assert_eq!(in_memory.backend_id(), "in-memory");
545 }
546
547 #[test]
548 fn mount_can_describe_folder_storage() {
549 let m = Mount {
550 mem: "specs".into(),
551 schema: Some(pin("default")),
552 storage: MountStorage::Folder {
553 path: PathBuf::from("/work/mem"),
554 },
555 capability: MountCapability::Write,
556 lifecycle: MountLifecycle::Eager,
557 cross_linkable: true,
558 migration_target: None,
559 };
560 assert_eq!(m.mem, "specs");
561 assert!(matches!(m.storage, MountStorage::Folder { .. }));
562 }
563
564 #[test]
565 fn mount_can_describe_git_branch_storage() {
566 let m = Mount {
567 mem: "engine".into(),
568 schema: Some(pin("default")),
569 storage: MountStorage::GitBranch {
570 gitdir: PathBuf::from("/work/mem-repo/.git"),
571 branch: "engine".into(),
572 },
573 capability: MountCapability::Write,
574 lifecycle: MountLifecycle::Eager,
575 cross_linkable: true,
576 migration_target: None,
577 };
578 assert!(matches!(m.storage, MountStorage::GitBranch { .. }));
579 }
580
581 /// `Mount::mem_path()` derives the hierarchical path component
582 /// the delete-side lifecycle composer needs. Tolerates both bare
583 /// `<path>/<mem>` (operator-edited mounts.json) and
584 /// fully-qualified `refs/heads/<path>/<mem>` (runtime-created
585 /// mems). Folder / Archive variants always return `None`.
586 #[test]
587 fn mem_path_extracts_hierarchical_prefix_from_git_branch() {
588 // Bare hierarchical (mounts.json shape).
589 let m = Mount {
590 mem: "engine".into(),
591 schema: Some(pin("default")),
592 storage: MountStorage::GitBranch {
593 gitdir: PathBuf::from("/work/mem-repo/.git"),
594 branch: "memstead/engine".into(),
595 },
596 capability: MountCapability::Write,
597 lifecycle: MountLifecycle::Eager,
598 cross_linkable: true,
599 migration_target: None,
600 };
601 assert_eq!(m.mem_path(), Some("memstead".to_string()));
602
603 // Fully-qualified hierarchical (create_mem shape).
604 let m = Mount {
605 mem: "plan-foo".into(),
606 schema: Some(pin("default")),
607 storage: MountStorage::GitBranch {
608 gitdir: PathBuf::from("/work/mem-repo/.git"),
609 branch: "refs/heads/planning/plan-foo".into(),
610 },
611 capability: MountCapability::Write,
612 lifecycle: MountLifecycle::Eager,
613 cross_linkable: true,
614 migration_target: None,
615 };
616 assert_eq!(m.mem_path(), Some("planning".to_string()));
617
618 // Multi-segment hierarchical prefix.
619 let m = Mount {
620 mem: "leaf".into(),
621 schema: Some(pin("default")),
622 storage: MountStorage::GitBranch {
623 gitdir: PathBuf::from("/work/mem-repo/.git"),
624 branch: "refs/heads/a/b/c/leaf".into(),
625 },
626 capability: MountCapability::Write,
627 lifecycle: MountLifecycle::Eager,
628 cross_linkable: true,
629 migration_target: None,
630 };
631 assert_eq!(m.mem_path(), Some("a/b/c".to_string()));
632
633 // Flat layout (bare leaf, no prefix).
634 let m = Mount {
635 mem: "engine".into(),
636 schema: Some(pin("default")),
637 storage: MountStorage::GitBranch {
638 gitdir: PathBuf::from("/work/mem-repo/.git"),
639 branch: "engine".into(),
640 },
641 capability: MountCapability::Write,
642 lifecycle: MountLifecycle::Eager,
643 cross_linkable: true,
644 migration_target: None,
645 };
646 assert_eq!(m.mem_path(), None);
647
648 // Flat layout (fully-qualified, no prefix beyond refs/heads/).
649 let m = Mount {
650 mem: "engine".into(),
651 schema: Some(pin("default")),
652 storage: MountStorage::GitBranch {
653 gitdir: PathBuf::from("/work/mem-repo/.git"),
654 branch: "refs/heads/engine".into(),
655 },
656 capability: MountCapability::Write,
657 lifecycle: MountLifecycle::Eager,
658 cross_linkable: true,
659 migration_target: None,
660 };
661 assert_eq!(m.mem_path(), None);
662
663 // Folder backend has no hierarchical concept.
664 let m = Mount {
665 mem: "engine".into(),
666 schema: Some(pin("default")),
667 storage: MountStorage::Folder {
668 path: PathBuf::from("/work/mem"),
669 },
670 capability: MountCapability::Write,
671 lifecycle: MountLifecycle::Eager,
672 cross_linkable: true,
673 migration_target: None,
674 };
675 assert_eq!(m.mem_path(), None);
676 }
677
678 #[test]
679 fn mount_can_describe_archive_storage() {
680 let m = Mount {
681 mem: "external".into(),
682 schema: Some(pin("default")),
683 storage: MountStorage::Archive {
684 path: PathBuf::from("/deps/external.mem"),
685 },
686 capability: MountCapability::ReadOnly,
687 lifecycle: MountLifecycle::Lazy,
688 cross_linkable: false,
689 migration_target: None,
690 };
691 assert!(matches!(m.storage, MountStorage::Archive { .. }));
692 assert_eq!(m.capability, MountCapability::ReadOnly);
693 }
694
695 #[test]
696 fn workspace_with_heterogeneous_mounts() {
697 let ws = Workspace {
698 mounts: vec![
699 Mount {
700 mem: "engine".into(),
701 schema: Some(pin("default")),
702 storage: MountStorage::GitBranch {
703 gitdir: PathBuf::from("/work/mem-repo/.git"),
704 branch: "engine".into(),
705 },
706 capability: MountCapability::Write,
707 lifecycle: MountLifecycle::Eager,
708 cross_linkable: true,
709 migration_target: None,
710 },
711 Mount {
712 mem: "macos".into(),
713 schema: Some(pin("default")),
714 storage: MountStorage::GitBranch {
715 gitdir: PathBuf::from("/work/mem-repo/.git"),
716 branch: "macos".into(),
717 },
718 capability: MountCapability::Write,
719 lifecycle: MountLifecycle::Eager,
720 cross_linkable: true,
721 migration_target: None,
722 },
723 Mount {
724 mem: "external".into(),
725 schema: Some(pin("default")),
726 storage: MountStorage::Archive {
727 path: PathBuf::from("/deps/external.mem"),
728 },
729 capability: MountCapability::ReadOnly,
730 lifecycle: MountLifecycle::Lazy,
731 cross_linkable: false,
732 migration_target: None,
733 },
734 ],
735 settings: WorkspaceSettings::default(),
736 };
737 assert_eq!(ws.mounts.len(), 3);
738 // Two mounts share a gitdir — the engine will pool the handle
739 // internally; the conceptual mount stays per-mem.
740 let shared_gitdir_mounts = ws
741 .mounts
742 .iter()
743 .filter(|m| matches!(&m.storage, MountStorage::GitBranch { gitdir, .. } if gitdir == std::path::Path::new("/work/mem-repo/.git")))
744 .count();
745 assert_eq!(shared_gitdir_mounts, 2);
746 }
747}