Skip to main content

orch/engine/tasks/
mod.rs

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