1use crate::error::{Error, Result};
15use crate::message::{Message, Role};
16use rusqlite::{params, Connection, OptionalExtension};
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 db.conn
831 .execute(
832 "INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
833 VALUES (?1, ?2, ?2, 0, 'native')
834 ON CONFLICT(id) DO NOTHING",
835 params![goal.session, goal.created_ms],
836 )
837 .map_err(|e| Error::Session(format!("could not ensure the session row: {e}")))?;
838 db.conn
839 .execute(
840 "INSERT INTO goals
841 (session_id, text, gate, budget, turns, state, note, garbage,
842 created_ms, updated_ms)
843 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
844 ON CONFLICT(session_id) DO UPDATE SET
845 text = excluded.text, gate = excluded.gate, budget = excluded.budget,
846 turns = excluded.turns, state = excluded.state, note = excluded.note,
847 garbage = excluded.garbage, updated_ms = excluded.updated_ms",
848 params![
849 goal.session,
850 goal.text,
851 goal.gate,
852 goal.budget as i64,
853 goal.turns as i64,
854 goal.state.as_str(),
855 goal.note,
856 goal.garbage as i64,
857 goal.created_ms,
858 goal.updated_ms,
859 ],
860 )
861 .map_err(|e| Error::Session(format!("could not save the goal: {e}")))?;
862 Ok(())
863 })
864 }
865
866 pub fn goal(&self, id: &str) -> Result<Option<crate::goals::Goal>> {
868 validate_id(id)?;
869 self.with_db(|db| {
870 let found = db
871 .conn
872 .query_row(
873 "SELECT text, gate, budget, turns, state, note, garbage, created_ms, updated_ms
874 FROM goals WHERE session_id = ?1",
875 params![id],
876 |r| {
877 Ok(crate::goals::Goal {
878 session: id.to_string(),
879 text: r.get(0)?,
880 gate: r.get(1)?,
881 budget: r.get::<_, i64>(2)? as u32,
882 turns: r.get::<_, i64>(3)? as u32,
883 state: goal_state(r.get::<_, String>(4)?),
884 note: r.get(5)?,
885 garbage: r.get::<_, i64>(6)? != 0,
886 created_ms: r.get(7)?,
887 updated_ms: r.get(8)?,
888 })
889 },
890 )
891 .optional()?;
892 Ok(found)
893 })
894 }
895
896 pub fn clear_goal(&self, id: &str) -> Result<()> {
898 validate_id(id)?;
899 self.with_db(|db| {
900 db.conn
901 .execute("DELETE FROM goals WHERE session_id = ?1", params![id])
902 .map_err(|e| Error::Session(format!("could not clear the goal: {e}")))?;
903 db.conn
904 .execute("DELETE FROM goal_turns WHERE session_id = ?1", params![id])
905 .map_err(|e| Error::Session(format!("could not clear the judgements: {e}")))?;
906 Ok(())
907 })
908 }
909
910 pub fn record_goal_turn(&self, id: &str, judgement: &crate::goals::Judgement) -> Result<()> {
912 validate_id(id)?;
913 self.with_db(|db| {
914 db.conn
915 .execute(
916 "INSERT INTO goal_turns (session_id, turn, verdict, why, at_ms)
917 VALUES (?1, ?2, ?3, ?4, ?5)
918 ON CONFLICT(session_id, turn) DO UPDATE SET
919 verdict = excluded.verdict, why = excluded.why, at_ms = excluded.at_ms",
920 params![
921 id,
922 judgement.turn as i64,
923 judgement.verdict,
924 judgement.why,
925 judgement.at_ms,
926 ],
927 )
928 .map_err(|e| Error::Session(format!("could not record the judgement: {e}")))?;
929 Ok(())
930 })
931 }
932
933 pub fn goal_turns(&self, id: &str) -> Result<Vec<crate::goals::Judgement>> {
935 validate_id(id)?;
936 self.with_db(|db| {
937 let mut stmt = db
938 .conn
939 .prepare(
940 "SELECT turn, verdict, why, at_ms FROM goal_turns
941 WHERE session_id = ?1 ORDER BY turn",
942 )
943 .map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
944 let rows = stmt
945 .query_map(params![id], |r| {
946 Ok(crate::goals::Judgement {
947 turn: r.get::<_, i64>(0)? as u32,
948 verdict: r.get(1)?,
949 why: r.get(2)?,
950 at_ms: r.get(3)?,
951 })
952 })
953 .map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
954 Ok(rows.flatten().collect())
955 })
956 }
957
958 pub fn live_goals(&self) -> Result<Vec<crate::goals::Goal>> {
963 self.with_db(|db| {
964 let mut stmt = db
965 .conn
966 .prepare(
967 "SELECT session_id, text, gate, budget, turns, state, note, garbage,
968 created_ms, updated_ms
969 FROM goals WHERE state IN ('active', 'paused') ORDER BY updated_ms DESC",
970 )
971 .map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
972 let rows = stmt
973 .query_map([], |r| {
974 Ok(crate::goals::Goal {
975 session: r.get(0)?,
976 text: r.get(1)?,
977 gate: r.get(2)?,
978 budget: r.get::<_, i64>(3)? as u32,
979 turns: r.get::<_, i64>(4)? as u32,
980 state: goal_state(r.get::<_, String>(5)?),
981 note: r.get(6)?,
982 garbage: r.get::<_, i64>(7)? != 0,
983 created_ms: r.get(8)?,
984 updated_ms: r.get(9)?,
985 })
986 })
987 .map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
988 Ok(rows.flatten().collect())
989 })
990 }
991
992 pub fn is_busy(&self, id: &str) -> bool {
998 match self.try_lock(id) {
999 Ok(Some(lock)) => {
1000 drop(lock);
1001 false
1002 }
1003 Ok(None) => true,
1004 Err(_) => false,
1007 }
1008 }
1009
1010 pub fn exists(&self, id: &str) -> bool {
1011 if validate_id(id).is_err() {
1012 return false;
1013 }
1014 self.with_db(|db| {
1015 let found: Option<i64> = db
1016 .conn
1017 .query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
1018 r.get(0)
1019 })
1020 .optional()?;
1021 Ok(found.is_some())
1022 })
1023 .unwrap_or(false)
1024 }
1025
1026 pub fn record_pending(
1032 &self,
1033 id: &str,
1034 seq: i64,
1035 calls: &[crate::approvals::Pending],
1036 ) -> Result<()> {
1037 self.record_pending_at(id, seq, 0, calls)
1038 }
1039
1040 pub fn record_pending_at(
1046 &self,
1047 id: &str,
1048 seq: i64,
1049 ord: usize,
1050 calls: &[crate::approvals::Pending],
1051 ) -> Result<()> {
1052 validate_id(id)?;
1053 self.with_db(|db| {
1054 let tx = db.conn.transaction()?;
1055 for (offset, call) in calls.iter().enumerate() {
1056 tx.execute(
1057 "INSERT INTO approvals
1058 (session_id, seq, ord, call_id, tool, summary, args, decision, decided_ms)
1059 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, NULL)
1060 ON CONFLICT(session_id, seq, ord) DO NOTHING",
1061 params![
1062 id,
1063 seq,
1064 (ord + offset) as i64,
1065 call.call_id,
1066 call.tool,
1067 call.summary,
1068 call.args
1069 ],
1070 )?;
1071 }
1072 tx.commit()?;
1073 Ok(())
1074 })
1075 }
1076
1077 pub fn pending_calls(&self, id: &str) -> Result<Vec<crate::approvals::PendingCall>> {
1080 validate_id(id)?;
1081 self.with_db(|db| {
1082 let mut stmt = db.conn.prepare(
1083 "SELECT seq, ord, call_id, tool, summary, args, decision, decided_ms, by
1084 FROM approvals WHERE session_id = ?1 ORDER BY seq, ord",
1085 )?;
1086 let rows = stmt
1087 .query_map(params![id], |r| {
1088 let stored: Option<String> = r.get(6)?;
1089 Ok(crate::approvals::PendingCall {
1090 seq: r.get(0)?,
1091 ord: r.get::<_, i64>(1)? as usize,
1092 call: crate::approvals::Pending::new(
1093 r.get::<_, String>(2)?,
1094 r.get::<_, String>(3)?,
1095 r.get::<_, String>(4)?,
1096 r.get::<_, String>(5)?,
1097 ),
1098 decision: stored.as_deref().map(crate::approvals::Decision::parse),
1099 decided_ms: r.get(7)?,
1100 by: r.get(8)?,
1101 })
1102 })?
1103 .collect::<std::result::Result<Vec<_>, _>>()?;
1104 Ok(rows)
1105 })
1106 }
1107
1108 pub fn decide_pending(
1112 &self,
1113 id: &str,
1114 seq: i64,
1115 ord: usize,
1116 decision: &crate::approvals::Decision,
1117 by: &str,
1118 ) -> Result<()> {
1119 validate_id(id)?;
1120 let Some(stored) = decision.store() else {
1123 return Ok(());
1124 };
1125 let now = now_ms() as i64;
1126 let changed = self.with_db(|db| {
1127 let changed = db.conn.execute(
1128 "UPDATE approvals SET decision = ?4, decided_ms = ?5, by = ?6
1129 WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
1130 params![&id, seq, ord as i64, &stored, now, by],
1131 )?;
1132 if changed > 0 {
1136 db.conn.execute(
1137 "INSERT INTO approval_log
1138 (session_id, at_ms, call_id, tool, summary, decision, by)
1139 SELECT session_id, ?4, call_id, tool, summary, ?5, ?6 FROM approvals
1140 WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
1141 params![&id, seq, ord as i64, now, &stored, by],
1142 )?;
1143 }
1144 Ok(changed)
1145 })?;
1146 if changed == 0 {
1147 return Err(Error::Session(format!(
1148 "{id}: no tool call recorded at message {seq}, position {ord}"
1149 )));
1150 }
1151 Ok(())
1152 }
1153
1154 pub fn log_decision(
1160 &self,
1161 id: &str,
1162 call: &crate::approvals::Pending,
1163 decision: &crate::approvals::Decision,
1164 by: &str,
1165 ) -> Result<()> {
1166 validate_id(id)?;
1167 let Some(stored) = decision.store() else {
1168 return Ok(());
1169 };
1170 let now = now_ms() as i64;
1171 self.with_db(|db| {
1172 Ok(db.conn.execute(
1173 "INSERT INTO approval_log (session_id, at_ms, call_id, tool, summary, decision, by)
1174 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1175 params![
1176 id,
1177 now,
1178 &call.call_id,
1179 &call.tool,
1180 &call.summary,
1181 &stored,
1182 by
1183 ],
1184 )?)
1185 })?;
1186 Ok(())
1187 }
1188
1189 pub fn approval_log(&self, id: &str) -> Result<Vec<crate::approvals::Ruling>> {
1195 validate_id(id)?;
1196 self.with_db(|db| {
1197 let mut stmt = db.conn.prepare(
1198 "SELECT at_ms, call_id, tool, summary, decision, by FROM approval_log
1199 WHERE session_id = ?1 ORDER BY at_ms, rowid",
1200 )?;
1201 let rows = stmt
1202 .query_map(params![id], |r| {
1203 Ok(crate::approvals::Ruling {
1204 at_ms: r.get(0)?,
1205 call_id: r.get(1)?,
1206 tool: r.get(2)?,
1207 summary: r.get(3)?,
1208 decision: crate::approvals::Decision::parse(&r.get::<_, String>(4)?),
1209 by: r.get(5)?,
1210 })
1211 })?
1212 .collect::<std::result::Result<Vec<_>, _>>()?;
1213 Ok(rows)
1214 })
1215 }
1216
1217 pub fn clear_pending(&self, id: &str) -> Result<usize> {
1220 validate_id(id)?;
1221 self.with_db(|db| {
1222 Ok(db
1223 .conn
1224 .execute("DELETE FROM approvals WHERE session_id = ?1", params![id])?)
1225 })
1226 }
1227
1228 pub fn clear_call(&self, id: &str, call_id: &str) -> Result<usize> {
1231 validate_id(id)?;
1232 self.with_db(|db| {
1233 Ok(db.conn.execute(
1234 "DELETE FROM approvals WHERE session_id = ?1 AND call_id = ?2",
1235 params![id, call_id],
1236 )?)
1237 })
1238 }
1239
1240 pub fn last_seq(&self, id: &str) -> Result<i64> {
1242 validate_id(id)?;
1243 self.with_db(|db| {
1244 Ok(db.conn.query_row(
1245 "SELECT COALESCE(MAX(seq), -1) FROM messages WHERE session_id = ?1",
1246 params![id],
1247 |r| r.get(0),
1248 )?)
1249 })
1250 }
1251
1252 pub fn set_tool_outcome(&self, id: &str, call_id: &str, is_error: bool) -> Result<()> {
1259 validate_id(id)?;
1260 let session = id.to_string();
1261 let call = call_id.to_string();
1262 self.with_db(|db| {
1263 db.conn
1264 .execute(
1265 "INSERT INTO tool_outcomes (session_id, call_id, is_error) VALUES (?1, ?2, ?3)
1266 ON CONFLICT (session_id, call_id) DO UPDATE SET is_error = excluded.is_error",
1267 rusqlite::params![session, call, is_error as i64],
1268 )
1269 .map_err(|e| Error::Session(e.to_string()))?;
1270 Ok(())
1271 })
1272 }
1273
1274 pub fn tool_outcomes(&self, id: &str) -> Result<std::collections::HashMap<String, bool>> {
1277 validate_id(id)?;
1278 let session = id.to_string();
1279 self.with_db(|db| {
1280 let mut stmt = db
1281 .conn
1282 .prepare("SELECT call_id, is_error FROM tool_outcomes WHERE session_id = ?1")
1283 .map_err(|e| Error::Session(e.to_string()))?;
1284 let rows = stmt
1285 .query_map(rusqlite::params![session], |row| {
1286 Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? != 0))
1287 })
1288 .map_err(|e| Error::Session(e.to_string()))?;
1289 let mut out = std::collections::HashMap::new();
1290 for row in rows {
1291 let (call, is_error) = row.map_err(|e| Error::Session(e.to_string()))?;
1292 out.insert(call, is_error);
1293 }
1294 Ok(out)
1295 })
1296 }
1297
1298 pub fn append(&self, id: &str, message: &Message) -> Result<()> {
1299 self.append_seq(id, message).map(|_| ())
1300 }
1301
1302 pub fn append_seq(&self, id: &str, message: &Message) -> Result<i64> {
1306 validate_id(id)?;
1307 let now = now_ms() as i64;
1308 let body = serde_json::to_string(message).map_err(|e| Error::Session(e.to_string()))?;
1309 let role = role_name(message.role);
1310 let preview = (message.role == Role::User)
1313 .then(|| {
1314 message
1315 .content
1316 .as_deref()
1317 .map(|t| t.split_whitespace().collect::<Vec<_>>().join(" "))
1318 .map(|t| t.chars().take(60).collect::<String>())
1319 })
1320 .flatten()
1321 .filter(|p| !p.trim().is_empty());
1325
1326 self.with_db(|db| {
1327 let tx = db.conn.transaction()?;
1328 tx.execute(
1331 "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
1332 VALUES (?1, ?2, ?2, NULL, NULL, 0, 'native')
1333 ON CONFLICT(id) DO NOTHING",
1334 params![id, now],
1335 )?;
1336 let seq: i64 = tx.query_row(
1337 "SELECT COALESCE(MAX(seq), -1) + 1 FROM messages WHERE session_id = ?1",
1338 params![id],
1339 |r| r.get(0),
1340 )?;
1341 tx.execute(
1342 "INSERT INTO messages (session_id, seq, at_ms, role, body)
1343 VALUES (?1, ?2, ?3, ?4, ?5)",
1344 params![id, seq, now, role, body],
1345 )?;
1346 tx.execute(
1347 "UPDATE sessions
1348 SET updated_ms = ?2,
1349 messages = messages + 1,
1350 preview = COALESCE(preview, ?3)
1351 WHERE id = ?1",
1352 params![id, now, preview],
1353 )?;
1354 if db.fts {
1355 tx.execute(
1356 "INSERT INTO messages_fts (session_id, seq, content) VALUES (?1, ?2, ?3)",
1357 params![id, seq, searchable(message)],
1358 )?;
1359 }
1360 tx.commit()?;
1361 Ok(seq)
1362 })
1363 }
1364
1365 pub fn begin_subagent(&self, id: &str, parent: &str, route: &str) -> Result<()> {
1370 validate_id(parent)?;
1371 self.begin_row(id, &format!("{SUBAGENT_ORIGIN}{parent}:{route}"))
1372 }
1373
1374 pub fn begin_flare(&self, id: &str, run: &str, n: usize) -> Result<()> {
1379 if run.is_empty() || run.contains(':') {
1380 return Err(Error::Config(format!(
1381 "a flare run id is one word without a colon, not {run:?}"
1382 )));
1383 }
1384 self.begin_row(id, &format!("{FLARE_ORIGIN}{run}:{n}"))
1385 }
1386
1387 pub fn begin_flare_run(
1389 &self,
1390 id: &str,
1391 task: &str,
1392 routes: &[String],
1393 jobs: usize,
1394 parent: &str,
1395 ) -> Result<()> {
1396 let task: String = task.chars().take(500).collect();
1397 self.with_db(|db| {
1398 db.conn.execute(
1399 "INSERT INTO flare_runs (id, task, state, routes, jobs, parent, started_ms)
1400 VALUES (?1, ?2, 'running', ?3, ?4, ?5, ?6)",
1401 params![
1402 id,
1403 task,
1404 routes.join(","),
1405 jobs as i64,
1406 parent,
1407 now_ms() as i64
1408 ],
1409 )?;
1410 Ok(())
1411 })
1412 }
1413
1414 pub fn flare_job_running(&self, run: &str, n: usize, route: &str, session: &str) -> Result<()> {
1416 self.with_db(|db| {
1417 db.conn.execute(
1418 "INSERT INTO flare_jobs (run_id, n, route, session_id, state)
1419 VALUES (?1, ?2, ?3, ?4, 'running')
1420 ON CONFLICT(run_id, n) DO UPDATE SET
1421 route = excluded.route, session_id = excluded.session_id,
1422 state = 'running'",
1423 params![run, n as i64, route, session],
1424 )?;
1425 Ok(())
1426 })
1427 }
1428
1429 #[allow(clippy::too_many_arguments)]
1431 pub fn flare_job_done(&self, done: &FlareJobRow) -> Result<()> {
1432 self.with_db(|db| {
1433 db.conn.execute(
1434 "INSERT INTO flare_jobs (run_id, n, route, session_id, state, prompt_tokens,
1435 completion_tokens, iterations, why)
1436 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
1437 ON CONFLICT(run_id, n) DO UPDATE SET
1438 route = excluded.route, session_id = excluded.session_id,
1439 state = excluded.state, prompt_tokens = excluded.prompt_tokens,
1440 completion_tokens = excluded.completion_tokens,
1441 iterations = excluded.iterations, why = excluded.why",
1442 params![
1443 done.run_id,
1444 done.n as i64,
1445 done.route,
1446 done.session_id,
1447 done.state,
1448 done.prompt_tokens.map(|v| v as i64),
1449 done.completion_tokens.map(|v| v as i64),
1450 done.iterations as i64,
1451 done.why,
1452 ],
1453 )?;
1454 Ok(())
1455 })
1456 }
1457
1458 #[allow(clippy::too_many_arguments)]
1460 pub fn finish_flare_run(
1461 &self,
1462 id: &str,
1463 state: &str,
1464 prompt: Option<u64>,
1465 completion: Option<u64>,
1466 iterations: usize,
1467 ) -> Result<()> {
1468 self.with_db(|db| {
1469 db.conn.execute(
1470 "UPDATE flare_runs SET state = ?2, finished_ms = ?3, prompt_tokens = ?4,
1471 completion_tokens = ?5, iterations = ?6
1472 WHERE id = ?1",
1473 params![
1474 id,
1475 state,
1476 now_ms() as i64,
1477 prompt.map(|v| v as i64),
1478 completion.map(|v| v as i64),
1479 iterations as i64
1480 ],
1481 )?;
1482 Ok(())
1483 })
1484 }
1485
1486 pub fn cancel_flare_run(&self, id: &str) -> Result<bool> {
1489 self.with_db(|db| {
1490 let n = db.conn.execute(
1491 "UPDATE flare_runs SET cancel_requested = 1 WHERE id = ?1",
1492 params![id],
1493 )?;
1494 Ok(n > 0)
1495 })
1496 }
1497
1498 pub fn flare_cancel_requested(&self, id: &str) -> Result<bool> {
1500 self.with_db(|db| {
1501 let mut stmt = db
1502 .conn
1503 .prepare("SELECT cancel_requested FROM flare_runs WHERE id = ?1")?;
1504 let mut rows = stmt.query(params![id])?;
1505 match rows.next()? {
1506 Some(r) => Ok(r.get::<_, i64>(0)? != 0),
1507 None => Ok(false),
1508 }
1509 })
1510 }
1511
1512 pub fn flare_runs(&self, limit: usize) -> Result<Vec<FlareRunRow>> {
1514 let limit = limit.clamp(1, 200) as i64;
1515 self.with_db(|db| {
1516 let mut stmt = db.conn.prepare(
1517 "SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
1518 prompt_tokens, completion_tokens, iterations
1519 FROM flare_runs ORDER BY started_ms DESC LIMIT ?1",
1520 )?;
1521 let rows = stmt.query_map(params![limit], run_row)?;
1522 Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
1523 })
1524 }
1525
1526 pub fn flare_run(&self, id: &str) -> Result<Option<(FlareRunRow, Vec<FlareJobRow>)>> {
1528 self.with_db(|db| {
1529 let mut stmt = db.conn.prepare(
1530 "SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
1531 prompt_tokens, completion_tokens, iterations
1532 FROM flare_runs WHERE id = ?1",
1533 )?;
1534 let mut rows = stmt.query(params![id])?;
1535 let Some(row) = rows.next()? else {
1536 return Ok(None);
1537 };
1538 let run = run_row(row)?;
1539 let mut stmt = db.conn.prepare(
1540 "SELECT n, route, session_id, state, prompt_tokens, completion_tokens,
1541 iterations, why
1542 FROM flare_jobs WHERE run_id = ?1 ORDER BY n",
1543 )?;
1544 let jobs = stmt
1545 .query_map(params![id], |r| {
1546 Ok(FlareJobRow {
1547 run_id: id.to_string(),
1548 n: r.get::<_, i64>(0)? as usize,
1549 route: r.get(1)?,
1550 session_id: r.get(2)?,
1551 state: r.get(3)?,
1552 prompt_tokens: r.get::<_, Option<i64>>(4)?.map(|v| v as u64),
1553 completion_tokens: r.get::<_, Option<i64>>(5)?.map(|v| v as u64),
1554 iterations: r.get::<_, Option<i64>>(6)?.unwrap_or(0).max(0) as usize,
1555 why: r.get(7)?,
1556 })
1557 })?
1558 .collect::<std::result::Result<Vec<_>, _>>()?;
1559 Ok(Some((run, jobs)))
1560 })
1561 }
1562
1563 pub fn flares_of(&self, run: &str) -> Result<Vec<SessionInfo>> {
1568 let prefix = format!("{FLARE_ORIGIN}{run}:");
1569 let mut out: Vec<SessionInfo> = self
1570 .list_rows(true, true)?
1571 .into_iter()
1572 .filter(|s| s.origin.starts_with(&prefix))
1573 .collect();
1574 out.sort_by_key(|s| s.flare().map_or(0, |f| f.n));
1575 Ok(out)
1576 }
1577
1578 pub const API_ORIGIN: &str = "api";
1581
1582 pub fn begin_api(&self, id: &str) -> Result<()> {
1588 self.begin_row(id, Self::API_ORIGIN)
1589 }
1590
1591 pub fn origin(&self, id: &str) -> Result<Option<String>> {
1598 validate_id(id)?;
1599 self.with_db(|db| {
1600 let found = db
1601 .conn
1602 .query_row(
1603 "SELECT origin FROM sessions WHERE id = ?1",
1604 params![id],
1605 |r| r.get::<_, String>(0),
1606 )
1607 .map(Some)
1608 .or_else(|e| match e {
1609 rusqlite::Error::QueryReturnedNoRows => Ok(None),
1610 other => Err(other),
1611 })?;
1612 Ok(found)
1613 })
1614 }
1615
1616 pub fn begin_bot(&self, id: &str, name: &str) -> Result<()> {
1623 self.begin_row(id, &format!("{BOT_ORIGIN}{name}"))
1624 }
1625
1626 pub fn bot_session(&self, name: &str) -> Result<String> {
1633 let origin = format!("{BOT_ORIGIN}{name}");
1634 for info in self.list_rows(true, true)? {
1635 if info.origin == origin && !info.archived {
1636 return Ok(info.id);
1637 }
1638 }
1639 let id = self.new_id();
1640 self.begin_bot(&id, name)?;
1641 Ok(id)
1642 }
1643
1644 pub fn bot_sessions(&self, name: &str) -> Result<Vec<String>> {
1647 let origin = format!("{BOT_ORIGIN}{name}");
1648 Ok(self
1649 .list_rows(true, true)?
1650 .into_iter()
1651 .filter(|info| info.origin == origin && !info.archived)
1652 .map(|info| info.id)
1653 .collect())
1654 }
1655
1656 fn begin_row(&self, id: &str, origin: &str) -> Result<()> {
1658 validate_id(id)?;
1659 let now = now_ms() as i64;
1660 self.with_db(|db| {
1661 db.conn.execute(
1662 "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
1663 VALUES (?1, ?2, ?2, NULL, NULL, 0, ?3)
1664 ON CONFLICT(id) DO NOTHING",
1665 params![id, now, origin],
1666 )?;
1667 Ok(())
1668 })
1669 }
1670
1671 pub fn prune_api_sessions(&self, cutoff_ms: u64) -> Result<usize> {
1678 let stale: Vec<String> = self
1679 .list()?
1680 .into_iter()
1681 .filter(|s| s.origin == Self::API_ORIGIN && !s.pinned && s.updated_ms < cutoff_ms)
1682 .map(|s| s.id)
1683 .collect();
1684 let mut pruned = 0usize;
1685 for id in stale {
1686 match self.delete(&id) {
1687 Ok(()) => pruned += 1,
1688 Err(Error::Session(_)) => {}
1690 Err(e) => return Err(e),
1691 }
1692 }
1693 Ok(pruned)
1694 }
1695
1696 pub fn load_records(&self, id: &str) -> Result<Vec<Record>> {
1700 validate_id(id)?;
1701 if !self.exists(id) {
1705 return Err(Error::Session(format!("no such session {id:?}")));
1706 }
1707 self.with_db(|db| {
1708 let mut stmt = db.conn.prepare(
1709 "SELECT seq, at_ms, body FROM messages WHERE session_id = ?1 ORDER BY seq",
1710 )?;
1711 let rows = stmt.query_map(params![id], |r| {
1712 Ok((
1713 r.get::<_, i64>(0)?,
1714 r.get::<_, i64>(1)?,
1715 r.get::<_, String>(2)?,
1716 ))
1717 })?;
1718 let mut out = Vec::new();
1719 for row in rows {
1720 let (seq, at, body) = row?;
1721 let mut message: Message = serde_json::from_str(&body)
1722 .map_err(|e| Error::Session(format!("{id}:{seq}: {e}")))?;
1723 message.seq = Some(seq.max(0) as u64);
1726 out.push(Record {
1727 ts: at.max(0) as u64,
1728 message,
1729 });
1730 }
1731 Ok(out)
1732 })
1733 }
1734
1735 #[allow(clippy::unnecessary_wraps)] pub fn load(&self, id: &str) -> Result<Vec<Message>> {
1737 Ok(self
1738 .load_records(id)?
1739 .into_iter()
1740 .map(|r| r.message)
1741 .collect())
1742 }
1743
1744 pub fn title(&self, id: &str) -> Result<Option<String>> {
1746 validate_id(id)?;
1747 self.with_db(|db| {
1748 let title: Option<Option<String>> = db
1749 .conn
1750 .query_row(
1751 "SELECT title FROM sessions WHERE id = ?1",
1752 params![id],
1753 |r| r.get(0),
1754 )
1755 .optional()?;
1756 Ok(title.flatten())
1757 })
1758 }
1759
1760 pub fn rename(&self, id: &str, title: &str) -> Result<()> {
1767 validate_id(id)?;
1768 let title = title.trim();
1769 if title.is_empty() {
1770 return Err(Error::Session("title is empty".into()));
1771 }
1772 if title.chars().count() > MAX_TITLE_CHARS {
1773 return Err(Error::Session(format!(
1774 "title is longer than {MAX_TITLE_CHARS} characters"
1775 )));
1776 }
1777 if title.chars().any(char::is_control) {
1778 return Err(Error::Session("title contains control characters".into()));
1779 }
1780 let landed = self.set_title(id, title, TitleSource::User)?;
1781 if !landed {
1782 return Err(Error::Session(format!("no such session {id:?}")));
1783 }
1784 Ok(())
1785 }
1786
1787 pub fn set_title(&self, id: &str, title: &str, source: TitleSource) -> Result<bool> {
1794 validate_id(id)?;
1795 self.with_db(|db| {
1796 let n = db.conn.execute(
1797 "UPDATE sessions SET title = ?2, title_source = ?3, title_note = NULL
1801 WHERE id = ?1
1802 AND (CASE title_source WHEN 'user' THEN 3 WHEN 'llm' THEN 2
1803 WHEN 'derived' THEN 1 ELSE 0 END)
1804 < (CASE ?3 WHEN 'user' THEN 3 WHEN 'llm' THEN 2
1805 WHEN 'derived' THEN 1 ELSE 0 END)",
1806 params![id, title, source.as_str()],
1807 )?;
1808 Ok(n > 0)
1809 })
1810 }
1811
1812 pub fn title_if_unnamed(&self, id: &str, name: &str) -> Result<bool> {
1818 validate_id(id)?;
1819 let name = name.trim();
1820 if name.is_empty() || name.chars().any(char::is_control) {
1821 return Ok(false);
1822 }
1823 self.with_db(|db| {
1824 let n = db.conn.execute(
1825 "UPDATE sessions SET title = ?2, title_source = 'derived'
1826 WHERE id = ?1 AND title IS NULL",
1827 params![id, name],
1828 )?;
1829 Ok(n > 0)
1830 })
1831 }
1832
1833 pub fn claim_title_upgrade(&self, id: &str) -> Result<bool> {
1845 validate_id(id)?;
1846 self.with_db(|db| {
1847 let n = db.conn.execute(
1848 "UPDATE sessions SET title_note = 'trying'
1849 WHERE id = ?1 AND title_source = 'derived' AND title_note IS NULL
1850 AND origin NOT LIKE 'subagent:%' AND origin NOT LIKE 'bot:%'
1851 AND origin NOT LIKE 'flare:%' AND origin <> 'api'",
1852 params![id],
1853 )?;
1854 Ok(n > 0)
1855 })
1856 }
1857
1858 pub fn title_attempt_failed(&self, id: &str, why: &str) -> Result<()> {
1861 validate_id(id)?;
1862 let why: String = why.chars().take(300).collect();
1863 self.with_db(|db| {
1864 db.conn.execute(
1865 "UPDATE sessions SET title_note = ?2 WHERE id = ?1",
1866 params![id, why],
1867 )?;
1868 Ok(())
1869 })
1870 }
1871
1872 pub fn release_title_claim(&self, id: &str) -> Result<()> {
1875 validate_id(id)?;
1876 self.with_db(|db| {
1877 db.conn.execute(
1878 "UPDATE sessions SET title_note = NULL WHERE id = ?1 AND title_note = 'trying'",
1879 params![id],
1880 )?;
1881 Ok(())
1882 })
1883 }
1884
1885 pub fn set_last_cost(&self, id: &str, cost: &TurnCost) -> Result<()> {
1895 validate_id(id)?;
1896 let body = serde_json::to_string(cost)
1897 .map_err(|e| Error::Session(format!("a turn's cost did not encode: {e}")))?;
1898 self.with_db(|db| {
1899 db.conn.execute(
1900 "UPDATE sessions SET last_cost = ?2 WHERE id = ?1",
1901 params![id, body],
1902 )?;
1903 Ok(())
1904 })
1905 }
1906
1907 pub fn set_image_seen(&self, id: &str, seq: u64, index: usize, text: &str) -> Result<bool> {
1917 validate_id(id)?;
1918 let seq = i64::try_from(seq)
1919 .map_err(|_| Error::Session(format!("sequence {seq} is out of range")))?;
1920 self.with_db(|db| {
1921 let tx = db.conn.unchecked_transaction()?;
1924 let row: Option<String> = tx
1925 .query_row(
1926 "SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
1927 params![id, seq],
1928 |r| r.get(0),
1929 )
1930 .optional()?;
1931 let Some(body) = row else {
1932 return Ok(false);
1933 };
1934 let mut message: crate::message::Message = serde_json::from_str(&body)
1935 .map_err(|e| Error::Session(format!("a stored message did not decode: {e}")))?;
1936 let Some(image) = message.images.get_mut(index) else {
1937 return Ok(false);
1938 };
1939 image.seen = Some(text.to_string());
1940 let encoded = serde_json::to_string(&message)
1941 .map_err(|e| Error::Session(format!("a message did not encode: {e}")))?;
1942 let n = tx.execute(
1943 "UPDATE messages SET body = ?3 WHERE session_id = ?1 AND seq = ?2",
1944 params![id, seq, encoded],
1945 )?;
1946 if db.fts {
1949 tx.execute(
1950 "UPDATE messages_fts SET content = ?3 WHERE session_id = ?1 AND seq = ?2",
1951 params![id, seq, searchable(&message)],
1952 )?;
1953 }
1954 tx.commit()?;
1955 Ok(n > 0)
1956 })
1957 }
1958
1959 pub fn last_cost(&self, id: &str) -> Result<Option<TurnCost>> {
1962 validate_id(id)?;
1963 self.with_db(|db| {
1964 let body: Option<String> = db
1965 .conn
1966 .query_row(
1967 "SELECT last_cost FROM sessions WHERE id = ?1",
1968 params![id],
1969 |r| r.get(0),
1970 )
1971 .optional()?
1972 .flatten();
1973 Ok(body.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()))
1974 })
1975 }
1976
1977 pub fn set_pinned(&self, id: &str, pinned: bool) -> Result<()> {
1980 validate_id(id)?;
1981 self.with_db(|db| {
1982 let n = db.conn.execute(
1983 "UPDATE sessions SET pinned = ?2 WHERE id = ?1",
1984 params![id, i64::from(pinned)],
1985 )?;
1986 if n == 0 {
1987 return Err(Error::Session(format!("no such session {id:?}")));
1988 }
1989 Ok(())
1990 })
1991 }
1992
1993 pub fn set_archived(&self, id: &str, archived: bool) -> Result<()> {
2001 validate_id(id)?;
2002 self.with_db(|db| {
2003 let n = db.conn.execute(
2004 "UPDATE sessions SET archived = ?2 WHERE id = ?1",
2005 params![id, i64::from(archived)],
2006 )?;
2007 if n == 0 {
2008 return Err(Error::Session(format!("no such session {id:?}")));
2009 }
2010 Ok(())
2011 })
2012 }
2013
2014 pub fn memory(&self, id: &str) -> Result<Option<Memory>> {
2018 validate_id(id)?;
2019 self.with_db(|db| {
2020 let body: Option<String> = db
2021 .conn
2022 .query_row(
2023 "SELECT body FROM memory WHERE session_id = ?1",
2024 params![id],
2025 |r| r.get(0),
2026 )
2027 .optional()?;
2028 let Some(body) = body else { return Ok(None) };
2029 if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
2030 return Err(Error::Session(format!(
2031 "{id}: memory is larger than {MAX_MEMORY_FILE_BYTES} bytes"
2032 )));
2033 }
2034 serde_json::from_str(&body)
2035 .map(Some)
2036 .map_err(|e| Error::Session(format!("{id}: memory: {e}")))
2037 })
2038 }
2039
2040 pub fn readable_memory(&self, id: &str) -> Option<Memory> {
2043 self.memory(id)
2044 .ok()
2045 .flatten()
2046 .filter(|m| m.validate().is_ok())
2047 }
2048
2049 pub fn save_handoff(
2055 &self,
2056 id: &str,
2057 covered: crate::context::Trimmed,
2058 span: (Option<u64>, Option<u64>),
2059 text: &str,
2060 judgement: Option<Judgement>,
2061 ) -> Result<()> {
2062 validate_id(id)?;
2063 let mut memory = self.current(id);
2064 memory.handoff = Some(Handoff {
2065 text: text.to_string(),
2066 version: crate::compact::VERSION.to_string(),
2067 covered_turns: covered.turns,
2068 covered_messages: covered.messages,
2069 covered_from: span.0,
2070 covered_to: span.1,
2071 generated_at_ms: now_ms(),
2072 judgement,
2073 });
2074 self.save_memory(id, &memory)
2075 }
2076
2077 fn current(&self, id: &str) -> Memory {
2082 let mut memory = self.readable_memory(id).unwrap_or(Memory {
2083 version: MEMORY_VERSION,
2084 handoff: None,
2085 });
2086 memory.version = MEMORY_VERSION;
2089 memory
2090 }
2091
2092 pub fn save_memory(&self, id: &str, memory: &Memory) -> Result<()> {
2098 validate_id(id)?;
2099 memory.validate().map_err(Error::Session)?;
2100 if !self.exists(id) {
2101 return Err(Error::Session(format!("no such session {id:?}")));
2102 }
2103 let body = serde_json::to_string(memory).map_err(|e| Error::Session(e.to_string()))?;
2104 if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
2109 return Err(Error::Session(format!(
2110 "{id}: memory would be {} bytes, over the {MAX_MEMORY_FILE_BYTES}-byte record \
2111 limit; store less, or raise `MAX_MEMORY_FILE_BYTES` in both the writer and the \
2112 reader",
2113 body.len()
2114 )));
2115 }
2116 self.with_db(|db| {
2117 db.conn.execute(
2118 "INSERT INTO memory (session_id, body) VALUES (?1, ?2)
2119 ON CONFLICT(session_id) DO UPDATE SET body = ?2",
2120 params![id, body],
2121 )?;
2122 Ok(())
2123 })
2124 }
2125
2126 pub fn delete(&self, id: &str) -> Result<()> {
2128 validate_id(id)?;
2129 self.with_db(|db| {
2130 let tx = db.conn.unchecked_transaction()?;
2136 let n = tx.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
2137 if n == 0 {
2138 return Err(Error::Session(format!("no such session {id:?}")));
2141 }
2142 if db.fts {
2143 tx.execute(
2144 "DELETE FROM messages_fts WHERE session_id = ?1",
2145 params![id],
2146 )?;
2147 }
2148 tx.commit()?;
2149 Ok(())
2150 })?;
2151 for path in [
2158 self.lock_path(id)?,
2159 self.dir.join(format!("{id}.jsonl")),
2160 self.dir.join(format!("{id}.meta.json")),
2161 self.dir.join(format!("{id}.memory.json")),
2162 ] {
2163 match std::fs::remove_file(&path) {
2164 Ok(()) => {}
2165 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2166 Err(e) => return Err(Error::io(&path, e)),
2167 }
2168 }
2169 Ok(())
2170 }
2171
2172 pub fn prune_candidates(
2192 &self,
2193 keep_days: u64,
2194 keep_count: usize,
2195 now_ms: u64,
2196 include_archived: bool,
2197 ) -> Result<PrunePlan> {
2198 if keep_days == 0 && keep_count == 0 {
2199 return Ok(PrunePlan::default());
2200 }
2201 let mut sessions = self.session_ages()?;
2202 sessions.sort_by(|a, b| b.cmp(a));
2203 let cutoff = now_ms.saturating_sub(keep_days.saturating_mul(86_400_000));
2204 let mut plan = PrunePlan::default();
2205 for (i, (last, id, pinned, archived)) in sessions.into_iter().enumerate() {
2206 let over = (keep_count > 0 && i >= keep_count) || (keep_days > 0 && last < cutoff);
2207 if !over {
2208 continue;
2209 }
2210 if pinned {
2211 plan.pinned_kept += 1;
2212 } else if archived && !include_archived {
2213 plan.archived_kept += 1;
2214 } else {
2215 plan.candidates.push(id);
2216 }
2217 }
2218 Ok(plan)
2219 }
2220
2221 fn session_ages(&self) -> Result<Vec<(u64, String, bool, bool)>> {
2223 self.with_db(|db| {
2224 let mut stmt = db.conn.prepare(
2225 "SELECT updated_ms, id, pinned, archived FROM sessions ORDER BY updated_ms",
2226 )?;
2227 let rows = stmt.query_map([], |r| {
2228 let ms: i64 = r.get(0)?;
2229 let id: String = r.get(1)?;
2230 let pinned: i64 = r.get(2)?;
2231 let archived: i64 = r.get(3)?;
2232 Ok((ms.max(0) as u64, id, pinned != 0, archived != 0))
2233 })?;
2234 Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
2235 })
2236 }
2237
2238 pub fn auto_prune(
2248 &self,
2249 keep_days: u64,
2250 keep_count: usize,
2251 now_ms: u64,
2252 protect: Option<&str>,
2253 ) -> Result<AutoPrune> {
2254 if keep_days == 0 && keep_count == 0 {
2255 return Ok(AutoPrune::NoLimits);
2256 }
2257 let plan = self.prune_candidates(keep_days, keep_count, now_ms, false)?;
2258 let doomed: Vec<String> = plan
2259 .candidates
2260 .into_iter()
2261 .filter(|id| Some(id.as_str()) != protect)
2262 .collect();
2263 if doomed.is_empty() {
2264 return Ok(AutoPrune::Nothing);
2265 }
2266 if doomed.len() > PRUNE_CONFIRM_ABOVE {
2267 return Ok(AutoPrune::Skipped {
2268 would_remove: doomed.len(),
2269 });
2270 }
2271 let mut removed = 0;
2272 let mut failed = 0;
2273 for id in &doomed {
2274 match self.delete(id) {
2275 Ok(()) => removed += 1,
2276 Err(_) => failed += 1,
2277 }
2278 }
2279 Ok(AutoPrune::Pruned {
2280 removed,
2281 failed,
2282 pinned_kept: plan.pinned_kept,
2283 })
2284 }
2285
2286 pub fn export(&self, id: &str, format: ExportFormat) -> Result<String> {
2289 let records = self.load_records(id)?;
2290 let title = self.title(id).ok().flatten();
2291 match format {
2292 ExportFormat::Json => export_json(id, title, &records),
2293 ExportFormat::Markdown => Ok(export_markdown(id, title.as_deref(), &records)),
2294 }
2295 }
2296
2297 pub fn list(&self) -> Result<Vec<SessionInfo>> {
2307 self.list_rows(false, false)
2308 }
2309
2310 pub fn list_with_archived(&self) -> Result<Vec<SessionInfo>> {
2317 self.list_rows(true, false)
2318 }
2319
2320 pub fn list_bots(&self) -> Result<Vec<BotSessions>> {
2326 let mut out: Vec<BotSessions> = Vec::new();
2327 for info in self.list_rows(true, true)? {
2328 let Some(name) = info.bot() else { continue };
2329 match out.iter_mut().find(|b| b.name == name) {
2330 Some(bot) => {
2332 bot.sessions += 1;
2333 if !info.archived {
2334 bot.archived = false;
2335 }
2336 }
2337 None => out.push(BotSessions {
2338 name: name.to_string(),
2339 sessions: 1,
2340 messages: info.messages,
2341 last_session: info.id.clone(),
2342 last_activity_ms: info.updated_ms,
2343 archived: info.archived,
2344 }),
2345 }
2346 }
2347 Ok(out)
2348 }
2349
2350 fn list_rows(&self, include_archived: bool, include_bots: bool) -> Result<Vec<SessionInfo>> {
2357 self.with_db(|db| {
2358 let mut stmt = db.conn.prepare(
2364 "SELECT id, title, preview, messages, updated_ms, origin, pinned, archived, last_cost
2365 FROM sessions
2366 WHERE (archived = 0 OR ?1) AND (?2 OR origin NOT LIKE 'bot:%')
2367 ORDER BY pinned DESC, updated_ms DESC, rowid DESC",
2368 )?;
2369 let rows = stmt.query_map(
2370 params![i64::from(include_archived), i64::from(include_bots)],
2371 |r| {
2372 let updated: i64 = r.get(4)?;
2373 let messages: i64 = r.get(3)?;
2374 let pinned: i64 = r.get(6)?;
2375 let archived: i64 = r.get(7)?;
2376 let cost: Option<String> = r.get(8)?;
2377 Ok(SessionInfo {
2378 id: r.get(0)?,
2379 title: r.get(1)?,
2380 preview: r.get::<_, Option<String>>(2)?.unwrap_or_default(),
2381 messages: messages.max(0) as usize,
2382 updated_ms: updated.max(0) as u64,
2383 origin: r.get(5)?,
2384 pinned: pinned != 0,
2385 archived: archived != 0,
2386 cost: cost.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()),
2389 })
2390 })?;
2391 Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
2392 })
2393 }
2394
2395 pub fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>> {
2404 self.search_with(query, limit, false)
2405 }
2406
2407 pub fn search_with(
2415 &self,
2416 query: &str,
2417 limit: usize,
2418 include_children: bool,
2419 ) -> Result<Vec<SearchHit>> {
2420 let q = query.trim();
2421 if q.is_empty() {
2422 return Ok(Vec::new());
2423 }
2424 let limit = limit.clamp(1, 1000) as i64;
2425 self.with_db(|db| Self::search_in(db, q, limit, db.fts, include_children))
2426 }
2427
2428 fn search_in(
2435 db: &Db,
2436 q: &str,
2437 limit: i64,
2438 use_fts: bool,
2439 include_children: bool,
2440 ) -> Result<Vec<SearchHit>> {
2441 let children = i64::from(include_children);
2442 let mut out = Vec::new();
2443 let mut named = db.conn.prepare(
2449 "SELECT id, title, updated_ms FROM sessions
2450 WHERE title LIKE '%' || ?1 || '%' ESCAPE '\\'
2451 AND (?3 = 1 OR (origin NOT LIKE 'bot:%' AND origin NOT LIKE 'flare:%'))
2452 ORDER BY pinned DESC, archived ASC, updated_ms DESC LIMIT ?2",
2453 )?;
2454 let rows = named.query_map(params![like_literal(q), limit, children], |r| {
2455 Ok((
2456 r.get::<_, String>(0)?,
2457 r.get::<_, String>(1)?,
2458 r.get::<_, i64>(2)?,
2459 ))
2460 })?;
2461 for row in rows {
2462 let (session_id, title, updated_ms) = row?;
2463 out.push(SearchHit {
2464 session_id,
2465 seq: 0,
2466 at_ms: updated_ms.max(0) as u64,
2467 role: "title".to_string(),
2468 snippet: title,
2469 });
2470 }
2471
2472 let mut budget = limit.saturating_mul(4).max(limit + 8);
2477 loop {
2478 let (found, read) =
2479 Self::message_hits(db, q, limit, budget, use_fts, include_children)?;
2480 let room_to_widen = read >= budget && budget < OWN_TAIL_BUDGET_CAP;
2481 if !found.is_empty() || !room_to_widen {
2482 out.extend(found);
2483 break;
2484 }
2485 budget = (budget * 4).min(OWN_TAIL_BUDGET_CAP);
2486 }
2487 Ok(out)
2488 }
2489
2490 fn message_hits(
2498 db: &Db,
2499 q: &str,
2500 limit: i64,
2501 budget: i64,
2502 use_fts: bool,
2503 include_children: bool,
2504 ) -> Result<(Vec<SearchHit>, i64)> {
2505 let children = i64::from(include_children);
2506 let mut found = Vec::new();
2507 let mut read = 0i64;
2508 if use_fts {
2509 let terms: Vec<String> = q
2512 .split_whitespace()
2513 .map(|t| format!("\"{}\"", t.replace('"', "\"\"")))
2514 .collect();
2515 let mut stmt = db.conn.prepare(
2516 "SELECT f.session_id, f.seq, f.content
2521 FROM messages_fts f
2522 JOIN messages m ON m.session_id = f.session_id AND m.seq = f.seq
2523 JOIN sessions s ON s.id = f.session_id
2524 WHERE f.messages_fts MATCH ?1
2525 AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
2526 ORDER BY m.at_ms DESC, m.seq DESC
2527 LIMIT ?2",
2528 )?;
2529 let rows = stmt.query_map(params![terms.join(" "), budget, children], |r| {
2530 Ok((
2531 r.get::<_, String>(0)?,
2532 r.get::<_, i64>(1)?,
2533 r.get::<_, String>(2)?,
2534 ))
2535 })?;
2536 for row in rows {
2537 let (session_id, seq, content) = row?;
2538 read += 1;
2539 if is_own_tail(&db.conn, &session_id, seq)? {
2540 continue;
2541 }
2542 if let Some(found_hit) = hit(&db.conn, session_id, seq, &content)? {
2543 found.push(found_hit);
2544 if found.len() as i64 >= limit {
2545 break;
2546 }
2547 }
2548 }
2549 } else {
2550 let mut stmt = db.conn.prepare(
2553 "SELECT m.session_id, m.seq, m.body FROM messages m
2554 JOIN sessions s ON s.id = m.session_id
2555 WHERE m.body LIKE '%' || ?1 || '%' ESCAPE '\\'
2556 AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
2557 ORDER BY m.at_ms DESC, m.seq DESC LIMIT ?2",
2558 )?;
2559 let rows = stmt.query_map(params![like_literal(q), budget, children], |r| {
2560 Ok((
2561 r.get::<_, String>(0)?,
2562 r.get::<_, i64>(1)?,
2563 r.get::<_, String>(2)?,
2564 ))
2565 })?;
2566 for row in rows {
2567 let (session_id, seq, body) = row?;
2568 read += 1;
2569 let message: Message = serde_json::from_str(&body)
2570 .map_err(|e| Error::Session(format!("{session_id}:{seq}: {e}")))?;
2571 if is_own_tail(&db.conn, &session_id, seq)? {
2572 continue;
2573 }
2574 if let Some(found_hit) = hit(&db.conn, session_id, seq, &searchable(&message))? {
2575 found.push(found_hit);
2576 if found.len() as i64 >= limit {
2577 break;
2578 }
2579 }
2580 }
2581 }
2582 Ok((found, read))
2583 }
2584
2585 pub fn has_fts(&self) -> bool {
2587 self.with_db(|db| Ok(db.fts)).unwrap_or(false)
2588 }
2589}
2590
2591#[derive(Debug, Clone, PartialEq, Eq)]
2593pub struct SearchHit {
2594 pub session_id: String,
2595 pub seq: usize,
2597 pub at_ms: u64,
2598 pub role: String,
2599 pub snippet: String,
2601}
2602
2603fn hit(
2610 conn: &Connection,
2611 session_id: String,
2612 seq: i64,
2613 content: &str,
2614) -> Result<Option<SearchHit>> {
2615 let found: Option<(i64, String)> = conn
2616 .query_row(
2617 "SELECT at_ms, role FROM messages WHERE session_id = ?1 AND seq = ?2",
2618 params![session_id, seq],
2619 |r| Ok((r.get(0)?, r.get(1)?)),
2620 )
2621 .map(Some)
2622 .or_else(|e| match e {
2623 rusqlite::Error::QueryReturnedNoRows => Ok(None),
2624 other => Err(other),
2625 })?;
2626 let Some((at_ms, role)) = found else {
2627 return Ok(None);
2628 };
2629 Ok(Some(SearchHit {
2630 session_id,
2631 seq: seq.max(0) as usize,
2632 at_ms: at_ms.max(0) as u64,
2633 role,
2634 snippet: snippet(content, 160),
2635 }))
2636}
2637
2638const OWN_TAIL_TOOL: &str = "session_search";
2645
2646const OWN_TAIL_LOOKBACK: i64 = 20;
2649
2650const OWN_TAIL_BUDGET_CAP: i64 = 512;
2653
2654fn is_own_tail(conn: &Connection, session_id: &str, seq: i64) -> Result<bool> {
2660 let body: Option<String> = conn
2661 .query_row(
2662 "SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
2663 params![session_id, seq],
2664 |r| r.get(0),
2665 )
2666 .map(Some)
2667 .or_else(|e| match e {
2668 rusqlite::Error::QueryReturnedNoRows => Ok(None),
2669 other => Err(other),
2670 })?;
2671 let Some(body) = body else {
2672 return Ok(false);
2673 };
2674 let Ok(message) = serde_json::from_str::<Message>(&body) else {
2675 return Ok(false);
2676 };
2677 if message
2678 .tool_calls
2679 .iter()
2680 .any(|call| call.function.name == OWN_TAIL_TOOL)
2681 {
2682 return Ok(true);
2683 }
2684 let Some(answer_to) = message.tool_call_id.as_deref() else {
2685 return Ok(false);
2686 };
2687 let mut stmt = conn.prepare(
2688 "SELECT body FROM messages
2689 WHERE session_id = ?1 AND seq < ?2 AND role = 'assistant'
2690 ORDER BY seq DESC LIMIT ?3",
2691 )?;
2692 let rows = stmt.query_map(params![session_id, seq, OWN_TAIL_LOOKBACK], |r| {
2693 r.get::<_, String>(0)
2694 })?;
2695 for row in rows {
2696 let Ok(called) = serde_json::from_str::<Message>(&row?) else {
2697 continue;
2698 };
2699 if called
2700 .tool_calls
2701 .iter()
2702 .any(|call| call.id == answer_to && call.function.name == OWN_TAIL_TOOL)
2703 {
2704 return Ok(true);
2705 }
2706 }
2707 Ok(false)
2708}
2709
2710fn like_literal(q: &str) -> String {
2713 let mut out = String::with_capacity(q.len());
2714 for c in q.chars() {
2715 if matches!(c, '\\' | '%' | '_') {
2716 out.push('\\');
2717 }
2718 out.push(c);
2719 }
2720 out
2721}
2722
2723fn searchable(message: &Message) -> String {
2726 let mut out = message.text_with_pictures();
2729 for call in &message.tool_calls {
2730 if !out.is_empty() {
2731 out.push('\n');
2732 }
2733 out.push_str(&call.function.name);
2734 out.push(' ');
2735 out.push_str(&call.function.arguments);
2736 }
2737 out
2738}
2739
2740fn run_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<FlareRunRow> {
2743 let started: i64 = r.get(6)?;
2744 Ok(FlareRunRow {
2745 id: r.get(0)?,
2746 task: r.get(1)?,
2747 state: r.get(2)?,
2748 routes: r
2749 .get::<_, String>(3)?
2750 .split(',')
2751 .filter(|s| !s.is_empty())
2752 .map(str::to_string)
2753 .collect(),
2754 jobs: r.get::<_, i64>(4)?.max(0) as usize,
2755 parent: r.get(5)?,
2756 started_ms: started.max(0) as u64,
2757 finished_ms: r.get::<_, Option<i64>>(7)?.map(|v| v.max(0) as u64),
2758 prompt_tokens: r.get::<_, Option<i64>>(8)?.map(|v| v as u64),
2759 completion_tokens: r.get::<_, Option<i64>>(9)?.map(|v| v as u64),
2760 iterations: r.get::<_, Option<i64>>(10)?.unwrap_or(0).max(0) as usize,
2761 })
2762}
2763
2764fn snippet(text: &str, max: usize) -> String {
2765 let one: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
2766 if one.chars().count() <= max {
2767 return one;
2768 }
2769 one.chars().take(max.saturating_sub(1)).collect::<String>() + "…"
2770}
2771
2772fn role_name(role: Role) -> &'static str {
2773 match role {
2774 Role::System => "system",
2775 Role::User => "user",
2776 Role::Assistant => "assistant",
2777 Role::Tool => "tool",
2778 }
2779}
2780
2781pub(crate) struct Db {
2786 pub(crate) conn: Connection,
2787 fts: bool,
2790}
2791
2792impl Db {
2793 fn open(dir: &Path) -> Result<Self> {
2794 std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
2795 #[cfg(unix)]
2801 {
2802 use std::os::unix::fs::PermissionsExt;
2803 let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
2804 }
2805 let path = dir.join(DB_FILE);
2806 let conn = Connection::open(&path).map_err(db_err(&path))?;
2807 let _: String = conn
2809 .query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
2810 .map_err(db_err(&path))?;
2811 conn.execute_batch(
2812 "PRAGMA foreign_keys = ON;
2813 PRAGMA synchronous = NORMAL;
2814 PRAGMA busy_timeout = 5000;",
2815 )
2816 .map_err(db_err(&path))?;
2817 conn.execute_batch(SCHEMA).map_err(db_err(&path))?;
2818 #[cfg(unix)]
2822 {
2823 use std::os::unix::fs::PermissionsExt;
2824 for f in [
2825 path.clone(),
2826 path.with_extension("db-wal"),
2827 path.with_extension("db-shm"),
2828 ] {
2829 if f.exists() {
2830 let _ = std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o600));
2831 }
2832 }
2833 }
2834 if !has_column(&conn, "sessions", "pinned").map_err(db_err(&path))? {
2839 conn.execute_batch("ALTER TABLE sessions ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0")
2840 .map_err(db_err(&path))?;
2841 }
2842 if !has_column(&conn, "sessions", "archived").map_err(db_err(&path))? {
2845 conn.execute_batch(
2846 "ALTER TABLE sessions ADD COLUMN archived INTEGER NOT NULL DEFAULT 0",
2847 )
2848 .map_err(db_err(&path))?;
2849 }
2850 if !has_column(&conn, "approvals", "by").map_err(db_err(&path))? {
2855 conn.execute_batch("ALTER TABLE approvals ADD COLUMN by TEXT")
2856 .map_err(db_err(&path))?;
2857 }
2858 if !has_column(&conn, "sessions", "last_cost").map_err(db_err(&path))? {
2859 conn.execute_batch("ALTER TABLE sessions ADD COLUMN last_cost TEXT")
2860 .map_err(db_err(&path))?;
2861 }
2862 let title_source_added =
2866 !has_column(&conn, "sessions", "title_source").map_err(db_err(&path))?;
2867 if title_source_added {
2868 conn.execute_batch(
2869 "ALTER TABLE sessions ADD COLUMN title_source TEXT;
2870 ALTER TABLE sessions ADD COLUMN title_note TEXT;",
2871 )
2872 .map_err(db_err(&path))?;
2873 } else if !has_column(&conn, "sessions", "title_note").map_err(db_err(&path))? {
2874 conn.execute_batch("ALTER TABLE sessions ADD COLUMN title_note TEXT")
2875 .map_err(db_err(&path))?;
2876 }
2877 if title_source_added {
2878 conn.execute_batch("UPDATE sessions SET title_source = 'user' WHERE title IS NOT NULL")
2882 .map_err(db_err(&path))?;
2883 }
2884
2885 let fts = match conn.execute_batch(FTS_SCHEMA) {
2886 Ok(()) => true,
2887 Err(_) => false,
2889 };
2890
2891 let mut db = Self { conn, fts };
2892 let warnings = db.import_legacy(dir)?;
2893 for w in warnings {
2894 eprintln!("warning: {w}");
2895 }
2896 Ok(db)
2897 }
2898
2899 fn import_legacy(&mut self, dir: &Path) -> Result<Vec<String>> {
2905 let rd = match std::fs::read_dir(dir) {
2906 Ok(rd) => rd,
2907 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
2908 Err(e) => return Err(Error::io(dir, e)),
2909 };
2910 let mut files: Vec<PathBuf> = Vec::new();
2911 for entry in rd.flatten() {
2912 let path = entry.path();
2913 if path.extension().and_then(|e| e.to_str()) == Some("jsonl") {
2914 files.push(path);
2915 }
2916 }
2917 files.sort();
2918 let mut warnings = Vec::new();
2919 let tx = self.conn.transaction().map_err(db_err(dir))?;
2920 for path in files {
2921 let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
2922 continue;
2923 };
2924 if validate_id(id).is_err() {
2925 warnings.push(format!(
2926 "{}: ignoring, not a valid session id",
2927 path.display()
2928 ));
2929 continue;
2930 }
2931 let already: Option<i64> = tx
2932 .query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
2933 r.get(0)
2934 })
2935 .optional()
2936 .map_err(db_err(&path))?;
2937 if already.is_some() {
2938 continue;
2939 }
2940 match read_legacy(&path) {
2941 Ok(legacy) => {
2942 let first = legacy.records.first().map(|r| r.ts);
2943 let last = legacy.records.last().map(|r| r.ts);
2944 let mtime = std::fs::metadata(&path)
2945 .and_then(|m| m.modified())
2946 .ok()
2947 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
2948 .map_or(0, |d| d.as_millis() as u64);
2949 let created = first.unwrap_or(mtime) as i64;
2950 let updated = last.unwrap_or(mtime) as i64;
2951 let preview = legacy.preview();
2952 tx.execute(
2953 "INSERT INTO sessions
2954 (id, created_ms, updated_ms, title, preview, messages, origin)
2955 VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'jsonl')",
2956 params![
2957 id,
2958 created,
2959 updated,
2960 legacy.title,
2961 preview,
2962 legacy.records.len() as i64
2963 ],
2964 )
2965 .map_err(db_err(&path))?;
2966 for (i, rec) in legacy.records.iter().enumerate() {
2967 let body = serde_json::to_string(&rec.message)
2968 .map_err(|e| Error::Session(e.to_string()))?;
2969 tx.execute(
2970 "INSERT INTO messages (session_id, seq, at_ms, role, body)
2971 VALUES (?1, ?2, ?3, ?4, ?5)",
2972 params![
2973 id,
2974 i as i64,
2975 rec.ts as i64,
2976 role_name(rec.message.role),
2977 body
2978 ],
2979 )
2980 .map_err(db_err(&path))?;
2981 if self.fts {
2982 tx.execute(
2983 "INSERT INTO messages_fts (session_id, seq, content)
2984 VALUES (?1, ?2, ?3)",
2985 params![id, i as i64, searchable(&rec.message)],
2986 )
2987 .map_err(db_err(&path))?;
2988 }
2989 }
2990 if let Some(body) = legacy.memory {
2991 tx.execute(
2995 "INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, ?2)",
2996 params![id, body],
2997 )
2998 .map_err(db_err(&path))?;
2999 }
3000 if let Some(w) = legacy.warning {
3001 warnings.push(w);
3002 }
3003 }
3004 Err(e) => {
3005 warnings.push(format!("{}: not imported: {e}", path.display()));
3008 }
3009 }
3010 }
3011 tx.commit().map_err(db_err(dir))?;
3012 Ok(warnings)
3013 }
3014}
3015
3016const DB_FILE: &str = "sessions.db";
3018
3019pub fn db_path(dir: &Path) -> PathBuf {
3024 dir.join(DB_FILE)
3025}
3026
3027const SCHEMA: &str = "
3028CREATE TABLE IF NOT EXISTS sessions (
3029 id TEXT PRIMARY KEY,
3030 created_ms INTEGER NOT NULL,
3031 updated_ms INTEGER NOT NULL,
3032 title TEXT,
3033 preview TEXT,
3034 messages INTEGER NOT NULL DEFAULT 0,
3035 origin TEXT NOT NULL DEFAULT 'native',
3036 pinned INTEGER NOT NULL DEFAULT 0,
3037 archived INTEGER NOT NULL DEFAULT 0,
3038 title_source TEXT,
3039 title_note TEXT,
3040 last_cost TEXT
3041);
3042CREATE INDEX IF NOT EXISTS sessions_by_activity ON sessions(updated_ms DESC);
3043CREATE TABLE IF NOT EXISTS messages (
3044 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3045 seq INTEGER NOT NULL,
3046 at_ms INTEGER NOT NULL,
3047 role TEXT NOT NULL,
3048 body TEXT NOT NULL,
3049 PRIMARY KEY (session_id, seq)
3050);
3051CREATE TABLE IF NOT EXISTS memory (
3052 session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
3053 body TEXT NOT NULL
3054);
3055CREATE TABLE IF NOT EXISTS approvals (
3056 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3057 seq INTEGER NOT NULL,
3058 ord INTEGER NOT NULL,
3059 call_id TEXT NOT NULL,
3060 tool TEXT NOT NULL,
3061 summary TEXT NOT NULL,
3062 args TEXT NOT NULL,
3063 decision TEXT,
3064 decided_ms INTEGER,
3065 PRIMARY KEY (session_id, seq, ord)
3066);
3067CREATE INDEX IF NOT EXISTS approvals_by_call ON approvals(session_id, call_id);
3068-- `#340`: who answered a call, and a log that outlives the row.
3069--
3070-- `approvals` is deliberately transient — `clear_call` deletes the row once the answer is in the
3071-- transcript, because a row left behind would let a resume replay a call that already ran. That
3072-- makes it the wrong place to ask what the model waved through last week, so the decider goes
3073-- on the row (who answered *this* waiting call) and every ruling is also appended here, where
3074-- nothing ever deletes it.
3075CREATE TABLE IF NOT EXISTS approval_log (
3076 session_id TEXT NOT NULL,
3077 at_ms INTEGER NOT NULL,
3078 call_id TEXT NOT NULL,
3079 tool TEXT NOT NULL,
3080 summary TEXT NOT NULL,
3081 decision TEXT NOT NULL,
3082 by TEXT NOT NULL
3083);
3084CREATE INDEX IF NOT EXISTS approval_log_by_session ON approval_log(session_id, at_ms);
3085-- `#447`: how a tool call ended, kept beside the message rather than inside it. A stored `tool`
3086-- message is the model's wire shape and carries no verdict, so a replayed row used to read the
3087-- mark off the text and call a failed `read_file` a ✓. The call id is the key the dashboard
3088-- already joins on.
3089CREATE TABLE IF NOT EXISTS tool_outcomes (
3090 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3091 call_id TEXT NOT NULL,
3092 is_error INTEGER NOT NULL,
3093 PRIMARY KEY (session_id, call_id)
3094);
3095-- `#172`: one standing goal per session, and every judgement made about it. A new table rather
3096-- than a column, so an older `sessions.db` opens without a migration step and a session that has
3097-- never had a goal keeps no row at all. The foreign key is the whole of `deleting a session
3098-- deletes its goal`.
3099CREATE TABLE IF NOT EXISTS goals (
3100 session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
3101 text TEXT NOT NULL,
3102 gate TEXT,
3103 budget INTEGER NOT NULL,
3104 turns INTEGER NOT NULL DEFAULT 0,
3105 state TEXT NOT NULL,
3106 note TEXT,
3107 garbage INTEGER NOT NULL DEFAULT 0,
3108 created_ms INTEGER NOT NULL,
3109 updated_ms INTEGER NOT NULL
3110);
3111CREATE TABLE IF NOT EXISTS goal_turns (
3112 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3113 turn INTEGER NOT NULL,
3114 verdict TEXT NOT NULL,
3115 why TEXT,
3116 at_ms INTEGER NOT NULL,
3117 PRIMARY KEY (session_id, turn)
3118);
3119-- `#171`: a flare run and its N children. A run that cannot be listed after a restart is a run
3120-- that cannot be cancelled, so the ledger is a table rather than a field on the agent that
3121-- started it — and it is two tables because the run's cost is a sum over children that may have
3122-- failed, and a failed child's cost still happened.
3123CREATE TABLE IF NOT EXISTS flare_runs (
3124 id TEXT PRIMARY KEY,
3125 task TEXT NOT NULL,
3126 state TEXT NOT NULL,
3127 routes TEXT NOT NULL,
3128 jobs INTEGER NOT NULL,
3129 parent TEXT,
3130 started_ms INTEGER NOT NULL,
3131 finished_ms INTEGER,
3132 prompt_tokens INTEGER,
3133 completion_tokens INTEGER,
3134 iterations INTEGER,
3135 cancel_requested INTEGER NOT NULL DEFAULT 0
3136);
3137CREATE INDEX IF NOT EXISTS flare_runs_by_start ON flare_runs(started_ms DESC);
3138CREATE TABLE IF NOT EXISTS flare_jobs (
3139 run_id TEXT NOT NULL REFERENCES flare_runs(id) ON DELETE CASCADE,
3140 n INTEGER NOT NULL,
3141 route TEXT NOT NULL,
3142 session_id TEXT,
3143 state TEXT NOT NULL,
3144 prompt_tokens INTEGER,
3145 completion_tokens INTEGER,
3146 iterations INTEGER,
3147 why TEXT,
3148 PRIMARY KEY (run_id, n)
3149);
3150";
3151
3152const FTS_SCHEMA: &str = "
3155CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
3156 session_id UNINDEXED,
3157 seq UNINDEXED,
3158 content
3159);
3160";
3161
3162fn db_err(path: &Path) -> impl Fn(rusqlite::Error) -> Error + '_ {
3163 move |e| Error::Session(format!("{}: {e}", path.display()))
3164}
3165
3166fn has_column(conn: &Connection, table: &str, column: &str) -> rusqlite::Result<bool> {
3169 let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
3170 let mut rows = stmt.query([])?;
3171 while let Some(row) = rows.next()? {
3172 let name: String = row.get(1)?;
3173 if name == column {
3174 return Ok(true);
3175 }
3176 }
3177 Ok(false)
3178}
3179
3180struct Legacy {
3182 records: Vec<Record>,
3183 title: Option<String>,
3184 memory: Option<String>,
3186 warning: Option<String>,
3187}
3188
3189impl Legacy {
3190 fn preview(&self) -> Option<String> {
3191 self.records
3192 .iter()
3193 .find(|r| r.message.role == Role::User)
3194 .and_then(|r| r.message.content.as_deref())
3195 .map(|t| {
3196 let one_line: String = t.split_whitespace().collect::<Vec<_>>().join(" ");
3197 one_line.chars().take(60).collect()
3198 })
3199 }
3200}
3201
3202fn read_legacy(path: &Path) -> Result<Legacy> {
3208 let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
3209 let text = String::from_utf8_lossy(&bytes);
3210 let terminated = text.ends_with('\n');
3211 let lines: Vec<&str> = text.lines().collect();
3212 let mut records = Vec::new();
3213 let mut warning = None;
3214 for (i, line) in lines.iter().enumerate() {
3215 if line.trim().is_empty() {
3216 continue;
3217 }
3218 match serde_json::from_str::<Record>(line) {
3219 Ok(rec) => records.push(rec),
3220 Err(_) if i + 1 == lines.len() && !terminated => {
3221 warning = Some(format!(
3222 "{}:{}: ignoring truncated trailing line ({} bytes)",
3223 path.display(),
3224 i + 1,
3225 line.len()
3226 ));
3227 }
3228 Err(e) => return Err(Error::Session(format!("line {}: {e}", i + 1))),
3229 }
3230 }
3231 let dir = path.parent().unwrap_or(Path::new("."));
3232 let id = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
3233 let title = std::fs::read_to_string(dir.join(format!("{id}.meta.json")))
3234 .ok()
3235 .and_then(|t| serde_json::from_str::<Meta>(&t).ok())
3236 .map(|m| m.title);
3237 let memory = std::fs::read_to_string(dir.join(format!("{id}.memory.json")))
3238 .ok()
3239 .filter(|t| t.len() as u64 <= MAX_MEMORY_FILE_BYTES);
3240 Ok(Legacy {
3241 records,
3242 title,
3243 memory,
3244 warning,
3245 })
3246}
3247
3248fn export_json(id: &str, title: Option<String>, records: &[Record]) -> Result<String> {
3249 let doc = serde_json::json!({
3250 "format": "eclipse-session/1",
3251 "id": id,
3252 "title": title,
3253 "messages": records,
3254 });
3255 let mut out = serde_json::to_string_pretty(&doc).map_err(|e| Error::Session(e.to_string()))?;
3256 out.push('\n');
3257 Ok(out)
3258}
3259
3260fn fenced(info: &str, text: &str) -> String {
3262 let (mut run, mut longest) = (0usize, 0usize);
3263 for c in text.chars() {
3264 run = if c == '`' { run + 1 } else { 0 };
3265 longest = longest.max(run);
3266 }
3267 let fence = "`".repeat((longest + 1).max(3));
3268 let nl = if text.ends_with('\n') { "" } else { "\n" };
3269 format!("{fence}{info}\n{text}{nl}{fence}\n")
3270}
3271
3272fn export_markdown(id: &str, title: Option<&str>, records: &[Record]) -> String {
3273 use std::collections::HashMap;
3274 use std::fmt::Write as _;
3275
3276 let mut out = String::new();
3277 let _ = writeln!(out, "# {}\n", title.unwrap_or(id).replace('\n', " "));
3278 let _ = writeln!(out, "- Session: `{id}`");
3279 let _ = writeln!(out, "- Messages: {}", records.len());
3280 if let Some(first) = records.first() {
3281 let _ = writeln!(out, "- Started: {} UTC", format_utc(first.ts));
3282 }
3283 out.push_str(
3284 "\n_The system prompt is not stored in sessions, so it is not part of this transcript._\n",
3285 );
3286
3287 let mut tool_names: HashMap<&str, &str> = HashMap::new();
3288 for r in records {
3289 for c in &r.message.tool_calls {
3290 tool_names.insert(&c.id, &c.function.name);
3291 }
3292 }
3293 let mut answered: std::collections::HashSet<&str> = std::collections::HashSet::new();
3294 for r in records {
3295 if let Some(id) = r.message.tool_call_id.as_deref() {
3296 answered.insert(id);
3297 }
3298 }
3299
3300 for (i, r) in records.iter().enumerate() {
3301 let m = &r.message;
3302 let who = match m.role {
3303 Role::System => "System".to_string(),
3304 Role::User => "User".to_string(),
3305 Role::Assistant => "Assistant".to_string(),
3306 Role::Tool => {
3307 let name = m
3308 .tool_call_id
3309 .as_deref()
3310 .and_then(|c| tool_names.get(c).copied())
3311 .unwrap_or("unknown tool");
3312 format!("Tool result: {name}")
3313 }
3314 };
3315 let _ = writeln!(out, "\n## {}. {who} ({} UTC)\n", i + 1, format_utc(r.ts));
3316 match m.role {
3317 Role::Tool => out.push_str(&fenced("", &m.text_with_pictures())),
3318 _ => {
3319 let text = m.text_with_pictures();
3320 if !text.is_empty() {
3321 out.push_str(&text);
3322 out.push('\n');
3323 }
3324 }
3325 }
3326 for c in &m.tool_calls {
3327 let args = &c.function.arguments;
3328 let _ = writeln!(
3329 out,
3330 "\n**Tool call** `{}` (id `{}`){}\n",
3331 c.function.name.replace('`', "'"),
3332 c.id.replace('`', "'"),
3333 if answered.contains(c.id.as_str()) {
3334 ""
3335 } else {
3336 " - no result recorded"
3337 }
3338 );
3339 match serde_json::from_str::<serde_json::Value>(args) {
3340 Ok(v) => out.push_str(&fenced(
3341 "json",
3342 &serde_json::to_string_pretty(&v).unwrap_or_else(|_| args.clone()),
3343 )),
3344 Err(_) => out.push_str(&fenced("", args)),
3345 }
3346 }
3347 }
3348 out
3349}
3350
3351pub fn format_utc(ms: u64) -> String {
3353 let secs = ms / 1000;
3354 let days = (secs / 86_400) as i64;
3355 let rem = secs % 86_400;
3356 let z = days + 719_468;
3358 let era = z.div_euclid(146_097);
3359 let doe = z.rem_euclid(146_097);
3360 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
3361 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
3362 let mp = (5 * doy + 2) / 153;
3363 let d = doy - (153 * mp + 2) / 5 + 1;
3364 let m = if mp < 10 { mp + 3 } else { mp - 9 };
3365 let y = yoe + era * 400 + i64::from(m <= 2);
3366 format!(
3367 "{y:04}-{m:02}-{d:02} {:02}:{:02}",
3368 rem / 3600,
3369 rem % 3600 / 60
3370 )
3371}
3372
3373#[cfg(test)]
3374mod tests {
3375 use super::*;
3376 use crate::message::{FunctionCall, ToolCall};
3377
3378 fn store(dir: &Path) -> SessionStore {
3379 SessionStore::new(dir.join("sessions"))
3380 }
3381
3382 fn call(id: &str, name: &str, args: &str) -> ToolCall {
3383 ToolCall {
3384 id: id.into(),
3385 kind: "function".into(),
3386 function: FunctionCall {
3387 name: name.into(),
3388 arguments: args.into(),
3389 },
3390 }
3391 }
3392
3393 fn transcript(store: &SessionStore, id: &str) {
3395 store.append(id, &Message::user("hello there")).unwrap();
3396 store
3397 .append(
3398 id,
3399 &Message::assistant_tool_calls(
3400 Some("let me look".into()),
3401 vec![call("c1", "read_file", r#"{"path":"a.txt"}"#)],
3402 ),
3403 )
3404 .unwrap();
3405 store
3406 .append(id, &Message::tool_result("c1", "file contents"))
3407 .unwrap();
3408 store.append(id, &Message::assistant("done")).unwrap();
3409 }
3410
3411 #[test]
3415 fn a_tool_outcome_is_recorded_beside_the_call_and_read_back() {
3416 let dir = tempfile::tempdir().unwrap();
3417 let store = SessionStore::new(dir.path().to_path_buf());
3418 let id = store.new_id();
3419 store.append(&id, &Message::user("read it")).unwrap();
3420 assert!(
3421 store.tool_outcomes(&id).unwrap().is_empty(),
3422 "nothing recorded is an empty map, not an error"
3423 );
3424
3425 store.set_tool_outcome(&id, "c1", true).unwrap();
3426 store.set_tool_outcome(&id, "c2", false).unwrap();
3427 store.set_tool_outcome(&id, "c1", true).unwrap();
3428
3429 let marks = store.tool_outcomes(&id).unwrap();
3430 assert_eq!(
3431 marks.len(),
3432 2,
3433 "the second write is the same write: {marks:?}"
3434 );
3435 assert_eq!(marks.get("c1"), Some(&true));
3436 assert_eq!(marks.get("c2"), Some(&false));
3437 }
3438
3439 fn seed(store: &SessionStore, id: &str, updated_ms: u64) {
3441 store
3442 .with_db(|db| {
3443 db.conn.execute(
3444 "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
3445 VALUES (?1, ?2, ?2, NULL, 'seeded', 1, 'native')",
3446 params![id, updated_ms as i64],
3447 )?;
3448 Ok(())
3449 })
3450 .unwrap();
3451 }
3452
3453 fn legacy_file(dir: &Path, id: &str, body: &str) -> PathBuf {
3454 std::fs::create_dir_all(dir).unwrap();
3455 let path = dir.join(format!("{id}.jsonl"));
3456 std::fs::write(&path, body).unwrap();
3457 path
3458 }
3459
3460 fn line(m: &Message, ts: u64) -> String {
3461 let rec = Record {
3462 ts,
3463 message: m.clone(),
3464 };
3465 format!("{}\n", serde_json::to_string(&rec).unwrap())
3466 }
3467
3468 #[test]
3469 fn append_and_load_round_trip() {
3470 let dir = tempfile::tempdir().unwrap();
3471 let store = store(dir.path());
3472 let id = store.new_id();
3473 assert!(!store.exists(&id), "a store knows only what was written");
3474 transcript(&store, &id);
3475 assert!(store.exists(&id));
3476
3477 let messages = store.load(&id).unwrap();
3478 assert_eq!(messages.len(), 4);
3479 assert_eq!(messages[0], Message::user("hello there"));
3480 assert_eq!(messages[1].tool_calls.len(), 1);
3481 assert_eq!(messages[1].tool_calls[0].function.name, "read_file");
3482 assert_eq!(messages[1].content.as_deref(), Some("let me look"));
3483 assert_eq!(messages[2].tool_call_id.as_deref(), Some("c1"));
3484 assert_eq!(messages[2].content.as_deref(), Some("file contents"));
3485 assert_eq!(messages[3], Message::assistant("done"));
3486 }
3487
3488 #[test]
3489 fn every_message_is_one_row_in_order() {
3490 let dir = tempfile::tempdir().unwrap();
3491 let store = store(dir.path());
3492 let id = store.new_id();
3493 transcript(&store, &id);
3494 let records = store.load_records(&id).unwrap();
3495 let seqs: Vec<usize> = store
3496 .with_db(|db| {
3497 let mut stmt = db
3498 .conn
3499 .prepare("SELECT seq FROM messages WHERE session_id = ?1 ORDER BY seq")?;
3500 let rows = stmt.query_map(params![id], |r| r.get::<_, i64>(0))?;
3501 Ok(rows
3502 .collect::<std::result::Result<Vec<_>, _>>()?
3503 .into_iter()
3504 .map(|s| s as usize)
3505 .collect())
3506 })
3507 .unwrap();
3508 assert_eq!(seqs, [0, 1, 2, 3], "sequence numbers are dense and ordered");
3509 assert_eq!(records.len(), 4);
3510 assert!(
3511 records.windows(2).all(|w| w[0].ts <= w[1].ts),
3512 "timestamps do not run backwards"
3513 );
3514 }
3515
3516 #[test]
3517 fn data_survives_a_new_store_handle() {
3518 let dir = tempfile::tempdir().unwrap();
3519 let id;
3520 {
3521 let first = store(dir.path());
3522 id = first.new_id();
3523 transcript(&first, &id);
3524 first.rename(&id, "kept title").unwrap();
3525 }
3526 let second = store(dir.path());
3527 assert_eq!(second.load(&id).unwrap().len(), 4);
3528 assert_eq!(second.title(&id).unwrap().as_deref(), Some("kept title"));
3529 }
3530
3531 #[test]
3532 fn list_orders_newest_first_with_preview() {
3533 let dir = tempfile::tempdir().unwrap();
3534 let store = store(dir.path());
3535 let a = store.new_id();
3536 store
3537 .append(&a, &Message::user("the older question"))
3538 .unwrap();
3539 std::thread::sleep(std::time::Duration::from_millis(5));
3540 let b = store.new_id();
3541 store
3542 .append(&b, &Message::user("the newer question"))
3543 .unwrap();
3544
3545 let list = store.list().unwrap();
3546 assert_eq!(list.len(), 2);
3547 assert_eq!(list[0].id, b, "newest first");
3548 assert_eq!(list[0].preview, "the newer question");
3549 assert_eq!(list[0].messages, 1);
3550 assert_eq!(list[1].id, a);
3551 assert_eq!(list[0].label(), "the newer question");
3552 }
3553
3554 #[test]
3555 fn the_preview_is_the_first_user_message_not_the_latest() {
3556 let dir = tempfile::tempdir().unwrap();
3557 let store = store(dir.path());
3558 let id = store.new_id();
3559 store.append(&id, &Message::user("first thing")).unwrap();
3560 store.append(&id, &Message::user("second thing")).unwrap();
3561 let info = store.list().unwrap().into_iter().next().unwrap();
3562 assert_eq!(info.preview, "first thing");
3563 assert_eq!(info.messages, 2);
3564 }
3565
3566 #[test]
3567 fn prune_candidates_by_age_and_count() {
3568 let dir = tempfile::tempdir().unwrap();
3569 let store = store(dir.path());
3570 let now = 1_700_000_000_000u64;
3571 let day = 86_400_000u64;
3572 seed(&store, "old", now - 10 * day);
3573 seed(&store, "mid", now - 2 * day);
3574 seed(&store, "new", now - day / 24);
3575
3576 assert_eq!(
3577 store.prune_candidates(3, 0, now, false).unwrap().candidates,
3578 ["old"],
3579 "older than three days"
3580 );
3581 assert_eq!(
3582 store.prune_candidates(0, 2, now, false).unwrap().candidates,
3583 ["old"],
3584 "all but the newest two"
3585 );
3586 let both = store.prune_candidates(3, 10, now, false).unwrap();
3587 assert_eq!(
3588 both.candidates,
3589 ["old"],
3590 "a session selected by either rule is pruned once"
3591 );
3592 assert!(store
3593 .prune_candidates(0, 0, now, false)
3594 .unwrap()
3595 .candidates
3596 .is_empty());
3597 }
3598
3599 #[test]
3600 fn a_pinned_session_sorts_first_and_is_never_a_prune_candidate() {
3601 let dir = tempfile::tempdir().unwrap();
3602 let store = store(dir.path());
3603 let now = 1_700_000_000_000u64;
3604 seed(&store, "oldest", now - 10 * 86_400_000);
3605 seed(&store, "newest", now - 86_400_000);
3606
3607 store.set_pinned("oldest", true).unwrap();
3608 let list = store.list().unwrap();
3609 assert_eq!(list[0].id, "oldest", "pinned first, whatever the age");
3610 assert!(list[0].pinned);
3611 assert!(!list[1].pinned);
3612
3613 let plan = store.prune_candidates(7, 0, now, false).unwrap();
3615 assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
3616 assert_eq!(plan.pinned_kept, 1);
3617
3618 let outcome = store.auto_prune(7, 0, now, None).unwrap();
3620 assert_eq!(outcome, AutoPrune::Nothing);
3621 assert!(store.exists("oldest"));
3622
3623 store.set_pinned("oldest", false).unwrap();
3624 assert_eq!(
3625 store.prune_candidates(7, 0, now, false).unwrap().candidates,
3626 ["oldest"]
3627 );
3628 assert!(!store.list().unwrap()[0].pinned, "unpinning is not sticky");
3629 }
3630
3631 #[test]
3635 fn an_archived_session_leaves_the_list_and_stays_in_the_search() {
3636 let dir = tempfile::tempdir().unwrap();
3637 let store = store(dir.path());
3638 let now = 1_700_000_000_000u64;
3639 seed(&store, "kept", now - 86_400_000);
3640 seed(&store, "filed", now - 10 * 86_400_000);
3641 store.rename("filed", "the nginx migration").unwrap();
3642 store
3643 .append("filed", &Message::user("the zfs pool was rebuilt"))
3644 .unwrap();
3645 store
3648 .with_db(|db| {
3649 db.conn.execute(
3650 "UPDATE sessions SET updated_ms = ?2 WHERE id = ?1",
3651 params!["filed", (now - 10 * 86_400_000) as i64],
3652 )?;
3653 Ok(())
3654 })
3655 .unwrap();
3656
3657 store.set_archived("filed", true).unwrap();
3658
3659 let listed = store.list().unwrap();
3661 assert_eq!(listed.len(), 1);
3662 assert_eq!(listed[0].id, "kept");
3663 let all = store.list_with_archived().unwrap();
3664 assert_eq!(all.len(), 2);
3665 assert!(all.iter().find(|s| s.id == "filed").unwrap().archived);
3666 assert!(!all.iter().find(|s| s.id == "kept").unwrap().archived);
3667
3668 assert!(
3671 store
3672 .search("nginx", 20)
3673 .unwrap()
3674 .iter()
3675 .any(|h| h.session_id == "filed"),
3676 "a name hit survives archiving"
3677 );
3678 assert!(
3679 store
3680 .search("zfs", 20)
3681 .unwrap()
3682 .iter()
3683 .any(|h| h.session_id == "filed"),
3684 "a message hit survives archiving"
3685 );
3686 assert_eq!(
3687 store.load("filed").unwrap().len(),
3688 1,
3689 "the transcript is there"
3690 );
3691
3692 let plan = store.prune_candidates(7, 0, now, false).unwrap();
3694 assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
3695 assert_eq!(plan.archived_kept, 1);
3696 assert_eq!(
3697 plan.pinned_kept, 0,
3698 "counted apart, so the sentence can differ"
3699 );
3700 assert_eq!(
3701 store.prune_candidates(7, 0, now, true).unwrap().candidates,
3702 ["filed"]
3703 );
3704 assert_eq!(
3706 store.auto_prune(7, 0, now, None).unwrap(),
3707 AutoPrune::Nothing
3708 );
3709
3710 store.set_archived("filed", false).unwrap();
3712 assert_eq!(store.list().unwrap().len(), 2);
3713 assert!(matches!(
3714 store.set_archived("nope", true),
3715 Err(Error::Session(_))
3716 ));
3717 }
3718
3719 #[test]
3722 fn a_database_from_before_archiving_gains_the_column_in_place() {
3723 let dir = tempfile::tempdir().unwrap();
3724 {
3725 let dir = dir.path().join("sessions");
3726 std::fs::create_dir_all(&dir).unwrap();
3727 let conn = Connection::open(dir.join(DB_FILE)).unwrap();
3728 conn.execute_batch(
3729 "CREATE TABLE sessions (
3730 id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
3731 title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
3732 origin TEXT NOT NULL DEFAULT 'native');
3733 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
3734 VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
3735 )
3736 .unwrap();
3737 }
3738 let store = store(dir.path());
3739 let list = store.list().unwrap();
3740 assert_eq!(
3741 list.len(),
3742 1,
3743 "the old row is in the list, not archived by omission"
3744 );
3745 assert!(!list[0].archived);
3746 store.set_archived("s1", true).unwrap();
3747 assert!(store.list().unwrap().is_empty());
3748 assert!(store.list_with_archived().unwrap()[0].archived);
3749 }
3750
3751 #[test]
3752 fn a_database_from_before_pinning_gains_the_column_in_place() {
3753 let dir = tempfile::tempdir().unwrap();
3754 let id;
3755 {
3756 let dir = dir.path().join("sessions");
3759 std::fs::create_dir_all(&dir).unwrap();
3760 let conn = Connection::open(dir.join(DB_FILE)).unwrap();
3761 conn.execute_batch(
3762 "CREATE TABLE sessions (
3763 id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
3764 title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
3765 origin TEXT NOT NULL DEFAULT 'native');
3766 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
3767 VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
3768 )
3769 .unwrap();
3770 id = "s1".to_string();
3771 }
3772 let store = store(dir.path());
3773 let list = store.list().unwrap();
3774 assert_eq!(list.len(), 1, "the old row still reads");
3775 assert_eq!(list[0].id, id);
3776 assert!(!list[0].pinned, "an old row is not pinned");
3777 store.set_pinned(&id, true).unwrap();
3778 assert!(store.list().unwrap()[0].pinned);
3779 assert_eq!(
3780 store
3781 .prune_candidates(0, 1, 1_700_000_000_000, false)
3782 .unwrap(),
3783 PrunePlan::default(),
3784 "one session, newest one kept"
3785 );
3786 }
3787
3788 #[test]
3789 fn a_database_from_before_the_cost_record_gains_the_column_in_place() {
3790 let dir = tempfile::tempdir().unwrap();
3791 {
3792 let dir = dir.path().join("sessions");
3793 std::fs::create_dir_all(&dir).unwrap();
3794 let conn = Connection::open(dir.join(DB_FILE)).unwrap();
3795 conn.execute_batch(
3796 "CREATE TABLE sessions (
3797 id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
3798 title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
3799 origin TEXT NOT NULL DEFAULT 'native');
3800 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
3801 VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
3802 )
3803 .unwrap();
3804 }
3805 let store = store(dir.path());
3806 assert!(
3807 store.last_cost("s1").unwrap().is_none(),
3808 "an old row has no turn behind it, and no record is not a zero"
3809 );
3810 let prompt = 1_234_u64;
3811 let cost = TurnCost {
3812 at_ms: 7,
3813 ctx: "ctx 1.2K/8K ░░░░░░░░░░│░ 15%".to_string(),
3814 prompt_tokens: Some(prompt),
3815 ..TurnCost::default()
3816 };
3817 store.set_last_cost("s1", &cost).unwrap();
3818 assert_eq!(store.last_cost("s1").unwrap(), Some(cost));
3819 }
3820
3821 #[test]
3826 fn a_turn_writes_its_cost_and_the_listing_reads_it_back() {
3827 let dir = tempfile::tempdir().unwrap();
3828 let store = store(dir.path());
3829 let id = store.new_id();
3830 transcript(&store, &id);
3831 assert!(
3832 store.list().unwrap()[0].cost.is_none(),
3833 "a session with no finished turn has nothing to say about one"
3834 );
3835 let prompt = 30_000_u64;
3836 let cached = 28_000_u64;
3837 let cost = TurnCost {
3838 at_ms: 1_700_000_000_000,
3839 ctx: "ctx 30K/262K ██░░░░░░░░│░ 11%".to_string(),
3840 prompt_tokens: Some(prompt),
3841 completion_tokens: Some(400),
3842 cached_tokens: Some(cached),
3843 ttft_ms: Some(800),
3844 latency_ms: Some(13_000),
3845 tokens_per_sec: Some(63.0),
3846 window_tokens: Some(262_144),
3847 };
3848 store.set_last_cost(&id, &cost).unwrap();
3849 let listed = &store.list().unwrap()[0];
3850 assert_eq!(listed.cost.as_ref(), Some(&cost));
3851 let ctx = listed
3852 .cost
3853 .as_ref()
3854 .map(|c| c.ctx.as_str())
3855 .unwrap_or_default();
3856 assert!(
3857 ctx.contains("262K"),
3858 "the denominator the listing carries is the one that turn ran against: {ctx:?}"
3859 );
3860 }
3861
3862 #[test]
3865 fn recording_a_cost_does_not_move_the_session_up_the_list() {
3866 let dir = tempfile::tempdir().unwrap();
3867 let store = store(dir.path());
3868 let older = store.new_id();
3869 let newer = store.new_id();
3870 transcript(&store, &older);
3871 transcript(&store, &newer);
3872 let before: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
3873 let target = before.last().expect("two sessions").clone();
3874 store
3875 .set_last_cost(
3876 &target,
3877 &TurnCost {
3878 at_ms: 1,
3879 ctx: "ctx --".to_string(),
3880 ..TurnCost::default()
3881 },
3882 )
3883 .unwrap();
3884 let after: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
3885 assert_eq!(
3886 before, after,
3887 "the order is the store's, and a cost is not a move"
3888 );
3889 }
3890
3891 #[test]
3894 fn a_persons_name_outranks_the_machines_and_outlives_a_later_attempt() {
3895 let dir = tempfile::tempdir().unwrap();
3896 let store = store(dir.path());
3897 let id = store.new_id();
3898 transcript(&store, &id);
3899
3900 assert!(
3901 store.title_if_unnamed(&id, "the opening message").unwrap(),
3902 "nothing names it yet, so the derived name lands"
3903 );
3904 assert!(
3905 !store
3906 .title_if_unnamed(&id, "a second derived name")
3907 .unwrap(),
3908 "stage one never relabels a session it has already named"
3909 );
3910 assert_eq!(
3911 store.title(&id).unwrap().as_deref(),
3912 Some("the opening message")
3913 );
3914
3915 assert!(
3916 store
3917 .set_title(&id, "the model's name", TitleSource::Llm)
3918 .unwrap(),
3919 "a model name replaces a derived one"
3920 );
3921 assert!(
3922 !store
3923 .set_title(&id, "a second model name", TitleSource::Llm)
3924 .unwrap(),
3925 "one naming call means one name: it is not renamed by trying again"
3926 );
3927
3928 store.rename(&id, "what I called it").unwrap();
3929 for source in [TitleSource::Llm, TitleSource::Derived] {
3930 assert!(
3931 !store.set_title(&id, "the machine again", source).unwrap(),
3932 "a person's name is final to {source:?}"
3933 );
3934 }
3935 assert_eq!(
3936 store.title(&id).unwrap().as_deref(),
3937 Some("what I called it")
3938 );
3939 assert_eq!(
3940 store.list().unwrap()[0].label(),
3941 "what I called it",
3942 "and the listing shows it"
3943 );
3944 }
3945
3946 #[test]
3950 fn the_naming_attempt_is_claimed_once_per_session() {
3951 let dir = tempfile::tempdir().unwrap();
3952 let store = store(dir.path());
3953 let id = store.new_id();
3954 transcript(&store, &id);
3955 store.title_if_unnamed(&id, "a derived name").unwrap();
3956
3957 assert!(
3958 store.claim_title_upgrade(&id).unwrap(),
3959 "the first caller owns it"
3960 );
3961 assert!(
3962 !store.claim_title_upgrade(&id).unwrap(),
3963 "and nobody else does"
3964 );
3965 store
3966 .title_attempt_failed(&id, "the reply was not a JSON object")
3967 .unwrap();
3968 assert!(
3969 !store.claim_title_upgrade(&id).unwrap(),
3970 "a refused answer is not retried on the next run"
3971 );
3972 assert_eq!(
3973 store.title(&id).unwrap().as_deref(),
3974 Some("a derived name"),
3975 "and the name is still there: a failure never leaves it empty"
3976 );
3977
3978 let other = store.new_id();
3980 transcript(&store, &other);
3981 store.title_if_unnamed(&other, "another name").unwrap();
3982 assert!(store.claim_title_upgrade(&other).unwrap());
3983 store.release_title_claim(&other).unwrap();
3984 assert!(
3985 store.claim_title_upgrade(&other).unwrap(),
3986 "released, not failed"
3987 );
3988 }
3989
3990 #[test]
3993 fn a_delegated_child_session_is_never_named_by_a_call() {
3994 let dir = tempfile::tempdir().unwrap();
3995 let store = store(dir.path());
3996 let parent = store.new_id();
3997 let child = store.new_id();
3998 store.append(&parent, &Message::user("big job")).unwrap();
3999 store.begin_subagent(&child, &parent, "fast").unwrap();
4000 store
4001 .append(&child, &Message::user("summarise this"))
4002 .unwrap();
4003 store.title_if_unnamed(&child, "summarise this").unwrap();
4004 assert!(
4005 !store.claim_title_upgrade(&child).unwrap(),
4006 "a child is named by its opening message and left alone"
4007 );
4008
4009 let api = store.new_id();
4010 store.begin_api(&api).unwrap();
4011 store.append(&api, &Message::user("headless turn")).unwrap();
4012 store.title_if_unnamed(&api, "headless turn").unwrap();
4013 assert!(
4014 !store.claim_title_upgrade(&api).unwrap(),
4015 "a headless API session is named for free and never costs a call"
4016 );
4017 }
4018
4019 #[test]
4022 fn a_search_finds_a_session_by_the_name_it_was_given() {
4023 let dir = tempfile::tempdir().unwrap();
4024 let store = store(dir.path());
4025 let id = store.new_id();
4026 store
4027 .append(&id, &Message::user("something else entirely"))
4028 .unwrap();
4029 store.append(&id, &Message::assistant("noted")).unwrap();
4030 store.rename(&id, "gateway restart loop").unwrap();
4031
4032 for fts in [true, false] {
4033 let hits = store
4036 .with_db(|db| SessionStore::search_in(db, "restart loop", 10, fts, false))
4037 .unwrap();
4038 let named: Vec<_> = hits.iter().filter(|h| h.role == "title").collect();
4039 assert_eq!(named.len(), 1, "fts={fts}: {:?}", hits);
4040 assert_eq!(named[0].session_id, id);
4041 assert_eq!(named[0].snippet, "gateway restart loop");
4042 assert_eq!(
4043 named[0].seq, 0,
4044 "a name is read from the top of the transcript"
4045 );
4046 }
4047 let hits = store.search("noted", 10).unwrap();
4049 assert!(hits.iter().all(|h| h.role != "title"));
4050 assert_eq!(hits.len(), 1);
4051 }
4052
4053 #[test]
4057 fn a_page_of_the_tools_own_calls_does_not_hide_the_match_behind_them() {
4058 let dir = tempfile::tempdir().unwrap();
4059 let store = store(dir.path());
4060 let id = store.new_id();
4061 store
4062 .append(&id, &Message::user("the needle is here"))
4063 .unwrap();
4064 for i in 0..12 {
4065 let call = crate::message::ToolCall {
4066 id: format!("call-{i}"),
4067 kind: "function".to_string(),
4068 function: crate::message::FunctionCall {
4069 name: "session_search".to_string(),
4070 arguments: "{\"query\":\"needle\"}".to_string(),
4071 },
4072 };
4073 store
4074 .append(&id, &Message::assistant_tool_calls(None, vec![call]))
4075 .unwrap();
4076 store
4077 .append(
4078 &id,
4079 &Message::tool_result(format!("call-{i}"), "archive: no match for needle"),
4080 )
4081 .unwrap();
4082 }
4083
4084 for fts in [true, false] {
4085 let hits = store
4088 .with_db(|db| SessionStore::search_in(db, "needle", 1, fts, false))
4089 .unwrap();
4090 assert_eq!(hits.len(), 1, "fts={fts}: {hits:?}");
4091 assert_eq!(hits[0].role, "user", "fts={fts}: {hits:?}");
4092 }
4093 }
4094
4095 #[test]
4098 fn a_database_from_before_names_keeps_its_titles_and_learns_who_wrote_them() {
4099 let dir = tempfile::tempdir().unwrap();
4100 {
4101 let dir = dir.path().join("sessions");
4102 std::fs::create_dir_all(&dir).unwrap();
4103 let conn = Connection::open(dir.join(DB_FILE)).unwrap();
4104 conn.execute_batch(
4105 "CREATE TABLE sessions (
4106 id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
4107 title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
4108 origin TEXT NOT NULL DEFAULT 'native', pinned INTEGER NOT NULL DEFAULT 0);
4109 INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
4110 VALUES ('named', 1, 2, 'what I called it', 'first words', 2, 'native'),
4111 ('bare', 1, 2, NULL, 'first words', 2, 'native');",
4112 )
4113 .unwrap();
4114 }
4115 let store = store(dir.path());
4116 let list = store.list().unwrap();
4117 let named = list.iter().find(|s| s.id == "named").unwrap();
4118 assert_eq!(
4119 named.title.as_deref(),
4120 Some("what I called it"),
4121 "the title survives"
4122 );
4123
4124 assert!(
4125 !store.title_if_unnamed("named", "a derived name").unwrap(),
4126 "an old title is a person's, so stage one leaves it"
4127 );
4128 assert!(
4129 !store.claim_title_upgrade("named").unwrap(),
4130 "and no call is spent on it either"
4131 );
4132 assert!(
4133 store.title_if_unnamed("bare", "a derived name").unwrap(),
4134 "a session that had no name gets one"
4135 );
4136 assert_eq!(
4137 store.title("bare").unwrap().as_deref(),
4138 Some("a derived name")
4139 );
4140 }
4141
4142 #[test]
4143 fn deleting_a_session_removes_its_title_memory_and_lock_file() {
4144 let dir = tempfile::tempdir().unwrap();
4145 let root = dir.path().join("sessions");
4146 let store = store(dir.path());
4147 let a = store.new_id();
4148 let b = store.new_id();
4149 transcript(&store, &a);
4150 transcript(&store, &b);
4151 store.rename(&a, "doomed").unwrap();
4152 store
4153 .save_memory(&a, &memory("## Log\na summary", 2, 3))
4154 .unwrap();
4155 store
4156 .with_db(|db| {
4157 db.conn.execute(
4158 "INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, '{}')",
4159 params![a],
4160 )?;
4161 Ok(())
4162 })
4163 .unwrap();
4164 let lock = root.join(format!("{a}.lock"));
4165 std::fs::write(&lock, "pid 1\n").unwrap();
4166
4167 store.delete(&a).unwrap();
4168 assert!(!store.exists(&a));
4169 assert!(store.exists(&b), "the other session is untouched");
4170 assert!(store.load(&b).unwrap().len() == 4);
4171 assert_eq!(store.memory(&a).unwrap(), None);
4172 assert!(!lock.exists(), "the lock file does not outlive the session");
4173 assert!(store.delete(&a).is_err(), "deleting twice is an error");
4174 }
4175
4176 #[test]
4177 fn auto_prune_deletes_up_to_ten_sessions_and_refuses_more() {
4178 let dir = tempfile::tempdir().unwrap();
4179 let store = store(dir.path());
4180 let now = 1_700_000_000_000u64;
4181 for i in 0..12 {
4182 seed(&store, &format!("s{i:02}"), now - (100 - i) * 86_400_000);
4183 }
4184 assert_eq!(
4186 store.auto_prune(30, 0, now, None).unwrap(),
4187 AutoPrune::Skipped { would_remove: 12 }
4188 );
4189 assert_eq!(store.list().unwrap().len(), 12);
4190 assert_eq!(
4192 store.auto_prune(0, 2, now, None).unwrap(),
4193 AutoPrune::Pruned {
4194 removed: 10,
4195 failed: 0,
4196 pinned_kept: 0
4197 }
4198 );
4199 assert_eq!(store.list().unwrap().len(), 2);
4200 }
4201
4202 #[test]
4203 fn auto_prune_never_runs_without_a_limit_and_reports_nothing_to_do() {
4204 let dir = tempfile::tempdir().unwrap();
4205 let store = store(dir.path());
4206 let now = 1_700_000_000_000u64;
4207 assert_eq!(
4208 store.auto_prune(0, 0, now, None).unwrap(),
4209 AutoPrune::NoLimits
4210 );
4211 seed(&store, "fresh", now);
4212 assert_eq!(
4213 store.auto_prune(30, 0, now, None).unwrap(),
4214 AutoPrune::Nothing
4215 );
4216 assert_eq!(store.list().unwrap().len(), 1);
4217 }
4218
4219 #[test]
4220 fn auto_prune_spares_the_protected_session() {
4221 let dir = tempfile::tempdir().unwrap();
4222 let store = store(dir.path());
4223 let now = 1_700_000_000_000u64;
4224 seed(&store, "keep-me", now - 90 * 86_400_000);
4225 seed(&store, "old-1", now - 90 * 86_400_000);
4226 let outcome = store.auto_prune(7, 0, now, Some("keep-me")).unwrap();
4227 assert_eq!(
4228 outcome,
4229 AutoPrune::Pruned {
4230 removed: 1,
4231 failed: 0,
4232 pinned_kept: 0
4233 }
4234 );
4235 assert!(
4236 store.exists("keep-me"),
4237 "the session being resumed survives"
4238 );
4239 assert!(!store.exists("old-1"));
4240 }
4241
4242 #[test]
4243 fn rejects_path_traversal_ids() {
4244 let dir = tempfile::tempdir().unwrap();
4245 let store = store(dir.path());
4246 for bad in ["../etc/passwd", "a/b", "", "sp ace", "dot.dot"] {
4247 assert!(
4248 store.load(bad).is_err(),
4249 "{bad:?} must be refused before it reaches the database"
4250 );
4251 assert!(!store.exists(bad));
4252 }
4253 }
4254
4255 #[test]
4256 fn a_corrupt_row_is_reported_with_its_session_and_position() {
4257 let dir = tempfile::tempdir().unwrap();
4258 let store = store(dir.path());
4259 let id = store.new_id();
4260 transcript(&store, &id);
4261 store
4262 .with_db(|db| {
4263 db.conn.execute(
4264 "INSERT INTO messages (session_id, seq, at_ms, role, body)
4265 VALUES (?1, 99, 0, 'user', '{not json')",
4266 params![id],
4267 )?;
4268 Ok(())
4269 })
4270 .unwrap();
4271 let err = store.load(&id).unwrap_err().to_string();
4272 assert!(err.contains(&id) && err.contains("99"), "{err}");
4273 }
4274
4275 #[test]
4276 fn new_ids_are_unique() {
4277 let dir = tempfile::tempdir().unwrap();
4278 let store = store(dir.path());
4279 let ids: std::collections::HashSet<String> = (0..50).map(|_| store.new_id()).collect();
4280 assert_eq!(ids.len(), 50);
4281 for id in &ids {
4282 validate_id(id).unwrap();
4283 }
4284 }
4285
4286 #[test]
4287 fn utc_formatting() {
4288 assert_eq!(format_utc(0), "1970-01-01 00:00");
4289 assert_eq!(format_utc(1_700_000_000_000), "2023-11-14 22:13");
4290 }
4291
4292 #[test]
4293 fn rename_sets_title_without_touching_the_transcript() {
4294 let dir = tempfile::tempdir().unwrap();
4295 let store = store(dir.path());
4296 let id = store.new_id();
4297 transcript(&store, &id);
4298 let before = store.load(&id).unwrap();
4299 store.rename(&id, " a name ").unwrap();
4300 assert_eq!(store.title(&id).unwrap().as_deref(), Some("a name"));
4301 assert_eq!(store.load(&id).unwrap(), before);
4302 let listed = store.list().unwrap().into_iter().next().unwrap();
4303 assert_eq!(listed.label(), "a name", "the title wins over the preview");
4304 }
4305
4306 #[test]
4307 fn rename_rejects_bad_titles_and_unknown_sessions() {
4308 let dir = tempfile::tempdir().unwrap();
4309 let store = store(dir.path());
4310 let id = store.new_id();
4311 transcript(&store, &id);
4312 for bad in ["", " "] {
4313 assert!(store.rename(&id, bad).is_err(), "{bad:?}");
4314 }
4315 assert!(store.rename(&id, &"x".repeat(201)).is_err());
4316 assert!(store.rename(&id, "bad\nname").is_err());
4317 assert!(store.rename("no-such-session", "fine").is_err());
4318 assert_eq!(store.title(&id).unwrap(), None);
4319 }
4320
4321 #[test]
4322 fn json_export_is_the_complete_transcript() {
4323 let dir = tempfile::tempdir().unwrap();
4324 let store = store(dir.path());
4325 let id = store.new_id();
4326 transcript(&store, &id);
4327 let out = store.export(&id, ExportFormat::Json).unwrap();
4328 let doc: serde_json::Value = serde_json::from_str(&out).unwrap();
4329 assert_eq!(doc["format"], "eclipse-session/1");
4330 assert_eq!(doc["id"], id);
4331 assert_eq!(doc["messages"].as_array().unwrap().len(), 4);
4332 assert_eq!(doc["messages"][0]["message"]["role"], "user");
4333 assert_eq!(
4334 doc["messages"][1]["message"]["tool_calls"][0]["function"]["name"],
4335 "read_file"
4336 );
4337 assert!(out.ends_with('\n'));
4338 }
4339
4340 #[test]
4341 fn markdown_export_shows_turns_calls_and_results() {
4342 let dir = tempfile::tempdir().unwrap();
4343 let store = store(dir.path());
4344 let id = store.new_id();
4345 transcript(&store, &id);
4346 let out = store.export(&id, ExportFormat::Markdown).unwrap();
4347 assert!(out.contains("# "), "a heading, even without a title: {out}");
4348 assert!(out.contains("## 1. User"));
4349 assert!(out.contains("## 2. Assistant"));
4350 assert!(out.contains("**Tool call** `read_file`"));
4351 assert!(out.contains("## 3. Tool result: read_file"));
4352 assert!(out.contains("```json"), "arguments are pretty-printed");
4353 assert!(!out.contains("no result recorded"), "the call was answered");
4354 }
4355
4356 #[test]
4357 fn markdown_export_uses_the_title() {
4358 let dir = tempfile::tempdir().unwrap();
4359 let store = store(dir.path());
4360 let id = store.new_id();
4361 transcript(&store, &id);
4362 store.rename(&id, "a named session").unwrap();
4363 let out = store.export(&id, ExportFormat::Markdown).unwrap();
4364 assert!(out.starts_with("# a named session\n"), "{out}");
4365 }
4366
4367 const NO_SPAN: (Option<u64>, Option<u64>) = (None, None);
4370
4371 fn handoff(text: &str, turns: usize, messages: usize) -> Handoff {
4372 Handoff {
4373 text: text.into(),
4374 version: crate::compact::VERSION.into(),
4375 covered_turns: turns,
4376 covered_messages: messages,
4377 covered_from: None,
4378 covered_to: None,
4379 generated_at_ms: 1_700_000_000_000,
4380 judgement: None,
4381 }
4382 }
4383
4384 fn memory(text: &str, turns: usize, messages: usize) -> Memory {
4385 Memory {
4386 version: MEMORY_VERSION,
4387 handoff: Some(handoff(text, turns, messages)),
4388 }
4389 }
4390
4391 #[test]
4396 fn a_summary_era_memory_file_loads_with_its_summary_ignored() {
4397 let dir = tempfile::tempdir().unwrap();
4398 let store = store(dir.path());
4399 let id = store.new_id();
4400 transcript(&store, &id);
4401 let v2 = r#"{"version":2,"summary":"old news","covered_turns":2,
4402 "covered_messages":4,"generated_at_ms":1700000000000}"#;
4403 store
4404 .with_db(|db| {
4405 db.conn.execute(
4406 "INSERT INTO memory (session_id, body) VALUES (?1, ?2)",
4407 params![id, v2],
4408 )?;
4409 Ok(())
4410 })
4411 .unwrap();
4412
4413 let m = store.memory(&id).unwrap().unwrap();
4414 assert_eq!(m.schema(), 2, "the file says what wrote it");
4415 assert_eq!(
4416 m.usable_handoff(),
4417 None,
4418 "a summary alone is not a handoff, and there is nothing else to read"
4419 );
4420 assert!(
4421 m.validate().is_err(),
4422 "a record with nothing in it is not memory"
4423 );
4424
4425 store
4426 .save_handoff(
4427 &id,
4428 crate::context::Trimmed {
4429 turns: 2,
4430 messages: 4,
4431 },
4432 NO_SPAN,
4433 "## Log\n[#0]",
4434 None,
4435 )
4436 .unwrap();
4437 let after = store.memory(&id).unwrap().unwrap();
4438 assert_eq!(after.schema(), MEMORY_VERSION, "rewritten at this schema");
4439 assert_eq!(after.handoff.unwrap().text, "## Log\n[#0]");
4440 let raw = store
4441 .with_db(|db| {
4442 Ok(db
4443 .conn
4444 .query_row(
4445 "SELECT body FROM memory WHERE session_id = ?1",
4446 params![id],
4447 |r| r.get::<_, String>(0),
4448 )
4449 .unwrap())
4450 })
4451 .unwrap();
4452 assert!(
4453 !raw.contains("summary"),
4454 "the field a summary-era build wrote is gone from the file: {raw}"
4455 );
4456 }
4457
4458 #[test]
4459 fn saving_a_handoff_replaces_the_document_and_never_the_other_way_round() {
4460 let dir = tempfile::tempdir().unwrap();
4461 let store = store(dir.path());
4462 let id = store.new_id();
4463 transcript(&store, &id);
4464
4465 store
4466 .save_handoff(
4467 &id,
4468 crate::context::Trimmed {
4469 turns: 1,
4470 messages: 2,
4471 },
4472 NO_SPAN,
4473 "## Log\nA",
4474 None,
4475 )
4476 .unwrap();
4477 assert_eq!(
4478 store.readable_memory(&id).unwrap().handoff.unwrap().text,
4479 "## Log\nA"
4480 );
4481
4482 store
4485 .save_handoff(
4486 &id,
4487 crate::context::Trimmed {
4488 turns: 3,
4489 messages: 6,
4490 },
4491 NO_SPAN,
4492 "## Log\nB",
4493 Some(Judgement {
4494 text: "- because the first answer settled it".into(),
4495 model: "aux".into(),
4496 generated_at_ms: 1,
4497 }),
4498 )
4499 .unwrap();
4500 let now = store.readable_memory(&id).unwrap();
4501 let h = now.handoff.unwrap();
4502 assert_eq!(h.text, "## Log\nB");
4503 assert_eq!(h.covered_turns, 3);
4504 assert_eq!(
4505 h.judgement.unwrap().model,
4506 "aux",
4507 "and the judgement travels with the document it belongs to"
4508 );
4509 }
4510
4511 #[test]
4512 fn a_memory_from_a_newer_schema_is_refused_rather_than_half_read() {
4513 let dir = tempfile::tempdir().unwrap();
4514 let store = store(dir.path());
4515 let id = store.new_id();
4516 transcript(&store, &id);
4517 let mut m = memory("## Log\nC", 1, 2);
4518 m.version = MEMORY_VERSION + 1;
4519 let why = m.validate().unwrap_err();
4520 assert!(why.contains("newer than this build"), "{why}");
4521 assert!(
4522 store.save_memory(&id, &m).is_err(),
4523 "a record this build cannot read is not written either"
4524 );
4525 }
4526
4527 #[test]
4531 fn a_memory_too_large_to_read_back_is_refused_at_the_write() {
4532 let dir = tempfile::tempdir().unwrap();
4533 let store = store(dir.path());
4534 let id = store.new_id();
4535 transcript(&store, &id);
4536 let mut big = memory("## Log\n", 1, 2);
4537 big.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize);
4538 let err = store
4539 .save_memory(&id, &big)
4540 .expect_err("a record the reader would refuse is not written");
4541 assert!(err.to_string().contains("record limit"), "{err}");
4542 assert!(
4543 store.memory(&id).unwrap().is_none(),
4544 "nothing was stored, and the row did not become unreadable"
4545 );
4546
4547 let mut fits = memory("## Log\n", 1, 2);
4549 let overhead =
4550 serde_json::to_string(&fits).unwrap().len() - fits.handoff.as_ref().unwrap().text.len();
4551 fits.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize - overhead);
4552 store.save_memory(&id, &fits).expect("the cap itself fits");
4553 assert!(store.readable_memory(&id).is_some(), "and it reads back");
4554 }
4555
4556 #[test]
4560 fn a_handoff_is_its_range_and_not_just_its_counts() {
4561 let mut h = handoff("## Log\nsomeone decided something", 1, 2);
4562 assert!(
4563 !h.covers(1, 2, Some(2), Some(3)),
4564 "a document with no endpoints cannot say which window it described"
4565 );
4566 h.covered_from = Some(0);
4567 h.covered_to = Some(1);
4568 assert!(h.covers(1, 2, Some(0), Some(1)));
4569 assert!(
4570 !h.covers(1, 2, Some(2), Some(3)),
4571 "the same size and the same counts, a different window"
4572 );
4573 assert!(
4574 !h.covers(1, 2, None, None),
4575 "no endpoints on the caller's side either"
4576 );
4577 h.covered_to = Some(9);
4578 assert!(
4579 !h.covers(1, 2, Some(0), Some(1)),
4580 "the end is part of the range"
4581 );
4582 }
4583
4584 #[test]
4585 fn memory_round_trips_in_its_documented_shape_and_the_database_is_private() {
4586 let dir = tempfile::tempdir().unwrap();
4587 let store = store(dir.path());
4588 let id = store.new_id();
4589 transcript(&store, &id);
4590 store
4591 .save_handoff(
4592 &id,
4593 crate::context::Trimmed {
4594 turns: 2,
4595 messages: 4,
4596 },
4597 NO_SPAN,
4598 "## Log\nthey agreed on the plan",
4599 None,
4600 )
4601 .unwrap();
4602 let raw = store
4603 .with_db(|db| {
4604 Ok(db
4605 .conn
4606 .query_row(
4607 "SELECT body FROM memory WHERE session_id = ?1",
4608 params![id],
4609 |r| r.get::<_, String>(0),
4610 )
4611 .unwrap())
4612 })
4613 .unwrap();
4614 let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
4615 assert_eq!(parsed["version"], MEMORY_VERSION);
4616 assert_eq!(parsed["handoff"]["covered_turns"], 2);
4617 assert_eq!(parsed["handoff"]["text"], "## Log\nthey agreed on the plan");
4618 #[cfg(unix)]
4619 {
4620 use std::os::unix::fs::PermissionsExt;
4621 let mode = std::fs::metadata(store.dir().join("sessions.db"))
4622 .unwrap()
4623 .permissions()
4624 .mode()
4625 & 0o777;
4626 assert_eq!(
4627 mode, 0o600,
4628 "the database is owner-only, like the transcripts were"
4629 );
4630 let dir_mode = std::fs::metadata(store.dir()).unwrap().permissions().mode() & 0o777;
4634 assert_eq!(dir_mode, 0o700, "the session directory is owner-only");
4635 for sidecar in ["sessions.db-wal", "sessions.db-shm"] {
4636 let p = store.dir().join(sidecar);
4637 if !p.exists() {
4638 continue;
4639 }
4640 let m = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777;
4641 assert_eq!(m, 0o600, "{sidecar} is owner-only");
4642 }
4643 }
4644 }
4645
4646 #[test]
4647 fn memory_validation_rejects_nonsense() {
4648 let dir = tempfile::tempdir().unwrap();
4649 let store = store(dir.path());
4650 let id = store.new_id();
4651 transcript(&store, &id);
4652 let empty = Memory {
4653 version: MEMORY_VERSION,
4654 handoff: None,
4655 };
4656 assert!(empty.validate().is_err() && store.save_memory(&id, &empty).is_err());
4657 let mut m = memory(" padded ", 1, 1);
4658 assert!(m.validate().is_err(), "an untrimmed document is refused");
4659 m = memory("fine", 2, 1);
4660 assert!(m.validate().is_err(), "messages < turns is nonsense");
4661 m.handoff.as_mut().unwrap().covered_messages = 2;
4662 m.handoff.as_mut().unwrap().covered_turns = 0;
4663 assert!(m.validate().is_err(), "covering no turn is nonsense");
4664 m = memory("", 1, 2);
4665 assert!(m.validate().is_err(), "an empty document is not memory");
4666 let mut m = memory("fine", 2, 4);
4667 m.handoff.as_mut().unwrap().judgement = Some(Judgement {
4668 text: "\n- untrimmed".into(),
4669 model: "aux".into(),
4670 generated_at_ms: 1,
4671 });
4672 assert!(m.validate().is_err(), "an untrimmed judgement is refused");
4673 assert!(store.save_memory(&id, &memory("fine", 2, 4)).is_ok());
4674 }
4675
4676 #[test]
4677 fn corrupt_or_invalid_memory_is_not_usable() {
4678 let dir = tempfile::tempdir().unwrap();
4679 let store = store(dir.path());
4680 let id = store.new_id();
4681 transcript(&store, &id);
4682 store
4683 .with_db(|db| {
4684 db.conn.execute(
4685 "INSERT INTO memory (session_id, body) VALUES (?1, 'not json')",
4686 params![id],
4687 )?;
4688 Ok(())
4689 })
4690 .unwrap();
4691 assert!(
4692 store.memory(&id).is_err(),
4693 "corruption is reported, not hidden"
4694 );
4695 assert_eq!(store.readable_memory(&id), None, "and never used");
4696
4697 store
4698 .save_memory(&id, &memory("valid again", 1, 1))
4699 .unwrap();
4700 assert!(store.readable_memory(&id).is_some());
4701 }
4702
4703 #[test]
4704 fn memory_is_per_session() {
4705 let dir = tempfile::tempdir().unwrap();
4706 let store = store(dir.path());
4707 let a = store.new_id();
4708 let b = store.new_id();
4709 store.append(&a, &Message::user("a")).unwrap();
4710 store.append(&b, &Message::user("b")).unwrap();
4711 store.save_memory(&a, &memory("about a", 1, 1)).unwrap();
4712 assert!(store.memory(&b).unwrap().is_none());
4713 assert_eq!(
4714 store.readable_memory(&a).unwrap().handoff.unwrap().text,
4715 "about a"
4716 );
4717 }
4718
4719 #[test]
4720 fn delete_and_prune_remove_the_memory_too() {
4721 let dir = tempfile::tempdir().unwrap();
4722 let store = store(dir.path());
4723 let id = store.new_id();
4724 transcript(&store, &id);
4725 store
4726 .save_memory(&id, &memory("gone with it", 1, 1))
4727 .unwrap();
4728 store.delete(&id).unwrap();
4729 assert!(
4730 store.load_records(&id).is_err(),
4731 "the session is gone, not empty"
4732 );
4733 assert_eq!(store.memory(&id).unwrap(), None);
4734 }
4735
4736 #[test]
4739 fn a_deleted_legacy_session_does_not_come_back() {
4740 let dir = tempfile::tempdir().unwrap();
4741 let root = dir.path().join("sessions");
4742 let path = legacy_file(
4743 &root,
4744 "deleted-me",
4745 &line(&Message::user("doomed"), 1_700_000_000_000),
4746 );
4747 let store = SessionStore::new(&root);
4748 assert!(store.exists("deleted-me"));
4749 store.delete("deleted-me").unwrap();
4750 assert!(!path.exists(), "the imported source goes with the session");
4751 drop(store);
4752
4753 let again = SessionStore::new(&root);
4755 assert!(
4756 !again.exists("deleted-me"),
4757 "a deleted session must stay deleted across restarts"
4758 );
4759 assert!(again.list().unwrap().is_empty());
4760 }
4761
4762 #[test]
4763 fn a_legacy_transcript_is_imported_once_and_the_file_is_kept() {
4764 let dir = tempfile::tempdir().unwrap();
4765 let root = dir.path().join("sessions");
4766 let body = format!(
4767 "{}{}",
4768 line(&Message::user("from the old world"), 1_700_000_000_000),
4769 line(&Message::assistant("and the reply"), 1_700_000_001_000)
4770 );
4771 let path = legacy_file(&root, "legacy-1", &body);
4772 std::fs::write(root.join("legacy-1.meta.json"), r#"{"title":"old title"}"#).unwrap();
4773
4774 let store = SessionStore::new(&root);
4775 let messages = store.load("legacy-1").unwrap();
4776 assert_eq!(messages.len(), 2);
4777 assert_eq!(messages[0].content.as_deref(), Some("from the old world"));
4778 assert_eq!(
4779 store.title("legacy-1").unwrap().as_deref(),
4780 Some("old title")
4781 );
4782 assert!(path.exists(), "importing must not delete the source");
4783
4784 let info = store.list().unwrap().into_iter().next().unwrap();
4785 assert_eq!(info.preview, "from the old world");
4786 assert_eq!(info.updated_ms, 1_700_000_001_000);
4787
4788 drop(store);
4790 let again = SessionStore::new(&root);
4791 assert_eq!(again.load("legacy-1").unwrap().len(), 2);
4792 assert_eq!(again.list().unwrap().len(), 1);
4793 }
4794
4795 #[test]
4796 fn a_truncated_legacy_tail_is_dropped_and_the_rest_is_imported() {
4797 let dir = tempfile::tempdir().unwrap();
4798 let root = dir.path().join("sessions");
4799 let good = line(&Message::user("complete"), 1_700_000_000_000);
4800 let body = format!("{good}{{\"ts\":1,\"message\":{{\"role\":\"user\"");
4801 legacy_file(&root, "half-written", &body);
4802 let store = SessionStore::new(&root);
4803 let messages = store.load("half-written").unwrap();
4804 assert_eq!(messages.len(), 1, "the complete record survived");
4805 assert_eq!(messages[0].content.as_deref(), Some("complete"));
4806 }
4807
4808 #[test]
4809 fn a_complete_final_record_without_a_newline_is_kept() {
4810 let dir = tempfile::tempdir().unwrap();
4811 let root = dir.path().join("sessions");
4812 let body = line(&Message::user("no trailing newline"), 5)
4813 .trim_end()
4814 .to_string();
4815 legacy_file(&root, "unterminated", &body);
4816 let store = SessionStore::new(&root);
4817 assert_eq!(store.load("unterminated").unwrap().len(), 1);
4818 }
4819
4820 #[test]
4821 fn a_legacy_file_corrupt_in_the_middle_is_refused_not_half_imported() {
4822 let dir = tempfile::tempdir().unwrap();
4823 let root = dir.path().join("sessions");
4824 let body = format!(
4825 "{}garbage\n{}",
4826 line(&Message::user("before"), 1),
4827 line(&Message::assistant("after"), 2)
4828 );
4829 let path = legacy_file(&root, "corrupt-mid", &body);
4830 let store = SessionStore::new(&root);
4831 assert!(
4832 !store.exists("corrupt-mid"),
4833 "importing part of it would silently drop a message"
4834 );
4835 assert!(path.exists(), "and the file is left for a human to look at");
4836 assert!(store.list().unwrap().is_empty());
4837 }
4838
4839 #[test]
4840 fn an_empty_legacy_transcript_keeps_its_file_time_not_epoch() {
4841 let dir = tempfile::tempdir().unwrap();
4842 let root = dir.path().join("sessions");
4843 legacy_file(&root, "empty-one", "");
4844 let store = SessionStore::new(&root);
4845 let info = store.list().unwrap().into_iter().next().unwrap();
4846 assert_eq!(info.messages, 0);
4847 assert!(
4848 info.updated_ms > 1_600_000_000_000,
4849 "a corrupt transcript still ages from its mtime, not from 1970: {}",
4850 info.updated_ms
4851 );
4852 }
4853
4854 #[test]
4855 fn a_legacy_memory_sidecar_is_imported() {
4856 let dir = tempfile::tempdir().unwrap();
4857 let root = dir.path().join("sessions");
4858 legacy_file(
4859 &root,
4860 "with-memory",
4861 &line(&Message::user("hi"), 1_700_000_000_000),
4862 );
4863 let m = memory("remembered from before", 2, 4);
4864 std::fs::write(
4865 root.join("with-memory.memory.json"),
4866 serde_json::to_string(&m).unwrap(),
4867 )
4868 .unwrap();
4869 let store = SessionStore::new(&root);
4870 assert_eq!(store.readable_memory("with-memory"), Some(m));
4871 }
4872
4873 #[test]
4874 fn an_unparseable_legacy_memory_sidecar_is_imported_and_reported() {
4875 let dir = tempfile::tempdir().unwrap();
4876 let root = dir.path().join("sessions");
4877 legacy_file(
4878 &root,
4879 "bad-memory",
4880 &line(&Message::user("hi"), 1_700_000_000_000),
4881 );
4882 std::fs::write(
4884 root.join("bad-memory.memory.json"),
4885 r#"{"version":3,"handoff":{"#,
4886 )
4887 .unwrap();
4888 let store = SessionStore::new(&root);
4889 assert!(
4890 store.memory("bad-memory").is_err(),
4891 "an unparseable sidecar is an error to read, not silence"
4892 );
4893 assert_eq!(store.readable_memory("bad-memory"), None);
4894 }
4895
4896 #[test]
4899 fn search_finds_message_text_and_tool_arguments() {
4900 let dir = tempfile::tempdir().unwrap();
4901 let store = store(dir.path());
4902 let id = store.new_id();
4903 store
4904 .append(&id, &Message::user("the deploy key lives in vault"))
4905 .unwrap();
4906 store
4907 .append(
4908 &id,
4909 &Message::assistant_tool_calls(
4910 None,
4911 vec![call("c9", "shell", r#"{"cmd":"systemctl status nginx"}"#)],
4912 ),
4913 )
4914 .unwrap();
4915 let other = store.new_id();
4916 store.append(&other, &Message::user("unrelated")).unwrap();
4917
4918 let hits = store.search("vault", 10).unwrap();
4919 assert_eq!(hits.len(), 1, "{hits:?}");
4920 assert_eq!(hits[0].session_id, id);
4921 assert_eq!(hits[0].seq, 0);
4922 assert_eq!(hits[0].role, "user");
4923 assert!(hits[0].snippet.contains("vault"));
4924
4925 let hits = store.search("nginx", 10).unwrap();
4926 assert_eq!(hits.len(), 1, "tool arguments are searchable: {hits:?}");
4927 assert_eq!(hits[0].seq, 1);
4928
4929 assert!(store.search("nothing-said-this", 10).unwrap().is_empty());
4930 assert!(store.search(" ", 10).unwrap().is_empty());
4931 }
4932
4933 #[test]
4941 fn a_delete_that_fails_halfway_leaves_the_session_alone() {
4942 let dir = tempfile::tempdir().unwrap();
4943 let store = store(dir.path());
4944 let id = store.new_id();
4945 store
4946 .append(&id, &Message::user("an undeletable mention of widget"))
4947 .unwrap();
4948 if !store.with_db(|db| Ok(db.fts)).unwrap() {
4949 return; }
4951 store
4952 .with_db(|db| {
4953 db.conn.execute_batch("DROP TABLE messages_fts")?;
4954 Ok(())
4955 })
4956 .unwrap();
4957
4958 assert!(
4959 store.delete(&id).is_err(),
4960 "the failed delete is reported to the caller"
4961 );
4962
4963 store
4964 .with_db(|db| {
4965 let sessions: i64 = db.conn.query_row(
4966 "SELECT count(*) FROM sessions WHERE id = ?1",
4967 params![id],
4968 |r| r.get(0),
4969 )?;
4970 assert_eq!(
4971 sessions, 1,
4972 "a delete that failed must not have half-happened"
4973 );
4974 let messages: i64 = db.conn.query_row(
4975 "SELECT count(*) FROM messages WHERE session_id = ?1",
4976 params![id],
4977 |r| r.get(0),
4978 )?;
4979 assert_eq!(messages, 1, "its messages are still there too");
4980 Ok(())
4981 })
4982 .unwrap();
4983
4984 assert!(store.delete(&id).is_err());
4986 }
4987
4988 #[test]
4992 fn a_stale_index_row_is_skipped_rather_than_failing_the_search() {
4993 let dir = tempfile::tempdir().unwrap();
4994 let store = store(dir.path());
4995 let id = store.new_id();
4996 store
4997 .append(&id, &Message::user("the live mention of widget"))
4998 .unwrap();
4999
5000 store
5002 .with_db(|db| {
5003 db.conn
5004 .execute("DELETE FROM messages WHERE session_id = ?1", params![id])?;
5005 Ok(())
5006 })
5007 .unwrap();
5008
5009 let hits = store.search("widget", 10).unwrap();
5010 assert!(
5011 hits.is_empty(),
5012 "the orphan is dropped, not fatal: {hits:?}"
5013 );
5014 }
5015
5016 #[test]
5018 fn deleting_a_session_leaves_nothing_of_it_behind() {
5019 let dir = tempfile::tempdir().unwrap();
5020 let store = store(dir.path());
5021 let id = store.new_id();
5022 store
5023 .append(&id, &Message::user("a deletable mention of widget"))
5024 .unwrap();
5025 let keep = store.new_id();
5026 store
5027 .append(&keep, &Message::user("a kept mention of widget"))
5028 .unwrap();
5029
5030 store.delete(&id).unwrap();
5031
5032 store
5033 .with_db(|db| {
5034 let messages: i64 = db.conn.query_row(
5035 "SELECT count(*) FROM messages WHERE session_id = ?1",
5036 params![id],
5037 |r| r.get(0),
5038 )?;
5039 assert_eq!(messages, 0, "messages go with the session");
5040 if db.fts {
5041 let indexed: i64 = db.conn.query_row(
5042 "SELECT count(*) FROM messages_fts WHERE session_id = ?1",
5043 params![id],
5044 |r| r.get(0),
5045 )?;
5046 assert_eq!(indexed, 0, "and so does the index, in the same transaction");
5047 }
5048 Ok(())
5049 })
5050 .unwrap();
5051
5052 let hits = store.search("widget", 10).unwrap();
5053 assert_eq!(hits.len(), 1, "the other session is untouched: {hits:?}");
5054 assert_eq!(hits[0].session_id, keep);
5055 assert!(
5056 store.delete(&id).is_err(),
5057 "deleting it twice still says there is no such session"
5058 );
5059 }
5060
5061 #[test]
5064 fn search_answers_newest_first_whichever_backend_runs() {
5065 let dir = tempfile::tempdir().unwrap();
5066 let store = store(dir.path());
5067 let older = store.new_id();
5068 store
5069 .append(&older, &Message::user("the older mention of gadget"))
5070 .unwrap();
5071 std::thread::sleep(std::time::Duration::from_millis(3));
5074 let newer = store.new_id();
5075 store
5076 .append(&newer, &Message::user("the newer mention of gadget"))
5077 .unwrap();
5078
5079 store
5080 .with_db(|db| {
5081 for use_fts in [true, false] {
5082 if use_fts && !db.fts {
5083 continue;
5084 }
5085 let hits = SessionStore::search_in(db, "gadget", 1, use_fts, false).unwrap();
5086 assert_eq!(hits.len(), 1, "fts={use_fts}");
5087 assert_eq!(
5088 hits[0].session_id, newer,
5089 "a limit of one has to take the newest hit, not the first rowid (fts={use_fts})"
5090 );
5091 }
5092 Ok(())
5093 })
5094 .unwrap();
5095 }
5096
5097 #[test]
5098 fn search_treats_percent_and_underscore_as_text_not_wildcards() {
5099 let dir = tempfile::tempdir().unwrap();
5100 let store = store(dir.path());
5101 let id = store.new_id();
5102 store
5103 .append(&id, &Message::user("disk is 100% full"))
5104 .unwrap();
5105 store
5106 .append(&id, &Message::user("disk is 100 percent full"))
5107 .unwrap();
5108 store
5109 .append(&id, &Message::user("the file a_b.txt is here"))
5110 .unwrap();
5111 store
5112 .append(&id, &Message::user("the file axb.txt is not"))
5113 .unwrap();
5114
5115 store
5119 .with_db(|db| {
5120 let percent = SessionStore::search_in(db, "100%", 10, false, false).unwrap();
5121 assert_eq!(
5122 percent.len(),
5123 1,
5124 "`100%` is a substring, not `100` plus a wildcard: {percent:?}"
5125 );
5126 assert!(percent[0].snippet.contains("100% full"));
5127
5128 let underscore = SessionStore::search_in(db, "a_b.txt", 10, false, false).unwrap();
5129 assert_eq!(
5130 underscore.len(),
5131 1,
5132 "`_` is a character, not any character: {underscore:?}"
5133 );
5134 assert!(underscore[0].snippet.contains("a_b.txt"));
5135 Ok(())
5136 })
5137 .unwrap();
5138 }
5139
5140 #[test]
5143 fn a_like_literal_escapes_every_wildcard_character() {
5144 assert_eq!(like_literal("plain"), "plain");
5145 assert_eq!(like_literal("100%"), r"100\%");
5146 assert_eq!(like_literal("a_b"), r"a\_b");
5147 assert_eq!(like_literal(r"C:\temp"), r"C:\\temp");
5148 }
5149
5150 #[test]
5151 fn search_survives_query_syntax_that_would_break_fts() {
5152 let dir = tempfile::tempdir().unwrap();
5153 let store = store(dir.path());
5154 let id = store.new_id();
5155 store
5156 .append(&id, &Message::user(r#"a "quoted" thing AND (parens)"#))
5157 .unwrap();
5158 for q in [r#""quoted""#, "AND (parens)", "*", "a AND OR NOT", "-x"] {
5160 let _ = store.search(q, 5).unwrap();
5161 }
5162 assert_eq!(store.search("quoted", 5).unwrap().len(), 1);
5163 }
5164
5165 #[test]
5166 fn search_results_carry_the_session_and_position() {
5167 let dir = tempfile::tempdir().unwrap();
5168 let store = store(dir.path());
5169 let id = store.new_id();
5170 transcript(&store, &id);
5171 let hits = store.search("contents", 10).unwrap();
5172 assert_eq!(hits.len(), 1);
5173 assert_eq!(hits[0].session_id, id);
5174 assert_eq!(hits[0].seq, 2, "the tool result is the third message");
5175 assert_eq!(hits[0].role, "tool");
5176 assert!(hits[0].at_ms > 0);
5177 }
5178
5179 #[test]
5180 fn a_subagent_session_says_where_it_came_from_and_a_native_one_does_not() {
5181 let dir = tempfile::tempdir().unwrap();
5182 let store = store(dir.path());
5183 let parent = store.new_id();
5184 let child = store.new_id();
5185 store.append(&parent, &Message::user("big job")).unwrap();
5186 store.begin_subagent(&child, &parent, "big:v2").unwrap();
5187 store.append(&child, &Message::user("sub job")).unwrap();
5188
5189 let list = store.list().unwrap();
5190 let find = |id: &str| list.iter().find(|s| s.id == id).unwrap();
5191 assert_eq!(find(&parent).origin, "native");
5192 assert!(find(&parent).subagent().is_none());
5193 let origin = find(&child).subagent().unwrap();
5194 assert_eq!((origin.parent, origin.route), (parent.as_str(), "big:v2"));
5195 assert_eq!(
5196 find(&child).preview,
5197 "sub job",
5198 "the first message still names it"
5199 );
5200 }
5201
5202 #[test]
5203 fn beginning_a_subagent_twice_keeps_the_first_origin() {
5204 let dir = tempfile::tempdir().unwrap();
5205 let store = store(dir.path());
5206 store.begin_subagent("c1", "p1", "big").unwrap();
5207 store.begin_subagent("c1", "p2", "other").unwrap();
5208 let info = store.list().unwrap().remove(0);
5209 assert_eq!(info.subagent().unwrap().parent, "p1");
5210 assert!(store.begin_subagent("c2", "../p", "big").is_err());
5211 }
5212
5213 #[test]
5216 fn an_api_session_keeps_its_tag_when_the_run_writes_to_it() {
5217 let dir = tempfile::tempdir().unwrap();
5218 let store = store(dir.path());
5219 let id = store.new_id();
5220 store.begin_api(&id).unwrap();
5221 store.append(&id, &Message::user("ask")).unwrap();
5222 store.append(&id, &Message::assistant("answer")).unwrap();
5223
5224 let info = store.list().unwrap().remove(0);
5225 assert_eq!(info.id, id);
5226 assert_eq!(info.origin, SessionStore::API_ORIGIN);
5227 assert!(info.subagent().is_none(), "tagged, not a child");
5228 assert_eq!(info.messages, 2, "and the transcript is really there");
5229 }
5230
5231 #[test]
5234 fn the_sweep_takes_old_api_sessions_and_leaves_the_rest() {
5235 let dir = tempfile::tempdir().unwrap();
5236 let store = store(dir.path());
5237
5238 let old_api = store.new_id();
5239 store.begin_api(&old_api).unwrap();
5240 store.append(&old_api, &Message::user("poll")).unwrap();
5241
5242 let mine = store.new_id();
5243 store
5244 .append(&mine, &Message::user("a real conversation"))
5245 .unwrap();
5246
5247 let pinned_api = store.new_id();
5248 store.begin_api(&pinned_api).unwrap();
5249 store
5250 .append(&pinned_api, &Message::user("keep me"))
5251 .unwrap();
5252 store.set_pinned(&pinned_api, true).unwrap();
5253
5254 let pruned = store.prune_api_sessions(now_ms() + 1).unwrap();
5255 assert_eq!(pruned, 1, "only the API's own, unpinned session");
5256 let left: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
5257 assert!(
5258 left.contains(&mine),
5259 "a conversation is never swept: {left:?}"
5260 );
5261 assert!(left.contains(&pinned_api), "a pin is a decision: {left:?}");
5262 assert!(!left.contains(&old_api), "{left:?}");
5263 }
5264
5265 #[test]
5268 fn the_sweep_is_empty_when_there_is_nothing_the_api_left() {
5269 let dir = tempfile::tempdir().unwrap();
5270 let store = store(dir.path());
5271 store.append("n1", &Message::user("hello")).unwrap();
5272 assert_eq!(store.prune_api_sessions(u64::MAX).unwrap(), 0);
5273 assert_eq!(store.list().unwrap().len(), 1);
5274 }
5275
5276 #[cfg(unix)]
5277 #[tokio::test]
5278 async fn only_a_session_a_live_run_holds_is_reported_as_held() {
5279 let dir = tempfile::tempdir().unwrap();
5280 let store = store(dir.path());
5281 let wait = std::time::Duration::from_millis(0);
5282 let live = store.lock("live", wait).await.unwrap();
5283 drop(store.lock("finished", wait).await.unwrap());
5285
5286 let held = held_locks(store.dir());
5287 assert_eq!(held.len(), 1, "{held:?}");
5288 assert_eq!(held[0].id, "live");
5289 assert!(held[0].holder.starts_with("pid "), "{held:?}");
5290
5291 drop(live);
5292 assert!(held_locks(store.dir()).is_empty());
5293 assert!(held_locks(&dir.path().join("no-such-dir")).is_empty());
5294 }
5295
5296 fn picture_message(text: Option<&str>, name: &str) -> Message {
5297 let mut m = match text {
5298 Some(t) => Message::user(t),
5299 None => Message {
5300 role: Role::User,
5301 content: None,
5302 reasoning: None,
5303 finish_reason: None,
5304 tool_calls: Vec::new(),
5305 tool_call_id: None,
5306 images: Vec::new(),
5307 seq: None,
5308 },
5309 };
5310 m.images.push(crate::message::ImagePart {
5311 name: name.into(),
5312 mime: "image/png".into(),
5313 url: "data:image/png;base64,AAAA".into(),
5314 seen: None,
5315 });
5316 m
5317 }
5318
5319 #[test]
5322 fn describing_a_picture_reports_whether_it_changed_anything() {
5323 let dir = tempfile::tempdir().unwrap();
5324 let store = SessionStore::new(dir.path().to_path_buf());
5325 let id = store.new_id();
5326 let seq = store
5327 .append_seq(&id, &picture_message(Some("look"), "shot.png"))
5328 .unwrap();
5329 assert!(
5330 store
5331 .set_image_seen(&id, seq as u64, 0, "a dashboard with a red chart")
5332 .unwrap(),
5333 "a picture that is there was described"
5334 );
5335 let hits = store.search("red chart", 5).unwrap();
5337 assert_eq!(hits.len(), 1, "the description is searchable: {hits:?}");
5338 assert!(store.set_image_seen(&id, seq as u64, 0, "again").unwrap());
5340 assert!(
5342 !store.set_image_seen(&id, 999, 0, "nowhere").unwrap(),
5343 "a missing row used to answer Ok(()) — a caller could not tell it from a write"
5344 );
5345 assert!(!store.set_image_seen(&id, seq as u64, 7, "no").unwrap());
5347 }
5348
5349 #[test]
5352 fn a_first_message_with_no_text_does_not_freeze_the_preview() {
5353 let dir = tempfile::tempdir().unwrap();
5354 let store = SessionStore::new(dir.path().to_path_buf());
5355 let id = store.new_id();
5356 store
5359 .append(&id, &picture_message(Some(""), "shot.png"))
5360 .unwrap();
5361 store
5362 .append(&id, &Message::user("actually, summarise yesterday"))
5363 .unwrap();
5364 let listed = store.list().unwrap();
5365 let row = listed.iter().find(|s| s.id == id).expect("listed");
5366 assert_eq!(
5367 row.preview.as_str(),
5368 "actually, summarise yesterday",
5369 "the first empty row took the preview: {:?}",
5370 row.preview
5371 );
5372 }
5373
5374 #[test]
5382 fn a_bot_conversation_is_not_in_the_humans_list() {
5383 let dir = tempfile::tempdir().unwrap();
5384 let store = store(dir.path());
5385 let mine = store.new_id();
5386 store
5387 .append(&mine, &Message::user("the human asked this"))
5388 .unwrap();
5389 let theirs = store.bot_session("nox").unwrap();
5390 store
5391 .append(&theirs, &Message::user("the bot said this"))
5392 .unwrap();
5393
5394 let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
5395 assert_eq!(
5396 listed,
5397 vec![mine.clone()],
5398 "a bot's conversation left the sidebar alone"
5399 );
5400
5401 let archived: Vec<String> = store
5403 .list_with_archived()
5404 .unwrap()
5405 .into_iter()
5406 .map(|s| s.id)
5407 .collect();
5408 assert_eq!(archived, vec![mine], "`show archived` is not `show bots`");
5409 }
5410
5411 #[test]
5412 fn list_bots_groups_every_conversation_under_its_name() {
5413 let dir = tempfile::tempdir().unwrap();
5414 let store = store(dir.path());
5415 let first = store.bot_session("nox").unwrap();
5416 store.append(&first, &Message::user("one")).unwrap();
5417 for id in store.bot_sessions("nox").unwrap() {
5419 store.set_archived(&id, true).unwrap();
5420 }
5421 let second = store.bot_session("nox").unwrap();
5422 assert_ne!(
5423 first, second,
5424 "a cleared conversation is not the one reopened"
5425 );
5426 store.append(&second, &Message::user("two")).unwrap();
5427
5428 let other = store.bot_session("lux").unwrap();
5430 store.append(&other, &Message::user("three")).unwrap();
5431 let mine = store.new_id();
5432 store.append(&mine, &Message::user("four")).unwrap();
5433
5434 let bots = store.list_bots().unwrap();
5435 assert_eq!(bots.len(), 2, "one row per identity: {bots:?}");
5436 assert_eq!(bots[0].name, "lux", "newest activity first");
5437 let nox = bots.iter().find(|b| b.name == "nox").unwrap();
5438 assert_eq!(nox.sessions, 2, "both conversations counted");
5439 assert_eq!(nox.last_session, second, "the row opens the newest");
5440 assert_eq!(nox.messages, 1);
5441 assert!(
5442 !nox.archived,
5443 "one archived conversation is not a cleared bot"
5444 );
5445 }
5446
5447 #[test]
5452 fn two_sessions_in_the_same_millisecond_are_ordered_by_when_they_were_stored() {
5453 let dir = tempfile::tempdir().unwrap();
5454 let store = store(dir.path());
5455 store.list().unwrap(); let at = 1_796_297_799_945_i64;
5457 let rows = [
5459 ("1796297799945-11001-9", "bot:nox"),
5460 ("1796297799945-11001-10", "bot:nox"),
5461 ("1796297799945-11001-2", "native"),
5462 ("1796297799945-11001-11", "native"),
5463 ];
5464 store
5465 .with_db(|db| {
5466 for (id, origin) in rows {
5467 db.conn.execute(
5468 "INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
5469 VALUES (?1, ?2, ?3, 1, ?4)",
5470 params![id, at, at, origin],
5471 )?;
5472 }
5473 Ok(())
5474 })
5475 .unwrap();
5476
5477 let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
5478 assert_eq!(
5479 listed,
5480 ["1796297799945-11001-11", "1796297799945-11001-2"],
5481 "a tie is broken by which row was stored later, not by its text"
5482 );
5483
5484 let nox = store
5485 .list_bots()
5486 .unwrap()
5487 .into_iter()
5488 .find(|b| b.name == "nox")
5489 .expect("the bot's two conversations");
5490 assert_eq!(nox.sessions, 2);
5491 assert_eq!(
5492 nox.last_session, "1796297799945-11001-10",
5493 "the conversation opened second is the live one"
5494 );
5495 }
5496
5497 #[test]
5498 fn a_search_leaves_a_bots_conversation_out_unless_asked() {
5499 let dir = tempfile::tempdir().unwrap();
5500 let store = store(dir.path());
5501 let mine = store.new_id();
5502 store
5503 .append(&mine, &Message::user("the vault code is in the drawer"))
5504 .unwrap();
5505 let bots = store.bot_session("nox").unwrap();
5506 store
5507 .append(&bots, &Message::user("the vault code is on the lane"))
5508 .unwrap();
5509
5510 let found = store.search("vault", 10).unwrap();
5511 assert_eq!(
5512 found.len(),
5513 1,
5514 "the human's search found a bot's row: {found:?}"
5515 );
5516 assert_eq!(found[0].session_id, mine);
5517
5518 let asked = store.search_with("vault", 10, true).unwrap();
5519 assert_eq!(
5520 asked.len(),
5521 2,
5522 "`bots = true` is how a bot's rows are asked for"
5523 );
5524 assert!(asked.iter().any(|h| h.session_id == bots));
5525
5526 store
5528 .set_title(&bots, "never mention the vault", TitleSource::User)
5529 .unwrap();
5530 let named = store.search("never", 10).unwrap();
5531 assert!(
5532 named.is_empty(),
5533 "a bot's title answered the human's search: {named:?}"
5534 );
5535 let named = store.search_with("never", 10, true).unwrap();
5536 assert_eq!(named.len(), 1);
5537 }
5538
5539 #[test]
5540 fn a_title_is_never_claimed_for_a_bot() {
5541 let dir = tempfile::tempdir().unwrap();
5542 let store = store(dir.path());
5543 let mine = store.new_id();
5544 store.append(&mine, &Message::user("hello")).unwrap();
5545 store
5546 .set_title(&mine, "derived name", TitleSource::Derived)
5547 .unwrap();
5548 assert!(
5549 store.claim_title_upgrade(&mine).unwrap(),
5550 "a person's conversation may be named by a model"
5551 );
5552
5553 let bots = store.bot_session("nox").unwrap();
5554 store.append(&bots, &Message::user("hello")).unwrap();
5555 store
5556 .set_title(&bots, "derived name", TitleSource::Derived)
5557 .unwrap();
5558 assert!(
5559 !store.claim_title_upgrade(&bots).unwrap(),
5560 "a naming call per turn is the cost this rule exists to avoid"
5561 );
5562 }
5563
5564 #[test]
5565 fn a_bot_conversation_says_which_bot_it_belongs_to() {
5566 let dir = tempfile::tempdir().unwrap();
5567 let store = store(dir.path());
5568 let id = store.bot_session("nox").unwrap();
5569 store.append(&id, &Message::user("hello")).unwrap();
5570 assert_eq!(store.origin(&id).unwrap().as_deref(), Some("bot:nox"));
5574
5575 let info = SessionInfo {
5576 id,
5577 messages: 1,
5578 updated_ms: 0,
5579 preview: "hello".into(),
5580 title: None,
5581 origin: "bot:nox".into(),
5582 pinned: false,
5583 archived: false,
5584 cost: None,
5585 };
5586 assert_eq!(info.bot(), Some("nox"));
5587 assert!(info.is_bot());
5588 assert!(info.subagent().is_none());
5589 assert!(
5590 info.tagged_label().starts_with("[bot \u{b7} nox]"),
5591 "{}",
5592 info.tagged_label()
5593 );
5594
5595 let odd = SessionInfo {
5598 origin: "bot:a:b".to_string(),
5599 ..info
5600 };
5601 assert_eq!(odd.bot(), None);
5602 let empty = SessionInfo {
5604 origin: "bot:".to_string(),
5605 ..odd
5606 };
5607 assert_eq!(empty.bot(), None);
5608 }
5609
5610 #[test]
5616 fn a_flare_run_is_a_set_of_sessions_with_their_positions() {
5617 let dir = tempfile::tempdir().unwrap();
5618 let store = store(dir.path());
5619 let run = "f-1";
5620 let mut ids = Vec::new();
5623 for n in [2usize, 1, 3] {
5624 let id = store.new_id();
5625 store.begin_flare(&id, run, n).unwrap();
5626 store
5627 .append(&id, &Message::user(format!("flare {n} reading")))
5628 .unwrap();
5629 ids.push((n, id));
5630 }
5631
5632 let listed = store.flares_of(run).unwrap();
5633 assert_eq!(
5634 listed
5635 .iter()
5636 .filter_map(|s| s.flare().map(|f| f.n))
5637 .collect::<Vec<_>>(),
5638 vec![1, 2, 3],
5639 "the run's order is the lead's order, not the order they finished"
5640 );
5641 assert_eq!(listed[0].flare().unwrap().run, run);
5642 assert!(
5643 listed[0].tagged_label().starts_with("[flare \u{b7} f-1/1]"),
5644 "{}",
5645 listed[0].tagged_label()
5646 );
5647 assert!(listed[0].subagent().is_none());
5649 assert!(!listed[0].is_bot());
5650
5651 let other = store.new_id();
5653 store.begin_flare(&other, "f-2", 1).unwrap();
5654 assert_eq!(store.flares_of(run).unwrap().len(), 3);
5655
5656 let bad = store.new_id();
5658 assert!(store.begin_flare(&bad, "f:1", 1).is_err());
5659 let odd = SessionInfo {
5661 origin: "flare:run:two".into(),
5662 ..listed[0].clone()
5663 };
5664 assert!(odd.flare().is_none());
5665 assert!(SessionInfo {
5666 origin: "flare::1".into(),
5667 ..listed[0].clone()
5668 }
5669 .flare()
5670 .is_none());
5671 }
5672
5673 #[test]
5674 fn a_search_leaves_a_flares_transcript_out_unless_asked() {
5675 let dir = tempfile::tempdir().unwrap();
5676 let store = store(dir.path());
5677 let mine = store.new_id();
5678 store
5679 .append(&mine, &Message::user("the retry loop is in worker.rs"))
5680 .unwrap();
5681 let flare = store.new_id();
5682 store.begin_flare(&flare, "f-9", 1).unwrap();
5683 store
5684 .append(&flare, &Message::user("the retry loop is in pool.rs"))
5685 .unwrap();
5686
5687 let found = store.search("retry", 10).unwrap();
5688 assert_eq!(found.len(), 1, "the human found a flare's row: {found:?}");
5689 assert_eq!(found[0].session_id, mine);
5690
5691 let asked = store.search_with("retry", 10, true).unwrap();
5692 assert_eq!(
5693 asked.len(),
5694 2,
5695 "`children = true` is how those rows are asked for"
5696 );
5697 }
5698
5699 #[test]
5700 fn a_flare_is_never_named_by_a_model() {
5701 let dir = tempfile::tempdir().unwrap();
5702 let store = store(dir.path());
5703 let id = store.new_id();
5704 store.begin_flare(&id, "f-3", 1).unwrap();
5705 store.append(&id, &Message::user("reading")).unwrap();
5706 store
5707 .set_title(&id, "derived name", TitleSource::Derived)
5708 .unwrap();
5709 assert!(
5710 !store.claim_title_upgrade(&id).unwrap(),
5711 "a transient worker does not get a paid naming call"
5712 );
5713 }
5714}