use std::fs;
use std::io::Write as _;
use std::path::Path;
use std::process::{Command, Output, Stdio};
fn run(folder: &Path, args: &[&str], input: &str) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_vpf-run"))
.args(args)
.current_dir(folder)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("vpf-run starts");
child
.stdin
.take()
.expect("stdin")
.write_all(input.as_bytes())
.expect("input");
child.wait_with_output().expect("vpf-run ends")
}
fn text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
#[test]
fn a_plan_runs_with_an_agent_command_and_a_person() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("note.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "A note",
"steps": [
{ "id": "topic", "do": "What should the note be about?", "by": "person" },
{ "id": "note", "do": "Write a note about {{topic}} in note.md.", "by": "agent",
"proof": [ { "by": "algorithm", "needs": [{ "need": "files", "path": "note.md" }] },
{ "by": "person", "ask": "Is the note good?" } ] }
] }"#,
)
.expect("a plan");
let agent = r##"prompt=$(cat); echo "$prompt" > prompt.txt; echo "# Note" > note.md; echo 0.01 >> "$VPF_COST_FILE"; echo "I wrote note.md""##;
let output = run(
folder.path(),
&["note.vpf.json", "--agent", agent],
"the garden\nyes\n",
);
let out = text(&output.stdout);
assert!(output.status.success(), "{out}\n{}", text(&output.stderr));
assert!(out.contains("What should the note be about?"), "{out}");
assert!(out.contains("Is the note good?"), "{out}");
assert!(out.contains("Done"), "{out}");
let prompt = fs::read_to_string(folder.path().join("prompt.txt")).expect("the prompt");
assert!(
prompt.contains("Write a note about the garden in note.md."),
"{prompt}"
);
let records: Vec<_> = fs::read_dir(folder.path().join(".vpf/runs"))
.expect("records")
.collect();
assert_eq!(records.len(), 1);
let record =
fs::read_to_string(records[0].as_ref().expect("a record").path()).expect("a record");
let record: serde_json::Value = serde_json::from_str(&record).expect("JSON");
assert_eq!(record["outcome"], "done");
assert_eq!(record["plan"], "note");
assert_eq!(record["steps"][1]["answer"], "I wrote note.md");
assert!((record["cost"].as_f64().expect("a cost") - 0.01).abs() < 1e-9);
}
#[test]
fn a_plan_with_problems_does_not_run() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("bad.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "W", "steps": [ { "id": "a", "do": "A.", "by": "agent" } ] }"#,
)
.expect("a plan");
let output = run(folder.path(), &["bad.vpf.json"], "");
assert_eq!(output.status.code(), Some(1));
assert!(
text(&output.stdout).contains("proof.missing"),
"{}",
text(&output.stdout)
);
assert!(!folder.path().join(".vpf").exists());
}
#[test]
fn a_plan_that_needs_an_agent_asks_for_one() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("a.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "W",
"steps": [ { "id": "a", "do": "A.", "by": "agent", "proof": { "by": "person" } } ] }"#,
)
.expect("a plan");
let output = run(folder.path(), &["a.vpf.json"], "");
assert_eq!(output.status.code(), Some(2));
assert!(
text(&output.stderr).contains("--agent"),
"{}",
text(&output.stderr)
);
}
#[test]
fn a_stopped_run_ends_with_one() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("red.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "Green", "limits": { "repeats": 1 },
"steps": [ { "id": "test", "do": "Test.", "by": "algorithm", "run": "echo red; exit 1" } ] }"#,
)
.expect("a plan");
let output = run(folder.path(), &["red.vpf.json"], "no\n");
let out = text(&output.stdout);
assert_eq!(output.status.code(), Some(1), "{out}");
assert!(out.contains("red"), "{out}");
assert!(out.contains("Stopped"), "{out}");
}
#[test]
fn a_scheduled_plan_runs_as_many_times_as_asked() {
let folder = tempfile::tempdir().expect("a folder");
fs::create_dir(folder.path().join("inbox")).expect("a folder");
fs::write(
folder.path().join("watch.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "Counted", "start": { "on": "files", "paths": ["inbox/*.csv"] },
"steps": [ { "id": "count", "do": "Count.", "by": "algorithm", "run": "ls inbox | wc -l" } ] }"#,
)
.expect("a plan");
let inbox = folder.path().join("inbox");
let writer = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(600));
fs::write(inbox.join("a.csv"), "1").expect("a file");
});
let output = run(
folder.path(),
&["watch.vpf.json", "--runs", "1", "--poll-ms", "100"],
"",
);
writer.join().expect("the writer");
let out = text(&output.stdout);
assert!(output.status.success(), "{out}\n{}", text(&output.stderr));
assert!(out.contains("Waiting"), "{out}");
assert!(out.contains("Done"), "{out}");
}
#[test]
fn a_person_picks_from_the_choices_and_sends_work_back() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("pick.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "Picked",
"steps": [
{ "id": "kind", "do": "Which kind?", "by": "person", "choices": ["tea", "coffee"] },
{ "id": "cup", "do": "Pour {{kind}}.", "by": "algorithm", "run": "echo {{kind}} >> cups; echo {{kind}}",
"proof": { "by": "person", "ask": "Is it right?", "back_to": ["kind"] } }
] }"#,
)
.expect("a plan");
let output = run(
folder.path(),
&["pick.vpf.json"],
"water\ntea\nno\nnot tea\nkind\ncoffee\nyes\n",
);
let out = text(&output.stdout);
assert!(output.status.success(), "{out}\n{}", text(&output.stderr));
assert!(out.contains("tea, coffee"), "{out}");
assert!(out.contains("Send it back to"), "{out}");
assert!(out.contains("Done"), "{out}");
assert_eq!(
fs::read_to_string(folder.path().join("cups")).expect("cups"),
"tea\ncoffee\n"
);
}
fn kept(folder: &Path) -> serde_json::Value {
let mut runs: Vec<_> = fs::read_dir(folder.join(".vpf/runs"))
.expect("runs")
.map(|entry| entry.expect("a run").path())
.collect();
assert_eq!(runs.len(), 1, "{runs:?}");
let text = fs::read_to_string(runs.remove(0)).expect("a run");
serde_json::from_str(&text).expect("JSON")
}
#[test]
fn a_detached_run_is_answered_from_elsewhere_and_goes_on() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("hello.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "A greeting",
"steps": [
{ "id": "name", "do": "Say a name.", "by": "person", "person": "ana" },
{ "id": "hello", "do": "Greet.", "by": "algorithm", "run": "echo 'hello {{name}}' >> log" }
] }"#,
)
.expect("a plan");
let output = run(folder.path(), &["--detach", "hello.vpf.json"], "");
let out = text(&output.stdout);
assert_eq!(
output.status.code(),
Some(3),
"{out}\n{}",
text(&output.stderr)
);
assert!(out.contains("For ana: Step 1 · name: Say a name."), "{out}");
assert!(out.contains("vpf-run answer"), "{out}");
let record = kept(folder.path());
let id = record["id"].as_str().expect("an id").to_owned();
let key = record["waiting"][0]["key"]
.as_str()
.expect("a key")
.to_owned();
let status = text(&run(folder.path(), &["status"], "").stdout);
assert!(status.contains(&id), "{status}");
assert!(status.contains(&key), "{status}");
assert!(status.contains("For ana"), "{status}");
let refused = run(folder.path(), &["answer", &id, &key, "Ana"], "");
assert_eq!(refused.status.code(), Some(1), "only ana answers");
assert!(
text(&refused.stdout).contains("ana"),
"{}",
text(&refused.stdout)
);
let answered = run(
folder.path(),
&["answer", &id[..12], &key, "Ana", "--as", "ana"],
"",
);
assert!(
answered.status.success(),
"{}{}",
text(&answered.stdout),
text(&answered.stderr)
);
let went = run(folder.path(), &["go"], "");
let out = text(&went.stdout);
assert!(went.status.success(), "{out}\n{}", text(&went.stderr));
assert!(out.contains("Done"), "{out}");
assert_eq!(
fs::read_to_string(folder.path().join("log")).expect("log"),
"hello Ana\n"
);
assert_eq!(kept(folder.path())["outcome"], "done");
let status = text(&run(folder.path(), &["status"], "").stdout);
assert!(status.contains("No run waits"), "{status}");
}
#[test]
fn a_run_that_waits_for_a_time_shows_when_and_takes_a_new_version() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("trip.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "A trip",
"steps": [
{ "id": "where", "do": "Where to?", "by": "algorithm", "run": "echo Rome" },
{ "id": "book", "do": "Book.", "by": "algorithm", "run": "echo 'hotel {{where}}' >> log",
"not_before": "P1D" }
] }"#,
)
.expect("a plan");
let output = run(folder.path(), &["trip.vpf.json", "--detach"], "");
assert_eq!(output.status.code(), Some(3), "{}", text(&output.stdout));
let id = kept(folder.path())["id"]
.as_str()
.expect("an id")
.to_owned();
let status = text(&run(folder.path(), &["status"], "").stdout);
assert!(status.contains("book may start"), "{status}");
fs::write(
folder.path().join("trip-2.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "A trip",
"steps": [
{ "id": "where", "do": "Where to?", "by": "algorithm", "run": "echo Rome" },
{ "id": "train", "do": "Book a train.", "by": "algorithm", "run": "echo 'train {{where}}' >> log" }
] }"#,
)
.expect("a new version");
let unapproved = run(folder.path(), &["change", &id, "trip-2.vpf.json"], "");
assert_eq!(unapproved.status.code(), Some(2));
let changed = run(
folder.path(),
&["change", &id, "trip-2.vpf.json", "--approved-by", "caio"],
"",
);
assert!(
changed.status.success(),
"{}{}",
text(&changed.stdout),
text(&changed.stderr)
);
let went = run(folder.path(), &["go", &id], "");
assert!(went.status.success(), "{}", text(&went.stdout));
assert_eq!(
fs::read_to_string(folder.path().join("log")).expect("log"),
"train Rome\n"
);
let record = kept(folder.path());
assert_eq!(record["versions"][1]["approved_by"], "caio");
assert_eq!(record["versions"][1]["from"], "train");
}
#[test]
fn a_waiting_run_goes_on_with_the_agent_it_started_with() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("note.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "A note",
"steps": [
{ "id": "topic", "do": "Say what the note is about.", "by": "person", "person": "ana" },
{ "id": "note", "do": "Write a note about {{topic}} in note.md.", "by": "agent",
"proof": { "by": "algorithm", "needs": [{ "need": "files", "path": "note.md" }] } }
] }"#,
)
.expect("a plan");
let agent = r##"cat > /dev/null; echo "# Note" > note.md; echo "I wrote note.md""##;
let started = run(
folder.path(),
&["--detach", "note.vpf.json", "--agent", agent],
"",
);
assert_eq!(started.status.code(), Some(3), "{}", text(&started.stderr));
let record = kept(folder.path());
let id = record["id"].as_str().expect("an id").to_owned();
let key = record["waiting"][0]["key"]
.as_str()
.expect("a key")
.to_owned();
let answered = run(
folder.path(),
&["answer", &id, &key, "the garden", "--as", "ana"],
"",
);
assert!(answered.status.success(), "{}", text(&answered.stdout));
let went = Command::new(env!("CARGO_BIN_EXE_vpf-run"))
.args(["go", &id])
.current_dir(folder.path())
.env_remove("VPF_AGENT_COMMAND")
.stdin(Stdio::null())
.output()
.expect("vpf-run ends");
let out = text(&went.stdout);
assert!(went.status.success(), "{out}\n{}", text(&went.stderr));
assert!(out.contains("Done"), "{out}");
assert!(folder.path().join("note.md").exists());
}
#[test]
fn no_run_starts_after_the_plan_s_until() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("over.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "Counted", "start": { "on": "asked", "until": "2020-01-01T00:00Z" },
"steps": [ { "id": "count", "do": "Count.", "by": "algorithm", "run": "echo counted > counted.txt" } ] }"#,
)
.expect("a plan");
let output = run(folder.path(), &["over.vpf.json"], "");
let out = text(&output.stdout);
assert_eq!(output.status.code(), Some(1), "{out}");
assert!(
out.contains("No run starts after 2020-01-01T00:00Z"),
"{out}"
);
assert!(!folder.path().join("counted.txt").exists(), "{out}");
}
#[test]
fn a_run_asked_for_before_the_plan_s_from_does_not_start() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("early.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "Counted", "start": { "on": "asked", "from": "2999-01-01T00:00Z" },
"steps": [ { "id": "count", "do": "Count.", "by": "algorithm", "run": "echo counted > counted.txt" } ] }"#,
)
.expect("a plan");
let output = run(folder.path(), &["early.vpf.json"], "");
let out = text(&output.stdout);
assert_eq!(output.status.code(), Some(1), "{out}");
assert!(
out.contains("No run starts before 2999-01-01T00:00Z"),
"{out}"
);
assert!(!folder.path().join("counted.txt").exists(), "{out}");
}
#[test]
fn a_plan_between_its_from_and_until_runs() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("open.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "Counted",
"start": { "on": "asked", "from": "2020-01-01T00:00Z", "until": "2999-01-01T00:00Z" },
"steps": [ { "id": "count", "do": "Count.", "by": "algorithm", "run": "echo counted > counted.txt" } ] }"#,
)
.expect("a plan");
let output = run(folder.path(), &["open.vpf.json"], "");
let out = text(&output.stdout);
assert!(output.status.success(), "{out}\n{}", text(&output.stderr));
assert!(folder.path().join("counted.txt").exists(), "{out}");
}
#[test]
fn a_repeating_plan_stops_starting_runs_at_its_until() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("every.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "Counted", "start": { "on": "every", "minutes": 1, "until": "2020-01-01T00:00Z" },
"steps": [ { "id": "count", "do": "Count.", "by": "algorithm", "run": "echo counted > counted.txt" } ] }"#,
)
.expect("a plan");
let output = run(folder.path(), &["every.vpf.json", "--runs", "3"], "");
let out = text(&output.stdout);
assert_eq!(output.status.code(), Some(1), "{out}");
assert!(out.contains("No run starts after"), "{out}");
assert!(!folder.path().join("counted.txt").exists(), "{out}");
}
#[test]
fn an_agent_command_that_fails_is_named_once_in_the_points() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("broken.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "Broken", "limits": { "repeats": 1 },
"steps": [ { "id": "work", "do": "Work.", "by": "agent",
"proof": { "by": "algorithm", "run": "true" } } ] }"#,
)
.expect("a plan");
let output = run(
folder.path(),
&[
"broken.vpf.json",
"--agent",
"echo always broken >&2; exit 1",
],
"no\n",
);
let out = text(&output.stdout);
assert!(
out.contains("The agent ended with an error: always broken"),
"{out}"
);
assert!(!out.contains("agent command failed"), "{out}");
}
#[test]
fn a_no_answered_from_elsewhere_sends_work_back_in_either_form() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("push.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "Push",
"steps": [
{ "id": "commit", "do": "Commit.", "by": "algorithm", "run": "echo commit >> log" },
{ "id": "push", "do": "Push.", "by": "algorithm", "run": "echo push >> log", "irreversible": true }
] }"#,
)
.expect("a plan");
run(folder.path(), &["--detach", "push.vpf.json"], "");
let record = kept(folder.path());
let id = record["id"].as_str().expect("an id").to_owned();
let key = record["waiting"][0]["key"]
.as_str()
.expect("a key")
.to_owned();
let refused = run(folder.path(), &["answer", &id, &key, "maybe"], "");
assert_eq!(refused.status.code(), Some(1));
assert!(
text(&refused.stdout).contains("--back"),
"{}",
text(&refused.stdout)
);
let answered = run(
folder.path(),
&["answer", &id, &key, "no>commit: the message is wrong"],
"",
);
assert!(answered.status.success(), "{}", text(&answered.stdout));
run(folder.path(), &["go", "--detach"], "");
assert_eq!(
fs::read_to_string(folder.path().join("log")).expect("the log"),
"commit\ncommit\n"
);
}
#[test]
fn a_run_killed_in_the_middle_goes_on_without_asking_its_agent_again() {
let folder = tempfile::tempdir().expect("a folder");
fs::write(
folder.path().join("text.vpf.json"),
r#"{ "$schema": "vpf/1.1", "wish": "A short text",
"steps": [
{ "id": "outline", "do": "Outline it.", "by": "agent", "proof": [ { "by": "algorithm", "run": "true" } ] },
{ "id": "text", "do": "Write it from {{outline}}.", "by": "agent", "proof": [ { "by": "algorithm", "run": "true" } ] }
] }"#,
)
.expect("a plan");
let agent = r#"echo "$VPF_STEP" >> asked.txt
if [ "$VPF_STEP" = text ] && [ ! -f fast ]; then sleep 20; fi
echo "did $VPF_STEP""#;
let mut child = Command::new(env!("CARGO_BIN_EXE_vpf-run"))
.args(["text.vpf.json", "--agent", agent])
.current_dir(folder.path())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("vpf-run starts");
let asked = folder.path().join("asked.txt");
let started = std::time::Instant::now();
while !fs::read_to_string(&asked)
.unwrap_or_default()
.contains("text")
{
assert!(
started.elapsed() < std::time::Duration::from_secs(20),
"the text was never asked"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
child.kill().expect("the run is killed");
child.wait().expect("the run ended");
let status = run(folder.path(), &["status"], "");
let said = text(&status.stdout);
assert!(
said.contains("It is running, or it stopped before it ended."),
"{said}"
);
fs::write(folder.path().join("fast"), "").expect("fast");
let output = run(folder.path(), &["go"], "");
let out = text(&output.stdout);
assert!(output.status.success(), "{out}\n{}", text(&output.stderr));
assert!(out.contains("Done"), "{out}");
assert_eq!(
fs::read_to_string(&asked).expect("what was asked"),
"outline\ntext\ntext\n",
"the outline is not asked again, and `go` goes on with the same agent"
);
}