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