Skip to main content

memstead_base/engine/
drift.rs

1//! Drift detection and per-mem change synthesis.
2//!
3//! `reload_if_stale` probes each candidate mount's `current_head()`
4//! cursor on every operation (no throttle), reloads mems whose
5//! on-disk state has advanced past the engine's cached head, and
6//! surfaces `MemReloaded` warnings for handlers that need to
7//! re-derive conclusions from a now-reloaded snapshot. `changes_since`
8//! produces
9//! the per-entity diff between a stored cursor and the backend's
10//! current state — folder mounts synthesise from the changelog, the
11//! git-branch hook walks the tree with rename detection, archive
12//! mounts return empty.
13
14use crate::backend::BackendError;
15use crate::workspace::MountStorage;
16
17use super::mutation::lookup_title_and_type;
18use super::{Engine, EngineError};
19
20/// What [`Engine::fast_forward_ref`] did with one local ref.
21enum FastForward {
22    /// The remote-tracking ref does not exist.
23    NotOnRemote,
24    /// Local and remote already point at the same commit.
25    InSync,
26    /// The local ref moved (or was created, `previous` empty).
27    Moved { previous: String, new: String },
28    /// The local ref already contains the remote's commit and more
29    /// (unpushed local work); it was left alone.
30    LocalAhead,
31    /// Local and remote each have commits the other lacks; not moved.
32    Diverged,
33}
34
35impl Engine {
36    /// Reload-before-operation: before any read or write executes,
37    /// check the mem ref; if it advanced past the engine's cached
38    /// `last_known_head`, reload the affected mem(s) and return one
39    /// [`WarningHint::MemReloaded`] per reload so the caller can
40    /// surface the drift to the agent (the response *itself* already
41    /// carries fresh content — the warning explains why state
42    /// shifted).
43    ///
44    /// The ref check runs on **every** call — there is no throttle
45    /// window. A per-operation `current_head()` read is microseconds,
46    /// effectively free at LLM latencies, and a throttle that let an
47    /// operation execute against an already-moved ref would reintroduce
48    /// the exact silent-staleness this guards against. This is the
49    /// correctness floor: no operation acts on a projection that is
50    /// behind git truth.
51    ///
52    /// `mem = Some(name)` scopes the probe to one mount; `None`
53    /// scans every mount. Read handlers that target a known mem
54    /// (`memstead_entity` derives the mem from the id;
55    /// `memstead_changes_since` takes it as a param) and every mutation
56    /// (which knows its target mem) pass a name; tools that scan
57    /// multi-mem (`memstead_search` without a mem filter,
58    /// `memstead_overview`, `memstead_health`) pass `None`.
59    ///
60    /// Behaviour matrix per mount:
61    /// - cached `Some(old)` + on-disk `Some(new)`, `old != new` →
62    ///   reload the mem, emit `MemReloaded`, refresh the cached
63    ///   head to `new`.
64    /// - cached `None` + on-disk `Some(new)` → reload the mem and
65    ///   emit `MemReloaded`: a head appeared where none was seen (a
66    ///   branch that arrived, a folder ledger written by another
67    ///   process), so the view is behind it.
68    /// - cached / on-disk match, or on-disk `None` (a backend without a
69    ///   head) → no-op.
70    /// - `current_head` errors, or the mem's last reload failed or was
71    ///   incomplete → reload the mem whatever the head says; until a
72    ///   reload succeeds the mem takes no write.
73    ///
74    /// Reload errors are warn-logged and the affected mem is
75    /// skipped — the caller's response is still served from the (now
76    /// stale) in-memory snapshot rather than failing the entire
77    /// request. The next operation retries.
78    ///
79    /// Cache invalidation rides on `reload_one_mem` — community
80    /// and search-index memos drop when any mem reloads.
81    pub fn reload_if_stale(&mut self, mem: Option<&str>) -> Vec<crate::ops::WarningHint> {
82        let mut warnings = self.roster_warnings();
83        warnings.extend(self.reload_if_stale_content_only(mem));
84        warnings
85    }
86
87    /// The membership half of [`Self::reload_if_stale`]: the roster is
88    /// probed before content, because a mem that left must not be loaded
89    /// or served and a mem that arrived must be there for the operation
90    /// that follows (roster.rs). Also run on its own by a verb that
91    /// locks every writable mount, before it computes that lock set.
92    pub(in crate::engine) fn roster_warnings(&mut self) -> Vec<crate::ops::WarningHint> {
93        let mut warnings = Vec::new();
94        match self.reconcile_roster() {
95            Ok(Some(change)) if !change.is_empty() => {
96                warnings.push(crate::ops::WarningHint::MemRosterChanged {
97                    added: change.added,
98                    removed: change.removed,
99                    quarantined: change.quarantined,
100                    failures: change
101                        .failures
102                        .iter()
103                        .map(|f| format!("{}: {}", f.item, f.error))
104                        .collect(),
105                });
106            }
107            Ok(_) => {}
108            Err(e) => {
109                warnings.push(crate::ops::WarningHint::MemRosterChanged {
110                    added: Vec::new(),
111                    removed: Vec::new(),
112                    quarantined: Vec::new(),
113                    failures: vec![e.to_string()],
114                });
115            }
116        }
117        warnings
118    }
119
120    /// The content half of [`Self::reload_if_stale`] alone — the branch-tip
121    /// probe without the roster probe. Exposed for the cost comparison the
122    /// roster probe is held to; every operation goes through the full form.
123    pub fn reload_if_stale_content_only(
124        &mut self,
125        mem: Option<&str>,
126    ) -> Vec<crate::ops::WarningHint> {
127        let mut warnings = Vec::new();
128        // A single-caller surface has been there since boot: it is known
129        // with the heads as they stand before this reload, so what the
130        // reload brings in is news to it.
131        self.know_default_caller();
132        // Phase 0 — the lazy-mount first-read trigger. Every operation
133        // funnels through this check, so a deferred mem the operation's
134        // scope touches loads here, before the staleness probes — a
135        // scoped operation loads exactly its mem, a workspace-scoped one
136        // loads every deferred mem so no answer is computed over a
137        // partial store. Operations scoped to eager mems never load a
138        // lazy sibling as a side effect.
139        self.ensure_mems_loaded(mem);
140
141        // Phase 1 — pick candidate mem names that match the filter.
142        // Cloned so the immutable borrow doesn't survive into the
143        // mutation phase.
144        let candidates: Vec<String> = self
145            .mounts
146            .iter()
147            .filter(|m| mem.is_none_or(|v| m.mount.mem == v))
148            .map(|m| m.mount.mem.clone())
149            .collect();
150
151        if candidates.is_empty() {
152            return warnings;
153        }
154
155        // Before anything reads a backend: drop what a failed mutation
156        // left staged on it when its discard failed. While that cannot
157        // be done the mem's view takes no write, and no reload reads
158        // the backend (it would read the staged bytes as content).
159        for name in &candidates {
160            if let Err(e) = self.discard_strays(name)
161                && let Some(state) = self.mounts.iter_mut().find(|m| &m.mount.mem == name)
162            {
163                state.reload_failure = Some(crate::engine::ViewFailure {
164                    cause: crate::engine::StaleCause::DiscardFailed,
165                    detail: e.to_string(),
166                });
167            }
168        }
169
170        // Phase 2 — probe every candidate's current head via the
171        // backend. A probe error surfaces no warning; it marks the
172        // mem's view as unsure, which a reload below settles.
173        let mut probe_failures: Vec<(String, String)> = Vec::new();
174        let probes: Vec<(String, Option<String>, Option<String>, bool)> = candidates
175            .iter()
176            .filter_map(|name| {
177                let m = self.mounts.iter().find(|m| &m.mount.mem == name)?;
178                // A probe that fails says nothing about drift, and
179                // "nothing" must not read as "none": a write that
180                // followed would be computed from a view a sibling may
181                // have moved past. The mem is marked like one whose
182                // reload failed, and reloaded below regardless of what
183                // the head says.
184                let new_head = match m.backend.current_head() {
185                    Ok(head) => head,
186                    Err(e) => {
187                        probe_failures.push((name.clone(), e.to_string()));
188                        None
189                    }
190                };
191                let cached = m.last_known_head.clone();
192                let unsure = m.reload_failure.is_some()
193                    || probe_failures.last().is_some_and(|(n, _)| n == name);
194                Some((name.clone(), cached, new_head, unsure))
195            })
196            .collect();
197        for (name, error) in probe_failures {
198            if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == name) {
199                state.reload_failure = Some(crate::engine::ViewFailure::drift(format!(
200                    "the drift probe failed: {error}"
201                )));
202            }
203        }
204
205        // Phase 3 — act on each probe. The drift case is the only
206        // one that calls `reload_one_mem`; every other arm just
207        // (for first-observation) captures the baseline head silently.
208        for (name, cached, new_head, view_incomplete) in probes {
209            match (cached, new_head.clone()) {
210                (Some(old), Some(new)) if old != new => {
211                    match self.reload_one_mem(&name) {
212                        Ok(report) => {
213                            let new = self.head_after_reload(&name, new);
214                            warnings.push(crate::ops::WarningHint::MemReloaded {
215                                mem: name.clone(),
216                                old_head: old.clone(),
217                                new_head: new.clone(),
218                                entities_loaded: report.added.len() + report.changed.len(),
219                            });
220                            if let Some(state) =
221                                self.mounts.iter_mut().find(|m| m.mount.mem == name)
222                            {
223                                state.last_known_head = Some(new.clone());
224                            }
225                            // The structured notice is built once the
226                            // reload is through, per caller
227                            // (`note_changes_for_caller`): the delta from
228                            // the head that caller last saw, which for a
229                            // single-caller surface is `old → new`.
230                            // Emit the same change on the mem-change
231                            // event channel: subscribers (SSE forwarders
232                            // foremost) previously saw only this engine's
233                            // own writes — a sibling process's commit,
234                            // detected here as drift, is every bit as
235                            // much a change. `n_commits: 1` per the
236                            // watcher precedent (events batch by
237                            // detection, not by commit archaeology).
238                            self.emit_mem_changed(&crate::engine::events::MemChangedEvent {
239                                mem: name.clone(),
240                                head: new.clone(),
241                                previous: old.clone(),
242                                n_commits: 1,
243                            });
244                        }
245                        Err(e) => {
246                            self.note_reload_failure(&name, &e);
247                            tracing::warn!(
248                                mem = %name,
249                                error = %e,
250                                "drift-detected reload_one_mem failed; serving \
251                                 stale snapshot — will retry on the next operation"
252                            );
253                        }
254                    }
255                }
256                // A head that appears where none was cached is a change
257                // too: the branch was born, fetched or pushed into place
258                // since the engine last looked (a mount whose branch was
259                // missing at boot, an unborn mem that took its first
260                // commit). Adopting the head silently left the store at
261                // the empty load and the boot-time `MOUNT_UNBACKED`
262                // probe standing over entities the branch now holds.
263                (None, Some(new)) => match self.reload_one_mem(&name) {
264                    Ok(report) => {
265                        let new = self.head_after_reload(&name, new);
266                        warnings.push(crate::ops::WarningHint::MemReloaded {
267                            mem: name.clone(),
268                            old_head: String::new(),
269                            new_head: new.clone(),
270                            entities_loaded: report.added.len() + report.changed.len(),
271                        });
272                        if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == name) {
273                            state.last_known_head = Some(new.clone());
274                        }
275                        // The notice for a head that appeared where
276                        // none was is built per caller once the reload is
277                        // through (`note_changes_for_caller`).
278                        self.appeared_heads
279                            .insert(name.clone(), report.added.clone());
280                        self.emit_mem_changed(&crate::engine::events::MemChangedEvent {
281                            mem: name.clone(),
282                            head: new.clone(),
283                            previous: String::new(),
284                            n_commits: 1,
285                        });
286                    }
287                    Err(e) => {
288                        self.note_reload_failure(&name, &e);
289                        tracing::warn!(
290                            mem = %name,
291                            error = %e,
292                            "reload of a mem whose branch appeared failed; serving the \
293                             empty snapshot — will retry on the next operation"
294                        );
295                    }
296                },
297                // A head that was there and is gone: the mem's storage
298                // was moved or removed under this engine (a mem rename
299                // by another process moves the branch away). The view
300                // is of storage that no longer exists under this name,
301                // and a write would recreate it beside the mem that
302                // moved. The view takes no write; the roster reconcile
303                // of a workspace engine unmounts the mem, and a reload
304                // settles an engine that has no roster.
305                (Some(old), None) if !view_incomplete => {
306                    // Only storage that says it is gone: a backend with
307                    // no head to report (an in-memory mem) is as
308                    // present as ever.
309                    if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == name)
310                        && matches!(state.backend.storage_present(), Ok(false))
311                    {
312                        state.reload_failure = Some(crate::engine::ViewFailure::drift(format!(
313                            "the mem's storage is gone: its head was {old} and it has none now"
314                        )));
315                    }
316                }
317                // No drift, and the view in place is known to be
318                // incomplete or behind (its last load could not read
319                // everything): try again, so the mem takes writes again
320                // once storage delivers.
321                _ if view_incomplete => {
322                    if let Err(e) = self.reload_one_mem(&name) {
323                        self.note_reload_failure(&name, &e);
324                    }
325                }
326                _ => {}
327            }
328        }
329
330        // A commit that a load completed is reported by an operation,
331        // whatever became of that load after it. It waits while its
332        // mem's view is still behind (the operation at hand will be
333        // refused or serve the stale view), and it keeps a standing copy
334        // among the load warnings.
335        let (ready, waiting): (Vec<_>, Vec<_>) = std::mem::take(&mut self.completed_commits)
336            .into_iter()
337            .partition(|w| {
338                !self.mounts.iter().any(|m| {
339                    m.reload_failure.is_some() && w.source_mem() == Some(m.mount.mem.as_str())
340                })
341            });
342        self.completed_commits = waiting;
343        for warning in ready {
344            let text = warning.to_string();
345            if !self.load_warnings.iter().any(|w| w.to_string() == text) {
346                self.load_warnings.push(warning.clone());
347            }
348            warnings.push(warning);
349        }
350        // The reload is through and nothing of this operation is written
351        // yet: tell the caller what moved since it last looked.
352        let told = self.note_changes_for_caller();
353        if self.callers.catching_up {
354            // A reload on behalf of a notice in the making: the step
355            // that asked for it reads what this reload recorded.
356            return warnings;
357        }
358        if self.current_caller_is_default() {
359            // The default caller. Where it is the single caller of a
360            // surface, a mem this call reloaded has its warning already
361            // and that warning runs between the very heads its notice
362            // names: it stays as it is. Where the default caller shares
363            // the engine and was behind it, its notice runs from an
364            // older head than the reload's warning: the warning built
365            // from the notice takes its place. A mem that moved without
366            // a reload in this call gets its warning here.
367            for told in told {
368                let crate::ops::WarningHint::MemReloaded {
369                    mem: told_mem,
370                    old_head: told_from,
371                    new_head: told_to,
372                    ..
373                } = &told
374                else {
375                    continue;
376                };
377                let same_delta = warnings.iter().any(|w| {
378                    matches!(
379                        w,
380                        crate::ops::WarningHint::MemReloaded { mem, old_head, new_head, .. }
381                            if mem == told_mem && old_head == told_from && new_head == told_to
382                    )
383                });
384                if same_delta {
385                    continue;
386                }
387                let told_mem = told_mem.clone();
388                warnings.retain(|w| {
389                    !matches!(
390                        w,
391                        crate::ops::WarningHint::MemReloaded { mem, .. } if *mem == told_mem
392                    )
393                });
394                warnings.push(told);
395            }
396        } else {
397            // A named caller: the warning is the text form of its
398            // notice and nothing else. What this call's reload moved in
399            // the engine may be more or less than what is news to this
400            // caller (it may have been behind the engine already, or
401            // have come after the change), so the warnings of the
402            // reload give way to the ones built from its notices, which
403            // run from the head it last saw.
404            warnings.retain(|w| !matches!(w, crate::ops::WarningHint::MemReloaded { .. }));
405            warnings.extend(told);
406        }
407        self.appeared_heads.clear();
408        warnings
409    }
410
411    /// Remember that the drift reload of `mem` failed: its view is
412    /// behind storage until a reload succeeds, and no write may land on
413    /// it meanwhile ([`Self::commit_staged`]).
414    /// After this engine moved a mem's branch (a pull, a reset): serve the
415    /// tree the branch now names. The head cursor moves only with a
416    /// reload that went through; a failed one marks the view stale, so
417    /// the next operation reloads again and no write lands from the old
418    /// view in the meantime.
419    fn adopt_moved_head(
420        &mut self,
421        mount_idx: usize,
422        mem: &str,
423        new_head: &str,
424    ) -> Result<(), EngineError> {
425        match self.reload_one_mem(mem) {
426            Ok(_) => {
427                if let Some(state) = self.mounts.get_mut(mount_idx) {
428                    let before = state
429                        .last_known_head
430                        .replace(new_head.to_string())
431                        .unwrap_or_default();
432                    // The caller moved the branch itself (a pull, a
433                    // reset): it has seen where it now points.
434                    self.caller_saw_own_write(mem, &before, new_head);
435                }
436                Ok(())
437            }
438            Err(e) => {
439                self.note_reload_failure(mem, &e);
440                Err(e)
441            }
442        }
443    }
444
445    pub(in crate::engine) fn note_reload_failure(&mut self, mem: &str, error: &EngineError) {
446        if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == mem) {
447            state.reload_failure = Some(crate::engine::ViewFailure::drift(error.to_string()));
448        }
449    }
450
451    /// The head to record after a reload of `mem`. A load can move the
452    /// head itself: it completes a commit that was cut off, and the
453    /// cursor probed before the reload named the unfinished commit.
454    /// Recording that stale cursor would make the next operation see
455    /// drift again and reload a second time.
456    fn head_after_reload(&self, mem: &str, probed: String) -> String {
457        self.mounts
458            .iter()
459            .find(|m| m.mount.mem == mem)
460            .and_then(|m| m.backend.current_head().ok().flatten())
461            .unwrap_or(probed)
462    }
463
464    /// Mark `mount_idx`'s on-disk head as advanced by *this* engine's
465    /// own write so the next `reload_if_stale` doesn't surface
466    /// `MEM_RELOADED` for the commit we just produced. Mutation
467    /// paths call this immediately after `backend.commit` returns —
468    /// the cached `last_known_head` jumps straight to the new SHA
469    /// without going through a reload. Because every mutation runs
470    /// `reload_if_stale` for its target mem *before* committing,
471    /// the cached `last_known_head` is current at commit time, so
472    /// this advance is over a verified parent — it can never jump
473    /// the cache past an unobserved sibling commit. Cross-session and
474    /// out-of-band advances (sibling engine, manual `git pull`) that
475    /// land before the next operation still mismatch the cached value
476    /// and fire the warning as before.
477    ///
478    /// Empty SHA is a no-op (no commit landed — e.g. duplicate-add
479    /// relate). A folder backend's head is its change-ledger
480    /// watermark, recorded here like a branch tip; an archive tracks
481    /// no head and leaves `last_known_head` at `None`.
482    pub(crate) fn record_self_write(&mut self, mount_idx: usize, write_id: &str) {
483        if write_id.is_empty() {
484            return;
485        }
486        // Capture the pre-write head + mem name so the
487        // `MemChangedEvent` we emit reflects the transition the
488        // current commit produced. We do this before mutating
489        // `last_known_head` because that field is the previous SHA
490        // from the event's point of view.
491        let (mem, previous) = match self.mounts.get(mount_idx) {
492            Some(state) => (
493                state.mount.mem.clone(),
494                state.last_known_head.clone().unwrap_or_default(),
495            ),
496            None => return,
497        };
498        // The recorded head must equal what the backend's next
499        // `current_head()` probe will report, or every self-write
500        // would look like sibling drift on the following operation.
501        // For git-branch backends the probe returns exactly the commit
502        // SHA just produced; the folder backend's drift cursor is the
503        // changelog's last-line timestamp (a different dialect from
504        // its synthetic commit id), so probe once and prefer the
505        // backend's answer. Probe errors fall back to the commit id —
506        // drift detection stays best-effort, never blocking the write.
507        let recorded = self
508            .mounts
509            .get(mount_idx)
510            .and_then(|state| state.backend.current_head().ok().flatten())
511            .unwrap_or_else(|| write_id.to_string());
512        if let Some(state) = self.mounts.get_mut(mount_idx) {
513            state.last_known_head = Some(recorded.clone());
514        }
515        // The write is the current caller's own: it has seen this head.
516        self.caller_saw_own_write(&mem, &previous, &recorded);
517        // Skip emit when no SHA actually advanced — folder backends
518        // (and archive backends) carry `last_known_head: None` and
519        // pass `write_id = ""` in some paths; the early-return at
520        // the top already catches the explicit empty case, but
521        // `previous == write_id` covers idempotent re-writes that
522        // pass through the same write path (e.g. a relate that
523        // re-applies the same edge). Skipping keeps the event stream
524        // a stream of *changes* rather than a stream of *writes*.
525        if previous == recorded {
526            return;
527        }
528        let event = crate::engine::events::MemChangedEvent {
529            mem,
530            // The corrected head, not the raw commit id: consumers feed
531            // event heads into `changes_since`, whose folder dialect is
532            // the changelog-timestamp cursor `recorded` carries.
533            head: recorded,
534            previous,
535            n_commits: 1,
536        };
537        self.emit_mem_changed(&event);
538    }
539
540    /// Build a [`crate::ops::MemChangedNotice`] describing the
541    /// per-entity delta a reload applied to `mem` (from `from_head`
542    /// to `to_head`). Derived from [`Self::changes_since`] so it
543    /// carries rename detection on git-branch mounts; on any backend
544    /// error (e.g. an unresolvable cursor) it falls back to an empty
545    /// delta — the heads alone still tell the agent the mem moved.
546    ///
547    /// Callers pair this with [`Self::reload_if_stale`]: a returned
548    /// [`crate::ops::WarningHint::MemReloaded`] carries the
549    /// `old_head` / `new_head` to pass here. The delta matches the
550    /// transition the reload applied (`changes_since` walks the same
551    /// `from_head → current` range).
552    pub fn mem_changed_notice(
553        &self,
554        mem: &str,
555        from_head: &str,
556        to_head: &str,
557    ) -> crate::ops::MemChangedNotice {
558        let report = self.changes_since(mem, from_head, None).ok();
559        let (changes, notes) = match report {
560            Some(r) => (r.changes, r.notes),
561            None => (Vec::new(), None),
562        };
563        self.notice_for(mem, from_head, to_head, changes, notes.as_deref())
564    }
565
566    /// Build the notice for a delta of `mem` that starts at `from_head`.
567    /// For a delta small enough for the `detailed` tier, each entry
568    /// names the newest write to its entity in the range: on a
569    /// git-branch mem from the commit notes the change feed returned
570    /// (`notes`), on a folder mem from its change ledger. A larger
571    /// delta reads neither, and a storage kind without a history of
572    /// writes names nobody.
573    pub(in crate::engine) fn notice_for(
574        &self,
575        mem: &str,
576        from_head: &str,
577        to_head: &str,
578        changes: Vec<crate::ops::ChangeEnvelope>,
579        notes: Option<&[crate::ops::agent_notes::CommitNote]>,
580    ) -> crate::ops::MemChangedNotice {
581        let writes = if changes.len() <= crate::ops::changes::NOTICE_DETAILED_MAX {
582            match self.find_mount(mem).map(|m| &m.mount.storage) {
583                Ok(MountStorage::Folder { path }) => {
584                    crate::ops::changes::folder_newest_writes(path, from_head)
585                }
586                Ok(MountStorage::GitBranch { .. }) => {
587                    crate::ops::changes::newest_writes_from_notes(notes.unwrap_or_default())
588                }
589                _ => std::collections::BTreeMap::new(),
590            }
591        } else {
592            std::collections::BTreeMap::new()
593        };
594        crate::ops::MemChangedNotice::from_delta_with_writes(
595            mem.to_string(),
596            from_head.to_string(),
597            to_head.to_string(),
598            changes,
599            &writes,
600        )
601    }
602
603    /// Per-entity events for `mem` between `since` and the backend's
604    /// current state.
605    ///
606    /// 1. Resolves the mount (returns [`EngineError::UnknownMem`]
607    ///    on unknown mem).
608    /// 2. Validates `rename_similarity` against
609    ///    `[RENAME_SIMILARITY_MIN, RENAME_SIMILARITY_MAX]`. Out-of-range
610    ///    values refuse with [`EngineError::InvalidInput`] carrying
611    ///    `details.allowed_range` and `details.requested`. `None` falls
612    ///    back to [`crate::ops::RENAME_SIMILARITY_DEFAULT`].
613    /// 3. Dispatches on the mount's `MountStorage`:
614    ///    - Folder mounts synthesize from the JSONL changelog via
615    ///      [`crate::ops::folder_changes_since`].
616    ///    - Git-branch mounts call the registered
617    ///      [`GitBranchOps::changes_since`] hook (real tree-diff with
618    ///      rename detection); missing hook = git-branch ops not wired
619    ///      and the report comes back empty. The cursor is the empty
620    ///      tree or a commit of the mem's own history (its branch tip
621    ///      or an ancestor), given as a hash, as the mem's branch or as
622    ///      `HEAD`, with `~n` and `^n` parent steps. A cursor anchored
623    ///      anywhere else (another mem's branch or commit in the same
624    ///      git directory, a history that was replaced since) is
625    ///      refused `INVALID_CURSOR` exactly as a cursor that names
626    ///      nothing is, so a workspace learns nothing of mems it does
627    ///      not mount.
628    ///    - Archive mounts return an empty report.
629    /// 4. Enriches each envelope's `title` / `entity_type` from the
630    ///    in-memory store (best-effort — `Removed` envelopes always
631    ///    leave both `None`; missing-from-store entities also leave
632    ///    them `None`).
633    /// 5. Returns [`crate::ops::ChangesReport`] with `mem`,
634    ///    `since` (echoed), `head` (backend-resolved current
635    ///    cursor), enriched `changes`, and any clamping warnings.
636    pub fn changes_since(
637        &self,
638        mem: &str,
639        since: &str,
640        rename_similarity: Option<f32>,
641    ) -> Result<crate::ops::ChangesReport, EngineError> {
642        let m = self.find_mount(mem)?;
643
644        // Reject out-of-range `rename_similarity` early so CLI and MCP
645        // share one refusal surface.
646        // The prior clamp+warn shape silently accepted nonsense values
647        // (e.g. 1.5 ≡ 1.0); typed refusal gives the agent a recoverable
648        // signal.
649        if let Some(v) = rename_similarity
650            && !(crate::ops::RENAME_SIMILARITY_MIN..=crate::ops::RENAME_SIMILARITY_MAX).contains(&v)
651        {
652            return Err(EngineError::RenameSimilarityOutOfRange {
653                requested: v,
654                allowed_min: crate::ops::RENAME_SIMILARITY_MIN,
655                allowed_max: crate::ops::RENAME_SIMILARITY_MAX,
656            });
657        }
658        let clamped = rename_similarity.unwrap_or(crate::ops::RENAME_SIMILARITY_DEFAULT);
659
660        // The folder replay pairs a rename row with the id that vanished
661        // for it only over a loaded store: a deferred mount would read
662        // every id as vanished.
663        let store_lookup = |id: &crate::EntityId| -> Option<String> {
664            let e = self.store.get(id)?;
665            if e.stub {
666                return None;
667            }
668            Some(
669                e.metadata
670                    .get("created_date")
671                    .map(|v| v.to_frontmatter_string())
672                    .unwrap_or_default(),
673            )
674        };
675        let store_ref: Option<crate::ops::StoreLookup<'_>> = if m.deferred {
676            None
677        } else {
678            Some(&store_lookup)
679        };
680        let backend_changes = match &m.mount.storage {
681            MountStorage::Folder { path } => {
682                match crate::ops::folder_changes_since_within(
683                    path,
684                    mem,
685                    since,
686                    store_ref,
687                    self.settings.mutations.write_lock_timeout(),
688                ) {
689                    Ok(c) => c,
690                    // A commit of the mem is decided and not applied, and
691                    // its writer kept the lock past the workspace's
692                    // deadline: the mem's own typed condition, named
693                    // with the mem.
694                    Err(BackendError::CommitNotApplied { detail }) => {
695                        return Err(EngineError::CommitNotApplied {
696                            mem: mem.to_string(),
697                            detail,
698                        });
699                    }
700                    // Lift the backend's typed bad-`since` marker, parallel
701                    // to the git arm's COMMIT_NOT_FOUND lift below: the
702                    // folder cursor is a timestamp, and anything else —
703                    // a mutation's `write_id` above all — refuses instead
704                    // of silently replaying the whole history.
705                    Err(BackendError::Other(msg)) if msg.starts_with("INVALID_TS_CURSOR:") => {
706                        let since = msg
707                            .strip_prefix("INVALID_TS_CURSOR:")
708                            .unwrap_or_default()
709                            .to_string();
710                        return Err(EngineError::InvalidTimestampCursor {
711                            mem: mem.to_string(),
712                            since,
713                        });
714                    }
715                    Err(e) => return Err(EngineError::Backend(e)),
716                }
717            }
718            MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
719                Some(hook) => match (hook.changes_since)(gitdir, branch, mem, since, clamped) {
720                    Ok(c) => c,
721                    // Lift the backend's typed bad-`since` marker to a typed
722                    // engine error carrying the untruncated SHA, parallel
723                    // to the UNKNOWN_REMOTE / LOCAL_DIVERGENCE prefixes.
724                    Err(BackendError::Other(msg)) if msg.starts_with("COMMIT_NOT_FOUND:") => {
725                        let since = msg
726                            .strip_prefix("COMMIT_NOT_FOUND:")
727                            .unwrap_or_default()
728                            .to_string();
729                        return Err(EngineError::InvalidChangesCursor {
730                            mem: mem.to_string(),
731                            since,
732                        });
733                    }
734                    Err(e) => return Err(EngineError::Backend(e)),
735                },
736                None => crate::ops::BackendChanges::empty_at(since),
737            },
738            // Archive is sealed; the in-memory backend keeps a
739            // provenance log but no cursor-addressable change history,
740            // so both yield no backend-derived changes here (the live
741            // playground stream rides the engine's event broadcast, not
742            // this path).
743            MountStorage::Archive { .. } | MountStorage::InMemory => {
744                crate::ops::BackendChanges::empty_at(since)
745            }
746        };
747
748        // Enrich each id-only envelope from the engine's store.
749        // `Removed` always leaves title / entity_type None — the
750        // entity is gone by definition; the post-reload store does
751        // not have it. Other variants populate when the lookup
752        // succeeds; missing ids stay None.
753        let enriched: Vec<crate::ops::ChangeEnvelope> = backend_changes
754            .changes
755            .into_iter()
756            .map(|env| match env {
757                crate::ops::ChangeEnvelope::Added { id, .. } => {
758                    let (title, entity_type) = lookup_title_and_type(&self.store, &id);
759                    crate::ops::ChangeEnvelope::Added {
760                        id,
761                        title,
762                        entity_type,
763                    }
764                }
765                crate::ops::ChangeEnvelope::Updated { id, .. } => {
766                    let (title, entity_type) = lookup_title_and_type(&self.store, &id);
767                    crate::ops::ChangeEnvelope::Updated {
768                        id,
769                        title,
770                        entity_type,
771                    }
772                }
773                crate::ops::ChangeEnvelope::Removed { id, .. } => {
774                    crate::ops::ChangeEnvelope::Removed {
775                        id,
776                        title: None,
777                        entity_type: None,
778                    }
779                }
780                crate::ops::ChangeEnvelope::Renamed { from_id, to_id, .. } => {
781                    let (title, entity_type) = lookup_title_and_type(&self.store, &to_id);
782                    crate::ops::ChangeEnvelope::Renamed {
783                        from_id,
784                        to_id,
785                        title,
786                        entity_type,
787                    }
788                }
789            })
790            .collect();
791
792        // Out-of-range `rename_similarity` is now a hard refusal (see
793        // early-return above); the response carries no clamping warning.
794        let warnings: Vec<crate::ops::WarningHint> = Vec::new();
795
796        // The backend populates
797        // notes + memstead_ref on every git-branch call (folder + archive
798        // backends leave them empty / None). Surface them
799        // unconditionally; the MCP `include_notes` parameter becomes
800        // a renderer-side filter rather than a separate engine call.
801        let notes = if backend_changes.notes.is_empty() && backend_changes.memstead_ref.is_none() {
802            None
803        } else {
804            Some(backend_changes.notes)
805        };
806        Ok(crate::ops::ChangesReport {
807            mem: mem.to_string(),
808            since: backend_changes.since,
809            head: backend_changes.head,
810            changes: enriched,
811            warnings,
812            notes,
813            memstead_ref: backend_changes.memstead_ref,
814        })
815    }
816
817    /// Fetch updates from `remote` into the workspace's mem-repo.
818    /// Advances remote-tracking refs only; the local branch pointer
819    /// is not moved.
820    ///
821    /// `refspecs` is forwarded verbatim to `git fetch`. An empty list
822    /// uses the remote's configured defaults.
823    ///
824    /// Refusal codes: `UNKNOWN_MEM`, `UNKNOWN_REMOTE`,
825    /// `INVALID_INPUT` (folder / archive mounts).
826    ///
827    /// V1 atomicity: schema-validation quarantine for
828    /// fetched commits is not yet wired. The remote-tracking refs
829    /// advance unconditionally on a successful fetch; downstream
830    /// schema validation runs on read via the engine's existing
831    /// reload pipeline.
832    pub fn fetch(
833        &self,
834        mem: &str,
835        remote: &str,
836        refspecs: &[String],
837    ) -> Result<crate::ops::FetchOutcome, EngineError> {
838        // A fetch moves remote-tracking refs only. A refspec whose
839        // destination is a local branch would move a mem's branch or the
840        // schema ref with no fast-forward test and no schema gate; the
841        // routes that move local branches are `pull` and `pull --all`.
842        // The destination is admitted by allowlist (`refs/remotes/`, in
843        // the exact spelling), never by denying `refs/heads/`: on a
844        // case-insensitive filesystem `refs/HEADS/x` is the same file.
845        for spec in refspecs {
846            if spec.starts_with('-') {
847                return Err(EngineError::InvalidInput(format!(
848                    "refspec `{spec}` starts with '-'; a refspec is never a git option"
849                )));
850            }
851            let spec_body = spec.trim_start_matches('+');
852            if spec_body.starts_with('^') {
853                continue;
854            }
855            if let Some((_, dst)) = spec_body.split_once(':')
856                && !dst.is_empty()
857                && !dst.starts_with("refs/remotes/")
858            {
859                return Err(EngineError::InvalidInput(format!(
860                    "refspec `{spec}` writes outside the remote-tracking refs (`{dst}`); a fetch \
861                     only updates `refs/remotes/<remote>/…` — move local branches with \
862                     `memstead pull <mem>` or `memstead pull --all`"
863                )));
864            }
865        }
866        let m = self.find_mount(mem)?;
867        match &m.mount.storage {
868            MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
869                Err(EngineError::NotGitBacked {
870                    mem: Some(mem.to_string()),
871                    operation: "memstead_fetch".to_string(),
872                })
873            }
874            MountStorage::GitBranch { gitdir, .. } => match self.git_branch_ops.as_ref() {
875                Some(hook) => {
876                    let mut outcome =
877                        (hook.fetch)(gitdir, remote, refspecs).map_err(|e| match e {
878                            other if EngineError::is_remote_marker(&other) => {
879                                EngineError::from_transport(other)
880                            }
881                            other => EngineError::Backend(other),
882                        })?;
883                    // The mem's check-ledger rows travel with it: the
884                    // remote's transport ref, unioned into the local
885                    // ledger (engine::checks_transport).
886                    let merged = self.import_checks(hook, gitdir, remote, &[mem])?;
887                    outcome.checks_imported = merged.appended;
888                    outcome.checks_refused = merged.refused;
889                    Ok(outcome)
890                }
891                None => Err(EngineError::Backend(BackendError::Other(
892                    "git-branch fetch hook not installed (git-branch ops not wired)".to_string(),
893                ))),
894            },
895        }
896    }
897
898    /// Pull updates from `remote` into the named mem's branch.
899    /// Fetches into the remote-tracking ref, runs a pre-merge schema
900    /// validation pass against the prospective state, then
901    /// fast-forwards the local branch. Refuses with
902    /// `LOCAL_DIVERGENCE` for diverged local branches and with
903    /// `SCHEMA_VIOLATION_IN_FETCH` when the prospective state fails
904    /// schema validation — in both refusal cases the local branch
905    /// pointer is untouched (the underlying fetch has updated
906    /// `refs/remotes/*` but the engine has not promoted the new
907    /// state).
908    pub fn pull(
909        &mut self,
910        mem: &str,
911        remote: &str,
912    ) -> Result<crate::ops::PullOutcome, EngineError> {
913        // A ref move waits for a write in progress in any mem: a guard
914        // elsewhere may have read a reference the move takes away. The
915        // subject itself may be unreadable (a pull is how it is repaired).
916        let (_write_lock, _) = self.lock_workspace_for_mem_operation(mem)?;
917        let mount_idx = self
918            .mounts
919            .iter()
920            .position(|m| m.mount.mem == mem)
921            .ok_or_else(|| self.unknown_mem_error(mem))?;
922        let (gitdir, branch) = match &self.mounts[mount_idx].mount.storage {
923            MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
924                return Err(EngineError::NotGitBacked {
925                    mem: Some(mem.to_string()),
926                    operation: "memstead_pull".to_string(),
927                });
928            }
929            MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
930        };
931
932        // Run the fetch step alone first so we can validate the
933        // prospective state against the schema before letting the
934        // pull's fast-forward land. Errors map to the typed surface
935        // just like a standalone `memstead_fetch` call.
936        let hook = self.git_branch_ops.ok_or_else(|| {
937            EngineError::Backend(BackendError::Other(
938                "git-branch pull hook not installed (git-branch ops not wired)".to_string(),
939            ))
940        })?;
941        (hook.fetch)(&gitdir, remote, &[]).map_err(|e| match e {
942            other if EngineError::is_remote_marker(&other) => EngineError::from_transport(other),
943            other => EngineError::Backend(other),
944        })?;
945
946        // Pre-merge schema validation. The remote-tracking ref now
947        // points at the fetched tip; we walk it, parse every `.md`
948        // blob against the mem's pinned schema, and refuse the
949        // pull if any parse fails. The local branch pointer is still
950        // unchanged at this point — the refusal is fully atomic.
951        // The remote-tracking ref follows the mount's declared
952        // branch, never the mem name — the two differ on namespaced
953        // mounts.
954        let remote_ref = format!(
955            "refs/remotes/{remote}/{}",
956            crate::workspace::branch_short_name(&branch)
957        );
958        self.validate_ref_against_schema(&hook, &gitdir, mem, &remote_ref)?;
959
960        // Run the underlying pull (re-runs the fetch via git CLI, but
961        // that's a no-op cache-wise and keeps the fast-forward logic
962        // co-located with the rest of the transport implementation).
963        let mut outcome = (hook.pull)(&gitdir, remote, &branch, mem).map_err(|e| match e {
964            other if EngineError::is_remote_marker(&other) => EngineError::from_transport(other),
965            BackendError::Other(msg) if msg.starts_with("LOCAL_DIVERGENCE:") => {
966                let payload = msg.trim_start_matches("LOCAL_DIVERGENCE:");
967                let mut parts = payload.splitn(2, ':');
968                let v = parts.next().unwrap_or(mem).to_string();
969                let remote_ref = parts.next().unwrap_or("refs/remotes/?/?").to_string();
970                EngineError::LocalDivergence { mem: v, remote_ref }
971            }
972            other => EngineError::Backend(other),
973        })?;
974        // The mem's check-ledger rows travel with it (engine::checks_transport).
975        let merged = self.import_checks(&hook, &gitdir, remote, &[mem])?;
976        outcome.checks_imported = merged.appended;
977        outcome.checks_refused = merged.refused;
978
979        // Rewind cached head, reload the store so it serves the pulled
980        // state before this call returns (as `pull_all` does; a
981        // long-lived engine used to serve the old content until its
982        // next stale probe), then emit the change event.
983        if outcome.previous_sha != outcome.new_sha {
984            if let Err(e) = self.adopt_moved_head(mount_idx, mem, &outcome.new_sha) {
985                outcome.notices.push(format!(
986                    "mem `{mem}` was pulled but did not reload in this process: {e}"
987                ));
988            }
989            let event = crate::engine::events::MemChangedEvent {
990                mem: mem.to_string(),
991                head: outcome.new_sha.clone(),
992                previous: outcome.previous_sha.clone(),
993                n_commits: 1,
994            };
995            self.emit_mem_changed(&event);
996        }
997        Ok(outcome)
998    }
999
1000    /// Push the named mem's branch to `remote`. Runs a pre-push
1001    /// schema validation pass against the local branch tree; refuses
1002    /// with `LOCAL_INVALID_STATE` when the local state fails schema
1003    /// validation (the remote is not contacted in that case). Refuses
1004    /// with `NON_FAST_FORWARD` when the push is not a fast-forward
1005    /// and `force: false`; with `force: true` runs a
1006    /// `--force-with-lease` push instead.
1007    pub fn push(
1008        &self,
1009        mem: &str,
1010        remote: &str,
1011        force: bool,
1012    ) -> Result<crate::ops::PushOutcome, EngineError> {
1013        let m = self.find_mount(mem)?;
1014        let (gitdir, branch) = match &m.mount.storage {
1015            MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
1016                return Err(EngineError::NotGitBacked {
1017                    mem: Some(mem.to_string()),
1018                    operation: "memstead_push".to_string(),
1019                });
1020            }
1021            MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
1022        };
1023        let hook = self.git_branch_ops.ok_or_else(|| {
1024            EngineError::Backend(BackendError::Other(
1025                "git-branch push hook not installed (git-branch ops not wired)".to_string(),
1026            ))
1027        })?;
1028
1029        // Pre-push schema validation: walk the local branch tree (the
1030        // mount's declared branch, never a ref derived from the mem
1031        // name), run the mem's pinned schema over every `.md` blob.
1032        // Any parse failure refuses the push with
1033        // `LOCAL_INVALID_STATE` — the remote is not contacted. A gate
1034        // that cannot run (the ref unresolvable, the tree unreadable)
1035        // refuses too: a validation that did not happen must never
1036        // read as a pass.
1037        let local_ref = crate::workspace::branch_full_ref(&branch);
1038        match self.validate_ref_against_schema(&hook, &gitdir, mem, &local_ref) {
1039            Ok(()) => {}
1040            Err(EngineError::SchemaViolationInFetch { violations, .. }) => {
1041                return Err(EngineError::LocalInvalidState {
1042                    mem: mem.to_string(),
1043                    remote: remote.to_string(),
1044                    detail: format!(
1045                        "{} violation(s) in local branch: {}",
1046                        violations.len(),
1047                        violations.join("; "),
1048                    ),
1049                });
1050            }
1051            Err(EngineError::UnknownRef(raw)) => {
1052                // Names the declared branch the gate looked for, so
1053                // the reader sees what was resolved, not an invented
1054                // ref.
1055                return Err(EngineError::UnknownRef(raw));
1056            }
1057            Err(other) => {
1058                return Err(EngineError::Backend(BackendError::Other(format!(
1059                    "pre-push schema validation could not run for mem '{mem}' \
1060                     (declared branch `{local_ref}`): {other}",
1061                ))));
1062            }
1063        }
1064
1065        let mut outcome =
1066            (hook.push)(&gitdir, remote, &branch, mem, force).map_err(|e| match e {
1067                other if EngineError::is_remote_marker(&other) => {
1068                    EngineError::from_transport(other)
1069                }
1070                BackendError::Other(msg) if msg.starts_with("NON_FAST_FORWARD:") => {
1071                    let payload = msg.trim_start_matches("NON_FAST_FORWARD:");
1072                    let mut parts = payload.splitn(2, ':');
1073                    let v = parts.next().unwrap_or(mem).to_string();
1074                    let r = parts.next().unwrap_or(remote).to_string();
1075                    EngineError::NonFastForward { mem: v, remote: r }
1076                }
1077                BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
1078                    EngineError::UnknownRef(
1079                        msg.trim_start_matches("UNKNOWN_REF:").trim().to_string(),
1080                    )
1081                }
1082                other => EngineError::Backend(other),
1083            })?;
1084        // The mem's check-ledger rows follow its branch: published on
1085        // the transport ref and pushed beside it (engine::checks_transport).
1086        // The branch is on the remote by now, so a failure here names
1087        // that, and a rerun publishes the rows alone.
1088        let (published, refused) = self
1089            .publish_checks(&hook, &gitdir, remote, &[mem])
1090            .map_err(|e| {
1091                EngineError::Mem(format!(
1092                    "the branch of mem '{mem}' was pushed; its check-ledger rows were not \
1093                     ({}); run the push again to publish them",
1094                    e.prose_render()
1095                ))
1096            })?;
1097        outcome.checks_published = published;
1098        outcome.checks_refused = refused;
1099        Ok(outcome)
1100    }
1101
1102    /// `memstead status --remote`: every mounted git-branch mem and the
1103    /// schemas ref compared against `remote` by one read-only
1104    /// `ls-remote` per gitdir, classified in sync / local-ahead / behind
1105    /// / forked / unfetched (the remote head is not in the local object
1106    /// store, so behind or forked, which a fetch tells) / missing locally,
1107    /// plus the remote's branches nothing mounts (a notice, whether or
1108    /// not a local ref of that name exists) and the mounted branches the
1109    /// remote lacks (a notice). Moves no ref and never refuses: no git-branch mount, no
1110    /// hook (git-branch ops not wired), no remote configured or one that cannot be
1111    /// reached each become a notice and the outcome stands as not stale,
1112    /// so a network blip never blocks a session. The mount table the
1113    /// classification reads is this engine's own, so a remote branch with
1114    /// no mount is a leftover of a retired or re-homed mem, never
1115    /// staleness; the reconcile itself stays `fetch` and `pull`.
1116    pub fn remote_status(&self, remote: &str) -> crate::ops::RemoteStatusOutcome {
1117        use crate::ops::{RemoteRefState, RemoteRefStatus, RemoteStatusOutcome};
1118
1119        let mut outcome = RemoteStatusOutcome {
1120            remote: remote.to_string(),
1121            ..Default::default()
1122        };
1123        let mut gitdirs: Vec<std::path::PathBuf> = Vec::new();
1124        for m in &self.mounts {
1125            if let MountStorage::GitBranch { gitdir, .. } = &m.mount.storage
1126                && !gitdirs.contains(gitdir)
1127            {
1128                gitdirs.push(gitdir.clone());
1129            }
1130        }
1131        if gitdirs.is_empty() {
1132            outcome.notices.push(
1133                "no git-branch mem is mounted, so there is no remote to compare against"
1134                    .to_string(),
1135            );
1136            return outcome;
1137        }
1138        let Some(hook) = self.git_branch_ops.as_ref() else {
1139            outcome.notices.push(
1140                "git-branch hooks not installed (git-branch ops not wired): the remote was not compared"
1141                    .to_string(),
1142            );
1143            return outcome;
1144        };
1145
1146        let memstead_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
1147        let checks_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_CHECKS_REF_BRANCH);
1148        for gitdir in &gitdirs {
1149            let remote_refs: std::collections::BTreeMap<String, String> =
1150                match (hook.ls_remote)(gitdir, remote) {
1151                    Ok(v) => v.into_iter().collect(),
1152                    Err(e) if EngineError::is_remote_marker(&e) => {
1153                        outcome.notices.push(format!(
1154                            "{} (from {}): the comparison did not run (fail open)",
1155                            EngineError::from_transport(e),
1156                            gitdir.display()
1157                        ));
1158                        continue;
1159                    }
1160                    Err(e) => {
1161                        outcome.notices.push(format!(
1162                            "remote `{remote}` could not be read from {}: {e} (fail open)",
1163                            gitdir.display()
1164                        ));
1165                        continue;
1166                    }
1167                };
1168            // The branches this workspace mounts from this gitdir, by ref.
1169            let mut mounted: std::collections::BTreeMap<String, String> =
1170                std::collections::BTreeMap::new();
1171            for m in &self.mounts {
1172                if let MountStorage::GitBranch { gitdir: g, branch } = &m.mount.storage
1173                    && g == gitdir
1174                {
1175                    mounted.insert(
1176                        crate::workspace::branch_full_ref(branch),
1177                        m.mount.mem.clone(),
1178                    );
1179                }
1180            }
1181            let local = |ref_name: &str| -> Option<String> {
1182                (hook.resolve_ref)(gitdir, ref_name).ok().flatten()
1183            };
1184            // The ancestry verdict for a tracked ref whose heads differ.
1185            // A remote head this clone has never fetched is not in the
1186            // local object store, so neither direction can be tested:
1187            // that is `Unfetched`, never a guessed `Forked`.
1188            let compare = |local_sha: &str, remote_sha: &str| -> RemoteRefState {
1189                match (hook.is_ancestor)(gitdir, remote_sha, local_sha) {
1190                    Ok(true) => RemoteRefState::LocalAhead,
1191                    Ok(false) => match (hook.is_ancestor)(gitdir, local_sha, remote_sha) {
1192                        Ok(true) => RemoteRefState::Behind,
1193                        Ok(false) => RemoteRefState::Forked,
1194                        Err(_) => RemoteRefState::Unfetched,
1195                    },
1196                    Err(_) => RemoteRefState::Unfetched,
1197                }
1198            };
1199
1200            for (ref_name, remote_sha) in &remote_refs {
1201                // The check-ledger transport ref is derived from the
1202                // workspace ledger before every publish and unioned on
1203                // every fetch: it has no ahead or behind to report.
1204                if *ref_name == checks_ref {
1205                    continue;
1206                }
1207                let schemas_ref = *ref_name == memstead_ref;
1208                let mem = mounted.get(ref_name).cloned();
1209                let tracked = schemas_ref || mem.is_some();
1210                let local_sha = local(ref_name);
1211                // Mount first: a branch nothing mounts is not graph state,
1212                // whatever a local ref of that name says, so it can never
1213                // be staleness.
1214                let state = match (&local_sha, tracked) {
1215                    (_, false) => RemoteRefState::UnmountedRemote,
1216                    (None, true) => RemoteRefState::MissingLocal,
1217                    (Some(l), true) if l == remote_sha => RemoteRefState::InSync,
1218                    (Some(l), true) => compare(l, remote_sha),
1219                };
1220                outcome.refs.push(RemoteRefStatus {
1221                    ref_name: ref_name.clone(),
1222                    mem,
1223                    schemas_ref,
1224                    state,
1225                    remote_sha: Some(remote_sha.clone()),
1226                    local_sha,
1227                });
1228            }
1229            // Tracked refs the remote lacks: every mounted branch, and the
1230            // schemas ref when this clone carries one. Never pushed, a
1231            // notice.
1232            let mut tracked_only: Vec<(String, Option<String>, bool)> = mounted
1233                .iter()
1234                .map(|(r, m)| (r.clone(), Some(m.clone()), false))
1235                .collect();
1236            if local(&memstead_ref).is_some() {
1237                tracked_only.push((memstead_ref.clone(), None, true));
1238            }
1239            for (ref_name, mem, schemas_ref) in tracked_only {
1240                if remote_refs.contains_key(&ref_name) {
1241                    continue;
1242                }
1243                outcome.refs.push(RemoteRefStatus {
1244                    local_sha: local(&ref_name),
1245                    ref_name,
1246                    mem,
1247                    schemas_ref,
1248                    state: RemoteRefState::NotOnRemote,
1249                    remote_sha: None,
1250                });
1251            }
1252        }
1253        outcome.refs.sort_by(|a, b| a.ref_name.cmp(&b.ref_name));
1254        for r in &outcome.refs {
1255            *outcome
1256                .counts
1257                .entry(r.state.as_wire().to_string())
1258                .or_default() += 1;
1259        }
1260        outcome.stale = outcome.refs.iter().any(|r| r.state.is_stale());
1261        outcome
1262    }
1263
1264    /// Push every mounted git-branch mem's declared branch, plus the
1265    /// `__MEMSTEAD` ref of every mem-repo those mounts share, to
1266    /// `remote` — fast-forward only, there is no force variant. One
1267    /// `ls-remote` per mem-repo decides which refs lag; a ref whose
1268    /// local and remote SHA agree is reported `in_sync` and never
1269    /// sent. Each lagging mem branch goes through [`Self::push`]
1270    /// (the pre-push schema gate included); `__MEMSTEAD` goes through
1271    /// the same transport seam with no schema gate, it IS the
1272    /// schemas. A refusal on one ref lands in `refused` with its
1273    /// typed code and the run continues with the next ref — the
1274    /// caller decides the exit status from the outcome. Folder,
1275    /// archive and in-memory mounts have no branch and are skipped.
1276    /// Only a remote that cannot be listed at all (`UNKNOWN_REMOTE`)
1277    /// fails the run as a whole.
1278    pub fn push_all(&self, remote: &str) -> Result<crate::ops::PushAllOutcome, EngineError> {
1279        use crate::ops::{PushAllOutcome, PushedRef, RefusedRef};
1280
1281        let hook = self.git_branch_ops.ok_or_else(|| {
1282            EngineError::Backend(BackendError::Other(
1283                "git-branch push hook not installed (git-branch ops not wired)".to_string(),
1284            ))
1285        })?;
1286
1287        // Mem-repos in mount order, each once; a workspace may spread
1288        // its mounts over more than one gitdir.
1289        let mut gitdirs: Vec<std::path::PathBuf> = Vec::new();
1290        for m in &self.mounts {
1291            if let MountStorage::GitBranch { gitdir, .. } = &m.mount.storage
1292                && !gitdirs.contains(gitdir)
1293            {
1294                gitdirs.push(gitdir.clone());
1295            }
1296        }
1297
1298        let mut outcome = PushAllOutcome {
1299            remote: remote.to_string(),
1300            ..Default::default()
1301        };
1302
1303        for gitdir in &gitdirs {
1304            let remote_refs: std::collections::HashMap<String, String> =
1305                (hook.ls_remote)(gitdir, remote)
1306                    .map_err(|e| match e {
1307                        other if EngineError::is_remote_marker(&other) => {
1308                            EngineError::from_transport(other)
1309                        }
1310                        other => EngineError::Backend(other),
1311                    })?
1312                    .into_iter()
1313                    .collect();
1314
1315            // `__MEMSTEAD` first: schemas and mem configs before the
1316            // content that depends on them, so a clone that pulls
1317            // mid-run never sees a mem its schema ref lacks.
1318            let memstead_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
1319            let mut targets: Vec<(String, Option<String>, String)> = Vec::new();
1320            match (hook.resolve_ref)(gitdir, &memstead_ref) {
1321                Ok(Some(_)) => targets.push((
1322                    memstead_ref.clone(),
1323                    None,
1324                    crate::MEMSTEAD_REF_BRANCH.to_string(),
1325                )),
1326                Ok(None) => {}
1327                Err(e) => return Err(EngineError::Backend(e)),
1328            }
1329            for m in &self.mounts {
1330                if let MountStorage::GitBranch { gitdir: g, branch } = &m.mount.storage
1331                    && g == gitdir
1332                {
1333                    targets.push((
1334                        crate::workspace::branch_full_ref(branch),
1335                        Some(m.mount.mem.clone()),
1336                        branch.clone(),
1337                    ));
1338                }
1339            }
1340
1341            for (ref_name, mem, branch) in targets {
1342                let local_sha = match (hook.resolve_ref)(gitdir, &ref_name) {
1343                    Ok(Some(sha)) => sha,
1344                    Ok(None) => {
1345                        outcome.refused.push(RefusedRef {
1346                            ref_name: ref_name.clone(),
1347                            mem: mem.clone(),
1348                            code: "UNKNOWN_REF".to_string(),
1349                            message: format!(
1350                                "{ref_name} does not exist locally{}",
1351                                mem.as_deref()
1352                                    .map(|m| format!(" (mem `{m}`'s declared branch)"))
1353                                    .unwrap_or_default()
1354                            ),
1355                        });
1356                        continue;
1357                    }
1358                    Err(e) => return Err(EngineError::Backend(e)),
1359                };
1360                let previous_sha = remote_refs.get(&ref_name).cloned().unwrap_or_default();
1361                if previous_sha == local_sha {
1362                    outcome.in_sync.push(ref_name);
1363                    continue;
1364                }
1365                let result = match &mem {
1366                    Some(m) => self.push(m, remote, false).map(|o| o.new_sha),
1367                    None => (hook.push)(gitdir, remote, &branch, crate::MEMSTEAD_REF_BRANCH, false)
1368                        .map(|o| o.new_sha)
1369                        .map_err(|e| match e {
1370                            BackendError::Other(msg) if msg.starts_with("NON_FAST_FORWARD:") => {
1371                                EngineError::NonFastForward {
1372                                    mem: crate::MEMSTEAD_REF_BRANCH.to_string(),
1373                                    remote: remote.to_string(),
1374                                }
1375                            }
1376                            other if EngineError::is_remote_marker(&other) => {
1377                                EngineError::from_transport(other)
1378                            }
1379                            other => EngineError::Backend(other),
1380                        }),
1381                };
1382                match result {
1383                    Ok(new_sha) => outcome.pushed.push(PushedRef {
1384                        ref_name,
1385                        mem,
1386                        previous_sha,
1387                        new_sha,
1388                    }),
1389                    Err(e) => {
1390                        // The single-mem refusal names `force`, which
1391                        // `--all` does not offer; say what applies here.
1392                        let message = match &e {
1393                            EngineError::NonFastForward { .. } => format!(
1394                                "remote `{remote}` carries commits on {ref_name} this clone lacks; \
1395                                 fetch and pull {}, then push again",
1396                                mem.as_deref()
1397                                    .map(|m| format!("mem `{m}`"))
1398                                    .unwrap_or_else(|| "the schema ref".to_string()),
1399                            ),
1400                            other => other.to_string(),
1401                        };
1402                        outcome.refused.push(RefusedRef {
1403                            ref_name,
1404                            mem,
1405                            code: e.code().to_string(),
1406                            message,
1407                        })
1408                    }
1409                }
1410            }
1411            // The check-ledger rows of every mem mounted from this
1412            // gitdir ride the transport ref, published once per gitdir
1413            // after the branches (engine::checks_transport).
1414            let mems: Vec<String> = self
1415                .mounts
1416                .iter()
1417                .filter_map(|m| match &m.mount.storage {
1418                    MountStorage::GitBranch { gitdir: g, .. } if g == gitdir => {
1419                        Some(m.mount.mem.clone())
1420                    }
1421                    _ => None,
1422                })
1423                .collect();
1424            let mem_refs: Vec<&str> = mems.iter().map(String::as_str).collect();
1425            let checks_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_CHECKS_REF_BRANCH);
1426            let previous_sha = remote_refs.get(&checks_ref).cloned().unwrap_or_default();
1427            match self.publish_checks(&hook, gitdir, remote, &mem_refs) {
1428                Ok((Some(new_sha), refused)) => {
1429                    outcome.checks_refused.extend(refused);
1430                    outcome.pushed.push(PushedRef {
1431                        ref_name: checks_ref,
1432                        mem: None,
1433                        previous_sha,
1434                        new_sha,
1435                    })
1436                }
1437                Ok((None, refused)) => {
1438                    outcome.checks_refused.extend(refused);
1439                    if !previous_sha.is_empty() {
1440                        outcome.in_sync.push(checks_ref);
1441                    }
1442                }
1443                Err(e) => outcome.refused.push(RefusedRef {
1444                    ref_name: checks_ref,
1445                    mem: None,
1446                    code: e.code().to_string(),
1447                    message: e.prose_render(),
1448                }),
1449            }
1450        }
1451
1452        Ok(outcome)
1453    }
1454
1455    /// Bring every mem-repo the workspace mounts from to `remote`'s
1456    /// state, fast-forward only — the inverse of [`Self::push_all`].
1457    ///
1458    /// Order, per the dependency between the refs: one fetch per
1459    /// mem-repo; the `__MEMSTEAD` ref first (schemas and mem configs);
1460    /// then the schema catalogue is re-read, every mounted mem's pin is
1461    /// re-resolved from its (possibly new) config, and every mem
1462    /// quarantined `SCHEMA_NOT_FOUND` is re-attached; then each mounted
1463    /// mem's declared branch, validated against the schema it now
1464    /// resolves to exactly as [`Self::pull`] validates; last the check
1465    /// rows of the mounted mems. A ref absent locally is created; a ref
1466    /// whose local side has commits the remote lacks is never moved
1467    /// (`LOCAL_DIVERGENCE`), and the run continues with the next ref.
1468    /// A mem quarantined for any other reason is never pulled and is
1469    /// reported with its reason. Only a remote that cannot be fetched at
1470    /// all (`UNKNOWN_REMOTE`) fails the run as a whole.
1471    pub fn pull_all(&mut self, remote: &str) -> Result<crate::ops::PullAllOutcome, EngineError> {
1472        use crate::ops::{PullAllOutcome, PulledRef, QuarantinedAfterPull, RefusedRef};
1473
1474        // Every ref move waits for a write in progress; each mem is a
1475        // subject here, so an unreadable one does not refuse the pull
1476        // that repairs it.
1477        let subjects: Vec<String> = self
1478            .mounts
1479            .iter()
1480            .map(|m| m.mount.mem.clone())
1481            .chain(self.quarantined.iter().map(|q| q.mount.mem.clone()))
1482            .collect();
1483        let subject_refs: Vec<&str> = subjects.iter().map(String::as_str).collect();
1484        let (_write_lock, _) = self.lock_workspace_for_mems_operation(&subject_refs)?;
1485
1486        let hook = self.git_branch_ops.ok_or_else(|| {
1487            EngineError::Backend(BackendError::Other(
1488                "git-branch pull hook not installed (git-branch ops not wired)".to_string(),
1489            ))
1490        })?;
1491        let map_fetch_err = |e: BackendError| match e {
1492            other if EngineError::is_remote_marker(&other) => EngineError::from_transport(other),
1493            other => EngineError::Backend(other),
1494        };
1495
1496        // Mem-repos of mounted AND quarantined git-branch mems, each
1497        // once: a mem quarantined because its schema lives only on the
1498        // remote is exactly what this run repairs.
1499        let gitdirs = self.workspace_gitdirs();
1500
1501        let mut outcome = PullAllOutcome {
1502            remote: remote.to_string(),
1503            ..Default::default()
1504        };
1505
1506        // --- Leg 1: fetch, then the schema-and-config ref. ---
1507        // A mem-repo that cannot be fetched is refused by name and its
1508        // refs are skipped; the other mem-repos still move. Only when no
1509        // mem-repo could be fetched because the remote is unknown or
1510        // unreachable does the run fail as a whole.
1511        let mut failed: Vec<std::path::PathBuf> = Vec::new();
1512        let mut first_unknown_remote: Option<EngineError> = None;
1513        for gitdir in &gitdirs {
1514            if let Err(e) = (hook.fetch)(gitdir, remote, &[]).map_err(map_fetch_err) {
1515                outcome.refused.push(RefusedRef {
1516                    ref_name: gitdir.display().to_string(),
1517                    mem: None,
1518                    code: e.code().to_string(),
1519                    message: format!(
1520                        "the mem-repo at {} could not be fetched from `{remote}`; its refs \
1521                         were not touched: {e}",
1522                        gitdir.display()
1523                    ),
1524                });
1525                if matches!(e, EngineError::UnknownRemote(_)) && first_unknown_remote.is_none() {
1526                    first_unknown_remote = Some(e);
1527                }
1528                failed.push(gitdir.clone());
1529                continue;
1530            }
1531            let local_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
1532            let remote_ref = format!("refs/remotes/{remote}/{}", crate::MEMSTEAD_REF_BRANCH);
1533            // A local schema ref that is nothing but a bootstrap seed
1534            // carries no state, so adopting the backup's history in its
1535            // place loses nothing, whichever engine version seeded either.
1536            match Self::fast_forward_ref(&hook, gitdir, &local_ref, &remote_ref, true)? {
1537                FastForward::NotOnRemote => outcome.notices.push(format!(
1538                    "remote `{remote}` carries no schema-and-config ref for {}; \
1539                     the local one was left as it is",
1540                    gitdir.display()
1541                )),
1542                FastForward::InSync => outcome.in_sync.push(local_ref),
1543                FastForward::Moved { previous, new } => outcome.pulled.push(PulledRef {
1544                    ref_name: local_ref,
1545                    mem: None,
1546                    previous_sha: previous,
1547                    new_sha: new,
1548                }),
1549                FastForward::LocalAhead => outcome.local_ahead.push(local_ref),
1550                // Both clones moved the ref (each created a mem, say).
1551                // The ref holds files, one per mem and schema, so the two
1552                // histories merge path by path when no file changed on
1553                // both sides; a file both changed is a decision the merge
1554                // does not make, and nothing moves.
1555                FastForward::Diverged => {
1556                    match self.merge_config_ref(&hook, gitdir, &local_ref, &remote_ref, remote)? {
1557                        Ok(pulled) => outcome.pulled.push(pulled),
1558                        Err(Some(paths)) => outcome.refused.push(RefusedRef {
1559                            ref_name: local_ref,
1560                            mem: None,
1561                            code: "LOCAL_DIVERGENCE".to_string(),
1562                            message: format!(
1563                                "the local schema-and-config ref and remote `{remote}`'s both \
1564                                 changed {}; it was not moved. Settle those files on one clone \
1565                                 and push them (`memstead push --all`), then pull here",
1566                                paths
1567                                    .iter()
1568                                    .map(|p| format!("`{p}`"))
1569                                    .collect::<Vec<_>>()
1570                                    .join(", ")
1571                            ),
1572                        }),
1573                        Err(None) => outcome.refused.push(RefusedRef {
1574                            ref_name: local_ref,
1575                            mem: None,
1576                            code: "LOCAL_DIVERGENCE".to_string(),
1577                            message: format!(
1578                                "the local schema-and-config ref and remote `{remote}`'s share \
1579                                 no history, so there is nothing to merge from; it was not \
1580                                 moved. Push from this clone (`memstead push --all`) or \
1581                                 reconcile on the other clone first"
1582                            ),
1583                        }),
1584                    }
1585                }
1586            }
1587        }
1588
1589        if failed.len() == gitdirs.len()
1590            && let Some(e) = first_unknown_remote
1591        {
1592            return Err(e);
1593        }
1594        let usable: Vec<std::path::PathBuf> = gitdirs
1595            .iter()
1596            .filter(|g| !failed.contains(g))
1597            .cloned()
1598            .collect();
1599
1600        // --- Leg 2: schemas, pins and quarantines re-resolved. ---
1601        let mut refresh = crate::ops::FullRefreshReport::default();
1602        self.refresh_schema_sources(&mut refresh);
1603        let mut unresolved: std::collections::HashMap<String, EngineError> =
1604            std::collections::HashMap::new();
1605        let mounted_git: Vec<String> = self
1606            .mounts
1607            .iter()
1608            .filter(|m| matches!(m.mount.storage, MountStorage::GitBranch { .. }))
1609            .map(|m| m.mount.mem.clone())
1610            .collect();
1611        for mem in &mounted_git {
1612            if let Err(e) = self.rebind_schema_from_config(mem) {
1613                unresolved.insert(mem.clone(), e);
1614            }
1615        }
1616        let schema_quarantined: Vec<String> = self
1617            .quarantined
1618            .iter()
1619            .filter(|q| {
1620                q.reason_code == "SCHEMA_NOT_FOUND"
1621                    && matches!(q.mount.storage, MountStorage::GitBranch { .. })
1622            })
1623            .map(|q| q.mount.mem.clone())
1624            .collect();
1625        for mem in schema_quarantined {
1626            if self.reload_one_mem(&mem).is_ok() && self.quarantine_reason(&mem).is_none() {
1627                outcome.returned_to_service.push(mem);
1628            }
1629        }
1630
1631        // Mems on the remote that nothing here mounts: named with the
1632        // command that mounts them, never mounted by this run.
1633        let known: std::collections::HashSet<String> = self
1634            .mounts
1635            .iter()
1636            .map(|m| &m.mount.storage)
1637            .chain(self.quarantined.iter().map(|q| &q.mount.storage))
1638            .filter_map(|s| match s {
1639                MountStorage::GitBranch { branch, .. } => {
1640                    Some(crate::workspace::branch_full_ref(branch))
1641                }
1642                _ => None,
1643            })
1644            .collect();
1645        let schema_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
1646        for gitdir in &usable {
1647            let Ok(remote_refs) = (hook.ls_remote)(gitdir, remote) else {
1648                continue;
1649            };
1650            for (ref_name, _) in remote_refs {
1651                let Some(short) = ref_name.strip_prefix("refs/heads/") else {
1652                    continue;
1653                };
1654                if known.contains(&ref_name)
1655                    || short.starts_with(crate::MEMSTEAD_REF_BRANCH)
1656                    || short == "main"
1657                {
1658                    continue;
1659                }
1660                let Ok(Some(bytes)) = (hook.read_config_at_ref)(gitdir, &schema_ref, short) else {
1661                    continue;
1662                };
1663                let schema = serde_json::from_slice::<serde_json::Value>(&bytes)
1664                    .ok()
1665                    .and_then(|v| memstead_schema::config::parse_mem_config(&v).ok())
1666                    .and_then(|c| c.schema)
1667                    .map(|p| p.as_display());
1668                outcome
1669                    .unmounted_on_remote
1670                    .push(crate::ops::UnmountedRemoteMem {
1671                        branch: short.to_string(),
1672                        schema,
1673                    });
1674            }
1675        }
1676
1677        // --- Leg 3: every mounted mem's declared branch. ---
1678        let targets: Vec<(String, std::path::PathBuf, String)> = self
1679            .mounts
1680            .iter()
1681            .filter_map(|m| match &m.mount.storage {
1682                MountStorage::GitBranch { gitdir, branch } => {
1683                    Some((m.mount.mem.clone(), gitdir.clone(), branch.clone()))
1684                }
1685                _ => None,
1686            })
1687            .collect();
1688        for (mem, gitdir, branch) in targets {
1689            if failed.contains(&gitdir) {
1690                continue;
1691            }
1692            let local_ref = crate::workspace::branch_full_ref(&branch);
1693            if let Some(e) = unresolved.remove(&mem) {
1694                outcome.refused.push(RefusedRef {
1695                    ref_name: local_ref,
1696                    mem: Some(mem.clone()),
1697                    code: e.code().to_string(),
1698                    message: e.to_string(),
1699                });
1700                continue;
1701            }
1702            let remote_ref = format!(
1703                "refs/remotes/{remote}/{}",
1704                crate::workspace::branch_short_name(&branch)
1705            );
1706            let Some(remote_sha) =
1707                (hook.resolve_ref)(&gitdir, &remote_ref).map_err(EngineError::Backend)?
1708            else {
1709                outcome.notices.push(format!(
1710                    "remote `{remote}` does not carry {local_ref} (mem `{mem}`); \
1711                     the local branch was left as it is"
1712                ));
1713                continue;
1714            };
1715            let local_sha =
1716                (hook.resolve_ref)(&gitdir, &local_ref).map_err(EngineError::Backend)?;
1717            if local_sha.as_deref() == Some(remote_sha.as_str()) {
1718                outcome.in_sync.push(local_ref);
1719                continue;
1720            }
1721            if let Some(l) = &local_sha
1722                && (hook.is_ancestor)(&gitdir, &remote_sha, l).map_err(EngineError::Backend)?
1723            {
1724                outcome.local_ahead.push(local_ref);
1725                continue;
1726            }
1727            // The same whole-tree gate `pull` runs, against the schema
1728            // the mem resolves to now that the schema ref has arrived.
1729            if let Err(e) = self.validate_ref_against_schema(&hook, &gitdir, &mem, &remote_ref) {
1730                outcome.refused.push(RefusedRef {
1731                    ref_name: local_ref,
1732                    mem: Some(mem.clone()),
1733                    code: e.code().to_string(),
1734                    message: e.to_string(),
1735                });
1736                continue;
1737            }
1738            match Self::fast_forward_ref(&hook, &gitdir, &local_ref, &remote_ref, false)? {
1739                FastForward::Moved { previous, new } => {
1740                    // The store serves the pulled state before the run
1741                    // returns; a reload failure is reported, the ref
1742                    // move stands (the next operation reloads again).
1743                    if let Err(e) = self.reload_one_mem(&mem) {
1744                        outcome.notices.push(format!(
1745                            "mem `{mem}` was pulled but did not reload in this process: {e}"
1746                        ));
1747                    }
1748                    let event = crate::engine::events::MemChangedEvent {
1749                        mem: mem.clone(),
1750                        head: new.clone(),
1751                        previous: previous.clone(),
1752                        n_commits: 1,
1753                    };
1754                    self.emit_mem_changed(&event);
1755                    outcome.pulled.push(PulledRef {
1756                        ref_name: local_ref,
1757                        mem: Some(mem.clone()),
1758                        previous_sha: previous,
1759                        new_sha: new,
1760                    });
1761                }
1762                FastForward::InSync => outcome.in_sync.push(local_ref),
1763                FastForward::LocalAhead => outcome.local_ahead.push(local_ref),
1764                FastForward::NotOnRemote => {}
1765                FastForward::Diverged => outcome.refused.push(RefusedRef {
1766                    ref_name: local_ref.clone(),
1767                    mem: Some(mem.clone()),
1768                    code: "LOCAL_DIVERGENCE".to_string(),
1769                    message: EngineError::LocalDivergence {
1770                        mem: mem.clone(),
1771                        remote_ref,
1772                    }
1773                    .to_string(),
1774                }),
1775            }
1776        }
1777
1778        // --- Leg 4: the mounted mems' check rows, once per mem-repo. ---
1779        for gitdir in &usable {
1780            let mems: Vec<String> = self
1781                .mounts
1782                .iter()
1783                .filter_map(|m| match &m.mount.storage {
1784                    MountStorage::GitBranch { gitdir: g, .. } if g == gitdir => {
1785                        Some(m.mount.mem.clone())
1786                    }
1787                    _ => None,
1788                })
1789                .collect();
1790            if mems.is_empty() {
1791                continue;
1792            }
1793            let mem_refs: Vec<&str> = mems.iter().map(String::as_str).collect();
1794            let merged = self.import_checks(&hook, gitdir, remote, &mem_refs)?;
1795            outcome.checks_imported += merged.appended;
1796            outcome.checks_refused.extend(merged.refused);
1797        }
1798
1799        outcome.quarantined = self
1800            .quarantined
1801            .iter()
1802            .map(|q| QuarantinedAfterPull {
1803                mem: q.mount.mem.clone(),
1804                code: q.reason_code.clone(),
1805                message: q.reason_message.clone(),
1806            })
1807            .collect();
1808        Ok(outcome)
1809    }
1810
1811    /// The mem-repos this workspace keeps git-branch mems in, each once:
1812    /// those of the mounted mems, then those of the quarantined ones (a
1813    /// mem quarantined because its schema lives only on the remote is
1814    /// still in its mem-repo), and, when no mount names one, the
1815    /// workspace's own `mem-repo/` as `memstead mem-repo init` creates
1816    /// it, so a workspace with no mem yet can still be wired to a remote
1817    /// and restored from it.
1818    fn workspace_gitdirs(&self) -> Vec<std::path::PathBuf> {
1819        let mut gitdirs: Vec<std::path::PathBuf> = Vec::new();
1820        let storages = self
1821            .mounts
1822            .iter()
1823            .map(|m| &m.mount.storage)
1824            .chain(self.quarantined.iter().map(|q| &q.mount.storage));
1825        for storage in storages {
1826            if let MountStorage::GitBranch { gitdir, .. } = storage
1827                && !gitdirs.contains(gitdir)
1828            {
1829                gitdirs.push(gitdir.clone());
1830            }
1831        }
1832        if gitdirs.is_empty()
1833            && let Some(root) = self.workspace_root.as_ref()
1834        {
1835            let default = root.join("mem-repo").join(".git");
1836            if default.is_dir() {
1837                gitdirs.push(default);
1838            }
1839        }
1840        gitdirs
1841    }
1842
1843    /// Merge the remote's schema-and-config ref into the local one when
1844    /// their histories diverged and no file changed on both sides: a
1845    /// commit with both parents, the ref moved onto it compare-and-set
1846    /// against the local tip the merge was computed on. `Err` carries
1847    /// the files both sides changed; then nothing is written or moved.
1848    fn merge_config_ref(
1849        &self,
1850        hook: &crate::engine::GitBranchOps,
1851        gitdir: &std::path::Path,
1852        local_ref: &str,
1853        remote_ref: &str,
1854        remote: &str,
1855    ) -> Result<Result<crate::ops::PulledRef, Option<Vec<String>>>, EngineError> {
1856        let local = (hook.resolve_ref)(gitdir, local_ref)
1857            .map_err(EngineError::Backend)?
1858            .ok_or_else(|| {
1859                EngineError::Backend(BackendError::Other(format!("{local_ref} vanished")))
1860            })?;
1861        let theirs = (hook.resolve_ref)(gitdir, remote_ref)
1862            .map_err(EngineError::Backend)?
1863            .ok_or_else(|| {
1864                EngineError::Backend(BackendError::Other(format!("{remote_ref} vanished")))
1865            })?;
1866        let ctx = self.commit_context(Some("pull_all"), crate::vcs::Actor::Cli, None, None);
1867        let message = crate::vcs::format_commit_message(
1868            &format!("memstead: merge schema-and-config ref from {remote}"),
1869            &ctx,
1870        );
1871        match (hook.merge_disjoint)(gitdir, &local, &theirs, &message)
1872            .map_err(EngineError::Backend)?
1873        {
1874            crate::engine::DisjointMerge::Overlap { paths } => Ok(Err(Some(paths))),
1875            crate::engine::DisjointMerge::Unrelated => Ok(Err(None)),
1876            crate::engine::DisjointMerge::Merged { commit } => {
1877                (hook.update_ref)(
1878                    gitdir,
1879                    local_ref,
1880                    &commit,
1881                    crate::engine::RefPrevious::At(&local),
1882                )
1883                .map_err(EngineError::Backend)?;
1884                Ok(Ok(crate::ops::PulledRef {
1885                    ref_name: local_ref.to_string(),
1886                    mem: None,
1887                    previous_sha: local,
1888                    new_sha: commit,
1889                }))
1890            }
1891        }
1892    }
1893
1894    /// Fast-forward `local_ref` to what `remote_ref` points at, the
1895    /// ancestry tested first. A local ref that does not exist is
1896    /// created (a fast-forward from nothing).
1897    fn fast_forward_ref(
1898        hook: &crate::engine::GitBranchOps,
1899        gitdir: &std::path::Path,
1900        local_ref: &str,
1901        remote_ref: &str,
1902        replace_empty_seed: bool,
1903    ) -> Result<FastForward, EngineError> {
1904        let Some(remote_sha) =
1905            (hook.resolve_ref)(gitdir, remote_ref).map_err(EngineError::Backend)?
1906        else {
1907            return Ok(FastForward::NotOnRemote);
1908        };
1909        // The move is pinned to the local tip the decision was made on, so
1910        // a commit that lands in between fails the move instead of being
1911        // dropped from the branch. A lost race decides again on the new
1912        // tip, which then usually reads as local-ahead or diverged.
1913        let mut attempt = 0;
1914        loop {
1915            let local_sha = (hook.resolve_ref)(gitdir, local_ref).map_err(EngineError::Backend)?;
1916            if let Some(l) = &local_sha {
1917                if *l == remote_sha {
1918                    return Ok(FastForward::InSync);
1919                }
1920                let fast_forward =
1921                    (hook.is_ancestor)(gitdir, l, &remote_sha).map_err(EngineError::Backend)?;
1922                let local_ahead = !fast_forward
1923                    && (hook.is_ancestor)(gitdir, &remote_sha, l).map_err(EngineError::Backend)?;
1924                if local_ahead {
1925                    return Ok(FastForward::LocalAhead);
1926                }
1927                let replaceable_seed = !fast_forward
1928                    && replace_empty_seed
1929                    && (hook.is_empty_root)(gitdir, l).map_err(EngineError::Backend)?;
1930                if !fast_forward && !replaceable_seed {
1931                    return Ok(FastForward::Diverged);
1932                }
1933            }
1934            let previous = match &local_sha {
1935                Some(l) => crate::engine::RefPrevious::At(l),
1936                None => crate::engine::RefPrevious::Absent,
1937            };
1938            match (hook.update_ref)(gitdir, local_ref, &remote_sha, previous) {
1939                Ok(()) => {
1940                    return Ok(FastForward::Moved {
1941                        previous: local_sha.unwrap_or_default(),
1942                        new: remote_sha,
1943                    });
1944                }
1945                Err(e) => {
1946                    let now =
1947                        (hook.resolve_ref)(gitdir, local_ref).map_err(EngineError::Backend)?;
1948                    attempt += 1;
1949                    if now == local_sha || attempt == 3 {
1950                        return Err(EngineError::Backend(e));
1951                    }
1952                }
1953            }
1954        }
1955    }
1956
1957    /// Re-read a mounted mem's config and re-resolve its schema pin
1958    /// against the current catalogue, the boot resolver's order. Used
1959    /// after the schema-and-config ref moved: a pin another clone
1960    /// switched must govern what this engine validates next. A pin that
1961    /// no longer resolves leaves the mem's current schema in place and
1962    /// returns the typed refusal.
1963    fn rebind_schema_from_config(&mut self, mem: &str) -> Result<(), EngineError> {
1964        let Some(idx) = self.mounts.iter().position(|m| m.mount.mem == mem) else {
1965            return Ok(());
1966        };
1967        let mem_config = self.mounts[idx]
1968            .backend
1969            .read_mem_config()
1970            .ok()
1971            .flatten()
1972            .and_then(|bytes| {
1973                let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
1974                memstead_schema::config::parse_mem_config(&value).ok()
1975            });
1976        let Some(pin) = self.mounts[idx]
1977            .mount
1978            .migration_target
1979            .clone()
1980            .or_else(|| mem_config.as_ref().and_then(|c| c.schema.clone()))
1981            .or_else(|| self.mounts[idx].mount.schema.clone())
1982        else {
1983            return Ok(());
1984        };
1985        let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = self
1986            .workspace_schemas
1987            .iter()
1988            .cloned()
1989            .chain(self.builtin_schemas.iter().cloned())
1990            .collect();
1991        let schema = crate::engine::SchemaResolver::new(&catalogue)
1992            .resolve(&pin)
1993            .map_err(|sources| {
1994                EngineError::SchemaNotFound {
1995                    mem: mem.to_string(),
1996                    pin: pin.as_display(),
1997                    sources,
1998                    install_hint: None,
1999                }
2000                .with_schema_install_probe(self.workspace_root())
2001            })?;
2002        let unchanged = self
2003            .schemas
2004            .get(mem)
2005            .is_some_and(|current| current.id() == schema.id());
2006        if mem_config.is_some() {
2007            self.mounts[idx].mem_config = mem_config;
2008        }
2009        if !unchanged {
2010            self.schemas_insert(mem.to_string(), schema);
2011        }
2012        Ok(())
2013    }
2014
2015    /// Configure (or re-point) a named remote on the workspace's
2016    /// mem-repo, so `fetch` / `pull` / `push` have somewhere to go.
2017    /// Upsert semantics — safe to re-run with a new URL. The mem-repo
2018    /// is shared by every git-branch mount, so the op is
2019    /// workspace-level: any git-branch mount locates it; refuses
2020    /// `INVALID_INPUT` when the workspace has none.
2021    pub fn remote_add(
2022        &self,
2023        name: &str,
2024        url: &str,
2025    ) -> Result<crate::ops::RemoteAddOutcome, EngineError> {
2026        // Both values become git subprocess arguments — refuse shapes
2027        // that would parse as flags.
2028        if name.is_empty() || name.starts_with('-') || url.is_empty() || url.starts_with('-') {
2029            return Err(EngineError::InvalidInput(format!(
2030                "remote name and url must be non-empty and must not start with '-' \
2031                 (got name '{name}', url '{url}')",
2032            )));
2033        }
2034        let gitdir = self.workspace_gitdirs().into_iter().next().ok_or_else(|| {
2035            EngineError::InvalidInput(
2036                "no mem-repo in this workspace — `remote-add` requires a mem-repo workspace"
2037                    .to_string(),
2038            )
2039        })?;
2040        let hook = self.git_branch_ops.ok_or_else(|| {
2041            EngineError::Backend(BackendError::Other(
2042                "git-branch remote_add hook not installed (git-branch ops not wired)".to_string(),
2043            ))
2044        })?;
2045        (hook.remote_add)(&gitdir, name, url).map_err(EngineError::Backend)
2046    }
2047
2048    /// Pre-merge schema validation pass: walks every `.md` blob at
2049    /// `ref_name` and runs `parse_entries` with the mem's pinned
2050    /// schema. Returns `Ok(())` when the tree is schema-clean;
2051    /// returns `EngineError::SchemaViolationInFetch` with the list of
2052    /// per-entity violation messages otherwise. The validation is
2053    /// strict on parse-time errors — any `(path, error)` pair from
2054    /// `parse_entries` triggers a refusal.
2055    ///
2056    /// `ref_name` is the prospective state (a `refs/remotes/*` ref
2057    /// for pull, `refs/heads/*` for push). The engine layer maps the
2058    /// returned error into the surface code it needs
2059    /// (`SCHEMA_VIOLATION_IN_FETCH` for pull, `LOCAL_INVALID_STATE`
2060    /// for push).
2061    fn validate_ref_against_schema(
2062        &self,
2063        hook: &crate::engine::GitBranchOps,
2064        gitdir: &std::path::Path,
2065        mem: &str,
2066        ref_name: &str,
2067    ) -> Result<(), EngineError> {
2068        // The REF first, then the schema. A branch that does not exist is the
2069        // clearer answer, and asking for the schema first turned "that branch
2070        // is not there" into "the schema pin did not resolve", which is true
2071        // of a quarantined mem and tells the reader nothing about why their
2072        // push failed (04/05).
2073        let blobs = Self::read_ref_blobs(hook, gitdir, ref_name)?;
2074        let schema = self
2075            .schemas
2076            .get(mem)
2077            .ok_or_else(|| EngineError::SchemaNotFound {
2078                mem: mem.to_string(),
2079                pin: "<missing engine-side resolution>".to_string(),
2080                // Internal invariant breach (an already-resolved schema
2081                // absent from the per-mem map), not a source-resolution
2082                // failure — no per-source diagnostics apply.
2083                sources: Vec::new(),
2084                install_hint: None,
2085            })?
2086            .clone();
2087        Self::validate_blobs_against_schema(mem, ref_name, blobs, schema.as_ref())
2088    }
2089
2090    /// The same whole-tree validation `pull` runs before it moves a
2091    /// pointer, for a mem that is not mounted yet: the caller resolved
2092    /// the schema itself (a fork validates the fetched source tree
2093    /// against the source's pin before the mount exists). Refuses with
2094    /// `SCHEMA_VIOLATION_IN_FETCH`, the pull path's code.
2095    pub(crate) fn validate_ref_with_schema(
2096        hook: &crate::engine::GitBranchOps,
2097        gitdir: &std::path::Path,
2098        mem: &str,
2099        ref_name: &str,
2100        schema: &memstead_schema::Schema,
2101    ) -> Result<(), EngineError> {
2102        let blobs = Self::read_ref_blobs(hook, gitdir, ref_name)?;
2103        Self::validate_blobs_against_schema(mem, ref_name, blobs, schema)
2104    }
2105
2106    /// Every `.md` blob at `ref_name`; an absent ref is `UNKNOWN_REF`.
2107    fn read_ref_blobs(
2108        hook: &crate::engine::GitBranchOps,
2109        gitdir: &std::path::Path,
2110        ref_name: &str,
2111    ) -> Result<Vec<(String, String)>, EngineError> {
2112        (hook.read_tree)(gitdir, ref_name).map_err(|e| match e {
2113            BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
2114                EngineError::UnknownRef(msg.trim_start_matches("UNKNOWN_REF:").trim().to_string())
2115            }
2116            other => EngineError::Backend(other),
2117        })
2118    }
2119
2120    /// The permissive parse plus the strict per-entity pass over the
2121    /// blobs of one ref, against one schema.
2122    fn validate_blobs_against_schema(
2123        mem: &str,
2124        ref_name: &str,
2125        blobs: Vec<(String, String)>,
2126        schema: &memstead_schema::Schema,
2127    ) -> Result<(), EngineError> {
2128        let mut source_entries: Vec<crate::entity::source::SourceEntry> = Vec::new();
2129        for (rel_path, content) in blobs {
2130            source_entries.push(crate::entity::source::SourceEntry {
2131                relative_path: rel_path.clone(),
2132                source_path: std::path::PathBuf::from(rel_path),
2133                content,
2134            });
2135        }
2136
2137        // First pass: permissive parse via the engine's loader so we
2138        // can build Entity values for the strict validator. The
2139        // loader silently absorbs frontmatter / title / section
2140        // drift; the strict pass below is what catches it.
2141        let load_result =
2142            crate::entity::loader::parse_entries(source_entries.clone(), Vec::new(), mem, schema);
2143        let mut violations: Vec<String> = load_result
2144            .errors
2145            .iter()
2146            .map(|(path, msg)| format!("{}: {msg}", path.display()))
2147            .collect();
2148
2149        // Strict per-entity validator: enforces "looks like a mem
2150        // entity" invariants (frontmatter shape, title presence,
2151        // required sections, unknown sections, relationship syntax,
2152        // wiki-link shape) that the permissive loader doesn't refuse.
2153        // Re-runs against the same source bytes so unparseable
2154        // frontmatter surfaces here even when the loader's tolerant
2155        // path produces an Entity stub.
2156        let entities_by_path: std::collections::HashMap<String, &crate::entity::Entity> =
2157            load_result
2158                .entities
2159                .iter()
2160                .map(|p| (p.entity.file_path.clone(), &p.entity))
2161                .collect();
2162        for source in &source_entries {
2163            let Some(entity) = entities_by_path.get(&source.relative_path) else {
2164                continue;
2165            };
2166            let type_def = match schema.get_type(&entity.entity_type) {
2167                Some(t) => t,
2168                None => {
2169                    violations.push(format!(
2170                        "{}: unknown entity_type '{}' in schema",
2171                        source.relative_path, entity.entity_type,
2172                    ));
2173                    continue;
2174                }
2175            };
2176            if let Err(e) = crate::validator::strict::validate_strict(
2177                &source.content,
2178                entity,
2179                type_def.as_ref(),
2180                &source.relative_path,
2181            ) {
2182                violations.push(format!("{}: {e}", source.relative_path));
2183            }
2184        }
2185
2186        if violations.is_empty() {
2187            Ok(())
2188        } else {
2189            Err(EngineError::SchemaViolationInFetch {
2190                mem: mem.to_string(),
2191                ref_name: ref_name.to_string(),
2192                violations,
2193            })
2194        }
2195    }
2196
2197    /// Reset a mem's branch pointer to `target_sha`. The only
2198    /// engine surface that moves a branch pointer over existing
2199    /// commits — every other mutation appends. Refuses if any commit
2200    /// that would be discarded by the reset is already reachable from
2201    /// a `refs/remotes/*` ref (the engine's definition of "pushed").
2202    ///
2203    /// `target_sha` accepts anything `gix::rev_parse_single` admits:
2204    /// a SHA, an abbreviated SHA, a branch name, a tag. The branch
2205    /// itself (the mount's declared branch) must exist.
2206    ///
2207    /// Refusal codes:
2208    /// - [`EngineError::UnknownMem`] (`UNKNOWN_MEM`)
2209    /// - [`EngineError::UnknownRef`] (`UNKNOWN_REF`) — branch or
2210    ///   target ref does not resolve.
2211    /// - [`EngineError::PushedCommitsProtected`]
2212    ///   (`PUSHED_COMMITS_PROTECTED`) — at least one discarded commit
2213    ///   is pushed. The error carries the offending SHAs verbatim.
2214    /// - [`EngineError::InvalidInput`] (`INVALID_INPUT`) — mem is
2215    ///   folder / archive-backed (history rewriting only makes sense
2216    ///   for git-branch mounts).
2217    ///
2218    /// Emits a [`crate::engine::events::MemChangedEvent`] on
2219    /// success when the SHA actually changed; the reset's effect is
2220    /// observable through the same change-event surface every commit
2221    /// flows through. Engine's cached `last_known_head` for the
2222    /// affected mount is rewound to the new SHA so the next drift
2223    /// probe doesn't flag the reset as a sibling-writer surprise.
2224    pub fn branch_reset(
2225        &mut self,
2226        mem: &str,
2227        target_sha: &str,
2228        expected_head: Option<&str>,
2229    ) -> Result<crate::ops::BranchResetOutcome, EngineError> {
2230        // A branch move waits for a write in progress in any mem (a
2231        // delete elsewhere may have read a reference the move removes);
2232        // the subject may be unreadable. Under a proposal merge's own
2233        // lock this is a nested acquisition and takes nothing more.
2234        let (_write_lock, _) = self.lock_workspace_for_mem_operation(mem)?;
2235        let mount_idx = self
2236            .mounts
2237            .iter()
2238            .position(|m| m.mount.mem == mem)
2239            .ok_or_else(|| self.unknown_mem_error(mem))?;
2240
2241        // History rewriting is a write — read-only and archive mounts
2242        // refuse before any dispatch (parity with the mutation surface).
2243        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
2244            return Err(EngineError::ReadOnlyMount(mem.to_string()));
2245        }
2246
2247        let outcome = match &self.mounts[mount_idx].mount.storage {
2248            MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
2249                return Err(EngineError::NotGitBacked {
2250                    mem: Some(mem.to_string()),
2251                    operation: "memstead_branch_reset".to_string(),
2252                });
2253            }
2254            MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
2255                Some(hook) => (hook.branch_reset)(gitdir, branch, target_sha, expected_head)
2256                    .map_err(|e| match e {
2257                        BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
2258                            let raw = msg.trim_start_matches("UNKNOWN_REF:").trim().to_string();
2259                            EngineError::UnknownRef(raw)
2260                        }
2261                        BackendError::Other(msg) if msg.starts_with("EXPECTED_HEAD_MISMATCH:") => {
2262                            let current = msg
2263                                .trim_start_matches("EXPECTED_HEAD_MISMATCH:")
2264                                .trim()
2265                                .to_string();
2266                            EngineError::BranchResetHeadMoved {
2267                                mem: mem.to_string(),
2268                                expected: expected_head.unwrap_or_default().to_string(),
2269                                current,
2270                            }
2271                        }
2272                        BackendError::Other(msg)
2273                            if msg.starts_with("PUSHED_COMMITS_PROTECTED:") =>
2274                        {
2275                            let payload =
2276                                msg.trim_start_matches("PUSHED_COMMITS_PROTECTED:").trim();
2277                            let pushed_shas = payload
2278                                .split(',')
2279                                .map(|s| s.trim().to_string())
2280                                .filter(|s| !s.is_empty())
2281                                .collect();
2282                            EngineError::PushedCommitsProtected {
2283                                mem: mem.to_string(),
2284                                target_sha: target_sha.to_string(),
2285                                pushed_shas,
2286                            }
2287                        }
2288                        other => EngineError::Backend(other),
2289                    })?,
2290                None => {
2291                    return Err(EngineError::Backend(BackendError::Other(
2292                        "git-branch branch_reset hook not installed (git-branch ops not wired)"
2293                            .to_string(),
2294                    )));
2295                }
2296            },
2297        };
2298
2299        // Rewind the engine's cached HEAD so subsequent drift probes
2300        // don't surface MEM_RELOADED for the reset we just made.
2301        // Then emit a change event so subscribers see the transition
2302        // (skipping the no-op case where previous == new).
2303        if outcome.previous_sha != outcome.new_sha {
2304            // The store serves the tree the branch was reset to; a reload
2305            // that fails leaves the view marked stale, so no write lands
2306            // from the discarded commits' contents.
2307            let _ = self.adopt_moved_head(mount_idx, mem, &outcome.new_sha);
2308            let event = crate::engine::events::MemChangedEvent {
2309                mem: mem.to_string(),
2310                head: outcome.new_sha.clone(),
2311                previous: outcome.previous_sha.clone(),
2312                // n_commits stays at 1 for reset events. The wire
2313                // shape is the same `MemChangedEvent` consumers
2314                // already key on; semantics: "the head moved by this
2315                // operation". Replay-aware consumers branch on the
2316                // commit-vs-reset distinction by inspecting the
2317                // produced commit (a reset's new head is an existing
2318                // commit, not a freshly minted one).
2319                n_commits: 1,
2320            };
2321            self.emit_mem_changed(&event);
2322        }
2323        Ok(outcome)
2324    }
2325
2326    /// Cross-mem references that a reset of `mem` to `target_sha` would
2327    /// strand: incoming edges from entities in *other* mems whose target
2328    /// exists at the current head but would not exist at the target
2329    /// commit — entities created after the target, or renamed to their
2330    /// current id after it (the reset re-materialises the old id, so
2331    /// references to the new id dangle either way).
2332    ///
2333    /// A read — computes against the live store and the commit history,
2334    /// moves nothing. The human surface calls this fresh at
2335    /// confirmation-dialog time and warns before `branch_reset`. Sorted
2336    /// (from_id, to_id, rel_type) for stable rendering.
2337    ///
2338    /// Refusals mirror `changes_since`: `UnknownMem`, `InvalidCursor`
2339    /// for an unresolvable `target_sha`, `InvalidInput` for
2340    /// non-git-backed mounts.
2341    pub fn branch_reset_stranded_refs(
2342        &self,
2343        mem: &str,
2344        target_sha: &str,
2345    ) -> Result<Vec<crate::ops::StrandedCrossMemRef>, EngineError> {
2346        use crate::ops::ChangeEnvelope;
2347
2348        let report = self.changes_since(mem, target_sha, None)?;
2349        let mut discarded: std::collections::HashSet<String> = std::collections::HashSet::new();
2350        for change in &report.changes {
2351            match change {
2352                ChangeEnvelope::Added { id, .. } => {
2353                    discarded.insert(id.to_string());
2354                }
2355                ChangeEnvelope::Renamed { to_id, .. } => {
2356                    discarded.insert(to_id.to_string());
2357                }
2358                ChangeEnvelope::Updated { .. } | ChangeEnvelope::Removed { .. } => {}
2359            }
2360        }
2361        if discarded.is_empty() {
2362            return Ok(Vec::new());
2363        }
2364
2365        let mut stranded: Vec<crate::ops::StrandedCrossMemRef> = self
2366            .store
2367            .all_entities()
2368            .filter(|e| e.mem != mem)
2369            .flat_map(|e| {
2370                e.relationships
2371                    .iter()
2372                    .filter(|r| discarded.contains(&r.target.to_string()))
2373                    .map(|r| crate::ops::StrandedCrossMemRef {
2374                        from_id: e.id.to_string(),
2375                        from_mem: e.mem.clone(),
2376                        to_id: r.target.to_string(),
2377                        rel_type: r.rel_type.clone(),
2378                    })
2379                    .collect::<Vec<_>>()
2380            })
2381            .collect();
2382        stranded.sort_by(|a, b| {
2383            (&a.from_id, &a.to_id, &a.rel_type).cmp(&(&b.from_id, &b.to_id, &b.rel_type))
2384        });
2385        Ok(stranded)
2386    }
2387
2388    /// Two-ref structural diff. Produces a per-entity [`crate::ops::Diff`]
2389    /// comparing the trees at `ref_a` and `ref_b` for the named
2390    /// mem's storage. Folder and archive backends carry no git
2391    /// refs and refuse via [`EngineError::InvalidInput`]; the
2392    /// git-branch backend routes through [`GitBranchOps::diff`] when
2393    /// the git-branch ops are wired.
2394    ///
2395    /// `mem` selects the storage context (the gitdir, for
2396    /// git-branch mounts). Each of `ref_a` / `ref_b` names the empty
2397    /// tree, or is anchored in the history of a mem this workspace
2398    /// mounts in that git directory (the named mem, or a mounted peer,
2399    /// which is what keeps a diff across mems working by the peer's
2400    /// branch name): at such a mem's branch by name, at `HEAD`, which
2401    /// means this mem's declared branch, or at a commit hash of those
2402    /// histories, full or abbreviated, with `~n` and `^n` parent steps
2403    /// from there. No other revision syntax is read.
2404    ///
2405    /// A git directory can hold mems the workspace does not mount. A
2406    /// ref anchored in one of them (its branch by name, a hash out of
2407    /// its history, a form that starts at its branch and walks into a
2408    /// mounted history, as a fork's does) refuses `UNKNOWN_REF` exactly
2409    /// as a ref that names nothing does, and no object outside the
2410    /// mounted histories is read to tell: what the workspace does not
2411    /// mount does not exist for its callers, not even by name.
2412    ///
2413    /// Refusal codes:
2414    /// - [`EngineError::UnknownMem`] (`UNKNOWN_MEM`) — no mount
2415    ///   for `mem`.
2416    /// - [`EngineError::UnknownRef`] (`UNKNOWN_REF`) — either ref
2417    ///   names no commit in the history of a mem this workspace
2418    ///   mounts in the git directory.
2419    /// - [`EngineError::RenameSimilarityOutOfRange`] (`INVALID_INPUT`)
2420    ///   — `config.rename_similarity` outside `[0.1, 1.0]`.
2421    /// - [`EngineError::InvalidInput`] (`INVALID_INPUT`) — mem is
2422    ///   folder or archive-backed (no refs to diff).
2423    pub fn diff(
2424        &self,
2425        mem: &str,
2426        ref_a: &str,
2427        ref_b: &str,
2428        config: Option<crate::ops::DiffConfig>,
2429    ) -> Result<crate::ops::Diff, EngineError> {
2430        let m = self.find_mount(mem)?;
2431        let config = config.unwrap_or_default();
2432
2433        if config.rename_similarity < crate::ops::RENAME_SIMILARITY_MIN
2434            || config.rename_similarity > crate::ops::RENAME_SIMILARITY_MAX
2435        {
2436            return Err(EngineError::RenameSimilarityOutOfRange {
2437                requested: config.rename_similarity,
2438                allowed_min: crate::ops::RENAME_SIMILARITY_MIN,
2439                allowed_max: crate::ops::RENAME_SIMILARITY_MAX,
2440            });
2441        }
2442
2443        match &m.mount.storage {
2444            MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
2445                Err(EngineError::NotGitBacked {
2446                    mem: Some(mem.to_string()),
2447                    operation: "memstead_diff".to_string(),
2448                })
2449            }
2450            MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
2451                Some(hook) => {
2452                    let readable = self.branches_mounted_in(gitdir, branch);
2453                    (hook.diff)(gitdir, branch, &readable, mem, ref_a, ref_b, &config).map_err(
2454                        |e| match e {
2455                            // Map the standard backend-side "ref not found" shape into the
2456                            // typed engine-level refusal. The git-branch dispatcher uses
2457                            // `BackendError::Other` with a leading marker so the engine can
2458                            // recover the typed code without re-parsing the message.
2459                            BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
2460                                let raw = msg.trim_start_matches("UNKNOWN_REF:").trim().to_string();
2461                                EngineError::UnknownRef(raw)
2462                            }
2463                            other => EngineError::Backend(other),
2464                        },
2465                    )
2466                }
2467                None => Err(EngineError::Backend(BackendError::Other(
2468                    "git-branch diff hook not installed (git-branch ops not wired)".to_string(),
2469                ))),
2470            },
2471        }
2472    }
2473}
2474
2475impl Engine {
2476    /// The declared branches of the other mems this workspace mounts in
2477    /// `gitdir`, under either capability: the histories a ref given to
2478    /// a read verb may lie in beside the named mem's own (`own`).
2479    fn branches_mounted_in(&self, gitdir: &std::path::Path, own: &str) -> Vec<String> {
2480        let canonical = |p: &std::path::Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
2481        let here = canonical(gitdir);
2482        self.mounts
2483            .iter()
2484            .filter_map(|m| match &m.mount.storage {
2485                MountStorage::GitBranch { gitdir, branch }
2486                    if branch != own && canonical(gitdir) == here =>
2487                {
2488                    Some(branch.clone())
2489                }
2490                _ => None,
2491            })
2492            .collect()
2493    }
2494}
2495
2496/// Anything that hands out an [`Engine`]: the engine itself, a mutable
2497/// borrow, a boxed engine, or a mutex guard. What [`OperationScope`]
2498/// wraps.
2499pub trait EngineHandle {
2500    fn engine(&self) -> &Engine;
2501    fn engine_mut(&mut self) -> &mut Engine;
2502}
2503
2504impl EngineHandle for Engine {
2505    fn engine(&self) -> &Engine {
2506        self
2507    }
2508    fn engine_mut(&mut self) -> &mut Engine {
2509        self
2510    }
2511}
2512
2513impl EngineHandle for &mut Engine {
2514    fn engine(&self) -> &Engine {
2515        self
2516    }
2517    fn engine_mut(&mut self) -> &mut Engine {
2518        self
2519    }
2520}
2521
2522impl EngineHandle for Box<Engine> {
2523    fn engine(&self) -> &Engine {
2524        self
2525    }
2526    fn engine_mut(&mut self) -> &mut Engine {
2527        self
2528    }
2529}
2530
2531impl EngineHandle for std::sync::MutexGuard<'_, Engine> {
2532    fn engine(&self) -> &Engine {
2533        self
2534    }
2535    fn engine_mut(&mut self) -> &mut Engine {
2536        self
2537    }
2538}
2539
2540/// The scope of one operation against the engine, and the only way
2541/// the reload-before-operation notices reach a response.
2542///
2543/// [`Engine::reload_if_stale`] runs before every operation and, when
2544/// it reloaded a mem a sibling had advanced, records a
2545/// [`crate::ops::MemChangedNotice`] describing the delta. Until
2546/// 2026-09-11 those notices accumulated on the engine and every
2547/// response builder had to remember to drain them, or the next
2548/// operation's response carried a notice that was not its own (the
2549/// hazard the old drain's doc comment named, guarded by convention at
2550/// some fifty call sites). Now the notices belong to a scope: opening
2551/// one ([`OperationScope::begin`]) discards whatever an unscoped
2552/// caller left behind, [`OperationScope::finish`] hands the notices
2553/// out as a value together with the engine handle, and dropping a
2554/// scope without finishing discards them. No operation can inherit
2555/// another operation's notice, and there is no method on the engine
2556/// that hands accumulated notices out on demand.
2557///
2558/// The scope derefs to the engine, so a handler uses it exactly as it
2559/// used the engine handle before.
2560#[must_use = "an operation scope hands its notices out through `finish`; dropping it discards them"]
2561pub struct OperationScope<G: EngineHandle> {
2562    inner: Option<G>,
2563}
2564
2565impl<G: EngineHandle> OperationScope<G> {
2566    /// Open the scope: whatever notices an unscoped caller left on the
2567    /// engine are discarded first, so this operation starts clean.
2568    pub fn begin(handle: G) -> Self {
2569        Self::begin_as(handle, crate::engine::callers::CallerKey::default())
2570    }
2571
2572    /// Open the scope for a named caller. The notices this operation
2573    /// hands out describe what moved in each mem since that caller last
2574    /// saw it, including what another caller wrote through this same
2575    /// engine ([`crate::engine::callers`]). A surface with one caller
2576    /// uses [`Self::begin`].
2577    pub fn begin_as(mut handle: G, caller: crate::engine::callers::CallerKey) -> Self {
2578        let engine = handle.engine_mut();
2579        engine.pending_mem_changed.clear();
2580        engine.set_current_caller(caller);
2581        Self {
2582            inner: Some(handle),
2583        }
2584    }
2585
2586    /// Close the scope: the engine handle comes back together with the
2587    /// notices this operation recorded for its caller, in order. A
2588    /// dropped scope hands out nothing; what its caller was not told by
2589    /// a reload of that operation, it is told on a later one.
2590    pub fn finish(mut self) -> (G, Vec<crate::ops::MemChangedNotice>) {
2591        let mut handle = self
2592            .inner
2593            .take()
2594            .expect("an operation scope is finished at most once");
2595        // An operation that reloaded nothing still tells its caller
2596        // what other callers wrote through this engine.
2597        handle.engine_mut().bring_caller_up_to_date();
2598        let notices = std::mem::take(&mut handle.engine_mut().pending_mem_changed);
2599        handle.engine_mut().close_caller_scope();
2600        (handle, notices)
2601    }
2602}
2603
2604impl<G: EngineHandle> std::ops::Deref for OperationScope<G> {
2605    type Target = Engine;
2606    fn deref(&self) -> &Engine {
2607        self.inner
2608            .as_ref()
2609            .expect("an operation scope holds its engine until finished")
2610            .engine()
2611    }
2612}
2613
2614impl<G: EngineHandle> std::ops::DerefMut for OperationScope<G> {
2615    fn deref_mut(&mut self) -> &mut Engine {
2616        self.inner
2617            .as_mut()
2618            .expect("an operation scope holds its engine until finished")
2619            .engine_mut()
2620    }
2621}
2622
2623impl<G: EngineHandle> Drop for OperationScope<G> {
2624    fn drop(&mut self) {
2625        if let Some(handle) = self.inner.as_mut() {
2626            handle.engine_mut().pending_mem_changed.clear();
2627            handle.engine_mut().close_caller_scope();
2628        }
2629    }
2630}
2631
2632#[cfg(test)]
2633mod remote_status_source_scan;
2634#[cfg(test)]
2635mod tests;