interplane.Get Omega
Read in your language

aegis-runtime-mv

Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.

Brought by drakestapleton

branch main Branches Tags History

aegis-runtime-mv / src / persistence / legacy.rs

299 lines · 9286 bytes Raw Blame History
1use chrono::Utc;
2use rusqlite::{params, Connection};
3use serde::{Deserialize, Serialize};
4use std::fs::OpenOptions;
5use std::io::Write;
6use std::path::{Path, PathBuf};
7use std::sync::{Arc, Mutex};
8use tracing::info;
9
10use super::async_db::AsyncDatabase;
11use super::sqlite::schema::initialize_schema;
12use super::task_lifecycle::{lock_file, TaskOwner};
13use crate::heartbeat::PulseReceipt;
14
15#[derive(Serialize, Deserialize, Clone, Debug)]
16pub struct TaskRecord {
17 pub id: String,
18 pub task_type: String,
19 pub payload: String,
20 pub status: String,
21 pub result: Option<String>,
22 pub created_at: String,
23 pub completed_at: Option<String>,
24}
25
26#[derive(Serialize, Deserialize, Clone, Debug)]
27pub struct CrumbRecord {
28 pub key: String,
29 pub value: String,
30 pub namespace: String,
31 pub created_at: String,
32}
33
34#[derive(Serialize, Deserialize, Clone, Debug)]
35pub struct TurnRecord {
36 pub id: i64,
37 pub session_id: String,
38 pub role: String,
39 pub prompt: String,
40 pub response: String,
41 pub duration_ms: u64,
42 pub created_at: String,
43}
44
45pub struct Database {
46 pub(super) conn: Arc<Mutex<Connection>>,
47 pub(super) transcript_path: Option<PathBuf>,
48 pub(super) owner: TaskOwner,
49}
50
51impl Database {
52 pub fn open(path: &Path) -> Result<Self, rusqlite::Error> {
53 let conn = Connection::open(path)?;
54 let transcript_path = path.parent().map(|p| p.join("transcript.jsonl"));
55 let db = Self {
56 conn: Arc::new(Mutex::new(conn)),
57 transcript_path,
58 owner: TaskOwner::new(Some(path))?,
59 };
60 db.init_tables()?;
61 db.recover_abandoned_tasks()?;
62 db.export_terminal_events()?;
63 Ok(db)
64 }
65
66 pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
67 let conn = Connection::open_in_memory()?;
68 let db = Self {
69 conn: Arc::new(Mutex::new(conn)),
70 transcript_path: None,
71 owner: TaskOwner::new(None)?,
72 };
73 db.init_tables()?;
74 Ok(db)
75 }
76
77 pub fn to_async(&self) -> AsyncDatabase {
78 AsyncDatabase::from_connection_arc(Arc::clone(&self.conn), self.transcript_path.clone())
79 }
80
81 pub fn init_tables(&self) -> Result<(), rusqlite::Error> {
82 let conn = self.conn.lock().unwrap();
83 initialize_schema(&conn)?;
84 info!("SQLite tables initialized");
85 Ok(())
86 }
87
88 pub fn record_turn(
89 &self,
90 role: &str,
91 prompt: &str,
92 response: &str,
93 duration_ms: u64,
94 ) -> Result<(), rusqlite::Error> {
95 let conn = self.conn.lock().unwrap();
96 conn.execute(
97 "INSERT INTO turns (session_id, role, prompt, response, duration_ms, created_at)
98 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
99 params![
100 "default",
101 role,
102 prompt,
103 response,
104 duration_ms as i64,
105 Utc::now().to_rfc3339()
106 ],
107 )?;
108
109 self.record_transcript(
110 "chat_turn",
111 &serde_json::json!({
112 "role": role,
113 "prompt": prompt,
114 "response": response,
115 "duration_ms": duration_ms,
116 }),
117 )?;
118
119 Ok(())
120 }
121
122 pub fn list_recent_turns(&self, limit: usize) -> Result<Vec<TurnRecord>, rusqlite::Error> {
123 let conn = self.conn.lock().unwrap();
124 let mut stmt = conn.prepare(
125 "SELECT id, session_id, role, prompt, response, duration_ms, created_at
126 FROM turns ORDER BY id DESC LIMIT ?1",
127 )?;
128 let rows = stmt.query_map(params![limit as i64], |row| {
129 Ok(TurnRecord {
130 id: row.get(0)?,
131 session_id: row.get(1)?,
132 role: row.get(2)?,
133 prompt: row.get(3)?,
134 response: row.get(4)?,
135 duration_ms: row.get::<_, i64>(5)? as u64,
136 created_at: row.get(6)?,
137 })
138 })?;
139
140 let mut turns = Vec::new();
141 for r in rows {
142 turns.push(r?);
143 }
144 Ok(turns)
145 }
146
147 /// Projection failure changes the receipt before its authoritative SQLite transaction commits.
148 pub fn record_heartbeat_tick(&self, receipt: &mut PulseReceipt) -> Result<(), rusqlite::Error> {
149 let mut conn = self.conn.lock().unwrap();
150 let tx = conn.transaction()?;
151 tx.execute(
152 "INSERT OR REPLACE INTO heartbeats (tick_id, timestamp, status, tasks_scanned, actions_dispatched, notes)
153 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
154 params![
155 receipt.tick_id as i64,
156 receipt.timestamp,
157 receipt.status,
158 receipt.tasks_scanned as i64,
159 receipt.actions_dispatched as i64,
160 receipt.notes
161 ],
162 )?;
163 if let Err(error) = self.record_transcript("heartbeat_tick", receipt) {
164 receipt.status = "degraded";
165 receipt
166 .notes
167 .push_str(&format!("; receipt projection failed: {}", error));
168 tracing::warn!("Heartbeat transcript projection failed: {}", error);
169 tx.execute(
170 "UPDATE heartbeats SET status=?2,notes=?3 WHERE tick_id=?1",
171 params![receipt.tick_id as i64, receipt.status, receipt.notes],
172 )?;
173 }
174 tx.commit()
175 }
176
177 pub fn create_task(
178 &self,
179 id: &str,
180 task_type: &str,
181 payload: &str,
182 ) -> Result<(), rusqlite::Error> {
183 let conn = self.conn.lock().unwrap();
184 let now = Utc::now().to_rfc3339();
185 conn.execute(
186 "INSERT INTO tasks (id, task_type, payload, status, created_at)
187 VALUES (?1, ?2, ?3, 'pending', ?4)",
188 params![id, task_type, payload, now],
189 )?;
190
191 self.record_transcript(
192 "task_created",
193 &serde_json::json!({
194 "id": id,
195 "task_type": task_type,
196 "payload": payload,
197 }),
198 )?;
199 Ok(())
200 }
201
202 pub fn list_pending_tasks(&self) -> Result<Vec<TaskRecord>, rusqlite::Error> {
203 let conn = self.conn.lock().unwrap();
204 let mut stmt = conn.prepare(
205 "SELECT id, task_type, payload, status, result, created_at, completed_at
206 FROM tasks WHERE status = 'pending' ORDER BY created_at ASC",
207 )?;
208 let rows = stmt.query_map([], |row| {
209 Ok(TaskRecord {
210 id: row.get(0)?,
211 task_type: row.get(1)?,
212 payload: row.get(2)?,
213 status: row.get(3)?,
214 result: row.get(4)?,
215 created_at: row.get(5)?,
216 completed_at: row.get(6)?,
217 })
218 })?;
219
220 let mut tasks = Vec::new();
221 for r in rows {
222 tasks.push(r?);
223 }
224 Ok(tasks)
225 }
226
227 pub fn store_crumb(
228 &self,
229 key: &str,
230 value: &str,
231 namespace: &str,
232 ) -> Result<(), rusqlite::Error> {
233 let conn = self.conn.lock().unwrap();
234 let now = Utc::now().to_rfc3339();
235 conn.execute(
236 "INSERT OR REPLACE INTO memory_crumbs (key, value, namespace, created_at)
237 VALUES (?1, ?2, ?3, ?4)",
238 params![key, value, namespace, now],
239 )?;
240
241 self.record_transcript(
242 "memory_crumb",
243 &serde_json::json!({
244 "key": key,
245 "value": value,
246 "namespace": namespace,
247 }),
248 )?;
249 Ok(())
250 }
251
252 pub fn get_recent_crumbs(
253 &self,
254 namespace: &str,
255 limit: usize,
256 ) -> Result<Vec<CrumbRecord>, rusqlite::Error> {
257 let conn = self.conn.lock().unwrap();
258 let mut stmt = conn.prepare(
259 "SELECT key, value, namespace, created_at
260 FROM memory_crumbs WHERE namespace = ?1 ORDER BY created_at DESC LIMIT ?2",
261 )?;
262 let rows = stmt.query_map(params![namespace, limit as i64], |row| {
263 Ok(CrumbRecord {
264 key: row.get(0)?,
265 value: row.get(1)?,
266 namespace: row.get(2)?,
267 created_at: row.get(3)?,
268 })
269 })?;
270
271 let mut crumbs = Vec::new();
272 for r in rows {
273 crumbs.push(r?);
274 }
275 Ok(crumbs)
276 }
277
278 pub fn record_transcript<T: Serialize>(
279 &self,
280 event_type: &str,
281 data: &T,
282 ) -> Result<(), rusqlite::Error> {
283 if let Some(path) = &self.transcript_path {
284 let event = serde_json::json!({
285 "timestamp": Utc::now().to_rfc3339(),
286 "event_type": event_type,
287 "data": data,
288 });
289 let write = || -> std::io::Result<()> {
290 let _writer = lock_file(&path.with_extension("jsonl.lock"), false)?;
291 let mut file = OpenOptions::new().create(true).append(true).open(path)?;
292 writeln!(file, "{}", event)?;
293 file.sync_all()
294 };
295 write().map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
296 }
297 Ok(())
298 }
299}