Skip to main content

tracevault_cli/
subagents.rs

1//! Claude Code subagent transcripts.
2//!
3//! Claude Code (2.1.x) writes each subagent's conversation to a file of its
4//! own, `<dir of transcript_path>/<session id>/subagents/agent-<id>.jsonl`,
5//! next to an `agent-<id>.meta.json`. The main transcript holds none of the
6//! subagent's assistant lines or `usage`, so a hook that tails only
7//! `transcript_path` misses every token a subagent spends (VIS-1078).
8//!
9//! Every line in those files carries the subagent's `agentId` and the parent
10//! `sessionId`. The stream hook sends each file's new lines under the parent
11//! session, one file per request, with `transcript_offset` counted within that
12//! file; the server keys the chunks on the line's own `agentId`, so they never
13//! collide with the main transcript's chunk indexes.
14
15use std::fs;
16use std::io::{self, BufRead, Seek, SeekFrom};
17use std::path::{Path, PathBuf};
18
19/// Where the per-file read offsets live inside a session directory.
20const OFFSETS_DIR: &str = ".subagent_offsets";
21
22/// The session's subagent transcripts, sorted by path so a hook sends them in
23/// a stable order. Empty when the session has none (or `transcript_path` is
24/// empty, as with fileless agents). Only `agent-<id>.jsonl` is taken: the
25/// directory also holds `agent-<id>.meta.json` and forked-skill sidecars.
26pub 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
49/// The file that holds how far `transcript` has been sent, keyed by its file
50/// stem (`agent-<id>`). Separate from the main transcript's `.stream_offset`.
51pub 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
56/// Persist `offset` as the next read position of the file `offset_path` keys.
57/// Replaced atomically: a hook killed mid-write must leave the old offset,
58/// not an empty file every later read rejects as corrupt.
59pub 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
71/// Take the exclusive lock on the file `offset_path` keys, without waiting.
72/// `None` means another hook of the session holds it.
73///
74/// A hook holds it from reading the file to writing its new offset. Parallel
75/// hooks of one session run concurrently, and without it two of them can read
76/// from one offset, the one that read less can write its offset last, and the
77/// next hook re-sends the rest from that offset: same lines, new chunk_indexes,
78/// stored twice. A hook that finds the lock taken skips the file instead of
79/// waiting (the holder may spend the whole delivery budget); a later hook, at
80/// the latest that subagent's `SubagentStop`, sends what the holder did not
81/// read. The OS drops the lock when its holder exits, even if killed.
82pub 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
98/// Read the lines appended to `transcript` since the offset stored in
99/// `offset_path` (0 when absent). Returns `(lines, start_offset, end_offset)`
100/// with the meaning of `commands::stream::read_new_transcript_lines`:
101/// `start_offset` goes on the request as `transcript_offset`, `end_offset` is
102/// the next read position.
103///
104/// Unlike that reader, it stops before a trailing line with no newline yet. A
105/// subagent running in the background appends to its file while the parent's
106/// hooks fire, so a hook can catch a line half-written; counting it as read
107/// would skip the rest of that line for good. Offsets are exact byte counts.
108///
109/// A corrupt offset file is an error rather than a restart from 0: chunk
110/// indexes derive from the start offset, so re-reading from elsewhere would
111/// give the same lines new indexes and the server would store them twice.
112pub 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
120/// [`read_new_lines`], reading no further than the line that reaches
121/// `max_bytes`, and telling where each line ends (see
122/// [`crate::commands::stream::TranscriptBatch`]).
123pub 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}