Skip to main content

memstead_base/storage/
in_memory.rs

1//! In-memory [`MemBackend`](crate::backend::MemBackend) — the
2//! writable, filesystem- and git-free companion to the folder backend.
3//!
4//! The mem lives entirely in RAM: committed entity bytes, the staged
5//! mutation buffer, the provenance log, and the per-mem config all
6//! sit on one [`Mutex`]-guarded [`State`]. Creating a backend
7//! provisions nothing on disk; dropping it releases the mem with no
8//! residue to clean up. Built to serve ephemeral per-session
9//! playground mems the session server spins up and tears down on
10//! demand.
11//!
12//! ## Why model on the folder backend
13//!
14//! The folder backend ([`super::filesystem::FilesystemBackend`]) is
15//! the closest sibling: it buffers mutations until commit, mints a
16//! synthetic history-free commit-id, and keeps a sidecar provenance
17//! log. This backend mirrors that contract one-for-one — same
18//! buffer-then-commit semantics, same `read`-sees-pending ordering,
19//! same path-rejection rules (it reuses
20//! [`super::filesystem::normalise_rel_path`]), same synthetic commit-id
21//! ([`super::filesystem::make_commit_id`]) — so the engine produces
22//! identical engine-level outcomes regardless of which of the two
23//! serves a mount. The only difference is the substrate: a `HashMap`
24//! in RAM instead of a directory tree on disk.
25//!
26//! ## No durable history
27//!
28//! Like the folder backend, this one has no commit history:
29//! [`MemBackend::current_head`](crate::backend::MemBackend::current_head)
30//! inherits the trait default returning `Ok(None)` rather than
31//! fabricating a git-like head, and
32//! `commit_with_expected_parent` inherits the default that ignores the
33//! pin and delegates to [`commit`](crate::backend::MemBackend::commit).
34//! Optimistic locking is unaffected — the engine enforces the
35//! `expected_hash` CAS above the backend, so a stale hash trips the
36//! same `HASH_MISMATCH` here as on any other backend.
37
38use std::collections::HashMap;
39use std::path::{Path, PathBuf};
40use std::sync::Mutex;
41
42use super::CommitId;
43use super::filesystem::{make_commit_id, normalise_rel_path};
44use crate::backend::{BackendError, MemBackend};
45use crate::filesystem::changelog::format_rfc3339_utc;
46use crate::provenance::Provenance;
47use crate::vcs::CommitContext;
48
49/// Per-path terminal state for the staged op buffer. Move resolves at
50/// call time into a `Delete(from)` + `Upsert(to, bytes)` pair, so
51/// commit-time replay only ever sees these two states — mirroring the
52/// folder backend's [`super::filesystem`] buffer shape.
53enum PendingState {
54    Upsert(Vec<u8>),
55    Delete,
56}
57
58/// Every byte the mem holds, behind one lock. Committed bytes are
59/// the in-RAM analogue of the folder backend's on-disk directory; the
60/// pending buffer folds into them on [`commit`](MemBackend::commit).
61#[derive(Default)]
62struct State {
63    /// Committed entity bytes keyed by normalised mem-relative path
64    /// (forward-slash). The in-RAM stand-in for the folder backend's
65    /// directory tree.
66    committed: HashMap<String, Vec<u8>>,
67    /// Staged mutations not yet committed. Cleared on commit or
68    /// [`discard_pending`](MemBackend::discard_pending).
69    pending: HashMap<String, PendingState>,
70    /// Provenance records staged for the next commit; they land in
71    /// `provenance` with it and are dropped with a discard.
72    pending_provenance: Vec<Provenance>,
73    /// Append-only provenance log. The folder backend persists this as
74    /// JSONL under `.memstead/changes.jsonl`; here it is a `Vec` in RAM.
75    provenance: Vec<Provenance>,
76    /// Per-mem `.memstead/config.json` bytes once written. `None`
77    /// until the create path writes the config.
78    config: Option<Vec<u8>>,
79}
80
81/// Writable mem backend whose entire state lives in memory. See the
82/// module docs for the contract it shares with the folder backend.
83pub struct InMemoryBackend {
84    state: Mutex<State>,
85}
86
87impl InMemoryBackend {
88    /// Build an empty in-memory mem. Nothing is provisioned on disk;
89    /// the mem exists only for as long as this backend is held.
90    pub fn new() -> Self {
91        Self {
92            state: Mutex::new(State::default()),
93        }
94    }
95
96    fn lock(&self) -> Result<std::sync::MutexGuard<'_, State>, BackendError> {
97        self.state
98            .lock()
99            .map_err(|_| BackendError::Other("in-memory backend state poisoned".to_string()))
100    }
101}
102
103impl Default for InMemoryBackend {
104    fn default() -> Self {
105        Self::new()
106    }
107}
108
109/// Append a provenance record with its timestamp clamped strictly past the
110/// last stored one at the cursor's millisecond grain, as the folder
111/// backend's ledger does: a cursor equal to one record's timestamp then
112/// never hides a later record that formats to the same millisecond.
113fn push_monotonic(log: &mut Vec<Provenance>, mut record: Provenance) {
114    let last = log.last().map(|r| r.timestamp);
115    record.timestamp = crate::filesystem::changelog::monotonic_ts(last, record.timestamp);
116    log.push(record);
117}
118
119impl MemBackend for InMemoryBackend {
120    fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError> {
121        // Committed state only — pending writes are not listable until
122        // they commit, matching the folder backend (which walks the
123        // on-disk tree and ignores its in-memory buffer). Entity-bearing
124        // `.md` files outside the `.memstead/` umbrella only, so the
125        // engine-owned anchors sidecar (`.memstead/anchors.json`) — and
126        // any other `.memstead/` member — is never mis-parsed as an
127        // entity. Mirrors the git-branch and folder backends' filters.
128        let state = self.lock()?;
129        Ok(state
130            .committed
131            .keys()
132            .filter(|k| k.ends_with(".md") && !k.starts_with(".memstead/"))
133            .map(PathBuf::from)
134            .collect())
135    }
136
137    fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError> {
138        let key = normalise_rel_path(rel_path)?;
139        let state = self.lock()?;
140        // Pending buffer wins over committed — a read after an
141        // uncommitted write sees the staged bytes, and a read after a
142        // staged delete sees `None`. Same ordering as the folder
143        // backend's "pending first, then disk".
144        if let Some(staged) = state.pending.get(&key) {
145            return Ok(match staged {
146                PendingState::Upsert(bytes) => Some(bytes.clone()),
147                PendingState::Delete => None,
148            });
149        }
150        Ok(state.committed.get(&key).cloned())
151    }
152
153    fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError> {
154        let key = normalise_rel_path(rel_path)?;
155        let mut state = self.lock()?;
156        state
157            .pending
158            .insert(key, PendingState::Upsert(content.to_vec()));
159        Ok(())
160    }
161
162    fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError> {
163        let key = normalise_rel_path(rel_path)?;
164        let mut state = self.lock()?;
165        state.pending.insert(key, PendingState::Delete);
166        Ok(())
167    }
168
169    fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError> {
170        let from_key = normalise_rel_path(from)?;
171        let to_key = normalise_rel_path(to)?;
172        let mut state = self.lock()?;
173
174        // The target is checked before the source is touched, so a
175        // refused move leaves the staged state exactly as it was.
176        match state.pending.get(&to_key) {
177            Some(PendingState::Upsert(_)) => {
178                return Err(BackendError::Other(format!(
179                    "move target {} already has a pending write",
180                    to.display()
181                )));
182            }
183            Some(PendingState::Delete) => {}
184            None => {
185                if state.committed.contains_key(&to_key) {
186                    return Err(BackendError::Other(format!(
187                        "move target {} already exists",
188                        to.display()
189                    )));
190                }
191            }
192        }
193
194        // Resolve the source bytes from the pending buffer if staged,
195        // otherwise from committed state — mirroring the folder
196        // backend's `read_source`.
197        let bytes = match state.pending.remove(&from_key) {
198            Some(PendingState::Upsert(b)) => b,
199            Some(PendingState::Delete) => {
200                state.pending.insert(from_key, PendingState::Delete);
201                return Err(BackendError::Other(format!(
202                    "move source {} is already pending deletion",
203                    from.display()
204                )));
205            }
206            None => match state.committed.get(&from_key) {
207                Some(b) => b.clone(),
208                None => {
209                    return Err(BackendError::Other(format!(
210                        "move source {} does not exist",
211                        from.display()
212                    )));
213                }
214            },
215        };
216
217        state.pending.insert(from_key, PendingState::Delete);
218        state.pending.insert(to_key, PendingState::Upsert(bytes));
219        Ok(())
220    }
221
222    fn discard_pending(&self) -> Result<(), BackendError> {
223        let mut state = self.lock()?;
224        state.pending.clear();
225        state.pending_provenance.clear();
226        Ok(())
227    }
228
229    fn commit(&self, _message: &str, _ctx: &CommitContext<'_>) -> Result<CommitId, BackendError> {
230        let mut state = self.lock()?;
231        let ops: Vec<(String, PendingState)> = state.pending.drain().collect();
232        for (key, op) in ops {
233            match op {
234                PendingState::Upsert(bytes) => {
235                    state.committed.insert(key, bytes);
236                }
237                PendingState::Delete => {
238                    state.committed.remove(&key);
239                }
240            }
241        }
242        let records = std::mem::take(&mut state.pending_provenance);
243        for record in records {
244            push_monotonic(&mut state.provenance, record);
245        }
246        Ok(make_commit_id())
247    }
248
249    fn stage_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
250        let mut state = self.lock()?;
251        state.pending_provenance.push(record.clone());
252        Ok(())
253    }
254
255    fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
256        let mut state = self.lock()?;
257        push_monotonic(&mut state.provenance, record.clone());
258        Ok(())
259    }
260
261    fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError> {
262        let state = self.lock()?;
263        // Cursor is an opaque RFC-3339 timestamp string, same as the
264        // folder backend's `ts` field. String compare matches its
265        // `ts_str <= c` filter — lexical order of RFC-3339 UTC strings
266        // is chronological.
267        let out = state
268            .provenance
269            .iter()
270            .filter(|r| match cursor {
271                Some(c) => format_rfc3339_utc(r.timestamp).as_str() > c,
272                None => true,
273            })
274            .cloned()
275            .collect();
276        Ok(out)
277    }
278
279    fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
280        // Read via the entity path so pending-buffer precedence applies —
281        // a staged sidecar write is visible before its commit, symmetric
282        // with the git-branch backend.
283        self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
284    }
285
286    fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
287        // Stage into the same pending buffer entity writes use, so the
288        // next commit folds entity + sidecar together. `list_entities`
289        // filters `.memstead/`, so the sidecar never lists as an entity.
290        self.write_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH), bytes)
291    }
292
293    fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
294        let state = self.lock()?;
295        Ok(state.config.clone())
296    }
297
298    fn write_mem_config(
299        &self,
300        bytes: &[u8],
301        _ctx: &crate::vcs::CommitContext<'_>,
302    ) -> Result<(), BackendError> {
303        // Writable backend — unlike the sealed archive (whose default
304        // impl returns `Sealed`), the in-memory mem stores the config
305        // so the create path can write it and boot can read it back.
306        let mut state = self.lock()?;
307        state.config = Some(bytes.to_vec());
308        Ok(())
309    }
310
311    /// The compare and the write run under the one state lock, so they are
312    /// a single step against every other caller of this backend.
313    fn write_mem_config_cas(
314        &self,
315        expected: Option<&[u8]>,
316        bytes: &[u8],
317        _ctx: &crate::vcs::CommitContext<'_>,
318    ) -> Result<bool, BackendError> {
319        let mut state = self.lock()?;
320        if let Some(expected) = expected
321            && state.config.as_deref() != Some(expected)
322        {
323            return Ok(false);
324        }
325        state.config = Some(bytes.to_vec());
326        Ok(true)
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use crate::provenance::ProvenanceKind;
334    use crate::vcs::{Actor, ClientId, CommitContext};
335    use std::time::{Duration, UNIX_EPOCH};
336
337    fn ctx<'a>() -> CommitContext<'a> {
338        CommitContext {
339            actor: Actor::Cli,
340            client: Some(ClientId {
341                name: "claude-code".to_string(),
342                version: "0.1.0".to_string(),
343            }),
344            tool: Some("test"),
345            note: None,
346            role: Default::default(),
347            identity: None,
348            logical_operation_id: None,
349            entity_ids: None,
350            proposal: None,
351        }
352    }
353
354    #[test]
355    fn write_then_commit_round_trips_in_ram() {
356        let b = InMemoryBackend::new();
357        b.write_entity(Path::new("notes/hello.md"), b"# hi\n")
358            .unwrap();
359        let id = b.commit("c1", &ctx()).unwrap();
360        assert!(!id.is_empty());
361        assert_eq!(
362            b.read_entity(Path::new("notes/hello.md")).unwrap(),
363            Some(b"# hi\n".to_vec())
364        );
365        assert_eq!(
366            b.list_entities().unwrap(),
367            vec![PathBuf::from("notes/hello.md")]
368        );
369    }
370
371    #[test]
372    fn read_sees_pending_write_before_commit() {
373        let b = InMemoryBackend::new();
374        b.write_entity(Path::new("a.md"), b"staged").unwrap();
375        // Visible to read, not yet to list (uncommitted).
376        assert_eq!(
377            b.read_entity(Path::new("a.md")).unwrap(),
378            Some(b"staged".to_vec())
379        );
380        assert!(b.list_entities().unwrap().is_empty());
381    }
382
383    #[test]
384    fn delete_removes_committed_path() {
385        let b = InMemoryBackend::new();
386        b.write_entity(Path::new("a.md"), b"a").unwrap();
387        b.write_entity(Path::new("b.md"), b"b").unwrap();
388        b.commit("seed", &ctx()).unwrap();
389        b.delete_entity(Path::new("a.md")).unwrap();
390        b.commit("drop", &ctx()).unwrap();
391        assert_eq!(b.read_entity(Path::new("a.md")).unwrap(), None);
392        assert_eq!(
393            b.read_entity(Path::new("b.md")).unwrap(),
394            Some(b"b".to_vec())
395        );
396    }
397
398    #[test]
399    fn delete_of_missing_path_is_idempotent() {
400        let b = InMemoryBackend::new();
401        b.delete_entity(Path::new("ghost.md")).unwrap();
402        b.commit("noop", &ctx()).unwrap();
403        assert_eq!(b.read_entity(Path::new("ghost.md")).unwrap(), None);
404    }
405
406    #[test]
407    fn move_renames_committed_path() {
408        let b = InMemoryBackend::new();
409        b.write_entity(Path::new("from.md"), b"payload").unwrap();
410        b.commit("seed", &ctx()).unwrap();
411        b.move_entity(Path::new("from.md"), Path::new("nested/to.md"))
412            .unwrap();
413        b.commit("rename", &ctx()).unwrap();
414        assert_eq!(b.read_entity(Path::new("from.md")).unwrap(), None);
415        assert_eq!(
416            b.read_entity(Path::new("nested/to.md")).unwrap(),
417            Some(b"payload".to_vec())
418        );
419    }
420
421    #[test]
422    fn move_carries_pending_upsert_bytes() {
423        let b = InMemoryBackend::new();
424        b.write_entity(Path::new("a.md"), b"alpha").unwrap();
425        b.move_entity(Path::new("a.md"), Path::new("b.md")).unwrap();
426        b.commit("write+move", &ctx()).unwrap();
427        assert_eq!(b.read_entity(Path::new("a.md")).unwrap(), None);
428        assert_eq!(
429            b.read_entity(Path::new("b.md")).unwrap(),
430            Some(b"alpha".to_vec())
431        );
432    }
433
434    #[test]
435    fn move_missing_source_errors() {
436        let b = InMemoryBackend::new();
437        let err = b
438            .move_entity(Path::new("ghost.md"), Path::new("here.md"))
439            .unwrap_err();
440        assert!(matches!(err, BackendError::Other(_)));
441    }
442
443    #[test]
444    fn move_onto_a_committed_target_refuses_and_keeps_both_files() {
445        let b = InMemoryBackend::new();
446        b.write_entity(Path::new("from.md"), b"source").unwrap();
447        b.write_entity(Path::new("to.md"), b"target").unwrap();
448        b.commit("seed", &ctx()).unwrap();
449        b.move_entity(Path::new("from.md"), Path::new("to.md"))
450            .unwrap_err();
451        b.commit("after refused move", &ctx()).unwrap();
452        assert_eq!(
453            b.read_entity(Path::new("from.md")).unwrap(),
454            Some(b"source".to_vec())
455        );
456        assert_eq!(
457            b.read_entity(Path::new("to.md")).unwrap(),
458            Some(b"target".to_vec())
459        );
460    }
461
462    #[test]
463    fn a_refused_move_keeps_the_source_staged_bytes() {
464        let b = InMemoryBackend::new();
465        b.write_entity(Path::new("from.md"), b"new").unwrap();
466        b.write_entity(Path::new("to.md"), b"other").unwrap();
467        b.move_entity(Path::new("from.md"), Path::new("to.md"))
468            .unwrap_err();
469        assert_eq!(
470            b.read_entity(Path::new("from.md")).unwrap(),
471            Some(b"new".to_vec())
472        );
473    }
474
475    #[test]
476    fn rejects_path_traversal_absolute_and_empty() {
477        let b = InMemoryBackend::new();
478        // Same rejection rules as the folder backend — reused via
479        // `normalise_rel_path`, surfaced as backend path errors.
480        assert!(b.write_entity(Path::new("../escape.md"), b"x").is_err());
481        assert!(b.write_entity(Path::new("/etc/passwd"), b"x").is_err());
482        assert!(b.write_entity(Path::new(""), b"x").is_err());
483    }
484
485    #[test]
486    fn discard_pending_drops_staged_writes() {
487        let b = InMemoryBackend::new();
488        b.write_entity(Path::new("a.md"), b"first").unwrap();
489        b.commit("seed", &ctx()).unwrap();
490        b.write_entity(Path::new("a.md"), b"second-uncommitted")
491            .unwrap();
492        b.discard_pending().unwrap();
493        b.commit("after-discard", &ctx()).unwrap();
494        // The discarded write never landed; committed bytes unchanged.
495        assert_eq!(
496            b.read_entity(Path::new("a.md")).unwrap(),
497            Some(b"first".to_vec())
498        );
499    }
500
501    #[test]
502    fn reports_no_durable_history() {
503        // Matches the folder backend: no fabricated git-like head.
504        let b = InMemoryBackend::new();
505        assert_eq!(b.current_head().unwrap(), None);
506    }
507
508    #[test]
509    fn provenance_in_one_millisecond_stays_visible_past_a_cursor() {
510        let b = InMemoryBackend::new();
511        let at = UNIX_EPOCH + Duration::from_millis(1_700_000_000_123);
512        let record = |ts| {
513            Provenance::new(
514                ts,
515                ProvenanceKind::Create,
516                Some("specs--a".to_string()),
517                Actor::Cli,
518                None,
519                None,
520            )
521        };
522        b.append_provenance(&record(at)).unwrap();
523        b.append_provenance(&record(at + Duration::from_micros(10)))
524            .unwrap();
525        let all = b.read_provenance(None).unwrap();
526        assert_eq!(all.len(), 2);
527        let cursor = format_rfc3339_utc(all[0].timestamp);
528        assert_eq!(b.read_provenance(Some(&cursor)).unwrap().len(), 1);
529    }
530
531    #[test]
532    fn mem_config_cas_refuses_a_stale_expected() {
533        let b = InMemoryBackend::new();
534        let c = ctx();
535        b.write_mem_config(b"{\"v\":2}", &c).unwrap();
536        assert!(
537            !b.write_mem_config_cas(Some(b"{\"v\":1}"), b"{\"v\":3}", &c)
538                .unwrap()
539        );
540        assert_eq!(b.read_mem_config().unwrap(), Some(b"{\"v\":2}".to_vec()));
541        assert!(
542            b.write_mem_config_cas(Some(b"{\"v\":2}"), b"{\"v\":3}", &c)
543                .unwrap()
544        );
545        assert_eq!(b.read_mem_config().unwrap(), Some(b"{\"v\":3}".to_vec()));
546    }
547
548    #[test]
549    fn mem_config_round_trips() {
550        let b = InMemoryBackend::new();
551        assert_eq!(b.read_mem_config().unwrap(), None);
552        b.write_mem_config(
553            b"{\"schema\":\"default@1.0.0\"}",
554            &crate::vcs::CommitContext::new(
555                Some("test"),
556                crate::vcs::Actor::Cli,
557                None,
558                None,
559                crate::vcs::Role::Unspecified,
560                None,
561            ),
562        )
563        .unwrap();
564        assert_eq!(
565            b.read_mem_config().unwrap(),
566            Some(b"{\"schema\":\"default@1.0.0\"}".to_vec())
567        );
568    }
569
570    #[test]
571    fn anchors_sidecar_round_trips_and_is_not_listed_as_entity() {
572        let b = InMemoryBackend::new();
573        // No sidecar on a fresh mem.
574        assert_eq!(b.read_anchors_sidecar().unwrap(), None);
575        // Seed a real entity so list has something to filter against.
576        b.write_entity(Path::new("x.md"), b"# x\n").unwrap();
577        b.write_anchors_sidecar(b"{\"version\":1,\"entities\":{}}")
578            .unwrap();
579        // Staged sidecar is visible before commit (pending precedence).
580        assert_eq!(
581            b.read_anchors_sidecar().unwrap(),
582            Some(b"{\"version\":1,\"entities\":{}}".to_vec())
583        );
584        b.commit("seed+anchors", &ctx()).unwrap();
585        // Survives the commit.
586        assert_eq!(
587            b.read_anchors_sidecar().unwrap(),
588            Some(b"{\"version\":1,\"entities\":{}}".to_vec())
589        );
590        // The sidecar never surfaces as an entity.
591        assert_eq!(
592            b.list_entities().unwrap(),
593            vec![PathBuf::from("x.md")],
594            "anchors sidecar must not list as an entity"
595        );
596    }
597
598    #[test]
599    fn provenance_appends_and_reads_with_cursor() {
600        let b = InMemoryBackend::new();
601        let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000);
602        let t1 = UNIX_EPOCH + Duration::from_secs(1_700_000_001);
603        b.append_provenance(&Provenance::new(
604            t0,
605            ProvenanceKind::Create,
606            Some("specs--a".to_string()),
607            Actor::Cli,
608            None,
609            None,
610        ))
611        .unwrap();
612        b.append_provenance(&Provenance::new(
613            t1,
614            ProvenanceKind::Update,
615            Some("specs--a".to_string()),
616            Actor::Cli,
617            None,
618            None,
619        ))
620        .unwrap();
621
622        // No cursor → both records.
623        assert_eq!(b.read_provenance(None).unwrap().len(), 2);
624        // Cursor at t0 → only the strictly-later t1 record.
625        let cursor = format_rfc3339_utc(t0);
626        let after = b.read_provenance(Some(&cursor)).unwrap();
627        assert_eq!(after.len(), 1);
628        assert_eq!(after[0].kind, ProvenanceKind::Update);
629    }
630}