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