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