use super::{Compaction, LoadEvent, Session, Source, Turn};
use serde_json::Value;
use std::path::{Path, PathBuf};
#[must_use]
pub fn parse(text: &str) -> Session {
parse_with(text).0
}
#[must_use]
pub fn parse_with(text: &str) -> (Session, Vec<Compaction>) {
let mut out = Session::default();
let mut compactions = Vec::new();
for line in text.lines() {
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<Value>(line) {
Err(_) => out.skipped = out.skipped.saturating_add(1),
Ok(v) => absorb(&v, &mut out, &mut compactions),
}
}
(out, compactions)
}
fn absorb(v: &Value, out: &mut Session, compactions: &mut Vec<Compaction>) {
out.content_bytes = out.content_bytes.saturating_add(content_bytes(v));
match str_at(v, "type") {
Some("assistant") => out.turns.extend(turn(v, out.content_bytes)),
Some("user") => out.events.extend(tool_event(v)),
Some("attachment") => out.events.extend(attachment_event(v)),
Some("system") => compactions.extend(compaction(v)),
_ => {}
}
}
fn compaction(v: &Value) -> Option<Compaction> {
let meta = v.get("compactMetadata")?;
Some(Compaction {
trigger: str_at(meta, "trigger").unwrap_or_default().to_owned(),
pre_tokens: meta.get("preTokens")?.as_u64()?,
post_tokens: meta
.get("postTokens")
.and_then(Value::as_u64)
.unwrap_or_default(),
ts: ts_of(v),
})
}
fn str_at<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
v.get(key)?.as_str()
}
fn session_of(v: &Value) -> String {
str_at(v, "sessionId").unwrap_or_default().to_owned()
}
fn ts_of(v: &Value) -> String {
str_at(v, "timestamp").unwrap_or_default().to_owned()
}
fn turn(v: &Value, cum_content_bytes: u64) -> Option<Turn> {
let usage = usage_of(v);
let num = |k: &str| usage.get(k).and_then(Value::as_u64);
Some(Turn {
session: session_of(v),
ts: ts_of(v),
input: num("input_tokens"),
cache_creation: num("cache_creation_input_tokens"),
cache_read: num("cache_read_input_tokens"),
output: num("output_tokens"),
cum_content_bytes,
})
}
fn content_bytes(v: &Value) -> u64 {
let Some(c) = v.get("message").and_then(|m| m.get("content")) else {
return 0;
};
match c {
Value::String(s) => len_of(s.len()),
Value::Array(blocks) => blocks.iter().map(block_bytes).sum(),
_ => 0,
}
}
fn block_bytes(b: &Value) -> u64 {
let field = |k: &str| b.get(k).and_then(Value::as_str).map_or(0, str::len);
let json = |k: &str| b.get(k).map_or(0, |x| x.to_string().len());
len_of(match str_at(b, "type") {
Some("text") => field("text"),
Some("thinking") => {
field("signature").saturating_add(field("thinking"))
}
Some("tool_use") => json("input"),
Some("tool_result") => json("content"),
_ => 0,
})
}
fn len_of(n: usize) -> u64 {
u64::try_from(n).unwrap_or(u64::MAX)
}
fn usage_of(v: &Value) -> Value {
v.get("message")
.and_then(|m| m.get("usage"))
.cloned()
.unwrap_or(Value::Null)
}
fn tool_event(v: &Value) -> Option<LoadEvent> {
let result = v.get("toolUseResult")?;
let (bytes, spilled, path) = measure(result);
Some(LoadEvent {
session: session_of(v),
ts: ts_of(v),
source: Source::Tool(tool_name(result).to_owned()),
path,
bytes,
spilled,
})
}
fn measure(result: &Value) -> (usize, Option<usize>, Option<String>) {
match result {
Value::String(s) => (s.len(), None, None),
_ => (
retained_bytes(result),
spilled_bytes(result),
path_of(result),
),
}
}
fn retained_bytes(result: &Value) -> usize {
let field =
|k: &str| result.get(k).and_then(Value::as_str).map_or(0, str::len);
let streams = field("stdout")
.saturating_add(field("stderr"))
.saturating_add(field("content"));
if streams > 0 {
return streams;
}
result
.get("file")
.and_then(|f| f.get("content"))
.and_then(Value::as_str)
.map_or(0, str::len)
}
fn spilled_bytes(result: &Value) -> Option<usize> {
let n = result.get("persistedOutputSize")?.as_u64()?;
usize::try_from(n).ok()
}
fn path_of(result: &Value) -> Option<String> {
let direct = result.get("filePath").and_then(Value::as_str);
let nested = result
.get("file")
.and_then(|f| f.get("filePath"))
.and_then(Value::as_str);
direct.or(nested).map(str::to_owned)
}
fn tool_name(result: &Value) -> &'static str {
if result.is_string() {
return "text";
}
by_key(result).unwrap_or_else(|| by_type(result))
}
fn by_key(result: &Value) -> Option<&'static str> {
BY_KEY
.iter()
.find(|(key, _)| result.get(key).is_some())
.map(|(_, label)| *label)
}
fn by_type(result: &Value) -> &'static str {
match str_at(result, "type") {
Some("create" | "update") => "write",
Some("text") => "read",
_ => "tool",
}
}
const BY_KEY: [(&str, &str); 3] = [
("stdout", "shell"),
("oldString", "edit"),
("persistedOutputPath", "shell"),
];
fn attachment_event(v: &Value) -> Option<LoadEvent> {
let a = v.get("attachment")?;
let kind = str_at(a, "type").unwrap_or("attachment").to_owned();
Some(LoadEvent {
session: session_of(v),
ts: ts_of(v),
source: Source::Attachment(kind),
path: None,
bytes: attachment_bytes(a),
spilled: None,
})
}
fn attachment_bytes(a: &Value) -> usize {
match a {
Value::String(s) => s.len(),
Value::Object(map) => map
.iter()
.filter(|(k, _)| k.as_str() != "type")
.map(|(_, v)| attachment_bytes(v))
.fold(0usize, usize::saturating_add),
Value::Array(items) => items
.iter()
.map(attachment_bytes)
.fold(0usize, usize::saturating_add),
_ => 0,
}
}
#[must_use]
pub fn project_dir(home: &Path, project: &Path) -> PathBuf {
let encoded: String = project
.to_string_lossy()
.chars()
.map(|c| if c == '/' || c == '\\' { '-' } else { c })
.collect();
home.join(".claude").join("projects").join(encoded)
}
#[must_use]
pub fn newest_transcript(home: &Path, project: &Path) -> Option<PathBuf> {
newest_in(&project_dir(home, project))
}
#[must_use]
pub fn newest_in(dir: &Path) -> Option<PathBuf> {
let dir = dir.to_path_buf();
let mut best: Option<(std::time::SystemTime, PathBuf)> = None;
for entry in std::fs::read_dir(dir).ok()?.flatten() {
let path = entry.path();
if path.extension().is_none_or(|x| x != "jsonl") {
continue;
}
let Ok(when) = entry.metadata().and_then(|m| m.modified()) else {
continue;
};
if best.as_ref().is_none_or(|(b, _)| when > *b) {
best = Some((when, path));
}
}
best.map(|(_, p)| p)
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch(tag: &str) -> PathBuf {
let d = std::env::temp_dir()
.join(format!("itok-cc-{tag}-{}", std::process::id()));
std::fs::remove_dir_all(&d).ok();
d
}
#[test]
fn a_compact_boundary_becomes_a_compaction() {
let line = r#"{"type":"system","subtype":"compact_boundary","timestamp":"2026-09-05T12:29:54.086Z","compactMetadata":{"trigger":"auto","preTokens":968887,"postTokens":11503,"cumulativeDroppedTokens":957384}}"#;
let (_, got) = super::parse_with(line);
assert_eq!(got.len(), 1);
assert_eq!(super::super::compact_point(&got), Some(968_887));
assert_eq!(super::super::auto_compactions(&got).count(), 1);
}
#[test]
fn a_manual_compaction_is_recorded_but_never_sets_the_point() {
let line = r#"{"type":"system","subtype":"compact_boundary","compactMetadata":{"trigger":"manual","preTokens":120000,"postTokens":9000}}"#;
let (_, got) = super::parse_with(line);
assert_eq!(got.len(), 1);
assert_eq!(super::super::compact_point(&got), None);
}
#[test]
fn the_lowest_auto_point_is_the_one_reported() {
let text = concat!(
r#"{"type":"system","compactMetadata":{"trigger":"auto","preTokens":1000418,"postTokens":1}}"#,
"\n",
r#"{"type":"system","compactMetadata":{"trigger":"auto","preTokens":968887,"postTokens":1}}"#,
);
let (_, got) = super::parse_with(text);
assert_eq!(super::super::compact_point(&got), Some(968_887));
assert_eq!(super::super::auto_compactions(&got).count(), 2);
}
#[test]
fn a_boundary_without_a_pre_count_is_not_a_zero() {
let line = r#"{"type":"system","compactMetadata":{"trigger":"auto"}}"#;
let (_, got) = super::parse_with(line);
assert!(got.is_empty());
assert_eq!(super::super::compact_point(&got), None);
}
#[test]
fn project_dir_encodes_the_path() {
let got = project_dir(Path::new("/home/u"), Path::new("/w/proj"));
assert_eq!(got, Path::new("/home/u/.claude/projects/-w-proj"));
}
#[test]
fn no_project_dir_yields_none() {
let home = scratch("nodir");
assert!(newest_transcript(&home, Path::new("/w/proj")).is_none());
}
#[test]
fn only_jsonl_files_are_transcripts() {
let home = scratch("filter");
let dir = project_dir(&home, Path::new("/w/p"));
std::fs::create_dir_all(&dir).ok();
std::fs::write(dir.join("notes.txt"), "x").ok();
std::fs::write(dir.join("a.jsonl"), "{}\n").ok();
let got = newest_transcript(&home, Path::new("/w/p"));
assert_eq!(got, Some(dir.join("a.jsonl")));
}
#[test]
fn a_dir_without_transcripts_yields_none() {
let home = scratch("empty");
let dir = project_dir(&home, Path::new("/w/p"));
std::fs::create_dir_all(&dir).ok();
std::fs::write(dir.join("readme.md"), "x").ok();
assert!(newest_transcript(&home, Path::new("/w/p")).is_none());
}
#[test]
fn several_transcripts_yield_one_of_them() {
let home = scratch("many");
let dir = project_dir(&home, Path::new("/w/p"));
std::fs::create_dir_all(&dir).ok();
for name in ["a.jsonl", "b.jsonl"] {
std::fs::write(dir.join(name), "{}\n").ok();
}
let got = newest_transcript(&home, Path::new("/w/p"));
let ok = got == Some(dir.join("a.jsonl"))
|| got == Some(dir.join("b.jsonl"));
assert!(ok, "picked {got:?}");
}
}