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