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    /// 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/// The edge a relate names, read under the lock: everything later phases
65/// read from the workspace before they decide anything.
66struct ResolvedRelate {
67    args: RelateEntityArgs,
68    source_mem: String,
69    target_mem: String,
70    mount_idx: usize,
71    schema: std::sync::Arc<memstead_schema::Schema>,
72    target_schema_ref: Option<SchemaRef>,
73    cross_mem_different: bool,
74    warnings: Vec<WarningHint>,
75    entity: Entity,
76    target_type: Option<String>,
77    target_verified_in_storage: bool,
78    target_mem_uncreated: bool,
79}
80
81/// The edge with every add-time gate passed, and the source's type.
82struct ValidatedRelate {
83    resolved: ResolvedRelate,
84    type_def: std::sync::Arc<memstead_schema::TypeDefinition>,
85}
86
87/// What a relate's commit returns to the outcome phase.
88struct CommittedRelate {
89    prepared: PreparedRelate,
90    write_id: String,
91    landed_warnings: Vec<WarningHint>,
92    stamp_warnings: Vec<WarningHint>,
93}
94
95/// Per-item state of a batch relate, carrying the applied item's
96/// action label from its prepared state.
97enum ItemState {
98    Applied(&'static str),
99    Noop,
100    Error,
101}
102
103/// The relate verb's action words: the applied item's own label,
104/// `noop` for an applied no-op.
105fn relate_actions(items: Vec<(EntityId, ItemState)>) -> Vec<(EntityId, String)> {
106    items
107        .into_iter()
108        .map(|(id, state)| {
109            let action = match state {
110                ItemState::Applied(label) => label,
111                ItemState::Noop => "noop",
112                ItemState::Error => unreachable!("refusal path returned above"),
113            };
114            (id, action.to_string())
115        })
116        .collect()
117}
118
119impl Engine {
120    /// Add or remove a typed relationship on `args.source`.
121    ///
122    /// Cross-mem relate is policy-gated through
123    /// [`Engine::cross_mem_link_allowed`] — the workspace's
124    /// `[cross_mem_links]` table (or per-create-rule
125    /// `default_cross_links` synthesis) decides whether the edge is
126    /// permitted. Disallowed pairings surface
127    /// [`EngineError::CrossMemLinkNotAllowed`]. Cross-mem relate
128    /// only writes the source entity's markdown — the target mem is
129    /// never written to. Auto-stub for absent targets works for
130    /// Write target mems; ReadOnly target mems reject absent
131    /// targets with [`EngineError::CrossMemTargetNotFound`] because
132    /// the engine cannot persist a stub through the read-only
133    /// boundary.
134    ///
135    /// Schema-undeclared rel types surface either as validation
136    /// errors (strict mode) or as ride-along warnings on the outcome
137    /// (open mode).
138    pub fn relate_entity(
139        &mut self,
140        args: RelateEntityArgs,
141        actor: Actor,
142        client: Option<&ClientId>,
143        note: Option<&str>,
144    ) -> Result<RelateEntityOutcome, EngineError> {
145        // The lock first, then the ids. A relate locks the mems of both
146        // ends and reloads the source's (a DEFERRED target mem is
147        // deliberately not loaded: target verification must never cost
148        // a mem's load, the storage check below answers the existence
149        // and type questions against the branch tree / filesystem
150        // instead). It takes the whole workspace when an end is named
151        // by a bare slug, resolved under the lock, or when it adds an
152        // edge on an acyclic relationship, whose cycle guard walks
153        // edges in every mem. The announcements of resolved ids lead
154        // the warnings. Hoisted out of `prepare_relate` so
155        // `batch_relate` can lock and reload once up front instead of
156        // per entry.
157        let mut args = args;
158        let (named_source, named_target) =
159            (args.source.mem().to_string(), args.target.mem().to_string());
160        let short = named_source.is_empty() || named_target.is_empty();
161        let (_write_lock, reloaded) = {
162            let (rel_type, adds) = (&args.rel_type, !args.remove);
163            // Both ends' mems, and a mem a link in the description names.
164            let mut locked = crate::engine::write_lock::referred_mems(
165                &named_source,
166                std::iter::empty(),
167                args.description.as_deref(),
168            );
169            locked.push(named_source.clone());
170            locked.push(named_target.clone());
171            self.lock_for_verb(
172                !args.dry_run,
173                &locked,
174                std::slice::from_ref(&named_source),
175                |engine| {
176                    short
177                        || engine.write_needs_full_load(
178                            &named_source,
179                            [crate::engine::mutation::EdgeWrite {
180                                rel_type,
181                                target_mem: &named_target,
182                                remove: !adds,
183                            }],
184                            // relate writes declared edges only
185                            std::iter::empty(),
186                        )
187                },
188            )?
189        };
190        let (source, source_hint) = self.resolve_entity_id(&args.source)?;
191        args.source = source;
192        let (target, target_hint) = self.resolve_entity_id(&args.target)?;
193        args.target = target;
194        let source_mem = args.source.mem().to_string();
195        let mut drift_warnings: Vec<WarningHint> =
196            source_hint.into_iter().chain(target_hint).collect();
197        drift_warnings.extend(reloaded);
198        // An ACYCLIC rel-type's cycle guard walks the whole rel-type
199        // subgraph (`would_cycle`), and a cycle can pass through any
200        // mem — an edge on a deferred (lazy, unloaded) mem's entity is
201        // invisible to a walk over the endpoint mems alone, so an add
202        // an eager boot refuses would land silently and corrupt an
203        // innocent edge on the next full load (the fourth lazy-mount
204        // grade demonstrated exactly that on a three-mem chain). The
205        // same holds for a rel-type in an `acyclic_sets` set, whose
206        // guard walks the set's UNION subgraph, and for declared
207        // aggregate signals on either endpoint's schema: the
208        // threshold-crossing diff counts edges that can originate in
209        // any mem, so a partial store silently mis-levels it. Full
210        // load before the guard; writes touching neither skip the
211        // cost.
212        if self.write_needs_full_load(
213            &source_mem,
214            [crate::engine::mutation::EdgeWrite {
215                rel_type: &args.rel_type,
216                target_mem: args.target.mem(),
217                remove: args.remove,
218            }],
219            // relate writes declared edges only
220            std::iter::empty(),
221        ) {
222            self.ensure_mems_loaded(None);
223        }
224
225        let dry_run = args.dry_run;
226        let stubs_before = self.stub_ids();
227        let landed = self
228            .prepare_relate(args, drift_warnings)
229            .and_then(|p| match p {
230                RelatePrepareOutcome::Done(outcome) => {
231                    self.relate_noop_outcome(outcome, dry_run, actor, client, note)
232                }
233                RelatePrepareOutcome::Prepared(prepared) if dry_run => {
234                    self.relate_preview(prepared)
235                }
236                RelatePrepareOutcome::Prepared(prepared) => {
237                    self.commit_prepared_relate(prepared, actor, client, note)
238                }
239            });
240        self.drop_stubs_of_an_unlanded_write(&stubs_before, &landed, dry_run);
241        landed
242    }
243
244    /// The duplicate-add re-baseline. Called
245    /// from the `NoOpAlreadyPresent` path when the rel-type is
246    /// derivation-declared: stages a sidecar-only refresh of the
247    /// edge's baseline to the target's current hash and commits it
248    /// (the anchor-only-update precedent — a real persisted effect
249    /// rides a real commit), then returns the outcome with the
250    /// refresh STATED (`DERIVATION_BASELINE_REFRESHED` warning + the
251    /// sidecar commit's sha). `_hash` and the edge are untouched. On
252    /// an undeclared rel-type the outcome passes through unchanged —
253    /// today's exact no-op response.
254    fn refresh_derivation_baseline_on_noop(
255        &mut self,
256        mut outcome: RelateEntityOutcome,
257        actor: Actor,
258        client: Option<&ClientId>,
259        note: Option<&str>,
260    ) -> Result<RelateEntityOutcome, EngineError> {
261        let source_mem = outcome.from.mem().to_string();
262        let declared = self
263            .schemas
264            .get(&source_mem)
265            .is_some_and(|s| super::rel_type_declares_derivation(s, &outcome.rel_type));
266        if !declared {
267            return Ok(outcome);
268        }
269        let Some(mount_idx) = self.mounts.iter().position(|m| m.mount.mem == source_mem) else {
270            return Ok(outcome);
271        };
272        let hash = self
273            .store
274            .get(&outcome.to)
275            .map(|e| e.content_hash.clone())
276            .unwrap_or_default();
277        let (from, rel, to) = (
278            outcome.from.to_string(),
279            outcome.rel_type.clone(),
280            outcome.to.to_string(),
281        );
282        let backend = self.mounts[mount_idx].backend.as_ref();
283        super::stage_derivation_sidecar(backend, |s| s.set(&from, &rel, &to, &hash))?;
284        let ctx = self.commit_context(
285            Some("relate_entity"),
286            actor,
287            client.cloned(),
288            note.map(String::from),
289        );
290        let landed = self.commit_staged(
291            mount_idx,
292            &format!("memstead: derivation re-baseline {}", outcome.from),
293            &ctx,
294            &[],
295        )?;
296        let write_id = landed.write_id;
297        outcome.warnings.extend(landed.warnings);
298        self.record_self_write(mount_idx, &write_id);
299        // `relate_entity` returns early into this path, so the stamp call on
300        // the ordinary path never runs and its report has to be collected
301        // here (found by the re-grade).
302        outcome
303            .warnings
304            .extend(self.stamp_mutation_versions(mount_idx));
305        outcome.write_id = write_id;
306        outcome
307            .warnings
308            .push(WarningHint::DerivationBaselineRefreshed {
309                from: outcome.from.clone(),
310                rel_type: outcome.rel_type.clone(),
311                to: outcome.to.clone(),
312            });
313        Ok(outcome)
314    }
315
316    /// A relate that changes nothing: an idempotent re-add on a real
317    /// run refreshes a derivation edge's baseline (the agent's explicit
318    /// "reviewed, still holds"); every other no-op is its outcome.
319    fn relate_noop_outcome(
320        &mut self,
321        outcome: RelateEntityOutcome,
322        dry_run: bool,
323        actor: Actor,
324        client: Option<&ClientId>,
325        note: Option<&str>,
326    ) -> Result<RelateEntityOutcome, EngineError> {
327        if !dry_run && matches!(outcome.action, RelateAction::NoOpAlreadyPresent) {
328            return self.refresh_derivation_baseline_on_noop(outcome, actor, client, note);
329        }
330        Ok(outcome)
331    }
332
333    /// A dry run's outcome: the prospective hash of the rendered file,
334    /// nothing written.
335    fn relate_preview(&self, prepared: PreparedRelate) -> Result<RelateEntityOutcome, EngineError> {
336        let parse_result = parse_markdown(
337            &prepared.markdown,
338            &prepared.file_path,
339            prepared.type_def.as_ref(),
340            &prepared.source_mem,
341        )
342        .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
343        // A rehearsal demands no note: `NOTE_MISSING` attributes a
344        // write that landed without provenance, and nothing lands
345        // here (create and update rehearse the same way; a relate
346        // rehearsal once carried the nudge and so reported a
347        // provenance gap on a commit that did not exist).
348        let warnings = prepared.warnings;
349        Ok(RelateEntityOutcome {
350            from: prepared.from,
351            to: prepared.to,
352            rel_type: prepared.rel_type,
353            action: prepared.action,
354            content_hash: parse_result.entity.content_hash,
355            write_id: String::new(),
356            source: "explicit".to_string(),
357            orphan_stubs_removed: Vec::new(),
358            warnings,
359        })
360    }
361
362    /// Stage, commit and report a prepared relate; the signal levels
363    /// before the write are read first, for the crossing warnings.
364    fn commit_prepared_relate(
365        &mut self,
366        prepared: PreparedRelate,
367        actor: Actor,
368        client: Option<&ClientId>,
369        note: Option<&str>,
370    ) -> Result<RelateEntityOutcome, EngineError> {
371        let signal_snapshot = crate::ops::signals::snapshot_levels(
372            &self.store,
373            &self.schemas,
374            [&prepared.from, &prepared.to],
375        );
376
377        self.stage_relate(&prepared)?;
378        let committed = self.commit_relate(prepared, actor, client, note)?;
379        Ok(self.relate_outcome(committed, signal_snapshot, note))
380    }
381
382    /// Stage phase: the planned stub and the source's file, and on a
383    /// derivation-declared rel-type the edge's baseline.
384    fn stage_relate(&mut self, prepared: &PreparedRelate) -> Result<(), EngineError> {
385        self.stage_prepared_relate(prepared)?;
386        if let Some(schema) = self.schemas.get(&prepared.source_mem)
387            && crate::engine::mutation::rel_type_declares_derivation(schema, &prepared.rel_type)
388        {
389            let backend = self.mounts[prepared.mount_idx].backend.as_ref();
390            let (from, rel, to) = (
391                prepared.from.to_string(),
392                prepared.rel_type.clone(),
393                prepared.to.to_string(),
394            );
395            match prepared.action {
396                RelateAction::Added => {
397                    let hash = self
398                        .store
399                        .get(&prepared.to)
400                        .map(|e| e.content_hash.clone())
401                        .unwrap_or_default();
402                    crate::engine::mutation::stage_derivation_sidecar(backend, |s| {
403                        s.set(&from, &rel, &to, &hash)
404                    })?;
405                }
406                RelateAction::Removed => {
407                    crate::engine::mutation::stage_derivation_sidecar(backend, |s| {
408                        s.remove(&from, &rel, &to)
409                    })?;
410                }
411                _ => {}
412            }
413        }
414
415        Ok(())
416    }
417
418    /// Commit phase: one commit with the relate's provenance, recorded
419    /// as this engine's own write.
420    fn commit_relate(
421        &mut self,
422        prepared: PreparedRelate,
423        actor: Actor,
424        client: Option<&ClientId>,
425        note: Option<&str>,
426    ) -> Result<CommittedRelate, EngineError> {
427        let commit_subject = format!("memstead: relate {}", prepared.from);
428        let ctx = self.commit_context(
429            Some("relate_entity"),
430            actor,
431            client.cloned(),
432            note.map(String::from),
433        );
434        let record =
435            self.provenance_record(ProvenanceKind::Relate, &prepared.from, actor, client, note);
436        let landed = self.commit_staged(prepared.mount_idx, &commit_subject, &ctx, &[record])?;
437        let write_id = landed.write_id;
438        let follow_up_warnings = landed.warnings;
439
440        self.record_self_write(prepared.mount_idx, &write_id);
441        let stamp_warnings = self.stamp_mutation_versions(prepared.mount_idx);
442
443        // A failed store update reloaded the mem from storage, where the
444        // write is; the receipt reads from that view.
445        Ok(CommittedRelate {
446            prepared,
447            write_id,
448            landed_warnings: follow_up_warnings,
449            stamp_warnings,
450        })
451    }
452
453    /// Outcome phase: the store and the indexes take the write, and the
454    /// receipt reports it with every warning in the order the verb has
455    /// always reported them.
456    fn relate_outcome(
457        &mut self,
458        committed: CommittedRelate,
459        signal_snapshot: crate::ops::signals::SignalSnapshot,
460        note: Option<&str>,
461    ) -> RelateEntityOutcome {
462        let CommittedRelate {
463            prepared,
464            write_id,
465            landed_warnings: mut follow_up_warnings,
466            stamp_warnings,
467        } = committed;
468        let content_hash = self
469            .after_commit(
470                prepared.mount_idx,
471                "store_update",
472                &mut follow_up_warnings,
473                |engine| engine.apply_prepared_relate_to_store(&prepared),
474            )
475            .unwrap_or_else(|| {
476                self.store
477                    .get(&prepared.from)
478                    .map(|e| e.content_hash.clone())
479                    .unwrap_or_default()
480            });
481
482        // On the `--remove` path, the edge we just dropped may
483        // have been the last incoming edge to a stub. The orphan-stub
484        // GC hook fired from `memstead_delete` already; mirror it here so
485        // every mutation that can leave orphans cleans them up.
486        // Scoped sweep — only inspect the just-severed target. The
487        // only possible new orphan from a relate-remove is the
488        // target whose incoming edge we removed; checking the entire
489        // store would catch pre-existing orphans which aren't this
490        // mutation's responsibility (and which `memstead_delete`'s full
491        // sweep also leaves alone before its own removal). Funnels
492        // through the shared `gc_orphan_stubs_among` predicate so the
493        // relate-remove, delete, and update-via-alias-resync paths
494        // can't drift on what counts as a GC-able orphan.
495        let orphan_stubs_removed: Vec<EntityId> =
496            if matches!(prepared.action, RelateAction::Removed) {
497                crate::engine::mutation::gc_orphan_stubs_among(
498                    &mut self.store,
499                    std::iter::once(&prepared.to),
500                )
501            } else {
502                Vec::new()
503            };
504
505        self.invalidate_communities();
506        // Incremental: only the SOURCE entity's file
507        // was rewritten; stub targets and GC'd orphan stubs were never
508        // indexed.
509        self.maintain_search_indexes(std::slice::from_ref(&prepared.from));
510
511        let PreparedRelate {
512            from,
513            to,
514            rel_type,
515            action,
516            mut warnings,
517            ..
518        } = prepared;
519
520        warnings.extend(follow_up_warnings);
521        warnings.extend(stamp_warnings);
522
523        // Signal crossings ride the out-of-band warning channel beside
524        // the success payload — never error-shaped, never changing the
525        // mutation's success semantics.
526        warnings.extend(crate::ops::signals::crossing_warnings(
527            &self.store,
528            &self.schemas,
529            &signal_snapshot,
530        ));
531
532        // `require_notes` provenance nudge — single engine-level
533        // enforcement point. Only reached on the real-commit path
534        // (Added / Removed); the NoOpAlreadyPresent / NoOpAbsent branches
535        // return early above with an empty `write_id` and never demand
536        // a note (nothing landed to attribute).
537        if let Some(w) = self.note_missing_warning("relate_entity", note) {
538            warnings.push(w);
539        }
540
541        RelateEntityOutcome {
542            from,
543            to,
544            rel_type,
545            action,
546            content_hash,
547            write_id,
548            source: "explicit".to_string(),
549            warnings,
550            orphan_stubs_removed,
551        }
552    }
553
554    /// Every validation gate and the mutation plan for one relate —
555    /// shared verbatim by the single-item path above and
556    /// [`Self::batch_relate`], so batching can never drift from the
557    /// single-item gates. Never mutates the store, writes no file,
558    /// commits nothing: refusals are side-effect-free by
559    /// construction. The reload-before-operation probe is the
560    /// caller's job (hoisted so a batch probes each mem once).
561    fn prepare_relate(
562        &mut self,
563        args: RelateEntityArgs,
564        drift_warnings: Vec<WarningHint>,
565    ) -> Result<RelatePrepareOutcome, EngineError> {
566        let resolved = self.resolve_relate(args, drift_warnings)?;
567        let validated = self.validate_relate(resolved)?;
568        self.compose_relate(validated)
569    }
570
571    /// Perform a prepared relate's pre-commit side effects: upsert the
572    /// planned forward-reference stub (if any) and write the source
573    /// entity's regenerated markdown into the backend's pending
574    /// buffer. Nothing is committed; a caller that aborts afterwards
575    /// rolls back with a store snapshot + `discard_all_pending`.
576    fn stage_prepared_relate(&mut self, p: &PreparedRelate) -> Result<(), EngineError> {
577        if let Some(stub_id) = &p.stub_target {
578            self.store
579                .upsert(stub_id.clone(), make_stub(stub_id, p.stub_kind.clone()));
580        }
581        self.mounts[p.mount_idx]
582            .backend
583            .write_entity(Path::new(&p.file_path), p.markdown.as_bytes())?;
584        Ok(())
585    }
586
587    /// Parse the prepared markdown back and push it into the store
588    /// (replacing the pre-mutation source entity), then re-run the
589    /// alias-edge remap. Returns the new `content_hash`. In the
590    /// single-item path this runs after the commit (preserving the
591    /// pre-split ordering); `batch_relate` runs it immediately after
592    /// staging each entry so later entries in the same batch validate
593    /// against this entry's effect — applied-in-order semantics.
594    fn apply_prepared_relate_to_store(
595        &mut self,
596        p: &PreparedRelate,
597    ) -> Result<String, EngineError> {
598        let parse_result = parse_markdown(
599            &p.markdown,
600            &p.file_path,
601            p.type_def.as_ref(),
602            &p.source_mem,
603        )
604        .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
605        let content_hash = parse_result.entity.content_hash.clone();
606        let fallback = engine_fallback_type();
607        push_entities_into_store(&mut self.store, vec![parse_result], fallback.as_ref(), None);
608        crate::entity::store_builder::remap_alias_target_edge_sources(
609            &mut self.store,
610            &self.schemas,
611        );
612        Ok(content_hash)
613    }
614
615    /// Atomic batch relate — the edge-side sibling of
616    /// [`Self::batch_create`] / [`Self::batch_update`]. One list
617    /// carrying both additions and removals, **applied in order**:
618    /// each entry validates against the graph state produced by every
619    /// prior valid entry (an add followed by a remove of the same edge
620    /// nets to no edge; an acyclic check sees edges added earlier in
621    /// the same batch). Per-entry shape mirrors what `relate` accepts.
622    ///
623    /// - **All-or-nothing, report-all.** A single invalid entry
624    ///   refuses the whole batch — no edge changes, no head movement —
625    ///   and the refusal identifies EVERY failing entry with its typed
626    ///   `{code, message, details}` envelope, bounded at
627    ///   [`Self::BATCH_ERROR_REPORT_CAP`] with `errors_suppressed`
628    ///   counting the rest. An entry after a failing one validates
629    ///   against the state as of the prior *valid* entries, so a
630    ///   dependent entry may cascade — every reported code is still a
631    ///   true refusal of the submitted file.
632    /// - **One commit per touched mem** (subject
633    ///   `memstead: batch-relate (N edges)`), per-entry provenance
634    ///   notes, exactly like the rest of the family. No-op entries
635    ///   (idempotent re-add / absent remove) report `"noop"` and
636    ///   produce no write.
637    /// - Orphan-stub GC runs over every removed edge's target after
638    ///   the commit, same predicate as the single-item path (the
639    ///   collected ids are not part of `BatchResult`'s fixed family
640    ///   shape).
641    ///
642    /// **Rehearsal** (`dry_run: true`): the FULL in-order validation
643    /// pass runs — each entry staged against the state its
644    /// predecessors produced, identical refusals, identical report-all
645    /// envelope — then the batch stops before any commit and rolls the
646    /// staged state back. A legal batch returns the would-be receipt
647    /// (per-entry actions, would-be `orphan_stubs_removed` computed on
648    /// the staged state) with the marker form's empty `write_id`; an
649    /// illegal one returns the same refusal a real call would. No
650    /// edge, stub, or commit lands.
651    pub fn batch_relate(
652        &mut self,
653        relates: Vec<(RelateEntityArgs, Option<String>)>,
654        actor: Actor,
655        client: Option<&ClientId>,
656        dry_run: bool,
657    ) -> Result<crate::ops::BatchResult, EngineError> {
658        if relates.is_empty() {
659            return Ok(super::batch_empty());
660        }
661
662        // Reload every touched mem (sources and targets) once, up
663        // front — the per-entry probe is hoisted out of
664        // `prepare_relate` for exactly this.
665        // The lock first, then the ids. Every mem an item names is
666        // locked, a deferred target included: its lock costs no load,
667        // and the storage check of the target runs under it. A mem that
668        // is only ever a TARGET in this batch and is deferred stays
669        // unloaded: target verification runs against storage, and
670        // loading it would convert verification into a
671        // full load. Source mems always load: a write into a mem needs
672        // the mem. The batch takes the whole workspace when an item
673        // names an end by a bare slug (resolved under the lock) or adds
674        // an edge on an acyclic relationship (the cycle guard walks
675        // edges in every mem). What the roster reconcile and the
676        // reloads report rides the receipt like on a single verb.
677        let mut touched_mems: Vec<String> = relates
678            .iter()
679            .flat_map(|(a, _)| [a.source.mem().to_string(), a.target.mem().to_string()])
680            .collect();
681        touched_mems.sort();
682        touched_mems.dedup();
683        let mut source_mems: Vec<String> = relates
684            .iter()
685            .map(|(a, _)| a.source.mem().to_string())
686            .collect();
687        source_mems.sort();
688        source_mems.dedup();
689        let (_write_lock, drift_warnings) = {
690            let items = &relates;
691            let mut locked = touched_mems.clone();
692            for (a, _) in items {
693                locked.extend(crate::engine::write_lock::referred_mems(
694                    a.source.mem(),
695                    std::iter::empty(),
696                    a.description.as_deref(),
697                ));
698            }
699            self.lock_for_verb(!dry_run, &locked, &source_mems, |engine| {
700                items.iter().any(|(a, _)| {
701                    a.source.mem().is_empty()
702                        || a.target.mem().is_empty()
703                        || engine.write_needs_full_load(
704                            a.source.mem(),
705                            [crate::engine::mutation::EdgeWrite {
706                                rel_type: &a.rel_type,
707                                target_mem: a.target.mem(),
708                                remove: a.remove,
709                            }],
710                            // relate writes declared edges only
711                            std::iter::empty(),
712                        )
713                })
714            })?
715        };
716        // An item whose short id does not resolve fails as its own
717        // error below, never the whole batch.
718        let mut short_hints: Vec<WarningHint> = Vec::new();
719        let mut short_errors: Vec<(usize, EngineError)> = Vec::new();
720        let relates: Vec<(RelateEntityArgs, Option<String>)> = relates
721            .into_iter()
722            .enumerate()
723            .map(|(i, (mut a, n))| {
724                match self.resolve_entity_id(&a.source) {
725                    Ok((s, hint)) => {
726                        a.source = s;
727                        short_hints.extend(hint);
728                    }
729                    Err(e) => short_errors.push((i, e)),
730                }
731                match self.resolve_entity_id(&a.target) {
732                    Ok((t, hint)) => {
733                        a.target = t;
734                        short_hints.extend(hint);
735                    }
736                    Err(e) => short_errors.push((i, e)),
737                }
738                (a, n)
739            })
740            .collect();
741        // Same acyclic-guard rule as the single-item path: any added
742        // edge on an ACYCLIC rel-type (or a rel-type in an
743        // `acyclic_sets` set, whose guard walks the set's UNION
744        // subgraph) walks the whole subgraph, so the walk must see
745        // every mem — deferred (lazy, unloaded) ones included — or a
746        // cycle through an unloaded mem is admitted through this
747        // path. Declared signals on either endpoint's schema need
748        // the full load for the same reason as the single-item path.
749        if relates.iter().any(|(a, _)| {
750            self.write_needs_full_load(
751                a.source.mem(),
752                [crate::engine::mutation::EdgeWrite {
753                    rel_type: &a.rel_type,
754                    target_mem: a.target.mem(),
755                    remove: a.remove,
756                }],
757                // relate writes declared edges only
758                std::iter::empty(),
759            )
760        }) {
761            self.ensure_mems_loaded(None);
762        }
763
764        // Snapshot for the all-or-nothing rollback: staged entries
765        // mutate the store as they apply (in-order semantics), so a
766        // refusal restores this snapshot and discards every backend's
767        // pending buffer. Any early-return added below MUST do both.
768        let store_snapshot = self.store.clone();
769
770        let mut items: Vec<(EntityId, ItemState)> = Vec::with_capacity(relates.len());
771        let mut prepared: Vec<PreparedRelate> = Vec::new();
772        let mut notes: Vec<Option<String>> = Vec::new();
773        let mut errors: Vec<(usize, EngineError)> = Vec::new();
774
775        for (i, (args, note)) in relates.into_iter().enumerate() {
776            let source_id = args.source.clone();
777            if let Some(pos) = short_errors.iter().position(|(j, _)| *j == i) {
778                let (_, e) = short_errors.remove(pos);
779                items.push((source_id, ItemState::Error));
780                errors.push((i, e));
781                continue;
782            }
783            // Rehearsal is batch-level (the `dry_run` parameter) —
784            // per-entry dry-run stays forced off; the staging below is
785            // what gives later entries in-order semantics, and the
786            // batch-level rollback undoes it.
787            let mut args = args;
788            args.dry_run = false;
789            match self.prepare_relate(args, Vec::new()) {
790                Ok(RelatePrepareOutcome::Done(_)) => {
791                    items.push((source_id, ItemState::Noop));
792                }
793                Ok(RelatePrepareOutcome::Prepared(p)) => {
794                    // Stage + apply NOW so later entries validate
795                    // against this entry's effect (applied-in-order).
796                    if let Err(e) = self.stage_prepared_relate(&p) {
797                        self.store = store_snapshot;
798                        self.discard_all_pending();
799                        return Err(e);
800                    }
801                    if let Err(e) = self.apply_prepared_relate_to_store(&p) {
802                        self.store = store_snapshot;
803                        self.discard_all_pending();
804                        return Err(e);
805                    }
806                    // Derivation baseline — same predicate
807                    // and staging as the single-item path; rides the
808                    // batch commit, rolls back with a refusal. (Batch
809                    // no-op entries do NOT re-baseline — the explicit
810                    // "reviewed, still holds" gesture is the single
811                    // relate / single-op MCP list.)
812                    if let Some(schema) = self.schemas.get(&p.source_mem)
813                        && super::rel_type_declares_derivation(schema, &p.rel_type)
814                    {
815                        let backend = self.mounts[p.mount_idx].backend.as_ref();
816                        let (from, rel, to) =
817                            (p.from.to_string(), p.rel_type.clone(), p.to.to_string());
818                        let staged = match p.action {
819                            RelateAction::Added => {
820                                let hash = self
821                                    .store
822                                    .get(&p.to)
823                                    .map(|e| e.content_hash.clone())
824                                    .unwrap_or_default();
825                                super::stage_derivation_sidecar(backend, |s| {
826                                    s.set(&from, &rel, &to, &hash)
827                                })
828                            }
829                            RelateAction::Removed => {
830                                super::stage_derivation_sidecar(backend, |s| {
831                                    s.remove(&from, &rel, &to)
832                                })
833                            }
834                            _ => Ok(()),
835                        };
836                        if let Err(e) = staged {
837                            self.store = store_snapshot;
838                            self.discard_all_pending();
839                            return Err(e);
840                        }
841                    }
842                    let label = match p.action {
843                        RelateAction::Added => "added",
844                        RelateAction::Removed => "removed",
845                        _ => unreachable!("no-ops resolve to Done"),
846                    };
847                    items.push((source_id, ItemState::Applied(label)));
848                    prepared.push(p);
849                    notes.push(note);
850                }
851                Err(e) => {
852                    items.push((source_id, ItemState::Error));
853                    errors.push((i, e));
854                }
855            }
856        }
857
858        if !errors.is_empty() {
859            // Refuse the whole batch; roll back every staged entry.
860            self.store = store_snapshot;
861            self.discard_all_pending();
862            return Ok(super::batch_refusal(
863                items.into_iter().map(|(id, _)| id).collect(),
864                errors,
865            ));
866        }
867
868        // Rehearsal: every entry validated in order against the state
869        // its predecessors produced and nothing failed — stop before
870        // any commit. The would-be orphan GC is computed on the staged
871        // store (honest: it is exactly what the real call would
872        // collect), then the whole staged state rolls back.
873        if dry_run {
874            let removed_targets: Vec<EntityId> = prepared
875                .iter()
876                .filter(|p| matches!(p.action, RelateAction::Removed))
877                .map(|p| p.to.clone())
878                .collect();
879            let orphan_stubs_removed =
880                super::gc_orphan_stubs_among(&mut self.store, removed_targets.iter());
881            self.store = store_snapshot;
882            self.discard_all_pending();
883            return Ok(super::batch_receipt(
884                relate_actions(items),
885                Vec::new(),
886                orphan_stubs_removed,
887                String::new(),
888            ));
889        }
890
891        // --- Commit once per touched mount, in first-seen order. ---
892        let mut distinct_mounts: Vec<usize> = Vec::new();
893        for p in &prepared {
894            if !distinct_mounts.contains(&p.mount_idx) {
895                distinct_mounts.push(p.mount_idx);
896            }
897        }
898        let mut mount_commits: Vec<(usize, String)> = Vec::with_capacity(distinct_mounts.len());
899        let mut batch_warnings: Vec<WarningHint> = drift_warnings;
900        batch_warnings.extend(short_hints);
901        for &m in &distinct_mounts {
902            // Distinct source ids for this mount (an entity may carry
903            // several edge changes in one batch).
904            let mut entity_ids: Vec<String> = Vec::new();
905            let mut edge_count = 0usize;
906            for p in prepared.iter().filter(|p| p.mount_idx == m) {
907                edge_count += 1;
908                let s = p.from.to_string();
909                if !entity_ids.contains(&s) {
910                    entity_ids.push(s);
911                }
912            }
913            let subject = format!("memstead: batch-relate ({edge_count} edges)");
914            // Per-entry notes ride the batch commit's note record as
915            // `<id>: <note>` lines, keyed by the edge's
916            // source entity — `append_provenance` is a no-op on the
917            // git-branch backend. No notes → no note record.
918            let note_lines: Vec<String> = prepared
919                .iter()
920                .zip(notes.iter())
921                .filter(|(p, _)| p.mount_idx == m)
922                .filter_map(|(p, n)| n.as_ref().map(|n| format!("{}: {n}", p.from)))
923                .collect();
924            let mut ctx = self.commit_context(
925                Some("batch_relate"),
926                actor,
927                client.cloned(),
928                if note_lines.is_empty() {
929                    None
930                } else {
931                    Some(note_lines.join("\n"))
932                },
933            );
934            ctx.entity_ids = Some(entity_ids);
935            // One provenance record per entry, landing with the mem's
936            // commit.
937            let records: Vec<Provenance> = prepared
938                .iter()
939                .zip(notes.iter())
940                .filter(|(p, _)| p.mount_idx == m)
941                .map(|(p, note)| {
942                    self.provenance_record(
943                        ProvenanceKind::Relate,
944                        &p.from,
945                        actor,
946                        client,
947                        note.as_deref(),
948                    )
949                })
950                .collect();
951            match self.commit_or_complete(m, self.commit_staged(m, &subject, &ctx, &records)) {
952                Ok(landed) => {
953                    batch_warnings.extend(landed.warnings);
954                    mount_commits.push((m, landed.write_id));
955                }
956                Err(e) => {
957                    // A commit failed: roll back the store and any
958                    // still-pending backends. Mems already committed
959                    // in this loop stay committed (the family's
960                    // per-mem atomicity), so the view of each is
961                    // reloaded from storage.
962                    self.store = store_snapshot;
963                    self.discard_all_pending();
964                    let items: Vec<(usize, EntityId)> = prepared
965                        .iter()
966                        .map(|p| (p.mount_idx, p.from.clone()))
967                        .collect();
968                    return Err(self.batch_commit_failed(
969                        &distinct_mounts,
970                        &items,
971                        mount_commits,
972                        m,
973                        e,
974                    ));
975                }
976            }
977        }
978
979        // Self-write markers per mount.
980        for (m, write_id) in &mount_commits {
981            self.record_self_write(*m, write_id);
982            batch_warnings.extend(self.stamp_mutation_versions(*m));
983        }
984
985        // Orphan-stub GC over every removed edge's target — same
986        // scoped sweep and shared predicate as the single-item path.
987        let removed_targets: Vec<EntityId> = prepared
988            .iter()
989            .filter(|p| matches!(p.action, RelateAction::Removed))
990            .map(|p| p.to.clone())
991            .collect();
992        let orphan_stubs_removed =
993            super::gc_orphan_stubs_among(&mut self.store, removed_targets.iter());
994
995        self.invalidate_communities();
996        self.invalidate_search_indexes();
997
998        let write_id = mount_commits
999            .last()
1000            .map(|(_, s)| s.clone())
1001            .unwrap_or_default();
1002        Ok(super::batch_receipt(
1003            relate_actions(items),
1004            batch_warnings,
1005            orphan_stubs_removed,
1006            write_id,
1007        ))
1008    }
1009
1010    /// Positional-args alias for [`Self::relate_entity`]. Bundles
1011    /// the positional inputs into a [`RelateEntityArgs`] (with
1012    /// `expected_hash: None`) and delegates to
1013    /// [`Self::relate_entity`]. The `CommitContext` is destructured
1014    /// into the 4-tuple (actor, client, note) the unified mutation
1015    /// surface accepts.
1016    pub fn relate(
1017        &mut self,
1018        from: &EntityId,
1019        to: &EntityId,
1020        rel_type: &str,
1021        remove: bool,
1022        ctx: &CommitContext<'_>,
1023    ) -> Result<RelateEntityOutcome, EngineError> {
1024        let args = RelateEntityArgs {
1025            source: from.clone(),
1026            expected_hash: None,
1027            rel_type: rel_type.to_string(),
1028            target: to.clone(),
1029            remove,
1030            description: None,
1031            dry_run: false,
1032        };
1033        self.relate_entity(args, ctx.actor, ctx.client.as_ref(), ctx.note.as_deref())
1034    }
1035}
1036
1037mod compose;
1038#[cfg(test)]
1039mod derivation_tests;
1040mod resolve;
1041#[cfg(test)]
1042mod tests;
1043mod validate;