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
64impl Engine {
65    /// Add or remove a typed relationship on `args.source`.
66    ///
67    /// Cross-mem relate is policy-gated through
68    /// [`Engine::cross_mem_link_allowed`] — the workspace's
69    /// `[cross_mem_links]` table (or per-create-rule
70    /// `default_cross_links` synthesis) decides whether the edge is
71    /// permitted. Disallowed pairings surface
72    /// [`EngineError::CrossMemLinkNotAllowed`]. Cross-mem relate
73    /// only writes the source entity's markdown — the target mem is
74    /// never written to. Auto-stub for absent targets works for
75    /// Write target mems; ReadOnly target mems reject absent
76    /// targets with [`EngineError::CrossMemTargetNotFound`] because
77    /// the engine cannot persist a stub through the read-only
78    /// boundary.
79    ///
80    /// Schema-undeclared rel types surface either as validation
81    /// errors (strict mode) or as ride-along warnings on the outcome
82    /// (open mode).
83    pub fn relate_entity(
84        &mut self,
85        args: RelateEntityArgs,
86        actor: Actor,
87        client: Option<&ClientId>,
88        note: Option<&str>,
89    ) -> Result<RelateEntityOutcome, EngineError> {
90        // Short ids on either end resolve (or refuse) before anything
91        // reads their mems; the announcements lead the warnings.
92        let mut args = args;
93        let (source, source_hint) = self.resolve_entity_id(&args.source)?;
94        args.source = source;
95        let (target, target_hint) = self.resolve_entity_id(&args.target)?;
96        args.target = target;
97        let source_mem = args.source.mem().to_string();
98        let target_mem = args.target.mem().to_string();
99
100        // Reload-before-operation: reload the source mem (and the
101        // target mem, when distinct) if a sibling advanced either
102        // ref, so the source `expected_hash` compare and the target
103        // existence/stub decisions below run against current truth.
104        // The drift notice rides the outcome's `warnings`. Hoisted
105        // out of `prepare_relate` so `batch_relate` can probe every
106        // touched mem exactly once up front instead of per entry.
107        let mut drift_warnings: Vec<WarningHint> =
108            source_hint.into_iter().chain(target_hint).collect();
109        drift_warnings.extend(self.reload_if_stale(Some(&source_mem)));
110        if target_mem != source_mem && !self.mem_is_deferred(&target_mem) {
111            // A DEFERRED target mem is deliberately not probed here:
112            // the funnel's phase-0 trigger would full-load it, and
113            // target verification must never cost a mem's load
114            // (flywheel W7/02 — the storage check below answers the
115            // existence and type questions against the branch tree /
116            // filesystem instead).
117            drift_warnings.append(&mut self.reload_if_stale(Some(&target_mem)));
118        }
119        // An ACYCLIC rel-type's cycle guard walks the whole rel-type
120        // subgraph (`would_cycle`), and a cycle can pass through any
121        // mem — an edge on a deferred (lazy, unloaded) mem's entity is
122        // invisible to a walk over the endpoint mems alone, so an add
123        // an eager boot refuses would land silently and corrupt an
124        // innocent edge on the next full load (the fourth lazy-mount
125        // grade demonstrated exactly that on a three-mem chain). The
126        // same holds for a rel-type in an `acyclic_sets` set, whose
127        // guard walks the set's UNION subgraph, and for declared
128        // aggregate signals on either endpoint's schema: the
129        // threshold-crossing diff counts edges that can originate in
130        // any mem, so a partial store silently mis-levels it. Full
131        // load before the guard; writes touching neither skip the
132        // cost.
133        let cycle_guard_needs_full = !args.remove
134            && self.schemas.get(&source_mem).is_some_and(|s| {
135                s.relationship_acyclic(&args.rel_type)
136                    || s.acyclic_set_containing(&args.rel_type).is_some()
137            });
138        let signal_diff_needs_full = [source_mem.as_str(), args.target.mem()].iter().any(|m| {
139            self.schemas
140                .get(*m)
141                .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
142        });
143        if cycle_guard_needs_full || signal_diff_needs_full {
144            self.ensure_mems_loaded(None);
145        }
146
147        let dry_run = args.dry_run;
148        let prepared = match self.prepare_relate(args, drift_warnings)? {
149            RelatePrepareOutcome::Done(outcome) => {
150                // Derivation re-baseline: on a
151                // derivation-declared rel-type, the duplicate-add
152                // no-op's ONE effect is refreshing the edge's
153                // baseline to the target's current hash — the agent's
154                // explicit "reviewed, still holds". Sidecar-only:
155                // `_hash` unchanged, the edge unchanged; the response
156                // states the refresh (warning + the sidecar commit's
157                // sha) instead of a bare no-op. Undeclared rel-types
158                // keep today's exact no-op response; rehearsals
159                // refresh nothing.
160                if !dry_run
161                    && matches!(
162                        outcome.action,
163                        super::super::RelateAction::NoOpAlreadyPresent
164                    )
165                {
166                    return self.refresh_derivation_baseline_on_noop(outcome, actor, client, note);
167                }
168                return Ok(outcome);
169            }
170            RelatePrepareOutcome::Prepared(p) => p,
171        };
172
173        // Rehearsal: the full validation stage ran (identical refusals
174        // and warnings, would-be stub included via the prepared
175        // AUTO_STUB_CREATED warning) — stop before any write. `_hash`
176        // reports the PROSPECTIVE post-write hash; `write_id` stays
177        // empty (the marker form). Nothing staged, committed, or
178        // stubbed.
179        if dry_run {
180            let parse_result = parse_markdown(
181                &prepared.markdown,
182                &prepared.file_path,
183                prepared.type_def.as_ref(),
184                &prepared.source_mem,
185            )
186            .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
187            // A rehearsal demands no note: `NOTE_MISSING` attributes a
188            // write that landed without provenance, and nothing lands
189            // here (create and update rehearse the same way; a relate
190            // rehearsal once carried the nudge and so reported a
191            // provenance gap on a commit that did not exist).
192            let warnings = prepared.warnings;
193            return Ok(RelateEntityOutcome {
194                from: prepared.from,
195                to: prepared.to,
196                rel_type: prepared.rel_type,
197                action: prepared.action,
198                content_hash: parse_result.entity.content_hash,
199                write_id: String::new(),
200                source: "explicit".to_string(),
201                orphan_stubs_removed: Vec::new(),
202                warnings,
203            });
204        }
205
206        // Aggregate signals: capture both endpoints' levels before the
207        // store mutates — the entities a relate can move are exactly
208        // the edge's endpoints. Diffed after the write below.
209        let signal_snapshot = crate::ops::signals::snapshot_levels(
210            &self.store,
211            &self.schemas,
212            [&prepared.from, &prepared.to],
213        );
214
215        self.stage_prepared_relate(&prepared)?;
216
217        // Derivation baseline: an explicit add
218        // on a declared rel-type records the target's CURRENT content
219        // hash ("" for a just-stubbed absent target — deriving from
220        // nothing, honestly); a remove prunes the row. Staged into
221        // the same pending set so baseline and edge ride one commit.
222        if let Some(schema) = self.schemas.get(&prepared.source_mem)
223            && super::rel_type_declares_derivation(schema, &prepared.rel_type)
224        {
225            let backend = self.mounts[prepared.mount_idx].backend.as_ref();
226            let (from, rel, to) = (
227                prepared.from.to_string(),
228                prepared.rel_type.clone(),
229                prepared.to.to_string(),
230            );
231            match prepared.action {
232                RelateAction::Added => {
233                    let hash = self
234                        .store
235                        .get(&prepared.to)
236                        .map(|e| e.content_hash.clone())
237                        .unwrap_or_default();
238                    super::stage_derivation_sidecar(backend, |s| s.set(&from, &rel, &to, &hash))?;
239                }
240                RelateAction::Removed => {
241                    super::stage_derivation_sidecar(backend, |s| s.remove(&from, &rel, &to))?;
242                }
243                _ => {}
244            }
245        }
246
247        let backend = self.mounts[prepared.mount_idx].backend.as_ref();
248        let commit_subject = format!("memstead: relate {}", prepared.from);
249        let ctx = CommitContext {
250            actor,
251            client: client.cloned(),
252            tool: Some("relate_entity"),
253            note: note.map(String::from),
254            role: self.current_role,
255            identity: self.current_identity.clone(),
256            logical_operation_id: None,
257            entity_ids: None,
258        };
259        let write_id = backend.commit(&commit_subject, &ctx)?;
260
261        backend.append_provenance(
262            &Provenance::new(
263                std::time::SystemTime::now(),
264                ProvenanceKind::Relate,
265                Some(prepared.from.to_string()),
266                actor,
267                client.cloned(),
268                note.map(String::from),
269            )
270            .with_role(self.current_role)
271            .with_identity(self.current_identity.clone()),
272        )?;
273
274        self.record_self_write(prepared.mount_idx, &write_id);
275        let stamp_warnings = self.stamp_mutation_versions(prepared.mount_idx);
276
277        let content_hash = self.apply_prepared_relate_to_store(&prepared)?;
278
279        // On the `--remove` path, the edge we just dropped may
280        // have been the last incoming edge to a stub. The orphan-stub
281        // GC hook fired from `memstead_delete` already; mirror it here so
282        // every mutation that can leave orphans cleans them up.
283        // Scoped sweep — only inspect the just-severed target. The
284        // only possible new orphan from a relate-remove is the
285        // target whose incoming edge we removed; checking the entire
286        // store would catch pre-existing orphans which aren't this
287        // mutation's responsibility (and which `memstead_delete`'s full
288        // sweep also leaves alone before its own removal). Funnels
289        // through the shared `gc_orphan_stubs_among` predicate so the
290        // relate-remove, delete, and update-via-alias-resync paths
291        // can't drift on what counts as a GC-able orphan.
292        let orphan_stubs_removed: Vec<EntityId> =
293            if matches!(prepared.action, RelateAction::Removed) {
294                super::gc_orphan_stubs_among(&mut self.store, std::iter::once(&prepared.to))
295            } else {
296                Vec::new()
297            };
298
299        self.invalidate_communities();
300        // Incremental (flywheel W8/01): only the SOURCE entity's file
301        // was rewritten; stub targets and GC'd orphan stubs were never
302        // indexed.
303        self.maintain_search_indexes(std::slice::from_ref(&prepared.from));
304
305        let PreparedRelate {
306            from,
307            to,
308            rel_type,
309            action,
310            mut warnings,
311            ..
312        } = prepared;
313
314        warnings.extend(stamp_warnings);
315
316        // Signal crossings ride the out-of-band warning channel beside
317        // the success payload — never error-shaped, never changing the
318        // mutation's success semantics.
319        warnings.extend(crate::ops::signals::crossing_warnings(
320            &self.store,
321            &self.schemas,
322            &signal_snapshot,
323        ));
324
325        // `require_notes` provenance nudge — single engine-level
326        // enforcement point. Only reached on the real-commit path
327        // (Added / Removed); the NoOpAlreadyPresent / NoOpAbsent branches
328        // return early above with an empty `write_id` and never demand
329        // a note (nothing landed to attribute).
330        if let Some(w) = self.note_missing_warning("relate_entity", note) {
331            warnings.push(w);
332        }
333
334        Ok(RelateEntityOutcome {
335            from,
336            to,
337            rel_type,
338            action,
339            content_hash,
340            write_id,
341            source: "explicit".to_string(),
342            warnings,
343            orphan_stubs_removed,
344        })
345    }
346
347    /// The duplicate-add re-baseline. Called
348    /// from the `NoOpAlreadyPresent` path when the rel-type is
349    /// derivation-declared: stages a sidecar-only refresh of the
350    /// edge's baseline to the target's current hash and commits it
351    /// (the anchor-only-update precedent — a real persisted effect
352    /// rides a real commit), then returns the outcome with the
353    /// refresh STATED (`DERIVATION_BASELINE_REFRESHED` warning + the
354    /// sidecar commit's sha). `_hash` and the edge are untouched. On
355    /// an undeclared rel-type the outcome passes through unchanged —
356    /// today's exact no-op response.
357    fn refresh_derivation_baseline_on_noop(
358        &mut self,
359        mut outcome: RelateEntityOutcome,
360        actor: Actor,
361        client: Option<&ClientId>,
362        note: Option<&str>,
363    ) -> Result<RelateEntityOutcome, EngineError> {
364        let source_mem = outcome.from.mem().to_string();
365        let declared = self
366            .schemas
367            .get(&source_mem)
368            .is_some_and(|s| super::rel_type_declares_derivation(s, &outcome.rel_type));
369        if !declared {
370            return Ok(outcome);
371        }
372        let Some(mount_idx) = self.mounts.iter().position(|m| m.mount.mem == source_mem) else {
373            return Ok(outcome);
374        };
375        let hash = self
376            .store
377            .get(&outcome.to)
378            .map(|e| e.content_hash.clone())
379            .unwrap_or_default();
380        let (from, rel, to) = (
381            outcome.from.to_string(),
382            outcome.rel_type.clone(),
383            outcome.to.to_string(),
384        );
385        let backend = self.mounts[mount_idx].backend.as_ref();
386        super::stage_derivation_sidecar(backend, |s| s.set(&from, &rel, &to, &hash))?;
387        let ctx = CommitContext {
388            actor,
389            client: client.cloned(),
390            tool: Some("relate_entity"),
391            note: note.map(String::from),
392            role: self.current_role,
393            identity: self.current_identity.clone(),
394            logical_operation_id: None,
395            entity_ids: None,
396        };
397        let write_id = backend.commit(
398            &format!("memstead: derivation re-baseline {}", outcome.from),
399            &ctx,
400        )?;
401        self.record_self_write(mount_idx, &write_id);
402        // `relate_entity` returns early into this path, so the stamp call on
403        // the ordinary path never runs and its report has to be collected
404        // here (found by the re-grade).
405        outcome
406            .warnings
407            .extend(self.stamp_mutation_versions(mount_idx));
408        outcome.write_id = write_id;
409        outcome
410            .warnings
411            .push(WarningHint::DerivationBaselineRefreshed {
412                from: outcome.from.clone(),
413                rel_type: outcome.rel_type.clone(),
414                to: outcome.to.clone(),
415            });
416        Ok(outcome)
417    }
418
419    /// Every validation gate and the mutation plan for one relate —
420    /// shared verbatim by the single-item path above and
421    /// [`Self::batch_relate`], so batching can never drift from the
422    /// single-item gates. Never mutates the store, writes no file,
423    /// commits nothing: refusals are side-effect-free by
424    /// construction. The reload-before-operation probe is the
425    /// caller's job (hoisted so a batch probes each mem once).
426    fn prepare_relate(
427        &mut self,
428        args: RelateEntityArgs,
429        mut drift_warnings: Vec<WarningHint>,
430    ) -> Result<RelatePrepareOutcome, EngineError> {
431        let mut args = args;
432        let source_mem = args.source.mem().to_string();
433        let target_mem = args.target.mem().to_string();
434
435        // Target-id grammar gate (shared helper, also called from
436        // `Engine::create_entity` for inline relations so both
437        // gateways trip the same envelope). Source-id grammar is
438        // implicit — a malformed source surfaces as `ENTITY_NOT_FOUND`
439        // because it can never have been created.
440        //
441        // The grammar check runs BEFORE the cross-mem policy check:
442        // a bare-string target with no `--` separator (e.g.
443        // `bad target`) parses as `mem: ""`, `path: "bad target"`,
444        // and without this ordering would surface a cross-mem
445        // policy error against an empty mem name — pointing the
446        // agent at workspace policy when the actual fix is a
447        // malformed id. The grammar check is intrinsic to the target
448        // id; it doesn't need to know which mem the target lives
449        // in.
450        validate_relation_target_grammar(&args.target)?;
451
452        // Track whether the cross-mem target's mem is unmounted —
453        // we deferred the warning emission to the canonical
454        // `warnings` vec initialisation below, but the policy / RO
455        // gates fire first to keep the refusal-before-warning ordering:
456        // a policy refusal preempts the warning.
457        let mut target_mem_uncreated = false;
458        if source_mem != target_mem {
459            // Policy gates *new* edges only — remove is structurally
460            // cleanup. The same convention governs the acyclic, shape,
461            // and schema gates below (each one wraps `if !args.remove`).
462            // Without this bypass, a workspace whose cross-mem grant
463            // was revoked while edges still existed gets wedged: the
464            // grant must be re-introduced just to delete the data it
465            // permitted, then re-revoked. The gate-on-add
466            // rule holds because `cross_mem_links: named` semantically reads
467            // as "only these new edges may be created", not "these
468            // edges may exist."
469            if !args.remove {
470                super::validate_cross_mem_add_policy(self, &source_mem, &args.target)?;
471            }
472            // ReadOnly target mem: the engine has no write access to
473            // persist a stub there, so the target must already exist
474            // before relate. (Same-mem and cross-mem-to-Write
475            // both retain the auto-stub mechanic below.) The add path
476            // already refused above via the shared funnel; this check
477            // stays unconditional so the remove path keeps its
478            // pre-funnel behaviour.
479            if let Some(mount) = self.mount(&target_mem)
480                && mount.capability == MountCapability::ReadOnly
481                && !self.store.contains(&args.target)
482                && !matches!(
483                    super::probe_deferred_target(self, &args.target)?,
484                    super::DeferredTargetProbe::Exists
485                )
486            {
487                return Err(EngineError::CrossMemTargetNotFound {
488                    target_id: args.target.to_string(),
489                    target_mem: target_mem.clone(),
490                });
491            }
492            // The target mem isn't mounted in the workspace
493            // at all. Policy admitted the edge so the relate must
494            // succeed and auto-stub; surface a warning so the operator
495            // can distinguish a typo from a deliberate forward
496            // reference. The auto-stub still lands via the
497            // `AutoStubCreated` path below; this layered warning is
498            // additive observability.
499            if self.mount(&target_mem).is_none() {
500                target_mem_uncreated = true;
501            }
502        }
503
504        // Canonicalise rel_type to UPPER_SNAKE_CASE so the schema lookup,
505        // stored edge, and response all see the same wire-contract form
506        // ("case-insensitive on input"). Syntax errors (non-letter
507        // characters) fall through to the strict-mode schema check below,
508        // which surfaces them as INVALID_REL_TYPE with the declared
509        // vocabulary.
510        if let Ok(canonical) = crate::entity::id::validate_rel_type(&args.rel_type) {
511            args.rel_type = canonical;
512        }
513        // Normalise the description at the boundary so empty /
514        // whitespace-only strings collapse to `None` before the
515        // posture check and before the renderer ever sees them.
516        args.description = normalise_description(args.description.as_deref());
517
518        let mount_idx = self
519            .mounts
520            .iter()
521            .position(|m| m.mount.mem == source_mem)
522            .ok_or_else(|| self.unknown_mem_error(&source_mem))?;
523        if self.mounts[mount_idx].mount.capability != MountCapability::Write {
524            return Err(EngineError::ReadOnlyMount(source_mem));
525        }
526
527        let schema = self
528            .schemas
529            .get(&source_mem)
530            .expect("schema present for every registered mount");
531
532        // Determine whether this is a cross-mem edge to a mem
533        // pinning a schema with a *different name*. Same-name (any
534        // version pair — a schema name is a domain) and same-mem
535        // stay on the intra-mem validation path, governed by the
536        // source mem's pinned version; cross-different-schema
537        // routes vocabulary and shape checks through the source
538        // schema's `cross_mem_relationships:` section.
539        //
540        // If the target mem is not mounted (unknown to the engine
541        // — typically only in malformed callers), there is no target
542        // schema to consult and the validation falls back to the
543        // intra-mem path. Real workspaces always mount the target
544        // mem before relating.
545        let target_schema_ref: Option<SchemaRef> = if source_mem == target_mem {
546            None
547        } else {
548            // Loaded mems answer from the schema catalogue; an
549            // unmounted mem with discoverable storage answers from
550            // its stored config's pin (flywheel W7/02) — see
551            // `target_schema_ref_for_routing`.
552            super::target_schema_ref_for_routing(self, &target_mem)
553        };
554        let cross_mem_different = match (&target_schema_ref, schema.id()) {
555            (Some(target), (src_name, _)) => target.name != src_name,
556            (None, _) => false,
557        };
558
559        let mut warnings: Vec<WarningHint> = Vec::new();
560        // Reload-before-operation drift notice, surfaced first.
561        warnings.append(&mut drift_warnings);
562        // Vocabulary check: intra-mem flow consults the source
563        // schema's `relationships.definitions`; cross-different-schema
564        // skips this entirely (the cross-mem entry's `definitions`
565        // are the sole authority — see the add-path check below).
566        if !cross_mem_different {
567            match validate_rel_type(&args.rel_type, schema.as_ref())? {
568                RelationshipCheck::Ok => {}
569                RelationshipCheck::OpenWarning(message) => {
570                    warnings.push(WarningHint::UndeclaredRelationshipOpen {
571                        rel_type: args.rel_type.clone(),
572                        message,
573                    });
574                }
575            }
576        }
577
578        // Clone the source entity early so subsequent mutable
579        // operations on `self.store` (the stub-creation upsert below)
580        // don't conflict with the borrow.
581        let entity: Entity = self
582            .store
583            .get(&args.source)
584            .ok_or_else(|| EngineError::NotFound {
585                id: args.source.to_string(),
586            })?
587            .clone();
588
589        // Stubs have no `entity_type`, so the schema lookup below
590        // would surface a cryptic `UnknownType { name: "" }`. Surface
591        // the actual constraint instead — a stub source has no body
592        // to write to and no schema-resolved type to validate
593        // against. Promotion via `memstead_create` adopts the stub's
594        // incoming references and lets the agent re-issue the relate
595        // against a real entity.
596        if entity.stub {
597            return Err(EngineError::StubCannotRelate {
598                id: args.source.to_string(),
599            });
600        }
601
602        let target_type = self
603            .store
604            .get(&args.target)
605            .map(|e| e.entity_type.clone())
606            .filter(|t| !t.is_empty());
607        // Storage verification for a target in a DEFERRED mem
608        // (flywheel W7/02): the store cannot answer for an unloaded
609        // mem, so existence comes from the cheap storage probe and —
610        // when the shape check will need it — the type from the one
611        // resolved blob. Neither triggers the mem's load.
612        let target_verified_in_storage = if target_type.is_none() && target_mem != source_mem {
613            matches!(
614                super::probe_deferred_target(self, &args.target)?,
615                super::DeferredTargetProbe::Exists
616            )
617        } else {
618            false
619        };
620        let target_type = match target_type {
621            Some(t) => Some(t),
622            None if target_verified_in_storage && !args.remove => {
623                super::peek_deferred_target_type(self, &args.target)?
624            }
625            None => None,
626        };
627        if target_verified_in_storage {
628            // A verified target's mem is not "uncreated" — for an
629            // unmounted mem the discovery hook just found its storage
630            // and the entity in it; the layered warning would claim
631            // the opposite.
632            target_mem_uncreated = false;
633        }
634        // Shape validation is add-only. Edges that violated the
635        // schema's shape before constraints landed must remain
636        // removable through `memstead_relate remove=true` — otherwise the
637        // graph carries unfixable shape drift. The health scan
638        // surfaces the existing violations so an agent can run the
639        // cleanup pass. The same posture applies to cross-mem
640        // vocabulary: the cleanup path stays permissive so
641        // pre-tightening edges can be dropped without first
642        // re-declaring them in the source schema.
643        // Per-edge description posture (intra-mem and cross-mem).
644        // Add-only — the remove path stays permissive so pre-tightening
645        // edges remain droppable (mirrors the shape-validation posture
646        // below). Posture is a no-op for rel-types not declared in the
647        // schema; the vocabulary gate runs first and surfaces those.
648        if !args.remove {
649            validate_description_posture(
650                self,
651                &args.rel_type,
652                args.description.as_deref(),
653                &source_mem,
654                &target_mem,
655                &args.source,
656                &args.target,
657            )?;
658            // Refuse
659            // explicit `memstead_relate` calls for rel-types whose schema
660            // declares `manual_authoring: forbidden`. The body-link →
661            // relation alias machinery synthesises these relations
662            // from wiki-links via a separate path that doesn't go
663            // through this validator, so the alias contract stays
664            // intact.
665            super::validate_manual_authoring_posture(
666                self,
667                &args.rel_type,
668                &source_mem,
669                &args.source,
670                &args.target,
671            )?;
672        }
673
674        if !args.remove {
675            if cross_mem_different {
676                // Safe-by-construction: `cross_mem_different` only
677                // becomes true when `target_schema_ref` is `Some`.
678                let target_ref = target_schema_ref
679                    .as_ref()
680                    .expect("target_schema_ref is Some when cross_mem_different");
681                match validate_cross_mem_edge(
682                    &args.rel_type,
683                    entity.entity_type.as_str(),
684                    target_type.as_deref(),
685                    schema.as_ref(),
686                    target_ref,
687                ) {
688                    CrossMemRelCheck::Ok => {}
689                    CrossMemRelCheck::EdgeNotDeclared => {
690                        let (src_name, src_version) = schema.id();
691                        return Err(EngineError::CrossMemEdgeNotDeclared {
692                            source_schema: SchemaRef::new(src_name, src_version).as_display(),
693                            target_schema: target_ref.as_display(),
694                            rel_type: args.rel_type.clone(),
695                            from_id: args.source.to_string(),
696                            to_id: args.target.to_string(),
697                        });
698                    }
699                    CrossMemRelCheck::Invalid(v) => {
700                        return Err(EngineError::Validation(v));
701                    }
702                }
703            } else {
704                validate_rel_shape(
705                    &args.rel_type,
706                    entity.entity_type.as_str(),
707                    target_type.as_deref(),
708                    schema.as_ref(),
709                )?;
710            }
711        }
712
713        if let Some(expected) = args.expected_hash.as_deref()
714            && entity.content_hash != expected
715        {
716            return Err(EngineError::HashMismatch {
717                id: args.source.to_string(),
718                current: entity.content_hash.clone(),
719                is_stub: entity.stub,
720            });
721        }
722
723        // Cycle family on the real-add path — the self-loop refusal
724        // (listed no-self-loop rel-types) and the acyclic long-cycle refusal,
725        // via the shared gate every edge-writing verb runs
726        // (`validate_edge_acyclicity`). Skipped on the remove path:
727        // removal can only break cycles, never close one.
728        if !args.remove {
729            super::validate_edge_acyclicity(
730                &self.store,
731                schema,
732                &args.source,
733                entity.entity_type.as_str(),
734                &args.target,
735                &args.rel_type,
736            )?;
737        }
738
739        let type_def = schema
740            .get_type(&entity.entity_type)
741            .ok_or_else(|| unknown_type_error(schema, &entity.entity_type))?;
742
743        let mut next = entity.clone();
744        let already = next
745            .relationships
746            .iter()
747            .position(|r| r.rel_type == args.rel_type && r.target == args.target);
748
749        // Alias-existence RESTRICT semantics on the remove path. Under
750        // set-membership semantics a body wiki-link `[[X]]` aliases the
751        // *set* of relations to X; removing one relation is fine as
752        // long as another survives. Refuse only when the removal would
753        // empty the relation-set to `b` while body wiki-links to `b`
754        // are still present in the source entity's section bodies.
755        if args.remove && already.is_some() {
756            let other_relation_to_target_exists = entity
757                .relationships
758                .iter()
759                .any(|r| r.target == args.target && r.rel_type != args.rel_type);
760            if !other_relation_to_target_exists {
761                // Read-side scan over the source entity's existing
762                // body. Use the lenient decoder so on-disk drift on
763                // pre-strict entities continues to surface in the
764                // body-link survival check — the mutation gate sits
765                // on the create/update path, not on a relate-remove
766                // scan of historical state.
767                let mut surviving_sections: Vec<String> = Vec::new();
768                for (section_key, body) in entity.sections.iter() {
769                    let inline_targets =
770                        crate::entity::parser::extract_inline_links_lenient(body, &source_mem);
771                    if inline_targets.iter().any(|t| t == &args.target) {
772                        surviving_sections.push(section_key.clone());
773                    }
774                }
775                if !surviving_sections.is_empty() {
776                    return Err(EngineError::RelationHasBodyLinks {
777                        from_id: args.source.to_string(),
778                        to_id: args.target.to_string(),
779                        rel_type: args.rel_type.clone(),
780                        body_links: surviving_sections,
781                    });
782                }
783            }
784        }
785
786        let action = if args.remove {
787            match already {
788                Some(idx) => {
789                    next.relationships.remove(idx);
790                    RelateAction::Removed
791                }
792                None => RelateAction::NoOpAbsent,
793            }
794        } else {
795            match already {
796                Some(_) => RelateAction::NoOpAlreadyPresent,
797                None => {
798                    next.relationships.push(Relationship {
799                        rel_type: args.rel_type.clone(),
800                        target: args.target.clone(),
801                        description: normalise_description(args.description.as_deref()),
802                    });
803                    RelateAction::Added
804                }
805            }
806        };
807
808        // Block-tier `required_outgoing` on the remove path: dropping
809        // this edge must not leave a `severity: block` block
810        // unsatisfied — the same refusal create/update raise when the
811        // written edge set falls short. Warn-tier blocks stay silent
812        // here (the health sweep owns standing warn-tier findings;
813        // relate-remove has never warned and the no-noise rule keeps
814        // it that way).
815        if matches!(action, RelateAction::Removed) {
816            let blocked: Vec<_> =
817                crate::ops::health::unsatisfied_required_outgoing(&next, type_def.as_ref())
818                    .into_iter()
819                    .filter(|b| b.severity == memstead_schema::ConstraintSeverity::Block)
820                    .collect();
821            if !blocked.is_empty() {
822                return Err(EngineError::RequiredOutgoingUnsatisfied {
823                    entity_type: next.entity_type.clone(),
824                    entity_id: args.source.to_string(),
825                    missing: blocked,
826                });
827            }
828            // Edge-dependent declared constraints: removing this edge
829            // must not un-back a block-tier `enum_from_neighbour`
830            // value (the edge to the enumerating neighbour is what
831            // backs it). Edge-independent forms are filtered out —
832            // their verdict is identical before and after a relate,
833            // so refusing here would block unrelated repair work.
834            // `None` check provider: only `enum_from_neighbour` is
835            // kept below, so the checks-gated form never evaluates on
836            // this path (a relate changes edges, not the gated field).
837            let blocked: Vec<_> = crate::ops::health::unsatisfied_constraints(
838                &self.store,
839                &next,
840                type_def.as_ref(),
841                Some(&args.source),
842                None,
843            )
844            .into_iter()
845            .filter(|v| {
846                matches!(
847                    v,
848                    crate::ops::health::UnsatisfiedConstraint::EnumFromNeighbour { .. }
849                ) && v.severity() == memstead_schema::ConstraintSeverity::Block
850            })
851            .collect();
852            if !blocked.is_empty() {
853                return Err(EngineError::ConstraintUnsatisfied {
854                    entity_type: next.entity_type.clone(),
855                    entity_id: args.source.to_string(),
856                    violations: blocked,
857                });
858            }
859        }
860
861        // Plan a stub for an absent target on the real-add path.
862        // Skipped on no-op paths (NoOpAlreadyPresent / NoOpAbsent — the
863        // edge isn't actually being added) and on the remove path (the
864        // edge being dropped, no need to manifest the target). This is
865        // the engine's target-materialisation step on the add path;
866        // prepare only records the decision — the upsert happens in
867        // `stage_prepared_relate` so prepare stays store-neutral.
868        // The auto-stub surfaces as a typed `AutoStubCreated` warning
869        // on the response's `warnings[]` — the deprecated top-level
870        // `stub_warning` field that pre-Item-03 carried this fact has
871        // been removed, so every diagnostic now follows the uniform
872        // `{ code, message, details }` warning shape.
873        let mut stub_target: Option<EntityId> = None;
874        let mut stub_kind = crate::entity::StubKind::ForwardReference;
875        if matches!(action, RelateAction::Added) && !self.store.contains(&args.target) {
876            stub_target = Some(args.target.clone());
877            if target_verified_in_storage {
878                // The target EXISTS — storage said so. The in-store
879                // stub is only plan 01's until-load representation of
880                // a cross-mem link into a deferred mem (it resolves
881                // when the mem loads), so it carries the load-time
882                // kind and no AUTO_STUB_CREATED warning: that warning
883                // tells an agent the target awaits creation, which
884                // would be false here.
885                stub_kind = crate::entity::StubKind::LoadTime;
886            } else {
887                // Rehearsal honesty: on the dry-run path nothing is
888                // written, so the warning's `pending` flag branches the
889                // message to the would-be form — the code stays
890                // AUTO_STUB_CREATED either way.
891                warnings.push(WarningHint::AutoStubCreated {
892                    stub_id: args.target.clone(),
893                    pending: args.dry_run,
894                });
895            }
896            // If the target mem is unmounted, the
897            // auto-stub above has no `_mem_schema` resolution. Layer
898            // the typed mem-uncreated warning alongside the
899            // `AutoStubCreated` so the operator sees both signals.
900            // (Never true on the verified branch — a deferred mem is
901            // mounted by definition.)
902            if target_mem_uncreated {
903                warnings.push(WarningHint::CrossMemTargetMemUncreated {
904                    from_mem: source_mem.clone(),
905                    to_mem: target_mem.clone(),
906                    target_id: args.target.clone(),
907                });
908            }
909        }
910
911        // No-op paths skip the disk write so the provenance log doesn't
912        // record a non-event. Return the live `content_hash` so callers
913        // can chain follow-ups without refetching. Surface the no-op as
914        // a typed warning so an agent re-running a pipeline can tell the
915        // call didn't change the graph (mirrors full's wire shape).
916        if matches!(
917            action,
918            RelateAction::NoOpAlreadyPresent | RelateAction::NoOpAbsent
919        ) {
920            match action {
921                RelateAction::NoOpAlreadyPresent => {
922                    warnings.push(WarningHint::DuplicateRelationship {
923                        rel_type: args.rel_type.clone(),
924                        from: args.source.clone(),
925                        to: args.target.clone(),
926                    });
927                }
928                RelateAction::NoOpAbsent => {
929                    warnings.push(WarningHint::NoSuchRelationship {
930                        rel_type: args.rel_type.clone(),
931                        from: args.source.clone(),
932                        to: args.target.clone(),
933                    });
934                }
935                _ => unreachable!(),
936            }
937            return Ok(RelatePrepareOutcome::Done(RelateEntityOutcome {
938                from: args.source,
939                to: args.target,
940                rel_type: args.rel_type,
941                action,
942                content_hash: entity.content_hash.clone(),
943                write_id: String::new(),
944                source: "explicit".to_string(),
945                warnings,
946                // No-op branch: nothing changed in the graph, so the
947                // orphan-stub sweep can't have anything to collect.
948                orphan_stubs_removed: Vec::new(),
949            }));
950        }
951
952        // The relate path rewrites the on-disk file (the
953        // `## Relationships` section materialises from
954        // `next.relationships`), so the schema's `auto_timestamp`
955        // metadata (default schema: `last_modified`) bumps to the
956        // current ISO. Only fires on the commit-producing branch —
957        // the no-op early-return above skips this block, so an
958        // idempotent re-add or NoOpAbsent never advances the stamp.
959        let today = self.now_iso();
960        super::auto_stamp_timestamps(&mut next, type_def.as_ref(), &today);
961
962        let file_path = next.file_path.clone();
963        let markdown = super::render_for_write(&next, type_def.as_ref())?;
964
965        Ok(RelatePrepareOutcome::Prepared(PreparedRelate {
966            mount_idx,
967            source_mem,
968            from: args.source,
969            to: args.target,
970            rel_type: args.rel_type,
971            action,
972            file_path,
973            markdown,
974            warnings,
975            stub_target,
976            stub_kind,
977            type_def,
978        }))
979    }
980
981    /// Perform a prepared relate's pre-commit side effects: upsert the
982    /// planned forward-reference stub (if any) and write the source
983    /// entity's regenerated markdown into the backend's pending
984    /// buffer. Nothing is committed; a caller that aborts afterwards
985    /// rolls back with a store snapshot + `discard_all_pending`.
986    fn stage_prepared_relate(&mut self, p: &PreparedRelate) -> Result<(), EngineError> {
987        if let Some(stub_id) = &p.stub_target {
988            self.store
989                .upsert(stub_id.clone(), make_stub(stub_id, p.stub_kind.clone()));
990        }
991        self.mounts[p.mount_idx]
992            .backend
993            .write_entity(Path::new(&p.file_path), p.markdown.as_bytes())?;
994        Ok(())
995    }
996
997    /// Parse the prepared markdown back and push it into the store
998    /// (replacing the pre-mutation source entity), then re-run the
999    /// alias-edge remap. Returns the new `content_hash`. In the
1000    /// single-item path this runs after the commit (preserving the
1001    /// pre-split ordering); `batch_relate` runs it immediately after
1002    /// staging each entry so later entries in the same batch validate
1003    /// against this entry's effect — applied-in-order semantics.
1004    fn apply_prepared_relate_to_store(
1005        &mut self,
1006        p: &PreparedRelate,
1007    ) -> Result<String, EngineError> {
1008        let parse_result = parse_markdown(
1009            &p.markdown,
1010            &p.file_path,
1011            p.type_def.as_ref(),
1012            &p.source_mem,
1013        )
1014        .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
1015        let content_hash = parse_result.entity.content_hash.clone();
1016        let fallback = engine_fallback_type();
1017        push_entities_into_store(&mut self.store, vec![parse_result], fallback.as_ref(), None);
1018        crate::entity::store_builder::remap_alias_target_edge_sources(
1019            &mut self.store,
1020            &self.schemas,
1021        );
1022        Ok(content_hash)
1023    }
1024
1025    /// Atomic batch relate — the edge-side sibling of
1026    /// [`Self::batch_create`] / [`Self::batch_update`]. One list
1027    /// carrying both additions and removals, **applied in order**:
1028    /// each entry validates against the graph state produced by every
1029    /// prior valid entry (an add followed by a remove of the same edge
1030    /// nets to no edge; an acyclic check sees edges added earlier in
1031    /// the same batch). Per-entry shape mirrors what `relate` accepts.
1032    ///
1033    /// - **All-or-nothing, report-all.** A single invalid entry
1034    ///   refuses the whole batch — no edge changes, no head movement —
1035    ///   and the refusal identifies EVERY failing entry with its typed
1036    ///   `{code, message, details}` envelope, bounded at
1037    ///   [`Self::BATCH_ERROR_REPORT_CAP`] with `errors_suppressed`
1038    ///   counting the rest. An entry after a failing one validates
1039    ///   against the state as of the prior *valid* entries, so a
1040    ///   dependent entry may cascade — every reported code is still a
1041    ///   true refusal of the submitted file.
1042    /// - **One commit per touched mem** (subject
1043    ///   `memstead: batch-relate (N edges)`), per-entry provenance
1044    ///   notes, exactly like the rest of the family. No-op entries
1045    ///   (idempotent re-add / absent remove) report `"noop"` and
1046    ///   produce no write.
1047    /// - Orphan-stub GC runs over every removed edge's target after
1048    ///   the commit, same predicate as the single-item path (the
1049    ///   collected ids are not part of `BatchResult`'s fixed family
1050    ///   shape).
1051    ///
1052    /// **Rehearsal** (`dry_run: true`): the FULL in-order validation
1053    /// pass runs — each entry staged against the state its
1054    /// predecessors produced, identical refusals, identical report-all
1055    /// envelope — then the batch stops before any commit and rolls the
1056    /// staged state back. A legal batch returns the would-be receipt
1057    /// (per-entry actions, would-be `orphan_stubs_removed` computed on
1058    /// the staged state) with the marker form's empty `write_id`; an
1059    /// illegal one returns the same refusal a real call would. No
1060    /// edge, stub, or commit lands.
1061    pub fn batch_relate(
1062        &mut self,
1063        relates: Vec<(RelateEntityArgs, Option<String>)>,
1064        actor: Actor,
1065        client: Option<&ClientId>,
1066        dry_run: bool,
1067    ) -> Result<crate::ops::BatchResult, EngineError> {
1068        if relates.is_empty() {
1069            return Ok(crate::ops::BatchResult {
1070                warnings: Vec::new(),
1071                orphan_stubs_removed: Vec::new(),
1072                errors_suppressed: 0,
1073                applied: true,
1074                results: Vec::new(),
1075                succeeded: 0,
1076                failed: 0,
1077                write_id: String::new(),
1078            });
1079        }
1080
1081        // Reload every touched mem (sources and targets) once, up
1082        // front — the per-entry probe is hoisted out of
1083        // `prepare_relate` for exactly this.
1084        // Short ids on either end resolve once, before the touched-mem
1085        // probe reads each item's mems; an item that does not resolve
1086        // fails as its own error below, never the whole batch.
1087        let mut short_hints: Vec<WarningHint> = Vec::new();
1088        let mut short_errors: Vec<(usize, EngineError)> = Vec::new();
1089        let relates: Vec<(RelateEntityArgs, Option<String>)> = relates
1090            .into_iter()
1091            .enumerate()
1092            .map(|(i, (mut a, n))| {
1093                match self.resolve_entity_id(&a.source) {
1094                    Ok((s, hint)) => {
1095                        a.source = s;
1096                        short_hints.extend(hint);
1097                    }
1098                    Err(e) => short_errors.push((i, e)),
1099                }
1100                match self.resolve_entity_id(&a.target) {
1101                    Ok((t, hint)) => {
1102                        a.target = t;
1103                        short_hints.extend(hint);
1104                    }
1105                    Err(e) => short_errors.push((i, e)),
1106                }
1107                (a, n)
1108            })
1109            .collect();
1110        let mut touched_mems: Vec<String> = relates
1111            .iter()
1112            .flat_map(|(a, _)| [a.source.mem().to_string(), a.target.mem().to_string()])
1113            .collect();
1114        touched_mems.sort();
1115        touched_mems.dedup();
1116        // A mem that is only ever a TARGET in this batch and is
1117        // deferred stays unloaded: target verification runs against
1118        // storage (flywheel W7/02), and the funnel's phase-0 trigger
1119        // would otherwise convert verification into a full load.
1120        // Source mems always reload — a write into a mem needs the mem.
1121        let source_mems: std::collections::HashSet<&str> =
1122            relates.iter().map(|(a, _)| a.source.mem()).collect();
1123        touched_mems.retain(|m| source_mems.contains(m.as_str()) || !self.mem_is_deferred(m));
1124        for m in &touched_mems {
1125            self.reload_if_stale(Some(m));
1126        }
1127        // Same acyclic-guard rule as the single-item path: any added
1128        // edge on an ACYCLIC rel-type (or a rel-type in an
1129        // `acyclic_sets` set, whose guard walks the set's UNION
1130        // subgraph) walks the whole subgraph, so the walk must see
1131        // every mem — deferred (lazy, unloaded) ones included — or a
1132        // cycle through an unloaded mem is admitted (the fifth
1133        // lazy-mount grade demonstrated exactly that through this
1134        // path). Declared signals on either endpoint's schema need
1135        // the full load for the same reason as the single-item path.
1136        if relates.iter().any(|(a, _)| {
1137            (!a.remove
1138                && self.schemas.get(a.source.mem()).is_some_and(|s| {
1139                    s.relationship_acyclic(&a.rel_type)
1140                        || s.acyclic_set_containing(&a.rel_type).is_some()
1141                }))
1142                || [a.source.mem(), a.target.mem()].iter().any(|m| {
1143                    self.schemas
1144                        .get(*m)
1145                        .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
1146                })
1147        }) {
1148            self.ensure_mems_loaded(None);
1149        }
1150
1151        // Snapshot for the all-or-nothing rollback: staged entries
1152        // mutate the store as they apply (in-order semantics), so a
1153        // refusal restores this snapshot and discards every backend's
1154        // pending buffer. Any early-return added below MUST do both.
1155        let store_snapshot = self.store.clone();
1156
1157        enum ItemState {
1158            Applied(&'static str),
1159            Noop,
1160            Error,
1161        }
1162        let mut items: Vec<(EntityId, ItemState)> = Vec::with_capacity(relates.len());
1163        let mut prepared: Vec<PreparedRelate> = Vec::new();
1164        let mut notes: Vec<Option<String>> = Vec::new();
1165        let mut errors: Vec<(usize, EngineError)> = Vec::new();
1166
1167        for (i, (args, note)) in relates.into_iter().enumerate() {
1168            let source_id = args.source.clone();
1169            if let Some(pos) = short_errors.iter().position(|(j, _)| *j == i) {
1170                let (_, e) = short_errors.remove(pos);
1171                items.push((source_id, ItemState::Error));
1172                errors.push((i, e));
1173                continue;
1174            }
1175            // Rehearsal is batch-level (the `dry_run` parameter) —
1176            // per-entry dry-run stays forced off; the staging below is
1177            // what gives later entries in-order semantics, and the
1178            // batch-level rollback undoes it.
1179            let mut args = args;
1180            args.dry_run = false;
1181            match self.prepare_relate(args, Vec::new()) {
1182                Ok(RelatePrepareOutcome::Done(_)) => {
1183                    items.push((source_id, ItemState::Noop));
1184                }
1185                Ok(RelatePrepareOutcome::Prepared(p)) => {
1186                    // Stage + apply NOW so later entries validate
1187                    // against this entry's effect (applied-in-order).
1188                    if let Err(e) = self.stage_prepared_relate(&p) {
1189                        self.store = store_snapshot;
1190                        self.discard_all_pending();
1191                        return Err(e);
1192                    }
1193                    if let Err(e) = self.apply_prepared_relate_to_store(&p) {
1194                        self.store = store_snapshot;
1195                        self.discard_all_pending();
1196                        return Err(e);
1197                    }
1198                    // Derivation baseline (plan 12) — same predicate
1199                    // and staging as the single-item path; rides the
1200                    // batch commit, rolls back with a refusal. (Batch
1201                    // no-op entries do NOT re-baseline — the explicit
1202                    // "reviewed, still holds" gesture is the single
1203                    // relate / single-op MCP list.)
1204                    if let Some(schema) = self.schemas.get(&p.source_mem)
1205                        && super::rel_type_declares_derivation(schema, &p.rel_type)
1206                    {
1207                        let backend = self.mounts[p.mount_idx].backend.as_ref();
1208                        let (from, rel, to) =
1209                            (p.from.to_string(), p.rel_type.clone(), p.to.to_string());
1210                        let staged = match p.action {
1211                            RelateAction::Added => {
1212                                let hash = self
1213                                    .store
1214                                    .get(&p.to)
1215                                    .map(|e| e.content_hash.clone())
1216                                    .unwrap_or_default();
1217                                super::stage_derivation_sidecar(backend, |s| {
1218                                    s.set(&from, &rel, &to, &hash)
1219                                })
1220                            }
1221                            RelateAction::Removed => {
1222                                super::stage_derivation_sidecar(backend, |s| {
1223                                    s.remove(&from, &rel, &to)
1224                                })
1225                            }
1226                            _ => Ok(()),
1227                        };
1228                        if let Err(e) = staged {
1229                            self.store = store_snapshot;
1230                            self.discard_all_pending();
1231                            return Err(e);
1232                        }
1233                    }
1234                    let label = match p.action {
1235                        RelateAction::Added => "added",
1236                        RelateAction::Removed => "removed",
1237                        _ => unreachable!("no-ops resolve to Done"),
1238                    };
1239                    items.push((source_id, ItemState::Applied(label)));
1240                    prepared.push(p);
1241                    notes.push(note);
1242                }
1243                Err(e) => {
1244                    items.push((source_id, ItemState::Error));
1245                    errors.push((i, e));
1246                }
1247            }
1248        }
1249
1250        if !errors.is_empty() {
1251            // Refuse the whole batch; roll back every staged entry.
1252            self.store = store_snapshot;
1253            self.discard_all_pending();
1254            let failed = errors.len();
1255            let mut error_map: std::collections::HashMap<usize, EngineError> =
1256                errors.into_iter().collect();
1257            let mut reported = 0usize;
1258            let mut suppressed = 0usize;
1259            let results: Vec<crate::ops::BatchEntry> = items
1260                .into_iter()
1261                .enumerate()
1262                .map(|(i, (id, _))| match error_map.remove(&i) {
1263                    Some(e) => {
1264                        if reported < Self::BATCH_ERROR_REPORT_CAP {
1265                            reported += 1;
1266                            crate::ops::BatchEntry {
1267                                id,
1268                                action: "error".to_string(),
1269                                error: Some(super::update::batch_error_envelope(&e)),
1270                            }
1271                        } else {
1272                            suppressed += 1;
1273                            crate::ops::BatchEntry {
1274                                id,
1275                                action: "error".to_string(),
1276                                error: None,
1277                            }
1278                        }
1279                    }
1280                    None => crate::ops::BatchEntry {
1281                        id,
1282                        action: "not_applied".to_string(),
1283                        error: None,
1284                    },
1285                })
1286                .collect();
1287            return Ok(crate::ops::BatchResult {
1288                warnings: Vec::new(),
1289                orphan_stubs_removed: Vec::new(),
1290                errors_suppressed: suppressed,
1291                applied: false,
1292                results,
1293                succeeded: 0,
1294                failed,
1295                write_id: String::new(),
1296            });
1297        }
1298
1299        // Rehearsal: every entry validated in order against the state
1300        // its predecessors produced and nothing failed — stop before
1301        // any commit. The would-be orphan GC is computed on the staged
1302        // store (honest: it is exactly what the real call would
1303        // collect), then the whole staged state rolls back.
1304        if dry_run {
1305            let removed_targets: Vec<EntityId> = prepared
1306                .iter()
1307                .filter(|p| matches!(p.action, RelateAction::Removed))
1308                .map(|p| p.to.clone())
1309                .collect();
1310            let orphan_stubs_removed =
1311                super::gc_orphan_stubs_among(&mut self.store, removed_targets.iter());
1312            self.store = store_snapshot;
1313            self.discard_all_pending();
1314            let succeeded = items.len();
1315            let results: Vec<crate::ops::BatchEntry> = items
1316                .into_iter()
1317                .map(|(id, state)| crate::ops::BatchEntry {
1318                    id,
1319                    action: match state {
1320                        ItemState::Applied(label) => label.to_string(),
1321                        ItemState::Noop => "noop".to_string(),
1322                        ItemState::Error => unreachable!("refusal path returned above"),
1323                    },
1324                    error: None,
1325                })
1326                .collect();
1327            return Ok(crate::ops::BatchResult {
1328                warnings: Vec::new(),
1329                orphan_stubs_removed,
1330                errors_suppressed: 0,
1331                applied: true,
1332                results,
1333                succeeded,
1334                failed: 0,
1335                write_id: String::new(),
1336            });
1337        }
1338
1339        // --- Commit once per touched mount, in first-seen order. ---
1340        let mut distinct_mounts: Vec<usize> = Vec::new();
1341        for p in &prepared {
1342            if !distinct_mounts.contains(&p.mount_idx) {
1343                distinct_mounts.push(p.mount_idx);
1344            }
1345        }
1346        let mut mount_commits: Vec<(usize, String)> = Vec::with_capacity(distinct_mounts.len());
1347        for &m in &distinct_mounts {
1348            // Distinct source ids for this mount (an entity may carry
1349            // several edge changes in one batch).
1350            let mut entity_ids: Vec<String> = Vec::new();
1351            let mut edge_count = 0usize;
1352            for p in prepared.iter().filter(|p| p.mount_idx == m) {
1353                edge_count += 1;
1354                let s = p.from.to_string();
1355                if !entity_ids.contains(&s) {
1356                    entity_ids.push(s);
1357                }
1358            }
1359            let subject = format!("memstead: batch-relate ({edge_count} edges)");
1360            // Per-entry notes ride the batch commit's note record as
1361            // `<id>: <note>` lines (decision 3), keyed by the edge's
1362            // source entity — `append_provenance` is a no-op on the
1363            // git-branch backend. No notes → no note record.
1364            let note_lines: Vec<String> = prepared
1365                .iter()
1366                .zip(notes.iter())
1367                .filter(|(p, _)| p.mount_idx == m)
1368                .filter_map(|(p, n)| n.as_ref().map(|n| format!("{}: {n}", p.from)))
1369                .collect();
1370            let ctx = CommitContext {
1371                actor,
1372                client: client.cloned(),
1373                tool: Some("batch_relate"),
1374                note: if note_lines.is_empty() {
1375                    None
1376                } else {
1377                    Some(note_lines.join("\n"))
1378                },
1379                role: self.current_role,
1380                identity: self.current_identity.clone(),
1381                logical_operation_id: None,
1382                entity_ids: Some(entity_ids),
1383            };
1384            match self.mounts[m].backend.commit(&subject, &ctx) {
1385                Ok(sha) => mount_commits.push((m, sha)),
1386                Err(e) => {
1387                    // A commit failed: roll back the store and any
1388                    // still-pending backends. Mems already committed
1389                    // in this loop stay committed (the family's
1390                    // per-mem atomicity).
1391                    self.store = store_snapshot;
1392                    self.discard_all_pending();
1393                    return Err(e.into());
1394                }
1395            }
1396        }
1397
1398        // Provenance per entry, self-write markers per mount.
1399        let mut batch_warnings: Vec<WarningHint> = short_hints;
1400        for (p, note) in prepared.iter().zip(notes.iter()) {
1401            let write_id = mount_commits
1402                .iter()
1403                .find(|(m, _)| *m == p.mount_idx)
1404                .map(|(_, s)| s.clone())
1405                .unwrap_or_default();
1406            self.mounts[p.mount_idx].backend.append_provenance(
1407                &Provenance::new(
1408                    std::time::SystemTime::now(),
1409                    ProvenanceKind::Relate,
1410                    Some(p.from.to_string()),
1411                    actor,
1412                    client.cloned(),
1413                    note.clone(),
1414                )
1415                .with_role(self.current_role)
1416                .with_identity(self.current_identity.clone()),
1417            )?;
1418            self.record_self_write(p.mount_idx, &write_id);
1419            batch_warnings.extend(self.stamp_mutation_versions(p.mount_idx));
1420        }
1421
1422        // Orphan-stub GC over every removed edge's target — same
1423        // scoped sweep and shared predicate as the single-item path.
1424        let removed_targets: Vec<EntityId> = prepared
1425            .iter()
1426            .filter(|p| matches!(p.action, RelateAction::Removed))
1427            .map(|p| p.to.clone())
1428            .collect();
1429        let orphan_stubs_removed =
1430            super::gc_orphan_stubs_among(&mut self.store, removed_targets.iter());
1431
1432        self.invalidate_communities();
1433        self.invalidate_search_indexes();
1434
1435        let write_id = mount_commits
1436            .last()
1437            .map(|(_, s)| s.clone())
1438            .unwrap_or_default();
1439        let succeeded = items.len();
1440        let results: Vec<crate::ops::BatchEntry> = items
1441            .into_iter()
1442            .map(|(id, state)| crate::ops::BatchEntry {
1443                id,
1444                action: match state {
1445                    ItemState::Applied(label) => label.to_string(),
1446                    ItemState::Noop => "noop".to_string(),
1447                    ItemState::Error => unreachable!("refusal path returned above"),
1448                },
1449                error: None,
1450            })
1451            .collect();
1452
1453        Ok(crate::ops::BatchResult {
1454            warnings: batch_warnings,
1455            orphan_stubs_removed,
1456            errors_suppressed: 0,
1457            applied: true,
1458            results,
1459            succeeded,
1460            failed: 0,
1461            write_id,
1462        })
1463    }
1464
1465    /// Positional-args alias for [`Self::relate_entity`]. Bundles
1466    /// the positional inputs into a [`RelateEntityArgs`] (with
1467    /// `expected_hash: None`) and delegates to
1468    /// [`Self::relate_entity`]. The `CommitContext` is destructured
1469    /// into the 4-tuple (actor, client, note) the unified mutation
1470    /// surface accepts.
1471    pub fn relate(
1472        &mut self,
1473        from: &EntityId,
1474        to: &EntityId,
1475        rel_type: &str,
1476        remove: bool,
1477        ctx: &CommitContext<'_>,
1478    ) -> Result<RelateEntityOutcome, EngineError> {
1479        let args = RelateEntityArgs {
1480            source: from.clone(),
1481            expected_hash: None,
1482            rel_type: rel_type.to_string(),
1483            target: to.clone(),
1484            remove,
1485            description: None,
1486            dry_run: false,
1487        };
1488        self.relate_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
1489    }
1490}
1491
1492#[cfg(test)]
1493mod tests {
1494
1495    use indexmap::IndexMap;
1496    use tempfile::TempDir;
1497
1498    use crate::backend::MemBackend;
1499    use crate::engine::test_helpers::*;
1500    use crate::engine::{CreateEntityArgs, Engine, EngineError, RelateAction, RelateEntityArgs};
1501    use crate::ops::WarningHint;
1502    use crate::storage::FilesystemMemWriter;
1503    use crate::vcs::{Actor, CommitContext};
1504
1505    #[test]
1506    fn relate_alias_delegates_to_relate_entity() {
1507        // Positional-args alias mirrors full's signature
1508        // `engine.relate(from, to, rel_type, remove, ctx)`. Add an
1509        // edge via the alias and via `relate_entity` and assert
1510        // they reach the same observable post-state.
1511        let tmp = TempDir::new().unwrap();
1512        let mem_dir = tmp.path().to_path_buf();
1513        let writer = FilesystemMemWriter::new(mem_dir.clone());
1514        let mut engine = Engine::from_mounts(vec![(
1515            folder_mount("specs", mem_dir),
1516            Box::new(writer) as Box<dyn MemBackend>,
1517        )])
1518        .unwrap();
1519
1520        // Seed two real entities (no stub).
1521        let a = engine
1522            .create_entity(
1523                CreateEntityArgs {
1524                    anchors: Vec::new(),
1525                    mem: "specs".to_string(),
1526                    title: "A".to_string(),
1527                    entity_type: "spec".to_string(),
1528                    sections: IndexMap::from_iter([
1529                        ("identity".to_string(), "seed identity".to_string()),
1530                        ("purpose".to_string(), "seed purpose".to_string()),
1531                    ]),
1532                    metadata: IndexMap::new(),
1533                    relations: Vec::new(),
1534                    dry_run: false,
1535                },
1536                Actor::Cli,
1537                None,
1538                None,
1539            )
1540            .unwrap();
1541        let b = engine
1542            .create_entity(
1543                CreateEntityArgs {
1544                    anchors: Vec::new(),
1545                    mem: "specs".to_string(),
1546                    title: "B".to_string(),
1547                    entity_type: "spec".to_string(),
1548                    sections: IndexMap::from_iter([
1549                        ("identity".to_string(), "seed identity".to_string()),
1550                        ("purpose".to_string(), "seed purpose".to_string()),
1551                    ]),
1552                    metadata: IndexMap::new(),
1553                    relations: Vec::new(),
1554                    dry_run: false,
1555                },
1556                Actor::Cli,
1557                None,
1558                None,
1559            )
1560            .unwrap();
1561
1562        // Use the positional `relate` alias.
1563        let ctx = CommitContext::internal();
1564        let result = engine.relate(&a.id, &b.id, "PART_OF", false, &ctx).unwrap();
1565        assert_eq!(result.from, a.id);
1566        assert_eq!(result.to, b.id);
1567        assert_eq!(result.rel_type, "PART_OF");
1568        // The edge is in the store post-call.
1569        let outgoing: Vec<_> = engine.store().outgoing(&a.id).to_vec();
1570        assert!(
1571            outgoing
1572                .iter()
1573                .any(|e| e.target == b.id && e.rel_type == "PART_OF")
1574        );
1575    }
1576
1577    #[test]
1578    fn relate_entity_appends_relationship_and_logs_provenance() {
1579        let tmp = TempDir::new().unwrap();
1580        let (mut engine, source) = engine_with_seed(&tmp, "Source");
1581        let (actor, client) = cli_actor();
1582        let target = engine
1583            .create_entity(
1584                empty_create_args("specs", "Target"),
1585                actor,
1586                Some(&client),
1587                None,
1588            )
1589            .unwrap();
1590
1591        let outcome = engine
1592            .relate_entity(
1593                RelateEntityArgs {
1594                    source: source.id.clone(),
1595                    expected_hash: Some(source.content_hash.clone()),
1596                    rel_type: "USES".to_string(),
1597                    target: target.id.clone(),
1598                    remove: false,
1599                    description: None,
1600                    dry_run: false,
1601                },
1602                actor,
1603                Some(&client),
1604                None,
1605            )
1606            .unwrap();
1607        assert_eq!(outcome.action, RelateAction::Added);
1608        assert_ne!(outcome.content_hash, source.content_hash);
1609        // Edge present in store.
1610        let edges = engine.store().outgoing(&source.id);
1611        assert!(
1612            edges
1613                .iter()
1614                .any(|e| e.rel_type == "USES" && e.target == target.id),
1615            "expected USES edge in store"
1616        );
1617        // Provenance log records relate.
1618        let log = std::fs::read_to_string(tmp.path().join(".memstead/changes.jsonl")).unwrap();
1619        assert!(log.contains("\"kind\":\"relate\""));
1620    }
1621
1622    #[test]
1623    fn relate_entity_no_op_when_already_present() {
1624        let tmp = TempDir::new().unwrap();
1625        let (mut engine, source) = engine_with_seed(&tmp, "Already");
1626        let (actor, client) = cli_actor();
1627        let target = engine
1628            .create_entity(empty_create_args("specs", "T2"), actor, Some(&client), None)
1629            .unwrap();
1630        let first = engine
1631            .relate_entity(
1632                RelateEntityArgs {
1633                    source: source.id.clone(),
1634                    expected_hash: Some(source.content_hash.clone()),
1635                    rel_type: "USES".to_string(),
1636                    target: target.id.clone(),
1637                    remove: false,
1638                    description: None,
1639                    dry_run: false,
1640                },
1641                actor,
1642                Some(&client),
1643                None,
1644            )
1645            .unwrap();
1646        let second = engine
1647            .relate_entity(
1648                RelateEntityArgs {
1649                    source: source.id.clone(),
1650                    expected_hash: Some(first.content_hash.clone()),
1651                    rel_type: "USES".to_string(),
1652                    target: target.id.clone(),
1653                    remove: false,
1654                    description: None,
1655                    dry_run: false,
1656                },
1657                actor,
1658                Some(&client),
1659                None,
1660            )
1661            .unwrap();
1662        assert_eq!(second.action, RelateAction::NoOpAlreadyPresent);
1663        // Hash unchanged on no-op.
1664        assert_eq!(second.content_hash, first.content_hash);
1665    }
1666
1667    #[test]
1668    fn relate_entity_returns_write_id_on_real_write() {
1669        let tmp = TempDir::new().unwrap();
1670        let (mut engine, source) = engine_with_seed(&tmp, "Source");
1671        let (actor, client) = cli_actor();
1672        let target = engine
1673            .create_entity(
1674                empty_create_args("specs", "Target"),
1675                actor,
1676                Some(&client),
1677                None,
1678            )
1679            .unwrap();
1680
1681        let outcome = engine
1682            .relate_entity(
1683                RelateEntityArgs {
1684                    source: source.id.clone(),
1685                    expected_hash: Some(source.content_hash.clone()),
1686                    rel_type: "USES".to_string(),
1687                    target: target.id.clone(),
1688                    remove: false,
1689                    description: None,
1690                    dry_run: false,
1691                },
1692                actor,
1693                Some(&client),
1694                None,
1695            )
1696            .unwrap();
1697        // Folder backend returns a synthetic CommitId — non-empty string.
1698        // Wire-equivalent to full's commit SHA: agents reading the field
1699        // get a usable cursor regardless of which backend served the write.
1700        assert!(
1701            !outcome.write_id.is_empty(),
1702            "write_id must be populated on a real write"
1703        );
1704    }
1705
1706    #[test]
1707    fn relate_entity_no_op_paths_carry_typed_warnings_and_empty_write_id() {
1708        let tmp = TempDir::new().unwrap();
1709        let (mut engine, source) = engine_with_seed(&tmp, "S");
1710        let (actor, client) = cli_actor();
1711        let target = engine
1712            .create_entity(empty_create_args("specs", "T"), actor, Some(&client), None)
1713            .unwrap();
1714
1715        // Add the edge once.
1716        let first = engine
1717            .relate_entity(
1718                RelateEntityArgs {
1719                    source: source.id.clone(),
1720                    expected_hash: Some(source.content_hash.clone()),
1721                    rel_type: "USES".to_string(),
1722                    target: target.id.clone(),
1723                    remove: false,
1724                    description: None,
1725                    dry_run: false,
1726                },
1727                actor,
1728                Some(&client),
1729                None,
1730            )
1731            .unwrap();
1732
1733        // Duplicate-add — typed DuplicateRelationship warning, empty
1734        // write_id (no disk write happened).
1735        let dup = engine
1736            .relate_entity(
1737                RelateEntityArgs {
1738                    source: source.id.clone(),
1739                    expected_hash: Some(first.content_hash.clone()),
1740                    rel_type: "USES".to_string(),
1741                    target: target.id.clone(),
1742                    remove: false,
1743                    description: None,
1744                    dry_run: false,
1745                },
1746                actor,
1747                Some(&client),
1748                None,
1749            )
1750            .unwrap();
1751        assert_eq!(dup.action, RelateAction::NoOpAlreadyPresent);
1752        assert!(dup.write_id.is_empty());
1753        assert_eq!(dup.warnings.len(), 1);
1754        assert!(matches!(
1755            dup.warnings[0],
1756            WarningHint::DuplicateRelationship { .. }
1757        ));
1758
1759        // Remove a non-existent edge — typed NoSuchRelationship warning,
1760        // empty write_id.
1761        let no_such = engine
1762            .relate_entity(
1763                RelateEntityArgs {
1764                    source: source.id.clone(),
1765                    expected_hash: Some(first.content_hash.clone()),
1766                    rel_type: "DEPENDS_ON".to_string(),
1767                    target: target.id.clone(),
1768                    remove: true,
1769                    description: None,
1770                    dry_run: false,
1771                },
1772                actor,
1773                Some(&client),
1774                None,
1775            )
1776            .unwrap();
1777        assert_eq!(no_such.action, RelateAction::NoOpAbsent);
1778        assert!(no_such.write_id.is_empty());
1779        assert_eq!(no_such.warnings.len(), 1);
1780        assert!(matches!(
1781            no_such.warnings[0],
1782            WarningHint::NoSuchRelationship { .. }
1783        ));
1784    }
1785
1786    #[test]
1787    fn relate_entity_creates_stub_for_absent_target_on_add_path() {
1788        let tmp = TempDir::new().unwrap();
1789        let (mut engine, source) = engine_with_seed(&tmp, "Source");
1790        let (actor, client) = cli_actor();
1791        let absent_target = crate::EntityId::new("specs", "ghost-target");
1792        // Sanity: target not in store.
1793        assert!(!engine.store().contains(&absent_target));
1794
1795        let outcome = engine
1796            .relate_entity(
1797                RelateEntityArgs {
1798                    source: source.id.clone(),
1799                    expected_hash: Some(source.content_hash.clone()),
1800                    rel_type: "USES".to_string(),
1801                    target: absent_target.clone(),
1802                    remove: false,
1803                    description: None,
1804                    dry_run: false,
1805                },
1806                actor,
1807                Some(&client),
1808                None,
1809            )
1810            .unwrap();
1811
1812        assert_eq!(outcome.action, RelateAction::Added);
1813        assert_eq!(outcome.source, "explicit");
1814        // Auto-stub now surfaces through the typed warning vocabulary
1815        // (`AutoStubCreated`) on `warnings[]` — the deprecated
1816        // top-level `stub_warning` field was retired in favour of the
1817        // uniform diagnostic shape. Agents iterating `warnings[]` see
1818        // the stub id without special-casing a sibling field.
1819        let stub_warning = outcome
1820            .warnings
1821            .iter()
1822            .find_map(|w| match w {
1823                crate::ops::WarningHint::AutoStubCreated { stub_id, .. } => Some(stub_id.clone()),
1824                _ => None,
1825            })
1826            .expect("AutoStubCreated warning must surface when target was absent");
1827        assert_eq!(stub_warning, absent_target);
1828        // The real path keeps the performed-effect wording exactly —
1829        // only the dry-run path carries the conditional form.
1830        let msg = outcome
1831            .warnings
1832            .iter()
1833            .find(|w| matches!(w, crate::ops::WarningHint::AutoStubCreated { .. }))
1834            .unwrap()
1835            .message();
1836        assert!(
1837            msg.contains("stub auto-created"),
1838            "real relate keeps the performed-effect wording: {msg}"
1839        );
1840
1841        // Stub now in-store, marked as stub, no body.
1842        let stub = engine.store().get(&absent_target).expect("stub upserted");
1843        assert!(stub.stub);
1844        assert!(stub.entity_type.is_empty());
1845        assert!(stub.file_path.is_empty());
1846    }
1847
1848    #[test]
1849    fn relate_entity_skips_stub_creation_when_target_already_exists() {
1850        let tmp = TempDir::new().unwrap();
1851        let (mut engine, source) = engine_with_seed(&tmp, "Src");
1852        let (actor, client) = cli_actor();
1853        let target = engine
1854            .create_entity(
1855                empty_create_args("specs", "Real"),
1856                actor,
1857                Some(&client),
1858                None,
1859            )
1860            .unwrap();
1861
1862        let outcome = engine
1863            .relate_entity(
1864                RelateEntityArgs {
1865                    source: source.id.clone(),
1866                    expected_hash: Some(source.content_hash.clone()),
1867                    rel_type: "USES".to_string(),
1868                    target: target.id.clone(),
1869                    remove: false,
1870                    description: None,
1871                    dry_run: false,
1872                },
1873                actor,
1874                Some(&client),
1875                None,
1876            )
1877            .unwrap();
1878
1879        assert!(
1880            !outcome
1881                .warnings
1882                .iter()
1883                .any(|w| matches!(w, crate::ops::WarningHint::AutoStubCreated { .. })),
1884            "AutoStubCreated must not surface when target was already in store"
1885        );
1886        assert_eq!(outcome.source, "explicit");
1887        // Real entity remains a real entity (not coerced to stub).
1888        let target_after = engine.store().get(&target.id).unwrap();
1889        assert!(!target_after.stub);
1890    }
1891
1892    #[test]
1893    fn relate_entity_does_not_create_stub_on_remove_path() {
1894        let tmp = TempDir::new().unwrap();
1895        let (mut engine, source) = engine_with_seed(&tmp, "Src");
1896        let (actor, client) = cli_actor();
1897        let absent_target = crate::EntityId::new("specs", "never-existed");
1898
1899        let outcome = engine
1900            .relate_entity(
1901                RelateEntityArgs {
1902                    source: source.id.clone(),
1903                    expected_hash: Some(source.content_hash.clone()),
1904                    rel_type: "USES".to_string(),
1905                    target: absent_target.clone(),
1906                    remove: true,
1907                    description: None,
1908                    dry_run: false,
1909                },
1910                actor,
1911                Some(&client),
1912                None,
1913            )
1914            .unwrap();
1915
1916        // Remove of an absent edge — no stub creation, NoOpAbsent action,
1917        // typed NoSuchRelationship warning.
1918        assert_eq!(outcome.action, RelateAction::NoOpAbsent);
1919        assert!(
1920            !outcome
1921                .warnings
1922                .iter()
1923                .any(|w| matches!(w, crate::ops::WarningHint::AutoStubCreated { .. })),
1924            "remove path must never auto-stub the target",
1925        );
1926        assert!(!engine.store().contains(&absent_target));
1927    }
1928
1929    #[test]
1930    fn relate_entity_remove_refuses_when_source_body_still_references_target() {
1931        use crate::engine::CreateEntityArgs;
1932        use indexmap::IndexMap;
1933
1934        let tmp = TempDir::new().unwrap();
1935        let mem_dir = tmp.path().to_path_buf();
1936        let writer = FilesystemMemWriter::new(mem_dir.clone());
1937        let mut engine = Engine::from_mounts(vec![(
1938            folder_mount("specs", mem_dir.clone()),
1939            Box::new(writer) as Box<dyn MemBackend>,
1940        )])
1941        .unwrap();
1942        let (actor, client) = cli_actor();
1943
1944        let target = engine
1945            .create_entity(
1946                empty_create_args("specs", "Target"),
1947                actor,
1948                Some(&client),
1949                None,
1950            )
1951            .unwrap();
1952
1953        // Source entity carries a body wiki-link to the target — the
1954        // alias-synthesis pass emits the backing REFERENCES relation
1955        // (default schema's `alias_target_rel_type` points at
1956        // REFERENCES, so explicit `memstead_relate type=REFERENCES` is
1957        // refused; the body link alone produces the relation).
1958        let mut sections: IndexMap<String, String> = IndexMap::new();
1959        sections.insert("identity".to_string(), "source identity".to_string());
1960        sections.insert(
1961            "purpose".to_string(),
1962            "discussion stems from [[target]]".to_string(),
1963        );
1964        let source = engine
1965            .create_entity(
1966                CreateEntityArgs {
1967                    anchors: Vec::new(),
1968                    mem: "specs".to_string(),
1969                    title: "Source".to_string(),
1970                    entity_type: "spec".to_string(),
1971                    sections,
1972                    metadata: IndexMap::new(),
1973                    relations: Vec::new(),
1974                    dry_run: false,
1975                },
1976                actor,
1977                Some(&client),
1978                None,
1979            )
1980            .unwrap();
1981        let related = source.clone();
1982
1983        // Removing the explicit relation while the body still has
1984        // [[target]] must refuse with `RelationHasBodyLinks`, naming
1985        // the surviving section in `body_links`.
1986        let err = engine
1987            .relate_entity(
1988                RelateEntityArgs {
1989                    source: source.id.clone(),
1990                    expected_hash: Some(related.content_hash.clone()),
1991                    rel_type: "REFERENCES".to_string(),
1992                    target: target.id.clone(),
1993                    remove: true,
1994                    description: None,
1995                    dry_run: false,
1996                },
1997                actor,
1998                Some(&client),
1999                None,
2000            )
2001            .unwrap_err();
2002        match err {
2003            EngineError::RelationHasBodyLinks {
2004                from_id,
2005                to_id,
2006                rel_type,
2007                body_links,
2008            } => {
2009                assert_eq!(from_id, source.id.to_string());
2010                assert_eq!(to_id, target.id.to_string());
2011                assert_eq!(rel_type, "REFERENCES");
2012                assert_eq!(body_links, vec!["purpose".to_string()]);
2013            }
2014            other => panic!("expected RelationHasBodyLinks, got {other:?}"),
2015        }
2016        // Relation must still be present in-memory (refuse before any
2017        // store mutation).
2018        let in_mem = engine.get_entity(&source.id).unwrap();
2019        assert!(
2020            in_mem
2021                .relationships
2022                .iter()
2023                .any(|r| r.rel_type == "REFERENCES" && r.target == target.id),
2024            "relation must survive the refused remove; got {:?}",
2025            in_mem.relationships
2026        );
2027    }
2028
2029    #[test]
2030    fn relate_entity_remove_succeeds_when_body_no_longer_references_target() {
2031        let tmp = TempDir::new().unwrap();
2032        let (mut engine, source) = engine_with_seed(&tmp, "Src");
2033        let (actor, client) = cli_actor();
2034        let target = engine
2035            .create_entity(
2036                empty_create_args("specs", "Other"),
2037                actor,
2038                Some(&client),
2039                None,
2040            )
2041            .unwrap();
2042        // Default seed has empty body sections, so the relation can be
2043        // added and removed without body-link interference. This locks
2044        // the happy path: when no body link survives, remove proceeds.
2045        // (USES instead of REFERENCES — REFERENCES is engine-emitted-only
2046        // under the default schema's alias_target_rel_type pointer.)
2047        let related = engine
2048            .relate_entity(
2049                RelateEntityArgs {
2050                    source: source.id.clone(),
2051                    expected_hash: Some(source.content_hash.clone()),
2052                    rel_type: "USES".to_string(),
2053                    target: target.id.clone(),
2054                    remove: false,
2055                    description: None,
2056                    dry_run: false,
2057                },
2058                actor,
2059                Some(&client),
2060                None,
2061            )
2062            .unwrap();
2063        let removed = engine
2064            .relate_entity(
2065                RelateEntityArgs {
2066                    source: source.id.clone(),
2067                    expected_hash: Some(related.content_hash.clone()),
2068                    rel_type: "USES".to_string(),
2069                    target: target.id.clone(),
2070                    remove: true,
2071                    description: None,
2072                    dry_run: false,
2073                },
2074                actor,
2075                Some(&client),
2076                None,
2077            )
2078            .unwrap();
2079        assert_eq!(removed.action, RelateAction::Removed);
2080    }
2081
2082    #[test]
2083    fn relate_entity_auto_stub_is_tagged_forward_reference() {
2084        // `memstead_relate` to an absent target auto-stubs it. The stub's
2085        // `stub_kind` records the origin (`ForwardReference`) so an
2086        // agent reading the stub later via `memstead_entity` sees the
2087        // typed provenance — not just `stub: true`.
2088        use crate::entity::StubKind;
2089
2090        let tmp = TempDir::new().unwrap();
2091        let (mut engine, source) = engine_with_seed(&tmp, "Src");
2092        let (actor, client) = cli_actor();
2093        let absent_target = crate::EntityId::new("specs", "absent-target");
2094
2095        let _ = engine
2096            .relate_entity(
2097                RelateEntityArgs {
2098                    source: source.id.clone(),
2099                    expected_hash: Some(source.content_hash.clone()),
2100                    rel_type: "USES".to_string(),
2101                    target: absent_target.clone(),
2102                    remove: false,
2103                    description: None,
2104                    dry_run: false,
2105                },
2106                actor,
2107                Some(&client),
2108                None,
2109            )
2110            .unwrap();
2111
2112        let stub = engine
2113            .get_entity(&absent_target)
2114            .expect("relate auto-stubbed target must be in the store");
2115        assert!(stub.stub, "auto-stubbed target must carry stub: true");
2116        assert_eq!(
2117            stub.stub_kind,
2118            Some(StubKind::ForwardReference),
2119            "auto-stub from relate must be tagged ForwardReference; got {:?}",
2120            stub.stub_kind
2121        );
2122    }
2123
2124    #[test]
2125    fn relate_entity_case_insensitive_rel_type_input_canonicalises_to_upper_snake_case() {
2126        // Wire-level contract: rel_type input is case-insensitive; the
2127        // engine stores it as UPPER_SNAKE_CASE and echoes the canonical
2128        // form back in the response. Same store-shape regardless of
2129        // input case.
2130        let tmp = TempDir::new().unwrap();
2131        let (mut engine, source) = engine_with_seed(&tmp, "Source");
2132        let (actor, client) = cli_actor();
2133        let target = engine
2134            .create_entity(
2135                empty_create_args("specs", "Target"),
2136                actor,
2137                Some(&client),
2138                None,
2139            )
2140            .unwrap();
2141
2142        // Lowercase input — must succeed and store as `USES`.
2143        let lower = engine
2144            .relate_entity(
2145                RelateEntityArgs {
2146                    source: source.id.clone(),
2147                    expected_hash: Some(source.content_hash.clone()),
2148                    rel_type: "uses".to_string(),
2149                    target: target.id.clone(),
2150                    remove: false,
2151                    description: None,
2152                    dry_run: false,
2153                },
2154                actor,
2155                Some(&client),
2156                None,
2157            )
2158            .unwrap();
2159        assert_eq!(lower.rel_type, "USES", "response must echo canonical form");
2160        assert_eq!(lower.action, RelateAction::Added);
2161        let edges = engine.store().outgoing(&source.id);
2162        assert!(
2163            edges
2164                .iter()
2165                .any(|e| e.rel_type == "USES" && e.target == target.id),
2166            "store must hold UPPER_SNAKE_CASE rel_type after lowercase input"
2167        );
2168
2169        // Adding via mixed-case input on the same edge is the canonical
2170        // duplicate — DuplicateRelationship warning, no second store
2171        // entry.
2172        let dup = engine
2173            .relate_entity(
2174                RelateEntityArgs {
2175                    source: source.id.clone(),
2176                    expected_hash: Some(lower.content_hash.clone()),
2177                    rel_type: "Uses".to_string(),
2178                    target: target.id.clone(),
2179                    remove: false,
2180                    description: None,
2181                    dry_run: false,
2182                },
2183                actor,
2184                Some(&client),
2185                None,
2186            )
2187            .unwrap();
2188        assert_eq!(dup.action, RelateAction::NoOpAlreadyPresent);
2189        assert_eq!(dup.rel_type, "USES");
2190        assert!(matches!(
2191            dup.warnings[0],
2192            WarningHint::DuplicateRelationship { .. }
2193        ));
2194    }
2195
2196    #[test]
2197    fn relate_entity_rejects_cross_mem_when_policy_denies() {
2198        // Default workspace settings carry no `cross_mem_links`
2199        // policy and no `default_cross_links` on the create rules, so
2200        // `cross_mem_link_allowed` returns false for any cross-mem
2201        // pair. The relate refuse now surfaces the typed
2202        // policy-denial code instead of the legacy categorical
2203        // `CrossMemRelate`.
2204        let tmp = TempDir::new().unwrap();
2205        let (mut engine, source) = engine_with_seed(&tmp, "S");
2206        let (actor, client) = cli_actor();
2207        let err = engine
2208            .relate_entity(
2209                RelateEntityArgs {
2210                    source: source.id.clone(),
2211                    expected_hash: Some(source.content_hash.clone()),
2212                    rel_type: "USES".to_string(),
2213                    target: crate::EntityId::new("other-mem", "thing"),
2214                    remove: false,
2215                    description: None,
2216                    dry_run: false,
2217                },
2218                actor,
2219                Some(&client),
2220                None,
2221            )
2222            .unwrap_err();
2223        match err {
2224            EngineError::CrossMemLinkNotAllowed { from_mem, to_mem } => {
2225                assert_eq!(from_mem, "specs");
2226                assert_eq!(to_mem, "other-mem");
2227            }
2228            other => panic!("expected CrossMemLinkNotAllowed, got {other:?}"),
2229        }
2230    }
2231
2232    /// Bare-string target without a `mem--` separator is malformed
2233    /// (the wiki-link grammar requires `<mem>--<path>`). Pre-fix
2234    /// the cross-mem check fired first: the parser saw `mem: ""`,
2235    /// compared against the source mem, and produced
2236    /// `CROSS_MEM_RELATION` — pointing the agent at workspace
2237    /// `[cross_mem_links]` policy when the actual issue was a
2238    /// malformed id. Post-fix the grammar gate runs first; the
2239    /// envelope identifies the real problem.
2240    #[test]
2241    fn relate_entity_malformed_bare_target_surfaces_invalid_entity_id_not_cross_mem() {
2242        let tmp = TempDir::new().unwrap();
2243        let (mut engine, source) = engine_with_seed(&tmp, "S");
2244        let (actor, client) = cli_actor();
2245        let err = engine
2246            .relate_entity(
2247                RelateEntityArgs {
2248                    source: source.id.clone(),
2249                    expected_hash: Some(source.content_hash.clone()),
2250                    rel_type: "USES".to_string(),
2251                    // No `--` separator AND contains characters the
2252                    // grammar rejects. Parses as mem="", path=raw.
2253                    target: crate::EntityId("bad target with spaces!!".to_string()),
2254                    remove: false,
2255                    description: None,
2256                    dry_run: false,
2257                },
2258                actor,
2259                Some(&client),
2260                None,
2261            )
2262            .unwrap_err();
2263        assert!(
2264            matches!(err, EngineError::InvalidEntityId { .. }),
2265            "malformed bare-string target must surface INVALID_ENTITY_ID, got: {err:?}"
2266        );
2267    }
2268
2269    /// Companion case: target carries the source's mem prefix but a
2270    /// grammar-violating path. The grammar check fires (same path as
2271    /// the bare-string case); cross-mem stays out of the picture
2272    /// because mems match.
2273    #[test]
2274    fn relate_entity_malformed_prefixed_target_surfaces_invalid_entity_id() {
2275        let tmp = TempDir::new().unwrap();
2276        let (mut engine, source) = engine_with_seed(&tmp, "S");
2277        let (actor, client) = cli_actor();
2278        let source_mem = source.id.mem().to_string();
2279        let err = engine
2280            .relate_entity(
2281                RelateEntityArgs {
2282                    source: source.id.clone(),
2283                    expected_hash: Some(source.content_hash.clone()),
2284                    rel_type: "USES".to_string(),
2285                    target: crate::EntityId(format!("{source_mem}--bad target with spaces!!")),
2286                    remove: false,
2287                    description: None,
2288                    dry_run: false,
2289                },
2290                actor,
2291                Some(&client),
2292                None,
2293            )
2294            .unwrap_err();
2295        assert!(
2296            matches!(err, EngineError::InvalidEntityId { .. }),
2297            "prefixed malformed target must still surface INVALID_ENTITY_ID, got: {err:?}"
2298        );
2299    }
2300
2301    // ---- Auto-timestamp on relate add/remove ------------------------
2302
2303    /// `memstead_relate add` rewrites the
2304    /// source's on-disk file, so its `last_modified` auto-stamp must
2305    /// bump. The schema's default-stamped field is `last_modified`.
2306    #[test]
2307    fn relate_add_bumps_last_modified_on_source_entity() {
2308        let tmp = TempDir::new().unwrap();
2309        let (mut engine, source) = engine_with_seed(&tmp, "S");
2310        let (actor, client) = cli_actor();
2311        let target = engine
2312            .create_entity(empty_create_args("specs", "T"), actor, Some(&client), None)
2313            .unwrap();
2314
2315        let outcome = engine
2316            .relate_entity(
2317                RelateEntityArgs {
2318                    source: source.id.clone(),
2319                    expected_hash: Some(source.content_hash.clone()),
2320                    rel_type: "USES".to_string(),
2321                    target: target.id.clone(),
2322                    remove: false,
2323                    description: None,
2324                    dry_run: false,
2325                },
2326                actor,
2327                Some(&client),
2328                None,
2329            )
2330            .unwrap();
2331        assert_eq!(outcome.action, RelateAction::Added);
2332
2333        // last_modified now carries a fresh ISO timestamp on the
2334        // source entity. The auto-stamp helper sets every
2335        // `auto_timestamp: true` metadata field on each commit-
2336        // producing relate mutation.
2337        let post = engine.get_entity(&source.id).unwrap();
2338        let last_modified = post
2339            .metadata
2340            .get("last_modified")
2341            .map(|v| v.to_frontmatter_string())
2342            .unwrap_or_default();
2343        assert!(
2344            last_modified.starts_with("20"),
2345            "last_modified must carry an ISO timestamp post-relate; got: {last_modified:?}"
2346        );
2347    }
2348
2349    /// Relate-add no-op (idempotent
2350    /// re-add) skips the disk write and therefore does not advance
2351    /// `last_modified`. The auto-stamp fires only on commit-producing
2352    /// mutations — wired into the post-no-op-short-circuit branch.
2353    #[test]
2354    fn relate_add_noop_does_not_bump_last_modified() {
2355        let tmp = TempDir::new().unwrap();
2356        let (mut engine, source) = engine_with_seed(&tmp, "S");
2357        let (actor, client) = cli_actor();
2358        let target = engine
2359            .create_entity(empty_create_args("specs", "T"), actor, Some(&client), None)
2360            .unwrap();
2361        let first = engine
2362            .relate_entity(
2363                RelateEntityArgs {
2364                    source: source.id.clone(),
2365                    expected_hash: Some(source.content_hash.clone()),
2366                    rel_type: "USES".to_string(),
2367                    target: target.id.clone(),
2368                    remove: false,
2369                    description: None,
2370                    dry_run: false,
2371                },
2372                actor,
2373                Some(&client),
2374                None,
2375            )
2376            .unwrap();
2377        let pre = engine.get_entity(&source.id).unwrap();
2378        let pre_stamp = pre
2379            .metadata
2380            .get("last_modified")
2381            .map(|v| v.to_frontmatter_string())
2382            .unwrap_or_default();
2383
2384        // Second relate of same edge — NoOpAlreadyPresent.
2385        let dup = engine
2386            .relate_entity(
2387                RelateEntityArgs {
2388                    source: source.id.clone(),
2389                    expected_hash: Some(first.content_hash.clone()),
2390                    rel_type: "USES".to_string(),
2391                    target: target.id.clone(),
2392                    remove: false,
2393                    description: None,
2394                    dry_run: false,
2395                },
2396                actor,
2397                Some(&client),
2398                None,
2399            )
2400            .unwrap();
2401        assert_eq!(dup.action, RelateAction::NoOpAlreadyPresent);
2402
2403        let post = engine.get_entity(&source.id).unwrap();
2404        let post_stamp = post
2405            .metadata
2406            .get("last_modified")
2407            .map(|v| v.to_frontmatter_string())
2408            .unwrap_or_default();
2409        assert_eq!(
2410            pre_stamp, post_stamp,
2411            "last_modified must not advance on a duplicate-add no-op (no disk write happened)"
2412        );
2413    }
2414
2415    /// Cross-mem relate that policy admits
2416    /// but whose target mem is not mounted in the workspace emits
2417    /// `CROSS_MEM_TARGET_MEM_UNCREATED` alongside `AutoStubCreated`.
2418    /// The auto-stub still lands; the warning is layered observability.
2419    #[test]
2420    fn cross_mem_relate_to_uncreated_mem_emits_typed_warning() {
2421        use memstead_schema::workspace_config::CrossLinkValue;
2422        let tmp = TempDir::new().unwrap();
2423        let (mut engine, source) = engine_with_seed(&tmp, "S");
2424        let (actor, client) = cli_actor();
2425        // Grant `specs -> uncreated-mem` so the policy gate passes.
2426        // The target mem is intentionally not mounted; the auto-stub
2427        // should still land, with the typed warning attached.
2428        let mut settings = crate::workspace::WorkspaceSettings::default();
2429        settings.cross_mem_links.insert(
2430            "specs".to_string(),
2431            CrossLinkValue::List(vec!["uncreated-mem".to_string()]),
2432        );
2433        engine.set_settings(settings);
2434
2435        let absent = crate::EntityId::new("uncreated-mem", "ghost");
2436        let outcome = engine
2437            .relate_entity(
2438                RelateEntityArgs {
2439                    source: source.id.clone(),
2440                    expected_hash: Some(source.content_hash.clone()),
2441                    rel_type: "USES".to_string(),
2442                    target: absent.clone(),
2443                    remove: false,
2444                    description: None,
2445                    dry_run: false,
2446                },
2447                actor,
2448                Some(&client),
2449                None,
2450            )
2451            .unwrap();
2452        assert_eq!(outcome.action, RelateAction::Added);
2453
2454        // Auto-stub created plus uncreated-mem warning, side by side.
2455        let saw_uncreated = outcome.warnings.iter().any(|w| {
2456            matches!(
2457                w,
2458                WarningHint::CrossMemTargetMemUncreated {
2459                    from_mem,
2460                    to_mem,
2461                    target_id,
2462                } if from_mem == "specs"
2463                    && to_mem == "uncreated-mem"
2464                    && target_id == &absent
2465            )
2466        });
2467        assert!(
2468            saw_uncreated,
2469            "CrossMemTargetMemUncreated warning must surface; got: {:?}",
2470            outcome.warnings
2471        );
2472        // The auto-stub still landed.
2473        assert!(engine.store().contains(&absent));
2474    }
2475
2476    /// Policy refusal takes precedence
2477    /// over the uncreated-mem warning. When the cross-mem link
2478    /// isn't granted, the engine refuses with
2479    /// `CROSS_MEM_LINK_NOT_ALLOWED` and never reaches the warning
2480    /// emission point — there's no stub to warn about.
2481    #[test]
2482    fn cross_mem_relate_policy_refusal_preempts_uncreated_mem_warning() {
2483        let tmp = TempDir::new().unwrap();
2484        let (mut engine, source) = engine_with_seed(&tmp, "S");
2485        let (actor, client) = cli_actor();
2486        // No cross_mem_links entry → policy denies.
2487        let absent = crate::EntityId::new("uncreated-mem", "ghost");
2488        let err = engine
2489            .relate_entity(
2490                RelateEntityArgs {
2491                    source: source.id.clone(),
2492                    expected_hash: Some(source.content_hash.clone()),
2493                    rel_type: "USES".to_string(),
2494                    target: absent.clone(),
2495                    remove: false,
2496                    description: None,
2497                    dry_run: false,
2498                },
2499                actor,
2500                Some(&client),
2501                None,
2502            )
2503            .unwrap_err();
2504        assert!(matches!(err, EngineError::CrossMemLinkNotAllowed { .. }));
2505        // No stub created on the refusal path.
2506        assert!(!engine.store().contains(&absent));
2507    }
2508
2509    /// `memstead_relate --remove` that drops the
2510    /// last incoming edge to a stub GCs the now-orphan stub in the
2511    /// same call. The response carries the dropped ids in
2512    /// `orphan_stubs_removed`, mirroring the `memstead_delete` envelope's
2513    /// shape so consumers branch uniformly.
2514    #[test]
2515    fn relate_remove_garbage_collects_orphan_stub() {
2516        let tmp = TempDir::new().unwrap();
2517        let (mut engine, source) = engine_with_seed(&tmp, "Src");
2518        let (actor, client) = cli_actor();
2519        let stub_id = crate::EntityId::new("specs", "ghost-target");
2520
2521        // Auto-stub via relate-add.
2522        let added = engine
2523            .relate_entity(
2524                RelateEntityArgs {
2525                    source: source.id.clone(),
2526                    expected_hash: Some(source.content_hash.clone()),
2527                    rel_type: "USES".to_string(),
2528                    target: stub_id.clone(),
2529                    remove: false,
2530                    description: None,
2531                    dry_run: false,
2532                },
2533                actor,
2534                Some(&client),
2535                None,
2536            )
2537            .unwrap();
2538        assert!(engine.store().contains(&stub_id));
2539
2540        let removed = engine
2541            .relate_entity(
2542                RelateEntityArgs {
2543                    source: source.id.clone(),
2544                    expected_hash: Some(added.content_hash.clone()),
2545                    rel_type: "USES".to_string(),
2546                    target: stub_id.clone(),
2547                    remove: true,
2548                    description: None,
2549                    dry_run: false,
2550                },
2551                actor,
2552                Some(&client),
2553                None,
2554            )
2555            .unwrap();
2556        assert_eq!(removed.action, RelateAction::Removed);
2557        assert_eq!(
2558            removed.orphan_stubs_removed,
2559            vec![stub_id.clone()],
2560            "orphan stub must be GC'd in the same call"
2561        );
2562        assert!(
2563            !engine.store().contains(&stub_id),
2564            "stub must be gone from the store after GC"
2565        );
2566    }
2567
2568    /// When the stub has another
2569    /// surviving incoming edge, the relate-remove GCs nothing —
2570    /// the stub stays alive via the second referrer. The sweep is
2571    /// scoped to *just-orphaned* targets, not pre-existing orphans
2572    /// or stubs that still have referrers.
2573    #[test]
2574    fn relate_remove_does_not_gc_stub_with_surviving_incoming_edge() {
2575        let tmp = TempDir::new().unwrap();
2576        let (mut engine, source_a) = engine_with_seed(&tmp, "SrcA");
2577        let (actor, client) = cli_actor();
2578        let source_b = engine
2579            .create_entity(
2580                empty_create_args("specs", "SrcB"),
2581                actor,
2582                Some(&client),
2583                None,
2584            )
2585            .unwrap();
2586        let stub_id = crate::EntityId::new("specs", "ghost-target");
2587
2588        // Both sources relate to the same stub.
2589        let a_added = engine
2590            .relate_entity(
2591                RelateEntityArgs {
2592                    source: source_a.id.clone(),
2593                    expected_hash: Some(source_a.content_hash.clone()),
2594                    rel_type: "USES".to_string(),
2595                    target: stub_id.clone(),
2596                    remove: false,
2597                    description: None,
2598                    dry_run: false,
2599                },
2600                actor,
2601                Some(&client),
2602                None,
2603            )
2604            .unwrap();
2605        let _b_added = engine
2606            .relate_entity(
2607                RelateEntityArgs {
2608                    source: source_b.id.clone(),
2609                    expected_hash: Some(source_b.content_hash.clone()),
2610                    rel_type: "USES".to_string(),
2611                    target: stub_id.clone(),
2612                    remove: false,
2613                    description: None,
2614                    dry_run: false,
2615                },
2616                actor,
2617                Some(&client),
2618                None,
2619            )
2620            .unwrap();
2621
2622        // Drop source_a's edge only — source_b's edge survives,
2623        // so the stub is not orphaned.
2624        let removed = engine
2625            .relate_entity(
2626                RelateEntityArgs {
2627                    source: source_a.id.clone(),
2628                    expected_hash: Some(a_added.content_hash.clone()),
2629                    rel_type: "USES".to_string(),
2630                    target: stub_id.clone(),
2631                    remove: true,
2632                    description: None,
2633                    dry_run: false,
2634                },
2635                actor,
2636                Some(&client),
2637                None,
2638            )
2639            .unwrap();
2640        assert_eq!(removed.action, RelateAction::Removed);
2641        assert!(
2642            removed.orphan_stubs_removed.is_empty(),
2643            "stub with surviving referrer must not be GC'd; got: {:?}",
2644            removed.orphan_stubs_removed
2645        );
2646        assert!(
2647            engine.store().contains(&stub_id),
2648            "stub must remain in store while another referrer holds it"
2649        );
2650    }
2651
2652    // ---- Cross-mem vocabulary -------------------------------------
2653
2654    /// Two-mem test bench wired for cross-mem routing.
2655    /// Mem `src` pins `src-cv@0.1.0` whose `cross_mem_relationships`
2656    /// section declares an outbound entry to the `tgt-cv` domain with
2657    /// `ADDRESSES: doc → req`. Mem `tgt` pins `tgt-cv@0.1.0`, a
2658    /// schema with a different name. The workspace policy admits the
2659    /// cross-mem link so vocabulary failures surface independently
2660    /// of permission.
2661    mod cross_mem {
2662        use std::collections::BTreeMap;
2663        use std::path::Path;
2664
2665        use indexmap::IndexMap;
2666        use memstead_schema::SchemaRef;
2667        use memstead_schema::workspace_config::CrossLinkValue;
2668        use tempfile::TempDir;
2669
2670        use crate::backend::MemBackend;
2671        use crate::engine::test_helpers::*;
2672        use crate::engine::{
2673            CreateEntityArgs, CreateEntityOutcome, Engine, EngineError, RelateAction,
2674            RelateEntityArgs,
2675        };
2676        use crate::storage::FilesystemMemWriter;
2677
2678        use crate::workspace::{
2679            Mount, MountCapability, MountLifecycle, MountStorage, WorkspaceSettings,
2680        };
2681
2682        fn write_schema_files(root: &Path, name: &str, manifest: &str, types: &[(&str, &str)]) {
2683            let dir = root.join(name);
2684            std::fs::create_dir_all(dir.join("types")).unwrap();
2685            std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
2686            for (type_name, body) in types {
2687                std::fs::write(dir.join("types").join(format!("{type_name}.yaml")), body).unwrap();
2688            }
2689        }
2690
2691        const TYPE_BODY: &str = r#"description: t
2692when_to_use: Here
2693sections:
2694  - key: body
2695    heading: Body
2696    required: true
2697    search_weight: 10.0
2698    catch_all: true
2699    write_rules: []
2700metadata_fields: []
2701title_weight: 100.0
2702text_fields:
2703  - body
2704hierarchy_relationship: _default
2705no_self_loop_relationships: []
2706updatable_fields:
2707  - title
2708  - body
2709health_required_fields:
2710  - body
2711staleness_threshold_days: 90
2712write_rules: []
2713"#;
2714
2715        fn make_type_yaml(name: &str) -> String {
2716            format!("name: {name}\n{TYPE_BODY}")
2717        }
2718
2719        fn folder_mount_with_pin(mem: &str, path: std::path::PathBuf, pin: SchemaRef) -> Mount {
2720            Mount {
2721                mem: mem.to_string(),
2722                schema: Some(pin),
2723                storage: MountStorage::Folder { path },
2724                capability: MountCapability::Write,
2725                lifecycle: MountLifecycle::Eager,
2726                cross_linkable: true,
2727                migration_target: None,
2728            }
2729        }
2730
2731        /// Build an engine with two mems pinning two distinct schemas
2732        /// and a `cross_mem_links` policy admitting the cross-edge.
2733        fn two_mem_engine() -> (TempDir, Engine, CreateEntityOutcome, CreateEntityOutcome) {
2734            let tmp = TempDir::new().unwrap();
2735
2736            // Source schema with cross-mem declarations to the
2737            // tgt-cv domain.
2738            let src_manifest = r#"name: src-cv
2739version: 0.1.0
2740description: source schema
2741when_to_use: tests
2742types:
2743  - doc
2744relationships:
2745  mode: strict
2746  definitions:
2747    - name: IMPLEMENTS
2748      description: intra-mem only
2749      default_weight: 1.0
2750    - name: _default
2751      description: fallback
2752      default_weight: 1.0
2753cross_mem_relationships:
2754  - to_schema: tgt-cv
2755    definitions:
2756      - name: ADDRESSES
2757        description: outbound shape-pinned
2758        default_weight: 1.0
2759        source_types: [doc]
2760        target_types: [req]
2761community:
2762  resolution: 1.0
2763  seed: 42
2764"#;
2765            // Target schema declares no cross_mem_relationships (we
2766            // never relate from tgt → src in these tests).
2767            let tgt_manifest = r#"name: tgt-cv
2768version: 0.1.0
2769description: target schema
2770when_to_use: tests
2771types:
2772  - req
2773relationships:
2774  mode: strict
2775  definitions:
2776    - name: PART_OF
2777      description: hierarchy
2778      default_weight: 3.0
2779      acyclic: true
2780    - name: _default
2781      description: fallback
2782      default_weight: 1.0
2783community:
2784  resolution: 1.0
2785  seed: 42
2786"#;
2787            let schemas_dir = tmp.path().join("schemas");
2788            std::fs::create_dir_all(&schemas_dir).unwrap();
2789            write_schema_files(
2790                &schemas_dir,
2791                "src-cv",
2792                src_manifest,
2793                &[("doc", &make_type_yaml("doc"))],
2794            );
2795            write_schema_files(
2796                &schemas_dir,
2797                "tgt-cv",
2798                tgt_manifest,
2799                &[("req", &make_type_yaml("req"))],
2800            );
2801
2802            let src_dir = tmp.path().join("mem-src");
2803            let tgt_dir = tmp.path().join("mem-tgt");
2804            std::fs::create_dir_all(&src_dir).unwrap();
2805            std::fs::create_dir_all(&tgt_dir).unwrap();
2806
2807            let src_writer = FilesystemMemWriter::new(src_dir.clone());
2808            let tgt_writer = FilesystemMemWriter::new(tgt_dir.clone());
2809            let src_pin = SchemaRef::new("src-cv", semver::Version::new(0, 1, 0));
2810            let tgt_pin = SchemaRef::new("tgt-cv", semver::Version::new(0, 1, 0));
2811
2812            let mut engine = Engine::from_mounts_with_schemas_dir(
2813                vec![
2814                    (
2815                        folder_mount_with_pin("src", src_dir, src_pin),
2816                        Box::new(src_writer) as Box<dyn MemBackend>,
2817                    ),
2818                    (
2819                        folder_mount_with_pin("tgt", tgt_dir, tgt_pin),
2820                        Box::new(tgt_writer) as Box<dyn MemBackend>,
2821                    ),
2822                ],
2823                Some(&schemas_dir),
2824            )
2825            .expect("two-mem engine constructs");
2826
2827            // Wildcard permission so cross-mem edges aren't blocked
2828            // by the orthogonal policy gate (we exercise the vocabulary
2829            // gate here, not the permission gate).
2830            let mut settings = WorkspaceSettings::default();
2831            let mut links: BTreeMap<String, CrossLinkValue> = BTreeMap::new();
2832            links.insert("src".to_string(), CrossLinkValue::Wildcard);
2833            settings.cross_mem_links = links;
2834            engine.set_settings(settings);
2835
2836            let (actor, client) = cli_actor();
2837            let src_entity = engine
2838                .create_entity(
2839                    CreateEntityArgs {
2840                        anchors: Vec::new(),
2841                        mem: "src".to_string(),
2842                        title: "Doc One".to_string(),
2843                        entity_type: "doc".to_string(),
2844                        sections: IndexMap::from_iter([("body".to_string(), "seed".to_string())]),
2845                        metadata: IndexMap::new(),
2846                        relations: Vec::new(),
2847                        dry_run: false,
2848                    },
2849                    actor,
2850                    Some(&client),
2851                    None,
2852                )
2853                .expect("source entity creates");
2854            let tgt_entity = engine
2855                .create_entity(
2856                    CreateEntityArgs {
2857                        anchors: Vec::new(),
2858                        mem: "tgt".to_string(),
2859                        title: "Req One".to_string(),
2860                        entity_type: "req".to_string(),
2861                        sections: IndexMap::from_iter([("body".to_string(), "seed".to_string())]),
2862                        metadata: IndexMap::new(),
2863                        relations: Vec::new(),
2864                        dry_run: false,
2865                    },
2866                    actor,
2867                    Some(&client),
2868                    None,
2869                )
2870                .expect("target entity creates");
2871
2872            (tmp, engine, src_entity, tgt_entity)
2873        }
2874
2875        #[test]
2876        fn cross_different_schema_admits_declared_edge() {
2877            let (_tmp, mut engine, src, tgt) = two_mem_engine();
2878            let (actor, client) = cli_actor();
2879            let outcome = engine
2880                .relate_entity(
2881                    RelateEntityArgs {
2882                        source: src.id.clone(),
2883                        expected_hash: Some(src.content_hash.clone()),
2884                        rel_type: "ADDRESSES".to_string(),
2885                        target: tgt.id.clone(),
2886                        remove: false,
2887                        description: None,
2888                        dry_run: false,
2889                    },
2890                    actor,
2891                    Some(&client),
2892                    None,
2893                )
2894                .expect("declared cross-mem edge admits");
2895            assert_eq!(outcome.rel_type, "ADDRESSES");
2896        }
2897
2898        /// Same schema name at different versions is the same domain:
2899        /// edges between two `same-dom`-pinned mems route through
2900        /// the intra-schema relationship vocabulary (governed by the
2901        /// source mem's pinned version) with no
2902        /// `cross_mem_relationships` declaration at all.
2903        #[test]
2904        fn same_name_different_version_uses_intra_mem_vocabulary() {
2905            let tmp = TempDir::new().unwrap();
2906
2907            let manifest_for = |version: &str| {
2908                format!(
2909                    r#"name: same-dom
2910version: {version}
2911description: same-domain schema
2912when_to_use: tests
2913types:
2914  - doc
2915relationships:
2916  mode: strict
2917  definitions:
2918    - name: IMPLEMENTS
2919      description: intra-mem vocabulary
2920      default_weight: 1.0
2921    - name: _default
2922      description: fallback
2923      default_weight: 1.0
2924community:
2925  resolution: 1.0
2926  seed: 42
2927"#
2928                )
2929            };
2930            let schemas_dir = tmp.path().join("schemas");
2931            std::fs::create_dir_all(&schemas_dir).unwrap();
2932            // Subdir names carry the version so both iterations of the
2933            // `same-dom` domain coexist in one schemas dir.
2934            write_schema_files(
2935                &schemas_dir,
2936                "same-dom-0.1.0",
2937                &manifest_for("0.1.0"),
2938                &[("doc", &make_type_yaml("doc"))],
2939            );
2940            write_schema_files(
2941                &schemas_dir,
2942                "same-dom-0.2.0",
2943                &manifest_for("0.2.0"),
2944                &[("doc", &make_type_yaml("doc"))],
2945            );
2946
2947            let src_dir = tmp.path().join("mem-src");
2948            let tgt_dir = tmp.path().join("mem-tgt");
2949            std::fs::create_dir_all(&src_dir).unwrap();
2950            std::fs::create_dir_all(&tgt_dir).unwrap();
2951            let src_pin = SchemaRef::new("same-dom", semver::Version::new(0, 1, 0));
2952            let tgt_pin = SchemaRef::new("same-dom", semver::Version::new(0, 2, 0));
2953            let mut engine = Engine::from_mounts_with_schemas_dir(
2954                vec![
2955                    (
2956                        folder_mount_with_pin("src", src_dir.clone(), src_pin),
2957                        Box::new(FilesystemMemWriter::new(src_dir)) as Box<dyn MemBackend>,
2958                    ),
2959                    (
2960                        folder_mount_with_pin("tgt", tgt_dir.clone(), tgt_pin),
2961                        Box::new(FilesystemMemWriter::new(tgt_dir)) as Box<dyn MemBackend>,
2962                    ),
2963                ],
2964                Some(&schemas_dir),
2965            )
2966            .expect("same-domain two-version engine constructs");
2967
2968            let mut settings = WorkspaceSettings::default();
2969            let mut links: BTreeMap<String, CrossLinkValue> = BTreeMap::new();
2970            links.insert("src".to_string(), CrossLinkValue::Wildcard);
2971            settings.cross_mem_links = links;
2972            engine.set_settings(settings);
2973
2974            let (actor, client) = cli_actor();
2975            let mk_entity = |engine: &mut Engine, mem: &str, title: &str| {
2976                engine
2977                    .create_entity(
2978                        CreateEntityArgs {
2979                            anchors: Vec::new(),
2980                            mem: mem.to_string(),
2981                            title: title.to_string(),
2982                            entity_type: "doc".to_string(),
2983                            sections: IndexMap::from_iter([(
2984                                "body".to_string(),
2985                                "seed".to_string(),
2986                            )]),
2987                            metadata: IndexMap::new(),
2988                            relations: Vec::new(),
2989                            dry_run: false,
2990                        },
2991                        actor,
2992                        Some(&client),
2993                        None,
2994                    )
2995                    .expect("entity creates")
2996            };
2997            let src_entity = mk_entity(&mut engine, "src", "Doc A");
2998            let tgt_entity = mk_entity(&mut engine, "tgt", "Doc B");
2999
3000            let outcome = engine
3001                .relate_entity(
3002                    RelateEntityArgs {
3003                        source: src_entity.id.clone(),
3004                        expected_hash: Some(src_entity.content_hash.clone()),
3005                        rel_type: "IMPLEMENTS".to_string(),
3006                        target: tgt_entity.id.clone(),
3007                        remove: false,
3008                        description: None,
3009                        dry_run: false,
3010                    },
3011                    actor,
3012                    Some(&client),
3013                    None,
3014                )
3015                .expect("same-domain edge uses the intra-schema vocabulary across versions");
3016            assert_eq!(outcome.rel_type, "IMPLEMENTS");
3017        }
3018
3019        #[test]
3020        fn cross_different_schema_unknown_rel_type_returns_invalid_rel_type() {
3021            // `IMPLEMENTS` exists intra-mem but not in the cross-mem
3022            // entry — must refuse with INVALID_REL_TYPE against the
3023            // cross-mem entry's vocabulary (not intra-mem's).
3024            let (_tmp, mut engine, src, tgt) = two_mem_engine();
3025            let (actor, client) = cli_actor();
3026            let err = engine
3027                .relate_entity(
3028                    RelateEntityArgs {
3029                        source: src.id.clone(),
3030                        expected_hash: Some(src.content_hash.clone()),
3031                        rel_type: "IMPLEMENTS".to_string(),
3032                        target: tgt.id.clone(),
3033                        remove: false,
3034                        description: None,
3035                        dry_run: false,
3036                    },
3037                    actor,
3038                    Some(&client),
3039                    None,
3040                )
3041                .unwrap_err();
3042            match err {
3043                EngineError::Validation(
3044                    crate::runtime_validator::ValidationError::InvalidRelationshipType {
3045                        input,
3046                        allowed,
3047                        ..
3048                    },
3049                ) => {
3050                    assert_eq!(input, "IMPLEMENTS");
3051                    let names: Vec<String> = allowed.into_iter().map(|h| h.name).collect();
3052                    assert!(names.iter().any(|n| n == "ADDRESSES"));
3053                    assert!(!names.iter().any(|n| n == "IMPLEMENTS"));
3054                }
3055                other => panic!("expected Validation(InvalidRelationshipType), got {other:?}"),
3056            }
3057        }
3058
3059        #[test]
3060        fn cross_different_schema_shape_violation_returns_invalid_rel_shape() {
3061            // ADDRESSES is shape-pinned to source=doc, target=req in
3062            // the cross-mem entry. Need a source whose type isn't doc.
3063            // src-cv only declares `doc`, so to provoke a shape miss we
3064            // build a third schema with type `note` and a fresh mem —
3065            // but that requires more plumbing than this test needs.
3066            // Instead: exercise a target-side shape miss by relating
3067            // ADDRESSES to a target that doesn't exist at all — the
3068            // target_type lookup returns None and the target check is
3069            // skipped (admits). So we exercise this via cross_mem
3070            // unit tests instead.
3071            //
3072            // What this integration test confirms: the source-side
3073            // shape check fires when the source type doesn't match —
3074            // here we'd need a non-`doc` source. Since src-cv only has
3075            // `doc`, the source-side admits trivially. Covered fully
3076            // by the runtime_validator unit tests.
3077        }
3078
3079        #[test]
3080        fn cross_different_schema_no_matching_entry_returns_edge_not_declared() {
3081            // Build a third mem pinning a schema not declared in
3082            // src-cv's cross_mem_relationships, then relate from src.
3083            let tmp = TempDir::new().unwrap();
3084            let src_manifest = r#"name: src-cv
3085version: 0.1.0
3086description: source schema
3087when_to_use: tests
3088types:
3089  - doc
3090relationships:
3091  mode: strict
3092  definitions:
3093    - name: IMPLEMENTS
3094      description: intra-mem
3095      default_weight: 1.0
3096    - name: _default
3097      description: fallback
3098      default_weight: 1.0
3099cross_mem_relationships:
3100  - to_schema: tgt-cv
3101    definitions:
3102      - name: ADDRESSES
3103        description: outbound
3104        default_weight: 1.0
3105        source_types: [doc]
3106        target_types: [req]
3107community:
3108  resolution: 1.0
3109  seed: 42
3110"#;
3111            // Different target schema NOT named in src's cross-mem list.
3112            let other_manifest = r#"name: other-cv
3113version: 0.1.0
3114description: foreign schema
3115when_to_use: tests
3116types:
3117  - thing
3118relationships:
3119  mode: strict
3120  definitions:
3121    - name: _default
3122      description: fallback
3123      default_weight: 1.0
3124community:
3125  resolution: 1.0
3126  seed: 42
3127"#;
3128            let schemas_dir = tmp.path().join("schemas");
3129            std::fs::create_dir_all(&schemas_dir).unwrap();
3130            write_schema_files(
3131                &schemas_dir,
3132                "src-cv",
3133                src_manifest,
3134                &[("doc", &make_type_yaml("doc"))],
3135            );
3136            write_schema_files(
3137                &schemas_dir,
3138                "other-cv",
3139                other_manifest,
3140                &[("thing", &make_type_yaml("thing"))],
3141            );
3142            let src_dir = tmp.path().join("mem-src");
3143            let other_dir = tmp.path().join("mem-other");
3144            std::fs::create_dir_all(&src_dir).unwrap();
3145            std::fs::create_dir_all(&other_dir).unwrap();
3146
3147            let mut engine = Engine::from_mounts_with_schemas_dir(
3148                vec![
3149                    (
3150                        folder_mount_with_pin(
3151                            "src",
3152                            src_dir.clone(),
3153                            SchemaRef::new("src-cv", semver::Version::new(0, 1, 0)),
3154                        ),
3155                        Box::new(FilesystemMemWriter::new(src_dir)) as Box<dyn MemBackend>,
3156                    ),
3157                    (
3158                        folder_mount_with_pin(
3159                            "other",
3160                            other_dir.clone(),
3161                            SchemaRef::new("other-cv", semver::Version::new(0, 1, 0)),
3162                        ),
3163                        Box::new(FilesystemMemWriter::new(other_dir)) as Box<dyn MemBackend>,
3164                    ),
3165                ],
3166                Some(&schemas_dir),
3167            )
3168            .expect("engine constructs");
3169
3170            let mut settings = WorkspaceSettings::default();
3171            let mut links: BTreeMap<String, CrossLinkValue> = BTreeMap::new();
3172            links.insert("src".to_string(), CrossLinkValue::Wildcard);
3173            settings.cross_mem_links = links;
3174            engine.set_settings(settings);
3175
3176            let (actor, client) = cli_actor();
3177            let src_entity = engine
3178                .create_entity(
3179                    CreateEntityArgs {
3180                        anchors: Vec::new(),
3181                        mem: "src".to_string(),
3182                        title: "D".to_string(),
3183                        entity_type: "doc".to_string(),
3184                        sections: IndexMap::from_iter([("body".to_string(), "x".to_string())]),
3185                        metadata: IndexMap::new(),
3186                        relations: Vec::new(),
3187                        dry_run: false,
3188                    },
3189                    actor,
3190                    Some(&client),
3191                    None,
3192                )
3193                .unwrap();
3194            let other_entity = engine
3195                .create_entity(
3196                    CreateEntityArgs {
3197                        anchors: Vec::new(),
3198                        mem: "other".to_string(),
3199                        title: "T".to_string(),
3200                        entity_type: "thing".to_string(),
3201                        sections: IndexMap::from_iter([("body".to_string(), "x".to_string())]),
3202                        metadata: IndexMap::new(),
3203                        relations: Vec::new(),
3204                        dry_run: false,
3205                    },
3206                    actor,
3207                    Some(&client),
3208                    None,
3209                )
3210                .unwrap();
3211
3212            let err = engine
3213                .relate_entity(
3214                    RelateEntityArgs {
3215                        source: src_entity.id.clone(),
3216                        expected_hash: Some(src_entity.content_hash.clone()),
3217                        rel_type: "ADDRESSES".to_string(),
3218                        target: other_entity.id.clone(),
3219                        remove: false,
3220                        description: None,
3221                        dry_run: false,
3222                    },
3223                    actor,
3224                    Some(&client),
3225                    None,
3226                )
3227                .unwrap_err();
3228            match err {
3229                EngineError::CrossMemEdgeNotDeclared {
3230                    source_schema,
3231                    target_schema,
3232                    rel_type,
3233                    from_id,
3234                    to_id,
3235                } => {
3236                    assert_eq!(source_schema, "src-cv@0.1.0");
3237                    assert_eq!(target_schema, "other-cv@0.1.0");
3238                    assert_eq!(rel_type, "ADDRESSES");
3239                    assert_eq!(from_id, src_entity.id.to_string());
3240                    assert_eq!(to_id, other_entity.id.to_string());
3241                }
3242                other => panic!("expected CrossMemEdgeNotDeclared, got {other:?}"),
3243            }
3244        }
3245
3246        #[test]
3247        fn intra_mem_with_cross_mem_only_rel_type_returns_invalid_rel_type() {
3248            // `ADDRESSES` is declared in src-cv's cross_mem_relationships
3249            // only — intra-mem relate must refuse with
3250            // INVALID_REL_TYPE since the intra-mem vocabulary
3251            // (`IMPLEMENTS` / `_default`) doesn't know it.
3252            let (_tmp, mut engine, src, _tgt) = two_mem_engine();
3253            let (actor, client) = cli_actor();
3254            // Create a same-mem target.
3255            let intra_target = engine
3256                .create_entity(
3257                    CreateEntityArgs {
3258                        anchors: Vec::new(),
3259                        mem: "src".to_string(),
3260                        title: "Doc Two".to_string(),
3261                        entity_type: "doc".to_string(),
3262                        sections: IndexMap::from_iter([("body".to_string(), "x".to_string())]),
3263                        metadata: IndexMap::new(),
3264                        relations: Vec::new(),
3265                        dry_run: false,
3266                    },
3267                    actor,
3268                    Some(&client),
3269                    None,
3270                )
3271                .unwrap();
3272            // Source's content_hash may have rotated due to incoming
3273            // edges from intra_target — fetch fresh.
3274            let src_fresh = engine.get_entity(&src.id).unwrap();
3275            let err = engine
3276                .relate_entity(
3277                    RelateEntityArgs {
3278                        source: src.id.clone(),
3279                        expected_hash: Some(src_fresh.content_hash.clone()),
3280                        rel_type: "ADDRESSES".to_string(),
3281                        target: intra_target.id.clone(),
3282                        remove: false,
3283                        description: None,
3284                        dry_run: false,
3285                    },
3286                    actor,
3287                    Some(&client),
3288                    None,
3289                )
3290                .unwrap_err();
3291            match err {
3292                EngineError::Validation(
3293                    crate::runtime_validator::ValidationError::InvalidRelationshipType {
3294                        input,
3295                        ..
3296                    },
3297                ) => {
3298                    assert_eq!(input, "ADDRESSES");
3299                }
3300                other => panic!("expected Validation(InvalidRelationshipType), got {other:?}"),
3301            }
3302        }
3303
3304        #[test]
3305        fn vocabulary_admissible_edge_blocked_by_policy_returns_cross_mem_link_not_allowed() {
3306            // Same fixture but flip the cross-mem policy to deny.
3307            // ADDRESSES is vocabulary-admissible but permission refuses
3308            // it independently — surfaces CROSS_MEM_LINK_NOT_ALLOWED.
3309            let (_tmp, mut engine, src, tgt) = two_mem_engine();
3310            // Replace the wildcard policy with default-deny.
3311            engine.set_settings(WorkspaceSettings::default());
3312            let (actor, client) = cli_actor();
3313            let err = engine
3314                .relate_entity(
3315                    RelateEntityArgs {
3316                        source: src.id.clone(),
3317                        expected_hash: Some(src.content_hash.clone()),
3318                        rel_type: "ADDRESSES".to_string(),
3319                        target: tgt.id.clone(),
3320                        remove: false,
3321                        description: None,
3322                        dry_run: false,
3323                    },
3324                    actor,
3325                    Some(&client),
3326                    None,
3327                )
3328                .unwrap_err();
3329            assert!(
3330                matches!(err, EngineError::CrossMemLinkNotAllowed { .. }),
3331                "expected CrossMemLinkNotAllowed, got {err:?}"
3332            );
3333        }
3334
3335        /// Cross-mem remove bypasses the `cross_mem_links` policy
3336        /// gate. Without this, a workspace whose grant was revoked
3337        /// while edges still existed gets wedged: the natural recovery
3338        /// (`memstead_relate ... --remove`) refuses, leaving the operator
3339        /// to re-grant just to delete the data that the grant once
3340        /// permitted.
3341        #[test]
3342        fn cross_mem_remove_bypasses_policy_after_revoke() {
3343            let (_tmp, mut engine, src, tgt) = two_mem_engine();
3344            let (actor, client) = cli_actor();
3345
3346            // 1. Edge admits under wildcard grant.
3347            let added = engine
3348                .relate_entity(
3349                    RelateEntityArgs {
3350                        source: src.id.clone(),
3351                        expected_hash: Some(src.content_hash.clone()),
3352                        rel_type: "ADDRESSES".to_string(),
3353                        target: tgt.id.clone(),
3354                        remove: false,
3355                        description: None,
3356                        dry_run: false,
3357                    },
3358                    actor,
3359                    Some(&client),
3360                    None,
3361                )
3362                .expect("declared cross-mem edge admits under grant");
3363            assert_eq!(added.action, RelateAction::Added);
3364
3365            // 2. Revoke the grant — default settings deny everything.
3366            engine.set_settings(WorkspaceSettings::default());
3367
3368            // 3. Re-attempting an *add* still refuses (constraint:
3369            //    the gate is unchanged for the add path).
3370            let add_err = engine
3371                .relate_entity(
3372                    RelateEntityArgs {
3373                        source: src.id.clone(),
3374                        expected_hash: Some(added.content_hash.clone()),
3375                        rel_type: "ADDRESSES".to_string(),
3376                        target: tgt.id.clone(),
3377                        remove: false,
3378                        description: None,
3379                        dry_run: false,
3380                    },
3381                    actor,
3382                    Some(&client),
3383                    None,
3384                )
3385                .unwrap_err();
3386            assert!(
3387                matches!(add_err, EngineError::CrossMemLinkNotAllowed { .. }),
3388                "add path must still refuse under denial, got {add_err:?}"
3389            );
3390
3391            // 4. Remove succeeds — the cleanup path bypasses the
3392            //    policy gate.
3393            let removed = engine
3394                .relate_entity(
3395                    RelateEntityArgs {
3396                        source: src.id.clone(),
3397                        expected_hash: Some(added.content_hash.clone()),
3398                        rel_type: "ADDRESSES".to_string(),
3399                        target: tgt.id.clone(),
3400                        remove: true,
3401                        description: None,
3402                        dry_run: false,
3403                    },
3404                    actor,
3405                    Some(&client),
3406                    None,
3407                )
3408                .expect("remove must bypass the policy gate post-revoke");
3409            assert_eq!(removed.action, RelateAction::Removed);
3410
3411            // 5. Edge is gone from the store's outgoing index.
3412            let outgoing = engine.store().outgoing(&src.id);
3413            assert!(
3414                !outgoing
3415                    .iter()
3416                    .any(|e| e.target == tgt.id && e.rel_type == "ADDRESSES"),
3417                "ADDRESSES edge must be gone after remove"
3418            );
3419        }
3420
3421        /// Remove on a non-existent cross-mem edge with no grant
3422        /// returns a no-op, not a policy refusal. The remove path is
3423        /// permissive on absence — same shape as same-mem remove.
3424        #[test]
3425        fn cross_mem_remove_of_absent_edge_under_denial_is_no_op() {
3426            let (_tmp, mut engine, src, tgt) = two_mem_engine();
3427            // Default-deny from the start: no edge ever existed.
3428            engine.set_settings(WorkspaceSettings::default());
3429            let (actor, client) = cli_actor();
3430            let outcome = engine
3431                .relate_entity(
3432                    RelateEntityArgs {
3433                        source: src.id.clone(),
3434                        expected_hash: Some(src.content_hash.clone()),
3435                        rel_type: "ADDRESSES".to_string(),
3436                        target: tgt.id.clone(),
3437                        remove: true,
3438                        description: None,
3439                        dry_run: false,
3440                    },
3441                    actor,
3442                    Some(&client),
3443                    None,
3444                )
3445                .expect("absent-edge remove must not refuse on policy");
3446            assert!(
3447                matches!(outcome.action, RelateAction::NoOpAbsent),
3448                "expected NoOpAbsent, got {:?}",
3449                outcome.action
3450            );
3451        }
3452
3453        // ---- ReadOnly-target refusal (shared add-path funnel) --------
3454
3455        /// Engine with mem `src` (Write, `alias_target_rel_type:
3456        /// REFERENCES`, cross-mem vocabulary into `tgt-al`) and mem
3457        /// `tgt` mounted with the given capability, pre-populated on
3458        /// disk with one entity `tgt--req-one`. Wildcard cross-mem
3459        /// grant for `src`. Exercises the funnel's ReadOnly-missing-
3460        /// target refusal across every add-shaped write path.
3461        fn engine_with_tgt_capability(
3462            capability: MountCapability,
3463        ) -> (TempDir, Engine, CreateEntityOutcome) {
3464            let tmp = TempDir::new().unwrap();
3465
3466            let src_manifest = r#"name: src-al
3467version: 0.1.0
3468description: source schema with alias pointer
3469when_to_use: tests
3470types:
3471  - doc
3472relationships:
3473  mode: strict
3474  definitions:
3475    - name: ADDRESSES
3476      description: explicit cross-mem
3477      default_weight: 1.0
3478    - name: REFERENCES
3479      description: alias pointer
3480      default_weight: 1.0
3481    - name: _default
3482      description: fallback
3483      default_weight: 1.0
3484cross_mem_relationships:
3485  - to_schema: tgt-al
3486    definitions:
3487      - name: ADDRESSES
3488        description: explicit cross-mem
3489        default_weight: 1.0
3490      - name: REFERENCES
3491        description: alias-emitted cross-mem
3492        default_weight: 1.0
3493alias_target_rel_type: REFERENCES
3494community:
3495  resolution: 1.0
3496  seed: 42
3497"#;
3498            let tgt_manifest = r#"name: tgt-al
3499version: 0.1.0
3500description: target schema
3501when_to_use: tests
3502types:
3503  - req
3504relationships:
3505  mode: strict
3506  definitions:
3507    - name: _default
3508      description: fallback
3509      default_weight: 1.0
3510community:
3511  resolution: 1.0
3512  seed: 42
3513"#;
3514            let schemas_dir = tmp.path().join("schemas");
3515            std::fs::create_dir_all(&schemas_dir).unwrap();
3516            write_schema_files(
3517                &schemas_dir,
3518                "src-al",
3519                src_manifest,
3520                &[("doc", &make_type_yaml("doc"))],
3521            );
3522            write_schema_files(
3523                &schemas_dir,
3524                "tgt-al",
3525                tgt_manifest,
3526                &[("req", &make_type_yaml("req"))],
3527            );
3528
3529            let src_dir = tmp.path().join("mem-src");
3530            let tgt_dir = tmp.path().join("mem-tgt");
3531            std::fs::create_dir_all(&src_dir).unwrap();
3532            std::fs::create_dir_all(&tgt_dir).unwrap();
3533            // The read-only mem is pre-populated on disk — the engine
3534            // never writes to it.
3535            std::fs::write(
3536                tgt_dir.join("req-one.md"),
3537                "---\ntype: req\n---\n# Req One\n\n## Body\n\nseed.\n",
3538            )
3539            .unwrap();
3540
3541            let src_writer = FilesystemMemWriter::new(src_dir.clone());
3542            let tgt_writer = FilesystemMemWriter::new(tgt_dir.clone());
3543            let src_pin = SchemaRef::new("src-al", semver::Version::new(0, 1, 0));
3544            let tgt_pin = SchemaRef::new("tgt-al", semver::Version::new(0, 1, 0));
3545
3546            let tgt_mount = Mount {
3547                mem: "tgt".to_string(),
3548                schema: Some(tgt_pin),
3549                storage: MountStorage::Folder {
3550                    path: tgt_dir.clone(),
3551                },
3552                capability,
3553                lifecycle: MountLifecycle::Eager,
3554                cross_linkable: true,
3555                migration_target: None,
3556            };
3557            let mut engine = Engine::from_mounts_with_schemas_dir(
3558                vec![
3559                    (
3560                        folder_mount_with_pin("src", src_dir, src_pin),
3561                        Box::new(src_writer) as Box<dyn MemBackend>,
3562                    ),
3563                    (tgt_mount, Box::new(tgt_writer) as Box<dyn MemBackend>),
3564                ],
3565                Some(&schemas_dir),
3566            )
3567            .expect("two-mem engine constructs");
3568
3569            let mut settings = WorkspaceSettings::default();
3570            let mut links: BTreeMap<String, CrossLinkValue> = BTreeMap::new();
3571            links.insert("src".to_string(), CrossLinkValue::Wildcard);
3572            settings.cross_mem_links = links;
3573            engine.set_settings(settings);
3574
3575            let (actor, client) = cli_actor();
3576            let src_entity = engine
3577                .create_entity(
3578                    CreateEntityArgs {
3579                        anchors: Vec::new(),
3580                        mem: "src".to_string(),
3581                        title: "Doc One".to_string(),
3582                        entity_type: "doc".to_string(),
3583                        sections: IndexMap::from_iter([("body".to_string(), "seed".to_string())]),
3584                        metadata: IndexMap::new(),
3585                        relations: Vec::new(),
3586                        dry_run: false,
3587                    },
3588                    actor,
3589                    Some(&client),
3590                    None,
3591                )
3592                .expect("source entity creates");
3593
3594            (tmp, engine, src_entity)
3595        }
3596
3597        fn assert_cross_mem_target_not_found(err: EngineError, expected_target: &str) {
3598            match err {
3599                EngineError::CrossMemTargetNotFound {
3600                    target_id,
3601                    target_mem,
3602                } => {
3603                    assert_eq!(target_id, expected_target);
3604                    assert_eq!(target_mem, "tgt");
3605                }
3606                other => panic!("expected CrossMemTargetNotFound, got {other:?}"),
3607            }
3608        }
3609
3610        /// Rehearsal complement: a rehearsed
3611        /// relate against a read-only boundary refuses EXACTLY as the
3612        /// real call would — same variant, same payload. Paired with
3613        /// `relate_to_missing_target_in_readonly_mem_refuses` below.
3614        #[test]
3615        fn relate_dry_run_to_missing_target_in_readonly_mem_refuses_identically() {
3616            let (_tmp, mut engine, src) = engine_with_tgt_capability(MountCapability::ReadOnly);
3617            let (actor, client) = cli_actor();
3618            let args = |dry_run: bool| RelateEntityArgs {
3619                source: src.id.clone(),
3620                expected_hash: Some(src.content_hash.clone()),
3621                rel_type: "ADDRESSES".to_string(),
3622                target: crate::EntityId::new("tgt", "missing"),
3623                remove: false,
3624                description: None,
3625                dry_run,
3626            };
3627            let rehearsed = engine
3628                .relate_entity(args(true), actor, Some(&client), None)
3629                .unwrap_err();
3630            let real = engine
3631                .relate_entity(args(false), actor, Some(&client), None)
3632                .unwrap_err();
3633            assert_eq!(format!("{rehearsed:?}"), format!("{real:?}"));
3634            assert_cross_mem_target_not_found(rehearsed, "tgt--missing");
3635        }
3636
3637        #[test]
3638        fn relate_to_missing_target_in_readonly_mem_refuses() {
3639            let (_tmp, mut engine, src) = engine_with_tgt_capability(MountCapability::ReadOnly);
3640            let (actor, client) = cli_actor();
3641            let err = engine
3642                .relate_entity(
3643                    RelateEntityArgs {
3644                        source: src.id.clone(),
3645                        expected_hash: Some(src.content_hash.clone()),
3646                        rel_type: "ADDRESSES".to_string(),
3647                        target: crate::EntityId::new("tgt", "missing"),
3648                        remove: false,
3649                        description: None,
3650                        dry_run: false,
3651                    },
3652                    actor,
3653                    Some(&client),
3654                    None,
3655                )
3656                .unwrap_err();
3657            assert_cross_mem_target_not_found(err, "tgt--missing");
3658        }
3659
3660        /// Pre-funnel, `memstead_create.relations[]` lacked the
3661        /// ReadOnly-missing-target check the relate path had — an
3662        /// inline relation to an absent read-only target auto-stubbed
3663        /// instead of refusing.
3664        #[test]
3665        fn create_inline_relation_to_missing_target_in_readonly_mem_refuses() {
3666            let (_tmp, mut engine, _src) = engine_with_tgt_capability(MountCapability::ReadOnly);
3667            let (actor, client) = cli_actor();
3668            let err = engine
3669                .create_entity(
3670                    CreateEntityArgs {
3671                        anchors: Vec::new(),
3672                        mem: "src".to_string(),
3673                        title: "Doc Two".to_string(),
3674                        entity_type: "doc".to_string(),
3675                        sections: IndexMap::from_iter([("body".to_string(), "x".to_string())]),
3676                        metadata: IndexMap::new(),
3677                        relations: vec![crate::ops::RelateArg {
3678                            target: crate::EntityId::new("tgt", "missing"),
3679                            rel_type: "ADDRESSES".to_string(),
3680                            description: None,
3681                        }],
3682                        dry_run: false,
3683                    },
3684                    actor,
3685                    Some(&client),
3686                    None,
3687                )
3688                .unwrap_err();
3689            assert_cross_mem_target_not_found(err, "tgt--missing");
3690        }
3691
3692        /// The body-wiki-link channel (alias synthesis) — pre-funnel a
3693        /// granted body link to a missing read-only target silently
3694        /// auto-stubbed at load; `memstead_health` was the only signal.
3695        #[test]
3696        fn create_body_link_to_missing_target_in_readonly_mem_refuses() {
3697            let (_tmp, mut engine, _src) = engine_with_tgt_capability(MountCapability::ReadOnly);
3698            let (actor, client) = cli_actor();
3699            let err = engine
3700                .create_entity(
3701                    CreateEntityArgs {
3702                        anchors: Vec::new(),
3703                        mem: "src".to_string(),
3704                        title: "Doc Three".to_string(),
3705                        entity_type: "doc".to_string(),
3706                        sections: IndexMap::from_iter([(
3707                            "body".to_string(),
3708                            "see [[tgt--missing]].".to_string(),
3709                        )]),
3710                        metadata: IndexMap::new(),
3711                        relations: Vec::new(),
3712                        dry_run: false,
3713                    },
3714                    actor,
3715                    Some(&client),
3716                    None,
3717                )
3718                .unwrap_err();
3719            assert_cross_mem_target_not_found(err, "tgt--missing");
3720        }
3721
3722        #[test]
3723        fn update_body_link_to_missing_target_in_readonly_mem_refuses() {
3724            let (_tmp, mut engine, src) = engine_with_tgt_capability(MountCapability::ReadOnly);
3725            let (actor, client) = cli_actor();
3726            let err = engine
3727                .update_entity(
3728                    crate::engine::UpdateEntityArgs {
3729                        anchors: Vec::new(),
3730                        id: src.id.clone(),
3731                        expected_hash: Some(src.content_hash.clone()),
3732                        sections: IndexMap::from_iter([(
3733                            "body".to_string(),
3734                            "now see [[tgt--missing]].".to_string(),
3735                        )]),
3736                        append_sections: IndexMap::new(),
3737                        patch_sections: IndexMap::new(),
3738                        sections_unset: Vec::new(),
3739                        metadata: IndexMap::new(),
3740                        metadata_unset: Vec::new(),
3741                        declare_relations: Vec::new(),
3742                        dry_run: false,
3743                        relations_unset: Vec::new(),
3744                        anchors_unset: Vec::new(),
3745                    },
3746                    actor,
3747                    Some(&client),
3748                    None,
3749                )
3750                .unwrap_err();
3751            assert_cross_mem_target_not_found(err, "tgt--missing");
3752        }
3753
3754        /// Positive control: a body link to a target that EXISTS in
3755        /// the read-only mem writes clean and materialises the typed
3756        /// alias edge — the seam's happy path.
3757        #[test]
3758        fn body_link_to_existing_target_in_readonly_mem_admits_and_emits_edge() {
3759            let (_tmp, mut engine, _src) = engine_with_tgt_capability(MountCapability::ReadOnly);
3760            let (actor, client) = cli_actor();
3761            let created = engine
3762                .create_entity(
3763                    CreateEntityArgs {
3764                        anchors: Vec::new(),
3765                        mem: "src".to_string(),
3766                        title: "Doc Four".to_string(),
3767                        entity_type: "doc".to_string(),
3768                        sections: IndexMap::from_iter([(
3769                            "body".to_string(),
3770                            "see [[tgt--req-one]].".to_string(),
3771                        )]),
3772                        metadata: IndexMap::new(),
3773                        relations: Vec::new(),
3774                        dry_run: false,
3775                    },
3776                    actor,
3777                    Some(&client),
3778                    None,
3779                )
3780                .expect("body link to existing read-only target admits");
3781            let outgoing = engine.store().outgoing(&created.id);
3782            assert!(
3783                outgoing.iter().any(|e| e.rel_type == "REFERENCES"
3784                    && e.target == crate::EntityId::new("tgt", "req-one")),
3785                "alias REFERENCES edge to the read-only target must materialise; got {outgoing:?}"
3786            );
3787        }
3788
3789        /// Behaviour preserved: a missing target in a WRITE-mounted
3790        /// sibling mem is a legitimate forward reference and keeps
3791        /// the auto-stub mechanic on every path.
3792        #[test]
3793        fn body_link_to_missing_target_in_write_mem_still_stubs() {
3794            let (_tmp, mut engine, _src) = engine_with_tgt_capability(MountCapability::Write);
3795            let (actor, client) = cli_actor();
3796            let created = engine
3797                .create_entity(
3798                    CreateEntityArgs {
3799                        anchors: Vec::new(),
3800                        mem: "src".to_string(),
3801                        title: "Doc Five".to_string(),
3802                        entity_type: "doc".to_string(),
3803                        sections: IndexMap::from_iter([(
3804                            "body".to_string(),
3805                            "see [[tgt--missing]].".to_string(),
3806                        )]),
3807                        metadata: IndexMap::new(),
3808                        relations: Vec::new(),
3809                        dry_run: false,
3810                    },
3811                    actor,
3812                    Some(&client),
3813                    None,
3814                )
3815                .expect("forward reference into a Write sibling mem keeps stubbing");
3816            assert!(
3817                engine
3818                    .store()
3819                    .contains(&crate::EntityId::new("tgt", "missing")),
3820                "auto-stub must land for the Write-mem forward reference"
3821            );
3822            let outgoing = engine.store().outgoing(&created.id);
3823            assert!(
3824                outgoing.iter().any(|e| e.rel_type == "REFERENCES"),
3825                "alias edge must still emit for the stubbed target"
3826            );
3827        }
3828    }
3829
3830    // ---- Engine::rename_entity --------------------------------------
3831
3832    /// Batch relate: one list mixing additions and removals, applied
3833    /// IN ORDER in one invocation with one commit. The remove entry
3834    /// targets an edge added earlier in the same batch — if entries
3835    /// validated against the pre-batch state instead, that remove
3836    /// would resolve to `NoOpAbsent` ("noop"), so the asserted
3837    /// `"removed"` action is the in-order proof.
3838    #[test]
3839    fn batch_relate_applies_adds_and_removes_in_order_one_commit() {
3840        let tmp = TempDir::new().unwrap();
3841        let mem_dir = tmp.path().to_path_buf();
3842        let writer = FilesystemMemWriter::new(mem_dir.clone());
3843        let mut engine = Engine::from_mounts(vec![(
3844            folder_mount("specs", mem_dir),
3845            Box::new(writer) as Box<dyn MemBackend>,
3846        )])
3847        .unwrap();
3848        let (actor, client) = cli_actor();
3849
3850        for title in ["A", "B", "C"] {
3851            engine
3852                .create_entity(
3853                    empty_create_args("specs", title),
3854                    actor,
3855                    Some(&client),
3856                    None,
3857                )
3858                .unwrap();
3859        }
3860        let id = |slug: &str| crate::entity::EntityId::new("specs", slug);
3861        let edge = |from: &str, to: &str, remove: bool| RelateEntityArgs {
3862            source: id(from),
3863            expected_hash: None,
3864            rel_type: "USES".to_string(),
3865            target: id(to),
3866            remove,
3867            description: None,
3868            dry_run: false,
3869        };
3870
3871        let result = engine
3872            .batch_relate(
3873                vec![
3874                    (edge("a", "b", false), Some("add a-b".to_string())),
3875                    (edge("a", "c", false), Some("add a-c".to_string())),
3876                    (edge("a", "c", true), Some("undo a-c".to_string())),
3877                ],
3878                actor,
3879                Some(&client),
3880                false,
3881            )
3882            .unwrap();
3883        assert!(result.applied, "{result:?}");
3884        assert_eq!(result.succeeded, 3);
3885        assert_eq!(result.failed, 0);
3886        assert!(!result.write_id.is_empty(), "one real commit");
3887        let actions: Vec<&str> = result.results.iter().map(|r| r.action.as_str()).collect();
3888        assert_eq!(
3889            actions,
3890            vec!["added", "added", "removed"],
3891            "in-order application: the remove sees the same batch's add"
3892        );
3893
3894        // Net state: A carries exactly the surviving edge to B.
3895        let a = engine.get_entity(&id("a")).unwrap();
3896        assert_eq!(a.relationships.len(), 1, "{:?}", a.relationships);
3897        assert_eq!(a.relationships[0].rel_type, "USES");
3898        assert_eq!(a.relationships[0].target, id("b"));
3899    }
3900
3901    /// Rehearsal contract — single relate:
3902    /// `dry_run: true` runs the FULL validation, reports the would-be
3903    /// edge and the would-be auto-stub (reported, never created) with
3904    /// the marker form's empty `write_id`, and writes nothing. The
3905    /// follow-up real call succeeds and lands EXACTLY the rehearsed
3906    /// prospective `_hash` — the strongest identical-validation
3907    /// observable.
3908    #[test]
3909    fn relate_dry_run_reports_would_be_stub_and_writes_nothing() {
3910        let tmp = TempDir::new().unwrap();
3911        let (mut engine, source) = engine_with_seed(&tmp, "Src");
3912        // Pin the mutation clock: the auto-stamped `last_modified`
3913        // enters the content hash, so the prospective-hash == real-hash
3914        // assertion below is only deterministic under a frozen clock
3915        // (unpinned, it fails whenever a wall-clock second ticks
3916        // between the rehearsal and the real call).
3917        engine.set_mutation_clock(std::sync::Arc::new(|| {
3918            std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_754_000_000)
3919        }));
3920        let (actor, client) = cli_actor();
3921        let absent = crate::EntityId::new("specs", "ghost-target");
3922        let args = |dry_run: bool| RelateEntityArgs {
3923            source: source.id.clone(),
3924            expected_hash: Some(source.content_hash.clone()),
3925            rel_type: "USES".to_string(),
3926            target: absent.clone(),
3927            remove: false,
3928            description: None,
3929            dry_run,
3930        };
3931
3932        let rehearsed = engine
3933            .relate_entity(args(true), actor, Some(&client), None)
3934            .unwrap();
3935        assert_eq!(rehearsed.action, RelateAction::Added);
3936        assert!(rehearsed.write_id.is_empty(), "marker form: empty write_id");
3937        assert!(
3938            rehearsed.warnings.iter().any(
3939                |w| matches!(w, crate::ops::WarningHint::AutoStubCreated { stub_id, pending: true } if *stub_id == absent)
3940            ),
3941            "would-be stub must be reported as pending: {:?}",
3942            rehearsed.warnings
3943        );
3944        // The rehearsed warning must not claim a performed effect —
3945        // conditional wording, code unchanged (AUTO_STUB_CREATED).
3946        let rehearsed_stub = rehearsed
3947            .warnings
3948            .iter()
3949            .find(|w| matches!(w, crate::ops::WarningHint::AutoStubCreated { .. }))
3950            .unwrap();
3951        assert_eq!(rehearsed_stub.code(), "AUTO_STUB_CREATED");
3952        let msg = rehearsed_stub.message();
3953        assert!(
3954            msg.contains("would be auto-created") && !msg.contains("stub auto-created."),
3955            "dry-run wording must be conditional: {msg}"
3956        );
3957        assert!(
3958            !engine.store().contains(&absent),
3959            "would-be stub reported, never created"
3960        );
3961        // Source untouched: stored hash still the pre-call hash, and
3962        // the reported hash is the PROSPECTIVE one (a real change).
3963        let stored = engine.store().get(&source.id).unwrap();
3964        assert_eq!(stored.content_hash, source.content_hash);
3965        assert_ne!(rehearsed.content_hash, source.content_hash);
3966        assert!(stored.relationships.is_empty(), "no edge landed");
3967
3968        // Follow-up real call: succeeds, commits, and the rehearsed
3969        // prospective hash IS the real post-write hash.
3970        let real = engine
3971            .relate_entity(args(false), actor, Some(&client), None)
3972            .unwrap();
3973        assert!(!real.write_id.is_empty(), "the real relate commits");
3974        assert_eq!(
3975            real.content_hash, rehearsed.content_hash,
3976            "prospective hash must equal the real post-write hash"
3977        );
3978        assert!(engine.store().get(&absent).expect("real call stubs").stub);
3979        // The real call keeps the performed-effect wording exactly.
3980        let real_msg = real
3981            .warnings
3982            .iter()
3983            .find(|w| {
3984                matches!(
3985                    w,
3986                    crate::ops::WarningHint::AutoStubCreated { pending: false, .. }
3987                )
3988            })
3989            .expect("real relate carries the non-pending stub warning")
3990            .message();
3991        assert!(
3992            real_msg.contains("did not exist — stub auto-created."),
3993            "real wording unchanged: {real_msg}"
3994        );
3995    }
3996
3997    /// Rehearsal refusal parity — single relate: an illegal rehearsed
3998    /// relate refuses with the IDENTICAL typed error the real call
3999    /// returns (same variant, same payload).
4000    #[test]
4001    fn relate_dry_run_refuses_identically_to_real() {
4002        let tmp = TempDir::new().unwrap();
4003        let (mut engine, source) = engine_with_seed(&tmp, "Src");
4004        let (actor, client) = cli_actor();
4005        // Malformed target id (no `--` separator) — INVALID_ENTITY_ID.
4006        let args = |dry_run: bool| RelateEntityArgs {
4007            source: source.id.clone(),
4008            expected_hash: None,
4009            rel_type: "USES".to_string(),
4010            target: crate::EntityId("bad target with spaces".to_string()),
4011            remove: false,
4012            description: None,
4013            dry_run,
4014        };
4015        let rehearsed = engine
4016            .relate_entity(args(true), actor, Some(&client), None)
4017            .unwrap_err();
4018        let real = engine
4019            .relate_entity(args(false), actor, Some(&client), None)
4020            .unwrap_err();
4021        assert_eq!(
4022            format!("{rehearsed:?}"),
4023            format!("{real:?}"),
4024            "identical typed refusal"
4025        );
4026        assert_eq!(rehearsed.code(), real.code());
4027    }
4028
4029    /// Rehearsal — batch relate: `dry_run: true` validates the whole
4030    /// list in order (a remove of an edge added earlier in the SAME
4031    /// batch reports `"removed"` — the in-order proof), reports the
4032    /// would-be receipt with empty `write_id`, and commits nothing:
4033    /// no edge, no stub, no head movement. The follow-up real batch
4034    /// succeeds.
4035    #[test]
4036    fn batch_relate_dry_run_reports_receipt_and_commits_nothing() {
4037        let tmp = TempDir::new().unwrap();
4038        let mem_dir = tmp.path().to_path_buf();
4039        let writer = FilesystemMemWriter::new(mem_dir.clone());
4040        let mut engine = Engine::from_mounts(vec![(
4041            folder_mount("specs", mem_dir),
4042            Box::new(writer) as Box<dyn MemBackend>,
4043        )])
4044        .unwrap();
4045        let (actor, client) = cli_actor();
4046        for title in ["A", "B"] {
4047            engine
4048                .create_entity(
4049                    empty_create_args("specs", title),
4050                    actor,
4051                    Some(&client),
4052                    None,
4053                )
4054                .unwrap();
4055        }
4056        let id = |slug: &str| crate::entity::EntityId::new("specs", slug);
4057        let edge = |from: &str, to: &str, remove: bool| RelateEntityArgs {
4058            source: id(from),
4059            expected_hash: None,
4060            rel_type: "USES".to_string(),
4061            target: id(to),
4062            remove,
4063            description: None,
4064            dry_run: false,
4065        };
4066        let batch = || {
4067            vec![
4068                (edge("a", "b", false), None),
4069                (edge("a", "ghost", false), None), // would-be auto-stub
4070                (edge("a", "b", true), None),      // in-order: sees entry 0's add
4071            ]
4072        };
4073        let head_before = engine
4074            .mem_head_sha("specs")
4075            .ok()
4076            .flatten()
4077            .unwrap_or_default();
4078
4079        let rehearsed = engine
4080            .batch_relate(batch(), actor, Some(&client), true)
4081            .unwrap();
4082        assert!(rehearsed.applied, "{rehearsed:?}");
4083        assert!(rehearsed.write_id.is_empty(), "marker form: empty write_id");
4084        let actions: Vec<&str> = rehearsed
4085            .results
4086            .iter()
4087            .map(|r| r.action.as_str())
4088            .collect();
4089        assert_eq!(
4090            actions,
4091            vec!["added", "added", "removed"],
4092            "in-order rehearsal semantics"
4093        );
4094        // Nothing landed: no stub, no edge, no head movement.
4095        assert!(!engine.store().contains(&id("ghost")), "no stub created");
4096        assert!(
4097            engine
4098                .get_entity(&id("a"))
4099                .unwrap()
4100                .relationships
4101                .is_empty(),
4102            "no edge landed"
4103        );
4104        let head_after = engine
4105            .mem_head_sha("specs")
4106            .ok()
4107            .flatten()
4108            .unwrap_or_default();
4109        assert_eq!(head_before, head_after, "no commit landed");
4110
4111        // The real batch on the unchanged mem succeeds.
4112        let real = engine
4113            .batch_relate(batch(), actor, Some(&client), false)
4114            .unwrap();
4115        assert!(real.applied, "{real:?}");
4116        assert!(!real.write_id.is_empty());
4117    }
4118
4119    /// Rehearsal refusal parity — batch relate: a failing list refuses
4120    /// under `dry_run: true` with the SAME per-entry report-all
4121    /// envelope the real refusal carries.
4122    #[test]
4123    fn batch_relate_dry_run_refuses_identically_to_real() {
4124        let tmp = TempDir::new().unwrap();
4125        let mem_dir = tmp.path().to_path_buf();
4126        let writer = FilesystemMemWriter::new(mem_dir.clone());
4127        let mut engine = Engine::from_mounts(vec![(
4128            folder_mount("specs", mem_dir),
4129            Box::new(writer) as Box<dyn MemBackend>,
4130        )])
4131        .unwrap();
4132        let (actor, client) = cli_actor();
4133        for title in ["A", "B"] {
4134            engine
4135                .create_entity(
4136                    empty_create_args("specs", title),
4137                    actor,
4138                    Some(&client),
4139                    None,
4140                )
4141                .unwrap();
4142        }
4143        let id = |slug: &str| crate::entity::EntityId::new("specs", slug);
4144        let batch = || {
4145            vec![
4146                (
4147                    RelateEntityArgs {
4148                        source: id("a"),
4149                        expected_hash: None,
4150                        rel_type: "USES".to_string(),
4151                        target: id("b"),
4152                        remove: false,
4153                        description: None,
4154                        dry_run: false,
4155                    },
4156                    None,
4157                ),
4158                (
4159                    RelateEntityArgs {
4160                        source: id("a"),
4161                        expected_hash: None,
4162                        rel_type: "USES".to_string(),
4163                        target: crate::EntityId("bad target".to_string()),
4164                        remove: false,
4165                        description: None,
4166                        dry_run: false,
4167                    },
4168                    None,
4169                ),
4170            ]
4171        };
4172        let rehearsed = engine
4173            .batch_relate(batch(), actor, Some(&client), true)
4174            .unwrap();
4175        let real = engine
4176            .batch_relate(batch(), actor, Some(&client), false)
4177            .unwrap();
4178        assert!(!rehearsed.applied && !real.applied);
4179        let envelope = |r: &crate::ops::BatchResult| {
4180            r.results
4181                .iter()
4182                .map(|e| {
4183                    (
4184                        e.id.to_string(),
4185                        e.action.clone(),
4186                        e.error.as_ref().map(|err| {
4187                            (err.code.clone(), err.message.clone(), err.details.clone())
4188                        }),
4189                    )
4190                })
4191                .collect::<Vec<_>>()
4192        };
4193        assert_eq!(envelope(&rehearsed), envelope(&real), "identical refusals");
4194        assert!(
4195            engine
4196                .get_entity(&id("a"))
4197                .unwrap()
4198                .relationships
4199                .is_empty(),
4200            "neither run landed the valid entry"
4201        );
4202    }
4203
4204    /// Atomicity + report-all for batch relate: a batch with several
4205    /// invalid entries changes NOTHING (no edge lands, the head is
4206    /// unmoved, staged earlier entries roll back) and names EVERY
4207    /// failing entry with its typed code.
4208    #[test]
4209    fn batch_relate_refuses_whole_batch_reporting_every_failure() {
4210        let tmp = TempDir::new().unwrap();
4211        let mem_dir = tmp.path().to_path_buf();
4212        let writer = FilesystemMemWriter::new(mem_dir.clone());
4213        let mut engine = Engine::from_mounts(vec![(
4214            folder_mount("specs", mem_dir),
4215            Box::new(writer) as Box<dyn MemBackend>,
4216        )])
4217        .unwrap();
4218        let (actor, client) = cli_actor();
4219
4220        let a = engine
4221            .create_entity(empty_create_args("specs", "A"), actor, Some(&client), None)
4222            .unwrap();
4223        engine
4224            .create_entity(empty_create_args("specs", "B"), actor, Some(&client), None)
4225            .unwrap();
4226        let head_before = engine
4227            .mem_head_sha("specs")
4228            .ok()
4229            .flatten()
4230            .unwrap_or_default();
4231        let count_before = engine.store().all_entities().count();
4232
4233        let id = |slug: &str| crate::entity::EntityId::new("specs", slug);
4234        let result = engine
4235            .batch_relate(
4236                vec![
4237                    // Valid — stages an edge that must roll back.
4238                    (
4239                        RelateEntityArgs {
4240                            source: id("a"),
4241                            expected_hash: None,
4242                            rel_type: "USES".to_string(),
4243                            target: id("b"),
4244                            remove: false,
4245                            description: None,
4246                            dry_run: false,
4247                        },
4248                        None,
4249                    ),
4250                    // Missing source.
4251                    (
4252                        RelateEntityArgs {
4253                            source: id("ghost"),
4254                            expected_hash: None,
4255                            rel_type: "USES".to_string(),
4256                            target: id("b"),
4257                            remove: false,
4258                            description: None,
4259                            dry_run: false,
4260                        },
4261                        None,
4262                    ),
4263                    // Optimistic-lock mismatch.
4264                    (
4265                        RelateEntityArgs {
4266                            source: id("b"),
4267                            expected_hash: Some("definitely-wrong".to_string()),
4268                            rel_type: "USES".to_string(),
4269                            target: id("a"),
4270                            remove: false,
4271                            description: None,
4272                            dry_run: false,
4273                        },
4274                        None,
4275                    ),
4276                ],
4277                actor,
4278                Some(&client),
4279                false,
4280            )
4281            .unwrap();
4282        assert!(!result.applied);
4283        assert_eq!(result.failed, 2, "{result:?}");
4284        assert!(result.write_id.is_empty());
4285        let codes: Vec<(usize, &str)> = result
4286            .results
4287            .iter()
4288            .enumerate()
4289            .filter(|(_, r)| r.action == "error")
4290            .map(|(i, r)| (i, r.error.as_ref().map(|e| e.code.as_str()).unwrap_or("")))
4291            .collect();
4292        assert_eq!(
4293            codes,
4294            vec![(1, "ENTITY_NOT_FOUND"), (2, "HASH_MISMATCH")],
4295            "every failing entry named with index + typed code: {result:?}"
4296        );
4297        assert_eq!(result.results[0].action, "not_applied");
4298
4299        // NOTHING changed: the staged first edge rolled back, the head
4300        // is unmoved, and no stub or entity appeared.
4301        let a_after = engine.get_entity(&a.id).unwrap();
4302        assert!(
4303            a_after.relationships.is_empty(),
4304            "staged edge must roll back: {:?}",
4305            a_after.relationships
4306        );
4307        assert_eq!(a_after.content_hash, a.content_hash);
4308        let head_after = engine
4309            .mem_head_sha("specs")
4310            .ok()
4311            .flatten()
4312            .unwrap_or_default();
4313        assert_eq!(head_before, head_after, "mem head unmoved");
4314        assert_eq!(engine.store().all_entities().count(), count_before);
4315    }
4316}
4317
4318#[cfg(test)]
4319mod derivation_tests {
4320    use indexmap::IndexMap;
4321    use tempfile::TempDir;
4322
4323    use crate::backend::MemBackend;
4324    use crate::engine::{
4325        CreateEntityArgs, Engine, RelateAction, RelateEntityArgs, UpdateEntityArgs,
4326    };
4327    use crate::ops::WarningHint;
4328    use crate::storage::FilesystemMemWriter;
4329    use crate::vcs::Actor;
4330    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
4331
4332    /// A schema whose `DERIVED_FROM` declares `derivation: true` and
4333    /// whose `SUPPORTS` does not — the paired fixture every assertion
4334    /// here contrasts.
4335    fn deriv_schema() -> std::sync::Arc<memstead_schema::Schema> {
4336        let manifest = r#"name: deriv
4337version: 0.1.0
4338description: derivation fixture
4339when_to_use: tests
4340types:
4341  - note
4342relationships:
4343  mode: strict
4344  definitions:
4345    - name: PART_OF
4346      description: hier
4347      default_weight: 3.0
4348    - name: DERIVED_FROM
4349      description: source derives from target
4350      default_weight: 2.0
4351      derivation: true
4352    - name: SUPPORTS
4353      description: plain edge
4354      default_weight: 1.0
4355    - name: _default
4356      description: fallback
4357      default_weight: 1.0
4358community:
4359  resolution: 1.0
4360  seed: 42
4361"#;
4362        let type_yaml = r#"name: note
4363description: t
4364when_to_use: tests
4365sections:
4366  - key: body
4367    heading: Body
4368    required: true
4369    search_weight: 10.0
4370    catch_all: true
4371    write_rules: []
4372metadata_fields: []
4373title_weight: 100.0
4374text_fields:
4375  - body
4376hierarchy_relationship: PART_OF
4377no_self_loop_relationships: []
4378updatable_fields:
4379  - title
4380  - body
4381health_required_fields:
4382  - body
4383staleness_threshold_days: 90
4384write_rules: []
4385"#;
4386        std::sync::Arc::new(
4387            memstead_schema::loader::load_schema_from_memory(
4388                manifest,
4389                &[("note".to_string(), type_yaml.to_string())],
4390            )
4391            .expect("fixture schema loads"),
4392        )
4393    }
4394
4395    fn engine_at(tmp: &TempDir) -> Engine {
4396        let mem_dir = tmp.path().to_path_buf();
4397        let writer = FilesystemMemWriter::new(mem_dir.clone());
4398        let mount = Mount {
4399            mem: "m".to_string(),
4400            schema: Some("deriv@0.1.0".parse().unwrap()),
4401            storage: MountStorage::Folder { path: mem_dir },
4402            capability: MountCapability::Write,
4403            lifecycle: MountLifecycle::Eager,
4404            cross_linkable: true,
4405            migration_target: None,
4406        };
4407        Engine::from_mounts_with_schemas_dir_and_extra(
4408            vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
4409            None,
4410            vec![deriv_schema()],
4411        )
4412        .unwrap()
4413    }
4414
4415    fn note(title: &str, body: &str) -> CreateEntityArgs {
4416        CreateEntityArgs {
4417            anchors: Vec::new(),
4418            mem: "m".to_string(),
4419            title: title.to_string(),
4420            entity_type: "note".to_string(),
4421            sections: IndexMap::from_iter([("body".to_string(), body.to_string())]),
4422            metadata: IndexMap::new(),
4423            relations: Vec::new(),
4424            dry_run: false,
4425        }
4426    }
4427
4428    fn relate_args(from: &crate::EntityId, rel: &str, to: &crate::EntityId) -> RelateEntityArgs {
4429        RelateEntityArgs {
4430            source: from.clone(),
4431            expected_hash: None,
4432            rel_type: rel.to_string(),
4433            target: to.clone(),
4434            remove: false,
4435            description: None,
4436            dry_run: false,
4437        }
4438    }
4439
4440    /// Criterion 1's fixture, one flow: write → edit target → report
4441    /// stale → re-assert → clear, with the refresh STATED. Plus the
4442    /// undeclared-rel-type no-op complement and the
4443    /// source-edit / markdown-invisibility complements.
4444    #[test]
4445    fn derivation_write_edit_report_reassert_clear() {
4446        let tmp = TempDir::new().unwrap();
4447        let mut engine = engine_at(&tmp);
4448        let target = engine
4449            .create_entity(note("Target", "v1"), Actor::Cli, None, None)
4450            .unwrap();
4451        let source = engine
4452            .create_entity(note("Source", "conclusion"), Actor::Cli, None, None)
4453            .unwrap();
4454
4455        // Write the derivation edge — baseline recorded, report clean.
4456        let added = engine
4457            .relate_entity(
4458                relate_args(&source.id, "DERIVED_FROM", &target.id),
4459                Actor::Cli,
4460                None,
4461                None,
4462            )
4463            .unwrap();
4464        assert_eq!(added.action, RelateAction::Added);
4465        assert!(
4466            engine.derivation_report("m").unwrap().is_empty(),
4467            "freshly baselined edge must not report"
4468        );
4469
4470        // Edit the TARGET → the edge reports stale, naming all three.
4471        let t_now = engine.get_entity(&target.id).unwrap().content_hash.clone();
4472        engine
4473            .update_entity(
4474                UpdateEntityArgs {
4475                    anchors: Vec::new(),
4476                    id: target.id.clone(),
4477                    expected_hash: Some(t_now),
4478                    sections: IndexMap::from_iter([("body".to_string(), "v2".to_string())]),
4479                    append_sections: IndexMap::new(),
4480                    patch_sections: IndexMap::new(),
4481                    sections_unset: Vec::new(),
4482                    metadata: IndexMap::new(),
4483                    metadata_unset: Vec::new(),
4484                    declare_relations: Vec::new(),
4485                    dry_run: false,
4486                    relations_unset: Vec::new(),
4487                    anchors_unset: Vec::new(),
4488                },
4489                Actor::Cli,
4490                None,
4491                None,
4492            )
4493            .unwrap();
4494        let report = engine.derivation_report("m").unwrap();
4495        assert_eq!(report.len(), 1, "{report:?}");
4496        assert_eq!(report[0].source, source.id);
4497        assert_eq!(report[0].rel_type, "DERIVED_FROM");
4498        assert_eq!(report[0].target, target.id);
4499        assert_eq!(report[0].state, "stale");
4500        assert!(report[0].baseline.is_some());
4501
4502        // Editing the SOURCE does not mark its own derivation stale
4503        // (already covered: the edit above touched only the target;
4504        // now touch the source and assert the report is unchanged in
4505        // meaning — still exactly the one stale edge).
4506        let s_now = engine.get_entity(&source.id).unwrap().content_hash.clone();
4507        engine
4508            .update_entity(
4509                UpdateEntityArgs {
4510                    anchors: Vec::new(),
4511                    id: source.id.clone(),
4512                    expected_hash: Some(s_now),
4513                    sections: IndexMap::from_iter([(
4514                        "body".to_string(),
4515                        "conclusion v2".to_string(),
4516                    )]),
4517                    append_sections: IndexMap::new(),
4518                    patch_sections: IndexMap::new(),
4519                    sections_unset: Vec::new(),
4520                    metadata: IndexMap::new(),
4521                    metadata_unset: Vec::new(),
4522                    declare_relations: Vec::new(),
4523                    dry_run: false,
4524                    relations_unset: Vec::new(),
4525                    anchors_unset: Vec::new(),
4526                },
4527                Actor::Cli,
4528                None,
4529                None,
4530            )
4531            .unwrap();
4532        let report = engine.derivation_report("m").unwrap();
4533        assert_eq!(report.len(), 1, "source edit adds nothing: {report:?}");
4534        assert_eq!(report[0].state, "stale");
4535
4536        // Re-assert: duplicate-add refreshes the baseline as its ONE
4537        // effect — action noop, `_hash` unchanged, markdown
4538        // byte-identical, the refresh STATED, a real commit sha.
4539        let md_before = std::fs::read(tmp.path().join("source.md")).unwrap();
4540        let hash_before = engine.get_entity(&source.id).unwrap().content_hash.clone();
4541        let refreshed = engine
4542            .relate_entity(
4543                relate_args(&source.id, "DERIVED_FROM", &target.id),
4544                Actor::Cli,
4545                None,
4546                None,
4547            )
4548            .unwrap();
4549        assert_eq!(refreshed.action, RelateAction::NoOpAlreadyPresent);
4550        assert_eq!(refreshed.content_hash, hash_before, "_hash unchanged");
4551        assert!(
4552            !refreshed.write_id.is_empty(),
4553            "the sidecar refresh persists via a real commit"
4554        );
4555        assert!(
4556            refreshed
4557                .warnings
4558                .iter()
4559                .any(|w| matches!(w, WarningHint::DerivationBaselineRefreshed { .. })),
4560            "the refresh is STATED, never a bare no-op: {:?}",
4561            refreshed.warnings
4562        );
4563        let md_after = std::fs::read(tmp.path().join("source.md")).unwrap();
4564        assert_eq!(md_before, md_after, "baselines never touch the markdown");
4565        assert!(
4566            engine.derivation_report("m").unwrap().is_empty(),
4567            "re-assert clears the staleness"
4568        );
4569
4570        // Undeclared rel-type: duplicate-add keeps today's EXACT
4571        // no-op — empty write_id, no refresh warning.
4572        engine
4573            .relate_entity(
4574                relate_args(&source.id, "SUPPORTS", &target.id),
4575                Actor::Cli,
4576                None,
4577                None,
4578            )
4579            .unwrap();
4580        let noop = engine
4581            .relate_entity(
4582                relate_args(&source.id, "SUPPORTS", &target.id),
4583                Actor::Cli,
4584                None,
4585                None,
4586            )
4587            .unwrap();
4588        assert_eq!(noop.action, RelateAction::NoOpAlreadyPresent);
4589        assert!(noop.write_id.is_empty(), "undeclared no-op stays bare");
4590        assert!(
4591            !noop
4592                .warnings
4593                .iter()
4594                .any(|w| matches!(w, WarningHint::DerivationBaselineRefreshed { .. })),
4595        );
4596        // And undeclared edges never enter the axis: still empty.
4597        assert!(engine.derivation_report("m").unwrap().is_empty());
4598    }
4599
4600    /// A derivation edge with NO recorded baseline (pre-declaration
4601    /// legacy, simulated by removing the sidecar out of band) reports
4602    /// `unbaselined` — distinct from both fresh and stale, never
4603    /// fabricated. The sidecar file itself never lists as an entity.
4604    #[test]
4605    fn missing_baseline_reports_unbaselined_never_fabricated() {
4606        let tmp = TempDir::new().unwrap();
4607        let mut engine = engine_at(&tmp);
4608        let target = engine
4609            .create_entity(note("Target", "v1"), Actor::Cli, None, None)
4610            .unwrap();
4611        let source = engine
4612            .create_entity(note("Source", "conclusion"), Actor::Cli, None, None)
4613            .unwrap();
4614        engine
4615            .relate_entity(
4616                relate_args(&source.id, "DERIVED_FROM", &target.id),
4617                Actor::Cli,
4618                None,
4619                None,
4620            )
4621            .unwrap();
4622        // The sidecar exists on disk but is not an entity.
4623        let sidecar = tmp.path().join(".memstead").join("derivations.json");
4624        assert!(sidecar.exists(), "baseline persisted to the sidecar");
4625        assert!(
4626            engine
4627                .get_entity(&crate::EntityId::new("m", "derivations"))
4628                .is_none()
4629        );
4630
4631        // Simulate a pre-declaration edge: drop the sidecar out of
4632        // band (fixture surgery, the mounts.json precedent).
4633        std::fs::remove_file(&sidecar).unwrap();
4634        let report = engine.derivation_report("m").unwrap();
4635        assert_eq!(report.len(), 1, "{report:?}");
4636        assert_eq!(report[0].state, "unbaselined");
4637        assert!(report[0].baseline.is_none());
4638    }
4639}