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