1use std::path::{Path, PathBuf};
48
49use serde::{Deserialize, Serialize};
50
51use crate::backend::MemBackend;
52use crate::storage::{ArchiveBackend, FilesystemMemWriter, InMemoryBackend};
53use crate::workspace::{
54 McpSection, Mount, MountCapability, MountLifecycle, MountStorage, MutationsSection, Workspace,
55 WorkspaceSettings,
56};
57
58pub const WORKSPACE_STORE_DIR: &str = ".memstead";
71
72#[derive(Debug, thiserror::Error)]
77pub enum StoreError {
78 #[error("workspace store not found at {path} — run `memstead mem-repo init` first")]
82 NotInitialised { path: PathBuf },
83 #[error(
85 "workspace store io error at {path}: {source} — no memstead command repairs this; \
86 check filesystem permissions and disk state"
87 )]
88 Io {
89 path: PathBuf,
90 #[source]
91 source: std::io::Error,
92 },
93 #[error(
97 "workspace store parse error at {path}: {message} — no memstead command repairs this; \
98 fix the named file by hand or restore it from version control"
99 )]
100 Parse { path: PathBuf, message: String },
101 #[error(
104 "workspace store format mismatch at {path}: expected {expected}, found {found} — \
105 no memstead command repairs this; use an engine version whose format matches the file"
106 )]
107 FormatMismatch {
108 path: PathBuf,
109 expected: String,
110 found: String,
111 },
112 #[error(
117 "pre-rename workspace layout at {path} (found format {found}): migrate the workspace \
118 state in place — rewrite mounts.json to memstead-mounts-3 (record field `mem`, storage \
119 paths under mem-repo/), workspace.toml to memstead-git-branch-2 (tables `mem_management`, \
120 `cross_mem_links`), rename the gitdir container to mem-repo/, and move the metadata \
121 branch tree to mems/ — then retry"
122 )]
123 LegacyLayout { path: PathBuf, found: String },
124 #[error(
132 "retired binding format at {path}: this file is a gen-2 (version-less) or v1 binding, \
133 a format this engine no longer converts; re-author the binding with \
134 `memstead projection init`"
135 )]
136 LegacyProjectionStore { path: PathBuf },
137 #[error(
141 "unsupported binding format version {version} at {path}: this engine understands v2 (version 2)"
142 )]
143 UnknownBindingVersion { path: PathBuf, version: i64 },
144 #[error("workspace store error: {0}")]
147 Other(String),
148}
149
150impl StoreError {
151 pub fn code(&self) -> &'static str {
158 match self {
159 StoreError::NotInitialised { .. } => "WORKSPACE_NOT_INITIALISED",
163 StoreError::Io { .. } => "WORKSPACE_STORE_IO",
164 StoreError::Parse { .. } => "WORKSPACE_STORE_PARSE",
165 StoreError::FormatMismatch { .. } => "WORKSPACE_STORE_FORMAT_MISMATCH",
166 StoreError::LegacyLayout { .. } => "LEGACY_WORKSPACE_LAYOUT",
167 StoreError::LegacyProjectionStore { .. } => "PROJECTION_STORE_LEGACY",
168 StoreError::UnknownBindingVersion { .. } => "UNKNOWN_BINDING_VERSION",
169 StoreError::Other(_) => "WORKSPACE_STORE_ERROR",
170 }
171 }
172}
173
174pub trait WorkspaceStoreAdapter: Send + Sync {
180 fn load(&self, workspace_root: &Path) -> Result<Workspace, StoreError>;
186
187 fn save_state(&self, workspace_root: &Path, workspace: &Workspace) -> Result<(), StoreError>;
198
199 fn read_state_bytes(&self, workspace_root: &Path) -> Result<Option<Vec<u8>>, StoreError>;
203
204 fn parse_state_bytes(
207 &self,
208 workspace_root: &Path,
209 bytes: &[u8],
210 ) -> Result<Vec<Mount>, StoreError>;
211
212 fn save_state_cas(
220 &self,
221 workspace_root: &Path,
222 workspace: &Workspace,
223 expected: Option<&[u8]>,
224 ) -> Result<bool, StoreError>;
225}
226
227#[derive(Debug, Default, Clone, Copy)]
233pub struct FileWorkspaceStore;
234
235impl FileWorkspaceStore {
236 pub fn new() -> Self {
239 Self
240 }
241
242 pub fn workspace_toml_path(workspace_root: &Path) -> PathBuf {
244 workspace_root
245 .join(WORKSPACE_STORE_DIR)
246 .join("workspace.toml")
247 }
248
249 pub fn mounts_json_path(workspace_root: &Path) -> PathBuf {
251 workspace_root
252 .join(WORKSPACE_STORE_DIR)
253 .join("state")
254 .join("mounts.json")
255 }
256}
257
258const WORKSPACE_TOML_FORMAT: &str = "memstead-git-branch-2";
259const WORKSPACE_TOML_FORMAT_LEGACY: &str = "memstead-git-branch-1";
263const MOUNTS_JSON_FORMAT_V3: &str = "memstead-mounts-3";
273const MOUNTS_JSON_FORMAT_LEGACY: [&str; 2] = ["memstead-mounts-1", "memstead-mounts-2"];
278
279#[derive(Deserialize)]
283struct MountsFormatProbe {
284 format: String,
285}
286
287fn check_workspace_toml_format(format: &str, toml_path: &Path) -> Result<(), StoreError> {
291 if format == WORKSPACE_TOML_FORMAT {
292 return Ok(());
293 }
294 if format == WORKSPACE_TOML_FORMAT_LEGACY {
295 return Err(StoreError::LegacyLayout {
296 path: toml_path.to_path_buf(),
297 found: format.to_string(),
298 });
299 }
300 Err(StoreError::FormatMismatch {
301 path: toml_path.to_path_buf(),
302 expected: WORKSPACE_TOML_FORMAT.to_string(),
303 found: format.to_string(),
304 })
305}
306
307fn absolutize_mount_path(value: PathBuf, workspace_root: &Path) -> PathBuf {
313 if value.is_absolute() {
314 value
315 } else {
316 workspace_root.join(value)
317 }
318}
319
320fn relativize_mount_path(value: &Path, workspace_root: &Path) -> PathBuf {
326 match value.strip_prefix(workspace_root) {
327 Ok(rel) => rel.to_path_buf(),
328 Err(_) => value.to_path_buf(),
329 }
330}
331
332pub fn is_workspace_root(dir: &Path) -> bool {
337 FileWorkspaceStore::workspace_toml_path(dir).is_file()
338}
339
340pub fn is_mem_repo_shaped(workspace_root: &Path) -> bool {
349 workspace_root.join("mem-repo").join(".git").is_dir()
350}
351
352pub fn workspace_shape_label(workspace_root: &Path) -> &'static str {
358 if is_mem_repo_shaped(workspace_root) {
359 "mem-repo"
360 } else {
361 "filesystem-mem"
362 }
363}
364
365impl WorkspaceStoreAdapter for FileWorkspaceStore {
366 fn load(&self, workspace_root: &Path) -> Result<Workspace, StoreError> {
367 let memstead_dir = workspace_root.join(WORKSPACE_STORE_DIR);
368 if !memstead_dir.is_dir() {
369 return Err(StoreError::NotInitialised {
370 path: workspace_root.to_path_buf(),
371 });
372 }
373
374 let toml_path = Self::workspace_toml_path(workspace_root);
376 let toml_text = std::fs::read_to_string(&toml_path).map_err(|e| {
377 if e.kind() == std::io::ErrorKind::NotFound {
378 StoreError::NotInitialised {
379 path: workspace_root.to_path_buf(),
380 }
381 } else {
382 StoreError::Io {
383 path: toml_path.clone(),
384 source: e,
385 }
386 }
387 })?;
388 let toml_doc: WorkspaceTomlDoc =
389 toml::from_str(&toml_text).map_err(|e| StoreError::Parse {
390 path: toml_path.clone(),
391 message: e.to_string(),
392 })?;
393 check_workspace_toml_format(&toml_doc.format, &toml_path)?;
394
395 let mounts_path = Self::mounts_json_path(workspace_root);
399 let mounts: Vec<Mount> = match std::fs::read_to_string(&mounts_path) {
400 Ok(text) => parse_mounts_text(&text, &mounts_path, workspace_root)?,
401 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
402 Err(e) => {
403 return Err(StoreError::Io {
404 path: mounts_path,
405 source: e,
406 });
407 }
408 };
409
410 warn_if_legacy_schemas_dir(toml_doc.schemas_dir.as_deref());
411 let settings = build_settings(
412 toml_doc.mem_management,
413 toml_doc.cross_mem_links,
414 toml_doc.mcp,
415 toml_doc.mutations,
416 toml_doc.plugin,
417 )?;
418 Ok(Workspace { mounts, settings })
419 }
420
421 fn save_state(&self, workspace_root: &Path, workspace: &Workspace) -> Result<(), StoreError> {
422 let mounts_path = Self::mounts_json_path(workspace_root);
423 ensure_state_dir(&mounts_path)?;
424 let text = render_mounts_text(workspace, workspace_root, &mounts_path)?;
425 std::fs::write(&mounts_path, text).map_err(|e| StoreError::Io {
426 path: mounts_path,
427 source: e,
428 })?;
429 Ok(())
430 }
431
432 fn read_state_bytes(&self, workspace_root: &Path) -> Result<Option<Vec<u8>>, StoreError> {
433 let mounts_path = Self::mounts_json_path(workspace_root);
434 match std::fs::read(&mounts_path) {
435 Ok(b) => Ok(Some(b)),
436 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
437 Err(e) => Err(StoreError::Io {
438 path: mounts_path,
439 source: e,
440 }),
441 }
442 }
443
444 fn parse_state_bytes(
445 &self,
446 workspace_root: &Path,
447 bytes: &[u8],
448 ) -> Result<Vec<Mount>, StoreError> {
449 let mounts_path = Self::mounts_json_path(workspace_root);
450 let text = std::str::from_utf8(bytes).map_err(|e| StoreError::Parse {
451 path: mounts_path.clone(),
452 message: e.to_string(),
453 })?;
454 parse_mounts_text(text, &mounts_path, workspace_root)
455 }
456
457 fn save_state_cas(
458 &self,
459 workspace_root: &Path,
460 workspace: &Workspace,
461 expected: Option<&[u8]>,
462 ) -> Result<bool, StoreError> {
463 let mounts_path = Self::mounts_json_path(workspace_root);
464 ensure_state_dir(&mounts_path)?;
465 let text = render_mounts_text(workspace, workspace_root, &mounts_path)?;
466
467 let lock_path = mounts_path.with_extension("json.lock");
473 let mut held = None;
474 for attempt in 0..50 {
475 match std::fs::OpenOptions::new()
476 .write(true)
477 .create_new(true)
478 .open(&lock_path)
479 {
480 Ok(f) => {
481 held = Some(f);
482 break;
483 }
484 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
485 if attempt == 49 {
486 let _ = std::fs::remove_file(&lock_path);
487 }
488 std::thread::sleep(std::time::Duration::from_millis(10));
489 }
490 Err(e) => {
491 return Err(StoreError::Io {
492 path: lock_path,
493 source: e,
494 });
495 }
496 }
497 }
498 let _lock = match held {
499 Some(f) => f,
500 None => std::fs::OpenOptions::new()
501 .write(true)
502 .create(true)
503 .truncate(true)
504 .open(&lock_path)
505 .map_err(|e| StoreError::Io {
506 path: lock_path.clone(),
507 source: e,
508 })?,
509 };
510 let release = || {
511 let _ = std::fs::remove_file(&lock_path);
512 };
513
514 let current = match std::fs::read(&mounts_path) {
515 Ok(b) => Some(b),
516 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
517 Err(e) => {
518 release();
519 return Err(StoreError::Io {
520 path: mounts_path,
521 source: e,
522 });
523 }
524 };
525 if current.as_deref() != expected {
526 release();
527 return Ok(false);
528 }
529 let result = std::fs::write(&mounts_path, text).map_err(|e| StoreError::Io {
530 path: mounts_path,
531 source: e,
532 });
533 release();
534 result.map(|_| true)
535 }
536}
537
538fn ensure_state_dir(mounts_path: &Path) -> Result<(), StoreError> {
540 if let Some(parent) = mounts_path.parent() {
541 std::fs::create_dir_all(parent).map_err(|e| StoreError::Io {
542 path: parent.to_path_buf(),
543 source: e,
544 })?;
545 }
546 Ok(())
547}
548
549fn render_mounts_text(
551 workspace: &Workspace,
552 workspace_root: &Path,
553 mounts_path: &Path,
554) -> Result<String, StoreError> {
555 let doc = MountsJsonDoc {
556 format: MOUNTS_JSON_FORMAT_V3.to_string(),
557 mounts: workspace
558 .mounts
559 .iter()
560 .map(|m| MountWire::from_mount(m, workspace_root))
561 .collect(),
562 };
563 serde_json::to_string_pretty(&doc).map_err(|e| StoreError::Parse {
564 path: mounts_path.to_path_buf(),
565 message: e.to_string(),
566 })
567}
568
569fn parse_mounts_text(
575 text: &str,
576 mounts_path: &Path,
577 workspace_root: &Path,
578) -> Result<Vec<Mount>, StoreError> {
579 let probe: MountsFormatProbe = serde_json::from_str(text).map_err(|e| StoreError::Parse {
580 path: mounts_path.to_path_buf(),
581 message: e.to_string(),
582 })?;
583 if MOUNTS_JSON_FORMAT_LEGACY.contains(&probe.format.as_str()) {
584 return Err(StoreError::LegacyLayout {
585 path: mounts_path.to_path_buf(),
586 found: probe.format,
587 });
588 }
589 if probe.format != MOUNTS_JSON_FORMAT_V3 {
590 return Err(StoreError::FormatMismatch {
591 path: mounts_path.to_path_buf(),
592 expected: MOUNTS_JSON_FORMAT_V3.to_string(),
593 found: probe.format,
594 });
595 }
596 let doc: MountsJsonDoc = serde_json::from_str(text).map_err(|e| StoreError::Parse {
597 path: mounts_path.to_path_buf(),
598 message: e.to_string(),
599 })?;
600 Ok(doc
601 .mounts
602 .into_iter()
603 .map(|w| w.into_mount(workspace_root))
604 .collect())
605}
606
607#[derive(Debug, Serialize, Deserialize)]
612#[serde(deny_unknown_fields)]
613struct WorkspaceTomlDoc {
614 format: String,
618 #[serde(default)]
622 persistence_adapter: PersistenceAdapterDecl,
623 #[serde(default)]
628 mem_management: MemManagementWire,
629 #[serde(default)]
636 cross_mem_links: toml::Table,
637 #[serde(default)]
644 schemas_dir: Option<std::path::PathBuf>,
645 #[serde(default)]
649 mcp: McpSection,
650 #[serde(default)]
653 mutations: MutationsSection,
654 #[serde(default)]
658 plugin: std::collections::HashMap<String, toml::Table>,
659}
660
661#[derive(Debug, Default, Serialize, Deserialize)]
665struct MemManagementWire {
666 #[serde(default)]
667 create: Vec<CreateRuleWire>,
668 #[serde(default)]
669 delete: Vec<DeleteRuleWire>,
670}
671
672#[derive(Debug, Serialize, Deserialize)]
682struct CreateRuleWire {
683 pattern: String,
684 #[serde(default)]
685 schemas: Vec<String>,
686 #[serde(default)]
687 default_cross_links: Option<toml::Value>,
688}
689
690#[derive(Debug, Serialize, Deserialize)]
693struct DeleteRuleWire {
694 pattern: String,
695}
696
697pub fn parse_workspace_settings(
715 workspace_root: &Path,
716) -> Result<crate::workspace::WorkspaceSettings, StoreError> {
717 let memstead_dir = workspace_root.join(WORKSPACE_STORE_DIR);
718 if !memstead_dir.is_dir() {
719 return Err(StoreError::NotInitialised {
720 path: workspace_root.to_path_buf(),
721 });
722 }
723 let toml_path = FileWorkspaceStore::workspace_toml_path(workspace_root);
724 let toml_text = std::fs::read_to_string(&toml_path).map_err(|e| {
725 if e.kind() == std::io::ErrorKind::NotFound {
726 StoreError::NotInitialised {
727 path: workspace_root.to_path_buf(),
728 }
729 } else {
730 StoreError::Io {
731 path: toml_path.clone(),
732 source: e,
733 }
734 }
735 })?;
736 let toml_doc: WorkspaceTomlDoc = toml::from_str(&toml_text).map_err(|e| StoreError::Parse {
737 path: toml_path.clone(),
738 message: e.to_string(),
739 })?;
740 check_workspace_toml_format(&toml_doc.format, &toml_path)?;
741 warn_if_legacy_schemas_dir(toml_doc.schemas_dir.as_deref());
742 build_settings(
743 toml_doc.mem_management,
744 toml_doc.cross_mem_links,
745 toml_doc.mcp,
746 toml_doc.mutations,
747 toml_doc.plugin,
748 )
749}
750
751fn build_settings(
757 vm: MemManagementWire,
758 cross_mem_links_raw: toml::Table,
759 mcp: McpSection,
760 mutations: MutationsSection,
761 plugin: std::collections::HashMap<String, toml::Table>,
762) -> Result<WorkspaceSettings, StoreError> {
763 let mut create_rules = Vec::with_capacity(vm.create.len());
764 for r in vm.create {
765 let default_cross_links = match r.default_cross_links {
766 None => None,
767 Some(value) => {
768 let location = format!(
769 "[[mem_management.create]] pattern={}.default_cross_links",
770 r.pattern
771 );
772 Some(parse_cross_link_value(&location, &value)?)
773 }
774 };
775 create_rules.push(crate::workspace::CreateRuleSetting {
776 pattern: r.pattern,
777 schemas: r.schemas,
778 default_cross_links,
779 });
780 }
781
782 let mut cross_mem_links = std::collections::BTreeMap::new();
783 for (mem, value) in &cross_mem_links_raw {
784 let location = format!("[cross_mem_links].{mem}");
785 let parsed = parse_cross_link_value(&location, value)?;
786 cross_mem_links.insert(mem.clone(), parsed);
787 }
788
789 Ok(WorkspaceSettings {
790 mem_create_rules: create_rules,
791 mem_delete_rules: vm
792 .delete
793 .into_iter()
794 .map(|r| crate::workspace::DeleteRuleSetting { pattern: r.pattern })
795 .collect(),
796 cross_mem_links,
797 mcp,
798 mutations,
799 plugin,
800 })
801}
802
803fn warn_if_legacy_schemas_dir(schemas_dir: Option<&std::path::Path>) {
810 if let Some(dir) = schemas_dir {
811 tracing::warn!(
812 "`schemas_dir` (= {:?}) in workspace.toml is retired and ignored — \
813 authored schemas are read from the fixed `<workspace>/.memstead/schemas/`. \
814 Remove the key to silence this warning.",
815 dir
816 );
817 }
818}
819
820fn parse_cross_link_value(
824 location: &str,
825 value: &toml::Value,
826) -> Result<memstead_schema::workspace_config::CrossLinkValue, StoreError> {
827 memstead_schema::workspace_config::CrossLinkValue::parse_toml(location, value).map_err(|e| {
828 StoreError::Parse {
829 path: std::path::PathBuf::from("workspace.toml"),
830 message: e.to_string(),
831 }
832 })
833}
834
835#[derive(Debug, Serialize, Deserialize)]
838struct PersistenceAdapterDecl {
839 name: String,
840}
841
842impl Default for PersistenceAdapterDecl {
843 fn default() -> Self {
844 Self {
845 name: "file-two-layer".to_string(),
846 }
847 }
848}
849
850#[derive(Debug, Serialize, Deserialize)]
854struct MountsJsonDoc {
855 format: String,
856 mounts: Vec<MountWire>,
857}
858
859#[derive(Debug, Serialize, Deserialize)]
864struct MountWire {
865 mem: String,
866 #[serde(default, skip_serializing_if = "Option::is_none")]
872 schema: Option<String>,
873 #[serde(default, skip_serializing_if = "Option::is_none")]
878 migration_target: Option<String>,
879 storage: MountStorageWire,
880 capability: CapabilityWire,
881 lifecycle: LifecycleWire,
882 cross_linkable: bool,
883}
884
885#[derive(Debug, Serialize, Deserialize)]
886#[serde(tag = "type", rename_all = "kebab-case")]
887enum MountStorageWire {
888 Folder {
889 path: PathBuf,
890 },
891 GitBranch {
892 gitdir: PathBuf,
893 branch: String,
894 },
895 Archive {
896 path: PathBuf,
897 },
898 InMemory,
906}
907
908#[derive(Debug, Serialize, Deserialize)]
909#[serde(rename_all = "kebab-case")]
910enum CapabilityWire {
911 ReadOnly,
912 Write,
913}
914
915#[derive(Debug, Serialize, Deserialize)]
916#[serde(rename_all = "kebab-case")]
917enum LifecycleWire {
918 Eager,
919 Lazy,
920}
921
922impl MountWire {
923 fn from_mount(m: &Mount, workspace_root: &Path) -> Self {
924 Self {
925 mem: m.mem.clone(),
926 schema: m.schema.as_ref().map(|s| s.to_string()),
927 migration_target: m.migration_target.as_ref().map(|t| t.to_string()),
928 storage: match &m.storage {
929 MountStorage::Folder { path } => MountStorageWire::Folder {
930 path: relativize_mount_path(path, workspace_root),
931 },
932 MountStorage::GitBranch { gitdir, branch } => MountStorageWire::GitBranch {
933 gitdir: relativize_mount_path(gitdir, workspace_root),
934 branch: branch.clone(),
935 },
936 MountStorage::Archive { path } => MountStorageWire::Archive {
937 path: relativize_mount_path(path, workspace_root),
938 },
939 MountStorage::InMemory => MountStorageWire::InMemory,
940 },
941 capability: match m.capability {
942 MountCapability::ReadOnly => CapabilityWire::ReadOnly,
943 MountCapability::Write => CapabilityWire::Write,
944 },
945 lifecycle: match m.lifecycle {
946 MountLifecycle::Eager => LifecycleWire::Eager,
947 MountLifecycle::Lazy => LifecycleWire::Lazy,
948 },
949 cross_linkable: m.cross_linkable,
950 }
951 }
952
953 fn into_mount(self, workspace_root: &Path) -> Mount {
954 Mount {
955 mem: self.mem,
956 schema: self.schema.map(|s| {
957 s.parse()
958 .expect("schema pin on disk must be `<name>@<version>`")
959 }),
960 migration_target: self.migration_target.map(|t| {
961 t.parse()
962 .expect("migration_target on disk must be `<name>@<version>`")
963 }),
964 storage: match self.storage {
965 MountStorageWire::Folder { path } => MountStorage::Folder {
966 path: absolutize_mount_path(path, workspace_root),
967 },
968 MountStorageWire::GitBranch { gitdir, branch } => MountStorage::GitBranch {
969 gitdir: absolutize_mount_path(gitdir, workspace_root),
970 branch,
971 },
972 MountStorageWire::Archive { path } => MountStorage::Archive {
973 path: absolutize_mount_path(path, workspace_root),
974 },
975 MountStorageWire::InMemory => MountStorage::InMemory,
976 },
977 capability: match self.capability {
978 CapabilityWire::ReadOnly => MountCapability::ReadOnly,
979 CapabilityWire::Write => MountCapability::Write,
980 },
981 lifecycle: match self.lifecycle {
982 LifecycleWire::Eager => MountLifecycle::Eager,
983 LifecycleWire::Lazy => MountLifecycle::Lazy,
984 },
985 cross_linkable: self.cross_linkable,
986 }
987 }
988}
989
990#[derive(Debug, thiserror::Error)]
992pub enum InstantiateError {
993 #[error(
1005 "mem {mem}: git-branch storage needs the memstead-git-branch crate \
1006 (`cargo add memstead-git-branch`). Simplest: open the workspace with \
1007 `memstead_git_branch::workspace_store::engine_from_workspace_root(root)` \
1008 instead of the memstead-base constructor. Alternative, if you build the \
1009 Engine yourself: `engine.set_backend_factory(\
1010 memstead_git_branch::storage::instantiate_full_backend)` before mounting"
1011 )]
1012 GitBranchBackendUnavailable { mem: String },
1013}
1014
1015impl InstantiateError {
1016 pub fn code(&self) -> &'static str {
1023 match self {
1024 InstantiateError::GitBranchBackendUnavailable { .. } => "UNSUPPORTED_WORKSPACE_SHAPE",
1025 }
1026 }
1027}
1028
1029pub fn instantiate_local_backend(mount: &Mount) -> Result<Box<dyn MemBackend>, InstantiateError> {
1040 match &mount.storage {
1041 MountStorage::Folder { path } => Ok(Box::new(FilesystemMemWriter::new(path.clone()))),
1042 MountStorage::Archive { path } => Ok(Box::new(ArchiveBackend::new(path.clone()))),
1043 MountStorage::InMemory => Ok(Box::new(InMemoryBackend::new())),
1044 MountStorage::GitBranch { .. } => Err(InstantiateError::GitBranchBackendUnavailable {
1045 mem: mount.mem.clone(),
1046 }),
1047 }
1048}
1049
1050#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1058pub enum Layout {
1059 Empty,
1062 New,
1065}
1066
1067pub fn detect_layout(workspace_root: &Path) -> Layout {
1071 if is_workspace_root(workspace_root) {
1072 Layout::New
1073 } else {
1074 Layout::Empty
1075 }
1076}
1077
1078pub fn standalone_workspace(workspace_root: &Path) -> Option<Workspace> {
1098 let config = memstead_schema::config::load_and_validate(workspace_root).ok()?;
1099 let schema = config.schema.clone()?;
1100 let name = config.name.clone().unwrap_or_else(|| {
1101 workspace_root
1102 .file_name()
1103 .map(|n| n.to_string_lossy().to_string())
1104 .unwrap_or_else(|| "mem".to_string())
1105 });
1106 let mount = Mount {
1107 mem: name,
1108 schema: Some(schema),
1109 storage: MountStorage::Folder {
1110 path: workspace_root.to_path_buf(),
1111 },
1112 capability: MountCapability::Write,
1113 lifecycle: MountLifecycle::Eager,
1114 cross_linkable: false,
1115 migration_target: None,
1116 };
1117 Some(Workspace {
1118 mounts: vec![mount],
1119 settings: WorkspaceSettings::default(),
1120 })
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125 use super::*;
1126 use memstead_schema::SchemaRef;
1127 use std::io::Write as _;
1128 use tempfile::TempDir;
1129
1130 fn pin(s: &str) -> SchemaRef {
1131 s.parse().unwrap()
1132 }
1133
1134 fn folder_mount(mem: &str, path: PathBuf) -> Mount {
1135 Mount {
1136 mem: mem.to_string(),
1137 schema: Some(pin("default@1.0.0")),
1138 storage: MountStorage::Folder { path },
1139 capability: MountCapability::Write,
1140 lifecycle: MountLifecycle::Eager,
1141 cross_linkable: true,
1142 migration_target: None,
1143 }
1144 }
1145
1146 fn write_workspace_toml(workspace_root: &Path, body: &str) {
1147 let path = FileWorkspaceStore::workspace_toml_path(workspace_root);
1148 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1149 std::fs::write(path, body).unwrap();
1150 }
1151
1152 #[test]
1153 fn load_returns_not_initialised_when_memstead_dir_absent() {
1154 let tmp = TempDir::new().unwrap();
1155 let store = FileWorkspaceStore::new();
1156 let err = store.load(tmp.path()).unwrap_err();
1157 assert!(matches!(err, StoreError::NotInitialised { .. }));
1158 }
1159
1160 #[test]
1166 fn parse_workspace_settings_reflects_cross_mem_links_edit() {
1167 let tmp = TempDir::new().unwrap();
1168 write_workspace_toml(
1169 tmp.path(),
1170 r#"
1171format = "memstead-git-branch-2"
1172
1173[persistence_adapter]
1174name = "file-two-layer"
1175
1176[cross_mem_links]
1177team-a = ["team-b"]
1178"#,
1179 );
1180 let settings = super::parse_workspace_settings(tmp.path()).unwrap();
1181 assert!(
1182 settings.cross_mem_links.contains_key("team-a"),
1183 "initial parse must surface the team-a grant; got {:?}",
1184 settings.cross_mem_links
1185 );
1186
1187 write_workspace_toml(
1189 tmp.path(),
1190 r#"
1191format = "memstead-git-branch-2"
1192
1193[persistence_adapter]
1194name = "file-two-layer"
1195
1196[cross_mem_links]
1197"#,
1198 );
1199 let refreshed = super::parse_workspace_settings(tmp.path()).unwrap();
1200 assert!(
1201 refreshed.cross_mem_links.is_empty(),
1202 "refreshed parse must drop the team-a grant; got {:?}",
1203 refreshed.cross_mem_links
1204 );
1205 }
1206
1207 #[test]
1212 fn parse_workspace_settings_reflects_allowlist_edit() {
1213 let tmp = TempDir::new().unwrap();
1214 write_workspace_toml(
1215 tmp.path(),
1216 r#"
1217format = "memstead-git-branch-2"
1218
1219[persistence_adapter]
1220name = "file-two-layer"
1221"#,
1222 );
1223 let initial = super::parse_workspace_settings(tmp.path()).unwrap();
1224 assert!(initial.mem_create_rules.is_empty());
1225
1226 write_workspace_toml(
1228 tmp.path(),
1229 r#"
1230format = "memstead-git-branch-2"
1231
1232[persistence_adapter]
1233name = "file-two-layer"
1234
1235[[mem_management.create]]
1236pattern = "test-*"
1237schemas = ["default@1.0.0"]
1238"#,
1239 );
1240 let refreshed = super::parse_workspace_settings(tmp.path()).unwrap();
1241 assert_eq!(refreshed.mem_create_rules.len(), 1);
1242 assert_eq!(refreshed.mem_create_rules[0].pattern, "test-*");
1243 }
1244
1245 #[test]
1246 fn load_returns_not_initialised_when_workspace_toml_missing() {
1247 let tmp = TempDir::new().unwrap();
1248 std::fs::create_dir_all(tmp.path().join(".memstead")).unwrap();
1249 let store = FileWorkspaceStore::new();
1250 let err = store.load(tmp.path()).unwrap_err();
1251 assert!(matches!(err, StoreError::NotInitialised { .. }));
1252 }
1253
1254 #[test]
1255 fn load_with_no_mounts_yields_empty_mount_list() {
1256 let tmp = TempDir::new().unwrap();
1257 write_workspace_toml(
1258 tmp.path(),
1259 r#"
1260format = "memstead-git-branch-2"
1261
1262[persistence_adapter]
1263name = "file-two-layer"
1264"#,
1265 );
1266 let store = FileWorkspaceStore::new();
1267 let workspace = store.load(tmp.path()).unwrap();
1268 assert!(workspace.mounts.is_empty());
1269 }
1270
1271 #[test]
1272 fn load_with_no_mem_management_yields_empty_settings() {
1273 let tmp = TempDir::new().unwrap();
1278 write_workspace_toml(
1279 tmp.path(),
1280 r#"
1281format = "memstead-git-branch-2"
1282
1283[persistence_adapter]
1284name = "file-two-layer"
1285"#,
1286 );
1287 let store = FileWorkspaceStore::new();
1288 let workspace = store.load(tmp.path()).unwrap();
1289 assert!(workspace.settings.mem_create_rules.is_empty());
1290 assert!(workspace.settings.mem_delete_rules.is_empty());
1291 assert!(workspace.settings.cross_mem_links.is_empty());
1292 }
1293
1294 #[test]
1295 fn load_picks_up_cross_mem_links_wildcard_and_list() {
1296 use memstead_schema::workspace_config::CrossLinkValue;
1301 let tmp = TempDir::new().unwrap();
1302 write_workspace_toml(
1303 tmp.path(),
1304 r#"
1305format = "memstead-git-branch-2"
1306
1307[persistence_adapter]
1308name = "file-two-layer"
1309
1310[cross_mem_links]
1311specs = "*"
1312engine = ["specs", "macos"]
1313locked = []
1314"#,
1315 );
1316 let store = FileWorkspaceStore::new();
1317 let workspace = store.load(tmp.path()).unwrap();
1318 let cvl = &workspace.settings.cross_mem_links;
1319 assert_eq!(cvl.len(), 3);
1320 assert_eq!(cvl.get("specs"), Some(&CrossLinkValue::Wildcard));
1321 assert_eq!(
1322 cvl.get("engine"),
1323 Some(&CrossLinkValue::List(vec![
1324 "specs".to_string(),
1325 "macos".to_string()
1326 ]))
1327 );
1328 assert_eq!(cvl.get("locked"), Some(&CrossLinkValue::List(vec![])));
1329 }
1330
1331 #[test]
1332 fn load_rejects_cross_mem_links_mixed_wildcard_and_names() {
1333 let tmp = TempDir::new().unwrap();
1338 write_workspace_toml(
1339 tmp.path(),
1340 r#"
1341format = "memstead-git-branch-2"
1342
1343[persistence_adapter]
1344name = "file-two-layer"
1345
1346[cross_mem_links]
1347specs = ["*", "engine"]
1348"#,
1349 );
1350 let store = FileWorkspaceStore::new();
1351 let err = store.load(tmp.path()).unwrap_err();
1352 match err {
1353 StoreError::Parse { message, .. } => {
1354 assert!(message.contains("[cross_mem_links].specs"));
1355 assert!(message.contains("wildcard"));
1356 }
1357 other => panic!("expected StoreError::Parse, got {other:?}"),
1358 }
1359 }
1360
1361 #[test]
1362 fn load_picks_up_default_cross_links_on_create_rule() {
1363 use memstead_schema::workspace_config::CrossLinkValue;
1367 let tmp = TempDir::new().unwrap();
1368 write_workspace_toml(
1369 tmp.path(),
1370 r#"
1371format = "memstead-git-branch-2"
1372
1373[persistence_adapter]
1374name = "file-two-layer"
1375
1376[[mem_management.create]]
1377pattern = "exec-*"
1378schemas = ["default"]
1379default_cross_links = "*"
1380"#,
1381 );
1382 let store = FileWorkspaceStore::new();
1383 let workspace = store.load(tmp.path()).unwrap();
1384 let rule = &workspace.settings.mem_create_rules[0];
1385 assert_eq!(rule.pattern, "exec-*");
1386 assert_eq!(rule.default_cross_links, Some(CrossLinkValue::Wildcard));
1387 }
1388
1389 #[test]
1390 fn load_picks_up_mem_management_create_and_delete_rules() {
1391 let tmp = TempDir::new().unwrap();
1395 write_workspace_toml(
1396 tmp.path(),
1397 r#"
1398format = "memstead-git-branch-2"
1399
1400[persistence_adapter]
1401name = "file-two-layer"
1402
1403[[mem_management.create]]
1404pattern = "exec-*"
1405schemas = ["default@1.0.0", "*"]
1406
1407[[mem_management.create]]
1408pattern = "scratch-*"
1409schemas = ["default"]
1410
1411[[mem_management.delete]]
1412pattern = "exec-*"
1413"#,
1414 );
1415 let store = FileWorkspaceStore::new();
1416 let workspace = store.load(tmp.path()).unwrap();
1417 assert_eq!(workspace.settings.mem_create_rules.len(), 2);
1418 assert_eq!(workspace.settings.mem_create_rules[0].pattern, "exec-*");
1419 assert_eq!(
1420 workspace.settings.mem_create_rules[0].schemas,
1421 vec!["default@1.0.0".to_string(), "*".to_string()]
1422 );
1423 assert_eq!(workspace.settings.mem_create_rules[1].pattern, "scratch-*");
1424 assert_eq!(workspace.settings.mem_delete_rules.len(), 1);
1425 assert_eq!(workspace.settings.mem_delete_rules[0].pattern, "exec-*");
1426 }
1427
1428 #[test]
1433 fn save_state_round_trips_migration_target() {
1434 let tmp = TempDir::new().unwrap();
1435 write_workspace_toml(
1436 tmp.path(),
1437 "\nformat = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
1438 );
1439 let store = FileWorkspaceStore::new();
1440 let mut migrating = folder_mount("specs", PathBuf::from("/work/mem"));
1441 migrating.migration_target = Some(pin("mig-b@0.1.0"));
1442 let settled = folder_mount("other", PathBuf::from("/work/other"));
1443 let original = Workspace {
1444 mounts: vec![migrating, settled],
1445 settings: WorkspaceSettings::default(),
1446 };
1447 store.save_state(tmp.path(), &original).unwrap();
1448 let raw =
1449 std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
1450 assert!(
1451 raw.contains("mig-b@0.1.0"),
1452 "migration_target must persist: {raw}"
1453 );
1454 assert_eq!(
1455 raw.matches("migration_target").count(),
1456 1,
1457 "settled mounts must omit the key entirely: {raw}"
1458 );
1459 let loaded = store.load(tmp.path()).unwrap();
1460 assert_eq!(loaded.mounts[0].migration_target, Some(pin("mig-b@0.1.0")));
1461 assert_eq!(loaded.mounts[1].migration_target, None);
1462 }
1463
1464 #[test]
1465 fn save_state_then_load_round_trips_mount_list() {
1466 let tmp = TempDir::new().unwrap();
1467 write_workspace_toml(
1468 tmp.path(),
1469 r#"
1470format = "memstead-git-branch-2"
1471
1472[persistence_adapter]
1473name = "file-two-layer"
1474"#,
1475 );
1476 let store = FileWorkspaceStore::new();
1477 let original = Workspace {
1478 mounts: vec![
1479 folder_mount("specs", PathBuf::from("/work/mem")),
1480 Mount {
1481 mem: "engine".to_string(),
1482 schema: Some(pin("default@1.0.0")),
1483 storage: MountStorage::GitBranch {
1484 gitdir: PathBuf::from("/work/mem-repo/.git"),
1485 branch: "engine".to_string(),
1486 },
1487 capability: MountCapability::Write,
1488 lifecycle: MountLifecycle::Eager,
1489 cross_linkable: true,
1490 migration_target: None,
1491 },
1492 Mount {
1493 mem: "external".to_string(),
1494 schema: Some(pin("default@1.0.0")),
1495 storage: MountStorage::Archive {
1496 path: PathBuf::from("/deps/external.mem"),
1497 },
1498 capability: MountCapability::ReadOnly,
1499 lifecycle: MountLifecycle::Lazy,
1500 cross_linkable: false,
1501 migration_target: None,
1502 },
1503 ],
1504 settings: WorkspaceSettings::default(),
1505 };
1506 store.save_state(tmp.path(), &original).unwrap();
1507
1508 assert!(FileWorkspaceStore::mounts_json_path(tmp.path()).is_file());
1510
1511 let reloaded = store.load(tmp.path()).unwrap();
1512 assert_eq!(reloaded.mounts.len(), original.mounts.len());
1513 for (a, b) in reloaded.mounts.iter().zip(original.mounts.iter()) {
1514 assert_eq!(a.mem, b.mem);
1515 assert_eq!(a.schema, b.schema);
1516 assert_eq!(a.capability, b.capability);
1517 assert_eq!(a.lifecycle, b.lifecycle);
1518 assert_eq!(a.cross_linkable, b.cross_linkable);
1519 assert_eq!(a.storage, b.storage);
1520 }
1521 }
1522
1523 #[test]
1524 fn save_state_round_trips_unset_schema_assertion() {
1525 let tmp = TempDir::new().unwrap();
1530 write_workspace_toml(
1531 tmp.path(),
1532 r#"
1533format = "memstead-git-branch-2"
1534
1535[persistence_adapter]
1536name = "file-two-layer"
1537"#,
1538 );
1539 let store = FileWorkspaceStore::new();
1540 let original = Workspace {
1541 mounts: vec![Mount {
1542 mem: "foreign".to_string(),
1543 schema: None,
1544 storage: MountStorage::Folder {
1545 path: tmp.path().join("foreign"),
1546 },
1547 capability: MountCapability::ReadOnly,
1548 lifecycle: MountLifecycle::Eager,
1549 cross_linkable: false,
1550 migration_target: None,
1551 }],
1552 settings: WorkspaceSettings::default(),
1553 };
1554 store.save_state(tmp.path(), &original).unwrap();
1555
1556 let raw =
1558 std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
1559 assert!(
1560 !raw.contains("\"schema\""),
1561 "unset schema assertion must omit the key on the wire; got:\n{raw}"
1562 );
1563
1564 let reloaded = store.load(tmp.path()).unwrap();
1566 assert_eq!(reloaded.mounts.len(), 1);
1567 assert_eq!(reloaded.mounts[0].schema, None);
1568 }
1569
1570 #[test]
1571 fn save_state_does_not_touch_workspace_toml() {
1572 let tmp = TempDir::new().unwrap();
1573 let original_body = r#"
1574format = "memstead-git-branch-2"
1575
1576[persistence_adapter]
1577name = "file-two-layer"
1578"#;
1579 write_workspace_toml(tmp.path(), original_body);
1580 let store = FileWorkspaceStore::new();
1581 let workspace = Workspace::default();
1582 store.save_state(tmp.path(), &workspace).unwrap();
1583 let toml_after =
1585 std::fs::read_to_string(FileWorkspaceStore::workspace_toml_path(tmp.path())).unwrap();
1586 assert_eq!(toml_after, original_body);
1587 }
1588
1589 #[test]
1590 fn save_state_writes_paths_relative_to_workspace_root() {
1591 let tmp = TempDir::new().unwrap();
1592 write_workspace_toml(
1593 tmp.path(),
1594 r#"
1595format = "memstead-git-branch-2"
1596
1597[persistence_adapter]
1598name = "file-two-layer"
1599"#,
1600 );
1601 let store = FileWorkspaceStore::new();
1602 let workspace = Workspace {
1603 mounts: vec![
1604 Mount {
1605 mem: "engine".to_string(),
1606 schema: Some(pin("default@1.0.0")),
1607 storage: MountStorage::GitBranch {
1608 gitdir: tmp.path().join("mem-repo").join(".git"),
1609 branch: "engine".to_string(),
1610 },
1611 capability: MountCapability::Write,
1612 lifecycle: MountLifecycle::Eager,
1613 cross_linkable: true,
1614 migration_target: None,
1615 },
1616 Mount {
1617 mem: "external".to_string(),
1618 schema: Some(pin("default@1.0.0")),
1619 storage: MountStorage::Archive {
1620 path: PathBuf::from("/global/cache/external.mem"),
1621 },
1622 capability: MountCapability::ReadOnly,
1623 lifecycle: MountLifecycle::Lazy,
1624 cross_linkable: false,
1625 migration_target: None,
1626 },
1627 ],
1628 settings: WorkspaceSettings::default(),
1629 };
1630 store.save_state(tmp.path(), &workspace).unwrap();
1631
1632 let on_disk =
1633 std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
1634 assert!(on_disk.contains("\"memstead-mounts-3\""));
1636 assert!(
1638 on_disk.contains("\"mem-repo/.git\""),
1639 "expected relative gitdir, got: {on_disk}"
1640 );
1641 assert!(
1642 !on_disk.contains(tmp.path().to_str().unwrap()),
1643 "in-workspace path should not include the absolute tmp prefix: {on_disk}"
1644 );
1645 assert!(on_disk.contains("\"/global/cache/external.mem\""));
1647
1648 let reloaded = store.load(tmp.path()).unwrap();
1650 match &reloaded.mounts[0].storage {
1651 MountStorage::GitBranch { gitdir, .. } => {
1652 assert_eq!(gitdir, &tmp.path().join("mem-repo").join(".git"));
1653 }
1654 other => panic!("expected GitBranch storage, got {other:?}"),
1655 }
1656 match &reloaded.mounts[1].storage {
1657 MountStorage::Archive { path } => {
1658 assert_eq!(path, &PathBuf::from("/global/cache/external.mem"));
1659 }
1660 other => panic!("expected Archive storage, got {other:?}"),
1661 }
1662 }
1663
1664 #[test]
1665 fn load_absolute_inside_root_path_then_save_rewrites_relative() {
1666 let tmp = TempDir::new().unwrap();
1667 write_workspace_toml(
1668 tmp.path(),
1669 r#"
1670format = "memstead-git-branch-2"
1671
1672[persistence_adapter]
1673name = "file-two-layer"
1674"#,
1675 );
1676 let mounts_path = FileWorkspaceStore::mounts_json_path(tmp.path());
1681 std::fs::create_dir_all(mounts_path.parent().unwrap()).unwrap();
1682 let abs_gitdir = tmp.path().join("mem-repo").join(".git");
1683 let mounts_body = format!(
1684 r#"{{
1685 "format": "memstead-mounts-3",
1686 "mounts": [
1687 {{
1688 "mem": "engine",
1689 "schema": "default@1.0.0",
1690 "storage": {{
1691 "type": "git-branch",
1692 "gitdir": "{}",
1693 "branch": "engine"
1694 }},
1695 "capability": "write",
1696 "lifecycle": "eager",
1697 "cross_linkable": true
1698 }}
1699 ]
1700}}"#,
1701 abs_gitdir.to_str().unwrap()
1702 );
1703 std::fs::write(&mounts_path, &mounts_body).unwrap();
1704
1705 let store = FileWorkspaceStore::new();
1706 let workspace = store.load(tmp.path()).unwrap();
1709 match &workspace.mounts[0].storage {
1710 MountStorage::GitBranch { gitdir, .. } => assert_eq!(gitdir, &abs_gitdir),
1711 other => panic!("expected GitBranch storage, got {other:?}"),
1712 }
1713
1714 store.save_state(tmp.path(), &workspace).unwrap();
1717 let on_disk = std::fs::read_to_string(&mounts_path).unwrap();
1718 assert!(on_disk.contains("\"memstead-mounts-3\""));
1719 assert!(on_disk.contains("\"mem-repo/.git\""));
1720 assert!(!on_disk.contains(tmp.path().to_str().unwrap()));
1721 }
1722
1723 #[test]
1732 fn save_state_preserves_refs_heads_branch_form() {
1733 let tmp = TempDir::new().unwrap();
1734 write_workspace_toml(
1735 tmp.path(),
1736 r#"
1737format = "memstead-git-branch-2"
1738
1739[persistence_adapter]
1740name = "file-two-layer"
1741"#,
1742 );
1743 let store = FileWorkspaceStore::new();
1744 let original = Workspace {
1745 mounts: vec![Mount {
1746 mem: "engine".to_string(),
1747 schema: Some(pin("default@1.0.0")),
1748 storage: MountStorage::GitBranch {
1749 gitdir: tmp.path().join("mem-repo").join(".git"),
1750 branch: "refs/heads/demo/engine".to_string(),
1751 },
1752 capability: MountCapability::Write,
1753 lifecycle: MountLifecycle::Eager,
1754 cross_linkable: true,
1755 migration_target: None,
1756 }],
1757 settings: WorkspaceSettings::default(),
1758 };
1759 store.save_state(tmp.path(), &original).unwrap();
1760
1761 let on_disk =
1762 std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
1763 assert!(
1764 on_disk.contains("\"branch\": \"refs/heads/demo/engine\""),
1765 "expected fully-qualified ref on disk, got: {on_disk}"
1766 );
1767
1768 let reloaded = store.load(tmp.path()).unwrap();
1769 match &reloaded.mounts[0].storage {
1770 MountStorage::GitBranch { branch, .. } => {
1771 assert_eq!(branch, "refs/heads/demo/engine");
1772 }
1773 other => panic!("expected GitBranch storage, got {other:?}"),
1774 }
1775 }
1776
1777 #[test]
1787 fn load_preserves_short_form_branch_without_rewrite() {
1788 let tmp = TempDir::new().unwrap();
1789 write_workspace_toml(
1790 tmp.path(),
1791 r#"
1792format = "memstead-git-branch-2"
1793
1794[persistence_adapter]
1795name = "file-two-layer"
1796"#,
1797 );
1798 let mounts_path = FileWorkspaceStore::mounts_json_path(tmp.path());
1799 std::fs::create_dir_all(mounts_path.parent().unwrap()).unwrap();
1800 std::fs::write(
1801 &mounts_path,
1802 r#"{
1803 "format": "memstead-mounts-3",
1804 "mounts": [
1805 {
1806 "mem": "engine",
1807 "schema": "default@1.0.0",
1808 "storage": {
1809 "type": "git-branch",
1810 "gitdir": "mem-repo/.git",
1811 "branch": "demo/engine"
1812 },
1813 "capability": "write",
1814 "lifecycle": "eager",
1815 "cross_linkable": true
1816 }
1817 ]
1818}"#,
1819 )
1820 .unwrap();
1821
1822 let store = FileWorkspaceStore::new();
1823 let workspace = store.load(tmp.path()).unwrap();
1824 match &workspace.mounts[0].storage {
1825 MountStorage::GitBranch { branch, .. } => {
1826 assert_eq!(
1827 branch, "demo/engine",
1828 "reader must not silently rewrite short-form branch"
1829 );
1830 }
1831 other => panic!("expected GitBranch storage, got {other:?}"),
1832 }
1833 }
1834
1835 #[test]
1836 fn load_rejects_format_version_mismatch_on_toml() {
1837 let tmp = TempDir::new().unwrap();
1838 write_workspace_toml(
1839 tmp.path(),
1840 r#"
1841format = "memstead-git-branch-99"
1842
1843[persistence_adapter]
1844name = "file-two-layer"
1845"#,
1846 );
1847 let store = FileWorkspaceStore::new();
1848 let err = store.load(tmp.path()).unwrap_err();
1849 match err {
1850 StoreError::FormatMismatch {
1851 expected, found, ..
1852 } => {
1853 assert_eq!(expected, "memstead-git-branch-2");
1854 assert_eq!(found, "memstead-git-branch-99");
1855 }
1856 other => panic!("expected FormatMismatch, got {other:?}"),
1857 }
1858 }
1859
1860 #[test]
1861 fn load_rejects_format_version_mismatch_on_mounts_json() {
1862 let tmp = TempDir::new().unwrap();
1863 write_workspace_toml(
1864 tmp.path(),
1865 r#"
1866format = "memstead-git-branch-2"
1867
1868[persistence_adapter]
1869name = "file-two-layer"
1870"#,
1871 );
1872 let mounts_path = FileWorkspaceStore::mounts_json_path(tmp.path());
1873 std::fs::create_dir_all(mounts_path.parent().unwrap()).unwrap();
1874 std::fs::write(
1875 &mounts_path,
1876 r#"{ "format": "memstead-mounts-99", "mounts": [] }"#,
1877 )
1878 .unwrap();
1879 let store = FileWorkspaceStore::new();
1880 let err = store.load(tmp.path()).unwrap_err();
1881 assert!(matches!(err, StoreError::FormatMismatch { .. }));
1882 }
1883
1884 #[test]
1887 fn load_refuses_pre_rename_toml_as_legacy_layout() {
1888 let tmp = TempDir::new().unwrap();
1889 write_workspace_toml(
1890 tmp.path(),
1891 r#"
1892format = "memstead-git-branch-1"
1893
1894[persistence_adapter]
1895name = "file-two-layer"
1896"#,
1897 );
1898 let store = FileWorkspaceStore::new();
1899 let err = store.load(tmp.path()).unwrap_err();
1900 match err {
1901 StoreError::LegacyLayout { found, .. } => {
1902 assert_eq!(found, "memstead-git-branch-1");
1903 }
1904 other => panic!("expected LegacyLayout, got {other:?}"),
1905 }
1906 }
1907
1908 #[test]
1915 fn load_refuses_pre_rename_mounts_json_as_legacy_layout() {
1916 for legacy in ["memstead-mounts-1", "memstead-mounts-2"] {
1917 let tmp = TempDir::new().unwrap();
1918 write_workspace_toml(
1919 tmp.path(),
1920 r#"
1921format = "memstead-git-branch-2"
1922
1923[persistence_adapter]
1924name = "file-two-layer"
1925"#,
1926 );
1927 let mounts_path = FileWorkspaceStore::mounts_json_path(tmp.path());
1928 std::fs::create_dir_all(mounts_path.parent().unwrap()).unwrap();
1929 std::fs::write(
1930 &mounts_path,
1931 format!(
1932 r#"{{ "format": "{legacy}", "mounts": [{{ "unit": "notes", "storage": {{ "type": "folder", "path": "notes" }}, "capability": "write", "lifecycle": "eager", "cross_linkable": true }}] }}"#
1933 ),
1934 )
1935 .unwrap();
1936 let store = FileWorkspaceStore::new();
1937 let err = store.load(tmp.path()).unwrap_err();
1938 match err {
1939 StoreError::LegacyLayout { found, .. } => assert_eq!(found, legacy),
1940 other => panic!("expected LegacyLayout for {legacy}, got {other:?}"),
1941 }
1942 }
1943 }
1944
1945 #[test]
1946 fn load_rejects_invalid_toml() {
1947 let tmp = TempDir::new().unwrap();
1948 write_workspace_toml(tmp.path(), "this is not = valid = toml");
1949 let store = FileWorkspaceStore::new();
1950 let err = store.load(tmp.path()).unwrap_err();
1951 assert!(matches!(err, StoreError::Parse { .. }));
1952 }
1953
1954 #[test]
1955 fn load_rejects_unknown_top_level_key() {
1956 let tmp = TempDir::new().unwrap();
1960 write_workspace_toml(
1961 tmp.path(),
1962 "format = \"memstead-git-branch-2\"\nnonexistent_key = true\n",
1963 );
1964 let store = FileWorkspaceStore::new();
1965 let err = store.load(tmp.path()).unwrap_err();
1966 match err {
1967 StoreError::Parse { message, .. } => {
1968 assert!(
1969 message.contains("nonexistent_key"),
1970 "refusal must name the unknown key: {message}"
1971 );
1972 }
1973 other => panic!("expected Parse error, got {other:?}"),
1974 }
1975 }
1976
1977 #[test]
1978 fn instantiate_local_backend_handles_folder_archive_and_in_memory() {
1979 let tmp = TempDir::new().unwrap();
1980 let folder = folder_mount("local", tmp.path().to_path_buf());
1981 let archive_path = tmp.path().join("ext.mem");
1982 let f = std::fs::File::create(&archive_path).unwrap();
1984 let mut w = zip::ZipWriter::new(f);
1985 w.start_file("a.md", zip::write::SimpleFileOptions::default())
1986 .unwrap();
1987 w.write_all(b"# a").unwrap();
1988 w.finish().unwrap();
1989 let archive = Mount {
1990 mem: "external".to_string(),
1991 schema: Some(pin("default@1.0.0")),
1992 storage: MountStorage::Archive { path: archive_path },
1993 capability: MountCapability::ReadOnly,
1994 lifecycle: MountLifecycle::Lazy,
1995 cross_linkable: false,
1996 migration_target: None,
1997 };
1998 let in_memory = Mount {
1999 mem: "session".to_string(),
2000 schema: Some(pin("default@1.0.0")),
2001 storage: MountStorage::InMemory,
2002 capability: MountCapability::Write,
2003 lifecycle: MountLifecycle::Eager,
2004 cross_linkable: true,
2005 migration_target: None,
2006 };
2007
2008 let _: Box<dyn MemBackend> = instantiate_local_backend(&folder).unwrap();
2009 let _: Box<dyn MemBackend> = instantiate_local_backend(&archive).unwrap();
2010 let _: Box<dyn MemBackend> = instantiate_local_backend(&in_memory).unwrap();
2013 }
2014
2015 #[test]
2020 fn save_state_round_trips_in_memory_variant_unambiguously() {
2021 let tmp = TempDir::new().unwrap();
2022 write_workspace_toml(
2023 tmp.path(),
2024 r#"
2025format = "memstead-git-branch-2"
2026
2027[persistence_adapter]
2028name = "file-two-layer"
2029"#,
2030 );
2031 let store = FileWorkspaceStore::new();
2032 let original = Workspace {
2033 mounts: vec![
2034 folder_mount("local", PathBuf::from("/work/mem")),
2035 Mount {
2036 mem: "session".to_string(),
2037 schema: Some(pin("default@1.0.0")),
2038 storage: MountStorage::InMemory,
2039 capability: MountCapability::Write,
2040 lifecycle: MountLifecycle::Eager,
2041 cross_linkable: true,
2042 migration_target: None,
2043 },
2044 ],
2045 settings: WorkspaceSettings::default(),
2046 };
2047 store.save_state(tmp.path(), &original).unwrap();
2048
2049 let raw =
2051 std::fs::read_to_string(FileWorkspaceStore::mounts_json_path(tmp.path())).unwrap();
2052 assert!(raw.contains("\"type\": \"in-memory\""), "got: {raw}");
2053
2054 let reloaded = store.load(tmp.path()).unwrap();
2055 assert_eq!(reloaded.mounts.len(), 2);
2056 let session = reloaded
2059 .mounts
2060 .iter()
2061 .find(|m| m.mem == "session")
2062 .expect("session mount survives reload");
2063 assert_eq!(session.storage, MountStorage::InMemory);
2064 let local = reloaded.mounts.iter().find(|m| m.mem == "local").unwrap();
2067 assert!(matches!(local.storage, MountStorage::Folder { .. }));
2068 }
2069
2070 #[test]
2071 fn instantiate_local_backend_rejects_git_branch_with_typed_error() {
2072 let mount = Mount {
2073 mem: "engine".to_string(),
2074 schema: Some(pin("default@1.0.0")),
2075 storage: MountStorage::GitBranch {
2076 gitdir: PathBuf::from("/some/path/.git"),
2077 branch: "engine".to_string(),
2078 },
2079 capability: MountCapability::Write,
2080 lifecycle: MountLifecycle::Eager,
2081 cross_linkable: true,
2082 migration_target: None,
2083 };
2084 match instantiate_local_backend(&mount) {
2088 Err(InstantiateError::GitBranchBackendUnavailable { mem }) => {
2089 assert_eq!(mem, "engine");
2090 }
2091 Ok(_) => panic!("expected GitBranchBackendUnavailable, got Ok"),
2092 }
2093 }
2094
2095 #[test]
2096 fn detect_layout_returns_empty_for_unrecognised_workspace() {
2097 let tmp = TempDir::new().unwrap();
2098 assert_eq!(detect_layout(tmp.path()), Layout::Empty);
2099 }
2100 #[test]
2101 fn detect_layout_returns_new_when_workspace_toml_present() {
2102 let tmp = TempDir::new().unwrap();
2103 write_workspace_toml(
2104 tmp.path(),
2105 "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2106 );
2107 assert_eq!(detect_layout(tmp.path()), Layout::New);
2108 }
2109}