apoc 0.9.1

Agentic process control for LLMs
Documentation
use std::collections::BTreeSet;
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)
            .args(["--purpose", "Running the execution parent filter fixture."])
            .env("APOC_HOME", self.home.path())
            .env("APOC_RUNTIME_DIR", self.runtime.path())
            .env("APOC_VIEW", "full")
            .output()
            .unwrap()
    }

    fn json(&self, args: &[&str]) -> Value {
        let output = self.run(args);
        assert!(
            output.status.success(),
            "command failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        serde_json::from_slice(&output.stdout).unwrap()
    }
}

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

#[test]
fn execution_list_filters_direct_children_by_parent_in_cli_and_code_mode() {
    let apoc = Fixture::new();
    let outer = apoc.json(&[
        "code",
        "run",
        r#"
            const first = await apoc.execution_command({
                executable: "/usr/bin/printf",
                arg: ["first"],
                idempotency_key: "parent-filter-direct-first",
                name: "parent-filter-direct-first",
                purpose: "Creating the first direct child for parent filtering."
            });
            const second = await apoc.execution_command({
                executable: "/usr/bin/printf",
                arg: ["second"],
                idempotency_key: "parent-filter-direct-second",
                name: "parent-filter-direct-second",
                purpose: "Creating the second direct child for parent filtering."
            });
            const grandchild = await apoc.execution_command({
                executable: "/usr/bin/printf",
                arg: ["grandchild"],
                idempotency_key: "parent-filter-grandchild",
                parent: first.execution.id,
                name: "parent-filter-grandchild",
                purpose: "Creating a nested child excluded by parent filtering."
            });
            return {
                direct_children: [first, second].map(({ execution }) => ({
                    id: execution.id,
                    status: execution.status,
                    parent_id: execution.parent_id
                })),
                grandchild: {
                    id: grandchild.execution.id,
                    status: grandchild.execution.status,
                    parent_id: grandchild.execution.parent_id
                }
            };
        "#,
        "--idempotency-key",
        "execution-parent-code-run",
        "--format",
        "json",
    ]);
    assert_eq!(outer["status"], "completed", "{outer:#}");
    let outer_id = outer["id"].as_str().unwrap().to_string();
    let expected_children = expected_child_set(&outer);
    assert_eq!(expected_children.len(), 2, "{outer:#}");
    assert!(
        expected_children
            .iter()
            .all(|(_, status, parent_id)| status == "completed"
                && parent_id.as_deref() == Some(outer_id.as_str())),
        "{expected_children:#?}"
    );
    assert_ne!(
        outer["result"]["grandchild"]["parent_id"].as_str(),
        Some(outer_id.as_str()),
        "{outer:#}"
    );

    let cli_output = apoc.run(&[
        "execution",
        "list",
        "--parent",
        &outer_id,
        "--format",
        "json",
    ]);
    assert!(
        cli_output.status.success(),
        "execution list --parent failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&cli_output.stdout),
        String::from_utf8_lossy(&cli_output.stderr)
    );
    let cli_page: Value = serde_json::from_slice(&cli_output.stdout).unwrap();
    assert_eq!(
        compact_child_set(&cli_page),
        expected_children,
        "{cli_page:#}"
    );

    let first_page = apoc.json(&[
        "execution",
        "list",
        "--parent",
        &outer_id,
        "--status",
        "completed",
        "--limit",
        "1",
        "--format",
        "json",
    ]);
    assert_eq!(first_page["executions"].as_array().unwrap().len(), 1);
    let cursor = first_page["next_cursor"].as_str().unwrap().to_string();
    let second_page = apoc.json(&[
        "execution",
        "list",
        "--parent",
        &outer_id,
        "--status",
        "completed",
        "--limit",
        "1",
        "--cursor",
        &cursor,
        "--format",
        "json",
    ]);
    assert_eq!(second_page["executions"].as_array().unwrap().len(), 1);
    assert_eq!(second_page["next_cursor"], Value::Null);
    let mut paged_children = compact_child_set(&first_page);
    paged_children.extend(compact_child_set(&second_page));
    assert_eq!(
        paged_children, expected_children,
        "{first_page:#}\n{second_page:#}"
    );

    let code = format!(
        r#"
            const page = await apoc.execution_list({{
                parent: {},
                status: "completed",
                limit: 10,
                purpose: "Recovering direct child execution summaries by outer Code Mode ID."
            }});
            return page.executions.map((execution) => ({{
                id: execution.id,
                status: execution.status,
                parent_id: execution.parent_id
            }})).sort((left, right) => left.id.localeCompare(right.id));
        "#,
        serde_json::to_string(&outer_id).unwrap()
    );
    let code_page = apoc.json(&[
        "code",
        "run",
        &code,
        "--idempotency-key",
        "execution-parent-page-code-run",
        "--format",
        "json",
    ]);
    assert_eq!(code_page["status"], "completed", "{code_page:#}");
    let code_children = code_page["result"]
        .as_array()
        .unwrap()
        .iter()
        .map(compact_child)
        .collect::<BTreeSet<_>>();
    assert_eq!(code_children, expected_children, "{code_page:#}");
}

fn expected_child_set(outer: &Value) -> BTreeSet<(String, String, Option<String>)> {
    outer["result"]["direct_children"]
        .as_array()
        .unwrap()
        .iter()
        .map(compact_child)
        .collect()
}

fn compact_child_set(page: &Value) -> BTreeSet<(String, String, Option<String>)> {
    page["executions"]
        .as_array()
        .unwrap()
        .iter()
        .map(compact_child)
        .collect()
}

fn compact_child(execution: &Value) -> (String, String, Option<String>) {
    (
        execution["id"].as_str().unwrap().to_string(),
        execution["status"].as_str().unwrap().to_string(),
        execution["parent_id"].as_str().map(ToString::to_string),
    )
}