Skip to main content

orch/store/tasks/
mod.rs

1/// The SQL behind each replicated task write, run with the proposer's time
2pub(crate) mod apply;
3mod cli_ref;
4mod fields;
5mod queries;
6mod runs;
7
8use super::{Context, MemoryEntry, SqlitePool, TaskStore};
9use crate::security;
10use crate::store::Command;
11use crate::store::now_stamp;
12pub use cli_ref::{CliTaskRef, CliTaskSpec, parse_cli_task_spec};
13use serde::{Deserialize, Serialize};
14use sqlx::Row;
15use sqlx::sqlite::SqliteRow;
16
17/// Explicit column list for `SELECT` queries on the `tasks` table.
18///
19/// Using `SELECT *` with `sqlx-sqlite`'s persistent prepared statements can
20/// cause OOB panics when the schema changes (new migration columns) because
21/// `sqlite3_column_count()` returns the updated count but the cached column
22/// metadata vector was built at prepare time. Explicit columns prevent the
23/// mismatch.
24pub(crate) const TASK_COLS: &str = "id, external_id, repo, origin, title, body, status, \
25    source, source_id, author, url, labels, agent, model, complexity, estimate, \
26    route_reason, agent_profile, route_attempts, attempts, \
27    branch, worktree, worktree_cleaned, summary, last_error, parent_id, \
28    block_reason, pr_number, pr_review_context, last_review_ts, review_ts_map, \
29    last_comment_review_ts, merge_conflict_retries, ci_merge_failures, \
30    pr_create_failures, review_agent_failures, review_resets, review_cycles, input_tokens, \
31    output_tokens, input_cost_usd, output_cost_usd, total_cost_usd, \
32    model_reroute_chain, limit_reroute_chain, \
33    memory, delegations, created_at, updated_at, \
34     review_invocations, needs_review_refires, push_failures, auto_unblock_count, auto_unblock_last_at, \
35     ci_recovery_count, auto_unblock_last_reason, no_code_reroutes, network_retries, no_code_last_agent, \
36     owner_node, timeout_retries";
37
38/// Number of columns in TASK_COLS (used for diagnostic verification).
39pub(crate) const TASK_COLS_COUNT: usize = 61;
40
41/// Explicit column list for `SELECT` queries on the `task_runs` table.
42const TASK_RUN_COLS: &str = "id, task_id, attempt, run_type, agent, model, command, prompt, env_vars, \
43    exit_code, stdout, stderr, parsed_response, outcome, error, input_tokens, output_tokens, \
44    total_cost_usd, duration_secs, started_at, completed_at";
45
46/// Explicit column list for `SELECT` queries on the `task_activity` table.
47const TASK_ACTIVITY_COLS: &str =
48    "id, task_id, timestamp, event_type, from_status, to_status, agent, model, details";
49
50/// Allowlist of columns that can be updated via `set_fields` and `batch_set_fields`.
51const ALLOWED_FIELDS: &[&str] = &[
52    "agent",
53    "model",
54    "complexity",
55    "route_reason",
56    "agent_profile",
57    "route_attempts",
58    "attempts",
59    "branch",
60    "worktree",
61    "worktree_cleaned",
62    "owner_node",
63    "summary",
64    "last_error",
65    "parent_id",
66    "block_reason",
67    "pr_number",
68    "pr_review_context",
69    "last_review_ts",
70    "review_ts_map",
71    "last_comment_review_ts",
72    "merge_conflict_retries",
73    "ci_merge_failures",
74    "pr_create_failures",
75    "push_failures",
76    "review_agent_failures",
77    "review_resets",
78    "review_cycles",
79    "review_invocations",
80    "needs_review_refires",
81    "input_tokens",
82    "output_tokens",
83    "input_cost_usd",
84    "output_cost_usd",
85    "total_cost_usd",
86    "model_reroute_chain",
87    "limit_reroute_chain",
88    "memory",
89    "delegations",
90    "source",
91    "source_id",
92    "labels",
93    "auto_unblock_count",
94    "auto_unblock_last_at",
95    "auto_unblock_last_reason",
96    "ci_recovery_count",
97    "no_code_reroutes",
98    "network_retries",
99    "timeout_retries",
100    "no_code_last_agent",
101];
102
103/// Allowlist of fields that can be incremented via `increment` and `batch_increment`.
104const INCREMENTABLE_FIELDS: &[&str] = &[
105    "attempts",
106    "route_attempts",
107    "merge_conflict_retries",
108    "ci_merge_failures",
109    "pr_create_failures",
110    "push_failures",
111    "review_agent_failures",
112    "review_resets",
113    "review_cycles",
114    "review_invocations",
115    "needs_review_refires",
116    "auto_unblock_count",
117    "ci_recovery_count",
118    "no_code_reroutes",
119    "network_retries",
120    "timeout_retries",
121];
122
123fn sanitize_activity_details(value: &serde_json::Value) -> serde_json::Value {
124    match value {
125        serde_json::Value::String(text) => serde_json::Value::String(security::redact(text)),
126        serde_json::Value::Array(items) => serde_json::Value::Array(
127            items
128                .iter()
129                .map(sanitize_activity_details)
130                .collect::<Vec<_>>(),
131        ),
132        serde_json::Value::Object(map) => serde_json::Value::Object(
133            map.iter()
134                .map(|(key, value)| (key.clone(), sanitize_activity_details(value)))
135                .collect(),
136        ),
137        other => other.clone(),
138    }
139}
140
141fn sanitize_task_field_value(col: &str, value: &serde_json::Value) -> serde_json::Value {
142    match (col, value) {
143        ("last_error" | "block_reason", serde_json::Value::String(text)) => {
144            serde_json::Value::String(security::redact(text))
145        }
146        _ => value.clone(),
147    }
148}
149
150fn sql_value_for_task_field(
151    col: &str,
152    value: &serde_json::Value,
153) -> anyhow::Result<Option<String>> {
154    let sanitized = sanitize_task_field_value(col, value);
155    match sanitized {
156        serde_json::Value::String(text) => Ok(Some(text)),
157        serde_json::Value::Number(number) => Ok(Some(number.to_string())),
158        serde_json::Value::Bool(boolean) => Ok(Some(if boolean { "1" } else { "0" }.to_string())),
159        serde_json::Value::Null => Ok(None),
160        other => Ok(Some(serde_json::to_string(&other)?)),
161    }
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
165#[serde(rename_all = "snake_case")]
166pub enum TaskStatus {
167    New,
168    Routed,
169    InProgress,
170    Done,
171    Blocked,
172    InReview,
173    Approved,
174    NeedsReview,
175    Waiting,
176}
177
178impl TaskStatus {
179    pub fn as_str(&self) -> &'static str {
180        match self {
181            Self::New => "new",
182            Self::Routed => "routed",
183            Self::InProgress => "in_progress",
184            Self::Done => "done",
185            Self::Blocked => "blocked",
186            Self::InReview => "in_review",
187            Self::Approved => "approved",
188            Self::NeedsReview => "needs_review",
189            Self::Waiting => "waiting",
190        }
191    }
192
193    pub fn from_str(s: &str) -> Option<Self> {
194        match s {
195            "new" => Some(Self::New),
196            "routed" => Some(Self::Routed),
197            "in_progress" => Some(Self::InProgress),
198            "done" => Some(Self::Done),
199            "blocked" => Some(Self::Blocked),
200            "in_review" => Some(Self::InReview),
201            "approved" => Some(Self::Approved),
202            "needs_review" => Some(Self::NeedsReview),
203            "waiting" => Some(Self::Waiting),
204            _ => None,
205        }
206    }
207}
208
209/// Unified task record — single row in the `tasks` table.
210#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct Task {
212    pub id: i64,
213    pub external_id: Option<String>,
214    pub repo: String,
215    pub origin: String,
216
217    pub title: String,
218    pub body: String,
219    pub status: TaskStatus,
220    pub source: String,
221    pub source_id: String,
222    pub author: String,
223    pub url: String,
224    pub labels: Vec<String>,
225
226    // Routing
227    pub agent: Option<String>,
228    pub model: Option<String>,
229    pub complexity: String,
230    /// Fibonacci effort estimate (1, 2, 3, 5, 8, 13, or 21). 0 means not provided.
231    pub estimate: u8,
232    pub route_reason: String,
233    pub agent_profile: String,
234    pub route_attempts: i32,
235
236    // Execution
237    pub attempts: i32,
238    pub branch: String,
239    pub worktree: String,
240    pub worktree_cleaned: bool,
241    /// The node that runs the task, None until one starts it
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub owner_node: Option<String>,
244    pub summary: String,
245    pub last_error: String,
246    pub parent_id: Option<i64>,
247    pub block_reason: Option<String>,
248
249    // PR Review
250    pub pr_number: Option<i32>,
251    pub pr_review_context: String,
252    pub last_review_ts: String,
253    pub review_ts_map: String,
254    pub last_comment_review_ts: String,
255    pub merge_conflict_retries: i32,
256    pub ci_merge_failures: i32,
257    pub pr_create_failures: i32,
258    pub push_failures: i32,
259    pub network_retries: i32,
260    /// Runs that ended in a timeout, reset by retry.
261    pub timeout_retries: i32,
262    pub review_agent_failures: i32,
263    // Review retries that ended without a decision and without counting as a failure
264    pub review_resets: i32,
265    pub review_cycles: i32,
266    pub review_invocations: i32,
267    // NeedsReview re-fire counter (incremented by sync catch-up and reset on successful review cycles)
268    pub needs_review_refires: i32,
269
270    // Tokens & Cost
271    pub input_tokens: i64,
272    pub output_tokens: i64,
273    // Sum of the costs the task's runs reported, 0 when none did
274    pub total_cost_usd: f64,
275
276    // Recovery
277    pub model_reroute_chain: String,
278    pub limit_reroute_chain: String,
279
280    // Structured data
281    pub memory: Vec<MemoryEntry>,
282    pub delegations: Vec<serde_json::Value>,
283
284    // Auto-unblock tracking
285    pub auto_unblock_count: i32,
286    pub auto_unblock_last_at: String,
287    pub auto_unblock_last_reason: String,
288
289    // CI-based auto-recovery tracking (separate from auto_unblock_count)
290    pub ci_recovery_count: i32,
291
292    // Done-without-PR circuit breaker
293    pub no_code_reroutes: i32,
294    /// Which agent produced the last no-code failure (used to detect same-agent loops).
295    pub no_code_last_agent: String,
296
297    // Timestamps
298    pub created_at: String,
299    pub updated_at: String,
300}
301
302impl Task {
303    /// The cost the task's runs reported, `None` when no run reported one.
304    pub fn reported_cost_usd(&self) -> Option<f64> {
305        (self.total_cost_usd > 0.0).then_some(self.total_cost_usd)
306    }
307}
308
309/// Parameters for creating a new task.
310#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
311pub struct NewTask {
312    pub external_id: Option<String>,
313    pub repo: String,
314    pub origin: String,
315    pub title: String,
316    pub body: String,
317    pub source: String,
318    pub source_id: String,
319    pub author: String,
320    pub url: String,
321    pub labels: Vec<String>,
322    /// Optional link to a parent task (e.g. the issue/PR a mention was posted on).
323    pub parent_id: Option<i64>,
324}
325
326/// A single run (agent execution, review, or routing attempt).
327#[derive(Debug, Clone, Serialize, Deserialize)]
328pub struct TaskRun {
329    pub id: i64,
330    pub task_id: i64,
331    pub attempt: i32,
332    pub run_type: String,
333    pub agent: String,
334    pub model: String,
335    pub command: String,
336    pub prompt: String,
337    pub env_vars: String,
338    pub exit_code: Option<i32>,
339    pub stdout: String,
340    pub stderr: String,
341    pub parsed_response: String,
342    pub outcome: String,
343    pub error: String,
344    pub input_tokens: i64,
345    pub output_tokens: i64,
346    pub total_cost_usd: f64,
347    pub duration_secs: f64,
348    pub started_at: String,
349    pub completed_at: Option<String>,
350}
351
352/// A single task lifecycle activity event.
353#[derive(Debug, Clone, Serialize, Deserialize)]
354pub struct TaskActivity {
355    pub id: i64,
356    pub task_id: i64,
357    pub timestamp: String,
358    pub event_type: String,
359    pub from_status: Option<String>,
360    pub to_status: Option<String>,
361    pub agent: Option<String>,
362    pub model: Option<String>,
363    pub details: serde_json::Value,
364}
365
366/// A task reaching done, with what cycle time and first-try counts need
367#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
368pub struct MergedEvent {
369    pub at: String,
370    pub task_id: i64,
371    pub repo: String,
372    pub agent: Option<String>,
373    pub created_at: String,
374    pub attempts: i32,
375    pub review_cycles: i32,
376}
377
378/// A task entering blocked
379#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
380pub struct BlockedEvent {
381    pub at: String,
382    pub task_id: i64,
383    pub repo: String,
384}
385
386/// One agent run, for time spent per agent and project
387#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
388pub struct RunEvent {
389    pub at: Option<String>,
390    pub repo: String,
391    pub agent: Option<String>,
392    pub model: Option<String>,
393    pub run_type: Option<String>,
394    pub outcome: Option<String>,
395    pub duration_secs: f64,
396}
397
398/// What the statistics page counts over a window
399#[derive(Debug, Clone, Serialize)]
400pub struct StatsEvents {
401    pub merged: Vec<MergedEvent>,
402    pub blocked: Vec<BlockedEvent>,
403    pub runs: Vec<RunEvent>,
404}
405
406/// A task moving between statuses, with what a feed needs to name it
407#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
408pub struct StatusChange {
409    pub timestamp: String,
410    pub task_id: i64,
411    pub repo: String,
412    pub external_id: Option<String>,
413    pub title: String,
414    pub from_status: Option<String>,
415    pub to_status: Option<String>,
416    pub agent: Option<String>,
417}
418
419/// Token usage for a run.
420#[derive(Debug, Clone, Copy, Default)]
421pub struct RunTokenUsage {
422    pub input_tokens: u64,
423    pub output_tokens: u64,
424    pub total_cost_usd: f64,
425    pub duration_secs: f64,
426}
427
428/// Parameters for starting a new run.
429#[derive(Debug, Clone)]
430pub struct StartRun<'a> {
431    pub task_id: i64,
432    pub attempt: i32,
433    pub run_type: &'a str,
434    pub agent: &'a str,
435    pub model: &'a str,
436    pub command: &'a str,
437    pub prompt: &'a str,
438}
439
440/// Parameters for completing a run.
441#[derive(Debug, Clone)]
442pub struct CompleteRun<'a> {
443    pub run_id: i64,
444    pub exit_code: Option<i32>,
445    pub stdout: &'a str,
446    pub stderr: &'a str,
447    pub parsed: &'a str,
448    pub outcome: &'a str,
449    pub error: &'a str,
450    pub tokens: RunTokenUsage,
451}
452
453/// Parameters for storing a route result.
454#[derive(Debug, Clone)]
455pub struct StoreRoute<'a> {
456    pub id: i64,
457    pub agent: &'a str,
458    pub model: Option<&'a str>,
459    pub complexity: &'a str,
460    /// Fibonacci effort estimate (1, 2, 3, 5, 8, 13, or 21). 0 means not provided.
461    pub estimate: u8,
462    pub reason: &'a str,
463    pub profile: &'a str,
464}
465
466/// Parameters for upserting an external task.
467#[derive(Debug, Clone)]
468pub struct UpsertExternal<'a> {
469    pub repo: &'a str,
470    pub ext_id: &'a str,
471    pub title: &'a str,
472    pub body: &'a str,
473    pub author: &'a str,
474    pub url: &'a str,
475    pub labels: &'a [String],
476    pub origin: &'a str,
477}
478
479fn parent_external_id_from_labels(labels: &[String]) -> Option<&str> {
480    labels
481        .iter()
482        .find_map(|label| label.strip_prefix("parent:"))
483        .filter(|parent| !parent.is_empty())
484}
485
486fn owned_updates(
487    updates: &[(&str, serde_json::Value)],
488) -> anyhow::Result<Vec<(String, serde_json::Value)>> {
489    updates
490        .iter()
491        .map(|(col, val)| {
492            anyhow::ensure!(
493                ALLOWED_FIELDS.contains(col),
494                "column {col} is not in the update allowlist"
495            );
496            Ok((col.to_string(), val.clone()))
497        })
498        .collect()
499}
500
501impl TaskStore {
502    /// Append a lifecycle activity event for a task.
503    #[expect(
504        clippy::too_many_arguments,
505        reason = "one argument per column of the activity row"
506    )]
507    pub async fn append_activity(
508        &self,
509        task_id: i64,
510        event_type: &str,
511        from_status: Option<&str>,
512        to_status: Option<&str>,
513        agent: Option<&str>,
514        model: Option<&str>,
515        details: Option<&serde_json::Value>,
516    ) -> anyhow::Result<()> {
517        let details_json = match details {
518            Some(v) => serde_json::to_string(&sanitize_activity_details(v))?,
519            None => "{}".to_string(),
520        };
521        sqlx::query(
522            "INSERT INTO task_activity
523             (task_id, event_type, from_status, to_status, agent, model, details)
524             VALUES (?, ?, ?, ?, ?, ?, ?)",
525        )
526        .bind(task_id)
527        .bind(event_type)
528        .bind(from_status)
529        .bind(to_status)
530        .bind(agent)
531        .bind(model)
532        .bind(details_json)
533        .execute(&self.pool)
534        .await?;
535        Ok(())
536    }
537
538    /// When the task last entered `status`
539    pub async fn status_entered_at(
540        &self,
541        task_id: i64,
542        status: TaskStatus,
543    ) -> anyhow::Result<Option<String>> {
544        let row: Option<(String,)> = sqlx::query_as(
545            "SELECT timestamp FROM task_activity
546             WHERE task_id = ? AND event_type = 'status_change' AND to_status = ?
547             ORDER BY id DESC LIMIT 1",
548        )
549        .bind(task_id)
550        .bind(status.as_str())
551        .fetch_optional(&self.pool)
552        .await?;
553        Ok(row.map(|(ts,)| ts))
554    }
555
556    /// When the task last entered in_review, and whether a review decision was recorded since
557    pub async fn in_review_entry(&self, task_id: i64) -> anyhow::Result<Option<(String, bool)>> {
558        let row: Option<(String, bool)> = sqlx::query_as(
559            "SELECT a.timestamp, EXISTS (
560                 SELECT 1 FROM task_activity d
561                 WHERE d.task_id = a.task_id AND d.event_type = 'review_decision' AND d.id > a.id
562             )
563             FROM task_activity a
564             WHERE a.task_id = ? AND a.event_type = 'status_change' AND a.to_status = 'in_review'
565             ORDER BY a.id DESC LIMIT 1",
566        )
567        .bind(task_id)
568        .fetch_optional(&self.pool)
569        .await?;
570        Ok(row)
571    }
572
573    /// Get task activity timeline in chronological order.
574    pub async fn get_activity(
575        &self,
576        task_id: i64,
577        limit: Option<usize>,
578    ) -> anyhow::Result<Vec<TaskActivity>> {
579        let rows = if let Some(limit) = limit {
580            let limit_i64 = i64::try_from(limit).unwrap_or(i64::MAX);
581            sqlx::query(sqlx::AssertSqlSafe(format!(
582                "SELECT {TASK_ACTIVITY_COLS} FROM task_activity WHERE task_id = ? ORDER BY timestamp ASC, id ASC LIMIT ?"
583            )))
584            .bind(task_id)
585            .bind(limit_i64)
586            .fetch_all(&self.pool)
587            .await?
588        } else {
589            sqlx::query(sqlx::AssertSqlSafe(format!(
590                "SELECT {TASK_ACTIVITY_COLS} FROM task_activity WHERE task_id = ? ORDER BY timestamp ASC, id ASC"
591            )))
592            .bind(task_id)
593            .fetch_all(&self.pool)
594            .await?
595        };
596
597        rows.iter().map(Self::row_to_activity).collect()
598    }
599
600    pub async fn create(&self, new: &NewTask) -> anyhow::Result<i64> {
601        self.write_int(Command::TaskCreate {
602            new: new.clone(),
603            internal: false,
604        })
605        .await
606    }
607
608    /// Create an internal task, returning its auto-generated ID.
609    ///
610    /// Convenience wrapper around `create()` that sets origin = "internal"
611    /// and generates `external_id = "internal:{id}"` after creation.
612    pub async fn create_internal(
613        &self,
614        repo: &str,
615        title: &str,
616        body: &str,
617        source: &str,
618        source_id: &str,
619        parent_id: Option<i64>,
620    ) -> anyhow::Result<i64> {
621        let new = NewTask {
622            external_id: None,
623            repo: repo.to_string(),
624            origin: "internal".to_string(),
625            title: title.to_string(),
626            body: body.to_string(),
627            source: source.to_string(),
628            source_id: source_id.to_string(),
629            author: String::new(),
630            url: String::new(),
631            labels: vec![],
632            parent_id,
633        };
634        self.write_int(Command::TaskCreate {
635            new,
636            internal: true,
637        })
638        .await
639    }
640
641    /// An internal task born with its labels, so a hold label is there before any tick reads it
642    pub async fn create_internal_labeled(
643        &self,
644        repo: &str,
645        title: &str,
646        body: &str,
647        source: &str,
648        labels: Vec<String>,
649    ) -> anyhow::Result<i64> {
650        let new = NewTask {
651            external_id: None,
652            repo: repo.to_string(),
653            origin: "internal".to_string(),
654            title: title.to_string(),
655            body: body.to_string(),
656            source: source.to_string(),
657            source_id: source.to_string(),
658            author: String::new(),
659            url: String::new(),
660            labels,
661            parent_id: None,
662        };
663        self.write_int(Command::TaskCreate {
664            new,
665            internal: true,
666        })
667        .await
668    }
669
670    /// Get a task by its internal ID.
671    pub async fn get(&self, id: i64) -> anyhow::Result<Task> {
672        let row = sqlx::query(sqlx::AssertSqlSafe(format!(
673            "SELECT {TASK_COLS} FROM tasks WHERE id = ?"
674        )))
675        .bind(id)
676        .fetch_optional(&self.pool)
677        .await?
678        .with_context(|| format!("task {id} not found"))?;
679
680        Self::row_to_task(&row)
681    }
682
683    /// Get a task by its external ID within a repo.
684    pub async fn get_by_external_id(
685        &self,
686        repo: &str,
687        ext_id: &str,
688    ) -> anyhow::Result<Option<Task>> {
689        let row = sqlx::query(sqlx::AssertSqlSafe(format!(
690            "SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND external_id = ?"
691        )))
692        .bind(repo)
693        .bind(ext_id)
694        .fetch_optional(&self.pool)
695        .await?;
696
697        match row {
698            Some(r) => Ok(Some(Self::row_to_task(&r)?)),
699            None => Ok(None),
700        }
701    }
702
703    /// Lightweight lookup: return only the numeric `id` for a given repo + external_id.
704    ///
705    /// Many call sites only need the internal store ID and were previously calling
706    /// `get_by_external_id()` which deserializes the full 60-column `Task` row. This
707    /// method avoids that work by selecting only `id`.
708    pub async fn resolve_id_by_external(
709        &self,
710        repo: &str,
711        ext_id: &str,
712    ) -> anyhow::Result<Option<i64>> {
713        let row = sqlx::query("SELECT id FROM tasks WHERE repo = ? AND external_id = ?")
714            .bind(repo)
715            .bind(ext_id)
716            .fetch_optional(&self.pool)
717            .await?;
718        let id = row.map(|r| r.try_get::<i64, _>("id")).transpose()?;
719        Ok(id)
720    }
721
722    /// The task whose worktree on this node is `path`
723    pub async fn resolve_id_by_worktree(&self, path: &str) -> anyhow::Result<Option<i64>> {
724        if path.is_empty() {
725            return Ok(None);
726        }
727
728        let row = sqlx::query("SELECT id FROM tasks WHERE worktree = ? LIMIT 1")
729            .bind(path)
730            .fetch_optional(&self.pool)
731            .await?;
732        Ok(row.map(|r| r.try_get::<i64, _>("id")).transpose()?)
733    }
734
735    /// Resolve the parent task ID by PR number.
736    ///
737    /// When a mention arrives on a PR, we need to find the issue task that owns
738    /// this PR. The task store tracks `pr_number` on tasks, so we look up the
739    /// task whose `pr_number` matches the given PR number.
740    pub async fn resolve_id_by_pr_number(
741        &self,
742        repo: &str,
743        pr_number: i32,
744    ) -> anyhow::Result<Option<i64>> {
745        let row = sqlx::query("SELECT id FROM tasks WHERE repo = ? AND pr_number = ? LIMIT 1")
746            .bind(repo)
747            .bind(pr_number)
748            .fetch_optional(&self.pool)
749            .await?;
750        let id = row.map(|r| r.try_get::<i64, _>("id")).transpose()?;
751        Ok(id)
752    }
753
754    /// Lightweight lookup: return only the `agent` column for a given repo + external_id.
755    /// Returns None when no row matches or the agent is NULL/empty.
756    pub async fn get_agent_by_external_id(
757        &self,
758        repo: &str,
759        ext_id: &str,
760    ) -> anyhow::Result<Option<String>> {
761        let row = sqlx::query("SELECT agent FROM tasks WHERE repo = ? AND external_id = ?")
762            .bind(repo)
763            .bind(ext_id)
764            .fetch_optional(&self.pool)
765            .await?;
766        let agent = row
767            .map(|r| r.try_get::<Option<String>, _>("agent"))
768            .transpose()?
769            .flatten();
770        Ok(agent)
771    }
772
773    /// Upsert an external task — insert if new, update title/body/labels if exists.
774    pub async fn upsert_external(&self, ext: &UpsertExternal<'_>) -> anyhow::Result<i64> {
775        let parent_id = match parent_external_id_from_labels(ext.labels) {
776            Some(parent_external_id) => self.resolve_task_id(ext.repo, parent_external_id).await?,
777            None => None,
778        };
779        self.write_int(Command::TaskUpsertExternal(UpsertExternalCmd {
780            repo: ext.repo.to_string(),
781            ext_id: ext.ext_id.to_string(),
782            title: ext.title.to_string(),
783            body: ext.body.to_string(),
784            author: ext.author.to_string(),
785            url: ext.url.to_string(),
786            labels: ext.labels.to_vec(),
787            origin: ext.origin.to_string(),
788            parent_id,
789        }))
790        .await
791    }
792
793    // ---------------------------------------------------------------
794    // Status
795    // ---------------------------------------------------------------
796
797    pub async fn update_status_and_fields(
798        &self,
799        id: i64,
800        status: TaskStatus,
801        updates: &[(&str, serde_json::Value)],
802    ) -> anyhow::Result<()> {
803        let mut updates = owned_updates(updates)?;
804        // Local columns stay on this node, as set_fields keeps them
805        if self.replicates() {
806            let local: Vec<_> = updates
807                .iter()
808                .filter(|(col, _)| is_local_column(col))
809                .cloned()
810                .collect();
811            updates.retain(|(col, _)| !is_local_column(col));
812
813            if !local.is_empty() {
814                let mut tx = self.begin_write().await?;
815                apply::set_fields(&mut tx, &now_stamp(), id, &local, true).await?;
816                tx.commit().await?;
817            }
818        }
819
820        self.write(Command::TaskUpdateStatusAndFields {
821            id,
822            status,
823            updates,
824        })
825        .await
826        .map(|_| ())
827    }
828
829    /// Update the status of a task.
830    pub async fn update_status(&self, id: i64, status: TaskStatus) -> anyhow::Result<()> {
831        self.write_bool(Command::TaskUpdateStatus {
832            id,
833            status,
834            expected: None,
835        })
836        .await
837        .map(|_| ())
838    }
839
840    /// Persist the external_id (e.g. a newly-created GitHub issue number) onto an existing task row.
841    pub async fn update_external_id(&self, id: i64, external_id: &str) -> anyhow::Result<()> {
842        self.write(Command::TaskUpdateExternalId {
843            id,
844            external_id: external_id.to_string(),
845        })
846        .await
847        .map(|_| ())
848    }
849
850    /// Conditionally update the status of a task only if it currently has `expected` status.
851    ///
852    /// Returns `true` if the row was updated, `false` if the current status did not match
853    /// `expected` (i.e. a concurrent transition already moved the task elsewhere).
854    pub async fn update_status_if(
855        &self,
856        id: i64,
857        status: TaskStatus,
858        expected: TaskStatus,
859    ) -> anyhow::Result<bool> {
860        self.write_bool(Command::TaskUpdateStatus {
861            id,
862            status,
863            expected: Some(expected),
864        })
865        .await
866    }
867
868    /// Touch `updated_at` to now without changing any other field.
869    ///
870    /// Called by the runner immediately after a tmux session exits so that the
871    /// stuck-task recovery timer is reset before response_handler post-processing
872    /// (git push, PR creation, status update) begins.  Without this, a session
873    /// that ran longer than `no_session_stuck_timeout` (default 10 min) would be
874    /// re-dispatched by the tick while the runner is still writing results.
875    pub async fn touch_updated_at(&self, id: i64) -> anyhow::Result<()> {
876        self.write(Command::TaskTouch { id }).await.map(|_| ())
877    }
878
879    /// Reset a task back to `new`, clearing `branch` and `worktree`
880    pub async fn reset_to_new(&self, id: i64) -> anyhow::Result<()> {
881        self.write(Command::TaskResetToNew {
882            id,
883            keep_branch: false,
884        })
885        .await
886        .map(|_| ())
887    }
888
889    /// Reset a task back to `new` and keep `branch` when cleanup left the local ref
890    pub async fn reset_to_new_keep_branch(&self, id: i64) -> anyhow::Result<()> {
891        self.write(Command::TaskResetToNew {
892            id,
893            keep_branch: true,
894        })
895        .await
896        .map(|_| ())
897    }
898
899    /// Update the block reason for a task.
900    pub async fn set_block_reason(&self, id: i64, reason: Option<&str>) -> anyhow::Result<()> {
901        let value = reason.map_or(serde_json::Value::Null, |r| {
902            serde_json::Value::String(r.to_string())
903        });
904        self.set_fields(id, &[("block_reason", value)]).await
905    }
906
907    // ---------------------------------------------------------------
908    // Routing
909    // ---------------------------------------------------------------
910
911    // ---------------------------------------------------------------
912    // Memory
913    // ---------------------------------------------------------------
914
915    // ---------------------------------------------------------------
916    // Tokens
917    // ---------------------------------------------------------------
918
919    // ---------------------------------------------------------------
920    // Cleanup
921    // ---------------------------------------------------------------
922
923    // ---------------------------------------------------------------
924    // Task Runs (audit trail)
925    // ---------------------------------------------------------------
926
927    // ---------------------------------------------------------------
928    // Row mapping helpers
929    // ---------------------------------------------------------------
930
931    fn row_to_task(row: &SqliteRow) -> anyhow::Result<Task> {
932        // Diagnostic: verify column count matches expected to prevent OOB panics
933        // when schema changes without updating TASK_COLS
934        let col_count = row.len();
935        if col_count != TASK_COLS_COUNT {
936            tracing::warn!(
937                expected = TASK_COLS_COUNT,
938                actual = col_count,
939                "TASK_COLS column count mismatch - schema may have changed"
940            );
941        }
942
943        let status_str: String = row
944            .try_get("status")
945            .map_err(|e| anyhow::anyhow!("task row missing status column: {e}"))?;
946        let labels_str: String = row.try_get("labels").unwrap_or_default();
947        let memory_str: String = row.try_get("memory").unwrap_or_default();
948        let delegations_str: String = row.try_get("delegations").unwrap_or_default();
949
950        Ok(Task {
951            id: row
952                .try_get("id")
953                .map_err(|e| anyhow::anyhow!("task row missing id: {e}"))?,
954            external_id: row.try_get("external_id").unwrap_or(None),
955            repo: row
956                .try_get("repo")
957                .map_err(|e| anyhow::anyhow!("task row missing or invalid repo: {e}"))?,
958            origin: row
959                .try_get("origin")
960                .map_err(|e| anyhow::anyhow!("task row missing or invalid origin: {e}"))?,
961            title: row
962                .try_get("title")
963                .map_err(|e| anyhow::anyhow!("task row missing or invalid title: {e}"))?,
964            body: row
965                .try_get("body")
966                .map_err(|e| anyhow::anyhow!("task row missing or invalid body: {e}"))?,
967            status: TaskStatus::from_str(&status_str)
968                .ok_or_else(|| anyhow::anyhow!("unknown task status: '{status_str}'"))?,
969            source: row
970                .try_get("source")
971                .map_err(|e| anyhow::anyhow!("task row missing or invalid source: {e}"))?,
972            source_id: row
973                .try_get("source_id")
974                .map_err(|e| anyhow::anyhow!("task row missing or invalid source_id: {e}"))?,
975            author: row
976                .try_get("author")
977                .map_err(|e| anyhow::anyhow!("task row missing or invalid author: {e}"))?,
978            url: row
979                .try_get("url")
980                .map_err(|e| anyhow::anyhow!("task row missing or invalid url: {e}"))?,
981            labels: serde_json::from_str(&labels_str)
982                .inspect_err(
983                    |e| tracing::warn!(error = %e, "corrupt labels JSON, defaulting to empty"),
984                )
985                .unwrap_or_default(),
986            agent: row.try_get("agent").unwrap_or(None),
987            model: row.try_get("model").unwrap_or(None),
988            complexity: row.try_get("complexity").unwrap_or_default(),
989            estimate: {
990                let raw: i32 = row.try_get("estimate").unwrap_or(0);
991                u8::try_from(raw).unwrap_or_else(|_| {
992                    tracing::warn!(
993                        raw_estimate = raw,
994                        "estimate value out of u8 range; defaulting to 0"
995                    );
996                    0
997                })
998            },
999            route_reason: row.try_get("route_reason").unwrap_or_default(),
1000            agent_profile: row.try_get("agent_profile").unwrap_or_default(),
1001            route_attempts: row.try_get("route_attempts").unwrap_or(0),
1002            attempts: row.try_get("attempts").unwrap_or(0),
1003            branch: row.try_get("branch").unwrap_or_default(),
1004            worktree: row.try_get("worktree").unwrap_or_default(),
1005            worktree_cleaned: row.try_get::<i32, _>("worktree_cleaned").unwrap_or(0) != 0,
1006            owner_node: row.try_get("owner_node").unwrap_or(None),
1007            summary: row.try_get("summary").unwrap_or_default(),
1008            last_error: row.try_get("last_error").unwrap_or_default(),
1009            parent_id: row.try_get("parent_id").unwrap_or(None),
1010            block_reason: row.try_get("block_reason").unwrap_or(None),
1011            pr_number: row.try_get("pr_number").unwrap_or(None),
1012            pr_review_context: row.try_get("pr_review_context").unwrap_or_default(),
1013            last_review_ts: row.try_get("last_review_ts").unwrap_or_default(),
1014            review_ts_map: row.try_get("review_ts_map").unwrap_or_default(),
1015            last_comment_review_ts: row.try_get("last_comment_review_ts").unwrap_or_default(),
1016            merge_conflict_retries: row.try_get("merge_conflict_retries").unwrap_or(0),
1017            ci_merge_failures: row.try_get("ci_merge_failures").unwrap_or(0),
1018            pr_create_failures: row.try_get("pr_create_failures").unwrap_or(0),
1019            push_failures: row.try_get::<i32, _>("push_failures").unwrap_or(0),
1020            network_retries: row.try_get::<i32, _>("network_retries").unwrap_or(0),
1021            timeout_retries: row.try_get::<i32, _>("timeout_retries").unwrap_or(0),
1022            review_agent_failures: row.try_get("review_agent_failures").unwrap_or(0),
1023            review_resets: row.try_get::<i32, _>("review_resets").unwrap_or(0),
1024            review_cycles: row.try_get("review_cycles").unwrap_or(0),
1025            review_invocations: row.try_get::<i32, _>("review_invocations").unwrap_or(0),
1026            needs_review_refires: row.try_get::<i32, _>("needs_review_refires").unwrap_or(0),
1027            input_tokens: row.try_get("input_tokens").unwrap_or(0),
1028            output_tokens: row.try_get("output_tokens").unwrap_or(0),
1029            total_cost_usd: row.try_get("total_cost_usd").unwrap_or(0.0),
1030            model_reroute_chain: row.try_get("model_reroute_chain").unwrap_or_default(),
1031            limit_reroute_chain: row.try_get("limit_reroute_chain").unwrap_or_default(),
1032            memory: serde_json::from_str(&memory_str)
1033                .inspect_err(
1034                    |e| tracing::warn!(error = %e, "corrupt memory JSON, defaulting to empty"),
1035                )
1036                .unwrap_or_default(),
1037            delegations: serde_json::from_str(&delegations_str)
1038                .inspect_err(
1039                    |e| tracing::warn!(error = %e, "corrupt delegations JSON, defaulting to empty"),
1040                )
1041                .unwrap_or_default(),
1042            // Some deployments may be running databases that haven't had
1043            // the most recent migrations applied. Use `try_get` with
1044            // sensible defaults for recently-added columns so a missing
1045            // column doesn't cause a panic in the sqlx row accessor.
1046            auto_unblock_count: row.try_get::<i32, _>("auto_unblock_count").unwrap_or(0),
1047            auto_unblock_last_at: row
1048                .try_get::<String, _>("auto_unblock_last_at")
1049                .unwrap_or_default(),
1050            auto_unblock_last_reason: row
1051                .try_get::<String, _>("auto_unblock_last_reason")
1052                .unwrap_or_default(),
1053            ci_recovery_count: row.try_get::<i32, _>("ci_recovery_count").unwrap_or(0),
1054            no_code_reroutes: row.try_get::<i32, _>("no_code_reroutes").unwrap_or(0),
1055            no_code_last_agent: row
1056                .try_get::<String, _>("no_code_last_agent")
1057                .unwrap_or_default(),
1058            created_at: row
1059                .try_get::<String, _>("created_at")
1060                .map_err(|e| anyhow::anyhow!("task row missing created_at: {e}"))?,
1061            updated_at: row
1062                .try_get::<String, _>("updated_at")
1063                .map_err(|e| anyhow::anyhow!("task row missing updated_at: {e}"))?,
1064        })
1065    }
1066
1067    fn row_to_activity(row: &SqliteRow) -> anyhow::Result<TaskActivity> {
1068        let details_str: String = row
1069            .try_get("details")
1070            .map_err(|e| anyhow::anyhow!("activity row decode error for details: {e}"))?;
1071        let details = serde_json::from_str::<serde_json::Value>(&details_str).inspect_err(
1072            |e| tracing::warn!(error = %e, "corrupt activity details JSON, skipping field"),
1073        )?;
1074        Ok(TaskActivity {
1075            id: row
1076                .try_get("id")
1077                .map_err(|e| anyhow::anyhow!("activity row decode error for id: {e}"))?,
1078            task_id: row
1079                .try_get("task_id")
1080                .map_err(|e| anyhow::anyhow!("activity row decode error for task_id: {e}"))?,
1081            timestamp: row
1082                .try_get("timestamp")
1083                .map_err(|e| anyhow::anyhow!("activity row decode error for timestamp: {e}"))?,
1084            event_type: row
1085                .try_get("event_type")
1086                .map_err(|e| anyhow::anyhow!("activity row decode error for event_type: {e}"))?,
1087            from_status: row
1088                .try_get("from_status")
1089                .map_err(|e| anyhow::anyhow!("activity row decode error for from_status: {e}"))?,
1090            to_status: row
1091                .try_get("to_status")
1092                .map_err(|e| anyhow::anyhow!("activity row decode error for to_status: {e}"))?,
1093            agent: row
1094                .try_get("agent")
1095                .map_err(|e| anyhow::anyhow!("activity row decode error for agent: {e}"))?,
1096            model: row
1097                .try_get("model")
1098                .map_err(|e| anyhow::anyhow!("activity row decode error for model: {e}"))?,
1099            details,
1100        })
1101    }
1102}
1103
1104/// Columns that describe this node's own copy of a task, never sent through the log
1105const LOCAL_TASK_COLUMNS: &[&str] = &[
1106    "worktree",
1107    "input_tokens",
1108    "output_tokens",
1109    "input_cost_usd",
1110    "output_cost_usd",
1111    "total_cost_usd",
1112];
1113
1114pub(crate) fn is_local_column(col: &str) -> bool {
1115    LOCAL_TASK_COLUMNS.contains(&col)
1116}
1117
1118/// Owned copy of [`UpsertExternal`], so it can travel in a Raft entry
1119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1120pub struct UpsertExternalCmd {
1121    pub repo: String,
1122    pub ext_id: String,
1123    pub title: String,
1124    pub body: String,
1125    pub author: String,
1126    pub url: String,
1127    pub labels: Vec<String>,
1128    pub origin: String,
1129    pub parent_id: Option<i64>,
1130}
1131
1132/// Owned copy of [`StoreRoute`], so it can travel in a Raft entry
1133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1134pub struct StoreRouteCmd {
1135    pub id: i64,
1136    pub agent: String,
1137    pub model: Option<String>,
1138    pub complexity: String,
1139    pub estimate: u8,
1140    pub reason: String,
1141    pub profile: String,
1142}
1143
1144/// The columns a done task's tombstone keeps. Nodes that had the task keep the rest locally
1145const TOMBSTONE_COLUMNS: &[&str] = &[
1146    "id",
1147    "external_id",
1148    "repo",
1149    "origin",
1150    "title",
1151    "status",
1152    "pr_number",
1153    "parent_id",
1154    "created_at",
1155    "updated_at",
1156];
1157
1158async fn replicated_columns(conn: &mut sqlx::SqliteConnection) -> anyhow::Result<Vec<String>> {
1159    let cols: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('tasks')")
1160        .fetch_all(conn)
1161        .await?;
1162    Ok(cols
1163        .into_iter()
1164        .map(|(c,)| c)
1165        .filter(|c| !is_local_column(c))
1166        .collect())
1167}
1168
1169/// Every task row as JSON with its replicated columns, done tasks as tombstones
1170pub(crate) async fn replicated_rows(pool: &SqlitePool) -> anyhow::Result<Vec<serde_json::Value>> {
1171    let mut conn = pool.acquire().await?;
1172    let cols = replicated_columns(&mut conn).await?;
1173    let full: Vec<&String> = cols.iter().collect();
1174    let tomb: Vec<&String> = cols
1175        .iter()
1176        .filter(|c| TOMBSTONE_COLUMNS.contains(&c.as_str()))
1177        .collect();
1178    let sql = format!(
1179        "SELECT CASE WHEN status = 'done' THEN {} ELSE {} END FROM tasks ORDER BY id",
1180        super::replica::json_row_sql(&tomb),
1181        super::replica::json_row_sql(&full)
1182    );
1183    let rows: Vec<(String,)> = sqlx::query_as(sqlx::AssertSqlSafe(sql.as_str()))
1184        .fetch_all(&mut *conn)
1185        .await?;
1186    rows.into_iter()
1187        .map(|(r,)| Ok(serde_json::from_str(&r)?))
1188        .collect()
1189}
1190
1191/// Make the task rows match `rows`. Local columns, and a tombstone's missing columns, keep the local
1192/// value. Tasks missing from `rows` go, with this node's runs and activity for them
1193pub(crate) async fn replace_replicated(
1194    conn: &mut sqlx::SqliteConnection,
1195    rows: &[serde_json::Value],
1196) -> anyhow::Result<()> {
1197    let allowed = replicated_columns(conn).await?;
1198    sqlx::query("PRAGMA defer_foreign_keys = ON")
1199        .execute(&mut *conn)
1200        .await?;
1201    sqlx::query("CREATE TEMP TABLE IF NOT EXISTS snapshot_ids (id INTEGER PRIMARY KEY)")
1202        .execute(&mut *conn)
1203        .await?;
1204    sqlx::query("DELETE FROM snapshot_ids")
1205        .execute(&mut *conn)
1206        .await?;
1207    for row in rows {
1208        let id = row["id"]
1209            .as_i64()
1210            .context("snapshot task row without an id")?;
1211        sqlx::query("INSERT INTO snapshot_ids (id) VALUES (?)")
1212            .bind(id)
1213            .execute(&mut *conn)
1214            .await?;
1215    }
1216
1217    for table in ["task_runs", "task_activity"] {
1218        sqlx::query(sqlx::AssertSqlSafe(format!(
1219            "DELETE FROM {table} WHERE task_id NOT IN (SELECT id FROM snapshot_ids)"
1220        )))
1221        .execute(&mut *conn)
1222        .await?;
1223    }
1224
1225    sqlx::query("DELETE FROM tasks WHERE id NOT IN (SELECT id FROM snapshot_ids)")
1226        .execute(&mut *conn)
1227        .await?;
1228
1229    for row in rows {
1230        let obj = row
1231            .as_object()
1232            .context("snapshot task row is not an object")?;
1233        let cols: Vec<&String> = obj.keys().collect();
1234        for c in &cols {
1235            anyhow::ensure!(
1236                allowed.contains(c),
1237                "snapshot names unknown task column {c}"
1238            );
1239        }
1240
1241        let values: Vec<String> = cols
1242            .iter()
1243            .map(|c| format!("json_extract(?1, '$.\"{c}\"')"))
1244            .collect();
1245        let updates: Vec<String> = cols.iter().map(|c| format!("{c} = excluded.{c}")).collect();
1246        let names: Vec<&str> = cols.iter().map(|c| c.as_str()).collect();
1247        let sql = format!(
1248            "INSERT INTO tasks ({}) VALUES ({}) ON CONFLICT(id) DO UPDATE SET {}",
1249            names.join(", "),
1250            values.join(", "),
1251            updates.join(", ")
1252        );
1253        sqlx::query(sqlx::AssertSqlSafe(sql.as_str()))
1254            .bind(serde_json::to_string(row)?)
1255            .execute(&mut *conn)
1256            .await?;
1257    }
1258
1259    sqlx::query("DROP TABLE snapshot_ids")
1260        .execute(&mut *conn)
1261        .await?;
1262    Ok(())
1263}
1264
1265#[cfg(test)]
1266mod row_to_task_tests;