supercode-cli 0.4.18

supercode — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
//! ORC-10 CLI acceptance: the operator's access verbs, and the lease the
//! daemon owns.
//!
//! `supercode orchestrator pair|access …` never encodes the orchestrator
//! folder itself — it spawns the `supercode-orchestrator` package's own writer
//! (`sdk/orchestrator/bin/orchestrator.mjs access …`). These tests drive the
//! real binary against a temporary home and read the YAML that writer left, so
//! a second encoder appearing in Rust would fail them.
//!
//! Nothing here installs a service unit: registering a launchd/systemd label is
//! machine-wide state, and its receipt is `docs/interop/research/`.

use std::path::{Path, PathBuf};
use std::process::{Command, Output};

fn bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_supercode"))
}

fn temp_root(label: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "orc10-{label}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("config.yaml"),
        "worker:\n  harness: hermes\naccess:\n  pairing_ttl_minutes: 20\nplatforms:\n  loopback:\n    enabled: true\n",
    )
    .unwrap();
    std::fs::write(dir.join("access.yaml"), "policy:\n  loopback: allowlist\n").unwrap();
    dir
}

fn run(root: &Path, args: &[&str]) -> Output {
    Command::new(bin())
        .env("SUPERCODE_ORCHESTRATOR_HOME", root)
        .args(args)
        .arg("--root")
        .arg(root)
        .output()
        .expect("supercode binary runs")
}

fn json_of(output: &Output) -> serde_json::Value {
    assert!(
        output.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).expect("stdout is JSON")
}

fn access_yaml(root: &Path) -> String {
    std::fs::read_to_string(root.join("access.yaml")).unwrap()
}

/// A `node` on PATH; the operator verbs and the daemon both need one.
fn node() -> Option<PathBuf> {
    std::env::split_paths(&std::env::var_os("PATH")?)
        .map(|dir| dir.join("node"))
        .find(|candidate| candidate.is_file())
}

#[test]
fn access_verbs_edit_the_allowlist_and_the_admin_tier_through_the_packages_writer() {
    let Some(_node) = node() else {
        eprintln!("skipped: no `node` on PATH");
        return;
    };
    let root = temp_root("access");

    let allowed = json_of(&run(
        &root,
        &[
            "orchestrator",
            "access",
            "allow",
            "loopback",
            "u1",
            "--json",
        ],
    ));
    assert_eq!(allowed["allowlist"]["loopback"][0], "u1");
    assert_eq!(allowed["default_policy"], "allowlist");
    assert_eq!(allowed["pairing_ttl_minutes"], 20);
    assert!(access_yaml(&root).contains("u1"));

    let admin = json_of(&run(
        &root,
        &[
            "orchestrator",
            "access",
            "admin",
            "add",
            "loopback",
            "u1",
            "--json",
        ],
    ));
    assert_eq!(admin["admins"]["loopback"][0], "u1");

    let demoted = json_of(&run(
        &root,
        &[
            "orchestrator",
            "access",
            "admin",
            "remove",
            "loopback",
            "u1",
            "--json",
        ],
    ));
    assert!(demoted["admins"].get("loopback").is_none(), "{demoted:#}");

    let revoked = json_of(&run(
        &root,
        &[
            "orchestrator",
            "access",
            "revoke",
            "loopback",
            "u1",
            "--json",
        ],
    ));
    assert!(
        revoked["allowlist"].get("loopback").is_none(),
        "{revoked:#}"
    );
    assert!(!access_yaml(&root).contains("u1"));

    std::fs::remove_dir_all(&root).ok();
}

#[test]
fn pair_list_shows_the_code_its_policy_and_its_expiry_and_approve_admits_the_sender() {
    let Some(_node) = node() else {
        eprintln!("skipped: no `node` on PATH");
        return;
    };
    let root = temp_root("pair");
    // A code the channel handed out a moment ago, as the reducer writes it.
    let issued = "2126-01-01T00:00:00.000Z"; // far future: unambiguously unexpired
    std::fs::write(
        root.join("access.yaml"),
        format!("policy:\n  loopback: allowlist\npending_pairings:\n  ABC123:\n    platform: loopback\n    user_id: \"9\"\n    issued_at: \"{issued}\"\n"),
    )
    .unwrap();

    let listed = json_of(&run(&root, &["orchestrator", "pair", "list", "--json"]));
    let row = &listed["pending"][0];
    assert_eq!(row["code"], "ABC123");
    assert_eq!(row["user_id"], "9");
    // the platform's effective policy is on the row, default included
    assert_eq!(row["policy"], "allowlist");
    assert_eq!(row["expired"], false);
    assert_eq!(row["expires_at"], "2126-01-01T00:20:00.000Z");

    let approved = json_of(&run(
        &root,
        &["orchestrator", "pair", "approve", "ABC123", "--json"],
    ));
    assert_eq!(approved["allowlist"]["loopback"][0], "9");
    assert_eq!(approved["pending"].as_array().unwrap().len(), 0);
    assert!(access_yaml(&root).contains("\"9\""));

    // an unknown code is refused by name, never a silent no-op
    let refused = run(
        &root,
        &["orchestrator", "pair", "approve", "ABC123", "--json"],
    );
    assert!(!refused.status.success());
    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert!(stderr.contains("no pending pairing ABC123"), "{stderr}");

    std::fs::remove_dir_all(&root).ok();
}

#[test]
fn an_expired_pairing_code_is_refused_and_dropped() {
    let Some(_node) = node() else {
        eprintln!("skipped: no `node` on PATH");
        return;
    };
    let root = temp_root("expired");
    std::fs::write(
        root.join("access.yaml"),
        "policy:\n  loopback: allowlist\npending_pairings:\n  OLD999:\n    platform: loopback\n    user_id: \"9\"\n    issued_at: \"2020-01-01T00:00:00.000Z\"\n",
    )
    .unwrap();

    let listed = json_of(&run(&root, &["orchestrator", "pair", "list", "--json"]));
    assert_eq!(listed["pending"][0]["expired"], true);

    let refused = run(
        &root,
        &["orchestrator", "pair", "approve", "OLD999", "--json"],
    );
    assert!(!refused.status.success());
    let stderr = String::from_utf8_lossy(&refused.stderr);
    assert!(stderr.contains("expired"), "{stderr}");

    // and the dead code is gone, so nobody can approve it later either
    let after = json_of(&run(&root, &["orchestrator", "pair", "list", "--json"]));
    assert_eq!(after["pending"].as_array().unwrap().len(), 0);
    assert!(after["allowlist"].get("loopback").is_none());

    std::fs::remove_dir_all(&root).ok();
}

#[test]
fn setup_without_a_flag_renders_the_unit_and_installs_nothing_and_status_reports_the_service() {
    let root = temp_root("setup");
    let rendered = json_of(&run(&root, &["orchestrator", "setup", "--json"]));
    assert_eq!(rendered["installed"], false);
    assert!(rendered["service"].is_null());
    let unit_path = PathBuf::from(rendered["unit"]["path"].as_str().unwrap());
    assert!(unit_path.starts_with(root.join("service")));
    assert!(std::fs::read_to_string(&unit_path)
        .unwrap()
        .contains("ai.volter.supercode.orchestrator"));

    // `status` answers the lease question and the service question separately:
    // this home has neither, and says so without inventing either.
    let status = json_of(&run(&root, &["orchestrator", "status", "--json"]));
    assert_eq!(status["state"], "down");
    assert!(status["lease"].is_null());
    assert_eq!(
        status["service"]["label"],
        "ai.volter.supercode.orchestrator"
    );
    assert!(
        ["launchd", "systemd", "none"].contains(&status["service"]["kind"].as_str().unwrap()),
        "{status:#}"
    );

    std::fs::remove_dir_all(&root).ok();
}

#[test]
fn the_daemon_owns_the_lease_and_stop_takes_it_down() {
    let Some(node) = node() else {
        eprintln!("skipped: no `node` on PATH");
        return;
    };
    let root = temp_root("lease");
    let mut child = Command::new(bin())
        .args(["orchestrator", "start", "--root"])
        .arg(&root)
        .arg("--node")
        .arg(&node)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .expect("supercode orchestrator start runs");

    // The daemon writes `<home>/orchestrator.lock` itself — this verb no longer
    // does — so the lease appearing at all is the daemon reporting for duty.
    let lock = root.join("orchestrator.lock");
    let mut lease = None;
    for _ in 0..200 {
        if let Ok(text) = std::fs::read_to_string(&lock) {
            lease = serde_json::from_str::<serde_json::Value>(&text).ok();
            if lease.is_some() {
                break;
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    let lease = lease.unwrap_or_else(|| panic!("no lease at {}", lock.display()));
    assert!(lease["pid"].as_u64().unwrap() > 0);

    let status = json_of(&run(&root, &["orchestrator", "status", "--json"]));
    assert_eq!(status["state"], "up");
    assert_eq!(status["lease"]["pid"], lease["pid"]);

    let stopped = json_of(&run(&root, &["orchestrator", "stop", "--json"]));
    assert_eq!(stopped["stopped"]["pid"], lease["pid"]);
    child.wait().ok();
    assert!(!lock.exists(), "a stopped daemon leaves no lease behind");

    std::fs::remove_dir_all(&root).ok();
}