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 batch = read_batch(transcript, offset_path, i64::MAX)?;
117 Ok((batch.lines, batch.start, batch.end))
118}
119
120pub fn read_batch(
124 transcript: &Path,
125 offset_path: &Path,
126 max_bytes: i64,
127) -> io::Result<crate::commands::stream::TranscriptBatch> {
128 let start: i64 = match fs::read_to_string(offset_path) {
129 Ok(content) => content
130 .trim()
131 .parse()
132 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
133 Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
134 Err(e) => return Err(e),
135 };
136 let mut file = fs::File::open(transcript)?;
137 file.seek(SeekFrom::Start(start as u64))?;
138 let mut reader = io::BufReader::new(file);
139
140 let mut lines = Vec::new();
141 let mut ends = Vec::new();
142 let mut end = start;
143 let mut buf = Vec::new();
144 loop {
145 buf.clear();
146 let n = reader.read_until(b'\n', &mut buf)?;
147 if n == 0 || buf.last() != Some(&b'\n') {
148 break;
149 }
150 end += n as i64;
151 if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&buf) {
152 lines.push(value);
153 ends.push(end);
154 }
155 if end - start >= max_bytes {
156 break;
157 }
158 }
159 Ok(crate::commands::stream::TranscriptBatch {
160 lines,
161 ends,
162 start,
163 end,
164 })
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170 use std::io::Write;
171
172 fn append(path: &Path, text: &str) {
173 let mut f = fs::OpenOptions::new()
174 .create(true)
175 .append(true)
176 .open(path)
177 .unwrap();
178 f.write_all(text.as_bytes()).unwrap();
179 }
180
181 #[test]
182 fn transcripts_lists_only_agent_jsonl_files_sorted() {
183 let dir = tempfile::tempdir().unwrap();
184 let main = dir.path().join("sess-1.jsonl");
185 let sub = dir.path().join("sess-1").join("subagents");
186 fs::create_dir_all(&sub).unwrap();
187 for name in [
188 "agent-b2.jsonl",
189 "agent-a1.jsonl",
190 "agent-a1.meta.json",
191 "agent-a1.forked-skill.json",
192 "agent-.jsonl",
193 "notes.jsonl",
194 ] {
195 fs::write(sub.join(name), "").unwrap();
196 }
197 fs::create_dir(sub.join("agent-dir.jsonl")).unwrap();
198
199 assert_eq!(
200 transcripts(&main),
201 vec![sub.join("agent-a1.jsonl"), sub.join("agent-b2.jsonl")]
202 );
203 }
204
205 #[test]
206 fn transcripts_is_empty_without_a_subagents_dir_or_a_path() {
207 let dir = tempfile::tempdir().unwrap();
208 assert!(transcripts(&dir.path().join("sess-1.jsonl")).is_empty());
209 assert!(transcripts(Path::new("")).is_empty());
210 }
211
212 #[test]
213 fn offset_path_is_per_file_and_apart_from_the_main_offset() {
214 let a = offset_path(Path::new("/s"), Path::new("/t/subagents/agent-a1.jsonl"));
215 let b = offset_path(Path::new("/s"), Path::new("/t/subagents/agent-b2.jsonl"));
216 assert_eq!(a, Path::new("/s/.subagent_offsets/agent-a1"));
217 assert_ne!(a, b);
218 }
219
220 #[test]
221 fn read_new_lines_resumes_at_the_stored_offset() {
222 let dir = tempfile::tempdir().unwrap();
223 let file = dir.path().join("agent-a1.jsonl");
224 let off = offset_path(dir.path(), &file);
225 append(&file, "{\"n\":1}\n{\"n\":2}\n");
226
227 let (lines, start, end) = read_new_lines(&file, &off).unwrap();
228 assert_eq!(lines.len(), 2);
229 assert_eq!((start, end), (0, 16));
230 write_offset(&off, end).unwrap();
231
232 append(&file, "{\"n\":3}\n");
233 let (lines, start, end) = read_new_lines(&file, &off).unwrap();
234 assert_eq!(lines, vec![serde_json::json!({"n": 3})]);
235 assert_eq!((start, end), (16, 24));
236 }
237
238 #[test]
239 fn read_new_lines_leaves_a_half_written_line_for_the_next_read() {
240 let dir = tempfile::tempdir().unwrap();
241 let file = dir.path().join("agent-a1.jsonl");
242 let off = offset_path(dir.path(), &file);
243 append(&file, "{\"n\":1}\n{\"n\":");
244
245 let (lines, _, end) = read_new_lines(&file, &off).unwrap();
246 assert_eq!(lines.len(), 1);
247 assert_eq!(end, 8);
248 write_offset(&off, end).unwrap();
249
250 append(&file, "2}\n");
251 let (lines, start, end) = read_new_lines(&file, &off).unwrap();
252 assert_eq!(lines, vec![serde_json::json!({"n": 2})]);
253 assert_eq!((start, end), (8, 16));
254 }
255
256 #[test]
257 fn read_new_lines_skips_blank_and_malformed_lines_but_counts_their_bytes() {
258 let dir = tempfile::tempdir().unwrap();
259 let file = dir.path().join("agent-a1.jsonl");
260 append(&file, "\nnot json\r\n{\"n\":1}\r\n");
261
262 let (lines, _, end) = read_new_lines(&file, &offset_path(dir.path(), &file)).unwrap();
263 assert_eq!(lines, vec![serde_json::json!({"n": 1})]);
264 assert_eq!(end, fs::metadata(&file).unwrap().len() as i64);
265 }
266
267 #[test]
268 fn try_lock_is_exclusive_per_file_until_dropped() {
269 let dir = tempfile::tempdir().unwrap();
270 let a1 = offset_path(dir.path(), Path::new("agent-a1.jsonl"));
271 let b2 = offset_path(dir.path(), Path::new("agent-b2.jsonl"));
272
273 let held = try_lock(&a1).unwrap().expect("free lock");
274 assert!(try_lock(&a1).unwrap().is_none(), "a second holder");
275 assert!(try_lock(&b2).unwrap().is_some(), "another file is free");
276 drop(held);
277 assert!(try_lock(&a1).unwrap().is_some());
278 assert!(!a1.exists(), "the lock is not the offset file");
279 }
280
281 #[test]
282 fn read_new_lines_rejects_a_corrupt_offset() {
283 let dir = tempfile::tempdir().unwrap();
284 let file = dir.path().join("agent-a1.jsonl");
285 let off = offset_path(dir.path(), &file);
286 append(&file, "{\"n\":1}\n");
287 write_offset(&off, 0).unwrap();
288 fs::write(&off, "garbage").unwrap();
289
290 let err = read_new_lines(&file, &off).unwrap_err();
291 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
292 }
293}