Skip to main content

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