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, MergedEntity, PROPOSAL_RECORD_PATH,
56    ProposalBrief, ProposalChange, ProposalEntry, ProposalMergeOutcome, ProposalRecord,
57    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}
118
119impl Engine {
120    /// The origin marks for a body the merge has just landed in `target`:
121    /// one prepared hash per load-bearing section the landed entity
122    /// carries. `None` when the slug holds no real entity (a stub) or the
123    /// landed body has no non-empty load-bearing section, so the record
124    /// carries no mark and the entity inherits its mem's class.
125    ///
126    /// Per section, and the prepared form rather than the file hash, so the
127    /// marks survive the owner's bookkeeping edits, a repin and a retype,
128    /// and expire per claim-carrying section; see
129    /// [`crate::ops::proposal::RecordedDisposition::landed_sections`]. The
130    /// read path compares with the same primitive
131    /// ([`crate::preparation::entity_section_prepared_hash`]), so the two
132    /// sides cannot drift into computing different things.
133    fn landed_section_marks(
134        &self,
135        target: &str,
136        slug: &str,
137    ) -> Option<std::collections::BTreeMap<String, String>> {
138        let id = EntityId::new(target, slug);
139        let entity = self.store.get(&id).filter(|e| !e.stub)?;
140        let type_def = self
141            .schema_for(target)
142            .and_then(|schema| schema.get_type(&entity.entity_type));
143        let marks =
144            crate::preparation::entity_load_bearing_section_marks(entity, type_def.as_deref());
145        (!marks.is_empty()).then_some(marks)
146    }
147
148    /// Apply `file` (the brief's JSON with `dispositions` filled) onto
149    /// the mem `fork` was forked from. The merger is the session's
150    /// identity ([`Engine::set_identity`]) and is required. The file's
151    /// `description` (trimmed; blank is absent) is recorded on the
152    /// proposal record's entry as the proposal in the owner's words;
153    /// when the file carries none, `note` stands in.
154    ///
155    /// Refusals, each landing nothing: `INVALID_INPUT` (no merger
156    /// identity; the file names another fork; a value outside the
157    /// vocabulary; a missing reason or body; `adopt_with_changes` on a
158    /// deletion), `PROPOSAL_DISPOSITIONS_INCOMPLETE`, `PROPOSAL_CONFLICT`,
159    /// `PROPOSAL_STALE` (a pinned tip moved), `PROPOSAL_UNATTRIBUTED`
160    /// (an adopted entity's last fork commit carries no identity), the
161    /// write gate's own code for a body it refuses (with
162    /// `details.entity` naming the slug and `details.stage` saying
163    /// `landing` or `amend`), `HAS_INCOMING_REFS` for a deletion the
164    /// target's referrers block, `UNKNOWN_MEM`, `READ_ONLY_MOUNT`, and
165    /// the brief's refusals. Once the last commit is on the branch a
166    /// failure is a warning on the outcome, never an error.
167    pub fn proposal_merge(
168        &mut self,
169        fork: &str,
170        file: &ProposalBrief,
171        actor: Actor,
172        client: Option<&ClientId>,
173        note: Option<&str>,
174    ) -> Result<ProposalMergeOutcome, EngineError> {
175        let Some(merger) = self.current_identity().map(str::to_string) else {
176            return Err(EngineError::InvalidInput(
177                "a proposal merge records the merger's identity beside the proposer's, and \
178                 the session declares none: pass `--identity <merger>`"
179                    .to_string(),
180            ));
181        };
182        if file.fork != fork {
183            return Err(EngineError::InvalidInput(format!(
184                "the disposition file was rendered for fork '{}', not '{fork}'",
185                file.fork
186            )));
187        }
188
189        // ---- The picture as it stands, and the file against it ----
190        let brief = self.proposal_brief(fork)?;
191        let target = brief.target.clone();
192        let (gitdir, fork_branch) = match &self.find_mount(fork)?.mount.storage {
193            MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
194            _ => unreachable!("the brief refused a fork that is not git-backed"),
195        };
196        let target_mount = self
197            .mounts
198            .iter()
199            .position(|m| m.mount.mem == target)
200            .ok_or_else(|| self.unknown_mem_error(&target))?;
201        if self.mounts[target_mount].mount.capability != MountCapability::Write {
202            return Err(EngineError::ReadOnlyMount(target.clone()));
203        }
204        for (side, recorded, current) in [
205            ("target", &file.target_tip, &brief.target_tip),
206            ("fork", &file.fork_tip, &brief.fork_tip),
207            ("base", &file.base, &brief.base),
208        ] {
209            if recorded != current {
210                return Err(EngineError::ProposalStale {
211                    fork: fork.to_string(),
212                    side: side.to_string(),
213                    recorded: recorded.clone(),
214                    current: current.clone(),
215                });
216            }
217        }
218        let listed: BTreeSet<&str> = brief.entries.iter().map(|e| e.slug.as_str()).collect();
219        let filed: BTreeSet<&str> = file.dispositions.keys().map(String::as_str).collect();
220        let missing: Vec<String> = listed.difference(&filed).map(|s| s.to_string()).collect();
221        let unexpected: Vec<String> = filed.difference(&listed).map(|s| s.to_string()).collect();
222        if !missing.is_empty() || !unexpected.is_empty() {
223            return Err(EngineError::ProposalDispositionsIncomplete {
224                fork: fork.to_string(),
225                missing,
226                unexpected,
227            });
228        }
229
230        // ---- Every slot, in slug order ----
231        struct Slot<'a> {
232            entry: &'a ProposalEntry,
233            disposition: &'a str,
234            reason: Option<String>,
235            body: Option<DispositionBody>,
236        }
237        let mut slots: Vec<Slot<'_>> = Vec::with_capacity(brief.entries.len());
238        for entry in &brief.entries {
239            let slot = &file.dispositions[&entry.slug];
240            let disposition = slot.disposition.trim();
241            if !DISPOSITION_VOCABULARY.contains(&disposition) {
242                return Err(EngineError::InvalidInput(format!(
243                    "dispositions.{}.disposition is '{}': the vocabulary is {}",
244                    entry.slug,
245                    slot.disposition,
246                    DISPOSITION_VOCABULARY.join(", ")
247                )));
248            }
249            let disposition = DISPOSITION_VOCABULARY
250                .iter()
251                .find(|v| **v == disposition)
252                .copied()
253                .expect("checked above");
254            let reason = crate::vcs::normalise_identity(Some(&slot.reason));
255            if matches!(
256                disposition,
257                DISPOSITION_REJECT | DISPOSITION_ADOPT_WITH_CHANGES
258            ) && reason.is_none()
259            {
260                return Err(EngineError::InvalidInput(format!(
261                    "dispositions.{}.reason is empty: `{disposition}` needs a reason",
262                    entry.slug
263                )));
264            }
265            if disposition == DISPOSITION_ADOPT
266                && let Some(c) = &entry.conflict
267            {
268                return Err(EngineError::ProposalConflict {
269                    fork: fork.to_string(),
270                    slug: entry.slug.clone(),
271                    kind: c.kind.as_wire().to_string(),
272                });
273            }
274            let body = if disposition == DISPOSITION_ADOPT_WITH_CHANGES {
275                if entry.status == ProposalChange::Deleted {
276                    return Err(EngineError::InvalidInput(format!(
277                        "dispositions.{}: the fork's version is a deletion, which takes no \
278                         final body; `adopt` it or `reject` it",
279                        entry.slug
280                    )));
281                }
282                let Some(raw) = &slot.body else {
283                    return Err(EngineError::InvalidInput(format!(
284                        "dispositions.{}.body is absent: `adopt_with_changes` carries the \
285                         owner's final body (`sections`, `metadata`, optional `title` and \
286                         `relations`)",
287                        entry.slug
288                    )));
289                };
290                let body: DispositionBody = serde_json::from_value(raw.clone()).map_err(|e| {
291                    EngineError::InvalidInput(format!(
292                        "dispositions.{}.body does not parse as a body (`sections`, \
293                             `metadata`, optional `title` and `relations`): {e}",
294                        entry.slug
295                    ))
296                })?;
297                if body.sections.is_empty() {
298                    return Err(EngineError::InvalidInput(format!(
299                        "dispositions.{}.body.sections is empty: the final body carries at \
300                         least one section",
301                        entry.slug
302                    )));
303                }
304                Some(body)
305            } else {
306                None
307            };
308            slots.push(Slot {
309                entry,
310                disposition,
311                reason,
312                body,
313            });
314        }
315
316        // ---- The proposer of every adopted entity, off the fork's commits ----
317        let notes = {
318            let Some(hook) = self.git_branch_ops.as_ref() else {
319                return Err(EngineError::InvalidInput(
320                    "a proposal merge needs the git-branch ops bundle (full boot only)".to_string(),
321                ));
322            };
323            (hook.changes_since)(
324                &gitdir,
325                &fork_branch,
326                fork,
327                crate::ops::EMPTY_TREE_SHA,
328                crate::ops::RENAME_SIMILARITY_DEFAULT,
329            )
330            .map_err(EngineError::Backend)?
331            .notes
332        };
333        // Per slug: the proposer's identity and the role the same
334        // commit named (absence recorded as `Unspecified`). An adopted
335        // entity must be attributed, because its landing commit carries
336        // that identity; a rejected one is attributed where the fork's
337        // commits allow it, so the record still names who proposed, and
338        // is silently unattributed otherwise (nothing lands under it).
339        let mut proposers: BTreeMap<String, (String, Role)> = BTreeMap::new();
340        for slot in &slots {
341            let fork_id = EntityId::new(fork, &slot.entry.slug);
342            let touch = filter_notes_for_entity(fork_id.as_ref(), &notes)
343                .into_iter()
344                .next();
345            match touch.as_ref().and_then(|t| t.identity.clone()) {
346                Some(identity) => {
347                    let role = touch
348                        .as_ref()
349                        .and_then(|t| t.role.as_deref())
350                        .and_then(Role::from_wire)
351                        .unwrap_or_default();
352                    proposers.insert(slot.entry.slug.clone(), (identity, role));
353                }
354                None if slot.disposition == DISPOSITION_REJECT => {}
355                None => {
356                    return Err(EngineError::ProposalUnattributed {
357                        fork: fork.to_string(),
358                        slug: slot.entry.slug.clone(),
359                        sha: touch
360                            .map(|t| t.reference)
361                            .unwrap_or_else(|| "(no engine-recorded commit)".to_string()),
362                    });
363                }
364            }
365        }
366
367        // ---- The validation baseline, before anything moves ----
368        let findings_before = self.merge_findings(&target)?;
369        let load_errors_before = self.load_errors().len();
370
371        // ---- Rehearse every adopted write through the gate ----
372        let store_snapshot = self.store.clone();
373        let target_schema = self.schema_for(&target);
374        let mut adopted: Vec<Adopted> = Vec::new();
375        let mut noops: Vec<String> = Vec::new();
376        // The fork's version of every adopted entity under the target's
377        // name, parsed under the target's schema.
378        let mut versions: BTreeMap<String, Entity> = BTreeMap::new();
379        for slot in slots
380            .iter()
381            .filter(|s| s.disposition != DISPOSITION_REJECT)
382            .filter(|s| s.entry.status != ProposalChange::Deleted)
383        {
384            let slug = slot.entry.slug.as_str();
385            let target_id = EntityId::new(&target, slug);
386            let landing = slot
387                .entry
388                .fork_body
389                .as_deref()
390                .map(|b| normalise_to(b, fork, &target))
391                .and_then(|b| {
392                    parse_body(
393                        &b,
394                        &crate::entity::id::id_to_file_path(&target_id),
395                        &target,
396                        target_schema.as_deref(),
397                    )
398                })
399                .ok_or_else(|| {
400                    EngineError::InvalidInput(format!(
401                        "the fork's body of '{slug}' does not parse under the target's schema \
402                         (the brief's precheck names the failure); reject it, or repair it on \
403                         the fork"
404                    ))
405                })?;
406            versions.insert(slug.to_string(), landing);
407        }
408        // Every entity the merge creates is staged as a typed skeleton
409        // first, so a sibling's edge to it validates against a real
410        // target (the batch create's rule).
411        let creates: HashSet<EntityId> = versions
412            .keys()
413            .map(|slug| EntityId::new(&target, slug))
414            .filter(|id| !self.target_holds(id))
415            .collect();
416        for id in &creates {
417            let landing = &versions[id.path()];
418            let mut skeleton = make_stub(id, crate::entity::StubKind::ForwardReference);
419            skeleton.stub = false;
420            skeleton.stub_kind = None;
421            skeleton.entity_type = landing.entity_type.clone();
422            skeleton.title = landing.title.clone();
423            self.store.upsert(id.clone(), skeleton);
424        }
425        let deletions: HashSet<EntityId> = slots
426            .iter()
427            .filter(|s| s.disposition == DISPOSITION_ADOPT)
428            .filter_map(|s| match s.entry.status {
429                ProposalChange::Deleted => Some(EntityId::new(&target, &s.entry.slug)),
430                ProposalChange::Renamed => s
431                    .entry
432                    .renamed_from
433                    .as_deref()
434                    .map(|from| EntityId::new(&target, from)),
435                _ => None,
436            })
437            .collect();
438        let prepared: Result<(), EngineError> = (|| {
439            for slot in slots.iter().filter(|s| s.disposition != DISPOSITION_REJECT) {
440                let slug = slot.entry.slug.as_str();
441                let target_id = EntityId::new(&target, slug);
442                let mut landings: Vec<Landing> = Vec::new();
443                match slot.entry.status {
444                    ProposalChange::Deleted => {
445                        if let Some(l) = self.plan_delete(&target_id, &deletions)? {
446                            landings.push(l);
447                        } else {
448                            noops.push(slug.to_string());
449                        }
450                    }
451                    _ => {
452                        let landing = &versions[slug];
453                        match self.plan_landing(&target_id, landing, &creates)? {
454                            Some(l) => landings.push(l),
455                            None => noops.push(slug.to_string()),
456                        }
457                        if slot.entry.status == ProposalChange::Renamed
458                            && let Some(from) = slot.entry.renamed_from.as_deref()
459                            && let Some(l) =
460                                self.plan_delete(&EntityId::new(&target, from), &deletions)?
461                        {
462                            landings.push(l);
463                        }
464                    }
465                }
466                let (proposer, role) = proposers[slug].clone();
467                adopted.push(Adopted {
468                    slug: slug.to_string(),
469                    proposer,
470                    role,
471                    landings,
472                    amend: slot.body.clone(),
473                });
474            }
475            Ok(())
476        })();
477        if let Err(e) = prepared {
478            self.store = store_snapshot;
479            self.discard_all_pending();
480            return Err(e);
481        }
482
483        // ---- The store as it will be, so a deletion's referrers are judged
484        //      against the adopted bodies, not the pre-merge ones ----
485        let applied: Result<(), EngineError> = (|| {
486            let fallback = engine_fallback_type();
487            for a in &adopted {
488                for l in &a.landings {
489                    match l {
490                        Landing::Create(p) => {
491                            let parsed = parse_markdown(
492                                &p.markdown,
493                                &p.file_path,
494                                p.type_def.as_ref(),
495                                &p.mem,
496                            )
497                            .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
498                            push_entities_into_store(
499                                &mut self.store,
500                                vec![parsed],
501                                fallback.as_ref(),
502                                None,
503                            );
504                        }
505                        Landing::Update(p) => {
506                            self.apply_prepared_to_store(p)?;
507                        }
508                        Landing::Delete { .. } => {}
509                    }
510                }
511            }
512            crate::entity::store_builder::remap_alias_target_edge_sources(
513                &mut self.store,
514                &self.schemas,
515            );
516            for a in &adopted {
517                for l in &a.landings {
518                    if let Landing::Delete { id, .. } = l {
519                        let referrers = self.classify_delete_referrers(id);
520                        let blocking: Vec<_> = referrers
521                            .write_referrers
522                            .into_iter()
523                            .filter(|r| !deletions.contains(&EntityId(r.from_id.clone())))
524                            .collect();
525                        if !blocking.is_empty() {
526                            return Err(EngineError::HasIncomingRefs {
527                                id: id.to_string(),
528                                referrers: blocking,
529                            });
530                        }
531                    }
532                }
533            }
534            Ok(())
535        })();
536        if let Err(e) = applied {
537            self.store = store_snapshot;
538            self.discard_all_pending();
539            return Err(e);
540        }
541
542        // ---- The owner's final bodies, rehearsed now against the landed
543        //      versions the store holds, so a body the gate refuses lands
544        //      nothing; staged and committed after the merge commits ----
545        let amends: Result<Vec<PreparedUpdate>, EngineError> = (|| {
546            let mut prepared: Vec<PreparedUpdate> = Vec::new();
547            for a in &adopted {
548                if let Some(body) = &a.amend
549                    && let Some(p) = self.plan_amend(&EntityId::new(&target, &a.slug), body)?
550                {
551                    prepared.push(p);
552                }
553            }
554            Ok(prepared)
555        })();
556        let amends = match amends {
557            Ok(p) => p,
558            Err(e) => {
559                self.store = store_snapshot;
560                self.discard_all_pending();
561                return Err(e);
562            }
563        };
564
565        // ---- The record ----
566        // The proposal in the owner's words: the file's slot, trimmed,
567        // else the merge's note; the file wins when both are given.
568        let description = crate::vcs::normalise_identity(Some(&file.description))
569            .or_else(|| crate::vcs::normalise_identity(note));
570        let mut record = self.read_proposal_record(&target)?.unwrap_or_default();
571        // The identities the merge commits land under: one per adopted
572        // proposer, in slug order.
573        let mut distinct_proposers: Vec<String> = Vec::new();
574        for a in &adopted {
575            if !distinct_proposers.contains(&a.proposer) {
576                distinct_proposers.push(a.proposer.clone());
577            }
578        }
579        // The identities the record names as the proposal's: every
580        // attributed entry, adopted or rejected, in slug order.
581        let mut recorded_proposers: Vec<String> = Vec::new();
582        for slot in &slots {
583            if let Some((identity, _)) = proposers.get(&slot.entry.slug)
584                && !recorded_proposers.contains(identity)
585            {
586                recorded_proposers.push(identity.clone());
587            }
588        }
589        record.proposals.push(ProposalRecordEntry {
590            id: brief.proposal_id.clone(),
591            proposer: (!recorded_proposers.is_empty()).then(|| recorded_proposers.join(", ")),
592            ancestor: brief.ancestor.clone(),
593            base: brief.base.clone(),
594            target_tip: brief.target_tip.clone(),
595            merged_by: Some(merger.clone()),
596            at: self.now_iso(),
597            description,
598            entities: slots
599                .iter()
600                .map(|s| {
601                    (s.entry.slug.clone(), {
602                        // The adopt-time origin decision. An `adopt`
603                        // lands the proposer's bytes verbatim (the
604                        // landing commit carries the proposer's
605                        // identity), so the entity's claim-carrying
606                        // sections are a stranger's until the owner
607                        // rewrites them; an `adopt_with_changes` lands
608                        // the owner's own body in the amend commit and
609                        // is first-party, so it records no mark. The
610                        // store already holds the landed body here
611                        // (`apply_prepared_to_store` ran above), and
612                        // the hash is a pure function of those bytes,
613                        // so the value matches what the re-read serves.
614                        // Only where the adoption actually LANDS a body.
615                        // A fork's deletion is an `adopt` too, and the
616                        // store still holds the owner's pre-delete
617                        // entity at this point, so marking on the
618                        // disposition alone would stamp the owner's own
619                        // body as a stranger's.
620                        let lands_a_body = adopted
621                            .iter()
622                            .find(|a| a.slug == s.entry.slug)
623                            .is_some_and(|a| {
624                                a.landings.iter().any(|l| {
625                                    !matches!(l, Landing::Delete { .. })
626                                        && l.id() == &EntityId::new(&target, &s.entry.slug)
627                                })
628                            });
629                        let landed_sections = (s.disposition == DISPOSITION_ADOPT && lands_a_body)
630                            .then(|| self.landed_section_marks(&target, &s.entry.slug))
631                            .flatten();
632                        RecordedDisposition {
633                            disposition: s.disposition.to_string(),
634                            reason: s.reason.clone(),
635                            content_hash: s.entry.content_hash.clone(),
636                            landed_sections,
637                        }
638                    })
639                })
640                .collect(),
641        });
642        let record_bytes = record.to_bytes();
643
644        // ---- Land: one commit per proposer identity, in slug order ----
645        let mut merge_commits: Vec<MergeCommit> = Vec::new();
646        let mut parent = brief.target_tip.clone();
647        let mut landed_any = false;
648        let mut created_ids: HashSet<EntityId> = HashSet::new();
649        let mut deleted_ids: Vec<(EntityId, Vec<EntityId>)> = Vec::new();
650        for (i, proposer) in distinct_proposers.iter().enumerate() {
651            let group: Vec<&Adopted> = adopted.iter().filter(|a| &a.proposer == proposer).collect();
652            let last_group = i + 1 == distinct_proposers.len();
653            let staged: Result<(Vec<String>, Vec<String>), EngineError> = (|| {
654                let backend = self.mounts[target_mount].backend.as_ref();
655                let mut ids: Vec<String> = Vec::new();
656                let mut created: Vec<String> = Vec::new();
657                for a in &group {
658                    for l in &a.landings {
659                        match l {
660                            Landing::Create(p) => {
661                                self.stage_prepared_create(p)?;
662                                let rows = self.entity_anchors(&EntityId::new(fork, &a.slug));
663                                stage_anchors_replace(backend, &p.id, rows)?;
664                                created.push(p.id.to_string());
665                            }
666                            Landing::Update(p) => {
667                                self.stage_prepared_update(p)?;
668                                let rows = self.entity_anchors(&EntityId::new(fork, &a.slug));
669                                stage_anchors_replace(backend, &p.id, rows)?;
670                            }
671                            Landing::Delete { id, file_path, .. } => {
672                                backend.delete_entity(Path::new(file_path))?;
673                                stage_anchors_removal(backend, id)?;
674                            }
675                        }
676                        ids.push(l.id().to_string());
677                    }
678                }
679                if last_group {
680                    backend.write_entity(Path::new(PROPOSAL_RECORD_PATH), &record_bytes)?;
681                }
682                Ok((ids, created))
683            })();
684            let (ids, created) = match staged {
685                Ok(v) => v,
686                Err(e) => {
687                    return Err(self.unwind_merge(
688                        &target,
689                        &brief.target_tip,
690                        landed_any.then_some(parent.as_str()),
691                        &store_snapshot,
692                        e,
693                    ));
694                }
695            };
696            // The proposer's role rides the merge commit beside the
697            // identity: the role off the fork commit that last touched
698            // the group's first entity in slug order (one commit per
699            // proposer, so one role; a proposer who wrote under several
700            // roles lands under the first slug's).
701            let role = group.first().map(|a| a.role).unwrap_or_default();
702            let mut ctx = CommitContext::new(
703                Some(MERGE_TOOL),
704                actor,
705                client.cloned(),
706                note.map(String::from),
707                role,
708                Some(proposer.clone()),
709            );
710            ctx.entity_ids = Some(ids.clone());
711            ctx.proposal = Some(ProposalTrailers {
712                proposal: brief.proposal_id.clone(),
713                merged_by: merger.clone(),
714                created: created.clone(),
715            });
716            let subject = format!("memstead: proposal-merge {}", brief.proposal_id);
717            let sha = match self.mounts[target_mount]
718                .backend
719                .commit_with_expected_parent(&subject, &ctx, Some(&parent))
720            {
721                Ok(sha) => sha,
722                Err(e) => {
723                    let e = match e {
724                        crate::backend::BackendError::ParentMismatch { expected, actual } => {
725                            EngineError::ProposalStale {
726                                fork: fork.to_string(),
727                                side: "target".to_string(),
728                                recorded: expected,
729                                current: actual,
730                            }
731                        }
732                        other => other.into(),
733                    };
734                    return Err(self.unwind_merge(
735                        &target,
736                        &brief.target_tip,
737                        landed_any.then_some(parent.as_str()),
738                        &store_snapshot,
739                        e,
740                    ));
741                }
742            };
743            landed_any = true;
744            self.record_self_write(target_mount, &sha);
745            for a in &group {
746                for l in &a.landings {
747                    match l {
748                        Landing::Delete {
749                            id,
750                            readonly_referrers,
751                            ..
752                        } => deleted_ids.push((id.clone(), readonly_referrers.clone())),
753                        l if l.is_create() => {
754                            created_ids.insert(l.id().clone());
755                        }
756                        _ => {}
757                    }
758                }
759            }
760            parent = sha.clone();
761            merge_commits.push(MergeCommit {
762                sha,
763                identity: proposer.clone(),
764                entities: ids,
765            });
766        }
767
768        // ---- Nothing adopted: the record still lands ----
769        // A merge is a decision record before it is a content change.
770        // With every entry rejected there is no proposer to land under,
771        // so one commit under the merger carries the record alone,
772        // parent-pinned like the others: a refused proposal is as
773        // visible on the target branch as an accepted one, the brief
774        // marks a re-proposal of it, and a reader of the branch learns
775        // the fork is disposed.
776        if distinct_proposers.is_empty() {
777            let staged: Result<(), EngineError> = (|| {
778                let backend = self.mounts[target_mount].backend.as_ref();
779                backend.write_entity(Path::new(PROPOSAL_RECORD_PATH), &record_bytes)?;
780                Ok(())
781            })();
782            if let Err(e) = staged {
783                return Err(self.unwind_merge(
784                    &target,
785                    &brief.target_tip,
786                    None,
787                    &store_snapshot,
788                    e,
789                ));
790            }
791            let mut ctx = self.commit_context(
792                Some(MERGE_TOOL),
793                actor,
794                client.cloned(),
795                note.map(String::from),
796            );
797            ctx.entity_ids = Some(Vec::new());
798            ctx.proposal = Some(ProposalTrailers {
799                proposal: brief.proposal_id.clone(),
800                merged_by: merger.clone(),
801                created: Vec::new(),
802            });
803            let subject = format!("memstead: proposal-merge {}", brief.proposal_id);
804            let sha = match self.mounts[target_mount]
805                .backend
806                .commit_with_expected_parent(&subject, &ctx, Some(&parent))
807            {
808                Ok(sha) => sha,
809                Err(e) => {
810                    let e = match e {
811                        crate::backend::BackendError::ParentMismatch { expected, actual } => {
812                            EngineError::ProposalStale {
813                                fork: fork.to_string(),
814                                side: "target".to_string(),
815                                recorded: expected,
816                                current: actual,
817                            }
818                        }
819                        other => other.into(),
820                    };
821                    return Err(self.unwind_merge(
822                        &target,
823                        &brief.target_tip,
824                        None,
825                        &store_snapshot,
826                        e,
827                    ));
828                }
829            };
830            self.record_self_write(target_mount, &sha);
831            parent = sha.clone();
832            merge_commits.push(MergeCommit {
833                sha,
834                identity: merger.clone(),
835                entities: Vec::new(),
836            });
837        }
838
839        // ---- The store after the commits: deletions, stubs, indexes ----
840        for (id, readonly_referrers) in &deleted_ids {
841            if readonly_referrers.is_empty() {
842                self.store.remove(id);
843            } else {
844                self.store.remove_edges_from(id);
845                self.store.upsert(
846                    id.clone(),
847                    make_stub(
848                        id,
849                        crate::entity::StubKind::Residual {
850                            since_commit: parent.clone(),
851                            readonly_referrers: readonly_referrers.clone(),
852                        },
853                    ),
854                );
855            }
856        }
857        let mut out_of_batch: Vec<(EntityId, crate::entity::StubKind)> = Vec::new();
858        for a in &adopted {
859            for l in &a.landings {
860                if let Landing::Create(p) = l {
861                    for t in &p.relation_targets {
862                        if !self.store.contains(t) {
863                            out_of_batch.push((t.clone(), deferred_verified_stub_kind(self, t)?));
864                        }
865                    }
866                }
867            }
868        }
869        for (t, kind) in out_of_batch {
870            self.store.upsert(t.clone(), make_stub(&t, kind));
871        }
872        gc_orphan_stubs(&mut self.store);
873        let _ = self.stamp_mutation_versions(target_mount);
874        self.invalidate_communities();
875        self.invalidate_search_indexes();
876
877        // ---- The owner's final bodies, one commit under the merger ----
878        // From the last commit on, a failure is bookkeeping: it goes here
879        // and the merge is reported as landed (see the module doc).
880        let mut warnings: Vec<String> = Vec::new();
881        let mut amend_commit: Option<MergeCommit> = None;
882        if !amends.is_empty() {
883            let staged: Result<(), EngineError> = (|| {
884                for p in &amends {
885                    self.stage_prepared_update(p)?;
886                }
887                Ok(())
888            })();
889            if let Err(e) = staged {
890                return Err(self.unwind_merge(
891                    &target,
892                    &brief.target_tip,
893                    Some(&parent),
894                    &store_snapshot,
895                    e,
896                ));
897            }
898            let ids: Vec<String> = amends.iter().map(|p| p.id.to_string()).collect();
899            let mut ctx = self.commit_context(
900                Some(MERGE_TOOL),
901                actor,
902                client.cloned(),
903                note.map(String::from),
904            );
905            ctx.entity_ids = Some(ids.clone());
906            ctx.proposal = Some(ProposalTrailers {
907                proposal: brief.proposal_id.clone(),
908                merged_by: merger.clone(),
909                created: Vec::new(),
910            });
911            let subject = format!("memstead: proposal-amend {}", brief.proposal_id);
912            let sha = match self.mounts[target_mount]
913                .backend
914                .commit_with_expected_parent(&subject, &ctx, Some(&parent))
915            {
916                Ok(sha) => sha,
917                Err(e) => {
918                    return Err(self.unwind_merge(
919                        &target,
920                        &brief.target_tip,
921                        Some(&parent),
922                        &store_snapshot,
923                        e.into(),
924                    ));
925                }
926            };
927            self.record_self_write(target_mount, &sha);
928            for p in &amends {
929                if let Err(e) = self.apply_prepared_to_store(p) {
930                    warnings.push(format!(
931                        "{}: the store's copy of the amended entity was not refreshed ({}); \
932                         the re-read after the merge serves the landed body",
933                        p.id,
934                        e.prose_render()
935                    ));
936                }
937            }
938            let _ = self.stamp_mutation_versions(target_mount);
939            self.invalidate_communities();
940            self.invalidate_search_indexes();
941            parent = sha.clone();
942            amend_commit = Some(MergeCommit {
943                sha,
944                identity: merger.clone(),
945                entities: ids,
946            });
947        }
948
949        // ---- The merger's check per entity the merge created or updated,
950        //      against the landed hash; a no-op or a deletion gets none ----
951        let method = format!("proposal {}", brief.proposal_id);
952        let mut entities: Vec<MergedEntity> = Vec::with_capacity(slots.len());
953        for slot in &slots {
954            let slug = slot.entry.slug.as_str();
955            let target_id = EntityId::new(&target, slug);
956            let plan = adopted.iter().find(|a| a.slug == slug);
957            let amended = amends.iter().any(|p| p.id == target_id);
958            let (action, proposer) = match plan {
959                None => (
960                    "none",
961                    proposers.get(slug).map(|(identity, _)| identity.clone()),
962                ),
963                Some(a) => {
964                    let action = if a.landings.iter().any(|l| l.is_create()) {
965                        "created"
966                    } else if amended || a.landings.iter().any(|l| matches!(l, Landing::Update(_)))
967                    {
968                        "updated"
969                    } else if a
970                        .landings
971                        .iter()
972                        .any(|l| matches!(l, Landing::Delete { .. }))
973                    {
974                        "deleted"
975                    } else {
976                        "noop"
977                    };
978                    (action, Some(a.proposer.clone()))
979                }
980            };
981            let exists = self.target_holds(&target_id);
982            let content_hash = exists.then(|| {
983                self.store
984                    .get(&target_id)
985                    .map(|e| e.content_hash.clone())
986                    .unwrap_or_default()
987            });
988            let check_recorded = exists
989                && matches!(action, "created" | "updated")
990                && match self.record_check(
991                    &target,
992                    target_id.as_ref(),
993                    Verdict::Ok,
994                    CheckKind::Verification,
995                    Some(&method),
996                    actor,
997                    client,
998                ) {
999                    Ok(_) => true,
1000                    Err(e) => {
1001                        warnings.push(format!(
1002                            "{target_id}: the verification check was not recorded ({}); the \
1003                             entity reads as never checked until `memstead check` records one",
1004                            e.prose_render()
1005                        ));
1006                        false
1007                    }
1008                };
1009            entities.push(MergedEntity {
1010                slug: slug.to_string(),
1011                target_id: target_id.to_string(),
1012                disposition: slot.disposition.to_string(),
1013                action: action.to_string(),
1014                proposer,
1015                content_hash,
1016                check_recorded,
1017            });
1018        }
1019        let _ = noops;
1020        let _ = created_ids;
1021
1022        // ---- The whole store, read back ----
1023        let reread = match self.reload_one_mem(&target) {
1024            Ok(_) => true,
1025            Err(e) => {
1026                warnings.push(format!(
1027                    "the target was not re-read from its backend after the merge ({}); run \
1028                     `memstead reload --mem {target}`",
1029                    e.prose_render()
1030                ));
1031                false
1032            }
1033        };
1034        let findings_after = match self.merge_findings(&target) {
1035            Ok(after) => Some(after),
1036            Err(e) => {
1037                warnings.push(format!(
1038                    "the validation reading after the merge failed ({}); `findings_after` \
1039                     restates the count before the merge and `new_findings` is unknown",
1040                    e.prose_render()
1041                ));
1042                None
1043            }
1044        };
1045        let new_findings: Vec<String> = findings_after
1046            .as_ref()
1047            .map(|after| {
1048                after
1049                    .difference(&findings_before)
1050                    .map(|(id, code)| format!("{id}: {code}"))
1051                    .collect()
1052            })
1053            .unwrap_or_default();
1054        let validation = MergeValidation {
1055            entities: self
1056                .store
1057                .all_entities()
1058                .filter(|e| e.mem == target && !e.stub)
1059                .count(),
1060            findings_before: findings_before.len(),
1061            findings_after: findings_after
1062                .as_ref()
1063                .map_or(findings_before.len(), BTreeSet::len),
1064            new_findings,
1065            all_entities_parse: reread && self.load_errors().len() <= load_errors_before,
1066        };
1067
1068        let target_tip_after = {
1069            let Some(ops) = self.git_branch_ops() else {
1070                unreachable!("checked above");
1071            };
1072            let target_branch = match &self.mounts[target_mount].mount.storage {
1073                MountStorage::GitBranch { branch, .. } => branch.clone(),
1074                _ => unreachable!("the brief refused a target that is not git-backed"),
1075            };
1076            match resolve_sha(&ops, &gitdir, &crate::branch_full_ref(&target_branch)) {
1077                Ok(sha) => sha,
1078                Err(e) => {
1079                    warnings.push(format!(
1080                        "the target tip was not read back after the last commit ({}); \
1081                         `target_tip_after` is the sha of the last commit landed",
1082                        e.prose_render()
1083                    ));
1084                    parent.clone()
1085                }
1086            }
1087        };
1088        debug_assert_eq!(target_tip_after, parent);
1089
1090        Ok(ProposalMergeOutcome {
1091            fork: fork.to_string(),
1092            target,
1093            proposal_id: brief.proposal_id,
1094            merged_by: merger,
1095            target_tip_before: brief.target_tip,
1096            target_tip_after,
1097            merge_commits,
1098            amend_commit,
1099            entities,
1100            record_path: PROPOSAL_RECORD_PATH.to_string(),
1101            validation,
1102            warnings,
1103        })
1104    }
1105
1106    /// The proposal record of `target`: every proposal merged into it,
1107    /// with every disposition. An empty record for a mem no proposal
1108    /// was merged into; `UNKNOWN_MEM` for a mem that is not mounted.
1109    pub fn proposal_list(&mut self, target: &str) -> Result<ProposalRecord, EngineError> {
1110        self.find_mount(target)?;
1111        self.reload_if_stale(Some(target));
1112        Ok(self.read_proposal_record(target)?.unwrap_or_default())
1113    }
1114
1115    /// The integrity and conformance findings of `mem` as a set of
1116    /// `(id, code)`, the whole-store reading the merge compares before
1117    /// and after.
1118    fn merge_findings(&self, mem: &str) -> Result<BTreeSet<(String, String)>, EngineError> {
1119        let mut out = BTreeSet::new();
1120        for f in self
1121            .conformance_findings(mem, None)?
1122            .into_iter()
1123            .chain(self.consistency_findings(mem)?)
1124        {
1125            out.insert((f.id, f.code));
1126        }
1127        Ok(out)
1128    }
1129
1130    /// The create or update that lands `landing` in the target, rehearsed
1131    /// through the gate; `None` when the target already holds exactly
1132    /// this version. Relations the fork dropped are removed from the
1133    /// store's copy of the entity before the update composes, so the
1134    /// composed post-state (which the gate validates: required edges,
1135    /// acyclicity, shapes) is the fork's version, not a union.
1136    fn plan_landing(
1137        &mut self,
1138        target_id: &EntityId,
1139        landing: &Entity,
1140        creates: &HashSet<EntityId>,
1141    ) -> Result<Option<Landing>, EngineError> {
1142        let existing = if creates.contains(target_id) {
1143            None
1144        } else {
1145            self.store.get(target_id).filter(|e| !e.stub).cloned()
1146        };
1147        match self.landing_write_args(
1148            target_id.mem(),
1149            target_id.path(),
1150            landing,
1151            existing.as_ref(),
1152        ) {
1153            LandingWrite::Create(args) => {
1154                match self
1155                    .prepare_create(*args, Some(creates), Vec::new())
1156                    .map_err(|e| e.in_entity(target_id.path(), STAGE_LANDING))?
1157                {
1158                    CreatePrepareOutcome::Prepared(p) => Ok(Some(Landing::Create(p))),
1159                    CreatePrepareOutcome::Done(_) => Ok(None),
1160                }
1161            }
1162            LandingWrite::Update(args) => {
1163                let mut args = *args;
1164                let dropped: Vec<(String, EntityId)> = args
1165                    .relations_unset
1166                    .drain(..)
1167                    .map(|r| (r.rel_type, r.target))
1168                    .collect();
1169                if !dropped.is_empty()
1170                    && let Some(existing) = self.store.get_mut(target_id)
1171                {
1172                    existing.relationships.retain(|r| {
1173                        !dropped
1174                            .iter()
1175                            .any(|(t, id)| *t == r.rel_type && *id == r.target)
1176                    });
1177                }
1178                for (rel_type, to) in &dropped {
1179                    self.store.remove_edge(target_id, to, rel_type);
1180                }
1181                match self
1182                    .prepare_update(args)
1183                    .map_err(|e| e.in_entity(target_id.path(), STAGE_LANDING))?
1184                {
1185                    PrepareOutcome::Prepared(p) => Ok(Some(Landing::Update(p))),
1186                    PrepareOutcome::Done(_) => Ok(None),
1187                }
1188            }
1189        }
1190    }
1191
1192    /// The deletion of `id` in the target, when the target holds it;
1193    /// the write-mem referrers are judged later, against the adopted
1194    /// bodies. Read-only referrers demote the id to a residual stub, as
1195    /// a plain delete does.
1196    fn plan_delete(
1197        &self,
1198        id: &EntityId,
1199        deletions: &HashSet<EntityId>,
1200    ) -> Result<Option<Landing>, EngineError> {
1201        let Some(entity) = self.store.get(id).filter(|e| !e.stub) else {
1202            return Ok(None);
1203        };
1204        let _ = deletions;
1205        let referrers = self.classify_delete_referrers(id);
1206        Ok(Some(Landing::Delete {
1207            id: id.clone(),
1208            file_path: entity.file_path.clone(),
1209            readonly_referrers: referrers.readonly_referrers,
1210        }))
1211    }
1212
1213    /// The update that lands the owner's final body over the landed
1214    /// entity: the body's sections replace the landed ones (a landed
1215    /// section the body lacks is unset), its metadata sets the fields
1216    /// it names (a field it omits keeps the landed value, as a create
1217    /// keeps a default), its relations (when given) replace the landed
1218    /// ones. A title that differs refuses: a title change is a rename.
1219    /// `None` when the body restates the landed version.
1220    fn plan_amend(
1221        &mut self,
1222        id: &EntityId,
1223        body: &DispositionBody,
1224    ) -> Result<Option<PreparedUpdate>, EngineError> {
1225        let Some(existing) = self.store.get(id).filter(|e| !e.stub).cloned() else {
1226            return Err(EngineError::NotFound { id: id.to_string() });
1227        };
1228        if let Some(title) = body.title.as_deref().map(str::trim)
1229            && !title.is_empty()
1230            && title != existing.title
1231        {
1232            return Err(EngineError::InvalidInput(format!(
1233                "dispositions.{}.body.title is '{title}' and the landed title is '{}': a title \
1234                 change is a rename (`memstead rename`), not a merge",
1235                id.path(),
1236                existing.title
1237            )));
1238        }
1239        let sections_unset: Vec<String> = existing
1240            .sections
1241            .keys()
1242            .filter(|k| k.as_str() != "relationships" && !body.sections.contains_key(*k))
1243            .cloned()
1244            .collect();
1245        let mut declare_relations: Vec<crate::ops::RelateArg> = Vec::new();
1246        if let Some(relations) = &body.relations {
1247            let wanted: Vec<(String, EntityId, Option<String>)> = relations
1248                .iter()
1249                .map(|r| {
1250                    let (resolved, _) = self
1251                        .resolve_entity_id(&EntityId(r.target.clone()))
1252                        .unwrap_or((EntityId(r.target.clone()), None));
1253                    (r.rel_type.clone(), resolved, r.description.clone())
1254                })
1255                .collect();
1256            let dropped: Vec<(String, EntityId)> = existing
1257                .relationships
1258                .iter()
1259                .filter(|x| {
1260                    !wanted
1261                        .iter()
1262                        .any(|(t, id, _)| *t == x.rel_type && *id == x.target)
1263                })
1264                .map(|x| (x.rel_type.clone(), x.target.clone()))
1265                .collect();
1266            if let Some(e) = self.store.get_mut(id) {
1267                e.relationships.retain(|r| {
1268                    !dropped
1269                        .iter()
1270                        .any(|(t, id)| *t == r.rel_type && *id == r.target)
1271                });
1272            }
1273            for (rel_type, to) in &dropped {
1274                self.store.remove_edge(id, to, rel_type);
1275            }
1276            for (rel_type, target, description) in wanted {
1277                if !existing
1278                    .relationships
1279                    .iter()
1280                    .any(|x| x.rel_type == rel_type && x.target == target)
1281                {
1282                    declare_relations.push(crate::ops::RelateArg {
1283                        target,
1284                        rel_type,
1285                        description,
1286                    });
1287                }
1288            }
1289        }
1290        let args = crate::UpdateEntityArgs {
1291            id: id.clone(),
1292            expected_hash: None,
1293            sections: body.sections.clone(),
1294            append_sections: Default::default(),
1295            patch_sections: Default::default(),
1296            sections_unset,
1297            metadata: body.metadata.clone(),
1298            metadata_unset: Vec::new(),
1299            dry_run: false,
1300            declare_relations,
1301            anchors: Vec::new(),
1302            anchors_unset: Vec::new(),
1303            relations_unset: Vec::new(),
1304        };
1305        match self
1306            .prepare_update(args)
1307            .map_err(|e| e.in_entity(id.path(), STAGE_AMEND))?
1308        {
1309            PrepareOutcome::Prepared(p) => Ok(Some(p)),
1310            PrepareOutcome::Done(_) => Ok(None),
1311        }
1312    }
1313
1314    /// Roll a failed merge back so nothing of it stands: every pending
1315    /// buffer discarded and the store snapshot restored; when a commit
1316    /// of this merge already landed (`landed` is the branch's tip then),
1317    /// the target branch moved back to `target_tip`, the tip the merge
1318    /// was pinned to (every commit above it is this merge's own, each
1319    /// parent-pinned, so no other writer's work sits between), and the
1320    /// target re-read from its backend. Returns `error`, the failure
1321    /// that triggered the unwind, unless the branch could not be moved
1322    /// back: then the landed commits stand and the error names both.
1323    fn unwind_merge(
1324        &mut self,
1325        target: &str,
1326        target_tip: &str,
1327        landed: Option<&str>,
1328        snapshot: &crate::store::Store,
1329        error: EngineError,
1330    ) -> EngineError {
1331        self.discard_all_pending();
1332        self.store = snapshot.clone();
1333        let Some(landed) = landed else {
1334            return error;
1335        };
1336        match self.branch_reset(target, target_tip, Some(landed)) {
1337            Ok(_) => {
1338                let _ = self.reload_one_mem(target);
1339                error
1340            }
1341            Err(reset) => {
1342                let _ = self.reload_one_mem(target);
1343                EngineError::Backend(crate::backend::BackendError::Other(format!(
1344                    "{}; the merge commits already on '{target}' (tip {landed}) could not be \
1345                     moved back to {target_tip} and stand: {reset}",
1346                    error.prose_render()
1347                )))
1348            }
1349        }
1350    }
1351}