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}
418
419/// One `[[mem_management.create]]` rule. Carries a glob `pattern`
420/// matched against the candidate mem path, the `schemas` allowlist
421/// (each entry an exact `name@x.y.z` pin or the literal `"*"` for
422/// any-schema), and an optional `default_cross_links` value applied
423/// to every mem the rule matches.
424#[derive(Debug, Clone, PartialEq, Eq)]
425pub struct CreateRuleSetting {
426 pub pattern: String,
427 pub schemas: Vec<String>,
428 pub default_cross_links: Option<CrossLinkValue>,
429}
430
431/// One `[[mem_management.delete]]` rule. Carries only a `pattern`;
432/// delete has no schema dimension.
433#[derive(Debug, Clone, PartialEq, Eq)]
434pub struct DeleteRuleSetting {
435 pub pattern: String,
436}
437
438/// The literal `"*"` schema-allowlist entry that admits any pinned
439/// schema. Consumed by the create-rule allowlist parser.
440pub const SCHEMA_WILDCARD: &str = "*";
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445
446 fn pin(name: &str) -> SchemaRef {
447 SchemaRef::new(name, semver::Version::new(1, 0, 0))
448 }
449
450 #[test]
451 fn empty_workspace_has_no_mounts() {
452 let ws = Workspace::empty();
453 assert!(ws.mounts.is_empty());
454 }
455
456 #[test]
457 fn durability_follows_storage_kind() {
458 // On-disk backends persist; only in-memory is volatile. This is
459 // the fact the durability marker projects across overview / health
460 // / mutation responses.
461 let folder = MountStorage::Folder {
462 path: PathBuf::from("/work/mem"),
463 };
464 let git = MountStorage::GitBranch {
465 gitdir: PathBuf::from("/work/mem-repo/.git"),
466 branch: "specs".into(),
467 };
468 let archive = MountStorage::Archive {
469 path: PathBuf::from("/work/curated.mem"),
470 };
471 let in_memory = MountStorage::InMemory;
472
473 assert!(folder.is_durable());
474 assert!(git.is_durable());
475 assert!(archive.is_durable());
476 assert!(!in_memory.is_durable());
477
478 // The backend_id kebab string the marker rides alongside.
479 assert_eq!(folder.backend_id(), "folder");
480 assert_eq!(git.backend_id(), "git-branch");
481 assert_eq!(archive.backend_id(), "archive");
482 assert_eq!(in_memory.backend_id(), "in-memory");
483 }
484
485 #[test]
486 fn mount_can_describe_folder_storage() {
487 let m = Mount {
488 mem: "specs".into(),
489 schema: Some(pin("default")),
490 storage: MountStorage::Folder {
491 path: PathBuf::from("/work/mem"),
492 },
493 capability: MountCapability::Write,
494 lifecycle: MountLifecycle::Eager,
495 cross_linkable: true,
496 migration_target: None,
497 };
498 assert_eq!(m.mem, "specs");
499 assert!(matches!(m.storage, MountStorage::Folder { .. }));
500 }
501
502 #[test]
503 fn mount_can_describe_git_branch_storage() {
504 let m = Mount {
505 mem: "engine".into(),
506 schema: Some(pin("default")),
507 storage: MountStorage::GitBranch {
508 gitdir: PathBuf::from("/work/mem-repo/.git"),
509 branch: "engine".into(),
510 },
511 capability: MountCapability::Write,
512 lifecycle: MountLifecycle::Eager,
513 cross_linkable: true,
514 migration_target: None,
515 };
516 assert!(matches!(m.storage, MountStorage::GitBranch { .. }));
517 }
518
519 /// `Mount::mem_path()` derives the hierarchical path component
520 /// the delete-side lifecycle composer needs. Tolerates both bare
521 /// `<path>/<mem>` (operator-edited mounts.json) and
522 /// fully-qualified `refs/heads/<path>/<mem>` (runtime-created
523 /// mems). Folder / Archive variants always return `None`.
524 #[test]
525 fn mem_path_extracts_hierarchical_prefix_from_git_branch() {
526 // Bare hierarchical (mounts.json shape).
527 let m = Mount {
528 mem: "engine".into(),
529 schema: Some(pin("default")),
530 storage: MountStorage::GitBranch {
531 gitdir: PathBuf::from("/work/mem-repo/.git"),
532 branch: "memstead/engine".into(),
533 },
534 capability: MountCapability::Write,
535 lifecycle: MountLifecycle::Eager,
536 cross_linkable: true,
537 migration_target: None,
538 };
539 assert_eq!(m.mem_path(), Some("memstead".to_string()));
540
541 // Fully-qualified hierarchical (create_mem shape).
542 let m = Mount {
543 mem: "plan-foo".into(),
544 schema: Some(pin("default")),
545 storage: MountStorage::GitBranch {
546 gitdir: PathBuf::from("/work/mem-repo/.git"),
547 branch: "refs/heads/planning/plan-foo".into(),
548 },
549 capability: MountCapability::Write,
550 lifecycle: MountLifecycle::Eager,
551 cross_linkable: true,
552 migration_target: None,
553 };
554 assert_eq!(m.mem_path(), Some("planning".to_string()));
555
556 // Multi-segment hierarchical prefix.
557 let m = Mount {
558 mem: "leaf".into(),
559 schema: Some(pin("default")),
560 storage: MountStorage::GitBranch {
561 gitdir: PathBuf::from("/work/mem-repo/.git"),
562 branch: "refs/heads/a/b/c/leaf".into(),
563 },
564 capability: MountCapability::Write,
565 lifecycle: MountLifecycle::Eager,
566 cross_linkable: true,
567 migration_target: None,
568 };
569 assert_eq!(m.mem_path(), Some("a/b/c".to_string()));
570
571 // Flat layout (bare leaf, no prefix).
572 let m = Mount {
573 mem: "engine".into(),
574 schema: Some(pin("default")),
575 storage: MountStorage::GitBranch {
576 gitdir: PathBuf::from("/work/mem-repo/.git"),
577 branch: "engine".into(),
578 },
579 capability: MountCapability::Write,
580 lifecycle: MountLifecycle::Eager,
581 cross_linkable: true,
582 migration_target: None,
583 };
584 assert_eq!(m.mem_path(), None);
585
586 // Flat layout (fully-qualified, no prefix beyond refs/heads/).
587 let m = Mount {
588 mem: "engine".into(),
589 schema: Some(pin("default")),
590 storage: MountStorage::GitBranch {
591 gitdir: PathBuf::from("/work/mem-repo/.git"),
592 branch: "refs/heads/engine".into(),
593 },
594 capability: MountCapability::Write,
595 lifecycle: MountLifecycle::Eager,
596 cross_linkable: true,
597 migration_target: None,
598 };
599 assert_eq!(m.mem_path(), None);
600
601 // Folder backend has no hierarchical concept.
602 let m = Mount {
603 mem: "engine".into(),
604 schema: Some(pin("default")),
605 storage: MountStorage::Folder {
606 path: PathBuf::from("/work/mem"),
607 },
608 capability: MountCapability::Write,
609 lifecycle: MountLifecycle::Eager,
610 cross_linkable: true,
611 migration_target: None,
612 };
613 assert_eq!(m.mem_path(), None);
614 }
615
616 #[test]
617 fn mount_can_describe_archive_storage() {
618 let m = Mount {
619 mem: "external".into(),
620 schema: Some(pin("default")),
621 storage: MountStorage::Archive {
622 path: PathBuf::from("/deps/external.mem"),
623 },
624 capability: MountCapability::ReadOnly,
625 lifecycle: MountLifecycle::Lazy,
626 cross_linkable: false,
627 migration_target: None,
628 };
629 assert!(matches!(m.storage, MountStorage::Archive { .. }));
630 assert_eq!(m.capability, MountCapability::ReadOnly);
631 }
632
633 #[test]
634 fn workspace_with_heterogeneous_mounts() {
635 let ws = Workspace {
636 mounts: vec![
637 Mount {
638 mem: "engine".into(),
639 schema: Some(pin("default")),
640 storage: MountStorage::GitBranch {
641 gitdir: PathBuf::from("/work/mem-repo/.git"),
642 branch: "engine".into(),
643 },
644 capability: MountCapability::Write,
645 lifecycle: MountLifecycle::Eager,
646 cross_linkable: true,
647 migration_target: None,
648 },
649 Mount {
650 mem: "macos".into(),
651 schema: Some(pin("default")),
652 storage: MountStorage::GitBranch {
653 gitdir: PathBuf::from("/work/mem-repo/.git"),
654 branch: "macos".into(),
655 },
656 capability: MountCapability::Write,
657 lifecycle: MountLifecycle::Eager,
658 cross_linkable: true,
659 migration_target: None,
660 },
661 Mount {
662 mem: "external".into(),
663 schema: Some(pin("default")),
664 storage: MountStorage::Archive {
665 path: PathBuf::from("/deps/external.mem"),
666 },
667 capability: MountCapability::ReadOnly,
668 lifecycle: MountLifecycle::Lazy,
669 cross_linkable: false,
670 migration_target: None,
671 },
672 ],
673 settings: WorkspaceSettings::default(),
674 };
675 assert_eq!(ws.mounts.len(), 3);
676 // Two mounts share a gitdir — the engine will pool the handle
677 // internally; the conceptual mount stays per-mem.
678 let shared_gitdir_mounts = ws
679 .mounts
680 .iter()
681 .filter(|m| matches!(&m.storage, MountStorage::GitBranch { gitdir, .. } if gitdir == std::path::Path::new("/work/mem-repo/.git")))
682 .count();
683 assert_eq!(shared_gitdir_mounts, 2);
684 }
685}