use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
pub const DISPOSITION_VOCABULARY: &[&str] = &["adopt", "adopt_with_changes", "reject"];
pub const DISPOSITION_ADOPT: &str = "adopt";
pub const DISPOSITION_ADOPT_WITH_CHANGES: &str = "adopt_with_changes";
pub const DISPOSITION_REJECT: &str = "reject";
pub const PROPOSAL_RECORD_PATH: &str = ".memstead/proposals.json";
pub const PROPOSAL_RECORD_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalBrief {
pub fork: String,
pub target: String,
pub proposal_id: String,
pub ancestor: String,
pub base: String,
pub base_is_ancestor: bool,
pub fork_tip: String,
pub target_tip: String,
pub summary: ProposalSummary,
pub entries: Vec<ProposalEntry>,
#[serde(default)]
pub description: String,
pub dispositions: BTreeMap<String, DispositionSlot>,
}
#[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,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProposalChange {
Added,
Modified,
Deleted,
Renamed,
}
impl ProposalChange {
pub fn as_wire(self) -> &'static str {
match self {
ProposalChange::Added => "added",
ProposalChange::Modified => "modified",
ProposalChange::Deleted => "deleted",
ProposalChange::Renamed => "renamed",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalEntry {
pub slug: String,
pub fork_id: String,
pub target_id: String,
pub status: ProposalChange,
#[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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_hash: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fork_delta: Option<VersionDelta>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub referrers: Vec<Referrer>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub anchors: Vec<AnchorRow>,
pub precheck: Precheck,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conflict: Option<Conflict>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub re_proposal: Vec<ReProposalMark>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base_body: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fork_body: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct VersionDelta {
pub title_differs: bool,
pub entity_type_differs: bool,
pub sections: Vec<String>,
pub metadata: Vec<String>,
pub relationships_differ: bool,
}
impl VersionDelta {
pub fn is_empty(&self) -> bool {
!self.title_differs
&& !self.entity_type_differs
&& self.sections.is_empty()
&& self.metadata.is_empty()
&& !self.relationships_differ
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Referrer {
pub id: String,
pub rel_type: String,
}
#[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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_state: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_observed_at: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Precheck {
pub outcome: PrecheckOutcome,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub failures: Vec<PrecheckFailure>,
#[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",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PrecheckFailure {
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Conflict {
pub kind: ConflictKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_delta: Option<VersionDelta>,
#[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 {
TargetModified,
TargetDeleted,
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"
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReProposalMark {
pub matched_by: String,
pub proposal: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DispositionSlot {
pub disposition: String,
pub reason: String,
pub accepts: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body: Option<serde_json::Value>,
}
impl DispositionSlot {
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,
}
}
}
#[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 {
fn default() -> Self {
Self {
version: PROPOSAL_RECORD_VERSION,
proposals: Vec::new(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ProposalRecordEntry {
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,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default)]
pub entities: BTreeMap<String, RecordedDisposition>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecordedDisposition {
pub disposition: String,
#[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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub landed_sections: Option<BTreeMap<String, String>>,
}
impl ProposalRecord {
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()),
Some(_) => {}
None if entry.disposition == DISPOSITION_REJECT => {}
None => effective = None,
}
}
effective
}
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
}
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
}
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 {
pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
serde_json::from_slice(bytes)
}
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
}
}
pub fn proposal_id(fork: &str, base: &str) -> String {
format!("{fork}@{base}")
}
impl ProposalRecord {
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()
}
}
#[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>>,
}
#[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>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalMergeOutcome {
pub fork: String,
pub target: String,
pub proposal_id: String,
pub merged_by: String,
pub target_tip_before: String,
pub target_tip_after: String,
pub merge_commits: Vec<MergeCommit>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub amend_commit: Option<MergeCommit>,
pub entities: Vec<MergedEntity>,
pub record_path: String,
pub validation: MergeValidation,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MergeCommit {
pub sha: String,
pub identity: String,
pub entities: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MergedEntity {
pub slug: String,
pub target_id: String,
pub disposition: String,
pub action: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub proposer: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_hash: Option<String>,
pub check_recorded: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MergeValidation {
pub entities: usize,
pub findings_before: usize,
pub findings_after: usize,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub new_findings: Vec<String>,
pub all_entities_parse: bool,
}
impl MergeValidation {
pub fn is_clean(&self) -> bool {
self.all_entities_parse && self.new_findings.is_empty()
}
}
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
}
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));
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
}
const BODY_FENCE: &str = "````";
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,
}
}
#[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"], "");
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");
let back: ProposalBrief = serde_json::from_value(json).unwrap();
assert_eq!(back, b);
}
#[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}");
}
assert!(!md.contains('\u{2014}'));
}
#[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."));
}
#[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);
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}");
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"));
let marks = record.rejections_matching("alpha", Some("h9"));
assert_eq!(marks.len(), 1);
assert_eq!(marks[0].matched_by, "id");
assert!(record.rejections_matching("beta", Some("h2")).is_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);
}
}