orch-cli 0.117.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! The leader serves projects it does not host, across in-process cluster nodes. Work that needs a
//! checkout goes to the node that hosts the project. No agent binary runs here

use super::assign::{self, WAITING_PREFIX};
use super::assign_tests::{
    Member, name, other, register, register_entry, routed, stop, three_nodes,
};
use super::tests::MockBackend;
use super::*;
use crate::channels::transport::Transport;
use crate::engine::chore::{self, Ask, Checkout, Execute, Outcome, Request};
use crate::engine::review::auto_merge::{WorktreeRebaseOutcome, rebase_on_host};
use crate::engine::service::cluster_projects;
use crate::store::cluster::NodeId;
use crate::store::cluster::registry::Entry;
use async_trait::async_trait;
use std::collections::BTreeMap;
use std::fs;
use std::sync::Mutex;
use std::time::Duration;
use tokio::time;

const REPO: &str = "o/b";

/// Node `a` leads and hosts nothing, `b` hosts `REPO`
async fn a_leads_b_hosts(dirs: &[tempfile::TempDir]) -> (BTreeMap<NodeId, Member>, NodeId, NodeId) {
    let (members, leader) = three_nodes(dirs).await;
    let b = other(leader);
    register(&members[&leader].store, &name(leader), &[], &["claude"], 4).await;
    register(&members[&leader].store, &name(b), &[REPO], &["claude"], 4).await;
    (members, leader, b)
}

/// Executes nothing, records each request and answers with a rebased branch
#[derive(Default)]
struct Rebaser {
    seen: Mutex<Vec<(String, String)>>,
}

#[async_trait]
impl Execute for Rebaser {
    async fn execute(&self, _store: &Arc<TaskStore>, repo: &str, request: &Request) -> Outcome {
        self.seen
            .lock()
            .unwrap()
            .push((repo.to_string(), format!("{request:?}")));
        Outcome::Rebase {
            outcome: WorktreeRebaseOutcome::RebasedAndPushed,
        }
    }
}

/// Ask the leader's question until a node answered it
async fn rebase_until_done(store: &Arc<TaskStore>, task_id: &str) -> WorktreeRebaseOutcome {
    for _ in 0..200 {
        match rebase_on_host(store, REPO, task_id, 7, true).await {
            Some(WorktreeRebaseOutcome::Waiting(_)) => {}
            Some(outcome) => return outcome,
            None => panic!("the leader does not host the repo, it must not rebase here"),
        }

        time::sleep(Duration::from_millis(50)).await;
    }

    panic!("no node answered the rebase");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_leader_with_no_project_serves_and_assigns_a_project_b_hosts() {
    let dirs: Vec<_> = (0..3).map(|_| tempfile::tempdir().unwrap()).collect();
    let (members, a_id, b_id) = a_leads_b_hosts(&dirs).await;
    let a = &members[&a_id];

    // The leader serves the project from the registry
    assert_eq!(
        cluster_projects::remote_projects(&a.store, &HashSet::new()).await,
        vec![REPO.to_string()]
    );
    // The router is offered the agents of the node that hosts it
    assert_eq!(
        assign::host_agents(&a.store, REPO).await,
        Some(["claude".to_string()].into())
    );

    // A new issue the leader ingested and routed is assigned to b
    let id = routed(&a.store, REPO, "1", "claude").await;
    let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
    let task_manager = Arc::new(TaskManager::with_store(
        Arc::clone(&backend),
        Arc::clone(&a.store),
        REPO.to_string(),
    ));
    let (weight_tx, _weight_rx) = mpsc::channel(16);
    tick_dispatch_tasks(
        &backend,
        &Arc::new(TmuxManager::new()),
        REPO,
        &Arc::new(TaskRunner::new(REPO.to_string())),
        &Arc::new(CaptureService::new(Arc::new(Transport::new()))),
        &Arc::new(Semaphore::new(4)),
        &task_manager,
        &weight_tx,
        DispatchMode {
            is_degraded: false,
            healthy_agents: 1,
            threshold: 1,
        },
        &Arc::new(DashMap::new()),
        &a.store,
        &HashMap::new(),
    )
    .await
    .unwrap();
    let task = a.store.get(id).await.unwrap();
    assert_eq!(task.status, TaskStatus::InProgress);
    assert_eq!(task.owner_node.as_deref(), Some(name(b_id).as_str()));
    stop(members).await;
}

#[tokio::test(flavor = "multi_thread")]
async fn the_rebase_of_an_approved_pr_runs_on_the_node_that_hosts_the_repo() {
    let dirs: Vec<_> = (0..3).map(|_| tempfile::tempdir().unwrap()).collect();
    let (members, a_id, b_id) = a_leads_b_hosts(&dirs).await;
    let (a, b) = (&members[&a_id], &members[&b_id]);
    routed(&a.store, REPO, "1", "claude").await;

    let first = rebase_on_host(&a.store, REPO, "1", 7, true).await;
    assert_eq!(
        first,
        Some(WorktreeRebaseOutcome::Waiting(format!(
            "the rebase runs on {}",
            name(b_id)
        )))
    );

    // The leader's node never runs it
    let on_a = Arc::new(Rebaser::default());
    let on_a_exec: Arc<dyn Execute> = Arc::clone(&on_a) as Arc<dyn Execute>;
    chore::run_assigned(&a.store, &on_a_exec).await;

    let on_b = Arc::new(Rebaser::default());
    let on_b_exec: Arc<dyn Execute> = Arc::clone(&on_b) as Arc<dyn Execute>;
    for _ in 0..200 {
        chore::run_assigned(&b.store, &on_b_exec).await;
        if !on_b.seen.lock().unwrap().is_empty() {
            break;
        }

        time::sleep(Duration::from_millis(50)).await;
    }

    // The leader reads the outcome once, so it merges after the rebase
    assert_eq!(
        rebase_until_done(&a.store, "1").await,
        WorktreeRebaseOutcome::RebasedAndPushed
    );
    assert!(
        on_a.seen.lock().unwrap().is_empty(),
        "the leader ran nothing"
    );
    let seen = on_b.seen.lock().unwrap().clone();
    assert_eq!(seen.len(), 1);
    assert_eq!(seen[0].0, REPO);
    assert!(seen[0].1.contains("carry: true"), "{}", seen[0].1);
    assert_eq!(
        a.store.kv_list_prefix("chore:").await.unwrap().len(),
        0,
        "a read outcome leaves no row"
    );
    stop(members).await;
}

#[tokio::test(flavor = "multi_thread")]
async fn a_bash_job_for_a_project_b_hosts_runs_on_b() {
    let dirs: Vec<_> = (0..3).map(|_| tempfile::tempdir().unwrap()).collect();
    let (members, a_id, b_id) = a_leads_b_hosts(&dirs).await;
    let (a, b) = (&members[&a_id], &members[&b_id]);

    // a reads the job from the .orch.yml it fetched, b has the checkout
    let a_config = tempfile::tempdir().unwrap();
    let b_checkout = tempfile::tempdir().unwrap();
    let jobs_path = a_config.path().join(".orch.yml");
    fs::write(
        &jobs_path,
        "jobs:\n  - id: mark\n    schedule: \"* * * * *\"\n    type: bash\n    command: \"echo ran > marker\"\n",
    )
    .unwrap();
    let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());

    jobs::tick(&jobs_path, &backend, Some(&a.store), REPO, None)
        .await
        .unwrap();
    assert!(!a_config.path().join("marker").exists(), "a ran nothing");

    let checkout: Arc<dyn Execute> = Arc::new(Checkout {
        dirs: [(REPO.to_string(), b_checkout.path().to_path_buf())].into(),
    });
    let marker = b_checkout.path().join("marker");
    let mut status = None;
    for _ in 0..200 {
        chore::run_assigned(&b.store, &checkout).await;
        jobs::tick(&jobs_path, &backend, Some(&a.store), REPO, None)
            .await
            .unwrap();
        status = a
            .store
            .get_job_state(REPO, "mark")
            .await
            .unwrap()
            .and_then(|s| s.last_task_status);
        if status.is_some() {
            break;
        }

        time::sleep(Duration::from_millis(50)).await;
    }

    assert_eq!(status.as_deref(), Some("done"));
    assert_eq!(fs::read_to_string(&marker).unwrap().trim(), "ran");
    assert!(!a_config.path().join("marker").exists());
    stop(members).await;
}

#[tokio::test(flavor = "multi_thread")]
async fn with_the_host_offline_the_work_waits_and_no_counter_changes() {
    let dirs: Vec<_> = (0..3).map(|_| tempfile::tempdir().unwrap()).collect();
    let (members, leader) = three_nodes(&dirs).await;
    let a = &members[&leader];
    register(&a.store, &name(leader), &[], &["claude"], 4).await;
    register_entry(
        &a.store,
        Entry {
            node: name(other(leader)),
            projects: vec![REPO.into()],
            agents: vec!["claude".into()],
            max_parallel: 4,
            version: None,
            witness: false,
            seen: (chrono::Utc::now() - chrono::Duration::minutes(10)).to_rfc3339(),
        },
    )
    .await;
    let id = routed(&a.store, REPO, "1", "claude").await;
    let before = a.store.get(id).await.unwrap();

    for _ in 0..2 {
        assert_eq!(
            rebase_on_host(&a.store, REPO, "1", 7, false).await,
            Some(WorktreeRebaseOutcome::Waiting(chore::waiting_note(REPO)))
        );
    }
    let task = a.store.get(id).await.unwrap();
    assert_eq!(task.last_error, format!("{WAITING_PREFIX}{REPO}"));
    assert_eq!(task.status, before.status);
    assert_eq!(task.attempts, before.attempts);
    assert_eq!(task.merge_conflict_retries, before.merge_conflict_retries);
    assert_eq!(task.ci_merge_failures, before.ci_merge_failures);
    assert!(
        a.store.kv_list_prefix("chore:").await.unwrap().is_empty(),
        "a wait writes no row and no timer"
    );

    // A bash job waits too and keeps its schedule, so the next tick tries again
    let config = tempfile::tempdir().unwrap();
    let jobs_path = config.path().join(".orch.yml");
    fs::write(
        &jobs_path,
        "jobs:\n  - id: mark\n    schedule: \"* * * * *\"\n    type: bash\n    command: \"true\"\n",
    )
    .unwrap();
    let backend: Arc<dyn ExternalBackend> = Arc::new(MockBackend::new());
    jobs::tick(&jobs_path, &backend, Some(&a.store), REPO, None)
        .await
        .unwrap();
    let state = a.store.get_job_state(REPO, "mark").await.unwrap().unwrap();
    assert_eq!(state.last_run, None);
    assert_eq!(state.last_task_status, Some(chore::waiting_note(REPO)));
    stop(members).await;
}

#[tokio::test]
async fn one_machine_runs_the_work_here() {
    let store = Arc::new(TaskStore::open_memory().await.unwrap());
    let request = Request::Shipcheck {
        task_id: "1".into(),
    };
    assert_eq!(chore::ask(&store, REPO, request).await, Ask::Here);
    assert_eq!(rebase_on_host(&store, REPO, "1", 7, true).await, None);
    assert_eq!(chore::place(&store, REPO).await, chore::Where::Here);
    assert!(
        cluster_projects::remote_projects(&store, &HashSet::new())
            .await
            .is_empty()
    );
}