use std::collections::HashMap;
use indexmap::IndexMap;
use crate::entity::{Entity, EntityId};
use crate::store::Store;
use super::EngineError;
pub(super) use batch::{batch_empty, batch_receipt, batch_refusal};
mod batch;
pub mod create;
pub mod delete;
mod landing;
pub mod mem_sweep;
pub mod parse_recovery;
pub mod proposal_merge;
pub mod relate;
pub mod rename;
pub mod retype;
pub mod update;
pub(super) fn lookup_title_and_type(
store: &Store,
id: &EntityId,
) -> (Option<String>, Option<String>) {
match store.get(id) {
Some(e) => (Some(e.title.clone()), Some(e.entity_type.clone())),
None => (None, None),
}
}
pub const PATCH_OLD_NOT_FOUND_CONTENT_CAP: usize = 500;
pub const RELATIONSHIP_CYCLE_PATH_CAP: usize = 20;
pub(crate) fn render_for_write(
entity: &Entity,
type_def: &memstead_schema::TypeDefinition,
) -> Result<String, EngineError> {
for (key, value) in &entity.sections {
if let Some(fence) = crate::markdown::closing_fence_if_unterminated(value.trim()) {
return Err(EngineError::UnterminatedFenceInStoredBody {
id: entity.id.to_string(),
section: key.clone(),
fence,
swallowed: crate::ops::integrity::swallowed_declared_sections(value, type_def),
});
}
}
Ok(crate::entity::generator::generate_markdown(
entity, type_def,
))
}
pub(crate) struct EdgeWrite<'a> {
pub rel_type: &'a str,
pub target_mem: &'a str,
pub remove: bool,
}
impl super::Engine {
pub(in crate::engine) fn stub_ids(&self) -> std::collections::HashSet<EntityId> {
self.store
.all_entities()
.filter(|e| e.stub)
.map(|e| e.id.clone())
.collect()
}
pub(in crate::engine) fn drop_stubs_of_an_unlanded_write<T>(
&mut self,
before: &std::collections::HashSet<EntityId>,
landed: &Result<T, EngineError>,
rehearsal: bool,
) {
if !rehearsal
&& !matches!(landed, Err(e) if !matches!(e, EngineError::CommitNotApplied { .. }))
{
return;
}
let made: Vec<EntityId> = self
.store
.all_entities()
.filter(|e| e.stub && !before.contains(&e.id))
.map(|e| e.id.clone())
.collect();
for id in made {
self.store.remove(&id);
}
}
}
impl super::Engine {
pub(crate) fn write_needs_full_load<'a, 't>(
&self,
mem: &str,
edges: impl IntoIterator<Item = EdgeWrite<'a>>,
texts: impl IntoIterator<Item = &'t str>,
) -> bool {
let has_signals = |m: &str| {
self.schemas
.get(m)
.is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
};
let cycle_guarded = |rel: &str| self.rel_type_is_acyclic(mem, rel);
if has_signals(mem)
|| edges
.into_iter()
.any(|e| (!e.remove && cycle_guarded(e.rel_type)) || has_signals(e.target_mem))
{
return true;
}
let Some(pointer) = self
.schemas
.get(mem)
.and_then(|s| s.manifest.alias_target_rel_type.clone())
else {
return false;
};
texts
.into_iter()
.filter(|t| t.contains("[["))
.flat_map(|t| crate::entity::parser::extract_inline_links_lenient(t, mem))
.any(|target| cycle_guarded(&pointer) || has_signals(target.mem()))
}
}
pub(crate) fn unknown_type_error(schema: &memstead_schema::Schema, attempted: &str) -> EngineError {
let mut declared: Vec<String> = schema.types.keys().cloned().collect();
declared.sort();
let (sname, sver) = schema.id();
EngineError::UnknownType {
name: attempted.to_string(),
schema_ref: format!("{sname}@{sver}"),
declared,
suggestion: schema.suggest_type(attempted),
}
}
pub(crate) fn medium_type_wire(t: crate::pipeline::MediumType) -> &'static str {
use crate::pipeline::MediumType::*;
match t {
Codebase => "codebase",
Filesystem => "filesystem",
Graph => "graph",
Git => "git",
Web => "web",
}
}
impl super::Engine {
pub(crate) fn resolve_anchor_medium(&self, mem: &str) -> Option<(String, &'static str)> {
let mut sources = self
.pipeline_configs()
.bindings
.iter()
.filter(|r| r.mem == mem)
.flat_map(|r| r.config.sources.iter());
let first = sources.next()?;
if sources.next().is_some() {
return None;
}
let caps = crate::binding::medium_capabilities(first.medium_type);
Some((
medium_type_wire(first.medium_type).to_string(),
caps.anchor_namespace,
))
}
pub fn validate_anchor_inputs(
&self,
mem: &str,
inputs: &[crate::anchor::AnchorInput],
) -> Result<Vec<crate::anchor::Anchor>, EngineError> {
if inputs.is_empty() {
return Ok(Vec::new());
}
let medium = self.resolve_anchor_medium(mem);
let medium_ref = medium.as_ref().map(|(t, ns)| (t.as_str(), *ns));
let mut anchors: Vec<crate::anchor::Anchor> = inputs
.iter()
.map(|i| i.validate(medium_ref).map_err(EngineError::from))
.collect::<Result<_, _>>()?;
{
let mut seen: std::collections::HashSet<(&str, &str, &str, Option<String>)> =
std::collections::HashSet::new();
for a in &anchors {
let key = (
a.artifact.as_str(),
a.grain.as_wire(),
a.class.as_wire(),
a.span
.as_deref()
.map(crate::preparation::canonical_span_form),
);
if !seen.insert(key) {
return Err(EngineError::from(
crate::anchor::AnchorValidationError::DuplicateAnchorTriple {
artifact: a.artifact.clone(),
grain: a.grain.as_wire(),
class: a.class.as_wire(),
span: a.span.clone(),
},
));
}
}
}
if inputs.iter().any(|i| i.content.is_some()) {
let joins = self.anchor_source_roots(mem);
for (input, anchor) in inputs.iter().zip(anchors.iter_mut()) {
let (Some(content), Some(source)) = (&input.content, &anchor.source) else {
continue;
};
let Some(join) = joins.get(source) else {
continue;
};
if join.preparation.is_none() {
continue;
}
match crate::preparation::path_prepared_hash(
join.preparation.as_deref(),
&anchor.artifact,
anchor.grain,
content.as_bytes(),
) {
crate::preparation::PathPrepared::Hash(h) => anchor.hash = Some(h),
crate::preparation::PathPrepared::NoHash => {}
crate::preparation::PathPrepared::UnitAbsent => {
return Err(EngineError::from(
crate::anchor::AnchorValidationError::UnitAbsentFromContent {
artifact: anchor.artifact.clone(),
},
));
}
}
}
}
if anchors
.iter()
.any(|a| a.binding.is_some() && a.source.is_some())
&& let Some(root) = self.workspace_root()
&& let Ok(configs) = crate::pipeline_store::load_pipeline_configs(root)
{
for a in &anchors {
let (Some(binding_hash), Some(source)) = (&a.binding, &a.source) else {
continue;
};
let Some(record) = configs
.bindings
.iter()
.find(|r| crate::binding::hash_binding(&r.config) == *binding_hash)
else {
continue; };
let declared: Vec<String> = record
.config
.sources
.iter()
.map(|s| s.name.clone())
.collect();
if !declared.iter().any(|n| n == source) {
return Err(EngineError::from(
crate::anchor::AnchorValidationError::SourceNotDeclared {
got: source.clone(),
declared,
},
));
}
}
}
if let Some(root) = self.workspace_root()
&& crate::pipeline_store::load_pipeline_configs(root).is_ok()
{
let source_roots = self.anchor_source_roots(mem);
for a in &anchors {
match a.grain {
crate::anchor::AnchorGrain::Span
| crate::anchor::AnchorGrain::File
| crate::anchor::AnchorGrain::Tree => {}
crate::anchor::AnchorGrain::Url | crate::anchor::AnchorGrain::Entity => {
continue;
}
}
let base = crate::engine::query::anchor_base_path(&a.artifact);
let candidates: Vec<String> = match a
.source
.as_ref()
.and_then(|source| source_roots.get(source))
{
Some(join) => crate::engine::query::artifact_candidates(&join.pointer, base),
None => vec![base.to_string()],
};
if !candidates.iter().any(|c| root.join(c).exists()) {
return Err(EngineError::from(
crate::anchor::AnchorValidationError::ArtifactUnresolvable {
artifact: a.artifact.clone(),
candidates,
},
));
}
}
}
if anchors
.iter()
.any(|a| a.grain == crate::anchor::AnchorGrain::Entity)
{
let joins = self.anchor_source_roots(mem);
for a in anchors.iter_mut() {
if a.grain != crate::anchor::AnchorGrain::Entity
|| !a.class.is_hash_bearing()
|| a.hash.is_some()
{
continue;
}
let preparation = a
.source
.as_deref()
.and_then(|name| joins.get(name))
.and_then(|j| j.preparation.as_deref());
if let Some(hash) = self.entity_anchor_target_hash(&a.artifact, preparation) {
a.hash = Some(hash);
a.hash_source = Some(crate::anchor::AnchorHashSource::Pinned);
}
}
}
Ok(anchors)
}
pub(crate) fn validate_anchor_unsets(
inputs: &[crate::anchor::AnchorUnsetInput],
) -> Result<Vec<crate::anchor::AnchorUnset>, EngineError> {
inputs
.iter()
.map(|i| i.validate().map_err(EngineError::from))
.collect()
}
pub fn record_anchor_observed_hashes(
&mut self,
mem_name: &str,
observed: &[crate::anchor::ObservedArtifactHash],
note: Option<&str>,
) -> Result<usize, EngineError> {
if observed.is_empty() {
return Ok(0);
}
let (_, _roster_notice) = self.writable_mount_on_current_roster(mem_name)?;
let (_write_lock, _roster) = self.lock_for_write(true, &[mem_name])?;
let _warnings = self.reload_if_stale_content_only(Some(mem_name));
let mount_idx = self.writable_mount_index(mem_name)?;
let backend = self.mounts[mount_idx].backend.as_ref();
let mut sidecar = read_sidecar(backend)?;
let mut written = 0usize;
for obs in observed {
let Some(anchors) = sidecar.entities.get_mut(&obs.entity) else {
continue;
};
for a in anchors {
if a.class.is_hash_bearing() && a.hash.is_none() && a.artifact == obs.artifact {
a.hash = Some(obs.hash.clone());
a.hash_source = Some(crate::anchor::AnchorHashSource::Backfill);
written += 1;
}
}
}
if written == 0 {
return Ok(0);
}
backend.write_anchors_sidecar(&sidecar.to_bytes())?;
let ctx = self.session_commit_context(
Some("record_anchor_observed_hashes"),
note.map(String::from),
);
let write_id = self
.commit_staged(
mount_idx,
&format!("memstead: anchor-hash backfill ({written} anchor(s))"),
&ctx,
&[],
)?
.write_id;
self.record_self_write(mount_idx, &write_id);
let _intervention_has_no_channel_here = self.stamp_mutation_versions(mount_idx);
Ok(written)
}
pub fn record_anchor_observations(
&mut self,
mem_name: &str,
observations: &[crate::engine::query::RecordedObservation],
note: Option<&str>,
) -> Result<usize, EngineError> {
if observations.is_empty() {
return Ok(0);
}
let (_, _roster_notice) = self.writable_mount_on_current_roster(mem_name)?;
let (_write_lock, _roster) = self.lock_for_write(true, &[mem_name])?;
let _warnings = self.reload_if_stale_content_only(Some(mem_name));
let mount_idx = self.writable_mount_index(mem_name)?;
let backend = self.mounts[mount_idx].backend.as_ref();
let mut sidecar = read_sidecar(backend)?;
let mut written = 0usize;
for obs in observations {
let Some(anchors) = sidecar.entities.get_mut(&obs.entity) else {
continue;
};
for a in anchors {
if a.grain != crate::anchor::AnchorGrain::Url
|| a.artifact != obs.artifact
|| !crate::anchor::same_span(a.span.as_deref(), obs.span.as_deref())
{
continue;
}
let mut changed = false;
if a.last_observed.as_ref() != Some(&obs.observation) {
a.last_observed = Some(obs.observation.clone());
changed = true;
}
if a.span.is_some()
&& a.span_unvalidated
&& matches!(
obs.observation.state,
crate::anchor::AnchorState::Resolves
| crate::anchor::AnchorState::SpanAbsent
)
{
a.span_unvalidated = false;
changed = true;
}
if a.class.is_hash_bearing()
&& a.hash.is_none()
&& let Some(hash) = &obs.observation.hash
{
a.hash = Some(hash.clone());
a.hash_source = Some(crate::anchor::AnchorHashSource::Backfill);
changed = true;
}
if changed {
written += 1;
}
}
}
if written == 0 {
return Ok(0);
}
backend.write_anchors_sidecar(&sidecar.to_bytes())?;
let ctx =
self.session_commit_context(Some("record_anchor_observations"), note.map(String::from));
let write_id = self
.commit_staged(
mount_idx,
&format!("memstead: anchor observations recorded ({written} row(s))"),
&ctx,
&[],
)?
.write_id;
self.record_self_write(mount_idx, &write_id);
let _intervention_has_no_channel_here = self.stamp_mutation_versions(mount_idx);
Ok(written)
}
pub(crate) fn stamp_mutation_versions(
&mut self,
mount_idx: usize,
) -> Vec<crate::ops::WarningHint> {
let Some(state) = self.mounts.get(mount_idx) else {
return Vec::new();
};
let mem = state.mount.mem.clone();
let Some(schema) = self.schemas.get(&mem) else {
return Vec::new();
};
let (name, version) = schema.id();
let stamp = memstead_schema::MutationStamp {
engine_version: crate::build_info::full_version().to_string(),
schema: format!("{name}@{version}"),
};
let Some(config) = self
.mounts
.get(mount_idx)
.and_then(|s| s.mem_config.as_ref())
else {
return Vec::new();
};
let mut warnings = Vec::new();
if let Some(prior) = config.mutation_stamp.as_ref()
&& let Some(direction) = crate::build_info::skew_direction(
&prior.engine_version,
crate::build_info::full_version(),
)
{
warnings.push(crate::ops::WarningHint::EngineVersionSkew {
mem: mem.clone(),
stamped_engine: prior.engine_version.clone(),
running_engine: crate::build_info::full_version().to_string(),
stamped_schema: prior.schema.clone(),
direction,
});
}
if config.mutation_stamp.as_ref() == Some(&stamp) {
return warnings;
}
match self.write_mem_config_merged(
mount_idx,
&mem,
"stamp_mutation_versions",
Some("engine version stamp"),
&move |c: &mut memstead_schema::config::MemConfig| {
c.mutation_stamp = Some(stamp.clone());
},
) {
Ok((_, intervened)) if !intervened.is_empty() => {
warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
mem,
fields: intervened,
});
warnings
}
_ => warnings,
}
}
}
pub(crate) fn stage_derivation_sidecar(
backend: &dyn crate::backend::MemBackend,
mutate: impl FnOnce(&mut crate::derivation::DerivationSidecar),
) -> Result<(), EngineError> {
let path = std::path::Path::new(crate::derivation::DERIVATION_SIDECAR_PATH);
let mut sidecar = match backend.read_entity(path)? {
Some(bytes) => crate::derivation::DerivationSidecar::from_bytes(&bytes).map_err(|e| {
EngineError::Backend(crate::backend::BackendError::Other(format!(
"derivations sidecar parse: {e}"
)))
})?,
None => crate::derivation::DerivationSidecar::default(),
};
mutate(&mut sidecar);
backend.write_entity(path, &sidecar.to_bytes())?;
Ok(())
}
pub(crate) fn rel_type_declares_derivation(
schema: &memstead_schema::Schema,
rel_type: &str,
) -> bool {
schema
.manifest
.relationships
.definitions
.iter()
.any(|d| d.name == rel_type && d.derivation)
}
pub(crate) fn stage_anchors_sidecar(
backend: &dyn crate::backend::MemBackend,
entity_id: &EntityId,
unsets: &[crate::anchor::AnchorUnset],
anchors: Vec<crate::anchor::Anchor>,
rebaseline: bool,
) -> Result<bool, EngineError> {
let mut sidecar = read_sidecar(backend)?;
if !sidecar.merge(entity_id.as_ref(), unsets, anchors, rebaseline) {
return Ok(false);
}
backend.write_anchors_sidecar(&sidecar.to_bytes())?;
Ok(true)
}
pub(crate) fn anchors_would_change(
backend: &dyn crate::backend::MemBackend,
entity_id: &EntityId,
unsets: &[crate::anchor::AnchorUnset],
anchors: &[crate::anchor::Anchor],
rebaseline: bool,
) -> Result<bool, EngineError> {
let mut sidecar = read_sidecar(backend)?;
Ok(sidecar.merge(entity_id.as_ref(), unsets, anchors.to_vec(), rebaseline))
}
fn read_sidecar(
backend: &dyn crate::backend::MemBackend,
) -> Result<crate::anchor::AnchorSidecar, EngineError> {
match backend.read_anchors_sidecar()? {
Some(bytes) => crate::anchor::AnchorSidecar::from_bytes(&bytes).map_err(|e| {
EngineError::Backend(crate::backend::BackendError::Other(format!(
"anchors sidecar parse: {e}"
)))
}),
None => Ok(crate::anchor::AnchorSidecar::default()),
}
}
pub(crate) fn stage_anchors_removal(
backend: &dyn crate::backend::MemBackend,
entity_id: &EntityId,
) -> Result<bool, EngineError> {
let mut sidecar = read_sidecar(backend)?;
if sidecar.get(entity_id.as_ref()).is_empty() {
return Ok(false);
}
sidecar.remove(entity_id.as_ref());
backend.write_anchors_sidecar(&sidecar.to_bytes())?;
Ok(true)
}
pub(crate) fn stage_anchors_replace(
backend: &dyn crate::backend::MemBackend,
entity_id: &EntityId,
rows: Vec<crate::anchor::Anchor>,
) -> Result<bool, EngineError> {
let mut sidecar = read_sidecar(backend)?;
if sidecar.get(entity_id.as_ref()) == rows.as_slice() {
return Ok(false);
}
sidecar.set(entity_id.as_ref(), rows);
backend.write_anchors_sidecar(&sidecar.to_bytes())?;
Ok(true)
}
pub(crate) fn stage_anchors_rename(
backend: &dyn crate::backend::MemBackend,
from: &EntityId,
to: &EntityId,
) -> Result<bool, EngineError> {
let mut sidecar = read_sidecar(backend)?;
if sidecar.get(from.as_ref()).is_empty() {
return Ok(false);
}
sidecar.rename(from.as_ref(), to.as_ref());
backend.write_anchors_sidecar(&sidecar.to_bytes())?;
Ok(true)
}
pub(crate) fn stage_proposal_marks_rename(
backend: &dyn crate::backend::MemBackend,
from: &EntityId,
to: &EntityId,
) -> Result<bool, EngineError> {
let Some(bytes) = backend
.read_proposal_record()
.map_err(EngineError::Backend)?
else {
return Ok(false);
};
let Ok(record) = crate::ops::proposal::ProposalRecord::from_bytes(&bytes) else {
return Ok(false);
};
let (record, moved) = move_marks_on_rename(record, from.path(), to.path());
if !moved {
return Ok(false);
}
backend
.write_entity(
std::path::Path::new(crate::ops::proposal::PROPOSAL_RECORD_PATH),
&record.to_bytes(),
)
.map_err(EngineError::Backend)?;
Ok(true)
}
pub(crate) fn rekey_marks_for_retype(
before: &std::collections::BTreeMap<String, String>,
section_map: &indexmap::IndexMap<String, String>,
sections: &indexmap::IndexMap<String, String>,
) -> std::collections::BTreeMap<String, String> {
let mut after = std::collections::BTreeMap::new();
for (key, hash) in before {
let target = section_map.get(key).unwrap_or(key);
let carried = sections.get(target).filter(|content| {
&crate::preparation::entity_section_prepared_hash(key, content) == hash
});
if let Some(content) = carried {
after.insert(
target.clone(),
crate::preparation::entity_section_prepared_hash(target, content),
);
}
}
after
}
pub(crate) fn stage_proposal_marks_rehash(
backend: &dyn crate::backend::MemBackend,
id: &EntityId,
before: &indexmap::IndexMap<String, String>,
after: &indexmap::IndexMap<String, String>,
) -> Result<bool, EngineError> {
let Some(bytes) = backend
.read_proposal_record()
.map_err(EngineError::Backend)?
else {
return Ok(false);
};
let Ok(mut record) = crate::ops::proposal::ProposalRecord::from_bytes(&bytes) else {
return Ok(false);
};
if record.structural_defect().is_some() {
return Ok(false);
}
let mut changed = false;
for proposal in &mut record.proposals {
let Some(entry) = proposal.entities.get_mut(id.path()) else {
continue;
};
let Some(marks) = entry.landed_sections.as_mut() else {
continue;
};
for (key, hash) in marks.iter_mut() {
let Some(was) = before.get(key) else { continue };
let Some(now) = after.get(key) else { continue };
if was == now {
continue;
}
if &crate::preparation::entity_section_prepared_hash(key, was) != hash {
continue;
}
*hash = crate::preparation::entity_section_prepared_hash(key, now);
changed = true;
}
}
if !changed {
return Ok(false);
}
backend
.write_entity(
std::path::Path::new(crate::ops::proposal::PROPOSAL_RECORD_PATH),
&record.to_bytes(),
)
.map_err(EngineError::Backend)?;
Ok(true)
}
pub(crate) fn move_marks_on_rename(
mut record: crate::ops::proposal::ProposalRecord,
from: &str,
to: &str,
) -> (crate::ops::proposal::ProposalRecord, bool) {
if record.structural_defect().is_some() {
return (record, false);
}
let before = (record.effective_marks(from), record.effective_marks(to));
let Some(marks) = before.0.clone() else {
return (record, false);
};
let source_row = record.effective_marks_at(from);
let target_row = record.effective_marks_at(to).or_else(|| {
record
.proposals
.iter()
.rposition(|p| p.entities.contains_key(to))
});
for proposal in &mut record.proposals {
if let Some(entry) = proposal.entities.get_mut(from) {
entry.landed_sections = None;
}
}
match target_row {
Some(idx) => {
if let Some(entry) = record.proposals[idx].entities.get_mut(to) {
entry.landed_sections = Some(marks);
}
}
None => {
if let Some(idx) = source_row
&& let Some(mut entry) = record.proposals[idx].entities.remove(from)
{
entry.landed_sections = Some(marks);
record.proposals[idx].entities.insert(to.to_string(), entry);
}
}
}
let after = (record.effective_marks(from), record.effective_marks(to));
(record, after != before)
}
pub(crate) fn stage_proposal_marks_retype(
backend: &dyn crate::backend::MemBackend,
id: &EntityId,
section_map: &indexmap::IndexMap<String, String>,
sections: &indexmap::IndexMap<String, String>,
) -> Result<bool, EngineError> {
if section_map.is_empty() {
return Ok(false);
}
let Some(bytes) = backend
.read_proposal_record()
.map_err(EngineError::Backend)?
else {
return Ok(false);
};
let Ok(mut record) = crate::ops::proposal::ProposalRecord::from_bytes(&bytes) else {
return Ok(false);
};
if record.structural_defect().is_some() {
return Ok(false);
}
let mut rekeyed = false;
for proposal in &mut record.proposals {
let Some(entry) = proposal.entities.get_mut(id.path()) else {
continue;
};
let Some(before) = entry.landed_sections.clone() else {
continue;
};
let after = rekey_marks_for_retype(&before, section_map, sections);
if after == before {
continue;
}
if after.is_empty() {
entry.landed_sections = None;
} else {
entry.landed_sections = Some(after);
}
rekeyed = true;
}
if !rekeyed {
return Ok(false);
}
backend
.write_entity(
std::path::Path::new(crate::ops::proposal::PROPOSAL_RECORD_PATH),
&record.to_bytes(),
)
.map_err(EngineError::Backend)?;
Ok(true)
}
pub fn iso_now() -> String {
iso_from_system_time(wall_clock_now())
}
pub fn wall_clock_now() -> std::time::SystemTime {
#[cfg(target_arch = "wasm32")]
{
std::time::UNIX_EPOCH + std::time::Duration::from_millis(js_sys::Date::now() as u64)
}
#[cfg(not(target_arch = "wasm32"))]
{
std::time::SystemTime::now()
}
}
pub(super) fn iso_from_system_time(t: std::time::SystemTime) -> String {
let now = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
let secs = now.as_secs();
let days = secs / 86400;
let secs_of_day = secs % 86400;
let hh = secs_of_day / 3600;
let mm = (secs_of_day % 3600) / 60;
let ss = secs_of_day % 60;
let z = days + 719468;
let era = z / 146097;
let doe = z - era * 146097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
}
pub(super) fn gc_orphan_stubs(store: &mut Store) -> Vec<EntityId> {
let stub_ids: Vec<EntityId> = store
.all_entities()
.filter(|e| e.stub)
.map(|e| e.id.clone())
.collect();
gc_orphan_stubs_among(store, &stub_ids)
}
pub(super) fn gc_orphan_stubs_among<'a>(
store: &mut Store,
candidates: impl IntoIterator<Item = &'a EntityId>,
) -> Vec<EntityId> {
let mut removed: Vec<EntityId> = Vec::new();
let mut seen: std::collections::HashSet<&EntityId> = std::collections::HashSet::new();
for id in candidates {
if !seen.insert(id) {
continue;
}
if store.get(id).is_some_and(|e| e.stub) && store.incoming(id).is_empty() {
store.remove(id);
removed.push(id.clone());
}
}
removed
}
pub(super) fn validate_relation_target_grammar(target: &EntityId) -> Result<(), EngineError> {
if let Err(reason) = crate::entity::id::validate_mem_name_grammar(target.mem()) {
return Err(EngineError::InvalidEntityId {
id: target.to_string(),
reason,
});
}
if let Err(reason) = crate::entity::id::validate_id_path_grammar(target.path()) {
return Err(EngineError::InvalidEntityId {
id: target.to_string(),
reason,
});
}
Ok(())
}
pub(super) fn auto_stamp_timestamps(
entity: &mut Entity,
type_def: &memstead_schema::TypeDefinition,
today: &str,
) {
for field_def in &type_def.metadata_fields {
if field_def.auto_timestamp {
entity.metadata.insert(
field_def.key.clone(),
crate::entity::MetadataValue::String(today.to_string()),
);
}
}
}
pub(super) fn make_stub(id: &EntityId, kind: crate::entity::StubKind) -> Entity {
Entity {
id: id.clone(),
title: id.name().to_string(),
entity_type: String::new(),
mem: id.mem().to_string(),
file_path: String::new(),
metadata: IndexMap::new(),
sections: IndexMap::new(),
relationships: Vec::new(),
content_hash: String::new(),
stub: true,
stub_kind: Some(kind),
heading_spans: HashMap::new(),
raw_section_headings: Vec::new(),
}
}
pub(super) fn validate_cross_mem_add_policy(
engine: &super::Engine,
source_mem: &str,
target: &EntityId,
) -> Result<(), EngineError> {
let target_mem = target.mem();
if source_mem == target_mem {
return Ok(());
}
if !engine.cross_mem_link_allowed(source_mem, target_mem) {
return Err(EngineError::CrossMemLinkNotAllowed {
from_mem: source_mem.to_string(),
to_mem: target_mem.to_string(),
});
}
if let Some(failure) = engine
.mounts
.iter()
.find(|m| m.mount.mem == target_mem)
.and_then(|m| m.reload_failure.as_ref())
{
return Err(failure.refusal(target_mem));
}
if let Some(mount) = engine.mount(target_mem)
&& mount.capability == crate::workspace::MountCapability::ReadOnly
&& !engine.store.contains(target)
&& !matches!(
probe_deferred_target(engine, target)?,
DeferredTargetProbe::Exists
)
{
return Err(EngineError::CrossMemTargetNotFound {
target_id: target.to_string(),
target_mem: target_mem.to_string(),
});
}
Ok(())
}
pub(super) enum DeferredTargetProbe {
NotApplicable,
Exists,
Absent,
}
pub(super) fn probe_deferred_target(
engine: &super::Engine,
target: &EntityId,
) -> Result<DeferredTargetProbe, EngineError> {
let rel_path = crate::entity::id::id_to_file_path(target);
if engine.mem_is_deferred(target.mem()) {
let Some(mounted) = engine.mounts.iter().find(|m| m.mount.mem == target.mem()) else {
return Ok(DeferredTargetProbe::NotApplicable);
};
return Ok(
if mounted
.backend
.entity_exists(std::path::Path::new(&rel_path))?
{
DeferredTargetProbe::Exists
} else {
DeferredTargetProbe::Absent
},
);
}
if engine.mount(target.mem()).is_none()
&& let Some(prober) = &engine.unmounted_storage_prober
&& let Some(storage) = prober(target.mem())
{
return Ok(
if storage
.backend
.entity_exists(std::path::Path::new(&rel_path))?
{
DeferredTargetProbe::Exists
} else {
DeferredTargetProbe::Absent
},
);
}
Ok(DeferredTargetProbe::NotApplicable)
}
pub(super) fn deferred_verified_stub_kind(
engine: &super::Engine,
target: &EntityId,
) -> Result<crate::entity::StubKind, EngineError> {
Ok(
if matches!(
probe_deferred_target(engine, target)?,
DeferredTargetProbe::Exists
) {
crate::entity::StubKind::LoadTime
} else {
crate::entity::StubKind::ForwardReference
},
)
}
pub(super) fn peek_deferred_target_type(
engine: &super::Engine,
target: &EntityId,
) -> Result<Option<String>, EngineError> {
let rel_path = crate::entity::id::id_to_file_path(target);
let bytes = if engine.mem_is_deferred(target.mem()) {
let Some(mounted) = engine.mounts.iter().find(|m| m.mount.mem == target.mem()) else {
return Ok(None);
};
mounted
.backend
.read_entity(std::path::Path::new(&rel_path))?
} else if engine.mount(target.mem()).is_none()
&& let Some(prober) = &engine.unmounted_storage_prober
&& let Some(storage) = prober(target.mem())
{
storage
.backend
.read_entity(std::path::Path::new(&rel_path))?
} else {
return Ok(None);
};
let Some(bytes) = bytes else {
return Ok(None);
};
Ok(String::from_utf8(bytes)
.ok()
.and_then(|c| crate::entity::parser::peek_type_from_frontmatter(&c)))
}
pub(super) fn target_schema_ref_for_routing(
engine: &super::Engine,
target_mem: &str,
) -> Option<memstead_schema::SchemaRef> {
if let Some(s) = engine.schemas.get(target_mem) {
let (name, version) = s.id();
return Some(memstead_schema::SchemaRef::new(name, version));
}
if engine.mount(target_mem).is_none()
&& let Some(prober) = &engine.unmounted_storage_prober
&& let Some(storage) = prober(target_mem)
{
return storage.schema;
}
None
}
pub(super) enum EdgeRouteOutcome {
Ok,
OpenModeWarning(Box<crate::ops::WarningHint>),
}
#[allow(clippy::too_many_arguments)]
pub(super) fn route_edge_validation(
engine: &super::Engine,
rel_type: &str,
from_type: &str,
to_type: Option<&str>,
source_mem: &str,
target_mem: &str,
from_id: &EntityId,
to_id: &EntityId,
check_shape: bool,
) -> Result<EdgeRouteOutcome, EngineError> {
use crate::runtime_validator::{
CrossMemRelCheck, RelationshipCheck, validate_cross_mem_edge, validate_rel_shape,
validate_rel_type,
};
use memstead_schema::SchemaRef;
let source_schema = engine
.schemas
.get(source_mem)
.expect("schema present for every registered mount");
let target_schema_ref: Option<SchemaRef> = if source_mem == target_mem {
None
} else {
target_schema_ref_for_routing(engine, target_mem)
};
let cross_mem_different = match (&target_schema_ref, source_schema.id()) {
(Some(target), (src_name, _)) => target.name != src_name,
(None, _) => false,
};
if cross_mem_different {
let target_ref = target_schema_ref
.as_ref()
.expect("target_schema_ref is Some when cross_mem_different");
if !check_shape {
return Ok(EdgeRouteOutcome::Ok);
}
match validate_cross_mem_edge(
rel_type,
from_type,
to_type,
source_schema.as_ref(),
target_ref,
) {
CrossMemRelCheck::Ok => Ok(EdgeRouteOutcome::Ok),
CrossMemRelCheck::EdgeNotDeclared => {
let (src_name, src_version) = source_schema.id();
Err(EngineError::CrossMemEdgeNotDeclared {
source_schema: SchemaRef::new(src_name, src_version).as_display(),
target_schema: target_ref.as_display(),
rel_type: rel_type.to_string(),
from_id: from_id.to_string(),
to_id: to_id.to_string(),
})
}
CrossMemRelCheck::Invalid(v) => Err(EngineError::Validation(v)),
}
} else {
let warning_hint = match validate_rel_type(rel_type, source_schema.as_ref())? {
RelationshipCheck::Ok => None,
RelationshipCheck::OpenWarning(message) => {
Some(crate::ops::WarningHint::UndeclaredRelationshipOpen {
rel_type: rel_type.to_string(),
message,
})
}
};
if check_shape {
validate_rel_shape(rel_type, from_type, to_type, source_schema.as_ref())?;
}
Ok(match warning_hint {
Some(w) => EdgeRouteOutcome::OpenModeWarning(Box::new(w)),
None => EdgeRouteOutcome::Ok,
})
}
}
pub(super) fn validate_edge_acyclicity(
store: &Store,
schema: &memstead_schema::Schema,
from: &EntityId,
from_type: &str,
to: &EntityId,
rel_type: &str,
) -> Result<(), EngineError> {
if from == to && schema.type_refuses_self_loop(from_type, rel_type) {
return Err(EngineError::RelationshipCycle {
rel_type: rel_type.to_string(),
from: from.clone(),
to: to.clone(),
existing_path: vec![from.clone()],
path_truncated: false,
acyclic_set: None,
existing_path_rel_types: None,
});
}
if schema.relationship_acyclic(rel_type)
&& let Some(path) = crate::graph::query::would_cycle(store, from, to, rel_type)
{
let truncated = path.len() > RELATIONSHIP_CYCLE_PATH_CAP;
let mut existing_path = path;
if truncated {
existing_path.truncate(RELATIONSHIP_CYCLE_PATH_CAP);
}
return Err(EngineError::RelationshipCycle {
rel_type: rel_type.to_string(),
from: from.clone(),
to: to.clone(),
existing_path,
path_truncated: truncated,
acyclic_set: None,
existing_path_rel_types: None,
});
}
if let Some(set) = schema.acyclic_set_containing(rel_type)
&& let Some((path, path_rels)) =
crate::graph::query::would_cycle_in_set(store, from, to, set)
{
let truncated = path.len() > RELATIONSHIP_CYCLE_PATH_CAP;
let mut existing_path = path;
let mut existing_path_rel_types = path_rels;
if truncated {
existing_path.truncate(RELATIONSHIP_CYCLE_PATH_CAP);
existing_path_rel_types.truncate(existing_path.len().saturating_sub(1));
}
return Err(EngineError::RelationshipCycle {
rel_type: rel_type.to_string(),
from: from.clone(),
to: to.clone(),
existing_path,
path_truncated: truncated,
acyclic_set: Some(set.to_vec()),
existing_path_rel_types: Some(existing_path_rel_types),
});
}
Ok(())
}
pub(super) fn validate_description_posture(
engine: &super::Engine,
rel_type: &str,
description: Option<&str>,
source_mem: &str,
target_mem: &str,
from_id: &EntityId,
to_id: &EntityId,
) -> Result<(), EngineError> {
use memstead_schema::{PerEdgeDescription, SchemaRef};
let source_schema = engine
.schemas
.get(source_mem)
.expect("schema present for every registered mount");
let target_schema_ref: Option<SchemaRef> = if source_mem == target_mem {
None
} else {
target_schema_ref_for_routing(engine, target_mem)
};
let cross_mem_different = match (&target_schema_ref, source_schema.id()) {
(Some(target), (src_name, _)) => target.name != src_name,
(None, _) => false,
};
let posture = if cross_mem_different {
let target_ref = target_schema_ref
.as_ref()
.expect("target_schema_ref is Some when cross_mem_different");
source_schema
.cross_mem_entries(&target_ref.name)
.iter()
.find_map(|entry| entry.definitions.iter().find(|d| d.name == rel_type))
.map(|d| d.per_edge_description)
} else {
source_schema
.relationship_def(rel_type)
.map(|d| d.per_edge_description)
};
match posture {
Some(PerEdgeDescription::Required) if description.is_none() => {
Err(EngineError::MissingRequiredDescription {
rel_type: rel_type.to_string(),
from_id: from_id.to_string(),
to_id: to_id.to_string(),
})
}
Some(PerEdgeDescription::Forbidden) if description.is_some() => {
Err(EngineError::DescriptionNotPermitted {
rel_type: rel_type.to_string(),
from_id: from_id.to_string(),
to_id: to_id.to_string(),
})
}
_ => Ok(()),
}
}
pub(super) fn validate_manual_authoring_posture(
engine: &super::Engine,
rel_type: &str,
source_mem: &str,
from_id: &EntityId,
to_id: &EntityId,
) -> Result<(), EngineError> {
use memstead_schema::ManualAuthoring;
let source_schema = engine
.schemas
.get(source_mem)
.expect("schema present for every registered mount");
let posture = source_schema.relationship_manual_authoring(rel_type);
if matches!(posture, ManualAuthoring::Forbidden) {
let guidance = source_schema
.relationship_when_to_use(rel_type)
.unwrap_or_default();
return Err(EngineError::RelationManualAuthoringForbidden {
rel_type: rel_type.to_string(),
from_id: from_id.to_string(),
to_id: to_id.to_string(),
guidance,
});
}
Ok(())
}
pub(super) fn synthesise_alias_relations(
engine: &super::Engine,
prev_body_targets: &std::collections::HashSet<EntityId>,
next: &mut Entity,
) -> Result<AliasSynthesisOutcome, super::EngineError> {
let schema = engine
.schemas
.get(next.mem.as_str())
.expect("schema present for every registered mount");
let Some(pointer) = schema.alias_target_rel_type().map(str::to_string) else {
return Ok(AliasSynthesisOutcome::default());
};
let mut next_targets: std::collections::HashSet<EntityId> = std::collections::HashSet::new();
for (section_key, body) in next.sections.iter() {
let ids = crate::entity::parser::extract_inline_links(body, &next.mem)
.map_err(|errs| map_wiki_link_errors(section_key, errs))?;
next_targets.extend(ids);
}
next.relationships.retain(|r| {
!(r.rel_type == pointer
&& prev_body_targets.contains(&r.target)
&& !next_targets.contains(&r.target))
});
let existing: std::collections::HashSet<(String, EntityId)> = next
.relationships
.iter()
.map(|r| (r.rel_type.clone(), r.target.clone()))
.collect();
let mut emitted: Vec<crate::entity::Relationship> = Vec::new();
let mut already_synthesised: std::collections::HashSet<EntityId> =
std::collections::HashSet::new();
let mut self_link_ignored = false;
let mut undeclared_dropped: Vec<UndeclaredCrossSchemaLink> = Vec::new();
let mut undeclared_seen: std::collections::HashSet<EntityId> = std::collections::HashSet::new();
for (section_key, body) in next.sections.iter() {
let ids = crate::entity::parser::extract_inline_links(body, &next.mem)
.map_err(|errs| map_wiki_link_errors(section_key, errs))?;
for target in ids {
if target == next.id {
self_link_ignored = true;
continue;
}
let key = (pointer.clone(), target.clone());
if existing.contains(&key) || already_synthesised.contains(&target) {
continue;
}
validate_cross_mem_add_policy(engine, &next.mem, &target)?;
if target.mem() != next.mem
&& let Some(target_ref) = target_schema_ref_for_routing(engine, target.mem())
&& target_ref.name != schema.id().0
&& !schema
.cross_mem_entries(&target_ref.name)
.iter()
.any(|entry| entry.definitions.iter().any(|d| d.name == pointer))
{
if undeclared_seen.insert(target.clone()) {
let (src_name, src_version) = schema.id();
undeclared_dropped.push(UndeclaredCrossSchemaLink {
target,
source_schema: memstead_schema::SchemaRef::new(src_name, src_version)
.as_display(),
target_schema: target_ref.name,
});
}
continue;
}
let target_type = match engine
.store
.get(&target)
.map(|e| e.entity_type.clone())
.filter(|t| !t.is_empty())
{
Some(t) => Some(t),
None => peek_deferred_target_type(engine, &target)?,
};
let _ = route_edge_validation(
engine,
&pointer,
next.entity_type.as_str(),
target_type.as_deref(),
&next.mem,
target.mem(),
&next.id,
&target,
true,
)?;
validate_edge_acyclicity(
&engine.store,
schema.as_ref(),
&next.id,
next.entity_type.as_str(),
&target,
&pointer,
)?;
let rel = crate::entity::Relationship::new(pointer.clone(), target.clone());
next.relationships.push(rel.clone());
already_synthesised.insert(target);
emitted.push(rel);
}
}
Ok(AliasSynthesisOutcome {
emitted,
self_link_ignored,
undeclared_dropped,
})
}
pub(super) struct UndeclaredCrossSchemaLink {
pub target: EntityId,
pub source_schema: String,
pub target_schema: String,
}
#[derive(Default)]
pub(super) struct AliasSynthesisOutcome {
pub emitted: Vec<crate::entity::Relationship>,
pub self_link_ignored: bool,
pub undeclared_dropped: Vec<UndeclaredCrossSchemaLink>,
}
pub(super) fn map_wiki_link_errors(
section_key: &str,
errors: Vec<crate::entity::id::WikiLinkError>,
) -> EngineError {
use crate::entity::id::WikiLinkError;
let first = errors
.into_iter()
.next()
.expect("map_wiki_link_errors called with non-empty error list");
match first {
WikiLinkError::InvalidTarget {
raw,
suggested,
reason,
} => EngineError::InvalidWikiLinkTarget {
raw,
suggested,
section: section_key.to_string(),
link_source: "body_link".to_string(),
reason,
},
WikiLinkError::InvalidMemName { raw, reason } => EngineError::InvalidWikiLinkMem {
raw,
section: section_key.to_string(),
reason,
},
}
}
pub(super) fn collect_body_link_targets(entity: &Entity) -> std::collections::HashSet<EntityId> {
entity
.sections
.iter()
.flat_map(|(_, body)| {
crate::entity::parser::extract_inline_links_lenient(body, &entity.mem)
})
.collect()
}
pub(super) fn scan_wikilinks_without_relation(
next: &Entity,
exempt: &std::collections::HashSet<EntityId>,
) -> Result<Vec<(String, EntityId)>, EngineError> {
let explicit_targets: std::collections::HashSet<EntityId> = next
.relationships
.iter()
.map(|r| r.target.clone())
.collect();
let mut missing: Vec<(String, EntityId)> = Vec::new();
for (section_key, body) in next.sections.iter() {
let ids = crate::entity::parser::extract_inline_links(body, &next.mem)
.map_err(|errs| map_wiki_link_errors(section_key, errs))?;
for target in ids {
if target == next.id {
continue;
}
if exempt.contains(&target) {
continue;
}
if !explicit_targets.contains(&target)
&& !missing
.iter()
.any(|(k, t)| k == section_key && t == &target)
{
missing.push((section_key.clone(), target));
}
}
}
Ok(missing)
}
#[cfg(test)]
mod tests;