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