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<String>,
734}
735
736/// One commit a merge landed.
737#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
738pub struct MergeCommit {
739    pub sha: String,
740    /// The commit's `Identity:` trailer: the proposer on a merge commit,
741    /// the merger on the amend commit and on the record-only commit an
742    /// all-reject merge lands.
743    pub identity: String,
744    /// The target ids the commit touched, in slug order; empty on the
745    /// record-only commit.
746    pub entities: Vec<String>,
747}
748
749/// What the merge did with one entity of the brief.
750#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
751pub struct MergedEntity {
752    pub slug: String,
753    pub target_id: String,
754    pub disposition: String,
755    /// `created`, `updated`, `deleted`, `noop` (the fork's version
756    /// equals the target's), or `none` (rejected: nothing landed).
757    pub action: String,
758    /// The proposer read off the fork commit that last touched this
759    /// entity: the identity the merge commit carries for an adopted
760    /// entity, the identity recorded for a rejected one; absent on a
761    /// rejected entity whose fork commit carries none.
762    #[serde(default, skip_serializing_if = "Option::is_none")]
763    pub proposer: Option<String>,
764    /// The content hash of the entity as it stands in the target after
765    /// the merge (after the amend commit for `adopt_with_changes`);
766    /// absent for a deletion or a rejection.
767    #[serde(default, skip_serializing_if = "Option::is_none")]
768    pub content_hash: Option<String>,
769    /// Whether a verification check record under the merger's identity
770    /// was written for it (every adopted entity that still exists).
771    pub check_recorded: bool,
772}
773
774/// The post-merge validation: the target mem re-read from its backend
775/// after the last commit, with every entity parsing under the schema
776/// and the integrity and conformance axes reporting no finding the
777/// pre-merge store did not already carry. The write gate ran per
778/// adopted entity before anything landed; this is the whole-store
779/// reading after.
780#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
781pub struct MergeValidation {
782    /// Entities the target serves after the re-read.
783    pub entities: usize,
784    /// Findings (integrity and conformance axes) before the merge.
785    pub findings_before: usize,
786    /// Findings after the merge.
787    pub findings_after: usize,
788    /// Findings present after the merge and absent before, as
789    /// `<id>: <code>`; empty when the store validates.
790    #[serde(default, skip_serializing_if = "Vec::is_empty")]
791    pub new_findings: Vec<String>,
792    /// Whether every entity of the target parsed on the re-read; false
793    /// also when the re-read itself did not complete (the outcome's
794    /// `warnings` say why).
795    pub all_entities_parse: bool,
796}
797
798impl MergeValidation {
799    /// Whether the whole store validates: everything parses and no new
800    /// finding appeared.
801    pub fn is_clean(&self) -> bool {
802        self.all_entities_parse && self.new_findings.is_empty()
803    }
804}
805
806/// Render a merge outcome for a human.
807pub 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
895/// Render a target's proposal record for a human: one block per
896/// merged proposal, newest last, with every disposition.
897pub 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        // The owner's words, as written, under the header.
912        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
945// ---------------------------------------------------------------------------
946// The markdown rendering
947// ---------------------------------------------------------------------------
948
949/// The fence that wraps a body: four backticks, so a body carrying a
950/// three-backtick block renders whole.
951const BODY_FENCE: &str = "````";
952
953/// Render the brief for a human. Deterministic: the same brief renders
954/// the same bytes.
955pub 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    /// The skeleton carries the closed vocabulary, and a conflict slot
1288    /// withholds `adopt`; the wire keys are the ones the merge reads;
1289    /// the description slot is emitted empty beside the dispositions.
1290    #[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        // A file rendered before the slot existed still parses.
1324        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        // The JSON round-trips through the same types the merge reads.
1332        let back: ProposalBrief = serde_json::from_value(json).unwrap();
1333        assert_eq!(back, b);
1334    }
1335
1336    /// The markdown names the four shas, one block per entity, the
1337    /// differing sections, the referrers, the anchor row with its span
1338    /// and unobserved state, the precheck, the conflict with its three
1339    /// versions; and it renders the same bytes twice.
1340    #[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        // No clock, no em dash.
1366        assert!(!md.contains('\u{2014}'));
1367    }
1368
1369    /// The fallback line for a fork without a recorded base, and an
1370    /// empty brief.
1371    #[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    /// The record parses with unknown keys tolerated, an absent record
1383    /// is the caller's empty default, and the rejection match names
1384    /// the hash before the id.
1385    #[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        // An entry written before the description existed reads as
1391        // none, and writes back without the key.
1392        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        // Same body under a new slug: matched by hash.
1412        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        // Same slug, different body: matched by id.
1418        let marks = record.rejections_matching("alpha", Some("h9"));
1419        assert_eq!(marks.len(), 1);
1420        assert_eq!(marks[0].matched_by, "id");
1421        // An adopted entity never marks.
1422        assert!(record.rejections_matching("beta", Some("h2")).is_empty());
1423        // Malformed bytes refuse rather than read as empty.
1424        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}