1use 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
49enum PendingState {
54 Upsert(Vec<u8>),
55 Delete,
56}
57
58#[derive(Default)]
62struct State {
63 committed: HashMap<String, Vec<u8>>,
67 pending: HashMap<String, PendingState>,
70 pending_provenance: Vec<Provenance>,
73 provenance: Vec<Provenance>,
76 config: Option<Vec<u8>>,
79}
80
81pub struct InMemoryBackend {
84 state: Mutex<State>,
85}
86
87impl InMemoryBackend {
88 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
109fn 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 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 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 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 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 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 self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
284 }
285
286 fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
287 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 let mut state = self.lock()?;
307 state.config = Some(bytes.to_vec());
308 Ok(())
309 }
310
311 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 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 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 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 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 assert_eq!(b.read_anchors_sidecar().unwrap(), None);
575 b.write_entity(Path::new("x.md"), b"# x\n").unwrap();
577 b.write_anchors_sidecar(b"{\"version\":1,\"entities\":{}}")
578 .unwrap();
579 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 assert_eq!(
587 b.read_anchors_sidecar().unwrap(),
588 Some(b"{\"version\":1,\"entities\":{}}".to_vec())
589 );
590 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 assert_eq!(b.read_provenance(None).unwrap().len(), 2);
624 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}