1pub 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#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct ExternalId(pub String);
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct Mention {
25 pub id: String,
27 pub body: String,
29 pub author: String,
31 pub created_at: String,
33 pub issue_url: Option<String>,
36}
37
38#[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 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#[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 Approved,
80 NeedsReview,
81 Waiting,
82}
83
84impl Status {
85 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#[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#[async_trait]
143pub trait ExternalBackend: Send + Sync {
144 fn name(&self) -> &str;
146
147 async fn create_task(
149 &self,
150 title: &str,
151 body: &str,
152 labels: &[String],
153 ) -> anyhow::Result<ExternalId>;
154
155 async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask>;
157
158 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 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 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 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 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 async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>>;
233
234 async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
239 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 async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
265 Ok(Vec::new())
266 }
267
268 async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
272 self.list_by_status(Status::New).await
273 }
274
275 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 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 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 async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()>;
320
321 async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()>;
325
326 async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()>;
328
329 async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>>;
334
335 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 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 async fn ensure_status_label(&self, _label: &str) -> anyhow::Result<()> {
359 Ok(())
360 }
361
362 async fn sync_to_project(
370 &self,
371 _id: &ExternalId,
372 _status: Status,
373 ) -> anyhow::Result<Option<String>> {
374 Ok(None)
375 }
376
377 async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
381 Ok(())
382 }
383
384 async fn sync_estimate_to_project(
390 &self,
391 _id: &ExternalId,
392 _estimate: u8,
393 ) -> anyhow::Result<()> {
394 Ok(())
395 }
396
397 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 async fn has_open_issue_with_title(&self, _title: &str, _label: &str) -> anyhow::Result<bool> {
416 Ok(false)
417 }
418
419 async fn health_check(&self) -> anyhow::Result<()>;
421
422 async fn is_pr_merged(&self, _branch: &str) -> anyhow::Result<bool> {
426 Ok(false)
427 }
428
429 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 async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
456 Ok(None)
457 }
458
459 async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
463 Ok(vec![])
464 }
465
466 async fn list_issue_comments(&self, _id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
470 Ok(vec![])
471 }
472
473 async fn acknowledge_issue(&self, _id: &ExternalId) -> anyhow::Result<()> {
478 Ok(())
479 }
480
481 async fn acknowledge_mention(&self, _comment_id: &str) -> anyhow::Result<()> {
486 Ok(())
487 }
488
489 async fn blocked_by(&self, _repo: &str, _issue_number: i64) -> anyhow::Result<BlockedByFetch> {
494 Ok(BlockedByFetch::Unavailable)
495 }
496
497 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 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 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 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 struct MockBackend {
572 labels: Arc<Mutex<Vec<String>>>,
574 remove_err: Option<String>,
576 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 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 #[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 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 *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 *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;