Skip to main content

memstead_base/engine/
drift.rs

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