parse-run.mjs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. #!/usr/bin/env node
  2. // Parse Claude Code stream-json run log(s): tool-call sequence, token usage, and
  3. // RESIDUAL CONTEXT OCCUPANCY — how many tokens of the context window each tool
  4. // family's responses still occupy when the run ends.
  5. //
  6. // Usage: parse-run.mjs <run.jsonl> [run.t2.jsonl ...] [--envelope] [--answer <glob>]...
  7. // Multiple files = one multi-turn session's segments, IN ORDER (run-all.sh
  8. // writes run-<label>.jsonl, run-<label>.t2.jsonl, … for a `Q1||Q2||Q3` set).
  9. // `--resume` does not replay prior messages, so the segments concatenate
  10. // cleanly and token accounting carries across the boundary.
  11. //
  12. // `--envelope` additionally reports how the codegraph_explore responses were
  13. // DIVIDED across files — the per-file share of the source envelope (#1500).
  14. // `--answer <glob>` (repeatable, implies --envelope) marks the files that
  15. // actually answer the question and reports their combined share: bar 2 of the
  16. // CG-1/CG-22 allocation gate. See formatEnvelope for why it parses the
  17. // rendered markdown rather than the CG-4 diagnostic sidecar.
  18. //
  19. // ---------------------------------------------------------------------------
  20. // Why occupancy, and how it's measured
  21. // ---------------------------------------------------------------------------
  22. // A single-question A/B reports cost/tokens/time/tool-calls for ONE answer. It
  23. // cannot see what issue #1500 measured: a tool response stays in the window for
  24. // everything that follows, so it is charged against every later turn's headroom.
  25. // That is a per-session cost our single-question runs structurally miss.
  26. //
  27. // Tokens are MEASURED, not estimated at bytes/4. For assistant request k,
  28. // ctx_k = usage.input_tokens + cache_read_input_tokens + cache_creation_input_tokens
  29. // is the exact token count of that request's whole prompt. So
  30. // gap_k = ctx_k - ctx_{k-1}
  31. // is exactly the tokens appended since the previous request: the previous
  32. // assistant output (thinking + text + tool_use JSON) plus the tool_results and
  33. // user text that followed it. We split gap_k across those blocks in proportion
  34. // to their characters, which attributes each tool_result its measured share.
  35. // (Measured on real runs, explore output lands near 2.3 chars/token — bytes/4
  36. // under-counts it by ~40%, which is why the estimate isn't good enough.)
  37. //
  38. // Two traps this file works around, both verified against real logs:
  39. // * Claude Code emits ONE assistant event PER CONTENT BLOCK, all carrying the
  40. // same message.id and the same `usage`. Summing usage per event double-counts
  41. // every turn that emits both thinking and a tool_use — dedupe by message.id.
  42. // * The streamed `output_tokens` is a partial snapshot (observed `out=2` on a
  43. // turn that really generated ~1100). Never trust it; the char-proportional
  44. // split doesn't need it.
  45. //
  46. // Residual ≠ contributed. Content leaves the window two ways, and both are
  47. // tracked: a `compact_boundary` system event (everything prior is replaced by a
  48. // summary) and micro-compaction (ctx drops mid-run — oldest tool results are
  49. // dropped first, so eviction is applied FIFO).
  50. import { readFileSync } from 'fs';
  51. import { pathToFileURL } from 'url';
  52. // Nominal window for the share-of-window column. Override for a [1m] context.
  53. const WINDOW_TOKENS = Number(process.env.CG_WINDOW_TOKENS || 200_000);
  54. const CHARS_PER_TOKEN_FALLBACK = 3.0;
  55. /** Which tool family a tool_use belongs to. */
  56. function familyOf(name) {
  57. if (/codegraph/.test(name)) return 'codegraph';
  58. if (name === 'Read' || name === 'NotebookRead') return 'read';
  59. if (name === 'Grep' || name === 'Glob') return 'search';
  60. if (name === 'Bash' || name === 'BashOutput') return 'bash';
  61. return 'other';
  62. }
  63. const FAMILIES = ['codegraph', 'read', 'search', 'bash', 'other'];
  64. // The without-arm's way of getting the same bytes: reading and searching files.
  65. const FILE_ACCESS = ['read', 'search', 'bash'];
  66. // A Bash command that INVOKES the codegraph CLI, in any command position and by
  67. // any path. Mentions are not invocations: `grep codegraph src/`, `ls .codegraph`
  68. // and `which codegraph` all pass. Kept in step with run-all.sh's blocking hook.
  69. const CG_CLI_RE = /(^|[;&|(]|&&|\|\||\$\(|`)\s*(?:[A-Za-z_]\w*=\S*\s+)*[\w./~-]*codegraph(\s|$)/;
  70. const textOf = (content) =>
  71. Array.isArray(content) ? content.map((c) => c.text ?? (typeof c === 'string' ? c : JSON.stringify(c))).join('')
  72. : typeof content === 'string' ? content
  73. : content == null ? '' : JSON.stringify(content);
  74. /** Characters an assistant content block occupies once it is back in the prompt. */
  75. function assistantBlockChars(b) {
  76. if (b.type === 'text') return (b.text || '').length;
  77. if (b.type === 'thinking') return (b.thinking || '').length;
  78. if (b.type === 'tool_use') return JSON.stringify(b.input ?? {}).length + (b.name || '').length;
  79. return JSON.stringify(b).length;
  80. }
  81. /**
  82. * Parse one session (its segment files, in order) into tool + occupancy stats.
  83. * Exported so parse-bench-readme.mjs can aggregate without duplicating any of
  84. * this — deliberately NOT a separate module file: a new scripts/agent-eval/*.mjs
  85. * scores into the self-query eval fixture's own corpus and moves its numbers.
  86. */
  87. export function parseSession(files) {
  88. const events = [];
  89. for (const f of files) {
  90. for (const line of readFileSync(f, 'utf8').split('\n')) {
  91. if (!line) continue;
  92. try { events.push(JSON.parse(line)); } catch { /* partial line */ }
  93. }
  94. }
  95. const toolCalls = []; // display sequence
  96. const nameById = new Map(); // tool_use_id -> tool name
  97. const cliById = new Set(); // tool_use_ids that tried to run the codegraph CLI
  98. const counts = {}; // tool name -> calls
  99. // Attempts vs successes: run-all.sh's hook DENIES CLI invocations, and a
  100. // denied attempt puts no codegraph output in the window. Only a call that
  101. // actually returned content contaminates the arm.
  102. let initTools = null, result = null, raced = false, cliCalls = 0, cliContaminated = 0;
  103. const results = []; // one `result` event per session segment (multi-turn)
  104. let compactions = 0;
  105. // Raw codegraph_explore response text, in call order. Feeds the envelope view
  106. // (see formatEnvelope) — kept here rather than re-parsed from the log later so
  107. // a multi-segment session's responses stay in one ordered list.
  108. const exploreTexts = [];
  109. // A timeline of everything appended to the context, in order. `req` entries
  110. // are assistant requests (carrying that request's ctx); `add` entries are
  111. // characters appended (assistant output blocks, tool results, user text).
  112. const timeline = [];
  113. const seenMsgIds = new Set();
  114. for (const ev of events) {
  115. if (ev.type === 'system' && ev.subtype === 'init') {
  116. initTools = (ev.tools || []).filter((t) => /codegraph/.test(t));
  117. }
  118. if (ev.type === 'system' && (ev.subtype === 'compact_boundary' || ev.subtype === 'compaction')) {
  119. compactions++;
  120. timeline.push({ kind: 'compact' });
  121. }
  122. if (ev.type === 'assistant' && ev.message) {
  123. const id = ev.message.id;
  124. // One event per content block, same id + same usage: count usage once,
  125. // but take the content blocks from every event that carries the id.
  126. if (id && !seenMsgIds.has(id)) {
  127. seenMsgIds.add(id);
  128. const u = ev.message.usage || {};
  129. const ctx = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
  130. timeline.push({ kind: 'req', ctx, out: u.output_tokens || 0 });
  131. }
  132. for (const b of ev.message.content || []) {
  133. timeline.push({ kind: 'add', family: null, chars: assistantBlockChars(b) });
  134. if (b.type === 'tool_use') {
  135. nameById.set(b.id, b.name);
  136. counts[b.name] = (counts[b.name] || 0) + 1;
  137. let detail = '';
  138. if (b.name === 'Task') detail = ` [subagent_type=${b.input?.subagent_type ?? '?'}] ${(b.input?.description ?? '').slice(0, 40)}`;
  139. else if (/codegraph/.test(b.name)) detail = ` ${JSON.stringify(b.input?.query ?? b.input?.task ?? b.input?.symbol ?? '').slice(0, 60)}`;
  140. else if (b.name === 'Bash') {
  141. detail = ` ${(b.input?.command ?? '').slice(0, 50)}`;
  142. // An arm with no codegraph MCP can still shell out to the CLI — the
  143. // target repo carries the .codegraph/ index and the binary is on
  144. // PATH. That silently turns a "without" arm into codegraph-over-CLI.
  145. if (CG_CLI_RE.test(b.input?.command ?? '')) { cliCalls++; cliById.add(b.id); }
  146. }
  147. else if (b.name === 'Read') detail = ` ${(b.input?.file_path ?? '').split('/').slice(-1)[0]}`;
  148. toolCalls.push(`${b.name}${detail}`);
  149. }
  150. }
  151. }
  152. if (ev.type === 'user' && ev.message) {
  153. const content = ev.message.content;
  154. if (Array.isArray(content)) {
  155. for (const b of content) {
  156. if (b.type === 'tool_result') {
  157. const t = textOf(b.content);
  158. // MCP cold-start race: the agent fired before `serve --mcp` had
  159. // registered its tools, so it floundered into grep/Read. That
  160. // measures startup latency, not steady-state value — flag it.
  161. if (/No such tool available/.test(t)) raced = true;
  162. // A CLI attempt that came back an error was blocked (by the hook, or
  163. // by the binary being genuinely absent) and put nothing in context.
  164. if (cliById.has(b.tool_use_id) && !b.is_error) cliContaminated++;
  165. const name = nameById.get(b.tool_use_id) || '';
  166. if (/codegraph_explore/.test(name) && !b.is_error) exploreTexts.push(t);
  167. timeline.push({ kind: 'add', family: familyOf(name), chars: t.length, tool: name });
  168. } else {
  169. timeline.push({ kind: 'add', family: null, chars: textOf([b]).length });
  170. }
  171. }
  172. } else if (typeof content === 'string') {
  173. timeline.push({ kind: 'add', family: null, chars: content.length });
  174. }
  175. }
  176. if (ev.type === 'result') { result = ev; results.push(ev); }
  177. }
  178. // ---- Pass 1: chars/token, calibrated on tool-result-dominated gaps. ------
  179. // Splitting a gap in proportion to characters over-attributes to tool results
  180. // whenever the assistant's own output is under-represented in the transcript
  181. // (redacted/empty thinking blocks are the common case — a gap whose only
  182. // visible chars were a 73-char tool_result charged it the whole 830-token
  183. // delta, 5.5 tok/char). So calibrate the ratio on gaps that are ≥80% tool
  184. // result by characters, then price every result at that ratio.
  185. const reqIdx = timeline.map((t, i) => (t.kind === 'req' ? i : -1)).filter((i) => i >= 0);
  186. const gaps = [];
  187. for (let k = 1; k < reqIdx.length; k++) {
  188. const prev = timeline[reqIdx[k - 1]], cur = timeline[reqIdx[k]];
  189. let chars = 0, toolChars = 0, compacted = false;
  190. const byFamily = {};
  191. for (let i = reqIdx[k - 1] + 1; i < reqIdx[k]; i++) {
  192. const t = timeline[i];
  193. if (t.kind === 'compact') { compacted = true; continue; }
  194. if (t.kind !== 'add') continue;
  195. chars += t.chars;
  196. if (t.family) { toolChars += t.chars; byFamily[t.family] = (byFamily[t.family] || 0) + t.chars; }
  197. }
  198. gaps.push({ delta: cur.ctx - prev.ctx, chars, toolChars, byFamily, compacted });
  199. }
  200. const clean = gaps.filter((g) => !g.compacted && g.delta > 0 && g.chars > 500 && g.toolChars / g.chars >= 0.8);
  201. // A gap where the window also SHED content has a delta far below what was
  202. // added, which reads as absurdly dense text and would drag the whole run's
  203. // ratio with it. Shedding can only push a gap's chars/token UP, so take the
  204. // lower median as the honest centre and drop anything well above it, then
  205. // pool the survivors. (On runs that never shed, every ratio is within a few
  206. // percent of the others and this changes nothing.)
  207. const ratios = clean.map((g) => g.toolChars / g.delta).sort((a, b) => a - b);
  208. const lowerMedian = ratios.length ? ratios[Math.floor((ratios.length - 1) / 2)] : 0;
  209. let sumD = 0, sumC = 0;
  210. for (const g of clean) {
  211. if (lowerMedian > 0 && g.toolChars / g.delta > lowerMedian * 1.5) continue; // shed
  212. sumD += g.delta; sumC += g.toolChars;
  213. }
  214. if (sumD === 0) { // no clean gap — fall back to every growing gap, all chars
  215. for (const g of gaps) if (!g.compacted && g.delta > 0 && g.chars > 0) { sumD += g.delta; sumC += g.chars; }
  216. }
  217. const charsPerToken = sumD > 0 ? sumC / sumD : CHARS_PER_TOKEN_FALLBACK;
  218. const calibrated = sumD > 0;
  219. // How far a single result's token density strays from the run-level ratio.
  220. // On a gap that is almost entirely one tool result, `delta` IS that result's
  221. // token count, so |chars/ratio - delta| / delta is the attribution error for
  222. // that result. The median over such gaps is the metric's real error bar.
  223. const errs = [];
  224. for (const g of gaps) {
  225. if (g.compacted || g.delta <= 0 || g.chars <= 500) continue;
  226. if (g.toolChars / g.chars < 0.95) continue;
  227. errs.push(Math.abs(g.toolChars / charsPerToken - g.delta) / g.delta);
  228. }
  229. errs.sort((a, b) => a - b);
  230. const dispersion = errs.length ? errs[(errs.length - 1) >> 1] : null;
  231. // ---- Pass 2: attribute gap tokens, then apply evictions FIFO. ------------
  232. const contributed = Object.fromEntries(FAMILIES.map((f) => [f, 0]));
  233. const resultChars = Object.fromEntries(FAMILIES.map((f) => [f, 0]));
  234. const resultCount = Object.fromEntries(FAMILIES.map((f) => [f, 0]));
  235. for (const t of timeline) if (t.kind === 'add' && t.family) { resultChars[t.family] += t.chars; resultCount[t.family]++; }
  236. let queue = []; // resident contributions, oldest first
  237. let evicted = 0;
  238. const evict = (tokens) => {
  239. let left = tokens;
  240. while (left > 0 && queue.length) {
  241. const head = queue[0];
  242. if (head.tokens <= left) { left -= head.tokens; evicted += head.tokens; queue.shift(); }
  243. else { head.tokens -= left; evicted += left; left = 0; }
  244. }
  245. };
  246. for (const g of gaps) {
  247. if (g.compacted) {
  248. // Everything before the boundary is gone; the summary replaces it.
  249. evicted += queue.reduce((s, q) => s + q.tokens, 0);
  250. queue = [];
  251. }
  252. let toolTokens = 0;
  253. for (const [fam, ch] of Object.entries(g.byFamily)) {
  254. const tok = ch / charsPerToken;
  255. toolTokens += tok;
  256. contributed[fam] += tok;
  257. queue.push({ family: fam, tokens: tok });
  258. }
  259. // The gap grew by `delta`; the tool results account for `toolTokens` of it.
  260. // A shortfall means the window also shed content — micro-compaction drops
  261. // the OLDEST tool results first, so evict FIFO. The tolerance keeps
  262. // attribution noise (a run-level ratio priced against one gap's delta,
  263. // typically ±2%) from reading as an eviction; real shedding is thousands.
  264. const shortfall = toolTokens - g.delta;
  265. if (!g.compacted && shortfall > Math.max(200, toolTokens * 0.05)) evict(shortfall);
  266. }
  267. const residual = Object.fromEntries(FAMILIES.map((f) => [f, 0]));
  268. for (const q of queue) residual[q.family] += q.tokens;
  269. const ctxFinal = reqIdx.length ? timeline[reqIdx[reqIdx.length - 1]].ctx : 0;
  270. // The FIRST request's prompt is system + tool schemas + the question, before
  271. // any tool has answered. Differencing the arms' ctxBase prices codegraph's
  272. // FIXED occupancy — its tool schema and MCP `initialize` instructions — which
  273. // it pays whether or not the agent ever calls it.
  274. const ctxBase = reqIdx.length ? timeline[reqIdx[0]].ctx : 0;
  275. // Multi-turn: duration/cost/tokens are per-segment, so sum them. `result.usage`
  276. // is cumulative WITHIN a segment (verified: its in+cache+out equals the sum of
  277. // that segment's per-request prompts), so summing segments is correct and does
  278. // NOT double-count. It is a "tokens processed" figure — every request re-counts
  279. // the whole prefix — which is exactly why it can't answer the occupancy question.
  280. const sumUsage = (k) => results.reduce((s, r) => s + (r.usage?.[k] || 0), 0);
  281. const processed = sumUsage('input_tokens') + sumUsage('cache_read_input_tokens')
  282. + sumUsage('cache_creation_input_tokens') + sumUsage('output_tokens');
  283. return {
  284. files, toolCalls, counts, initTools, result, results, raced, cliCalls, cliContaminated,
  285. exploreTexts,
  286. ok: results.length > 0 && results.every((r) => r.subtype === 'success'),
  287. turns: reqIdx.length,
  288. tools: toolCalls.filter((t) => !t.startsWith('ToolSearch')).length,
  289. reads: counts.Read || 0,
  290. grep: (counts.Grep || 0) + (counts.Glob || 0),
  291. cg: Object.entries(counts).filter(([n]) => /codegraph/.test(n)).reduce((s, [, v]) => s + v, 0),
  292. dur: results.reduce((s, r) => s + (r.duration_ms || 0), 0) / 1000,
  293. cost: results.reduce((s, r) => s + (r.total_cost_usd || 0), 0),
  294. processed,
  295. occupancy: {
  296. ctxFinal, ctxBase, windowTokens: WINDOW_TOKENS,
  297. charsPerToken, calibrated, compactions, dispersion, evicted: Math.round(evicted),
  298. residual: Object.fromEntries(FAMILIES.map((f) => [f, Math.round(residual[f])])),
  299. contributed: Object.fromEntries(FAMILIES.map((f) => [f, Math.round(contributed[f])])),
  300. chars: resultChars, results: resultCount,
  301. residualFileAccess: Math.round(FILE_ACCESS.reduce((s, f) => s + residual[f], 0)),
  302. contributedFileAccess: Math.round(FILE_ACCESS.reduce((s, f) => s + contributed[f], 0)),
  303. charsFileAccess: FILE_ACCESS.reduce((s, f) => s + resultChars[f], 0),
  304. },
  305. };
  306. }
  307. /** The occupancy block, as printed under a run and reused by the aggregator. */
  308. export function formatOccupancy(s, indent = ' ') {
  309. const o = s.occupancy;
  310. const n = (x) => x.toLocaleString('en-US');
  311. const pctCtx = (t) => (o.ctxFinal > 0 ? ((t / o.ctxFinal) * 100).toFixed(1) : '0.0');
  312. const pctWin = (t) => ((t / o.windowTokens) * 100).toFixed(1);
  313. const rows = [];
  314. const row = (label, tok, chars, results) => rows.push(
  315. `${indent} ${label.padEnd(18)}${(n(tok) + ' tok').padStart(12)} ${(pctCtx(tok) + '%').padStart(6)} of ctx ` +
  316. `${(pctWin(tok) + '%').padStart(6)} of ${Math.round(o.windowTokens / 1000)}k win` +
  317. (chars !== undefined ? ` (${n(chars)} chars, ${results} result${results === 1 ? '' : 's'})` : '')
  318. );
  319. const out = [`${indent}Residual context occupancy at end of run:`];
  320. out.push(`${indent} ${'final context'.padEnd(18)}${(n(o.ctxFinal) + ' tok').padStart(12)} ${(pctWin(o.ctxFinal) + '%').padStart(6)} of ${Math.round(o.windowTokens / 1000)}k window`);
  321. row('codegraph', o.residual.codegraph, o.chars.codegraph, o.results.codegraph);
  322. row('Read', o.residual.read, o.chars.read, o.results.read);
  323. row('Grep/Glob', o.residual.search, o.chars.search, o.results.search);
  324. row('Bash', o.residual.bash, o.chars.bash, o.results.bash);
  325. row('→ file-access', o.residualFileAccess, o.charsFileAccess,
  326. o.results.read + o.results.search + o.results.bash);
  327. row('other tools', o.residual.other, o.chars.other, o.results.other);
  328. const toolTotal = Object.values(o.residual).reduce((a, b) => a + b, 0);
  329. row('base (prompt+prose)', Math.max(0, o.ctxFinal - toolTotal));
  330. out.push(`${indent} ${' of which fixed'.padEnd(18)}${(n(o.ctxBase) + ' tok').padStart(12)} system + tool schemas + question, before any tool answered`);
  331. out.push(...rows);
  332. const dropped = o.contributed.codegraph + o.contributedFileAccess + o.contributed.other
  333. - (o.residual.codegraph + o.residualFileAccess + o.residual.other);
  334. out.push(
  335. `${indent} measure: ${o.charsPerToken.toFixed(2)} chars/tok ${o.calibrated ? 'measured' : '(FALLBACK — no clean gap to calibrate on)'}` +
  336. (o.dispersion !== null ? ` ±${(o.dispersion * 100).toFixed(1)}%` : '') +
  337. ` · turns ${s.turns} · compactions ${o.compactions}` +
  338. (o.evicted > 0 || dropped > 1 ? ` · evicted ${n(o.evicted)} tok` : '')
  339. );
  340. return out.join('\n');
  341. }
  342. /**
  343. * How the codegraph_explore responses the agent received were DIVIDED across
  344. * files — the per-file share of the source envelope (#1500 / epic CG-1).
  345. *
  346. * Parsed out of the RENDERED MARKDOWN, not the CG-4 diagnostic sidecar: the
  347. * sidecar only exists on a post-CG-4 build, so it cannot measure a baseline arm.
  348. * The markdown parse is the only instrument that measures both arms of a
  349. * new-vs-baseline A/B the same way.
  350. *
  351. * `answerGlobs` marks the files that actually answer the question; the summary
  352. * reports their combined share, which is bar 2 of the CG-1/CG-22 gate.
  353. */
  354. export function formatEnvelope(exploreTexts, answerGlobs = [], indent = ' ') {
  355. // `tools/cache/**` -> /^tools\/cache\/.*$/ . Same semantics as probe-allocation.
  356. // The `**` sentinel is written as an escape, never a literal NUL byte — a raw
  357. // one makes git treat this whole script as binary and costs every future diff.
  358. const glob2re = (glob) => {
  359. const S = '\\u0000';
  360. const body = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&')
  361. .replace(/\*\*/g, S).replace(/\*/g, '[^/]*').replaceAll(S, '.*');
  362. return new RegExp(`^${body}$`);
  363. };
  364. const answerRes = answerGlobs.map(glob2re);
  365. const isAnswer = (p) => answerRes.some((re) => re.test(p));
  366. // Each rendered file section starts with **`path`** — its bytes run to the next
  367. // such header (or to the trailing guidance quote). Share is over the sum of the
  368. // sections, i.e. of the source envelope the allocator divides.
  369. const pooled = new Map();
  370. let envelope = 0;
  371. for (const text of exploreTexts) {
  372. const re = /^\*\*`([^`]+)`\*\*/gm;
  373. const marks = [];
  374. let m;
  375. while ((m = re.exec(text)) !== null) marks.push({ path: m[1], at: m.index });
  376. if (!marks.length) continue;
  377. const tail = text.indexOf('\n> ', marks[marks.length - 1].at);
  378. const end = tail === -1 ? text.length : tail;
  379. marks.forEach((mark, i) => {
  380. const chars = (i + 1 < marks.length ? marks[i + 1].at : end) - mark.at;
  381. pooled.set(mark.path, (pooled.get(mark.path) ?? 0) + chars);
  382. envelope += chars;
  383. });
  384. }
  385. const ranked = [...pooled.entries()]
  386. .map(([path, chars]) => ({ path, chars, share: envelope ? chars / envelope : 0, answer: isAnswer(path) }))
  387. .sort((a, b) => b.chars - a.chars);
  388. const answerChars = ranked.filter((r) => r.answer).reduce((s, r) => s + r.chars, 0);
  389. const pct = (f) => `${(f * 100).toFixed(1)}%`;
  390. const out = [];
  391. out.push(`${indent}Explore envelope: ${envelope.toLocaleString('en-US')} chars over ${exploreTexts.length} response(s)`);
  392. if (answerGlobs.length) {
  393. out.push(`${indent} answer-set share: ${pct(envelope ? answerChars / envelope : 0)} | top file answers: ${ranked[0]?.answer ?? false}`);
  394. }
  395. for (const f of ranked.slice(0, 12)) {
  396. out.push(`${indent} ${f.answer ? '*' : ' '} ${pct(f.share).padStart(6)} ${String(f.chars).padStart(6)} ${f.path}`);
  397. }
  398. if (ranked.length > 12) out.push(`${indent} … ${ranked.length - 12} more files`);
  399. return out.join('\n');
  400. }
  401. // ---------------------------------------------------------------------------
  402. // `--selftest`: the occupancy math over synthetic transcripts with known
  403. // answers. It lives here rather than in a test file on purpose — a new
  404. // scripts/agent-eval/*.mjs scores into the self-query eval fixture's corpus.
  405. function selftest() {
  406. const { writeFileSync, mkdtempSync } = require0('fs');
  407. const { join } = require0('path');
  408. const { tmpdir } = require0('os');
  409. const dir = mkdtempSync(join(tmpdir(), 'cg-occ-'));
  410. let n = 0, failures = 0;
  411. const check = (name, got, want, tol) => {
  412. n++;
  413. const ok = Math.abs(got - want) <= tol;
  414. if (!ok) failures++;
  415. console.log(`${ok ? ' ok ' : ' FAIL'} ${name}: got ${Math.round(got)}, want ${want} ±${tol}`);
  416. };
  417. // Builders for the event shapes Claude Code actually emits.
  418. const req = (ctx, id, blocks) => blocks.map((b) => JSON.stringify({
  419. type: 'assistant',
  420. message: { id, content: [b], usage: { input_tokens: ctx, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: 2 } },
  421. }));
  422. const use = (id, name) => ({ type: 'tool_use', id, name, input: {} });
  423. const res = (id, chars) => JSON.stringify({
  424. type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: id, content: [{ type: 'text', text: 'x'.repeat(chars) }] }] },
  425. });
  426. const done = () => JSON.stringify({ type: 'result', subtype: 'success', duration_ms: 1000, total_cost_usd: 0.1, usage: {} });
  427. const write = (name, lines) => { const f = join(dir, name); writeFileSync(f, lines.join('\n') + '\n'); return f; };
  428. // 1. Attribution: ratio 2.5 chars/tok, two families, no shedding.
  429. // 10,000 explore chars over a 4,000-tok gap; 5,000 Read chars over 2,000.
  430. let f = write('basic.jsonl', [
  431. ...req(10000, 'm1', [use('t1', 'mcp__codegraph__codegraph_explore')]),
  432. res('t1', 10000),
  433. ...req(14000, 'm2', [use('t2', 'Read')]),
  434. res('t2', 5000),
  435. ...req(16000, 'm3', [{ type: 'text', text: 'done' }]),
  436. done(),
  437. ]);
  438. let o = parseSession([f]).occupancy;
  439. check('chars/token', o.charsPerToken * 1000, 2500, 30);
  440. check('codegraph residual', o.residual.codegraph, 4000, 60);
  441. check('Read residual', o.residual.read, 2000, 40);
  442. check('file-access residual', o.residualFileAccess, 2000, 40);
  443. check('final context', o.ctxFinal, 16000, 0);
  444. check('fixed base', o.ctxBase, 10000, 0);
  445. check('nothing evicted', o.evicted, 0, 1);
  446. // 2. Dedupe: thinking + tool_use are two events sharing one id and one usage.
  447. // Counting usage per event would report 5 requests instead of 3.
  448. f = write('dupe.jsonl', [
  449. ...req(10000, 'm1', [{ type: 'thinking', thinking: '' }, use('t1', 'mcp__codegraph__codegraph_explore')]),
  450. res('t1', 10000),
  451. ...req(14000, 'm2', [{ type: 'thinking', thinking: '' }, use('t2', 'Read')]),
  452. res('t2', 5000),
  453. ...req(16000, 'm3', [{ type: 'text', text: 'done' }]),
  454. done(),
  455. ]);
  456. let s = parseSession([f]);
  457. check('turns deduped by message.id', s.turns, 3, 0);
  458. check('codegraph residual (deduped)', s.occupancy.residual.codegraph, 4000, 60);
  459. // 3. Compaction: the boundary clears everything resident before it.
  460. f = write('compact.jsonl', [
  461. ...req(10000, 'm1', [use('t1', 'mcp__codegraph__codegraph_explore')]),
  462. res('t1', 10000),
  463. ...req(14000, 'm2', [use('t2', 'mcp__codegraph__codegraph_explore')]),
  464. JSON.stringify({ type: 'system', subtype: 'compact_boundary' }),
  465. res('t2', 5000),
  466. ...req(8000, 'm3', [{ type: 'text', text: 'done' }]),
  467. done(),
  468. ]);
  469. o = parseSession([f]).occupancy;
  470. check('post-compaction residual = last result only', o.residual.codegraph, 2000, 40);
  471. check('contributed still counts both', o.contributed.codegraph, 6000, 80);
  472. // 4. Micro-compaction: context grows less than the results added, so the
  473. // oldest result is shed first (FIFO) — here explore, leaving Read.
  474. f = write('micro.jsonl', [
  475. ...req(10000, 'm1', [use('t1', 'mcp__codegraph__codegraph_explore')]),
  476. res('t1', 10000),
  477. ...req(14000, 'm2', [use('t2', 'Read')]),
  478. res('t2', 10000),
  479. ...req(14500, 'm3', [{ type: 'text', text: 'done' }]), // +500 for 4,000 tok of Read
  480. done(),
  481. ]);
  482. o = parseSession([f]).occupancy;
  483. check('FIFO evicted the older codegraph result', o.residual.codegraph, 500, 60);
  484. check('newer Read result survives', o.residual.read, 4000, 60);
  485. check('eviction recorded', o.evicted, 3500, 60);
  486. // 5. Multi-turn stitching: a resumed segment continues the same context, and
  487. // a turn that calls no tool leaves the earlier residual in place.
  488. const a = write('seg1.jsonl', [
  489. ...req(10000, 'm1', [use('t1', 'mcp__codegraph__codegraph_explore')]),
  490. res('t1', 10000),
  491. ...req(14000, 'm2', [{ type: 'text', text: 'answer one' }]),
  492. done(),
  493. ]);
  494. const b = write('seg2.jsonl', [
  495. ...req(14600, 'm3', [{ type: 'text', text: 'answer two, from what is already here' }]),
  496. done(),
  497. ]);
  498. s = parseSession([a, b]);
  499. check('stitched turns', s.turns, 3, 0);
  500. check('residual carries into turn 2', s.occupancy.residual.codegraph, 4000, 60);
  501. check('stitched final context', s.occupancy.ctxFinal, 14600, 0);
  502. check('stitched cost sums segments', s.cost * 100, 20, 0.1);
  503. console.log(`\n${n - failures}/${n} checks passed`);
  504. return failures;
  505. }
  506. // `--selftest` needs sync fs helpers the module path doesn't import at top level.
  507. function require0(m) { return process.getBuiltinModule(m); }
  508. const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
  509. if (isMain && process.argv.includes('--selftest')) process.exit(selftest() ? 1 : 0);
  510. if (isMain) {
  511. // `--answer <glob>` is repeatable and implies `--envelope`. Its VALUE is not a
  512. // run file, so consume it here rather than letting the positional filter below
  513. // mistake a glob for a log path.
  514. const argv = process.argv.slice(2);
  515. const files = [];
  516. const answerGlobs = [];
  517. let wantEnvelope = false;
  518. for (let i = 0; i < argv.length; i++) {
  519. if (argv[i] === '--envelope') wantEnvelope = true;
  520. else if (argv[i] === '--answer') { answerGlobs.push(argv[++i]); wantEnvelope = true; }
  521. else if (!argv[i].startsWith('--')) files.push(argv[i]);
  522. }
  523. if (!files.length) { console.error('usage: parse-run.mjs <run.jsonl> [run.t2.jsonl ...] [--envelope] [--answer <glob>]... | --selftest'); process.exit(1); }
  524. const s = parseSession(files);
  525. console.log(`\n=== ${files.map((f) => f.split('/').pop()).join(' + ')} ===`);
  526. console.log(`codegraph tools exposed: ${s.initTools ? s.initTools.length : '?'}${s.raced ? ' [MCP COLD-START RACE — tool call hit "No such tool available"]' : ''}`);
  527. if (s.cliContaminated) console.log(`!! ${s.cliContaminated} codegraph CLI call${s.cliContaminated === 1 ? '' : 's'} RETURNED OUTPUT via Bash — if this is a without-arm, the run is CONTAMINATED`);
  528. else if (s.cliCalls) console.log(` (${s.cliCalls} codegraph CLI attempt${s.cliCalls === 1 ? '' : 's'} blocked — no output entered the window)`);
  529. console.log(`\nTool calls (${s.toolCalls.length}):`);
  530. console.log(' by type:', JSON.stringify(s.counts));
  531. s.toolCalls.forEach((tc, i) => console.log(` ${i + 1}. ${tc}`));
  532. if (s.result) {
  533. const seg = s.results.length > 1 ? ` | ${s.results.length} segments (${s.results.map((r) => r.subtype).join(',')})` : '';
  534. console.log(`\nResult: ${s.result.subtype} | duration ${s.dur.toFixed(0)}s | turns ${s.turns}${seg}`);
  535. console.log(` tokens processed: ${s.processed.toLocaleString('en-US')} | cost $${s.cost.toFixed(3)}`);
  536. }
  537. console.log('');
  538. console.log(formatOccupancy(s));
  539. if (wantEnvelope) {
  540. console.log('');
  541. console.log(formatEnvelope(s.exploreTexts, answerGlobs));
  542. }
  543. }