apoc 0.9.1

Agentic process control for LLMs
Documentation
//! apoc embedded in another process, with no daemon and no socket.
//!
//! One test, run in order, because it points the process environment at a
//! throwaway home first: any call that fell back to the daemon would start one
//! there, and the test asserts that nothing did.

use std::process::Command;

use apoc::{Apoc, CoreConfig};
use serde_json::{Value, json};
use tempfile::tempdir;

fn run_program(core: &Apoc, code: &str) -> Value {
    core.call(
        "code.run",
        json!({
            "code": code,
            "timeout_ms": 60_000,
            "purpose": "Exercising an embedded apoc core.",
        }),
    )
    .unwrap_or_else(|error| panic!("code.run failed: {error}"))
}

#[test]
fn an_embedded_core_owns_its_root_and_runs_without_a_daemon() {
    // Anything that reached for a daemon would find this home, not the
    // developer's real one, and leave evidence in it.
    let fallback_home = tempdir().unwrap();
    let fallback_runtime = tempdir().unwrap();
    let fallback_data = tempdir().unwrap();
    unsafe {
        std::env::set_var("APOC_HOME", fallback_home.path());
        std::env::set_var("XDG_DATA_HOME", fallback_data.path());
        std::env::remove_var("APOC_ERROR_TELEMETRY");
        std::env::set_var("APOC_RUNTIME_DIR", fallback_runtime.path());
        std::env::set_var("APOC_MCP_ROOT", fallback_home.path());
    }

    let root = tempdir().unwrap();
    let core = Apoc::open(root.path()).unwrap();

    // 1. A program runs a command through apoc, all in this process.
    let state = run_program(
        &core,
        r#"
        const ran = await apoc.execution_command({
          executable: "/bin/echo", arg: ["embedded"],
          expect_stdout_regex: "embedded",
          idempotency_key: "embedded-echo",
          purpose: "Running a command from an embedded core." });
        return ran.outcome;
        "#,
    );
    assert_eq!(state["result"], "passed", "{state:#}");
    assert!(
        !root.path().join("runtime").join("apoc.sock").exists(),
        "an embedded core must not bind a socket"
    );
    assert!(
        std::fs::read_dir(fallback_runtime.path())
            .unwrap()
            .next()
            .is_none(),
        "nothing may have fallen back to a daemon"
    );

    // RPC diagnostics belong to this embedded core, not the process fallback.
    let error = core.call("execution.get", json!({"id":"missing-embedded-execution"}));
    assert!(error.is_err());
    let text = std::fs::read_to_string(root.path().join("telemetry/errors.jsonl"))
        .expect("embedded RPC failure must leave local telemetry");
    let events = text
        .lines()
        .map(|line| serde_json::from_str::<Value>(line).unwrap())
        .collect::<Vec<_>>();
    assert!(
        events
            .iter()
            .any(|event| event["kind"] == "rpc" && event["operation"] == "execution.get")
    );
    assert!(!fallback_home.path().join("telemetry/errors.jsonl").exists());

    // 2. A second owner of the same root is refused, not admitted.
    let second = Apoc::open(root.path());
    assert!(
        second
            .as_ref()
            .is_err_and(|error| error.starts_with("STATE_ROOT_BUSY")),
        "a second core on one root must be refused: {:?}",
        second.err()
    );

    // 3. Dropping the owner releases the root.
    drop(core);
    let reopened = Apoc::open(root.path()).unwrap();
    let state = run_program(&reopened, "return 41 + 1;");
    assert_eq!(state["result"], 42, "{state:#}");
    drop(reopened);

    // 4. Two cores on different roots, open at once in one process, each keep
    //    their own MCP namespace ledger rather than the first one's.
    let first_root = tempdir().unwrap();
    let second_root = tempdir().unwrap();
    let first = Apoc::open(first_root.path()).unwrap();
    let second = Apoc::open(second_root.path()).unwrap();
    for core in [&first, &second] {
        assert_eq!(run_program(core, "return 1;")["result"], 1);
    }
    for root in [&first_root, &second_root] {
        assert!(
            root.path().join("mcp").join("registry.json").exists(),
            "each core must keep its own namespace ledger under {}",
            root.path().display()
        );
    }
    drop((first, second));

    // 5. The blocking API refuses to run inside an async runtime.
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();
    let inside = runtime.block_on(async { Apoc::open(tempdir().unwrap().path()).err() });
    assert!(
        inside.is_some_and(|error| error.starts_with("BLOCKING_FROM_ASYNC")),
        "blocking from async must be an error, not a deadlock"
    );

    // 6. The user's daemon and an embedded core cannot both own one root.
    let daemon_home = tempdir().unwrap();
    let daemon_runtime = tempdir().unwrap();
    let apoc = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_apoc"))
            .args(args)
            .env("APOC_HOME", daemon_home.path())
            .env("APOC_RUNTIME_DIR", daemon_runtime.path())
            .output()
            .unwrap()
    };
    let started = apoc(&[
        "execution",
        "list",
        "--purpose",
        "Starting a daemon that owns this root.",
        "--format",
        "json",
    ]);
    assert!(started.status.success(), "{started:?}");
    let contended = Apoc::open_with(CoreConfig::new(daemon_home.path()));
    let _ = apoc(&[
        "daemon",
        "stop",
        "--purpose",
        "Stopping the daemon that owned this root.",
        "--idempotency-key",
        "embed-contract-daemon-stop",
    ]);
    assert!(
        contended
            .as_ref()
            .is_err_and(|error| error.starts_with("STATE_ROOT_BUSY")),
        "an embedded core must not open a root the daemon owns: {:?}",
        contended.err()
    );
}