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