Skip to main content

memstead_base/engine/mutation/
proposal_merge.rs

1//! `Engine::proposal_merge`: apply a filled review brief onto the mem a
2//! fork was forked from; `Engine::proposal_list`: read the record the
3//! merge keeps.
4//!
5//! The merge re-renders the brief (so the picture it applies is the
6//! picture as it stands, never the file's copy), validates the
7//! disposition file against it (coverage, the closed vocabulary, the
8//! reasons, no `adopt` on a conflict, the pinned tips), reads the
9//! proposer of every adopted entity (the identity and the role) off the
10//! fork commit that last touched it, rehearses every adopted body
11//! through the target's write gate, and only then lands: one commit on
12//! the target branch per proposer identity (in slug order, each
13//! parent-pinned to the tip before it) carrying every adopted entity as
14//! the fork has it, under the proposer's identity and the role the fork
15//! commit of the group's first entity in slug order named, the record
16//! sidecar in the last of them (or, when every entry is rejected and
17//! there is no proposer to land under, one commit under the merger's
18//! identity carrying the record alone: a merge is a decision record
19//! before it is a content change); a second commit under the
20//! merger's identity with the owner's final bodies for
21//! `adopt_with_changes`; a verification check record per entity the
22//! merge created or updated, under the merger's identity; and a
23//! whole-store validation of the target read back from its backend. A
24//! refusal lands nothing: the store snapshot is restored and every
25//! pending buffer discarded, and when an earlier proposer's commit had
26//! already landed, the target branch is moved back to the tip the merge
27//! was pinned to (every commit above it was this merge's own). A gate
28//! refusal is the gate's own error wrapped per entity
29//! ([`EngineError::InEntity`]): the code stays the gate's, and
30//! `details.entity` and `details.stage` (`landing` for the fork's
31//! version, `amend` for the owner's body) say where it failed.
32//!
33//! Once the last commit is on the branch, nothing refuses any more: a
34//! failure of the bookkeeping after it (a check record the ledger
35//! refused, the re-read of the target, the validation reading, the tip
36//! read back) is a warning on the outcome, and the merge is reported as
37//! landed, because it is. An error from this function therefore always
38//! means a refusal that landed nothing.
39//!
40//! Nothing is written to the fork.
41
42use std::collections::{BTreeMap, BTreeSet, HashSet};
43use std::path::Path;
44
45use crate::check::{CheckKind, Verdict};
46use crate::engine::history::filter_notes_for_entity;
47use crate::engine::proposal::{LandingWrite, normalise_to, parse_body, resolve_sha};
48use crate::engine::{Engine, EngineError};
49use crate::engine_fallback_type;
50use crate::entity::parser::parse_markdown;
51use crate::entity::store_builder::push_entities_into_store;
52use crate::entity::{Entity, EntityId};
53use crate::ops::proposal::{
54    DISPOSITION_ADOPT, DISPOSITION_ADOPT_WITH_CHANGES, DISPOSITION_REJECT, DISPOSITION_VOCABULARY,
55    DispositionBody, MergeCommit, MergeValidation, MergeWarning, MergedEntity,
56    PROPOSAL_RECORD_PATH, ProposalBrief, ProposalChange, ProposalEntry, ProposalMergeOutcome,
57    ProposalRecord, ProposalRecordEntry, RecordedDisposition,
58};
59use crate::vcs::{Actor, ClientId, CommitContext, ProposalTrailers, Role};
60use crate::workspace::{MountCapability, MountStorage};
61
62use super::create::{CreatePrepareOutcome, PreparedCreate};
63use super::update::{PrepareOutcome, PreparedUpdate};
64use super::{
65    deferred_verified_stub_kind, gc_orphan_stubs, make_stub, stage_anchors_removal,
66    stage_anchors_replace,
67};
68
69/// The tool name on the merge commits' `Tool:` trailer.
70const MERGE_TOOL: &str = "proposal_merge";
71
72/// `details.stage` of a gate refusal met while landing the fork's
73/// version of an entity.
74const STAGE_LANDING: &str = "landing";
75/// `details.stage` of a gate refusal met while amending a landed entity
76/// with the owner's final body.
77const STAGE_AMEND: &str = "amend";
78
79/// One write the merge lands for an adopted entity.
80enum Landing {
81    Create(PreparedCreate),
82    Update(PreparedUpdate),
83    /// A deletion in the target: the id, its file path, and the
84    /// read-only referrers that demote it to a residual stub.
85    Delete {
86        id: EntityId,
87        file_path: String,
88        readonly_referrers: Vec<EntityId>,
89    },
90}
91
92impl Landing {
93    fn id(&self) -> &EntityId {
94        match self {
95            Landing::Create(p) => &p.id,
96            Landing::Update(p) => &p.id,
97            Landing::Delete { id, .. } => id,
98        }
99    }
100
101    fn is_create(&self) -> bool {
102        matches!(self, Landing::Create(_))
103    }
104}
105
106/// One adopted entry's plan: the slug, its proposer (the identity and
107/// the role off the fork commit that last touched it), and the writes.
108struct Adopted {
109    slug: String,
110    proposer: String,
111    /// The role the proposer's fork commit named; `Unspecified` when it
112    /// carried no `Role:` trailer.
113    role: Role,
114    landings: Vec<Landing>,
115    /// The owner's final body, for `adopt_with_changes`.
116    amend: Option<DispositionBody>,
117    /// The target id the fork renamed this entry from, when the merge
118    /// lands that rename.
119    renamed_from: Option<String>,
120}
121
122impl Engine {
123    /// The origin marks for a body the merge has just landed in `target`:
124    /// one prepared hash per load-bearing section the landed entity
125    /// carries. `None` when the slug holds no real entity (a stub) or the
126    /// landed body has no non-empty load-bearing section, so the record
127    /// carries no mark and the entity inherits its mem's class.
128    ///
129    /// Per section, and the prepared form rather than the file hash, so the
130    /// marks survive the owner's bookkeeping edits, a repin and a retype,
131    /// and expire per claim-carrying section; see
132    /// [`crate::ops::proposal::RecordedDisposition::landed_sections`]. The
133    /// read path compares with the same primitive
134    /// ([`crate::preparation::entity_section_prepared_hash`]), so the two
135    /// sides cannot drift into computing different things.
136    fn landed_section_marks(
137        &self,
138        target: &str,
139        slug: &str,
140    ) -> Option<std::collections::BTreeMap<String, String>> {
141        let id = EntityId::new(target, slug);
142        let entity = self.store.get(&id).filter(|e| !e.stub)?;
143        let type_def = self
144            .schema_for(target)
145            .and_then(|schema| schema.get_type(&entity.entity_type));
146        let marks =
147            crate::preparation::entity_load_bearing_section_marks(entity, type_def.as_deref());
148        (!marks.is_empty()).then_some(marks)
149    }
150
151    /// Apply `file` (the brief's JSON with `dispositions` filled) onto
152    /// the mem `fork` was forked from. The merger is the session's
153    /// identity ([`Engine::set_identity`]) and is required. The file's
154    /// `description` (trimmed; blank is absent) is recorded on the
155    /// proposal record's entry as the proposal in the owner's words;
156    /// when the file carries none, `note` stands in.
157    ///
158    /// Refusals, each landing nothing: `INVALID_INPUT` (no merger
159    /// identity; the file names another fork; a value outside the
160    /// vocabulary; a missing reason or body; `adopt_with_changes` on a
161    /// deletion), `PROPOSAL_DISPOSITIONS_INCOMPLETE`, `PROPOSAL_CONFLICT`,
162    /// `PROPOSAL_STALE` (a pinned tip moved), `PROPOSAL_UNATTRIBUTED`
163    /// (an adopted entity's last fork commit carries no identity), the
164    /// write gate's own code for a body it refuses (with
165    /// `details.entity` naming the slug and `details.stage` saying
166    /// `landing` or `amend`), `HAS_INCOMING_REFS` for a deletion the
167    /// target's referrers block, `UNKNOWN_MEM`, `READ_ONLY_MOUNT`, and
168    /// the brief's refusals. Once the last commit is on the branch a
169    /// failure is a warning on the outcome, never an error.
170    pub fn proposal_merge(
171        &mut self,
172        fork: &str,
173        file: &ProposalBrief,
174        actor: Actor,
175        client: Option<&ClientId>,
176        note: Option<&str>,
177    ) -> Result<ProposalMergeOutcome, EngineError> {
178        let Some(merger) = self.current_identity().map(str::to_string) else {
179            return Err(EngineError::InvalidInput(
180                "a proposal merge records the merger's identity beside the proposer's, and \
181                 the session declares none: pass `--identity <merger>`"
182                    .to_string(),
183            ));
184        };
185        if file.fork != fork {
186            return Err(EngineError::InvalidInput(format!(
187                "the disposition file was rendered for fork '{}', not '{fork}'",
188                file.fork
189            )));
190        }
191
192        // A merge commits to the target mem, and a deletion it carries
193        // is guarded by the referrers in every mem. So it holds every
194        // writable mem's write lock, and takes its picture under it: a
195        // write that locked the target, reloaded and passed its hash
196        // compare has committed before the merge reads the target's
197        // tip, and the merge cannot land between that write's compare
198        // and its commit.
199        let (_write_lock, _reloaded) = self.lock_workspace_for_write_if(true)?;
200
201        // ---- The picture as it stands, and the file against it ----
202        let brief = self.proposal_brief(fork)?;
203        let target = brief.target.clone();
204        let (gitdir, fork_branch) = match &self.find_mount(fork)?.mount.storage {
205            MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
206            _ => unreachable!("the brief refused a fork that is not git-backed"),
207        };
208        let target_mount = self
209            .mounts
210            .iter()
211            .position(|m| m.mount.mem == target)
212            .ok_or_else(|| self.unknown_mem_error(&target))?;
213        if self.mounts[target_mount].mount.capability != MountCapability::Write {
214            return Err(EngineError::ReadOnlyMount(target.clone()));
215        }
216        for (side, recorded, current) in [
217            ("target", &file.target_tip, &brief.target_tip),
218            ("fork", &file.fork_tip, &brief.fork_tip),
219            ("base", &file.base, &brief.base),
220        ] {
221            if recorded != current {
222                return Err(EngineError::ProposalStale {
223                    fork: fork.to_string(),
224                    side: side.to_string(),
225                    recorded: recorded.clone(),
226                    current: current.clone(),
227                });
228            }
229        }
230        let listed: BTreeSet<&str> = brief.entries.iter().map(|e| e.slug.as_str()).collect();
231        let filed: BTreeSet<&str> = file.dispositions.keys().map(String::as_str).collect();
232        let missing: Vec<String> = listed.difference(&filed).map(|s| s.to_string()).collect();
233        let unexpected: Vec<String> = filed.difference(&listed).map(|s| s.to_string()).collect();
234        if !missing.is_empty() || !unexpected.is_empty() {
235            return Err(EngineError::ProposalDispositionsIncomplete {
236                fork: fork.to_string(),
237                missing,
238                unexpected,
239            });
240        }
241
242        // ---- Every slot, in slug order ----
243        struct Slot<'a> {
244            entry: &'a ProposalEntry,
245            disposition: &'a str,
246            reason: Option<String>,
247            body: Option<DispositionBody>,
248        }
249        let mut slots: Vec<Slot<'_>> = Vec::with_capacity(brief.entries.len());
250        for entry in &brief.entries {
251            let slot = &file.dispositions[&entry.slug];
252            let disposition = slot.disposition.trim();
253            if !DISPOSITION_VOCABULARY.contains(&disposition) {
254                return Err(EngineError::InvalidInput(format!(
255                    "dispositions.{}.disposition is '{}': the vocabulary is {}",
256                    entry.slug,
257                    slot.disposition,
258                    DISPOSITION_VOCABULARY.join(", ")
259                )));
260            }
261            let disposition = DISPOSITION_VOCABULARY
262                .iter()
263                .find(|v| **v == disposition)
264                .copied()
265                .expect("checked above");
266            let reason = crate::vcs::normalise_identity(Some(&slot.reason));
267            if matches!(
268                disposition,
269                DISPOSITION_REJECT | DISPOSITION_ADOPT_WITH_CHANGES
270            ) && reason.is_none()
271            {
272                return Err(EngineError::InvalidInput(format!(
273                    "dispositions.{}.reason is empty: `{disposition}` needs a reason",
274                    entry.slug
275                )));
276            }
277            if disposition == DISPOSITION_ADOPT
278                && let Some(c) = &entry.conflict
279            {
280                return Err(EngineError::ProposalConflict {
281                    fork: fork.to_string(),
282                    slug: entry.slug.clone(),
283                    kind: c.kind.as_wire().to_string(),
284                });
285            }
286            let body = if disposition == DISPOSITION_ADOPT_WITH_CHANGES {
287                if entry.status == ProposalChange::Deleted {
288                    return Err(EngineError::InvalidInput(format!(
289                        "dispositions.{}: the fork's version is a deletion, which takes no \
290                         final body; `adopt` it or `reject` it",
291                        entry.slug
292                    )));
293                }
294                let Some(raw) = &slot.body else {
295                    return Err(EngineError::InvalidInput(format!(
296                        "dispositions.{}.body is absent: `adopt_with_changes` carries the \
297                         owner's final body (`sections`, `metadata`, optional `title` and \
298                         `relations`)",
299                        entry.slug
300                    )));
301                };
302                let body: DispositionBody = serde_json::from_value(raw.clone()).map_err(|e| {
303                    EngineError::InvalidInput(format!(
304                        "dispositions.{}.body does not parse as a body (`sections`, \
305                             `metadata`, optional `title` and `relations`): {e}",
306                        entry.slug
307                    ))
308                })?;
309                if body.sections.is_empty() {
310                    return Err(EngineError::InvalidInput(format!(
311                        "dispositions.{}.body.sections is empty: the final body carries at \
312                         least one section",
313                        entry.slug
314                    )));
315                }
316                Some(body)
317            } else {
318                None
319            };
320            slots.push(Slot {
321                entry,
322                disposition,
323                reason,
324                body,
325            });
326        }
327
328        // ---- The proposer of every adopted entity, off the fork's commits ----
329        let notes = {
330            let Some(hook) = self.git_branch_ops.as_ref() else {
331                return Err(EngineError::InvalidInput(
332                    "a proposal merge needs the git-branch ops bundle (full boot only)".to_string(),
333                ));
334            };
335            (hook.changes_since)(
336                &gitdir,
337                &fork_branch,
338                fork,
339                crate::ops::EMPTY_TREE_SHA,
340                crate::ops::RENAME_SIMILARITY_DEFAULT,
341            )
342            .map_err(EngineError::Backend)?
343            .notes
344        };
345        // Per slug: the proposer's identity and the role the same
346        // commit named (absence recorded as `Unspecified`). An adopted
347        // entity must be attributed, because its landing commit carries
348        // that identity; a rejected one is attributed where the fork's
349        // commits allow it, so the record still names who proposed, and
350        // is silently unattributed otherwise (nothing lands under it).
351        let mut proposers: BTreeMap<String, (String, Role)> = BTreeMap::new();
352        // Per slug: every identity that wrote the entity on the fork. The
353        // landing commit is attributed to the proposer; the others ride it
354        // as `Co-Writer:` trailers, so independence counts them as writers.
355        // `None` stands for a fork write without an identity. A fork that
356        // itself merged a proposal carries that merge's co-writers and
357        // unattributed writes in its trailers; they travel on.
358        let mut fork_writers: BTreeMap<String, Vec<Option<String>>> = BTreeMap::new();
359        for slot in &slots {
360            let fork_id = EntityId::new(fork, &slot.entry.slug);
361            let mut writers: Vec<Option<String>> = Vec::new();
362            let mut add = |w: Option<String>| {
363                if !writers.contains(&w) {
364                    writers.push(w);
365                }
366            };
367            for t in filter_notes_for_entity(fork_id.as_ref(), &notes) {
368                add(t.identity.clone());
369            }
370            // Every id the entity had on the fork, along its renames, so a
371            // co-writer an earlier merge recorded under an older id travels.
372            let mut aliases: Vec<String> = vec![fork_id.to_string()];
373            loop {
374                let before = aliases.len();
375                for n in &notes {
376                    // A rename commit, or a merge that landed one.
377                    let pairs = n
378                        .entity_id
379                        .iter()
380                        .chain(n.merge_renames.iter())
381                        .filter_map(|f| crate::engine::history::parse_rename_pair(f));
382                    for (old_id, new_id) in pairs {
383                        if aliases.contains(&new_id) && !aliases.contains(&old_id) {
384                            aliases.push(old_id);
385                        }
386                    }
387                }
388                if aliases.len() == before {
389                    break;
390                }
391            }
392            for n in &notes {
393                for (id, who) in &n.co_writers {
394                    if aliases.contains(id) {
395                        add(Some(who.clone()));
396                    }
397                }
398                if n.unattributed_writes.iter().any(|id| aliases.contains(id)) {
399                    add(None);
400                }
401            }
402            fork_writers.insert(slot.entry.slug.clone(), writers);
403            let touch = filter_notes_for_entity(fork_id.as_ref(), &notes)
404                .into_iter()
405                .next();
406            match touch.as_ref().and_then(|t| t.identity.clone()) {
407                Some(identity) => {
408                    let role = touch
409                        .as_ref()
410                        .and_then(|t| t.role.as_deref())
411                        .and_then(Role::from_wire)
412                        .unwrap_or_default();
413                    proposers.insert(slot.entry.slug.clone(), (identity, role));
414                }
415                None if slot.disposition == DISPOSITION_REJECT => {}
416                None => {
417                    return Err(EngineError::ProposalUnattributed {
418                        fork: fork.to_string(),
419                        slug: slot.entry.slug.clone(),
420                        sha: touch
421                            .map(|t| t.reference)
422                            .unwrap_or_else(|| "(no engine-recorded commit)".to_string()),
423                    });
424                }
425            }
426        }
427
428        // ---- The validation baseline, before anything moves ----
429        let findings_before = self.merge_findings(&target)?;
430        let load_errors_before = self.load_errors().len();
431
432        // ---- Rehearse every adopted write through the gate ----
433        let store_snapshot = self.store.clone();
434        let target_schema = self.schema_for(&target);
435        let mut adopted: Vec<Adopted> = Vec::new();
436        let mut noops: Vec<String> = Vec::new();
437        // The fork's version of every adopted entity under the target's
438        // name, parsed under the target's schema.
439        let mut versions: BTreeMap<String, Entity> = BTreeMap::new();
440        for slot in slots
441            .iter()
442            .filter(|s| s.disposition != DISPOSITION_REJECT)
443            .filter(|s| s.entry.status != ProposalChange::Deleted)
444        {
445            let slug = slot.entry.slug.as_str();
446            let target_id = EntityId::new(&target, slug);
447            let landing = slot
448                .entry
449                .fork_body
450                .as_deref()
451                .map(|b| normalise_to(b, fork, &target))
452                .and_then(|b| {
453                    parse_body(
454                        &b,
455                        &crate::entity::id::id_to_file_path(&target_id),
456                        &target,
457                        target_schema.as_deref(),
458                    )
459                })
460                .ok_or_else(|| {
461                    EngineError::InvalidInput(format!(
462                        "the fork's body of '{slug}' does not parse under the target's schema \
463                         (the brief's precheck names the failure); reject it, or repair it on \
464                         the fork"
465                    ))
466                })?;
467            versions.insert(slug.to_string(), landing);
468        }
469        // ---- An adopted entity that links a rejected one of the same file ----
470        // The gate would auto-stub the missing target and the merge would
471        // report success over a dangling edge (the target then read
472        // `UNRESOLVED_STUB` under `health --strict`). The file itself cut
473        // the link, so the file is where it refuses.
474        let rejected: BTreeSet<&str> = slots
475            .iter()
476            .filter(|s| s.disposition == DISPOSITION_REJECT)
477            .map(|s| s.entry.slug.as_str())
478            .collect();
479        for slot in slots
480            .iter()
481            .filter(|s| s.disposition != DISPOSITION_REJECT)
482            .filter(|s| s.entry.status != ProposalChange::Deleted)
483        {
484            let slug = slot.entry.slug.as_str();
485            // An owner's body with `relations` replaces the landed rows;
486            // otherwise the fork's rows land, body-link aliases included.
487            let edges: Vec<(String, EntityId)> =
488                match slot.body.as_ref().and_then(|b| b.relations.as_ref()) {
489                    Some(relations) => relations
490                        .iter()
491                        .map(|r| (r.rel_type.clone(), EntityId::canonical(&r.target)))
492                        .collect(),
493                    None => versions[slug]
494                        .relationships
495                        .iter()
496                        .map(|r| (r.rel_type.clone(), r.target.clone()))
497                        .collect(),
498                };
499            for (rel_type, to) in edges {
500                if to.mem() == target && rejected.contains(to.path()) && !self.target_holds(&to) {
501                    return Err(EngineError::ProposalLinksRejected {
502                        fork: fork.to_string(),
503                        slug: slug.to_string(),
504                        rel_type,
505                        target: to.path().to_string(),
506                    });
507                }
508            }
509        }
510        // Every entity the merge creates is staged as a typed skeleton
511        // first, so a sibling's edge to it validates against a real
512        // target (the batch create's rule).
513        let creates: HashSet<EntityId> = versions
514            .keys()
515            .map(|slug| EntityId::new(&target, slug))
516            .filter(|id| !self.target_holds(id))
517            .collect();
518        for id in &creates {
519            let landing = &versions[id.path()];
520            let mut skeleton = make_stub(id, crate::entity::StubKind::ForwardReference);
521            skeleton.stub = false;
522            skeleton.stub_kind = None;
523            skeleton.entity_type = landing.entity_type.clone();
524            skeleton.title = landing.title.clone();
525            self.store.upsert(id.clone(), skeleton);
526        }
527        let deletions: HashSet<EntityId> = slots
528            .iter()
529            .filter(|s| s.disposition == DISPOSITION_ADOPT)
530            .filter_map(|s| match s.entry.status {
531                ProposalChange::Deleted => Some(EntityId::new(&target, &s.entry.slug)),
532                ProposalChange::Renamed => s
533                    .entry
534                    .renamed_from
535                    .as_deref()
536                    .map(|from| EntityId::new(&target, from)),
537                _ => None,
538            })
539            .collect();
540        let prepared: Result<(), EngineError> = (|| {
541            for slot in slots.iter().filter(|s| s.disposition != DISPOSITION_REJECT) {
542                let slug = slot.entry.slug.as_str();
543                let target_id = EntityId::new(&target, slug);
544                let mut landings: Vec<Landing> = Vec::new();
545                match slot.entry.status {
546                    ProposalChange::Deleted => {
547                        if let Some(l) = self.plan_delete(&target_id, &deletions)? {
548                            landings.push(l);
549                        } else {
550                            noops.push(slug.to_string());
551                        }
552                    }
553                    _ => {
554                        let landing = &versions[slug];
555                        // An amended entry is judged once, by the merge's net
556                        // effect, after its amend is prepared.
557                        self.defer_transition_gates = slot.body.is_some();
558                        let planned = self.plan_landing(&target_id, landing, &creates);
559                        self.defer_transition_gates = false;
560                        match planned? {
561                            Some(l) => landings.push(l),
562                            None => noops.push(slug.to_string()),
563                        }
564                        if slot.entry.status == ProposalChange::Renamed
565                            && let Some(from) = slot.entry.renamed_from.as_deref()
566                            && let Some(l) =
567                                self.plan_delete(&EntityId::new(&target, from), &deletions)?
568                        {
569                            landings.push(l);
570                        }
571                    }
572                }
573                let (proposer, role) = proposers[slug].clone();
574                adopted.push(Adopted {
575                    slug: slug.to_string(),
576                    proposer,
577                    role,
578                    landings,
579                    amend: slot.body.clone(),
580                    renamed_from: (slot.entry.status == ProposalChange::Renamed)
581                        .then_some(slot.entry.renamed_from.as_deref())
582                        .flatten()
583                        .map(|from| EntityId::new(&target, from).to_string()),
584                });
585            }
586            Ok(())
587        })();
588        if let Err(e) = prepared {
589            self.store = store_snapshot;
590            self.discard_all_pending();
591            return Err(e);
592        }
593
594        // ---- The store as it will be, so a deletion's referrers are judged
595        //      against the adopted bodies, not the pre-merge ones ----
596        let applied: Result<(), EngineError> = (|| {
597            let fallback = engine_fallback_type();
598            for a in &adopted {
599                for l in &a.landings {
600                    match l {
601                        Landing::Create(p) => {
602                            let parsed = parse_markdown(
603                                &p.markdown,
604                                &p.file_path,
605                                p.type_def.as_ref(),
606                                &p.mem,
607                            )
608                            .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
609                            push_entities_into_store(
610                                &mut self.store,
611                                vec![parsed],
612                                fallback.as_ref(),
613                                None,
614                            );
615                        }
616                        Landing::Update(p) => {
617                            self.apply_prepared_to_store(p)?;
618                        }
619                        Landing::Delete { .. } => {}
620                    }
621                }
622            }
623            crate::entity::store_builder::remap_alias_target_edge_sources(
624                &mut self.store,
625                &self.schemas,
626            );
627            for a in &adopted {
628                for l in &a.landings {
629                    if let Landing::Delete { id, .. } = l {
630                        let referrers = self.classify_delete_referrers(id);
631                        let blocking: Vec<_> = referrers
632                            .write_referrers
633                            .into_iter()
634                            .filter(|r| !deletions.contains(&EntityId(r.from_id.clone())))
635                            .collect();
636                        if !blocking.is_empty() {
637                            return Err(EngineError::HasIncomingRefs {
638                                id: id.to_string(),
639                                referrers: blocking,
640                            });
641                        }
642                    }
643                }
644            }
645            Ok(())
646        })();
647        if let Err(e) = applied {
648            self.store = store_snapshot;
649            self.discard_all_pending();
650            return Err(e);
651        }
652
653        // ---- The owner's final bodies, rehearsed now against the landed
654        //      versions the store holds, so a body the gate refuses lands
655        //      nothing; staged and committed after the merge commits ----
656        let amends: Result<Vec<PreparedUpdate>, EngineError> = (|| {
657            let mut prepared: Vec<PreparedUpdate> = Vec::new();
658            for a in &adopted {
659                if let Some(body) = &a.amend {
660                    self.defer_transition_gates = true;
661                    let planned = self.plan_amend(&EntityId::new(&target, &a.slug), body);
662                    self.defer_transition_gates = false;
663                    if let Some(p) = planned? {
664                        prepared.push(p);
665                    }
666                }
667            }
668            Ok(prepared)
669        })();
670        let amends = match amends {
671            Ok(p) => p,
672            Err(e) => {
673                self.store = store_snapshot;
674                self.discard_all_pending();
675                return Err(e);
676            }
677        };
678        let mut net_carries: Vec<(EntityId, Vec<String>, String, String)> = Vec::new();
679        // A merge is one write of each adopted entity: an amend that lands
680        // beside an adopted status change is judged against the entity as
681        // it stood before the merge, so the merge cannot reach a gated
682        // value on text no record names (the landing entered the value, the
683        // amend then changes the content).
684        // The writes judged by their net effect: each amend, and the landing
685        // of an amended entry whose amend prepared to nothing (the landed
686        // version already equals it).
687        struct NetWrite {
688            id: EntityId,
689            markdown: String,
690            file_path: String,
691            type_def: std::sync::Arc<memstead_schema::TypeDefinition>,
692            mem: String,
693        }
694        let mut net_writes: Vec<NetWrite> = amends
695            .iter()
696            .map(|p| NetWrite {
697                id: p.id.clone(),
698                markdown: p.markdown.clone(),
699                file_path: p.file_path.clone(),
700                type_def: p.type_def.clone(),
701                mem: p.mem.clone(),
702            })
703            .collect();
704        for a in adopted.iter().filter(|a| a.amend.is_some()) {
705            let id = EntityId::new(&target, &a.slug);
706            if amends.iter().any(|p| p.id == id) {
707                continue;
708            }
709            for l in &a.landings {
710                match l {
711                    Landing::Update(p) => net_writes.push(NetWrite {
712                        id: p.id.clone(),
713                        markdown: p.markdown.clone(),
714                        file_path: p.file_path.clone(),
715                        type_def: p.type_def.clone(),
716                        mem: p.mem.clone(),
717                    }),
718                    Landing::Create(p) => net_writes.push(NetWrite {
719                        id: p.id.clone(),
720                        markdown: p.markdown.clone(),
721                        file_path: p.file_path.clone(),
722                        type_def: p.type_def.clone(),
723                        mem: p.mem.clone(),
724                    }),
725                    Landing::Delete { .. } => {}
726                }
727            }
728        }
729        for p in &net_writes {
730            let next = match parse_markdown(&p.markdown, &p.file_path, p.type_def.as_ref(), &p.mem)
731            {
732                Ok(parsed) => parsed.entity,
733                Err(e) => {
734                    self.store = store_snapshot;
735                    self.discard_all_pending();
736                    return Err(EngineError::ParseAfterWrite(e.to_string()));
737                }
738            };
739            let before = store_snapshot.get(&p.id).cloned();
740            let before_def = before.as_ref().and_then(|b| {
741                self.schemas
742                    .get(&p.mem)
743                    .and_then(|schema| schema.get_type(&b.entity_type))
744            });
745            let pre = match (&before, &before_def) {
746                (Some(b), Some(d)) => Some((b, d.as_ref())),
747                _ => None,
748            };
749            let post_hash = crate::entity::parser::compute_hash(&p.markdown);
750            let (violated, carry_kinds) =
751                self.gate_transition_forms(pre, &next, &post_hash, p.type_def.as_ref(), Vec::new());
752            if let Some(b) = &before
753                && !carry_kinds.is_empty()
754            {
755                net_carries.push((p.id.clone(), carry_kinds, b.content_hash.clone(), post_hash));
756            }
757            let blocked: Vec<_> = violated
758                .into_iter()
759                .filter(|v| v.severity() == memstead_schema::ConstraintSeverity::Block)
760                .collect();
761            if !blocked.is_empty() {
762                self.store = store_snapshot;
763                self.discard_all_pending();
764                return Err(EngineError::ConstraintUnsatisfied {
765                    entity_type: next.entity_type.clone(),
766                    entity_id: p.id.to_string(),
767                    violations: blocked,
768                });
769            }
770        }
771        // The checks form of every entity the merge writes, read over the
772        // store as the whole merge leaves it (landings applied, amends on
773        // top): a merge that edits a checked criterion and closes its plan
774        // is the same pair of writes refused one after the other.
775        {
776            let mut written: BTreeMap<
777                String,
778                (Entity, std::sync::Arc<memstead_schema::TypeDefinition>),
779            > = BTreeMap::new();
780            let parse = |md: &str,
781                         fp: &str,
782                         td: &std::sync::Arc<memstead_schema::TypeDefinition>,
783                         mem: &str| {
784                parse_markdown(md, fp, td.as_ref(), mem)
785                    .map(|parsed| (parsed.entity, td.clone()))
786                    .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))
787            };
788            let mut collected: Result<(), EngineError> = Ok(());
789            for a in &adopted {
790                for l in &a.landings {
791                    let one = match l {
792                        Landing::Update(p) => {
793                            Some(parse(&p.markdown, &p.file_path, &p.type_def, &p.mem))
794                        }
795                        Landing::Create(p) => {
796                            Some(parse(&p.markdown, &p.file_path, &p.type_def, &p.mem))
797                        }
798                        Landing::Delete { .. } => None,
799                    };
800                    match one {
801                        Some(Ok((e, td))) => {
802                            written.insert(e.id.0.clone(), (e, td));
803                        }
804                        Some(Err(e)) => collected = Err(e),
805                        None => {}
806                    }
807                }
808            }
809            for p in &amends {
810                match parse(&p.markdown, &p.file_path, &p.type_def, &p.mem) {
811                    Ok((e, td)) => {
812                        written.insert(e.id.0.clone(), (e, td));
813                    }
814                    Err(e) => collected = Err(e),
815                }
816            }
817            if let Err(e) = collected {
818                self.store = store_snapshot;
819                self.discard_all_pending();
820                return Err(e);
821            }
822            let mut post = self.store.clone();
823            for (e, _) in written.values() {
824                post.upsert(e.id.clone(), e.clone());
825            }
826            let writes: Vec<_> = written.into_values().collect();
827            if let Some((entity, blocked)) = self
828                .checks_form_after(&post, &store_snapshot, &writes)
829                .into_iter()
830                .next()
831            {
832                self.store = store_snapshot;
833                self.discard_all_pending();
834                return Err(EngineError::ConstraintUnsatisfied {
835                    entity_type: entity.entity_type.clone(),
836                    entity_id: entity.id.to_string(),
837                    violations: blocked,
838                });
839            }
840        }
841        // An adopted update that passed a self-check transition on the
842        // stored content's record carries that record to the landed bytes,
843        // as the single and batch update paths do: after every gate of the
844        // merge passed, before anything lands.
845        for a in &adopted {
846            for l in &a.landings {
847                if let Landing::Update(p) = l
848                    && let Err(e) = self.carry_prepared_self_checks(p)
849                {
850                    self.store = store_snapshot;
851                    self.discard_all_pending();
852                    return Err(e);
853                }
854            }
855        }
856        for (id, kinds, pre, post) in &net_carries {
857            if let Err(e) = self.carry_checks_across_transition(id, kinds, pre, post) {
858                self.store = store_snapshot;
859                self.discard_all_pending();
860                return Err(e);
861            }
862        }
863        for p in &amends {
864            if let Err(e) = self.carry_prepared_self_checks(p) {
865                self.store = store_snapshot;
866                self.discard_all_pending();
867                return Err(e);
868            }
869        }
870
871        // ---- The record ----
872        // The proposal in the owner's words: the file's slot, trimmed,
873        // else the merge's note; the file wins when both are given.
874        let description = crate::vcs::normalise_identity(Some(&file.description))
875            .or_else(|| crate::vcs::normalise_identity(note));
876        // The store holds the planned landings from here on: a refusal
877        // puts it back as it was, as every refusal above does.
878        let mut record = match self.read_proposal_record(&target) {
879            Ok(record) => record.unwrap_or_default(),
880            Err(e) => {
881                self.discard_all_pending();
882                self.store = store_snapshot;
883                return Err(e);
884            }
885        };
886        // The identities the merge commits land under: one per adopted
887        // proposer, in slug order.
888        let mut distinct_proposers: Vec<String> = Vec::new();
889        for a in &adopted {
890            if !distinct_proposers.contains(&a.proposer) {
891                distinct_proposers.push(a.proposer.clone());
892            }
893        }
894        // The identities the record names as the proposal's: every
895        // attributed entry, adopted or rejected, in slug order.
896        let mut recorded_proposers: Vec<String> = Vec::new();
897        for slot in &slots {
898            if let Some((identity, _)) = proposers.get(&slot.entry.slug)
899                && !recorded_proposers.contains(identity)
900            {
901                recorded_proposers.push(identity.clone());
902            }
903        }
904        record.proposals.push(ProposalRecordEntry {
905            id: brief.proposal_id.clone(),
906            proposer: (!recorded_proposers.is_empty()).then(|| recorded_proposers.join(", ")),
907            ancestor: brief.ancestor.clone(),
908            base: brief.base.clone(),
909            target_tip: brief.target_tip.clone(),
910            merged_by: Some(merger.clone()),
911            at: self.now_iso(),
912            description,
913            entities: slots
914                .iter()
915                .map(|s| {
916                    (s.entry.slug.clone(), {
917                        // The adopt-time origin decision. An `adopt`
918                        // lands the proposer's bytes verbatim (the
919                        // landing commit carries the proposer's
920                        // identity), so the entity's claim-carrying
921                        // sections are a stranger's until the owner
922                        // rewrites them; an `adopt_with_changes` lands
923                        // the owner's own body in the amend commit and
924                        // is first-party, so it records no mark. The
925                        // store already holds the landed body here
926                        // (`apply_prepared_to_store` ran above), and
927                        // the hash is a pure function of those bytes,
928                        // so the value matches what the re-read serves.
929                        // Only where the adoption actually LANDS a body.
930                        // A fork's deletion is an `adopt` too, and the
931                        // store still holds the owner's pre-delete
932                        // entity at this point, so marking on the
933                        // disposition alone would stamp the owner's own
934                        // body as a stranger's.
935                        let lands_a_body = adopted
936                            .iter()
937                            .find(|a| a.slug == s.entry.slug)
938                            .is_some_and(|a| {
939                                a.landings.iter().any(|l| {
940                                    !matches!(l, Landing::Delete { .. })
941                                        && l.id() == &EntityId::new(&target, &s.entry.slug)
942                                })
943                            });
944                        let landed_sections = (s.disposition == DISPOSITION_ADOPT && lands_a_body)
945                            .then(|| self.landed_section_marks(&target, &s.entry.slug))
946                            .flatten();
947                        RecordedDisposition {
948                            disposition: s.disposition.to_string(),
949                            reason: s.reason.clone(),
950                            content_hash: s.entry.content_hash.clone(),
951                            landed_sections,
952                        }
953                    })
954                })
955                .collect(),
956        });
957        let record_bytes = record.to_bytes();
958
959        // ---- Land: one commit per proposer identity, in slug order ----
960        let mut merge_commits: Vec<MergeCommit> = Vec::new();
961        // Follow-up steps of a landed commit that failed; reported, never
962        // turned into a failed merge.
963        let mut follow_ups: Vec<crate::ops::WarningHint> = Vec::new();
964        let mut parent = brief.target_tip.clone();
965        let mut landed_any = false;
966        let mut created_ids: HashSet<EntityId> = HashSet::new();
967        let mut deleted_ids: Vec<(EntityId, Vec<EntityId>)> = Vec::new();
968        for (i, proposer) in distinct_proposers.iter().enumerate() {
969            let group: Vec<&Adopted> = adopted.iter().filter(|a| &a.proposer == proposer).collect();
970            let last_group = i + 1 == distinct_proposers.len();
971            let staged: Result<(Vec<String>, Vec<String>), EngineError> = (|| {
972                let backend = self.mounts[target_mount].backend.as_ref();
973                let mut ids: Vec<String> = Vec::new();
974                let mut created: Vec<String> = Vec::new();
975                for a in &group {
976                    for l in &a.landings {
977                        match l {
978                            Landing::Create(p) => {
979                                self.stage_prepared_create(p)?;
980                                let rows =
981                                    self.entity_anchors_for_write(&EntityId::new(fork, &a.slug))?;
982                                stage_anchors_replace(backend, &p.id, rows)?;
983                                created.push(p.id.to_string());
984                            }
985                            Landing::Update(p) => {
986                                self.stage_prepared_update(p)?;
987                                let rows =
988                                    self.entity_anchors_for_write(&EntityId::new(fork, &a.slug))?;
989                                stage_anchors_replace(backend, &p.id, rows)?;
990                            }
991                            Landing::Delete { id, file_path, .. } => {
992                                backend.delete_entity(Path::new(file_path))?;
993                                stage_anchors_removal(backend, id)?;
994                            }
995                        }
996                        ids.push(l.id().to_string());
997                    }
998                }
999                if last_group {
1000                    backend.write_entity(Path::new(PROPOSAL_RECORD_PATH), &record_bytes)?;
1001                }
1002                Ok((ids, created))
1003            })();
1004            let (ids, created) = match staged {
1005                Ok(v) => v,
1006                Err(e) if landed_any => {
1007                    let failed = group
1008                        .iter()
1009                        .flat_map(|a| a.landings.iter().map(|l| l.id().to_string()))
1010                        .collect();
1011                    return Err(self.merge_partial_failure(
1012                        &target,
1013                        &store_snapshot,
1014                        &merge_commits,
1015                        failed,
1016                        e,
1017                    ));
1018                }
1019                Err(e) => {
1020                    return Err(self.unwind_merge(
1021                        &target,
1022                        &brief.target_tip,
1023                        None,
1024                        &store_snapshot,
1025                        e,
1026                    ));
1027                }
1028            };
1029            // The proposer's role rides the merge commit beside the
1030            // identity: the role off the fork commit that last touched
1031            // the group's first entity in slug order (one commit per
1032            // proposer, so one role; a proposer who wrote under several
1033            // roles lands under the first slug's).
1034            let role = group.first().map(|a| a.role).unwrap_or_default();
1035            let mut ctx = CommitContext::new(
1036                Some(MERGE_TOOL),
1037                actor,
1038                client.cloned(),
1039                note.map(String::from),
1040                role,
1041                Some(proposer.clone()),
1042            );
1043            ctx.entity_ids = Some(ids.clone());
1044            let mut co_writers: Vec<(String, String)> = Vec::new();
1045            let mut unattributed: Vec<String> = Vec::new();
1046            for id in &ids {
1047                let slug = EntityId(id.clone()).path().to_string();
1048                for w in fork_writers.get(&slug).into_iter().flatten() {
1049                    match w {
1050                        Some(w) if w != proposer => co_writers.push((id.clone(), w.clone())),
1051                        Some(_) => {}
1052                        None => unattributed.push(id.clone()),
1053                    }
1054                }
1055            }
1056            ctx.proposal = Some(ProposalTrailers {
1057                proposal: brief.proposal_id.clone(),
1058                merged_by: merger.clone(),
1059                created: created.clone(),
1060                co_writers,
1061                unattributed,
1062                renamed: group
1063                    .iter()
1064                    .filter_map(|a| {
1065                        a.renamed_from
1066                            .clone()
1067                            .map(|old| (old, EntityId::new(&target, &a.slug).to_string()))
1068                    })
1069                    .collect(),
1070            });
1071            let subject = format!("memstead: proposal-merge {}", brief.proposal_id);
1072            let sha =
1073                match self.commit_staged_pinned(target_mount, &subject, &ctx, &[], Some(&parent)) {
1074                    Ok(landed) => {
1075                        follow_ups.extend(landed.warnings);
1076                        landed.write_id
1077                    }
1078                    Err(e) => {
1079                        let e = proposal_stale_or(e, fork);
1080                        if landed_any {
1081                            return Err(self.merge_partial_failure(
1082                                &target,
1083                                &store_snapshot,
1084                                &merge_commits,
1085                                ids,
1086                                e,
1087                            ));
1088                        }
1089                        return Err(self.unwind_merge(
1090                            &target,
1091                            &brief.target_tip,
1092                            None,
1093                            &store_snapshot,
1094                            e,
1095                        ));
1096                    }
1097                };
1098            landed_any = true;
1099            self.record_self_write(target_mount, &sha);
1100            for a in &group {
1101                for l in &a.landings {
1102                    match l {
1103                        Landing::Delete {
1104                            id,
1105                            readonly_referrers,
1106                            ..
1107                        } => deleted_ids.push((id.clone(), readonly_referrers.clone())),
1108                        l if l.is_create() => {
1109                            created_ids.insert(l.id().clone());
1110                        }
1111                        _ => {}
1112                    }
1113                }
1114            }
1115            parent = sha.clone();
1116            merge_commits.push(MergeCommit {
1117                sha,
1118                identity: proposer.clone(),
1119                entities: ids,
1120            });
1121        }
1122
1123        // ---- Nothing adopted: the record still lands ----
1124        // A merge is a decision record before it is a content change.
1125        // With every entry rejected there is no proposer to land under,
1126        // so one commit under the merger carries the record alone,
1127        // parent-pinned like the others: a refused proposal is as
1128        // visible on the target branch as an accepted one, the brief
1129        // marks a re-proposal of it, and a reader of the branch learns
1130        // the fork is disposed.
1131        if distinct_proposers.is_empty() {
1132            let staged: Result<(), EngineError> = (|| {
1133                let backend = self.mounts[target_mount].backend.as_ref();
1134                backend.write_entity(Path::new(PROPOSAL_RECORD_PATH), &record_bytes)?;
1135                Ok(())
1136            })();
1137            if let Err(e) = staged {
1138                return Err(self.unwind_merge(
1139                    &target,
1140                    &brief.target_tip,
1141                    None,
1142                    &store_snapshot,
1143                    e,
1144                ));
1145            }
1146            let mut ctx = self.commit_context(
1147                Some(MERGE_TOOL),
1148                actor,
1149                client.cloned(),
1150                note.map(String::from),
1151            );
1152            ctx.entity_ids = Some(Vec::new());
1153            ctx.proposal = Some(ProposalTrailers {
1154                proposal: brief.proposal_id.clone(),
1155                merged_by: merger.clone(),
1156                created: Vec::new(),
1157                co_writers: Vec::new(),
1158                unattributed: Vec::new(),
1159                renamed: Vec::new(),
1160            });
1161            let subject = format!("memstead: proposal-merge {}", brief.proposal_id);
1162            let sha =
1163                match self.commit_staged_pinned(target_mount, &subject, &ctx, &[], Some(&parent)) {
1164                    Ok(landed) => {
1165                        follow_ups.extend(landed.warnings);
1166                        landed.write_id
1167                    }
1168                    Err(e) => {
1169                        let e = proposal_stale_or(e, fork);
1170                        return Err(self.unwind_merge(
1171                            &target,
1172                            &brief.target_tip,
1173                            None,
1174                            &store_snapshot,
1175                            e,
1176                        ));
1177                    }
1178                };
1179            self.record_self_write(target_mount, &sha);
1180            parent = sha.clone();
1181            merge_commits.push(MergeCommit {
1182                sha,
1183                identity: merger.clone(),
1184                entities: Vec::new(),
1185            });
1186        }
1187
1188        // ---- The store after the commits: deletions, stubs, indexes ----
1189        for (id, readonly_referrers) in &deleted_ids {
1190            if readonly_referrers.is_empty() {
1191                self.store.remove(id);
1192            } else {
1193                self.store.remove_edges_from(id);
1194                self.store.upsert(
1195                    id.clone(),
1196                    make_stub(
1197                        id,
1198                        crate::entity::StubKind::Residual {
1199                            since_commit: parent.clone(),
1200                            readonly_referrers: readonly_referrers.clone(),
1201                        },
1202                    ),
1203                );
1204            }
1205        }
1206        let mut out_of_batch: Vec<(EntityId, crate::entity::StubKind)> = Vec::new();
1207        for a in &adopted {
1208            for l in &a.landings {
1209                if let Landing::Create(p) = l {
1210                    for t in &p.relation_targets {
1211                        if !self.store.contains(t) {
1212                            out_of_batch.push((t.clone(), deferred_verified_stub_kind(self, t)?));
1213                        }
1214                    }
1215                }
1216            }
1217        }
1218        for (t, kind) in out_of_batch {
1219            self.store.upsert(t.clone(), make_stub(&t, kind));
1220        }
1221        gc_orphan_stubs(&mut self.store);
1222        let _ = self.stamp_mutation_versions(target_mount);
1223        self.invalidate_communities();
1224        self.invalidate_search_indexes();
1225
1226        // ---- The owner's final bodies, one commit under the merger ----
1227        // From the last commit on, a failure is bookkeeping: it goes here
1228        // and the merge is reported as landed (see the module doc).
1229        let mut warnings: Vec<MergeWarning> = follow_ups
1230            .drain(..)
1231            .map(|h| MergeWarning::from_hint(&h))
1232            .collect();
1233        let mut amend_commit: Option<MergeCommit> = None;
1234        if !amends.is_empty() {
1235            let staged: Result<(), EngineError> = (|| {
1236                for p in &amends {
1237                    self.stage_prepared_update(p)?;
1238                }
1239                Ok(())
1240            })();
1241            let ids: Vec<String> = amends.iter().map(|p| p.id.to_string()).collect();
1242            if let Err(e) = staged {
1243                return Err(self.merge_partial_failure(
1244                    &target,
1245                    &store_snapshot,
1246                    &merge_commits,
1247                    ids,
1248                    e,
1249                ));
1250            }
1251            let mut ctx = self.commit_context(
1252                Some(MERGE_TOOL),
1253                actor,
1254                client.cloned(),
1255                note.map(String::from),
1256            );
1257            ctx.entity_ids = Some(ids.clone());
1258            ctx.proposal = Some(ProposalTrailers {
1259                proposal: brief.proposal_id.clone(),
1260                merged_by: merger.clone(),
1261                created: Vec::new(),
1262                co_writers: Vec::new(),
1263                unattributed: Vec::new(),
1264                renamed: Vec::new(),
1265            });
1266            let subject = format!("memstead: proposal-amend {}", brief.proposal_id);
1267            let sha =
1268                match self.commit_staged_pinned(target_mount, &subject, &ctx, &[], Some(&parent)) {
1269                    Ok(landed) => {
1270                        // After the drain into `warnings` above: the
1271                        // amend's own follow-ups go straight to the outcome.
1272                        warnings.extend(landed.warnings.iter().map(MergeWarning::from_hint));
1273                        landed.write_id
1274                    }
1275                    Err(e) => {
1276                        return Err(self.merge_partial_failure(
1277                            &target,
1278                            &store_snapshot,
1279                            &merge_commits,
1280                            ids,
1281                            proposal_stale_or(e, fork),
1282                        ));
1283                    }
1284                };
1285            self.record_self_write(target_mount, &sha);
1286            for p in &amends {
1287                if let Err(e) = self.apply_prepared_to_store(p) {
1288                    warnings.push(MergeWarning::follow_up_failed(
1289                        &target,
1290                        "store_update",
1291                        format!(
1292                            "{}: the store's copy of the amended entity was not refreshed ({}); \
1293                         the re-read after the merge serves the landed body",
1294                            p.id,
1295                            e.prose_render()
1296                        ),
1297                    ));
1298                }
1299            }
1300            let _ = self.stamp_mutation_versions(target_mount);
1301            self.invalidate_communities();
1302            self.invalidate_search_indexes();
1303            parent = sha.clone();
1304            amend_commit = Some(MergeCommit {
1305                sha,
1306                identity: merger.clone(),
1307                entities: ids,
1308            });
1309        }
1310
1311        // ---- The merger's check per entity the merge created or updated,
1312        //      against the landed hash; a no-op or a deletion gets none ----
1313        let method = format!("proposal {}", brief.proposal_id);
1314        let mut entities: Vec<MergedEntity> = Vec::with_capacity(slots.len());
1315        for slot in &slots {
1316            let slug = slot.entry.slug.as_str();
1317            let target_id = EntityId::new(&target, slug);
1318            let plan = adopted.iter().find(|a| a.slug == slug);
1319            let amended = amends.iter().any(|p| p.id == target_id);
1320            let (action, proposer) = match plan {
1321                None => (
1322                    "none",
1323                    proposers.get(slug).map(|(identity, _)| identity.clone()),
1324                ),
1325                Some(a) => {
1326                    let action = if a.landings.iter().any(|l| l.is_create()) {
1327                        "created"
1328                    } else if amended || a.landings.iter().any(|l| matches!(l, Landing::Update(_)))
1329                    {
1330                        "updated"
1331                    } else if a
1332                        .landings
1333                        .iter()
1334                        .any(|l| matches!(l, Landing::Delete { .. }))
1335                    {
1336                        "deleted"
1337                    } else {
1338                        "noop"
1339                    };
1340                    (action, Some(a.proposer.clone()))
1341                }
1342            };
1343            let exists = self.target_holds(&target_id);
1344            let content_hash = exists.then(|| {
1345                self.store
1346                    .get(&target_id)
1347                    .map(|e| e.content_hash.clone())
1348                    .unwrap_or_default()
1349            });
1350            let check_recorded = exists
1351                && matches!(action, "created" | "updated")
1352                && match self.record_check(
1353                    &target,
1354                    target_id.as_ref(),
1355                    Verdict::Ok,
1356                    CheckKind::Verification,
1357                    Some(&method),
1358                    actor,
1359                    client,
1360                ) {
1361                    Ok(_) => true,
1362                    Err(e) => {
1363                        warnings.push(MergeWarning::follow_up_failed(
1364                            &target,
1365                            "check_record",
1366                            format!(
1367                                "{target_id}: the verification check was not recorded ({}); the \
1368                             entity reads as never checked until `memstead check` records one",
1369                                e.prose_render()
1370                            ),
1371                        ));
1372                        false
1373                    }
1374                };
1375            entities.push(MergedEntity {
1376                slug: slug.to_string(),
1377                target_id: target_id.to_string(),
1378                disposition: slot.disposition.to_string(),
1379                action: action.to_string(),
1380                proposer,
1381                content_hash,
1382                check_recorded,
1383            });
1384        }
1385        let _ = noops;
1386        let _ = created_ids;
1387
1388        // ---- The whole store, read back ----
1389        let reread = match self.reload_one_mem(&target) {
1390            Ok(_) => true,
1391            Err(e) => {
1392                warnings.push(MergeWarning::follow_up_failed(
1393                    &target,
1394                    "reload",
1395                    format!(
1396                        "the target was not re-read from its backend after the merge ({}); run \
1397                     `memstead reload --mem {target}`",
1398                        e.prose_render()
1399                    ),
1400                ));
1401                false
1402            }
1403        };
1404        let findings_after = match self.merge_findings(&target) {
1405            Ok(after) => Some(after),
1406            Err(e) => {
1407                warnings.push(MergeWarning::follow_up_failed(
1408                    &target,
1409                    "validation",
1410                    format!(
1411                        "the validation reading after the merge failed ({}); `findings_after` \
1412                     restates the count before the merge and `new_findings` is unknown",
1413                        e.prose_render()
1414                    ),
1415                ));
1416                None
1417            }
1418        };
1419        let new_findings: Vec<String> = findings_after
1420            .as_ref()
1421            .map(|after| {
1422                after
1423                    .difference(&findings_before)
1424                    .map(|(id, code)| format!("{id}: {code}"))
1425                    .collect()
1426            })
1427            .unwrap_or_default();
1428        let validation = MergeValidation {
1429            entities: self
1430                .store
1431                .all_entities()
1432                .filter(|e| e.mem == target && !e.stub)
1433                .count(),
1434            findings_before: findings_before.len(),
1435            findings_after: findings_after
1436                .as_ref()
1437                .map_or(findings_before.len(), BTreeSet::len),
1438            new_findings,
1439            all_entities_parse: reread && self.load_errors().len() <= load_errors_before,
1440        };
1441
1442        let target_tip_after = {
1443            let Some(ops) = self.git_branch_ops() else {
1444                unreachable!("checked above");
1445            };
1446            let target_branch = match &self.mounts[target_mount].mount.storage {
1447                MountStorage::GitBranch { branch, .. } => branch.clone(),
1448                _ => unreachable!("the brief refused a target that is not git-backed"),
1449            };
1450            match resolve_sha(&ops, &gitdir, &crate::branch_full_ref(&target_branch)) {
1451                Ok(sha) => sha,
1452                Err(e) => {
1453                    warnings.push(MergeWarning::follow_up_failed(
1454                        &target,
1455                        "tip_read",
1456                        format!(
1457                            "the target tip was not read back after the last commit ({}); \
1458                         `target_tip_after` is the sha of the last commit landed",
1459                            e.prose_render()
1460                        ),
1461                    ));
1462                    parent.clone()
1463                }
1464            }
1465        };
1466        debug_assert_eq!(target_tip_after, parent);
1467
1468        Ok(ProposalMergeOutcome {
1469            fork: fork.to_string(),
1470            target,
1471            proposal_id: brief.proposal_id,
1472            merged_by: merger,
1473            target_tip_before: brief.target_tip,
1474            target_tip_after,
1475            merge_commits,
1476            amend_commit,
1477            entities,
1478            record_path: PROPOSAL_RECORD_PATH.to_string(),
1479            validation,
1480            warnings,
1481        })
1482    }
1483
1484    /// The proposal record of `target`: every proposal merged into it,
1485    /// with every disposition. An empty record for a mem no proposal
1486    /// was merged into; `UNKNOWN_MEM` for a mem that is not mounted.
1487    pub fn proposal_list(&mut self, target: &str) -> Result<ProposalRecord, EngineError> {
1488        self.find_mount(target)?;
1489        self.reload_if_stale(Some(target));
1490        Ok(self.read_proposal_record(target)?.unwrap_or_default())
1491    }
1492
1493    /// The integrity and conformance findings of `mem` as a set of
1494    /// `(id, code)`, the whole-store reading the merge compares before
1495    /// and after.
1496    fn merge_findings(&self, mem: &str) -> Result<BTreeSet<(String, String)>, EngineError> {
1497        let mut out = BTreeSet::new();
1498        for f in self
1499            .conformance_findings(mem, None)?
1500            .into_iter()
1501            .chain(self.consistency_findings(mem)?)
1502        {
1503            // A sidecar the backend could not read is a storage failure,
1504            // not a finding of the mem: the reading refuses. One that reads
1505            // and does not parse stays a finding.
1506            if f.code == "ANCHORS_SIDECAR_UNREADABLE"
1507                && let Some(reason) = f.detail["reason"].as_str()
1508                && reason.starts_with("could not read the sidecar")
1509            {
1510                return Err(EngineError::Backend(crate::backend::BackendError::Other(
1511                    reason.to_string(),
1512                )));
1513            }
1514            out.insert((f.id, f.code));
1515        }
1516        Ok(out)
1517    }
1518
1519    /// The create or update that lands `landing` in the target, rehearsed
1520    /// through the gate; `None` when the target already holds exactly
1521    /// this version. Relations the fork dropped are removed from the
1522    /// store's copy of the entity before the update composes, so the
1523    /// composed post-state (which the gate validates: required edges,
1524    /// acyclicity, shapes) is the fork's version, not a union.
1525    fn plan_landing(
1526        &mut self,
1527        target_id: &EntityId,
1528        landing: &Entity,
1529        creates: &HashSet<EntityId>,
1530    ) -> Result<Option<Landing>, EngineError> {
1531        let existing = if creates.contains(target_id) {
1532            None
1533        } else {
1534            self.store.get(target_id).filter(|e| !e.stub).cloned()
1535        };
1536        match self.landing_write_args(
1537            target_id.mem(),
1538            target_id.path(),
1539            landing,
1540            existing.as_ref(),
1541        ) {
1542            LandingWrite::Create(args) => {
1543                match self
1544                    .prepare_create(*args, Some(creates), Vec::new())
1545                    .map_err(|e| e.in_entity(target_id.path(), STAGE_LANDING))?
1546                {
1547                    CreatePrepareOutcome::Prepared(p) => Ok(Some(Landing::Create(p))),
1548                    CreatePrepareOutcome::Done(_) => Ok(None),
1549                }
1550            }
1551            LandingWrite::Update(args) => {
1552                let mut args = *args;
1553                let dropped: Vec<(String, EntityId)> = args
1554                    .relations_unset
1555                    .drain(..)
1556                    .map(|r| (r.rel_type, r.target))
1557                    .collect();
1558                if !dropped.is_empty()
1559                    && let Some(existing) = self.store.get_mut(target_id)
1560                {
1561                    existing.relationships.retain(|r| {
1562                        !dropped
1563                            .iter()
1564                            .any(|(t, id)| *t == r.rel_type && *id == r.target)
1565                    });
1566                }
1567                for (rel_type, to) in &dropped {
1568                    self.store.remove_edge(target_id, to, rel_type);
1569                }
1570                match self
1571                    .prepare_update(args)
1572                    .map_err(|e| e.in_entity(target_id.path(), STAGE_LANDING))?
1573                {
1574                    PrepareOutcome::Prepared(p) => Ok(Some(Landing::Update(p))),
1575                    PrepareOutcome::Done(_) => Ok(None),
1576                }
1577            }
1578        }
1579    }
1580
1581    /// The deletion of `id` in the target, when the target holds it;
1582    /// the write-mem referrers are judged later, against the adopted
1583    /// bodies. Read-only referrers demote the id to a residual stub, as
1584    /// a plain delete does.
1585    fn plan_delete(
1586        &self,
1587        id: &EntityId,
1588        deletions: &HashSet<EntityId>,
1589    ) -> Result<Option<Landing>, EngineError> {
1590        let Some(entity) = self.store.get(id).filter(|e| !e.stub) else {
1591            return Ok(None);
1592        };
1593        let _ = deletions;
1594        let referrers = self.classify_delete_referrers(id);
1595        Ok(Some(Landing::Delete {
1596            id: id.clone(),
1597            file_path: entity.file_path.clone(),
1598            readonly_referrers: referrers.readonly_referrers,
1599        }))
1600    }
1601
1602    /// The update that lands the owner's final body over the landed
1603    /// entity: the body's sections replace the landed ones (a landed
1604    /// section the body lacks is unset), its metadata sets the fields
1605    /// it names (a field it omits keeps the landed value, as a create
1606    /// keeps a default), its relations (when given) replace the landed
1607    /// ones. A title that differs refuses: a title change is a rename.
1608    /// `None` when the body restates the landed version.
1609    fn plan_amend(
1610        &mut self,
1611        id: &EntityId,
1612        body: &DispositionBody,
1613    ) -> Result<Option<PreparedUpdate>, EngineError> {
1614        let Some(existing) = self.store.get(id).filter(|e| !e.stub).cloned() else {
1615            return Err(self.not_found(id.as_ref()));
1616        };
1617        if let Some(title) = body.title.as_deref().map(str::trim)
1618            && !title.is_empty()
1619            && title != existing.title
1620        {
1621            return Err(EngineError::InvalidInput(format!(
1622                "dispositions.{}.body.title is '{title}' and the landed title is '{}': a title \
1623                 change is a rename (`memstead rename`), not a merge",
1624                id.path(),
1625                existing.title
1626            )));
1627        }
1628        let sections_unset: Vec<String> = existing
1629            .sections
1630            .keys()
1631            .filter(|k| k.as_str() != "relationships" && !body.sections.contains_key(*k))
1632            .cloned()
1633            .collect();
1634        let mut declare_relations: Vec<crate::ops::RelateArg> = Vec::new();
1635        if let Some(relations) = &body.relations {
1636            let wanted: Vec<(String, EntityId, Option<String>)> = relations
1637                .iter()
1638                .map(|r| {
1639                    let (resolved, _) = self
1640                        .resolve_entity_id(&EntityId(r.target.clone()))
1641                        .unwrap_or((EntityId(r.target.clone()), None));
1642                    (r.rel_type.clone(), resolved, r.description.clone())
1643                })
1644                .collect();
1645            let dropped: Vec<(String, EntityId)> = existing
1646                .relationships
1647                .iter()
1648                .filter(|x| {
1649                    !wanted
1650                        .iter()
1651                        .any(|(t, id, _)| *t == x.rel_type && *id == x.target)
1652                })
1653                .map(|x| (x.rel_type.clone(), x.target.clone()))
1654                .collect();
1655            if let Some(e) = self.store.get_mut(id) {
1656                e.relationships.retain(|r| {
1657                    !dropped
1658                        .iter()
1659                        .any(|(t, id)| *t == r.rel_type && *id == r.target)
1660                });
1661            }
1662            for (rel_type, to) in &dropped {
1663                self.store.remove_edge(id, to, rel_type);
1664            }
1665            for (rel_type, target, description) in wanted {
1666                if !existing
1667                    .relationships
1668                    .iter()
1669                    .any(|x| x.rel_type == rel_type && x.target == target)
1670                {
1671                    declare_relations.push(crate::ops::RelateArg {
1672                        target,
1673                        rel_type,
1674                        description,
1675                    });
1676                }
1677            }
1678        }
1679        let args = crate::UpdateEntityArgs {
1680            id: id.clone(),
1681            // The amend writes from the recorded ancestor under the merge's
1682            // own lock, which already compared the target against it.
1683            expected_hash: crate::ExpectedHash::Override(crate::HashOverride::ProposalMerge),
1684            sections: body.sections.clone(),
1685            append_sections: Default::default(),
1686            patch_sections: Default::default(),
1687            sections_unset,
1688            metadata: body.metadata.clone(),
1689            metadata_unset: Vec::new(),
1690            dry_run: false,
1691            declare_relations,
1692            anchors: Vec::new(),
1693            anchors_unset: Vec::new(),
1694            relations_unset: Vec::new(),
1695        };
1696        match self
1697            .prepare_update(args)
1698            .map_err(|e| e.in_entity(id.path(), STAGE_AMEND))?
1699        {
1700            PrepareOutcome::Prepared(p) => Ok(Some(p)),
1701            PrepareOutcome::Done(_) => Ok(None),
1702        }
1703    }
1704
1705    /// Roll a failed merge back so nothing of it stands: every pending
1706    /// buffer discarded and the store snapshot restored; when a commit
1707    /// of this merge already landed (`landed` is the branch's tip then),
1708    /// the target branch moved back to `target_tip`, the tip the merge
1709    /// was pinned to (every commit above it is this merge's own, each
1710    /// parent-pinned, so no other writer's work sits between), and the
1711    /// target re-read from its backend. Returns `error`, the failure
1712    /// that triggered the unwind, unless the branch could not be moved
1713    /// back: then the landed commits stand and the error names both.
1714    /// The report of a merge that failed after one of its commits
1715    /// landed: the landed commits stay on the branch (no reset), the
1716    /// store is brought level with storage, and the error states per
1717    /// commit, in the `RENAME_PARTIAL_FAILURE` shape every operation that
1718    /// lands in parts reports, which entities landed and their hash now.
1719    /// The branch tip moved, so the same file is stale: re-render the
1720    /// brief and merge again to land the rest.
1721    fn merge_partial_failure(
1722        &mut self,
1723        target: &str,
1724        snapshot: &crate::store::Store,
1725        landed: &[MergeCommit],
1726        failed: Vec<String>,
1727        cause: EngineError,
1728    ) -> EngineError {
1729        use crate::engine::error::{PartialItem, PartialMem};
1730        self.discard_all_pending();
1731        self.store = snapshot.clone();
1732        let _ = self.reload_one_mem(target);
1733        let item =
1734            |engine: &Self, ids: &[String], landed: bool, error: Option<String>| PartialMem {
1735                mem: target.to_string(),
1736                landed,
1737                error,
1738                items: ids
1739                    .iter()
1740                    .map(|id| PartialItem {
1741                        id: id.clone(),
1742                        landed,
1743                        current_hash: engine.hash_now(&EntityId(id.clone())),
1744                    })
1745                    .collect(),
1746            };
1747        let mut mems: Vec<PartialMem> = landed
1748            .iter()
1749            .map(|c| item(self, &c.entities, true, None))
1750            .collect();
1751        mems.push(item(self, &failed, false, Some(cause.to_string())));
1752        EngineError::RenamePartialFailure {
1753            committed_mems: vec![target.to_string()],
1754            failed_mem: target.to_string(),
1755            failure_cause: crate::engine::mutation::landing::failure_cause_of(&cause).to_string(),
1756            mems,
1757        }
1758    }
1759
1760    fn unwind_merge(
1761        &mut self,
1762        target: &str,
1763        target_tip: &str,
1764        landed: Option<&str>,
1765        snapshot: &crate::store::Store,
1766        error: EngineError,
1767    ) -> EngineError {
1768        self.discard_all_pending();
1769        self.store = snapshot.clone();
1770        let Some(landed) = landed else {
1771            return error;
1772        };
1773        match self.branch_reset(target, target_tip, Some(landed)) {
1774            Ok(_) => {
1775                let _ = self.reload_one_mem(target);
1776                error
1777            }
1778            Err(reset) => {
1779                let _ = self.reload_one_mem(target);
1780                EngineError::Backend(crate::backend::BackendError::Other(format!(
1781                    "{}; the merge commits already on '{target}' (tip {landed}) could not be \
1782                     moved back to {target_tip} and stand: {reset}",
1783                    error.prose_render()
1784                )))
1785            }
1786        }
1787    }
1788}
1789
1790/// A parent mismatch at a merge commit is the target moving under the
1791/// merge: the merge's own refusal names it; every other error passes.
1792fn proposal_stale_or(e: EngineError, fork: &str) -> EngineError {
1793    match e {
1794        EngineError::Backend(crate::backend::BackendError::ParentMismatch { expected, actual }) => {
1795            EngineError::ProposalStale {
1796                fork: fork.to_string(),
1797                side: "target".to_string(),
1798                recorded: expected,
1799                current: actual,
1800            }
1801        }
1802        other => other,
1803    }
1804}