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