Skip to main content

agentstategraph_storage/
memory.rs

1//! In-memory storage backend.
2//!
3//! Fast, ephemeral storage suitable for testing, speculation,
4//! and workflows that don't need durability.
5
6use std::collections::{BTreeMap, HashMap, HashSet};
7use std::sync::RwLock;
8
9use chrono::{DateTime, Utc};
10
11use agentstategraph_core::{
12    Commit, Epoch, EpochStatus, Namespace, Object, ObjectId, Session, SessionStatus,
13};
14use agentstategraph_reminders::{
15    MemoryReminderStore, Reminder, ReminderError, ReminderFilter, ReminderStore,
16};
17use agentstategraph_taint::{Taint, TaintKind};
18
19use crate::traits::{
20    CommitStore, EpochStore, ObjectStore, RefStore, SessionStore, StorageError, TaintStore,
21};
22
23/// In-memory storage backend. Thread-safe via RwLock.
24///
25/// All data is lost when the process exits. Use SQLite for durable storage.
26pub struct MemoryStorage {
27    objects: RwLock<HashMap<ObjectId, Object>>,
28    commits: RwLock<HashMap<ObjectId, Commit>>,
29    /// Refs keyed by (namespace, name). Namespace must exist in `namespaces`.
30    refs: RwLock<BTreeMap<(String, String), ObjectId>>,
31    /// Known namespaces. A ref cannot be created in an unknown namespace.
32    namespaces: RwLock<HashSet<String>>,
33    epochs: RwLock<Vec<Epoch>>,
34    sessions: RwLock<HashMap<String, Session>>,
35    /// (commit_id, epoch_id) associations, in insertion order.
36    commit_epoch: RwLock<Vec<(ObjectId, String)>>,
37    /// (commit_id, session_id) associations, in insertion order.
38    commit_session: RwLock<Vec<(ObjectId, String)>>,
39    /// The trace each commit was made in.
40    commit_traces: RwLock<HashMap<ObjectId, crate::traits::CommitTrace>>,
41    /// Taints keyed by id, insertion-ordered for deterministic
42    /// list output.
43    taints: RwLock<Vec<Taint>>,
44    /// Reminders delegated to the in-crate memory store.
45    pub(crate) reminders: MemoryReminderStore,
46}
47
48impl MemoryStorage {
49    pub fn new() -> Self {
50        let mut namespaces = HashSet::new();
51        namespaces.insert(Namespace::DEFAULT.to_string());
52        Self {
53            objects: RwLock::new(HashMap::new()),
54            commits: RwLock::new(HashMap::new()),
55            refs: RwLock::new(BTreeMap::new()),
56            namespaces: RwLock::new(namespaces),
57            epochs: RwLock::new(Vec::new()),
58            sessions: RwLock::new(HashMap::new()),
59            commit_epoch: RwLock::new(Vec::new()),
60            commit_session: RwLock::new(Vec::new()),
61            commit_traces: RwLock::new(HashMap::new()),
62            taints: RwLock::new(Vec::new()),
63            reminders: MemoryReminderStore::new(),
64        }
65    }
66
67    fn require_namespace(&self, namespace: &Namespace) -> Result<(), StorageError> {
68        let namespaces = self
69            .namespaces
70            .read()
71            .map_err(|e| StorageError::Backend(e.to_string()))?;
72        if namespaces.contains(namespace.as_str()) {
73            Ok(())
74        } else {
75            Err(StorageError::NamespaceNotFound(
76                namespace.as_str().to_string(),
77            ))
78        }
79    }
80}
81
82impl Default for MemoryStorage {
83    fn default() -> Self {
84        Self::new()
85    }
86}
87
88impl ObjectStore for MemoryStorage {
89    fn get_object(&self, id: &ObjectId) -> Result<Option<Object>, StorageError> {
90        let store = self
91            .objects
92            .read()
93            .map_err(|e| StorageError::Backend(e.to_string()))?;
94        Ok(store.get(id).cloned())
95    }
96
97    fn put_object(&self, obj: &Object) -> Result<ObjectId, StorageError> {
98        let id = obj.id();
99        let mut store = self
100            .objects
101            .write()
102            .map_err(|e| StorageError::Backend(e.to_string()))?;
103        store.entry(id).or_insert_with(|| obj.clone());
104        Ok(id)
105    }
106
107    fn has_object(&self, id: &ObjectId) -> Result<bool, StorageError> {
108        let store = self
109            .objects
110            .read()
111            .map_err(|e| StorageError::Backend(e.to_string()))?;
112        Ok(store.contains_key(id))
113    }
114}
115
116impl CommitStore for MemoryStorage {
117    fn set_commit_trace(
118        &self,
119        commit_id: &ObjectId,
120        trace: &crate::traits::CommitTrace,
121    ) -> Result<(), StorageError> {
122        self.commit_traces
123            .write()
124            .map_err(|e| StorageError::Backend(e.to_string()))?
125            .entry(*commit_id)
126            .or_insert_with(|| trace.clone());
127        Ok(())
128    }
129
130    fn get_commit_trace(
131        &self,
132        commit_id: &ObjectId,
133    ) -> Result<Option<crate::traits::CommitTrace>, StorageError> {
134        Ok(self
135            .commit_traces
136            .read()
137            .map_err(|e| StorageError::Backend(e.to_string()))?
138            .get(commit_id)
139            .cloned())
140    }
141
142    fn store_totals(&self) -> Result<Option<crate::traits::StoreTotals>, StorageError> {
143        let objects = self
144            .objects
145            .read()
146            .map_err(|e| StorageError::Backend(e.to_string()))?
147            .len();
148        let commits = self
149            .commits
150            .read()
151            .map_err(|e| StorageError::Backend(e.to_string()))?
152            .len();
153        Ok(Some(crate::traits::StoreTotals {
154            objects: objects as i64,
155            commits: commits as i64,
156            bytes: None,
157        }))
158    }
159
160    fn get_commit(&self, id: &ObjectId) -> Result<Option<Commit>, StorageError> {
161        let store = self
162            .commits
163            .read()
164            .map_err(|e| StorageError::Backend(e.to_string()))?;
165        Ok(store.get(id).cloned())
166    }
167
168    fn put_commit(&self, commit: &Commit) -> Result<(), StorageError> {
169        let mut store = self
170            .commits
171            .write()
172            .map_err(|e| StorageError::Backend(e.to_string()))?;
173        store.insert(commit.id, commit.clone());
174        Ok(())
175    }
176
177    fn has_commit(&self, id: &ObjectId) -> Result<bool, StorageError> {
178        let store = self
179            .commits
180            .read()
181            .map_err(|e| StorageError::Backend(e.to_string()))?;
182        Ok(store.contains_key(id))
183    }
184
185    fn all_commit_ids(&self) -> Result<Vec<ObjectId>, StorageError> {
186        let store = self
187            .commits
188            .read()
189            .map_err(|e| StorageError::Backend(e.to_string()))?;
190        Ok(store.keys().copied().collect())
191    }
192
193    fn list_commits(&self, from: &ObjectId, limit: usize) -> Result<Vec<Commit>, StorageError> {
194        let store = self
195            .commits
196            .read()
197            .map_err(|e| StorageError::Backend(e.to_string()))?;
198        let mut result = Vec::new();
199        let mut current = Some(*from);
200
201        while let Some(id) = current {
202            if result.len() >= limit {
203                break;
204            }
205            if let Some(commit) = store.get(&id) {
206                result.push(commit.clone());
207                // Follow first parent for linear history traversal
208                current = commit.parents.first().copied();
209            } else {
210                break;
211            }
212        }
213
214        Ok(result)
215    }
216}
217
218impl RefStore for MemoryStorage {
219    fn create_namespace(&self, namespace: &Namespace) -> Result<(), StorageError> {
220        let mut ns_store = self
221            .namespaces
222            .write()
223            .map_err(|e| StorageError::Backend(e.to_string()))?;
224        if !ns_store.insert(namespace.as_str().to_string()) {
225            return Err(StorageError::NamespaceAlreadyExists(
226                namespace.as_str().to_string(),
227            ));
228        }
229        Ok(())
230    }
231
232    fn list_namespaces(&self) -> Result<Vec<Namespace>, StorageError> {
233        let ns_store = self
234            .namespaces
235            .read()
236            .map_err(|e| StorageError::Backend(e.to_string()))?;
237        let mut names: Vec<Namespace> = ns_store
238            .iter()
239            .map(|s| Namespace::new(s).expect("stored namespace is always valid"))
240            .collect();
241        names.sort_by(|a, b| a.as_str().cmp(b.as_str()));
242        Ok(names)
243    }
244
245    fn get_ref(&self, namespace: &Namespace, name: &str) -> Result<Option<ObjectId>, StorageError> {
246        let ns_store = self
247            .namespaces
248            .read()
249            .map_err(|e| StorageError::Backend(e.to_string()))?;
250        if !ns_store.contains(namespace.as_str()) {
251            return Err(StorageError::NamespaceNotFound(
252                namespace.as_str().to_string(),
253            ));
254        }
255        drop(ns_store);
256        let store = self
257            .refs
258            .read()
259            .map_err(|e| StorageError::Backend(e.to_string()))?;
260        Ok(store
261            .get(&(namespace.as_str().to_string(), name.to_string()))
262            .copied())
263    }
264
265    fn set_ref(
266        &self,
267        namespace: &Namespace,
268        name: &str,
269        target: ObjectId,
270    ) -> Result<(), StorageError> {
271        let ns_store = self
272            .namespaces
273            .read()
274            .map_err(|e| StorageError::Backend(e.to_string()))?;
275        if !ns_store.contains(namespace.as_str()) {
276            return Err(StorageError::NamespaceNotFound(
277                namespace.as_str().to_string(),
278            ));
279        }
280        drop(ns_store);
281        let mut store = self
282            .refs
283            .write()
284            .map_err(|e| StorageError::Backend(e.to_string()))?;
285        store.insert((namespace.as_str().to_string(), name.to_string()), target);
286        Ok(())
287    }
288
289    fn cas_ref(
290        &self,
291        namespace: &Namespace,
292        name: &str,
293        expected: ObjectId,
294        new: ObjectId,
295    ) -> Result<bool, StorageError> {
296        let ns_store = self
297            .namespaces
298            .read()
299            .map_err(|e| StorageError::Backend(e.to_string()))?;
300        if !ns_store.contains(namespace.as_str()) {
301            return Err(StorageError::NamespaceNotFound(
302                namespace.as_str().to_string(),
303            ));
304        }
305        drop(ns_store);
306        let mut store = self
307            .refs
308            .write()
309            .map_err(|e| StorageError::Backend(e.to_string()))?;
310        let key = (namespace.as_str().to_string(), name.to_string());
311        match store.get(&key) {
312            Some(&current) if current == expected => {
313                store.insert(key, new);
314                Ok(true)
315            }
316            Some(_) => Ok(false),
317            None => Ok(false),
318        }
319    }
320
321    fn create_ref(
322        &self,
323        namespace: &Namespace,
324        name: &str,
325        target: ObjectId,
326    ) -> Result<bool, StorageError> {
327        self.require_namespace(namespace)?;
328        let mut store = self
329            .refs
330            .write()
331            .map_err(|e| StorageError::Backend(e.to_string()))?;
332        let key = (namespace.as_str().to_string(), name.to_string());
333        if store.contains_key(&key) {
334            return Ok(false);
335        }
336        store.insert(key, target);
337        Ok(true)
338    }
339
340    fn cas_delete_ref(
341        &self,
342        namespace: &Namespace,
343        name: &str,
344        expected: ObjectId,
345    ) -> Result<bool, StorageError> {
346        self.require_namespace(namespace)?;
347        let mut store = self
348            .refs
349            .write()
350            .map_err(|e| StorageError::Backend(e.to_string()))?;
351        let key = (namespace.as_str().to_string(), name.to_string());
352        if store.get(&key) != Some(&expected) {
353            return Ok(false);
354        }
355        store.remove(&key);
356        Ok(true)
357    }
358
359    fn list_refs(
360        &self,
361        namespace: &Namespace,
362        prefix: &str,
363    ) -> Result<Vec<(String, ObjectId)>, StorageError> {
364        let ns_store = self
365            .namespaces
366            .read()
367            .map_err(|e| StorageError::Backend(e.to_string()))?;
368        if !ns_store.contains(namespace.as_str()) {
369            return Err(StorageError::NamespaceNotFound(
370                namespace.as_str().to_string(),
371            ));
372        }
373        drop(ns_store);
374        let store = self
375            .refs
376            .read()
377            .map_err(|e| StorageError::Backend(e.to_string()))?;
378        let ns = namespace.as_str().to_string();
379        let result = store
380            .iter()
381            .filter(|((n, name), _)| n == &ns && name.starts_with(prefix))
382            .map(|((_, name), id)| (name.clone(), *id))
383            .collect();
384        Ok(result)
385    }
386
387    fn delete_ref(&self, namespace: &Namespace, name: &str) -> Result<bool, StorageError> {
388        let ns_store = self
389            .namespaces
390            .read()
391            .map_err(|e| StorageError::Backend(e.to_string()))?;
392        if !ns_store.contains(namespace.as_str()) {
393            return Err(StorageError::NamespaceNotFound(
394                namespace.as_str().to_string(),
395            ));
396        }
397        drop(ns_store);
398        let mut store = self
399            .refs
400            .write()
401            .map_err(|e| StorageError::Backend(e.to_string()))?;
402        Ok(store
403            .remove(&(namespace.as_str().to_string(), name.to_string()))
404            .is_some())
405    }
406
407    fn delete_namespace(&self, namespace: &Namespace) -> Result<bool, StorageError> {
408        if namespace.as_str() == Namespace::DEFAULT {
409            return Err(StorageError::InvalidOperation(
410                "cannot delete the 'default' namespace".to_string(),
411            ));
412        }
413        let existed = self.namespaces.write().unwrap().remove(namespace.as_str());
414        if existed {
415            let ns_str = namespace.as_str().to_string();
416            self.refs
417                .write()
418                .unwrap()
419                .retain(|(ns, _), _| ns != &ns_str);
420        }
421        Ok(existed)
422    }
423}
424
425impl EpochStore for MemoryStorage {
426    fn create_epoch(&self, epoch: &Epoch) -> Result<(), StorageError> {
427        let mut epochs = self
428            .epochs
429            .write()
430            .map_err(|e| StorageError::Backend(e.to_string()))?;
431        if epochs.iter().any(|e| e.id == epoch.id) {
432            return Err(StorageError::Backend(format!(
433                "epoch '{}' already exists",
434                epoch.id
435            )));
436        }
437        epochs.push(epoch.clone());
438        Ok(())
439    }
440
441    fn seal_epoch(
442        &self,
443        id: &str,
444        summary: &str,
445        sealed_at: DateTime<Utc>,
446        sealed_commits: &[ObjectId],
447        seal_hash: &ObjectId,
448    ) -> Result<(), StorageError> {
449        let mut epochs = self
450            .epochs
451            .write()
452            .map_err(|e| StorageError::Backend(e.to_string()))?;
453        let epoch = epochs
454            .iter_mut()
455            .find(|e| e.id == id)
456            .ok_or_else(|| StorageError::Backend(format!("epoch not found: {}", id)))?;
457        if epoch.status == EpochStatus::Sealed || epoch.status == EpochStatus::Archived {
458            return Err(StorageError::EpochAlreadySealed { id: id.to_string() });
459        }
460        epoch.status = EpochStatus::Sealed;
461        epoch.sealed_at = Some(sealed_at);
462        epoch.seal_summary = Some(summary.to_string());
463        epoch.sealed_commits = sealed_commits.to_vec();
464        epoch.seal_hash = Some(*seal_hash);
465        Ok(())
466    }
467
468    fn assign_epoch_namespace(&self, id: &str, namespace: &str) -> Result<bool, StorageError> {
469        let mut epochs = self
470            .epochs
471            .write()
472            .map_err(|e| StorageError::Backend(e.to_string()))?;
473        let epoch = epochs
474            .iter_mut()
475            .find(|e| e.id == id)
476            .ok_or_else(|| StorageError::Backend(format!("epoch not found: {}", id)))?;
477        // Assign-only: an epoch that already has an owner is left untouched.
478        if epoch.namespace.is_some() {
479            return Ok(false);
480        }
481        epoch.namespace = Some(namespace.to_string());
482        Ok(true)
483    }
484
485    fn list_epochs(&self) -> Result<Vec<Epoch>, StorageError> {
486        let epochs = self
487            .epochs
488            .read()
489            .map_err(|e| StorageError::Backend(e.to_string()))?;
490        let mut out: Vec<Epoch> = epochs.clone();
491        out.sort_by_key(|b| std::cmp::Reverse(b.created_at));
492        Ok(out)
493    }
494
495    fn get_epoch(&self, id: &str) -> Result<Option<Epoch>, StorageError> {
496        let epochs = self
497            .epochs
498            .read()
499            .map_err(|e| StorageError::Backend(e.to_string()))?;
500        let Some(mut epoch) = epochs.iter().find(|e| e.id == id).cloned() else {
501            return Ok(None);
502        };
503        // Rehydrate commits from the association map.
504        let assoc = self
505            .commit_epoch
506            .read()
507            .map_err(|e| StorageError::Backend(e.to_string()))?;
508        epoch.commits = assoc
509            .iter()
510            .filter(|(_, eid)| eid == id)
511            .map(|(cid, _)| *cid)
512            .collect();
513        Ok(Some(epoch))
514    }
515
516    fn archive_epoch(&self, id: &str) -> Result<(), StorageError> {
517        let mut epochs = self
518            .epochs
519            .write()
520            .map_err(|e| StorageError::Backend(e.to_string()))?;
521        let epoch = epochs
522            .iter_mut()
523            .find(|e| e.id == id)
524            .ok_or_else(|| StorageError::Backend(format!("epoch not found: {}", id)))?;
525        if epoch.status != EpochStatus::Sealed {
526            return Err(StorageError::Backend(format!(
527                "epoch '{}' is not sealed",
528                id
529            )));
530        }
531        epoch.status = EpochStatus::Archived;
532        Ok(())
533    }
534
535    fn set_commit_epoch(&self, commit_id: &ObjectId, epoch_id: &str) -> Result<(), StorageError> {
536        // The status check holds the epochs lock until the association is
537        // written, so a seal (which needs the write lock) can't land between.
538        let epochs = self
539            .epochs
540            .read()
541            .map_err(|e| StorageError::Backend(e.to_string()))?;
542        let epoch = epochs
543            .iter()
544            .find(|e| e.id == epoch_id)
545            .ok_or_else(|| StorageError::Backend(format!("epoch not found: {}", epoch_id)))?;
546        if epoch.status == EpochStatus::Sealed || epoch.status == EpochStatus::Archived {
547            return Err(StorageError::EpochAlreadySealed {
548                id: epoch_id.to_string(),
549            });
550        }
551        let mut assoc = self
552            .commit_epoch
553            .write()
554            .map_err(|e| StorageError::Backend(e.to_string()))?;
555        // One epoch per commit, as in the SQL backends; linking twice used to
556        // list the commit twice.
557        assoc.retain(|(c, _)| c != commit_id);
558        assoc.push((*commit_id, epoch_id.to_string()));
559        Ok(())
560    }
561}
562
563impl SessionStore for MemoryStorage {
564    fn create_session(&self, session: &Session) -> Result<(), StorageError> {
565        let mut sessions = self
566            .sessions
567            .write()
568            .map_err(|e| StorageError::Backend(e.to_string()))?;
569        sessions.insert(session.id.clone(), session.clone());
570        Ok(())
571    }
572
573    fn end_session(
574        &self,
575        id: &str,
576        status: SessionStatus,
577        ended_at: DateTime<Utc>,
578    ) -> Result<(), StorageError> {
579        let mut sessions = self
580            .sessions
581            .write()
582            .map_err(|e| StorageError::Backend(e.to_string()))?;
583        let session = sessions
584            .get_mut(id)
585            .ok_or_else(|| StorageError::Backend(format!("session not found: {}", id)))?;
586        if session.status != SessionStatus::Active {
587            return Err(StorageError::SessionEnded { id: id.to_string() });
588        }
589        session.status = status;
590        session.ended_at = Some(ended_at);
591        Ok(())
592    }
593
594    fn list_sessions(&self, agent_filter: Option<&str>) -> Result<Vec<Session>, StorageError> {
595        let sessions = self
596            .sessions
597            .read()
598            .map_err(|e| StorageError::Backend(e.to_string()))?;
599        Ok(sessions
600            .values()
601            .filter(|s| agent_filter.map(|f| s.agent_id == f).unwrap_or(true))
602            .cloned()
603            .collect())
604    }
605
606    fn get_session(&self, id: &str) -> Result<Option<Session>, StorageError> {
607        let sessions = self
608            .sessions
609            .read()
610            .map_err(|e| StorageError::Backend(e.to_string()))?;
611        Ok(sessions.get(id).cloned())
612    }
613
614    fn set_commit_session(
615        &self,
616        commit_id: &ObjectId,
617        session_id: &str,
618    ) -> Result<(), StorageError> {
619        // As set_commit_epoch: hold the sessions lock through the write, and
620        // keep one session per commit.
621        let sessions = self
622            .sessions
623            .read()
624            .map_err(|e| StorageError::Backend(e.to_string()))?;
625        let session = sessions
626            .get(session_id)
627            .ok_or_else(|| StorageError::Backend(format!("session not found: {}", session_id)))?;
628        if session.status != SessionStatus::Active {
629            return Err(StorageError::SessionEnded {
630                id: session_id.to_string(),
631            });
632        }
633        let mut assoc = self
634            .commit_session
635            .write()
636            .map_err(|e| StorageError::Backend(e.to_string()))?;
637        assoc.retain(|(c, _)| c != commit_id);
638        assoc.push((*commit_id, session_id.to_string()));
639        Ok(())
640    }
641}
642
643impl TaintStore for MemoryStorage {
644    fn create_taint(&self, taint: &Taint) -> Result<(), StorageError> {
645        let mut list = self
646            .taints
647            .write()
648            .map_err(|e| StorageError::Backend(e.to_string()))?;
649        // Uniqueness: no other active (unresolved) row for
650        // (path, name, kind).
651        for existing in list.iter() {
652            if existing.resolved_at.is_some() {
653                continue;
654            }
655            if existing.path == taint.path
656                && existing.name == taint.name
657                && existing.kind == taint.kind
658            {
659                return Err(StorageError::Backend(format!(
660                    "duplicate active taint ({path}, {name}, {kind:?})",
661                    path = taint.path,
662                    name = taint.name,
663                    kind = taint.kind,
664                )));
665            }
666        }
667        list.push(taint.clone());
668        Ok(())
669    }
670
671    fn resolve_taint(
672        &self,
673        id: &str,
674        resolved_by: &str,
675        reason: &str,
676        proof: Option<&str>,
677        resolved_at: DateTime<Utc>,
678    ) -> Result<(), StorageError> {
679        let mut list = self
680            .taints
681            .write()
682            .map_err(|e| StorageError::Backend(e.to_string()))?;
683        let t = list
684            .iter_mut()
685            .find(|t| t.id == id)
686            .ok_or_else(|| StorageError::Backend(format!("taint {id} not found")))?;
687        if t.resolved_at.is_some() {
688            return Err(StorageError::Backend(format!(
689                "taint {id} is already resolved"
690            )));
691        }
692        t.resolved_at = Some(resolved_at);
693        t.resolved_by = Some(resolved_by.to_string());
694        t.resolved_reason = Some(reason.to_string());
695        t.resolved_proof = proof.map(str::to_string);
696        Ok(())
697    }
698
699    fn list_taints(
700        &self,
701        path_prefix: Option<&str>,
702        kind: Option<TaintKind>,
703        include_resolved: bool,
704    ) -> Result<Vec<Taint>, StorageError> {
705        let list = self
706            .taints
707            .read()
708            .map_err(|e| StorageError::Backend(e.to_string()))?;
709        let mut out: Vec<Taint> = list
710            .iter()
711            .filter(|t| include_resolved || t.resolved_at.is_none())
712            .filter(|t| match path_prefix {
713                None => true,
714                Some(p) => {
715                    t.path == p || t.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
716                }
717            })
718            .filter(|t| kind.map(|k| k == t.kind).unwrap_or(true))
719            .cloned()
720            .collect();
721        // Most-recently-created first for deterministic ordering.
722        out.sort_by(|a, b| b.created_at.cmp(&a.created_at));
723        Ok(out)
724    }
725
726    fn check_taint(&self, request_path: &str) -> Result<Vec<Taint>, StorageError> {
727        let list = self
728            .taints
729            .read()
730            .map_err(|e| StorageError::Backend(e.to_string()))?;
731        let now = Utc::now();
732        let out: Vec<Taint> = list
733            .iter()
734            .filter(|t| t.is_active(now))
735            .filter(|t| {
736                if t.path == request_path {
737                    return true;
738                }
739                if !t.propagate {
740                    return false;
741                }
742                let prefix = if t.path.ends_with('/') {
743                    t.path.clone()
744                } else {
745                    format!("{}/", t.path)
746                };
747                request_path.starts_with(&prefix)
748            })
749            .cloned()
750            .collect();
751        Ok(out)
752    }
753
754    fn get_taint(&self, id: &str) -> Result<Option<Taint>, StorageError> {
755        let list = self
756            .taints
757            .read()
758            .map_err(|e| StorageError::Backend(e.to_string()))?;
759        Ok(list.iter().find(|t| t.id == id).cloned())
760    }
761
762    fn set_taint_commit_id(&self, id: &str, commit_id: &str) -> Result<(), StorageError> {
763        let mut list = self
764            .taints
765            .write()
766            .map_err(|e| StorageError::Backend(e.to_string()))?;
767        let t = list
768            .iter_mut()
769            .find(|t| t.id == id)
770            .ok_or_else(|| StorageError::Backend(format!("taint {id} not found")))?;
771        t.commit_id = commit_id.to_string();
772        Ok(())
773    }
774}
775
776impl ReminderStore for MemoryStorage {
777    fn save(&self, reminder: &Reminder) -> Result<(), ReminderError> {
778        self.reminders.save(reminder)
779    }
780    fn get(&self, id: &str) -> Result<Option<Reminder>, ReminderError> {
781        self.reminders.get(id)
782    }
783    fn update(&self, reminder: &Reminder) -> Result<(), ReminderError> {
784        self.reminders.update(reminder)
785    }
786
787    // Forwarded: without it the trait's non-atomic default applied, and
788    // racing updates from one snapshot could all win.
789    fn update_if_unchanged(
790        &self,
791        expected: &Reminder,
792        new: &Reminder,
793    ) -> Result<bool, ReminderError> {
794        self.reminders.update_if_unchanged(expected, new)
795    }
796    fn delete(&self, id: &str) -> Result<bool, ReminderError> {
797        self.reminders.delete(id)
798    }
799    fn list(&self, filter: &ReminderFilter) -> Result<Vec<Reminder>, ReminderError> {
800        self.reminders.list(filter)
801    }
802}
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807    use agentstategraph_core::*;
808
809    #[test]
810    fn test_object_store_roundtrip() {
811        let store = MemoryStorage::new();
812
813        let obj = Object::string("hello world");
814        let id = store.put_object(&obj).unwrap();
815
816        let retrieved = store.get_object(&id).unwrap();
817        assert_eq!(retrieved, Some(obj));
818    }
819
820    #[test]
821    fn test_object_deduplication() {
822        let store = MemoryStorage::new();
823
824        let obj1 = Object::string("duplicate");
825        let obj2 = Object::string("duplicate");
826
827        let id1 = store.put_object(&obj1).unwrap();
828        let id2 = store.put_object(&obj2).unwrap();
829
830        assert_eq!(id1, id2, "identical objects should produce same ID");
831    }
832
833    #[test]
834    fn test_ref_operations() {
835        let store = MemoryStorage::new();
836        let ns = Namespace::default_ns();
837        let target = ObjectId::hash(b"test-commit");
838
839        // Set
840        store.set_ref(&ns, "main", target).unwrap();
841        assert_eq!(store.get_ref(&ns, "main").unwrap(), Some(target));
842
843        // CAS success
844        let new_target = ObjectId::hash(b"new-commit");
845        assert!(store.cas_ref(&ns, "main", target, new_target).unwrap());
846        assert_eq!(store.get_ref(&ns, "main").unwrap(), Some(new_target));
847
848        // CAS failure (stale expected value)
849        let stale = ObjectId::hash(b"stale");
850        let another = ObjectId::hash(b"another");
851        assert!(!store.cas_ref(&ns, "main", stale, another).unwrap());
852        assert_eq!(store.get_ref(&ns, "main").unwrap(), Some(new_target)); // unchanged
853    }
854
855    #[test]
856    fn test_list_refs_with_prefix() {
857        let store = MemoryStorage::new();
858        let ns = Namespace::default_ns();
859
860        store
861            .set_ref(&ns, "agents/planner/workspace", ObjectId::hash(b"a"))
862            .unwrap();
863        store
864            .set_ref(&ns, "agents/storage/workspace", ObjectId::hash(b"b"))
865            .unwrap();
866        store.set_ref(&ns, "main", ObjectId::hash(b"c")).unwrap();
867
868        let agent_refs = store.list_refs(&ns, "agents/").unwrap();
869        assert_eq!(agent_refs.len(), 2);
870
871        let all_refs = store.list_refs(&ns, "").unwrap();
872        assert_eq!(all_refs.len(), 3);
873    }
874
875    #[test]
876    fn test_delete_ref() {
877        let store = MemoryStorage::new();
878        let ns = Namespace::default_ns();
879        let target = ObjectId::hash(b"test");
880
881        store.set_ref(&ns, "temp", target).unwrap();
882        assert!(store.delete_ref(&ns, "temp").unwrap());
883        assert_eq!(store.get_ref(&ns, "temp").unwrap(), None);
884        assert!(!store.delete_ref(&ns, "temp").unwrap()); // already deleted
885    }
886
887    #[test]
888    fn test_namespace_isolation() {
889        let store = MemoryStorage::new();
890        let ns_a = Namespace::default_ns();
891        let ns_b = Namespace::new("project-b").unwrap();
892        store.create_namespace(&ns_b).unwrap();
893
894        let id_a = ObjectId::hash(b"a");
895        let id_b = ObjectId::hash(b"b");
896
897        store.set_ref(&ns_a, "main", id_a).unwrap();
898        store.set_ref(&ns_b, "main", id_b).unwrap();
899
900        assert_eq!(store.get_ref(&ns_a, "main").unwrap(), Some(id_a));
901        assert_eq!(store.get_ref(&ns_b, "main").unwrap(), Some(id_b));
902
903        let list_a = store.list_refs(&ns_a, "").unwrap();
904        let list_b = store.list_refs(&ns_b, "").unwrap();
905        assert_eq!(list_a.len(), 1);
906        assert_eq!(list_b.len(), 1);
907        assert_eq!(list_a[0].0, "main");
908        assert_eq!(list_b[0].0, "main");
909    }
910
911    #[test]
912    fn test_namespace_not_found() {
913        let store = MemoryStorage::new();
914        let unknown = Namespace::new("unknown-ns").unwrap();
915        let target = ObjectId::hash(b"x");
916
917        let err = store.set_ref(&unknown, "main", target).unwrap_err();
918        assert!(
919            matches!(err, StorageError::NamespaceNotFound(_)),
920            "expected NamespaceNotFound, got {err:?}"
921        );
922    }
923
924    #[test]
925    fn test_commit_store() {
926        let store = MemoryStorage::new();
927
928        let commit = CommitBuilder::new(
929            ObjectId::hash(b"state"),
930            "agent/test",
931            Authority::simple("test"),
932            Intent::new(IntentCategory::Checkpoint, "initial state"),
933        )
934        .build();
935
936        store.put_commit(&commit).unwrap();
937        let retrieved = store.get_commit(&commit.id).unwrap();
938        assert!(retrieved.is_some());
939        assert_eq!(retrieved.unwrap().agent_id, "agent/test");
940    }
941
942    // --- Object edge cases ---
943
944    #[test]
945    fn test_get_nonexistent_object_returns_none() {
946        let store = MemoryStorage::new();
947        let missing = ObjectId::hash(b"does-not-exist");
948        assert_eq!(store.get_object(&missing).unwrap(), None);
949    }
950
951    #[test]
952    fn test_has_object() {
953        let store = MemoryStorage::new();
954        let obj = Object::int(99);
955        let id = store.put_object(&obj).unwrap();
956        assert!(store.has_object(&id).unwrap());
957        assert!(!store.has_object(&ObjectId::hash(b"missing")).unwrap());
958    }
959
960    // --- Commit edge cases ---
961
962    #[test]
963    fn test_get_nonexistent_commit_returns_none() {
964        let store = MemoryStorage::new();
965        let missing = ObjectId::hash(b"no-commit");
966        assert_eq!(store.get_commit(&missing).unwrap(), None);
967    }
968
969    #[test]
970    fn test_has_commit() {
971        let store = MemoryStorage::new();
972        let commit = CommitBuilder::new(
973            ObjectId::hash(b"s"),
974            "a",
975            Authority::simple("a"),
976            Intent::new(IntentCategory::Refine, "x"),
977        )
978        .build();
979        store.put_commit(&commit).unwrap();
980        assert!(store.has_commit(&commit.id).unwrap());
981        assert!(!store.has_commit(&ObjectId::hash(b"missing")).unwrap());
982    }
983
984    #[test]
985    fn test_list_commits_follows_parent_chain() {
986        let store = MemoryStorage::new();
987
988        let c1 = CommitBuilder::new(
989            ObjectId::hash(b"s1"),
990            "a",
991            Authority::simple("a"),
992            Intent::new(IntentCategory::Checkpoint, "first"),
993        )
994        .build();
995        store.put_commit(&c1).unwrap();
996
997        let c2 = CommitBuilder::new(
998            ObjectId::hash(b"s2"),
999            "a",
1000            Authority::simple("a"),
1001            Intent::new(IntentCategory::Refine, "second"),
1002        )
1003        .parent(c1.id)
1004        .build();
1005        store.put_commit(&c2).unwrap();
1006
1007        let c3 = CommitBuilder::new(
1008            ObjectId::hash(b"s3"),
1009            "a",
1010            Authority::simple("a"),
1011            Intent::new(IntentCategory::Refine, "third"),
1012        )
1013        .parent(c2.id)
1014        .build();
1015        store.put_commit(&c3).unwrap();
1016
1017        let log = store.list_commits(&c3.id, 10).unwrap();
1018        assert_eq!(log.len(), 3);
1019        assert_eq!(log[0].id, c3.id);
1020        assert_eq!(log[1].id, c2.id);
1021        assert_eq!(log[2].id, c1.id);
1022    }
1023
1024    #[test]
1025    fn test_list_commits_respects_limit() {
1026        let store = MemoryStorage::new();
1027
1028        let c1 = CommitBuilder::new(
1029            ObjectId::hash(b"l1"),
1030            "a",
1031            Authority::simple("a"),
1032            Intent::new(IntentCategory::Checkpoint, "1"),
1033        )
1034        .build();
1035        store.put_commit(&c1).unwrap();
1036
1037        let c2 = CommitBuilder::new(
1038            ObjectId::hash(b"l2"),
1039            "a",
1040            Authority::simple("a"),
1041            Intent::new(IntentCategory::Refine, "2"),
1042        )
1043        .parent(c1.id)
1044        .build();
1045        store.put_commit(&c2).unwrap();
1046
1047        let log = store.list_commits(&c2.id, 1).unwrap();
1048        assert_eq!(log.len(), 1);
1049        assert_eq!(log[0].id, c2.id);
1050    }
1051
1052    // --- EpochStore ---
1053
1054    fn test_epoch(id: &str) -> Epoch {
1055        Epoch {
1056            scope: EpochScope::All,
1057            namespace: None,
1058            id: id.to_string(),
1059            description: "test epoch".into(),
1060            root_intents: Vec::new(),
1061            status: EpochStatus::Active,
1062            created_at: Utc::now(),
1063            sealed_at: None,
1064            seal_summary: None,
1065            seal_hash: None,
1066            commits: Vec::new(),
1067            agents: Vec::new(),
1068            branches: Vec::new(),
1069            tags: Vec::new(),
1070            sealed_commits: Vec::new(),
1071        }
1072    }
1073
1074    #[test]
1075    fn test_epoch_create_get_list() {
1076        let store = MemoryStorage::new();
1077        let e = test_epoch("epoch-1");
1078        store.create_epoch(&e).unwrap();
1079
1080        let got = store.get_epoch("epoch-1").unwrap();
1081        assert!(got.is_some());
1082        assert_eq!(got.unwrap().id, "epoch-1");
1083
1084        let list = store.list_epochs().unwrap();
1085        assert_eq!(list.len(), 1);
1086    }
1087
1088    #[test]
1089    fn test_epoch_duplicate_is_error() {
1090        let store = MemoryStorage::new();
1091        let e = test_epoch("e1");
1092        store.create_epoch(&e).unwrap();
1093        assert!(store.create_epoch(&e).is_err());
1094    }
1095
1096    #[test]
1097    fn test_epoch_seal() {
1098        let store = MemoryStorage::new();
1099        store.create_epoch(&test_epoch("e1")).unwrap();
1100        let cid = ObjectId::hash(b"c1");
1101        store
1102            .seal_epoch(
1103                "e1",
1104                "sealed for testing",
1105                Utc::now(),
1106                &[cid],
1107                &ObjectId::from_bytes([0u8; 32]),
1108            )
1109            .unwrap();
1110
1111        let epoch = store.get_epoch("e1").unwrap().unwrap();
1112        assert_eq!(epoch.status, EpochStatus::Sealed);
1113        assert!(epoch.seal_summary.as_deref() == Some("sealed for testing"));
1114        assert_eq!(epoch.sealed_commits, vec![cid]);
1115    }
1116
1117    #[test]
1118    fn test_epoch_seal_twice_is_error() {
1119        let store = MemoryStorage::new();
1120        store.create_epoch(&test_epoch("e1")).unwrap();
1121        store
1122            .seal_epoch(
1123                "e1",
1124                "first seal",
1125                Utc::now(),
1126                &[],
1127                &ObjectId::from_bytes([0u8; 32]),
1128            )
1129            .unwrap();
1130        assert!(
1131            store
1132                .seal_epoch(
1133                    "e1",
1134                    "second seal",
1135                    Utc::now(),
1136                    &[],
1137                    &ObjectId::from_bytes([0u8; 32])
1138                )
1139                .is_err(),
1140            "sealing an already-sealed epoch must fail"
1141        );
1142    }
1143
1144    #[test]
1145    fn test_set_commit_epoch_rejects_sealed() {
1146        let store = MemoryStorage::new();
1147        store.create_epoch(&test_epoch("e1")).unwrap();
1148        store
1149            .seal_epoch(
1150                "e1",
1151                "done",
1152                Utc::now(),
1153                &[],
1154                &ObjectId::from_bytes([0u8; 32]),
1155            )
1156            .unwrap();
1157
1158        let cid = ObjectId::hash(b"late-commit");
1159        assert!(
1160            store.set_commit_epoch(&cid, "e1").is_err(),
1161            "assigning a commit to a sealed epoch must fail"
1162        );
1163    }
1164
1165    // --- SessionStore ---
1166
1167    fn test_session(id: &str, agent: &str) -> Session {
1168        Session {
1169            id: id.to_string(),
1170            agent_id: agent.to_string(),
1171            working_branch: "main".into(),
1172            head: ObjectId::hash(id.as_bytes()),
1173            parent_session: None,
1174            delegated_intent: None,
1175            report_to: None,
1176            path_scope: None,
1177            scope_tenant: None,
1178            scope_namespace: None,
1179            status: SessionStatus::Active,
1180            created_at: Utc::now(),
1181            ended_at: None,
1182        }
1183    }
1184
1185    #[test]
1186    fn test_session_create_get() {
1187        let store = MemoryStorage::new();
1188        store
1189            .create_session(&test_session("s1", "agent/a"))
1190            .unwrap();
1191
1192        let got = store.get_session("s1").unwrap();
1193        assert!(got.is_some());
1194        assert_eq!(got.unwrap().agent_id, "agent/a");
1195    }
1196
1197    #[test]
1198    fn test_session_get_nonexistent() {
1199        let store = MemoryStorage::new();
1200        assert!(store.get_session("no-such-session").unwrap().is_none());
1201    }
1202
1203    #[test]
1204    fn test_session_end() {
1205        let store = MemoryStorage::new();
1206        store
1207            .create_session(&test_session("s1", "agent/a"))
1208            .unwrap();
1209
1210        store
1211            .end_session("s1", SessionStatus::Completed, Utc::now())
1212            .unwrap();
1213
1214        let got = store.get_session("s1").unwrap().unwrap();
1215        assert_eq!(got.status, SessionStatus::Completed);
1216        assert!(got.ended_at.is_some());
1217    }
1218
1219    #[test]
1220    fn test_session_end_twice_is_error() {
1221        let store = MemoryStorage::new();
1222        store.create_session(&test_session("s1", "a")).unwrap();
1223        store
1224            .end_session("s1", SessionStatus::Completed, Utc::now())
1225            .unwrap();
1226        assert!(
1227            store
1228                .end_session("s1", SessionStatus::Abandoned, Utc::now())
1229                .is_err(),
1230            "ending an already-ended session must fail"
1231        );
1232    }
1233
1234    #[test]
1235    fn test_session_list_with_agent_filter() {
1236        let store = MemoryStorage::new();
1237        store
1238            .create_session(&test_session("s1", "agent/alpha"))
1239            .unwrap();
1240        store
1241            .create_session(&test_session("s2", "agent/beta"))
1242            .unwrap();
1243        store
1244            .create_session(&test_session("s3", "agent/alpha"))
1245            .unwrap();
1246
1247        let alpha = store.list_sessions(Some("agent/alpha")).unwrap();
1248        assert_eq!(alpha.len(), 2);
1249
1250        let all = store.list_sessions(None).unwrap();
1251        assert_eq!(all.len(), 3);
1252    }
1253
1254    #[test]
1255    fn test_set_commit_session_rejects_ended_session() {
1256        let store = MemoryStorage::new();
1257        store.create_session(&test_session("s1", "a")).unwrap();
1258        store
1259            .end_session("s1", SessionStatus::Completed, Utc::now())
1260            .unwrap();
1261
1262        let cid = ObjectId::hash(b"late");
1263        assert!(
1264            store.set_commit_session(&cid, "s1").is_err(),
1265            "associating a commit with an ended session must fail"
1266        );
1267    }
1268
1269    // --- TaintStore ---
1270
1271    fn test_taint(id: &str, path: &str) -> Taint {
1272        use agentstategraph_taint::{TaintEffect, TaintMetadata, TaintSeverity};
1273        Taint {
1274            id: id.to_string(),
1275            path: path.to_string(),
1276            name: "test-taint".into(),
1277            kind: TaintKind::Taint,
1278            effect: TaintEffect::Warn,
1279            severity: TaintSeverity::Medium,
1280            reason: "test".into(),
1281            agent_id: "agent/test".into(),
1282            commit_id: String::new(),
1283            created_at: Utc::now(),
1284            expires_at: None,
1285            resolved_at: None,
1286            resolved_by: None,
1287            resolved_reason: None,
1288            resolved_proof: None,
1289            propagate: true,
1290            metadata: TaintMetadata::new(),
1291        }
1292    }
1293
1294    #[test]
1295    fn test_taint_create_get() {
1296        let store = MemoryStorage::new();
1297        store
1298            .create_taint(&test_taint("t1", "/nodes/pico1"))
1299            .unwrap();
1300
1301        let got = store.get_taint("t1").unwrap();
1302        assert!(got.is_some());
1303        assert_eq!(got.unwrap().path, "/nodes/pico1");
1304    }
1305
1306    #[test]
1307    fn test_taint_get_nonexistent() {
1308        let store = MemoryStorage::new();
1309        assert_eq!(store.get_taint("no-taint").unwrap(), None);
1310    }
1311
1312    #[test]
1313    fn test_taint_duplicate_active_is_error() {
1314        let store = MemoryStorage::new();
1315        store.create_taint(&test_taint("t1", "/x")).unwrap();
1316        // Same path+name+kind → error
1317        let mut t2 = test_taint("t2", "/x");
1318        t2.name = "test-taint".into(); // same name
1319        assert!(store.create_taint(&t2).is_err());
1320    }
1321
1322    #[test]
1323    fn test_taint_resolve() {
1324        let store = MemoryStorage::new();
1325        store.create_taint(&test_taint("t1", "/x")).unwrap();
1326        store
1327            .resolve_taint("t1", "agent/ops", "fixed", Some("commit-abc"), Utc::now())
1328            .unwrap();
1329
1330        let got = store.get_taint("t1").unwrap().unwrap();
1331        assert!(got.resolved_at.is_some());
1332        assert_eq!(got.resolved_by.as_deref(), Some("agent/ops"));
1333        assert_eq!(got.resolved_reason.as_deref(), Some("fixed"));
1334        assert_eq!(got.resolved_proof.as_deref(), Some("commit-abc"));
1335    }
1336
1337    #[test]
1338    fn test_taint_resolve_twice_is_error() {
1339        let store = MemoryStorage::new();
1340        store.create_taint(&test_taint("t1", "/x")).unwrap();
1341        store
1342            .resolve_taint("t1", "a", "r", None, Utc::now())
1343            .unwrap();
1344        assert!(
1345            store
1346                .resolve_taint("t1", "a", "r2", None, Utc::now())
1347                .is_err()
1348        );
1349    }
1350
1351    #[test]
1352    fn test_taint_list_excludes_resolved_by_default() {
1353        let store = MemoryStorage::new();
1354        store.create_taint(&test_taint("t1", "/x")).unwrap();
1355        store.create_taint(&test_taint("t2", "/y")).unwrap();
1356        store
1357            .resolve_taint("t2", "a", "done", None, Utc::now())
1358            .unwrap();
1359
1360        let active = store.list_taints(None, None, false).unwrap();
1361        assert_eq!(active.len(), 1);
1362        assert_eq!(active[0].id, "t1");
1363
1364        let all = store.list_taints(None, None, true).unwrap();
1365        assert_eq!(all.len(), 2);
1366    }
1367
1368    #[test]
1369    fn test_taint_list_path_prefix_filter() {
1370        let store = MemoryStorage::new();
1371        store
1372            .create_taint(&test_taint("t1", "/nodes/pico1"))
1373            .unwrap();
1374        store
1375            .create_taint(&test_taint("t2", "/nodes/pico2"))
1376            .unwrap();
1377        store.create_taint(&test_taint("t3", "/config")).unwrap();
1378
1379        let nodes = store.list_taints(Some("/nodes"), None, false).unwrap();
1380        assert_eq!(nodes.len(), 2);
1381
1382        let pico1 = store
1383            .list_taints(Some("/nodes/pico1"), None, false)
1384            .unwrap();
1385        assert_eq!(pico1.len(), 1);
1386    }
1387
1388    #[test]
1389    fn test_taint_check_propagation() {
1390        let store = MemoryStorage::new();
1391        // propagate=true — should match child paths
1392        store.create_taint(&test_taint("t1", "/nodes")).unwrap();
1393        // propagate=false — should only match exact path
1394        let mut t2 = test_taint("t2", "/config");
1395        t2.name = "no-propagate".to_string();
1396        t2.propagate = false;
1397        store.create_taint(&t2).unwrap();
1398
1399        let child_hits = store.check_taint("/nodes/pico1").unwrap();
1400        assert_eq!(child_hits.len(), 1, "propagating taint should match child");
1401
1402        let exact_hit = store.check_taint("/config").unwrap();
1403        assert_eq!(exact_hit.len(), 1, "exact match always fires");
1404
1405        let child_no_prop = store.check_taint("/config/network").unwrap();
1406        assert!(
1407            child_no_prop.is_empty(),
1408            "non-propagating should not match child"
1409        );
1410    }
1411
1412    #[test]
1413    fn test_taint_set_commit_id() {
1414        let store = MemoryStorage::new();
1415        store.create_taint(&test_taint("t1", "/x")).unwrap();
1416        store.set_taint_commit_id("t1", "commit-777").unwrap();
1417
1418        let got = store.get_taint("t1").unwrap().unwrap();
1419        assert_eq!(got.commit_id, "commit-777");
1420    }
1421}