openclaw-rs
High-performance sovereign agent runtime in native Rust and Mojo for NVIDIA DGX Spark
Brought by drakestapleton
openclaw-rs / src / persistence.rs
| 1 | use chrono::Utc; |
| 2 | use rusqlite::{params, Connection}; |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use std::fs::OpenOptions; |
| 5 | use std::io::Write; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | use std::sync::{Arc, Mutex}; |
| 8 | use tracing::info; |
| 9 | |
| 10 | use crate::heartbeat::PulseReceipt; |
| 11 | |
| 12 | #[derive(Serialize, Deserialize, Clone, Debug)] |
| 13 | pub struct TaskRecord { |
| 14 | pub id: String, |
| 15 | pub task_type: String, |
| 16 | pub payload: String, |
| 17 | pub status: String, |
| 18 | pub result: Option<String>, |
| 19 | pub created_at: String, |
| 20 | pub completed_at: Option<String>, |
| 21 | } |
| 22 | |
| 23 | #[derive(Serialize, Deserialize, Clone, Debug)] |
| 24 | pub struct CrumbRecord { |
| 25 | pub key: String, |
| 26 | pub value: String, |
| 27 | pub namespace: String, |
| 28 | pub created_at: String, |
| 29 | } |
| 30 | |
| 31 | #[derive(Serialize, Deserialize, Clone, Debug)] |
| 32 | pub struct TurnRecord { |
| 33 | pub id: i64, |
| 34 | pub session_id: String, |
| 35 | pub role: String, |
| 36 | pub prompt: String, |
| 37 | pub response: String, |
| 38 | pub duration_ms: u64, |
| 39 | pub created_at: String, |
| 40 | } |
| 41 | |
| 42 | pub struct Database { |
| 43 | conn: Arc<Mutex<Connection>>, |
| 44 | transcript_path: Option<PathBuf>, |
| 45 | } |
| 46 | |
| 47 | impl Database { |
| 48 | pub fn open(path: &Path) -> Result<Self, rusqlite::Error> { |
| 49 | let conn = Connection::open(path)?; |
| 50 | |
| 51 | let _ = conn.query_row("PRAGMA journal_mode = WAL", [], |_| Ok(())); |
| 52 | conn.execute_batch( |
| 53 | " |
| 54 | PRAGMA synchronous = NORMAL; |
| 55 | PRAGMA temp_store = MEMORY; |
| 56 | PRAGMA cache_size = -64000; |
| 57 | ", |
| 58 | )?; |
| 59 | |
| 60 | let db = Self { |
| 61 | conn: Arc::new(Mutex::new(conn)), |
| 62 | transcript_path: Some(path.with_file_name("events.jsonl")), |
| 63 | }; |
| 64 | db.init_tables()?; |
| 65 | |
| 66 | info!("OpenClaw SQLite WAL database initialized at {:?}", path); |
| 67 | Ok(db) |
| 68 | } |
| 69 | |
| 70 | pub fn open_in_memory() -> Result<Self, rusqlite::Error> { |
| 71 | let conn = Connection::open_in_memory()?; |
| 72 | let _ = conn.query_row("PRAGMA journal_mode = WAL", [], |_| Ok(())); |
| 73 | conn.execute_batch( |
| 74 | " |
| 75 | PRAGMA synchronous = NORMAL; |
| 76 | PRAGMA temp_store = MEMORY; |
| 77 | PRAGMA cache_size = -64000; |
| 78 | ", |
| 79 | )?; |
| 80 | let db = Self { |
| 81 | conn: Arc::new(Mutex::new(conn)), |
| 82 | transcript_path: None, |
| 83 | }; |
| 84 | db.init_tables()?; |
| 85 | Ok(db) |
| 86 | } |
| 87 | |
| 88 | pub fn set_transcript_path(&mut self, path: PathBuf) { |
| 89 | self.transcript_path = Some(path); |
| 90 | } |
| 91 | |
| 92 | fn init_tables(&self) -> Result<(), rusqlite::Error> { |
| 93 | let conn = self.conn.lock().unwrap(); |
| 94 | conn.execute_batch( |
| 95 | " |
| 96 | CREATE TABLE IF NOT EXISTS sessions ( |
| 97 | id TEXT PRIMARY KEY, |
| 98 | title TEXT NOT NULL, |
| 99 | created_at TEXT NOT NULL |
| 100 | ); |
| 101 | |
| 102 | CREATE TABLE IF NOT EXISTS turns ( |
| 103 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 104 | session_id TEXT NOT NULL, |
| 105 | role TEXT NOT NULL, |
| 106 | prompt TEXT NOT NULL, |
| 107 | response TEXT NOT NULL, |
| 108 | duration_ms INTEGER NOT NULL, |
| 109 | created_at TEXT NOT NULL |
| 110 | ); |
| 111 | |
| 112 | CREATE TABLE IF NOT EXISTS heartbeats ( |
| 113 | tick_id INTEGER PRIMARY KEY, |
| 114 | timestamp TEXT NOT NULL, |
| 115 | status TEXT NOT NULL, |
| 116 | tasks_scanned INTEGER NOT NULL, |
| 117 | actions_dispatched INTEGER NOT NULL, |
| 118 | notes TEXT NOT NULL |
| 119 | ); |
| 120 | |
| 121 | CREATE TABLE IF NOT EXISTS tasks ( |
| 122 | id TEXT PRIMARY KEY, |
| 123 | task_type TEXT NOT NULL, |
| 124 | payload TEXT NOT NULL, |
| 125 | status TEXT NOT NULL, |
| 126 | result TEXT, |
| 127 | created_at TEXT NOT NULL, |
| 128 | completed_at TEXT |
| 129 | ); |
| 130 | |
| 131 | CREATE TABLE IF NOT EXISTS memory_crumbs ( |
| 132 | key TEXT PRIMARY KEY, |
| 133 | value TEXT NOT NULL, |
| 134 | namespace TEXT NOT NULL, |
| 135 | created_at TEXT NOT NULL |
| 136 | ); |
| 137 | |
| 138 | CREATE TABLE IF NOT EXISTS skills ( |
| 139 | name TEXT PRIMARY KEY, |
| 140 | description TEXT NOT NULL, |
| 141 | command TEXT NOT NULL, |
| 142 | updated_at TEXT NOT NULL |
| 143 | ); |
| 144 | ", |
| 145 | )?; |
| 146 | Ok(()) |
| 147 | } |
| 148 | |
| 149 | pub fn record_turn( |
| 150 | &self, |
| 151 | role: &str, |
| 152 | prompt: &str, |
| 153 | response: &str, |
| 154 | duration_ms: u64, |
| 155 | ) -> Result<(), rusqlite::Error> { |
| 156 | let conn = self.conn.lock().unwrap(); |
| 157 | conn.execute( |
| 158 | "INSERT INTO turns (session_id, role, prompt, response, duration_ms, created_at) |
| 159 | VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 160 | params![ |
| 161 | "default", |
| 162 | role, |
| 163 | prompt, |
| 164 | response, |
| 165 | duration_ms as i64, |
| 166 | Utc::now().to_rfc3339() |
| 167 | ], |
| 168 | )?; |
| 169 | |
| 170 | self.record_transcript( |
| 171 | "chat_turn", |
| 172 | &serde_json::json!({ |
| 173 | "role": role, |
| 174 | "prompt": prompt, |
| 175 | "response": response, |
| 176 | "duration_ms": duration_ms, |
| 177 | }), |
| 178 | ); |
| 179 | |
| 180 | Ok(()) |
| 181 | } |
| 182 | |
| 183 | pub fn list_recent_turns(&self, limit: usize) -> Result<Vec<TurnRecord>, rusqlite::Error> { |
| 184 | let conn = self.conn.lock().unwrap(); |
| 185 | let mut stmt = conn.prepare( |
| 186 | "SELECT id, session_id, role, prompt, response, duration_ms, created_at |
| 187 | FROM turns ORDER BY id DESC LIMIT ?1", |
| 188 | )?; |
| 189 | let rows = stmt.query_map(params![limit as i64], |row| { |
| 190 | Ok(TurnRecord { |
| 191 | id: row.get(0)?, |
| 192 | session_id: row.get(1)?, |
| 193 | role: row.get(2)?, |
| 194 | prompt: row.get(3)?, |
| 195 | response: row.get(4)?, |
| 196 | duration_ms: row.get::<_, i64>(5)? as u64, |
| 197 | created_at: row.get(6)?, |
| 198 | }) |
| 199 | })?; |
| 200 | |
| 201 | let mut turns = Vec::new(); |
| 202 | for r in rows { |
| 203 | turns.push(r?); |
| 204 | } |
| 205 | Ok(turns) |
| 206 | } |
| 207 | |
| 208 | pub fn record_heartbeat_tick(&self, receipt: &PulseReceipt) -> Result<(), rusqlite::Error> { |
| 209 | let conn = self.conn.lock().unwrap(); |
| 210 | conn.execute( |
| 211 | "INSERT OR REPLACE INTO heartbeats (tick_id, timestamp, status, tasks_scanned, actions_dispatched, notes) |
| 212 | VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 213 | params![ |
| 214 | receipt.tick_id as i64, |
| 215 | receipt.timestamp, |
| 216 | receipt.status, |
| 217 | receipt.tasks_scanned as i64, |
| 218 | receipt.actions_dispatched as i64, |
| 219 | receipt.notes |
| 220 | ], |
| 221 | )?; |
| 222 | |
| 223 | self.record_transcript("heartbeat_tick", &receipt); |
| 224 | Ok(()) |
| 225 | } |
| 226 | |
| 227 | pub fn create_task( |
| 228 | &self, |
| 229 | id: &str, |
| 230 | task_type: &str, |
| 231 | payload: &str, |
| 232 | ) -> Result<(), rusqlite::Error> { |
| 233 | let conn = self.conn.lock().unwrap(); |
| 234 | let now = Utc::now().to_rfc3339(); |
| 235 | conn.execute( |
| 236 | "INSERT INTO tasks (id, task_type, payload, status, created_at) |
| 237 | VALUES (?1, ?2, ?3, 'pending', ?4)", |
| 238 | params![id, task_type, payload, now], |
| 239 | )?; |
| 240 | |
| 241 | self.record_transcript( |
| 242 | "task_created", |
| 243 | &serde_json::json!({ |
| 244 | "id": id, |
| 245 | "task_type": task_type, |
| 246 | "payload": payload, |
| 247 | }), |
| 248 | ); |
| 249 | Ok(()) |
| 250 | } |
| 251 | |
| 252 | pub fn list_pending_tasks(&self) -> Result<Vec<TaskRecord>, rusqlite::Error> { |
| 253 | let conn = self.conn.lock().unwrap(); |
| 254 | let mut stmt = conn.prepare( |
| 255 | "SELECT id, task_type, payload, status, result, created_at, completed_at |
| 256 | FROM tasks WHERE status = 'pending' ORDER BY created_at ASC", |
| 257 | )?; |
| 258 | let rows = stmt.query_map([], |row| { |
| 259 | Ok(TaskRecord { |
| 260 | id: row.get(0)?, |
| 261 | task_type: row.get(1)?, |
| 262 | payload: row.get(2)?, |
| 263 | status: row.get(3)?, |
| 264 | result: row.get(4)?, |
| 265 | created_at: row.get(5)?, |
| 266 | completed_at: row.get(6)?, |
| 267 | }) |
| 268 | })?; |
| 269 | |
| 270 | let mut tasks = Vec::new(); |
| 271 | for r in rows { |
| 272 | tasks.push(r?); |
| 273 | } |
| 274 | Ok(tasks) |
| 275 | } |
| 276 | |
| 277 | pub fn complete_task(&self, id: &str, result: &str) -> Result<(), rusqlite::Error> { |
| 278 | let conn = self.conn.lock().unwrap(); |
| 279 | let now = Utc::now().to_rfc3339(); |
| 280 | conn.execute( |
| 281 | "UPDATE tasks SET status = 'completed', result = ?1, completed_at = ?2 WHERE id = ?3", |
| 282 | params![result, now, id], |
| 283 | )?; |
| 284 | |
| 285 | self.record_transcript( |
| 286 | "task_completed", |
| 287 | &serde_json::json!({ |
| 288 | "id": id, |
| 289 | "result": result, |
| 290 | "completed_at": now, |
| 291 | }), |
| 292 | ); |
| 293 | Ok(()) |
| 294 | } |
| 295 | |
| 296 | pub fn store_crumb( |
| 297 | &self, |
| 298 | key: &str, |
| 299 | value: &str, |
| 300 | namespace: &str, |
| 301 | ) -> Result<(), rusqlite::Error> { |
| 302 | let conn = self.conn.lock().unwrap(); |
| 303 | let now = Utc::now().to_rfc3339(); |
| 304 | conn.execute( |
| 305 | "INSERT OR REPLACE INTO memory_crumbs (key, value, namespace, created_at) |
| 306 | VALUES (?1, ?2, ?3, ?4)", |
| 307 | params![key, value, namespace, now], |
| 308 | )?; |
| 309 | |
| 310 | self.record_transcript( |
| 311 | "memory_crumb", |
| 312 | &serde_json::json!({ |
| 313 | "key": key, |
| 314 | "value": value, |
| 315 | "namespace": namespace, |
| 316 | }), |
| 317 | ); |
| 318 | Ok(()) |
| 319 | } |
| 320 | |
| 321 | pub fn get_recent_crumbs( |
| 322 | &self, |
| 323 | namespace: &str, |
| 324 | limit: usize, |
| 325 | ) -> Result<Vec<CrumbRecord>, rusqlite::Error> { |
| 326 | let conn = self.conn.lock().unwrap(); |
| 327 | let mut stmt = conn.prepare( |
| 328 | "SELECT key, value, namespace, created_at |
| 329 | FROM memory_crumbs WHERE namespace = ?1 ORDER BY created_at DESC LIMIT ?2", |
| 330 | )?; |
| 331 | let rows = stmt.query_map(params![namespace, limit as i64], |row| { |
| 332 | Ok(CrumbRecord { |
| 333 | key: row.get(0)?, |
| 334 | value: row.get(1)?, |
| 335 | namespace: row.get(2)?, |
| 336 | created_at: row.get(3)?, |
| 337 | }) |
| 338 | })?; |
| 339 | |
| 340 | let mut crumbs = Vec::new(); |
| 341 | for r in rows { |
| 342 | crumbs.push(r?); |
| 343 | } |
| 344 | Ok(crumbs) |
| 345 | } |
| 346 | |
| 347 | pub fn record_transcript<T: Serialize>(&self, event_type: &str, data: &T) { |
| 348 | if let Some(ref path) = self.transcript_path { |
| 349 | let event = serde_json::json!({ |
| 350 | "timestamp": Utc::now().to_rfc3339(), |
| 351 | "event_type": event_type, |
| 352 | "data": data, |
| 353 | }); |
| 354 | if let Ok(line) = serde_json::to_string(&event) { |
| 355 | if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) { |
| 356 | let _ = writeln!(file, "{}", line); |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | #[cfg(test)] |
| 364 | mod tests { |
| 365 | use super::*; |
| 366 | |
| 367 | #[test] |
| 368 | fn test_task_lifecycle_and_crumbs() { |
| 369 | let db = Database::open_in_memory().unwrap(); |
| 370 | db.create_task("t1", "build_check", "cargo check").unwrap(); |
| 371 | |
| 372 | let pending = db.list_pending_tasks().unwrap(); |
| 373 | assert_eq!(pending.len(), 1); |
| 374 | assert_eq!(pending[0].id, "t1"); |
| 375 | assert_eq!(pending[0].task_type, "build_check"); |
| 376 | |
| 377 | db.complete_task("t1", "passed").unwrap(); |
| 378 | let remaining = db.list_pending_tasks().unwrap(); |
| 379 | assert_eq!(remaining.len(), 0); |
| 380 | |
| 381 | db.store_crumb("summary", "all tests passed", "cortex") |
| 382 | .unwrap(); |
| 383 | let crumbs = db.get_recent_crumbs("cortex", 10).unwrap(); |
| 384 | assert_eq!(crumbs.len(), 1); |
| 385 | assert_eq!(crumbs[0].key, "summary"); |
| 386 | assert_eq!(crumbs[0].value, "all tests passed"); |
| 387 | } |
| 388 | } |