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 get_active_open_issue(
243 &self,
244 id: &ExternalId,
245 ) -> anyhow::Result<Option<(ExternalTask, Option<Status>)>> {
246 Ok(self
247 .list_active_open_issues()
248 .await?
249 .into_iter()
250 .find(|(task, _)| task.id.0 == id.0))
251 }
252
253 async fn has_open_issue_with_title(&self, _title: &str, _label: &str) -> anyhow::Result<bool> {
259 Ok(false)
260 }
261}
262
263#[async_trait]
265pub trait TaskWriter: TaskReader + Send + Sync {
266 async fn create_task(
268 &self,
269 title: &str,
270 body: &str,
271 labels: &[String],
272 ) -> anyhow::Result<ExternalId>;
273
274 async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
288 const MAX_RETRIES: u32 = 3;
289 let label = status.as_label();
290
291 if let Err(e) = self.ensure_status_label(label).await {
293 tracing::warn!(label, err = %e, "ensure_status_label failed, continuing");
294 }
295
296 let mut last_err =
297 anyhow::anyhow!("update_status({label}) failed: all {MAX_RETRIES} attempts exhausted");
298
299 for attempt in 0..MAX_RETRIES {
300 if attempt > 0 {
301 time::sleep(Duration::from_millis(500 * u64::from(attempt))).await;
302 tracing::debug!(attempt, label, "retrying update_status");
303 }
304
305 let task = match self.get_task(id).await {
307 Ok(t) => t,
308 Err(e) => {
309 last_err = e;
310 continue;
311 }
312 };
313
314 let mut remove_failed = false;
316 for old in task
317 .labels
318 .iter()
319 .filter(|l| l.starts_with("status:") && l.as_str() != label)
320 {
321 if let Err(e) = self.remove_label(id, old).await {
322 tracing::warn!(old_label = %old, err = %e, attempt, "remove_label failed");
323 last_err = e;
324 remove_failed = true;
325 break;
326 }
327 }
328 if remove_failed {
329 continue;
330 }
331
332 match self.set_labels(id, &[label.to_string()]).await {
334 Ok(()) => return Ok(()),
335 Err(e) => {
336 tracing::warn!(label, err = %e, attempt, "set_labels failed");
337 last_err = e;
338 }
339 }
340 }
341
342 Err(last_err.context(format!(
343 "update_status({label}) failed after {MAX_RETRIES} attempts"
344 )))
345 }
346
347 async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()>;
351
352 async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()>;
354
355 async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>>;
360
361 async fn create_sub_task(
367 &self,
368 parent_id: &ExternalId,
369 title: &str,
370 body: &str,
371 labels: &[String],
372 ) -> anyhow::Result<ExternalId> {
373 let mut all_labels = labels.to_vec();
375 all_labels.push(format!("parent:{}", parent_id.0));
376 self.create_task(title, body, &all_labels).await
377 }
378
379 async fn ensure_status_label(&self, _label: &str) -> anyhow::Result<()> {
385 Ok(())
386 }
387}
388
389#[async_trait]
391pub trait Conversation: Send + Sync {
392 async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()>;
394
395 async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
399 Ok(None)
400 }
401
402 async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
406 Ok(vec![])
407 }
408
409 async fn list_issue_comments(&self, _id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
413 Ok(vec![])
414 }
415
416 async fn acknowledge_issue(&self, _id: &ExternalId) -> anyhow::Result<()> {
421 Ok(())
422 }
423
424 async fn acknowledge_mention(&self, _comment_id: &str) -> anyhow::Result<()> {
429 Ok(())
430 }
431
432 async fn post_comment_in_repo(
436 &self,
437 _repo: &str,
438 id: &ExternalId,
439 body: &str,
440 ) -> anyhow::Result<()> {
441 self.post_comment(id, body).await
442 }
443}
444
445#[async_trait]
447pub trait MergeState: Send + Sync {
448 async fn is_pr_merged(&self, _branch: &str) -> anyhow::Result<bool> {
452 Ok(false)
453 }
454
455 async fn batch_is_pr_merged(
461 &self,
462 branches: &[String],
463 ) -> anyhow::Result<HashMap<String, bool>> {
464 let mut result = HashMap::new();
465 for branch in branches {
466 match self.is_pr_merged(branch).await {
467 Ok(merged) => {
468 result.insert(branch.clone(), merged);
469 }
470 Err(e) => {
471 tracing::warn!(branch, err = %e, "failed to check PR merge status");
472 }
473 }
474 }
475 Ok(result)
476 }
477
478 async fn blocked_by(&self, _repo: &str, _issue_number: i64) -> anyhow::Result<BlockedByFetch> {
483 Ok(BlockedByFetch::Unavailable)
484 }
485
486 async fn issue_close_state(
490 &self,
491 _repo: &str,
492 _issue_number: i64,
493 ) -> anyhow::Result<Option<(String, Option<String>)>> {
494 Ok(None)
495 }
496
497 async fn pull_request_completion(
502 &self,
503 _repo: &str,
504 _pr_number: i64,
505 ) -> anyhow::Result<Option<PullRequestCompletion>> {
506 Ok(None)
507 }
508
509 async fn add_dependency(
514 &self,
515 _issue_number: i64,
516 _blocking_repo: &str,
517 _blocking_number: i64,
518 ) -> anyhow::Result<()> {
519 anyhow::bail!("this backend cannot write issue dependencies")
520 }
521}
522
523#[async_trait]
525pub trait Tracker: Send + Sync {
526 fn name(&self) -> &str;
528
529 async fn sync_to_project(
537 &self,
538 _id: &ExternalId,
539 _status: Status,
540 ) -> anyhow::Result<Option<String>> {
541 Ok(None)
542 }
543
544 async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
548 Ok(())
549 }
550
551 async fn sync_estimate_to_project(
557 &self,
558 _id: &ExternalId,
559 _estimate: u8,
560 ) -> anyhow::Result<()> {
561 Ok(())
562 }
563
564 async fn get_project_item_estimates(
571 &self,
572 _issue_node_ids: &[String],
573 ) -> anyhow::Result<HashMap<String, u8>> {
574 Ok(HashMap::new())
575 }
576
577 async fn health_check(&self) -> anyhow::Result<()>;
579}
580
581#[cfg(test)]
582mod tests {
583 use super::*;
584
585 use crate::store::TaskStatus;
586 use async_trait::async_trait;
587 use std::sync::{Arc, Mutex};
588
589 #[test]
590 fn status_maps_to_board_columns() {
591 assert_eq!(Status::New.board_column(), "backlog");
592 assert_eq!(Status::Routed.board_column(), "backlog");
593 assert_eq!(Status::InProgress.board_column(), "in_progress");
594 assert_eq!(Status::Blocked.board_column(), "in_progress");
595 assert_eq!(Status::InReview.board_column(), "review");
596 assert_eq!(Status::Approved.board_column(), "review");
597 assert_eq!(Status::NeedsReview.board_column(), "review");
598 assert_eq!(Status::Done.board_column(), "done");
599 }
600
601 struct MockBackend {
607 labels: Arc<Mutex<Vec<String>>>,
609 remove_err: Option<String>,
611 set_labels_fail_count: Arc<Mutex<u32>>,
613 }
614
615 impl MockBackend {
616 fn with_labels(labels: Vec<&str>) -> Self {
617 Self {
618 labels: Arc::new(Mutex::new(labels.into_iter().map(String::from).collect())),
619 remove_err: None,
620 set_labels_fail_count: Arc::new(Mutex::new(0)),
621 }
622 }
623
624 fn current_labels(&self) -> Vec<String> {
625 self.labels.lock().unwrap().clone()
626 }
627 }
628
629 #[async_trait]
630 impl TaskReader for MockBackend {
631 async fn get_task(&self, _id: &ExternalId) -> anyhow::Result<ExternalTask> {
632 Ok(ExternalTask {
633 id: ExternalId("1".into()),
634 title: "mock".into(),
635 body: String::new(),
636 state: "open".into(),
637 labels: self.current_labels(),
638 author: "user".into(),
639 created_at: "2026-01-01T00:00:00Z".into(),
640 updated_at: "2026-01-01T00:00:00Z".into(),
641 url: "https://example.com".into(),
642 })
643 }
644
645 async fn list_by_status(&self, _status: Status) -> anyhow::Result<Vec<ExternalTask>> {
646 Ok(vec![])
647 }
648 }
649
650 #[async_trait]
651 impl TaskWriter for MockBackend {
652 async fn create_task(
653 &self,
654 _title: &str,
655 _body: &str,
656 _labels: &[String],
657 ) -> anyhow::Result<ExternalId> {
658 Ok(ExternalId("1".into()))
659 }
660
661 async fn set_labels(&self, _id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
662 let mut fail_count = self.set_labels_fail_count.lock().unwrap();
663 if *fail_count > 0 {
664 *fail_count -= 1;
665 return Err(anyhow::anyhow!("transient network error"));
666 }
667 drop(fail_count);
668 let mut current = self.labels.lock().unwrap();
669 for l in labels {
670 if !current.contains(l) {
671 current.push(l.clone());
672 }
673 }
674 Ok(())
675 }
676
677 async fn remove_label(&self, _id: &ExternalId, label: &str) -> anyhow::Result<()> {
678 if let Some(ref err_label) = self.remove_err
679 && label == err_label
680 {
681 return Err(anyhow::anyhow!("rate limit (429)"));
682 }
683 self.labels.lock().unwrap().retain(|l| l != label);
684 Ok(())
685 }
686
687 async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
688 Ok(vec![])
689 }
690 }
691
692 #[async_trait]
693 impl Conversation for MockBackend {
694 async fn post_comment(&self, _id: &ExternalId, _body: &str) -> anyhow::Result<()> {
695 Ok(())
696 }
697 }
698
699 impl MergeState for MockBackend {}
700
701 #[async_trait]
702 impl Tracker for MockBackend {
703 fn name(&self) -> &'static str {
704 "mock"
705 }
706
707 async fn health_check(&self) -> anyhow::Result<()> {
708 Ok(())
709 }
710 }
711
712 #[tokio::test]
715 async fn update_status_replaces_single_old_label() {
716 let backend = MockBackend::with_labels(vec!["status:new", "priority:high"]);
717 let id = ExternalId("1".into());
718 backend
719 .update_status(&id, Status::InProgress)
720 .await
721 .unwrap();
722 let labels = backend.current_labels();
723 assert!(
724 labels.contains(&"status:in_progress".to_string()),
725 "new label added: {labels:?}"
726 );
727 assert!(
728 !labels.contains(&"status:new".to_string()),
729 "old label removed: {labels:?}"
730 );
731 assert!(
732 labels.contains(&"priority:high".to_string()),
733 "non-status label preserved: {labels:?}"
734 );
735 }
736
737 #[tokio::test]
738 async fn update_status_removes_multiple_old_status_labels() {
739 let backend = MockBackend::with_labels(vec!["status:in_progress", "status:blocked", "bug"]);
741 let id = ExternalId("1".into());
742 backend.update_status(&id, Status::Done).await.unwrap();
743 let labels = backend.current_labels();
744 let status_labels: Vec<_> = labels.iter().filter(|l| l.starts_with("status:")).collect();
745 assert_eq!(
746 status_labels,
747 vec!["status:done"],
748 "exactly one status label: {labels:?}"
749 );
750 }
751
752 #[tokio::test]
753 async fn update_status_is_idempotent() {
754 let backend = MockBackend::with_labels(vec!["status:done"]);
755 let id = ExternalId("1".into());
756 backend.update_status(&id, Status::Done).await.unwrap();
757 let labels = backend.current_labels();
758 let status_count = labels.iter().filter(|l| l.starts_with("status:")).count();
759 assert_eq!(
760 status_count, 1,
761 "idempotent: still exactly one status label: {labels:?}"
762 );
763 }
764
765 #[tokio::test]
766 async fn update_status_non_status_labels_are_preserved() {
767 let backend =
768 MockBackend::with_labels(vec!["status:routed", "agent:claude", "maintenance"]);
769 let id = ExternalId("1".into());
770 backend
771 .update_status(&id, Status::InProgress)
772 .await
773 .unwrap();
774 let labels = backend.current_labels();
775 assert!(
776 labels.contains(&"agent:claude".to_string()),
777 "agent label preserved: {labels:?}"
778 );
779 assert!(
780 labels.contains(&"maintenance".to_string()),
781 "other label preserved: {labels:?}"
782 );
783 }
784
785 #[tokio::test]
786 async fn lifecycle_transition_preserves_board_label_and_no_agent_hold() {
787 let backend = MockBackend::with_labels(vec!["status:new", "board:held", "no-agent"]);
788 backend
789 .update_status(&ExternalId("1".into()), Status::Routed)
790 .await
791 .unwrap();
792 let mut labels = backend.current_labels();
793 labels.sort();
794 assert_eq!(labels, vec!["board:held", "no-agent", "status:routed"]);
795 }
796
797 #[tokio::test]
798 async fn update_status_retries_on_transient_set_labels_failure() {
799 let backend = MockBackend::with_labels(vec!["status:new"]);
800 *backend.set_labels_fail_count.lock().unwrap() = 1;
802 let id = ExternalId("1".into());
803 backend
804 .update_status(&id, Status::InProgress)
805 .await
806 .unwrap();
807 let labels = backend.current_labels();
808 assert!(
809 labels.contains(&"status:in_progress".to_string()),
810 "label added after retry: {labels:?}"
811 );
812 assert!(
813 !labels.contains(&"status:new".to_string()),
814 "old label removed: {labels:?}"
815 );
816 }
817
818 #[tokio::test]
819 async fn update_status_fails_after_max_retries() {
820 let backend = MockBackend::with_labels(vec!["status:new"]);
821 *backend.set_labels_fail_count.lock().unwrap() = 10;
823 let id = ExternalId("1".into());
824 let result = backend.update_status(&id, Status::Done).await;
825 assert!(result.is_err(), "should fail after max retries");
826 assert!(
827 result
828 .unwrap_err()
829 .to_string()
830 .contains("failed after 3 attempts"),
831 "error message mentions retry exhaustion"
832 );
833 }
834
835 #[test]
836 fn status_as_label() {
837 assert_eq!(Status::New.as_label(), "status:new");
838 assert_eq!(Status::Routed.as_label(), "status:routed");
839 assert_eq!(Status::InProgress.as_label(), "status:in_progress");
840 assert_eq!(Status::Done.as_label(), "status:done");
841 assert_eq!(Status::Blocked.as_label(), "status:blocked");
842 assert_eq!(Status::InReview.as_label(), "status:in_review");
843 assert_eq!(Status::Approved.as_label(), "status:approved");
844 assert_eq!(Status::Approved.as_str(), "approved");
845 assert_eq!(TaskStatus::from_str("approved"), Some(TaskStatus::Approved));
846 assert_eq!(TaskStatus::Approved.as_str(), "approved");
847 assert_eq!(Status::NeedsReview.as_label(), "status:needs_review");
848 assert_eq!(Status::Waiting.as_label(), "status:waiting");
849 assert_eq!(Status::Waiting.as_str(), "waiting");
850 }
851
852 #[test]
853 fn as_str_is_as_label_without_status_prefix() {
854 for status in [
855 Status::New,
856 Status::Routed,
857 Status::InProgress,
858 Status::Done,
859 Status::Blocked,
860 Status::InReview,
861 Status::Approved,
862 Status::NeedsReview,
863 Status::Waiting,
864 ] {
865 let label = status.as_label();
866 assert_eq!(
867 status.as_str(),
868 label.strip_prefix("status:").unwrap(),
869 "{status:?}"
870 );
871 assert_eq!(status.as_str(), label.replace("status:", ""), "{status:?}");
872 assert_eq!(
873 status.as_str(),
874 label.trim_start_matches("status:"),
875 "{status:?}"
876 );
877 }
878 }
879
880 #[test]
881 fn status_serializes_snake_case() {
882 let json = serde_json::to_string(&Status::InProgress).unwrap();
883 assert_eq!(json, "\"in_progress\"");
884 }
885
886 #[test]
887 fn status_deserializes_snake_case() {
888 let status: Status = serde_json::from_str("\"needs_review\"").unwrap();
889 assert_eq!(status, Status::NeedsReview);
890 }
891
892 #[test]
893 fn external_id_clone() {
894 let id = ExternalId("42".to_string());
895 let cloned = id.clone();
896 assert_eq!(id.0, cloned.0);
897 }
898
899 #[test]
900 fn external_task_serializes() {
901 let task = ExternalTask {
902 id: ExternalId("1".to_string()),
903 title: "Test".to_string(),
904 body: "Body".to_string(),
905 state: "open".to_string(),
906 labels: vec!["status:new".to_string()],
907 author: "user".to_string(),
908 created_at: "2026-01-01T00:00:00Z".to_string(),
909 updated_at: "2026-01-01T00:00:00Z".to_string(),
910 url: "https://github.com/test/test/issues/1".to_string(),
911 };
912 let json = serde_json::to_string(&task).unwrap();
913 assert!(json.contains("\"title\":\"Test\""));
914 assert!(json.contains("status:new"));
915 }
916}
917
918#[cfg(test)]
919pub(crate) mod test_helpers;