Skip to main content

memstead_base/engine/mutation/
relate.rs

1//! `Engine::relate_entity` and the `relate` alias — append / remove a
2//! single edge between two entities.
3
4use std::path::Path;
5
6use crate::engine_fallback_type;
7use crate::entity::parser::parse_markdown;
8use crate::entity::store_builder::push_entities_into_store;
9use crate::entity::{Entity, EntityId, Relationship, normalise_description};
10use crate::ops::WarningHint;
11use crate::provenance::{Provenance, ProvenanceKind};
12use crate::runtime_validator::{
13    CrossMemRelCheck, RelationshipCheck, validate_cross_mem_edge, validate_rel_shape,
14    validate_rel_type,
15};
16use crate::vcs::{Actor, ClientId, CommitContext};
17use crate::workspace::MountCapability;
18use memstead_schema::SchemaRef;
19
20use super::super::{Engine, EngineError, RelateAction, RelateEntityArgs, RelateEntityOutcome};
21use super::{
22    make_stub, unknown_type_error, validate_description_posture, validate_relation_target_grammar,
23};
24
25/// A fully validated relate — every gate has passed and the source
26/// entity's next markdown is generated, but nothing has been written
27/// to the store, the disk, or the mem-repo yet. `stage_prepared_relate`
28/// performs the store-side effects and the (uncommitted) file write;
29/// the caller then commits and applies via
30/// `apply_prepared_relate_to_store`.
31pub(super) struct PreparedRelate {
32    pub(super) mount_idx: usize,
33    pub(super) source_mem: String,
34    pub(super) from: EntityId,
35    pub(super) to: EntityId,
36    pub(super) rel_type: String,
37    pub(super) action: RelateAction,
38    pub(super) file_path: String,
39    pub(super) markdown: String,
40    pub(super) warnings: Vec<WarningHint>,
41    /// `Some` when the add path must materialise a forward-reference
42    /// stub for an absent target. Prepare plans the stub; the stage
43    /// step upserts it — prepare itself never mutates the store, so a
44    /// refused batch has nothing to undo from prepares alone.
45    pub(super) stub_target: Option<EntityId>,
46    /// The planned stub's kind: `ForwardReference` for a genuinely
47    /// absent target, `LoadTime` for a storage-verified target in a
48    /// deferred mem (the stub is only the until-load representation —
49    /// flywheel W7/02). Meaningless when `stub_target` is `None`.
50    pub(super) stub_kind: crate::entity::StubKind,
51    pub(super) type_def: std::sync::Arc<memstead_schema::TypeDefinition>,
52}
53
54/// What `prepare_relate` resolved to.
55pub(super) enum RelatePrepareOutcome {
56    /// No-op path (idempotent re-add / absent remove): the complete
57    /// outcome, with its typed no-op warning and an empty
58    /// `write_id` — nothing to write or commit.
59    Done(RelateEntityOutcome),
60    /// A real edge change, validated and ready to stage.
61    Prepared(PreparedRelate),
62}
63
64/// Per-item state of a batch relate, carrying the applied item's
65/// action label from its prepared state.
66enum ItemState {
67    Applied(&'static str),
68    Noop,
69    Error,
70}
71
72/// The relate verb's action words: the applied item's own label,
73/// `noop` for an applied no-op.
74fn relate_actions(items: Vec<(EntityId, ItemState)>) -> Vec<(EntityId, String)> {
75    items
76        .into_iter()
77        .map(|(id, state)| {
78            let action = match state {
79                ItemState::Applied(label) => label,
80                ItemState::Noop => "noop",
81                ItemState::Error => unreachable!("refusal path returned above"),
82            };
83            (id, action.to_string())
84        })
85        .collect()
86}
87
88impl Engine {
89    /// Add or remove a typed relationship on `args.source`.
90    ///
91    /// Cross-mem relate is policy-gated through
92    /// [`Engine::cross_mem_link_allowed`] — the workspace's
93    /// `[cross_mem_links]` table (or per-create-rule
94    /// `default_cross_links` synthesis) decides whether the edge is
95    /// permitted. Disallowed pairings surface
96    /// [`EngineError::CrossMemLinkNotAllowed`]. Cross-mem relate
97    /// only writes the source entity's markdown — the target mem is
98    /// never written to. Auto-stub for absent targets works for
99    /// Write target mems; ReadOnly target mems reject absent
100    /// targets with [`EngineError::CrossMemTargetNotFound`] because
101    /// the engine cannot persist a stub through the read-only
102    /// boundary.
103    ///
104    /// Schema-undeclared rel types surface either as validation
105    /// errors (strict mode) or as ride-along warnings on the outcome
106    /// (open mode).
107    pub fn relate_entity(
108        &mut self,
109        args: RelateEntityArgs,
110        actor: Actor,
111        client: Option<&ClientId>,
112        note: Option<&str>,
113    ) -> Result<RelateEntityOutcome, EngineError> {
114        // Short ids on either end resolve (or refuse) before anything
115        // reads their mems; the announcements lead the warnings.
116        let mut args = args;
117        let (source, source_hint) = self.resolve_entity_id(&args.source)?;
118        args.source = source;
119        let (target, target_hint) = self.resolve_entity_id(&args.target)?;
120        args.target = target;
121        let source_mem = args.source.mem().to_string();
122        let target_mem = args.target.mem().to_string();
123
124        // Reload-before-operation: reload the source mem (and the
125        // target mem, when distinct) if a sibling advanced either
126        // ref, so the source `expected_hash` compare and the target
127        // existence/stub decisions below run against current truth.
128        // The drift notice rides the outcome's `warnings`. Hoisted
129        // out of `prepare_relate` so `batch_relate` can probe every
130        // touched mem exactly once up front instead of per entry.
131        let mut drift_warnings: Vec<WarningHint> =
132            source_hint.into_iter().chain(target_hint).collect();
133        drift_warnings.extend(self.reload_if_stale(Some(&source_mem)));
134        if target_mem != source_mem && !self.mem_is_deferred(&target_mem) {
135            // A DEFERRED target mem is deliberately not probed here:
136            // the funnel's phase-0 trigger would full-load it, and
137            // target verification must never cost a mem's load
138            // (flywheel W7/02 — the storage check below answers the
139            // existence and type questions against the branch tree /
140            // filesystem instead).
141            drift_warnings.append(&mut self.reload_if_stale(Some(&target_mem)));
142        }
143        // An ACYCLIC rel-type's cycle guard walks the whole rel-type
144        // subgraph (`would_cycle`), and a cycle can pass through any
145        // mem — an edge on a deferred (lazy, unloaded) mem's entity is
146        // invisible to a walk over the endpoint mems alone, so an add
147        // an eager boot refuses would land silently and corrupt an
148        // innocent edge on the next full load (the fourth lazy-mount
149        // grade demonstrated exactly that on a three-mem chain). The
150        // same holds for a rel-type in an `acyclic_sets` set, whose
151        // guard walks the set's UNION subgraph, and for declared
152        // aggregate signals on either endpoint's schema: the
153        // threshold-crossing diff counts edges that can originate in
154        // any mem, so a partial store silently mis-levels it. Full
155        // load before the guard; writes touching neither skip the
156        // cost.
157        let cycle_guard_needs_full = !args.remove
158            && self.schemas.get(&source_mem).is_some_and(|s| {
159                s.relationship_acyclic(&args.rel_type)
160                    || s.acyclic_set_containing(&args.rel_type).is_some()
161            });
162        let signal_diff_needs_full = [source_mem.as_str(), args.target.mem()].iter().any(|m| {
163            self.schemas
164                .get(*m)
165                .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
166        });
167        if cycle_guard_needs_full || signal_diff_needs_full {
168            self.ensure_mems_loaded(None);
169        }
170
171        let dry_run = args.dry_run;
172        let prepared = match self.prepare_relate(args, drift_warnings)? {
173            RelatePrepareOutcome::Done(outcome) => {
174                // Derivation re-baseline: on a
175                // derivation-declared rel-type, the duplicate-add
176                // no-op's ONE effect is refreshing the edge's
177                // baseline to the target's current hash — the agent's
178                // explicit "reviewed, still holds". Sidecar-only:
179                // `_hash` unchanged, the edge unchanged; the response
180                // states the refresh (warning + the sidecar commit's
181                // sha) instead of a bare no-op. Undeclared rel-types
182                // keep today's exact no-op response; rehearsals
183                // refresh nothing.
184                if !dry_run
185                    && matches!(
186                        outcome.action,
187                        super::super::RelateAction::NoOpAlreadyPresent
188                    )
189                {
190                    return self.refresh_derivation_baseline_on_noop(outcome, actor, client, note);
191                }
192                return Ok(outcome);
193            }
194            RelatePrepareOutcome::Prepared(p) => p,
195        };
196
197        // Rehearsal: the full validation stage ran (identical refusals
198        // and warnings, would-be stub included via the prepared
199        // AUTO_STUB_CREATED warning) — stop before any write. `_hash`
200        // reports the PROSPECTIVE post-write hash; `write_id` stays
201        // empty (the marker form). Nothing staged, committed, or
202        // stubbed.
203        if dry_run {
204            let parse_result = parse_markdown(
205                &prepared.markdown,
206                &prepared.file_path,
207                prepared.type_def.as_ref(),
208                &prepared.source_mem,
209            )
210            .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
211            // A rehearsal demands no note: `NOTE_MISSING` attributes a
212            // write that landed without provenance, and nothing lands
213            // here (create and update rehearse the same way; a relate
214            // rehearsal once carried the nudge and so reported a
215            // provenance gap on a commit that did not exist).
216            let warnings = prepared.warnings;
217            return Ok(RelateEntityOutcome {
218                from: prepared.from,
219                to: prepared.to,
220                rel_type: prepared.rel_type,
221                action: prepared.action,
222                content_hash: parse_result.entity.content_hash,
223                write_id: String::new(),
224                source: "explicit".to_string(),
225                orphan_stubs_removed: Vec::new(),
226                warnings,
227            });
228        }
229
230        // Aggregate signals: capture both endpoints' levels before the
231        // store mutates — the entities a relate can move are exactly
232        // the edge's endpoints. Diffed after the write below.
233        let signal_snapshot = crate::ops::signals::snapshot_levels(
234            &self.store,
235            &self.schemas,
236            [&prepared.from, &prepared.to],
237        );
238
239        self.stage_prepared_relate(&prepared)?;
240
241        // Derivation baseline: an explicit add
242        // on a declared rel-type records the target's CURRENT content
243        // hash ("" for a just-stubbed absent target — deriving from
244        // nothing, honestly); a remove prunes the row. Staged into
245        // the same pending set so baseline and edge ride one commit.
246        if let Some(schema) = self.schemas.get(&prepared.source_mem)
247            && super::rel_type_declares_derivation(schema, &prepared.rel_type)
248        {
249            let backend = self.mounts[prepared.mount_idx].backend.as_ref();
250            let (from, rel, to) = (
251                prepared.from.to_string(),
252                prepared.rel_type.clone(),
253                prepared.to.to_string(),
254            );
255            match prepared.action {
256                RelateAction::Added => {
257                    let hash = self
258                        .store
259                        .get(&prepared.to)
260                        .map(|e| e.content_hash.clone())
261                        .unwrap_or_default();
262                    super::stage_derivation_sidecar(backend, |s| s.set(&from, &rel, &to, &hash))?;
263                }
264                RelateAction::Removed => {
265                    super::stage_derivation_sidecar(backend, |s| s.remove(&from, &rel, &to))?;
266                }
267                _ => {}
268            }
269        }
270
271        let backend = self.mounts[prepared.mount_idx].backend.as_ref();
272        let commit_subject = format!("memstead: relate {}", prepared.from);
273        let ctx = self.commit_context(
274            Some("relate_entity"),
275            actor,
276            client.cloned(),
277            note.map(String::from),
278        );
279        let write_id = backend.commit(&commit_subject, &ctx)?;
280
281        backend.append_provenance(
282            &Provenance::new(
283                std::time::SystemTime::now(),
284                ProvenanceKind::Relate,
285                Some(prepared.from.to_string()),
286                actor,
287                client.cloned(),
288                note.map(String::from),
289            )
290            .with_role(self.current_role)
291            .with_identity(self.current_identity.clone()),
292        )?;
293
294        self.record_self_write(prepared.mount_idx, &write_id);
295        let stamp_warnings = self.stamp_mutation_versions(prepared.mount_idx);
296
297        let content_hash = self.apply_prepared_relate_to_store(&prepared)?;
298
299        // On the `--remove` path, the edge we just dropped may
300        // have been the last incoming edge to a stub. The orphan-stub
301        // GC hook fired from `memstead_delete` already; mirror it here so
302        // every mutation that can leave orphans cleans them up.
303        // Scoped sweep — only inspect the just-severed target. The
304        // only possible new orphan from a relate-remove is the
305        // target whose incoming edge we removed; checking the entire
306        // store would catch pre-existing orphans which aren't this
307        // mutation's responsibility (and which `memstead_delete`'s full
308        // sweep also leaves alone before its own removal). Funnels
309        // through the shared `gc_orphan_stubs_among` predicate so the
310        // relate-remove, delete, and update-via-alias-resync paths
311        // can't drift on what counts as a GC-able orphan.
312        let orphan_stubs_removed: Vec<EntityId> =
313            if matches!(prepared.action, RelateAction::Removed) {
314                super::gc_orphan_stubs_among(&mut self.store, std::iter::once(&prepared.to))
315            } else {
316                Vec::new()
317            };
318
319        self.invalidate_communities();
320        // Incremental (flywheel W8/01): only the SOURCE entity's file
321        // was rewritten; stub targets and GC'd orphan stubs were never
322        // indexed.
323        self.maintain_search_indexes(std::slice::from_ref(&prepared.from));
324
325        let PreparedRelate {
326            from,
327            to,
328            rel_type,
329            action,
330            mut warnings,
331            ..
332        } = prepared;
333
334        warnings.extend(stamp_warnings);
335
336        // Signal crossings ride the out-of-band warning channel beside
337        // the success payload — never error-shaped, never changing the
338        // mutation's success semantics.
339        warnings.extend(crate::ops::signals::crossing_warnings(
340            &self.store,
341            &self.schemas,
342            &signal_snapshot,
343        ));
344
345        // `require_notes` provenance nudge — single engine-level
346        // enforcement point. Only reached on the real-commit path
347        // (Added / Removed); the NoOpAlreadyPresent / NoOpAbsent branches
348        // return early above with an empty `write_id` and never demand
349        // a note (nothing landed to attribute).
350        if let Some(w) = self.note_missing_warning("relate_entity", note) {
351            warnings.push(w);
352        }
353
354        Ok(RelateEntityOutcome {
355            from,
356            to,
357            rel_type,
358            action,
359            content_hash,
360            write_id,
361            source: "explicit".to_string(),
362            warnings,
363            orphan_stubs_removed,
364        })
365    }
366
367    /// The duplicate-add re-baseline. Called
368    /// from the `NoOpAlreadyPresent` path when the rel-type is
369    /// derivation-declared: stages a sidecar-only refresh of the
370    /// edge's baseline to the target's current hash and commits it
371    /// (the anchor-only-update precedent — a real persisted effect
372    /// rides a real commit), then returns the outcome with the
373    /// refresh STATED (`DERIVATION_BASELINE_REFRESHED` warning + the
374    /// sidecar commit's sha). `_hash` and the edge are untouched. On
375    /// an undeclared rel-type the outcome passes through unchanged —
376    /// today's exact no-op response.
377    fn refresh_derivation_baseline_on_noop(
378        &mut self,
379        mut outcome: RelateEntityOutcome,
380        actor: Actor,
381        client: Option<&ClientId>,
382        note: Option<&str>,
383    ) -> Result<RelateEntityOutcome, EngineError> {
384        let source_mem = outcome.from.mem().to_string();
385        let declared = self
386            .schemas
387            .get(&source_mem)
388            .is_some_and(|s| super::rel_type_declares_derivation(s, &outcome.rel_type));
389        if !declared {
390            return Ok(outcome);
391        }
392        let Some(mount_idx) = self.mounts.iter().position(|m| m.mount.mem == source_mem) else {
393            return Ok(outcome);
394        };
395        let hash = self
396            .store
397            .get(&outcome.to)
398            .map(|e| e.content_hash.clone())
399            .unwrap_or_default();
400        let (from, rel, to) = (
401            outcome.from.to_string(),
402            outcome.rel_type.clone(),
403            outcome.to.to_string(),
404        );
405        let backend = self.mounts[mount_idx].backend.as_ref();
406        super::stage_derivation_sidecar(backend, |s| s.set(&from, &rel, &to, &hash))?;
407        let ctx = self.commit_context(
408            Some("relate_entity"),
409            actor,
410            client.cloned(),
411            note.map(String::from),
412        );
413        let write_id = backend.commit(
414            &format!("memstead: derivation re-baseline {}", outcome.from),
415            &ctx,
416        )?;
417        self.record_self_write(mount_idx, &write_id);
418        // `relate_entity` returns early into this path, so the stamp call on
419        // the ordinary path never runs and its report has to be collected
420        // here (found by the re-grade).
421        outcome
422            .warnings
423            .extend(self.stamp_mutation_versions(mount_idx));
424        outcome.write_id = write_id;
425        outcome
426            .warnings
427            .push(WarningHint::DerivationBaselineRefreshed {
428                from: outcome.from.clone(),
429                rel_type: outcome.rel_type.clone(),
430                to: outcome.to.clone(),
431            });
432        Ok(outcome)
433    }
434
435    /// Every validation gate and the mutation plan for one relate —
436    /// shared verbatim by the single-item path above and
437    /// [`Self::batch_relate`], so batching can never drift from the
438    /// single-item gates. Never mutates the store, writes no file,
439    /// commits nothing: refusals are side-effect-free by
440    /// construction. The reload-before-operation probe is the
441    /// caller's job (hoisted so a batch probes each mem once).
442    fn prepare_relate(
443        &mut self,
444        args: RelateEntityArgs,
445        mut drift_warnings: Vec<WarningHint>,
446    ) -> Result<RelatePrepareOutcome, EngineError> {
447        let mut args = args;
448        let source_mem = args.source.mem().to_string();
449        let target_mem = args.target.mem().to_string();
450
451        // Target-id grammar gate (shared helper, also called from
452        // `Engine::create_entity` for inline relations so both
453        // gateways trip the same envelope). Source-id grammar is
454        // implicit — a malformed source surfaces as `ENTITY_NOT_FOUND`
455        // because it can never have been created.
456        //
457        // The grammar check runs BEFORE the cross-mem policy check:
458        // a bare-string target with no `--` separator (e.g.
459        // `bad target`) parses as `mem: ""`, `path: "bad target"`,
460        // and without this ordering would surface a cross-mem
461        // policy error against an empty mem name — pointing the
462        // agent at workspace policy when the actual fix is a
463        // malformed id. The grammar check is intrinsic to the target
464        // id; it doesn't need to know which mem the target lives
465        // in.
466        validate_relation_target_grammar(&args.target)?;
467
468        // Track whether the cross-mem target's mem is unmounted —
469        // we deferred the warning emission to the canonical
470        // `warnings` vec initialisation below, but the policy / RO
471        // gates fire first to keep the refusal-before-warning ordering:
472        // a policy refusal preempts the warning.
473        let mut target_mem_uncreated = false;
474        if source_mem != target_mem {
475            // Policy gates *new* edges only — remove is structurally
476            // cleanup. The same convention governs the acyclic, shape,
477            // and schema gates below (each one wraps `if !args.remove`).
478            // Without this bypass, a workspace whose cross-mem grant
479            // was revoked while edges still existed gets wedged: the
480            // grant must be re-introduced just to delete the data it
481            // permitted, then re-revoked. The gate-on-add
482            // rule holds because `cross_mem_links: named` semantically reads
483            // as "only these new edges may be created", not "these
484            // edges may exist."
485            if !args.remove {
486                super::validate_cross_mem_add_policy(self, &source_mem, &args.target)?;
487            }
488            // ReadOnly target mem: the engine has no write access to
489            // persist a stub there, so the target must already exist
490            // before relate. (Same-mem and cross-mem-to-Write
491            // both retain the auto-stub mechanic below.) The add path
492            // already refused above via the shared funnel; this check
493            // stays unconditional so the remove path keeps its
494            // pre-funnel behaviour.
495            if let Some(mount) = self.mount(&target_mem)
496                && mount.capability == MountCapability::ReadOnly
497                && !self.store.contains(&args.target)
498                && !matches!(
499                    super::probe_deferred_target(self, &args.target)?,
500                    super::DeferredTargetProbe::Exists
501                )
502            {
503                return Err(EngineError::CrossMemTargetNotFound {
504                    target_id: args.target.to_string(),
505                    target_mem: target_mem.clone(),
506                });
507            }
508            // The target mem isn't mounted in the workspace
509            // at all. Policy admitted the edge so the relate must
510            // succeed and auto-stub; surface a warning so the operator
511            // can distinguish a typo from a deliberate forward
512            // reference. The auto-stub still lands via the
513            // `AutoStubCreated` path below; this layered warning is
514            // additive observability.
515            if self.mount(&target_mem).is_none() {
516                target_mem_uncreated = true;
517            }
518        }
519
520        // Canonicalise rel_type to UPPER_SNAKE_CASE so the schema lookup,
521        // stored edge, and response all see the same wire-contract form
522        // ("case-insensitive on input"). Syntax errors (non-letter
523        // characters) fall through to the strict-mode schema check below,
524        // which surfaces them as INVALID_REL_TYPE with the declared
525        // vocabulary.
526        if let Ok(canonical) = crate::entity::id::validate_rel_type(&args.rel_type) {
527            args.rel_type = canonical;
528        }
529        // Normalise the description at the boundary so empty /
530        // whitespace-only strings collapse to `None` before the
531        // posture check and before the renderer ever sees them.
532        args.description = normalise_description(args.description.as_deref());
533
534        let mount_idx = self
535            .mounts
536            .iter()
537            .position(|m| m.mount.mem == source_mem)
538            .ok_or_else(|| self.unknown_mem_error(&source_mem))?;
539        if self.mounts[mount_idx].mount.capability != MountCapability::Write {
540            return Err(EngineError::ReadOnlyMount(source_mem));
541        }
542
543        let schema = self
544            .schemas
545            .get(&source_mem)
546            .expect("schema present for every registered mount");
547
548        // Determine whether this is a cross-mem edge to a mem
549        // pinning a schema with a *different name*. Same-name (any
550        // version pair — a schema name is a domain) and same-mem
551        // stay on the intra-mem validation path, governed by the
552        // source mem's pinned version; cross-different-schema
553        // routes vocabulary and shape checks through the source
554        // schema's `cross_mem_relationships:` section.
555        //
556        // If the target mem is not mounted (unknown to the engine
557        // — typically only in malformed callers), there is no target
558        // schema to consult and the validation falls back to the
559        // intra-mem path. Real workspaces always mount the target
560        // mem before relating.
561        let target_schema_ref: Option<SchemaRef> = if source_mem == target_mem {
562            None
563        } else {
564            // Loaded mems answer from the schema catalogue; an
565            // unmounted mem with discoverable storage answers from
566            // its stored config's pin (flywheel W7/02) — see
567            // `target_schema_ref_for_routing`.
568            super::target_schema_ref_for_routing(self, &target_mem)
569        };
570        let cross_mem_different = match (&target_schema_ref, schema.id()) {
571            (Some(target), (src_name, _)) => target.name != src_name,
572            (None, _) => false,
573        };
574
575        let mut warnings: Vec<WarningHint> = Vec::new();
576        // Reload-before-operation drift notice, surfaced first.
577        warnings.append(&mut drift_warnings);
578        // Vocabulary check: intra-mem flow consults the source
579        // schema's `relationships.definitions`; cross-different-schema
580        // skips this entirely (the cross-mem entry's `definitions`
581        // are the sole authority — see the add-path check below).
582        if !cross_mem_different {
583            match validate_rel_type(&args.rel_type, schema.as_ref())? {
584                RelationshipCheck::Ok => {}
585                RelationshipCheck::OpenWarning(message) => {
586                    warnings.push(WarningHint::UndeclaredRelationshipOpen {
587                        rel_type: args.rel_type.clone(),
588                        message,
589                    });
590                }
591            }
592        }
593
594        // Clone the source entity early so subsequent mutable
595        // operations on `self.store` (the stub-creation upsert below)
596        // don't conflict with the borrow.
597        let entity: Entity = self
598            .store
599            .get(&args.source)
600            .ok_or_else(|| EngineError::NotFound {
601                id: args.source.to_string(),
602            })?
603            .clone();
604
605        // Stubs have no `entity_type`, so the schema lookup below
606        // would surface a cryptic `UnknownType { name: "" }`. Surface
607        // the actual constraint instead — a stub source has no body
608        // to write to and no schema-resolved type to validate
609        // against. Promotion via `memstead_create` adopts the stub's
610        // incoming references and lets the agent re-issue the relate
611        // against a real entity.
612        if entity.stub {
613            return Err(EngineError::StubCannotRelate {
614                id: args.source.to_string(),
615            });
616        }
617
618        let target_type = self
619            .store
620            .get(&args.target)
621            .map(|e| e.entity_type.clone())
622            .filter(|t| !t.is_empty());
623        // Storage verification for a target in a DEFERRED mem
624        // (flywheel W7/02): the store cannot answer for an unloaded
625        // mem, so existence comes from the cheap storage probe and —
626        // when the shape check will need it — the type from the one
627        // resolved blob. Neither triggers the mem's load.
628        let target_verified_in_storage = if target_type.is_none() && target_mem != source_mem {
629            matches!(
630                super::probe_deferred_target(self, &args.target)?,
631                super::DeferredTargetProbe::Exists
632            )
633        } else {
634            false
635        };
636        let target_type = match target_type {
637            Some(t) => Some(t),
638            None if target_verified_in_storage && !args.remove => {
639                super::peek_deferred_target_type(self, &args.target)?
640            }
641            None => None,
642        };
643        if target_verified_in_storage {
644            // A verified target's mem is not "uncreated" — for an
645            // unmounted mem the discovery hook just found its storage
646            // and the entity in it; the layered warning would claim
647            // the opposite.
648            target_mem_uncreated = false;
649        }
650        // Shape validation is add-only. Edges that violated the
651        // schema's shape before constraints landed must remain
652        // removable through `memstead_relate remove=true` — otherwise the
653        // graph carries unfixable shape drift. The health scan
654        // surfaces the existing violations so an agent can run the
655        // cleanup pass. The same posture applies to cross-mem
656        // vocabulary: the cleanup path stays permissive so
657        // pre-tightening edges can be dropped without first
658        // re-declaring them in the source schema.
659        // Per-edge description posture (intra-mem and cross-mem).
660        // Add-only — the remove path stays permissive so pre-tightening
661        // edges remain droppable (mirrors the shape-validation posture
662        // below). Posture is a no-op for rel-types not declared in the
663        // schema; the vocabulary gate runs first and surfaces those.
664        if !args.remove {
665            validate_description_posture(
666                self,
667                &args.rel_type,
668                args.description.as_deref(),
669                &source_mem,
670                &target_mem,
671                &args.source,
672                &args.target,
673            )?;
674            // Refuse
675            // explicit `memstead_relate` calls for rel-types whose schema
676            // declares `manual_authoring: forbidden`. The body-link →
677            // relation alias machinery synthesises these relations
678            // from wiki-links via a separate path that doesn't go
679            // through this validator, so the alias contract stays
680            // intact.
681            super::validate_manual_authoring_posture(
682                self,
683                &args.rel_type,
684                &source_mem,
685                &args.source,
686                &args.target,
687            )?;
688        }
689
690        if !args.remove {
691            if cross_mem_different {
692                // Safe-by-construction: `cross_mem_different` only
693                // becomes true when `target_schema_ref` is `Some`.
694                let target_ref = target_schema_ref
695                    .as_ref()
696                    .expect("target_schema_ref is Some when cross_mem_different");
697                match validate_cross_mem_edge(
698                    &args.rel_type,
699                    entity.entity_type.as_str(),
700                    target_type.as_deref(),
701                    schema.as_ref(),
702                    target_ref,
703                ) {
704                    CrossMemRelCheck::Ok => {}
705                    CrossMemRelCheck::EdgeNotDeclared => {
706                        let (src_name, src_version) = schema.id();
707                        return Err(EngineError::CrossMemEdgeNotDeclared {
708                            source_schema: SchemaRef::new(src_name, src_version).as_display(),
709                            target_schema: target_ref.as_display(),
710                            rel_type: args.rel_type.clone(),
711                            from_id: args.source.to_string(),
712                            to_id: args.target.to_string(),
713                        });
714                    }
715                    CrossMemRelCheck::Invalid(v) => {
716                        return Err(EngineError::Validation(v));
717                    }
718                }
719            } else {
720                validate_rel_shape(
721                    &args.rel_type,
722                    entity.entity_type.as_str(),
723                    target_type.as_deref(),
724                    schema.as_ref(),
725                )?;
726            }
727        }
728
729        if let Some(expected) = args.expected_hash.as_deref()
730            && entity.content_hash != expected
731        {
732            return Err(EngineError::HashMismatch {
733                id: args.source.to_string(),
734                current: entity.content_hash.clone(),
735                is_stub: entity.stub,
736            });
737        }
738
739        // Cycle family on the real-add path — the self-loop refusal
740        // (listed no-self-loop rel-types) and the acyclic long-cycle refusal,
741        // via the shared gate every edge-writing verb runs
742        // (`validate_edge_acyclicity`). Skipped on the remove path:
743        // removal can only break cycles, never close one.
744        if !args.remove {
745            super::validate_edge_acyclicity(
746                &self.store,
747                schema,
748                &args.source,
749                entity.entity_type.as_str(),
750                &args.target,
751                &args.rel_type,
752            )?;
753        }
754
755        let type_def = schema
756            .get_type(&entity.entity_type)
757            .ok_or_else(|| unknown_type_error(schema, &entity.entity_type))?;
758
759        let mut next = entity.clone();
760        let already = next
761            .relationships
762            .iter()
763            .position(|r| r.rel_type == args.rel_type && r.target == args.target);
764
765        // Alias-existence RESTRICT semantics on the remove path. Under
766        // set-membership semantics a body wiki-link `[[X]]` aliases the
767        // *set* of relations to X; removing one relation is fine as
768        // long as another survives. Refuse only when the removal would
769        // empty the relation-set to `b` while body wiki-links to `b`
770        // are still present in the source entity's section bodies.
771        if args.remove && already.is_some() {
772            let other_relation_to_target_exists = entity
773                .relationships
774                .iter()
775                .any(|r| r.target == args.target && r.rel_type != args.rel_type);
776            if !other_relation_to_target_exists {
777                // Read-side scan over the source entity's existing
778                // body. Use the lenient decoder so on-disk drift on
779                // pre-strict entities continues to surface in the
780                // body-link survival check — the mutation gate sits
781                // on the create/update path, not on a relate-remove
782                // scan of historical state.
783                let mut surviving_sections: Vec<String> = Vec::new();
784                for (section_key, body) in entity.sections.iter() {
785                    let inline_targets =
786                        crate::entity::parser::extract_inline_links_lenient(body, &source_mem);
787                    if inline_targets.iter().any(|t| t == &args.target) {
788                        surviving_sections.push(section_key.clone());
789                    }
790                }
791                if !surviving_sections.is_empty() {
792                    return Err(EngineError::RelationHasBodyLinks {
793                        from_id: args.source.to_string(),
794                        to_id: args.target.to_string(),
795                        rel_type: args.rel_type.clone(),
796                        body_links: surviving_sections,
797                    });
798                }
799            }
800        }
801
802        let action = if args.remove {
803            match already {
804                Some(idx) => {
805                    next.relationships.remove(idx);
806                    RelateAction::Removed
807                }
808                None => RelateAction::NoOpAbsent,
809            }
810        } else {
811            match already {
812                Some(_) => RelateAction::NoOpAlreadyPresent,
813                None => {
814                    next.relationships.push(Relationship {
815                        rel_type: args.rel_type.clone(),
816                        target: args.target.clone(),
817                        description: normalise_description(args.description.as_deref()),
818                    });
819                    RelateAction::Added
820                }
821            }
822        };
823
824        // Block-tier `required_outgoing` on the remove path: dropping
825        // this edge must not leave a `severity: block` block
826        // unsatisfied — the same refusal create/update raise when the
827        // written edge set falls short. Warn-tier blocks stay silent
828        // here (the health sweep owns standing warn-tier findings;
829        // relate-remove has never warned and the no-noise rule keeps
830        // it that way).
831        if matches!(action, RelateAction::Removed) {
832            let blocked: Vec<_> =
833                crate::ops::health::unsatisfied_required_outgoing(&next, type_def.as_ref())
834                    .into_iter()
835                    .filter(|b| b.severity == memstead_schema::ConstraintSeverity::Block)
836                    .collect();
837            if !blocked.is_empty() {
838                return Err(EngineError::RequiredOutgoingUnsatisfied {
839                    entity_type: next.entity_type.clone(),
840                    entity_id: args.source.to_string(),
841                    missing: blocked,
842                });
843            }
844            // Edge-dependent declared constraints: removing this edge
845            // must not un-back a block-tier `enum_from_neighbour`
846            // value (the edge to the enumerating neighbour is what
847            // backs it). Edge-independent forms are filtered out —
848            // their verdict is identical before and after a relate,
849            // so refusing here would block unrelated repair work.
850            // `None` check provider: only `enum_from_neighbour` is
851            // kept below, so the checks-gated form never evaluates on
852            // this path (a relate changes edges, not the gated field).
853            let blocked: Vec<_> = crate::ops::health::unsatisfied_constraints(
854                &self.store,
855                &next,
856                type_def.as_ref(),
857                Some(&args.source),
858                None,
859            )
860            .into_iter()
861            .filter(|v| {
862                matches!(
863                    v,
864                    crate::ops::health::UnsatisfiedConstraint::EnumFromNeighbour { .. }
865                ) && v.severity() == memstead_schema::ConstraintSeverity::Block
866            })
867            .collect();
868            if !blocked.is_empty() {
869                return Err(EngineError::ConstraintUnsatisfied {
870                    entity_type: next.entity_type.clone(),
871                    entity_id: args.source.to_string(),
872                    violations: blocked,
873                });
874            }
875        }
876
877        // Plan a stub for an absent target on the real-add path.
878        // Skipped on no-op paths (NoOpAlreadyPresent / NoOpAbsent — the
879        // edge isn't actually being added) and on the remove path (the
880        // edge being dropped, no need to manifest the target). This is
881        // the engine's target-materialisation step on the add path;
882        // prepare only records the decision — the upsert happens in
883        // `stage_prepared_relate` so prepare stays store-neutral.
884        // The auto-stub surfaces as a typed `AutoStubCreated` warning
885        // on the response's `warnings[]` — the deprecated top-level
886        // `stub_warning` field that pre-Item-03 carried this fact has
887        // been removed, so every diagnostic now follows the uniform
888        // `{ code, message, details }` warning shape.
889        let mut stub_target: Option<EntityId> = None;
890        let mut stub_kind = crate::entity::StubKind::ForwardReference;
891        if matches!(action, RelateAction::Added) && !self.store.contains(&args.target) {
892            stub_target = Some(args.target.clone());
893            if target_verified_in_storage {
894                // The target EXISTS — storage said so. The in-store
895                // stub is only plan 01's until-load representation of
896                // a cross-mem link into a deferred mem (it resolves
897                // when the mem loads), so it carries the load-time
898                // kind and no AUTO_STUB_CREATED warning: that warning
899                // tells an agent the target awaits creation, which
900                // would be false here.
901                stub_kind = crate::entity::StubKind::LoadTime;
902            } else {
903                // Rehearsal honesty: on the dry-run path nothing is
904                // written, so the warning's `pending` flag branches the
905                // message to the would-be form — the code stays
906                // AUTO_STUB_CREATED either way.
907                warnings.push(WarningHint::AutoStubCreated {
908                    stub_id: args.target.clone(),
909                    pending: args.dry_run,
910                });
911            }
912            // If the target mem is unmounted, the
913            // auto-stub above has no `_mem_schema` resolution. Layer
914            // the typed mem-uncreated warning alongside the
915            // `AutoStubCreated` so the operator sees both signals.
916            // (Never true on the verified branch — a deferred mem is
917            // mounted by definition.)
918            if target_mem_uncreated {
919                warnings.push(WarningHint::CrossMemTargetMemUncreated {
920                    from_mem: source_mem.clone(),
921                    to_mem: target_mem.clone(),
922                    target_id: args.target.clone(),
923                });
924            }
925        }
926
927        // No-op paths skip the disk write so the provenance log doesn't
928        // record a non-event. Return the live `content_hash` so callers
929        // can chain follow-ups without refetching. Surface the no-op as
930        // a typed warning so an agent re-running a pipeline can tell the
931        // call didn't change the graph (mirrors full's wire shape).
932        if matches!(
933            action,
934            RelateAction::NoOpAlreadyPresent | RelateAction::NoOpAbsent
935        ) {
936            match action {
937                RelateAction::NoOpAlreadyPresent => {
938                    warnings.push(WarningHint::DuplicateRelationship {
939                        rel_type: args.rel_type.clone(),
940                        from: args.source.clone(),
941                        to: args.target.clone(),
942                    });
943                }
944                RelateAction::NoOpAbsent => {
945                    warnings.push(WarningHint::NoSuchRelationship {
946                        rel_type: args.rel_type.clone(),
947                        from: args.source.clone(),
948                        to: args.target.clone(),
949                    });
950                }
951                _ => unreachable!(),
952            }
953            return Ok(RelatePrepareOutcome::Done(RelateEntityOutcome {
954                from: args.source,
955                to: args.target,
956                rel_type: args.rel_type,
957                action,
958                content_hash: entity.content_hash.clone(),
959                write_id: String::new(),
960                source: "explicit".to_string(),
961                warnings,
962                // No-op branch: nothing changed in the graph, so the
963                // orphan-stub sweep can't have anything to collect.
964                orphan_stubs_removed: Vec::new(),
965            }));
966        }
967
968        // The relate path rewrites the on-disk file (the
969        // `## Relationships` section materialises from
970        // `next.relationships`), so the schema's `auto_timestamp`
971        // metadata (default schema: `last_modified`) bumps to the
972        // current ISO. Only fires on the commit-producing branch —
973        // the no-op early-return above skips this block, so an
974        // idempotent re-add or NoOpAbsent never advances the stamp.
975        let today = self.now_iso();
976        super::auto_stamp_timestamps(&mut next, type_def.as_ref(), &today);
977
978        let file_path = next.file_path.clone();
979        let markdown = super::render_for_write(&next, type_def.as_ref())?;
980
981        Ok(RelatePrepareOutcome::Prepared(PreparedRelate {
982            mount_idx,
983            source_mem,
984            from: args.source,
985            to: args.target,
986            rel_type: args.rel_type,
987            action,
988            file_path,
989            markdown,
990            warnings,
991            stub_target,
992            stub_kind,
993            type_def,
994        }))
995    }
996
997    /// Perform a prepared relate's pre-commit side effects: upsert the
998    /// planned forward-reference stub (if any) and write the source
999    /// entity's regenerated markdown into the backend's pending
1000    /// buffer. Nothing is committed; a caller that aborts afterwards
1001    /// rolls back with a store snapshot + `discard_all_pending`.
1002    fn stage_prepared_relate(&mut self, p: &PreparedRelate) -> Result<(), EngineError> {
1003        if let Some(stub_id) = &p.stub_target {
1004            self.store
1005                .upsert(stub_id.clone(), make_stub(stub_id, p.stub_kind.clone()));
1006        }
1007        self.mounts[p.mount_idx]
1008            .backend
1009            .write_entity(Path::new(&p.file_path), p.markdown.as_bytes())?;
1010        Ok(())
1011    }
1012
1013    /// Parse the prepared markdown back and push it into the store
1014    /// (replacing the pre-mutation source entity), then re-run the
1015    /// alias-edge remap. Returns the new `content_hash`. In the
1016    /// single-item path this runs after the commit (preserving the
1017    /// pre-split ordering); `batch_relate` runs it immediately after
1018    /// staging each entry so later entries in the same batch validate
1019    /// against this entry's effect — applied-in-order semantics.
1020    fn apply_prepared_relate_to_store(
1021        &mut self,
1022        p: &PreparedRelate,
1023    ) -> Result<String, EngineError> {
1024        let parse_result = parse_markdown(
1025            &p.markdown,
1026            &p.file_path,
1027            p.type_def.as_ref(),
1028            &p.source_mem,
1029        )
1030        .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
1031        let content_hash = parse_result.entity.content_hash.clone();
1032        let fallback = engine_fallback_type();
1033        push_entities_into_store(&mut self.store, vec![parse_result], fallback.as_ref(), None);
1034        crate::entity::store_builder::remap_alias_target_edge_sources(
1035            &mut self.store,
1036            &self.schemas,
1037        );
1038        Ok(content_hash)
1039    }
1040
1041    /// Atomic batch relate — the edge-side sibling of
1042    /// [`Self::batch_create`] / [`Self::batch_update`]. One list
1043    /// carrying both additions and removals, **applied in order**:
1044    /// each entry validates against the graph state produced by every
1045    /// prior valid entry (an add followed by a remove of the same edge
1046    /// nets to no edge; an acyclic check sees edges added earlier in
1047    /// the same batch). Per-entry shape mirrors what `relate` accepts.
1048    ///
1049    /// - **All-or-nothing, report-all.** A single invalid entry
1050    ///   refuses the whole batch — no edge changes, no head movement —
1051    ///   and the refusal identifies EVERY failing entry with its typed
1052    ///   `{code, message, details}` envelope, bounded at
1053    ///   [`Self::BATCH_ERROR_REPORT_CAP`] with `errors_suppressed`
1054    ///   counting the rest. An entry after a failing one validates
1055    ///   against the state as of the prior *valid* entries, so a
1056    ///   dependent entry may cascade — every reported code is still a
1057    ///   true refusal of the submitted file.
1058    /// - **One commit per touched mem** (subject
1059    ///   `memstead: batch-relate (N edges)`), per-entry provenance
1060    ///   notes, exactly like the rest of the family. No-op entries
1061    ///   (idempotent re-add / absent remove) report `"noop"` and
1062    ///   produce no write.
1063    /// - Orphan-stub GC runs over every removed edge's target after
1064    ///   the commit, same predicate as the single-item path (the
1065    ///   collected ids are not part of `BatchResult`'s fixed family
1066    ///   shape).
1067    ///
1068    /// **Rehearsal** (`dry_run: true`): the FULL in-order validation
1069    /// pass runs — each entry staged against the state its
1070    /// predecessors produced, identical refusals, identical report-all
1071    /// envelope — then the batch stops before any commit and rolls the
1072    /// staged state back. A legal batch returns the would-be receipt
1073    /// (per-entry actions, would-be `orphan_stubs_removed` computed on
1074    /// the staged state) with the marker form's empty `write_id`; an
1075    /// illegal one returns the same refusal a real call would. No
1076    /// edge, stub, or commit lands.
1077    pub fn batch_relate(
1078        &mut self,
1079        relates: Vec<(RelateEntityArgs, Option<String>)>,
1080        actor: Actor,
1081        client: Option<&ClientId>,
1082        dry_run: bool,
1083    ) -> Result<crate::ops::BatchResult, EngineError> {
1084        if relates.is_empty() {
1085            return Ok(super::batch_empty());
1086        }
1087
1088        // Reload every touched mem (sources and targets) once, up
1089        // front — the per-entry probe is hoisted out of
1090        // `prepare_relate` for exactly this.
1091        // Short ids on either end resolve once, before the touched-mem
1092        // probe reads each item's mems; an item that does not resolve
1093        // fails as its own error below, never the whole batch.
1094        let mut short_hints: Vec<WarningHint> = Vec::new();
1095        let mut short_errors: Vec<(usize, EngineError)> = Vec::new();
1096        let relates: Vec<(RelateEntityArgs, Option<String>)> = relates
1097            .into_iter()
1098            .enumerate()
1099            .map(|(i, (mut a, n))| {
1100                match self.resolve_entity_id(&a.source) {
1101                    Ok((s, hint)) => {
1102                        a.source = s;
1103                        short_hints.extend(hint);
1104                    }
1105                    Err(e) => short_errors.push((i, e)),
1106                }
1107                match self.resolve_entity_id(&a.target) {
1108                    Ok((t, hint)) => {
1109                        a.target = t;
1110                        short_hints.extend(hint);
1111                    }
1112                    Err(e) => short_errors.push((i, e)),
1113                }
1114                (a, n)
1115            })
1116            .collect();
1117        let mut touched_mems: Vec<String> = relates
1118            .iter()
1119            .flat_map(|(a, _)| [a.source.mem().to_string(), a.target.mem().to_string()])
1120            .collect();
1121        touched_mems.sort();
1122        touched_mems.dedup();
1123        // A mem that is only ever a TARGET in this batch and is
1124        // deferred stays unloaded: target verification runs against
1125        // storage (flywheel W7/02), and the funnel's phase-0 trigger
1126        // would otherwise convert verification into a full load.
1127        // Source mems always reload — a write into a mem needs the mem.
1128        let source_mems: std::collections::HashSet<&str> =
1129            relates.iter().map(|(a, _)| a.source.mem()).collect();
1130        touched_mems.retain(|m| source_mems.contains(m.as_str()) || !self.mem_is_deferred(m));
1131        for m in &touched_mems {
1132            self.reload_if_stale(Some(m));
1133        }
1134        // Same acyclic-guard rule as the single-item path: any added
1135        // edge on an ACYCLIC rel-type (or a rel-type in an
1136        // `acyclic_sets` set, whose guard walks the set's UNION
1137        // subgraph) walks the whole subgraph, so the walk must see
1138        // every mem — deferred (lazy, unloaded) ones included — or a
1139        // cycle through an unloaded mem is admitted (the fifth
1140        // lazy-mount grade demonstrated exactly that through this
1141        // path). Declared signals on either endpoint's schema need
1142        // the full load for the same reason as the single-item path.
1143        if relates.iter().any(|(a, _)| {
1144            (!a.remove
1145                && self.schemas.get(a.source.mem()).is_some_and(|s| {
1146                    s.relationship_acyclic(&a.rel_type)
1147                        || s.acyclic_set_containing(&a.rel_type).is_some()
1148                }))
1149                || [a.source.mem(), a.target.mem()].iter().any(|m| {
1150                    self.schemas
1151                        .get(*m)
1152                        .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
1153                })
1154        }) {
1155            self.ensure_mems_loaded(None);
1156        }
1157
1158        // Snapshot for the all-or-nothing rollback: staged entries
1159        // mutate the store as they apply (in-order semantics), so a
1160        // refusal restores this snapshot and discards every backend's
1161        // pending buffer. Any early-return added below MUST do both.
1162        let store_snapshot = self.store.clone();
1163
1164        let mut items: Vec<(EntityId, ItemState)> = Vec::with_capacity(relates.len());
1165        let mut prepared: Vec<PreparedRelate> = Vec::new();
1166        let mut notes: Vec<Option<String>> = Vec::new();
1167        let mut errors: Vec<(usize, EngineError)> = Vec::new();
1168
1169        for (i, (args, note)) in relates.into_iter().enumerate() {
1170            let source_id = args.source.clone();
1171            if let Some(pos) = short_errors.iter().position(|(j, _)| *j == i) {
1172                let (_, e) = short_errors.remove(pos);
1173                items.push((source_id, ItemState::Error));
1174                errors.push((i, e));
1175                continue;
1176            }
1177            // Rehearsal is batch-level (the `dry_run` parameter) —
1178            // per-entry dry-run stays forced off; the staging below is
1179            // what gives later entries in-order semantics, and the
1180            // batch-level rollback undoes it.
1181            let mut args = args;
1182            args.dry_run = false;
1183            match self.prepare_relate(args, Vec::new()) {
1184                Ok(RelatePrepareOutcome::Done(_)) => {
1185                    items.push((source_id, ItemState::Noop));
1186                }
1187                Ok(RelatePrepareOutcome::Prepared(p)) => {
1188                    // Stage + apply NOW so later entries validate
1189                    // against this entry's effect (applied-in-order).
1190                    if let Err(e) = self.stage_prepared_relate(&p) {
1191                        self.store = store_snapshot;
1192                        self.discard_all_pending();
1193                        return Err(e);
1194                    }
1195                    if let Err(e) = self.apply_prepared_relate_to_store(&p) {
1196                        self.store = store_snapshot;
1197                        self.discard_all_pending();
1198                        return Err(e);
1199                    }
1200                    // Derivation baseline (plan 12) — same predicate
1201                    // and staging as the single-item path; rides the
1202                    // batch commit, rolls back with a refusal. (Batch
1203                    // no-op entries do NOT re-baseline — the explicit
1204                    // "reviewed, still holds" gesture is the single
1205                    // relate / single-op MCP list.)
1206                    if let Some(schema) = self.schemas.get(&p.source_mem)
1207                        && super::rel_type_declares_derivation(schema, &p.rel_type)
1208                    {
1209                        let backend = self.mounts[p.mount_idx].backend.as_ref();
1210                        let (from, rel, to) =
1211                            (p.from.to_string(), p.rel_type.clone(), p.to.to_string());
1212                        let staged = match p.action {
1213                            RelateAction::Added => {
1214                                let hash = self
1215                                    .store
1216                                    .get(&p.to)
1217                                    .map(|e| e.content_hash.clone())
1218                                    .unwrap_or_default();
1219                                super::stage_derivation_sidecar(backend, |s| {
1220                                    s.set(&from, &rel, &to, &hash)
1221                                })
1222                            }
1223                            RelateAction::Removed => {
1224                                super::stage_derivation_sidecar(backend, |s| {
1225                                    s.remove(&from, &rel, &to)
1226                                })
1227                            }
1228                            _ => Ok(()),
1229                        };
1230                        if let Err(e) = staged {
1231                            self.store = store_snapshot;
1232                            self.discard_all_pending();
1233                            return Err(e);
1234                        }
1235                    }
1236                    let label = match p.action {
1237                        RelateAction::Added => "added",
1238                        RelateAction::Removed => "removed",
1239                        _ => unreachable!("no-ops resolve to Done"),
1240                    };
1241                    items.push((source_id, ItemState::Applied(label)));
1242                    prepared.push(p);
1243                    notes.push(note);
1244                }
1245                Err(e) => {
1246                    items.push((source_id, ItemState::Error));
1247                    errors.push((i, e));
1248                }
1249            }
1250        }
1251
1252        if !errors.is_empty() {
1253            // Refuse the whole batch; roll back every staged entry.
1254            self.store = store_snapshot;
1255            self.discard_all_pending();
1256            return Ok(super::batch_refusal(
1257                items.into_iter().map(|(id, _)| id).collect(),
1258                errors,
1259            ));
1260        }
1261
1262        // Rehearsal: every entry validated in order against the state
1263        // its predecessors produced and nothing failed — stop before
1264        // any commit. The would-be orphan GC is computed on the staged
1265        // store (honest: it is exactly what the real call would
1266        // collect), then the whole staged state rolls back.
1267        if dry_run {
1268            let removed_targets: Vec<EntityId> = prepared
1269                .iter()
1270                .filter(|p| matches!(p.action, RelateAction::Removed))
1271                .map(|p| p.to.clone())
1272                .collect();
1273            let orphan_stubs_removed =
1274                super::gc_orphan_stubs_among(&mut self.store, removed_targets.iter());
1275            self.store = store_snapshot;
1276            self.discard_all_pending();
1277            return Ok(super::batch_receipt(
1278                relate_actions(items),
1279                Vec::new(),
1280                orphan_stubs_removed,
1281                String::new(),
1282            ));
1283        }
1284
1285        // --- Commit once per touched mount, in first-seen order. ---
1286        let mut distinct_mounts: Vec<usize> = Vec::new();
1287        for p in &prepared {
1288            if !distinct_mounts.contains(&p.mount_idx) {
1289                distinct_mounts.push(p.mount_idx);
1290            }
1291        }
1292        let mut mount_commits: Vec<(usize, String)> = Vec::with_capacity(distinct_mounts.len());
1293        for &m in &distinct_mounts {
1294            // Distinct source ids for this mount (an entity may carry
1295            // several edge changes in one batch).
1296            let mut entity_ids: Vec<String> = Vec::new();
1297            let mut edge_count = 0usize;
1298            for p in prepared.iter().filter(|p| p.mount_idx == m) {
1299                edge_count += 1;
1300                let s = p.from.to_string();
1301                if !entity_ids.contains(&s) {
1302                    entity_ids.push(s);
1303                }
1304            }
1305            let subject = format!("memstead: batch-relate ({edge_count} edges)");
1306            // Per-entry notes ride the batch commit's note record as
1307            // `<id>: <note>` lines (decision 3), keyed by the edge's
1308            // source entity — `append_provenance` is a no-op on the
1309            // git-branch backend. No notes → no note record.
1310            let note_lines: Vec<String> = prepared
1311                .iter()
1312                .zip(notes.iter())
1313                .filter(|(p, _)| p.mount_idx == m)
1314                .filter_map(|(p, n)| n.as_ref().map(|n| format!("{}: {n}", p.from)))
1315                .collect();
1316            let mut ctx = self.commit_context(
1317                Some("batch_relate"),
1318                actor,
1319                client.cloned(),
1320                if note_lines.is_empty() {
1321                    None
1322                } else {
1323                    Some(note_lines.join("\n"))
1324                },
1325            );
1326            ctx.entity_ids = Some(entity_ids);
1327            match self.mounts[m].backend.commit(&subject, &ctx) {
1328                Ok(sha) => mount_commits.push((m, sha)),
1329                Err(e) => {
1330                    // A commit failed: roll back the store and any
1331                    // still-pending backends. Mems already committed
1332                    // in this loop stay committed (the family's
1333                    // per-mem atomicity).
1334                    self.store = store_snapshot;
1335                    self.discard_all_pending();
1336                    return Err(e.into());
1337                }
1338            }
1339        }
1340
1341        // Provenance per entry, self-write markers per mount.
1342        let mut batch_warnings: Vec<WarningHint> = short_hints;
1343        for (p, note) in prepared.iter().zip(notes.iter()) {
1344            let write_id = mount_commits
1345                .iter()
1346                .find(|(m, _)| *m == p.mount_idx)
1347                .map(|(_, s)| s.clone())
1348                .unwrap_or_default();
1349            self.mounts[p.mount_idx].backend.append_provenance(
1350                &Provenance::new(
1351                    std::time::SystemTime::now(),
1352                    ProvenanceKind::Relate,
1353                    Some(p.from.to_string()),
1354                    actor,
1355                    client.cloned(),
1356                    note.clone(),
1357                )
1358                .with_role(self.current_role)
1359                .with_identity(self.current_identity.clone()),
1360            )?;
1361            self.record_self_write(p.mount_idx, &write_id);
1362            batch_warnings.extend(self.stamp_mutation_versions(p.mount_idx));
1363        }
1364
1365        // Orphan-stub GC over every removed edge's target — same
1366        // scoped sweep and shared predicate as the single-item path.
1367        let removed_targets: Vec<EntityId> = prepared
1368            .iter()
1369            .filter(|p| matches!(p.action, RelateAction::Removed))
1370            .map(|p| p.to.clone())
1371            .collect();
1372        let orphan_stubs_removed =
1373            super::gc_orphan_stubs_among(&mut self.store, removed_targets.iter());
1374
1375        self.invalidate_communities();
1376        self.invalidate_search_indexes();
1377
1378        let write_id = mount_commits
1379            .last()
1380            .map(|(_, s)| s.clone())
1381            .unwrap_or_default();
1382        Ok(super::batch_receipt(
1383            relate_actions(items),
1384            batch_warnings,
1385            orphan_stubs_removed,
1386            write_id,
1387        ))
1388    }
1389
1390    /// Positional-args alias for [`Self::relate_entity`]. Bundles
1391    /// the positional inputs into a [`RelateEntityArgs`] (with
1392    /// `expected_hash: None`) and delegates to
1393    /// [`Self::relate_entity`]. The `CommitContext` is destructured
1394    /// into the 4-tuple (actor, client, note) the unified mutation
1395    /// surface accepts.
1396    pub fn relate(
1397        &mut self,
1398        from: &EntityId,
1399        to: &EntityId,
1400        rel_type: &str,
1401        remove: bool,
1402        ctx: &CommitContext<'_>,
1403    ) -> Result<RelateEntityOutcome, EngineError> {
1404        let args = RelateEntityArgs {
1405            source: from.clone(),
1406            expected_hash: None,
1407            rel_type: rel_type.to_string(),
1408            target: to.clone(),
1409            remove,
1410            description: None,
1411            dry_run: false,
1412        };
1413        self.relate_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
1414    }
1415}
1416
1417#[cfg(test)]
1418mod derivation_tests;
1419#[cfg(test)]
1420mod tests;