use crate::error::{Error, Result};
use crate::message::{Message, Role};
use rusqlite::{params, Connection, OptionalExtension, TransactionBehavior};
use serde::{Deserialize, Serialize};
use std::io::{Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
pub ts: u64,
pub message: Message,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct TurnCost {
pub at_ms: u64,
pub ctx: String,
#[serde(default)]
pub prompt_tokens: Option<u64>,
#[serde(default)]
pub completion_tokens: Option<u64>,
#[serde(default)]
pub cached_tokens: Option<u64>,
#[serde(default)]
pub ttft_ms: Option<u64>,
#[serde(default)]
pub latency_ms: Option<u64>,
#[serde(default)]
pub tokens_per_sec: Option<f64>,
#[serde(default)]
pub window_tokens: Option<u64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SessionInfo {
pub id: String,
pub messages: usize,
pub updated_ms: u64,
pub preview: String,
pub title: Option<String>,
pub origin: String,
pub pinned: bool,
pub archived: bool,
pub cost: Option<TurnCost>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SubagentOrigin<'a> {
pub parent: &'a str,
pub route: &'a str,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlareRunRow {
pub id: String,
pub task: String,
pub state: String,
pub routes: Vec<String>,
pub jobs: usize,
pub parent: Option<String>,
pub started_ms: u64,
pub finished_ms: Option<u64>,
pub prompt_tokens: Option<u64>,
pub completion_tokens: Option<u64>,
pub iterations: usize,
}
impl FlareRunRow {
pub fn finished(&self) -> bool {
self.finished_ms.is_some()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlareJobRow {
pub run_id: String,
pub n: usize,
pub route: String,
pub session_id: Option<String>,
pub state: String,
pub prompt_tokens: Option<u64>,
pub completion_tokens: Option<u64>,
pub iterations: usize,
pub why: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BotSessions {
pub name: String,
pub sessions: usize,
pub messages: usize,
pub last_session: String,
pub last_activity_ms: u64,
pub archived: bool,
}
const SUBAGENT_ORIGIN: &str = "subagent:";
const BOT_ORIGIN: &str = "bot:";
const FLARE_ORIGIN: &str = "flare:";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlareOrigin<'a> {
pub run: &'a str,
pub n: usize,
}
impl SessionInfo {
pub fn subagent(&self) -> Option<SubagentOrigin<'_>> {
let rest = self.origin.strip_prefix(SUBAGENT_ORIGIN)?;
let (parent, route) = rest.split_once(':')?;
Some(SubagentOrigin { parent, route })
}
pub fn bot(&self) -> Option<&str> {
self.origin
.strip_prefix(BOT_ORIGIN)
.filter(|name| !name.is_empty() && !name.contains(':'))
}
pub fn is_bot(&self) -> bool {
self.bot().is_some()
}
pub fn flare(&self) -> Option<FlareOrigin<'_>> {
let rest = self.origin.strip_prefix(FLARE_ORIGIN)?;
let (run, n) = rest.rsplit_once(':')?;
let n: usize = n.parse().ok()?;
(!run.is_empty() && n > 0).then_some(FlareOrigin { run, n })
}
pub fn is_flare(&self) -> bool {
self.flare().is_some()
}
pub fn tagged_label(&self) -> String {
if let Some(o) = self.subagent() {
return format!("[subagent \u{b7} {}] {}", o.route, self.label());
}
if let Some(name) = self.bot() {
return format!("[bot \u{b7} {name}] {}", self.label());
}
if let Some(f) = self.flare() {
return format!("[flare \u{b7} {}/{}] {}", f.run, f.n, self.label());
}
self.label().to_string()
}
pub fn label(&self) -> &str {
match (&self.title, self.preview.is_empty()) {
(Some(t), _) => t,
(None, false) => &self.preview,
(None, true) => &self.id,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TitleSource {
Derived,
Llm,
User,
}
impl TitleSource {
pub fn as_str(self) -> &'static str {
match self {
TitleSource::Derived => "derived",
TitleSource::Llm => "llm",
TitleSource::User => "user",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportFormat {
Json,
Markdown,
}
const MAX_TITLE_CHARS: usize = 200;
pub const PRUNE_CONFIRM_ABOVE: usize = 10;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutoPrune {
NoLimits,
Nothing,
Pruned {
removed: usize,
failed: usize,
pinned_kept: usize,
},
Skipped { would_remove: usize },
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PrunePlan {
pub candidates: Vec<String>,
pub pinned_kept: usize,
pub archived_kept: usize,
}
#[derive(Serialize, Deserialize)]
struct Meta {
title: String,
}
const MAX_MEMORY_FILE_BYTES: u64 = 64 * 1024;
pub const MEMORY_VERSION: u32 = 3;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Handoff {
pub text: String,
pub version: String,
pub covered_turns: usize,
pub covered_messages: usize,
#[serde(default)]
pub covered_from: Option<u64>,
#[serde(default)]
pub covered_to: Option<u64>,
pub generated_at_ms: u64,
#[serde(default)]
pub judgement: Option<Judgement>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Judgement {
pub text: String,
pub model: String,
pub generated_at_ms: u64,
}
impl Handoff {
pub fn covers(
&self,
turns: usize,
messages: usize,
from: Option<u64>,
to: Option<u64>,
) -> bool {
self.version == crate::compact::VERSION
&& self.covered_turns == turns
&& self.covered_messages == messages
&& match (self.covered_from, self.covered_to, from, to) {
(Some(a), Some(b), Some(c), Some(d)) => a == c && b == d,
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Memory {
#[serde(default)]
pub version: u32,
#[serde(default)]
pub handoff: Option<Handoff>,
}
impl Memory {
pub fn schema(&self) -> u32 {
self.version.max(1)
}
pub fn validate(&self) -> std::result::Result<(), String> {
let schema = self.schema();
if schema > MEMORY_VERSION {
return Err(format!(
"memory schema {schema} is newer than this build understands ({MEMORY_VERSION})"
));
}
if self.handoff.is_some() && schema < 2 {
return Err("a handoff in a v1 memory file".into());
}
if self.handoff.is_none() {
return Err("nothing remembered".into());
}
if let Some(h) = &self.handoff {
if h.text.trim().is_empty() {
return Err("empty handoff".into());
}
if h.text.trim() != h.text {
return Err("handoff is not trimmed".into());
}
if h.covered_turns == 0 || h.covered_messages < h.covered_turns {
return Err("inconsistent handoff counts".into());
}
if let Some(j) = &h.judgement {
if j.text.trim().is_empty() || j.text.trim() != j.text {
return Err("empty or untrimmed judgement".into());
}
}
}
Ok(())
}
pub fn usable_handoff(&self) -> Option<&Handoff> {
self.validate().ok()?;
self.handoff.as_ref()
}
}
#[derive(Clone)]
pub struct SessionStore {
dir: PathBuf,
db: Arc<Mutex<Option<Db>>>,
}
impl std::fmt::Debug for SessionStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionStore")
.field("dir", &self.dir)
.finish()
}
}
pub const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(30);
const LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(50);
#[derive(Debug)]
pub struct SessionLock {
id: String,
_file: std::fs::File,
}
impl SessionLock {
pub fn id(&self) -> &str {
&self.id
}
}
fn goal_state(word: String) -> crate::goals::State {
use crate::goals::State;
match word.as_str() {
"active" => State::Active,
"paused" => State::Paused,
"done" => State::Done,
"blocked" => State::Blocked,
_ => State::Stopped,
}
}
fn open_lock_file(path: &Path) -> Result<std::fs::File> {
let mut opts = std::fs::OpenOptions::new();
opts.create(true).read(true).write(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
opts.open(path).map_err(|e| Error::io(path, e))
}
fn write_lock_holder(file: &mut std::fs::File) {
let text = format!("pid {}\n", std::process::id());
let _ = file.set_len(0);
let _ = file.seek(SeekFrom::Start(0));
let _ = file.write_all(text.as_bytes());
let _ = file.flush();
}
#[cfg(unix)]
fn try_lock_exclusive(file: &std::fs::File) -> std::io::Result<bool> {
use std::os::unix::io::AsRawFd;
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if rc == 0 {
return Ok(true);
}
let err = std::io::Error::last_os_error();
match err.raw_os_error() {
Some(libc::EWOULDBLOCK) => Ok(false),
_ => Err(err),
}
}
#[cfg(not(unix))]
fn try_lock_exclusive(_file: &std::fs::File) -> std::io::Result<bool> {
Ok(true)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeldLock {
pub id: String,
pub holder: String,
}
pub fn held_locks(dir: &Path) -> Vec<HeldLock> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut held = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
let Some(id) = path
.file_name()
.and_then(|n| n.to_str())
.and_then(|n| n.strip_suffix(".lock"))
else {
continue;
};
if validate_id(id).is_err() {
continue;
}
let Ok(file) = std::fs::File::open(&path) else {
continue;
};
if is_locked_by_another(&file) {
let holder = std::fs::read_to_string(&path)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "another process".to_string());
held.push(HeldLock {
id: id.to_string(),
holder,
});
}
}
held.sort_by(|a, b| a.id.cmp(&b.id));
held
}
#[cfg(unix)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StaleLock {
pub path: PathBuf,
pub id: String,
pub holder: String,
}
pub fn stale_locks(dir: &Path) -> Vec<StaleLock> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut stale = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
let Some(id) = path
.file_name()
.and_then(|n| n.to_str())
.and_then(|n| n.strip_suffix(".lock"))
else {
continue;
};
if validate_id(id).is_err() {
continue;
}
let Ok(file) = std::fs::File::open(&path) else {
continue;
};
if is_locked_by_another(&file) {
continue;
}
let holder = std::fs::read_to_string(&path)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "another process".to_string());
let id = id.to_string();
stale.push(StaleLock { path, id, holder });
}
stale.sort_by(|a, b| a.path.cmp(&b.path));
stale
}
fn is_locked_by_another(file: &std::fs::File) -> bool {
use std::os::unix::io::AsRawFd;
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) };
if rc == 0 {
return false;
}
std::io::Error::last_os_error().raw_os_error() == Some(libc::EWOULDBLOCK)
}
#[cfg(not(unix))]
fn is_locked_by_another(_file: &std::fs::File) -> bool {
false
}
static COUNTER: AtomicU64 = AtomicU64::new(0);
pub fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
pub fn ago_words(at_ms: u64) -> String {
if at_ms == 0 {
return String::new();
}
let secs = now_ms().saturating_sub(at_ms) / 1000;
match secs {
0..=59 => "just now".to_string(),
60..=3_599 => format!("{}m ago", secs / 60),
3_600..=86_399 => format!("{}h ago", secs / 3_600),
_ => format!("{}d ago", secs / 86_400),
}
}
pub fn validate_id(id: &str) -> Result<()> {
let ok = !id.is_empty()
&& id.len() <= 64
&& id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
if ok {
Ok(())
} else {
Err(Error::Session(format!("invalid session id {id:?}")))
}
}
impl SessionStore {
pub fn new(dir: impl Into<PathBuf>) -> Self {
Self {
dir: dir.into(),
db: std::sync::Arc::new(std::sync::Mutex::new(None)),
}
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn new_id(&self) -> String {
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
format!("{}-{}-{}", now_ms(), std::process::id(), n)
}
fn lock_path(&self, id: &str) -> Result<PathBuf> {
validate_id(id)?;
Ok(self.dir.join(format!("{id}.lock")))
}
pub(crate) fn with_db<T>(&self, f: impl FnOnce(&mut Db) -> Result<T>) -> Result<T> {
let mut guard = self
.db
.lock()
.map_err(|_| Error::Session("session store is poisoned".into()))?;
if guard.is_none() {
*guard = Some(Db::open(&self.dir)?);
}
f(guard.as_mut().expect("just opened"))
}
pub async fn lock(&self, id: &str, wait: std::time::Duration) -> Result<SessionLock> {
let path = self.lock_path(id)?;
std::fs::create_dir_all(&self.dir).map_err(|e| Error::io(&self.dir, e))?;
let mut file = open_lock_file(&path)?;
let started = std::time::Instant::now();
loop {
match try_lock_exclusive(&file) {
Ok(true) => {
write_lock_holder(&mut file);
return Ok(SessionLock {
id: id.to_string(),
_file: file,
});
}
Ok(false) => {
if started.elapsed() >= wait {
let holder = std::fs::read_to_string(&path)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "another process".to_string());
return Err(Error::Session(format!(
"session {id} is in use by {holder}; waited {}s",
wait.as_secs()
)));
}
tokio::time::sleep(LOCK_POLL).await;
}
Err(e) => return Err(Error::io(&path, e)),
}
}
}
pub fn try_lock(&self, id: &str) -> Result<Option<SessionLock>> {
let path = self.lock_path(id)?;
std::fs::create_dir_all(&self.dir).map_err(|e| Error::io(&self.dir, e))?;
let mut file = open_lock_file(&path)?;
match try_lock_exclusive(&file) {
Ok(true) => {
write_lock_holder(&mut file);
Ok(Some(SessionLock {
id: id.to_string(),
_file: file,
}))
}
Ok(false) => Ok(None),
Err(e) => Err(Error::io(&path, e)),
}
}
pub fn set_goal(&self, goal: &crate::goals::Goal) -> Result<()> {
validate_id(&goal.session)?;
self.with_db(|db| {
let tx = db
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)?;
tx.execute(
"INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
VALUES (?1, ?2, ?2, 0, 'native')
ON CONFLICT(id) DO NOTHING",
params![goal.session, goal.created_ms],
)
.map_err(|e| Error::Session(format!("could not ensure the session row: {e}")))?;
tx.execute(
"INSERT INTO goals
(session_id, text, gate, budget, turns, state, note, garbage,
created_ms, updated_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
ON CONFLICT(session_id) DO UPDATE SET
text = excluded.text, gate = excluded.gate, budget = excluded.budget,
turns = excluded.turns, state = excluded.state, note = excluded.note,
garbage = excluded.garbage, updated_ms = excluded.updated_ms",
params![
goal.session,
goal.text,
goal.gate,
goal.budget as i64,
goal.turns as i64,
goal.state.as_str(),
goal.note,
goal.garbage as i64,
goal.created_ms,
goal.updated_ms,
],
)
.map_err(|e| Error::Session(format!("could not save the goal: {e}")))?;
tx.commit()?;
Ok(())
})
}
pub fn set_plan(&self, session: &str, items: &[crate::plans::Item]) -> Result<u64> {
validate_id(session)?;
let now = now_ms();
self.with_db(|db| {
let tx = db
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)?;
tx.execute(
"INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
VALUES (?1, ?2, ?2, 0, 'native')
ON CONFLICT(id) DO NOTHING",
params![session, now as i64],
)
.map_err(|e| Error::Session(format!("could not ensure the session row: {e}")))?;
tx.execute(
"INSERT INTO plans (session_id, revision, updated_ms) VALUES (?1, 1, ?2)
ON CONFLICT(session_id) DO UPDATE SET
revision = revision + 1,
updated_ms = excluded.updated_ms",
params![session, now as i64],
)
.map_err(|e| Error::Session(format!("could not save the plan: {e}")))?;
let revision: i64 = tx
.query_row(
"SELECT revision FROM plans WHERE session_id = ?1",
params![session],
|r| r.get(0),
)
.map_err(|e| Error::Session(format!("could not read the plan revision: {e}")))?;
tx.execute(
"DELETE FROM plan_items WHERE session_id = ?1",
params![session],
)
.map_err(|e| Error::Session(format!("could not replace the steps: {e}")))?;
for (position, item) in items.iter().enumerate() {
tx.execute(
"INSERT INTO plan_items (session_id, id, content, status, parent, position)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
session,
item.id,
item.content,
item.status.as_str(),
item.parent,
position as i64
],
)
.map_err(|e| Error::Session(format!("could not save step `{}`: {e}", item.id)))?;
}
tx.commit()?;
Ok(revision as u64)
})
}
pub fn plan(&self, session: &str) -> Result<Option<crate::plans::Plan>> {
validate_id(session)?;
self.with_db(|db| {
let revision: Option<i64> = db
.conn
.query_row(
"SELECT revision FROM plans WHERE session_id = ?1",
params![session],
|r| r.get(0),
)
.optional()?;
let Some(revision) = revision else {
return Ok(None);
};
let mut stmt = db.conn.prepare(
"SELECT id, content, status, parent FROM plan_items
WHERE session_id = ?1 ORDER BY position",
)?;
let items = stmt
.query_map(params![session], |r| {
Ok(crate::plans::Item {
id: r.get(0)?,
content: r.get(1)?,
status: crate::plans::Status::parse(&r.get::<_, String>(2)?)
.unwrap_or(crate::plans::Status::Pending),
parent: r.get(3)?,
})
})?
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(Some(crate::plans::Plan {
revision: revision as u64,
items,
}))
})
}
pub fn goal(&self, id: &str) -> Result<Option<crate::goals::Goal>> {
validate_id(id)?;
self.with_db(|db| {
let found = db
.conn
.query_row(
"SELECT text, gate, budget, turns, state, note, garbage, created_ms, updated_ms
FROM goals WHERE session_id = ?1",
params![id],
|r| {
Ok(crate::goals::Goal {
session: id.to_string(),
text: r.get(0)?,
gate: r.get(1)?,
budget: r.get::<_, i64>(2)? as u32,
turns: r.get::<_, i64>(3)? as u32,
state: goal_state(r.get::<_, String>(4)?),
note: r.get(5)?,
garbage: r.get::<_, i64>(6)? != 0,
created_ms: r.get(7)?,
updated_ms: r.get(8)?,
})
},
)
.optional()?;
Ok(found)
})
}
pub fn clear_goal(&self, id: &str) -> Result<()> {
validate_id(id)?;
self.with_db(|db| {
let tx = db
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)?;
tx.execute("DELETE FROM goals WHERE session_id = ?1", params![id])
.map_err(|e| Error::Session(format!("could not clear the goal: {e}")))?;
tx.execute("DELETE FROM goal_turns WHERE session_id = ?1", params![id])
.map_err(|e| Error::Session(format!("could not clear the judgements: {e}")))?;
tx.commit()?;
Ok(())
})
}
pub fn record_goal_turn(&self, id: &str, judgement: &crate::goals::Judgement) -> Result<()> {
validate_id(id)?;
self.with_db(|db| {
db.conn
.execute(
"INSERT INTO goal_turns (session_id, turn, verdict, why, at_ms)
VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(session_id, turn) DO UPDATE SET
verdict = excluded.verdict, why = excluded.why, at_ms = excluded.at_ms",
params![
id,
judgement.turn as i64,
judgement.verdict,
judgement.why,
judgement.at_ms,
],
)
.map_err(|e| Error::Session(format!("could not record the judgement: {e}")))?;
Ok(())
})
}
pub fn goal_turns(&self, id: &str) -> Result<Vec<crate::goals::Judgement>> {
validate_id(id)?;
self.with_db(|db| {
let mut stmt = db
.conn
.prepare(
"SELECT turn, verdict, why, at_ms FROM goal_turns
WHERE session_id = ?1 ORDER BY turn",
)
.map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
let rows = stmt
.query_map(params![id], |r| {
Ok(crate::goals::Judgement {
turn: r.get::<_, i64>(0)? as u32,
verdict: r.get(1)?,
why: r.get(2)?,
at_ms: r.get(3)?,
})
})
.map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
Ok(rows.flatten().collect())
})
}
pub fn live_goals(&self) -> Result<Vec<crate::goals::Goal>> {
self.with_db(|db| {
let mut stmt = db
.conn
.prepare(
"SELECT session_id, text, gate, budget, turns, state, note, garbage,
created_ms, updated_ms
FROM goals WHERE state IN ('active', 'paused') ORDER BY updated_ms DESC",
)
.map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
let rows = stmt
.query_map([], |r| {
Ok(crate::goals::Goal {
session: r.get(0)?,
text: r.get(1)?,
gate: r.get(2)?,
budget: r.get::<_, i64>(3)? as u32,
turns: r.get::<_, i64>(4)? as u32,
state: goal_state(r.get::<_, String>(5)?),
note: r.get(6)?,
garbage: r.get::<_, i64>(7)? != 0,
created_ms: r.get(8)?,
updated_ms: r.get(9)?,
})
})
.map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
Ok(rows.flatten().collect())
})
}
pub fn is_busy(&self, id: &str) -> bool {
match self.try_lock(id) {
Ok(Some(lock)) => {
drop(lock);
false
}
Ok(None) => true,
Err(_) => false,
}
}
pub fn exists(&self, id: &str) -> bool {
if validate_id(id).is_err() {
return false;
}
self.with_db(|db| {
let found: Option<i64> = db
.conn
.query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
r.get(0)
})
.optional()?;
Ok(found.is_some())
})
.unwrap_or(false)
}
pub fn record_pending(
&self,
id: &str,
seq: i64,
calls: &[crate::approvals::Pending],
) -> Result<()> {
self.record_pending_at(id, seq, 0, calls)
}
pub fn record_pending_at(
&self,
id: &str,
seq: i64,
ord: usize,
calls: &[crate::approvals::Pending],
) -> Result<()> {
validate_id(id)?;
self.with_db(|db| {
let tx = db.conn.transaction()?;
for (offset, call) in calls.iter().enumerate() {
tx.execute(
"INSERT INTO approvals
(session_id, seq, ord, call_id, tool, summary, args, decision, decided_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, NULL)
ON CONFLICT(session_id, seq, ord) DO NOTHING",
params![
id,
seq,
(ord + offset) as i64,
call.call_id,
call.tool,
call.summary,
call.args
],
)?;
}
tx.commit()?;
Ok(())
})
}
pub fn pending_calls(&self, id: &str) -> Result<Vec<crate::approvals::PendingCall>> {
validate_id(id)?;
self.with_db(|db| {
let mut stmt = db.conn.prepare(
"SELECT seq, ord, call_id, tool, summary, args, decision, decided_ms, by
FROM approvals WHERE session_id = ?1 ORDER BY seq, ord",
)?;
let rows = stmt
.query_map(params![id], |r| {
let stored: Option<String> = r.get(6)?;
Ok(crate::approvals::PendingCall {
seq: r.get(0)?,
ord: r.get::<_, i64>(1)? as usize,
call: crate::approvals::Pending::new(
r.get::<_, String>(2)?,
r.get::<_, String>(3)?,
r.get::<_, String>(4)?,
r.get::<_, String>(5)?,
),
decision: stored.as_deref().map(crate::approvals::Decision::parse),
decided_ms: r.get(7)?,
by: r.get(8)?,
})
})?
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(rows)
})
}
pub fn decide_pending(
&self,
id: &str,
seq: i64,
ord: usize,
decision: &crate::approvals::Decision,
by: &str,
) -> Result<()> {
validate_id(id)?;
let Some(stored) = decision.store() else {
return Ok(());
};
let now = now_ms() as i64;
let changed = self.with_db(|db| {
let tx = db
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)?;
let changed = tx.execute(
"UPDATE approvals SET decision = ?4, decided_ms = ?5, by = ?6
WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
params![&id, seq, ord as i64, &stored, now, by],
)?;
if changed > 0 {
tx.execute(
"INSERT INTO approval_log
(session_id, at_ms, call_id, tool, summary, decision, by)
SELECT session_id, ?4, call_id, tool, summary, ?5, ?6 FROM approvals
WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
params![&id, seq, ord as i64, now, &stored, by],
)?;
}
tx.commit()?;
Ok(changed)
})?;
if changed == 0 {
return Err(Error::Session(format!(
"{id}: no tool call recorded at message {seq}, position {ord}"
)));
}
Ok(())
}
pub fn log_decision(
&self,
id: &str,
call: &crate::approvals::Pending,
decision: &crate::approvals::Decision,
by: &str,
) -> Result<()> {
validate_id(id)?;
let Some(stored) = decision.store() else {
return Ok(());
};
let now = now_ms() as i64;
self.with_db(|db| {
Ok(db.conn.execute(
"INSERT INTO approval_log (session_id, at_ms, call_id, tool, summary, decision, by)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
id,
now,
&call.call_id,
&call.tool,
&call.summary,
&stored,
by
],
)?)
})?;
Ok(())
}
pub fn approval_log(&self, id: &str) -> Result<Vec<crate::approvals::Ruling>> {
validate_id(id)?;
self.with_db(|db| {
let mut stmt = db.conn.prepare(
"SELECT at_ms, call_id, tool, summary, decision, by FROM approval_log
WHERE session_id = ?1 ORDER BY at_ms, rowid",
)?;
let rows = stmt
.query_map(params![id], |r| {
Ok(crate::approvals::Ruling {
at_ms: r.get(0)?,
call_id: r.get(1)?,
tool: r.get(2)?,
summary: r.get(3)?,
decision: crate::approvals::Decision::parse(&r.get::<_, String>(4)?),
by: r.get(5)?,
})
})?
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(rows)
})
}
pub fn clear_pending(&self, id: &str) -> Result<usize> {
validate_id(id)?;
self.with_db(|db| {
Ok(db
.conn
.execute("DELETE FROM approvals WHERE session_id = ?1", params![id])?)
})
}
pub fn clear_call(&self, id: &str, call_id: &str) -> Result<usize> {
validate_id(id)?;
self.with_db(|db| {
Ok(db.conn.execute(
"DELETE FROM approvals WHERE session_id = ?1 AND call_id = ?2",
params![id, call_id],
)?)
})
}
pub fn last_seq(&self, id: &str) -> Result<i64> {
validate_id(id)?;
self.with_db(|db| {
Ok(db.conn.query_row(
"SELECT COALESCE(MAX(seq), -1) FROM messages WHERE session_id = ?1",
params![id],
|r| r.get(0),
)?)
})
}
pub fn set_tool_outcome(&self, id: &str, call_id: &str, is_error: bool) -> Result<()> {
validate_id(id)?;
let session = id.to_string();
let call = call_id.to_string();
self.with_db(|db| {
db.conn
.execute(
"INSERT INTO tool_outcomes (session_id, call_id, is_error) VALUES (?1, ?2, ?3)
ON CONFLICT (session_id, call_id) DO UPDATE SET is_error = excluded.is_error",
rusqlite::params![session, call, is_error as i64],
)
.map_err(|e| Error::Session(e.to_string()))?;
Ok(())
})
}
pub fn tool_outcomes(&self, id: &str) -> Result<std::collections::HashMap<String, bool>> {
validate_id(id)?;
let session = id.to_string();
self.with_db(|db| {
let mut stmt = db
.conn
.prepare("SELECT call_id, is_error FROM tool_outcomes WHERE session_id = ?1")
.map_err(|e| Error::Session(e.to_string()))?;
let rows = stmt
.query_map(rusqlite::params![session], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? != 0))
})
.map_err(|e| Error::Session(e.to_string()))?;
let mut out = std::collections::HashMap::new();
for row in rows {
let (call, is_error) = row.map_err(|e| Error::Session(e.to_string()))?;
out.insert(call, is_error);
}
Ok(out)
})
}
pub fn append(&self, id: &str, message: &Message) -> Result<()> {
self.append_seq(id, message).map(|_| ())
}
pub fn append_seq(&self, id: &str, message: &Message) -> Result<i64> {
validate_id(id)?;
let now = now_ms() as i64;
let body = serde_json::to_string(message).map_err(|e| Error::Session(e.to_string()))?;
let role = role_name(message.role);
let preview = (message.role == Role::User)
.then(|| {
message
.content
.as_deref()
.map(|t| t.split_whitespace().collect::<Vec<_>>().join(" "))
.map(|t| t.chars().take(60).collect::<String>())
})
.flatten()
.filter(|p| !p.trim().is_empty());
self.with_db(|db| {
let tx = db.conn.transaction()?;
tx.execute(
"INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
VALUES (?1, ?2, ?2, NULL, NULL, 0, 'native')
ON CONFLICT(id) DO NOTHING",
params![id, now],
)?;
let seq: i64 = tx.query_row(
"SELECT COALESCE(MAX(seq), -1) + 1 FROM messages WHERE session_id = ?1",
params![id],
|r| r.get(0),
)?;
tx.execute(
"INSERT INTO messages (session_id, seq, at_ms, role, body)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![id, seq, now, role, body],
)?;
tx.execute(
"UPDATE sessions
SET updated_ms = ?2,
messages = messages + 1,
preview = COALESCE(preview, ?3)
WHERE id = ?1",
params![id, now, preview],
)?;
if db.fts {
tx.execute(
"INSERT INTO messages_fts (session_id, seq, content) VALUES (?1, ?2, ?3)",
params![id, seq, searchable(message)],
)?;
}
tx.commit()?;
Ok(seq)
})
}
pub fn begin_subagent(&self, id: &str, parent: &str, route: &str) -> Result<()> {
validate_id(parent)?;
self.begin_row(id, &format!("{SUBAGENT_ORIGIN}{parent}:{route}"))
}
pub fn begin_flare(&self, id: &str, run: &str, n: usize) -> Result<()> {
if run.is_empty() || run.contains(':') {
return Err(Error::Config(format!(
"a flare run id is one word without a colon, not {run:?}"
)));
}
self.begin_row(id, &format!("{FLARE_ORIGIN}{run}:{n}"))
}
pub fn begin_flare_run(
&self,
id: &str,
task: &str,
routes: &[String],
jobs: usize,
parent: &str,
) -> Result<()> {
let task: String = task.chars().take(500).collect();
self.with_db(|db| {
db.conn.execute(
"INSERT INTO flare_runs (id, task, state, routes, jobs, parent, started_ms)
VALUES (?1, ?2, 'running', ?3, ?4, ?5, ?6)",
params![
id,
task,
routes.join(","),
jobs as i64,
parent,
now_ms() as i64
],
)?;
Ok(())
})
}
pub fn flare_job_running(&self, run: &str, n: usize, route: &str, session: &str) -> Result<()> {
self.with_db(|db| {
db.conn.execute(
"INSERT INTO flare_jobs (run_id, n, route, session_id, state)
VALUES (?1, ?2, ?3, ?4, 'running')
ON CONFLICT(run_id, n) DO UPDATE SET
route = excluded.route, session_id = excluded.session_id,
state = 'running'",
params![run, n as i64, route, session],
)?;
Ok(())
})
}
#[allow(clippy::too_many_arguments)]
pub fn flare_job_done(&self, done: &FlareJobRow) -> Result<()> {
self.with_db(|db| {
db.conn.execute(
"INSERT INTO flare_jobs (run_id, n, route, session_id, state, prompt_tokens,
completion_tokens, iterations, why)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
ON CONFLICT(run_id, n) DO UPDATE SET
route = excluded.route, session_id = excluded.session_id,
state = excluded.state, prompt_tokens = excluded.prompt_tokens,
completion_tokens = excluded.completion_tokens,
iterations = excluded.iterations, why = excluded.why",
params![
done.run_id,
done.n as i64,
done.route,
done.session_id,
done.state,
done.prompt_tokens.map(|v| v as i64),
done.completion_tokens.map(|v| v as i64),
done.iterations as i64,
done.why,
],
)?;
Ok(())
})
}
#[allow(clippy::too_many_arguments)]
pub fn finish_flare_run(
&self,
id: &str,
state: &str,
prompt: Option<u64>,
completion: Option<u64>,
iterations: usize,
) -> Result<()> {
self.with_db(|db| {
db.conn.execute(
"UPDATE flare_runs SET state = ?2, finished_ms = ?3, prompt_tokens = ?4,
completion_tokens = ?5, iterations = ?6
WHERE id = ?1",
params![
id,
state,
now_ms() as i64,
prompt.map(|v| v as i64),
completion.map(|v| v as i64),
iterations as i64
],
)?;
Ok(())
})
}
pub fn cancel_flare_run(&self, id: &str) -> Result<bool> {
self.with_db(|db| {
let n = db.conn.execute(
"UPDATE flare_runs SET cancel_requested = 1 WHERE id = ?1",
params![id],
)?;
Ok(n > 0)
})
}
pub fn flare_cancel_requested(&self, id: &str) -> Result<bool> {
self.with_db(|db| {
let mut stmt = db
.conn
.prepare("SELECT cancel_requested FROM flare_runs WHERE id = ?1")?;
let mut rows = stmt.query(params![id])?;
match rows.next()? {
Some(r) => Ok(r.get::<_, i64>(0)? != 0),
None => Ok(false),
}
})
}
pub fn flare_runs(&self, limit: usize) -> Result<Vec<FlareRunRow>> {
let limit = limit.clamp(1, 200) as i64;
self.with_db(|db| {
let mut stmt = db.conn.prepare(
"SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
prompt_tokens, completion_tokens, iterations
FROM flare_runs ORDER BY started_ms DESC LIMIT ?1",
)?;
let rows = stmt.query_map(params![limit], run_row)?;
Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
})
}
pub fn flare_run(&self, id: &str) -> Result<Option<(FlareRunRow, Vec<FlareJobRow>)>> {
self.with_db(|db| {
let mut stmt = db.conn.prepare(
"SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
prompt_tokens, completion_tokens, iterations
FROM flare_runs WHERE id = ?1",
)?;
let mut rows = stmt.query(params![id])?;
let Some(row) = rows.next()? else {
return Ok(None);
};
let run = run_row(row)?;
let mut stmt = db.conn.prepare(
"SELECT n, route, session_id, state, prompt_tokens, completion_tokens,
iterations, why
FROM flare_jobs WHERE run_id = ?1 ORDER BY n",
)?;
let jobs = stmt
.query_map(params![id], |r| {
Ok(FlareJobRow {
run_id: id.to_string(),
n: r.get::<_, i64>(0)? as usize,
route: r.get(1)?,
session_id: r.get(2)?,
state: r.get(3)?,
prompt_tokens: r.get::<_, Option<i64>>(4)?.map(|v| v as u64),
completion_tokens: r.get::<_, Option<i64>>(5)?.map(|v| v as u64),
iterations: r.get::<_, Option<i64>>(6)?.unwrap_or(0).max(0) as usize,
why: r.get(7)?,
})
})?
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(Some((run, jobs)))
})
}
pub fn flares_of(&self, run: &str) -> Result<Vec<SessionInfo>> {
let prefix = format!("{FLARE_ORIGIN}{run}:");
let mut out: Vec<SessionInfo> = self
.list_rows(true, true)?
.into_iter()
.filter(|s| s.origin.starts_with(&prefix))
.collect();
out.sort_by_key(|s| s.flare().map_or(0, |f| f.n));
Ok(out)
}
pub const API_ORIGIN: &str = "api";
pub fn begin_api(&self, id: &str) -> Result<()> {
self.begin_row(id, Self::API_ORIGIN)
}
pub fn origin(&self, id: &str) -> Result<Option<String>> {
validate_id(id)?;
self.with_db(|db| {
let found = db
.conn
.query_row(
"SELECT origin FROM sessions WHERE id = ?1",
params![id],
|r| r.get::<_, String>(0),
)
.map(Some)
.or_else(|e| match e {
rusqlite::Error::QueryReturnedNoRows => Ok(None),
other => Err(other),
})?;
Ok(found)
})
}
pub fn begin_bot(&self, id: &str, name: &str) -> Result<()> {
self.begin_row(id, &format!("{BOT_ORIGIN}{name}"))
}
pub fn bot_session(&self, name: &str) -> Result<String> {
let origin = format!("{BOT_ORIGIN}{name}");
for info in self.list_rows(true, true)? {
if info.origin == origin && !info.archived {
return Ok(info.id);
}
}
let id = self.new_id();
self.begin_bot(&id, name)?;
Ok(id)
}
pub fn bot_sessions(&self, name: &str) -> Result<Vec<String>> {
let origin = format!("{BOT_ORIGIN}{name}");
Ok(self
.list_rows(true, true)?
.into_iter()
.filter(|info| info.origin == origin && !info.archived)
.map(|info| info.id)
.collect())
}
fn begin_row(&self, id: &str, origin: &str) -> Result<()> {
validate_id(id)?;
let now = now_ms() as i64;
self.with_db(|db| {
db.conn.execute(
"INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
VALUES (?1, ?2, ?2, NULL, NULL, 0, ?3)
ON CONFLICT(id) DO NOTHING",
params![id, now, origin],
)?;
Ok(())
})
}
pub fn prune_api_sessions(&self, cutoff_ms: u64) -> Result<usize> {
let stale: Vec<String> = self
.list()?
.into_iter()
.filter(|s| s.origin == Self::API_ORIGIN && !s.pinned && s.updated_ms < cutoff_ms)
.map(|s| s.id)
.collect();
let mut pruned = 0usize;
for id in stale {
match self.delete(&id) {
Ok(()) => pruned += 1,
Err(Error::Session(_)) => {}
Err(e) => return Err(e),
}
}
Ok(pruned)
}
pub fn load_records(&self, id: &str) -> Result<Vec<Record>> {
validate_id(id)?;
if !self.exists(id) {
return Err(Error::Session(format!("no such session {id:?}")));
}
self.with_db(|db| {
let mut stmt = db.conn.prepare(
"SELECT seq, at_ms, body FROM messages WHERE session_id = ?1 ORDER BY seq",
)?;
let rows = stmt.query_map(params![id], |r| {
Ok((
r.get::<_, i64>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, String>(2)?,
))
})?;
let mut out = Vec::new();
for row in rows {
let (seq, at, body) = row?;
let mut message: Message = serde_json::from_str(&body)
.map_err(|e| Error::Session(format!("{id}:{seq}: {e}")))?;
message.seq = Some(seq.max(0) as u64);
out.push(Record {
ts: at.max(0) as u64,
message,
});
}
Ok(out)
})
}
#[allow(clippy::unnecessary_wraps)] pub fn load(&self, id: &str) -> Result<Vec<Message>> {
Ok(self
.load_records(id)?
.into_iter()
.map(|r| r.message)
.collect())
}
pub fn title(&self, id: &str) -> Result<Option<String>> {
validate_id(id)?;
self.with_db(|db| {
let title: Option<Option<String>> = db
.conn
.query_row(
"SELECT title FROM sessions WHERE id = ?1",
params![id],
|r| r.get(0),
)
.optional()?;
Ok(title.flatten())
})
}
pub fn rename(&self, id: &str, title: &str) -> Result<()> {
validate_id(id)?;
let title = title.trim();
if title.is_empty() {
return Err(Error::Session("title is empty".into()));
}
if title.chars().count() > MAX_TITLE_CHARS {
return Err(Error::Session(format!(
"title is longer than {MAX_TITLE_CHARS} characters"
)));
}
if title.chars().any(char::is_control) {
return Err(Error::Session("title contains control characters".into()));
}
let landed = self.set_title(id, title, TitleSource::User)?;
if !landed {
return Err(Error::Session(format!("no such session {id:?}")));
}
Ok(())
}
pub fn set_title(&self, id: &str, title: &str, source: TitleSource) -> Result<bool> {
validate_id(id)?;
self.with_db(|db| {
let n = db.conn.execute(
"UPDATE sessions SET title = ?2, title_source = ?3, title_note = NULL
WHERE id = ?1
AND (CASE title_source WHEN 'user' THEN 3 WHEN 'llm' THEN 2
WHEN 'derived' THEN 1 ELSE 0 END)
< (CASE ?3 WHEN 'user' THEN 3 WHEN 'llm' THEN 2
WHEN 'derived' THEN 1 ELSE 0 END)",
params![id, title, source.as_str()],
)?;
Ok(n > 0)
})
}
pub fn title_if_unnamed(&self, id: &str, name: &str) -> Result<bool> {
validate_id(id)?;
let name = name.trim();
if name.is_empty() || name.chars().any(char::is_control) {
return Ok(false);
}
self.with_db(|db| {
let n = db.conn.execute(
"UPDATE sessions SET title = ?2, title_source = 'derived'
WHERE id = ?1 AND title IS NULL",
params![id, name],
)?;
Ok(n > 0)
})
}
pub fn claim_title_upgrade(&self, id: &str) -> Result<bool> {
validate_id(id)?;
self.with_db(|db| {
let n = db.conn.execute(
"UPDATE sessions SET title_note = 'trying'
WHERE id = ?1 AND title_source = 'derived' AND title_note IS NULL
AND origin NOT LIKE 'subagent:%' AND origin NOT LIKE 'bot:%'
AND origin NOT LIKE 'flare:%' AND origin <> 'api'",
params![id],
)?;
Ok(n > 0)
})
}
pub fn title_attempt_failed(&self, id: &str, why: &str) -> Result<()> {
validate_id(id)?;
let why: String = why.chars().take(300).collect();
self.with_db(|db| {
db.conn.execute(
"UPDATE sessions SET title_note = ?2 WHERE id = ?1",
params![id, why],
)?;
Ok(())
})
}
pub fn release_title_claim(&self, id: &str) -> Result<()> {
validate_id(id)?;
self.with_db(|db| {
db.conn.execute(
"UPDATE sessions SET title_note = NULL WHERE id = ?1 AND title_note = 'trying'",
params![id],
)?;
Ok(())
})
}
pub fn set_last_cost(&self, id: &str, cost: &TurnCost) -> Result<()> {
validate_id(id)?;
let body = serde_json::to_string(cost)
.map_err(|e| Error::Session(format!("a turn's cost did not encode: {e}")))?;
self.with_db(|db| {
db.conn.execute(
"UPDATE sessions SET last_cost = ?2 WHERE id = ?1",
params![id, body],
)?;
Ok(())
})
}
pub fn set_image_seen(&self, id: &str, seq: u64, index: usize, text: &str) -> Result<bool> {
validate_id(id)?;
let seq = i64::try_from(seq)
.map_err(|_| Error::Session(format!("sequence {seq} is out of range")))?;
self.with_db(|db| {
let tx = db.conn.unchecked_transaction()?;
let row: Option<String> = tx
.query_row(
"SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
params![id, seq],
|r| r.get(0),
)
.optional()?;
let Some(body) = row else {
return Ok(false);
};
let mut message: crate::message::Message = serde_json::from_str(&body)
.map_err(|e| Error::Session(format!("a stored message did not decode: {e}")))?;
let Some(image) = message.images.get_mut(index) else {
return Ok(false);
};
image.seen = Some(text.to_string());
let encoded = serde_json::to_string(&message)
.map_err(|e| Error::Session(format!("a message did not encode: {e}")))?;
let n = tx.execute(
"UPDATE messages SET body = ?3 WHERE session_id = ?1 AND seq = ?2",
params![id, seq, encoded],
)?;
if db.fts {
tx.execute(
"UPDATE messages_fts SET content = ?3 WHERE session_id = ?1 AND seq = ?2",
params![id, seq, searchable(&message)],
)?;
}
tx.commit()?;
Ok(n > 0)
})
}
pub fn last_cost(&self, id: &str) -> Result<Option<TurnCost>> {
validate_id(id)?;
self.with_db(|db| {
let body: Option<String> = db
.conn
.query_row(
"SELECT last_cost FROM sessions WHERE id = ?1",
params![id],
|r| r.get(0),
)
.optional()?
.flatten();
Ok(body.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()))
})
}
pub fn set_pinned(&self, id: &str, pinned: bool) -> Result<()> {
validate_id(id)?;
self.with_db(|db| {
let n = db.conn.execute(
"UPDATE sessions SET pinned = ?2 WHERE id = ?1",
params![id, i64::from(pinned)],
)?;
if n == 0 {
return Err(Error::Session(format!("no such session {id:?}")));
}
Ok(())
})
}
pub fn set_archived(&self, id: &str, archived: bool) -> Result<()> {
validate_id(id)?;
self.with_db(|db| {
let n = db.conn.execute(
"UPDATE sessions SET archived = ?2 WHERE id = ?1",
params![id, i64::from(archived)],
)?;
if n == 0 {
return Err(Error::Session(format!("no such session {id:?}")));
}
Ok(())
})
}
pub fn memory(&self, id: &str) -> Result<Option<Memory>> {
validate_id(id)?;
self.with_db(|db| {
let body: Option<String> = db
.conn
.query_row(
"SELECT body FROM memory WHERE session_id = ?1",
params![id],
|r| r.get(0),
)
.optional()?;
let Some(body) = body else { return Ok(None) };
if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
return Err(Error::Session(format!(
"{id}: memory is larger than {MAX_MEMORY_FILE_BYTES} bytes"
)));
}
serde_json::from_str(&body)
.map(Some)
.map_err(|e| Error::Session(format!("{id}: memory: {e}")))
})
}
pub fn readable_memory(&self, id: &str) -> Option<Memory> {
self.memory(id)
.ok()
.flatten()
.filter(|m| m.validate().is_ok())
}
pub fn save_handoff(
&self,
id: &str,
covered: crate::context::Trimmed,
span: (Option<u64>, Option<u64>),
text: &str,
judgement: Option<Judgement>,
) -> Result<()> {
validate_id(id)?;
let mut memory = self.current(id);
memory.handoff = Some(Handoff {
text: text.to_string(),
version: crate::compact::VERSION.to_string(),
covered_turns: covered.turns,
covered_messages: covered.messages,
covered_from: span.0,
covered_to: span.1,
generated_at_ms: now_ms(),
judgement,
});
self.save_memory(id, &memory)
}
fn current(&self, id: &str) -> Memory {
let mut memory = self.readable_memory(id).unwrap_or(Memory {
version: MEMORY_VERSION,
handoff: None,
});
memory.version = MEMORY_VERSION;
memory
}
pub fn save_memory(&self, id: &str, memory: &Memory) -> Result<()> {
validate_id(id)?;
memory.validate().map_err(Error::Session)?;
if !self.exists(id) {
return Err(Error::Session(format!("no such session {id:?}")));
}
let body = serde_json::to_string(memory).map_err(|e| Error::Session(e.to_string()))?;
if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
return Err(Error::Session(format!(
"{id}: memory would be {} bytes, over the {MAX_MEMORY_FILE_BYTES}-byte record \
limit; store less, or raise `MAX_MEMORY_FILE_BYTES` in both the writer and the \
reader",
body.len()
)));
}
self.with_db(|db| {
db.conn.execute(
"INSERT INTO memory (session_id, body) VALUES (?1, ?2)
ON CONFLICT(session_id) DO UPDATE SET body = ?2",
params![id, body],
)?;
Ok(())
})
}
pub fn delete(&self, id: &str) -> Result<()> {
validate_id(id)?;
self.with_db(|db| {
let tx = db.conn.unchecked_transaction()?;
let n = tx.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
if n == 0 {
return Err(Error::Session(format!("no such session {id:?}")));
}
if db.fts {
tx.execute(
"DELETE FROM messages_fts WHERE session_id = ?1",
params![id],
)?;
}
tx.commit()?;
Ok(())
})?;
for path in [
self.lock_path(id)?,
self.dir.join(format!("{id}.jsonl")),
self.dir.join(format!("{id}.meta.json")),
self.dir.join(format!("{id}.memory.json")),
] {
match std::fs::remove_file(&path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(Error::io(&path, e)),
}
}
Ok(())
}
pub fn prune_candidates(
&self,
keep_days: u64,
keep_count: usize,
now_ms: u64,
include_archived: bool,
) -> Result<PrunePlan> {
if keep_days == 0 && keep_count == 0 {
return Ok(PrunePlan::default());
}
let mut sessions = self.session_ages()?;
sessions.sort_by(|a, b| b.cmp(a));
let cutoff = now_ms.saturating_sub(keep_days.saturating_mul(86_400_000));
let mut plan = PrunePlan::default();
for (i, (last, id, pinned, archived)) in sessions.into_iter().enumerate() {
let over = (keep_count > 0 && i >= keep_count) || (keep_days > 0 && last < cutoff);
if !over {
continue;
}
if pinned {
plan.pinned_kept += 1;
} else if archived && !include_archived {
plan.archived_kept += 1;
} else {
plan.candidates.push(id);
}
}
Ok(plan)
}
fn session_ages(&self) -> Result<Vec<(u64, String, bool, bool)>> {
self.with_db(|db| {
let mut stmt = db.conn.prepare(
"SELECT updated_ms, id, pinned, archived FROM sessions ORDER BY updated_ms",
)?;
let rows = stmt.query_map([], |r| {
let ms: i64 = r.get(0)?;
let id: String = r.get(1)?;
let pinned: i64 = r.get(2)?;
let archived: i64 = r.get(3)?;
Ok((ms.max(0) as u64, id, pinned != 0, archived != 0))
})?;
Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
})
}
pub fn auto_prune(
&self,
keep_days: u64,
keep_count: usize,
now_ms: u64,
protect: Option<&str>,
) -> Result<AutoPrune> {
if keep_days == 0 && keep_count == 0 {
return Ok(AutoPrune::NoLimits);
}
let plan = self.prune_candidates(keep_days, keep_count, now_ms, false)?;
let doomed: Vec<String> = plan
.candidates
.into_iter()
.filter(|id| Some(id.as_str()) != protect)
.collect();
if doomed.is_empty() {
return Ok(AutoPrune::Nothing);
}
if doomed.len() > PRUNE_CONFIRM_ABOVE {
return Ok(AutoPrune::Skipped {
would_remove: doomed.len(),
});
}
let mut removed = 0;
let mut failed = 0;
for id in &doomed {
match self.delete(id) {
Ok(()) => removed += 1,
Err(_) => failed += 1,
}
}
Ok(AutoPrune::Pruned {
removed,
failed,
pinned_kept: plan.pinned_kept,
})
}
pub fn export(&self, id: &str, format: ExportFormat) -> Result<String> {
let records = self.load_records(id)?;
let title = self.title(id).ok().flatten();
match format {
ExportFormat::Json => export_json(id, title, &records),
ExportFormat::Markdown => Ok(export_markdown(id, title.as_deref(), &records)),
}
}
pub fn list(&self) -> Result<Vec<SessionInfo>> {
self.list_rows(false, false)
}
pub fn list_with_archived(&self) -> Result<Vec<SessionInfo>> {
self.list_rows(true, false)
}
pub fn list_bots(&self) -> Result<Vec<BotSessions>> {
let mut out: Vec<BotSessions> = Vec::new();
for info in self.list_rows(true, true)? {
let Some(name) = info.bot() else { continue };
match out.iter_mut().find(|b| b.name == name) {
Some(bot) => {
bot.sessions += 1;
if !info.archived {
bot.archived = false;
}
}
None => out.push(BotSessions {
name: name.to_string(),
sessions: 1,
messages: info.messages,
last_session: info.id.clone(),
last_activity_ms: info.updated_ms,
archived: info.archived,
}),
}
}
Ok(out)
}
fn list_rows(&self, include_archived: bool, include_bots: bool) -> Result<Vec<SessionInfo>> {
self.with_db(|db| {
let mut stmt = db.conn.prepare(
"SELECT id, title, preview, messages, updated_ms, origin, pinned, archived, last_cost
FROM sessions
WHERE (archived = 0 OR ?1) AND (?2 OR origin NOT LIKE 'bot:%')
ORDER BY pinned DESC, updated_ms DESC, rowid DESC",
)?;
let rows = stmt.query_map(
params![i64::from(include_archived), i64::from(include_bots)],
|r| {
let updated: i64 = r.get(4)?;
let messages: i64 = r.get(3)?;
let pinned: i64 = r.get(6)?;
let archived: i64 = r.get(7)?;
let cost: Option<String> = r.get(8)?;
Ok(SessionInfo {
id: r.get(0)?,
title: r.get(1)?,
preview: r.get::<_, Option<String>>(2)?.unwrap_or_default(),
messages: messages.max(0) as usize,
updated_ms: updated.max(0) as u64,
origin: r.get(5)?,
pinned: pinned != 0,
archived: archived != 0,
cost: cost.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()),
})
})?;
Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
})
}
pub fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>> {
self.search_with(query, limit, false)
}
pub fn search_with(
&self,
query: &str,
limit: usize,
include_children: bool,
) -> Result<Vec<SearchHit>> {
let q = query.trim();
if q.is_empty() {
return Ok(Vec::new());
}
let limit = limit.clamp(1, 1000) as i64;
self.with_db(|db| Self::search_in(db, q, limit, db.fts, include_children))
}
fn search_in(
db: &Db,
q: &str,
limit: i64,
use_fts: bool,
include_children: bool,
) -> Result<Vec<SearchHit>> {
let children = i64::from(include_children);
let mut out = Vec::new();
let mut named = db.conn.prepare(
"SELECT id, title, updated_ms FROM sessions
WHERE title LIKE '%' || ?1 || '%' ESCAPE '\\'
AND (?3 = 1 OR (origin NOT LIKE 'bot:%' AND origin NOT LIKE 'flare:%'))
ORDER BY pinned DESC, archived ASC, updated_ms DESC LIMIT ?2",
)?;
let rows = named.query_map(params![like_literal(q), limit, children], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, i64>(2)?,
))
})?;
for row in rows {
let (session_id, title, updated_ms) = row?;
out.push(SearchHit {
session_id,
seq: 0,
at_ms: updated_ms.max(0) as u64,
role: "title".to_string(),
snippet: title,
});
}
let mut budget = limit.saturating_mul(4).max(limit + 8);
loop {
let (found, read) =
Self::message_hits(db, q, limit, budget, use_fts, include_children)?;
let room_to_widen = read >= budget && budget < OWN_TAIL_BUDGET_CAP;
if !found.is_empty() || !room_to_widen {
out.extend(found);
break;
}
budget = (budget * 4).min(OWN_TAIL_BUDGET_CAP);
}
Ok(out)
}
fn message_hits(
db: &Db,
q: &str,
limit: i64,
budget: i64,
use_fts: bool,
include_children: bool,
) -> Result<(Vec<SearchHit>, i64)> {
let children = i64::from(include_children);
let mut found = Vec::new();
let mut read = 0i64;
if use_fts {
let terms: Vec<String> = q
.split_whitespace()
.map(|t| format!("\"{}\"", t.replace('"', "\"\"")))
.collect();
let mut stmt = db.conn.prepare(
"SELECT f.session_id, f.seq, f.content
FROM messages_fts f
JOIN messages m ON m.session_id = f.session_id AND m.seq = f.seq
JOIN sessions s ON s.id = f.session_id
WHERE f.messages_fts MATCH ?1
AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
ORDER BY m.at_ms DESC, m.seq DESC
LIMIT ?2",
)?;
let rows = stmt.query_map(params![terms.join(" "), budget, children], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, String>(2)?,
))
})?;
for row in rows {
let (session_id, seq, content) = row?;
read += 1;
if is_own_tail(&db.conn, &session_id, seq)? {
continue;
}
if let Some(found_hit) = hit(&db.conn, session_id, seq, &content)? {
found.push(found_hit);
if found.len() as i64 >= limit {
break;
}
}
}
} else {
let mut stmt = db.conn.prepare(
"SELECT m.session_id, m.seq, m.body FROM messages m
JOIN sessions s ON s.id = m.session_id
WHERE m.body LIKE '%' || ?1 || '%' ESCAPE '\\'
AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
ORDER BY m.at_ms DESC, m.seq DESC LIMIT ?2",
)?;
let rows = stmt.query_map(params![like_literal(q), budget, children], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, String>(2)?,
))
})?;
for row in rows {
let (session_id, seq, body) = row?;
read += 1;
let message: Message = serde_json::from_str(&body)
.map_err(|e| Error::Session(format!("{session_id}:{seq}: {e}")))?;
if is_own_tail(&db.conn, &session_id, seq)? {
continue;
}
if let Some(found_hit) = hit(&db.conn, session_id, seq, &searchable(&message))? {
found.push(found_hit);
if found.len() as i64 >= limit {
break;
}
}
}
}
Ok((found, read))
}
pub fn has_fts(&self) -> bool {
self.with_db(|db| Ok(db.fts)).unwrap_or(false)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchHit {
pub session_id: String,
pub seq: usize,
pub at_ms: u64,
pub role: String,
pub snippet: String,
}
fn hit(
conn: &Connection,
session_id: String,
seq: i64,
content: &str,
) -> Result<Option<SearchHit>> {
let found: Option<(i64, String)> = conn
.query_row(
"SELECT at_ms, role FROM messages WHERE session_id = ?1 AND seq = ?2",
params![session_id, seq],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.map(Some)
.or_else(|e| match e {
rusqlite::Error::QueryReturnedNoRows => Ok(None),
other => Err(other),
})?;
let Some((at_ms, role)) = found else {
return Ok(None);
};
Ok(Some(SearchHit {
session_id,
seq: seq.max(0) as usize,
at_ms: at_ms.max(0) as u64,
role,
snippet: snippet(content, 160),
}))
}
const OWN_TAIL_TOOL: &str = "session_search";
const OWN_TAIL_LOOKBACK: i64 = 20;
const OWN_TAIL_BUDGET_CAP: i64 = 512;
fn is_own_tail(conn: &Connection, session_id: &str, seq: i64) -> Result<bool> {
let body: Option<String> = conn
.query_row(
"SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
params![session_id, seq],
|r| r.get(0),
)
.map(Some)
.or_else(|e| match e {
rusqlite::Error::QueryReturnedNoRows => Ok(None),
other => Err(other),
})?;
let Some(body) = body else {
return Ok(false);
};
let Ok(message) = serde_json::from_str::<Message>(&body) else {
return Ok(false);
};
if message
.tool_calls
.iter()
.any(|call| call.function.name == OWN_TAIL_TOOL)
{
return Ok(true);
}
let Some(answer_to) = message.tool_call_id.as_deref() else {
return Ok(false);
};
let mut stmt = conn.prepare(
"SELECT body FROM messages
WHERE session_id = ?1 AND seq < ?2 AND role = 'assistant'
ORDER BY seq DESC LIMIT ?3",
)?;
let rows = stmt.query_map(params![session_id, seq, OWN_TAIL_LOOKBACK], |r| {
r.get::<_, String>(0)
})?;
for row in rows {
let Ok(called) = serde_json::from_str::<Message>(&row?) else {
continue;
};
if called
.tool_calls
.iter()
.any(|call| call.id == answer_to && call.function.name == OWN_TAIL_TOOL)
{
return Ok(true);
}
}
Ok(false)
}
fn like_literal(q: &str) -> String {
let mut out = String::with_capacity(q.len());
for c in q.chars() {
if matches!(c, '\\' | '%' | '_') {
out.push('\\');
}
out.push(c);
}
out
}
fn searchable(message: &Message) -> String {
let mut out = message.text_with_pictures();
for call in &message.tool_calls {
if !out.is_empty() {
out.push('\n');
}
out.push_str(&call.function.name);
out.push(' ');
out.push_str(&call.function.arguments);
}
out
}
fn run_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<FlareRunRow> {
let started: i64 = r.get(6)?;
Ok(FlareRunRow {
id: r.get(0)?,
task: r.get(1)?,
state: r.get(2)?,
routes: r
.get::<_, String>(3)?
.split(',')
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect(),
jobs: r.get::<_, i64>(4)?.max(0) as usize,
parent: r.get(5)?,
started_ms: started.max(0) as u64,
finished_ms: r.get::<_, Option<i64>>(7)?.map(|v| v.max(0) as u64),
prompt_tokens: r.get::<_, Option<i64>>(8)?.map(|v| v as u64),
completion_tokens: r.get::<_, Option<i64>>(9)?.map(|v| v as u64),
iterations: r.get::<_, Option<i64>>(10)?.unwrap_or(0).max(0) as usize,
})
}
fn snippet(text: &str, max: usize) -> String {
let one: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
if one.chars().count() <= max {
return one;
}
one.chars().take(max.saturating_sub(1)).collect::<String>() + "…"
}
fn role_name(role: Role) -> &'static str {
match role {
Role::System => "system",
Role::User => "user",
Role::Assistant => "assistant",
Role::Tool => "tool",
}
}
pub(crate) struct Db {
pub(crate) conn: Connection,
fts: bool,
}
impl Db {
fn open(dir: &Path) -> Result<Self> {
std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
}
let path = dir.join(DB_FILE);
let conn = Connection::open(&path).map_err(db_err(&path))?;
let _: String = conn
.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
.map_err(db_err(&path))?;
conn.execute_batch(
"PRAGMA foreign_keys = ON;
PRAGMA synchronous = NORMAL;
PRAGMA busy_timeout = 5000;",
)
.map_err(db_err(&path))?;
conn.execute_batch(SCHEMA).map_err(db_err(&path))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for f in [
path.clone(),
path.with_extension("db-wal"),
path.with_extension("db-shm"),
] {
if f.exists() {
let _ = std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o600));
}
}
}
if !has_column(&conn, "sessions", "pinned").map_err(db_err(&path))? {
conn.execute_batch("ALTER TABLE sessions ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0")
.map_err(db_err(&path))?;
}
if !has_column(&conn, "sessions", "archived").map_err(db_err(&path))? {
conn.execute_batch(
"ALTER TABLE sessions ADD COLUMN archived INTEGER NOT NULL DEFAULT 0",
)
.map_err(db_err(&path))?;
}
if !has_column(&conn, "approvals", "by").map_err(db_err(&path))? {
conn.execute_batch("ALTER TABLE approvals ADD COLUMN by TEXT")
.map_err(db_err(&path))?;
}
if !has_column(&conn, "sessions", "last_cost").map_err(db_err(&path))? {
conn.execute_batch("ALTER TABLE sessions ADD COLUMN last_cost TEXT")
.map_err(db_err(&path))?;
}
let title_source_added =
!has_column(&conn, "sessions", "title_source").map_err(db_err(&path))?;
if title_source_added {
conn.execute_batch(
"ALTER TABLE sessions ADD COLUMN title_source TEXT;
ALTER TABLE sessions ADD COLUMN title_note TEXT;",
)
.map_err(db_err(&path))?;
} else if !has_column(&conn, "sessions", "title_note").map_err(db_err(&path))? {
conn.execute_batch("ALTER TABLE sessions ADD COLUMN title_note TEXT")
.map_err(db_err(&path))?;
}
if title_source_added {
conn.execute_batch("UPDATE sessions SET title_source = 'user' WHERE title IS NOT NULL")
.map_err(db_err(&path))?;
}
let fts = match conn.execute_batch(FTS_SCHEMA) {
Ok(()) => true,
Err(_) => false,
};
let mut db = Self { conn, fts };
let warnings = db.import_legacy(dir)?;
for w in warnings {
eprintln!("warning: {w}");
}
Ok(db)
}
fn import_legacy(&mut self, dir: &Path) -> Result<Vec<String>> {
let rd = match std::fs::read_dir(dir) {
Ok(rd) => rd,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(Error::io(dir, e)),
};
let mut files: Vec<PathBuf> = Vec::new();
for entry in rd.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) == Some("jsonl") {
files.push(path);
}
}
files.sort();
let mut warnings = Vec::new();
let tx = self.conn.transaction().map_err(db_err(dir))?;
for path in files {
let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
if validate_id(id).is_err() {
warnings.push(format!(
"{}: ignoring, not a valid session id",
path.display()
));
continue;
}
let already: Option<i64> = tx
.query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
r.get(0)
})
.optional()
.map_err(db_err(&path))?;
if already.is_some() {
continue;
}
match read_legacy(&path) {
Ok(legacy) => {
let first = legacy.records.first().map(|r| r.ts);
let last = legacy.records.last().map(|r| r.ts);
let mtime = std::fs::metadata(&path)
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map_or(0, |d| d.as_millis() as u64);
let created = first.unwrap_or(mtime) as i64;
let updated = last.unwrap_or(mtime) as i64;
let preview = legacy.preview();
tx.execute(
"INSERT INTO sessions
(id, created_ms, updated_ms, title, preview, messages, origin)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'jsonl')",
params![
id,
created,
updated,
legacy.title,
preview,
legacy.records.len() as i64
],
)
.map_err(db_err(&path))?;
for (i, rec) in legacy.records.iter().enumerate() {
let body = serde_json::to_string(&rec.message)
.map_err(|e| Error::Session(e.to_string()))?;
tx.execute(
"INSERT INTO messages (session_id, seq, at_ms, role, body)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![
id,
i as i64,
rec.ts as i64,
role_name(rec.message.role),
body
],
)
.map_err(db_err(&path))?;
if self.fts {
tx.execute(
"INSERT INTO messages_fts (session_id, seq, content)
VALUES (?1, ?2, ?3)",
params![id, i as i64, searchable(&rec.message)],
)
.map_err(db_err(&path))?;
}
}
if let Some(body) = legacy.memory {
tx.execute(
"INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, ?2)",
params![id, body],
)
.map_err(db_err(&path))?;
}
if let Some(w) = legacy.warning {
warnings.push(w);
}
}
Err(e) => {
warnings.push(format!("{}: not imported: {e}", path.display()));
}
}
}
tx.commit().map_err(db_err(dir))?;
Ok(warnings)
}
}
const DB_FILE: &str = "sessions.db";
pub fn db_path(dir: &Path) -> PathBuf {
dir.join(DB_FILE)
}
const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
created_ms INTEGER NOT NULL,
updated_ms INTEGER NOT NULL,
title TEXT,
preview TEXT,
messages INTEGER NOT NULL DEFAULT 0,
origin TEXT NOT NULL DEFAULT 'native',
pinned INTEGER NOT NULL DEFAULT 0,
archived INTEGER NOT NULL DEFAULT 0,
title_source TEXT,
title_note TEXT,
last_cost TEXT
);
CREATE INDEX IF NOT EXISTS sessions_by_activity ON sessions(updated_ms DESC);
CREATE TABLE IF NOT EXISTS messages (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
seq INTEGER NOT NULL,
at_ms INTEGER NOT NULL,
role TEXT NOT NULL,
body TEXT NOT NULL,
PRIMARY KEY (session_id, seq)
);
CREATE TABLE IF NOT EXISTS memory (
session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
body TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS approvals (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
seq INTEGER NOT NULL,
ord INTEGER NOT NULL,
call_id TEXT NOT NULL,
tool TEXT NOT NULL,
summary TEXT NOT NULL,
args TEXT NOT NULL,
decision TEXT,
decided_ms INTEGER,
PRIMARY KEY (session_id, seq, ord)
);
CREATE INDEX IF NOT EXISTS approvals_by_call ON approvals(session_id, call_id);
-- `#340`: who answered a call, and a log that outlives the row.
--
-- `approvals` is deliberately transient — `clear_call` deletes the row once the answer is in the
-- transcript, because a row left behind would let a resume replay a call that already ran. That
-- makes it the wrong place to ask what the model waved through last week, so the decider goes
-- on the row (who answered *this* waiting call) and every ruling is also appended here, where
-- nothing ever deletes it.
CREATE TABLE IF NOT EXISTS approval_log (
session_id TEXT NOT NULL,
at_ms INTEGER NOT NULL,
call_id TEXT NOT NULL,
tool TEXT NOT NULL,
summary TEXT NOT NULL,
decision TEXT NOT NULL,
by TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS approval_log_by_session ON approval_log(session_id, at_ms);
-- `#447`: how a tool call ended, kept beside the message rather than inside it. A stored `tool`
-- message is the model's wire shape and carries no verdict, so a replayed row used to read the
-- mark off the text and call a failed `read_file` a ✓. The call id is the key the dashboard
-- already joins on.
CREATE TABLE IF NOT EXISTS tool_outcomes (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
call_id TEXT NOT NULL,
is_error INTEGER NOT NULL,
PRIMARY KEY (session_id, call_id)
);
-- `#172`: one standing goal per session, and every judgement made about it. A new table rather
-- than a column, so an older `sessions.db` opens without a migration step and a session that has
-- never had a goal keeps no row at all. The foreign key is the whole of `deleting a session
-- deletes its goal`.
CREATE TABLE IF NOT EXISTS goals (
session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
text TEXT NOT NULL,
gate TEXT,
budget INTEGER NOT NULL,
turns INTEGER NOT NULL DEFAULT 0,
state TEXT NOT NULL,
note TEXT,
garbage INTEGER NOT NULL DEFAULT 0,
created_ms INTEGER NOT NULL,
updated_ms INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS goal_turns (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
turn INTEGER NOT NULL,
verdict TEXT NOT NULL,
why TEXT,
at_ms INTEGER NOT NULL,
PRIMARY KEY (session_id, turn)
);
-- `#657`: the plan — the steps of a job, in priority order, and which one is being done. Two
-- tables for the reason `goals` is two: a status change is then one row updated rather than a blob
-- rewritten, and `position` is the order the model wrote, which means nothing inside a blob and
-- everything to a list. The foreign key is the whole of `deleting a session deletes its plan`.
CREATE TABLE IF NOT EXISTS plans (
session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
revision INTEGER NOT NULL,
updated_ms INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS plan_items (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
id TEXT NOT NULL,
content TEXT NOT NULL,
status TEXT NOT NULL,
parent TEXT,
position INTEGER NOT NULL,
PRIMARY KEY (session_id, id)
);
-- `#171`: a flare run and its N children. A run that cannot be listed after a restart is a run
-- that cannot be cancelled, so the ledger is a table rather than a field on the agent that
-- started it — and it is two tables because the run's cost is a sum over children that may have
-- failed, and a failed child's cost still happened.
CREATE TABLE IF NOT EXISTS flare_runs (
id TEXT PRIMARY KEY,
task TEXT NOT NULL,
state TEXT NOT NULL,
routes TEXT NOT NULL,
jobs INTEGER NOT NULL,
parent TEXT,
started_ms INTEGER NOT NULL,
finished_ms INTEGER,
prompt_tokens INTEGER,
completion_tokens INTEGER,
iterations INTEGER,
cancel_requested INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS flare_runs_by_start ON flare_runs(started_ms DESC);
CREATE TABLE IF NOT EXISTS flare_jobs (
run_id TEXT NOT NULL REFERENCES flare_runs(id) ON DELETE CASCADE,
n INTEGER NOT NULL,
route TEXT NOT NULL,
session_id TEXT,
state TEXT NOT NULL,
prompt_tokens INTEGER,
completion_tokens INTEGER,
iterations INTEGER,
why TEXT,
PRIMARY KEY (run_id, n)
);
";
const FTS_SCHEMA: &str = "
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
session_id UNINDEXED,
seq UNINDEXED,
content
);
";
fn db_err(path: &Path) -> impl Fn(rusqlite::Error) -> Error + '_ {
move |e| Error::Session(format!("{}: {e}", path.display()))
}
fn has_column(conn: &Connection, table: &str, column: &str) -> rusqlite::Result<bool> {
let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
let mut rows = stmt.query([])?;
while let Some(row) = rows.next()? {
let name: String = row.get(1)?;
if name == column {
return Ok(true);
}
}
Ok(false)
}
struct Legacy {
records: Vec<Record>,
title: Option<String>,
memory: Option<String>,
warning: Option<String>,
}
impl Legacy {
fn preview(&self) -> Option<String> {
self.records
.iter()
.find(|r| r.message.role == Role::User)
.and_then(|r| r.message.content.as_deref())
.map(|t| {
let one_line: String = t.split_whitespace().collect::<Vec<_>>().join(" ");
one_line.chars().take(60).collect()
})
}
}
fn read_legacy(path: &Path) -> Result<Legacy> {
let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
let text = String::from_utf8_lossy(&bytes);
let terminated = text.ends_with('\n');
let lines: Vec<&str> = text.lines().collect();
let mut records = Vec::new();
let mut warning = None;
for (i, line) in lines.iter().enumerate() {
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<Record>(line) {
Ok(rec) => records.push(rec),
Err(_) if i + 1 == lines.len() && !terminated => {
warning = Some(format!(
"{}:{}: ignoring truncated trailing line ({} bytes)",
path.display(),
i + 1,
line.len()
));
}
Err(e) => return Err(Error::Session(format!("line {}: {e}", i + 1))),
}
}
let dir = path.parent().unwrap_or(Path::new("."));
let id = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
let title = std::fs::read_to_string(dir.join(format!("{id}.meta.json")))
.ok()
.and_then(|t| serde_json::from_str::<Meta>(&t).ok())
.map(|m| m.title);
let memory = std::fs::read_to_string(dir.join(format!("{id}.memory.json")))
.ok()
.filter(|t| t.len() as u64 <= MAX_MEMORY_FILE_BYTES);
Ok(Legacy {
records,
title,
memory,
warning,
})
}
fn export_json(id: &str, title: Option<String>, records: &[Record]) -> Result<String> {
let doc = serde_json::json!({
"format": "eclipse-session/1",
"id": id,
"title": title,
"messages": records,
});
let mut out = serde_json::to_string_pretty(&doc).map_err(|e| Error::Session(e.to_string()))?;
out.push('\n');
Ok(out)
}
fn fenced(info: &str, text: &str) -> String {
let (mut run, mut longest) = (0usize, 0usize);
for c in text.chars() {
run = if c == '`' { run + 1 } else { 0 };
longest = longest.max(run);
}
let fence = "`".repeat((longest + 1).max(3));
let nl = if text.ends_with('\n') { "" } else { "\n" };
format!("{fence}{info}\n{text}{nl}{fence}\n")
}
fn export_markdown(id: &str, title: Option<&str>, records: &[Record]) -> String {
use std::collections::HashMap;
use std::fmt::Write as _;
let mut out = String::new();
let _ = writeln!(out, "# {}\n", title.unwrap_or(id).replace('\n', " "));
let _ = writeln!(out, "- Session: `{id}`");
let _ = writeln!(out, "- Messages: {}", records.len());
if let Some(first) = records.first() {
let _ = writeln!(out, "- Started: {} UTC", format_utc(first.ts));
}
out.push_str(
"\n_The system prompt is not stored in sessions, so it is not part of this transcript._\n",
);
let mut tool_names: HashMap<&str, &str> = HashMap::new();
for r in records {
for c in &r.message.tool_calls {
tool_names.insert(&c.id, &c.function.name);
}
}
let mut answered: std::collections::HashSet<&str> = std::collections::HashSet::new();
for r in records {
if let Some(id) = r.message.tool_call_id.as_deref() {
answered.insert(id);
}
}
for (i, r) in records.iter().enumerate() {
let m = &r.message;
let who = match m.role {
Role::System => "System".to_string(),
Role::User => "User".to_string(),
Role::Assistant => "Assistant".to_string(),
Role::Tool => {
let name = m
.tool_call_id
.as_deref()
.and_then(|c| tool_names.get(c).copied())
.unwrap_or("unknown tool");
format!("Tool result: {name}")
}
};
let _ = writeln!(out, "\n## {}. {who} ({} UTC)\n", i + 1, format_utc(r.ts));
match m.role {
Role::Tool => out.push_str(&fenced("", &m.text_with_pictures())),
_ => {
let text = m.text_with_pictures();
if !text.is_empty() {
out.push_str(&text);
out.push('\n');
}
}
}
for c in &m.tool_calls {
let args = &c.function.arguments;
let _ = writeln!(
out,
"\n**Tool call** `{}` (id `{}`){}\n",
c.function.name.replace('`', "'"),
c.id.replace('`', "'"),
if answered.contains(c.id.as_str()) {
""
} else {
" - no result recorded"
}
);
match serde_json::from_str::<serde_json::Value>(args) {
Ok(v) => out.push_str(&fenced(
"json",
&serde_json::to_string_pretty(&v).unwrap_or_else(|_| args.clone()),
)),
Err(_) => out.push_str(&fenced("", args)),
}
}
}
out
}
pub fn format_utc(ms: u64) -> String {
let secs = ms / 1000;
let days = (secs / 86_400) as i64;
let rem = secs % 86_400;
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!(
"{y:04}-{m:02}-{d:02} {:02}:{:02}",
rem / 3600,
rem % 3600 / 60
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::message::{FunctionCall, ToolCall};
fn store(dir: &Path) -> SessionStore {
SessionStore::new(dir.join("sessions"))
}
fn call(id: &str, name: &str, args: &str) -> ToolCall {
ToolCall {
id: id.into(),
kind: "function".into(),
function: FunctionCall {
name: name.into(),
arguments: args.into(),
},
}
}
fn transcript(store: &SessionStore, id: &str) {
store.append(id, &Message::user("hello there")).unwrap();
store
.append(
id,
&Message::assistant_tool_calls(
Some("let me look".into()),
vec![call("c1", "read_file", r#"{"path":"a.txt"}"#)],
),
)
.unwrap();
store
.append(id, &Message::tool_result("c1", "file contents"))
.unwrap();
store.append(id, &Message::assistant("done")).unwrap();
}
#[test]
fn a_tool_outcome_is_recorded_beside_the_call_and_read_back() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().to_path_buf());
let id = store.new_id();
store.append(&id, &Message::user("read it")).unwrap();
assert!(
store.tool_outcomes(&id).unwrap().is_empty(),
"nothing recorded is an empty map, not an error"
);
store.set_tool_outcome(&id, "c1", true).unwrap();
store.set_tool_outcome(&id, "c2", false).unwrap();
store.set_tool_outcome(&id, "c1", true).unwrap();
let marks = store.tool_outcomes(&id).unwrap();
assert_eq!(
marks.len(),
2,
"the second write is the same write: {marks:?}"
);
assert_eq!(marks.get("c1"), Some(&true));
assert_eq!(marks.get("c2"), Some(&false));
}
fn seed(store: &SessionStore, id: &str, updated_ms: u64) {
store
.with_db(|db| {
db.conn.execute(
"INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
VALUES (?1, ?2, ?2, NULL, 'seeded', 1, 'native')",
params![id, updated_ms as i64],
)?;
Ok(())
})
.unwrap();
}
fn legacy_file(dir: &Path, id: &str, body: &str) -> PathBuf {
std::fs::create_dir_all(dir).unwrap();
let path = dir.join(format!("{id}.jsonl"));
std::fs::write(&path, body).unwrap();
path
}
fn line(m: &Message, ts: u64) -> String {
let rec = Record {
ts,
message: m.clone(),
};
format!("{}\n", serde_json::to_string(&rec).unwrap())
}
#[test]
fn append_and_load_round_trip() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
assert!(!store.exists(&id), "a store knows only what was written");
transcript(&store, &id);
assert!(store.exists(&id));
let messages = store.load(&id).unwrap();
assert_eq!(messages.len(), 4);
assert_eq!(messages[0], Message::user("hello there"));
assert_eq!(messages[1].tool_calls.len(), 1);
assert_eq!(messages[1].tool_calls[0].function.name, "read_file");
assert_eq!(messages[1].content.as_deref(), Some("let me look"));
assert_eq!(messages[2].tool_call_id.as_deref(), Some("c1"));
assert_eq!(messages[2].content.as_deref(), Some("file contents"));
assert_eq!(messages[3], Message::assistant("done"));
}
#[test]
fn every_message_is_one_row_in_order() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
let records = store.load_records(&id).unwrap();
let seqs: Vec<usize> = store
.with_db(|db| {
let mut stmt = db
.conn
.prepare("SELECT seq FROM messages WHERE session_id = ?1 ORDER BY seq")?;
let rows = stmt.query_map(params![id], |r| r.get::<_, i64>(0))?;
Ok(rows
.collect::<std::result::Result<Vec<_>, _>>()?
.into_iter()
.map(|s| s as usize)
.collect())
})
.unwrap();
assert_eq!(seqs, [0, 1, 2, 3], "sequence numbers are dense and ordered");
assert_eq!(records.len(), 4);
assert!(
records.windows(2).all(|w| w[0].ts <= w[1].ts),
"timestamps do not run backwards"
);
}
#[test]
fn data_survives_a_new_store_handle() {
let dir = tempfile::tempdir().unwrap();
let id;
{
let first = store(dir.path());
id = first.new_id();
transcript(&first, &id);
first.rename(&id, "kept title").unwrap();
}
let second = store(dir.path());
assert_eq!(second.load(&id).unwrap().len(), 4);
assert_eq!(second.title(&id).unwrap().as_deref(), Some("kept title"));
}
#[test]
fn list_orders_newest_first_with_preview() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let a = store.new_id();
store
.append(&a, &Message::user("the older question"))
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(5));
let b = store.new_id();
store
.append(&b, &Message::user("the newer question"))
.unwrap();
let list = store.list().unwrap();
assert_eq!(list.len(), 2);
assert_eq!(list[0].id, b, "newest first");
assert_eq!(list[0].preview, "the newer question");
assert_eq!(list[0].messages, 1);
assert_eq!(list[1].id, a);
assert_eq!(list[0].label(), "the newer question");
}
#[test]
fn the_preview_is_the_first_user_message_not_the_latest() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store.append(&id, &Message::user("first thing")).unwrap();
store.append(&id, &Message::user("second thing")).unwrap();
let info = store.list().unwrap().into_iter().next().unwrap();
assert_eq!(info.preview, "first thing");
assert_eq!(info.messages, 2);
}
#[test]
fn prune_candidates_by_age_and_count() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let now = 1_700_000_000_000u64;
let day = 86_400_000u64;
seed(&store, "old", now - 10 * day);
seed(&store, "mid", now - 2 * day);
seed(&store, "new", now - day / 24);
assert_eq!(
store.prune_candidates(3, 0, now, false).unwrap().candidates,
["old"],
"older than three days"
);
assert_eq!(
store.prune_candidates(0, 2, now, false).unwrap().candidates,
["old"],
"all but the newest two"
);
let both = store.prune_candidates(3, 10, now, false).unwrap();
assert_eq!(
both.candidates,
["old"],
"a session selected by either rule is pruned once"
);
assert!(store
.prune_candidates(0, 0, now, false)
.unwrap()
.candidates
.is_empty());
}
#[test]
fn a_pinned_session_sorts_first_and_is_never_a_prune_candidate() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let now = 1_700_000_000_000u64;
seed(&store, "oldest", now - 10 * 86_400_000);
seed(&store, "newest", now - 86_400_000);
store.set_pinned("oldest", true).unwrap();
let list = store.list().unwrap();
assert_eq!(list[0].id, "oldest", "pinned first, whatever the age");
assert!(list[0].pinned);
assert!(!list[1].pinned);
let plan = store.prune_candidates(7, 0, now, false).unwrap();
assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
assert_eq!(plan.pinned_kept, 1);
let outcome = store.auto_prune(7, 0, now, None).unwrap();
assert_eq!(outcome, AutoPrune::Nothing);
assert!(store.exists("oldest"));
store.set_pinned("oldest", false).unwrap();
assert_eq!(
store.prune_candidates(7, 0, now, false).unwrap().candidates,
["oldest"]
);
assert!(!store.list().unwrap()[0].pinned, "unpinning is not sticky");
}
#[test]
fn an_archived_session_leaves_the_list_and_stays_in_the_search() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let now = 1_700_000_000_000u64;
seed(&store, "kept", now - 86_400_000);
seed(&store, "filed", now - 10 * 86_400_000);
store.rename("filed", "the nginx migration").unwrap();
store
.append("filed", &Message::user("the zfs pool was rebuilt"))
.unwrap();
store
.with_db(|db| {
db.conn.execute(
"UPDATE sessions SET updated_ms = ?2 WHERE id = ?1",
params!["filed", (now - 10 * 86_400_000) as i64],
)?;
Ok(())
})
.unwrap();
store.set_archived("filed", true).unwrap();
let listed = store.list().unwrap();
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].id, "kept");
let all = store.list_with_archived().unwrap();
assert_eq!(all.len(), 2);
assert!(all.iter().find(|s| s.id == "filed").unwrap().archived);
assert!(!all.iter().find(|s| s.id == "kept").unwrap().archived);
assert!(
store
.search("nginx", 20)
.unwrap()
.iter()
.any(|h| h.session_id == "filed"),
"a name hit survives archiving"
);
assert!(
store
.search("zfs", 20)
.unwrap()
.iter()
.any(|h| h.session_id == "filed"),
"a message hit survives archiving"
);
assert_eq!(
store.load("filed").unwrap().len(),
1,
"the transcript is there"
);
let plan = store.prune_candidates(7, 0, now, false).unwrap();
assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
assert_eq!(plan.archived_kept, 1);
assert_eq!(
plan.pinned_kept, 0,
"counted apart, so the sentence can differ"
);
assert_eq!(
store.prune_candidates(7, 0, now, true).unwrap().candidates,
["filed"]
);
assert_eq!(
store.auto_prune(7, 0, now, None).unwrap(),
AutoPrune::Nothing
);
store.set_archived("filed", false).unwrap();
assert_eq!(store.list().unwrap().len(), 2);
assert!(matches!(
store.set_archived("nope", true),
Err(Error::Session(_))
));
}
#[test]
fn a_database_from_before_archiving_gains_the_column_in_place() {
let dir = tempfile::tempdir().unwrap();
{
let dir = dir.path().join("sessions");
std::fs::create_dir_all(&dir).unwrap();
let conn = Connection::open(dir.join(DB_FILE)).unwrap();
conn.execute_batch(
"CREATE TABLE sessions (
id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
origin TEXT NOT NULL DEFAULT 'native');
INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
)
.unwrap();
}
let store = store(dir.path());
let list = store.list().unwrap();
assert_eq!(
list.len(),
1,
"the old row is in the list, not archived by omission"
);
assert!(!list[0].archived);
store.set_archived("s1", true).unwrap();
assert!(store.list().unwrap().is_empty());
assert!(store.list_with_archived().unwrap()[0].archived);
}
#[test]
fn a_database_from_before_pinning_gains_the_column_in_place() {
let dir = tempfile::tempdir().unwrap();
let id;
{
let dir = dir.path().join("sessions");
std::fs::create_dir_all(&dir).unwrap();
let conn = Connection::open(dir.join(DB_FILE)).unwrap();
conn.execute_batch(
"CREATE TABLE sessions (
id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
origin TEXT NOT NULL DEFAULT 'native');
INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
)
.unwrap();
id = "s1".to_string();
}
let store = store(dir.path());
let list = store.list().unwrap();
assert_eq!(list.len(), 1, "the old row still reads");
assert_eq!(list[0].id, id);
assert!(!list[0].pinned, "an old row is not pinned");
store.set_pinned(&id, true).unwrap();
assert!(store.list().unwrap()[0].pinned);
assert_eq!(
store
.prune_candidates(0, 1, 1_700_000_000_000, false)
.unwrap(),
PrunePlan::default(),
"one session, newest one kept"
);
}
#[test]
fn a_database_from_before_the_cost_record_gains_the_column_in_place() {
let dir = tempfile::tempdir().unwrap();
{
let dir = dir.path().join("sessions");
std::fs::create_dir_all(&dir).unwrap();
let conn = Connection::open(dir.join(DB_FILE)).unwrap();
conn.execute_batch(
"CREATE TABLE sessions (
id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
origin TEXT NOT NULL DEFAULT 'native');
INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
)
.unwrap();
}
let store = store(dir.path());
assert!(
store.last_cost("s1").unwrap().is_none(),
"an old row has no turn behind it, and no record is not a zero"
);
let prompt = 1_234_u64;
let cost = TurnCost {
at_ms: 7,
ctx: "ctx 1.2K/8K ░░░░░░░░░░│░ 15%".to_string(),
prompt_tokens: Some(prompt),
..TurnCost::default()
};
store.set_last_cost("s1", &cost).unwrap();
assert_eq!(store.last_cost("s1").unwrap(), Some(cost));
}
#[test]
fn a_turn_writes_its_cost_and_the_listing_reads_it_back() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
assert!(
store.list().unwrap()[0].cost.is_none(),
"a session with no finished turn has nothing to say about one"
);
let prompt = 30_000_u64;
let cached = 28_000_u64;
let cost = TurnCost {
at_ms: 1_700_000_000_000,
ctx: "ctx 30K/262K ██░░░░░░░░│░ 11%".to_string(),
prompt_tokens: Some(prompt),
completion_tokens: Some(400),
cached_tokens: Some(cached),
ttft_ms: Some(800),
latency_ms: Some(13_000),
tokens_per_sec: Some(63.0),
window_tokens: Some(262_144),
};
store.set_last_cost(&id, &cost).unwrap();
let listed = &store.list().unwrap()[0];
assert_eq!(listed.cost.as_ref(), Some(&cost));
let ctx = listed
.cost
.as_ref()
.map(|c| c.ctx.as_str())
.unwrap_or_default();
assert!(
ctx.contains("262K"),
"the denominator the listing carries is the one that turn ran against: {ctx:?}"
);
}
#[test]
fn recording_a_cost_does_not_move_the_session_up_the_list() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let older = store.new_id();
let newer = store.new_id();
transcript(&store, &older);
transcript(&store, &newer);
let before: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
let target = before.last().expect("two sessions").clone();
store
.set_last_cost(
&target,
&TurnCost {
at_ms: 1,
ctx: "ctx --".to_string(),
..TurnCost::default()
},
)
.unwrap();
let after: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
assert_eq!(
before, after,
"the order is the store's, and a cost is not a move"
);
}
#[test]
fn a_persons_name_outranks_the_machines_and_outlives_a_later_attempt() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
assert!(
store.title_if_unnamed(&id, "the opening message").unwrap(),
"nothing names it yet, so the derived name lands"
);
assert!(
!store
.title_if_unnamed(&id, "a second derived name")
.unwrap(),
"stage one never relabels a session it has already named"
);
assert_eq!(
store.title(&id).unwrap().as_deref(),
Some("the opening message")
);
assert!(
store
.set_title(&id, "the model's name", TitleSource::Llm)
.unwrap(),
"a model name replaces a derived one"
);
assert!(
!store
.set_title(&id, "a second model name", TitleSource::Llm)
.unwrap(),
"one naming call means one name: it is not renamed by trying again"
);
store.rename(&id, "what I called it").unwrap();
for source in [TitleSource::Llm, TitleSource::Derived] {
assert!(
!store.set_title(&id, "the machine again", source).unwrap(),
"a person's name is final to {source:?}"
);
}
assert_eq!(
store.title(&id).unwrap().as_deref(),
Some("what I called it")
);
assert_eq!(
store.list().unwrap()[0].label(),
"what I called it",
"and the listing shows it"
);
}
#[test]
fn the_naming_attempt_is_claimed_once_per_session() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
store.title_if_unnamed(&id, "a derived name").unwrap();
assert!(
store.claim_title_upgrade(&id).unwrap(),
"the first caller owns it"
);
assert!(
!store.claim_title_upgrade(&id).unwrap(),
"and nobody else does"
);
store
.title_attempt_failed(&id, "the reply was not a JSON object")
.unwrap();
assert!(
!store.claim_title_upgrade(&id).unwrap(),
"a refused answer is not retried on the next run"
);
assert_eq!(
store.title(&id).unwrap().as_deref(),
Some("a derived name"),
"and the name is still there: a failure never leaves it empty"
);
let other = store.new_id();
transcript(&store, &other);
store.title_if_unnamed(&other, "another name").unwrap();
assert!(store.claim_title_upgrade(&other).unwrap());
store.release_title_claim(&other).unwrap();
assert!(
store.claim_title_upgrade(&other).unwrap(),
"released, not failed"
);
}
#[test]
fn a_delegated_child_session_is_never_named_by_a_call() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let parent = store.new_id();
let child = store.new_id();
store.append(&parent, &Message::user("big job")).unwrap();
store.begin_subagent(&child, &parent, "fast").unwrap();
store
.append(&child, &Message::user("summarise this"))
.unwrap();
store.title_if_unnamed(&child, "summarise this").unwrap();
assert!(
!store.claim_title_upgrade(&child).unwrap(),
"a child is named by its opening message and left alone"
);
let api = store.new_id();
store.begin_api(&api).unwrap();
store.append(&api, &Message::user("headless turn")).unwrap();
store.title_if_unnamed(&api, "headless turn").unwrap();
assert!(
!store.claim_title_upgrade(&api).unwrap(),
"a headless API session is named for free and never costs a call"
);
}
#[test]
fn a_search_finds_a_session_by_the_name_it_was_given() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store
.append(&id, &Message::user("something else entirely"))
.unwrap();
store.append(&id, &Message::assistant("noted")).unwrap();
store.rename(&id, "gateway restart loop").unwrap();
for fts in [true, false] {
let hits = store
.with_db(|db| SessionStore::search_in(db, "restart loop", 10, fts, false))
.unwrap();
let named: Vec<_> = hits.iter().filter(|h| h.role == "title").collect();
assert_eq!(named.len(), 1, "fts={fts}: {:?}", hits);
assert_eq!(named[0].session_id, id);
assert_eq!(named[0].snippet, "gateway restart loop");
assert_eq!(
named[0].seq, 0,
"a name is read from the top of the transcript"
);
}
let hits = store.search("noted", 10).unwrap();
assert!(hits.iter().all(|h| h.role != "title"));
assert_eq!(hits.len(), 1);
}
#[test]
fn a_page_of_the_tools_own_calls_does_not_hide_the_match_behind_them() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store
.append(&id, &Message::user("the needle is here"))
.unwrap();
for i in 0..12 {
let call = crate::message::ToolCall {
id: format!("call-{i}"),
kind: "function".to_string(),
function: crate::message::FunctionCall {
name: "session_search".to_string(),
arguments: "{\"query\":\"needle\"}".to_string(),
},
};
store
.append(&id, &Message::assistant_tool_calls(None, vec![call]))
.unwrap();
store
.append(
&id,
&Message::tool_result(format!("call-{i}"), "archive: no match for needle"),
)
.unwrap();
}
for fts in [true, false] {
let hits = store
.with_db(|db| SessionStore::search_in(db, "needle", 1, fts, false))
.unwrap();
assert_eq!(hits.len(), 1, "fts={fts}: {hits:?}");
assert_eq!(hits[0].role, "user", "fts={fts}: {hits:?}");
}
}
#[test]
fn a_database_from_before_names_keeps_its_titles_and_learns_who_wrote_them() {
let dir = tempfile::tempdir().unwrap();
{
let dir = dir.path().join("sessions");
std::fs::create_dir_all(&dir).unwrap();
let conn = Connection::open(dir.join(DB_FILE)).unwrap();
conn.execute_batch(
"CREATE TABLE sessions (
id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
origin TEXT NOT NULL DEFAULT 'native', pinned INTEGER NOT NULL DEFAULT 0);
INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
VALUES ('named', 1, 2, 'what I called it', 'first words', 2, 'native'),
('bare', 1, 2, NULL, 'first words', 2, 'native');",
)
.unwrap();
}
let store = store(dir.path());
let list = store.list().unwrap();
let named = list.iter().find(|s| s.id == "named").unwrap();
assert_eq!(
named.title.as_deref(),
Some("what I called it"),
"the title survives"
);
assert!(
!store.title_if_unnamed("named", "a derived name").unwrap(),
"an old title is a person's, so stage one leaves it"
);
assert!(
!store.claim_title_upgrade("named").unwrap(),
"and no call is spent on it either"
);
assert!(
store.title_if_unnamed("bare", "a derived name").unwrap(),
"a session that had no name gets one"
);
assert_eq!(
store.title("bare").unwrap().as_deref(),
Some("a derived name")
);
}
#[test]
fn deleting_a_session_removes_its_title_memory_and_lock_file() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("sessions");
let store = store(dir.path());
let a = store.new_id();
let b = store.new_id();
transcript(&store, &a);
transcript(&store, &b);
store.rename(&a, "doomed").unwrap();
store
.save_memory(&a, &memory("## Log\na summary", 2, 3))
.unwrap();
store
.with_db(|db| {
db.conn.execute(
"INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, '{}')",
params![a],
)?;
Ok(())
})
.unwrap();
let lock = root.join(format!("{a}.lock"));
std::fs::write(&lock, "pid 1\n").unwrap();
store.delete(&a).unwrap();
assert!(!store.exists(&a));
assert!(store.exists(&b), "the other session is untouched");
assert!(store.load(&b).unwrap().len() == 4);
assert_eq!(store.memory(&a).unwrap(), None);
assert!(!lock.exists(), "the lock file does not outlive the session");
assert!(store.delete(&a).is_err(), "deleting twice is an error");
}
#[test]
fn auto_prune_deletes_up_to_ten_sessions_and_refuses_more() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let now = 1_700_000_000_000u64;
for i in 0..12 {
seed(&store, &format!("s{i:02}"), now - (100 - i) * 86_400_000);
}
assert_eq!(
store.auto_prune(30, 0, now, None).unwrap(),
AutoPrune::Skipped { would_remove: 12 }
);
assert_eq!(store.list().unwrap().len(), 12);
assert_eq!(
store.auto_prune(0, 2, now, None).unwrap(),
AutoPrune::Pruned {
removed: 10,
failed: 0,
pinned_kept: 0
}
);
assert_eq!(store.list().unwrap().len(), 2);
}
#[test]
fn auto_prune_never_runs_without_a_limit_and_reports_nothing_to_do() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let now = 1_700_000_000_000u64;
assert_eq!(
store.auto_prune(0, 0, now, None).unwrap(),
AutoPrune::NoLimits
);
seed(&store, "fresh", now);
assert_eq!(
store.auto_prune(30, 0, now, None).unwrap(),
AutoPrune::Nothing
);
assert_eq!(store.list().unwrap().len(), 1);
}
#[test]
fn auto_prune_spares_the_protected_session() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let now = 1_700_000_000_000u64;
seed(&store, "keep-me", now - 90 * 86_400_000);
seed(&store, "old-1", now - 90 * 86_400_000);
let outcome = store.auto_prune(7, 0, now, Some("keep-me")).unwrap();
assert_eq!(
outcome,
AutoPrune::Pruned {
removed: 1,
failed: 0,
pinned_kept: 0
}
);
assert!(
store.exists("keep-me"),
"the session being resumed survives"
);
assert!(!store.exists("old-1"));
}
#[test]
fn rejects_path_traversal_ids() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
for bad in ["../etc/passwd", "a/b", "", "sp ace", "dot.dot"] {
assert!(
store.load(bad).is_err(),
"{bad:?} must be refused before it reaches the database"
);
assert!(!store.exists(bad));
}
}
#[test]
fn a_corrupt_row_is_reported_with_its_session_and_position() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
store
.with_db(|db| {
db.conn.execute(
"INSERT INTO messages (session_id, seq, at_ms, role, body)
VALUES (?1, 99, 0, 'user', '{not json')",
params![id],
)?;
Ok(())
})
.unwrap();
let err = store.load(&id).unwrap_err().to_string();
assert!(err.contains(&id) && err.contains("99"), "{err}");
}
#[test]
fn new_ids_are_unique() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let ids: std::collections::HashSet<String> = (0..50).map(|_| store.new_id()).collect();
assert_eq!(ids.len(), 50);
for id in &ids {
validate_id(id).unwrap();
}
}
#[test]
fn utc_formatting() {
assert_eq!(format_utc(0), "1970-01-01 00:00");
assert_eq!(format_utc(1_700_000_000_000), "2023-11-14 22:13");
}
#[test]
fn rename_sets_title_without_touching_the_transcript() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
let before = store.load(&id).unwrap();
store.rename(&id, " a name ").unwrap();
assert_eq!(store.title(&id).unwrap().as_deref(), Some("a name"));
assert_eq!(store.load(&id).unwrap(), before);
let listed = store.list().unwrap().into_iter().next().unwrap();
assert_eq!(listed.label(), "a name", "the title wins over the preview");
}
#[test]
fn rename_rejects_bad_titles_and_unknown_sessions() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
for bad in ["", " "] {
assert!(store.rename(&id, bad).is_err(), "{bad:?}");
}
assert!(store.rename(&id, &"x".repeat(201)).is_err());
assert!(store.rename(&id, "bad\nname").is_err());
assert!(store.rename("no-such-session", "fine").is_err());
assert_eq!(store.title(&id).unwrap(), None);
}
#[test]
fn json_export_is_the_complete_transcript() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
let out = store.export(&id, ExportFormat::Json).unwrap();
let doc: serde_json::Value = serde_json::from_str(&out).unwrap();
assert_eq!(doc["format"], "eclipse-session/1");
assert_eq!(doc["id"], id);
assert_eq!(doc["messages"].as_array().unwrap().len(), 4);
assert_eq!(doc["messages"][0]["message"]["role"], "user");
assert_eq!(
doc["messages"][1]["message"]["tool_calls"][0]["function"]["name"],
"read_file"
);
assert!(out.ends_with('\n'));
}
#[test]
fn markdown_export_shows_turns_calls_and_results() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
let out = store.export(&id, ExportFormat::Markdown).unwrap();
assert!(out.contains("# "), "a heading, even without a title: {out}");
assert!(out.contains("## 1. User"));
assert!(out.contains("## 2. Assistant"));
assert!(out.contains("**Tool call** `read_file`"));
assert!(out.contains("## 3. Tool result: read_file"));
assert!(out.contains("```json"), "arguments are pretty-printed");
assert!(!out.contains("no result recorded"), "the call was answered");
}
#[test]
fn markdown_export_uses_the_title() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
store.rename(&id, "a named session").unwrap();
let out = store.export(&id, ExportFormat::Markdown).unwrap();
assert!(out.starts_with("# a named session\n"), "{out}");
}
const NO_SPAN: (Option<u64>, Option<u64>) = (None, None);
fn handoff(text: &str, turns: usize, messages: usize) -> Handoff {
Handoff {
text: text.into(),
version: crate::compact::VERSION.into(),
covered_turns: turns,
covered_messages: messages,
covered_from: None,
covered_to: None,
generated_at_ms: 1_700_000_000_000,
judgement: None,
}
}
fn memory(text: &str, turns: usize, messages: usize) -> Memory {
Memory {
version: MEMORY_VERSION,
handoff: Some(handoff(text, turns, messages)),
}
}
#[test]
fn a_summary_era_memory_file_loads_with_its_summary_ignored() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
let v2 = r#"{"version":2,"summary":"old news","covered_turns":2,
"covered_messages":4,"generated_at_ms":1700000000000}"#;
store
.with_db(|db| {
db.conn.execute(
"INSERT INTO memory (session_id, body) VALUES (?1, ?2)",
params![id, v2],
)?;
Ok(())
})
.unwrap();
let m = store.memory(&id).unwrap().unwrap();
assert_eq!(m.schema(), 2, "the file says what wrote it");
assert_eq!(
m.usable_handoff(),
None,
"a summary alone is not a handoff, and there is nothing else to read"
);
assert!(
m.validate().is_err(),
"a record with nothing in it is not memory"
);
store
.save_handoff(
&id,
crate::context::Trimmed {
turns: 2,
messages: 4,
},
NO_SPAN,
"## Log\n[#0]",
None,
)
.unwrap();
let after = store.memory(&id).unwrap().unwrap();
assert_eq!(after.schema(), MEMORY_VERSION, "rewritten at this schema");
assert_eq!(after.handoff.unwrap().text, "## Log\n[#0]");
let raw = store
.with_db(|db| {
Ok(db
.conn
.query_row(
"SELECT body FROM memory WHERE session_id = ?1",
params![id],
|r| r.get::<_, String>(0),
)
.unwrap())
})
.unwrap();
assert!(
!raw.contains("summary"),
"the field a summary-era build wrote is gone from the file: {raw}"
);
}
#[test]
fn saving_a_handoff_replaces_the_document_and_never_the_other_way_round() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
store
.save_handoff(
&id,
crate::context::Trimmed {
turns: 1,
messages: 2,
},
NO_SPAN,
"## Log\nA",
None,
)
.unwrap();
assert_eq!(
store.readable_memory(&id).unwrap().handoff.unwrap().text,
"## Log\nA"
);
store
.save_handoff(
&id,
crate::context::Trimmed {
turns: 3,
messages: 6,
},
NO_SPAN,
"## Log\nB",
Some(Judgement {
text: "- because the first answer settled it".into(),
model: "aux".into(),
generated_at_ms: 1,
}),
)
.unwrap();
let now = store.readable_memory(&id).unwrap();
let h = now.handoff.unwrap();
assert_eq!(h.text, "## Log\nB");
assert_eq!(h.covered_turns, 3);
assert_eq!(
h.judgement.unwrap().model,
"aux",
"and the judgement travels with the document it belongs to"
);
}
#[test]
fn a_memory_from_a_newer_schema_is_refused_rather_than_half_read() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
let mut m = memory("## Log\nC", 1, 2);
m.version = MEMORY_VERSION + 1;
let why = m.validate().unwrap_err();
assert!(why.contains("newer than this build"), "{why}");
assert!(
store.save_memory(&id, &m).is_err(),
"a record this build cannot read is not written either"
);
}
#[test]
fn a_memory_too_large_to_read_back_is_refused_at_the_write() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
let mut big = memory("## Log\n", 1, 2);
big.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize);
let err = store
.save_memory(&id, &big)
.expect_err("a record the reader would refuse is not written");
assert!(err.to_string().contains("record limit"), "{err}");
assert!(
store.memory(&id).unwrap().is_none(),
"nothing was stored, and the row did not become unreadable"
);
let mut fits = memory("## Log\n", 1, 2);
let overhead =
serde_json::to_string(&fits).unwrap().len() - fits.handoff.as_ref().unwrap().text.len();
fits.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize - overhead);
store.save_memory(&id, &fits).expect("the cap itself fits");
assert!(store.readable_memory(&id).is_some(), "and it reads back");
}
#[test]
fn a_handoff_is_its_range_and_not_just_its_counts() {
let mut h = handoff("## Log\nsomeone decided something", 1, 2);
assert!(
!h.covers(1, 2, Some(2), Some(3)),
"a document with no endpoints cannot say which window it described"
);
h.covered_from = Some(0);
h.covered_to = Some(1);
assert!(h.covers(1, 2, Some(0), Some(1)));
assert!(
!h.covers(1, 2, Some(2), Some(3)),
"the same size and the same counts, a different window"
);
assert!(
!h.covers(1, 2, None, None),
"no endpoints on the caller's side either"
);
h.covered_to = Some(9);
assert!(
!h.covers(1, 2, Some(0), Some(1)),
"the end is part of the range"
);
}
#[test]
fn memory_round_trips_in_its_documented_shape_and_the_database_is_private() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
store
.save_handoff(
&id,
crate::context::Trimmed {
turns: 2,
messages: 4,
},
NO_SPAN,
"## Log\nthey agreed on the plan",
None,
)
.unwrap();
let raw = store
.with_db(|db| {
Ok(db
.conn
.query_row(
"SELECT body FROM memory WHERE session_id = ?1",
params![id],
|r| r.get::<_, String>(0),
)
.unwrap())
})
.unwrap();
let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
assert_eq!(parsed["version"], MEMORY_VERSION);
assert_eq!(parsed["handoff"]["covered_turns"], 2);
assert_eq!(parsed["handoff"]["text"], "## Log\nthey agreed on the plan");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(store.dir().join("sessions.db"))
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(
mode, 0o600,
"the database is owner-only, like the transcripts were"
);
let dir_mode = std::fs::metadata(store.dir()).unwrap().permissions().mode() & 0o777;
assert_eq!(dir_mode, 0o700, "the session directory is owner-only");
for sidecar in ["sessions.db-wal", "sessions.db-shm"] {
let p = store.dir().join(sidecar);
if !p.exists() {
continue;
}
let m = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777;
assert_eq!(m, 0o600, "{sidecar} is owner-only");
}
}
}
#[test]
fn memory_validation_rejects_nonsense() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
let empty = Memory {
version: MEMORY_VERSION,
handoff: None,
};
assert!(empty.validate().is_err() && store.save_memory(&id, &empty).is_err());
let mut m = memory(" padded ", 1, 1);
assert!(m.validate().is_err(), "an untrimmed document is refused");
m = memory("fine", 2, 1);
assert!(m.validate().is_err(), "messages < turns is nonsense");
m.handoff.as_mut().unwrap().covered_messages = 2;
m.handoff.as_mut().unwrap().covered_turns = 0;
assert!(m.validate().is_err(), "covering no turn is nonsense");
m = memory("", 1, 2);
assert!(m.validate().is_err(), "an empty document is not memory");
let mut m = memory("fine", 2, 4);
m.handoff.as_mut().unwrap().judgement = Some(Judgement {
text: "\n- untrimmed".into(),
model: "aux".into(),
generated_at_ms: 1,
});
assert!(m.validate().is_err(), "an untrimmed judgement is refused");
assert!(store.save_memory(&id, &memory("fine", 2, 4)).is_ok());
}
#[test]
fn corrupt_or_invalid_memory_is_not_usable() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
store
.with_db(|db| {
db.conn.execute(
"INSERT INTO memory (session_id, body) VALUES (?1, 'not json')",
params![id],
)?;
Ok(())
})
.unwrap();
assert!(
store.memory(&id).is_err(),
"corruption is reported, not hidden"
);
assert_eq!(store.readable_memory(&id), None, "and never used");
store
.save_memory(&id, &memory("valid again", 1, 1))
.unwrap();
assert!(store.readable_memory(&id).is_some());
}
#[test]
fn memory_is_per_session() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let a = store.new_id();
let b = store.new_id();
store.append(&a, &Message::user("a")).unwrap();
store.append(&b, &Message::user("b")).unwrap();
store.save_memory(&a, &memory("about a", 1, 1)).unwrap();
assert!(store.memory(&b).unwrap().is_none());
assert_eq!(
store.readable_memory(&a).unwrap().handoff.unwrap().text,
"about a"
);
}
#[test]
fn delete_and_prune_remove_the_memory_too() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
store
.save_memory(&id, &memory("gone with it", 1, 1))
.unwrap();
store.delete(&id).unwrap();
assert!(
store.load_records(&id).is_err(),
"the session is gone, not empty"
);
assert_eq!(store.memory(&id).unwrap(), None);
}
#[test]
fn a_deleted_legacy_session_does_not_come_back() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("sessions");
let path = legacy_file(
&root,
"deleted-me",
&line(&Message::user("doomed"), 1_700_000_000_000),
);
let store = SessionStore::new(&root);
assert!(store.exists("deleted-me"));
store.delete("deleted-me").unwrap();
assert!(!path.exists(), "the imported source goes with the session");
drop(store);
let again = SessionStore::new(&root);
assert!(
!again.exists("deleted-me"),
"a deleted session must stay deleted across restarts"
);
assert!(again.list().unwrap().is_empty());
}
#[test]
fn a_legacy_transcript_is_imported_once_and_the_file_is_kept() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("sessions");
let body = format!(
"{}{}",
line(&Message::user("from the old world"), 1_700_000_000_000),
line(&Message::assistant("and the reply"), 1_700_000_001_000)
);
let path = legacy_file(&root, "legacy-1", &body);
std::fs::write(root.join("legacy-1.meta.json"), r#"{"title":"old title"}"#).unwrap();
let store = SessionStore::new(&root);
let messages = store.load("legacy-1").unwrap();
assert_eq!(messages.len(), 2);
assert_eq!(messages[0].content.as_deref(), Some("from the old world"));
assert_eq!(
store.title("legacy-1").unwrap().as_deref(),
Some("old title")
);
assert!(path.exists(), "importing must not delete the source");
let info = store.list().unwrap().into_iter().next().unwrap();
assert_eq!(info.preview, "from the old world");
assert_eq!(info.updated_ms, 1_700_000_001_000);
drop(store);
let again = SessionStore::new(&root);
assert_eq!(again.load("legacy-1").unwrap().len(), 2);
assert_eq!(again.list().unwrap().len(), 1);
}
#[test]
fn a_truncated_legacy_tail_is_dropped_and_the_rest_is_imported() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("sessions");
let good = line(&Message::user("complete"), 1_700_000_000_000);
let body = format!("{good}{{\"ts\":1,\"message\":{{\"role\":\"user\"");
legacy_file(&root, "half-written", &body);
let store = SessionStore::new(&root);
let messages = store.load("half-written").unwrap();
assert_eq!(messages.len(), 1, "the complete record survived");
assert_eq!(messages[0].content.as_deref(), Some("complete"));
}
#[test]
fn a_complete_final_record_without_a_newline_is_kept() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("sessions");
let body = line(&Message::user("no trailing newline"), 5)
.trim_end()
.to_string();
legacy_file(&root, "unterminated", &body);
let store = SessionStore::new(&root);
assert_eq!(store.load("unterminated").unwrap().len(), 1);
}
#[test]
fn a_legacy_file_corrupt_in_the_middle_is_refused_not_half_imported() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("sessions");
let body = format!(
"{}garbage\n{}",
line(&Message::user("before"), 1),
line(&Message::assistant("after"), 2)
);
let path = legacy_file(&root, "corrupt-mid", &body);
let store = SessionStore::new(&root);
assert!(
!store.exists("corrupt-mid"),
"importing part of it would silently drop a message"
);
assert!(path.exists(), "and the file is left for a human to look at");
assert!(store.list().unwrap().is_empty());
}
#[test]
fn an_empty_legacy_transcript_keeps_its_file_time_not_epoch() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("sessions");
legacy_file(&root, "empty-one", "");
let store = SessionStore::new(&root);
let info = store.list().unwrap().into_iter().next().unwrap();
assert_eq!(info.messages, 0);
assert!(
info.updated_ms > 1_600_000_000_000,
"a corrupt transcript still ages from its mtime, not from 1970: {}",
info.updated_ms
);
}
#[test]
fn a_legacy_memory_sidecar_is_imported() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("sessions");
legacy_file(
&root,
"with-memory",
&line(&Message::user("hi"), 1_700_000_000_000),
);
let m = memory("remembered from before", 2, 4);
std::fs::write(
root.join("with-memory.memory.json"),
serde_json::to_string(&m).unwrap(),
)
.unwrap();
let store = SessionStore::new(&root);
assert_eq!(store.readable_memory("with-memory"), Some(m));
}
#[test]
fn an_unparseable_legacy_memory_sidecar_is_imported_and_reported() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("sessions");
legacy_file(
&root,
"bad-memory",
&line(&Message::user("hi"), 1_700_000_000_000),
);
std::fs::write(
root.join("bad-memory.memory.json"),
r#"{"version":3,"handoff":{"#,
)
.unwrap();
let store = SessionStore::new(&root);
assert!(
store.memory("bad-memory").is_err(),
"an unparseable sidecar is an error to read, not silence"
);
assert_eq!(store.readable_memory("bad-memory"), None);
}
#[test]
fn search_finds_message_text_and_tool_arguments() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store
.append(&id, &Message::user("the deploy key lives in vault"))
.unwrap();
store
.append(
&id,
&Message::assistant_tool_calls(
None,
vec![call("c9", "shell", r#"{"cmd":"systemctl status nginx"}"#)],
),
)
.unwrap();
let other = store.new_id();
store.append(&other, &Message::user("unrelated")).unwrap();
let hits = store.search("vault", 10).unwrap();
assert_eq!(hits.len(), 1, "{hits:?}");
assert_eq!(hits[0].session_id, id);
assert_eq!(hits[0].seq, 0);
assert_eq!(hits[0].role, "user");
assert!(hits[0].snippet.contains("vault"));
let hits = store.search("nginx", 10).unwrap();
assert_eq!(hits.len(), 1, "tool arguments are searchable: {hits:?}");
assert_eq!(hits[0].seq, 1);
assert!(store.search("nothing-said-this", 10).unwrap().is_empty());
assert!(store.search(" ", 10).unwrap().is_empty());
}
#[test]
fn a_delete_that_fails_halfway_leaves_the_session_alone() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store
.append(&id, &Message::user("an undeletable mention of widget"))
.unwrap();
if !store.with_db(|db| Ok(db.fts)).unwrap() {
return; }
store
.with_db(|db| {
db.conn.execute_batch("DROP TABLE messages_fts")?;
Ok(())
})
.unwrap();
assert!(
store.delete(&id).is_err(),
"the failed delete is reported to the caller"
);
store
.with_db(|db| {
let sessions: i64 = db.conn.query_row(
"SELECT count(*) FROM sessions WHERE id = ?1",
params![id],
|r| r.get(0),
)?;
assert_eq!(
sessions, 1,
"a delete that failed must not have half-happened"
);
let messages: i64 = db.conn.query_row(
"SELECT count(*) FROM messages WHERE session_id = ?1",
params![id],
|r| r.get(0),
)?;
assert_eq!(messages, 1, "its messages are still there too");
Ok(())
})
.unwrap();
assert!(store.delete(&id).is_err());
}
#[test]
fn a_stale_index_row_is_skipped_rather_than_failing_the_search() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store
.append(&id, &Message::user("the live mention of widget"))
.unwrap();
store
.with_db(|db| {
db.conn
.execute("DELETE FROM messages WHERE session_id = ?1", params![id])?;
Ok(())
})
.unwrap();
let hits = store.search("widget", 10).unwrap();
assert!(
hits.is_empty(),
"the orphan is dropped, not fatal: {hits:?}"
);
}
#[test]
fn deleting_a_session_leaves_nothing_of_it_behind() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store
.append(&id, &Message::user("a deletable mention of widget"))
.unwrap();
let keep = store.new_id();
store
.append(&keep, &Message::user("a kept mention of widget"))
.unwrap();
store.delete(&id).unwrap();
store
.with_db(|db| {
let messages: i64 = db.conn.query_row(
"SELECT count(*) FROM messages WHERE session_id = ?1",
params![id],
|r| r.get(0),
)?;
assert_eq!(messages, 0, "messages go with the session");
if db.fts {
let indexed: i64 = db.conn.query_row(
"SELECT count(*) FROM messages_fts WHERE session_id = ?1",
params![id],
|r| r.get(0),
)?;
assert_eq!(indexed, 0, "and so does the index, in the same transaction");
}
Ok(())
})
.unwrap();
let hits = store.search("widget", 10).unwrap();
assert_eq!(hits.len(), 1, "the other session is untouched: {hits:?}");
assert_eq!(hits[0].session_id, keep);
assert!(
store.delete(&id).is_err(),
"deleting it twice still says there is no such session"
);
}
#[test]
fn deleting_a_session_deletes_its_plan_and_its_steps() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let doomed = store.new_id();
let kept = store.new_id();
let items = vec![
crate::plans::Item::new("1", "read the audit", crate::plans::Status::Done),
crate::plans::Item::new("2", "fix the writer", crate::plans::Status::InProgress),
];
assert_eq!(store.set_plan(&doomed, &items).unwrap(), 1);
assert_eq!(
store.set_plan(&doomed, &items).unwrap(),
2,
"every write bumps the revision, so two surfaces can tell a stale list"
);
store.set_plan(&kept, &items).unwrap();
let read = store.plan(&doomed).unwrap().unwrap();
assert_eq!(read.revision, 2);
assert_eq!(read.items, items, "read back in `position` order");
store.delete(&doomed).unwrap();
assert!(
store.plan(&doomed).unwrap().is_none(),
"the plan goes with the session"
);
store
.with_db(|db| {
let gone: i64 = db.conn.query_row(
"SELECT count(*) FROM plan_items WHERE session_id = ?1",
params![doomed],
|r| r.get(0),
)?;
assert_eq!(gone, 0, "and so do its steps");
let kept_steps: i64 = db.conn.query_row(
"SELECT count(*) FROM plan_items WHERE session_id = ?1",
params![kept],
|r| r.get(0),
)?;
assert_eq!(kept_steps, 2, "the other session's plan is untouched");
Ok(())
})
.unwrap();
}
#[test]
fn search_answers_newest_first_whichever_backend_runs() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let older = store.new_id();
store
.append(&older, &Message::user("the older mention of gadget"))
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(3));
let newer = store.new_id();
store
.append(&newer, &Message::user("the newer mention of gadget"))
.unwrap();
store
.with_db(|db| {
for use_fts in [true, false] {
if use_fts && !db.fts {
continue;
}
let hits = SessionStore::search_in(db, "gadget", 1, use_fts, false).unwrap();
assert_eq!(hits.len(), 1, "fts={use_fts}");
assert_eq!(
hits[0].session_id, newer,
"a limit of one has to take the newest hit, not the first rowid (fts={use_fts})"
);
}
Ok(())
})
.unwrap();
}
#[test]
fn search_treats_percent_and_underscore_as_text_not_wildcards() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store
.append(&id, &Message::user("disk is 100% full"))
.unwrap();
store
.append(&id, &Message::user("disk is 100 percent full"))
.unwrap();
store
.append(&id, &Message::user("the file a_b.txt is here"))
.unwrap();
store
.append(&id, &Message::user("the file axb.txt is not"))
.unwrap();
store
.with_db(|db| {
let percent = SessionStore::search_in(db, "100%", 10, false, false).unwrap();
assert_eq!(
percent.len(),
1,
"`100%` is a substring, not `100` plus a wildcard: {percent:?}"
);
assert!(percent[0].snippet.contains("100% full"));
let underscore = SessionStore::search_in(db, "a_b.txt", 10, false, false).unwrap();
assert_eq!(
underscore.len(),
1,
"`_` is a character, not any character: {underscore:?}"
);
assert!(underscore[0].snippet.contains("a_b.txt"));
Ok(())
})
.unwrap();
}
#[test]
fn a_like_literal_escapes_every_wildcard_character() {
assert_eq!(like_literal("plain"), "plain");
assert_eq!(like_literal("100%"), r"100\%");
assert_eq!(like_literal("a_b"), r"a\_b");
assert_eq!(like_literal(r"C:\temp"), r"C:\\temp");
}
#[test]
fn search_survives_query_syntax_that_would_break_fts() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store
.append(&id, &Message::user(r#"a "quoted" thing AND (parens)"#))
.unwrap();
for q in [r#""quoted""#, "AND (parens)", "*", "a AND OR NOT", "-x"] {
let _ = store.search(q, 5).unwrap();
}
assert_eq!(store.search("quoted", 5).unwrap().len(), 1);
}
#[test]
fn search_results_carry_the_session_and_position() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
transcript(&store, &id);
let hits = store.search("contents", 10).unwrap();
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, id);
assert_eq!(hits[0].seq, 2, "the tool result is the third message");
assert_eq!(hits[0].role, "tool");
assert!(hits[0].at_ms > 0);
}
#[test]
fn a_subagent_session_says_where_it_came_from_and_a_native_one_does_not() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let parent = store.new_id();
let child = store.new_id();
store.append(&parent, &Message::user("big job")).unwrap();
store.begin_subagent(&child, &parent, "big:v2").unwrap();
store.append(&child, &Message::user("sub job")).unwrap();
let list = store.list().unwrap();
let find = |id: &str| list.iter().find(|s| s.id == id).unwrap();
assert_eq!(find(&parent).origin, "native");
assert!(find(&parent).subagent().is_none());
let origin = find(&child).subagent().unwrap();
assert_eq!((origin.parent, origin.route), (parent.as_str(), "big:v2"));
assert_eq!(
find(&child).preview,
"sub job",
"the first message still names it"
);
}
#[test]
fn beginning_a_subagent_twice_keeps_the_first_origin() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
store.begin_subagent("c1", "p1", "big").unwrap();
store.begin_subagent("c1", "p2", "other").unwrap();
let info = store.list().unwrap().remove(0);
assert_eq!(info.subagent().unwrap().parent, "p1");
assert!(store.begin_subagent("c2", "../p", "big").is_err());
}
#[test]
fn an_api_session_keeps_its_tag_when_the_run_writes_to_it() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store.begin_api(&id).unwrap();
store.append(&id, &Message::user("ask")).unwrap();
store.append(&id, &Message::assistant("answer")).unwrap();
let info = store.list().unwrap().remove(0);
assert_eq!(info.id, id);
assert_eq!(info.origin, SessionStore::API_ORIGIN);
assert!(info.subagent().is_none(), "tagged, not a child");
assert_eq!(info.messages, 2, "and the transcript is really there");
}
#[test]
fn the_sweep_takes_old_api_sessions_and_leaves_the_rest() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let old_api = store.new_id();
store.begin_api(&old_api).unwrap();
store.append(&old_api, &Message::user("poll")).unwrap();
let mine = store.new_id();
store
.append(&mine, &Message::user("a real conversation"))
.unwrap();
let pinned_api = store.new_id();
store.begin_api(&pinned_api).unwrap();
store
.append(&pinned_api, &Message::user("keep me"))
.unwrap();
store.set_pinned(&pinned_api, true).unwrap();
let pruned = store.prune_api_sessions(now_ms() + 1).unwrap();
assert_eq!(pruned, 1, "only the API's own, unpinned session");
let left: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
assert!(
left.contains(&mine),
"a conversation is never swept: {left:?}"
);
assert!(left.contains(&pinned_api), "a pin is a decision: {left:?}");
assert!(!left.contains(&old_api), "{left:?}");
}
#[test]
fn the_sweep_is_empty_when_there_is_nothing_the_api_left() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
store.append("n1", &Message::user("hello")).unwrap();
assert_eq!(store.prune_api_sessions(u64::MAX).unwrap(), 0);
assert_eq!(store.list().unwrap().len(), 1);
}
#[cfg(unix)]
#[tokio::test]
async fn only_a_session_a_live_run_holds_is_reported_as_held() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let wait = std::time::Duration::from_millis(0);
let live = store.lock("live", wait).await.unwrap();
drop(store.lock("finished", wait).await.unwrap());
let held = held_locks(store.dir());
assert_eq!(held.len(), 1, "{held:?}");
assert_eq!(held[0].id, "live");
assert!(held[0].holder.starts_with("pid "), "{held:?}");
drop(live);
assert!(held_locks(store.dir()).is_empty());
assert!(held_locks(&dir.path().join("no-such-dir")).is_empty());
}
fn picture_message(text: Option<&str>, name: &str) -> Message {
let mut m = match text {
Some(t) => Message::user(t),
None => Message {
role: Role::User,
content: None,
reasoning: None,
finish_reason: None,
tool_calls: Vec::new(),
tool_call_id: None,
images: Vec::new(),
seq: None,
},
};
m.images.push(crate::message::ImagePart {
name: name.into(),
mime: "image/png".into(),
url: "data:image/png;base64,AAAA".into(),
seen: None,
});
m
}
#[test]
fn describing_a_picture_reports_whether_it_changed_anything() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().to_path_buf());
let id = store.new_id();
let seq = store
.append_seq(&id, &picture_message(Some("look"), "shot.png"))
.unwrap();
assert!(
store
.set_image_seen(&id, seq as u64, 0, "a dashboard with a red chart")
.unwrap(),
"a picture that is there was described"
);
let hits = store.search("red chart", 5).unwrap();
assert_eq!(hits.len(), 1, "the description is searchable: {hits:?}");
assert!(store.set_image_seen(&id, seq as u64, 0, "again").unwrap());
assert!(
!store.set_image_seen(&id, 999, 0, "nowhere").unwrap(),
"a missing row used to answer Ok(()) — a caller could not tell it from a write"
);
assert!(!store.set_image_seen(&id, seq as u64, 7, "no").unwrap());
}
#[test]
fn a_first_message_with_no_text_does_not_freeze_the_preview() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().to_path_buf());
let id = store.new_id();
store
.append(&id, &picture_message(Some(""), "shot.png"))
.unwrap();
store
.append(&id, &Message::user("actually, summarise yesterday"))
.unwrap();
let listed = store.list().unwrap();
let row = listed.iter().find(|s| s.id == id).expect("listed");
assert_eq!(
row.preview.as_str(),
"actually, summarise yesterday",
"the first empty row took the preview: {:?}",
row.preview
);
}
#[test]
fn a_bot_conversation_is_not_in_the_humans_list() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let mine = store.new_id();
store
.append(&mine, &Message::user("the human asked this"))
.unwrap();
let theirs = store.bot_session("nox").unwrap();
store
.append(&theirs, &Message::user("the bot said this"))
.unwrap();
let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
assert_eq!(
listed,
vec![mine.clone()],
"a bot's conversation left the sidebar alone"
);
let archived: Vec<String> = store
.list_with_archived()
.unwrap()
.into_iter()
.map(|s| s.id)
.collect();
assert_eq!(archived, vec![mine], "`show archived` is not `show bots`");
}
#[test]
fn list_bots_groups_every_conversation_under_its_name() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let first = store.bot_session("nox").unwrap();
store.append(&first, &Message::user("one")).unwrap();
for id in store.bot_sessions("nox").unwrap() {
store.set_archived(&id, true).unwrap();
}
let second = store.bot_session("nox").unwrap();
assert_ne!(
first, second,
"a cleared conversation is not the one reopened"
);
store.append(&second, &Message::user("two")).unwrap();
let other = store.bot_session("lux").unwrap();
store.append(&other, &Message::user("three")).unwrap();
let mine = store.new_id();
store.append(&mine, &Message::user("four")).unwrap();
let bots = store.list_bots().unwrap();
assert_eq!(bots.len(), 2, "one row per identity: {bots:?}");
assert_eq!(bots[0].name, "lux", "newest activity first");
let nox = bots.iter().find(|b| b.name == "nox").unwrap();
assert_eq!(nox.sessions, 2, "both conversations counted");
assert_eq!(nox.last_session, second, "the row opens the newest");
assert_eq!(nox.messages, 1);
assert!(
!nox.archived,
"one archived conversation is not a cleared bot"
);
}
#[test]
fn two_sessions_in_the_same_millisecond_are_ordered_by_when_they_were_stored() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
store.list().unwrap(); let at = 1_796_297_799_945_i64;
let rows = [
("1796297799945-11001-9", "bot:nox"),
("1796297799945-11001-10", "bot:nox"),
("1796297799945-11001-2", "native"),
("1796297799945-11001-11", "native"),
];
store
.with_db(|db| {
for (id, origin) in rows {
db.conn.execute(
"INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
VALUES (?1, ?2, ?3, 1, ?4)",
params![id, at, at, origin],
)?;
}
Ok(())
})
.unwrap();
let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
assert_eq!(
listed,
["1796297799945-11001-11", "1796297799945-11001-2"],
"a tie is broken by which row was stored later, not by its text"
);
let nox = store
.list_bots()
.unwrap()
.into_iter()
.find(|b| b.name == "nox")
.expect("the bot's two conversations");
assert_eq!(nox.sessions, 2);
assert_eq!(
nox.last_session, "1796297799945-11001-10",
"the conversation opened second is the live one"
);
}
#[test]
fn a_search_leaves_a_bots_conversation_out_unless_asked() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let mine = store.new_id();
store
.append(&mine, &Message::user("the vault code is in the drawer"))
.unwrap();
let bots = store.bot_session("nox").unwrap();
store
.append(&bots, &Message::user("the vault code is on the lane"))
.unwrap();
let found = store.search("vault", 10).unwrap();
assert_eq!(
found.len(),
1,
"the human's search found a bot's row: {found:?}"
);
assert_eq!(found[0].session_id, mine);
let asked = store.search_with("vault", 10, true).unwrap();
assert_eq!(
asked.len(),
2,
"`bots = true` is how a bot's rows are asked for"
);
assert!(asked.iter().any(|h| h.session_id == bots));
store
.set_title(&bots, "never mention the vault", TitleSource::User)
.unwrap();
let named = store.search("never", 10).unwrap();
assert!(
named.is_empty(),
"a bot's title answered the human's search: {named:?}"
);
let named = store.search_with("never", 10, true).unwrap();
assert_eq!(named.len(), 1);
}
#[test]
fn a_title_is_never_claimed_for_a_bot() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let mine = store.new_id();
store.append(&mine, &Message::user("hello")).unwrap();
store
.set_title(&mine, "derived name", TitleSource::Derived)
.unwrap();
assert!(
store.claim_title_upgrade(&mine).unwrap(),
"a person's conversation may be named by a model"
);
let bots = store.bot_session("nox").unwrap();
store.append(&bots, &Message::user("hello")).unwrap();
store
.set_title(&bots, "derived name", TitleSource::Derived)
.unwrap();
assert!(
!store.claim_title_upgrade(&bots).unwrap(),
"a naming call per turn is the cost this rule exists to avoid"
);
}
#[test]
fn a_bot_conversation_says_which_bot_it_belongs_to() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.bot_session("nox").unwrap();
store.append(&id, &Message::user("hello")).unwrap();
assert_eq!(store.origin(&id).unwrap().as_deref(), Some("bot:nox"));
let info = SessionInfo {
id,
messages: 1,
updated_ms: 0,
preview: "hello".into(),
title: None,
origin: "bot:nox".into(),
pinned: false,
archived: false,
cost: None,
};
assert_eq!(info.bot(), Some("nox"));
assert!(info.is_bot());
assert!(info.subagent().is_none());
assert!(
info.tagged_label().starts_with("[bot \u{b7} nox]"),
"{}",
info.tagged_label()
);
let odd = SessionInfo {
origin: "bot:a:b".to_string(),
..info
};
assert_eq!(odd.bot(), None);
let empty = SessionInfo {
origin: "bot:".to_string(),
..odd
};
assert_eq!(empty.bot(), None);
}
#[test]
fn a_flare_run_is_a_set_of_sessions_with_their_positions() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let run = "f-1";
let mut ids = Vec::new();
for n in [2usize, 1, 3] {
let id = store.new_id();
store.begin_flare(&id, run, n).unwrap();
store
.append(&id, &Message::user(format!("flare {n} reading")))
.unwrap();
ids.push((n, id));
}
let listed = store.flares_of(run).unwrap();
assert_eq!(
listed
.iter()
.filter_map(|s| s.flare().map(|f| f.n))
.collect::<Vec<_>>(),
vec![1, 2, 3],
"the run's order is the lead's order, not the order they finished"
);
assert_eq!(listed[0].flare().unwrap().run, run);
assert!(
listed[0].tagged_label().starts_with("[flare \u{b7} f-1/1]"),
"{}",
listed[0].tagged_label()
);
assert!(listed[0].subagent().is_none());
assert!(!listed[0].is_bot());
let other = store.new_id();
store.begin_flare(&other, "f-2", 1).unwrap();
assert_eq!(store.flares_of(run).unwrap().len(), 3);
let bad = store.new_id();
assert!(store.begin_flare(&bad, "f:1", 1).is_err());
let odd = SessionInfo {
origin: "flare:run:two".into(),
..listed[0].clone()
};
assert!(odd.flare().is_none());
assert!(SessionInfo {
origin: "flare::1".into(),
..listed[0].clone()
}
.flare()
.is_none());
}
#[test]
fn a_search_leaves_a_flares_transcript_out_unless_asked() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let mine = store.new_id();
store
.append(&mine, &Message::user("the retry loop is in worker.rs"))
.unwrap();
let flare = store.new_id();
store.begin_flare(&flare, "f-9", 1).unwrap();
store
.append(&flare, &Message::user("the retry loop is in pool.rs"))
.unwrap();
let found = store.search("retry", 10).unwrap();
assert_eq!(found.len(), 1, "the human found a flare's row: {found:?}");
assert_eq!(found[0].session_id, mine);
let asked = store.search_with("retry", 10, true).unwrap();
assert_eq!(
asked.len(),
2,
"`children = true` is how those rows are asked for"
);
}
#[test]
fn a_flare_is_never_named_by_a_model() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store.begin_flare(&id, "f-3", 1).unwrap();
store.append(&id, &Message::user("reading")).unwrap();
store
.set_title(&id, "derived name", TitleSource::Derived)
.unwrap();
assert!(
!store.claim_title_upgrade(&id).unwrap(),
"a transient worker does not get a paid naming call"
);
}
fn refuse(store: &SessionStore, on: &str) {
store
.with_db(|db| {
db.conn.execute_batch(&format!(
"CREATE TRIGGER refused {on} BEGIN SELECT RAISE(ABORT, 'refused by the test'); END"
))?;
Ok(())
})
.unwrap();
}
#[test]
fn a_goal_clear_that_fails_on_its_last_delete_clears_nothing() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
let goal =
crate::goals::Goal::new(&id, "ship the release", None, Some(5), 1_700_000_000_000);
store.set_goal(&goal).unwrap();
store
.record_goal_turn(
&id,
&crate::goals::Judgement {
turn: 1,
verdict: "continue".into(),
why: None,
at_ms: 1_700_000_000_001,
},
)
.unwrap();
refuse(&store, "BEFORE DELETE ON goal_turns");
assert!(
store.clear_goal(&id).is_err(),
"the second delete was refused, so the clear cannot report itself as done"
);
assert!(
store.goal(&id).unwrap().is_some(),
"the goal went on its own, leaving its judgements for the next goal to inherit"
);
assert_eq!(
store.goal_turns(&id).unwrap().len(),
1,
"the judgements of a goal that was not cleared"
);
}
#[test]
fn a_goal_that_cannot_be_saved_does_not_leave_a_session_behind() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
refuse(&store, "BEFORE INSERT ON goals");
let goal = crate::goals::Goal::new(&id, "ship the release", None, None, 1_700_000_000_000);
assert!(store.set_goal(&goal).is_err(), "the goal write was refused");
let rows: i64 = store
.with_db(|db| {
Ok(db.conn.query_row(
"SELECT COUNT(*) FROM sessions WHERE id = ?1",
params![id],
|r| r.get(0),
)?)
})
.unwrap();
assert_eq!(
rows, 0,
"the session row outlived the goal it was written for"
);
}
#[test]
fn a_ruling_that_cannot_be_logged_does_not_land() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let id = store.new_id();
store.append(&id, &Message::user("run it")).unwrap();
store
.record_pending(
&id,
1,
&[crate::approvals::Pending::new(
"c1",
"shell",
"rm -rf build".into(),
"{}".into(),
)],
)
.unwrap();
refuse(&store, "BEFORE INSERT ON approval_log");
assert!(store
.decide_pending(&id, 1, 0, &crate::approvals::Decision::Allow, "user")
.is_err());
let rows = store.pending_calls(&id).unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(
rows[0].decision, None,
"the answer landed without the log row that says who gave it"
);
}
}