Skip to main content

memstead_base/engine/
proposal.rs

1//! `Engine::proposal_brief`: the three-way review of a fork against
2//! its source mem. Types and the markdown renderer live in
3//! [`crate::ops::proposal`]; this module reads.
4//!
5//! The picture is built from two two-tree walks of the mem-repo (the
6//! git-branch diff hook, the same walk `memstead_diff` uses): the
7//! fork's base to the fork's tip says what the fork did, the ancestor
8//! to the target's tip says what the target did meanwhile. Entities
9//! match by slug across the two mems. Bodies compare with mem-qualified
10//! self-links normalised to the fork's name on every side, so a link
11//! the fork commit retargeted is never a difference. The mechanics
12//! precheck rehearses the create or update the merge would run in the
13//! target, through the write gate's own dry run, over a store snapshot
14//! that is restored afterwards. Anchor rows come from the fork's
15//! sidecar under the fork's ids, as stored; nothing is observed.
16//! Re-proposal marks come from the target's proposal record when the
17//! target branch carries one.
18//!
19//! Nothing here writes: not the fork, not the target, not the
20//! workspace state.
21
22use std::collections::{BTreeMap, HashMap};
23use std::path::Path;
24
25use crate::backend::BackendError;
26use crate::engine::{Engine, EngineError};
27use crate::entity::{Entity, EntityId};
28use crate::ops::proposal::{
29    AnchorRow, Conflict, ConflictKind, DispositionSlot, PROPOSAL_RECORD_PATH, Precheck,
30    PrecheckFailure, ProposalBrief, ProposalChange, ProposalEntry, ProposalRecord, ProposalSummary,
31    ReProposalMark, Referrer, VersionDelta, proposal_id,
32};
33use crate::ops::{DiffConfig, EntityDiff};
34use crate::workspace::MountStorage;
35
36/// Metadata keys the engine stamps; never a difference between two
37/// versions, never part of a rehearsed write.
38const STAMPED_METADATA: &[&str] = &["type", "created_date", "last_modified"];
39
40/// What one side (the fork, or the target) did to one slug, read off a
41/// two-tree diff.
42#[derive(Debug, Clone)]
43enum SideChange {
44    Added {
45        after: Option<String>,
46    },
47    Modified {
48        before: Option<String>,
49        after: Option<String>,
50    },
51    Deleted {
52        before: Option<String>,
53    },
54    /// Keyed by the new slug; `from` is the old one.
55    Renamed {
56        from: String,
57        before: Option<String>,
58        after: Option<String>,
59    },
60    /// A side that does not parse; the surviving bytes ride along.
61    Invalid {
62        error: String,
63        before: Option<String>,
64        after: Option<String>,
65    },
66}
67
68impl Engine {
69    /// The review brief of `fork` against the mem it was forked from.
70    ///
71    /// Refusals: `UNKNOWN_MEM` (the fork is not mounted, or its source
72    /// is not), `INVALID_INPUT` (the mem records no `forkedFrom`; the
73    /// fork or its source is not a git-branch mem of this mem-repo),
74    /// `UNKNOWN_REF` (a recorded sha the mem-repo no longer resolves).
75    /// The brief writes nothing.
76    pub fn proposal_brief(&mut self, fork: &str) -> Result<ProposalBrief, EngineError> {
77        let (gitdir, fork_branch) = match &self.find_mount(fork)?.mount.storage {
78            MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
79            _ => {
80                return Err(EngineError::InvalidInput(format!(
81                    "mem '{fork}' is not git-backed: a proposal brief reads a fork's branch \
82                     against its source's branch"
83                )));
84            }
85        };
86        let forked_from = self
87            .mem_config_for(fork)
88            .and_then(|c| c.forked_from.clone())
89            .ok_or_else(|| {
90                EngineError::InvalidInput(format!(
91                    "mem '{fork}' records no forkedFrom: it is not a fork, so there is no \
92                     ancestor to compare against (`memstead mem fork` records one)"
93                ))
94            })?;
95        let target = forked_from.mem.clone();
96        let target_branch = match &self.find_mount(&target)?.mount.storage {
97            MountStorage::GitBranch {
98                gitdir: target_gitdir,
99                branch,
100            } => {
101                if target_gitdir
102                    .canonicalize()
103                    .unwrap_or(target_gitdir.clone())
104                    != gitdir.canonicalize().unwrap_or(gitdir.clone())
105                {
106                    return Err(EngineError::InvalidInput(format!(
107                        "the source '{target}' of fork '{fork}' lives in another mem-repo \
108                         ({}): a brief compares two branches of one mem-repo",
109                        target_gitdir.display()
110                    )));
111                }
112                branch.clone()
113            }
114            _ => {
115                return Err(EngineError::InvalidInput(format!(
116                    "the source '{target}' of fork '{fork}' is not git-backed: a proposal \
117                     brief reads the source's branch"
118                )));
119            }
120        };
121        let Some(ops) = self.git_branch_ops() else {
122            return Err(EngineError::Backend(BackendError::Other(
123                "git-branch ops not installed (git-branch ops not wired)".to_string(),
124            )));
125        };
126
127        // Fresh state on both sides, and the whole store loaded: the
128        // target's referrers can sit in any mem.
129        self.reload_if_stale(Some(fork));
130        self.reload_if_stale(Some(&target));
131        self.ensure_mems_loaded(None);
132
133        let fork_ref = crate::branch_full_ref(&fork_branch);
134        let target_ref = crate::branch_full_ref(&target_branch);
135        let fork_tip = resolve_sha(&ops, &gitdir, &fork_ref)?;
136        let target_tip = resolve_sha(&ops, &gitdir, &target_ref)?;
137        let ancestor = forked_from.sha.clone();
138        let base = forked_from.base_sha().to_string();
139        let base_is_ancestor = forked_from.base.is_none();
140        resolve_sha(&ops, &gitdir, &base)?;
141        resolve_sha(&ops, &gitdir, &ancestor)?;
142
143        // A rename in the brief is a recorded act (the engine's rename
144        // note on the fork's branch, which the walk pairs exactly) or a
145        // byte-identical move; content similarity never guesses one, so
146        // a deletion beside an unrelated addition reads as both.
147        let config = DiffConfig {
148            rename_similarity: crate::ops::RENAME_SIMILARITY_MAX,
149            include_content: true,
150            include_ripple: false,
151        };
152        let fork_diff = run_diff(&ops, &gitdir, &fork_branch, fork, &base, &fork_tip, &config)?;
153        let target_diff = run_diff(
154            &ops,
155            &gitdir,
156            &target_branch,
157            &target,
158            &ancestor,
159            &target_tip,
160            &config,
161        )?;
162        let fork_changes = side_changes(&fork_diff.entries);
163        let target_changes = side_changes(&target_diff.entries);
164
165        let record = self.read_proposal_record(&target)?;
166        let proposal = proposal_id(fork, &base);
167
168        let mut entries: Vec<ProposalEntry> = Vec::with_capacity(fork_changes.len());
169        for (slug, change) in &fork_changes {
170            // A modification that is only the fork commit's retargeting
171            // (a fork read against its ancestor) is no change at all:
172            // the bodies agree once their mem qualifiers are normalised.
173            if let SideChange::Modified {
174                before: Some(before),
175                after: Some(after),
176            } = change
177                && normalise_to(before, &target, fork) == normalise_to(after, &target, fork)
178            {
179                continue;
180            }
181            let entry = self.build_entry(
182                fork,
183                &target,
184                slug,
185                change,
186                &target_changes,
187                record.as_ref(),
188            );
189            entries.push(entry);
190        }
191        entries.sort_by(|a, b| a.slug.cmp(&b.slug));
192
193        let mut summary = ProposalSummary::default();
194        let mut dispositions = BTreeMap::new();
195        for e in &entries {
196            match e.status {
197                ProposalChange::Added => summary.added += 1,
198                ProposalChange::Modified => summary.modified += 1,
199                ProposalChange::Deleted => summary.deleted += 1,
200                ProposalChange::Renamed => summary.renamed += 1,
201            }
202            if e.conflict.is_some() {
203                summary.conflicts += 1;
204            }
205            if e.precheck.outcome == crate::ops::proposal::PrecheckOutcome::Failed {
206                summary.precheck_failures += 1;
207            }
208            if !e.re_proposal.is_empty() {
209                summary.re_proposals += 1;
210            }
211            dispositions.insert(
212                e.slug.clone(),
213                DispositionSlot::skeleton(e.conflict.is_some()),
214            );
215        }
216
217        Ok(ProposalBrief {
218            fork: fork.to_string(),
219            target,
220            proposal_id: proposal,
221            ancestor,
222            base,
223            base_is_ancestor,
224            fork_tip,
225            target_tip,
226            summary,
227            entries,
228            description: String::new(),
229            dispositions,
230        })
231    }
232
233    /// The target's proposal record, `None` when the mem carries none
234    /// (a git-branch mem without the sidecar, an archive sealed without
235    /// the member); a record that does not parse refuses, named.
236    pub(crate) fn read_proposal_record(
237        &self,
238        target: &str,
239    ) -> Result<Option<ProposalRecord>, EngineError> {
240        let mount = self.find_mount(target)?;
241        let bytes = mount
242            .backend
243            .read_proposal_record()
244            .map_err(EngineError::Backend)?;
245        match bytes {
246            None => Ok(None),
247            Some(bytes) => ProposalRecord::from_bytes(&bytes).map(Some).map_err(|e| {
248                EngineError::Mem(format!(
249                    "the proposal record of '{target}' ({PROPOSAL_RECORD_PATH}) does not parse: {e}"
250                ))
251            }),
252        }
253    }
254
255    /// One entry: the fork's change, the conflict against the target's
256    /// change on the same slug, the target's referrers, the fork's
257    /// anchor rows, the precheck and the re-proposal marks.
258    fn build_entry(
259        &mut self,
260        fork: &str,
261        target: &str,
262        slug: &str,
263        change: &SideChange,
264        target_changes: &BTreeMap<String, SideChange>,
265        record: Option<&ProposalRecord>,
266    ) -> ProposalEntry {
267        let fork_schema = self.schema_for(fork);
268        let target_schema = self.schema_for(target);
269        let normalise = |body: &Option<String>| -> Option<String> {
270            body.as_deref().map(|b| normalise_to(b, target, fork))
271        };
272        let rel_path = crate::entity::id::id_to_file_path(&EntityId::new(fork, slug));
273
274        let (status, renamed_from, base_body, fork_body, parse_failure) = match change {
275            SideChange::Added { after } => {
276                (ProposalChange::Added, None, None, normalise(after), None)
277            }
278            SideChange::Modified { before, after } => (
279                ProposalChange::Modified,
280                None,
281                normalise(before),
282                normalise(after),
283                None,
284            ),
285            SideChange::Deleted { before } => {
286                (ProposalChange::Deleted, None, normalise(before), None, None)
287            }
288            SideChange::Renamed {
289                from,
290                before,
291                after,
292            } => (
293                ProposalChange::Renamed,
294                Some(from.clone()),
295                normalise(before),
296                normalise(after),
297                None,
298            ),
299            SideChange::Invalid {
300                error,
301                before,
302                after,
303            } => {
304                let status = match (before, after) {
305                    (None, _) => ProposalChange::Added,
306                    (_, None) => ProposalChange::Deleted,
307                    _ => ProposalChange::Modified,
308                };
309                (
310                    status,
311                    None,
312                    normalise(before),
313                    normalise(after),
314                    Some(error.clone()),
315                )
316            }
317        };
318
319        let base_entity = base_body
320            .as_deref()
321            .and_then(|b| parse_body(b, &rel_path, fork, fork_schema.as_deref()));
322        let fork_entity = fork_body
323            .as_deref()
324            .and_then(|b| parse_body(b, &rel_path, fork, fork_schema.as_deref()));
325        let (title, entity_type) = match (&fork_entity, &base_entity) {
326            (Some(e), _) | (None, Some(e)) => (Some(e.title.clone()), Some(e.entity_type.clone())),
327            (None, None) => fork_body
328                .as_deref()
329                .or(base_body.as_deref())
330                .map(crate::entity::parser::peek_title_and_type)
331                .unwrap_or((None, None)),
332        };
333        let fork_delta = match (&base_entity, &fork_entity) {
334            (Some(b), Some(f)) => Some(version_delta(b, f)),
335            _ => None,
336        };
337
338        // The proposed version as it would land in the target: the
339        // fork's body with its self-links under the target's name.
340        let landing_body = fork_body.as_deref().map(|b| normalise_to(b, fork, target));
341        let landing_entity = landing_body.as_deref().and_then(|b| {
342            parse_body(
343                b,
344                &crate::entity::id::id_to_file_path(&EntityId::new(target, slug)),
345                target,
346                target_schema.as_deref(),
347            )
348        });
349        let content_hash = landing_body.as_deref().map(proposal_content_hash);
350
351        // The conflict: the target moved the same slug (or, for a
352        // rename, the slug the entity had) since the ancestor.
353        let conflict = conflict_for(status, slug, renamed_from.as_deref(), target_changes).map(
354            |(kind, target_body)| {
355                let target_body = target_body.map(|b| normalise_to(&b, target, fork));
356                let target_entity = target_body
357                    .as_deref()
358                    .and_then(|b| parse_body(b, &rel_path, fork, fork_schema.as_deref()));
359                let target_delta = match (&base_entity, &target_entity) {
360                    (Some(b), Some(t)) => Some(version_delta(b, t)),
361                    _ => None,
362                };
363                Conflict {
364                    kind,
365                    target_delta,
366                    target_body,
367                }
368            },
369        );
370
371        // The target's referrers of the entity the target holds: the
372        // slug itself, or for a rename the slug it still has.
373        let held_slug = renamed_from.as_deref().unwrap_or(slug);
374        let held_id = EntityId::new(target, held_slug);
375        let mut referrers: Vec<Referrer> = self
376            .store
377            .incoming(&held_id)
378            .iter()
379            .filter(|e| e.from.mem() != fork)
380            .map(|e| Referrer {
381                id: e.from.to_string(),
382                rel_type: e.rel_type.clone(),
383            })
384            .collect();
385        referrers.sort_by(|a, b| (&a.id, &a.rel_type).cmp(&(&b.id, &b.rel_type)));
386        referrers.dedup();
387
388        // The fork's anchor rows, as stored, under the fork's ids.
389        let anchors: Vec<AnchorRow> = self
390            .entity_anchors(&EntityId::new(fork, slug))
391            .into_iter()
392            .map(|a| AnchorRow {
393                artifact: a.artifact.clone(),
394                grain: a.grain.as_wire().to_string(),
395                class: a.class.as_wire().to_string(),
396                span: a.span.clone(),
397                last_state: a
398                    .last_observed
399                    .as_ref()
400                    .map(|o| o.state.as_wire().to_string()),
401                last_observed_at: a.last_observed.as_ref().map(|o| o.at.clone()),
402            })
403            .collect();
404
405        let precheck = match parse_failure {
406            Some(error) => Precheck::failed(
407                "parse",
408                vec![PrecheckFailure {
409                    code: "PARSE_ERROR".to_string(),
410                    message: error,
411                }],
412            ),
413            None => self.precheck(target, slug, status, &conflict, landing_entity.as_ref()),
414        };
415
416        let re_proposal: Vec<ReProposalMark> = record
417            .map(|r| r.rejections_matching(slug, content_hash.as_deref()))
418            .unwrap_or_default();
419
420        ProposalEntry {
421            slug: slug.to_string(),
422            fork_id: EntityId::new(fork, slug).to_string(),
423            target_id: EntityId::new(target, slug).to_string(),
424            status,
425            renamed_from,
426            title,
427            entity_type,
428            content_hash,
429            fork_delta,
430            referrers,
431            anchors,
432            precheck,
433            conflict,
434            re_proposal,
435            base_body,
436            fork_body,
437        }
438    }
439
440    /// Rehearse the write the merge would run in the target for this
441    /// entry, through the write gate's dry run, over a store snapshot
442    /// restored afterwards (a dry run may stage auto-stubs in memory).
443    /// Never a content judgement: the gate refuses mechanics only.
444    fn precheck(
445        &mut self,
446        target: &str,
447        slug: &str,
448        status: ProposalChange,
449        conflict: &Option<Conflict>,
450        landing: Option<&Entity>,
451    ) -> Precheck {
452        let Some(landing) = landing else {
453            return match status {
454                ProposalChange::Deleted => Precheck::not_run(
455                    "a deletion is judged against the target's referrers, listed above",
456                ),
457                _ => Precheck::not_run("the fork's body does not parse under the target's schema"),
458            };
459        };
460        if status == ProposalChange::Deleted {
461            return Precheck::not_run(
462                "a deletion is judged against the target's referrers, listed above",
463            );
464        }
465        let target_id = EntityId::new(target, slug);
466        let target_has = self.target_holds(&target_id);
467        if let Some(c) = conflict {
468            match c.kind {
469                ConflictKind::TargetDeleted => {
470                    return Precheck::not_run(
471                        "the target no longer holds this entity; the owner resolves the conflict first",
472                    );
473                }
474                ConflictKind::TargetAdded => {
475                    return Precheck::not_run(
476                        "the target holds its own entity under this slug; the owner resolves the conflict first",
477                    );
478                }
479                ConflictKind::TargetModified => {}
480            }
481        }
482        let snapshot = self.store.clone();
483        let existing = self.store.get(&target_id).filter(|e| !e.stub).cloned();
484        let outcome: Result<(), EngineError> =
485            match self.landing_write_args(target, slug, landing, existing.as_ref()) {
486                // The dry run keeps the relations the fork dropped (the
487                // repair gate reserves `relations_unset` for a non-conformant
488                // entity); the merge removes them before it composes.
489                LandingWrite::Update(args) => self
490                    .update_entity(
491                        crate::UpdateEntityArgs {
492                            dry_run: true,
493                            relations_unset: Vec::new(),
494                            ..*args
495                        },
496                        crate::vcs::Actor::Cli,
497                        None,
498                        None,
499                    )
500                    .map(|_| ()),
501                LandingWrite::Create(args) => self
502                    .create_entity(
503                        crate::CreateEntityArgs {
504                            dry_run: true,
505                            ..*args
506                        },
507                        crate::vcs::Actor::Cli,
508                        None,
509                        None,
510                    )
511                    .map(|_| ()),
512            };
513        self.store = snapshot;
514        let operation = if target_has { "update" } else { "create" };
515        match outcome {
516            Ok(()) => Precheck::clean(operation),
517            Err(e) => Precheck::failed(
518                operation,
519                vec![PrecheckFailure {
520                    code: e.code().to_string(),
521                    message: e.prose_render(),
522                }],
523            ),
524        }
525    }
526}
527
528/// The write the merge would run in the target for a landing body:
529/// an update of the entity the target holds, or a create.
530pub(crate) enum LandingWrite {
531    Create(Box<crate::CreateEntityArgs>),
532    Update(Box<crate::UpdateEntityArgs>),
533}
534
535impl Engine {
536    /// Whether the target holds a real (non-stub) entity at `id`.
537    pub(crate) fn target_holds(&self, id: &EntityId) -> bool {
538        self.store.get(id).is_some_and(|e| !e.stub)
539    }
540
541    /// The create or update that lands `landing` (the fork's version
542    /// under the target's name) in the target as the fork has it: every
543    /// section and metadata field set, the target's sections and fields
544    /// the fork lacks unset, the fork's authored relations declared (the
545    /// rows the schema synthesises from body links are left to the
546    /// gate, which re-emits them from the landed body) and the target's
547    /// relations the fork lacks unset. `existing` is the entity the
548    /// target holds at the slug (an update), or `None` (a create). The
549    /// brief's precheck rehearses exactly this; the merge applies it.
550    pub(crate) fn landing_write_args(
551        &self,
552        target: &str,
553        slug: &str,
554        landing: &Entity,
555        existing: Option<&Entity>,
556    ) -> LandingWrite {
557        let target_id = EntityId::new(target, slug);
558        let sections: indexmap::IndexMap<String, String> = landing
559            .sections
560            .iter()
561            .filter(|(k, _)| k.as_str() != "relationships")
562            .map(|(k, v)| (k.clone(), v.clone()))
563            .collect();
564        let metadata: indexmap::IndexMap<String, String> = landing
565            .metadata
566            .iter()
567            .filter(|(k, _)| !STAMPED_METADATA.contains(&k.as_str()))
568            .map(|(k, v)| (k.clone(), v.to_frontmatter_string()))
569            .collect();
570        // The rows the engine synthesises from body wiki-links (the
571        // schema's `alias_target_rel_type`, which the loader forces to
572        // `manual_authoring: forbidden`) are never authored here: the
573        // write gate re-emits them from the landed body, and an explicit
574        // row would refuse `RELATION_MANUAL_AUTHORING_FORBIDDEN`. Every
575        // other row is the proposer's own declaration and lands as such.
576        let synthesised: Option<String> = self
577            .schemas
578            .get(target)
579            .and_then(|s| s.alias_target_rel_type().map(str::to_string));
580        let relations: Vec<crate::ops::RelateArg> = landing
581            .relationships
582            .iter()
583            .filter(|r| synthesised.as_deref() != Some(r.rel_type.as_str()))
584            .map(|r| crate::ops::RelateArg {
585                target: r.target.clone(),
586                rel_type: r.rel_type.clone(),
587                description: r.description.clone(),
588            })
589            .collect();
590        match existing {
591            Some(existing) => {
592                let sections_unset: Vec<String> = existing
593                    .sections
594                    .keys()
595                    .filter(|k| k.as_str() != "relationships" && !sections.contains_key(*k))
596                    .cloned()
597                    .collect();
598                let metadata_unset: Vec<String> = existing
599                    .metadata
600                    .keys()
601                    .filter(|k| {
602                        !STAMPED_METADATA.contains(&k.as_str()) && !metadata.contains_key(*k)
603                    })
604                    .cloned()
605                    .collect();
606                let declare_relations: Vec<crate::ops::RelateArg> = relations
607                    .iter()
608                    .filter(|r| {
609                        !existing
610                            .relationships
611                            .iter()
612                            .any(|x| x.rel_type == r.rel_type && x.target == r.target)
613                    })
614                    .cloned()
615                    .collect();
616                // The relations the fork dropped. The merge removes them
617                // from the store's copy before the update composes (the
618                // repair gate keeps `relations_unset` for non-conformant
619                // entities); the precheck's dry run leaves them, which
620                // only makes it stricter.
621                let relations_unset: Vec<crate::ops::RelationUnsetArg> = existing
622                    .relationships
623                    .iter()
624                    .filter(|x| {
625                        !landing
626                            .relationships
627                            .iter()
628                            .any(|r| r.rel_type == x.rel_type && r.target == x.target)
629                    })
630                    .map(|x| crate::ops::RelationUnsetArg {
631                        target: x.target.clone(),
632                        rel_type: x.rel_type.clone(),
633                    })
634                    .collect();
635                LandingWrite::Update(Box::new(crate::UpdateEntityArgs {
636                    id: target_id,
637                    expected_hash: None,
638                    sections,
639                    append_sections: Default::default(),
640                    patch_sections: Default::default(),
641                    sections_unset,
642                    metadata,
643                    metadata_unset,
644                    dry_run: false,
645                    declare_relations,
646                    anchors: Vec::new(),
647                    anchors_unset: Vec::new(),
648                    relations_unset,
649                }))
650            }
651            None => LandingWrite::Create(Box::new(crate::CreateEntityArgs {
652                mem: target.to_string(),
653                title: landing.title.clone(),
654                entity_type: landing.entity_type.clone(),
655                sections,
656                metadata,
657                relations,
658                anchors: Vec::new(),
659                dry_run: false,
660            })),
661        }
662    }
663}
664
665/// The sha a ref resolves to; `UNKNOWN_REF` when it does not.
666pub(crate) fn resolve_sha(
667    ops: &crate::engine::GitBranchOps,
668    gitdir: &Path,
669    ref_name: &str,
670) -> Result<String, EngineError> {
671    match (ops.resolve_ref)(gitdir, ref_name) {
672        Ok(Some(sha)) => Ok(sha),
673        Ok(None) => Err(EngineError::UnknownRef(ref_name.to_string())),
674        Err(e) => Err(EngineError::Backend(e)),
675    }
676}
677
678/// The two-tree walk between two refs of one branch's mem, ids under
679/// `mem`.
680fn run_diff(
681    ops: &crate::engine::GitBranchOps,
682    gitdir: &Path,
683    branch: &str,
684    mem: &str,
685    ref_a: &str,
686    ref_b: &str,
687    config: &DiffConfig,
688) -> Result<crate::ops::Diff, EngineError> {
689    (ops.diff)(gitdir, branch, mem, ref_a, ref_b, config).map_err(|e| match e {
690        BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
691            EngineError::UnknownRef(msg.trim_start_matches("UNKNOWN_REF:").trim().to_string())
692        }
693        other => EngineError::Backend(other),
694    })
695}
696
697/// A diff's entries keyed by slug (a rename by its new slug).
698fn side_changes(entries: &[EntityDiff]) -> BTreeMap<String, SideChange> {
699    let mut out = BTreeMap::new();
700    for entry in entries {
701        match entry {
702            EntityDiff::Added {
703                id, content_after, ..
704            } => {
705                out.insert(
706                    id.path().to_string(),
707                    SideChange::Added {
708                        after: content_after.clone(),
709                    },
710                );
711            }
712            EntityDiff::Modified {
713                id,
714                content_before,
715                content_after,
716                ..
717            } => {
718                out.insert(
719                    id.path().to_string(),
720                    SideChange::Modified {
721                        before: content_before.clone(),
722                        after: content_after.clone(),
723                    },
724                );
725            }
726            EntityDiff::Deleted {
727                id, content_before, ..
728            } => {
729                out.insert(
730                    id.path().to_string(),
731                    SideChange::Deleted {
732                        before: content_before.clone(),
733                    },
734                );
735            }
736            EntityDiff::Renamed {
737                from_id,
738                to_id,
739                content_before,
740                content_after,
741                ..
742            } => {
743                out.insert(
744                    to_id.path().to_string(),
745                    SideChange::Renamed {
746                        from: from_id.path().to_string(),
747                        before: content_before.clone(),
748                        after: content_after.clone(),
749                    },
750                );
751            }
752            EntityDiff::InvalidEntity {
753                id,
754                error,
755                content_before,
756                content_after,
757                ..
758            } => {
759                out.insert(
760                    id.path().to_string(),
761                    SideChange::Invalid {
762                        error: error.clone(),
763                        before: content_before.clone(),
764                        after: content_after.clone(),
765                    },
766                );
767            }
768        }
769    }
770    out
771}
772
773/// The hash the brief and the record key a proposed version by: the
774/// landing body with the engine's date stamps (`created_date`,
775/// `last_modified`) dropped from the frontmatter, so the same body
776/// proposed again from another fork, on another day, hashes the same
777/// and a recorded rejection is recognised. The entity's own `_hash`
778/// stays the file hash; this one exists for the re-proposal match.
779pub(crate) fn proposal_content_hash(landing_body: &str) -> String {
780    let mut out = String::with_capacity(landing_body.len());
781    let mut in_frontmatter = false;
782    for (i, line) in landing_body.split_inclusive('\n').enumerate() {
783        let trimmed = line.trim_end_matches(['\n', '\r']);
784        if i == 0 && trimmed == "---" {
785            in_frontmatter = true;
786            out.push_str(line);
787            continue;
788        }
789        if in_frontmatter {
790            if trimmed == "---" {
791                in_frontmatter = false;
792            } else if STAMPED_METADATA
793                .iter()
794                .filter(|k| **k != "type")
795                .any(|k| trimmed.starts_with(&format!("{k}:")))
796            {
797                continue;
798            }
799        }
800        out.push_str(line);
801    }
802    crate::entity::parser::compute_hash(&out)
803}
804
805/// A body with the mem-qualified self-links of `from` rewritten to
806/// `to` (`[[from--slug]]`, `[[from:slug]]`), code spans and links
807/// naming any other mem untouched. The export retargeting rule.
808pub(crate) fn normalise_to(body: &str, from: &str, to: &str) -> String {
809    let bytes = crate::ops::export::retarget_mem_links(body.as_bytes().to_vec(), from, to);
810    String::from_utf8(bytes).unwrap_or_else(|_| body.to_string())
811}
812
813/// Parse a body under `mem` against the schema; `None` when the type
814/// is unknown or the body does not parse.
815pub(crate) fn parse_body(
816    body: &str,
817    rel_path: &str,
818    mem: &str,
819    schema: Option<&memstead_schema::Schema>,
820) -> Option<Entity> {
821    let schema = schema?;
822    let (_, entity_type) = crate::entity::parser::peek_title_and_type(body);
823    let type_def = schema.get_type(&entity_type?)?;
824    crate::entity::parser::parse_markdown(body, rel_path, type_def.as_ref(), mem)
825        .ok()
826        .map(|r| r.entity)
827}
828
829/// How `side` differs from `base`.
830fn version_delta(base: &Entity, side: &Entity) -> VersionDelta {
831    let mut sections: Vec<String> = Vec::new();
832    for (key, value) in &side.sections {
833        if key == "relationships" {
834            continue;
835        }
836        if base.sections.get(key) != Some(value) {
837            sections.push(key.clone());
838        }
839    }
840    for key in base.sections.keys() {
841        if key != "relationships" && !side.sections.contains_key(key) {
842            sections.push(key.clone());
843        }
844    }
845    let mut metadata: Vec<String> = Vec::new();
846    for (key, value) in &side.metadata {
847        if STAMPED_METADATA.contains(&key.as_str()) {
848            continue;
849        }
850        if base.metadata.get(key) != Some(value) {
851            metadata.push(key.clone());
852        }
853    }
854    for key in base.metadata.keys() {
855        if !STAMPED_METADATA.contains(&key.as_str()) && !side.metadata.contains_key(key) {
856            metadata.push(key.clone());
857        }
858    }
859    let rels = |e: &Entity| -> Vec<(String, String, Option<String>)> {
860        let mut v: Vec<_> = e
861            .relationships
862            .iter()
863            .map(|r| {
864                (
865                    r.rel_type.clone(),
866                    r.target.to_string(),
867                    r.description.clone(),
868                )
869            })
870            .collect();
871        v.sort();
872        v
873    };
874    VersionDelta {
875        title_differs: base.title != side.title,
876        entity_type_differs: base.entity_type != side.entity_type,
877        sections,
878        metadata,
879        relationships_differ: rels(base) != rels(side),
880    }
881}
882
883/// The conflict for one fork change against the target's changes:
884/// the kind and the target's body (when the target still holds one).
885fn conflict_for(
886    status: ProposalChange,
887    slug: &str,
888    renamed_from: Option<&str>,
889    target_changes: &BTreeMap<String, SideChange>,
890) -> Option<(ConflictKind, Option<String>)> {
891    // The target's changes read as: a slug it created, a slug it
892    // modified, a slug it deleted (a rename is a deletion of the old
893    // slug and a creation of the new one).
894    let mut created: HashMap<&str, Option<String>> = HashMap::new();
895    let mut modified: HashMap<&str, Option<String>> = HashMap::new();
896    let mut deleted: Vec<&str> = Vec::new();
897    for (target_slug, change) in target_changes {
898        match change {
899            SideChange::Added { after } => {
900                created.insert(target_slug.as_str(), after.clone());
901            }
902            SideChange::Modified { after, .. } => {
903                modified.insert(target_slug.as_str(), after.clone());
904            }
905            SideChange::Deleted { .. } => deleted.push(target_slug.as_str()),
906            SideChange::Renamed { from, after, .. } => {
907                deleted.push(from.as_str());
908                created.insert(target_slug.as_str(), after.clone());
909            }
910            SideChange::Invalid { before, after, .. } => match (before, after) {
911                (None, _) => {
912                    created.insert(target_slug.as_str(), after.clone());
913                }
914                (_, None) => deleted.push(target_slug.as_str()),
915                _ => {
916                    modified.insert(target_slug.as_str(), after.clone());
917                }
918            },
919        }
920    }
921    match status {
922        ProposalChange::Added => created
923            .get(slug)
924            .map(|body| (ConflictKind::TargetAdded, body.clone())),
925        ProposalChange::Modified | ProposalChange::Deleted => {
926            if let Some(body) = modified.get(slug) {
927                Some((ConflictKind::TargetModified, body.clone()))
928            } else if deleted.contains(&slug) {
929                Some((ConflictKind::TargetDeleted, None))
930            } else {
931                None
932            }
933        }
934        ProposalChange::Renamed => {
935            let from = renamed_from.unwrap_or(slug);
936            if let Some(body) = created.get(slug) {
937                Some((ConflictKind::TargetAdded, body.clone()))
938            } else if let Some(body) = modified.get(from) {
939                Some((ConflictKind::TargetModified, body.clone()))
940            } else if deleted.contains(&from) {
941                Some((ConflictKind::TargetDeleted, None))
942            } else {
943                None
944            }
945        }
946    }
947}