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 mod create;
20pub mod delete;
21pub mod mem_sweep;
22pub mod parse_recovery;
23pub mod relate;
24pub mod rename;
25pub mod update;
26
27/// Look up an entity's `(title, entity_type)` pair in `store`. Both
28/// `None` for missing-from-store ids — matches full's `title_for` /
29/// `type_for` lossy-lookup contract. Used by [`Engine::changes_since`]
30/// to enrich id-only envelopes the backend returned with metadata
31/// from the in-memory store.
32pub(super) fn lookup_title_and_type(
33 store: &Store,
34 id: &EntityId,
35) -> (Option<String>, Option<String>) {
36 match store.get(id) {
37 Some(e) => (Some(e.title.clone()), Some(e.entity_type.clone())),
38 None => (None, None),
39 }
40}
41
42/// Maximum byte length of the truncated `current_content` snapshot
43/// that [`EngineError::PatchOldNotFound`] carries. Keeps the wire
44/// envelope bounded for sections with large bodies. Mirrors full's
45/// `memstead_git_branch::PATCH_OLD_NOT_FOUND_CONTENT_CAP`.
46pub const PATCH_OLD_NOT_FOUND_CONTENT_CAP: usize = 500;
47
48/// Maximum number of entity IDs retained in
49/// [`EngineError::RelationshipCycle::existing_path`]. Keeps the cycle
50/// envelope bounded for pathologically long chains. Mirrors full's
51/// `memstead_git_branch::RELATIONSHIP_CYCLE_PATH_CAP`.
52pub const RELATIONSHIP_CYCLE_PATH_CAP: usize = 20;
53
54/// Build an [`EngineError::UnknownType`] populated with the schema's
55/// declared type names (sorted) and a fuzzy suggestion. Mirrors full's
56/// `UnknownEntityType` recovery payload so MCP envelopes carry the
57/// same `name` / `schema_ref` / `declared` / `suggestion` keys
58/// regardless of which engine served the call.
59pub(crate) fn unknown_type_error(schema: &memstead_schema::Schema, attempted: &str) -> EngineError {
60 let mut declared: Vec<String> = schema.types.keys().cloned().collect();
61 declared.sort();
62 let (sname, sver) = schema.id();
63 EngineError::UnknownType {
64 name: attempted.to_string(),
65 schema_ref: format!("{sname}@{sver}"),
66 declared,
67 suggestion: schema.suggest_type(attempted),
68 }
69}
70
71/// The lowercase wire string for a [`crate::pipeline::MediumType`] — the
72/// value the `INVALID_ANCHOR` recovery detail carries so an agent sees
73/// which medium's namespace rejected the grain. Matches the enum's
74/// `#[serde(rename_all = "lowercase")]` form.
75pub(crate) fn medium_type_wire(t: crate::pipeline::MediumType) -> &'static str {
76 use crate::pipeline::MediumType::*;
77 match t {
78 Codebase => "codebase",
79 Filesystem => "filesystem",
80 Graph => "graph",
81 Git => "git",
82 Web => "web",
83 }
84}
85
86impl super::Engine {
87 /// Resolve the single-source anchor-namespace context for `mem`, when
88 /// unambiguous. An `anchors[]` element carries no source name, so the
89 /// grain/namespace refusal ([`crate::anchor::AnchorValidationError::GrainNamespaceUnsupported`])
90 /// can only be fired deterministically when the mem's bindings declare
91 /// exactly one inline source; with zero or several the namespace check
92 /// is skipped (the vocabulary + hash-semantics rules still apply).
93 /// Returns the `(medium_type_wire, anchor_namespace)` pair the
94 /// validator consumes — the medium *half* of the lone source.
95 pub(crate) fn resolve_anchor_medium(&self, mem: &str) -> Option<(String, &'static str)> {
96 let mut sources = self
97 .pipeline_configs()
98 .bindings
99 .iter()
100 .filter(|r| r.mem == mem)
101 .flat_map(|r| r.config.sources.iter());
102 let first = sources.next()?;
103 if sources.next().is_some() {
104 // Ambiguous — the anchor does not name which source it targets;
105 // skip the namespace refinement rather than guess.
106 return None;
107 }
108 let caps = crate::binding::medium_capabilities(first.medium_type);
109 Some((
110 medium_type_wire(first.medium_type).to_string(),
111 caps.anchor_namespace,
112 ))
113 }
114
115 /// Validate the permissive `anchors[]` inputs for a mutation against
116 /// `mem`'s medium context into strict [`crate::anchor::Anchor`]s, or
117 /// refuse the whole mutation with a typed
118 /// [`EngineError::InvalidAnchor`]. Empty input yields an empty vec (no
119 /// sidecar write); a single malformed element aborts before any state
120 /// change so the entity is never written.
121 pub(crate) fn validate_anchor_inputs(
122 &self,
123 mem: &str,
124 inputs: &[crate::anchor::AnchorInput],
125 ) -> Result<Vec<crate::anchor::Anchor>, EngineError> {
126 if inputs.is_empty() {
127 return Ok(Vec::new());
128 }
129 let medium = self.resolve_anchor_medium(mem);
130 let medium_ref = medium.as_ref().map(|(t, ns)| (t.as_str(), *ns));
131 let anchors: Vec<crate::anchor::Anchor> = inputs
132 .iter()
133 .map(|i| i.validate(medium_ref).map_err(EngineError::from))
134 .collect::<Result<_, _>>()?;
135
136 // Source-vs-binding check: when an anchor names BOTH a producing
137 // binding and a source, and that binding hash still resolves in
138 // this workspace (reverse lookup — any later binding edit moves
139 // the hash and drops earlier anchors into the accept-any-name
140 // branch for good), the source must be one of the binding's
141 // declared names. The bindings load is skipped entirely unless
142 // some input needs it, and a missing workspace root or an
143 // unloadable store degrades to accept-any-name — validation
144 // must never require the binding to resolve.
145 if anchors
146 .iter()
147 .any(|a| a.binding.is_some() && a.source.is_some())
148 && let Some(root) = self.workspace_root()
149 && let Ok(configs) = crate::pipeline_store::load_pipeline_configs(root)
150 {
151 for a in &anchors {
152 let (Some(binding_hash), Some(source)) = (&a.binding, &a.source) else {
153 continue;
154 };
155 let Some(record) = configs
156 .bindings
157 .iter()
158 .find(|r| crate::binding::hash_binding(&r.config) == *binding_hash)
159 else {
160 continue; // unresolvable binding: accept any non-empty name
161 };
162 let declared: Vec<String> = record
163 .config
164 .sources
165 .iter()
166 .map(|s| s.name.clone())
167 .collect();
168 if !declared.iter().any(|n| n == source) {
169 return Err(EngineError::from(
170 crate::anchor::AnchorValidationError::SourceNotDeclared {
171 got: source.clone(),
172 declared,
173 },
174 ));
175 }
176 }
177 }
178
179 // Write time resolves or refuses (decision 26, plan 03a): a
180 // path-grain anchor whose artifact resolves under NO candidate join
181 // is a silently dead reference — refuse now, while the write moment
182 // still has the binding context to say what the right dialect is.
183 // Candidates in decision-29 priority: the source-join (the anchor's
184 // `source` name resolved to its declared pointer) first, then the
185 // workspace-relative form. An anchor naming a source the LOADED
186 // roster does not declare (a typo, a renamed binding) gets no join
187 // candidate — its workspace-relative form must resolve or the write
188 // refuses, because resolution will make the same roster lookup and
189 // orphan it at birth. The gate skips entirely only when it cannot
190 // know: no workspace root, or a pipeline store whose LOAD fails as a
191 // whole — validation never requires the binding store to be
192 // readable. (A corrupted individual binding file does not fail the
193 // load; it yields a reduced roster, and the gate then fail-closes on
194 // paths that resolve under no surviving candidate.)
195 if let Some(root) = self.workspace_root()
196 && crate::pipeline_store::load_pipeline_configs(root).is_ok()
197 {
198 let source_roots = self.anchor_source_roots(mem);
199 for a in &anchors {
200 match a.grain {
201 crate::anchor::AnchorGrain::Span
202 | crate::anchor::AnchorGrain::File
203 | crate::anchor::AnchorGrain::Tree => {}
204 crate::anchor::AnchorGrain::Url | crate::anchor::AnchorGrain::Entity => {
205 continue;
206 }
207 }
208 let base = crate::engine::query::anchor_base_path(&a.artifact);
209 let mut candidates: Vec<String> = Vec::new();
210 if let Some(source) = &a.source
211 && let Some(pointer) = source_roots.get(source)
212 {
213 candidates.push(crate::engine::query::join_pointer(pointer, base));
214 }
215 candidates.push(base.to_string());
216 if !candidates.iter().any(|c| root.join(c).exists()) {
217 return Err(EngineError::from(
218 crate::anchor::AnchorValidationError::ArtifactUnresolvable {
219 artifact: a.artifact.clone(),
220 candidates,
221 },
222 ));
223 }
224 }
225 }
226
227 Ok(anchors)
228 }
229
230 /// Validate an update's `anchors_unset[]` payload up front — a
231 /// malformed selector (missing artifact, unknown grain/class wire
232 /// string) refuses the whole mutation with the same typed
233 /// `INVALID_ANCHOR` envelope as a malformed `anchors[]` element.
234 /// Empty payload → empty vec.
235 pub(crate) fn validate_anchor_unsets(
236 inputs: &[crate::anchor::AnchorUnsetInput],
237 ) -> Result<Vec<crate::anchor::AnchorUnset>, EngineError> {
238 inputs
239 .iter()
240 .map(|i| i.validate().map_err(EngineError::from))
241 .collect()
242 }
243
244 /// Record verify-observed prepared-content hashes onto **hash-less
245 /// hash-bearing** anchors in `mem_name`'s anchors sidecar — the
246 /// measurement-bookkeeping backfill the verify pass hands over via
247 /// [`crate::ingest::VerifyOutcome::hash_backfill`].
248 ///
249 /// This mutates **only** the engine-owned sidecar
250 /// ([`crate::anchor::ANCHOR_SIDECAR_PATH`]): no entity content, no
251 /// section, no `_hash` is touched — an anchor-only commit yields zero
252 /// entity deltas by construction. Guards enforced at this write seam,
253 /// not left to callers:
254 ///
255 /// - only a hash-bearing class (`anchored` / `derived`) may gain a hash —
256 /// an `authored` / `informed-by` anchor is never written, whatever the
257 /// caller observed;
258 /// - an anchor that already carries a hash is never overwritten — the
259 /// recorded hash is the drift baseline, so the backfill is idempotent
260 /// (a second identical call stages nothing and produces no commit).
261 ///
262 /// Returns how many anchors gained a hash. Zero writes ⇒ no commit.
263 pub fn record_anchor_observed_hashes(
264 &mut self,
265 mem_name: &str,
266 observed: &[crate::anchor::ObservedArtifactHash],
267 note: Option<&str>,
268 ) -> Result<usize, EngineError> {
269 if observed.is_empty() {
270 return Ok(0);
271 }
272 let mount_idx = self
273 .mounts
274 .iter()
275 .position(|m| m.mount.mem == mem_name)
276 .ok_or_else(|| self.unknown_mem_error(mem_name))?;
277 if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
278 return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
279 }
280 // Same posture as every other commit-producing write: probe for
281 // sibling-engine drift so the sidecar merge runs against current truth.
282 let _warnings = self.reload_if_stale(Some(mem_name));
283
284 let backend = self.mounts[mount_idx].backend.as_ref();
285 let mut sidecar = read_sidecar(backend)?;
286 let mut written = 0usize;
287 for obs in observed {
288 let Some(anchors) = sidecar.entities.get_mut(&obs.entity) else {
289 continue;
290 };
291 for a in anchors {
292 if a.class.is_hash_bearing() && a.hash.is_none() && a.artifact == obs.artifact {
293 a.hash = Some(obs.hash.clone());
294 written += 1;
295 }
296 }
297 }
298 if written == 0 {
299 return Ok(0);
300 }
301 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
302 let ctx = crate::vcs::CommitContext {
303 actor: crate::vcs::Actor::Agent,
304 client: None,
305 tool: Some("record_anchor_observed_hashes"),
306 note: note.map(String::from),
307 role: self.current_role,
308 logical_operation_id: None,
309 entity_ids: None,
310 };
311 let commit_sha = backend.commit(
312 &format!("memstead: anchor-hash backfill ({written} anchor(s))"),
313 &ctx,
314 )?;
315 self.record_self_write(mount_idx, &commit_sha);
316 self.stamp_mutation_versions(mount_idx);
317 Ok(written)
318 }
319
320 /// Record on the mem which engine version and which resolved
321 /// schema performed the mutation that just committed
322 /// (`MemConfig.mutation_stamp`). Called by every mutation verb
323 /// after `record_self_write` — one shared implementation, per the
324 /// one-guard-on-all-write-paths principle — and deliberately NOT
325 /// by `apply_external_commit`: a replayed sibling commit was
326 /// stamped by the engine that performed it, and this engine must
327 /// not claim it.
328 ///
329 /// Write-cheap by construction: the config write happens only when
330 /// the stamp VALUE changes (a binary upgrade or a schema repin) —
331 /// steady-state mutations compare and return. The write is
332 /// best-effort: a failed stamp never fails the mutation that
333 /// preceded it. On git-branch backends the config rides the
334 /// `__MEMSTEAD` ref, so a stamp write never moves the mem branch
335 /// head — mutation `commit_sha` cursors stay valid.
336 pub(crate) fn stamp_mutation_versions(&mut self, mount_idx: usize) {
337 let Some(state) = self.mounts.get(mount_idx) else {
338 return;
339 };
340 let mem = state.mount.mem.clone();
341 let Some(schema) = self.schemas.get(&mem) else {
342 return;
343 };
344 let (name, version) = schema.id();
345 // Full build version (semver + git build sha when present) so
346 // a rebuild between mutations is a recordable — and hence
347 // skew-detectable — event even between releases.
348 let stamp = memstead_schema::MutationStamp {
349 engine_version: crate::build_info::full_version().to_string(),
350 schema: format!("{name}@{version}"),
351 };
352 let Some(state) = self.mounts.get_mut(mount_idx) else {
353 return;
354 };
355 // A mem with no loaded config has nowhere to carry the stamp;
356 // skip silently (in-memory sketches, minimal fixtures).
357 let Some(config) = state.mem_config.as_ref() else {
358 return;
359 };
360 if config.mutation_stamp.as_ref() == Some(&stamp) {
361 return;
362 }
363 let mut updated = config.clone();
364 updated.mutation_stamp = Some(stamp);
365 let Ok(mut bytes) = serde_json::to_vec_pretty(&updated) else {
366 return;
367 };
368 bytes.push(b'\n');
369 if state
370 .backend
371 .write_mem_config_with_note(&bytes, Some("engine version stamp"))
372 .is_ok()
373 {
374 state.mem_config = Some(updated);
375 }
376 }
377}
378
379/// Stage a write of `entity_id`'s anchors into the mem's anchors sidecar
380/// through `backend`, merged over the existing sidecar at BOTH levels —
381/// other entities' rows survive (document level), and within the entity's
382/// own row `unsets` apply first, then each incoming anchor replaces the
383/// existing anchor with the same `(artifact, grain, class)` triple or
384/// appends ([`crate::anchor::AnchorSidecar::merge`]). Writing never
385/// removes an anchor the call did not name in `unsets`. The write is
386/// buffered into the SAME pending op set the entity write used — so the
387/// next [`crate::backend::MemBackend::commit`] carries entity + anchors
388/// as one atomic commit. Reads honour pending-buffer precedence, so
389/// successive stages within one transaction compose.
390/// Stage a mutation of the engine-owned derivations sidecar
391/// (agent-trust plan 12) so it rides the SAME commit as the edge
392/// write that produced it — the anchors-sidecar atomicity precedent.
393/// The sidecar travels through the backend's normal entity-path
394/// read/write under `.memstead/`, which every backend filters from
395/// entity listings and every archive/export path carries as-is.
396pub(crate) fn stage_derivation_sidecar(
397 backend: &dyn crate::backend::MemBackend,
398 mutate: impl FnOnce(&mut crate::derivation::DerivationSidecar),
399) -> Result<(), EngineError> {
400 let path = std::path::Path::new(crate::derivation::DERIVATION_SIDECAR_PATH);
401 let mut sidecar = match backend.read_entity(path)? {
402 Some(bytes) => crate::derivation::DerivationSidecar::from_bytes(&bytes).map_err(|e| {
403 EngineError::Backend(crate::backend::BackendError::Other(format!(
404 "derivations sidecar parse: {e}"
405 )))
406 })?,
407 None => crate::derivation::DerivationSidecar::default(),
408 };
409 mutate(&mut sidecar);
410 backend.write_entity(path, &sidecar.to_bytes())?;
411 Ok(())
412}
413
414/// True when `schema` declares `rel_type` as a derivation
415/// (`derivation: true` on the relationship definition) — the
416/// predicate every write path shares, so baseline recording cannot
417/// fork per verb.
418pub(crate) fn rel_type_declares_derivation(
419 schema: &memstead_schema::Schema,
420 rel_type: &str,
421) -> bool {
422 schema
423 .manifest
424 .relationships
425 .definitions
426 .iter()
427 .any(|d| d.name == rel_type && d.derivation)
428}
429
430pub(crate) fn stage_anchors_sidecar(
431 backend: &dyn crate::backend::MemBackend,
432 entity_id: &EntityId,
433 unsets: &[crate::anchor::AnchorUnset],
434 anchors: Vec<crate::anchor::Anchor>,
435) -> Result<(), EngineError> {
436 let mut sidecar = match backend.read_anchors_sidecar()? {
437 Some(bytes) => crate::anchor::AnchorSidecar::from_bytes(&bytes).map_err(|e| {
438 EngineError::Backend(crate::backend::BackendError::Other(format!(
439 "anchors sidecar parse: {e}"
440 )))
441 })?,
442 None => crate::anchor::AnchorSidecar::default(),
443 };
444 sidecar.merge(entity_id.as_ref(), unsets, anchors);
445 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
446 Ok(())
447}
448
449/// Load the mem's anchors sidecar through `backend`, or the empty
450/// document when none exists yet. Shared by the delete / rename legs
451/// which must decide whether the entity actually has anchor rows before
452/// staging a sidecar write (so an entity with none stays byte-identical
453/// to a pre-anchor mutation).
454fn read_sidecar(
455 backend: &dyn crate::backend::MemBackend,
456) -> Result<crate::anchor::AnchorSidecar, EngineError> {
457 match backend.read_anchors_sidecar()? {
458 Some(bytes) => crate::anchor::AnchorSidecar::from_bytes(&bytes).map_err(|e| {
459 EngineError::Backend(crate::backend::BackendError::Other(format!(
460 "anchors sidecar parse: {e}"
461 )))
462 }),
463 None => Ok(crate::anchor::AnchorSidecar::default()),
464 }
465}
466
467/// Stage removal of `entity_id`'s anchor row into the same commit as an
468/// entity delete — a no-op (no sidecar write, so byte-identical to today)
469/// when the entity carries no anchors. Returns whether a write was staged.
470pub(crate) fn stage_anchors_removal(
471 backend: &dyn crate::backend::MemBackend,
472 entity_id: &EntityId,
473) -> Result<bool, EngineError> {
474 let mut sidecar = read_sidecar(backend)?;
475 if sidecar.get(entity_id.as_ref()).is_empty() {
476 return Ok(false);
477 }
478 sidecar.remove(entity_id.as_ref());
479 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
480 Ok(true)
481}
482
483/// Stage a move of `from`'s anchor row to `to` into the same commit as an
484/// entity rename — leaving zero rows under the old id. A no-op (byte-
485/// identical to today) when the renamed entity carries no anchors. Returns
486/// whether a write was staged.
487pub(crate) fn stage_anchors_rename(
488 backend: &dyn crate::backend::MemBackend,
489 from: &EntityId,
490 to: &EntityId,
491) -> Result<bool, EngineError> {
492 let mut sidecar = read_sidecar(backend)?;
493 if sidecar.get(from.as_ref()).is_empty() {
494 return Ok(false);
495 }
496 sidecar.rename(from.as_ref(), to.as_ref());
497 backend.write_anchors_sidecar(&sidecar.to_bytes())?;
498 Ok(true)
499}
500
501// A `today_iso()` wall-clock convenience used to live here, for tests
502// comparing an auto-stamp against "roughly now". It is deliberately
503// gone: the stamp is second-resolution, so every such comparison races
504// the clock between the mutation and the assertion, and one of them
505// duly failed on a suite run that straddled midnight. Tests that need
506// a stamped value pin `Engine::set_mutation_clock` and derive the
507// expected string from the same instant via [`iso_from_system_time`].
508
509/// An instant as a full ISO-8601 datetime string `YYYY-MM-DDTHH:MM:SSZ`
510/// (UTC). Used by mutation paths that auto-stamp metadata fields
511/// (e.g. `last_modified` on update, `created_date` on create).
512///
513/// This is second-resolution (rather than
514/// date-only `YYYY-MM-DD`) so intra-day
515/// updates produce distinguishable timestamps and drift / staleness
516/// queries become per-update aware. The strict-mode date validator
517/// already accepts both forms (`^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}Z)?$`)
518/// so existing entities written with the date-only form continue to
519/// load; new writes carry the wider form.
520///
521/// Pure function: no allocation outside the `format!` invocation,
522/// no error path (the fallback to UNIX epoch on an instant before
523/// the epoch is acceptable for a best-effort timestamp).
524/// Howard-Hinnant civil-from-days for the date half; trivial modular
525/// arithmetic for the time half.
526pub(super) fn iso_from_system_time(t: std::time::SystemTime) -> String {
527 let now = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
528 let secs = now.as_secs();
529 let days = secs / 86400;
530 let secs_of_day = secs % 86400;
531 let hh = secs_of_day / 3600;
532 let mm = (secs_of_day % 3600) / 60;
533 let ss = secs_of_day % 60;
534 let z = days + 719468;
535 let era = z / 146097;
536 let doe = z - era * 146097;
537 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
538 let y = yoe + era * 400;
539 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
540 let mp = (5 * doy + 2) / 153;
541 let d = doy - (153 * mp + 2) / 5 + 1;
542 let m = if mp < 10 { mp + 3 } else { mp - 9 };
543 let y = if m <= 2 { y + 1 } else { y };
544 format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
545}
546
547/// Sweep stubs whose last incoming edge has just disappeared. Returns
548/// the dropped ids so callers can surface them to the agent (e.g. via
549/// [`DeleteEntityOutcome::orphan_stubs_removed`]).
550///
551/// Stubs are auto-created when a relate names an absent target — a
552/// "promise" that a real entity will land there later (see
553/// [`make_stub`]). When the last referrer drops its edge or is itself
554/// deleted, the promise has no holder and becomes pure bloat. Only
555/// stubs are eligible — real entities never count as orphans via this
556/// path.
557pub(super) fn gc_orphan_stubs(store: &mut Store) -> Vec<EntityId> {
558 let stub_ids: Vec<EntityId> = store
559 .all_entities()
560 .filter(|e| e.stub)
561 .map(|e| e.id.clone())
562 .collect();
563 gc_orphan_stubs_among(store, &stub_ids)
564}
565
566/// Scoped orphan-stub sweep: GC only the stubs *among `candidates`*
567/// whose last incoming edge has just disappeared, returning the dropped
568/// ids. This is the single home of the orphan-stub predicate (`stub &&
569/// no incoming`) — the three write paths that can sever a stub's last
570/// referrer all funnel through here so they cannot drift:
571/// [`gc_orphan_stubs`] (delete's full-store sweep) supplies every stub
572/// id; the `memstead_relate(remove)` path supplies the just-severed target;
573/// the `memstead_update` alias-resync path supplies the entity's
574/// pre-mutation body-link targets (the only edges that commit could
575/// have dropped). Scoping to a candidate set rather than walking the
576/// whole store keeps each path from GC'ing pre-existing orphans that
577/// aren't its responsibility. Candidates are de-duplicated; a candidate
578/// that is absent, not a stub, or still has a referrer is left
579/// untouched.
580pub(super) fn gc_orphan_stubs_among<'a>(
581 store: &mut Store,
582 candidates: impl IntoIterator<Item = &'a EntityId>,
583) -> Vec<EntityId> {
584 let mut removed: Vec<EntityId> = Vec::new();
585 let mut seen: std::collections::HashSet<&EntityId> = std::collections::HashSet::new();
586 for id in candidates {
587 if !seen.insert(id) {
588 continue;
589 }
590 if store.get(id).is_some_and(|e| e.stub) && store.incoming(id).is_empty() {
591 store.remove(id);
592 removed.push(id.clone());
593 }
594 }
595 removed
596}
597
598/// Shared target-id grammar validator. The wiki-link grammar gate
599/// runs on every relation-authoring path (`memstead_relate`,
600/// `memstead_create.relations[]`, future inline-relation surfaces) so a
601/// malformed target id (e.g. `bad@chars$here`) cannot land an
602/// auto-stub at the literal id — that stub would later fail every
603/// wiki-link parse that referenced it. Pre-Item-02 the gate lived
604/// only on `memstead_relate`; the create path admitted the same input
605/// silently.
606pub(super) fn validate_relation_target_grammar(target: &EntityId) -> Result<(), EngineError> {
607 if let Err(reason) = crate::entity::id::validate_mem_name_grammar(target.mem()) {
608 return Err(EngineError::InvalidEntityId {
609 id: target.to_string(),
610 reason,
611 });
612 }
613 if let Err(reason) = crate::entity::id::validate_id_path_grammar(target.path()) {
614 return Err(EngineError::InvalidEntityId {
615 id: target.to_string(),
616 reason,
617 });
618 }
619 Ok(())
620}
621
622/// Auto-stamp `auto_timestamp` metadata fields on an entity that's
623/// about to be re-written. Extracted from the update-path hot loop so
624/// the relate-path (add and remove) and the rename-path (the renaming
625/// entity plus every referrer the rewrite cascade touched) can
626/// invoke the same engine-driven stamp.
627///
628/// Walks the type's metadata-field declarations; any field flagged
629/// `auto_timestamp: true` (the default schema declares this on
630/// `last_modified`) is set to the supplied `today` ISO string. The
631/// helper is a no-op on schemas that declare no auto-timestamp
632/// fields. Callers pre-compute `today` via [`today_iso`] so a single
633/// mutation that touches multiple entities (rename's referrer rewrite
634/// cascade) stamps them all with the same value.
635pub(super) fn auto_stamp_timestamps(
636 entity: &mut Entity,
637 type_def: &memstead_schema::TypeDefinition,
638 today: &str,
639) {
640 for field_def in &type_def.metadata_fields {
641 if field_def.auto_timestamp {
642 entity.metadata.insert(
643 field_def.key.clone(),
644 crate::entity::MetadataValue::String(today.to_string()),
645 );
646 }
647 }
648}
649
650/// Build a stub [`Entity`] for an unresolved relate target. Callers
651/// declare the stub's origin via [`crate::entity::StubKind`] —
652/// `ForwardReference` for `memstead_relate` to an absent target,
653/// `Residual { since_commit, readonly_referrers }` for the
654/// delete/rename demote path. The kind persists for the engine
655/// instance's lifetime; a reload reduces every stub to `LoadTime`
656/// — the kind is annotation, not state.
657///
658/// The stub is in-store but unwritten to disk — `entity_type` empty,
659/// `file_path` empty, no metadata, no sections, `stub: true` and
660/// `stub_kind: Some(kind)` set together. A later
661/// [`Engine::create_entity`] at the same id promotes the stub to a
662/// real entity (loader / parse-result merge handles the upgrade
663/// path; `stub_kind` clears to `None`).
664pub(super) fn make_stub(id: &EntityId, kind: crate::entity::StubKind) -> Entity {
665 Entity {
666 id: id.clone(),
667 title: id.name().to_string(),
668 entity_type: String::new(),
669 mem: id.mem().to_string(),
670 file_path: String::new(),
671 metadata: IndexMap::new(),
672 sections: IndexMap::new(),
673 relationships: Vec::new(),
674 content_hash: String::new(),
675 stub: true,
676 stub_kind: Some(kind),
677 heading_spans: HashMap::new(),
678 raw_section_headings: Vec::new(),
679 }
680}
681
682/// Cross-mem add-path policy gate. Same-mem writes bypass; the
683/// `[cross_mem_links]` table only gates writes that cross the
684/// mem boundary. Cross-mem writes consult
685/// [`super::Engine::cross_mem_link_allowed`] in the edge's actual
686/// direction (`source_mem → target_mem`). Disallowed pairings
687/// surface [`EngineError::CrossMemLinkNotAllowed`] with the
688/// `(from_mem, to_mem)` payload an agent already sees on
689/// `memstead_relate`.
690///
691/// After the grant admits the pairing, a target absent from a
692/// `MountCapability::ReadOnly` mount refuses with
693/// [`EngineError::CrossMemTargetNotFound`]: the engine cannot
694/// persist a stub through the read-only boundary, and a read-only
695/// mem never gains the entity later — a missing target there is a
696/// wrong link, not a pending forward reference. Same-mem targets,
697/// cross-mem targets in Write mounts, and unmounted target mems all
698/// retain the auto-stub mechanic.
699///
700/// Funnel point for every add-shaped edge write — `memstead_relate`,
701/// `memstead_create.relations[]`, `memstead_update.declare_relations`,
702/// body-wiki-link alias synthesis, and any future add-path mutation
703/// surface route through one gate so the policy can't drift between
704/// sites. Remove-shaped writes (cleanup) remain permissive and call
705/// this helper not at all.
706pub(super) fn validate_cross_mem_add_policy(
707 engine: &super::Engine,
708 source_mem: &str,
709 target: &EntityId,
710) -> Result<(), EngineError> {
711 let target_mem = target.mem();
712 if source_mem == target_mem {
713 return Ok(());
714 }
715 if !engine.cross_mem_link_allowed(source_mem, target_mem) {
716 return Err(EngineError::CrossMemLinkNotAllowed {
717 from_mem: source_mem.to_string(),
718 to_mem: target_mem.to_string(),
719 });
720 }
721 if let Some(mount) = engine.mount(target_mem)
722 && mount.capability == crate::workspace::MountCapability::ReadOnly
723 && !engine.store.contains(target)
724 && !matches!(
725 probe_deferred_target(engine, target)?,
726 DeferredTargetProbe::Exists
727 )
728 {
729 return Err(EngineError::CrossMemTargetNotFound {
730 target_id: target.to_string(),
731 target_mem: target_mem.to_string(),
732 });
733 }
734 Ok(())
735}
736
737/// Storage verdict for a cross-mem target whose mem is mounted but
738/// DEFERRED (lazy, not yet loaded) — the write-time verification of
739/// flywheel W7/02. The check asks the mem's real storage through the
740/// cheap [`crate::backend::MemBackend::entity_exists`] probe
741/// (tree-lookup-class on git-branch, metadata-class on folder) and
742/// never triggers the mem's load: verification must not convert into
743/// a full-load side effect (plan 01's seam).
744pub(super) enum DeferredTargetProbe {
745 /// The target's mem is loaded (the store is the truth) or not
746 /// mounted at all (no storage handle to ask — the
747 /// forward-reference mechanic governs).
748 NotApplicable,
749 /// Storage holds the entity: the reference is verified against
750 /// real storage even though the mem is unloaded.
751 Exists,
752 /// Storage answers and the entity is not there.
753 Absent,
754}
755
756pub(super) fn probe_deferred_target(
757 engine: &super::Engine,
758 target: &EntityId,
759) -> Result<DeferredTargetProbe, EngineError> {
760 let rel_path = crate::entity::id::id_to_file_path(target);
761 if engine.mem_is_deferred(target.mem()) {
762 let Some(mounted) = engine.mounts.iter().find(|m| m.mount.mem == target.mem()) else {
763 return Ok(DeferredTargetProbe::NotApplicable);
764 };
765 return Ok(
766 if mounted
767 .backend
768 .entity_exists(std::path::Path::new(&rel_path))?
769 {
770 DeferredTargetProbe::Exists
771 } else {
772 DeferredTargetProbe::Absent
773 },
774 );
775 }
776 // UNMOUNTED mem: ask the workspace layer's discovery hook. No
777 // hook, or no discoverable storage → NotApplicable (the
778 // forward-reference mechanic governs, unchanged).
779 if engine.mount(target.mem()).is_none()
780 && let Some(prober) = &engine.unmounted_storage_prober
781 && let Some(storage) = prober(target.mem())
782 {
783 return Ok(
784 if storage
785 .backend
786 .entity_exists(std::path::Path::new(&rel_path))?
787 {
788 DeferredTargetProbe::Exists
789 } else {
790 DeferredTargetProbe::Absent
791 },
792 );
793 }
794 Ok(DeferredTargetProbe::NotApplicable)
795}
796
797/// The one-blob type read for a storage-verified deferred target: the
798/// shape check needs the target's real entity type, and a tree hit
799/// proves existence, not type. Reads exactly the resolved path's
800/// bytes and peeks the frontmatter `type:` — never the mem. Returns
801/// `None` when the entity is absent or declares no type (the shape
802/// gate then admits, the same posture the stub-bound case has
803/// always had — the check never guesses).
804/// The stub kind for a target being auto-stubbed on an add path: a
805/// target that storage VERIFIES inside a deferred mem gets the
806/// load-time kind — the stub is only plan 01's until-load
807/// representation of a link into an unloaded mem, not a forward
808/// reference to something that awaits creation. Everything else keeps
809/// `ForwardReference`. Kinds stay annotation-not-state either way.
810pub(super) fn deferred_verified_stub_kind(
811 engine: &super::Engine,
812 target: &EntityId,
813) -> Result<crate::entity::StubKind, EngineError> {
814 Ok(
815 if matches!(
816 probe_deferred_target(engine, target)?,
817 DeferredTargetProbe::Exists
818 ) {
819 crate::entity::StubKind::LoadTime
820 } else {
821 crate::entity::StubKind::ForwardReference
822 },
823 )
824}
825
826pub(super) fn peek_deferred_target_type(
827 engine: &super::Engine,
828 target: &EntityId,
829) -> Result<Option<String>, EngineError> {
830 let rel_path = crate::entity::id::id_to_file_path(target);
831 let bytes = if engine.mem_is_deferred(target.mem()) {
832 let Some(mounted) = engine.mounts.iter().find(|m| m.mount.mem == target.mem()) else {
833 return Ok(None);
834 };
835 mounted
836 .backend
837 .read_entity(std::path::Path::new(&rel_path))?
838 } else if engine.mount(target.mem()).is_none()
839 && let Some(prober) = &engine.unmounted_storage_prober
840 && let Some(storage) = prober(target.mem())
841 {
842 storage
843 .backend
844 .read_entity(std::path::Path::new(&rel_path))?
845 } else {
846 return Ok(None);
847 };
848 let Some(bytes) = bytes else {
849 return Ok(None);
850 };
851 Ok(String::from_utf8(bytes)
852 .ok()
853 .and_then(|c| crate::entity::parser::peek_type_from_frontmatter(&c)))
854}
855
856/// The target-schema REF for cross-schema edge routing. Loaded mems
857/// answer from the engine's schema catalogue; an UNMOUNTED mem with
858/// discoverable storage answers from its stored config's pin via the
859/// discovery hook (flywheel W7/02) — the routing check
860/// (`validate_cross_mem_edge`) needs only the ref, never the full
861/// schema, so the source schema's `cross_mem_relationships:` entry
862/// keeps its authority without a mount. `None` falls back to the
863/// intra-mem path, exactly the pre-existing posture.
864pub(super) fn target_schema_ref_for_routing(
865 engine: &super::Engine,
866 target_mem: &str,
867) -> Option<memstead_schema::SchemaRef> {
868 if let Some(s) = engine.schemas.get(target_mem) {
869 let (name, version) = s.id();
870 return Some(memstead_schema::SchemaRef::new(name, version));
871 }
872 if engine.mount(target_mem).is_none()
873 && let Some(prober) = &engine.unmounted_storage_prober
874 && let Some(storage) = prober(target_mem)
875 {
876 return storage.schema;
877 }
878 None
879}
880
881/// Outcome of the engine's edge-validation router for a single
882/// inline / explicit relate. Carries the optional open-mode warning
883/// from the intra-mem flow; the cross-mem flow has no
884/// open-mode (cross-mem entries are declared vocabulary).
885pub(super) enum EdgeRouteOutcome {
886 Ok,
887 OpenModeWarning(Box<crate::ops::WarningHint>),
888}
889
890/// Run rel-type + shape validation for one edge, routing through
891/// intra-mem vocabulary or the source schema's
892/// `cross_mem_relationships:` section as appropriate.
893///
894/// The routing rule:
895/// when `source_mem != target_mem` AND the target mem's
896/// pinned schema differs from the source schema by name or by
897/// version, the source schema's `cross_mem_relationships:` entry
898/// for the target schema is the sole authority for both the
899/// vocabulary check (`INVALID_REL_TYPE`) and the shape check
900/// (`INVALID_REL_SHAPE`). If no matching entry exists, surface
901/// [`EngineError::CrossMemEdgeNotDeclared`].
902///
903/// Otherwise (same-mem, same-schema cross-mem, or target mem
904/// unmounted) the call falls through to the existing intra-mem
905/// validators — the same behaviour the intra-mem path always had.
906///
907/// `check_shape` mirrors the relate path's add-only shape posture:
908/// pass `false` to skip the shape check (currently only the
909/// `memstead_relate --remove` path). The vocabulary check still fires
910/// in that case, matching the intra-mem behaviour where
911/// `validate_rel_type` runs on both add and remove.
912// The nine parameters are one edge's full coordinates; a params struct
913// would restate the same fields at every call site without grouping
914// anything that travels together elsewhere.
915#[allow(clippy::too_many_arguments)]
916pub(super) fn route_edge_validation(
917 engine: &super::Engine,
918 rel_type: &str,
919 from_type: &str,
920 to_type: Option<&str>,
921 source_mem: &str,
922 target_mem: &str,
923 from_id: &EntityId,
924 to_id: &EntityId,
925 check_shape: bool,
926) -> Result<EdgeRouteOutcome, EngineError> {
927 use crate::runtime_validator::{
928 CrossMemRelCheck, RelationshipCheck, validate_cross_mem_edge, validate_rel_shape,
929 validate_rel_type,
930 };
931 use memstead_schema::SchemaRef;
932
933 let source_schema = engine
934 .schemas
935 .get(source_mem)
936 .expect("schema present for every registered mount");
937
938 let target_schema_ref: Option<SchemaRef> = if source_mem == target_mem {
939 None
940 } else {
941 target_schema_ref_for_routing(engine, target_mem)
942 };
943 let cross_mem_different = match (&target_schema_ref, source_schema.id()) {
944 (Some(target), (src_name, _)) => target.name != src_name,
945 (None, _) => false,
946 };
947
948 if cross_mem_different {
949 let target_ref = target_schema_ref
950 .as_ref()
951 .expect("target_schema_ref is Some when cross_mem_different");
952 if !check_shape {
953 // Cleanup posture: cross-mem remove stays permissive so
954 // pre-tightening edges remain droppable without first
955 // re-declaring them. Mirrors the intra-mem shape gate's
956 // add-only stance.
957 return Ok(EdgeRouteOutcome::Ok);
958 }
959 match validate_cross_mem_edge(
960 rel_type,
961 from_type,
962 to_type,
963 source_schema.as_ref(),
964 target_ref,
965 ) {
966 CrossMemRelCheck::Ok => Ok(EdgeRouteOutcome::Ok),
967 CrossMemRelCheck::EdgeNotDeclared => {
968 let (src_name, src_version) = source_schema.id();
969 Err(EngineError::CrossMemEdgeNotDeclared {
970 source_schema: SchemaRef::new(src_name, src_version).as_display(),
971 target_schema: target_ref.as_display(),
972 rel_type: rel_type.to_string(),
973 from_id: from_id.to_string(),
974 to_id: to_id.to_string(),
975 })
976 }
977 CrossMemRelCheck::Invalid(v) => Err(EngineError::Validation(v)),
978 }
979 } else {
980 let warning_hint = match validate_rel_type(rel_type, source_schema.as_ref())? {
981 RelationshipCheck::Ok => None,
982 RelationshipCheck::OpenWarning(message) => {
983 Some(crate::ops::WarningHint::UndeclaredRelationshipOpen {
984 rel_type: rel_type.to_string(),
985 message,
986 })
987 }
988 };
989 if check_shape {
990 validate_rel_shape(rel_type, from_type, to_type, source_schema.as_ref())?;
991 }
992 Ok(match warning_hint {
993 Some(w) => EdgeRouteOutcome::OpenModeWarning(Box::new(w)),
994 None => EdgeRouteOutcome::Ok,
995 })
996 }
997}
998
999/// Cycle-family gate for one prospective edge — the single owner of
1000/// both refusals, shared by every edge-writing verb (`memstead_relate`,
1001/// `memstead_create.relations[]`, `memstead_update.declare_relations`, and the
1002/// batch paths, which stage prior items' edges into `store` so an
1003/// intra-batch cycle refuses like a stored one):
1004///
1005/// - **Self-loop on a listed no-self-loop rel-type.** `from == to` on
1006/// any rel-type the source type lists in `no_self_loop_relationships`
1007/// refuses, regardless of the `acyclic` flag — the declaration's one
1008/// effect (see `TypeDefinition::no_self_loop_relationships`).
1009/// - **Cycle on an acyclic rel-type.** An add closing a back-path
1010/// `to → … → from` (via [`crate::graph::query::would_cycle`]) refuses
1011/// with the existing path, capped at [`RELATIONSHIP_CYCLE_PATH_CAP`].
1012/// - **Cycle in a declared acyclicity set.** When the rel-type belongs
1013/// to a `relationships.acyclic_sets` set, an add closing a back-path
1014/// in the set's UNION subgraph (via
1015/// [`crate::graph::query::would_cycle_in_set`]) refuses; the payload
1016/// additionally echoes the set and the path's per-hop rel-types.
1017///
1018/// All refuse [`EngineError::RelationshipCycle`] (`RELATIONSHIP_CYCLE`)
1019/// with identical recovery detail on every path. Callers skip this on
1020/// remove paths — removal can only break cycles, never close one.
1021pub(super) fn validate_edge_acyclicity(
1022 store: &Store,
1023 schema: &memstead_schema::Schema,
1024 from: &EntityId,
1025 from_type: &str,
1026 to: &EntityId,
1027 rel_type: &str,
1028) -> Result<(), EngineError> {
1029 if from == to && schema.type_refuses_self_loop(from_type, rel_type) {
1030 return Err(EngineError::RelationshipCycle {
1031 rel_type: rel_type.to_string(),
1032 from: from.clone(),
1033 to: to.clone(),
1034 existing_path: vec![from.clone()],
1035 path_truncated: false,
1036 acyclic_set: None,
1037 existing_path_rel_types: None,
1038 });
1039 }
1040 if schema.relationship_acyclic(rel_type)
1041 && let Some(path) = crate::graph::query::would_cycle(store, from, to, rel_type)
1042 {
1043 let truncated = path.len() > RELATIONSHIP_CYCLE_PATH_CAP;
1044 let mut existing_path = path;
1045 if truncated {
1046 existing_path.truncate(RELATIONSHIP_CYCLE_PATH_CAP);
1047 }
1048 return Err(EngineError::RelationshipCycle {
1049 rel_type: rel_type.to_string(),
1050 from: from.clone(),
1051 to: to.clone(),
1052 existing_path,
1053 path_truncated: truncated,
1054 acyclic_set: None,
1055 existing_path_rel_types: None,
1056 });
1057 }
1058 // Cycle in a declared acyclicity SET: the union subgraph of the
1059 // set must stay acyclic, so the back-path may mix rel-types. The
1060 // refusal is additive — it echoes the declared set and one
1061 // rel-type per hop of the path.
1062 if let Some(set) = schema.acyclic_set_containing(rel_type)
1063 && let Some((path, path_rels)) =
1064 crate::graph::query::would_cycle_in_set(store, from, to, set)
1065 {
1066 let truncated = path.len() > RELATIONSHIP_CYCLE_PATH_CAP;
1067 let mut existing_path = path;
1068 let mut existing_path_rel_types = path_rels;
1069 if truncated {
1070 existing_path.truncate(RELATIONSHIP_CYCLE_PATH_CAP);
1071 existing_path_rel_types.truncate(existing_path.len().saturating_sub(1));
1072 }
1073 return Err(EngineError::RelationshipCycle {
1074 rel_type: rel_type.to_string(),
1075 from: from.clone(),
1076 to: to.clone(),
1077 existing_path,
1078 path_truncated: truncated,
1079 acyclic_set: Some(set.to_vec()),
1080 existing_path_rel_types: Some(existing_path_rel_types),
1081 });
1082 }
1083 Ok(())
1084}
1085
1086/// Validate the per-edge description posture declared on the rel-type
1087/// in the routing-appropriate definition (intra-mem when source and
1088/// target share the schema; cross-mem entry when they don't). Emits
1089/// `MissingRequiredDescription` / `DescriptionNotPermitted` on
1090/// violations; `optional` and unknown rel-types are no-ops (the
1091/// vocabulary / shape gates already catch undeclared names — posture
1092/// only fires for declared names).
1093///
1094/// `description` is the normalised value (empty / whitespace-only
1095/// collapses to `None` before reaching this gate). Called from every
1096/// add path: `memstead_relate`, `declare_relations` on `memstead_create` and
1097/// `memstead_update`.
1098pub(super) fn validate_description_posture(
1099 engine: &super::Engine,
1100 rel_type: &str,
1101 description: Option<&str>,
1102 source_mem: &str,
1103 target_mem: &str,
1104 from_id: &EntityId,
1105 to_id: &EntityId,
1106) -> Result<(), EngineError> {
1107 use memstead_schema::{PerEdgeDescription, SchemaRef};
1108
1109 let source_schema = engine
1110 .schemas
1111 .get(source_mem)
1112 .expect("schema present for every registered mount");
1113 let target_schema_ref: Option<SchemaRef> = if source_mem == target_mem {
1114 None
1115 } else {
1116 target_schema_ref_for_routing(engine, target_mem)
1117 };
1118 let cross_mem_different = match (&target_schema_ref, source_schema.id()) {
1119 (Some(target), (src_name, _)) => target.name != src_name,
1120 (None, _) => false,
1121 };
1122
1123 let posture = if cross_mem_different {
1124 // Look up the matching cross-mem entry's definition. If the
1125 // entry exists but the rel-type isn't enumerated under it, the
1126 // vocabulary gate (route_edge_validation) will surface
1127 // `CROSS_MEM_EDGE_NOT_DECLARED`; posture is a no-op there.
1128 let target_ref = target_schema_ref
1129 .as_ref()
1130 .expect("target_schema_ref is Some when cross_mem_different");
1131 source_schema
1132 .cross_mem_entries(&target_ref.name)
1133 .iter()
1134 .find_map(|entry| entry.definitions.iter().find(|d| d.name == rel_type))
1135 .map(|d| d.per_edge_description)
1136 } else {
1137 source_schema
1138 .relationship_def(rel_type)
1139 .map(|d| d.per_edge_description)
1140 };
1141
1142 match posture {
1143 Some(PerEdgeDescription::Required) if description.is_none() => {
1144 Err(EngineError::MissingRequiredDescription {
1145 rel_type: rel_type.to_string(),
1146 from_id: from_id.to_string(),
1147 to_id: to_id.to_string(),
1148 })
1149 }
1150 Some(PerEdgeDescription::Forbidden) if description.is_some() => {
1151 Err(EngineError::DescriptionNotPermitted {
1152 rel_type: rel_type.to_string(),
1153 from_id: from_id.to_string(),
1154 to_id: to_id.to_string(),
1155 })
1156 }
1157 _ => Ok(()),
1158 }
1159}
1160
1161/// Validate the manual-authoring posture declared on the rel-type.
1162/// Fires only on explicit-author paths (`memstead_relate`, inline
1163/// `relations:` on `memstead_create`, `declare_relations` on
1164/// `memstead_update`). The body-link → relation alias machinery
1165/// synthesises relations from wiki-links — that path bypasses this
1166/// gate by construction (it never calls this function), keeping the
1167/// alias path for `manual_authoring: forbidden` rel-types (e.g.
1168/// REFERENCES) intact.
1169pub(super) fn validate_manual_authoring_posture(
1170 engine: &super::Engine,
1171 rel_type: &str,
1172 source_mem: &str,
1173 from_id: &EntityId,
1174 to_id: &EntityId,
1175) -> Result<(), EngineError> {
1176 use memstead_schema::ManualAuthoring;
1177
1178 let source_schema = engine
1179 .schemas
1180 .get(source_mem)
1181 .expect("schema present for every registered mount");
1182 let posture = source_schema.relationship_manual_authoring(rel_type);
1183 if matches!(posture, ManualAuthoring::Forbidden) {
1184 let guidance = source_schema
1185 .relationship_when_to_use(rel_type)
1186 .unwrap_or_default();
1187 return Err(EngineError::RelationManualAuthoringForbidden {
1188 rel_type: rel_type.to_string(),
1189 from_id: from_id.to_string(),
1190 to_id: to_id.to_string(),
1191 guidance,
1192 });
1193 }
1194 Ok(())
1195}
1196
1197/// Alias-synthesis pass — populates `next.relationships` with engine-
1198/// emitted relations of the source schema's `alias_target_rel_type`
1199/// pointer for every body wiki-link not already backed by an
1200/// in-section-body explicit relation. Runs before the
1201/// `scan_wikilinks_without_relation` validator; after this pass the
1202/// validator finds zero missing wiki-links for the pointer rel-type.
1203///
1204/// Three cases:
1205/// 1. Schema has no pointer (`alias_target_rel_type` absent): no-op.
1206/// Caller's validator continues to refuse unbacked links exactly as
1207/// today.
1208/// 2. Schema has a pointer, body wiki-link target is in the same mem
1209/// OR cross-mem policy admits it: append `Relationship { rel_type:
1210/// pointer, target, description: None }` to `next.relationships` if
1211/// no relation of `(pointer, target)` is already present. Dedupe is
1212/// `(target, rel_type)` — a USES or DEPENDS_ON edge to the same
1213/// target does not suppress synthesis of the pointer rel-type.
1214/// 3. Schema has a pointer but a body wiki-link crosses a mem
1215/// boundary the workspace doesn't grant — or targets an entity
1216/// absent from a read-only mount: return the funnel's typed
1217/// refusal ([`EngineError::CrossMemLinkNotAllowed`] /
1218/// [`EngineError::CrossMemTargetNotFound`], via
1219/// [`validate_cross_mem_add_policy`]). The entire mutation
1220/// aborts — no partial state.
1221///
1222/// GC: when `prev` is `Some`, the pass also drops pointer-rel-type
1223/// relations whose target was a body wiki-link in `prev` but no longer
1224/// appears in `next.sections`. The loader forces `manual_authoring:
1225/// forbidden` on every schema's `alias_target_rel_type` pointer, so the
1226/// only path to a pointer-rel-type edge is the body-link channel; the
1227/// GC rule therefore reduces to "drop pointer-rel-type relations whose
1228/// target is not in the new body". Targeting prev's wiki-link set
1229/// specifically (rather than every pointer-rel-type relation) keeps the
1230/// pass correct even for an explicit-author relation that predates the
1231/// forbid posture.
1232///
1233/// Returns the list of relations the pass emitted (in body iteration
1234/// order) — `create.rs` / `update.rs` use it to surface
1235/// `relations_emitted` on the response envelope.
1236/// Returns the synthesised relations (in body iteration order) and a flag
1237/// signalling whether a body wiki-link to the entity's own id was dropped
1238/// (F11). The caller surfaces that as a `SELF_LINK_IGNORED` warning — the
1239/// pass has no warning channel of its own.
1240pub(super) fn synthesise_alias_relations(
1241 engine: &super::Engine,
1242 prev_body_targets: &std::collections::HashSet<EntityId>,
1243 next: &mut Entity,
1244) -> Result<(Vec<crate::entity::Relationship>, bool), super::EngineError> {
1245 let schema = engine
1246 .schemas
1247 .get(next.mem.as_str())
1248 .expect("schema present for every registered mount");
1249 let Some(pointer) = schema.alias_target_rel_type().map(str::to_string) else {
1250 return Ok((Vec::new(), false));
1251 };
1252
1253 // 1. GC: drop pointer-rel-type relations whose target was a body
1254 // wiki-link in the prev entity state but isn't in next. Targets
1255 // not in prev's wiki-link set are explicit-author relations and
1256 // are never touched — the rule preserves explicit edges even
1257 // while the 5 built-ins still admit explicit REFERENCES.
1258 //
1259 // `extract_inline_links` is strict — non-slug-form targets refuse
1260 // here with the typed `InvalidWikiLinkTarget` envelope rather
1261 // than silently flowing into the GC's retain set as malformed
1262 // EntityIds. Section context comes from the iteration key.
1263 let mut next_targets: std::collections::HashSet<EntityId> = std::collections::HashSet::new();
1264 for (section_key, body) in next.sections.iter() {
1265 let ids = crate::entity::parser::extract_inline_links(body, &next.mem)
1266 .map_err(|errs| map_wiki_link_errors(section_key, errs))?;
1267 next_targets.extend(ids);
1268 }
1269 next.relationships.retain(|r| {
1270 !(r.rel_type == pointer
1271 && prev_body_targets.contains(&r.target)
1272 && !next_targets.contains(&r.target))
1273 });
1274
1275 // 2. Walk body wiki-links in section iteration order and append
1276 // one relation per `(target, pointer)` pair not already
1277 // present. Cross-mem gate fires on the first refusal.
1278 let existing: std::collections::HashSet<(String, EntityId)> = next
1279 .relationships
1280 .iter()
1281 .map(|r| (r.rel_type.clone(), r.target.clone()))
1282 .collect();
1283 let mut emitted: Vec<crate::entity::Relationship> = Vec::new();
1284 let mut already_synthesised: std::collections::HashSet<EntityId> =
1285 std::collections::HashSet::new();
1286 let mut self_link_ignored = false;
1287 for (section_key, body) in next.sections.iter() {
1288 let ids = crate::entity::parser::extract_inline_links(body, &next.mem)
1289 .map_err(|errs| map_wiki_link_errors(section_key, errs))?;
1290 for target in ids {
1291 // F11: a body wiki-link to the entity's own id is a vacuous
1292 // self-edge (renders as both Outgoing and Incoming, inflates
1293 // connectivity). Drop it — but don't refuse: the author may
1294 // have written their own slug. The caller surfaces
1295 // `SELF_LINK_IGNORED` so the dropped link stays observable.
1296 if target == next.id {
1297 self_link_ignored = true;
1298 continue;
1299 }
1300 let key = (pointer.clone(), target.clone());
1301 if existing.contains(&key) || already_synthesised.contains(&target) {
1302 continue;
1303 }
1304 validate_cross_mem_add_policy(engine, &next.mem, &target)?;
1305 let rel = crate::entity::Relationship::new(pointer.clone(), target.clone());
1306 next.relationships.push(rel.clone());
1307 already_synthesised.insert(target);
1308 emitted.push(rel);
1309 }
1310 }
1311 Ok((emitted, self_link_ignored))
1312}
1313
1314/// Map the first [`crate::entity::id::WikiLinkError`] from a body
1315/// wiki-link extraction into the typed [`EngineError`] envelope,
1316/// attaching the offending section's key. Errors after the first are
1317/// dropped — the agent reads the error, fixes the link, retries, and
1318/// surfaces the next one on the follow-up call. Keeps the envelope
1319/// shape stable (single typed payload rather than a list) so MCP /
1320/// CLI clients don't need a fan-out renderer.
1321pub(super) fn map_wiki_link_errors(
1322 section_key: &str,
1323 errors: Vec<crate::entity::id::WikiLinkError>,
1324) -> EngineError {
1325 use crate::entity::id::WikiLinkError;
1326 let first = errors
1327 .into_iter()
1328 .next()
1329 .expect("map_wiki_link_errors called with non-empty error list");
1330 match first {
1331 WikiLinkError::InvalidTarget {
1332 raw,
1333 suggested,
1334 reason,
1335 } => EngineError::InvalidWikiLinkTarget {
1336 raw,
1337 suggested,
1338 section: section_key.to_string(),
1339 link_source: "body_link".to_string(),
1340 reason,
1341 },
1342 WikiLinkError::InvalidMemName { raw, reason } => EngineError::InvalidWikiLinkMem {
1343 raw,
1344 section: section_key.to_string(),
1345 reason,
1346 },
1347 }
1348}
1349
1350/// Compute the set of body wiki-link targets in an entity. Used by
1351/// callers of `synthesise_alias_relations` to capture the pre-mutation
1352/// state once, before any borrow conflicts re-enter the engine's
1353/// schemas / store maps. Uses the lenient decoder — this snapshot
1354/// must tolerate on-disk drift on pre-strict entities whose bodies
1355/// may still contain non-conformant links; the strict gate fires
1356/// only on the post-mutation `next` state.
1357pub(super) fn collect_body_link_targets(entity: &Entity) -> std::collections::HashSet<EntityId> {
1358 entity
1359 .sections
1360 .iter()
1361 .flat_map(|(_, body)| {
1362 crate::entity::parser::extract_inline_links_lenient(body, &entity.mem)
1363 })
1364 .collect()
1365}
1366
1367/// Alias-existence invariant validator. Given the post-mutation entity
1368/// state, scan every section body for wiki-links whose target has no
1369/// corresponding explicit relation in `entity.relationships`. Returns
1370/// the list of `(section_key, target_id)` pairs that violate the
1371/// invariant — empty when the post-mutation state is clean.
1372///
1373/// Used by [`Engine::create_entity`] and [`Engine::update_entity`]
1374/// (and `batch_update`). The validator runs unconditionally — under
1375/// the alias model body wiki-links are foreign-key references on the
1376/// `## Relationships` table and every reference must be backed.
1377///
1378/// Sections from the auto-managed `## Relationships` heading are
1379/// not scanned (the engine generates them from the relations list
1380/// at write time; the parser keeps them out of
1381/// `entity.sections` so they never reach this function).
1382///
1383/// Reuses [`crate::entity::parser::extract_inline_links`] so the
1384/// lexical discipline (fenced-code masking, inline-code masking,
1385/// alias handling, cross-mem forms) matches every other validator
1386/// surface in the engine.
1387pub(super) fn scan_wikilinks_without_relation(
1388 next: &Entity,
1389) -> Result<Vec<(String, EntityId)>, EngineError> {
1390 let explicit_targets: std::collections::HashSet<EntityId> = next
1391 .relationships
1392 .iter()
1393 .map(|r| r.target.clone())
1394 .collect();
1395 let mut missing: Vec<(String, EntityId)> = Vec::new();
1396 for (section_key, body) in next.sections.iter() {
1397 let ids = crate::entity::parser::extract_inline_links(body, &next.mem)
1398 .map_err(|errs| map_wiki_link_errors(section_key, errs))?;
1399 for target in ids {
1400 // A self-targeting body link is intentionally unbacked: the
1401 // alias pass drops its (vacuous) self-edge (F11), so it has no
1402 // backing relation by design and must not trip the
1403 // unbacked-link refusal here.
1404 if target == next.id {
1405 continue;
1406 }
1407 if !explicit_targets.contains(&target)
1408 && !missing
1409 .iter()
1410 .any(|(k, t)| k == section_key && t == &target)
1411 {
1412 missing.push((section_key.clone(), target));
1413 }
1414 }
1415 }
1416 Ok(missing)
1417}
1418
1419#[cfg(test)]
1420mod tests {
1421
1422 use tempfile::TempDir;
1423
1424 use crate::backend::MemBackend;
1425 use crate::engine::test_helpers::*;
1426 use crate::engine::{CreateEntityArgs, Engine, UpdateEntityArgs};
1427
1428 use crate::storage::FilesystemMemWriter;
1429 use crate::vcs::CommitContext;
1430
1431 use indexmap::IndexMap;
1432
1433 #[test]
1434 fn with_ctx_wrappers_delegate_to_explicit_forms() {
1435 // Each *_with_ctx wrapper bundles a CommitContext and
1436 // routes through the corresponding 4-arg method. Verify
1437 // create → update → rename → delete via the wrappers
1438 // observably mutate the store the same way the explicit
1439 // forms would.
1440 let tmp = TempDir::new().unwrap();
1441 let mem_dir = tmp.path().to_path_buf();
1442 let writer = FilesystemMemWriter::new(mem_dir.clone());
1443 let mut engine = Engine::from_mounts(vec![(
1444 folder_mount("specs", mem_dir),
1445 Box::new(writer) as Box<dyn MemBackend>,
1446 )])
1447 .unwrap();
1448 let ctx = CommitContext::internal();
1449
1450 // create_entity_with_ctx
1451 let create_args = CreateEntityArgs {
1452 anchors: Vec::new(),
1453 mem: "specs".to_string(),
1454 title: "Seed".to_string(),
1455 entity_type: "spec".to_string(),
1456 sections: IndexMap::from_iter([
1457 ("identity".to_string(), "seed identity".to_string()),
1458 ("purpose".to_string(), "seed purpose".to_string()),
1459 ]),
1460 metadata: IndexMap::new(),
1461 relations: Vec::new(),
1462 dry_run: false,
1463 };
1464 let created = engine.create_entity_with_ctx(create_args, &ctx).unwrap();
1465 assert_eq!(created.title, "Seed");
1466 assert!(engine.store().get(&created.id).is_some());
1467
1468 // update_entity_with_ctx
1469 let update_args = UpdateEntityArgs {
1470 anchors: Vec::new(),
1471 id: created.id.clone(),
1472 expected_hash: Some(created.content_hash.clone()),
1473 sections: IndexMap::from_iter([("identity".to_string(), "updated".to_string())]),
1474 append_sections: IndexMap::new(),
1475 patch_sections: IndexMap::new(),
1476 metadata: IndexMap::new(),
1477 metadata_unset: Vec::new(),
1478 dry_run: false,
1479 declare_relations: Vec::new(),
1480 relations_unset: Vec::new(),
1481 anchors_unset: Vec::new(),
1482 };
1483 let updated = engine.update_entity_with_ctx(update_args, &ctx).unwrap();
1484 assert!(
1485 !updated.commit_sha.is_empty()
1486 || (updated.modified_sections.replaced.is_empty()
1487 && updated.modified_sections.appended.is_empty()
1488 && updated.modified_sections.patched.is_empty())
1489 );
1490
1491 // rename_entity_with_ctx
1492 let renamed = engine
1493 .rename_entity_with_ctx(&created.id, "Renamed", &updated.content_hash, &ctx)
1494 .unwrap();
1495 assert_ne!(renamed.old_id, renamed.new_id);
1496 assert!(engine.store().get(&renamed.new_id).is_some());
1497
1498 // delete_entity_with_ctx
1499 let deleted = engine
1500 .delete_entity_with_ctx(&renamed.new_id, &renamed.content_hash, &ctx)
1501 .unwrap();
1502 assert_eq!(deleted.id, renamed.new_id);
1503 assert!(engine.store().get(&renamed.new_id).is_none());
1504 }
1505
1506 /// Minimal on-disk MemConfig pinning `default@1.0.0`, with an
1507 /// optional pre-set mutation stamp — the carrier the stamp path
1508 /// and the boot skew check both read.
1509 fn write_config(dir: &std::path::Path, stamp: Option<memstead_schema::MutationStamp>) {
1510 let meta = dir.join(memstead_schema::MEM_META_DIR);
1511 std::fs::create_dir_all(&meta).unwrap();
1512 let mut config: memstead_schema::MemConfig =
1513 serde_json::from_str(r#"{"schema": "default@1.0.0"}"#).unwrap();
1514 config.mutation_stamp = stamp;
1515 std::fs::write(
1516 meta.join("config.json"),
1517 serde_json::to_vec_pretty(&config).unwrap(),
1518 )
1519 .unwrap();
1520 }
1521
1522 fn stamped_engine_fixture(mem_dir: std::path::PathBuf) -> Engine {
1523 Engine::from_mounts(vec![(
1524 folder_mount("specs", mem_dir.clone()),
1525 Box::new(FilesystemMemWriter::new(mem_dir)) as Box<dyn MemBackend>,
1526 )])
1527 .unwrap()
1528 }
1529
1530 fn disk_stamp(dir: &std::path::Path) -> Option<memstead_schema::MutationStamp> {
1531 let bytes =
1532 std::fs::read(dir.join(memstead_schema::MEM_META_DIR).join("config.json")).unwrap();
1533 let config: memstead_schema::MemConfig = serde_json::from_slice(&bytes).unwrap();
1534 config.mutation_stamp
1535 }
1536
1537 fn spec_create_args(title: &str) -> CreateEntityArgs {
1538 CreateEntityArgs {
1539 anchors: Vec::new(),
1540 mem: "specs".to_string(),
1541 title: title.to_string(),
1542 entity_type: "spec".to_string(),
1543 sections: IndexMap::from_iter([
1544 ("identity".to_string(), "seed identity".to_string()),
1545 ("purpose".to_string(), "seed purpose".to_string()),
1546 ]),
1547 metadata: IndexMap::new(),
1548 relations: Vec::new(),
1549 dry_run: false,
1550 }
1551 }
1552
1553 /// Criterion 3 (agent-trust plan 02): a mutation stamps the mem's
1554 /// engine-owned state with the running engine version and resolved
1555 /// schema; a read-only load writes nothing.
1556 #[test]
1557 fn mutation_writes_version_stamp_and_read_only_load_does_not() {
1558 let tmp = TempDir::new().unwrap();
1559 let mem_dir = tmp.path().to_path_buf();
1560 write_config(&mem_dir, None);
1561
1562 // Read-only session: boot and drop without mutating — the
1563 // stamp stays absent.
1564 drop(stamped_engine_fixture(mem_dir.clone()));
1565 assert!(
1566 disk_stamp(&mem_dir).is_none(),
1567 "a read-only load must not write a stamp"
1568 );
1569
1570 // A mutation stamps engine version + resolved schema.
1571 let mut engine = stamped_engine_fixture(mem_dir.clone());
1572 engine
1573 .create_entity_with_ctx(spec_create_args("Seed"), &CommitContext::internal())
1574 .unwrap();
1575 let stamp = disk_stamp(&mem_dir).expect("mutation must write the stamp");
1576 assert_eq!(stamp.engine_version, crate::build_info::full_version());
1577 assert_eq!(stamp.schema, "default@1.0.0");
1578
1579 // A second mutation under the same binary leaves the stamp at
1580 // the same value (the write path compares and no-ops).
1581 let mut engine = stamped_engine_fixture(mem_dir.clone());
1582 engine
1583 .create_entity_with_ctx(spec_create_args("Second"), &CommitContext::internal())
1584 .unwrap();
1585 let again = disk_stamp(&mem_dir).expect("stamp survives");
1586 assert_eq!(again, stamp);
1587 }
1588
1589 /// Criterion 3/4 (agent-trust plan 02): boot under a different
1590 /// binary version surfaces the warn-tier `ENGINE_VERSION_SKEW`
1591 /// naming both versions, on load warnings AND in `health()`;
1592 /// a stamp-less mem and a matching stamp are silent.
1593 #[test]
1594 fn boot_skew_warning_fires_only_on_disagreeing_stamp() {
1595 use crate::ops::WarningHint;
1596
1597 // Disagreeing stamp → warning on boot and in health.
1598 let tmp = TempDir::new().unwrap();
1599 let mem_dir = tmp.path().to_path_buf();
1600 write_config(
1601 &mem_dir,
1602 Some(memstead_schema::MutationStamp {
1603 engine_version: "0.0.1".to_string(),
1604 schema: "default@1.0.0".to_string(),
1605 }),
1606 );
1607 let engine = stamped_engine_fixture(mem_dir);
1608 let skew: Vec<_> = engine
1609 .load_warnings()
1610 .iter()
1611 .filter(|w| matches!(w, WarningHint::EngineVersionSkew { .. }))
1612 .collect();
1613 assert_eq!(skew.len(), 1, "one skewed mem, one warning: {skew:?}");
1614 if let WarningHint::EngineVersionSkew {
1615 mem,
1616 stamped_engine,
1617 running_engine,
1618 stamped_schema,
1619 } = skew[0]
1620 {
1621 assert_eq!(mem, "specs");
1622 assert_eq!(stamped_engine, "0.0.1");
1623 assert_eq!(running_engine, crate::build_info::full_version());
1624 assert_eq!(stamped_schema, "default@1.0.0");
1625 }
1626 let health = engine.health();
1627 assert!(
1628 health
1629 .warnings
1630 .iter()
1631 .any(|w| w.code() == "ENGINE_VERSION_SKEW"),
1632 "health() must surface the skew without an include gate: {:?}",
1633 health.warnings,
1634 );
1635
1636 // Matching stamp → silent.
1637 let tmp = TempDir::new().unwrap();
1638 let mem_dir = tmp.path().to_path_buf();
1639 write_config(
1640 &mem_dir,
1641 Some(memstead_schema::MutationStamp {
1642 engine_version: crate::build_info::full_version().to_string(),
1643 schema: "default@1.0.0".to_string(),
1644 }),
1645 );
1646 let engine = stamped_engine_fixture(mem_dir);
1647 assert!(
1648 !engine
1649 .load_warnings()
1650 .iter()
1651 .any(|w| matches!(w, WarningHint::EngineVersionSkew { .. })),
1652 "a matching stamp is not skew"
1653 );
1654
1655 // No stamp → silent (absence of a stamp is not skew).
1656 let tmp = TempDir::new().unwrap();
1657 let mem_dir = tmp.path().to_path_buf();
1658 write_config(&mem_dir, None);
1659 let engine = stamped_engine_fixture(mem_dir);
1660 assert!(
1661 !engine
1662 .load_warnings()
1663 .iter()
1664 .any(|w| matches!(w, WarningHint::EngineVersionSkew { .. })),
1665 "a stamp-less (pre-plan) mem boots without warning noise"
1666 );
1667 }
1668}