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