1use 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
69const MERGE_TOOL: &str = "proposal_merge";
71
72const STAGE_LANDING: &str = "landing";
75const STAGE_AMEND: &str = "amend";
78
79enum Landing {
81 Create(PreparedCreate),
82 Update(PreparedUpdate),
83 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
106struct Adopted {
109 slug: String,
110 proposer: String,
111 role: Role,
114 landings: Vec<Landing>,
115 amend: Option<DispositionBody>,
117}
118
119impl Engine {
120 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 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 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 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 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 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(), ¬es)
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 let findings_before = self.merge_findings(&target)?;
369 let load_errors_before = self.load_errors().len();
370
371 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}