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/// The git directories whose `__MEMSTEAD:schemas/` registry a workspace
443/// resolves schema pins from: the git directory of every git-branch
444/// mount, in mount order, then the workspace's own `mem-repo/.git` when
445/// it exists. Each directory appears once (compared after
446/// canonicalisation, so a mount that names the workspace's own mem-repo
447/// through another spelling does not double).
448///
449/// A git-branch mem's schema is sealed on the registry of the
450/// repository that holds the mem, which is the mount's git directory
451/// and need not be the mounting workspace's `mem-repo/`: a workspace
452/// may consist of engine state only and mount mems that live in
453/// another workspace's mem-repo. Every reader of the registry (boot,
454/// full refresh, below-boot repair, export, health) walks this list,
455/// so the place a schema is installed into is a place it is read from.
456/// On a name-and-version collision between two registries the earlier
457/// directory wins.
458pub fn schema_registry_gitdirs<'a>(
459 mounts: impl IntoIterator<Item = &'a Mount>,
460 workspace_root: Option<&std::path::Path>,
461) -> Vec<PathBuf> {
462 let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
463 let mut out: Vec<PathBuf> = Vec::new();
464 let own = workspace_root
465 .map(|root| root.join("mem-repo").join(".git"))
466 .filter(|gitdir| gitdir.is_dir());
467 let mounted = mounts.into_iter().filter_map(|m| match &m.storage {
468 MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
469 _ => None,
470 });
471 for gitdir in mounted.chain(own) {
472 let key = gitdir.canonicalize().unwrap_or_else(|_| gitdir.clone());
473 if seen.insert(key) {
474 out.push(gitdir);
475 }
476 }
477 out
478}
479
480#[cfg(test)]
481mod tests {
482 use super::*;
483
484 fn pin(name: &str) -> SchemaRef {
485 SchemaRef::new(name, semver::Version::new(1, 0, 0))
486 }
487
488 #[test]
489 fn empty_workspace_has_no_mounts() {
490 let ws = Workspace::empty();
491 assert!(ws.mounts.is_empty());
492 }
493
494 #[test]
495 fn durability_follows_storage_kind() {
496 // On-disk backends persist; only in-memory is volatile. This is
497 // the fact the durability marker projects across overview / health
498 // / mutation responses.
499 let folder = MountStorage::Folder {
500 path: PathBuf::from("/work/mem"),
501 };
502 let git = MountStorage::GitBranch {
503 gitdir: PathBuf::from("/work/mem-repo/.git"),
504 branch: "specs".into(),
505 };
506 let archive = MountStorage::Archive {
507 path: PathBuf::from("/work/curated.mem"),
508 };
509 let in_memory = MountStorage::InMemory;
510
511 assert!(folder.is_durable());
512 assert!(git.is_durable());
513 assert!(archive.is_durable());
514 assert!(!in_memory.is_durable());
515
516 // The backend_id kebab string the marker rides alongside.
517 assert_eq!(folder.backend_id(), "folder");
518 assert_eq!(git.backend_id(), "git-branch");
519 assert_eq!(archive.backend_id(), "archive");
520 assert_eq!(in_memory.backend_id(), "in-memory");
521 }
522
523 #[test]
524 fn mount_can_describe_folder_storage() {
525 let m = Mount {
526 mem: "specs".into(),
527 schema: Some(pin("default")),
528 storage: MountStorage::Folder {
529 path: PathBuf::from("/work/mem"),
530 },
531 capability: MountCapability::Write,
532 lifecycle: MountLifecycle::Eager,
533 cross_linkable: true,
534 migration_target: None,
535 };
536 assert_eq!(m.mem, "specs");
537 assert!(matches!(m.storage, MountStorage::Folder { .. }));
538 }
539
540 #[test]
541 fn mount_can_describe_git_branch_storage() {
542 let m = Mount {
543 mem: "engine".into(),
544 schema: Some(pin("default")),
545 storage: MountStorage::GitBranch {
546 gitdir: PathBuf::from("/work/mem-repo/.git"),
547 branch: "engine".into(),
548 },
549 capability: MountCapability::Write,
550 lifecycle: MountLifecycle::Eager,
551 cross_linkable: true,
552 migration_target: None,
553 };
554 assert!(matches!(m.storage, MountStorage::GitBranch { .. }));
555 }
556
557 /// `Mount::mem_path()` derives the hierarchical path component
558 /// the delete-side lifecycle composer needs. Tolerates both bare
559 /// `<path>/<mem>` (operator-edited mounts.json) and
560 /// fully-qualified `refs/heads/<path>/<mem>` (runtime-created
561 /// mems). Folder / Archive variants always return `None`.
562 #[test]
563 fn mem_path_extracts_hierarchical_prefix_from_git_branch() {
564 // Bare hierarchical (mounts.json shape).
565 let m = Mount {
566 mem: "engine".into(),
567 schema: Some(pin("default")),
568 storage: MountStorage::GitBranch {
569 gitdir: PathBuf::from("/work/mem-repo/.git"),
570 branch: "memstead/engine".into(),
571 },
572 capability: MountCapability::Write,
573 lifecycle: MountLifecycle::Eager,
574 cross_linkable: true,
575 migration_target: None,
576 };
577 assert_eq!(m.mem_path(), Some("memstead".to_string()));
578
579 // Fully-qualified hierarchical (create_mem shape).
580 let m = Mount {
581 mem: "plan-foo".into(),
582 schema: Some(pin("default")),
583 storage: MountStorage::GitBranch {
584 gitdir: PathBuf::from("/work/mem-repo/.git"),
585 branch: "refs/heads/planning/plan-foo".into(),
586 },
587 capability: MountCapability::Write,
588 lifecycle: MountLifecycle::Eager,
589 cross_linkable: true,
590 migration_target: None,
591 };
592 assert_eq!(m.mem_path(), Some("planning".to_string()));
593
594 // Multi-segment hierarchical prefix.
595 let m = Mount {
596 mem: "leaf".into(),
597 schema: Some(pin("default")),
598 storage: MountStorage::GitBranch {
599 gitdir: PathBuf::from("/work/mem-repo/.git"),
600 branch: "refs/heads/a/b/c/leaf".into(),
601 },
602 capability: MountCapability::Write,
603 lifecycle: MountLifecycle::Eager,
604 cross_linkable: true,
605 migration_target: None,
606 };
607 assert_eq!(m.mem_path(), Some("a/b/c".to_string()));
608
609 // Flat layout (bare leaf, no prefix).
610 let m = Mount {
611 mem: "engine".into(),
612 schema: Some(pin("default")),
613 storage: MountStorage::GitBranch {
614 gitdir: PathBuf::from("/work/mem-repo/.git"),
615 branch: "engine".into(),
616 },
617 capability: MountCapability::Write,
618 lifecycle: MountLifecycle::Eager,
619 cross_linkable: true,
620 migration_target: None,
621 };
622 assert_eq!(m.mem_path(), None);
623
624 // Flat layout (fully-qualified, no prefix beyond refs/heads/).
625 let m = Mount {
626 mem: "engine".into(),
627 schema: Some(pin("default")),
628 storage: MountStorage::GitBranch {
629 gitdir: PathBuf::from("/work/mem-repo/.git"),
630 branch: "refs/heads/engine".into(),
631 },
632 capability: MountCapability::Write,
633 lifecycle: MountLifecycle::Eager,
634 cross_linkable: true,
635 migration_target: None,
636 };
637 assert_eq!(m.mem_path(), None);
638
639 // Folder backend has no hierarchical concept.
640 let m = Mount {
641 mem: "engine".into(),
642 schema: Some(pin("default")),
643 storage: MountStorage::Folder {
644 path: PathBuf::from("/work/mem"),
645 },
646 capability: MountCapability::Write,
647 lifecycle: MountLifecycle::Eager,
648 cross_linkable: true,
649 migration_target: None,
650 };
651 assert_eq!(m.mem_path(), None);
652 }
653
654 #[test]
655 fn mount_can_describe_archive_storage() {
656 let m = Mount {
657 mem: "external".into(),
658 schema: Some(pin("default")),
659 storage: MountStorage::Archive {
660 path: PathBuf::from("/deps/external.mem"),
661 },
662 capability: MountCapability::ReadOnly,
663 lifecycle: MountLifecycle::Lazy,
664 cross_linkable: false,
665 migration_target: None,
666 };
667 assert!(matches!(m.storage, MountStorage::Archive { .. }));
668 assert_eq!(m.capability, MountCapability::ReadOnly);
669 }
670
671 #[test]
672 fn workspace_with_heterogeneous_mounts() {
673 let ws = Workspace {
674 mounts: vec![
675 Mount {
676 mem: "engine".into(),
677 schema: Some(pin("default")),
678 storage: MountStorage::GitBranch {
679 gitdir: PathBuf::from("/work/mem-repo/.git"),
680 branch: "engine".into(),
681 },
682 capability: MountCapability::Write,
683 lifecycle: MountLifecycle::Eager,
684 cross_linkable: true,
685 migration_target: None,
686 },
687 Mount {
688 mem: "macos".into(),
689 schema: Some(pin("default")),
690 storage: MountStorage::GitBranch {
691 gitdir: PathBuf::from("/work/mem-repo/.git"),
692 branch: "macos".into(),
693 },
694 capability: MountCapability::Write,
695 lifecycle: MountLifecycle::Eager,
696 cross_linkable: true,
697 migration_target: None,
698 },
699 Mount {
700 mem: "external".into(),
701 schema: Some(pin("default")),
702 storage: MountStorage::Archive {
703 path: PathBuf::from("/deps/external.mem"),
704 },
705 capability: MountCapability::ReadOnly,
706 lifecycle: MountLifecycle::Lazy,
707 cross_linkable: false,
708 migration_target: None,
709 },
710 ],
711 settings: WorkspaceSettings::default(),
712 };
713 assert_eq!(ws.mounts.len(), 3);
714 // Two mounts share a gitdir — the engine will pool the handle
715 // internally; the conceptual mount stays per-mem.
716 let shared_gitdir_mounts = ws
717 .mounts
718 .iter()
719 .filter(|m| matches!(&m.storage, MountStorage::GitBranch { gitdir, .. } if gitdir == std::path::Path::new("/work/mem-repo/.git")))
720 .count();
721 assert_eq!(shared_gitdir_mounts, 2);
722 }
723}