parse-session.mjs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. #!/usr/bin/env node
  2. // Parse the newest Claude Code session log for a project + its subagent logs,
  3. // and report the tool-call breakdown (main + subagents). Works for interactive
  4. // runs (driven via itrun.sh) — Claude Code writes full transcripts to
  5. // ~/.claude/projects/<escaped-cwd>/<session>.jsonl with subagents/ alongside.
  6. import { readFileSync, readdirSync, statSync, existsSync, realpathSync } from 'fs';
  7. import { join } from 'path';
  8. import { homedir } from 'os';
  9. import { classifySufficiency, formatSufficiency } from './parse-run.mjs';
  10. const projectArg = process.argv[2];
  11. if (!projectArg) { console.error('usage: parse-session.mjs <project-dir>'); process.exit(1); }
  12. // Claude Code escapes the (real) cwd by replacing every "/" with "-".
  13. const real = realpathSync(projectArg);
  14. const escaped = real.replace(/\//g, '-');
  15. const projDir = join(homedir(), '.claude', 'projects', escaped);
  16. if (!existsSync(projDir)) { console.error('no session logs at', projDir); process.exit(1); }
  17. // Newest top-level session .jsonl
  18. const sessions = readdirSync(projDir)
  19. .filter(f => f.endsWith('.jsonl'))
  20. .map(f => ({ f, m: statSync(join(projDir, f)).mtimeMs }))
  21. .sort((a, b) => b.m - a.m);
  22. if (sessions.length === 0) { console.error('no .jsonl sessions in', projDir); process.exit(1); }
  23. const sessionId = sessions[0].f.replace('.jsonl', '');
  24. function tally(file) {
  25. const counts = {};
  26. for (const line of readFileSync(file, 'utf8').split('\n')) {
  27. if (!line) continue;
  28. let ev; try { ev = JSON.parse(line); } catch { continue; }
  29. const content = ev.message?.content;
  30. if (!Array.isArray(content)) continue;
  31. for (const b of content) {
  32. if (b.type === 'tool_use') counts[b.name] = (counts[b.name] || 0) + 1;
  33. }
  34. }
  35. return counts;
  36. }
  37. // Sum token usage from a transcript. The TUI's "Done (…Xk tokens…)" line only
  38. // covers a subagent's throughput; this works for main-thread runs too and is
  39. // consistent across both paths. `gen` = output, `fresh` = uncached input
  40. // (input + cache_creation), `cached` = cache reads (≈free), `total` = all.
  41. function sumTokens(file) {
  42. const t = { gen: 0, fresh: 0, cached: 0 };
  43. for (const line of readFileSync(file, 'utf8').split('\n')) {
  44. if (!line) continue;
  45. let ev; try { ev = JSON.parse(line); } catch { continue; }
  46. const u = ev.message?.usage;
  47. if (!u) continue;
  48. t.gen += u.output_tokens || 0;
  49. t.fresh += (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0);
  50. t.cached += u.cache_read_input_tokens || 0;
  51. }
  52. return t;
  53. }
  54. const mainCounts = tally(join(projDir, sessionId + '.jsonl'));
  55. // Subagent transcripts live under <session>/subagents/*.jsonl
  56. const subDir = join(projDir, sessionId, 'subagents');
  57. const subCounts = {};
  58. let subAgentFiles = 0;
  59. if (existsSync(subDir)) {
  60. for (const f of readdirSync(subDir).filter(f => f.endsWith('.jsonl'))) {
  61. subAgentFiles++;
  62. const c = tally(join(subDir, f));
  63. for (const [k, v] of Object.entries(c)) subCounts[k] = (subCounts[k] || 0) + v;
  64. }
  65. }
  66. const fmt = (counts) => Object.entries(counts).sort((a, b) => b[1] - a[1])
  67. .map(([k, v]) => ` ${String(v).padStart(3)} ${k}`).join('\n') || ' (none)';
  68. console.log(`session: ${sessionId}`);
  69. console.log(`\nMAIN thread tools:\n${fmt(mainCounts)}`);
  70. console.log(`\nSUBAGENT tools (${subAgentFiles} subagent transcript${subAgentFiles === 1 ? '' : 's'}):\n${fmt(subCounts)}`);
  71. const explore = subCounts['mcp__codegraph__codegraph_explore'] || mainCounts['mcp__codegraph__codegraph_explore'] || 0;
  72. const reads = (subCounts['Read'] || 0) + (mainCounts['Read'] || 0);
  73. const greps = (subCounts['Grep'] || 0) + (mainCounts['Grep'] || 0) + (subCounts['Bash'] || 0) + (mainCounts['Bash'] || 0);
  74. console.log(`\nVERDICT: codegraph_explore used ${explore}x | Read ${reads} | Grep/Bash ${greps}`);
  75. // Token totals (main + subagents), consistent across main-thread and subagent runs.
  76. const tok = { gen: 0, fresh: 0, cached: 0 };
  77. const addTok = (t) => { tok.gen += t.gen; tok.fresh += t.fresh; tok.cached += t.cached; };
  78. addTok(sumTokens(join(projDir, sessionId + '.jsonl')));
  79. if (existsSync(subDir)) {
  80. for (const f of readdirSync(subDir).filter(f => f.endsWith('.jsonl'))) addTok(sumTokens(join(subDir, f)));
  81. }
  82. const k = (n) => (n / 1000).toFixed(1) + 'k';
  83. console.log(`TOKENS: gen ${k(tok.gen)} | fresh-in ${k(tok.fresh)} | cached-in ${k(tok.cached)} | billable≈ ${k(tok.gen + tok.fresh)}`);
  84. // What the agent did after each codegraph_explore (CG-8) — the same classifier
  85. // the headless A/B uses, over the interactive transcript.
  86. //
  87. // A subagent's calls live in their OWN file here (headless stream-json
  88. // interleaves them into one stream instead), so they are stitched back in:
  89. // each `agent-*.meta.json` carries the `toolUseId` of the Task that spawned it,
  90. // which is exactly the `parent_tool_use_id` the classifier keys threads on.
  91. // Without that, a delegated search would score as "the agent moved on".
  92. const parseLines = (file, parentToolUseId) => readFileSync(file, 'utf8').split('\n')
  93. .filter(Boolean)
  94. .map((l) => { try { return JSON.parse(l); } catch { return null; } })
  95. .filter(Boolean)
  96. .map((ev) => (parentToolUseId ? { ...ev, parent_tool_use_id: parentToolUseId } : ev));
  97. const events = parseLines(join(projDir, sessionId + '.jsonl'));
  98. if (existsSync(subDir)) {
  99. for (const f of readdirSync(subDir).filter((f) => f.endsWith('.jsonl'))) {
  100. let parent = null;
  101. const meta = join(subDir, f.replace(/\.jsonl$/, '.meta.json'));
  102. if (existsSync(meta)) { try { parent = JSON.parse(readFileSync(meta, 'utf8')).toolUseId ?? null; } catch { /* unreadable */ } }
  103. events.push(...parseLines(join(subDir, f), parent ?? `subagent:${f}`));
  104. }
  105. }
  106. console.log('');
  107. console.log(formatSufficiency({ sufficiency: classifySufficiency(events) }, ''));