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