apoc 0.9.1

Agentic process control for LLMs
Documentation
use std::process::{Command, Output};

use serde_json::Value;
use tempfile::{TempDir, tempdir};

struct Fixture {
    binary: String,
    home: TempDir,
    runtime: TempDir,
    data: TempDir,
}

impl Fixture {
    fn new() -> Self {
        Self {
            binary: env!("CARGO_BIN_EXE_apoc").to_string(),
            home: tempdir().unwrap(),
            runtime: tempdir().unwrap(),
            data: tempdir().unwrap(),
        }
    }

    fn run(&self, args: &[&str]) -> Output {
        Command::new(&self.binary)
            .current_dir(self.home.path())
            .args(args)
            .args(["--purpose", "Running the code launch failure fixture."])
            .env("APOC_HOME", self.home.path())
            .env("APOC_RUNTIME_DIR", self.runtime.path())
            .env("XDG_DATA_HOME", self.data.path())
            .env("APOC_MCP_ROOT", self.home.path().join("empty-mcp"))
            .env("APOC_VIEW", "full")
            .output()
            .unwrap()
    }
    fn identity(&self) -> (Value, Value) {
        let output = self.run(&["daemon", "status", "--format", "json"]);
        assert!(output.status.success(), "{output:?}");
        let state: Value = serde_json::from_slice(&output.stdout).unwrap();
        assert!(state["pid"].as_u64().is_some(), "{state:#}");
        assert!(state["started_at"].as_u64().is_some(), "{state:#}");
        (state["pid"].clone(), state["started_at"].clone())
    }

    fn assert_program_error(&self, code: &str, expected: &str, key: &str) {
        let output = self.run(&[
            "code",
            "run",
            code,
            "--idempotency-key",
            key,
            "--format",
            "json",
        ]);
        assert!(
            !output.status.success(),
            "invalid program must fail: {output:?}"
        );
        let state: Value = serde_json::from_slice(&output.stdout).unwrap();
        assert_eq!(state["status"], "error", "{state:#}");
        let id = state["id"]
            .as_str()
            .expect("error must retain execution identity");
        assert!(
            state["error"]
                .as_str()
                .is_some_and(|error| error.contains(expected)),
            "{state:#}"
        );
        let durable = self.run(&["code", "get", id, "--format", "json"]);
        assert!(durable.status.success(), "{durable:?}");
        let record: Value = serde_json::from_slice(&durable.stdout).unwrap();
        assert_eq!(record["error"], state["error"], "{record:#}");
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = self.run(&[
            "daemon",
            "stop",
            "--idempotency-key",
            "code-launch-fixture-stop",
            "--format",
            "json",
        ]);
    }
}

#[test]
fn code_mode_returns_launch_failures_without_replaying_them() {
    let apoc = Fixture::new();
    let code = r#"
        const executions = await Promise.all([
            apoc.execution_command({
                executable: "/usr/bin/true",
                purpose: "Running the valid command before a launch failure.",
                idempotency_key: "code-launch-valid-before",
                name: "valid-before-launch-failure"
            }),
            apoc.execution_command({
                executable: "/definitely/missing-apoc-executable",
                purpose: "Checking a missing executable launch failure.",
                idempotency_key: "code-launch-missing",
                name: "missing-launch-failure"
            }),
            apoc.execution_command({
                executable: "/usr/bin/printf",
                purpose: "Running the valid command after a launch failure.",
                idempotency_key: "code-launch-valid-after",
                arg: ["ok"],
                name: "valid-after-launch-failure"
            })
        ]);
        return executions.map(({ execution: { id, status, result } }) => ({ id, status, result }));
    "#;
    let output = apoc.run(&[
        "code",
        "run",
        code,
        "--idempotency-key",
        "code-launch-failure-run",
        "--format",
        "json",
    ]);
    assert!(
        output.status.success(),
        "code run failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let state: Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(state["status"], "completed", "{state:#}");
    assert_eq!(state["result"][0]["status"], "completed", "{state:#}");
    assert_eq!(state["result"][1]["status"], "failed", "{state:#}");
    assert_eq!(
        state["result"][1]["result"]["error_code"], "EXECUTION_START_FAILED",
        "{state:#}"
    );
    assert_eq!(state["result"][2]["status"], "completed", "{state:#}");

    let output = apoc.run(&["execution", "list", "--format", "json"]);
    assert!(
        output.status.success(),
        "execution list failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let executions: Value = serde_json::from_slice(&output.stdout).unwrap();
    let missing = executions
        .get("executions")
        .and_then(Value::as_array)
        .unwrap()
        .iter()
        .filter(|execution| execution["name"] == "missing-launch-failure")
        .collect::<Vec<_>>();
    assert_eq!(missing.len(), 1, "{executions:#}");
    assert_eq!(missing[0]["status"], "failed", "{executions:#}");
    assert_eq!(missing[0]["parent_id"], state["id"], "{executions:#}");
}

#[test]
fn code_mode_reports_syntax_errors_with_source_locations() {
    let apoc = Fixture::new();
    let output = apoc.run(&[
        "code",
        "run",
        "const value = \"first\nsecond\"; return value;",
        "--idempotency-key",
        "code-syntax-diagnostic",
        "--format",
        "json",
    ]);
    assert!(!output.status.success(), "invalid syntax must fail");
    let state: Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(state["status"], "error", "{state:#}");
    let error = state["error"].as_str().expect("syntax diagnostic");
    assert!(error.contains("SyntaxError"), "{error}");
    assert!(error.contains("unexpected end of string"), "{error}");
    assert!(error.contains("eval_script:"), "{error}");
    assert!(
        state["log"].as_array().is_none_or(Vec::is_empty),
        "{state:#}"
    );
}

#[test]
fn code_mode_invalid_values_and_recursion_preserve_daemon_identity() {
    let apoc = Fixture::new();
    let initial = apoc.run(&[
        "code",
        "run",
        "return 42;",
        "--idempotency-key",
        "survival-initial",
        "--format",
        "json",
    ]);
    assert!(initial.status.success(), "{initial:?}");
    let original_identity = apoc.identity();
    for (code, expected, key) in [
        (
            "const value = {}; value.self = value; return value;",
            "CODE_VALUE_CYCLE",
            "survival-object-cycle",
        ),
        (
            "const value = []; value.push(value); return value;",
            "CODE_VALUE_CYCLE",
            "survival-array-cycle",
        ),
        (
            "function recurse() { return recurse() + 1; } return recurse();",
            "Maximum call stack size exceeded",
            "survival-recursion",
        ),
    ] {
        apoc.assert_program_error(code, expected, key);
        assert_eq!(
            apoc.identity(),
            original_identity,
            "daemon must survive without replacement"
        );
    }
    let output = apoc.run(&[
        "code",
        "run",
        "const shared = {answer: 42}; return {left: shared, right: shared};",
        "--idempotency-key",
        "survival-shared-reference",
        "--format",
        "json",
    ]);
    assert!(output.status.success(), "{output:?}");
    let state: Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(
        state["result"],
        serde_json::json!({"left": {"answer": 42}, "right": {"answer": 42}})
    );
    assert_eq!(apoc.identity(), original_identity);
}

#[test]
fn code_mode_inherits_context_and_preserves_explicit_overrides() {
    let apoc = Fixture::new();
    let source = r#"
        const inherited = await apoc.execution_command({
            executable: "/usr/bin/true", expect_exit_code: [0], verbosity: "trace"
        });
        const explicit = await apoc.execution_command({
            executable: "/usr/bin/true", expect_exit_code: [0], verbosity: "trace",
            purpose: "Explicit child purpose", idempotency_key: "explicit-child-key"
        });
        return {inherited: inherited.execution.spec, explicit: explicit.execution.spec};
    "#;
    let output = apoc.run(&[
        "code",
        "run",
        source,
        "--idempotency-key",
        "context-defaults",
        "--format",
        "json",
    ]);
    assert!(output.status.success(), "{output:?}");
    let state: Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(state["status"], "completed", "{state:#}");
    assert_eq!(
        state["result"]["inherited"]["purpose"], "Running the code launch failure fixture.",
        "{state:#}"
    );
    assert!(
        state["result"]["inherited"]["idempotency_key"]
            .as_str()
            .is_some_and(|key| !key.is_empty()),
        "{state:#}"
    );
    assert_eq!(
        state["result"]["explicit"]["purpose"], "Explicit child purpose",
        "{state:#}"
    );
    assert_eq!(
        state["result"]["explicit"]["idempotency_key"], "explicit-child-key",
        "{state:#}"
    );
}

#[test]
fn code_mode_context_replay_and_conflict_launch_one_child() {
    let apoc = Fixture::new();
    let counter = apoc.home.path().join("counter");
    let script = format!(
        "from pathlib import Path; p=Path({:?}); p.write_text(str(int(p.read_text())+1) if p.exists() else '1')",
        counter
    );
    let source = format!(
        "return await apoc.execution_command({{executable: '/usr/bin/python3', arg: ['-c', {}], expect_exit_code: [0]}});",
        serde_json::to_string(&script).unwrap()
    );
    let run = |code: &str| {
        apoc.run(&[
            "code",
            "run",
            code,
            "--idempotency-key",
            "context-replay",
            "--format",
            "json",
        ])
    };
    let first = run(&source);
    assert!(first.status.success(), "{first:?}");
    let second = run(&source);
    assert!(second.status.success(), "{second:?}");
    let a: Value = serde_json::from_slice(&first.stdout).unwrap();
    let b: Value = serde_json::from_slice(&second.stdout).unwrap();
    assert_eq!(a["result"]["id"], b["result"]["id"], "{a:#} {b:#}");
    assert_eq!(std::fs::read_to_string(&counter).unwrap(), "1");
    let conflict = run(
        "return await apoc.execution_command({executable: '/usr/bin/false', expect_exit_code: [0]});",
    );
    assert!(!conflict.status.success(), "{conflict:?}");
    let result: Value = serde_json::from_slice(&conflict.stdout).unwrap();
    assert!(
        result.to_string().contains("IDEMPOTENCY_CONFLICT"),
        "{result:#}"
    );
    assert_eq!(std::fs::read_to_string(&counter).unwrap(), "1");
}

#[test]
fn code_mode_executes_source_file_without_shell_escaping() {
    let apoc = Fixture::new();
    let file = apoc.home.path().join("program.js");
    std::fs::write(&file, "return \"quotes: ' and double\";").unwrap();
    let input = "@program.js".to_string();
    let output = apoc.run(&[
        "code",
        "run",
        &input,
        "--idempotency-key",
        "source-file",
        "--format",
        "json",
    ]);
    assert!(output.status.success(), "{output:?}");
    let state: Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(state["result"], "quotes: ' and double", "{state:#}");
}

#[test]
fn code_mode_rejects_missing_source_file_before_execution() {
    let apoc = Fixture::new();
    let input = format!("@{}", apoc.home.path().join("absent.js").display());
    let output = apoc.run(&[
        "code",
        "run",
        &input,
        "--idempotency-key",
        "source-missing",
        "--format",
        "json",
    ]);
    assert!(!output.status.success(), "{output:?}");
    let state: Value = serde_json::from_slice(&output.stdout).unwrap();
    assert!(
        state.to_string().contains("CODE_SOURCE_READ_FAILED"),
        "{state:#}"
    );
    assert!(state.get("id").is_none(), "{state:#}");
}