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
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
//! `orch stream` and `orch task watch`: tail each running agent's `output.json` through the
//! NDJSON formatter. The runner tees agent stdout there, so lines arrive whole

use crate::channels::tmux;
use crate::cli;
use crate::cli::task::reference;
use crate::engine::runner::ndjson::{self, Formatter};
use crate::store::cluster;
use crate::store::cluster::discovery;
use crate::store::cluster::local::{self, Endpoint};
use crate::store::cluster::output::{Cursor, Output};
use crate::store::{Task, TaskStatus, TaskStore};
use crate::sys::home;
use crate::sys::tmux::TmuxManager;
use std::collections::HashMap;
use std::fs::File;
use std::io::{IsTerminal, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

use tokio::time;

use std::fs;
use std::io;
use std::mem;

// Replayed when a file is first opened, so a new viewer sees recent context
const BACKLOG_BYTES: u64 = 64 * 1024;

pub(crate) struct Tail {
    path: PathBuf,
    offset: u64,
    partial: Vec<u8>,
    skip_first: bool,
    formatter: Formatter,
}

impl Tail {
    /// New lines since the last read, run through the formatter when `formatted` is set
    pub(crate) fn read_entries(&mut self, formatted: bool) -> Vec<String> {
        let mut entries = Vec::new();
        for line in self.read_lines() {
            if formatted {
                entries.extend(self.formatter.format(&line));
            } else {
                entries.push(line);
            }
        }
        entries
    }

    pub(crate) fn open(path: PathBuf, color: bool) -> Self {
        let len = fs::metadata(&path).map_or(0, |m| m.len());
        let offset = len.saturating_sub(BACKLOG_BYTES);
        Self {
            path,
            offset,
            partial: Vec::new(),
            skip_first: offset > 0,
            formatter: Formatter::new(color),
        }
    }

    /// Follow only what is written from now on
    pub(crate) fn open_at_end(path: PathBuf) -> Self {
        let offset = fs::metadata(&path).map_or(0, |m| m.len());
        Self {
            path,
            offset,
            partial: Vec::new(),
            skip_first: false,
            formatter: Formatter::new(false),
        }
    }

    /// The file is shorter than what was read, so it was rotated or truncated
    pub(crate) fn shrank(&self) -> bool {
        fs::metadata(&self.path).is_ok_and(|m| m.len() < self.offset)
    }

    /// Complete lines appended since the last call
    pub(crate) fn read_lines(&mut self) -> Vec<String> {
        let mut buf = Vec::new();
        let read = File::open(&self.path).and_then(|mut f| {
            f.seek(SeekFrom::Start(self.offset))?;
            f.read_to_end(&mut buf)
        });
        let Ok(n) = read else {
            return vec![];
        };

        self.offset += n as u64;
        self.partial.extend_from_slice(&buf);
        let Some(end) = self.partial.iter().rposition(|&b| b == b'\n') else {
            return vec![];
        };

        let rest = self.partial.split_off(end + 1);
        let complete = mem::replace(&mut self.partial, rest);
        let mut lines: Vec<String> = String::from_utf8_lossy(&complete)
            .lines()
            .map(String::from)
            .collect();
        // The backlog starts mid-line
        if mem::take(&mut self.skip_first) && !lines.is_empty() {
            lines.remove(0);
        }

        lines
    }
}

/// Follow one task (and its review) when `task_id` is set, else every running agent session
pub async fn run(task_id: Option<&str>, formatted: bool) -> anyhow::Result<()> {
    let color = formatted && io::stdout().is_terminal();
    let watched = if let Some(id) = task_id {
        println!("Watching task {id}. Ctrl+C to stop");
        Some(Watched::resolve(id).await?)
    } else {
        println!("Watching all running agents. Ctrl+C to stop");
        None
    };
    // In a cluster the task may run on another node, and the service relays its output
    let daemon = if cluster::enabled() {
        local::daemon_endpoint().await
    } else {
        None
    };
    if let (Some(task), Some(endpoint)) = (&watched, &daemon) {
        return follow_remote(task, endpoint, formatted, color).await;
    }

    let others = match daemon {
        Some(endpoint) => Some(Others::new(endpoint).await?),
        None => None,
    };
    follow_local(watched.as_ref(), others, formatted, color).await
}

async fn follow_local(
    watched: Option<&Watched>,
    mut others: Option<Others>,
    formatted: bool,
    color: bool,
) -> anyhow::Result<()> {
    let mut tails: HashMap<String, Tail> = HashMap::new();
    let mut printer = Printer::new(formatted, color);
    let mut said_waiting = false;
    loop {
        let found = match watched {
            Some(task) => task.sources(),
            None => session_sources().await,
        };
        if let (Some(task), true, false) = (watched, found.is_empty(), said_waiting) {
            println!("{}", task.nothing_yet());
            said_waiting = true;
        }

        let live: Vec<String> = found.iter().map(|(key, _)| key.clone()).collect();
        for (key, path) in found {
            let tail = tails
                .entry(key)
                .or_insert_with(|| Tail::open(path.clone(), color));
            if tail.path != path {
                *tail = Tail::open(path, color);
            }
        }

        // A session that just ended gets this last read, its final message lands after the work
        for tail in tails.values_mut() {
            let entries = tail.read_entries(formatted);
            printer.print(&tail.path, &entries);
        }
        tails.retain(|key, _| live.contains(key));
        if let Some(others) = others.as_mut() {
            others.poll(&mut printer).await;
        }

        io::stdout().flush()?;
        time::sleep(Duration::from_secs(1)).await;
    }
}

/// Every entry carries its task and attempt in a coloured gutter, since output scrolls fast
struct Printer {
    formatted: bool,
    color: bool,
    colors: HashMap<String, &'static str>,
    tag_width: usize,
}

impl Printer {
    fn new(formatted: bool, color: bool) -> Self {
        Self {
            formatted,
            color,
            colors: HashMap::new(),
            tag_width: 0,
        }
    }

    fn print(&mut self, path: &Path, entries: &[String]) {
        if entries.is_empty() {
            return;
        }

        let tag = tag(path);
        self.tag_width = self.tag_width.max(tag.chars().count());
        let next = TAG_COLORS[self.colors.len() % TAG_COLORS.len()];
        let code = *self.colors.entry(key_of(path)).or_insert(next);
        let (width, color) = (self.tag_width, self.color);
        let gutter = |show: bool| {
            let text = if show { tag.as_str() } else { "" };
            let text = format!("{text:<width$} │");
            if color {
                format!("\x1b[{code}m{text}\x1b[0m")
            } else {
                text
            }
        };
        for line in tag_lines(entries, self.formatted, gutter) {
            println!("{line}");
        }
    }
}

/// One task's output read through the service, which fetches it from the node that runs it
struct Remote {
    cursor: Cursor,
    formatter: Formatter,
}

impl Remote {
    fn new(task: i64, color: bool) -> Self {
        Self {
            cursor: Cursor {
                task,
                ..Cursor::default()
            },
            formatter: Formatter::new(color),
        }
    }

    /// The entries since the last call, and the file they came from
    async fn read(
        &mut self,
        endpoint: &Endpoint,
        formatted: bool,
        color: bool,
    ) -> anyhow::Result<Fetched> {
        let chunk = match local::fetch_output(endpoint, &self.cursor).await? {
            Output::Lines(chunk) => chunk,
            Output::Offline { node } => return Ok(Fetched::Offline(node)),
        };
        if chunk.file != self.cursor.file {
            self.formatter = Formatter::new(color);
        }

        let mut entries = Vec::new();
        for line in &chunk.lines {
            if formatted {
                entries.extend(self.formatter.format(line));
            } else {
                entries.push(line.clone());
            }
        }
        self.cursor.offset = Some(chunk.offset);
        self.cursor.file.clone_from(&chunk.file);
        Ok(Fetched::Entries(chunk.file.map(PathBuf::from), entries))
    }
}

enum Fetched {
    Entries(Option<PathBuf>, Vec<String>),
    Offline(String),
}

/// `orch stream <id>` in a cluster. The stream ends when the node that runs the task goes offline
async fn follow_remote(
    task: &Watched,
    endpoint: &Endpoint,
    formatted: bool,
    color: bool,
) -> anyhow::Result<()> {
    let store_id = task
        .store_id
        .ok_or_else(|| anyhow::anyhow!("{} is not in the store", task.id))?;
    let mut remote = Remote::new(store_id, color);
    let mut printer = Printer::new(formatted, color);
    let mut said_waiting = false;
    loop {
        match remote.read(endpoint, formatted, color).await? {
            Fetched::Offline(node) => {
                println!("{}", offline_message(&task.id, &node));
                return Ok(());
            }
            Fetched::Entries(None, _) if !said_waiting => {
                println!(
                    "No output for task {} yet, waiting for it to start",
                    task.id
                );
                said_waiting = true;
            }
            Fetched::Entries(Some(path), entries) => printer.print(&path, &entries),
            Fetched::Entries(None, _) => {}
        }

        io::stdout().flush()?;
        time::sleep(Duration::from_secs(1)).await;
    }
}

fn offline_message(task: &str, node: &str) -> String {
    format!("Task {task} runs on {node}, which is offline. The stream ends here")
}

/// Running tasks other nodes own, for `orch stream` with no id in a cluster
struct Others {
    endpoint: Endpoint,
    store: TaskStore,
    me: Option<String>,
    remotes: HashMap<i64, Remote>,
    /// Tasks whose node was offline, skipped until the task changes hands or ends
    offline: HashMap<i64, String>,
}

impl Others {
    async fn new(endpoint: Endpoint) -> anyhow::Result<Self> {
        Ok(Self {
            endpoint,
            store: cli::init_store().await?,
            me: discovery::status().await.ok().map(|t| t.me.name),
            remotes: HashMap::new(),
            offline: HashMap::new(),
        })
    }

    async fn running(&self) -> Vec<Task> {
        let mut running = Vec::new();
        for status in [TaskStatus::InProgress, TaskStatus::InReview] {
            running.extend(
                self.store
                    .list_all_by_status_global(status)
                    .await
                    .unwrap_or_default(),
            );
        }
        running
            .into_iter()
            .filter(|t| t.owner_node.is_some() && t.owner_node != self.me)
            .collect()
    }

    async fn poll(&mut self, printer: &mut Printer) {
        let running = self.running().await;
        self.remotes
            .retain(|id, _| running.iter().any(|t| t.id == *id));
        self.offline.retain(|id, node| {
            running
                .iter()
                .any(|t| t.id == *id && t.owner_node.as_deref() == Some(node.as_str()))
        });
        for task in running {
            if self.offline.contains_key(&task.id) {
                continue;
            }

            let remote = self
                .remotes
                .entry(task.id)
                .or_insert_with(|| Remote::new(task.id, printer.color));
            match remote
                .read(&self.endpoint, printer.formatted, printer.color)
                .await
            {
                Ok(Fetched::Entries(Some(path), entries)) => printer.print(&path, &entries),
                Ok(Fetched::Entries(None, _)) => {}
                Ok(Fetched::Offline(node)) => {
                    let id = format!(
                        "{}#{}",
                        task.repo,
                        task.external_id.as_deref().unwrap_or_default()
                    );
                    println!("{}", offline_message(&id, &node));
                    self.offline.insert(task.id, node);
                    self.remotes.remove(&task.id);
                }
                Err(e) => tracing::debug!(task = task.id, err = %e, "could not read remote output"),
            }
        }
    }
}

/// The task `orch task watch <id>` follows, resolved once through the shared CLI helper
struct Watched {
    id: String,
    store_id: Option<i64>,
    status: String,
    /// The task's review dir and its own
    dirs: Vec<PathBuf>,
}

impl Watched {
    async fn resolve(id: &str) -> anyhow::Result<Self> {
        let store = cli::init_store().await?;
        // The review dir is watched anyway, so `<id>-review` watches the same pair
        let id = id.strip_suffix("-review").unwrap_or(id);
        let task = reference::resolve(&store, id).await?;
        Ok(Self {
            id: task.display_spec(),
            store_id: task.store_id,
            status: task.status.clone(),
            dirs: reference::state_dirs(&task)?,
        })
    }

    fn sources(&self) -> Vec<(String, PathBuf)> {
        newest_output(&self.dirs)
            .map(|path| (self.id.clone(), path))
            .into_iter()
            .collect()
    }

    /// A running task with no output file is a problem, so name the path instead of waiting quietly
    fn nothing_yet(&self) -> String {
        if self.status != TaskStatus::InProgress.as_str() {
            return format!(
                "No output for task {} yet, waiting for it to start",
                self.id
            );
        }

        let searched: Vec<String> = self
            .dirs
            .iter()
            .map(|dir| dir.join("attempts").display().to_string())
            .collect();
        format!(
            "Task {} is in_progress but no output file was found under {}",
            self.id,
            searched.join(" or ")
        )
    }
}

/// Output files of every running agent session, keyed by session name
async fn session_sources() -> Vec<(String, PathBuf)> {
    let tmux = TmuxManager::new();
    tmux::list_orch_sessions()
        .await
        .unwrap_or_default()
        .into_iter()
        .filter_map(|session| {
            let (project, task) = tmux.parse_session_name(&session)?;
            let path = session_output(&project, &task_dir_name(&task))?;
            Some((session, path))
        })
        .collect()
}

/// Session names replace `:` with `-`, task dirs keep the `internal:` id
fn task_dir_name(task: &str) -> String {
    match task.strip_prefix("internal-") {
        Some(rest) => format!("internal:{rest}"),
        None => task.to_string(),
    }
}

/// A tmux session names the repo without its owner, so look under every owner
fn session_output(project: &str, name: &str) -> Option<PathBuf> {
    let state = home::state_dir().ok()?;
    let dirs: Vec<PathBuf> = subdirs(&state)
        .iter()
        .flat_map(|owner| subdirs(owner))
        .filter(|repo| repo.file_name() == Some(project.as_ref()))
        .map(|repo| repo.join("tasks").join(name))
        .collect();
    newest_output(&dirs)
}

/// Newest `output.json` under `<dir>/attempts/*` for any of `dirs`
pub(crate) fn newest_output(dirs: &[PathBuf]) -> Option<PathBuf> {
    let mut best: Option<(SystemTime, PathBuf)> = None;
    for dir in dirs {
        for attempt in subdirs(&dir.join("attempts")) {
            let output = attempt.join("output.json");
            let Ok(modified) = output.metadata().and_then(|m| m.modified()) else {
                continue;
            };
            if best.as_ref().is_none_or(|(t, _)| modified > *t) {
                best = Some((modified, output));
            }
        }
    }

    best.map(|(_, p)| p)
}

fn subdirs(dir: &Path) -> Vec<PathBuf> {
    fs::read_dir(dir)
        .into_iter()
        .flatten()
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.is_dir())
        .collect()
}

const TAG_COLORS: [&str; 6] = ["36", "35", "33", "34", "96", "95"];

/// Entry lines with `gutter(true)` on each step's first line and `gutter(false)` on the rest
fn tag_lines(entries: &[String], formatted: bool, gutter: impl Fn(bool) -> String) -> Vec<String> {
    let mut out = Vec::new();
    for entry in entries {
        let step = !formatted || !entry.starts_with(ndjson::RESULT_PREFIX);
        if formatted && step {
            out.push(gutter(false));
        }

        for (i, line) in entry.lines().enumerate() {
            out.push(format!("{} {line}", gutter(step && i == 0)));
        }
    }
    out
}

/// `<repo>#<task> a<n>` from `.../<repo>/tasks/<task>/attempts/<n>/output.json`
fn tag(path: &Path) -> String {
    match path_parts(path).as_slice() {
        [attempt, _, task, _, repo] => {
            let task = task.strip_prefix("internal:").unwrap_or(task);
            format!("{repo}#{task} a{attempt}")
        }
        _ => path.display().to_string(),
    }
}

/// Task dir of an output file, so a task keeps its colour across attempts
fn key_of(path: &Path) -> String {
    path.ancestors()
        .nth(3)
        .map_or_else(String::new, |p| p.display().to_string())
}

fn path_parts(path: &Path) -> Vec<String> {
    path.iter()
        .rev()
        .skip(1)
        .take(5)
        .map(|p| p.to_string_lossy().into_owned())
        .collect()
}

/// Print entries with a blank line before each step, keeping results right under their call
pub fn print(entries: &[String]) {
    for entry in entries {
        if entry.starts_with(ndjson::RESULT_PREFIX) {
            println!("{entry}");
        } else {
            println!("\n{entry}");
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs::OpenOptions;
    use std::thread;

    use super::*;

    #[test]
    fn tail_returns_only_complete_lines() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("output.json");
        fs::write(&path, "one\ntw").unwrap();
        let mut tail = Tail::open(path.clone(), false);
        assert_eq!(tail.read_lines(), vec!["one"]);

        let mut f = OpenOptions::new().append(true).open(&path).unwrap();
        f.write_all(b"o\nthree\n").unwrap();
        assert_eq!(tail.read_lines(), vec!["two", "three"]);
        assert_eq!(tail.read_lines(), [] as [String; 0]);
    }

    #[test]
    fn tail_skips_cut_line_in_backlog() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("output.json");
        let long = "x".repeat(usize::try_from(BACKLOG_BYTES).unwrap());

        fs::write(&path, format!("{long}\nlast\n")).unwrap();
        assert_eq!(Tail::open(path, false).read_lines(), vec!["last"]);
    }

    #[test]
    fn task_dir_name_restores_internal_colon() {
        assert_eq!(task_dir_name("internal-8-review"), "internal:8-review");
        assert_eq!(task_dir_name("3601"), "3601");
    }

    #[test]
    fn in_progress_without_output_names_the_path() {
        let watched = Watched {
            id: "owner/repo#5".to_string(),
            store_id: Some(5),
            status: TaskStatus::InProgress.as_str().to_string(),
            dirs: vec![
                PathBuf::from("/state/owner/repo/tasks/5-review"),
                PathBuf::from("/state/owner/repo/tasks/5"),
            ],
        };
        let msg = watched.nothing_yet();
        assert!(msg.contains("in_progress"), "{msg}");
        assert!(msg.contains("/state/owner/repo/tasks/5/attempts"), "{msg}");
        assert!(
            msg.contains("/state/owner/repo/tasks/5-review/attempts"),
            "{msg}"
        );

        let waiting = Watched {
            status: TaskStatus::Routed.as_str().to_string(),
            ..watched
        };
        let msg = waiting.nothing_yet();
        assert!(msg.contains("waiting for it to start"), "{msg}");
        assert!(!msg.contains("no output file was found"), "{msg}");
    }

    #[test]
    fn newest_output_picks_the_latest_attempt() {
        let dir = tempfile::tempdir().unwrap();
        let task = dir.path().join("tasks").join("5");
        for attempt in ["1", "2"] {
            let d = task.join("attempts").join(attempt);
            fs::create_dir_all(&d).unwrap();
            fs::write(d.join("output.json"), attempt).unwrap();
            // mtime resolution is coarse on some filesystems
            thread::sleep(Duration::from_millis(10));
        }
        let found = newest_output(&[task.join("5-review"), task.clone()]).unwrap();
        assert_eq!(found, task.join("attempts").join("2").join("output.json"));
        assert!(newest_output(&[dir.path().join("missing")]).is_none());
    }

    #[test]
    fn tag_drops_internal_prefix() {
        let path = Path::new("/s/owner/bean/tasks/internal:189488-review/attempts/1/output.json");
        assert_eq!(tag(path), "bean#189488-review a1");
        assert_eq!(key_of(path), "/s/owner/bean/tasks/internal:189488-review");
    }

    #[test]
    fn tag_lines_label_each_step_only() {
        let entries = vec![
            "⏺ Read(a.rs)".to_string(),
            "  ⎿  Read 3 lines".to_string(),
            "⏺ Fixing it.\n  Then test.".to_string(),
        ];
        let gutter = |show: bool| if show { "t1 │" } else { "   │" }.to_string();
        assert_eq!(
            tag_lines(&entries, true, gutter),
            vec![
                "   │",
                "t1 │ ⏺ Read(a.rs)",
                "   │   ⎿  Read 3 lines",
                "   │",
                "t1 │ ⏺ Fixing it.",
                "   │   Then test.",
            ]
        );
    }

    #[test]
    fn tag_lines_raw_tags_every_line() {
        let entries = vec!["{\"a\":1}".to_string(), "{\"b\":2}".to_string()];
        let gutter = |show: bool| if show { "t │" } else { "  │" }.to_string();
        assert_eq!(
            tag_lines(&entries, false, gutter),
            vec!["t │ {\"a\":1}", "t │ {\"b\":2}"]
        );
    }
}