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