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 rejected: BTreeSet<&str> = slots
414 .iter()
415 .filter(|s| s.disposition == DISPOSITION_REJECT)
416 .map(|s| s.entry.slug.as_str())
417 .collect();
418 for slot in slots
419 .iter()
420 .filter(|s| s.disposition != DISPOSITION_REJECT)
421 .filter(|s| s.entry.status != ProposalChange::Deleted)
422 {
423 let slug = slot.entry.slug.as_str();
424 let edges: Vec<(String, EntityId)> =
427 match slot.body.as_ref().and_then(|b| b.relations.as_ref()) {
428 Some(relations) => relations
429 .iter()
430 .map(|r| (r.rel_type.clone(), EntityId::canonical(&r.target)))
431 .collect(),
432 None => versions[slug]
433 .relationships
434 .iter()
435 .map(|r| (r.rel_type.clone(), r.target.clone()))
436 .collect(),
437 };
438 for (rel_type, to) in edges {
439 if to.mem() == target && rejected.contains(to.path()) && !self.target_holds(&to) {
440 return Err(EngineError::ProposalLinksRejected {
441 fork: fork.to_string(),
442 slug: slug.to_string(),
443 rel_type,
444 target: to.path().to_string(),
445 });
446 }
447 }
448 }
449 let creates: HashSet<EntityId> = versions
453 .keys()
454 .map(|slug| EntityId::new(&target, slug))
455 .filter(|id| !self.target_holds(id))
456 .collect();
457 for id in &creates {
458 let landing = &versions[id.path()];
459 let mut skeleton = make_stub(id, crate::entity::StubKind::ForwardReference);
460 skeleton.stub = false;
461 skeleton.stub_kind = None;
462 skeleton.entity_type = landing.entity_type.clone();
463 skeleton.title = landing.title.clone();
464 self.store.upsert(id.clone(), skeleton);
465 }
466 let deletions: HashSet<EntityId> = slots
467 .iter()
468 .filter(|s| s.disposition == DISPOSITION_ADOPT)
469 .filter_map(|s| match s.entry.status {
470 ProposalChange::Deleted => Some(EntityId::new(&target, &s.entry.slug)),
471 ProposalChange::Renamed => s
472 .entry
473 .renamed_from
474 .as_deref()
475 .map(|from| EntityId::new(&target, from)),
476 _ => None,
477 })
478 .collect();
479 let prepared: Result<(), EngineError> = (|| {
480 for slot in slots.iter().filter(|s| s.disposition != DISPOSITION_REJECT) {
481 let slug = slot.entry.slug.as_str();
482 let target_id = EntityId::new(&target, slug);
483 let mut landings: Vec<Landing> = Vec::new();
484 match slot.entry.status {
485 ProposalChange::Deleted => {
486 if let Some(l) = self.plan_delete(&target_id, &deletions)? {
487 landings.push(l);
488 } else {
489 noops.push(slug.to_string());
490 }
491 }
492 _ => {
493 let landing = &versions[slug];
494 match self.plan_landing(&target_id, landing, &creates)? {
495 Some(l) => landings.push(l),
496 None => noops.push(slug.to_string()),
497 }
498 if slot.entry.status == ProposalChange::Renamed
499 && let Some(from) = slot.entry.renamed_from.as_deref()
500 && let Some(l) =
501 self.plan_delete(&EntityId::new(&target, from), &deletions)?
502 {
503 landings.push(l);
504 }
505 }
506 }
507 let (proposer, role) = proposers[slug].clone();
508 adopted.push(Adopted {
509 slug: slug.to_string(),
510 proposer,
511 role,
512 landings,
513 amend: slot.body.clone(),
514 });
515 }
516 Ok(())
517 })();
518 if let Err(e) = prepared {
519 self.store = store_snapshot;
520 self.discard_all_pending();
521 return Err(e);
522 }
523
524 let applied: Result<(), EngineError> = (|| {
527 let fallback = engine_fallback_type();
528 for a in &adopted {
529 for l in &a.landings {
530 match l {
531 Landing::Create(p) => {
532 let parsed = parse_markdown(
533 &p.markdown,
534 &p.file_path,
535 p.type_def.as_ref(),
536 &p.mem,
537 )
538 .map_err(|e| EngineError::ParseAfterWrite(e.to_string()))?;
539 push_entities_into_store(
540 &mut self.store,
541 vec![parsed],
542 fallback.as_ref(),
543 None,
544 );
545 }
546 Landing::Update(p) => {
547 self.apply_prepared_to_store(p)?;
548 }
549 Landing::Delete { .. } => {}
550 }
551 }
552 }
553 crate::entity::store_builder::remap_alias_target_edge_sources(
554 &mut self.store,
555 &self.schemas,
556 );
557 for a in &adopted {
558 for l in &a.landings {
559 if let Landing::Delete { id, .. } = l {
560 let referrers = self.classify_delete_referrers(id);
561 let blocking: Vec<_> = referrers
562 .write_referrers
563 .into_iter()
564 .filter(|r| !deletions.contains(&EntityId(r.from_id.clone())))
565 .collect();
566 if !blocking.is_empty() {
567 return Err(EngineError::HasIncomingRefs {
568 id: id.to_string(),
569 referrers: blocking,
570 });
571 }
572 }
573 }
574 }
575 Ok(())
576 })();
577 if let Err(e) = applied {
578 self.store = store_snapshot;
579 self.discard_all_pending();
580 return Err(e);
581 }
582
583 let amends: Result<Vec<PreparedUpdate>, EngineError> = (|| {
587 let mut prepared: Vec<PreparedUpdate> = Vec::new();
588 for a in &adopted {
589 if let Some(body) = &a.amend
590 && let Some(p) = self.plan_amend(&EntityId::new(&target, &a.slug), body)?
591 {
592 prepared.push(p);
593 }
594 }
595 Ok(prepared)
596 })();
597 let amends = match amends {
598 Ok(p) => p,
599 Err(e) => {
600 self.store = store_snapshot;
601 self.discard_all_pending();
602 return Err(e);
603 }
604 };
605
606 let description = crate::vcs::normalise_identity(Some(&file.description))
610 .or_else(|| crate::vcs::normalise_identity(note));
611 let mut record = self.read_proposal_record(&target)?.unwrap_or_default();
612 let mut distinct_proposers: Vec<String> = Vec::new();
615 for a in &adopted {
616 if !distinct_proposers.contains(&a.proposer) {
617 distinct_proposers.push(a.proposer.clone());
618 }
619 }
620 let mut recorded_proposers: Vec<String> = Vec::new();
623 for slot in &slots {
624 if let Some((identity, _)) = proposers.get(&slot.entry.slug)
625 && !recorded_proposers.contains(identity)
626 {
627 recorded_proposers.push(identity.clone());
628 }
629 }
630 record.proposals.push(ProposalRecordEntry {
631 id: brief.proposal_id.clone(),
632 proposer: (!recorded_proposers.is_empty()).then(|| recorded_proposers.join(", ")),
633 ancestor: brief.ancestor.clone(),
634 base: brief.base.clone(),
635 target_tip: brief.target_tip.clone(),
636 merged_by: Some(merger.clone()),
637 at: self.now_iso(),
638 description,
639 entities: slots
640 .iter()
641 .map(|s| {
642 (s.entry.slug.clone(), {
643 let lands_a_body = adopted
662 .iter()
663 .find(|a| a.slug == s.entry.slug)
664 .is_some_and(|a| {
665 a.landings.iter().any(|l| {
666 !matches!(l, Landing::Delete { .. })
667 && l.id() == &EntityId::new(&target, &s.entry.slug)
668 })
669 });
670 let landed_sections = (s.disposition == DISPOSITION_ADOPT && lands_a_body)
671 .then(|| self.landed_section_marks(&target, &s.entry.slug))
672 .flatten();
673 RecordedDisposition {
674 disposition: s.disposition.to_string(),
675 reason: s.reason.clone(),
676 content_hash: s.entry.content_hash.clone(),
677 landed_sections,
678 }
679 })
680 })
681 .collect(),
682 });
683 let record_bytes = record.to_bytes();
684
685 let mut merge_commits: Vec<MergeCommit> = Vec::new();
687 let mut parent = brief.target_tip.clone();
688 let mut landed_any = false;
689 let mut created_ids: HashSet<EntityId> = HashSet::new();
690 let mut deleted_ids: Vec<(EntityId, Vec<EntityId>)> = Vec::new();
691 for (i, proposer) in distinct_proposers.iter().enumerate() {
692 let group: Vec<&Adopted> = adopted.iter().filter(|a| &a.proposer == proposer).collect();
693 let last_group = i + 1 == distinct_proposers.len();
694 let staged: Result<(Vec<String>, Vec<String>), EngineError> = (|| {
695 let backend = self.mounts[target_mount].backend.as_ref();
696 let mut ids: Vec<String> = Vec::new();
697 let mut created: Vec<String> = Vec::new();
698 for a in &group {
699 for l in &a.landings {
700 match l {
701 Landing::Create(p) => {
702 self.stage_prepared_create(p)?;
703 let rows = self.entity_anchors(&EntityId::new(fork, &a.slug));
704 stage_anchors_replace(backend, &p.id, rows)?;
705 created.push(p.id.to_string());
706 }
707 Landing::Update(p) => {
708 self.stage_prepared_update(p)?;
709 let rows = self.entity_anchors(&EntityId::new(fork, &a.slug));
710 stage_anchors_replace(backend, &p.id, rows)?;
711 }
712 Landing::Delete { id, file_path, .. } => {
713 backend.delete_entity(Path::new(file_path))?;
714 stage_anchors_removal(backend, id)?;
715 }
716 }
717 ids.push(l.id().to_string());
718 }
719 }
720 if last_group {
721 backend.write_entity(Path::new(PROPOSAL_RECORD_PATH), &record_bytes)?;
722 }
723 Ok((ids, created))
724 })();
725 let (ids, created) = match staged {
726 Ok(v) => v,
727 Err(e) => {
728 return Err(self.unwind_merge(
729 &target,
730 &brief.target_tip,
731 landed_any.then_some(parent.as_str()),
732 &store_snapshot,
733 e,
734 ));
735 }
736 };
737 let role = group.first().map(|a| a.role).unwrap_or_default();
743 let mut ctx = CommitContext::new(
744 Some(MERGE_TOOL),
745 actor,
746 client.cloned(),
747 note.map(String::from),
748 role,
749 Some(proposer.clone()),
750 );
751 ctx.entity_ids = Some(ids.clone());
752 ctx.proposal = Some(ProposalTrailers {
753 proposal: brief.proposal_id.clone(),
754 merged_by: merger.clone(),
755 created: created.clone(),
756 });
757 let subject = format!("memstead: proposal-merge {}", brief.proposal_id);
758 let sha = match self.mounts[target_mount]
759 .backend
760 .commit_with_expected_parent(&subject, &ctx, Some(&parent))
761 {
762 Ok(sha) => sha,
763 Err(e) => {
764 let e = match e {
765 crate::backend::BackendError::ParentMismatch { expected, actual } => {
766 EngineError::ProposalStale {
767 fork: fork.to_string(),
768 side: "target".to_string(),
769 recorded: expected,
770 current: actual,
771 }
772 }
773 other => other.into(),
774 };
775 return Err(self.unwind_merge(
776 &target,
777 &brief.target_tip,
778 landed_any.then_some(parent.as_str()),
779 &store_snapshot,
780 e,
781 ));
782 }
783 };
784 landed_any = true;
785 self.record_self_write(target_mount, &sha);
786 for a in &group {
787 for l in &a.landings {
788 match l {
789 Landing::Delete {
790 id,
791 readonly_referrers,
792 ..
793 } => deleted_ids.push((id.clone(), readonly_referrers.clone())),
794 l if l.is_create() => {
795 created_ids.insert(l.id().clone());
796 }
797 _ => {}
798 }
799 }
800 }
801 parent = sha.clone();
802 merge_commits.push(MergeCommit {
803 sha,
804 identity: proposer.clone(),
805 entities: ids,
806 });
807 }
808
809 if distinct_proposers.is_empty() {
818 let staged: Result<(), EngineError> = (|| {
819 let backend = self.mounts[target_mount].backend.as_ref();
820 backend.write_entity(Path::new(PROPOSAL_RECORD_PATH), &record_bytes)?;
821 Ok(())
822 })();
823 if let Err(e) = staged {
824 return Err(self.unwind_merge(
825 &target,
826 &brief.target_tip,
827 None,
828 &store_snapshot,
829 e,
830 ));
831 }
832 let mut ctx = self.commit_context(
833 Some(MERGE_TOOL),
834 actor,
835 client.cloned(),
836 note.map(String::from),
837 );
838 ctx.entity_ids = Some(Vec::new());
839 ctx.proposal = Some(ProposalTrailers {
840 proposal: brief.proposal_id.clone(),
841 merged_by: merger.clone(),
842 created: Vec::new(),
843 });
844 let subject = format!("memstead: proposal-merge {}", brief.proposal_id);
845 let sha = match self.mounts[target_mount]
846 .backend
847 .commit_with_expected_parent(&subject, &ctx, Some(&parent))
848 {
849 Ok(sha) => sha,
850 Err(e) => {
851 let e = match e {
852 crate::backend::BackendError::ParentMismatch { expected, actual } => {
853 EngineError::ProposalStale {
854 fork: fork.to_string(),
855 side: "target".to_string(),
856 recorded: expected,
857 current: actual,
858 }
859 }
860 other => other.into(),
861 };
862 return Err(self.unwind_merge(
863 &target,
864 &brief.target_tip,
865 None,
866 &store_snapshot,
867 e,
868 ));
869 }
870 };
871 self.record_self_write(target_mount, &sha);
872 parent = sha.clone();
873 merge_commits.push(MergeCommit {
874 sha,
875 identity: merger.clone(),
876 entities: Vec::new(),
877 });
878 }
879
880 for (id, readonly_referrers) in &deleted_ids {
882 if readonly_referrers.is_empty() {
883 self.store.remove(id);
884 } else {
885 self.store.remove_edges_from(id);
886 self.store.upsert(
887 id.clone(),
888 make_stub(
889 id,
890 crate::entity::StubKind::Residual {
891 since_commit: parent.clone(),
892 readonly_referrers: readonly_referrers.clone(),
893 },
894 ),
895 );
896 }
897 }
898 let mut out_of_batch: Vec<(EntityId, crate::entity::StubKind)> = Vec::new();
899 for a in &adopted {
900 for l in &a.landings {
901 if let Landing::Create(p) = l {
902 for t in &p.relation_targets {
903 if !self.store.contains(t) {
904 out_of_batch.push((t.clone(), deferred_verified_stub_kind(self, t)?));
905 }
906 }
907 }
908 }
909 }
910 for (t, kind) in out_of_batch {
911 self.store.upsert(t.clone(), make_stub(&t, kind));
912 }
913 gc_orphan_stubs(&mut self.store);
914 let _ = self.stamp_mutation_versions(target_mount);
915 self.invalidate_communities();
916 self.invalidate_search_indexes();
917
918 let mut warnings: Vec<String> = Vec::new();
922 let mut amend_commit: Option<MergeCommit> = None;
923 if !amends.is_empty() {
924 let staged: Result<(), EngineError> = (|| {
925 for p in &amends {
926 self.stage_prepared_update(p)?;
927 }
928 Ok(())
929 })();
930 if let Err(e) = staged {
931 return Err(self.unwind_merge(
932 &target,
933 &brief.target_tip,
934 Some(&parent),
935 &store_snapshot,
936 e,
937 ));
938 }
939 let ids: Vec<String> = amends.iter().map(|p| p.id.to_string()).collect();
940 let mut ctx = self.commit_context(
941 Some(MERGE_TOOL),
942 actor,
943 client.cloned(),
944 note.map(String::from),
945 );
946 ctx.entity_ids = Some(ids.clone());
947 ctx.proposal = Some(ProposalTrailers {
948 proposal: brief.proposal_id.clone(),
949 merged_by: merger.clone(),
950 created: Vec::new(),
951 });
952 let subject = format!("memstead: proposal-amend {}", brief.proposal_id);
953 let sha = match self.mounts[target_mount]
954 .backend
955 .commit_with_expected_parent(&subject, &ctx, Some(&parent))
956 {
957 Ok(sha) => sha,
958 Err(e) => {
959 return Err(self.unwind_merge(
960 &target,
961 &brief.target_tip,
962 Some(&parent),
963 &store_snapshot,
964 e.into(),
965 ));
966 }
967 };
968 self.record_self_write(target_mount, &sha);
969 for p in &amends {
970 if let Err(e) = self.apply_prepared_to_store(p) {
971 warnings.push(format!(
972 "{}: the store's copy of the amended entity was not refreshed ({}); \
973 the re-read after the merge serves the landed body",
974 p.id,
975 e.prose_render()
976 ));
977 }
978 }
979 let _ = self.stamp_mutation_versions(target_mount);
980 self.invalidate_communities();
981 self.invalidate_search_indexes();
982 parent = sha.clone();
983 amend_commit = Some(MergeCommit {
984 sha,
985 identity: merger.clone(),
986 entities: ids,
987 });
988 }
989
990 let method = format!("proposal {}", brief.proposal_id);
993 let mut entities: Vec<MergedEntity> = Vec::with_capacity(slots.len());
994 for slot in &slots {
995 let slug = slot.entry.slug.as_str();
996 let target_id = EntityId::new(&target, slug);
997 let plan = adopted.iter().find(|a| a.slug == slug);
998 let amended = amends.iter().any(|p| p.id == target_id);
999 let (action, proposer) = match plan {
1000 None => (
1001 "none",
1002 proposers.get(slug).map(|(identity, _)| identity.clone()),
1003 ),
1004 Some(a) => {
1005 let action = if a.landings.iter().any(|l| l.is_create()) {
1006 "created"
1007 } else if amended || a.landings.iter().any(|l| matches!(l, Landing::Update(_)))
1008 {
1009 "updated"
1010 } else if a
1011 .landings
1012 .iter()
1013 .any(|l| matches!(l, Landing::Delete { .. }))
1014 {
1015 "deleted"
1016 } else {
1017 "noop"
1018 };
1019 (action, Some(a.proposer.clone()))
1020 }
1021 };
1022 let exists = self.target_holds(&target_id);
1023 let content_hash = exists.then(|| {
1024 self.store
1025 .get(&target_id)
1026 .map(|e| e.content_hash.clone())
1027 .unwrap_or_default()
1028 });
1029 let check_recorded = exists
1030 && matches!(action, "created" | "updated")
1031 && match self.record_check(
1032 &target,
1033 target_id.as_ref(),
1034 Verdict::Ok,
1035 CheckKind::Verification,
1036 Some(&method),
1037 actor,
1038 client,
1039 ) {
1040 Ok(_) => true,
1041 Err(e) => {
1042 warnings.push(format!(
1043 "{target_id}: the verification check was not recorded ({}); the \
1044 entity reads as never checked until `memstead check` records one",
1045 e.prose_render()
1046 ));
1047 false
1048 }
1049 };
1050 entities.push(MergedEntity {
1051 slug: slug.to_string(),
1052 target_id: target_id.to_string(),
1053 disposition: slot.disposition.to_string(),
1054 action: action.to_string(),
1055 proposer,
1056 content_hash,
1057 check_recorded,
1058 });
1059 }
1060 let _ = noops;
1061 let _ = created_ids;
1062
1063 let reread = match self.reload_one_mem(&target) {
1065 Ok(_) => true,
1066 Err(e) => {
1067 warnings.push(format!(
1068 "the target was not re-read from its backend after the merge ({}); run \
1069 `memstead reload --mem {target}`",
1070 e.prose_render()
1071 ));
1072 false
1073 }
1074 };
1075 let findings_after = match self.merge_findings(&target) {
1076 Ok(after) => Some(after),
1077 Err(e) => {
1078 warnings.push(format!(
1079 "the validation reading after the merge failed ({}); `findings_after` \
1080 restates the count before the merge and `new_findings` is unknown",
1081 e.prose_render()
1082 ));
1083 None
1084 }
1085 };
1086 let new_findings: Vec<String> = findings_after
1087 .as_ref()
1088 .map(|after| {
1089 after
1090 .difference(&findings_before)
1091 .map(|(id, code)| format!("{id}: {code}"))
1092 .collect()
1093 })
1094 .unwrap_or_default();
1095 let validation = MergeValidation {
1096 entities: self
1097 .store
1098 .all_entities()
1099 .filter(|e| e.mem == target && !e.stub)
1100 .count(),
1101 findings_before: findings_before.len(),
1102 findings_after: findings_after
1103 .as_ref()
1104 .map_or(findings_before.len(), BTreeSet::len),
1105 new_findings,
1106 all_entities_parse: reread && self.load_errors().len() <= load_errors_before,
1107 };
1108
1109 let target_tip_after = {
1110 let Some(ops) = self.git_branch_ops() else {
1111 unreachable!("checked above");
1112 };
1113 let target_branch = match &self.mounts[target_mount].mount.storage {
1114 MountStorage::GitBranch { branch, .. } => branch.clone(),
1115 _ => unreachable!("the brief refused a target that is not git-backed"),
1116 };
1117 match resolve_sha(&ops, &gitdir, &crate::branch_full_ref(&target_branch)) {
1118 Ok(sha) => sha,
1119 Err(e) => {
1120 warnings.push(format!(
1121 "the target tip was not read back after the last commit ({}); \
1122 `target_tip_after` is the sha of the last commit landed",
1123 e.prose_render()
1124 ));
1125 parent.clone()
1126 }
1127 }
1128 };
1129 debug_assert_eq!(target_tip_after, parent);
1130
1131 Ok(ProposalMergeOutcome {
1132 fork: fork.to_string(),
1133 target,
1134 proposal_id: brief.proposal_id,
1135 merged_by: merger,
1136 target_tip_before: brief.target_tip,
1137 target_tip_after,
1138 merge_commits,
1139 amend_commit,
1140 entities,
1141 record_path: PROPOSAL_RECORD_PATH.to_string(),
1142 validation,
1143 warnings,
1144 })
1145 }
1146
1147 pub fn proposal_list(&mut self, target: &str) -> Result<ProposalRecord, EngineError> {
1151 self.find_mount(target)?;
1152 self.reload_if_stale(Some(target));
1153 Ok(self.read_proposal_record(target)?.unwrap_or_default())
1154 }
1155
1156 fn merge_findings(&self, mem: &str) -> Result<BTreeSet<(String, String)>, EngineError> {
1160 let mut out = BTreeSet::new();
1161 for f in self
1162 .conformance_findings(mem, None)?
1163 .into_iter()
1164 .chain(self.consistency_findings(mem)?)
1165 {
1166 out.insert((f.id, f.code));
1167 }
1168 Ok(out)
1169 }
1170
1171 fn plan_landing(
1178 &mut self,
1179 target_id: &EntityId,
1180 landing: &Entity,
1181 creates: &HashSet<EntityId>,
1182 ) -> Result<Option<Landing>, EngineError> {
1183 let existing = if creates.contains(target_id) {
1184 None
1185 } else {
1186 self.store.get(target_id).filter(|e| !e.stub).cloned()
1187 };
1188 match self.landing_write_args(
1189 target_id.mem(),
1190 target_id.path(),
1191 landing,
1192 existing.as_ref(),
1193 ) {
1194 LandingWrite::Create(args) => {
1195 match self
1196 .prepare_create(*args, Some(creates), Vec::new())
1197 .map_err(|e| e.in_entity(target_id.path(), STAGE_LANDING))?
1198 {
1199 CreatePrepareOutcome::Prepared(p) => Ok(Some(Landing::Create(p))),
1200 CreatePrepareOutcome::Done(_) => Ok(None),
1201 }
1202 }
1203 LandingWrite::Update(args) => {
1204 let mut args = *args;
1205 let dropped: Vec<(String, EntityId)> = args
1206 .relations_unset
1207 .drain(..)
1208 .map(|r| (r.rel_type, r.target))
1209 .collect();
1210 if !dropped.is_empty()
1211 && let Some(existing) = self.store.get_mut(target_id)
1212 {
1213 existing.relationships.retain(|r| {
1214 !dropped
1215 .iter()
1216 .any(|(t, id)| *t == r.rel_type && *id == r.target)
1217 });
1218 }
1219 for (rel_type, to) in &dropped {
1220 self.store.remove_edge(target_id, to, rel_type);
1221 }
1222 match self
1223 .prepare_update(args)
1224 .map_err(|e| e.in_entity(target_id.path(), STAGE_LANDING))?
1225 {
1226 PrepareOutcome::Prepared(p) => Ok(Some(Landing::Update(p))),
1227 PrepareOutcome::Done(_) => Ok(None),
1228 }
1229 }
1230 }
1231 }
1232
1233 fn plan_delete(
1238 &self,
1239 id: &EntityId,
1240 deletions: &HashSet<EntityId>,
1241 ) -> Result<Option<Landing>, EngineError> {
1242 let Some(entity) = self.store.get(id).filter(|e| !e.stub) else {
1243 return Ok(None);
1244 };
1245 let _ = deletions;
1246 let referrers = self.classify_delete_referrers(id);
1247 Ok(Some(Landing::Delete {
1248 id: id.clone(),
1249 file_path: entity.file_path.clone(),
1250 readonly_referrers: referrers.readonly_referrers,
1251 }))
1252 }
1253
1254 fn plan_amend(
1262 &mut self,
1263 id: &EntityId,
1264 body: &DispositionBody,
1265 ) -> Result<Option<PreparedUpdate>, EngineError> {
1266 let Some(existing) = self.store.get(id).filter(|e| !e.stub).cloned() else {
1267 return Err(EngineError::NotFound { id: id.to_string() });
1268 };
1269 if let Some(title) = body.title.as_deref().map(str::trim)
1270 && !title.is_empty()
1271 && title != existing.title
1272 {
1273 return Err(EngineError::InvalidInput(format!(
1274 "dispositions.{}.body.title is '{title}' and the landed title is '{}': a title \
1275 change is a rename (`memstead rename`), not a merge",
1276 id.path(),
1277 existing.title
1278 )));
1279 }
1280 let sections_unset: Vec<String> = existing
1281 .sections
1282 .keys()
1283 .filter(|k| k.as_str() != "relationships" && !body.sections.contains_key(*k))
1284 .cloned()
1285 .collect();
1286 let mut declare_relations: Vec<crate::ops::RelateArg> = Vec::new();
1287 if let Some(relations) = &body.relations {
1288 let wanted: Vec<(String, EntityId, Option<String>)> = relations
1289 .iter()
1290 .map(|r| {
1291 let (resolved, _) = self
1292 .resolve_entity_id(&EntityId(r.target.clone()))
1293 .unwrap_or((EntityId(r.target.clone()), None));
1294 (r.rel_type.clone(), resolved, r.description.clone())
1295 })
1296 .collect();
1297 let dropped: Vec<(String, EntityId)> = existing
1298 .relationships
1299 .iter()
1300 .filter(|x| {
1301 !wanted
1302 .iter()
1303 .any(|(t, id, _)| *t == x.rel_type && *id == x.target)
1304 })
1305 .map(|x| (x.rel_type.clone(), x.target.clone()))
1306 .collect();
1307 if let Some(e) = self.store.get_mut(id) {
1308 e.relationships.retain(|r| {
1309 !dropped
1310 .iter()
1311 .any(|(t, id)| *t == r.rel_type && *id == r.target)
1312 });
1313 }
1314 for (rel_type, to) in &dropped {
1315 self.store.remove_edge(id, to, rel_type);
1316 }
1317 for (rel_type, target, description) in wanted {
1318 if !existing
1319 .relationships
1320 .iter()
1321 .any(|x| x.rel_type == rel_type && x.target == target)
1322 {
1323 declare_relations.push(crate::ops::RelateArg {
1324 target,
1325 rel_type,
1326 description,
1327 });
1328 }
1329 }
1330 }
1331 let args = crate::UpdateEntityArgs {
1332 id: id.clone(),
1333 expected_hash: None,
1334 sections: body.sections.clone(),
1335 append_sections: Default::default(),
1336 patch_sections: Default::default(),
1337 sections_unset,
1338 metadata: body.metadata.clone(),
1339 metadata_unset: Vec::new(),
1340 dry_run: false,
1341 declare_relations,
1342 anchors: Vec::new(),
1343 anchors_unset: Vec::new(),
1344 relations_unset: Vec::new(),
1345 };
1346 match self
1347 .prepare_update(args)
1348 .map_err(|e| e.in_entity(id.path(), STAGE_AMEND))?
1349 {
1350 PrepareOutcome::Prepared(p) => Ok(Some(p)),
1351 PrepareOutcome::Done(_) => Ok(None),
1352 }
1353 }
1354
1355 fn unwind_merge(
1365 &mut self,
1366 target: &str,
1367 target_tip: &str,
1368 landed: Option<&str>,
1369 snapshot: &crate::store::Store,
1370 error: EngineError,
1371 ) -> EngineError {
1372 self.discard_all_pending();
1373 self.store = snapshot.clone();
1374 let Some(landed) = landed else {
1375 return error;
1376 };
1377 match self.branch_reset(target, target_tip, Some(landed)) {
1378 Ok(_) => {
1379 let _ = self.reload_one_mem(target);
1380 error
1381 }
1382 Err(reset) => {
1383 let _ = self.reload_one_mem(target);
1384 EngineError::Backend(crate::backend::BackendError::Other(format!(
1385 "{}; the merge commits already on '{target}' (tip {landed}) could not be \
1386 moved back to {target_tip} and stand: {reset}",
1387 error.prose_render()
1388 )))
1389 }
1390 }
1391 }
1392}