orch-cli 0.117.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! `orch task move` across in-process cluster nodes. No agent binary runs here

use super::assign_tests::{
    Member, dispatch, name, other, register, routed, stop, three_nodes, wait_for_owner,
};
use super::worker;
use super::*;
use crate::engine::tasks::handoff;
use crate::store::cluster::NodeId;
use crate::store::cluster::registry::{self, Entry};
use std::collections::BTreeMap;
use std::path::Path;
use std::process;
use std::time::Duration;
use tokio::time;

const BRANCH: &str = "gh-issue-1-routed-task";

/// The leader, the node that runs the task and the third node
fn roles(leader: NodeId) -> (NodeId, NodeId) {
    let old = other(leader);
    let new = (1..=3).find(|i| *i != leader && *i != old).unwrap();
    (old, new)
}

fn git(dir: &Path, args: &[&str]) -> bool {
    process::Command::new("git")
        .args(["-c", "user.name=T", "-c", "user.email=t@t.com"])
        .args(args)
        .current_dir(dir)
        .status()
        .is_ok_and(|s| s.success())
}

/// A checkout on the old node with the task branch and one commit that was never pushed
fn old_checkout(dir: &Path) {
    assert!(git(dir, &["init", "-q", "-b", "main"]));
    assert!(git(dir, &["commit", "-q", "--allow-empty", "-m", "init"]));
    assert!(git(dir, &["checkout", "-q", "-b", BRANCH]));
    assert!(git(
        dir,
        &["commit", "-q", "--allow-empty", "-m", "unpushed step"]
    ));
}

/// A routed task that `old` runs in `in_progress` from the worktree at `wt`
async fn running_on(
    members: &BTreeMap<NodeId, Member>,
    leader: NodeId,
    old: NodeId,
    wt: &Path,
) -> i64 {
    let a = &members[&leader];
    let id = routed(&a.store, "o/r", "1", "claude").await;
    a.store
        .update_status_and_fields(
            id,
            TaskStatus::InProgress,
            &[
                ("owner_node", serde_json::json!(name(old))),
                ("owner_term", serde_json::json!(a.node.term())),
                ("lease_until", serde_json::json!("2099-01-01T00:00:00Z")),
                ("branch", serde_json::json!(BRANCH)),
            ],
        )
        .await
        .unwrap();
    let o = &members[&old].store;
    wait_for_owner(o, id, Some(&name(old))).await;
    o.set_fields(id, &[("worktree", serde_json::json!(wt.to_string_lossy()))])
        .await
        .unwrap();
    id
}

#[tokio::test(flavor = "multi_thread")]
async fn a_moved_task_is_dispatched_on_the_new_node_and_the_old_node_keeps_its_worktree() {
    let dirs: Vec<_> = (0..3).map(|_| tempfile::tempdir().unwrap()).collect();
    let (members, leader) = three_nodes(&dirs).await;
    let (old, new) = roles(leader);
    let a = &members[&leader];
    for id in [leader, old, new] {
        register(&a.store, &name(id), &["o/r"], &["claude"], 4).await;
    }

    let wt = tempfile::tempdir().unwrap();
    old_checkout(wt.path());
    let id = running_on(&members, leader, old, wt.path()).await;

    // The CLI on the new node sends the move through its own store
    let n = &members[&new].store;
    let task = wait_for_owner(n, id, Some(&name(old))).await;
    let moved = handoff::move_task(n, &task, Some(&name(new)), chrono::Utc::now())
        .await
        .unwrap();
    assert_eq!(moved.from.as_deref(), Some(name(old).as_str()));
    assert!(moved.from_online);
    let task = wait_for_owner(&a.store, id, Some(&name(new))).await;
    assert_eq!(task.status, TaskStatus::Routed);
    assert_eq!(task.lease_until, None);
    assert_eq!(task.owner_term, None);

    // The leader dispatches it on the new node, under its own term
    assert_eq!(
        dispatch(&a.store, "o/r").await,
        0,
        "the leader starts nothing"
    );
    let task = a.store.get(id).await.unwrap();
    assert_eq!(task.status, TaskStatus::InProgress);
    assert_eq!(task.owner_node.as_deref(), Some(name(new).as_str()));
    assert_eq!(task.owner_term, Some(i64::try_from(a.node.term()).unwrap()));
    let on_new = wait_for_owner(n, id, Some(&name(new))).await;
    assert!(!n.runs_elsewhere(&on_new), "the new node runs it");

    // The old node drops its run and ends its session, and keeps the worktree and the branch
    let o = &members[&old];
    let seen = o.store.get(id).await.unwrap();
    assert!(o.store.moved_away(&seen));
    assert_eq!(o.store.moved_from(&name(old)).await.unwrap(), vec![id]);
    worker::end_moved_sessions(&o.store, &TmuxManager::new(), &o.node).await;
    for _ in 0..200 {
        if a.store.moved_from(&name(old)).await.unwrap().is_empty() {
            break;
        }

        time::sleep(Duration::from_millis(50)).await;
    }
    assert!(a.store.moved_from(&name(old)).await.unwrap().is_empty());
    assert!(wt.path().exists());
    assert!(git(wt.path(), &["rev-parse", "--verify", "-q", BRANCH]));
    assert_eq!(
        o.store.get(id).await.unwrap().worktree,
        wt.path().to_string_lossy()
    );
    stop(members).await;
}

#[tokio::test(flavor = "multi_thread")]
async fn a_task_moved_to_an_offline_node_waits_for_it() {
    let dirs: Vec<_> = (0..3).map(|_| tempfile::tempdir().unwrap()).collect();
    let (members, leader) = three_nodes(&dirs).await;
    let (old, new) = roles(leader);
    let a = &members[&leader];
    for id in [leader, old] {
        register(&a.store, &name(id), &["o/r"], &["claude"], 4).await;
    }
    registry::write(
        &a.store,
        &Entry {
            node: name(new),
            projects: vec!["o/r".into()],
            agents: vec!["claude".into()],
            max_parallel: 4,
            version: None,
            witness: false,
            seen: (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339(),
        },
    )
    .await
    .unwrap();
    let wt = tempfile::tempdir().unwrap();
    let id = running_on(&members, leader, old, wt.path()).await;
    let task = a.store.get(id).await.unwrap();

    let moved = handoff::move_task(&a.store, &task, Some(&name(new)), chrono::Utc::now())
        .await
        .unwrap();
    assert!(!moved.to_online);
    dispatch(&a.store, "o/r").await;
    let task = a.store.get(id).await.unwrap();
    assert_eq!(task.status, TaskStatus::Routed, "no other node takes it");
    assert_eq!(task.owner_node.as_deref(), Some(name(new).as_str()));
    stop(members).await;
}