Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / store.rs

store.rs1034 lines · 39.0 KiBRaw
1//! SQLite store: tasks, events, messages, sessions. Migrations run on startup.
2//!
3//! `Store` is a thin synchronous wrapper around a `rusqlite::Connection`
4//! guarded by a `Mutex`; the HTTP/agent code calls `Store::with` from
5//! `spawn_blocking` so the async runtime never blocks. Schema:
6//!
7//! * `tasks(...)` — one row per agent task (see [`crate::models::Task`]).
8//! * `events(task_id, seq, ...)` — append-only log; `seq` is per-task.
9//! * `messages(task_id, seq, body)` — persisted OpenRouter conversation
10//! (user / assistant / tool only; the system message is rebuilt per turn
11//! and never stored).
12//! * `sessions(token_sha256_hex, expires_at)` — login sessions.
13
14use std::path::Path;
15use std::sync::{Arc, Mutex};
16
17use rusqlite::{params, Connection, OptionalExtension};
18
19use crate::models::{now_unix, Event, Pending, Task, TaskStatus};
20
21/// One drained inbox row: user text plus the route's `kind` tag
22/// (`plan_approve`, `plan_changes`, `review_changes`; `""` = plain message).
23#[derive(Debug, Clone)]
24pub struct InboxRow {
25 pub text: String,
26 pub kind: String,
27}
28
29#[derive(Clone)]
30pub struct Store {
31 inner: Arc<Mutex<Connection>>,
32}
33
34impl Store {
35 pub fn open(dir: &Path) -> Result<Store, String> {
36 std::fs::create_dir_all(dir).map_err(|e| format!("create state dir: {e}"))?;
37 let db = dir.join("agentd.db");
38 let conn =
39 Connection::open(&db).map_err(|e| format!("open sqlite {}: {e}", db.display()))?;
40 let store = Store {
41 inner: Arc::new(Mutex::new(conn)),
42 };
43 store.migrate()?;
44 Ok(store)
45 }
46
47 fn with<T>(&self, f: impl FnOnce(&Connection) -> rusqlite::Result<T>) -> Result<T, String> {
48 let conn = self.inner.lock().map_err(|e| format!("db lock: {e}"))?;
49 f(&conn).map_err(|e| format!("sqlite: {e}"))
50 }
51
52 fn migrate(&self) -> Result<(), String> {
53 self.with(|c| {
54 c.execute_batch(
55 "PRAGMA journal_mode=WAL;
56 CREATE TABLE IF NOT EXISTS tasks (
57 id INTEGER PRIMARY KEY AUTOINCREMENT,
58 title TEXT NOT NULL,
59 prompt TEXT NOT NULL,
60 module_scope TEXT NOT NULL DEFAULT '',
61 model TEXT NOT NULL,
62 status TEXT NOT NULL DEFAULT 'queued',
63 slot INTEGER,
64 branch TEXT NOT NULL DEFAULT '',
65 base_sha TEXT,
66 commit_sha TEXT,
67 pushed INTEGER NOT NULL DEFAULT 0,
68 created_at INTEGER NOT NULL,
69 updated_at INTEGER NOT NULL,
70 started_at INTEGER,
71 finished_at INTEGER,
72 steps INTEGER NOT NULL DEFAULT 0,
73 prompt_tokens INTEGER NOT NULL DEFAULT 0,
74 completion_tokens INTEGER NOT NULL DEFAULT 0,
75 cost_usd REAL NOT NULL DEFAULT 0,
76 budget_steps INTEGER NOT NULL DEFAULT 60,
77 budget_usd REAL NOT NULL DEFAULT 2.0,
78 error TEXT,
79 summary TEXT
80 );
81 CREATE TABLE IF NOT EXISTS events (
82 id INTEGER PRIMARY KEY AUTOINCREMENT,
83 task_id INTEGER NOT NULL REFERENCES tasks(id),
84 seq INTEGER NOT NULL,
85 ts INTEGER NOT NULL,
86 kind TEXT NOT NULL,
87 body TEXT NOT NULL,
88 UNIQUE(task_id, seq)
89 );
90 CREATE INDEX IF NOT EXISTS idx_events_task ON events(task_id, seq);
91 CREATE TABLE IF NOT EXISTS sessions (
92 token_sha256_hex TEXT PRIMARY KEY,
93 expires_at INTEGER NOT NULL
94 );
95 CREATE TABLE IF NOT EXISTS messages (
96 id INTEGER PRIMARY KEY AUTOINCREMENT,
97 task_id INTEGER NOT NULL REFERENCES tasks(id),
98 seq INTEGER NOT NULL,
99 body TEXT NOT NULL,
100 UNIQUE(task_id, seq)
101 );
102 CREATE INDEX IF NOT EXISTS idx_messages_task ON messages(task_id, seq);
103 CREATE TABLE IF NOT EXISTS inbox (
104 id INTEGER PRIMARY KEY AUTOINCREMENT,
105 task_id INTEGER NOT NULL REFERENCES tasks(id),
106 text TEXT NOT NULL,
107 kind TEXT NOT NULL DEFAULT ''
108 );
109 CREATE INDEX IF NOT EXISTS idx_inbox_task ON inbox(task_id, id);
110 CREATE TABLE IF NOT EXISTS triage (
111 issue_number INTEGER PRIMARY KEY,
112 task_id INTEGER NOT NULL REFERENCES tasks(id),
113 status TEXT NOT NULL DEFAULT 'queued',
114 created_at INTEGER NOT NULL,
115 result_json TEXT
116 );
117 CREATE TABLE IF NOT EXISTS kv (
118 key TEXT PRIMARY KEY,
119 value TEXT NOT NULL
120 );",
121 )?;
122 // Forward-compatible columns for DBs created by older migrates.
123 for (table, col, ddl) in [
124 ("tasks", "module_scope", "ALTER TABLE tasks ADD COLUMN module_scope TEXT NOT NULL DEFAULT ''"),
125 ("tasks", "slot", "ALTER TABLE tasks ADD COLUMN slot INTEGER"),
126 ("tasks", "base_sha", "ALTER TABLE tasks ADD COLUMN base_sha TEXT"),
127 ("tasks", "commit_sha", "ALTER TABLE tasks ADD COLUMN commit_sha TEXT"),
128 ("tasks", "pending_json", "ALTER TABLE tasks ADD COLUMN pending_json TEXT"),
129 ("tasks", "todos_json", "ALTER TABLE tasks ADD COLUMN todos_json TEXT"),
130 ("tasks", "rules_json", "ALTER TABLE tasks ADD COLUMN rules_json TEXT"),
131 ("tasks", "require_plan", "ALTER TABLE tasks ADD COLUMN require_plan INTEGER NOT NULL DEFAULT 0"),
132 ("tasks", "plan_approved", "ALTER TABLE tasks ADD COLUMN plan_approved INTEGER NOT NULL DEFAULT 0"),
133 ("tasks", "wip_sha", "ALTER TABLE tasks ADD COLUMN wip_sha TEXT"),
134 ("tasks", "pushed_sha", "ALTER TABLE tasks ADD COLUMN pushed_sha TEXT"),
135 ("tasks", "final_diff", "ALTER TABLE tasks ADD COLUMN final_diff TEXT"),
136 ("tasks", "commit_message", "ALTER TABLE tasks ADD COLUMN commit_message TEXT"),
137 ("tasks", "issue_number", "ALTER TABLE tasks ADD COLUMN issue_number INTEGER"),
138 ("tasks", "plan_md", "ALTER TABLE tasks ADD COLUMN plan_md TEXT"),
139 ("inbox", "kind", "ALTER TABLE inbox ADD COLUMN kind TEXT NOT NULL DEFAULT ''"),
140 ("tasks", "stop_requested", "ALTER TABLE tasks ADD COLUMN stop_requested INTEGER NOT NULL DEFAULT 0"),
141 ("tasks", "approving", "ALTER TABLE tasks ADD COLUMN approving INTEGER NOT NULL DEFAULT 0"),
142 ("tasks", "kind", "ALTER TABLE tasks ADD COLUMN kind TEXT NOT NULL DEFAULT 'task'"),
143 ] {
144 let exists: i64 = c.query_row(
145 "SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?",
146 params![table, col],
147 |r| r.get(0),
148 )?;
149 if exists == 0 {
150 c.execute_batch(ddl)?;
151 }
152 }
153 Ok(())
154 })
155 }
156
157 // ---- tasks ----
158
159 pub fn create_task(
160 &self,
161 title: &str,
162 prompt: &str,
163 module_scope: &str,
164 model: &str,
165 budget_steps: i64,
166 budget_usd: f64,
167 ) -> Result<i64, String> {
168 let now = now_unix();
169 self.with(|c| {
170 c.execute(
171 "INSERT INTO tasks (title, prompt, module_scope, model, status, created_at, updated_at, budget_steps, budget_usd)
172 VALUES (?, ?, ?, ?, 'queued', ?, ?, ?, ?)",
173 params![title, prompt, module_scope, model, now, now, budget_steps, budget_usd],
174 )?;
175 Ok(c.last_insert_rowid())
176 })
177 }
178
179 pub fn set_branch(&self, id: i64, branch: &str) -> Result<(), String> {
180 self.with(|c| {
181 c.execute(
182 "UPDATE tasks SET branch = ?, updated_at = ? WHERE id = ?",
183 params![branch, now_unix(), id],
184 )?;
185 Ok(())
186 })
187 }
188
189 /// Record the linked GitHub issue for start-from-issue tasks
190 /// (the form stores it; `finish` then requires the ` (#<n>)` suffix).
191 pub fn set_issue_number(&self, id: i64, issue_number: i64) -> Result<(), String> {
192 self.with(|c| {
193 c.execute(
194 "UPDATE tasks SET issue_number = ?, updated_at = ? WHERE id = ?",
195 params![issue_number, now_unix(), id],
196 )?;
197 Ok(())
198 })
199 }
200
201 fn row_to_task(r: &rusqlite::Row<'_>) -> rusqlite::Result<Task> {
202 let status_s: String = r.get("status")?;
203 let kind: Option<String> = r
204 .get::<_, Option<String>>("kind")
205 .unwrap_or(None);
206 let pending_s: Option<String> = r.get("pending_json")?;
207 let pending = pending_s
208 .as_deref()
209 .map(serde_json::from_str::<Pending>)
210 .transpose()
211 .map_err(|e| {
212 rusqlite::Error::FromSqlConversionFailure(
213 0,
214 rusqlite::types::Type::Text,
215 Box::new(e),
216 )
217 })?;
218 Ok(Task {
219 id: r.get("id")?,
220 title: r.get("title")?,
221 prompt: r.get("prompt")?,
222 module_scope: r.get("module_scope")?,
223 model: r.get("model")?,
224 kind: kind.unwrap_or_else(crate::models::default_task_kind),
225 status: TaskStatus::parse(&status_s).unwrap_or(TaskStatus::Queued),
226 slot: r.get::<_, Option<i64>>("slot")?.map(|v| v as u32),
227 branch: r.get("branch")?,
228 base_sha: r.get("base_sha")?,
229 commit_sha: r.get("commit_sha")?,
230 pushed: r.get::<_, i64>("pushed")? != 0,
231 created_at: r.get("created_at")?,
232 updated_at: r.get("updated_at")?,
233 started_at: r.get("started_at")?,
234 finished_at: r.get("finished_at")?,
235 steps: r.get("steps")?,
236 prompt_tokens: r.get("prompt_tokens")?,
237 completion_tokens: r.get("completion_tokens")?,
238 cost_usd: r.get("cost_usd")?,
239 budget_steps: r.get("budget_steps")?,
240 budget_usd: r.get("budget_usd")?,
241 error: r.get("error")?,
242 summary: r.get("summary")?,
243 pending,
244 todos_json: r.get("todos_json")?,
245 rules_json: r.get("rules_json")?,
246 require_plan: r.get::<_, i64>("require_plan")? != 0,
247 plan_approved: r.get::<_, i64>("plan_approved")? != 0,
248 wip_sha: r.get("wip_sha")?,
249 pushed_sha: r.get("pushed_sha")?,
250 final_diff: r.get("final_diff")?,
251 commit_message: r.get("commit_message")?,
252 issue_number: r.get("issue_number")?,
253 plan_md: r.get("plan_md")?,
254 stop_requested: r.get::<_, i64>("stop_requested")? != 0,
255 })
256 }
257
258 pub fn get_task(&self, id: i64) -> Result<Option<Task>, String> {
259 self.with(|c| {
260 c.query_row("SELECT * FROM tasks WHERE id = ?", params![id], Self::row_to_task)
261 .optional()
262 })
263 }
264
265 pub fn list_tasks(&self, limit: i64) -> Result<Vec<Task>, String> {
266 self.with(|c| {
267 let mut st = c.prepare("SELECT * FROM tasks ORDER BY id DESC LIMIT ?")?;
268 let rows = st.query_map(params![limit], Self::row_to_task)?;
269 rows.collect::<rusqlite::Result<Vec<_>>>()
270 })
271 }
272
273 /// Oldest queued task (for the scheduler; `claim_queued` is the atomic
274 /// variant used by workers).
275 /// (`#[allow]` — kept as the non-atomic read for tests/debugging.)
276 #[allow(dead_code)]
277 pub fn next_queued(&self) -> Result<Option<Task>, String> {
278 self.with(|c| {
279 c.query_row(
280 "SELECT * FROM tasks WHERE status = 'queued' ORDER BY id ASC LIMIT 1",
281 [],
282 Self::row_to_task,
283 )
284 .optional()
285 })
286 }
287
288 /// Atomically claim the oldest queued task for `slot`: returns the task
289 /// if the claim won, `None` if another worker claimed it first.
290 pub fn claim_queued(&self, slot: u32) -> Result<Option<Task>, String> {
291 let conn = self.inner.lock().map_err(|e| format!("db lock: {e}"))?;
292 let now = now_unix();
293 let claimed: Option<Task> = (|| -> rusqlite::Result<Option<Task>> {
294 let tx_begin: Option<Task> = conn
295 .query_row(
296 "SELECT * FROM tasks WHERE status = 'queued' ORDER BY id ASC LIMIT 1",
297 [],
298 Self::row_to_task,
299 )
300 .optional()?;
301 let Some(task) = tx_begin else { return Ok(None) };
302 let n = conn.execute(
303 "UPDATE tasks SET status = 'running', slot = ?, started_at = ?, updated_at = ?
304 WHERE id = ? AND status = 'queued'",
305 params![slot as i64, now, now, task.id],
306 )?;
307 if n == 0 {
308 return Ok(None);
309 }
310 Ok(Some(conn.query_row(
311 "SELECT * FROM tasks WHERE id = ?",
312 params![task.id],
313 Self::row_to_task,
314 )?))
315 })()
316 .map_err(|e| format!("sqlite: {e}"))?;
317 Ok(claimed)
318 }
319
320 pub fn update_status(
321 &self,
322 id: i64,
323 status: TaskStatus,
324 error: Option<&str>,
325 summary: Option<&str>,
326 ) -> Result<(), String> {
327 let finished = if status.is_terminal() {
328 Some(now_unix())
329 } else {
330 None
331 };
332 self.with(|c| {
333 c.execute(
334 "UPDATE tasks SET status = ?, error = COALESCE(?, error), summary = COALESCE(?, summary),
335 updated_at = ?, finished_at = COALESCE(?, finished_at) WHERE id = ?",
336 params![status.as_str(), error, summary, now_unix(), finished, id],
337 )?;
338 Ok(())
339 })
340 }
341
342 /// Ids of tasks left `running` by a previous process (restart orphans).
343 pub fn interrupted_running_ids(&self) -> Result<Vec<i64>, String> {
344 self.with(|c| {
345 let mut st = c.prepare("SELECT id FROM tasks WHERE status = 'running' ORDER BY id ASC")?;
346 let rows = st.query_map([], |r| r.get(0))?;
347 rows.collect::<rusqlite::Result<Vec<i64>>>()
348 })
349 }
350
351 /// Set the "plan first" requirement + approval flag on a task.
352 pub fn set_plan_gate(&self, id: i64, require_plan: bool) -> Result<(), String> {
353 self.with(|c| {
354 c.execute(
355 "UPDATE tasks SET require_plan = ?, updated_at = ? WHERE id = ?",
356 params![require_plan as i64, now_unix(), id],
357 )?;
358 Ok(())
359 })
360 }
361
362 pub fn set_base_sha(&self, id: i64, sha: &str) -> Result<(), String> {
363 self.with(|c| {
364 c.execute(
365 "UPDATE tasks SET base_sha = ?, updated_at = ? WHERE id = ?",
366 params![sha, now_unix(), id],
367 )?;
368 Ok(())
369 })
370 }
371
372 pub fn set_finished_commit(
373 &self,
374 id: i64,
375 commit_sha: &str,
376 pushed: bool,
377 summary: &str,
378 ) -> Result<(), String> {
379 self.with(|c| {
380 c.execute(
381 "UPDATE tasks SET commit_sha = ?, pushed = ?, summary = ?, updated_at = ? WHERE id = ?",
382 params![commit_sha, pushed as i64, summary, now_unix(), id],
383 )?;
384 Ok(())
385 })
386 }
387
388 /// Store the proposed plan text (phase 4) without approving it.
389 pub fn set_plan_md(&self, id: i64, plan_md: &str) -> Result<(), String> {
390 self.with(|c| {
391 c.execute(
392 "UPDATE tasks SET plan_md = ?, updated_at = ? WHERE id = ?",
393 params![plan_md, now_unix(), id],
394 )?;
395 Ok(())
396 })
397 }
398
399 /// Mark the plan approved (operator route).
400 pub fn approve_plan(&self, id: i64) -> Result<(), String> {
401 self.with(|c| {
402 c.execute(
403 "UPDATE tasks SET plan_approved = 1, updated_at = ? WHERE id = ?",
404 params![now_unix(), id],
405 )?;
406 Ok(())
407 })
408 }
409
410 /// Store the validated `update_todos` list (raw `todos_json`).
411 pub fn set_todos(&self, id: i64, todos_json: &str) -> Result<(), String> {
412 self.with(|c| {
413 c.execute(
414 "UPDATE tasks SET todos_json = ?, updated_at = ? WHERE id = ?",
415 params![todos_json, now_unix(), id],
416 )?;
417 Ok(())
418 })
419 }
420
421 /// Merge freshly loaded rules into `rules_json` (path → content, or null
422 /// for "no file"). Existing entries win; returns nothing (callers read
423 /// back via `get_task` when they need the merged map).
424 pub fn merge_rules(
425 &self,
426 id: i64,
427 fresh: &std::collections::BTreeMap<String, Option<String>>,
428 ) -> Result<(), String> {
429 let current: Option<String> = self.with(|c| {
430 c.query_row(
431 "SELECT rules_json FROM tasks WHERE id = ?",
432 params![id],
433 |r| r.get(0),
434 )
435 })?;
436 let mut map: serde_json::Map<String, serde_json::Value> = current
437 .as_deref()
438 .map(serde_json::from_str)
439 .transpose()
440 .map_err(|e| format!("parse rules_json: {e}"))?
441 .unwrap_or_default();
442 for (path, content) in fresh {
443 map.entry(path.clone()).or_insert_with(|| match content {
444 Some(c) => serde_json::Value::String(c.clone()),
445 None => serde_json::Value::Null,
446 });
447 }
448 let merged = serde_json::Value::Object(map).to_string();
449 self.with(|c| {
450 c.execute(
451 "UPDATE tasks SET rules_json = ?, updated_at = ? WHERE id = ?",
452 params![merged, now_unix(), id],
453 )?;
454 Ok(())
455 })
456 }
457
458 /// Record the review snapshot at `finish` time: squashed-commit sha is
459 /// kept in `wip_sha` (the WIP ref), plus `final_diff`, `commit_message`
460 /// and `summary`.
461 pub fn set_review(
462 &self,
463 id: i64,
464 wip_sha: &str,
465 final_diff: &str,
466 commit_message: &str,
467 summary: &str,
468 ) -> Result<(), String> {
469 self.with(|c| {
470 c.execute(
471 "UPDATE tasks SET wip_sha = ?, final_diff = ?, commit_message = ?,
472 summary = ?, updated_at = ? WHERE id = ?",
473 params![wip_sha, final_diff, commit_message, summary, now_unix(), id],
474 )?;
475 Ok(())
476 })
477 }
478
479 /// Record a successful push: `pushed=1`, `pushed_sha`, `commit_sha`, and
480 /// `base_sha = pushed_sha` (follow-ups resume from the pushed tip with no
481 /// WIP). Clears `pending_json` and the stop flag; leaves status changes to
482 /// the caller.
483 /// Atomically claim a task in `review` for approval. Returns false if it
484 /// is not in review or another approve is already in flight, so double
485 /// clicks can never push (or comment on the issue) twice.
486 pub fn claim_approve(&self, id: i64) -> Result<bool, String> {
487 self.with(|c| {
488 let n = c.execute(
489 "UPDATE tasks SET approving = 1, updated_at = ?
490 WHERE id = ? AND status = 'review' AND approving = 0",
491 params![now_unix(), id],
492 )?;
493 Ok(n == 1)
494 })
495 }
496
497 /// End an approve attempt. If messages arrived while approving, re-queue
498 /// the task so they are handled (as review changes on failure, or as a
499 /// follow-up after a successful push).
500 pub fn finish_approve(&self, id: i64) -> Result<(), String> {
501 self.with(|c| {
502 c.execute(
503 "UPDATE tasks SET approving = 0, updated_at = ? WHERE id = ?",
504 params![now_unix(), id],
505 )?;
506 c.execute(
507 "UPDATE tasks SET status = 'queued', updated_at = ?
508 WHERE id = ? AND status IN ('review', 'succeeded')
509 AND EXISTS (SELECT 1 FROM inbox WHERE task_id = ?)",
510 params![now_unix(), id, id],
511 )?;
512 Ok(())
513 })
514 }
515
516 /// Clear approve claims left by a crashed process (startup only).
517 pub fn clear_stale_approving(&self) -> Result<usize, String> {
518 self.with(|c| c.execute("UPDATE tasks SET approving = 0 WHERE approving = 1", []))
519 }
520
521 pub fn set_pushed(&self, id: i64, pushed_sha: &str) -> Result<(), String> {
522 self.with(|c| {
523 c.execute(
524 "UPDATE tasks SET pushed = 1, pushed_sha = ?, commit_sha = ?,
525 base_sha = ?, wip_sha = NULL, pending_json = NULL, stop_requested = 0,
526 updated_at = ? WHERE id = ?",
527 params![pushed_sha, pushed_sha, pushed_sha, now_unix(), id],
528 )?;
529 Ok(())
530 })
531 }
532
533 pub fn add_usage(
534 &self,
535 id: i64,
536 steps: i64,
537 prompt_tokens: i64,
538 completion_tokens: i64,
539 cost_usd: f64,
540 ) -> Result<(), String> {
541 self.with(|c| {
542 c.execute(
543 "UPDATE tasks SET steps = steps + ?, prompt_tokens = prompt_tokens + ?,
544 completion_tokens = completion_tokens + ?, cost_usd = cost_usd + ?, updated_at = ?
545 WHERE id = ?",
546 params![steps, prompt_tokens, completion_tokens, cost_usd, now_unix(), id],
547 )?;
548 Ok(())
549 })
550 }
551
552 /// Add headroom after a `budget` park is answered: +20 steps, +$1.00.
553 pub fn extend_budget(&self, id: i64) -> Result<(), String> {
554 self.with(|c| {
555 c.execute(
556 "UPDATE tasks SET budget_steps = budget_steps + 20, budget_usd = budget_usd + 1.0,
557 updated_at = ? WHERE id = ?",
558 params![now_unix(), id],
559 )?;
560 Ok(())
561 })
562 }
563
564 pub fn request_stop(&self, id: i64) -> Result<(), String> {
565 self.with(|c| {
566 c.execute(
567 "UPDATE tasks SET stop_requested = 1, updated_at = ? WHERE id = ?",
568 params![now_unix(), id],
569 )?;
570 Ok(())
571 })
572 }
573
574 /// Atomically park a task and release its slot.
575 ///
576 /// Sets `status`, `pending_json`, `wip_sha`, `slot = NULL` and clears the
577 /// stop flag. Lost-wakeup fix: when the inbox already holds an unconsumed
578 /// user message, the task is set to `queued` instead so the worker loop
579 /// picks it up again (the message is the wakeup). Returns the status the
580 /// task was set to.
581 pub fn park_task(
582 &self,
583 id: i64,
584 status: TaskStatus,
585 pending: &Pending,
586 wip_sha: Option<&str>,
587 ) -> Result<TaskStatus, String> {
588 let conn = self.inner.lock().map_err(|e| format!("db lock: {e}"))?;
589 (|| -> rusqlite::Result<TaskStatus> {
590 conn.execute_batch("BEGIN IMMEDIATE")?;
591 let r = (|| -> rusqlite::Result<TaskStatus> {
592 let pending_s = serde_json::to_string(pending).map_err(|e| {
593 rusqlite::Error::FromSqlConversionFailure(
594 0,
595 rusqlite::types::Type::Text,
596 Box::new(e),
597 )
598 })?;
599 let inbox_n: i64 = conn.query_row(
600 "SELECT COUNT(*) FROM inbox WHERE task_id = ?",
601 params![id],
602 |row| row.get(0),
603 )?;
604 let effective = if inbox_n > 0 {
605 TaskStatus::Queued
606 } else {
607 status
608 };
609 conn.execute(
610 "UPDATE tasks SET status = ?, pending_json = ?, wip_sha = ?,
611 slot = NULL, stop_requested = 0, updated_at = ? WHERE id = ?",
612 params![
613 effective.as_str(),
614 pending_s,
615 wip_sha,
616 now_unix(),
617 id
618 ],
619 )?;
620 Ok(effective)
621 })();
622 match r {
623 Ok(s) => {
624 conn.execute_batch("COMMIT")?;
625 Ok(s)
626 }
627 Err(e) => {
628 let _ = conn.execute_batch("ROLLBACK");
629 Err(e)
630 }
631 }
632 })()
633 .map_err(|e| format!("sqlite: {e}"))
634 }
635
636 // ---- messages (persisted conversation) ----
637
638 /// Append one OpenRouter message (user / assistant / tool) to the stored
639 /// history. Returns the assigned `seq`.
640 pub fn append_message(
641 &self,
642 task_id: i64,
643 msg: &crate::openrouter::Message,
644 ) -> Result<i64, String> {
645 let body = serde_json::to_string(msg).map_err(|e| format!("serialize message: {e}"))?;
646 let conn = self.inner.lock().map_err(|e| format!("db lock: {e}"))?;
647 (|| -> rusqlite::Result<i64> {
648 let seq: i64 = conn.query_row(
649 "SELECT COALESCE(MAX(seq), -1) + 1 FROM messages WHERE task_id = ?",
650 params![task_id],
651 |r| r.get(0),
652 )?;
653 conn.execute(
654 "INSERT INTO messages (task_id, seq, body) VALUES (?, ?, ?)",
655 params![task_id, seq, body],
656 )?;
657 Ok(seq)
658 })()
659 .map_err(|e| format!("sqlite: {e}"))
660 }
661
662 /// Load the stored conversation in order. The system message is never
663 /// stored; the caller prepends the rebuilt one.
664 pub fn load_messages(&self, task_id: i64) -> Result<Vec<crate::openrouter::Message>, String> {
665 self.with(|c| {
666 let mut st = c.prepare(
667 "SELECT body FROM messages WHERE task_id = ? ORDER BY seq ASC LIMIT 10000",
668 )?;
669 let rows = st.query_map(params![task_id], |r| {
670 let body_s: String = r.get("body")?;
671 let msg: crate::openrouter::Message = serde_json::from_str(&body_s).map_err(|e| {
672 rusqlite::Error::FromSqlConversionFailure(
673 0,
674 rusqlite::types::Type::Text,
675 Box::new(e),
676 )
677 })?;
678 Ok(msg)
679 })?;
680 rows.collect::<rusqlite::Result<Vec<_>>>()
681 })
682 }
683
684 // ---- inbox (steering / answers) ----
685
686 /// Insert a user message and, in the SAME transaction, re-queue the task
687 /// when it is parked (`needs_input`), in `review`, or already `succeeded`
688 /// (follow-up). Returns `true` when the task was re-queued.
689 ///
690 /// Records `kind` on the inbox row (`plan_approve`, `plan_changes`,
691 /// `review_changes`; `""` = plain message) so the resume path can format
692 /// the pending tool-call answer.
693 pub fn inbox_post_kind(
694 &self,
695 task_id: i64,
696 text: &str,
697 kind: &str,
698 ) -> Result<bool, String> {
699 let conn = self.inner.lock().map_err(|e| format!("db lock: {e}"))?;
700 (|| -> rusqlite::Result<bool> {
701 conn.execute_batch("BEGIN IMMEDIATE")?;
702 let r = (|| -> rusqlite::Result<bool> {
703 conn.execute(
704 "INSERT INTO inbox (task_id, text, kind) VALUES (?, ?, ?)",
705 params![task_id, text, kind],
706 )?;
707 let row: Option<(String, i64)> = conn
708 .query_row(
709 "SELECT status, approving FROM tasks WHERE id = ?",
710 params![task_id],
711 |row| Ok((row.get(0)?, row.get(1)?)),
712 )
713 .optional()?;
714 // Parked tasks (needs_input/review) and succeeded tasks
715 // (follow-ups) re-queue on a new message. A task mid-approve
716 // keeps the message queued; `finish_approve` re-queues after.
717 let requeue = row
718 .filter(|(_, approving)| *approving == 0)
719 .and_then(|(s, _)| TaskStatus::parse(&s))
720 .map(|s| s.is_parked() || s == TaskStatus::Succeeded)
721 .unwrap_or(false);
722 if requeue {
723 conn.execute(
724 "UPDATE tasks SET status = 'queued', updated_at = ? WHERE id = ?",
725 params![now_unix(), task_id],
726 )?;
727 }
728 Ok(requeue)
729 })();
730 match r {
731 Ok(v) => {
732 conn.execute_batch("COMMIT")?;
733 Ok(v)
734 }
735 Err(e) => {
736 let _ = conn.execute_batch("ROLLBACK");
737 Err(e)
738 }
739 }
740 })()
741 .map_err(|e| format!("sqlite: {e}"))
742 }
743
744 /// Atomically take all unconsumed inbox rows (ordered) and delete them,
745 /// so concurrent consumers can never double-deliver. Returns untagged
746 /// text; use [`Store::drain_inbox_tagged`] for the [`InboxRow`] kinds.
747 pub fn drain_inbox(&self, task_id: i64) -> Result<Vec<String>, String> {
748 Ok(self
749 .drain_inbox_tagged(task_id)?
750 .into_iter()
751 .map(|r| r.text)
752 .collect())
753 }
754
755 /// Tagged variant of [`Store::drain_inbox`].
756 pub fn drain_inbox_tagged(&self, task_id: i64) -> Result<Vec<InboxRow>, String> {
757 let conn = self.inner.lock().map_err(|e| format!("db lock: {e}"))?;
758 (|| -> rusqlite::Result<Vec<InboxRow>> {
759 conn.execute_batch("BEGIN IMMEDIATE")?;
760 let r = (|| -> rusqlite::Result<Vec<InboxRow>> {
761 let mut st = conn.prepare(
762 "SELECT id, text, COALESCE(kind, '') FROM inbox WHERE task_id = ? ORDER BY id ASC",
763 )?;
764 let rows: Vec<(i64, String, String)> = st
765 .query_map(params![task_id], |row| {
766 Ok((row.get(0)?, row.get(1)?, row.get(2)?))
767 })?
768 .collect::<rusqlite::Result<Vec<_>>>()?;
769 if !rows.is_empty() {
770 let ids: Vec<String> = rows.iter().map(|(id, _, _)| id.to_string()).collect();
771 conn.execute(
772 &format!("DELETE FROM inbox WHERE id IN ({})", ids.join(",")),
773 [],
774 )?;
775 }
776 Ok(rows
777 .into_iter()
778 .map(|(_, text, kind)| InboxRow { text, kind })
779 .collect())
780 })();
781 match r {
782 Ok(v) => {
783 conn.execute_batch("COMMIT")?;
784 Ok(v)
785 }
786 Err(e) => {
787 let _ = conn.execute_batch("ROLLBACK");
788 Err(e)
789 }
790 }
791 })()
792 .map_err(|e| format!("sqlite: {e}"))
793 }
794
795 // ---- events ----
796
797 /// Append an event; assigns the next per-task `seq`.
798 pub fn push_event(
799 &self,
800 task_id: i64,
801 kind: &str,
802 body: &serde_json::Value,
803 ) -> Result<Event, String> {
804 let conn = self.inner.lock().map_err(|e| format!("db lock: {e}"))?;
805 (|| -> rusqlite::Result<Event> {
806 let seq: i64 = conn.query_row(
807 "SELECT COALESCE(MAX(seq), -1) + 1 FROM events WHERE task_id = ?",
808 params![task_id],
809 |r| r.get(0),
810 )?;
811 let body_s = serde_json::to_string(body).unwrap_or_else(|_| "{}".to_string());
812 let ts = now_unix();
813 conn.execute(
814 "INSERT INTO events (task_id, seq, ts, kind, body) VALUES (?, ?, ?, ?, ?)",
815 params![task_id, seq, ts, kind, body_s],
816 )?;
817 let id = conn.last_insert_rowid();
818 Ok(Event {
819 id,
820 task_id,
821 seq,
822 ts,
823 kind: kind.to_string(),
824 body: body.clone(),
825 })
826 })()
827 .map_err(|e| format!("sqlite: {e}"))
828 }
829
830 pub fn list_events(&self, task_id: i64, after_seq: Option<i64>) -> Result<Vec<Event>, String> {
831 self.with(|c| {
832 let mut st = c.prepare(
833 "SELECT id, task_id, seq, ts, kind, body FROM events
834 WHERE task_id = ? AND seq > COALESCE(?, -1) ORDER BY seq ASC LIMIT 2000",
835 )?;
836 let rows = st.query_map(params![task_id, after_seq], |r| {
837 let body_s: String = r.get("body")?;
838 let body: serde_json::Value =
839 serde_json::from_str(&body_s).unwrap_or(serde_json::Value::Null);
840 Ok(Event {
841 id: r.get("id")?,
842 task_id: r.get("task_id")?,
843 seq: r.get("seq")?,
844 ts: r.get("ts")?,
845 kind: r.get("kind")?,
846 body,
847 })
848 })?;
849 rows.collect::<rusqlite::Result<Vec<_>>>()
850 })
851 }
852
853 // ---- sessions ----
854
855 pub fn put_session(&self, token_sha_hex: &str, expires_at: i64) -> Result<(), String> {
856 self.with(|c| {
857 c.execute(
858 "INSERT OR REPLACE INTO sessions (token_sha256_hex, expires_at) VALUES (?, ?)",
859 params![token_sha_hex, expires_at],
860 )?;
861 Ok(())
862 })
863 }
864
865 pub fn session_valid(&self, token_sha_hex: &str, now: i64) -> Result<bool, String> {
866 self.with(|c| {
867 let exp: Option<i64> = c
868 .query_row(
869 "SELECT expires_at FROM sessions WHERE token_sha256_hex = ?",
870 params![token_sha_hex],
871 |r| r.get(0),
872 )
873 .optional()?;
874 match exp {
875 Some(e) if e > now => Ok(true),
876 _ => {
877 // Best-effort cleanup of the presented (dead) token.
878 let _ = c.execute(
879 "DELETE FROM sessions WHERE token_sha256_hex = ?",
880 params![token_sha_hex],
881 );
882 Ok(false)
883 }
884 }
885 })
886 }
887
888 pub fn delete_session(&self, token_sha_hex: &str) -> Result<(), String> {
889 self.with(|c| {
890 c.execute(
891 "DELETE FROM sessions WHERE token_sha256_hex = ?",
892 params![token_sha_hex],
893 )?;
894 Ok(())
895 })
896 }
897
898 pub fn purge_expired_sessions(&self, now: i64) -> Result<(), String> {
899 self.with(|c| {
900 c.execute("DELETE FROM sessions WHERE expires_at <= ?", params![now])?;
901 Ok(())
902 })
903 }
904
905 // ---- kv (small persistent key/value: triage watermark, ...) ----
906
907 pub fn kv_get(&self, key: &str) -> Result<Option<String>, String> {
908 self.with(|c| {
909 c.query_row(
910 "SELECT value FROM kv WHERE key = ?",
911 params![key],
912 |r| r.get(0),
913 )
914 .optional()
915 })
916 }
917
918 pub fn kv_set(&self, key: &str, value: &str) -> Result<(), String> {
919 self.with(|c| {
920 c.execute(
921 "INSERT INTO kv (key, value) VALUES (?, ?)
922 ON CONFLICT(key) DO UPDATE SET value = excluded.value",
923 params![key, value],
924 )?;
925 Ok(())
926 })
927 }
928
929 // ---- triage (issue → triage task idempotency + results) ----
930
931 /// Record that `issue` is being triaged by `task_id`. Returns false when a
932 /// row already exists (the caller then skips the issue).
933 pub fn triage_insert(&self, issue: u64, task_id: i64) -> Result<bool, String> {
934 self.with(|c| {
935 let n = c.execute(
936 "INSERT OR IGNORE INTO triage (issue_number, task_id, status, created_at)
937 VALUES (?, ?, 'queued', ?)",
938 params![issue as i64, task_id, now_unix()],
939 )?;
940 Ok(n == 1)
941 })
942 }
943
944 pub fn triage_get(&self, issue: u64) -> Result<Option<TriageRow>, String> {
945 self.with(|c| {
946 c.query_row(
947 "SELECT issue_number, task_id, status, created_at, result_json
948 FROM triage WHERE issue_number = ?",
949 params![issue as i64],
950 |r| {
951 Ok(TriageRow {
952 issue_number: r.get::<_, i64>(0)? as u64,
953 task_id: r.get(1)?,
954 status: r.get(2)?,
955 created_at: r.get(3)?,
956 result_json: r.get(4)?,
957 })
958 },
959 )
960 .optional()
961 })
962 }
963
964 /// Store the triage outcome (`status`: e.g. `done` / `low_confidence` /
965 /// `failed`; `result_json`: serialized [`crate::triage::TriageResult`]).
966 pub fn triage_set_result(
967 &self,
968 issue: u64,
969 status: &str,
970 result_json: Option<&str>,
971 ) -> Result<(), String> {
972 self.with(|c| {
973 c.execute(
974 "UPDATE triage SET status = ?, result_json = ? WHERE issue_number = ?",
975 params![status, result_json, issue as i64],
976 )?;
977 Ok(())
978 })
979 }
980
981 /// Newest triage rows first (for the dashboard badge list; the driver
982 /// worker's UI comes later).
983 pub fn triage_recent(&self, limit: i64) -> Result<Vec<TriageRow>, String> {
984 self.with(|c| {
985 let mut st = c.prepare(
986 "SELECT issue_number, task_id, status, created_at, result_json
987 FROM triage ORDER BY issue_number DESC LIMIT ?",
988 )?;
989 let rows = st.query_map(params![limit], |r| {
990 Ok(TriageRow {
991 issue_number: r.get::<_, i64>(0)? as u64,
992 task_id: r.get(1)?,
993 status: r.get(2)?,
994 created_at: r.get(3)?,
995 result_json: r.get(4)?,
996 })
997 })?;
998 rows.collect::<rusqlite::Result<Vec<_>>>()
999 })
1000 }
1001
1002 /// Create a `triage`-kind task for `issue_number`: read-only, 40 steps /
1003 /// $0.50, no plan gate, linked to the issue. Returns the task id.
1004 pub fn create_triage_task(
1005 &self,
1006 issue_number: u64,
1007 title: &str,
1008 prompt: &str,
1009 module_scope: &str,
1010 model: &str,
1011 ) -> Result<i64, String> {
1012 let now = now_unix();
1013 self.with(|c| {
1014 c.execute(
1015 "INSERT INTO tasks (title, prompt, module_scope, model, status, kind,
1016 created_at, updated_at, budget_steps, budget_usd, require_plan, issue_number)
1017 VALUES (?, ?, ?, ?, 'queued', 'triage', ?, ?, 40, 0.50, 0, ?)",
1018 params![title, prompt, module_scope, model, now, now, issue_number as i64],
1019 )?;
1020 Ok(c.last_insert_rowid())
1021 })
1022 }
1023}
1024
1025/// One row of the `triage` table: which task triages an issue, its status,
1026/// and (once finished) the JSON result.
1027#[derive(Debug, Clone, PartialEq, Eq)]
1028pub struct TriageRow {
1029 pub issue_number: u64,
1030 pub task_id: i64,
1031 pub status: String,
1032 pub created_at: i64,
1033 pub result_json: Option<String>,
1034}