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 /// Build a [`crate::ops::MemChangedNotice`] describing the
323 /// per-entity delta a reload applied to `mem` (from `from_head`
324 /// to `to_head`). Derived from [`Self::changes_since`] so it
325 /// carries rename detection on git-branch mounts; on any backend
326 /// error (e.g. an unresolvable cursor) it falls back to an empty
327 /// delta — the heads alone still tell the agent the mem moved.
328 ///
329 /// Callers pair this with [`Self::reload_if_stale`]: a returned
330 /// [`crate::ops::WarningHint::MemReloaded`] carries the
331 /// `old_head` / `new_head` to pass here. The delta matches the
332 /// transition the reload applied (`changes_since` walks the same
333 /// `from_head → current` range).
334 pub fn mem_changed_notice(
335 &self,
336 mem: &str,
337 from_head: &str,
338 to_head: &str,
339 ) -> crate::ops::MemChangedNotice {
340 let changes = self
341 .changes_since(mem, from_head, None)
342 .map(|r| r.changes)
343 .unwrap_or_default();
344 crate::ops::MemChangedNotice::from_delta(
345 mem.to_string(),
346 from_head.to_string(),
347 to_head.to_string(),
348 changes,
349 )
350 }
351
352 /// Per-entity events for `mem` between `since` and the backend's
353 /// current state.
354 ///
355 /// 1. Resolves the mount (returns [`EngineError::UnknownMem`]
356 /// on unknown mem).
357 /// 2. Validates `rename_similarity` against
358 /// `[RENAME_SIMILARITY_MIN, RENAME_SIMILARITY_MAX]`. Out-of-range
359 /// values refuse with [`EngineError::InvalidInput`] carrying
360 /// `details.allowed_range` and `details.requested`. `None` falls
361 /// back to [`crate::ops::RENAME_SIMILARITY_DEFAULT`].
362 /// 3. Dispatches on the mount's `MountStorage`:
363 /// - Folder mounts synthesize from the JSONL changelog via
364 /// [`crate::ops::folder_changes_since`].
365 /// - Git-branch mounts call the registered
366 /// [`GitBranchOps::changes_since`] hook (real tree-diff with
367 /// rename detection); missing hook = git-branch ops not wired
368 /// and the report comes back empty.
369 /// - Archive mounts return an empty report.
370 /// 4. Enriches each envelope's `title` / `entity_type` from the
371 /// in-memory store (best-effort — `Removed` envelopes always
372 /// leave both `None`; missing-from-store entities also leave
373 /// them `None`).
374 /// 5. Returns [`crate::ops::ChangesReport`] with `mem`,
375 /// `since` (echoed), `head` (backend-resolved current
376 /// cursor), enriched `changes`, and any clamping warnings.
377 pub fn changes_since(
378 &self,
379 mem: &str,
380 since: &str,
381 rename_similarity: Option<f32>,
382 ) -> Result<crate::ops::ChangesReport, EngineError> {
383 let m = self.find_mount(mem)?;
384
385 // Reject out-of-range `rename_similarity` early so CLI and MCP
386 // share one refusal surface.
387 // The prior clamp+warn shape silently accepted nonsense values
388 // (e.g. 1.5 ≡ 1.0); typed refusal gives the agent a recoverable
389 // signal.
390 if let Some(v) = rename_similarity
391 && !(crate::ops::RENAME_SIMILARITY_MIN..=crate::ops::RENAME_SIMILARITY_MAX).contains(&v)
392 {
393 return Err(EngineError::RenameSimilarityOutOfRange {
394 requested: v,
395 allowed_min: crate::ops::RENAME_SIMILARITY_MIN,
396 allowed_max: crate::ops::RENAME_SIMILARITY_MAX,
397 });
398 }
399 let clamped = rename_similarity.unwrap_or(crate::ops::RENAME_SIMILARITY_DEFAULT);
400
401 // The folder replay pairs a rename row with the id that vanished
402 // for it only over a loaded store: a deferred mount would read
403 // every id as vanished.
404 let store_lookup = |id: &crate::EntityId| -> Option<String> {
405 let e = self.store.get(id)?;
406 if e.stub {
407 return None;
408 }
409 Some(
410 e.metadata
411 .get("created_date")
412 .map(|v| v.to_frontmatter_string())
413 .unwrap_or_default(),
414 )
415 };
416 let store_ref: Option<crate::ops::StoreLookup<'_>> = if m.deferred {
417 None
418 } else {
419 Some(&store_lookup)
420 };
421 let backend_changes = match &m.mount.storage {
422 MountStorage::Folder { path } => {
423 match crate::ops::folder_changes_since(path, mem, since, store_ref) {
424 Ok(c) => c,
425 // Lift the backend's typed bad-`since` marker, parallel
426 // to the git arm's COMMIT_NOT_FOUND lift below: the
427 // folder cursor is a timestamp, and anything else —
428 // a mutation's `write_id` above all — refuses instead
429 // of silently replaying the whole history.
430 Err(BackendError::Other(msg)) if msg.starts_with("INVALID_TS_CURSOR:") => {
431 let since = msg
432 .strip_prefix("INVALID_TS_CURSOR:")
433 .unwrap_or_default()
434 .to_string();
435 return Err(EngineError::InvalidTimestampCursor {
436 mem: mem.to_string(),
437 since,
438 });
439 }
440 Err(e) => return Err(EngineError::Backend(e)),
441 }
442 }
443 MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
444 Some(hook) => match (hook.changes_since)(gitdir, branch, mem, since, clamped) {
445 Ok(c) => c,
446 // Lift the backend's typed bad-`since` marker to a typed
447 // engine error carrying the untruncated SHA, parallel
448 // to the UNKNOWN_REMOTE / LOCAL_DIVERGENCE prefixes.
449 Err(BackendError::Other(msg)) if msg.starts_with("COMMIT_NOT_FOUND:") => {
450 let since = msg
451 .strip_prefix("COMMIT_NOT_FOUND:")
452 .unwrap_or_default()
453 .to_string();
454 return Err(EngineError::InvalidChangesCursor {
455 mem: mem.to_string(),
456 since,
457 });
458 }
459 Err(e) => return Err(EngineError::Backend(e)),
460 },
461 None => crate::ops::BackendChanges::empty_at(since),
462 },
463 // Archive is sealed; the in-memory backend keeps a
464 // provenance log but no cursor-addressable change history,
465 // so both yield no backend-derived changes here (the live
466 // playground stream rides the engine's event broadcast, not
467 // this path).
468 MountStorage::Archive { .. } | MountStorage::InMemory => {
469 crate::ops::BackendChanges::empty_at(since)
470 }
471 };
472
473 // Enrich each id-only envelope from the engine's store.
474 // `Removed` always leaves title / entity_type None — the
475 // entity is gone by definition; the post-reload store does
476 // not have it. Other variants populate when the lookup
477 // succeeds; missing ids stay None.
478 let enriched: Vec<crate::ops::ChangeEnvelope> = backend_changes
479 .changes
480 .into_iter()
481 .map(|env| match env {
482 crate::ops::ChangeEnvelope::Added { id, .. } => {
483 let (title, entity_type) = lookup_title_and_type(&self.store, &id);
484 crate::ops::ChangeEnvelope::Added {
485 id,
486 title,
487 entity_type,
488 }
489 }
490 crate::ops::ChangeEnvelope::Updated { id, .. } => {
491 let (title, entity_type) = lookup_title_and_type(&self.store, &id);
492 crate::ops::ChangeEnvelope::Updated {
493 id,
494 title,
495 entity_type,
496 }
497 }
498 crate::ops::ChangeEnvelope::Removed { id, .. } => {
499 crate::ops::ChangeEnvelope::Removed {
500 id,
501 title: None,
502 entity_type: None,
503 }
504 }
505 crate::ops::ChangeEnvelope::Renamed { from_id, to_id, .. } => {
506 let (title, entity_type) = lookup_title_and_type(&self.store, &to_id);
507 crate::ops::ChangeEnvelope::Renamed {
508 from_id,
509 to_id,
510 title,
511 entity_type,
512 }
513 }
514 })
515 .collect();
516
517 // Out-of-range `rename_similarity` is now a hard refusal (see
518 // early-return above); the response carries no clamping warning.
519 let warnings: Vec<crate::ops::WarningHint> = Vec::new();
520
521 // The backend populates
522 // notes + memstead_ref on every git-branch call (folder + archive
523 // backends leave them empty / None). Surface them
524 // unconditionally; the MCP `include_notes` parameter becomes
525 // a renderer-side filter rather than a separate engine call.
526 let notes = if backend_changes.notes.is_empty() && backend_changes.memstead_ref.is_none() {
527 None
528 } else {
529 Some(backend_changes.notes)
530 };
531 Ok(crate::ops::ChangesReport {
532 mem: mem.to_string(),
533 since: backend_changes.since,
534 head: backend_changes.head,
535 changes: enriched,
536 warnings,
537 notes,
538 memstead_ref: backend_changes.memstead_ref,
539 })
540 }
541
542 /// Fetch updates from `remote` into the workspace's mem-repo.
543 /// Advances remote-tracking refs only; the local branch pointer
544 /// is not moved.
545 ///
546 /// `refspecs` is forwarded verbatim to `git fetch`. An empty list
547 /// uses the remote's configured defaults.
548 ///
549 /// Refusal codes: `UNKNOWN_MEM`, `UNKNOWN_REMOTE`,
550 /// `INVALID_INPUT` (folder / archive mounts).
551 ///
552 /// V1 atomicity: schema-validation quarantine for
553 /// fetched commits is not yet wired. The remote-tracking refs
554 /// advance unconditionally on a successful fetch; downstream
555 /// schema validation runs on read via the engine's existing
556 /// reload pipeline.
557 pub fn fetch(
558 &self,
559 mem: &str,
560 remote: &str,
561 refspecs: &[String],
562 ) -> Result<crate::ops::FetchOutcome, EngineError> {
563 let m = self.find_mount(mem)?;
564 match &m.mount.storage {
565 MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
566 Err(EngineError::InvalidInput(format!(
567 "mem '{mem}' is not git-backed — `memstead_fetch` requires a git-branch mount",
568 )))
569 }
570 MountStorage::GitBranch { gitdir, .. } => match self.git_branch_ops.as_ref() {
571 Some(hook) => {
572 let mut outcome =
573 (hook.fetch)(gitdir, remote, refspecs).map_err(|e| match e {
574 BackendError::Other(msg) if msg.starts_with("UNKNOWN_REMOTE:") => {
575 EngineError::UnknownRemote(
576 msg.trim_start_matches("UNKNOWN_REMOTE:").trim().to_string(),
577 )
578 }
579 other => EngineError::Backend(other),
580 })?;
581 // The mem's check-ledger rows travel with it: the
582 // remote's transport ref, unioned into the local
583 // ledger (engine::checks_transport).
584 outcome.checks_imported = self.import_checks(hook, gitdir, remote, &[mem])?;
585 Ok(outcome)
586 }
587 None => Err(EngineError::Backend(BackendError::Other(
588 "git-branch fetch hook not installed (git-branch ops not wired)".to_string(),
589 ))),
590 },
591 }
592 }
593
594 /// Pull updates from `remote` into the named mem's branch.
595 /// Fetches into the remote-tracking ref, runs a pre-merge schema
596 /// validation pass against the prospective state, then
597 /// fast-forwards the local branch. Refuses with
598 /// `LOCAL_DIVERGENCE` for diverged local branches and with
599 /// `SCHEMA_VIOLATION_IN_FETCH` when the prospective state fails
600 /// schema validation — in both refusal cases the local branch
601 /// pointer is untouched (the underlying fetch has updated
602 /// `refs/remotes/*` but the engine has not promoted the new
603 /// state).
604 pub fn pull(
605 &mut self,
606 mem: &str,
607 remote: &str,
608 ) -> Result<crate::ops::PullOutcome, EngineError> {
609 let mount_idx = self
610 .mounts
611 .iter()
612 .position(|m| m.mount.mem == mem)
613 .ok_or_else(|| self.unknown_mem_error(mem))?;
614 let (gitdir, branch) = match &self.mounts[mount_idx].mount.storage {
615 MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
616 return Err(EngineError::InvalidInput(format!(
617 "mem '{mem}' is not git-backed — `memstead_pull` requires a git-branch mount",
618 )));
619 }
620 MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
621 };
622
623 // Run the fetch step alone first so we can validate the
624 // prospective state against the schema before letting the
625 // pull's fast-forward land. Errors map to the typed surface
626 // just like a standalone `memstead_fetch` call.
627 let hook = self.git_branch_ops.ok_or_else(|| {
628 EngineError::Backend(BackendError::Other(
629 "git-branch pull hook not installed (git-branch ops not wired)".to_string(),
630 ))
631 })?;
632 (hook.fetch)(&gitdir, remote, &[]).map_err(|e| match e {
633 BackendError::Other(msg) if msg.starts_with("UNKNOWN_REMOTE:") => {
634 EngineError::UnknownRemote(
635 msg.trim_start_matches("UNKNOWN_REMOTE:").trim().to_string(),
636 )
637 }
638 other => EngineError::Backend(other),
639 })?;
640
641 // Pre-merge schema validation. The remote-tracking ref now
642 // points at the fetched tip; we walk it, parse every `.md`
643 // blob against the mem's pinned schema, and refuse the
644 // pull if any parse fails. The local branch pointer is still
645 // unchanged at this point — the refusal is fully atomic.
646 // The remote-tracking ref follows the mount's declared
647 // branch, never the mem name — the two differ on namespaced
648 // mounts.
649 let remote_ref = format!(
650 "refs/remotes/{remote}/{}",
651 crate::workspace::branch_short_name(&branch)
652 );
653 self.validate_ref_against_schema(&hook, &gitdir, mem, &remote_ref)?;
654
655 // Run the underlying pull (re-runs the fetch via git CLI, but
656 // that's a no-op cache-wise and keeps the fast-forward logic
657 // co-located with the rest of the transport implementation).
658 let mut outcome = (hook.pull)(&gitdir, remote, &branch, mem).map_err(|e| match e {
659 BackendError::Other(msg) if msg.starts_with("UNKNOWN_REMOTE:") => {
660 EngineError::UnknownRemote(
661 msg.trim_start_matches("UNKNOWN_REMOTE:").trim().to_string(),
662 )
663 }
664 BackendError::Other(msg) if msg.starts_with("LOCAL_DIVERGENCE:") => {
665 let payload = msg.trim_start_matches("LOCAL_DIVERGENCE:");
666 let mut parts = payload.splitn(2, ':');
667 let v = parts.next().unwrap_or(mem).to_string();
668 let remote_ref = parts.next().unwrap_or("refs/remotes/?/?").to_string();
669 EngineError::LocalDivergence { mem: v, remote_ref }
670 }
671 other => EngineError::Backend(other),
672 })?;
673 // The mem's check-ledger rows travel with it (engine::checks_transport).
674 outcome.checks_imported = self.import_checks(&hook, &gitdir, remote, &[mem])?;
675
676 // Rewind cached head + emit change event.
677 if outcome.previous_sha != outcome.new_sha {
678 if let Some(state) = self.mounts.get_mut(mount_idx) {
679 state.last_known_head = Some(outcome.new_sha.clone());
680 }
681 let event = crate::engine::events::MemChangedEvent {
682 mem: mem.to_string(),
683 head: outcome.new_sha.clone(),
684 previous: outcome.previous_sha.clone(),
685 n_commits: 1,
686 };
687 self.emit_mem_changed(&event);
688 }
689 Ok(outcome)
690 }
691
692 /// Push the named mem's branch to `remote`. Runs a pre-push
693 /// schema validation pass against the local branch tree; refuses
694 /// with `LOCAL_INVALID_STATE` when the local state fails schema
695 /// validation (the remote is not contacted in that case). Refuses
696 /// with `NON_FAST_FORWARD` when the push is not a fast-forward
697 /// and `force: false`; with `force: true` runs a
698 /// `--force-with-lease` push instead.
699 pub fn push(
700 &self,
701 mem: &str,
702 remote: &str,
703 force: bool,
704 ) -> Result<crate::ops::PushOutcome, EngineError> {
705 let m = self.find_mount(mem)?;
706 let (gitdir, branch) = match &m.mount.storage {
707 MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
708 return Err(EngineError::InvalidInput(format!(
709 "mem '{mem}' is not git-backed — `memstead_push` requires a git-branch mount",
710 )));
711 }
712 MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
713 };
714 let hook = self.git_branch_ops.ok_or_else(|| {
715 EngineError::Backend(BackendError::Other(
716 "git-branch push hook not installed (git-branch ops not wired)".to_string(),
717 ))
718 })?;
719
720 // Pre-push schema validation: walk the local branch tree (the
721 // mount's declared branch, never a ref derived from the mem
722 // name), run the mem's pinned schema over every `.md` blob.
723 // Any parse failure refuses the push with
724 // `LOCAL_INVALID_STATE` — the remote is not contacted. A gate
725 // that cannot run (the ref unresolvable, the tree unreadable)
726 // refuses too: a validation that did not happen must never
727 // read as a pass.
728 let local_ref = crate::workspace::branch_full_ref(&branch);
729 match self.validate_ref_against_schema(&hook, &gitdir, mem, &local_ref) {
730 Ok(()) => {}
731 Err(EngineError::SchemaViolationInFetch { violations, .. }) => {
732 return Err(EngineError::LocalInvalidState {
733 mem: mem.to_string(),
734 remote: remote.to_string(),
735 detail: format!(
736 "{} violation(s) in local branch: {}",
737 violations.len(),
738 violations.join("; "),
739 ),
740 });
741 }
742 Err(EngineError::UnknownRef(raw)) => {
743 // Names the declared branch the gate looked for, so
744 // the reader sees what was resolved, not an invented
745 // ref.
746 return Err(EngineError::UnknownRef(raw));
747 }
748 Err(other) => {
749 return Err(EngineError::Backend(BackendError::Other(format!(
750 "pre-push schema validation could not run for mem '{mem}' \
751 (declared branch `{local_ref}`): {other}",
752 ))));
753 }
754 }
755
756 let mut outcome =
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(
772 msg.trim_start_matches("UNKNOWN_REF:").trim().to_string(),
773 )
774 }
775 other => EngineError::Backend(other),
776 })?;
777 // The mem's check-ledger rows follow its branch: published on
778 // the transport ref and pushed beside it (engine::checks_transport).
779 // The branch is on the remote by now, so a failure here names
780 // that, and a rerun publishes the rows alone.
781 outcome.checks_published = self
782 .publish_checks(&hook, &gitdir, remote, &[mem])
783 .map_err(|e| {
784 EngineError::Mem(format!(
785 "the branch of mem '{mem}' was pushed; its check-ledger rows were not \
786 ({}); run the push again to publish them",
787 e.prose_render()
788 ))
789 })?;
790 Ok(outcome)
791 }
792
793 /// `memstead status --remote`: every mounted git-branch mem and the
794 /// schemas ref compared against `remote` by one read-only
795 /// `ls-remote` per gitdir, classified in sync / local-ahead / behind
796 /// / forked / unfetched (the remote head is not in the local object
797 /// store, so behind or forked, which a fetch tells) / missing locally,
798 /// plus the remote's branches nothing mounts (a notice, whether or
799 /// not a local ref of that name exists) and the mounted branches the
800 /// remote lacks (a notice). Moves no ref and never refuses: no git-branch mount, no
801 /// hook (git-branch ops not wired), no remote configured or one that cannot be
802 /// reached each become a notice and the outcome stands as not stale,
803 /// so a network blip never blocks a session. The mount table the
804 /// classification reads is this engine's own, so a remote branch with
805 /// no mount is a leftover of a retired or re-homed mem, never
806 /// staleness; the reconcile itself stays `fetch` and `pull`.
807 pub fn remote_status(&self, remote: &str) -> crate::ops::RemoteStatusOutcome {
808 use crate::ops::{RemoteRefState, RemoteRefStatus, RemoteStatusOutcome};
809
810 let mut outcome = RemoteStatusOutcome {
811 remote: remote.to_string(),
812 ..Default::default()
813 };
814 let mut gitdirs: Vec<std::path::PathBuf> = Vec::new();
815 for m in &self.mounts {
816 if let MountStorage::GitBranch { gitdir, .. } = &m.mount.storage
817 && !gitdirs.contains(gitdir)
818 {
819 gitdirs.push(gitdir.clone());
820 }
821 }
822 if gitdirs.is_empty() {
823 outcome.notices.push(
824 "no git-branch mem is mounted, so there is no remote to compare against"
825 .to_string(),
826 );
827 return outcome;
828 }
829 let Some(hook) = self.git_branch_ops.as_ref() else {
830 outcome.notices.push(
831 "git-branch hooks not installed (git-branch ops not wired): the remote was not compared"
832 .to_string(),
833 );
834 return outcome;
835 };
836
837 let memstead_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
838 let checks_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_CHECKS_REF_BRANCH);
839 for gitdir in &gitdirs {
840 let remote_refs: std::collections::BTreeMap<String, String> =
841 match (hook.ls_remote)(gitdir, remote) {
842 Ok(v) => v.into_iter().collect(),
843 Err(BackendError::Other(msg)) if msg.starts_with("UNKNOWN_REMOTE:") => {
844 outcome.notices.push(format!(
845 "remote `{}` is not configured or not reachable from {}: the \
846 comparison did not run (fail open)",
847 msg.trim_start_matches("UNKNOWN_REMOTE:").trim(),
848 gitdir.display()
849 ));
850 continue;
851 }
852 Err(e) => {
853 outcome.notices.push(format!(
854 "remote `{remote}` could not be read from {}: {e} (fail open)",
855 gitdir.display()
856 ));
857 continue;
858 }
859 };
860 // The branches this workspace mounts from this gitdir, by ref.
861 let mut mounted: std::collections::BTreeMap<String, String> =
862 std::collections::BTreeMap::new();
863 for m in &self.mounts {
864 if let MountStorage::GitBranch { gitdir: g, branch } = &m.mount.storage
865 && g == gitdir
866 {
867 mounted.insert(
868 crate::workspace::branch_full_ref(branch),
869 m.mount.mem.clone(),
870 );
871 }
872 }
873 let local = |ref_name: &str| -> Option<String> {
874 (hook.resolve_ref)(gitdir, ref_name).ok().flatten()
875 };
876 // The ancestry verdict for a tracked ref whose heads differ.
877 // A remote head this clone has never fetched is not in the
878 // local object store, so neither direction can be tested:
879 // that is `Unfetched`, never a guessed `Forked`.
880 let compare = |local_sha: &str, remote_sha: &str| -> RemoteRefState {
881 match (hook.is_ancestor)(gitdir, remote_sha, local_sha) {
882 Ok(true) => RemoteRefState::LocalAhead,
883 Ok(false) => match (hook.is_ancestor)(gitdir, local_sha, remote_sha) {
884 Ok(true) => RemoteRefState::Behind,
885 Ok(false) => RemoteRefState::Forked,
886 Err(_) => RemoteRefState::Unfetched,
887 },
888 Err(_) => RemoteRefState::Unfetched,
889 }
890 };
891
892 for (ref_name, remote_sha) in &remote_refs {
893 // The check-ledger transport ref is derived from the
894 // workspace ledger before every publish and unioned on
895 // every fetch: it has no ahead or behind to report.
896 if *ref_name == checks_ref {
897 continue;
898 }
899 let schemas_ref = *ref_name == memstead_ref;
900 let mem = mounted.get(ref_name).cloned();
901 let tracked = schemas_ref || mem.is_some();
902 let local_sha = local(ref_name);
903 // Mount first: a branch nothing mounts is not graph state,
904 // whatever a local ref of that name says, so it can never
905 // be staleness.
906 let state = match (&local_sha, tracked) {
907 (_, false) => RemoteRefState::UnmountedRemote,
908 (None, true) => RemoteRefState::MissingLocal,
909 (Some(l), true) if l == remote_sha => RemoteRefState::InSync,
910 (Some(l), true) => compare(l, remote_sha),
911 };
912 outcome.refs.push(RemoteRefStatus {
913 ref_name: ref_name.clone(),
914 mem,
915 schemas_ref,
916 state,
917 remote_sha: Some(remote_sha.clone()),
918 local_sha,
919 });
920 }
921 // Tracked refs the remote lacks: every mounted branch, and the
922 // schemas ref when this clone carries one. Never pushed, a
923 // notice.
924 let mut tracked_only: Vec<(String, Option<String>, bool)> = mounted
925 .iter()
926 .map(|(r, m)| (r.clone(), Some(m.clone()), false))
927 .collect();
928 if local(&memstead_ref).is_some() {
929 tracked_only.push((memstead_ref.clone(), None, true));
930 }
931 for (ref_name, mem, schemas_ref) in tracked_only {
932 if remote_refs.contains_key(&ref_name) {
933 continue;
934 }
935 outcome.refs.push(RemoteRefStatus {
936 local_sha: local(&ref_name),
937 ref_name,
938 mem,
939 schemas_ref,
940 state: RemoteRefState::NotOnRemote,
941 remote_sha: None,
942 });
943 }
944 }
945 outcome.refs.sort_by(|a, b| a.ref_name.cmp(&b.ref_name));
946 for r in &outcome.refs {
947 *outcome
948 .counts
949 .entry(r.state.as_wire().to_string())
950 .or_default() += 1;
951 }
952 outcome.stale = outcome.refs.iter().any(|r| r.state.is_stale());
953 outcome
954 }
955
956 /// Push every mounted git-branch mem's declared branch, plus the
957 /// `__MEMSTEAD` ref of every mem-repo those mounts share, to
958 /// `remote` — fast-forward only, there is no force variant. One
959 /// `ls-remote` per mem-repo decides which refs lag; a ref whose
960 /// local and remote SHA agree is reported `in_sync` and never
961 /// sent. Each lagging mem branch goes through [`Self::push`]
962 /// (the pre-push schema gate included); `__MEMSTEAD` goes through
963 /// the same transport seam with no schema gate, it IS the
964 /// schemas. A refusal on one ref lands in `refused` with its
965 /// typed code and the run continues with the next ref — the
966 /// caller decides the exit status from the outcome. Folder,
967 /// archive and in-memory mounts have no branch and are skipped.
968 /// Only a remote that cannot be listed at all (`UNKNOWN_REMOTE`)
969 /// fails the run as a whole.
970 pub fn push_all(&self, remote: &str) -> Result<crate::ops::PushAllOutcome, EngineError> {
971 use crate::ops::{PushAllOutcome, PushedRef, RefusedRef};
972
973 let hook = self.git_branch_ops.ok_or_else(|| {
974 EngineError::Backend(BackendError::Other(
975 "git-branch push hook not installed (git-branch ops not wired)".to_string(),
976 ))
977 })?;
978
979 // Mem-repos in mount order, each once; a workspace may spread
980 // its mounts over more than one gitdir.
981 let mut gitdirs: Vec<std::path::PathBuf> = Vec::new();
982 for m in &self.mounts {
983 if let MountStorage::GitBranch { gitdir, .. } = &m.mount.storage
984 && !gitdirs.contains(gitdir)
985 {
986 gitdirs.push(gitdir.clone());
987 }
988 }
989
990 let mut outcome = PushAllOutcome {
991 remote: remote.to_string(),
992 ..Default::default()
993 };
994
995 for gitdir in &gitdirs {
996 let remote_refs: std::collections::HashMap<String, String> =
997 (hook.ls_remote)(gitdir, remote)
998 .map_err(|e| match e {
999 BackendError::Other(msg) if msg.starts_with("UNKNOWN_REMOTE:") => {
1000 EngineError::UnknownRemote(
1001 msg.trim_start_matches("UNKNOWN_REMOTE:").trim().to_string(),
1002 )
1003 }
1004 other => EngineError::Backend(other),
1005 })?
1006 .into_iter()
1007 .collect();
1008
1009 // `__MEMSTEAD` first: schemas and mem configs before the
1010 // content that depends on them, so a clone that pulls
1011 // mid-run never sees a mem its schema ref lacks.
1012 let memstead_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
1013 let mut targets: Vec<(String, Option<String>, String)> = Vec::new();
1014 match (hook.resolve_ref)(gitdir, &memstead_ref) {
1015 Ok(Some(_)) => targets.push((
1016 memstead_ref.clone(),
1017 None,
1018 crate::MEMSTEAD_REF_BRANCH.to_string(),
1019 )),
1020 Ok(None) => {}
1021 Err(e) => return Err(EngineError::Backend(e)),
1022 }
1023 for m in &self.mounts {
1024 if let MountStorage::GitBranch { gitdir: g, branch } = &m.mount.storage
1025 && g == gitdir
1026 {
1027 targets.push((
1028 crate::workspace::branch_full_ref(branch),
1029 Some(m.mount.mem.clone()),
1030 branch.clone(),
1031 ));
1032 }
1033 }
1034
1035 for (ref_name, mem, branch) in targets {
1036 let local_sha = match (hook.resolve_ref)(gitdir, &ref_name) {
1037 Ok(Some(sha)) => sha,
1038 Ok(None) => {
1039 outcome.refused.push(RefusedRef {
1040 ref_name: ref_name.clone(),
1041 mem: mem.clone(),
1042 code: "UNKNOWN_REF".to_string(),
1043 message: format!(
1044 "{ref_name} does not exist locally{}",
1045 mem.as_deref()
1046 .map(|m| format!(" (mem `{m}`'s declared branch)"))
1047 .unwrap_or_default()
1048 ),
1049 });
1050 continue;
1051 }
1052 Err(e) => return Err(EngineError::Backend(e)),
1053 };
1054 let previous_sha = remote_refs.get(&ref_name).cloned().unwrap_or_default();
1055 if previous_sha == local_sha {
1056 outcome.in_sync.push(ref_name);
1057 continue;
1058 }
1059 let result = match &mem {
1060 Some(m) => self.push(m, remote, false).map(|o| o.new_sha),
1061 None => (hook.push)(gitdir, remote, &branch, crate::MEMSTEAD_REF_BRANCH, false)
1062 .map(|o| o.new_sha)
1063 .map_err(|e| match e {
1064 BackendError::Other(msg) if msg.starts_with("NON_FAST_FORWARD:") => {
1065 EngineError::NonFastForward {
1066 mem: crate::MEMSTEAD_REF_BRANCH.to_string(),
1067 remote: remote.to_string(),
1068 }
1069 }
1070 BackendError::Other(msg) if msg.starts_with("UNKNOWN_REMOTE:") => {
1071 EngineError::UnknownRemote(
1072 msg.trim_start_matches("UNKNOWN_REMOTE:").trim().to_string(),
1073 )
1074 }
1075 other => EngineError::Backend(other),
1076 }),
1077 };
1078 match result {
1079 Ok(new_sha) => outcome.pushed.push(PushedRef {
1080 ref_name,
1081 mem,
1082 previous_sha,
1083 new_sha,
1084 }),
1085 Err(e) => {
1086 // The single-mem refusal names `force`, which
1087 // `--all` does not offer; say what applies here.
1088 let message = match &e {
1089 EngineError::NonFastForward { .. } => format!(
1090 "remote `{remote}` carries commits on {ref_name} this clone lacks; \
1091 fetch and pull {}, then push again",
1092 mem.as_deref()
1093 .map(|m| format!("mem `{m}`"))
1094 .unwrap_or_else(|| "the schema ref".to_string()),
1095 ),
1096 other => other.to_string(),
1097 };
1098 outcome.refused.push(RefusedRef {
1099 ref_name,
1100 mem,
1101 code: e.code().to_string(),
1102 message,
1103 })
1104 }
1105 }
1106 }
1107 // The check-ledger rows of every mem mounted from this
1108 // gitdir ride the transport ref, published once per gitdir
1109 // after the branches (engine::checks_transport).
1110 let mems: Vec<String> = self
1111 .mounts
1112 .iter()
1113 .filter_map(|m| match &m.mount.storage {
1114 MountStorage::GitBranch { gitdir: g, .. } if g == gitdir => {
1115 Some(m.mount.mem.clone())
1116 }
1117 _ => None,
1118 })
1119 .collect();
1120 let mem_refs: Vec<&str> = mems.iter().map(String::as_str).collect();
1121 let checks_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_CHECKS_REF_BRANCH);
1122 let previous_sha = remote_refs.get(&checks_ref).cloned().unwrap_or_default();
1123 match self.publish_checks(&hook, gitdir, remote, &mem_refs) {
1124 Ok(Some(new_sha)) => outcome.pushed.push(PushedRef {
1125 ref_name: checks_ref,
1126 mem: None,
1127 previous_sha,
1128 new_sha,
1129 }),
1130 Ok(None) => {
1131 if !previous_sha.is_empty() {
1132 outcome.in_sync.push(checks_ref);
1133 }
1134 }
1135 Err(e) => outcome.refused.push(RefusedRef {
1136 ref_name: checks_ref,
1137 mem: None,
1138 code: e.code().to_string(),
1139 message: e.prose_render(),
1140 }),
1141 }
1142 }
1143
1144 Ok(outcome)
1145 }
1146
1147 /// Configure (or re-point) a named remote on the workspace's
1148 /// mem-repo, so `fetch` / `pull` / `push` have somewhere to go.
1149 /// Upsert semantics — safe to re-run with a new URL. The mem-repo
1150 /// is shared by every git-branch mount, so the op is
1151 /// workspace-level: any git-branch mount locates it; refuses
1152 /// `INVALID_INPUT` when the workspace has none.
1153 pub fn remote_add(
1154 &self,
1155 name: &str,
1156 url: &str,
1157 ) -> Result<crate::ops::RemoteAddOutcome, EngineError> {
1158 // Both values become git subprocess arguments — refuse shapes
1159 // that would parse as flags.
1160 if name.is_empty() || name.starts_with('-') || url.is_empty() || url.starts_with('-') {
1161 return Err(EngineError::InvalidInput(format!(
1162 "remote name and url must be non-empty and must not start with '-' \
1163 (got name '{name}', url '{url}')",
1164 )));
1165 }
1166 let gitdir = self
1167 .mounts
1168 .iter()
1169 .find_map(|m| match &m.mount.storage {
1170 MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
1171 _ => None,
1172 })
1173 .ok_or_else(|| {
1174 EngineError::InvalidInput(
1175 "no git-branch mounts — `remote-add` requires a mem-repo workspace".to_string(),
1176 )
1177 })?;
1178 let hook = self.git_branch_ops.ok_or_else(|| {
1179 EngineError::Backend(BackendError::Other(
1180 "git-branch remote_add hook not installed (git-branch ops not wired)".to_string(),
1181 ))
1182 })?;
1183 (hook.remote_add)(&gitdir, name, url).map_err(EngineError::Backend)
1184 }
1185
1186 /// Pre-merge schema validation pass: walks every `.md` blob at
1187 /// `ref_name` and runs `parse_entries` with the mem's pinned
1188 /// schema. Returns `Ok(())` when the tree is schema-clean;
1189 /// returns `EngineError::SchemaViolationInFetch` with the list of
1190 /// per-entity violation messages otherwise. The validation is
1191 /// strict on parse-time errors — any `(path, error)` pair from
1192 /// `parse_entries` triggers a refusal.
1193 ///
1194 /// `ref_name` is the prospective state (a `refs/remotes/*` ref
1195 /// for pull, `refs/heads/*` for push). The engine layer maps the
1196 /// returned error into the surface code it needs
1197 /// (`SCHEMA_VIOLATION_IN_FETCH` for pull, `LOCAL_INVALID_STATE`
1198 /// for push).
1199 fn validate_ref_against_schema(
1200 &self,
1201 hook: &crate::engine::GitBranchOps,
1202 gitdir: &std::path::Path,
1203 mem: &str,
1204 ref_name: &str,
1205 ) -> Result<(), EngineError> {
1206 // The REF first, then the schema. A branch that does not exist is the
1207 // clearer answer, and asking for the schema first turned "that branch
1208 // is not there" into "the schema pin did not resolve", which is true
1209 // of a quarantined mem and tells the reader nothing about why their
1210 // push failed (04/05).
1211 let blobs = Self::read_ref_blobs(hook, gitdir, ref_name)?;
1212 let schema = self
1213 .schemas
1214 .get(mem)
1215 .ok_or_else(|| EngineError::SchemaNotFound {
1216 mem: mem.to_string(),
1217 pin: "<missing engine-side resolution>".to_string(),
1218 // Internal invariant breach (an already-resolved schema
1219 // absent from the per-mem map), not a source-resolution
1220 // failure — no per-source diagnostics apply.
1221 sources: Vec::new(),
1222 install_hint: None,
1223 })?
1224 .clone();
1225 Self::validate_blobs_against_schema(mem, ref_name, blobs, schema.as_ref())
1226 }
1227
1228 /// The same whole-tree validation `pull` runs before it moves a
1229 /// pointer, for a mem that is not mounted yet: the caller resolved
1230 /// the schema itself (a fork validates the fetched source tree
1231 /// against the source's pin before the mount exists). Refuses with
1232 /// `SCHEMA_VIOLATION_IN_FETCH`, the pull path's code.
1233 pub(crate) fn validate_ref_with_schema(
1234 hook: &crate::engine::GitBranchOps,
1235 gitdir: &std::path::Path,
1236 mem: &str,
1237 ref_name: &str,
1238 schema: &memstead_schema::Schema,
1239 ) -> Result<(), EngineError> {
1240 let blobs = Self::read_ref_blobs(hook, gitdir, ref_name)?;
1241 Self::validate_blobs_against_schema(mem, ref_name, blobs, schema)
1242 }
1243
1244 /// Every `.md` blob at `ref_name`; an absent ref is `UNKNOWN_REF`.
1245 fn read_ref_blobs(
1246 hook: &crate::engine::GitBranchOps,
1247 gitdir: &std::path::Path,
1248 ref_name: &str,
1249 ) -> Result<Vec<(String, String)>, EngineError> {
1250 (hook.read_tree)(gitdir, ref_name).map_err(|e| match e {
1251 BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
1252 EngineError::UnknownRef(msg.trim_start_matches("UNKNOWN_REF:").trim().to_string())
1253 }
1254 other => EngineError::Backend(other),
1255 })
1256 }
1257
1258 /// The permissive parse plus the strict per-entity pass over the
1259 /// blobs of one ref, against one schema.
1260 fn validate_blobs_against_schema(
1261 mem: &str,
1262 ref_name: &str,
1263 blobs: Vec<(String, String)>,
1264 schema: &memstead_schema::Schema,
1265 ) -> Result<(), EngineError> {
1266 let mut source_entries: Vec<crate::entity::source::SourceEntry> = Vec::new();
1267 for (rel_path, content) in blobs {
1268 source_entries.push(crate::entity::source::SourceEntry {
1269 relative_path: rel_path.clone(),
1270 source_path: std::path::PathBuf::from(rel_path),
1271 content,
1272 });
1273 }
1274
1275 // First pass: permissive parse via the engine's loader so we
1276 // can build Entity values for the strict validator. The
1277 // loader silently absorbs frontmatter / title / section
1278 // drift; the strict pass below is what catches it.
1279 let load_result =
1280 crate::entity::loader::parse_entries(source_entries.clone(), Vec::new(), mem, schema);
1281 let mut violations: Vec<String> = load_result
1282 .errors
1283 .iter()
1284 .map(|(path, msg)| format!("{}: {msg}", path.display()))
1285 .collect();
1286
1287 // Strict per-entity validator: enforces "looks like a mem
1288 // entity" invariants (frontmatter shape, title presence,
1289 // required sections, unknown sections, relationship syntax,
1290 // wiki-link shape) that the permissive loader doesn't refuse.
1291 // Re-runs against the same source bytes so unparseable
1292 // frontmatter surfaces here even when the loader's tolerant
1293 // path produces an Entity stub.
1294 let entities_by_path: std::collections::HashMap<String, &crate::entity::Entity> =
1295 load_result
1296 .entities
1297 .iter()
1298 .map(|p| (p.entity.file_path.clone(), &p.entity))
1299 .collect();
1300 for source in &source_entries {
1301 let Some(entity) = entities_by_path.get(&source.relative_path) else {
1302 continue;
1303 };
1304 let type_def = match schema.get_type(&entity.entity_type) {
1305 Some(t) => t,
1306 None => {
1307 violations.push(format!(
1308 "{}: unknown entity_type '{}' in schema",
1309 source.relative_path, entity.entity_type,
1310 ));
1311 continue;
1312 }
1313 };
1314 if let Err(e) = crate::validator::strict::validate_strict(
1315 &source.content,
1316 entity,
1317 type_def.as_ref(),
1318 &source.relative_path,
1319 ) {
1320 violations.push(format!("{}: {e}", source.relative_path));
1321 }
1322 }
1323
1324 if violations.is_empty() {
1325 Ok(())
1326 } else {
1327 Err(EngineError::SchemaViolationInFetch {
1328 mem: mem.to_string(),
1329 ref_name: ref_name.to_string(),
1330 violations,
1331 })
1332 }
1333 }
1334
1335 /// Reset a mem's branch pointer to `target_sha`. The only
1336 /// engine surface that moves a branch pointer over existing
1337 /// commits — every other mutation appends. Refuses if any commit
1338 /// that would be discarded by the reset is already reachable from
1339 /// a `refs/remotes/*` ref (the engine's definition of "pushed").
1340 ///
1341 /// `target_sha` accepts anything `gix::rev_parse_single` admits:
1342 /// a SHA, an abbreviated SHA, a branch name, a tag. The branch
1343 /// itself (the mount's declared branch) must exist.
1344 ///
1345 /// Refusal codes:
1346 /// - [`EngineError::UnknownMem`] (`UNKNOWN_MEM`)
1347 /// - [`EngineError::UnknownRef`] (`UNKNOWN_REF`) — branch or
1348 /// target ref does not resolve.
1349 /// - [`EngineError::PushedCommitsProtected`]
1350 /// (`PUSHED_COMMITS_PROTECTED`) — at least one discarded commit
1351 /// is pushed. The error carries the offending SHAs verbatim.
1352 /// - [`EngineError::InvalidInput`] (`INVALID_INPUT`) — mem is
1353 /// folder / archive-backed (history rewriting only makes sense
1354 /// for git-branch mounts).
1355 ///
1356 /// Emits a [`crate::engine::events::MemChangedEvent`] on
1357 /// success when the SHA actually changed; the reset's effect is
1358 /// observable through the same change-event surface every commit
1359 /// flows through. Engine's cached `last_known_head` for the
1360 /// affected mount is rewound to the new SHA so the next drift
1361 /// probe doesn't flag the reset as a sibling-writer surprise.
1362 pub fn branch_reset(
1363 &mut self,
1364 mem: &str,
1365 target_sha: &str,
1366 expected_head: Option<&str>,
1367 ) -> Result<crate::ops::BranchResetOutcome, EngineError> {
1368 let mount_idx = self
1369 .mounts
1370 .iter()
1371 .position(|m| m.mount.mem == mem)
1372 .ok_or_else(|| self.unknown_mem_error(mem))?;
1373
1374 // History rewriting is a write — read-only and archive mounts
1375 // refuse before any dispatch (parity with the mutation surface).
1376 if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
1377 return Err(EngineError::ReadOnlyMount(mem.to_string()));
1378 }
1379
1380 let outcome = match &self.mounts[mount_idx].mount.storage {
1381 MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
1382 return Err(EngineError::InvalidInput(format!(
1383 "mem '{mem}' is not git-backed — `memstead_branch_reset` requires a git-branch mount",
1384 )));
1385 }
1386 MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
1387 Some(hook) => (hook.branch_reset)(gitdir, branch, target_sha, expected_head)
1388 .map_err(|e| match e {
1389 BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
1390 let raw = msg.trim_start_matches("UNKNOWN_REF:").trim().to_string();
1391 EngineError::UnknownRef(raw)
1392 }
1393 BackendError::Other(msg) if msg.starts_with("EXPECTED_HEAD_MISMATCH:") => {
1394 let current = msg
1395 .trim_start_matches("EXPECTED_HEAD_MISMATCH:")
1396 .trim()
1397 .to_string();
1398 EngineError::BranchResetHeadMoved {
1399 mem: mem.to_string(),
1400 expected: expected_head.unwrap_or_default().to_string(),
1401 current,
1402 }
1403 }
1404 BackendError::Other(msg)
1405 if msg.starts_with("PUSHED_COMMITS_PROTECTED:") =>
1406 {
1407 let payload =
1408 msg.trim_start_matches("PUSHED_COMMITS_PROTECTED:").trim();
1409 let pushed_shas = payload
1410 .split(',')
1411 .map(|s| s.trim().to_string())
1412 .filter(|s| !s.is_empty())
1413 .collect();
1414 EngineError::PushedCommitsProtected {
1415 mem: mem.to_string(),
1416 target_sha: target_sha.to_string(),
1417 pushed_shas,
1418 }
1419 }
1420 other => EngineError::Backend(other),
1421 })?,
1422 None => {
1423 return Err(EngineError::Backend(BackendError::Other(
1424 "git-branch branch_reset hook not installed (git-branch ops not wired)"
1425 .to_string(),
1426 )));
1427 }
1428 },
1429 };
1430
1431 // Rewind the engine's cached HEAD so subsequent drift probes
1432 // don't surface MEM_RELOADED for the reset we just made.
1433 // Then emit a change event so subscribers see the transition
1434 // (skipping the no-op case where previous == new).
1435 if outcome.previous_sha != outcome.new_sha {
1436 if let Some(state) = self.mounts.get_mut(mount_idx) {
1437 state.last_known_head = Some(outcome.new_sha.clone());
1438 }
1439 let event = crate::engine::events::MemChangedEvent {
1440 mem: mem.to_string(),
1441 head: outcome.new_sha.clone(),
1442 previous: outcome.previous_sha.clone(),
1443 // n_commits stays at 1 for reset events. The wire
1444 // shape is the same `MemChangedEvent` consumers
1445 // already key on; semantics: "the head moved by this
1446 // operation". Replay-aware consumers branch on the
1447 // commit-vs-reset distinction by inspecting the
1448 // produced commit (a reset's new head is an existing
1449 // commit, not a freshly minted one).
1450 n_commits: 1,
1451 };
1452 self.emit_mem_changed(&event);
1453 }
1454 Ok(outcome)
1455 }
1456
1457 /// Cross-mem references that a reset of `mem` to `target_sha` would
1458 /// strand: incoming edges from entities in *other* mems whose target
1459 /// exists at the current head but would not exist at the target
1460 /// commit — entities created after the target, or renamed to their
1461 /// current id after it (the reset re-materialises the old id, so
1462 /// references to the new id dangle either way).
1463 ///
1464 /// A read — computes against the live store and the commit history,
1465 /// moves nothing. The human surface calls this fresh at
1466 /// confirmation-dialog time and warns before `branch_reset`. Sorted
1467 /// (from_id, to_id, rel_type) for stable rendering.
1468 ///
1469 /// Refusals mirror `changes_since`: `UnknownMem`, `InvalidCursor`
1470 /// for an unresolvable `target_sha`, `InvalidInput` for
1471 /// non-git-backed mounts.
1472 pub fn branch_reset_stranded_refs(
1473 &self,
1474 mem: &str,
1475 target_sha: &str,
1476 ) -> Result<Vec<crate::ops::StrandedCrossMemRef>, EngineError> {
1477 use crate::ops::ChangeEnvelope;
1478
1479 let report = self.changes_since(mem, target_sha, None)?;
1480 let mut discarded: std::collections::HashSet<String> = std::collections::HashSet::new();
1481 for change in &report.changes {
1482 match change {
1483 ChangeEnvelope::Added { id, .. } => {
1484 discarded.insert(id.to_string());
1485 }
1486 ChangeEnvelope::Renamed { to_id, .. } => {
1487 discarded.insert(to_id.to_string());
1488 }
1489 ChangeEnvelope::Updated { .. } | ChangeEnvelope::Removed { .. } => {}
1490 }
1491 }
1492 if discarded.is_empty() {
1493 return Ok(Vec::new());
1494 }
1495
1496 let mut stranded: Vec<crate::ops::StrandedCrossMemRef> = self
1497 .store
1498 .all_entities()
1499 .filter(|e| e.mem != mem)
1500 .flat_map(|e| {
1501 e.relationships
1502 .iter()
1503 .filter(|r| discarded.contains(&r.target.to_string()))
1504 .map(|r| crate::ops::StrandedCrossMemRef {
1505 from_id: e.id.to_string(),
1506 from_mem: e.mem.clone(),
1507 to_id: r.target.to_string(),
1508 rel_type: r.rel_type.clone(),
1509 })
1510 .collect::<Vec<_>>()
1511 })
1512 .collect();
1513 stranded.sort_by(|a, b| {
1514 (&a.from_id, &a.to_id, &a.rel_type).cmp(&(&b.from_id, &b.to_id, &b.rel_type))
1515 });
1516 Ok(stranded)
1517 }
1518
1519 /// Two-ref structural diff. Produces a per-entity [`crate::ops::Diff`]
1520 /// comparing the trees at `ref_a` and `ref_b` for the named
1521 /// mem's storage. Folder and archive backends carry no git
1522 /// refs and refuse via [`EngineError::InvalidInput`]; the
1523 /// git-branch backend routes through [`GitBranchOps::diff`] when
1524 /// the git-branch ops are wired.
1525 ///
1526 /// `mem` selects the storage context (the gitdir, for
1527 /// git-branch mounts). `ref_a` / `ref_b` are arbitrary refs the
1528 /// underlying git layer accepts — branch names, commit SHAs, tag
1529 /// names — so cross-mem diffs work via fully-qualified refs
1530 /// (the other mount's declared branch) without a separate API. A
1531 /// bare `HEAD` token re-anchors onto this mem's declared branch.
1532 ///
1533 /// Refusal codes:
1534 /// - [`EngineError::UnknownMem`] (`UNKNOWN_MEM`) — no mount
1535 /// for `mem`.
1536 /// - [`EngineError::UnknownRef`] (`UNKNOWN_REF`) — either ref
1537 /// does not resolve. Surfaces verbatim from the git layer's
1538 /// `rev_parse` refusal.
1539 /// - [`EngineError::RenameSimilarityOutOfRange`] (`INVALID_INPUT`)
1540 /// — `config.rename_similarity` outside `[0.1, 1.0]`.
1541 /// - [`EngineError::InvalidInput`] (`INVALID_INPUT`) — mem is
1542 /// folder or archive-backed (no refs to diff).
1543 pub fn diff(
1544 &self,
1545 mem: &str,
1546 ref_a: &str,
1547 ref_b: &str,
1548 config: Option<crate::ops::DiffConfig>,
1549 ) -> Result<crate::ops::Diff, EngineError> {
1550 let m = self.find_mount(mem)?;
1551 let config = config.unwrap_or_default();
1552
1553 if config.rename_similarity < crate::ops::RENAME_SIMILARITY_MIN
1554 || config.rename_similarity > crate::ops::RENAME_SIMILARITY_MAX
1555 {
1556 return Err(EngineError::RenameSimilarityOutOfRange {
1557 requested: config.rename_similarity,
1558 allowed_min: crate::ops::RENAME_SIMILARITY_MIN,
1559 allowed_max: crate::ops::RENAME_SIMILARITY_MAX,
1560 });
1561 }
1562
1563 match &m.mount.storage {
1564 MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
1565 Err(EngineError::InvalidInput(format!(
1566 "mem '{mem}' is not git-backed — `memstead_diff` requires a git-branch mount",
1567 )))
1568 }
1569 MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
1570 Some(hook) => {
1571 (hook.diff)(gitdir, branch, mem, ref_a, ref_b, &config).map_err(|e| match e {
1572 // Map the standard backend-side "ref not found" shape into the
1573 // typed engine-level refusal. The git-branch dispatcher uses
1574 // `BackendError::Other` with a leading marker so the engine can
1575 // recover the typed code without re-parsing the message.
1576 BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
1577 let raw = msg.trim_start_matches("UNKNOWN_REF:").trim().to_string();
1578 EngineError::UnknownRef(raw)
1579 }
1580 other => EngineError::Backend(other),
1581 })
1582 }
1583 None => Err(EngineError::Backend(BackendError::Other(
1584 "git-branch diff hook not installed (git-branch ops not wired)".to_string(),
1585 ))),
1586 },
1587 }
1588 }
1589}
1590
1591/// Anything that hands out an [`Engine`]: the engine itself, a mutable
1592/// borrow, a boxed engine, or a mutex guard. What [`OperationScope`]
1593/// wraps.
1594pub trait EngineHandle {
1595 fn engine(&self) -> &Engine;
1596 fn engine_mut(&mut self) -> &mut Engine;
1597}
1598
1599impl EngineHandle for Engine {
1600 fn engine(&self) -> &Engine {
1601 self
1602 }
1603 fn engine_mut(&mut self) -> &mut Engine {
1604 self
1605 }
1606}
1607
1608impl EngineHandle for &mut Engine {
1609 fn engine(&self) -> &Engine {
1610 self
1611 }
1612 fn engine_mut(&mut self) -> &mut Engine {
1613 self
1614 }
1615}
1616
1617impl EngineHandle for Box<Engine> {
1618 fn engine(&self) -> &Engine {
1619 self
1620 }
1621 fn engine_mut(&mut self) -> &mut Engine {
1622 self
1623 }
1624}
1625
1626impl EngineHandle for std::sync::MutexGuard<'_, Engine> {
1627 fn engine(&self) -> &Engine {
1628 self
1629 }
1630 fn engine_mut(&mut self) -> &mut Engine {
1631 self
1632 }
1633}
1634
1635/// The scope of one operation against the engine, and the only way
1636/// the reload-before-operation notices reach a response.
1637///
1638/// [`Engine::reload_if_stale`] runs before every operation and, when
1639/// it reloaded a mem a sibling had advanced, records a
1640/// [`crate::ops::MemChangedNotice`] describing the delta. Until
1641/// 2026-09-11 those notices accumulated on the engine and every
1642/// response builder had to remember to drain them, or the next
1643/// operation's response carried a notice that was not its own (the
1644/// hazard the old drain's doc comment named, guarded by convention at
1645/// some fifty call sites). Now the notices belong to a scope: opening
1646/// one ([`OperationScope::begin`]) discards whatever an unscoped
1647/// caller left behind, [`OperationScope::finish`] hands the notices
1648/// out as a value together with the engine handle, and dropping a
1649/// scope without finishing discards them. No operation can inherit
1650/// another operation's notice, and there is no method on the engine
1651/// that hands accumulated notices out on demand.
1652///
1653/// The scope derefs to the engine, so a handler uses it exactly as it
1654/// used the engine handle before.
1655#[must_use = "an operation scope hands its notices out through `finish`; dropping it discards them"]
1656pub struct OperationScope<G: EngineHandle> {
1657 inner: Option<G>,
1658}
1659
1660impl<G: EngineHandle> OperationScope<G> {
1661 /// Open the scope: whatever notices an unscoped caller left on the
1662 /// engine are discarded first, so this operation starts clean.
1663 pub fn begin(mut handle: G) -> Self {
1664 handle.engine_mut().pending_mem_changed.clear();
1665 Self {
1666 inner: Some(handle),
1667 }
1668 }
1669
1670 /// Close the scope: the engine handle comes back together with the
1671 /// notices this operation's reloads recorded, in order.
1672 pub fn finish(mut self) -> (G, Vec<crate::ops::MemChangedNotice>) {
1673 let mut handle = self
1674 .inner
1675 .take()
1676 .expect("an operation scope is finished at most once");
1677 let notices = std::mem::take(&mut handle.engine_mut().pending_mem_changed);
1678 (handle, notices)
1679 }
1680}
1681
1682impl<G: EngineHandle> std::ops::Deref for OperationScope<G> {
1683 type Target = Engine;
1684 fn deref(&self) -> &Engine {
1685 self.inner
1686 .as_ref()
1687 .expect("an operation scope holds its engine until finished")
1688 .engine()
1689 }
1690}
1691
1692impl<G: EngineHandle> std::ops::DerefMut for OperationScope<G> {
1693 fn deref_mut(&mut self) -> &mut Engine {
1694 self.inner
1695 .as_mut()
1696 .expect("an operation scope holds its engine until finished")
1697 .engine_mut()
1698 }
1699}
1700
1701impl<G: EngineHandle> Drop for OperationScope<G> {
1702 fn drop(&mut self) {
1703 if let Some(handle) = self.inner.as_mut() {
1704 handle.engine_mut().pending_mem_changed.clear();
1705 }
1706 }
1707}
1708
1709#[cfg(test)]
1710mod remote_status_source_scan;
1711#[cfg(test)]
1712mod tests;