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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// SPF Smart Gateway - Agent State LMDB
|
| 2 |
+
// Copyright 2026 Joseph Stone - All Rights Reserved
|
| 3 |
+
//
|
| 4 |
+
// LMDB-backed persistent state for Agent's virtual home. Stores preferences,
|
| 5 |
+
// memory, working context, and session continuity data across sessions.
|
| 6 |
+
//
|
| 7 |
+
// Database: AGENT_STATE
|
| 8 |
+
// Storage: ~/SPFsmartGATE/LIVE/LMDB5/LMDB5.DB/
|
| 9 |
+
|
| 10 |
+
use anyhow::{anyhow, Result};
|
| 11 |
+
use heed::types::*;
|
| 12 |
+
use heed::{Database, Env, EnvOpenOptions};
|
| 13 |
+
use serde::{Deserialize, Serialize};
|
| 14 |
+
use std::collections::HashMap;
|
| 15 |
+
use std::path::Path;
|
| 16 |
+
use std::sync::atomic::{AtomicU64, Ordering};
|
| 17 |
+
use std::time::{SystemTime, UNIX_EPOCH};
|
| 18 |
+
|
| 19 |
+
/// Atomic counter for unique memory IDs within same timestamp
|
| 20 |
+
static MEMORY_COUNTER: AtomicU64 = AtomicU64::new(0);
|
| 21 |
+
|
| 22 |
+
const MAX_DB_SIZE: usize = 1024 * 1024 * 1024; // 1GB — virtual address space only, no physical cost
|
| 23 |
+
|
| 24 |
+
/// Memory entry type
|
| 25 |
+
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
| 26 |
+
pub enum MemoryType {
|
| 27 |
+
/// User preference
|
| 28 |
+
Preference,
|
| 29 |
+
/// Fact about the user/project
|
| 30 |
+
Fact,
|
| 31 |
+
/// Instruction from user
|
| 32 |
+
Instruction,
|
| 33 |
+
/// Context from previous sessions
|
| 34 |
+
Context,
|
| 35 |
+
/// Working state (temporary, session-bound)
|
| 36 |
+
Working,
|
| 37 |
+
/// Pinned (never auto-expire)
|
| 38 |
+
Pinned,
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
/// Memory entry stored in Agent's memory
|
| 42 |
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
| 43 |
+
pub struct MemoryEntry {
|
| 44 |
+
/// Unique ID
|
| 45 |
+
pub id: String,
|
| 46 |
+
/// Memory content
|
| 47 |
+
pub content: String,
|
| 48 |
+
/// Memory type
|
| 49 |
+
pub memory_type: MemoryType,
|
| 50 |
+
/// Tags for categorization
|
| 51 |
+
pub tags: Vec<String>,
|
| 52 |
+
/// Source (session ID or "user" if explicit)
|
| 53 |
+
pub source: String,
|
| 54 |
+
/// Created timestamp
|
| 55 |
+
pub created_at: u64,
|
| 56 |
+
/// Last accessed timestamp
|
| 57 |
+
pub last_accessed: u64,
|
| 58 |
+
/// Access count
|
| 59 |
+
pub access_count: u64,
|
| 60 |
+
/// Relevance score (0.0 - 1.0)
|
| 61 |
+
pub relevance: f64,
|
| 62 |
+
/// Expiry timestamp (0 = never)
|
| 63 |
+
pub expires_at: u64,
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
/// Session context for continuity
|
| 67 |
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
| 68 |
+
pub struct SessionContext {
|
| 69 |
+
/// Session ID
|
| 70 |
+
pub session_id: String,
|
| 71 |
+
/// Parent session ID (if resumed)
|
| 72 |
+
pub parent_session: Option<String>,
|
| 73 |
+
/// Session start time
|
| 74 |
+
pub started_at: u64,
|
| 75 |
+
/// Session end time (0 if ongoing)
|
| 76 |
+
pub ended_at: u64,
|
| 77 |
+
/// Working directory at start
|
| 78 |
+
pub working_dir: String,
|
| 79 |
+
/// Active project at start
|
| 80 |
+
pub active_project: Option<String>,
|
| 81 |
+
/// Summary of what was accomplished
|
| 82 |
+
pub summary: String,
|
| 83 |
+
/// Files modified
|
| 84 |
+
pub files_modified: Vec<String>,
|
| 85 |
+
/// Total complexity
|
| 86 |
+
pub total_complexity: u64,
|
| 87 |
+
/// Total actions
|
| 88 |
+
pub total_actions: u64,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
/// Agent preferences
|
| 92 |
+
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
| 93 |
+
pub struct AgentPreferences {
|
| 94 |
+
/// Preferred code style (e.g., "rust", "python")
|
| 95 |
+
pub code_style: Option<String>,
|
| 96 |
+
/// Preferred response length ("brief", "detailed", "adaptive")
|
| 97 |
+
pub response_length: String,
|
| 98 |
+
/// Whether to show thinking process
|
| 99 |
+
pub show_thinking: bool,
|
| 100 |
+
/// Preferred editor for large edits
|
| 101 |
+
pub preferred_editor: Option<String>,
|
| 102 |
+
/// Auto-save session context
|
| 103 |
+
pub auto_save_context: bool,
|
| 104 |
+
/// Maximum context entries to remember
|
| 105 |
+
pub max_context_entries: usize,
|
| 106 |
+
/// Custom key-value preferences
|
| 107 |
+
pub custom: HashMap<String, String>,
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
/// LMDB-backed Agent state manager
|
| 111 |
+
pub struct AgentStateDb {
|
| 112 |
+
env: Env,
|
| 113 |
+
/// Memory storage: id -> MemoryEntry
|
| 114 |
+
memory: Database<Str, SerdeBincode<MemoryEntry>>,
|
| 115 |
+
/// Session history: session_id -> SessionContext
|
| 116 |
+
sessions: Database<Str, SerdeBincode<SessionContext>>,
|
| 117 |
+
/// Key-value state: key -> JSON value
|
| 118 |
+
state: Database<Str, Str>,
|
| 119 |
+
/// Tag index: "tag:tagname" -> list of memory IDs (JSON array)
|
| 120 |
+
tags: Database<Str, Str>,
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
impl AgentStateDb {
|
| 124 |
+
/// Open or create Agent state LMDB at given path
|
| 125 |
+
pub fn open(path: &Path) -> Result<Self> {
|
| 126 |
+
std::fs::create_dir_all(path)?;
|
| 127 |
+
|
| 128 |
+
let env = unsafe {
|
| 129 |
+
EnvOpenOptions::new()
|
| 130 |
+
.map_size(MAX_DB_SIZE)
|
| 131 |
+
.max_dbs(8)
|
| 132 |
+
.open(path)?
|
| 133 |
+
};
|
| 134 |
+
|
| 135 |
+
let mut wtxn = env.write_txn()?;
|
| 136 |
+
let memory = env.create_database(&mut wtxn, Some("memory"))?;
|
| 137 |
+
let sessions = env.create_database(&mut wtxn, Some("sessions"))?;
|
| 138 |
+
let state = env.create_database(&mut wtxn, Some("state"))?;
|
| 139 |
+
let tags = env.create_database(&mut wtxn, Some("tags"))?;
|
| 140 |
+
wtxn.commit()?;
|
| 141 |
+
|
| 142 |
+
log::info!("Agent State LMDB opened at {:?}", path);
|
| 143 |
+
Ok(Self { env, memory, sessions, state, tags })
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// ========================================================================
|
| 147 |
+
// MEMORY OPERATIONS
|
| 148 |
+
// ========================================================================
|
| 149 |
+
|
| 150 |
+
/// Store a memory entry
|
| 151 |
+
pub fn remember(&self, entry: MemoryEntry) -> Result<String> {
|
| 152 |
+
let id = entry.id.clone();
|
| 153 |
+
|
| 154 |
+
// Update tag index
|
| 155 |
+
for tag in &entry.tags {
|
| 156 |
+
self.add_to_tag_index(tag, &id)?;
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
let mut wtxn = self.env.write_txn()?;
|
| 160 |
+
self.memory.put(&mut wtxn, &id, &entry)?;
|
| 161 |
+
wtxn.commit()?;
|
| 162 |
+
|
| 163 |
+
Ok(id)
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
/// Create and store a new memory
|
| 167 |
+
pub fn create_memory(
|
| 168 |
+
&self,
|
| 169 |
+
content: &str,
|
| 170 |
+
memory_type: MemoryType,
|
| 171 |
+
tags: Vec<String>,
|
| 172 |
+
source: &str,
|
| 173 |
+
) -> Result<String> {
|
| 174 |
+
let now = SystemTime::now()
|
| 175 |
+
.duration_since(UNIX_EPOCH)
|
| 176 |
+
.unwrap_or_default()
|
| 177 |
+
.as_secs();
|
| 178 |
+
|
| 179 |
+
let counter = MEMORY_COUNTER.fetch_add(1, Ordering::SeqCst);
|
| 180 |
+
let id = format!("mem_{}_{}", now, counter);
|
| 181 |
+
|
| 182 |
+
let entry = MemoryEntry {
|
| 183 |
+
id: id.clone(),
|
| 184 |
+
content: content.to_string(),
|
| 185 |
+
memory_type,
|
| 186 |
+
tags,
|
| 187 |
+
source: source.to_string(),
|
| 188 |
+
created_at: now,
|
| 189 |
+
last_accessed: now,
|
| 190 |
+
access_count: 0,
|
| 191 |
+
relevance: 1.0,
|
| 192 |
+
expires_at: match memory_type {
|
| 193 |
+
MemoryType::Working => now + 3600, // 1 hour
|
| 194 |
+
MemoryType::Fact => now + 43200, // 12 hours
|
| 195 |
+
MemoryType::Pinned => now + 172800, // 48 hours
|
| 196 |
+
_ => 0,
|
| 197 |
+
},
|
| 198 |
+
};
|
| 199 |
+
|
| 200 |
+
self.remember(entry)
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
/// Recall a memory by ID
|
| 204 |
+
pub fn recall(&self, id: &str) -> Result<Option<MemoryEntry>> {
|
| 205 |
+
let rtxn = self.env.read_txn()?;
|
| 206 |
+
let entry = self.memory.get(&rtxn, id)?;
|
| 207 |
+
drop(rtxn);
|
| 208 |
+
|
| 209 |
+
// Update access stats
|
| 210 |
+
if let Some(mut e) = entry.clone() {
|
| 211 |
+
e.last_accessed = SystemTime::now()
|
| 212 |
+
.duration_since(UNIX_EPOCH)
|
| 213 |
+
.unwrap_or_default()
|
| 214 |
+
.as_secs();
|
| 215 |
+
e.access_count += 1;
|
| 216 |
+
|
| 217 |
+
let mut wtxn = self.env.write_txn()?;
|
| 218 |
+
self.memory.put(&mut wtxn, id, &e)?;
|
| 219 |
+
wtxn.commit()?;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
Ok(entry)
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
/// Search memories by content (simple substring match)
|
| 226 |
+
pub fn search_memories(&self, query: &str, limit: usize) -> Result<Vec<MemoryEntry>> {
|
| 227 |
+
let rtxn = self.env.read_txn()?;
|
| 228 |
+
let iter = self.memory.iter(&rtxn)?;
|
| 229 |
+
|
| 230 |
+
let query_lower = query.to_lowercase();
|
| 231 |
+
let mut matches = Vec::new();
|
| 232 |
+
|
| 233 |
+
for result in iter {
|
| 234 |
+
let (_, entry) = result?;
|
| 235 |
+
if entry.content.to_lowercase().contains(&query_lower) {
|
| 236 |
+
matches.push(entry);
|
| 237 |
+
if matches.len() >= limit {
|
| 238 |
+
break;
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
// Sort by relevance * recency
|
| 244 |
+
matches.sort_by(|a, b| {
|
| 245 |
+
let score_a = a.relevance * (a.last_accessed as f64);
|
| 246 |
+
let score_b = b.relevance * (b.last_accessed as f64);
|
| 247 |
+
score_b.partial_cmp(&score_a).unwrap_or(std::cmp::Ordering::Equal)
|
| 248 |
+
});
|
| 249 |
+
|
| 250 |
+
Ok(matches)
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
/// Get memories by tag
|
| 254 |
+
pub fn get_by_tag(&self, tag: &str) -> Result<Vec<MemoryEntry>> {
|
| 255 |
+
let key = format!("tag:{}", tag);
|
| 256 |
+
let rtxn = self.env.read_txn()?;
|
| 257 |
+
|
| 258 |
+
let ids: Vec<String> = match self.tags.get(&rtxn, &key)? {
|
| 259 |
+
Some(json) => serde_json::from_str(json)?,
|
| 260 |
+
None => return Ok(Vec::new()),
|
| 261 |
+
};
|
| 262 |
+
|
| 263 |
+
let mut entries = Vec::new();
|
| 264 |
+
for id in ids {
|
| 265 |
+
if let Some(entry) = self.memory.get(&rtxn, &id)? {
|
| 266 |
+
entries.push(entry);
|
| 267 |
+
}
|
| 268 |
+
}
|
| 269 |
+
Ok(entries)
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
/// Get memories by type
|
| 273 |
+
pub fn get_by_type(&self, memory_type: MemoryType) -> Result<Vec<MemoryEntry>> {
|
| 274 |
+
let rtxn = self.env.read_txn()?;
|
| 275 |
+
let iter = self.memory.iter(&rtxn)?;
|
| 276 |
+
|
| 277 |
+
let mut entries = Vec::new();
|
| 278 |
+
for result in iter {
|
| 279 |
+
let (_, entry) = result?;
|
| 280 |
+
if entry.memory_type == memory_type {
|
| 281 |
+
entries.push(entry);
|
| 282 |
+
}
|
| 283 |
+
}
|
| 284 |
+
Ok(entries)
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
/// Forget a memory
|
| 288 |
+
pub fn forget(&self, id: &str) -> Result<bool> {
|
| 289 |
+
// Remove from tag index
|
| 290 |
+
if let Some(entry) = self.recall(id)? {
|
| 291 |
+
for tag in &entry.tags {
|
| 292 |
+
self.remove_from_tag_index(tag, id)?;
|
| 293 |
+
}
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
let mut wtxn = self.env.write_txn()?;
|
| 297 |
+
let deleted = self.memory.delete(&mut wtxn, id)?;
|
| 298 |
+
wtxn.commit()?;
|
| 299 |
+
Ok(deleted)
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
/// Expire old memories
|
| 303 |
+
pub fn expire_memories(&self) -> Result<u64> {
|
| 304 |
+
let now = SystemTime::now()
|
| 305 |
+
.duration_since(UNIX_EPOCH)
|
| 306 |
+
.unwrap_or_default()
|
| 307 |
+
.as_secs();
|
| 308 |
+
|
| 309 |
+
let rtxn = self.env.read_txn()?;
|
| 310 |
+
let iter = self.memory.iter(&rtxn)?;
|
| 311 |
+
|
| 312 |
+
let mut to_delete = Vec::new();
|
| 313 |
+
for result in iter {
|
| 314 |
+
let (id, entry) = result?;
|
| 315 |
+
if entry.expires_at > 0 && entry.expires_at < now {
|
| 316 |
+
to_delete.push(id.to_string());
|
| 317 |
+
}
|
| 318 |
+
}
|
| 319 |
+
drop(rtxn);
|
| 320 |
+
|
| 321 |
+
let count = to_delete.len() as u64;
|
| 322 |
+
for id in to_delete {
|
| 323 |
+
self.forget(&id)?;
|
| 324 |
+
}
|
| 325 |
+
Ok(count)
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
// ========================================================================
|
| 329 |
+
// TAG INDEX
|
| 330 |
+
// ========================================================================
|
| 331 |
+
|
| 332 |
+
fn add_to_tag_index(&self, tag: &str, id: &str) -> Result<()> {
|
| 333 |
+
let key = format!("tag:{}", tag);
|
| 334 |
+
let rtxn = self.env.read_txn()?;
|
| 335 |
+
|
| 336 |
+
let mut ids: Vec<String> = match self.tags.get(&rtxn, &key)? {
|
| 337 |
+
Some(json) => serde_json::from_str(json)?,
|
| 338 |
+
None => Vec::new(),
|
| 339 |
+
};
|
| 340 |
+
drop(rtxn);
|
| 341 |
+
|
| 342 |
+
if !ids.contains(&id.to_string()) {
|
| 343 |
+
ids.push(id.to_string());
|
| 344 |
+
let json = serde_json::to_string(&ids)?;
|
| 345 |
+
|
| 346 |
+
let mut wtxn = self.env.write_txn()?;
|
| 347 |
+
self.tags.put(&mut wtxn, &key, &json)?;
|
| 348 |
+
wtxn.commit()?;
|
| 349 |
+
}
|
| 350 |
+
Ok(())
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
fn remove_from_tag_index(&self, tag: &str, id: &str) -> Result<()> {
|
| 354 |
+
let key = format!("tag:{}", tag);
|
| 355 |
+
let rtxn = self.env.read_txn()?;
|
| 356 |
+
|
| 357 |
+
let mut ids: Vec<String> = match self.tags.get(&rtxn, &key)? {
|
| 358 |
+
Some(json) => serde_json::from_str(json)?,
|
| 359 |
+
None => return Ok(()),
|
| 360 |
+
};
|
| 361 |
+
drop(rtxn);
|
| 362 |
+
|
| 363 |
+
ids.retain(|i| i != id);
|
| 364 |
+
let json = serde_json::to_string(&ids)?;
|
| 365 |
+
|
| 366 |
+
let mut wtxn = self.env.write_txn()?;
|
| 367 |
+
self.tags.put(&mut wtxn, &key, &json)?;
|
| 368 |
+
wtxn.commit()?;
|
| 369 |
+
Ok(())
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
/// List all tags
|
| 373 |
+
pub fn list_tags(&self) -> Result<Vec<String>> {
|
| 374 |
+
let rtxn = self.env.read_txn()?;
|
| 375 |
+
let iter = self.tags.iter(&rtxn)?;
|
| 376 |
+
|
| 377 |
+
let mut tags = Vec::new();
|
| 378 |
+
for result in iter {
|
| 379 |
+
let (key, _) = result?;
|
| 380 |
+
if key.starts_with("tag:") {
|
| 381 |
+
tags.push(key[4..].to_string());
|
| 382 |
+
}
|
| 383 |
+
}
|
| 384 |
+
Ok(tags)
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
// ========================================================================
|
| 388 |
+
// SESSION MANAGEMENT
|
| 389 |
+
// ========================================================================
|
| 390 |
+
|
| 391 |
+
/// Start a new session
|
| 392 |
+
pub fn start_session(&self, session_id: &str, working_dir: &str) -> Result<SessionContext> {
|
| 393 |
+
let now = SystemTime::now()
|
| 394 |
+
.duration_since(UNIX_EPOCH)
|
| 395 |
+
.unwrap_or_default()
|
| 396 |
+
.as_secs();
|
| 397 |
+
|
| 398 |
+
// Check for parent session (most recent)
|
| 399 |
+
let parent = self.get_latest_session()?.map(|s| s.session_id);
|
| 400 |
+
|
| 401 |
+
let ctx = SessionContext {
|
| 402 |
+
session_id: session_id.to_string(),
|
| 403 |
+
parent_session: parent,
|
| 404 |
+
started_at: now,
|
| 405 |
+
ended_at: 0,
|
| 406 |
+
working_dir: working_dir.to_string(),
|
| 407 |
+
active_project: None,
|
| 408 |
+
summary: String::new(),
|
| 409 |
+
files_modified: Vec::new(),
|
| 410 |
+
total_complexity: 0,
|
| 411 |
+
total_actions: 0,
|
| 412 |
+
};
|
| 413 |
+
|
| 414 |
+
let mut wtxn = self.env.write_txn()?;
|
| 415 |
+
self.sessions.put(&mut wtxn, session_id, &ctx)?;
|
| 416 |
+
wtxn.commit()?;
|
| 417 |
+
|
| 418 |
+
Ok(ctx)
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
/// End a session
|
| 422 |
+
pub fn end_session(&self, session_id: &str, summary: &str) -> Result<()> {
|
| 423 |
+
let rtxn = self.env.read_txn()?;
|
| 424 |
+
let mut ctx = self.sessions.get(&rtxn, session_id)?
|
| 425 |
+
.ok_or_else(|| anyhow!("Session not found: {}", session_id))?;
|
| 426 |
+
drop(rtxn);
|
| 427 |
+
|
| 428 |
+
ctx.ended_at = SystemTime::now()
|
| 429 |
+
.duration_since(UNIX_EPOCH)
|
| 430 |
+
.unwrap_or_default()
|
| 431 |
+
.as_secs();
|
| 432 |
+
ctx.summary = summary.to_string();
|
| 433 |
+
|
| 434 |
+
let mut wtxn = self.env.write_txn()?;
|
| 435 |
+
self.sessions.put(&mut wtxn, session_id, &ctx)?;
|
| 436 |
+
wtxn.commit()?;
|
| 437 |
+
Ok(())
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
/// Update session context
|
| 441 |
+
pub fn update_session(&self, ctx: &SessionContext) -> Result<()> {
|
| 442 |
+
let mut wtxn = self.env.write_txn()?;
|
| 443 |
+
self.sessions.put(&mut wtxn, &ctx.session_id, ctx)?;
|
| 444 |
+
wtxn.commit()?;
|
| 445 |
+
Ok(())
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
/// Get session by ID
|
| 449 |
+
pub fn get_session(&self, session_id: &str) -> Result<Option<SessionContext>> {
|
| 450 |
+
let rtxn = self.env.read_txn()?;
|
| 451 |
+
Ok(self.sessions.get(&rtxn, session_id)?)
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
/// Get most recent session
|
| 455 |
+
pub fn get_latest_session(&self) -> Result<Option<SessionContext>> {
|
| 456 |
+
let rtxn = self.env.read_txn()?;
|
| 457 |
+
let iter = self.sessions.iter(&rtxn)?;
|
| 458 |
+
|
| 459 |
+
let mut latest: Option<SessionContext> = None;
|
| 460 |
+
for result in iter {
|
| 461 |
+
let (_, ctx) = result?;
|
| 462 |
+
if latest.as_ref().map_or(true, |l| ctx.started_at > l.started_at) {
|
| 463 |
+
latest = Some(ctx);
|
| 464 |
+
}
|
| 465 |
+
}
|
| 466 |
+
Ok(latest)
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
/// Get session chain (this session and all parents)
|
| 470 |
+
pub fn get_session_chain(&self, session_id: &str) -> Result<Vec<SessionContext>> {
|
| 471 |
+
let mut chain = Vec::new();
|
| 472 |
+
let mut current = session_id.to_string();
|
| 473 |
+
|
| 474 |
+
while let Some(ctx) = self.get_session(¤t)? {
|
| 475 |
+
let parent = ctx.parent_session.clone();
|
| 476 |
+
chain.push(ctx);
|
| 477 |
+
match parent {
|
| 478 |
+
Some(p) => current = p,
|
| 479 |
+
None => break,
|
| 480 |
+
}
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
Ok(chain)
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
/// Record file modification in session
|
| 487 |
+
pub fn record_file_modified(&self, session_id: &str, file_path: &str) -> Result<()> {
|
| 488 |
+
let rtxn = self.env.read_txn()?;
|
| 489 |
+
let mut ctx = self.sessions.get(&rtxn, session_id)?
|
| 490 |
+
.ok_or_else(|| anyhow!("Session not found"))?;
|
| 491 |
+
drop(rtxn);
|
| 492 |
+
|
| 493 |
+
if !ctx.files_modified.contains(&file_path.to_string()) {
|
| 494 |
+
ctx.files_modified.push(file_path.to_string());
|
| 495 |
+
self.update_session(&ctx)?;
|
| 496 |
+
}
|
| 497 |
+
Ok(())
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
/// Increment session counters
|
| 501 |
+
pub fn increment_session_stats(&self, session_id: &str, complexity: u64) -> Result<()> {
|
| 502 |
+
let rtxn = self.env.read_txn()?;
|
| 503 |
+
let mut ctx = self.sessions.get(&rtxn, session_id)?
|
| 504 |
+
.ok_or_else(|| anyhow!("Session not found"))?;
|
| 505 |
+
drop(rtxn);
|
| 506 |
+
|
| 507 |
+
ctx.total_complexity += complexity;
|
| 508 |
+
ctx.total_actions += 1;
|
| 509 |
+
self.update_session(&ctx)
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
// ========================================================================
|
| 513 |
+
// STATE (Key-Value)
|
| 514 |
+
// ========================================================================
|
| 515 |
+
|
| 516 |
+
/// Get a state value
|
| 517 |
+
pub fn get_state(&self, key: &str) -> Result<Option<String>> {
|
| 518 |
+
let rtxn = self.env.read_txn()?;
|
| 519 |
+
Ok(self.state.get(&rtxn, key)?.map(|s| s.to_string()))
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
/// Set a state value
|
| 523 |
+
pub fn set_state(&self, key: &str, value: &str) -> Result<()> {
|
| 524 |
+
let mut wtxn = self.env.write_txn()?;
|
| 525 |
+
self.state.put(&mut wtxn, key, value)?;
|
| 526 |
+
wtxn.commit()?;
|
| 527 |
+
Ok(())
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
/// Get typed state value
|
| 531 |
+
pub fn get_state_typed<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Result<Option<T>> {
|
| 532 |
+
match self.get_state(key)? {
|
| 533 |
+
Some(json) => Ok(Some(serde_json::from_str(&json)?)),
|
| 534 |
+
None => Ok(None),
|
| 535 |
+
}
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
/// Set typed state value
|
| 539 |
+
pub fn set_state_typed<T: Serialize>(&self, key: &str, value: &T) -> Result<()> {
|
| 540 |
+
let json = serde_json::to_string(value)?;
|
| 541 |
+
self.set_state(key, &json)
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
/// Delete a state key
|
| 545 |
+
pub fn delete_state(&self, key: &str) -> Result<bool> {
|
| 546 |
+
let mut wtxn = self.env.write_txn()?;
|
| 547 |
+
let deleted = self.state.delete(&mut wtxn, key)?;
|
| 548 |
+
wtxn.commit()?;
|
| 549 |
+
Ok(deleted)
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
/// List all state keys
|
| 553 |
+
pub fn list_state_keys(&self) -> Result<Vec<String>> {
|
| 554 |
+
let rtxn = self.env.read_txn()?;
|
| 555 |
+
let iter = self.state.iter(&rtxn)?;
|
| 556 |
+
|
| 557 |
+
let mut keys = Vec::new();
|
| 558 |
+
for result in iter {
|
| 559 |
+
let (key, _) = result?;
|
| 560 |
+
keys.push(key.to_string());
|
| 561 |
+
}
|
| 562 |
+
Ok(keys)
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
// ========================================================================
|
| 566 |
+
// PREFERENCES
|
| 567 |
+
// ========================================================================
|
| 568 |
+
|
| 569 |
+
/// Get Agent preferences
|
| 570 |
+
pub fn get_preferences(&self) -> Result<AgentPreferences> {
|
| 571 |
+
self.get_state_typed::<AgentPreferences>("preferences")?
|
| 572 |
+
.ok_or_else(|| anyhow!("Preferences not initialized"))
|
| 573 |
+
.or_else(|_| Ok(AgentPreferences::default()))
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
/// Set Agent preferences
|
| 577 |
+
pub fn set_preferences(&self, prefs: &AgentPreferences) -> Result<()> {
|
| 578 |
+
self.set_state_typed("preferences", prefs)
|
| 579 |
+
}
|
| 580 |
+
|
| 581 |
+
/// Update a single preference
|
| 582 |
+
pub fn set_preference(&self, key: &str, value: &str) -> Result<()> {
|
| 583 |
+
let mut prefs = self.get_preferences()?;
|
| 584 |
+
prefs.custom.insert(key.to_string(), value.to_string());
|
| 585 |
+
self.set_preferences(&prefs)
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
// ========================================================================
|
| 589 |
+
// INITIALIZATION
|
| 590 |
+
// ========================================================================
|
| 591 |
+
|
| 592 |
+
/// Initialize with defaults
|
| 593 |
+
pub fn init_defaults(&self) -> Result<()> {
|
| 594 |
+
// Only init if not already initialized
|
| 595 |
+
if self.get_state("initialized")?.is_some() {
|
| 596 |
+
return Ok(());
|
| 597 |
+
}
|
| 598 |
+
|
| 599 |
+
// Default preferences
|
| 600 |
+
self.set_preferences(&AgentPreferences {
|
| 601 |
+
code_style: None,
|
| 602 |
+
response_length: "adaptive".to_string(),
|
| 603 |
+
show_thinking: false,
|
| 604 |
+
preferred_editor: None,
|
| 605 |
+
auto_save_context: true,
|
| 606 |
+
max_context_entries: 100,
|
| 607 |
+
custom: HashMap::new(),
|
| 608 |
+
})?;
|
| 609 |
+
|
| 610 |
+
// Initial memories
|
| 611 |
+
self.create_memory(
|
| 612 |
+
"SPF Smart Gateway provides AI self-governance with complexity-based enforcement",
|
| 613 |
+
MemoryType::Fact,
|
| 614 |
+
vec!["spf".to_string(), "system".to_string()],
|
| 615 |
+
"system",
|
| 616 |
+
)?;
|
| 617 |
+
|
| 618 |
+
self.create_memory(
|
| 619 |
+
"User prefers concise responses without emojis unless requested",
|
| 620 |
+
MemoryType::Preference,
|
| 621 |
+
vec!["style".to_string()],
|
| 622 |
+
"system",
|
| 623 |
+
)?;
|
| 624 |
+
|
| 625 |
+
self.set_state("initialized", "true")?;
|
| 626 |
+
self.set_state("version", "1.0.0")?;
|
| 627 |
+
|
| 628 |
+
log::info!("Agent State LMDB initialized with defaults");
|
| 629 |
+
Ok(())
|
| 630 |
+
}
|
| 631 |
+
|
| 632 |
+
/// Get context summary for session start
|
| 633 |
+
pub fn get_context_summary(&self) -> Result<String> {
|
| 634 |
+
let mut summary = String::new();
|
| 635 |
+
|
| 636 |
+
// Last session info
|
| 637 |
+
if let Some(last) = self.get_latest_session()? {
|
| 638 |
+
if !last.summary.is_empty() {
|
| 639 |
+
summary.push_str(&format!("Last session: {}\n", last.summary));
|
| 640 |
+
}
|
| 641 |
+
if !last.files_modified.is_empty() {
|
| 642 |
+
summary.push_str(&format!(
|
| 643 |
+
"Files modified: {}\n",
|
| 644 |
+
last.files_modified.len()
|
| 645 |
+
));
|
| 646 |
+
}
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
// Active instructions
|
| 650 |
+
let instructions = self.get_by_type(MemoryType::Instruction)?;
|
| 651 |
+
if !instructions.is_empty() {
|
| 652 |
+
summary.push_str("\nActive instructions:\n");
|
| 653 |
+
for inst in instructions.iter().take(5) {
|
| 654 |
+
summary.push_str(&format!("- {}\n", inst.content));
|
| 655 |
+
}
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
// Recent context
|
| 659 |
+
let context = self.get_by_type(MemoryType::Context)?;
|
| 660 |
+
if !context.is_empty() {
|
| 661 |
+
summary.push_str("\nRecent context:\n");
|
| 662 |
+
for ctx in context.iter().take(3) {
|
| 663 |
+
summary.push_str(&format!("- {}\n", ctx.content));
|
| 664 |
+
}
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
Ok(summary)
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
+
/// Get database stats
|
| 671 |
+
pub fn db_stats(&self) -> Result<(u64, u64, u64, u64)> {
|
| 672 |
+
let rtxn = self.env.read_txn()?;
|
| 673 |
+
let memory_stat = self.memory.stat(&rtxn)?;
|
| 674 |
+
let sessions_stat = self.sessions.stat(&rtxn)?;
|
| 675 |
+
let state_stat = self.state.stat(&rtxn)?;
|
| 676 |
+
let tags_stat = self.tags.stat(&rtxn)?;
|
| 677 |
+
Ok((
|
| 678 |
+
memory_stat.entries as u64,
|
| 679 |
+
sessions_stat.entries as u64,
|
| 680 |
+
state_stat.entries as u64,
|
| 681 |
+
tags_stat.entries as u64,
|
| 682 |
+
))
|
| 683 |
+
}
|
| 684 |
+
}
|