orch-cli 0.118.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
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";

/// GitHub as the event path sees it: a single-issue read and a list that may lag behind it
#[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(())
    }
}

/// The PR reads of the review step, counted
#[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() {
    // The backend leaves out an untrusted author's issue, the same filter the list uses
    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;

    // Back to its author, `new` here because the test config has no model to keep it routed
    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);
}