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