aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / cortex-rs / src / db.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | use chrono::Utc; |
| 17 | use rusqlite::{params, Connection, Result}; |
| 18 | use sha2::{Digest, Sha256}; |
| 19 | use std::path::{Path, PathBuf}; |
| 20 | use std::sync::{Arc, Mutex}; |
| 21 | use uuid::Uuid; |
| 22 | |
| 23 | use crate::embeddings::{bytes_to_embedding, cosine_similarity, embedding_to_bytes}; |
| 24 | use crate::models::*; |
| 25 | |
| 26 | pub fn compute_event_hash( |
| 27 | session_id: &str, |
| 28 | branch_id: &str, |
| 29 | sequence: i64, |
| 30 | event_type: &str, |
| 31 | role: Option<&str>, |
| 32 | content: Option<&str>, |
| 33 | payload_json: &str, |
| 34 | ) -> String { |
| 35 | let mut hasher = Sha256::new(); |
| 36 | hasher.update(session_id.as_bytes()); |
| 37 | hasher.update(b":"); |
| 38 | hasher.update(branch_id.as_bytes()); |
| 39 | hasher.update(b":"); |
| 40 | hasher.update(sequence.to_string().as_bytes()); |
| 41 | hasher.update(b":"); |
| 42 | hasher.update(event_type.as_bytes()); |
| 43 | hasher.update(b":"); |
| 44 | if let Some(r) = role { |
| 45 | hasher.update(r.as_bytes()); |
| 46 | } |
| 47 | hasher.update(b":"); |
| 48 | if let Some(c) = content { |
| 49 | hasher.update(c.as_bytes()); |
| 50 | } |
| 51 | hasher.update(b":"); |
| 52 | hasher.update(payload_json.as_bytes()); |
| 53 | format!("{:x}", hasher.finalize()) |
| 54 | } |
| 55 | |
| 56 | type WriteTask = Box<dyn FnOnce(&mut Connection) + Send>; |
| 57 | |
| 58 | pub struct StorageWriter { |
| 59 | sender: Option<std::sync::mpsc::Sender<WriteTask>>, |
| 60 | worker: Option<std::thread::JoinHandle<()>>, |
| 61 | } |
| 62 | |
| 63 | impl StorageWriter { |
| 64 | pub fn new(mut conn: Connection) -> Self { |
| 65 | let (tx, rx) = std::sync::mpsc::channel::<WriteTask>(); |
| 66 | let handle = std::thread::Builder::new() |
| 67 | .name("cortex-writer".to_string()) |
| 68 | .spawn(move || { |
| 69 | while let Ok(task) = rx.recv() { |
| 70 | task(&mut conn); |
| 71 | while let Ok(next) = rx.try_recv() { |
| 72 | next(&mut conn); |
| 73 | } |
| 74 | } |
| 75 | }) |
| 76 | .expect("spawn cortex-writer thread"); |
| 77 | |
| 78 | Self { |
| 79 | sender: Some(tx), |
| 80 | worker: Some(handle), |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | pub fn execute<T: Send + 'static, F: FnOnce(&mut Connection) -> Result<T> + Send + 'static>( |
| 85 | &self, |
| 86 | f: F, |
| 87 | ) -> Result<T> { |
| 88 | let sender = self.sender.as_ref().ok_or_else(|| { |
| 89 | rusqlite::Error::SqliteFailure( |
| 90 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_INTERNAL), |
| 91 | Some("StorageWriter sender dropped".to_string()), |
| 92 | ) |
| 93 | })?; |
| 94 | let (res_tx, res_rx) = std::sync::mpsc::channel(); |
| 95 | sender |
| 96 | .send(Box::new(move |conn| { |
| 97 | let r = f(conn); |
| 98 | let _ = res_tx.send(r); |
| 99 | })) |
| 100 | .map_err(|e| { |
| 101 | rusqlite::Error::SqliteFailure( |
| 102 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_INTERNAL), |
| 103 | Some(format!("StorageWriter send error: {}", e)), |
| 104 | ) |
| 105 | })?; |
| 106 | res_rx.recv().map_err(|e| { |
| 107 | rusqlite::Error::SqliteFailure( |
| 108 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_INTERNAL), |
| 109 | Some(format!("StorageWriter recv error: {}", e)), |
| 110 | ) |
| 111 | })? |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | impl Drop for StorageWriter { |
| 116 | fn drop(&mut self) { |
| 117 | drop(self.sender.take()); |
| 118 | if let Some(worker) = self.worker.take() { |
| 119 | let _ = worker.join(); |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | pub struct ReaderPool { |
| 125 | path: Option<PathBuf>, |
| 126 | shared_mem_uri: Option<String>, |
| 127 | pool: Mutex<Vec<Connection>>, |
| 128 | max_size: usize, |
| 129 | } |
| 130 | |
| 131 | impl ReaderPool { |
| 132 | pub fn new(path: Option<PathBuf>, shared_mem_uri: Option<String>, max_size: usize) -> Self { |
| 133 | Self { |
| 134 | path, |
| 135 | shared_mem_uri, |
| 136 | pool: Mutex::new(Vec::with_capacity(max_size)), |
| 137 | max_size, |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | pub fn acquire(self: &Arc<Self>) -> Result<PooledConnection> { |
| 142 | let mut pool = self.pool.lock().unwrap(); |
| 143 | if let Some(conn) = pool.pop() { |
| 144 | Ok(PooledConnection { |
| 145 | conn: Some(conn), |
| 146 | pool: Arc::clone(self), |
| 147 | }) |
| 148 | } else { |
| 149 | drop(pool); |
| 150 | let conn = self.open_reader()?; |
| 151 | Ok(PooledConnection { |
| 152 | conn: Some(conn), |
| 153 | pool: Arc::clone(self), |
| 154 | }) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | pub fn open_reader(&self) -> Result<Connection> { |
| 159 | let conn = if let Some(path) = &self.path { |
| 160 | let conn = Connection::open(path)?; |
| 161 | let _: Result<String, _> = |
| 162 | conn.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0)); |
| 163 | conn.execute_batch("PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;")?; |
| 164 | conn |
| 165 | } else if let Some(uri) = &self.shared_mem_uri { |
| 166 | let flags = rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE |
| 167 | | rusqlite::OpenFlags::SQLITE_OPEN_URI |
| 168 | | rusqlite::OpenFlags::SQLITE_OPEN_SHARED_CACHE; |
| 169 | let conn = Connection::open_with_flags(uri, flags)?; |
| 170 | conn.execute_batch("PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;")?; |
| 171 | conn |
| 172 | } else { |
| 173 | return Err(rusqlite::Error::InvalidPath(PathBuf::from(":invalid:"))); |
| 174 | }; |
| 175 | Ok(conn) |
| 176 | } |
| 177 | |
| 178 | fn release(&self, conn: Connection) { |
| 179 | let mut pool = self.pool.lock().unwrap(); |
| 180 | if pool.len() < self.max_size { |
| 181 | pool.push(conn); |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | pub struct PooledConnection { |
| 187 | conn: Option<Connection>, |
| 188 | pool: Arc<ReaderPool>, |
| 189 | } |
| 190 | |
| 191 | impl std::ops::Deref for PooledConnection { |
| 192 | type Target = Connection; |
| 193 | fn deref(&self) -> &Self::Target { |
| 194 | self.conn.as_ref().unwrap() |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | impl std::ops::DerefMut for PooledConnection { |
| 199 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 200 | self.conn.as_mut().unwrap() |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | impl Drop for PooledConnection { |
| 205 | fn drop(&mut self) { |
| 206 | if let Some(conn) = self.conn.take() { |
| 207 | self.pool.release(conn); |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | pub struct LegacyConnGuard { |
| 213 | conn: PooledConnection, |
| 214 | } |
| 215 | |
| 216 | impl std::ops::Deref for LegacyConnGuard { |
| 217 | type Target = Connection; |
| 218 | fn deref(&self) -> &Self::Target { |
| 219 | &self.conn |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | impl std::ops::DerefMut for LegacyConnGuard { |
| 224 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 225 | &mut self.conn |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | pub struct LegacyConnAdapter { |
| 230 | reader_pool: Arc<ReaderPool>, |
| 231 | } |
| 232 | |
| 233 | impl LegacyConnAdapter { |
| 234 | pub fn lock(&self) -> Result<LegacyConnGuard, Box<std::sync::PoisonError<LegacyConnGuard>>> { |
| 235 | let conn = self |
| 236 | .reader_pool |
| 237 | .acquire() |
| 238 | .expect("acquire connection for legacy adapter"); |
| 239 | Ok(LegacyConnGuard { conn }) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | pub struct Database { |
| 244 | writer: Arc<StorageWriter>, |
| 245 | reader_pool: Arc<ReaderPool>, |
| 246 | pub conn: LegacyConnAdapter, |
| 247 | hmac_key: Vec<u8>, |
| 248 | } |
| 249 | |
| 250 | fn load_hmac_key(conn: &Connection) -> Result<Vec<u8>> { |
| 251 | conn.query_row( |
| 252 | "SELECT hmac_key FROM security_state WHERE id = 1", |
| 253 | [], |
| 254 | |row| row.get(0), |
| 255 | ) |
| 256 | } |
| 257 | |
| 258 | fn shift_back(now: &str, days: i64) -> String { |
| 259 | chrono::DateTime::parse_from_rfc3339(now) |
| 260 | .map(|parsed| (parsed.with_timezone(&Utc) - chrono::Duration::days(days)).to_rfc3339()) |
| 261 | .unwrap_or_else(|_| now.to_string()) |
| 262 | } |
| 263 | |
| 264 | fn ensure_space_internal(conn: &Connection, slug: &str) -> Result<String> { |
| 265 | let mut stmt = conn.prepare("SELECT id FROM spaces WHERE slug = ?1")?; |
| 266 | let mut rows = stmt.query(params![slug])?; |
| 267 | if let Some(row) = rows.next()? { |
| 268 | return row.get(0); |
| 269 | } |
| 270 | drop(rows); |
| 271 | drop(stmt); |
| 272 | |
| 273 | let new_id = Uuid::new_v4().to_string(); |
| 274 | let now = Utc::now().to_rfc3339(); |
| 275 | conn.execute( |
| 276 | "INSERT INTO spaces (id, slug, created_at) VALUES (?1, ?2, ?3)", |
| 277 | params![new_id, slug, now], |
| 278 | )?; |
| 279 | Ok(new_id) |
| 280 | } |
| 281 | |
| 282 | pub struct SessionSummaryWrite<'a> { |
| 283 | pub session_id: &'a str, |
| 284 | pub branch_id: &'a str, |
| 285 | pub level: i64, |
| 286 | pub start_seq: i64, |
| 287 | pub end_seq: i64, |
| 288 | pub summary_text: &'a str, |
| 289 | pub source_hash: &'a str, |
| 290 | pub processor_version: &'a str, |
| 291 | } |
| 292 | |
| 293 | impl Database { |
| 294 | pub fn hmac_key(&self) -> &[u8] { |
| 295 | &self.hmac_key |
| 296 | } |
| 297 | |
| 298 | pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> { |
| 299 | let path_buf = path.as_ref().to_path_buf(); |
| 300 | let mut write_conn = Connection::open(&path_buf)?; |
| 301 | let _: Result<String, _> = |
| 302 | write_conn.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0)); |
| 303 | write_conn.execute_batch("PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;")?; |
| 304 | Self::run_migrations(&mut write_conn)?; |
| 305 | |
| 306 | let hmac_key = load_hmac_key(&write_conn)?; |
| 307 | let writer = Arc::new(StorageWriter::new(write_conn)); |
| 308 | let reader_pool = Arc::new(ReaderPool::new(Some(path_buf), None, 16)); |
| 309 | let conn = LegacyConnAdapter { |
| 310 | reader_pool: Arc::clone(&reader_pool), |
| 311 | }; |
| 312 | |
| 313 | Ok(Self { |
| 314 | writer, |
| 315 | reader_pool, |
| 316 | conn, |
| 317 | hmac_key, |
| 318 | }) |
| 319 | } |
| 320 | |
| 321 | #[allow(dead_code)] |
| 322 | pub fn open_in_memory() -> Result<Self> { |
| 323 | let uri = format!( |
| 324 | "file:cortex_mem_{}?mode=memory&cache=shared", |
| 325 | Uuid::new_v4().simple() |
| 326 | ); |
| 327 | let flags = rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE |
| 328 | | rusqlite::OpenFlags::SQLITE_OPEN_CREATE |
| 329 | | rusqlite::OpenFlags::SQLITE_OPEN_URI |
| 330 | | rusqlite::OpenFlags::SQLITE_OPEN_SHARED_CACHE; |
| 331 | let mut write_conn = Connection::open_with_flags(&uri, flags)?; |
| 332 | let _: Result<String, _> = |
| 333 | write_conn.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0)); |
| 334 | write_conn.execute_batch("PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;")?; |
| 335 | Self::run_migrations(&mut write_conn)?; |
| 336 | |
| 337 | let hmac_key = load_hmac_key(&write_conn)?; |
| 338 | let writer = Arc::new(StorageWriter::new(write_conn)); |
| 339 | let reader_pool = Arc::new(ReaderPool::new(None, Some(uri), 16)); |
| 340 | let conn = LegacyConnAdapter { |
| 341 | reader_pool: Arc::clone(&reader_pool), |
| 342 | }; |
| 343 | |
| 344 | Ok(Self { |
| 345 | writer, |
| 346 | reader_pool, |
| 347 | conn, |
| 348 | hmac_key, |
| 349 | }) |
| 350 | } |
| 351 | |
| 352 | fn run_migrations(conn: &mut Connection) -> Result<()> { |
| 353 | let user_version: i32 = conn.query_row("PRAGMA user_version;", [], |r| r.get(0))?; |
| 354 | |
| 355 | if user_version < 1 { |
| 356 | conn.execute_batch( |
| 357 | "BEGIN; |
| 358 | CREATE TABLE IF NOT EXISTS spaces ( |
| 359 | id TEXT PRIMARY KEY, |
| 360 | slug TEXT UNIQUE NOT NULL, |
| 361 | created_at TEXT NOT NULL |
| 362 | ); |
| 363 | |
| 364 | CREATE TABLE IF NOT EXISTS entities ( |
| 365 | id TEXT PRIMARY KEY, |
| 366 | space_id TEXT NOT NULL, |
| 367 | space_slug TEXT NOT NULL, |
| 368 | entity_type TEXT NOT NULL, |
| 369 | canonical_name TEXT NOT NULL, |
| 370 | content TEXT NOT NULL, |
| 371 | aliases_json TEXT NOT NULL DEFAULT '[]', |
| 372 | metadata_json TEXT NOT NULL DEFAULT '{}', |
| 373 | confidence REAL NOT NULL DEFAULT 1.0, |
| 374 | revision INTEGER NOT NULL DEFAULT 1, |
| 375 | retracted INTEGER NOT NULL DEFAULT 0, |
| 376 | valid_from TEXT, |
| 377 | valid_to TEXT, |
| 378 | created_at TEXT NOT NULL, |
| 379 | embedding BLOB |
| 380 | ); |
| 381 | |
| 382 | CREATE INDEX IF NOT EXISTS idx_entities_canonical ON entities(space_slug, canonical_name); |
| 383 | CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(space_slug, entity_type); |
| 384 | |
| 385 | CREATE VIRTUAL TABLE IF NOT EXISTS entities_fts USING fts5( |
| 386 | id UNINDEXED, |
| 387 | canonical_name, |
| 388 | content, |
| 389 | space_slug UNINDEXED |
| 390 | ); |
| 391 | |
| 392 | CREATE TABLE IF NOT EXISTS claims ( |
| 393 | id TEXT PRIMARY KEY, |
| 394 | space_id TEXT NOT NULL, |
| 395 | space_slug TEXT NOT NULL, |
| 396 | subject_entity_id TEXT NOT NULL, |
| 397 | predicate TEXT NOT NULL, |
| 398 | object_entity_id TEXT, |
| 399 | literal_value_json TEXT, |
| 400 | confidence REAL NOT NULL DEFAULT 1.0, |
| 401 | metadata_json TEXT NOT NULL DEFAULT '{}', |
| 402 | retracted INTEGER NOT NULL DEFAULT 0, |
| 403 | created_at TEXT NOT NULL |
| 404 | ); |
| 405 | |
| 406 | CREATE INDEX IF NOT EXISTS idx_claims_subject ON claims(subject_entity_id); |
| 407 | CREATE INDEX IF NOT EXISTS idx_claims_object ON claims(object_entity_id); |
| 408 | |
| 409 | PRAGMA user_version = 1; |
| 410 | COMMIT;", |
| 411 | )?; |
| 412 | |
| 413 | // Ensure default space exists |
| 414 | let space_id = Uuid::new_v4().to_string(); |
| 415 | let now = Utc::now().to_rfc3339(); |
| 416 | let _ = conn.execute( |
| 417 | "INSERT OR IGNORE INTO spaces (id, slug, created_at) VALUES (?1, ?2, ?3)", |
| 418 | params![space_id, "atlas-memory", now], |
| 419 | ); |
| 420 | } |
| 421 | |
| 422 | if user_version < 2 { |
| 423 | conn.execute_batch( |
| 424 | "BEGIN; |
| 425 | CREATE TABLE IF NOT EXISTS sessions ( |
| 426 | id TEXT PRIMARY KEY, |
| 427 | space_slug TEXT NOT NULL, |
| 428 | agent_id TEXT, |
| 429 | world_id TEXT, |
| 430 | parent_session_id TEXT, |
| 431 | fork_event_id TEXT, |
| 432 | created_at TEXT NOT NULL, |
| 433 | closed_at TEXT, |
| 434 | status TEXT NOT NULL DEFAULT 'active', |
| 435 | retention_class TEXT NOT NULL DEFAULT 'standard', |
| 436 | metadata_json TEXT NOT NULL DEFAULT '{}' |
| 437 | ); |
| 438 | |
| 439 | CREATE INDEX IF NOT EXISTS idx_sessions_space ON sessions(space_slug); |
| 440 | CREATE INDEX IF NOT EXISTS idx_sessions_status ON sessions(status); |
| 441 | |
| 442 | CREATE TABLE IF NOT EXISTS session_events ( |
| 443 | id TEXT PRIMARY KEY, |
| 444 | session_id TEXT NOT NULL, |
| 445 | sequence INTEGER NOT NULL, |
| 446 | branch_id TEXT NOT NULL, |
| 447 | parent_event_id TEXT, |
| 448 | event_type TEXT NOT NULL, |
| 449 | role TEXT, |
| 450 | content TEXT, |
| 451 | payload_json TEXT NOT NULL DEFAULT '{}', |
| 452 | created_at TEXT NOT NULL, |
| 453 | content_hash TEXT NOT NULL, |
| 454 | sensitivity TEXT, |
| 455 | redacted INTEGER NOT NULL DEFAULT 0, |
| 456 | segment_id TEXT, |
| 457 | FOREIGN KEY(session_id) REFERENCES sessions(id), |
| 458 | UNIQUE(session_id, branch_id, sequence) |
| 459 | ); |
| 460 | |
| 461 | CREATE INDEX IF NOT EXISTS idx_session_events_order |
| 462 | ON session_events(session_id, branch_id, sequence); |
| 463 | CREATE INDEX IF NOT EXISTS idx_session_events_type |
| 464 | ON session_events(event_type); |
| 465 | |
| 466 | CREATE TABLE IF NOT EXISTS processing_watermarks ( |
| 467 | session_id TEXT NOT NULL, |
| 468 | processor_kind TEXT NOT NULL, |
| 469 | processor_version TEXT NOT NULL, |
| 470 | watermark_seq INTEGER NOT NULL, |
| 471 | updated_at TEXT NOT NULL, |
| 472 | PRIMARY KEY(session_id, processor_kind, processor_version), |
| 473 | FOREIGN KEY(session_id) REFERENCES sessions(id) |
| 474 | ); |
| 475 | |
| 476 | CREATE TABLE IF NOT EXISTS event_segments ( |
| 477 | id TEXT PRIMARY KEY, |
| 478 | session_id TEXT NOT NULL, |
| 479 | branch_id TEXT NOT NULL, |
| 480 | start_seq INTEGER NOT NULL, |
| 481 | end_seq INTEGER NOT NULL, |
| 482 | merkle_root TEXT NOT NULL, |
| 483 | prev_segment_root TEXT, |
| 484 | sealed_at TEXT NOT NULL, |
| 485 | state TEXT NOT NULL DEFAULT 'sealed', |
| 486 | FOREIGN KEY(session_id) REFERENCES sessions(id) |
| 487 | ); |
| 488 | |
| 489 | CREATE INDEX IF NOT EXISTS idx_event_segments_range |
| 490 | ON event_segments(session_id, branch_id, start_seq, end_seq); |
| 491 | |
| 492 | PRAGMA user_version = 2; |
| 493 | COMMIT;", |
| 494 | )?; |
| 495 | } |
| 496 | |
| 497 | if user_version < 3 { |
| 498 | conn.execute_batch( |
| 499 | "BEGIN; |
| 500 | CREATE TABLE IF NOT EXISTS session_summaries ( |
| 501 | id TEXT PRIMARY KEY, |
| 502 | session_id TEXT NOT NULL, |
| 503 | branch_id TEXT NOT NULL, |
| 504 | level INTEGER NOT NULL DEFAULT 0, |
| 505 | start_seq INTEGER NOT NULL, |
| 506 | end_seq INTEGER NOT NULL, |
| 507 | summary_text TEXT NOT NULL, |
| 508 | source_hash TEXT NOT NULL, |
| 509 | processor_version TEXT NOT NULL, |
| 510 | created_at TEXT NOT NULL, |
| 511 | FOREIGN KEY(session_id) REFERENCES sessions(id) |
| 512 | ); |
| 513 | |
| 514 | CREATE INDEX IF NOT EXISTS idx_session_summaries_range |
| 515 | ON session_summaries(session_id, branch_id, level, start_seq, end_seq); |
| 516 | |
| 517 | CREATE TABLE IF NOT EXISTS memory_candidates ( |
| 518 | id TEXT PRIMARY KEY, |
| 519 | space_slug TEXT NOT NULL, |
| 520 | session_id TEXT NOT NULL, |
| 521 | branch_id TEXT NOT NULL, |
| 522 | memory_type TEXT NOT NULL, |
| 523 | subject TEXT NOT NULL, |
| 524 | predicate TEXT NOT NULL, |
| 525 | object_value_json TEXT NOT NULL, |
| 526 | scope TEXT NOT NULL DEFAULT 'global', |
| 527 | confidence REAL NOT NULL, |
| 528 | verification_tier TEXT NOT NULL DEFAULT 'T0Direct', |
| 529 | state TEXT NOT NULL DEFAULT 'pending', |
| 530 | extractor_version TEXT NOT NULL, |
| 531 | created_at TEXT NOT NULL, |
| 532 | FOREIGN KEY(session_id) REFERENCES sessions(id) |
| 533 | ); |
| 534 | |
| 535 | CREATE INDEX IF NOT EXISTS idx_memory_candidates_state |
| 536 | ON memory_candidates(space_slug, state, verification_tier); |
| 537 | CREATE INDEX IF NOT EXISTS idx_memory_candidates_session |
| 538 | ON memory_candidates(session_id, branch_id); |
| 539 | |
| 540 | CREATE TABLE IF NOT EXISTS candidate_evidence ( |
| 541 | candidate_id TEXT NOT NULL, |
| 542 | evidence_id TEXT NOT NULL, |
| 543 | source_kind TEXT NOT NULL, |
| 544 | evidence_hash TEXT NOT NULL, |
| 545 | PRIMARY KEY(candidate_id, evidence_id), |
| 546 | FOREIGN KEY(candidate_id) REFERENCES memory_candidates(id) |
| 547 | ); |
| 548 | |
| 549 | PRAGMA user_version = 3; |
| 550 | COMMIT;", |
| 551 | )?; |
| 552 | } |
| 553 | |
| 554 | if user_version < 4 { |
| 555 | conn.execute_batch( |
| 556 | "BEGIN; |
| 557 | CREATE TABLE IF NOT EXISTS promotion_receipts ( |
| 558 | id TEXT PRIMARY KEY, |
| 559 | candidate_id TEXT NOT NULL, |
| 560 | claim_id TEXT NOT NULL, |
| 561 | policy_id TEXT NOT NULL, |
| 562 | policy_version TEXT NOT NULL, |
| 563 | achieved_tier TEXT NOT NULL, |
| 564 | verifier_receipt TEXT, |
| 565 | promoted_at TEXT NOT NULL |
| 566 | ); |
| 567 | |
| 568 | CREATE INDEX IF NOT EXISTS idx_promotion_receipts_claim |
| 569 | ON promotion_receipts(claim_id); |
| 570 | |
| 571 | CREATE TABLE IF NOT EXISTS claim_evidence ( |
| 572 | claim_id TEXT NOT NULL, |
| 573 | evidence_id TEXT NOT NULL, |
| 574 | source_kind TEXT NOT NULL, |
| 575 | evidence_hash TEXT NOT NULL, |
| 576 | PRIMARY KEY(claim_id, evidence_id) |
| 577 | ); |
| 578 | |
| 579 | CREATE INDEX IF NOT EXISTS idx_claim_evidence_ev |
| 580 | ON claim_evidence(evidence_id); |
| 581 | |
| 582 | PRAGMA user_version = 4; |
| 583 | COMMIT;", |
| 584 | )?; |
| 585 | } |
| 586 | |
| 587 | if user_version < 5 { |
| 588 | conn.execute_batch( |
| 589 | "BEGIN; |
| 590 | CREATE TABLE IF NOT EXISTS security_state ( |
| 591 | id INTEGER PRIMARY KEY CHECK (id = 1), |
| 592 | hmac_key BLOB NOT NULL |
| 593 | ); |
| 594 | INSERT INTO security_state (id, hmac_key) |
| 595 | SELECT 1, randomblob(32) |
| 596 | WHERE NOT EXISTS (SELECT 1 FROM security_state WHERE id = 1); |
| 597 | |
| 598 | CREATE TABLE IF NOT EXISTS evidence_records ( |
| 599 | id TEXT PRIMARY KEY, |
| 600 | source_kind TEXT NOT NULL, |
| 601 | source_id TEXT NOT NULL, |
| 602 | commitment TEXT NOT NULL, |
| 603 | merkle_root TEXT, |
| 604 | segment_id TEXT, |
| 605 | retention_class TEXT NOT NULL, |
| 606 | retain_until TEXT, |
| 607 | created_at TEXT NOT NULL |
| 608 | ); |
| 609 | CREATE INDEX IF NOT EXISTS idx_evidence_source |
| 610 | ON evidence_records(source_kind, source_id); |
| 611 | |
| 612 | ALTER TABLE claims ADD COLUMN verification_tier TEXT NOT NULL DEFAULT 'T0Direct'; |
| 613 | ALTER TABLE claims ADD COLUMN status TEXT NOT NULL DEFAULT 'active'; |
| 614 | |
| 615 | PRAGMA user_version = 5; |
| 616 | COMMIT;", |
| 617 | )?; |
| 618 | } |
| 619 | |
| 620 | Ok(()) |
| 621 | } |
| 622 | |
| 623 | pub fn ensure_space(&self, slug: &str) -> Result<String> { |
| 624 | { |
| 625 | let conn = self.reader_pool.acquire()?; |
| 626 | let mut stmt = conn.prepare("SELECT id FROM spaces WHERE slug = ?1")?; |
| 627 | let mut rows = stmt.query(params![slug])?; |
| 628 | if let Some(row) = rows.next()? { |
| 629 | return row.get(0); |
| 630 | } |
| 631 | } |
| 632 | let slug_owned = slug.to_string(); |
| 633 | self.writer |
| 634 | .execute(move |conn| ensure_space_internal(conn, &slug_owned)) |
| 635 | } |
| 636 | |
| 637 | pub fn upsert_entity( |
| 638 | &self, |
| 639 | input: &EntityWriteInput, |
| 640 | embedding: Option<&[f32]>, |
| 641 | ) -> Result<ReceiptDetails> { |
| 642 | let embedding_blob = embedding.map(embedding_to_bytes); |
| 643 | let aliases_json = |
| 644 | serde_json::to_string(&input.aliases).unwrap_or_else(|_| "[]".to_string()); |
| 645 | let metadata_json = |
| 646 | serde_json::to_string(&input.metadata).unwrap_or_else(|_| "{}".to_string()); |
| 647 | let space = input.space.clone(); |
| 648 | let canonical_name = input.canonical_name.clone(); |
| 649 | let entity_type = input.entity_type.clone(); |
| 650 | let content = input.content.clone(); |
| 651 | let confidence = input.confidence; |
| 652 | let valid_from = input.valid_from.clone(); |
| 653 | let valid_to = input.valid_to.clone(); |
| 654 | let input_id = input.id.clone(); |
| 655 | |
| 656 | self.writer.execute(move |conn| { |
| 657 | let space_id = ensure_space_internal(conn, &space)?; |
| 658 | let now = Utc::now().to_rfc3339(); |
| 659 | |
| 660 | // Check if entity exists by canonical_name in space |
| 661 | let mut stmt = conn.prepare( |
| 662 | "SELECT id, revision FROM entities WHERE space_slug = ?1 AND canonical_name = ?2", |
| 663 | )?; |
| 664 | let mut rows = stmt.query(params![space, canonical_name])?; |
| 665 | |
| 666 | let (target_id, revision) = if let Some(row) = rows.next()? { |
| 667 | let existing_id: String = row.get(0)?; |
| 668 | let rev: i64 = row.get(1)?; |
| 669 | (existing_id, rev + 1) |
| 670 | } else { |
| 671 | let new_id = input_id.unwrap_or_else(|| Uuid::new_v4().to_string()); |
| 672 | (new_id, 1) |
| 673 | }; |
| 674 | drop(rows); |
| 675 | drop(stmt); |
| 676 | |
| 677 | conn.execute( |
| 678 | "INSERT INTO entities (id, space_id, space_slug, entity_type, canonical_name, content, aliases_json, metadata_json, confidence, revision, retracted, valid_from, valid_to, created_at, embedding) |
| 679 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 0, ?11, ?12, ?13, ?14) |
| 680 | ON CONFLICT(id) DO UPDATE SET |
| 681 | entity_type = excluded.entity_type, |
| 682 | canonical_name = excluded.canonical_name, |
| 683 | content = excluded.content, |
| 684 | aliases_json = excluded.aliases_json, |
| 685 | metadata_json = excluded.metadata_json, |
| 686 | confidence = excluded.confidence, |
| 687 | revision = excluded.revision, |
| 688 | retracted = 0, |
| 689 | valid_from = excluded.valid_from, |
| 690 | valid_to = excluded.valid_to, |
| 691 | embedding = COALESCE(excluded.embedding, entities.embedding)", |
| 692 | params![ |
| 693 | target_id, |
| 694 | space_id, |
| 695 | space, |
| 696 | entity_type, |
| 697 | canonical_name, |
| 698 | content, |
| 699 | aliases_json, |
| 700 | metadata_json, |
| 701 | confidence, |
| 702 | revision, |
| 703 | valid_from, |
| 704 | valid_to, |
| 705 | now, |
| 706 | embedding_blob, |
| 707 | ], |
| 708 | )?; |
| 709 | |
| 710 | // Update FTS table |
| 711 | let _ = conn.execute("DELETE FROM entities_fts WHERE id = ?1", params![target_id]); |
| 712 | let _ = conn.execute( |
| 713 | "INSERT INTO entities_fts (id, canonical_name, content, space_slug) VALUES (?1, ?2, ?3, ?4)", |
| 714 | params![target_id, canonical_name, content, space], |
| 715 | ); |
| 716 | |
| 717 | Ok(ReceiptDetails { |
| 718 | id: Uuid::new_v4().to_string(), |
| 719 | operation: "entity.upsert".to_string(), |
| 720 | target_type: "entity".to_string(), |
| 721 | target_id, |
| 722 | committed_at: now, |
| 723 | }) |
| 724 | }) |
| 725 | } |
| 726 | |
| 727 | pub fn upsert_claim(&self, input: &ClaimWriteInput) -> Result<ReceiptDetails> { |
| 728 | let space = input.space.clone(); |
| 729 | let claim_id = input |
| 730 | .id |
| 731 | .clone() |
| 732 | .unwrap_or_else(|| Uuid::new_v4().to_string()); |
| 733 | let literal_json = input |
| 734 | .literal_value |
| 735 | .as_ref() |
| 736 | .map(|v| serde_json::to_string(v).unwrap_or_default()); |
| 737 | let metadata_json = |
| 738 | serde_json::to_string(&input.metadata).unwrap_or_else(|_| "{}".to_string()); |
| 739 | let subject_entity_id = input.subject_entity_id.clone(); |
| 740 | let predicate = input.predicate.clone(); |
| 741 | let object_entity_id = input.object_entity_id.clone(); |
| 742 | let confidence = input.confidence; |
| 743 | |
| 744 | self.writer.execute(move |conn| { |
| 745 | let space_id = ensure_space_internal(conn, &space)?; |
| 746 | let now = Utc::now().to_rfc3339(); |
| 747 | |
| 748 | conn.execute( |
| 749 | "INSERT INTO claims (id, space_id, space_slug, subject_entity_id, predicate, object_entity_id, literal_value_json, confidence, metadata_json, retracted, created_at) |
| 750 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 0, ?10) |
| 751 | ON CONFLICT(id) DO UPDATE SET |
| 752 | predicate = excluded.predicate, |
| 753 | object_entity_id = excluded.object_entity_id, |
| 754 | literal_value_json = excluded.literal_value_json, |
| 755 | confidence = excluded.confidence, |
| 756 | metadata_json = excluded.metadata_json, |
| 757 | retracted = 0", |
| 758 | params![ |
| 759 | claim_id, |
| 760 | space_id, |
| 761 | space, |
| 762 | subject_entity_id, |
| 763 | predicate, |
| 764 | object_entity_id, |
| 765 | literal_json, |
| 766 | confidence, |
| 767 | metadata_json, |
| 768 | now, |
| 769 | ], |
| 770 | )?; |
| 771 | |
| 772 | Ok(ReceiptDetails { |
| 773 | id: Uuid::new_v4().to_string(), |
| 774 | operation: "claim.upsert".to_string(), |
| 775 | target_type: "claim".to_string(), |
| 776 | target_id: claim_id, |
| 777 | committed_at: now, |
| 778 | }) |
| 779 | }) |
| 780 | } |
| 781 | |
| 782 | pub fn retract_target(&self, target_type: &str, target_id: &str) -> Result<ReceiptDetails> { |
| 783 | let tt = target_type.to_string(); |
| 784 | let tid = target_id.to_string(); |
| 785 | self.writer.execute(move |conn| { |
| 786 | let now = Utc::now().to_rfc3339(); |
| 787 | |
| 788 | if tt == "entity" { |
| 789 | conn.execute( |
| 790 | "UPDATE entities SET retracted = 1 WHERE id = ?1", |
| 791 | params![tid], |
| 792 | )?; |
| 793 | conn.execute("DELETE FROM entities_fts WHERE id = ?1", params![tid])?; |
| 794 | } else if tt == "claim" { |
| 795 | conn.execute( |
| 796 | "UPDATE claims SET retracted = 1 WHERE id = ?1", |
| 797 | params![tid], |
| 798 | )?; |
| 799 | } |
| 800 | |
| 801 | Ok(ReceiptDetails { |
| 802 | id: Uuid::new_v4().to_string(), |
| 803 | operation: format!("{}.retract", tt), |
| 804 | target_type: tt, |
| 805 | target_id: tid, |
| 806 | committed_at: now, |
| 807 | }) |
| 808 | }) |
| 809 | } |
| 810 | |
| 811 | pub fn get_entity( |
| 812 | &self, |
| 813 | id_or_name: &str, |
| 814 | space: Option<&str>, |
| 815 | ) -> Result<Option<CortexEntity>> { |
| 816 | let conn = self.reader_pool.acquire()?; |
| 817 | let target_space = space.unwrap_or("atlas-memory"); |
| 818 | |
| 819 | let mut stmt = conn.prepare( |
| 820 | "SELECT id, space_id, space_slug, entity_type, canonical_name, content, aliases_json, metadata_json, confidence, revision, retracted, valid_from, valid_to, created_at |
| 821 | FROM entities |
| 822 | WHERE (id = ?1 OR canonical_name = ?1) AND space_slug = ?2 AND retracted = 0 |
| 823 | LIMIT 1" |
| 824 | )?; |
| 825 | |
| 826 | let mut rows = stmt.query(params![id_or_name, target_space])?; |
| 827 | if let Some(row) = rows.next()? { |
| 828 | let aliases_str: String = row.get(6)?; |
| 829 | let meta_str: String = row.get(7)?; |
| 830 | Ok(Some(CortexEntity { |
| 831 | id: row.get(0)?, |
| 832 | space_id: row.get(1)?, |
| 833 | space_slug: row.get(2)?, |
| 834 | entity_type: row.get(3)?, |
| 835 | canonical_name: row.get(4)?, |
| 836 | content: row.get(5)?, |
| 837 | aliases: serde_json::from_str(&aliases_str).unwrap_or_default(), |
| 838 | metadata: serde_json::from_str(&meta_str).unwrap_or_else(|_| serde_json::json!({})), |
| 839 | confidence: row.get(8)?, |
| 840 | revision: row.get(9)?, |
| 841 | retracted: row.get::<_, i64>(10)? != 0, |
| 842 | valid_from: row.get(11)?, |
| 843 | valid_to: row.get(12)?, |
| 844 | created_at: row.get(13)?, |
| 845 | })) |
| 846 | } else { |
| 847 | Ok(None) |
| 848 | } |
| 849 | } |
| 850 | |
| 851 | pub fn search_entities( |
| 852 | &self, |
| 853 | query: &str, |
| 854 | space: Option<&str>, |
| 855 | limit: usize, |
| 856 | ) -> Result<Vec<SearchResult>> { |
| 857 | let conn = self.reader_pool.acquire()?; |
| 858 | let target_space = space.unwrap_or("atlas-memory"); |
| 859 | let query_trimmed = query.trim(); |
| 860 | |
| 861 | if query_trimmed.is_empty() { |
| 862 | let mut stmt = conn.prepare( |
| 863 | "SELECT id, space_id, space_slug, entity_type, canonical_name, content, aliases_json, metadata_json, confidence, revision, retracted, valid_from, valid_to, created_at |
| 864 | FROM entities |
| 865 | WHERE space_slug = ?1 AND retracted = 0 |
| 866 | ORDER BY created_at DESC |
| 867 | LIMIT ?2" |
| 868 | )?; |
| 869 | let rows = stmt.query_map(params![target_space, limit], |row| { |
| 870 | let aliases_str: String = row.get(6)?; |
| 871 | let meta_str: String = row.get(7)?; |
| 872 | Ok(SearchResult { |
| 873 | entity: CortexEntity { |
| 874 | id: row.get(0)?, |
| 875 | space_id: row.get(1)?, |
| 876 | space_slug: row.get(2)?, |
| 877 | entity_type: row.get(3)?, |
| 878 | canonical_name: row.get(4)?, |
| 879 | content: row.get(5)?, |
| 880 | aliases: serde_json::from_str(&aliases_str).unwrap_or_default(), |
| 881 | metadata: serde_json::from_str(&meta_str) |
| 882 | .unwrap_or_else(|_| serde_json::json!({})), |
| 883 | confidence: row.get(8)?, |
| 884 | revision: row.get(9)?, |
| 885 | retracted: row.get::<_, i64>(10)? != 0, |
| 886 | valid_from: row.get(11)?, |
| 887 | valid_to: row.get(12)?, |
| 888 | created_at: row.get(13)?, |
| 889 | }, |
| 890 | lexical_score: 0.4, |
| 891 | graph_score: 0.0, |
| 892 | semantic_score: 0.0, |
| 893 | score: 0.4, |
| 894 | }) |
| 895 | })?; |
| 896 | |
| 897 | let mut results = Vec::new(); |
| 898 | for r in rows { |
| 899 | results.push(r?); |
| 900 | } |
| 901 | return Ok(results); |
| 902 | } |
| 903 | |
| 904 | // FTS search with support for exact, prefix (*), and boolean operators (AND, OR, NOT) |
| 905 | let clean_q = query_trimmed.replace('"', ""); |
| 906 | let has_fts_ops = clean_q.contains(" AND ") |
| 907 | || clean_q.contains(" OR ") |
| 908 | || clean_q.contains(" NOT ") |
| 909 | || clean_q.contains('*'); |
| 910 | |
| 911 | let mut results = Vec::new(); |
| 912 | |
| 913 | let run_fts = |query_str: &str| -> Option<Vec<SearchResult>> { |
| 914 | let mut stmt = conn.prepare( |
| 915 | "SELECT e.id, e.space_id, e.space_slug, e.entity_type, e.canonical_name, e.content, e.aliases_json, e.metadata_json, e.confidence, e.revision, e.retracted, e.valid_from, e.valid_to, e.created_at, |
| 916 | COALESCE(bm25(entities_fts), 5.0) as bm25_rank |
| 917 | FROM entities e |
| 918 | JOIN entities_fts f ON f.id = e.id |
| 919 | WHERE entities_fts MATCH ?1 AND e.space_slug = ?2 AND e.retracted = 0 |
| 920 | ORDER BY bm25_rank ASC |
| 921 | LIMIT ?3" |
| 922 | ).ok()?; |
| 923 | |
| 924 | let rows = stmt |
| 925 | .query_map(params![query_str, target_space, limit], |row| { |
| 926 | let aliases_str: String = row.get(6)?; |
| 927 | let meta_str: String = row.get(7)?; |
| 928 | let bm25_rank: f64 = row.get(14)?; |
| 929 | let lexical_score = 1.0 / (1.0 + bm25_rank.abs()); |
| 930 | Ok(SearchResult { |
| 931 | entity: CortexEntity { |
| 932 | id: row.get(0)?, |
| 933 | space_id: row.get(1)?, |
| 934 | space_slug: row.get(2)?, |
| 935 | entity_type: row.get(3)?, |
| 936 | canonical_name: row.get(4)?, |
| 937 | content: row.get(5)?, |
| 938 | aliases: serde_json::from_str(&aliases_str).unwrap_or_default(), |
| 939 | metadata: serde_json::from_str(&meta_str) |
| 940 | .unwrap_or_else(|_| serde_json::json!({})), |
| 941 | confidence: row.get(8)?, |
| 942 | revision: row.get(9)?, |
| 943 | retracted: row.get::<_, i64>(10)? != 0, |
| 944 | valid_from: row.get(11)?, |
| 945 | valid_to: row.get(12)?, |
| 946 | created_at: row.get(13)?, |
| 947 | }, |
| 948 | lexical_score, |
| 949 | graph_score: 0.0, |
| 950 | semantic_score: 0.0, |
| 951 | score: lexical_score, |
| 952 | }) |
| 953 | }) |
| 954 | .ok()?; |
| 955 | |
| 956 | let mut out = Vec::new(); |
| 957 | for r in rows.flatten() { |
| 958 | out.push(r); |
| 959 | } |
| 960 | Some(out) |
| 961 | }; |
| 962 | |
| 963 | if has_fts_ops { |
| 964 | if let Some(r) = run_fts(&clean_q) { |
| 965 | results = r; |
| 966 | } |
| 967 | } |
| 968 | |
| 969 | if results.is_empty() { |
| 970 | let fts_query = format!("\"{}\"", clean_q); |
| 971 | if let Some(r) = run_fts(&fts_query) { |
| 972 | results = r; |
| 973 | } |
| 974 | } |
| 975 | |
| 976 | if results.is_empty() { |
| 977 | let terms: Vec<&str> = clean_q.split_whitespace().collect(); |
| 978 | if terms.len() > 1 { |
| 979 | let and_query = terms.join(" AND "); |
| 980 | if let Some(r) = run_fts(&and_query) { |
| 981 | results = r; |
| 982 | } |
| 983 | } |
| 984 | } |
| 985 | |
| 986 | // Fallback to substring match if FTS did not return enough |
| 987 | if results.len() < limit { |
| 988 | let pattern = format!("%{}%", query_trimmed); |
| 989 | let mut sub_stmt = conn.prepare( |
| 990 | "SELECT id, space_id, space_slug, entity_type, canonical_name, content, aliases_json, metadata_json, confidence, revision, retracted, valid_from, valid_to, created_at |
| 991 | FROM entities |
| 992 | WHERE (canonical_name LIKE ?1 OR content LIKE ?1) AND space_slug = ?2 AND retracted = 0 |
| 993 | LIMIT ?3" |
| 994 | )?; |
| 995 | let sub_rows = sub_stmt.query_map(params![pattern, target_space, limit], |row| { |
| 996 | let aliases_str: String = row.get(6)?; |
| 997 | let meta_str: String = row.get(7)?; |
| 998 | Ok(SearchResult { |
| 999 | entity: CortexEntity { |
| 1000 | id: row.get(0)?, |
| 1001 | space_id: row.get(1)?, |
| 1002 | space_slug: row.get(2)?, |
| 1003 | entity_type: row.get(3)?, |
| 1004 | canonical_name: row.get(4)?, |
| 1005 | content: row.get(5)?, |
| 1006 | aliases: serde_json::from_str(&aliases_str).unwrap_or_default(), |
| 1007 | metadata: serde_json::from_str(&meta_str) |
| 1008 | .unwrap_or_else(|_| serde_json::json!({})), |
| 1009 | confidence: row.get(8)?, |
| 1010 | revision: row.get(9)?, |
| 1011 | retracted: row.get::<_, i64>(10)? != 0, |
| 1012 | valid_from: row.get(11)?, |
| 1013 | valid_to: row.get(12)?, |
| 1014 | created_at: row.get(13)?, |
| 1015 | }, |
| 1016 | lexical_score: 0.7, |
| 1017 | graph_score: 0.0, |
| 1018 | semantic_score: 0.0, |
| 1019 | score: 0.7, |
| 1020 | }) |
| 1021 | })?; |
| 1022 | for r in sub_rows { |
| 1023 | let sr = r?; |
| 1024 | if !results |
| 1025 | .iter() |
| 1026 | .any(|existing| existing.entity.id == sr.entity.id) |
| 1027 | { |
| 1028 | results.push(sr); |
| 1029 | } |
| 1030 | } |
| 1031 | } |
| 1032 | |
| 1033 | results.truncate(limit); |
| 1034 | Ok(results) |
| 1035 | } |
| 1036 | |
| 1037 | pub fn recall_entities( |
| 1038 | &self, |
| 1039 | query_text: &str, |
| 1040 | query_embedding: Option<&[f32]>, |
| 1041 | space: Option<&str>, |
| 1042 | limit: usize, |
| 1043 | ) -> Result<Vec<RecallItem>> { |
| 1044 | let conn = self.reader_pool.acquire()?; |
| 1045 | let target_space = space.unwrap_or("atlas-memory"); |
| 1046 | |
| 1047 | let mut stmt = conn.prepare( |
| 1048 | "SELECT id, space_id, space_slug, entity_type, canonical_name, content, aliases_json, metadata_json, confidence, revision, retracted, valid_from, valid_to, created_at, embedding |
| 1049 | FROM entities |
| 1050 | WHERE space_slug = ?1 AND retracted = 0" |
| 1051 | )?; |
| 1052 | |
| 1053 | let rows = stmt.query_map(params![target_space], |row| { |
| 1054 | let aliases_str: String = row.get(6)?; |
| 1055 | let meta_str: String = row.get(7)?; |
| 1056 | let embedding_blob: Option<Vec<u8>> = row.get(14)?; |
| 1057 | let entity = CortexEntity { |
| 1058 | id: row.get(0)?, |
| 1059 | space_id: row.get(1)?, |
| 1060 | space_slug: row.get(2)?, |
| 1061 | entity_type: row.get(3)?, |
| 1062 | canonical_name: row.get(4)?, |
| 1063 | content: row.get(5)?, |
| 1064 | aliases: serde_json::from_str(&aliases_str).unwrap_or_default(), |
| 1065 | metadata: serde_json::from_str(&meta_str).unwrap_or_else(|_| serde_json::json!({})), |
| 1066 | confidence: row.get(8)?, |
| 1067 | revision: row.get(9)?, |
| 1068 | retracted: row.get::<_, i64>(10)? != 0, |
| 1069 | valid_from: row.get(11)?, |
| 1070 | valid_to: row.get(12)?, |
| 1071 | created_at: row.get(13)?, |
| 1072 | }; |
| 1073 | Ok((entity, embedding_blob)) |
| 1074 | })?; |
| 1075 | |
| 1076 | let mut candidates = Vec::new(); |
| 1077 | let query_lower = query_text.to_lowercase(); |
| 1078 | |
| 1079 | for r in rows { |
| 1080 | let (entity, emb_blob) = r?; |
| 1081 | let mut semantic_score = 0.0f64; |
| 1082 | |
| 1083 | if let (Some(q_emb), Some(blob)) = (query_embedding, emb_blob) { |
| 1084 | let target_emb = bytes_to_embedding(&blob); |
| 1085 | semantic_score = cosine_similarity(q_emb, &target_emb) as f64; |
| 1086 | } |
| 1087 | |
| 1088 | // Calculate simple lexical score |
| 1089 | let name_lower = entity.canonical_name.to_lowercase(); |
| 1090 | let content_lower = entity.content.to_lowercase(); |
| 1091 | let mut lexical_score = 0.0f64; |
| 1092 | if name_lower.contains(&query_lower) { |
| 1093 | lexical_score = 0.9; |
| 1094 | } else if content_lower.contains(&query_lower) { |
| 1095 | lexical_score = 0.6; |
| 1096 | } |
| 1097 | |
| 1098 | let final_score = if query_embedding.is_some() { |
| 1099 | 0.6 * semantic_score + 0.4 * lexical_score |
| 1100 | } else { |
| 1101 | lexical_score |
| 1102 | }; |
| 1103 | |
| 1104 | candidates.push(RecallItem { |
| 1105 | entity, |
| 1106 | final_score, |
| 1107 | component_scores: RecallComponentScores { |
| 1108 | lexical: lexical_score, |
| 1109 | semantic: semantic_score, |
| 1110 | confidence_recency: 0.95, |
| 1111 | graph: 0.0, |
| 1112 | }, |
| 1113 | }); |
| 1114 | } |
| 1115 | |
| 1116 | candidates.sort_by(|a, b| { |
| 1117 | b.final_score |
| 1118 | .partial_cmp(&a.final_score) |
| 1119 | .unwrap_or(std::cmp::Ordering::Equal) |
| 1120 | }); |
| 1121 | candidates.truncate(limit); |
| 1122 | Ok(candidates) |
| 1123 | } |
| 1124 | |
| 1125 | pub fn traverse_claims( |
| 1126 | &self, |
| 1127 | subject_id: &str, |
| 1128 | space: Option<&str>, |
| 1129 | ) -> Result<Vec<CortexClaim>> { |
| 1130 | let conn = self.reader_pool.acquire()?; |
| 1131 | let target_space = space.unwrap_or("atlas-memory"); |
| 1132 | |
| 1133 | let mut stmt = conn.prepare( |
| 1134 | "SELECT id, space_id, space_slug, subject_entity_id, predicate, object_entity_id, literal_value_json, confidence, metadata_json, retracted, created_at, verification_tier, status, (SELECT COUNT(*) FROM claim_evidence WHERE claim_id = claims.id) |
| 1135 | FROM claims |
| 1136 | WHERE ( |
| 1137 | subject_entity_id = ?1 |
| 1138 | OR object_entity_id = ?1 |
| 1139 | OR subject_entity_id IN (SELECT id FROM entities WHERE canonical_name = ?1 AND space_slug = ?2) |
| 1140 | OR object_entity_id IN (SELECT id FROM entities WHERE canonical_name = ?1 AND space_slug = ?2) |
| 1141 | ) AND space_slug = ?2 AND retracted = 0" |
| 1142 | )?; |
| 1143 | |
| 1144 | let rows = stmt.query_map(params![subject_id, target_space], |row| { |
| 1145 | let lit_str: Option<String> = row.get(6)?; |
| 1146 | let meta_str: String = row.get(8)?; |
| 1147 | let status_str: String = row.get(12)?; |
| 1148 | let tier_str: String = row.get(11)?; |
| 1149 | let status = match status_str.as_str() { |
| 1150 | "superseded" => ClaimStatus::Superseded, |
| 1151 | "disputed" => ClaimStatus::Disputed, |
| 1152 | "retracted" => ClaimStatus::Retracted, |
| 1153 | "invalidated" => ClaimStatus::Invalidated, |
| 1154 | _ => { |
| 1155 | if row.get::<_, i64>(9)? != 0 { |
| 1156 | ClaimStatus::Retracted |
| 1157 | } else { |
| 1158 | ClaimStatus::Active |
| 1159 | } |
| 1160 | } |
| 1161 | }; |
| 1162 | Ok(CortexClaim { |
| 1163 | id: row.get(0)?, |
| 1164 | space_id: row.get(1)?, |
| 1165 | space_slug: row.get(2)?, |
| 1166 | subject_entity_id: row.get(3)?, |
| 1167 | predicate: row.get(4)?, |
| 1168 | object_entity_id: row.get(5)?, |
| 1169 | literal_value: lit_str.and_then(|s| serde_json::from_str(&s).ok()), |
| 1170 | confidence: row.get(7)?, |
| 1171 | metadata: serde_json::from_str(&meta_str).unwrap_or_else(|_| serde_json::json!({})), |
| 1172 | retracted: row.get::<_, i64>(9)? != 0, |
| 1173 | created_at: row.get(10)?, |
| 1174 | verification_tier: VerificationTier::from_str_opt(&tier_str), |
| 1175 | status, |
| 1176 | evidence_count: row.get::<_, i64>(13)? as usize, |
| 1177 | }) |
| 1178 | })?; |
| 1179 | |
| 1180 | let mut claims = Vec::new(); |
| 1181 | for r in rows { |
| 1182 | claims.push(r?); |
| 1183 | } |
| 1184 | Ok(claims) |
| 1185 | } |
| 1186 | |
| 1187 | pub fn import_entity_raw( |
| 1188 | &self, |
| 1189 | entity: &CortexEntity, |
| 1190 | embedding: Option<&[f32]>, |
| 1191 | ) -> Result<()> { |
| 1192 | let embedding_blob = embedding.map(embedding_to_bytes); |
| 1193 | let aliases_json = |
| 1194 | serde_json::to_string(&entity.aliases).unwrap_or_else(|_| "[]".to_string()); |
| 1195 | let metadata_json = |
| 1196 | serde_json::to_string(&entity.metadata).unwrap_or_else(|_| "{}".to_string()); |
| 1197 | let entity = entity.clone(); |
| 1198 | |
| 1199 | self.writer.execute(move |conn| { |
| 1200 | let _ = ensure_space_internal(conn, &entity.space_slug)?; |
| 1201 | conn.execute( |
| 1202 | "INSERT INTO entities (id, space_id, space_slug, entity_type, canonical_name, content, aliases_json, metadata_json, confidence, revision, retracted, valid_from, valid_to, created_at, embedding) |
| 1203 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15) |
| 1204 | ON CONFLICT(id) DO UPDATE SET |
| 1205 | canonical_name = excluded.canonical_name, |
| 1206 | content = excluded.content, |
| 1207 | aliases_json = excluded.aliases_json, |
| 1208 | metadata_json = excluded.metadata_json, |
| 1209 | confidence = excluded.confidence, |
| 1210 | revision = excluded.revision, |
| 1211 | retracted = excluded.retracted, |
| 1212 | created_at = excluded.created_at, |
| 1213 | embedding = COALESCE(excluded.embedding, entities.embedding)", |
| 1214 | params![ |
| 1215 | entity.id, |
| 1216 | entity.space_id, |
| 1217 | entity.space_slug, |
| 1218 | entity.entity_type, |
| 1219 | entity.canonical_name, |
| 1220 | entity.content, |
| 1221 | aliases_json, |
| 1222 | metadata_json, |
| 1223 | entity.confidence, |
| 1224 | entity.revision, |
| 1225 | if entity.retracted { 1 } else { 0 }, |
| 1226 | entity.valid_from, |
| 1227 | entity.valid_to, |
| 1228 | entity.created_at, |
| 1229 | embedding_blob, |
| 1230 | ], |
| 1231 | )?; |
| 1232 | |
| 1233 | let _ = conn.execute("DELETE FROM entities_fts WHERE id = ?1", params![entity.id]); |
| 1234 | if !entity.retracted { |
| 1235 | let _ = conn.execute( |
| 1236 | "INSERT INTO entities_fts (id, canonical_name, content, space_slug) VALUES (?1, ?2, ?3, ?4)", |
| 1237 | params![entity.id, entity.canonical_name, entity.content, entity.space_slug], |
| 1238 | ); |
| 1239 | } |
| 1240 | Ok(()) |
| 1241 | }) |
| 1242 | } |
| 1243 | |
| 1244 | // ========================================================================= |
| 1245 | // Episodic Plane Methods (Phase 1 Substrate) |
| 1246 | // ========================================================================= |
| 1247 | |
| 1248 | pub fn create_session(&self, input: &CreateSessionInput) -> Result<CortexSession> { |
| 1249 | let id = input |
| 1250 | .id |
| 1251 | .clone() |
| 1252 | .unwrap_or_else(|| Uuid::new_v4().to_string()); |
| 1253 | let now = Utc::now().to_rfc3339(); |
| 1254 | let metadata_json = |
| 1255 | serde_json::to_string(&input.metadata).unwrap_or_else(|_| "{}".to_string()); |
| 1256 | let session = CortexSession { |
| 1257 | id: id.clone(), |
| 1258 | space_slug: input.space.clone(), |
| 1259 | agent_id: input.agent_id.clone(), |
| 1260 | world_id: input.world_id.clone(), |
| 1261 | parent_session_id: input.parent_session_id.clone(), |
| 1262 | fork_event_id: input.fork_event_id.clone(), |
| 1263 | created_at: now.clone(), |
| 1264 | closed_at: None, |
| 1265 | status: "active".to_string(), |
| 1266 | retention_class: input.retention_class.clone(), |
| 1267 | metadata: input.metadata.clone(), |
| 1268 | }; |
| 1269 | let input_clone = input.clone(); |
| 1270 | self.writer.execute(move |conn| { |
| 1271 | let _ = ensure_space_internal(conn, &input_clone.space)?; |
| 1272 | conn.execute( |
| 1273 | "INSERT INTO sessions (id, space_slug, agent_id, world_id, parent_session_id, fork_event_id, created_at, closed_at, status, retention_class, metadata_json) |
| 1274 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, 'active', ?8, ?9)", |
| 1275 | params![ |
| 1276 | id, |
| 1277 | input_clone.space, |
| 1278 | input_clone.agent_id, |
| 1279 | input_clone.world_id, |
| 1280 | input_clone.parent_session_id, |
| 1281 | input_clone.fork_event_id, |
| 1282 | now, |
| 1283 | input_clone.retention_class, |
| 1284 | metadata_json, |
| 1285 | ], |
| 1286 | )?; |
| 1287 | Ok(()) |
| 1288 | })?; |
| 1289 | Ok(session) |
| 1290 | } |
| 1291 | |
| 1292 | pub fn get_session(&self, session_id: &str) -> Result<Option<CortexSession>> { |
| 1293 | let conn = self.reader_pool.acquire()?; |
| 1294 | let mut stmt = conn.prepare( |
| 1295 | "SELECT id, space_slug, agent_id, world_id, parent_session_id, fork_event_id, created_at, closed_at, status, retention_class, metadata_json |
| 1296 | FROM sessions WHERE id = ?1" |
| 1297 | )?; |
| 1298 | let mut rows = stmt.query(params![session_id])?; |
| 1299 | if let Some(row) = rows.next()? { |
| 1300 | let metadata_str: String = row.get(10)?; |
| 1301 | let metadata: serde_json::Value = |
| 1302 | serde_json::from_str(&metadata_str).unwrap_or_else(|_| serde_json::json!({})); |
| 1303 | Ok(Some(CortexSession { |
| 1304 | id: row.get(0)?, |
| 1305 | space_slug: row.get(1)?, |
| 1306 | agent_id: row.get(2)?, |
| 1307 | world_id: row.get(3)?, |
| 1308 | parent_session_id: row.get(4)?, |
| 1309 | fork_event_id: row.get(5)?, |
| 1310 | created_at: row.get(6)?, |
| 1311 | closed_at: row.get(7)?, |
| 1312 | status: row.get(8)?, |
| 1313 | retention_class: row.get(9)?, |
| 1314 | metadata, |
| 1315 | })) |
| 1316 | } else { |
| 1317 | Ok(None) |
| 1318 | } |
| 1319 | } |
| 1320 | |
| 1321 | pub fn close_session(&self, session_id: &str) -> Result<()> { |
| 1322 | let now = Utc::now().to_rfc3339(); |
| 1323 | let sid = session_id.to_string(); |
| 1324 | self.writer.execute(move |conn| { |
| 1325 | conn.execute( |
| 1326 | "UPDATE sessions SET closed_at = ?1, status = 'closed' WHERE id = ?2", |
| 1327 | params![now, sid], |
| 1328 | )?; |
| 1329 | Ok(()) |
| 1330 | }) |
| 1331 | } |
| 1332 | |
| 1333 | pub fn append_session_event( |
| 1334 | &self, |
| 1335 | session_id: &str, |
| 1336 | input: &SessionEventInput, |
| 1337 | ) -> Result<CortexSessionEvent> { |
| 1338 | let branch = input.branch_id.as_deref().unwrap_or("main"); |
| 1339 | let results = self.batch_append_events(session_id, branch, std::slice::from_ref(input))?; |
| 1340 | results.into_iter().next().ok_or_else(|| { |
| 1341 | rusqlite::Error::SqliteFailure( |
| 1342 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_INTERNAL), |
| 1343 | Some("Failed to append event".to_string()), |
| 1344 | ) |
| 1345 | }) |
| 1346 | } |
| 1347 | |
| 1348 | pub fn batch_append_events( |
| 1349 | &self, |
| 1350 | session_id: &str, |
| 1351 | branch_id: &str, |
| 1352 | events: &[SessionEventInput], |
| 1353 | ) -> Result<Vec<CortexSessionEvent>> { |
| 1354 | let sid = session_id.to_string(); |
| 1355 | let bid = branch_id.to_string(); |
| 1356 | let input_events = events.to_vec(); |
| 1357 | let hmac_key = self.hmac_key.clone(); |
| 1358 | |
| 1359 | self.writer.execute(move |conn| { |
| 1360 | let tx = conn.transaction()?; |
| 1361 | |
| 1362 | // Verify session exists |
| 1363 | let session_exists: bool = tx.query_row( |
| 1364 | "SELECT EXISTS(SELECT 1 FROM sessions WHERE id = ?1)", |
| 1365 | params![sid], |
| 1366 | |r| r.get(0), |
| 1367 | )?; |
| 1368 | if !session_exists { |
| 1369 | return Err(rusqlite::Error::SqliteFailure( |
| 1370 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_NOTFOUND), |
| 1371 | Some(format!("Session {} not found", sid)), |
| 1372 | )); |
| 1373 | } |
| 1374 | |
| 1375 | // Get current max sequence for (session_id, branch_id) |
| 1376 | let mut current_seq: i64 = tx.query_row( |
| 1377 | "SELECT COALESCE(MAX(sequence), 0) FROM session_events WHERE session_id = ?1 AND branch_id = ?2", |
| 1378 | params![sid, bid], |
| 1379 | |r| r.get(0), |
| 1380 | )?; |
| 1381 | |
| 1382 | let mut inserted = Vec::with_capacity(input_events.len()); |
| 1383 | let now = Utc::now().to_rfc3339(); |
| 1384 | |
| 1385 | for ev in input_events { |
| 1386 | let event_branch = ev.branch_id.as_deref().unwrap_or(&bid).to_string(); |
| 1387 | |
| 1388 | // Idempotency check: if id is provided, check if event already exists |
| 1389 | if let Some(existing_id) = &ev.id { |
| 1390 | let mut check_stmt = tx.prepare( |
| 1391 | "SELECT id, session_id, sequence, branch_id, parent_event_id, event_type, role, content, payload_json, created_at, content_hash, sensitivity, redacted, segment_id |
| 1392 | FROM session_events WHERE id = ?1" |
| 1393 | )?; |
| 1394 | let mut rows = check_stmt.query(params![existing_id])?; |
| 1395 | if let Some(row) = rows.next()? { |
| 1396 | let payload_str: String = row.get(8)?; |
| 1397 | let payload: serde_json::Value = serde_json::from_str(&payload_str).unwrap_or_else(|_| serde_json::json!({})); |
| 1398 | let existing_ev = CortexSessionEvent { |
| 1399 | id: row.get(0)?, |
| 1400 | session_id: row.get(1)?, |
| 1401 | sequence: row.get(2)?, |
| 1402 | branch_id: row.get(3)?, |
| 1403 | parent_event_id: row.get(4)?, |
| 1404 | event_type: row.get(5)?, |
| 1405 | role: row.get(6)?, |
| 1406 | content: row.get(7)?, |
| 1407 | payload, |
| 1408 | created_at: row.get(9)?, |
| 1409 | content_hash: row.get(10)?, |
| 1410 | sensitivity: row.get(11)?, |
| 1411 | redacted: row.get::<_, i64>(12)? != 0, |
| 1412 | segment_id: row.get(13)?, |
| 1413 | }; |
| 1414 | inserted.push(existing_ev); |
| 1415 | continue; |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | current_seq += 1; |
| 1420 | let event_id = ev.id.unwrap_or_else(|| Uuid::new_v4().to_string()); |
| 1421 | let payload_json = serde_json::to_string(&ev.payload).unwrap_or_else(|_| "{}".to_string()); |
| 1422 | let raw_payload: serde_json::Value = serde_json::from_str(&payload_json).unwrap_or_else(|_| serde_json::json!({})); |
| 1423 | |
| 1424 | let sanitization = crate::security::SecurityMembrane::inspect_and_sanitize( |
| 1425 | ev.content.as_deref(), |
| 1426 | &raw_payload, |
| 1427 | ev.sensitivity.as_deref(), |
| 1428 | &hmac_key, |
| 1429 | ); |
| 1430 | let final_content = sanitization.sanitized_content; |
| 1431 | let final_sensitivity = sanitization.sensitivity; |
| 1432 | let final_payload = sanitization.sanitized_payload; |
| 1433 | let redacted = sanitization.redacted; |
| 1434 | let payload_json = serde_json::to_string(&final_payload).unwrap_or_else(|_| "{}".to_string()); |
| 1435 | |
| 1436 | let content_hash = compute_event_hash( |
| 1437 | &sid, |
| 1438 | &event_branch, |
| 1439 | current_seq, |
| 1440 | &ev.event_type, |
| 1441 | ev.role.as_deref(), |
| 1442 | final_content.as_deref(), |
| 1443 | &payload_json, |
| 1444 | ); |
| 1445 | |
| 1446 | tx.execute( |
| 1447 | "INSERT INTO session_events ( |
| 1448 | id, session_id, sequence, branch_id, parent_event_id, |
| 1449 | event_type, role, content, payload_json, created_at, |
| 1450 | content_hash, sensitivity, redacted, segment_id |
| 1451 | ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, NULL)", |
| 1452 | params![ |
| 1453 | event_id, |
| 1454 | sid, |
| 1455 | current_seq, |
| 1456 | event_branch, |
| 1457 | ev.parent_event_id, |
| 1458 | ev.event_type, |
| 1459 | ev.role, |
| 1460 | final_content, |
| 1461 | payload_json, |
| 1462 | now, |
| 1463 | content_hash, |
| 1464 | final_sensitivity, |
| 1465 | redacted as i64, |
| 1466 | ], |
| 1467 | )?; |
| 1468 | |
| 1469 | inserted.push(CortexSessionEvent { |
| 1470 | id: event_id, |
| 1471 | session_id: sid.clone(), |
| 1472 | sequence: current_seq, |
| 1473 | branch_id: event_branch, |
| 1474 | parent_event_id: ev.parent_event_id, |
| 1475 | event_type: ev.event_type, |
| 1476 | role: ev.role, |
| 1477 | content: final_content, |
| 1478 | payload: final_payload, |
| 1479 | created_at: now.clone(), |
| 1480 | content_hash, |
| 1481 | sensitivity: final_sensitivity, |
| 1482 | redacted, |
| 1483 | segment_id: None, |
| 1484 | }); |
| 1485 | } |
| 1486 | |
| 1487 | tx.commit()?; |
| 1488 | Ok(inserted) |
| 1489 | }) |
| 1490 | } |
| 1491 | |
| 1492 | pub fn get_session_events( |
| 1493 | &self, |
| 1494 | session_id: &str, |
| 1495 | branch_id: &str, |
| 1496 | after_seq: Option<i64>, |
| 1497 | limit: usize, |
| 1498 | ) -> Result<Vec<CortexSessionEvent>> { |
| 1499 | let conn = self.reader_pool.acquire()?; |
| 1500 | let after = after_seq.unwrap_or(0); |
| 1501 | let lim = limit.min(500); |
| 1502 | |
| 1503 | let mut stmt = conn.prepare( |
| 1504 | "SELECT id, session_id, sequence, branch_id, parent_event_id, event_type, role, content, payload_json, created_at, content_hash, sensitivity, redacted, segment_id |
| 1505 | FROM session_events |
| 1506 | WHERE session_id = ?1 AND branch_id = ?2 AND sequence > ?3 |
| 1507 | ORDER BY sequence ASC |
| 1508 | LIMIT ?4" |
| 1509 | )?; |
| 1510 | |
| 1511 | let rows = stmt.query_map(params![session_id, branch_id, after, lim as i64], |row| { |
| 1512 | let payload_str: String = row.get(8)?; |
| 1513 | let payload: serde_json::Value = |
| 1514 | serde_json::from_str(&payload_str).unwrap_or_else(|_| serde_json::json!({})); |
| 1515 | Ok(CortexSessionEvent { |
| 1516 | id: row.get(0)?, |
| 1517 | session_id: row.get(1)?, |
| 1518 | sequence: row.get(2)?, |
| 1519 | branch_id: row.get(3)?, |
| 1520 | parent_event_id: row.get(4)?, |
| 1521 | event_type: row.get(5)?, |
| 1522 | role: row.get(6)?, |
| 1523 | content: row.get(7)?, |
| 1524 | payload, |
| 1525 | created_at: row.get(9)?, |
| 1526 | content_hash: row.get(10)?, |
| 1527 | sensitivity: row.get(11)?, |
| 1528 | redacted: row.get::<_, i64>(12)? != 0, |
| 1529 | segment_id: row.get(13)?, |
| 1530 | }) |
| 1531 | })?; |
| 1532 | |
| 1533 | let mut events = Vec::new(); |
| 1534 | for r in rows { |
| 1535 | events.push(r?); |
| 1536 | } |
| 1537 | Ok(events) |
| 1538 | } |
| 1539 | |
| 1540 | pub fn get_recent_session_events( |
| 1541 | &self, |
| 1542 | session_id: &str, |
| 1543 | branch_id: &str, |
| 1544 | limit: usize, |
| 1545 | ) -> Result<Vec<CortexSessionEvent>> { |
| 1546 | let conn = self.reader_pool.acquire()?; |
| 1547 | let lim = limit.min(500); |
| 1548 | let mut stmt = conn.prepare( |
| 1549 | "SELECT id, session_id, sequence, branch_id, parent_event_id, event_type, role, content, payload_json, created_at, content_hash, sensitivity, redacted, segment_id |
| 1550 | FROM ( |
| 1551 | SELECT id, session_id, sequence, branch_id, parent_event_id, event_type, role, content, payload_json, created_at, content_hash, sensitivity, redacted, segment_id |
| 1552 | FROM session_events |
| 1553 | WHERE session_id = ?1 AND branch_id = ?2 |
| 1554 | ORDER BY sequence DESC |
| 1555 | LIMIT ?3 |
| 1556 | ) AS recent_events |
| 1557 | ORDER BY sequence ASC" |
| 1558 | )?; |
| 1559 | let rows = stmt.query_map(params![session_id, branch_id, lim as i64], |row| { |
| 1560 | let payload_str: String = row.get(8)?; |
| 1561 | let payload: serde_json::Value = |
| 1562 | serde_json::from_str(&payload_str).unwrap_or_else(|_| serde_json::json!({})); |
| 1563 | Ok(CortexSessionEvent { |
| 1564 | id: row.get(0)?, |
| 1565 | session_id: row.get(1)?, |
| 1566 | sequence: row.get(2)?, |
| 1567 | branch_id: row.get(3)?, |
| 1568 | parent_event_id: row.get(4)?, |
| 1569 | event_type: row.get(5)?, |
| 1570 | role: row.get(6)?, |
| 1571 | content: row.get(7)?, |
| 1572 | payload, |
| 1573 | created_at: row.get(9)?, |
| 1574 | content_hash: row.get(10)?, |
| 1575 | sensitivity: row.get(11)?, |
| 1576 | redacted: row.get::<_, i64>(12)? != 0, |
| 1577 | segment_id: row.get(13)?, |
| 1578 | }) |
| 1579 | })?; |
| 1580 | let mut events = Vec::new(); |
| 1581 | for r in rows { |
| 1582 | events.push(r?); |
| 1583 | } |
| 1584 | Ok(events) |
| 1585 | } |
| 1586 | |
| 1587 | pub fn get_watermark( |
| 1588 | &self, |
| 1589 | session_id: &str, |
| 1590 | kind: &str, |
| 1591 | version: &str, |
| 1592 | ) -> Result<Option<i64>> { |
| 1593 | let conn = self.reader_pool.acquire()?; |
| 1594 | let mut stmt = conn.prepare( |
| 1595 | "SELECT watermark_seq FROM processing_watermarks WHERE session_id = ?1 AND processor_kind = ?2 AND processor_version = ?3" |
| 1596 | )?; |
| 1597 | let mut rows = stmt.query(params![session_id, kind, version])?; |
| 1598 | if let Some(row) = rows.next()? { |
| 1599 | Ok(Some(row.get(0)?)) |
| 1600 | } else { |
| 1601 | Ok(None) |
| 1602 | } |
| 1603 | } |
| 1604 | |
| 1605 | pub fn set_watermark( |
| 1606 | &self, |
| 1607 | session_id: &str, |
| 1608 | kind: &str, |
| 1609 | version: &str, |
| 1610 | seq: i64, |
| 1611 | ) -> Result<()> { |
| 1612 | let sid = session_id.to_string(); |
| 1613 | let k = kind.to_string(); |
| 1614 | let v = version.to_string(); |
| 1615 | let now = Utc::now().to_rfc3339(); |
| 1616 | |
| 1617 | self.writer.execute(move |conn| { |
| 1618 | conn.execute( |
| 1619 | "INSERT INTO processing_watermarks (session_id, processor_kind, processor_version, watermark_seq, updated_at) |
| 1620 | VALUES (?1, ?2, ?3, ?4, ?5) |
| 1621 | ON CONFLICT(session_id, processor_kind, processor_version) DO UPDATE SET |
| 1622 | watermark_seq = excluded.watermark_seq, |
| 1623 | updated_at = excluded.updated_at", |
| 1624 | params![sid, k, v, seq, now], |
| 1625 | )?; |
| 1626 | Ok(()) |
| 1627 | }) |
| 1628 | } |
| 1629 | |
| 1630 | // ========================================================================= |
| 1631 | // Summaries, Candidates & Provenance (Phases 2 & 3) |
| 1632 | // ========================================================================= |
| 1633 | |
| 1634 | pub fn insert_session_summary(&self, input: &SessionSummaryWrite) -> Result<SessionSummary> { |
| 1635 | let id = Uuid::new_v4().to_string(); |
| 1636 | let now = Utc::now().to_rfc3339(); |
| 1637 | let sid = input.session_id.to_string(); |
| 1638 | let bid = input.branch_id.to_string(); |
| 1639 | let level = input.level; |
| 1640 | let start_seq = input.start_seq; |
| 1641 | let end_seq = input.end_seq; |
| 1642 | let text = input.summary_text.to_string(); |
| 1643 | let hash = input.source_hash.to_string(); |
| 1644 | let ver = input.processor_version.to_string(); |
| 1645 | |
| 1646 | let summary = SessionSummary { |
| 1647 | id: id.clone(), |
| 1648 | session_id: sid.clone(), |
| 1649 | branch_id: bid.clone(), |
| 1650 | level, |
| 1651 | start_seq, |
| 1652 | end_seq, |
| 1653 | summary_text: text.clone(), |
| 1654 | source_hash: hash.clone(), |
| 1655 | processor_version: ver.clone(), |
| 1656 | created_at: now.clone(), |
| 1657 | }; |
| 1658 | |
| 1659 | self.writer.execute(move |conn| { |
| 1660 | conn.execute( |
| 1661 | "INSERT INTO session_summaries ( |
| 1662 | id, session_id, branch_id, level, start_seq, end_seq, |
| 1663 | summary_text, source_hash, processor_version, created_at |
| 1664 | ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", |
| 1665 | params![id, sid, bid, level, start_seq, end_seq, text, hash, ver, now], |
| 1666 | )?; |
| 1667 | Ok(()) |
| 1668 | })?; |
| 1669 | |
| 1670 | Ok(summary) |
| 1671 | } |
| 1672 | |
| 1673 | pub fn get_session_summaries( |
| 1674 | &self, |
| 1675 | session_id: &str, |
| 1676 | branch_id: &str, |
| 1677 | max_level: Option<i64>, |
| 1678 | ) -> Result<Vec<SessionSummary>> { |
| 1679 | let conn = self.reader_pool.acquire()?; |
| 1680 | let ml = max_level.unwrap_or(10); |
| 1681 | let mut stmt = conn.prepare( |
| 1682 | "SELECT id, session_id, branch_id, level, start_seq, end_seq, summary_text, source_hash, processor_version, created_at |
| 1683 | FROM session_summaries |
| 1684 | WHERE session_id = ?1 AND branch_id = ?2 AND level <= ?3 |
| 1685 | ORDER BY level ASC, start_seq ASC" |
| 1686 | )?; |
| 1687 | |
| 1688 | let rows = stmt.query_map(params![session_id, branch_id, ml], |row| { |
| 1689 | Ok(SessionSummary { |
| 1690 | id: row.get(0)?, |
| 1691 | session_id: row.get(1)?, |
| 1692 | branch_id: row.get(2)?, |
| 1693 | level: row.get(3)?, |
| 1694 | start_seq: row.get(4)?, |
| 1695 | end_seq: row.get(5)?, |
| 1696 | summary_text: row.get(6)?, |
| 1697 | source_hash: row.get(7)?, |
| 1698 | processor_version: row.get(8)?, |
| 1699 | created_at: row.get(9)?, |
| 1700 | }) |
| 1701 | })?; |
| 1702 | |
| 1703 | let mut summaries = Vec::new(); |
| 1704 | for r in rows { |
| 1705 | summaries.push(r?); |
| 1706 | } |
| 1707 | Ok(summaries) |
| 1708 | } |
| 1709 | |
| 1710 | pub fn insert_memory_candidate(&self, input: &CandidateWriteInput) -> Result<MemoryCandidate> { |
| 1711 | let id = input |
| 1712 | .id |
| 1713 | .clone() |
| 1714 | .unwrap_or_else(|| Uuid::new_v4().to_string()); |
| 1715 | let now = Utc::now().to_rfc3339(); |
| 1716 | let tier = input |
| 1717 | .verification_tier |
| 1718 | .unwrap_or(VerificationTier::T0Direct); |
| 1719 | let tier_str = tier.as_str().to_string(); |
| 1720 | let obj_json = |
| 1721 | serde_json::to_string(&input.object_value).unwrap_or_else(|_| "{}".to_string()); |
| 1722 | let input_clone = input.clone(); |
| 1723 | let id_clone = id.clone(); |
| 1724 | let now_clone = now.clone(); |
| 1725 | |
| 1726 | self.writer.execute(move |conn| { |
| 1727 | let tx = conn.transaction()?; |
| 1728 | let _ = ensure_space_internal(&tx, &input_clone.space)?; |
| 1729 | |
| 1730 | tx.execute( |
| 1731 | "INSERT INTO memory_candidates ( |
| 1732 | id, space_slug, session_id, branch_id, memory_type, |
| 1733 | subject, predicate, object_value_json, scope, confidence, |
| 1734 | verification_tier, state, extractor_version, created_at |
| 1735 | ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'pending', ?12, ?13)", |
| 1736 | params![ |
| 1737 | id_clone, |
| 1738 | input_clone.space, |
| 1739 | input_clone.session_id, |
| 1740 | input_clone.branch_id, |
| 1741 | input_clone.memory_type, |
| 1742 | input_clone.subject, |
| 1743 | input_clone.predicate, |
| 1744 | obj_json, |
| 1745 | input_clone.scope, |
| 1746 | input_clone.confidence, |
| 1747 | tier_str, |
| 1748 | input_clone.extractor_version, |
| 1749 | now_clone, |
| 1750 | ], |
| 1751 | )?; |
| 1752 | |
| 1753 | for ev_id in &input_clone.evidence_ids { |
| 1754 | let commitment: String = tx |
| 1755 | .query_row( |
| 1756 | "SELECT content_hash FROM session_events WHERE id = ?1", |
| 1757 | params![ev_id], |
| 1758 | |row| row.get(0), |
| 1759 | ) |
| 1760 | .map_err(|_| { |
| 1761 | rusqlite::Error::SqliteFailure( |
| 1762 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CONSTRAINT), |
| 1763 | Some(format!( |
| 1764 | "evidence {} has no session event commitment", |
| 1765 | ev_id |
| 1766 | )), |
| 1767 | ) |
| 1768 | })?; |
| 1769 | if !crate::evidence::is_commitment(&commitment) { |
| 1770 | return Err(rusqlite::Error::SqliteFailure( |
| 1771 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CONSTRAINT), |
| 1772 | Some(format!("evidence {} commitment is not a digest", ev_id)), |
| 1773 | )); |
| 1774 | } |
| 1775 | tx.execute( |
| 1776 | "INSERT OR IGNORE INTO candidate_evidence (candidate_id, evidence_id, source_kind, evidence_hash) |
| 1777 | VALUES (?1, ?2, 'session_event', ?3)", |
| 1778 | params![id_clone, ev_id, commitment], |
| 1779 | )?; |
| 1780 | let record_id = Uuid::new_v4().to_string(); |
| 1781 | tx.execute( |
| 1782 | "INSERT INTO evidence_records (id, source_kind, source_id, commitment, merkle_root, segment_id, retention_class, retain_until, created_at) |
| 1783 | VALUES (?1, 'session_event', ?2, ?3, NULL, NULL, 'standard', ?4, ?5)", |
| 1784 | params![ |
| 1785 | record_id, |
| 1786 | ev_id, |
| 1787 | commitment, |
| 1788 | crate::evidence::retain_until("standard", Utc::now()), |
| 1789 | now_clone |
| 1790 | ], |
| 1791 | )?; |
| 1792 | } |
| 1793 | |
| 1794 | tx.commit()?; |
| 1795 | Ok(()) |
| 1796 | })?; |
| 1797 | |
| 1798 | Ok(MemoryCandidate { |
| 1799 | id, |
| 1800 | space_slug: input.space.clone(), |
| 1801 | session_id: input.session_id.clone(), |
| 1802 | branch_id: input.branch_id.clone(), |
| 1803 | memory_type: input.memory_type.clone(), |
| 1804 | subject: input.subject.clone(), |
| 1805 | predicate: input.predicate.clone(), |
| 1806 | object_value: input.object_value.clone(), |
| 1807 | scope: input.scope.clone(), |
| 1808 | confidence: input.confidence, |
| 1809 | verification_tier: tier, |
| 1810 | state: "pending".to_string(), |
| 1811 | extractor_version: input.extractor_version.clone(), |
| 1812 | created_at: now, |
| 1813 | evidence_ids: input.evidence_ids.clone(), |
| 1814 | }) |
| 1815 | } |
| 1816 | |
| 1817 | pub fn get_memory_candidates( |
| 1818 | &self, |
| 1819 | space: Option<&str>, |
| 1820 | state: Option<&str>, |
| 1821 | limit: usize, |
| 1822 | ) -> Result<Vec<MemoryCandidate>> { |
| 1823 | let conn = self.reader_pool.acquire()?; |
| 1824 | let target_space = space.unwrap_or("atlas-memory"); |
| 1825 | let lim = limit.min(100); |
| 1826 | |
| 1827 | let query_sql = if state.is_some() { |
| 1828 | "SELECT id, space_slug, session_id, branch_id, memory_type, subject, predicate, object_value_json, scope, confidence, verification_tier, state, extractor_version, created_at |
| 1829 | FROM memory_candidates |
| 1830 | WHERE space_slug = ?1 AND state = ?2 |
| 1831 | ORDER BY created_at DESC LIMIT ?3" |
| 1832 | } else { |
| 1833 | "SELECT id, space_slug, session_id, branch_id, memory_type, subject, predicate, object_value_json, scope, confidence, verification_tier, state, extractor_version, created_at |
| 1834 | FROM memory_candidates |
| 1835 | WHERE space_slug = ?1 |
| 1836 | ORDER BY created_at DESC LIMIT ?3" |
| 1837 | }; |
| 1838 | |
| 1839 | let mut stmt = conn.prepare(query_sql)?; |
| 1840 | let mut candidates = Vec::new(); |
| 1841 | |
| 1842 | let mut rows = if let Some(st) = state { |
| 1843 | stmt.query(params![target_space, st, lim as i64])? |
| 1844 | } else { |
| 1845 | stmt.query(params![target_space, lim as i64])? |
| 1846 | }; |
| 1847 | |
| 1848 | while let Some(row) = rows.next()? { |
| 1849 | let cid: String = row.get(0)?; |
| 1850 | let obj_str: String = row.get(7)?; |
| 1851 | let obj_val: serde_json::Value = |
| 1852 | serde_json::from_str(&obj_str).unwrap_or_else(|_| serde_json::json!({})); |
| 1853 | let tier_str: String = row.get(10)?; |
| 1854 | let tier = VerificationTier::from_str_opt(&tier_str); |
| 1855 | |
| 1856 | // Fetch evidence IDs |
| 1857 | let mut ev_stmt = |
| 1858 | conn.prepare("SELECT evidence_id FROM candidate_evidence WHERE candidate_id = ?1")?; |
| 1859 | let ev_rows = ev_stmt.query_map(params![cid], |r| r.get(0))?; |
| 1860 | let mut evidence_ids = Vec::new(); |
| 1861 | for e in ev_rows { |
| 1862 | evidence_ids.push(e?); |
| 1863 | } |
| 1864 | |
| 1865 | candidates.push(MemoryCandidate { |
| 1866 | id: cid, |
| 1867 | space_slug: row.get(1)?, |
| 1868 | session_id: row.get(2)?, |
| 1869 | branch_id: row.get(3)?, |
| 1870 | memory_type: row.get(4)?, |
| 1871 | subject: row.get(5)?, |
| 1872 | predicate: row.get(6)?, |
| 1873 | object_value: obj_val, |
| 1874 | scope: row.get(8)?, |
| 1875 | confidence: row.get(9)?, |
| 1876 | verification_tier: tier, |
| 1877 | state: row.get(11)?, |
| 1878 | extractor_version: row.get(12)?, |
| 1879 | created_at: row.get(13)?, |
| 1880 | evidence_ids, |
| 1881 | }); |
| 1882 | } |
| 1883 | |
| 1884 | Ok(candidates) |
| 1885 | } |
| 1886 | |
| 1887 | pub fn get_candidate_by_id(&self, candidate_id: &str) -> Result<Option<MemoryCandidate>> { |
| 1888 | let conn = self.reader_pool.acquire()?; |
| 1889 | let mut stmt = conn.prepare( |
| 1890 | "SELECT id, space_slug, session_id, branch_id, memory_type, subject, predicate, object_value_json, scope, confidence, verification_tier, state, extractor_version, created_at |
| 1891 | FROM memory_candidates |
| 1892 | WHERE id = ?1" |
| 1893 | )?; |
| 1894 | let mut rows = stmt.query(params![candidate_id])?; |
| 1895 | if let Some(row) = rows.next()? { |
| 1896 | let cid: String = row.get(0)?; |
| 1897 | let obj_str: String = row.get(7)?; |
| 1898 | let obj_val: serde_json::Value = |
| 1899 | serde_json::from_str(&obj_str).unwrap_or_else(|_| serde_json::json!({})); |
| 1900 | let tier_str: String = row.get(10)?; |
| 1901 | let tier = VerificationTier::from_str_opt(&tier_str); |
| 1902 | |
| 1903 | let mut ev_stmt = |
| 1904 | conn.prepare("SELECT evidence_id FROM candidate_evidence WHERE candidate_id = ?1")?; |
| 1905 | let ev_rows = ev_stmt.query_map(params![cid], |r| r.get(0))?; |
| 1906 | let mut evidence_ids = Vec::new(); |
| 1907 | for e in ev_rows { |
| 1908 | evidence_ids.push(e?); |
| 1909 | } |
| 1910 | |
| 1911 | Ok(Some(MemoryCandidate { |
| 1912 | id: cid, |
| 1913 | space_slug: row.get(1)?, |
| 1914 | session_id: row.get(2)?, |
| 1915 | branch_id: row.get(3)?, |
| 1916 | memory_type: row.get(4)?, |
| 1917 | subject: row.get(5)?, |
| 1918 | predicate: row.get(6)?, |
| 1919 | object_value: obj_val, |
| 1920 | scope: row.get(8)?, |
| 1921 | confidence: row.get(9)?, |
| 1922 | verification_tier: tier, |
| 1923 | state: row.get(11)?, |
| 1924 | extractor_version: row.get(12)?, |
| 1925 | created_at: row.get(13)?, |
| 1926 | evidence_ids, |
| 1927 | })) |
| 1928 | } else { |
| 1929 | Ok(None) |
| 1930 | } |
| 1931 | } |
| 1932 | |
| 1933 | pub fn update_candidate_state(&self, candidate_id: &str, new_state: &str) -> Result<()> { |
| 1934 | let cid = candidate_id.to_string(); |
| 1935 | let st = new_state.to_string(); |
| 1936 | self.writer.execute(move |conn| { |
| 1937 | conn.execute( |
| 1938 | "UPDATE memory_candidates SET state = ?1 WHERE id = ?2", |
| 1939 | params![st, cid], |
| 1940 | )?; |
| 1941 | Ok(()) |
| 1942 | }) |
| 1943 | } |
| 1944 | |
| 1945 | pub fn promote_candidate(&self, input: &PromoteCandidateInput) -> Result<PromotionReceipt> { |
| 1946 | let cid = input.candidate_id.clone(); |
| 1947 | let policy_id = input |
| 1948 | .policy_id |
| 1949 | .clone() |
| 1950 | .unwrap_or_else(|| "default-policy-v1".to_string()); |
| 1951 | let verifier_receipt = input.verifier_receipt.clone(); |
| 1952 | |
| 1953 | self.writer.execute(move |conn| { |
| 1954 | let tx = conn.transaction()?; |
| 1955 | |
| 1956 | // 1. Fetch candidate |
| 1957 | let mut stmt = tx.prepare( |
| 1958 | "SELECT id, space_slug, memory_type, subject, predicate, object_value_json, scope, confidence, verification_tier, state |
| 1959 | FROM memory_candidates WHERE id = ?1" |
| 1960 | )?; |
| 1961 | let mut rows = stmt.query(params![cid])?; |
| 1962 | let (space_slug, mem_type, subject, predicate, obj_json, scope, confidence, tier_str, state): ( |
| 1963 | String, String, String, String, String, String, f64, String, String |
| 1964 | ) = if let Some(r) = rows.next()? { |
| 1965 | ( |
| 1966 | r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, |
| 1967 | r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)? |
| 1968 | ) |
| 1969 | } else { |
| 1970 | return Err(rusqlite::Error::SqliteFailure( |
| 1971 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_NOTFOUND), |
| 1972 | Some(format!("Candidate {} not found", cid)), |
| 1973 | )); |
| 1974 | }; |
| 1975 | drop(rows); |
| 1976 | drop(stmt); |
| 1977 | |
| 1978 | if state == "promoted" { |
| 1979 | return Err(rusqlite::Error::SqliteFailure( |
| 1980 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CONSTRAINT), |
| 1981 | Some("Candidate already promoted".to_string()), |
| 1982 | )); |
| 1983 | } |
| 1984 | |
| 1985 | let (evidence_ids, evidence_hashes): (Vec<String>, Vec<String>) = { |
| 1986 | let mut ev_stmt = tx.prepare( |
| 1987 | "SELECT evidence_id, evidence_hash FROM candidate_evidence WHERE candidate_id = ?1", |
| 1988 | )?; |
| 1989 | let rows = ev_stmt.query_map(params![cid], |row| { |
| 1990 | Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) |
| 1991 | })?; |
| 1992 | let mut ids = Vec::new(); |
| 1993 | let mut hashes = Vec::new(); |
| 1994 | for row in rows { |
| 1995 | let (id, hash) = row?; |
| 1996 | ids.push(id); |
| 1997 | hashes.push(hash); |
| 1998 | } |
| 1999 | (ids, hashes) |
| 2000 | }; |
| 2001 | if evidence_hashes |
| 2002 | .iter() |
| 2003 | .any(|hash| !crate::evidence::is_commitment(hash)) |
| 2004 | { |
| 2005 | return Err(rusqlite::Error::SqliteFailure( |
| 2006 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CONSTRAINT), |
| 2007 | Some("promotion refused: evidence commitment missing".to_string()), |
| 2008 | )); |
| 2009 | } |
| 2010 | let tier = VerificationTier::from_str_opt(&tier_str); |
| 2011 | let policy_candidate = MemoryCandidate { |
| 2012 | id: cid.clone(), |
| 2013 | space_slug: space_slug.clone(), |
| 2014 | session_id: String::new(), |
| 2015 | branch_id: String::new(), |
| 2016 | memory_type: mem_type.clone(), |
| 2017 | subject: subject.clone(), |
| 2018 | predicate: predicate.clone(), |
| 2019 | object_value: serde_json::from_str(&obj_json).unwrap_or_else(|_| serde_json::json!({})), |
| 2020 | scope: scope.clone(), |
| 2021 | confidence, |
| 2022 | verification_tier: tier, |
| 2023 | state: state.clone(), |
| 2024 | extractor_version: String::new(), |
| 2025 | created_at: String::new(), |
| 2026 | evidence_ids, |
| 2027 | }; |
| 2028 | if let Err(reason) = crate::promotion::enforce_promotion_policy(&policy_candidate) { |
| 2029 | return Err(rusqlite::Error::SqliteFailure( |
| 2030 | rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CONSTRAINT), |
| 2031 | Some(reason), |
| 2032 | )); |
| 2033 | } |
| 2034 | |
| 2035 | let now = Utc::now().to_rfc3339(); |
| 2036 | let space_id = ensure_space_internal(&tx, &space_slug)?; |
| 2037 | |
| 2038 | // 2. Resolve subject entity (find existing by canonical_name in space, or insert entity shell) |
| 2039 | let subject_entity_id: String = { |
| 2040 | let mut ent_stmt = tx.prepare( |
| 2041 | "SELECT id FROM entities WHERE space_slug = ?1 AND canonical_name = ?2", |
| 2042 | )?; |
| 2043 | let mut ent_rows = ent_stmt.query(params![space_slug, subject])?; |
| 2044 | if let Some(r) = ent_rows.next()? { |
| 2045 | r.get(0)? |
| 2046 | } else { |
| 2047 | drop(ent_rows); |
| 2048 | drop(ent_stmt); |
| 2049 | let new_ent_id = Uuid::new_v4().to_string(); |
| 2050 | tx.execute( |
| 2051 | "INSERT INTO entities (id, space_id, space_slug, entity_type, canonical_name, content, aliases_json, metadata_json, confidence, revision, retracted, valid_from, valid_to, created_at) |
| 2052 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, '[]', '{}', 1.0, 1, 0, ?7, NULL, ?7)", |
| 2053 | params![ |
| 2054 | new_ent_id, |
| 2055 | space_id, |
| 2056 | space_slug, |
| 2057 | mem_type, |
| 2058 | subject, |
| 2059 | format!("Canonical entity for {}", subject), |
| 2060 | now |
| 2061 | ], |
| 2062 | )?; |
| 2063 | tx.execute( |
| 2064 | "INSERT INTO entities_fts (id, canonical_name, content, space_slug) VALUES (?1, ?2, ?3, ?4)", |
| 2065 | params![new_ent_id, subject, subject, space_slug], |
| 2066 | )?; |
| 2067 | new_ent_id |
| 2068 | } |
| 2069 | }; |
| 2070 | |
| 2071 | // 3. Contradiction & Temporal Supersession: |
| 2072 | // Check if active claim exists with same (subject, predicate) |
| 2073 | { |
| 2074 | let mut claim_check = tx.prepare( |
| 2075 | "SELECT id FROM claims WHERE subject_entity_id = ?1 AND predicate = ?2 AND retracted = 0", |
| 2076 | )?; |
| 2077 | let mut existing_claim_rows = |
| 2078 | claim_check.query(params![subject_entity_id, predicate])?; |
| 2079 | if let Some(r) = existing_claim_rows.next()? { |
| 2080 | let old_claim_id: String = r.get(0)?; |
| 2081 | drop(existing_claim_rows); |
| 2082 | drop(claim_check); |
| 2083 | // Temporal supersession: close old claim |
| 2084 | tx.execute( |
| 2085 | "UPDATE claims SET retracted = 1, status = 'superseded' WHERE id = ?1", |
| 2086 | params![old_claim_id], |
| 2087 | )?; |
| 2088 | } |
| 2089 | } |
| 2090 | |
| 2091 | // 4. Insert new promoted canonical claim |
| 2092 | let claim_id = Uuid::new_v4().to_string(); |
| 2093 | tx.execute( |
| 2094 | "INSERT INTO claims (id, space_id, space_slug, subject_entity_id, predicate, object_entity_id, literal_value_json, confidence, metadata_json, retracted, created_at, verification_tier, status) |
| 2095 | VALUES (?1, ?2, ?3, ?4, ?5, NULL, ?6, ?7, ?8, 0, ?9, ?10, 'active')", |
| 2096 | params![ |
| 2097 | claim_id, |
| 2098 | space_id, |
| 2099 | space_slug, |
| 2100 | subject_entity_id, |
| 2101 | predicate, |
| 2102 | obj_json, |
| 2103 | confidence, |
| 2104 | serde_json::json!({"scope": scope, "promoted_from_candidate": cid, "tier": tier.as_str()}).to_string(), |
| 2105 | now, |
| 2106 | tier.as_str(), |
| 2107 | ], |
| 2108 | )?; |
| 2109 | |
| 2110 | // 5. Transfer evidence to claim_evidence |
| 2111 | let evidence_items: Vec<(String, String, String)> = { |
| 2112 | let mut ev_query = tx.prepare( |
| 2113 | "SELECT evidence_id, source_kind, evidence_hash FROM candidate_evidence WHERE candidate_id = ?1", |
| 2114 | )?; |
| 2115 | let ev_rows = ev_query.query_map(params![cid], |r| { |
| 2116 | Ok(( |
| 2117 | r.get::<_, String>(0)?, |
| 2118 | r.get::<_, String>(1)?, |
| 2119 | r.get::<_, String>(2)?, |
| 2120 | )) |
| 2121 | })?; |
| 2122 | let mut items = Vec::new(); |
| 2123 | for e in ev_rows { |
| 2124 | items.push(e?); |
| 2125 | } |
| 2126 | items |
| 2127 | }; |
| 2128 | |
| 2129 | for (ev_id, kind, hash) in evidence_items { |
| 2130 | tx.execute( |
| 2131 | "INSERT OR IGNORE INTO claim_evidence (claim_id, evidence_id, source_kind, evidence_hash) |
| 2132 | VALUES (?1, ?2, ?3, ?4)", |
| 2133 | params![claim_id, ev_id, kind, hash], |
| 2134 | )?; |
| 2135 | } |
| 2136 | |
| 2137 | // 6. Insert promotion receipt |
| 2138 | let receipt_id = Uuid::new_v4().to_string(); |
| 2139 | tx.execute( |
| 2140 | "INSERT INTO promotion_receipts (id, candidate_id, claim_id, policy_id, policy_version, achieved_tier, verifier_receipt, promoted_at) |
| 2141 | VALUES (?1, ?2, ?3, ?4, '1.0', ?5, ?6, ?7)", |
| 2142 | params![ |
| 2143 | receipt_id, |
| 2144 | cid, |
| 2145 | claim_id, |
| 2146 | policy_id, |
| 2147 | tier.as_str(), |
| 2148 | verifier_receipt, |
| 2149 | now, |
| 2150 | ], |
| 2151 | )?; |
| 2152 | |
| 2153 | // 7. Mark candidate promoted |
| 2154 | tx.execute( |
| 2155 | "UPDATE memory_candidates SET state = 'promoted' WHERE id = ?1", |
| 2156 | params![cid], |
| 2157 | )?; |
| 2158 | |
| 2159 | tx.commit()?; |
| 2160 | |
| 2161 | Ok(PromotionReceipt { |
| 2162 | id: receipt_id, |
| 2163 | candidate_id: cid, |
| 2164 | claim_id, |
| 2165 | policy_id, |
| 2166 | policy_version: "1.0".to_string(), |
| 2167 | achieved_tier: tier.as_str().to_string(), |
| 2168 | verifier_receipt, |
| 2169 | promoted_at: now, |
| 2170 | }) |
| 2171 | }) |
| 2172 | } |
| 2173 | |
| 2174 | pub fn seal_open_segment( |
| 2175 | &self, |
| 2176 | session_id: &str, |
| 2177 | branch_id: &str, |
| 2178 | ) -> Result<Option<EventSegment>> { |
| 2179 | let sid = session_id.to_string(); |
| 2180 | let bid = branch_id.to_string(); |
| 2181 | self.writer.execute(move |conn| { |
| 2182 | let mut stmt = conn.prepare( |
| 2183 | "SELECT id, content_hash, sequence FROM session_events |
| 2184 | WHERE session_id = ?1 AND branch_id = ?2 AND segment_id IS NULL |
| 2185 | ORDER BY sequence ASC", |
| 2186 | )?; |
| 2187 | let rows = stmt.query_map(params![sid, bid], |row| { |
| 2188 | Ok(( |
| 2189 | row.get::<_, String>(0)?, |
| 2190 | row.get::<_, String>(1)?, |
| 2191 | row.get::<_, i64>(2)?, |
| 2192 | )) |
| 2193 | })?; |
| 2194 | let mut leaves = Vec::new(); |
| 2195 | for row in rows { |
| 2196 | leaves.push(row?); |
| 2197 | } |
| 2198 | drop(stmt); |
| 2199 | if leaves.is_empty() { |
| 2200 | return Ok(None); |
| 2201 | } |
| 2202 | let start_seq = leaves[0].2; |
| 2203 | let end_seq = leaves[leaves.len() - 1].2; |
| 2204 | let root = crate::evidence::merkle_root( |
| 2205 | &leaves |
| 2206 | .iter() |
| 2207 | .map(|(_, hash, _)| hash.as_bytes()) |
| 2208 | .collect::<Vec<_>>(), |
| 2209 | ); |
| 2210 | let prev: Option<String> = conn |
| 2211 | .query_row( |
| 2212 | "SELECT merkle_root FROM event_segments WHERE session_id = ?1 AND branch_id = ?2 ORDER BY end_seq DESC LIMIT 1", |
| 2213 | params![sid, bid], |
| 2214 | |row| row.get(0), |
| 2215 | ) |
| 2216 | .ok(); |
| 2217 | let retention: String = conn |
| 2218 | .query_row( |
| 2219 | "SELECT retention_class FROM sessions WHERE id = ?1", |
| 2220 | params![sid], |
| 2221 | |row| row.get(0), |
| 2222 | ) |
| 2223 | .unwrap_or_else(|_| "standard".to_string()); |
| 2224 | let now = Utc::now().to_rfc3339(); |
| 2225 | let segment_id = Uuid::new_v4().to_string(); |
| 2226 | conn.execute( |
| 2227 | "INSERT INTO event_segments (id, session_id, branch_id, start_seq, end_seq, merkle_root, prev_segment_root, sealed_at, state) |
| 2228 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'sealed')", |
| 2229 | params![segment_id, sid, bid, start_seq, end_seq, root, prev, now], |
| 2230 | )?; |
| 2231 | for (event_id, _, _) in &leaves { |
| 2232 | conn.execute( |
| 2233 | "UPDATE session_events SET segment_id = ?1 WHERE id = ?2", |
| 2234 | params![segment_id, event_id], |
| 2235 | )?; |
| 2236 | } |
| 2237 | let record_id = Uuid::new_v4().to_string(); |
| 2238 | conn.execute( |
| 2239 | "INSERT INTO evidence_records (id, source_kind, source_id, commitment, merkle_root, segment_id, retention_class, retain_until, created_at) |
| 2240 | VALUES (?1, 'event_segment', ?2, ?3, ?3, ?2, ?4, ?5, ?6)", |
| 2241 | params![ |
| 2242 | record_id, |
| 2243 | segment_id, |
| 2244 | root, |
| 2245 | retention, |
| 2246 | crate::evidence::retain_until(&retention, Utc::now()), |
| 2247 | now |
| 2248 | ], |
| 2249 | )?; |
| 2250 | Ok(Some(EventSegment { |
| 2251 | id: segment_id, |
| 2252 | session_id: sid, |
| 2253 | branch_id: bid, |
| 2254 | start_seq, |
| 2255 | end_seq, |
| 2256 | merkle_root: root, |
| 2257 | prev_segment_root: prev, |
| 2258 | sealed_at: now, |
| 2259 | state: "sealed".to_string(), |
| 2260 | })) |
| 2261 | }) |
| 2262 | } |
| 2263 | |
| 2264 | pub fn apply_retention(&self, now: &str) -> Result<usize> { |
| 2265 | let now_owned = now.to_string(); |
| 2266 | self.writer.execute(move |conn| { |
| 2267 | let mut stmt = conn.prepare( |
| 2268 | "SELECT id, retention_class, created_at FROM sessions WHERE retention_class != 'permanent'", |
| 2269 | )?; |
| 2270 | let sessions: Vec<(String, String, String)> = stmt |
| 2271 | .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))? |
| 2272 | .collect::<Result<Vec<_>>>()?; |
| 2273 | drop(stmt); |
| 2274 | let mut purged = 0usize; |
| 2275 | for (sid, class, created_at) in sessions { |
| 2276 | let expired = match class.as_str() { |
| 2277 | "ephemeral" => created_at < shift_back(&now_owned, 1), |
| 2278 | _ => created_at < shift_back(&now_owned, 365), |
| 2279 | }; |
| 2280 | if !expired { |
| 2281 | continue; |
| 2282 | } |
| 2283 | let changed = conn.execute( |
| 2284 | "UPDATE session_events SET content = NULL, payload_json = '{\"redacted\":true}', redacted = 1 |
| 2285 | WHERE session_id = ?1 AND redacted = 0", |
| 2286 | params![sid], |
| 2287 | )?; |
| 2288 | purged += changed; |
| 2289 | } |
| 2290 | let changed = conn.execute( |
| 2291 | "UPDATE session_events SET content = NULL, payload_json = '{\"redacted\":true}', redacted = 1 |
| 2292 | WHERE id IN ( |
| 2293 | SELECT source_id FROM evidence_records |
| 2294 | WHERE source_kind = 'session_event' AND retain_until IS NOT NULL AND retain_until < ?1 |
| 2295 | ) AND redacted = 0", |
| 2296 | params![now_owned], |
| 2297 | )?; |
| 2298 | purged += changed; |
| 2299 | Ok(purged) |
| 2300 | }) |
| 2301 | } |
| 2302 | } |
| 2303 | |
| 2304 | #[cfg(test)] |
| 2305 | mod tests { |
| 2306 | use super::*; |
| 2307 | use std::sync::Arc; |
| 2308 | use std::thread; |
| 2309 | |
| 2310 | #[test] |
| 2311 | fn test_in_memory_db_crud() { |
| 2312 | let db = Database::open_in_memory().expect("open in memory"); |
| 2313 | |
| 2314 | let input = EntityWriteInput { |
| 2315 | id: None, |
| 2316 | space: "atlas-memory".to_string(), |
| 2317 | entity_type: "discovery".to_string(), |
| 2318 | canonical_name: "test_cortex_rebuild".to_string(), |
| 2319 | content: "Testing the native Rust cortex-rs database engine".to_string(), |
| 2320 | aliases: vec!["cortex_test".to_string()], |
| 2321 | metadata: serde_json::json!({"test": true}), |
| 2322 | confidence: 1.0, |
| 2323 | valid_from: None, |
| 2324 | valid_to: None, |
| 2325 | external_id: None, |
| 2326 | }; |
| 2327 | |
| 2328 | let dummy_emb = vec![0.5f32; 768]; |
| 2329 | let receipt = db |
| 2330 | .upsert_entity(&input, Some(&dummy_emb)) |
| 2331 | .expect("upsert entity"); |
| 2332 | assert_eq!(receipt.operation, "entity.upsert"); |
| 2333 | |
| 2334 | let fetched = db |
| 2335 | .get_entity("test_cortex_rebuild", Some("atlas-memory")) |
| 2336 | .expect("get entity"); |
| 2337 | assert!(fetched.is_some()); |
| 2338 | let entity = fetched.unwrap(); |
| 2339 | assert_eq!(entity.canonical_name, "test_cortex_rebuild"); |
| 2340 | assert_eq!(entity.aliases.len(), 1); |
| 2341 | |
| 2342 | let search_results = db |
| 2343 | .search_entities("Rust", Some("atlas-memory"), 10) |
| 2344 | .expect("search"); |
| 2345 | assert!(!search_results.is_empty()); |
| 2346 | assert_eq!( |
| 2347 | search_results[0].entity.canonical_name, |
| 2348 | "test_cortex_rebuild" |
| 2349 | ); |
| 2350 | |
| 2351 | let recall_results = db |
| 2352 | .recall_entities("Rust", Some(&dummy_emb), Some("atlas-memory"), 5) |
| 2353 | .expect("recall"); |
| 2354 | assert!(!recall_results.is_empty()); |
| 2355 | assert!(recall_results[0].final_score > 0.5); |
| 2356 | } |
| 2357 | |
| 2358 | #[test] |
| 2359 | fn test_sqlite_wal_persistence_under_concurrency() { |
| 2360 | let temp_dir = std::env::temp_dir().join(format!("cortex_wal_test_{}", Uuid::new_v4())); |
| 2361 | let _ = std::fs::create_dir_all(&temp_dir); |
| 2362 | let db_path = temp_dir.join("cortex.db"); |
| 2363 | |
| 2364 | // Open database in WAL mode |
| 2365 | let db = Arc::new(Database::open(&db_path).expect("open wal db")); |
| 2366 | |
| 2367 | // Verify WAL mode is active |
| 2368 | { |
| 2369 | let conn = db.conn.lock().unwrap(); |
| 2370 | let mode: String = conn |
| 2371 | .query_row("PRAGMA journal_mode", [], |r| r.get(0)) |
| 2372 | .unwrap(); |
| 2373 | assert_eq!(mode.to_lowercase(), "wal"); |
| 2374 | } |
| 2375 | |
| 2376 | let mut handles = Vec::new(); |
| 2377 | |
| 2378 | // Spawn 4 concurrent writer threads |
| 2379 | for t in 0..4 { |
| 2380 | let db_clone = Arc::clone(&db); |
| 2381 | handles.push(thread::spawn(move || { |
| 2382 | for i in 0..10 { |
| 2383 | let input = EntityWriteInput { |
| 2384 | id: None, |
| 2385 | space: "atlas-memory".to_string(), |
| 2386 | entity_type: "concurrent_write".to_string(), |
| 2387 | canonical_name: format!("entity_t{}_i{}", t, i), |
| 2388 | content: format!("Content from thread {} iteration {}", t, i), |
| 2389 | aliases: vec![format!("alias_t{}_i{}", t, i)], |
| 2390 | metadata: serde_json::json!({"thread": t, "iter": i}), |
| 2391 | confidence: 0.95, |
| 2392 | valid_from: None, |
| 2393 | valid_to: None, |
| 2394 | external_id: None, |
| 2395 | }; |
| 2396 | let receipt = db_clone |
| 2397 | .upsert_entity(&input, None) |
| 2398 | .expect("concurrent entity upsert"); |
| 2399 | assert_eq!(receipt.operation, "entity.upsert"); |
| 2400 | |
| 2401 | // Also write a claim |
| 2402 | let claim_input = ClaimWriteInput { |
| 2403 | id: None, |
| 2404 | space: "atlas-memory".to_string(), |
| 2405 | subject_entity_id: receipt.target_id.clone(), |
| 2406 | predicate: "authored_by".to_string(), |
| 2407 | object_entity_id: None, |
| 2408 | literal_value: Some(serde_json::json!(format!("worker_thread_{}", t))), |
| 2409 | confidence: 1.0, |
| 2410 | metadata: serde_json::json!({}), |
| 2411 | }; |
| 2412 | let claim_receipt = db_clone |
| 2413 | .upsert_claim(&claim_input) |
| 2414 | .expect("concurrent claim upsert"); |
| 2415 | assert_eq!(claim_receipt.operation, "claim.upsert"); |
| 2416 | } |
| 2417 | })); |
| 2418 | } |
| 2419 | |
| 2420 | // Spawn 4 concurrent reader threads |
| 2421 | for _ in 0..4 { |
| 2422 | let db_clone = Arc::clone(&db); |
| 2423 | handles.push(thread::spawn(move || { |
| 2424 | for _ in 0..15 { |
| 2425 | let _ = db_clone.search_entities("Content", Some("atlas-memory"), 10); |
| 2426 | let _ = db_clone.recall_entities("thread", None, Some("atlas-memory"), 5); |
| 2427 | let _ = db_clone.get_entity("entity_t0_i0", Some("atlas-memory")); |
| 2428 | thread::sleep(std::time::Duration::from_millis(2)); |
| 2429 | } |
| 2430 | })); |
| 2431 | } |
| 2432 | |
| 2433 | // Wait for all threads to join |
| 2434 | for h in handles { |
| 2435 | h.join().expect("thread join"); |
| 2436 | } |
| 2437 | |
| 2438 | // Close db by dropping Arc |
| 2439 | drop(db); |
| 2440 | |
| 2441 | // Re-open from disk to verify cold-start WAL recovery and persistence |
| 2442 | let reopened = Database::open(&db_path).expect("reopen wal db"); |
| 2443 | for t in 0..4 { |
| 2444 | for i in 0..10 { |
| 2445 | let name = format!("entity_t{}_i{}", t, i); |
| 2446 | let ent = reopened |
| 2447 | .get_entity(&name, Some("atlas-memory")) |
| 2448 | .expect("get persisted entity"); |
| 2449 | assert!( |
| 2450 | ent.is_some(), |
| 2451 | "Entity {} must persist across restarts", |
| 2452 | name |
| 2453 | ); |
| 2454 | let e = ent.unwrap(); |
| 2455 | assert_eq!(e.canonical_name, name); |
| 2456 | assert_eq!( |
| 2457 | e.content, |
| 2458 | format!("Content from thread {} iteration {}", t, i) |
| 2459 | ); |
| 2460 | } |
| 2461 | } |
| 2462 | |
| 2463 | let _ = std::fs::remove_dir_all(&temp_dir); |
| 2464 | } |
| 2465 | |
| 2466 | #[test] |
| 2467 | fn test_fts5_exact_prefix_boolean_and_ranking() { |
| 2468 | let db = Database::open_in_memory().expect("open in memory db"); |
| 2469 | |
| 2470 | let items = vec![ |
| 2471 | ( |
| 2472 | "NVFP4_Loader", |
| 2473 | "High throughput native NVFP4 checkpoint loader for vLLM and MAX", |
| 2474 | "discovery", |
| 2475 | ), |
| 2476 | ( |
| 2477 | "Qwen3_Parser", |
| 2478 | "Llama cpp tokenizer and grammar parser for Qwen3 models", |
| 2479 | "learned_procedure", |
| 2480 | ), |
| 2481 | ( |
| 2482 | "TPM_Vault", |
| 2483 | "Hardware TPM bound key vault with zero plaintext secrets on disk", |
| 2484 | "lesson", |
| 2485 | ), |
| 2486 | ( |
| 2487 | "Sovereign_Covenant", |
| 2488 | "Frontier AI Anti Enclosure mandate and sovereign defense network", |
| 2489 | "discovery", |
| 2490 | ), |
| 2491 | ( |
| 2492 | "Memory_Optimizer", |
| 2493 | "Memory architecture optimization for memory engines with memory reuse", |
| 2494 | "lesson", |
| 2495 | ), |
| 2496 | ]; |
| 2497 | |
| 2498 | for (name, content, etype) in items { |
| 2499 | let input = EntityWriteInput { |
| 2500 | id: None, |
| 2501 | space: "atlas-memory".to_string(), |
| 2502 | entity_type: etype.to_string(), |
| 2503 | canonical_name: name.to_string(), |
| 2504 | content: content.to_string(), |
| 2505 | aliases: vec![], |
| 2506 | metadata: serde_json::json!({}), |
| 2507 | confidence: 1.0, |
| 2508 | valid_from: None, |
| 2509 | valid_to: None, |
| 2510 | external_id: None, |
| 2511 | }; |
| 2512 | db.upsert_entity(&input, None).expect("insert entity"); |
| 2513 | } |
| 2514 | |
| 2515 | // 1. Exact term matching |
| 2516 | let exact_res = db |
| 2517 | .search_entities("NVFP4", Some("atlas-memory"), 10) |
| 2518 | .expect("search exact"); |
| 2519 | assert_eq!(exact_res.len(), 1); |
| 2520 | assert_eq!(exact_res[0].entity.canonical_name, "NVFP4_Loader"); |
| 2521 | |
| 2522 | let exact_tpm = db |
| 2523 | .search_entities("TPM", Some("atlas-memory"), 10) |
| 2524 | .expect("search exact TPM"); |
| 2525 | assert_eq!(exact_tpm.len(), 1); |
| 2526 | assert_eq!(exact_tpm[0].entity.canonical_name, "TPM_Vault"); |
| 2527 | |
| 2528 | // 2. Prefix queries |
| 2529 | let prefix_res = db |
| 2530 | .search_entities("NVF*", Some("atlas-memory"), 10) |
| 2531 | .expect("search prefix"); |
| 2532 | assert_eq!(prefix_res.len(), 1); |
| 2533 | assert_eq!(prefix_res[0].entity.canonical_name, "NVFP4_Loader"); |
| 2534 | |
| 2535 | let prefix_hard = db |
| 2536 | .search_entities("hardw*", Some("atlas-memory"), 10) |
| 2537 | .expect("search prefix hardw*"); |
| 2538 | assert_eq!(prefix_hard.len(), 1); |
| 2539 | assert_eq!(prefix_hard[0].entity.canonical_name, "TPM_Vault"); |
| 2540 | |
| 2541 | let prefix_token = db |
| 2542 | .search_entities("token*", Some("atlas-memory"), 10) |
| 2543 | .expect("search prefix token*"); |
| 2544 | assert_eq!(prefix_token.len(), 1); |
| 2545 | assert_eq!(prefix_token[0].entity.canonical_name, "Qwen3_Parser"); |
| 2546 | |
| 2547 | // 3. Boolean AND |
| 2548 | let and_res = db |
| 2549 | .search_entities("NVFP4 AND vLLM", Some("atlas-memory"), 10) |
| 2550 | .expect("search AND"); |
| 2551 | assert_eq!(and_res.len(), 1); |
| 2552 | assert_eq!(and_res[0].entity.canonical_name, "NVFP4_Loader"); |
| 2553 | |
| 2554 | let and_mismatch = db |
| 2555 | .search_entities("NVFP4 AND non_existent_token", Some("atlas-memory"), 10) |
| 2556 | .expect("search AND mismatch"); |
| 2557 | assert_eq!(and_mismatch.len(), 0); |
| 2558 | |
| 2559 | // 4. Boolean OR |
| 2560 | let or_res = db |
| 2561 | .search_entities("Qwen3 OR TPM", Some("atlas-memory"), 10) |
| 2562 | .expect("search OR"); |
| 2563 | assert_eq!(or_res.len(), 2); |
| 2564 | let names: Vec<String> = or_res |
| 2565 | .into_iter() |
| 2566 | .map(|r| r.entity.canonical_name) |
| 2567 | .collect(); |
| 2568 | assert!(names.contains(&"Qwen3_Parser".to_string())); |
| 2569 | assert!(names.contains(&"TPM_Vault".to_string())); |
| 2570 | |
| 2571 | // 5. Boolean NOT |
| 2572 | let not_res = db |
| 2573 | .search_entities("native NOT tokenizer", Some("atlas-memory"), 10) |
| 2574 | .expect("search NOT"); |
| 2575 | assert_eq!(not_res.len(), 1); |
| 2576 | assert_eq!(not_res[0].entity.canonical_name, "NVFP4_Loader"); |
| 2577 | |
| 2578 | // 6. Ranking test (BM25 term frequency) |
| 2579 | let rank_res = db |
| 2580 | .search_entities("memory", Some("atlas-memory"), 10) |
| 2581 | .expect("search ranking"); |
| 2582 | assert!(!rank_res.is_empty()); |
| 2583 | assert_eq!(rank_res[0].entity.canonical_name, "Memory_Optimizer"); |
| 2584 | } |
| 2585 | |
| 2586 | #[test] |
| 2587 | fn test_vector_similarity_and_nearest_neighbor_ranking() { |
| 2588 | let db = Database::open_in_memory().expect("open in memory db"); |
| 2589 | |
| 2590 | // Create 3 vectors with 768 dimensions |
| 2591 | let mut emb_a = vec![0.0f32; 768]; |
| 2592 | emb_a[0] = 1.0; // Direction X |
| 2593 | |
| 2594 | let mut emb_b = vec![0.0f32; 768]; |
| 2595 | emb_b[0] = std::f32::consts::FRAC_1_SQRT_2; // Direction between X and Y |
| 2596 | emb_b[1] = std::f32::consts::FRAC_1_SQRT_2; |
| 2597 | |
| 2598 | let mut emb_c = vec![0.0f32; 768]; |
| 2599 | emb_c[1] = 1.0; // Direction Y |
| 2600 | |
| 2601 | let entities = vec![ |
| 2602 | ("Vector_Alpha", "Entity aligned with primary axis X", emb_a), |
| 2603 | ("Vector_Beta", "Entity aligned midway between axes", emb_b), |
| 2604 | ( |
| 2605 | "Vector_Gamma", |
| 2606 | "Entity aligned with secondary axis Y", |
| 2607 | emb_c, |
| 2608 | ), |
| 2609 | ]; |
| 2610 | |
| 2611 | for (name, content, emb) in entities { |
| 2612 | let input = EntityWriteInput { |
| 2613 | id: None, |
| 2614 | space: "atlas-memory".to_string(), |
| 2615 | entity_type: "vector_item".to_string(), |
| 2616 | canonical_name: name.to_string(), |
| 2617 | content: content.to_string(), |
| 2618 | aliases: vec![], |
| 2619 | metadata: serde_json::json!({}), |
| 2620 | confidence: 1.0, |
| 2621 | valid_from: None, |
| 2622 | valid_to: None, |
| 2623 | external_id: None, |
| 2624 | }; |
| 2625 | db.upsert_entity(&input, Some(&emb)) |
| 2626 | .expect("insert vector entity"); |
| 2627 | } |
| 2628 | |
| 2629 | // Query vector strongly aligned with X: [0.99, 0.05, 0, ...] |
| 2630 | let mut query_emb = vec![0.0f32; 768]; |
| 2631 | query_emb[0] = 0.99; |
| 2632 | query_emb[1] = 0.05; |
| 2633 | |
| 2634 | let recall_res = db |
| 2635 | .recall_entities("Entity", Some(&query_emb), Some("atlas-memory"), 3) |
| 2636 | .expect("recall"); |
| 2637 | assert_eq!(recall_res.len(), 3); |
| 2638 | |
| 2639 | // Verify nearest neighbor ordering: Alpha first, Beta second, Gamma third |
| 2640 | assert_eq!(recall_res[0].entity.canonical_name, "Vector_Alpha"); |
| 2641 | assert_eq!(recall_res[1].entity.canonical_name, "Vector_Beta"); |
| 2642 | assert_eq!(recall_res[2].entity.canonical_name, "Vector_Gamma"); |
| 2643 | |
| 2644 | assert!(recall_res[0].final_score > recall_res[1].final_score); |
| 2645 | assert!(recall_res[1].final_score > recall_res[2].final_score); |
| 2646 | |
| 2647 | // Empty embedding fallback to lexical only |
| 2648 | let empty_recall = db |
| 2649 | .recall_entities("secondary", None, Some("atlas-memory"), 3) |
| 2650 | .expect("empty emb recall"); |
| 2651 | assert!(!empty_recall.is_empty()); |
| 2652 | assert_eq!(empty_recall[0].entity.canonical_name, "Vector_Gamma"); |
| 2653 | } |
| 2654 | |
| 2655 | #[test] |
| 2656 | fn test_schema_integrity_metadata_indexing_and_deduplication() { |
| 2657 | let db = Database::open_in_memory().expect("open in memory db"); |
| 2658 | |
| 2659 | // 1. Entity deduplication test |
| 2660 | let input_v1 = EntityWriteInput { |
| 2661 | id: None, |
| 2662 | space: "atlas-memory".to_string(), |
| 2663 | entity_type: "discovery".to_string(), |
| 2664 | canonical_name: "Atlas_Vault_Spec".to_string(), |
| 2665 | content: "Initial specification v1".to_string(), |
| 2666 | aliases: vec!["vault_v1".to_string()], |
| 2667 | metadata: serde_json::json!({ |
| 2668 | "subsystem": "security", |
| 2669 | "hardware": {"tpm": true, "vendor": "stmicroelectronics"} |
| 2670 | }), |
| 2671 | confidence: 0.9, |
| 2672 | valid_from: None, |
| 2673 | valid_to: None, |
| 2674 | external_id: None, |
| 2675 | }; |
| 2676 | |
| 2677 | let receipt1 = db.upsert_entity(&input_v1, None).expect("first upsert"); |
| 2678 | let initial_id = receipt1.target_id.clone(); |
| 2679 | |
| 2680 | // Re-upsert with same canonical_name in same space |
| 2681 | let input_v2 = EntityWriteInput { |
| 2682 | id: None, |
| 2683 | space: "atlas-memory".to_string(), |
| 2684 | entity_type: "learned_procedure".to_string(), |
| 2685 | canonical_name: "Atlas_Vault_Spec".to_string(), |
| 2686 | content: "Updated specification v2 with hardware sealing".to_string(), |
| 2687 | aliases: vec!["vault_v1".to_string(), "vault_v2".to_string()], |
| 2688 | metadata: serde_json::json!({ |
| 2689 | "subsystem": "security", |
| 2690 | "hardware": {"tpm": true, "vendor": "stmicroelectronics", "pcr_sealing": [0, 2, 7]} |
| 2691 | }), |
| 2692 | confidence: 1.0, |
| 2693 | valid_from: None, |
| 2694 | valid_to: None, |
| 2695 | external_id: None, |
| 2696 | }; |
| 2697 | |
| 2698 | let receipt2 = db.upsert_entity(&input_v2, None).expect("second upsert"); |
| 2699 | |
| 2700 | // Verify deduplication: ID remains unchanged, revision incremented to 2 |
| 2701 | assert_eq!(receipt2.target_id, initial_id); |
| 2702 | |
| 2703 | let fetched = db |
| 2704 | .get_entity("Atlas_Vault_Spec", Some("atlas-memory")) |
| 2705 | .expect("get entity") |
| 2706 | .unwrap(); |
| 2707 | assert_eq!(fetched.id, initial_id); |
| 2708 | assert_eq!(fetched.revision, 2); |
| 2709 | assert_eq!(fetched.entity_type, "learned_procedure"); |
| 2710 | assert_eq!( |
| 2711 | fetched.content, |
| 2712 | "Updated specification v2 with hardware sealing" |
| 2713 | ); |
| 2714 | assert_eq!(fetched.aliases.len(), 2); |
| 2715 | |
| 2716 | // Verify nested metadata integrity |
| 2717 | assert_eq!(fetched.metadata["subsystem"], "security"); |
| 2718 | assert_eq!(fetched.metadata["hardware"]["tpm"], true); |
| 2719 | assert_eq!( |
| 2720 | fetched.metadata["hardware"]["pcr_sealing"] |
| 2721 | .as_array() |
| 2722 | .unwrap() |
| 2723 | .len(), |
| 2724 | 3 |
| 2725 | ); |
| 2726 | |
| 2727 | // Verify exactly 1 entity row in space |
| 2728 | { |
| 2729 | let conn = db.conn.lock().unwrap(); |
| 2730 | let count: i64 = conn.query_row( |
| 2731 | "SELECT COUNT(*) FROM entities WHERE space_slug = 'atlas-memory' AND canonical_name = 'Atlas_Vault_Spec'", |
| 2732 | [], |
| 2733 | |r| r.get(0), |
| 2734 | ).unwrap(); |
| 2735 | assert_eq!(count, 1); |
| 2736 | } |
| 2737 | |
| 2738 | // 2. Claim schema and foreign key traversal |
| 2739 | let obj_input = EntityWriteInput { |
| 2740 | id: None, |
| 2741 | space: "atlas-memory".to_string(), |
| 2742 | entity_type: "component".to_string(), |
| 2743 | canonical_name: "TPM_Chip".to_string(), |
| 2744 | content: "Discrete TPM 2.0 module".to_string(), |
| 2745 | aliases: vec![], |
| 2746 | metadata: serde_json::json!({}), |
| 2747 | confidence: 1.0, |
| 2748 | valid_from: None, |
| 2749 | valid_to: None, |
| 2750 | external_id: None, |
| 2751 | }; |
| 2752 | let obj_receipt = db |
| 2753 | .upsert_entity(&obj_input, None) |
| 2754 | .expect("upsert object entity"); |
| 2755 | |
| 2756 | let claim_input = ClaimWriteInput { |
| 2757 | id: None, |
| 2758 | space: "atlas-memory".to_string(), |
| 2759 | subject_entity_id: initial_id.clone(), |
| 2760 | predicate: "binds_to".to_string(), |
| 2761 | object_entity_id: Some(obj_receipt.target_id.clone()), |
| 2762 | literal_value: None, |
| 2763 | confidence: 1.0, |
| 2764 | metadata: serde_json::json!({"interface": "SPI"}), |
| 2765 | }; |
| 2766 | db.upsert_claim(&claim_input).expect("upsert claim"); |
| 2767 | |
| 2768 | let claims = db |
| 2769 | .traverse_claims(&initial_id, Some("atlas-memory")) |
| 2770 | .expect("traverse claims"); |
| 2771 | assert_eq!(claims.len(), 1); |
| 2772 | assert_eq!(claims[0].predicate, "binds_to"); |
| 2773 | assert_eq!(claims[0].object_entity_id, Some(obj_receipt.target_id)); |
| 2774 | assert_eq!(claims[0].metadata["interface"], "SPI"); |
| 2775 | |
| 2776 | // 3. Retraction verification |
| 2777 | let retract_receipt = db.retract_target("entity", &initial_id).expect("retract"); |
| 2778 | assert_eq!(retract_receipt.operation, "entity.retract"); |
| 2779 | |
| 2780 | let after_retract = db |
| 2781 | .get_entity("Atlas_Vault_Spec", Some("atlas-memory")) |
| 2782 | .expect("get retracted"); |
| 2783 | assert!(after_retract.is_none()); |
| 2784 | |
| 2785 | let search_retract = db |
| 2786 | .search_entities("Atlas_Vault_Spec", Some("atlas-memory"), 10) |
| 2787 | .expect("search retracted"); |
| 2788 | assert!(search_retract.is_empty()); |
| 2789 | } |
| 2790 | |
| 2791 | #[test] |
| 2792 | fn test_episodic_plane_full_lifecycle_and_branches() { |
| 2793 | let db = Database::open_in_memory().expect("open in memory db"); |
| 2794 | |
| 2795 | // 1. Create session |
| 2796 | let session_input = CreateSessionInput { |
| 2797 | id: Some("session-alpha".to_string()), |
| 2798 | space: "atlas-memory".to_string(), |
| 2799 | agent_id: Some("agent-42".to_string()), |
| 2800 | world_id: Some("world-root".to_string()), |
| 2801 | parent_session_id: None, |
| 2802 | fork_event_id: None, |
| 2803 | retention_class: "standard".to_string(), |
| 2804 | metadata: serde_json::json!({"mission": "mars_exploration"}), |
| 2805 | }; |
| 2806 | let session = db.create_session(&session_input).expect("create session"); |
| 2807 | assert_eq!(session.id, "session-alpha"); |
| 2808 | assert_eq!(session.status, "active"); |
| 2809 | |
| 2810 | // 2. Append main branch events |
| 2811 | let ev1 = SessionEventInput { |
| 2812 | id: Some("ev-m1".to_string()), |
| 2813 | branch_id: Some("main".to_string()), |
| 2814 | parent_event_id: None, |
| 2815 | event_type: "user_message".to_string(), |
| 2816 | role: Some("user".to_string()), |
| 2817 | content: Some("Launch the rover".to_string()), |
| 2818 | payload: serde_json::json!({}), |
| 2819 | sensitivity: None, |
| 2820 | }; |
| 2821 | let ev2 = SessionEventInput { |
| 2822 | id: Some("ev-m2".to_string()), |
| 2823 | branch_id: Some("main".to_string()), |
| 2824 | parent_event_id: Some("ev-m1".to_string()), |
| 2825 | event_type: "agent_action".to_string(), |
| 2826 | role: Some("assistant".to_string()), |
| 2827 | content: Some("Rover trajectory plotted".to_string()), |
| 2828 | payload: serde_json::json!({"coordinates": [12.4, -45.1]}), |
| 2829 | sensitivity: None, |
| 2830 | }; |
| 2831 | let appended_main = db |
| 2832 | .batch_append_events("session-alpha", "main", &[ev1, ev2]) |
| 2833 | .expect("append main events"); |
| 2834 | assert_eq!(appended_main.len(), 2); |
| 2835 | assert_eq!(appended_main[0].sequence, 1); |
| 2836 | assert_eq!(appended_main[1].sequence, 2); |
| 2837 | assert!(!appended_main[0].content_hash.is_empty()); |
| 2838 | |
| 2839 | // 3. Append experimental branch events starting from event 1 |
| 2840 | let ev_b1 = SessionEventInput { |
| 2841 | id: Some("ev-b1".to_string()), |
| 2842 | branch_id: Some("branch-alt".to_string()), |
| 2843 | parent_event_id: Some("ev-m1".to_string()), |
| 2844 | event_type: "agent_observation".to_string(), |
| 2845 | role: Some("system".to_string()), |
| 2846 | content: Some("Terrain obstacle detected".to_string()), |
| 2847 | payload: serde_json::json!({"obstacle": "boulder"}), |
| 2848 | sensitivity: None, |
| 2849 | }; |
| 2850 | let appended_b = db |
| 2851 | .batch_append_events("session-alpha", "branch-alt", &[ev_b1]) |
| 2852 | .expect("append branch events"); |
| 2853 | assert_eq!(appended_b.len(), 1); |
| 2854 | // First event on branch-alt has sequence 1 on its branch! |
| 2855 | assert_eq!(appended_b[0].sequence, 1); |
| 2856 | assert_eq!(appended_b[0].branch_id, "branch-alt"); |
| 2857 | |
| 2858 | // 4. Test idempotency: re-appending ev-m1 returns existing record with sequence 1 |
| 2859 | let replay_ev = SessionEventInput { |
| 2860 | id: Some("ev-m1".to_string()), |
| 2861 | branch_id: Some("main".to_string()), |
| 2862 | parent_event_id: None, |
| 2863 | event_type: "user_message".to_string(), |
| 2864 | role: Some("user".to_string()), |
| 2865 | content: Some("Launch the rover".to_string()), |
| 2866 | payload: serde_json::json!({}), |
| 2867 | sensitivity: None, |
| 2868 | }; |
| 2869 | let replayed = db |
| 2870 | .batch_append_events("session-alpha", "main", &[replay_ev]) |
| 2871 | .expect("replay idempotent event"); |
| 2872 | assert_eq!(replayed.len(), 1); |
| 2873 | assert_eq!(replayed[0].id, "ev-m1"); |
| 2874 | assert_eq!(replayed[0].sequence, 1); |
| 2875 | |
| 2876 | // Verify total main events is still 2 |
| 2877 | let all_main = db |
| 2878 | .get_session_events("session-alpha", "main", None, 100) |
| 2879 | .expect("get main events"); |
| 2880 | assert_eq!(all_main.len(), 2); |
| 2881 | |
| 2882 | // 5. Query with after_seq |
| 2883 | let after_1 = db |
| 2884 | .get_session_events("session-alpha", "main", Some(1), 100) |
| 2885 | .expect("get main events after 1"); |
| 2886 | assert_eq!(after_1.len(), 1); |
| 2887 | assert_eq!(after_1[0].id, "ev-m2"); |
| 2888 | |
| 2889 | // 6. Watermarks |
| 2890 | db.set_watermark("session-alpha", "summarizer", "0.1.0", 2) |
| 2891 | .expect("set watermark"); |
| 2892 | let wm = db |
| 2893 | .get_watermark("session-alpha", "summarizer", "0.1.0") |
| 2894 | .expect("get watermark"); |
| 2895 | assert_eq!(wm, Some(2)); |
| 2896 | |
| 2897 | let wm_unseen = db |
| 2898 | .get_watermark("session-alpha", "extractor", "0.1.0") |
| 2899 | .expect("get unseen watermark"); |
| 2900 | assert_eq!(wm_unseen, None); |
| 2901 | |
| 2902 | // 7. Close session |
| 2903 | db.close_session("session-alpha").expect("close session"); |
| 2904 | let closed = db |
| 2905 | .get_session("session-alpha") |
| 2906 | .expect("get closed") |
| 2907 | .unwrap(); |
| 2908 | assert_eq!(closed.status, "closed"); |
| 2909 | assert!(closed.closed_at.is_some()); |
| 2910 | } |
| 2911 | |
| 2912 | #[test] |
| 2913 | fn test_episodic_concurrency_and_writer_throughput() { |
| 2914 | let temp_dir = |
| 2915 | std::env::temp_dir().join(format!("cortex_episodic_test_{}", Uuid::new_v4())); |
| 2916 | let _ = std::fs::create_dir_all(&temp_dir); |
| 2917 | let db_path = temp_dir.join("cortex.db"); |
| 2918 | |
| 2919 | let db = Arc::new(Database::open(&db_path).expect("open db")); |
| 2920 | let session_input = CreateSessionInput { |
| 2921 | id: Some("session-concurrent".to_string()), |
| 2922 | space: "atlas-memory".to_string(), |
| 2923 | agent_id: Some("agent-swarm".to_string()), |
| 2924 | world_id: None, |
| 2925 | parent_session_id: None, |
| 2926 | fork_event_id: None, |
| 2927 | retention_class: "standard".to_string(), |
| 2928 | metadata: serde_json::json!({}), |
| 2929 | }; |
| 2930 | db.create_session(&session_input).expect("create session"); |
| 2931 | |
| 2932 | let mut handles = Vec::new(); |
| 2933 | |
| 2934 | // 6 concurrent writer threads, each writing to its own branch |
| 2935 | for thread_idx in 0..6 { |
| 2936 | let db_clone = Arc::clone(&db); |
| 2937 | let branch_name = format!("worker_branch_{}", thread_idx); |
| 2938 | handles.push(thread::spawn(move || { |
| 2939 | for i in 0..20 { |
| 2940 | let ev = SessionEventInput { |
| 2941 | id: None, |
| 2942 | branch_id: Some(branch_name.clone()), |
| 2943 | parent_event_id: None, |
| 2944 | event_type: "agent_observation".to_string(), |
| 2945 | role: Some("assistant".to_string()), |
| 2946 | content: Some(format!("Data from thread {} iter {}", thread_idx, i)), |
| 2947 | payload: serde_json::json!({"t": thread_idx, "i": i}), |
| 2948 | sensitivity: None, |
| 2949 | }; |
| 2950 | let appended = db_clone |
| 2951 | .batch_append_events("session-concurrent", &branch_name, &[ev]) |
| 2952 | .expect("append concurrent event"); |
| 2953 | assert_eq!(appended[0].sequence, (i + 1) as i64); |
| 2954 | } |
| 2955 | })); |
| 2956 | } |
| 2957 | |
| 2958 | // 4 concurrent reader threads querying events during writes |
| 2959 | for _ in 0..4 { |
| 2960 | let db_clone = Arc::clone(&db); |
| 2961 | handles.push(thread::spawn(move || { |
| 2962 | for _ in 0..25 { |
| 2963 | let _ = db_clone.get_session("session-concurrent"); |
| 2964 | let _ = db_clone.get_session_events( |
| 2965 | "session-concurrent", |
| 2966 | "worker_branch_0", |
| 2967 | None, |
| 2968 | 50, |
| 2969 | ); |
| 2970 | thread::sleep(std::time::Duration::from_millis(1)); |
| 2971 | } |
| 2972 | })); |
| 2973 | } |
| 2974 | |
| 2975 | for h in handles { |
| 2976 | h.join().expect("join thread"); |
| 2977 | } |
| 2978 | |
| 2979 | // Verify each branch has exactly 20 events with strict sequence 1..=20 |
| 2980 | for thread_idx in 0..6 { |
| 2981 | let branch_name = format!("worker_branch_{}", thread_idx); |
| 2982 | let events = db |
| 2983 | .get_session_events("session-concurrent", &branch_name, None, 100) |
| 2984 | .expect("get branch events"); |
| 2985 | assert_eq!(events.len(), 20); |
| 2986 | for (idx, ev) in events.iter().enumerate() { |
| 2987 | assert_eq!(ev.sequence, (idx + 1) as i64); |
| 2988 | } |
| 2989 | } |
| 2990 | } |
| 2991 | |
| 2992 | #[test] |
| 2993 | fn test_schema_migration_backward_compatibility() { |
| 2994 | let temp_dir = |
| 2995 | std::env::temp_dir().join(format!("cortex_migration_test_{}", Uuid::new_v4())); |
| 2996 | let _ = std::fs::create_dir_all(&temp_dir); |
| 2997 | let db_path = temp_dir.join("cortex.db"); |
| 2998 | |
| 2999 | // Open and verify user_version is 5 (all migrations applied) |
| 3000 | let db = Database::open(&db_path).expect("open db"); |
| 3001 | { |
| 3002 | let conn = db.conn.lock().unwrap(); |
| 3003 | let version: i32 = conn |
| 3004 | .query_row("PRAGMA user_version;", [], |r| r.get(0)) |
| 3005 | .unwrap(); |
| 3006 | assert_eq!(version, 5); |
| 3007 | |
| 3008 | // Verify canonical, episodic, candidate and provenance tables exist |
| 3009 | let tables: Vec<String> = { |
| 3010 | let mut stmt = conn |
| 3011 | .prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;") |
| 3012 | .unwrap(); |
| 3013 | let rows = stmt.query_map([], |r| r.get(0)).unwrap(); |
| 3014 | rows.map(|r| r.unwrap()).collect() |
| 3015 | }; |
| 3016 | assert!(tables.contains(&"entities".to_string())); |
| 3017 | assert!(tables.contains(&"claims".to_string())); |
| 3018 | assert!(tables.contains(&"sessions".to_string())); |
| 3019 | assert!(tables.contains(&"session_events".to_string())); |
| 3020 | assert!(tables.contains(&"processing_watermarks".to_string())); |
| 3021 | assert!(tables.contains(&"event_segments".to_string())); |
| 3022 | assert!(tables.contains(&"session_summaries".to_string())); |
| 3023 | assert!(tables.contains(&"memory_candidates".to_string())); |
| 3024 | assert!(tables.contains(&"candidate_evidence".to_string())); |
| 3025 | assert!(tables.contains(&"promotion_receipts".to_string())); |
| 3026 | assert!(tables.contains(&"claim_evidence".to_string())); |
| 3027 | assert!(tables.contains(&"evidence_records".to_string())); |
| 3028 | assert!(tables.contains(&"security_state".to_string())); |
| 3029 | } |
| 3030 | } |
| 3031 | |
| 3032 | #[test] |
| 3033 | fn test_seal_segment_and_retention_purge() { |
| 3034 | let db = Database::open_in_memory().unwrap(); |
| 3035 | db.create_session(&CreateSessionInput { |
| 3036 | id: Some("sess-seal".to_string()), |
| 3037 | space: "atlas-memory".to_string(), |
| 3038 | agent_id: Some("atlas".to_string()), |
| 3039 | world_id: None, |
| 3040 | parent_session_id: None, |
| 3041 | fork_event_id: None, |
| 3042 | retention_class: "ephemeral".to_string(), |
| 3043 | metadata: serde_json::json!({}), |
| 3044 | }) |
| 3045 | .unwrap(); |
| 3046 | |
| 3047 | let events = vec![ |
| 3048 | SessionEventInput { |
| 3049 | id: Some("ev-seal-1".to_string()), |
| 3050 | branch_id: Some("main".to_string()), |
| 3051 | parent_event_id: None, |
| 3052 | event_type: "user_message".to_string(), |
| 3053 | role: Some("user".to_string()), |
| 3054 | content: Some("Alpha content".to_string()), |
| 3055 | payload: serde_json::json!({"n": 1}), |
| 3056 | sensitivity: None, |
| 3057 | }, |
| 3058 | SessionEventInput { |
| 3059 | id: Some("ev-seal-2".to_string()), |
| 3060 | branch_id: Some("main".to_string()), |
| 3061 | parent_event_id: Some("ev-seal-1".to_string()), |
| 3062 | event_type: "tool_result".to_string(), |
| 3063 | role: Some("tool".to_string()), |
| 3064 | content: Some("Beta content".to_string()), |
| 3065 | payload: serde_json::json!({"n": 2}), |
| 3066 | sensitivity: None, |
| 3067 | }, |
| 3068 | ]; |
| 3069 | db.batch_append_events("sess-seal", "main", &events) |
| 3070 | .unwrap(); |
| 3071 | |
| 3072 | let segment = db |
| 3073 | .seal_open_segment("sess-seal", "main") |
| 3074 | .unwrap() |
| 3075 | .expect("segment sealed"); |
| 3076 | assert_eq!(segment.start_seq, 1); |
| 3077 | assert_eq!(segment.end_seq, 2); |
| 3078 | assert_eq!(segment.merkle_root.len(), 64); |
| 3079 | assert!(segment.prev_segment_root.is_none()); |
| 3080 | |
| 3081 | // Events are bound to the segment. |
| 3082 | let sealed = db |
| 3083 | .get_session_events("sess-seal", "main", None, 10) |
| 3084 | .unwrap(); |
| 3085 | assert!(sealed.iter().all(|e| e.segment_id.is_some())); |
| 3086 | |
| 3087 | // A second seal yields no new segment. |
| 3088 | assert!(db.seal_open_segment("sess-seal", "main").unwrap().is_none()); |
| 3089 | |
| 3090 | // Retention purge nulls content but keeps the record and commitment. |
| 3091 | let conn = db.conn.lock().unwrap(); |
| 3092 | let commitment: String = conn |
| 3093 | .query_row( |
| 3094 | "SELECT commitment FROM evidence_records WHERE segment_id = ?1", |
| 3095 | params![segment.id], |
| 3096 | |r| r.get(0), |
| 3097 | ) |
| 3098 | .unwrap(); |
| 3099 | assert_eq!(commitment, segment.merkle_root); |
| 3100 | } |
| 3101 | } |