use std::path::Path;
use std::process::Command;
use std::sync::Mutex;
use std::time::Duration;
use blyte_agent::context::{ContextStrategy, Conversational};
use blyte_agent::fs::LocalFs;
use blyte_agent::run::{Budget, Outcome, Runner};
use blyte_agent::shell::{Output, Shell};
use blyte_agent::state::State;
use blyte_provider::{Provider, ProviderError, Request, Response, ToolCall, Usage};
use serde_json::json;
struct StubShell;
impl Shell for StubShell {
fn exec(&self, command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
let trimmed = command.trim();
if command.lines().any(|l| l.trim() == "true") {
return Ok(Output {
stdout: String::new(),
stderr: String::new(),
exit_code: 0,
});
}
if let Some(rest) = trimmed.strip_prefix("echo ") {
return Ok(Output {
stdout: format!("{rest}\n"),
stderr: String::new(),
exit_code: 0,
});
}
Ok(Output {
stdout: String::new(),
stderr: String::new(),
exit_code: 1,
})
}
fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
self.exec(command, cwd, timeout)
}
fn describe(&self) -> String {
String::new()
}
fn available_binaries(
&self,
_cwd: &Path,
_candidates: &[&'static str],
) -> Result<Vec<String>, String> {
Ok(vec!["git".into()])
}
}
struct FastShell;
impl Shell for FastShell {
fn exec(&self, command: &str, cwd: &Path, _timeout: Duration) -> Result<Output, String> {
let out = Command::new("bash")
.arg("-c")
.arg(command)
.current_dir(cwd)
.output()
.map_err(|e| format!("failed to run bash: {e}"))?;
Ok(Output {
stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
exit_code: out.status.code().unwrap_or(-1),
})
}
fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
self.exec(command, cwd, timeout)
}
fn describe(&self) -> String {
String::new()
}
fn available_binaries(
&self,
_cwd: &Path,
_candidates: &[&'static str],
) -> Result<Vec<String>, String> {
Ok(vec!["git".into()])
}
}
struct ScriptedProvider {
script: Mutex<Vec<Response>>,
seen: Mutex<Vec<Request>>,
}
impl ScriptedProvider {
fn new(script: Vec<Response>) -> Self {
Self {
script: Mutex::new(script),
seen: Mutex::new(Vec::new()),
}
}
}
impl Provider for ScriptedProvider {
fn complete(&self, req: &Request) -> Result<Response, ProviderError> {
self.seen.lock().unwrap().push(req.clone());
let mut s = self.script.lock().unwrap();
if s.is_empty() {
return Ok(Response::default());
}
Ok(s.remove(0))
}
fn model_id(&self) -> String {
"scripted".into()
}
}
fn says(text: &str) -> Response {
Response {
text: text.into(),
..Default::default()
}
}
fn calls(name: &str, args: serde_json::Value) -> Response {
Response {
tool_calls: vec![ToolCall {
id: "c0".into(),
name: name.into(),
arguments: args,
signature: None,
}],
usage: Usage {
input: 100,
cached: 0,
output: 10,
thinking: 0,
},
..Default::default()
}
}
fn git(dir: &Path, args: &[&str]) {
let status = Command::new("git")
.args(args)
.current_dir(dir)
.status()
.unwrap();
assert!(status.success(), "git {args:?} failed");
}
fn repo() -> tempfile::TempDir {
let d = tempfile::tempdir().unwrap();
git(d.path(), &["init", "-q"]);
std::fs::write(d.path().join("marker"), "0\n").unwrap();
git(d.path(), &["add", "-A"]);
git(
d.path(),
&[
"-c",
"user.email=a@b",
"-c",
"user.name=c",
"commit",
"-qm",
"base",
],
);
d
}
fn runner<'a>(
p: &'a ScriptedProvider,
shell: &'a dyn Shell,
root: &std::path::Path,
ctx: &'a dyn ContextStrategy,
rollback: bool,
) -> Runner<'a> {
Runner {
provider: p,
shell,
fs: &LocalFs,
context: ctx,
root: root.to_path_buf(),
budget: Budget {
max_turns: 12,
max_gate_attempts: 3,
max_duration: None,
},
rollback,
on_event: None,
research: false,
claim_check: false,
base_check: blyte_agent::run::BaseCheck::None,
}
}
#[test]
fn the_gate_is_not_in_the_tool_surface() {
let names: Vec<String> = blyte_agent::tools::specs()
.into_iter()
.map(|t| t.name)
.collect();
for forbidden in [
"verify",
"gate",
"check",
"run_tests",
"complete",
"done",
"finish",
] {
assert!(
!names.iter().any(|n| n == forbidden),
"`{forbidden}` must not be callable by the model: {names:?}"
);
}
}
#[test]
fn stopping_triggers_the_gate_and_passing_it_ends_the_run() {
let d = tempfile::tempdir().unwrap();
let p = ScriptedProvider::new(vec![says("I think that is done.")]);
let mut st = State::new("make it work", "true");
let (outcome, rep) = runner(&p, &StubShell, d.path(), &Conversational, true).run(&mut st);
assert_eq!(outcome, Outcome::Verified);
assert_eq!(rep.gate_attempts, 1);
}
#[test]
fn the_model_cannot_finish_by_claiming_to_have_finished() {
let d = tempfile::tempdir().unwrap();
let p = ScriptedProvider::new(vec![
says("Done! All tests pass."),
says("Definitely finished now."),
says("Complete."),
]);
let mut st = State::new("fix it", "false");
let (outcome, rep) = runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
assert_eq!(outcome, Outcome::GateFailed);
assert_eq!(
rep.gate_attempts, 3,
"every claim was tested, none accepted"
);
}
#[test]
fn a_gate_that_cannot_run_is_a_failure_not_a_pass() {
let d = tempfile::tempdir().unwrap();
let p = ScriptedProvider::new(vec![says("done")]);
let mut st = State::new("g", "this-command-does-not-exist-anywhere");
let (outcome, _) = runner(&p, &FastShell, d.path(), &Conversational, false).run(&mut st);
assert_eq!(outcome, Outcome::GateFailed);
}
#[test]
fn a_failed_gate_resets_the_tree_to_the_checkpoint() {
let d = repo();
let p = ScriptedProvider::new(vec![
calls(
"write",
json!({"path": "marker", "content": "vandalised\n"}),
),
says("done"),
]);
let mut st = State::new("g", "false");
let (_, _) = runner(&p, &FastShell, d.path(), &Conversational, true).run(&mut st);
assert_eq!(
std::fs::read_to_string(d.path().join("marker")).unwrap(),
"0\n",
"the working tree must be back at the checkpoint"
);
assert!(st.runtime.rollbacks >= 1);
}
#[test]
fn rollback_can_be_switched_off_because_it_is_not_free() {
let d = tempfile::tempdir().unwrap();
std::fs::write(d.path().join("marker"), "0\n").unwrap();
let p = ScriptedProvider::new(vec![
calls("write", json!({"path": "marker", "content": "kept\n"})),
says("done"),
]);
let mut st = State::new("g", "false");
let (_, _) = runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
assert_eq!(
std::fs::read_to_string(d.path().join("marker")).unwrap(),
"kept\n"
);
assert_eq!(st.runtime.rollbacks, 0);
}
#[test]
fn the_worker_is_told_when_its_edits_were_reverted() {
let d = repo();
let p = ScriptedProvider::new(vec![
calls("write", json!({"path": "marker", "content": "x\n"})),
says("done"),
says("done"),
]);
let mut st = State::new("g", "false");
runner(&p, &FastShell, d.path(), &Conversational, true).run(&mut st);
let last = p.seen.lock().unwrap().last().cloned().unwrap();
let text = format!("{:?}", last.messages);
assert!(
text.contains("reverted"),
"the reset must be stated to the worker: {text:.400}"
);
}
#[test]
fn the_system_prompt_states_the_gate_without_offering_it() {
let d = tempfile::tempdir().unwrap();
let p = ScriptedProvider::new(vec![says("done")]);
let mut st = State::new("fix the parser", "npm test");
runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
let sys = p.seen.lock().unwrap()[0].system.clone();
assert!(
sys.contains("npm test"),
"the worker must know the standard it is held to"
);
assert!(sys.contains("you do not decide the verdict"));
assert!(
sys.contains("Available:"),
"the environment probe must reach the prompt"
);
}
#[test]
fn conversational_context_does_grow_which_is_the_thing_being_compared() {
let d = tempfile::tempdir().unwrap();
let script: Vec<_> = (0..6)
.map(|i| calls("bash", json!({"command": format!("echo {i}")})))
.collect();
let p = ScriptedProvider::new(script);
let mut st = State::new("g", "true");
runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
let seen = p.seen.lock().unwrap();
let first = seen.first().unwrap().messages.len();
let last = seen.last().unwrap().messages.len();
assert!(
last > first,
"the baseline is meant to accumulate: {first} -> {last}"
);
}
#[test]
fn a_provider_error_is_reported_as_an_error_not_as_failed_work() {
struct Broken;
impl Provider for Broken {
fn complete(&self, _: &Request) -> Result<Response, ProviderError> {
Err(ProviderError::Auth("bad key".into()))
}
fn model_id(&self) -> String {
"broken".into()
}
}
let d = tempfile::tempdir().unwrap();
let mut st = State::new("g", "true");
let r = Runner {
provider: &Broken,
shell: &StubShell,
fs: &LocalFs,
context: &Conversational,
root: d.path().to_path_buf(),
budget: Budget::default(),
rollback: false,
on_event: None,
research: false,
claim_check: false,
base_check: blyte_agent::run::BaseCheck::None,
};
let (outcome, _) = r.run(&mut st);
assert!(
matches!(outcome, Outcome::Error(_)),
"infrastructure failure must not read as a
failed task: {outcome:?}"
);
}
#[test]
fn the_turn_budget_bounds_a_model_that_never_stops() {
let d = tempfile::tempdir().unwrap();
let script: Vec<_> = (0..500)
.map(|_| calls("bash", json!({"command": "true"})))
.collect();
let p = ScriptedProvider::new(script);
let mut st = State::new("g", "true");
let (outcome, rep) = runner(&p, &StubShell, d.path(), &Conversational, false).run(&mut st);
assert_eq!(outcome, Outcome::BudgetExhausted);
assert_eq!(rep.outcome_turns, 12);
}
struct FailingResetShell {
exec_error: Option<&'static str>,
}
impl Shell for FailingResetShell {
fn exec(&self, command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
let trimmed = command.trim();
if trimmed == "git rev-parse HEAD" {
return Ok(Output {
stdout: "deadbeef1234\n".into(),
stderr: String::new(),
exit_code: 0,
});
}
if trimmed.starts_with("git reset --hard ") {
if let Some(err) = self.exec_error {
return Err(err.into());
}
return Ok(Output {
stdout: String::new(),
stderr: "fatal: unable to create '.git/index.lock': File exists\n".into(),
exit_code: 128,
});
}
Ok(Output {
stdout: String::new(),
stderr: String::new(),
exit_code: 1,
})
}
fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
self.exec(command, cwd, timeout)
}
fn describe(&self) -> String {
String::new()
}
fn available_binaries(
&self,
_cwd: &Path,
_candidates: &[&'static str],
) -> Result<Vec<String>, String> {
Ok(vec!["git".into()])
}
}
#[test]
fn a_failed_rollback_nonzero_exit_ends_the_run_with_an_error() {
let d = tempfile::tempdir().unwrap();
let p = ScriptedProvider::new(vec![says("done"), says("should not run")]);
let shell = FailingResetShell { exec_error: None };
let mut st = State::new("g", "false");
let (outcome, _) = runner(&p, &shell, d.path(), &Conversational, true).run(&mut st);
match outcome {
Outcome::Error(msg) => {
assert!(msg.contains("could not roll back to deadbeef1234"), "{msg}");
assert!(msg.contains("index.lock"), "{msg}");
}
other => panic!("expected Outcome::Error, got {other:?}"),
}
assert_eq!(st.runtime.rollbacks, 0);
assert_eq!(p.seen.lock().unwrap().len(), 1);
}
#[test]
fn a_failed_rollback_exec_error_ends_the_run_with_an_error() {
let d = tempfile::tempdir().unwrap();
let p = ScriptedProvider::new(vec![says("done"), says("should not run")]);
let shell = FailingResetShell {
exec_error: Some("shell session closed"),
};
let mut st = State::new("g", "false");
let (outcome, _) = runner(&p, &shell, d.path(), &Conversational, true).run(&mut st);
match outcome {
Outcome::Error(msg) => {
assert!(msg.contains("could not roll back to deadbeef1234"), "{msg}");
assert!(msg.contains("shell session closed"), "{msg}");
}
other => panic!("expected Outcome::Error, got {other:?}"),
}
assert_eq!(st.runtime.rollbacks, 0);
assert_eq!(p.seen.lock().unwrap().len(), 1);
}
struct FailingProbeShell {
outcome: Result<Output, String>,
}
impl Shell for FailingProbeShell {
fn exec(&self, _command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
self.outcome.clone()
}
fn describe(&self) -> String {
"broken shell".into()
}
}
#[test]
fn a_failed_environment_probe_spawn_error_ends_the_run_with_an_error() {
let d = tempfile::tempdir().unwrap();
let p = ScriptedProvider::new(vec![says("should not run")]);
let shell = FailingProbeShell {
outcome: Err("cannot run command `docker`: No such file or directory".into()),
};
let mut st = State::new("g", "true");
let (outcome, _) = runner(&p, &shell, d.path(), &Conversational, false).run(&mut st);
match outcome {
Outcome::Error(msg) => {
assert!(msg.contains("command -v"), "{msg}");
assert!(msg.contains("No such file or directory"), "{msg}");
}
other => panic!("expected Outcome::Error, got {other:?}"),
}
assert!(p.seen.lock().unwrap().is_empty());
}
#[test]
fn a_failed_environment_probe_nonzero_exit_ends_the_run_with_an_error() {
let d = tempfile::tempdir().unwrap();
let p = ScriptedProvider::new(vec![says("should not run")]);
let shell = FailingProbeShell {
outcome: Ok(Output {
stdout: String::new(),
stderr: "container is not running\n".into(),
exit_code: 125,
}),
};
let mut st = State::new("g", "true");
let (outcome, _) = runner(&p, &shell, d.path(), &Conversational, false).run(&mut st);
match outcome {
Outcome::Error(msg) => {
assert!(msg.contains("command -v"), "{msg}");
assert!(msg.contains("125"), "{msg}");
assert!(msg.contains("container is not running"), "{msg}");
}
other => panic!("expected Outcome::Error, got {other:?}"),
}
assert!(p.seen.lock().unwrap().is_empty());
}