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