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 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}