memstead_base/engine/mutation/mod.rs
1//! Engine mutation entrypoints — split per mutation kind.
2//!
3//! Each sub-module implements one mutation of `Engine`: `create`,
4//! `update` (with batch), `delete`, `relate`, `rename`. The shared
5//! helpers (`today_iso`, `make_stub`, `gc_orphan_stubs`,
6//! `lookup_title_and_type`, `unknown_type_error`) plus the typed
7//! constants `PATCH_OLD_NOT_FOUND_CONTENT_CAP` and
8//! `RELATIONSHIP_CYCLE_PATH_CAP` live here.
9
10use std::collections::HashMap;
11
12use indexmap::IndexMap;
13
14use crate::entity::{Entity, EntityId};
15use crate::store::Store;
16
17use super::EngineError;
18
19pub(super) use batch::{batch_empty, batch_receipt, batch_refusal};
20
21mod batch;
22pub mod create;
23pub mod delete;
24mod landing;
25pub mod mem_sweep;
26pub mod parse_recovery;
27pub mod proposal_merge;
28pub mod relate;
29pub mod rename;
30pub mod retype;
31pub mod update;
32
33/// Look up an entity's `(title, entity_type)` pair in `store`. Both
34/// `None` for missing-from-store ids — matches full's `title_for` /
35/// `type_for` lossy-lookup contract. Used by [`Engine::changes_since`]
36/// to enrich id-only envelopes the backend returned with metadata
37/// from the in-memory store.
38pub(super) fn lookup_title_and_type(
39 store: &Store,
40 id: &EntityId,
41) -> (Option<String>, Option<String>) {
42 match store.get(id) {
43 Some(e) => (Some(e.title.clone()), Some(e.entity_type.clone())),
44 None => (None, None),
45 }
46}
47
48/// Maximum byte length of the truncated `current_content` snapshot
49/// that [`EngineError::PatchOldNotFound`] carries. Keeps the wire
50/// envelope bounded for sections with large bodies. Mirrors full's
51/// `memstead_git_branch::PATCH_OLD_NOT_FOUND_CONTENT_CAP`.
52pub const PATCH_OLD_NOT_FOUND_CONTENT_CAP: usize = 500;
53
54/// Maximum number of entity IDs retained in
55/// [`EngineError::RelationshipCycle::existing_path`]. Keeps the cycle
56/// envelope bounded for pathologically long chains. Mirrors full's
57/// `memstead_git_branch::RELATIONSHIP_CYCLE_PATH_CAP`.
58pub const RELATIONSHIP_CYCLE_PATH_CAP: usize = 20;
59
60/// Build an [`EngineError::UnknownType`] populated with the schema's
61/// declared type names (sorted) and a fuzzy suggestion. Mirrors full's
62/// `UnknownEntityType` recovery payload so MCP envelopes carry the
63/// same `name` / `schema_ref` / `declared` / `suggestion` keys
64/// regardless of which engine served the call.
65/// Render an entity for a write, refusing the one state the generator would
66/// silently make permanent.
67///
68/// **This is the mutation path's only way to bytes.** Calling
69/// `generate_markdown` directly from a mutation verb bypasses the guard, and
70/// the first version of this fix did exactly that: the check lived in
71/// `update_entity`, so `memstead relate` against the same entity walked
72/// straight past it and froze the absorption anyway (found by
73/// the grade). A guard a new verb can miss by following the
74/// local idiom is not a guard; making the guarded call BE the idiom is.
75///
76/// The condition: a section whose stored body ends inside an unterminated
77/// fence has already absorbed every section after it, and the generator
78/// appends its closer AFTER those bytes. One write seals them inside a
79/// legitimately fenced block where nothing can tell them from prose the
80/// author meant to fence. It is refused rather than warned about because it
81/// is unrecoverable once it lands.
82///
83/// The way out needs no special case: a caller who replaces the absorbing
84/// section hands us an entity whose fence is closed, so the guard simply
85/// does not fire.
86pub(crate) fn render_for_write(
87 entity: &Entity,
88 type_def: &memstead_schema::TypeDefinition,
89) -> Result<String, EngineError> {
90 for (key, value) in &entity.sections {
91 if let Some(fence) = crate::markdown::closing_fence_if_unterminated(value.trim()) {
92 return Err(EngineError::UnterminatedFenceInStoredBody {
93 id: entity.id.to_string(),
94 section: key.clone(),
95 fence,
96 swallowed: crate::ops::integrity::swallowed_declared_sections(value, type_def),
97 });
98 }
99 }
100 Ok(crate::entity::generator::generate_markdown(
101 entity, type_def,
102 ))
103}
104
105/// One edge a write adds or removes, as the full-load decision reads it.
106pub(crate) struct EdgeWrite<'a> {
107 pub rel_type: &'a str,
108 pub target_mem: &'a str,
109 pub remove: bool,
110}
111
112impl super::Engine {
113 /// The ids of the stubs in the store, read before a single write so a
114 /// refusal can take back the stubs the write's composition created.
115 pub(in crate::engine) fn stub_ids(&self) -> std::collections::HashSet<EntityId> {
116 self.store
117 .all_entities()
118 .filter(|e| e.stub)
119 .map(|e| e.id.clone())
120 .collect()
121 }
122
123 /// Take back what a write that did not land left in the store: every
124 /// stub not in `before` was made by its composition (a declared or
125 /// wiki-linked target), and no committed edge points at it. A commit
126 /// that is decided and not yet applied counts as landed.
127 pub(in crate::engine) fn drop_stubs_of_an_unlanded_write<T>(
128 &mut self,
129 before: &std::collections::HashSet<EntityId>,
130 landed: &Result<T, EngineError>,
131 rehearsal: bool,
132 ) {
133 if !rehearsal
134 && !matches!(landed, Err(e) if !matches!(e, EngineError::CommitNotApplied { .. }))
135 {
136 return;
137 }
138 let made: Vec<EntityId> = self
139 .store
140 .all_entities()
141 .filter(|e| e.stub && !before.contains(&e.id))
142 .map(|e| e.id.clone())
143 .collect();
144 for id in made {
145 self.store.remove(&id);
146 }
147 }
148}
149
150impl super::Engine {
151 /// Whether a write to `mem` touching `edges` needs every mem loaded
152 /// first: a partial store would mis-judge it. Two guards read edges
153 /// that can originate in any mem: the cycle guard of an acyclic
154 /// rel-type, or of one in an `acyclic_sets` set (it walks the union
155 /// subgraph), on an edge being added; and the threshold-crossing diff
156 /// of declared aggregate signals on the written mem's schema or an
157 /// edge target's. A write touching neither skips the cost. The write
158 /// lock asks the same question: a write that reads every mem holds
159 /// every mem's lock, so each is reloaded under it before it is read.
160 ///
161 /// `texts` is the body content the write lands. When the mem's schema
162 /// declares `alias_target_rel_type`, each body wiki-link in it is a
163 /// pointer edge of that relationship and is judged as a declared edge
164 /// is, so a cycle a body link closes is guarded on the full store.
165 pub(crate) fn write_needs_full_load<'a, 't>(
166 &self,
167 mem: &str,
168 edges: impl IntoIterator<Item = EdgeWrite<'a>>,
169 texts: impl IntoIterator<Item = &'t str>,
170 ) -> bool {
171 let has_signals = |m: &str| {
172 self.schemas
173 .get(m)
174 .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
175 };
176 let cycle_guarded = |rel: &str| self.rel_type_is_acyclic(mem, rel);
177 if has_signals(mem)
178 || edges
179 .into_iter()
180 .any(|e| (!e.remove && cycle_guarded(e.rel_type)) || has_signals(e.target_mem))
181 {
182 return true;
183 }
184 let Some(pointer) = self
185 .schemas
186 .get(mem)
187 .and_then(|s| s.manifest.alias_target_rel_type.clone())
188 else {
189 return false;
190 };
191 texts
192 .into_iter()
193 .filter(|t| t.contains("[["))
194 .flat_map(|t| crate::entity::parser::extract_inline_links_lenient(t, mem))
195 .any(|target| cycle_guarded(&pointer) || has_signals(target.mem()))
196 }
197}
198
199pub(crate) fn unknown_type_error(schema: &memstead_schema::Schema, attempted: &str) -> EngineError {
200 let mut declared: Vec<String> = schema.types.keys().cloned().collect();
201 declared.sort();
202 let (sname, sver) = schema.id();
203 EngineError::UnknownType {
204 name: attempted.to_string(),
205 schema_ref: format!("{sname}@{sver}"),
206 declared,
207 suggestion: schema.suggest_type(attempted),
208 }
209}
210
211/// The lowercase wire string for a [`crate::pipeline::MediumType`] — the
212/// value the `INVALID_ANCHOR` recovery detail carries so an agent sees
213/// which medium's namespace rejected the grain. Matches the enum's
214/// `#[serde(rename_all = "lowercase")]` form.
215pub(crate) fn medium_type_wire(t: crate::pipeline::MediumType) -> &'static str {
216 use crate::pipeline::MediumType::*;
217 match t {
218 Codebase => "codebase",
219 Filesystem => "filesystem",
220 Graph => "graph",
221 Git => "git",
222 Web => "web",
223 }
224}
225
226impl super::Engine {
227 /// Resolve the single-source anchor-namespace context for `mem`, when
228 /// unambiguous. An `anchors[]` element carries no source name, so the
229 /// grain/namespace refusal ([`crate::anchor::AnchorValidationError::GrainNamespaceUnsupported`])
230 /// can only be fired deterministically when the mem's bindings declare
231 /// exactly one inline source; with zero or several the namespace check
232 /// is skipped (the vocabulary + hash-semantics rules still apply).
233 /// Returns the `(medium_type_wire, anchor_namespace)` pair the
234 /// validator consumes — the medium *half* of the lone source.
235 pub(crate) fn resolve_anchor_medium(&self, mem: &str) -> Option<(String, &'static str)> {
236 let mut sources = self
237 .pipeline_configs()
238 .bindings
239 .iter()
240 .filter(|r| r.mem == mem)
241 .flat_map(|r| r.config.sources.iter());
242 let first = sources.next()?;
243 if sources.next().is_some() {
244 // Ambiguous — the anchor does not name which source it targets;
245 // skip the namespace refinement rather than guess.
246 return None;
247 }
248 let caps = crate::binding::medium_capabilities(first.medium_type);
249 Some((
250 medium_type_wire(first.medium_type).to_string(),
251 caps.anchor_namespace,
252 ))
253 }
254
255 /// Validate the permissive `anchors[]` inputs for a mutation against
256 /// `mem`'s medium context into strict [`crate::anchor::Anchor`]s, or
257 /// refuse the whole mutation with a typed
258 /// [`EngineError::InvalidAnchor`]. Empty input yields an empty vec (no
259 /// sidecar write); a single malformed element aborts before any state
260 /// change so the entity is never written.
261 pub fn validate_anchor_inputs(
262 &self,
263 mem: &str,
264 inputs: &[crate::anchor::AnchorInput],
265 ) -> Result<Vec<crate::anchor::Anchor>, EngineError> {
266 if inputs.is_empty() {
267 return Ok(Vec::new());
268 }
269 let medium = self.resolve_anchor_medium(mem);
270 let medium_ref = medium.as_ref().map(|(t, ns)| (t.as_str(), *ns));
271 let mut anchors: Vec<crate::anchor::Anchor> = inputs
272 .iter()
273 .map(|i| i.validate(medium_ref).map_err(EngineError::from))
274 .collect::<Result<_, _>>()?;
275
276 // One payload, one row per identity.
277 // `(artifact, grain, class, span)` is the sidecar's merge
278 // identity, so a payload naming it twice used to collapse to the last
279 // occurrence and the caller was never told an anchor it wrote had
280 // vanished. The unit is THIS payload: the same identity arriving in a
281 // later call still replaces the stored row, which is what the
282 // carry-forward depends on. The span compares in its canonical form,
283 // the form the row is matched in everywhere else.
284 {
285 let mut seen: std::collections::HashSet<(&str, &str, &str, Option<String>)> =
286 std::collections::HashSet::new();
287 for a in &anchors {
288 let key = (
289 a.artifact.as_str(),
290 a.grain.as_wire(),
291 a.class.as_wire(),
292 a.span
293 .as_deref()
294 .map(crate::preparation::canonical_span_form),
295 );
296 if !seen.insert(key) {
297 return Err(EngineError::from(
298 crate::anchor::AnchorValidationError::DuplicateAnchorTriple {
299 artifact: a.artifact.clone(),
300 grain: a.grain.as_wire(),
301 class: a.class.as_wire(),
302 span: a.span.clone(),
303 },
304 ));
305 }
306 }
307 }
308
309 // Supplied `content` under the source's preparation: the context-free
310 // validator hashed the bytes under the default canonicalization; the
311 // seam knows the anchor's source and re-hashes through the registry's
312 // rule for that source (touchpoint A at write time), so the recorded
313 // hash is the one a later observation computes.
314 if inputs.iter().any(|i| i.content.is_some()) {
315 let joins = self.anchor_source_roots(mem);
316 for (input, anchor) in inputs.iter().zip(anchors.iter_mut()) {
317 let (Some(content), Some(source)) = (&input.content, &anchor.source) else {
318 continue;
319 };
320 let Some(join) = joins.get(source) else {
321 continue;
322 };
323 if join.preparation.is_none() {
324 continue;
325 }
326 match crate::preparation::path_prepared_hash(
327 join.preparation.as_deref(),
328 &anchor.artifact,
329 anchor.grain,
330 content.as_bytes(),
331 ) {
332 crate::preparation::PathPrepared::Hash(h) => anchor.hash = Some(h),
333 crate::preparation::PathPrepared::NoHash => {}
334 crate::preparation::PathPrepared::UnitAbsent => {
335 return Err(EngineError::from(
336 crate::anchor::AnchorValidationError::UnitAbsentFromContent {
337 artifact: anchor.artifact.clone(),
338 },
339 ));
340 }
341 }
342 }
343 }
344
345 // Source-vs-binding check: when an anchor names BOTH a producing
346 // binding and a source, and that binding hash still resolves in
347 // this workspace (reverse lookup — any later binding edit moves
348 // the hash and drops earlier anchors into the accept-any-name
349 // branch for good), the source must be one of the binding's
350 // declared names. The bindings load is skipped entirely unless
351 // some input needs it, and a missing workspace root or an
352 // unloadable store degrades to accept-any-name — validation
353 // must never require the binding to resolve.
354 if anchors
355 .iter()
356 .any(|a| a.binding.is_some() && a.source.is_some())
357 && let Some(root) = self.workspace_root()
358 && let Ok(configs) = crate::pipeline_store::load_pipeline_configs(root)
359 {
360 for a in &anchors {
361 let (Some(binding_hash), Some(source)) = (&a.binding, &a.source) else {
362 continue;
363 };
364 let Some(record) = configs
365 .bindings
366 .iter()
367 .find(|r| crate::binding::hash_binding(&r.config) == *binding_hash)
368 else {
369 continue; // unresolvable binding: accept any non-empty name
370 };
371 let declared: Vec<String> = record
372 .config
373 .sources
374 .iter()
375 .map(|s| s.name.clone())
376 .collect();
377 if !declared.iter().any(|n| n == source) {
378 return Err(EngineError::from(
379 crate::anchor::AnchorValidationError::SourceNotDeclared {
380 got: source.clone(),
381 declared,
382 },
383 ));
384 }
385 }
386 }
387
388 // Write time resolves or refuses: a
389 // path-grain anchor whose artifact resolves under NO candidate join
390 // is a silently dead reference — refuse now, while the write moment
391 // still has the binding context to say what the right dialect is.
392 // Candidates in decision-29 priority: the source-join (the anchor's
393 // `source` name resolved to its declared pointer) first, then the
394 // workspace-relative form. An anchor naming a source the LOADED
395 // roster does not declare (a typo, a renamed binding) gets no join
396 // candidate — its workspace-relative form must resolve or the write
397 // refuses, because resolution will make the same roster lookup and
398 // orphan it at birth. The gate skips entirely only when it cannot
399 // know: no workspace root, or a pipeline store whose LOAD fails as a
400 // whole — validation never requires the binding store to be
401 // readable. (A corrupted individual binding file does not fail the
402 // load; it yields a reduced roster, and the gate then fail-closes on
403 // paths that resolve under no surviving candidate.)
404 if let Some(root) = self.workspace_root()
405 && crate::pipeline_store::load_pipeline_configs(root).is_ok()
406 {
407 let source_roots = self.anchor_source_roots(mem);
408 for a in &anchors {
409 match a.grain {
410 crate::anchor::AnchorGrain::Span
411 | crate::anchor::AnchorGrain::File
412 | crate::anchor::AnchorGrain::Tree => {}
413 crate::anchor::AnchorGrain::Url | crate::anchor::AnchorGrain::Entity => {
414 continue;
415 }
416 }
417 let base = crate::engine::query::anchor_base_path(&a.artifact);
418 // The shared decision-29 candidate rule — the same set
419 // resolution will later read, so the gate cannot accept a
420 // path resolution would read differently.
421 let candidates: Vec<String> = match a
422 .source
423 .as_ref()
424 .and_then(|source| source_roots.get(source))
425 {
426 Some(join) => crate::engine::query::artifact_candidates(&join.pointer, base),
427 None => vec![base.to_string()],
428 };
429 if !candidates.iter().any(|c| root.join(c).exists()) {
430 return Err(EngineError::from(
431 crate::anchor::AnchorValidationError::ArtifactUnresolvable {
432 artifact: a.artifact.clone(),
433 candidates,
434 },
435 ));
436 }
437 }
438 }
439
440 // The entity-grain pin: a hash-bearing `entity` row written without
441 // a hash takes its target's prepared hash as the engine computes it
442 // NOW (the same form observation compares, under the preparation the
443 // row's source declares), marked `pinned`, so the next verify reads
444 // the row against the target as it was when the claim was made. A
445 // row backfilled at a later verify instead was pinned to whatever
446 // the target had become by then. A target
447 // the engine cannot resolve at write (unknown id, unmounted mem, a
448 // stub, a preparation without an entity form) leaves the row
449 // hash-less and unverified: never a guessed hash. A supplied hash is
450 // the author's baseline and is kept.
451 if anchors
452 .iter()
453 .any(|a| a.grain == crate::anchor::AnchorGrain::Entity)
454 {
455 let joins = self.anchor_source_roots(mem);
456 for a in anchors.iter_mut() {
457 if a.grain != crate::anchor::AnchorGrain::Entity
458 || !a.class.is_hash_bearing()
459 || a.hash.is_some()
460 {
461 continue;
462 }
463 let preparation = a
464 .source
465 .as_deref()
466 .and_then(|name| joins.get(name))
467 .and_then(|j| j.preparation.as_deref());
468 if let Some(hash) = self.entity_anchor_target_hash(&a.artifact, preparation) {
469 a.hash = Some(hash);
470 a.hash_source = Some(crate::anchor::AnchorHashSource::Pinned);
471 }
472 }
473 }
474
475 Ok(anchors)
476 }
477
478 /// Validate an update's `anchors_unset[]` payload up front — a
479 /// malformed selector (missing artifact, unknown grain/class wire
480 /// string) refuses the whole mutation with the same typed
481 /// `INVALID_ANCHOR` envelope as a malformed `anchors[]` element.
482 /// Empty payload → empty vec.
483 pub(crate) fn validate_anchor_unsets(
484 inputs: &[crate::anchor::AnchorUnsetInput],
485 ) -> Result<Vec<crate::anchor::AnchorUnset>, EngineError> {
486 inputs
487 .iter()
488 .map(|i| i.validate().map_err(EngineError::from))
489 .collect()
490 }
491
492 /// Record verify-observed prepared-content hashes onto **hash-less
493 /// hash-bearing** anchors in `mem_name`'s anchors sidecar — the
494 /// measurement-bookkeeping backfill the verify pass hands over via
495 /// the loop's `VerifyOutcome::hash_backfill` (`memstead_projection`).
496 ///
497 /// This mutates **only** the engine-owned sidecar
498 /// ([`crate::anchor::ANCHOR_SIDECAR_PATH`]): no entity content, no
499 /// section, no `_hash` is touched — an anchor-only commit yields zero
500 /// entity deltas by construction. Guards enforced at this write seam,
501 /// not left to callers:
502 ///
503 /// - only a hash-bearing class (`anchored` / `derived`) may gain a hash —
504 /// an `authored` / `informed-by` anchor is never written, whatever the
505 /// caller observed;
506 /// - an anchor that already carries a hash is never overwritten — the
507 /// recorded hash is the drift baseline, so the backfill is idempotent
508 /// (a second identical call stages nothing and produces no commit).
509 ///
510 /// Returns how many anchors gained a hash. Zero writes ⇒ no commit.
511 pub fn record_anchor_observed_hashes(
512 &mut self,
513 mem_name: &str,
514 observed: &[crate::anchor::ObservedArtifactHash],
515 note: Option<&str>,
516 ) -> Result<usize, EngineError> {
517 if observed.is_empty() {
518 return Ok(0);
519 }
520 let (_, _roster_notice) = self.writable_mount_on_current_roster(mem_name)?;
521 // Same posture as every other commit-producing write: probe for
522 // sibling-engine drift so the sidecar merge runs against current truth.
523 let (_write_lock, _roster) = self.lock_for_write(true, &[mem_name])?;
524 let _warnings = self.reload_if_stale_content_only(Some(mem_name));
525 let mount_idx = self.writable_mount_index(mem_name)?;
526
527 let backend = self.mounts[mount_idx].backend.as_ref();
528 let mut sidecar = read_sidecar(backend)?;
529 let mut written = 0usize;
530 for obs in observed {
531 let Some(anchors) = sidecar.entities.get_mut(&obs.entity) else {
532 continue;
533 };
534 for a in anchors {
535 if a.class.is_hash_bearing() && a.hash.is_none() && a.artifact == obs.artifact {
536 a.hash = Some(obs.hash.clone());
537 // Stamp the origin:
538 // this baseline is the engine's inference from what it
539 // observed, not something an author pinned, and a reader
540 // comparing drift needs to know which.
541 a.hash_source = Some(crate::anchor::AnchorHashSource::Backfill);
542 written += 1;
543 }
544 }
545 }
546 if written == 0 {
547 return Ok(0);
548 }
549 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
550 let ctx = self.session_commit_context(
551 Some("record_anchor_observed_hashes"),
552 note.map(String::from),
553 );
554 // The count this returns has no channel for a follow-up warning
555 // either; the write id is all it takes from the landed commit.
556 let write_id = self
557 .commit_staged(
558 mount_idx,
559 &format!("memstead: anchor-hash backfill ({written} anchor(s))"),
560 &ctx,
561 &[],
562 )?
563 .write_id;
564 self.record_self_write(mount_idx, &write_id);
565 // Anchor-hash backfill returns a count, not an agent-facing response,
566 // so an intervention report has nowhere to ride. Discarded knowingly:
567 // the merge itself still happened, so nothing was lost — only the
568 // notice that someone else had written.
569 let _intervention_has_no_channel_here = self.stamp_mutation_versions(mount_idx);
570 Ok(written)
571 }
572
573 /// Record observer-supplied observations onto `url` rows of `mem_name`'s
574 /// anchors sidecar as their `last_observed` record (sidecar version 2)
575 /// — the bookkeeping leg of `memstead verify-anchors --observations`.
576 /// Mutates only the engine-owned sidecar: no entity content, no `_hash`.
577 /// Guards at this seam:
578 ///
579 /// - only a `url` row is written: path and entity rows are observed live
580 /// on every pass and never carry a recorded observation;
581 /// - a hash-bearing row that has no hash yet takes the observed hash as
582 /// its baseline (`hash_source: backfill`), exactly as the path
583 /// backfill does; a row that already carries a hash keeps it;
584 /// - a row that already carries the identical `last_observed` stages
585 /// nothing, so re-running with the same file produces no commit.
586 ///
587 /// Returns how many rows changed. Zero writes ⇒ no commit.
588 pub fn record_anchor_observations(
589 &mut self,
590 mem_name: &str,
591 observations: &[crate::engine::query::RecordedObservation],
592 note: Option<&str>,
593 ) -> Result<usize, EngineError> {
594 if observations.is_empty() {
595 return Ok(0);
596 }
597 let (_, _roster_notice) = self.writable_mount_on_current_roster(mem_name)?;
598 let (_write_lock, _roster) = self.lock_for_write(true, &[mem_name])?;
599 let _warnings = self.reload_if_stale_content_only(Some(mem_name));
600 let mount_idx = self.writable_mount_index(mem_name)?;
601
602 let backend = self.mounts[mount_idx].backend.as_ref();
603 let mut sidecar = read_sidecar(backend)?;
604 let mut written = 0usize;
605 for obs in observations {
606 let Some(anchors) = sidecar.entities.get_mut(&obs.entity) else {
607 continue;
608 };
609 for a in anchors {
610 // The row identity, span included: an artifact carrying
611 // several span rows takes each observation on the one row
612 // the verify adjudicated, and a row the verify did not
613 // adjudicate (a hash-only observation over a span row) gets
614 // no record.
615 if a.grain != crate::anchor::AnchorGrain::Url
616 || a.artifact != obs.artifact
617 || !crate::anchor::same_span(a.span.as_deref(), obs.span.as_deref())
618 {
619 continue;
620 }
621 let mut changed = false;
622 if a.last_observed.as_ref() != Some(&obs.observation) {
623 a.last_observed = Some(obs.observation.clone());
624 changed = true;
625 }
626 // A span the write could not check has now been looked for
627 // in observed text (resolves or span_absent): it is no
628 // longer unverified. A `recheck` (failed retrieval) says
629 // nothing about the span and leaves the flag.
630 if a.span.is_some()
631 && a.span_unvalidated
632 && matches!(
633 obs.observation.state,
634 crate::anchor::AnchorState::Resolves
635 | crate::anchor::AnchorState::SpanAbsent
636 )
637 {
638 a.span_unvalidated = false;
639 changed = true;
640 }
641 if a.class.is_hash_bearing()
642 && a.hash.is_none()
643 && let Some(hash) = &obs.observation.hash
644 {
645 a.hash = Some(hash.clone());
646 a.hash_source = Some(crate::anchor::AnchorHashSource::Backfill);
647 changed = true;
648 }
649 if changed {
650 written += 1;
651 }
652 }
653 }
654 if written == 0 {
655 return Ok(0);
656 }
657 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
658 let ctx =
659 self.session_commit_context(Some("record_anchor_observations"), note.map(String::from));
660 let write_id = self
661 .commit_staged(
662 mount_idx,
663 &format!("memstead: anchor observations recorded ({written} row(s))"),
664 &ctx,
665 &[],
666 )?
667 .write_id;
668 self.record_self_write(mount_idx, &write_id);
669 let _intervention_has_no_channel_here = self.stamp_mutation_versions(mount_idx);
670 Ok(written)
671 }
672
673 /// Record on the mem which engine version and which resolved
674 /// schema performed the mutation that just committed
675 /// (`MemConfig.mutation_stamp`). Called by every mutation verb
676 /// after `record_self_write` — one shared implementation, per the
677 /// one-guard-on-all-write-paths principle — and deliberately NOT
678 /// by `apply_external_commit`: a replayed sibling commit was
679 /// stamped by the engine that performed it, and this engine must
680 /// not claim it.
681 ///
682 /// Write-cheap by construction: the config write happens only when
683 /// the stamp VALUE changes (a binary upgrade or a schema repin) —
684 /// steady-state mutations compare and return. The write is
685 /// best-effort: a failed stamp never fails the mutation that
686 /// preceded it. On git-branch backends the config rides the
687 /// `__MEMSTEAD` ref, so a stamp write never moves the mem branch
688 /// head — so a git-branch mem's change cursor (the `head` a prior
689 /// `changes_since` returned) stays valid across a stamp write.
690 pub(crate) fn stamp_mutation_versions(
691 &mut self,
692 mount_idx: usize,
693 ) -> Vec<crate::ops::WarningHint> {
694 let Some(state) = self.mounts.get(mount_idx) else {
695 return Vec::new();
696 };
697 let mem = state.mount.mem.clone();
698 let Some(schema) = self.schemas.get(&mem) else {
699 return Vec::new();
700 };
701 let (name, version) = schema.id();
702 // Full build version (semver + git build sha when present) so
703 // a rebuild between mutations is a recordable — and hence
704 // skew-detectable — event even between releases.
705 let stamp = memstead_schema::MutationStamp {
706 engine_version: crate::build_info::full_version().to_string(),
707 schema: format!("{name}@{version}"),
708 };
709 // A mem with no loaded config has nowhere to carry the stamp;
710 // skip silently (in-memory sketches, minimal fixtures).
711 let Some(config) = self
712 .mounts
713 .get(mount_idx)
714 .and_then(|s| s.mem_config.as_ref())
715 else {
716 return Vec::new();
717 };
718 // Skew at WRITE time, and before the restamp below erases the evidence.
719 // Boot-only detection meant a long-lived server
720 // that started under one binary and was written to by another never
721 // said so, and the very write that would have revealed it wrote the
722 // stamp that hid it. The write is never refused: a
723 // deliberate downgrade is the operator's business.
724 let mut warnings = Vec::new();
725 if let Some(prior) = config.mutation_stamp.as_ref()
726 && let Some(direction) = crate::build_info::skew_direction(
727 &prior.engine_version,
728 crate::build_info::full_version(),
729 )
730 {
731 warnings.push(crate::ops::WarningHint::EngineVersionSkew {
732 mem: mem.clone(),
733 stamped_engine: prior.engine_version.clone(),
734 running_engine: crate::build_info::full_version().to_string(),
735 stamped_schema: prior.schema.clone(),
736 direction,
737 });
738 }
739 if config.mutation_stamp.as_ref() == Some(&stamp) {
740 return warnings;
741 }
742 // Through the shared writer like the seven lifecycle setters.
743 // This one is why the damage looked
744 // spontaneous: it rides ordinary create/update/relate/rename/delete,
745 // so an operator saw a config field vanish during an innocuous entity
746 // write with no lifecycle call in sight. It stays exactly as dormant
747 // as before, because the equality guard above still decides whether
748 // to write at all; what changed is only what it writes over.
749 // The intervention rides the ENTITY mutation's own response: this
750 // writer has no response of its own, and the operator who sees a
751 // config field move during an innocuous entity write is owed the
752 // reason there (found by the grade:
753 // an earlier draft discarded this with `let _`).
754 match self.write_mem_config_merged(
755 mount_idx,
756 &mem,
757 "stamp_mutation_versions",
758 Some("engine version stamp"),
759 &move |c: &mut memstead_schema::config::MemConfig| {
760 c.mutation_stamp = Some(stamp.clone());
761 },
762 ) {
763 Ok((_, intervened)) if !intervened.is_empty() => {
764 warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
765 mem,
766 fields: intervened,
767 });
768 warnings
769 }
770 _ => warnings,
771 }
772 }
773}
774
775/// Stage a write of `entity_id`'s anchors into the mem's anchors sidecar
776/// through `backend`, merged over the existing sidecar at BOTH levels —
777/// other entities' rows survive (document level), and within the entity's
778/// own row `unsets` apply first, then each incoming anchor replaces the
779/// existing anchor with the same `(artifact, grain, class, span)` identity
780/// or appends ([`crate::anchor::AnchorSidecar::merge`]). Writing never
781/// removes an anchor the call did not name in `unsets`. The write is
782/// buffered into the SAME pending op set the entity write used — so the
783/// next [`crate::backend::MemBackend::commit`] carries entity + anchors
784/// as one atomic commit. Reads honour pending-buffer precedence, so
785/// successive stages within one transaction compose.
786/// Stage a mutation of the engine-owned derivations sidecar
787/// so it rides the SAME commit as the edge
788/// write that produced it — the anchors-sidecar atomicity precedent.
789/// The sidecar travels through the backend's normal entity-path
790/// read/write under `.memstead/`, which every backend filters from
791/// entity listings and every archive/export path carries as-is.
792pub(crate) fn stage_derivation_sidecar(
793 backend: &dyn crate::backend::MemBackend,
794 mutate: impl FnOnce(&mut crate::derivation::DerivationSidecar),
795) -> Result<(), EngineError> {
796 let path = std::path::Path::new(crate::derivation::DERIVATION_SIDECAR_PATH);
797 let mut sidecar = match backend.read_entity(path)? {
798 Some(bytes) => crate::derivation::DerivationSidecar::from_bytes(&bytes).map_err(|e| {
799 EngineError::Backend(crate::backend::BackendError::Other(format!(
800 "derivations sidecar parse: {e}"
801 )))
802 })?,
803 None => crate::derivation::DerivationSidecar::default(),
804 };
805 mutate(&mut sidecar);
806 backend.write_entity(path, &sidecar.to_bytes())?;
807 Ok(())
808}
809
810/// True when `schema` declares `rel_type` as a derivation
811/// (`derivation: true` on the relationship definition) — the
812/// predicate every write path shares, so baseline recording cannot
813/// fork per verb.
814pub(crate) fn rel_type_declares_derivation(
815 schema: &memstead_schema::Schema,
816 rel_type: &str,
817) -> bool {
818 schema
819 .manifest
820 .relationships
821 .definitions
822 .iter()
823 .any(|d| d.name == rel_type && d.derivation)
824}
825
826pub(crate) fn stage_anchors_sidecar(
827 backend: &dyn crate::backend::MemBackend,
828 entity_id: &EntityId,
829 unsets: &[crate::anchor::AnchorUnset],
830 anchors: Vec<crate::anchor::Anchor>,
831 rebaseline: bool,
832) -> Result<bool, EngineError> {
833 let mut sidecar = read_sidecar(backend)?;
834 // An anchors-only update whose rows restate the stored ones writes
835 // nothing: the sidecar bytes stay, and the caller is told the anchors
836 // did not change. `rebaseline` marks the
837 // update that also changed the entity's content, where a restated row
838 // is rewritten hash-less for the next verify to backfill.
839 if !sidecar.merge(entity_id.as_ref(), unsets, anchors, rebaseline) {
840 return Ok(false);
841 }
842 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
843 Ok(true)
844}
845
846/// Whether merging `anchors` / `unsets` into `entity_id`'s row would change
847/// the mem's sidecar, computed on a copy before anything is written, so
848/// the update path can answer truthfully (and skip the commit) when an
849/// anchors-only update restates what is stored.
850pub(crate) fn anchors_would_change(
851 backend: &dyn crate::backend::MemBackend,
852 entity_id: &EntityId,
853 unsets: &[crate::anchor::AnchorUnset],
854 anchors: &[crate::anchor::Anchor],
855 rebaseline: bool,
856) -> Result<bool, EngineError> {
857 let mut sidecar = read_sidecar(backend)?;
858 Ok(sidecar.merge(entity_id.as_ref(), unsets, anchors.to_vec(), rebaseline))
859}
860
861/// Load the mem's anchors sidecar through `backend`, or the empty
862/// document when none exists yet. Shared by the delete / rename legs
863/// which must decide whether the entity actually has anchor rows before
864/// staging a sidecar write (so an entity with none stays byte-identical
865/// to a pre-anchor mutation).
866fn read_sidecar(
867 backend: &dyn crate::backend::MemBackend,
868) -> Result<crate::anchor::AnchorSidecar, EngineError> {
869 match backend.read_anchors_sidecar()? {
870 Some(bytes) => crate::anchor::AnchorSidecar::from_bytes(&bytes).map_err(|e| {
871 EngineError::Backend(crate::backend::BackendError::Other(format!(
872 "anchors sidecar parse: {e}"
873 )))
874 }),
875 None => Ok(crate::anchor::AnchorSidecar::default()),
876 }
877}
878
879/// Stage removal of `entity_id`'s anchor row into the same commit as an
880/// entity delete — a no-op (no sidecar write, so byte-identical to today)
881/// when the entity carries no anchors. Returns whether a write was staged.
882pub(crate) fn stage_anchors_removal(
883 backend: &dyn crate::backend::MemBackend,
884 entity_id: &EntityId,
885) -> Result<bool, EngineError> {
886 let mut sidecar = read_sidecar(backend)?;
887 if sidecar.get(entity_id.as_ref()).is_empty() {
888 return Ok(false);
889 }
890 sidecar.remove(entity_id.as_ref());
891 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
892 Ok(true)
893}
894
895/// Stage a replacement of `entity_id`'s whole anchor row with `rows` (a
896/// proposal merge landing an entity's anchors as the fork has them): the
897/// target's rows for that entity go, the fork's rows come, under the
898/// target's id. A no-op when the stored row already equals `rows` (an
899/// entity with no rows on either side stages nothing). Returns whether a
900/// write was staged.
901pub(crate) fn stage_anchors_replace(
902 backend: &dyn crate::backend::MemBackend,
903 entity_id: &EntityId,
904 rows: Vec<crate::anchor::Anchor>,
905) -> Result<bool, EngineError> {
906 let mut sidecar = read_sidecar(backend)?;
907 if sidecar.get(entity_id.as_ref()) == rows.as_slice() {
908 return Ok(false);
909 }
910 sidecar.set(entity_id.as_ref(), rows);
911 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
912 Ok(true)
913}
914
915/// Stage a move of `from`'s anchor row to `to` into the same commit as an
916/// entity rename — leaving zero rows under the old id. A no-op (byte-
917/// identical to today) when the renamed entity carries no anchors. Returns
918/// whether a write was staged.
919pub(crate) fn stage_anchors_rename(
920 backend: &dyn crate::backend::MemBackend,
921 from: &EntityId,
922 to: &EntityId,
923) -> Result<bool, EngineError> {
924 let mut sidecar = read_sidecar(backend)?;
925 if sidecar.get(from.as_ref()).is_empty() {
926 return Ok(false);
927 }
928 sidecar.rename(from.as_ref(), to.as_ref());
929 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
930 Ok(true)
931}
932
933/// Follow an adopted body's origin marks across a rename, staged into the
934/// same commit as the file move, exactly as the anchors sidecar is.
935///
936/// The marks live in the proposal record keyed by slug
937/// ([`crate::ops::proposal::RecordedDisposition::landed_sections`]), and a
938/// rename moves the slug while leaving the contributor's bytes in place. The
939/// engine maintains the key rather than inferring the move from content at
940/// read time: content inference across slugs cannot tell a renamed body from
941/// an unrelated entity that happens to share a section, and a type whose
942/// load-bearing set is a single section (there are many) makes that
943/// collision a one-line coincidence a contributor can aim.
944///
945/// `Ok(false)` when the record holds no mark for `from`, in which case
946/// nothing is written and the commit is byte-identical.
947pub(crate) fn stage_proposal_marks_rename(
948 backend: &dyn crate::backend::MemBackend,
949 from: &EntityId,
950 to: &EntityId,
951) -> Result<bool, EngineError> {
952 let Some(bytes) = backend
953 .read_proposal_record()
954 .map_err(EngineError::Backend)?
955 else {
956 return Ok(false);
957 };
958 let Ok(record) = crate::ops::proposal::ProposalRecord::from_bytes(&bytes) else {
959 // A record this path cannot parse is left exactly as it is: the read
960 // path fails closed on it, which is the safe reading, and a rename is
961 // not the place to rewrite a file it does not understand.
962 return Ok(false);
963 };
964 let (record, moved) = move_marks_on_rename(record, from.path(), to.path());
965 if !moved {
966 return Ok(false);
967 }
968 backend
969 .write_entity(
970 std::path::Path::new(crate::ops::proposal::PROPOSAL_RECORD_PATH),
971 &record.to_bytes(),
972 )
973 .map_err(EngineError::Backend)?;
974 Ok(true)
975}
976
977/// Re-key one entity's marks for a retype's `section_map`: each mark whose
978/// content moved unchanged follows to its new key, recomputed under it, and a
979/// mark whose content the owner has since rewritten stays expired.
980///
981/// Built from an immutable snapshot rather than mutated in place. A
982/// `section_map` may swap (`{a: b, b: a}`) or chain (`{a: b, b: c}`) — retype
983/// refuses only collisions — and a loop that read its own writes would take
984/// the hash it just wrote for `b` as `b`'s original, drop the real one, and
985/// leave the contributor's content at the end of the chain unmarked.
986pub(crate) fn rekey_marks_for_retype(
987 before: &std::collections::BTreeMap<String, String>,
988 section_map: &indexmap::IndexMap<String, String>,
989 sections: &indexmap::IndexMap<String, String>,
990) -> std::collections::BTreeMap<String, String> {
991 let mut after = std::collections::BTreeMap::new();
992 for (key, hash) in before {
993 let target = section_map.get(key).unwrap_or(key);
994 let carried = sections.get(target).filter(|content| {
995 &crate::preparation::entity_section_prepared_hash(key, content) == hash
996 });
997 if let Some(content) = carried {
998 after.insert(
999 target.clone(),
1000 crate::preparation::entity_section_prepared_hash(target, content),
1001 );
1002 }
1003 }
1004 after
1005}
1006
1007/// Carry an adopted body's origin marks across a rewrite the ENGINE made to
1008/// its sections, staged into the same commit as that rewrite.
1009///
1010/// A rename retargets the wiki-links of every entity that pointed at the
1011/// renamed one, and a mem rename does the same workspace-wide. The engine
1012/// itself classifies that as a foreign-key change and not a semantic edit:
1013/// it deliberately leaves `last_modified` alone for exactly this reason. The
1014/// trust mark has to follow the same reasoning, because a mark is bytes and
1015/// the rewrite moves bytes. Unfollowed, ordinary owner housekeeping serves a
1016/// contributor's untouched sentences as the workspace's own, and a
1017/// contributor plants that for free by writing one wiki-link into the body
1018/// they propose.
1019///
1020/// Only a mark that still held over the PRE-rewrite content is carried,
1021/// recomputed over the post-rewrite content; a mark the owner had already
1022/// expired by rewriting the section stays expired. `Ok(false)` when nothing
1023/// moved, in which case nothing is written and the commit is byte-identical.
1024pub(crate) fn stage_proposal_marks_rehash(
1025 backend: &dyn crate::backend::MemBackend,
1026 id: &EntityId,
1027 before: &indexmap::IndexMap<String, String>,
1028 after: &indexmap::IndexMap<String, String>,
1029) -> Result<bool, EngineError> {
1030 let Some(bytes) = backend
1031 .read_proposal_record()
1032 .map_err(EngineError::Backend)?
1033 else {
1034 return Ok(false);
1035 };
1036 let Ok(mut record) = crate::ops::proposal::ProposalRecord::from_bytes(&bytes) else {
1037 return Ok(false);
1038 };
1039 if record.structural_defect().is_some() {
1040 // The reader calls this record defective and quarantines the whole
1041 // mem on it. A write that repaired it would lift a quarantine the
1042 // read installed on purpose, so every mark-following write refuses
1043 // it untouched.
1044 return Ok(false);
1045 }
1046 let mut changed = false;
1047 for proposal in &mut record.proposals {
1048 let Some(entry) = proposal.entities.get_mut(id.path()) else {
1049 continue;
1050 };
1051 let Some(marks) = entry.landed_sections.as_mut() else {
1052 continue;
1053 };
1054 for (key, hash) in marks.iter_mut() {
1055 let Some(was) = before.get(key) else { continue };
1056 let Some(now) = after.get(key) else { continue };
1057 if was == now {
1058 continue;
1059 }
1060 if &crate::preparation::entity_section_prepared_hash(key, was) != hash {
1061 continue;
1062 }
1063 *hash = crate::preparation::entity_section_prepared_hash(key, now);
1064 changed = true;
1065 }
1066 }
1067 if !changed {
1068 return Ok(false);
1069 }
1070 backend
1071 .write_entity(
1072 std::path::Path::new(crate::ops::proposal::PROPOSAL_RECORD_PATH),
1073 &record.to_bytes(),
1074 )
1075 .map_err(EngineError::Backend)?;
1076 Ok(true)
1077}
1078
1079/// Move one entity's origin marks from `from` to `to` inside a proposal
1080/// record, returning the record and whether anything changed.
1081///
1082/// Every rule this needs is the record's own
1083/// ([`crate::ops::proposal::ProposalRecord::effective_marks`],
1084/// `effective_marks_at`, `structural_defect`), which is the point: four review
1085/// rounds in a row found the same defect one position over while this function
1086/// kept its own copy of the read's flattening, modelling last-write-wins and
1087/// retirement by hand and getting one arm wrong each time.
1088///
1089/// What it does. A record the reader cannot make sense of is refused
1090/// untouched, the stance the unparseable case already takes: a rename that
1091/// repaired such a record would lift a quarantine the read installed on
1092/// purpose. Otherwise the marks effective for `from` move to `to`: cleared
1093/// wherever they stand at the source, and written onto the row that makes
1094/// `to`'s marks effective, or onto the last row naming `to`, so nothing later
1095/// in the record can retire them. Only when no row names `to` at all does the
1096/// source's own row relocate, and then the row that carried the effective
1097/// marks, never merely the first row naming the slug: relocating a `reject`'s
1098/// reason and content hash would move the re-proposal gate to a slug nothing
1099/// was ever rejected at.
1100///
1101/// Audit fields (disposition, reason, content hash) of an existing target row
1102/// are never touched: they document what happened to the entity that WAS at
1103/// that slug. Only the marks move, because only they describe the bytes that
1104/// are there now.
1105pub(crate) fn move_marks_on_rename(
1106 mut record: crate::ops::proposal::ProposalRecord,
1107 from: &str,
1108 to: &str,
1109) -> (crate::ops::proposal::ProposalRecord, bool) {
1110 if record.structural_defect().is_some() {
1111 return (record, false);
1112 }
1113 let before = (record.effective_marks(from), record.effective_marks(to));
1114 let Some(marks) = before.0.clone() else {
1115 // Nothing effective at the source: no label to move, and relocating a
1116 // mark-less row would make the record's slug keys depend on an
1117 // unrelated proposal's marks.
1118 return (record, false);
1119 };
1120 let source_row = record.effective_marks_at(from);
1121 let target_row = record.effective_marks_at(to).or_else(|| {
1122 record
1123 .proposals
1124 .iter()
1125 .rposition(|p| p.entities.contains_key(to))
1126 });
1127
1128 // The source no longer holds the body, so it no longer holds the label.
1129 for proposal in &mut record.proposals {
1130 if let Some(entry) = proposal.entities.get_mut(from) {
1131 entry.landed_sections = None;
1132 }
1133 }
1134 match target_row {
1135 Some(idx) => {
1136 if let Some(entry) = record.proposals[idx].entities.get_mut(to) {
1137 entry.landed_sections = Some(marks);
1138 }
1139 }
1140 None => {
1141 // No row names the target at all: relocate the source's own row,
1142 // audit fields and all, and only the row whose marks were the
1143 // effective ones.
1144 if let Some(idx) = source_row
1145 && let Some(mut entry) = record.proposals[idx].entities.remove(from)
1146 {
1147 entry.landed_sections = Some(marks);
1148 record.proposals[idx].entities.insert(to.to_string(), entry);
1149 }
1150 }
1151 }
1152 let after = (record.effective_marks(from), record.effective_marks(to));
1153 (record, after != before)
1154}
1155
1156/// Follow an adopted body's origin marks across a retype that re-keys
1157/// sections, staged into the same commit as the entity write.
1158///
1159/// A `section_map` moves a section's content to another key without
1160/// changing it, and a mark's hash covers its key, so an unfollowed mark
1161/// would stop matching and serve a contributor's untouched sentences as the
1162/// workspace's own prose. Only a mark whose content is still the bytes it
1163/// landed with is carried, recomputed under the new key; a mark whose
1164/// content the owner has since rewritten stays expired.
1165///
1166/// `sections` is the entity's post-retype section map. `Ok(false)` when
1167/// nothing was carried, in which case nothing is written.
1168pub(crate) fn stage_proposal_marks_retype(
1169 backend: &dyn crate::backend::MemBackend,
1170 id: &EntityId,
1171 section_map: &indexmap::IndexMap<String, String>,
1172 sections: &indexmap::IndexMap<String, String>,
1173) -> Result<bool, EngineError> {
1174 if section_map.is_empty() {
1175 return Ok(false);
1176 }
1177 let Some(bytes) = backend
1178 .read_proposal_record()
1179 .map_err(EngineError::Backend)?
1180 else {
1181 return Ok(false);
1182 };
1183 let Ok(mut record) = crate::ops::proposal::ProposalRecord::from_bytes(&bytes) else {
1184 return Ok(false);
1185 };
1186 if record.structural_defect().is_some() {
1187 // The reader calls this record defective and quarantines the whole
1188 // mem on it. A write that repaired it would lift a quarantine the
1189 // read installed on purpose, so every mark-following write refuses
1190 // it untouched.
1191 return Ok(false);
1192 }
1193 let mut rekeyed = false;
1194 for proposal in &mut record.proposals {
1195 let Some(entry) = proposal.entities.get_mut(id.path()) else {
1196 continue;
1197 };
1198 let Some(before) = entry.landed_sections.clone() else {
1199 continue;
1200 };
1201 let after = rekey_marks_for_retype(&before, section_map, sections);
1202 if after == before {
1203 continue;
1204 }
1205 if after.is_empty() {
1206 // Nothing held, so the mark is retired rather than written as an
1207 // empty map. An empty map is a record defect the read path fails
1208 // the whole mem closed on, and the engine's own retype must not
1209 // manufacture one: the owner rewriting every section and then
1210 // retyping is an ordinary sequence.
1211 entry.landed_sections = None;
1212 } else {
1213 entry.landed_sections = Some(after);
1214 }
1215 rekeyed = true;
1216 }
1217 if !rekeyed {
1218 return Ok(false);
1219 }
1220 backend
1221 .write_entity(
1222 std::path::Path::new(crate::ops::proposal::PROPOSAL_RECORD_PATH),
1223 &record.to_bytes(),
1224 )
1225 .map_err(EngineError::Backend)?;
1226 Ok(true)
1227}
1228
1229// A `today_iso()` wall-clock convenience used to live here, for tests
1230// comparing an auto-stamp against "roughly now". It is deliberately
1231// gone: the stamp is second-resolution, so every such comparison races
1232// the clock between the mutation and the assertion, and one of them
1233// duly failed on a suite run that straddled midnight. Tests that need
1234// a stamped value pin `Engine::set_mutation_clock` and derive the
1235// expected string from the same instant via [`iso_from_system_time`].
1236
1237/// An instant as a full ISO-8601 datetime string `YYYY-MM-DDTHH:MM:SSZ`
1238/// (UTC). Used by mutation paths that auto-stamp metadata fields
1239/// (e.g. `last_modified` on update, `created_date` on create).
1240///
1241/// This is second-resolution (rather than
1242/// date-only `YYYY-MM-DD`) so intra-day
1243/// updates produce distinguishable timestamps and drift / staleness
1244/// queries become per-update aware. The strict-mode date validator
1245/// already accepts both forms (`^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}Z)?$`)
1246/// so existing entities written with the date-only form continue to
1247/// load; new writes carry the wider form.
1248///
1249/// Pure function: no allocation outside the `format!` invocation,
1250/// no error path (the fallback to UNIX epoch on an instant before
1251/// the epoch is acceptable for a best-effort timestamp).
1252/// Howard-Hinnant civil-from-days for the date half; trivial modular
1253/// arithmetic for the time half.
1254/// The current wall-clock time as the second-granularity ISO form every
1255/// stamping path writes — for callers outside an engine (a CLI validating
1256/// input before boot). Engine code uses `Engine::now_iso`, which honours a
1257/// pinned test clock.
1258pub fn iso_now() -> String {
1259 iso_from_system_time(wall_clock_now())
1260}
1261
1262/// The wall clock as a `SystemTime`, on every target. `SystemTime::now()`
1263/// is unimplemented on `wasm32-unknown-unknown` — it traps with
1264/// `RuntimeError: unreachable` and poisons the instance — so the wasm
1265/// build derives the instant from the JS-backed clock instead
1266/// (`UNIX_EPOCH` plus the millisecond offset; `SystemTime` arithmetic is
1267/// implemented there, only `now()` is not). This is the engine's default
1268/// mutation clock and the one every unpinned stamping or adjudication
1269/// path reads; a health read that verifies anchors reaches it too, which
1270/// is how the wasm health surface came to trap once the stale axis
1271/// deferred to anchor state.
1272pub fn wall_clock_now() -> std::time::SystemTime {
1273 #[cfg(target_arch = "wasm32")]
1274 {
1275 std::time::UNIX_EPOCH + std::time::Duration::from_millis(js_sys::Date::now() as u64)
1276 }
1277 #[cfg(not(target_arch = "wasm32"))]
1278 {
1279 std::time::SystemTime::now()
1280 }
1281}
1282
1283pub(super) fn iso_from_system_time(t: std::time::SystemTime) -> String {
1284 let now = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
1285 let secs = now.as_secs();
1286 let days = secs / 86400;
1287 let secs_of_day = secs % 86400;
1288 let hh = secs_of_day / 3600;
1289 let mm = (secs_of_day % 3600) / 60;
1290 let ss = secs_of_day % 60;
1291 let z = days + 719468;
1292 let era = z / 146097;
1293 let doe = z - era * 146097;
1294 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
1295 let y = yoe + era * 400;
1296 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1297 let mp = (5 * doy + 2) / 153;
1298 let d = doy - (153 * mp + 2) / 5 + 1;
1299 let m = if mp < 10 { mp + 3 } else { mp - 9 };
1300 let y = if m <= 2 { y + 1 } else { y };
1301 format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
1302}
1303
1304/// Sweep stubs whose last incoming edge has just disappeared. Returns
1305/// the dropped ids so callers can surface them to the agent (e.g. via
1306/// [`DeleteEntityOutcome::orphan_stubs_removed`]).
1307///
1308/// Stubs are auto-created when a relate names an absent target — a
1309/// "promise" that a real entity will land there later (see
1310/// [`make_stub`]). When the last referrer drops its edge or is itself
1311/// deleted, the promise has no holder and becomes pure bloat. Only
1312/// stubs are eligible — real entities never count as orphans via this
1313/// path.
1314pub(super) fn gc_orphan_stubs(store: &mut Store) -> Vec<EntityId> {
1315 let stub_ids: Vec<EntityId> = store
1316 .all_entities()
1317 .filter(|e| e.stub)
1318 .map(|e| e.id.clone())
1319 .collect();
1320 gc_orphan_stubs_among(store, &stub_ids)
1321}
1322
1323/// Scoped orphan-stub sweep: GC only the stubs *among `candidates`*
1324/// whose last incoming edge has just disappeared, returning the dropped
1325/// ids. This is the single home of the orphan-stub predicate (`stub &&
1326/// no incoming`) — the three write paths that can sever a stub's last
1327/// referrer all funnel through here so they cannot drift:
1328/// [`gc_orphan_stubs`] (delete's full-store sweep) supplies every stub
1329/// id; the `memstead_relate(remove)` path supplies the just-severed target;
1330/// the `memstead_update` alias-resync path supplies the entity's
1331/// pre-mutation body-link targets (the only edges that commit could
1332/// have dropped). Scoping to a candidate set rather than walking the
1333/// whole store keeps each path from GC'ing pre-existing orphans that
1334/// aren't its responsibility. Candidates are de-duplicated; a candidate
1335/// that is absent, not a stub, or still has a referrer is left
1336/// untouched.
1337pub(super) fn gc_orphan_stubs_among<'a>(
1338 store: &mut Store,
1339 candidates: impl IntoIterator<Item = &'a EntityId>,
1340) -> Vec<EntityId> {
1341 let mut removed: Vec<EntityId> = Vec::new();
1342 let mut seen: std::collections::HashSet<&EntityId> = std::collections::HashSet::new();
1343 for id in candidates {
1344 if !seen.insert(id) {
1345 continue;
1346 }
1347 if store.get(id).is_some_and(|e| e.stub) && store.incoming(id).is_empty() {
1348 store.remove(id);
1349 removed.push(id.clone());
1350 }
1351 }
1352 removed
1353}
1354
1355/// Shared target-id grammar validator. The wiki-link grammar gate
1356/// runs on every relation-authoring path (`memstead_relate`,
1357/// `memstead_create.relations[]`, future inline-relation surfaces) so a
1358/// malformed target id (e.g. `bad@chars$here`) cannot land an
1359/// auto-stub at the literal id — that stub would later fail every
1360/// wiki-link parse that referenced it. A gate living only on
1361/// `memstead_relate` would let the create path admit the same input
1362/// silently.
1363pub(super) fn validate_relation_target_grammar(target: &EntityId) -> Result<(), EngineError> {
1364 if let Err(reason) = crate::entity::id::validate_mem_name_grammar(target.mem()) {
1365 return Err(EngineError::InvalidEntityId {
1366 id: target.to_string(),
1367 reason,
1368 });
1369 }
1370 if let Err(reason) = crate::entity::id::validate_id_path_grammar(target.path()) {
1371 return Err(EngineError::InvalidEntityId {
1372 id: target.to_string(),
1373 reason,
1374 });
1375 }
1376 Ok(())
1377}
1378
1379/// Auto-stamp `auto_timestamp` metadata fields on an entity that's
1380/// about to be re-written. Extracted from the update-path hot loop so
1381/// the relate-path (add and remove) and the rename-path (the renaming
1382/// entity plus every referrer the rewrite cascade touched) can
1383/// invoke the same engine-driven stamp.
1384///
1385/// Walks the type's metadata-field declarations; any field flagged
1386/// `auto_timestamp: true` (the default schema declares this on
1387/// `last_modified`) is set to the supplied `today` ISO string. The
1388/// helper is a no-op on schemas that declare no auto-timestamp
1389/// fields. Callers pre-compute `today` via [`today_iso`] so a single
1390/// mutation that touches multiple entities (rename's referrer rewrite
1391/// cascade) stamps them all with the same value.
1392pub(super) fn auto_stamp_timestamps(
1393 entity: &mut Entity,
1394 type_def: &memstead_schema::TypeDefinition,
1395 today: &str,
1396) {
1397 for field_def in &type_def.metadata_fields {
1398 if field_def.auto_timestamp {
1399 entity.metadata.insert(
1400 field_def.key.clone(),
1401 crate::entity::MetadataValue::String(today.to_string()),
1402 );
1403 }
1404 }
1405}
1406
1407/// Build a stub [`Entity`] for an unresolved relate target. Callers
1408/// declare the stub's origin via [`crate::entity::StubKind`] —
1409/// `ForwardReference` for `memstead_relate` to an absent target,
1410/// `Residual { since_commit, readonly_referrers }` for the
1411/// delete/rename demote path. The kind persists for the engine
1412/// instance's lifetime; a reload reduces every stub to `LoadTime`
1413/// — the kind is annotation, not state.
1414///
1415/// The stub is in-store but unwritten to disk — `entity_type` empty,
1416/// `file_path` empty, no metadata, no sections, `stub: true` and
1417/// `stub_kind: Some(kind)` set together. A later
1418/// [`Engine::create_entity`] at the same id promotes the stub to a
1419/// real entity (loader / parse-result merge handles the upgrade
1420/// path; `stub_kind` clears to `None`).
1421pub(super) fn make_stub(id: &EntityId, kind: crate::entity::StubKind) -> Entity {
1422 Entity {
1423 id: id.clone(),
1424 title: id.name().to_string(),
1425 entity_type: String::new(),
1426 mem: id.mem().to_string(),
1427 file_path: String::new(),
1428 metadata: IndexMap::new(),
1429 sections: IndexMap::new(),
1430 relationships: Vec::new(),
1431 content_hash: String::new(),
1432 stub: true,
1433 stub_kind: Some(kind),
1434 heading_spans: HashMap::new(),
1435 raw_section_headings: Vec::new(),
1436 }
1437}
1438
1439/// Cross-mem add-path policy gate. Same-mem writes bypass; the
1440/// `[cross_mem_links]` table only gates writes that cross the
1441/// mem boundary. Cross-mem writes consult
1442/// [`super::Engine::cross_mem_link_allowed`] in the edge's actual
1443/// direction (`source_mem → target_mem`). Disallowed pairings
1444/// surface [`EngineError::CrossMemLinkNotAllowed`] with the
1445/// `(from_mem, to_mem)` payload an agent already sees on
1446/// `memstead_relate`.
1447///
1448/// After the grant admits the pairing, a target absent from a
1449/// `MountCapability::ReadOnly` mount refuses with
1450/// [`EngineError::CrossMemTargetNotFound`]: the engine cannot
1451/// persist a stub through the read-only boundary, and a read-only
1452/// mem never gains the entity later — a missing target there is a
1453/// wrong link, not a pending forward reference. Same-mem targets,
1454/// cross-mem targets in Write mounts, and unmounted target mems all
1455/// retain the auto-stub mechanic.
1456///
1457/// Funnel point for every add-shaped edge write — `memstead_relate`,
1458/// `memstead_create.relations[]`, `memstead_update.declare_relations`,
1459/// body-wiki-link alias synthesis, and any future add-path mutation
1460/// surface route through one gate so the policy can't drift between
1461/// sites. Remove-shaped writes (cleanup) remain permissive and call
1462/// this helper not at all.
1463pub(super) fn validate_cross_mem_add_policy(
1464 engine: &super::Engine,
1465 source_mem: &str,
1466 target: &EntityId,
1467) -> Result<(), EngineError> {
1468 let target_mem = target.mem();
1469 if source_mem == target_mem {
1470 return Ok(());
1471 }
1472 if !engine.cross_mem_link_allowed(source_mem, target_mem) {
1473 return Err(EngineError::CrossMemLinkNotAllowed {
1474 from_mem: source_mem.to_string(),
1475 to_mem: target_mem.to_string(),
1476 });
1477 }
1478 // The target is checked against the engine's view of its mem. A
1479 // view that could not be reloaded under this write's lock is from
1480 // before the lock: the target may be gone or retyped since.
1481 if let Some(failure) = engine
1482 .mounts
1483 .iter()
1484 .find(|m| m.mount.mem == target_mem)
1485 .and_then(|m| m.reload_failure.as_ref())
1486 {
1487 return Err(failure.refusal(target_mem));
1488 }
1489 if let Some(mount) = engine.mount(target_mem)
1490 && mount.capability == crate::workspace::MountCapability::ReadOnly
1491 && !engine.store.contains(target)
1492 && !matches!(
1493 probe_deferred_target(engine, target)?,
1494 DeferredTargetProbe::Exists
1495 )
1496 {
1497 return Err(EngineError::CrossMemTargetNotFound {
1498 target_id: target.to_string(),
1499 target_mem: target_mem.to_string(),
1500 });
1501 }
1502 Ok(())
1503}
1504
1505/// Storage verdict for a cross-mem target whose mem is mounted but
1506/// DEFERRED (lazy, not yet loaded): the write-time cross-mem target
1507/// verification. The check asks the mem's real storage through the
1508/// cheap [`crate::backend::MemBackend::entity_exists`] probe
1509/// (tree-lookup-class on git-branch, metadata-class on folder) and
1510/// never triggers the mem's load: verification must not convert into
1511/// a full-load side effect.
1512pub(super) enum DeferredTargetProbe {
1513 /// The target's mem is loaded (the store is the truth) or not
1514 /// mounted at all (no storage handle to ask — the
1515 /// forward-reference mechanic governs).
1516 NotApplicable,
1517 /// Storage holds the entity: the reference is verified against
1518 /// real storage even though the mem is unloaded.
1519 Exists,
1520 /// Storage answers and the entity is not there.
1521 Absent,
1522}
1523
1524pub(super) fn probe_deferred_target(
1525 engine: &super::Engine,
1526 target: &EntityId,
1527) -> Result<DeferredTargetProbe, EngineError> {
1528 let rel_path = crate::entity::id::id_to_file_path(target);
1529 if engine.mem_is_deferred(target.mem()) {
1530 let Some(mounted) = engine.mounts.iter().find(|m| m.mount.mem == target.mem()) else {
1531 return Ok(DeferredTargetProbe::NotApplicable);
1532 };
1533 return Ok(
1534 if mounted
1535 .backend
1536 .entity_exists(std::path::Path::new(&rel_path))?
1537 {
1538 DeferredTargetProbe::Exists
1539 } else {
1540 DeferredTargetProbe::Absent
1541 },
1542 );
1543 }
1544 // UNMOUNTED mem: ask the workspace layer's discovery hook. No
1545 // hook, or no discoverable storage → NotApplicable (the
1546 // forward-reference mechanic governs, unchanged).
1547 if engine.mount(target.mem()).is_none()
1548 && let Some(prober) = &engine.unmounted_storage_prober
1549 && let Some(storage) = prober(target.mem())
1550 {
1551 return Ok(
1552 if storage
1553 .backend
1554 .entity_exists(std::path::Path::new(&rel_path))?
1555 {
1556 DeferredTargetProbe::Exists
1557 } else {
1558 DeferredTargetProbe::Absent
1559 },
1560 );
1561 }
1562 Ok(DeferredTargetProbe::NotApplicable)
1563}
1564
1565/// The one-blob type read for a storage-verified deferred target: the
1566/// shape check needs the target's real entity type, and a tree hit
1567/// proves existence, not type. Reads exactly the resolved path's
1568/// bytes and peeks the frontmatter `type:` — never the mem. Returns
1569/// `None` when the entity is absent or declares no type (the shape
1570/// gate then admits, the same posture the stub-bound case has
1571/// always had — the check never guesses).
1572/// The stub kind for a target being auto-stubbed on an add path: a
1573/// target that storage VERIFIES inside a deferred mem gets the
1574/// load-time kind — the stub is only the until-load
1575/// representation of a link into an unloaded mem, not a forward
1576/// reference to something that awaits creation. Everything else keeps
1577/// `ForwardReference`. Kinds stay annotation-not-state either way.
1578pub(super) fn deferred_verified_stub_kind(
1579 engine: &super::Engine,
1580 target: &EntityId,
1581) -> Result<crate::entity::StubKind, EngineError> {
1582 Ok(
1583 if matches!(
1584 probe_deferred_target(engine, target)?,
1585 DeferredTargetProbe::Exists
1586 ) {
1587 crate::entity::StubKind::LoadTime
1588 } else {
1589 crate::entity::StubKind::ForwardReference
1590 },
1591 )
1592}
1593
1594pub(super) fn peek_deferred_target_type(
1595 engine: &super::Engine,
1596 target: &EntityId,
1597) -> Result<Option<String>, EngineError> {
1598 let rel_path = crate::entity::id::id_to_file_path(target);
1599 let bytes = if engine.mem_is_deferred(target.mem()) {
1600 let Some(mounted) = engine.mounts.iter().find(|m| m.mount.mem == target.mem()) else {
1601 return Ok(None);
1602 };
1603 mounted
1604 .backend
1605 .read_entity(std::path::Path::new(&rel_path))?
1606 } else if engine.mount(target.mem()).is_none()
1607 && let Some(prober) = &engine.unmounted_storage_prober
1608 && let Some(storage) = prober(target.mem())
1609 {
1610 storage
1611 .backend
1612 .read_entity(std::path::Path::new(&rel_path))?
1613 } else {
1614 return Ok(None);
1615 };
1616 let Some(bytes) = bytes else {
1617 return Ok(None);
1618 };
1619 Ok(String::from_utf8(bytes)
1620 .ok()
1621 .and_then(|c| crate::entity::parser::peek_type_from_frontmatter(&c)))
1622}
1623
1624/// The target-schema REF for cross-schema edge routing. Loaded mems
1625/// answer from the engine's schema catalogue; an UNMOUNTED mem with
1626/// discoverable storage answers from its stored config's pin via the
1627/// discovery hook — the routing check
1628/// (`validate_cross_mem_edge`) needs only the ref, never the full
1629/// schema, so the source schema's `cross_mem_relationships:` entry
1630/// keeps its authority without a mount. `None` falls back to the
1631/// intra-mem path, exactly the pre-existing posture.
1632pub(super) fn target_schema_ref_for_routing(
1633 engine: &super::Engine,
1634 target_mem: &str,
1635) -> Option<memstead_schema::SchemaRef> {
1636 if let Some(s) = engine.schemas.get(target_mem) {
1637 let (name, version) = s.id();
1638 return Some(memstead_schema::SchemaRef::new(name, version));
1639 }
1640 if engine.mount(target_mem).is_none()
1641 && let Some(prober) = &engine.unmounted_storage_prober
1642 && let Some(storage) = prober(target_mem)
1643 {
1644 return storage.schema;
1645 }
1646 None
1647}
1648
1649/// Outcome of the engine's edge-validation router for a single
1650/// inline / explicit relate. Carries the optional open-mode warning
1651/// from the intra-mem flow; the cross-mem flow has no
1652/// open-mode (cross-mem entries are declared vocabulary).
1653pub(super) enum EdgeRouteOutcome {
1654 Ok,
1655 OpenModeWarning(Box<crate::ops::WarningHint>),
1656}
1657
1658/// Run rel-type + shape validation for one edge, routing through
1659/// intra-mem vocabulary or the source schema's
1660/// `cross_mem_relationships:` section as appropriate.
1661///
1662/// The routing rule:
1663/// when `source_mem != target_mem` AND the target mem's
1664/// pinned schema differs from the source schema by name or by
1665/// version, the source schema's `cross_mem_relationships:` entry
1666/// for the target schema is the sole authority for both the
1667/// vocabulary check (`INVALID_REL_TYPE`) and the shape check
1668/// (`INVALID_REL_SHAPE`). If no matching entry exists, surface
1669/// [`EngineError::CrossMemEdgeNotDeclared`].
1670///
1671/// Otherwise (same-mem, same-schema cross-mem, or target mem
1672/// unmounted) the call falls through to the existing intra-mem
1673/// validators — the same behaviour the intra-mem path always had.
1674///
1675/// `check_shape` mirrors the relate path's add-only shape posture:
1676/// pass `false` to skip the shape check (currently only the
1677/// `memstead_relate --remove` path). The vocabulary check still fires
1678/// in that case, matching the intra-mem behaviour where
1679/// `validate_rel_type` runs on both add and remove.
1680// The nine parameters are one edge's full coordinates; a params struct
1681// would restate the same fields at every call site without grouping
1682// anything that travels together elsewhere.
1683#[allow(clippy::too_many_arguments)]
1684pub(super) fn route_edge_validation(
1685 engine: &super::Engine,
1686 rel_type: &str,
1687 from_type: &str,
1688 to_type: Option<&str>,
1689 source_mem: &str,
1690 target_mem: &str,
1691 from_id: &EntityId,
1692 to_id: &EntityId,
1693 check_shape: bool,
1694) -> Result<EdgeRouteOutcome, EngineError> {
1695 use crate::runtime_validator::{
1696 CrossMemRelCheck, RelationshipCheck, validate_cross_mem_edge, validate_rel_shape,
1697 validate_rel_type,
1698 };
1699 use memstead_schema::SchemaRef;
1700
1701 let source_schema = engine
1702 .schemas
1703 .get(source_mem)
1704 .expect("schema present for every registered mount");
1705
1706 let target_schema_ref: Option<SchemaRef> = if source_mem == target_mem {
1707 None
1708 } else {
1709 target_schema_ref_for_routing(engine, target_mem)
1710 };
1711 let cross_mem_different = match (&target_schema_ref, source_schema.id()) {
1712 (Some(target), (src_name, _)) => target.name != src_name,
1713 (None, _) => false,
1714 };
1715
1716 if cross_mem_different {
1717 let target_ref = target_schema_ref
1718 .as_ref()
1719 .expect("target_schema_ref is Some when cross_mem_different");
1720 if !check_shape {
1721 // Cleanup posture: cross-mem remove stays permissive so
1722 // pre-tightening edges remain droppable without first
1723 // re-declaring them. Mirrors the intra-mem shape gate's
1724 // add-only stance.
1725 return Ok(EdgeRouteOutcome::Ok);
1726 }
1727 match validate_cross_mem_edge(
1728 rel_type,
1729 from_type,
1730 to_type,
1731 source_schema.as_ref(),
1732 target_ref,
1733 ) {
1734 CrossMemRelCheck::Ok => Ok(EdgeRouteOutcome::Ok),
1735 CrossMemRelCheck::EdgeNotDeclared => {
1736 let (src_name, src_version) = source_schema.id();
1737 Err(EngineError::CrossMemEdgeNotDeclared {
1738 source_schema: SchemaRef::new(src_name, src_version).as_display(),
1739 target_schema: target_ref.as_display(),
1740 rel_type: rel_type.to_string(),
1741 from_id: from_id.to_string(),
1742 to_id: to_id.to_string(),
1743 })
1744 }
1745 CrossMemRelCheck::Invalid(v) => Err(EngineError::Validation(v)),
1746 }
1747 } else {
1748 let warning_hint = match validate_rel_type(rel_type, source_schema.as_ref())? {
1749 RelationshipCheck::Ok => None,
1750 RelationshipCheck::OpenWarning(message) => {
1751 Some(crate::ops::WarningHint::UndeclaredRelationshipOpen {
1752 rel_type: rel_type.to_string(),
1753 message,
1754 })
1755 }
1756 };
1757 if check_shape {
1758 validate_rel_shape(rel_type, from_type, to_type, source_schema.as_ref())?;
1759 }
1760 Ok(match warning_hint {
1761 Some(w) => EdgeRouteOutcome::OpenModeWarning(Box::new(w)),
1762 None => EdgeRouteOutcome::Ok,
1763 })
1764 }
1765}
1766
1767/// Cycle-family gate for one prospective edge — the single owner of
1768/// both refusals, shared by every edge-writing verb (`memstead_relate`,
1769/// `memstead_create.relations[]`, `memstead_update.declare_relations`, and the
1770/// batch paths, which stage prior items' edges into `store` so an
1771/// intra-batch cycle refuses like a stored one):
1772///
1773/// - **Self-loop on a listed no-self-loop rel-type.** `from == to` on
1774/// any rel-type the source type lists in `no_self_loop_relationships`
1775/// refuses, regardless of the `acyclic` flag — the declaration's one
1776/// effect (see `TypeDefinition::no_self_loop_relationships`).
1777/// - **Cycle on an acyclic rel-type.** An add closing a back-path
1778/// `to → … → from` (via [`crate::graph::query::would_cycle`]) refuses
1779/// with the existing path, capped at [`RELATIONSHIP_CYCLE_PATH_CAP`].
1780/// - **Cycle in a declared acyclicity set.** When the rel-type belongs
1781/// to a `relationships.acyclic_sets` set, an add closing a back-path
1782/// in the set's UNION subgraph (via
1783/// [`crate::graph::query::would_cycle_in_set`]) refuses; the payload
1784/// additionally echoes the set and the path's per-hop rel-types.
1785///
1786/// All refuse [`EngineError::RelationshipCycle`] (`RELATIONSHIP_CYCLE`)
1787/// with identical recovery detail on every path. Callers skip this on
1788/// remove paths — removal can only break cycles, never close one.
1789pub(super) fn validate_edge_acyclicity(
1790 store: &Store,
1791 schema: &memstead_schema::Schema,
1792 from: &EntityId,
1793 from_type: &str,
1794 to: &EntityId,
1795 rel_type: &str,
1796) -> Result<(), EngineError> {
1797 if from == to && schema.type_refuses_self_loop(from_type, rel_type) {
1798 return Err(EngineError::RelationshipCycle {
1799 rel_type: rel_type.to_string(),
1800 from: from.clone(),
1801 to: to.clone(),
1802 existing_path: vec![from.clone()],
1803 path_truncated: false,
1804 acyclic_set: None,
1805 existing_path_rel_types: None,
1806 });
1807 }
1808 if schema.relationship_acyclic(rel_type)
1809 && let Some(path) = crate::graph::query::would_cycle(store, from, to, rel_type)
1810 {
1811 let truncated = path.len() > RELATIONSHIP_CYCLE_PATH_CAP;
1812 let mut existing_path = path;
1813 if truncated {
1814 existing_path.truncate(RELATIONSHIP_CYCLE_PATH_CAP);
1815 }
1816 return Err(EngineError::RelationshipCycle {
1817 rel_type: rel_type.to_string(),
1818 from: from.clone(),
1819 to: to.clone(),
1820 existing_path,
1821 path_truncated: truncated,
1822 acyclic_set: None,
1823 existing_path_rel_types: None,
1824 });
1825 }
1826 // Cycle in a declared acyclicity SET: the union subgraph of the
1827 // set must stay acyclic, so the back-path may mix rel-types. The
1828 // refusal is additive — it echoes the declared set and one
1829 // rel-type per hop of the path.
1830 if let Some(set) = schema.acyclic_set_containing(rel_type)
1831 && let Some((path, path_rels)) =
1832 crate::graph::query::would_cycle_in_set(store, from, to, set)
1833 {
1834 let truncated = path.len() > RELATIONSHIP_CYCLE_PATH_CAP;
1835 let mut existing_path = path;
1836 let mut existing_path_rel_types = path_rels;
1837 if truncated {
1838 existing_path.truncate(RELATIONSHIP_CYCLE_PATH_CAP);
1839 existing_path_rel_types.truncate(existing_path.len().saturating_sub(1));
1840 }
1841 return Err(EngineError::RelationshipCycle {
1842 rel_type: rel_type.to_string(),
1843 from: from.clone(),
1844 to: to.clone(),
1845 existing_path,
1846 path_truncated: truncated,
1847 acyclic_set: Some(set.to_vec()),
1848 existing_path_rel_types: Some(existing_path_rel_types),
1849 });
1850 }
1851 Ok(())
1852}
1853
1854/// Validate the per-edge description posture declared on the rel-type
1855/// in the routing-appropriate definition (intra-mem when source and
1856/// target share the schema; cross-mem entry when they don't). Emits
1857/// `MissingRequiredDescription` / `DescriptionNotPermitted` on
1858/// violations; `optional` and unknown rel-types are no-ops (the
1859/// vocabulary / shape gates already catch undeclared names — posture
1860/// only fires for declared names).
1861///
1862/// `description` is the normalised value (empty / whitespace-only
1863/// collapses to `None` before reaching this gate). Called from every
1864/// add path: `memstead_relate`, `declare_relations` on `memstead_create` and
1865/// `memstead_update`.
1866pub(super) fn validate_description_posture(
1867 engine: &super::Engine,
1868 rel_type: &str,
1869 description: Option<&str>,
1870 source_mem: &str,
1871 target_mem: &str,
1872 from_id: &EntityId,
1873 to_id: &EntityId,
1874) -> Result<(), EngineError> {
1875 use memstead_schema::{PerEdgeDescription, SchemaRef};
1876
1877 let source_schema = engine
1878 .schemas
1879 .get(source_mem)
1880 .expect("schema present for every registered mount");
1881 let target_schema_ref: Option<SchemaRef> = if source_mem == target_mem {
1882 None
1883 } else {
1884 target_schema_ref_for_routing(engine, target_mem)
1885 };
1886 let cross_mem_different = match (&target_schema_ref, source_schema.id()) {
1887 (Some(target), (src_name, _)) => target.name != src_name,
1888 (None, _) => false,
1889 };
1890
1891 let posture = if cross_mem_different {
1892 // Look up the matching cross-mem entry's definition. If the
1893 // entry exists but the rel-type isn't enumerated under it, the
1894 // vocabulary gate (route_edge_validation) will surface
1895 // `CROSS_MEM_EDGE_NOT_DECLARED`; posture is a no-op there.
1896 let target_ref = target_schema_ref
1897 .as_ref()
1898 .expect("target_schema_ref is Some when cross_mem_different");
1899 source_schema
1900 .cross_mem_entries(&target_ref.name)
1901 .iter()
1902 .find_map(|entry| entry.definitions.iter().find(|d| d.name == rel_type))
1903 .map(|d| d.per_edge_description)
1904 } else {
1905 source_schema
1906 .relationship_def(rel_type)
1907 .map(|d| d.per_edge_description)
1908 };
1909
1910 match posture {
1911 Some(PerEdgeDescription::Required) if description.is_none() => {
1912 Err(EngineError::MissingRequiredDescription {
1913 rel_type: rel_type.to_string(),
1914 from_id: from_id.to_string(),
1915 to_id: to_id.to_string(),
1916 })
1917 }
1918 Some(PerEdgeDescription::Forbidden) if description.is_some() => {
1919 Err(EngineError::DescriptionNotPermitted {
1920 rel_type: rel_type.to_string(),
1921 from_id: from_id.to_string(),
1922 to_id: to_id.to_string(),
1923 })
1924 }
1925 _ => Ok(()),
1926 }
1927}
1928
1929/// Validate the manual-authoring posture declared on the rel-type.
1930/// Fires only on explicit-author paths (`memstead_relate`, inline
1931/// `relations:` on `memstead_create`, `declare_relations` on
1932/// `memstead_update`). The body-link → relation alias machinery
1933/// synthesises relations from wiki-links — that path bypasses this
1934/// gate by construction (it never calls this function), keeping the
1935/// alias path for `manual_authoring: forbidden` rel-types (e.g.
1936/// REFERENCES) intact.
1937pub(super) fn validate_manual_authoring_posture(
1938 engine: &super::Engine,
1939 rel_type: &str,
1940 source_mem: &str,
1941 from_id: &EntityId,
1942 to_id: &EntityId,
1943) -> Result<(), EngineError> {
1944 use memstead_schema::ManualAuthoring;
1945
1946 let source_schema = engine
1947 .schemas
1948 .get(source_mem)
1949 .expect("schema present for every registered mount");
1950 let posture = source_schema.relationship_manual_authoring(rel_type);
1951 if matches!(posture, ManualAuthoring::Forbidden) {
1952 let guidance = source_schema
1953 .relationship_when_to_use(rel_type)
1954 .unwrap_or_default();
1955 return Err(EngineError::RelationManualAuthoringForbidden {
1956 rel_type: rel_type.to_string(),
1957 from_id: from_id.to_string(),
1958 to_id: to_id.to_string(),
1959 guidance,
1960 });
1961 }
1962 Ok(())
1963}
1964
1965/// Alias-synthesis pass — populates `next.relationships` with engine-
1966/// emitted relations of the source schema's `alias_target_rel_type`
1967/// pointer for every body wiki-link not already backed by an
1968/// in-section-body explicit relation. Runs before the
1969/// `scan_wikilinks_without_relation` validator; after this pass the
1970/// validator finds zero missing wiki-links for the pointer rel-type.
1971///
1972/// Three cases:
1973/// 1. Schema has no pointer (`alias_target_rel_type` absent): no-op.
1974/// Caller's validator continues to refuse unbacked links exactly as
1975/// today.
1976/// 2. Schema has a pointer, body wiki-link target is in the same mem
1977/// OR cross-mem policy admits it: append `Relationship { rel_type:
1978/// pointer, target, description: None }` to `next.relationships` if
1979/// no relation of `(pointer, target)` is already present. Dedupe is
1980/// `(target, rel_type)` — a USES or DEPENDS_ON edge to the same
1981/// target does not suppress synthesis of the pointer rel-type.
1982/// 3. Schema has a pointer but a body wiki-link crosses a mem
1983/// boundary the workspace doesn't grant — or targets an entity
1984/// absent from a read-only mount: return the funnel's typed
1985/// refusal ([`EngineError::CrossMemLinkNotAllowed`] /
1986/// [`EngineError::CrossMemTargetNotFound`], via
1987/// [`validate_cross_mem_add_policy`]). The entire mutation
1988/// aborts — no partial state.
1989///
1990/// GC: when `prev` is `Some`, the pass also drops pointer-rel-type
1991/// relations whose target was a body wiki-link in `prev` but no longer
1992/// appears in `next.sections`. The loader forces `manual_authoring:
1993/// forbidden` on every schema's `alias_target_rel_type` pointer, so the
1994/// only path to a pointer-rel-type edge is the body-link channel; the
1995/// GC rule therefore reduces to "drop pointer-rel-type relations whose
1996/// target is not in the new body". Targeting prev's wiki-link set
1997/// specifically (rather than every pointer-rel-type relation) keeps the
1998/// pass correct even for an explicit-author relation that predates the
1999/// forbid posture.
2000///
2001/// Returns the list of relations the pass emitted (in body iteration
2002/// order) — `create.rs` / `update.rs` use it to surface
2003/// `relations_emitted` on the response envelope.
2004/// Returns the synthesised relations (in body iteration order) and a flag
2005/// signalling whether a body wiki-link to the entity's own id was dropped.
2006/// The caller surfaces that as a `SELF_LINK_IGNORED` warning — the
2007/// pass has no warning channel of its own.
2008pub(super) fn synthesise_alias_relations(
2009 engine: &super::Engine,
2010 prev_body_targets: &std::collections::HashSet<EntityId>,
2011 next: &mut Entity,
2012) -> Result<AliasSynthesisOutcome, super::EngineError> {
2013 let schema = engine
2014 .schemas
2015 .get(next.mem.as_str())
2016 .expect("schema present for every registered mount");
2017 let Some(pointer) = schema.alias_target_rel_type().map(str::to_string) else {
2018 return Ok(AliasSynthesisOutcome::default());
2019 };
2020
2021 // 1. GC: drop pointer-rel-type relations whose target was a body
2022 // wiki-link in the prev entity state but isn't in next. Targets
2023 // not in prev's wiki-link set are explicit-author relations and
2024 // are never touched — the rule preserves explicit edges even
2025 // while the 5 built-ins still admit explicit REFERENCES.
2026 //
2027 // `extract_inline_links` is strict — non-slug-form targets refuse
2028 // here with the typed `InvalidWikiLinkTarget` envelope rather
2029 // than silently flowing into the GC's retain set as malformed
2030 // EntityIds. Section context comes from the iteration key.
2031 let mut next_targets: std::collections::HashSet<EntityId> = std::collections::HashSet::new();
2032 for (section_key, body) in next.sections.iter() {
2033 let ids = crate::entity::parser::extract_inline_links(body, &next.mem)
2034 .map_err(|errs| map_wiki_link_errors(section_key, errs))?;
2035 next_targets.extend(ids);
2036 }
2037 next.relationships.retain(|r| {
2038 !(r.rel_type == pointer
2039 && prev_body_targets.contains(&r.target)
2040 && !next_targets.contains(&r.target))
2041 });
2042
2043 // 2. Walk body wiki-links in section iteration order and append
2044 // one relation per `(target, pointer)` pair not already
2045 // present. Cross-mem gate fires on the first refusal.
2046 let existing: std::collections::HashSet<(String, EntityId)> = next
2047 .relationships
2048 .iter()
2049 .map(|r| (r.rel_type.clone(), r.target.clone()))
2050 .collect();
2051 let mut emitted: Vec<crate::entity::Relationship> = Vec::new();
2052 let mut already_synthesised: std::collections::HashSet<EntityId> =
2053 std::collections::HashSet::new();
2054 let mut self_link_ignored = false;
2055 let mut undeclared_dropped: Vec<UndeclaredCrossSchemaLink> = Vec::new();
2056 let mut undeclared_seen: std::collections::HashSet<EntityId> = std::collections::HashSet::new();
2057 for (section_key, body) in next.sections.iter() {
2058 let ids = crate::entity::parser::extract_inline_links(body, &next.mem)
2059 .map_err(|errs| map_wiki_link_errors(section_key, errs))?;
2060 for target in ids {
2061 // A body wiki-link to the entity's own id is a vacuous
2062 // self-edge (renders as both Outgoing and Incoming, inflates
2063 // connectivity). Drop it — but don't refuse: the author may
2064 // have written their own slug. The caller surfaces
2065 // `SELF_LINK_IGNORED` so the dropped link stays observable.
2066 if target == next.id {
2067 self_link_ignored = true;
2068 continue;
2069 }
2070 let key = (pointer.clone(), target.clone());
2071 if existing.contains(&key) || already_synthesised.contains(&target) {
2072 continue;
2073 }
2074 validate_cross_mem_add_policy(engine, &next.mem, &target)?;
2075 // Schema-law gate: a link into a DIFFERENT schema is an edge
2076 // only where the source schema's cross_mem_relationships
2077 // declare the pointer rel-type for that destination (exact
2078 // entry or wildcard). Emitting anyway wrote an edge the
2079 // load-path filter then silently discarded on the next boot
2080 // — the write showed a relation the graph would not keep.
2081 // Skip synthesis and
2082 // record the drop; the caller warns, typed, so the author
2083 // learns the citation is prose only. An unmounted or
2084 // schema-less target stays permissive (nothing to judge).
2085 if target.mem() != next.mem
2086 && let Some(target_ref) = target_schema_ref_for_routing(engine, target.mem())
2087 && target_ref.name != schema.id().0
2088 && !schema
2089 .cross_mem_entries(&target_ref.name)
2090 .iter()
2091 .any(|entry| entry.definitions.iter().any(|d| d.name == pointer))
2092 {
2093 if undeclared_seen.insert(target.clone()) {
2094 let (src_name, src_version) = schema.id();
2095 undeclared_dropped.push(UndeclaredCrossSchemaLink {
2096 target,
2097 source_schema: memstead_schema::SchemaRef::new(src_name, src_version)
2098 .as_display(),
2099 target_schema: target_ref.name,
2100 });
2101 }
2102 continue;
2103 }
2104 // The pointer edge is an edge like any other: it passes the
2105 // gates a declared edge passes, the shape and the cycle law,
2106 // so a wiki-link the graph would not keep refuses here rather
2107 // than landing and being dropped by the next load.
2108 let target_type = match engine
2109 .store
2110 .get(&target)
2111 .map(|e| e.entity_type.clone())
2112 .filter(|t| !t.is_empty())
2113 {
2114 Some(t) => Some(t),
2115 None => peek_deferred_target_type(engine, &target)?,
2116 };
2117 // An open-mode vocabulary note is already the pointer's own:
2118 // the pointer is declared, so only a shape miss can refuse.
2119 let _ = route_edge_validation(
2120 engine,
2121 &pointer,
2122 next.entity_type.as_str(),
2123 target_type.as_deref(),
2124 &next.mem,
2125 target.mem(),
2126 &next.id,
2127 &target,
2128 /* check_shape = */ true,
2129 )?;
2130 validate_edge_acyclicity(
2131 &engine.store,
2132 schema.as_ref(),
2133 &next.id,
2134 next.entity_type.as_str(),
2135 &target,
2136 &pointer,
2137 )?;
2138 let rel = crate::entity::Relationship::new(pointer.clone(), target.clone());
2139 next.relationships.push(rel.clone());
2140 already_synthesised.insert(target);
2141 emitted.push(rel);
2142 }
2143 }
2144 Ok(AliasSynthesisOutcome {
2145 emitted,
2146 self_link_ignored,
2147 undeclared_dropped,
2148 })
2149}
2150
2151/// One body wiki-link the alias pass declined to turn into an edge
2152/// because the source schema declares no cross-mem entry carrying the
2153/// pointer rel-type for the target's schema. The caller surfaces each
2154/// as a `CROSS_SCHEMA_LINK_UNDECLARED` warning.
2155pub(super) struct UndeclaredCrossSchemaLink {
2156 pub target: EntityId,
2157 pub source_schema: String,
2158 pub target_schema: String,
2159}
2160
2161/// What [`synthesise_alias_relations`] did: the relations it emitted
2162/// (in body iteration order), whether a self-link was dropped,
2163/// and the cross-schema links it declined for lack of a declaration.
2164#[derive(Default)]
2165pub(super) struct AliasSynthesisOutcome {
2166 pub emitted: Vec<crate::entity::Relationship>,
2167 pub self_link_ignored: bool,
2168 pub undeclared_dropped: Vec<UndeclaredCrossSchemaLink>,
2169}
2170
2171/// Map the first [`crate::entity::id::WikiLinkError`] from a body
2172/// wiki-link extraction into the typed [`EngineError`] envelope,
2173/// attaching the offending section's key. Errors after the first are
2174/// dropped — the agent reads the error, fixes the link, retries, and
2175/// surfaces the next one on the follow-up call. Keeps the envelope
2176/// shape stable (single typed payload rather than a list) so MCP /
2177/// CLI clients don't need a fan-out renderer.
2178pub(super) fn map_wiki_link_errors(
2179 section_key: &str,
2180 errors: Vec<crate::entity::id::WikiLinkError>,
2181) -> EngineError {
2182 use crate::entity::id::WikiLinkError;
2183 let first = errors
2184 .into_iter()
2185 .next()
2186 .expect("map_wiki_link_errors called with non-empty error list");
2187 match first {
2188 WikiLinkError::InvalidTarget {
2189 raw,
2190 suggested,
2191 reason,
2192 } => EngineError::InvalidWikiLinkTarget {
2193 raw,
2194 suggested,
2195 section: section_key.to_string(),
2196 link_source: "body_link".to_string(),
2197 reason,
2198 },
2199 WikiLinkError::InvalidMemName { raw, reason } => EngineError::InvalidWikiLinkMem {
2200 raw,
2201 section: section_key.to_string(),
2202 reason,
2203 },
2204 }
2205}
2206
2207/// Compute the set of body wiki-link targets in an entity. Used by
2208/// callers of `synthesise_alias_relations` to capture the pre-mutation
2209/// state once, before any borrow conflicts re-enter the engine's
2210/// schemas / store maps. Uses the lenient decoder — this snapshot
2211/// must tolerate on-disk drift on pre-strict entities whose bodies
2212/// may still contain non-conformant links; the strict gate fires
2213/// only on the post-mutation `next` state.
2214pub(super) fn collect_body_link_targets(entity: &Entity) -> std::collections::HashSet<EntityId> {
2215 entity
2216 .sections
2217 .iter()
2218 .flat_map(|(_, body)| {
2219 crate::entity::parser::extract_inline_links_lenient(body, &entity.mem)
2220 })
2221 .collect()
2222}
2223
2224/// Alias-existence invariant validator. Given the post-mutation entity
2225/// state, scan every section body for wiki-links whose target has no
2226/// corresponding explicit relation in `entity.relationships`. Returns
2227/// the list of `(section_key, target_id)` pairs that violate the
2228/// invariant — empty when the post-mutation state is clean.
2229///
2230/// Used by [`Engine::create_entity`] and [`Engine::update_entity`]
2231/// (and `batch_update`). The validator runs unconditionally — under
2232/// the alias model body wiki-links are foreign-key references on the
2233/// `## Relationships` table and every reference must be backed.
2234///
2235/// Sections from the auto-managed `## Relationships` heading are
2236/// not scanned (the engine generates them from the relations list
2237/// at write time; the parser keeps them out of
2238/// `entity.sections` so they never reach this function).
2239///
2240/// Reuses [`crate::entity::parser::extract_inline_links`] so the
2241/// lexical discipline (fenced-code masking, inline-code masking,
2242/// alias handling, cross-mem forms) matches every other validator
2243/// surface in the engine.
2244pub(super) fn scan_wikilinks_without_relation(
2245 next: &Entity,
2246 exempt: &std::collections::HashSet<EntityId>,
2247) -> Result<Vec<(String, EntityId)>, EngineError> {
2248 let explicit_targets: std::collections::HashSet<EntityId> = next
2249 .relationships
2250 .iter()
2251 .map(|r| r.target.clone())
2252 .collect();
2253 let mut missing: Vec<(String, EntityId)> = Vec::new();
2254 for (section_key, body) in next.sections.iter() {
2255 let ids = crate::entity::parser::extract_inline_links(body, &next.mem)
2256 .map_err(|errs| map_wiki_link_errors(section_key, errs))?;
2257 for target in ids {
2258 // A self-targeting body link is intentionally unbacked: the
2259 // alias pass drops its (vacuous) self-edge, so it has no
2260 // backing relation by design and must not trip the
2261 // unbacked-link refusal here.
2262 if target == next.id {
2263 continue;
2264 }
2265 // A cross-schema link the alias pass declined for lack of a
2266 // declaration is likewise intentionally unbacked: the caller
2267 // warns (`CROSS_SCHEMA_LINK_UNDECLARED`) instead of the write
2268 // refusing over prose the schema deliberately keeps inert.
2269 if exempt.contains(&target) {
2270 continue;
2271 }
2272 if !explicit_targets.contains(&target)
2273 && !missing
2274 .iter()
2275 .any(|(k, t)| k == section_key && t == &target)
2276 {
2277 missing.push((section_key.clone(), target));
2278 }
2279 }
2280 }
2281 Ok(missing)
2282}
2283
2284#[cfg(test)]
2285mod tests;