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