Skip to main content

aidaemon_core/
store.rs

1use std::collections::HashMap;
2use std::sync::Mutex;
3
4use async_trait::async_trait;
5
6use crate::event::Event;
7use crate::state::{RunId, RunState};
8
9#[derive(Debug, Clone, PartialEq, thiserror::Error)]
10#[error("run store error: {0}")]
11pub struct StoreError(pub String);
12
13/// Durable home for runs: an append-only event journal plus the latest state
14/// snapshot. The loop saves state after every turn and at every exit, so a
15/// crash loses at most the turn in flight.
16///
17/// This is the whole persistence contract the kernel needs. Domain data
18/// (memory, goals, people) belongs to the plugin crates that own it.
19#[async_trait]
20pub trait RunStore: Send + Sync {
21    async fn append_event(&self, run_id: RunId, event: &Event) -> Result<(), StoreError>;
22    async fn save_state(&self, state: &RunState) -> Result<(), StoreError>;
23    async fn load_state(&self, run_id: RunId) -> Result<Option<RunState>, StoreError>;
24}
25
26/// In-process store for tests and short-lived agents.
27#[derive(Default)]
28pub struct MemoryStore {
29    events: Mutex<HashMap<RunId, Vec<Event>>>,
30    states: Mutex<HashMap<RunId, RunState>>,
31}
32
33impl MemoryStore {
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    pub fn events(&self, run_id: RunId) -> Vec<Event> {
39        self.events
40            .lock()
41            .expect("memory store poisoned")
42            .get(&run_id)
43            .cloned()
44            .unwrap_or_default()
45    }
46}
47
48#[async_trait]
49impl RunStore for MemoryStore {
50    async fn append_event(&self, run_id: RunId, event: &Event) -> Result<(), StoreError> {
51        self.events
52            .lock()
53            .map_err(|e| StoreError(e.to_string()))?
54            .entry(run_id)
55            .or_default()
56            .push(event.clone());
57        Ok(())
58    }
59
60    async fn save_state(&self, state: &RunState) -> Result<(), StoreError> {
61        self.states
62            .lock()
63            .map_err(|e| StoreError(e.to_string()))?
64            .insert(state.run_id, state.clone());
65        Ok(())
66    }
67
68    async fn load_state(&self, run_id: RunId) -> Result<Option<RunState>, StoreError> {
69        Ok(self
70            .states
71            .lock()
72            .map_err(|e| StoreError(e.to_string()))?
73            .get(&run_id)
74            .cloned())
75    }
76}