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