From d64e8a21565c333a2a35ca06984ad460dd2381d5 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:25:33 +0100 Subject: 0.2.0: streaming line-range reads read seeks to offset with a buffered reader and consumes over-long lines without keeping them: 16 MB RSS on a 200 MB file, 0.8s to line 999000. Adds CHANGELOG and the versioning policy. --- CHANGELOG.md | 32 ++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 6 +++ src/tools/fs.rs | 156 +++++++++++++++++++++++++++++++++++++++++++++----------- tests/tools.rs | 63 ++++++++++++++++++++++- 6 files changed, 227 insertions(+), 34 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..f68a04f --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,32 @@ +# Changelog + +Versioning: **MAJOR** for API-breaking changes, **MINOR** for features that do not +break the interface, **PATCH** for bug fixes. + +"Interface" means: CLI flags and their meaning, the session file format, the config +file, and the tool schemas the model sees. Anything a script or a resumed session +could depend on counts as API. + +## 0.2.0 + +### Added +- `read` streams instead of loading the whole file. It seeks to `offset` with a + buffered reader and consumes long lines without keeping them, so memory stays + flat: 16 MB RSS reading a 200 MB file at any offset, 0.8 s to reach line + 999,000. +- Single lines longer than 4 KiB are clipped and marked `…(line truncated)`. + +### Changed +- The truncation marker is now `… more lines; continue with offset=N`. + +## 0.1.0 + +Baseline: the harness as first built, before versioning was defined here. + +- Streaming provider client for OpenCode Go (`chat/completions`), stable + `x-opencode-session` header, retry with backoff. +- Append-only JSONL sessions, `--continue`, `--session`, `--list`. +- Six tools: read, write, edit, bash, grep, glob. +- Approval: first edit of a session with a diff, every bash call. +- Line editor with history and bracketed paste. +- i686 release gate: `GLIBC_2.34` required, verified on `linux/386 debian:12`. diff --git a/Cargo.lock b/Cargo.lock index 9716ba1..449ee7b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "agent686" -version = "0.1.0" +version = "0.2.0" dependencies = [ "crossterm", "libc", diff --git a/Cargo.toml b/Cargo.toml index 2e5e56a..6d0bb14 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.1.0" +version = "0.2.0" edition = "2021" description = "A small coding agent for a 32-bit Debian box" publish = false diff --git a/README.md b/README.md index 19d9585..c44bdec 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,12 @@ docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gat inside UTF-8 characters are covered. `tests/loop.rs` proves a tool call is executed, recorded, and that a denial is returned to the model as data. +## Versioning + +MAJOR for API-breaking changes, MINOR for features that do not break the +interface, PATCH for bug fixes. The interface is the CLI flags, the session file +format, the config file, and the tool schemas. See [CHANGELOG.md](CHANGELOG.md). + ## Design notes - [CONTEXT.md](CONTEXT.md) — what the words mean (session, turn, step, approval). diff --git a/src/tools/fs.rs b/src/tools/fs.rs index 6addf8d..e543cb6 100644 --- a/src/tools/fs.rs +++ b/src/tools/fs.rs @@ -1,9 +1,11 @@ use std::fs; +use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use serde_json::Value; const MAX_LINE_CHARS: usize = 400; +const MAX_LINE_BYTES: usize = 4096; const MAX_READ_LINES: usize = 2000; const MAX_MATCHES: usize = 200; const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; @@ -138,42 +140,134 @@ pub fn read(args: &Value) -> Result { .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 meta = fs::metadata(&path).map_err(|e| format!("{path}: {e}"))?; + if meta.is_dir() { + return Err(format!("{path} is a directory; use glob or grep")); } - 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 - )); + + let file = fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?; + let mut reader = BufReader::with_capacity(64 * 1024, file); + + if let Ok(head) = reader.fill_buf() { + if head.iter().take(8192).any(|&b| b == 0) { + return Err(format!( + "{path}: looks like a binary file and will not be shown" + )); + } + } + + // Skip to the first requested line without buffering what is skipped, so a + // 500 MB log with offset near the end costs a scan, not a 500 MB allocation. + for _ in 1..offset { + match skip_line(&mut reader).map_err(|e| format!("{path}: {e}"))? { + true => {} + false => return Ok(format!("{path} has fewer than {offset} lines")), + } + } + + let mut out = String::new(); + let mut produced = 0usize; + let mut number = offset; + + while produced < limit { + let (bytes, truncated) = match read_line_limited(&mut reader, MAX_LINE_BYTES) + .map_err(|e| format!("{path}: {e}"))? + { + Some(line) => line, + None => break, + }; + let text = String::from_utf8_lossy(&bytes); + let text = text.trim_end_matches('\n'); + let mut rendered = clip(text, MAX_LINE_CHARS); + if truncated { + rendered.push_str(" …(line truncated)"); + } + out.push_str(&format!("{number:>6}\t{rendered}\n")); + produced += 1; + number += 1; + } + + if produced == 0 { + return Ok(if offset == 1 { + format!("{path}: empty file") + } else { + format!("{path} has fewer than {offset} lines") + }); + } + + if let Ok(head) = reader.fill_buf() { + if !head.is_empty() { + out.push_str(&format!("… more lines; continue with offset={number}\n")); + } } + Ok(out) } +/// Consumes one line without keeping it. False at end of file. +fn skip_line(reader: &mut R) -> std::io::Result { + let mut any = false; + loop { + let buf = reader.fill_buf()?; + if buf.is_empty() { + return Ok(any); + } + any = true; + match buf.iter().position(|&b| b == b'\n') { + Some(index) => { + reader.consume(index + 1); + return Ok(true); + } + None => { + let len = buf.len(); + reader.consume(len); + } + } + } +} + +/// Reads one line, keeping at most `max` bytes but consuming the whole line. +/// Returns `(bytes, truncated)`; `None` at end of file. +fn read_line_limited( + reader: &mut R, + max: usize, +) -> std::io::Result, bool)>> { + let mut kept: Vec = Vec::new(); + let mut any = false; + let mut truncated = false; + + loop { + let buf = reader.fill_buf()?; + if buf.is_empty() { + return Ok(if any { Some((kept, truncated)) } else { None }); + } + any = true; + + let newline = buf.iter().position(|&b| b == b'\n'); + let take = match newline { + Some(index) => index + 1, + None => buf.len(), + }; + + if kept.len() < max { + let room = max - kept.len(); + let slice = &buf[..take.min(room)]; + kept.extend_from_slice(slice); + if take > slice.len() { + truncated = true; + } + } else { + truncated = true; + } + + reader.consume(take); + + if newline.is_some() { + return Ok(Some((kept, truncated))); + } + } +} + pub fn grep(args: &Value) -> Result { let pattern = req(args, "pattern")?; if pattern.is_empty() { diff --git a/tests/tools.rs b/tests/tools.rs index 0189af8..3df353f 100644 --- a/tests/tools.rs +++ b/tests/tools.rs @@ -76,7 +76,7 @@ fn read_numbers_lines_and_reports_truncation() { 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("continue with offset=3"), "{text}"); assert!(!text.contains("three"), "{text}"); } @@ -140,3 +140,64 @@ fn unknown_tool_is_an_error_not_a_panic() { let error = tools::run("teleport", &json!({})).err().unwrap(); assert!(error.contains("unknown tool"), "{error}"); } + +#[test] +fn read_streams_large_files_and_reports_the_next_offset() { + let dir = temp_dir("read-large"); + let path = dir.join("big.txt"); + let mut body = String::new(); + for n in 1..=1000 { + body.push_str(&format!("line {n}\n")); + } + fs::write(&path, body).unwrap(); + + let text = tools::run("read", &json!({ "path": path, "offset": 990, "limit": 5 })).unwrap(); + assert!(text.contains(" 990\tline 990"), "{text}"); + assert!(text.contains(" 994\tline 994"), "{text}"); + assert!(!text.contains("line 995"), "{text}"); + assert!(text.contains("continue with offset=995"), "{text}"); +} + +#[test] +fn read_clips_a_single_enormous_line() { + let dir = temp_dir("read-huge-line"); + let path = dir.join("one-line.txt"); + fs::write(&path, "x".repeat(5 * 1024 * 1024)).unwrap(); + + let text = tools::run("read", &json!({ "path": path })).unwrap(); + assert!(text.starts_with(" 1\tx"), "{text}"); + assert!(text.contains("line truncated"), "{text}"); + // Bounded by the per-line cap, not by the file size. + assert!(text.len() < 1000, "read produced {} bytes", text.len()); +} + +#[test] +fn read_reports_an_offset_past_the_end() { + let dir = temp_dir("read-eof"); + let path = dir.join("short.txt"); + fs::write(&path, "only\n").unwrap(); + let text = tools::run("read", &json!({ "path": path, "offset": 9 })).unwrap(); + assert!(text.contains("fewer than 9 lines"), "{text}"); +} + +#[test] +fn read_refuses_binaries_and_directories() { + let dir = temp_dir("read-binary"); + let binary = dir.join("blob.bin"); + fs::write(&binary, [0u8, 1, 2, 3, 0, 9]).unwrap(); + let error = tools::run("read", &json!({ "path": binary })).err().unwrap(); + assert!(error.contains("binary"), "{error}"); + + let error = tools::run("read", &json!({ "path": dir })).err().unwrap(); + assert!(error.contains("is a directory"), "{error}"); +} + +#[test] +fn read_handles_a_missing_trailing_newline() { + let dir = temp_dir("read-no-newline"); + let path = dir.join("f.txt"); + fs::write(&path, "one\ntwo").unwrap(); + let text = tools::run("read", &json!({ "path": path })).unwrap(); + assert!(text.contains(" 2\ttwo"), "{text}"); + assert!(!text.contains("continue with offset"), "{text}"); +} -- cgit v1.2.3