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`. The same limit bounds the wait of
419 /// a load, and of a direct read, of a folder mem that holds a
420 /// commit which is decided and not applied while another process
421 /// holds the mem's write lock: past it the mem is not served and
422 /// the condition is `COMMIT_NOT_APPLIED`. Absent → 30. `0` waits
423 /// without bound. A value that is not a non-negative whole number
424 /// refuses when the configuration is loaded.
425 #[serde(default, skip_serializing_if = "Option::is_none")]
426 pub write_lock_timeout_secs: Option<u64>,
427}
428
429impl MutationsSection {
430 /// The default wait for a mem's write lock, in seconds.
431 pub const DEFAULT_WRITE_LOCK_TIMEOUT_SECS: u64 = 30;
432
433 /// The limit a write waits for a mem's write lock: `None` waits
434 /// without bound (the key set to `0`), otherwise the configured
435 /// seconds or the default.
436 pub fn write_lock_timeout(&self) -> Option<std::time::Duration> {
437 match self
438 .write_lock_timeout_secs
439 .unwrap_or(Self::DEFAULT_WRITE_LOCK_TIMEOUT_SECS)
440 {
441 0 => None,
442 secs => Some(std::time::Duration::from_secs(secs)),
443 }
444 }
445}
446
447/// One `[[mem_management.create]]` rule. Carries a glob `pattern`
448/// matched against the candidate mem path, the `schemas` allowlist
449/// (each entry an exact `name@x.y.z` pin or the literal `"*"` for
450/// any-schema), and an optional `default_cross_links` value applied
451/// to every mem the rule matches.
452#[derive(Debug, Clone, PartialEq, Eq)]
453pub struct CreateRuleSetting {
454 pub pattern: String,
455 pub schemas: Vec<String>,
456 pub default_cross_links: Option<CrossLinkValue>,
457}
458
459/// One `[[mem_management.delete]]` rule. Carries only a `pattern`;
460/// delete has no schema dimension.
461#[derive(Debug, Clone, PartialEq, Eq)]
462pub struct DeleteRuleSetting {
463 pub pattern: String,
464}
465
466/// The literal `"*"` schema-allowlist entry that admits any pinned
467/// schema. Consumed by the create-rule allowlist parser.
468pub const SCHEMA_WILDCARD: &str = "*";
469
470/// The git directories whose `__MEMSTEAD:schemas/` registry a workspace
471/// resolves schema pins from: the git directory of every git-branch
472/// mount, in mount order, then the workspace's own `mem-repo/.git` when
473/// it exists. Each directory appears once (compared after
474/// canonicalisation, so a mount that names the workspace's own mem-repo
475/// through another spelling does not double).
476///
477/// A git-branch mem's schema is sealed on the registry of the
478/// repository that holds the mem, which is the mount's git directory
479/// and need not be the mounting workspace's `mem-repo/`: a workspace
480/// may consist of engine state only and mount mems that live in
481/// another workspace's mem-repo. Every reader of the registry (boot,
482/// full refresh, below-boot repair, export, health) walks this list,
483/// so the place a schema is installed into is a place it is read from.
484/// On a name-and-version collision between two registries the earlier
485/// directory wins.
486pub fn schema_registry_gitdirs<'a>(
487 mounts: impl IntoIterator<Item = &'a Mount>,
488 workspace_root: Option<&std::path::Path>,
489) -> Vec<PathBuf> {
490 let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
491 let mut out: Vec<PathBuf> = Vec::new();
492 let own = workspace_root
493 .map(|root| root.join("mem-repo").join(".git"))
494 .filter(|gitdir| gitdir.is_dir());
495 let mounted = mounts.into_iter().filter_map(|m| match &m.storage {
496 MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
497 _ => None,
498 });
499 for gitdir in mounted.chain(own) {
500 let key = gitdir.canonicalize().unwrap_or_else(|_| gitdir.clone());
501 if seen.insert(key) {
502 out.push(gitdir);
503 }
504 }
505 out
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511
512 fn pin(name: &str) -> SchemaRef {
513 SchemaRef::new(name, semver::Version::new(1, 0, 0))
514 }
515
516 #[test]
517 fn empty_workspace_has_no_mounts() {
518 let ws = Workspace::empty();
519 assert!(ws.mounts.is_empty());
520 }
521
522 #[test]
523 fn durability_follows_storage_kind() {
524 // On-disk backends persist; only in-memory is volatile. This is
525 // the fact the durability marker projects across overview / health
526 // / mutation responses.
527 let folder = MountStorage::Folder {
528 path: PathBuf::from("/work/mem"),
529 };
530 let git = MountStorage::GitBranch {
531 gitdir: PathBuf::from("/work/mem-repo/.git"),
532 branch: "specs".into(),
533 };
534 let archive = MountStorage::Archive {
535 path: PathBuf::from("/work/curated.mem"),
536 };
537 let in_memory = MountStorage::InMemory;
538
539 assert!(folder.is_durable());
540 assert!(git.is_durable());
541 assert!(archive.is_durable());
542 assert!(!in_memory.is_durable());
543
544 // The backend_id kebab string the marker rides alongside.
545 assert_eq!(folder.backend_id(), "folder");
546 assert_eq!(git.backend_id(), "git-branch");
547 assert_eq!(archive.backend_id(), "archive");
548 assert_eq!(in_memory.backend_id(), "in-memory");
549 }
550
551 #[test]
552 fn mount_can_describe_folder_storage() {
553 let m = Mount {
554 mem: "specs".into(),
555 schema: Some(pin("default")),
556 storage: MountStorage::Folder {
557 path: PathBuf::from("/work/mem"),
558 },
559 capability: MountCapability::Write,
560 lifecycle: MountLifecycle::Eager,
561 cross_linkable: true,
562 migration_target: None,
563 };
564 assert_eq!(m.mem, "specs");
565 assert!(matches!(m.storage, MountStorage::Folder { .. }));
566 }
567
568 #[test]
569 fn mount_can_describe_git_branch_storage() {
570 let m = Mount {
571 mem: "engine".into(),
572 schema: Some(pin("default")),
573 storage: MountStorage::GitBranch {
574 gitdir: PathBuf::from("/work/mem-repo/.git"),
575 branch: "engine".into(),
576 },
577 capability: MountCapability::Write,
578 lifecycle: MountLifecycle::Eager,
579 cross_linkable: true,
580 migration_target: None,
581 };
582 assert!(matches!(m.storage, MountStorage::GitBranch { .. }));
583 }
584
585 /// `Mount::mem_path()` derives the hierarchical path component
586 /// the delete-side lifecycle composer needs. Tolerates both bare
587 /// `<path>/<mem>` (operator-edited mounts.json) and
588 /// fully-qualified `refs/heads/<path>/<mem>` (runtime-created
589 /// mems). Folder / Archive variants always return `None`.
590 #[test]
591 fn mem_path_extracts_hierarchical_prefix_from_git_branch() {
592 // Bare hierarchical (mounts.json shape).
593 let m = Mount {
594 mem: "engine".into(),
595 schema: Some(pin("default")),
596 storage: MountStorage::GitBranch {
597 gitdir: PathBuf::from("/work/mem-repo/.git"),
598 branch: "memstead/engine".into(),
599 },
600 capability: MountCapability::Write,
601 lifecycle: MountLifecycle::Eager,
602 cross_linkable: true,
603 migration_target: None,
604 };
605 assert_eq!(m.mem_path(), Some("memstead".to_string()));
606
607 // Fully-qualified hierarchical (create_mem shape).
608 let m = Mount {
609 mem: "plan-foo".into(),
610 schema: Some(pin("default")),
611 storage: MountStorage::GitBranch {
612 gitdir: PathBuf::from("/work/mem-repo/.git"),
613 branch: "refs/heads/planning/plan-foo".into(),
614 },
615 capability: MountCapability::Write,
616 lifecycle: MountLifecycle::Eager,
617 cross_linkable: true,
618 migration_target: None,
619 };
620 assert_eq!(m.mem_path(), Some("planning".to_string()));
621
622 // Multi-segment hierarchical prefix.
623 let m = Mount {
624 mem: "leaf".into(),
625 schema: Some(pin("default")),
626 storage: MountStorage::GitBranch {
627 gitdir: PathBuf::from("/work/mem-repo/.git"),
628 branch: "refs/heads/a/b/c/leaf".into(),
629 },
630 capability: MountCapability::Write,
631 lifecycle: MountLifecycle::Eager,
632 cross_linkable: true,
633 migration_target: None,
634 };
635 assert_eq!(m.mem_path(), Some("a/b/c".to_string()));
636
637 // Flat layout (bare leaf, no prefix).
638 let m = Mount {
639 mem: "engine".into(),
640 schema: Some(pin("default")),
641 storage: MountStorage::GitBranch {
642 gitdir: PathBuf::from("/work/mem-repo/.git"),
643 branch: "engine".into(),
644 },
645 capability: MountCapability::Write,
646 lifecycle: MountLifecycle::Eager,
647 cross_linkable: true,
648 migration_target: None,
649 };
650 assert_eq!(m.mem_path(), None);
651
652 // Flat layout (fully-qualified, no prefix beyond refs/heads/).
653 let m = Mount {
654 mem: "engine".into(),
655 schema: Some(pin("default")),
656 storage: MountStorage::GitBranch {
657 gitdir: PathBuf::from("/work/mem-repo/.git"),
658 branch: "refs/heads/engine".into(),
659 },
660 capability: MountCapability::Write,
661 lifecycle: MountLifecycle::Eager,
662 cross_linkable: true,
663 migration_target: None,
664 };
665 assert_eq!(m.mem_path(), None);
666
667 // Folder backend has no hierarchical concept.
668 let m = Mount {
669 mem: "engine".into(),
670 schema: Some(pin("default")),
671 storage: MountStorage::Folder {
672 path: PathBuf::from("/work/mem"),
673 },
674 capability: MountCapability::Write,
675 lifecycle: MountLifecycle::Eager,
676 cross_linkable: true,
677 migration_target: None,
678 };
679 assert_eq!(m.mem_path(), None);
680 }
681
682 #[test]
683 fn mount_can_describe_archive_storage() {
684 let m = Mount {
685 mem: "external".into(),
686 schema: Some(pin("default")),
687 storage: MountStorage::Archive {
688 path: PathBuf::from("/deps/external.mem"),
689 },
690 capability: MountCapability::ReadOnly,
691 lifecycle: MountLifecycle::Lazy,
692 cross_linkable: false,
693 migration_target: None,
694 };
695 assert!(matches!(m.storage, MountStorage::Archive { .. }));
696 assert_eq!(m.capability, MountCapability::ReadOnly);
697 }
698
699 #[test]
700 fn workspace_with_heterogeneous_mounts() {
701 let ws = Workspace {
702 mounts: vec![
703 Mount {
704 mem: "engine".into(),
705 schema: Some(pin("default")),
706 storage: MountStorage::GitBranch {
707 gitdir: PathBuf::from("/work/mem-repo/.git"),
708 branch: "engine".into(),
709 },
710 capability: MountCapability::Write,
711 lifecycle: MountLifecycle::Eager,
712 cross_linkable: true,
713 migration_target: None,
714 },
715 Mount {
716 mem: "macos".into(),
717 schema: Some(pin("default")),
718 storage: MountStorage::GitBranch {
719 gitdir: PathBuf::from("/work/mem-repo/.git"),
720 branch: "macos".into(),
721 },
722 capability: MountCapability::Write,
723 lifecycle: MountLifecycle::Eager,
724 cross_linkable: true,
725 migration_target: None,
726 },
727 Mount {
728 mem: "external".into(),
729 schema: Some(pin("default")),
730 storage: MountStorage::Archive {
731 path: PathBuf::from("/deps/external.mem"),
732 },
733 capability: MountCapability::ReadOnly,
734 lifecycle: MountLifecycle::Lazy,
735 cross_linkable: false,
736 migration_target: None,
737 },
738 ],
739 settings: WorkspaceSettings::default(),
740 };
741 assert_eq!(ws.mounts.len(), 3);
742 // Two mounts share a gitdir — the engine will pool the handle
743 // internally; the conceptual mount stays per-mem.
744 let shared_gitdir_mounts = ws
745 .mounts
746 .iter()
747 .filter(|m| matches!(&m.storage, MountStorage::GitBranch { gitdir, .. } if gitdir == std::path::Path::new("/work/mem-repo/.git")))
748 .count();
749 assert_eq!(shared_gitdir_mounts, 2);
750 }
751}