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<'a> From<(&'a ExternalTask, &'a str)> for UpsertExternal<'a> {
54 fn from((task, repo): (&'a ExternalTask, &'a str)) -> Self {
55 UpsertExternal {
56 repo,
57 ext_id: &task.id.0,
58 title: &task.title,
59 body: &task.body,
60 author: &task.author,
61 url: &task.url,
62 labels: &task.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
138pub trait ExternalBackend: TaskReader + TaskWriter + Conversation + MergeState + Tracker {}
143
144impl<T: TaskReader + TaskWriter + Conversation + MergeState + Tracker> ExternalBackend for T {}
145
146#[async_trait]
148pub trait TaskReader: Send + Sync {
149 async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask>;
151
152 async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>>;
154
155 async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
160 let statuses = [
163 Status::New,
164 Status::Routed,
165 Status::InProgress,
166 Status::Done,
167 Status::Blocked,
168 Status::InReview,
169 Status::Approved,
170 Status::NeedsReview,
171 Status::Waiting,
172 ];
173 let mut all_tasks = Vec::new();
174 for status in statuses {
175 let tasks = self.list_by_status(status).await?;
176 all_tasks.extend(tasks);
177 }
178 Ok(all_tasks)
179 }
180
181 async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
186 Ok(Vec::new())
187 }
188
189 async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
193 self.list_by_status(Status::New).await
194 }
195
196 async fn list_active_open_issues(&self) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
204 let mut seen = HashSet::new();
205 let mut result = Vec::new();
206
207 if let Ok(routable) = self.list_routable().await {
209 for task in routable {
210 if seen.insert(task.id.0.clone()) {
211 result.push((task, None));
212 }
213 }
214 }
215
216 let active_non_new = [
218 Status::Routed,
219 Status::InProgress,
220 Status::NeedsReview,
221 Status::InReview,
222 Status::Approved,
223 Status::Blocked,
224 Status::Waiting,
225 ];
226 for status in active_non_new {
227 if let Ok(tasks) = self.list_by_status(status).await {
228 for task in tasks {
229 if seen.insert(task.id.0.clone()) {
230 result.push((task, Some(status)));
231 }
232 }
233 }
234 }
235
236 Ok(result)
237 }
238
239 async fn has_open_issue_with_title(&self, _title: &str, _label: &str) -> anyhow::Result<bool> {
245 Ok(false)
246 }
247}
248
249#[async_trait]
251pub trait TaskWriter: TaskReader + Send + Sync {
252 async fn create_task(
254 &self,
255 title: &str,
256 body: &str,
257 labels: &[String],
258 ) -> anyhow::Result<ExternalId>;
259
260 async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
274 const MAX_RETRIES: u32 = 3;
275 let label = status.as_label();
276
277 if let Err(e) = self.ensure_status_label(label).await {
279 tracing::warn!(label, err = %e, "ensure_status_label failed, continuing");
280 }
281
282 let mut last_err =
283 anyhow::anyhow!("update_status({label}) failed: all {MAX_RETRIES} attempts exhausted");
284
285 for attempt in 0..MAX_RETRIES {
286 if attempt > 0 {
287 time::sleep(Duration::from_millis(500 * u64::from(attempt))).await;
288 tracing::debug!(attempt, label, "retrying update_status");
289 }
290
291 let task = match self.get_task(id).await {
293 Ok(t) => t,
294 Err(e) => {
295 last_err = e;
296 continue;
297 }
298 };
299
300 let mut remove_failed = false;
302 for old in task
303 .labels
304 .iter()
305 .filter(|l| l.starts_with("status:") && l.as_str() != label)
306 {
307 if let Err(e) = self.remove_label(id, old).await {
308 tracing::warn!(old_label = %old, err = %e, attempt, "remove_label failed");
309 last_err = e;
310 remove_failed = true;
311 break;
312 }
313 }
314 if remove_failed {
315 continue;
316 }
317
318 match self.set_labels(id, &[label.to_string()]).await {
320 Ok(()) => return Ok(()),
321 Err(e) => {
322 tracing::warn!(label, err = %e, attempt, "set_labels failed");
323 last_err = e;
324 }
325 }
326 }
327
328 Err(last_err.context(format!(
329 "update_status({label}) failed after {MAX_RETRIES} attempts"
330 )))
331 }
332
333 async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()>;
337
338 async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()>;
340
341 async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>>;
346
347 async fn create_sub_task(
353 &self,
354 parent_id: &ExternalId,
355 title: &str,
356 body: &str,
357 labels: &[String],
358 ) -> anyhow::Result<ExternalId> {
359 let mut all_labels = labels.to_vec();
361 all_labels.push(format!("parent:{}", parent_id.0));
362 self.create_task(title, body, &all_labels).await
363 }
364
365 async fn ensure_status_label(&self, _label: &str) -> anyhow::Result<()> {
371 Ok(())
372 }
373}
374
375#[async_trait]
377pub trait Conversation: Send + Sync {
378 async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()>;
380
381 async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
385 Ok(None)
386 }
387
388 async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
392 Ok(vec![])
393 }
394
395 async fn list_issue_comments(&self, _id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
399 Ok(vec![])
400 }
401
402 async fn acknowledge_issue(&self, _id: &ExternalId) -> anyhow::Result<()> {
407 Ok(())
408 }
409
410 async fn acknowledge_mention(&self, _comment_id: &str) -> anyhow::Result<()> {
415 Ok(())
416 }
417
418 async fn post_comment_in_repo(
422 &self,
423 _repo: &str,
424 id: &ExternalId,
425 body: &str,
426 ) -> anyhow::Result<()> {
427 self.post_comment(id, body).await
428 }
429}
430
431#[async_trait]
433pub trait MergeState: Send + Sync {
434 async fn is_pr_merged(&self, _branch: &str) -> anyhow::Result<bool> {
438 Ok(false)
439 }
440
441 async fn batch_is_pr_merged(
447 &self,
448 branches: &[String],
449 ) -> anyhow::Result<HashMap<String, bool>> {
450 let mut result = HashMap::new();
451 for branch in branches {
452 match self.is_pr_merged(branch).await {
453 Ok(merged) => {
454 result.insert(branch.clone(), merged);
455 }
456 Err(e) => {
457 tracing::warn!(branch, err = %e, "failed to check PR merge status");
458 }
459 }
460 }
461 Ok(result)
462 }
463
464 async fn blocked_by(&self, _repo: &str, _issue_number: i64) -> anyhow::Result<BlockedByFetch> {
469 Ok(BlockedByFetch::Unavailable)
470 }
471
472 async fn issue_close_state(
476 &self,
477 _repo: &str,
478 _issue_number: i64,
479 ) -> anyhow::Result<Option<(String, Option<String>)>> {
480 Ok(None)
481 }
482
483 async fn pull_request_completion(
488 &self,
489 _repo: &str,
490 _pr_number: i64,
491 ) -> anyhow::Result<Option<PullRequestCompletion>> {
492 Ok(None)
493 }
494
495 async fn add_dependency(
500 &self,
501 _issue_number: i64,
502 _blocking_repo: &str,
503 _blocking_number: i64,
504 ) -> anyhow::Result<()> {
505 anyhow::bail!("this backend cannot write issue dependencies")
506 }
507}
508
509#[async_trait]
511pub trait Tracker: Send + Sync {
512 fn name(&self) -> &str;
514
515 async fn sync_to_project(
523 &self,
524 _id: &ExternalId,
525 _status: Status,
526 ) -> anyhow::Result<Option<String>> {
527 Ok(None)
528 }
529
530 async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
534 Ok(())
535 }
536
537 async fn sync_estimate_to_project(
543 &self,
544 _id: &ExternalId,
545 _estimate: u8,
546 ) -> anyhow::Result<()> {
547 Ok(())
548 }
549
550 async fn get_project_item_estimates(
557 &self,
558 _issue_node_ids: &[String],
559 ) -> anyhow::Result<HashMap<String, u8>> {
560 Ok(HashMap::new())
561 }
562
563 async fn health_check(&self) -> anyhow::Result<()>;
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570
571 use crate::store::TaskStatus;
572 use async_trait::async_trait;
573 use std::sync::{Arc, Mutex};
574
575 #[test]
576 fn status_maps_to_board_columns() {
577 assert_eq!(Status::New.board_column(), "backlog");
578 assert_eq!(Status::Routed.board_column(), "backlog");
579 assert_eq!(Status::InProgress.board_column(), "in_progress");
580 assert_eq!(Status::Blocked.board_column(), "in_progress");
581 assert_eq!(Status::InReview.board_column(), "review");
582 assert_eq!(Status::Approved.board_column(), "review");
583 assert_eq!(Status::NeedsReview.board_column(), "review");
584 assert_eq!(Status::Done.board_column(), "done");
585 }
586
587 struct MockBackend {
593 labels: Arc<Mutex<Vec<String>>>,
595 remove_err: Option<String>,
597 set_labels_fail_count: Arc<Mutex<u32>>,
599 }
600
601 impl MockBackend {
602 fn with_labels(labels: Vec<&str>) -> Self {
603 Self {
604 labels: Arc::new(Mutex::new(labels.into_iter().map(String::from).collect())),
605 remove_err: None,
606 set_labels_fail_count: Arc::new(Mutex::new(0)),
607 }
608 }
609
610 fn current_labels(&self) -> Vec<String> {
611 self.labels.lock().unwrap().clone()
612 }
613 }
614
615 #[async_trait]
616 impl TaskReader for MockBackend {
617 async fn get_task(&self, _id: &ExternalId) -> anyhow::Result<ExternalTask> {
618 Ok(ExternalTask {
619 id: ExternalId("1".into()),
620 title: "mock".into(),
621 body: String::new(),
622 state: "open".into(),
623 labels: self.current_labels(),
624 author: "user".into(),
625 created_at: "2026-01-01T00:00:00Z".into(),
626 updated_at: "2026-01-01T00:00:00Z".into(),
627 url: "https://example.com".into(),
628 })
629 }
630
631 async fn list_by_status(&self, _status: Status) -> anyhow::Result<Vec<ExternalTask>> {
632 Ok(vec![])
633 }
634 }
635
636 #[async_trait]
637 impl TaskWriter for MockBackend {
638 async fn create_task(
639 &self,
640 _title: &str,
641 _body: &str,
642 _labels: &[String],
643 ) -> anyhow::Result<ExternalId> {
644 Ok(ExternalId("1".into()))
645 }
646
647 async fn set_labels(&self, _id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
648 let mut fail_count = self.set_labels_fail_count.lock().unwrap();
649 if *fail_count > 0 {
650 *fail_count -= 1;
651 return Err(anyhow::anyhow!("transient network error"));
652 }
653 drop(fail_count);
654 let mut current = self.labels.lock().unwrap();
655 for l in labels {
656 if !current.contains(l) {
657 current.push(l.clone());
658 }
659 }
660 Ok(())
661 }
662
663 async fn remove_label(&self, _id: &ExternalId, label: &str) -> anyhow::Result<()> {
664 if let Some(ref err_label) = self.remove_err
665 && label == err_label
666 {
667 return Err(anyhow::anyhow!("rate limit (429)"));
668 }
669 self.labels.lock().unwrap().retain(|l| l != label);
670 Ok(())
671 }
672
673 async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
674 Ok(vec![])
675 }
676 }
677
678 #[async_trait]
679 impl Conversation for MockBackend {
680 async fn post_comment(&self, _id: &ExternalId, _body: &str) -> anyhow::Result<()> {
681 Ok(())
682 }
683 }
684
685 impl MergeState for MockBackend {}
686
687 #[async_trait]
688 impl Tracker for MockBackend {
689 fn name(&self) -> &'static str {
690 "mock"
691 }
692
693 async fn health_check(&self) -> anyhow::Result<()> {
694 Ok(())
695 }
696 }
697
698 #[tokio::test]
701 async fn update_status_replaces_single_old_label() {
702 let backend = MockBackend::with_labels(vec!["status:new", "priority:high"]);
703 let id = ExternalId("1".into());
704 backend
705 .update_status(&id, Status::InProgress)
706 .await
707 .unwrap();
708 let labels = backend.current_labels();
709 assert!(
710 labels.contains(&"status:in_progress".to_string()),
711 "new label added: {labels:?}"
712 );
713 assert!(
714 !labels.contains(&"status:new".to_string()),
715 "old label removed: {labels:?}"
716 );
717 assert!(
718 labels.contains(&"priority:high".to_string()),
719 "non-status label preserved: {labels:?}"
720 );
721 }
722
723 #[tokio::test]
724 async fn update_status_removes_multiple_old_status_labels() {
725 let backend = MockBackend::with_labels(vec!["status:in_progress", "status:blocked", "bug"]);
727 let id = ExternalId("1".into());
728 backend.update_status(&id, Status::Done).await.unwrap();
729 let labels = backend.current_labels();
730 let status_labels: Vec<_> = labels.iter().filter(|l| l.starts_with("status:")).collect();
731 assert_eq!(
732 status_labels,
733 vec!["status:done"],
734 "exactly one status label: {labels:?}"
735 );
736 }
737
738 #[tokio::test]
739 async fn update_status_is_idempotent() {
740 let backend = MockBackend::with_labels(vec!["status:done"]);
741 let id = ExternalId("1".into());
742 backend.update_status(&id, Status::Done).await.unwrap();
743 let labels = backend.current_labels();
744 let status_count = labels.iter().filter(|l| l.starts_with("status:")).count();
745 assert_eq!(
746 status_count, 1,
747 "idempotent: still exactly one status label: {labels:?}"
748 );
749 }
750
751 #[tokio::test]
752 async fn update_status_non_status_labels_are_preserved() {
753 let backend =
754 MockBackend::with_labels(vec!["status:routed", "agent:claude", "maintenance"]);
755 let id = ExternalId("1".into());
756 backend
757 .update_status(&id, Status::InProgress)
758 .await
759 .unwrap();
760 let labels = backend.current_labels();
761 assert!(
762 labels.contains(&"agent:claude".to_string()),
763 "agent label preserved: {labels:?}"
764 );
765 assert!(
766 labels.contains(&"maintenance".to_string()),
767 "other label preserved: {labels:?}"
768 );
769 }
770
771 #[tokio::test]
772 async fn lifecycle_transition_preserves_board_label_and_no_agent_hold() {
773 let backend = MockBackend::with_labels(vec!["status:new", "board:held", "no-agent"]);
774 backend
775 .update_status(&ExternalId("1".into()), Status::Routed)
776 .await
777 .unwrap();
778 let mut labels = backend.current_labels();
779 labels.sort();
780 assert_eq!(labels, vec!["board:held", "no-agent", "status:routed"]);
781 }
782
783 #[tokio::test]
784 async fn update_status_retries_on_transient_set_labels_failure() {
785 let backend = MockBackend::with_labels(vec!["status:new"]);
786 *backend.set_labels_fail_count.lock().unwrap() = 1;
788 let id = ExternalId("1".into());
789 backend
790 .update_status(&id, Status::InProgress)
791 .await
792 .unwrap();
793 let labels = backend.current_labels();
794 assert!(
795 labels.contains(&"status:in_progress".to_string()),
796 "label added after retry: {labels:?}"
797 );
798 assert!(
799 !labels.contains(&"status:new".to_string()),
800 "old label removed: {labels:?}"
801 );
802 }
803
804 #[tokio::test]
805 async fn update_status_fails_after_max_retries() {
806 let backend = MockBackend::with_labels(vec!["status:new"]);
807 *backend.set_labels_fail_count.lock().unwrap() = 10;
809 let id = ExternalId("1".into());
810 let result = backend.update_status(&id, Status::Done).await;
811 assert!(result.is_err(), "should fail after max retries");
812 assert!(
813 result
814 .unwrap_err()
815 .to_string()
816 .contains("failed after 3 attempts"),
817 "error message mentions retry exhaustion"
818 );
819 }
820
821 #[test]
822 fn status_as_label() {
823 assert_eq!(Status::New.as_label(), "status:new");
824 assert_eq!(Status::Routed.as_label(), "status:routed");
825 assert_eq!(Status::InProgress.as_label(), "status:in_progress");
826 assert_eq!(Status::Done.as_label(), "status:done");
827 assert_eq!(Status::Blocked.as_label(), "status:blocked");
828 assert_eq!(Status::InReview.as_label(), "status:in_review");
829 assert_eq!(Status::Approved.as_label(), "status:approved");
830 assert_eq!(Status::Approved.as_str(), "approved");
831 assert_eq!(TaskStatus::from_str("approved"), Some(TaskStatus::Approved));
832 assert_eq!(TaskStatus::Approved.as_str(), "approved");
833 assert_eq!(Status::NeedsReview.as_label(), "status:needs_review");
834 assert_eq!(Status::Waiting.as_label(), "status:waiting");
835 assert_eq!(Status::Waiting.as_str(), "waiting");
836 }
837
838 #[test]
839 fn as_str_is_as_label_without_status_prefix() {
840 for status in [
841 Status::New,
842 Status::Routed,
843 Status::InProgress,
844 Status::Done,
845 Status::Blocked,
846 Status::InReview,
847 Status::Approved,
848 Status::NeedsReview,
849 Status::Waiting,
850 ] {
851 let label = status.as_label();
852 assert_eq!(
853 status.as_str(),
854 label.strip_prefix("status:").unwrap(),
855 "{status:?}"
856 );
857 assert_eq!(status.as_str(), label.replace("status:", ""), "{status:?}");
858 assert_eq!(
859 status.as_str(),
860 label.trim_start_matches("status:"),
861 "{status:?}"
862 );
863 }
864 }
865
866 #[test]
867 fn status_serializes_snake_case() {
868 let json = serde_json::to_string(&Status::InProgress).unwrap();
869 assert_eq!(json, "\"in_progress\"");
870 }
871
872 #[test]
873 fn status_deserializes_snake_case() {
874 let status: Status = serde_json::from_str("\"needs_review\"").unwrap();
875 assert_eq!(status, Status::NeedsReview);
876 }
877
878 #[test]
879 fn external_id_clone() {
880 let id = ExternalId("42".to_string());
881 let cloned = id.clone();
882 assert_eq!(id.0, cloned.0);
883 }
884
885 #[test]
886 fn external_task_serializes() {
887 let task = ExternalTask {
888 id: ExternalId("1".to_string()),
889 title: "Test".to_string(),
890 body: "Body".to_string(),
891 state: "open".to_string(),
892 labels: vec!["status:new".to_string()],
893 author: "user".to_string(),
894 created_at: "2026-01-01T00:00:00Z".to_string(),
895 updated_at: "2026-01-01T00:00:00Z".to_string(),
896 url: "https://github.com/test/test/issues/1".to_string(),
897 };
898 let json = serde_json::to_string(&task).unwrap();
899 assert!(json.contains("\"title\":\"Test\""));
900 assert!(json.contains("status:new"));
901 }
902}
903
904#[cfg(test)]
905pub(crate) mod test_helpers;