From 343f2a8a6148b8004d6f4d74fb779b4f30c9686a Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 03:11:22 +0100 Subject: M1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate - append-only JSONL sessions with --continue/--session; reasoning stored, stripped on replay - read/write/edit/grep/glob + bash with timeout and capped output - diff-preview approval for the first edit of a session, per-call approval for bash - system prompt frozen per session with AGENTS.md snapshot and change warning - SIGINT aborts the turn, second Ctrl-C exits - glibc gate ignores weak symbols; verified in linux/386 debian:12 - acceptance test (calculator in C) passes on both x86-64 and i386 --- tests/loop.rs | 192 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ tests/mock.rs | 5 ++ tests/tools.rs | 142 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 339 insertions(+) create mode 100644 tests/loop.rs create mode 100644 tests/tools.rs (limited to 'tests') diff --git a/tests/loop.rs b/tests/loop.rs new file mode 100644 index 0000000..d77d890 --- /dev/null +++ b/tests/loop.rs @@ -0,0 +1,192 @@ +use std::fs; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; +use std::thread; + +use serde_json::json; + +use agent686::agent; +use agent686::config::Config; +use agent686::session::Session; +use agent686::ui::Approver; + +fn sse(body: &str) -> String { + format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{body}" + ) +} + +/// Serves one canned SSE response per connection, in order. +fn serve_sequence(responses: Vec) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + thread::spawn(move || { + for response in responses { + let (mut stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + break; + } + if line == "\r\n" || line == "\n" { + break; + } + if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0u8; length]; + let _ = reader.read_exact(&mut body); + let _ = stream.write_all(response.as_bytes()); + let _ = stream.flush(); + } + }); + format!("http://{addr}") +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("agent686-loop-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn runs_a_tool_call_then_finishes_and_records_every_message() { + let dir = temp_dir("write"); + let target = dir.join("hello.txt"); + let arguments = json!({ + "path": target.display().to_string(), + "content": "hello from the mock\n" + }) + .to_string(); + + let tool_round = sse(&format!( + "data: {}\n\ndata: [DONE]\n\n", + json!({ + "choices": [{ + "delta": { "tool_calls": [{ + "index": 0, + "id": "call_1", + "function": { "name": "write", "arguments": arguments } + }]}, + "finish_reason": "tool_calls" + }] + }) + )); + let final_round = sse( + "data: {\"choices\":[{\"delta\":{\"content\":\"done\"},\"finish_reason\":\"stop\"}]}\n\n\ + data: [DONE]\n\n", + ); + + let base = serve_sequence(vec![tool_round, final_round]); + + std::env::set_var("AGENT686_DATA", dir.join("data")); + + let system = agent::system_prompt(); + let mut session = Session::create("test-model", &system).unwrap(); + let cfg = Config { + base_url: base, + api_key: "test-key".into(), + model: "test-model".into(), + session: session.id.clone(), + yolo: true, + }; + let mut history = agent::new_history(system); + let mut approver = Approver::new(true); + + agent::run_turn( + &cfg, + &mut session, + &mut history, + "write a file", + &AtomicBool::new(false), + &mut approver, + ) + .expect("turn should complete"); + + assert_eq!( + fs::read_to_string(&target).unwrap(), + "hello from the mock\n" + ); + + // system, user, assistant(tool_calls), tool result, assistant(final) + assert_eq!(history.len(), 5); + assert_eq!(history[3]["role"], "tool"); + assert_eq!(history[3]["tool_call_id"], "call_1"); + + let log = fs::read_to_string(session.path()).unwrap(); + let lines: Vec<&str> = log.lines().collect(); + assert_eq!(lines.len(), 5, "header plus four messages: {log}"); + assert!(lines[0].contains("\"t\":\"header\"")); + assert_eq!(lines[3].contains("\"role\":\"tool\""), true); +} + +#[test] +fn a_denied_tool_call_is_returned_as_data() { + let dir = temp_dir("denied"); + let target = dir.join("never.txt"); + let arguments = json!({ + "path": target.display().to_string(), + "content": "should not exist" + }) + .to_string(); + + let tool_round = sse(&format!( + "data: {}\n\ndata: [DONE]\n\n", + json!({ + "choices": [{ + "delta": { "tool_calls": [{ + "index": 0, + "id": "call_1", + "function": { "name": "write", "arguments": arguments } + }]}, + "finish_reason": "tool_calls" + }] + }) + )); + let final_round = sse( + "data: {\"choices\":[{\"delta\":{\"content\":\"understood\"},\"finish_reason\":\"stop\"}]}\n\n\ + data: [DONE]\n\n", + ); + + let base = serve_sequence(vec![tool_round, final_round]); + std::env::set_var("AGENT686_DATA", dir.join("data")); + + let system = agent::system_prompt(); + let mut session = Session::create("test-model", &system).unwrap(); + let cfg = Config { + base_url: base, + api_key: "test-key".into(), + model: "test-model".into(), + session: session.id.clone(), + yolo: false, + }; + let mut history = agent::new_history(system); + // Not a terminal, so the approver must deny rather than block. + let mut approver = Approver::new(false); + + agent::run_turn( + &cfg, + &mut session, + &mut history, + "write a file", + &AtomicBool::new(false), + &mut approver, + ) + .expect("a denial is not a failed turn"); + + assert!(!target.exists()); + assert_eq!(history[3]["role"], "tool"); + assert!( + history[3]["content"] + .as_str() + .unwrap() + .contains("denied by the user") + ); + assert_eq!(history[4]["content"], "understood"); +} diff --git a/tests/mock.rs b/tests/mock.rs index 80d965b..52dec7c 100644 --- a/tests/mock.rs +++ b/tests/mock.rs @@ -73,6 +73,7 @@ fn config(base_url: String) -> Config { api_key: "test-key".into(), model: "test-model".into(), session: "testsession".into(), + yolo: true, } } @@ -94,6 +95,7 @@ fn streams_text_reasoning_and_usage() { let outcome = provider::chat( &config(base), &[json!({ "role": "user", "content": "hi" })], + &[], &AtomicBool::new(false), &mut sink, ) @@ -133,6 +135,7 @@ fn assembles_tool_call_arguments_byte_for_byte() { let outcome = provider::chat( &config(base), &[json!({ "role": "user", "content": "read a.txt" })], + &[], &AtomicBool::new(false), &mut sink, ) @@ -161,6 +164,7 @@ fn surfaces_provider_error_text() { let error = provider::chat( &config(base), &[json!({ "role": "user", "content": "hi" })], + &[], &AtomicBool::new(false), &mut sink, ) @@ -184,6 +188,7 @@ fn honours_a_cancelled_turn() { let error = provider::chat( &config(base), &[json!({ "role": "user", "content": "hi" })], + &[], &AtomicBool::new(true), &mut sink, ) diff --git a/tests/tools.rs b/tests/tools.rs new file mode 100644 index 0000000..0189af8 --- /dev/null +++ b/tests/tools.rs @@ -0,0 +1,142 @@ +use std::fs; +use std::path::PathBuf; +use std::time::Duration; + +use serde_json::json; + +use agent686::tools::{self, shell}; + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("agent686-test-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn edit_refuses_ambiguous_and_missing_text() { + let dir = temp_dir("edit-ambiguous"); + let path = dir.join("a.txt"); + fs::write(&path, "alpha\nbeta\nalpha\n").unwrap(); + + let error = tools::plan("edit", &json!({ "path": path, "old": "alpha", "new": "gamma" })) + .err() + .expect("ambiguous edit must fail"); + assert!(error.contains("appears 2 times"), "{error}"); + assert!(error.contains("lines 1, 3"), "{error}"); + + let error = tools::plan("edit", &json!({ "path": path, "old": "nope", "new": "x" })) + .err() + .expect("missing text must fail"); + assert!(error.contains("was not found"), "{error}"); + + // The file is untouched by a refused plan. + assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta\nalpha\n"); +} + +#[test] +fn edit_applies_exactly_one_replacement() { + let dir = temp_dir("edit-apply"); + let path = dir.join("main.c"); + fs::write(&path, "int main(void) {\n return 0;\n}\n").unwrap(); + + let change = tools::plan( + "edit", + &json!({ "path": path, "old": " return 0;", "new": " return 1;" }), + ) + .expect("unique edit should plan"); + + let preview = change.preview(); + assert!(preview.contains("- return 0;"), "{preview}"); + assert!(preview.contains("+ return 1;"), "{preview}"); + + let outcome = change.apply().expect("apply should succeed"); + assert!(outcome.contains("1 replacement at line 2"), "{outcome}"); + assert_eq!( + fs::read_to_string(&path).unwrap(), + "int main(void) {\n return 1;\n}\n" + ); +} + +#[test] +fn write_does_not_create_parent_directories() { + let dir = temp_dir("write-parent"); + let path = dir.join("missing").join("file.txt"); + let change = tools::plan("write", &json!({ "path": path, "content": "hi" })).unwrap(); + let error = change.apply().err().expect("apply must fail"); + assert!(error.contains("parent directory does not exist"), "{error}"); +} + +#[test] +fn read_numbers_lines_and_reports_truncation() { + let dir = temp_dir("read"); + let path = dir.join("f.txt"); + fs::write(&path, "one\ntwo\nthree\nfour\n").unwrap(); + + let text = tools::run("read", &json!({ "path": path, "limit": 2 })).unwrap(); + assert!(text.contains(" 1\tone"), "{text}"); + assert!(text.contains(" 2\ttwo"), "{text}"); + assert!(text.contains("2 more line(s); continue with offset=3"), "{text}"); + assert!(!text.contains("three"), "{text}"); +} + +#[test] +fn grep_finds_lines_and_honours_case() { + let dir = temp_dir("grep"); + let path = dir.join("f.txt"); + fs::write(&path, "alpha\nbeta\nALPHA\n").unwrap(); + + let text = tools::run("grep", &json!({ "pattern": "alpha", "path": dir })).unwrap(); + assert_eq!(text.lines().count(), 1, "{text}"); + + let text = tools::run( + "grep", + &json!({ "pattern": "alpha", "path": dir, "ignore_case": true }), + ) + .unwrap(); + assert_eq!(text.lines().count(), 2, "{text}"); +} + +#[test] +fn glob_supports_double_star_and_bare_names() { + let dir = temp_dir("glob"); + fs::create_dir_all(dir.join("sub/deep")).unwrap(); + fs::write(dir.join("a.rs"), "").unwrap(); + fs::write(dir.join("sub/b.rs"), "").unwrap(); + fs::write(dir.join("sub/deep/c.rs"), "").unwrap(); + fs::write(dir.join("sub/note.txt"), "").unwrap(); + + let text = tools::run("glob", &json!({ "pattern": "**/*.rs", "path": dir })).unwrap(); + assert_eq!(text.lines().count(), 3, "{text}"); + + let text = tools::run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap(); + assert_eq!(text.lines().count(), 3, "{text}"); + + let text = tools::run("glob", &json!({ "pattern": "sub/*.rs", "path": dir })).unwrap(); + assert_eq!(text.lines().count(), 1, "{text}"); + assert!(text.contains("b.rs"), "{text}"); +} + +#[test] +fn bash_reports_exit_code_and_times_out() { + let text = tools::run("bash", &json!({ "cmd": "echo hi; exit 3" })).unwrap(); + assert!(text.contains("hi"), "{text}"); + assert!(text.contains("[exit 3]"), "{text}"); + + let text = shell::bash(&json!({ "cmd": "sleep 5" }), Duration::from_millis(150)).unwrap(); + assert!(text.contains("timed out after"), "{text}"); +} + +#[test] +fn bash_rejects_a_missing_cwd() { + let error = tools::run("bash", &json!({ "cmd": "true", "cwd": "/nonexistent-dir-xyz" })) + .err() + .expect("missing cwd must fail"); + assert!(error.contains("cwd is not a directory"), "{error}"); +} + +#[test] +fn unknown_tool_is_an_error_not_a_panic() { + let error = tools::run("teleport", &json!({})).err().unwrap(); + assert!(error.contains("unknown tool"), "{error}"); +} -- cgit v1.2.3