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