vpf-runner 0.4.0

The reference runner of the Verifiable Plan Format (VPF): runs a plan step by step and proves each step.
Documentation
//! Steps that wait for none of each other, and the items of a step, are done at the same time.

mod common;

use std::sync::Mutex;
use std::thread;
use std::time::Duration;

use vpf_runner::{AgentAnswer, AgentRequest, Outcome, Runner};

use common::{Scripted, no_agent, plan};

/// Waits until the files `names` are all in the folder, for at most five seconds, and fails when they are not.
fn meet(names: &str) -> String {
    let all: Vec<String> = names
        .split(' ')
        .map(|name| format!("[ -e {name} ]"))
        .collect();
    let all = all.join(" && ");
    format!("for i in $(seq 50); do {all} && break; sleep 0.1; done; {all}")
}

#[test]
fn steps_that_wait_for_none_of_each_other_run_at_the_same_time() {
    let folder = tempfile::tempdir().expect("a folder");
    let text = format!(
        r#"{{ "$schema": "vpf/1.1", "wish": "Met",
             "steps": [
               {{ "id": "a", "do": "A.", "by": "algorithm", "run": "touch a; {meet}" }},
               {{ "id": "b", "do": "B.", "by": "algorithm", "run": "touch b; {meet}", "after": [] }},
               {{ "id": "both", "do": "Both.", "by": "algorithm", "run": "echo met", "after": ["a", "b"] }}
             ] }}"#,
        meet = meet("a b")
    );
    let plan = plan(&text);
    let (agent, mut person) = (no_agent(), Scripted::default());
    let record = Runner::new(folder.path(), &agent, &mut person).run(&plan, "");

    assert_eq!(record.outcome, Outcome::Done, "{}", person.all());
    assert_eq!(record.steps[2].answer.as_deref(), Some("met"));
}

#[test]
fn the_items_of_a_step_are_done_at_the_same_time() {
    let folder = tempfile::tempdir().expect("a folder");
    let text = format!(
        r#"{{ "$schema": "vpf/1.1", "wish": "Met",
             "steps": [
               {{ "id": "names", "do": "Names.", "by": "algorithm", "run": "printf 'x\\ny\\nz\\n'" }},
               {{ "id": "each", "do": "Each.", "by": "algorithm", "run": "touch {{{{item}}}}; {meet}; echo {{{{item}}}}",
                 "for_each": "names" }}
             ] }}"#,
        meet = meet("x y z")
    );
    let plan = plan(&text);
    let (agent, mut person) = (no_agent(), Scripted::default());
    let record = Runner::new(folder.path(), &agent, &mut person).run(&plan, "");

    assert_eq!(record.outcome, Outcome::Done, "{}", person.all());
    assert_eq!(record.steps[1].answer.as_deref(), Some(r#"["x","y","z"]"#));
}

/// An agent that takes a while, and keeps how many of it worked at once at most.
struct Slow {
    now: Mutex<(usize, usize)>,
}

impl Slow {
    fn new() -> Self {
        Self {
            now: Mutex::new((0, 0)),
        }
    }

    fn most(&self) -> usize {
        self.now.lock().expect("the count").1
    }
}

impl vpf_runner::Agent for Slow {
    fn ask(&self, request: &AgentRequest<'_>) -> Result<AgentAnswer, String> {
        {
            let mut now = self.now.lock().expect("the count");
            now.0 += 1;
            now.1 = now.1.max(now.0);
        }
        thread::sleep(Duration::from_millis(300));
        self.now.lock().expect("the count").0 -= 1;
        let text = if request.prompt.contains("Answer PASS or FAIL") {
            "PASS"
        } else {
            "done"
        };
        Ok(AgentAnswer::new(text).with_cost(0.01))
    }
}

const THREE: &str = r#"{ "$schema": "vpf/1.1", "wish": "Three notes",
     "steps": [
       { "id": "one",   "do": "One.",   "by": "agent", "proof": { "by": "agent", "check": "It is done." } },
       { "id": "two",   "do": "Two.",   "by": "agent", "proof": { "by": "agent", "check": "It is done." }, "after": [] },
       { "id": "three", "do": "Three.", "by": "agent", "proof": { "by": "agent", "check": "It is done." }, "after": [] }
     ] }"#;

#[test]
fn agents_work_at_the_same_time() {
    let folder = tempfile::tempdir().expect("a folder");
    let (agent, mut person) = (Slow::new(), Scripted::default());
    let record = Runner::new(folder.path(), &agent, &mut person).run(&plan(THREE), "");

    assert_eq!(record.outcome, Outcome::Done, "{}", person.all());
    assert_eq!(agent.most(), 3);
    for header in ["Step 1 · one", "Step 2 · two", "Step 3 · three"] {
        assert_eq!(person.all().matches(header).count(), 1, "{}", person.all());
    }
    assert!((record.cost - 0.06).abs() < 1e-9, "{}", record.cost);
    assert_eq!(record.steps[1].attempts[0].proofs[0].by, "agent");
}

#[test]
fn no_more_agents_work_at_once_than_the_runner_allows() {
    let folder = tempfile::tempdir().expect("a folder");
    let (agent, mut person) = (Slow::new(), Scripted::default());
    let record = Runner::new(folder.path(), &agent, &mut person)
        .at_once(2)
        .run(&plan(THREE), "");

    assert_eq!(record.outcome, Outcome::Done, "{}", person.all());
    assert_eq!(agent.most(), 2);
}

#[test]
fn a_reading_agent_is_not_blamed_for_what_a_command_writes_meanwhile() {
    let folder = tempfile::tempdir().expect("a folder");
    let plan = plan(
        r#"{ "$schema": "vpf/1.1", "wish": "Read and written",
             "steps": [
               { "id": "read", "do": "Read.", "by": "agent", "tools": ["read"],
                 "proof": { "by": "algorithm", "run": "true" } },
               { "id": "write", "do": "Write.", "by": "algorithm", "run": "sleep 0.2; echo x > out", "after": [] }
             ] }"#,
    );
    let (agent, mut person) = (Slow::new(), Scripted::default());
    let record = Runner::new(folder.path(), &agent, &mut person).run(&plan, "");

    assert_eq!(record.outcome, Outcome::Done, "{}", person.all());
}

#[test]
fn the_items_of_a_step_one_by_one_are_done_one_after_the_other() {
    let folder = tempfile::tempdir().expect("a folder");
    let plan = plan(
        r#"{ "$schema": "vpf/1.1", "wish": "In order",
             "steps": [
               { "id": "names", "do": "Names.", "by": "algorithm", "run": "printf 'x\\ny\\nz\\n'" },
               { "id": "each", "do": "Each.", "by": "algorithm", "for_each": "names", "one_by_one": true,
                 "run": "echo start {{item}} >> log; sleep 0.2; echo end {{item}} >> log; echo {{item}}" }
             ] }"#,
    );
    let (agent, mut person) = (no_agent(), Scripted::default());
    let record = Runner::new(folder.path(), &agent, &mut person).run(&plan, "");

    assert_eq!(record.outcome, Outcome::Done, "{}", person.all());
    assert_eq!(record.steps[1].answer.as_deref(), Some(r#"["x","y","z"]"#));
    let log = std::fs::read_to_string(folder.path().join("log")).expect("the log");
    assert_eq!(log, "start x\nend x\nstart y\nend y\nstart z\nend z\n");
}

#[test]
fn agents_do_the_items_of_a_step_one_by_one_one_at_a_time() {
    let folder = tempfile::tempdir().expect("a folder");
    let plan = plan(
        r#"{ "$schema": "vpf/1.1", "wish": "Notes in order",
             "steps": [
               { "id": "names", "do": "Names.", "by": "algorithm", "run": "printf 'x\\ny\\nz\\n'" },
               { "id": "each", "do": "Write about {{item}}.", "by": "agent", "for_each": "names", "one_by_one": true,
                 "proof": { "by": "agent", "check": "It is done." } }
             ] }"#,
    );
    let (agent, mut person) = (Slow::new(), Scripted::default());
    let record = Runner::new(folder.path(), &agent, &mut person).run(&plan, "");

    assert_eq!(record.outcome, Outcome::Done, "{}", person.all());
    assert_eq!(agent.most(), 1);
    assert_eq!(record.steps[1].items.len(), 3);
}