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