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 --- src/tools/fs.rs | 527 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 527 insertions(+) create mode 100644 src/tools/fs.rs (limited to 'src/tools/fs.rs') diff --git a/src/tools/fs.rs b/src/tools/fs.rs new file mode 100644 index 0000000..6addf8d --- /dev/null +++ b/src/tools/fs.rs @@ -0,0 +1,527 @@ +use std::fs; +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +const MAX_LINE_CHARS: usize = 400; +const MAX_READ_LINES: usize = 2000; +const MAX_MATCHES: usize = 200; +const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; +const PREVIEW_BUDGET: usize = 60; + +const SKIP_DIRS: &[&str] = &[ + ".git", + "target", + "node_modules", + "dist", + "build", + ".venv", + "vendor", + ".cache", +]; + +/// A pending file change. Built and previewed first, applied only after the +/// human agrees. +pub enum Change { + Write { path: String, content: String }, + Edit { path: String, old: String, new: String, text: String }, +} + +impl Change { + pub fn path(&self) -> &str { + match self { + Change::Write { path, .. } | Change::Edit { path, .. } => path, + } + } + + pub fn preview(&self) -> String { + match self { + Change::Write { path, content } => 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) + } + } + } + + pub fn apply(self) -> Result { + match self { + Change::Write { path, content } => { + let parent = Path::new(&path).parent(); + if let Some(parent) = parent { + if !parent.as_os_str().is_empty() && !parent.is_dir() { + return Err(format!( + "parent directory does not exist: {} (create it with bash first)", + parent.display() + )); + } + } + fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?; + 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}"))?; + Ok(format!("edited {path}: 1 replacement at line {line}")) + } + } + } +} + +pub fn plan_write(args: &Value) -> Result { + Ok(Change::Write { + path: req(args, "path")?, + content: req(args, "content")?, + }) +} + +pub fn plan_edit(args: &Value) -> Result { + let path = req(args, "path")?; + let old = req(args, "old")?; + let new = req(args, "new")?; + if old.is_empty() { + 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) + )), + } +} + +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 limit = args + .get("limit") + .and_then(|v| v.as_u64()) + .unwrap_or(MAX_READ_LINES as u64) + .clamp(1, MAX_READ_LINES as u64) as usize; + + let bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?; + if bytes.iter().take(8192).any(|&b| b == 0) { + return Err(format!( + "{path}: looks like a binary file and will not be shown" + )); + } + let text = String::from_utf8_lossy(&bytes); + let lines: Vec<&str> = text.lines().collect(); + if lines.is_empty() { + return Ok(format!("{path}: empty file")); + } + if offset > lines.len() { + return Ok(format!( + "{path} has {} lines; offset {offset} is past the end", + lines.len() + )); + } + + let end = (offset + limit - 1).min(lines.len()); + let mut out = String::with_capacity((end - offset + 2) * 40); + for number in offset..=end { + out.push_str(&format!( + "{number:>6}\t{}\n", + clip(lines[number - 1], MAX_LINE_CHARS) + )); + } + if end < lines.len() { + out.push_str(&format!( + "… {} more line(s); continue with offset={}\n", + lines.len() - end, + end + 1 + )); + } + Ok(out) +} + +pub fn grep(args: &Value) -> Result { + let pattern = req(args, "pattern")?; + if pattern.is_empty() { + return Err("pattern must not be empty".into()); + } + let base = args + .get("path") + .and_then(|v| v.as_str()) + .unwrap_or(".") + .to_string(); + let ignore_case = args + .get("ignore_case") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let needle = if ignore_case { + pattern.to_lowercase() + } else { + pattern.clone() + }; + + let root = Path::new(&base); + let files = if root.is_file() { + vec![root.to_path_buf()] + } else { + let mut files = Vec::new(); + walk(root, &mut files); + files + }; + + let mut out = String::new(); + let mut matches = 0usize; + for file in files { + if matches >= MAX_MATCHES { + break; + } + grep_file(&file, &needle, ignore_case, &mut matches, &mut out); + } + + if matches == 0 { + return Ok(format!("no matches for `{pattern}` under {base}")); + } + if matches >= MAX_MATCHES { + out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n")); + } + Ok(out) +} + +pub fn glob(args: &Value) -> Result { + let pattern = req(args, "pattern")?; + let base = args + .get("path") + .and_then(|v| v.as_str()) + .unwrap_or(".") + .to_string(); + let root = Path::new(&base); + if !root.is_dir() { + return Err(format!("not a directory: {base}")); + } + + let mut files = Vec::new(); + walk(root, &mut files); + + // A pattern without a slash is matched against the file name at any depth. + let bare = !pattern.contains('/'); + let mut hits = Vec::new(); + for file in files { + let name = file.file_name().and_then(|n| n.to_str()).unwrap_or(""); + let hit = if bare { + wildcard_match(pattern.as_bytes(), name.as_bytes()) + } else { + let relative = file + .strip_prefix(root) + .unwrap_or(&file) + .to_string_lossy() + .to_string(); + glob_match(&pattern, &relative) + }; + if hit { + hits.push(file); + if hits.len() >= MAX_MATCHES { + break; + } + } + } + + if hits.is_empty() { + return Ok(format!("no files match `{pattern}` under {base}")); + } + + let mut out = String::new(); + for hit in &hits { + out.push_str(&hit.display().to_string()); + out.push('\n'); + } + if hits.len() >= MAX_MATCHES { + out.push_str(&format!("… stopped after {MAX_MATCHES} files\n")); + } + Ok(out) +} + +fn grep_file(path: &Path, needle_lower: &str, ignore_case: bool, count: &mut usize, out: &mut String) { + let meta = match fs::metadata(path) { + Ok(m) => m, + Err(_) => return, + }; + if meta.len() > MAX_SCAN_BYTES { + return; + } + let bytes = match fs::read(path) { + Ok(b) => b, + Err(_) => return, + }; + if bytes.iter().take(8192).any(|&b| b == 0) { + return; + } + let text = String::from_utf8_lossy(&bytes); + let mut needle = needle_lower.to_string(); + if !ignore_case { + needle = needle.to_string(); + } + + for (index, line) in text.lines().enumerate() { + if *count >= MAX_MATCHES { + return; + } + let hit = if ignore_case { + line.to_lowercase().contains(&needle) + } else { + line.contains(&needle) + }; + if hit { + *count += 1; + out.push_str(&format!( + "{}:{}: {}\n", + path.display(), + index + 1, + clip(line.trim_end(), 200) + )); + } + } +} + +fn walk(dir: &Path, out: &mut Vec) { + let entries = match fs::read_dir(dir) { + Ok(entries) => entries, + Err(_) => return, + }; + for entry in entries.flatten() { + let file_type = match entry.file_type() { + Ok(t) => t, + Err(_) => continue, + }; + let path = entry.path(); + if file_type.is_dir() { + let name = entry.file_name(); + if SKIP_DIRS.iter().any(|skip| name == *skip) { + continue; + } + walk(&path, out); + } else if file_type.is_file() { + out.push(path); + } + } +} + +fn glob_match(pattern: &str, path: &str) -> bool { + let p: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect(); + let s: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); + match_segments(&p, &s) +} + +fn match_segments(pattern: &[&str], path: &[&str]) -> bool { + match pattern.split_first() { + None => path.is_empty(), + Some((&"**", rest)) => { + if match_segments(rest, path) { + return true; + } + for skip in 0..path.len() { + if match_segments(rest, &path[skip + 1..]) { + return true; + } + } + false + } + Some((segment, rest)) => match path.split_first() { + None => false, + Some((name, tail)) => { + wildcard_match(segment.as_bytes(), name.as_bytes()) && match_segments(rest, tail) + } + }, + } +} + +fn wildcard_match(pattern: &[u8], text: &[u8]) -> bool { + match pattern.split_first() { + None => text.is_empty(), + Some((&b'*', rest)) => (0..=text.len()).any(|skip| wildcard_match(rest, &text[skip..])), + Some((&b'?', rest)) => !text.is_empty() && wildcard_match(rest, &text[1..]), + Some((byte, rest)) => match text.split_first() { + Some((first, tail)) => first == byte && wildcard_match(rest, tail), + None => false, + }, + } +} + +fn new_file_preview(path: &str, content: &str) -> String { + let lines: Vec<&str> = content.lines().collect(); + let mut out = format!("@@ new file {path} ({} lines) @@\n", lines.len()); + for line in lines.iter().take(PREVIEW_BUDGET) { + out.push_str(&format!("+ {}\n", clip(line, 200))); + } + if lines.len() > PREVIEW_BUDGET { + out.push_str(&format!("… {} more line(s)\n", lines.len() - PREVIEW_BUDGET)); + } + out +} + +fn diff_preview(old: &str, new: &str) -> String { + let a: Vec<&str> = old.lines().collect(); + let b: Vec<&str> = new.lines().collect(); + + let mut prefix = 0; + while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] { + prefix += 1; + } + let mut suffix = 0; + while suffix < a.len().saturating_sub(prefix) + && suffix < b.len().saturating_sub(prefix) + && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix] + { + suffix += 1; + } + + let start = prefix.saturating_sub(2); + let a_end = a.len() - suffix; + let b_end = b.len() - suffix; + + let mut out = format!( + "@@ -{},{} +{},{} @@\n", + start + 1, + a_end.saturating_sub(start), + start + 1, + b_end.saturating_sub(start) + ); + let mut budget = PREVIEW_BUDGET; + + for line in &a[start..prefix] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + for line in &a[prefix..a_end] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("- {}\n", clip(line, 200))); + } + for line in &b[prefix..b_end] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("+ {}\n", clip(line, 200))); + } + for line in a[a_end..(a_end + 2).min(a.len())].iter() { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + if budget == 0 { + out.push_str("… diff truncated\n"); + } + out +} + +fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String { + let lines: Vec<&str> = text.lines().collect(); + let line_no = text[..at].matches('\n').count() + 1; + let old_lines = old.lines().count().max(1); + + let mut out = format!("@@ {path}:{line_no} @@\n"); + let mut budget = PREVIEW_BUDGET; + + let before_start = (line_no - 1).saturating_sub(2); + for line in &lines[before_start..line_no.saturating_sub(1)] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + for line in old.lines() { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("- {}\n", clip(line, 200))); + } + for line in new.lines() { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("+ {}\n", clip(line, 200))); + } + let after_start = (line_no - 1 + old_lines).min(lines.len()); + for line in &lines[after_start..(after_start + 2).min(lines.len())] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + if budget == 0 { + out.push_str("… diff truncated\n"); + } + out +} + +fn line_list(text: &str, offsets: &[usize]) -> String { + let mut numbers: Vec = offsets + .iter() + .take(10) + .map(|&at| (text[..at].matches('\n').count() + 1).to_string()) + .collect(); + if offsets.len() > 10 { + numbers.push("…".into()); + } + numbers.join(", ") +} + +fn req(args: &Value, key: &str) -> Result { + match args.get(key).and_then(|v| v.as_str()) { + Some(value) => Ok(value.to_string()), + None => Err(format!("missing required argument `{key}`")), + } +} + +fn clip(s: &str, max: usize) -> String { + if s.chars().count() <= max { + return s.to_string(); + } + let cut: String = s.chars().take(max).collect(); + format!("{cut}…") +} -- cgit v1.2.3