orch-cli 0.117.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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! GitHub writes of a cluster node go through a pending kv row in the Raft state, so the next
//! leader sends again what a stopped leader left. The design is in the cluster spec, "Leader and workers"

use std::collections::HashMap;
use std::collections::HashSet;
use std::error;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use std::future::Future;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::sync::PoisonError;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::time;

use super::github::GitHubBackend;
use super::{
    BlockedByFetch, Conversation, ExternalBackend, ExternalId, ExternalTask, Mention, MergeState,
    PullRequestCompletion, Status, TaskReader, TaskWriter, Tracker,
};
use crate::github::http::GhHttp;
use crate::security;
use crate::store::TaskStore;
use crate::store::cluster::MAJORITY_TIMEOUT;

/// Every pending write is one kv row under this prefix
pub const PREFIX: &str = "outbox:";

/// Keys of the rows this process is sending now, so a retry never runs one twice at once
static IN_FLIGHT: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Mutex::default);

/// One pending GitHub write. `repo` is the repository the write goes to
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Entry {
    pub repo: String,
    #[serde(flatten)]
    pub op: Op,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Op {
    Status {
        issue: String,
        status: Status,
    },
    AddLabels {
        issue: String,
        labels: Vec<String>,
    },
    RemoveLabel {
        issue: String,
        label: String,
    },
    /// `body` ends with `marker`, so a retry finds a comment that was already posted
    Comment {
        issue: String,
        body: String,
        marker: String,
    },
    /// GitHub refuses the merge when the head is no longer `head_sha`
    Merge {
        pr: u64,
        head_sha: String,
        delete_branch: bool,
    },
}

/// The write was not sent: this node is not the leader or lost the majority. A recorded row stays
/// for the next leader
#[derive(Debug)]
pub struct Fenced(pub String);

impl Display for Fenced {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "not sent to GitHub: {}", self.0)
    }
}

impl error::Error for Fenced {}

/// Where a retried write goes. `GitHub` outside tests
#[async_trait]
pub trait Targets: Send + Sync {
    fn backend(&self, repo: &str) -> anyhow::Result<Arc<dyn ExternalBackend>>;

    async fn merge(
        &self,
        repo: &str,
        pr: u64,
        delete_branch: bool,
        head_sha: &str,
    ) -> anyhow::Result<()>;

    /// Bodies of every comment on the issue, from any author
    async fn comment_bodies(&self, repo: &str, issue: u64) -> anyhow::Result<Vec<String>>;
}

#[derive(Debug)]
pub struct GitHub;

#[async_trait]
impl Targets for GitHub {
    fn backend(&self, repo: &str) -> anyhow::Result<Arc<dyn ExternalBackend>> {
        Ok(Arc::new(GitHubBackend::new(repo.to_string())?))
    }

    async fn merge(
        &self,
        repo: &str,
        pr: u64,
        delete_branch: bool,
        head_sha: &str,
    ) -> anyhow::Result<()> {
        GhHttp::new()?
            .merge_pr(repo, pr, delete_branch, head_sha)
            .await
    }

    async fn comment_bodies(&self, repo: &str, issue: u64) -> anyhow::Result<Vec<String>> {
        let comments = GhHttp::new()?.get_issue_comments(repo, issue).await?;
        Ok(comments.into_iter().map(|c| c.body).collect())
    }
}

/// Releases a claimed key when dropped
struct Claim(String);

impl Claim {
    fn take(key: &str) -> Option<Self> {
        let mut keys = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
        keys.insert(key.to_string()).then(|| Claim(key.to_string()))
    }
}

impl Drop for Claim {
    fn drop(&mut self) {
        IN_FLIGHT
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&self.0);
    }
}

/// Keys sort in the order the proposers made them, the suffix keeps two at one instant apart
fn new_key() -> String {
    let nanos = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default();
    let id = uuid::Uuid::new_v4().simple().to_string();
    format!("{PREFIX}{nanos:020}-{}", &id[..8])
}

fn marker(key: &str) -> String {
    format!("<!-- orch-outbox:{} -->", key.trim_start_matches(PREFIX))
}

async fn record(store: &TaskStore, key: &str, entry: &Entry) -> anyhow::Result<()> {
    let value = serde_json::to_string(entry)?;
    // A leader without a majority never commits, so the write would wait forever
    time::timeout(MAJORITY_TIMEOUT, store.kv_set(key, &value))
        .await
        .map_err(|_| anyhow::anyhow!("no majority committed the outbox row"))?
}

/// A new status makes the pending older ones for the same issue stale, so a retry never sends them
/// after the new one
async fn supersede(store: &TaskStore, key: &str, entry: &Entry) {
    let Op::Status { issue, .. } = &entry.op else {
        return;
    };
    let rows = match store.kv_list_prefix(PREFIX).await {
        Ok(rows) => rows,
        Err(e) => {
            tracing::warn!(key, err = %e, "outbox: failed to list older status rows");
            return;
        }
    };
    for (older, value) in rows {
        if older.as_str() >= key {
            continue;
        }

        let Ok(row) = serde_json::from_str::<Entry>(&value) else {
            continue;
        };
        if row.repo == entry.repo && matches!(&row.op, Op::Status { issue: i, .. } if i == issue) {
            remove(store, &older).await;
        }
    }
}

async fn remove(store: &TaskStore, key: &str) {
    match time::timeout(MAJORITY_TIMEOUT, store.kv_delete(key)).await {
        Ok(Ok(())) => {}
        Ok(Err(e)) => tracing::warn!(key, err = %e, "outbox: failed to remove a sent row"),
        Err(_) => tracing::warn!(key, "outbox: no majority to remove a sent row"),
    }
}

/// Send one write. With no cluster it runs `run` as before. A follower records the write for the
/// leader, except a merge, which only the leader decides
pub async fn send(
    store: &TaskStore,
    key: &str,
    entry: Entry,
    run: impl Future<Output = anyhow::Result<()>>,
) -> anyhow::Result<()> {
    let Some(node) = store.node() else {
        return run.await;
    };
    if !node.is_leader() {
        if matches!(entry.op, Op::Merge { .. }) {
            return Err(Fenced("only the leader merges".into()).into());
        }

        // A leader that just stepped down lands here too, and its write was not sent
        if let Err(e) = record(store, key, &entry).await {
            return Err(Fenced(format!("{e:#}")).into());
        }

        supersede(store, key, &entry).await;
        return Ok(());
    }

    let _claim = Claim::take(key);
    if let Err(e) = record(store, key, &entry).await {
        return Err(Fenced(format!("{e:#}")).into());
    }

    supersede(store, key, &entry).await;

    if let Err(e) = node.ensure_majority().await {
        tracing::warn!(key, err = %e, "outbox: leaving the write for the next leader");
        return Err(Fenced(format!("{e:#}")).into());
    }

    let result = run.await;
    remove(store, key).await;
    result
}

/// Merge through the outbox. GitHub refuses it when the head moved off `head_sha`
pub async fn merge(
    store: &TaskStore,
    gh: &GhHttp,
    repo: &str,
    pr: u64,
    delete_branch: bool,
    head_sha: &str,
) -> anyhow::Result<()> {
    let entry = Entry {
        repo: repo.to_string(),
        op: Op::Merge {
            pr,
            head_sha: head_sha.to_string(),
            delete_branch,
        },
    };
    send(
        store,
        &new_key(),
        entry,
        Box::pin(gh.merge_pr(repo, pr, delete_branch, head_sha)),
    )
    .await
}

/// On the leader, send every row no write of this process holds. A later status for the same
/// issue replaces an earlier one. A failed retry is logged and dropped. Returns the writes sent
pub async fn retry_pending(store: &TaskStore, targets: &dyn Targets) -> anyhow::Result<usize> {
    let Some(node) = store.node() else {
        return Ok(0);
    };
    if !node.is_leader() {
        return Ok(0);
    }

    let mut rows: Vec<(String, Entry)> = Vec::new();
    for (key, value) in store.kv_list_prefix(PREFIX).await? {
        match serde_json::from_str(&value) {
            Ok(entry) => rows.push((key, entry)),
            Err(e) => {
                tracing::warn!(key, err = %e, "outbox: dropping a row this version cannot read");
                remove(store, &key).await;
            }
        }
    }
    if rows.is_empty() {
        return Ok(0);
    }

    rows.sort_by(|a, b| a.0.cmp(&b.0));
    node.ensure_majority()
        .await
        .map_err(|e| Fenced(format!("{e:#}")))?;
    let latest_status: HashMap<(&str, &str), &str> = rows
        .iter()
        .filter_map(|(key, e)| match &e.op {
            Op::Status { issue, .. } => Some(((e.repo.as_str(), issue.as_str()), key.as_str())),
            _ => None,
        })
        .collect();
    let mut sent = 0;
    for (key, entry) in &rows {
        let Some(_claim) = Claim::take(key) else {
            continue;
        };
        // A live write can finish between the listing and the claim
        if store.kv_get(key).await?.is_none() {
            continue;
        }

        let superseded = match &entry.op {
            Op::Status { issue, .. } => {
                latest_status.get(&(entry.repo.as_str(), issue.as_str())) != Some(&key.as_str())
            }
            _ => false,
        };
        if !superseded {
            match retry(entry, targets).await {
                Ok(()) => sent += 1,
                Err(e) => {
                    tracing::warn!(key, repo = %entry.repo, err = %e, "outbox: retry failed, dropping it");
                }
            }
        }

        remove(store, key).await;
    }

    Ok(sent)
}

/// Run a write that may already have reached GitHub. Labels and merges are idempotent, a comment
/// looks for its marker first
async fn retry(entry: &Entry, targets: &dyn Targets) -> anyhow::Result<()> {
    let id = |issue: &str| ExternalId(issue.to_string());
    match &entry.op {
        Op::Status { issue, status } => {
            targets
                .backend(&entry.repo)?
                .update_status(&id(issue), *status)
                .await
        }
        Op::AddLabels { issue, labels } => {
            targets
                .backend(&entry.repo)?
                .set_labels(&id(issue), labels)
                .await
        }
        Op::RemoveLabel { issue, label } => {
            targets
                .backend(&entry.repo)?
                .remove_label(&id(issue), label)
                .await
        }
        Op::Comment {
            issue,
            body,
            marker,
        } => {
            let number: u64 = issue.parse()?;
            let posted = targets.comment_bodies(&entry.repo, number).await?;
            if posted.iter().any(|b| b.contains(marker.as_str())) {
                return Ok(());
            }

            targets
                .backend(&entry.repo)?
                .post_comment(&id(issue), body)
                .await
        }
        Op::Merge {
            pr,
            head_sha,
            delete_branch,
        } => {
            targets
                .merge(&entry.repo, *pr, *delete_branch, head_sha)
                .await
        }
    }
}

/// `backend` with its GitHub writes sent through the outbox. Without a cluster it is `backend`
pub fn wrap(
    backend: Arc<dyn ExternalBackend>,
    store: &TaskStore,
    repo: &str,
) -> Arc<dyn ExternalBackend> {
    if store.node().is_none() {
        return backend;
    }

    Arc::new(Outboxed {
        inner: backend,
        store: store.clone(),
        repo: repo.to_string(),
    })
}

/// A backend whose label and comment writes go through the outbox. Its other writes check the
/// majority on the leader and go straight to GitHub
struct Outboxed {
    inner: Arc<dyn ExternalBackend>,
    store: TaskStore,
    repo: String,
}

fn entry(repo: &str, op: Op) -> Entry {
    Entry {
        repo: repo.to_string(),
        op,
    }
}

/// Internal tasks have no GitHub issue, the backend skips them
fn is_issue(id: &ExternalId) -> bool {
    id.0.parse::<u64>().is_ok()
}

impl Outboxed {
    async fn fence(&self) -> anyhow::Result<()> {
        match self.store.node() {
            Some(node) if node.is_leader() => node
                .ensure_majority()
                .await
                .map_err(|e| Fenced(format!("{e:#}")).into()),
            Some(node) if !node.has_leader() => {
                Err(Fenced("this node knows no leader".into()).into())
            }
            _ => Ok(()),
        }
    }

    async fn comment(&self, repo: &str, id: &ExternalId, body: &str) -> anyhow::Result<()> {
        if !is_issue(id) {
            return self.inner.post_comment_in_repo(repo, id, body).await;
        }

        let key = new_key();
        let marker = marker(&key);
        // Redacted before the log carries it to every node, the post redacts again
        let body = format!("{}\n\n{marker}", security::redact_posted_body(body));
        let op = Op::Comment {
            issue: id.0.clone(),
            body: body.clone(),
            marker,
        };
        let run = async {
            if repo == self.repo {
                self.inner.post_comment(id, &body).await
            } else {
                self.inner.post_comment_in_repo(repo, id, &body).await
            }
        };
        send(&self.store, &key, entry(repo, op), run).await
    }
}

#[async_trait]
impl TaskReader for Outboxed {
    async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
        self.inner.get_task(id).await
    }

    async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
        self.inner.list_by_status(status).await
    }

    async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
        self.inner.list_all_tasks().await
    }

    async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
        self.inner.list_reconciliation_candidates().await
    }

    async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
        self.inner.list_routable().await
    }

    async fn list_active_open_issues(&self) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
        self.inner.list_active_open_issues().await
    }

    async fn get_active_open_issue(
        &self,
        id: &ExternalId,
    ) -> anyhow::Result<Option<(ExternalTask, Option<Status>)>> {
        self.inner.get_active_open_issue(id).await
    }

    async fn has_open_issue_with_title(&self, title: &str, label: &str) -> anyhow::Result<bool> {
        self.inner.has_open_issue_with_title(title, label).await
    }
}

#[async_trait]
impl TaskWriter for Outboxed {
    /// Not through the outbox: the caller needs the new issue number, and a retry with no caller
    /// would open a second issue
    async fn create_task(
        &self,
        title: &str,
        body: &str,
        labels: &[String],
    ) -> anyhow::Result<ExternalId> {
        self.fence().await?;
        self.inner.create_task(title, body, labels).await
    }

    async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
        if !is_issue(id) {
            return self.inner.update_status(id, status).await;
        }

        let op = Op::Status {
            issue: id.0.clone(),
            status,
        };
        let run = self.inner.update_status(id, status);
        send(&self.store, &new_key(), entry(&self.repo, op), run).await
    }

    async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
        if !is_issue(id) {
            return self.inner.set_labels(id, labels).await;
        }

        let op = Op::AddLabels {
            issue: id.0.clone(),
            labels: labels.to_vec(),
        };
        let run = self.inner.set_labels(id, labels);
        send(&self.store, &new_key(), entry(&self.repo, op), run).await
    }

    async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()> {
        if !is_issue(id) {
            return self.inner.remove_label(id, label).await;
        }

        let op = Op::RemoveLabel {
            issue: id.0.clone(),
            label: label.to_string(),
        };
        let run = self.inner.remove_label(id, label);
        send(&self.store, &new_key(), entry(&self.repo, op), run).await
    }

    async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
        self.inner.get_sub_issues(id).await
    }

    async fn create_sub_task(
        &self,
        parent_id: &ExternalId,
        title: &str,
        body: &str,
        labels: &[String],
    ) -> anyhow::Result<ExternalId> {
        self.fence().await?;
        self.inner
            .create_sub_task(parent_id, title, body, labels)
            .await
    }

    async fn ensure_status_label(&self, label: &str) -> anyhow::Result<()> {
        self.fence().await?;
        self.inner.ensure_status_label(label).await
    }
}

#[async_trait]
impl Conversation for Outboxed {
    async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()> {
        self.comment(&self.repo, id, body).await
    }

    async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
        self.inner.get_authenticated_user().await
    }

    async fn get_mentions(&self, since: &str) -> anyhow::Result<Vec<Mention>> {
        self.inner.get_mentions(since).await
    }

    async fn list_issue_comments(&self, id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
        self.inner.list_issue_comments(id).await
    }

    async fn acknowledge_issue(&self, id: &ExternalId) -> anyhow::Result<()> {
        self.fence().await?;
        self.inner.acknowledge_issue(id).await
    }

    async fn acknowledge_mention(&self, comment_id: &str) -> anyhow::Result<()> {
        self.fence().await?;
        self.inner.acknowledge_mention(comment_id).await
    }

    async fn post_comment_in_repo(
        &self,
        repo: &str,
        id: &ExternalId,
        body: &str,
    ) -> anyhow::Result<()> {
        self.comment(repo, id, body).await
    }
}

#[async_trait]
impl MergeState for Outboxed {
    async fn is_pr_merged(&self, branch: &str) -> anyhow::Result<bool> {
        self.inner.is_pr_merged(branch).await
    }

    async fn batch_is_pr_merged(
        &self,
        branches: &[String],
    ) -> anyhow::Result<HashMap<String, bool>> {
        self.inner.batch_is_pr_merged(branches).await
    }

    async fn blocked_by(&self, repo: &str, issue_number: i64) -> anyhow::Result<BlockedByFetch> {
        self.inner.blocked_by(repo, issue_number).await
    }

    async fn issue_close_state(
        &self,
        repo: &str,
        issue_number: i64,
    ) -> anyhow::Result<Option<(String, Option<String>)>> {
        self.inner.issue_close_state(repo, issue_number).await
    }

    async fn pull_request_completion(
        &self,
        repo: &str,
        pr_number: i64,
    ) -> anyhow::Result<Option<PullRequestCompletion>> {
        self.inner.pull_request_completion(repo, pr_number).await
    }

    async fn add_dependency(
        &self,
        issue_number: i64,
        blocking_repo: &str,
        blocking_number: i64,
    ) -> anyhow::Result<()> {
        self.fence().await?;
        self.inner
            .add_dependency(issue_number, blocking_repo, blocking_number)
            .await
    }
}

#[async_trait]
impl Tracker for Outboxed {
    fn name(&self) -> &str {
        self.inner.name()
    }

    async fn sync_to_project(
        &self,
        id: &ExternalId,
        status: Status,
    ) -> anyhow::Result<Option<String>> {
        self.fence().await?;
        self.inner.sync_to_project(id, status).await
    }

    async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
        self.fence().await?;
        self.inner.reconcile_project_statuses().await
    }

    async fn sync_estimate_to_project(&self, id: &ExternalId, estimate: u8) -> anyhow::Result<()> {
        self.fence().await?;
        self.inner.sync_estimate_to_project(id, estimate).await
    }

    async fn get_project_item_estimates(
        &self,
        issue_node_ids: &[String],
    ) -> anyhow::Result<HashMap<String, u8>> {
        self.inner.get_project_item_estimates(issue_node_ids).await
    }

    async fn health_check(&self) -> anyhow::Result<()> {
        self.inner.health_check().await
    }
}

#[cfg(test)]
mod tests;