From a39ea052deff856ff9d27cdebecbbea1837d5a69 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:40:13 +0100 Subject: 0.4.4: file-tool correctness - read: regular files only, checked offset conversion on 32-bit - write/edit: atomic rename, re-read before apply, preserve mode - edit: CRLF files match and keep their line endings - grep: missing path is an error, skipped files are reported - glob: follows file symlinks --- CHANGELOG.md | 20 +++++ Cargo.lock | 2 +- Cargo.toml | 2 +- src/agent.rs | 19 +++-- src/tools/fs.rs | 258 ++++++++++++++++++++++++++++++++++++++++++++------------ tests/tools.rs | 110 +++++++++++++++++++++++- 6 files changed, 346 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79acd31..213f5f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,26 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.4.4 + +### Fixed +- `read` refused only directories; a FIFO or device would block the single-threaded + harness forever. It now requires a regular file. +- `read`'s `offset` was cast from `u64` to `usize`, which wrapped on 32-bit builds + and produced wrong line numbers. Out-of-range values are now an error. +- `write` truncates in place, so a crash or full disk could destroy the original. + It now writes a temporary file and renames, and preserves the file mode. +- `edit` applied the snapshot taken before the approval prompt, silently + discarding anything written in between. It now re-reads and re-checks at apply + time and refuses if the text is no longer unique. +- `edit` reported "not found" for CRLF files, because the carriage returns are + invisible in `read` output. Matching now retries with normalised line endings + and writes back in the file's own style. +- `grep` on a nonexistent path said "no matches", implying the symbol was absent; + it now errors. It also reports how many files it skipped as too large or binary. +- `glob` now includes symlinked files (symlinked directories are still skipped, to + avoid loops). + ## 0.4.3 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index 0d49260..f42e359 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "agent686" -version = "0.4.2" +version = "0.4.3" dependencies = [ "crossterm", "libc", diff --git a/Cargo.toml b/Cargo.toml index faf882f..8b28d2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.4.3" +version = "0.4.4" edition = "2021" description = "A small coding agent for a 32-bit Debian box" publish = false diff --git a/src/agent.rs b/src/agent.rs index 9e2a431..77807ae 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -302,16 +302,19 @@ fn execute( Err(error) => ToolOutcome::Failed(error), }, Approval::Once => match tools::plan(&call.name, &args) { - Ok(change) => { - if approver.allow_edit(change.path(), &change.preview()) { - match change.apply() { - Ok(output) => ToolOutcome::Ok(output), - Err(error) => ToolOutcome::Failed(error), + Ok(change) => match change.preview() { + Ok(preview) => { + if approver.allow_edit(change.path(), &preview) { + match change.apply() { + Ok(output) => ToolOutcome::Ok(output), + Err(error) => ToolOutcome::Failed(error), + } + } else { + ToolOutcome::Denied } - } else { - ToolOutcome::Denied } - } + Err(error) => ToolOutcome::Failed(error), + }, Err(error) => ToolOutcome::Failed(error), }, Approval::EveryCall => { diff --git a/src/tools/fs.rs b/src/tools/fs.rs index caa3992..947649f 100644 --- a/src/tools/fs.rs +++ b/src/tools/fs.rs @@ -1,6 +1,7 @@ use std::fs; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; use serde_json::Value; @@ -23,10 +24,11 @@ const SKIP_DIRS: &[&str] = &[ ]; /// A pending file change. Built and previewed first, applied only after the -/// human agrees. +/// human agrees. The file is re-read at apply time, so an edit made while the +/// approval prompt was open is not silently discarded. pub enum Change { Write { path: String, content: String }, - Edit { path: String, old: String, new: String, text: String }, + Edit { path: String, old: String, new: String }, } impl Change { @@ -36,21 +38,17 @@ impl Change { } } - pub fn preview(&self) -> String { + pub fn preview(&self) -> Result { match self { - Change::Write { path, content } => match fs::read_to_string(path) { + Change::Write { path, content } => Ok(match fs::read_to_string(path) { Ok(old) if old == *content => format!("{path}: unchanged"), Ok(old) => diff_preview(&old, content), Err(_) => new_file_preview(path, content), - }, - Change::Edit { - path, - old, - new, - text, - } => { - let at = text.find(old.as_str()).unwrap_or(0); - edit_preview(path, text, old, new, at) + }), + Change::Edit { path, old, new } => { + let text = fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?; + let span = locate(&text, old)?; + Ok(edit_preview(path, &text, &span, old, new)) } } } @@ -67,31 +65,166 @@ impl Change { )); } } - fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?; + atomic_write(&path, &content)?; Ok(format!( "wrote {} bytes ({} lines) to {path}", content.len(), content.lines().count() )) } - Change::Edit { - path, - old, - new, - mut text, - } => { - let at = text - .find(old.as_str()) - .ok_or_else(|| format!("{path}: text to replace disappeared"))?; - let line = text[..at].matches('\n').count() + 1; - text.replace_range(at..at + old.len(), &new); - fs::write(&path, &text).map_err(|e| format!("{path}: {e}"))?; + Change::Edit { path, old, new } => { + let mut text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; + let span = locate(&text, &old)?; + let line = text[..span.start].matches('\n').count() + 1; + // Keep the file's line-ending style. + let replacement = if span.crlf { + new.replace("\r\n", "\n").replace('\n', "\r\n") + } else { + new.clone() + }; + text.replace_range(span.start..span.end, &replacement); + atomic_write(&path, &text)?; Ok(format!("edited {path}: 1 replacement at line {line}")) } } } } +/// Where the text to replace sits in the file, and whether the file uses CRLF. +struct Span { + start: usize, + end: usize, + crlf: bool, +} + +fn locate(text: &str, old: &str) -> Result { + let exact: Vec = text.match_indices(old).map(|(index, _)| index).collect(); + match exact.len() { + 1 => { + return Ok(Span { + start: exact[0], + end: exact[0] + old.len(), + crlf: false, + }) + } + 0 => {} + many => { + return Err(format!( + "text to replace appears {many} times (lines {}); include more \ + surrounding context so it is unique.", + line_list(text, &exact) + )) + } + } + + // A CRLF file shows up in `read` with a trailing carriage return the model + // cannot see. Retry with line endings normalised rather than reporting + // "not found" for text that is visibly there. + if text.contains("\r\n") { + let normalized = text.replace("\r\n", "\n"); + let wanted = old.replace("\r\n", "\n"); + let hits: Vec = normalized + .match_indices(&wanted) + .map(|(index, _)| index) + .collect(); + match hits.len() { + 1 => { + let start = original_offset(text, hits[0]); + if let Some(end) = original_range(text, start, &wanted) { + return Ok(Span { + start, + end, + crlf: true, + }); + } + } + many if many > 1 => { + let lines: Vec = hits + .iter() + .take(10) + .map(|hit| (normalized[..*hit].matches('\n').count() + 1).to_string()) + .collect(); + return Err(format!( + "text to replace appears {many} times in this CRLF file (lines {}); \ + include more surrounding context so it is unique.", + lines.join(", ") + )); + } + _ => {} + } + } + + Err("text to replace was not found. Read the file and copy the exact text, \ + including indentation." + .to_string()) +} + +/// Byte offset in the original text for an offset in the CRLF-normalised text. +fn original_offset(text: &str, target: usize) -> usize { + let bytes = text.as_bytes(); + let mut original = 0usize; + let mut normalized = 0usize; + while original < bytes.len() && normalized < target { + if bytes[original] == b'\r' && bytes.get(original + 1) == Some(&b'\n') { + original += 2; + } else { + original += 1; + } + normalized += 1; + } + original +} + +/// End offset in the original text for a normalised match of `wanted`. +fn original_range(text: &str, start: usize, wanted: &str) -> Option { + let bytes = text.as_bytes(); + let mut cursor = start; + for byte in wanted.bytes() { + if byte == b'\n' { + if bytes.get(cursor) == Some(&b'\r') && bytes.get(cursor + 1) == Some(&b'\n') { + cursor += 2; + } else if bytes.get(cursor) == Some(&b'\n') { + cursor += 1; + } else { + return None; + } + } else { + if bytes.get(cursor) != Some(&byte) { + return None; + } + cursor += 1; + } + } + Some(cursor) +} + +/// Write via a temporary file and rename, so a crash or a full disk leaves the +/// original intact instead of a half-written file. +fn atomic_write(path: &str, content: &str) -> Result<(), String> { + let target = Path::new(path); + let parent = match target.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(), + _ => PathBuf::from("."), + }; + let temp = parent.join(format!( + ".agent686-{}-{}.tmp", + std::process::id(), + TEMP_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + + fs::write(&temp, content).map_err(|e| format!("{}: {e}", temp.display()))?; + if let Ok(meta) = fs::metadata(target) { + let _ = fs::set_permissions(&temp, meta.permissions()); + } + if let Err(error) = fs::rename(&temp, target) { + let _ = fs::remove_file(&temp); + return Err(format!("{path}: {error}")); + } + Ok(()) +} + +static TEMP_COUNTER: AtomicUsize = AtomicUsize::new(0); + pub fn plan_write(args: &Value) -> Result { Ok(Change::Write { path: req(args, "path")?, @@ -107,33 +240,16 @@ pub fn plan_edit(args: &Value) -> Result { return Err("`old` must not be empty; use write to create a file".into()); } let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; - let hits: Vec = text.match_indices(&old).map(|(i, _)| i).collect(); - match hits.len() { - 0 => Err(format!( - "text to replace was not found in {path}. Read the file and copy the exact \ - text, including indentation." - )), - 1 => Ok(Change::Edit { - path, - old, - new, - text, - }), - n => Err(format!( - "text to replace appears {n} times in {path} (lines {}); include more \ - surrounding context so it is unique.", - line_list(&text, &hits) - )), - } + // Fail before the approval prompt if the match is unusable. + locate(&text, &old)?; + Ok(Change::Edit { path, old, new }) } pub fn read(args: &Value) -> Result { let path = req(args, "path")?; - let offset = args - .get("offset") - .and_then(|v| v.as_u64()) - .unwrap_or(1) - .max(1) as usize; + let offset = args.get("offset").and_then(|v| v.as_u64()).unwrap_or(1).max(1); + let offset = usize::try_from(offset) + .map_err(|_| format!("offset {offset} is too large for this build"))?; let limit = args .get("limit") .and_then(|v| v.as_u64()) @@ -144,6 +260,11 @@ pub fn read(args: &Value) -> Result { if meta.is_dir() { return Err(format!("{path} is a directory; use glob or grep")); } + if !meta.is_file() { + // A FIFO or a device would block forever, and this process is single + // threaded, so nothing could interrupt it. + return Err(format!("{path} is not a regular file")); + } let file = fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?; let mut reader = BufReader::with_capacity(64 * 1024, file); @@ -331,6 +452,9 @@ pub fn grep(args: &Value) -> Result { }; let root = Path::new(&base); + if !root.exists() { + return Err(format!("{base}: no such file or directory")); + } let files = if root.is_file() { vec![root.to_path_buf()] } else { @@ -341,19 +465,32 @@ pub fn grep(args: &Value) -> Result { let mut out = String::new(); let mut matches = 0usize; + let mut skipped = 0usize; for file in files { if matches >= MAX_MATCHES { break; } - grep_file(&file, &matcher, &mut matches, &mut out); + grep_file(&file, &matcher, &mut matches, &mut skipped, &mut out); } if matches == 0 { - return Ok(format!("no matches for `{pattern}` under {base}")); + let mut message = format!("no matches for `{pattern}` under {base}"); + if skipped > 0 { + message.push_str(&format!( + "\n({skipped} file(s) not searched: larger than 4 MiB or binary)" + )); + } + return Ok(message); } if matches >= MAX_MATCHES { out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n")); } + if skipped > 0 { + out.push_str(&format!( + "({skipped} file(s) not searched: larger than {} or binary)\n", + "4 MiB" + )); + } Ok(out) } @@ -410,12 +547,19 @@ pub fn glob(args: &Value) -> Result { Ok(out) } -fn grep_file(path: &Path, matcher: &Matcher, count: &mut usize, out: &mut String) { +fn grep_file( + path: &Path, + matcher: &Matcher, + count: &mut usize, + skipped: &mut usize, + out: &mut String, +) { let meta = match fs::metadata(path) { Ok(m) => m, Err(_) => return, }; if meta.len() > MAX_SCAN_BYTES { + *skipped += 1; return; } let bytes = match fs::read(path) { @@ -423,6 +567,7 @@ fn grep_file(path: &Path, matcher: &Matcher, count: &mut usize, out: &mut String Err(_) => return, }; if bytes.iter().take(8192).any(|&b| b == 0) { + *skipped += 1; return; } let text = String::from_utf8_lossy(&bytes); @@ -462,6 +607,11 @@ fn walk(dir: &Path, out: &mut Vec) { walk(&path, out); } else if file_type.is_file() { out.push(path); + } else if file_type.is_symlink() && fs::metadata(&path).map(|m| m.is_file()).unwrap_or(false) + { + // Follow file symlinks; symlinked directories are skipped so a loop + // cannot walk forever. + out.push(path); } } } @@ -582,9 +732,9 @@ fn diff_preview(old: &str, new: &str) -> String { out } -fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String { +fn edit_preview(path: &str, text: &str, span: &Span, old: &str, new: &str) -> String { let lines: Vec<&str> = text.lines().collect(); - let line_no = text[..at].matches('\n').count() + 1; + let line_no = text[..span.start].matches('\n').count() + 1; let old_lines = old.lines().count().max(1); let mut out = format!("@@ {path}:{line_no} @@\n"); diff --git a/tests/tools.rs b/tests/tools.rs index c30128e..77c1698 100644 --- a/tests/tools.rs +++ b/tests/tools.rs @@ -51,7 +51,7 @@ fn edit_applies_exactly_one_replacement() { ) .expect("unique edit should plan"); - let preview = change.preview(); + let preview = change.preview().unwrap(); assert!(preview.contains("- return 0;"), "{preview}"); assert!(preview.contains("+ return 1;"), "{preview}"); @@ -311,3 +311,111 @@ fn bash_does_not_inherit_the_api_key() { std::env::remove_var("OPENCODE_API_KEY"); assert!(text.contains('0'), "the key was visible to the child: {text}"); } + +#[test] +fn edit_matches_crlf_files_without_visible_carriage_returns() { + let dir = temp_dir("edit-crlf"); + let path = dir.join("win.c"); + fs::write(&path, "int main(void) {\r\n return 0;\r\n}\r\n").unwrap(); + + // The model copies what `read` showed it: plain newlines. + let change = tools::plan( + "edit", + &json!({ + "path": path, + "old": "int main(void) {\n return 0;\n", + "new": "int main(void) {\n return 1;\n" + }), + ) + .expect("CRLF file should still match"); + + change.apply().expect("apply should succeed"); + assert_eq!( + fs::read_to_string(&path).unwrap(), + "int main(void) {\r\n return 1;\r\n}\r\n" + ); +} + +#[test] +fn edit_refuses_when_the_file_changed_while_waiting_for_approval() { + let dir = temp_dir("edit-concurrent"); + let path = dir.join("f.txt"); + fs::write(&path, "alpha\n").unwrap(); + + let change = tools::plan("edit", &json!({ "path": path, "old": "alpha", "new": "beta" })) + .unwrap(); + // Something else (cargo fmt, the user's editor) ran before approval. + fs::write(&path, "alpha\nalpha\n").unwrap(); + + let error = change.apply().err().expect("apply must refuse"); + assert!(error.contains("appears 2 times"), "{error}"); + assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nalpha\n"); +} + +#[test] +fn write_preserves_the_existing_file_mode() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir("write-mode"); + let path = dir.join("script.sh"); + fs::write(&path, "old").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + + tools::plan("write", &json!({ "path": path, "content": "new" })) + .unwrap() + .apply() + .unwrap(); + + let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o755); + assert_eq!(fs::read_to_string(&path).unwrap(), "new"); +} + +#[test] +fn read_refuses_special_files() { + let dir = temp_dir("read-fifo"); + let path = dir.join("fifo"); + let name = std::ffi::CString::new(path.to_str().unwrap()).unwrap(); + let made = unsafe { libc::mkfifo(name.as_ptr(), 0o600) }; + assert_eq!(made, 0, "could not create a fifo"); + + let error = run("read", &json!({ "path": path })).err().unwrap(); + assert!(error.contains("not a regular file"), "{error}"); +} + +#[test] +fn grep_errors_on_a_missing_path_instead_of_reporting_no_matches() { + let dir = temp_dir("grep-missing"); + let error = run( + "grep", + &json!({ "pattern": "needle", "path": dir.join("does-not-exist") }), + ) + .err() + .expect("missing path must be an error"); + assert!(error.contains("no such file or directory"), "{error}"); +} + +#[test] +fn grep_says_when_it_skipped_files() { + let dir = temp_dir("grep-skip"); + let mut body = String::from("needle\n"); + body.push_str(&"x".repeat(5 * 1024 * 1024)); + fs::write(dir.join("big.txt"), body).unwrap(); + + let text = run("grep", &json!({ "pattern": "needle", "path": dir })).unwrap(); + assert!(text.contains("not searched"), "{text}"); +} + +#[test] +fn glob_follows_file_symlinks_but_not_directories() { + let dir = temp_dir("glob-symlink"); + fs::create_dir_all(dir.join("real-dir")).unwrap(); + fs::write(dir.join("real-dir/inner.rs"), "").unwrap(); + fs::write(dir.join("real.rs"), "").unwrap(); + std::os::unix::fs::symlink(dir.join("real.rs"), dir.join("link.rs")).unwrap(); + std::os::unix::fs::symlink(dir.join("real-dir"), dir.join("link-dir")).unwrap(); + + let text = run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap(); + assert!(text.contains("real.rs"), "{text}"); + assert!(text.contains("link.rs"), "{text}"); + assert!(text.contains("inner.rs"), "{text}"); +} -- cgit v1.2.3