orch-cli 0.117.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;
use std::iter;

use chrono::{DateTime, Utc};

use crate::cli;
use crate::store::cluster;
use crate::store::cluster::registry::{self, Entry};
use crate::store::cluster::{discovery, local};
use crate::store::{Task, TaskStatus};

/// The cluster's members as this machine's service sees them
pub async fn run() -> anyhow::Result<()> {
    if !cluster::enabled() {
        println!("orch runs on this machine only: the config has no cluster section");
        return Ok(());
    }

    let Some(endpoint) = local::daemon_endpoint().await else {
        anyhow::bail!("the orch service is not running");
    };
    let members = local::fetch_nodes(&endpoint).await?;
    let tailnet = discovery::status().await.ok();
    let name_of = |addr: &str| {
        let ip = addr.split(':').next().unwrap_or_default();
        tailnet
            .as_ref()
            .and_then(|t| {
                iter::once(&t.me)
                    .chain(&t.peers)
                    .find(|h| h.ip == ip)
                    .map(|h| (h.name.clone(), h.online))
            })
            .unwrap_or_else(|| (ip.to_string(), true))
    };
    println!(
        "{:<20} {:<22} {:<8} {:<10} STATE",
        "NODE", "ADDRESS", "ROLE", "VERSION"
    );
    for m in members {
        let (name, online) = name_of(&m.addr);
        let role = if m.voter { "voter" } else { "learner" };
        let version = m.version.map_or_else(|| "-".to_string(), |v| v.to_string());
        let mut state = Vec::new();
        let needs = m.needs_upgrade.map(|v| format!("needs upgrade to {v}"));
        if let Some(needs) = &needs {
            state.push(needs.as_str());
        }
        if m.leader {
            state.push("leader");
        }
        if m.me {
            state.push("this machine");
        }
        if !online {
            state.push("offline");
        }
        let failed = m
            .answered
            .and_then(|a| a.upgrade_error)
            .map(|e| format!("upgrade failed: {e}"));
        if let Some(failed) = &failed {
            state.push(failed.as_str());
        }
        println!(
            "{name:<20} {:<22} {role:<8} {version:<10} {}",
            m.addr,
            state.join(", ")
        );
    }

    let store = cli::init_store().await?;
    let entries = registry::read(&store).await?;
    let mut running = store
        .list_all_by_status_global(TaskStatus::InProgress)
        .await?;
    running.extend(
        store
            .list_all_by_status_global(TaskStatus::InReview)
            .await?,
    );
    print!("\n{}", hosting(&entries, &running, Utc::now()));
    Ok(())
}

/**
 * What each node hosts and runs, from the registry. A project only one node hosts has no failover,
 * so it is marked with `*`. A running task shows as `repo#id status`
 **/
fn hosting(entries: &[Entry], running: &[Task], now: DateTime<Utc>) -> String {
    let hosts = registry::hosts_by_project(entries);
    let mut by_node: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
    for task in running {
        if let Some(node) = task.owner_node.as_deref() {
            let id = task
                .external_id
                .clone()
                .unwrap_or_else(|| format!("internal:{}", task.id));
            by_node.entry(node).or_default().insert(format!(
                "{}#{id} {}",
                task.repo,
                task.status.as_str()
            ));
        }
    }

    let mut out = format!("{:<20} {:<8} {:<8} PROJECTS\n", "NODE", "STATE", "RUNNING");
    for e in entries {
        let state = if e.witness {
            "witness"
        } else if e.online_at(now) {
            "online"
        } else {
            "offline"
        };
        let tasks = by_node.get(e.node.as_str());
        let slots = tasks.map_or(0, BTreeSet::len);
        let projects: Vec<String> = e
            .projects
            .iter()
            .map(|p| {
                let only = hosts.get(p).is_some_and(|h| h.len() == 1);
                if only { format!("{p}*") } else { p.clone() }
            })
            .collect();
        let _ = writeln!(
            out,
            "{:<20} {state:<8} {slots:<8} {}",
            e.node,
            projects.join(", ")
        );
        for task in tasks.into_iter().flatten() {
            let _ = writeln!(out, "  {task}");
        }
    }

    if hosts.values().any(|h| h.len() == 1) {
        out.push_str("* hosted on one node only, no failover\n");
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::TaskStore;

    fn entry(node: &str, projects: &[&str], seen: DateTime<Utc>) -> Entry {
        Entry {
            node: node.into(),
            projects: projects.iter().map(ToString::to_string).collect(),
            agents: vec!["claude".into()],
            max_parallel: 2,
            version: None,
            witness: false,
            seen: seen.to_rfc3339(),
        }
    }

    #[tokio::test]
    async fn marks_projects_one_node_hosts_and_lists_running_tasks() {
        let now = Utc::now();
        let entries = [
            entry("a", &["o/shared", "o/only-a"], now),
            entry("b", &["o/shared"], now - chrono::Duration::minutes(10)),
        ];
        let store = TaskStore::open_memory().await.unwrap();
        let id = store
            .create_internal("o/shared", "t", "", "manual", "", None)
            .await
            .unwrap();
        store
            .update_status_and_fields(
                id,
                TaskStatus::InProgress,
                &[("owner_node", serde_json::json!("a"))],
            )
            .await
            .unwrap();
        let task = store.get(id).await.unwrap();

        let out = hosting(&entries, &[task], now);
        assert!(out.contains("o/shared, o/only-a*"), "{out}");
        assert!(
            out.contains(&format!("  o/shared#internal:{id} in_progress")),
            "{out}"
        );
        assert!(out.contains("online   1 "), "{out}");
        assert!(out.contains("offline  0 "), "{out}");
        assert!(out.contains("* hosted on one node only"), "{out}");
    }
}