1use std::fs;
16use std::io::{self, BufRead, Seek, SeekFrom};
17use std::path::{Path, PathBuf};
18
19const OFFSETS_DIR: &str = ".subagent_offsets";
21
22pub fn transcripts(transcript_path: &Path) -> Vec<PathBuf> {
27 let (Some(dir), Some(session)) = (transcript_path.parent(), transcript_path.file_stem()) else {
28 return vec![];
29 };
30 let Ok(entries) = fs::read_dir(dir.join(session).join("subagents")) else {
31 return vec![];
32 };
33 let mut files: Vec<PathBuf> = entries
34 .filter_map(|e| e.ok())
35 .map(|e| e.path())
36 .filter(|p| p.is_file())
37 .filter(|p| {
38 p.file_name()
39 .and_then(|n| n.to_str())
40 .and_then(|n| n.strip_prefix("agent-"))
41 .and_then(|n| n.strip_suffix(".jsonl"))
42 .is_some_and(|id| !id.is_empty() && !id.contains('.'))
43 })
44 .collect();
45 files.sort();
46 files
47}
48
49pub fn offset_path(session_dir: &Path, transcript: &Path) -> PathBuf {
52 let stem = transcript.file_stem().unwrap_or_default();
53 session_dir.join(OFFSETS_DIR).join(stem)
54}
55
56pub fn write_offset(offset_path: &Path, offset: i64) -> io::Result<()> {
60 let Some(dir) = offset_path.parent() else {
61 return fs::write(offset_path, offset.to_string());
62 };
63 fs::create_dir_all(dir)?;
64 let tmp = offset_path.with_extension(format!("tmp.{}", uuid::Uuid::now_v7()));
65 fs::write(&tmp, offset.to_string())?;
66 fs::rename(&tmp, offset_path).inspect_err(|_| {
67 let _ = fs::remove_file(&tmp);
68 })
69}
70
71pub fn try_lock(offset_path: &Path) -> io::Result<Option<fs::File>> {
83 if let Some(dir) = offset_path.parent() {
84 fs::create_dir_all(dir)?;
85 }
86 let file = fs::OpenOptions::new()
87 .create(true)
88 .truncate(false)
89 .write(true)
90 .open(offset_path.with_extension("lock"))?;
91 match file.try_lock() {
92 Ok(()) => Ok(Some(file)),
93 Err(fs::TryLockError::WouldBlock) => Ok(None),
94 Err(fs::TryLockError::Error(e)) => Err(e),
95 }
96}
97
98pub fn read_new_lines(
113 transcript: &Path,
114 offset_path: &Path,
115) -> io::Result<(Vec<serde_json::Value>, i64, i64)> {
116 let start: i64 = match fs::read_to_string(offset_path) {
117 Ok(content) => content
118 .trim()
119 .parse()
120 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
121 Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
122 Err(e) => return Err(e),
123 };
124 let mut file = fs::File::open(transcript)?;
125 file.seek(SeekFrom::Start(start as u64))?;
126 let mut reader = io::BufReader::new(file);
127
128 let mut lines = Vec::new();
129 let mut end = start;
130 let mut buf = Vec::new();
131 loop {
132 buf.clear();
133 let n = reader.read_until(b'\n', &mut buf)?;
134 if n == 0 || buf.last() != Some(&b'\n') {
135 break;
136 }
137 end += n as i64;
138 if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&buf) {
139 lines.push(value);
140 }
141 }
142 Ok((lines, start, end))
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148 use std::io::Write;
149
150 fn append(path: &Path, text: &str) {
151 let mut f = fs::OpenOptions::new()
152 .create(true)
153 .append(true)
154 .open(path)
155 .unwrap();
156 f.write_all(text.as_bytes()).unwrap();
157 }
158
159 #[test]
160 fn transcripts_lists_only_agent_jsonl_files_sorted() {
161 let dir = tempfile::tempdir().unwrap();
162 let main = dir.path().join("sess-1.jsonl");
163 let sub = dir.path().join("sess-1").join("subagents");
164 fs::create_dir_all(&sub).unwrap();
165 for name in [
166 "agent-b2.jsonl",
167 "agent-a1.jsonl",
168 "agent-a1.meta.json",
169 "agent-a1.forked-skill.json",
170 "agent-.jsonl",
171 "notes.jsonl",
172 ] {
173 fs::write(sub.join(name), "").unwrap();
174 }
175 fs::create_dir(sub.join("agent-dir.jsonl")).unwrap();
176
177 assert_eq!(
178 transcripts(&main),
179 vec![sub.join("agent-a1.jsonl"), sub.join("agent-b2.jsonl")]
180 );
181 }
182
183 #[test]
184 fn transcripts_is_empty_without_a_subagents_dir_or_a_path() {
185 let dir = tempfile::tempdir().unwrap();
186 assert!(transcripts(&dir.path().join("sess-1.jsonl")).is_empty());
187 assert!(transcripts(Path::new("")).is_empty());
188 }
189
190 #[test]
191 fn offset_path_is_per_file_and_apart_from_the_main_offset() {
192 let a = offset_path(Path::new("/s"), Path::new("/t/subagents/agent-a1.jsonl"));
193 let b = offset_path(Path::new("/s"), Path::new("/t/subagents/agent-b2.jsonl"));
194 assert_eq!(a, Path::new("/s/.subagent_offsets/agent-a1"));
195 assert_ne!(a, b);
196 }
197
198 #[test]
199 fn read_new_lines_resumes_at_the_stored_offset() {
200 let dir = tempfile::tempdir().unwrap();
201 let file = dir.path().join("agent-a1.jsonl");
202 let off = offset_path(dir.path(), &file);
203 append(&file, "{\"n\":1}\n{\"n\":2}\n");
204
205 let (lines, start, end) = read_new_lines(&file, &off).unwrap();
206 assert_eq!(lines.len(), 2);
207 assert_eq!((start, end), (0, 16));
208 write_offset(&off, end).unwrap();
209
210 append(&file, "{\"n\":3}\n");
211 let (lines, start, end) = read_new_lines(&file, &off).unwrap();
212 assert_eq!(lines, vec![serde_json::json!({"n": 3})]);
213 assert_eq!((start, end), (16, 24));
214 }
215
216 #[test]
217 fn read_new_lines_leaves_a_half_written_line_for_the_next_read() {
218 let dir = tempfile::tempdir().unwrap();
219 let file = dir.path().join("agent-a1.jsonl");
220 let off = offset_path(dir.path(), &file);
221 append(&file, "{\"n\":1}\n{\"n\":");
222
223 let (lines, _, end) = read_new_lines(&file, &off).unwrap();
224 assert_eq!(lines.len(), 1);
225 assert_eq!(end, 8);
226 write_offset(&off, end).unwrap();
227
228 append(&file, "2}\n");
229 let (lines, start, end) = read_new_lines(&file, &off).unwrap();
230 assert_eq!(lines, vec![serde_json::json!({"n": 2})]);
231 assert_eq!((start, end), (8, 16));
232 }
233
234 #[test]
235 fn read_new_lines_skips_blank_and_malformed_lines_but_counts_their_bytes() {
236 let dir = tempfile::tempdir().unwrap();
237 let file = dir.path().join("agent-a1.jsonl");
238 append(&file, "\nnot json\r\n{\"n\":1}\r\n");
239
240 let (lines, _, end) = read_new_lines(&file, &offset_path(dir.path(), &file)).unwrap();
241 assert_eq!(lines, vec![serde_json::json!({"n": 1})]);
242 assert_eq!(end, fs::metadata(&file).unwrap().len() as i64);
243 }
244
245 #[test]
246 fn try_lock_is_exclusive_per_file_until_dropped() {
247 let dir = tempfile::tempdir().unwrap();
248 let a1 = offset_path(dir.path(), Path::new("agent-a1.jsonl"));
249 let b2 = offset_path(dir.path(), Path::new("agent-b2.jsonl"));
250
251 let held = try_lock(&a1).unwrap().expect("free lock");
252 assert!(try_lock(&a1).unwrap().is_none(), "a second holder");
253 assert!(try_lock(&b2).unwrap().is_some(), "another file is free");
254 drop(held);
255 assert!(try_lock(&a1).unwrap().is_some());
256 assert!(!a1.exists(), "the lock is not the offset file");
257 }
258
259 #[test]
260 fn read_new_lines_rejects_a_corrupt_offset() {
261 let dir = tempfile::tempdir().unwrap();
262 let file = dir.path().join("agent-a1.jsonl");
263 let off = offset_path(dir.path(), &file);
264 append(&file, "{\"n\":1}\n");
265 write_offset(&off, 0).unwrap();
266 fs::write(&off, "garbage").unwrap();
267
268 let err = read_new_lines(&file, &off).unwrap_err();
269 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
270 }
271}