use super::events::{Followup, ItemContext, Target, apply, target};
use crate::backends::{
Conversation, ExternalBackend, ExternalId, ExternalTask, Mention, MergeState, Status,
TaskReader, TaskWriter, Tracker,
};
use crate::engine::EngineConfig;
use crate::engine::review::poll::GhReviewClient;
use crate::engine::router::RouterConfig;
use crate::engine::service::relay::Event;
use crate::engine::tasks::TaskManager;
use crate::github::http::PrReviewBatchData;
use crate::github::types::{GitHubReview, GitHubUser};
use crate::store::{NewTask, Task, TaskStatus, TaskStore};
use async_trait::async_trait;
use dashmap::{DashMap, DashSet};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
const REPO: &str = "o/r";
#[derive(Default)]
struct Issues {
single: Mutex<HashMap<String, (ExternalTask, Option<Status>)>>,
list: Mutex<Vec<(ExternalTask, Option<Status>)>>,
single_reads: AtomicUsize,
list_reads: AtomicUsize,
acks: AtomicUsize,
}
impl Issues {
fn put(&self, task: ExternalTask) {
self.single
.lock()
.unwrap()
.insert(task.id.0.clone(), (task, None));
}
}
#[async_trait]
impl TaskReader for Issues {
async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
anyhow::bail!("unexpected get_task {}", id.0)
}
async fn list_by_status(&self, _s: Status) -> anyhow::Result<Vec<ExternalTask>> {
Ok(vec![])
}
async fn list_active_open_issues(&self) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
self.list_reads.fetch_add(1, Ordering::SeqCst);
Ok(self.list.lock().unwrap().clone())
}
async fn get_active_open_issue(
&self,
id: &ExternalId,
) -> anyhow::Result<Option<(ExternalTask, Option<Status>)>> {
self.single_reads.fetch_add(1, Ordering::SeqCst);
Ok(self.single.lock().unwrap().get(&id.0).cloned())
}
}
#[async_trait]
impl TaskWriter for Issues {
async fn create_task(&self, _t: &str, _b: &str, _l: &[String]) -> anyhow::Result<ExternalId> {
Ok(ExternalId("new".into()))
}
async fn set_labels(&self, _id: &ExternalId, _l: &[String]) -> anyhow::Result<()> {
Ok(())
}
async fn remove_label(&self, _id: &ExternalId, _l: &str) -> anyhow::Result<()> {
Ok(())
}
async fn get_sub_issues(&self, _id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
Ok(vec![])
}
async fn create_sub_task(
&self,
_p: &ExternalId,
_t: &str,
_b: &str,
_l: &[String],
) -> anyhow::Result<ExternalId> {
Ok(ExternalId("child".into()))
}
async fn update_status(&self, _id: &ExternalId, _s: Status) -> anyhow::Result<()> {
Ok(())
}
}
#[async_trait]
impl Conversation for Issues {
async fn post_comment(&self, _id: &ExternalId, _b: &str) -> anyhow::Result<()> {
Ok(())
}
async fn get_mentions(&self, _s: &str) -> anyhow::Result<Vec<Mention>> {
Ok(vec![])
}
async fn acknowledge_issue(&self, _id: &ExternalId) -> anyhow::Result<()> {
self.acks.fetch_add(1, Ordering::SeqCst);
Ok(())
}
}
#[async_trait]
impl MergeState for Issues {
async fn is_pr_merged(&self, _b: &str) -> anyhow::Result<bool> {
Ok(false)
}
}
#[async_trait]
impl Tracker for Issues {
fn name(&self) -> &'static str {
"events-test"
}
async fn health_check(&self) -> anyhow::Result<()> {
Ok(())
}
}
#[derive(Default)]
struct Prs {
data: HashMap<u64, PrReviewBatchData>,
reads: AtomicUsize,
}
#[async_trait]
impl GhReviewClient for Prs {
async fn get_pr_number(&self, _repo: &str, _branch: &str) -> anyhow::Result<Option<u64>> {
anyhow::bail!("unexpected PR lookup by branch")
}
async fn is_pr_merged(&self, _repo: &str, _branch: &str) -> anyhow::Result<bool> {
Ok(false)
}
async fn batch_fetch_pr_review_data(
&self,
_repo: &str,
pr_numbers: &[u64],
) -> anyhow::Result<HashMap<u64, PrReviewBatchData>> {
self.reads.fetch_add(pr_numbers.len(), Ordering::SeqCst);
Ok(self.data.clone())
}
async fn is_collaborator(&self, _repo: &str, _username: &str) -> anyhow::Result<bool> {
Ok(true)
}
}
struct Harness {
issues: Arc<Issues>,
backend: Arc<dyn ExternalBackend>,
store: Arc<TaskStore>,
task_manager: Arc<TaskManager>,
config: EngineConfig,
dispatching: Arc<DashMap<String, String>>,
in_flight: Arc<DashSet<String>>,
router_config: RouterConfig,
}
impl Harness {
async fn new() -> Self {
let issues = Arc::new(Issues::default());
let backend: Arc<dyn ExternalBackend> = Arc::<Issues>::clone(&issues);
let store = Arc::new(TaskStore::open_memory().await.unwrap());
let task_manager = Arc::new(TaskManager::with_store(
Arc::clone(&backend),
Arc::clone(&store),
REPO.to_string(),
));
Self {
issues,
backend,
store,
task_manager,
config: EngineConfig::default(),
dispatching: Arc::new(DashMap::new()),
in_flight: Arc::new(DashSet::new()),
router_config: RouterConfig::default(),
}
}
async fn deliver(&self, event: &Event, gh: &Prs) -> Followup {
let ctx = ItemContext {
backend: &self.backend,
repo: REPO,
config: &self.config,
task_manager: &self.task_manager,
store: &self.store,
dispatching: &self.dispatching,
auto_merge_in_flight: &self.in_flight,
router_config: &self.router_config,
gh,
};
Box::pin(apply(&ctx, target(event))).await.unwrap()
}
async fn task(&self, number: &str) -> Option<Task> {
let id = self.store.resolve_task_id(REPO, number).await.unwrap()?;
Some(self.store.get(id).await.unwrap())
}
}
fn issue(number: &str, title: &str, body: &str) -> ExternalTask {
ExternalTask {
id: ExternalId(number.to_string()),
title: title.to_string(),
body: body.to_string(),
state: "open".to_string(),
labels: vec![],
author: "owner".to_string(),
created_at: "2026-12-01T00:00:00Z".to_string(),
updated_at: "2026-12-01T00:00:00Z".to_string(),
url: String::new(),
}
}
fn issues_event(action: &str, number: i64) -> Event {
Event {
name: "issues".to_string(),
action: action.to_string(),
repo: REPO.to_string(),
payload: Some(serde_json::json!({ "action": action, "issue": { "number": number } })),
}
}
#[tokio::test]
async fn an_opened_issue_becomes_a_task_from_the_single_issue_read() {
let h = Harness::new().await;
h.issues.put(issue("12", "Add a flag", "body"));
let followup = h
.deliver(&issues_event("opened", 12), &Prs::default())
.await;
assert_eq!(followup, Followup::None);
let task = h.task("12").await.expect("the event created the task");
assert_eq!(task.title, "Add a flag");
assert_eq!(task.status, TaskStatus::New);
assert_eq!(h.issues.single_reads.load(Ordering::SeqCst), 1);
assert_eq!(h.issues.list_reads.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn an_edited_issue_updates_the_title_and_body() {
let h = Harness::new().await;
h.issues.put(issue("12", "Old title", "old body"));
h.deliver(&issues_event("opened", 12), &Prs::default())
.await;
h.issues.put(issue("12", "New title", "new body"));
h.deliver(&issues_event("edited", 12), &Prs::default())
.await;
let task = h.task("12").await.unwrap();
assert_eq!(task.title, "New title");
assert_eq!(task.body, "new body");
}
#[tokio::test]
async fn an_issue_the_read_skips_creates_no_task() {
let h = Harness::new().await;
h.deliver(&issues_event("opened", 13), &Prs::default())
.await;
assert!(h.task("13").await.is_none());
assert_eq!(h.issues.acks.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn the_same_event_twice_changes_nothing_the_second_time() {
let h = Harness::new().await;
h.issues.put(issue("12", "Add a flag", "body"));
let event = issues_event("opened", 12);
h.deliver(&event, &Prs::default()).await;
let first = h.task("12").await.unwrap();
h.deliver(&event, &Prs::default()).await;
let second = h.task("12").await.unwrap();
assert_eq!(first.id, second.id);
assert_eq!(first.title, second.title);
assert_eq!(first.body, second.body);
assert_eq!(first.status, second.status);
assert_eq!(first.labels, second.labels);
assert_eq!(h.issues.acks.load(Ordering::SeqCst), 1);
assert_eq!(h.store.existing_external_ids(REPO).await.unwrap().len(), 1);
}
#[tokio::test]
async fn a_truncated_issue_event_ingests_the_issue_from_its_repository() {
let h = Harness::new().await;
h.issues
.list
.lock()
.unwrap()
.push((issue("14", "Big body", "x"), None));
let event = Event {
name: "issues".to_string(),
action: "opened".to_string(),
repo: REPO.to_string(),
payload: None,
};
assert_eq!(target(&event), Target::Issues);
h.deliver(&event, &Prs::default()).await;
assert_eq!(h.task("14").await.unwrap().title, "Big body");
}
#[tokio::test]
async fn a_review_that_requests_changes_reroutes_the_task_with_one_pr_read() {
let h = Harness::new().await;
let id = h
.store
.create(&NewTask {
repo: REPO.to_string(),
origin: "github".to_string(),
external_id: Some("20".to_string()),
title: "Fix the parser".to_string(),
..Default::default()
})
.await
.unwrap();
h.store
.set_fields(
id,
&[
("branch", serde_json::json!("fix-parser")),
("pr_number", serde_json::json!(31)),
],
)
.await
.unwrap();
h.store
.update_status(id, TaskStatus::InReview)
.await
.unwrap();
let review = GitHubReview {
id: 1,
user: GitHubUser {
login: "owner".to_string(),
},
body: Some("Handle the empty input".to_string()),
state: "CHANGES_REQUESTED".to_string(),
html_url: None,
submitted_at: "2026-12-01T10:00:00Z".to_string(),
commit_id: None,
};
let gh = Prs {
data: HashMap::from([(
31,
PrReviewBatchData {
merged: false,
head_sha: String::new(),
mergeable: Some(true),
reviews: vec![review],
review_comments: vec![],
issue_comments: vec![],
},
)]),
reads: AtomicUsize::new(0),
};
let event = Event {
name: "pull_request_review".to_string(),
action: "submitted".to_string(),
repo: REPO.to_string(),
payload: Some(serde_json::json!({ "pull_request": { "number": 31 } })),
};
h.deliver(&event, &gh).await;
let task = h.store.get(id).await.unwrap();
assert!(matches!(task.status, TaskStatus::Routed | TaskStatus::New));
assert_eq!(task.review_cycles, 1);
assert!(task.pr_review_context.contains("Handle the empty input"));
assert_eq!(gh.reads.load(Ordering::SeqCst), 1);
assert_eq!(h.issues.list_reads.load(Ordering::SeqCst), 0);
assert_eq!(h.issues.single_reads.load(Ordering::SeqCst), 0);
}
#[test]
fn events_name_their_items() {
let event = |name: &str, action: &str, payload: serde_json::Value| Event {
name: name.to_string(),
action: action.to_string(),
repo: REPO.to_string(),
payload: Some(payload),
};
assert_eq!(
target(&issues_event("labeled", 5)),
Target::Issue("5".to_string())
);
assert_eq!(target(&issues_event("closed", 5)), Target::Repo);
assert_eq!(
target(&event("issue_comment", "created", serde_json::json!({}))),
Target::Comments
);
assert_eq!(
target(&event(
"pull_request",
"synchronize",
serde_json::json!({ "number": 7, "pull_request": { "number": 7 } })
)),
Target::Prs(vec![7])
);
assert_eq!(
target(&event(
"check_suite",
"completed",
serde_json::json!({ "check_suite": { "pull_requests": [{ "number": 8 }] } })
)),
Target::Prs(vec![8])
);
assert_eq!(
target(&event(
"workflow_run",
"completed",
serde_json::json!({ "workflow_run": { "pull_requests": [] } })
)),
Target::Tick
);
for action in ["created", "requested", "in_progress", "rerequested"] {
assert_eq!(
target(&event(
"check_run",
action,
serde_json::json!({ "check_run": { "pull_requests": [{ "number": 8 }] } })
)),
Target::Ignore
);
}
assert_eq!(
target(&Event {
name: "check_suite".to_string(),
action: "requested".to_string(),
repo: REPO.to_string(),
payload: None,
}),
Target::Ignore
);
assert_eq!(
target(&event(
"push",
"",
serde_json::json!({ "ref": "refs/heads/main", "repository": { "default_branch": "main" } })
)),
Target::DefaultBranch
);
assert_eq!(
target(&event(
"push",
"",
serde_json::json!({ "ref": "refs/heads/feat", "repository": { "default_branch": "main" } })
)),
Target::Tick
);
assert_eq!(
target(&event("pull_request", "opened", serde_json::json!({}))),
Target::Repo
);
assert_eq!(
target(&event("milestone", "created", serde_json::json!({}))),
Target::Repo
);
}
#[tokio::test]
async fn a_check_that_has_not_completed_reads_no_pr() {
let h = Harness::new().await;
let gh = Prs {
data: HashMap::new(),
reads: AtomicUsize::new(0),
};
let event = Event {
name: "check_run".to_string(),
action: "created".to_string(),
repo: REPO.to_string(),
payload: Some(serde_json::json!({ "check_run": { "pull_requests": [{ "number": 31 }] } })),
};
assert_eq!(h.deliver(&event, &gh).await, Followup::None);
assert_eq!(gh.reads.load(Ordering::SeqCst), 0);
assert_eq!(h.issues.list_reads.load(Ordering::SeqCst), 0);
}