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 provenance: Vec<Provenance>,
73 config: Option<Vec<u8>>,
76}
77
78pub struct InMemoryBackend {
81 state: Mutex<State>,
82}
83
84impl InMemoryBackend {
85 pub fn new() -> Self {
88 Self {
89 state: Mutex::new(State::default()),
90 }
91 }
92
93 fn lock(&self) -> Result<std::sync::MutexGuard<'_, State>, BackendError> {
94 self.state
95 .lock()
96 .map_err(|_| BackendError::Other("in-memory backend state poisoned".to_string()))
97 }
98}
99
100impl Default for InMemoryBackend {
101 fn default() -> Self {
102 Self::new()
103 }
104}
105
106impl MemBackend for InMemoryBackend {
107 fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError> {
108 let state = self.lock()?;
116 Ok(state
117 .committed
118 .keys()
119 .filter(|k| k.ends_with(".md") && !k.starts_with(".memstead/"))
120 .map(PathBuf::from)
121 .collect())
122 }
123
124 fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError> {
125 let key = normalise_rel_path(rel_path)?;
126 let state = self.lock()?;
127 if let Some(staged) = state.pending.get(&key) {
132 return Ok(match staged {
133 PendingState::Upsert(bytes) => Some(bytes.clone()),
134 PendingState::Delete => None,
135 });
136 }
137 Ok(state.committed.get(&key).cloned())
138 }
139
140 fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError> {
141 let key = normalise_rel_path(rel_path)?;
142 let mut state = self.lock()?;
143 state
144 .pending
145 .insert(key, PendingState::Upsert(content.to_vec()));
146 Ok(())
147 }
148
149 fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError> {
150 let key = normalise_rel_path(rel_path)?;
151 let mut state = self.lock()?;
152 state.pending.insert(key, PendingState::Delete);
153 Ok(())
154 }
155
156 fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError> {
157 let from_key = normalise_rel_path(from)?;
158 let to_key = normalise_rel_path(to)?;
159 let mut state = self.lock()?;
160
161 let bytes = match state.pending.remove(&from_key) {
165 Some(PendingState::Upsert(b)) => b,
166 Some(PendingState::Delete) => {
167 state.pending.insert(from_key, PendingState::Delete);
168 return Err(BackendError::Other(format!(
169 "move source {} is already pending deletion",
170 from.display()
171 )));
172 }
173 None => match state.committed.get(&from_key) {
174 Some(b) => b.clone(),
175 None => {
176 return Err(BackendError::Other(format!(
177 "move source {} does not exist",
178 from.display()
179 )));
180 }
181 },
182 };
183
184 if matches!(state.pending.get(&to_key), Some(PendingState::Upsert(_))) {
185 return Err(BackendError::Other(format!(
186 "move target {} already has a pending write",
187 to.display()
188 )));
189 }
190 state.pending.insert(from_key, PendingState::Delete);
191 state.pending.insert(to_key, PendingState::Upsert(bytes));
192 Ok(())
193 }
194
195 fn discard_pending(&self) -> Result<(), BackendError> {
196 let mut state = self.lock()?;
197 state.pending.clear();
198 Ok(())
199 }
200
201 fn commit(&self, _message: &str, _ctx: &CommitContext<'_>) -> Result<CommitId, BackendError> {
202 let mut state = self.lock()?;
203 let ops: Vec<(String, PendingState)> = state.pending.drain().collect();
204 for (key, op) in ops {
205 match op {
206 PendingState::Upsert(bytes) => {
207 state.committed.insert(key, bytes);
208 }
209 PendingState::Delete => {
210 state.committed.remove(&key);
211 }
212 }
213 }
214 Ok(make_commit_id())
215 }
216
217 fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
218 let mut state = self.lock()?;
219 state.provenance.push(record.clone());
220 Ok(())
221 }
222
223 fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError> {
224 let state = self.lock()?;
225 let out = state
230 .provenance
231 .iter()
232 .filter(|r| match cursor {
233 Some(c) => format_rfc3339_utc(r.timestamp).as_str() > c,
234 None => true,
235 })
236 .cloned()
237 .collect();
238 Ok(out)
239 }
240
241 fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
242 self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
246 }
247
248 fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
249 self.write_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH), bytes)
253 }
254
255 fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
256 let state = self.lock()?;
257 Ok(state.config.clone())
258 }
259
260 fn write_mem_config(
261 &self,
262 bytes: &[u8],
263 _ctx: &crate::vcs::CommitContext<'_>,
264 ) -> Result<(), BackendError> {
265 let mut state = self.lock()?;
269 state.config = Some(bytes.to_vec());
270 Ok(())
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277 use crate::provenance::ProvenanceKind;
278 use crate::vcs::{Actor, ClientId, CommitContext};
279 use std::time::{Duration, UNIX_EPOCH};
280
281 fn ctx<'a>() -> CommitContext<'a> {
282 CommitContext {
283 actor: Actor::Cli,
284 client: Some(ClientId {
285 name: "claude-code".to_string(),
286 version: "0.1.0".to_string(),
287 }),
288 tool: Some("test"),
289 note: None,
290 role: Default::default(),
291 identity: None,
292 logical_operation_id: None,
293 entity_ids: None,
294 proposal: None,
295 }
296 }
297
298 #[test]
299 fn write_then_commit_round_trips_in_ram() {
300 let b = InMemoryBackend::new();
301 b.write_entity(Path::new("notes/hello.md"), b"# hi\n")
302 .unwrap();
303 let id = b.commit("c1", &ctx()).unwrap();
304 assert!(!id.is_empty());
305 assert_eq!(
306 b.read_entity(Path::new("notes/hello.md")).unwrap(),
307 Some(b"# hi\n".to_vec())
308 );
309 assert_eq!(
310 b.list_entities().unwrap(),
311 vec![PathBuf::from("notes/hello.md")]
312 );
313 }
314
315 #[test]
316 fn read_sees_pending_write_before_commit() {
317 let b = InMemoryBackend::new();
318 b.write_entity(Path::new("a.md"), b"staged").unwrap();
319 assert_eq!(
321 b.read_entity(Path::new("a.md")).unwrap(),
322 Some(b"staged".to_vec())
323 );
324 assert!(b.list_entities().unwrap().is_empty());
325 }
326
327 #[test]
328 fn delete_removes_committed_path() {
329 let b = InMemoryBackend::new();
330 b.write_entity(Path::new("a.md"), b"a").unwrap();
331 b.write_entity(Path::new("b.md"), b"b").unwrap();
332 b.commit("seed", &ctx()).unwrap();
333 b.delete_entity(Path::new("a.md")).unwrap();
334 b.commit("drop", &ctx()).unwrap();
335 assert_eq!(b.read_entity(Path::new("a.md")).unwrap(), None);
336 assert_eq!(
337 b.read_entity(Path::new("b.md")).unwrap(),
338 Some(b"b".to_vec())
339 );
340 }
341
342 #[test]
343 fn delete_of_missing_path_is_idempotent() {
344 let b = InMemoryBackend::new();
345 b.delete_entity(Path::new("ghost.md")).unwrap();
346 b.commit("noop", &ctx()).unwrap();
347 assert_eq!(b.read_entity(Path::new("ghost.md")).unwrap(), None);
348 }
349
350 #[test]
351 fn move_renames_committed_path() {
352 let b = InMemoryBackend::new();
353 b.write_entity(Path::new("from.md"), b"payload").unwrap();
354 b.commit("seed", &ctx()).unwrap();
355 b.move_entity(Path::new("from.md"), Path::new("nested/to.md"))
356 .unwrap();
357 b.commit("rename", &ctx()).unwrap();
358 assert_eq!(b.read_entity(Path::new("from.md")).unwrap(), None);
359 assert_eq!(
360 b.read_entity(Path::new("nested/to.md")).unwrap(),
361 Some(b"payload".to_vec())
362 );
363 }
364
365 #[test]
366 fn move_carries_pending_upsert_bytes() {
367 let b = InMemoryBackend::new();
368 b.write_entity(Path::new("a.md"), b"alpha").unwrap();
369 b.move_entity(Path::new("a.md"), Path::new("b.md")).unwrap();
370 b.commit("write+move", &ctx()).unwrap();
371 assert_eq!(b.read_entity(Path::new("a.md")).unwrap(), None);
372 assert_eq!(
373 b.read_entity(Path::new("b.md")).unwrap(),
374 Some(b"alpha".to_vec())
375 );
376 }
377
378 #[test]
379 fn move_missing_source_errors() {
380 let b = InMemoryBackend::new();
381 let err = b
382 .move_entity(Path::new("ghost.md"), Path::new("here.md"))
383 .unwrap_err();
384 assert!(matches!(err, BackendError::Other(_)));
385 }
386
387 #[test]
388 fn rejects_path_traversal_absolute_and_empty() {
389 let b = InMemoryBackend::new();
390 assert!(b.write_entity(Path::new("../escape.md"), b"x").is_err());
393 assert!(b.write_entity(Path::new("/etc/passwd"), b"x").is_err());
394 assert!(b.write_entity(Path::new(""), b"x").is_err());
395 }
396
397 #[test]
398 fn discard_pending_drops_staged_writes() {
399 let b = InMemoryBackend::new();
400 b.write_entity(Path::new("a.md"), b"first").unwrap();
401 b.commit("seed", &ctx()).unwrap();
402 b.write_entity(Path::new("a.md"), b"second-uncommitted")
403 .unwrap();
404 b.discard_pending().unwrap();
405 b.commit("after-discard", &ctx()).unwrap();
406 assert_eq!(
408 b.read_entity(Path::new("a.md")).unwrap(),
409 Some(b"first".to_vec())
410 );
411 }
412
413 #[test]
414 fn reports_no_durable_history() {
415 let b = InMemoryBackend::new();
417 assert_eq!(b.current_head().unwrap(), None);
418 }
419
420 #[test]
421 fn mem_config_round_trips() {
422 let b = InMemoryBackend::new();
423 assert_eq!(b.read_mem_config().unwrap(), None);
424 b.write_mem_config(
425 b"{\"schema\":\"default@1.0.0\"}",
426 &crate::vcs::CommitContext::new(
427 Some("test"),
428 crate::vcs::Actor::Cli,
429 None,
430 None,
431 crate::vcs::Role::Unspecified,
432 None,
433 ),
434 )
435 .unwrap();
436 assert_eq!(
437 b.read_mem_config().unwrap(),
438 Some(b"{\"schema\":\"default@1.0.0\"}".to_vec())
439 );
440 }
441
442 #[test]
443 fn anchors_sidecar_round_trips_and_is_not_listed_as_entity() {
444 let b = InMemoryBackend::new();
445 assert_eq!(b.read_anchors_sidecar().unwrap(), None);
447 b.write_entity(Path::new("x.md"), b"# x\n").unwrap();
449 b.write_anchors_sidecar(b"{\"version\":1,\"entities\":{}}")
450 .unwrap();
451 assert_eq!(
453 b.read_anchors_sidecar().unwrap(),
454 Some(b"{\"version\":1,\"entities\":{}}".to_vec())
455 );
456 b.commit("seed+anchors", &ctx()).unwrap();
457 assert_eq!(
459 b.read_anchors_sidecar().unwrap(),
460 Some(b"{\"version\":1,\"entities\":{}}".to_vec())
461 );
462 assert_eq!(
464 b.list_entities().unwrap(),
465 vec![PathBuf::from("x.md")],
466 "anchors sidecar must not list as an entity"
467 );
468 }
469
470 #[test]
471 fn provenance_appends_and_reads_with_cursor() {
472 let b = InMemoryBackend::new();
473 let t0 = UNIX_EPOCH + Duration::from_secs(1_700_000_000);
474 let t1 = UNIX_EPOCH + Duration::from_secs(1_700_000_001);
475 b.append_provenance(&Provenance::new(
476 t0,
477 ProvenanceKind::Create,
478 Some("specs--a".to_string()),
479 Actor::Cli,
480 None,
481 None,
482 ))
483 .unwrap();
484 b.append_provenance(&Provenance::new(
485 t1,
486 ProvenanceKind::Update,
487 Some("specs--a".to_string()),
488 Actor::Cli,
489 None,
490 None,
491 ))
492 .unwrap();
493
494 assert_eq!(b.read_provenance(None).unwrap().len(), 2);
496 let cursor = format_rfc3339_utc(t0);
498 let after = b.read_provenance(Some(&cursor)).unwrap();
499 assert_eq!(after.len(), 1);
500 assert_eq!(after[0].kind, ProvenanceKind::Update);
501 }
502}