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    ) -> Result<ProposalEntry, EngineError> {
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        // An unreadable sidecar refuses the brief: a reviewer would
390        // otherwise read the entry as carrying no anchors.
391        let anchors: Vec<AnchorRow> = self
392            .entity_anchors_for_write(&EntityId::new(fork, slug))?
393            .into_iter()
394            .map(|a| AnchorRow {
395                artifact: a.artifact.clone(),
396                grain: a.grain.as_wire().to_string(),
397                class: a.class.as_wire().to_string(),
398                span: a.span.clone(),
399                last_state: a
400                    .last_observed
401                    .as_ref()
402                    .map(|o| o.state.as_wire().to_string()),
403                last_observed_at: a.last_observed.as_ref().map(|o| o.at.clone()),
404            })
405            .collect();
406
407        let precheck = match parse_failure {
408            Some(error) => Precheck::failed(
409                "parse",
410                vec![PrecheckFailure {
411                    code: "PARSE_ERROR".to_string(),
412                    message: error,
413                }],
414            ),
415            None => self.precheck(target, slug, status, &conflict, landing_entity.as_ref())?,
416        };
417
418        let re_proposal: Vec<ReProposalMark> = record
419            .map(|r| r.rejections_matching(slug, content_hash.as_deref()))
420            .unwrap_or_default();
421
422        Ok(ProposalEntry {
423            slug: slug.to_string(),
424            fork_id: EntityId::new(fork, slug).to_string(),
425            target_id: EntityId::new(target, slug).to_string(),
426            status,
427            renamed_from,
428            title,
429            entity_type,
430            content_hash,
431            fork_delta,
432            referrers,
433            anchors,
434            precheck,
435            conflict,
436            re_proposal,
437            base_body,
438            fork_body,
439        })
440    }
441
442    /// Rehearse the write the merge would run in the target for this
443    /// entry, through the write gate's dry run, over a store snapshot
444    /// restored afterwards (a dry run may stage auto-stubs in memory).
445    /// Never a content judgement: the gate refuses mechanics only.
446    fn precheck(
447        &mut self,
448        target: &str,
449        slug: &str,
450        status: ProposalChange,
451        conflict: &Option<Conflict>,
452        landing: Option<&Entity>,
453    ) -> Result<Precheck, EngineError> {
454        let Some(landing) = landing else {
455            return Ok(match status {
456                ProposalChange::Deleted => Precheck::not_run(
457                    "a deletion is judged against the target's referrers, listed above",
458                ),
459                _ => Precheck::not_run("the fork's body does not parse under the target's schema"),
460            });
461        };
462        if status == ProposalChange::Deleted {
463            return Ok(Precheck::not_run(
464                "a deletion is judged against the target's referrers, listed above",
465            ));
466        }
467        let target_id = EntityId::new(target, slug);
468        let target_has = self.target_holds(&target_id);
469        if let Some(c) = conflict {
470            match c.kind {
471                ConflictKind::TargetDeleted => {
472                    return Ok(Precheck::not_run(
473                        "the target no longer holds this entity; the owner resolves the conflict first",
474                    ));
475                }
476                ConflictKind::TargetAdded => {
477                    return Ok(Precheck::not_run(
478                        "the target holds its own entity under this slug; the owner resolves the conflict first",
479                    ));
480                }
481                ConflictKind::TargetModified => {}
482            }
483        }
484        let snapshot = self.store.clone();
485        let existing = self.store.get(&target_id).filter(|e| !e.stub).cloned();
486        let outcome: Result<(), EngineError> =
487            match self.landing_write_args(target, slug, landing, existing.as_ref()) {
488                // The dry run keeps the relations the fork dropped (the
489                // repair gate reserves `relations_unset` for a non-conformant
490                // entity); the merge removes them before it composes.
491                LandingWrite::Update(args) => self
492                    .update_entity(
493                        crate::UpdateEntityArgs {
494                            dry_run: true,
495                            relations_unset: Vec::new(),
496                            ..*args
497                        },
498                        crate::vcs::Actor::Cli,
499                        None,
500                        None,
501                    )
502                    .map(|_| ()),
503                LandingWrite::Create(args) => self
504                    .create_entity(
505                        crate::CreateEntityArgs {
506                            dry_run: true,
507                            ..*args
508                        },
509                        crate::vcs::Actor::Cli,
510                        None,
511                        None,
512                    )
513                    .map(|_| ()),
514            };
515        self.store = snapshot;
516        let operation = if target_has { "update" } else { "create" };
517        Ok(match outcome {
518            Ok(()) => Precheck::clean(operation),
519            // A storage failure says nothing about the proposal: the
520            // brief refuses rather than report it as the entry's result.
521            Err(
522                e @ (EngineError::Backend(_)
523                | EngineError::StaleView { .. }
524                | EngineError::CommitNotApplied { .. }),
525            ) => return Err(e),
526            Err(e) => Precheck::failed(
527                operation,
528                vec![PrecheckFailure {
529                    code: e.code().to_string(),
530                    message: e.prose_render(),
531                }],
532            ),
533        })
534    }
535}
536
537/// The write the merge would run in the target for a landing body:
538/// an update of the entity the target holds, or a create.
539pub(crate) enum LandingWrite {
540    Create(Box<crate::CreateEntityArgs>),
541    Update(Box<crate::UpdateEntityArgs>),
542}
543
544impl Engine {
545    /// Whether the target holds a real (non-stub) entity at `id`.
546    pub(crate) fn target_holds(&self, id: &EntityId) -> bool {
547        self.store.get(id).is_some_and(|e| !e.stub)
548    }
549
550    /// The create or update that lands `landing` (the fork's version
551    /// under the target's name) in the target as the fork has it: every
552    /// section and metadata field set, the target's sections and fields
553    /// the fork lacks unset, the fork's authored relations declared (the
554    /// rows the schema synthesises from body links are left to the
555    /// gate, which re-emits them from the landed body) and the target's
556    /// relations the fork lacks unset. `existing` is the entity the
557    /// target holds at the slug (an update), or `None` (a create). The
558    /// brief's precheck rehearses exactly this; the merge applies it.
559    pub(crate) fn landing_write_args(
560        &self,
561        target: &str,
562        slug: &str,
563        landing: &Entity,
564        existing: Option<&Entity>,
565    ) -> LandingWrite {
566        let target_id = EntityId::new(target, slug);
567        let sections: indexmap::IndexMap<String, String> = landing
568            .sections
569            .iter()
570            .filter(|(k, _)| k.as_str() != "relationships")
571            .map(|(k, v)| (k.clone(), v.clone()))
572            .collect();
573        let metadata: indexmap::IndexMap<String, String> = landing
574            .metadata
575            .iter()
576            .filter(|(k, _)| !STAMPED_METADATA.contains(&k.as_str()))
577            .map(|(k, v)| (k.clone(), v.to_frontmatter_string()))
578            .collect();
579        // The rows the engine synthesises from body wiki-links (the
580        // schema's `alias_target_rel_type`, which the loader forces to
581        // `manual_authoring: forbidden`) are never authored here: the
582        // write gate re-emits them from the landed body, and an explicit
583        // row would refuse `RELATION_MANUAL_AUTHORING_FORBIDDEN`. Every
584        // other row is the proposer's own declaration and lands as such.
585        let synthesised: Option<String> = self
586            .schemas
587            .get(target)
588            .and_then(|s| s.alias_target_rel_type().map(str::to_string));
589        let relations: Vec<crate::ops::RelateArg> = landing
590            .relationships
591            .iter()
592            .filter(|r| synthesised.as_deref() != Some(r.rel_type.as_str()))
593            .map(|r| crate::ops::RelateArg {
594                target: r.target.clone(),
595                rel_type: r.rel_type.clone(),
596                description: r.description.clone(),
597            })
598            .collect();
599        match existing {
600            Some(existing) => {
601                let sections_unset: Vec<String> = existing
602                    .sections
603                    .keys()
604                    .filter(|k| k.as_str() != "relationships" && !sections.contains_key(*k))
605                    .cloned()
606                    .collect();
607                let metadata_unset: Vec<String> = existing
608                    .metadata
609                    .keys()
610                    .filter(|k| {
611                        !STAMPED_METADATA.contains(&k.as_str()) && !metadata.contains_key(*k)
612                    })
613                    .cloned()
614                    .collect();
615                let declare_relations: Vec<crate::ops::RelateArg> = relations
616                    .iter()
617                    .filter(|r| {
618                        !existing
619                            .relationships
620                            .iter()
621                            .any(|x| x.rel_type == r.rel_type && x.target == r.target)
622                    })
623                    .cloned()
624                    .collect();
625                // The relations the fork dropped. The merge removes them
626                // from the store's copy before the update composes (the
627                // repair gate keeps `relations_unset` for non-conformant
628                // entities); the precheck's dry run leaves them, which
629                // only makes it stricter.
630                let relations_unset: Vec<crate::ops::RelationUnsetArg> = existing
631                    .relationships
632                    .iter()
633                    .filter(|x| {
634                        !landing
635                            .relationships
636                            .iter()
637                            .any(|r| r.rel_type == x.rel_type && r.target == x.target)
638                    })
639                    .map(|x| crate::ops::RelationUnsetArg {
640                        target: x.target.clone(),
641                        rel_type: x.rel_type.clone(),
642                    })
643                    .collect();
644                LandingWrite::Update(Box::new(crate::UpdateEntityArgs {
645                    id: target_id,
646                    // The merge has compared the target against the recorded
647                    // ancestor under its own lock; a hash read now adds nothing.
648                    expected_hash: crate::ExpectedHash::Override(
649                        crate::HashOverride::ProposalMerge,
650                    ),
651                    sections,
652                    append_sections: Default::default(),
653                    patch_sections: Default::default(),
654                    sections_unset,
655                    metadata,
656                    metadata_unset,
657                    dry_run: false,
658                    declare_relations,
659                    anchors: Vec::new(),
660                    anchors_unset: Vec::new(),
661                    relations_unset,
662                }))
663            }
664            None => LandingWrite::Create(Box::new(crate::CreateEntityArgs {
665                mem: target.to_string(),
666                title: landing.title.clone(),
667                entity_type: landing.entity_type.clone(),
668                sections,
669                metadata,
670                relations,
671                anchors: Vec::new(),
672                dry_run: false,
673            })),
674        }
675    }
676}
677
678/// The sha a ref resolves to; `UNKNOWN_REF` when it does not.
679pub(crate) fn resolve_sha(
680    ops: &crate::engine::GitBranchOps,
681    gitdir: &Path,
682    ref_name: &str,
683) -> Result<String, EngineError> {
684    match (ops.resolve_ref)(gitdir, ref_name) {
685        Ok(Some(sha)) => Ok(sha),
686        Ok(None) => Err(EngineError::UnknownRef(ref_name.to_string())),
687        Err(e) => Err(EngineError::Backend(e)),
688    }
689}
690
691/// The two-tree walk between two refs of one branch's mem, ids under
692/// `mem`.
693fn run_diff(
694    ops: &crate::engine::GitBranchOps,
695    gitdir: &Path,
696    branch: &str,
697    mem: &str,
698    ref_a: &str,
699    ref_b: &str,
700    config: &DiffConfig,
701) -> Result<crate::ops::Diff, EngineError> {
702    (ops.diff)(gitdir, branch, mem, ref_a, ref_b, config).map_err(|e| match e {
703        BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
704            EngineError::UnknownRef(msg.trim_start_matches("UNKNOWN_REF:").trim().to_string())
705        }
706        other => EngineError::Backend(other),
707    })
708}
709
710/// A diff's entries keyed by slug (a rename by its new slug).
711fn side_changes(entries: &[EntityDiff]) -> BTreeMap<String, SideChange> {
712    let mut out = BTreeMap::new();
713    for entry in entries {
714        match entry {
715            EntityDiff::Added {
716                id, content_after, ..
717            } => {
718                out.insert(
719                    id.path().to_string(),
720                    SideChange::Added {
721                        after: content_after.clone(),
722                    },
723                );
724            }
725            EntityDiff::Modified {
726                id,
727                content_before,
728                content_after,
729                ..
730            } => {
731                out.insert(
732                    id.path().to_string(),
733                    SideChange::Modified {
734                        before: content_before.clone(),
735                        after: content_after.clone(),
736                    },
737                );
738            }
739            EntityDiff::Deleted {
740                id, content_before, ..
741            } => {
742                out.insert(
743                    id.path().to_string(),
744                    SideChange::Deleted {
745                        before: content_before.clone(),
746                    },
747                );
748            }
749            EntityDiff::Renamed {
750                from_id,
751                to_id,
752                content_before,
753                content_after,
754                ..
755            } => {
756                out.insert(
757                    to_id.path().to_string(),
758                    SideChange::Renamed {
759                        from: from_id.path().to_string(),
760                        before: content_before.clone(),
761                        after: content_after.clone(),
762                    },
763                );
764            }
765            EntityDiff::InvalidEntity {
766                id,
767                error,
768                content_before,
769                content_after,
770                ..
771            } => {
772                out.insert(
773                    id.path().to_string(),
774                    SideChange::Invalid {
775                        error: error.clone(),
776                        before: content_before.clone(),
777                        after: content_after.clone(),
778                    },
779                );
780            }
781        }
782    }
783    out
784}
785
786/// The hash the brief and the record key a proposed version by: the
787/// landing body with the engine's date stamps (`created_date`,
788/// `last_modified`) dropped from the frontmatter, so the same body
789/// proposed again from another fork, on another day, hashes the same
790/// and a recorded rejection is recognised. The entity's own `_hash`
791/// stays the file hash; this one exists for the re-proposal match.
792pub(crate) fn proposal_content_hash(landing_body: &str) -> String {
793    let mut out = String::with_capacity(landing_body.len());
794    let mut in_frontmatter = false;
795    for (i, line) in landing_body.split_inclusive('\n').enumerate() {
796        let trimmed = line.trim_end_matches(['\n', '\r']);
797        if i == 0 && trimmed == "---" {
798            in_frontmatter = true;
799            out.push_str(line);
800            continue;
801        }
802        if in_frontmatter {
803            if trimmed == "---" {
804                in_frontmatter = false;
805            } else if STAMPED_METADATA
806                .iter()
807                .filter(|k| **k != "type")
808                .any(|k| trimmed.starts_with(&format!("{k}:")))
809            {
810                continue;
811            }
812        }
813        out.push_str(line);
814    }
815    crate::entity::parser::compute_hash(&out)
816}
817
818/// A body with the mem-qualified self-links of `from` rewritten to
819/// `to` (`[[from--slug]]`, `[[from:slug]]`), code spans and links
820/// naming any other mem untouched. The export retargeting rule.
821pub(crate) fn normalise_to(body: &str, from: &str, to: &str) -> String {
822    let bytes = crate::ops::export::retarget_mem_links(body.as_bytes().to_vec(), from, to);
823    String::from_utf8(bytes).unwrap_or_else(|_| body.to_string())
824}
825
826/// Parse a body under `mem` against the schema; `None` when the type
827/// is unknown or the body does not parse.
828pub(crate) fn parse_body(
829    body: &str,
830    rel_path: &str,
831    mem: &str,
832    schema: Option<&memstead_schema::Schema>,
833) -> Option<Entity> {
834    let schema = schema?;
835    let (_, entity_type) = crate::entity::parser::peek_title_and_type(body);
836    let type_def = schema.get_type(&entity_type?)?;
837    crate::entity::parser::parse_markdown(body, rel_path, type_def.as_ref(), mem)
838        .ok()
839        .map(|r| r.entity)
840}
841
842/// How `side` differs from `base`.
843fn version_delta(base: &Entity, side: &Entity) -> VersionDelta {
844    let mut sections: Vec<String> = Vec::new();
845    for (key, value) in &side.sections {
846        if key == "relationships" {
847            continue;
848        }
849        if base.sections.get(key) != Some(value) {
850            sections.push(key.clone());
851        }
852    }
853    for key in base.sections.keys() {
854        if key != "relationships" && !side.sections.contains_key(key) {
855            sections.push(key.clone());
856        }
857    }
858    let mut metadata: Vec<String> = Vec::new();
859    for (key, value) in &side.metadata {
860        if STAMPED_METADATA.contains(&key.as_str()) {
861            continue;
862        }
863        if base.metadata.get(key) != Some(value) {
864            metadata.push(key.clone());
865        }
866    }
867    for key in base.metadata.keys() {
868        if !STAMPED_METADATA.contains(&key.as_str()) && !side.metadata.contains_key(key) {
869            metadata.push(key.clone());
870        }
871    }
872    let rels = |e: &Entity| -> Vec<(String, String, Option<String>)> {
873        let mut v: Vec<_> = e
874            .relationships
875            .iter()
876            .map(|r| {
877                (
878                    r.rel_type.clone(),
879                    r.target.to_string(),
880                    r.description.clone(),
881                )
882            })
883            .collect();
884        v.sort();
885        v
886    };
887    VersionDelta {
888        title_differs: base.title != side.title,
889        entity_type_differs: base.entity_type != side.entity_type,
890        sections,
891        metadata,
892        relationships_differ: rels(base) != rels(side),
893    }
894}
895
896/// The conflict for one fork change against the target's changes:
897/// the kind and the target's body (when the target still holds one).
898fn conflict_for(
899    status: ProposalChange,
900    slug: &str,
901    renamed_from: Option<&str>,
902    target_changes: &BTreeMap<String, SideChange>,
903) -> Option<(ConflictKind, Option<String>)> {
904    // The target's changes read as: a slug it created, a slug it
905    // modified, a slug it deleted (a rename is a deletion of the old
906    // slug and a creation of the new one).
907    let mut created: HashMap<&str, Option<String>> = HashMap::new();
908    let mut modified: HashMap<&str, Option<String>> = HashMap::new();
909    let mut deleted: Vec<&str> = Vec::new();
910    for (target_slug, change) in target_changes {
911        match change {
912            SideChange::Added { after } => {
913                created.insert(target_slug.as_str(), after.clone());
914            }
915            SideChange::Modified { after, .. } => {
916                modified.insert(target_slug.as_str(), after.clone());
917            }
918            SideChange::Deleted { .. } => deleted.push(target_slug.as_str()),
919            SideChange::Renamed { from, after, .. } => {
920                deleted.push(from.as_str());
921                created.insert(target_slug.as_str(), after.clone());
922            }
923            SideChange::Invalid { before, after, .. } => match (before, after) {
924                (None, _) => {
925                    created.insert(target_slug.as_str(), after.clone());
926                }
927                (_, None) => deleted.push(target_slug.as_str()),
928                _ => {
929                    modified.insert(target_slug.as_str(), after.clone());
930                }
931            },
932        }
933    }
934    match status {
935        ProposalChange::Added => created
936            .get(slug)
937            .map(|body| (ConflictKind::TargetAdded, body.clone())),
938        ProposalChange::Modified | ProposalChange::Deleted => {
939            if let Some(body) = modified.get(slug) {
940                Some((ConflictKind::TargetModified, body.clone()))
941            } else if deleted.contains(&slug) {
942                Some((ConflictKind::TargetDeleted, None))
943            } else {
944                None
945            }
946        }
947        ProposalChange::Renamed => {
948            let from = renamed_from.unwrap_or(slug);
949            if let Some(body) = created.get(slug) {
950                Some((ConflictKind::TargetAdded, body.clone()))
951            } else if let Some(body) = modified.get(from) {
952                Some((ConflictKind::TargetModified, body.clone()))
953            } else if deleted.contains(&from) {
954                Some((ConflictKind::TargetDeleted, None))
955            } else {
956                None
957            }
958        }
959    }
960}