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