#![cfg(test)]
use std::path::Path;
use tempfile::TempDir;
use crate::backend::{BackendError, MemBackend};
use crate::engine::test_helpers::*;
use crate::engine::{Engine, EngineError, RelateEntityArgs};
use crate::entity::EntityId;
use crate::ops::{Direction, SearchScope, WarningHint};
use crate::provenance::Provenance;
use crate::storage::{ArchiveBackend, FilesystemBackend};
use crate::vcs::CommitContext;
use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
#[test]
fn artifact_candidates_follow_decision_29_priority() {
use super::artifact_candidates;
assert_eq!(artifact_candidates("", "a/b.rs"), vec!["a/b.rs"]);
assert_eq!(artifact_candidates(".", "a/b.rs"), vec!["a/b.rs"]);
assert_eq!(artifact_candidates("./", "a/b.rs"), vec!["a/b.rs"]);
assert_eq!(
artifact_candidates("sub", "a/b.rs"),
vec!["sub/a/b.rs", "a/b.rs"]
);
assert_eq!(
artifact_candidates("sub/", "a/b.rs"),
vec!["sub/a/b.rs", "a/b.rs"]
);
assert_eq!(
artifact_candidates("sub", "sub/x.rs"),
vec!["sub/sub/x.rs", "sub/x.rs"]
);
assert_eq!(
artifact_candidates("sub", "../dev/x.md"),
vec!["../dev/x.md"]
);
assert_eq!(
artifact_candidates("../dev", "../dev/x.md"),
vec!["../dev/x.md"]
);
assert_eq!(artifact_candidates("sub", ".."), vec![".."]);
}
#[test]
fn schema_origin_classifies_builtin_first_party_and_unknown_third_party() {
use std::sync::Arc;
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let engine = Engine::from_mounts(vec![(
folder_mount("specs", tmp.path().to_path_buf()),
Box::new(FilesystemBackend::new(tmp.path().to_path_buf())) as Box<dyn MemBackend>,
)])
.unwrap();
let builtin = engine.builtin_schemas()[0].clone();
assert_eq!(
engine.schema_origin(&builtin),
OriginClass::FirstParty,
"a built-in schema is first-party"
);
let foreign = Arc::new(memstead_schema::Schema {
manifest: builtin.manifest.clone(),
version: semver::Version::new(99, 0, 0),
types: builtin.types.clone(),
});
assert_eq!(
engine.schema_origin(&foreign),
OriginClass::ThirdParty,
"a schema in neither catalogue classifies third-party (safe default)"
);
}
#[test]
fn mem_origin_class_writable_first_party_readonly_third_party() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let writable_dir = tmp.path().join("writable");
std::fs::create_dir_all(&writable_dir).unwrap();
let writer = FilesystemBackend::new(writable_dir.clone());
let body = "---\ntype: spec\n---\n# Ext\n\n## Identity\n\nFrom an archive.\n";
let archive_path = build_archive(tmp.path(), "ext", &[("ext.md", body.as_bytes())]);
let engine = Engine::from_mounts(vec![
(
folder_mount("local", writable_dir),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("external", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
),
])
.unwrap();
assert_eq!(
engine.mem_origin_class("local"),
OriginClass::FirstParty,
"a writable mount is first-party"
);
assert_eq!(
engine.mem_origin_class("external"),
OriginClass::ThirdParty,
"a read-only mount is third-party"
);
assert_eq!(
engine.mem_origin_class("no-such-mem"),
OriginClass::ThirdParty,
"an unknown mem is third-party (safe default)"
);
}
#[test]
fn entity_origin_inherits_the_mem_class_without_foreign_evidence() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let writable_dir = tmp.path().join("writable");
std::fs::create_dir_all(&writable_dir).unwrap();
std::fs::write(
writable_dir.join("own.md"),
"---\ntype: spec\n---\n# Own\n\n## Identity\n\nAuthored here.\n",
)
.unwrap();
let writer = FilesystemBackend::new(writable_dir.clone());
let body = "---\ntype: spec\n---\n# Ext\n\n## Identity\n\nFrom an archive.\n";
let archive_path = build_archive(tmp.path(), "ext", &[("ext.md", body.as_bytes())]);
let engine = Engine::from_mounts(vec![
(
folder_mount("local", writable_dir),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("external", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
),
])
.unwrap();
assert_eq!(
engine.entity_origin_class(&crate::EntityId::new("local", "own")),
OriginClass::FirstParty,
"an entity of a writable mem with no merge mark is first-party"
);
assert_eq!(
engine.entity_origin_class(&crate::EntityId::new("external", "ext")),
OriginClass::ThirdParty,
"every entity of a read-only mount stays third-party"
);
}
#[test]
fn check_row_origin_follows_the_declared_owner_identities() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().join("writable");
std::fs::create_dir_all(&dir).unwrap();
let mut engine = Engine::from_mounts(vec![(
folder_mount("local", dir.clone()),
Box::new(FilesystemBackend::new(dir)) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(!engine.declares_owner_identities());
assert_eq!(
engine.check_row_origin_class("local", Some("some-other-model")),
OriginClass::FirstParty,
"undeclared: every ledger identity inherits the mem's class"
);
engine.declare_owner_identities(["ops-session"]);
assert!(engine.declares_owner_identities());
assert_eq!(
engine.check_row_origin_class("local", Some("ops-session")),
OriginClass::FirstParty,
"a declared owner identity writes first-party prose"
);
assert_eq!(
engine.check_row_origin_class("local", Some("some-other-model")),
OriginClass::ThirdParty,
"an identity outside the declared set authored foreign prose"
);
assert_eq!(
engine.check_row_origin_class("local", None),
OriginClass::FirstParty,
"no identity is unconfirmable, never a guessed third-party"
);
}
#[test]
fn declared_origin_overrides_inference_per_mem() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let body = "---\ntype: spec\n---\n# Ext\n\n## Identity\n\nFrom an archive.\n";
let vouched_path = build_archive(tmp.path(), "vouched", &[("v.md", body.as_bytes())]);
let other_path = build_archive(tmp.path(), "other", &[("o.md", body.as_bytes())]);
let mut engine = Engine::from_mounts(vec![
(
archive_mount("vouched", vouched_path.clone()),
Box::new(ArchiveBackend::new(vouched_path)) as Box<dyn MemBackend>,
),
(
archive_mount("other", other_path.clone()),
Box::new(ArchiveBackend::new(other_path)) as Box<dyn MemBackend>,
),
])
.unwrap();
engine.declare_mem_origin("vouched", OriginClass::FirstParty);
assert_eq!(
engine.mem_origin_class("vouched"),
OriginClass::FirstParty,
"the deployment's declaration wins over the read-only inference"
);
assert_eq!(
engine.mem_origin_class("other"),
OriginClass::ThirdParty,
"an undeclared sibling mount keeps the safe default"
);
}
#[test]
fn schema_origin_third_party_until_pinned_by_a_writable_mount() {
use memstead_schema::SchemaRef;
use crate::render::OriginClass;
let manifest = r#"name: trust-test
version: 0.1.0
description: adopt-gate test schema
when_to_use: tests
types:
- doc
relationships:
mode: strict
definitions:
- name: _default
description: fallback
default_weight: 1.0
community:
resolution: 1.0
seed: 42
"#;
let pin = SchemaRef::new("trust-test", semver::Version::new(0, 1, 0));
let mk_engine = |cap: MountCapability| -> Engine {
let tmp = TempDir::new().unwrap();
let schemas_dir = tmp.path().join("schemas");
std::fs::create_dir_all(&schemas_dir).unwrap();
write_schema_files_with_default_type(&schemas_dir, "trust-test", manifest, &["doc"]);
let mem_dir = tmp.path().join("mem");
std::fs::create_dir_all(&mem_dir).unwrap();
let mount = Mount {
mem: "v".to_string(),
schema: Some(pin.clone()),
storage: MountStorage::Folder {
path: mem_dir.clone(),
},
capability: cap,
lifecycle: MountLifecycle::Eager,
cross_linkable: true,
migration_target: None,
};
let backend = Box::new(FilesystemBackend::new(mem_dir)) as Box<dyn MemBackend>;
std::mem::forget(tmp);
Engine::from_mounts_with_schemas_dir(vec![(mount, backend)], Some(&schemas_dir)).unwrap()
};
let ro = mk_engine(MountCapability::ReadOnly);
let schema = ro.schemas().get("v").expect("schema resolved").clone();
assert_eq!(
ro.schema_origin(&schema),
OriginClass::ThirdParty,
"a non-built-in schema pinned only by a read-only mount is third-party"
);
let rw = mk_engine(MountCapability::Write);
let schema = rw.schemas().get("v").expect("schema resolved").clone();
assert_eq!(
rw.schema_origin(&schema),
OriginClass::FirstParty,
"a writable mount pinning the schema adopts it → first-party"
);
}
#[test]
fn archive_provenance_surfaces_per_entity_and_reports_absence() {
use memstead_schema::History;
let tmp = TempDir::new().unwrap();
let config = br#"{"format":3,"name":"seed","version":"0.1.0","schema":"default@1.0.0"}"#;
let alpha = b"---\ntype: spec\n---\n# Alpha\n\n## Identity\n\na\n\n## Purpose\n\np\n";
let beta = b"---\ntype: spec\n---\n# Beta\n\n## Identity\n\nb\n\n## Purpose\n\np\n";
let provenance = br#"{"format":1,"history":"summarised","entities":{"alpha":{"rationale":"why alpha exists","kind":"create","timestamp":"2026-06-24T00:00:00Z","actor":"agent"}}}"#;
let archive = build_archive(
tmp.path(),
"seed",
&[
(".memstead/config.json", config),
("alpha.md", alpha),
("beta.md", beta),
(".memstead/provenance.json", provenance),
],
);
let engine = Engine::from_mounts(vec![(
archive_mount("seed", archive.clone()),
Box::new(ArchiveBackend::new(archive)) as Box<dyn MemBackend>,
)])
.unwrap();
let prov = engine
.archive_provenance_for("seed")
.expect("provenance payload read from the archive");
assert_eq!(
prov.history,
History::Summarised,
"history-not-shipped is observable"
);
assert_eq!(
prov.entity("alpha").and_then(|r| r.rationale.as_deref()),
Some("why alpha exists"),
"noted entity surfaces its rationale"
);
assert!(
prov.entity("beta").is_none(),
"unnoted entity is absent (reported absent, not fabricated)"
);
}
#[test]
fn archive_without_provenance_reports_absent() {
let tmp = TempDir::new().unwrap();
let config = br#"{"format":3,"name":"seed","version":"0.1.0","schema":"default@1.0.0"}"#;
let alpha = b"---\ntype: spec\n---\n# Alpha\n\n## Identity\n\na\n\n## Purpose\n\np\n";
let archive = build_archive(
tmp.path(),
"seed",
&[(".memstead/config.json", config), ("alpha.md", alpha)],
);
let engine = Engine::from_mounts(vec![(
archive_mount("seed", archive.clone()),
Box::new(ArchiveBackend::new(archive)) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(
engine.archive_provenance_for("seed").is_none(),
"an archive without a provenance payload reports provenance absent"
);
}
#[test]
fn folder_mount_routes_reads_to_filesystem_backend() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
<FilesystemBackend as MemBackend>::write_entity(&writer, Path::new("a.md"), b"alpha").unwrap();
<FilesystemBackend as MemBackend>::commit(&writer, "seed", &CommitContext::internal()).unwrap();
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let mut paths: Vec<String> = engine
.list_entities("specs")
.unwrap()
.into_iter()
.map(|p| p.to_string_lossy().into_owned())
.collect();
paths.sort();
assert_eq!(paths, vec!["a.md".to_string()]);
assert_eq!(
engine.read_entity("specs", Path::new("a.md")).unwrap(),
Some(b"alpha".to_vec())
);
}
#[test]
fn heterogeneous_mounts_route_to_correct_backend() {
let tmp = TempDir::new().unwrap();
let folder_dir = tmp.path().join("folder-mem");
std::fs::create_dir_all(&folder_dir).unwrap();
let folder_writer = FilesystemBackend::new(folder_dir.clone());
<FilesystemBackend as MemBackend>::write_entity(
&folder_writer,
Path::new("local.md"),
b"local",
)
.unwrap();
<FilesystemBackend as MemBackend>::commit(&folder_writer, "seed", &CommitContext::internal())
.unwrap();
let archive_path = build_archive(
tmp.path(),
"external",
&[("ext.md", b"external"), ("dir/nested.md", b"nested")],
);
let engine = Engine::from_mounts(vec![
(
folder_mount("local", folder_dir),
Box::new(folder_writer) as Box<dyn MemBackend>,
),
(
archive_mount("external", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
assert_eq!(engine.mem_names(), vec!["local", "external"]);
assert_eq!(
engine.read_entity("local", Path::new("local.md")).unwrap(),
Some(b"local".to_vec())
);
assert_eq!(
engine.read_entity("external", Path::new("ext.md")).unwrap(),
Some(b"external".to_vec())
);
assert_eq!(
engine
.read_entity("external", Path::new("dir/nested.md"))
.unwrap(),
Some(b"nested".to_vec())
);
assert_eq!(
engine.read_entity("local", Path::new("ext.md")).unwrap(),
None
);
assert_eq!(
engine
.read_entity("external", Path::new("local.md"))
.unwrap(),
None
);
}
#[test]
fn edge_is_from_readonly_classifies_every_edge_by_source_mount_capability() {
let tmp = TempDir::new().unwrap();
let folder_dir = tmp.path().join("local-mem");
std::fs::create_dir_all(&folder_dir).unwrap();
let folder_writer = FilesystemBackend::new(folder_dir.clone());
let local_md = b"---\ntype: spec\n---\n# Note\n\n## Identity\n\nsee [[external:archived]] for prior context.\n\n## Relationships\n\n- **REFERENCES**: [[external:archived]]\n";
<FilesystemBackend as MemBackend>::write_entity(&folder_writer, Path::new("note.md"), local_md)
.unwrap();
<FilesystemBackend as MemBackend>::commit(&folder_writer, "seed", &CommitContext::internal())
.unwrap();
let archive_md = b"---\ntype: spec\n---\n# Archived\n\n## Identity\n\nrefers back to [[local:note]] for the current revision.\n\n## Relationships\n\n- **REFERENCES**: [[local:note]]\n";
let archive_path = build_archive(tmp.path(), "external", &[("archived.md", archive_md)]);
let engine = Engine::from_mounts(vec![
(
folder_mount("local", folder_dir),
Box::new(folder_writer) as Box<dyn MemBackend>,
),
(
archive_mount("external", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
let local_id = EntityId::new("local", "note");
let archived_id = EntityId::new("external", "archived");
assert!(engine.get_entity(&local_id).is_some());
assert!(engine.get_entity(&archived_id).is_some());
assert!(matches!(
engine.capability("local").unwrap(),
MountCapability::Write
));
assert!(matches!(
engine.capability("external").unwrap(),
MountCapability::ReadOnly
));
let mut seen_write_edge = false;
let mut seen_readonly_edge = false;
for from in engine.store().all_ids().cloned().collect::<Vec<_>>() {
for _edge in engine.store().outgoing(&from) {
let is_ro = engine.edge_is_from_readonly(&from);
match engine.capability(from.mem()).unwrap() {
MountCapability::Write => {
assert!(
!is_ro,
"edge from write mem {} reported as ReadOnly",
from.mem()
);
seen_write_edge = true;
}
MountCapability::ReadOnly => {
assert!(
is_ro,
"edge from readonly mem {} reported as Write",
from.mem()
);
seen_readonly_edge = true;
}
}
}
}
assert!(
seen_write_edge,
"fixture must produce at least one edge from a write mem"
);
assert!(
seen_readonly_edge,
"fixture must produce at least one edge from a readonly mem"
);
let phantom = EntityId::new("missing-mem", "phantom");
assert!(
!engine.edge_is_from_readonly(&phantom),
"absent mount must not be reported as ReadOnly"
);
}
#[test]
fn cross_mem_link_allowed_same_mem_always_true() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
assert!(engine.cross_mem_link_allowed("specs", "specs"));
assert!(engine.cross_mem_link_allowed("anywhere", "anywhere"));
}
#[test]
fn cross_mem_link_allowed_absent_denies_by_default() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
assert!(!engine.cross_mem_link_allowed("specs", "engine"));
assert!(!engine.cross_mem_link_allowed("missing", "anywhere"));
}
#[test]
fn cross_mem_link_allowed_wildcard_admits_any_target() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.cross_mem_links
.insert("specs".to_string(), CrossLinkValue::Wildcard);
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("specs", "engine"));
assert!(engine.cross_mem_link_allowed("specs", "macos"));
assert!(engine.cross_mem_link_allowed("specs", "any-other"));
assert!(!engine.cross_mem_link_allowed("engine", "specs"));
}
#[test]
fn cross_mem_link_allowed_allowlist_enforces_membership() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings.cross_mem_links.insert(
"specs".to_string(),
CrossLinkValue::List(vec!["engine".to_string(), "macos".to_string()]),
);
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("specs", "engine"));
assert!(engine.cross_mem_link_allowed("specs", "macos"));
assert!(!engine.cross_mem_link_allowed("specs", "external"));
}
#[test]
fn cross_mem_link_allowed_synthesises_from_matching_create_rule_wildcard() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::Wildcard),
});
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
assert!(engine.cross_mem_link_allowed("exec-foo", "engine"));
assert!(!engine.cross_mem_link_allowed("orphan", "specs"));
}
#[test]
fn cross_mem_link_allowed_synthesises_for_hierarchical_mem() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let mount = Mount {
mem: "project".into(),
schema: Some(pin("default")),
storage: MountStorage::GitBranch {
gitdir: mem_dir.join(".git"),
branch: "memstead/project".into(),
},
capability: MountCapability::Write,
lifecycle: MountLifecycle::Eager,
cross_linkable: true,
migration_target: None,
};
let writer = FilesystemBackend::new(mem_dir.clone());
let mut engine =
Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "memstead/*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::List(vec!["engine".to_string()])),
});
engine.set_settings(settings);
assert!(
engine.cross_mem_link_allowed("project", "engine"),
"synthesis must match via the composed `memstead/project` candidate"
);
assert!(
!engine.cross_mem_link_allowed("project", "macos"),
"a target outside the rule's default_cross_links is still denied"
);
}
#[test]
fn cross_mem_link_allowed_synthesises_from_matching_create_rule_list() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::List(vec!["specs".to_string()])),
});
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
assert!(!engine.cross_mem_link_allowed("exec-foo", "engine"));
}
#[test]
fn cross_mem_link_allowed_explicit_policy_wins_over_synthesis() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.cross_mem_links
.insert("exec-foo".to_string(), CrossLinkValue::Wildcard);
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("exec-foo", "engine"));
}
#[test]
fn cross_mem_link_allowed_synthesis_unions_into_explicit_list() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings.cross_mem_links.insert(
"exec-foo".to_string(),
CrossLinkValue::List(vec!["specs".to_string()]),
);
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::List(vec!["macos".to_string()])),
});
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
assert!(engine.cross_mem_link_allowed("exec-foo", "macos"));
assert!(!engine.cross_mem_link_allowed("exec-foo", "engine"));
}
#[test]
fn cross_mem_link_allowed_set_settings_invalidates_compiled_rule_cache() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut s1 = crate::workspace::WorkspaceSettings::default();
s1.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::List(vec!["specs".to_string()])),
});
engine.set_settings(s1);
assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
let mut s2 = crate::workspace::WorkspaceSettings::default();
s2.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: None,
});
engine.set_settings(s2);
assert!(!engine.cross_mem_link_allowed("exec-foo", "specs"));
}
#[test]
fn cross_mem_link_allowed_malformed_glob_falls_back_to_explicit_policy() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "[unclosed".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::Wildcard),
});
settings
.cross_mem_links
.insert("specs".to_string(), CrossLinkValue::Wildcard);
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("specs", "engine"));
assert!(!engine.cross_mem_link_allowed("orphan", "anything"));
}
#[test]
fn cross_mem_link_allowed_empty_list_denies_all_cross_mem_targets() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.cross_mem_links
.insert("specs".to_string(), CrossLinkValue::List(Vec::new()));
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("specs", "specs"));
assert!(!engine.cross_mem_link_allowed("specs", "engine"));
assert!(!engine.cross_mem_link_allowed("specs", "anything"));
}
#[test]
fn from_mounts_load_warnings_merge_into_health_summary() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let body = "---\ntype: spec\n---\n# Dup2\n\n## Identity\n\na.\n\n## Identity\n\nb.\n";
std::fs::write(mem_dir.join("dup2.md"), body).unwrap();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let summary = engine.health();
assert!(
summary
.warnings
.iter()
.any(|w| matches!(w, WarningHint::DuplicateSectionHeading { .. })),
"health() must merge load_warnings into summary.warnings: {:?}",
summary.warnings,
);
}
#[test]
fn workspace_root_accessor_is_none_for_engine_built_from_mounts() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let mut mount = folder_mount("specs", mem_dir);
mount.schema = Some("default@1.3.0".parse().unwrap());
let engine =
Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
assert!(
engine.workspace_root().is_none(),
"from_mounts has no workspace path",
);
assert!(
engine
.load_warnings()
.iter()
.all(|w| w.code() == "MOUNT_UNBACKED"),
"{:?}",
engine.load_warnings()
);
}
#[test]
fn health_omits_outer_repo_warning_when_workspace_root_unset() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let health = engine.health();
assert!(
!health
.warnings
.iter()
.any(|w| matches!(w, WarningHint::OuterRepoNotIgnoringMemRepo { .. })),
"outer-repo check must skip when workspace_root is None",
);
}
#[test]
fn writable_mem_names_filters_by_capability() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("writable", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("sealed", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
let names = engine.writable_mem_names();
assert_eq!(names, vec!["writable"]);
}
#[test]
fn default_writable_mem_is_declaration_first_not_alphabetical() {
let tmp = TempDir::new().unwrap();
let test_dir = tmp.path().join("test");
let other_dir = tmp.path().join("other");
std::fs::create_dir_all(&test_dir).unwrap();
std::fs::create_dir_all(&other_dir).unwrap();
let engine = Engine::from_mounts(vec![
(
folder_mount("test", test_dir.clone()),
Box::new(FilesystemBackend::new(test_dir)) as Box<dyn MemBackend>,
),
(
folder_mount("other", other_dir.clone()),
Box::new(FilesystemBackend::new(other_dir)) as Box<dyn MemBackend>,
),
])
.unwrap();
assert_eq!(
engine.default_writable_mem(),
Some("test"),
"default must be the declaration-first writable mem, not the alphabetically-first",
);
}
#[test]
fn default_writable_mem_follows_declaration_order() {
let tmp = TempDir::new().unwrap();
let other_dir = tmp.path().join("other");
let test_dir = tmp.path().join("test");
std::fs::create_dir_all(&other_dir).unwrap();
std::fs::create_dir_all(&test_dir).unwrap();
let engine = Engine::from_mounts(vec![
(
folder_mount("other", other_dir.clone()),
Box::new(FilesystemBackend::new(other_dir)) as Box<dyn MemBackend>,
),
(
folder_mount("test", test_dir.clone()),
Box::new(FilesystemBackend::new(test_dir)) as Box<dyn MemBackend>,
),
])
.unwrap();
assert_eq!(engine.default_writable_mem(), Some("other"));
}
#[test]
fn default_writable_mem_none_without_writable_mount() {
let tmp = TempDir::new().unwrap();
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![(
archive_mount("sealed", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
)])
.unwrap();
assert_eq!(engine.default_writable_mem(), None);
}
#[test]
fn folder_path_for_mem_returns_path_for_folder_mounts_only() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemBackend::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("specs", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("sealed", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
assert_eq!(engine.folder_path_for_mem("specs"), Some(mem_dir.as_path()),);
assert_eq!(engine.folder_path_for_mem("sealed"), None);
assert_eq!(engine.folder_path_for_mem("missing"), None);
}
#[test]
fn mount_accessor_returns_public_mount_shape() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("writable", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("sealed", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path.clone())),
),
])
.unwrap();
let folder = engine.mount("writable").expect("known mem");
assert!(matches!(folder.storage, MountStorage::Folder { .. }));
assert_eq!(folder.capability, MountCapability::Write);
let archive = engine.mount("sealed").expect("known mem");
match &archive.storage {
MountStorage::Archive { path } => assert_eq!(path, &archive_path),
other => panic!("expected Archive storage, got {other:?}"),
}
assert_eq!(archive.capability, MountCapability::ReadOnly);
assert!(engine.mount("missing").is_none());
let mounts = engine.mounts();
assert_eq!(mounts.len(), 2);
assert_eq!(mounts[0].mem, "writable");
assert_eq!(mounts[1].mem, "sealed");
}
#[test]
fn mem_router_writable_set_matches_writable_mount_capability() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemBackend::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("specs", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("ext", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
let router = engine.mem_router();
assert!(router.is_writable("specs"));
assert!(!router.is_writable("ext"));
assert!(router.is_visible("specs"));
assert!(router.is_visible("ext"));
let writable: std::collections::HashSet<&String> = router.writable_mems().iter().collect();
assert_eq!(writable.len(), 1);
assert!(writable.contains(&"specs".to_string()));
}
#[test]
fn mem_router_origin_is_explicit_toml_for_workspace_mounts() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let origin = engine
.mem_router()
.origin_for_mem("specs")
.expect("known mem");
assert_eq!(origin.kind(), "explicit");
}
#[test]
fn mem_router_dir_for_writable_folder_mount_matches_storage_path() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
assert_eq!(
engine.mem_router().dir_for_mem("specs"),
Some(mem_dir.as_path()),
);
assert_eq!(engine.mem_router().dir_for_mem("unknown"), None);
}
#[test]
fn mem_router_archive_path_for_read_only_archive_mount() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemBackend::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("ext", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path.clone())),
),
])
.unwrap();
let router = engine.mem_router();
assert_eq!(
router.archive_path_for_mem("ext"),
Some(archive_path.as_path()),
);
assert_eq!(router.archive_path_for_mem("specs"), None);
}
#[test]
fn read_mem_config_via_backend_trait_folder_reads_bytes() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
let body = br#"{
"format": 1,
"schema": "default@1.0.0",
"writeGuidance": { "tone": "neutral" }
}"#;
std::fs::write(mem_dir.join(".memstead").join("config.json"), body).unwrap();
let writer = FilesystemBackend::new(mem_dir);
let result = MemBackend::read_mem_config(&writer).unwrap();
let bytes = result.expect("config bytes must surface");
let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(parsed["schema"], "default@1.0.0");
}
#[test]
fn read_mem_config_via_backend_trait_folder_missing_returns_none() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir);
let result = MemBackend::read_mem_config(&writer).unwrap();
assert!(result.is_none());
}
#[test]
fn read_mem_config_via_backend_trait_archive_reads_bytes() {
let tmp = TempDir::new().unwrap();
let archive_path = tmp.path().join("seed.mem");
let body = br#"{
"format": 1,
"schema": "default@1.0.0",
"writeGuidance": { "tone": "archive" }
}"#;
{
let file = std::fs::File::create(&archive_path).unwrap();
let mut writer = zip::ZipWriter::new(file);
writer
.start_file(
".memstead/config.json",
zip::write::SimpleFileOptions::default(),
)
.unwrap();
use std::io::Write;
writer.write_all(body).unwrap();
writer.finish().unwrap();
}
let backend = ArchiveBackend::new(archive_path);
let result = MemBackend::read_mem_config(&backend).unwrap();
let bytes = result.expect("config bytes must surface");
let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(parsed["writeGuidance"]["tone"], "archive");
}
#[test]
fn mem_config_for_returns_none_when_no_config_file_present() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(engine.mem_config_for("specs").is_none());
}
#[test]
fn mem_config_for_returns_some_when_config_file_present() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
let config_body = r#"{
"format": 1,
"schema": "default@1.0.0",
"writeGuidance": {
"tone": "neutral",
"voice": "active"
}
}"#;
std::fs::write(mem_dir.join(".memstead").join("config.json"), config_body).unwrap();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let cfg = engine
.mem_config_for("specs")
.expect("mem_config should load");
assert_eq!(cfg.write_guidance.len(), 2);
assert_eq!(
cfg.write_guidance.get("tone").and_then(|v| v.as_str()),
Some("neutral"),
);
assert_eq!(
cfg.write_guidance.get("voice").and_then(|v| v.as_str()),
Some("active"),
);
}
#[test]
fn mem_config_for_unknown_mem_returns_none() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(engine.mem_config_for("missing").is_none());
}
#[test]
fn mem_config_for_archive_mount_returns_none() {
let tmp = TempDir::new().unwrap();
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![(
archive_mount("ext", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(engine.mem_config_for("ext").is_none());
}
#[test]
fn mem_configs_named_iterates_only_mounts_with_config() {
let tmp = TempDir::new().unwrap();
let with_config = tmp.path().join("specs");
let without_config = tmp.path().join("memos");
std::fs::create_dir_all(with_config.join(".memstead")).unwrap();
std::fs::create_dir_all(&without_config).unwrap();
let config_body = r#"{
"format": 1,
"schema": "default@1.0.0",
"writeGuidance": { "tone": "neutral" }
}"#;
std::fs::write(
with_config.join(".memstead").join("config.json"),
config_body,
)
.unwrap();
let engine = Engine::from_mounts(vec![
(
folder_mount("specs", with_config.clone()),
Box::new(FilesystemBackend::new(with_config)) as Box<dyn MemBackend>,
),
(
folder_mount("memos", without_config.clone()),
Box::new(FilesystemBackend::new(without_config)) as Box<dyn MemBackend>,
),
])
.unwrap();
let yielded: Vec<(&str, usize)> = engine
.mem_configs_named()
.map(|(name, cfg)| (name, cfg.write_guidance.len()))
.collect();
assert_eq!(yielded, vec![("specs", 1)]);
}
#[test]
fn schema_for_returns_some_for_known_mem_and_none_for_unknown() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(engine.schema_for("specs").is_some());
assert!(engine.schema_for("missing").is_none());
}
#[test]
fn gitdir_for_unknown_mem_returns_unknown_mem() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.gitdir_for("missing").unwrap_err();
assert!(matches!(err, EngineError::UnknownMem { name: v, .. } if v == "missing"));
}
#[test]
fn gitdir_for_folder_mount_returns_no_gitdir_error() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.gitdir_for("specs").unwrap_err();
match err {
EngineError::Mem(msg) => assert!(msg.contains("no resolved gitdir")),
other => panic!("expected EngineError::Mem, got {other:?}"),
}
}
#[test]
fn worktree_for_folder_mount_returns_storage_path() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let worktree = engine.worktree_for("specs").unwrap();
assert_eq!(worktree, mem_dir);
}
#[test]
fn worktree_for_unknown_mem_returns_unknown_mem() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.worktree_for("missing").unwrap_err();
assert!(matches!(err, EngineError::UnknownMem { name: v, .. } if v == "missing"));
}
#[test]
fn worktree_for_archive_mount_returns_archive_backed_error() {
let tmp = TempDir::new().unwrap();
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![(
archive_mount("ext", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.worktree_for("ext").unwrap_err();
match err {
EngineError::Mem(msg) => assert!(msg.contains("archive-backed")),
other => panic!("expected EngineError::Mem, got {other:?}"),
}
}
#[test]
fn mem_head_sha_for_folder_mount_is_none() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let head = engine.mem_head_sha("specs").unwrap();
assert_eq!(head, None);
}
#[test]
fn mem_head_sha_unknown_mem_returns_unknown_mem() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.mem_head_sha("missing").unwrap_err();
assert!(matches!(err, EngineError::UnknownMem { name: v, .. } if v == "missing"));
}
#[test]
fn capability_surfaces_per_mount() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("writable", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("read-only", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
assert_eq!(
engine.capability("writable").unwrap(),
MountCapability::Write
);
assert_eq!(
engine.capability("read-only").unwrap(),
MountCapability::ReadOnly
);
assert!(matches!(
engine.capability("missing"),
Err(EngineError::UnknownMem { .. })
));
}
#[test]
fn read_provenance_routes_through_backend() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let backend_handle: &dyn MemBackend = &writer;
backend_handle
.append_provenance(&Provenance::new(
std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000),
crate::ProvenanceKind::Create,
Some("v:e".into()),
crate::vcs::Actor::Cli,
None,
Some("first".into()),
))
.unwrap();
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let records = engine.read_provenance("specs", None).unwrap();
assert_eq!(records.len(), 1);
assert_eq!(records[0].kind, crate::ProvenanceKind::Create);
assert_eq!(records[0].entity.as_deref(), Some("v:e"));
assert_eq!(records[0].note.as_deref(), Some("first"));
}
#[test]
fn archive_mount_returns_sealed_indirectly_through_backend_layer() {
let tmp = TempDir::new().unwrap();
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let backend = ArchiveBackend::new(archive_path);
match MemBackend::write_entity(&backend, Path::new("x.md"), b"x") {
Err(BackendError::Sealed) => {}
other => panic!("expected Sealed, got {other:?}"),
}
}
#[test]
fn generation_keyed_memos_survive_rollback_and_track_mutations() {
use indexmap::IndexMap;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let _ = engine.communities();
let memo_gen_before = engine.community_memo.get().expect("memo filled").0;
let _ = engine.communities();
assert_eq!(
engine.community_memo.get().expect("still filled").0,
memo_gen_before,
"repeated reads must serve the memo"
);
let bare = |id: crate::EntityId| crate::engine::UpdateEntityArgs {
anchors: Vec::new(),
anchors_unset: Vec::new(),
id,
expected_hash: crate::ExpectedHash::Missing,
sections: IndexMap::new(),
append_sections: IndexMap::new(),
patch_sections: IndexMap::new(),
sections_unset: Vec::new(),
metadata: IndexMap::new(),
metadata_unset: Vec::new(),
declare_relations: Vec::new(),
dry_run: false,
relations_unset: Vec::new(),
};
let mut real = bare(crate::EntityId::new("specs", "source-one"));
real.append_sections
.insert("identity".to_string(), "appended line".to_string());
let missing = bare(crate::EntityId::new("specs", "does-not-exist"));
let (actor, client) = cli_actor();
let result = engine
.batch_update(
vec![(real, None), (missing, None)],
actor,
Some(&client),
false,
)
.expect("refused batch returns a report-all envelope");
assert!(
!result.applied,
"the missing target refuses the whole batch"
);
assert_eq!(
engine.community_memo.get().map(|m| m.0),
Some(memo_gen_before),
"a refused batch must leave the pre-batch memo standing"
);
assert_eq!(
engine.store().generation(),
memo_gen_before.store_generation,
"rollback restored the store to the memo's generation"
);
let snapshot = engine.store.clone();
let interim_id = crate::EntityId::new("specs", "interim-only");
let mut interim = engine
.store
.get(&crate::EntityId::new("specs", "source-one"))
.expect("demo entity present")
.clone();
interim.id = interim_id.clone();
interim.title = "Interim Only".to_string();
engine.store.upsert(interim_id, interim);
engine.invalidate_communities();
let _ = engine.communities();
let interim_gen = engine.community_memo.get().expect("interim memo").0;
assert_ne!(interim_gen, memo_gen_before);
engine.store = snapshot; engine.invalidate_communities();
engine.invalidate_search_indexes();
if let Some((g, _)) = engine.community_memo.get() {
assert_ne!(
*g, interim_gen,
"a rolled-back interim state must never be served as fresh"
);
}
assert!(
!engine
.communities()
.entity_cluster_map
.keys()
.any(|id| id.contains("interim-only")),
"the partition served after rollback reflects the restored store, not the interim one"
);
let (actor, client) = cli_actor();
engine
.create_entity(
empty_create_args("specs", "Fourth Entity"),
actor,
Some(&client),
None,
)
.unwrap();
assert!(
engine
.communities()
.entity_cluster_map
.keys()
.any(|id| id.contains("fourth-entity")),
"recomputed partition sees the new entity"
);
let fresh = {
let schema = engine
.schemas
.iter()
.min_by(|a, b| a.0.cmp(b.0))
.map(|(_, s)| s.clone())
.expect("demo engine has a schema");
let schema_for_weights = schema.clone();
crate::graph::community::detect_communities(
engine.store(),
schema.manifest.community.resolution,
schema.manifest.community.seed,
move |rel_type| {
schema_for_weights
.manifest
.relationships
.definitions
.iter()
.find(|d| d.name == rel_type)
.map(|d| d.default_weight as f64)
.unwrap_or(1.0)
},
)
};
assert_eq!(
engine.communities().entity_cluster_map,
fresh.entity_cluster_map,
"memo must equal a from-scratch detection over the current store"
);
}
fn build_demo_engine(tmp: &TempDir) -> Engine {
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let mut engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let (actor, client) = cli_actor();
let source = engine
.create_entity(
empty_create_args("specs", "Source One"),
actor,
Some(&client),
None,
)
.unwrap();
let target = engine
.create_entity(
empty_create_args("specs", "Target Two"),
actor,
Some(&client),
None,
)
.unwrap();
engine
.create_entity(
empty_create_args("specs", "Lonely Three"),
actor,
Some(&client),
None,
)
.unwrap();
engine
.relate_entity(
RelateEntityArgs {
source: source.id.clone(),
expected_hash: Some(source.content_hash.clone()),
rel_type: "USES".to_string(),
target: target.id.clone(),
remove: false,
description: None,
dry_run: false,
},
actor,
Some(&client),
None,
)
.unwrap();
engine
}
#[test]
fn status_reports_per_engine_counts() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let stats = engine.status();
assert_eq!(stats.entity_count, 3);
assert_eq!(stats.edge_count, 1);
assert_eq!(stats.mem_count, 1);
assert_eq!(stats.types_in_use, vec!["spec".to_string()]);
assert_eq!(stats.edge_types.get("USES"), Some(&1));
}
#[test]
fn orphans_lists_unconnected_real_entities() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let orphans = engine.orphans();
assert_eq!(orphans.len(), 1);
assert_eq!(orphans[0].as_ref(), "specs--lonely-three");
}
#[test]
fn schema_breakdowns_attribute_to_mem_pin() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let orphans = engine.orphans();
let orphans_by_schema = engine.orphans_by_schema(&orphans);
assert_eq!(
orphans_by_schema.values().sum::<usize>(),
orphans.len(),
"per-schema orphan counts must sum to the raw total"
);
assert_eq!(orphans_by_schema.len(), 1, "one mem ⇒ one schema bucket");
let (schema, count) = orphans_by_schema.iter().next().unwrap();
assert!(!schema.is_empty(), "specs mem is pinned: {schema:?}");
assert_eq!(*count, 1);
let mems: Vec<String> = engine.mounts().iter().map(|m| m.mem.clone()).collect();
let communities_by_schema = engine.communities_by_schema(&mems);
assert_eq!(communities_by_schema.len(), 1);
assert_eq!(
communities_by_schema.values().sum::<usize>(),
engine.communities().count,
);
}
#[test]
fn stubs_lists_unresolved_link_targets() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let mut engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let (actor, client) = cli_actor();
let source = engine
.create_entity(
empty_create_args("specs", "Holder"),
actor,
Some(&client),
None,
)
.unwrap();
engine
.relate_entity(
RelateEntityArgs {
source: source.id.clone(),
expected_hash: Some(source.content_hash.clone()),
rel_type: "USES".to_string(),
target: EntityId::new("specs", "ghost"),
remove: false,
description: None,
dry_run: false,
},
actor,
Some(&client),
None,
)
.unwrap();
let stubs = engine.stubs();
assert!(
stubs.iter().any(|(id, _)| id.as_ref() == "specs--ghost"),
"expected ghost stub: {stubs:?}"
);
}
#[test]
fn most_connected_orders_by_degree() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let top = engine.most_connected(5);
assert_eq!(top.len(), 3);
let zero_degree: Vec<_> = top
.iter()
.filter(|c| c.total == 0)
.map(|c| c.id.as_ref().to_string())
.collect();
assert_eq!(zero_degree, vec!["specs--lonely-three".to_string()]);
}
#[test]
fn health_returns_per_engine_summary() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let health = engine.health();
assert!(
health
.missing_fields
.iter()
.all(|r| r.id.as_ref() != "specs--source-one"),
"post-strict-create fixture must not surface as missing-fields; got {:?}",
health.missing_fields,
);
}
#[test]
fn context_carries_neighbors_and_community() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let source_id = EntityId::new("specs", "source-one");
let ctx = engine.context(&source_id).unwrap();
assert_eq!(ctx.entity_id, source_id);
assert_eq!(ctx.neighbors.len(), 1);
assert_eq!(ctx.neighbors[0].relationship, "USES");
assert!(matches!(ctx.neighbors[0].direction, Direction::Outgoing));
}
#[test]
fn communities_caches_louvain_until_invalidated() {
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let entities_before = engine.communities().entity_cluster_map.len();
assert_eq!(
engine.communities().entity_cluster_map.len(),
entities_before
);
let (actor, client) = cli_actor();
engine
.create_entity(
empty_create_args("specs", "Disturber"),
actor,
Some(&client),
None,
)
.unwrap();
let entities_after = engine.communities().entity_cluster_map.len();
assert_eq!(
entities_after,
entities_before + 1,
"create_entity should have invalidated community cache and added the new entity"
);
}
#[test]
fn list_filters_by_metadata_only() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let scope = SearchScope {
entity_type: Some("spec".to_string()),
..Default::default()
};
let result = engine.list(&scope);
assert_eq!(result.hits.len(), 3);
}
#[test]
fn list_applies_schema_declared_filter_on_non_default_schema_mem() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemBackend::new(mem_dir.clone());
let mount = Mount {
mem: "planning".to_string(),
schema: Some(memstead_schema::SchemaRef::new(
"planning",
semver::Version::new(0, 1, 0),
)),
storage: MountStorage::Folder { path: mem_dir },
capability: MountCapability::Write,
lifecycle: MountLifecycle::Eager,
cross_linkable: true,
migration_target: None,
};
let mut engine =
Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
let (actor, client) = cli_actor();
for (title, status) in &[("Skip Postgres", "accepted"), ("Use SQLite", "proposed")] {
let mut metadata = indexmap::IndexMap::new();
metadata.insert("status".to_string(), status.to_string());
metadata.insert("deciders".to_string(), "alice".to_string());
metadata.insert("decided_on".to_string(), "2026-05-19".to_string());
let args = crate::engine::CreateEntityArgs {
anchors: Vec::new(),
mem: "planning".to_string(),
title: title.to_string(),
entity_type: "decision".to_string(),
sections: indexmap::IndexMap::from_iter([
("decision".to_string(), "We chose this.".to_string()),
("context".to_string(), "Single-user dev.".to_string()),
("consequences".to_string(), "Lose multi-writer.".to_string()),
]),
metadata,
relations: Vec::new(),
dry_run: false,
};
engine
.create_entity(args, actor, Some(&client), None)
.unwrap();
}
let scope = SearchScope {
entity_type: Some("decision".to_string()),
filters: std::collections::HashMap::from([("status".to_string(), "accepted".to_string())]),
..Default::default()
};
let result = engine.list(&scope);
assert_eq!(
result.hits.len(),
1,
"filter on schema-declared field must select only matching entities"
);
assert_eq!(result.hits[0].title, "Skip Postgres");
assert!(
result.warnings.is_empty(),
"no warning should fire when the filter is declared by the mem's pinned schema: {:?}",
result.warnings
);
}
#[test]
fn search_returns_results_against_built_index() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let scope = SearchScope {
query: Some(crate::ops::Query {
any: vec!["source".to_string()],
..Default::default()
}),
..Default::default()
};
let result = engine.search(&scope).expect("native search returns Ok");
assert!(result.total >= 1, "expected ≥1 hit for source: {result:?}");
assert!(
result
.hits
.iter()
.any(|h| h.id.as_ref() == "specs--source-one"),
"expected source-one in hits: {result:?}"
);
}
#[test]
fn an_unreadable_proposal_record_makes_every_entity_third_party() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().join("writable");
std::fs::create_dir_all(dir.join(".memstead")).unwrap();
std::fs::write(
dir.join("own.md"),
"---\ntype: spec\n---\n# Own\n\n## Identity\n\nAuthored here.\n",
)
.unwrap();
std::fs::write(dir.join(".memstead/proposals.json"), b"{ this is not json").unwrap();
let engine = Engine::from_mounts(vec![(
folder_mount("local", dir.clone()),
Box::new(FilesystemBackend::new(dir)) as Box<dyn MemBackend>,
)])
.unwrap();
assert_eq!(
engine.mem_origin_class("local"),
OriginClass::FirstParty,
"the mem itself is still writable"
);
assert_eq!(
engine.entity_origin_class(&crate::EntityId::new("local", "own")),
OriginClass::ThirdParty,
"with the evidence unreadable, the entity is unconfirmable and reads third-party"
);
}
#[test]
fn the_sealed_row_reader_carries_the_class_only_once_identities_are_declared() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().join("writable");
std::fs::create_dir_all(&dir).unwrap();
let mut engine = Engine::from_mounts(vec![(
folder_mount("local", dir.clone()),
Box::new(FilesystemBackend::new(dir)) as Box<dyn MemBackend>,
)])
.unwrap();
let row = |identity: &str| crate::check::CheckRecord {
ts: 1,
observed_at: None,
entity: "local--own".to_string(),
verdict: "ok".to_string(),
method: Some("read the source".to_string()),
entity_hash: "h1".to_string(),
actor: "agent".to_string(),
client: None,
role: "checker".to_string(),
identity: Some(identity.to_string()),
kind: None,
schema_ref: None,
finding: None,
renamed_from: None,
carried_from: None,
checked_write: None,
};
assert!(
engine.sealed_row_reader("local")(&row("some-other-model"))
.origin
.is_none(),
"undeclared seals no class, so an export stays byte-identical"
);
engine.declare_owner_identities(["ops-session"]);
assert_eq!(
engine.sealed_row_reader("local")(&row("some-other-model")).origin,
Some(OriginClass::ThirdParty),
"a row an outside party wrote seals third-party"
);
assert_eq!(
engine.sealed_row_reader("local")(&row("ops-session")).origin,
Some(OriginClass::FirstParty),
"the workspace's own row seals first-party"
);
}
#[test]
fn an_empty_mark_map_fails_the_mem_closed() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().join("writable");
std::fs::create_dir_all(dir.join(".memstead")).unwrap();
std::fs::write(
dir.join("own.md"),
"---\ntype: spec\n---\n# Own\n\n## Identity\n\nAuthored here.\n",
)
.unwrap();
std::fs::write(
dir.join("adopted.md"),
"---\ntype: spec\n---\n# Adopted\n\n## Identity\n\nA contribution.\n",
)
.unwrap();
std::fs::write(
dir.join(".memstead/proposals.json"),
br#"{"version":1,"proposals":[{"id":"f@0","ancestor":"","base":"","target_tip":"","at":"",
"entities":{"adopted":{"disposition":"adopt","landed_sections":{}}}}]}"#,
)
.unwrap();
let engine = Engine::from_mounts(vec![(
folder_mount("local", dir.clone()),
Box::new(FilesystemBackend::new(dir)) as Box<dyn MemBackend>,
)])
.unwrap();
assert_eq!(
engine.entity_origin_class(&crate::EntityId::new("local", "own")),
OriginClass::ThirdParty,
"the marks cannot be read, so no entity of the mem is confirmable"
);
assert!(
engine
.proposal_record_error("local")
.is_some_and(|why| why.contains("landed_sections")),
"and the label says why, naming the defect"
);
}
#[test]
fn a_publisher_supplied_identity_cannot_win_first_party() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let body = "---\ntype: spec\n---\n# Ext\n\n## Identity\n\nFrom an archive.\n";
let archive_path = build_archive(tmp.path(), "ext", &[("ext.md", body.as_bytes())]);
let mut engine = Engine::from_mounts(vec![(
archive_mount("external", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
)])
.unwrap();
engine.declare_owner_identities(["ops-session"]);
assert_eq!(
engine.check_row_origin_class("external", Some("ops-session")),
OriginClass::ThirdParty,
"a guessed owner identity on a third-party mem stays third-party"
);
}
#[test]
fn a_vouched_archive_still_reports_its_adopted_bodies() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let body = "---\ntype: spec\n---\n# Adopted\n\n## Identity\n\nA contribution.\n";
let record = br#"{"version":1,"proposals":[{"id":"f@0","ancestor":"","base":"","target_tip":"","at":"",
"entities":{"adopted":{"disposition":"adopt","landed_sections":{"identity":"PLACEHOLDER"}}}}]}"#;
let marks = crate::preparation::entity_section_prepared_hash("identity", "A contribution.");
let record = String::from_utf8_lossy(record).replace("PLACEHOLDER", &marks);
let archive_path = build_archive(
tmp.path(),
"vouched",
&[
("adopted.md", body.as_bytes()),
(".memstead/proposals.json", record.as_bytes()),
],
);
let mut engine = Engine::from_mounts(vec![(
archive_mount("vouched", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
)])
.unwrap();
engine.declare_mem_origin("vouched", OriginClass::FirstParty);
assert_eq!(
engine.mem_origin_class("vouched"),
OriginClass::FirstParty,
"the deployment vouches for the mem"
);
assert_eq!(
engine.entity_origin_class(&crate::EntityId::new("vouched", "adopted")),
OriginClass::ThirdParty,
"but not for a body its owner adopted from a contributor"
);
}
#[test]
fn a_sealed_first_party_claim_cannot_loosen_a_third_party_mem() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let body = "---\ntype: spec\n---\n# Ext\n\n## Identity\n\nFrom an archive.\n";
let checks = br#"{"version":1,"entities":{"ext":{"verification":{"ts":1,"verdict":"ok",
"method":"trust me","entity_hash":"h1","actor":"agent","role":"checker",
"identity":"the-publisher","origin":"first-party"}}}}"#;
let archive_path = build_archive(
tmp.path(),
"ext",
&[
("ext.md", body.as_bytes()),
(".memstead/checks.json", checks),
],
);
let engine = Engine::from_mounts(vec![(
archive_mount("external", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
)])
.unwrap();
let rec = crate::check::CheckRecord {
ts: 1,
observed_at: None,
entity: "external--ext".to_string(),
verdict: "ok".to_string(),
method: Some("trust me".to_string()),
entity_hash: "h1".to_string(),
actor: "agent".to_string(),
client: None,
role: "checker".to_string(),
identity: Some("the-publisher".to_string()),
kind: None,
schema_ref: None,
finding: None,
renamed_from: None,
carried_from: None,
checked_write: None,
};
assert_eq!(
engine.check_row_prose_origin("external", "external--ext", &rec),
OriginClass::ThirdParty,
"a sealed first-party claim does not loosen the mem's own class"
);
}