use crate::args::Format;
use crate::cli::Output;
use crate::json::escape;
use crate::session::{LoadEvent, Session, Source, claude_code};
use std::path::{Path, PathBuf};
#[derive(Default)]
struct Raw {
session: Option<String>,
limit: Option<String>,
since: Option<String>,
reverse: bool,
format: Format,
chdir: Option<String>,
}
pub(crate) fn trace(rest: &[String]) -> Output {
match parse(rest) {
Ok(raw) => run(&raw),
Err(e) => Output::usage_err(format!("itok: {e}")),
}
}
fn run(raw: &Raw) -> Output {
let parsed = match session_at(raw.session.as_deref(), raw.chdir.as_deref())
{
Ok((p, _)) => p,
Err(o) => return o,
};
let rows = select(parsed.events, raw);
Output::ok(match raw.format {
Format::Json => json(&rows),
Format::Human => report(&rows),
})
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Origin {
Argument,
Harness,
Newest,
}
const SESSION_VARS: [&str; 3] = [
"CLAUDE_SESSION_ID",
"ITOK_SESSION_ID",
"CLAUDE_CODE_SESSION_ID",
];
fn harness_session() -> Option<String> {
first_id(SESSION_VARS.iter().filter_map(|k| std::env::var(k).ok()))
}
fn first_id(values: impl Iterator<Item = String>) -> Option<String> {
values.map(|v| v.trim().to_owned()).find(|v| !v.is_empty())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Missing {
Inferred,
Named(String),
}
pub(crate) fn resolve_session(
session: Option<&str>,
chdir: Option<&str>,
) -> Result<(PathBuf, Origin), Missing> {
resolve_with(session, chdir, env_home(), harness_session())
}
fn resolve_with(
session: Option<&str>,
chdir: Option<&str>,
home: Option<PathBuf>,
offered: Option<String>,
) -> Result<(PathBuf, Origin), Missing> {
if let Some(s) = session {
return named_session(s, chdir, home.as_deref());
}
let dir = project_dir(chdir, home.as_deref()).ok_or(Missing::Inferred)?;
if let Some(id) = offered {
let named = dir.join(format!("{id}.jsonl"));
if named.is_file() {
return Ok((named, Origin::Harness));
}
}
newest_in(&dir)
.map(|p| (p, Origin::Newest))
.ok_or(Missing::Inferred)
}
fn named_session(
s: &str,
chdir: Option<&str>,
home: Option<&Path>,
) -> Result<(PathBuf, Origin), Missing> {
let dir = project_dir(chdir, home);
match found(s, dir.as_deref()) {
Some(p) => Ok((p, Origin::Argument)),
None => Err(Missing::Named(no_session(s, dir.as_deref()))),
}
}
fn found(s: &str, dir: Option<&Path>) -> Option<PathBuf> {
let as_path = PathBuf::from(s);
if as_path.is_file() {
return Some(as_path);
}
let as_id = dir?.join(format!("{s}.jsonl"));
as_id.is_file().then_some(as_id)
}
fn no_session(s: &str, dir: Option<&Path>) -> String {
let where_ = dir.map_or_else(
|| "no project directory for this working directory".to_owned(),
|d| d.display().to_string(),
);
format!(
"itok: no session '{s}' -- not a readable path, \
and no '{s}.jsonl' in {where_}"
)
}
pub(crate) fn missing_output(m: &Missing) -> Output {
match m {
Missing::Inferred => Output::ok(String::new()),
Missing::Named(msg) => Output::usage(format!("{msg}\n")),
}
}
fn read_source(path: &Path) -> Result<String, Output> {
std::fs::read_to_string(path).map_err(|e| {
Output::usage(format!("itok: cannot read {}: {e}\n", path.display()))
})
}
pub(crate) fn session_at(
session: Option<&str>,
chdir: Option<&str>,
) -> Result<(Session, Origin), Output> {
let (session, _, origin) = session_with_compactions(session, chdir)?;
Ok((session, origin))
}
pub(crate) type Loaded = (Session, Vec<crate::session::Compaction>, Origin);
pub(crate) fn session_with_compactions(
session: Option<&str>,
chdir: Option<&str>,
) -> Result<Loaded, Output> {
let (path, origin) =
resolve_session(session, chdir).map_err(|m| missing_output(&m))?;
let text = read_source(&path)?;
let (session, compactions) =
claude_code::parse_with(crate::session::complete_prefix(&text));
Ok((session, compactions, origin))
}
fn project_dir(chdir: Option<&str>, home: Option<&Path>) -> Option<PathBuf> {
let cwd = chdir.map_or_else(
|| std::env::current_dir().ok(),
|d| Some(PathBuf::from(d)),
)?;
let home = home?;
let project = std::fs::canonicalize(&cwd).unwrap_or(cwd);
Some(claude_code::project_dir(home, &project))
}
fn env_home() -> Option<PathBuf> {
std::env::var("HOME").ok().map(PathBuf::from)
}
fn newest_in(dir: &Path) -> Option<PathBuf> {
claude_code::newest_in(dir)
}
pub(crate) fn origin_note(origin: &Origin) -> String {
match origin {
Origin::Newest => " session: newest by mtime -- not necessarily \
yours; pass a path or set CLAUDE_SESSION_ID\n"
.to_owned(),
Origin::Argument | Origin::Harness => String::new(),
}
}
#[cfg(test)]
mod origin_tests {
use super::*;
#[test]
fn only_the_guess_announces_itself() {
assert!(origin_note(&Origin::Argument).is_empty());
assert!(origin_note(&Origin::Harness).is_empty());
let note = origin_note(&Origin::Newest);
assert!(note.contains("newest by mtime"), "{note}");
assert!(note.contains("not necessarily"), "the claim is weakened");
assert!(note.contains("CLAUDE_SESSION_ID"), "and says what to do");
}
#[test]
fn an_explicit_path_is_its_own_origin() {
let dir = std::env::temp_dir().join("itok-v104-path");
let _ = std::fs::create_dir_all(&dir);
let file = dir.join("x.jsonl");
let _ = std::fs::write(&file, "");
let got = resolve_session(Some(&file.to_string_lossy()), None);
assert_eq!(got, Ok((file.clone(), Origin::Argument)));
let _ = std::fs::remove_file(&file);
}
#[test]
fn v104_a_named_session_that_misses_is_an_error() {
let got = resolve_session(Some("no-such-session-xyz"), None);
let msg = match got {
Err(Missing::Named(m)) => m,
Err(Missing::Inferred) => {
unreachable!("a NAMED miss reported as an inferred one")
}
Ok(_) => unreachable!("a name resolving to nothing succeeded"),
};
assert!(msg.contains("no-such-session-xyz"), "{msg}");
assert!(msg.contains(".jsonl"), "names the id form tried: {msg}");
}
#[test]
fn v104_only_a_named_miss_is_a_usage_error() {
let inferred = missing_output(&Missing::Inferred);
assert_eq!(inferred.code, 0, "nothing was asked for");
assert!(inferred.out.is_empty() && inferred.err.is_empty());
let named = missing_output(&Missing::Named("itok: gone".to_owned()));
assert_eq!(named.code, 2, "a named miss is a usage error");
assert!(named.err.contains("itok: gone"), "{}", named.err);
assert!(named.out.is_empty(), "nothing on stdout");
}
fn planted_transcript(id: &str) -> (PathBuf, PathBuf, PathBuf) {
let home = std::env::temp_dir().join(format!("itok-v104-home-{id}"));
let cwd = std::env::temp_dir().join(format!("itok-v104-proj-{id}"));
let _ = std::fs::create_dir_all(&cwd);
let canon = std::fs::canonicalize(&cwd).unwrap_or_else(|_| cwd.clone());
let dir = crate::session::claude_code::project_dir(&home, &canon);
let _ = std::fs::create_dir_all(&dir);
let file = dir.join(format!("{id}.jsonl"));
let _ = std::fs::write(&file, "");
(home, cwd, file)
}
fn resolve_under_home(
home: &Path,
cwd: &Path,
arg: Option<&str>,
) -> Result<(PathBuf, Origin), Missing> {
let dir = cwd.to_string_lossy();
resolve_with(arg, Some(&dir), Some(home.to_path_buf()), None)
}
#[test]
fn v104_a_bare_id_resolves_against_the_project_dir() {
let (home, cwd, file) = planted_transcript("abc-123");
let got = resolve_under_home(&home, &cwd, Some("abc-123"));
assert_eq!(got, Ok((file.clone(), Origin::Argument)), "id resolved");
let _ = std::fs::remove_file(&file);
}
#[test]
fn a_harness_id_that_resolves_wins_over_newest() {
let (home, cwd, file) = planted_transcript("harness-wins");
let got = resolve_with(
None,
Some(&cwd.to_string_lossy()),
Some(home.clone()),
Some("harness-wins".to_owned()),
);
assert_eq!(
got,
Ok((file.clone(), Origin::Harness)),
"the id the harness offered, not a guess by mtime"
);
let _ = std::fs::remove_file(&file);
}
#[test]
fn a_miss_with_no_project_dir_says_so() {
let msg = no_session("ghost", None);
assert!(msg.contains("ghost"), "{msg}");
assert!(msg.contains("no project directory"), "{msg}");
}
#[test]
fn a_source_that_cannot_be_read_names_the_path() {
let dir = std::env::temp_dir();
let out = read_source(&dir)
.err()
.unwrap_or_else(|| Output::ok(String::new()));
assert_eq!(out.code, 2, "a read fault is a usage error");
assert!(out.err.contains("cannot read"), "{}", out.err);
assert!(
out.err.contains(&dir.display().to_string()),
"names the path: {}",
out.err
);
}
#[test]
fn a_stale_harness_id_falls_back_instead_of_failing() {
let (home, cwd, file) = planted_transcript("stale-fallback");
let dir = cwd.to_string_lossy();
let got = resolve_with(
None,
Some(&dir),
Some(home.clone()),
Some("no-such-session-id-xyz".to_owned()),
);
assert_eq!(
got,
Ok((file.clone(), Origin::Newest)),
"a stale harness id must fall back to newest, not resolve to \
nothing and not win"
);
let _ = std::fs::remove_file(&file);
}
#[test]
fn an_empty_variable_is_not_an_offer() {
let vals = |v: &[&str]| first_id(v.iter().map(|s| (*s).to_owned()));
assert_eq!(vals(&["", " ", "\t"]), None, "nothing offered");
assert_eq!(
vals(&["", "abc"]),
Some("abc".to_owned()),
"first real one"
);
assert_eq!(vals(&[" id "]), Some("id".to_owned()), "trimmed");
assert_eq!(vals(&[]), None);
}
}
fn select(events: Vec<LoadEvent>, raw: &Raw) -> Vec<LoadEvent> {
let mut rows = since(events, raw.since.as_deref());
keep_newest(&mut rows, raw.limit.as_deref());
if raw.reverse {
rows.reverse();
}
rows
}
fn since(events: Vec<LoadEvent>, cutoff: Option<&str>) -> Vec<LoadEvent> {
events
.into_iter()
.filter(|e| cutoff.is_none_or(|s| e.ts.as_str() >= s))
.collect()
}
fn keep_newest(rows: &mut Vec<LoadEvent>, limit: Option<&str>) {
let Some(n) = limit.and_then(|n| n.parse::<usize>().ok()) else {
return;
};
let drop = rows.len().saturating_sub(n);
rows.drain(..drop);
}
fn tokens(bytes: usize) -> usize {
bytes / 4
}
fn kind(source: &Source) -> &'static str {
match source {
Source::Tool(_) => "tool",
Source::Attachment(_) => "attachment",
}
}
fn report(rows: &[LoadEvent]) -> String {
let mut out = String::new();
for e in rows {
out.push_str(&format!(
"{} {:<22} ~{:>7} itok {}\n",
time_of(&e.ts),
e.source.label(),
tokens(e.bytes),
e.path.as_deref().unwrap_or(""),
));
}
out
}
fn time_of(ts: &str) -> &str {
ts.split('T')
.nth(1)
.and_then(|t| t.get(..8))
.unwrap_or("--:--:--")
}
fn json(rows: &[LoadEvent]) -> String {
rows.iter().map(json_object).collect()
}
fn json_object(e: &LoadEvent) -> String {
format!(
"{{\"ts\":\"{}\",\"kind\":\"{}\",\"source\":\"{}\",\"path\":{},\
\"bytes\":{},\"tokens\":{},\"unit\":\"input_tokens\",\
\"estimated\":true,\"method\":\"bytes/4\"}}\n",
escape(&e.ts),
kind(&e.source),
escape(e.source.label()),
json_path(e.path.as_deref()),
e.bytes,
tokens(e.bytes),
)
}
fn json_path(path: Option<&str>) -> String {
path.map_or_else(|| "null".to_owned(), |p| format!("\"{}\"", escape(p)))
}
fn parse(rest: &[String]) -> Result<Raw, String> {
let mut raw = Raw::default();
let mut it = rest.iter();
while let Some(a) = it.next() {
apply(a, &mut it, &mut raw)?;
}
Ok(raw)
}
fn apply<'a>(
a: &str,
it: &mut impl Iterator<Item = &'a String>,
raw: &mut Raw,
) -> Result<(), String> {
match a {
"--reverse" => raw.reverse = true,
"-n" => raw.limit = Some(value(it, "-n")?),
"--since" => raw.since = Some(value(it, "--since")?),
"-C" => raw.chdir = Some(value(it, "-C")?),
"--format" => raw.format = format_of(&value(it, "--format")?)?,
"--bpe" | "--ollama" => return Err(no_real_tier(a, "trace")),
other if other.starts_with('-') => {
return Err(format!("unknown flag {other}"));
}
other => raw.session = Some(other.to_owned()),
}
Ok(())
}
pub(crate) fn no_real_tier(flag: &str, verb: &str) -> String {
format!(
"{flag} is not available on {verb}: no content is stored, \
so per-event sizes are always an estimate"
)
}
pub(crate) fn format_of(s: &str) -> Result<Format, String> {
match s {
"json" => Ok(Format::Json),
"human" => Ok(Format::Human),
other => Err(format!("unknown format '{other}'")),
}
}
pub(crate) fn value<'a>(
it: &mut impl Iterator<Item = &'a String>,
flag: &str,
) -> Result<String, String> {
it.next()
.cloned()
.ok_or_else(|| format!("{flag} needs a value"))
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture(name: &str) -> String {
format!(
"{}/tests/fixtures/session/{name}",
env!("CARGO_MANIFEST_DIR")
)
}
fn run_on(name: &str, extra: &[&str]) -> Output {
let mut args = vec![fixture(name)];
args.extend(extra.iter().map(|s| (*s).to_owned()));
trace(&args)
}
#[test]
fn one_line_per_event() {
let out = run_on("tool-shapes.jsonl", &[]);
assert_eq!(out.out.lines().count(), 4);
assert_eq!(out.code, 0);
}
#[test]
fn limit_keeps_the_newest() {
let out = run_on("tool-shapes.jsonl", &["-n", "2"]);
let lines: Vec<&str> = out.out.lines().collect();
assert_eq!(lines.len(), 2);
assert!(lines.iter().any(|l| l.contains("two.txt")), "kept newest");
}
#[test]
fn reverse_flips_the_order() {
let fwd = run_on("tool-shapes.jsonl", &[]);
let rev = run_on("tool-shapes.jsonl", &["--reverse"]);
let f: Vec<&str> = fwd.out.lines().collect();
let mut r: Vec<&str> = rev.out.lines().collect();
r.reverse();
assert_eq!(f, r);
}
#[test]
fn since_filters_by_iso_timestamp() {
let all = run_on("tool-shapes.jsonl", &[]);
let cut =
run_on("tool-shapes.jsonl", &["--since", "2026-01-01T00:00:05"]);
assert!(cut.out.lines().count() < all.out.lines().count());
assert!(cut.out.contains("two.txt"), "later events survive");
}
#[test]
fn json_is_one_object_per_event() {
let out = run_on("tool-shapes.jsonl", &["--format", "json"]);
assert_eq!(out.out.lines().count(), 4);
for line in out.out.lines() {
assert!(line.starts_with('{') && line.ends_with('}'));
assert!(line.contains("\"unit\":\"input_tokens\""));
assert!(line.contains("\"estimated\":true"));
assert!(line.contains("\"method\":\"bytes/4\""));
}
}
#[test]
fn the_tilde_is_human_only() {
assert!(run_on("tool-shapes.jsonl", &[]).out.contains('~'));
assert!(
!run_on("tool-shapes.jsonl", &["--format", "json"])
.out
.contains('~')
);
}
#[test]
fn a_real_tier_is_refused_not_ignored() {
for flag in ["--bpe", "--ollama"] {
let out = run_on("tool-shapes.jsonl", &[flag]);
assert_eq!(out.code, 2, "{flag} must be a usage error");
assert!(out.err.contains("no content is stored"));
}
}
#[test]
fn a_named_miss_is_a_usage_error() {
let out = trace(&["/nonexistent/session.jsonl".to_owned()]);
assert_eq!(out.code, 2, "a name that resolves to nothing");
assert!(out.out.is_empty(), "nothing on stdout");
assert!(out.err.contains("no session"), "{}", out.err);
}
#[test]
fn a_torn_tail_does_not_break_the_listing() {
let out = run_on("torn-tail.jsonl", &[]);
assert_eq!(out.code, 0);
}
#[test]
fn attachments_are_listed_and_kinded() {
let out = run_on("weird.jsonl", &["--format", "json"]);
assert!(out.out.contains("\"kind\":\"attachment\""));
assert!(out.out.contains("\"source\":\"hook_success\""));
assert!(out.out.contains("\"path\":null"));
}
#[test]
fn human_format_is_default_and_explicit() {
let a = run_on("tool-shapes.jsonl", &[]);
let b = run_on("tool-shapes.jsonl", &["--format", "human"]);
assert_eq!(a.out, b.out);
}
#[test]
fn a_bad_format_is_a_usage_error() {
let out = run_on("tool-shapes.jsonl", &["--format", "yaml"]);
assert_eq!(out.code, 2);
assert!(out.err.contains("unknown format"));
}
#[test]
fn a_flag_missing_its_value_errors() {
let out = run_on("tool-shapes.jsonl", &["-n"]);
assert_eq!(out.code, 2);
assert!(out.err.contains("needs a value"));
}
#[test]
fn no_session_and_no_transcript_is_empty() {
let dir = std::env::temp_dir()
.join(format!("itok-tr-none-{}", std::process::id()));
std::fs::create_dir_all(&dir).ok();
let out = trace(&["-C".to_owned(), dir.display().to_string()]);
assert_eq!(out.code, 0);
assert!(out.out.is_empty());
}
#[test]
fn unknown_flags_are_usage_errors() {
let out = run_on("tool-shapes.jsonl", &["--nope"]);
assert_eq!(out.code, 2);
}
}