Skip to main content

orch/engine/
tasks.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 {
910    use super::*;
911    use crate::backends::{ExternalId, ExternalTask, Mention};
912    use crate::store::{NewTask, TaskStore};
913    use async_trait::async_trait;
914    use std::sync::{Arc, Mutex};
915    use tokio::sync::broadcast;
916
917    type StatusTaskMap = Arc<Mutex<Vec<(Status, Vec<ExternalTask>)>>>;
918
919    /// Mock backend that records update_status calls.
920    struct MockBackend {
921        status_updates: Arc<Mutex<Vec<(String, Status)>>>,
922        status_tasks: StatusTaskMap,
923        routable_tasks: Arc<Mutex<Vec<ExternalTask>>>,
924    }
925
926    impl MockBackend {
927        fn new() -> Self {
928            Self {
929                status_updates: Arc::new(Mutex::new(vec![])),
930                status_tasks: Arc::new(Mutex::new(vec![])),
931                routable_tasks: Arc::new(Mutex::new(vec![])),
932            }
933        }
934
935        fn with_status_tasks(self, status: Status, tasks: Vec<ExternalTask>) -> Self {
936            self.status_tasks.lock().unwrap().push((status, tasks));
937            self
938        }
939
940        fn with_routable_tasks(self, tasks: Vec<ExternalTask>) -> Self {
941            *self.routable_tasks.lock().unwrap() = tasks;
942            self
943        }
944    }
945
946    #[async_trait]
947    impl ExternalBackend for MockBackend {
948        fn name(&self) -> &'static str {
949            "mock"
950        }
951        async fn create_task(
952            &self,
953            _t: &str,
954            _b: &str,
955            _l: &[String],
956        ) -> anyhow::Result<ExternalId> {
957            Ok(ExternalId("new".to_string()))
958        }
959        async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
960            Ok(ExternalTask {
961                id: id.clone(),
962                title: "Mock".to_string(),
963                body: String::new(),
964                state: "open".to_string(),
965                labels: vec![],
966                author: "bot".to_string(),
967                created_at: "2026-01-01T00:00:00Z".to_string(),
968                updated_at: "2026-01-01T00:00:00Z".to_string(),
969                url: String::new(),
970            })
971        }
972        async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
973            Ok(self
974                .status_tasks
975                .lock()
976                .unwrap()
977                .iter()
978                .find(|(s, _)| *s == status)
979                .map(|(_, tasks)| tasks.clone())
980                .unwrap_or_default())
981        }
982        async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
983            Ok(self.routable_tasks.lock().unwrap().clone())
984        }
985        async fn post_comment(&self, _id: &ExternalId, _b: &str) -> anyhow::Result<()> {
986            Ok(())
987        }
988        async fn set_labels(&self, _id: &ExternalId, _l: &[String]) -> anyhow::Result<()> {
989            Ok(())
990        }
991        async fn remove_label(&self, _id: &ExternalId, _l: &str) -> anyhow::Result<()> {
992            Ok(())
993        }
994        async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
995            Ok(vec![])
996        }
997        async fn create_sub_task(
998            &self,
999            _p: &ExternalId,
1000            _t: &str,
1001            _b: &str,
1002            _l: &[String],
1003        ) -> anyhow::Result<ExternalId> {
1004            Ok(ExternalId("child".to_string()))
1005        }
1006        async fn ensure_status_label(&self, _l: &str) -> anyhow::Result<()> {
1007            Ok(())
1008        }
1009        async fn has_open_issue_with_title(&self, _t: &str, _l: &str) -> anyhow::Result<bool> {
1010            Ok(false)
1011        }
1012        async fn health_check(&self) -> anyhow::Result<()> {
1013            Ok(())
1014        }
1015        async fn is_pr_merged(&self, _b: &str) -> anyhow::Result<bool> {
1016            Ok(false)
1017        }
1018        async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
1019            Ok(Some("testbot".to_string()))
1020        }
1021        async fn get_mentions(&self, _s: &str) -> anyhow::Result<Vec<Mention>> {
1022            Ok(vec![])
1023        }
1024        async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
1025            self.status_updates
1026                .lock()
1027                .unwrap()
1028                .push((id.0.clone(), status));
1029            Ok(())
1030        }
1031    }
1032
1033    #[tokio::test]
1034    async fn with_store_constructor_enables_dual_write() {
1035        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1036        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1037
1038        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1039
1040        assert!(tm.store.is_some(), "store should be set via with_store");
1041        assert_eq!(tm.repo, "owner/repo");
1042    }
1043
1044    #[tokio::test]
1045    async fn update_status_dual_writes_to_store_for_external_task() {
1046        let mock = MockBackend::new();
1047        let backend: Arc<dyn ExternalBackend> = Arc::new(mock);
1048        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1049
1050        // Pre-create the task in the store so resolve_task_id finds it
1051        store
1052            .create(&NewTask {
1053                external_id: Some("42".to_string()),
1054                repo: "owner/repo".to_string(),
1055                origin: "github".to_string(),
1056                title: "Test".to_string(),
1057                ..Default::default()
1058            })
1059            .await
1060            .unwrap();
1061
1062        let tm = TaskManager::with_store(
1063            Arc::clone(&backend),
1064            Arc::clone(&store),
1065            "owner/repo".to_string(),
1066        );
1067
1068        // Update status — should write to both backend and store
1069        tm.update_task_status(&ExternalId("42".to_string()), Status::InProgress)
1070            .await
1071            .unwrap();
1072
1073        // Verify the store side was updated
1074        let task = store.get(1).await.unwrap();
1075        assert_eq!(
1076            task.status,
1077            TaskStatus::InProgress,
1078            "store should have updated status"
1079        );
1080    }
1081
1082    #[tokio::test]
1083    async fn update_status_skips_store_when_task_not_in_store() {
1084        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1085        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1086
1087        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1088
1089        // Update for a task not in the store — should not error
1090        let result = tm
1091            .update_task_status(&ExternalId("999".to_string()), Status::Done)
1092            .await;
1093        assert!(result.is_ok(), "should succeed even when task not in store");
1094    }
1095
1096    #[tokio::test]
1097    async fn update_status_works_without_store() {
1098        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1099
1100        // Use old constructor (no store)
1101        let tm = TaskManager::new(backend);
1102
1103        let result = tm
1104            .update_task_status(&ExternalId("42".to_string()), Status::Routed)
1105            .await;
1106        assert!(
1107            result.is_ok(),
1108            "should work without store (backward compat)"
1109        );
1110    }
1111
1112    #[tokio::test]
1113    async fn update_status_writes_to_store_for_internal_task() {
1114        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1115        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1116
1117        // Create an internal task in the store
1118        let internal_id = store
1119            .create_internal("owner/repo", "Internal task", "body", "cron", "job:1", None)
1120            .await
1121            .unwrap();
1122
1123        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1124
1125        // Update the internal task status via TaskManager
1126        let id_str = format!("internal:{internal_id}");
1127        tm.update_task_status(&ExternalId(id_str), Status::Routed)
1128            .await
1129            .unwrap();
1130
1131        // Verify the store was updated
1132        let task = store.get(internal_id).await.unwrap();
1133        assert_eq!(task.status, TaskStatus::Routed);
1134    }
1135
1136    #[tokio::test]
1137    async fn status_to_task_status_maps_all_variants() {
1138        assert_eq!(status_to_task_status(Status::New), TaskStatus::New);
1139        assert_eq!(status_to_task_status(Status::Routed), TaskStatus::Routed);
1140        assert_eq!(
1141            status_to_task_status(Status::InProgress),
1142            TaskStatus::InProgress
1143        );
1144        assert_eq!(status_to_task_status(Status::Done), TaskStatus::Done);
1145        assert_eq!(status_to_task_status(Status::Blocked), TaskStatus::Blocked);
1146        assert_eq!(
1147            status_to_task_status(Status::InReview),
1148            TaskStatus::InReview
1149        );
1150        assert_eq!(
1151            status_to_task_status(Status::NeedsReview),
1152            TaskStatus::NeedsReview
1153        );
1154        assert_eq!(
1155            status_to_task_status(Status::Approved),
1156            TaskStatus::Approved
1157        );
1158        assert_eq!(status_to_task_status(Status::Waiting), TaskStatus::Waiting);
1159    }
1160
1161    #[test]
1162    fn is_internal_id_detects_prefix() {
1163        assert!(is_internal_id("internal:5"));
1164        assert!(is_internal_id("internal:0"));
1165        assert!(!is_internal_id("42"));
1166        assert!(!is_internal_id(""));
1167        assert!(!is_internal_id("internal"));
1168    }
1169
1170    #[test]
1171    fn parse_internal_id_extracts_number() {
1172        assert_eq!(parse_internal_id("internal:5"), Some(5));
1173        assert_eq!(parse_internal_id("internal:0"), Some(0));
1174        assert_eq!(parse_internal_id("internal:abc"), None);
1175        assert_eq!(parse_internal_id("42"), None);
1176        assert_eq!(parse_internal_id(""), None);
1177    }
1178
1179    #[tokio::test]
1180    async fn create_internal_task_via_task_manager() {
1181        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1182        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1183        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1184
1185        let task = tm
1186            .create_task(CreateTaskRequest {
1187                title: "Internal task".to_string(),
1188                body: "Do something".to_string(),
1189                task_type: TaskType::Internal,
1190                labels: vec![],
1191                source: "cron".to_string(),
1192                source_id: "job:daily".to_string(),
1193            })
1194            .await
1195            .unwrap();
1196
1197        match task {
1198            Task::Internal(t) => {
1199                assert_eq!(t.title, "Internal task");
1200                assert_eq!(t.origin, "internal");
1201                assert!(
1202                    t.external_id
1203                        .as_deref()
1204                        .is_some_and(|s| s.starts_with("internal:"))
1205                );
1206            }
1207            Task::External(_) => panic!("expected Internal variant"),
1208        }
1209    }
1210
1211    #[tokio::test]
1212    async fn create_internal_task_fails_without_store() {
1213        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1214        let tm = TaskManager::new(backend);
1215
1216        let result = tm
1217            .create_task(CreateTaskRequest {
1218                title: "No store".to_string(),
1219                body: String::new(),
1220                task_type: TaskType::Internal,
1221                labels: vec![],
1222                source: "manual".to_string(),
1223                source_id: String::new(),
1224            })
1225            .await;
1226
1227        assert!(result.is_err(), "should fail without store");
1228    }
1229
1230    /// Regression test for the phantom-event bug: when an internal task ID is not found
1231    /// in the store, update_task_status must return Err and must NOT publish any event.
1232    #[tokio::test]
1233    async fn update_status_internal_task_not_found_returns_err_and_no_event() {
1234        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1235        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1236
1237        let (event_tx, mut event_rx) = broadcast::channel::<TaskEvent>(16);
1238
1239        let tm = TaskManager::with_events(
1240            backend,
1241            Arc::clone(&store),
1242            "owner/repo".to_string(),
1243            event_tx,
1244        );
1245
1246        // "internal:999" does not exist in the (empty) store
1247        let result = tm
1248            .update_task_status(&ExternalId("internal:999".to_string()), Status::Done)
1249            .await;
1250
1251        assert!(
1252            result.is_err(),
1253            "should return Err when internal task is not found in store"
1254        );
1255
1256        // No event must have been published
1257        assert!(
1258            event_rx.try_recv().is_err(),
1259            "no event should be published for a not-found internal task"
1260        );
1261    }
1262
1263    /// Regression test for #3437: `update_task_status` resolves by `self.repo`, so a
1264    /// `TaskManager` scoped to one repo cannot mark Done a task that belongs to a
1265    /// different repo — exactly the case the global cross-repo CI-failure unblock sweep
1266    /// hits. `mark_task_done_by_store_id` bypasses that repo-scoped resolution and must
1267    /// succeed where `update_task_status` fails.
1268    #[tokio::test]
1269    async fn mark_task_done_by_store_id_succeeds_across_repos() {
1270        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1271        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1272
1273        let store_id = store
1274            .create_internal(
1275                "other/repo",
1276                "Cross-repo task",
1277                "body",
1278                "cron",
1279                "job:1",
1280                None,
1281            )
1282            .await
1283            .unwrap();
1284        let ext_id = ExternalId(format!("internal:{store_id}"));
1285
1286        // TaskManager scoped to a different repo than the task belongs to.
1287        let tm = TaskManager::with_store(backend, Arc::clone(&store), "active/repo".to_string());
1288
1289        // The repo-scoped path fails to even find the task.
1290        let resolve_result = tm.update_task_status(&ext_id, Status::Done).await;
1291        assert!(
1292            resolve_result.is_err(),
1293            "repo-scoped update_task_status must fail for a cross-repo task"
1294        );
1295
1296        // The bypass path succeeds using the already-resolved store id + owning repo.
1297        tm.mark_task_done_by_store_id(store_id, "other/repo", &ext_id)
1298            .await
1299            .unwrap();
1300
1301        let task = store.get(store_id).await.unwrap();
1302        assert_eq!(task.status, TaskStatus::Done);
1303    }
1304
1305    #[tokio::test]
1306    async fn get_task_returns_internal_from_store() {
1307        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1308        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1309        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1310
1311        let id = store
1312            .create_internal("owner/repo", "Fetch me", "body", "cron", "job:1", None)
1313            .await
1314            .unwrap();
1315
1316        let task = tm.get_task(id).await.unwrap();
1317        match task {
1318            Task::Internal(t) => assert_eq!(t.title, "Fetch me"),
1319            Task::External(_) => panic!("expected Internal variant"),
1320        }
1321    }
1322
1323    #[tokio::test]
1324    async fn list_routable_includes_internal_new_tasks() {
1325        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1326        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1327        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1328
1329        // Create internal task (starts as New)
1330        store
1331            .create_internal("owner/repo", "Route me", "", "cron", "job:2", None)
1332            .await
1333            .unwrap();
1334
1335        let routable = tm.list_routable().await.unwrap();
1336        assert_eq!(routable.len(), 1);
1337        assert!(routable[0].id.0.starts_with("internal:"));
1338        assert_eq!(routable[0].title, "Route me");
1339    }
1340
1341    #[tokio::test]
1342    async fn list_routable_excludes_non_new_internal_tasks() {
1343        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1344        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1345        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1346
1347        let id = store
1348            .create_internal("owner/repo", "Already routed", "", "cron", "job:3", None)
1349            .await
1350            .unwrap();
1351        store
1352            .update_status(id, TaskStatus::InProgress)
1353            .await
1354            .unwrap();
1355
1356        let routable = tm.list_routable().await.unwrap();
1357        assert!(
1358            routable.is_empty(),
1359            "in_progress tasks should not be routable"
1360        );
1361    }
1362
1363    #[tokio::test]
1364    async fn list_internal_by_status_returns_external_tasks() {
1365        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1366        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1367        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1368
1369        store
1370            .create_internal("owner/repo", "Task A", "", "cron", "a", None)
1371            .await
1372            .unwrap();
1373        let id_b = store
1374            .create_internal("owner/repo", "Task B", "", "cron", "b", None)
1375            .await
1376            .unwrap();
1377        store.update_status(id_b, TaskStatus::Done).await.unwrap();
1378
1379        let new_tasks = tm.list_internal_by_status(TaskStatus::New).await.unwrap();
1380        assert_eq!(new_tasks.len(), 1);
1381        assert_eq!(new_tasks[0].title, "Task A");
1382        // Verify it's wrapped as ExternalTask with status label
1383        assert!(new_tasks[0].labels.contains(&"status:new".to_string()));
1384    }
1385
1386    #[tokio::test]
1387    async fn store_task_to_external_maps_fields_correctly() {
1388        let store = TaskStore::open_memory().await.unwrap();
1389        let id = store
1390            .create_internal(
1391                "owner/repo",
1392                "Convert me",
1393                "body text",
1394                "manual",
1395                "m:1",
1396                None,
1397            )
1398            .await
1399            .unwrap();
1400        let task = store.get(id).await.unwrap();
1401        let ext = store_task_to_external(&task);
1402
1403        assert!(ext.id.0.starts_with("internal:"));
1404        assert_eq!(ext.title, "Convert me");
1405        assert_eq!(ext.body, "body text");
1406        assert_eq!(ext.state, "open");
1407        assert!(ext.labels.contains(&"status:new".to_string()));
1408        assert_eq!(ext.author, "manual"); // source maps to author
1409    }
1410
1411    #[tokio::test]
1412    async fn list_all_internal_returns_store_tasks() {
1413        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1414        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1415        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1416
1417        store
1418            .create_internal("owner/repo", "T1", "", "cron", "1", None)
1419            .await
1420            .unwrap();
1421        store
1422            .create_internal("owner/repo", "T2", "", "cron", "2", None)
1423            .await
1424            .unwrap();
1425        // Different repo — should not appear
1426        store
1427            .create_internal("other/repo", "T3", "", "cron", "3", None)
1428            .await
1429            .unwrap();
1430
1431        let tasks = tm.list_all_internal().await.unwrap();
1432        assert_eq!(tasks.len(), 2);
1433    }
1434
1435    // ── Phase 4: store-first reads ───────────────────────────────────
1436
1437    #[tokio::test]
1438    async fn list_external_by_status_reads_from_store() {
1439        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1440        let backend = Arc::new(MockBackend::new());
1441        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1442
1443        // Create an external task in the store with status Routed
1444        let id = store
1445            .upsert_external(&crate::store::UpsertExternal {
1446                repo: "owner/repo",
1447                ext_id: "42",
1448                title: "Store task",
1449                body: "",
1450                author: "",
1451                url: "",
1452                labels: &[],
1453                origin: "github",
1454            })
1455            .await
1456            .unwrap();
1457        store.update_status(id, TaskStatus::Routed).await.unwrap();
1458
1459        let routed = tm.list_external_by_status(Status::Routed).await.unwrap();
1460        assert_eq!(routed.len(), 1);
1461        assert_eq!(routed[0].id.0, "42");
1462        assert_eq!(routed[0].title, "Store task");
1463    }
1464
1465    #[tokio::test]
1466    async fn list_external_by_status_excludes_internal_tasks() {
1467        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1468        let backend = Arc::new(MockBackend::new());
1469        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1470
1471        // Create an internal task with Routed status
1472        let id = store
1473            .create_internal("owner/repo", "Internal task", "", "cron", "1", None)
1474            .await
1475            .unwrap();
1476        store.update_status(id, TaskStatus::Routed).await.unwrap();
1477
1478        // Also create an external task to populate the store
1479        store
1480            .upsert_external(&crate::store::UpsertExternal {
1481                repo: "owner/repo",
1482                ext_id: "99",
1483                title: "External",
1484                body: "",
1485                author: "",
1486                url: "",
1487                labels: &[],
1488                origin: "github",
1489            })
1490            .await
1491            .unwrap();
1492
1493        let routed = tm.list_external_by_status(Status::Routed).await.unwrap();
1494        // Should only include the internal task since it's status Routed, but filtered to external only
1495        assert_eq!(routed.len(), 0);
1496    }
1497
1498    #[tokio::test]
1499    async fn list_external_by_status_falls_back_when_store_has_only_internal_tasks() {
1500        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1501        let backend = Arc::new(MockBackend::new().with_status_tasks(
1502            Status::Routed,
1503            vec![ExternalTask {
1504                id: ExternalId("123".to_string()),
1505                title: "Backend routed".to_string(),
1506                body: String::new(),
1507                state: "open".to_string(),
1508                labels: vec!["status:routed".to_string()],
1509                author: "bot".to_string(),
1510                created_at: "2026-01-01T00:00:00Z".to_string(),
1511                updated_at: "2026-01-01T00:00:00Z".to_string(),
1512                url: String::new(),
1513            }],
1514        ));
1515        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1516
1517        let id = store
1518            .create_internal("owner/repo", "Internal task", "", "cron", "1", None)
1519            .await
1520            .unwrap();
1521        store.update_status(id, TaskStatus::Routed).await.unwrap();
1522
1523        let routed = tm.list_external_by_status(Status::Routed).await.unwrap();
1524        assert_eq!(routed.len(), 1);
1525        assert_eq!(routed[0].id.0, "123");
1526    }
1527
1528    #[tokio::test]
1529    async fn list_routable_reads_from_store_when_populated() {
1530        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1531        let backend = Arc::new(MockBackend::new());
1532        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1533
1534        // Create a new external task
1535        store
1536            .upsert_external(&crate::store::UpsertExternal {
1537                repo: "owner/repo",
1538                ext_id: "10",
1539                title: "New external",
1540                body: "",
1541                author: "",
1542                url: "",
1543                labels: &[],
1544                origin: "github",
1545            })
1546            .await
1547            .unwrap();
1548        // Also a new internal task
1549        store
1550            .create_internal("owner/repo", "New internal", "", "cron", "1", None)
1551            .await
1552            .unwrap();
1553
1554        let routable = tm.list_routable().await.unwrap();
1555        // Both should appear (both are status=new)
1556        assert_eq!(routable.len(), 2);
1557    }
1558
1559    #[tokio::test]
1560    async fn list_routable_falls_back_when_store_has_only_internal_tasks() {
1561        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1562        let backend = Arc::new(MockBackend::new().with_routable_tasks(vec![ExternalTask {
1563            id: ExternalId("55".to_string()),
1564            title: "Backend new".to_string(),
1565            body: String::new(),
1566            state: "open".to_string(),
1567            labels: vec!["status:new".to_string()],
1568            author: "bot".to_string(),
1569            created_at: "2026-01-01T00:00:00Z".to_string(),
1570            updated_at: "2026-01-01T00:00:00Z".to_string(),
1571            url: String::new(),
1572        }]));
1573        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1574
1575        store
1576            .create_internal("owner/repo", "Internal new", "", "cron", "1", None)
1577            .await
1578            .unwrap();
1579
1580        let routable = tm.list_routable().await.unwrap();
1581        assert_eq!(routable.len(), 2);
1582        assert!(routable.iter().any(|task| task.id.0 == "55"));
1583        assert!(
1584            routable
1585                .iter()
1586                .any(|task| task.id.0.starts_with("internal:"))
1587        );
1588    }
1589
1590    #[tokio::test]
1591    async fn list_all_external_tasks_reads_from_store() {
1592        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1593        let backend = Arc::new(MockBackend::new());
1594        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1595
1596        // Create tasks with different statuses
1597        let id1 = store
1598            .upsert_external(&crate::store::UpsertExternal {
1599                repo: "owner/repo",
1600                ext_id: "1",
1601                title: "Task 1",
1602                body: "",
1603                author: "",
1604                url: "",
1605                labels: &[],
1606                origin: "github",
1607            })
1608            .await
1609            .unwrap();
1610        let id2 = store
1611            .upsert_external(&crate::store::UpsertExternal {
1612                repo: "owner/repo",
1613                ext_id: "2",
1614                title: "Task 2",
1615                body: "",
1616                author: "",
1617                url: "",
1618                labels: &[],
1619                origin: "github",
1620            })
1621            .await
1622            .unwrap();
1623        store.update_status(id1, TaskStatus::Done).await.unwrap();
1624        store
1625            .update_status(id2, TaskStatus::InProgress)
1626            .await
1627            .unwrap();
1628
1629        // Internal tasks should be excluded
1630        store
1631            .create_internal("owner/repo", "Internal", "", "cron", "1", None)
1632            .await
1633            .unwrap();
1634
1635        let all = tm.list_all_external_tasks().await.unwrap();
1636        assert_eq!(all.len(), 2);
1637    }
1638
1639    #[tokio::test]
1640    async fn list_all_external_tasks_falls_back_when_store_has_only_internal_tasks() {
1641        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1642        let backend = Arc::new(MockBackend::new().with_status_tasks(
1643            Status::Done,
1644            vec![ExternalTask {
1645                id: ExternalId("200".to_string()),
1646                title: "Backend done".to_string(),
1647                body: String::new(),
1648                state: "closed".to_string(),
1649                labels: vec!["status:done".to_string()],
1650                author: "bot".to_string(),
1651                created_at: "2026-01-01T00:00:00Z".to_string(),
1652                updated_at: "2026-01-01T00:00:00Z".to_string(),
1653                url: String::new(),
1654            }],
1655        ));
1656        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1657
1658        store
1659            .create_internal("owner/repo", "Internal", "", "cron", "1", None)
1660            .await
1661            .unwrap();
1662
1663        let all = tm.list_all_external_tasks().await.unwrap();
1664        assert_eq!(all.len(), 1);
1665        assert_eq!(all[0].id.0, "200");
1666    }
1667
1668    #[tokio::test]
1669    async fn list_tasks_without_status_merges_backend_external_when_store_only_has_internal() {
1670        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1671        let backend = Arc::new(MockBackend::new().with_status_tasks(
1672            Status::New,
1673            vec![ExternalTask {
1674                id: ExternalId("301".to_string()),
1675                title: "Backend new".to_string(),
1676                body: String::new(),
1677                state: "open".to_string(),
1678                labels: vec!["status:new".to_string()],
1679                author: "bot".to_string(),
1680                created_at: "2026-01-01T00:00:00Z".to_string(),
1681                updated_at: "2026-01-01T00:00:00Z".to_string(),
1682                url: String::new(),
1683            }],
1684        ));
1685        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1686
1687        let internal_id = store
1688            .create_internal("owner/repo", "Internal task", "", "cron", "1", None)
1689            .await
1690            .unwrap();
1691
1692        let listed = tm.list_tasks(TaskFilter::default()).await.unwrap();
1693        assert_eq!(listed.len(), 2);
1694        assert!(listed.iter().any(|task| matches!(
1695            task,
1696            Task::External(external) if external.id.0 == "301"
1697        )));
1698        assert!(listed.iter().any(|task| matches!(
1699            task,
1700            Task::Internal(internal) if internal.id == internal_id
1701        )));
1702    }
1703
1704    #[tokio::test]
1705    async fn list_tasks_status_all_merges_backend_external_when_store_only_has_internal() {
1706        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1707        let backend = Arc::new(MockBackend::new().with_status_tasks(
1708            Status::Done,
1709            vec![ExternalTask {
1710                id: ExternalId("302".to_string()),
1711                title: "Backend done".to_string(),
1712                body: String::new(),
1713                state: "closed".to_string(),
1714                labels: vec!["status:done".to_string()],
1715                author: "bot".to_string(),
1716                created_at: "2026-01-01T00:00:00Z".to_string(),
1717                updated_at: "2026-01-01T00:00:00Z".to_string(),
1718                url: String::new(),
1719            }],
1720        ));
1721        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1722
1723        let internal_id = store
1724            .create_internal("owner/repo", "Internal task", "", "cron", "1", None)
1725            .await
1726            .unwrap();
1727
1728        let listed = tm
1729            .list_tasks(TaskFilter {
1730                status: Some("all".to_string()),
1731                source: None,
1732            })
1733            .await
1734            .unwrap();
1735        assert_eq!(listed.len(), 2);
1736        assert!(listed.iter().any(|task| matches!(
1737            task,
1738            Task::External(external) if external.id.0 == "302"
1739        )));
1740        assert!(listed.iter().any(|task| matches!(
1741            task,
1742            Task::Internal(internal) if internal.id == internal_id
1743        )));
1744    }
1745
1746    // ── store-first update_task_status ──────────────────────────────
1747
1748    #[tokio::test]
1749    async fn update_task_status_writes_store_first_for_external() {
1750        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1751        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1752        let tm = TaskManager::with_store(
1753            Arc::clone(&backend),
1754            Arc::clone(&store),
1755            "owner/repo".to_string(),
1756        );
1757
1758        // Upsert an external task
1759        let store_id = store
1760            .upsert_external(&crate::store::UpsertExternal {
1761                repo: "owner/repo",
1762                ext_id: "42",
1763                title: "Test",
1764                body: "",
1765                author: "user",
1766                url: "",
1767                labels: &[],
1768                origin: "github",
1769            })
1770            .await
1771            .unwrap();
1772        assert_eq!(store.get(store_id).await.unwrap().status, TaskStatus::New);
1773
1774        // Update via task_manager — store should update first
1775        let ext_id = ExternalId("42".to_string());
1776        tm.update_task_status(&ext_id, Status::Routed)
1777            .await
1778            .unwrap();
1779
1780        // Store should now have Routed
1781        let task = store.get(store_id).await.unwrap();
1782        assert_eq!(task.status, TaskStatus::Routed);
1783    }
1784
1785    #[tokio::test]
1786    async fn update_task_status_handles_internal_tasks() {
1787        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1788        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1789        let tm = TaskManager::with_store(
1790            Arc::clone(&backend),
1791            Arc::clone(&store),
1792            "owner/repo".to_string(),
1793        );
1794
1795        // Create an internal task
1796        let store_id = store
1797            .create_internal("owner/repo", "task", "body", "manual", "", None)
1798            .await
1799            .unwrap();
1800
1801        let internal_id = ExternalId(format!("internal:{store_id}"));
1802        tm.update_task_status(&internal_id, Status::InProgress)
1803            .await
1804            .unwrap();
1805
1806        let task = store.get(store_id).await.unwrap();
1807        assert_eq!(task.status, TaskStatus::InProgress);
1808    }
1809
1810    #[tokio::test]
1811    async fn update_task_status_publishes_event() {
1812        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1813        let (tx, mut rx) = broadcast::channel::<TaskEvent>(16);
1814        let tm = TaskManager {
1815            backend,
1816            store: None,
1817            repo: "owner/repo".to_string(),
1818            event_tx: Some(tx),
1819        };
1820        // External task — backend mock accepts any status update
1821        let id = ExternalId("42".to_string());
1822        tm.update_task_status(&id, Status::Routed).await.unwrap();
1823        let event = rx.try_recv().unwrap();
1824        assert_eq!(event.task_id, "42");
1825        assert_eq!(event.new_status, "routed");
1826        assert_eq!(event.repo, "owner/repo");
1827    }
1828
1829    #[tokio::test]
1830    async fn event_includes_old_status_and_context() {
1831        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1832        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1833        let (tx, mut rx) = broadcast::channel::<TaskEvent>(16);
1834
1835        // Upsert an external task (starts as New)
1836        let store_id = store
1837            .upsert_external(&crate::store::UpsertExternal {
1838                repo: "owner/repo",
1839                ext_id: "77",
1840                title: "Context test",
1841                body: "",
1842                author: "user",
1843                url: "",
1844                labels: &[],
1845                origin: "github",
1846            })
1847            .await
1848            .unwrap();
1849
1850        // Set some context fields on the task
1851        store
1852            .set_fields(
1853                store_id,
1854                &[
1855                    ("agent", serde_json::Value::String("claude".to_string())),
1856                    ("model", serde_json::Value::String("sonnet".to_string())),
1857                    ("branch", serde_json::Value::String("feat-77".to_string())),
1858                    ("pr_number", serde_json::Value::Number(42.into())),
1859                    (
1860                        "last_error",
1861                        serde_json::Value::String("timeout".to_string()),
1862                    ),
1863                ],
1864            )
1865            .await
1866            .unwrap();
1867
1868        let tm =
1869            TaskManager::with_events(backend, Arc::clone(&store), "owner/repo".to_string(), tx);
1870
1871        // Update New → Routed
1872        let ext_id = ExternalId("77".to_string());
1873        tm.update_task_status(&ext_id, Status::Routed)
1874            .await
1875            .unwrap();
1876
1877        let event = rx.try_recv().unwrap();
1878        assert_eq!(event.task_id, "77");
1879        assert_eq!(event.old_status, "new");
1880        assert_eq!(event.new_status, "routed");
1881        assert_eq!(event.agent.as_deref(), Some("claude"));
1882        assert_eq!(event.model.as_deref(), Some("sonnet"));
1883        assert_eq!(event.branch.as_deref(), Some("feat-77"));
1884        assert_eq!(event.pr_number.as_deref(), Some("42"));
1885        assert_eq!(event.error.as_deref(), Some("timeout"));
1886    }
1887
1888    #[tokio::test]
1889    async fn event_includes_old_status_for_internal_task() {
1890        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1891        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1892        let (tx, mut rx) = broadcast::channel::<TaskEvent>(16);
1893
1894        // Create an internal task (starts as New)
1895        let store_id = store
1896            .create_internal(
1897                "owner/repo",
1898                "internal ctx test",
1899                "body",
1900                "manual",
1901                "",
1902                None,
1903            )
1904            .await
1905            .unwrap();
1906
1907        let tm =
1908            TaskManager::with_events(backend, Arc::clone(&store), "owner/repo".to_string(), tx);
1909
1910        // Update New → Routed
1911        let internal_id = ExternalId(format!("internal:{store_id}"));
1912        tm.update_task_status(&internal_id, Status::Routed)
1913            .await
1914            .unwrap();
1915
1916        let event = rx.try_recv().unwrap();
1917        assert_eq!(event.old_status, "new");
1918        assert_eq!(event.new_status, "routed");
1919
1920        // Update Routed → InProgress
1921        tm.update_task_status(&internal_id, Status::InProgress)
1922            .await
1923            .unwrap();
1924
1925        let event2 = rx.try_recv().unwrap();
1926        assert_eq!(event2.old_status, "routed");
1927        assert_eq!(event2.new_status, "in_progress");
1928    }
1929
1930    // ── update_task_status_if ────────────────────────────────────────
1931
1932    #[tokio::test]
1933    async fn update_task_status_if_applies_when_status_matches() {
1934        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1935        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1936        let tm = TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
1937
1938        let store_id = store
1939            .upsert_external(&crate::store::UpsertExternal {
1940                repo: "owner/repo",
1941                ext_id: "10",
1942                title: "T",
1943                body: "",
1944                author: "u",
1945                url: "",
1946                labels: &[],
1947                origin: "github",
1948            })
1949            .await
1950            .unwrap();
1951        // Task starts as New; move it to InReview first
1952        store
1953            .update_status(store_id, TaskStatus::InReview)
1954            .await
1955            .unwrap();
1956
1957        let id = ExternalId("10".to_string());
1958        let updated = tm
1959            .update_task_status_if(&id, Status::NeedsReview, Status::InReview)
1960            .await
1961            .unwrap();
1962        assert!(updated, "should update when expected status matches");
1963
1964        let task = store.get(store_id).await.unwrap();
1965        assert_eq!(task.status, TaskStatus::NeedsReview);
1966    }
1967
1968    #[tokio::test]
1969    async fn update_task_status_if_is_noop_when_status_mismatches() {
1970        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1971        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
1972        let (tx, mut rx) = broadcast::channel::<TaskEvent>(16);
1973        let tm =
1974            TaskManager::with_events(backend, Arc::clone(&store), "owner/repo".to_string(), tx);
1975
1976        let store_id = store
1977            .upsert_external(&crate::store::UpsertExternal {
1978                repo: "owner/repo",
1979                ext_id: "11",
1980                title: "T",
1981                body: "",
1982                author: "u",
1983                url: "",
1984                labels: &[],
1985                origin: "github",
1986            })
1987            .await
1988            .unwrap();
1989        // Simulate a concurrent transition: task already moved to Done
1990        store
1991            .update_status(store_id, TaskStatus::Done)
1992            .await
1993            .unwrap();
1994
1995        let id = ExternalId("11".to_string());
1996        // Attempt to reset to NeedsReview expecting InReview — should be a no-op
1997        let updated = tm
1998            .update_task_status_if(&id, Status::NeedsReview, Status::InReview)
1999            .await
2000            .unwrap();
2001        assert!(
2002            !updated,
2003            "should not update when status has already changed"
2004        );
2005
2006        // Status must remain Done
2007        let task = store.get(store_id).await.unwrap();
2008        assert_eq!(task.status, TaskStatus::Done);
2009
2010        // No event must be published
2011        assert!(
2012            rx.try_recv().is_err(),
2013            "no event should be published on a no-op update"
2014        );
2015    }
2016    async fn duration_fixture(
2017        internal: bool,
2018    ) -> (
2019        TaskManager,
2020        Arc<TaskStore>,
2021        i64,
2022        ExternalId,
2023        broadcast::Receiver<TaskEvent>,
2024    ) {
2025        let store = Arc::new(TaskStore::open_memory().await.unwrap());
2026        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
2027        let (tx, rx) = broadcast::channel::<TaskEvent>(16);
2028        let (store_id, id) = if internal {
2029            let sid = store
2030                .create_internal("owner/repo", "task", "body", "manual", "", None)
2031                .await
2032                .unwrap();
2033            (sid, ExternalId(format!("internal:{sid}")))
2034        } else {
2035            let sid = store
2036                .upsert_external(&crate::store::UpsertExternal {
2037                    repo: "owner/repo",
2038                    ext_id: "91",
2039                    title: "t",
2040                    body: "",
2041                    author: "user",
2042                    url: "",
2043                    labels: &[],
2044                    origin: "github",
2045                })
2046                .await
2047                .unwrap();
2048            (sid, ExternalId("91".to_string()))
2049        };
2050        store
2051            .set_block_reason(store_id, Some("stale reason"))
2052            .await
2053            .unwrap();
2054        let tm =
2055            TaskManager::with_events(backend, Arc::clone(&store), "owner/repo".to_string(), tx);
2056        (tm, store, store_id, id, rx)
2057    }
2058
2059    #[tokio::test]
2060    async fn status_update_clears_block_reason_and_publishes_event_for_both_kinds() {
2061        for internal in [false, true] {
2062            let (tm, store, store_id, id, mut rx) = duration_fixture(internal).await;
2063            tm.update_task_status(&id, Status::Routed).await.unwrap();
2064            let task = store.get(store_id).await.unwrap();
2065            assert_eq!(task.status, TaskStatus::Routed);
2066            assert_eq!(task.block_reason, None);
2067            let event = rx.try_recv().unwrap();
2068            assert_eq!(event.old_status, "new");
2069            assert_eq!(event.new_status, "routed");
2070            assert_eq!(event.duration_seconds, None);
2071        }
2072    }
2073
2074    #[tokio::test]
2075    async fn status_update_with_duration_clears_block_reason_and_carries_duration() {
2076        for internal in [false, true] {
2077            let (tm, store, store_id, id, mut rx) = duration_fixture(internal).await;
2078            tm.update_task_status_with_duration(&id, Status::Routed, Some(12.5))
2079                .await
2080                .unwrap();
2081            let task = store.get(store_id).await.unwrap();
2082            assert_eq!(task.status, TaskStatus::Routed);
2083            assert_eq!(task.block_reason, None);
2084            let event = rx.try_recv().unwrap();
2085            assert_eq!(event.old_status, "new");
2086            assert_eq!(event.new_status, "routed");
2087            assert_eq!(event.duration_seconds, Some(12.5));
2088        }
2089    }
2090
2091    #[tokio::test]
2092    async fn status_update_to_blocked_keeps_block_reason() {
2093        for internal in [false, true] {
2094            let (tm, store, store_id, id, _rx) = duration_fixture(internal).await;
2095            tm.update_task_status(&id, Status::Blocked).await.unwrap();
2096            let task = store.get(store_id).await.unwrap();
2097            assert_eq!(task.status, TaskStatus::Blocked);
2098            assert_eq!(task.block_reason.as_deref(), Some("stale reason"));
2099
2100            let (tm, store, store_id, id, _rx) = duration_fixture(internal).await;
2101            tm.update_task_status_with_duration(&id, Status::Blocked, None)
2102                .await
2103                .unwrap();
2104            let task = store.get(store_id).await.unwrap();
2105            assert_eq!(task.block_reason.as_deref(), Some("stale reason"));
2106        }
2107    }
2108
2109    #[tokio::test]
2110    async fn status_update_internal_without_store_or_row_errors() {
2111        let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
2112        let tm = TaskManager::new(Arc::clone(&backend));
2113        let id = ExternalId("internal:1".to_string());
2114        assert!(tm.update_task_status(&id, Status::Routed).await.is_err());
2115        assert!(
2116            tm.update_task_status_with_duration(&id, Status::Routed, None)
2117                .await
2118                .is_err()
2119        );
2120    }
2121}