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