use std::cell::OnceCell;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use memstead_schema::Schema;
use crate::backend::MemBackend;
use crate::engine_fallback_type;
use crate::entity::loader::parse_entries;
use crate::entity::source::{SourceEntry, SourceReadError};
use crate::entity::store_builder::push_entities_into_store;
use crate::mem::{MemOrigin, MemRouterSnapshot};
use crate::ops::WarningHint;
use crate::store::Store;
use crate::workspace::{Mount, MountCapability, MountStorage, WorkspaceSettings};
use super::{BootError, Engine, EngineError, MountedBackend};
impl Engine {
pub fn from_mounts(mounts: Vec<(Mount, Box<dyn MemBackend>)>) -> Result<Self, EngineError> {
Self::from_mounts_inner(mounts, Vec::new(), Vec::new())
}
pub fn from_mounts_with_schemas_dir(
mounts: Vec<(Mount, Box<dyn MemBackend>)>,
schemas_dir: Option<&Path>,
) -> Result<Self, EngineError> {
let (extra_schemas, failed) = load_workspace_schemas_with_failures(schemas_dir);
Self::from_mounts_inner(mounts, extra_schemas, failed)
}
pub fn from_mounts_with_schemas_dir_and_extra(
mounts: Vec<(Mount, Box<dyn MemBackend>)>,
schemas_dir: Option<&Path>,
mut extra: Vec<Arc<memstead_schema::Schema>>,
) -> Result<Self, EngineError> {
let (mut local, failed) = load_workspace_schemas_with_failures(schemas_dir);
local.append(&mut extra);
Self::from_mounts_inner(mounts, local, failed)
}
pub(crate) fn from_mounts_inner(
mounts: Vec<(Mount, Box<dyn MemBackend>)>,
extra_schemas: Vec<Arc<memstead_schema::Schema>>,
failed_schema_packages: Vec<FailedSchemaPackage>,
) -> Result<Self, EngineError> {
let mut seen: std::collections::HashSet<String> =
std::collections::HashSet::with_capacity(mounts.len());
let mut mounted: Vec<MountedBackend> = Vec::with_capacity(mounts.len());
for (mount, backend) in mounts {
if !seen.insert(mount.mem.clone()) {
return Err(EngineError::DuplicateMem(mount.mem));
}
let last_known_head = backend.current_head().ok().flatten();
let mem_config = backend.read_mem_config().ok().flatten().and_then(|bytes| {
let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
memstead_schema::config::parse_mem_config(&value).ok()
});
let archive_provenance =
backend
.read_archive_provenance()
.ok()
.flatten()
.and_then(|bytes| {
memstead_schema::ArchiveProvenance::from_archive_bytes(&bytes).ok()
});
let archive_checks = backend
.read_archive_checks()
.ok()
.flatten()
.and_then(|bytes| crate::check::SealedChecks::from_archive_bytes(&bytes).ok());
mounted.push(MountedBackend {
mount,
backend,
last_known_head,
mem_config,
archive_provenance,
archive_checks,
deferred: false,
});
}
let builtin_schemas_only = memstead_schema::builtins::load_builtin_schemas()
.map_err(|e| EngineError::SchemaResolverInit(e.to_string()))?;
let workspace_schemas = extra_schemas.clone();
let mut catalogue: Vec<Arc<memstead_schema::Schema>> =
Vec::with_capacity(extra_schemas.len() + builtin_schemas_only.len());
catalogue.extend(extra_schemas);
catalogue.extend(builtin_schemas_only.clone());
let builtin_schemas = catalogue;
let mut store = Store::new();
let mut load_errors: Vec<(PathBuf, String)> = Vec::new();
let mut schemas: HashMap<String, Arc<Schema>> = HashMap::with_capacity(mounted.len());
let fallback = engine_fallback_type();
let mem_names: Vec<String> = mounted.iter().map(|m| m.mount.mem.clone()).collect();
let known_suffixes: Vec<String> = mem_names
.iter()
.map(|n| crate::entity::store_builder::last_segment_suffix(n).to_string())
.collect();
let mut load_warnings: Vec<WarningHint> = Vec::new();
let mut quarantined: Vec<crate::engine::QuarantinedMem> = Vec::new();
let mut quarantined_idx: std::collections::HashSet<usize> =
std::collections::HashSet::new();
let mut deferred_idx: std::collections::HashSet<usize> = std::collections::HashSet::new();
for (m_idx, m) in mounted.iter().enumerate() {
if matches!(
m.mount.storage,
crate::workspace::MountStorage::Archive { .. }
) && !m.backend.storage_present().unwrap_or(true)
{
let (reason_code, reason_message) = missing_storage_reason(&m.mount);
quarantined.push(crate::engine::QuarantinedMem {
mount: m.mount.clone(),
reason_code,
reason_message,
});
quarantined_idx.insert(m_idx);
continue;
}
let config_pin = m.mem_config.as_ref().and_then(|c| c.schema.as_ref());
let mount_pin = m.mount.schema.as_ref();
if let (Some(cfg), Some(mp)) = (config_pin, mount_pin)
&& cfg != mp
{
load_warnings.push(WarningHint::SchemaPinMismatch {
mem: m.mount.mem.clone(),
config_pin: cfg.as_display(),
mount_pin: mp.as_display(),
});
}
if let Some(stamp) = m
.mem_config
.as_ref()
.and_then(|c| c.mutation_stamp.as_ref())
&& let Some(direction) = crate::build_info::skew_direction(
&stamp.engine_version,
crate::build_info::full_version(),
)
{
load_warnings.push(WarningHint::EngineVersionSkew {
mem: m.mount.mem.clone(),
stamped_engine: stamp.engine_version.clone(),
running_engine: crate::build_info::full_version().to_string(),
stamped_schema: stamp.schema.clone(),
direction,
});
}
let settled_pin = config_pin.or(mount_pin);
let Some(effective_pin) = m.mount.migration_target.as_ref().or(settled_pin) else {
let e = EngineError::MemConfigIncomplete {
mem: m.mount.mem.clone(),
missing_fields: vec!["schema".to_string()],
};
quarantined.push(crate::engine::QuarantinedMem {
mount: m.mount.clone(),
reason_code: e.code().to_string(),
reason_message: e.to_string(),
});
quarantined_idx.insert(m_idx);
continue;
};
let embedded = embedded_archive_schemas(&m.mount);
let resolved = if embedded.is_empty() {
SchemaResolver::new(&builtin_schemas).resolve(effective_pin)
} else {
let mut per_mount: Vec<Arc<Schema>> = Vec::with_capacity(
workspace_schemas.len() + embedded.len() + builtin_schemas_only.len(),
);
per_mount.extend(workspace_schemas.iter().cloned());
per_mount.extend(embedded);
per_mount.extend(builtin_schemas_only.iter().cloned());
SchemaResolver::new(&per_mount).resolve(effective_pin)
};
let schema = match resolved {
Ok(schema) => schema,
Err(sources) => {
let failed = failed_schema_packages.iter().find(|f| {
f.name.as_deref() == Some(effective_pin.name.as_str())
&& f.version
.as_deref()
.is_none_or(|v| v == effective_pin.version.to_string())
});
let (reason_code, reason_message) = match failed {
Some(f) => (
"SCHEMA_LOAD_FAILED".to_string(),
format!(
"schema package at {} failed to load: {}",
f.path.display(),
f.error
),
),
None => {
let e = EngineError::SchemaNotFound {
mem: m.mount.mem.clone(),
pin: effective_pin.as_display(),
sources,
install_hint: None,
};
(e.code().to_string(), e.to_string())
}
};
quarantined.push(crate::engine::QuarantinedMem {
mount: m.mount.clone(),
reason_code,
reason_message,
});
quarantined_idx.insert(m_idx);
continue;
}
};
schemas.insert(m.mount.mem.clone(), schema.clone());
let locally_installed = workspace_schemas.iter().any(|s| {
s.manifest.name == effective_pin.name && s.version == effective_pin.version
});
let is_builtin = builtin_schemas_only.iter().any(|s| {
s.manifest.name == effective_pin.name && s.version == effective_pin.version
});
if !locally_installed
&& is_builtin
&& let Some(newest) =
newest_builtin_version(&effective_pin.name, &builtin_schemas_only)
&& *newest > effective_pin.version
{
load_warnings.push(WarningHint::SchemaGenerationsBehind {
mem: m.mount.mem.clone(),
pinned: effective_pin.as_display(),
newest: newest.to_string(),
});
}
if let Err(memstead_schema::SchemaLoadError::SectionHeadingMismatch { violations }) =
memstead_schema::check_section_heading_roundtrip(&schema)
{
let (name, version) = schema.id();
load_warnings.push(WarningHint::SchemaHeadingRoundtripViolation {
mem: m.mount.mem.clone(),
schema_ref: format!("{name}@{version}"),
violations: violations.iter().map(Into::into).collect(),
});
}
if m.mount.lifecycle == crate::workspace::MountLifecycle::Lazy {
if let Some(w) = unbacked_mount_warning(&m.mount, m.backend.as_ref(), None) {
load_warnings.push(w);
}
deferred_idx.insert(m_idx);
continue;
}
let (entries, read_errors) = match collect_source_entries(m.backend.as_ref()) {
Ok(pair) => pair,
Err(e) => {
let (reason_code, reason_message) =
instantiate_failure_reason(&m.mount, e.code(), e.to_string());
quarantined.push(crate::engine::QuarantinedMem {
mount: m.mount.clone(),
reason_code,
reason_message,
});
quarantined_idx.insert(m_idx);
schemas.remove(&m.mount.mem);
continue;
}
};
let path_backed = matches!(
m.mount.storage,
crate::workspace::MountStorage::Folder { .. }
| crate::workspace::MountStorage::Archive { .. }
);
if path_backed && !m.backend.storage_present().unwrap_or(true) {
let (reason_code, reason_message) = missing_storage_reason(&m.mount);
quarantined.push(crate::engine::QuarantinedMem {
mount: m.mount.clone(),
reason_code,
reason_message,
});
quarantined_idx.insert(m_idx);
schemas.remove(&m.mount.mem);
continue;
}
if let Some(w) =
unbacked_mount_warning(&m.mount, m.backend.as_ref(), Some(entries.len()))
{
load_warnings.push(w);
}
let load_result = parse_entries(entries, read_errors, &m.mount.mem, schema.as_ref());
push_entities_into_store(
&mut store,
load_result.entities,
fallback.as_ref(),
Some(crate::entity::store_builder::LoadCollector {
warnings: &mut load_warnings,
known_suffixes: &known_suffixes,
mem_names: &mem_names,
}),
);
if let crate::workspace::MountStorage::Folder { path } = &m.mount.storage {
let root = path.clone();
load_errors.extend(load_result.errors.into_iter().map(|(p, msg)| {
let abs = if p.is_relative() { root.join(&p) } else { p };
(abs, msg)
}));
} else {
load_errors.extend(load_result.errors);
}
}
for idx in &deferred_idx {
mounted[*idx].deferred = true;
}
if !quarantined_idx.is_empty() {
let mut keep_idx = 0usize;
mounted.retain(|_| {
let keep = !quarantined_idx.contains(&keep_idx);
keep_idx += 1;
keep
});
}
let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> =
mounted
.iter()
.map(|m| (m.mount.mem.clone(), m.mount.capability))
.collect();
crate::entity::store_builder::validate_loaded_relations(
&mut store,
&schemas,
&mount_caps,
&mut load_warnings,
);
crate::entity::store_builder::remap_alias_target_edge_sources(&mut store, &schemas);
load_warnings.retain(|w| match w {
WarningHint::SuspiciousNestedPrefix { resolved_id, .. } => {
store.get(resolved_id).is_none_or(|e| e.stub)
}
_ => true,
});
let mem_router = build_mem_router_from_mounts(&mounted);
let mounts_baseline =
std::cell::RefCell::new(mounted.iter().map(|m| m.mount.clone()).collect::<Vec<_>>());
Ok(Self {
mounts: mounted,
mounts_baseline,
store,
schemas,
workspace_schemas,
builtin_schemas: builtin_schemas_only,
load_errors,
community_memo: OnceCell::new(),
labelling_memo: OnceCell::new(),
#[cfg(not(target_arch = "wasm32"))]
search_indexes_memo: OnceCell::new(),
settings: WorkspaceSettings::default(),
create_rule_set_memo: OnceCell::new(),
declared_origins: HashMap::new(),
owner_identities: std::collections::BTreeSet::new(),
foreign_entities_memo: OnceCell::new(),
workspace_root: None,
load_warnings,
quarantined,
boot_diagnosis: None,
pipeline_configs: crate::pipeline_store::BindingConfigs::default(),
mem_router: Arc::new(mem_router),
backend_factory: crate::workspace_store::instantiate_local_backend,
unmounted_storage_prober: None,
schemas_epoch: 0,
git_branch_ops: None,
event_subscribers: Arc::new(std::sync::Mutex::new(
crate::engine::events::SubscriberRegistry::new(),
)),
pending_mem_changed: Vec::new(),
roster_fingerprint: None,
roster_subscribers: Arc::new(std::sync::Mutex::new((0, Vec::new()))),
recently_unmounted: std::collections::HashSet::new(),
#[cfg(test)]
inject_unmount_failure: None,
mutation_clock: Arc::new(crate::engine::mutation::wall_clock_now),
current_role: crate::vcs::Role::Unspecified,
current_identity: None,
current_actor: crate::vcs::Actor::Agent,
current_client: None,
})
}
pub fn from_workspace_root(workspace_root: &Path) -> Result<Self, BootError> {
use crate::workspace_store::{
FileWorkspaceStore, Layout, WorkspaceStoreAdapter, detect_layout,
instantiate_local_backend,
};
let workspace = match detect_layout(workspace_root) {
Layout::Empty => match crate::workspace_store::standalone_workspace(workspace_root) {
Some(ws) => ws,
None => {
return Err(BootError::NotInitialised(workspace_root.to_path_buf()));
}
},
Layout::New => FileWorkspaceStore::new().load(workspace_root)?,
};
let settings = workspace.settings.clone();
let mut mounts: Vec<(Mount, Box<dyn MemBackend>)> =
Vec::with_capacity(workspace.mounts.len());
let mut instantiate_quarantine: Vec<crate::engine::QuarantinedMem> = Vec::new();
for mount in workspace.mounts {
match instantiate_local_backend(&mount) {
Ok(backend) => mounts.push((mount, backend)),
Err(e) => instantiate_quarantine.push(crate::engine::QuarantinedMem {
reason_code: e.code().to_string(),
reason_message: e.to_string(),
mount,
}),
}
}
let fixed_dir = workspace_root.join(".memstead").join("schemas");
let (local, failed) = load_workspace_schemas_with_failures(Some(fixed_dir.as_path()));
let mut engine = Engine::from_mounts_inner(mounts, local, failed)
.map_err(|e| e.with_schema_install_probe(Some(workspace_root)))?;
engine.quarantined.extend(instantiate_quarantine);
engine.set_settings(settings);
engine.workspace_root = Some(workspace_root.to_path_buf());
engine.capture_roster_fingerprint();
engine.set_pipeline_configs(crate::pipeline_store::load_pipeline_configs(
workspace_root,
)?);
Ok(engine)
}
}
pub(crate) fn build_mem_router_from_mounts(mounts: &[MountedBackend]) -> MemRouterSnapshot {
let mut router = MemRouterSnapshot::new();
for m in mounts {
match m.mount.capability {
MountCapability::Write => {
let dir: Option<PathBuf> = match &m.mount.storage {
MountStorage::Folder { path } => Some(path.clone()),
MountStorage::GitBranch { .. } => None,
MountStorage::Archive { .. } => None,
MountStorage::InMemory => None,
};
router.add_writable(m.mount.mem.clone(), dir, MemOrigin::ExplicitToml);
}
MountCapability::ReadOnly => match &m.mount.storage {
MountStorage::Archive { path } => {
router.add_read_only(m.mount.mem.clone(), path.clone());
}
MountStorage::Folder { path } => {
router.add_read_only(m.mount.mem.clone(), path.clone());
}
MountStorage::GitBranch { gitdir, .. } => {
router.add_read_only(m.mount.mem.clone(), gitdir.clone());
}
MountStorage::InMemory => {}
},
}
}
router
}
pub fn resolve_builtin_schema_pin_pub(
pin: &memstead_schema::SchemaRef,
catalogue: &[Arc<memstead_schema::Schema>],
) -> Option<Arc<memstead_schema::Schema>> {
resolve_builtin_schema_pin(pin, catalogue)
}
fn newest_builtin_version<'a>(
name: &str,
builtins: &'a [Arc<memstead_schema::Schema>],
) -> Option<&'a semver::Version> {
builtins
.iter()
.filter(|s| s.manifest.name == name)
.map(|s| &s.version)
.max()
}
pub struct SchemaResolver<'a> {
catalogue: &'a [Arc<memstead_schema::Schema>],
}
impl<'a> SchemaResolver<'a> {
pub fn new(catalogue: &'a [Arc<memstead_schema::Schema>]) -> Self {
Self { catalogue }
}
pub fn resolve(
&self,
pin: &memstead_schema::SchemaRef,
) -> Result<Arc<memstead_schema::Schema>, Vec<crate::engine::error::SchemaSourceDiagnostic>>
{
resolve_builtin_schema_pin(pin, self.catalogue).ok_or_else(|| {
crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
&pin.name,
&pin.version,
self.catalogue,
)
})
}
}
pub fn load_workspace_schemas(
schemas_dir: Option<&Path>,
) -> Result<Vec<Arc<memstead_schema::Schema>>, EngineError> {
Ok(load_workspace_schemas_with_failures(schemas_dir).0)
}
#[derive(Debug, Clone)]
pub struct FailedSchemaPackage {
pub path: PathBuf,
pub name: Option<String>,
pub version: Option<String>,
pub error: String,
}
pub(crate) fn embedded_archive_schemas(mount: &Mount) -> Vec<Arc<Schema>> {
let crate::workspace::MountStorage::Archive { path } = &mount.storage else {
return Vec::new();
};
if path.as_os_str().is_empty() || !path.is_file() {
return Vec::new();
}
use crate::schema_source::SchemaSource as _;
crate::schema_source::ArchiveSchemaSource::from_path(path)
.ok()
.and_then(|source| source.read_schemas().ok())
.unwrap_or_default()
}
pub fn load_workspace_schemas_with_failures(
schemas_dir: Option<&Path>,
) -> (Vec<Arc<memstead_schema::Schema>>, Vec<FailedSchemaPackage>) {
let Some(dir) = schemas_dir else {
return (Vec::new(), Vec::new());
};
if !dir.is_dir() {
return (Vec::new(), Vec::new());
}
let entries = match std::fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return (Vec::new(), Vec::new()),
};
let mut schemas: Vec<Arc<memstead_schema::Schema>> = Vec::new();
let mut failures: Vec<FailedSchemaPackage> = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
if !path.join("schema.yaml").is_file() {
continue;
}
match memstead_schema::load_schema_from_dir(&path) {
Ok(schema) => schemas.push(Arc::new(schema)),
Err(e) => {
let header = std::fs::read_to_string(path.join("schema.yaml")).unwrap_or_default();
let peek = |k: &str| {
header
.lines()
.find_map(|l| l.strip_prefix(&format!("{k}:")))
.map(|v| v.trim().trim_matches('"').to_string())
.filter(|v| !v.is_empty())
};
failures.push(FailedSchemaPackage {
path: path.clone(),
name: peek("name"),
version: peek("version"),
error: e.to_string(),
});
}
}
}
(schemas, failures)
}
pub(super) fn resolve_builtin_schema_pin(
pin: &memstead_schema::SchemaRef,
catalogue: &[Arc<memstead_schema::Schema>],
) -> Option<Arc<memstead_schema::Schema>> {
catalogue
.iter()
.find(|s| {
let id = s.id();
id.0 == pin.name && id.1 == pin.version
})
.cloned()
}
pub fn missing_storage_reason(mount: &crate::workspace::Mount) -> (String, String) {
use crate::workspace::MountStorage;
if let MountStorage::Archive { path } = &mount.storage
&& let Some(file) = crate::workspace_store::installed_archive_file(path)
{
let mem = &mount.mem;
let key = file
.strip_prefix(&format!("{mem}-"))
.and_then(|r| r.strip_suffix(".mem"))
.unwrap_or("?");
let dir = path
.parent()
.map(|p| p.display().to_string())
.unwrap_or_default();
let others: Vec<String> = path
.parent()
.and_then(|p| std::fs::read_dir(p).ok())
.map(|rd| {
rd.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| {
n.starts_with(&format!("{mem}-")) && n.ends_with(".mem") && *n != file
})
.collect()
})
.unwrap_or_default();
let other_note = if others.is_empty() {
String::new()
} else {
format!(
" The cache holds {} with different content; it does not match the recorded \
identity and is not mounted in its place.",
others
.iter()
.map(|o| format!("`{o}`"))
.collect::<Vec<_>>()
.join(", ")
)
};
return (
"ARCHIVE_NOT_INSTALLED".to_string(),
format!(
"mem `{mem}` is an installed archive (`{file}`, content key `{key}`) that this \
machine's archive cache ({dir}) does not hold.{other_note} Install it here, \
from the archive file (`memstead install <path to {file}>`) or from the \
registry it was published to (`memstead install <scope>/{mem}`), then run \
`memstead reload --full`."
),
);
}
let location = match &mount.storage {
MountStorage::GitBranch { branch, .. } => branch.clone(),
MountStorage::Folder { path } | MountStorage::Archive { path } => {
path.display().to_string()
}
MountStorage::InMemory => String::new(),
};
(
"MOUNT_UNBACKED".to_string(),
format!(
"the mount's storage is gone ({location}); it is configured but cannot \
serve, so it is held out of the roster rather than answering reads \
with an empty graph"
),
)
}
pub fn instantiate_failure_reason(
mount: &crate::workspace::Mount,
code: &str,
message: String,
) -> (String, String) {
if let crate::workspace::MountStorage::Archive { path } = &mount.storage
&& !path.exists()
{
return missing_storage_reason(mount);
}
(code.to_string(), message)
}
pub(super) fn unbacked_mount_warning(
mount: &crate::workspace::Mount,
backend: &dyn MemBackend,
entity_count: Option<usize>,
) -> Option<WarningHint> {
use crate::ops::MountUnbackedReason;
use crate::workspace::MountStorage;
let (location, missing_reason) = match &mount.storage {
MountStorage::GitBranch { branch, .. } => (branch.clone(), MountUnbackedReason::MissingRef),
MountStorage::Folder { path } => {
(path.display().to_string(), MountUnbackedReason::MissingPath)
}
MountStorage::Archive { path } => {
(path.display().to_string(), MountUnbackedReason::MissingPath)
}
MountStorage::InMemory => return None,
};
if !backend.storage_present().unwrap_or(true) {
return Some(WarningHint::MountUnbacked {
mem: mount.mem.clone(),
reason: missing_reason,
location,
});
}
if entity_count == Some(0) {
return Some(WarningHint::MountUnbacked {
mem: mount.mem.clone(),
reason: MountUnbackedReason::Empty,
location,
});
}
None
}
pub(super) fn collect_source_entries(
backend: &dyn MemBackend,
) -> Result<(Vec<SourceEntry>, Vec<SourceReadError>), EngineError> {
let reads = backend.read_all_entities()?;
let mut entries: Vec<SourceEntry> = Vec::with_capacity(reads.len());
let mut errors: Vec<SourceReadError> = Vec::new();
for (path, read) in reads {
match read {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(content) => entries.push(SourceEntry {
relative_path: path.to_string_lossy().into_owned(),
source_path: path.clone(),
content,
}),
Err(e) => errors.push(SourceReadError {
source_path: path,
error: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
}),
},
Err(e) => errors.push(SourceReadError {
source_path: path,
error: std::io::Error::other(e.to_string()),
}),
}
}
Ok((entries, errors))
}
#[cfg(test)]
mod tests;