use super::error;
use crate::session::{SessionStore, StoreError};
use rusqlite::{params, OptionalExtension, Row};
use serde_json::{Map, Value};
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) const PINS_SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS agent86_pins (
kind TEXT NOT NULL,
row_id INTEGER NOT NULL,
pinned_at REAL NOT NULL,
PRIMARY KEY (kind, row_id)
);
";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntryKind {
Fact,
Episode,
}
impl EntryKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Fact => "fact",
Self::Episode => "episode",
}
}
fn table(self) -> &'static str {
match self {
Self::Fact => "memories",
Self::Episode => "episodes",
}
}
pub(crate) fn unpinned(self) -> String {
format!(
"id NOT IN (SELECT row_id FROM agent86_pins WHERE kind = '{}')",
self.as_str()
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Entry {
pub kind: EntryKind,
pub id: i64,
pub ts: f64,
pub text: String,
pub outcome: Option<String>,
pub session_id: Option<String>,
pub category: Option<String>,
pub pinned_at: Option<f64>,
}
impl Entry {
pub fn pinned(&self) -> bool {
self.pinned_at.is_some()
}
}
#[derive(Debug, Clone, Copy)]
pub struct ListQuery {
pub kind: EntryKind,
pub limit: Option<usize>,
pub offset: usize,
pub pinned_only: bool,
}
fn now() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0.0, |elapsed| elapsed.as_secs_f64())
}
fn select(kind: EntryKind) -> String {
let columns = match kind {
EntryKind::Fact => "t.id, t.ts, t.text, NULL, NULL, t.kind, t.metadata_json",
EntryKind::Episode => "t.id, t.ts, t.task, t.outcome, t.session_id, NULL, t.metadata_json",
};
format!(
"SELECT {columns}, p.pinned_at FROM {table} t \
LEFT JOIN agent86_pins p ON p.kind = '{name}' AND p.row_id = t.id",
table = kind.table(),
name = kind.as_str(),
)
}
fn read(kind: EntryKind, row: &Row<'_>) -> rusqlite::Result<Entry> {
let category = match kind {
EntryKind::Fact => row.get(5)?,
EntryKind::Episode => row
.get::<_, Option<String>>(6)?
.and_then(|raw| serde_json::from_str::<Map<String, Value>>(&raw).ok())
.and_then(|metadata| metadata.get("kind")?.as_str().map(str::to_owned)),
};
Ok(Entry {
kind,
id: row.get(0)?,
ts: row.get::<_, Option<f64>>(1)?.unwrap_or(0.0),
text: row.get(2)?,
outcome: row.get(3)?,
session_id: row.get(4)?,
category,
pinned_at: row.get(7)?,
})
}
impl SessionStore {
pub fn list_entries(&self, query: ListQuery) -> Result<Vec<Entry>, StoreError> {
let filter = if query.pinned_only {
" WHERE p.pinned_at IS NOT NULL"
} else {
""
};
let sql = format!(
"{}{filter} ORDER BY t.ts DESC, t.id DESC LIMIT ?1 OFFSET ?2",
select(query.kind)
);
let limit = query
.limit
.map_or(-1, |limit| i64::try_from(limit).unwrap_or(i64::MAX));
let offset = i64::try_from(query.offset).unwrap_or(i64::MAX);
let connection = self.connection();
let mut statement = connection.prepare(&sql).map_err(error)?;
let rows = statement
.query_map(params![limit, offset], |row| read(query.kind, row))
.map_err(error)?;
rows.collect::<Result<_, _>>().map_err(error)
}
pub fn entry(&self, kind: EntryKind, id: i64) -> Result<Option<Entry>, StoreError> {
let sql = format!("{} WHERE t.id = ?1", select(kind));
self.connection()
.query_row(&sql, params![id], |row| read(kind, row))
.optional()
.map_err(error)
}
pub fn set_pinned(
&self,
kind: EntryKind,
id: i64,
pinned: bool,
) -> Result<Option<Entry>, StoreError> {
{
let connection = self.connection();
let exists = connection
.query_row(
&format!("SELECT 1 FROM {} WHERE id = ?1", kind.table()),
params![id],
|_| Ok(()),
)
.optional()
.map_err(error)?
.is_some();
if !exists {
return Ok(None);
}
if pinned {
connection
.execute(
"INSERT OR IGNORE INTO agent86_pins (kind, row_id, pinned_at) \
VALUES (?1, ?2, ?3)",
params![kind.as_str(), id, now()],
)
.map_err(error)?;
} else {
connection
.execute(
"DELETE FROM agent86_pins WHERE kind = ?1 AND row_id = ?2",
params![kind.as_str(), id],
)
.map_err(error)?;
}
}
self.entry(kind, id)
}
pub fn forget(&self, kind: EntryKind, id: i64) -> Result<bool, StoreError> {
let connection = self.connection();
let removed = connection
.execute(
&format!("DELETE FROM {} WHERE id = ?1", kind.table()),
params![id],
)
.map_err(error)?;
connection
.execute(
"DELETE FROM agent86_pins WHERE kind = ?1 AND row_id = ?2",
params![kind.as_str(), id],
)
.map_err(error)?;
Ok(removed > 0)
}
}
pub(crate) fn sweep_pins(connection: &rusqlite::Connection) -> Result<(), StoreError> {
connection
.execute(
"DELETE FROM agent86_pins WHERE \
(kind = 'episode' AND row_id NOT IN (SELECT id FROM episodes)) OR \
(kind = 'fact' AND row_id NOT IN (SELECT id FROM memories))",
[],
)
.map(drop)
.map_err(error)
}