Skip to main content

orch/engine/tasks/
mod.rs

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