1use crate::error::{Error, Result};
15use crate::message::{Message, Role};
16use rusqlite::{params, Connection, OptionalExtension, TransactionBehavior};
17use serde::{Deserialize, Serialize};
18use std::io::{Seek, SeekFrom, Write};
19use std::path::{Path, PathBuf};
20use std::sync::atomic::{AtomicU64, Ordering};
21use std::sync::{Arc, Mutex};
22use std::time::{SystemTime, UNIX_EPOCH};
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct Record {
26 pub ts: u64,
28 pub message: Message,
29}
30
31#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
44pub struct TurnCost {
45 pub at_ms: u64,
47 pub ctx: String,
49 #[serde(default)]
50 pub prompt_tokens: Option<u64>,
51 #[serde(default)]
52 pub completion_tokens: Option<u64>,
53 #[serde(default)]
54 pub cached_tokens: Option<u64>,
55 #[serde(default)]
56 pub ttft_ms: Option<u64>,
57 #[serde(default)]
58 pub latency_ms: Option<u64>,
59 #[serde(default)]
61 pub tokens_per_sec: Option<f64>,
62 #[serde(default)]
65 pub window_tokens: Option<u64>,
66}
67
68#[derive(Debug, Clone, PartialEq)]
69pub struct SessionInfo {
70 pub id: String,
71 pub messages: usize,
72 pub updated_ms: u64,
74 pub preview: String,
76 pub title: Option<String>,
78 pub origin: String,
80 pub pinned: bool,
83 pub archived: bool,
86 pub cost: Option<TurnCost>,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct SubagentOrigin<'a> {
95 pub parent: &'a str,
96 pub route: &'a str,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct FlareRunRow {
102 pub id: String,
103 pub task: String,
104 pub state: String,
106 pub routes: Vec<String>,
108 pub jobs: usize,
109 pub parent: Option<String>,
110 pub started_ms: u64,
111 pub finished_ms: Option<u64>,
112 pub prompt_tokens: Option<u64>,
113 pub completion_tokens: Option<u64>,
114 pub iterations: usize,
115}
116
117impl FlareRunRow {
118 pub fn finished(&self) -> bool {
119 self.finished_ms.is_some()
120 }
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct FlareJobRow {
126 pub run_id: String,
127 pub n: usize,
128 pub route: String,
129 pub session_id: Option<String>,
130 pub state: String,
132 pub prompt_tokens: Option<u64>,
133 pub completion_tokens: Option<u64>,
134 pub iterations: usize,
135 pub why: Option<String>,
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct BotSessions {
147 pub name: String,
148 pub sessions: usize,
149 pub messages: usize,
151 pub last_session: String,
153 pub last_activity_ms: u64,
154 pub archived: bool,
158}
159
160const SUBAGENT_ORIGIN: &str = "subagent:";
163
164const BOT_ORIGIN: &str = "bot:";
168
169const FLARE_ORIGIN: &str = "flare:";
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub struct FlareOrigin<'a> {
177 pub run: &'a str,
178 pub n: usize,
180}
181
182impl SessionInfo {
183 pub fn subagent(&self) -> Option<SubagentOrigin<'_>> {
185 let rest = self.origin.strip_prefix(SUBAGENT_ORIGIN)?;
186 let (parent, route) = rest.split_once(':')?;
187 Some(SubagentOrigin { parent, route })
188 }
189
190 pub fn bot(&self) -> Option<&str> {
195 self.origin
196 .strip_prefix(BOT_ORIGIN)
197 .filter(|name| !name.is_empty() && !name.contains(':'))
198 }
199
200 pub fn is_bot(&self) -> bool {
202 self.bot().is_some()
203 }
204
205 pub fn flare(&self) -> Option<FlareOrigin<'_>> {
210 let rest = self.origin.strip_prefix(FLARE_ORIGIN)?;
211 let (run, n) = rest.rsplit_once(':')?;
212 let n: usize = n.parse().ok()?;
213 (!run.is_empty() && n > 0).then_some(FlareOrigin { run, n })
214 }
215
216 pub fn is_flare(&self) -> bool {
218 self.flare().is_some()
219 }
220
221 pub fn tagged_label(&self) -> String {
225 if let Some(o) = self.subagent() {
226 return format!("[subagent \u{b7} {}] {}", o.route, self.label());
227 }
228 if let Some(name) = self.bot() {
229 return format!("[bot \u{b7} {name}] {}", self.label());
230 }
231 if let Some(f) = self.flare() {
232 return format!("[flare \u{b7} {}/{}] {}", f.run, f.n, self.label());
233 }
234 self.label().to_string()
235 }
236
237 pub fn label(&self) -> &str {
239 match (&self.title, self.preview.is_empty()) {
240 (Some(t), _) => t,
241 (None, false) => &self.preview,
242 (None, true) => &self.id,
243 }
244 }
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
251pub enum TitleSource {
252 Derived,
254 Llm,
256 User,
258}
259
260impl TitleSource {
261 pub fn as_str(self) -> &'static str {
262 match self {
263 TitleSource::Derived => "derived",
264 TitleSource::Llm => "llm",
265 TitleSource::User => "user",
266 }
267 }
268}
269
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub enum ExportFormat {
272 Json,
273 Markdown,
274}
275
276const MAX_TITLE_CHARS: usize = 200;
277
278pub const PRUNE_CONFIRM_ABOVE: usize = 10;
281
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub enum AutoPrune {
285 NoLimits,
287 Nothing,
289 Pruned {
292 removed: usize,
293 failed: usize,
294 pinned_kept: usize,
295 },
296 Skipped { would_remove: usize },
299}
300
301#[derive(Debug, Clone, Default, PartialEq, Eq)]
303pub struct PrunePlan {
304 pub candidates: Vec<String>,
306 pub pinned_kept: usize,
308 pub archived_kept: usize,
312}
313
314#[derive(Serialize, Deserialize)]
316struct Meta {
317 title: String,
318}
319
320const MAX_MEMORY_FILE_BYTES: u64 = 64 * 1024;
321
322pub const MEMORY_VERSION: u32 = 3;
327
328#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
335pub struct Handoff {
336 pub text: String,
337 pub version: String,
339 pub covered_turns: usize,
341 pub covered_messages: usize,
343 #[serde(default)]
350 pub covered_from: Option<u64>,
351 #[serde(default)]
352 pub covered_to: Option<u64>,
353 pub generated_at_ms: u64,
354 #[serde(default)]
358 pub judgement: Option<Judgement>,
359}
360
361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
363pub struct Judgement {
364 pub text: String,
365 pub model: String,
367 pub generated_at_ms: u64,
368}
369
370impl Handoff {
371 pub fn covers(
381 &self,
382 turns: usize,
383 messages: usize,
384 from: Option<u64>,
385 to: Option<u64>,
386 ) -> bool {
387 self.version == crate::compact::VERSION
388 && self.covered_turns == turns
389 && self.covered_messages == messages
390 && match (self.covered_from, self.covered_to, from, to) {
391 (Some(a), Some(b), Some(c), Some(d)) => a == c && b == d,
392 _ => false,
393 }
394 }
395}
396
397#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407pub struct Memory {
408 #[serde(default)]
410 pub version: u32,
411 #[serde(default)]
413 pub handoff: Option<Handoff>,
414}
415
416impl Memory {
417 pub fn schema(&self) -> u32 {
419 self.version.max(1)
420 }
421
422 pub fn validate(&self) -> std::result::Result<(), String> {
425 let schema = self.schema();
426 if schema > MEMORY_VERSION {
427 return Err(format!(
428 "memory schema {schema} is newer than this build understands ({MEMORY_VERSION})"
429 ));
430 }
431 if self.handoff.is_some() && schema < 2 {
432 return Err("a handoff in a v1 memory file".into());
433 }
434 if self.handoff.is_none() {
435 return Err("nothing remembered".into());
436 }
437 if let Some(h) = &self.handoff {
438 if h.text.trim().is_empty() {
439 return Err("empty handoff".into());
440 }
441 if h.text.trim() != h.text {
442 return Err("handoff is not trimmed".into());
443 }
444 if h.covered_turns == 0 || h.covered_messages < h.covered_turns {
445 return Err("inconsistent handoff counts".into());
446 }
447 if let Some(j) = &h.judgement {
448 if j.text.trim().is_empty() || j.text.trim() != j.text {
449 return Err("empty or untrimmed judgement".into());
450 }
451 }
452 }
453 Ok(())
454 }
455
456 pub fn usable_handoff(&self) -> Option<&Handoff> {
459 self.validate().ok()?;
460 self.handoff.as_ref()
461 }
462}
463
464#[derive(Clone)]
465pub struct SessionStore {
466 dir: PathBuf,
467 db: Arc<Mutex<Option<Db>>>,
470}
471
472impl std::fmt::Debug for SessionStore {
473 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474 f.debug_struct("SessionStore")
476 .field("dir", &self.dir)
477 .finish()
478 }
479}
480
481pub const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(30);
483
484const LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(50);
486
487#[derive(Debug)]
490pub struct SessionLock {
491 id: String,
492 _file: std::fs::File,
494}
495
496impl SessionLock {
497 pub fn id(&self) -> &str {
498 &self.id
499 }
500}
501
502fn goal_state(word: String) -> crate::goals::State {
505 use crate::goals::State;
506 match word.as_str() {
507 "active" => State::Active,
508 "paused" => State::Paused,
509 "done" => State::Done,
510 "blocked" => State::Blocked,
511 _ => State::Stopped,
512 }
513}
514
515fn open_lock_file(path: &Path) -> Result<std::fs::File> {
516 let mut opts = std::fs::OpenOptions::new();
517 opts.create(true).read(true).write(true);
518 #[cfg(unix)]
519 {
520 use std::os::unix::fs::OpenOptionsExt;
521 opts.mode(0o600);
522 }
523 opts.open(path).map_err(|e| Error::io(path, e))
524}
525
526fn write_lock_holder(file: &mut std::fs::File) {
529 let text = format!("pid {}\n", std::process::id());
530 let _ = file.set_len(0);
531 let _ = file.seek(SeekFrom::Start(0));
532 let _ = file.write_all(text.as_bytes());
533 let _ = file.flush();
534}
535
536#[cfg(unix)]
537fn try_lock_exclusive(file: &std::fs::File) -> std::io::Result<bool> {
538 use std::os::unix::io::AsRawFd;
539 let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
541 if rc == 0 {
542 return Ok(true);
543 }
544 let err = std::io::Error::last_os_error();
545 match err.raw_os_error() {
546 Some(libc::EWOULDBLOCK) => Ok(false),
548 _ => Err(err),
549 }
550}
551
552#[cfg(not(unix))]
553fn try_lock_exclusive(_file: &std::fs::File) -> std::io::Result<bool> {
554 Ok(true)
557}
558
559#[derive(Debug, Clone, PartialEq, Eq)]
561pub struct HeldLock {
562 pub id: String,
563 pub holder: String,
565}
566
567pub fn held_locks(dir: &Path) -> Vec<HeldLock> {
575 let Ok(entries) = std::fs::read_dir(dir) else {
576 return Vec::new();
577 };
578 let mut held = Vec::new();
579 for entry in entries.flatten() {
580 let path = entry.path();
581 let Some(id) = path
582 .file_name()
583 .and_then(|n| n.to_str())
584 .and_then(|n| n.strip_suffix(".lock"))
585 else {
586 continue;
587 };
588 if validate_id(id).is_err() {
589 continue;
590 }
591 let Ok(file) = std::fs::File::open(&path) else {
592 continue;
593 };
594 if is_locked_by_another(&file) {
595 let holder = std::fs::read_to_string(&path)
596 .ok()
597 .map(|s| s.trim().to_string())
598 .filter(|s| !s.is_empty())
599 .unwrap_or_else(|| "another process".to_string());
600 held.push(HeldLock {
601 id: id.to_string(),
602 holder,
603 });
604 }
605 }
606 held.sort_by(|a, b| a.id.cmp(&b.id));
607 held
608}
609
610#[cfg(unix)]
611#[derive(Debug, Clone, PartialEq, Eq)]
614pub struct StaleLock {
615 pub path: PathBuf,
616 pub id: String,
619 pub holder: String,
621}
622
623pub fn stale_locks(dir: &Path) -> Vec<StaleLock> {
629 let Ok(entries) = std::fs::read_dir(dir) else {
630 return Vec::new();
631 };
632 let mut stale = Vec::new();
633 for entry in entries.flatten() {
634 let path = entry.path();
635 let Some(id) = path
636 .file_name()
637 .and_then(|n| n.to_str())
638 .and_then(|n| n.strip_suffix(".lock"))
639 else {
640 continue;
641 };
642 if validate_id(id).is_err() {
643 continue;
644 }
645 let Ok(file) = std::fs::File::open(&path) else {
646 continue;
647 };
648 if is_locked_by_another(&file) {
649 continue;
650 }
651 let holder = std::fs::read_to_string(&path)
652 .ok()
653 .map(|s| s.trim().to_string())
654 .filter(|s| !s.is_empty())
655 .unwrap_or_else(|| "another process".to_string());
656 let id = id.to_string();
657 stale.push(StaleLock { path, id, holder });
658 }
659 stale.sort_by(|a, b| a.path.cmp(&b.path));
660 stale
661}
662
663fn is_locked_by_another(file: &std::fs::File) -> bool {
664 use std::os::unix::io::AsRawFd;
665 let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) };
667 if rc == 0 {
668 return false;
670 }
671 std::io::Error::last_os_error().raw_os_error() == Some(libc::EWOULDBLOCK)
672}
673
674#[cfg(not(unix))]
675fn is_locked_by_another(_file: &std::fs::File) -> bool {
676 false
677}
678
679static COUNTER: AtomicU64 = AtomicU64::new(0);
680
681pub fn now_ms() -> u64 {
682 SystemTime::now()
683 .duration_since(UNIX_EPOCH)
684 .map(|d| d.as_millis() as u64)
685 .unwrap_or(0)
686}
687
688pub fn ago_words(at_ms: u64) -> String {
691 if at_ms == 0 {
692 return String::new();
693 }
694 let secs = now_ms().saturating_sub(at_ms) / 1000;
695 match secs {
696 0..=59 => "just now".to_string(),
697 60..=3_599 => format!("{}m ago", secs / 60),
698 3_600..=86_399 => format!("{}h ago", secs / 3_600),
699 _ => format!("{}d ago", secs / 86_400),
700 }
701}
702
703pub fn validate_id(id: &str) -> Result<()> {
705 let ok = !id.is_empty()
706 && id.len() <= 64
707 && id
708 .chars()
709 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
710 if ok {
711 Ok(())
712 } else {
713 Err(Error::Session(format!("invalid session id {id:?}")))
714 }
715}
716
717impl SessionStore {
718 pub fn new(dir: impl Into<PathBuf>) -> Self {
719 Self {
720 dir: dir.into(),
721 db: std::sync::Arc::new(std::sync::Mutex::new(None)),
722 }
723 }
724
725 pub fn dir(&self) -> &Path {
726 &self.dir
727 }
728
729 pub fn new_id(&self) -> String {
731 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
732 format!("{}-{}-{}", now_ms(), std::process::id(), n)
733 }
734
735 fn lock_path(&self, id: &str) -> Result<PathBuf> {
736 validate_id(id)?;
737 Ok(self.dir.join(format!("{id}.lock")))
738 }
739
740 pub(crate) fn with_db<T>(&self, f: impl FnOnce(&mut Db) -> Result<T>) -> Result<T> {
749 let mut guard = self
750 .db
751 .lock()
752 .map_err(|_| Error::Session("session store is poisoned".into()))?;
753 if guard.is_none() {
754 *guard = Some(Db::open(&self.dir)?);
755 }
756 f(guard.as_mut().expect("just opened"))
757 }
758
759 pub async fn lock(&self, id: &str, wait: std::time::Duration) -> Result<SessionLock> {
768 let path = self.lock_path(id)?;
769 std::fs::create_dir_all(&self.dir).map_err(|e| Error::io(&self.dir, e))?;
770 let mut file = open_lock_file(&path)?;
771 let started = std::time::Instant::now();
772 loop {
773 match try_lock_exclusive(&file) {
774 Ok(true) => {
775 write_lock_holder(&mut file);
776 return Ok(SessionLock {
777 id: id.to_string(),
778 _file: file,
779 });
780 }
781 Ok(false) => {
782 if started.elapsed() >= wait {
783 let holder = std::fs::read_to_string(&path)
784 .ok()
785 .map(|s| s.trim().to_string())
786 .filter(|s| !s.is_empty())
787 .unwrap_or_else(|| "another process".to_string());
788 return Err(Error::Session(format!(
789 "session {id} is in use by {holder}; waited {}s",
790 wait.as_secs()
791 )));
792 }
793 tokio::time::sleep(LOCK_POLL).await;
794 }
795 Err(e) => return Err(Error::io(&path, e)),
796 }
797 }
798 }
799
800 pub fn try_lock(&self, id: &str) -> Result<Option<SessionLock>> {
807 let path = self.lock_path(id)?;
808 std::fs::create_dir_all(&self.dir).map_err(|e| Error::io(&self.dir, e))?;
809 let mut file = open_lock_file(&path)?;
810 match try_lock_exclusive(&file) {
811 Ok(true) => {
812 write_lock_holder(&mut file);
813 Ok(Some(SessionLock {
814 id: id.to_string(),
815 _file: file,
816 }))
817 }
818 Ok(false) => Ok(None),
819 Err(e) => Err(Error::io(&path, e)),
820 }
821 }
822
823 pub fn set_goal(&self, goal: &crate::goals::Goal) -> Result<()> {
828 validate_id(&goal.session)?;
829 self.with_db(|db| {
830 let tx = db
834 .conn
835 .transaction_with_behavior(TransactionBehavior::Immediate)?;
836 tx.execute(
837 "INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
838 VALUES (?1, ?2, ?2, 0, 'native')
839 ON CONFLICT(id) DO NOTHING",
840 params![goal.session, goal.created_ms],
841 )
842 .map_err(|e| Error::Session(format!("could not ensure the session row: {e}")))?;
843 tx.execute(
844 "INSERT INTO goals
845 (session_id, text, gate, budget, turns, state, note, garbage,
846 created_ms, updated_ms)
847 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
848 ON CONFLICT(session_id) DO UPDATE SET
849 text = excluded.text, gate = excluded.gate, budget = excluded.budget,
850 turns = excluded.turns, state = excluded.state, note = excluded.note,
851 garbage = excluded.garbage, updated_ms = excluded.updated_ms",
852 params![
853 goal.session,
854 goal.text,
855 goal.gate,
856 goal.budget as i64,
857 goal.turns as i64,
858 goal.state.as_str(),
859 goal.note,
860 goal.garbage as i64,
861 goal.created_ms,
862 goal.updated_ms,
863 ],
864 )
865 .map_err(|e| Error::Session(format!("could not save the goal: {e}")))?;
866 tx.commit()?;
867 Ok(())
868 })
869 }
870
871 pub fn set_plan(&self, session: &str, items: &[crate::plans::Item]) -> Result<u64> {
881 validate_id(session)?;
882 let now = now_ms();
883 self.with_db(|db| {
884 let tx = db
885 .conn
886 .transaction_with_behavior(TransactionBehavior::Immediate)?;
887 tx.execute(
888 "INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
889 VALUES (?1, ?2, ?2, 0, 'native')
890 ON CONFLICT(id) DO NOTHING",
891 params![session, now as i64],
892 )
893 .map_err(|e| Error::Session(format!("could not ensure the session row: {e}")))?;
894 tx.execute(
895 "INSERT INTO plans (session_id, revision, updated_ms) VALUES (?1, 1, ?2)
896 ON CONFLICT(session_id) DO UPDATE SET
897 revision = revision + 1,
898 updated_ms = excluded.updated_ms",
899 params![session, now as i64],
900 )
901 .map_err(|e| Error::Session(format!("could not save the plan: {e}")))?;
902 let revision: i64 = tx
903 .query_row(
904 "SELECT revision FROM plans WHERE session_id = ?1",
905 params![session],
906 |r| r.get(0),
907 )
908 .map_err(|e| Error::Session(format!("could not read the plan revision: {e}")))?;
909 tx.execute(
910 "DELETE FROM plan_items WHERE session_id = ?1",
911 params![session],
912 )
913 .map_err(|e| Error::Session(format!("could not replace the steps: {e}")))?;
914 for (position, item) in items.iter().enumerate() {
915 tx.execute(
916 "INSERT INTO plan_items (session_id, id, content, status, parent, position)
917 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
918 params![
919 session,
920 item.id,
921 item.content,
922 item.status.as_str(),
923 item.parent,
924 position as i64
925 ],
926 )
927 .map_err(|e| Error::Session(format!("could not save step `{}`: {e}", item.id)))?;
928 }
929 tx.commit()?;
930 Ok(revision as u64)
931 })
932 }
933
934 pub fn plan(&self, session: &str) -> Result<Option<crate::plans::Plan>> {
936 validate_id(session)?;
937 self.with_db(|db| {
938 let revision: Option<i64> = db
939 .conn
940 .query_row(
941 "SELECT revision FROM plans WHERE session_id = ?1",
942 params![session],
943 |r| r.get(0),
944 )
945 .optional()?;
946 let Some(revision) = revision else {
947 return Ok(None);
948 };
949 let mut stmt = db.conn.prepare(
950 "SELECT id, content, status, parent FROM plan_items
951 WHERE session_id = ?1 ORDER BY position",
952 )?;
953 let items = stmt
954 .query_map(params![session], |r| {
955 Ok(crate::plans::Item {
956 id: r.get(0)?,
957 content: r.get(1)?,
958 status: crate::plans::Status::parse(&r.get::<_, String>(2)?)
962 .unwrap_or(crate::plans::Status::Pending),
963 parent: r.get(3)?,
964 })
965 })?
966 .collect::<std::result::Result<Vec<_>, _>>()?;
967 Ok(Some(crate::plans::Plan {
968 revision: revision as u64,
969 items,
970 }))
971 })
972 }
973
974 pub fn goal(&self, id: &str) -> Result<Option<crate::goals::Goal>> {
976 validate_id(id)?;
977 self.with_db(|db| {
978 let found = db
979 .conn
980 .query_row(
981 "SELECT text, gate, budget, turns, state, note, garbage, created_ms, updated_ms
982 FROM goals WHERE session_id = ?1",
983 params![id],
984 |r| {
985 Ok(crate::goals::Goal {
986 session: id.to_string(),
987 text: r.get(0)?,
988 gate: r.get(1)?,
989 budget: r.get::<_, i64>(2)? as u32,
990 turns: r.get::<_, i64>(3)? as u32,
991 state: goal_state(r.get::<_, String>(4)?),
992 note: r.get(5)?,
993 garbage: r.get::<_, i64>(6)? != 0,
994 created_ms: r.get(7)?,
995 updated_ms: r.get(8)?,
996 })
997 },
998 )
999 .optional()?;
1000 Ok(found)
1001 })
1002 }
1003
1004 pub fn clear_goal(&self, id: &str) -> Result<()> {
1006 validate_id(id)?;
1007 self.with_db(|db| {
1008 let tx = db
1012 .conn
1013 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1014 tx.execute("DELETE FROM goals WHERE session_id = ?1", params![id])
1015 .map_err(|e| Error::Session(format!("could not clear the goal: {e}")))?;
1016 tx.execute("DELETE FROM goal_turns WHERE session_id = ?1", params![id])
1017 .map_err(|e| Error::Session(format!("could not clear the judgements: {e}")))?;
1018 tx.commit()?;
1019 Ok(())
1020 })
1021 }
1022
1023 pub fn record_goal_turn(&self, id: &str, judgement: &crate::goals::Judgement) -> Result<()> {
1025 validate_id(id)?;
1026 self.with_db(|db| {
1027 db.conn
1028 .execute(
1029 "INSERT INTO goal_turns (session_id, turn, verdict, why, at_ms)
1030 VALUES (?1, ?2, ?3, ?4, ?5)
1031 ON CONFLICT(session_id, turn) DO UPDATE SET
1032 verdict = excluded.verdict, why = excluded.why, at_ms = excluded.at_ms",
1033 params![
1034 id,
1035 judgement.turn as i64,
1036 judgement.verdict,
1037 judgement.why,
1038 judgement.at_ms,
1039 ],
1040 )
1041 .map_err(|e| Error::Session(format!("could not record the judgement: {e}")))?;
1042 Ok(())
1043 })
1044 }
1045
1046 pub fn goal_turns(&self, id: &str) -> Result<Vec<crate::goals::Judgement>> {
1048 validate_id(id)?;
1049 self.with_db(|db| {
1050 let mut stmt = db
1051 .conn
1052 .prepare(
1053 "SELECT turn, verdict, why, at_ms FROM goal_turns
1054 WHERE session_id = ?1 ORDER BY turn",
1055 )
1056 .map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
1057 let rows = stmt
1058 .query_map(params![id], |r| {
1059 Ok(crate::goals::Judgement {
1060 turn: r.get::<_, i64>(0)? as u32,
1061 verdict: r.get(1)?,
1062 why: r.get(2)?,
1063 at_ms: r.get(3)?,
1064 })
1065 })
1066 .map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
1067 Ok(rows.flatten().collect())
1068 })
1069 }
1070
1071 pub fn live_goals(&self) -> Result<Vec<crate::goals::Goal>> {
1076 self.with_db(|db| {
1077 let mut stmt = db
1078 .conn
1079 .prepare(
1080 "SELECT session_id, text, gate, budget, turns, state, note, garbage,
1081 created_ms, updated_ms
1082 FROM goals WHERE state IN ('active', 'paused') ORDER BY updated_ms DESC",
1083 )
1084 .map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
1085 let rows = stmt
1086 .query_map([], |r| {
1087 Ok(crate::goals::Goal {
1088 session: r.get(0)?,
1089 text: r.get(1)?,
1090 gate: r.get(2)?,
1091 budget: r.get::<_, i64>(3)? as u32,
1092 turns: r.get::<_, i64>(4)? as u32,
1093 state: goal_state(r.get::<_, String>(5)?),
1094 note: r.get(6)?,
1095 garbage: r.get::<_, i64>(7)? != 0,
1096 created_ms: r.get(8)?,
1097 updated_ms: r.get(9)?,
1098 })
1099 })
1100 .map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
1101 Ok(rows.flatten().collect())
1102 })
1103 }
1104
1105 pub fn is_busy(&self, id: &str) -> bool {
1111 match self.try_lock(id) {
1112 Ok(Some(lock)) => {
1113 drop(lock);
1114 false
1115 }
1116 Ok(None) => true,
1117 Err(_) => false,
1120 }
1121 }
1122
1123 pub fn exists(&self, id: &str) -> bool {
1124 if validate_id(id).is_err() {
1125 return false;
1126 }
1127 self.with_db(|db| {
1128 let found: Option<i64> = db
1129 .conn
1130 .query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
1131 r.get(0)
1132 })
1133 .optional()?;
1134 Ok(found.is_some())
1135 })
1136 .unwrap_or(false)
1137 }
1138
1139 pub fn record_pending(
1145 &self,
1146 id: &str,
1147 seq: i64,
1148 calls: &[crate::approvals::Pending],
1149 ) -> Result<()> {
1150 self.record_pending_at(id, seq, 0, calls)
1151 }
1152
1153 pub fn record_pending_at(
1159 &self,
1160 id: &str,
1161 seq: i64,
1162 ord: usize,
1163 calls: &[crate::approvals::Pending],
1164 ) -> Result<()> {
1165 validate_id(id)?;
1166 self.with_db(|db| {
1167 let tx = db.conn.transaction()?;
1168 for (offset, call) in calls.iter().enumerate() {
1169 tx.execute(
1170 "INSERT INTO approvals
1171 (session_id, seq, ord, call_id, tool, summary, args, decision, decided_ms)
1172 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, NULL)
1173 ON CONFLICT(session_id, seq, ord) DO NOTHING",
1174 params![
1175 id,
1176 seq,
1177 (ord + offset) as i64,
1178 call.call_id,
1179 call.tool,
1180 call.summary,
1181 call.args
1182 ],
1183 )?;
1184 }
1185 tx.commit()?;
1186 Ok(())
1187 })
1188 }
1189
1190 pub fn pending_calls(&self, id: &str) -> Result<Vec<crate::approvals::PendingCall>> {
1193 validate_id(id)?;
1194 self.with_db(|db| {
1195 let mut stmt = db.conn.prepare(
1196 "SELECT seq, ord, call_id, tool, summary, args, decision, decided_ms, by
1197 FROM approvals WHERE session_id = ?1 ORDER BY seq, ord",
1198 )?;
1199 let rows = stmt
1200 .query_map(params![id], |r| {
1201 let stored: Option<String> = r.get(6)?;
1202 Ok(crate::approvals::PendingCall {
1203 seq: r.get(0)?,
1204 ord: r.get::<_, i64>(1)? as usize,
1205 call: crate::approvals::Pending::new(
1206 r.get::<_, String>(2)?,
1207 r.get::<_, String>(3)?,
1208 r.get::<_, String>(4)?,
1209 r.get::<_, String>(5)?,
1210 ),
1211 decision: stored.as_deref().map(crate::approvals::Decision::parse),
1212 decided_ms: r.get(7)?,
1213 by: r.get(8)?,
1214 })
1215 })?
1216 .collect::<std::result::Result<Vec<_>, _>>()?;
1217 Ok(rows)
1218 })
1219 }
1220
1221 pub fn decide_pending(
1225 &self,
1226 id: &str,
1227 seq: i64,
1228 ord: usize,
1229 decision: &crate::approvals::Decision,
1230 by: &str,
1231 ) -> Result<()> {
1232 validate_id(id)?;
1233 let Some(stored) = decision.store() else {
1236 return Ok(());
1237 };
1238 let now = now_ms() as i64;
1239 let changed = self.with_db(|db| {
1240 let tx = db
1246 .conn
1247 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1248 let changed = tx.execute(
1249 "UPDATE approvals SET decision = ?4, decided_ms = ?5, by = ?6
1250 WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
1251 params![&id, seq, ord as i64, &stored, now, by],
1252 )?;
1253 if changed > 0 {
1256 tx.execute(
1257 "INSERT INTO approval_log
1258 (session_id, at_ms, call_id, tool, summary, decision, by)
1259 SELECT session_id, ?4, call_id, tool, summary, ?5, ?6 FROM approvals
1260 WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
1261 params![&id, seq, ord as i64, now, &stored, by],
1262 )?;
1263 }
1264 tx.commit()?;
1265 Ok(changed)
1266 })?;
1267 if changed == 0 {
1268 return Err(Error::Session(format!(
1269 "{id}: no tool call recorded at message {seq}, position {ord}"
1270 )));
1271 }
1272 Ok(())
1273 }
1274
1275 pub fn log_decision(
1281 &self,
1282 id: &str,
1283 call: &crate::approvals::Pending,
1284 decision: &crate::approvals::Decision,
1285 by: &str,
1286 ) -> Result<()> {
1287 validate_id(id)?;
1288 let Some(stored) = decision.store() else {
1289 return Ok(());
1290 };
1291 let now = now_ms() as i64;
1292 self.with_db(|db| {
1293 Ok(db.conn.execute(
1294 "INSERT INTO approval_log (session_id, at_ms, call_id, tool, summary, decision, by)
1295 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1296 params![
1297 id,
1298 now,
1299 &call.call_id,
1300 &call.tool,
1301 &call.summary,
1302 &stored,
1303 by
1304 ],
1305 )?)
1306 })?;
1307 Ok(())
1308 }
1309
1310 pub fn approval_log(&self, id: &str) -> Result<Vec<crate::approvals::Ruling>> {
1316 validate_id(id)?;
1317 self.with_db(|db| {
1318 let mut stmt = db.conn.prepare(
1319 "SELECT at_ms, call_id, tool, summary, decision, by FROM approval_log
1320 WHERE session_id = ?1 ORDER BY at_ms, rowid",
1321 )?;
1322 let rows = stmt
1323 .query_map(params![id], |r| {
1324 Ok(crate::approvals::Ruling {
1325 at_ms: r.get(0)?,
1326 call_id: r.get(1)?,
1327 tool: r.get(2)?,
1328 summary: r.get(3)?,
1329 decision: crate::approvals::Decision::parse(&r.get::<_, String>(4)?),
1330 by: r.get(5)?,
1331 })
1332 })?
1333 .collect::<std::result::Result<Vec<_>, _>>()?;
1334 Ok(rows)
1335 })
1336 }
1337
1338 pub fn clear_pending(&self, id: &str) -> Result<usize> {
1341 validate_id(id)?;
1342 self.with_db(|db| {
1343 Ok(db
1344 .conn
1345 .execute("DELETE FROM approvals WHERE session_id = ?1", params![id])?)
1346 })
1347 }
1348
1349 pub fn clear_call(&self, id: &str, call_id: &str) -> Result<usize> {
1352 validate_id(id)?;
1353 self.with_db(|db| {
1354 Ok(db.conn.execute(
1355 "DELETE FROM approvals WHERE session_id = ?1 AND call_id = ?2",
1356 params![id, call_id],
1357 )?)
1358 })
1359 }
1360
1361 pub fn last_seq(&self, id: &str) -> Result<i64> {
1363 validate_id(id)?;
1364 self.with_db(|db| {
1365 Ok(db.conn.query_row(
1366 "SELECT COALESCE(MAX(seq), -1) FROM messages WHERE session_id = ?1",
1367 params![id],
1368 |r| r.get(0),
1369 )?)
1370 })
1371 }
1372
1373 pub fn set_tool_outcome(&self, id: &str, call_id: &str, is_error: bool) -> Result<()> {
1380 validate_id(id)?;
1381 let session = id.to_string();
1382 let call = call_id.to_string();
1383 self.with_db(|db| {
1384 db.conn
1385 .execute(
1386 "INSERT INTO tool_outcomes (session_id, call_id, is_error) VALUES (?1, ?2, ?3)
1387 ON CONFLICT (session_id, call_id) DO UPDATE SET is_error = excluded.is_error",
1388 rusqlite::params![session, call, is_error as i64],
1389 )
1390 .map_err(|e| Error::Session(e.to_string()))?;
1391 Ok(())
1392 })
1393 }
1394
1395 pub fn tool_outcomes(&self, id: &str) -> Result<std::collections::HashMap<String, bool>> {
1398 validate_id(id)?;
1399 let session = id.to_string();
1400 self.with_db(|db| {
1401 let mut stmt = db
1402 .conn
1403 .prepare("SELECT call_id, is_error FROM tool_outcomes WHERE session_id = ?1")
1404 .map_err(|e| Error::Session(e.to_string()))?;
1405 let rows = stmt
1406 .query_map(rusqlite::params![session], |row| {
1407 Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? != 0))
1408 })
1409 .map_err(|e| Error::Session(e.to_string()))?;
1410 let mut out = std::collections::HashMap::new();
1411 for row in rows {
1412 let (call, is_error) = row.map_err(|e| Error::Session(e.to_string()))?;
1413 out.insert(call, is_error);
1414 }
1415 Ok(out)
1416 })
1417 }
1418
1419 pub fn append(&self, id: &str, message: &Message) -> Result<()> {
1420 self.append_seq(id, message).map(|_| ())
1421 }
1422
1423 pub fn append_seq(&self, id: &str, message: &Message) -> Result<i64> {
1427 validate_id(id)?;
1428 let now = now_ms() as i64;
1429 let body = serde_json::to_string(message).map_err(|e| Error::Session(e.to_string()))?;
1430 let role = role_name(message.role);
1431 let preview = (message.role == Role::User)
1434 .then(|| {
1435 message
1436 .content
1437 .as_deref()
1438 .map(|t| t.split_whitespace().collect::<Vec<_>>().join(" "))
1439 .map(|t| t.chars().take(60).collect::<String>())
1440 })
1441 .flatten()
1442 .filter(|p| !p.trim().is_empty());
1446
1447 self.with_db(|db| {
1448 let tx = db.conn.transaction()?;
1449 tx.execute(
1452 "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
1453 VALUES (?1, ?2, ?2, NULL, NULL, 0, 'native')
1454 ON CONFLICT(id) DO NOTHING",
1455 params![id, now],
1456 )?;
1457 let seq: i64 = tx.query_row(
1458 "SELECT COALESCE(MAX(seq), -1) + 1 FROM messages WHERE session_id = ?1",
1459 params![id],
1460 |r| r.get(0),
1461 )?;
1462 tx.execute(
1463 "INSERT INTO messages (session_id, seq, at_ms, role, body)
1464 VALUES (?1, ?2, ?3, ?4, ?5)",
1465 params![id, seq, now, role, body],
1466 )?;
1467 tx.execute(
1468 "UPDATE sessions
1469 SET updated_ms = ?2,
1470 messages = messages + 1,
1471 preview = COALESCE(preview, ?3)
1472 WHERE id = ?1",
1473 params![id, now, preview],
1474 )?;
1475 if db.fts {
1476 tx.execute(
1477 "INSERT INTO messages_fts (session_id, seq, content) VALUES (?1, ?2, ?3)",
1478 params![id, seq, searchable(message)],
1479 )?;
1480 }
1481 tx.commit()?;
1482 Ok(seq)
1483 })
1484 }
1485
1486 pub fn begin_subagent(&self, id: &str, parent: &str, route: &str) -> Result<()> {
1491 validate_id(parent)?;
1492 self.begin_row(id, &format!("{SUBAGENT_ORIGIN}{parent}:{route}"))
1493 }
1494
1495 pub fn begin_flare(&self, id: &str, run: &str, n: usize) -> Result<()> {
1500 if run.is_empty() || run.contains(':') {
1501 return Err(Error::Config(format!(
1502 "a flare run id is one word without a colon, not {run:?}"
1503 )));
1504 }
1505 self.begin_row(id, &format!("{FLARE_ORIGIN}{run}:{n}"))
1506 }
1507
1508 pub fn begin_flare_run(
1510 &self,
1511 id: &str,
1512 task: &str,
1513 routes: &[String],
1514 jobs: usize,
1515 parent: &str,
1516 ) -> Result<()> {
1517 let task: String = task.chars().take(500).collect();
1518 self.with_db(|db| {
1519 db.conn.execute(
1520 "INSERT INTO flare_runs (id, task, state, routes, jobs, parent, started_ms)
1521 VALUES (?1, ?2, 'running', ?3, ?4, ?5, ?6)",
1522 params![
1523 id,
1524 task,
1525 routes.join(","),
1526 jobs as i64,
1527 parent,
1528 now_ms() as i64
1529 ],
1530 )?;
1531 Ok(())
1532 })
1533 }
1534
1535 pub fn flare_job_running(&self, run: &str, n: usize, route: &str, session: &str) -> Result<()> {
1537 self.with_db(|db| {
1538 db.conn.execute(
1539 "INSERT INTO flare_jobs (run_id, n, route, session_id, state)
1540 VALUES (?1, ?2, ?3, ?4, 'running')
1541 ON CONFLICT(run_id, n) DO UPDATE SET
1542 route = excluded.route, session_id = excluded.session_id,
1543 state = 'running'",
1544 params![run, n as i64, route, session],
1545 )?;
1546 Ok(())
1547 })
1548 }
1549
1550 #[allow(clippy::too_many_arguments)]
1552 pub fn flare_job_done(&self, done: &FlareJobRow) -> Result<()> {
1553 self.with_db(|db| {
1554 db.conn.execute(
1555 "INSERT INTO flare_jobs (run_id, n, route, session_id, state, prompt_tokens,
1556 completion_tokens, iterations, why)
1557 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
1558 ON CONFLICT(run_id, n) DO UPDATE SET
1559 route = excluded.route, session_id = excluded.session_id,
1560 state = excluded.state, prompt_tokens = excluded.prompt_tokens,
1561 completion_tokens = excluded.completion_tokens,
1562 iterations = excluded.iterations, why = excluded.why",
1563 params![
1564 done.run_id,
1565 done.n as i64,
1566 done.route,
1567 done.session_id,
1568 done.state,
1569 done.prompt_tokens.map(|v| v as i64),
1570 done.completion_tokens.map(|v| v as i64),
1571 done.iterations as i64,
1572 done.why,
1573 ],
1574 )?;
1575 Ok(())
1576 })
1577 }
1578
1579 #[allow(clippy::too_many_arguments)]
1581 pub fn finish_flare_run(
1582 &self,
1583 id: &str,
1584 state: &str,
1585 prompt: Option<u64>,
1586 completion: Option<u64>,
1587 iterations: usize,
1588 ) -> Result<()> {
1589 self.with_db(|db| {
1590 db.conn.execute(
1591 "UPDATE flare_runs SET state = ?2, finished_ms = ?3, prompt_tokens = ?4,
1592 completion_tokens = ?5, iterations = ?6
1593 WHERE id = ?1",
1594 params![
1595 id,
1596 state,
1597 now_ms() as i64,
1598 prompt.map(|v| v as i64),
1599 completion.map(|v| v as i64),
1600 iterations as i64
1601 ],
1602 )?;
1603 Ok(())
1604 })
1605 }
1606
1607 pub fn cancel_flare_run(&self, id: &str) -> Result<bool> {
1610 self.with_db(|db| {
1611 let n = db.conn.execute(
1612 "UPDATE flare_runs SET cancel_requested = 1 WHERE id = ?1",
1613 params![id],
1614 )?;
1615 Ok(n > 0)
1616 })
1617 }
1618
1619 pub fn flare_cancel_requested(&self, id: &str) -> Result<bool> {
1621 self.with_db(|db| {
1622 let mut stmt = db
1623 .conn
1624 .prepare("SELECT cancel_requested FROM flare_runs WHERE id = ?1")?;
1625 let mut rows = stmt.query(params![id])?;
1626 match rows.next()? {
1627 Some(r) => Ok(r.get::<_, i64>(0)? != 0),
1628 None => Ok(false),
1629 }
1630 })
1631 }
1632
1633 pub fn flare_runs(&self, limit: usize) -> Result<Vec<FlareRunRow>> {
1635 let limit = limit.clamp(1, 200) as i64;
1636 self.with_db(|db| {
1637 let mut stmt = db.conn.prepare(
1638 "SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
1639 prompt_tokens, completion_tokens, iterations
1640 FROM flare_runs ORDER BY started_ms DESC LIMIT ?1",
1641 )?;
1642 let rows = stmt.query_map(params![limit], run_row)?;
1643 Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
1644 })
1645 }
1646
1647 pub fn flare_run(&self, id: &str) -> Result<Option<(FlareRunRow, Vec<FlareJobRow>)>> {
1649 self.with_db(|db| {
1650 let mut stmt = db.conn.prepare(
1651 "SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
1652 prompt_tokens, completion_tokens, iterations
1653 FROM flare_runs WHERE id = ?1",
1654 )?;
1655 let mut rows = stmt.query(params![id])?;
1656 let Some(row) = rows.next()? else {
1657 return Ok(None);
1658 };
1659 let run = run_row(row)?;
1660 let mut stmt = db.conn.prepare(
1661 "SELECT n, route, session_id, state, prompt_tokens, completion_tokens,
1662 iterations, why
1663 FROM flare_jobs WHERE run_id = ?1 ORDER BY n",
1664 )?;
1665 let jobs = stmt
1666 .query_map(params![id], |r| {
1667 Ok(FlareJobRow {
1668 run_id: id.to_string(),
1669 n: r.get::<_, i64>(0)? as usize,
1670 route: r.get(1)?,
1671 session_id: r.get(2)?,
1672 state: r.get(3)?,
1673 prompt_tokens: r.get::<_, Option<i64>>(4)?.map(|v| v as u64),
1674 completion_tokens: r.get::<_, Option<i64>>(5)?.map(|v| v as u64),
1675 iterations: r.get::<_, Option<i64>>(6)?.unwrap_or(0).max(0) as usize,
1676 why: r.get(7)?,
1677 })
1678 })?
1679 .collect::<std::result::Result<Vec<_>, _>>()?;
1680 Ok(Some((run, jobs)))
1681 })
1682 }
1683
1684 pub fn flares_of(&self, run: &str) -> Result<Vec<SessionInfo>> {
1689 let prefix = format!("{FLARE_ORIGIN}{run}:");
1690 let mut out: Vec<SessionInfo> = self
1691 .list_rows(true, true)?
1692 .into_iter()
1693 .filter(|s| s.origin.starts_with(&prefix))
1694 .collect();
1695 out.sort_by_key(|s| s.flare().map_or(0, |f| f.n));
1696 Ok(out)
1697 }
1698
1699 pub const API_ORIGIN: &str = "api";
1702
1703 pub fn begin_api(&self, id: &str) -> Result<()> {
1709 self.begin_row(id, Self::API_ORIGIN)
1710 }
1711
1712 pub fn origin(&self, id: &str) -> Result<Option<String>> {
1719 validate_id(id)?;
1720 self.with_db(|db| {
1721 let found = db
1722 .conn
1723 .query_row(
1724 "SELECT origin FROM sessions WHERE id = ?1",
1725 params![id],
1726 |r| r.get::<_, String>(0),
1727 )
1728 .map(Some)
1729 .or_else(|e| match e {
1730 rusqlite::Error::QueryReturnedNoRows => Ok(None),
1731 other => Err(other),
1732 })?;
1733 Ok(found)
1734 })
1735 }
1736
1737 pub fn begin_bot(&self, id: &str, name: &str) -> Result<()> {
1744 self.begin_row(id, &format!("{BOT_ORIGIN}{name}"))
1745 }
1746
1747 pub fn bot_session(&self, name: &str) -> Result<String> {
1754 let origin = format!("{BOT_ORIGIN}{name}");
1755 for info in self.list_rows(true, true)? {
1756 if info.origin == origin && !info.archived {
1757 return Ok(info.id);
1758 }
1759 }
1760 let id = self.new_id();
1761 self.begin_bot(&id, name)?;
1762 Ok(id)
1763 }
1764
1765 pub fn bot_sessions(&self, name: &str) -> Result<Vec<String>> {
1768 let origin = format!("{BOT_ORIGIN}{name}");
1769 Ok(self
1770 .list_rows(true, true)?
1771 .into_iter()
1772 .filter(|info| info.origin == origin && !info.archived)
1773 .map(|info| info.id)
1774 .collect())
1775 }
1776
1777 fn begin_row(&self, id: &str, origin: &str) -> Result<()> {
1779 validate_id(id)?;
1780 let now = now_ms() as i64;
1781 self.with_db(|db| {
1782 db.conn.execute(
1783 "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
1784 VALUES (?1, ?2, ?2, NULL, NULL, 0, ?3)
1785 ON CONFLICT(id) DO NOTHING",
1786 params![id, now, origin],
1787 )?;
1788 Ok(())
1789 })
1790 }
1791
1792 pub fn prune_api_sessions(&self, cutoff_ms: u64) -> Result<usize> {
1799 let stale: Vec<String> = self
1800 .list()?
1801 .into_iter()
1802 .filter(|s| s.origin == Self::API_ORIGIN && !s.pinned && s.updated_ms < cutoff_ms)
1803 .map(|s| s.id)
1804 .collect();
1805 let mut pruned = 0usize;
1806 for id in stale {
1807 match self.delete(&id) {
1808 Ok(()) => pruned += 1,
1809 Err(Error::Session(_)) => {}
1811 Err(e) => return Err(e),
1812 }
1813 }
1814 Ok(pruned)
1815 }
1816
1817 pub fn load_records(&self, id: &str) -> Result<Vec<Record>> {
1821 validate_id(id)?;
1822 if !self.exists(id) {
1826 return Err(Error::Session(format!("no such session {id:?}")));
1827 }
1828 self.with_db(|db| {
1829 let mut stmt = db.conn.prepare(
1830 "SELECT seq, at_ms, body FROM messages WHERE session_id = ?1 ORDER BY seq",
1831 )?;
1832 let rows = stmt.query_map(params![id], |r| {
1833 Ok((
1834 r.get::<_, i64>(0)?,
1835 r.get::<_, i64>(1)?,
1836 r.get::<_, String>(2)?,
1837 ))
1838 })?;
1839 let mut out = Vec::new();
1840 for row in rows {
1841 let (seq, at, body) = row?;
1842 let mut message: Message = serde_json::from_str(&body)
1843 .map_err(|e| Error::Session(format!("{id}:{seq}: {e}")))?;
1844 message.seq = Some(seq.max(0) as u64);
1847 out.push(Record {
1848 ts: at.max(0) as u64,
1849 message,
1850 });
1851 }
1852 Ok(out)
1853 })
1854 }
1855
1856 #[allow(clippy::unnecessary_wraps)] pub fn load(&self, id: &str) -> Result<Vec<Message>> {
1858 Ok(self
1859 .load_records(id)?
1860 .into_iter()
1861 .map(|r| r.message)
1862 .collect())
1863 }
1864
1865 pub fn title(&self, id: &str) -> Result<Option<String>> {
1867 validate_id(id)?;
1868 self.with_db(|db| {
1869 let title: Option<Option<String>> = db
1870 .conn
1871 .query_row(
1872 "SELECT title FROM sessions WHERE id = ?1",
1873 params![id],
1874 |r| r.get(0),
1875 )
1876 .optional()?;
1877 Ok(title.flatten())
1878 })
1879 }
1880
1881 pub fn rename(&self, id: &str, title: &str) -> Result<()> {
1888 validate_id(id)?;
1889 let title = title.trim();
1890 if title.is_empty() {
1891 return Err(Error::Session("title is empty".into()));
1892 }
1893 if title.chars().count() > MAX_TITLE_CHARS {
1894 return Err(Error::Session(format!(
1895 "title is longer than {MAX_TITLE_CHARS} characters"
1896 )));
1897 }
1898 if title.chars().any(char::is_control) {
1899 return Err(Error::Session("title contains control characters".into()));
1900 }
1901 if !self.set_title(id, title, TitleSource::User)? {
1902 return Err(Error::Session(if self.exists(id) {
1906 format!("session {id:?} did not accept the rename")
1907 } else {
1908 format!("no such session {id:?}")
1909 }));
1910 }
1911 Ok(())
1912 }
1913
1914 pub fn set_title(&self, id: &str, title: &str, source: TitleSource) -> Result<bool> {
1921 validate_id(id)?;
1922 self.with_db(|db| {
1923 let n = db.conn.execute(
1924 "UPDATE sessions SET title = ?2, title_source = ?3, title_note = NULL
1928 WHERE id = ?1
1929 AND ((CASE title_source WHEN 'user' THEN 3 WHEN 'llm' THEN 2
1930 WHEN 'derived' THEN 1 ELSE 0 END)
1931 < (CASE ?3 WHEN 'user' THEN 3 WHEN 'llm' THEN 2
1932 WHEN 'derived' THEN 1 ELSE 0 END)
1933 -- `#563`: a person's rename always wins, including over an earlier
1934 -- person's title. Without this a session named once could never be
1935 -- renamed again, and `rename` blamed the id for it.
1936 OR ?3 = 'user')",
1937 params![id, title, source.as_str()],
1938 )?;
1939 Ok(n > 0)
1940 })
1941 }
1942
1943 pub fn title_if_unnamed(&self, id: &str, name: &str) -> Result<bool> {
1949 validate_id(id)?;
1950 let name = name.trim();
1951 if name.is_empty() || name.chars().any(char::is_control) {
1952 return Ok(false);
1953 }
1954 self.with_db(|db| {
1955 let n = db.conn.execute(
1956 "UPDATE sessions SET title = ?2, title_source = 'derived'
1957 WHERE id = ?1 AND title IS NULL",
1958 params![id, name],
1959 )?;
1960 Ok(n > 0)
1961 })
1962 }
1963
1964 pub fn claim_title_upgrade(&self, id: &str) -> Result<bool> {
1976 validate_id(id)?;
1977 self.with_db(|db| {
1978 let n = db.conn.execute(
1979 "UPDATE sessions SET title_note = 'trying'
1980 WHERE id = ?1 AND title_source = 'derived' AND title_note IS NULL
1981 AND origin NOT LIKE 'subagent:%' AND origin NOT LIKE 'bot:%'
1982 AND origin NOT LIKE 'flare:%' AND origin <> 'api'",
1983 params![id],
1984 )?;
1985 Ok(n > 0)
1986 })
1987 }
1988
1989 pub fn title_attempt_failed(&self, id: &str, why: &str) -> Result<()> {
1992 validate_id(id)?;
1993 let why: String = why.chars().take(300).collect();
1994 self.with_db(|db| {
1995 db.conn.execute(
1996 "UPDATE sessions SET title_note = ?2 WHERE id = ?1",
1997 params![id, why],
1998 )?;
1999 Ok(())
2000 })
2001 }
2002
2003 pub fn release_title_claim(&self, id: &str) -> Result<()> {
2006 validate_id(id)?;
2007 self.with_db(|db| {
2008 db.conn.execute(
2009 "UPDATE sessions SET title_note = NULL WHERE id = ?1 AND title_note = 'trying'",
2010 params![id],
2011 )?;
2012 Ok(())
2013 })
2014 }
2015
2016 pub fn set_last_cost(&self, id: &str, cost: &TurnCost) -> Result<()> {
2026 validate_id(id)?;
2027 let body = serde_json::to_string(cost)
2028 .map_err(|e| Error::Session(format!("a turn's cost did not encode: {e}")))?;
2029 self.with_db(|db| {
2030 db.conn.execute(
2031 "UPDATE sessions SET last_cost = ?2 WHERE id = ?1",
2032 params![id, body],
2033 )?;
2034 Ok(())
2035 })
2036 }
2037
2038 pub fn set_image_seen(&self, id: &str, seq: u64, index: usize, text: &str) -> Result<bool> {
2048 validate_id(id)?;
2049 let seq = i64::try_from(seq)
2050 .map_err(|_| Error::Session(format!("sequence {seq} is out of range")))?;
2051 self.with_db(|db| {
2052 let tx = db.conn.unchecked_transaction()?;
2055 let row: Option<String> = tx
2056 .query_row(
2057 "SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
2058 params![id, seq],
2059 |r| r.get(0),
2060 )
2061 .optional()?;
2062 let Some(body) = row else {
2063 return Ok(false);
2064 };
2065 let mut message: crate::message::Message = serde_json::from_str(&body)
2066 .map_err(|e| Error::Session(format!("a stored message did not decode: {e}")))?;
2067 let Some(image) = message.images.get_mut(index) else {
2068 return Ok(false);
2069 };
2070 image.seen = Some(text.to_string());
2071 let encoded = serde_json::to_string(&message)
2072 .map_err(|e| Error::Session(format!("a message did not encode: {e}")))?;
2073 let n = tx.execute(
2074 "UPDATE messages SET body = ?3 WHERE session_id = ?1 AND seq = ?2",
2075 params![id, seq, encoded],
2076 )?;
2077 if db.fts {
2080 tx.execute(
2081 "UPDATE messages_fts SET content = ?3 WHERE session_id = ?1 AND seq = ?2",
2082 params![id, seq, searchable(&message)],
2083 )?;
2084 }
2085 tx.commit()?;
2086 Ok(n > 0)
2087 })
2088 }
2089
2090 pub fn last_cost(&self, id: &str) -> Result<Option<TurnCost>> {
2093 validate_id(id)?;
2094 self.with_db(|db| {
2095 let body: Option<String> = db
2096 .conn
2097 .query_row(
2098 "SELECT last_cost FROM sessions WHERE id = ?1",
2099 params![id],
2100 |r| r.get(0),
2101 )
2102 .optional()?
2103 .flatten();
2104 Ok(body.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()))
2105 })
2106 }
2107
2108 pub fn set_pinned(&self, id: &str, pinned: bool) -> Result<()> {
2111 validate_id(id)?;
2112 self.with_db(|db| {
2113 let n = db.conn.execute(
2114 "UPDATE sessions SET pinned = ?2 WHERE id = ?1",
2115 params![id, i64::from(pinned)],
2116 )?;
2117 if n == 0 {
2118 return Err(Error::Session(format!("no such session {id:?}")));
2119 }
2120 Ok(())
2121 })
2122 }
2123
2124 pub fn set_archived(&self, id: &str, archived: bool) -> Result<()> {
2132 validate_id(id)?;
2133 self.with_db(|db| {
2134 let n = db.conn.execute(
2135 "UPDATE sessions SET archived = ?2 WHERE id = ?1",
2136 params![id, i64::from(archived)],
2137 )?;
2138 if n == 0 {
2139 return Err(Error::Session(format!("no such session {id:?}")));
2140 }
2141 Ok(())
2142 })
2143 }
2144
2145 pub fn memory(&self, id: &str) -> Result<Option<Memory>> {
2149 validate_id(id)?;
2150 self.with_db(|db| {
2151 let body: Option<String> = db
2152 .conn
2153 .query_row(
2154 "SELECT body FROM memory WHERE session_id = ?1",
2155 params![id],
2156 |r| r.get(0),
2157 )
2158 .optional()?;
2159 let Some(body) = body else { return Ok(None) };
2160 if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
2161 return Err(Error::Session(format!(
2162 "{id}: memory is larger than {MAX_MEMORY_FILE_BYTES} bytes"
2163 )));
2164 }
2165 serde_json::from_str(&body)
2166 .map(Some)
2167 .map_err(|e| Error::Session(format!("{id}: memory: {e}")))
2168 })
2169 }
2170
2171 pub fn readable_memory(&self, id: &str) -> Option<Memory> {
2174 self.memory(id)
2175 .ok()
2176 .flatten()
2177 .filter(|m| m.validate().is_ok())
2178 }
2179
2180 pub fn save_handoff(
2186 &self,
2187 id: &str,
2188 covered: crate::context::Trimmed,
2189 span: (Option<u64>, Option<u64>),
2190 text: &str,
2191 judgement: Option<Judgement>,
2192 ) -> Result<()> {
2193 validate_id(id)?;
2194 let mut memory = self.current(id);
2195 memory.handoff = Some(Handoff {
2196 text: text.to_string(),
2197 version: crate::compact::VERSION.to_string(),
2198 covered_turns: covered.turns,
2199 covered_messages: covered.messages,
2200 covered_from: span.0,
2201 covered_to: span.1,
2202 generated_at_ms: now_ms(),
2203 judgement,
2204 });
2205 self.save_memory(id, &memory)
2206 }
2207
2208 fn current(&self, id: &str) -> Memory {
2213 let mut memory = self.readable_memory(id).unwrap_or(Memory {
2214 version: MEMORY_VERSION,
2215 handoff: None,
2216 });
2217 memory.version = MEMORY_VERSION;
2220 memory
2221 }
2222
2223 pub fn save_memory(&self, id: &str, memory: &Memory) -> Result<()> {
2229 validate_id(id)?;
2230 memory.validate().map_err(Error::Session)?;
2231 if !self.exists(id) {
2232 return Err(Error::Session(format!("no such session {id:?}")));
2233 }
2234 let body = serde_json::to_string(memory).map_err(|e| Error::Session(e.to_string()))?;
2235 if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
2240 return Err(Error::Session(format!(
2241 "{id}: memory would be {} bytes, over the {MAX_MEMORY_FILE_BYTES}-byte record \
2242 limit; store less, or raise `MAX_MEMORY_FILE_BYTES` in both the writer and the \
2243 reader",
2244 body.len()
2245 )));
2246 }
2247 self.with_db(|db| {
2248 db.conn.execute(
2249 "INSERT INTO memory (session_id, body) VALUES (?1, ?2)
2250 ON CONFLICT(session_id) DO UPDATE SET body = ?2",
2251 params![id, body],
2252 )?;
2253 Ok(())
2254 })
2255 }
2256
2257 pub fn delete(&self, id: &str) -> Result<()> {
2259 validate_id(id)?;
2260 self.with_db(|db| {
2261 let tx = db.conn.unchecked_transaction()?;
2267 let n = tx.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
2268 if n == 0 {
2269 return Err(Error::Session(format!("no such session {id:?}")));
2272 }
2273 if db.fts {
2274 tx.execute(
2275 "DELETE FROM messages_fts WHERE session_id = ?1",
2276 params![id],
2277 )?;
2278 }
2279 tx.commit()?;
2280 Ok(())
2281 })?;
2282 for path in [
2289 self.lock_path(id)?,
2290 self.dir.join(format!("{id}.jsonl")),
2291 self.dir.join(format!("{id}.meta.json")),
2292 self.dir.join(format!("{id}.memory.json")),
2293 ] {
2294 match std::fs::remove_file(&path) {
2295 Ok(()) => {}
2296 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2297 Err(e) => return Err(Error::io(&path, e)),
2298 }
2299 }
2300 Ok(())
2301 }
2302
2303 pub fn prune_candidates(
2323 &self,
2324 keep_days: u64,
2325 keep_count: usize,
2326 now_ms: u64,
2327 include_archived: bool,
2328 ) -> Result<PrunePlan> {
2329 if keep_days == 0 && keep_count == 0 {
2330 return Ok(PrunePlan::default());
2331 }
2332 let mut sessions = self.session_ages()?;
2333 sessions.sort_by(|a, b| b.cmp(a));
2334 let cutoff = now_ms.saturating_sub(keep_days.saturating_mul(86_400_000));
2335 let mut plan = PrunePlan::default();
2336 for (i, (last, id, pinned, archived)) in sessions.into_iter().enumerate() {
2337 let over = (keep_count > 0 && i >= keep_count) || (keep_days > 0 && last < cutoff);
2338 if !over {
2339 continue;
2340 }
2341 if pinned {
2342 plan.pinned_kept += 1;
2343 } else if archived && !include_archived {
2344 plan.archived_kept += 1;
2345 } else {
2346 plan.candidates.push(id);
2347 }
2348 }
2349 Ok(plan)
2350 }
2351
2352 fn session_ages(&self) -> Result<Vec<(u64, String, bool, bool)>> {
2354 self.with_db(|db| {
2355 let mut stmt = db.conn.prepare(
2356 "SELECT updated_ms, id, pinned, archived FROM sessions ORDER BY updated_ms",
2357 )?;
2358 let rows = stmt.query_map([], |r| {
2359 let ms: i64 = r.get(0)?;
2360 let id: String = r.get(1)?;
2361 let pinned: i64 = r.get(2)?;
2362 let archived: i64 = r.get(3)?;
2363 Ok((ms.max(0) as u64, id, pinned != 0, archived != 0))
2364 })?;
2365 Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
2366 })
2367 }
2368
2369 pub fn auto_prune(
2379 &self,
2380 keep_days: u64,
2381 keep_count: usize,
2382 now_ms: u64,
2383 protect: Option<&str>,
2384 ) -> Result<AutoPrune> {
2385 if keep_days == 0 && keep_count == 0 {
2386 return Ok(AutoPrune::NoLimits);
2387 }
2388 let plan = self.prune_candidates(keep_days, keep_count, now_ms, false)?;
2389 let doomed: Vec<String> = plan
2390 .candidates
2391 .into_iter()
2392 .filter(|id| Some(id.as_str()) != protect)
2393 .collect();
2394 if doomed.is_empty() {
2395 return Ok(AutoPrune::Nothing);
2396 }
2397 if doomed.len() > PRUNE_CONFIRM_ABOVE {
2398 return Ok(AutoPrune::Skipped {
2399 would_remove: doomed.len(),
2400 });
2401 }
2402 let mut removed = 0;
2403 let mut failed = 0;
2404 for id in &doomed {
2405 match self.delete(id) {
2406 Ok(()) => removed += 1,
2407 Err(_) => failed += 1,
2408 }
2409 }
2410 Ok(AutoPrune::Pruned {
2411 removed,
2412 failed,
2413 pinned_kept: plan.pinned_kept,
2414 })
2415 }
2416
2417 pub fn export(&self, id: &str, format: ExportFormat) -> Result<String> {
2420 let records = self.load_records(id)?;
2421 let title = self.title(id).ok().flatten();
2422 match format {
2423 ExportFormat::Json => export_json(id, title, &records),
2424 ExportFormat::Markdown => Ok(export_markdown(id, title.as_deref(), &records)),
2425 }
2426 }
2427
2428 pub fn list(&self) -> Result<Vec<SessionInfo>> {
2438 self.list_rows(false, false)
2439 }
2440
2441 pub fn list_with_archived(&self) -> Result<Vec<SessionInfo>> {
2448 self.list_rows(true, false)
2449 }
2450
2451 pub fn list_bots(&self) -> Result<Vec<BotSessions>> {
2457 let mut out: Vec<BotSessions> = Vec::new();
2458 for info in self.list_rows(true, true)? {
2459 let Some(name) = info.bot() else { continue };
2460 match out.iter_mut().find(|b| b.name == name) {
2461 Some(bot) => {
2463 bot.sessions += 1;
2464 if !info.archived {
2465 bot.archived = false;
2466 }
2467 }
2468 None => out.push(BotSessions {
2469 name: name.to_string(),
2470 sessions: 1,
2471 messages: info.messages,
2472 last_session: info.id.clone(),
2473 last_activity_ms: info.updated_ms,
2474 archived: info.archived,
2475 }),
2476 }
2477 }
2478 Ok(out)
2479 }
2480
2481 fn list_rows(&self, include_archived: bool, include_bots: bool) -> Result<Vec<SessionInfo>> {
2488 self.with_db(|db| {
2489 let mut stmt = db.conn.prepare(
2495 "SELECT id, title, preview, messages, updated_ms, origin, pinned, archived, last_cost
2496 FROM sessions
2497 WHERE (archived = 0 OR ?1) AND (?2 OR origin NOT LIKE 'bot:%')
2498 ORDER BY pinned DESC, updated_ms DESC, rowid DESC",
2499 )?;
2500 let rows = stmt.query_map(
2501 params![i64::from(include_archived), i64::from(include_bots)],
2502 |r| {
2503 let updated: i64 = r.get(4)?;
2504 let messages: i64 = r.get(3)?;
2505 let pinned: i64 = r.get(6)?;
2506 let archived: i64 = r.get(7)?;
2507 let cost: Option<String> = r.get(8)?;
2508 Ok(SessionInfo {
2509 id: r.get(0)?,
2510 title: r.get(1)?,
2511 preview: r.get::<_, Option<String>>(2)?.unwrap_or_default(),
2512 messages: messages.max(0) as usize,
2513 updated_ms: updated.max(0) as u64,
2514 origin: r.get(5)?,
2515 pinned: pinned != 0,
2516 archived: archived != 0,
2517 cost: cost.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()),
2520 })
2521 })?;
2522 Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
2523 })
2524 }
2525
2526 pub fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>> {
2535 self.search_with(query, limit, false)
2536 }
2537
2538 pub fn search_with(
2546 &self,
2547 query: &str,
2548 limit: usize,
2549 include_children: bool,
2550 ) -> Result<Vec<SearchHit>> {
2551 let q = query.trim();
2552 if q.is_empty() {
2553 return Ok(Vec::new());
2554 }
2555 let limit = limit.clamp(1, 1000) as i64;
2556 self.with_db(|db| Self::search_in(db, q, limit, db.fts, include_children))
2557 }
2558
2559 fn search_in(
2566 db: &Db,
2567 q: &str,
2568 limit: i64,
2569 use_fts: bool,
2570 include_children: bool,
2571 ) -> Result<Vec<SearchHit>> {
2572 let children = i64::from(include_children);
2573 let mut out = Vec::new();
2574 let mut named = db.conn.prepare(
2580 "SELECT id, title, updated_ms FROM sessions
2581 WHERE title LIKE '%' || ?1 || '%' ESCAPE '\\'
2582 AND (?3 = 1 OR (origin NOT LIKE 'bot:%' AND origin NOT LIKE 'flare:%'))
2583 ORDER BY pinned DESC, archived ASC, updated_ms DESC LIMIT ?2",
2584 )?;
2585 let rows = named.query_map(params![like_literal(q), limit, children], |r| {
2586 Ok((
2587 r.get::<_, String>(0)?,
2588 r.get::<_, String>(1)?,
2589 r.get::<_, i64>(2)?,
2590 ))
2591 })?;
2592 for row in rows {
2593 let (session_id, title, updated_ms) = row?;
2594 out.push(SearchHit {
2595 session_id,
2596 seq: 0,
2597 at_ms: updated_ms.max(0) as u64,
2598 role: "title".to_string(),
2599 snippet: title,
2600 });
2601 }
2602
2603 let mut budget = limit.saturating_mul(4).max(limit + 8);
2608 loop {
2609 let (found, read) =
2610 Self::message_hits(db, q, limit, budget, use_fts, include_children)?;
2611 let room_to_widen = read >= budget && budget < OWN_TAIL_BUDGET_CAP;
2612 if !found.is_empty() || !room_to_widen {
2613 out.extend(found);
2614 break;
2615 }
2616 budget = (budget * 4).min(OWN_TAIL_BUDGET_CAP);
2617 }
2618 Ok(out)
2619 }
2620
2621 fn message_hits(
2629 db: &Db,
2630 q: &str,
2631 limit: i64,
2632 budget: i64,
2633 use_fts: bool,
2634 include_children: bool,
2635 ) -> Result<(Vec<SearchHit>, i64)> {
2636 let children = i64::from(include_children);
2637 let mut found = Vec::new();
2638 let mut read = 0i64;
2639 if use_fts {
2640 let terms: Vec<String> = q
2643 .split_whitespace()
2644 .map(|t| format!("\"{}\"", t.replace('"', "\"\"")))
2645 .collect();
2646 let mut stmt = db.conn.prepare(
2647 "SELECT f.session_id, f.seq, f.content
2652 FROM messages_fts f
2653 JOIN messages m ON m.session_id = f.session_id AND m.seq = f.seq
2654 JOIN sessions s ON s.id = f.session_id
2655 WHERE f.messages_fts MATCH ?1
2656 AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
2657 ORDER BY m.at_ms DESC, m.seq DESC
2658 LIMIT ?2",
2659 )?;
2660 let rows = stmt.query_map(params![terms.join(" "), budget, children], |r| {
2661 Ok((
2662 r.get::<_, String>(0)?,
2663 r.get::<_, i64>(1)?,
2664 r.get::<_, String>(2)?,
2665 ))
2666 })?;
2667 for row in rows {
2668 let (session_id, seq, content) = row?;
2669 read += 1;
2670 if is_own_tail(&db.conn, &session_id, seq)? {
2671 continue;
2672 }
2673 if let Some(found_hit) = hit(&db.conn, session_id, seq, &content)? {
2674 found.push(found_hit);
2675 if found.len() as i64 >= limit {
2676 break;
2677 }
2678 }
2679 }
2680 } else {
2681 let mut stmt = db.conn.prepare(
2684 "SELECT m.session_id, m.seq, m.body FROM messages m
2685 JOIN sessions s ON s.id = m.session_id
2686 WHERE m.body LIKE '%' || ?1 || '%' ESCAPE '\\'
2687 AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
2688 ORDER BY m.at_ms DESC, m.seq DESC LIMIT ?2",
2689 )?;
2690 let rows = stmt.query_map(params![like_literal(q), budget, children], |r| {
2691 Ok((
2692 r.get::<_, String>(0)?,
2693 r.get::<_, i64>(1)?,
2694 r.get::<_, String>(2)?,
2695 ))
2696 })?;
2697 for row in rows {
2698 let (session_id, seq, body) = row?;
2699 read += 1;
2700 let message: Message = serde_json::from_str(&body)
2701 .map_err(|e| Error::Session(format!("{session_id}:{seq}: {e}")))?;
2702 if is_own_tail(&db.conn, &session_id, seq)? {
2703 continue;
2704 }
2705 if let Some(found_hit) = hit(&db.conn, session_id, seq, &searchable(&message))? {
2706 found.push(found_hit);
2707 if found.len() as i64 >= limit {
2708 break;
2709 }
2710 }
2711 }
2712 }
2713 Ok((found, read))
2714 }
2715
2716 pub fn has_fts(&self) -> bool {
2718 self.with_db(|db| Ok(db.fts)).unwrap_or(false)
2719 }
2720}
2721
2722#[derive(Debug, Clone, PartialEq, Eq)]
2724pub struct SearchHit {
2725 pub session_id: String,
2726 pub seq: usize,
2728 pub at_ms: u64,
2729 pub role: String,
2730 pub snippet: String,
2732}
2733
2734fn hit(
2741 conn: &Connection,
2742 session_id: String,
2743 seq: i64,
2744 content: &str,
2745) -> Result<Option<SearchHit>> {
2746 let found: Option<(i64, String)> = conn
2747 .query_row(
2748 "SELECT at_ms, role FROM messages WHERE session_id = ?1 AND seq = ?2",
2749 params![session_id, seq],
2750 |r| Ok((r.get(0)?, r.get(1)?)),
2751 )
2752 .map(Some)
2753 .or_else(|e| match e {
2754 rusqlite::Error::QueryReturnedNoRows => Ok(None),
2755 other => Err(other),
2756 })?;
2757 let Some((at_ms, role)) = found else {
2758 return Ok(None);
2759 };
2760 Ok(Some(SearchHit {
2761 session_id,
2762 seq: seq.max(0) as usize,
2763 at_ms: at_ms.max(0) as u64,
2764 role,
2765 snippet: snippet(content, 160),
2766 }))
2767}
2768
2769const OWN_TAIL_TOOL: &str = "session_search";
2776
2777const OWN_TAIL_LOOKBACK: i64 = 20;
2780
2781const OWN_TAIL_BUDGET_CAP: i64 = 512;
2784
2785fn is_own_tail(conn: &Connection, session_id: &str, seq: i64) -> Result<bool> {
2791 let body: Option<String> = conn
2792 .query_row(
2793 "SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
2794 params![session_id, seq],
2795 |r| r.get(0),
2796 )
2797 .map(Some)
2798 .or_else(|e| match e {
2799 rusqlite::Error::QueryReturnedNoRows => Ok(None),
2800 other => Err(other),
2801 })?;
2802 let Some(body) = body else {
2803 return Ok(false);
2804 };
2805 let Ok(message) = serde_json::from_str::<Message>(&body) else {
2806 return Ok(false);
2807 };
2808 if message
2809 .tool_calls
2810 .iter()
2811 .any(|call| call.function.name == OWN_TAIL_TOOL)
2812 {
2813 return Ok(true);
2814 }
2815 let Some(answer_to) = message.tool_call_id.as_deref() else {
2816 return Ok(false);
2817 };
2818 let mut stmt = conn.prepare(
2819 "SELECT body FROM messages
2820 WHERE session_id = ?1 AND seq < ?2 AND role = 'assistant'
2821 ORDER BY seq DESC LIMIT ?3",
2822 )?;
2823 let rows = stmt.query_map(params![session_id, seq, OWN_TAIL_LOOKBACK], |r| {
2824 r.get::<_, String>(0)
2825 })?;
2826 for row in rows {
2827 let Ok(called) = serde_json::from_str::<Message>(&row?) else {
2828 continue;
2829 };
2830 if called
2831 .tool_calls
2832 .iter()
2833 .any(|call| call.id == answer_to && call.function.name == OWN_TAIL_TOOL)
2834 {
2835 return Ok(true);
2836 }
2837 }
2838 Ok(false)
2839}
2840
2841fn like_literal(q: &str) -> String {
2844 let mut out = String::with_capacity(q.len());
2845 for c in q.chars() {
2846 if matches!(c, '\\' | '%' | '_') {
2847 out.push('\\');
2848 }
2849 out.push(c);
2850 }
2851 out
2852}
2853
2854fn searchable(message: &Message) -> String {
2857 let mut out = message.text_with_pictures();
2860 for call in &message.tool_calls {
2861 if !out.is_empty() {
2862 out.push('\n');
2863 }
2864 out.push_str(&call.function.name);
2865 out.push(' ');
2866 out.push_str(&call.function.arguments);
2867 }
2868 out
2869}
2870
2871fn run_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<FlareRunRow> {
2874 let started: i64 = r.get(6)?;
2875 Ok(FlareRunRow {
2876 id: r.get(0)?,
2877 task: r.get(1)?,
2878 state: r.get(2)?,
2879 routes: r
2880 .get::<_, String>(3)?
2881 .split(',')
2882 .filter(|s| !s.is_empty())
2883 .map(str::to_string)
2884 .collect(),
2885 jobs: r.get::<_, i64>(4)?.max(0) as usize,
2886 parent: r.get(5)?,
2887 started_ms: started.max(0) as u64,
2888 finished_ms: r.get::<_, Option<i64>>(7)?.map(|v| v.max(0) as u64),
2889 prompt_tokens: r.get::<_, Option<i64>>(8)?.map(|v| v as u64),
2890 completion_tokens: r.get::<_, Option<i64>>(9)?.map(|v| v as u64),
2891 iterations: r.get::<_, Option<i64>>(10)?.unwrap_or(0).max(0) as usize,
2892 })
2893}
2894
2895fn snippet(text: &str, max: usize) -> String {
2896 let one: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
2897 if one.chars().count() <= max {
2898 return one;
2899 }
2900 one.chars().take(max.saturating_sub(1)).collect::<String>() + "…"
2901}
2902
2903fn role_name(role: Role) -> &'static str {
2904 match role {
2905 Role::System => "system",
2906 Role::User => "user",
2907 Role::Assistant => "assistant",
2908 Role::Tool => "tool",
2909 }
2910}
2911
2912pub(crate) struct Db {
2917 pub(crate) conn: Connection,
2918 fts: bool,
2921}
2922
2923impl Db {
2924 fn open(dir: &Path) -> Result<Self> {
2925 std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
2926 #[cfg(unix)]
2932 {
2933 use std::os::unix::fs::PermissionsExt;
2934 let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
2935 }
2936 let path = dir.join(DB_FILE);
2937 let mut conn = Connection::open(&path).map_err(db_err(&path))?;
2938 let _: String = conn
2940 .query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
2941 .map_err(db_err(&path))?;
2942 conn.execute_batch(
2943 "PRAGMA foreign_keys = ON;
2944 PRAGMA synchronous = NORMAL;
2945 PRAGMA busy_timeout = 5000;",
2946 )
2947 .map_err(db_err(&path))?;
2948 conn.execute_batch(SCHEMA).map_err(db_err(&path))?;
2949 #[cfg(unix)]
2953 {
2954 use std::os::unix::fs::PermissionsExt;
2955 for f in [
2956 path.clone(),
2957 path.with_extension("db-wal"),
2958 path.with_extension("db-shm"),
2959 ] {
2960 if f.exists() {
2961 let _ = std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o600));
2962 }
2963 }
2964 }
2965 {
2970 let tx = conn
2977 .transaction_with_behavior(TransactionBehavior::Immediate)
2978 .map_err(db_err(&path))?;
2979 if !has_column(&tx, "sessions", "pinned").map_err(db_err(&path))? {
2980 tx.execute_batch(
2981 "ALTER TABLE sessions ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0",
2982 )
2983 .map_err(db_err(&path))?;
2984 }
2985 if !has_column(&tx, "sessions", "archived").map_err(db_err(&path))? {
2988 tx.execute_batch(
2989 "ALTER TABLE sessions ADD COLUMN archived INTEGER NOT NULL DEFAULT 0",
2990 )
2991 .map_err(db_err(&path))?;
2992 }
2993 if !has_column(&tx, "approvals", "by").map_err(db_err(&path))? {
2998 tx.execute_batch("ALTER TABLE approvals ADD COLUMN by TEXT")
2999 .map_err(db_err(&path))?;
3000 }
3001 if !has_column(&tx, "sessions", "last_cost").map_err(db_err(&path))? {
3002 tx.execute_batch("ALTER TABLE sessions ADD COLUMN last_cost TEXT")
3003 .map_err(db_err(&path))?;
3004 }
3005 let title_source_added =
3009 !has_column(&tx, "sessions", "title_source").map_err(db_err(&path))?;
3010 if title_source_added {
3011 tx.execute_batch(
3012 "ALTER TABLE sessions ADD COLUMN title_source TEXT;
3013 ALTER TABLE sessions ADD COLUMN title_note TEXT;",
3014 )
3015 .map_err(db_err(&path))?;
3016 } else if !has_column(&tx, "sessions", "title_note").map_err(db_err(&path))? {
3017 tx.execute_batch("ALTER TABLE sessions ADD COLUMN title_note TEXT")
3018 .map_err(db_err(&path))?;
3019 }
3020 if title_source_added {
3021 tx.execute_batch(
3025 "UPDATE sessions SET title_source = 'user' WHERE title IS NOT NULL",
3026 )
3027 .map_err(db_err(&path))?;
3028 }
3029
3030 tx.commit().map_err(db_err(&path))?;
3031 }
3032
3033 let fts = match conn.execute_batch(FTS_SCHEMA) {
3034 Ok(()) => true,
3035 Err(_) => false,
3037 };
3038
3039 let mut db = Self { conn, fts };
3040 let warnings = db.import_legacy(dir)?;
3041 for w in warnings {
3042 eprintln!("warning: {w}");
3043 }
3044 Ok(db)
3045 }
3046
3047 fn import_legacy(&mut self, dir: &Path) -> Result<Vec<String>> {
3053 let rd = match std::fs::read_dir(dir) {
3054 Ok(rd) => rd,
3055 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
3056 Err(e) => return Err(Error::io(dir, e)),
3057 };
3058 let mut files: Vec<PathBuf> = Vec::new();
3059 for entry in rd.flatten() {
3060 let path = entry.path();
3061 if path.extension().and_then(|e| e.to_str()) == Some("jsonl") {
3062 files.push(path);
3063 }
3064 }
3065 files.sort();
3066 let mut warnings = Vec::new();
3067 let tx = self.conn.transaction().map_err(db_err(dir))?;
3068 for path in files {
3069 let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
3070 continue;
3071 };
3072 if validate_id(id).is_err() {
3073 warnings.push(format!(
3074 "{}: ignoring, not a valid session id",
3075 path.display()
3076 ));
3077 continue;
3078 }
3079 let already: Option<i64> = tx
3080 .query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
3081 r.get(0)
3082 })
3083 .optional()
3084 .map_err(db_err(&path))?;
3085 if already.is_some() {
3086 continue;
3087 }
3088 match read_legacy(&path) {
3089 Ok(legacy) => {
3090 let first = legacy.records.first().map(|r| r.ts);
3091 let last = legacy.records.last().map(|r| r.ts);
3092 let mtime = std::fs::metadata(&path)
3093 .and_then(|m| m.modified())
3094 .ok()
3095 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
3096 .map_or(0, |d| d.as_millis() as u64);
3097 let created = first.unwrap_or(mtime) as i64;
3098 let updated = last.unwrap_or(mtime) as i64;
3099 let preview = legacy.preview();
3100 tx.execute(
3101 "INSERT INTO sessions
3102 (id, created_ms, updated_ms, title, preview, messages, origin)
3103 VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'jsonl')",
3104 params![
3105 id,
3106 created,
3107 updated,
3108 legacy.title,
3109 preview,
3110 legacy.records.len() as i64
3111 ],
3112 )
3113 .map_err(db_err(&path))?;
3114 for (i, rec) in legacy.records.iter().enumerate() {
3115 let body = serde_json::to_string(&rec.message)
3116 .map_err(|e| Error::Session(e.to_string()))?;
3117 tx.execute(
3118 "INSERT INTO messages (session_id, seq, at_ms, role, body)
3119 VALUES (?1, ?2, ?3, ?4, ?5)",
3120 params![
3121 id,
3122 i as i64,
3123 rec.ts as i64,
3124 role_name(rec.message.role),
3125 body
3126 ],
3127 )
3128 .map_err(db_err(&path))?;
3129 if self.fts {
3130 tx.execute(
3131 "INSERT INTO messages_fts (session_id, seq, content)
3132 VALUES (?1, ?2, ?3)",
3133 params![id, i as i64, searchable(&rec.message)],
3134 )
3135 .map_err(db_err(&path))?;
3136 }
3137 }
3138 if let Some(body) = legacy.memory {
3139 tx.execute(
3143 "INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, ?2)",
3144 params![id, body],
3145 )
3146 .map_err(db_err(&path))?;
3147 }
3148 if let Some(w) = legacy.warning {
3149 warnings.push(w);
3150 }
3151 }
3152 Err(e) => {
3153 warnings.push(format!("{}: not imported: {e}", path.display()));
3156 }
3157 }
3158 }
3159 tx.commit().map_err(db_err(dir))?;
3160 Ok(warnings)
3161 }
3162}
3163
3164const DB_FILE: &str = "sessions.db";
3166
3167pub fn db_path(dir: &Path) -> PathBuf {
3172 dir.join(DB_FILE)
3173}
3174
3175const SCHEMA: &str = "
3176CREATE TABLE IF NOT EXISTS sessions (
3177 id TEXT PRIMARY KEY,
3178 created_ms INTEGER NOT NULL,
3179 updated_ms INTEGER NOT NULL,
3180 title TEXT,
3181 preview TEXT,
3182 messages INTEGER NOT NULL DEFAULT 0,
3183 origin TEXT NOT NULL DEFAULT 'native',
3184 pinned INTEGER NOT NULL DEFAULT 0,
3185 archived INTEGER NOT NULL DEFAULT 0,
3186 title_source TEXT,
3187 title_note TEXT,
3188 last_cost TEXT
3189);
3190CREATE INDEX IF NOT EXISTS sessions_by_activity ON sessions(updated_ms DESC);
3191CREATE TABLE IF NOT EXISTS messages (
3192 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3193 seq INTEGER NOT NULL,
3194 at_ms INTEGER NOT NULL,
3195 role TEXT NOT NULL,
3196 body TEXT NOT NULL,
3197 PRIMARY KEY (session_id, seq)
3198);
3199CREATE TABLE IF NOT EXISTS memory (
3200 session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
3201 body TEXT NOT NULL
3202);
3203CREATE TABLE IF NOT EXISTS approvals (
3204 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3205 seq INTEGER NOT NULL,
3206 ord INTEGER NOT NULL,
3207 call_id TEXT NOT NULL,
3208 tool TEXT NOT NULL,
3209 summary TEXT NOT NULL,
3210 args TEXT NOT NULL,
3211 decision TEXT,
3212 decided_ms INTEGER,
3213 PRIMARY KEY (session_id, seq, ord)
3214);
3215CREATE INDEX IF NOT EXISTS approvals_by_call ON approvals(session_id, call_id);
3216-- `#340`: who answered a call, and a log that outlives the row.
3217--
3218-- `approvals` is deliberately transient — `clear_call` deletes the row once the answer is in the
3219-- transcript, because a row left behind would let a resume replay a call that already ran. That
3220-- makes it the wrong place to ask what the model waved through last week, so the decider goes
3221-- on the row (who answered *this* waiting call) and every ruling is also appended here, where
3222-- nothing ever deletes it.
3223CREATE TABLE IF NOT EXISTS approval_log (
3224 session_id TEXT NOT NULL,
3225 at_ms INTEGER NOT NULL,
3226 call_id TEXT NOT NULL,
3227 tool TEXT NOT NULL,
3228 summary TEXT NOT NULL,
3229 decision TEXT NOT NULL,
3230 by TEXT NOT NULL
3231);
3232CREATE INDEX IF NOT EXISTS approval_log_by_session ON approval_log(session_id, at_ms);
3233-- `#447`: how a tool call ended, kept beside the message rather than inside it. A stored `tool`
3234-- message is the model's wire shape and carries no verdict, so a replayed row used to read the
3235-- mark off the text and call a failed `read_file` a ✓. The call id is the key the dashboard
3236-- already joins on.
3237CREATE TABLE IF NOT EXISTS tool_outcomes (
3238 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3239 call_id TEXT NOT NULL,
3240 is_error INTEGER NOT NULL,
3241 PRIMARY KEY (session_id, call_id)
3242);
3243-- `#172`: one standing goal per session, and every judgement made about it. A new table rather
3244-- than a column, so an older `sessions.db` opens without a migration step and a session that has
3245-- never had a goal keeps no row at all. The foreign key is the whole of `deleting a session
3246-- deletes its goal`.
3247CREATE TABLE IF NOT EXISTS goals (
3248 session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
3249 text TEXT NOT NULL,
3250 gate TEXT,
3251 budget INTEGER NOT NULL,
3252 turns INTEGER NOT NULL DEFAULT 0,
3253 state TEXT NOT NULL,
3254 note TEXT,
3255 garbage INTEGER NOT NULL DEFAULT 0,
3256 created_ms INTEGER NOT NULL,
3257 updated_ms INTEGER NOT NULL
3258);
3259CREATE TABLE IF NOT EXISTS goal_turns (
3260 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3261 turn INTEGER NOT NULL,
3262 verdict TEXT NOT NULL,
3263 why TEXT,
3264 at_ms INTEGER NOT NULL,
3265 PRIMARY KEY (session_id, turn)
3266);
3267-- `#657`: the plan — the steps of a job, in priority order, and which one is being done. Two
3268-- tables for the reason `goals` is two: a status change is then one row updated rather than a blob
3269-- rewritten, and `position` is the order the model wrote, which means nothing inside a blob and
3270-- everything to a list. The foreign key is the whole of `deleting a session deletes its plan`.
3271CREATE TABLE IF NOT EXISTS plans (
3272 session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
3273 revision INTEGER NOT NULL,
3274 updated_ms INTEGER NOT NULL
3275);
3276CREATE TABLE IF NOT EXISTS plan_items (
3277 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3278 id TEXT NOT NULL,
3279 content TEXT NOT NULL,
3280 status TEXT NOT NULL,
3281 parent TEXT,
3282 position INTEGER NOT NULL,
3283 PRIMARY KEY (session_id, id)
3284);
3285-- `#171`: a flare run and its N children. A run that cannot be listed after a restart is a run
3286-- that cannot be cancelled, so the ledger is a table rather than a field on the agent that
3287-- started it — and it is two tables because the run's cost is a sum over children that may have
3288-- failed, and a failed child's cost still happened.
3289CREATE TABLE IF NOT EXISTS flare_runs (
3290 id TEXT PRIMARY KEY,
3291 task TEXT NOT NULL,
3292 state TEXT NOT NULL,
3293 routes TEXT NOT NULL,
3294 jobs INTEGER NOT NULL,
3295 parent TEXT,
3296 started_ms INTEGER NOT NULL,
3297 finished_ms INTEGER,
3298 prompt_tokens INTEGER,
3299 completion_tokens INTEGER,
3300 iterations INTEGER,
3301 cancel_requested INTEGER NOT NULL DEFAULT 0
3302);
3303CREATE INDEX IF NOT EXISTS flare_runs_by_start ON flare_runs(started_ms DESC);
3304CREATE TABLE IF NOT EXISTS flare_jobs (
3305 run_id TEXT NOT NULL REFERENCES flare_runs(id) ON DELETE CASCADE,
3306 n INTEGER NOT NULL,
3307 route TEXT NOT NULL,
3308 session_id TEXT,
3309 state TEXT NOT NULL,
3310 prompt_tokens INTEGER,
3311 completion_tokens INTEGER,
3312 iterations INTEGER,
3313 why TEXT,
3314 PRIMARY KEY (run_id, n)
3315);
3316";
3317
3318const FTS_SCHEMA: &str = "
3321CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
3322 session_id UNINDEXED,
3323 seq UNINDEXED,
3324 content
3325);
3326";
3327
3328fn db_err(path: &Path) -> impl Fn(rusqlite::Error) -> Error + '_ {
3329 move |e| Error::Session(format!("{}: {e}", path.display()))
3330}
3331
3332fn has_column(conn: &Connection, table: &str, column: &str) -> rusqlite::Result<bool> {
3335 let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
3336 let mut rows = stmt.query([])?;
3337 while let Some(row) = rows.next()? {
3338 let name: String = row.get(1)?;
3339 if name == column {
3340 return Ok(true);
3341 }
3342 }
3343 Ok(false)
3344}
3345
3346struct Legacy {
3348 records: Vec<Record>,
3349 title: Option<String>,
3350 memory: Option<String>,
3352 warning: Option<String>,
3353}
3354
3355impl Legacy {
3356 fn preview(&self) -> Option<String> {
3357 self.records
3358 .iter()
3359 .find(|r| r.message.role == Role::User)
3360 .and_then(|r| r.message.content.as_deref())
3361 .map(|t| {
3362 let one_line: String = t.split_whitespace().collect::<Vec<_>>().join(" ");
3363 one_line.chars().take(60).collect()
3364 })
3365 }
3366}
3367
3368fn read_legacy(path: &Path) -> Result<Legacy> {
3374 let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
3375 let text = String::from_utf8_lossy(&bytes);
3376 let terminated = text.ends_with('\n');
3377 let lines: Vec<&str> = text.lines().collect();
3378 let mut records = Vec::new();
3379 let mut warning = None;
3380 for (i, line) in lines.iter().enumerate() {
3381 if line.trim().is_empty() {
3382 continue;
3383 }
3384 match serde_json::from_str::<Record>(line) {
3385 Ok(rec) => records.push(rec),
3386 Err(_) if i + 1 == lines.len() && !terminated => {
3387 warning = Some(format!(
3388 "{}:{}: ignoring truncated trailing line ({} bytes)",
3389 path.display(),
3390 i + 1,
3391 line.len()
3392 ));
3393 }
3394 Err(e) => return Err(Error::Session(format!("line {}: {e}", i + 1))),
3395 }
3396 }
3397 let dir = path.parent().unwrap_or(Path::new("."));
3398 let id = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
3399 let title = std::fs::read_to_string(dir.join(format!("{id}.meta.json")))
3400 .ok()
3401 .and_then(|t| serde_json::from_str::<Meta>(&t).ok())
3402 .map(|m| m.title);
3403 let memory = std::fs::read_to_string(dir.join(format!("{id}.memory.json")))
3404 .ok()
3405 .filter(|t| t.len() as u64 <= MAX_MEMORY_FILE_BYTES);
3406 Ok(Legacy {
3407 records,
3408 title,
3409 memory,
3410 warning,
3411 })
3412}
3413
3414fn export_json(id: &str, title: Option<String>, records: &[Record]) -> Result<String> {
3415 let doc = serde_json::json!({
3416 "format": "eclipse-session/1",
3417 "id": id,
3418 "title": title,
3419 "messages": records,
3420 });
3421 let mut out = serde_json::to_string_pretty(&doc).map_err(|e| Error::Session(e.to_string()))?;
3422 out.push('\n');
3423 Ok(out)
3424}
3425
3426fn fenced(info: &str, text: &str) -> String {
3428 let (mut run, mut longest) = (0usize, 0usize);
3429 for c in text.chars() {
3430 run = if c == '`' { run + 1 } else { 0 };
3431 longest = longest.max(run);
3432 }
3433 let fence = "`".repeat((longest + 1).max(3));
3434 let nl = if text.ends_with('\n') { "" } else { "\n" };
3435 format!("{fence}{info}\n{text}{nl}{fence}\n")
3436}
3437
3438fn export_markdown(id: &str, title: Option<&str>, records: &[Record]) -> String {
3439 use std::collections::HashMap;
3440 use std::fmt::Write as _;
3441
3442 let mut out = String::new();
3443 let _ = writeln!(out, "# {}\n", title.unwrap_or(id).replace('\n', " "));
3444 let _ = writeln!(out, "- Session: `{id}`");
3445 let _ = writeln!(out, "- Messages: {}", records.len());
3446 if let Some(first) = records.first() {
3447 let _ = writeln!(out, "- Started: {} UTC", format_utc(first.ts));
3448 }
3449 out.push_str(
3450 "\n_The system prompt is not stored in sessions, so it is not part of this transcript._\n",
3451 );
3452
3453 let mut tool_names: HashMap<&str, &str> = HashMap::new();
3454 for r in records {
3455 for c in &r.message.tool_calls {
3456 tool_names.insert(&c.id, &c.function.name);
3457 }
3458 }
3459 let mut answered: std::collections::HashSet<&str> = std::collections::HashSet::new();
3460 for r in records {
3461 if let Some(id) = r.message.tool_call_id.as_deref() {
3462 answered.insert(id);
3463 }
3464 }
3465
3466 for (i, r) in records.iter().enumerate() {
3467 let m = &r.message;
3468 let who = match m.role {
3469 Role::System => "System".to_string(),
3470 Role::User => "User".to_string(),
3471 Role::Assistant => "Assistant".to_string(),
3472 Role::Tool => {
3473 let name = m
3474 .tool_call_id
3475 .as_deref()
3476 .and_then(|c| tool_names.get(c).copied())
3477 .unwrap_or("unknown tool");
3478 format!("Tool result: {name}")
3479 }
3480 };
3481 let _ = writeln!(out, "\n## {}. {who} ({} UTC)\n", i + 1, format_utc(r.ts));
3482 match m.role {
3483 Role::Tool => out.push_str(&fenced("", &m.text_with_pictures())),
3484 _ => {
3485 let text = m.text_with_pictures();
3486 if !text.is_empty() {
3487 out.push_str(&text);
3488 out.push('\n');
3489 }
3490 }
3491 }
3492 for c in &m.tool_calls {
3493 let args = &c.function.arguments;
3494 let _ = writeln!(
3495 out,
3496 "\n**Tool call** `{}` (id `{}`){}\n",
3497 c.function.name.replace('`', "'"),
3498 c.id.replace('`', "'"),
3499 if answered.contains(c.id.as_str()) {
3500 ""
3501 } else {
3502 " - no result recorded"
3503 }
3504 );
3505 match serde_json::from_str::<serde_json::Value>(args) {
3506 Ok(v) => out.push_str(&fenced(
3507 "json",
3508 &serde_json::to_string_pretty(&v).unwrap_or_else(|_| args.clone()),
3509 )),
3510 Err(_) => out.push_str(&fenced("", args)),
3511 }
3512 }
3513 }
3514 out
3515}
3516
3517pub fn format_utc(ms: u64) -> String {
3519 let secs = ms / 1000;
3520 let days = (secs / 86_400) as i64;
3521 let rem = secs % 86_400;
3522 let z = days + 719_468;
3524 let era = z.div_euclid(146_097);
3525 let doe = z.rem_euclid(146_097);
3526 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
3527 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
3528 let mp = (5 * doy + 2) / 153;
3529 let d = doy - (153 * mp + 2) / 5 + 1;
3530 let m = if mp < 10 { mp + 3 } else { mp - 9 };
3531 let y = yoe + era * 400 + i64::from(m <= 2);
3532 format!(
3533 "{y:04}-{m:02}-{d:02} {:02}:{:02}",
3534 rem / 3600,
3535 rem % 3600 / 60
3536 )
3537}
3538
3539#[cfg(test)]
3540mod tests {
3541 use super::*;
3542 use crate::message::{FunctionCall, ToolCall};
3543
3544 fn store(dir: &Path) -> SessionStore {
3545 SessionStore::new(dir.join("sessions"))
3546 }
3547
3548 fn call(id: &str, name: &str, args: &str) -> ToolCall {
3549 ToolCall {
3550 id: id.into(),
3551 kind: "function".into(),
3552 function: FunctionCall {
3553 name: name.into(),
3554 arguments: args.into(),
3555 },
3556 }
3557 }
3558
3559 fn transcript(store: &SessionStore, id: &str) {
3561 store.append(id, &Message::user("hello there")).unwrap();
3562 store
3563 .append(
3564 id,
3565 &Message::assistant_tool_calls(
3566 Some("let me look".into()),
3567 vec![call("c1", "read_file", r#"{"path":"a.txt"}"#)],
3568 ),
3569 )
3570 .unwrap();
3571 store
3572 .append(id, &Message::tool_result("c1", "file contents"))
3573 .unwrap();
3574 store.append(id, &Message::assistant("done")).unwrap();
3575 }
3576
3577 #[test]
3581 fn a_tool_outcome_is_recorded_beside_the_call_and_read_back() {
3582 let dir = tempfile::tempdir().unwrap();
3583 let store = SessionStore::new(dir.path().to_path_buf());
3584 let id = store.new_id();
3585 store.append(&id, &Message::user("read it")).unwrap();
3586 assert!(
3587 store.tool_outcomes(&id).unwrap().is_empty(),
3588 "nothing recorded is an empty map, not an error"
3589 );
3590
3591 store.set_tool_outcome(&id, "c1", true).unwrap();
3592 store.set_tool_outcome(&id, "c2", false).unwrap();
3593 store.set_tool_outcome(&id, "c1", true).unwrap();
3594
3595 let marks = store.tool_outcomes(&id).unwrap();
3596 assert_eq!(
3597 marks.len(),
3598 2,
3599 "the second write is the same write: {marks:?}"
3600 );
3601 assert_eq!(marks.get("c1"), Some(&true));
3602 assert_eq!(marks.get("c2"), Some(&false));
3603 }
3604
3605 fn seed(store: &SessionStore, id: &str, updated_ms: u64) {
3607 store
3608 .with_db(|db| {
3609 db.conn.execute(
3610 "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
3611 VALUES (?1, ?2, ?2, NULL, 'seeded', 1, 'native')",
3612 params![id, updated_ms as i64],
3613 )?;
3614 Ok(())
3615 })
3616 .unwrap();
3617 }
3618
3619 fn legacy_file(dir: &Path, id: &str, body: &str) -> PathBuf {
3620 std::fs::create_dir_all(dir).unwrap();
3621 let path = dir.join(format!("{id}.jsonl"));
3622 std::fs::write(&path, body).unwrap();
3623 path
3624 }
3625
3626 fn line(m: &Message, ts: u64) -> String {
3627 let rec = Record {
3628 ts,
3629 message: m.clone(),
3630 };
3631 format!("{}\n", serde_json::to_string(&rec).unwrap())
3632 }
3633
3634 #[test]
3635 fn append_and_load_round_trip() {
3636 let dir = tempfile::tempdir().unwrap();
3637 let store = store(dir.path());
3638 let id = store.new_id();
3639 assert!(!store.exists(&id), "a store knows only what was written");
3640 transcript(&store, &id);
3641 assert!(store.exists(&id));
3642
3643 let messages = store.load(&id).unwrap();
3644 assert_eq!(messages.len(), 4);
3645 assert_eq!(messages[0], Message::user("hello there"));
3646 assert_eq!(messages[1].tool_calls.len(), 1);
3647 assert_eq!(messages[1].tool_calls[0].function.name, "read_file");
3648 assert_eq!(messages[1].content.as_deref(), Some("let me look"));
3649 assert_eq!(messages[2].tool_call_id.as_deref(), Some("c1"));
3650 assert_eq!(messages[2].content.as_deref(), Some("file contents"));
3651 assert_eq!(messages[3], Message::assistant("done"));
3652 }
3653
3654 #[test]
3655 fn every_message_is_one_row_in_order() {
3656 let dir = tempfile::tempdir().unwrap();
3657 let store = store(dir.path());
3658 let id = store.new_id();
3659 transcript(&store, &id);
3660 let records = store.load_records(&id).unwrap();
3661 let seqs: Vec<usize> = store
3662 .with_db(|db| {
3663 let mut stmt = db
3664 .conn
3665 .prepare("SELECT seq FROM messages WHERE session_id = ?1 ORDER BY seq")?;
3666 let rows = stmt.query_map(params![id], |r| r.get::<_, i64>(0))?;
3667 Ok(rows
3668 .collect::<std::result::Result<Vec<_>, _>>()?
3669 .into_iter()
3670 .map(|s| s as usize)
3671 .collect())
3672 })
3673 .unwrap();
3674 assert_eq!(seqs, [0, 1, 2, 3], "sequence numbers are dense and ordered");
3675 assert_eq!(records.len(), 4);
3676 assert!(
3677 records.windows(2).all(|w| w[0].ts <= w[1].ts),
3678 "timestamps do not run backwards"
3679 );
3680 }
3681
3682 #[test]
3683 fn data_survives_a_new_store_handle() {
3684 let dir = tempfile::tempdir().unwrap();
3685 let id;
3686 {
3687 let first = store(dir.path());
3688 id = first.new_id();
3689 transcript(&first, &id);
3690 first.rename(&id, "kept title").unwrap();
3691 }
3692 let second = store(dir.path());
3693 assert_eq!(second.load(&id).unwrap().len(), 4);
3694 assert_eq!(second.title(&id).unwrap().as_deref(), Some("kept title"));
3695 }
3696
3697 #[test]
3698 fn list_orders_newest_first_with_preview() {
3699 let dir = tempfile::tempdir().unwrap();
3700 let store = store(dir.path());
3701 let a = store.new_id();
3702 store
3703 .append(&a, &Message::user("the older question"))
3704 .unwrap();
3705 std::thread::sleep(std::time::Duration::from_millis(5));
3706 let b = store.new_id();
3707 store
3708 .append(&b, &Message::user("the newer question"))
3709 .unwrap();
3710
3711 let list = store.list().unwrap();
3712 assert_eq!(list.len(), 2);
3713 assert_eq!(list[0].id, b, "newest first");
3714 assert_eq!(list[0].preview, "the newer question");
3715 assert_eq!(list[0].messages, 1);
3716 assert_eq!(list[1].id, a);
3717 assert_eq!(list[0].label(), "the newer question");
3718 }
3719
3720 #[test]
3721 fn the_preview_is_the_first_user_message_not_the_latest() {
3722 let dir = tempfile::tempdir().unwrap();
3723 let store = store(dir.path());
3724 let id = store.new_id();
3725 store.append(&id, &Message::user("first thing")).unwrap();
3726 store.append(&id, &Message::user("second thing")).unwrap();
3727 let info = store.list().unwrap().into_iter().next().unwrap();
3728 assert_eq!(info.preview, "first thing");
3729 assert_eq!(info.messages, 2);
3730 }
3731
3732 #[test]
3733 fn prune_candidates_by_age_and_count() {
3734 let dir = tempfile::tempdir().unwrap();
3735 let store = store(dir.path());
3736 let now = 1_700_000_000_000u64;
3737 let day = 86_400_000u64;
3738 seed(&store, "old", now - 10 * day);
3739 seed(&store, "mid", now - 2 * day);
3740 seed(&store, "new", now - day / 24);
3741
3742 assert_eq!(
3743 store.prune_candidates(3, 0, now, false).unwrap().candidates,
3744 ["old"],
3745 "older than three days"
3746 );
3747 assert_eq!(
3748 store.prune_candidates(0, 2, now, false).unwrap().candidates,
3749 ["old"],
3750 "all but the newest two"
3751 );
3752 let both = store.prune_candidates(3, 10, now, false).unwrap();
3753 assert_eq!(
3754 both.candidates,
3755 ["old"],
3756 "a session selected by either rule is pruned once"
3757 );
3758 assert!(store
3759 .prune_candidates(0, 0, now, false)
3760 .unwrap()
3761 .candidates
3762 .is_empty());
3763 }
3764
3765 #[test]
3766 fn a_pinned_session_sorts_first_and_is_never_a_prune_candidate() {
3767 let dir = tempfile::tempdir().unwrap();
3768 let store = store(dir.path());
3769 let now = 1_700_000_000_000u64;
3770 seed(&store, "oldest", now - 10 * 86_400_000);
3771 seed(&store, "newest", now - 86_400_000);
3772
3773 store.set_pinned("oldest", true).unwrap();
3774 let list = store.list().unwrap();
3775 assert_eq!(list[0].id, "oldest", "pinned first, whatever the age");
3776 assert!(list[0].pinned);
3777 assert!(!list[1].pinned);
3778
3779 let plan = store.prune_candidates(7, 0, now, false).unwrap();
3781 assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
3782 assert_eq!(plan.pinned_kept, 1);
3783
3784 let outcome = store.auto_prune(7, 0, now, None).unwrap();
3786 assert_eq!(outcome, AutoPrune::Nothing);
3787 assert!(store.exists("oldest"));
3788
3789 store.set_pinned("oldest", false).unwrap();
3790 assert_eq!(
3791 store.prune_candidates(7, 0, now, false).unwrap().candidates,
3792 ["oldest"]
3793 );
3794 assert!(!store.list().unwrap()[0].pinned, "unpinning is not sticky");
3795 }
3796
3797 #[test]
3801 fn an_archived_session_leaves_the_list_and_stays_in_the_search() {
3802 let dir = tempfile::tempdir().unwrap();
3803 let store = store(dir.path());
3804 let now = 1_700_000_000_000u64;
3805 seed(&store, "kept", now - 86_400_000);
3806 seed(&store, "filed", now - 10 * 86_400_000);
3807 store.rename("filed", "the nginx migration").unwrap();
3808 store
3809 .append("filed", &Message::user("the zfs pool was rebuilt"))
3810 .unwrap();
3811 store
3814 .with_db(|db| {
3815 db.conn.execute(
3816 "UPDATE sessions SET updated_ms = ?2 WHERE id = ?1",
3817 params!["filed", (now - 10 * 86_400_000) as i64],
3818 )?;
3819 Ok(())
3820 })
3821 .unwrap();
3822
3823 store.set_archived("filed", true).unwrap();
3824
3825 let listed = store.list().unwrap();
3827 assert_eq!(listed.len(), 1);
3828 assert_eq!(listed[0].id, "kept");
3829 let all = store.list_with_archived().unwrap();
3830 assert_eq!(all.len(), 2);
3831 assert!(all.iter().find(|s| s.id == "filed").unwrap().archived);
3832 assert!(!all.iter().find(|s| s.id == "kept").unwrap().archived);
3833
3834 assert!(
3837 store
3838 .search("nginx", 20)
3839 .unwrap()
3840 .iter()
3841 .any(|h| h.session_id == "filed"),
3842 "a name hit survives archiving"
3843 );
3844 assert!(
3845 store
3846 .search("zfs", 20)
3847 .unwrap()
3848 .iter()
3849 .any(|h| h.session_id == "filed"),
3850 "a message hit survives archiving"
3851 );
3852 assert_eq!(
3853 store.load("filed").unwrap().len(),
3854 1,
3855 "the transcript is there"
3856 );
3857
3858 let plan = store.prune_candidates(7, 0, now, false).unwrap();
3860 assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
3861 assert_eq!(plan.archived_kept, 1);
3862 assert_eq!(
3863 plan.pinned_kept, 0,
3864 "counted apart, so the sentence can differ"
3865 );
3866 assert_eq!(
3867 store.prune_candidates(7, 0, now, true).unwrap().candidates,
3868 ["filed"]
3869 );
3870 assert_eq!(
3872 store.auto_prune(7, 0, now, None).unwrap(),
3873 AutoPrune::Nothing
3874 );
3875
3876 store.set_archived("filed", false).unwrap();
3878 assert_eq!(store.list().unwrap().len(), 2);
3879 assert!(matches!(
3880 store.set_archived("nope", true),
3881 Err(Error::Session(_))
3882 ));
3883 }
3884
3885 #[test]
3888 fn a_database_from_before_archiving_gains_the_column_in_place() {
3889 let dir = tempfile::tempdir().unwrap();
3890 {
3891 let dir = dir.path().join("sessions");
3892 std::fs::create_dir_all(&dir).unwrap();
3893 let conn = Connection::open(dir.join(DB_FILE)).unwrap();
3894 conn.execute_batch(
3895 "CREATE TABLE sessions (
3896 id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
3897 title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
3898 origin TEXT NOT NULL DEFAULT 'native');
3899 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
3900 VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
3901 )
3902 .unwrap();
3903 }
3904 let store = store(dir.path());
3905 let list = store.list().unwrap();
3906 assert_eq!(
3907 list.len(),
3908 1,
3909 "the old row is in the list, not archived by omission"
3910 );
3911 assert!(!list[0].archived);
3912 store.set_archived("s1", true).unwrap();
3913 assert!(store.list().unwrap().is_empty());
3914 assert!(store.list_with_archived().unwrap()[0].archived);
3915 }
3916
3917 #[test]
3918 fn a_database_from_before_pinning_gains_the_column_in_place() {
3919 let dir = tempfile::tempdir().unwrap();
3920 let id;
3921 {
3922 let dir = dir.path().join("sessions");
3925 std::fs::create_dir_all(&dir).unwrap();
3926 let conn = Connection::open(dir.join(DB_FILE)).unwrap();
3927 conn.execute_batch(
3928 "CREATE TABLE sessions (
3929 id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
3930 title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
3931 origin TEXT NOT NULL DEFAULT 'native');
3932 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
3933 VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
3934 )
3935 .unwrap();
3936 id = "s1".to_string();
3937 }
3938 let store = store(dir.path());
3939 let list = store.list().unwrap();
3940 assert_eq!(list.len(), 1, "the old row still reads");
3941 assert_eq!(list[0].id, id);
3942 assert!(!list[0].pinned, "an old row is not pinned");
3943 store.set_pinned(&id, true).unwrap();
3944 assert!(store.list().unwrap()[0].pinned);
3945 assert_eq!(
3946 store
3947 .prune_candidates(0, 1, 1_700_000_000_000, false)
3948 .unwrap(),
3949 PrunePlan::default(),
3950 "one session, newest one kept"
3951 );
3952 }
3953
3954 #[test]
3955 fn a_database_from_before_the_cost_record_gains_the_column_in_place() {
3956 let dir = tempfile::tempdir().unwrap();
3957 {
3958 let dir = dir.path().join("sessions");
3959 std::fs::create_dir_all(&dir).unwrap();
3960 let conn = Connection::open(dir.join(DB_FILE)).unwrap();
3961 conn.execute_batch(
3962 "CREATE TABLE sessions (
3963 id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
3964 title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
3965 origin TEXT NOT NULL DEFAULT 'native');
3966 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
3967 VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
3968 )
3969 .unwrap();
3970 }
3971 let store = store(dir.path());
3972 assert!(
3973 store.last_cost("s1").unwrap().is_none(),
3974 "an old row has no turn behind it, and no record is not a zero"
3975 );
3976 let prompt = 1_234_u64;
3977 let cost = TurnCost {
3978 at_ms: 7,
3979 ctx: "ctx 1.2K/8K ░░░░░░░░░░│░ 15%".to_string(),
3980 prompt_tokens: Some(prompt),
3981 ..TurnCost::default()
3982 };
3983 store.set_last_cost("s1", &cost).unwrap();
3984 assert_eq!(store.last_cost("s1").unwrap(), Some(cost));
3985 }
3986
3987 #[test]
3992 fn a_turn_writes_its_cost_and_the_listing_reads_it_back() {
3993 let dir = tempfile::tempdir().unwrap();
3994 let store = store(dir.path());
3995 let id = store.new_id();
3996 transcript(&store, &id);
3997 assert!(
3998 store.list().unwrap()[0].cost.is_none(),
3999 "a session with no finished turn has nothing to say about one"
4000 );
4001 let prompt = 30_000_u64;
4002 let cached = 28_000_u64;
4003 let cost = TurnCost {
4004 at_ms: 1_700_000_000_000,
4005 ctx: "ctx 30K/262K ██░░░░░░░░│░ 11%".to_string(),
4006 prompt_tokens: Some(prompt),
4007 completion_tokens: Some(400),
4008 cached_tokens: Some(cached),
4009 ttft_ms: Some(800),
4010 latency_ms: Some(13_000),
4011 tokens_per_sec: Some(63.0),
4012 window_tokens: Some(262_144),
4013 };
4014 store.set_last_cost(&id, &cost).unwrap();
4015 let listed = &store.list().unwrap()[0];
4016 assert_eq!(listed.cost.as_ref(), Some(&cost));
4017 let ctx = listed
4018 .cost
4019 .as_ref()
4020 .map(|c| c.ctx.as_str())
4021 .unwrap_or_default();
4022 assert!(
4023 ctx.contains("262K"),
4024 "the denominator the listing carries is the one that turn ran against: {ctx:?}"
4025 );
4026 }
4027
4028 #[test]
4031 fn recording_a_cost_does_not_move_the_session_up_the_list() {
4032 let dir = tempfile::tempdir().unwrap();
4033 let store = store(dir.path());
4034 let older = store.new_id();
4035 let newer = store.new_id();
4036 transcript(&store, &older);
4037 transcript(&store, &newer);
4038 let before: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
4039 let target = before.last().expect("two sessions").clone();
4040 store
4041 .set_last_cost(
4042 &target,
4043 &TurnCost {
4044 at_ms: 1,
4045 ctx: "ctx --".to_string(),
4046 ..TurnCost::default()
4047 },
4048 )
4049 .unwrap();
4050 let after: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
4051 assert_eq!(
4052 before, after,
4053 "the order is the store's, and a cost is not a move"
4054 );
4055 }
4056
4057 #[test]
4060 fn a_persons_name_outranks_the_machines_and_outlives_a_later_attempt() {
4061 let dir = tempfile::tempdir().unwrap();
4062 let store = store(dir.path());
4063 let id = store.new_id();
4064 transcript(&store, &id);
4065
4066 assert!(
4067 store.title_if_unnamed(&id, "the opening message").unwrap(),
4068 "nothing names it yet, so the derived name lands"
4069 );
4070 assert!(
4071 !store
4072 .title_if_unnamed(&id, "a second derived name")
4073 .unwrap(),
4074 "stage one never relabels a session it has already named"
4075 );
4076 assert_eq!(
4077 store.title(&id).unwrap().as_deref(),
4078 Some("the opening message")
4079 );
4080
4081 assert!(
4082 store
4083 .set_title(&id, "the model's name", TitleSource::Llm)
4084 .unwrap(),
4085 "a model name replaces a derived one"
4086 );
4087 assert!(
4088 !store
4089 .set_title(&id, "a second model name", TitleSource::Llm)
4090 .unwrap(),
4091 "one naming call means one name: it is not renamed by trying again"
4092 );
4093
4094 store.rename(&id, "what I called it").unwrap();
4095 for source in [TitleSource::Llm, TitleSource::Derived] {
4096 assert!(
4097 !store.set_title(&id, "the machine again", source).unwrap(),
4098 "a person's name is final to {source:?}"
4099 );
4100 }
4101 assert_eq!(
4102 store.title(&id).unwrap().as_deref(),
4103 Some("what I called it")
4104 );
4105 assert_eq!(
4106 store.list().unwrap()[0].label(),
4107 "what I called it",
4108 "and the listing shows it"
4109 );
4110 }
4111
4112 #[test]
4116 fn the_naming_attempt_is_claimed_once_per_session() {
4117 let dir = tempfile::tempdir().unwrap();
4118 let store = store(dir.path());
4119 let id = store.new_id();
4120 transcript(&store, &id);
4121 store.title_if_unnamed(&id, "a derived name").unwrap();
4122
4123 assert!(
4124 store.claim_title_upgrade(&id).unwrap(),
4125 "the first caller owns it"
4126 );
4127 assert!(
4128 !store.claim_title_upgrade(&id).unwrap(),
4129 "and nobody else does"
4130 );
4131 store
4132 .title_attempt_failed(&id, "the reply was not a JSON object")
4133 .unwrap();
4134 assert!(
4135 !store.claim_title_upgrade(&id).unwrap(),
4136 "a refused answer is not retried on the next run"
4137 );
4138 assert_eq!(
4139 store.title(&id).unwrap().as_deref(),
4140 Some("a derived name"),
4141 "and the name is still there: a failure never leaves it empty"
4142 );
4143
4144 let other = store.new_id();
4146 transcript(&store, &other);
4147 store.title_if_unnamed(&other, "another name").unwrap();
4148 assert!(store.claim_title_upgrade(&other).unwrap());
4149 store.release_title_claim(&other).unwrap();
4150 assert!(
4151 store.claim_title_upgrade(&other).unwrap(),
4152 "released, not failed"
4153 );
4154 }
4155
4156 #[test]
4159 fn a_delegated_child_session_is_never_named_by_a_call() {
4160 let dir = tempfile::tempdir().unwrap();
4161 let store = store(dir.path());
4162 let parent = store.new_id();
4163 let child = store.new_id();
4164 store.append(&parent, &Message::user("big job")).unwrap();
4165 store.begin_subagent(&child, &parent, "fast").unwrap();
4166 store
4167 .append(&child, &Message::user("summarise this"))
4168 .unwrap();
4169 store.title_if_unnamed(&child, "summarise this").unwrap();
4170 assert!(
4171 !store.claim_title_upgrade(&child).unwrap(),
4172 "a child is named by its opening message and left alone"
4173 );
4174
4175 let api = store.new_id();
4176 store.begin_api(&api).unwrap();
4177 store.append(&api, &Message::user("headless turn")).unwrap();
4178 store.title_if_unnamed(&api, "headless turn").unwrap();
4179 assert!(
4180 !store.claim_title_upgrade(&api).unwrap(),
4181 "a headless API session is named for free and never costs a call"
4182 );
4183 }
4184
4185 #[test]
4188 fn a_search_finds_a_session_by_the_name_it_was_given() {
4189 let dir = tempfile::tempdir().unwrap();
4190 let store = store(dir.path());
4191 let id = store.new_id();
4192 store
4193 .append(&id, &Message::user("something else entirely"))
4194 .unwrap();
4195 store.append(&id, &Message::assistant("noted")).unwrap();
4196 store.rename(&id, "gateway restart loop").unwrap();
4197
4198 for fts in [true, false] {
4199 let hits = store
4202 .with_db(|db| SessionStore::search_in(db, "restart loop", 10, fts, false))
4203 .unwrap();
4204 let named: Vec<_> = hits.iter().filter(|h| h.role == "title").collect();
4205 assert_eq!(named.len(), 1, "fts={fts}: {:?}", hits);
4206 assert_eq!(named[0].session_id, id);
4207 assert_eq!(named[0].snippet, "gateway restart loop");
4208 assert_eq!(
4209 named[0].seq, 0,
4210 "a name is read from the top of the transcript"
4211 );
4212 }
4213 let hits = store.search("noted", 10).unwrap();
4215 assert!(hits.iter().all(|h| h.role != "title"));
4216 assert_eq!(hits.len(), 1);
4217 }
4218
4219 #[test]
4223 fn a_page_of_the_tools_own_calls_does_not_hide_the_match_behind_them() {
4224 let dir = tempfile::tempdir().unwrap();
4225 let store = store(dir.path());
4226 let id = store.new_id();
4227 store
4228 .append(&id, &Message::user("the needle is here"))
4229 .unwrap();
4230 for i in 0..12 {
4231 let call = crate::message::ToolCall {
4232 id: format!("call-{i}"),
4233 kind: "function".to_string(),
4234 function: crate::message::FunctionCall {
4235 name: "session_search".to_string(),
4236 arguments: "{\"query\":\"needle\"}".to_string(),
4237 },
4238 };
4239 store
4240 .append(&id, &Message::assistant_tool_calls(None, vec![call]))
4241 .unwrap();
4242 store
4243 .append(
4244 &id,
4245 &Message::tool_result(format!("call-{i}"), "archive: no match for needle"),
4246 )
4247 .unwrap();
4248 }
4249
4250 for fts in [true, false] {
4251 let hits = store
4254 .with_db(|db| SessionStore::search_in(db, "needle", 1, fts, false))
4255 .unwrap();
4256 assert_eq!(hits.len(), 1, "fts={fts}: {hits:?}");
4257 assert_eq!(hits[0].role, "user", "fts={fts}: {hits:?}");
4258 }
4259 }
4260
4261 #[test]
4264 fn a_database_from_before_names_keeps_its_titles_and_learns_who_wrote_them() {
4265 let dir = tempfile::tempdir().unwrap();
4266 {
4267 let dir = dir.path().join("sessions");
4268 std::fs::create_dir_all(&dir).unwrap();
4269 let conn = Connection::open(dir.join(DB_FILE)).unwrap();
4270 conn.execute_batch(
4271 "CREATE TABLE sessions (
4272 id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
4273 title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
4274 origin TEXT NOT NULL DEFAULT 'native', pinned INTEGER NOT NULL DEFAULT 0);
4275 INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
4276 VALUES ('named', 1, 2, 'what I called it', 'first words', 2, 'native'),
4277 ('bare', 1, 2, NULL, 'first words', 2, 'native');",
4278 )
4279 .unwrap();
4280 }
4281 let store = store(dir.path());
4282 let list = store.list().unwrap();
4283 let named = list.iter().find(|s| s.id == "named").unwrap();
4284 assert_eq!(
4285 named.title.as_deref(),
4286 Some("what I called it"),
4287 "the title survives"
4288 );
4289
4290 assert!(
4291 !store.title_if_unnamed("named", "a derived name").unwrap(),
4292 "an old title is a person's, so stage one leaves it"
4293 );
4294 assert!(
4295 !store.claim_title_upgrade("named").unwrap(),
4296 "and no call is spent on it either"
4297 );
4298 assert!(
4299 store.title_if_unnamed("bare", "a derived name").unwrap(),
4300 "a session that had no name gets one"
4301 );
4302 assert_eq!(
4303 store.title("bare").unwrap().as_deref(),
4304 Some("a derived name")
4305 );
4306 }
4307
4308 #[test]
4309 fn deleting_a_session_removes_its_title_memory_and_lock_file() {
4310 let dir = tempfile::tempdir().unwrap();
4311 let root = dir.path().join("sessions");
4312 let store = store(dir.path());
4313 let a = store.new_id();
4314 let b = store.new_id();
4315 transcript(&store, &a);
4316 transcript(&store, &b);
4317 store.rename(&a, "doomed").unwrap();
4318 store
4319 .save_memory(&a, &memory("## Log\na summary", 2, 3))
4320 .unwrap();
4321 store
4322 .with_db(|db| {
4323 db.conn.execute(
4324 "INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, '{}')",
4325 params![a],
4326 )?;
4327 Ok(())
4328 })
4329 .unwrap();
4330 let lock = root.join(format!("{a}.lock"));
4331 std::fs::write(&lock, "pid 1\n").unwrap();
4332
4333 store.delete(&a).unwrap();
4334 assert!(!store.exists(&a));
4335 assert!(store.exists(&b), "the other session is untouched");
4336 assert!(store.load(&b).unwrap().len() == 4);
4337 assert_eq!(store.memory(&a).unwrap(), None);
4338 assert!(!lock.exists(), "the lock file does not outlive the session");
4339 assert!(store.delete(&a).is_err(), "deleting twice is an error");
4340 }
4341
4342 #[test]
4343 fn auto_prune_deletes_up_to_ten_sessions_and_refuses_more() {
4344 let dir = tempfile::tempdir().unwrap();
4345 let store = store(dir.path());
4346 let now = 1_700_000_000_000u64;
4347 for i in 0..12 {
4348 seed(&store, &format!("s{i:02}"), now - (100 - i) * 86_400_000);
4349 }
4350 assert_eq!(
4352 store.auto_prune(30, 0, now, None).unwrap(),
4353 AutoPrune::Skipped { would_remove: 12 }
4354 );
4355 assert_eq!(store.list().unwrap().len(), 12);
4356 assert_eq!(
4358 store.auto_prune(0, 2, now, None).unwrap(),
4359 AutoPrune::Pruned {
4360 removed: 10,
4361 failed: 0,
4362 pinned_kept: 0
4363 }
4364 );
4365 assert_eq!(store.list().unwrap().len(), 2);
4366 }
4367
4368 #[test]
4369 fn auto_prune_never_runs_without_a_limit_and_reports_nothing_to_do() {
4370 let dir = tempfile::tempdir().unwrap();
4371 let store = store(dir.path());
4372 let now = 1_700_000_000_000u64;
4373 assert_eq!(
4374 store.auto_prune(0, 0, now, None).unwrap(),
4375 AutoPrune::NoLimits
4376 );
4377 seed(&store, "fresh", now);
4378 assert_eq!(
4379 store.auto_prune(30, 0, now, None).unwrap(),
4380 AutoPrune::Nothing
4381 );
4382 assert_eq!(store.list().unwrap().len(), 1);
4383 }
4384
4385 #[test]
4386 fn auto_prune_spares_the_protected_session() {
4387 let dir = tempfile::tempdir().unwrap();
4388 let store = store(dir.path());
4389 let now = 1_700_000_000_000u64;
4390 seed(&store, "keep-me", now - 90 * 86_400_000);
4391 seed(&store, "old-1", now - 90 * 86_400_000);
4392 let outcome = store.auto_prune(7, 0, now, Some("keep-me")).unwrap();
4393 assert_eq!(
4394 outcome,
4395 AutoPrune::Pruned {
4396 removed: 1,
4397 failed: 0,
4398 pinned_kept: 0
4399 }
4400 );
4401 assert!(
4402 store.exists("keep-me"),
4403 "the session being resumed survives"
4404 );
4405 assert!(!store.exists("old-1"));
4406 }
4407
4408 #[test]
4409 fn rejects_path_traversal_ids() {
4410 let dir = tempfile::tempdir().unwrap();
4411 let store = store(dir.path());
4412 for bad in ["../etc/passwd", "a/b", "", "sp ace", "dot.dot"] {
4413 assert!(
4414 store.load(bad).is_err(),
4415 "{bad:?} must be refused before it reaches the database"
4416 );
4417 assert!(!store.exists(bad));
4418 }
4419 }
4420
4421 #[test]
4422 fn a_corrupt_row_is_reported_with_its_session_and_position() {
4423 let dir = tempfile::tempdir().unwrap();
4424 let store = store(dir.path());
4425 let id = store.new_id();
4426 transcript(&store, &id);
4427 store
4428 .with_db(|db| {
4429 db.conn.execute(
4430 "INSERT INTO messages (session_id, seq, at_ms, role, body)
4431 VALUES (?1, 99, 0, 'user', '{not json')",
4432 params![id],
4433 )?;
4434 Ok(())
4435 })
4436 .unwrap();
4437 let err = store.load(&id).unwrap_err().to_string();
4438 assert!(err.contains(&id) && err.contains("99"), "{err}");
4439 }
4440
4441 #[test]
4442 fn new_ids_are_unique() {
4443 let dir = tempfile::tempdir().unwrap();
4444 let store = store(dir.path());
4445 let ids: std::collections::HashSet<String> = (0..50).map(|_| store.new_id()).collect();
4446 assert_eq!(ids.len(), 50);
4447 for id in &ids {
4448 validate_id(id).unwrap();
4449 }
4450 }
4451
4452 #[test]
4453 fn utc_formatting() {
4454 assert_eq!(format_utc(0), "1970-01-01 00:00");
4455 assert_eq!(format_utc(1_700_000_000_000), "2023-11-14 22:13");
4456 }
4457
4458 #[test]
4459 fn rename_sets_title_without_touching_the_transcript() {
4460 let dir = tempfile::tempdir().unwrap();
4461 let store = store(dir.path());
4462 let id = store.new_id();
4463 transcript(&store, &id);
4464 let before = store.load(&id).unwrap();
4465 store.rename(&id, " a name ").unwrap();
4466 assert_eq!(store.title(&id).unwrap().as_deref(), Some("a name"));
4467 assert_eq!(store.load(&id).unwrap(), before);
4468 let listed = store.list().unwrap().into_iter().next().unwrap();
4469 assert_eq!(listed.label(), "a name", "the title wins over the preview");
4470 }
4471
4472 #[test]
4473 fn rename_rejects_bad_titles_and_unknown_sessions() {
4474 let dir = tempfile::tempdir().unwrap();
4475 let store = store(dir.path());
4476 let id = store.new_id();
4477 transcript(&store, &id);
4478 for bad in ["", " "] {
4479 assert!(store.rename(&id, bad).is_err(), "{bad:?}");
4480 }
4481 assert!(store.rename(&id, &"x".repeat(201)).is_err());
4482 assert!(store.rename(&id, "bad\nname").is_err());
4483 assert!(store.rename("no-such-session", "fine").is_err());
4484 assert_eq!(store.title(&id).unwrap(), None);
4485 }
4486
4487 #[test]
4488 fn json_export_is_the_complete_transcript() {
4489 let dir = tempfile::tempdir().unwrap();
4490 let store = store(dir.path());
4491 let id = store.new_id();
4492 transcript(&store, &id);
4493 let out = store.export(&id, ExportFormat::Json).unwrap();
4494 let doc: serde_json::Value = serde_json::from_str(&out).unwrap();
4495 assert_eq!(doc["format"], "eclipse-session/1");
4496 assert_eq!(doc["id"], id);
4497 assert_eq!(doc["messages"].as_array().unwrap().len(), 4);
4498 assert_eq!(doc["messages"][0]["message"]["role"], "user");
4499 assert_eq!(
4500 doc["messages"][1]["message"]["tool_calls"][0]["function"]["name"],
4501 "read_file"
4502 );
4503 assert!(out.ends_with('\n'));
4504 }
4505
4506 #[test]
4507 fn markdown_export_shows_turns_calls_and_results() {
4508 let dir = tempfile::tempdir().unwrap();
4509 let store = store(dir.path());
4510 let id = store.new_id();
4511 transcript(&store, &id);
4512 let out = store.export(&id, ExportFormat::Markdown).unwrap();
4513 assert!(out.contains("# "), "a heading, even without a title: {out}");
4514 assert!(out.contains("## 1. User"));
4515 assert!(out.contains("## 2. Assistant"));
4516 assert!(out.contains("**Tool call** `read_file`"));
4517 assert!(out.contains("## 3. Tool result: read_file"));
4518 assert!(out.contains("```json"), "arguments are pretty-printed");
4519 assert!(!out.contains("no result recorded"), "the call was answered");
4520 }
4521
4522 #[test]
4523 fn markdown_export_uses_the_title() {
4524 let dir = tempfile::tempdir().unwrap();
4525 let store = store(dir.path());
4526 let id = store.new_id();
4527 transcript(&store, &id);
4528 store.rename(&id, "a named session").unwrap();
4529 let out = store.export(&id, ExportFormat::Markdown).unwrap();
4530 assert!(out.starts_with("# a named session\n"), "{out}");
4531 }
4532
4533 const NO_SPAN: (Option<u64>, Option<u64>) = (None, None);
4536
4537 fn handoff(text: &str, turns: usize, messages: usize) -> Handoff {
4538 Handoff {
4539 text: text.into(),
4540 version: crate::compact::VERSION.into(),
4541 covered_turns: turns,
4542 covered_messages: messages,
4543 covered_from: None,
4544 covered_to: None,
4545 generated_at_ms: 1_700_000_000_000,
4546 judgement: None,
4547 }
4548 }
4549
4550 fn memory(text: &str, turns: usize, messages: usize) -> Memory {
4551 Memory {
4552 version: MEMORY_VERSION,
4553 handoff: Some(handoff(text, turns, messages)),
4554 }
4555 }
4556
4557 #[test]
4562 fn a_summary_era_memory_file_loads_with_its_summary_ignored() {
4563 let dir = tempfile::tempdir().unwrap();
4564 let store = store(dir.path());
4565 let id = store.new_id();
4566 transcript(&store, &id);
4567 let v2 = r#"{"version":2,"summary":"old news","covered_turns":2,
4568 "covered_messages":4,"generated_at_ms":1700000000000}"#;
4569 store
4570 .with_db(|db| {
4571 db.conn.execute(
4572 "INSERT INTO memory (session_id, body) VALUES (?1, ?2)",
4573 params![id, v2],
4574 )?;
4575 Ok(())
4576 })
4577 .unwrap();
4578
4579 let m = store.memory(&id).unwrap().unwrap();
4580 assert_eq!(m.schema(), 2, "the file says what wrote it");
4581 assert_eq!(
4582 m.usable_handoff(),
4583 None,
4584 "a summary alone is not a handoff, and there is nothing else to read"
4585 );
4586 assert!(
4587 m.validate().is_err(),
4588 "a record with nothing in it is not memory"
4589 );
4590
4591 store
4592 .save_handoff(
4593 &id,
4594 crate::context::Trimmed {
4595 turns: 2,
4596 messages: 4,
4597 },
4598 NO_SPAN,
4599 "## Log\n[#0]",
4600 None,
4601 )
4602 .unwrap();
4603 let after = store.memory(&id).unwrap().unwrap();
4604 assert_eq!(after.schema(), MEMORY_VERSION, "rewritten at this schema");
4605 assert_eq!(after.handoff.unwrap().text, "## Log\n[#0]");
4606 let raw = store
4607 .with_db(|db| {
4608 Ok(db
4609 .conn
4610 .query_row(
4611 "SELECT body FROM memory WHERE session_id = ?1",
4612 params![id],
4613 |r| r.get::<_, String>(0),
4614 )
4615 .unwrap())
4616 })
4617 .unwrap();
4618 assert!(
4619 !raw.contains("summary"),
4620 "the field a summary-era build wrote is gone from the file: {raw}"
4621 );
4622 }
4623
4624 #[test]
4625 fn saving_a_handoff_replaces_the_document_and_never_the_other_way_round() {
4626 let dir = tempfile::tempdir().unwrap();
4627 let store = store(dir.path());
4628 let id = store.new_id();
4629 transcript(&store, &id);
4630
4631 store
4632 .save_handoff(
4633 &id,
4634 crate::context::Trimmed {
4635 turns: 1,
4636 messages: 2,
4637 },
4638 NO_SPAN,
4639 "## Log\nA",
4640 None,
4641 )
4642 .unwrap();
4643 assert_eq!(
4644 store.readable_memory(&id).unwrap().handoff.unwrap().text,
4645 "## Log\nA"
4646 );
4647
4648 store
4651 .save_handoff(
4652 &id,
4653 crate::context::Trimmed {
4654 turns: 3,
4655 messages: 6,
4656 },
4657 NO_SPAN,
4658 "## Log\nB",
4659 Some(Judgement {
4660 text: "- because the first answer settled it".into(),
4661 model: "aux".into(),
4662 generated_at_ms: 1,
4663 }),
4664 )
4665 .unwrap();
4666 let now = store.readable_memory(&id).unwrap();
4667 let h = now.handoff.unwrap();
4668 assert_eq!(h.text, "## Log\nB");
4669 assert_eq!(h.covered_turns, 3);
4670 assert_eq!(
4671 h.judgement.unwrap().model,
4672 "aux",
4673 "and the judgement travels with the document it belongs to"
4674 );
4675 }
4676
4677 #[test]
4678 fn a_memory_from_a_newer_schema_is_refused_rather_than_half_read() {
4679 let dir = tempfile::tempdir().unwrap();
4680 let store = store(dir.path());
4681 let id = store.new_id();
4682 transcript(&store, &id);
4683 let mut m = memory("## Log\nC", 1, 2);
4684 m.version = MEMORY_VERSION + 1;
4685 let why = m.validate().unwrap_err();
4686 assert!(why.contains("newer than this build"), "{why}");
4687 assert!(
4688 store.save_memory(&id, &m).is_err(),
4689 "a record this build cannot read is not written either"
4690 );
4691 }
4692
4693 #[test]
4697 fn a_memory_too_large_to_read_back_is_refused_at_the_write() {
4698 let dir = tempfile::tempdir().unwrap();
4699 let store = store(dir.path());
4700 let id = store.new_id();
4701 transcript(&store, &id);
4702 let mut big = memory("## Log\n", 1, 2);
4703 big.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize);
4704 let err = store
4705 .save_memory(&id, &big)
4706 .expect_err("a record the reader would refuse is not written");
4707 assert!(err.to_string().contains("record limit"), "{err}");
4708 assert!(
4709 store.memory(&id).unwrap().is_none(),
4710 "nothing was stored, and the row did not become unreadable"
4711 );
4712
4713 let mut fits = memory("## Log\n", 1, 2);
4715 let overhead =
4716 serde_json::to_string(&fits).unwrap().len() - fits.handoff.as_ref().unwrap().text.len();
4717 fits.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize - overhead);
4718 store.save_memory(&id, &fits).expect("the cap itself fits");
4719 assert!(store.readable_memory(&id).is_some(), "and it reads back");
4720 }
4721
4722 #[test]
4726 fn a_handoff_is_its_range_and_not_just_its_counts() {
4727 let mut h = handoff("## Log\nsomeone decided something", 1, 2);
4728 assert!(
4729 !h.covers(1, 2, Some(2), Some(3)),
4730 "a document with no endpoints cannot say which window it described"
4731 );
4732 h.covered_from = Some(0);
4733 h.covered_to = Some(1);
4734 assert!(h.covers(1, 2, Some(0), Some(1)));
4735 assert!(
4736 !h.covers(1, 2, Some(2), Some(3)),
4737 "the same size and the same counts, a different window"
4738 );
4739 assert!(
4740 !h.covers(1, 2, None, None),
4741 "no endpoints on the caller's side either"
4742 );
4743 h.covered_to = Some(9);
4744 assert!(
4745 !h.covers(1, 2, Some(0), Some(1)),
4746 "the end is part of the range"
4747 );
4748 }
4749
4750 #[test]
4751 fn memory_round_trips_in_its_documented_shape_and_the_database_is_private() {
4752 let dir = tempfile::tempdir().unwrap();
4753 let store = store(dir.path());
4754 let id = store.new_id();
4755 transcript(&store, &id);
4756 store
4757 .save_handoff(
4758 &id,
4759 crate::context::Trimmed {
4760 turns: 2,
4761 messages: 4,
4762 },
4763 NO_SPAN,
4764 "## Log\nthey agreed on the plan",
4765 None,
4766 )
4767 .unwrap();
4768 let raw = store
4769 .with_db(|db| {
4770 Ok(db
4771 .conn
4772 .query_row(
4773 "SELECT body FROM memory WHERE session_id = ?1",
4774 params![id],
4775 |r| r.get::<_, String>(0),
4776 )
4777 .unwrap())
4778 })
4779 .unwrap();
4780 let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
4781 assert_eq!(parsed["version"], MEMORY_VERSION);
4782 assert_eq!(parsed["handoff"]["covered_turns"], 2);
4783 assert_eq!(parsed["handoff"]["text"], "## Log\nthey agreed on the plan");
4784 #[cfg(unix)]
4785 {
4786 use std::os::unix::fs::PermissionsExt;
4787 let mode = std::fs::metadata(store.dir().join("sessions.db"))
4788 .unwrap()
4789 .permissions()
4790 .mode()
4791 & 0o777;
4792 assert_eq!(
4793 mode, 0o600,
4794 "the database is owner-only, like the transcripts were"
4795 );
4796 let dir_mode = std::fs::metadata(store.dir()).unwrap().permissions().mode() & 0o777;
4800 assert_eq!(dir_mode, 0o700, "the session directory is owner-only");
4801 for sidecar in ["sessions.db-wal", "sessions.db-shm"] {
4802 let p = store.dir().join(sidecar);
4803 if !p.exists() {
4804 continue;
4805 }
4806 let m = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777;
4807 assert_eq!(m, 0o600, "{sidecar} is owner-only");
4808 }
4809 }
4810 }
4811
4812 #[test]
4813 fn memory_validation_rejects_nonsense() {
4814 let dir = tempfile::tempdir().unwrap();
4815 let store = store(dir.path());
4816 let id = store.new_id();
4817 transcript(&store, &id);
4818 let empty = Memory {
4819 version: MEMORY_VERSION,
4820 handoff: None,
4821 };
4822 assert!(empty.validate().is_err() && store.save_memory(&id, &empty).is_err());
4823 let mut m = memory(" padded ", 1, 1);
4824 assert!(m.validate().is_err(), "an untrimmed document is refused");
4825 m = memory("fine", 2, 1);
4826 assert!(m.validate().is_err(), "messages < turns is nonsense");
4827 m.handoff.as_mut().unwrap().covered_messages = 2;
4828 m.handoff.as_mut().unwrap().covered_turns = 0;
4829 assert!(m.validate().is_err(), "covering no turn is nonsense");
4830 m = memory("", 1, 2);
4831 assert!(m.validate().is_err(), "an empty document is not memory");
4832 let mut m = memory("fine", 2, 4);
4833 m.handoff.as_mut().unwrap().judgement = Some(Judgement {
4834 text: "\n- untrimmed".into(),
4835 model: "aux".into(),
4836 generated_at_ms: 1,
4837 });
4838 assert!(m.validate().is_err(), "an untrimmed judgement is refused");
4839 assert!(store.save_memory(&id, &memory("fine", 2, 4)).is_ok());
4840 }
4841
4842 #[test]
4843 fn corrupt_or_invalid_memory_is_not_usable() {
4844 let dir = tempfile::tempdir().unwrap();
4845 let store = store(dir.path());
4846 let id = store.new_id();
4847 transcript(&store, &id);
4848 store
4849 .with_db(|db| {
4850 db.conn.execute(
4851 "INSERT INTO memory (session_id, body) VALUES (?1, 'not json')",
4852 params![id],
4853 )?;
4854 Ok(())
4855 })
4856 .unwrap();
4857 assert!(
4858 store.memory(&id).is_err(),
4859 "corruption is reported, not hidden"
4860 );
4861 assert_eq!(store.readable_memory(&id), None, "and never used");
4862
4863 store
4864 .save_memory(&id, &memory("valid again", 1, 1))
4865 .unwrap();
4866 assert!(store.readable_memory(&id).is_some());
4867 }
4868
4869 #[test]
4870 fn memory_is_per_session() {
4871 let dir = tempfile::tempdir().unwrap();
4872 let store = store(dir.path());
4873 let a = store.new_id();
4874 let b = store.new_id();
4875 store.append(&a, &Message::user("a")).unwrap();
4876 store.append(&b, &Message::user("b")).unwrap();
4877 store.save_memory(&a, &memory("about a", 1, 1)).unwrap();
4878 assert!(store.memory(&b).unwrap().is_none());
4879 assert_eq!(
4880 store.readable_memory(&a).unwrap().handoff.unwrap().text,
4881 "about a"
4882 );
4883 }
4884
4885 #[test]
4886 fn delete_and_prune_remove_the_memory_too() {
4887 let dir = tempfile::tempdir().unwrap();
4888 let store = store(dir.path());
4889 let id = store.new_id();
4890 transcript(&store, &id);
4891 store
4892 .save_memory(&id, &memory("gone with it", 1, 1))
4893 .unwrap();
4894 store.delete(&id).unwrap();
4895 assert!(
4896 store.load_records(&id).is_err(),
4897 "the session is gone, not empty"
4898 );
4899 assert_eq!(store.memory(&id).unwrap(), None);
4900 }
4901
4902 #[test]
4905 fn a_deleted_legacy_session_does_not_come_back() {
4906 let dir = tempfile::tempdir().unwrap();
4907 let root = dir.path().join("sessions");
4908 let path = legacy_file(
4909 &root,
4910 "deleted-me",
4911 &line(&Message::user("doomed"), 1_700_000_000_000),
4912 );
4913 let store = SessionStore::new(&root);
4914 assert!(store.exists("deleted-me"));
4915 store.delete("deleted-me").unwrap();
4916 assert!(!path.exists(), "the imported source goes with the session");
4917 drop(store);
4918
4919 let again = SessionStore::new(&root);
4921 assert!(
4922 !again.exists("deleted-me"),
4923 "a deleted session must stay deleted across restarts"
4924 );
4925 assert!(again.list().unwrap().is_empty());
4926 }
4927
4928 #[test]
4929 fn a_legacy_transcript_is_imported_once_and_the_file_is_kept() {
4930 let dir = tempfile::tempdir().unwrap();
4931 let root = dir.path().join("sessions");
4932 let body = format!(
4933 "{}{}",
4934 line(&Message::user("from the old world"), 1_700_000_000_000),
4935 line(&Message::assistant("and the reply"), 1_700_000_001_000)
4936 );
4937 let path = legacy_file(&root, "legacy-1", &body);
4938 std::fs::write(root.join("legacy-1.meta.json"), r#"{"title":"old title"}"#).unwrap();
4939
4940 let store = SessionStore::new(&root);
4941 let messages = store.load("legacy-1").unwrap();
4942 assert_eq!(messages.len(), 2);
4943 assert_eq!(messages[0].content.as_deref(), Some("from the old world"));
4944 assert_eq!(
4945 store.title("legacy-1").unwrap().as_deref(),
4946 Some("old title")
4947 );
4948 assert!(path.exists(), "importing must not delete the source");
4949
4950 let info = store.list().unwrap().into_iter().next().unwrap();
4951 assert_eq!(info.preview, "from the old world");
4952 assert_eq!(info.updated_ms, 1_700_000_001_000);
4953
4954 drop(store);
4956 let again = SessionStore::new(&root);
4957 assert_eq!(again.load("legacy-1").unwrap().len(), 2);
4958 assert_eq!(again.list().unwrap().len(), 1);
4959 }
4960
4961 #[test]
4962 fn a_truncated_legacy_tail_is_dropped_and_the_rest_is_imported() {
4963 let dir = tempfile::tempdir().unwrap();
4964 let root = dir.path().join("sessions");
4965 let good = line(&Message::user("complete"), 1_700_000_000_000);
4966 let body = format!("{good}{{\"ts\":1,\"message\":{{\"role\":\"user\"");
4967 legacy_file(&root, "half-written", &body);
4968 let store = SessionStore::new(&root);
4969 let messages = store.load("half-written").unwrap();
4970 assert_eq!(messages.len(), 1, "the complete record survived");
4971 assert_eq!(messages[0].content.as_deref(), Some("complete"));
4972 }
4973
4974 #[test]
4975 fn a_complete_final_record_without_a_newline_is_kept() {
4976 let dir = tempfile::tempdir().unwrap();
4977 let root = dir.path().join("sessions");
4978 let body = line(&Message::user("no trailing newline"), 5)
4979 .trim_end()
4980 .to_string();
4981 legacy_file(&root, "unterminated", &body);
4982 let store = SessionStore::new(&root);
4983 assert_eq!(store.load("unterminated").unwrap().len(), 1);
4984 }
4985
4986 #[test]
4987 fn a_legacy_file_corrupt_in_the_middle_is_refused_not_half_imported() {
4988 let dir = tempfile::tempdir().unwrap();
4989 let root = dir.path().join("sessions");
4990 let body = format!(
4991 "{}garbage\n{}",
4992 line(&Message::user("before"), 1),
4993 line(&Message::assistant("after"), 2)
4994 );
4995 let path = legacy_file(&root, "corrupt-mid", &body);
4996 let store = SessionStore::new(&root);
4997 assert!(
4998 !store.exists("corrupt-mid"),
4999 "importing part of it would silently drop a message"
5000 );
5001 assert!(path.exists(), "and the file is left for a human to look at");
5002 assert!(store.list().unwrap().is_empty());
5003 }
5004
5005 #[test]
5006 fn an_empty_legacy_transcript_keeps_its_file_time_not_epoch() {
5007 let dir = tempfile::tempdir().unwrap();
5008 let root = dir.path().join("sessions");
5009 legacy_file(&root, "empty-one", "");
5010 let store = SessionStore::new(&root);
5011 let info = store.list().unwrap().into_iter().next().unwrap();
5012 assert_eq!(info.messages, 0);
5013 assert!(
5014 info.updated_ms > 1_600_000_000_000,
5015 "a corrupt transcript still ages from its mtime, not from 1970: {}",
5016 info.updated_ms
5017 );
5018 }
5019
5020 #[test]
5021 fn a_legacy_memory_sidecar_is_imported() {
5022 let dir = tempfile::tempdir().unwrap();
5023 let root = dir.path().join("sessions");
5024 legacy_file(
5025 &root,
5026 "with-memory",
5027 &line(&Message::user("hi"), 1_700_000_000_000),
5028 );
5029 let m = memory("remembered from before", 2, 4);
5030 std::fs::write(
5031 root.join("with-memory.memory.json"),
5032 serde_json::to_string(&m).unwrap(),
5033 )
5034 .unwrap();
5035 let store = SessionStore::new(&root);
5036 assert_eq!(store.readable_memory("with-memory"), Some(m));
5037 }
5038
5039 #[test]
5040 fn an_unparseable_legacy_memory_sidecar_is_imported_and_reported() {
5041 let dir = tempfile::tempdir().unwrap();
5042 let root = dir.path().join("sessions");
5043 legacy_file(
5044 &root,
5045 "bad-memory",
5046 &line(&Message::user("hi"), 1_700_000_000_000),
5047 );
5048 std::fs::write(
5050 root.join("bad-memory.memory.json"),
5051 r#"{"version":3,"handoff":{"#,
5052 )
5053 .unwrap();
5054 let store = SessionStore::new(&root);
5055 assert!(
5056 store.memory("bad-memory").is_err(),
5057 "an unparseable sidecar is an error to read, not silence"
5058 );
5059 assert_eq!(store.readable_memory("bad-memory"), None);
5060 }
5061
5062 #[test]
5065 fn search_finds_message_text_and_tool_arguments() {
5066 let dir = tempfile::tempdir().unwrap();
5067 let store = store(dir.path());
5068 let id = store.new_id();
5069 store
5070 .append(&id, &Message::user("the deploy key lives in vault"))
5071 .unwrap();
5072 store
5073 .append(
5074 &id,
5075 &Message::assistant_tool_calls(
5076 None,
5077 vec![call("c9", "shell", r#"{"cmd":"systemctl status nginx"}"#)],
5078 ),
5079 )
5080 .unwrap();
5081 let other = store.new_id();
5082 store.append(&other, &Message::user("unrelated")).unwrap();
5083
5084 let hits = store.search("vault", 10).unwrap();
5085 assert_eq!(hits.len(), 1, "{hits:?}");
5086 assert_eq!(hits[0].session_id, id);
5087 assert_eq!(hits[0].seq, 0);
5088 assert_eq!(hits[0].role, "user");
5089 assert!(hits[0].snippet.contains("vault"));
5090
5091 let hits = store.search("nginx", 10).unwrap();
5092 assert_eq!(hits.len(), 1, "tool arguments are searchable: {hits:?}");
5093 assert_eq!(hits[0].seq, 1);
5094
5095 assert!(store.search("nothing-said-this", 10).unwrap().is_empty());
5096 assert!(store.search(" ", 10).unwrap().is_empty());
5097 }
5098
5099 #[test]
5107 fn a_delete_that_fails_halfway_leaves_the_session_alone() {
5108 let dir = tempfile::tempdir().unwrap();
5109 let store = store(dir.path());
5110 let id = store.new_id();
5111 store
5112 .append(&id, &Message::user("an undeletable mention of widget"))
5113 .unwrap();
5114 if !store.with_db(|db| Ok(db.fts)).unwrap() {
5115 return; }
5117 store
5118 .with_db(|db| {
5119 db.conn.execute_batch("DROP TABLE messages_fts")?;
5120 Ok(())
5121 })
5122 .unwrap();
5123
5124 assert!(
5125 store.delete(&id).is_err(),
5126 "the failed delete is reported to the caller"
5127 );
5128
5129 store
5130 .with_db(|db| {
5131 let sessions: i64 = db.conn.query_row(
5132 "SELECT count(*) FROM sessions WHERE id = ?1",
5133 params![id],
5134 |r| r.get(0),
5135 )?;
5136 assert_eq!(
5137 sessions, 1,
5138 "a delete that failed must not have half-happened"
5139 );
5140 let messages: i64 = db.conn.query_row(
5141 "SELECT count(*) FROM messages WHERE session_id = ?1",
5142 params![id],
5143 |r| r.get(0),
5144 )?;
5145 assert_eq!(messages, 1, "its messages are still there too");
5146 Ok(())
5147 })
5148 .unwrap();
5149
5150 assert!(store.delete(&id).is_err());
5152 }
5153
5154 #[test]
5158 fn a_stale_index_row_is_skipped_rather_than_failing_the_search() {
5159 let dir = tempfile::tempdir().unwrap();
5160 let store = store(dir.path());
5161 let id = store.new_id();
5162 store
5163 .append(&id, &Message::user("the live mention of widget"))
5164 .unwrap();
5165
5166 store
5168 .with_db(|db| {
5169 db.conn
5170 .execute("DELETE FROM messages WHERE session_id = ?1", params![id])?;
5171 Ok(())
5172 })
5173 .unwrap();
5174
5175 let hits = store.search("widget", 10).unwrap();
5176 assert!(
5177 hits.is_empty(),
5178 "the orphan is dropped, not fatal: {hits:?}"
5179 );
5180 }
5181
5182 #[test]
5184 fn deleting_a_session_leaves_nothing_of_it_behind() {
5185 let dir = tempfile::tempdir().unwrap();
5186 let store = store(dir.path());
5187 let id = store.new_id();
5188 store
5189 .append(&id, &Message::user("a deletable mention of widget"))
5190 .unwrap();
5191 let keep = store.new_id();
5192 store
5193 .append(&keep, &Message::user("a kept mention of widget"))
5194 .unwrap();
5195
5196 store.delete(&id).unwrap();
5197
5198 store
5199 .with_db(|db| {
5200 let messages: i64 = db.conn.query_row(
5201 "SELECT count(*) FROM messages WHERE session_id = ?1",
5202 params![id],
5203 |r| r.get(0),
5204 )?;
5205 assert_eq!(messages, 0, "messages go with the session");
5206 if db.fts {
5207 let indexed: i64 = db.conn.query_row(
5208 "SELECT count(*) FROM messages_fts WHERE session_id = ?1",
5209 params![id],
5210 |r| r.get(0),
5211 )?;
5212 assert_eq!(indexed, 0, "and so does the index, in the same transaction");
5213 }
5214 Ok(())
5215 })
5216 .unwrap();
5217
5218 let hits = store.search("widget", 10).unwrap();
5219 assert_eq!(hits.len(), 1, "the other session is untouched: {hits:?}");
5220 assert_eq!(hits[0].session_id, keep);
5221 assert!(
5222 store.delete(&id).is_err(),
5223 "deleting it twice still says there is no such session"
5224 );
5225 }
5226
5227 #[test]
5231 fn deleting_a_session_deletes_its_plan_and_its_steps() {
5232 let dir = tempfile::tempdir().unwrap();
5233 let store = store(dir.path());
5234 let doomed = store.new_id();
5235 let kept = store.new_id();
5236 let items = vec![
5237 crate::plans::Item::new("1", "read the audit", crate::plans::Status::Done),
5238 crate::plans::Item::new("2", "fix the writer", crate::plans::Status::InProgress),
5239 ];
5240 assert_eq!(store.set_plan(&doomed, &items).unwrap(), 1);
5241 assert_eq!(
5242 store.set_plan(&doomed, &items).unwrap(),
5243 2,
5244 "every write bumps the revision, so two surfaces can tell a stale list"
5245 );
5246 store.set_plan(&kept, &items).unwrap();
5247 let read = store.plan(&doomed).unwrap().unwrap();
5248 assert_eq!(read.revision, 2);
5249 assert_eq!(read.items, items, "read back in `position` order");
5250
5251 store.delete(&doomed).unwrap();
5252
5253 assert!(
5254 store.plan(&doomed).unwrap().is_none(),
5255 "the plan goes with the session"
5256 );
5257 store
5258 .with_db(|db| {
5259 let gone: i64 = db.conn.query_row(
5260 "SELECT count(*) FROM plan_items WHERE session_id = ?1",
5261 params![doomed],
5262 |r| r.get(0),
5263 )?;
5264 assert_eq!(gone, 0, "and so do its steps");
5265 let kept_steps: i64 = db.conn.query_row(
5266 "SELECT count(*) FROM plan_items WHERE session_id = ?1",
5267 params![kept],
5268 |r| r.get(0),
5269 )?;
5270 assert_eq!(kept_steps, 2, "the other session's plan is untouched");
5271 Ok(())
5272 })
5273 .unwrap();
5274 }
5275
5276 #[test]
5279 fn search_answers_newest_first_whichever_backend_runs() {
5280 let dir = tempfile::tempdir().unwrap();
5281 let store = store(dir.path());
5282 let older = store.new_id();
5283 store
5284 .append(&older, &Message::user("the older mention of gadget"))
5285 .unwrap();
5286 std::thread::sleep(std::time::Duration::from_millis(3));
5289 let newer = store.new_id();
5290 store
5291 .append(&newer, &Message::user("the newer mention of gadget"))
5292 .unwrap();
5293
5294 store
5295 .with_db(|db| {
5296 for use_fts in [true, false] {
5297 if use_fts && !db.fts {
5298 continue;
5299 }
5300 let hits = SessionStore::search_in(db, "gadget", 1, use_fts, false).unwrap();
5301 assert_eq!(hits.len(), 1, "fts={use_fts}");
5302 assert_eq!(
5303 hits[0].session_id, newer,
5304 "a limit of one has to take the newest hit, not the first rowid (fts={use_fts})"
5305 );
5306 }
5307 Ok(())
5308 })
5309 .unwrap();
5310 }
5311
5312 #[test]
5313 fn search_treats_percent_and_underscore_as_text_not_wildcards() {
5314 let dir = tempfile::tempdir().unwrap();
5315 let store = store(dir.path());
5316 let id = store.new_id();
5317 store
5318 .append(&id, &Message::user("disk is 100% full"))
5319 .unwrap();
5320 store
5321 .append(&id, &Message::user("disk is 100 percent full"))
5322 .unwrap();
5323 store
5324 .append(&id, &Message::user("the file a_b.txt is here"))
5325 .unwrap();
5326 store
5327 .append(&id, &Message::user("the file axb.txt is not"))
5328 .unwrap();
5329
5330 store
5334 .with_db(|db| {
5335 let percent = SessionStore::search_in(db, "100%", 10, false, false).unwrap();
5336 assert_eq!(
5337 percent.len(),
5338 1,
5339 "`100%` is a substring, not `100` plus a wildcard: {percent:?}"
5340 );
5341 assert!(percent[0].snippet.contains("100% full"));
5342
5343 let underscore = SessionStore::search_in(db, "a_b.txt", 10, false, false).unwrap();
5344 assert_eq!(
5345 underscore.len(),
5346 1,
5347 "`_` is a character, not any character: {underscore:?}"
5348 );
5349 assert!(underscore[0].snippet.contains("a_b.txt"));
5350 Ok(())
5351 })
5352 .unwrap();
5353 }
5354
5355 #[test]
5358 fn a_like_literal_escapes_every_wildcard_character() {
5359 assert_eq!(like_literal("plain"), "plain");
5360 assert_eq!(like_literal("100%"), r"100\%");
5361 assert_eq!(like_literal("a_b"), r"a\_b");
5362 assert_eq!(like_literal(r"C:\temp"), r"C:\\temp");
5363 }
5364
5365 #[test]
5366 fn search_survives_query_syntax_that_would_break_fts() {
5367 let dir = tempfile::tempdir().unwrap();
5368 let store = store(dir.path());
5369 let id = store.new_id();
5370 store
5371 .append(&id, &Message::user(r#"a "quoted" thing AND (parens)"#))
5372 .unwrap();
5373 for q in [r#""quoted""#, "AND (parens)", "*", "a AND OR NOT", "-x"] {
5375 let _ = store.search(q, 5).unwrap();
5376 }
5377 assert_eq!(store.search("quoted", 5).unwrap().len(), 1);
5378 }
5379
5380 #[test]
5381 fn search_results_carry_the_session_and_position() {
5382 let dir = tempfile::tempdir().unwrap();
5383 let store = store(dir.path());
5384 let id = store.new_id();
5385 transcript(&store, &id);
5386 let hits = store.search("contents", 10).unwrap();
5387 assert_eq!(hits.len(), 1);
5388 assert_eq!(hits[0].session_id, id);
5389 assert_eq!(hits[0].seq, 2, "the tool result is the third message");
5390 assert_eq!(hits[0].role, "tool");
5391 assert!(hits[0].at_ms > 0);
5392 }
5393
5394 #[test]
5395 fn a_subagent_session_says_where_it_came_from_and_a_native_one_does_not() {
5396 let dir = tempfile::tempdir().unwrap();
5397 let store = store(dir.path());
5398 let parent = store.new_id();
5399 let child = store.new_id();
5400 store.append(&parent, &Message::user("big job")).unwrap();
5401 store.begin_subagent(&child, &parent, "big:v2").unwrap();
5402 store.append(&child, &Message::user("sub job")).unwrap();
5403
5404 let list = store.list().unwrap();
5405 let find = |id: &str| list.iter().find(|s| s.id == id).unwrap();
5406 assert_eq!(find(&parent).origin, "native");
5407 assert!(find(&parent).subagent().is_none());
5408 let origin = find(&child).subagent().unwrap();
5409 assert_eq!((origin.parent, origin.route), (parent.as_str(), "big:v2"));
5410 assert_eq!(
5411 find(&child).preview,
5412 "sub job",
5413 "the first message still names it"
5414 );
5415 }
5416
5417 #[test]
5418 fn beginning_a_subagent_twice_keeps_the_first_origin() {
5419 let dir = tempfile::tempdir().unwrap();
5420 let store = store(dir.path());
5421 store.begin_subagent("c1", "p1", "big").unwrap();
5422 store.begin_subagent("c1", "p2", "other").unwrap();
5423 let info = store.list().unwrap().remove(0);
5424 assert_eq!(info.subagent().unwrap().parent, "p1");
5425 assert!(store.begin_subagent("c2", "../p", "big").is_err());
5426 }
5427
5428 #[test]
5431 fn an_api_session_keeps_its_tag_when_the_run_writes_to_it() {
5432 let dir = tempfile::tempdir().unwrap();
5433 let store = store(dir.path());
5434 let id = store.new_id();
5435 store.begin_api(&id).unwrap();
5436 store.append(&id, &Message::user("ask")).unwrap();
5437 store.append(&id, &Message::assistant("answer")).unwrap();
5438
5439 let info = store.list().unwrap().remove(0);
5440 assert_eq!(info.id, id);
5441 assert_eq!(info.origin, SessionStore::API_ORIGIN);
5442 assert!(info.subagent().is_none(), "tagged, not a child");
5443 assert_eq!(info.messages, 2, "and the transcript is really there");
5444 }
5445
5446 #[test]
5449 fn the_sweep_takes_old_api_sessions_and_leaves_the_rest() {
5450 let dir = tempfile::tempdir().unwrap();
5451 let store = store(dir.path());
5452
5453 let old_api = store.new_id();
5454 store.begin_api(&old_api).unwrap();
5455 store.append(&old_api, &Message::user("poll")).unwrap();
5456
5457 let mine = store.new_id();
5458 store
5459 .append(&mine, &Message::user("a real conversation"))
5460 .unwrap();
5461
5462 let pinned_api = store.new_id();
5463 store.begin_api(&pinned_api).unwrap();
5464 store
5465 .append(&pinned_api, &Message::user("keep me"))
5466 .unwrap();
5467 store.set_pinned(&pinned_api, true).unwrap();
5468
5469 let pruned = store.prune_api_sessions(now_ms() + 1).unwrap();
5470 assert_eq!(pruned, 1, "only the API's own, unpinned session");
5471 let left: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
5472 assert!(
5473 left.contains(&mine),
5474 "a conversation is never swept: {left:?}"
5475 );
5476 assert!(left.contains(&pinned_api), "a pin is a decision: {left:?}");
5477 assert!(!left.contains(&old_api), "{left:?}");
5478 }
5479
5480 #[test]
5483 fn the_sweep_is_empty_when_there_is_nothing_the_api_left() {
5484 let dir = tempfile::tempdir().unwrap();
5485 let store = store(dir.path());
5486 store.append("n1", &Message::user("hello")).unwrap();
5487 assert_eq!(store.prune_api_sessions(u64::MAX).unwrap(), 0);
5488 assert_eq!(store.list().unwrap().len(), 1);
5489 }
5490
5491 #[cfg(unix)]
5492 #[tokio::test]
5493 async fn only_a_session_a_live_run_holds_is_reported_as_held() {
5494 let dir = tempfile::tempdir().unwrap();
5495 let store = store(dir.path());
5496 let wait = std::time::Duration::from_millis(0);
5497 let live = store.lock("live", wait).await.unwrap();
5498 drop(store.lock("finished", wait).await.unwrap());
5500
5501 let held = held_locks(store.dir());
5502 assert_eq!(held.len(), 1, "{held:?}");
5503 assert_eq!(held[0].id, "live");
5504 assert!(held[0].holder.starts_with("pid "), "{held:?}");
5505
5506 drop(live);
5507 assert!(held_locks(store.dir()).is_empty());
5508 assert!(held_locks(&dir.path().join("no-such-dir")).is_empty());
5509 }
5510
5511 fn picture_message(text: Option<&str>, name: &str) -> Message {
5512 let mut m = match text {
5513 Some(t) => Message::user(t),
5514 None => Message {
5515 role: Role::User,
5516 content: None,
5517 reasoning: None,
5518 finish_reason: None,
5519 tool_calls: Vec::new(),
5520 tool_call_id: None,
5521 images: Vec::new(),
5522 seq: None,
5523 },
5524 };
5525 m.images.push(crate::message::ImagePart {
5526 name: name.into(),
5527 mime: "image/png".into(),
5528 url: "data:image/png;base64,AAAA".into(),
5529 seen: None,
5530 });
5531 m
5532 }
5533
5534 #[test]
5537 fn describing_a_picture_reports_whether_it_changed_anything() {
5538 let dir = tempfile::tempdir().unwrap();
5539 let store = SessionStore::new(dir.path().to_path_buf());
5540 let id = store.new_id();
5541 let seq = store
5542 .append_seq(&id, &picture_message(Some("look"), "shot.png"))
5543 .unwrap();
5544 assert!(
5545 store
5546 .set_image_seen(&id, seq as u64, 0, "a dashboard with a red chart")
5547 .unwrap(),
5548 "a picture that is there was described"
5549 );
5550 let hits = store.search("red chart", 5).unwrap();
5552 assert_eq!(hits.len(), 1, "the description is searchable: {hits:?}");
5553 assert!(store.set_image_seen(&id, seq as u64, 0, "again").unwrap());
5555 assert!(
5557 !store.set_image_seen(&id, 999, 0, "nowhere").unwrap(),
5558 "a missing row used to answer Ok(()) — a caller could not tell it from a write"
5559 );
5560 assert!(!store.set_image_seen(&id, seq as u64, 7, "no").unwrap());
5562 }
5563
5564 #[test]
5567 fn a_first_message_with_no_text_does_not_freeze_the_preview() {
5568 let dir = tempfile::tempdir().unwrap();
5569 let store = SessionStore::new(dir.path().to_path_buf());
5570 let id = store.new_id();
5571 store
5574 .append(&id, &picture_message(Some(""), "shot.png"))
5575 .unwrap();
5576 store
5577 .append(&id, &Message::user("actually, summarise yesterday"))
5578 .unwrap();
5579 let listed = store.list().unwrap();
5580 let row = listed.iter().find(|s| s.id == id).expect("listed");
5581 assert_eq!(
5582 row.preview.as_str(),
5583 "actually, summarise yesterday",
5584 "the first empty row took the preview: {:?}",
5585 row.preview
5586 );
5587 }
5588
5589 #[test]
5597 fn a_bot_conversation_is_not_in_the_humans_list() {
5598 let dir = tempfile::tempdir().unwrap();
5599 let store = store(dir.path());
5600 let mine = store.new_id();
5601 store
5602 .append(&mine, &Message::user("the human asked this"))
5603 .unwrap();
5604 let theirs = store.bot_session("nox").unwrap();
5605 store
5606 .append(&theirs, &Message::user("the bot said this"))
5607 .unwrap();
5608
5609 let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
5610 assert_eq!(
5611 listed,
5612 vec![mine.clone()],
5613 "a bot's conversation left the sidebar alone"
5614 );
5615
5616 let archived: Vec<String> = store
5618 .list_with_archived()
5619 .unwrap()
5620 .into_iter()
5621 .map(|s| s.id)
5622 .collect();
5623 assert_eq!(archived, vec![mine], "`show archived` is not `show bots`");
5624 }
5625
5626 #[test]
5627 fn list_bots_groups_every_conversation_under_its_name() {
5628 let dir = tempfile::tempdir().unwrap();
5629 let store = store(dir.path());
5630 let first = store.bot_session("nox").unwrap();
5631 store.append(&first, &Message::user("one")).unwrap();
5632 for id in store.bot_sessions("nox").unwrap() {
5634 store.set_archived(&id, true).unwrap();
5635 }
5636 let second = store.bot_session("nox").unwrap();
5637 assert_ne!(
5638 first, second,
5639 "a cleared conversation is not the one reopened"
5640 );
5641 store.append(&second, &Message::user("two")).unwrap();
5642
5643 let other = store.bot_session("lux").unwrap();
5645 store.append(&other, &Message::user("three")).unwrap();
5646 let mine = store.new_id();
5647 store.append(&mine, &Message::user("four")).unwrap();
5648
5649 let bots = store.list_bots().unwrap();
5650 assert_eq!(bots.len(), 2, "one row per identity: {bots:?}");
5651 assert_eq!(bots[0].name, "lux", "newest activity first");
5652 let nox = bots.iter().find(|b| b.name == "nox").unwrap();
5653 assert_eq!(nox.sessions, 2, "both conversations counted");
5654 assert_eq!(nox.last_session, second, "the row opens the newest");
5655 assert_eq!(nox.messages, 1);
5656 assert!(
5657 !nox.archived,
5658 "one archived conversation is not a cleared bot"
5659 );
5660 }
5661
5662 #[test]
5667 fn two_sessions_in_the_same_millisecond_are_ordered_by_when_they_were_stored() {
5668 let dir = tempfile::tempdir().unwrap();
5669 let store = store(dir.path());
5670 store.list().unwrap(); let at = 1_796_297_799_945_i64;
5672 let rows = [
5674 ("1796297799945-11001-9", "bot:nox"),
5675 ("1796297799945-11001-10", "bot:nox"),
5676 ("1796297799945-11001-2", "native"),
5677 ("1796297799945-11001-11", "native"),
5678 ];
5679 store
5680 .with_db(|db| {
5681 for (id, origin) in rows {
5682 db.conn.execute(
5683 "INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
5684 VALUES (?1, ?2, ?3, 1, ?4)",
5685 params![id, at, at, origin],
5686 )?;
5687 }
5688 Ok(())
5689 })
5690 .unwrap();
5691
5692 let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
5693 assert_eq!(
5694 listed,
5695 ["1796297799945-11001-11", "1796297799945-11001-2"],
5696 "a tie is broken by which row was stored later, not by its text"
5697 );
5698
5699 let nox = store
5700 .list_bots()
5701 .unwrap()
5702 .into_iter()
5703 .find(|b| b.name == "nox")
5704 .expect("the bot's two conversations");
5705 assert_eq!(nox.sessions, 2);
5706 assert_eq!(
5707 nox.last_session, "1796297799945-11001-10",
5708 "the conversation opened second is the live one"
5709 );
5710 }
5711
5712 #[test]
5713 fn a_search_leaves_a_bots_conversation_out_unless_asked() {
5714 let dir = tempfile::tempdir().unwrap();
5715 let store = store(dir.path());
5716 let mine = store.new_id();
5717 store
5718 .append(&mine, &Message::user("the vault code is in the drawer"))
5719 .unwrap();
5720 let bots = store.bot_session("nox").unwrap();
5721 store
5722 .append(&bots, &Message::user("the vault code is on the lane"))
5723 .unwrap();
5724
5725 let found = store.search("vault", 10).unwrap();
5726 assert_eq!(
5727 found.len(),
5728 1,
5729 "the human's search found a bot's row: {found:?}"
5730 );
5731 assert_eq!(found[0].session_id, mine);
5732
5733 let asked = store.search_with("vault", 10, true).unwrap();
5734 assert_eq!(
5735 asked.len(),
5736 2,
5737 "`bots = true` is how a bot's rows are asked for"
5738 );
5739 assert!(asked.iter().any(|h| h.session_id == bots));
5740
5741 store
5743 .set_title(&bots, "never mention the vault", TitleSource::User)
5744 .unwrap();
5745 let named = store.search("never", 10).unwrap();
5746 assert!(
5747 named.is_empty(),
5748 "a bot's title answered the human's search: {named:?}"
5749 );
5750 let named = store.search_with("never", 10, true).unwrap();
5751 assert_eq!(named.len(), 1);
5752 }
5753
5754 #[test]
5755 fn a_title_is_never_claimed_for_a_bot() {
5756 let dir = tempfile::tempdir().unwrap();
5757 let store = store(dir.path());
5758 let mine = store.new_id();
5759 store.append(&mine, &Message::user("hello")).unwrap();
5760 store
5761 .set_title(&mine, "derived name", TitleSource::Derived)
5762 .unwrap();
5763 assert!(
5764 store.claim_title_upgrade(&mine).unwrap(),
5765 "a person's conversation may be named by a model"
5766 );
5767
5768 let bots = store.bot_session("nox").unwrap();
5769 store.append(&bots, &Message::user("hello")).unwrap();
5770 store
5771 .set_title(&bots, "derived name", TitleSource::Derived)
5772 .unwrap();
5773 assert!(
5774 !store.claim_title_upgrade(&bots).unwrap(),
5775 "a naming call per turn is the cost this rule exists to avoid"
5776 );
5777 }
5778
5779 #[test]
5780 fn a_bot_conversation_says_which_bot_it_belongs_to() {
5781 let dir = tempfile::tempdir().unwrap();
5782 let store = store(dir.path());
5783 let id = store.bot_session("nox").unwrap();
5784 store.append(&id, &Message::user("hello")).unwrap();
5785 assert_eq!(store.origin(&id).unwrap().as_deref(), Some("bot:nox"));
5789
5790 let info = SessionInfo {
5791 id,
5792 messages: 1,
5793 updated_ms: 0,
5794 preview: "hello".into(),
5795 title: None,
5796 origin: "bot:nox".into(),
5797 pinned: false,
5798 archived: false,
5799 cost: None,
5800 };
5801 assert_eq!(info.bot(), Some("nox"));
5802 assert!(info.is_bot());
5803 assert!(info.subagent().is_none());
5804 assert!(
5805 info.tagged_label().starts_with("[bot \u{b7} nox]"),
5806 "{}",
5807 info.tagged_label()
5808 );
5809
5810 let odd = SessionInfo {
5813 origin: "bot:a:b".to_string(),
5814 ..info
5815 };
5816 assert_eq!(odd.bot(), None);
5817 let empty = SessionInfo {
5819 origin: "bot:".to_string(),
5820 ..odd
5821 };
5822 assert_eq!(empty.bot(), None);
5823 }
5824
5825 #[test]
5831 fn a_flare_run_is_a_set_of_sessions_with_their_positions() {
5832 let dir = tempfile::tempdir().unwrap();
5833 let store = store(dir.path());
5834 let run = "f-1";
5835 let mut ids = Vec::new();
5838 for n in [2usize, 1, 3] {
5839 let id = store.new_id();
5840 store.begin_flare(&id, run, n).unwrap();
5841 store
5842 .append(&id, &Message::user(format!("flare {n} reading")))
5843 .unwrap();
5844 ids.push((n, id));
5845 }
5846
5847 let listed = store.flares_of(run).unwrap();
5848 assert_eq!(
5849 listed
5850 .iter()
5851 .filter_map(|s| s.flare().map(|f| f.n))
5852 .collect::<Vec<_>>(),
5853 vec![1, 2, 3],
5854 "the run's order is the lead's order, not the order they finished"
5855 );
5856 assert_eq!(listed[0].flare().unwrap().run, run);
5857 assert!(
5858 listed[0].tagged_label().starts_with("[flare \u{b7} f-1/1]"),
5859 "{}",
5860 listed[0].tagged_label()
5861 );
5862 assert!(listed[0].subagent().is_none());
5864 assert!(!listed[0].is_bot());
5865
5866 let other = store.new_id();
5868 store.begin_flare(&other, "f-2", 1).unwrap();
5869 assert_eq!(store.flares_of(run).unwrap().len(), 3);
5870
5871 let bad = store.new_id();
5873 assert!(store.begin_flare(&bad, "f:1", 1).is_err());
5874 let odd = SessionInfo {
5876 origin: "flare:run:two".into(),
5877 ..listed[0].clone()
5878 };
5879 assert!(odd.flare().is_none());
5880 assert!(SessionInfo {
5881 origin: "flare::1".into(),
5882 ..listed[0].clone()
5883 }
5884 .flare()
5885 .is_none());
5886 }
5887
5888 #[test]
5889 fn a_search_leaves_a_flares_transcript_out_unless_asked() {
5890 let dir = tempfile::tempdir().unwrap();
5891 let store = store(dir.path());
5892 let mine = store.new_id();
5893 store
5894 .append(&mine, &Message::user("the retry loop is in worker.rs"))
5895 .unwrap();
5896 let flare = store.new_id();
5897 store.begin_flare(&flare, "f-9", 1).unwrap();
5898 store
5899 .append(&flare, &Message::user("the retry loop is in pool.rs"))
5900 .unwrap();
5901
5902 let found = store.search("retry", 10).unwrap();
5903 assert_eq!(found.len(), 1, "the human found a flare's row: {found:?}");
5904 assert_eq!(found[0].session_id, mine);
5905
5906 let asked = store.search_with("retry", 10, true).unwrap();
5907 assert_eq!(
5908 asked.len(),
5909 2,
5910 "`children = true` is how those rows are asked for"
5911 );
5912 }
5913
5914 #[test]
5915 fn a_flare_is_never_named_by_a_model() {
5916 let dir = tempfile::tempdir().unwrap();
5917 let store = store(dir.path());
5918 let id = store.new_id();
5919 store.begin_flare(&id, "f-3", 1).unwrap();
5920 store.append(&id, &Message::user("reading")).unwrap();
5921 store
5922 .set_title(&id, "derived name", TitleSource::Derived)
5923 .unwrap();
5924 assert!(
5925 !store.claim_title_upgrade(&id).unwrap(),
5926 "a transient worker does not get a paid naming call"
5927 );
5928 }
5929
5930 fn refuse(store: &SessionStore, on: &str) {
5933 store
5934 .with_db(|db| {
5935 db.conn.execute_batch(&format!(
5936 "CREATE TRIGGER refused {on} BEGIN SELECT RAISE(ABORT, 'refused by the test'); END"
5937 ))?;
5938 Ok(())
5939 })
5940 .unwrap();
5941 }
5942
5943 #[test]
5947 fn a_goal_clear_that_fails_on_its_last_delete_clears_nothing() {
5948 let dir = tempfile::tempdir().unwrap();
5949 let store = store(dir.path());
5950 let id = store.new_id();
5951 let goal =
5952 crate::goals::Goal::new(&id, "ship the release", None, Some(5), 1_700_000_000_000);
5953 store.set_goal(&goal).unwrap();
5954 store
5955 .record_goal_turn(
5956 &id,
5957 &crate::goals::Judgement {
5958 turn: 1,
5959 verdict: "continue".into(),
5960 why: None,
5961 at_ms: 1_700_000_000_001,
5962 },
5963 )
5964 .unwrap();
5965 refuse(&store, "BEFORE DELETE ON goal_turns");
5966
5967 assert!(
5968 store.clear_goal(&id).is_err(),
5969 "the second delete was refused, so the clear cannot report itself as done"
5970 );
5971 assert!(
5972 store.goal(&id).unwrap().is_some(),
5973 "the goal went on its own, leaving its judgements for the next goal to inherit"
5974 );
5975 assert_eq!(
5976 store.goal_turns(&id).unwrap().len(),
5977 1,
5978 "the judgements of a goal that was not cleared"
5979 );
5980 }
5981
5982 #[test]
5986 fn a_goal_that_cannot_be_saved_does_not_leave_a_session_behind() {
5987 let dir = tempfile::tempdir().unwrap();
5988 let store = store(dir.path());
5989 let id = store.new_id();
5990 refuse(&store, "BEFORE INSERT ON goals");
5991
5992 let goal = crate::goals::Goal::new(&id, "ship the release", None, None, 1_700_000_000_000);
5993 assert!(store.set_goal(&goal).is_err(), "the goal write was refused");
5994
5995 let rows: i64 = store
5996 .with_db(|db| {
5997 Ok(db.conn.query_row(
5998 "SELECT COUNT(*) FROM sessions WHERE id = ?1",
5999 params![id],
6000 |r| r.get(0),
6001 )?)
6002 })
6003 .unwrap();
6004 assert_eq!(
6005 rows, 0,
6006 "the session row outlived the goal it was written for"
6007 );
6008 }
6009
6010 #[test]
6016 fn a_ruling_that_cannot_be_logged_does_not_land() {
6017 let dir = tempfile::tempdir().unwrap();
6018 let store = store(dir.path());
6019 let id = store.new_id();
6020 store.append(&id, &Message::user("run it")).unwrap();
6021 store
6022 .record_pending(
6023 &id,
6024 1,
6025 &[crate::approvals::Pending::new(
6026 "c1",
6027 "shell",
6028 "rm -rf build".into(),
6029 "{}".into(),
6030 )],
6031 )
6032 .unwrap();
6033 refuse(&store, "BEFORE INSERT ON approval_log");
6034
6035 assert!(store
6036 .decide_pending(&id, 1, 0, &crate::approvals::Decision::Allow, "user")
6037 .is_err());
6038
6039 let rows = store.pending_calls(&id).unwrap();
6040 assert_eq!(rows.len(), 1);
6041 assert_eq!(
6042 rows[0].decision, None,
6043 "the answer landed without the log row that says who gave it"
6044 );
6045 }
6046
6047 #[test]
6050 fn a_session_a_person_named_can_be_named_again() {
6051 let dir = tempfile::tempdir().unwrap();
6052 let store = store(dir.path());
6053 let id = store.new_id();
6054 store.append(&id, &Message::user("hello")).unwrap();
6055 store.rename(&id, "first name").unwrap();
6056 store.rename(&id, "second name").unwrap();
6057 let seen = store
6058 .with_db(|db| {
6059 Ok(db.conn.query_row(
6060 "SELECT title, title_source FROM sessions WHERE id = ?1",
6061 [&id],
6062 |r| {
6063 Ok((
6064 r.get::<_, Option<String>>(0)?,
6065 r.get::<_, Option<String>>(1)?,
6066 ))
6067 },
6068 )?)
6069 })
6070 .unwrap();
6071 assert_eq!(
6072 seen,
6073 (Some("second name".into()), Some("user".into())),
6074 "the second rename is the title, and it is still a person's"
6075 );
6076 }
6077
6078 #[test]
6084 fn a_migration_that_fails_halfway_leaves_nothing_behind() {
6085 let dir = tempfile::tempdir().unwrap();
6086 let path = dir.path().join("sessions");
6087 let id = {
6088 let store = SessionStore::new(path.clone());
6089 let id = store.new_id();
6090 store.append(&id, &Message::user("hello")).unwrap();
6091 store.rename(&id, "typed by a person").unwrap();
6092 id
6093 };
6094 let db = path.join("sessions.db");
6095 {
6096 let conn = Connection::open(&db).unwrap();
6097 conn.execute_batch(
6099 "ALTER TABLE sessions DROP COLUMN title_source;
6100 ALTER TABLE sessions DROP COLUMN title_note;
6101 CREATE TRIGGER no_backfill BEFORE UPDATE OF title_source ON sessions
6102 BEGIN SELECT RAISE(ABORT, 'the backfill cannot run'); END;",
6103 )
6104 .unwrap();
6105 }
6106
6107 let refused = SessionStore::new(path.clone()).list();
6108 assert!(
6109 refused.is_err(),
6110 "the migration cannot finish, so opening the store must fail"
6111 );
6112
6113 {
6114 let conn = Connection::open(&db).unwrap();
6115 conn.execute_batch("DROP TRIGGER no_backfill").unwrap();
6116 }
6117 let store = SessionStore::new(path.clone());
6118 let source: Option<String> = store
6119 .with_db(|db| {
6120 Ok(db.conn.query_row(
6121 "SELECT title_source FROM sessions WHERE id = ?1",
6122 [&id],
6123 |r| r.get(0),
6124 )?)
6125 })
6126 .unwrap();
6127 assert_eq!(
6128 source.as_deref(),
6129 Some("user"),
6130 "a title that existed before the column is a person's — the half-run migration left \
6131 it unranked, so the naming pass could have relabelled it"
6132 );
6133 }
6134}