Skip to main content

memstead_base/ops/
proposal.rs

1//! The proposal brief: a fork's changes against its source, three ways.
2//!
3//! `Engine::proposal_brief(fork)` renders the entity-level picture the
4//! owner of a mem reviews before merging a fork: every entity the fork
5//! added, modified, deleted or renamed against its base (the fork
6//! commit, or the ancestor for a fork made before fork commits existed),
7//! each with the sections that differ, the target's referrers, the
8//! anchor rows it rests on, a mechanics precheck through the target's
9//! write gate, a conflict mark where the target moved the same entity
10//! since the ancestor, and a re-proposal mark where the target's
11//! proposal record already holds a rejection of the same content or id.
12//!
13//! The wire shape ([`ProposalBrief`]) is the JSON the CLI writes with
14//! `--out` and the MCP tool serves as `structured_content`; its
15//! `dispositions` map is the skeleton the owner fills and the merge
16//! consumes. [`render_proposal_brief`] renders the same data as
17//! markdown for a human. Rendering is deterministic: entries sort by
18//! slug and nothing carries a clock.
19//!
20//! The brief is a read. It writes nothing anywhere.
21
22use std::collections::BTreeMap;
23
24use serde::{Deserialize, Serialize};
25
26/// The closed disposition vocabulary, in the order the skeleton lists
27/// it. A conflict entity's slot omits `adopt`.
28pub const DISPOSITION_VOCABULARY: &[&str] = &["adopt", "adopt_with_changes", "reject"];
29
30/// The disposition of an adopted entity.
31pub const DISPOSITION_ADOPT: &str = "adopt";
32/// The disposition of an entity the owner adopts with a final body of
33/// their own.
34pub const DISPOSITION_ADOPT_WITH_CHANGES: &str = "adopt_with_changes";
35/// The disposition of a rejected entity.
36pub const DISPOSITION_REJECT: &str = "reject";
37
38/// The proposal record's path on a target branch: the sidecar the
39/// merge appends to and the brief reads for re-proposal marks.
40pub const PROPOSAL_RECORD_PATH: &str = ".memstead/proposals.json";
41
42/// The proposal record's format version.
43pub const PROPOSAL_RECORD_VERSION: u32 = 1;
44
45/// The brief of one fork against its source mem.
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub struct ProposalBrief {
48    /// The fork mem's name.
49    pub fork: String,
50    /// The source mem's name: the target of the proposal.
51    pub target: String,
52    /// The proposal's id: the fork's name and its base sha, the key the
53    /// proposal record uses.
54    pub proposal_id: String,
55    /// The ancestor on the target (`forkedFrom.sha`).
56    pub ancestor: String,
57    /// The commit the fork's changes are read against: the fork commit
58    /// (`forkedFrom.base`) when one was recorded, the ancestor otherwise.
59    pub base: String,
60    /// Whether the base is the ancestor itself (a fork made before fork
61    /// commits existed recorded no base).
62    pub base_is_ancestor: bool,
63    /// The fork's branch tip at render time.
64    pub fork_tip: String,
65    /// The target's branch tip at render time; the merge pins it.
66    pub target_tip: String,
67    /// Counts over `entries`.
68    pub summary: ProposalSummary,
69    /// One entry per entity the fork touched, sorted by slug.
70    pub entries: Vec<ProposalEntry>,
71    /// The proposal in the owner's words: free text the owner writes
72    /// into the disposition file, which the merge records on the
73    /// proposal record's entry so a reader of the record (or of a
74    /// published archive) learns what the proposal was, not only what
75    /// happened to each entity. The skeleton emits it empty; the merge
76    /// trims it and treats a blank slot as absent (the merge's note
77    /// stands in then, when one was given). Absent in a file rendered
78    /// before the slot existed.
79    #[serde(default)]
80    pub description: String,
81    /// The disposition skeleton, keyed by slug: the owner fills
82    /// `disposition` (and `reason`, and for `adopt_with_changes` a
83    /// `body`) and hands the file to the merge.
84    pub dispositions: BTreeMap<String, DispositionSlot>,
85}
86
87/// Counts over a brief's entries.
88#[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/// What the fork did to one entity, read against the base.
100#[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    /// Stable wire form.
111    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/// One entity the fork touched.
122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
123pub struct ProposalEntry {
124    /// The entity's slug: the part of the id after the mem name, the
125    /// key the two mems share.
126    pub slug: String,
127    /// The entity's id in the fork (`<fork>--<slug>`).
128    pub fork_id: String,
129    /// The entity's id in the target (`<target>--<slug>`).
130    pub target_id: String,
131    /// What the fork did.
132    pub status: ProposalChange,
133    /// For a renamed entity: the slug it had at the base.
134    #[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    /// The hash of the proposed version as it would land in the target
141    /// (the fork's body with its self-links under the target's name),
142    /// computed with the engine's date stamps (`created_date`,
143    /// `last_modified`) left out, so the same body proposed again from
144    /// another fork hashes the same; absent for a deletion. The
145    /// proposal record stores the same hash, so a rejected body is
146    /// recognised when a later fork proposes it again. Not the
147    /// entity's `_hash` (the file hash, stamps included).
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub content_hash: Option<String>,
150    /// How the fork's version differs from the base (absent for an
151    /// added or deleted entity, and when a side does not parse).
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub fork_delta: Option<VersionDelta>,
154    /// The target's referrers of this entity: entities in the target
155    /// or in other mems holding an edge to it (the fork's own excluded).
156    #[serde(default, skip_serializing_if = "Vec::is_empty")]
157    pub referrers: Vec<Referrer>,
158    /// The anchor rows the fork's entity rests on, read from the
159    /// fork's sidecar under the fork's ids; no observation is fetched.
160    #[serde(default, skip_serializing_if = "Vec::is_empty")]
161    pub anchors: Vec<AnchorRow>,
162    /// The mechanics precheck through the target's write gate.
163    pub precheck: Precheck,
164    /// Present when the target moved the same entity since the ancestor.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub conflict: Option<Conflict>,
167    /// Present when the target's proposal record holds a rejection of
168    /// the same content hash or the same id.
169    #[serde(default, skip_serializing_if = "Vec::is_empty")]
170    pub re_proposal: Vec<ReProposalMark>,
171    /// The base's body, with mem qualifiers normalised to the fork's
172    /// name (absent for an added entity).
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub base_body: Option<String>,
175    /// The fork's body, the proposed version (absent for a deletion).
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub fork_body: Option<String>,
178}
179
180/// How one side's version differs from the base.
181#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
182pub struct VersionDelta {
183    pub title_differs: bool,
184    pub entity_type_differs: bool,
185    /// Section keys whose content differs, or that one side has and
186    /// the other lacks, in the order the fork's body declares them.
187    pub sections: Vec<String>,
188    /// Metadata keys whose value differs (the engine-stamped
189    /// `created_date` and `last_modified` never count).
190    pub metadata: Vec<String>,
191    pub relationships_differ: bool,
192}
193
194impl VersionDelta {
195    /// Whether anything differs.
196    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/// An entity holding an edge to the target's entity.
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207pub struct Referrer {
208    pub id: String,
209    pub rel_type: String,
210}
211
212/// One anchor row of the fork's entity, as stored.
213#[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    /// The last recorded state of the row (`resolves`, `drifted`,
221    /// `recheck`, `orphaned`, `span_absent`); absent when the row was
222    /// never observed.
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub last_state: Option<String>,
225    /// When that state was recorded.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub last_observed_at: Option<String>,
228}
229
230/// The mechanics precheck: would the fork's body pass the target's
231/// write gate as it stands. Never a content judgement.
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233pub struct Precheck {
234    pub outcome: PrecheckOutcome,
235    /// The rehearsed operation (`create` or `update`) when one ran.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub operation: Option<String>,
238    /// The typed refusal the gate returned, when it refused.
239    #[serde(default, skip_serializing_if = "Vec::is_empty")]
240    pub failures: Vec<PrecheckFailure>,
241    /// Why no operation ran, when none did.
242    #[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/// One typed refusal of the write gate.
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295pub struct PrecheckFailure {
296    pub code: String,
297    pub message: String,
298}
299
300/// The target moved the same entity since the ancestor.
301#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
302pub struct Conflict {
303    pub kind: ConflictKind,
304    /// How the target's version differs from the base (when both parse).
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub target_delta: Option<VersionDelta>,
307    /// The target's body, mem qualifiers normalised to the fork's name
308    /// (absent when the target deleted the entity).
309    #[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    /// The target modified an entity the fork modified, deleted or
317    /// renamed.
318    TargetModified,
319    /// The target deleted (or renamed away) an entity the fork
320    /// modified, deleted or renamed.
321    TargetDeleted,
322    /// The target created an entity with a slug the fork added.
323    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/// A rejection in the target's proposal record that this entry matches.
347#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
348pub struct ReProposalMark {
349    /// `content_hash` (the same proposed body) or `id` (the same slug).
350    pub matched_by: String,
351    /// The recorded proposal's id.
352    pub proposal: String,
353    #[serde(default, skip_serializing_if = "Option::is_none")]
354    pub reason: Option<String>,
355}
356
357/// One slot of the disposition skeleton.
358#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
359pub struct DispositionSlot {
360    /// Empty in the skeleton; one of `accepts` once filled.
361    pub disposition: String,
362    /// Empty in the skeleton; required for `reject` and
363    /// `adopt_with_changes`, optional on `adopt`. Recorded whenever
364    /// given.
365    pub reason: String,
366    /// The values this slot accepts: the closed vocabulary, without
367    /// `adopt` on a conflict entity.
368    pub accepts: Vec<String>,
369    /// For `adopt_with_changes`: the owner's final body in the shape a
370    /// create takes (`title`, `sections`, `metadata`); absent in the
371    /// skeleton.
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub body: Option<serde_json::Value>,
374}
375
376impl DispositionSlot {
377    /// The empty slot for an entry, `adopt` withheld on a conflict.
378    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// ---------------------------------------------------------------------------
394// The proposal record
395// ---------------------------------------------------------------------------
396
397/// The proposal record a target branch carries at
398/// [`PROPOSAL_RECORD_PATH`]: one entry per merged proposal with every
399/// disposition, so a rejected claim cannot return unseen. The merge
400/// writes it; the brief reads it. Unknown keys are tolerated so an
401/// older reader survives a newer writer.
402#[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    /// The empty record at the current format version (the derive
416    /// would say version 0).
417    fn default() -> Self {
418        Self {
419            version: PROPOSAL_RECORD_VERSION,
420            proposals: Vec::new(),
421        }
422    }
423}
424
425/// One merged proposal in the record.
426#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
427pub struct ProposalRecordEntry {
428    /// The proposal's id: the fork's name and its base sha.
429    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    /// The proposal in the owner's words: the disposition file's
443    /// `description`, or the merge's note when the file carried none.
444    /// Absent when neither was given, and on every entry written before
445    /// the field existed; the key is left off the bytes then.
446    #[serde(default, skip_serializing_if = "Option::is_none")]
447    pub description: Option<String>,
448    /// Per slug: the disposition, the reason and the content hash of
449    /// the proposed version (never its body).
450    #[serde(default)]
451    pub entities: BTreeMap<String, RecordedDisposition>,
452}
453
454/// One entity's disposition in the record.
455#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
456pub struct RecordedDisposition {
457    pub disposition: String,
458    /// The owner's reason: always present on `reject` and
459    /// `adopt_with_changes`, present on `adopt` when the owner gave one.
460    #[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    /// For an `adopt`: one prepared hash per LOAD-BEARING section of the
465    /// body the merge landed, keyed by section key
466    /// ([`crate::preparation::entity_load_bearing_section_marks`]).
467    ///
468    /// This is the adopt-time decision that
469    /// [`crate::engine::Engine::entity_origin_class`] reports at read
470    /// time: while any recorded section still hashes to the value here,
471    /// that section is the proposer's bytes, so the entity serves
472    /// `third-party`.
473    ///
474    /// Per section, and prepared rather than the file hash, for three
475    /// reasons the coarser forms each get wrong. The file hash moves on a
476    /// metadata stamp or a notes-only edit, so a stranger's claim would
477    /// promote itself to first-party on the owner's next unrelated edit.
478    /// One hash over the whole load-bearing form collapses a type's
479    /// sections to one bit, so rewriting one of three would clear a mark
480    /// still covering the other two. And a per-section hash carries its
481    /// own section key, so the comparison needs neither the schema pin nor
482    /// the entity type: a repin or a retype changes which sections a type
483    /// calls load-bearing, and a comparison that depended on the current
484    /// declaration would report a rewrite that never happened.
485    ///
486    /// A MERGE writes it only for an `adopt`: absent on an
487    /// `adopt_with_changes` (the owner typed those bytes, so they are
488    /// first-party), on a `reject` (nothing landed), on a deletion, and on
489    /// every entry written before this field existed. A later rename may
490    /// carry marks onto an entry of any disposition
491    /// ([`crate::engine::mutation::move_marks_on_rename`]), because the
492    /// entry then describes the body that is at that slug NOW rather than
493    /// the one the proposal landed there; the other fields keep documenting
494    /// the proposal. A
495    /// legacy entry cannot confirm the comparison and inherits the mem's
496    /// class, which is what the engine did before the field. A contributor
497    /// cannot cause the absence: the record is written by the owner's
498    /// merge, on the target branch, never by the fork.
499    #[serde(default, skip_serializing_if = "Option::is_none")]
500    pub landed_sections: Option<BTreeMap<String, String>>,
501}
502
503/// The origin marks a record makes effective for one slug, and the one
504/// structural verdict it can raise about itself.
505///
506/// These two methods are the ONLY reading of `landed_sections`. Both the read
507/// path ([`crate::Engine::entity_origin_class`]) and every write that has to
508/// follow a mark (rename, retype, the wiki-link retargets) go through them,
509/// because four review rounds in a row found the same defect one position
510/// over while the write path kept its own copy of these rules: it modelled
511/// last-write-wins and retirement by hand and got one arm wrong each time.
512/// One owner, so the arms cannot disagree.
513impl ProposalRecord {
514    /// The marks effective for `slug`: every proposal in record order, last
515    /// write wins, a non-reject entry without marks retires the slug, and a
516    /// `reject` retires nothing (it landed no bytes, so a later rejected
517    /// proposal must not relabel a standing contribution).
518    ///
519    /// Only meaningful on a record with no [`Self::structural_defect`]; a
520    /// caller that has not checked that is reading a record it does not
521    /// understand.
522    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                // A structurally empty map is a defect, never a retirement;
531                // `structural_defect` is what a caller acts on.
532                Some(_) => {}
533                None if entry.disposition == DISPOSITION_REJECT => {}
534                None => effective = None,
535            }
536        }
537        effective
538    }
539
540    /// The index of the proposal whose entry currently makes `slug`'s marks
541    /// effective, when one does. The row a write must move or replace, rather
542    /// than the first row that happens to name the slug: moving the first
543    /// relocated a `reject`'s reason and content hash onto another slug and
544    /// took the re-proposal gate with it.
545    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    /// Every slug the record makes marks effective for, in one pass.
562    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    /// Why the record cannot be read as evidence of anything, when it cannot:
582    /// an entry recording a structurally empty `landed_sections` map, which no
583    /// engine write produces. Such a record has been hand-edited or
584    /// half-written, so which bodies came from a contributor is unknown, and
585    /// unknown resolves to the stranger's side: the read serves every entity
586    /// of the mem third-party, and every write that follows a mark (the
587    /// rename, the retype re-key, the rehash after a link retarget, the
588    /// export's carry) refuses to touch the record at all, because repairing
589    /// it would lift a quarantine the read installed on purpose.
590    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    /// Parse the record's bytes; a malformed record is an error the
608    /// caller names, never an empty record.
609    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
610        serde_json::from_slice(bytes)
611    }
612
613    /// The rejections that match an entry: by the proposed content hash
614    /// (the same body) or by slug (the same id), in record order.
615    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
649/// The proposal id the record keys by: the fork's name and its base sha.
650pub fn proposal_id(fork: &str, base: &str) -> String {
651    format!("{fork}@{base}")
652}
653
654impl ProposalRecord {
655    /// Serialise the record as the bytes the merge commits: pretty
656    /// JSON with a trailing newline, diff-friendly on the branch.
657    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// ---------------------------------------------------------------------------
665// The merge: the owner's body and the outcome
666// ---------------------------------------------------------------------------
667
668/// The owner's final body under `adopt_with_changes`, in the shape a
669/// create takes: `sections` (key to content), `metadata` (key to
670/// value), an optional `title` (which must equal the landed title: a
671/// title change is a rename, not a merge) and optional `relations`
672/// (which replace the landed relations when present). Parsed from
673/// [`DispositionSlot::body`] by the merge; the write gate validates the
674/// result like any update.
675#[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/// One relation of an owner's final body.
688#[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/// What `Engine::proposal_merge` did: the commits it landed, one line
697/// per entity the brief listed, the check records it wrote, and the
698/// post-merge validation of the target.
699#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
700pub struct ProposalMergeOutcome {
701    pub fork: String,
702    pub target: String,
703    pub proposal_id: String,
704    /// The merger's identity (the session's `--identity`).
705    pub merged_by: String,
706    /// The target tip the file pinned, which the first merge commit
707    /// has as its parent.
708    pub target_tip_before: String,
709    /// The target tip after the last commit the merge landed.
710    pub target_tip_after: String,
711    /// The merge commits, one per proposer identity in slug order,
712    /// each parent-pinned to the previous.
713    pub merge_commits: Vec<MergeCommit>,
714    /// The commit carrying the owner's final bodies of every
715    /// `adopt_with_changes` entity, under the merger's identity; absent
716    /// when none was needed.
717    #[serde(default, skip_serializing_if = "Option::is_none")]
718    pub amend_commit: Option<MergeCommit>,
719    /// One line per entity the brief listed, in slug order.
720    pub entities: Vec<MergedEntity>,
721    /// The record sidecar's path on the target branch.
722    pub record_path: String,
723    /// The post-merge validation of the whole target store.
724    pub validation: MergeValidation,
725    /// What the bookkeeping after the last commit could not do, one
726    /// line each with the cause and the recovery: a verification check
727    /// the ledger refused (the entity's `check_recorded` is false), the
728    /// re-read of the target from its backend, the validation reading,
729    /// the tip read back. Every commit stands whenever an outcome is
730    /// returned; a merge that refuses returns an error and lands
731    /// nothing. Empty when everything after the commits went through.
732    #[serde(default, skip_serializing_if = "Vec::is_empty")]
733    pub warnings: Vec<MergeWarning>,
734}
735
736/// A step after a landed merge commit that failed, as the
737/// `WRITE_FOLLOW_UP_FAILED` warning every write reports, in its wire shape
738/// (`code`, `message`, `details` with `mem`, `step`, `detail`).
739#[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    /// The warning of a failed follow-up step of the merge into `mem`.
748    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    /// A warning the commit call reported, in the outcome's shape.
757    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/// One commit a merge landed.
768#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
769pub struct MergeCommit {
770    pub sha: String,
771    /// The commit's `Identity:` trailer: the proposer on a merge commit,
772    /// the merger on the amend commit and on the record-only commit an
773    /// all-reject merge lands.
774    pub identity: String,
775    /// The target ids the commit touched, in slug order; empty on the
776    /// record-only commit.
777    pub entities: Vec<String>,
778}
779
780/// What the merge did with one entity of the brief.
781#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
782pub struct MergedEntity {
783    pub slug: String,
784    pub target_id: String,
785    pub disposition: String,
786    /// `created`, `updated`, `deleted`, `noop` (the fork's version
787    /// equals the target's), or `none` (rejected: nothing landed).
788    pub action: String,
789    /// The proposer read off the fork commit that last touched this
790    /// entity: the identity the merge commit carries for an adopted
791    /// entity, the identity recorded for a rejected one; absent on a
792    /// rejected entity whose fork commit carries none.
793    #[serde(default, skip_serializing_if = "Option::is_none")]
794    pub proposer: Option<String>,
795    /// The content hash of the entity as it stands in the target after
796    /// the merge (after the amend commit for `adopt_with_changes`);
797    /// absent for a deletion or a rejection.
798    #[serde(default, skip_serializing_if = "Option::is_none")]
799    pub content_hash: Option<String>,
800    /// Whether a verification check record under the merger's identity
801    /// was written for it (every adopted entity that still exists).
802    pub check_recorded: bool,
803}
804
805/// The post-merge validation: the target mem re-read from its backend
806/// after the last commit, with every entity parsing under the schema
807/// and the integrity and conformance axes reporting no finding the
808/// pre-merge store did not already carry. The write gate ran per
809/// adopted entity before anything landed; this is the whole-store
810/// reading after.
811#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
812pub struct MergeValidation {
813    /// Entities the target serves after the re-read.
814    pub entities: usize,
815    /// Findings (integrity and conformance axes) before the merge.
816    pub findings_before: usize,
817    /// Findings after the merge.
818    pub findings_after: usize,
819    /// Findings present after the merge and absent before, as
820    /// `<id>: <code>`; empty when the store validates.
821    #[serde(default, skip_serializing_if = "Vec::is_empty")]
822    pub new_findings: Vec<String>,
823    /// Whether every entity of the target parsed on the re-read; false
824    /// also when the re-read itself did not complete (the outcome's
825    /// `warnings` say why).
826    pub all_entities_parse: bool,
827}
828
829impl MergeValidation {
830    /// Whether the whole store validates: everything parses and no new
831    /// finding appeared.
832    pub fn is_clean(&self) -> bool {
833        self.all_entities_parse && self.new_findings.is_empty()
834    }
835}
836
837/// Render a merge outcome for a human.
838pub 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
926/// Render a target's proposal record for a human: one block per
927/// merged proposal, newest last, with every disposition.
928pub 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        // The owner's words, as written, under the header.
943        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
976// ---------------------------------------------------------------------------
977// The markdown rendering
978// ---------------------------------------------------------------------------
979
980/// The fence that wraps a body: four backticks, so a body carrying a
981/// three-backtick block renders whole.
982const BODY_FENCE: &str = "````";
983
984/// Render the brief for a human. Deterministic: the same brief renders
985/// the same bytes.
986pub 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    /// The skeleton carries the closed vocabulary, and a conflict slot
1319    /// withholds `adopt`; the wire keys are the ones the merge reads;
1320    /// the description slot is emitted empty beside the dispositions.
1321    #[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        // A file rendered before the slot existed still parses.
1355        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        // The JSON round-trips through the same types the merge reads.
1363        let back: ProposalBrief = serde_json::from_value(json).unwrap();
1364        assert_eq!(back, b);
1365    }
1366
1367    /// The markdown names the four shas, one block per entity, the
1368    /// differing sections, the referrers, the anchor row with its span
1369    /// and unobserved state, the precheck, the conflict with its three
1370    /// versions; and it renders the same bytes twice.
1371    #[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        // No clock, no em dash.
1397        assert!(!md.contains('\u{2014}'));
1398    }
1399
1400    /// The fallback line for a fork without a recorded base, and an
1401    /// empty brief.
1402    #[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    /// The record parses with unknown keys tolerated, an absent record
1414    /// is the caller's empty default, and the rejection match names
1415    /// the hash before the id.
1416    #[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        // An entry written before the description existed reads as
1422        // none, and writes back without the key.
1423        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        // Same body under a new slug: matched by hash.
1443        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        // Same slug, different body: matched by id.
1449        let marks = record.rejections_matching("alpha", Some("h9"));
1450        assert_eq!(marks.len(), 1);
1451        assert_eq!(marks[0].matched_by, "id");
1452        // An adopted entity never marks.
1453        assert!(record.rejections_matching("beta", Some("h2")).is_empty());
1454        // Malformed bytes refuse rather than read as empty.
1455        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}