mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-03 00:09:19 -08:00
427 lines
15 KiB
Rust
427 lines
15 KiB
Rust
//! A stand-in for Claude, Devin and Codex in the app's tests.
|
|
//!
|
|
//! It behaves the same on Windows, macOS and Linux. Commands, one per line on
|
|
//! stdin (these words are the contract the app's integration tests rely on):
|
|
//!
|
|
//! STEP <n> print one progress line a second for n seconds, then `STEP DONE`
|
|
//! EXIT <c> exit with code c
|
|
//! SIZE print the terminal size once
|
|
//! PID print the agent's process id as `PID <n>`
|
|
//! REPORT <json> write <json> as `loopOutcome` into the session's state.json
|
|
//! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say
|
|
//! `REPORT written` (`REPORT unavailable` when either is missing)
|
|
//! ROUND <json> write <json> as `roundOutcome` the same way; when it names a
|
|
//! `report` id, first add that doc (`kind: report`) to `docs`.
|
|
//! Says `ROUND written` (`ROUND unavailable` when it cannot)
|
|
//! FILE <path> <text> write <text> to <path> under the working directory (`\n`
|
|
//! in the text is a line break), for a round's "fixes". Says
|
|
//! `FILE written <path>` (`FILE refused <path>` for a path that
|
|
//! leaves the folder)
|
|
//! ENV <name> print the variable as `ENV <name>=<value>`
|
|
//! HANG say `HANGING`, then go silent for good (no more lines read)
|
|
//! <other> echoed back as `echo: <line>`
|
|
//!
|
|
//! A change in terminal size is reported on its own as `SIZE <cols>x<rows>`.
|
|
|
|
use std::io::{self, BufRead, Write};
|
|
use std::thread;
|
|
use std::time::Duration;
|
|
|
|
use terminal_size::{terminal_size, Height, Width};
|
|
|
|
fn size_text() -> Option<String> {
|
|
terminal_size().map(|(Width(w), Height(h))| format!("SIZE {w}x{h}"))
|
|
}
|
|
|
|
fn say(line: &str) {
|
|
let mut out = io::stdout().lock();
|
|
let _ = writeln!(out, "{line}\r");
|
|
let _ = out.flush();
|
|
}
|
|
|
|
/// What a command line asks the agent to do.
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub enum Command {
|
|
Step(u64),
|
|
Exit(i32),
|
|
Size,
|
|
Pid,
|
|
/// `ENV NAME`: print the variable's value, for tests of what an agent is given.
|
|
Env(String),
|
|
/// `REPORT <json>`: the phase report the loop waits for, as the JSON text.
|
|
Report(String),
|
|
/// `ROUND <json>`: a Review Loop round's report, as the JSON text.
|
|
Round(String),
|
|
/// `FILE <path> <text>`: a file the agent "fixed", relative to its folder.
|
|
File(String, String),
|
|
/// `HANG`: go silent, to model an agent that stops answering.
|
|
Hang,
|
|
Echo(String),
|
|
}
|
|
|
|
/// Write `json` as the `loopOutcome` of the session named by the environment.
|
|
/// Returns false when the session cannot be named.
|
|
fn write_report(json: &str) -> bool {
|
|
let (Ok(home), Ok(sid)) = (
|
|
std::env::var("PLAN2CODE_CONSOLE_HOME"),
|
|
std::env::var("PLAN2CODE_CONSOLE_SID"),
|
|
) else {
|
|
return false;
|
|
};
|
|
write_report_to(std::path::Path::new(&home), &sid, json)
|
|
}
|
|
|
|
/// `write_report` with the session named: `<home>/sessions/<sid>/state.json`.
|
|
fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool {
|
|
let Ok(outcome) = serde_json::from_str::<serde_json::Value>(json) else {
|
|
return false;
|
|
};
|
|
update_state(home, sid, |state| state["loopOutcome"] = outcome)
|
|
}
|
|
|
|
/// Write the JSON as the `roundOutcome` of the session named by the environment.
|
|
fn write_round(json: &str) -> bool {
|
|
let (Ok(home), Ok(sid)) = (
|
|
std::env::var("PLAN2CODE_CONSOLE_HOME"),
|
|
std::env::var("PLAN2CODE_CONSOLE_SID"),
|
|
) else {
|
|
return false;
|
|
};
|
|
write_round_to(std::path::Path::new(&home), &sid, json)
|
|
}
|
|
|
|
/// `write_round` with the session named. A named `report` is added to `docs`
|
|
/// first, as the console would hold it, so the app finds the doc it checks for.
|
|
fn write_round_to(home: &std::path::Path, sid: &str, json: &str) -> bool {
|
|
let Ok(outcome) = serde_json::from_str::<serde_json::Value>(json) else {
|
|
return false;
|
|
};
|
|
update_state(home, sid, |state| {
|
|
if let Some(report) = outcome.get("report").and_then(|value| value.as_str()) {
|
|
let doc =
|
|
serde_json::json!({ "id": report, "kind": "report", "title": "Review round" });
|
|
match state.get_mut("docs").and_then(|docs| docs.as_array_mut()) {
|
|
Some(docs) => docs.push(doc),
|
|
None => state["docs"] = serde_json::json!([doc]),
|
|
}
|
|
}
|
|
state["roundOutcome"] = outcome;
|
|
})
|
|
}
|
|
|
|
/// Read `<home>/sessions/<sid>/state.json` (a new object when it is missing or
|
|
/// not one), let `change` edit it, and write it back through a temp file and a
|
|
/// rename, so a reader never sees half a file.
|
|
fn update_state(
|
|
home: &std::path::Path,
|
|
sid: &str,
|
|
change: impl FnOnce(&mut serde_json::Value),
|
|
) -> bool {
|
|
let dir = home.join("sessions").join(sid);
|
|
let file = dir.join("state.json");
|
|
let mut state = std::fs::read_to_string(&file)
|
|
.ok()
|
|
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
|
|
.filter(|value| value.is_object())
|
|
// The console's own file always carries its schema number; a new one does too.
|
|
.unwrap_or_else(|| serde_json::json!({ "schema": 1 }));
|
|
change(&mut state);
|
|
let _ = std::fs::create_dir_all(&dir);
|
|
let temp = dir.join("state.json.tmp");
|
|
let Ok(text) = serde_json::to_string(&state) else {
|
|
return false;
|
|
};
|
|
std::fs::write(&temp, text).is_ok() && std::fs::rename(&temp, &file).is_ok()
|
|
}
|
|
|
|
pub fn parse(line: &str) -> Command {
|
|
let line = line.trim();
|
|
if let Some(rest) = line.strip_prefix("STEP ") {
|
|
if let Ok(n) = rest.trim().parse() {
|
|
return Command::Step(n);
|
|
}
|
|
}
|
|
if let Some(rest) = line.strip_prefix("EXIT ") {
|
|
if let Ok(code) = rest.trim().parse() {
|
|
return Command::Exit(code);
|
|
}
|
|
}
|
|
if line == "SIZE" {
|
|
return Command::Size;
|
|
}
|
|
if line == "PID" {
|
|
return Command::Pid;
|
|
}
|
|
if let Some(name) = line.strip_prefix("ENV ") {
|
|
return Command::Env(name.trim().to_string());
|
|
}
|
|
if let Some(rest) = line.strip_prefix("REPORT ") {
|
|
let json = rest.trim();
|
|
if serde_json::from_str::<serde_json::Value>(json).is_ok() {
|
|
return Command::Report(json.to_string());
|
|
}
|
|
}
|
|
if let Some(rest) = line.strip_prefix("ROUND ") {
|
|
let json = rest.trim();
|
|
if serde_json::from_str::<serde_json::Value>(json).is_ok() {
|
|
return Command::Round(json.to_string());
|
|
}
|
|
}
|
|
if let Some(rest) = line.strip_prefix("FILE ") {
|
|
let rest = rest.trim_start();
|
|
if let Some((path, text)) = rest.split_once(char::is_whitespace) {
|
|
return Command::File(path.to_string(), text.trim_start().to_string());
|
|
}
|
|
}
|
|
if line == "HANG" {
|
|
return Command::Hang;
|
|
}
|
|
Command::Echo(line.to_string())
|
|
}
|
|
|
|
/// Write `text` to `relative` under the working directory. Refuses a path that
|
|
/// is absolute or climbs out of it. `\n` in `text` becomes a line break.
|
|
fn write_file(relative: &str, text: &str) -> bool {
|
|
use std::path::{Component, Path};
|
|
let path = Path::new(relative);
|
|
let inside = !relative.is_empty()
|
|
&& path
|
|
.components()
|
|
.all(|part| matches!(part, Component::Normal(_) | Component::CurDir));
|
|
if !inside {
|
|
return false;
|
|
}
|
|
if let Some(parent) = path
|
|
.parent()
|
|
.filter(|parent| !parent.as_os_str().is_empty())
|
|
{
|
|
let _ = std::fs::create_dir_all(parent);
|
|
}
|
|
std::fs::write(path, text.replace("\\n", "\n")).is_ok()
|
|
}
|
|
|
|
fn main() {
|
|
say("FAKE-AGENT ready");
|
|
// What the app launched it with: the launch prompt is one of these, so a
|
|
// test can read back which prompt a generation was started on.
|
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
|
say(&format!("ARGS {}", args.join(" ")));
|
|
if let Some(size) = size_text() {
|
|
say(&size);
|
|
}
|
|
|
|
// Report a resize on its own, by watching the size, so the same code works
|
|
// where there is no resize signal (Windows).
|
|
thread::spawn(|| {
|
|
let mut last = size_text();
|
|
loop {
|
|
thread::sleep(Duration::from_millis(100));
|
|
let now = size_text();
|
|
if now != last {
|
|
if let Some(text) = &now {
|
|
say(text);
|
|
}
|
|
last = now;
|
|
}
|
|
}
|
|
});
|
|
|
|
let stdin = io::stdin();
|
|
for line in stdin.lock().lines() {
|
|
let Ok(line) = line else { break };
|
|
match parse(&line) {
|
|
Command::Step(n) => {
|
|
for i in 1..=n {
|
|
say(&format!("working {i}/{n}"));
|
|
thread::sleep(Duration::from_secs(1));
|
|
}
|
|
say("STEP DONE");
|
|
}
|
|
Command::Exit(code) => {
|
|
say(&format!("exiting {code}"));
|
|
std::process::exit(code);
|
|
}
|
|
Command::Size => say(&size_text().unwrap_or_else(|| "SIZE unknown".into())),
|
|
Command::Pid => say(&format!("PID {}", std::process::id())),
|
|
Command::Env(name) => say(&format!(
|
|
"ENV {name}={}",
|
|
std::env::var(&name).unwrap_or_default()
|
|
)),
|
|
Command::Report(json) => {
|
|
if write_report(&json) {
|
|
say("REPORT written")
|
|
} else {
|
|
say("REPORT unavailable")
|
|
}
|
|
}
|
|
Command::Round(json) => {
|
|
if write_round(&json) {
|
|
say("ROUND written")
|
|
} else {
|
|
say("ROUND unavailable")
|
|
}
|
|
}
|
|
Command::File(path, text) => {
|
|
if write_file(&path, &text) {
|
|
say(&format!("FILE written {path}"))
|
|
} else {
|
|
say(&format!("FILE refused {path}"))
|
|
}
|
|
}
|
|
Command::Hang => {
|
|
say("HANGING");
|
|
loop {
|
|
thread::sleep(Duration::from_secs(3600));
|
|
}
|
|
}
|
|
Command::Echo(text) => say(&format!("echo: {text}")),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn parses_the_command_words() {
|
|
assert_eq!(parse("STEP 3"), Command::Step(3));
|
|
assert_eq!(parse("EXIT 7\r\n"), Command::Exit(7));
|
|
assert_eq!(parse("SIZE"), Command::Size);
|
|
assert_eq!(parse("PID"), Command::Pid);
|
|
assert_eq!(
|
|
parse("ENV PLAN2CODE_IN_APP"),
|
|
Command::Env("PLAN2CODE_IN_APP".into())
|
|
);
|
|
assert_eq!(parse("hello there"), Command::Echo("hello there".into()));
|
|
}
|
|
|
|
#[test]
|
|
fn parses_report_and_hang() {
|
|
assert_eq!(
|
|
parse("REPORT {\"phase\":2}"),
|
|
Command::Report("{\"phase\":2}".into())
|
|
);
|
|
assert_eq!(parse("HANG\r\n"), Command::Hang);
|
|
}
|
|
|
|
#[test]
|
|
fn a_report_lands_in_the_session_file_beside_what_was_there() {
|
|
let home = std::env::temp_dir().join(format!("fake-agent-report-{}", std::process::id()));
|
|
let dir = home.join("sessions").join("s9");
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
// No file yet: a new one with the schema number.
|
|
assert!(write_report_to(&home, "s9", "{\"phase\":2}"));
|
|
let read = || -> serde_json::Value {
|
|
serde_json::from_str(&std::fs::read_to_string(dir.join("state.json")).unwrap()).unwrap()
|
|
};
|
|
assert_eq!(read()["loopOutcome"]["phase"], 2);
|
|
assert_eq!(read()["schema"], 1);
|
|
// An existing object keeps its keys.
|
|
std::fs::write(dir.join("state.json"), "{\"schema\":1,\"title\":\"t\"}").unwrap();
|
|
assert!(write_report_to(&home, "s9", "{\"phase\":3}"));
|
|
assert_eq!(read()["title"], "t");
|
|
assert_eq!(read()["loopOutcome"]["phase"], 3);
|
|
// A garbage file is replaced, not trusted.
|
|
std::fs::write(dir.join("state.json"), "not json").unwrap();
|
|
assert!(write_report_to(&home, "s9", "{\"phase\":4}"));
|
|
assert_eq!(read()["loopOutcome"]["phase"], 4);
|
|
let _ = std::fs::remove_dir_all(&home);
|
|
}
|
|
|
|
#[test]
|
|
fn parses_round_and_file() {
|
|
assert_eq!(
|
|
parse("ROUND {\"round\":1}"),
|
|
Command::Round("{\"round\":1}".into())
|
|
);
|
|
assert_eq!(parse("ROUND {nope"), Command::Echo("ROUND {nope".into()));
|
|
assert_eq!(
|
|
parse("FILE src/a.rs fixed it\\nline two"),
|
|
Command::File("src/a.rs".into(), "fixed it\\nline two".into())
|
|
);
|
|
assert_eq!(
|
|
parse("FILE onlypath"),
|
|
Command::Echo("FILE onlypath".into())
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_round_lands_with_its_report_doc_beside_what_was_there() {
|
|
let home = std::env::temp_dir().join(format!("fake-agent-round-{}", std::process::id()));
|
|
let dir = home.join("sessions").join("s5");
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let read = || -> serde_json::Value {
|
|
serde_json::from_str(&std::fs::read_to_string(dir.join("state.json")).unwrap()).unwrap()
|
|
};
|
|
// A report id adds the doc to a state that had none.
|
|
assert!(write_round_to(
|
|
&home,
|
|
"s5",
|
|
"{\"round\":1,\"role\":\"both\",\"report\":\"rep\"}"
|
|
));
|
|
let state = read();
|
|
assert_eq!(state["roundOutcome"]["round"], 1);
|
|
assert_eq!(state["docs"][0]["id"], "rep");
|
|
assert_eq!(state["docs"][0]["kind"], "report");
|
|
assert_eq!(state["docs"][0]["title"], "Review round");
|
|
assert_eq!(state["schema"], 1);
|
|
// Existing docs stay, and the new one is appended.
|
|
std::fs::write(
|
|
dir.join("state.json"),
|
|
"{\"schema\":1,\"docs\":[{\"id\":\"phasefile\"}]}",
|
|
)
|
|
.unwrap();
|
|
assert!(write_round_to(
|
|
&home,
|
|
"s5",
|
|
"{\"round\":2,\"report\":\"r2\"}"
|
|
));
|
|
let state = read();
|
|
assert_eq!(state["docs"][0]["id"], "phasefile");
|
|
assert_eq!(state["docs"][1]["id"], "r2");
|
|
// No report id, no doc; a fixer's outcome adds none.
|
|
std::fs::write(dir.join("state.json"), "{\"schema\":1}").unwrap();
|
|
assert!(write_round_to(
|
|
&home,
|
|
"s5",
|
|
"{\"round\":3,\"role\":\"fixer\"}"
|
|
));
|
|
let state = read();
|
|
assert!(state.get("docs").is_none());
|
|
assert_eq!(state["roundOutcome"]["role"], "fixer");
|
|
// The loop's own report key is untouched by a round.
|
|
assert!(state.get("loopOutcome").is_none());
|
|
assert!(!write_round_to(&home, "s5", "not json"));
|
|
let _ = std::fs::remove_dir_all(&home);
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_command_writes_under_the_working_folder_only() {
|
|
let base = format!("fake-agent-file-{}", std::process::id());
|
|
assert!(write_file(&format!("{base}/sub/a.txt"), "one\\ntwo"));
|
|
assert_eq!(
|
|
std::fs::read_to_string(format!("{base}/sub/a.txt")).unwrap(),
|
|
"one\ntwo"
|
|
);
|
|
let _ = std::fs::remove_dir_all(&base);
|
|
assert!(!write_file("../escape.txt", "x"));
|
|
assert!(!write_file("/abs.txt", "x"));
|
|
assert!(!write_file("", "x"));
|
|
}
|
|
|
|
#[test]
|
|
fn a_report_with_bad_json_is_an_echo() {
|
|
assert_eq!(
|
|
parse("REPORT {not json"),
|
|
Command::Echo("REPORT {not json".into())
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_bad_number_is_just_an_echo() {
|
|
assert_eq!(parse("STEP x"), Command::Echo("STEP x".into()));
|
|
assert_eq!(parse("EXIT"), Command::Echo("EXIT".into()));
|
|
}
|
|
}
|