Skip to main content

orch/engine/tasks/
mod.rs

1pub mod commands;
2pub mod dependencies;
3pub mod dispatch_guard;
4pub mod events;
5pub mod jobs;
6pub mod priority;
7
8use crate::backends::{ExternalBackend, ExternalId, ExternalTask, Status};
9use crate::engine::tasks::events::TaskEvent;
10use crate::store::{self, TaskStatus, TaskStore};
11use serde::{Deserialize, Serialize};
12use std::fmt;
13use std::fmt::Debug;
14use std::fmt::Formatter;
15use std::sync::Arc;
16use tokio::sync::broadcast::Sender;
17
18/// Returns true if the given task ID refers to an internal (SQLite) task.
19pub fn is_internal_id(id: &str) -> bool {
20    id.starts_with("internal:")
21}
22
23/// Parse an internal task ID string (e.g. "internal:8") to its numeric SQLite id.
24pub fn parse_internal_id(id: &str) -> Option<i64> {
25    id.strip_prefix("internal:")?.parse().ok()
26}
27
28/// Map a backend `Status` to a DB `TaskStatus`.
29pub fn status_to_task_status(status: Status) -> TaskStatus {
30    match status {
31        Status::New => TaskStatus::New,
32        Status::Routed => TaskStatus::Routed,
33        Status::InProgress => TaskStatus::InProgress,
34        Status::Done => TaskStatus::Done,
35        Status::Blocked => TaskStatus::Blocked,
36        Status::InReview => TaskStatus::InReview,
37        Status::Approved => TaskStatus::Approved,
38        Status::NeedsReview => TaskStatus::NeedsReview,
39        Status::Waiting => TaskStatus::Waiting,
40    }
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum TaskType {
46    External,
47    Internal,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct CreateTaskRequest {
52    pub title: String,
53    pub body: String,
54    pub task_type: TaskType,
55    pub labels: Vec<String>,
56    pub source: String,
57    pub source_id: String,
58}
59
60#[derive(Debug, Clone, Default, Serialize, Deserialize)]
61pub struct TaskFilter {
62    pub status: Option<String>,
63    pub source: Option<String>,
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize)]
67#[serde(untagged)]
68#[expect(
69    clippy::large_enum_variant,
70    reason = "tasks are few and boxing would touch every match"
71)]
72pub enum Task {
73    External(ExternalTask),
74    Internal(store::Task),
75}
76
77/// Pre-update snapshot of a task's state, used to enrich events with
78/// the old status and context fields (agent, model, branch, etc.).
79#[derive(Debug, Clone, Default)]
80struct TaskSnapshot {
81    old_status: Option<String>,
82    agent: Option<String>,
83    model: Option<String>,
84    branch: Option<String>,
85    pr_number: Option<String>,
86    error: Option<String>,
87    title: Option<String>,
88    summary: Option<String>,
89    duration_seconds: Option<f64>,
90}
91
92pub struct TaskManager {
93    backend: Arc<dyn ExternalBackend>,
94    /// Unified task store (Phase 2+). Optional for backward compat with tests.
95    store: Option<Arc<TaskStore>>,
96    /// Repo identifier for store operations (e.g. "owner/repo").
97    repo: String,
98    /// Event bus sender — publishes TaskEvent on every status change.
99    event_tx: Option<Sender<TaskEvent>>,
100}
101
102impl Debug for TaskManager {
103    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
104        f.debug_struct("TaskManager")
105            .field("repo", &self.repo)
106            .finish_non_exhaustive()
107    }
108}
109
110impl Clone for TaskManager {
111    fn clone(&self) -> Self {
112        Self {
113            backend: Arc::clone(&self.backend),
114            store: self.store.clone(),
115            repo: self.repo.clone(),
116            event_tx: self.event_tx.clone(),
117        }
118    }
119}
120
121impl TaskManager {
122    #[cfg(test)]
123    pub fn new(backend: Arc<dyn ExternalBackend>) -> Self {
124        Self {
125            backend,
126            store: None,
127            repo: String::new(),
128            event_tx: None,
129        }
130    }
131
132    /// Create a TaskManager with the unified store for dual-write support.
133    pub fn with_store(
134        backend: Arc<dyn ExternalBackend>,
135        store: Arc<TaskStore>,
136        repo: String,
137    ) -> Self {
138        Self {
139            backend,
140            store: Some(store),
141            repo,
142            event_tx: None,
143        }
144    }
145
146    /// Create a TaskManager with event bus support.
147    pub fn with_events(
148        backend: Arc<dyn ExternalBackend>,
149        store: Arc<TaskStore>,
150        repo: String,
151        event_tx: Sender<TaskEvent>,
152    ) -> Self {
153        Self {
154            backend,
155            store: Some(store),
156            repo,
157            event_tx: Some(event_tx),
158        }
159    }
160
161    pub async fn create_task(&self, req: CreateTaskRequest) -> anyhow::Result<Task> {
162        match req.task_type {
163            TaskType::Internal => {
164                let store = self
165                    .store
166                    .as_ref()
167                    .ok_or_else(|| anyhow::anyhow!("store required for internal tasks"))?;
168                let id = store
169                    .create_internal(
170                        &self.repo,
171                        &req.title,
172                        &req.body,
173                        &req.source,
174                        &req.source_id,
175                        None,
176                    )
177                    .await?;
178                let task = store.get(id).await?;
179                Ok(Task::Internal(task))
180            }
181            TaskType::External => {
182                let ext_id = self
183                    .backend
184                    .create_task(&req.title, &req.body, &req.labels)
185                    .await?;
186                let task = self.backend.get_task(&ext_id).await?;
187                Ok(Task::External(task))
188            }
189        }
190    }
191
192    pub async fn get_task(&self, id: i64) -> anyhow::Result<Task> {
193        // Try store first (covers both internal and external tasks)
194        if let Some(ref store) = self.store
195            && let Ok(task) = store.get(id).await
196            && task.origin == "internal"
197        {
198            return Ok(Task::Internal(task));
199        }
200        // External task found in store — still return as External from backend
201        // for compatibility with callers that expect ExternalTask fields
202        // Fall back to backend for external tasks
203        let ext_id = ExternalId(id.to_string());
204        match self.backend.get_task(&ext_id).await {
205            Ok(external) => Ok(Task::External(external)),
206            Err(external_err) => Err(anyhow::anyhow!(
207                "task {id} not found in store or externally (external: {external_err})"
208            )),
209        }
210    }
211
212    /// List tasks by status, source, or both.
213    /// Returns both internal (store) and external (GitHub) tasks.
214    pub async fn list_tasks(&self, filter: TaskFilter) -> anyhow::Result<Vec<Task>> {
215        let mut tasks = Vec::new();
216
217        let is_all = filter.status.as_deref() == Some("all");
218
219        if let Some(status_str) = &filter.status {
220            if !is_all {
221                let task_status = TaskStatus::from_str(status_str)
222                    .ok_or_else(|| anyhow::anyhow!(
223                        "invalid status: '{status_str}'. allowed: new, routed, in_progress, needs_review, in_review, approved, blocked, waiting, done, all"
224                    ))?;
225                let backend_status = match status_str.as_str() {
226                    "new" => Status::New,
227                    "routed" => Status::Routed,
228                    "in_progress" => Status::InProgress,
229                    "done" => Status::Done,
230                    "blocked" => Status::Blocked,
231                    "in_review" => Status::InReview,
232                    "approved" => Status::Approved,
233                    "needs_review" => Status::NeedsReview,
234                    "waiting" => Status::Waiting,
235                    _ => unreachable!(),
236                };
237
238                // Get internal tasks from store
239                if let Some(ref store) = self.store {
240                    let internal_tasks = store
241                        .list_internal_by_status(&self.repo, task_status)
242                        .await?;
243                    for t in internal_tasks {
244                        if let Some(ref source) = filter.source
245                            && t.source != *source
246                        {
247                            continue;
248                        }
249                        tasks.push(Task::Internal(t));
250                    }
251                }
252
253                // Get external tasks with this status (store-first, same pattern as list_external_by_status)
254                let external_tasks = self.list_external_by_status(backend_status).await?;
255                for t in external_tasks {
256                    tasks.push(Task::External(t));
257                }
258            }
259        } else if let Some(source) = &filter.source {
260            // Only source filter — query internal tasks by source directly in SQL
261            if let Some(ref store) = self.store {
262                let by_source = store.list_internal_by_source(&self.repo, source).await?;
263                for t in by_source {
264                    tasks.push(Task::Internal(t));
265                }
266            }
267        }
268
269        // No status filter or --status all: return all tasks for the repo
270        if filter.status.is_none() || is_all {
271            let mut has_external_in_store = false;
272            let store_tasks = if let Some(ref store) = self.store {
273                if is_all {
274                    let tasks = store.list_all(&self.repo).await?;
275                    has_external_in_store = match store.has_external_tasks(&self.repo).await {
276                        Ok(has_external) => has_external,
277                        Err(e) => {
278                            tracing::warn!(
279                                repo = %self.repo,
280                                error = %e,
281                                "failed to check external task sentinel; using store-only list path"
282                            );
283                            true
284                        }
285                    };
286                    tasks
287                } else {
288                    let tasks = store.list_active(&self.repo).await?;
289                    has_external_in_store = match store.has_external_tasks(&self.repo).await {
290                        Ok(has_external) => has_external,
291                        Err(e) => {
292                            tracing::warn!(
293                                repo = %self.repo,
294                                error = %e,
295                                "failed to check external task sentinel; using store-only list path"
296                            );
297                            true
298                        }
299                    };
300                    tasks
301                }
302            } else {
303                vec![]
304            };
305
306            for t in store_tasks {
307                if t.origin == "internal" {
308                    tasks.push(Task::Internal(t));
309                } else {
310                    tasks.push(Task::External(store_task_to_external(&t)));
311                }
312            }
313
314            if !has_external_in_store {
315                let external_tasks = self.backend.list_all_tasks().await?;
316                for t in external_tasks {
317                    tasks.push(Task::External(t));
318                }
319            }
320        }
321
322        Ok(tasks)
323    }
324
325    /// Get all external tasks across all statuses (for status summary).
326    /// Reads from the store when available, falling back to the backend.
327    pub async fn list_all_external_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
328        if let Some(ref store) = self.store {
329            let tasks = store.list_all_external(&self.repo).await?;
330            if !tasks.is_empty() {
331                return Ok(tasks.iter().map(store_task_to_external).collect());
332            }
333        }
334        self.backend.list_all_tasks().await
335    }
336
337    /// Get external tasks by status (for engine use).
338    /// Store-first: reads from the store when available, falls back to backend
339    /// if the store has no tasks (e.g. before first sync).
340    pub async fn list_external_by_status(
341        &self,
342        status: Status,
343    ) -> anyhow::Result<Vec<ExternalTask>> {
344        if let Some(ref store) = self.store {
345            let db_status = status_to_task_status(status);
346            let external = store.list_external_by_status(&self.repo, db_status).await?;
347            // Use the fetched results when non-empty; only check the sentinel when empty
348            // (empty could mean "no tasks with this status" OR "store not yet synced").
349            let has_external_in_store = if external.is_empty() {
350                match store.has_external_tasks(&self.repo).await {
351                    Ok(has_external) => has_external,
352                    Err(e) => {
353                        tracing::warn!(
354                            repo = %self.repo,
355                            status = ?status,
356                            error = %e,
357                            "failed to check external task sentinel; skipping backend fallback"
358                        );
359                        true
360                    }
361                }
362            } else {
363                true
364            };
365            if has_external_in_store {
366                let external: Vec<ExternalTask> =
367                    external.iter().map(store_task_to_external).collect();
368                return Ok(external);
369            }
370        }
371        self.backend.list_by_status(status).await
372    }
373
374    /// Get all tasks (external + internal) by status.
375    /// Store-first for external tasks: reads from the store when available,
376    /// falls back to backend if the store has no tasks.
377    /// Always includes internal tasks from the store when available.
378    pub async fn list_all_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
379        let mut tasks = Vec::new();
380
381        // Get external tasks with store-first pattern
382        if let Some(ref store) = self.store {
383            let db_status = status_to_task_status(status);
384            let external = store.list_external_by_status(&self.repo, db_status).await?;
385            // Use the fetched results when non-empty; only check the sentinel when empty
386            // (empty could mean "no tasks with this status" OR "store not yet synced").
387            let has_external_in_store = if external.is_empty() {
388                match store.has_external_tasks(&self.repo).await {
389                    Ok(has_external) => has_external,
390                    Err(e) => {
391                        tracing::warn!(
392                            repo = %self.repo,
393                            status = ?status,
394                            error = %e,
395                            "failed to check external task sentinel; skipping backend fallback"
396                        );
397                        true
398                    }
399                }
400            } else {
401                true
402            };
403            if has_external_in_store {
404                tasks.extend(external.into_iter().map(|t| store_task_to_external(&t)));
405            } else {
406                // Store not synced yet — fall back to backend for external tasks
407                tasks.extend(self.backend.list_by_status(status).await?);
408            }
409        } else {
410            // No store - get from backend
411            tasks.extend(self.backend.list_by_status(status).await?);
412        }
413
414        // Always include internal tasks from store when available
415        if self.store.is_some()
416            && let Ok(internal) = self
417                .list_internal_by_status(status_to_task_status(status))
418                .await
419        {
420            tasks.extend(internal);
421        }
422
423        Ok(tasks)
424    }
425
426    /// Get open tasks that are routable (status = new).
427    /// Store-first: reads all New tasks (external + internal) from the store,
428    /// falling back to the backend for external tasks before first sync.
429    pub async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
430        if let Some(ref store) = self.store {
431            let all_new = store.list_routable(&self.repo).await?;
432            // Check if any external (non-internal) tasks are in the result — if so
433            // the store has external tasks and we can skip the has_external_tasks query.
434            let has_external_new = all_new.iter().any(|t| t.origin != "internal");
435            let tasks: Vec<ExternalTask> = all_new.iter().map(store_task_to_external).collect();
436            let has_external_in_store = if has_external_new {
437                true
438            } else {
439                match store.has_external_tasks(&self.repo).await {
440                    Ok(has_external) => has_external,
441                    Err(e) => {
442                        tracing::warn!(
443                            repo = %self.repo,
444                            error = %e,
445                            "failed to check external task sentinel; skipping backend fallback"
446                        );
447                        true
448                    }
449                }
450            };
451            if has_external_in_store {
452                return Ok(tasks);
453            }
454        }
455
456        // Fallback: backend for external + store for internal
457        let mut tasks = self.backend.list_routable().await?;
458        if let Some(ref store) = self.store {
459            let internal_new = store
460                .list_internal_by_status(&self.repo, TaskStatus::New)
461                .await?;
462            for t in internal_new {
463                tasks.push(store_task_to_external(&t));
464            }
465        }
466        Ok(tasks)
467    }
468
469    /// Update the status of an internal or external task by its string ID.
470    /// For `"internal:{n}"` IDs, updates the store. For all others, calls the backend.
471    /// Store is always updated when available.
472    pub async fn update_task_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
473        self.update_task_status_with_duration(id, status, None)
474            .await
475    }
476
477    pub async fn update_task_status_and_result(
478        &self,
479        id: &ExternalId,
480        status: Status,
481        updates: &[(&str, serde_json::Value)],
482    ) -> anyhow::Result<()> {
483        let task_status = status_to_task_status(status);
484        self.release_dependents_if_done(task_status, &self.repo, &id.0)
485            .await;
486
487        // Read pre-update snapshot from the store (old_status + context fields).
488        let (pre_snapshot, snapshot_store_id) = self.read_task_snapshot(&id.0).await;
489
490        if is_internal_id(&id.0) {
491            // Internal tasks: store is the single source of truth
492            let store = self
493                .store
494                .as_ref()
495                .ok_or_else(|| anyhow::anyhow!("store required for internal task status update"))?;
496            let store_id = snapshot_store_id
497                .ok_or_else(|| anyhow::anyhow!("internal task {} not found in store", id.0))?;
498
499            store
500                .update_status_and_fields(store_id, task_status, updates)
501                .await?;
502            // Publish event to bus only after confirmed update
503            self.publish_event(id, status, &pre_snapshot, &self.repo, None);
504            return Ok(());
505        }
506
507        // External tasks: store-first, then mirror to backend.
508        if let Some(ref store) = self.store
509            && let Some(store_id) = snapshot_store_id
510        {
511            store
512                .update_status_and_fields(store_id, task_status, updates)
513                .await?;
514        }
515
516        // Mirror to backend (GitHub labels).
517        if let Err(e) = self.backend.update_status(id, status).await {
518            tracing::warn!(
519                task_id = id.0,
520                ?status,
521                err = %e,
522                "failed to mirror status to backend — store is authoritative"
523            );
524        }
525
526        // Publish event to bus
527        self.publish_event(id, status, &pre_snapshot, &self.repo, None);
528
529        Ok(())
530    }
531
532    /// Update the status of a task only if it is currently in `expected_status`.
533    ///
534    /// Returns `Ok(true)` if the update was applied, `Ok(false)` if the task had
535    /// already transitioned to a different status (TOCTOU-safe — no-op on race).
536    pub async fn update_task_status_if(
537        &self,
538        id: &ExternalId,
539        status: Status,
540        expected_status: Status,
541    ) -> anyhow::Result<bool> {
542        let task_status = status_to_task_status(status);
543        self.release_dependents_if_done(task_status, &self.repo, &id.0)
544            .await;
545        let expected_task_status = status_to_task_status(expected_status);
546
547        let (pre_snapshot, snapshot_store_id) = self.read_task_snapshot(&id.0).await;
548
549        if is_internal_id(&id.0) {
550            let store = self
551                .store
552                .as_ref()
553                .ok_or_else(|| anyhow::anyhow!("store required for internal task status update"))?;
554            let store_id = snapshot_store_id
555                .ok_or_else(|| anyhow::anyhow!("internal task {} not found in store", id.0))?;
556            let updated = store
557                .update_status_if(store_id, task_status, expected_task_status)
558                .await?;
559            if updated {
560                self.publish_event(id, status, &pre_snapshot, &self.repo, None);
561            }
562            return Ok(updated);
563        }
564
565        // External tasks: conditional store update, then mirror to backend.
566        // The conditional guarantee (update only when current == expected) relies on
567        // having a local store record. If the unified store isn't available or the
568        // task has no store record (e.g. not yet synced), we cannot safely perform
569        // the conditional update — return false and warn so callers treat this as
570        // a no-op instead of assuming the update succeeded.
571        if let Some(ref store) = self.store {
572            if let Some(store_id) = snapshot_store_id {
573                let updated = store
574                    .update_status_if(store_id, task_status, expected_task_status)
575                    .await?;
576                if !updated {
577                    return Ok(false);
578                }
579            } else {
580                tracing::warn!(
581                    task_id = id.0,
582                    ?expected_task_status,
583                    "update_task_status_if: external task has no store record — cannot perform conditional update"
584                );
585                return Ok(false);
586            }
587        } else {
588            tracing::warn!(
589                task_id = id.0,
590                ?expected_task_status,
591                "update_task_status_if: no store available — cannot perform conditional update for external task"
592            );
593            return Ok(false);
594        }
595
596        if let Err(e) = self.backend.update_status(id, status).await {
597            tracing::warn!(
598                task_id = id.0,
599                ?status,
600                err = %e,
601                "failed to mirror status to backend — store is authoritative"
602            );
603        }
604
605        self.publish_event(id, status, &pre_snapshot, &self.repo, None);
606        Ok(true)
607    }
608
609    /// Update the status of a task and include elapsed duration in the event.
610    ///
611    /// Use this at task completion points (success or failure) so the notify
612    /// subscriber can include accurate timing in channel messages instead of 0.0.
613    pub async fn update_task_status_with_duration(
614        &self,
615        id: &ExternalId,
616        status: Status,
617        duration_seconds: Option<f64>,
618    ) -> anyhow::Result<()> {
619        let task_status = status_to_task_status(status);
620        self.release_dependents_if_done(task_status, &self.repo, &id.0)
621            .await;
622        let (pre_snapshot, snapshot_store_id) = self.read_task_snapshot(&id.0).await;
623
624        if is_internal_id(&id.0) {
625            let store = self
626                .store
627                .as_ref()
628                .ok_or_else(|| anyhow::anyhow!("store required for internal task status update"))?;
629            let store_id = snapshot_store_id
630                .ok_or_else(|| anyhow::anyhow!("internal task {} not found in store", id.0))?;
631            if task_status != TaskStatus::Blocked {
632                store.set_block_reason(store_id, None).await?;
633            }
634            store.update_status(store_id, task_status).await?;
635            self.publish_event(id, status, &pre_snapshot, &self.repo, duration_seconds);
636            return Ok(());
637        }
638
639        if let Some(ref store) = self.store
640            && let Some(store_id) = snapshot_store_id
641        {
642            if task_status != TaskStatus::Blocked {
643                store.set_block_reason(store_id, None).await?;
644            }
645            store.update_status(store_id, task_status).await?;
646        }
647
648        if let Err(e) = self.backend.update_status(id, status).await {
649            tracing::warn!(
650                task_id = id.0,
651                ?status,
652                err = %e,
653                "failed to mirror status to backend — store is authoritative"
654            );
655        }
656
657        self.publish_event(id, status, &pre_snapshot, &self.repo, duration_seconds);
658
659        Ok(())
660    }
661
662    /// Read the current task snapshot from the store for event enrichment.
663    /// Returns `(snapshot, store_id)` — store_id is `Some` when the task was found,
664    /// so callers can reuse it for subsequent store operations without a second lookup.
665    async fn read_task_snapshot(&self, task_id: &str) -> (TaskSnapshot, Option<i64>) {
666        let Some(ref store) = self.store else {
667            return (TaskSnapshot::default(), None);
668        };
669        let Ok(Some(store_id)) = store.resolve_task_id(&self.repo, task_id).await else {
670            return (TaskSnapshot::default(), None);
671        };
672        let snapshot = Self::snapshot_for_store_id(store, store_id, task_id).await;
673        (snapshot, Some(store_id))
674    }
675
676    /// Build a `TaskSnapshot` for an already-resolved numeric store id, without
677    /// going through `resolve_task_id`. `metric_task_id` is the external id string
678    /// used as the key in `task_metrics` for duration lookup.
679    async fn snapshot_for_store_id(
680        store: &TaskStore,
681        store_id: i64,
682        metric_task_id: &str,
683    ) -> TaskSnapshot {
684        match store.get(store_id).await {
685            Ok(task) => {
686                let duration_seconds = store.latest_task_metric_duration(metric_task_id).await;
687                TaskSnapshot {
688                    old_status: Some(task.status.as_str().to_string()),
689                    agent: task.agent.clone(),
690                    model: task.model.clone(),
691                    branch: if task.branch.is_empty() {
692                        None
693                    } else {
694                        Some(task.branch.clone())
695                    },
696                    pr_number: task.pr_number.map(|n| n.to_string()),
697                    error: if task.last_error.is_empty() {
698                        None
699                    } else {
700                        Some(task.last_error.clone())
701                    },
702                    title: if task.title.is_empty() {
703                        None
704                    } else {
705                        Some(task.title.clone())
706                    },
707                    summary: if task.summary.is_empty() {
708                        None
709                    } else {
710                        Some(task.summary.clone())
711                    },
712                    duration_seconds,
713                }
714            }
715            Err(e) => {
716                tracing::warn!(
717                    task_id = store_id,
718                    err = %e,
719                    "failed to read task snapshot for event enrichment — event context will be empty"
720                );
721                TaskSnapshot::default()
722            }
723        }
724    }
725
726    /**
727     * Drop the blocker read cache for a task that is finishing, so the next snapshot
728     * refresh reads it and releases its dependents instead of waiting out the read TTL.
729     * Called before the write, because a cleared cache only costs one extra read if the
730     * write then fails or no-ops
731     **/
732    async fn release_dependents_if_done(&self, status: TaskStatus, repo: &str, ext_id: &str) {
733        if status != TaskStatus::Done {
734            return;
735        }
736        if let Some(ref store) = self.store {
737            dependencies::clear_blocker_read_cache(store, repo, ext_id).await;
738        }
739    }
740
741    /// Publish a TaskEvent to the event bus (if wired).
742    fn publish_event(
743        &self,
744        id: &ExternalId,
745        status: Status,
746        snapshot: &TaskSnapshot,
747        repo: &str,
748        duration_seconds: Option<f64>,
749    ) {
750        if let Some(ref tx) = self.event_tx {
751            let event = TaskEvent {
752                task_id: id.0.clone(),
753                repo: repo.to_string(),
754                old_status: snapshot.old_status.clone().unwrap_or_default(),
755                new_status: status.as_str().to_string(),
756                agent: snapshot.agent.clone(),
757                model: snapshot.model.clone(),
758                pr_number: snapshot.pr_number.clone(),
759                branch: snapshot.branch.clone(),
760                review_context: None,
761                error: snapshot.error.clone(),
762                timestamp: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
763                title: snapshot.title.clone(),
764                summary: snapshot.summary.clone(),
765                duration_seconds: duration_seconds.or(snapshot.duration_seconds),
766            };
767            let _ = tx.send(event);
768        }
769    }
770
771    /// Mark an already-resolved task Done directly by its numeric store id and owning
772    /// repo, bypassing the repo-scoped `resolve_task_id` lookup that `self.repo` would
773    /// otherwise apply. For callers that already hold the correct store row from a
774    /// cross-repo query — e.g. the global CI-failure unblock sweep — and would otherwise
775    /// fail to resolve a task belonging to a different repo than this `TaskManager`.
776    pub async fn mark_task_done_by_store_id(
777        &self,
778        store_id: i64,
779        repo: &str,
780        ext_id: &ExternalId,
781    ) -> anyhow::Result<()> {
782        self.update_task_status_by_store_id(store_id, repo, ext_id, Status::Done)
783            .await
784    }
785
786    /// Update a task's status directly by its already-resolved numeric store id and
787    /// owning repo, bypassing the repo-scoped `resolve_task_id` lookup that `self.repo`
788    /// would otherwise apply. For callers that already hold the correct store row from a
789    /// cross-repo query — e.g. a global sweep over tasks from inactive/removed repos —
790    /// and would otherwise fail to resolve a task belonging to a different repo than this
791    /// `TaskManager`. Does not mirror to the backend (GitHub), since the caller's backend
792    /// instance may not correspond to the task's owning repo.
793    pub async fn update_task_status_by_store_id(
794        &self,
795        store_id: i64,
796        repo: &str,
797        ext_id: &ExternalId,
798        status: Status,
799    ) -> anyhow::Result<()> {
800        let store = self
801            .store
802            .as_ref()
803            .ok_or_else(|| anyhow::anyhow!("store required for status update"))?;
804        let task_status = status_to_task_status(status);
805        self.release_dependents_if_done(task_status, repo, &ext_id.0)
806            .await;
807
808        let snapshot = Self::snapshot_for_store_id(store, store_id, &ext_id.0).await;
809        if task_status != TaskStatus::Blocked {
810            store.set_block_reason(store_id, None).await?;
811        }
812        store.update_status(store_id, task_status).await?;
813        self.publish_event(ext_id, status, &snapshot, repo, None);
814        Ok(())
815    }
816
817    /// Like [`Self::update_task_status_by_store_id`] but also sets additional result
818    /// fields atomically with the status transition (e.g. `block_reason`, `last_error`).
819    pub async fn update_task_status_and_result_by_store_id(
820        &self,
821        store_id: i64,
822        repo: &str,
823        ext_id: &ExternalId,
824        status: Status,
825        updates: &[(&str, serde_json::Value)],
826    ) -> anyhow::Result<()> {
827        let store = self
828            .store
829            .as_ref()
830            .ok_or_else(|| anyhow::anyhow!("store required for status update"))?;
831        let task_status = status_to_task_status(status);
832        self.release_dependents_if_done(task_status, repo, &ext_id.0)
833            .await;
834
835        let snapshot = Self::snapshot_for_store_id(store, store_id, &ext_id.0).await;
836        store
837            .update_status_and_fields(store_id, task_status, updates)
838            .await?;
839        self.publish_event(ext_id, status, &snapshot, repo, None);
840        Ok(())
841    }
842
843    /// List internal tasks by status from the store.
844    /// Returns store::Task items converted to ExternalTask for backward compatibility.
845    pub async fn list_internal_by_status(
846        &self,
847        status: TaskStatus,
848    ) -> anyhow::Result<Vec<ExternalTask>> {
849        let store = self
850            .store
851            .as_ref()
852            .ok_or_else(|| anyhow::anyhow!("store required"))?;
853        let tasks = store.list_internal_by_status(&self.repo, status).await?;
854        Ok(tasks
855            .into_iter()
856            .map(|t| store_task_to_external(&t))
857            .collect())
858    }
859
860    /// List all internal tasks from the store.
861    pub async fn list_all_internal(&self) -> anyhow::Result<Vec<store::Task>> {
862        let store = self
863            .store
864            .as_ref()
865            .ok_or_else(|| anyhow::anyhow!("store required"))?;
866        store.list_all_internal(&self.repo).await
867    }
868
869    pub async fn publish_task(&self, id: i64, labels: &[String]) -> anyhow::Result<ExternalId> {
870        let store = self
871            .store
872            .as_ref()
873            .ok_or_else(|| anyhow::anyhow!("store required for publish_task"))?;
874        let task = store.get(id).await?;
875        let ext_id = self
876            .backend
877            .create_task(&task.title, &task.body, labels)
878            .await?;
879        store.update_external_id(id, &ext_id.0).await?;
880        store.update_status(id, TaskStatus::New).await?;
881        Ok(ext_id)
882    }
883}
884
885/// Convert a store::Task to an ExternalTask for backward compatibility with
886/// code that expects ExternalTask (engine dispatch, review, etc.).
887pub fn store_task_to_external(t: &store::Task) -> ExternalTask {
888    let ext_id = t
889        .external_id
890        .clone()
891        .unwrap_or_else(|| format!("internal:{}", t.id));
892    ExternalTask {
893        id: ExternalId(ext_id),
894        title: t.title.clone(),
895        body: t.body.clone(),
896        state: "open".to_string(),
897        labels: {
898            let mut labels: Vec<String> = t
899                .labels
900                .iter()
901                .filter(|l| !l.starts_with("status:"))
902                .cloned()
903                .collect();
904            labels.push(format!("status:{}", t.status.as_str()));
905            labels
906        },
907        author: t.source.clone(),
908        created_at: t.created_at.clone(),
909        updated_at: t.updated_at.clone(),
910        url: t.url.clone(),
911    }
912}
913
914#[cfg(test)]
915mod tests;