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