1use std::collections::BTreeMap;
23
24use serde::{Deserialize, Serialize};
25
26pub const DISPOSITION_VOCABULARY: &[&str] = &["adopt", "adopt_with_changes", "reject"];
29
30pub const DISPOSITION_ADOPT: &str = "adopt";
32pub const DISPOSITION_ADOPT_WITH_CHANGES: &str = "adopt_with_changes";
35pub const DISPOSITION_REJECT: &str = "reject";
37
38pub const PROPOSAL_RECORD_PATH: &str = ".memstead/proposals.json";
41
42pub const PROPOSAL_RECORD_VERSION: u32 = 1;
44
45#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub struct ProposalBrief {
48 pub fork: String,
50 pub target: String,
52 pub proposal_id: String,
55 pub ancestor: String,
57 pub base: String,
60 pub base_is_ancestor: bool,
63 pub fork_tip: String,
65 pub target_tip: String,
67 pub summary: ProposalSummary,
69 pub entries: Vec<ProposalEntry>,
71 #[serde(default)]
80 pub description: String,
81 pub dispositions: BTreeMap<String, DispositionSlot>,
85}
86
87#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
89pub struct ProposalSummary {
90 pub added: usize,
91 pub modified: usize,
92 pub deleted: usize,
93 pub renamed: usize,
94 pub conflicts: usize,
95 pub precheck_failures: usize,
96 pub re_proposals: usize,
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum ProposalChange {
103 Added,
104 Modified,
105 Deleted,
106 Renamed,
107}
108
109impl ProposalChange {
110 pub fn as_wire(self) -> &'static str {
112 match self {
113 ProposalChange::Added => "added",
114 ProposalChange::Modified => "modified",
115 ProposalChange::Deleted => "deleted",
116 ProposalChange::Renamed => "renamed",
117 }
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
123pub struct ProposalEntry {
124 pub slug: String,
127 pub fork_id: String,
129 pub target_id: String,
131 pub status: ProposalChange,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub renamed_from: Option<String>,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub title: Option<String>,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub entity_type: Option<String>,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub content_hash: Option<String>,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub fork_delta: Option<VersionDelta>,
154 #[serde(default, skip_serializing_if = "Vec::is_empty")]
157 pub referrers: Vec<Referrer>,
158 #[serde(default, skip_serializing_if = "Vec::is_empty")]
161 pub anchors: Vec<AnchorRow>,
162 pub precheck: Precheck,
164 #[serde(default, skip_serializing_if = "Option::is_none")]
166 pub conflict: Option<Conflict>,
167 #[serde(default, skip_serializing_if = "Vec::is_empty")]
170 pub re_proposal: Vec<ReProposalMark>,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub base_body: Option<String>,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub fork_body: Option<String>,
178}
179
180#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
182pub struct VersionDelta {
183 pub title_differs: bool,
184 pub entity_type_differs: bool,
185 pub sections: Vec<String>,
188 pub metadata: Vec<String>,
191 pub relationships_differ: bool,
192}
193
194impl VersionDelta {
195 pub fn is_empty(&self) -> bool {
197 !self.title_differs
198 && !self.entity_type_differs
199 && self.sections.is_empty()
200 && self.metadata.is_empty()
201 && !self.relationships_differ
202 }
203}
204
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207pub struct Referrer {
208 pub id: String,
209 pub rel_type: String,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214pub struct AnchorRow {
215 pub artifact: String,
216 pub grain: String,
217 pub class: String,
218 #[serde(default, skip_serializing_if = "Option::is_none")]
219 pub span: Option<String>,
220 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub last_state: Option<String>,
225 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub last_observed_at: Option<String>,
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233pub struct Precheck {
234 pub outcome: PrecheckOutcome,
235 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub operation: Option<String>,
238 #[serde(default, skip_serializing_if = "Vec::is_empty")]
240 pub failures: Vec<PrecheckFailure>,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub note: Option<String>,
244}
245
246impl Precheck {
247 pub fn clean(operation: &str) -> Self {
248 Self {
249 outcome: PrecheckOutcome::Clean,
250 operation: Some(operation.to_string()),
251 failures: Vec::new(),
252 note: None,
253 }
254 }
255
256 pub fn failed(operation: &str, failures: Vec<PrecheckFailure>) -> Self {
257 Self {
258 outcome: PrecheckOutcome::Failed,
259 operation: Some(operation.to_string()),
260 failures,
261 note: None,
262 }
263 }
264
265 pub fn not_run(note: &str) -> Self {
266 Self {
267 outcome: PrecheckOutcome::NotRun,
268 operation: None,
269 failures: Vec::new(),
270 note: Some(note.to_string()),
271 }
272 }
273}
274
275#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
276#[serde(rename_all = "snake_case")]
277pub enum PrecheckOutcome {
278 Clean,
279 Failed,
280 NotRun,
281}
282
283impl PrecheckOutcome {
284 pub fn as_wire(self) -> &'static str {
285 match self {
286 PrecheckOutcome::Clean => "clean",
287 PrecheckOutcome::Failed => "failed",
288 PrecheckOutcome::NotRun => "not_run",
289 }
290 }
291}
292
293#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295pub struct PrecheckFailure {
296 pub code: String,
297 pub message: String,
298}
299
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
302pub struct Conflict {
303 pub kind: ConflictKind,
304 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub target_delta: Option<VersionDelta>,
307 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub target_body: Option<String>,
311}
312
313#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
314#[serde(rename_all = "snake_case")]
315pub enum ConflictKind {
316 TargetModified,
319 TargetDeleted,
322 TargetAdded,
324}
325
326impl ConflictKind {
327 pub fn as_wire(self) -> &'static str {
328 match self {
329 ConflictKind::TargetModified => "target_modified",
330 ConflictKind::TargetDeleted => "target_deleted",
331 ConflictKind::TargetAdded => "target_added",
332 }
333 }
334
335 fn describe(self) -> &'static str {
336 match self {
337 ConflictKind::TargetModified => "the target modified this entity since the ancestor",
338 ConflictKind::TargetDeleted => "the target deleted this entity since the ancestor",
339 ConflictKind::TargetAdded => {
340 "the target created an entity with this slug since the ancestor"
341 }
342 }
343 }
344}
345
346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
348pub struct ReProposalMark {
349 pub matched_by: String,
351 pub proposal: String,
353 #[serde(default, skip_serializing_if = "Option::is_none")]
354 pub reason: Option<String>,
355}
356
357#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
359pub struct DispositionSlot {
360 pub disposition: String,
362 pub reason: String,
366 pub accepts: Vec<String>,
369 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub body: Option<serde_json::Value>,
374}
375
376impl DispositionSlot {
377 pub fn skeleton(conflict: bool) -> Self {
379 let accepts = DISPOSITION_VOCABULARY
380 .iter()
381 .filter(|v| !(conflict && **v == DISPOSITION_ADOPT))
382 .map(|v| (*v).to_string())
383 .collect();
384 Self {
385 disposition: String::new(),
386 reason: String::new(),
387 accepts,
388 body: None,
389 }
390 }
391}
392
393#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
403pub struct ProposalRecord {
404 #[serde(default = "default_record_version")]
405 pub version: u32,
406 #[serde(default)]
407 pub proposals: Vec<ProposalRecordEntry>,
408}
409
410fn default_record_version() -> u32 {
411 PROPOSAL_RECORD_VERSION
412}
413
414impl Default for ProposalRecord {
415 fn default() -> Self {
418 Self {
419 version: PROPOSAL_RECORD_VERSION,
420 proposals: Vec::new(),
421 }
422 }
423}
424
425#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
427pub struct ProposalRecordEntry {
428 pub id: String,
430 #[serde(default, skip_serializing_if = "Option::is_none")]
431 pub proposer: Option<String>,
432 #[serde(default)]
433 pub ancestor: String,
434 #[serde(default)]
435 pub base: String,
436 #[serde(default)]
437 pub target_tip: String,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
439 pub merged_by: Option<String>,
440 #[serde(default)]
441 pub at: String,
442 #[serde(default, skip_serializing_if = "Option::is_none")]
447 pub description: Option<String>,
448 #[serde(default)]
451 pub entities: BTreeMap<String, RecordedDisposition>,
452}
453
454#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
456pub struct RecordedDisposition {
457 pub disposition: String,
458 #[serde(default, skip_serializing_if = "Option::is_none")]
461 pub reason: Option<String>,
462 #[serde(default, skip_serializing_if = "Option::is_none")]
463 pub content_hash: Option<String>,
464 #[serde(default, skip_serializing_if = "Option::is_none")]
500 pub landed_sections: Option<BTreeMap<String, String>>,
501}
502
503impl ProposalRecord {
514 pub fn effective_marks(&self, slug: &str) -> Option<BTreeMap<String, String>> {
523 let mut effective = None;
524 for proposal in &self.proposals {
525 let Some(entry) = proposal.entities.get(slug) else {
526 continue;
527 };
528 match entry.landed_sections.as_ref() {
529 Some(sections) if !sections.is_empty() => effective = Some(sections.clone()),
530 Some(_) => {}
533 None if entry.disposition == DISPOSITION_REJECT => {}
534 None => effective = None,
535 }
536 }
537 effective
538 }
539
540 pub fn effective_marks_at(&self, slug: &str) -> Option<usize> {
546 let mut at = None;
547 for (idx, proposal) in self.proposals.iter().enumerate() {
548 let Some(entry) = proposal.entities.get(slug) else {
549 continue;
550 };
551 match entry.landed_sections.as_ref() {
552 Some(sections) if !sections.is_empty() => at = Some(idx),
553 Some(_) => {}
554 None if entry.disposition == DISPOSITION_REJECT => {}
555 None => at = None,
556 }
557 }
558 at
559 }
560
561 pub fn effective_marks_by_slug(&self) -> BTreeMap<String, BTreeMap<String, String>> {
563 let mut out: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
564 for proposal in &self.proposals {
565 for (slug, entry) in &proposal.entities {
566 match entry.landed_sections.as_ref() {
567 Some(sections) if !sections.is_empty() => {
568 out.insert(slug.clone(), sections.clone());
569 }
570 Some(_) => {}
571 None if entry.disposition == DISPOSITION_REJECT => {}
572 None => {
573 out.remove(slug);
574 }
575 }
576 }
577 }
578 out
579 }
580
581 pub fn structural_defect(&self) -> Option<String> {
591 let defective = self.proposals.iter().any(|p| {
592 p.entities
593 .values()
594 .any(|e| e.landed_sections.as_ref().is_some_and(|s| s.is_empty()))
595 });
596 defective.then(|| {
597 format!(
598 "an entry in {PROPOSAL_RECORD_PATH} records an empty `landed_sections` map, \
599 which no engine write produces: which bodies came from a contributor cannot \
600 be read from it"
601 )
602 })
603 }
604}
605
606impl ProposalRecord {
607 pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
610 serde_json::from_slice(bytes)
611 }
612
613 pub fn rejections_matching(
616 &self,
617 slug: &str,
618 content_hash: Option<&str>,
619 ) -> Vec<ReProposalMark> {
620 let mut marks = Vec::new();
621 for proposal in &self.proposals {
622 for (recorded_slug, recorded) in &proposal.entities {
623 if recorded.disposition != DISPOSITION_REJECT {
624 continue;
625 }
626 let by_hash = matches!(
627 (content_hash, recorded.content_hash.as_deref()),
628 (Some(a), Some(b)) if a == b
629 );
630 if by_hash {
631 marks.push(ReProposalMark {
632 matched_by: "content_hash".to_string(),
633 proposal: proposal.id.clone(),
634 reason: recorded.reason.clone(),
635 });
636 } else if recorded_slug == slug {
637 marks.push(ReProposalMark {
638 matched_by: "id".to_string(),
639 proposal: proposal.id.clone(),
640 reason: recorded.reason.clone(),
641 });
642 }
643 }
644 }
645 marks
646 }
647}
648
649pub fn proposal_id(fork: &str, base: &str) -> String {
651 format!("{fork}@{base}")
652}
653
654impl ProposalRecord {
655 pub fn to_bytes(&self) -> Vec<u8> {
658 let mut s = serde_json::to_string_pretty(self).expect("proposal record serialises");
659 s.push('\n');
660 s.into_bytes()
661 }
662}
663
664#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
676pub struct DispositionBody {
677 #[serde(default, skip_serializing_if = "Option::is_none")]
678 pub title: Option<String>,
679 #[serde(default)]
680 pub sections: indexmap::IndexMap<String, String>,
681 #[serde(default)]
682 pub metadata: indexmap::IndexMap<String, String>,
683 #[serde(default, skip_serializing_if = "Option::is_none")]
684 pub relations: Option<Vec<DispositionRelation>>,
685}
686
687#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
689pub struct DispositionRelation {
690 pub target: String,
691 pub rel_type: String,
692 #[serde(default, skip_serializing_if = "Option::is_none")]
693 pub description: Option<String>,
694}
695
696#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
700pub struct ProposalMergeOutcome {
701 pub fork: String,
702 pub target: String,
703 pub proposal_id: String,
704 pub merged_by: String,
706 pub target_tip_before: String,
709 pub target_tip_after: String,
711 pub merge_commits: Vec<MergeCommit>,
714 #[serde(default, skip_serializing_if = "Option::is_none")]
718 pub amend_commit: Option<MergeCommit>,
719 pub entities: Vec<MergedEntity>,
721 pub record_path: String,
723 pub validation: MergeValidation,
725 #[serde(default, skip_serializing_if = "Vec::is_empty")]
733 pub warnings: Vec<MergeWarning>,
734}
735
736#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
740pub struct MergeWarning {
741 pub code: String,
742 pub message: String,
743 pub details: serde_json::Value,
744}
745
746impl MergeWarning {
747 pub fn follow_up_failed(mem: &str, step: &str, detail: String) -> Self {
749 Self::from_hint(&crate::ops::WarningHint::WriteFollowUpFailed {
750 mem: mem.to_string(),
751 step: step.to_string(),
752 detail,
753 })
754 }
755
756 pub fn from_hint(hint: &crate::ops::WarningHint) -> Self {
758 let v = serde_json::to_value(hint).unwrap_or_default();
759 Self {
760 code: v["code"].as_str().unwrap_or_default().to_string(),
761 message: v["message"].as_str().unwrap_or_default().to_string(),
762 details: v["details"].clone(),
763 }
764 }
765}
766
767#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
769pub struct MergeCommit {
770 pub sha: String,
771 pub identity: String,
775 pub entities: Vec<String>,
778}
779
780#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
782pub struct MergedEntity {
783 pub slug: String,
784 pub target_id: String,
785 pub disposition: String,
786 pub action: String,
789 #[serde(default, skip_serializing_if = "Option::is_none")]
794 pub proposer: Option<String>,
795 #[serde(default, skip_serializing_if = "Option::is_none")]
799 pub content_hash: Option<String>,
800 pub check_recorded: bool,
803}
804
805#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
812pub struct MergeValidation {
813 pub entities: usize,
815 pub findings_before: usize,
817 pub findings_after: usize,
819 #[serde(default, skip_serializing_if = "Vec::is_empty")]
822 pub new_findings: Vec<String>,
823 pub all_entities_parse: bool,
827}
828
829impl MergeValidation {
830 pub fn is_clean(&self) -> bool {
833 self.all_entities_parse && self.new_findings.is_empty()
834 }
835}
836
837pub fn render_proposal_merge(o: &ProposalMergeOutcome) -> String {
839 let mut out = String::new();
840 out.push_str(&format!(
841 "# Proposal `{}` merged into `{}`\n\n",
842 o.proposal_id, o.target
843 ));
844 out.push_str(&format!("- Merged by: `{}`\n", o.merged_by));
845 out.push_str(&format!(
846 "- Target tip: `{}` before, `{}` after\n",
847 o.target_tip_before, o.target_tip_after
848 ));
849 for c in &o.merge_commits {
850 if c.entities.is_empty() {
851 out.push_str(&format!(
852 "- Record commit `{}` under merger `{}`: nothing adopted\n",
853 c.sha, c.identity
854 ));
855 continue;
856 }
857 out.push_str(&format!(
858 "- Merge commit `{}` under proposer `{}`: {}\n",
859 c.sha,
860 c.identity,
861 c.entities
862 .iter()
863 .map(|e| format!("`{e}`"))
864 .collect::<Vec<_>>()
865 .join(", ")
866 ));
867 }
868 if let Some(c) = &o.amend_commit {
869 out.push_str(&format!(
870 "- Amend commit `{}` under merger `{}`: {}\n",
871 c.sha,
872 c.identity,
873 c.entities
874 .iter()
875 .map(|e| format!("`{e}`"))
876 .collect::<Vec<_>>()
877 .join(", ")
878 ));
879 }
880 out.push_str(&format!(
881 "- Record: `{}` on `{}`\n",
882 o.record_path, o.target
883 ));
884 out.push_str("\n## Entities\n\n");
885 for e in &o.entities {
886 let mut line = format!("- `{}`: {} ({})", e.slug, e.disposition, e.action);
887 if let Some(p) = &e.proposer {
888 line.push_str(&format!(", proposer `{p}`"));
889 }
890 if let Some(h) = &e.content_hash {
891 line.push_str(&format!(", hash `{h}`"));
892 }
893 if e.check_recorded {
894 line.push_str(", check recorded");
895 }
896 out.push_str(&line);
897 out.push('\n');
898 }
899 let v = &o.validation;
900 out.push_str("\n## Validation\n\n");
901 out.push_str(&format!(
902 "- {} entities re-read; every entity parses: {}; findings {} before, {} after\n",
903 v.entities,
904 if v.all_entities_parse { "yes" } else { "NO" },
905 v.findings_before,
906 v.findings_after
907 ));
908 if v.new_findings.is_empty() {
909 out.push_str("- New findings: none (the whole store validates)\n");
910 } else {
911 out.push_str("- New findings:\n");
912 for f in &v.new_findings {
913 out.push_str(&format!(" - {f}\n"));
914 }
915 }
916 if !o.warnings.is_empty() {
917 out.push_str("\n## Warnings\n\n");
918 out.push_str("The merge landed; the bookkeeping after the last commit did not complete:\n");
919 for w in &o.warnings {
920 out.push_str(&format!("- {}: {}\n", w.code, w.message));
921 }
922 }
923 out
924}
925
926pub fn render_proposal_record(target: &str, record: &ProposalRecord) -> String {
929 let mut out = String::new();
930 out.push_str(&format!("# Proposals merged into `{target}`\n\n"));
931 if record.proposals.is_empty() {
932 out.push_str("No proposal has been merged into this mem.\n");
933 return out;
934 }
935 out.push_str(&format!(
936 "- Record: `{PROPOSAL_RECORD_PATH}` (version {}), {} proposal(s)\n",
937 record.version,
938 record.proposals.len()
939 ));
940 for p in &record.proposals {
941 out.push_str(&format!("\n## `{}`\n\n", p.id));
942 if let Some(d) = &p.description {
944 out.push_str(d);
945 out.push_str("\n\n");
946 }
947 out.push_str(&format!(
948 "- Proposer: `{}`; merged by `{}` at {}\n",
949 p.proposer.as_deref().unwrap_or("(unrecorded)"),
950 p.merged_by.as_deref().unwrap_or("(unrecorded)"),
951 if p.at.is_empty() {
952 "(unrecorded)"
953 } else {
954 &p.at
955 }
956 ));
957 out.push_str(&format!(
958 "- Ancestor `{}`; base `{}`; target tip at merge `{}`\n",
959 p.ancestor, p.base, p.target_tip
960 ));
961 for (slug, d) in &p.entities {
962 let mut line = format!("- `{slug}`: {}", d.disposition);
963 if let Some(r) = &d.reason {
964 line.push_str(&format!(" ({r})"));
965 }
966 if let Some(h) = &d.content_hash {
967 line.push_str(&format!(", proposed hash `{h}`"));
968 }
969 out.push_str(&line);
970 out.push('\n');
971 }
972 }
973 out
974}
975
976const BODY_FENCE: &str = "````";
983
984pub fn render_proposal_brief(brief: &ProposalBrief) -> String {
987 let mut out = String::new();
988 out.push_str(&format!(
989 "# Proposal brief: `{}` against `{}`\n\n",
990 brief.fork, brief.target
991 ));
992 out.push_str(&format!("- Proposal: `{}`\n", brief.proposal_id));
993 out.push_str(&format!(
994 "- Ancestor on `{}`: `{}`\n",
995 brief.target, brief.ancestor
996 ));
997 if brief.base_is_ancestor {
998 out.push_str(&format!(
999 "- Base: `{}` (no fork commit recorded; the ancestor is the base)\n",
1000 brief.base
1001 ));
1002 } else {
1003 out.push_str(&format!("- Base (the fork commit): `{}`\n", brief.base));
1004 }
1005 out.push_str(&format!("- Fork tip: `{}`\n", brief.fork_tip));
1006 out.push_str(&format!(
1007 "- Target tip: `{}` (at render time; the merge pins it)\n",
1008 brief.target_tip
1009 ));
1010 let s = &brief.summary;
1011 out.push_str(&format!(
1012 "- Entities: {} (added {}, modified {}, deleted {}, renamed {}); conflicts {}; precheck failures {}; re-proposals {}\n\n",
1013 brief.entries.len(),
1014 s.added,
1015 s.modified,
1016 s.deleted,
1017 s.renamed,
1018 s.conflicts,
1019 s.precheck_failures,
1020 s.re_proposals
1021 ));
1022 out.push_str(
1023 "Dispositions: in the JSON form (`--json`, or `--out <file>`), fill each \
1024 `dispositions.<slug>.disposition` with one of `adopt`, `adopt_with_changes`, `reject`; \
1025 `reject` and `adopt_with_changes` need a `reason`; `adopt_with_changes` carries the \
1026 owner's final body as `body` in the shape a create takes (`title`, `sections`, \
1027 `metadata`); a conflict entity accepts no `adopt`; `adopt` may carry a `reason` \
1028 too. The top-level `description` slot takes the proposal in the owner's words, \
1029 recorded with the merge. The merge validates the file against these shas.\n",
1030 );
1031 if brief.entries.is_empty() {
1032 out.push_str("\nThe fork has no change against its base.\n");
1033 return out;
1034 }
1035 for entry in &brief.entries {
1036 out.push('\n');
1037 render_entry(&mut out, brief, entry);
1038 }
1039 out
1040}
1041
1042fn render_entry(out: &mut String, brief: &ProposalBrief, e: &ProposalEntry) {
1043 let title = e.title.as_deref().unwrap_or("(no title)");
1044 out.push_str(&format!(
1045 "## `{}`: {} ({})\n\n",
1046 e.slug,
1047 e.status.as_wire(),
1048 title
1049 ));
1050 out.push_str(&format!(
1051 "- Type: {}\n",
1052 e.entity_type.as_deref().unwrap_or("(unknown)")
1053 ));
1054 out.push_str(&format!(
1055 "- Fork id: `{}`; target id: `{}`\n",
1056 e.fork_id, e.target_id
1057 ));
1058 if let Some(from) = &e.renamed_from {
1059 out.push_str(&format!("- Renamed from: `{from}`\n"));
1060 }
1061 if let Some(hash) = &e.content_hash {
1062 out.push_str(&format!("- Proposed content hash: `{hash}`\n"));
1063 }
1064 match e.status {
1065 ProposalChange::Added => {
1066 out.push_str("- Difference against base: the whole entity is new\n")
1067 }
1068 ProposalChange::Deleted => {
1069 out.push_str("- Difference against base: the entity is removed\n")
1070 }
1071 ProposalChange::Modified | ProposalChange::Renamed => {
1072 out.push_str(&format!(
1073 "- Differences (fork against base): {}\n",
1074 render_delta(e.fork_delta.as_ref())
1075 ));
1076 }
1077 }
1078 if e.referrers.is_empty() {
1079 out.push_str("- Target referrers: none\n");
1080 } else {
1081 let list: Vec<String> = e
1082 .referrers
1083 .iter()
1084 .map(|r| format!("`{}` ({})", r.id, r.rel_type))
1085 .collect();
1086 out.push_str(&format!("- Target referrers: {}\n", list.join(", ")));
1087 }
1088 if e.anchors.is_empty() {
1089 out.push_str("- Anchors: none\n");
1090 } else {
1091 out.push_str("- Anchors:\n");
1092 for a in &e.anchors {
1093 let span = match &a.span {
1094 Some(s) => format!("; span: \"{s}\""),
1095 None => String::new(),
1096 };
1097 let state = match (&a.last_state, &a.last_observed_at) {
1098 (Some(state), Some(at)) => format!("; last state: {state} at {at}"),
1099 (Some(state), None) => format!("; last state: {state}"),
1100 (None, _) => "; last state: unobserved".to_string(),
1101 };
1102 out.push_str(&format!(
1103 " - `{}` ({}, {}{span}{state})\n",
1104 a.artifact, a.grain, a.class
1105 ));
1106 }
1107 }
1108 match e.precheck.outcome {
1109 PrecheckOutcome::Clean => out.push_str(&format!(
1110 "- Precheck ({} in `{}`): clean\n",
1111 e.precheck.operation.as_deref().unwrap_or("gate"),
1112 brief.target
1113 )),
1114 PrecheckOutcome::Failed => {
1115 out.push_str(&format!(
1116 "- Precheck ({} in `{}`): FAILED\n",
1117 e.precheck.operation.as_deref().unwrap_or("gate"),
1118 brief.target
1119 ));
1120 for f in &e.precheck.failures {
1121 out.push_str(&format!(" - `{}`: {}\n", f.code, f.message));
1122 }
1123 }
1124 PrecheckOutcome::NotRun => out.push_str(&format!(
1125 "- Precheck: not run ({})\n",
1126 e.precheck.note.as_deref().unwrap_or("no operation applies")
1127 )),
1128 }
1129 if let Some(c) = &e.conflict {
1130 let target_side = match &c.target_delta {
1131 Some(d) => format!("; target against base: {}", render_delta(Some(d))),
1132 None => String::new(),
1133 };
1134 out.push_str(&format!(
1135 "- CONFLICT: {} ({}{target_side}); `adopt` is withheld, the owner supplies the merged body or rejects\n",
1136 c.kind.describe(),
1137 c.kind.as_wire()
1138 ));
1139 }
1140 for mark in &e.re_proposal {
1141 let reason = match &mark.reason {
1142 Some(r) => format!(": {r}"),
1143 None => String::new(),
1144 };
1145 let how = match mark.matched_by.as_str() {
1146 "content_hash" => "the same content",
1147 _ => "the same id",
1148 };
1149 out.push_str(&format!(
1150 "- RE-PROPOSAL: rejected in proposal `{}` ({how}){reason}\n",
1151 mark.proposal
1152 ));
1153 }
1154 if let Some(c) = &e.conflict {
1155 out.push_str("\n### Base version\n\n");
1156 render_body(out, e.base_body.as_deref());
1157 out.push_str("\n### Fork version\n\n");
1158 render_body(out, e.fork_body.as_deref());
1159 out.push_str("\n### Target version\n\n");
1160 render_body(out, c.target_body.as_deref());
1161 return;
1162 }
1163 match e.status {
1164 ProposalChange::Added => {
1165 out.push_str("\n### Proposed body\n\n");
1166 render_body(out, e.fork_body.as_deref());
1167 }
1168 ProposalChange::Deleted => {
1169 out.push_str("\n### Body at base\n\n");
1170 render_body(out, e.base_body.as_deref());
1171 }
1172 ProposalChange::Modified | ProposalChange::Renamed => {
1173 out.push_str("\n### Fork version\n\n");
1174 render_body(out, e.fork_body.as_deref());
1175 }
1176 }
1177}
1178
1179fn render_delta(delta: Option<&VersionDelta>) -> String {
1180 let Some(d) = delta else {
1181 return "(a side does not parse)".to_string();
1182 };
1183 if d.is_empty() {
1184 return "none beyond mem qualifiers".to_string();
1185 }
1186 let mut parts: Vec<String> = Vec::new();
1187 if d.title_differs {
1188 parts.push("title".to_string());
1189 }
1190 if d.entity_type_differs {
1191 parts.push("type".to_string());
1192 }
1193 if !d.sections.is_empty() {
1194 parts.push(format!(
1195 "sections {}",
1196 d.sections
1197 .iter()
1198 .map(|s| format!("`{s}`"))
1199 .collect::<Vec<_>>()
1200 .join(", ")
1201 ));
1202 }
1203 if !d.metadata.is_empty() {
1204 parts.push(format!(
1205 "metadata {}",
1206 d.metadata
1207 .iter()
1208 .map(|s| format!("`{s}`"))
1209 .collect::<Vec<_>>()
1210 .join(", ")
1211 ));
1212 }
1213 if d.relationships_differ {
1214 parts.push("relationships".to_string());
1215 }
1216 parts.join("; ")
1217}
1218
1219fn render_body(out: &mut String, body: Option<&str>) {
1220 match body {
1221 Some(b) => {
1222 out.push_str(BODY_FENCE);
1223 out.push_str("markdown\n");
1224 out.push_str(b);
1225 if !b.ends_with('\n') {
1226 out.push('\n');
1227 }
1228 out.push_str(BODY_FENCE);
1229 out.push('\n');
1230 }
1231 None => out.push_str("(absent)\n"),
1232 }
1233}
1234
1235#[cfg(test)]
1236mod tests {
1237 use super::*;
1238
1239 fn entry(slug: &str, status: ProposalChange, conflict: Option<ConflictKind>) -> ProposalEntry {
1240 ProposalEntry {
1241 slug: slug.to_string(),
1242 fork_id: format!("f--{slug}"),
1243 target_id: format!("t--{slug}"),
1244 status,
1245 renamed_from: None,
1246 title: Some(slug.to_uppercase()),
1247 entity_type: Some("spec".to_string()),
1248 content_hash: Some("abc".to_string()),
1249 fork_delta: Some(VersionDelta {
1250 sections: vec!["identity".to_string()],
1251 ..Default::default()
1252 }),
1253 referrers: vec![Referrer {
1254 id: "t--alpha".to_string(),
1255 rel_type: "DEPENDS_ON".to_string(),
1256 }],
1257 anchors: vec![AnchorRow {
1258 artifact: "https://example.org/p".to_string(),
1259 grain: "url".to_string(),
1260 class: "anchored".to_string(),
1261 span: Some("the words".to_string()),
1262 last_state: None,
1263 last_observed_at: None,
1264 }],
1265 precheck: Precheck::clean("update"),
1266 conflict: conflict.map(|kind| Conflict {
1267 kind,
1268 target_delta: Some(VersionDelta {
1269 sections: vec!["identity".to_string()],
1270 ..Default::default()
1271 }),
1272 target_body: Some("# T\n".to_string()),
1273 }),
1274 re_proposal: Vec::new(),
1275 base_body: Some("# B\n".to_string()),
1276 fork_body: Some("# F\n".to_string()),
1277 }
1278 }
1279
1280 fn brief() -> ProposalBrief {
1281 let entries = vec![
1282 entry("beta", ProposalChange::Modified, None),
1283 entry(
1284 "alpha",
1285 ProposalChange::Modified,
1286 Some(ConflictKind::TargetModified),
1287 ),
1288 ];
1289 let dispositions = entries
1290 .iter()
1291 .map(|e| {
1292 (
1293 e.slug.clone(),
1294 DispositionSlot::skeleton(e.conflict.is_some()),
1295 )
1296 })
1297 .collect();
1298 ProposalBrief {
1299 fork: "f".to_string(),
1300 target: "t".to_string(),
1301 proposal_id: proposal_id("f", "b"),
1302 ancestor: "a".to_string(),
1303 base: "b".to_string(),
1304 base_is_ancestor: false,
1305 fork_tip: "c".to_string(),
1306 target_tip: "d".to_string(),
1307 summary: ProposalSummary {
1308 modified: 2,
1309 conflicts: 1,
1310 ..Default::default()
1311 },
1312 entries,
1313 description: String::new(),
1314 dispositions,
1315 }
1316 }
1317
1318 #[test]
1322 fn skeleton_vocabulary_is_closed_and_a_conflict_withholds_adopt() {
1323 let b = brief();
1324 let json = serde_json::to_value(&b).unwrap();
1325 assert_eq!(
1326 json["dispositions"]["beta"],
1327 serde_json::json!({
1328 "disposition": "",
1329 "reason": "",
1330 "accepts": ["adopt", "adopt_with_changes", "reject"]
1331 })
1332 );
1333 assert_eq!(
1334 json["dispositions"]["alpha"]["accepts"],
1335 serde_json::json!(["adopt_with_changes", "reject"])
1336 );
1337 for key in [
1338 "fork",
1339 "target",
1340 "proposal_id",
1341 "ancestor",
1342 "base",
1343 "base_is_ancestor",
1344 "fork_tip",
1345 "target_tip",
1346 "summary",
1347 "entries",
1348 "description",
1349 "dispositions",
1350 ] {
1351 assert!(json.get(key).is_some(), "top-level key {key}");
1352 }
1353 assert_eq!(json["description"], "");
1354 let mut older = json.clone();
1356 older.as_object_mut().unwrap().remove("description");
1357 let older: ProposalBrief = serde_json::from_value(older).unwrap();
1358 assert_eq!(older, b);
1359 assert_eq!(json["entries"][0]["status"], "modified");
1360 assert_eq!(json["entries"][0]["precheck"]["outcome"], "clean");
1361 assert_eq!(json["entries"][1]["conflict"]["kind"], "target_modified");
1362 let back: ProposalBrief = serde_json::from_value(json).unwrap();
1364 assert_eq!(back, b);
1365 }
1366
1367 #[test]
1372 fn markdown_is_deterministic_and_names_every_axis() {
1373 let b = brief();
1374 let md = render_proposal_brief(&b);
1375 assert_eq!(md, render_proposal_brief(&b));
1376 for needle in [
1377 "# Proposal brief: `f` against `t`",
1378 "- Ancestor on `t`: `a`",
1379 "- Base (the fork commit): `b`",
1380 "- Fork tip: `c`",
1381 "- Target tip: `d`",
1382 "## `alpha`: modified (ALPHA)",
1383 "## `beta`: modified (BETA)",
1384 "- Differences (fork against base): sections `identity`",
1385 "- Target referrers: `t--alpha` (DEPENDS_ON)",
1386 " - `https://example.org/p` (url, anchored; span: \"the words\"; last state: unobserved)",
1387 "- Precheck (update in `t`): clean",
1388 "- CONFLICT: the target modified this entity since the ancestor (target_modified; target against base: sections `identity`)",
1389 "### Base version",
1390 "### Fork version",
1391 "### Target version",
1392 "````markdown\n# T\n````",
1393 ] {
1394 assert!(md.contains(needle), "missing {needle:?} in:\n{md}");
1395 }
1396 assert!(!md.contains('\u{2014}'));
1398 }
1399
1400 #[test]
1403 fn markdown_names_the_ancestor_fallback_and_the_empty_case() {
1404 let mut b = brief();
1405 b.base_is_ancestor = true;
1406 b.entries.clear();
1407 b.dispositions.clear();
1408 let md = render_proposal_brief(&b);
1409 assert!(md.contains("- Base: `b` (no fork commit recorded; the ancestor is the base)"));
1410 assert!(md.contains("The fork has no change against its base."));
1411 }
1412
1413 #[test]
1417 fn record_parses_and_matches_rejections_by_hash_then_id() {
1418 let bytes = br#"{"version": 1, "future": true, "proposals": [{"id": "f@b", "proposer": "p", "ancestor": "a", "base": "b", "target_tip": "d", "merged_by": "m", "at": "2026-09-20T00:00:00Z", "entities": {"alpha": {"disposition": "reject", "reason": "weak", "content_hash": "h1"}, "beta": {"disposition": "adopt", "content_hash": "h2"}}}]}"#;
1419 let record = ProposalRecord::from_bytes(bytes).unwrap();
1420 assert_eq!(record.proposals.len(), 1);
1421 assert_eq!(record.proposals[0].description, None);
1424 let written: serde_json::Value = serde_json::from_slice(&record.to_bytes()).unwrap();
1425 assert!(written["proposals"][0].get("description").is_none());
1426 let described = br#"{"version": 1, "proposals": [{"id": "f@b", "at": "2026-09-20T00:00:00Z", "description": "a staged exercise", "entities": {"beta": {"disposition": "adopt", "reason": "as proposed"}}}]}"#;
1427 let described = ProposalRecord::from_bytes(described).unwrap();
1428 assert_eq!(
1429 described.proposals[0].description.as_deref(),
1430 Some("a staged exercise")
1431 );
1432 assert_eq!(
1433 described.proposals[0].entities["beta"].reason.as_deref(),
1434 Some("as proposed")
1435 );
1436 let md = render_proposal_record("t", &described);
1437 assert!(
1438 md.contains("## `f@b`\n\na staged exercise\n\n- Proposer:"),
1439 "{md}"
1440 );
1441 assert!(md.contains("- `beta`: adopt (as proposed)"), "{md}");
1442 let marks = record.rejections_matching("gamma", Some("h1"));
1444 assert_eq!(marks.len(), 1);
1445 assert_eq!(marks[0].matched_by, "content_hash");
1446 assert_eq!(marks[0].proposal, "f@b");
1447 assert_eq!(marks[0].reason.as_deref(), Some("weak"));
1448 let marks = record.rejections_matching("alpha", Some("h9"));
1450 assert_eq!(marks.len(), 1);
1451 assert_eq!(marks[0].matched_by, "id");
1452 assert!(record.rejections_matching("beta", Some("h2")).is_empty());
1454 assert!(ProposalRecord::from_bytes(b"not json").is_err());
1456 assert_eq!(ProposalRecord::default().proposals.len(), 0);
1457 assert_eq!(ProposalRecord::default().version, PROPOSAL_RECORD_VERSION);
1458 }
1459}