diff --git a/src/defense/approval.rs b/src/defense/approval.rs new file mode 100644 index 0000000..2a7e0c6 --- /dev/null +++ b/src/defense/approval.rs @@ -0,0 +1,66 @@ +use crate::sessions::id::{ActionId, ApprovalId, RunId, SessionId}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ApprovalStatus { + Pending, + Approved, + Rejected, + Expired, +} + +impl ApprovalStatus { + pub fn as_str(&self) -> &'static str { + match self { + Self::Pending => "pending", + Self::Approved => "approved", + Self::Rejected => "rejected", + Self::Expired => "expired", + } + } + + pub fn from_str(s: &str) -> Option { + match s { + "pending" => Some(Self::Pending), + "approved" => Some(Self::Approved), + "rejected" => Some(Self::Rejected), + "expired" => Some(Self::Expired), + _ => None, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Approval { + pub id: ApprovalId, + pub action_id: ActionId, + pub run_id: RunId, + pub session_id: SessionId, + pub prompt: String, + pub status: ApprovalStatus, + pub requested_at: i64, + pub decided_at: Option, + pub decided_by: Option, +} + +impl Approval { + pub fn new( + action_id: ActionId, + run_id: RunId, + session_id: SessionId, + prompt: impl Into, + ) -> Self { + Self { + id: ApprovalId::new(), + action_id, + run_id, + session_id, + prompt: prompt.into(), + status: ApprovalStatus::Pending, + requested_at: chrono::Utc::now().timestamp(), + decided_at: None, + decided_by: None, + } + } +} diff --git a/src/defense/mod.rs b/src/defense/mod.rs index d08a10b..c68cc7d 100644 --- a/src/defense/mod.rs +++ b/src/defense/mod.rs @@ -1,5 +1,7 @@ +pub mod approval; pub mod decision; pub mod receipt; +pub use approval::{Approval, ApprovalStatus}; pub use decision::{ContainmentLevel, DoctrineDecision}; pub use receipt::DefenseReceipt; diff --git a/src/execution/action.rs b/src/execution/action.rs new file mode 100644 index 0000000..288a5aa --- /dev/null +++ b/src/execution/action.rs @@ -0,0 +1,76 @@ +use crate::execution::receipt::ActionReceipt; +use crate::sessions::id::{ActionId, RunId, SessionId}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ActionStatus { + Pending, + Approved, + Denied, + Executing, + Completed, + Failed, +} + +impl ActionStatus { + pub fn as_str(&self) -> &'static str { + match self { + Self::Pending => "pending", + Self::Approved => "approved", + Self::Denied => "denied", + Self::Executing => "executing", + Self::Completed => "completed", + Self::Failed => "failed", + } + } + + pub fn from_str(s: &str) -> Option { + match s { + "pending" => Some(Self::Pending), + "approved" => Some(Self::Approved), + "denied" => Some(Self::Denied), + "executing" => Some(Self::Executing), + "completed" => Some(Self::Completed), + "failed" => Some(Self::Failed), + _ => None, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Action { + pub id: ActionId, + pub run_id: RunId, + pub session_id: SessionId, + pub capability: String, + pub intent: String, + pub params: serde_json::Value, + pub status: ActionStatus, + pub receipt: Option, + pub created_at: i64, + pub completed_at: Option, +} + +impl Action { + pub fn new( + run_id: RunId, + session_id: SessionId, + capability: impl Into, + intent: impl Into, + params: serde_json::Value, + ) -> Self { + Self { + id: ActionId::new(), + run_id, + session_id, + capability: capability.into(), + intent: intent.into(), + params, + status: ActionStatus::Pending, + receipt: None, + created_at: chrono::Utc::now().timestamp(), + completed_at: None, + } + } +} diff --git a/src/execution/broker.rs b/src/execution/broker.rs new file mode 100644 index 0000000..daf31ed --- /dev/null +++ b/src/execution/broker.rs @@ -0,0 +1,18 @@ +use crate::defense::DoctrineDecision; +use async_trait::async_trait; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ActionRequest { + pub session_id: String, + pub run_id: String, + pub capability: String, + pub intent: String, + pub target: String, + pub params: serde_json::Value, +} + +#[async_trait] +pub trait ExecutionAuthority: Send + Sync { + async fn authorize(&self, request: &ActionRequest) -> Result; +} diff --git a/src/execution/mod.rs b/src/execution/mod.rs index 1d912a3..b1477bf 100644 --- a/src/execution/mod.rs +++ b/src/execution/mod.rs @@ -1,3 +1,7 @@ +pub mod action; +pub mod broker; pub mod receipt; +pub use action::{Action, ActionStatus}; +pub use broker::{ActionRequest, ExecutionAuthority}; pub use receipt::ActionReceipt; diff --git a/src/execution/receipt.rs b/src/execution/receipt.rs index 94cc999..27d9967 100644 --- a/src/execution/receipt.rs +++ b/src/execution/receipt.rs @@ -1,6 +1,5 @@ use crate::defense::DoctrineDecision; use serde::{Deserialize, Serialize}; -use std::time::Duration; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ActionReceipt { diff --git a/src/gateway.rs b/src/gateway.rs index 58b966c..7849f43 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -19,7 +19,6 @@ use std::convert::Infallible; use std::net::SocketAddr; use std::sync::Arc; use std::time::Instant; -use tokio::process::Command; use tokio_stream::wrappers::BroadcastStream; use tower_http::cors::{Any, CorsLayer}; use tracing::info; diff --git a/src/lib.rs b/src/lib.rs index eed3526..c87c21a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,9 +14,9 @@ pub mod skills; pub mod vault; pub use agent::{AgentEngine, AgentExecutionResult, AgentStep}; -pub use defense::{ContainmentLevel, DefenseReceipt, DoctrineDecision}; +pub use defense::{Approval, ApprovalStatus, ContainmentLevel, DefenseReceipt, DoctrineDecision}; pub use events::{AegisEvent, EventBus, EventEnvelope, EventId, EventSubscriber}; -pub use execution::ActionReceipt; +pub use execution::{Action, ActionReceipt, ActionRequest, ActionStatus, ExecutionAuthority}; pub use gateway::{create_router, start_gateway, GatewayState, HealthResponse}; pub use heartbeat::{HeartbeatEngine, PulseReceipt}; pub use inference::{ @@ -25,12 +25,15 @@ pub use inference::{ }; pub use mojo_bridge::MojoSimdBridge; pub use orchestration::{Run, RunBudget, RunState, TerminationReason, Trigger}; -pub use persistence::{CrumbRecord, Database, TaskRecord, TurnRecord}; +pub use persistence::{ + AsyncDatabase, CrumbRecord, Database, PersistenceError, SqliteActionStore, SqliteApprovalStore, + SqliteMessageStore, SqliteRunStore, SqliteSessionStore, TaskRecord, TurnRecord, +}; pub use security::{SecurityError, WorkspaceCapability}; pub use sessions::{ - ActionId, ApprovalId, AssistantMessage, Message, MessageId, MessageStore, Role, RunId, Session, - SessionBudget, SessionId, SessionStatus, SessionStore, SystemMessage, ToolResultMessage, - UserMessage, + ActionId, ActionStore, ApprovalId, ApprovalStore, AssistantMessage, Message, MessageId, + MessageStore, Role, RunId, RunStore, Session, SessionBudget, SessionId, SessionStatus, + SessionStore, SystemMessage, ToolResultMessage, UserMessage, }; pub use skills::{SkillDefinition, SkillExecutionRequest, SkillExecutionResponse, SkillRegistry}; pub use vault::{VaultResolver, REDACTED_MARKER}; diff --git a/src/orchestration/budget.rs b/src/orchestration/budget.rs index 9889b43..9c9430a 100644 --- a/src/orchestration/budget.rs +++ b/src/orchestration/budget.rs @@ -1,5 +1,4 @@ use serde::{Deserialize, Serialize}; -use std::time::Duration; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RunBudget { diff --git a/src/orchestration/run.rs b/src/orchestration/run.rs index 75052db..72034f7 100644 --- a/src/orchestration/run.rs +++ b/src/orchestration/run.rs @@ -16,6 +16,31 @@ pub enum RunState { Cancelled, } +impl RunState { + pub fn as_str(&self) -> &'static str { + match self { + Self::Running => "running", + Self::WaitingForApproval => "waiting_for_approval", + Self::WaitingForTool => "waiting_for_tool", + Self::Completed => "completed", + Self::Failed => "failed", + Self::Cancelled => "cancelled", + } + } + + pub fn from_str(s: &str) -> Option { + match s { + "running" => Some(Self::Running), + "waiting_for_approval" => Some(Self::WaitingForApproval), + "waiting_for_tool" => Some(Self::WaitingForTool), + "completed" => Some(Self::Completed), + "failed" => Some(Self::Failed), + "cancelled" => Some(Self::Cancelled), + _ => None, + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Run { pub id: RunId, diff --git a/src/persistence/async_db.rs b/src/persistence/async_db.rs new file mode 100644 index 0000000..6a8e154 --- /dev/null +++ b/src/persistence/async_db.rs @@ -0,0 +1,64 @@ +use super::error::PersistenceError; +use super::sqlite::schema::initialize_schema; +use rusqlite::Connection; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +#[derive(Clone)] +pub struct AsyncDatabase { + conn: Arc>, + transcript_path: Option, +} + +impl AsyncDatabase { + pub fn open(path: &Path) -> Result { + let conn = Connection::open(path)?; + initialize_schema(&conn)?; + let transcript_path = path.parent().map(|p| p.join("transcript.jsonl")); + Ok(Self { + conn: Arc::new(Mutex::new(conn)), + transcript_path, + }) + } + + pub fn open_in_memory() -> Result { + let conn = Connection::open_in_memory()?; + initialize_schema(&conn)?; + Ok(Self { + conn: Arc::new(Mutex::new(conn)), + transcript_path: None, + }) + } + + pub fn from_connection_arc( + conn: Arc>, + transcript_path: Option, + ) -> Self { + Self { + conn, + transcript_path, + } + } + + pub fn shared_conn(&self) -> Arc> { + Arc::clone(&self.conn) + } + + pub fn transcript_path(&self) -> Option<&PathBuf> { + self.transcript_path.as_ref() + } + + pub async fn interact(&self, f: F) -> Result + where + F: FnOnce(&mut Connection) -> Result + Send + 'static, + R: Send + 'static, + { + let conn = Arc::clone(&self.conn); + tokio::task::spawn_blocking(move || { + let mut guard = conn.lock().map_err(|_| PersistenceError::LockPoisoned)?; + f(&mut guard) + }) + .await + .map_err(|e| PersistenceError::TaskJoin(e.to_string()))? + } +} diff --git a/src/persistence/error.rs b/src/persistence/error.rs new file mode 100644 index 0000000..8389a1a --- /dev/null +++ b/src/persistence/error.rs @@ -0,0 +1,64 @@ +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PersistenceError { + Sqlite(String), + NotFound(String), + ConcurrencyConflict { + id: String, + expected_version: u64, + }, + ActiveRunConflict { + session_id: String, + active_run_id: String, + }, + Serialization(String), + LockPoisoned, + TaskJoin(String), + Other(String), +} + +impl fmt::Display for PersistenceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Sqlite(e) => write!(f, "SQLite error: {e}"), + Self::NotFound(msg) => write!(f, "Record not found: {msg}"), + Self::ConcurrencyConflict { + id, + expected_version, + } => { + write!( + f, + "Concurrency conflict on {id}: expected version {expected_version}" + ) + } + Self::ActiveRunConflict { + session_id, + active_run_id, + } => { + write!( + f, + "Session {session_id} already has active run: {active_run_id}" + ) + } + Self::Serialization(e) => write!(f, "Serialization error: {e}"), + Self::LockPoisoned => write!(f, "Database lock poisoned"), + Self::TaskJoin(e) => write!(f, "Task join error: {e}"), + Self::Other(msg) => write!(f, "Persistence error: {msg}"), + } + } +} + +impl std::error::Error for PersistenceError {} + +impl From for PersistenceError { + fn from(err: rusqlite::Error) -> Self { + Self::Sqlite(err.to_string()) + } +} + +impl From for PersistenceError { + fn from(err: serde_json::Error) -> Self { + Self::Serialization(err.to_string()) + } +} diff --git a/src/persistence.rs b/src/persistence/legacy.rs similarity index 70% rename from src/persistence.rs rename to src/persistence/legacy.rs index aca6a91..f90d7f0 100644 --- a/src/persistence.rs +++ b/src/persistence/legacy.rs @@ -7,6 +7,8 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use tracing::info; +use super::async_db::AsyncDatabase; +use super::sqlite::schema::initialize_schema; use crate::heartbeat::PulseReceipt; #[derive(Serialize, Deserialize, Clone, Debug)] @@ -47,36 +49,17 @@ pub struct Database { impl Database { pub fn open(path: &Path) -> Result { let conn = Connection::open(path)?; - - let _ = conn.query_row("PRAGMA journal_mode = WAL", [], |_| Ok(())); - conn.execute_batch( - " - PRAGMA synchronous = NORMAL; - PRAGMA temp_store = MEMORY; - PRAGMA cache_size = -64000; - ", - )?; - + let transcript_path = path.parent().map(|p| p.join("transcript.jsonl")); let db = Self { conn: Arc::new(Mutex::new(conn)), - transcript_path: Some(path.with_file_name("events.jsonl")), + transcript_path, }; db.init_tables()?; - - info!("OpenClaw SQLite WAL database initialized at {:?}", path); Ok(db) } pub fn open_in_memory() -> Result { let conn = Connection::open_in_memory()?; - let _ = conn.query_row("PRAGMA journal_mode = WAL", [], |_| Ok(())); - conn.execute_batch( - " - PRAGMA synchronous = NORMAL; - PRAGMA temp_store = MEMORY; - PRAGMA cache_size = -64000; - ", - )?; let db = Self { conn: Arc::new(Mutex::new(conn)), transcript_path: None, @@ -85,64 +68,14 @@ impl Database { Ok(db) } - pub fn set_transcript_path(&mut self, path: PathBuf) { - self.transcript_path = Some(path); + pub fn to_async(&self) -> AsyncDatabase { + AsyncDatabase::from_connection_arc(Arc::clone(&self.conn), self.transcript_path.clone()) } - fn init_tables(&self) -> Result<(), rusqlite::Error> { + pub fn init_tables(&self) -> Result<(), rusqlite::Error> { let conn = self.conn.lock().unwrap(); - conn.execute_batch( - " - CREATE TABLE IF NOT EXISTS sessions ( - id TEXT PRIMARY KEY, - title TEXT NOT NULL, - created_at TEXT NOT NULL - ); - - CREATE TABLE IF NOT EXISTS turns ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - session_id TEXT NOT NULL, - role TEXT NOT NULL, - prompt TEXT NOT NULL, - response TEXT NOT NULL, - duration_ms INTEGER NOT NULL, - created_at TEXT NOT NULL - ); - - CREATE TABLE IF NOT EXISTS heartbeats ( - tick_id INTEGER PRIMARY KEY, - timestamp TEXT NOT NULL, - status TEXT NOT NULL, - tasks_scanned INTEGER NOT NULL, - actions_dispatched INTEGER NOT NULL, - notes TEXT NOT NULL - ); - - CREATE TABLE IF NOT EXISTS tasks ( - id TEXT PRIMARY KEY, - task_type TEXT NOT NULL, - payload TEXT NOT NULL, - status TEXT NOT NULL, - result TEXT, - created_at TEXT NOT NULL, - completed_at TEXT - ); - - CREATE TABLE IF NOT EXISTS memory_crumbs ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL, - namespace TEXT NOT NULL, - created_at TEXT NOT NULL - ); - - CREATE TABLE IF NOT EXISTS skills ( - name TEXT PRIMARY KEY, - description TEXT NOT NULL, - command TEXT NOT NULL, - updated_at TEXT NOT NULL - ); - ", - )?; + initialize_schema(&conn)?; + info!("SQLite tables initialized"); Ok(()) } @@ -359,30 +292,3 @@ impl Database { } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_task_lifecycle_and_crumbs() { - let db = Database::open_in_memory().unwrap(); - db.create_task("t1", "build_check", "cargo check").unwrap(); - - let pending = db.list_pending_tasks().unwrap(); - assert_eq!(pending.len(), 1); - assert_eq!(pending[0].id, "t1"); - assert_eq!(pending[0].task_type, "build_check"); - - db.complete_task("t1", "passed").unwrap(); - let remaining = db.list_pending_tasks().unwrap(); - assert_eq!(remaining.len(), 0); - - db.store_crumb("summary", "all tests passed", "cortex") - .unwrap(); - let crumbs = db.get_recent_crumbs("cortex", 10).unwrap(); - assert_eq!(crumbs.len(), 1); - assert_eq!(crumbs[0].key, "summary"); - assert_eq!(crumbs[0].value, "all tests passed"); - } -} diff --git a/src/persistence/mod.rs b/src/persistence/mod.rs new file mode 100644 index 0000000..f96ea10 --- /dev/null +++ b/src/persistence/mod.rs @@ -0,0 +1,11 @@ +pub mod async_db; +pub mod error; +pub mod legacy; +pub mod sqlite; + +pub use async_db::AsyncDatabase; +pub use error::PersistenceError; +pub use legacy::{CrumbRecord, Database, TaskRecord, TurnRecord}; +pub use sqlite::{ + SqliteActionStore, SqliteApprovalStore, SqliteMessageStore, SqliteRunStore, SqliteSessionStore, +}; diff --git a/src/persistence/sqlite/actions.rs b/src/persistence/sqlite/actions.rs new file mode 100644 index 0000000..3a6e979 --- /dev/null +++ b/src/persistence/sqlite/actions.rs @@ -0,0 +1,178 @@ +use crate::execution::action::{Action, ActionStatus}; +use crate::execution::receipt::ActionReceipt; +use crate::persistence::async_db::AsyncDatabase; +use crate::persistence::error::PersistenceError; +use crate::sessions::id::{ActionId, RunId, SessionId}; +use crate::sessions::store::ActionStore; +use async_trait::async_trait; +use rusqlite::params; + +#[derive(Clone)] +pub struct SqliteActionStore { + db: AsyncDatabase, +} + +impl SqliteActionStore { + pub fn new(db: AsyncDatabase) -> Self { + Self { db } + } +} + +#[async_trait] +impl ActionStore for SqliteActionStore { + async fn create(&self, action: &Action) -> Result<(), PersistenceError> { + let action = action.clone(); + self.db + .interact(move |conn| { + let params_str = serde_json::to_string(&action.params)?; + let receipt_str = action + .receipt + .as_ref() + .map(|r| serde_json::to_string(r)) + .transpose()?; + + conn.execute( + "INSERT INTO actions (id, run_id, session_id, capability, intent, params_json, status, receipt_json, created_at, completed_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", + params![ + action.id.as_str(), + action.run_id.as_str(), + action.session_id.as_str(), + action.capability, + action.intent, + params_str, + action.status.as_str(), + receipt_str, + action.created_at, + action.completed_at, + ], + )?; + Ok(()) + }) + .await + } + + async fn get(&self, id: &ActionId) -> Result, PersistenceError> { + let id_str = id.to_string(); + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT id, run_id, session_id, capability, intent, params_json, status, receipt_json, created_at, completed_at + FROM actions WHERE id = ?1", + )?; + let mut rows = stmt.query(params![id_str])?; + if let Some(row) = rows.next()? { + let id_val: String = row.get(0)?; + let run_val: String = row.get(1)?; + let session_val: String = row.get(2)?; + let capability: String = row.get(3)?; + let intent: String = row.get(4)?; + let params_json: String = row.get(5)?; + let status_str: String = row.get(6)?; + let receipt_json: Option = row.get(7)?; + let created_at: i64 = row.get(8)?; + let completed_at: Option = row.get(9)?; + + let params: serde_json::Value = serde_json::from_str(¶ms_json)?; + let status = ActionStatus::from_str(&status_str) + .ok_or_else(|| PersistenceError::Serialization(format!("Invalid status: {status_str}")))?; + let receipt: Option = receipt_json + .map(|s| serde_json::from_str(&s)) + .transpose()?; + + Ok(Some(Action { + id: ActionId::from_string(id_val), + run_id: RunId::from_string(run_val), + session_id: SessionId::from_string(session_val), + capability, + intent, + params, + status, + receipt, + created_at, + completed_at, + })) + } else { + Ok(None) + } + }) + .await + } + + async fn update(&self, action: &Action) -> Result<(), PersistenceError> { + let action = action.clone(); + self.db + .interact(move |conn| { + let receipt_str = action + .receipt + .as_ref() + .map(|r| serde_json::to_string(r)) + .transpose()?; + + let rows = conn.execute( + "UPDATE actions SET status = ?1, receipt_json = ?2, completed_at = ?3 WHERE id = ?4", + params![ + action.status.as_str(), + receipt_str, + action.completed_at, + action.id.as_str(), + ], + )?; + if rows == 0 { + return Err(PersistenceError::NotFound(action.id.to_string())); + } + Ok(()) + }) + .await + } + + async fn list_by_run(&self, run_id: &RunId) -> Result, PersistenceError> { + let run_id = run_id.clone(); + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT id, run_id, session_id, capability, intent, params_json, status, receipt_json, created_at, completed_at + FROM actions WHERE run_id = ?1 ORDER BY created_at ASC", + )?; + let rows = stmt.query_map(params![run_id.as_str()], |row| { + let id_val: String = row.get(0)?; + let run_val: String = row.get(1)?; + let session_val: String = row.get(2)?; + let capability: String = row.get(3)?; + let intent: String = row.get(4)?; + let params_json: String = row.get(5)?; + let status_str: String = row.get(6)?; + let receipt_json: Option = row.get(7)?; + let created_at: i64 = row.get(8)?; + let completed_at: Option = row.get(9)?; + Ok((id_val, run_val, session_val, capability, intent, params_json, status_str, receipt_json, created_at, completed_at)) + })?; + + let mut actions = Vec::new(); + for r in rows { + let (id_val, run_val, session_val, capability, intent, params_json, status_str, receipt_json, created_at, completed_at) = r?; + let params: serde_json::Value = serde_json::from_str(¶ms_json)?; + let status = ActionStatus::from_str(&status_str) + .ok_or_else(|| PersistenceError::Serialization(format!("Invalid status: {status_str}")))?; + let receipt: Option = receipt_json + .map(|s| serde_json::from_str(&s)) + .transpose()?; + + actions.push(Action { + id: ActionId::from_string(id_val), + run_id: RunId::from_string(run_val), + session_id: SessionId::from_string(session_val), + capability, + intent, + params, + status, + receipt, + created_at, + completed_at, + }); + } + Ok(actions) + }) + .await + } +} diff --git a/src/persistence/sqlite/approvals.rs b/src/persistence/sqlite/approvals.rs new file mode 100644 index 0000000..ecce6b3 --- /dev/null +++ b/src/persistence/sqlite/approvals.rs @@ -0,0 +1,149 @@ +use crate::defense::approval::{Approval, ApprovalStatus}; +use crate::persistence::async_db::AsyncDatabase; +use crate::persistence::error::PersistenceError; +use crate::sessions::id::{ActionId, ApprovalId, RunId, SessionId}; +use crate::sessions::store::ApprovalStore; +use async_trait::async_trait; +use rusqlite::params; + +#[derive(Clone)] +pub struct SqliteApprovalStore { + db: AsyncDatabase, +} + +impl SqliteApprovalStore { + pub fn new(db: AsyncDatabase) -> Self { + Self { db } + } +} + +#[async_trait] +impl ApprovalStore for SqliteApprovalStore { + async fn create(&self, approval: &Approval) -> Result<(), PersistenceError> { + let approval = approval.clone(); + self.db + .interact(move |conn| { + conn.execute( + "INSERT INTO approvals (id, action_id, run_id, session_id, prompt, status, requested_at, decided_at, decided_by) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + params![ + approval.id.as_str(), + approval.action_id.as_str(), + approval.run_id.as_str(), + approval.session_id.as_str(), + approval.prompt, + approval.status.as_str(), + approval.requested_at, + approval.decided_at, + approval.decided_by, + ], + )?; + Ok(()) + }) + .await + } + + async fn get(&self, id: &ApprovalId) -> Result, PersistenceError> { + let id_str = id.to_string(); + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT id, action_id, run_id, session_id, prompt, status, requested_at, decided_at, decided_by + FROM approvals WHERE id = ?1", + )?; + let mut rows = stmt.query(params![id_str])?; + if let Some(row) = rows.next()? { + let id_val: String = row.get(0)?; + let action_val: String = row.get(1)?; + let run_val: String = row.get(2)?; + let session_val: String = row.get(3)?; + let prompt: String = row.get(4)?; + let status_str: String = row.get(5)?; + let requested_at: i64 = row.get(6)?; + let decided_at: Option = row.get(7)?; + let decided_by: Option = row.get(8)?; + + let status = ApprovalStatus::from_str(&status_str) + .ok_or_else(|| PersistenceError::Serialization(format!("Invalid status: {status_str}")))?; + + Ok(Some(Approval { + id: ApprovalId::from_string(id_val), + action_id: ActionId::from_string(action_val), + run_id: RunId::from_string(run_val), + session_id: SessionId::from_string(session_val), + prompt, + status, + requested_at, + decided_at, + decided_by, + })) + } else { + Ok(None) + } + }) + .await + } + + async fn update(&self, approval: &Approval) -> Result<(), PersistenceError> { + let approval = approval.clone(); + self.db + .interact(move |conn| { + let rows = conn.execute( + "UPDATE approvals SET status = ?1, decided_at = ?2, decided_by = ?3 WHERE id = ?4", + params![ + approval.status.as_str(), + approval.decided_at, + approval.decided_by, + approval.id.as_str(), + ], + )?; + if rows == 0 { + return Err(PersistenceError::NotFound(approval.id.to_string())); + } + Ok(()) + }) + .await + } + + async fn list_pending(&self) -> Result, PersistenceError> { + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT id, action_id, run_id, session_id, prompt, status, requested_at, decided_at, decided_by + FROM approvals WHERE status = 'pending' ORDER BY requested_at ASC", + )?; + let rows = stmt.query_map([], |row| { + let id_val: String = row.get(0)?; + let action_val: String = row.get(1)?; + let run_val: String = row.get(2)?; + let session_val: String = row.get(3)?; + let prompt: String = row.get(4)?; + let status_str: String = row.get(5)?; + let requested_at: i64 = row.get(6)?; + let decided_at: Option = row.get(7)?; + let decided_by: Option = row.get(8)?; + Ok((id_val, action_val, run_val, session_val, prompt, status_str, requested_at, decided_at, decided_by)) + })?; + + let mut approvals = Vec::new(); + for r in rows { + let (id_val, action_val, run_val, session_val, prompt, status_str, requested_at, decided_at, decided_by) = r?; + let status = ApprovalStatus::from_str(&status_str) + .ok_or_else(|| PersistenceError::Serialization(format!("Invalid status: {status_str}")))?; + approvals.push(Approval { + id: ApprovalId::from_string(id_val), + action_id: ActionId::from_string(action_val), + run_id: RunId::from_string(run_val), + session_id: SessionId::from_string(session_val), + prompt, + status, + requested_at, + decided_at, + decided_by, + }); + } + Ok(approvals) + }) + .await + } +} diff --git a/src/persistence/sqlite/messages.rs b/src/persistence/sqlite/messages.rs new file mode 100644 index 0000000..5b613e9 --- /dev/null +++ b/src/persistence/sqlite/messages.rs @@ -0,0 +1,98 @@ +use crate::persistence::async_db::AsyncDatabase; +use crate::persistence::error::PersistenceError; +use crate::sessions::id::{MessageId, SessionId}; +use crate::sessions::message::Message; +use crate::sessions::store::MessageStore; +use async_trait::async_trait; +use rusqlite::params; + +#[derive(Clone)] +pub struct SqliteMessageStore { + db: AsyncDatabase, +} + +impl SqliteMessageStore { + pub fn new(db: AsyncDatabase) -> Self { + Self { db } + } +} + +#[async_trait] +impl MessageStore for SqliteMessageStore { + async fn append( + &self, + session_id: &SessionId, + message: &Message, + ) -> Result<(), PersistenceError> { + let session_id = session_id.clone(); + let message = message.clone(); + self.db + .interact(move |conn| { + let role_str = match message.role() { + crate::sessions::message::Role::System => "system", + crate::sessions::message::Role::User => "user", + crate::sessions::message::Role::Assistant => "assistant", + crate::sessions::message::Role::Tool => "tool", + }; + let data_json = serde_json::to_string(&message)?; + let created_at = match &message { + Message::System(m) => m.created_at, + Message::User(m) => m.created_at, + Message::Assistant(m) => m.created_at, + Message::Tool(m) => m.created_at, + }; + conn.execute( + "INSERT INTO messages (id, session_id, role, data_json, created_at) + VALUES (?1, ?2, ?3, ?4, ?5)", + params![ + message.id().as_str(), + session_id.as_str(), + role_str, + data_json, + created_at, + ], + )?; + Ok(()) + }) + .await + } + + async fn list(&self, session_id: &SessionId) -> Result, PersistenceError> { + let session_id = session_id.clone(); + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT data_json FROM messages WHERE session_id = ?1 ORDER BY created_at ASC, rowid ASC", + )?; + let rows = stmt.query_map(params![session_id.as_str()], |row| { + let data: String = row.get(0)?; + Ok(data) + })?; + let mut messages = Vec::new(); + for r in rows { + let data = r?; + let msg: Message = serde_json::from_str(&data)?; + messages.push(msg); + } + Ok(messages) + }) + .await + } + + async fn get(&self, message_id: &MessageId) -> Result, PersistenceError> { + let id_str = message_id.to_string(); + self.db + .interact(move |conn| { + let mut stmt = conn.prepare("SELECT data_json FROM messages WHERE id = ?1")?; + let mut rows = stmt.query(params![id_str])?; + if let Some(row) = rows.next()? { + let data: String = row.get(0)?; + let msg: Message = serde_json::from_str(&data)?; + Ok(Some(msg)) + } else { + Ok(None) + } + }) + .await + } +} diff --git a/src/persistence/sqlite/mod.rs b/src/persistence/sqlite/mod.rs new file mode 100644 index 0000000..8708b28 --- /dev/null +++ b/src/persistence/sqlite/mod.rs @@ -0,0 +1,13 @@ +pub mod actions; +pub mod approvals; +pub mod messages; +pub mod runs; +pub mod schema; +pub mod sessions; + +pub use actions::SqliteActionStore; +pub use approvals::SqliteApprovalStore; +pub use messages::SqliteMessageStore; +pub use runs::SqliteRunStore; +pub use schema::initialize_schema; +pub use sessions::SqliteSessionStore; diff --git a/src/persistence/sqlite/runs.rs b/src/persistence/sqlite/runs.rs new file mode 100644 index 0000000..f18afbc --- /dev/null +++ b/src/persistence/sqlite/runs.rs @@ -0,0 +1,261 @@ +use crate::orchestration::budget::RunBudget; +use crate::orchestration::run::{Run, RunState}; +use crate::orchestration::termination::TerminationReason; +use crate::orchestration::trigger::Trigger; +use crate::persistence::async_db::AsyncDatabase; +use crate::persistence::error::PersistenceError; +use crate::sessions::id::{RunId, SessionId}; +use crate::sessions::store::RunStore; +use async_trait::async_trait; +use rusqlite::params; + +#[derive(Clone)] +pub struct SqliteRunStore { + db: AsyncDatabase, +} + +impl SqliteRunStore { + pub fn new(db: AsyncDatabase) -> Self { + Self { db } + } +} + +#[async_trait] +impl RunStore for SqliteRunStore { + async fn create(&self, run: &Run) -> Result<(), PersistenceError> { + let run = run.clone(); + self.db + .interact(move |conn| { + let active_count: i64 = conn.query_row( + "SELECT COUNT(*) FROM runs WHERE session_id = ?1 AND state IN ('running', 'waiting_for_approval', 'waiting_for_tool')", + params![run.session_id.as_str()], + |r| r.get(0), + )?; + if active_count > 0 { + let active_id: String = conn.query_row( + "SELECT id FROM runs WHERE session_id = ?1 AND state IN ('running', 'waiting_for_approval', 'waiting_for_tool') LIMIT 1", + params![run.session_id.as_str()], + |r| r.get(0), + )?; + return Err(PersistenceError::ActiveRunConflict { + session_id: run.session_id.to_string(), + active_run_id: active_id, + }); + } + + let trigger_str = serde_json::to_string(&run.trigger)?; + let budget_str = serde_json::to_string(&run.budget)?; + let term_str = run.termination.as_ref().map(|t| serde_json::to_string(t)).transpose()?; + + conn.execute( + "INSERT INTO runs (id, session_id, state, trigger_json, steps_used, inference_calls_used, actions_used, budget_json, started_at, completed_at, termination_json) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", + params![ + run.id.as_str(), + run.session_id.as_str(), + run.state.as_str(), + trigger_str, + run.steps_used as i64, + run.inference_calls_used as i64, + run.actions_used as i64, + budget_str, + run.started_at, + run.completed_at, + term_str, + ], + )?; + Ok(()) + }) + .await + } + + async fn get(&self, id: &RunId) -> Result, PersistenceError> { + let id_str = id.to_string(); + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT id, session_id, state, trigger_json, steps_used, inference_calls_used, actions_used, budget_json, started_at, completed_at, termination_json + FROM runs WHERE id = ?1", + )?; + let mut rows = stmt.query(params![id_str])?; + if let Some(row) = rows.next()? { + let id_val: String = row.get(0)?; + let session_val: String = row.get(1)?; + let state_str: String = row.get(2)?; + let trigger_json: String = row.get(3)?; + let steps_used: i64 = row.get(4)?; + let inference_calls_used: i64 = row.get(5)?; + let actions_used: i64 = row.get(6)?; + let budget_json: String = row.get(7)?; + let started_at: i64 = row.get(8)?; + let completed_at: Option = row.get(9)?; + let term_json: Option = row.get(10)?; + + let state = RunState::from_str(&state_str) + .ok_or_else(|| PersistenceError::Serialization(format!("Invalid state: {state_str}")))?; + let trigger: Trigger = serde_json::from_str(&trigger_json)?; + let budget: RunBudget = serde_json::from_str(&budget_json)?; + let termination: Option = term_json + .map(|s| serde_json::from_str(&s)) + .transpose()?; + + Ok(Some(Run { + id: RunId::from_string(id_val), + session_id: SessionId::from_string(session_val), + state, + trigger, + steps_used: steps_used as u32, + inference_calls_used: inference_calls_used as u32, + actions_used: actions_used as u32, + budget, + started_at, + completed_at, + termination, + })) + } else { + Ok(None) + } + }) + .await + } + + async fn update(&self, run: &Run) -> Result<(), PersistenceError> { + let run = run.clone(); + self.db + .interact(move |conn| { + let budget_str = serde_json::to_string(&run.budget)?; + let term_str = run + .termination + .as_ref() + .map(|t| serde_json::to_string(t)) + .transpose()?; + + let rows = conn.execute( + "UPDATE runs SET state = ?1, steps_used = ?2, inference_calls_used = ?3, + actions_used = ?4, budget_json = ?5, completed_at = ?6, termination_json = ?7 + WHERE id = ?8", + params![ + run.state.as_str(), + run.steps_used as i64, + run.inference_calls_used as i64, + run.actions_used as i64, + budget_str, + run.completed_at, + term_str, + run.id.as_str(), + ], + )?; + if rows == 0 { + return Err(PersistenceError::NotFound(run.id.to_string())); + } + Ok(()) + }) + .await + } + + async fn list_by_session(&self, session_id: &SessionId) -> Result, PersistenceError> { + let session_id = session_id.clone(); + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT id, session_id, state, trigger_json, steps_used, inference_calls_used, actions_used, budget_json, started_at, completed_at, termination_json + FROM runs WHERE session_id = ?1 ORDER BY started_at DESC", + )?; + let rows = stmt.query_map(params![session_id.as_str()], |row| { + let id_val: String = row.get(0)?; + let session_val: String = row.get(1)?; + let state_str: String = row.get(2)?; + let trigger_json: String = row.get(3)?; + let steps_used: i64 = row.get(4)?; + let inference_calls_used: i64 = row.get(5)?; + let actions_used: i64 = row.get(6)?; + let budget_json: String = row.get(7)?; + let started_at: i64 = row.get(8)?; + let completed_at: Option = row.get(9)?; + let term_json: Option = row.get(10)?; + Ok((id_val, session_val, state_str, trigger_json, steps_used, inference_calls_used, actions_used, budget_json, started_at, completed_at, term_json)) + })?; + + let mut runs = Vec::new(); + for r in rows { + let (id_val, session_val, state_str, trigger_json, steps_used, inference_calls_used, actions_used, budget_json, started_at, completed_at, term_json) = r?; + let state = RunState::from_str(&state_str) + .ok_or_else(|| PersistenceError::Serialization(format!("Invalid state: {state_str}")))?; + let trigger: Trigger = serde_json::from_str(&trigger_json)?; + let budget: RunBudget = serde_json::from_str(&budget_json)?; + let termination: Option = term_json + .map(|s| serde_json::from_str(&s)) + .transpose()?; + + runs.push(Run { + id: RunId::from_string(id_val), + session_id: SessionId::from_string(session_val), + state, + trigger, + steps_used: steps_used as u32, + inference_calls_used: inference_calls_used as u32, + actions_used: actions_used as u32, + budget, + started_at, + completed_at, + termination, + }); + } + Ok(runs) + }) + .await + } + + async fn get_active_run( + &self, + session_id: &SessionId, + ) -> Result, PersistenceError> { + let session_id = session_id.clone(); + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT id, session_id, state, trigger_json, steps_used, inference_calls_used, actions_used, budget_json, started_at, completed_at, termination_json + FROM runs WHERE session_id = ?1 AND state IN ('running', 'waiting_for_approval', 'waiting_for_tool') LIMIT 1", + )?; + let mut rows = stmt.query(params![session_id.as_str()])?; + if let Some(row) = rows.next()? { + let id_val: String = row.get(0)?; + let session_val: String = row.get(1)?; + let state_str: String = row.get(2)?; + let trigger_json: String = row.get(3)?; + let steps_used: i64 = row.get(4)?; + let inference_calls_used: i64 = row.get(5)?; + let actions_used: i64 = row.get(6)?; + let budget_json: String = row.get(7)?; + let started_at: i64 = row.get(8)?; + let completed_at: Option = row.get(9)?; + let term_json: Option = row.get(10)?; + + let state = RunState::from_str(&state_str) + .ok_or_else(|| PersistenceError::Serialization(format!("Invalid state: {state_str}")))?; + let trigger: Trigger = serde_json::from_str(&trigger_json)?; + let budget: RunBudget = serde_json::from_str(&budget_json)?; + let termination: Option = term_json + .map(|s| serde_json::from_str(&s)) + .transpose()?; + + Ok(Some(Run { + id: RunId::from_string(id_val), + session_id: SessionId::from_string(session_val), + state, + trigger, + steps_used: steps_used as u32, + inference_calls_used: inference_calls_used as u32, + actions_used: actions_used as u32, + budget, + started_at, + completed_at, + termination, + })) + } else { + Ok(None) + } + }) + .await + } +} diff --git a/src/persistence/sqlite/schema.rs b/src/persistence/sqlite/schema.rs new file mode 100644 index 0000000..e088d20 --- /dev/null +++ b/src/persistence/sqlite/schema.rs @@ -0,0 +1,142 @@ +use rusqlite::Connection; + +pub fn initialize_schema(conn: &Connection) -> Result<(), rusqlite::Error> { + let _ = conn.pragma_update(None, "journal_mode", "WAL"); + let _ = conn.pragma_update(None, "busy_timeout", 5000); + let _ = conn.pragma_update(None, "foreign_keys", "ON"); + + conn.execute_batch( + " + CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + parent_session_id TEXT, + status TEXT NOT NULL, + objective TEXT, + agent_profile TEXT NOT NULL, + model_profile TEXT NOT NULL, + policy_profile TEXT NOT NULL, + budget_json TEXT NOT NULL, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + version INTEGER NOT NULL DEFAULT 1 + ); + CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions (updated_at DESC); + + CREATE TABLE IF NOT EXISTS messages ( + id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + role TEXT NOT NULL, + data_json TEXT NOT NULL, + created_at INTEGER NOT NULL, + FOREIGN KEY(session_id) REFERENCES sessions(id) ON DELETE CASCADE + ); + CREATE INDEX IF NOT EXISTS idx_messages_session ON messages (session_id, created_at ASC); + + CREATE TABLE IF NOT EXISTS runs ( + id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + state TEXT NOT NULL, + trigger_json TEXT NOT NULL, + steps_used INTEGER NOT NULL DEFAULT 0, + inference_calls_used INTEGER NOT NULL DEFAULT 0, + actions_used INTEGER NOT NULL DEFAULT 0, + budget_json TEXT NOT NULL, + started_at INTEGER NOT NULL, + completed_at INTEGER, + termination_json TEXT, + FOREIGN KEY(session_id) REFERENCES sessions(id) ON DELETE CASCADE + ); + CREATE INDEX IF NOT EXISTS idx_runs_session ON runs (session_id, started_at DESC); + CREATE INDEX IF NOT EXISTS idx_runs_active ON runs (session_id, state); + + CREATE TABLE IF NOT EXISTS actions ( + id TEXT PRIMARY KEY, + run_id TEXT NOT NULL, + session_id TEXT NOT NULL, + capability TEXT NOT NULL, + intent TEXT NOT NULL, + params_json TEXT NOT NULL, + status TEXT NOT NULL, + receipt_json TEXT, + created_at INTEGER NOT NULL, + completed_at INTEGER, + FOREIGN KEY(session_id) REFERENCES sessions(id) ON DELETE CASCADE, + FOREIGN KEY(run_id) REFERENCES runs(id) ON DELETE CASCADE + ); + CREATE INDEX IF NOT EXISTS idx_actions_run ON actions (run_id, created_at ASC); + + CREATE TABLE IF NOT EXISTS approvals ( + id TEXT PRIMARY KEY, + action_id TEXT NOT NULL, + run_id TEXT NOT NULL, + session_id TEXT NOT NULL, + prompt TEXT NOT NULL, + status TEXT NOT NULL, + requested_at INTEGER NOT NULL, + decided_at INTEGER, + decided_by TEXT, + FOREIGN KEY(session_id) REFERENCES sessions(id) ON DELETE CASCADE, + FOREIGN KEY(run_id) REFERENCES runs(id) ON DELETE CASCADE, + FOREIGN KEY(action_id) REFERENCES actions(id) ON DELETE CASCADE + ); + CREATE INDEX IF NOT EXISTS idx_approvals_pending ON approvals (status, requested_at ASC); + + CREATE TABLE IF NOT EXISTS audit_events ( + id TEXT PRIMARY KEY, + sequence INTEGER NOT NULL, + session_id TEXT, + run_id TEXT, + event_type TEXT NOT NULL, + payload_json TEXT NOT NULL, + prev_hash TEXT NOT NULL, + hash TEXT NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_audit_sequence ON audit_events (sequence ASC); + + CREATE TABLE IF NOT EXISTS turns ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL, + role TEXT NOT NULL, + prompt TEXT NOT NULL, + response TEXT NOT NULL, + duration_ms INTEGER NOT NULL, + created_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS heartbeats ( + tick_id INTEGER PRIMARY KEY, + timestamp TEXT NOT NULL, + status TEXT NOT NULL, + tasks_scanned INTEGER NOT NULL, + actions_dispatched INTEGER NOT NULL, + notes TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS tasks ( + id TEXT PRIMARY KEY, + task_type TEXT NOT NULL, + payload TEXT NOT NULL, + status TEXT NOT NULL, + result TEXT, + created_at TEXT NOT NULL, + completed_at TEXT + ); + + CREATE TABLE IF NOT EXISTS memory_crumbs ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + namespace TEXT NOT NULL, + created_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS skills ( + name TEXT PRIMARY KEY, + description TEXT NOT NULL, + command TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + ", + )?; + Ok(()) +} diff --git a/src/persistence/sqlite/sessions.rs b/src/persistence/sqlite/sessions.rs new file mode 100644 index 0000000..d431d6b --- /dev/null +++ b/src/persistence/sqlite/sessions.rs @@ -0,0 +1,196 @@ +use crate::persistence::async_db::AsyncDatabase; +use crate::persistence::error::PersistenceError; +use crate::sessions::id::SessionId; +use crate::sessions::session::{Session, SessionBudget, SessionStatus}; +use crate::sessions::store::SessionStore; +use async_trait::async_trait; +use chrono::Utc; +use rusqlite::params; + +#[derive(Clone)] +pub struct SqliteSessionStore { + db: AsyncDatabase, +} + +impl SqliteSessionStore { + pub fn new(db: AsyncDatabase) -> Self { + Self { db } + } +} + +#[async_trait] +impl SessionStore for SqliteSessionStore { + async fn create(&self, session: &Session) -> Result<(), PersistenceError> { + let session = session.clone(); + self.db + .interact(move |conn| { + let budget_str = serde_json::to_string(&session.budget)?; + conn.execute( + "INSERT INTO sessions (id, parent_session_id, status, objective, agent_profile, model_profile, policy_profile, budget_json, created_at, updated_at, version) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", + params![ + session.id.as_str(), + session.parent_session_id.as_ref().map(|p| p.as_str()), + session.status.as_str(), + session.objective, + session.agent_profile, + session.model_profile, + session.policy_profile, + budget_str, + session.created_at, + session.updated_at, + session.version as i64, + ], + )?; + Ok(()) + }) + .await + } + + async fn get(&self, id: &SessionId) -> Result, PersistenceError> { + let id_str = id.to_string(); + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT id, parent_session_id, status, objective, agent_profile, model_profile, policy_profile, budget_json, created_at, updated_at, version + FROM sessions WHERE id = ?1", + )?; + let mut rows = stmt.query(params![id_str])?; + if let Some(row) = rows.next()? { + let id_val: String = row.get(0)?; + let parent_val: Option = row.get(1)?; + let status_str: String = row.get(2)?; + let objective: Option = row.get(3)?; + let agent_profile: String = row.get(4)?; + let model_profile: String = row.get(5)?; + let policy_profile: String = row.get(6)?; + let budget_json: String = row.get(7)?; + let created_at: i64 = row.get(8)?; + let updated_at: i64 = row.get(9)?; + let version: i64 = row.get(10)?; + + let status = SessionStatus::from_str(&status_str) + .ok_or_else(|| PersistenceError::Serialization(format!("Invalid status: {status_str}")))?; + let budget: SessionBudget = serde_json::from_str(&budget_json)?; + + let mut msg_stmt = conn.prepare( + "SELECT data_json FROM messages WHERE session_id = ?1 ORDER BY created_at ASC, rowid ASC", + )?; + let msg_rows = msg_stmt.query_map(params![id_val], |r| { + let data: String = r.get(0)?; + Ok(data) + })?; + let mut messages = Vec::new(); + for m in msg_rows { + let data = m?; + let msg: crate::sessions::message::Message = serde_json::from_str(&data)?; + messages.push(msg); + } + + Ok(Some(Session { + id: SessionId::from_string(id_val), + parent_session_id: parent_val.map(SessionId::from_string), + status, + objective, + agent_profile, + model_profile, + policy_profile, + messages, + budget, + created_at, + updated_at, + version: version as u64, + })) + } else { + Ok(None) + } + }) + .await + } + + async fn update(&self, session: &Session) -> Result<(), PersistenceError> { + let session = session.clone(); + self.db + .interact(move |conn| { + let budget_str = serde_json::to_string(&session.budget)?; + let now = Utc::now().timestamp(); + + let updated_rows = conn.execute( + "UPDATE sessions SET parent_session_id = ?1, status = ?2, objective = ?3, + agent_profile = ?4, model_profile = ?5, policy_profile = ?6, + budget_json = ?7, updated_at = ?8, version = version + 1 + WHERE id = ?9 AND version = ?10", + params![ + session.parent_session_id.as_ref().map(|p| p.as_str()), + session.status.as_str(), + session.objective, + session.agent_profile, + session.model_profile, + session.policy_profile, + budget_str, + now, + session.id.as_str(), + session.version as i64, + ], + )?; + + if updated_rows == 0 { + return Err(PersistenceError::ConcurrencyConflict { + id: session.id.to_string(), + expected_version: session.version, + }); + } + Ok(()) + }) + .await + } + + async fn list(&self, limit: usize, offset: usize) -> Result, PersistenceError> { + self.db + .interact(move |conn| { + let mut stmt = conn.prepare( + "SELECT id, parent_session_id, status, objective, agent_profile, model_profile, policy_profile, budget_json, created_at, updated_at, version + FROM sessions ORDER BY updated_at DESC LIMIT ?1 OFFSET ?2", + )?; + let rows = stmt.query_map(params![limit as i64, offset as i64], |row| { + let id_val: String = row.get(0)?; + let parent_val: Option = row.get(1)?; + let status_str: String = row.get(2)?; + let objective: Option = row.get(3)?; + let agent_profile: String = row.get(4)?; + let model_profile: String = row.get(5)?; + let policy_profile: String = row.get(6)?; + let budget_json: String = row.get(7)?; + let created_at: i64 = row.get(8)?; + let updated_at: i64 = row.get(9)?; + let version: i64 = row.get(10)?; + Ok((id_val, parent_val, status_str, objective, agent_profile, model_profile, policy_profile, budget_json, created_at, updated_at, version)) + })?; + + let mut sessions = Vec::new(); + for r in rows { + let (id_val, parent_val, status_str, objective, agent_profile, model_profile, policy_profile, budget_json, created_at, updated_at, version) = r?; + let status = SessionStatus::from_str(&status_str) + .ok_or_else(|| PersistenceError::Serialization(format!("Invalid status: {status_str}")))?; + let budget: SessionBudget = serde_json::from_str(&budget_json)?; + + sessions.push(Session { + id: SessionId::from_string(id_val), + parent_session_id: parent_val.map(SessionId::from_string), + status, + objective, + agent_profile, + model_profile, + policy_profile, + messages: Vec::new(), + budget, + created_at, + updated_at, + version: version as u64, + }); + } + Ok(sessions) + }) + .await + } +} diff --git a/src/sessions/mod.rs b/src/sessions/mod.rs index be5b998..56a2dd7 100644 --- a/src/sessions/mod.rs +++ b/src/sessions/mod.rs @@ -6,4 +6,4 @@ pub mod store; pub use id::{ActionId, ApprovalId, MessageId, RunId, SessionId}; pub use message::{AssistantMessage, Message, Role, SystemMessage, ToolResultMessage, UserMessage}; pub use session::{Session, SessionBudget, SessionStatus}; -pub use store::{MessageStore, SessionStore}; +pub use store::{ActionStore, ApprovalStore, MessageStore, RunStore, SessionStore}; diff --git a/src/sessions/session.rs b/src/sessions/session.rs index 4a1690f..73fc5d5 100644 --- a/src/sessions/session.rs +++ b/src/sessions/session.rs @@ -11,6 +11,25 @@ pub enum SessionStatus { Closed, } +impl SessionStatus { + pub fn as_str(&self) -> &'static str { + match self { + Self::Active => "active", + Self::Suspended => "suspended", + Self::Closed => "closed", + } + } + + pub fn from_str(s: &str) -> Option { + match s { + "active" => Some(Self::Active), + "suspended" => Some(Self::Suspended), + "closed" => Some(Self::Closed), + _ => None, + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SessionBudget { pub max_total_tokens: u64, diff --git a/src/sessions/store.rs b/src/sessions/store.rs index 47ce376..322ff5d 100644 --- a/src/sessions/store.rs +++ b/src/sessions/store.rs @@ -1,18 +1,53 @@ -use super::id::{MessageId, SessionId}; +use super::id::{ActionId, ApprovalId, MessageId, RunId, SessionId}; use super::message::Message; use super::session::Session; +use crate::defense::Approval; +use crate::execution::Action; +use crate::orchestration::Run; +use crate::persistence::PersistenceError; use async_trait::async_trait; #[async_trait] pub trait SessionStore: Send + Sync { - async fn create(&self, session: &Session) -> Result<(), String>; - async fn get(&self, id: &SessionId) -> Result, String>; - async fn update(&self, session: &Session) -> Result<(), String>; + async fn create(&self, session: &Session) -> Result<(), PersistenceError>; + async fn get(&self, id: &SessionId) -> Result, PersistenceError>; + async fn update(&self, session: &Session) -> Result<(), PersistenceError>; + async fn list(&self, limit: usize, offset: usize) -> Result, PersistenceError>; } #[async_trait] pub trait MessageStore: Send + Sync { - async fn append(&self, session_id: &SessionId, message: &Message) -> Result<(), String>; - async fn list(&self, session_id: &SessionId) -> Result, String>; - async fn get(&self, message_id: &MessageId) -> Result, String>; + async fn append( + &self, + session_id: &SessionId, + message: &Message, + ) -> Result<(), PersistenceError>; + async fn list(&self, session_id: &SessionId) -> Result, PersistenceError>; + async fn get(&self, message_id: &MessageId) -> Result, PersistenceError>; +} + +#[async_trait] +pub trait RunStore: Send + Sync { + async fn create(&self, run: &Run) -> Result<(), PersistenceError>; + async fn get(&self, id: &RunId) -> Result, PersistenceError>; + async fn update(&self, run: &Run) -> Result<(), PersistenceError>; + async fn list_by_session(&self, session_id: &SessionId) -> Result, PersistenceError>; + async fn get_active_run(&self, session_id: &SessionId) + -> Result, PersistenceError>; +} + +#[async_trait] +pub trait ActionStore: Send + Sync { + async fn create(&self, action: &Action) -> Result<(), PersistenceError>; + async fn get(&self, id: &ActionId) -> Result, PersistenceError>; + async fn update(&self, action: &Action) -> Result<(), PersistenceError>; + async fn list_by_run(&self, run_id: &RunId) -> Result, PersistenceError>; +} + +#[async_trait] +pub trait ApprovalStore: Send + Sync { + async fn create(&self, approval: &Approval) -> Result<(), PersistenceError>; + async fn get(&self, id: &ApprovalId) -> Result, PersistenceError>; + async fn update(&self, approval: &Approval) -> Result<(), PersistenceError>; + async fn list_pending(&self) -> Result, PersistenceError>; } diff --git a/tests/stage2_primitives_tests.rs b/tests/stage2_primitives_tests.rs index 32a2e87..7aa9805 100644 --- a/tests/stage2_primitives_tests.rs +++ b/tests/stage2_primitives_tests.rs @@ -1,7 +1,7 @@ use aegis::{ - ActionId, ActionReceipt, AegisEvent, ApprovalId, ContainmentLevel, DoctrineDecision, EventBus, - EventEnvelope, EventId, Message, MessageId, Role, Run, RunBudget, RunId, RunState, Session, - SessionId, SessionStatus, SystemMessage, TerminationReason, Trigger, UserMessage, + ActionId, ActionReceipt, AegisEvent, ApprovalId, DoctrineDecision, EventBus, EventEnvelope, + EventId, Message, MessageId, Role, Run, RunBudget, RunId, RunState, Session, SessionId, + SessionStatus, SystemMessage, TerminationReason, Trigger, UserMessage, }; #[test] diff --git a/tests/stage3_4_persistence_tests.rs b/tests/stage3_4_persistence_tests.rs new file mode 100644 index 0000000..a77e2bc --- /dev/null +++ b/tests/stage3_4_persistence_tests.rs @@ -0,0 +1,263 @@ +use aegis::{ + Action, ActionReceipt, ActionStatus, ActionStore, Approval, ApprovalStatus, ApprovalStore, + AsyncDatabase, Database, DoctrineDecision, Message, MessageId, MessageStore, PersistenceError, + Role, Run, RunBudget, RunState, RunStore, Session, SessionStatus, SessionStore, + SqliteActionStore, SqliteApprovalStore, SqliteMessageStore, SqliteRunStore, SqliteSessionStore, + SystemMessage, Trigger, UserMessage, +}; + +#[tokio::test] +async fn test_sqlite_session_crud_and_optimistic_concurrency() { + let db = AsyncDatabase::open_in_memory().unwrap(); + let store = SqliteSessionStore::new(db); + + let mut session = Session::new(Some("Optimistic test".to_string())); + assert_eq!(session.version, 1); + store.create(&session).await.unwrap(); + + let fetched = store + .get(&session.id) + .await + .unwrap() + .expect("session must exist"); + assert_eq!(fetched.id, session.id); + assert_eq!(fetched.version, 1); + assert_eq!(fetched.objective.as_deref(), Some("Optimistic test")); + + // First update succeeds and increments version to 2 + session.status = SessionStatus::Suspended; + store.update(&session).await.unwrap(); + + let updated = store + .get(&session.id) + .await + .unwrap() + .expect("session must exist"); + assert_eq!(updated.version, 2); + assert_eq!(updated.status, SessionStatus::Suspended); + + // Stale update with version 1 must return ConcurrencyConflict + let err = store.update(&session).await.unwrap_err(); + match err { + PersistenceError::ConcurrencyConflict { + id, + expected_version, + } => { + assert_eq!(id, session.id.to_string()); + assert_eq!(expected_version, 1); + } + other => panic!("Expected ConcurrencyConflict, got: {:?}", other), + } + + // Update with fresh version 2 succeeds and increments to 3 + let mut fresh_session = updated; + fresh_session.objective = Some("Updated objective".to_string()); + store.update(&fresh_session).await.unwrap(); + + let final_session = store + .get(&session.id) + .await + .unwrap() + .expect("session must exist"); + assert_eq!(final_session.version, 3); + assert_eq!( + final_session.objective.as_deref(), + Some("Updated objective") + ); + + // List sessions + let list = store.list(10, 0).await.unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].id, session.id); +} + +#[tokio::test] +async fn test_sqlite_message_store_lifecycle() { + let db = AsyncDatabase::open_in_memory().unwrap(); + let session_store = SqliteSessionStore::new(db.clone()); + let msg_store = SqliteMessageStore::new(db); + + let session = Session::new(Some("Message lifecycle test".to_string())); + session_store.create(&session).await.unwrap(); + + let msg1 = Message::System(SystemMessage { + id: MessageId::new(), + content: "You are Aegis.".to_string(), + created_at: 100, + }); + let msg2 = Message::User(UserMessage { + id: MessageId::new(), + content: "Run test scan.".to_string(), + created_at: 101, + }); + + msg_store.append(&session.id, &msg1).await.unwrap(); + msg_store.append(&session.id, &msg2).await.unwrap(); + + let messages = msg_store.list(&session.id).await.unwrap(); + assert_eq!(messages.len(), 2); + assert_eq!(messages[0].role(), Role::System); + assert_eq!(messages[1].role(), Role::User); + + let retrieved = msg_store + .get(msg1.id()) + .await + .unwrap() + .expect("msg1 exists"); + assert_eq!(retrieved.id(), msg1.id()); + + // Messages also load with session.get() + let loaded_session = session_store.get(&session.id).await.unwrap().unwrap(); + assert_eq!(loaded_session.messages.len(), 2); +} + +#[tokio::test] +async fn test_sqlite_run_store_single_active_run_constraint() { + let db = AsyncDatabase::open_in_memory().unwrap(); + let session_store = SqliteSessionStore::new(db.clone()); + let run_store = SqliteRunStore::new(db); + + let session = Session::new(Some("Run constraint test".to_string())); + session_store.create(&session).await.unwrap(); + + let run1 = Run::new(session.id.clone(), Trigger::Heartbeat, RunBudget::default()); + run_store.create(&run1).await.unwrap(); + + // Attempting to create another active run on the same session must fail with ActiveRunConflict + let run2 = Run::new(session.id.clone(), Trigger::Heartbeat, RunBudget::default()); + let err = run_store.create(&run2).await.unwrap_err(); + match err { + PersistenceError::ActiveRunConflict { + session_id, + active_run_id, + } => { + assert_eq!(session_id, session.id.to_string()); + assert_eq!(active_run_id, run1.id.to_string()); + } + other => panic!("Expected ActiveRunConflict, got: {:?}", other), + } + + // Active run can be retrieved + let active = run_store + .get_active_run(&session.id) + .await + .unwrap() + .expect("active run must exist"); + assert_eq!(active.id, run1.id); + + // Once run1 completes, run2 can be created + let mut finished_run1 = run1.clone(); + finished_run1.state = RunState::Completed; + finished_run1.completed_at = Some(chrono::Utc::now().timestamp()); + run_store.update(&finished_run1).await.unwrap(); + + assert!(run_store + .get_active_run(&session.id) + .await + .unwrap() + .is_none()); + + run_store.create(&run2).await.unwrap(); + let new_active = run_store + .get_active_run(&session.id) + .await + .unwrap() + .expect("run2 is now active"); + assert_eq!(new_active.id, run2.id); +} + +#[tokio::test] +async fn test_sqlite_action_and_approval_store() { + let db = AsyncDatabase::open_in_memory().unwrap(); + let session_store = SqliteSessionStore::new(db.clone()); + let run_store = SqliteRunStore::new(db.clone()); + let action_store = SqliteActionStore::new(db.clone()); + let approval_store = SqliteApprovalStore::new(db); + + let session = Session::new(Some("Action and approval test".to_string())); + session_store.create(&session).await.unwrap(); + + let run = Run::new(session.id.clone(), Trigger::Heartbeat, RunBudget::default()); + run_store.create(&run).await.unwrap(); + + let mut action = Action::new( + run.id.clone(), + session.id.clone(), + "workspace_write", + "write to file", + serde_json::json!({"path": "/tmp/test.txt"}), + ); + action_store.create(&action).await.unwrap(); + + let mut approval = Approval::new( + action.id.clone(), + run.id.clone(), + session.id.clone(), + "Approve writing /tmp/test.txt?", + ); + approval_store.create(&approval).await.unwrap(); + + let pending = approval_store.list_pending().await.unwrap(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].id, approval.id); + + // Approve + approval.status = ApprovalStatus::Approved; + approval.decided_at = Some(chrono::Utc::now().timestamp()); + approval.decided_by = Some("operator".to_string()); + approval_store.update(&approval).await.unwrap(); + + let pending_after = approval_store.list_pending().await.unwrap(); + assert_eq!(pending_after.len(), 0); + + // Update action with receipt + action.status = ActionStatus::Completed; + action.receipt = Some(ActionReceipt { + action_id: action.id.to_string(), + session_id: session.id.to_string(), + run_id: run.id.to_string(), + capability: "workspace_write".to_string(), + target: "/tmp/test.txt".to_string(), + decision: DoctrineDecision::Allow, + output: "file written successfully".to_string(), + success: true, + duration_ms: 42, + }); + action.completed_at = Some(chrono::Utc::now().timestamp()); + action_store.update(&action).await.unwrap(); + + let fetched_action = action_store + .get(&action.id) + .await + .unwrap() + .expect("action exists"); + assert_eq!(fetched_action.status, ActionStatus::Completed); + assert!(fetched_action.receipt.is_some()); + assert_eq!(fetched_action.receipt.unwrap().duration_ms, 42); +} + +#[test] +fn test_legacy_database_interop() { + let db = Database::open_in_memory().unwrap(); + db.create_task("task_001", "scan", "run full audit") + .unwrap(); + let pending = db.list_pending_tasks().unwrap(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].id, "task_001"); + + db.store_crumb("key1", "val1", "ns").unwrap(); + let crumbs = db.get_recent_crumbs("ns", 5).unwrap(); + assert_eq!(crumbs.len(), 1); + assert_eq!(crumbs[0].value, "val1"); + + // Interop with async database + let async_db = db.to_async(); + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let session_store = SqliteSessionStore::new(async_db); + let session = Session::new(Some("Interop session".to_string())); + session_store.create(&session).await.unwrap(); + let fetched = session_store.get(&session.id).await.unwrap().unwrap(); + assert_eq!(fetched.id, session.id); + }); +}