Skip to main content

memstead_base/engine/
apply_commit.rs

1//! Apply a [`CommitEnvelope`] to the in-memory store.
2//!
3//! Distinct from the engine's git-touching mutation paths
4//! ([`crate::engine::mutation`]): `apply_external_commit` materializes
5//! changes the engine did not author. The wire envelope arrives from
6//! some external producer (the bridge today; future Node / Python
7//! adapters) and replays the per-entity changes against the [`Store`]
8//! without producing a new commit. Routes:
9//!
10//! - WASM clients receive envelopes over the bridge wire and call this
11//!   method to keep their in-memory mirror in step with the server.
12//! - Native test setups use it to seed a known graph state without
13//!   running the full storage pipeline.
14//! - A future replay tool reads a stream of envelopes back from disk
15//!   and reconstructs the graph at a point in history.
16//!
17//! Per-change semantics:
18//!
19//! - `Added` / `Modified` → parse the new body, upsert into the store,
20//!   re-emit explicit relationship edges. Parse failures abort the
21//!   entire envelope (the post-state must be coherent — a partial
22//!   apply would leave the store wedged between two SHAs).
23//! - `Deleted` → drop the entity and cascade its edges.
24//! - `Renamed` → drop the source entity, then parse + upsert the new
25//!   body at the new id. We do *not* call [`Store::rename_node`]
26//!   because the wire content is authoritative — the new body may
27//!   carry a different relationship section than the old one did.
28//!
29//! Schema-validation is *soft*: a parse
30//! failure refuses (the entity can't be loaded at all), but
31//! schema-level warnings (dangling wiki-links, unknown rel-types in
32//! the relationships section) do not refuse — the server is the
33//! authority on schema, the client mirrors what arrives.
34//!
35//! HEAD cursor + subscriber notification: after a successful apply
36//! the engine's cached `last_known_head` for the affected mount
37//! advances to the envelope SHA, and one [`MemChangedEvent`] fires
38//! to every subscriber. Same shape every other mem-advance event
39//! flows through.
40
41use crate::engine::{Engine, EngineError, MemChangedEvent};
42use crate::entity::id::file_path_to_id;
43use crate::entity::loader::parse_entries;
44use crate::entity::source::SourceEntry;
45use crate::entity::store_builder::push_entities_into_store;
46use crate::ops::{CommitEnvelope, EntityChange};
47
48impl Engine {
49    /// Replay an externally-produced commit envelope into the
50    /// in-memory store.
51    ///
52    /// Refuses with [`EngineError::UnknownMem`] when the envelope
53    /// names a mem the engine has no mount for. Parse failures on
54    /// any change variant surface as [`EngineError::Parse`] and abort
55    /// the apply before any store mutation lands — the post-state is
56    /// either coherent at the envelope SHA or unchanged. (The store
57    /// mutation loop below uses a staged scratch list precisely to
58    /// preserve this all-or-nothing property; do not refactor it
59    /// into per-change in-place mutations without restoring an
60    /// equivalent guarantee.)
61    ///
62    /// Empty `changes` is a valid envelope: the head cursor advances
63    /// and a `MemChangedEvent` fires, but no store mutation
64    /// happens. Lets replay drivers signal "we saw a commit, here is
65    /// its SHA, no entity-level changes" — useful for empty commits
66    /// (e.g. tag-only or merge commits without tree changes).
67    pub fn apply_external_commit(&mut self, envelope: &CommitEnvelope) -> Result<(), EngineError> {
68        let mem = envelope.mem.as_str();
69
70        // 1. Resolve mount + schema. Unknown mem refuses before any
71        //    parse work — same idempotent shape as `reload_one_mem`.
72        let mount_idx = self
73            .mounts
74            .iter()
75            .position(|m| m.mount.mem == mem)
76            .ok_or_else(|| self.unknown_mem_error(mem))?;
77        let schema = self
78            .schemas
79            .get(mem)
80            .cloned()
81            .ok_or_else(|| self.unknown_mem_error(mem))?;
82
83        // 2. Walk the changes. Stage parse outputs so a parse failure
84        //    on a late change rolls back the entire apply (the store
85        //    remains untouched until the second loop below). Deletions
86        //    and rename-source removals stage too — they're just paths.
87        let mut to_upsert: Vec<SourceEntry> = Vec::new();
88        let mut to_remove: Vec<String> = Vec::new();
89        for change in &envelope.changes {
90            match change {
91                EntityChange::Added { path, content }
92                | EntityChange::Modified { path, content } => {
93                    to_upsert.push(SourceEntry {
94                        relative_path: path.clone(),
95                        source_path: std::path::PathBuf::from(path.clone()),
96                        content: content.clone(),
97                    });
98                }
99                EntityChange::Deleted { path } => {
100                    to_remove.push(path.clone());
101                }
102                EntityChange::Renamed { from, to, content } => {
103                    to_remove.push(from.clone());
104                    to_upsert.push(SourceEntry {
105                        relative_path: to.clone(),
106                        source_path: std::path::PathBuf::from(to.clone()),
107                        content: content.clone(),
108                    });
109                }
110            }
111        }
112
113        // 3. Parse the staged adds/modifies/rename-targets against the
114        //    mem schema. Parse errors abort before the store sees a
115        //    mutation. `parse_entries` collects per-file errors into
116        //    `LoadResult::errors`; on `apply_external_commit` semantics
117        //    we treat any parse failure as a hard refuse — the client
118        //    cannot half-apply a commit.
119        let load_result = parse_entries(to_upsert, Vec::new(), mem, schema.as_ref());
120        if let Some((path, msg)) = load_result.errors.into_iter().next() {
121            return Err(EngineError::ParseAfterWrite(format!(
122                "apply_external_commit: failed to parse '{}' in mem '{}': {}",
123                path.display(),
124                mem,
125                msg
126            )));
127        }
128
129        // 4. Mutate the store. Removals first so a rename's
130        //    (from, to) pair where `to == from + suffix-rename`
131        //    doesn't wipe the just-inserted new entity.
132        for path in &to_remove {
133            let id = file_path_to_id(path, mem);
134            self.store.remove(&id);
135        }
136        // Attach file_path on each parsed entity to mirror the
137        // boot/reload contract — handlers that surface
138        // `Entity::file_path` to consumers (e.g. health, export) see
139        // the same value the source pipeline would have produced.
140        let mut parsed = load_result.entities;
141        for result in parsed.iter_mut() {
142            result.entity.file_path = result.entity.id.0.clone();
143        }
144        // Mutation-path call site → no `LoadCollector`; matches the
145        // documented invariant in `push_entities_into_store` (load
146        // sites emit drift warnings, mutation sites stay silent).
147        // The fallback-schema parameter is underscored inside the
148        // helper (no longer consulted for edge emission); the
149        // engine-wide sentinel is the historical pick here.
150        let fallback = crate::engine_fallback_type();
151        push_entities_into_store(&mut self.store, parsed, fallback.as_ref(), None);
152
153        // 5. Advance the cached head + invalidate memos so the next
154        //    read sees the new state.
155        let previous = self
156            .mounts
157            .get(mount_idx)
158            .and_then(|m| m.last_known_head.clone())
159            .unwrap_or_default();
160        if let Some(state) = self.mounts.get_mut(mount_idx) {
161            state.last_known_head = Some(envelope.sha.clone());
162        }
163        // The caller applied the commit itself: it has seen it.
164        self.caller_saw_own_write(mem, &previous, &envelope.sha);
165        self.invalidate_communities();
166        #[cfg(not(target_arch = "wasm32"))]
167        self.invalidate_search_indexes();
168
169        // 6. Emit one `MemChangedEvent` so subscribers see the
170        //    transition. Same shape `record_self_write` and
171        //    `branch_reset` use.
172        if previous != envelope.sha {
173            let event = MemChangedEvent {
174                mem: mem.to_string(),
175                head: envelope.sha.clone(),
176                previous,
177                n_commits: 1,
178            };
179            self.emit_mem_changed(&event);
180        }
181        Ok(())
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::backend::MemBackend;
189    use crate::engine::test_helpers::*;
190    use crate::entity::EntityId;
191    use crate::storage::FilesystemBackend;
192    use std::collections::BTreeMap;
193    use std::sync::{Arc, Mutex};
194    use tempfile::TempDir;
195
196    fn empty_folder_engine(tmp: &TempDir, mem: &str) -> Engine {
197        let mem_dir = tmp.path().to_path_buf();
198        let writer = FilesystemBackend::new(mem_dir.clone());
199        Engine::from_mounts(vec![(
200            folder_mount(mem, mem_dir),
201            Box::new(writer) as Box<dyn MemBackend>,
202        )])
203        .unwrap()
204    }
205
206    fn envelope(mem: &str, sha: &str, parent: &str, changes: Vec<EntityChange>) -> CommitEnvelope {
207        CommitEnvelope {
208            sha: sha.to_string(),
209            parent: parent.to_string(),
210            mem: mem.to_string(),
211            timestamp: "2026-05-19T10:00:00Z".to_string(),
212            trailers: BTreeMap::new(),
213            changes,
214        }
215    }
216
217    fn well_formed_body(title: &str) -> String {
218        format!(
219            "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# {title}\n\n## Identity\n\n{title}\n"
220        )
221    }
222
223    #[test]
224    fn apply_external_commit_unknown_mem_refuses() {
225        let tmp = TempDir::new().unwrap();
226        let mut engine = empty_folder_engine(&tmp, "specs");
227        let env = envelope("missing", "deadbeef", "", vec![]);
228        let err = engine.apply_external_commit(&env).unwrap_err();
229        assert_eq!(err.code(), "UNKNOWN_MEM");
230    }
231
232    #[test]
233    fn apply_external_commit_added_lands_entity_in_store() {
234        let tmp = TempDir::new().unwrap();
235        let mut engine = empty_folder_engine(&tmp, "specs");
236        let env = envelope(
237            "specs",
238            "abc123",
239            "",
240            vec![EntityChange::Added {
241                path: "alpha.md".to_string(),
242                content: well_formed_body("Alpha"),
243            }],
244        );
245        engine.apply_external_commit(&env).unwrap();
246        let id = EntityId::new("specs", "alpha");
247        assert!(
248            engine.get_entity(&id).is_some(),
249            "expected 'specs--alpha' in store after Added apply"
250        );
251    }
252
253    #[test]
254    fn apply_external_commit_modified_replaces_existing_body() {
255        let tmp = TempDir::new().unwrap();
256        let mut engine = empty_folder_engine(&tmp, "specs");
257        // First apply seeds the entity.
258        engine
259            .apply_external_commit(&envelope(
260                "specs",
261                "sha1",
262                "",
263                vec![EntityChange::Added {
264                    path: "alpha.md".to_string(),
265                    content: well_formed_body("Alpha-v0"),
266                }],
267            ))
268            .unwrap();
269        // Second apply mutates it.
270        engine
271            .apply_external_commit(&envelope(
272                "specs",
273                "sha2",
274                "sha1",
275                vec![EntityChange::Modified {
276                    path: "alpha.md".to_string(),
277                    content: well_formed_body("Alpha-v1"),
278                }],
279            ))
280            .unwrap();
281        let id = EntityId::new("specs", "alpha");
282        let entity = engine.get_entity(&id).expect("alpha must still exist");
283        assert_eq!(entity.title, "Alpha-v1");
284    }
285
286    #[test]
287    fn apply_external_commit_deleted_removes_entity_from_store() {
288        let tmp = TempDir::new().unwrap();
289        let mut engine = empty_folder_engine(&tmp, "specs");
290        engine
291            .apply_external_commit(&envelope(
292                "specs",
293                "sha1",
294                "",
295                vec![EntityChange::Added {
296                    path: "alpha.md".to_string(),
297                    content: well_formed_body("Alpha"),
298                }],
299            ))
300            .unwrap();
301        engine
302            .apply_external_commit(&envelope(
303                "specs",
304                "sha2",
305                "sha1",
306                vec![EntityChange::Deleted {
307                    path: "alpha.md".to_string(),
308                }],
309            ))
310            .unwrap();
311        let id = EntityId::new("specs", "alpha");
312        assert!(
313            engine.get_entity(&id).is_none(),
314            "expected 'specs--alpha' removed after Deleted apply"
315        );
316    }
317
318    #[test]
319    fn apply_external_commit_renamed_moves_entity_to_new_id() {
320        let tmp = TempDir::new().unwrap();
321        let mut engine = empty_folder_engine(&tmp, "specs");
322        engine
323            .apply_external_commit(&envelope(
324                "specs",
325                "sha1",
326                "",
327                vec![EntityChange::Added {
328                    path: "alpha.md".to_string(),
329                    content: well_formed_body("Alpha"),
330                }],
331            ))
332            .unwrap();
333        engine
334            .apply_external_commit(&envelope(
335                "specs",
336                "sha2",
337                "sha1",
338                vec![EntityChange::Renamed {
339                    from: "alpha.md".to_string(),
340                    to: "alpha-renamed.md".to_string(),
341                    content: well_formed_body("Alpha Renamed"),
342                }],
343            ))
344            .unwrap();
345        let old_id = EntityId::new("specs", "alpha");
346        let new_id = EntityId::new("specs", "alpha-renamed");
347        assert!(engine.get_entity(&old_id).is_none(), "old id must be gone");
348        assert!(
349            engine.get_entity(&new_id).is_some(),
350            "new id must be present"
351        );
352    }
353
354    #[test]
355    fn apply_external_commit_mixed_changes_apply_atomically() {
356        let tmp = TempDir::new().unwrap();
357        let mut engine = empty_folder_engine(&tmp, "specs");
358        // Seed the mem with two entities.
359        engine
360            .apply_external_commit(&envelope(
361                "specs",
362                "sha1",
363                "",
364                vec![
365                    EntityChange::Added {
366                        path: "alpha.md".to_string(),
367                        content: well_formed_body("Alpha"),
368                    },
369                    EntityChange::Added {
370                        path: "beta.md".to_string(),
371                        content: well_formed_body("Beta"),
372                    },
373                ],
374            ))
375            .unwrap();
376        // Mix: delete one, modify the other, add a third.
377        engine
378            .apply_external_commit(&envelope(
379                "specs",
380                "sha2",
381                "sha1",
382                vec![
383                    EntityChange::Deleted {
384                        path: "alpha.md".to_string(),
385                    },
386                    EntityChange::Modified {
387                        path: "beta.md".to_string(),
388                        content: well_formed_body("Beta-v2"),
389                    },
390                    EntityChange::Added {
391                        path: "gamma.md".to_string(),
392                        content: well_formed_body("Gamma"),
393                    },
394                ],
395            ))
396            .unwrap();
397        let alpha = EntityId::new("specs", "alpha");
398        let beta = EntityId::new("specs", "beta");
399        let gamma = EntityId::new("specs", "gamma");
400        assert!(engine.get_entity(&alpha).is_none());
401        assert_eq!(engine.get_entity(&beta).unwrap().title, "Beta-v2");
402        assert!(engine.get_entity(&gamma).is_some());
403    }
404
405    #[test]
406    fn apply_external_commit_permissive_parser_accepts_minimal_body() {
407        // The parse layer used by `apply_external_commit` is
408        // intentionally permissive — `parse_markdown` does not refuse
409        // missing frontmatter or missing titles (those `ParseError`
410        // variants only fire under the strict validator). This is the
411        // documented design: schema validation is soft — the server is
412        // the authority, the client shows what it receives. Pin the
413        // behavior so a future tightening here surfaces as an
414        // intentional decision.
415        let tmp = TempDir::new().unwrap();
416        let mut engine = empty_folder_engine(&tmp, "specs");
417        let bare_body = "# Bare\n\nNo frontmatter, no schema sections.\n";
418        engine
419            .apply_external_commit(&envelope(
420                "specs",
421                "sha1",
422                "",
423                vec![EntityChange::Added {
424                    path: "bare.md".to_string(),
425                    content: bare_body.to_string(),
426                }],
427            ))
428            .unwrap();
429        let id = EntityId::new("specs", "bare");
430        let entity = engine
431            .get_entity(&id)
432            .expect("permissive parser must produce an entity even without frontmatter");
433        assert_eq!(entity.title, "Bare");
434    }
435
436    #[test]
437    fn apply_external_commit_emits_mem_changed_event_to_subscribers() {
438        let tmp = TempDir::new().unwrap();
439        let mut engine = empty_folder_engine(&tmp, "specs");
440        let observed = Arc::new(Mutex::new(Vec::<MemChangedEvent>::new()));
441        let observed_clone = observed.clone();
442        let _handle = engine
443            .subscribe_mem_changes(
444                "specs",
445                Arc::new(move |event| {
446                    observed_clone.lock().unwrap().push(event.clone());
447                }),
448            )
449            .unwrap();
450        engine
451            .apply_external_commit(&envelope(
452                "specs",
453                "sha-new",
454                "",
455                vec![EntityChange::Added {
456                    path: "alpha.md".to_string(),
457                    content: well_formed_body("Alpha"),
458                }],
459            ))
460            .unwrap();
461        let events = observed.lock().unwrap();
462        assert_eq!(events.len(), 1, "expected one MemChangedEvent");
463        assert_eq!(events[0].head, "sha-new");
464        assert_eq!(events[0].mem, "specs");
465        assert_eq!(events[0].n_commits, 1);
466    }
467
468    #[test]
469    fn apply_external_commit_empty_changes_still_advances_head() {
470        let tmp = TempDir::new().unwrap();
471        let mut engine = empty_folder_engine(&tmp, "specs");
472        let observed = Arc::new(Mutex::new(Vec::<MemChangedEvent>::new()));
473        let observed_clone = observed.clone();
474        let _handle = engine
475            .subscribe_mem_changes(
476                "specs",
477                Arc::new(move |event| {
478                    observed_clone.lock().unwrap().push(event.clone());
479                }),
480            )
481            .unwrap();
482        engine
483            .apply_external_commit(&envelope("specs", "empty-commit-sha", "", vec![]))
484            .unwrap();
485        let events = observed.lock().unwrap();
486        assert_eq!(events.len(), 1, "empty envelope must still emit one event");
487        assert_eq!(events[0].head, "empty-commit-sha");
488    }
489}