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<String>,
734}
735
736#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
738pub struct MergeCommit {
739 pub sha: String,
740 pub identity: String,
744 pub entities: Vec<String>,
747}
748
749#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
751pub struct MergedEntity {
752 pub slug: String,
753 pub target_id: String,
754 pub disposition: String,
755 pub action: String,
758 #[serde(default, skip_serializing_if = "Option::is_none")]
763 pub proposer: Option<String>,
764 #[serde(default, skip_serializing_if = "Option::is_none")]
768 pub content_hash: Option<String>,
769 pub check_recorded: bool,
772}
773
774#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
781pub struct MergeValidation {
782 pub entities: usize,
784 pub findings_before: usize,
786 pub findings_after: usize,
788 #[serde(default, skip_serializing_if = "Vec::is_empty")]
791 pub new_findings: Vec<String>,
792 pub all_entities_parse: bool,
796}
797
798impl MergeValidation {
799 pub fn is_clean(&self) -> bool {
802 self.all_entities_parse && self.new_findings.is_empty()
803 }
804}
805
806pub fn render_proposal_merge(o: &ProposalMergeOutcome) -> String {
808 let mut out = String::new();
809 out.push_str(&format!(
810 "# Proposal `{}` merged into `{}`\n\n",
811 o.proposal_id, o.target
812 ));
813 out.push_str(&format!("- Merged by: `{}`\n", o.merged_by));
814 out.push_str(&format!(
815 "- Target tip: `{}` before, `{}` after\n",
816 o.target_tip_before, o.target_tip_after
817 ));
818 for c in &o.merge_commits {
819 if c.entities.is_empty() {
820 out.push_str(&format!(
821 "- Record commit `{}` under merger `{}`: nothing adopted\n",
822 c.sha, c.identity
823 ));
824 continue;
825 }
826 out.push_str(&format!(
827 "- Merge commit `{}` under proposer `{}`: {}\n",
828 c.sha,
829 c.identity,
830 c.entities
831 .iter()
832 .map(|e| format!("`{e}`"))
833 .collect::<Vec<_>>()
834 .join(", ")
835 ));
836 }
837 if let Some(c) = &o.amend_commit {
838 out.push_str(&format!(
839 "- Amend commit `{}` under merger `{}`: {}\n",
840 c.sha,
841 c.identity,
842 c.entities
843 .iter()
844 .map(|e| format!("`{e}`"))
845 .collect::<Vec<_>>()
846 .join(", ")
847 ));
848 }
849 out.push_str(&format!(
850 "- Record: `{}` on `{}`\n",
851 o.record_path, o.target
852 ));
853 out.push_str("\n## Entities\n\n");
854 for e in &o.entities {
855 let mut line = format!("- `{}`: {} ({})", e.slug, e.disposition, e.action);
856 if let Some(p) = &e.proposer {
857 line.push_str(&format!(", proposer `{p}`"));
858 }
859 if let Some(h) = &e.content_hash {
860 line.push_str(&format!(", hash `{h}`"));
861 }
862 if e.check_recorded {
863 line.push_str(", check recorded");
864 }
865 out.push_str(&line);
866 out.push('\n');
867 }
868 let v = &o.validation;
869 out.push_str("\n## Validation\n\n");
870 out.push_str(&format!(
871 "- {} entities re-read; every entity parses: {}; findings {} before, {} after\n",
872 v.entities,
873 if v.all_entities_parse { "yes" } else { "NO" },
874 v.findings_before,
875 v.findings_after
876 ));
877 if v.new_findings.is_empty() {
878 out.push_str("- New findings: none (the whole store validates)\n");
879 } else {
880 out.push_str("- New findings:\n");
881 for f in &v.new_findings {
882 out.push_str(&format!(" - {f}\n"));
883 }
884 }
885 if !o.warnings.is_empty() {
886 out.push_str("\n## Warnings\n\n");
887 out.push_str("The merge landed; the bookkeeping after the last commit did not complete:\n");
888 for w in &o.warnings {
889 out.push_str(&format!("- {w}\n"));
890 }
891 }
892 out
893}
894
895pub fn render_proposal_record(target: &str, record: &ProposalRecord) -> String {
898 let mut out = String::new();
899 out.push_str(&format!("# Proposals merged into `{target}`\n\n"));
900 if record.proposals.is_empty() {
901 out.push_str("No proposal has been merged into this mem.\n");
902 return out;
903 }
904 out.push_str(&format!(
905 "- Record: `{PROPOSAL_RECORD_PATH}` (version {}), {} proposal(s)\n",
906 record.version,
907 record.proposals.len()
908 ));
909 for p in &record.proposals {
910 out.push_str(&format!("\n## `{}`\n\n", p.id));
911 if let Some(d) = &p.description {
913 out.push_str(d);
914 out.push_str("\n\n");
915 }
916 out.push_str(&format!(
917 "- Proposer: `{}`; merged by `{}` at {}\n",
918 p.proposer.as_deref().unwrap_or("(unrecorded)"),
919 p.merged_by.as_deref().unwrap_or("(unrecorded)"),
920 if p.at.is_empty() {
921 "(unrecorded)"
922 } else {
923 &p.at
924 }
925 ));
926 out.push_str(&format!(
927 "- Ancestor `{}`; base `{}`; target tip at merge `{}`\n",
928 p.ancestor, p.base, p.target_tip
929 ));
930 for (slug, d) in &p.entities {
931 let mut line = format!("- `{slug}`: {}", d.disposition);
932 if let Some(r) = &d.reason {
933 line.push_str(&format!(" ({r})"));
934 }
935 if let Some(h) = &d.content_hash {
936 line.push_str(&format!(", proposed hash `{h}`"));
937 }
938 out.push_str(&line);
939 out.push('\n');
940 }
941 }
942 out
943}
944
945const BODY_FENCE: &str = "````";
952
953pub fn render_proposal_brief(brief: &ProposalBrief) -> String {
956 let mut out = String::new();
957 out.push_str(&format!(
958 "# Proposal brief: `{}` against `{}`\n\n",
959 brief.fork, brief.target
960 ));
961 out.push_str(&format!("- Proposal: `{}`\n", brief.proposal_id));
962 out.push_str(&format!(
963 "- Ancestor on `{}`: `{}`\n",
964 brief.target, brief.ancestor
965 ));
966 if brief.base_is_ancestor {
967 out.push_str(&format!(
968 "- Base: `{}` (no fork commit recorded; the ancestor is the base)\n",
969 brief.base
970 ));
971 } else {
972 out.push_str(&format!("- Base (the fork commit): `{}`\n", brief.base));
973 }
974 out.push_str(&format!("- Fork tip: `{}`\n", brief.fork_tip));
975 out.push_str(&format!(
976 "- Target tip: `{}` (at render time; the merge pins it)\n",
977 brief.target_tip
978 ));
979 let s = &brief.summary;
980 out.push_str(&format!(
981 "- Entities: {} (added {}, modified {}, deleted {}, renamed {}); conflicts {}; precheck failures {}; re-proposals {}\n\n",
982 brief.entries.len(),
983 s.added,
984 s.modified,
985 s.deleted,
986 s.renamed,
987 s.conflicts,
988 s.precheck_failures,
989 s.re_proposals
990 ));
991 out.push_str(
992 "Dispositions: in the JSON form (`--json`, or `--out <file>`), fill each \
993 `dispositions.<slug>.disposition` with one of `adopt`, `adopt_with_changes`, `reject`; \
994 `reject` and `adopt_with_changes` need a `reason`; `adopt_with_changes` carries the \
995 owner's final body as `body` in the shape a create takes (`title`, `sections`, \
996 `metadata`); a conflict entity accepts no `adopt`; `adopt` may carry a `reason` \
997 too. The top-level `description` slot takes the proposal in the owner's words, \
998 recorded with the merge. The merge validates the file against these shas.\n",
999 );
1000 if brief.entries.is_empty() {
1001 out.push_str("\nThe fork has no change against its base.\n");
1002 return out;
1003 }
1004 for entry in &brief.entries {
1005 out.push('\n');
1006 render_entry(&mut out, brief, entry);
1007 }
1008 out
1009}
1010
1011fn render_entry(out: &mut String, brief: &ProposalBrief, e: &ProposalEntry) {
1012 let title = e.title.as_deref().unwrap_or("(no title)");
1013 out.push_str(&format!(
1014 "## `{}`: {} ({})\n\n",
1015 e.slug,
1016 e.status.as_wire(),
1017 title
1018 ));
1019 out.push_str(&format!(
1020 "- Type: {}\n",
1021 e.entity_type.as_deref().unwrap_or("(unknown)")
1022 ));
1023 out.push_str(&format!(
1024 "- Fork id: `{}`; target id: `{}`\n",
1025 e.fork_id, e.target_id
1026 ));
1027 if let Some(from) = &e.renamed_from {
1028 out.push_str(&format!("- Renamed from: `{from}`\n"));
1029 }
1030 if let Some(hash) = &e.content_hash {
1031 out.push_str(&format!("- Proposed content hash: `{hash}`\n"));
1032 }
1033 match e.status {
1034 ProposalChange::Added => {
1035 out.push_str("- Difference against base: the whole entity is new\n")
1036 }
1037 ProposalChange::Deleted => {
1038 out.push_str("- Difference against base: the entity is removed\n")
1039 }
1040 ProposalChange::Modified | ProposalChange::Renamed => {
1041 out.push_str(&format!(
1042 "- Differences (fork against base): {}\n",
1043 render_delta(e.fork_delta.as_ref())
1044 ));
1045 }
1046 }
1047 if e.referrers.is_empty() {
1048 out.push_str("- Target referrers: none\n");
1049 } else {
1050 let list: Vec<String> = e
1051 .referrers
1052 .iter()
1053 .map(|r| format!("`{}` ({})", r.id, r.rel_type))
1054 .collect();
1055 out.push_str(&format!("- Target referrers: {}\n", list.join(", ")));
1056 }
1057 if e.anchors.is_empty() {
1058 out.push_str("- Anchors: none\n");
1059 } else {
1060 out.push_str("- Anchors:\n");
1061 for a in &e.anchors {
1062 let span = match &a.span {
1063 Some(s) => format!("; span: \"{s}\""),
1064 None => String::new(),
1065 };
1066 let state = match (&a.last_state, &a.last_observed_at) {
1067 (Some(state), Some(at)) => format!("; last state: {state} at {at}"),
1068 (Some(state), None) => format!("; last state: {state}"),
1069 (None, _) => "; last state: unobserved".to_string(),
1070 };
1071 out.push_str(&format!(
1072 " - `{}` ({}, {}{span}{state})\n",
1073 a.artifact, a.grain, a.class
1074 ));
1075 }
1076 }
1077 match e.precheck.outcome {
1078 PrecheckOutcome::Clean => out.push_str(&format!(
1079 "- Precheck ({} in `{}`): clean\n",
1080 e.precheck.operation.as_deref().unwrap_or("gate"),
1081 brief.target
1082 )),
1083 PrecheckOutcome::Failed => {
1084 out.push_str(&format!(
1085 "- Precheck ({} in `{}`): FAILED\n",
1086 e.precheck.operation.as_deref().unwrap_or("gate"),
1087 brief.target
1088 ));
1089 for f in &e.precheck.failures {
1090 out.push_str(&format!(" - `{}`: {}\n", f.code, f.message));
1091 }
1092 }
1093 PrecheckOutcome::NotRun => out.push_str(&format!(
1094 "- Precheck: not run ({})\n",
1095 e.precheck.note.as_deref().unwrap_or("no operation applies")
1096 )),
1097 }
1098 if let Some(c) = &e.conflict {
1099 let target_side = match &c.target_delta {
1100 Some(d) => format!("; target against base: {}", render_delta(Some(d))),
1101 None => String::new(),
1102 };
1103 out.push_str(&format!(
1104 "- CONFLICT: {} ({}{target_side}); `adopt` is withheld, the owner supplies the merged body or rejects\n",
1105 c.kind.describe(),
1106 c.kind.as_wire()
1107 ));
1108 }
1109 for mark in &e.re_proposal {
1110 let reason = match &mark.reason {
1111 Some(r) => format!(": {r}"),
1112 None => String::new(),
1113 };
1114 let how = match mark.matched_by.as_str() {
1115 "content_hash" => "the same content",
1116 _ => "the same id",
1117 };
1118 out.push_str(&format!(
1119 "- RE-PROPOSAL: rejected in proposal `{}` ({how}){reason}\n",
1120 mark.proposal
1121 ));
1122 }
1123 if let Some(c) = &e.conflict {
1124 out.push_str("\n### Base version\n\n");
1125 render_body(out, e.base_body.as_deref());
1126 out.push_str("\n### Fork version\n\n");
1127 render_body(out, e.fork_body.as_deref());
1128 out.push_str("\n### Target version\n\n");
1129 render_body(out, c.target_body.as_deref());
1130 return;
1131 }
1132 match e.status {
1133 ProposalChange::Added => {
1134 out.push_str("\n### Proposed body\n\n");
1135 render_body(out, e.fork_body.as_deref());
1136 }
1137 ProposalChange::Deleted => {
1138 out.push_str("\n### Body at base\n\n");
1139 render_body(out, e.base_body.as_deref());
1140 }
1141 ProposalChange::Modified | ProposalChange::Renamed => {
1142 out.push_str("\n### Fork version\n\n");
1143 render_body(out, e.fork_body.as_deref());
1144 }
1145 }
1146}
1147
1148fn render_delta(delta: Option<&VersionDelta>) -> String {
1149 let Some(d) = delta else {
1150 return "(a side does not parse)".to_string();
1151 };
1152 if d.is_empty() {
1153 return "none beyond mem qualifiers".to_string();
1154 }
1155 let mut parts: Vec<String> = Vec::new();
1156 if d.title_differs {
1157 parts.push("title".to_string());
1158 }
1159 if d.entity_type_differs {
1160 parts.push("type".to_string());
1161 }
1162 if !d.sections.is_empty() {
1163 parts.push(format!(
1164 "sections {}",
1165 d.sections
1166 .iter()
1167 .map(|s| format!("`{s}`"))
1168 .collect::<Vec<_>>()
1169 .join(", ")
1170 ));
1171 }
1172 if !d.metadata.is_empty() {
1173 parts.push(format!(
1174 "metadata {}",
1175 d.metadata
1176 .iter()
1177 .map(|s| format!("`{s}`"))
1178 .collect::<Vec<_>>()
1179 .join(", ")
1180 ));
1181 }
1182 if d.relationships_differ {
1183 parts.push("relationships".to_string());
1184 }
1185 parts.join("; ")
1186}
1187
1188fn render_body(out: &mut String, body: Option<&str>) {
1189 match body {
1190 Some(b) => {
1191 out.push_str(BODY_FENCE);
1192 out.push_str("markdown\n");
1193 out.push_str(b);
1194 if !b.ends_with('\n') {
1195 out.push('\n');
1196 }
1197 out.push_str(BODY_FENCE);
1198 out.push('\n');
1199 }
1200 None => out.push_str("(absent)\n"),
1201 }
1202}
1203
1204#[cfg(test)]
1205mod tests {
1206 use super::*;
1207
1208 fn entry(slug: &str, status: ProposalChange, conflict: Option<ConflictKind>) -> ProposalEntry {
1209 ProposalEntry {
1210 slug: slug.to_string(),
1211 fork_id: format!("f--{slug}"),
1212 target_id: format!("t--{slug}"),
1213 status,
1214 renamed_from: None,
1215 title: Some(slug.to_uppercase()),
1216 entity_type: Some("spec".to_string()),
1217 content_hash: Some("abc".to_string()),
1218 fork_delta: Some(VersionDelta {
1219 sections: vec!["identity".to_string()],
1220 ..Default::default()
1221 }),
1222 referrers: vec![Referrer {
1223 id: "t--alpha".to_string(),
1224 rel_type: "DEPENDS_ON".to_string(),
1225 }],
1226 anchors: vec![AnchorRow {
1227 artifact: "https://example.org/p".to_string(),
1228 grain: "url".to_string(),
1229 class: "anchored".to_string(),
1230 span: Some("the words".to_string()),
1231 last_state: None,
1232 last_observed_at: None,
1233 }],
1234 precheck: Precheck::clean("update"),
1235 conflict: conflict.map(|kind| Conflict {
1236 kind,
1237 target_delta: Some(VersionDelta {
1238 sections: vec!["identity".to_string()],
1239 ..Default::default()
1240 }),
1241 target_body: Some("# T\n".to_string()),
1242 }),
1243 re_proposal: Vec::new(),
1244 base_body: Some("# B\n".to_string()),
1245 fork_body: Some("# F\n".to_string()),
1246 }
1247 }
1248
1249 fn brief() -> ProposalBrief {
1250 let entries = vec![
1251 entry("beta", ProposalChange::Modified, None),
1252 entry(
1253 "alpha",
1254 ProposalChange::Modified,
1255 Some(ConflictKind::TargetModified),
1256 ),
1257 ];
1258 let dispositions = entries
1259 .iter()
1260 .map(|e| {
1261 (
1262 e.slug.clone(),
1263 DispositionSlot::skeleton(e.conflict.is_some()),
1264 )
1265 })
1266 .collect();
1267 ProposalBrief {
1268 fork: "f".to_string(),
1269 target: "t".to_string(),
1270 proposal_id: proposal_id("f", "b"),
1271 ancestor: "a".to_string(),
1272 base: "b".to_string(),
1273 base_is_ancestor: false,
1274 fork_tip: "c".to_string(),
1275 target_tip: "d".to_string(),
1276 summary: ProposalSummary {
1277 modified: 2,
1278 conflicts: 1,
1279 ..Default::default()
1280 },
1281 entries,
1282 description: String::new(),
1283 dispositions,
1284 }
1285 }
1286
1287 #[test]
1291 fn skeleton_vocabulary_is_closed_and_a_conflict_withholds_adopt() {
1292 let b = brief();
1293 let json = serde_json::to_value(&b).unwrap();
1294 assert_eq!(
1295 json["dispositions"]["beta"],
1296 serde_json::json!({
1297 "disposition": "",
1298 "reason": "",
1299 "accepts": ["adopt", "adopt_with_changes", "reject"]
1300 })
1301 );
1302 assert_eq!(
1303 json["dispositions"]["alpha"]["accepts"],
1304 serde_json::json!(["adopt_with_changes", "reject"])
1305 );
1306 for key in [
1307 "fork",
1308 "target",
1309 "proposal_id",
1310 "ancestor",
1311 "base",
1312 "base_is_ancestor",
1313 "fork_tip",
1314 "target_tip",
1315 "summary",
1316 "entries",
1317 "description",
1318 "dispositions",
1319 ] {
1320 assert!(json.get(key).is_some(), "top-level key {key}");
1321 }
1322 assert_eq!(json["description"], "");
1323 let mut older = json.clone();
1325 older.as_object_mut().unwrap().remove("description");
1326 let older: ProposalBrief = serde_json::from_value(older).unwrap();
1327 assert_eq!(older, b);
1328 assert_eq!(json["entries"][0]["status"], "modified");
1329 assert_eq!(json["entries"][0]["precheck"]["outcome"], "clean");
1330 assert_eq!(json["entries"][1]["conflict"]["kind"], "target_modified");
1331 let back: ProposalBrief = serde_json::from_value(json).unwrap();
1333 assert_eq!(back, b);
1334 }
1335
1336 #[test]
1341 fn markdown_is_deterministic_and_names_every_axis() {
1342 let b = brief();
1343 let md = render_proposal_brief(&b);
1344 assert_eq!(md, render_proposal_brief(&b));
1345 for needle in [
1346 "# Proposal brief: `f` against `t`",
1347 "- Ancestor on `t`: `a`",
1348 "- Base (the fork commit): `b`",
1349 "- Fork tip: `c`",
1350 "- Target tip: `d`",
1351 "## `alpha`: modified (ALPHA)",
1352 "## `beta`: modified (BETA)",
1353 "- Differences (fork against base): sections `identity`",
1354 "- Target referrers: `t--alpha` (DEPENDS_ON)",
1355 " - `https://example.org/p` (url, anchored; span: \"the words\"; last state: unobserved)",
1356 "- Precheck (update in `t`): clean",
1357 "- CONFLICT: the target modified this entity since the ancestor (target_modified; target against base: sections `identity`)",
1358 "### Base version",
1359 "### Fork version",
1360 "### Target version",
1361 "````markdown\n# T\n````",
1362 ] {
1363 assert!(md.contains(needle), "missing {needle:?} in:\n{md}");
1364 }
1365 assert!(!md.contains('\u{2014}'));
1367 }
1368
1369 #[test]
1372 fn markdown_names_the_ancestor_fallback_and_the_empty_case() {
1373 let mut b = brief();
1374 b.base_is_ancestor = true;
1375 b.entries.clear();
1376 b.dispositions.clear();
1377 let md = render_proposal_brief(&b);
1378 assert!(md.contains("- Base: `b` (no fork commit recorded; the ancestor is the base)"));
1379 assert!(md.contains("The fork has no change against its base."));
1380 }
1381
1382 #[test]
1386 fn record_parses_and_matches_rejections_by_hash_then_id() {
1387 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"}}}]}"#;
1388 let record = ProposalRecord::from_bytes(bytes).unwrap();
1389 assert_eq!(record.proposals.len(), 1);
1390 assert_eq!(record.proposals[0].description, None);
1393 let written: serde_json::Value = serde_json::from_slice(&record.to_bytes()).unwrap();
1394 assert!(written["proposals"][0].get("description").is_none());
1395 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"}}}]}"#;
1396 let described = ProposalRecord::from_bytes(described).unwrap();
1397 assert_eq!(
1398 described.proposals[0].description.as_deref(),
1399 Some("a staged exercise")
1400 );
1401 assert_eq!(
1402 described.proposals[0].entities["beta"].reason.as_deref(),
1403 Some("as proposed")
1404 );
1405 let md = render_proposal_record("t", &described);
1406 assert!(
1407 md.contains("## `f@b`\n\na staged exercise\n\n- Proposer:"),
1408 "{md}"
1409 );
1410 assert!(md.contains("- `beta`: adopt (as proposed)"), "{md}");
1411 let marks = record.rejections_matching("gamma", Some("h1"));
1413 assert_eq!(marks.len(), 1);
1414 assert_eq!(marks[0].matched_by, "content_hash");
1415 assert_eq!(marks[0].proposal, "f@b");
1416 assert_eq!(marks[0].reason.as_deref(), Some("weak"));
1417 let marks = record.rejections_matching("alpha", Some("h9"));
1419 assert_eq!(marks.len(), 1);
1420 assert_eq!(marks[0].matched_by, "id");
1421 assert!(record.rejections_matching("beta", Some("h2")).is_empty());
1423 assert!(ProposalRecord::from_bytes(b"not json").is_err());
1425 assert_eq!(ProposalRecord::default().proposals.len(), 0);
1426 assert_eq!(ProposalRecord::default().version, PROPOSAL_RECORD_VERSION);
1427 }
1428}