Skip to main content

eclipse_core/
session.rs

1//! Session storage: one SQLite database per state directory, one row per message.
2//!
3//! Why a database rather than the JSONL files this used to write: listing sessions, finding
4//! one by what was said in it, keeping a title or a memory summary beside it, and pruning by
5//! age are all index problems. Doing them by walking files meant an O(sessions) read of
6//! every transcript to render a list, and sidecar files that could be orphaned by a rename
7//! or a delete. The database is `sessions.db` in the session directory, `0600`, WAL so a
8//! reader never blocks a write.
9//!
10//! Old `.jsonl` transcripts are imported once, in one transaction, and **left on disk**: a
11//! database that turns out to be wrong must never be the reason someone's transcript is
12//! gone. `export` still produces the JSONL shape, which makes it the interchange format.
13
14use crate::error::{Error, Result};
15use crate::message::{Message, Role};
16use rusqlite::{params, Connection, OptionalExtension};
17use serde::{Deserialize, Serialize};
18use std::io::{Seek, SeekFrom, Write};
19use std::path::{Path, PathBuf};
20use std::sync::atomic::{AtomicU64, Ordering};
21use std::sync::{Arc, Mutex};
22use std::time::{SystemTime, UNIX_EPOCH};
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct Record {
26    /// Unix milliseconds.
27    pub ts: u64,
28    pub message: Message,
29}
30
31/// What the last turn on a session cost, kept in the store so a row can be honest about a
32/// session nothing is running any more (#344).
33///
34/// The numbers are a **snapshot of one turn**, not a dimension of the session, which is why they
35/// live in one JSON column rather than a column per counter: the counter set moves (a cache-write
36/// field, reasoning tokens), and a `sessions.db` should not grow a migration every time the usage
37/// struct does. A blob that will not parse reads as absent — the same thing the dashboard shows
38/// for a session that never ran — so a corrupt record can never be mistaken for a measurement.
39///
40/// `ctx` is the server's own string (`eclipse_core::contextbar`), rendered when the turn
41/// finished. Storing the string rather than its inputs is the point: the dashboard paints what
42/// the terminal prints, and neither surface recomputes a denominator (#264).
43#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
44pub struct TurnCost {
45    /// Unix milliseconds, when the turn's accounting was written.
46    pub at_ms: u64,
47    /// `ctx 121K/262K ██████░░░░│░ 46%`, from the reader the CLI uses.
48    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    /// Absent when the model counted nothing or the clock did not move.
60    #[serde(default)]
61    pub tokens_per_sec: Option<f64>,
62    /// The denominator that was in force for that turn — a fact about that model, not about the
63    /// one selected now.
64    #[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    /// Unix milliseconds of the last record (0 if empty/unknown).
73    pub updated_ms: u64,
74    /// First user message, truncated.
75    pub preview: String,
76    /// Name set with `rename`, if any.
77    pub title: Option<String>,
78    /// Where the session came from: `native`, `jsonl` (imported) or `subagent:<parent>:<route>`.
79    pub origin: String,
80    /// Set with `pin`: the session sorts first in every listing and no retention policy
81    /// deletes it.
82    pub pinned: bool,
83    /// Set with `archive`: out of every listing, still in the search, and out of a prune's
84    /// reach unless the prune asks for it (`#240`).
85    pub archived: bool,
86    /// The last turn's numbers, so a row can show what a session cost without a run in flight
87    /// (#344). `None` for a session that has never finished a turn.
88    pub cost: Option<TurnCost>,
89}
90
91/// What a subagent session says about itself: the session whose run started it and the route
92/// it ran on.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct SubagentOrigin<'a> {
95    pub parent: &'a str,
96    pub route: &'a str,
97}
98
99/// One flare run's ledger row (`#171`) — what `flares list` prints and what a cancel addresses.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct FlareRunRow {
102    pub id: String,
103    pub task: String,
104    /// `running`, `done`, `cancelled` or `failed`.
105    pub state: String,
106    /// The routes the run's jobs named, deduplicated, in the order they were asked for.
107    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/// One child of a run, as the ledger keeps it.
124#[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    /// `running`, `done`, `failed` or `dropped`.
131    pub state: String,
132    pub prompt_tokens: Option<u64>,
133    pub completion_tokens: Option<u64>,
134    pub iterations: usize,
135    /// Why a failed or dropped child ended that way, in one line.
136    pub why: Option<String>,
137}
138
139/// One bot's conversations, as the Bots tab reads them (`#509`).
140///
141/// The tab lists identities, not sessions: a bot answering on a lane opens one conversation and
142/// keeps it, so the row is "this bot, last heard from then, this much said". `sessions` counts
143/// every conversation the bot has had — a cleared one is archived, not deleted, and the count is
144/// what says it happened.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct BotSessions {
147    pub name: String,
148    pub sessions: usize,
149    /// Messages in the newest conversation, which is the one the row's label describes.
150    pub messages: usize,
151    /// The newest conversation: what the row opens.
152    pub last_session: String,
153    pub last_activity_ms: u64,
154    /// Every conversation this bot has is archived: it was cleared, and nothing has been said
155    /// since. The row still lists it — an identity does not stop existing because its transcript
156    /// was filed away.
157    pub archived: bool,
158}
159
160/// The prefix of a subagent session's `origin`. Ids contain no `:`, so the parent ends at the
161/// first one after it; a route name may contain anything and is last.
162const SUBAGENT_ORIGIN: &str = "subagent:";
163
164/// The prefix of a bot's session `origin` (`#509`): `bot:<name>`, one name and no parent. The
165/// same shape as `subagent:` on purpose — the store, compaction, search and the cost ledger read
166/// a session by its `origin`, so a bot adds a prefix and a parser, not a table.
167const BOT_ORIGIN: &str = "bot:";
168
169/// The prefix of a flare's session `origin` (`#171`): `flare:<run>:<n>`, the run's id and the
170/// flare's position in it. A run id contains no `:`, so the position is last and parses as a
171/// number — a row whose tail is not one is not a flare this build wrote.
172const FLARE_ORIGIN: &str = "flare:";
173
174/// What a flare session says about itself: the run that started it and its position in that run.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub struct FlareOrigin<'a> {
177    pub run: &'a str,
178    /// 1-based, the order the lead asked for them in — which is how a reader talks about them.
179    pub n: usize,
180}
181
182impl SessionInfo {
183    /// Set when the session is a child that a `delegate` call ran, not a conversation.
184    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    /// The bot whose conversation this is, when it is one (`#509`).
191    ///
192    /// A name with a `:` in it never parses: the name is checked at load for exactly that reason,
193    /// and a row written by something else is not allowed to look like two names.
194    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    /// Whether this session belongs to a bot rather than to the person at the keyboard.
201    pub fn is_bot(&self) -> bool {
202        self.bot().is_some()
203    }
204
205    /// The flare run and position this session belongs to, when it is a flare (`#171`).
206    ///
207    /// The tail must parse as a number: `flare:run:two` is not a flare this build wrote, and
208    /// reading it as one would put a row in a run listing under a position nothing can address.
209    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    /// Whether this session is one worker of a flare run rather than a conversation.
217    pub fn is_flare(&self) -> bool {
218        self.flare().is_some()
219    }
220
221    /// [`label`](Self::label), with `[subagent · route]` in front of a child's, `[bot · name]` in
222    /// front of a bot's and `[flare · run/n]` in front of a flare's — the places that list
223    /// sessions beside conversations and have no room for the parent's id.
224    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    /// What to call the session in listings: its title, else the preview, else the id.
238    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/// Who wrote a session's title. The order is the precedence: a name a person typed is never
248/// replaced, a name a model wrote is replaced only by a person, and the derived name is a
249/// placeholder that either of the other two may take over.
250#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
251pub enum TitleSource {
252    /// [`crate::naming::derive`]: the opening message's first line, written before any call.
253    Derived,
254    /// The one small-model call, when its answer survived `naming::clean_reply`.
255    Llm,
256    /// Typed by a person with `rename` (or the dashboard's ⋮ → rename).
257    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
278/// Pruning more sessions than this at once needs an explicit `--force` (manual prune) and
279/// is refused outright by [`SessionStore::auto_prune`].
280pub const PRUNE_CONFIRM_ABOVE: usize = 10;
281
282/// Result of [`SessionStore::auto_prune`].
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub enum AutoPrune {
285    /// Both retention limits are 0: nothing to apply, nothing deleted.
286    NoLimits,
287    /// The policy selects no session.
288    Nothing,
289    /// Deleted `removed` sessions; `failed` could not be deleted. `pinned_kept` matched the
290    /// policy and was left alone because it is pinned.
291    Pruned {
292        removed: usize,
293        failed: usize,
294        pinned_kept: usize,
295    },
296    /// The policy would remove `would_remove` sessions, more than
297    /// [`PRUNE_CONFIRM_ABOVE`]: nothing was deleted.
298    Skipped { would_remove: usize },
299}
300
301/// What a retention policy would delete, and what it refuses to touch.
302#[derive(Debug, Clone, Default, PartialEq, Eq)]
303pub struct PrunePlan {
304    /// Ids the policy selects, newest first. Nothing is deleted by computing this.
305    pub candidates: Vec<String>,
306    /// How many sessions matched the policy and were kept anyway because they are pinned.
307    pub pinned_kept: usize,
308    /// How many matched and were kept because they are archived, and this prune did not ask for
309    /// them (`--archived`). Counted apart from `pinned_kept` so the sentence that says why each
310    /// one survived can name the flag that would have changed the answer.
311    pub archived_kept: usize,
312}
313
314/// Title sidecar of a legacy `<id>.jsonl` session: read once, at import.
315#[derive(Serialize, Deserialize)]
316struct Meta {
317    title: String,
318}
319
320const MAX_MEMORY_FILE_BYTES: u64 = 64 * 1024;
321
322/// Schema of the stored memory. `1` was the model-written summary alone and, having no
323/// `version` field, is what a file without one means; `2` adds the compiled handoff
324/// ([`Handoff`]), which is what lets a long session reuse one instead of recompiling it on
325/// every request.
326pub const MEMORY_VERSION: u32 = 3;
327
328/// The deterministic handoff compiled from the dropped middle, stored beside the summary so the
329/// work is done once per covered range rather than once per request.
330///
331/// It carries the renderer's own version: a handoff written by a build that shaped the text
332/// differently is not reused, because reusing it would put two shapes of the same document in one
333/// session's history.
334#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
335pub struct Handoff {
336    pub text: String,
337    /// [`crate::compact::VERSION`] when it was compiled.
338    pub version: String,
339    /// Middle turns this document stands in for.
340    pub covered_turns: usize,
341    /// Middle messages this document stands in for.
342    pub covered_messages: usize,
343    /// The `seq` of the first and last message the document stands in for, when the caller knew
344    /// them. The counts describe a *size*, not a window: [`crate::context::Trimmed`] is relative
345    /// to `head_end`, and `head_end` flips between `0` and `first_end` when the budget, the
346    /// model or `protect_last_n` changes while the tail shifts to compensate — so "1 turn, 2
347    /// messages" names several different windows, and a document reused for the wrong one
348    /// describes messages that are still verbatim in the same request.
349    #[serde(default)]
350    pub covered_from: Option<u64>,
351    #[serde(default)]
352    pub covered_to: Option<u64>,
353    pub generated_at_ms: u64,
354    /// The bounded judgement pass's answer, when one survived the validator and went into
355    /// [`Handoff::text`]. Kept beside it so the readout and the harness can say what the model
356    /// contributed and on whose authority, without parsing the document.
357    #[serde(default)]
358    pub judgement: Option<Judgement>,
359}
360
361/// One accepted judgement pass: what the model said about *why*, and which model said it.
362#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
363pub struct Judgement {
364    pub text: String,
365    /// The auxiliary route that answered, as this process named it.
366    pub model: String,
367    pub generated_at_ms: u64,
368}
369
370impl Handoff {
371    /// Usable as-is for `turns`/`messages` only when it was compiled for exactly that range and
372    /// by this shape of compiler. A handoff for a *larger* range is not an extension of a
373    /// smaller one — the sections are re-rendered, not appended — so a wider document would
374    /// describe messages that are still present verbatim.
375    ///
376    /// The counts alone are not the range: the same pair of numbers names a different window
377    /// whenever `head_end` moves. `from`/`to` are the `seq` of the first and last covered
378    /// message, and a stored document that does not carry them is not reused — a recompile costs
379    /// milliseconds, and a wrong document costs the model's trust in its own history.
380    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/// Per-session memory, stored beside the transcript: the compiled handoff that stands in for the
398/// dropped middle of the conversation, and what range of the transcript it covers. It never
399/// replaces the transcript.
400///
401/// There is no model-written summary here, and no second shape to choose between: a file written
402/// by an older build (v1 or v2) still loads, its summary is ignored, and the next handoff write
403/// replaces the record. The only model input compaction has is the judgement pass's bullets,
404/// which live inside [`Handoff::judgement`] where they can be attributed and discarded together
405/// with the document they belong to.
406#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407pub struct Memory {
408    /// [`MEMORY_VERSION`] as written, or `0` for a file written before the field existed.
409    #[serde(default)]
410    pub version: u32,
411    /// The compiled handoff, absent when none has been stored yet.
412    #[serde(default)]
413    pub handoff: Option<Handoff>,
414}
415
416impl Memory {
417    /// The schema this file was written with; a file from before the field existed is v1.
418    pub fn schema(&self) -> u32 {
419        self.version.max(1)
420    }
421
422    /// Why this memory must not be used, if so: a schema this build cannot read, a handoff in a
423    /// file that predates handoffs, an empty or untrimmed document, or counts that make no sense.
424    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    /// The compiled handoff, if this build can read it and it is structurally sound. Whether it
457    /// still covers what is being dropped is [`Handoff::covers`]'s question, not this one's.
458    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    /// Opened on first use and kept for the life of the store. `None` until then, so
468    /// constructing a store cannot fail.
469    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        // The connection is not printable and carries nothing a caller needs to see.
475        f.debug_struct("SessionStore")
476            .field("dir", &self.dir)
477            .finish()
478    }
479}
480
481/// How long a run waits for another *process* to release a session before giving up.
482pub const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(30);
483
484/// How often the wait re-tries the lock.
485const LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(50);
486
487/// A held session lock. Dropping it releases the lock (the OS does the same if the
488/// process dies, so a crash cannot leave a session permanently locked).
489#[derive(Debug)]
490pub struct SessionLock {
491    id: String,
492    /// The locked file: closing it drops the `flock`.
493    _file: std::fs::File,
494}
495
496impl SessionLock {
497    pub fn id(&self) -> &str {
498        &self.id
499    }
500}
501
502/// A stored `state` word back into the enum. An unknown word reads as `Stopped`: a goal this
503/// build cannot name is not one it should keep working on.
504fn 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
526/// Record who holds the lock, so a refusal elsewhere can name them. Best effort: a failed
527/// write must not fail the lock.
528fn 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    // SAFETY: `file` owns a valid descriptor for the duration of the call.
540    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        // Another process holds it; anywhere else would be a real error.
547        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    // No portable advisory lock without extra dependencies; the per-process mutex in the
555    // runtime is all there is here (see the docs' limitations).
556    Ok(true)
557}
558
559/// A session some process is running right now, as seen by [`held_locks`].
560#[derive(Debug, Clone, PartialEq, Eq)]
561pub struct HeldLock {
562    pub id: String,
563    /// What the holder wrote into the lock file (`pid N`), or `another process`.
564    pub holder: String,
565}
566
567/// Which sessions in `dir` are locked by a live run.
568///
569/// A lock file left behind by a finished run is not a lock — the OS drops the `flock` with the
570/// process — so each file is probed with a non-blocking *shared* lock: it fails only while an
571/// exclusive holder exists, and it never creates a file or waits. A directory that does not
572/// exist holds nothing. On non-Unix targets there is no cross-process lock to ask about, and
573/// the answer is always empty.
574pub 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/// A lock file nobody is holding: its holder is gone, so the kernel released the lock and the
612/// file is left behind. `eclipse doctor --fix` removes these.
613#[derive(Debug, Clone, PartialEq, Eq)]
614pub struct StaleLock {
615    pub path: PathBuf,
616    /// The session the lock belongs to, taken from the file name — what `doctor` compares with the
617    /// store to tell a leftover from a lock whose session is gone (`#497`).
618    pub id: String,
619    /// What the file says held it, for the message: `pid 1234`, or `another process`.
620    pub holder: String,
621}
622
623/// The `<id>.lock` files in `dir` that are *not* held by a live process.
624///
625/// The counterpart of [`held_locks`]: that one answers "which sessions are in use", this one
626/// answers "which leftovers can be cleaned up". A file whose `flock` is free is a file whose
627/// holder died, because the kernel releases the lock then and nothing removes the file.
628pub 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    // SAFETY: `file` owns a valid descriptor for the duration of the call.
666    let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) };
667    if rc == 0 {
668        // Closing the descriptor drops the probe; nothing to undo.
669        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
688/// How long ago a stored timestamp is, in the words a person would use. `0` says nothing
689/// rather than claiming 1970: a session imported with no readable record has no time.
690pub 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
703/// Ids become file names, so only a conservative character set is accepted.
704pub 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    /// Sortable, unique-enough id: `<unix-ms>-<pid>-<counter>`.
730    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    /// Run `f` against the database, opening (and migrating, and importing any legacy
741    /// `.jsonl` files) on first use.
742    ///
743    /// Opening lazily keeps [`SessionStore::new`] infallible — the CLI constructs a store
744    /// before it knows whether the state directory is usable — and puts the error where it
745    /// can be reported: on the call that needed the data.
746    /// `pub(crate)` so the runtime's tests can inject a failure (a rejecting trigger) and
747    /// check that a failed memory save is reported instead of breaking the run.
748    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    /// Take an exclusive lock on one session so two *processes* (the CLI and the
760    /// dashboard, or two shells) cannot interleave their messages into the same
761    /// transcript. Waits up to `wait` for a holder to finish. Dropping the guard releases
762    /// it, and the OS releases it if the process dies, so a crashed run leaves nothing
763    /// stuck.
764    ///
765    /// On non-Unix targets no cross-process lock is taken (the guard is inert); within one
766    /// process the runtime's own per-session mutex still applies.
767    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    /// One non-blocking attempt at the same lock [`lock`](Self::lock) takes, for a caller that
801    /// has no future to await it in — a UI thread asking "is a run in flight?" before it fires a
802    /// `/loop` tick (`#173`). `Ok(Some)` means the caller now holds it and must drop it.
803    ///
804    /// It is the same primitive, not a second opinion: the lock is `flock`, and a session's lock
805    /// file is a session's lock file whether the take is polled or instantaneous.
806    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    /// `#172`: write a session's goal, replacing whatever was there.
824    ///
825    /// One goal per session, so this is an upsert rather than an append: `/goal <text>` on a
826    /// session that already has one replaces it, which is what "one standing goal" means.
827    pub fn set_goal(&self, goal: &crate::goals::Goal) -> Result<()> {
828        validate_id(&goal.session)?;
829        self.with_db(|db| {
830            db.conn
831                .execute(
832                    "INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
833                         VALUES (?1, ?2, ?2, 0, 'native')
834                     ON CONFLICT(id) DO NOTHING",
835                    params![goal.session, goal.created_ms],
836                )
837                .map_err(|e| Error::Session(format!("could not ensure the session row: {e}")))?;
838            db.conn
839                .execute(
840                    "INSERT INTO goals
841                         (session_id, text, gate, budget, turns, state, note, garbage,
842                          created_ms, updated_ms)
843                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
844                     ON CONFLICT(session_id) DO UPDATE SET
845                         text = excluded.text, gate = excluded.gate, budget = excluded.budget,
846                         turns = excluded.turns, state = excluded.state, note = excluded.note,
847                         garbage = excluded.garbage, updated_ms = excluded.updated_ms",
848                    params![
849                        goal.session,
850                        goal.text,
851                        goal.gate,
852                        goal.budget as i64,
853                        goal.turns as i64,
854                        goal.state.as_str(),
855                        goal.note,
856                        goal.garbage as i64,
857                        goal.created_ms,
858                        goal.updated_ms,
859                    ],
860                )
861                .map_err(|e| Error::Session(format!("could not save the goal: {e}")))?;
862            Ok(())
863        })
864    }
865
866    /// `#172`: a session's goal, if it has one.
867    pub fn goal(&self, id: &str) -> Result<Option<crate::goals::Goal>> {
868        validate_id(id)?;
869        self.with_db(|db| {
870            let found = db
871                .conn
872                .query_row(
873                    "SELECT text, gate, budget, turns, state, note, garbage, created_ms, updated_ms
874                       FROM goals WHERE session_id = ?1",
875                    params![id],
876                    |r| {
877                        Ok(crate::goals::Goal {
878                            session: id.to_string(),
879                            text: r.get(0)?,
880                            gate: r.get(1)?,
881                            budget: r.get::<_, i64>(2)? as u32,
882                            turns: r.get::<_, i64>(3)? as u32,
883                            state: goal_state(r.get::<_, String>(4)?),
884                            note: r.get(5)?,
885                            garbage: r.get::<_, i64>(6)? != 0,
886                            created_ms: r.get(7)?,
887                            updated_ms: r.get(8)?,
888                        })
889                    },
890                )
891                .optional()?;
892            Ok(found)
893        })
894    }
895
896    /// Remove a session's goal and its judgements (`/goal clear`).
897    pub fn clear_goal(&self, id: &str) -> Result<()> {
898        validate_id(id)?;
899        self.with_db(|db| {
900            db.conn
901                .execute("DELETE FROM goals WHERE session_id = ?1", params![id])
902                .map_err(|e| Error::Session(format!("could not clear the goal: {e}")))?;
903            db.conn
904                .execute("DELETE FROM goal_turns WHERE session_id = ?1", params![id])
905                .map_err(|e| Error::Session(format!("could not clear the judgements: {e}")))?;
906            Ok(())
907        })
908    }
909
910    /// Record one judgement, keyed by the turn number it judged.
911    pub fn record_goal_turn(&self, id: &str, judgement: &crate::goals::Judgement) -> Result<()> {
912        validate_id(id)?;
913        self.with_db(|db| {
914            db.conn
915                .execute(
916                    "INSERT INTO goal_turns (session_id, turn, verdict, why, at_ms)
917                     VALUES (?1, ?2, ?3, ?4, ?5)
918                     ON CONFLICT(session_id, turn) DO UPDATE SET
919                         verdict = excluded.verdict, why = excluded.why, at_ms = excluded.at_ms",
920                    params![
921                        id,
922                        judgement.turn as i64,
923                        judgement.verdict,
924                        judgement.why,
925                        judgement.at_ms,
926                    ],
927                )
928                .map_err(|e| Error::Session(format!("could not record the judgement: {e}")))?;
929            Ok(())
930        })
931    }
932
933    /// Every judgement about a session's goal, oldest first.
934    pub fn goal_turns(&self, id: &str) -> Result<Vec<crate::goals::Judgement>> {
935        validate_id(id)?;
936        self.with_db(|db| {
937            let mut stmt = db
938                .conn
939                .prepare(
940                    "SELECT turn, verdict, why, at_ms FROM goal_turns
941                      WHERE session_id = ?1 ORDER BY turn",
942                )
943                .map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
944            let rows = stmt
945                .query_map(params![id], |r| {
946                    Ok(crate::goals::Judgement {
947                        turn: r.get::<_, i64>(0)? as u32,
948                        verdict: r.get(1)?,
949                        why: r.get(2)?,
950                        at_ms: r.get(3)?,
951                    })
952                })
953                .map_err(|e| Error::Session(format!("could not read the judgements: {e}")))?;
954            Ok(rows.flatten().collect())
955        })
956    }
957
958    /// Every goal a process could still work on — `Active` or `Paused`, newest first.
959    ///
960    /// The dashboard's sweeper asks this each pass: a goal is due when its last turn said
961    /// "continue", which is a fact on the row, not a timer in a task.
962    pub fn live_goals(&self) -> Result<Vec<crate::goals::Goal>> {
963        self.with_db(|db| {
964            let mut stmt = db
965                .conn
966                .prepare(
967                    "SELECT session_id, text, gate, budget, turns, state, note, garbage,
968                            created_ms, updated_ms
969                       FROM goals WHERE state IN ('active', 'paused') ORDER BY updated_ms DESC",
970                )
971                .map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
972            let rows = stmt
973                .query_map([], |r| {
974                    Ok(crate::goals::Goal {
975                        session: r.get(0)?,
976                        text: r.get(1)?,
977                        gate: r.get(2)?,
978                        budget: r.get::<_, i64>(3)? as u32,
979                        turns: r.get::<_, i64>(4)? as u32,
980                        state: goal_state(r.get::<_, String>(5)?),
981                        note: r.get(6)?,
982                        garbage: r.get::<_, i64>(7)? != 0,
983                        created_ms: r.get(8)?,
984                        updated_ms: r.get(9)?,
985                    })
986                })
987                .map_err(|e| Error::Session(format!("could not list goals: {e}")))?;
988            Ok(rows.flatten().collect())
989        })
990    }
991
992    /// Whether some process is running this session right now — the busy test `/loop` uses.
993    ///
994    /// A probe, not a reservation: it takes the lock and releases it, so a run that starts in the
995    /// same instant is not blocked by the question. What it answers is "was it free a moment
996    /// ago", which is what a tick landing on a busy session needs to know.
997    pub fn is_busy(&self, id: &str) -> bool {
998        match self.try_lock(id) {
999            Ok(Some(lock)) => {
1000                drop(lock);
1001                false
1002            }
1003            Ok(None) => true,
1004            // A lock file that cannot be opened is not evidence of a run in flight; the run
1005            // itself will say what went wrong and that is the better place to report it.
1006            Err(_) => false,
1007        }
1008    }
1009
1010    pub fn exists(&self, id: &str) -> bool {
1011        if validate_id(id).is_err() {
1012            return false;
1013        }
1014        self.with_db(|db| {
1015            let found: Option<i64> = db
1016                .conn
1017                .query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
1018                    r.get(0)
1019                })
1020                .optional()?;
1021            Ok(found.is_some())
1022        })
1023        .unwrap_or(false)
1024    }
1025
1026    /// Record the calls of one assistant message as waiting for an answer.
1027    ///
1028    /// A row that already exists keeps its decision: the same call recorded twice has the same
1029    /// answer or none, and the second recording can arrive while the run that asked is already
1030    /// stopping, which is exactly when overwriting a decision would lose it.
1031    pub fn record_pending(
1032        &self,
1033        id: &str,
1034        seq: i64,
1035        calls: &[crate::approvals::Pending],
1036    ) -> Result<()> {
1037        validate_id(id)?;
1038        self.with_db(|db| {
1039            let tx = db.conn.transaction()?;
1040            for (ord, call) in calls.iter().enumerate() {
1041                tx.execute(
1042                    "INSERT INTO approvals
1043                         (session_id, seq, ord, call_id, tool, summary, args, decision, decided_ms)
1044                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, NULL)
1045                     ON CONFLICT(session_id, seq, ord) DO NOTHING",
1046                    params![
1047                        id,
1048                        seq,
1049                        ord as i64,
1050                        call.call_id,
1051                        call.tool,
1052                        call.summary,
1053                        call.args
1054                    ],
1055                )?;
1056            }
1057            tx.commit()?;
1058            Ok(())
1059        })
1060    }
1061
1062    /// Every recorded call for a session, oldest message first and in the order the model made
1063    /// them — the order `eclipse approve --index N` counts in.
1064    pub fn pending_calls(&self, id: &str) -> Result<Vec<crate::approvals::PendingCall>> {
1065        validate_id(id)?;
1066        self.with_db(|db| {
1067            let mut stmt = db.conn.prepare(
1068                "SELECT seq, ord, call_id, tool, summary, args, decision, decided_ms, by
1069                   FROM approvals WHERE session_id = ?1 ORDER BY seq, ord",
1070            )?;
1071            let rows = stmt
1072                .query_map(params![id], |r| {
1073                    let stored: Option<String> = r.get(6)?;
1074                    Ok(crate::approvals::PendingCall {
1075                        seq: r.get(0)?,
1076                        ord: r.get::<_, i64>(1)? as usize,
1077                        call: crate::approvals::Pending::new(
1078                            r.get::<_, String>(2)?,
1079                            r.get::<_, String>(3)?,
1080                            r.get::<_, String>(4)?,
1081                            r.get::<_, String>(5)?,
1082                        ),
1083                        decision: stored.as_deref().map(crate::approvals::Decision::parse),
1084                        decided_ms: r.get(7)?,
1085                        by: r.get(8)?,
1086                    })
1087                })?
1088                .collect::<std::result::Result<Vec<_>, _>>()?;
1089            Ok(rows)
1090        })
1091    }
1092
1093    /// Write the answer for one recorded call. Refused if the call is not recorded: an approval
1094    /// for a call that does not exist would resolve nothing, and silently accepting it would
1095    /// tell the user their answer counted.
1096    pub fn decide_pending(
1097        &self,
1098        id: &str,
1099        seq: i64,
1100        ord: usize,
1101        decision: &crate::approvals::Decision,
1102        by: &str,
1103    ) -> Result<()> {
1104        validate_id(id)?;
1105        // `Defer` has no stored value, and writing one would make "still waiting" look like an
1106        // answer: the row keeps its `NULL` and nothing goes in the log.
1107        let Some(stored) = decision.store() else {
1108            return Ok(());
1109        };
1110        let now = now_ms() as i64;
1111        let changed = self.with_db(|db| {
1112            let changed = db.conn.execute(
1113                "UPDATE approvals SET decision = ?4, decided_ms = ?5, by = ?6
1114                  WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
1115                params![&id, seq, ord as i64, &stored, now, by],
1116            )?;
1117            // The row is deleted once the answer is in the transcript, so the log is what makes
1118            // "who let this through" answerable afterwards — written in the same transaction as
1119            // the answer, so a ruling cannot exist in one and not the other.
1120            if changed > 0 {
1121                db.conn.execute(
1122                    "INSERT INTO approval_log
1123                         (session_id, at_ms, call_id, tool, summary, decision, by)
1124                     SELECT session_id, ?4, call_id, tool, summary, ?5, ?6 FROM approvals
1125                      WHERE session_id = ?1 AND seq = ?2 AND ord = ?3",
1126                    params![&id, seq, ord as i64, now, &stored, by],
1127                )?;
1128            }
1129            Ok(changed)
1130        })?;
1131        if changed == 0 {
1132            return Err(Error::Session(format!(
1133                "{id}: no tool call recorded at message {seq}, position {ord}"
1134            )));
1135        }
1136        Ok(())
1137    }
1138
1139    /// Note a ruling that had no waiting row: a judge's allow or deny (`#340`).
1140    ///
1141    /// Those calls never become pending — nothing is waiting on them — so there is no row to hang
1142    /// the decider on, and the log is the only place the decision can live. Written best-effort by
1143    /// the caller: a bookkeeping failure must never turn an approval into a refusal.
1144    pub fn log_decision(
1145        &self,
1146        id: &str,
1147        call: &crate::approvals::Pending,
1148        decision: &crate::approvals::Decision,
1149        by: &str,
1150    ) -> Result<()> {
1151        validate_id(id)?;
1152        let Some(stored) = decision.store() else {
1153            return Ok(());
1154        };
1155        let now = now_ms() as i64;
1156        self.with_db(|db| {
1157            Ok(db.conn.execute(
1158                "INSERT INTO approval_log (session_id, at_ms, call_id, tool, summary, decision, by)
1159                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1160                params![
1161                    id,
1162                    now,
1163                    &call.call_id,
1164                    &call.tool,
1165                    &call.summary,
1166                    &stored,
1167                    by
1168                ],
1169            )?)
1170        })?;
1171        Ok(())
1172    }
1173
1174    /// Every ruling recorded for a session, oldest first (`#340`).
1175    ///
1176    /// The pending rows are transient by design, so this is the only place "who let this through"
1177    /// survives. One row per answered call: the decision as stored (`allow`, `deny:<why>`) and who
1178    /// answered it.
1179    pub fn approval_log(&self, id: &str) -> Result<Vec<crate::approvals::Ruling>> {
1180        validate_id(id)?;
1181        self.with_db(|db| {
1182            let mut stmt = db.conn.prepare(
1183                "SELECT at_ms, call_id, tool, summary, decision, by FROM approval_log
1184                  WHERE session_id = ?1 ORDER BY at_ms, rowid",
1185            )?;
1186            let rows = stmt
1187                .query_map(params![id], |r| {
1188                    Ok(crate::approvals::Ruling {
1189                        at_ms: r.get(0)?,
1190                        call_id: r.get(1)?,
1191                        tool: r.get(2)?,
1192                        summary: r.get(3)?,
1193                        decision: crate::approvals::Decision::parse(&r.get::<_, String>(4)?),
1194                        by: r.get(5)?,
1195                    })
1196                })?
1197                .collect::<std::result::Result<Vec<_>, _>>()?;
1198            Ok(rows)
1199        })
1200    }
1201
1202    /// Forget the recorded calls of a session — the run that asked has answered them in the
1203    /// transcript, or the session is gone. Returns how many rows went.
1204    pub fn clear_pending(&self, id: &str) -> Result<usize> {
1205        validate_id(id)?;
1206        self.with_db(|db| {
1207            Ok(db
1208                .conn
1209                .execute("DELETE FROM approvals WHERE session_id = ?1", params![id])?)
1210        })
1211    }
1212
1213    /// Forget one recorded call — its answer has been written into the transcript as the tool
1214    /// result, which is the durable record a reader actually reads.
1215    pub fn clear_call(&self, id: &str, call_id: &str) -> Result<usize> {
1216        validate_id(id)?;
1217        self.with_db(|db| {
1218            Ok(db.conn.execute(
1219                "DELETE FROM approvals WHERE session_id = ?1 AND call_id = ?2",
1220                params![id, call_id],
1221            )?)
1222        })
1223    }
1224
1225    /// The `seq` a session's transcript ends at, or -1 for an empty one.
1226    pub fn last_seq(&self, id: &str) -> Result<i64> {
1227        validate_id(id)?;
1228        self.with_db(|db| {
1229            Ok(db.conn.query_row(
1230                "SELECT COALESCE(MAX(seq), -1) FROM messages WHERE session_id = ?1",
1231                params![id],
1232                |r| r.get(0),
1233            )?)
1234        })
1235    }
1236
1237    /// Append one message to the session, creating it on first use.
1238    /// How one tool call ended, for the marks a replayed session draws (`#447`).
1239    ///
1240    /// The verdict belongs beside the message, not inside it: a `tool` message is the model's wire
1241    /// shape, and a field there would either be sent to the model or skipped and never stored. The
1242    /// call id is what a replayed row joins on, so it is the key.
1243    pub fn set_tool_outcome(&self, id: &str, call_id: &str, is_error: bool) -> Result<()> {
1244        validate_id(id)?;
1245        let session = id.to_string();
1246        let call = call_id.to_string();
1247        self.with_db(|db| {
1248            db.conn
1249                .execute(
1250                    "INSERT INTO tool_outcomes (session_id, call_id, is_error) VALUES (?1, ?2, ?3)
1251                     ON CONFLICT (session_id, call_id) DO UPDATE SET is_error = excluded.is_error",
1252                    rusqlite::params![session, call, is_error as i64],
1253                )
1254                .map_err(|e| Error::Session(e.to_string()))?;
1255            Ok(())
1256        })
1257    }
1258
1259    /// Every recorded verdict for a session, by call id. An empty map is a session recorded before
1260    /// this table existed, and the reader falls back to reading the text.
1261    pub fn tool_outcomes(&self, id: &str) -> Result<std::collections::HashMap<String, bool>> {
1262        validate_id(id)?;
1263        let session = id.to_string();
1264        self.with_db(|db| {
1265            let mut stmt = db
1266                .conn
1267                .prepare("SELECT call_id, is_error FROM tool_outcomes WHERE session_id = ?1")
1268                .map_err(|e| Error::Session(e.to_string()))?;
1269            let rows = stmt
1270                .query_map(rusqlite::params![session], |row| {
1271                    Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? != 0))
1272                })
1273                .map_err(|e| Error::Session(e.to_string()))?;
1274            let mut out = std::collections::HashMap::new();
1275            for row in rows {
1276                let (call, is_error) = row.map_err(|e| Error::Session(e.to_string()))?;
1277                out.insert(call, is_error);
1278            }
1279            Ok(out)
1280        })
1281    }
1282
1283    pub fn append(&self, id: &str, message: &Message) -> Result<()> {
1284        self.append_seq(id, message).map(|_| ())
1285    }
1286
1287    /// [`append`](Self::append), returning the `seq` the message was stored under. A pending
1288    /// approval is keyed by the message that carried the call, so the loop needs the number it
1289    /// cannot compute itself: the store owns sequence allocation.
1290    pub fn append_seq(&self, id: &str, message: &Message) -> Result<i64> {
1291        validate_id(id)?;
1292        let now = now_ms() as i64;
1293        let body = serde_json::to_string(message).map_err(|e| Error::Session(e.to_string()))?;
1294        let role = role_name(message.role);
1295        // The preview is the first thing the user said; it is captured once, when that
1296        // message arrives, so listing never has to walk the transcript.
1297        let preview = (message.role == Role::User)
1298            .then(|| {
1299                message
1300                    .content
1301                    .as_deref()
1302                    .map(|t| t.split_whitespace().collect::<Vec<_>>().join(" "))
1303                    .map(|t| t.chars().take(60).collect::<String>())
1304            })
1305            .flatten()
1306            // An empty string is not a preview. `COALESCE(preview, ?3)` fills only a NULL, so a
1307            // user row that said nothing (a picture and no text) used to freeze the listing at
1308            // "untitled" for the rest of the session, even after a real message arrived.
1309            .filter(|p| !p.trim().is_empty());
1310
1311        self.with_db(|db| {
1312            let tx = db.conn.transaction()?;
1313            // The session row first: the foreign key on `messages` is immediate, and a
1314            // message cannot be inserted before the thing it belongs to exists.
1315            tx.execute(
1316                "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
1317                 VALUES (?1, ?2, ?2, NULL, NULL, 0, 'native')
1318                 ON CONFLICT(id) DO NOTHING",
1319                params![id, now],
1320            )?;
1321            let seq: i64 = tx.query_row(
1322                "SELECT COALESCE(MAX(seq), -1) + 1 FROM messages WHERE session_id = ?1",
1323                params![id],
1324                |r| r.get(0),
1325            )?;
1326            tx.execute(
1327                "INSERT INTO messages (session_id, seq, at_ms, role, body)
1328                 VALUES (?1, ?2, ?3, ?4, ?5)",
1329                params![id, seq, now, role, body],
1330            )?;
1331            tx.execute(
1332                "UPDATE sessions
1333                    SET updated_ms = ?2,
1334                        messages   = messages + 1,
1335                        preview    = COALESCE(preview, ?3)
1336                  WHERE id = ?1",
1337                params![id, now, preview],
1338            )?;
1339            if db.fts {
1340                tx.execute(
1341                    "INSERT INTO messages_fts (session_id, seq, content) VALUES (?1, ?2, ?3)",
1342                    params![id, seq, searchable(message)],
1343                )?;
1344            }
1345            tx.commit()?;
1346            Ok(seq)
1347        })
1348    }
1349
1350    /// Create the session row for a subagent, marked with where it came from, before it has a
1351    /// message. The origin is what `sessions list` shows and what `--continue` skips; the
1352    /// transcript of the parent never mentions the child. A row that already exists is left
1353    /// as it is.
1354    pub fn begin_subagent(&self, id: &str, parent: &str, route: &str) -> Result<()> {
1355        validate_id(parent)?;
1356        self.begin_row(id, &format!("{SUBAGENT_ORIGIN}{parent}:{route}"))
1357    }
1358
1359    /// Create the row for one flare of a run (`#171`), before it has a message.
1360    ///
1361    /// A flare is a child like a subagent's, and the run id is not a session id — it names the
1362    /// ledger row, not a conversation — so it is only checked for shape here.
1363    pub fn begin_flare(&self, id: &str, run: &str, n: usize) -> Result<()> {
1364        if run.is_empty() || run.contains(':') {
1365            return Err(Error::Config(format!(
1366                "a flare run id is one word without a colon, not {run:?}"
1367            )));
1368        }
1369        self.begin_row(id, &format!("{FLARE_ORIGIN}{run}:{n}"))
1370    }
1371
1372    /// Open the run's ledger row (`#171`), before the first child starts.
1373    pub fn begin_flare_run(
1374        &self,
1375        id: &str,
1376        task: &str,
1377        routes: &[String],
1378        jobs: usize,
1379        parent: &str,
1380    ) -> Result<()> {
1381        let task: String = task.chars().take(500).collect();
1382        self.with_db(|db| {
1383            db.conn.execute(
1384                "INSERT INTO flare_runs (id, task, state, routes, jobs, parent, started_ms)
1385                 VALUES (?1, ?2, 'running', ?3, ?4, ?5, ?6)",
1386                params![
1387                    id,
1388                    task,
1389                    routes.join(","),
1390                    jobs as i64,
1391                    parent,
1392                    now_ms() as i64
1393                ],
1394            )?;
1395            Ok(())
1396        })
1397    }
1398
1399    /// A child has its session and is about to call the model.
1400    pub fn flare_job_running(&self, run: &str, n: usize, route: &str, session: &str) -> Result<()> {
1401        self.with_db(|db| {
1402            db.conn.execute(
1403                "INSERT INTO flare_jobs (run_id, n, route, session_id, state)
1404                 VALUES (?1, ?2, ?3, ?4, 'running')
1405                 ON CONFLICT(run_id, n) DO UPDATE SET
1406                   route = excluded.route, session_id = excluded.session_id,
1407                   state = 'running'",
1408                params![run, n as i64, route, session],
1409            )?;
1410            Ok(())
1411        })
1412    }
1413
1414    /// How that child ended, and what it cost. `state` is one word: done, failed or dropped.
1415    #[allow(clippy::too_many_arguments)]
1416    pub fn flare_job_done(&self, done: &FlareJobRow) -> Result<()> {
1417        self.with_db(|db| {
1418            db.conn.execute(
1419                "INSERT INTO flare_jobs (run_id, n, route, session_id, state, prompt_tokens,
1420                                         completion_tokens, iterations, why)
1421                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
1422                 ON CONFLICT(run_id, n) DO UPDATE SET
1423                   route = excluded.route, session_id = excluded.session_id,
1424                   state = excluded.state, prompt_tokens = excluded.prompt_tokens,
1425                   completion_tokens = excluded.completion_tokens,
1426                   iterations = excluded.iterations, why = excluded.why",
1427                params![
1428                    done.run_id,
1429                    done.n as i64,
1430                    done.route,
1431                    done.session_id,
1432                    done.state,
1433                    done.prompt_tokens.map(|v| v as i64),
1434                    done.completion_tokens.map(|v| v as i64),
1435                    done.iterations as i64,
1436                    done.why,
1437                ],
1438            )?;
1439            Ok(())
1440        })
1441    }
1442
1443    /// Close the run: its state and what all its children cost together.
1444    #[allow(clippy::too_many_arguments)]
1445    pub fn finish_flare_run(
1446        &self,
1447        id: &str,
1448        state: &str,
1449        prompt: Option<u64>,
1450        completion: Option<u64>,
1451        iterations: usize,
1452    ) -> Result<()> {
1453        self.with_db(|db| {
1454            db.conn.execute(
1455                "UPDATE flare_runs SET state = ?2, finished_ms = ?3, prompt_tokens = ?4,
1456                        completion_tokens = ?5, iterations = ?6
1457                  WHERE id = ?1",
1458                params![
1459                    id,
1460                    state,
1461                    now_ms() as i64,
1462                    prompt.map(|v| v as i64),
1463                    completion.map(|v| v as i64),
1464                    iterations as i64
1465                ],
1466            )?;
1467            Ok(())
1468        })
1469    }
1470
1471    /// Ask a run to stop, from any process. The run checks between children, so a queued flare
1472    /// is dropped before it starts rather than after it has paid for its first turn.
1473    pub fn cancel_flare_run(&self, id: &str) -> Result<bool> {
1474        self.with_db(|db| {
1475            let n = db.conn.execute(
1476                "UPDATE flare_runs SET cancel_requested = 1 WHERE id = ?1",
1477                params![id],
1478            )?;
1479            Ok(n > 0)
1480        })
1481    }
1482
1483    /// Whether anyone has asked this run to stop.
1484    pub fn flare_cancel_requested(&self, id: &str) -> Result<bool> {
1485        self.with_db(|db| {
1486            let mut stmt = db
1487                .conn
1488                .prepare("SELECT cancel_requested FROM flare_runs WHERE id = ?1")?;
1489            let mut rows = stmt.query(params![id])?;
1490            match rows.next()? {
1491                Some(r) => Ok(r.get::<_, i64>(0)? != 0),
1492                None => Ok(false),
1493            }
1494        })
1495    }
1496
1497    /// The runs, newest first — what `flares list` and the dashboard read.
1498    pub fn flare_runs(&self, limit: usize) -> Result<Vec<FlareRunRow>> {
1499        let limit = limit.clamp(1, 200) as i64;
1500        self.with_db(|db| {
1501            let mut stmt = db.conn.prepare(
1502                "SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
1503                        prompt_tokens, completion_tokens, iterations
1504                   FROM flare_runs ORDER BY started_ms DESC LIMIT ?1",
1505            )?;
1506            let rows = stmt.query_map(params![limit], run_row)?;
1507            Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
1508        })
1509    }
1510
1511    /// One run and its children, in the lead's order.
1512    pub fn flare_run(&self, id: &str) -> Result<Option<(FlareRunRow, Vec<FlareJobRow>)>> {
1513        self.with_db(|db| {
1514            let mut stmt = db.conn.prepare(
1515                "SELECT id, task, state, routes, jobs, parent, started_ms, finished_ms,
1516                        prompt_tokens, completion_tokens, iterations
1517                   FROM flare_runs WHERE id = ?1",
1518            )?;
1519            let mut rows = stmt.query(params![id])?;
1520            let Some(row) = rows.next()? else {
1521                return Ok(None);
1522            };
1523            let run = run_row(row)?;
1524            let mut stmt = db.conn.prepare(
1525                "SELECT n, route, session_id, state, prompt_tokens, completion_tokens,
1526                        iterations, why
1527                   FROM flare_jobs WHERE run_id = ?1 ORDER BY n",
1528            )?;
1529            let jobs = stmt
1530                .query_map(params![id], |r| {
1531                    Ok(FlareJobRow {
1532                        run_id: id.to_string(),
1533                        n: r.get::<_, i64>(0)? as usize,
1534                        route: r.get(1)?,
1535                        session_id: r.get(2)?,
1536                        state: r.get(3)?,
1537                        prompt_tokens: r.get::<_, Option<i64>>(4)?.map(|v| v as u64),
1538                        completion_tokens: r.get::<_, Option<i64>>(5)?.map(|v| v as u64),
1539                        iterations: r.get::<_, Option<i64>>(6)?.unwrap_or(0).max(0) as usize,
1540                        why: r.get(7)?,
1541                    })
1542                })?
1543                .collect::<std::result::Result<Vec<_>, _>>()?;
1544            Ok(Some((run, jobs)))
1545        })
1546    }
1547
1548    /// The flares a run started, in the order the lead asked for them.
1549    ///
1550    /// A run that was cancelled part-way has fewer rows than jobs, and that is the honest answer:
1551    /// a flare that never started has no transcript to open.
1552    pub fn flares_of(&self, run: &str) -> Result<Vec<SessionInfo>> {
1553        let prefix = format!("{FLARE_ORIGIN}{run}:");
1554        let mut out: Vec<SessionInfo> = self
1555            .list_rows(true, true)?
1556            .into_iter()
1557            .filter(|s| s.origin.starts_with(&prefix))
1558            .collect();
1559        out.sort_by_key(|s| s.flare().map_or(0, |f| f.n));
1560        Ok(out)
1561    }
1562
1563    /// The origin `POST /v1/chat/completions` writes: a headless call is a run, not a
1564    /// conversation, and it must not look like one in a listing or in `--continue`.
1565    pub const API_ORIGIN: &str = "api";
1566
1567    /// Create the row for an API call, tagged, before it has a message.
1568    ///
1569    /// It has to happen *before* the run: `append` creates an untagged row when none exists, and a
1570    /// row that arrives as `native` can never be told apart from one a person typed. A row that
1571    /// already exists is left as it is.
1572    pub fn begin_api(&self, id: &str) -> Result<()> {
1573        self.begin_row(id, Self::API_ORIGIN)
1574    }
1575
1576    /// Where a session came from, or `None` when there is no such row (`#509`).
1577    ///
1578    /// The send path asks this one question: a turn's agent is decided by the row's own `origin`,
1579    /// so a transcript opened by id is the bot's conversation too. One row rather than a listing —
1580    /// the dashboard answers a request per keystroke elsewhere and a full list here would be a
1581    /// scan to learn one string.
1582    pub fn origin(&self, id: &str) -> Result<Option<String>> {
1583        validate_id(id)?;
1584        self.with_db(|db| {
1585            let found = db
1586                .conn
1587                .query_row(
1588                    "SELECT origin FROM sessions WHERE id = ?1",
1589                    params![id],
1590                    |r| r.get::<_, String>(0),
1591                )
1592                .map(Some)
1593                .or_else(|e| match e {
1594                    rusqlite::Error::QueryReturnedNoRows => Ok(None),
1595                    other => Err(other),
1596                })?;
1597            Ok(found)
1598        })
1599    }
1600
1601    /// Create the row for a bot's conversation, marked `bot:<name>`, before it has a message
1602    /// (`#509`).
1603    ///
1604    /// The row has to exist first for the same reason an API call's does: `append` creates an
1605    /// untagged row when none exists, and a bot's conversation that arrived as `native` would sit
1606    /// in the human's list for the rest of its life.
1607    pub fn begin_bot(&self, id: &str, name: &str) -> Result<()> {
1608        self.begin_row(id, &format!("{BOT_ORIGIN}{name}"))
1609    }
1610
1611    /// The bot's live conversation, creating one when it has none (`#509`).
1612    ///
1613    /// One conversation is what "an identity" means: the Bots tab's open button and every later
1614    /// send land in the same transcript until it is cleared. A cleared one is archived, not
1615    /// deleted, so the next open starts a new row beside it and the count the tab shows still says
1616    /// it happened.
1617    pub fn bot_session(&self, name: &str) -> Result<String> {
1618        let origin = format!("{BOT_ORIGIN}{name}");
1619        for info in self.list_rows(true, true)? {
1620            if info.origin == origin && !info.archived {
1621                return Ok(info.id);
1622            }
1623        }
1624        let id = self.new_id();
1625        self.begin_bot(&id, name)?;
1626        Ok(id)
1627    }
1628
1629    /// Every conversation `name` has that is still open, newest first: what clearing a bot
1630    /// archives (`#509`).
1631    pub fn bot_sessions(&self, name: &str) -> Result<Vec<String>> {
1632        let origin = format!("{BOT_ORIGIN}{name}");
1633        Ok(self
1634            .list_rows(true, true)?
1635            .into_iter()
1636            .filter(|info| info.origin == origin && !info.archived)
1637            .map(|info| info.id)
1638            .collect())
1639    }
1640
1641    /// Create a session row carrying `origin`, before it has a message.
1642    fn begin_row(&self, id: &str, origin: &str) -> Result<()> {
1643        validate_id(id)?;
1644        let now = now_ms() as i64;
1645        self.with_db(|db| {
1646            db.conn.execute(
1647                "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
1648                 VALUES (?1, ?2, ?2, NULL, NULL, 0, ?3)
1649                 ON CONFLICT(id) DO NOTHING",
1650                params![id, now, origin],
1651            )?;
1652            Ok(())
1653        })
1654    }
1655
1656    /// Delete the API's own sessions older than `cutoff_ms` (unix milliseconds): the ones
1657    /// `/v1/chat/completions` leaves behind, and nothing else. Returns how many went.
1658    ///
1659    /// A script polling the API writes a session per call; without this they accumulate until the
1660    /// listing and the search degrade. Pinned sessions stay — a person who pinned one meant it —
1661    /// and so does every session a person started.
1662    pub fn prune_api_sessions(&self, cutoff_ms: u64) -> Result<usize> {
1663        let stale: Vec<String> = self
1664            .list()?
1665            .into_iter()
1666            .filter(|s| s.origin == Self::API_ORIGIN && !s.pinned && s.updated_ms < cutoff_ms)
1667            .map(|s| s.id)
1668            .collect();
1669        let mut pruned = 0usize;
1670        for id in stale {
1671            match self.delete(&id) {
1672                Ok(()) => pruned += 1,
1673                // Gone between the listing and the delete: a sweeper is not a place to care.
1674                Err(Error::Session(_)) => {}
1675                Err(e) => return Err(e),
1676            }
1677        }
1678        Ok(pruned)
1679    }
1680
1681    /// Load all records in order. A row whose stored body cannot be parsed is an error
1682    /// naming the session and the record, because silently dropping a message would make
1683    /// the transcript lie.
1684    pub fn load_records(&self, id: &str) -> Result<Vec<Record>> {
1685        validate_id(id)?;
1686        // An unknown id is an error rather than an empty transcript: "there is nothing
1687        // here" and "this session does not exist" are different answers, and the second
1688        // one is what a mistyped id deserves.
1689        if !self.exists(id) {
1690            return Err(Error::Session(format!("no such session {id:?}")));
1691        }
1692        self.with_db(|db| {
1693            let mut stmt = db.conn.prepare(
1694                "SELECT seq, at_ms, body FROM messages WHERE session_id = ?1 ORDER BY seq",
1695            )?;
1696            let rows = stmt.query_map(params![id], |r| {
1697                Ok((
1698                    r.get::<_, i64>(0)?,
1699                    r.get::<_, i64>(1)?,
1700                    r.get::<_, String>(2)?,
1701                ))
1702            })?;
1703            let mut out = Vec::new();
1704            for row in rows {
1705                let (seq, at, body) = row?;
1706                let mut message: Message = serde_json::from_str(&body)
1707                    .map_err(|e| Error::Session(format!("{id}:{seq}: {e}")))?;
1708                // The row number travels with the message: a compiled handoff cites `[#N]`, and
1709                // a ref that cannot be resolved to a row is a dead end dressed up as a citation.
1710                message.seq = Some(seq.max(0) as u64);
1711                out.push(Record {
1712                    ts: at.max(0) as u64,
1713                    message,
1714                });
1715            }
1716            Ok(out)
1717        })
1718    }
1719
1720    #[allow(clippy::unnecessary_wraps)] // kept symmetric with load_records' Result
1721    pub fn load(&self, id: &str) -> Result<Vec<Message>> {
1722        Ok(self
1723            .load_records(id)?
1724            .into_iter()
1725            .map(|r| r.message)
1726            .collect())
1727    }
1728
1729    /// The name set with `rename`, if any.
1730    pub fn title(&self, id: &str) -> Result<Option<String>> {
1731        validate_id(id)?;
1732        self.with_db(|db| {
1733            let title: Option<Option<String>> = db
1734                .conn
1735                .query_row(
1736                    "SELECT title FROM sessions WHERE id = ?1",
1737                    params![id],
1738                    |r| r.get(0),
1739                )
1740                .optional()?;
1741            Ok(title.flatten())
1742        })
1743    }
1744
1745    /// Give an existing session a title (trimmed; 1-200 characters, no control
1746    /// characters). The transcript is left untouched.
1747    ///
1748    /// A human's title outranks anything the machine writes, so this is the one path that sets
1749    /// [`TitleSource::User`] — and a later [`set_title`](Self::set_title) from the naming pass
1750    /// cannot take it back.
1751    pub fn rename(&self, id: &str, title: &str) -> Result<()> {
1752        validate_id(id)?;
1753        let title = title.trim();
1754        if title.is_empty() {
1755            return Err(Error::Session("title is empty".into()));
1756        }
1757        if title.chars().count() > MAX_TITLE_CHARS {
1758            return Err(Error::Session(format!(
1759                "title is longer than {MAX_TITLE_CHARS} characters"
1760            )));
1761        }
1762        if title.chars().any(char::is_control) {
1763            return Err(Error::Session("title contains control characters".into()));
1764        }
1765        let landed = self.set_title(id, title, TitleSource::User)?;
1766        if !landed {
1767            return Err(Error::Session(format!("no such session {id:?}")));
1768        }
1769        Ok(())
1770    }
1771
1772    /// Write a title written by the machine, unless a better-sourced one is already there.
1773    ///
1774    /// `derived < llm < user`, enforced here rather than by whoever calls: the naming pass runs in
1775    /// a task of its own, so a rename landing between the read and the write is normal, and the
1776    /// database is the only place where "the user's name wins" can be a fact instead of a hope.
1777    /// Returns whether the row changed.
1778    pub fn set_title(&self, id: &str, title: &str, source: TitleSource) -> Result<bool> {
1779        validate_id(id)?;
1780        self.with_db(|db| {
1781            let n = db.conn.execute(
1782                // `derived < llm < user`, spelled out rather than looked up: a CASE here is one
1783                // statement with the rule inside it, where a helper function would be a second
1784                // place for the ranking to live.
1785                "UPDATE sessions SET title = ?2, title_source = ?3, title_note = NULL
1786                  WHERE id = ?1
1787                    AND (CASE title_source WHEN 'user' THEN 3 WHEN 'llm' THEN 2
1788                                           WHEN 'derived' THEN 1 ELSE 0 END)
1789                      < (CASE ?3 WHEN 'user' THEN 3 WHEN 'llm' THEN 2
1790                                 WHEN 'derived' THEN 1 ELSE 0 END)",
1791                params![id, title, source.as_str()],
1792            )?;
1793            Ok(n > 0)
1794        })
1795    }
1796
1797    /// [`set_title`](Self::set_title) for a session found by id, only if nothing names it yet.
1798    ///
1799    /// This is stage one: it runs on the turn's own path, costs nothing, and cannot fail. A title
1800    /// that already exists is left alone whatever wrote it, so an imported or renamed session is
1801    /// never relabelled by the machine.
1802    pub fn title_if_unnamed(&self, id: &str, name: &str) -> Result<bool> {
1803        validate_id(id)?;
1804        let name = name.trim();
1805        if name.is_empty() || name.chars().any(char::is_control) {
1806            return Ok(false);
1807        }
1808        self.with_db(|db| {
1809            let n = db.conn.execute(
1810                "UPDATE sessions SET title = ?2, title_source = 'derived'
1811                  WHERE id = ?1 AND title IS NULL",
1812                params![id, name],
1813            )?;
1814            Ok(n > 0)
1815        })
1816    }
1817
1818    /// Take the one naming attempt this session is allowed, or `None` when it has had it.
1819    ///
1820    /// The claim is a single `UPDATE`, so two processes racing on the same fresh session cannot
1821    /// both decide to spend a call — one gets the row, the other gets nothing.
1822    ///
1823    /// Two kinds of session are never claimed. A child of `delegate` has a name nobody reads
1824    /// outside the parent's list, and an `api` session is a headless call: naming one would put a
1825    /// second request on every programmatic turn, which is exactly the cost the cheap route exists
1826    /// to avoid. Both still get the derived name, which is free.
1827    ///
1828    /// Returns whether this caller owns the one call.
1829    pub fn claim_title_upgrade(&self, id: &str) -> Result<bool> {
1830        validate_id(id)?;
1831        self.with_db(|db| {
1832            let n = db.conn.execute(
1833                "UPDATE sessions SET title_note = 'trying'
1834                  WHERE id = ?1 AND title_source = 'derived' AND title_note IS NULL
1835                    AND origin NOT LIKE 'subagent:%' AND origin NOT LIKE 'bot:%'
1836                    AND origin NOT LIKE 'flare:%' AND origin <> 'api'",
1837                params![id],
1838            )?;
1839            Ok(n > 0)
1840        })
1841    }
1842
1843    /// Record why the naming attempt did not land. The derived title stays, and the note is what
1844    /// stops a second call: the failure is remembered rather than retried on every resume.
1845    pub fn title_attempt_failed(&self, id: &str, why: &str) -> Result<()> {
1846        validate_id(id)?;
1847        let why: String = why.chars().take(300).collect();
1848        self.with_db(|db| {
1849            db.conn.execute(
1850                "UPDATE sessions SET title_note = ?2 WHERE id = ?1",
1851                params![id, why],
1852            )?;
1853            Ok(())
1854        })
1855    }
1856
1857    /// Give up the claim without recording a failure: nothing was tried, so the session is still
1858    /// eligible if a later run is configured to name it.
1859    pub fn release_title_claim(&self, id: &str) -> Result<()> {
1860        validate_id(id)?;
1861        self.with_db(|db| {
1862            db.conn.execute(
1863                "UPDATE sessions SET title_note = NULL WHERE id = ?1 AND title_note = 'trying'",
1864                params![id],
1865            )?;
1866            Ok(())
1867        })
1868    }
1869
1870    /// Record what a turn cost, as one JSON snapshot beside the session (#344).
1871    ///
1872    /// `updated_ms` is deliberately untouched: this is bookkeeping about a turn, not activity in
1873    /// the session, and a write that reordered the list would make a session nobody is talking to
1874    /// jump to the top of `Today`.
1875    ///
1876    /// A write against a session that no longer exists is not an error. The turn had already
1877    /// happened; the record goes with the transcript it describes, and a run whose session was
1878    /// deleted mid-flight must not fail over its own bookkeeping.
1879    pub fn set_last_cost(&self, id: &str, cost: &TurnCost) -> Result<()> {
1880        validate_id(id)?;
1881        let body = serde_json::to_string(cost)
1882            .map_err(|e| Error::Session(format!("a turn's cost did not encode: {e}")))?;
1883        self.with_db(|db| {
1884            db.conn.execute(
1885                "UPDATE sessions SET last_cost = ?2 WHERE id = ?1",
1886                params![id, body],
1887            )?;
1888            Ok(())
1889        })
1890    }
1891
1892    /// Record what a model that can see said about one picture on a stored message (`#346`).
1893    ///
1894    /// Written once, on the turn that attached the picture, and read back by every later request.
1895    /// Without it a session that once attached a screenshot pays for the same description on every
1896    /// turn afterwards, and the prompt for a past turn changes under the conversation that is still
1897    /// talking about it — two ways to be wrong, both silent.
1898    /// Returns whether a stored picture was actually changed. `false` is not an error: the message
1899    /// or the picture is gone, and the description was for a turn that already happened — but the
1900    /// caller can now tell a write from a no-op, which it could not when this returned `()`.
1901    pub fn set_image_seen(&self, id: &str, seq: u64, index: usize, text: &str) -> Result<bool> {
1902        validate_id(id)?;
1903        let seq = i64::try_from(seq)
1904            .map_err(|_| Error::Session(format!("sequence {seq} is out of range")))?;
1905        self.with_db(|db| {
1906            // One transaction, because the body and the index are one decision: a crash between
1907            // them left a search hit whose content no longer matched the message it names.
1908            let tx = db.conn.unchecked_transaction()?;
1909            let row: Option<String> = tx
1910                .query_row(
1911                    "SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
1912                    params![id, seq],
1913                    |r| r.get(0),
1914                )
1915                .optional()?;
1916            let Some(body) = row else {
1917                return Ok(false);
1918            };
1919            let mut message: crate::message::Message = serde_json::from_str(&body)
1920                .map_err(|e| Error::Session(format!("a stored message did not decode: {e}")))?;
1921            let Some(image) = message.images.get_mut(index) else {
1922                return Ok(false);
1923            };
1924            image.seen = Some(text.to_string());
1925            let encoded = serde_json::to_string(&message)
1926                .map_err(|e| Error::Session(format!("a message did not encode: {e}")))?;
1927            let n = tx.execute(
1928                "UPDATE messages SET body = ?3 WHERE session_id = ?1 AND seq = ?2",
1929                params![id, seq, encoded],
1930            )?;
1931            // Guarded like every other FTS write: on a build without FTS5 the virtual table does
1932            // not exist, and this used to fail *after* the body had been written.
1933            if db.fts {
1934                tx.execute(
1935                    "UPDATE messages_fts SET content = ?3 WHERE session_id = ?1 AND seq = ?2",
1936                    params![id, seq, searchable(&message)],
1937                )?;
1938            }
1939            tx.commit()?;
1940            Ok(n > 0)
1941        })
1942    }
1943
1944    /// The last turn's numbers for one session, or `None` — never having run and having lost the
1945    /// record are the same answer here, because both mean "there is nothing honest to show".
1946    pub fn last_cost(&self, id: &str) -> Result<Option<TurnCost>> {
1947        validate_id(id)?;
1948        self.with_db(|db| {
1949            let body: Option<String> = db
1950                .conn
1951                .query_row(
1952                    "SELECT last_cost FROM sessions WHERE id = ?1",
1953                    params![id],
1954                    |r| r.get(0),
1955                )
1956                .optional()?
1957                .flatten();
1958            Ok(body.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()))
1959        })
1960    }
1961
1962    /// Pin or unpin a session: a pinned one sorts first in every listing and no retention
1963    /// policy deletes it. The transcript is left untouched.
1964    pub fn set_pinned(&self, id: &str, pinned: bool) -> Result<()> {
1965        validate_id(id)?;
1966        self.with_db(|db| {
1967            let n = db.conn.execute(
1968                "UPDATE sessions SET pinned = ?2 WHERE id = ?1",
1969                params![id, i64::from(pinned)],
1970            )?;
1971            if n == 0 {
1972                return Err(Error::Session(format!("no such session {id:?}")));
1973            }
1974            Ok(())
1975        })
1976    }
1977
1978    /// Archive or unarchive a session: an archived one is out of [`list`](Self::list) and out
1979    /// of every retention policy, and keeps its messages, its title and its place in
1980    /// [`search`](Self::search).
1981    ///
1982    /// The same shape as [`set_pinned`](Self::set_pinned) on purpose — one column, one
1983    /// `UPDATE`, and one function both surfaces call — so `archived` cannot be a thing the CLI
1984    /// knows and the dashboard guesses at.
1985    pub fn set_archived(&self, id: &str, archived: bool) -> Result<()> {
1986        validate_id(id)?;
1987        self.with_db(|db| {
1988            let n = db.conn.execute(
1989                "UPDATE sessions SET archived = ?2 WHERE id = ?1",
1990                params![id, i64::from(archived)],
1991            )?;
1992            if n == 0 {
1993                return Err(Error::Session(format!("no such session {id:?}")));
1994            }
1995            Ok(())
1996        })
1997    }
1998
1999    /// The session's stored memory. `Ok(None)` if there is none; an error if the row is
2000    /// unreadable, too large or not valid JSON of the expected shape. The content is not
2001    /// validated here: see [`Memory::validate`] and [`usable_memory`](Self::usable_memory).
2002    pub fn memory(&self, id: &str) -> Result<Option<Memory>> {
2003        validate_id(id)?;
2004        self.with_db(|db| {
2005            let body: Option<String> = db
2006                .conn
2007                .query_row(
2008                    "SELECT body FROM memory WHERE session_id = ?1",
2009                    params![id],
2010                    |r| r.get(0),
2011                )
2012                .optional()?;
2013            let Some(body) = body else { return Ok(None) };
2014            if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
2015                return Err(Error::Session(format!(
2016                    "{id}: memory is larger than {MAX_MEMORY_FILE_BYTES} bytes"
2017                )));
2018            }
2019            serde_json::from_str(&body)
2020                .map(Some)
2021                .map_err(|e| Error::Session(format!("{id}: memory: {e}")))
2022        })
2023    }
2024
2025    /// The stored memory if it passes [`Memory::validate`]: a missing, unreadable, corrupt or
2026    /// invalid row is treated as no memory.
2027    pub fn readable_memory(&self, id: &str) -> Option<Memory> {
2028        self.memory(id)
2029            .ok()
2030            .flatten()
2031            .filter(|m| m.validate().is_ok())
2032    }
2033
2034    /// Store the compiled handoff for `covered`, replacing whatever the record held.
2035    ///
2036    /// An existing memory that does *not* validate is replaced rather than preserved — a
2037    /// malformed record is not a fact worth defending, and refusing to save would leave the
2038    /// session with no handoff at all.
2039    pub fn save_handoff(
2040        &self,
2041        id: &str,
2042        covered: crate::context::Trimmed,
2043        span: (Option<u64>, Option<u64>),
2044        text: &str,
2045        judgement: Option<Judgement>,
2046    ) -> Result<()> {
2047        validate_id(id)?;
2048        let mut memory = self.current(id);
2049        memory.handoff = Some(Handoff {
2050            text: text.to_string(),
2051            version: crate::compact::VERSION.to_string(),
2052            covered_turns: covered.turns,
2053            covered_messages: covered.messages,
2054            covered_from: span.0,
2055            covered_to: span.1,
2056            generated_at_ms: now_ms(),
2057            judgement,
2058        });
2059        self.save_memory(id, &memory)
2060    }
2061
2062    /// The current memory as the starting point for writing: the stored record when this build
2063    /// can read it, else a blank record of this build's schema. A record this build cannot read is
2064    /// replaced rather than preserved — it is not a fact worth defending, and refusing to write
2065    /// would leave the session with no memory at all.
2066    fn current(&self, id: &str) -> Memory {
2067        let mut memory = self.readable_memory(id).unwrap_or(Memory {
2068            version: MEMORY_VERSION,
2069            handoff: None,
2070        });
2071        // Writing makes this a record of *this* build's schema, so a v1 file that gains a handoff
2072        // is stamped v3 and an old summary field is left behind, unread.
2073        memory.version = MEMORY_VERSION;
2074        memory
2075    }
2076
2077    /// Store `memory` for an existing session, replacing any earlier one. The transcript is
2078    /// never touched. Invalid memory is refused.
2079    ///
2080    /// Most callers want [`save_handoff`](Self::save_handoff), which builds the record around the
2081    /// document being stored; this is the raw setter.
2082    pub fn save_memory(&self, id: &str, memory: &Memory) -> Result<()> {
2083        validate_id(id)?;
2084        memory.validate().map_err(Error::Session)?;
2085        if !self.exists(id) {
2086            return Err(Error::Session(format!("no such session {id:?}")));
2087        }
2088        let body = serde_json::to_string(memory).map_err(|e| Error::Session(e.to_string()))?;
2089        // The reader refuses a body over the cap, and `readable_memory` turns that error into "no
2090        // memory" — so a record written past it is unreadable for the life of the session, and
2091        // every later `memory()` call errors while the agent silently recompiles on each request.
2092        // The store may not write what it cannot read back.
2093        if body.len() as u64 > MAX_MEMORY_FILE_BYTES {
2094            return Err(Error::Session(format!(
2095                "{id}: memory would be {} bytes, over the {MAX_MEMORY_FILE_BYTES}-byte record \
2096                 limit; store less, or raise `MAX_MEMORY_FILE_BYTES` in both the writer and the \
2097                 reader",
2098                body.len()
2099            )));
2100        }
2101        self.with_db(|db| {
2102            db.conn.execute(
2103                "INSERT INTO memory (session_id, body) VALUES (?1, ?2)
2104                 ON CONFLICT(session_id) DO UPDATE SET body = ?2",
2105                params![id, body],
2106            )?;
2107            Ok(())
2108        })
2109    }
2110
2111    /// Remove a session's transcript, title and memory. Errors if it does not exist.
2112    pub fn delete(&self, id: &str) -> Result<()> {
2113        validate_id(id)?;
2114        self.with_db(|db| {
2115            // One transaction, because the two statements are one decision. `messages` rows go with
2116            // the session by `ON DELETE CASCADE`, but `messages_fts` is a separate virtual table
2117            // with no foreign key to lean on: a crash between the two deletes used to leave index
2118            // rows pointing at messages that no longer existed, and every later `search()` then
2119            // failed on the first one instead of answering.
2120            let tx = db.conn.unchecked_transaction()?;
2121            let n = tx.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
2122            if n == 0 {
2123                // The transaction is dropped, which rolls it back: nothing was deleted, so there is
2124                // nothing to commit.
2125                return Err(Error::Session(format!("no such session {id:?}")));
2126            }
2127            if db.fts {
2128                tx.execute(
2129                    "DELETE FROM messages_fts WHERE session_id = ?1",
2130                    params![id],
2131                )?;
2132            }
2133            tx.commit()?;
2134            Ok(())
2135        })?;
2136        // The lock file is not in the database, and a stale one would keep naming a
2137        // session that no longer exists.
2138        //
2139        // The legacy files are removed as well, and not for tidiness: the importer adds any
2140        // `<id>.jsonl` it does not already know, so leaving one behind would resurrect a
2141        // session the user deleted the next time the store opened.
2142        for path in [
2143            self.lock_path(id)?,
2144            self.dir.join(format!("{id}.jsonl")),
2145            self.dir.join(format!("{id}.meta.json")),
2146            self.dir.join(format!("{id}.memory.json")),
2147        ] {
2148            match std::fs::remove_file(&path) {
2149                Ok(()) => {}
2150                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2151                Err(e) => return Err(Error::io(&path, e)),
2152            }
2153        }
2154        Ok(())
2155    }
2156
2157    /// What a retention policy would delete: sessions whose last activity is older than
2158    /// `keep_days` days, plus all but the newest `keep_count`. A limit of 0 is disabled; both 0
2159    /// selects nothing. Nothing is deleted here.
2160    ///
2161    /// Last activity is the newest record's timestamp. A session imported from a legacy
2162    /// file with no readable records keeps that file's modification time, so a corrupt old
2163    /// transcript can still be pruned.
2164    ///
2165    /// **A pinned session is never a candidate**, whatever the limits say, and the plan counts
2166    /// how many that kept out of reach so the caller can say so. A pinned session still holds
2167    /// its place in the ranking: the policy keeps N sessions, and a pinned one among them is
2168    /// still one of the N — the same accounting [`auto_prune`](Self::auto_prune)'s `protect` has
2169    /// always used.
2170    ///
2171    /// **An archived session is not a candidate either**, unless `include_archived` says so
2172    /// (`#240`): archiving is how a finished conversation stops taking a row, and a prune that
2173    /// quietly deleted the thing a person filed away would be a worse version of the delete it
2174    /// was chosen over. It keeps its place in the ranking too, like a pin, and is counted in
2175    /// [`PrunePlan::archived_kept`] so the caller can name the flag that would have taken it.
2176    pub fn prune_candidates(
2177        &self,
2178        keep_days: u64,
2179        keep_count: usize,
2180        now_ms: u64,
2181        include_archived: bool,
2182    ) -> Result<PrunePlan> {
2183        if keep_days == 0 && keep_count == 0 {
2184            return Ok(PrunePlan::default());
2185        }
2186        let mut sessions = self.session_ages()?;
2187        sessions.sort_by(|a, b| b.cmp(a));
2188        let cutoff = now_ms.saturating_sub(keep_days.saturating_mul(86_400_000));
2189        let mut plan = PrunePlan::default();
2190        for (i, (last, id, pinned, archived)) in sessions.into_iter().enumerate() {
2191            let over = (keep_count > 0 && i >= keep_count) || (keep_days > 0 && last < cutoff);
2192            if !over {
2193                continue;
2194            }
2195            if pinned {
2196                plan.pinned_kept += 1;
2197            } else if archived && !include_archived {
2198                plan.archived_kept += 1;
2199            } else {
2200                plan.candidates.push(id);
2201            }
2202        }
2203        Ok(plan)
2204    }
2205
2206    /// `(updated_ms, id, pinned, archived)` for every session, oldest first.
2207    fn session_ages(&self) -> Result<Vec<(u64, String, bool, bool)>> {
2208        self.with_db(|db| {
2209            let mut stmt = db.conn.prepare(
2210                "SELECT updated_ms, id, pinned, archived FROM sessions ORDER BY updated_ms",
2211            )?;
2212            let rows = stmt.query_map([], |r| {
2213                let ms: i64 = r.get(0)?;
2214                let id: String = r.get(1)?;
2215                let pinned: i64 = r.get(2)?;
2216                let archived: i64 = r.get(3)?;
2217                Ok((ms.max(0) as u64, id, pinned != 0, archived != 0))
2218            })?;
2219            Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
2220        })
2221    }
2222
2223    /// Apply a retention policy unattended, as `[sessions] auto_prune` does at CLI startup.
2224    /// Mirrors the manual `--force` rule: it deletes only when the policy would remove at
2225    /// most [`PRUNE_CONFIRM_ABOVE`] sessions, otherwise it deletes nothing and reports
2226    /// how many it would have removed. With both limits 0 it never deletes. `protect`
2227    /// (the session about to be resumed) is never deleted, even if it is old.
2228    ///
2229    /// An archived session is never deleted here: a policy that runs with nobody watching has
2230    /// no way to be given `--archived`, so the flag that would allow it is not one this path
2231    /// can take.
2232    pub fn auto_prune(
2233        &self,
2234        keep_days: u64,
2235        keep_count: usize,
2236        now_ms: u64,
2237        protect: Option<&str>,
2238    ) -> Result<AutoPrune> {
2239        if keep_days == 0 && keep_count == 0 {
2240            return Ok(AutoPrune::NoLimits);
2241        }
2242        let plan = self.prune_candidates(keep_days, keep_count, now_ms, false)?;
2243        let doomed: Vec<String> = plan
2244            .candidates
2245            .into_iter()
2246            .filter(|id| Some(id.as_str()) != protect)
2247            .collect();
2248        if doomed.is_empty() {
2249            return Ok(AutoPrune::Nothing);
2250        }
2251        if doomed.len() > PRUNE_CONFIRM_ABOVE {
2252            return Ok(AutoPrune::Skipped {
2253                would_remove: doomed.len(),
2254            });
2255        }
2256        let mut removed = 0;
2257        let mut failed = 0;
2258        for id in &doomed {
2259            match self.delete(id) {
2260                Ok(()) => removed += 1,
2261                Err(_) => failed += 1,
2262            }
2263        }
2264        Ok(AutoPrune::Pruned {
2265            removed,
2266            failed,
2267            pinned_kept: plan.pinned_kept,
2268        })
2269    }
2270
2271    /// The full stored transcript: every request/response turn and tool call, in order.
2272    /// The system prompt is not stored in sessions, so it is not included.
2273    pub fn export(&self, id: &str, format: ExportFormat) -> Result<String> {
2274        let records = self.load_records(id)?;
2275        let title = self.title(id).ok().flatten();
2276        match format {
2277            ExportFormat::Json => export_json(id, title, &records),
2278            ExportFormat::Markdown => Ok(export_markdown(id, title.as_deref(), &records)),
2279        }
2280    }
2281
2282    /// Sessions sorted newest first, pinned ones first of all — the list a person reads.
2283    ///
2284    /// Every surface lists through this method — `sessions list`, the `/resume` picker and the
2285    /// dashboard — so pinning is one ordering rule in one place rather than three.
2286    ///
2287    /// An **archived** session is not here, and that is the whole of what archiving means
2288    /// (`#240`): it keeps its messages, [`search`](Self::search) still finds it and
2289    /// [`list_with_archived`](Self::list_with_archived) still names it, so the one query that
2290    /// has to know about the flag is this one.
2291    pub fn list(&self) -> Result<Vec<SessionInfo>> {
2292        self.list_rows(false, false)
2293    }
2294
2295    /// Every session, archived ones included and marked, in the same order.
2296    ///
2297    /// For the places that have to *show* an archived row: `sessions list --archived`, the
2298    /// dashboard's filter, and the name lookups behind `search` and the recall block — a hit in
2299    /// an archived session is still a hit, and a session named by an id with no title beside it
2300    /// reads as a session that was deleted.
2301    pub fn list_with_archived(&self) -> Result<Vec<SessionInfo>> {
2302        self.list_rows(true, false)
2303    }
2304
2305    /// The bot conversations the Bots tab lists (`#509`), newest activity first.
2306    ///
2307    /// One query, the same one the human's list reads — a bot's sessions are *in* that list and
2308    /// filtered out of it, never a second table and never a second ordering rule. A bot's own
2309    /// row is what the tab groups: the newest conversation, when it last spoke, how much is in it.
2310    pub fn list_bots(&self) -> Result<Vec<BotSessions>> {
2311        let mut out: Vec<BotSessions> = Vec::new();
2312        for info in self.list_rows(true, true)? {
2313            let Some(name) = info.bot() else { continue };
2314            match out.iter_mut().find(|b| b.name == name) {
2315                // The listing is newest first, so the first row for a bot is its live one.
2316                Some(bot) => {
2317                    bot.sessions += 1;
2318                    if !info.archived {
2319                        bot.archived = false;
2320                    }
2321                }
2322                None => out.push(BotSessions {
2323                    name: name.to_string(),
2324                    sessions: 1,
2325                    messages: info.messages,
2326                    last_session: info.id.clone(),
2327                    last_activity_ms: info.updated_ms,
2328                    archived: info.archived,
2329                }),
2330            }
2331        }
2332        Ok(out)
2333    }
2334
2335    /// One query, one `WHERE`, so the two listings cannot disagree about ordering.
2336    ///
2337    /// `include_bots = false` is the human's list (`#509`): a bot's conversation is a session, but
2338    /// it is not one a person wrote, and a bot answering on a lane would otherwise push every
2339    /// conversation of theirs down the sidebar. The Bots tab is where it shows, through
2340    /// [`list_bots`](Self::list_bots), and the search that can reach it says so.
2341    fn list_rows(&self, include_archived: bool, include_bots: bool) -> Result<Vec<SessionInfo>> {
2342        self.with_db(|db| {
2343            // `rowid DESC` is the tiebreak, not `id DESC`: two rows written in the same
2344            // millisecond tie on `updated_ms`, and an id is text — `…-9` sorts above `…-10`
2345            // lexically, which named a cleared bot conversation newer than the one opened after
2346            // it (`#531`). `rowid` is the order the rows were stored in, so a tie is broken by
2347            // which conversation is actually the later one.
2348            let mut stmt = db.conn.prepare(
2349                "SELECT id, title, preview, messages, updated_ms, origin, pinned, archived, last_cost
2350                   FROM sessions
2351                  WHERE (archived = 0 OR ?1) AND (?2 OR origin NOT LIKE 'bot:%')
2352                  ORDER BY pinned DESC, updated_ms DESC, rowid DESC",
2353            )?;
2354            let rows = stmt.query_map(
2355                params![i64::from(include_archived), i64::from(include_bots)],
2356                |r| {
2357                let updated: i64 = r.get(4)?;
2358                let messages: i64 = r.get(3)?;
2359                let pinned: i64 = r.get(6)?;
2360                let archived: i64 = r.get(7)?;
2361                let cost: Option<String> = r.get(8)?;
2362                Ok(SessionInfo {
2363                    id: r.get(0)?,
2364                    title: r.get(1)?,
2365                    preview: r.get::<_, Option<String>>(2)?.unwrap_or_default(),
2366                    messages: messages.max(0) as usize,
2367                    updated_ms: updated.max(0) as u64,
2368                    origin: r.get(5)?,
2369                    pinned: pinned != 0,
2370                    archived: archived != 0,
2371                    // A blob that will not parse reads as absent: the row then shows `--` rather
2372                    // than a number nobody can vouch for.
2373                    cost: cost.and_then(|s| serde_json::from_str::<TurnCost>(&s).ok()),
2374                })
2375            })?;
2376            Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
2377        })
2378    }
2379
2380    /// Full-text search over the stored messages, newest first.
2381    ///
2382    /// Uses SQLite's FTS5 when the bundled library has it and `LIKE` when it does not — both are
2383    /// behind this one method, so callers never branch on it, and **both answer in the same order**:
2384    /// newest message first, ties broken by position. Which backend runs depends on how SQLite was
2385    /// compiled, and two installs must not disagree about what "the first 20 hits" means. FTS5
2386    /// matches on word boundaries, `LIKE` matches substrings; that difference is the price of the
2387    /// fallback, and it is one a searcher can see, unlike an arbitrary result order.
2388    pub fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>> {
2389        self.search_with(query, limit, false)
2390    }
2391
2392    /// [`search`](Self::search), with child conversations in the answer when `include_children`.
2393    ///
2394    /// The human's discovery results leave bots and flares out (`#509`, `#171`): a bot answering
2395    /// on a lane, or a flare reading a crate, writes to
2396    /// the same archive, and "search my transcripts" that returned someone else's conversation —
2397    /// one the searcher never had — would be a search that lies about who said it. The agent's
2398    /// `session_search` exposes the flag; nothing else has a reason to.
2399    pub fn search_with(
2400        &self,
2401        query: &str,
2402        limit: usize,
2403        include_children: bool,
2404    ) -> Result<Vec<SearchHit>> {
2405        let q = query.trim();
2406        if q.is_empty() {
2407            return Ok(Vec::new());
2408        }
2409        let limit = limit.clamp(1, 1000) as i64;
2410        self.with_db(|db| Self::search_in(db, q, limit, db.fts, include_children))
2411    }
2412
2413    /// Search one backend's way.
2414    ///
2415    /// `use_fts = false` is the fallback a build without FTS5 takes. It is a parameter rather than
2416    /// a read of `db.fts` so the tests can hold the fallback to the same answers on a build that
2417    /// has FTS5 — the two must agree, because which one runs depends on how SQLite was compiled
2418    /// and nobody should get different results from two installs.
2419    fn search_in(
2420        db: &Db,
2421        q: &str,
2422        limit: i64,
2423        use_fts: bool,
2424        include_children: bool,
2425    ) -> Result<Vec<SearchHit>> {
2426        let children = i64::from(include_children);
2427        let mut out = Vec::new();
2428        // The names first, because "the session I called X" is the strongest thing a search box
2429        // can be told: a session named `gateway restart loop` should answer to those words even
2430        // if nothing in its transcript ever used them together. A name hit points at `seq` 0 —
2431        // the name was made from the opening message, so that is where to read from — and says
2432        // `title` in the role column rather than pretending to be a message.
2433        let mut named = db.conn.prepare(
2434            "SELECT id, title, updated_ms FROM sessions
2435              WHERE title LIKE '%' || ?1 || '%' ESCAPE '\\'
2436                AND (?3 = 1 OR (origin NOT LIKE 'bot:%' AND origin NOT LIKE 'flare:%'))
2437              ORDER BY pinned DESC, archived ASC, updated_ms DESC LIMIT ?2",
2438        )?;
2439        let rows = named.query_map(params![like_literal(q), limit, children], |r| {
2440            Ok((
2441                r.get::<_, String>(0)?,
2442                r.get::<_, String>(1)?,
2443                r.get::<_, i64>(2)?,
2444            ))
2445        })?;
2446        for row in rows {
2447            let (session_id, title, updated_ms) = row?;
2448            out.push(SearchHit {
2449                session_id,
2450                seq: 0,
2451                at_ms: updated_ms.max(0) as u64,
2452                role: "title".to_string(),
2453                snippet: title,
2454            });
2455        }
2456
2457        // Own-tail rows are skipped, and a skipped row does not count toward `limit`, so the read
2458        // is wider than the answer. If even that page held nothing but the caller's own calls,
2459        // widen again rather than answer "no match" about a transcript that does match: the last
2460        // few searches must never be able to hide the archive (`#498`).
2461        let mut budget = limit.saturating_mul(4).max(limit + 8);
2462        loop {
2463            let (found, read) =
2464                Self::message_hits(db, q, limit, budget, use_fts, include_children)?;
2465            let room_to_widen = read >= budget && budget < OWN_TAIL_BUDGET_CAP;
2466            if !found.is_empty() || !room_to_widen {
2467                out.extend(found);
2468                break;
2469            }
2470            budget = (budget * 4).min(OWN_TAIL_BUDGET_CAP);
2471        }
2472        Ok(out)
2473    }
2474
2475    /// Up to `limit` message hits, read out of `budget` matching rows, and how many rows were read
2476    /// — the caller widens the budget when a page turned out to hold nothing.
2477    ///
2478    /// `use_fts = false` is the fallback a build without FTS5 takes. It is a parameter rather than
2479    /// a read of `db.fts` so the tests can hold the fallback to the same answers on a build that
2480    /// has FTS5 — the two must agree, because which one runs depends on how SQLite was compiled
2481    /// and nobody should get different results from two installs.
2482    fn message_hits(
2483        db: &Db,
2484        q: &str,
2485        limit: i64,
2486        budget: i64,
2487        use_fts: bool,
2488        include_children: bool,
2489    ) -> Result<(Vec<SearchHit>, i64)> {
2490        let children = i64::from(include_children);
2491        let mut found = Vec::new();
2492        let mut read = 0i64;
2493        if use_fts {
2494            // Every term quoted: a search box is not a place to raise a syntax error,
2495            // and doubled quotes are how FTS5 escapes one.
2496            let terms: Vec<String> = q
2497                .split_whitespace()
2498                .map(|t| format!("\"{}\"", t.replace('"', "\"\"")))
2499                .collect();
2500            let mut stmt = db.conn.prepare(
2501                // Joined back to `messages` for one reason: the ordering. FTS5 has no clock, and
2502                // without an ORDER BY it answers in rowid order, so `LIMIT` would cut an arbitrary
2503                // slice rather than the newest one. `sessions` rides along for the other reason a
2504                // row is joined: a bot's conversation is not the human's discovery (`#509`).
2505                "SELECT f.session_id, f.seq, f.content
2506                 FROM messages_fts f
2507                 JOIN messages m ON m.session_id = f.session_id AND m.seq = f.seq
2508                 JOIN sessions s ON s.id = f.session_id
2509                 WHERE f.messages_fts MATCH ?1
2510                   AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
2511                 ORDER BY m.at_ms DESC, m.seq DESC
2512                 LIMIT ?2",
2513            )?;
2514            let rows = stmt.query_map(params![terms.join(" "), budget, children], |r| {
2515                Ok((
2516                    r.get::<_, String>(0)?,
2517                    r.get::<_, i64>(1)?,
2518                    r.get::<_, String>(2)?,
2519                ))
2520            })?;
2521            for row in rows {
2522                let (session_id, seq, content) = row?;
2523                read += 1;
2524                if is_own_tail(&db.conn, &session_id, seq)? {
2525                    continue;
2526                }
2527                if let Some(found_hit) = hit(&db.conn, session_id, seq, &content)? {
2528                    found.push(found_hit);
2529                    if found.len() as i64 >= limit {
2530                        break;
2531                    }
2532                }
2533            }
2534        } else {
2535            // `ESCAPE '\'` and an escaped literal: `%` and `_` mean themselves in a search box, so
2536            // `100%` finds the text `100%` and not everything containing `100`.
2537            let mut stmt = db.conn.prepare(
2538                "SELECT m.session_id, m.seq, m.body FROM messages m
2539                 JOIN sessions s ON s.id = m.session_id
2540                 WHERE m.body LIKE '%' || ?1 || '%' ESCAPE '\\'
2541                   AND (?3 = 1 OR (s.origin NOT LIKE 'bot:%' AND s.origin NOT LIKE 'flare:%'))
2542                 ORDER BY m.at_ms DESC, m.seq DESC LIMIT ?2",
2543            )?;
2544            let rows = stmt.query_map(params![like_literal(q), budget, children], |r| {
2545                Ok((
2546                    r.get::<_, String>(0)?,
2547                    r.get::<_, i64>(1)?,
2548                    r.get::<_, String>(2)?,
2549                ))
2550            })?;
2551            for row in rows {
2552                let (session_id, seq, body) = row?;
2553                read += 1;
2554                let message: Message = serde_json::from_str(&body)
2555                    .map_err(|e| Error::Session(format!("{session_id}:{seq}: {e}")))?;
2556                if is_own_tail(&db.conn, &session_id, seq)? {
2557                    continue;
2558                }
2559                if let Some(found_hit) = hit(&db.conn, session_id, seq, &searchable(&message))? {
2560                    found.push(found_hit);
2561                    if found.len() as i64 >= limit {
2562                        break;
2563                    }
2564                }
2565            }
2566        }
2567        Ok((found, read))
2568    }
2569
2570    /// Whether full-text search is available (the bundled library normally has it).
2571    pub fn has_fts(&self) -> bool {
2572        self.with_db(|db| Ok(db.fts)).unwrap_or(false)
2573    }
2574}
2575
2576/// One search result: where the match is and enough text to recognise it.
2577#[derive(Debug, Clone, PartialEq, Eq)]
2578pub struct SearchHit {
2579    pub session_id: String,
2580    /// Position in the session, so the caller can load around it.
2581    pub seq: usize,
2582    pub at_ms: u64,
2583    pub role: String,
2584    /// The matching message's text, trimmed to a readable length around the match.
2585    pub snippet: String,
2586}
2587
2588/// One hit, or `None` when the message it points at is gone.
2589///
2590/// The FTS index can name a row the `messages` table no longer holds — an index written by a build
2591/// whose delete was two statements, or a crash inside one. That is a stale index entry, not a
2592/// failure of the query, so it is dropped rather than turned into an error that would take every
2593/// other hit with it.
2594fn hit(
2595    conn: &Connection,
2596    session_id: String,
2597    seq: i64,
2598    content: &str,
2599) -> Result<Option<SearchHit>> {
2600    let found: Option<(i64, String)> = conn
2601        .query_row(
2602            "SELECT at_ms, role FROM messages WHERE session_id = ?1 AND seq = ?2",
2603            params![session_id, seq],
2604            |r| Ok((r.get(0)?, r.get(1)?)),
2605        )
2606        .map(Some)
2607        .or_else(|e| match e {
2608            rusqlite::Error::QueryReturnedNoRows => Ok(None),
2609            other => Err(other),
2610        })?;
2611    let Some((at_ms, role)) = found else {
2612        return Ok(None);
2613    };
2614    Ok(Some(SearchHit {
2615        session_id,
2616        seq: seq.max(0) as usize,
2617        at_ms: at_ms.max(0) as u64,
2618        role,
2619        snippet: snippet(content, 160),
2620    }))
2621}
2622
2623/// The tool whose own calls are never a search result.
2624///
2625/// `session_search` searches the archive it is writing to, so every call it makes adds a row the
2626/// next call finds: the top hit is always the search that just ran, the result set grows, and the
2627/// model spends a turn re-reading its own tail instead of the answer (`#498`). A call to it, and
2628/// the answer to one, are the only rows a search drops.
2629const OWN_TAIL_TOOL: &str = "session_search";
2630
2631/// How far back to look for the assistant row that made a tool call. A transcript's calls and
2632/// their answers are adjacent; anything further is another turn's call and cannot be this row's.
2633const OWN_TAIL_LOOKBACK: i64 = 20;
2634
2635/// The most rows one search will read to get past the caller's own calls. A page of 512 matching
2636/// rows that is *all* own tail is not a search problem any more; the answer is "no match".
2637const OWN_TAIL_BUDGET_CAP: i64 = 512;
2638
2639/// Whether the row at `(session_id, seq)` is a call to [`OWN_TAIL_TOOL`], or the answer to one.
2640///
2641/// Both shapes are dropped: the call row is the `assistant` message carrying the `tool_calls`, and
2642/// the answer is the `tool` message whose `tool_call_id` names that call. A row we cannot parse is
2643/// not ours — a search is not the place to fail on a body this build no longer understands.
2644fn is_own_tail(conn: &Connection, session_id: &str, seq: i64) -> Result<bool> {
2645    let body: Option<String> = conn
2646        .query_row(
2647            "SELECT body FROM messages WHERE session_id = ?1 AND seq = ?2",
2648            params![session_id, seq],
2649            |r| r.get(0),
2650        )
2651        .map(Some)
2652        .or_else(|e| match e {
2653            rusqlite::Error::QueryReturnedNoRows => Ok(None),
2654            other => Err(other),
2655        })?;
2656    let Some(body) = body else {
2657        return Ok(false);
2658    };
2659    let Ok(message) = serde_json::from_str::<Message>(&body) else {
2660        return Ok(false);
2661    };
2662    if message
2663        .tool_calls
2664        .iter()
2665        .any(|call| call.function.name == OWN_TAIL_TOOL)
2666    {
2667        return Ok(true);
2668    }
2669    let Some(answer_to) = message.tool_call_id.as_deref() else {
2670        return Ok(false);
2671    };
2672    let mut stmt = conn.prepare(
2673        "SELECT body FROM messages
2674          WHERE session_id = ?1 AND seq < ?2 AND role = 'assistant'
2675          ORDER BY seq DESC LIMIT ?3",
2676    )?;
2677    let rows = stmt.query_map(params![session_id, seq, OWN_TAIL_LOOKBACK], |r| {
2678        r.get::<_, String>(0)
2679    })?;
2680    for row in rows {
2681        let Ok(called) = serde_json::from_str::<Message>(&row?) else {
2682            continue;
2683        };
2684        if called
2685            .tool_calls
2686            .iter()
2687            .any(|call| call.id == answer_to && call.function.name == OWN_TAIL_TOOL)
2688        {
2689            return Ok(true);
2690        }
2691    }
2692    Ok(false)
2693}
2694
2695/// A search string as a `LIKE` literal: `\`, `%` and `_` mean themselves in a search box, and the
2696/// query's `ESCAPE '\'` is what keeps them from being wildcards.
2697fn like_literal(q: &str) -> String {
2698    let mut out = String::with_capacity(q.len());
2699    for c in q.chars() {
2700        if matches!(c, '\\' | '%' | '_') {
2701            out.push('\\');
2702        }
2703        out.push(c);
2704    }
2705    out
2706}
2707
2708/// The text a message contributes to search: its content plus any tool call arguments,
2709/// so `git_status`-style calls are findable by what they did.
2710fn searchable(message: &Message) -> String {
2711    // The picture's label and any description of it are part of what the session says, so a search
2712    // can find the turn by what was in the screenshot (`#362`).
2713    let mut out = message.text_with_pictures();
2714    for call in &message.tool_calls {
2715        if !out.is_empty() {
2716            out.push('\n');
2717        }
2718        out.push_str(&call.function.name);
2719        out.push(' ');
2720        out.push_str(&call.function.arguments);
2721    }
2722    out
2723}
2724
2725/// The columns [`SessionStore::flare_runs`] and [`SessionStore::flare_run`] both read, in the one
2726/// order they are selected: six columns, then the cost, in the same shape a session's row has.
2727fn run_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<FlareRunRow> {
2728    let started: i64 = r.get(6)?;
2729    Ok(FlareRunRow {
2730        id: r.get(0)?,
2731        task: r.get(1)?,
2732        state: r.get(2)?,
2733        routes: r
2734            .get::<_, String>(3)?
2735            .split(',')
2736            .filter(|s| !s.is_empty())
2737            .map(str::to_string)
2738            .collect(),
2739        jobs: r.get::<_, i64>(4)?.max(0) as usize,
2740        parent: r.get(5)?,
2741        started_ms: started.max(0) as u64,
2742        finished_ms: r.get::<_, Option<i64>>(7)?.map(|v| v.max(0) as u64),
2743        prompt_tokens: r.get::<_, Option<i64>>(8)?.map(|v| v as u64),
2744        completion_tokens: r.get::<_, Option<i64>>(9)?.map(|v| v as u64),
2745        iterations: r.get::<_, Option<i64>>(10)?.unwrap_or(0).max(0) as usize,
2746    })
2747}
2748
2749fn snippet(text: &str, max: usize) -> String {
2750    let one: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
2751    if one.chars().count() <= max {
2752        return one;
2753    }
2754    one.chars().take(max.saturating_sub(1)).collect::<String>() + "…"
2755}
2756
2757fn role_name(role: Role) -> &'static str {
2758    match role {
2759        Role::System => "system",
2760        Role::User => "user",
2761        Role::Assistant => "assistant",
2762        Role::Tool => "tool",
2763    }
2764}
2765
2766/// The open database plus what it turned out to support.
2767///
2768/// Crate-visible so tests can act on the connection (forcing a write failure); nothing
2769/// outside this module uses it for anything else.
2770pub(crate) struct Db {
2771    pub(crate) conn: Connection,
2772    /// FTS5 is compiled in and the table exists; otherwise [`SessionStore::search`] falls
2773    /// back to `LIKE`.
2774    fts: bool,
2775}
2776
2777impl Db {
2778    fn open(dir: &Path) -> Result<Self> {
2779        std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
2780        // Owner-only before the database exists. `-wal` and `-shm` are created by SQLite beside
2781        // the file with `0666 & ~umask`, and are never chmodded by it: a `0600` `sessions.db` in
2782        // a `0775` directory is a transcript everybody on the host can read, and the sidecar holds
2783        // every turn not yet checkpointed. The mode is applied on open as well as on create,
2784        // because a directory made by an older build (or by hand) is still `0775` now.
2785        #[cfg(unix)]
2786        {
2787            use std::os::unix::fs::PermissionsExt;
2788            let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
2789        }
2790        let path = dir.join(DB_FILE);
2791        let conn = Connection::open(&path).map_err(db_err(&path))?;
2792        // WAL: a reader (the dashboard, a `sessions list`) never blocks the CLI's writes.
2793        let _: String = conn
2794            .query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
2795            .map_err(db_err(&path))?;
2796        conn.execute_batch(
2797            "PRAGMA foreign_keys = ON;
2798             PRAGMA synchronous = NORMAL;
2799             PRAGMA busy_timeout = 5000;",
2800        )
2801        .map_err(db_err(&path))?;
2802        conn.execute_batch(SCHEMA).map_err(db_err(&path))?;
2803        // The sidecars exist once there has been a write, so this runs after the schema. The
2804        // directory already keeps them private; this is what keeps them private wherever the
2805        // files are copied to.
2806        #[cfg(unix)]
2807        {
2808            use std::os::unix::fs::PermissionsExt;
2809            for f in [
2810                path.clone(),
2811                path.with_extension("db-wal"),
2812                path.with_extension("db-shm"),
2813            ] {
2814                if f.exists() {
2815                    let _ = std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o600));
2816                }
2817            }
2818        }
2819        // `CREATE TABLE IF NOT EXISTS` does nothing to a table that already exists, so every
2820        // column added after the first release needs its own step here. Without it an older
2821        // `sessions.db` keeps opening and simply has no `pinned`, which shows up much later as
2822        // "no such column" on someone's real state directory.
2823        if !has_column(&conn, "sessions", "pinned").map_err(db_err(&path))? {
2824            conn.execute_batch("ALTER TABLE sessions ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0")
2825                .map_err(db_err(&path))?;
2826        }
2827        // `#240`: an archive flag. The `DEFAULT 0` is the whole migration — every session that
2828        // existed before this column was in the list, and stays there.
2829        if !has_column(&conn, "sessions", "archived").map_err(db_err(&path))? {
2830            conn.execute_batch(
2831                "ALTER TABLE sessions ADD COLUMN archived INTEGER NOT NULL DEFAULT 0",
2832            )
2833            .map_err(db_err(&path))?;
2834        }
2835        // `#344`: the last turn's numbers, as one JSON snapshot. Nullable on purpose — a session
2836        // that has never finished a turn has none, and "no record" must not look like a zero.
2837        // `#340`: who decided. `NULL` on a row written before the column existed is honest —
2838        // nobody recorded it — and `user` is what every answer through `eclipse approve` writes.
2839        if !has_column(&conn, "approvals", "by").map_err(db_err(&path))? {
2840            conn.execute_batch("ALTER TABLE approvals ADD COLUMN by TEXT")
2841                .map_err(db_err(&path))?;
2842        }
2843        if !has_column(&conn, "sessions", "last_cost").map_err(db_err(&path))? {
2844            conn.execute_batch("ALTER TABLE sessions ADD COLUMN last_cost TEXT")
2845                .map_err(db_err(&path))?;
2846        }
2847        // `title_source` says who wrote a title and `title_note` says what happened to the naming
2848        // attempt, which is also what stops a second one. Added as a pair: a database with one and
2849        // not the other would open and then fail on the first `NULL` it read.
2850        let title_source_added =
2851            !has_column(&conn, "sessions", "title_source").map_err(db_err(&path))?;
2852        if title_source_added {
2853            conn.execute_batch(
2854                "ALTER TABLE sessions ADD COLUMN title_source TEXT;
2855                 ALTER TABLE sessions ADD COLUMN title_note TEXT;",
2856            )
2857            .map_err(db_err(&path))?;
2858        } else if !has_column(&conn, "sessions", "title_note").map_err(db_err(&path))? {
2859            conn.execute_batch("ALTER TABLE sessions ADD COLUMN title_note TEXT")
2860                .map_err(db_err(&path))?;
2861        }
2862        if title_source_added {
2863            // Every title that exists before this column came into being was typed by a person:
2864            // `rename` was the only thing that wrote one. Saying so once, here, is what keeps the
2865            // naming pass from relabelling somebody's session as machine-named.
2866            conn.execute_batch("UPDATE sessions SET title_source = 'user' WHERE title IS NOT NULL")
2867                .map_err(db_err(&path))?;
2868        }
2869
2870        let fts = match conn.execute_batch(FTS_SCHEMA) {
2871            Ok(()) => true,
2872            // A build without FTS5 is not an error: search falls back to LIKE.
2873            Err(_) => false,
2874        };
2875
2876        let mut db = Self { conn, fts };
2877        let warnings = db.import_legacy(dir)?;
2878        for w in warnings {
2879            eprintln!("warning: {w}");
2880        }
2881        Ok(db)
2882    }
2883
2884    /// Import every `<id>.jsonl` transcript that is not already in the database, once.
2885    ///
2886    /// The files are left exactly where they are: a database that turns out to be wrong
2887    /// must never be the reason someone's transcript is gone. Import is idempotent —
2888    /// a session id already present is skipped — so a deleted database re-imports cleanly.
2889    fn import_legacy(&mut self, dir: &Path) -> Result<Vec<String>> {
2890        let rd = match std::fs::read_dir(dir) {
2891            Ok(rd) => rd,
2892            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
2893            Err(e) => return Err(Error::io(dir, e)),
2894        };
2895        let mut files: Vec<PathBuf> = Vec::new();
2896        for entry in rd.flatten() {
2897            let path = entry.path();
2898            if path.extension().and_then(|e| e.to_str()) == Some("jsonl") {
2899                files.push(path);
2900            }
2901        }
2902        files.sort();
2903        let mut warnings = Vec::new();
2904        let tx = self.conn.transaction().map_err(db_err(dir))?;
2905        for path in files {
2906            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
2907                continue;
2908            };
2909            if validate_id(id).is_err() {
2910                warnings.push(format!(
2911                    "{}: ignoring, not a valid session id",
2912                    path.display()
2913                ));
2914                continue;
2915            }
2916            let already: Option<i64> = tx
2917                .query_row("SELECT 1 FROM sessions WHERE id = ?1", params![id], |r| {
2918                    r.get(0)
2919                })
2920                .optional()
2921                .map_err(db_err(&path))?;
2922            if already.is_some() {
2923                continue;
2924            }
2925            match read_legacy(&path) {
2926                Ok(legacy) => {
2927                    let first = legacy.records.first().map(|r| r.ts);
2928                    let last = legacy.records.last().map(|r| r.ts);
2929                    let mtime = std::fs::metadata(&path)
2930                        .and_then(|m| m.modified())
2931                        .ok()
2932                        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
2933                        .map_or(0, |d| d.as_millis() as u64);
2934                    let created = first.unwrap_or(mtime) as i64;
2935                    let updated = last.unwrap_or(mtime) as i64;
2936                    let preview = legacy.preview();
2937                    tx.execute(
2938                        "INSERT INTO sessions
2939                           (id, created_ms, updated_ms, title, preview, messages, origin)
2940                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'jsonl')",
2941                        params![
2942                            id,
2943                            created,
2944                            updated,
2945                            legacy.title,
2946                            preview,
2947                            legacy.records.len() as i64
2948                        ],
2949                    )
2950                    .map_err(db_err(&path))?;
2951                    for (i, rec) in legacy.records.iter().enumerate() {
2952                        let body = serde_json::to_string(&rec.message)
2953                            .map_err(|e| Error::Session(e.to_string()))?;
2954                        tx.execute(
2955                            "INSERT INTO messages (session_id, seq, at_ms, role, body)
2956                             VALUES (?1, ?2, ?3, ?4, ?5)",
2957                            params![
2958                                id,
2959                                i as i64,
2960                                rec.ts as i64,
2961                                role_name(rec.message.role),
2962                                body
2963                            ],
2964                        )
2965                        .map_err(db_err(&path))?;
2966                        if self.fts {
2967                            tx.execute(
2968                                "INSERT INTO messages_fts (session_id, seq, content)
2969                                 VALUES (?1, ?2, ?3)",
2970                                params![id, i as i64, searchable(&rec.message)],
2971                            )
2972                            .map_err(db_err(&path))?;
2973                        }
2974                    }
2975                    if let Some(body) = legacy.memory {
2976                        // Stored as found: an unparseable sidecar is imported so that
2977                        // `memory()` can report it and `usable_memory()` can refuse it,
2978                        // rather than disappearing at import time.
2979                        tx.execute(
2980                            "INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, ?2)",
2981                            params![id, body],
2982                        )
2983                        .map_err(db_err(&path))?;
2984                    }
2985                    if let Some(w) = legacy.warning {
2986                        warnings.push(w);
2987                    }
2988                }
2989                Err(e) => {
2990                    // One unreadable transcript must not stop the import of the rest, and
2991                    // must not be deleted either.
2992                    warnings.push(format!("{}: not imported: {e}", path.display()));
2993                }
2994            }
2995        }
2996        tx.commit().map_err(db_err(dir))?;
2997        Ok(warnings)
2998    }
2999}
3000
3001/// The database file inside the session directory.
3002const DB_FILE: &str = "sessions.db";
3003
3004/// The file a store keeps its sessions in, under the directory it was given.
3005///
3006/// Public because a verb that only *counts* them must not open one: [`SessionStore::list`]
3007/// creates the directory, the database and its schema on first use, and a report is not a write.
3008pub fn db_path(dir: &Path) -> PathBuf {
3009    dir.join(DB_FILE)
3010}
3011
3012const SCHEMA: &str = "
3013CREATE TABLE IF NOT EXISTS sessions (
3014  id          TEXT PRIMARY KEY,
3015  created_ms  INTEGER NOT NULL,
3016  updated_ms  INTEGER NOT NULL,
3017  title       TEXT,
3018  preview     TEXT,
3019  messages    INTEGER NOT NULL DEFAULT 0,
3020  origin      TEXT NOT NULL DEFAULT 'native',
3021  pinned      INTEGER NOT NULL DEFAULT 0,
3022  archived    INTEGER NOT NULL DEFAULT 0,
3023  title_source TEXT,
3024  title_note  TEXT,
3025  last_cost   TEXT
3026);
3027CREATE INDEX IF NOT EXISTS sessions_by_activity ON sessions(updated_ms DESC);
3028CREATE TABLE IF NOT EXISTS messages (
3029  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3030  seq        INTEGER NOT NULL,
3031  at_ms      INTEGER NOT NULL,
3032  role       TEXT NOT NULL,
3033  body       TEXT NOT NULL,
3034  PRIMARY KEY (session_id, seq)
3035);
3036CREATE TABLE IF NOT EXISTS memory (
3037  session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
3038  body       TEXT NOT NULL
3039);
3040CREATE TABLE IF NOT EXISTS approvals (
3041  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3042  seq        INTEGER NOT NULL,
3043  ord        INTEGER NOT NULL,
3044  call_id    TEXT NOT NULL,
3045  tool       TEXT NOT NULL,
3046  summary    TEXT NOT NULL,
3047  args       TEXT NOT NULL,
3048  decision   TEXT,
3049  decided_ms INTEGER,
3050  PRIMARY KEY (session_id, seq, ord)
3051);
3052CREATE INDEX IF NOT EXISTS approvals_by_call ON approvals(session_id, call_id);
3053-- `#340`: who answered a call, and a log that outlives the row.
3054--
3055-- `approvals` is deliberately transient — `clear_call` deletes the row once the answer is in the
3056-- transcript, because a row left behind would let a resume replay a call that already ran. That
3057-- makes it the wrong place to ask what the model waved through last week, so the decider goes
3058-- on the row (who answered *this* waiting call) and every ruling is also appended here, where
3059-- nothing ever deletes it.
3060CREATE TABLE IF NOT EXISTS approval_log (
3061  session_id TEXT NOT NULL,
3062  at_ms      INTEGER NOT NULL,
3063  call_id    TEXT NOT NULL,
3064  tool       TEXT NOT NULL,
3065  summary    TEXT NOT NULL,
3066  decision   TEXT NOT NULL,
3067  by         TEXT NOT NULL
3068);
3069CREATE INDEX IF NOT EXISTS approval_log_by_session ON approval_log(session_id, at_ms);
3070-- `#447`: how a tool call ended, kept beside the message rather than inside it. A stored `tool`
3071-- message is the model's wire shape and carries no verdict, so a replayed row used to read the
3072-- mark off the text and call a failed `read_file` a ✓. The call id is the key the dashboard
3073-- already joins on.
3074CREATE TABLE IF NOT EXISTS tool_outcomes (
3075  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3076  call_id    TEXT NOT NULL,
3077  is_error   INTEGER NOT NULL,
3078  PRIMARY KEY (session_id, call_id)
3079);
3080-- `#172`: one standing goal per session, and every judgement made about it. A new table rather
3081-- than a column, so an older `sessions.db` opens without a migration step and a session that has
3082-- never had a goal keeps no row at all. The foreign key is the whole of `deleting a session
3083-- deletes its goal`.
3084CREATE TABLE IF NOT EXISTS goals (
3085  session_id  TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
3086  text        TEXT NOT NULL,
3087  gate        TEXT,
3088  budget      INTEGER NOT NULL,
3089  turns       INTEGER NOT NULL DEFAULT 0,
3090  state       TEXT NOT NULL,
3091  note        TEXT,
3092  garbage     INTEGER NOT NULL DEFAULT 0,
3093  created_ms  INTEGER NOT NULL,
3094  updated_ms  INTEGER NOT NULL
3095);
3096CREATE TABLE IF NOT EXISTS goal_turns (
3097  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
3098  turn       INTEGER NOT NULL,
3099  verdict    TEXT NOT NULL,
3100  why        TEXT,
3101  at_ms      INTEGER NOT NULL,
3102  PRIMARY KEY (session_id, turn)
3103);
3104-- `#171`: a flare run and its N children. A run that cannot be listed after a restart is a run
3105-- that cannot be cancelled, so the ledger is a table rather than a field on the agent that
3106-- started it — and it is two tables because the run's cost is a sum over children that may have
3107-- failed, and a failed child's cost still happened.
3108CREATE TABLE IF NOT EXISTS flare_runs (
3109  id          TEXT PRIMARY KEY,
3110  task        TEXT NOT NULL,
3111  state       TEXT NOT NULL,
3112  routes      TEXT NOT NULL,
3113  jobs        INTEGER NOT NULL,
3114  parent      TEXT,
3115  started_ms  INTEGER NOT NULL,
3116  finished_ms INTEGER,
3117  prompt_tokens     INTEGER,
3118  completion_tokens INTEGER,
3119  iterations  INTEGER,
3120  cancel_requested INTEGER NOT NULL DEFAULT 0
3121);
3122CREATE INDEX IF NOT EXISTS flare_runs_by_start ON flare_runs(started_ms DESC);
3123CREATE TABLE IF NOT EXISTS flare_jobs (
3124  run_id     TEXT NOT NULL REFERENCES flare_runs(id) ON DELETE CASCADE,
3125  n          INTEGER NOT NULL,
3126  route      TEXT NOT NULL,
3127  session_id TEXT,
3128  state      TEXT NOT NULL,
3129  prompt_tokens     INTEGER,
3130  completion_tokens INTEGER,
3131  iterations INTEGER,
3132  why        TEXT,
3133  PRIMARY KEY (run_id, n)
3134);
3135";
3136
3137/// A plain FTS5 table: the message rows themselves stay the source of truth, so a build
3138/// without FTS5 loses nothing but the index.
3139const FTS_SCHEMA: &str = "
3140CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
3141  session_id UNINDEXED,
3142  seq        UNINDEXED,
3143  content
3144);
3145";
3146
3147fn db_err(path: &Path) -> impl Fn(rusqlite::Error) -> Error + '_ {
3148    move |e| Error::Session(format!("{}: {e}", path.display()))
3149}
3150
3151/// Whether `table` already has `column`. Used by the migration steps above, which cannot lean
3152/// on `CREATE TABLE IF NOT EXISTS`: that clause says nothing at all about an existing table.
3153fn has_column(conn: &Connection, table: &str, column: &str) -> rusqlite::Result<bool> {
3154    let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
3155    let mut rows = stmt.query([])?;
3156    while let Some(row) = rows.next()? {
3157        let name: String = row.get(1)?;
3158        if name == column {
3159            return Ok(true);
3160        }
3161    }
3162    Ok(false)
3163}
3164
3165/// What a legacy `.jsonl` file held.
3166struct Legacy {
3167    records: Vec<Record>,
3168    title: Option<String>,
3169    /// The memory sidecar verbatim; parse failures are reported by `memory()`, not here.
3170    memory: Option<String>,
3171    warning: Option<String>,
3172}
3173
3174impl Legacy {
3175    fn preview(&self) -> Option<String> {
3176        self.records
3177            .iter()
3178            .find(|r| r.message.role == Role::User)
3179            .and_then(|r| r.message.content.as_deref())
3180            .map(|t| {
3181                let one_line: String = t.split_whitespace().collect::<Vec<_>>().join(" ");
3182                one_line.chars().take(60).collect()
3183            })
3184    }
3185}
3186
3187/// Read one legacy transcript, tolerating an interrupted final line.
3188///
3189/// Only an unterminated, unparseable *last* line is tolerated (a crash mid-append). A bad
3190/// line anywhere else means the file is not trustworthy, and importing part of it would
3191/// silently drop a message — so the whole file is refused and reported instead.
3192fn read_legacy(path: &Path) -> Result<Legacy> {
3193    let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
3194    let text = String::from_utf8_lossy(&bytes);
3195    let terminated = text.ends_with('\n');
3196    let lines: Vec<&str> = text.lines().collect();
3197    let mut records = Vec::new();
3198    let mut warning = None;
3199    for (i, line) in lines.iter().enumerate() {
3200        if line.trim().is_empty() {
3201            continue;
3202        }
3203        match serde_json::from_str::<Record>(line) {
3204            Ok(rec) => records.push(rec),
3205            Err(_) if i + 1 == lines.len() && !terminated => {
3206                warning = Some(format!(
3207                    "{}:{}: ignoring truncated trailing line ({} bytes)",
3208                    path.display(),
3209                    i + 1,
3210                    line.len()
3211                ));
3212            }
3213            Err(e) => return Err(Error::Session(format!("line {}: {e}", i + 1))),
3214        }
3215    }
3216    let dir = path.parent().unwrap_or(Path::new("."));
3217    let id = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
3218    let title = std::fs::read_to_string(dir.join(format!("{id}.meta.json")))
3219        .ok()
3220        .and_then(|t| serde_json::from_str::<Meta>(&t).ok())
3221        .map(|m| m.title);
3222    let memory = std::fs::read_to_string(dir.join(format!("{id}.memory.json")))
3223        .ok()
3224        .filter(|t| t.len() as u64 <= MAX_MEMORY_FILE_BYTES);
3225    Ok(Legacy {
3226        records,
3227        title,
3228        memory,
3229        warning,
3230    })
3231}
3232
3233fn export_json(id: &str, title: Option<String>, records: &[Record]) -> Result<String> {
3234    let doc = serde_json::json!({
3235        "format": "eclipse-session/1",
3236        "id": id,
3237        "title": title,
3238        "messages": records,
3239    });
3240    let mut out = serde_json::to_string_pretty(&doc).map_err(|e| Error::Session(e.to_string()))?;
3241    out.push('\n');
3242    Ok(out)
3243}
3244
3245/// Fence long enough that nothing inside `text` can close it early.
3246fn fenced(info: &str, text: &str) -> String {
3247    let (mut run, mut longest) = (0usize, 0usize);
3248    for c in text.chars() {
3249        run = if c == '`' { run + 1 } else { 0 };
3250        longest = longest.max(run);
3251    }
3252    let fence = "`".repeat((longest + 1).max(3));
3253    let nl = if text.ends_with('\n') { "" } else { "\n" };
3254    format!("{fence}{info}\n{text}{nl}{fence}\n")
3255}
3256
3257fn export_markdown(id: &str, title: Option<&str>, records: &[Record]) -> String {
3258    use std::collections::HashMap;
3259    use std::fmt::Write as _;
3260
3261    let mut out = String::new();
3262    let _ = writeln!(out, "# {}\n", title.unwrap_or(id).replace('\n', " "));
3263    let _ = writeln!(out, "- Session: `{id}`");
3264    let _ = writeln!(out, "- Messages: {}", records.len());
3265    if let Some(first) = records.first() {
3266        let _ = writeln!(out, "- Started: {} UTC", format_utc(first.ts));
3267    }
3268    out.push_str(
3269        "\n_The system prompt is not stored in sessions, so it is not part of this transcript._\n",
3270    );
3271
3272    let mut tool_names: HashMap<&str, &str> = HashMap::new();
3273    for r in records {
3274        for c in &r.message.tool_calls {
3275            tool_names.insert(&c.id, &c.function.name);
3276        }
3277    }
3278    let mut answered: std::collections::HashSet<&str> = std::collections::HashSet::new();
3279    for r in records {
3280        if let Some(id) = r.message.tool_call_id.as_deref() {
3281            answered.insert(id);
3282        }
3283    }
3284
3285    for (i, r) in records.iter().enumerate() {
3286        let m = &r.message;
3287        let who = match m.role {
3288            Role::System => "System".to_string(),
3289            Role::User => "User".to_string(),
3290            Role::Assistant => "Assistant".to_string(),
3291            Role::Tool => {
3292                let name = m
3293                    .tool_call_id
3294                    .as_deref()
3295                    .and_then(|c| tool_names.get(c).copied())
3296                    .unwrap_or("unknown tool");
3297                format!("Tool result: {name}")
3298            }
3299        };
3300        let _ = writeln!(out, "\n## {}. {who} ({} UTC)\n", i + 1, format_utc(r.ts));
3301        match m.role {
3302            Role::Tool => out.push_str(&fenced("", &m.text_with_pictures())),
3303            _ => {
3304                let text = m.text_with_pictures();
3305                if !text.is_empty() {
3306                    out.push_str(&text);
3307                    out.push('\n');
3308                }
3309            }
3310        }
3311        for c in &m.tool_calls {
3312            let args = &c.function.arguments;
3313            let _ = writeln!(
3314                out,
3315                "\n**Tool call** `{}` (id `{}`){}\n",
3316                c.function.name.replace('`', "'"),
3317                c.id.replace('`', "'"),
3318                if answered.contains(c.id.as_str()) {
3319                    ""
3320                } else {
3321                    " - no result recorded"
3322                }
3323            );
3324            match serde_json::from_str::<serde_json::Value>(args) {
3325                Ok(v) => out.push_str(&fenced(
3326                    "json",
3327                    &serde_json::to_string_pretty(&v).unwrap_or_else(|_| args.clone()),
3328                )),
3329                Err(_) => out.push_str(&fenced("", args)),
3330            }
3331        }
3332    }
3333    out
3334}
3335
3336/// Format unix milliseconds as `YYYY-MM-DD HH:MM` (UTC).
3337pub fn format_utc(ms: u64) -> String {
3338    let secs = ms / 1000;
3339    let days = (secs / 86_400) as i64;
3340    let rem = secs % 86_400;
3341    // Howard Hinnant's civil-from-days algorithm.
3342    let z = days + 719_468;
3343    let era = z.div_euclid(146_097);
3344    let doe = z.rem_euclid(146_097);
3345    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
3346    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
3347    let mp = (5 * doy + 2) / 153;
3348    let d = doy - (153 * mp + 2) / 5 + 1;
3349    let m = if mp < 10 { mp + 3 } else { mp - 9 };
3350    let y = yoe + era * 400 + i64::from(m <= 2);
3351    format!(
3352        "{y:04}-{m:02}-{d:02} {:02}:{:02}",
3353        rem / 3600,
3354        rem % 3600 / 60
3355    )
3356}
3357
3358#[cfg(test)]
3359mod tests {
3360    use super::*;
3361    use crate::message::{FunctionCall, ToolCall};
3362
3363    fn store(dir: &Path) -> SessionStore {
3364        SessionStore::new(dir.join("sessions"))
3365    }
3366
3367    fn call(id: &str, name: &str, args: &str) -> ToolCall {
3368        ToolCall {
3369            id: id.into(),
3370            kind: "function".into(),
3371            function: FunctionCall {
3372                name: name.into(),
3373                arguments: args.into(),
3374            },
3375        }
3376    }
3377
3378    /// A session with one of each interesting message shape.
3379    fn transcript(store: &SessionStore, id: &str) {
3380        store.append(id, &Message::user("hello there")).unwrap();
3381        store
3382            .append(
3383                id,
3384                &Message::assistant_tool_calls(
3385                    Some("let me look".into()),
3386                    vec![call("c1", "read_file", r#"{"path":"a.txt"}"#)],
3387                ),
3388            )
3389            .unwrap();
3390        store
3391            .append(id, &Message::tool_result("c1", "file contents"))
3392            .unwrap();
3393        store.append(id, &Message::assistant("done")).unwrap();
3394    }
3395
3396    /// `#447`: the verdict a replayed row draws, kept beside the message rather than inside it. A
3397    /// second write of the same call is the same write — the table is keyed by the call id — and a
3398    /// call nobody recorded simply has no mark.
3399    #[test]
3400    fn a_tool_outcome_is_recorded_beside_the_call_and_read_back() {
3401        let dir = tempfile::tempdir().unwrap();
3402        let store = SessionStore::new(dir.path().to_path_buf());
3403        let id = store.new_id();
3404        store.append(&id, &Message::user("read it")).unwrap();
3405        assert!(
3406            store.tool_outcomes(&id).unwrap().is_empty(),
3407            "nothing recorded is an empty map, not an error"
3408        );
3409
3410        store.set_tool_outcome(&id, "c1", true).unwrap();
3411        store.set_tool_outcome(&id, "c2", false).unwrap();
3412        store.set_tool_outcome(&id, "c1", true).unwrap();
3413
3414        let marks = store.tool_outcomes(&id).unwrap();
3415        assert_eq!(
3416            marks.len(),
3417            2,
3418            "the second write is the same write: {marks:?}"
3419        );
3420        assert_eq!(marks.get("c1"), Some(&true));
3421        assert_eq!(marks.get("c2"), Some(&false));
3422    }
3423
3424    /// Insert a session directly, so age-based pruning can be tested without waiting.
3425    fn seed(store: &SessionStore, id: &str, updated_ms: u64) {
3426        store
3427            .with_db(|db| {
3428                db.conn.execute(
3429                    "INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
3430                     VALUES (?1, ?2, ?2, NULL, 'seeded', 1, 'native')",
3431                    params![id, updated_ms as i64],
3432                )?;
3433                Ok(())
3434            })
3435            .unwrap();
3436    }
3437
3438    fn legacy_file(dir: &Path, id: &str, body: &str) -> PathBuf {
3439        std::fs::create_dir_all(dir).unwrap();
3440        let path = dir.join(format!("{id}.jsonl"));
3441        std::fs::write(&path, body).unwrap();
3442        path
3443    }
3444
3445    fn line(m: &Message, ts: u64) -> String {
3446        let rec = Record {
3447            ts,
3448            message: m.clone(),
3449        };
3450        format!("{}\n", serde_json::to_string(&rec).unwrap())
3451    }
3452
3453    #[test]
3454    fn append_and_load_round_trip() {
3455        let dir = tempfile::tempdir().unwrap();
3456        let store = store(dir.path());
3457        let id = store.new_id();
3458        assert!(!store.exists(&id), "a store knows only what was written");
3459        transcript(&store, &id);
3460        assert!(store.exists(&id));
3461
3462        let messages = store.load(&id).unwrap();
3463        assert_eq!(messages.len(), 4);
3464        assert_eq!(messages[0], Message::user("hello there"));
3465        assert_eq!(messages[1].tool_calls.len(), 1);
3466        assert_eq!(messages[1].tool_calls[0].function.name, "read_file");
3467        assert_eq!(messages[1].content.as_deref(), Some("let me look"));
3468        assert_eq!(messages[2].tool_call_id.as_deref(), Some("c1"));
3469        assert_eq!(messages[2].content.as_deref(), Some("file contents"));
3470        assert_eq!(messages[3], Message::assistant("done"));
3471    }
3472
3473    #[test]
3474    fn every_message_is_one_row_in_order() {
3475        let dir = tempfile::tempdir().unwrap();
3476        let store = store(dir.path());
3477        let id = store.new_id();
3478        transcript(&store, &id);
3479        let records = store.load_records(&id).unwrap();
3480        let seqs: Vec<usize> = store
3481            .with_db(|db| {
3482                let mut stmt = db
3483                    .conn
3484                    .prepare("SELECT seq FROM messages WHERE session_id = ?1 ORDER BY seq")?;
3485                let rows = stmt.query_map(params![id], |r| r.get::<_, i64>(0))?;
3486                Ok(rows
3487                    .collect::<std::result::Result<Vec<_>, _>>()?
3488                    .into_iter()
3489                    .map(|s| s as usize)
3490                    .collect())
3491            })
3492            .unwrap();
3493        assert_eq!(seqs, [0, 1, 2, 3], "sequence numbers are dense and ordered");
3494        assert_eq!(records.len(), 4);
3495        assert!(
3496            records.windows(2).all(|w| w[0].ts <= w[1].ts),
3497            "timestamps do not run backwards"
3498        );
3499    }
3500
3501    #[test]
3502    fn data_survives_a_new_store_handle() {
3503        let dir = tempfile::tempdir().unwrap();
3504        let id;
3505        {
3506            let first = store(dir.path());
3507            id = first.new_id();
3508            transcript(&first, &id);
3509            first.rename(&id, "kept title").unwrap();
3510        }
3511        let second = store(dir.path());
3512        assert_eq!(second.load(&id).unwrap().len(), 4);
3513        assert_eq!(second.title(&id).unwrap().as_deref(), Some("kept title"));
3514    }
3515
3516    #[test]
3517    fn list_orders_newest_first_with_preview() {
3518        let dir = tempfile::tempdir().unwrap();
3519        let store = store(dir.path());
3520        let a = store.new_id();
3521        store
3522            .append(&a, &Message::user("the older question"))
3523            .unwrap();
3524        std::thread::sleep(std::time::Duration::from_millis(5));
3525        let b = store.new_id();
3526        store
3527            .append(&b, &Message::user("the newer question"))
3528            .unwrap();
3529
3530        let list = store.list().unwrap();
3531        assert_eq!(list.len(), 2);
3532        assert_eq!(list[0].id, b, "newest first");
3533        assert_eq!(list[0].preview, "the newer question");
3534        assert_eq!(list[0].messages, 1);
3535        assert_eq!(list[1].id, a);
3536        assert_eq!(list[0].label(), "the newer question");
3537    }
3538
3539    #[test]
3540    fn the_preview_is_the_first_user_message_not_the_latest() {
3541        let dir = tempfile::tempdir().unwrap();
3542        let store = store(dir.path());
3543        let id = store.new_id();
3544        store.append(&id, &Message::user("first thing")).unwrap();
3545        store.append(&id, &Message::user("second thing")).unwrap();
3546        let info = store.list().unwrap().into_iter().next().unwrap();
3547        assert_eq!(info.preview, "first thing");
3548        assert_eq!(info.messages, 2);
3549    }
3550
3551    #[test]
3552    fn prune_candidates_by_age_and_count() {
3553        let dir = tempfile::tempdir().unwrap();
3554        let store = store(dir.path());
3555        let now = 1_700_000_000_000u64;
3556        let day = 86_400_000u64;
3557        seed(&store, "old", now - 10 * day);
3558        seed(&store, "mid", now - 2 * day);
3559        seed(&store, "new", now - day / 24);
3560
3561        assert_eq!(
3562            store.prune_candidates(3, 0, now, false).unwrap().candidates,
3563            ["old"],
3564            "older than three days"
3565        );
3566        assert_eq!(
3567            store.prune_candidates(0, 2, now, false).unwrap().candidates,
3568            ["old"],
3569            "all but the newest two"
3570        );
3571        let both = store.prune_candidates(3, 10, now, false).unwrap();
3572        assert_eq!(
3573            both.candidates,
3574            ["old"],
3575            "a session selected by either rule is pruned once"
3576        );
3577        assert!(store
3578            .prune_candidates(0, 0, now, false)
3579            .unwrap()
3580            .candidates
3581            .is_empty());
3582    }
3583
3584    #[test]
3585    fn a_pinned_session_sorts_first_and_is_never_a_prune_candidate() {
3586        let dir = tempfile::tempdir().unwrap();
3587        let store = store(dir.path());
3588        let now = 1_700_000_000_000u64;
3589        seed(&store, "oldest", now - 10 * 86_400_000);
3590        seed(&store, "newest", now - 86_400_000);
3591
3592        store.set_pinned("oldest", true).unwrap();
3593        let list = store.list().unwrap();
3594        assert_eq!(list[0].id, "oldest", "pinned first, whatever the age");
3595        assert!(list[0].pinned);
3596        assert!(!list[1].pinned);
3597
3598        // The age rule would take it; the pin keeps it and says so.
3599        let plan = store.prune_candidates(7, 0, now, false).unwrap();
3600        assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
3601        assert_eq!(plan.pinned_kept, 1);
3602
3603        // And the unattended path agrees with the manual one.
3604        let outcome = store.auto_prune(7, 0, now, None).unwrap();
3605        assert_eq!(outcome, AutoPrune::Nothing);
3606        assert!(store.exists("oldest"));
3607
3608        store.set_pinned("oldest", false).unwrap();
3609        assert_eq!(
3610            store.prune_candidates(7, 0, now, false).unwrap().candidates,
3611            ["oldest"]
3612        );
3613        assert!(!store.list().unwrap()[0].pinned, "unpinning is not sticky");
3614    }
3615
3616    /// `#240`: archiving is not a soft delete. The session leaves the list and stays everywhere
3617    /// else — the search, the detail, the transcript — and a prune leaves it alone until it is
3618    /// told to take it.
3619    #[test]
3620    fn an_archived_session_leaves_the_list_and_stays_in_the_search() {
3621        let dir = tempfile::tempdir().unwrap();
3622        let store = store(dir.path());
3623        let now = 1_700_000_000_000u64;
3624        seed(&store, "kept", now - 86_400_000);
3625        seed(&store, "filed", now - 10 * 86_400_000);
3626        store.rename("filed", "the nginx migration").unwrap();
3627        store
3628            .append("filed", &Message::user("the zfs pool was rebuilt"))
3629            .unwrap();
3630        // Writing a message makes a row the newest one; put it back where the policy will find
3631        // it, so this test is about the flag and not about the clock.
3632        store
3633            .with_db(|db| {
3634                db.conn.execute(
3635                    "UPDATE sessions SET updated_ms = ?2 WHERE id = ?1",
3636                    params!["filed", (now - 10 * 86_400_000) as i64],
3637                )?;
3638                Ok(())
3639            })
3640            .unwrap();
3641
3642        store.set_archived("filed", true).unwrap();
3643
3644        // Out of the list a person reads, in the one that says what happened to every row.
3645        let listed = store.list().unwrap();
3646        assert_eq!(listed.len(), 1);
3647        assert_eq!(listed[0].id, "kept");
3648        let all = store.list_with_archived().unwrap();
3649        assert_eq!(all.len(), 2);
3650        assert!(all.iter().find(|s| s.id == "filed").unwrap().archived);
3651        assert!(!all.iter().find(|s| s.id == "kept").unwrap().archived);
3652
3653        // Still found, by its name and by what was said in it — that is the difference between
3654        // an archive and a delete.
3655        assert!(
3656            store
3657                .search("nginx", 20)
3658                .unwrap()
3659                .iter()
3660                .any(|h| h.session_id == "filed"),
3661            "a name hit survives archiving"
3662        );
3663        assert!(
3664            store
3665                .search("zfs", 20)
3666                .unwrap()
3667                .iter()
3668                .any(|h| h.session_id == "filed"),
3669            "a message hit survives archiving"
3670        );
3671        assert_eq!(
3672            store.load("filed").unwrap().len(),
3673            1,
3674            "the transcript is there"
3675        );
3676
3677        // A prune leaves it alone and counts it, and the flag is what changes the answer.
3678        let plan = store.prune_candidates(7, 0, now, false).unwrap();
3679        assert!(plan.candidates.is_empty(), "{:?}", plan.candidates);
3680        assert_eq!(plan.archived_kept, 1);
3681        assert_eq!(
3682            plan.pinned_kept, 0,
3683            "counted apart, so the sentence can differ"
3684        );
3685        assert_eq!(
3686            store.prune_candidates(7, 0, now, true).unwrap().candidates,
3687            ["filed"]
3688        );
3689        // The unattended path has no way to be given the flag, so it never takes one.
3690        assert_eq!(
3691            store.auto_prune(7, 0, now, None).unwrap(),
3692            AutoPrune::Nothing
3693        );
3694
3695        // And unarchiving is the same write in the other direction.
3696        store.set_archived("filed", false).unwrap();
3697        assert_eq!(store.list().unwrap().len(), 2);
3698        assert!(matches!(
3699            store.set_archived("nope", true),
3700            Err(Error::Session(_))
3701        ));
3702    }
3703
3704    /// The archive flag on a row that was written before it existed: the column arrives with a
3705    /// default, so an old row is in the list and nothing has to be backfilled.
3706    #[test]
3707    fn a_database_from_before_archiving_gains_the_column_in_place() {
3708        let dir = tempfile::tempdir().unwrap();
3709        {
3710            let dir = dir.path().join("sessions");
3711            std::fs::create_dir_all(&dir).unwrap();
3712            let conn = Connection::open(dir.join(DB_FILE)).unwrap();
3713            conn.execute_batch(
3714                "CREATE TABLE sessions (
3715                   id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
3716                   title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
3717                   origin TEXT NOT NULL DEFAULT 'native');
3718                 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
3719                   VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
3720            )
3721            .unwrap();
3722        }
3723        let store = store(dir.path());
3724        let list = store.list().unwrap();
3725        assert_eq!(
3726            list.len(),
3727            1,
3728            "the old row is in the list, not archived by omission"
3729        );
3730        assert!(!list[0].archived);
3731        store.set_archived("s1", true).unwrap();
3732        assert!(store.list().unwrap().is_empty());
3733        assert!(store.list_with_archived().unwrap()[0].archived);
3734    }
3735
3736    #[test]
3737    fn a_database_from_before_pinning_gains_the_column_in_place() {
3738        let dir = tempfile::tempdir().unwrap();
3739        let id;
3740        {
3741            // The schema as it was released, written by hand so the test does not depend on
3742            // this build's `SCHEMA` continuing to be the old one.
3743            let dir = dir.path().join("sessions");
3744            std::fs::create_dir_all(&dir).unwrap();
3745            let conn = Connection::open(dir.join(DB_FILE)).unwrap();
3746            conn.execute_batch(
3747                "CREATE TABLE sessions (
3748                   id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
3749                   title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
3750                   origin TEXT NOT NULL DEFAULT 'native');
3751                 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
3752                   VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
3753            )
3754            .unwrap();
3755            id = "s1".to_string();
3756        }
3757        let store = store(dir.path());
3758        let list = store.list().unwrap();
3759        assert_eq!(list.len(), 1, "the old row still reads");
3760        assert_eq!(list[0].id, id);
3761        assert!(!list[0].pinned, "an old row is not pinned");
3762        store.set_pinned(&id, true).unwrap();
3763        assert!(store.list().unwrap()[0].pinned);
3764        assert_eq!(
3765            store
3766                .prune_candidates(0, 1, 1_700_000_000_000, false)
3767                .unwrap(),
3768            PrunePlan::default(),
3769            "one session, newest one kept"
3770        );
3771    }
3772
3773    #[test]
3774    fn a_database_from_before_the_cost_record_gains_the_column_in_place() {
3775        let dir = tempfile::tempdir().unwrap();
3776        {
3777            let dir = dir.path().join("sessions");
3778            std::fs::create_dir_all(&dir).unwrap();
3779            let conn = Connection::open(dir.join(DB_FILE)).unwrap();
3780            conn.execute_batch(
3781                "CREATE TABLE sessions (
3782                   id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
3783                   title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
3784                   origin TEXT NOT NULL DEFAULT 'native');
3785                 INSERT INTO sessions (id, created_ms, updated_ms, preview, messages, origin)
3786                   VALUES ('s1', 1, 2, 'an old session', 1, 'native');",
3787            )
3788            .unwrap();
3789        }
3790        let store = store(dir.path());
3791        assert!(
3792            store.last_cost("s1").unwrap().is_none(),
3793            "an old row has no turn behind it, and no record is not a zero"
3794        );
3795        let prompt = 1_234_u64;
3796        let cost = TurnCost {
3797            at_ms: 7,
3798            ctx: "ctx 1.2K/8K ░░░░░░░░░░│░ 15%".to_string(),
3799            prompt_tokens: Some(prompt),
3800            ..TurnCost::default()
3801        };
3802        store.set_last_cost("s1", &cost).unwrap();
3803        assert_eq!(store.last_cost("s1").unwrap(), Some(cost));
3804    }
3805
3806    /// The row a person reads says what a session cost, and says it after the page that paid for
3807    /// it is gone (#344). The listing is where it has to arrive: opening a session costs no
3808    /// request of its own, so the sidebar's row and the stats row cannot describe one session
3809    /// differently.
3810    #[test]
3811    fn a_turn_writes_its_cost_and_the_listing_reads_it_back() {
3812        let dir = tempfile::tempdir().unwrap();
3813        let store = store(dir.path());
3814        let id = store.new_id();
3815        transcript(&store, &id);
3816        assert!(
3817            store.list().unwrap()[0].cost.is_none(),
3818            "a session with no finished turn has nothing to say about one"
3819        );
3820        let prompt = 30_000_u64;
3821        let cached = 28_000_u64;
3822        let cost = TurnCost {
3823            at_ms: 1_700_000_000_000,
3824            ctx: "ctx 30K/262K ██░░░░░░░░│░ 11%".to_string(),
3825            prompt_tokens: Some(prompt),
3826            completion_tokens: Some(400),
3827            cached_tokens: Some(cached),
3828            ttft_ms: Some(800),
3829            latency_ms: Some(13_000),
3830            tokens_per_sec: Some(63.0),
3831            window_tokens: Some(262_144),
3832        };
3833        store.set_last_cost(&id, &cost).unwrap();
3834        let listed = &store.list().unwrap()[0];
3835        assert_eq!(listed.cost.as_ref(), Some(&cost));
3836        let ctx = listed
3837            .cost
3838            .as_ref()
3839            .map(|c| c.ctx.as_str())
3840            .unwrap_or_default();
3841        assert!(
3842            ctx.contains("262K"),
3843            "the denominator the listing carries is the one that turn ran against: {ctx:?}"
3844        );
3845    }
3846
3847    /// A cost write is bookkeeping, not activity: a session that is not being talked to must not
3848    /// jump to the top of `Today` because a turn of its own finished hours ago.
3849    #[test]
3850    fn recording_a_cost_does_not_move_the_session_up_the_list() {
3851        let dir = tempfile::tempdir().unwrap();
3852        let store = store(dir.path());
3853        let older = store.new_id();
3854        let newer = store.new_id();
3855        transcript(&store, &older);
3856        transcript(&store, &newer);
3857        let before: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
3858        let target = before.last().expect("two sessions").clone();
3859        store
3860            .set_last_cost(
3861                &target,
3862                &TurnCost {
3863                    at_ms: 1,
3864                    ctx: "ctx --".to_string(),
3865                    ..TurnCost::default()
3866                },
3867            )
3868            .unwrap();
3869        let after: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
3870        assert_eq!(
3871            before, after,
3872            "the order is the store's, and a cost is not a move"
3873        );
3874    }
3875
3876    /// `derived < llm < user`, and the rule lives in the store because the naming pass runs in a
3877    /// task of its own: a rename that lands between the read and the write has to win.
3878    #[test]
3879    fn a_persons_name_outranks_the_machines_and_outlives_a_later_attempt() {
3880        let dir = tempfile::tempdir().unwrap();
3881        let store = store(dir.path());
3882        let id = store.new_id();
3883        transcript(&store, &id);
3884
3885        assert!(
3886            store.title_if_unnamed(&id, "the opening message").unwrap(),
3887            "nothing names it yet, so the derived name lands"
3888        );
3889        assert!(
3890            !store
3891                .title_if_unnamed(&id, "a second derived name")
3892                .unwrap(),
3893            "stage one never relabels a session it has already named"
3894        );
3895        assert_eq!(
3896            store.title(&id).unwrap().as_deref(),
3897            Some("the opening message")
3898        );
3899
3900        assert!(
3901            store
3902                .set_title(&id, "the model's name", TitleSource::Llm)
3903                .unwrap(),
3904            "a model name replaces a derived one"
3905        );
3906        assert!(
3907            !store
3908                .set_title(&id, "a second model name", TitleSource::Llm)
3909                .unwrap(),
3910            "one naming call means one name: it is not renamed by trying again"
3911        );
3912
3913        store.rename(&id, "what I called it").unwrap();
3914        for source in [TitleSource::Llm, TitleSource::Derived] {
3915            assert!(
3916                !store.set_title(&id, "the machine again", source).unwrap(),
3917                "a person's name is final to {source:?}"
3918            );
3919        }
3920        assert_eq!(
3921            store.title(&id).unwrap().as_deref(),
3922            Some("what I called it")
3923        );
3924        assert_eq!(
3925            store.list().unwrap()[0].label(),
3926            "what I called it",
3927            "and the listing shows it"
3928        );
3929    }
3930
3931    /// One call per session is a fact about the database: the claim is a single `UPDATE`, so a
3932    /// resume, a second process or a retry finds it taken. A failure is remembered as the reason
3933    /// the claim was spent, which is also what keeps the session from being tried again.
3934    #[test]
3935    fn the_naming_attempt_is_claimed_once_per_session() {
3936        let dir = tempfile::tempdir().unwrap();
3937        let store = store(dir.path());
3938        let id = store.new_id();
3939        transcript(&store, &id);
3940        store.title_if_unnamed(&id, "a derived name").unwrap();
3941
3942        assert!(
3943            store.claim_title_upgrade(&id).unwrap(),
3944            "the first caller owns it"
3945        );
3946        assert!(
3947            !store.claim_title_upgrade(&id).unwrap(),
3948            "and nobody else does"
3949        );
3950        store
3951            .title_attempt_failed(&id, "the reply was not a JSON object")
3952            .unwrap();
3953        assert!(
3954            !store.claim_title_upgrade(&id).unwrap(),
3955            "a refused answer is not retried on the next run"
3956        );
3957        assert_eq!(
3958            store.title(&id).unwrap().as_deref(),
3959            Some("a derived name"),
3960            "and the name is still there: a failure never leaves it empty"
3961        );
3962
3963        // Nothing was tried here, so giving the claim back leaves the session eligible.
3964        let other = store.new_id();
3965        transcript(&store, &other);
3966        store.title_if_unnamed(&other, "another name").unwrap();
3967        assert!(store.claim_title_upgrade(&other).unwrap());
3968        store.release_title_claim(&other).unwrap();
3969        assert!(
3970            store.claim_title_upgrade(&other).unwrap(),
3971            "released, not failed"
3972        );
3973    }
3974
3975    /// A child session's name is read by the parent's list and nobody types it in. The claim
3976    /// refuses those, so delegation never spends a call per child.
3977    #[test]
3978    fn a_delegated_child_session_is_never_named_by_a_call() {
3979        let dir = tempfile::tempdir().unwrap();
3980        let store = store(dir.path());
3981        let parent = store.new_id();
3982        let child = store.new_id();
3983        store.append(&parent, &Message::user("big job")).unwrap();
3984        store.begin_subagent(&child, &parent, "fast").unwrap();
3985        store
3986            .append(&child, &Message::user("summarise this"))
3987            .unwrap();
3988        store.title_if_unnamed(&child, "summarise this").unwrap();
3989        assert!(
3990            !store.claim_title_upgrade(&child).unwrap(),
3991            "a child is named by its opening message and left alone"
3992        );
3993
3994        let api = store.new_id();
3995        store.begin_api(&api).unwrap();
3996        store.append(&api, &Message::user("headless turn")).unwrap();
3997        store.title_if_unnamed(&api, "headless turn").unwrap();
3998        assert!(
3999            !store.claim_title_upgrade(&api).unwrap(),
4000            "a headless API session is named for free and never costs a call"
4001        );
4002    }
4003
4004    /// The name answers a search: the session I called X is a lookup, not a scroll, even when no
4005    /// message in it ever used those words together.
4006    #[test]
4007    fn a_search_finds_a_session_by_the_name_it_was_given() {
4008        let dir = tempfile::tempdir().unwrap();
4009        let store = store(dir.path());
4010        let id = store.new_id();
4011        store
4012            .append(&id, &Message::user("something else entirely"))
4013            .unwrap();
4014        store.append(&id, &Message::assistant("noted")).unwrap();
4015        store.rename(&id, "gateway restart loop").unwrap();
4016
4017        for fts in [true, false] {
4018            // Both backends, because which one runs depends on how SQLite was compiled and the
4019            // two must answer the same question the same way.
4020            let hits = store
4021                .with_db(|db| SessionStore::search_in(db, "restart loop", 10, fts, false))
4022                .unwrap();
4023            let named: Vec<_> = hits.iter().filter(|h| h.role == "title").collect();
4024            assert_eq!(named.len(), 1, "fts={fts}: {:?}", hits);
4025            assert_eq!(named[0].session_id, id);
4026            assert_eq!(named[0].snippet, "gateway restart loop");
4027            assert_eq!(
4028                named[0].seq, 0,
4029                "a name is read from the top of the transcript"
4030            );
4031        }
4032        // A query that matches no name still searches the transcript.
4033        let hits = store.search("noted", 10).unwrap();
4034        assert!(hits.iter().all(|h| h.role != "title"));
4035        assert_eq!(hits.len(), 1);
4036    }
4037
4038    /// `#498`: the rows a `session_search` writes into its own session are not results, and a page
4039    /// that holds nothing but them must not be reported as "no match" — the caller would be told
4040    /// its archive holds nothing while the match sat one row further down.
4041    #[test]
4042    fn a_page_of_the_tools_own_calls_does_not_hide_the_match_behind_them() {
4043        let dir = tempfile::tempdir().unwrap();
4044        let store = store(dir.path());
4045        let id = store.new_id();
4046        store
4047            .append(&id, &Message::user("the needle is here"))
4048            .unwrap();
4049        for i in 0..12 {
4050            let call = crate::message::ToolCall {
4051                id: format!("call-{i}"),
4052                kind: "function".to_string(),
4053                function: crate::message::FunctionCall {
4054                    name: "session_search".to_string(),
4055                    arguments: "{\"query\":\"needle\"}".to_string(),
4056                },
4057            };
4058            store
4059                .append(&id, &Message::assistant_tool_calls(None, vec![call]))
4060                .unwrap();
4061            store
4062                .append(
4063                    &id,
4064                    &Message::tool_result(format!("call-{i}"), "archive: no match for needle"),
4065                )
4066                .unwrap();
4067        }
4068
4069        for fts in [true, false] {
4070            // A limit of 1 is a budget of 9 rows, and the twenty-four own-tail rows are newer than
4071            // the match: without the widening this answers "no match" on both backends.
4072            let hits = store
4073                .with_db(|db| SessionStore::search_in(db, "needle", 1, fts, false))
4074                .unwrap();
4075            assert_eq!(hits.len(), 1, "fts={fts}: {hits:?}");
4076            assert_eq!(hits[0].role, "user", "fts={fts}: {hits:?}");
4077        }
4078    }
4079
4080    /// A database from before names existed gains the two columns in place, and every title it
4081    /// already holds is taken to be a person's: nothing else wrote one.
4082    #[test]
4083    fn a_database_from_before_names_keeps_its_titles_and_learns_who_wrote_them() {
4084        let dir = tempfile::tempdir().unwrap();
4085        {
4086            let dir = dir.path().join("sessions");
4087            std::fs::create_dir_all(&dir).unwrap();
4088            let conn = Connection::open(dir.join(DB_FILE)).unwrap();
4089            conn.execute_batch(
4090                "CREATE TABLE sessions (
4091                   id TEXT PRIMARY KEY, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL,
4092                   title TEXT, preview TEXT, messages INTEGER NOT NULL DEFAULT 0,
4093                   origin TEXT NOT NULL DEFAULT 'native', pinned INTEGER NOT NULL DEFAULT 0);
4094                 INSERT INTO sessions (id, created_ms, updated_ms, title, preview, messages, origin)
4095                   VALUES ('named', 1, 2, 'what I called it', 'first words', 2, 'native'),
4096                          ('bare', 1, 2, NULL, 'first words', 2, 'native');",
4097            )
4098            .unwrap();
4099        }
4100        let store = store(dir.path());
4101        let list = store.list().unwrap();
4102        let named = list.iter().find(|s| s.id == "named").unwrap();
4103        assert_eq!(
4104            named.title.as_deref(),
4105            Some("what I called it"),
4106            "the title survives"
4107        );
4108
4109        assert!(
4110            !store.title_if_unnamed("named", "a derived name").unwrap(),
4111            "an old title is a person's, so stage one leaves it"
4112        );
4113        assert!(
4114            !store.claim_title_upgrade("named").unwrap(),
4115            "and no call is spent on it either"
4116        );
4117        assert!(
4118            store.title_if_unnamed("bare", "a derived name").unwrap(),
4119            "a session that had no name gets one"
4120        );
4121        assert_eq!(
4122            store.title("bare").unwrap().as_deref(),
4123            Some("a derived name")
4124        );
4125    }
4126
4127    #[test]
4128    fn deleting_a_session_removes_its_title_memory_and_lock_file() {
4129        let dir = tempfile::tempdir().unwrap();
4130        let root = dir.path().join("sessions");
4131        let store = store(dir.path());
4132        let a = store.new_id();
4133        let b = store.new_id();
4134        transcript(&store, &a);
4135        transcript(&store, &b);
4136        store.rename(&a, "doomed").unwrap();
4137        store
4138            .save_memory(&a, &memory("## Log\na summary", 2, 3))
4139            .unwrap();
4140        store
4141            .with_db(|db| {
4142                db.conn.execute(
4143                    "INSERT OR REPLACE INTO memory (session_id, body) VALUES (?1, '{}')",
4144                    params![a],
4145                )?;
4146                Ok(())
4147            })
4148            .unwrap();
4149        let lock = root.join(format!("{a}.lock"));
4150        std::fs::write(&lock, "pid 1\n").unwrap();
4151
4152        store.delete(&a).unwrap();
4153        assert!(!store.exists(&a));
4154        assert!(store.exists(&b), "the other session is untouched");
4155        assert!(store.load(&b).unwrap().len() == 4);
4156        assert_eq!(store.memory(&a).unwrap(), None);
4157        assert!(!lock.exists(), "the lock file does not outlive the session");
4158        assert!(store.delete(&a).is_err(), "deleting twice is an error");
4159    }
4160
4161    #[test]
4162    fn auto_prune_deletes_up_to_ten_sessions_and_refuses_more() {
4163        let dir = tempfile::tempdir().unwrap();
4164        let store = store(dir.path());
4165        let now = 1_700_000_000_000u64;
4166        for i in 0..12 {
4167            seed(&store, &format!("s{i:02}"), now - (100 - i) * 86_400_000);
4168        }
4169        // Twelve candidates: over the limit, so nothing is deleted and the count is reported.
4170        assert_eq!(
4171            store.auto_prune(30, 0, now, None).unwrap(),
4172            AutoPrune::Skipped { would_remove: 12 }
4173        );
4174        assert_eq!(store.list().unwrap().len(), 12);
4175        // Ten is allowed.
4176        assert_eq!(
4177            store.auto_prune(0, 2, now, None).unwrap(),
4178            AutoPrune::Pruned {
4179                removed: 10,
4180                failed: 0,
4181                pinned_kept: 0
4182            }
4183        );
4184        assert_eq!(store.list().unwrap().len(), 2);
4185    }
4186
4187    #[test]
4188    fn auto_prune_never_runs_without_a_limit_and_reports_nothing_to_do() {
4189        let dir = tempfile::tempdir().unwrap();
4190        let store = store(dir.path());
4191        let now = 1_700_000_000_000u64;
4192        assert_eq!(
4193            store.auto_prune(0, 0, now, None).unwrap(),
4194            AutoPrune::NoLimits
4195        );
4196        seed(&store, "fresh", now);
4197        assert_eq!(
4198            store.auto_prune(30, 0, now, None).unwrap(),
4199            AutoPrune::Nothing
4200        );
4201        assert_eq!(store.list().unwrap().len(), 1);
4202    }
4203
4204    #[test]
4205    fn auto_prune_spares_the_protected_session() {
4206        let dir = tempfile::tempdir().unwrap();
4207        let store = store(dir.path());
4208        let now = 1_700_000_000_000u64;
4209        seed(&store, "keep-me", now - 90 * 86_400_000);
4210        seed(&store, "old-1", now - 90 * 86_400_000);
4211        let outcome = store.auto_prune(7, 0, now, Some("keep-me")).unwrap();
4212        assert_eq!(
4213            outcome,
4214            AutoPrune::Pruned {
4215                removed: 1,
4216                failed: 0,
4217                pinned_kept: 0
4218            }
4219        );
4220        assert!(
4221            store.exists("keep-me"),
4222            "the session being resumed survives"
4223        );
4224        assert!(!store.exists("old-1"));
4225    }
4226
4227    #[test]
4228    fn rejects_path_traversal_ids() {
4229        let dir = tempfile::tempdir().unwrap();
4230        let store = store(dir.path());
4231        for bad in ["../etc/passwd", "a/b", "", "sp ace", "dot.dot"] {
4232            assert!(
4233                store.load(bad).is_err(),
4234                "{bad:?} must be refused before it reaches the database"
4235            );
4236            assert!(!store.exists(bad));
4237        }
4238    }
4239
4240    #[test]
4241    fn a_corrupt_row_is_reported_with_its_session_and_position() {
4242        let dir = tempfile::tempdir().unwrap();
4243        let store = store(dir.path());
4244        let id = store.new_id();
4245        transcript(&store, &id);
4246        store
4247            .with_db(|db| {
4248                db.conn.execute(
4249                    "INSERT INTO messages (session_id, seq, at_ms, role, body)
4250                     VALUES (?1, 99, 0, 'user', '{not json')",
4251                    params![id],
4252                )?;
4253                Ok(())
4254            })
4255            .unwrap();
4256        let err = store.load(&id).unwrap_err().to_string();
4257        assert!(err.contains(&id) && err.contains("99"), "{err}");
4258    }
4259
4260    #[test]
4261    fn new_ids_are_unique() {
4262        let dir = tempfile::tempdir().unwrap();
4263        let store = store(dir.path());
4264        let ids: std::collections::HashSet<String> = (0..50).map(|_| store.new_id()).collect();
4265        assert_eq!(ids.len(), 50);
4266        for id in &ids {
4267            validate_id(id).unwrap();
4268        }
4269    }
4270
4271    #[test]
4272    fn utc_formatting() {
4273        assert_eq!(format_utc(0), "1970-01-01 00:00");
4274        assert_eq!(format_utc(1_700_000_000_000), "2023-11-14 22:13");
4275    }
4276
4277    #[test]
4278    fn rename_sets_title_without_touching_the_transcript() {
4279        let dir = tempfile::tempdir().unwrap();
4280        let store = store(dir.path());
4281        let id = store.new_id();
4282        transcript(&store, &id);
4283        let before = store.load(&id).unwrap();
4284        store.rename(&id, "  a name  ").unwrap();
4285        assert_eq!(store.title(&id).unwrap().as_deref(), Some("a name"));
4286        assert_eq!(store.load(&id).unwrap(), before);
4287        let listed = store.list().unwrap().into_iter().next().unwrap();
4288        assert_eq!(listed.label(), "a name", "the title wins over the preview");
4289    }
4290
4291    #[test]
4292    fn rename_rejects_bad_titles_and_unknown_sessions() {
4293        let dir = tempfile::tempdir().unwrap();
4294        let store = store(dir.path());
4295        let id = store.new_id();
4296        transcript(&store, &id);
4297        for bad in ["", "   "] {
4298            assert!(store.rename(&id, bad).is_err(), "{bad:?}");
4299        }
4300        assert!(store.rename(&id, &"x".repeat(201)).is_err());
4301        assert!(store.rename(&id, "bad\nname").is_err());
4302        assert!(store.rename("no-such-session", "fine").is_err());
4303        assert_eq!(store.title(&id).unwrap(), None);
4304    }
4305
4306    #[test]
4307    fn json_export_is_the_complete_transcript() {
4308        let dir = tempfile::tempdir().unwrap();
4309        let store = store(dir.path());
4310        let id = store.new_id();
4311        transcript(&store, &id);
4312        let out = store.export(&id, ExportFormat::Json).unwrap();
4313        let doc: serde_json::Value = serde_json::from_str(&out).unwrap();
4314        assert_eq!(doc["format"], "eclipse-session/1");
4315        assert_eq!(doc["id"], id);
4316        assert_eq!(doc["messages"].as_array().unwrap().len(), 4);
4317        assert_eq!(doc["messages"][0]["message"]["role"], "user");
4318        assert_eq!(
4319            doc["messages"][1]["message"]["tool_calls"][0]["function"]["name"],
4320            "read_file"
4321        );
4322        assert!(out.ends_with('\n'));
4323    }
4324
4325    #[test]
4326    fn markdown_export_shows_turns_calls_and_results() {
4327        let dir = tempfile::tempdir().unwrap();
4328        let store = store(dir.path());
4329        let id = store.new_id();
4330        transcript(&store, &id);
4331        let out = store.export(&id, ExportFormat::Markdown).unwrap();
4332        assert!(out.contains("# "), "a heading, even without a title: {out}");
4333        assert!(out.contains("## 1. User"));
4334        assert!(out.contains("## 2. Assistant"));
4335        assert!(out.contains("**Tool call** `read_file`"));
4336        assert!(out.contains("## 3. Tool result: read_file"));
4337        assert!(out.contains("```json"), "arguments are pretty-printed");
4338        assert!(!out.contains("no result recorded"), "the call was answered");
4339    }
4340
4341    #[test]
4342    fn markdown_export_uses_the_title() {
4343        let dir = tempfile::tempdir().unwrap();
4344        let store = store(dir.path());
4345        let id = store.new_id();
4346        transcript(&store, &id);
4347        store.rename(&id, "a named session").unwrap();
4348        let out = store.export(&id, ExportFormat::Markdown).unwrap();
4349        assert!(out.starts_with("# a named session\n"), "{out}");
4350    }
4351
4352    /// No range endpoints. `Handoff::covers` refuses a document without them on purpose, and none
4353    /// of these tests is about reuse — they are about what the file holds.
4354    const NO_SPAN: (Option<u64>, Option<u64>) = (None, None);
4355
4356    fn handoff(text: &str, turns: usize, messages: usize) -> Handoff {
4357        Handoff {
4358            text: text.into(),
4359            version: crate::compact::VERSION.into(),
4360            covered_turns: turns,
4361            covered_messages: messages,
4362            covered_from: None,
4363            covered_to: None,
4364            generated_at_ms: 1_700_000_000_000,
4365            judgement: None,
4366        }
4367    }
4368
4369    fn memory(text: &str, turns: usize, messages: usize) -> Memory {
4370        Memory {
4371            version: MEMORY_VERSION,
4372            handoff: Some(handoff(text, turns, messages)),
4373        }
4374    }
4375
4376    /// A file written by the build that still had a model-written summary: it loads, its summary
4377    /// is ignored rather than trusted or migrated, and the next handoff write replaces the record
4378    /// with one of this schema. Nothing is lost that matters — the summary was never the
4379    /// transcript, and the transcript is untouched.
4380    #[test]
4381    fn a_summary_era_memory_file_loads_with_its_summary_ignored() {
4382        let dir = tempfile::tempdir().unwrap();
4383        let store = store(dir.path());
4384        let id = store.new_id();
4385        transcript(&store, &id);
4386        let v2 = r#"{"version":2,"summary":"old news","covered_turns":2,
4387                     "covered_messages":4,"generated_at_ms":1700000000000}"#;
4388        store
4389            .with_db(|db| {
4390                db.conn.execute(
4391                    "INSERT INTO memory (session_id, body) VALUES (?1, ?2)",
4392                    params![id, v2],
4393                )?;
4394                Ok(())
4395            })
4396            .unwrap();
4397
4398        let m = store.memory(&id).unwrap().unwrap();
4399        assert_eq!(m.schema(), 2, "the file says what wrote it");
4400        assert_eq!(
4401            m.usable_handoff(),
4402            None,
4403            "a summary alone is not a handoff, and there is nothing else to read"
4404        );
4405        assert!(
4406            m.validate().is_err(),
4407            "a record with nothing in it is not memory"
4408        );
4409
4410        store
4411            .save_handoff(
4412                &id,
4413                crate::context::Trimmed {
4414                    turns: 2,
4415                    messages: 4,
4416                },
4417                NO_SPAN,
4418                "## Log\n[#0]",
4419                None,
4420            )
4421            .unwrap();
4422        let after = store.memory(&id).unwrap().unwrap();
4423        assert_eq!(after.schema(), MEMORY_VERSION, "rewritten at this schema");
4424        assert_eq!(after.handoff.unwrap().text, "## Log\n[#0]");
4425        let raw = store
4426            .with_db(|db| {
4427                Ok(db
4428                    .conn
4429                    .query_row(
4430                        "SELECT body FROM memory WHERE session_id = ?1",
4431                        params![id],
4432                        |r| r.get::<_, String>(0),
4433                    )
4434                    .unwrap())
4435            })
4436            .unwrap();
4437        assert!(
4438            !raw.contains("summary"),
4439            "the field a summary-era build wrote is gone from the file: {raw}"
4440        );
4441    }
4442
4443    #[test]
4444    fn saving_a_handoff_replaces_the_document_and_never_the_other_way_round() {
4445        let dir = tempfile::tempdir().unwrap();
4446        let store = store(dir.path());
4447        let id = store.new_id();
4448        transcript(&store, &id);
4449
4450        store
4451            .save_handoff(
4452                &id,
4453                crate::context::Trimmed {
4454                    turns: 1,
4455                    messages: 2,
4456                },
4457                NO_SPAN,
4458                "## Log\nA",
4459                None,
4460            )
4461            .unwrap();
4462        assert_eq!(
4463            store.readable_memory(&id).unwrap().handoff.unwrap().text,
4464            "## Log\nA"
4465        );
4466
4467        // A wider range replaces it whole: a handoff is a document for one drop, not a prefix of
4468        // the next one.
4469        store
4470            .save_handoff(
4471                &id,
4472                crate::context::Trimmed {
4473                    turns: 3,
4474                    messages: 6,
4475                },
4476                NO_SPAN,
4477                "## Log\nB",
4478                Some(Judgement {
4479                    text: "- because the first answer settled it".into(),
4480                    model: "aux".into(),
4481                    generated_at_ms: 1,
4482                }),
4483            )
4484            .unwrap();
4485        let now = store.readable_memory(&id).unwrap();
4486        let h = now.handoff.unwrap();
4487        assert_eq!(h.text, "## Log\nB");
4488        assert_eq!(h.covered_turns, 3);
4489        assert_eq!(
4490            h.judgement.unwrap().model,
4491            "aux",
4492            "and the judgement travels with the document it belongs to"
4493        );
4494    }
4495
4496    #[test]
4497    fn a_memory_from_a_newer_schema_is_refused_rather_than_half_read() {
4498        let dir = tempfile::tempdir().unwrap();
4499        let store = store(dir.path());
4500        let id = store.new_id();
4501        transcript(&store, &id);
4502        let mut m = memory("## Log\nC", 1, 2);
4503        m.version = MEMORY_VERSION + 1;
4504        let why = m.validate().unwrap_err();
4505        assert!(why.contains("newer than this build"), "{why}");
4506        assert!(
4507            store.save_memory(&id, &m).is_err(),
4508            "a record this build cannot read is not written either"
4509        );
4510    }
4511
4512    /// The store may not write a record its own reader refuses. Past the cap, `memory()` errors
4513    /// for ever and `readable_memory` reports "no memory", so the session recompiles on every
4514    /// request with no way back.
4515    #[test]
4516    fn a_memory_too_large_to_read_back_is_refused_at_the_write() {
4517        let dir = tempfile::tempdir().unwrap();
4518        let store = store(dir.path());
4519        let id = store.new_id();
4520        transcript(&store, &id);
4521        let mut big = memory("## Log\n", 1, 2);
4522        big.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize);
4523        let err = store
4524            .save_memory(&id, &big)
4525            .expect_err("a record the reader would refuse is not written");
4526        assert!(err.to_string().contains("record limit"), "{err}");
4527        assert!(
4528            store.memory(&id).unwrap().is_none(),
4529            "nothing was stored, and the row did not become unreadable"
4530        );
4531
4532        // The boundary itself is allowed: a record that serialises to exactly the cap reads back.
4533        let mut fits = memory("## Log\n", 1, 2);
4534        let overhead =
4535            serde_json::to_string(&fits).unwrap().len() - fits.handoff.as_ref().unwrap().text.len();
4536        fits.handoff.as_mut().unwrap().text = "x".repeat(MAX_MEMORY_FILE_BYTES as usize - overhead);
4537        store.save_memory(&id, &fits).expect("the cap itself fits");
4538        assert!(store.readable_memory(&id).is_some(), "and it reads back");
4539    }
4540
4541    /// The counts describe a size, not a window. `Trimmed` is measured from `head_end`, so the
4542    /// same pair of numbers can name a different drop once the budget moves — and a document
4543    /// reused for the wrong one mentions messages that are still verbatim in the request.
4544    #[test]
4545    fn a_handoff_is_its_range_and_not_just_its_counts() {
4546        let mut h = handoff("## Log\nsomeone decided something", 1, 2);
4547        assert!(
4548            !h.covers(1, 2, Some(2), Some(3)),
4549            "a document with no endpoints cannot say which window it described"
4550        );
4551        h.covered_from = Some(0);
4552        h.covered_to = Some(1);
4553        assert!(h.covers(1, 2, Some(0), Some(1)));
4554        assert!(
4555            !h.covers(1, 2, Some(2), Some(3)),
4556            "the same size and the same counts, a different window"
4557        );
4558        assert!(
4559            !h.covers(1, 2, None, None),
4560            "no endpoints on the caller's side either"
4561        );
4562        h.covered_to = Some(9);
4563        assert!(
4564            !h.covers(1, 2, Some(0), Some(1)),
4565            "the end is part of the range"
4566        );
4567    }
4568
4569    #[test]
4570    fn memory_round_trips_in_its_documented_shape_and_the_database_is_private() {
4571        let dir = tempfile::tempdir().unwrap();
4572        let store = store(dir.path());
4573        let id = store.new_id();
4574        transcript(&store, &id);
4575        store
4576            .save_handoff(
4577                &id,
4578                crate::context::Trimmed {
4579                    turns: 2,
4580                    messages: 4,
4581                },
4582                NO_SPAN,
4583                "## Log\nthey agreed on the plan",
4584                None,
4585            )
4586            .unwrap();
4587        let raw = store
4588            .with_db(|db| {
4589                Ok(db
4590                    .conn
4591                    .query_row(
4592                        "SELECT body FROM memory WHERE session_id = ?1",
4593                        params![id],
4594                        |r| r.get::<_, String>(0),
4595                    )
4596                    .unwrap())
4597            })
4598            .unwrap();
4599        let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
4600        assert_eq!(parsed["version"], MEMORY_VERSION);
4601        assert_eq!(parsed["handoff"]["covered_turns"], 2);
4602        assert_eq!(parsed["handoff"]["text"], "## Log\nthey agreed on the plan");
4603        #[cfg(unix)]
4604        {
4605            use std::os::unix::fs::PermissionsExt;
4606            let mode = std::fs::metadata(store.dir().join("sessions.db"))
4607                .unwrap()
4608                .permissions()
4609                .mode()
4610                & 0o777;
4611            assert_eq!(
4612                mode, 0o600,
4613                "the database is owner-only, like the transcripts were"
4614            );
4615            // The main file is not the transcript: everything written since the last checkpoint
4616            // lives in `-wal`, which SQLite creates with the umask. The directory has to be
4617            // owner-only for that to be a guarantee, and the sidecar itself is chmodded too.
4618            let dir_mode = std::fs::metadata(store.dir()).unwrap().permissions().mode() & 0o777;
4619            assert_eq!(dir_mode, 0o700, "the session directory is owner-only");
4620            for sidecar in ["sessions.db-wal", "sessions.db-shm"] {
4621                let p = store.dir().join(sidecar);
4622                if !p.exists() {
4623                    continue;
4624                }
4625                let m = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777;
4626                assert_eq!(m, 0o600, "{sidecar} is owner-only");
4627            }
4628        }
4629    }
4630
4631    #[test]
4632    fn memory_validation_rejects_nonsense() {
4633        let dir = tempfile::tempdir().unwrap();
4634        let store = store(dir.path());
4635        let id = store.new_id();
4636        transcript(&store, &id);
4637        let empty = Memory {
4638            version: MEMORY_VERSION,
4639            handoff: None,
4640        };
4641        assert!(empty.validate().is_err() && store.save_memory(&id, &empty).is_err());
4642        let mut m = memory(" padded ", 1, 1);
4643        assert!(m.validate().is_err(), "an untrimmed document is refused");
4644        m = memory("fine", 2, 1);
4645        assert!(m.validate().is_err(), "messages < turns is nonsense");
4646        m.handoff.as_mut().unwrap().covered_messages = 2;
4647        m.handoff.as_mut().unwrap().covered_turns = 0;
4648        assert!(m.validate().is_err(), "covering no turn is nonsense");
4649        m = memory("", 1, 2);
4650        assert!(m.validate().is_err(), "an empty document is not memory");
4651        let mut m = memory("fine", 2, 4);
4652        m.handoff.as_mut().unwrap().judgement = Some(Judgement {
4653            text: "\n- untrimmed".into(),
4654            model: "aux".into(),
4655            generated_at_ms: 1,
4656        });
4657        assert!(m.validate().is_err(), "an untrimmed judgement is refused");
4658        assert!(store.save_memory(&id, &memory("fine", 2, 4)).is_ok());
4659    }
4660
4661    #[test]
4662    fn corrupt_or_invalid_memory_is_not_usable() {
4663        let dir = tempfile::tempdir().unwrap();
4664        let store = store(dir.path());
4665        let id = store.new_id();
4666        transcript(&store, &id);
4667        store
4668            .with_db(|db| {
4669                db.conn.execute(
4670                    "INSERT INTO memory (session_id, body) VALUES (?1, 'not json')",
4671                    params![id],
4672                )?;
4673                Ok(())
4674            })
4675            .unwrap();
4676        assert!(
4677            store.memory(&id).is_err(),
4678            "corruption is reported, not hidden"
4679        );
4680        assert_eq!(store.readable_memory(&id), None, "and never used");
4681
4682        store
4683            .save_memory(&id, &memory("valid again", 1, 1))
4684            .unwrap();
4685        assert!(store.readable_memory(&id).is_some());
4686    }
4687
4688    #[test]
4689    fn memory_is_per_session() {
4690        let dir = tempfile::tempdir().unwrap();
4691        let store = store(dir.path());
4692        let a = store.new_id();
4693        let b = store.new_id();
4694        store.append(&a, &Message::user("a")).unwrap();
4695        store.append(&b, &Message::user("b")).unwrap();
4696        store.save_memory(&a, &memory("about a", 1, 1)).unwrap();
4697        assert!(store.memory(&b).unwrap().is_none());
4698        assert_eq!(
4699            store.readable_memory(&a).unwrap().handoff.unwrap().text,
4700            "about a"
4701        );
4702    }
4703
4704    #[test]
4705    fn delete_and_prune_remove_the_memory_too() {
4706        let dir = tempfile::tempdir().unwrap();
4707        let store = store(dir.path());
4708        let id = store.new_id();
4709        transcript(&store, &id);
4710        store
4711            .save_memory(&id, &memory("gone with it", 1, 1))
4712            .unwrap();
4713        store.delete(&id).unwrap();
4714        assert!(
4715            store.load_records(&id).is_err(),
4716            "the session is gone, not empty"
4717        );
4718        assert_eq!(store.memory(&id).unwrap(), None);
4719    }
4720
4721    // ---- legacy import ---------------------------------------------------------
4722
4723    #[test]
4724    fn a_deleted_legacy_session_does_not_come_back() {
4725        let dir = tempfile::tempdir().unwrap();
4726        let root = dir.path().join("sessions");
4727        let path = legacy_file(
4728            &root,
4729            "deleted-me",
4730            &line(&Message::user("doomed"), 1_700_000_000_000),
4731        );
4732        let store = SessionStore::new(&root);
4733        assert!(store.exists("deleted-me"));
4734        store.delete("deleted-me").unwrap();
4735        assert!(!path.exists(), "the imported source goes with the session");
4736        drop(store);
4737
4738        // A fresh handle over the same directory must not re-import it.
4739        let again = SessionStore::new(&root);
4740        assert!(
4741            !again.exists("deleted-me"),
4742            "a deleted session must stay deleted across restarts"
4743        );
4744        assert!(again.list().unwrap().is_empty());
4745    }
4746
4747    #[test]
4748    fn a_legacy_transcript_is_imported_once_and_the_file_is_kept() {
4749        let dir = tempfile::tempdir().unwrap();
4750        let root = dir.path().join("sessions");
4751        let body = format!(
4752            "{}{}",
4753            line(&Message::user("from the old world"), 1_700_000_000_000),
4754            line(&Message::assistant("and the reply"), 1_700_000_001_000)
4755        );
4756        let path = legacy_file(&root, "legacy-1", &body);
4757        std::fs::write(root.join("legacy-1.meta.json"), r#"{"title":"old title"}"#).unwrap();
4758
4759        let store = SessionStore::new(&root);
4760        let messages = store.load("legacy-1").unwrap();
4761        assert_eq!(messages.len(), 2);
4762        assert_eq!(messages[0].content.as_deref(), Some("from the old world"));
4763        assert_eq!(
4764            store.title("legacy-1").unwrap().as_deref(),
4765            Some("old title")
4766        );
4767        assert!(path.exists(), "importing must not delete the source");
4768
4769        let info = store.list().unwrap().into_iter().next().unwrap();
4770        assert_eq!(info.preview, "from the old world");
4771        assert_eq!(info.updated_ms, 1_700_000_001_000);
4772
4773        // A second handle over the same directory finds it already imported, not doubled.
4774        drop(store);
4775        let again = SessionStore::new(&root);
4776        assert_eq!(again.load("legacy-1").unwrap().len(), 2);
4777        assert_eq!(again.list().unwrap().len(), 1);
4778    }
4779
4780    #[test]
4781    fn a_truncated_legacy_tail_is_dropped_and_the_rest_is_imported() {
4782        let dir = tempfile::tempdir().unwrap();
4783        let root = dir.path().join("sessions");
4784        let good = line(&Message::user("complete"), 1_700_000_000_000);
4785        let body = format!("{good}{{\"ts\":1,\"message\":{{\"role\":\"user\"");
4786        legacy_file(&root, "half-written", &body);
4787        let store = SessionStore::new(&root);
4788        let messages = store.load("half-written").unwrap();
4789        assert_eq!(messages.len(), 1, "the complete record survived");
4790        assert_eq!(messages[0].content.as_deref(), Some("complete"));
4791    }
4792
4793    #[test]
4794    fn a_complete_final_record_without_a_newline_is_kept() {
4795        let dir = tempfile::tempdir().unwrap();
4796        let root = dir.path().join("sessions");
4797        let body = line(&Message::user("no trailing newline"), 5)
4798            .trim_end()
4799            .to_string();
4800        legacy_file(&root, "unterminated", &body);
4801        let store = SessionStore::new(&root);
4802        assert_eq!(store.load("unterminated").unwrap().len(), 1);
4803    }
4804
4805    #[test]
4806    fn a_legacy_file_corrupt_in_the_middle_is_refused_not_half_imported() {
4807        let dir = tempfile::tempdir().unwrap();
4808        let root = dir.path().join("sessions");
4809        let body = format!(
4810            "{}garbage\n{}",
4811            line(&Message::user("before"), 1),
4812            line(&Message::assistant("after"), 2)
4813        );
4814        let path = legacy_file(&root, "corrupt-mid", &body);
4815        let store = SessionStore::new(&root);
4816        assert!(
4817            !store.exists("corrupt-mid"),
4818            "importing part of it would silently drop a message"
4819        );
4820        assert!(path.exists(), "and the file is left for a human to look at");
4821        assert!(store.list().unwrap().is_empty());
4822    }
4823
4824    #[test]
4825    fn an_empty_legacy_transcript_keeps_its_file_time_not_epoch() {
4826        let dir = tempfile::tempdir().unwrap();
4827        let root = dir.path().join("sessions");
4828        legacy_file(&root, "empty-one", "");
4829        let store = SessionStore::new(&root);
4830        let info = store.list().unwrap().into_iter().next().unwrap();
4831        assert_eq!(info.messages, 0);
4832        assert!(
4833            info.updated_ms > 1_600_000_000_000,
4834            "a corrupt transcript still ages from its mtime, not from 1970: {}",
4835            info.updated_ms
4836        );
4837    }
4838
4839    #[test]
4840    fn a_legacy_memory_sidecar_is_imported() {
4841        let dir = tempfile::tempdir().unwrap();
4842        let root = dir.path().join("sessions");
4843        legacy_file(
4844            &root,
4845            "with-memory",
4846            &line(&Message::user("hi"), 1_700_000_000_000),
4847        );
4848        let m = memory("remembered from before", 2, 4);
4849        std::fs::write(
4850            root.join("with-memory.memory.json"),
4851            serde_json::to_string(&m).unwrap(),
4852        )
4853        .unwrap();
4854        let store = SessionStore::new(&root);
4855        assert_eq!(store.readable_memory("with-memory"), Some(m));
4856    }
4857
4858    #[test]
4859    fn an_unparseable_legacy_memory_sidecar_is_imported_and_reported() {
4860        let dir = tempfile::tempdir().unwrap();
4861        let root = dir.path().join("sessions");
4862        legacy_file(
4863            &root,
4864            "bad-memory",
4865            &line(&Message::user("hi"), 1_700_000_000_000),
4866        );
4867        // Truncated JSON: the import has to fail loudly rather than invent an empty record.
4868        std::fs::write(
4869            root.join("bad-memory.memory.json"),
4870            r#"{"version":3,"handoff":{"#,
4871        )
4872        .unwrap();
4873        let store = SessionStore::new(&root);
4874        assert!(
4875            store.memory("bad-memory").is_err(),
4876            "an unparseable sidecar is an error to read, not silence"
4877        );
4878        assert_eq!(store.readable_memory("bad-memory"), None);
4879    }
4880
4881    // ---- search ----------------------------------------------------------------
4882
4883    #[test]
4884    fn search_finds_message_text_and_tool_arguments() {
4885        let dir = tempfile::tempdir().unwrap();
4886        let store = store(dir.path());
4887        let id = store.new_id();
4888        store
4889            .append(&id, &Message::user("the deploy key lives in vault"))
4890            .unwrap();
4891        store
4892            .append(
4893                &id,
4894                &Message::assistant_tool_calls(
4895                    None,
4896                    vec![call("c9", "shell", r#"{"cmd":"systemctl status nginx"}"#)],
4897                ),
4898            )
4899            .unwrap();
4900        let other = store.new_id();
4901        store.append(&other, &Message::user("unrelated")).unwrap();
4902
4903        let hits = store.search("vault", 10).unwrap();
4904        assert_eq!(hits.len(), 1, "{hits:?}");
4905        assert_eq!(hits[0].session_id, id);
4906        assert_eq!(hits[0].seq, 0);
4907        assert_eq!(hits[0].role, "user");
4908        assert!(hits[0].snippet.contains("vault"));
4909
4910        let hits = store.search("nginx", 10).unwrap();
4911        assert_eq!(hits.len(), 1, "tool arguments are searchable: {hits:?}");
4912        assert_eq!(hits[0].seq, 1);
4913
4914        assert!(store.search("nothing-said-this", 10).unwrap().is_empty());
4915        assert!(store.search("   ", 10).unwrap().is_empty());
4916    }
4917
4918    /// A delete that fails halfway leaves the session alone.
4919    ///
4920    /// The index delete is made to fail (here: the index table is gone, which is what a corrupt or
4921    /// read-only index looks like from the caller's side). On a delete split across two unguarded
4922    /// statements the session row is already gone by then — by way of `ON DELETE CASCADE`, its
4923    /// messages too — so the caller is told the delete failed while it has in fact half-happened.
4924    /// Inside one transaction the rollback takes it back.
4925    #[test]
4926    fn a_delete_that_fails_halfway_leaves_the_session_alone() {
4927        let dir = tempfile::tempdir().unwrap();
4928        let store = store(dir.path());
4929        let id = store.new_id();
4930        store
4931            .append(&id, &Message::user("an undeletable mention of widget"))
4932            .unwrap();
4933        if !store.with_db(|db| Ok(db.fts)).unwrap() {
4934            return; // nothing to fail without an index
4935        }
4936        store
4937            .with_db(|db| {
4938                db.conn.execute_batch("DROP TABLE messages_fts")?;
4939                Ok(())
4940            })
4941            .unwrap();
4942
4943        assert!(
4944            store.delete(&id).is_err(),
4945            "the failed delete is reported to the caller"
4946        );
4947
4948        store
4949            .with_db(|db| {
4950                let sessions: i64 = db.conn.query_row(
4951                    "SELECT count(*) FROM sessions WHERE id = ?1",
4952                    params![id],
4953                    |r| r.get(0),
4954                )?;
4955                assert_eq!(
4956                    sessions, 1,
4957                    "a delete that failed must not have half-happened"
4958                );
4959                let messages: i64 = db.conn.query_row(
4960                    "SELECT count(*) FROM messages WHERE session_id = ?1",
4961                    params![id],
4962                    |r| r.get(0),
4963                )?;
4964                assert_eq!(messages, 1, "its messages are still there too");
4965                Ok(())
4966            })
4967            .unwrap();
4968
4969        // And a second delete is not confused by the corpse: it still reports the session as live.
4970        assert!(store.delete(&id).is_err());
4971    }
4972
4973    /// A stale index row is not a search failure. Index entries can outlive the messages they name —
4974    /// written by a build whose delete was two statements, or by a crash between them — and the old
4975    /// `hit()` turned the first such row into an error that took every other hit with it.
4976    #[test]
4977    fn a_stale_index_row_is_skipped_rather_than_failing_the_search() {
4978        let dir = tempfile::tempdir().unwrap();
4979        let store = store(dir.path());
4980        let id = store.new_id();
4981        store
4982            .append(&id, &Message::user("the live mention of widget"))
4983            .unwrap();
4984
4985        // Simulate the half-deleted past: the message goes, its index row stays.
4986        store
4987            .with_db(|db| {
4988                db.conn
4989                    .execute("DELETE FROM messages WHERE session_id = ?1", params![id])?;
4990                Ok(())
4991            })
4992            .unwrap();
4993
4994        let hits = store.search("widget", 10).unwrap();
4995        assert!(
4996            hits.is_empty(),
4997            "the orphan is dropped, not fatal: {hits:?}"
4998        );
4999    }
5000
5001    /// Deleting a session takes its messages and its index rows together, in one transaction.
5002    #[test]
5003    fn deleting_a_session_leaves_nothing_of_it_behind() {
5004        let dir = tempfile::tempdir().unwrap();
5005        let store = store(dir.path());
5006        let id = store.new_id();
5007        store
5008            .append(&id, &Message::user("a deletable mention of widget"))
5009            .unwrap();
5010        let keep = store.new_id();
5011        store
5012            .append(&keep, &Message::user("a kept mention of widget"))
5013            .unwrap();
5014
5015        store.delete(&id).unwrap();
5016
5017        store
5018            .with_db(|db| {
5019                let messages: i64 = db.conn.query_row(
5020                    "SELECT count(*) FROM messages WHERE session_id = ?1",
5021                    params![id],
5022                    |r| r.get(0),
5023                )?;
5024                assert_eq!(messages, 0, "messages go with the session");
5025                if db.fts {
5026                    let indexed: i64 = db.conn.query_row(
5027                        "SELECT count(*) FROM messages_fts WHERE session_id = ?1",
5028                        params![id],
5029                        |r| r.get(0),
5030                    )?;
5031                    assert_eq!(indexed, 0, "and so does the index, in the same transaction");
5032                }
5033                Ok(())
5034            })
5035            .unwrap();
5036
5037        let hits = store.search("widget", 10).unwrap();
5038        assert_eq!(hits.len(), 1, "the other session is untouched: {hits:?}");
5039        assert_eq!(hits[0].session_id, keep);
5040        assert!(
5041            store.delete(&id).is_err(),
5042            "deleting it twice still says there is no such session"
5043        );
5044    }
5045
5046    /// Both backends answer "newest first". Without the ORDER BY, FTS5 answers in rowid order — which
5047    /// is insertion order — so a `LIMIT` cut the oldest hits and two installs disagreed.
5048    #[test]
5049    fn search_answers_newest_first_whichever_backend_runs() {
5050        let dir = tempfile::tempdir().unwrap();
5051        let store = store(dir.path());
5052        let older = store.new_id();
5053        store
5054            .append(&older, &Message::user("the older mention of gadget"))
5055            .unwrap();
5056        // Distinct milliseconds: `at_ms` is the write time, and a tie would make the assertion
5057        // about the tie-breaker rather than about recency.
5058        std::thread::sleep(std::time::Duration::from_millis(3));
5059        let newer = store.new_id();
5060        store
5061            .append(&newer, &Message::user("the newer mention of gadget"))
5062            .unwrap();
5063
5064        store
5065            .with_db(|db| {
5066                for use_fts in [true, false] {
5067                    if use_fts && !db.fts {
5068                        continue;
5069                    }
5070                    let hits = SessionStore::search_in(db, "gadget", 1, use_fts, false).unwrap();
5071                    assert_eq!(hits.len(), 1, "fts={use_fts}");
5072                    assert_eq!(
5073                        hits[0].session_id, newer,
5074                        "a limit of one has to take the newest hit, not the first rowid (fts={use_fts})"
5075                    );
5076                }
5077                Ok(())
5078            })
5079            .unwrap();
5080    }
5081
5082    #[test]
5083    fn search_treats_percent_and_underscore_as_text_not_wildcards() {
5084        let dir = tempfile::tempdir().unwrap();
5085        let store = store(dir.path());
5086        let id = store.new_id();
5087        store
5088            .append(&id, &Message::user("disk is 100% full"))
5089            .unwrap();
5090        store
5091            .append(&id, &Message::user("disk is 100 percent full"))
5092            .unwrap();
5093        store
5094            .append(&id, &Message::user("the file a_b.txt is here"))
5095            .unwrap();
5096        store
5097            .append(&id, &Message::user("the file axb.txt is not"))
5098            .unwrap();
5099
5100        // The fallback is the branch that can promise substrings, so this is the branch where a
5101        // wildcard would be a lie. (FTS5 is token-based: it would match `100` inside `100 percent`,
5102        // which is its documented behaviour, not a wildcard.)
5103        store
5104            .with_db(|db| {
5105                let percent = SessionStore::search_in(db, "100%", 10, false, false).unwrap();
5106                assert_eq!(
5107                    percent.len(),
5108                    1,
5109                    "`100%` is a substring, not `100` plus a wildcard: {percent:?}"
5110                );
5111                assert!(percent[0].snippet.contains("100% full"));
5112
5113                let underscore = SessionStore::search_in(db, "a_b.txt", 10, false, false).unwrap();
5114                assert_eq!(
5115                    underscore.len(),
5116                    1,
5117                    "`_` is a character, not any character: {underscore:?}"
5118                );
5119                assert!(underscore[0].snippet.contains("a_b.txt"));
5120                Ok(())
5121            })
5122            .unwrap();
5123    }
5124
5125    /// The escaping itself, where it can be seen: `\`, `%` and `_` each gain one backslash, and the
5126    /// query's `ESCAPE '\'` is what makes them text again.
5127    #[test]
5128    fn a_like_literal_escapes_every_wildcard_character() {
5129        assert_eq!(like_literal("plain"), "plain");
5130        assert_eq!(like_literal("100%"), r"100\%");
5131        assert_eq!(like_literal("a_b"), r"a\_b");
5132        assert_eq!(like_literal(r"C:\temp"), r"C:\\temp");
5133    }
5134
5135    #[test]
5136    fn search_survives_query_syntax_that_would_break_fts() {
5137        let dir = tempfile::tempdir().unwrap();
5138        let store = store(dir.path());
5139        let id = store.new_id();
5140        store
5141            .append(&id, &Message::user(r#"a "quoted" thing AND (parens)"#))
5142            .unwrap();
5143        // If these raised, a search box would be a place where users meet SQL errors.
5144        for q in [r#""quoted""#, "AND (parens)", "*", "a AND OR NOT", "-x"] {
5145            let _ = store.search(q, 5).unwrap();
5146        }
5147        assert_eq!(store.search("quoted", 5).unwrap().len(), 1);
5148    }
5149
5150    #[test]
5151    fn search_results_carry_the_session_and_position() {
5152        let dir = tempfile::tempdir().unwrap();
5153        let store = store(dir.path());
5154        let id = store.new_id();
5155        transcript(&store, &id);
5156        let hits = store.search("contents", 10).unwrap();
5157        assert_eq!(hits.len(), 1);
5158        assert_eq!(hits[0].session_id, id);
5159        assert_eq!(hits[0].seq, 2, "the tool result is the third message");
5160        assert_eq!(hits[0].role, "tool");
5161        assert!(hits[0].at_ms > 0);
5162    }
5163
5164    #[test]
5165    fn a_subagent_session_says_where_it_came_from_and_a_native_one_does_not() {
5166        let dir = tempfile::tempdir().unwrap();
5167        let store = store(dir.path());
5168        let parent = store.new_id();
5169        let child = store.new_id();
5170        store.append(&parent, &Message::user("big job")).unwrap();
5171        store.begin_subagent(&child, &parent, "big:v2").unwrap();
5172        store.append(&child, &Message::user("sub job")).unwrap();
5173
5174        let list = store.list().unwrap();
5175        let find = |id: &str| list.iter().find(|s| s.id == id).unwrap();
5176        assert_eq!(find(&parent).origin, "native");
5177        assert!(find(&parent).subagent().is_none());
5178        let origin = find(&child).subagent().unwrap();
5179        assert_eq!((origin.parent, origin.route), (parent.as_str(), "big:v2"));
5180        assert_eq!(
5181            find(&child).preview,
5182            "sub job",
5183            "the first message still names it"
5184        );
5185    }
5186
5187    #[test]
5188    fn beginning_a_subagent_twice_keeps_the_first_origin() {
5189        let dir = tempfile::tempdir().unwrap();
5190        let store = store(dir.path());
5191        store.begin_subagent("c1", "p1", "big").unwrap();
5192        store.begin_subagent("c1", "p2", "other").unwrap();
5193        let info = store.list().unwrap().remove(0);
5194        assert_eq!(info.subagent().unwrap().parent, "p1");
5195        assert!(store.begin_subagent("c2", "../p", "big").is_err());
5196    }
5197
5198    /// An API call is a run, not a conversation: it is tagged before the loop writes to it, so the
5199    /// row does not arrive as `native` and cannot be mistaken for something a person typed.
5200    #[test]
5201    fn an_api_session_keeps_its_tag_when_the_run_writes_to_it() {
5202        let dir = tempfile::tempdir().unwrap();
5203        let store = store(dir.path());
5204        let id = store.new_id();
5205        store.begin_api(&id).unwrap();
5206        store.append(&id, &Message::user("ask")).unwrap();
5207        store.append(&id, &Message::assistant("answer")).unwrap();
5208
5209        let info = store.list().unwrap().remove(0);
5210        assert_eq!(info.id, id);
5211        assert_eq!(info.origin, SessionStore::API_ORIGIN);
5212        assert!(info.subagent().is_none(), "tagged, not a child");
5213        assert_eq!(info.messages, 2, "and the transcript is really there");
5214    }
5215
5216    /// The sweep is what keeps a polling script from filling the store: it takes the API's own old
5217    /// sessions, and nothing else. A session a person started, or pinned, is not the API's.
5218    #[test]
5219    fn the_sweep_takes_old_api_sessions_and_leaves_the_rest() {
5220        let dir = tempfile::tempdir().unwrap();
5221        let store = store(dir.path());
5222
5223        let old_api = store.new_id();
5224        store.begin_api(&old_api).unwrap();
5225        store.append(&old_api, &Message::user("poll")).unwrap();
5226
5227        let mine = store.new_id();
5228        store
5229            .append(&mine, &Message::user("a real conversation"))
5230            .unwrap();
5231
5232        let pinned_api = store.new_id();
5233        store.begin_api(&pinned_api).unwrap();
5234        store
5235            .append(&pinned_api, &Message::user("keep me"))
5236            .unwrap();
5237        store.set_pinned(&pinned_api, true).unwrap();
5238
5239        let pruned = store.prune_api_sessions(now_ms() + 1).unwrap();
5240        assert_eq!(pruned, 1, "only the API's own, unpinned session");
5241        let left: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
5242        assert!(
5243            left.contains(&mine),
5244            "a conversation is never swept: {left:?}"
5245        );
5246        assert!(left.contains(&pinned_api), "a pin is a decision: {left:?}");
5247        assert!(!left.contains(&old_api), "{left:?}");
5248    }
5249
5250    /// A cutoff in the future is the same sweep; a cutoff of zero takes everything the API left,
5251    /// and a store with no API sessions is untouched.
5252    #[test]
5253    fn the_sweep_is_empty_when_there_is_nothing_the_api_left() {
5254        let dir = tempfile::tempdir().unwrap();
5255        let store = store(dir.path());
5256        store.append("n1", &Message::user("hello")).unwrap();
5257        assert_eq!(store.prune_api_sessions(u64::MAX).unwrap(), 0);
5258        assert_eq!(store.list().unwrap().len(), 1);
5259    }
5260
5261    #[cfg(unix)]
5262    #[tokio::test]
5263    async fn only_a_session_a_live_run_holds_is_reported_as_held() {
5264        let dir = tempfile::tempdir().unwrap();
5265        let store = store(dir.path());
5266        let wait = std::time::Duration::from_millis(0);
5267        let live = store.lock("live", wait).await.unwrap();
5268        // A finished run leaves its lock file behind; the OS has dropped the lock itself.
5269        drop(store.lock("finished", wait).await.unwrap());
5270
5271        let held = held_locks(store.dir());
5272        assert_eq!(held.len(), 1, "{held:?}");
5273        assert_eq!(held[0].id, "live");
5274        assert!(held[0].holder.starts_with("pid "), "{held:?}");
5275
5276        drop(live);
5277        assert!(held_locks(store.dir()).is_empty());
5278        assert!(held_locks(&dir.path().join("no-such-dir")).is_empty());
5279    }
5280
5281    fn picture_message(text: Option<&str>, name: &str) -> Message {
5282        let mut m = match text {
5283            Some(t) => Message::user(t),
5284            None => Message {
5285                role: Role::User,
5286                content: None,
5287                reasoning: None,
5288                finish_reason: None,
5289                tool_calls: Vec::new(),
5290                tool_call_id: None,
5291                images: Vec::new(),
5292                seq: None,
5293            },
5294        };
5295        m.images.push(crate::message::ImagePart {
5296            name: name.into(),
5297            mime: "image/png".into(),
5298            url: "data:image/png;base64,AAAA".into(),
5299            seen: None,
5300        });
5301        m
5302    }
5303
5304    /// `#384`: a write that changed nothing says so, and the write itself is one transaction — the
5305    /// body and the index cannot disagree after a crash between them.
5306    #[test]
5307    fn describing_a_picture_reports_whether_it_changed_anything() {
5308        let dir = tempfile::tempdir().unwrap();
5309        let store = SessionStore::new(dir.path().to_path_buf());
5310        let id = store.new_id();
5311        let seq = store
5312            .append_seq(&id, &picture_message(Some("look"), "shot.png"))
5313            .unwrap();
5314        assert!(
5315            store
5316                .set_image_seen(&id, seq as u64, 0, "a dashboard with a red chart")
5317                .unwrap(),
5318            "a picture that is there was described"
5319        );
5320        // The description is part of what the session says, so a search finds it.
5321        let hits = store.search("red chart", 5).unwrap();
5322        assert_eq!(hits.len(), 1, "the description is searchable: {hits:?}");
5323        // A second write of the same description is still a write: the picture exists.
5324        assert!(store.set_image_seen(&id, seq as u64, 0, "again").unwrap());
5325        // A message that is not there is not a write, and not an error either.
5326        assert!(
5327            !store.set_image_seen(&id, 999, 0, "nowhere").unwrap(),
5328            "a missing row used to answer Ok(()) — a caller could not tell it from a write"
5329        );
5330        // Nor is a picture index the message does not have.
5331        assert!(!store.set_image_seen(&id, seq as u64, 7, "no").unwrap());
5332    }
5333
5334    /// `#388`: a first user row that says nothing must not take the preview slot, because the
5335    /// listing only fills a NULL and would show an empty title for the rest of the session.
5336    #[test]
5337    fn a_first_message_with_no_text_does_not_freeze_the_preview() {
5338        let dir = tempfile::tempdir().unwrap();
5339        let store = SessionStore::new(dir.path().to_path_buf());
5340        let id = store.new_id();
5341        // `Some("")`, not `None`: empty text is what an embedder sends beside a picture, and it is
5342        // the case that stored `""` — a `None` content already left the column NULL.
5343        store
5344            .append(&id, &picture_message(Some(""), "shot.png"))
5345            .unwrap();
5346        store
5347            .append(&id, &Message::user("actually, summarise yesterday"))
5348            .unwrap();
5349        let listed = store.list().unwrap();
5350        let row = listed.iter().find(|s| s.id == id).expect("listed");
5351        assert_eq!(
5352            row.preview.as_str(),
5353            "actually, summarise yesterday",
5354            "the first empty row took the preview: {:?}",
5355            row.preview
5356        );
5357    }
5358
5359    // ---------------------------------------------------------------------------------------
5360    // `#509`: a bot's conversation is a session with `origin = bot:<name>` — the store, the
5361    // compaction, the cost ledger and this listing are reused, so the tests here hold the two
5362    // places the identity changes what the listing answers: whose list it is in, and what a
5363    // search returns.
5364    // ---------------------------------------------------------------------------------------
5365
5366    #[test]
5367    fn a_bot_conversation_is_not_in_the_humans_list() {
5368        let dir = tempfile::tempdir().unwrap();
5369        let store = store(dir.path());
5370        let mine = store.new_id();
5371        store
5372            .append(&mine, &Message::user("the human asked this"))
5373            .unwrap();
5374        let theirs = store.bot_session("nox").unwrap();
5375        store
5376            .append(&theirs, &Message::user("the bot said this"))
5377            .unwrap();
5378
5379        let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
5380        assert_eq!(
5381            listed,
5382            vec![mine.clone()],
5383            "a bot's conversation left the sidebar alone"
5384        );
5385
5386        // Archived ones are the other filter, and it does not smuggle bots back in.
5387        let archived: Vec<String> = store
5388            .list_with_archived()
5389            .unwrap()
5390            .into_iter()
5391            .map(|s| s.id)
5392            .collect();
5393        assert_eq!(archived, vec![mine], "`show archived` is not `show bots`");
5394    }
5395
5396    #[test]
5397    fn list_bots_groups_every_conversation_under_its_name() {
5398        let dir = tempfile::tempdir().unwrap();
5399        let store = store(dir.path());
5400        let first = store.bot_session("nox").unwrap();
5401        store.append(&first, &Message::user("one")).unwrap();
5402        // Cleared, then opened again: two conversations, one identity.
5403        for id in store.bot_sessions("nox").unwrap() {
5404            store.set_archived(&id, true).unwrap();
5405        }
5406        let second = store.bot_session("nox").unwrap();
5407        assert_ne!(
5408            first, second,
5409            "a cleared conversation is not the one reopened"
5410        );
5411        store.append(&second, &Message::user("two")).unwrap();
5412
5413        // Another bot, and a human, so the grouping has something to leave out.
5414        let other = store.bot_session("lux").unwrap();
5415        store.append(&other, &Message::user("three")).unwrap();
5416        let mine = store.new_id();
5417        store.append(&mine, &Message::user("four")).unwrap();
5418
5419        let bots = store.list_bots().unwrap();
5420        assert_eq!(bots.len(), 2, "one row per identity: {bots:?}");
5421        assert_eq!(bots[0].name, "lux", "newest activity first");
5422        let nox = bots.iter().find(|b| b.name == "nox").unwrap();
5423        assert_eq!(nox.sessions, 2, "both conversations counted");
5424        assert_eq!(nox.last_session, second, "the row opens the newest");
5425        assert_eq!(nox.messages, 1);
5426        assert!(
5427            !nox.archived,
5428            "one archived conversation is not a cleared bot"
5429        );
5430    }
5431
5432    /// Two rows written in the same millisecond tie on `updated_ms`, and the tiebreak used to be
5433    /// `id DESC` — text, where `…-9` sorts above `…-10`. CI caught it once: a *cleared* bot
5434    /// conversation was listed as the bot's live one over the conversation opened after it. The
5435    /// tiebreak is the order the rows were stored in, so this holds for `sessions list` too.
5436    #[test]
5437    fn two_sessions_in_the_same_millisecond_are_ordered_by_when_they_were_stored() {
5438        let dir = tempfile::tempdir().unwrap();
5439        let store = store(dir.path());
5440        store.list().unwrap(); // the store exists before a row is written into it
5441        let at = 1_796_297_799_945_i64;
5442        // The pair the failure printed, and a human pair whose text order is the wrong way round.
5443        let rows = [
5444            ("1796297799945-11001-9", "bot:nox"),
5445            ("1796297799945-11001-10", "bot:nox"),
5446            ("1796297799945-11001-2", "native"),
5447            ("1796297799945-11001-11", "native"),
5448        ];
5449        store
5450            .with_db(|db| {
5451                for (id, origin) in rows {
5452                    db.conn.execute(
5453                        "INSERT INTO sessions (id, created_ms, updated_ms, messages, origin)
5454                         VALUES (?1, ?2, ?3, 1, ?4)",
5455                        params![id, at, at, origin],
5456                    )?;
5457                }
5458                Ok(())
5459            })
5460            .unwrap();
5461
5462        let listed: Vec<String> = store.list().unwrap().into_iter().map(|s| s.id).collect();
5463        assert_eq!(
5464            listed,
5465            ["1796297799945-11001-11", "1796297799945-11001-2"],
5466            "a tie is broken by which row was stored later, not by its text"
5467        );
5468
5469        let nox = store
5470            .list_bots()
5471            .unwrap()
5472            .into_iter()
5473            .find(|b| b.name == "nox")
5474            .expect("the bot's two conversations");
5475        assert_eq!(nox.sessions, 2);
5476        assert_eq!(
5477            nox.last_session, "1796297799945-11001-10",
5478            "the conversation opened second is the live one"
5479        );
5480    }
5481
5482    #[test]
5483    fn a_search_leaves_a_bots_conversation_out_unless_asked() {
5484        let dir = tempfile::tempdir().unwrap();
5485        let store = store(dir.path());
5486        let mine = store.new_id();
5487        store
5488            .append(&mine, &Message::user("the vault code is in the drawer"))
5489            .unwrap();
5490        let bots = store.bot_session("nox").unwrap();
5491        store
5492            .append(&bots, &Message::user("the vault code is on the lane"))
5493            .unwrap();
5494
5495        let found = store.search("vault", 10).unwrap();
5496        assert_eq!(
5497            found.len(),
5498            1,
5499            "the human's search found a bot's row: {found:?}"
5500        );
5501        assert_eq!(found[0].session_id, mine);
5502
5503        let asked = store.search_with("vault", 10, true).unwrap();
5504        assert_eq!(
5505            asked.len(),
5506            2,
5507            "`bots = true` is how a bot's rows are asked for"
5508        );
5509        assert!(asked.iter().any(|h| h.session_id == bots));
5510
5511        // A name search is the other half of the query: it must not leak one either.
5512        store
5513            .set_title(&bots, "never mention the vault", TitleSource::User)
5514            .unwrap();
5515        let named = store.search("never", 10).unwrap();
5516        assert!(
5517            named.is_empty(),
5518            "a bot's title answered the human's search: {named:?}"
5519        );
5520        let named = store.search_with("never", 10, true).unwrap();
5521        assert_eq!(named.len(), 1);
5522    }
5523
5524    #[test]
5525    fn a_title_is_never_claimed_for_a_bot() {
5526        let dir = tempfile::tempdir().unwrap();
5527        let store = store(dir.path());
5528        let mine = store.new_id();
5529        store.append(&mine, &Message::user("hello")).unwrap();
5530        store
5531            .set_title(&mine, "derived name", TitleSource::Derived)
5532            .unwrap();
5533        assert!(
5534            store.claim_title_upgrade(&mine).unwrap(),
5535            "a person's conversation may be named by a model"
5536        );
5537
5538        let bots = store.bot_session("nox").unwrap();
5539        store.append(&bots, &Message::user("hello")).unwrap();
5540        store
5541            .set_title(&bots, "derived name", TitleSource::Derived)
5542            .unwrap();
5543        assert!(
5544            !store.claim_title_upgrade(&bots).unwrap(),
5545            "a naming call per turn is the cost this rule exists to avoid"
5546        );
5547    }
5548
5549    #[test]
5550    fn a_bot_conversation_says_which_bot_it_belongs_to() {
5551        let dir = tempfile::tempdir().unwrap();
5552        let store = store(dir.path());
5553        let id = store.bot_session("nox").unwrap();
5554        store.append(&id, &Message::user("hello")).unwrap();
5555        // The row's own `origin` is where the send path reads the identity from, so that is what
5556        // is asserted on the store: one string, and a name that survives being spelled back into
5557        // a URL and a prompt.
5558        assert_eq!(store.origin(&id).unwrap().as_deref(), Some("bot:nox"));
5559
5560        let info = SessionInfo {
5561            id,
5562            messages: 1,
5563            updated_ms: 0,
5564            preview: "hello".into(),
5565            title: None,
5566            origin: "bot:nox".into(),
5567            pinned: false,
5568            archived: false,
5569            cost: None,
5570        };
5571        assert_eq!(info.bot(), Some("nox"));
5572        assert!(info.is_bot());
5573        assert!(info.subagent().is_none());
5574        assert!(
5575            info.tagged_label().starts_with("[bot \u{b7} nox]"),
5576            "{}",
5577            info.tagged_label()
5578        );
5579
5580        // A name with a colon in it is not a name: the origin parser refuses it rather than
5581        // reading it as two.
5582        let odd = SessionInfo {
5583            origin: "bot:a:b".to_string(),
5584            ..info
5585        };
5586        assert_eq!(odd.bot(), None);
5587        // An empty name is the other mistake: `bot:` with nobody behind it.
5588        let empty = SessionInfo {
5589            origin: "bot:".to_string(),
5590            ..odd
5591        };
5592        assert_eq!(empty.bot(), None);
5593    }
5594
5595    // ---------------------------------------------------------------------------------------
5596    // `#171`: a flare run is N sessions with `origin = "flare:<run>:<n>"`, and the position in
5597    // that string is what a run listing orders by and what the lead's result cites.
5598    // ---------------------------------------------------------------------------------------
5599
5600    #[test]
5601    fn a_flare_run_is_a_set_of_sessions_with_their_positions() {
5602        let dir = tempfile::tempdir().unwrap();
5603        let store = store(dir.path());
5604        let run = "f-1";
5605        // Started out of order on purpose: the run starts them in whatever order slots free up,
5606        // and the listing still reads 1..N.
5607        let mut ids = Vec::new();
5608        for n in [2usize, 1, 3] {
5609            let id = store.new_id();
5610            store.begin_flare(&id, run, n).unwrap();
5611            store
5612                .append(&id, &Message::user(format!("flare {n} reading")))
5613                .unwrap();
5614            ids.push((n, id));
5615        }
5616
5617        let listed = store.flares_of(run).unwrap();
5618        assert_eq!(
5619            listed
5620                .iter()
5621                .filter_map(|s| s.flare().map(|f| f.n))
5622                .collect::<Vec<_>>(),
5623            vec![1, 2, 3],
5624            "the run's order is the lead's order, not the order they finished"
5625        );
5626        assert_eq!(listed[0].flare().unwrap().run, run);
5627        assert!(
5628            listed[0].tagged_label().starts_with("[flare \u{b7} f-1/1]"),
5629            "{}",
5630            listed[0].tagged_label()
5631        );
5632        // A flare is not a subagent and not a bot: three prefixes, three answers.
5633        assert!(listed[0].subagent().is_none());
5634        assert!(!listed[0].is_bot());
5635
5636        // Another run's flares are not this run's.
5637        let other = store.new_id();
5638        store.begin_flare(&other, "f-2", 1).unwrap();
5639        assert_eq!(store.flares_of(run).unwrap().len(), 3);
5640
5641        // A run id carries no colon, because the position is the last field.
5642        let bad = store.new_id();
5643        assert!(store.begin_flare(&bad, "f:1", 1).is_err());
5644        // A row whose tail is not a number is not a flare this build wrote.
5645        let odd = SessionInfo {
5646            origin: "flare:run:two".into(),
5647            ..listed[0].clone()
5648        };
5649        assert!(odd.flare().is_none());
5650        assert!(SessionInfo {
5651            origin: "flare::1".into(),
5652            ..listed[0].clone()
5653        }
5654        .flare()
5655        .is_none());
5656    }
5657
5658    #[test]
5659    fn a_search_leaves_a_flares_transcript_out_unless_asked() {
5660        let dir = tempfile::tempdir().unwrap();
5661        let store = store(dir.path());
5662        let mine = store.new_id();
5663        store
5664            .append(&mine, &Message::user("the retry loop is in worker.rs"))
5665            .unwrap();
5666        let flare = store.new_id();
5667        store.begin_flare(&flare, "f-9", 1).unwrap();
5668        store
5669            .append(&flare, &Message::user("the retry loop is in pool.rs"))
5670            .unwrap();
5671
5672        let found = store.search("retry", 10).unwrap();
5673        assert_eq!(found.len(), 1, "the human found a flare's row: {found:?}");
5674        assert_eq!(found[0].session_id, mine);
5675
5676        let asked = store.search_with("retry", 10, true).unwrap();
5677        assert_eq!(
5678            asked.len(),
5679            2,
5680            "`children = true` is how those rows are asked for"
5681        );
5682    }
5683
5684    #[test]
5685    fn a_flare_is_never_named_by_a_model() {
5686        let dir = tempfile::tempdir().unwrap();
5687        let store = store(dir.path());
5688        let id = store.new_id();
5689        store.begin_flare(&id, "f-3", 1).unwrap();
5690        store.append(&id, &Message::user("reading")).unwrap();
5691        store
5692            .set_title(&id, "derived name", TitleSource::Derived)
5693            .unwrap();
5694        assert!(
5695            !store.claim_title_upgrade(&id).unwrap(),
5696            "a transient worker does not get a paid naming call"
5697        );
5698    }
5699}