apoc 0.7.4

Agentic process control for LLMs
Documentation
//! Nested Code Mode: a program invoking apoc, which runs another program, and so on.
//!
//! Composition is only worth the name if a program can reach apoc itself. The
//! hazard is re-entrancy: the outer program occupies a dispatch session while its
//! child opens another against the same daemon, so anything the outer pass holds
//! while dispatching becomes a deadlock the moment the child needs it.

use std::process::{Command, Output};

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

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

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

    fn run(&self, args: &[&str]) -> Output {
        Command::new(&self.binary)
            .args(args)
            .env("APOC_HOME", self.home.path())
            .env("APOC_RUNTIME_DIR", self.runtime.path())
            .output()
            .unwrap()
    }

    /// Runs one Code Mode program and returns its parsed execution state.
    fn code_run(&self, code: &str, key: &str) -> Value {
        let output = self.run(&[
            "code",
            "run",
            code,
            "--purpose",
            "Exercising nested Code Mode invocation.",
            "--idempotency-key",
            key,
            "--format",
            "json",
        ]);
        let stdout = String::from_utf8_lossy(&output.stdout);
        serde_json::from_str(&stdout).unwrap_or_else(|error| {
            panic!(
                "expected one JSON execution state, got {error}\nstdout: {stdout}\nstderr: {}",
                String::from_utf8_lossy(&output.stderr)
            )
        })
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = self.run(&[
            "daemon",
            "stop",
            "--purpose",
            "Stopping the nested Code Mode fixture daemon.",
            "--idempotency-key",
            "recursion-teardown",
        ]);
    }
}

/// A program that runs apoc, which runs a program, which runs apoc again.
///
/// Three levels, because two would not distinguish "nesting works" from "one
/// level of nesting is special-cased". The innermost value is carried back up
/// through both parents: asserting only that each child exited zero would pass
/// even if the innermost program never ran.
#[test]
fn code_mode_programs_nest_apoc_invocations_recursively() {
    let fixture = Fixture::new();
    let binary = serde_json::to_string(&fixture.binary).unwrap();

    // Depth 3 returns a token. Each parent runs its child, reads the child's
    // stdout, and hands the value further up, so the assertion at the top can
    // only hold if every level actually executed.
    let depth_three = serde_json::to_string("return \"INNERMOST-OK\"").unwrap();
    let depth_two = serde_json::to_string(&format!(
        r#"
        const run = await apoc.execution_command({{
          executable: {binary},
          arg: ["code", "run", {depth_three},
                "--purpose", "Innermost nested program.",
                "--idempotency-key", "depth-three",
                "--format", "json"],
          purpose: "Running the innermost nested program.",
          idempotency_key: "depth-two-spawn",
          expect_exit_code: [0]
        }});
        const logs = await apoc.execution_logs({{
          id: run.id, tail_bytes: 65536,
          purpose: "Reading the innermost program's output."
        }});
        return {{ depth: 2, outcome: run.outcome, inner: JSON.parse(logs.stdout).result }};
        "#
    ))
    .unwrap();

    let outer = format!(
        r#"
        const run = await apoc.execution_command({{
          executable: {binary},
          arg: ["code", "run", {depth_two},
                "--purpose", "Middle nested program.",
                "--idempotency-key", "depth-two",
                "--format", "json"],
          purpose: "Running the middle nested program.",
          idempotency_key: "outer-spawn",
          expect_exit_code: [0]
        }});
        const logs = await apoc.execution_logs({{
          id: run.id, tail_bytes: 65536,
          purpose: "Reading the middle program's output."
        }});
        return {{ depth: 1, outcome: run.outcome, middle: JSON.parse(logs.stdout).result }};
        "#
    );

    let state = fixture.code_run(&outer, "outer");

    assert_eq!(
        state.get("status").and_then(Value::as_str),
        Some("completed"),
        "three levels of nested apoc must complete: {state:#}"
    );
    let result = state.get("result").expect("a result");
    assert_eq!(result.get("depth").and_then(Value::as_i64), Some(1));

    let middle = result.get("middle").expect("the middle program's result");
    assert_eq!(
        middle.get("depth").and_then(Value::as_i64),
        Some(2),
        "the middle level must report itself: {result:#}"
    );
    assert_eq!(
        middle.get("inner").and_then(Value::as_str),
        Some("INNERMOST-OK"),
        "the innermost value must survive two levels of nesting: {result:#}"
    );
}