返回 CodeWhale
lib.rs
根目录 / crates / state / src / lib.rs
1 //! Historical thread recovery, canonical owner receipts and metadata.
2 //!
3 //! [`StateStore`] retains legacy conversation graphs as read-only archives.
4 //! A bounded absent-only restore can admit a complete historical graph in one
5 //! SQLite transaction; live transcript writes belong to Runtime's Engine and
6 //! SessionManager. Canonical aliases and durable operations use this same
7 //! SQLite connection. Thread metadata, dynamic tools and the session
8 //! index retain their existing ownership.
9
10 mod runtime_aliases;
11
12 use std::collections::HashMap;
13 use std::fs::{self, OpenOptions};
14 use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
15 use std::path::{Path, PathBuf};
16 use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
17
18 /// Serializes all `session_index.jsonl` read/append/compact/rename operations so
19 /// concurrent `StateStore` clones cannot interleave an append with a compaction
20 /// rename and silently drop entries.
21 static SESSION_INDEX_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
22
23 use anyhow::{Context, Result};
24 use chrono::Utc;
25 use codewhale_paths::{CODEWHALE_APP_DIR, LEGACY_APP_DIR, codewhale_home_override};
26 use rusqlite::{Connection, OptionalExtension, params};
27 use serde::{Deserialize, Serialize};
28 use serde_json::Value;
29
30 // Re-export protocol's ThreadStatus so callers in the state crate and
31 // external consumers (e.g. core) can reference a single canonical definition.
32 pub use codewhale_protocol::ThreadStatus;
33
34 /// Indicates how a session was initiated.
35 ///
36 /// Serialized as lowercase snake_case strings.
37 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
38 #[serde(rename_all = "snake_case")]
39 pub enum SessionSource {
40 /// Started by a user interacting with the CLI.
41 Interactive,
42 /// Resumed from a previously persisted session.
43 Resume,
44 /// Created by forking an existing conversation at a specific message.
45 Fork,
46 /// Initiated programmatically via the API.
47 Api,
48 /// Source is unknown or unspecified.
49 Unknown,
50 }
51
52 /// Metadata for a persisted conversation thread.
53 ///
54 /// Each thread represents a single conversation session and stores its
55 /// configuration, git context, and current status.
56 #[derive(Debug, Clone, Serialize, Deserialize)]
57 pub struct ThreadMetadata {
58 /// Unique identifier for this thread.
59 pub id: String,
60 /// Optional filesystem path to the rollout (JSONL transcript) file.
61 pub rollout_path: Option<PathBuf>,
62 /// Short preview or summary of the thread content.
63 pub preview: String,
64 /// Whether this thread is ephemeral (not persisted long-term).
65 pub ephemeral: bool,
66 /// Identifier of the model provider used for this thread (e.g. `"openai"`).
67 pub model_provider: String,
68 /// Unix timestamp (seconds) when the thread was created.
69 pub created_at: i64,
70 /// Unix timestamp (seconds) of the most recent update to the thread.
71 pub updated_at: i64,
72 /// Current lifecycle status of the thread.
73 pub status: ThreadStatus,
74 /// Optional filesystem path associated with the thread working context.
75 pub path: Option<PathBuf>,
76 /// Working directory that was active when the thread was created.
77 pub cwd: PathBuf,
78 /// Version of the CLI that created this thread.
79 pub cli_version: String,
80 /// How this session was initiated.
81 pub source: SessionSource,
82 /// User-assigned display name for the thread.
83 pub name: Option<String>,
84 /// Serialized sandbox policy applied to this thread, if any.
85 pub sandbox_policy: Option<String>,
86 /// Approval mode configured for tool calls in this thread.
87 pub approval_mode: Option<String>,
88 /// Whether the thread has been archived.
89 pub archived: bool,
90 /// Unix timestamp (seconds) when the thread was archived, or `None` if not archived.
91 pub archived_at: Option<i64>,
92 /// Git commit SHA of the working tree when the thread was created.
93 pub git_sha: Option<String>,
94 /// Git branch checked out when the thread was created.
95 pub git_branch: Option<String>,
96 /// URL of the git remote origin, if available.
97 pub git_origin_url: Option<String>,
98 /// Memory mode configured for this thread (e.g. `"local"`, `"remote"`).
99 pub memory_mode: Option<String>,
100 /// ID of the current leaf message in the conversation tree.
101 pub current_leaf_id: Option<i64>,
102 }
103
104 /// A complete historical SQLite thread, restored once into an absent target.
105 ///
106 /// This is recovery/import data, never a live transcript writer. Entry IDs,
107 /// timestamps, all branches and the exact selected leaf are retained.
108 #[derive(Debug, Clone, Serialize, Deserialize)]
109 #[serde(deny_unknown_fields)]
110 pub struct LegacyThreadArchive {
111 pub thread: ThreadMetadata,
112 pub messages: Vec<MessageRecord>,
113 #[serde(default)]
114 pub goal: Option<ThreadGoalRecord>,
115 #[serde(default)]
116 pub checkpoints: Vec<CheckpointRecord>,
117 }
118
119 /// A dynamically registered tool associated with a thread.
120 #[derive(Debug, Clone, Serialize, Deserialize)]
121 pub struct DynamicToolRecord {
122 /// Ordinal position of this tool in the thread tool list.
123 pub position: i64,
124 /// Unique name identifying the tool.
125 pub name: String,
126 /// Human-readable description of what the tool does.
127 pub description: Option<String>,
128 /// JSON Schema describing the tool input parameters.
129 pub input_schema: Value,
130 }
131
132 pub use codewhale_protocol::MessageRecord;
133
134 /// Private historical database fixture for State unit tests.
135 #[cfg(test)]
136 #[derive(Debug, Clone)]
137 struct NewMessage {
138 /// Role of the message sender (e.g. `"user"`, `"history"`).
139 pub role: String,
140 /// Text content of the message.
141 pub content: String,
142 /// Optional structured item payload.
143 pub item: Option<Value>,
144 }
145
146 /// A named checkpoint capturing the state of a thread at a point in time.
147 #[derive(Debug, Clone, Serialize, Deserialize)]
148 pub struct CheckpointRecord {
149 /// ID of the thread this checkpoint belongs to.
150 pub thread_id: String,
151 /// Unique identifier for this checkpoint within its thread.
152 pub checkpoint_id: String,
153 /// Serialized state snapshot stored as a JSON value.
154 pub state: Value,
155 /// Unix timestamp (seconds) when the checkpoint was created or last updated.
156 pub created_at: i64,
157 }
158
159 /// Persisted lifecycle status for a thread goal.
160 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
161 #[serde(rename_all = "snake_case")]
162 pub enum ThreadGoalStatus {
163 /// Goal is active and should continue receiving work.
164 Active,
165 /// Goal is paused by the user.
166 Paused,
167 /// Goal is blocked and cannot make meaningful progress.
168 Blocked,
169 /// Goal stopped because account/service usage limits were reached.
170 UsageLimited,
171 /// Goal stopped because its explicit token budget was reached.
172 BudgetLimited,
173 /// Goal has been completed.
174 Complete,
175 }
176
177 /// Persisted goal state attached to a thread.
178 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
179 pub struct ThreadGoalRecord {
180 /// Thread this goal belongs to.
181 pub thread_id: String,
182 /// Stable identifier for this goal revision.
183 pub goal_id: String,
184 /// User-visible objective.
185 pub objective: String,
186 /// Current lifecycle status.
187 pub status: ThreadGoalStatus,
188 /// Optional token budget requested by the user.
189 pub token_budget: Option<i64>,
190 /// Tokens consumed while pursuing the goal.
191 pub tokens_used: i64,
192 /// Elapsed wall-clock work time in seconds.
193 pub time_used_seconds: i64,
194 /// Durable continuation passes dispatched for this objective.
195 pub continuation_count: i64,
196 /// Unix timestamp (seconds) when the goal was created.
197 pub created_at: i64,
198 /// Unix timestamp (seconds) when the goal was last updated.
199 pub updated_at: i64,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub last_gap_fingerprint: Option<String>,
202 #[serde(default)]
203 pub repeated_gap_count: u32,
204 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub last_gap_pass: Option<u32>,
206 #[serde(default, skip_serializing_if = "Option::is_none")]
207 pub pause_reason: Option<codewhale_protocol::GoalPauseReason>,
208 }
209
210 /// Filters for listing conversation threads.
211 #[derive(Debug, Clone)]
212 pub struct ThreadListFilters {
213 /// Whether to include archived threads in the results.
214 pub include_archived: bool,
215 /// Maximum number of threads to return. Defaults to 50.
216 pub limit: Option<usize>,
217 }
218
219 impl Default for ThreadListFilters {
220 fn default() -> Self {
221 Self {
222 include_archived: false,
223 limit: Some(50),
224 }
225 }
226 }
227
228 #[derive(Debug, Clone, Serialize, Deserialize)]
229 struct SessionIndexEntry {
230 thread_id: String,
231 thread_name: Option<String>,
232 updated_at: i64,
233 rollout_path: Option<PathBuf>,
234 }
235
236 /// Rewrite the session index once the append-only log grows large enough that
237 /// full-file scans become costly. Lookups already dedupe by thread id, so
238 /// compaction keeps only the latest entry per thread.
239 fn session_index_compact_line_threshold() -> usize {
240 if cfg!(test) { 5 } else { 5_000 }
241 }
242
243 /// The `user_version` the last step of `StateStore::migrate_schema` writes.
244 const SCHEMA_VERSION: u32 = 7;
245
246 /// Persistent storage for conversation threads, messages, and checkpoints.
247 ///
248 /// Backed by a SQLite database and an append-only JSONL session index file.
249 /// The database schema is automatically initialized and migrated on [`open`](Self::open).
250 #[derive(Debug, Clone)]
251 pub struct StateStore {
252 db_path: PathBuf,
253 session_index_path: PathBuf,
254 // Single long-lived connection shared by all clones. SQLite pragmas are
255 // per-connection, so opening once in `open` and applying them there keeps
256 // every operation consistent without re-opening the database per call.
257 conn: Arc<Mutex<Connection>>,
258 }
259
260 impl StateStore {
261 /// Open (or create) a state store at the given database path.
262 ///
263 /// If `path` is `None`, the default location (`~/.codewhale/state.db`, with
264 /// `~/.deepseek/state.db` as a legacy fallback) is used.
265 /// The database schema is created automatically if it does not exist.
266 pub fn open(path: Option<PathBuf>) -> Result<Self> {
267 let db_path = match path {
268 Some(path) => path,
269 None => {
270 let default = default_state_db_path();
271 anyhow::ensure!(
272 default.is_absolute(),
273 "could not resolve an absolute home directory for the state database; set CODEWHALE_HOME to an absolute path"
274 );
275 default
276 }
277 };
278 let session_index_path = db_path
279 .parent()
280 .unwrap_or_else(|| Path::new("."))
281 .join("session_index.jsonl");
282 if let Some(parent) = db_path.parent()
283 && !parent.as_os_str().is_empty()
284 {
285 fs::create_dir_all(parent).with_context(|| {
286 format!("failed to create state directory {}", parent.display())
287 })?;
288 }
289 let conn = Connection::open(&db_path)
290 .with_context(|| format!("failed to open state db {}", db_path.display()))?;
291 Self::configure_connection(&conn, &db_path)?;
292 Self::init_schema(&conn)?;
293 Ok(Self {
294 db_path,
295 session_index_path,
296 conn: Arc::new(Mutex::new(conn)),
297 })
298 }
299
300 /// Apply connection-level SQLite settings that must hold for every open.
301 ///
302 /// Enables WAL so readers and writers from concurrent CodeWhale processes
303 /// do not block each other as aggressively as the default rollback journal,
304 /// and sets a multi-second busy timeout so a second process retries on
305 /// `SQLITE_BUSY` instead of failing immediately (issue #4734).
306 fn configure_connection(conn: &Connection, db_path: &Path) -> Result<()> {
307 // Install our wait policy before touching database-level settings or
308 // schema. Connection::open may currently provide a dependency default,
309 // but StateStore must not rely on that incidental behavior.
310 conn.busy_timeout(std::time::Duration::from_secs(5))
311 .with_context(|| format!("failed to set busy_timeout for {}", db_path.display()))?;
312 conn.pragma_update(None, "foreign_keys", "ON")
313 .with_context(|| format!("failed to enable foreign keys for {}", db_path.display()))?;
314
315 // WAL persists in the database header, so established stores need no
316 // write-like journal transition on every process start. Fresh or
317 // explicitly downgraded stores still transition once, and we verify
318 // SQLite accepted the requested mode instead of silently retaining the
319 // previous one (for example on an unsupported VFS).
320 let journal_mode: String = conn
321 .pragma_query_value(None, "journal_mode", |row| row.get(0))
322 .with_context(|| format!("failed to read journal mode for {}", db_path.display()))?;
323 if !journal_mode.eq_ignore_ascii_case("wal") {
324 let configured_mode: String = conn
325 .pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get(0))
326 .with_context(|| format!("failed to enable WAL for {}", db_path.display()))?;
327 if !configured_mode.eq_ignore_ascii_case("wal") {
328 anyhow::bail!(
329 "failed to enable WAL for {}: SQLite retained journal mode {configured_mode}",
330 db_path.display()
331 );
332 }
333 }
334 Ok(())
335 }
336
337 /// Returns the filesystem path of the underlying SQLite database.
338 pub fn db_path(&self) -> &Path {
339 &self.db_path
340 }
341
342 fn conn(&self) -> Result<MutexGuard<'_, Connection>> {
343 // Poisoning means a panic mid-operation; any open transaction was
344 // rolled back when it dropped, but surface the condition rather than
345 // silently continuing on a connection whose state we can't vouch for.
346 self.conn
347 .lock()
348 .map_err(|_| anyhow::anyhow!("state db connection mutex poisoned"))
349 }
350
351 fn init_schema(conn: &Connection) -> Result<()> {
352 let user_version: u32 = conn.query_row("PRAGMA user_version;", [], |row| row.get(0))?;
353 if user_version >= SCHEMA_VERSION {
354 return Ok(());
355 }
356 // Take the write lock *before* reading the version or probing
357 // columns. Two processes opening a fresh database used to both read
358 // v0 and "column missing" outside any transaction; the loser then
359 // waited out the winner's commit and re-ran its `ADD COLUMN`, failing
360 // the open with "duplicate column name". Under `BEGIN IMMEDIATE` the
361 // loser waits (busy_timeout) and then decides from the committed
362 // schema. The version read above is only a fast path for the
363 // already-current database, which never takes the write lock.
364 conn.execute_batch("BEGIN IMMEDIATE;")
365 .context("failed to lock the state db for its schema migration")?;
366 let migrated = Self::migrate_schema(conn).and_then(|()| {
367 conn.execute_batch("COMMIT;")
368 .context("failed to commit the state db schema migration")
369 });
370 if migrated.is_err() {
371 let _ = conn.execute_batch("ROLLBACK;");
372 }
373 migrated
374 }
375
376 /// Every schema step, run inside the one transaction [`Self::init_schema`]
377 /// holds; the steps themselves never begin or commit.
378 fn migrate_schema(conn: &Connection) -> Result<()> {
379 let mut user_version: u32 = conn.query_row("PRAGMA user_version;", [], |row| row.get(0))?;
380 if user_version == 0 {
381 // Guard each ALTER: a database restored with a v0 header (or
382 // stamped by a racing process that crashed before setting
383 // user_version) can already carry these columns, and an
384 // unguarded ADD COLUMN aborts the whole open with
385 // "duplicate column name".
386 let add_parent_entry_id = if column_exists(conn, "messages", "parent_entry_id")? {
387 ""
388 } else {
389 "ALTER TABLE messages ADD COLUMN parent_entry_id INTEGER NULL;"
390 };
391 let add_current_leaf_id = if column_exists(conn, "threads", "current_leaf_id")? {
392 ""
393 } else {
394 "ALTER TABLE threads ADD COLUMN current_leaf_id INTEGER NULL;"
395 };
396 conn.execute_batch(&format!(
397 r#"
398 CREATE TABLE IF NOT EXISTS threads (
399 id TEXT PRIMARY KEY,
400 rollout_path TEXT,
401 preview TEXT NOT NULL,
402 ephemeral INTEGER NOT NULL,
403 model_provider TEXT NOT NULL,
404 created_at INTEGER NOT NULL,
405 updated_at INTEGER NOT NULL,
406 status TEXT NOT NULL,
407 path TEXT,
408 cwd TEXT NOT NULL,
409 cli_version TEXT NOT NULL,
410 source TEXT NOT NULL,
411 title TEXT,
412 sandbox_policy TEXT,
413 approval_mode TEXT,
414 archived INTEGER NOT NULL DEFAULT 0,
415 archived_at INTEGER,
416 git_sha TEXT,
417 git_branch TEXT,
418 git_origin_url TEXT,
419 memory_mode TEXT
420 );
421 CREATE INDEX IF NOT EXISTS idx_threads_updated_at ON threads(updated_at DESC);
422 CREATE INDEX IF NOT EXISTS idx_threads_archived_at ON threads(archived_at DESC);
423 CREATE INDEX IF NOT EXISTS idx_threads_archived_updated ON threads(archived, updated_at DESC);
424
425 CREATE TABLE IF NOT EXISTS thread_dynamic_tools (
426 thread_id TEXT NOT NULL,
427 position INTEGER NOT NULL,
428 name TEXT NOT NULL,
429 description TEXT,
430 input_schema TEXT NOT NULL,
431 PRIMARY KEY (thread_id, position),
432 FOREIGN KEY(thread_id) REFERENCES threads(id) ON DELETE CASCADE
433 );
434
435 CREATE TABLE IF NOT EXISTS messages (
436 id INTEGER PRIMARY KEY AUTOINCREMENT,
437 thread_id TEXT NOT NULL,
438 role TEXT NOT NULL,
439 content TEXT NOT NULL,
440 item_json TEXT,
441 created_at INTEGER NOT NULL,
442 FOREIGN KEY(thread_id) REFERENCES threads(id) ON DELETE CASCADE
443 );
444 CREATE INDEX IF NOT EXISTS idx_messages_thread_created_at ON messages(thread_id, created_at ASC);
445
446 CREATE TABLE IF NOT EXISTS checkpoints (
447 thread_id TEXT NOT NULL,
448 checkpoint_id TEXT NOT NULL,
449 state_json TEXT NOT NULL,
450 created_at INTEGER NOT NULL,
451 PRIMARY KEY(thread_id, checkpoint_id),
452 FOREIGN KEY(thread_id) REFERENCES threads(id) ON DELETE CASCADE
453 );
454 CREATE INDEX IF NOT EXISTS idx_checkpoints_thread_created_at ON checkpoints(thread_id, created_at DESC);
455
456 CREATE TABLE IF NOT EXISTS jobs (
457 id TEXT PRIMARY KEY,
458 name TEXT NOT NULL,
459 status TEXT NOT NULL,
460 progress INTEGER,
461 detail TEXT,
462 created_at INTEGER NOT NULL,
463 updated_at INTEGER NOT NULL
464 );
465 CREATE INDEX IF NOT EXISTS idx_jobs_updated_at ON jobs(updated_at DESC);
466
467 -- Add parent_entry_id column, and set to last message before current message
468 {add_parent_entry_id}
469 UPDATE messages
470 SET parent_entry_id = (
471 SELECT m2.id
472 FROM messages m2
473 WHERE m2.thread_id = messages.thread_id
474 AND (
475 m2.created_at < messages.created_at
476 OR (
477 m2.created_at = messages.created_at
478 AND m2.id < messages.id
479 )
480 )
481 ORDER BY m2.created_at DESC, m2.id DESC
482 LIMIT 1
483 );
484 CREATE INDEX IF NOT EXISTS idx_messages_parent_entry_id ON messages(parent_entry_id);
485
486 -- Add current_leaf_id column, and set to last message in thread
487 {add_current_leaf_id}
488 UPDATE threads
489 SET current_leaf_id = (
490 SELECT m.id
491 FROM messages m
492 WHERE m.thread_id = threads.id
493 ORDER BY m.id DESC
494 LIMIT 1
495 );
496
497 PRAGMA user_version = 1;
498 "#
499 ))
500 .context("failed to initialize thread schema")?;
501 user_version = 1;
502 }
503 if user_version < 2 {
504 conn.execute_batch(
505 r#"
506 CREATE TABLE IF NOT EXISTS workflow_runs (
507 id TEXT PRIMARY KEY,
508 workflow_id TEXT NOT NULL,
509 goal TEXT NOT NULL,
510 status TEXT NOT NULL,
511 input_hash TEXT,
512 started_at INTEGER NOT NULL,
513 completed_at INTEGER,
514 metadata_json TEXT NOT NULL DEFAULT '{}'
515 );
516 CREATE INDEX IF NOT EXISTS idx_workflow_runs_status_started_at
517 ON workflow_runs(status, started_at DESC);
518 CREATE INDEX IF NOT EXISTS idx_workflow_runs_workflow_started_at
519 ON workflow_runs(workflow_id, started_at DESC);
520
521 CREATE TABLE IF NOT EXISTS branch_runs (
522 id TEXT PRIMARY KEY,
523 workflow_run_id TEXT NOT NULL,
524 branch_id TEXT NOT NULL,
525 node_id TEXT NOT NULL,
526 status TEXT NOT NULL,
527 started_at INTEGER NOT NULL,
528 completed_at INTEGER,
529 result_json TEXT NOT NULL DEFAULT '{}',
530 FOREIGN KEY(workflow_run_id) REFERENCES workflow_runs(id) ON DELETE CASCADE
531 );
532 CREATE INDEX IF NOT EXISTS idx_branch_runs_workflow_run_id
533 ON branch_runs(workflow_run_id);
534 CREATE INDEX IF NOT EXISTS idx_branch_runs_branch_id
535 ON branch_runs(branch_id);
536
537 CREATE TABLE IF NOT EXISTS leaf_runs (
538 id TEXT PRIMARY KEY,
539 workflow_run_id TEXT NOT NULL,
540 branch_run_id TEXT,
541 leaf_id TEXT NOT NULL,
542 task_id TEXT NOT NULL,
543 input_hash TEXT,
544 status TEXT NOT NULL,
545 output_json TEXT NOT NULL DEFAULT '{}',
546 artifacts_json TEXT NOT NULL DEFAULT '[]',
547 started_at INTEGER NOT NULL,
548 completed_at INTEGER,
549 FOREIGN KEY(workflow_run_id) REFERENCES workflow_runs(id) ON DELETE CASCADE,
550 FOREIGN KEY(branch_run_id) REFERENCES branch_runs(id) ON DELETE SET NULL
551 );
552 CREATE INDEX IF NOT EXISTS idx_leaf_runs_workflow_run_id
553 ON leaf_runs(workflow_run_id);
554 CREATE INDEX IF NOT EXISTS idx_leaf_runs_replay_lookup
555 ON leaf_runs(workflow_run_id, leaf_id, input_hash);
556
557 CREATE TABLE IF NOT EXISTS control_node_runs (
558 id TEXT PRIMARY KEY,
559 workflow_run_id TEXT NOT NULL,
560 node_id TEXT NOT NULL,
561 kind TEXT NOT NULL,
562 status TEXT NOT NULL,
563 selected_children_json TEXT NOT NULL DEFAULT '[]',
564 result_json TEXT NOT NULL DEFAULT '{}',
565 started_at INTEGER NOT NULL,
566 completed_at INTEGER,
567 FOREIGN KEY(workflow_run_id) REFERENCES workflow_runs(id) ON DELETE CASCADE
568 );
569 CREATE INDEX IF NOT EXISTS idx_control_node_runs_workflow_run_id
570 ON control_node_runs(workflow_run_id);
571 CREATE INDEX IF NOT EXISTS idx_control_node_runs_node_id
572 ON control_node_runs(node_id);
573
574 CREATE TABLE IF NOT EXISTS teacher_candidates (
575 id TEXT PRIMARY KEY,
576 workflow_run_id TEXT NOT NULL,
577 control_node_run_id TEXT NOT NULL,
578 candidate_id TEXT NOT NULL,
579 branch_run_id TEXT,
580 score REAL,
581 passed INTEGER,
582 rationale_json TEXT NOT NULL DEFAULT '{}',
583 created_at INTEGER NOT NULL,
584 FOREIGN KEY(workflow_run_id) REFERENCES workflow_runs(id) ON DELETE CASCADE,
585 FOREIGN KEY(control_node_run_id) REFERENCES control_node_runs(id) ON DELETE CASCADE,
586 FOREIGN KEY(branch_run_id) REFERENCES branch_runs(id) ON DELETE SET NULL
587 );
588 CREATE INDEX IF NOT EXISTS idx_teacher_candidates_workflow_run_id
589 ON teacher_candidates(workflow_run_id);
590 CREATE INDEX IF NOT EXISTS idx_teacher_candidates_control_node_run_id
591 ON teacher_candidates(control_node_run_id);
592
593 PRAGMA user_version = 2;
594 "#,
595 )
596 .context("failed to initialize workflow trace schema")?;
597 user_version = 2;
598 }
599 if user_version < 3 {
600 conn.execute_batch(
601 r#"
602 CREATE TABLE IF NOT EXISTS thread_goals (
603 thread_id TEXT PRIMARY KEY NOT NULL,
604 goal_id TEXT NOT NULL,
605 objective TEXT NOT NULL,
606 status TEXT NOT NULL CHECK(status IN (
607 'active',
608 'paused',
609 'blocked',
610 'usage_limited',
611 'budget_limited',
612 'complete'
613 )),
614 token_budget INTEGER,
615 tokens_used INTEGER NOT NULL DEFAULT 0,
616 time_used_seconds INTEGER NOT NULL DEFAULT 0,
617 created_at INTEGER NOT NULL,
618 updated_at INTEGER NOT NULL,
619 FOREIGN KEY(thread_id) REFERENCES threads(id) ON DELETE CASCADE
620 );
621
622 PRAGMA user_version = 3;
623 "#,
624 )
625 .context("failed to initialize thread goal schema")?;
626 user_version = 3;
627 }
628 if user_version < 4 {
629 // Same restore/race guard as the v0 block: the column may
630 // already exist even though the header predates version 4.
631 let add_continuation_count = if column_exists(
632 conn,
633 "thread_goals",
634 "continuation_count",
635 )? {
636 ""
637 } else {
638 "ALTER TABLE thread_goals\n ADD COLUMN continuation_count INTEGER NOT NULL DEFAULT 0;"
639 };
640 conn.execute_batch(&format!(
641 r#"
642 {add_continuation_count}
643
644 PRAGMA user_version = 4;
645 "#
646 ))
647 .context("failed to initialize thread goal continuation schema")?;
648 user_version = 4;
649 }
650 if user_version < 5 {
651 let mut additions = String::new();
652 for (column, definition) in [
653 ("last_gap_fingerprint", "TEXT"),
654 ("repeated_gap_count", "INTEGER NOT NULL DEFAULT 0"),
655 ("last_gap_pass", "INTEGER"),
656 ("pause_reason", "TEXT"),
657 ] {
658 if !column_exists(conn, "thread_goals", column)? {
659 additions.push_str(&format!(
660 "ALTER TABLE thread_goals ADD COLUMN {column} {definition};\n"
661 ));
662 }
663 }
664 conn.execute_batch(&format!("{additions} PRAGMA user_version = 5;"))
665 .context("failed to initialize durable goal stall schema")?;
666 user_version = 5;
667 }
668 if user_version < 6 {
669 conn.execute_batch(
670 r#"
671 CREATE TABLE IF NOT EXISTS thread_runtime_links (
672 thread_id TEXT PRIMARY KEY NOT NULL,
673 runtime_thread_id TEXT NOT NULL,
674 created_at INTEGER NOT NULL,
675 FOREIGN KEY(thread_id) REFERENCES threads(id) ON DELETE CASCADE
676 );
677
678 PRAGMA user_version = 6;
679 "#,
680 )
681 .context("failed to initialize thread runtime link schema")?;
682 user_version = 6;
683 }
684 if user_version < 7 {
685 conn.execute_batch(
686 "CREATE TABLE IF NOT EXISTS state_store_identity (singleton INTEGER PRIMARY KEY CHECK(singleton = 1), identity TEXT NOT NULL);
687 INSERT OR IGNORE INTO state_store_identity VALUES(1, lower(hex(randomblob(32))));
688 CREATE TABLE IF NOT EXISTS thread_runtime_receipts (thread_id TEXT PRIMARY KEY REFERENCES threads(id) ON DELETE CASCADE, receipt_json TEXT NOT NULL);
689 CREATE TABLE IF NOT EXISTS thread_runtime_operations (operation_key TEXT PRIMARY KEY, request_digest TEXT NOT NULL, receipt_json TEXT NOT NULL);
690 PRAGMA user_version = 7;",
691 ).context("failed to initialize bound canonical Runtime receipts")?;
692 }
693 Ok(())
694 }
695
696 /// The runtime (turn engine) thread a client-facing thread runs on, if
697 /// one was linked. Links outlive the app-server process, so a thread
698 /// keeps its conversation across a daemon restart.
699 pub fn get_runtime_thread_link(&self, thread_id: &str) -> Result<Option<String>> {
700 let conn = self.conn()?;
701 conn.query_row(
702 "SELECT runtime_thread_id FROM thread_runtime_links WHERE thread_id = ?1",
703 params![thread_id],
704 |row| row.get(0),
705 )
706 .optional()
707 .with_context(|| format!("failed to read runtime link for thread {thread_id}"))
708 }
709
710 /// Record the runtime thread for `thread_id`. The thread must exist; the
711 /// link is removed with it.
712 #[cfg(test)]
713 fn set_runtime_thread_link(&self, thread_id: &str, runtime_thread_id: &str) -> Result<()> {
714 let mut conn = self.conn()?;
715 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
716 let bound: bool = tx.query_row(
717 "SELECT EXISTS(SELECT 1 FROM thread_runtime_receipts WHERE thread_id = ?1)",
718 params![thread_id],
719 |row| row.get(0),
720 )?;
721 anyhow::ensure!(
722 !bound,
723 "bound canonical aliases cannot be changed by the legacy link writer"
724 );
725 tx.execute(
726 r#"
727 INSERT INTO thread_runtime_links(thread_id, runtime_thread_id, created_at)
728 VALUES (?1, ?2, ?3)
729 ON CONFLICT(thread_id) DO UPDATE SET
730 runtime_thread_id = excluded.runtime_thread_id,
731 created_at = excluded.created_at
732 "#,
733 params![thread_id, runtime_thread_id, Utc::now().timestamp()],
734 )
735 .with_context(|| format!("failed to save runtime link for thread {thread_id}"))?;
736 tx.commit()?;
737 Ok(())
738 }
739
740 /// Insert or update thread metadata.
741 ///
742 /// This does **not** update legacy history or its selected leaf. Restoring an
743 /// old transcript requires an absent target and a complete immutable archive.
744 pub fn upsert_thread(&self, thread: &ThreadMetadata) -> Result<()> {
745 let conn = self.conn()?;
746 write_thread_metadata_on(&conn, thread)?;
747
748 self.append_thread_name(
749 &thread.id,
750 thread.name.clone(),
751 thread.updated_at,
752 thread.rollout_path.clone(),
753 )?;
754 Ok(())
755 }
756
757 /// Retrieve a single thread by its ID.
758 ///
759 /// Returns `None` if no thread with the given ID exists.
760 pub fn get_thread(&self, id: &str) -> Result<Option<ThreadMetadata>> {
761 let conn = self.conn()?;
762 conn.query_row(
763 r#"
764 SELECT id, rollout_path, preview, ephemeral, model_provider, created_at, updated_at, status, path, cwd,
765 cli_version, source, title, sandbox_policy, approval_mode, archived, archived_at,
766 git_sha, git_branch, git_origin_url, memory_mode, current_leaf_id
767 FROM threads
768 WHERE id = ?1
769 "#,
770 params![id],
771 row_to_thread,
772 )
773 .optional()
774 .context("failed to read thread")
775 }
776
777 /// List threads ordered by most recently updated.
778 ///
779 /// Use [`ThreadListFilters`] to control whether archived threads are included
780 /// and the maximum number of results returned.
781 pub fn list_threads(&self, filters: ThreadListFilters) -> Result<Vec<ThreadMetadata>> {
782 let conn = self.conn()?;
783 let sql = if filters.include_archived {
784 "SELECT id, rollout_path, preview, ephemeral, model_provider, created_at, updated_at, status, path, cwd, cli_version, source, title, sandbox_policy, approval_mode, archived, archived_at, git_sha, git_branch, git_origin_url, memory_mode, current_leaf_id FROM threads ORDER BY updated_at DESC LIMIT +?1"
785 } else {
786 "SELECT id, rollout_path, preview, ephemeral, model_provider, created_at, updated_at, status, path, cwd, cli_version, source, title, sandbox_policy, approval_mode, archived, archived_at, git_sha, git_branch, git_origin_url, memory_mode, current_leaf_id FROM threads WHERE archived = 0 ORDER BY updated_at DESC LIMIT +?1"
787 };
788
789 let mut stmt = conn.prepare(sql).context("failed to prepare list query")?;
790 let limit = i64::try_from(filters.limit.unwrap_or(50)).unwrap_or(i64::MAX);
791 let mut rows = stmt
792 .query(params![limit])
793 .context("failed to query threads")?;
794 let mut out = Vec::new();
795 while let Some(row) = rows.next().context("failed to iterate thread rows")? {
796 out.push(row_to_thread(row)?);
797 }
798 Ok(out)
799 }
800
801 /// Archive a thread, setting its status to [`ThreadStatus::Archived`] and
802 /// recording the current timestamp.
803 pub fn mark_archived(&self, id: &str) -> Result<()> {
804 let conn = self.conn()?;
805 conn.execute(
806 "UPDATE threads SET archived = 1, archived_at = ?2, status = ?3 WHERE id = ?1",
807 params![
808 id,
809 Utc::now().timestamp(),
810 thread_status_to_str(&ThreadStatus::Archived)
811 ],
812 )
813 .context("failed to archive thread")?;
814 Ok(())
815 }
816
817 /// Unarchive a thread, removing the archived flag and clearing `archived_at`.
818 pub fn mark_unarchived(&self, id: &str) -> Result<()> {
819 let conn = self.conn()?;
820 conn.execute(
821 "UPDATE threads SET archived = 0, archived_at = NULL, status = CASE WHEN status = ?2 THEN ?3 ELSE status END WHERE id = ?1",
822 params![
823 id,
824 thread_status_to_str(&ThreadStatus::Archived),
825 thread_status_to_str(&ThreadStatus::Idle),
826 ],
827 )
828 .context("failed to unarchive thread")?;
829 Ok(())
830 }
831
832 /// Permanently delete a thread and all of its associated data
833 /// (messages, checkpoints, dynamic tools) via cascading foreign keys, and
834 /// drop it from the session index.
835 ///
836 /// The index is append-only and name lookups read it without the
837 /// database, so a deleted thread left there kept answering for its name —
838 /// shadowing a live thread of the same name when it was newer.
839 pub fn delete_thread(&self, id: &str) -> Result<()> {
840 {
841 let conn = self.conn()?;
842 conn.execute("DELETE FROM threads WHERE id = ?1", params![id])
843 .context("failed to delete thread")?;
844 }
845 let _guard = SESSION_INDEX_LOCK
846 .lock()
847 .unwrap_or_else(std::sync::PoisonError::into_inner);
848 self.with_session_index_lock(|| {
849 let mut latest = self.session_index_map()?;
850 if latest.remove(id).is_some() {
851 self.rewrite_session_index_locked(&latest)?;
852 }
853 Ok(())
854 })
855 }
856
857 /// Insert or replace the persisted goal for a thread.
858 #[cfg(test)]
859 fn upsert_thread_goal(&self, goal: &ThreadGoalRecord) -> Result<()> {
860 let conn = self.conn()?;
861 write_thread_goal_on(&conn, goal)
862 }
863
864 /// Accrue additional token and wall-clock usage onto a thread's persisted goal.
865 ///
866 /// This is the durable, additive accounting path for the persistent goal loop: it
867 /// increments `tokens_used` and `time_used_seconds` in a single atomic SQL `UPDATE`
868 /// (`col = col + ?`) so concurrent accruals do not race a read-modify-write. The
869 /// goal's `updated_at` is advanced to the larger of its current value and `now`,
870 /// keeping the timestamp monotonic even if a stale `now` is supplied.
871 ///
872 /// `token_delta` and `time_delta_seconds` are added on the database side; callers
873 /// should pass non-negative deltas (negative values are accepted and will decrement,
874 /// which is intentionally left to the caller's discretion).
875 ///
876 /// Returns the updated [`ThreadGoalRecord`], or `Ok(None)` if the thread has no
877 /// persisted goal. Unlike the historical fixture upsert this never
878 /// creates a goal row; it only accumulates onto an existing one.
879 #[cfg(test)]
880 fn record_thread_goal_usage(
881 &self,
882 thread_id: &str,
883 token_delta: i64,
884 time_delta_seconds: i64,
885 now: i64,
886 ) -> Result<Option<ThreadGoalRecord>> {
887 let conn = self.conn()?;
888 let changed = conn
889 .execute(
890 r#"
891 UPDATE thread_goals
892 SET tokens_used = tokens_used + ?2,
893 time_used_seconds = time_used_seconds + ?3,
894 updated_at = MAX(updated_at, ?4)
895 WHERE thread_id = ?1
896 "#,
897 params![thread_id, token_delta, time_delta_seconds, now],
898 )
899 .context("failed to record thread goal usage")?;
900 if changed == 0 {
901 return Ok(None);
902 }
903 Self::read_thread_goal(&conn, thread_id)
904 }
905
906 /// Increment the durable cross-turn continuation counter for a thread goal.
907 ///
908 /// The older TUI continuation guard is scoped to one engine turn. This
909 /// counter is intentionally persisted so a resumed goal loop can feed
910 /// `goal_loop::decide_continuation` with the true cross-turn count.
911 #[cfg(test)]
912 fn record_thread_goal_continuation(
913 &self,
914 thread_id: &str,
915 now: i64,
916 ) -> Result<Option<ThreadGoalRecord>> {
917 let conn = self.conn()?;
918 let changed = conn
919 .execute(
920 r#"
921 UPDATE thread_goals
922 SET continuation_count = continuation_count + 1,
923 updated_at = MAX(updated_at, ?2)
924 WHERE thread_id = ?1
925 "#,
926 params![thread_id, now],
927 )
928 .context("failed to record thread goal continuation")?;
929 if changed == 0 {
930 return Ok(None);
931 }
932 Self::read_thread_goal(&conn, thread_id)
933 }
934
935 /// Retrieve the persisted goal for a thread.
936 pub fn get_thread_goal(&self, thread_id: &str) -> Result<Option<ThreadGoalRecord>> {
937 let conn = self.conn()?;
938 Self::read_thread_goal(&conn, thread_id)
939 }
940
941 /// Read a goal on an already-held connection. The `record_*` mutators call
942 /// this instead of the public goal reader, which would re-lock the
943 /// connection mutex and self-deadlock.
944 fn read_thread_goal(conn: &Connection, thread_id: &str) -> Result<Option<ThreadGoalRecord>> {
945 let mut goal = Self::read_thread_goal_snapshot(conn, thread_id)?;
946 if let Some(goal) = goal.as_mut() {
947 goal.normalize_restored_stall_state();
948 }
949 Ok(goal)
950 }
951
952 /// Immutable migration/CAS snapshot keeps the original persisted status.
953 /// Restore normalization belongs to the reader/target, never source CAS.
954 fn read_thread_goal_snapshot(
955 conn: &Connection,
956 thread_id: &str,
957 ) -> Result<Option<ThreadGoalRecord>> {
958 conn.query_row(
959 r#"
960 SELECT thread_id, goal_id, objective, status, token_budget, tokens_used,
961 time_used_seconds, continuation_count, created_at, updated_at,
962 last_gap_fingerprint, repeated_gap_count, last_gap_pass, pause_reason
963 FROM thread_goals
964 WHERE thread_id = ?1
965 "#,
966 params![thread_id],
967 row_to_thread_goal,
968 )
969 .optional()
970 .context("failed to read thread goal")
971 }
972
973 /// Delete the persisted goal for a thread.
974 #[cfg(test)]
975 fn delete_thread_goal(&self, thread_id: &str) -> Result<bool> {
976 let conn = self.conn()?;
977 let changed = conn
978 .execute(
979 "DELETE FROM thread_goals WHERE thread_id = ?1",
980 params![thread_id],
981 )
982 .context("failed to delete thread goal")?;
983 Ok(changed > 0)
984 }
985
986 /// List all leaf messages in a thread.
987 ///
988 /// A leaf message is one that has no other message referencing it as a parent.
989 /// In a branching conversation tree, there may be multiple leaf messages.
990 pub fn list_leaf_messages(&self, thread_id: &str) -> Result<Vec<MessageRecord>> {
991 let conn = self.conn()?;
992 let mut stmt = conn
993 .prepare(
994 r#"
995 SELECT m1.id, m1.thread_id, m1.role, m1.content, m1.item_json, m1.created_at, m1.parent_entry_id
996 FROM messages m1
997 LEFT JOIN messages m2 ON m1.id = m2.parent_entry_id
998 WHERE m1.thread_id = ?1 AND m2.id IS NULL
999 "#,
1000 )
1001 .context("failed to prepare message listing query")?;
1002 let mut rows = stmt
1003 .query(params![thread_id])
1004 .with_context(|| format!("failed to list leaf messages for thread {thread_id}"))?;
1005 let mut out = Vec::new();
1006 while let Some(row) = rows.next().context("failed to iterate message rows")? {
1007 let item_json: Option<String> = row.get(4).context("failed to read item json")?;
1008 let item = item_json
1009 .as_deref()
1010 .map(serde_json::from_str)
1011 .transpose()
1012 .with_context(|| {
1013 format!("failed to parse message item json in thread {thread_id}")
1014 })?;
1015 out.push(MessageRecord {
1016 id: row.get(0).context("failed to read message id")?,
1017 thread_id: row.get(1).context("failed to read message thread id")?,
1018 role: row.get(2).context("failed to read message role")?,
1019 content: row.get(3).context("failed to read message content")?,
1020 item,
1021 created_at: row.get(5).context("failed to read message timestamp")?,
1022 parent_entry_id: row.get(6).context("failed to read parent entry id")?,
1023 });
1024 }
1025 Ok(out)
1026 }
1027
1028 /// Replace the dynamic tools for a thread.
1029 ///
1030 /// All existing dynamic tools for the thread are deleted and replaced with the
1031 /// provided list. The operation is performed within a transaction.
1032 pub fn persist_dynamic_tools(
1033 &self,
1034 thread_id: &str,
1035 tools: &[DynamicToolRecord],
1036 ) -> Result<()> {
1037 let mut conn = self.conn()?;
1038 let tx = conn
1039 .transaction()
1040 .context("failed to begin dynamic tools transaction")?;
1041 tx.execute(
1042 "DELETE FROM thread_dynamic_tools WHERE thread_id = ?1",
1043 params![thread_id],
1044 )
1045 .context("failed to clear dynamic tools")?;
1046 for tool in tools {
1047 tx.execute(
1048 "INSERT INTO thread_dynamic_tools(thread_id, position, name, description, input_schema) VALUES (?1, ?2, ?3, ?4, ?5)",
1049 params![
1050 thread_id,
1051 tool.position,
1052 tool.name,
1053 tool.description,
1054 tool.input_schema.to_string()
1055 ],
1056 )
1057 .with_context(|| format!("failed to persist dynamic tool {}", tool.name))?;
1058 }
1059 tx.commit().context("failed to commit dynamic tools")?;
1060 Ok(())
1061 }
1062
1063 /// Retrieve all dynamic tools registered for a thread, ordered by position.
1064 pub fn get_dynamic_tools(&self, thread_id: &str) -> Result<Vec<DynamicToolRecord>> {
1065 let conn = self.conn()?;
1066 let mut stmt = conn
1067 .prepare(
1068 "SELECT position, name, description, input_schema FROM thread_dynamic_tools WHERE thread_id = ?1 ORDER BY position ASC",
1069 )
1070 .context("failed to prepare get dynamic tools query")?;
1071 let mut rows = stmt
1072 .query(params![thread_id])
1073 .context("failed to query dynamic tools")?;
1074 let mut out = Vec::new();
1075 while let Some(row) = rows.next().context("failed to iterate dynamic tools")? {
1076 let input_schema_raw: String =
1077 row.get(3).context("failed to read tool input schema")?;
1078 let input_schema: Value =
1079 serde_json::from_str(&input_schema_raw).with_context(|| {
1080 format!("failed to parse input schema for dynamic tool in thread {thread_id}")
1081 })?;
1082 out.push(DynamicToolRecord {
1083 position: row.get(0).context("failed to read tool position")?,
1084 name: row.get(1).context("failed to read tool name")?,
1085 description: row.get(2).context("failed to read tool description")?,
1086 input_schema,
1087 });
1088 }
1089 Ok(out)
1090 }
1091
1092 /// Append a new message to a thread.
1093 ///
1094 /// The message is linked to the thread's current leaf as its parent, and the
1095 /// thread's `current_leaf_id` is updated to the new message. Returns the ID
1096 /// of the newly created message.
1097 #[cfg(test)]
1098 fn append_message(
1099 &self,
1100 thread_id: &str,
1101 role: &str,
1102 content: &str,
1103 item: Option<Value>,
1104 ) -> Result<i64> {
1105 let ids = self.append_messages(
1106 thread_id,
1107 &[NewMessage {
1108 role: role.to_string(),
1109 content: content.to_string(),
1110 item,
1111 }],
1112 )?;
1113 ids.first()
1114 .copied()
1115 .context("append message transaction returned no id")
1116 }
1117
1118 /// Append `messages` to a thread's current branch in one transaction.
1119 ///
1120 /// Each message is linked to the one before it (the first to the thread's
1121 /// current leaf), and the leaf ends on the last. All or nothing: a failure
1122 /// part-way leaves the thread exactly as it was, never a partial history.
1123 /// Returns the new message ids in order.
1124 #[cfg(test)]
1125 fn append_messages(&self, thread_id: &str, messages: &[NewMessage]) -> Result<Vec<i64>> {
1126 if messages.is_empty() {
1127 return Ok(Vec::new());
1128 }
1129 let encoded = messages
1130 .iter()
1131 .map(|message| {
1132 message
1133 .item
1134 .as_ref()
1135 .map(serde_json::to_string)
1136 .transpose()
1137 .context("failed to serialize message item payload")
1138 })
1139 .collect::<Result<Vec<_>>>()?;
1140 let mut conn = self.conn()?;
1141 let created_at = Utc::now().timestamp();
1142
1143 let tx = conn
1144 .transaction()
1145 .context("failed to begin append message transaction")?;
1146
1147 let mut leaf_id: Option<i64> = tx
1148 .query_row(
1149 "SELECT current_leaf_id FROM threads WHERE id = ?1",
1150 params![thread_id],
1151 |row| row.get(0),
1152 )
1153 .with_context(|| {
1154 format!("failed to query thread current leaf id for thread {thread_id}")
1155 })?;
1156
1157 let mut ids = Vec::with_capacity(messages.len());
1158 for (message, item_json) in messages.iter().zip(encoded) {
1159 let next_leaf_id: i64 = tx.query_row(
1160 r#"
1161 INSERT INTO messages(thread_id, role, content, item_json, created_at, parent_entry_id)
1162 SELECT ?1, ?2, ?3, ?4, ?5, ?6
1163 RETURNING id
1164 "#, params![thread_id, message.role, message.content, item_json, created_at, leaf_id], |row| row.get(0)
1165 ).with_context(|| format!("failed to append message for thread {thread_id}"))?;
1166 leaf_id = Some(next_leaf_id);
1167 ids.push(next_leaf_id);
1168 }
1169
1170 tx.execute(
1171 r#"
1172 UPDATE threads
1173 SET current_leaf_id = ?1
1174 WHERE id = ?2;
1175 "#,
1176 params![leaf_id, thread_id],
1177 )
1178 .with_context(|| {
1179 format!("failed to update thread current leaf id for thread {thread_id}")
1180 })?;
1181
1182 tx.commit()
1183 .context("failed to commit append message transaction")?;
1184
1185 Ok(ids)
1186 }
1187
1188 /// List messages in the current conversation branch, walking backwards from
1189 /// the thread's `current_leaf_id`.
1190 ///
1191 /// Messages are returned in chronological order (oldest first). The `limit`
1192 /// parameter caps how many ancestor messages are traversed; it defaults to 500.
1193 pub fn list_messages(
1194 &self,
1195 thread_id: &str,
1196 limit: Option<usize>,
1197 ) -> Result<Vec<MessageRecord>> {
1198 if limit == Some(0) {
1199 return Ok(Vec::new());
1200 }
1201 let conn = self.conn()?;
1202 let limit = i64::try_from(limit.unwrap_or(500)).unwrap_or(i64::MAX);
1203 let mut stmt = conn
1204 .prepare(
1205 r#"
1206 WITH RECURSIVE
1207 leaf_id AS (
1208 SELECT current_leaf_id FROM threads WHERE id = ?1
1209 ),
1210 ancestors AS (
1211 SELECT id, thread_id, role, content, item_json, created_at, parent_entry_id, 0 AS depth
1212 FROM messages
1213 WHERE id = (SELECT current_leaf_id FROM leaf_id)
1214
1215 UNION ALL
1216
1217 SELECT m.id, m.thread_id, m.role, m.content, m.item_json, m.created_at, m.parent_entry_id, a.depth + 1
1218 FROM messages m
1219 JOIN ancestors a ON m.id = a.parent_entry_id
1220 WHERE a.depth < ?2
1221 )
1222 SELECT id, thread_id, role, content, item_json, created_at, parent_entry_id FROM ancestors
1223 ORDER BY depth DESC
1224 "#
1225 )
1226 .context("failed to prepare message listing query")?;
1227 let mut rows = stmt
1228 .query(params![thread_id, limit - 1])
1229 .with_context(|| format!("failed to list messages for thread {thread_id}"))?;
1230 let mut out = Vec::new();
1231 while let Some(row) = rows.next().context("failed to iterate message rows")? {
1232 let item_json: Option<String> = row.get(4).context("failed to read item json")?;
1233 let item = item_json
1234 .as_deref()
1235 .map(serde_json::from_str)
1236 .transpose()
1237 .with_context(|| {
1238 format!("failed to parse message item json in thread {thread_id}")
1239 })?;
1240 out.push(MessageRecord {
1241 id: row.get(0).context("failed to read message id")?,
1242 thread_id: row.get(1).context("failed to read message thread id")?,
1243 role: row.get(2).context("failed to read message role")?,
1244 content: row.get(3).context("failed to read message content")?,
1245 item,
1246 created_at: row.get(5).context("failed to read message timestamp")?,
1247 parent_entry_id: row.get(6).context("failed to read parent entry id")?,
1248 });
1249 }
1250 Ok(out)
1251 }
1252
1253 /// Delete all messages belonging to a thread and reset its `current_leaf_id`.
1254 ///
1255 /// Returns the number of messages deleted.
1256 #[cfg(test)]
1257 fn clear_messages(&self, thread_id: &str) -> Result<usize> {
1258 let mut conn = self.conn()?;
1259 let tx = conn
1260 .transaction()
1261 .context("failed to begin clear messages transaction")?;
1262
1263 tx.execute(
1264 r#"
1265 UPDATE threads
1266 SET current_leaf_id = NULL
1267 WHERE id = ?1;
1268 "#,
1269 params![thread_id],
1270 )
1271 .with_context(|| format!("failed to clear messages for thread {thread_id}"))?;
1272 let result = tx
1273 .execute(
1274 r#"
1275 DELETE FROM messages WHERE thread_id = ?1
1276 "#,
1277 params![thread_id],
1278 )
1279 .with_context(|| format!("failed to clear messages for thread {thread_id}"))?;
1280 tx.commit()
1281 .context("failed to commit clear messages transaction")?;
1282
1283 Ok(result)
1284 }
1285
1286 /// Save (or update) a named checkpoint for a thread.
1287 ///
1288 /// If a checkpoint with the same `thread_id` and `checkpoint_id` already exists,
1289 /// its state and timestamp are overwritten.
1290 #[cfg(test)]
1291 fn save_checkpoint(&self, thread_id: &str, checkpoint_id: &str, state: &Value) -> Result<()> {
1292 let conn = self.conn()?;
1293 let state_json =
1294 serde_json::to_string(state).context("failed to encode checkpoint state")?;
1295 conn.execute(
1296 r#"
1297 INSERT INTO checkpoints(thread_id, checkpoint_id, state_json, created_at)
1298 VALUES (?1, ?2, ?3, ?4)
1299 ON CONFLICT(thread_id, checkpoint_id) DO UPDATE SET
1300 state_json = excluded.state_json,
1301 created_at = excluded.created_at
1302 "#,
1303 params![thread_id, checkpoint_id, state_json, Utc::now().timestamp()],
1304 )
1305 .with_context(|| {
1306 format!("failed to save checkpoint {checkpoint_id} for thread {thread_id}")
1307 })?;
1308 Ok(())
1309 }
1310
1311 /// Load a checkpoint for a thread.
1312 ///
1313 /// If `checkpoint_id` is provided, loads that specific checkpoint. Otherwise,
1314 /// loads the most recently created checkpoint for the thread. Returns `None`
1315 /// if no matching checkpoint exists.
1316 pub fn load_checkpoint(
1317 &self,
1318 thread_id: &str,
1319 checkpoint_id: Option<&str>,
1320 ) -> Result<Option<CheckpointRecord>> {
1321 let conn = self.conn()?;
1322 if let Some(checkpoint_id) = checkpoint_id {
1323 let row = conn
1324 .query_row(
1325 "SELECT thread_id, checkpoint_id, state_json, created_at FROM checkpoints WHERE thread_id = ?1 AND checkpoint_id = ?2",
1326 params![thread_id, checkpoint_id],
1327 |row| {
1328 Ok((
1329 row.get::<_, String>(0)?,
1330 row.get::<_, String>(1)?,
1331 row.get::<_, String>(2)?,
1332 row.get::<_, i64>(3)?,
1333 ))
1334 },
1335 )
1336 .optional()
1337 .with_context(|| {
1338 format!("failed to load checkpoint {checkpoint_id} for thread {thread_id}")
1339 })?;
1340 if let Some((thread_id, checkpoint_id, state_json, created_at)) = row {
1341 let state = parse_checkpoint_state(&state_json)?;
1342 return Ok(Some(CheckpointRecord {
1343 thread_id,
1344 checkpoint_id,
1345 state,
1346 created_at,
1347 }));
1348 }
1349 return Ok(None);
1350 }
1351
1352 let row = conn
1353 .query_row(
1354 "SELECT thread_id, checkpoint_id, state_json, created_at FROM checkpoints WHERE thread_id = ?1 ORDER BY created_at DESC LIMIT 1",
1355 params![thread_id],
1356 |row| {
1357 Ok((
1358 row.get::<_, String>(0)?,
1359 row.get::<_, String>(1)?,
1360 row.get::<_, String>(2)?,
1361 row.get::<_, i64>(3)?,
1362 ))
1363 },
1364 )
1365 .optional()
1366 .with_context(|| format!("failed to load latest checkpoint for thread {thread_id}"))?;
1367 if let Some((thread_id, checkpoint_id, state_json, created_at)) = row {
1368 let state = parse_checkpoint_state(&state_json)?;
1369 return Ok(Some(CheckpointRecord {
1370 thread_id,
1371 checkpoint_id,
1372 state,
1373 created_at,
1374 }));
1375 }
1376 Ok(None)
1377 }
1378
1379 /// List checkpoints for a thread, ordered by creation time (newest first).
1380 ///
1381 /// The `limit` parameter caps the number of results and defaults to 100.
1382 pub fn list_checkpoints(
1383 &self,
1384 thread_id: &str,
1385 limit: Option<usize>,
1386 ) -> Result<Vec<CheckpointRecord>> {
1387 let conn = self.conn()?;
1388 let limit = i64::try_from(limit.unwrap_or(100)).unwrap_or(i64::MAX);
1389 let mut stmt = conn
1390 .prepare(
1391 "SELECT thread_id, checkpoint_id, state_json, created_at FROM checkpoints WHERE thread_id = ?1 ORDER BY created_at DESC LIMIT +?2",
1392 )
1393 .context("failed to prepare checkpoint list query")?;
1394 let mut rows = stmt
1395 .query(params![thread_id, limit])
1396 .with_context(|| format!("failed to list checkpoints for thread {thread_id}"))?;
1397
1398 let mut out = Vec::new();
1399 while let Some(row) = rows.next().context("failed to iterate checkpoint rows")? {
1400 let state_json: String = row.get(2).context("failed to read checkpoint state json")?;
1401 let state = parse_checkpoint_state(&state_json)?;
1402 out.push(CheckpointRecord {
1403 thread_id: row.get(0).context("failed to read checkpoint thread id")?,
1404 checkpoint_id: row.get(1).context("failed to read checkpoint id")?,
1405 state,
1406 created_at: row.get(3).context("failed to read checkpoint timestamp")?,
1407 });
1408 }
1409 Ok(out)
1410 }
1411
1412 /// Append an entry to the JSONL session index file.
1413 ///
1414 /// The session index is an append-only log that maps thread IDs to their names,
1415 /// update timestamps, and rollout paths. It is used for fast name-based lookups
1416 /// without opening the SQLite database.
1417 pub fn append_thread_name(
1418 &self,
1419 thread_id: &str,
1420 thread_name: Option<String>,
1421 updated_at: i64,
1422 rollout_path: Option<PathBuf>,
1423 ) -> Result<()> {
1424 // Hold the index lock for the entire append + compaction so a concurrent
1425 // `StateStore` clone cannot rename the index while we are appending.
1426 let _guard = SESSION_INDEX_LOCK
1427 .lock()
1428 .unwrap_or_else(std::sync::PoisonError::into_inner);
1429 if let Some(parent) = self.session_index_path.parent()
1430 && !parent.as_os_str().is_empty()
1431 {
1432 fs::create_dir_all(parent).with_context(|| {
1433 format!(
1434 "failed to create session index directory {}",
1435 parent.display()
1436 )
1437 })?;
1438 }
1439 let entry = SessionIndexEntry {
1440 thread_id: thread_id.to_string(),
1441 thread_name,
1442 updated_at,
1443 rollout_path,
1444 };
1445 let encoded =
1446 serde_json::to_string(&entry).context("failed to serialize session index entry")?;
1447 // Append and compaction share one lock. Compaction rewrites the file
1448 // from a snapshot and renames over it, so an append landing between
1449 // that snapshot and the rename would be discarded — silently, since
1450 // the append already returned success to its caller.
1451 self.with_session_index_lock(|| {
1452 let mut file = OpenOptions::new()
1453 .create(true)
1454 .read(true)
1455 .append(true)
1456 .open(&self.session_index_path)
1457 .with_context(|| {
1458 format!(
1459 "failed to open session index {}",
1460 self.session_index_path.display()
1461 )
1462 })?;
1463 let mut last = *b"\n";
1464 if file.metadata()?.len() > 0 {
1465 file.seek(SeekFrom::End(-1))?;
1466 file.read_exact(&mut last)?;
1467 }
1468 let separator = if last[0] == b'\n' { "" } else { "\n" };
1469 writeln!(file, "{separator}{encoded}")
1470 .context("failed to append session index entry")?;
1471 // Durability: without this a crash mid-write can leave a torn
1472 // final line. Reads tolerate one (see `session_index_map`), but
1473 // not losing the entry beats recovering from having lost it.
1474 file.sync_data()
1475 .context("failed to flush session index entry")?;
1476 drop(file);
1477 self.compact_session_index_locked()
1478 })
1479 }
1480
1481 /// Run `operation` holding the exclusive session-index lock.
1482 ///
1483 /// The lock is an adjacent `.lock` file rather than the index itself, so
1484 /// compaction's rename cannot pull the lock out from under a waiter. This
1485 /// mirrors the discipline `codewhale-config` uses for `config.toml`.
1486 fn with_session_index_lock<T>(&self, operation: impl FnOnce() -> Result<T>) -> Result<T> {
1487 if let Some(parent) = self.session_index_path.parent()
1488 && !parent.as_os_str().is_empty()
1489 {
1490 fs::create_dir_all(parent).with_context(|| {
1491 format!(
1492 "failed to create session index directory {}",
1493 parent.display()
1494 )
1495 })?;
1496 }
1497 let lock_path = self.session_index_path.with_extension("jsonl.lock");
1498 let lock_file = OpenOptions::new()
1499 .create(true)
1500 .read(true)
1501 .write(true)
1502 // The file is only a lock handle; its contents are never read and
1503 // truncating it would race other holders for no benefit.
1504 .truncate(false)
1505 .open(&lock_path)
1506 .with_context(|| {
1507 format!("failed to open session index lock {}", lock_path.display())
1508 })?;
1509 #[cfg(unix)]
1510 {
1511 use std::os::unix::fs::PermissionsExt as _;
1512 lock_file
1513 .set_permissions(fs::Permissions::from_mode(0o600))
1514 .with_context(|| {
1515 format!(
1516 "failed to secure session index lock {}",
1517 lock_path.display()
1518 )
1519 })?;
1520 }
1521 let mut lock = fd_lock::RwLock::new(lock_file);
1522 let _guard = lock
1523 .write()
1524 .with_context(|| format!("failed to lock session index {}", lock_path.display()))?;
1525 operation()
1526 }
1527
1528 /// Find the display name for a thread by its ID, using the session index.
1529 ///
1530 /// Returns `None` if the thread is not in the index or has no name.
1531 pub fn find_thread_name_by_id(&self, thread_id: &str) -> Result<Option<String>> {
1532 let map = self.session_index_map()?;
1533 Ok(map
1534 .get(thread_id)
1535 .and_then(|entry| entry.thread_name.clone()))
1536 }
1537
1538 /// Find the rollout path for a thread by its display name (case-insensitive).
1539 ///
1540 /// If multiple threads share the same name, the most recently updated one is returned.
1541 /// Returns `None` if no matching thread is found.
1542 pub fn find_thread_path_by_name_str(&self, name: &str) -> Result<Option<PathBuf>> {
1543 let map = self.session_index_map()?;
1544 let matched = map
1545 .values()
1546 .filter(|entry| {
1547 entry
1548 .thread_name
1549 .as_deref()
1550 .is_some_and(|n| n.eq_ignore_ascii_case(name))
1551 })
1552 .max_by_key(|entry| entry.updated_at);
1553 Ok(matched.and_then(|entry| entry.rollout_path.clone()))
1554 }
1555
1556 /// Compact the session index. The caller must already hold the lock from
1557 /// [`Self::with_session_index_lock`]: this reads a snapshot and renames a
1558 /// rewritten file over the live one, and an append interleaved between
1559 /// those two steps is lost.
1560 fn compact_session_index_locked(&self) -> Result<()> {
1561 if !self.session_index_path.exists() {
1562 return Ok(());
1563 }
1564 let line_count = BufReader::new(
1565 OpenOptions::new()
1566 .read(true)
1567 .open(&self.session_index_path)
1568 .with_context(|| {
1569 format!(
1570 "failed to read session index {}",
1571 self.session_index_path.display()
1572 )
1573 })?,
1574 )
1575 .lines()
1576 .try_fold(0usize, |count, line| -> Result<usize> {
1577 let line = line.context("failed to read session index line during compaction")?;
1578 Ok(count + usize::from(!line.trim().is_empty()))
1579 })?;
1580 if line_count <= session_index_compact_line_threshold() {
1581 return Ok(());
1582 }
1583
1584 let latest = self.session_index_map()?;
1585 self.rewrite_session_index_locked(&latest)
1586 }
1587
1588 /// Replace the session index with exactly `latest`, one line per thread.
1589 /// The caller holds the lock from [`Self::with_session_index_lock`].
1590 fn rewrite_session_index_locked(
1591 &self,
1592 latest: &HashMap<String, SessionIndexEntry>,
1593 ) -> Result<()> {
1594 let compact_path = self.session_index_path.with_extension("jsonl.compact");
1595 let write_result = (|| -> Result<()> {
1596 let mut file = OpenOptions::new()
1597 .create(true)
1598 .write(true)
1599 .truncate(true)
1600 .open(&compact_path)
1601 .with_context(|| {
1602 format!(
1603 "failed to open compact session index {}",
1604 compact_path.display()
1605 )
1606 })?;
1607 #[cfg(unix)]
1608 {
1609 use std::os::unix::fs::PermissionsExt as _;
1610 file.set_permissions(fs::Permissions::from_mode(0o600))
1611 .with_context(|| {
1612 format!(
1613 "failed to secure compact session index {}",
1614 compact_path.display()
1615 )
1616 })?;
1617 }
1618 for entry in latest.values() {
1619 let encoded = serde_json::to_string(entry)
1620 .context("failed to serialize compact session index entry")?;
1621 writeln!(file, "{encoded}")
1622 .context("failed to write compact session index entry")?;
1623 }
1624 file.sync_data()
1625 .context("failed to flush compact session index")?;
1626 Ok(())
1627 })();
1628 if let Err(err) = write_result {
1629 let _ = fs::remove_file(&compact_path);
1630 return Err(err);
1631 }
1632 // The snapshot is written but the live file is still the old one:
1633 // this is the window an unsynchronized appender would write into and
1634 // lose. Tests widen it deliberately to prove the lock closes it.
1635 #[cfg(test)]
1636 tests::compaction_midpoint(&self.session_index_path);
1637 fs::rename(&compact_path, &self.session_index_path).with_context(|| {
1638 format!(
1639 "failed to replace session index {}",
1640 self.session_index_path.display()
1641 )
1642 })?;
1643 Ok(())
1644 }
1645
1646 #[cfg(test)]
1647 fn session_index_line_count(&self) -> Result<usize> {
1648 if !self.session_index_path.exists() {
1649 return Ok(0);
1650 }
1651 Ok(BufReader::new(
1652 OpenOptions::new()
1653 .read(true)
1654 .open(&self.session_index_path)
1655 .with_context(|| {
1656 format!(
1657 "failed to read session index {}",
1658 self.session_index_path.display()
1659 )
1660 })?,
1661 )
1662 .lines()
1663 .filter(|line| {
1664 line.as_ref()
1665 .map(|value| !value.trim().is_empty())
1666 .unwrap_or(false)
1667 })
1668 .count())
1669 }
1670
1671 fn session_index_map(&self) -> Result<HashMap<String, SessionIndexEntry>> {
1672 if !self.session_index_path.exists() {
1673 return Ok(HashMap::new());
1674 }
1675 let file = OpenOptions::new()
1676 .read(true)
1677 .open(&self.session_index_path)
1678 .with_context(|| {
1679 format!(
1680 "failed to read session index {}",
1681 self.session_index_path.display()
1682 )
1683 })?;
1684 let reader = BufReader::new(file);
1685 let mut latest = HashMap::<String, SessionIndexEntry>::new();
1686 for line in reader.lines() {
1687 let line = line.context("failed to read session index line")?;
1688 if line.trim().is_empty() {
1689 continue;
1690 }
1691 // Skip a line we can't parse instead of failing the whole read.
1692 // An append that was interrupted mid-write leaves a torn final
1693 // line; aborting here broke every thread-name lookup, and because
1694 // compaction reads through this same function, the index could
1695 // never repair itself either — the file stayed broken until
1696 // someone deleted it by hand.
1697 match serde_json::from_str::<SessionIndexEntry>(&line) {
1698 Ok(parsed) => {
1699 latest.insert(parsed.thread_id.clone(), parsed);
1700 }
1701 Err(err) => {
1702 tracing::warn!(
1703 "skipping unparseable session index entry in {}: {err}",
1704 self.session_index_path.display()
1705 );
1706 }
1707 }
1708 }
1709 Ok(latest)
1710 }
1711 }
1712
1713 /// Resolve the default SQLite state path without opening or creating it.
1714 ///
1715 /// An explicit `CODEWHALE_HOME` always yields `<override>/state.db` and blocks
1716 /// ambient legacy fallback. Without an override, an existing legacy database
1717 /// remains readable until it is migrated.
1718 #[must_use]
1719 pub fn default_state_db_path() -> PathBuf {
1720 // $CODEWHALE_HOME is a hard override of the base data directory
1721 // (docs/CONFIGURATION.md): when set, the state DB lives under it and we do
1722 // NOT fall back to the legacy ~/.deepseek path — silent fallback would
1723 // defeat the isolation the override promises (CI, containers, multi-project,
1724 // test harnesses). Legacy ~/.deepseek migration only applies to the default
1725 // home location.
1726 if let Some(overridden) = codewhale_home_override().ok().flatten() {
1727 return overridden.join("state.db");
1728 }
1729 let home = codewhale_paths::user_home().unwrap_or_else(|| PathBuf::from("."));
1730 // Prefer the CodeWhale directory, falling back to legacy DeepSeek path
1731 // so existing installs don't lose their session history.
1732 let primary = home.join(CODEWHALE_APP_DIR).join("state.db");
1733 if primary.exists() || !home.join(LEGACY_APP_DIR).join("state.db").exists() {
1734 primary
1735 } else {
1736 home.join(LEGACY_APP_DIR).join("state.db")
1737 }
1738 }
1739
1740 fn write_thread_metadata_on(conn: &Connection, thread: &ThreadMetadata) -> Result<()> {
1741 conn.execute(
1742 r#"
1743 INSERT INTO threads (
1744 id, rollout_path, preview, ephemeral, model_provider, created_at, updated_at, status, path, cwd,
1745 cli_version, source, title, sandbox_policy, approval_mode, archived, archived_at,
1746 git_sha, git_branch, git_origin_url, memory_mode
1747 ) VALUES (
1748 ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10,
1749 ?11, ?12, ?13, ?14, ?15, ?16, ?17,
1750 ?18, ?19, ?20, ?21
1751 )
1752 ON CONFLICT(id) DO UPDATE SET
1753 rollout_path=excluded.rollout_path,
1754 preview=excluded.preview,
1755 ephemeral=excluded.ephemeral,
1756 model_provider=excluded.model_provider,
1757 created_at=excluded.created_at,
1758 updated_at=excluded.updated_at,
1759 status=excluded.status,
1760 path=excluded.path,
1761 cwd=excluded.cwd,
1762 cli_version=excluded.cli_version,
1763 source=excluded.source,
1764 title=excluded.title,
1765 sandbox_policy=excluded.sandbox_policy,
1766 approval_mode=excluded.approval_mode,
1767 archived=excluded.archived,
1768 archived_at=excluded.archived_at,
1769 git_sha=excluded.git_sha,
1770 git_branch=excluded.git_branch,
1771 git_origin_url=excluded.git_origin_url,
1772 memory_mode=excluded.memory_mode
1773 "#,
1774 params![
1775 thread.id,
1776 path_to_opt_string(thread.rollout_path.as_deref()),
1777 thread.preview,
1778 bool_to_i64(thread.ephemeral),
1779 thread.model_provider,
1780 thread.created_at,
1781 thread.updated_at,
1782 thread_status_to_str(&thread.status),
1783 path_to_opt_string(thread.path.as_deref()),
1784 thread.cwd.display().to_string(),
1785 thread.cli_version,
1786 session_source_to_str(&thread.source),
1787 thread.name,
1788 thread.sandbox_policy,
1789 thread.approval_mode,
1790 bool_to_i64(thread.archived),
1791 thread.archived_at,
1792 thread.git_sha,
1793 thread.git_branch,
1794 thread.git_origin_url,
1795 thread.memory_mode,
1796 ],
1797 )
1798 .context("failed to upsert thread metadata")?;
1799 Ok(())
1800 }
1801
1802 fn write_thread_goal_on(conn: &Connection, goal: &ThreadGoalRecord) -> Result<()> {
1803 codewhale_protocol::validate_goal_stall_state(
1804 goal.last_gap_fingerprint.as_deref(),
1805 goal.repeated_gap_count,
1806 goal.last_gap_pass,
1807 u32::try_from(goal.continuation_count.max(0)).unwrap_or(u32::MAX),
1808 )
1809 .map_err(anyhow::Error::msg)?;
1810 let pause_reason = goal
1811 .pause_reason
1812 .map(|reason| serde_json::to_string(&reason))
1813 .transpose()?;
1814 let exists: Option<i64> = conn
1815 .query_row(
1816 "SELECT 1 FROM threads WHERE id = ?1",
1817 params![goal.thread_id],
1818 |row| row.get(0),
1819 )
1820 .optional()
1821 .context("failed to verify thread before saving goal")?;
1822 if exists.is_none() {
1823 anyhow::bail!("thread {} not found", goal.thread_id);
1824 }
1825
1826 conn.execute(
1827 r#"
1828 INSERT INTO thread_goals (
1829 thread_id, goal_id, objective, status, token_budget, tokens_used,
1830 time_used_seconds, continuation_count, created_at, updated_at,
1831 last_gap_fingerprint, repeated_gap_count, last_gap_pass, pause_reason
1832 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
1833 ON CONFLICT(thread_id) DO UPDATE SET
1834 goal_id=excluded.goal_id,
1835 objective=excluded.objective,
1836 status=excluded.status,
1837 token_budget=excluded.token_budget,
1838 tokens_used=excluded.tokens_used,
1839 time_used_seconds=excluded.time_used_seconds,
1840 continuation_count=excluded.continuation_count,
1841 created_at=excluded.created_at,
1842 updated_at=excluded.updated_at,
1843 last_gap_fingerprint=excluded.last_gap_fingerprint,
1844 repeated_gap_count=excluded.repeated_gap_count,
1845 last_gap_pass=excluded.last_gap_pass,
1846 pause_reason=excluded.pause_reason
1847 "#,
1848 params![
1849 goal.thread_id,
1850 goal.goal_id,
1851 goal.objective,
1852 thread_goal_status_to_str(&goal.status),
1853 goal.token_budget,
1854 goal.tokens_used,
1855 goal.time_used_seconds,
1856 goal.continuation_count,
1857 goal.created_at,
1858 goal.updated_at,
1859 goal.last_gap_fingerprint,
1860 goal.repeated_gap_count,
1861 goal.last_gap_pass,
1862 pause_reason,
1863 ],
1864 )
1865 .context("failed to upsert thread goal")?;
1866 Ok(())
1867 }
1868
1869 fn bool_to_i64(value: bool) -> i64 {
1870 if value { 1 } else { 0 }
1871 }
1872
1873 /// Whether `table` currently has a column named `column`.
1874 ///
1875 /// Used to guard `ALTER TABLE ... ADD COLUMN` migrations so they are
1876 /// idempotent. Both identifiers are compile-time literals at every call
1877 /// site, never user input. A missing table reports `false`, matching the
1878 /// fresh-database case where the migration must still run.
1879 fn column_exists(conn: &Connection, table: &str, column: &str) -> Result<bool> {
1880 let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
1881 let names = stmt.query_map([], |row| row.get::<_, String>(1))?;
1882 for name in names {
1883 if name? == column {
1884 return Ok(true);
1885 }
1886 }
1887 Ok(false)
1888 }
1889
1890 fn i64_to_bool(value: i64) -> bool {
1891 value != 0
1892 }
1893
1894 fn thread_status_to_str(status: &ThreadStatus) -> &'static str {
1895 match status {
1896 ThreadStatus::Running => "running",
1897 ThreadStatus::Idle => "idle",
1898 ThreadStatus::Completed => "completed",
1899 ThreadStatus::Failed => "failed",
1900 ThreadStatus::Paused => "paused",
1901 ThreadStatus::Archived => "archived",
1902 }
1903 }
1904
1905 fn thread_status_from_str(value: &str) -> ThreadStatus {
1906 match value {
1907 "running" => ThreadStatus::Running,
1908 "idle" => ThreadStatus::Idle,
1909 "completed" => ThreadStatus::Completed,
1910 "failed" => ThreadStatus::Failed,
1911 "paused" => ThreadStatus::Paused,
1912 "archived" => ThreadStatus::Archived,
1913 _ => ThreadStatus::Idle,
1914 }
1915 }
1916
1917 fn session_source_to_str(source: &SessionSource) -> &'static str {
1918 match source {
1919 SessionSource::Interactive => "interactive",
1920 SessionSource::Resume => "resume",
1921 SessionSource::Fork => "fork",
1922 SessionSource::Api => "api",
1923 SessionSource::Unknown => "unknown",
1924 }
1925 }
1926
1927 fn session_source_from_str(value: &str) -> SessionSource {
1928 match value {
1929 "interactive" => SessionSource::Interactive,
1930 "resume" => SessionSource::Resume,
1931 "fork" => SessionSource::Fork,
1932 "api" => SessionSource::Api,
1933 _ => SessionSource::Unknown,
1934 }
1935 }
1936
1937 fn path_to_opt_string(path: Option<&Path>) -> Option<String> {
1938 path.map(|p| p.display().to_string())
1939 }
1940
1941 fn parse_checkpoint_state(state_json: &str) -> Result<Value> {
1942 serde_json::from_str(state_json).context("failed to parse checkpoint state json")
1943 }
1944
1945 fn thread_goal_status_to_str(status: &ThreadGoalStatus) -> &'static str {
1946 match status {
1947 ThreadGoalStatus::Active => "active",
1948 ThreadGoalStatus::Paused => "paused",
1949 ThreadGoalStatus::Blocked => "blocked",
1950 ThreadGoalStatus::UsageLimited => "usage_limited",
1951 ThreadGoalStatus::BudgetLimited => "budget_limited",
1952 ThreadGoalStatus::Complete => "complete",
1953 }
1954 }
1955
1956 fn thread_goal_status_from_str(value: &str) -> ThreadGoalStatus {
1957 match value {
1958 "active" => ThreadGoalStatus::Active,
1959 "paused" => ThreadGoalStatus::Paused,
1960 "blocked" => ThreadGoalStatus::Blocked,
1961 "usage_limited" => ThreadGoalStatus::UsageLimited,
1962 "budget_limited" => ThreadGoalStatus::BudgetLimited,
1963 "complete" => ThreadGoalStatus::Complete,
1964 // Fail closed: an unknown or corrupted persisted value must never
1965 // resurrect a self-driving goal. The user can inspect and explicitly
1966 // resume a paused goal after repairing or replacing the record.
1967 _ => ThreadGoalStatus::Paused,
1968 }
1969 }
1970
1971 fn row_to_thread(row: &rusqlite::Row<'_>) -> rusqlite::Result<ThreadMetadata> {
1972 let status_raw: String = row.get(7)?;
1973 let source_raw: String = row.get(11)?;
1974 let rollout_path: Option<String> = row.get(1)?;
1975 let path: Option<String> = row.get(8)?;
1976 Ok(ThreadMetadata {
1977 id: row.get(0)?,
1978 rollout_path: rollout_path.map(PathBuf::from),
1979 preview: row.get(2)?,
1980 ephemeral: i64_to_bool(row.get(3)?),
1981 model_provider: row.get(4)?,
1982 created_at: row.get(5)?,
1983 updated_at: row.get(6)?,
1984 status: thread_status_from_str(&status_raw),
1985 path: path.map(PathBuf::from),
1986 cwd: PathBuf::from(row.get::<_, String>(9)?),
1987 cli_version: row.get(10)?,
1988 source: session_source_from_str(&source_raw),
1989 name: row.get(12)?,
1990 sandbox_policy: row.get(13)?,
1991 approval_mode: row.get(14)?,
1992 archived: i64_to_bool(row.get(15)?),
1993 archived_at: row.get(16)?,
1994 git_sha: row.get(17)?,
1995 git_branch: row.get(18)?,
1996 git_origin_url: row.get(19)?,
1997 memory_mode: row.get(20)?,
1998 current_leaf_id: row.get(21)?,
1999 })
2000 }
2001
2002 fn row_to_thread_goal(row: &rusqlite::Row<'_>) -> rusqlite::Result<ThreadGoalRecord> {
2003 let status_raw: String = row.get(3)?;
2004 let pause_reason: Option<String> = row.get(13)?;
2005 let goal = ThreadGoalRecord {
2006 thread_id: row.get(0)?,
2007 goal_id: row.get(1)?,
2008 objective: row.get(2)?,
2009 status: thread_goal_status_from_str(&status_raw),
2010 token_budget: row.get(4)?,
2011 tokens_used: row.get(5)?,
2012 time_used_seconds: row.get(6)?,
2013 continuation_count: row.get(7)?,
2014 created_at: row.get(8)?,
2015 updated_at: row.get(9)?,
2016 last_gap_fingerprint: row.get(10)?,
2017 repeated_gap_count: row.get(11)?,
2018 last_gap_pass: row.get(12)?,
2019 pause_reason: pause_reason
2020 .map(|value| serde_json::from_str(&value))
2021 .transpose()
2022 .map_err(|error| {
2023 rusqlite::Error::FromSqlConversionFailure(
2024 13,
2025 rusqlite::types::Type::Text,
2026 Box::new(error),
2027 )
2028 })?,
2029 };
2030 codewhale_protocol::validate_goal_stall_state(
2031 goal.last_gap_fingerprint.as_deref(),
2032 goal.repeated_gap_count,
2033 goal.last_gap_pass,
2034 u32::try_from(goal.continuation_count.max(0)).unwrap_or(u32::MAX),
2035 )
2036 .map_err(|error| {
2037 rusqlite::Error::FromSqlConversionFailure(
2038 10,
2039 rusqlite::types::Type::Text,
2040 Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, error)),
2041 )
2042 })?;
2043 Ok(goal)
2044 }
2045
2046 impl ThreadGoalRecord {
2047 /// Same restore rule as `codewhale_protocol::ThreadGoal`: an Active
2048 /// record with an exhausted stall window is corrupt and reads as paused.
2049 fn normalize_restored_stall_state(&mut self) {
2050 if matches!(self.status, ThreadGoalStatus::Active)
2051 && self.repeated_gap_count >= codewhale_protocol::MAX_REPEATED_GAP_COUNT
2052 {
2053 self.status = ThreadGoalStatus::Paused;
2054 self.pause_reason = Some(codewhale_protocol::GoalPauseReason::NoProgress);
2055 }
2056 }
2057 }
2058
2059 #[cfg(test)]
2060 mod tests {
2061 use super::*;
2062 use serde_json::json;
2063 use std::sync::{Arc, Barrier, Mutex, mpsc};
2064 use std::thread;
2065 use std::time::{Duration, SystemTime, UNIX_EPOCH};
2066
2067 fn temp_state_dir(name: &str) -> PathBuf {
2068 let suffix = SystemTime::now()
2069 .duration_since(UNIX_EPOCH)
2070 .expect("system time")
2071 .as_nanos();
2072 let dir = std::env::temp_dir().join(format!(
2073 "codewhale-state-{name}-{}-{suffix}",
2074 std::process::id()
2075 ));
2076 fs::create_dir_all(&dir).expect("create temp state dir");
2077 dir
2078 }
2079
2080 fn temp_state_store(name: &str) -> StateStore {
2081 let dir = temp_state_dir(name);
2082 StateStore::open(Some(dir.join("state.db"))).expect("open state store")
2083 }
2084
2085 fn test_thread(id: &str) -> ThreadMetadata {
2086 ThreadMetadata {
2087 id: id.to_string(),
2088 rollout_path: None,
2089 preview: "test thread".to_string(),
2090 ephemeral: false,
2091 model_provider: "deepseek".to_string(),
2092 created_at: 10,
2093 updated_at: 10,
2094 status: ThreadStatus::Running,
2095 path: None,
2096 cwd: PathBuf::from("/tmp/codewhale"),
2097 cli_version: "0.0.0-test".to_string(),
2098 source: SessionSource::Interactive,
2099 name: None,
2100 sandbox_policy: None,
2101 approval_mode: None,
2102 archived: false,
2103 archived_at: None,
2104 git_sha: None,
2105 git_branch: None,
2106 git_origin_url: None,
2107 memory_mode: None,
2108 current_leaf_id: None,
2109 }
2110 }
2111
2112 fn test_goal(thread_id: &str, objective: &str) -> ThreadGoalRecord {
2113 ThreadGoalRecord {
2114 thread_id: thread_id.to_string(),
2115 goal_id: "goal-1".to_string(),
2116 objective: objective.to_string(),
2117 status: ThreadGoalStatus::Active,
2118 token_budget: Some(123),
2119 tokens_used: 7,
2120 time_used_seconds: 11,
2121 continuation_count: 0,
2122 last_gap_fingerprint: None,
2123 repeated_gap_count: 0,
2124 last_gap_pass: None,
2125 pause_reason: None,
2126 created_at: 100,
2127 updated_at: 101,
2128 }
2129 }
2130
2131 #[test]
2132 fn unknown_persisted_goal_status_fails_closed() {
2133 assert_eq!(
2134 thread_goal_status_from_str("future_or_corrupt_status"),
2135 ThreadGoalStatus::Paused
2136 );
2137 }
2138
2139 #[test]
2140 fn thread_goal_crud_round_trips_and_replaces() {
2141 let store = temp_state_store("thread-goal-crud");
2142 store
2143 .upsert_thread(&test_thread("thread-1"))
2144 .expect("upsert thread");
2145
2146 let goal = test_goal("thread-1", "Ship v0.8.59");
2147 store.upsert_thread_goal(&goal).expect("upsert goal");
2148 assert_eq!(
2149 store
2150 .get_thread_goal("thread-1")
2151 .expect("read goal")
2152 .as_ref(),
2153 Some(&goal)
2154 );
2155
2156 let mut replacement = test_goal("thread-1", "Ship v0.8.59 safely");
2157 replacement.goal_id = "goal-2".to_string();
2158 replacement.status = ThreadGoalStatus::BudgetLimited;
2159 replacement.token_budget = None;
2160 replacement.updated_at = 202;
2161 store
2162 .upsert_thread_goal(&replacement)
2163 .expect("replace goal");
2164 assert_eq!(
2165 store.get_thread_goal("thread-1").expect("read replacement"),
2166 Some(replacement)
2167 );
2168
2169 assert!(store.delete_thread_goal("thread-1").expect("delete goal"));
2170 assert!(
2171 store
2172 .get_thread_goal("thread-1")
2173 .expect("read empty")
2174 .is_none()
2175 );
2176 assert!(!store.delete_thread_goal("thread-1").expect("delete empty"));
2177 }
2178
2179 #[test]
2180 fn thread_goal_requires_existing_thread() {
2181 let store = temp_state_store("thread-goal-missing-thread");
2182 let err = store
2183 .upsert_thread_goal(&test_goal("missing-thread", "nope"))
2184 .expect_err("goal without a thread should fail");
2185 assert!(err.to_string().contains("thread missing-thread not found"));
2186 }
2187
2188 /// Audit R03-07: two first opens of one fresh database. The loser must
2189 /// decide from the winner's committed schema, not from a probe taken
2190 /// before it could write. The old code read "column missing" outside its
2191 /// transaction, waited out the winner, then failed its own `ADD COLUMN`
2192 /// with "duplicate column name".
2193 #[test]
2194 fn a_first_open_that_loses_the_migration_race_still_opens() {
2195 let dir = temp_state_dir("migration-race");
2196 let path = dir.join("state.db");
2197 let winner = Connection::open(&path).expect("open winner");
2198 let mode: String = winner
2199 .query_row("PRAGMA journal_mode=WAL;", [], |row| row.get(0))
2200 .expect("wal");
2201 assert_eq!(mode, "wal");
2202 // The winner is mid-migration: the v1 columns exist inside its
2203 // uncommitted write transaction, user_version is still 0.
2204 winner
2205 .execute_batch(
2206 r#"
2207 BEGIN IMMEDIATE;
2208 CREATE TABLE threads (
2209 id TEXT PRIMARY KEY, rollout_path TEXT, preview TEXT NOT NULL,
2210 ephemeral INTEGER NOT NULL, model_provider TEXT NOT NULL,
2211 created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL,
2212 status TEXT NOT NULL, path TEXT, cwd TEXT NOT NULL,
2213 cli_version TEXT NOT NULL, source TEXT NOT NULL, title TEXT,
2214 sandbox_policy TEXT, approval_mode TEXT,
2215 archived INTEGER NOT NULL DEFAULT 0, archived_at INTEGER,
2216 git_sha TEXT, git_branch TEXT, git_origin_url TEXT,
2217 memory_mode TEXT, current_leaf_id INTEGER NULL
2218 );
2219 CREATE TABLE messages (
2220 id INTEGER PRIMARY KEY AUTOINCREMENT, thread_id TEXT NOT NULL,
2221 role TEXT NOT NULL, content TEXT NOT NULL, item_json TEXT,
2222 created_at INTEGER NOT NULL, parent_entry_id INTEGER NULL,
2223 FOREIGN KEY(thread_id) REFERENCES threads(id) ON DELETE CASCADE
2224 );
2225 "#,
2226 )
2227 .expect("winner begins its migration");
2228
2229 let loser = {
2230 let path = path.clone();
2231 thread::spawn(move || StateStore::open(Some(path)).map(|_| ()))
2232 };
2233 // Long enough for the loser to probe the schema; well inside its
2234 // five-second busy timeout.
2235 thread::sleep(Duration::from_millis(500));
2236 winner.execute_batch("COMMIT;").expect("winner commits");
2237
2238 loser
2239 .join()
2240 .expect("loser thread")
2241 .expect("the losing first open must succeed");
2242 }
2243
2244 /// Audit R05-05: a batch append is all or nothing. The pattern it
2245 /// replaces (one `append_message` transaction per item) leaves a
2246 /// partial chain when a later item fails.
2247 #[test]
2248 fn append_messages_is_all_or_nothing() {
2249 let store = temp_state_store("append-batch-atomic");
2250 store
2251 .upsert_thread(&test_thread("thread-1"))
2252 .expect("upsert thread");
2253 store
2254 .conn()
2255 .expect("conn")
2256 .execute_batch(
2257 "CREATE TRIGGER refuse_boom BEFORE INSERT ON messages \
2258 WHEN NEW.content = 'boom' BEGIN SELECT RAISE(ABORT, 'boom'); END;",
2259 )
2260 .expect("install failing trigger");
2261 let batch = ["one", "boom"].map(|content| NewMessage {
2262 role: "history".to_string(),
2263 content: content.to_string(),
2264 item: None,
2265 });
2266
2267 // The per-item pattern leaves "one" behind.
2268 let per_item: Result<Vec<i64>> = batch
2269 .iter()
2270 .map(|message| store.append_message("thread-1", &message.role, &message.content, None))
2271 .collect();
2272 assert!(per_item.is_err());
2273 let partial = store.list_messages("thread-1", None).expect("list");
2274 assert_eq!(partial.len(), 1, "per-item appends leave a partial chain");
2275 store.clear_messages("thread-1").expect("reset");
2276
2277 assert!(store.append_messages("thread-1", &batch).is_err());
2278 assert!(
2279 store
2280 .list_messages("thread-1", None)
2281 .expect("list")
2282 .is_empty(),
2283 "a failed batch must leave no messages"
2284 );
2285 let leaf: Option<i64> = store
2286 .conn()
2287 .expect("conn")
2288 .query_row(
2289 "SELECT current_leaf_id FROM threads WHERE id = 'thread-1'",
2290 [],
2291 |row| row.get(0),
2292 )
2293 .expect("leaf");
2294 assert_eq!(leaf, None, "a failed batch must not move the leaf");
2295
2296 let ok = ["a", "b", "c"].map(|content| NewMessage {
2297 role: "history".to_string(),
2298 content: content.to_string(),
2299 item: None,
2300 });
2301 let ids = store
2302 .append_messages("thread-1", &ok)
2303 .expect("append batch");
2304 let chain = store.list_messages("thread-1", None).expect("list");
2305 assert_eq!(chain.iter().map(|m| m.id).collect::<Vec<_>>(), ids);
2306 assert_eq!(chain[1].parent_entry_id, Some(ids[0]));
2307 assert_eq!(chain[2].parent_entry_id, Some(ids[1]));
2308 }
2309
2310 /// Audit R03-09: a deleted thread must not keep answering for its name
2311 /// in the session index, shadowing a live thread of the same name.
2312 #[test]
2313 fn deleted_thread_leaves_the_session_index() {
2314 let store = temp_state_store("delete-index");
2315 store
2316 .append_thread_name(
2317 "live",
2318 Some("Build".to_string()),
2319 100,
2320 Some(PathBuf::from("/live")),
2321 )
2322 .expect("index live");
2323 store
2324 .append_thread_name(
2325 "gone",
2326 Some("build".to_string()),
2327 200,
2328 Some(PathBuf::from("/gone")),
2329 )
2330 .expect("index gone");
2331 assert_eq!(
2332 store.find_thread_path_by_name_str("build").expect("find"),
2333 Some(PathBuf::from("/gone"))
2334 );
2335
2336 store.delete_thread("gone").expect("delete");
2337
2338 assert_eq!(
2339 store.find_thread_path_by_name_str("build").expect("find"),
2340 Some(PathBuf::from("/live"))
2341 );
2342 }
2343
2344 #[test]
2345 fn delete_thread_cascades_child_rows() {
2346 let store = temp_state_store("thread-delete-cascade");
2347 store
2348 .upsert_thread(&test_thread("thread-1"))
2349 .expect("upsert thread");
2350 store
2351 .append_message("thread-1", "user", "hello", None)
2352 .expect("append message");
2353 store
2354 .save_checkpoint("thread-1", "checkpoint-1", &serde_json::json!({"ok": true}))
2355 .expect("save checkpoint");
2356 store
2357 .persist_dynamic_tools(
2358 "thread-1",
2359 &[DynamicToolRecord {
2360 position: 0,
2361 name: "test_tool".to_string(),
2362 description: Some("test".to_string()),
2363 input_schema: serde_json::json!({"type": "object"}),
2364 }],
2365 )
2366 .expect("persist dynamic tools");
2367 store
2368 .upsert_thread_goal(&test_goal("thread-1", "Ship v0.8.67"))
2369 .expect("upsert goal");
2370
2371 store.delete_thread("thread-1").expect("delete thread");
2372
2373 let conn = store.conn().expect("conn");
2374 for table in [
2375 "messages",
2376 "checkpoints",
2377 "thread_dynamic_tools",
2378 "thread_goals",
2379 ] {
2380 let sql = format!("SELECT COUNT(*) FROM {table} WHERE thread_id = ?1");
2381 let count: i64 = conn
2382 .query_row(&sql, params!["thread-1"], |row| row.get(0))
2383 .expect("count child rows");
2384 assert_eq!(count, 0, "{table} row survived thread deletion");
2385 }
2386 }
2387
2388 #[test]
2389 fn state_store_reuses_one_connection_across_operations_and_clones() {
2390 let store = temp_state_store("conn-reuse");
2391 {
2392 let conn = store.conn().expect("conn");
2393 conn.execute_batch("CREATE TEMP TABLE conn_reuse_probe(id INTEGER);")
2394 .expect("create temp table");
2395 }
2396 // TEMP tables are visible only on the connection that created them, so
2397 // seeing the probe again — through a clone, after real operations ran —
2398 // proves the store holds one long-lived connection instead of
2399 // reopening the database (and reapplying pragmas) per call.
2400 let clone = store.clone();
2401 clone
2402 .upsert_thread(&test_thread("thread-conn-reuse"))
2403 .expect("upsert thread");
2404 let conn = clone.conn().expect("conn");
2405 let probe_count: i64 = conn
2406 .query_row(
2407 "SELECT COUNT(*) FROM sqlite_temp_master WHERE name = 'conn_reuse_probe'",
2408 [],
2409 |row| row.get(0),
2410 )
2411 .expect("query temp master");
2412 assert_eq!(
2413 probe_count, 1,
2414 "temp table not visible: a fresh connection was opened"
2415 );
2416 // The pragma applied once at open still governs the shared connection.
2417 let foreign_keys: i64 = conn
2418 .query_row("PRAGMA foreign_keys;", [], |row| row.get(0))
2419 .expect("read foreign_keys pragma");
2420 assert_eq!(foreign_keys, 1);
2421 let journal_mode: String = conn
2422 .query_row("PRAGMA journal_mode;", [], |row| row.get(0))
2423 .expect("read journal_mode pragma");
2424 assert_eq!(
2425 journal_mode.to_ascii_lowercase(),
2426 "wal",
2427 "open should enable WAL for multi-process readers/writers"
2428 );
2429 }
2430
2431 #[test]
2432 fn connection_setup_waits_for_database_lock_before_enabling_wal() {
2433 let dir = temp_state_dir("locked-open");
2434 let db_path = dir.join("state.db");
2435
2436 let candidate = Connection::open(&db_path).expect("open candidate connection");
2437 // Do not let rusqlite's current default mask StateStore's own setup
2438 // contract: configure_connection must install the wait policy before
2439 // it performs any operation that can need a database lock.
2440 candidate
2441 .busy_timeout(Duration::ZERO)
2442 .expect("disable dependency default timeout");
2443 let blocker = Connection::open(&db_path).expect("open blocking connection");
2444 let (locked_tx, locked_rx) = mpsc::sync_channel(0);
2445 let blocker_thread = thread::spawn(move || {
2446 blocker
2447 .execute_batch("BEGIN EXCLUSIVE;")
2448 .expect("acquire exclusive database lock");
2449 locked_tx.send(()).expect("announce database lock");
2450 thread::sleep(Duration::from_millis(200));
2451 blocker
2452 .execute_batch("COMMIT;")
2453 .expect("release exclusive database lock");
2454 });
2455
2456 locked_rx.recv().expect("wait for database lock");
2457 StateStore::configure_connection(&candidate, &db_path)
2458 .expect("connection setup should wait for the brief database lock");
2459 blocker_thread.join().expect("blocking thread panicked");
2460
2461 let journal_mode: String = candidate
2462 .query_row("PRAGMA journal_mode;", [], |row| row.get(0))
2463 .expect("read journal_mode");
2464 assert_eq!(journal_mode.to_ascii_lowercase(), "wal");
2465
2466 drop(candidate);
2467 let _ = fs::remove_dir_all(dir);
2468 }
2469
2470 /// A second process must wait for a brief active writer instead of
2471 /// surfacing SQLITE_BUSY (#4734).
2472 ///
2473 /// The lock handoff is explicit: unlike a race between many autocommit
2474 /// writes, this proves the busy timeout while keeping the contention
2475 /// duration below its documented five-second bound on every platform.
2476 #[test]
2477 fn second_connection_waits_for_active_writer() {
2478 let dir = temp_state_dir("concurrent-write");
2479 let db_path = dir.join("state.db");
2480
2481 let store_a = StateStore::open(Some(db_path.clone())).expect("open store a");
2482 let store_b = StateStore::open(Some(db_path.clone())).expect("open store b");
2483 let (locked_tx, locked_rx) = mpsc::sync_channel(0);
2484 let (release_tx, release_rx) = mpsc::sync_channel(0);
2485
2486 let writer_a = thread::spawn(move || {
2487 let conn = store_a.conn().expect("connection a");
2488 conn.execute_batch(
2489 r#"
2490 BEGIN IMMEDIATE;
2491 INSERT INTO jobs(id, name, status, created_at, updated_at)
2492 VALUES ('job-a', 'writer-a', 'running', 0, 0);
2493 "#,
2494 )
2495 .expect("writer a should acquire the database write lock");
2496 locked_tx.send(()).expect("announce active writer");
2497 release_rx.recv().expect("wait to release active writer");
2498 conn.execute_batch("COMMIT;")
2499 .expect("writer a should commit");
2500 });
2501
2502 locked_rx.recv().expect("wait for active writer");
2503 let (attempting_tx, attempting_rx) = mpsc::sync_channel(0);
2504 let writer_b = thread::spawn(move || -> Result<()> {
2505 attempting_tx.send(()).expect("announce second write");
2506 store_b.conn()?.execute(
2507 "INSERT INTO jobs(id, name, status, created_at, updated_at) VALUES ('job-b', 'writer-b', 'running', 1, 1)",
2508 [],
2509 )?;
2510 Ok(())
2511 });
2512
2513 attempting_rx.recv().expect("wait for second write attempt");
2514 thread::sleep(Duration::from_millis(100));
2515 assert!(
2516 !writer_b.is_finished(),
2517 "second writer should still be waiting while the first holds the lock"
2518 );
2519 release_tx.send(()).expect("release active writer");
2520 writer_a.join().expect("writer a panicked");
2521 writer_b
2522 .join()
2523 .expect("writer b panicked")
2524 .expect("writer b should succeed after the lock is released");
2525
2526 let store = StateStore::open(Some(db_path)).expect("reopen for verify");
2527 let listed: i64 = store
2528 .conn()
2529 .expect("connection")
2530 .query_row("SELECT COUNT(*) FROM jobs", [], |row| row.get(0))
2531 .expect("count jobs");
2532 assert_eq!(listed, 2, "both writers should persist their jobs");
2533
2534 let _ = fs::remove_dir_all(dir);
2535 }
2536
2537 #[test]
2538 fn runtime_thread_link_round_trips_and_goes_with_its_thread() {
2539 let store = temp_state_store("runtime-thread-link");
2540 store
2541 .upsert_thread(&test_thread("thread-linked"))
2542 .expect("upsert thread");
2543 assert_eq!(
2544 store
2545 .get_runtime_thread_link("thread-linked")
2546 .expect("read"),
2547 None
2548 );
2549 store
2550 .set_runtime_thread_link("thread-linked", "thr_runtime_1")
2551 .expect("link");
2552 store
2553 .set_runtime_thread_link("thread-linked", "thr_runtime_2")
2554 .expect("relink");
2555 assert_eq!(
2556 store
2557 .get_runtime_thread_link("thread-linked")
2558 .expect("read")
2559 .as_deref(),
2560 Some("thr_runtime_2")
2561 );
2562 assert!(
2563 store
2564 .set_runtime_thread_link("no-such-thread", "thr_runtime_3")
2565 .is_err(),
2566 "a link needs an existing thread"
2567 );
2568 store.delete_thread("thread-linked").expect("delete thread");
2569 assert_eq!(
2570 store
2571 .get_runtime_thread_link("thread-linked")
2572 .expect("read"),
2573 None
2574 );
2575 }
2576
2577 #[test]
2578 fn migration_runs_cleanly_when_schema_predates_user_version_header() {
2579 // Simulate a restore (or a racing process that crashed before
2580 // stamping user_version): the on-disk schema is fully migrated but
2581 // the header still says 0. The v0 block used to re-run unconditional
2582 // ADD COLUMN statements and abort the open with
2583 // "duplicate column name".
2584 let dir = temp_state_dir("migration-v0-idempotent");
2585 let db_path = dir.join("state.db");
2586 drop(StateStore::open(Some(db_path.clone())).expect("initial open"));
2587 {
2588 let conn = Connection::open(&db_path).expect("raw connection");
2589 conn.pragma_update(None, "user_version", 0)
2590 .expect("reset user_version");
2591 }
2592
2593 let store = StateStore::open(Some(db_path.clone())).expect("reopen with v0 header");
2594 store
2595 .upsert_thread(&test_thread("thread-migrated"))
2596 .expect("write after guarded migration");
2597
2598 // Reopening again (now stamped at the current version) still works.
2599 drop(store);
2600 let store = StateStore::open(Some(db_path)).expect("third open");
2601 let persisted = store
2602 .get_thread("thread-migrated")
2603 .expect("read after reopen");
2604 assert!(persisted.is_some());
2605
2606 let _ = fs::remove_dir_all(dir);
2607 }
2608
2609 #[test]
2610 fn record_thread_goal_usage_accumulates_tokens_and_time() {
2611 let store = temp_state_store("thread-goal-usage");
2612 store
2613 .upsert_thread(&test_thread("thread-1"))
2614 .expect("upsert thread");
2615
2616 // Mirror the runtime, which creates goals with zeroed accounting.
2617 let mut goal = test_goal("thread-1", "Ship the persistent goal loop");
2618 goal.tokens_used = 0;
2619 goal.time_used_seconds = 0;
2620 goal.updated_at = 100;
2621 store.upsert_thread_goal(&goal).expect("upsert goal");
2622
2623 // First accrual lands the deltas and advances updated_at.
2624 let after_first = store
2625 .record_thread_goal_usage("thread-1", 250, 12, 150)
2626 .expect("record usage")
2627 .expect("goal exists");
2628 assert_eq!(after_first.tokens_used, 250);
2629 assert_eq!(after_first.time_used_seconds, 12);
2630 assert_eq!(after_first.updated_at, 150);
2631 // Identity fields are preserved across accrual.
2632 assert_eq!(after_first.goal_id, goal.goal_id);
2633 assert_eq!(after_first.objective, goal.objective);
2634 assert_eq!(after_first.status, goal.status);
2635 assert_eq!(after_first.token_budget, goal.token_budget);
2636 assert_eq!(after_first.created_at, goal.created_at);
2637 assert_eq!(after_first.continuation_count, 0);
2638
2639 // Second accrual adds on top of the first (additive, not replacing).
2640 let after_second = store
2641 .record_thread_goal_usage("thread-1", 75, 8, 200)
2642 .expect("record usage")
2643 .expect("goal exists");
2644 assert_eq!(after_second.tokens_used, 325);
2645 assert_eq!(after_second.time_used_seconds, 20);
2646 assert_eq!(after_second.updated_at, 200);
2647
2648 // A stale `now` must not move updated_at backwards.
2649 let after_stale = store
2650 .record_thread_goal_usage("thread-1", 5, 1, 1)
2651 .expect("record usage")
2652 .expect("goal exists");
2653 assert_eq!(after_stale.tokens_used, 330);
2654 assert_eq!(after_stale.time_used_seconds, 21);
2655 assert_eq!(after_stale.updated_at, 200);
2656
2657 // Read back through the normal getter to confirm durability.
2658 let persisted = store
2659 .get_thread_goal("thread-1")
2660 .expect("read goal")
2661 .expect("goal exists");
2662 assert_eq!(persisted.tokens_used, 330);
2663 assert_eq!(persisted.time_used_seconds, 21);
2664 }
2665
2666 #[test]
2667 fn record_thread_goal_usage_returns_none_without_goal() {
2668 let store = temp_state_store("thread-goal-usage-missing");
2669 store
2670 .upsert_thread(&test_thread("thread-1"))
2671 .expect("upsert thread");
2672 // Thread exists but has no goal row yet: accrual is a no-op, not an error,
2673 // and must not create a goal.
2674 let result = store
2675 .record_thread_goal_usage("thread-1", 100, 5, 999)
2676 .expect("record usage on goalless thread");
2677 assert!(result.is_none());
2678 assert!(
2679 store
2680 .get_thread_goal("thread-1")
2681 .expect("read goal")
2682 .is_none()
2683 );
2684 }
2685
2686 #[test]
2687 fn record_thread_goal_continuation_accumulates_durably() {
2688 let store = temp_state_store("thread-goal-continuation");
2689 store
2690 .upsert_thread(&test_thread("thread-1"))
2691 .expect("upsert thread");
2692
2693 let mut goal = test_goal("thread-1", "Keep working across turns");
2694 goal.updated_at = 100;
2695 store.upsert_thread_goal(&goal).expect("upsert goal");
2696
2697 let after_first = store
2698 .record_thread_goal_continuation("thread-1", 120)
2699 .expect("record continuation")
2700 .expect("goal exists");
2701 assert_eq!(after_first.continuation_count, 1);
2702 assert_eq!(after_first.tokens_used, goal.tokens_used);
2703 assert_eq!(after_first.time_used_seconds, goal.time_used_seconds);
2704 assert_eq!(after_first.updated_at, 120);
2705
2706 let after_second = store
2707 .record_thread_goal_continuation("thread-1", 110)
2708 .expect("record second continuation")
2709 .expect("goal exists");
2710 assert_eq!(after_second.continuation_count, 2);
2711 assert_eq!(after_second.updated_at, 120);
2712
2713 let persisted = store
2714 .get_thread_goal("thread-1")
2715 .expect("read goal")
2716 .expect("goal exists");
2717 assert_eq!(persisted.continuation_count, 2);
2718 }
2719
2720 // ── $CODEWHALE_HOME override tests ──────────────────────────────
2721 //
2722 // These touch a process-global env var, so they serialize against each
2723 // other (and restore the prior value) to stay hermetic under parallel test
2724 // runs — the same concern AGENTS.md flags for config_command_allow_shell_*.
2725
2726 static CODEWHALE_HOME_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
2727
2728 struct CodeWhaleHomeGuard {
2729 prior: Option<std::ffi::OsString>,
2730 }
2731 impl CodeWhaleHomeGuard {
2732 fn set(value: &str) -> Self {
2733 let prior = std::env::var_os("CODEWHALE_HOME");
2734 // SAFETY: serialised by CODEWHALE_HOME_TEST_LOCK.
2735 unsafe { std::env::set_var("CODEWHALE_HOME", value) };
2736 Self { prior }
2737 }
2738 fn remove() -> Self {
2739 let prior = std::env::var_os("CODEWHALE_HOME");
2740 // SAFETY: serialised by CODEWHALE_HOME_TEST_LOCK.
2741 unsafe { std::env::remove_var("CODEWHALE_HOME") };
2742 Self { prior }
2743 }
2744 }
2745 impl Drop for CodeWhaleHomeGuard {
2746 fn drop(&mut self) {
2747 // SAFETY: serialised by CODEWHALE_HOME_TEST_LOCK.
2748 unsafe {
2749 match &self.prior {
2750 Some(value) => std::env::set_var("CODEWHALE_HOME", value),
2751 None => std::env::remove_var("CODEWHALE_HOME"),
2752 }
2753 }
2754 }
2755 }
2756
2757 #[test]
2758 fn codewhale_home_override_returns_the_env_value_verbatim() {
2759 let _lock = CODEWHALE_HOME_TEST_LOCK.lock().unwrap();
2760 let override_path = std::env::temp_dir().join("cw-isolated-state");
2761 let _g = CodeWhaleHomeGuard::set(override_path.to_str().unwrap());
2762 // The env var IS the home dir — no ".codewhale" appended. This matches
2763 // codewhale_home() in config ($CODEWHALE_HOME=/x means home is /x).
2764 assert_eq!(
2765 codewhale_home_override().unwrap().as_deref(),
2766 Some(override_path.as_path())
2767 );
2768 }
2769
2770 #[test]
2771 fn codewhale_home_override_none_when_unset() {
2772 let _lock = CODEWHALE_HOME_TEST_LOCK.lock().unwrap();
2773 let _g = CodeWhaleHomeGuard::remove();
2774 assert!(codewhale_home_override().unwrap().is_none());
2775 }
2776
2777 #[test]
2778 fn codewhale_home_override_none_when_whitespace_only() {
2779 let _lock = CODEWHALE_HOME_TEST_LOCK.lock().unwrap();
2780 let _g = CodeWhaleHomeGuard::set(" ");
2781 assert!(
2782 codewhale_home_override().unwrap().is_none(),
2783 "whitespace-only CODEWHALE_HOME must not establish isolation"
2784 );
2785 }
2786
2787 #[test]
2788 fn default_state_db_path_uses_codewhale_home_when_set() {
2789 let _lock = CODEWHALE_HOME_TEST_LOCK.lock().unwrap();
2790 let dir = std::env::temp_dir().join(format!(
2791 "cw-home-state-{}-{}",
2792 std::process::id(),
2793 std::time::SystemTime::now()
2794 .duration_since(std::time::UNIX_EPOCH)
2795 .unwrap()
2796 .as_nanos()
2797 ));
2798 let _g = CodeWhaleHomeGuard::set(dir.to_str().unwrap());
2799 // Hard override: the DB is <CODEWHALE_HOME>/state.db, NOT
2800 // <CODEWHALE_HOME>/.codewhale/state.db, and the legacy ~/.deepseek
2801 // fallback is bypassed entirely.
2802 assert_eq!(default_state_db_path(), dir.join("state.db"));
2803 }
2804
2805 #[test]
2806 fn implicit_state_database_refuses_unresolved_home() {
2807 const PROBE: &str = "CODEWHALE_STATE_DEFAULT_PATH_PROBE";
2808 if std::env::var_os(PROBE).is_some() {
2809 let error =
2810 StateStore::open(None).expect_err("implicit relative state must be refused");
2811 assert!(error.to_string().contains("absolute home directory"));
2812 assert!(!Path::new(".codewhale").exists());
2813 StateStore::open(Some(PathBuf::from("explicit/state.db")))
2814 .expect("an explicitly chosen relative path remains supported");
2815 return;
2816 }
2817 let probe = std::env::temp_dir().join(format!(
2818 "cw-state-default-probe-{}-{}",
2819 std::process::id(),
2820 std::time::SystemTime::now()
2821 .duration_since(std::time::UNIX_EPOCH)
2822 .unwrap()
2823 .as_nanos()
2824 ));
2825 fs::create_dir_all(&probe).unwrap();
2826 let output = std::process::Command::new(std::env::current_exe().unwrap())
2827 .args([
2828 "--exact",
2829 "tests::implicit_state_database_refuses_unresolved_home",
2830 ])
2831 .env(PROBE, "1")
2832 .env_remove("CODEWHALE_HOME")
2833 .env("HOME", "relative-home")
2834 .current_dir(&probe)
2835 .output()
2836 .unwrap();
2837 fs::remove_dir_all(&probe).unwrap();
2838 assert!(
2839 output.status.success(),
2840 "{}{}",
2841 String::from_utf8_lossy(&output.stdout),
2842 String::from_utf8_lossy(&output.stderr)
2843 );
2844 }
2845
2846 #[test]
2847 fn load_checkpoint_propagates_invalid_state_json() {
2848 let store = temp_state_store("checkpoint-parse-error");
2849 store
2850 .upsert_thread(&test_thread("thread-1"))
2851 .expect("upsert thread");
2852 store
2853 .save_checkpoint("thread-1", "broken", &json!({"ok": true}))
2854 .expect("save checkpoint");
2855
2856 {
2857 let conn = store.conn().expect("conn");
2858 conn.execute(
2859 "UPDATE checkpoints SET state_json = ?1 WHERE thread_id = ?2 AND checkpoint_id = ?3",
2860 params!["not-json", "thread-1", "broken"],
2861 )
2862 .expect("corrupt checkpoint");
2863 }
2864
2865 let err = store
2866 .load_checkpoint("thread-1", Some("broken"))
2867 .expect_err("invalid checkpoint json should fail");
2868 assert!(
2869 err.to_string()
2870 .contains("failed to parse checkpoint state json")
2871 );
2872 }
2873
2874 #[test]
2875 fn session_index_compacts_after_threshold() {
2876 let store = temp_state_store("session-index-compact");
2877 for idx in 0..6 {
2878 store
2879 .append_thread_name("thread-1", Some(format!("name-{idx}")), idx, None)
2880 .expect("append session index entry");
2881 }
2882
2883 let line_count = store
2884 .session_index_line_count()
2885 .expect("count session index lines");
2886 assert_eq!(line_count, 1);
2887
2888 let name = store
2889 .find_thread_name_by_id("thread-1")
2890 .expect("lookup thread name");
2891 assert_eq!(name.as_deref(), Some("name-5"));
2892 }
2893
2894 #[test]
2895 fn session_index_read_skips_a_torn_line() {
2896 // #4735: a crash mid-append leaves a truncated final line. Failing the
2897 // whole read broke every thread-name lookup at once, and compaction
2898 // reads through the same path, so the index could not repair itself.
2899 let store = temp_state_store("session-index-torn");
2900 store
2901 .append_thread_name("thread-1", Some("first".to_string()), 1, None)
2902 .expect("append first entry");
2903
2904 {
2905 let mut file = OpenOptions::new()
2906 .append(true)
2907 .open(&store.session_index_path)
2908 .expect("open session index");
2909 // A write cut off mid-JSON, exactly as a crash would leave it.
2910 writeln!(file, "{{\"thread_id\":\"thread-2\",\"thread_na").expect("write torn line");
2911 }
2912
2913 store
2914 .append_thread_name("thread-3", Some("third".to_string()), 3, None)
2915 .expect("append third entry");
2916
2917 assert_eq!(
2918 store
2919 .find_thread_name_by_id("thread-1")
2920 .expect("lookup thread-1")
2921 .as_deref(),
2922 Some("first"),
2923 );
2924 assert_eq!(
2925 store
2926 .find_thread_name_by_id("thread-3")
2927 .expect("lookup thread-3")
2928 .as_deref(),
2929 Some("third"),
2930 );
2931 }
2932
2933 #[test]
2934 fn session_index_append_after_an_unterminated_torn_line_is_kept() {
2935 let store = temp_state_store("session-index-unterminated");
2936 store
2937 .append_thread_name("thread-1", Some("first".to_string()), 1, None)
2938 .expect("append first entry");
2939 {
2940 let mut file = OpenOptions::new()
2941 .append(true)
2942 .open(&store.session_index_path)
2943 .expect("open session index");
2944 write!(file, "{{\"thread_id\":\"thread-2\",\"thread_na").expect("write torn line");
2945 }
2946
2947 store
2948 .append_thread_name("thread-3", Some("third".to_string()), 3, None)
2949 .expect("append third entry");
2950
2951 assert_eq!(
2952 store
2953 .find_thread_name_by_id("thread-3")
2954 .expect("lookup thread-3")
2955 .as_deref(),
2956 Some("third"),
2957 );
2958 }
2959
2960 /// Hook fired by compaction between writing the snapshot and renaming it
2961 /// over the live index — the window a concurrent append can be lost in.
2962 /// Only the store whose path a test registered is affected, so tests
2963 /// running in parallel don't disturb each other.
2964 type MidpointHook = Box<dyn Fn() + Send + Sync>;
2965 static COMPACTION_MIDPOINT: Mutex<Option<(PathBuf, MidpointHook)>> = Mutex::new(None);
2966
2967 /// Fires at most once: the racing append compacts too, and a hook that
2968 /// fired twice would re-enter the test's one-shot handshake.
2969 pub(super) fn compaction_midpoint(index_path: &Path) {
2970 let mut hook = COMPACTION_MIDPOINT.lock().expect("midpoint hook lock");
2971 let registered_for_this_store = match hook.as_ref() {
2972 Some((registered, _)) => registered == index_path,
2973 None => return,
2974 };
2975 if !registered_for_this_store {
2976 return;
2977 }
2978 let (_, callback) = hook.take().expect("presence checked above");
2979 drop(hook);
2980 callback();
2981 }
2982
2983 #[test]
2984 fn session_index_compaction_does_not_drop_a_concurrent_append() {
2985 // #4736: compaction snapshots the file, rewrites it, and renames over
2986 // the live one. An append landing between those two steps used to
2987 // vanish — silently, since it had already returned success to its
2988 // caller. The shared lock serializes the two.
2989 //
2990 // The race is real but narrow, so the test drives it deterministically:
2991 // a hook at the compaction midpoint releases the appender and then
2992 // waits. Without the lock the appender writes into the doomed file and
2993 // the rename discards it; with the lock it blocks until compaction
2994 // finishes, and its entry survives.
2995 let store = Arc::new(temp_state_store("session-index-race"));
2996 let threshold = session_index_compact_line_threshold();
2997
2998 // One line short of the threshold, so the next append compacts.
2999 for idx in 0..threshold {
3000 store
3001 .append_thread_name(
3002 &format!("thread-{idx}"),
3003 Some(format!("name-{idx}")),
3004 1,
3005 None,
3006 )
3007 .expect("append filler entry");
3008 }
3009
3010 let appender_released = Arc::new(Barrier::new(2));
3011 {
3012 let released = Arc::clone(&appender_released);
3013 *COMPACTION_MIDPOINT.lock().expect("midpoint hook lock") = Some((
3014 store.session_index_path.clone(),
3015 Box::new(move || {
3016 released.wait();
3017 // Give the appender time to complete its write into the
3018 // window. Under the fix it is blocked on the lock instead.
3019 thread::sleep(Duration::from_millis(300));
3020 }),
3021 ));
3022 }
3023
3024 let appender = {
3025 let store = Arc::clone(&store);
3026 let released = Arc::clone(&appender_released);
3027 thread::spawn(move || {
3028 released.wait();
3029 store
3030 .append_thread_name("racer", Some("racer-name".to_string()), 2, None)
3031 .expect("append racing entry");
3032 })
3033 };
3034
3035 store
3036 .append_thread_name("trigger", Some("trigger-name".to_string()), 1, None)
3037 .expect("append entry that triggers compaction");
3038 appender.join().expect("appender thread");
3039 *COMPACTION_MIDPOINT.lock().expect("midpoint hook lock") = None;
3040
3041 assert_eq!(
3042 store
3043 .find_thread_name_by_id("racer")
3044 .expect("lookup racer")
3045 .as_deref(),
3046 Some("racer-name"),
3047 "append was dropped by a concurrent compaction",
3048 );
3049 assert_eq!(
3050 store
3051 .find_thread_name_by_id("trigger")
3052 .expect("lookup trigger")
3053 .as_deref(),
3054 Some("trigger-name"),
3055 );
3056 }
3057 fn legacy_archive_fixture(id: &str) -> LegacyThreadArchive {
3058 let mut thread = test_thread(id);
3059 thread.current_leaf_id = Some(3);
3060 LegacyThreadArchive {
3061 thread,
3062 messages: [
3063 (1, None, "root"),
3064 (2, Some(1), "inactive"),
3065 (3, Some(1), "active"),
3066 ]
3067 .into_iter()
3068 .map(|(entry_id, parent_entry_id, content)| MessageRecord {
3069 id: entry_id,
3070 thread_id: id.into(),
3071 role: "user".into(),
3072 content: content.into(),
3073 item: Some(serde_json::json!({"content":content})),
3074 created_at: 100 + entry_id,
3075 parent_entry_id,
3076 })
3077 .collect(),
3078 goal: Some(test_goal(id, "historical goal")),
3079 checkpoints: vec![CheckpointRecord {
3080 thread_id: id.into(),
3081 checkpoint_id: "retained".into(),
3082 state: serde_json::json!({"receipt":"historical"}),
3083 created_at: 123,
3084 }],
3085 }
3086 }
3087
3088 #[test]
3089 fn legacy_archive_restore_keeps_full_graph_goal_checkpoint_and_refuses_replacement() {
3090 let store = temp_state_store("archive-once");
3091 let archive = legacy_archive_fixture("legacy");
3092 store.restore_legacy_thread_archive(&archive).unwrap();
3093 let snapshot = store.snapshot_legacy_thread_history("legacy").unwrap();
3094 assert_eq!(
3095 serde_json::to_value(&snapshot.messages).unwrap(),
3096 serde_json::to_value(&archive.messages).unwrap()
3097 );
3098 assert_eq!(snapshot.current_leaf_id, Some(3));
3099 assert_eq!(store.list_messages("legacy", None).unwrap().len(), 2);
3100 let goal = snapshot.goal.unwrap();
3101 assert_eq!(goal.status, codewhale_protocol::ThreadGoalStatus::Active);
3102 assert_eq!(goal.tokens_used, archive.goal.as_ref().unwrap().tokens_used);
3103 assert_eq!(goal.updated_at, archive.goal.as_ref().unwrap().updated_at);
3104 let checkpoint = store
3105 .load_checkpoint("legacy", Some("retained"))
3106 .unwrap()
3107 .unwrap();
3108 assert_eq!(checkpoint.created_at, 123);
3109 assert_eq!(checkpoint.state, archive.checkpoints[0].state);
3110 let mut replacement = archive.clone();
3111 replacement.messages[1].content = "changed inactive history".into();
3112 assert!(store.restore_legacy_thread_archive(&replacement).is_err());
3113 assert_eq!(
3114 store
3115 .snapshot_legacy_thread_history("legacy")
3116 .unwrap()
3117 .messages[1]
3118 .content,
3119 "inactive"
3120 );
3121 }
3122
3123 #[test]
3124 fn legacy_archive_restore_refuses_cycles_duplicates_foreign_rows_and_bounds_without_publication()
3125 {
3126 let store = temp_state_store("archive-refusals");
3127 let valid = legacy_archive_fixture("legacy");
3128 let mut invalid = Vec::new();
3129 let mut archive = valid.clone();
3130 archive.messages[0].parent_entry_id = Some(2);
3131 invalid.push(archive);
3132 let mut archive = valid.clone();
3133 archive.messages[1].id = 1;
3134 invalid.push(archive);
3135 let mut archive = valid.clone();
3136 archive.messages[1].parent_entry_id = Some(99);
3137 invalid.push(archive);
3138 let mut archive = valid.clone();
3139 archive.messages[1].thread_id = "foreign".into();
3140 invalid.push(archive);
3141 let mut archive = valid.clone();
3142 archive.thread.current_leaf_id = Some(99);
3143 invalid.push(archive);
3144 let mut archive = valid.clone();
3145 archive.goal.as_mut().unwrap().thread_id = "foreign".into();
3146 invalid.push(archive);
3147 let mut archive = valid.clone();
3148 archive.checkpoints[0].thread_id = "foreign".into();
3149 invalid.push(archive);
3150 let mut archive = valid.clone();
3151 archive.checkpoints.push(archive.checkpoints[0].clone());
3152 invalid.push(archive);
3153 let mut archive = valid.clone();
3154 archive.messages[0].content =
3155 "x".repeat(codewhale_protocol::MAX_CANONICAL_HISTORY_BYTES + 1);
3156 invalid.push(archive);
3157 for archive in invalid {
3158 assert!(store.restore_legacy_thread_archive(&archive).is_err());
3159 assert!(store.get_thread("legacy").unwrap().is_none());
3160 }
3161 store.restore_legacy_thread_archive(&valid).unwrap();
3162 }
3163
3164 #[test]
3165 fn legacy_archive_restore_rolls_back_metadata_messages_goal_on_late_checkpoint_failure() {
3166 let store = temp_state_store("archive-transaction");
3167 store.conn().unwrap().execute_batch("CREATE TRIGGER refuse_archive_checkpoint BEFORE INSERT ON checkpoints BEGIN SELECT RAISE(ABORT, 'fixture checkpoint failure'); END;").unwrap();
3168 let archive = legacy_archive_fixture("legacy");
3169 assert!(store.restore_legacy_thread_archive(&archive).is_err());
3170 let conn = store.conn().unwrap();
3171 for table in ["threads", "messages", "thread_goals", "checkpoints"] {
3172 let count: i64 = conn
3173 .query_row(&format!("SELECT count(*) FROM {table}"), [], |row| {
3174 row.get(0)
3175 })
3176 .unwrap();
3177 assert_eq!(
3178 count, 0,
3179 "{table} must roll back with the immutable archive"
3180 );
3181 }
3182 conn.execute_batch("DROP TRIGGER refuse_archive_checkpoint")
3183 .unwrap();
3184 drop(conn);
3185 store.restore_legacy_thread_archive(&archive).unwrap();
3186 }
3187
3188 #[test]
3189 fn list_messages_zero_limit_returns_empty_and_usize_max_returns_all() {
3190 let store = temp_state_store("list-messages-zero-limit");
3191 store
3192 .upsert_thread(&test_thread("thread-zero"))
3193 .expect("upsert thread");
3194 store
3195 .append_message("thread-zero", "user", "first", None)
3196 .expect("append first");
3197 store
3198 .append_message("thread-zero", "assistant", "second", None)
3199 .expect("append second");
3200
3201 let zero = store
3202 .list_messages("thread-zero", Some(0))
3203 .expect("zero limit");
3204 assert!(zero.is_empty(), "limit 0 must return no messages");
3205
3206 let all = store
3207 .list_messages("thread-zero", Some(usize::MAX))
3208 .expect("max limit");
3209 assert_eq!(all.len(), 2);
3210 }
3211
3212 #[test]
3213 fn compact_session_index_propagates_read_errors() {
3214 let store = temp_state_store("compact-read-error");
3215 fs::write(&store.session_index_path, [0xff_u8, 0xfe, b'\n']).expect("write invalid utf8");
3216 let err = store
3217 .compact_session_index_locked()
3218 .expect_err("invalid utf-8 read error must not be swallowed");
3219 assert!(
3220 err.to_string()
3221 .contains("failed to read session index line during compaction"),
3222 "{err:#}"
3223 );
3224 }
3225 }
3226
3226 lines RUST