use std::fs;
use std::io::{self, BufRead, Seek, SeekFrom};
use std::path::{Path, PathBuf};
const OFFSETS_DIR: &str = ".subagent_offsets";
pub fn transcripts(transcript_path: &Path) -> Vec<PathBuf> {
let (Some(dir), Some(session)) = (transcript_path.parent(), transcript_path.file_stem()) else {
return vec![];
};
let Ok(entries) = fs::read_dir(dir.join(session).join("subagents")) else {
return vec![];
};
let mut files: Vec<PathBuf> = entries
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.is_file())
.filter(|p| {
p.file_name()
.and_then(|n| n.to_str())
.and_then(|n| n.strip_prefix("agent-"))
.and_then(|n| n.strip_suffix(".jsonl"))
.is_some_and(|id| !id.is_empty() && !id.contains('.'))
})
.collect();
files.sort();
files
}
pub fn offset_path(session_dir: &Path, transcript: &Path) -> PathBuf {
let stem = transcript.file_stem().unwrap_or_default();
session_dir.join(OFFSETS_DIR).join(stem)
}
pub fn write_offset(offset_path: &Path, offset: i64) -> io::Result<()> {
let Some(dir) = offset_path.parent() else {
return fs::write(offset_path, offset.to_string());
};
fs::create_dir_all(dir)?;
let tmp = offset_path.with_extension(format!("tmp.{}", uuid::Uuid::now_v7()));
fs::write(&tmp, offset.to_string())?;
fs::rename(&tmp, offset_path).inspect_err(|_| {
let _ = fs::remove_file(&tmp);
})
}
pub fn try_lock(offset_path: &Path) -> io::Result<Option<fs::File>> {
if let Some(dir) = offset_path.parent() {
fs::create_dir_all(dir)?;
}
let file = fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(offset_path.with_extension("lock"))?;
match file.try_lock() {
Ok(()) => Ok(Some(file)),
Err(fs::TryLockError::WouldBlock) => Ok(None),
Err(fs::TryLockError::Error(e)) => Err(e),
}
}
pub fn read_new_lines(
transcript: &Path,
offset_path: &Path,
) -> io::Result<(Vec<serde_json::Value>, i64, i64)> {
let start: i64 = match fs::read_to_string(offset_path) {
Ok(content) => content
.trim()
.parse()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
Err(e) => return Err(e),
};
let mut file = fs::File::open(transcript)?;
file.seek(SeekFrom::Start(start as u64))?;
let mut reader = io::BufReader::new(file);
let mut lines = Vec::new();
let mut end = start;
let mut buf = Vec::new();
loop {
buf.clear();
let n = reader.read_until(b'\n', &mut buf)?;
if n == 0 || buf.last() != Some(&b'\n') {
break;
}
end += n as i64;
if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&buf) {
lines.push(value);
}
}
Ok((lines, start, end))
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn append(path: &Path, text: &str) {
let mut f = fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.unwrap();
f.write_all(text.as_bytes()).unwrap();
}
#[test]
fn transcripts_lists_only_agent_jsonl_files_sorted() {
let dir = tempfile::tempdir().unwrap();
let main = dir.path().join("sess-1.jsonl");
let sub = dir.path().join("sess-1").join("subagents");
fs::create_dir_all(&sub).unwrap();
for name in [
"agent-b2.jsonl",
"agent-a1.jsonl",
"agent-a1.meta.json",
"agent-a1.forked-skill.json",
"agent-.jsonl",
"notes.jsonl",
] {
fs::write(sub.join(name), "").unwrap();
}
fs::create_dir(sub.join("agent-dir.jsonl")).unwrap();
assert_eq!(
transcripts(&main),
vec![sub.join("agent-a1.jsonl"), sub.join("agent-b2.jsonl")]
);
}
#[test]
fn transcripts_is_empty_without_a_subagents_dir_or_a_path() {
let dir = tempfile::tempdir().unwrap();
assert!(transcripts(&dir.path().join("sess-1.jsonl")).is_empty());
assert!(transcripts(Path::new("")).is_empty());
}
#[test]
fn offset_path_is_per_file_and_apart_from_the_main_offset() {
let a = offset_path(Path::new("/s"), Path::new("/t/subagents/agent-a1.jsonl"));
let b = offset_path(Path::new("/s"), Path::new("/t/subagents/agent-b2.jsonl"));
assert_eq!(a, Path::new("/s/.subagent_offsets/agent-a1"));
assert_ne!(a, b);
}
#[test]
fn read_new_lines_resumes_at_the_stored_offset() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("agent-a1.jsonl");
let off = offset_path(dir.path(), &file);
append(&file, "{\"n\":1}\n{\"n\":2}\n");
let (lines, start, end) = read_new_lines(&file, &off).unwrap();
assert_eq!(lines.len(), 2);
assert_eq!((start, end), (0, 16));
write_offset(&off, end).unwrap();
append(&file, "{\"n\":3}\n");
let (lines, start, end) = read_new_lines(&file, &off).unwrap();
assert_eq!(lines, vec![serde_json::json!({"n": 3})]);
assert_eq!((start, end), (16, 24));
}
#[test]
fn read_new_lines_leaves_a_half_written_line_for_the_next_read() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("agent-a1.jsonl");
let off = offset_path(dir.path(), &file);
append(&file, "{\"n\":1}\n{\"n\":");
let (lines, _, end) = read_new_lines(&file, &off).unwrap();
assert_eq!(lines.len(), 1);
assert_eq!(end, 8);
write_offset(&off, end).unwrap();
append(&file, "2}\n");
let (lines, start, end) = read_new_lines(&file, &off).unwrap();
assert_eq!(lines, vec![serde_json::json!({"n": 2})]);
assert_eq!((start, end), (8, 16));
}
#[test]
fn read_new_lines_skips_blank_and_malformed_lines_but_counts_their_bytes() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("agent-a1.jsonl");
append(&file, "\nnot json\r\n{\"n\":1}\r\n");
let (lines, _, end) = read_new_lines(&file, &offset_path(dir.path(), &file)).unwrap();
assert_eq!(lines, vec![serde_json::json!({"n": 1})]);
assert_eq!(end, fs::metadata(&file).unwrap().len() as i64);
}
#[test]
fn try_lock_is_exclusive_per_file_until_dropped() {
let dir = tempfile::tempdir().unwrap();
let a1 = offset_path(dir.path(), Path::new("agent-a1.jsonl"));
let b2 = offset_path(dir.path(), Path::new("agent-b2.jsonl"));
let held = try_lock(&a1).unwrap().expect("free lock");
assert!(try_lock(&a1).unwrap().is_none(), "a second holder");
assert!(try_lock(&b2).unwrap().is_some(), "another file is free");
drop(held);
assert!(try_lock(&a1).unwrap().is_some());
assert!(!a1.exists(), "the lock is not the offset file");
}
#[test]
fn read_new_lines_rejects_a_corrupt_offset() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("agent-a1.jsonl");
let off = offset_path(dir.path(), &file);
append(&file, "{\"n\":1}\n");
write_offset(&off, 0).unwrap();
fs::write(&off, "garbage").unwrap();
let err = read_new_lines(&file, &off).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
}