supercode-cli 0.4.20

supercode — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
//! Process-level proof that a resumed Claude session CARRIES its runtime work
//! and fires none of it: an overdue wakeup and a pending queue both sit inert
//! while the interactive CLI is idle, the source transcript is untouched, and
//! the run says so on its way in.
//!
//! The listener below is the instrument: the CLI is pointed at it as its
//! provider base URL and never calls it. A connection queued in its backlog
//! would be a fired prompt, so `accept()` returning `WouldBlock` after the
//! child exits is the measurement.

use std::fs;
use std::io::ErrorKind;
use std::net::TcpListener;
use std::path::PathBuf;
use std::process::{Command, Output, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_supercode")
}

fn temp_home(label: &str) -> PathBuf {
    let nonce = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let home = std::env::temp_dir().join(format!(
        "supercode-claude-runtime-resume-{label}-{}-{nonce}",
        std::process::id(),
    ));
    fs::create_dir_all(&home).unwrap();
    home
}

fn write_lines(path: &PathBuf, lines: &[serde_json::Value]) {
    let text = lines
        .iter()
        .map(serde_json::Value::to_string)
        .collect::<Vec<_>>()
        .join("\n")
        + "\n";
    fs::write(path, text).unwrap();
}

/// A wakeup whose due instant passed years ago: the strongest case for a
/// scheduler to fire immediately, and therefore the case worth measuring.
fn write_overdue_wakeup(path: &PathBuf) {
    write_lines(
        path,
        &[
            serde_json::json!({
                "type": "user",
                "sessionId": "runtime-resume",
                "cwd": "/tmp",
                "timestamp": "2020-01-01T00:00:00Z",
                "message": {"role": "user", "content": "initial context"}
            }),
            serde_json::json!({
                "type": "assistant",
                "timestamp": "2020-01-01T00:00:01Z",
                "message": {"role": "assistant", "content": [{
                    "type": "tool_use",
                    "id": "wake-overdue",
                    "name": "ScheduleWakeup",
                    "input": {
                        "delaySeconds": 1,
                        "reason": "acceptance wakeup",
                        "prompt": "RUNTIME_WAKEUP_MARKER"
                    }
                }]}
            }),
            serde_json::json!({
                "type": "user",
                "timestamp": "2020-01-01T00:00:02Z",
                "message": {"role": "user", "content": [{
                    "type": "tool_result",
                    "tool_use_id": "wake-overdue",
                    "content": "Next wakeup scheduled for 00:00:02 (in 1s)."
                }]}
            }),
        ],
    );
}

fn write_active_cron(path: &PathBuf) {
    write_lines(
        path,
        &[
            serde_json::json!({
                "type": "user",
                "sessionId": "runtime-cron-resume",
                "cwd": "/tmp",
                "timestamp": "2020-01-01T00:00:00Z",
                "message": {"role": "user", "content": "initial context"}
            }),
            serde_json::json!({
                "type": "assistant",
                "timestamp": "2020-01-01T00:00:01Z",
                "message": {"role": "assistant", "content": [{
                    "type": "tool_use",
                    "id": "cron-every-minute",
                    "name": "CronCreate",
                    "input": {
                        "cron": "* * * * *",
                        "recurring": true,
                        "prompt": "RUNTIME_CRON_MARKER"
                    }
                }]}
            }),
            serde_json::json!({
                "type": "user",
                "timestamp": "2020-01-01T00:00:02Z",
                "message": {"role": "user", "content": [{
                    "type": "tool_result",
                    "tool_use_id": "cron-every-minute",
                    "content": "Scheduled recurring job every-minute (* * * * *). Session-only."
                }]}
            }),
        ],
    );
}

fn write_pending_queue(path: &PathBuf) {
    write_lines(
        path,
        &[
            serde_json::json!({
                "type": "user",
                "sessionId": "runtime-queue-resume",
                "cwd": "/tmp",
                "timestamp": "2020-01-01T00:00:00Z",
                "message": {"role": "user", "content": "initial context"}
            }),
            serde_json::json!({
                "type": "queue-operation",
                "operation": "enqueue",
                "timestamp": "2020-01-01T00:00:01Z",
                "content": "RUNTIME_QUEUE_MARKER"
            }),
        ],
    );
}

/// Resume `source` with stdin closed immediately, against a listener that
/// accepts nothing. Returns the run's output and whether any connection
/// reached the provider port.
fn resume_idle(home: &PathBuf, source: &PathBuf) -> (Output, bool) {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();
    listener.set_nonblocking(true).unwrap();

    let child = Command::new(bin())
        .env("HOME", home)
        .env("SUPERCODE_HOME", home.join("supercode-home"))
        .env_remove("OPENROUTER_API_KEY")
        .args([
            "--api-key",
            "x",
            "--base-url",
            &format!("http://{addr}"),
            "--max-iterations",
            "1",
            "resume",
            source.to_str().unwrap(),
        ])
        // Closed stdin: the REPL has no line to read and no turn to take, so
        // any provider request would be one this process decided to make.
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    let output = child.wait_with_output().unwrap();
    // A connection attempt is queued in the backlog whether or not anyone
    // called `accept`, so this is the honest reading.
    let contacted = match listener.accept() {
        Ok(_) => true,
        Err(error) if error.kind() == ErrorKind::WouldBlock => false,
        Err(error) => panic!("unexpected accept error: {error}"),
    };
    (output, contacted)
}

#[test]
fn an_overdue_wakeup_is_carried_paused_and_never_fires() {
    let home = temp_home("wakeup");
    let source = home.join("session.jsonl");
    write_overdue_wakeup(&source);
    let before = fs::read(&source).unwrap();

    let (output, contacted) = resume_idle(&home, &source);
    assert!(output.status.success(), "{:?}", output.status);
    assert!(
        !contacted,
        "an overdue wakeup must not issue a provider request"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("carried and PAUSED"), "{stderr}");
    assert!(stderr.contains("1 scheduled wakeup(s)"), "{stderr}");
    assert!(
        stderr.contains("None of them will execute here"),
        "{stderr}"
    );
    // The one door that does run them is named where the refusal is stated.
    assert!(
        stderr.contains("orchestrator import --from claude-session"),
        "{stderr}"
    );
    assert_eq!(fs::read(&source).unwrap(), before, "source stays read-only");
    fs::remove_dir_all(home).ok();
}

#[test]
fn an_active_cron_is_carried_paused_and_never_fires() {
    let home = temp_home("cron");
    let source = home.join("cron-session.jsonl");
    write_active_cron(&source);
    let before = fs::read(&source).unwrap();

    let (output, contacted) = resume_idle(&home, &source);
    assert!(output.status.success(), "{:?}", output.status);
    assert!(!contacted, "a due cron must not issue a provider request");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("carried and PAUSED"), "{stderr}");
    assert!(stderr.contains("1 cron job(s)"), "{stderr}");
    assert_eq!(fs::read(&source).unwrap(), before, "source stays read-only");
    fs::remove_dir_all(home).ok();
}

#[test]
fn a_pending_queue_is_carried_paused_and_never_replays() {
    let home = temp_home("queue");
    let source = home.join("queue-session.jsonl");
    write_pending_queue(&source);
    let before = fs::read(&source).unwrap();

    let (output, contacted) = resume_idle(&home, &source);
    assert!(output.status.success(), "{:?}", output.status);
    assert!(
        !contacted,
        "a pending queue must not be replayed into a provider request"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("carried and PAUSED"), "{stderr}");
    assert!(stderr.contains("1 queued prompt(s)"), "{stderr}");
    assert_eq!(fs::read(&source).unwrap(), before, "source stays read-only");
    fs::remove_dir_all(home).ok();
}