1pub mod github;
7
8use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct ExternalId(pub String);
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct Mention {
18 pub id: String,
20 pub body: String,
22 pub author: String,
24 pub created_at: String,
26 pub issue_url: Option<String>,
29}
30
31#[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#[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct PullRequestCompletion {
107 pub merged: bool,
108 pub base_ref: String,
109 pub default_branch: String,
110 pub approved: bool,
111 pub closed: bool,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum BlockedByFetch {
121 Native(Vec<BlockedByIssue>),
122 Unavailable,
123 Failed(String),
124}
125
126#[allow(clippy::double_must_use)] #[async_trait]
132pub trait ExternalBackend: Send + Sync {
133 fn name(&self) -> &str;
135
136 async fn create_task(
138 &self,
139 title: &str,
140 body: &str,
141 labels: &[String],
142 ) -> anyhow::Result<ExternalId>;
143
144 async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask>;
146
147 async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
161 let label = status.as_label();
162
163 if let Err(e) = self.ensure_status_label(label).await {
165 tracing::warn!(label, err = %e, "ensure_status_label failed, continuing");
166 }
167
168 const MAX_RETRIES: u32 = 3;
169 let mut last_err =
170 anyhow::anyhow!("update_status({label}) failed: all {MAX_RETRIES} attempts exhausted");
171
172 for attempt in 0..MAX_RETRIES {
173 if attempt > 0 {
174 tokio::time::sleep(std::time::Duration::from_millis(500 * u64::from(attempt)))
175 .await;
176 tracing::debug!(attempt, label, "retrying update_status");
177 }
178
179 let task = match self.get_task(id).await {
181 Ok(t) => t,
182 Err(e) => {
183 last_err = e;
184 continue;
185 }
186 };
187
188 let mut remove_failed = false;
190 for old in task
191 .labels
192 .iter()
193 .filter(|l| l.starts_with("status:") && l.as_str() != label)
194 {
195 if let Err(e) = self.remove_label(id, old).await {
196 tracing::warn!(old_label = %old, err = %e, attempt, "remove_label failed");
197 last_err = e;
198 remove_failed = true;
199 break;
200 }
201 }
202 if remove_failed {
203 continue;
204 }
205
206 match self.set_labels(id, &[label.to_string()]).await {
208 Ok(()) => return Ok(()),
209 Err(e) => {
210 tracing::warn!(label, err = %e, attempt, "set_labels failed");
211 last_err = e;
212 }
213 }
214 }
215
216 Err(last_err.context(format!(
217 "update_status({label}) failed after {MAX_RETRIES} attempts"
218 )))
219 }
220
221 async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>>;
223
224 async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
229 let statuses = [
232 Status::New,
233 Status::Routed,
234 Status::InProgress,
235 Status::Done,
236 Status::Blocked,
237 Status::InReview,
238 Status::NeedsReview,
239 Status::Waiting,
240 ];
241 let mut all_tasks = Vec::new();
242 for status in statuses {
243 let tasks = self.list_by_status(status).await?;
244 all_tasks.extend(tasks);
245 }
246 Ok(all_tasks)
247 }
248
249 async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
254 Ok(Vec::new())
255 }
256
257 async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
261 self.list_by_status(Status::New).await
262 }
263
264 async fn list_active_open_issues(
275 &self,
276 _since: Option<&str>,
277 ) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
278 let mut seen = std::collections::HashSet::new();
279 let mut result = Vec::new();
280
281 if let Ok(routable) = self.list_routable().await {
283 for task in routable {
284 if seen.insert(task.id.0.clone()) {
285 result.push((task, None));
286 }
287 }
288 }
289
290 let active_non_new = [
292 Status::Routed,
293 Status::InProgress,
294 Status::NeedsReview,
295 Status::InReview,
296 Status::Blocked,
297 Status::Waiting,
298 ];
299 for status in active_non_new {
300 if let Ok(tasks) = self.list_by_status(status).await {
301 for task in tasks {
302 if seen.insert(task.id.0.clone()) {
303 result.push((task, Some(status)));
304 }
305 }
306 }
307 }
308
309 Ok(result)
310 }
311
312 async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()>;
314
315 async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()>;
319
320 async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()>;
322
323 async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>>;
328
329 async fn create_sub_task(
335 &self,
336 parent_id: &ExternalId,
337 title: &str,
338 body: &str,
339 labels: &[String],
340 ) -> anyhow::Result<ExternalId> {
341 let mut all_labels = labels.to_vec();
343 all_labels.push(format!("parent:{}", parent_id.0));
344 self.create_task(title, body, &all_labels).await
345 }
346
347 async fn ensure_status_label(&self, _label: &str) -> anyhow::Result<()> {
353 Ok(())
354 }
355
356 async fn sync_to_project(
364 &self,
365 _id: &ExternalId,
366 _status: Status,
367 ) -> anyhow::Result<Option<String>> {
368 Ok(None)
369 }
370
371 async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
375 Ok(())
376 }
377
378 async fn sync_estimate_to_project(
384 &self,
385 _id: &ExternalId,
386 _estimate: u8,
387 ) -> anyhow::Result<()> {
388 Ok(())
389 }
390
391 async fn get_project_item_estimates(
398 &self,
399 _issue_node_ids: &[String],
400 ) -> anyhow::Result<std::collections::HashMap<String, u8>> {
401 Ok(std::collections::HashMap::new())
402 }
403
404 #[allow(dead_code)]
410 async fn has_open_issue_with_title(&self, _title: &str, _label: &str) -> anyhow::Result<bool> {
411 Ok(false)
412 }
413
414 async fn health_check(&self) -> anyhow::Result<()>;
416
417 async fn is_pr_merged(&self, _branch: &str) -> anyhow::Result<bool> {
421 Ok(false)
422 }
423
424 async fn batch_is_pr_merged(
430 &self,
431 branches: &[String],
432 ) -> anyhow::Result<std::collections::HashMap<String, bool>> {
433 let mut result = std::collections::HashMap::new();
434 for branch in branches {
435 match self.is_pr_merged(branch).await {
436 Ok(merged) => {
437 result.insert(branch.clone(), merged);
438 }
439 Err(e) => {
440 tracing::warn!(branch, err = %e, "failed to check PR merge status");
441 }
442 }
443 }
444 Ok(result)
445 }
446
447 async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
451 Ok(None)
452 }
453
454 async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
458 Ok(vec![])
459 }
460
461 async fn list_issue_comments(&self, _id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
465 Ok(vec![])
466 }
467
468 async fn acknowledge_issue(&self, _id: &ExternalId) -> anyhow::Result<()> {
473 Ok(())
474 }
475
476 async fn acknowledge_mention(&self, _comment_id: &str) -> anyhow::Result<()> {
481 Ok(())
482 }
483
484 async fn blocked_by(&self, _repo: &str, _issue_number: i64) -> anyhow::Result<BlockedByFetch> {
489 Ok(BlockedByFetch::Unavailable)
490 }
491
492 async fn issue_close_state(
496 &self,
497 _repo: &str,
498 _issue_number: i64,
499 ) -> anyhow::Result<Option<(String, Option<String>)>> {
500 Ok(None)
501 }
502
503 async fn post_comment_in_repo(
507 &self,
508 _repo: &str,
509 id: &ExternalId,
510 body: &str,
511 ) -> anyhow::Result<()> {
512 self.post_comment(id, body).await
513 }
514
515 async fn pull_request_completion(
520 &self,
521 _repo: &str,
522 _pr_number: i64,
523 ) -> anyhow::Result<Option<PullRequestCompletion>> {
524 Ok(None)
525 }
526
527 async fn add_dependency(
532 &self,
533 _issue_number: i64,
534 _blocking_repo: &str,
535 _blocking_number: i64,
536 ) -> anyhow::Result<()> {
537 anyhow::bail!("this backend cannot write issue dependencies")
538 }
539}
540
541#[cfg(test)]
542mod tests {
543 use super::*;
544 use async_trait::async_trait;
545 use std::sync::{Arc, Mutex};
546
547 struct MockBackend {
553 labels: Arc<Mutex<Vec<String>>>,
555 remove_err: Option<String>,
557 set_labels_fail_count: Arc<Mutex<u32>>,
559 }
560
561 impl MockBackend {
562 fn with_labels(labels: Vec<&str>) -> Self {
563 Self {
564 labels: Arc::new(Mutex::new(labels.into_iter().map(String::from).collect())),
565 remove_err: None,
566 set_labels_fail_count: Arc::new(Mutex::new(0)),
567 }
568 }
569
570 fn current_labels(&self) -> Vec<String> {
571 self.labels.lock().unwrap().clone()
572 }
573 }
574
575 #[async_trait]
576 impl ExternalBackend for MockBackend {
577 fn name(&self) -> &str {
578 "mock"
579 }
580
581 async fn create_task(
582 &self,
583 _title: &str,
584 _body: &str,
585 _labels: &[String],
586 ) -> anyhow::Result<ExternalId> {
587 Ok(ExternalId("1".into()))
588 }
589
590 async fn get_task(&self, _id: &ExternalId) -> anyhow::Result<ExternalTask> {
591 Ok(ExternalTask {
592 id: ExternalId("1".into()),
593 title: "mock".into(),
594 body: "".into(),
595 state: "open".into(),
596 labels: self.current_labels(),
597 author: "user".into(),
598 created_at: "2026-01-01T00:00:00Z".into(),
599 updated_at: "2026-01-01T00:00:00Z".into(),
600 url: "https://example.com".into(),
601 })
602 }
603
604 async fn list_by_status(&self, _status: Status) -> anyhow::Result<Vec<ExternalTask>> {
608 Ok(vec![])
609 }
610
611 async fn post_comment(&self, _id: &ExternalId, _body: &str) -> anyhow::Result<()> {
612 Ok(())
613 }
614
615 async fn set_labels(&self, _id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
616 let mut fail_count = self.set_labels_fail_count.lock().unwrap();
617 if *fail_count > 0 {
618 *fail_count -= 1;
619 return Err(anyhow::anyhow!("transient network error"));
620 }
621 drop(fail_count);
622 let mut current = self.labels.lock().unwrap();
623 for l in labels {
624 if !current.contains(l) {
625 current.push(l.clone());
626 }
627 }
628 Ok(())
629 }
630
631 async fn remove_label(&self, _id: &ExternalId, label: &str) -> anyhow::Result<()> {
632 if let Some(ref err_label) = self.remove_err {
633 if label == err_label {
634 return Err(anyhow::anyhow!("rate limit (429)"));
635 }
636 }
637 self.labels.lock().unwrap().retain(|l| l != label);
638 Ok(())
639 }
640
641 async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
642 Ok(vec![])
643 }
644
645 async fn health_check(&self) -> anyhow::Result<()> {
646 Ok(())
647 }
648 }
649
650 #[tokio::test]
653 async fn update_status_replaces_single_old_label() {
654 let backend = MockBackend::with_labels(vec!["status:new", "priority:high"]);
655 let id = ExternalId("1".into());
656 backend
657 .update_status(&id, Status::InProgress)
658 .await
659 .unwrap();
660 let labels = backend.current_labels();
661 assert!(
662 labels.contains(&"status:in_progress".to_string()),
663 "new label added: {labels:?}"
664 );
665 assert!(
666 !labels.contains(&"status:new".to_string()),
667 "old label removed: {labels:?}"
668 );
669 assert!(
670 labels.contains(&"priority:high".to_string()),
671 "non-status label preserved: {labels:?}"
672 );
673 }
674
675 #[tokio::test]
676 async fn update_status_removes_multiple_old_status_labels() {
677 let backend = MockBackend::with_labels(vec!["status:in_progress", "status:blocked", "bug"]);
679 let id = ExternalId("1".into());
680 backend.update_status(&id, Status::Done).await.unwrap();
681 let labels = backend.current_labels();
682 let status_labels: Vec<_> = labels.iter().filter(|l| l.starts_with("status:")).collect();
683 assert_eq!(
684 status_labels,
685 vec!["status:done"],
686 "exactly one status label: {labels:?}"
687 );
688 }
689
690 #[tokio::test]
691 async fn update_status_is_idempotent() {
692 let backend = MockBackend::with_labels(vec!["status:done"]);
693 let id = ExternalId("1".into());
694 backend.update_status(&id, Status::Done).await.unwrap();
695 let labels = backend.current_labels();
696 let status_count = labels.iter().filter(|l| l.starts_with("status:")).count();
697 assert_eq!(
698 status_count, 1,
699 "idempotent: still exactly one status label: {labels:?}"
700 );
701 }
702
703 #[tokio::test]
704 async fn update_status_non_status_labels_are_preserved() {
705 let backend =
706 MockBackend::with_labels(vec!["status:routed", "agent:claude", "maintenance"]);
707 let id = ExternalId("1".into());
708 backend
709 .update_status(&id, Status::InProgress)
710 .await
711 .unwrap();
712 let labels = backend.current_labels();
713 assert!(
714 labels.contains(&"agent:claude".to_string()),
715 "agent label preserved: {labels:?}"
716 );
717 assert!(
718 labels.contains(&"maintenance".to_string()),
719 "other label preserved: {labels:?}"
720 );
721 }
722
723 #[tokio::test]
724 async fn lifecycle_transition_preserves_board_label_and_no_agent_hold() {
725 let backend = MockBackend::with_labels(vec!["status:new", "board:held", "no-agent"]);
726 backend
727 .update_status(&ExternalId("1".into()), Status::Routed)
728 .await
729 .unwrap();
730 let mut labels = backend.current_labels();
731 labels.sort();
732 assert_eq!(labels, vec!["board:held", "no-agent", "status:routed"]);
733 }
734
735 #[tokio::test]
736 async fn update_status_retries_on_transient_set_labels_failure() {
737 let backend = MockBackend::with_labels(vec!["status:new"]);
738 *backend.set_labels_fail_count.lock().unwrap() = 1;
740 let id = ExternalId("1".into());
741 backend
742 .update_status(&id, Status::InProgress)
743 .await
744 .unwrap();
745 let labels = backend.current_labels();
746 assert!(
747 labels.contains(&"status:in_progress".to_string()),
748 "label added after retry: {labels:?}"
749 );
750 assert!(
751 !labels.contains(&"status:new".to_string()),
752 "old label removed: {labels:?}"
753 );
754 }
755
756 #[tokio::test]
757 async fn update_status_fails_after_max_retries() {
758 let backend = MockBackend::with_labels(vec!["status:new"]);
759 *backend.set_labels_fail_count.lock().unwrap() = 10;
761 let id = ExternalId("1".into());
762 let result = backend.update_status(&id, Status::Done).await;
763 assert!(result.is_err(), "should fail after max retries");
764 assert!(
765 result
766 .unwrap_err()
767 .to_string()
768 .contains("failed after 3 attempts"),
769 "error message mentions retry exhaustion"
770 );
771 }
772
773 #[test]
774 fn status_as_label() {
775 assert_eq!(Status::New.as_label(), "status:new");
776 assert_eq!(Status::Routed.as_label(), "status:routed");
777 assert_eq!(Status::InProgress.as_label(), "status:in_progress");
778 assert_eq!(Status::Done.as_label(), "status:done");
779 assert_eq!(Status::Blocked.as_label(), "status:blocked");
780 assert_eq!(Status::InReview.as_label(), "status:in_review");
781 assert_eq!(Status::NeedsReview.as_label(), "status:needs_review");
782 }
783
784 #[test]
785 fn status_serializes_snake_case() {
786 let json = serde_json::to_string(&Status::InProgress).unwrap();
787 assert_eq!(json, "\"in_progress\"");
788 }
789
790 #[test]
791 fn status_deserializes_snake_case() {
792 let status: Status = serde_json::from_str("\"needs_review\"").unwrap();
793 assert_eq!(status, Status::NeedsReview);
794 }
795
796 #[test]
797 fn external_id_clone() {
798 let id = ExternalId("42".to_string());
799 let cloned = id.clone();
800 assert_eq!(id.0, cloned.0);
801 }
802
803 #[test]
804 fn external_task_serializes() {
805 let task = ExternalTask {
806 id: ExternalId("1".to_string()),
807 title: "Test".to_string(),
808 body: "Body".to_string(),
809 state: "open".to_string(),
810 labels: vec!["status:new".to_string()],
811 author: "user".to_string(),
812 created_at: "2026-01-01T00:00:00Z".to_string(),
813 updated_at: "2026-01-01T00:00:00Z".to_string(),
814 url: "https://github.com/test/test/issues/1".to_string(),
815 };
816 let json = serde_json::to_string(&task).unwrap();
817 assert!(json.contains("\"title\":\"Test\""));
818 assert!(json.contains("status:new"));
819 }
820}
821
822#[cfg(test)]
823pub(crate) mod test_helpers;