Skip to main content

orch/backends/
mod.rs

1//! External backend abstraction — trait for issue trackers.
2//!
3//! GitHub Issues is the first implementation. The trait is designed so
4//! Linear, Jira, GitLab, or any issue tracker can be swapped in later.
5
6pub mod github;
7
8pub use crate::github::types::{BlockedByFetch, BlockedByIssue};
9use crate::store::UpsertExternal;
10use std::collections::HashMap;
11use std::collections::HashSet;
12use std::time::Duration;
13
14use async_trait::async_trait;
15use serde::{Deserialize, Serialize};
16use tokio::time;
17
18/// Opaque identifier from the external system (issue number, Linear ID, etc.)
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct ExternalId(pub String);
21
22/// A mention/comment from the external system (backend-agnostic).
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct Mention {
25    /// Unique identifier for deduplication.
26    pub id: String,
27    /// The comment/mention body text.
28    pub body: String,
29    /// Author of the mention.
30    pub author: String,
31    /// When the mention was created (RFC 3339).
32    pub created_at: String,
33    /// API URL of the issue/PR this comment belongs to.
34    /// Format: https://api.github.com/repos/owner/repo/issues/123
35    pub issue_url: Option<String>,
36}
37
38/// A task as represented in the external system.
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct ExternalTask {
41    pub id: ExternalId,
42    pub title: String,
43    pub body: String,
44    pub state: String,
45    pub labels: Vec<String>,
46    pub author: String,
47    pub created_at: String,
48    pub updated_at: String,
49    pub url: String,
50}
51
52/// The store row for a task in a repo
53impl<'a> From<(&'a ExternalTask, &'a str)> for UpsertExternal<'a> {
54    fn from((task, repo): (&'a ExternalTask, &'a str)) -> Self {
55        UpsertExternal {
56            repo,
57            ext_id: &task.id.0,
58            title: &task.title,
59            body: &task.body,
60            author: &task.author,
61            url: &task.url,
62            labels: &task.labels,
63            origin: "github",
64        }
65    }
66}
67
68/// Task status values understood by all backends.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "snake_case")]
71pub enum Status {
72    New,
73    Routed,
74    InProgress,
75    Done,
76    Blocked,
77    InReview,
78    // A review approved the PR, orch waits for CI and merges, no agent runs
79    Approved,
80    NeedsReview,
81    Waiting,
82}
83
84impl Status {
85    /// The project board column a task with this status sits in
86    pub fn board_column(&self) -> &'static str {
87        match self {
88            Self::New | Self::Routed | Self::Waiting => "backlog",
89            Self::InProgress | Self::Blocked => "in_progress",
90            Self::InReview | Self::NeedsReview | Self::Approved => "review",
91            Self::Done => "done",
92        }
93    }
94
95    pub fn as_label(&self) -> &'static str {
96        match self {
97            Self::New => "status:new",
98            Self::Routed => "status:routed",
99            Self::InProgress => "status:in_progress",
100            Self::Done => "status:done",
101            Self::Blocked => "status:blocked",
102            Self::InReview => "status:in_review",
103            Self::Approved => "status:approved",
104            Self::NeedsReview => "status:needs_review",
105            Self::Waiting => "status:waiting",
106        }
107    }
108
109    pub fn as_str(&self) -> &'static str {
110        match self {
111            Self::New => "new",
112            Self::Routed => "routed",
113            Self::InProgress => "in_progress",
114            Self::Done => "done",
115            Self::Blocked => "blocked",
116            Self::InReview => "in_review",
117            Self::Approved => "approved",
118            Self::NeedsReview => "needs_review",
119            Self::Waiting => "waiting",
120        }
121    }
122}
123
124/// Merge and review state of one pull request, read from GitHub.
125///
126/// `approved` is the latest substantive review (`APPROVED` or
127/// `CHANGES_REQUESTED`), or an approving `## Automated Review` comment from
128/// the orch reviewer account when GitHub's review list is empty
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct PullRequestCompletion {
131    pub merged: bool,
132    pub base_ref: String,
133    pub default_branch: String,
134    pub approved: bool,
135    pub closed: bool,
136}
137
138/// The core trait for external task backends.
139///
140/// Each implementation talks to a different issue tracker.
141/// The engine calls these methods without knowing which backend is active.
142pub trait ExternalBackend: TaskReader + TaskWriter + Conversation + MergeState + Tracker {}
143
144impl<T: TaskReader + TaskWriter + Conversation + MergeState + Tracker> ExternalBackend for T {}
145
146/// Reading tasks from the tracker
147#[async_trait]
148pub trait TaskReader: Send + Sync {
149    /// Fetch a task by its external ID.
150    async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask>;
151
152    /// List tasks by status.
153    async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>>;
154
155    /// List all tasks (open and closed) in a single API call.
156    ///
157    /// This is more efficient than calling `list_by_status` for each status
158    /// when you need counts or details for all statuses.
159    async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
160        // Default implementation falls back to calling list_by_status for each status
161        // This will be overridden by GitHub backend for efficiency
162        let statuses = [
163            Status::New,
164            Status::Routed,
165            Status::InProgress,
166            Status::Done,
167            Status::Blocked,
168            Status::InReview,
169            Status::Approved,
170            Status::NeedsReview,
171            Status::Waiting,
172        ];
173        let mut all_tasks = Vec::new();
174        for status in statuses {
175            let tasks = self.list_by_status(status).await?;
176            all_tasks.extend(tasks);
177        }
178        Ok(all_tasks)
179    }
180
181    /// List tasks for closed-issue reconciliation fallback.
182    ///
183    /// Used when `list_all_tasks` fails (e.g., transient API issues).
184    /// Default implementation returns an empty list, meaning no fallback data.
185    async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
186        Ok(Vec::new())
187    }
188
189    /// List open tasks that are routable — no `status:*` label yet, or `status:new`.
190    ///
191    /// Default implementation falls back to `list_by_status(New)`.
192    async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
193        self.list_by_status(Status::New).await
194    }
195
196    /// Fetch all open issues for ingest in a single logical call, returning each issue paired
197    /// with its detected status (`None` = unlabeled/routable, `Some(s)` = has status label `s`).
198    ///
199    /// The default implementation calls `list_routable()` followed by `list_by_status()` for
200    /// each active non-new status, deduplicating by ID.  Backends that support bulk listing
201    /// (e.g. GitHub) should override this to fetch all open issues in one API call and
202    /// partition locally, eliminating the 1 + N fan-out.
203    async fn list_active_open_issues(&self) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
204        let mut seen = HashSet::new();
205        let mut result = Vec::new();
206
207        // Routable tasks: unlabeled issues + status:new → no status sync needed.
208        if let Ok(routable) = self.list_routable().await {
209            for task in routable {
210                if seen.insert(task.id.0.clone()) {
211                    result.push((task, None));
212                }
213            }
214        }
215
216        // Remaining active statuses (non-new) that require status sync on first ingest.
217        let active_non_new = [
218            Status::Routed,
219            Status::InProgress,
220            Status::NeedsReview,
221            Status::InReview,
222            Status::Approved,
223            Status::Blocked,
224            Status::Waiting,
225        ];
226        for status in active_non_new {
227            if let Ok(tasks) = self.list_by_status(status).await {
228                for task in tasks {
229                    if seen.insert(task.id.0.clone()) {
230                        result.push((task, Some(status)));
231                    }
232                }
233            }
234        }
235
236        Ok(result)
237    }
238
239    /// Check if an open issue with the given title already exists.
240    ///
241    /// Used for deduplication before creating issues. The `label` parameter
242    /// narrows the search to issues with a specific label.
243    /// Default returns `false` (no dedup for backends that don't support it).
244    async fn has_open_issue_with_title(&self, _title: &str, _label: &str) -> anyhow::Result<bool> {
245        Ok(false)
246    }
247}
248
249/// Creating tasks and moving their status and labels
250#[async_trait]
251pub trait TaskWriter: TaskReader + Send + Sync {
252    /// Create a task in the external system.
253    async fn create_task(
254        &self,
255        title: &str,
256        body: &str,
257        labels: &[String],
258    ) -> anyhow::Result<ExternalId>;
259
260    /// Update task status using idempotent remove + add operations.
261    ///
262    /// Default implementation retries up to 3 times with a fresh snapshot on
263    /// each attempt to narrow the TOCTOU window. Backends that provide a native
264    /// atomic status-update endpoint can override this.
265    ///
266    /// The retry loop:
267    ///   1. Fetches a fresh label snapshot via `get_task`.
268    ///   2. Removes all `status:*` labels except the target via `remove_label`.
269    ///   3. Adds the target label via `set_labels`.
270    ///
271    /// Note: labels removed in a previous attempt are already gone — the retry
272    /// re-evaluates the current state rather than undoing prior work.
273    async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
274        const MAX_RETRIES: u32 = 3;
275        let label = status.as_label();
276
277        // Hook for backends that need to auto-create labels (e.g. GitHub).
278        if let Err(e) = self.ensure_status_label(label).await {
279            tracing::warn!(label, err = %e, "ensure_status_label failed, continuing");
280        }
281
282        let mut last_err =
283            anyhow::anyhow!("update_status({label}) failed: all {MAX_RETRIES} attempts exhausted");
284
285        for attempt in 0..MAX_RETRIES {
286            if attempt > 0 {
287                time::sleep(Duration::from_millis(500 * u64::from(attempt))).await;
288                tracing::debug!(attempt, label, "retrying update_status");
289            }
290
291            // Fresh snapshot on every attempt.
292            let task = match self.get_task(id).await {
293                Ok(t) => t,
294                Err(e) => {
295                    last_err = e;
296                    continue;
297                }
298            };
299
300            // Remove all existing status labels except the target.
301            let mut remove_failed = false;
302            for old in task
303                .labels
304                .iter()
305                .filter(|l| l.starts_with("status:") && l.as_str() != label)
306            {
307                if let Err(e) = self.remove_label(id, old).await {
308                    tracing::warn!(old_label = %old, err = %e, attempt, "remove_label failed");
309                    last_err = e;
310                    remove_failed = true;
311                    break;
312                }
313            }
314            if remove_failed {
315                continue;
316            }
317
318            // Add the target status label.
319            match self.set_labels(id, &[label.to_string()]).await {
320                Ok(()) => return Ok(()),
321                Err(e) => {
322                    tracing::warn!(label, err = %e, attempt, "set_labels failed");
323                    last_err = e;
324                }
325            }
326        }
327
328        Err(last_err.context(format!(
329            "update_status({label}) failed after {MAX_RETRIES} attempts"
330        )))
331    }
332
333    /// Add metadata labels / tags (additive — does not remove existing labels).
334    /// The GitHub backend uses POST /repos/{repo}/issues/{number}/labels,
335    /// which appends to the existing label set.
336    async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()>;
337
338    /// Remove a label / tag.
339    async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()>;
340
341    /// Get sub-issues (children) of a task.
342    ///
343    /// Returns the list of external IDs for sub-issues.
344    /// Empty list means no sub-issues or sub-issues not supported.
345    async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>>;
346
347    /// Create a child task and link it as a sub-issue of the parent.
348    ///
349    /// Creates the task via `create_task`, then attempts to establish
350    /// a native sub-issue relationship. Falls back to `parent:{id}` label
351    /// if the native link fails.
352    async fn create_sub_task(
353        &self,
354        parent_id: &ExternalId,
355        title: &str,
356        body: &str,
357        labels: &[String],
358    ) -> anyhow::Result<ExternalId> {
359        // Default: create task with parent label, no native sub-issue link
360        let mut all_labels = labels.to_vec();
361        all_labels.push(format!("parent:{}", parent_id.0));
362        self.create_task(title, body, &all_labels).await
363    }
364
365    /// Ensure a status label exists in the backend system.
366    ///
367    /// Called by the default `update_status` before applying labels.
368    /// GitHub overrides this to auto-create labels on the repo.
369    /// Default is a no-op.
370    async fn ensure_status_label(&self, _label: &str) -> anyhow::Result<()> {
371        Ok(())
372    }
373}
374
375/// Comments and mentions
376#[async_trait]
377pub trait Conversation: Send + Sync {
378    /// Post a comment / activity note.
379    async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()>;
380
381    /// Get the authenticated user's username.
382    ///
383    /// Returns None by default (backends that don't support user identity).
384    async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
385        Ok(None)
386    }
387
388    /// Get recent mentions/comments since a given timestamp.
389    ///
390    /// Returns empty by default (backends that don't support mention scanning).
391    async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
392        Ok(vec![])
393    }
394
395    /// Get all comments for a specific task/issue.
396    ///
397    /// Returns empty by default (backends that don't support per-issue comment listing).
398    async fn list_issue_comments(&self, _id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
399        Ok(vec![])
400    }
401
402    /// Acknowledge a newly detected issue (e.g., add a reaction emoji).
403    ///
404    /// Called when an issue is first ingested into the store.
405    /// Default is a no-op; GitHub backend adds an eyes emoji reaction.
406    async fn acknowledge_issue(&self, _id: &ExternalId) -> anyhow::Result<()> {
407        Ok(())
408    }
409
410    /// Acknowledge a mention (comment) by reacting with the eyes emoji.
411    ///
412    /// Called when a new @mention is detected in an issue or PR comment.
413    /// Default is a no-op; GitHub backend adds an eyes emoji reaction to the comment.
414    async fn acknowledge_mention(&self, _comment_id: &str) -> anyhow::Result<()> {
415        Ok(())
416    }
417
418    /// Post a comment on an issue in `repo`, which may differ from this backend's repo.
419    ///
420    /// The default posts through `post_comment`, which uses the backend repo
421    async fn post_comment_in_repo(
422        &self,
423        _repo: &str,
424        id: &ExternalId,
425        body: &str,
426    ) -> anyhow::Result<()> {
427        self.post_comment(id, body).await
428    }
429}
430
431/// Pull request and dependency state
432#[async_trait]
433pub trait MergeState: Send + Sync {
434    /// Check if a PR/merge request for the given branch has been merged.
435    ///
436    /// Returns false by default (backends that don't track PRs).
437    async fn is_pr_merged(&self, _branch: &str) -> anyhow::Result<bool> {
438        Ok(false)
439    }
440
441    /// Check if PRs for the given branches have been merged, in a single batch.
442    ///
443    /// Returns a map of branch → merged. Backends that support batch queries
444    /// (e.g. via GraphQL) should override this; the default falls back to
445    /// serial `is_pr_merged` calls.
446    async fn batch_is_pr_merged(
447        &self,
448        branches: &[String],
449    ) -> anyhow::Result<HashMap<String, bool>> {
450        let mut result = HashMap::new();
451        for branch in branches {
452            match self.is_pr_merged(branch).await {
453                Ok(merged) => {
454                    result.insert(branch.clone(), merged);
455                }
456                Err(e) => {
457                    tracing::warn!(branch, err = %e, "failed to check PR merge status");
458                }
459            }
460        }
461        Ok(result)
462    }
463
464    /// Native blocked-by issues for `issue_number` in `repo`.
465    ///
466    /// Default is `Unavailable`, an empty native list. A 200 with an empty list
467    /// is `Native`, not this default
468    async fn blocked_by(&self, _repo: &str, _issue_number: i64) -> anyhow::Result<BlockedByFetch> {
469        Ok(BlockedByFetch::Unavailable)
470    }
471
472    /// Close state of an issue orch may not track.
473    ///
474    /// `Ok(None)` means unknown. Callers treat unknown as still open
475    async fn issue_close_state(
476        &self,
477        _repo: &str,
478        _issue_number: i64,
479    ) -> anyhow::Result<Option<(String, Option<String>)>> {
480        Ok(None)
481    }
482
483    /// Review and merge state of pull request `pr_number` in `repo`.
484    ///
485    /// `Ok(None)` means the pull request does not exist. Callers that already
486    /// know a PR number treat that as not merged
487    async fn pull_request_completion(
488        &self,
489        _repo: &str,
490        _pr_number: i64,
491    ) -> anyhow::Result<Option<PullRequestCompletion>> {
492        Ok(None)
493    }
494
495    /// Record that `issue_number` in this backend's repo is blocked by another issue.
496    ///
497    /// The blocking issue is named by repository and number. The write uses that
498    /// issue's database id, which is valid across repositories
499    async fn add_dependency(
500        &self,
501        _issue_number: i64,
502        _blocking_repo: &str,
503        _blocking_number: i64,
504    ) -> anyhow::Result<()> {
505        anyhow::bail!("this backend cannot write issue dependencies")
506    }
507}
508
509/// The tracker itself: its name, health and project board
510#[async_trait]
511pub trait Tracker: Send + Sync {
512    /// Human-readable name (e.g. "github", "linear", "jira")
513    fn name(&self) -> &str;
514
515    /// Sync a task to the project board (if configured).
516    ///
517    /// Called when a task is first ingested to ensure it appears on the
518    /// project board immediately, not just when status changes later.
519    /// Returns `Some(node_id)` if the item was added/updated on the project board,
520    /// or `None` if project sync is not configured or failed.
521    /// Default is a no-op returning `None`; GitHub backend implements project board sync.
522    async fn sync_to_project(
523        &self,
524        _id: &ExternalId,
525        _status: Status,
526    ) -> anyhow::Result<Option<String>> {
527        Ok(None)
528    }
529
530    /// Repair project display state from authoritative external labels.
531    /// Called by periodic and webhook-triggered sync, independent of ingestion.
532    /// Does not transition tasks or dispatch agents. Default is a no-op.
533    async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
534        Ok(())
535    }
536
537    /// Sync a task's estimate to the project board Estimate field.
538    ///
539    /// Called after the router assigns an estimate to a task (via `store_route`).
540    /// Writes the estimate value to GitHub Projects V2 so humans can see it on the board.
541    /// Default is a no-op; GitHub backend implements estimate project sync.
542    async fn sync_estimate_to_project(
543        &self,
544        _id: &ExternalId,
545        _estimate: u8,
546    ) -> anyhow::Result<()> {
547        Ok(())
548    }
549
550    /// Batch-fetch project item estimates for a list of issue node IDs.
551    ///
552    /// Returns a map from issue node ID → estimate value (0 if not set).
553    /// Used during ingestion to populate `tasks.estimate` from GitHub Projects
554    /// when the orch estimate is still 0.
555    /// Default returns an empty map; GitHub backend implements batch estimate fetch.
556    async fn get_project_item_estimates(
557        &self,
558        _issue_node_ids: &[String],
559    ) -> anyhow::Result<HashMap<String, u8>> {
560        Ok(HashMap::new())
561    }
562
563    /// Check if connected and authenticated.
564    async fn health_check(&self) -> anyhow::Result<()>;
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570
571    use crate::store::TaskStatus;
572    use async_trait::async_trait;
573    use std::sync::{Arc, Mutex};
574
575    #[test]
576    fn status_maps_to_board_columns() {
577        assert_eq!(Status::New.board_column(), "backlog");
578        assert_eq!(Status::Routed.board_column(), "backlog");
579        assert_eq!(Status::InProgress.board_column(), "in_progress");
580        assert_eq!(Status::Blocked.board_column(), "in_progress");
581        assert_eq!(Status::InReview.board_column(), "review");
582        assert_eq!(Status::Approved.board_column(), "review");
583        assert_eq!(Status::NeedsReview.board_column(), "review");
584        assert_eq!(Status::Done.board_column(), "done");
585    }
586
587    /// Mock backend that exercises the default trait `update_status` implementation.
588    ///
589    /// Does NOT override `update_status` — the trait default (retry loop with
590    /// get_task → remove_label → set_labels) is what runs. This means tests
591    /// verify the actual production orchestration logic, not a simplified mock.
592    struct MockBackend {
593        /// Current labels on the (single) tracked issue.
594        labels: Arc<Mutex<Vec<String>>>,
595        /// If set, `remove_label` returns this error for the matching label.
596        remove_err: Option<String>,
597        /// Counter for `set_labels` failures. Each call decrements; fails while > 0.
598        set_labels_fail_count: Arc<Mutex<u32>>,
599    }
600
601    impl MockBackend {
602        fn with_labels(labels: Vec<&str>) -> Self {
603            Self {
604                labels: Arc::new(Mutex::new(labels.into_iter().map(String::from).collect())),
605                remove_err: None,
606                set_labels_fail_count: Arc::new(Mutex::new(0)),
607            }
608        }
609
610        fn current_labels(&self) -> Vec<String> {
611            self.labels.lock().unwrap().clone()
612        }
613    }
614
615    #[async_trait]
616    impl TaskReader for MockBackend {
617        async fn get_task(&self, _id: &ExternalId) -> anyhow::Result<ExternalTask> {
618            Ok(ExternalTask {
619                id: ExternalId("1".into()),
620                title: "mock".into(),
621                body: String::new(),
622                state: "open".into(),
623                labels: self.current_labels(),
624                author: "user".into(),
625                created_at: "2026-01-01T00:00:00Z".into(),
626                updated_at: "2026-01-01T00:00:00Z".into(),
627                url: "https://example.com".into(),
628            })
629        }
630
631        async fn list_by_status(&self, _status: Status) -> anyhow::Result<Vec<ExternalTask>> {
632            Ok(vec![])
633        }
634    }
635
636    #[async_trait]
637    impl TaskWriter for MockBackend {
638        async fn create_task(
639            &self,
640            _title: &str,
641            _body: &str,
642            _labels: &[String],
643        ) -> anyhow::Result<ExternalId> {
644            Ok(ExternalId("1".into()))
645        }
646
647        async fn set_labels(&self, _id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
648            let mut fail_count = self.set_labels_fail_count.lock().unwrap();
649            if *fail_count > 0 {
650                *fail_count -= 1;
651                return Err(anyhow::anyhow!("transient network error"));
652            }
653            drop(fail_count);
654            let mut current = self.labels.lock().unwrap();
655            for l in labels {
656                if !current.contains(l) {
657                    current.push(l.clone());
658                }
659            }
660            Ok(())
661        }
662
663        async fn remove_label(&self, _id: &ExternalId, label: &str) -> anyhow::Result<()> {
664            if let Some(ref err_label) = self.remove_err
665                && label == err_label
666            {
667                return Err(anyhow::anyhow!("rate limit (429)"));
668            }
669            self.labels.lock().unwrap().retain(|l| l != label);
670            Ok(())
671        }
672
673        async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
674            Ok(vec![])
675        }
676    }
677
678    #[async_trait]
679    impl Conversation for MockBackend {
680        async fn post_comment(&self, _id: &ExternalId, _body: &str) -> anyhow::Result<()> {
681            Ok(())
682        }
683    }
684
685    impl MergeState for MockBackend {}
686
687    #[async_trait]
688    impl Tracker for MockBackend {
689        fn name(&self) -> &'static str {
690            "mock"
691        }
692
693        async fn health_check(&self) -> anyhow::Result<()> {
694            Ok(())
695        }
696    }
697
698    // --- Tests exercise the default trait update_status (retry + remove + add) ---
699
700    #[tokio::test]
701    async fn update_status_replaces_single_old_label() {
702        let backend = MockBackend::with_labels(vec!["status:new", "priority:high"]);
703        let id = ExternalId("1".into());
704        backend
705            .update_status(&id, Status::InProgress)
706            .await
707            .unwrap();
708        let labels = backend.current_labels();
709        assert!(
710            labels.contains(&"status:in_progress".to_string()),
711            "new label added: {labels:?}"
712        );
713        assert!(
714            !labels.contains(&"status:new".to_string()),
715            "old label removed: {labels:?}"
716        );
717        assert!(
718            labels.contains(&"priority:high".to_string()),
719            "non-status label preserved: {labels:?}"
720        );
721    }
722
723    #[tokio::test]
724    async fn update_status_removes_multiple_old_status_labels() {
725        // Simulate state left by a previous partial failure: two status labels
726        let backend = MockBackend::with_labels(vec!["status:in_progress", "status:blocked", "bug"]);
727        let id = ExternalId("1".into());
728        backend.update_status(&id, Status::Done).await.unwrap();
729        let labels = backend.current_labels();
730        let status_labels: Vec<_> = labels.iter().filter(|l| l.starts_with("status:")).collect();
731        assert_eq!(
732            status_labels,
733            vec!["status:done"],
734            "exactly one status label: {labels:?}"
735        );
736    }
737
738    #[tokio::test]
739    async fn update_status_is_idempotent() {
740        let backend = MockBackend::with_labels(vec!["status:done"]);
741        let id = ExternalId("1".into());
742        backend.update_status(&id, Status::Done).await.unwrap();
743        let labels = backend.current_labels();
744        let status_count = labels.iter().filter(|l| l.starts_with("status:")).count();
745        assert_eq!(
746            status_count, 1,
747            "idempotent: still exactly one status label: {labels:?}"
748        );
749    }
750
751    #[tokio::test]
752    async fn update_status_non_status_labels_are_preserved() {
753        let backend =
754            MockBackend::with_labels(vec!["status:routed", "agent:claude", "maintenance"]);
755        let id = ExternalId("1".into());
756        backend
757            .update_status(&id, Status::InProgress)
758            .await
759            .unwrap();
760        let labels = backend.current_labels();
761        assert!(
762            labels.contains(&"agent:claude".to_string()),
763            "agent label preserved: {labels:?}"
764        );
765        assert!(
766            labels.contains(&"maintenance".to_string()),
767            "other label preserved: {labels:?}"
768        );
769    }
770
771    #[tokio::test]
772    async fn lifecycle_transition_preserves_board_label_and_no_agent_hold() {
773        let backend = MockBackend::with_labels(vec!["status:new", "board:held", "no-agent"]);
774        backend
775            .update_status(&ExternalId("1".into()), Status::Routed)
776            .await
777            .unwrap();
778        let mut labels = backend.current_labels();
779        labels.sort();
780        assert_eq!(labels, vec!["board:held", "no-agent", "status:routed"]);
781    }
782
783    #[tokio::test]
784    async fn update_status_retries_on_transient_set_labels_failure() {
785        let backend = MockBackend::with_labels(vec!["status:new"]);
786        // set_labels fails once, then succeeds on retry
787        *backend.set_labels_fail_count.lock().unwrap() = 1;
788        let id = ExternalId("1".into());
789        backend
790            .update_status(&id, Status::InProgress)
791            .await
792            .unwrap();
793        let labels = backend.current_labels();
794        assert!(
795            labels.contains(&"status:in_progress".to_string()),
796            "label added after retry: {labels:?}"
797        );
798        assert!(
799            !labels.contains(&"status:new".to_string()),
800            "old label removed: {labels:?}"
801        );
802    }
803
804    #[tokio::test]
805    async fn update_status_fails_after_max_retries() {
806        let backend = MockBackend::with_labels(vec!["status:new"]);
807        // set_labels always fails (more failures than retries)
808        *backend.set_labels_fail_count.lock().unwrap() = 10;
809        let id = ExternalId("1".into());
810        let result = backend.update_status(&id, Status::Done).await;
811        assert!(result.is_err(), "should fail after max retries");
812        assert!(
813            result
814                .unwrap_err()
815                .to_string()
816                .contains("failed after 3 attempts"),
817            "error message mentions retry exhaustion"
818        );
819    }
820
821    #[test]
822    fn status_as_label() {
823        assert_eq!(Status::New.as_label(), "status:new");
824        assert_eq!(Status::Routed.as_label(), "status:routed");
825        assert_eq!(Status::InProgress.as_label(), "status:in_progress");
826        assert_eq!(Status::Done.as_label(), "status:done");
827        assert_eq!(Status::Blocked.as_label(), "status:blocked");
828        assert_eq!(Status::InReview.as_label(), "status:in_review");
829        assert_eq!(Status::Approved.as_label(), "status:approved");
830        assert_eq!(Status::Approved.as_str(), "approved");
831        assert_eq!(TaskStatus::from_str("approved"), Some(TaskStatus::Approved));
832        assert_eq!(TaskStatus::Approved.as_str(), "approved");
833        assert_eq!(Status::NeedsReview.as_label(), "status:needs_review");
834        assert_eq!(Status::Waiting.as_label(), "status:waiting");
835        assert_eq!(Status::Waiting.as_str(), "waiting");
836    }
837
838    #[test]
839    fn as_str_is_as_label_without_status_prefix() {
840        for status in [
841            Status::New,
842            Status::Routed,
843            Status::InProgress,
844            Status::Done,
845            Status::Blocked,
846            Status::InReview,
847            Status::Approved,
848            Status::NeedsReview,
849            Status::Waiting,
850        ] {
851            let label = status.as_label();
852            assert_eq!(
853                status.as_str(),
854                label.strip_prefix("status:").unwrap(),
855                "{status:?}"
856            );
857            assert_eq!(status.as_str(), label.replace("status:", ""), "{status:?}");
858            assert_eq!(
859                status.as_str(),
860                label.trim_start_matches("status:"),
861                "{status:?}"
862            );
863        }
864    }
865
866    #[test]
867    fn status_serializes_snake_case() {
868        let json = serde_json::to_string(&Status::InProgress).unwrap();
869        assert_eq!(json, "\"in_progress\"");
870    }
871
872    #[test]
873    fn status_deserializes_snake_case() {
874        let status: Status = serde_json::from_str("\"needs_review\"").unwrap();
875        assert_eq!(status, Status::NeedsReview);
876    }
877
878    #[test]
879    fn external_id_clone() {
880        let id = ExternalId("42".to_string());
881        let cloned = id.clone();
882        assert_eq!(id.0, cloned.0);
883    }
884
885    #[test]
886    fn external_task_serializes() {
887        let task = ExternalTask {
888            id: ExternalId("1".to_string()),
889            title: "Test".to_string(),
890            body: "Body".to_string(),
891            state: "open".to_string(),
892            labels: vec!["status:new".to_string()],
893            author: "user".to_string(),
894            created_at: "2026-01-01T00:00:00Z".to_string(),
895            updated_at: "2026-01-01T00:00:00Z".to_string(),
896            url: "https://github.com/test/test/issues/1".to_string(),
897        };
898        let json = serde_json::to_string(&task).unwrap();
899        assert!(json.contains("\"title\":\"Test\""));
900        assert!(json.contains("status:new"));
901    }
902}
903
904#[cfg(test)]
905pub(crate) mod test_helpers;