memstead-base 0.24.0

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
//! The proposal brief: a fork's changes against its source, three ways.
//!
//! `Engine::proposal_brief(fork)` renders the entity-level picture the
//! owner of a mem reviews before merging a fork: every entity the fork
//! added, modified, deleted or renamed against its base (the fork
//! commit, or the ancestor for a fork made before fork commits existed),
//! each with the sections that differ, the target's referrers, the
//! anchor rows it rests on, a mechanics precheck through the target's
//! write gate, a conflict mark where the target moved the same entity
//! since the ancestor, and a re-proposal mark where the target's
//! proposal record already holds a rejection of the same content or id.
//!
//! The wire shape ([`ProposalBrief`]) is the JSON the CLI writes with
//! `--out` and the MCP tool serves as `structured_content`; its
//! `dispositions` map is the skeleton the owner fills and the merge
//! consumes. [`render_proposal_brief`] renders the same data as
//! markdown for a human. Rendering is deterministic: entries sort by
//! slug and nothing carries a clock.
//!
//! The brief is a read. It writes nothing anywhere.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

/// The closed disposition vocabulary, in the order the skeleton lists
/// it. A conflict entity's slot omits `adopt`.
pub const DISPOSITION_VOCABULARY: &[&str] = &["adopt", "adopt_with_changes", "reject"];

/// The disposition of an adopted entity.
pub const DISPOSITION_ADOPT: &str = "adopt";
/// The disposition of an entity the owner adopts with a final body of
/// their own.
pub const DISPOSITION_ADOPT_WITH_CHANGES: &str = "adopt_with_changes";
/// The disposition of a rejected entity.
pub const DISPOSITION_REJECT: &str = "reject";

/// The proposal record's path on a target branch: the sidecar the
/// merge appends to and the brief reads for re-proposal marks.
pub const PROPOSAL_RECORD_PATH: &str = ".memstead/proposals.json";

/// The proposal record's format version.
pub const PROPOSAL_RECORD_VERSION: u32 = 1;

/// The brief of one fork against its source mem.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalBrief {
    /// The fork mem's name.
    pub fork: String,
    /// The source mem's name: the target of the proposal.
    pub target: String,
    /// The proposal's id: the fork's name and its base sha, the key the
    /// proposal record uses.
    pub proposal_id: String,
    /// The ancestor on the target (`forkedFrom.sha`).
    pub ancestor: String,
    /// The commit the fork's changes are read against: the fork commit
    /// (`forkedFrom.base`) when one was recorded, the ancestor otherwise.
    pub base: String,
    /// Whether the base is the ancestor itself (a fork made before fork
    /// commits existed recorded no base).
    pub base_is_ancestor: bool,
    /// The fork's branch tip at render time.
    pub fork_tip: String,
    /// The target's branch tip at render time; the merge pins it.
    pub target_tip: String,
    /// Counts over `entries`.
    pub summary: ProposalSummary,
    /// One entry per entity the fork touched, sorted by slug.
    pub entries: Vec<ProposalEntry>,
    /// The proposal in the owner's words: free text the owner writes
    /// into the disposition file, which the merge records on the
    /// proposal record's entry so a reader of the record (or of a
    /// published archive) learns what the proposal was, not only what
    /// happened to each entity. The skeleton emits it empty; the merge
    /// trims it and treats a blank slot as absent (the merge's note
    /// stands in then, when one was given). Absent in a file rendered
    /// before the slot existed.
    #[serde(default)]
    pub description: String,
    /// The disposition skeleton, keyed by slug: the owner fills
    /// `disposition` (and `reason`, and for `adopt_with_changes` a
    /// `body`) and hands the file to the merge.
    pub dispositions: BTreeMap<String, DispositionSlot>,
}

/// Counts over a brief's entries.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProposalSummary {
    pub added: usize,
    pub modified: usize,
    pub deleted: usize,
    pub renamed: usize,
    pub conflicts: usize,
    pub precheck_failures: usize,
    pub re_proposals: usize,
}

/// What the fork did to one entity, read against the base.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProposalChange {
    Added,
    Modified,
    Deleted,
    Renamed,
}

impl ProposalChange {
    /// Stable wire form.
    pub fn as_wire(self) -> &'static str {
        match self {
            ProposalChange::Added => "added",
            ProposalChange::Modified => "modified",
            ProposalChange::Deleted => "deleted",
            ProposalChange::Renamed => "renamed",
        }
    }
}

/// One entity the fork touched.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalEntry {
    /// The entity's slug: the part of the id after the mem name, the
    /// key the two mems share.
    pub slug: String,
    /// The entity's id in the fork (`<fork>--<slug>`).
    pub fork_id: String,
    /// The entity's id in the target (`<target>--<slug>`).
    pub target_id: String,
    /// What the fork did.
    pub status: ProposalChange,
    /// For a renamed entity: the slug it had at the base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub renamed_from: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entity_type: Option<String>,
    /// The hash of the proposed version as it would land in the target
    /// (the fork's body with its self-links under the target's name),
    /// computed with the engine's date stamps (`created_date`,
    /// `last_modified`) left out, so the same body proposed again from
    /// another fork hashes the same; absent for a deletion. The
    /// proposal record stores the same hash, so a rejected body is
    /// recognised when a later fork proposes it again. Not the
    /// entity's `_hash` (the file hash, stamps included).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_hash: Option<String>,
    /// How the fork's version differs from the base (absent for an
    /// added or deleted entity, and when a side does not parse).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fork_delta: Option<VersionDelta>,
    /// The target's referrers of this entity: entities in the target
    /// or in other mems holding an edge to it (the fork's own excluded).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub referrers: Vec<Referrer>,
    /// The anchor rows the fork's entity rests on, read from the
    /// fork's sidecar under the fork's ids; no observation is fetched.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub anchors: Vec<AnchorRow>,
    /// The mechanics precheck through the target's write gate.
    pub precheck: Precheck,
    /// Present when the target moved the same entity since the ancestor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conflict: Option<Conflict>,
    /// Present when the target's proposal record holds a rejection of
    /// the same content hash or the same id.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub re_proposal: Vec<ReProposalMark>,
    /// The base's body, with mem qualifiers normalised to the fork's
    /// name (absent for an added entity).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_body: Option<String>,
    /// The fork's body, the proposed version (absent for a deletion).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fork_body: Option<String>,
}

/// How one side's version differs from the base.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct VersionDelta {
    pub title_differs: bool,
    pub entity_type_differs: bool,
    /// Section keys whose content differs, or that one side has and
    /// the other lacks, in the order the fork's body declares them.
    pub sections: Vec<String>,
    /// Metadata keys whose value differs (the engine-stamped
    /// `created_date` and `last_modified` never count).
    pub metadata: Vec<String>,
    pub relationships_differ: bool,
}

impl VersionDelta {
    /// Whether anything differs.
    pub fn is_empty(&self) -> bool {
        !self.title_differs
            && !self.entity_type_differs
            && self.sections.is_empty()
            && self.metadata.is_empty()
            && !self.relationships_differ
    }
}

/// An entity holding an edge to the target's entity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Referrer {
    pub id: String,
    pub rel_type: String,
}

/// One anchor row of the fork's entity, as stored.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnchorRow {
    pub artifact: String,
    pub grain: String,
    pub class: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<String>,
    /// The last recorded state of the row (`resolves`, `drifted`,
    /// `recheck`, `orphaned`, `span_absent`); absent when the row was
    /// never observed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_state: Option<String>,
    /// When that state was recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_observed_at: Option<String>,
}

/// The mechanics precheck: would the fork's body pass the target's
/// write gate as it stands. Never a content judgement.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Precheck {
    pub outcome: PrecheckOutcome,
    /// The rehearsed operation (`create` or `update`) when one ran.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operation: Option<String>,
    /// The typed refusal the gate returned, when it refused.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub failures: Vec<PrecheckFailure>,
    /// Why no operation ran, when none did.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

impl Precheck {
    pub fn clean(operation: &str) -> Self {
        Self {
            outcome: PrecheckOutcome::Clean,
            operation: Some(operation.to_string()),
            failures: Vec::new(),
            note: None,
        }
    }

    pub fn failed(operation: &str, failures: Vec<PrecheckFailure>) -> Self {
        Self {
            outcome: PrecheckOutcome::Failed,
            operation: Some(operation.to_string()),
            failures,
            note: None,
        }
    }

    pub fn not_run(note: &str) -> Self {
        Self {
            outcome: PrecheckOutcome::NotRun,
            operation: None,
            failures: Vec::new(),
            note: Some(note.to_string()),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PrecheckOutcome {
    Clean,
    Failed,
    NotRun,
}

impl PrecheckOutcome {
    pub fn as_wire(self) -> &'static str {
        match self {
            PrecheckOutcome::Clean => "clean",
            PrecheckOutcome::Failed => "failed",
            PrecheckOutcome::NotRun => "not_run",
        }
    }
}

/// One typed refusal of the write gate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PrecheckFailure {
    pub code: String,
    pub message: String,
}

/// The target moved the same entity since the ancestor.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Conflict {
    pub kind: ConflictKind,
    /// How the target's version differs from the base (when both parse).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_delta: Option<VersionDelta>,
    /// The target's body, mem qualifiers normalised to the fork's name
    /// (absent when the target deleted the entity).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_body: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConflictKind {
    /// The target modified an entity the fork modified, deleted or
    /// renamed.
    TargetModified,
    /// The target deleted (or renamed away) an entity the fork
    /// modified, deleted or renamed.
    TargetDeleted,
    /// The target created an entity with a slug the fork added.
    TargetAdded,
}

impl ConflictKind {
    pub fn as_wire(self) -> &'static str {
        match self {
            ConflictKind::TargetModified => "target_modified",
            ConflictKind::TargetDeleted => "target_deleted",
            ConflictKind::TargetAdded => "target_added",
        }
    }

    fn describe(self) -> &'static str {
        match self {
            ConflictKind::TargetModified => "the target modified this entity since the ancestor",
            ConflictKind::TargetDeleted => "the target deleted this entity since the ancestor",
            ConflictKind::TargetAdded => {
                "the target created an entity with this slug since the ancestor"
            }
        }
    }
}

/// A rejection in the target's proposal record that this entry matches.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReProposalMark {
    /// `content_hash` (the same proposed body) or `id` (the same slug).
    pub matched_by: String,
    /// The recorded proposal's id.
    pub proposal: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// One slot of the disposition skeleton.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DispositionSlot {
    /// Empty in the skeleton; one of `accepts` once filled.
    pub disposition: String,
    /// Empty in the skeleton; required for `reject` and
    /// `adopt_with_changes`, optional on `adopt`. Recorded whenever
    /// given.
    pub reason: String,
    /// The values this slot accepts: the closed vocabulary, without
    /// `adopt` on a conflict entity.
    pub accepts: Vec<String>,
    /// For `adopt_with_changes`: the owner's final body in the shape a
    /// create takes (`title`, `sections`, `metadata`); absent in the
    /// skeleton.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<serde_json::Value>,
}

impl DispositionSlot {
    /// The empty slot for an entry, `adopt` withheld on a conflict.
    pub fn skeleton(conflict: bool) -> Self {
        let accepts = DISPOSITION_VOCABULARY
            .iter()
            .filter(|v| !(conflict && **v == DISPOSITION_ADOPT))
            .map(|v| (*v).to_string())
            .collect();
        Self {
            disposition: String::new(),
            reason: String::new(),
            accepts,
            body: None,
        }
    }
}

// ---------------------------------------------------------------------------
// The proposal record
// ---------------------------------------------------------------------------

/// The proposal record a target branch carries at
/// [`PROPOSAL_RECORD_PATH`]: one entry per merged proposal with every
/// disposition, so a rejected claim cannot return unseen. The merge
/// writes it; the brief reads it. Unknown keys are tolerated so an
/// older reader survives a newer writer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalRecord {
    #[serde(default = "default_record_version")]
    pub version: u32,
    #[serde(default)]
    pub proposals: Vec<ProposalRecordEntry>,
}

fn default_record_version() -> u32 {
    PROPOSAL_RECORD_VERSION
}

impl Default for ProposalRecord {
    /// The empty record at the current format version (the derive
    /// would say version 0).
    fn default() -> Self {
        Self {
            version: PROPOSAL_RECORD_VERSION,
            proposals: Vec::new(),
        }
    }
}

/// One merged proposal in the record.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ProposalRecordEntry {
    /// The proposal's id: the fork's name and its base sha.
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proposer: Option<String>,
    #[serde(default)]
    pub ancestor: String,
    #[serde(default)]
    pub base: String,
    #[serde(default)]
    pub target_tip: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merged_by: Option<String>,
    #[serde(default)]
    pub at: String,
    /// The proposal in the owner's words: the disposition file's
    /// `description`, or the merge's note when the file carried none.
    /// Absent when neither was given, and on every entry written before
    /// the field existed; the key is left off the bytes then.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Per slug: the disposition, the reason and the content hash of
    /// the proposed version (never its body).
    #[serde(default)]
    pub entities: BTreeMap<String, RecordedDisposition>,
}

/// One entity's disposition in the record.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecordedDisposition {
    pub disposition: String,
    /// The owner's reason: always present on `reject` and
    /// `adopt_with_changes`, present on `adopt` when the owner gave one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_hash: Option<String>,
    /// For an `adopt`: one prepared hash per LOAD-BEARING section of the
    /// body the merge landed, keyed by section key
    /// ([`crate::preparation::entity_load_bearing_section_marks`]).
    ///
    /// This is the adopt-time decision that
    /// [`crate::engine::Engine::entity_origin_class`] reports at read
    /// time: while any recorded section still hashes to the value here,
    /// that section is the proposer's bytes, so the entity serves
    /// `third-party`.
    ///
    /// Per section, and prepared rather than the file hash, for three
    /// reasons the coarser forms each get wrong. The file hash moves on a
    /// metadata stamp or a notes-only edit, so a stranger's claim would
    /// promote itself to first-party on the owner's next unrelated edit.
    /// One hash over the whole load-bearing form collapses a type's
    /// sections to one bit, so rewriting one of three would clear a mark
    /// still covering the other two. And a per-section hash carries its
    /// own section key, so the comparison needs neither the schema pin nor
    /// the entity type: a repin or a retype changes which sections a type
    /// calls load-bearing, and a comparison that depended on the current
    /// declaration would report a rewrite that never happened.
    ///
    /// A MERGE writes it only for an `adopt`: absent on an
    /// `adopt_with_changes` (the owner typed those bytes, so they are
    /// first-party), on a `reject` (nothing landed), on a deletion, and on
    /// every entry written before this field existed. A later rename may
    /// carry marks onto an entry of any disposition
    /// ([`crate::engine::mutation::move_marks_on_rename`]), because the
    /// entry then describes the body that is at that slug NOW rather than
    /// the one the proposal landed there; the other fields keep documenting
    /// the proposal. A
    /// legacy entry cannot confirm the comparison and inherits the mem's
    /// class, which is what the engine did before the field. A contributor
    /// cannot cause the absence: the record is written by the owner's
    /// merge, on the target branch, never by the fork.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub landed_sections: Option<BTreeMap<String, String>>,
}

/// The origin marks a record makes effective for one slug, and the one
/// structural verdict it can raise about itself.
///
/// These two methods are the ONLY reading of `landed_sections`. Both the read
/// path ([`crate::Engine::entity_origin_class`]) and every write that has to
/// follow a mark (rename, retype, the wiki-link retargets) go through them,
/// because four review rounds in a row found the same defect one position
/// over while the write path kept its own copy of these rules: it modelled
/// last-write-wins and retirement by hand and got one arm wrong each time.
/// One owner, so the arms cannot disagree.
impl ProposalRecord {
    /// The marks effective for `slug`: every proposal in record order, last
    /// write wins, a non-reject entry without marks retires the slug, and a
    /// `reject` retires nothing (it landed no bytes, so a later rejected
    /// proposal must not relabel a standing contribution).
    ///
    /// Only meaningful on a record with no [`Self::structural_defect`]; a
    /// caller that has not checked that is reading a record it does not
    /// understand.
    pub fn effective_marks(&self, slug: &str) -> Option<BTreeMap<String, String>> {
        let mut effective = None;
        for proposal in &self.proposals {
            let Some(entry) = proposal.entities.get(slug) else {
                continue;
            };
            match entry.landed_sections.as_ref() {
                Some(sections) if !sections.is_empty() => effective = Some(sections.clone()),
                // A structurally empty map is a defect, never a retirement;
                // `structural_defect` is what a caller acts on.
                Some(_) => {}
                None if entry.disposition == DISPOSITION_REJECT => {}
                None => effective = None,
            }
        }
        effective
    }

    /// The index of the proposal whose entry currently makes `slug`'s marks
    /// effective, when one does. The row a write must move or replace, rather
    /// than the first row that happens to name the slug: moving the first
    /// relocated a `reject`'s reason and content hash onto another slug and
    /// took the re-proposal gate with it.
    pub fn effective_marks_at(&self, slug: &str) -> Option<usize> {
        let mut at = None;
        for (idx, proposal) in self.proposals.iter().enumerate() {
            let Some(entry) = proposal.entities.get(slug) else {
                continue;
            };
            match entry.landed_sections.as_ref() {
                Some(sections) if !sections.is_empty() => at = Some(idx),
                Some(_) => {}
                None if entry.disposition == DISPOSITION_REJECT => {}
                None => at = None,
            }
        }
        at
    }

    /// Every slug the record makes marks effective for, in one pass.
    pub fn effective_marks_by_slug(&self) -> BTreeMap<String, BTreeMap<String, String>> {
        let mut out: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
        for proposal in &self.proposals {
            for (slug, entry) in &proposal.entities {
                match entry.landed_sections.as_ref() {
                    Some(sections) if !sections.is_empty() => {
                        out.insert(slug.clone(), sections.clone());
                    }
                    Some(_) => {}
                    None if entry.disposition == DISPOSITION_REJECT => {}
                    None => {
                        out.remove(slug);
                    }
                }
            }
        }
        out
    }

    /// Why the record cannot be read as evidence of anything, when it cannot:
    /// an entry recording a structurally empty `landed_sections` map, which no
    /// engine write produces. Such a record has been hand-edited or
    /// half-written, so which bodies came from a contributor is unknown, and
    /// unknown resolves to the stranger's side: the read serves every entity
    /// of the mem third-party, and every write that follows a mark (the
    /// rename, the retype re-key, the rehash after a link retarget, the
    /// export's carry) refuses to touch the record at all, because repairing
    /// it would lift a quarantine the read installed on purpose.
    pub fn structural_defect(&self) -> Option<String> {
        let defective = self.proposals.iter().any(|p| {
            p.entities
                .values()
                .any(|e| e.landed_sections.as_ref().is_some_and(|s| s.is_empty()))
        });
        defective.then(|| {
            format!(
                "an entry in {PROPOSAL_RECORD_PATH} records an empty `landed_sections` map, \
                 which no engine write produces: which bodies came from a contributor cannot \
                 be read from it"
            )
        })
    }
}

impl ProposalRecord {
    /// Parse the record's bytes; a malformed record is an error the
    /// caller names, never an empty record.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }

    /// The rejections that match an entry: by the proposed content hash
    /// (the same body) or by slug (the same id), in record order.
    pub fn rejections_matching(
        &self,
        slug: &str,
        content_hash: Option<&str>,
    ) -> Vec<ReProposalMark> {
        let mut marks = Vec::new();
        for proposal in &self.proposals {
            for (recorded_slug, recorded) in &proposal.entities {
                if recorded.disposition != DISPOSITION_REJECT {
                    continue;
                }
                let by_hash = matches!(
                    (content_hash, recorded.content_hash.as_deref()),
                    (Some(a), Some(b)) if a == b
                );
                if by_hash {
                    marks.push(ReProposalMark {
                        matched_by: "content_hash".to_string(),
                        proposal: proposal.id.clone(),
                        reason: recorded.reason.clone(),
                    });
                } else if recorded_slug == slug {
                    marks.push(ReProposalMark {
                        matched_by: "id".to_string(),
                        proposal: proposal.id.clone(),
                        reason: recorded.reason.clone(),
                    });
                }
            }
        }
        marks
    }
}

/// The proposal id the record keys by: the fork's name and its base sha.
pub fn proposal_id(fork: &str, base: &str) -> String {
    format!("{fork}@{base}")
}

impl ProposalRecord {
    /// Serialise the record as the bytes the merge commits: pretty
    /// JSON with a trailing newline, diff-friendly on the branch.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut s = serde_json::to_string_pretty(self).expect("proposal record serialises");
        s.push('\n');
        s.into_bytes()
    }
}

// ---------------------------------------------------------------------------
// The merge: the owner's body and the outcome
// ---------------------------------------------------------------------------

/// The owner's final body under `adopt_with_changes`, in the shape a
/// create takes: `sections` (key to content), `metadata` (key to
/// value), an optional `title` (which must equal the landed title: a
/// title change is a rename, not a merge) and optional `relations`
/// (which replace the landed relations when present). Parsed from
/// [`DispositionSlot::body`] by the merge; the write gate validates the
/// result like any update.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct DispositionBody {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default)]
    pub sections: indexmap::IndexMap<String, String>,
    #[serde(default)]
    pub metadata: indexmap::IndexMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub relations: Option<Vec<DispositionRelation>>,
}

/// One relation of an owner's final body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DispositionRelation {
    pub target: String,
    pub rel_type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// What `Engine::proposal_merge` did: the commits it landed, one line
/// per entity the brief listed, the check records it wrote, and the
/// post-merge validation of the target.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalMergeOutcome {
    pub fork: String,
    pub target: String,
    pub proposal_id: String,
    /// The merger's identity (the session's `--identity`).
    pub merged_by: String,
    /// The target tip the file pinned, which the first merge commit
    /// has as its parent.
    pub target_tip_before: String,
    /// The target tip after the last commit the merge landed.
    pub target_tip_after: String,
    /// The merge commits, one per proposer identity in slug order,
    /// each parent-pinned to the previous.
    pub merge_commits: Vec<MergeCommit>,
    /// The commit carrying the owner's final bodies of every
    /// `adopt_with_changes` entity, under the merger's identity; absent
    /// when none was needed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub amend_commit: Option<MergeCommit>,
    /// One line per entity the brief listed, in slug order.
    pub entities: Vec<MergedEntity>,
    /// The record sidecar's path on the target branch.
    pub record_path: String,
    /// The post-merge validation of the whole target store.
    pub validation: MergeValidation,
    /// What the bookkeeping after the last commit could not do, one
    /// line each with the cause and the recovery: a verification check
    /// the ledger refused (the entity's `check_recorded` is false), the
    /// re-read of the target from its backend, the validation reading,
    /// the tip read back. Every commit stands whenever an outcome is
    /// returned; a merge that refuses returns an error and lands
    /// nothing. Empty when everything after the commits went through.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

/// One commit a merge landed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MergeCommit {
    pub sha: String,
    /// The commit's `Identity:` trailer: the proposer on a merge commit,
    /// the merger on the amend commit and on the record-only commit an
    /// all-reject merge lands.
    pub identity: String,
    /// The target ids the commit touched, in slug order; empty on the
    /// record-only commit.
    pub entities: Vec<String>,
}

/// What the merge did with one entity of the brief.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MergedEntity {
    pub slug: String,
    pub target_id: String,
    pub disposition: String,
    /// `created`, `updated`, `deleted`, `noop` (the fork's version
    /// equals the target's), or `none` (rejected: nothing landed).
    pub action: String,
    /// The proposer read off the fork commit that last touched this
    /// entity: the identity the merge commit carries for an adopted
    /// entity, the identity recorded for a rejected one; absent on a
    /// rejected entity whose fork commit carries none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proposer: Option<String>,
    /// The content hash of the entity as it stands in the target after
    /// the merge (after the amend commit for `adopt_with_changes`);
    /// absent for a deletion or a rejection.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_hash: Option<String>,
    /// Whether a verification check record under the merger's identity
    /// was written for it (every adopted entity that still exists).
    pub check_recorded: bool,
}

/// The post-merge validation: the target mem re-read from its backend
/// after the last commit, with every entity parsing under the schema
/// and the integrity and conformance axes reporting no finding the
/// pre-merge store did not already carry. The write gate ran per
/// adopted entity before anything landed; this is the whole-store
/// reading after.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MergeValidation {
    /// Entities the target serves after the re-read.
    pub entities: usize,
    /// Findings (integrity and conformance axes) before the merge.
    pub findings_before: usize,
    /// Findings after the merge.
    pub findings_after: usize,
    /// Findings present after the merge and absent before, as
    /// `<id>: <code>`; empty when the store validates.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub new_findings: Vec<String>,
    /// Whether every entity of the target parsed on the re-read; false
    /// also when the re-read itself did not complete (the outcome's
    /// `warnings` say why).
    pub all_entities_parse: bool,
}

impl MergeValidation {
    /// Whether the whole store validates: everything parses and no new
    /// finding appeared.
    pub fn is_clean(&self) -> bool {
        self.all_entities_parse && self.new_findings.is_empty()
    }
}

/// Render a merge outcome for a human.
pub fn render_proposal_merge(o: &ProposalMergeOutcome) -> String {
    let mut out = String::new();
    out.push_str(&format!(
        "# Proposal `{}` merged into `{}`\n\n",
        o.proposal_id, o.target
    ));
    out.push_str(&format!("- Merged by: `{}`\n", o.merged_by));
    out.push_str(&format!(
        "- Target tip: `{}` before, `{}` after\n",
        o.target_tip_before, o.target_tip_after
    ));
    for c in &o.merge_commits {
        if c.entities.is_empty() {
            out.push_str(&format!(
                "- Record commit `{}` under merger `{}`: nothing adopted\n",
                c.sha, c.identity
            ));
            continue;
        }
        out.push_str(&format!(
            "- Merge commit `{}` under proposer `{}`: {}\n",
            c.sha,
            c.identity,
            c.entities
                .iter()
                .map(|e| format!("`{e}`"))
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    if let Some(c) = &o.amend_commit {
        out.push_str(&format!(
            "- Amend commit `{}` under merger `{}`: {}\n",
            c.sha,
            c.identity,
            c.entities
                .iter()
                .map(|e| format!("`{e}`"))
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    out.push_str(&format!(
        "- Record: `{}` on `{}`\n",
        o.record_path, o.target
    ));
    out.push_str("\n## Entities\n\n");
    for e in &o.entities {
        let mut line = format!("- `{}`: {} ({})", e.slug, e.disposition, e.action);
        if let Some(p) = &e.proposer {
            line.push_str(&format!(", proposer `{p}`"));
        }
        if let Some(h) = &e.content_hash {
            line.push_str(&format!(", hash `{h}`"));
        }
        if e.check_recorded {
            line.push_str(", check recorded");
        }
        out.push_str(&line);
        out.push('\n');
    }
    let v = &o.validation;
    out.push_str("\n## Validation\n\n");
    out.push_str(&format!(
        "- {} entities re-read; every entity parses: {}; findings {} before, {} after\n",
        v.entities,
        if v.all_entities_parse { "yes" } else { "NO" },
        v.findings_before,
        v.findings_after
    ));
    if v.new_findings.is_empty() {
        out.push_str("- New findings: none (the whole store validates)\n");
    } else {
        out.push_str("- New findings:\n");
        for f in &v.new_findings {
            out.push_str(&format!("  - {f}\n"));
        }
    }
    if !o.warnings.is_empty() {
        out.push_str("\n## Warnings\n\n");
        out.push_str("The merge landed; the bookkeeping after the last commit did not complete:\n");
        for w in &o.warnings {
            out.push_str(&format!("- {w}\n"));
        }
    }
    out
}

/// Render a target's proposal record for a human: one block per
/// merged proposal, newest last, with every disposition.
pub fn render_proposal_record(target: &str, record: &ProposalRecord) -> String {
    let mut out = String::new();
    out.push_str(&format!("# Proposals merged into `{target}`\n\n"));
    if record.proposals.is_empty() {
        out.push_str("No proposal has been merged into this mem.\n");
        return out;
    }
    out.push_str(&format!(
        "- Record: `{PROPOSAL_RECORD_PATH}` (version {}), {} proposal(s)\n",
        record.version,
        record.proposals.len()
    ));
    for p in &record.proposals {
        out.push_str(&format!("\n## `{}`\n\n", p.id));
        // The owner's words, as written, under the header.
        if let Some(d) = &p.description {
            out.push_str(d);
            out.push_str("\n\n");
        }
        out.push_str(&format!(
            "- Proposer: `{}`; merged by `{}` at {}\n",
            p.proposer.as_deref().unwrap_or("(unrecorded)"),
            p.merged_by.as_deref().unwrap_or("(unrecorded)"),
            if p.at.is_empty() {
                "(unrecorded)"
            } else {
                &p.at
            }
        ));
        out.push_str(&format!(
            "- Ancestor `{}`; base `{}`; target tip at merge `{}`\n",
            p.ancestor, p.base, p.target_tip
        ));
        for (slug, d) in &p.entities {
            let mut line = format!("- `{slug}`: {}", d.disposition);
            if let Some(r) = &d.reason {
                line.push_str(&format!(" ({r})"));
            }
            if let Some(h) = &d.content_hash {
                line.push_str(&format!(", proposed hash `{h}`"));
            }
            out.push_str(&line);
            out.push('\n');
        }
    }
    out
}

// ---------------------------------------------------------------------------
// The markdown rendering
// ---------------------------------------------------------------------------

/// The fence that wraps a body: four backticks, so a body carrying a
/// three-backtick block renders whole.
const BODY_FENCE: &str = "````";

/// Render the brief for a human. Deterministic: the same brief renders
/// the same bytes.
pub fn render_proposal_brief(brief: &ProposalBrief) -> String {
    let mut out = String::new();
    out.push_str(&format!(
        "# Proposal brief: `{}` against `{}`\n\n",
        brief.fork, brief.target
    ));
    out.push_str(&format!("- Proposal: `{}`\n", brief.proposal_id));
    out.push_str(&format!(
        "- Ancestor on `{}`: `{}`\n",
        brief.target, brief.ancestor
    ));
    if brief.base_is_ancestor {
        out.push_str(&format!(
            "- Base: `{}` (no fork commit recorded; the ancestor is the base)\n",
            brief.base
        ));
    } else {
        out.push_str(&format!("- Base (the fork commit): `{}`\n", brief.base));
    }
    out.push_str(&format!("- Fork tip: `{}`\n", brief.fork_tip));
    out.push_str(&format!(
        "- Target tip: `{}` (at render time; the merge pins it)\n",
        brief.target_tip
    ));
    let s = &brief.summary;
    out.push_str(&format!(
        "- Entities: {} (added {}, modified {}, deleted {}, renamed {}); conflicts {}; precheck failures {}; re-proposals {}\n\n",
        brief.entries.len(),
        s.added,
        s.modified,
        s.deleted,
        s.renamed,
        s.conflicts,
        s.precheck_failures,
        s.re_proposals
    ));
    out.push_str(
        "Dispositions: in the JSON form (`--json`, or `--out <file>`), fill each \
         `dispositions.<slug>.disposition` with one of `adopt`, `adopt_with_changes`, `reject`; \
         `reject` and `adopt_with_changes` need a `reason`; `adopt_with_changes` carries the \
         owner's final body as `body` in the shape a create takes (`title`, `sections`, \
         `metadata`); a conflict entity accepts no `adopt`; `adopt` may carry a `reason` \
         too. The top-level `description` slot takes the proposal in the owner's words, \
         recorded with the merge. The merge validates the file against these shas.\n",
    );
    if brief.entries.is_empty() {
        out.push_str("\nThe fork has no change against its base.\n");
        return out;
    }
    for entry in &brief.entries {
        out.push('\n');
        render_entry(&mut out, brief, entry);
    }
    out
}

fn render_entry(out: &mut String, brief: &ProposalBrief, e: &ProposalEntry) {
    let title = e.title.as_deref().unwrap_or("(no title)");
    out.push_str(&format!(
        "## `{}`: {} ({})\n\n",
        e.slug,
        e.status.as_wire(),
        title
    ));
    out.push_str(&format!(
        "- Type: {}\n",
        e.entity_type.as_deref().unwrap_or("(unknown)")
    ));
    out.push_str(&format!(
        "- Fork id: `{}`; target id: `{}`\n",
        e.fork_id, e.target_id
    ));
    if let Some(from) = &e.renamed_from {
        out.push_str(&format!("- Renamed from: `{from}`\n"));
    }
    if let Some(hash) = &e.content_hash {
        out.push_str(&format!("- Proposed content hash: `{hash}`\n"));
    }
    match e.status {
        ProposalChange::Added => {
            out.push_str("- Difference against base: the whole entity is new\n")
        }
        ProposalChange::Deleted => {
            out.push_str("- Difference against base: the entity is removed\n")
        }
        ProposalChange::Modified | ProposalChange::Renamed => {
            out.push_str(&format!(
                "- Differences (fork against base): {}\n",
                render_delta(e.fork_delta.as_ref())
            ));
        }
    }
    if e.referrers.is_empty() {
        out.push_str("- Target referrers: none\n");
    } else {
        let list: Vec<String> = e
            .referrers
            .iter()
            .map(|r| format!("`{}` ({})", r.id, r.rel_type))
            .collect();
        out.push_str(&format!("- Target referrers: {}\n", list.join(", ")));
    }
    if e.anchors.is_empty() {
        out.push_str("- Anchors: none\n");
    } else {
        out.push_str("- Anchors:\n");
        for a in &e.anchors {
            let span = match &a.span {
                Some(s) => format!("; span: \"{s}\""),
                None => String::new(),
            };
            let state = match (&a.last_state, &a.last_observed_at) {
                (Some(state), Some(at)) => format!("; last state: {state} at {at}"),
                (Some(state), None) => format!("; last state: {state}"),
                (None, _) => "; last state: unobserved".to_string(),
            };
            out.push_str(&format!(
                "  - `{}` ({}, {}{span}{state})\n",
                a.artifact, a.grain, a.class
            ));
        }
    }
    match e.precheck.outcome {
        PrecheckOutcome::Clean => out.push_str(&format!(
            "- Precheck ({} in `{}`): clean\n",
            e.precheck.operation.as_deref().unwrap_or("gate"),
            brief.target
        )),
        PrecheckOutcome::Failed => {
            out.push_str(&format!(
                "- Precheck ({} in `{}`): FAILED\n",
                e.precheck.operation.as_deref().unwrap_or("gate"),
                brief.target
            ));
            for f in &e.precheck.failures {
                out.push_str(&format!("  - `{}`: {}\n", f.code, f.message));
            }
        }
        PrecheckOutcome::NotRun => out.push_str(&format!(
            "- Precheck: not run ({})\n",
            e.precheck.note.as_deref().unwrap_or("no operation applies")
        )),
    }
    if let Some(c) = &e.conflict {
        let target_side = match &c.target_delta {
            Some(d) => format!("; target against base: {}", render_delta(Some(d))),
            None => String::new(),
        };
        out.push_str(&format!(
            "- CONFLICT: {} ({}{target_side}); `adopt` is withheld, the owner supplies the merged body or rejects\n",
            c.kind.describe(),
            c.kind.as_wire()
        ));
    }
    for mark in &e.re_proposal {
        let reason = match &mark.reason {
            Some(r) => format!(": {r}"),
            None => String::new(),
        };
        let how = match mark.matched_by.as_str() {
            "content_hash" => "the same content",
            _ => "the same id",
        };
        out.push_str(&format!(
            "- RE-PROPOSAL: rejected in proposal `{}` ({how}){reason}\n",
            mark.proposal
        ));
    }
    if let Some(c) = &e.conflict {
        out.push_str("\n### Base version\n\n");
        render_body(out, e.base_body.as_deref());
        out.push_str("\n### Fork version\n\n");
        render_body(out, e.fork_body.as_deref());
        out.push_str("\n### Target version\n\n");
        render_body(out, c.target_body.as_deref());
        return;
    }
    match e.status {
        ProposalChange::Added => {
            out.push_str("\n### Proposed body\n\n");
            render_body(out, e.fork_body.as_deref());
        }
        ProposalChange::Deleted => {
            out.push_str("\n### Body at base\n\n");
            render_body(out, e.base_body.as_deref());
        }
        ProposalChange::Modified | ProposalChange::Renamed => {
            out.push_str("\n### Fork version\n\n");
            render_body(out, e.fork_body.as_deref());
        }
    }
}

fn render_delta(delta: Option<&VersionDelta>) -> String {
    let Some(d) = delta else {
        return "(a side does not parse)".to_string();
    };
    if d.is_empty() {
        return "none beyond mem qualifiers".to_string();
    }
    let mut parts: Vec<String> = Vec::new();
    if d.title_differs {
        parts.push("title".to_string());
    }
    if d.entity_type_differs {
        parts.push("type".to_string());
    }
    if !d.sections.is_empty() {
        parts.push(format!(
            "sections {}",
            d.sections
                .iter()
                .map(|s| format!("`{s}`"))
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    if !d.metadata.is_empty() {
        parts.push(format!(
            "metadata {}",
            d.metadata
                .iter()
                .map(|s| format!("`{s}`"))
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    if d.relationships_differ {
        parts.push("relationships".to_string());
    }
    parts.join("; ")
}

fn render_body(out: &mut String, body: Option<&str>) {
    match body {
        Some(b) => {
            out.push_str(BODY_FENCE);
            out.push_str("markdown\n");
            out.push_str(b);
            if !b.ends_with('\n') {
                out.push('\n');
            }
            out.push_str(BODY_FENCE);
            out.push('\n');
        }
        None => out.push_str("(absent)\n"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry(slug: &str, status: ProposalChange, conflict: Option<ConflictKind>) -> ProposalEntry {
        ProposalEntry {
            slug: slug.to_string(),
            fork_id: format!("f--{slug}"),
            target_id: format!("t--{slug}"),
            status,
            renamed_from: None,
            title: Some(slug.to_uppercase()),
            entity_type: Some("spec".to_string()),
            content_hash: Some("abc".to_string()),
            fork_delta: Some(VersionDelta {
                sections: vec!["identity".to_string()],
                ..Default::default()
            }),
            referrers: vec![Referrer {
                id: "t--alpha".to_string(),
                rel_type: "DEPENDS_ON".to_string(),
            }],
            anchors: vec![AnchorRow {
                artifact: "https://example.org/p".to_string(),
                grain: "url".to_string(),
                class: "anchored".to_string(),
                span: Some("the words".to_string()),
                last_state: None,
                last_observed_at: None,
            }],
            precheck: Precheck::clean("update"),
            conflict: conflict.map(|kind| Conflict {
                kind,
                target_delta: Some(VersionDelta {
                    sections: vec!["identity".to_string()],
                    ..Default::default()
                }),
                target_body: Some("# T\n".to_string()),
            }),
            re_proposal: Vec::new(),
            base_body: Some("# B\n".to_string()),
            fork_body: Some("# F\n".to_string()),
        }
    }

    fn brief() -> ProposalBrief {
        let entries = vec![
            entry("beta", ProposalChange::Modified, None),
            entry(
                "alpha",
                ProposalChange::Modified,
                Some(ConflictKind::TargetModified),
            ),
        ];
        let dispositions = entries
            .iter()
            .map(|e| {
                (
                    e.slug.clone(),
                    DispositionSlot::skeleton(e.conflict.is_some()),
                )
            })
            .collect();
        ProposalBrief {
            fork: "f".to_string(),
            target: "t".to_string(),
            proposal_id: proposal_id("f", "b"),
            ancestor: "a".to_string(),
            base: "b".to_string(),
            base_is_ancestor: false,
            fork_tip: "c".to_string(),
            target_tip: "d".to_string(),
            summary: ProposalSummary {
                modified: 2,
                conflicts: 1,
                ..Default::default()
            },
            entries,
            description: String::new(),
            dispositions,
        }
    }

    /// The skeleton carries the closed vocabulary, and a conflict slot
    /// withholds `adopt`; the wire keys are the ones the merge reads;
    /// the description slot is emitted empty beside the dispositions.
    #[test]
    fn skeleton_vocabulary_is_closed_and_a_conflict_withholds_adopt() {
        let b = brief();
        let json = serde_json::to_value(&b).unwrap();
        assert_eq!(
            json["dispositions"]["beta"],
            serde_json::json!({
                "disposition": "",
                "reason": "",
                "accepts": ["adopt", "adopt_with_changes", "reject"]
            })
        );
        assert_eq!(
            json["dispositions"]["alpha"]["accepts"],
            serde_json::json!(["adopt_with_changes", "reject"])
        );
        for key in [
            "fork",
            "target",
            "proposal_id",
            "ancestor",
            "base",
            "base_is_ancestor",
            "fork_tip",
            "target_tip",
            "summary",
            "entries",
            "description",
            "dispositions",
        ] {
            assert!(json.get(key).is_some(), "top-level key {key}");
        }
        assert_eq!(json["description"], "");
        // A file rendered before the slot existed still parses.
        let mut older = json.clone();
        older.as_object_mut().unwrap().remove("description");
        let older: ProposalBrief = serde_json::from_value(older).unwrap();
        assert_eq!(older, b);
        assert_eq!(json["entries"][0]["status"], "modified");
        assert_eq!(json["entries"][0]["precheck"]["outcome"], "clean");
        assert_eq!(json["entries"][1]["conflict"]["kind"], "target_modified");
        // The JSON round-trips through the same types the merge reads.
        let back: ProposalBrief = serde_json::from_value(json).unwrap();
        assert_eq!(back, b);
    }

    /// The markdown names the four shas, one block per entity, the
    /// differing sections, the referrers, the anchor row with its span
    /// and unobserved state, the precheck, the conflict with its three
    /// versions; and it renders the same bytes twice.
    #[test]
    fn markdown_is_deterministic_and_names_every_axis() {
        let b = brief();
        let md = render_proposal_brief(&b);
        assert_eq!(md, render_proposal_brief(&b));
        for needle in [
            "# Proposal brief: `f` against `t`",
            "- Ancestor on `t`: `a`",
            "- Base (the fork commit): `b`",
            "- Fork tip: `c`",
            "- Target tip: `d`",
            "## `alpha`: modified (ALPHA)",
            "## `beta`: modified (BETA)",
            "- Differences (fork against base): sections `identity`",
            "- Target referrers: `t--alpha` (DEPENDS_ON)",
            "  - `https://example.org/p` (url, anchored; span: \"the words\"; last state: unobserved)",
            "- Precheck (update in `t`): clean",
            "- CONFLICT: the target modified this entity since the ancestor (target_modified; target against base: sections `identity`)",
            "### Base version",
            "### Fork version",
            "### Target version",
            "````markdown\n# T\n````",
        ] {
            assert!(md.contains(needle), "missing {needle:?} in:\n{md}");
        }
        // No clock, no em dash.
        assert!(!md.contains('\u{2014}'));
    }

    /// The fallback line for a fork without a recorded base, and an
    /// empty brief.
    #[test]
    fn markdown_names_the_ancestor_fallback_and_the_empty_case() {
        let mut b = brief();
        b.base_is_ancestor = true;
        b.entries.clear();
        b.dispositions.clear();
        let md = render_proposal_brief(&b);
        assert!(md.contains("- Base: `b` (no fork commit recorded; the ancestor is the base)"));
        assert!(md.contains("The fork has no change against its base."));
    }

    /// The record parses with unknown keys tolerated, an absent record
    /// is the caller's empty default, and the rejection match names
    /// the hash before the id.
    #[test]
    fn record_parses_and_matches_rejections_by_hash_then_id() {
        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"}}}]}"#;
        let record = ProposalRecord::from_bytes(bytes).unwrap();
        assert_eq!(record.proposals.len(), 1);
        // An entry written before the description existed reads as
        // none, and writes back without the key.
        assert_eq!(record.proposals[0].description, None);
        let written: serde_json::Value = serde_json::from_slice(&record.to_bytes()).unwrap();
        assert!(written["proposals"][0].get("description").is_none());
        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"}}}]}"#;
        let described = ProposalRecord::from_bytes(described).unwrap();
        assert_eq!(
            described.proposals[0].description.as_deref(),
            Some("a staged exercise")
        );
        assert_eq!(
            described.proposals[0].entities["beta"].reason.as_deref(),
            Some("as proposed")
        );
        let md = render_proposal_record("t", &described);
        assert!(
            md.contains("## `f@b`\n\na staged exercise\n\n- Proposer:"),
            "{md}"
        );
        assert!(md.contains("- `beta`: adopt (as proposed)"), "{md}");
        // Same body under a new slug: matched by hash.
        let marks = record.rejections_matching("gamma", Some("h1"));
        assert_eq!(marks.len(), 1);
        assert_eq!(marks[0].matched_by, "content_hash");
        assert_eq!(marks[0].proposal, "f@b");
        assert_eq!(marks[0].reason.as_deref(), Some("weak"));
        // Same slug, different body: matched by id.
        let marks = record.rejections_matching("alpha", Some("h9"));
        assert_eq!(marks.len(), 1);
        assert_eq!(marks[0].matched_by, "id");
        // An adopted entity never marks.
        assert!(record.rejections_matching("beta", Some("h2")).is_empty());
        // Malformed bytes refuse rather than read as empty.
        assert!(ProposalRecord::from_bytes(b"not json").is_err());
        assert_eq!(ProposalRecord::default().proposals.len(), 0);
        assert_eq!(ProposalRecord::default().version, PROPOSAL_RECORD_VERSION);
    }
}