use std::collections::{BTreeMap, HashMap};
use std::path::Path;
use crate::backend::BackendError;
use crate::engine::{Engine, EngineError};
use crate::entity::{Entity, EntityId};
use crate::ops::proposal::{
AnchorRow, Conflict, ConflictKind, DispositionSlot, PROPOSAL_RECORD_PATH, Precheck,
PrecheckFailure, ProposalBrief, ProposalChange, ProposalEntry, ProposalRecord, ProposalSummary,
ReProposalMark, Referrer, VersionDelta, proposal_id,
};
use crate::ops::{DiffConfig, EntityDiff};
use crate::workspace::MountStorage;
const STAMPED_METADATA: &[&str] = &["type", "created_date", "last_modified"];
#[derive(Debug, Clone)]
enum SideChange {
Added {
after: Option<String>,
},
Modified {
before: Option<String>,
after: Option<String>,
},
Deleted {
before: Option<String>,
},
Renamed {
from: String,
before: Option<String>,
after: Option<String>,
},
Invalid {
error: String,
before: Option<String>,
after: Option<String>,
},
}
impl Engine {
pub fn proposal_brief(&mut self, fork: &str) -> Result<ProposalBrief, EngineError> {
let (gitdir, fork_branch) = match &self.find_mount(fork)?.mount.storage {
MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
_ => {
return Err(EngineError::InvalidInput(format!(
"mem '{fork}' is not git-backed: a proposal brief reads a fork's branch \
against its source's branch"
)));
}
};
let forked_from = self
.mem_config_for(fork)
.and_then(|c| c.forked_from.clone())
.ok_or_else(|| {
EngineError::InvalidInput(format!(
"mem '{fork}' records no forkedFrom: it is not a fork, so there is no \
ancestor to compare against (`memstead mem fork` records one)"
))
})?;
let target = forked_from.mem.clone();
let target_branch = match &self.find_mount(&target)?.mount.storage {
MountStorage::GitBranch {
gitdir: target_gitdir,
branch,
} => {
if target_gitdir
.canonicalize()
.unwrap_or(target_gitdir.clone())
!= gitdir.canonicalize().unwrap_or(gitdir.clone())
{
return Err(EngineError::InvalidInput(format!(
"the source '{target}' of fork '{fork}' lives in another mem-repo \
({}): a brief compares two branches of one mem-repo",
target_gitdir.display()
)));
}
branch.clone()
}
_ => {
return Err(EngineError::InvalidInput(format!(
"the source '{target}' of fork '{fork}' is not git-backed: a proposal \
brief reads the source's branch"
)));
}
};
let Some(ops) = self.git_branch_ops() else {
return Err(EngineError::Backend(BackendError::Other(
"git-branch ops not installed (git-branch ops not wired)".to_string(),
)));
};
self.reload_if_stale(Some(fork));
self.reload_if_stale(Some(&target));
self.ensure_mems_loaded(None);
let fork_ref = crate::branch_full_ref(&fork_branch);
let target_ref = crate::branch_full_ref(&target_branch);
let fork_tip = resolve_sha(&ops, &gitdir, &fork_ref)?;
let target_tip = resolve_sha(&ops, &gitdir, &target_ref)?;
let ancestor = forked_from.sha.clone();
let base = forked_from.base_sha().to_string();
let base_is_ancestor = forked_from.base.is_none();
resolve_sha(&ops, &gitdir, &base)?;
resolve_sha(&ops, &gitdir, &ancestor)?;
let config = DiffConfig {
rename_similarity: crate::ops::RENAME_SIMILARITY_MAX,
include_content: true,
include_ripple: false,
};
let both = [fork_branch.clone(), target_branch.clone()];
let fork_diff = run_diff(
&ops,
&gitdir,
&fork_branch,
&both,
fork,
&base,
&fork_tip,
&config,
)?;
let target_diff = run_diff(
&ops,
&gitdir,
&target_branch,
&both,
&target,
&ancestor,
&target_tip,
&config,
)?;
let fork_changes = side_changes(&fork_diff.entries);
let target_changes = side_changes(&target_diff.entries);
let record = self.read_proposal_record(&target)?;
let proposal = proposal_id(fork, &base);
let mut entries: Vec<ProposalEntry> = Vec::with_capacity(fork_changes.len());
for (slug, change) in &fork_changes {
if let SideChange::Modified {
before: Some(before),
after: Some(after),
} = change
&& normalise_to(before, &target, fork) == normalise_to(after, &target, fork)
{
continue;
}
let entry = self.build_entry(
fork,
&target,
slug,
change,
&target_changes,
record.as_ref(),
)?;
entries.push(entry);
}
entries.sort_by(|a, b| a.slug.cmp(&b.slug));
let mut summary = ProposalSummary::default();
let mut dispositions = BTreeMap::new();
for e in &entries {
match e.status {
ProposalChange::Added => summary.added += 1,
ProposalChange::Modified => summary.modified += 1,
ProposalChange::Deleted => summary.deleted += 1,
ProposalChange::Renamed => summary.renamed += 1,
}
if e.conflict.is_some() {
summary.conflicts += 1;
}
if e.precheck.outcome == crate::ops::proposal::PrecheckOutcome::Failed {
summary.precheck_failures += 1;
}
if !e.re_proposal.is_empty() {
summary.re_proposals += 1;
}
dispositions.insert(
e.slug.clone(),
DispositionSlot::skeleton(e.conflict.is_some()),
);
}
Ok(ProposalBrief {
fork: fork.to_string(),
target,
proposal_id: proposal,
ancestor,
base,
base_is_ancestor,
fork_tip,
target_tip,
summary,
entries,
description: String::new(),
dispositions,
})
}
pub(crate) fn read_proposal_record(
&self,
target: &str,
) -> Result<Option<ProposalRecord>, EngineError> {
let mount = self.find_mount(target)?;
let bytes = mount
.backend
.read_proposal_record()
.map_err(EngineError::Backend)?;
match bytes {
None => Ok(None),
Some(bytes) => ProposalRecord::from_bytes(&bytes).map(Some).map_err(|e| {
EngineError::Mem(format!(
"the proposal record of '{target}' ({PROPOSAL_RECORD_PATH}) does not parse: {e}"
))
}),
}
}
fn build_entry(
&mut self,
fork: &str,
target: &str,
slug: &str,
change: &SideChange,
target_changes: &BTreeMap<String, SideChange>,
record: Option<&ProposalRecord>,
) -> Result<ProposalEntry, EngineError> {
let fork_schema = self.schema_for(fork);
let target_schema = self.schema_for(target);
let normalise = |body: &Option<String>| -> Option<String> {
body.as_deref().map(|b| normalise_to(b, target, fork))
};
let rel_path = crate::entity::id::id_to_file_path(&EntityId::new(fork, slug));
let (status, renamed_from, base_body, fork_body, parse_failure) = match change {
SideChange::Added { after } => {
(ProposalChange::Added, None, None, normalise(after), None)
}
SideChange::Modified { before, after } => (
ProposalChange::Modified,
None,
normalise(before),
normalise(after),
None,
),
SideChange::Deleted { before } => {
(ProposalChange::Deleted, None, normalise(before), None, None)
}
SideChange::Renamed {
from,
before,
after,
} => (
ProposalChange::Renamed,
Some(from.clone()),
normalise(before),
normalise(after),
None,
),
SideChange::Invalid {
error,
before,
after,
} => {
let status = match (before, after) {
(None, _) => ProposalChange::Added,
(_, None) => ProposalChange::Deleted,
_ => ProposalChange::Modified,
};
(
status,
None,
normalise(before),
normalise(after),
Some(error.clone()),
)
}
};
let base_entity = base_body
.as_deref()
.and_then(|b| parse_body(b, &rel_path, fork, fork_schema.as_deref()));
let fork_entity = fork_body
.as_deref()
.and_then(|b| parse_body(b, &rel_path, fork, fork_schema.as_deref()));
let (title, entity_type) = match (&fork_entity, &base_entity) {
(Some(e), _) | (None, Some(e)) => (Some(e.title.clone()), Some(e.entity_type.clone())),
(None, None) => fork_body
.as_deref()
.or(base_body.as_deref())
.map(crate::entity::parser::peek_title_and_type)
.unwrap_or((None, None)),
};
let fork_delta = match (&base_entity, &fork_entity) {
(Some(b), Some(f)) => Some(version_delta(b, f)),
_ => None,
};
let landing_body = fork_body.as_deref().map(|b| normalise_to(b, fork, target));
let landing_entity = landing_body.as_deref().and_then(|b| {
parse_body(
b,
&crate::entity::id::id_to_file_path(&EntityId::new(target, slug)),
target,
target_schema.as_deref(),
)
});
let content_hash = landing_body.as_deref().map(proposal_content_hash);
let conflict = conflict_for(status, slug, renamed_from.as_deref(), target_changes).map(
|(kind, target_body)| {
let target_body = target_body.map(|b| normalise_to(&b, target, fork));
let target_entity = target_body
.as_deref()
.and_then(|b| parse_body(b, &rel_path, fork, fork_schema.as_deref()));
let target_delta = match (&base_entity, &target_entity) {
(Some(b), Some(t)) => Some(version_delta(b, t)),
_ => None,
};
Conflict {
kind,
target_delta,
target_body,
}
},
);
let held_slug = renamed_from.as_deref().unwrap_or(slug);
let held_id = EntityId::new(target, held_slug);
let mut referrers: Vec<Referrer> = self
.store
.incoming(&held_id)
.iter()
.filter(|e| e.from.mem() != fork)
.map(|e| Referrer {
id: e.from.to_string(),
rel_type: e.rel_type.clone(),
})
.collect();
referrers.sort_by(|a, b| (&a.id, &a.rel_type).cmp(&(&b.id, &b.rel_type)));
referrers.dedup();
let anchors: Vec<AnchorRow> = self
.entity_anchors_for_write(&EntityId::new(fork, slug))?
.into_iter()
.map(|a| AnchorRow {
artifact: a.artifact.clone(),
grain: a.grain.as_wire().to_string(),
class: a.class.as_wire().to_string(),
span: a.span.clone(),
last_state: a
.last_observed
.as_ref()
.map(|o| o.state.as_wire().to_string()),
last_observed_at: a.last_observed.as_ref().map(|o| o.at.clone()),
})
.collect();
let precheck = match parse_failure {
Some(error) => Precheck::failed(
"parse",
vec![PrecheckFailure {
code: "PARSE_ERROR".to_string(),
message: error,
}],
),
None => self.precheck(target, slug, status, &conflict, landing_entity.as_ref())?,
};
let re_proposal: Vec<ReProposalMark> = record
.map(|r| r.rejections_matching(slug, content_hash.as_deref()))
.unwrap_or_default();
Ok(ProposalEntry {
slug: slug.to_string(),
fork_id: EntityId::new(fork, slug).to_string(),
target_id: EntityId::new(target, slug).to_string(),
status,
renamed_from,
title,
entity_type,
content_hash,
fork_delta,
referrers,
anchors,
precheck,
conflict,
re_proposal,
base_body,
fork_body,
})
}
fn precheck(
&mut self,
target: &str,
slug: &str,
status: ProposalChange,
conflict: &Option<Conflict>,
landing: Option<&Entity>,
) -> Result<Precheck, EngineError> {
let Some(landing) = landing else {
return Ok(match status {
ProposalChange::Deleted => Precheck::not_run(
"a deletion is judged against the target's referrers, listed above",
),
_ => Precheck::not_run("the fork's body does not parse under the target's schema"),
});
};
if status == ProposalChange::Deleted {
return Ok(Precheck::not_run(
"a deletion is judged against the target's referrers, listed above",
));
}
let target_id = EntityId::new(target, slug);
let target_has = self.target_holds(&target_id);
if let Some(c) = conflict {
match c.kind {
ConflictKind::TargetDeleted => {
return Ok(Precheck::not_run(
"the target no longer holds this entity; the owner resolves the conflict first",
));
}
ConflictKind::TargetAdded => {
return Ok(Precheck::not_run(
"the target holds its own entity under this slug; the owner resolves the conflict first",
));
}
ConflictKind::TargetModified => {}
}
}
let snapshot = self.store.clone();
let existing = self.store.get(&target_id).filter(|e| !e.stub).cloned();
let outcome: Result<(), EngineError> =
match self.landing_write_args(target, slug, landing, existing.as_ref()) {
LandingWrite::Update(args) => self
.update_entity(
crate::UpdateEntityArgs {
dry_run: true,
relations_unset: Vec::new(),
..*args
},
crate::vcs::Actor::Cli,
None,
None,
)
.map(|_| ()),
LandingWrite::Create(args) => self
.create_entity(
crate::CreateEntityArgs {
dry_run: true,
..*args
},
crate::vcs::Actor::Cli,
None,
None,
)
.map(|_| ()),
};
self.store = snapshot;
let operation = if target_has { "update" } else { "create" };
Ok(match outcome {
Ok(()) => Precheck::clean(operation),
Err(
e @ (EngineError::Backend(_)
| EngineError::StaleView { .. }
| EngineError::CommitNotApplied { .. }),
) => return Err(e),
Err(e) => Precheck::failed(
operation,
vec![PrecheckFailure {
code: e.code().to_string(),
message: e.prose_render(),
}],
),
})
}
}
pub(crate) enum LandingWrite {
Create(Box<crate::CreateEntityArgs>),
Update(Box<crate::UpdateEntityArgs>),
}
impl Engine {
pub(crate) fn target_holds(&self, id: &EntityId) -> bool {
self.store.get(id).is_some_and(|e| !e.stub)
}
pub(crate) fn landing_write_args(
&self,
target: &str,
slug: &str,
landing: &Entity,
existing: Option<&Entity>,
) -> LandingWrite {
let target_id = EntityId::new(target, slug);
let sections: indexmap::IndexMap<String, String> = landing
.sections
.iter()
.filter(|(k, _)| k.as_str() != "relationships")
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let metadata: indexmap::IndexMap<String, String> = landing
.metadata
.iter()
.filter(|(k, _)| !STAMPED_METADATA.contains(&k.as_str()))
.map(|(k, v)| (k.clone(), v.to_frontmatter_string()))
.collect();
let synthesised: Option<String> = self
.schemas
.get(target)
.and_then(|s| s.alias_target_rel_type().map(str::to_string));
let relations: Vec<crate::ops::RelateArg> = landing
.relationships
.iter()
.filter(|r| synthesised.as_deref() != Some(r.rel_type.as_str()))
.map(|r| crate::ops::RelateArg {
target: r.target.clone(),
rel_type: r.rel_type.clone(),
description: r.description.clone(),
})
.collect();
match existing {
Some(existing) => {
let sections_unset: Vec<String> = existing
.sections
.keys()
.filter(|k| k.as_str() != "relationships" && !sections.contains_key(*k))
.cloned()
.collect();
let metadata_unset: Vec<String> = existing
.metadata
.keys()
.filter(|k| {
!STAMPED_METADATA.contains(&k.as_str()) && !metadata.contains_key(*k)
})
.cloned()
.collect();
let declare_relations: Vec<crate::ops::RelateArg> = relations
.iter()
.filter(|r| {
!existing
.relationships
.iter()
.any(|x| x.rel_type == r.rel_type && x.target == r.target)
})
.cloned()
.collect();
let relations_unset: Vec<crate::ops::RelationUnsetArg> = existing
.relationships
.iter()
.filter(|x| {
!landing
.relationships
.iter()
.any(|r| r.rel_type == x.rel_type && r.target == x.target)
})
.map(|x| crate::ops::RelationUnsetArg {
target: x.target.clone(),
rel_type: x.rel_type.clone(),
})
.collect();
LandingWrite::Update(Box::new(crate::UpdateEntityArgs {
id: target_id,
expected_hash: crate::ExpectedHash::Override(
crate::HashOverride::ProposalMerge,
),
sections,
append_sections: Default::default(),
patch_sections: Default::default(),
sections_unset,
metadata,
metadata_unset,
dry_run: false,
declare_relations,
anchors: Vec::new(),
anchors_unset: Vec::new(),
relations_unset,
}))
}
None => LandingWrite::Create(Box::new(crate::CreateEntityArgs {
mem: target.to_string(),
title: landing.title.clone(),
entity_type: landing.entity_type.clone(),
sections,
metadata,
relations,
anchors: Vec::new(),
dry_run: false,
})),
}
}
}
pub(crate) fn resolve_sha(
ops: &crate::engine::GitBranchOps,
gitdir: &Path,
ref_name: &str,
) -> Result<String, EngineError> {
match (ops.resolve_ref)(gitdir, ref_name) {
Ok(Some(sha)) => Ok(sha),
Ok(None) => Err(EngineError::UnknownRef(ref_name.to_string())),
Err(e) => Err(EngineError::Backend(e)),
}
}
#[allow(clippy::too_many_arguments)]
fn run_diff(
ops: &crate::engine::GitBranchOps,
gitdir: &Path,
branch: &str,
readable: &[String],
mem: &str,
ref_a: &str,
ref_b: &str,
config: &DiffConfig,
) -> Result<crate::ops::Diff, EngineError> {
(ops.diff)(gitdir, branch, readable, mem, ref_a, ref_b, config).map_err(|e| match e {
BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
EngineError::UnknownRef(msg.trim_start_matches("UNKNOWN_REF:").trim().to_string())
}
other => EngineError::Backend(other),
})
}
fn side_changes(entries: &[EntityDiff]) -> BTreeMap<String, SideChange> {
let mut out = BTreeMap::new();
for entry in entries {
match entry {
EntityDiff::Added {
id, content_after, ..
} => {
out.insert(
id.path().to_string(),
SideChange::Added {
after: content_after.clone(),
},
);
}
EntityDiff::Modified {
id,
content_before,
content_after,
..
} => {
out.insert(
id.path().to_string(),
SideChange::Modified {
before: content_before.clone(),
after: content_after.clone(),
},
);
}
EntityDiff::Deleted {
id, content_before, ..
} => {
out.insert(
id.path().to_string(),
SideChange::Deleted {
before: content_before.clone(),
},
);
}
EntityDiff::Renamed {
from_id,
to_id,
content_before,
content_after,
..
} => {
out.insert(
to_id.path().to_string(),
SideChange::Renamed {
from: from_id.path().to_string(),
before: content_before.clone(),
after: content_after.clone(),
},
);
}
EntityDiff::InvalidEntity {
id,
error,
content_before,
content_after,
..
} => {
out.insert(
id.path().to_string(),
SideChange::Invalid {
error: error.clone(),
before: content_before.clone(),
after: content_after.clone(),
},
);
}
}
}
out
}
pub(crate) fn proposal_content_hash(landing_body: &str) -> String {
let mut out = String::with_capacity(landing_body.len());
let mut in_frontmatter = false;
for (i, line) in landing_body.split_inclusive('\n').enumerate() {
let trimmed = line.trim_end_matches(['\n', '\r']);
if i == 0 && trimmed == "---" {
in_frontmatter = true;
out.push_str(line);
continue;
}
if in_frontmatter {
if trimmed == "---" {
in_frontmatter = false;
} else if STAMPED_METADATA
.iter()
.filter(|k| **k != "type")
.any(|k| trimmed.starts_with(&format!("{k}:")))
{
continue;
}
}
out.push_str(line);
}
crate::entity::parser::compute_hash(&out)
}
pub(crate) fn normalise_to(body: &str, from: &str, to: &str) -> String {
let bytes = crate::ops::export::retarget_mem_links(body.as_bytes().to_vec(), from, to);
String::from_utf8(bytes).unwrap_or_else(|_| body.to_string())
}
pub(crate) fn parse_body(
body: &str,
rel_path: &str,
mem: &str,
schema: Option<&memstead_schema::Schema>,
) -> Option<Entity> {
let schema = schema?;
let (_, entity_type) = crate::entity::parser::peek_title_and_type(body);
let type_def = schema.get_type(&entity_type?)?;
crate::entity::parser::parse_markdown(body, rel_path, type_def.as_ref(), mem)
.ok()
.map(|r| r.entity)
}
fn version_delta(base: &Entity, side: &Entity) -> VersionDelta {
let mut sections: Vec<String> = Vec::new();
for (key, value) in &side.sections {
if key == "relationships" {
continue;
}
if base.sections.get(key) != Some(value) {
sections.push(key.clone());
}
}
for key in base.sections.keys() {
if key != "relationships" && !side.sections.contains_key(key) {
sections.push(key.clone());
}
}
let mut metadata: Vec<String> = Vec::new();
for (key, value) in &side.metadata {
if STAMPED_METADATA.contains(&key.as_str()) {
continue;
}
if base.metadata.get(key) != Some(value) {
metadata.push(key.clone());
}
}
for key in base.metadata.keys() {
if !STAMPED_METADATA.contains(&key.as_str()) && !side.metadata.contains_key(key) {
metadata.push(key.clone());
}
}
let rels = |e: &Entity| -> Vec<(String, String, Option<String>)> {
let mut v: Vec<_> = e
.relationships
.iter()
.map(|r| {
(
r.rel_type.clone(),
r.target.to_string(),
r.description.clone(),
)
})
.collect();
v.sort();
v
};
VersionDelta {
title_differs: base.title != side.title,
entity_type_differs: base.entity_type != side.entity_type,
sections,
metadata,
relationships_differ: rels(base) != rels(side),
}
}
fn conflict_for(
status: ProposalChange,
slug: &str,
renamed_from: Option<&str>,
target_changes: &BTreeMap<String, SideChange>,
) -> Option<(ConflictKind, Option<String>)> {
let mut created: HashMap<&str, Option<String>> = HashMap::new();
let mut modified: HashMap<&str, Option<String>> = HashMap::new();
let mut deleted: Vec<&str> = Vec::new();
for (target_slug, change) in target_changes {
match change {
SideChange::Added { after } => {
created.insert(target_slug.as_str(), after.clone());
}
SideChange::Modified { after, .. } => {
modified.insert(target_slug.as_str(), after.clone());
}
SideChange::Deleted { .. } => deleted.push(target_slug.as_str()),
SideChange::Renamed { from, after, .. } => {
deleted.push(from.as_str());
created.insert(target_slug.as_str(), after.clone());
}
SideChange::Invalid { before, after, .. } => match (before, after) {
(None, _) => {
created.insert(target_slug.as_str(), after.clone());
}
(_, None) => deleted.push(target_slug.as_str()),
_ => {
modified.insert(target_slug.as_str(), after.clone());
}
},
}
}
match status {
ProposalChange::Added => created
.get(slug)
.map(|body| (ConflictKind::TargetAdded, body.clone())),
ProposalChange::Modified | ProposalChange::Deleted => {
if let Some(body) = modified.get(slug) {
Some((ConflictKind::TargetModified, body.clone()))
} else if deleted.contains(&slug) {
Some((ConflictKind::TargetDeleted, None))
} else {
None
}
}
ProposalChange::Renamed => {
let from = renamed_from.unwrap_or(slug);
if let Some(body) = created.get(slug) {
Some((ConflictKind::TargetAdded, body.clone()))
} else if let Some(body) = modified.get(from) {
Some((ConflictKind::TargetModified, body.clone()))
} else if deleted.contains(&from) {
Some((ConflictKind::TargetDeleted, None))
} else {
None
}
}
}
}