Public: anyone can read this; the crew can change it.
Traces: every conversation and run kept as a trace, imported from outside agents, and explored in the forge #17943
Merged 23h 44m ago, live in production
mason/forge:mason/17929-traces-every-conversation-and-run-kept-a → main 0 commits fork
8 files
changed +453
−0
docs/CLI.md +18
| @@ -505,3 +505,21 @@ the Data screen and the MCP `data` tool do. | ||
| 505 | 505 | $ forge data notes "select name from users" --json |
| 506 | 506 | [{"name":"ann"}] |
| 507 | 507 | |
| 508 | ||
| 509 | ## forge trace | |
| 510 | ||
| 511 | Reads one Claude Code session file (the JSONL under `~/.claude/projects/`) as a trace: turns, and under each the model replies and tool calls, one line a step with its time, tokens and outcome, and a running total last. It works on the file alone: nothing is sent anywhere, and no login is needed. | |
| 512 | ||
| 513 | - `forge trace <session.jsonl>` prints the tree. | |
| 514 | - `forge trace <session.jsonl> --otlp` prints OTLP/JSON with the OpenTelemetry GenAI conventions (`gen_ai.*`), one span for the thread, one per turn, one per step. | |
| 515 | ||
| 516 | A line that is not a record is skipped and counted; a file with no session records exits 1; one over 256 MB is refused before it is read. The file's bytes stay the record; the tree is rebuilt from them each time. | |
| 517 | ||
| 518 | console | |
| 519 | $ forge trace session.jsonl | |
| 520 | session 4f1c in /home/me/app | |
| 521 | ▾ 1. fix the login bug | |
| 522 | 09:00:01 claude-sonnet-5-5 I'll look 12+0c in 30 out 2.0s | |
| 523 | 09:00:03 Edit src/login.ts +3 −1 1.0s | |
| 524 | 1 steps in 3.0s, 12 in (0 cached), 30 out, 0 failed | |
| 525 |
docs/features/traces.md added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | --- | |
| 2 | topic: Your apps | |
| 3 | row: Traces: read an outside agent session as turns and steps | |
| 4 | --- | |
| 5 | # Traces | |
| 6 | ||
| 7 | Every conversation and run is a record the forge keeps; a trace is the same record read as a thread of turns and steps (#17929). This first slice reads a session from an outside agent, Claude Code's JSONL, and no more. | |
| 8 | ||
| 9 | - `forge trace <session.jsonl>` prints the tree: each turn's prompt, each step on one line (`Edit foo.ts +12 −3`, tokens, time), a total. Terminal door: `src/cli/commands/trace.ts`; the tree is also what `src/tui/` will show. | |
| 10 | - `forge trace <session.jsonl> --otlp` prints OTLP/JSON with the OpenTelemetry GenAI conventions, so a trace stays portable. Ids are derived from the session, so the same file always exports the same document. | |
| 11 | ||
| 12 | Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` (the reader), `src/trace/otlp.ts` (the export). Not yet: Codex files, storing an import, the /traces page, cost (the file holds none), compare, share. | |
| 13 | ||
| 14 | The file is read whole, then parsed, so the 256 MB limit is memory-bound: a session near it holds a few copies at once. Streaming the read is a later step. |
src/cli/commands/index.ts +2
| @@ -23,6 +23,7 @@ import { command as talk } from "./talk.ts"; | ||
| 23 | 23 | import { command as newApp } from "./new.ts"; |
| 24 | 24 | import { command as ship } from "./ship.ts"; |
| 25 | 25 | import { command as data } from "./data.ts"; |
| 26 | import { command as trace } from "./trace.ts"; | |
| 26 | 27 | import type { Command } from "./types.ts"; |
| 27 | 28 | |
| 28 | 29 | export const commands: readonly Command[] = [ |
| @@ -46,4 +47,5 @@ export const commands: readonly Command[] = [ | ||
| 46 | 47 | newApp, |
| 47 | 48 | ship, |
| 48 | 49 | data, |
| 50 | trace, | |
| 49 | 51 | ]; |
src/cli/commands/trace.ts added +60
| @@ -0,0 +1,60 @@ | ||
| 1 | import { readFile, stat } from "node:fs/promises"; | |
| 2 | import { EXIT } from "../exit.ts"; | |
| 3 | import { parseClaudeSession } from "../../trace/claude_code.ts"; | |
| 4 | import { totalsOf, type Trace } from "../../trace/model.ts"; | |
| 5 | import { toOtlp } from "../../trace/otlp.ts"; | |
| 6 | import type { Command } from "./types.ts"; | |
| 7 | ||
| 8 | /** A session file bigger than this is refused before it is read. */ | |
| 9 | export const MAX_SESSION_BYTES = 256 * 1024 * 1024; | |
| 10 | ||
| 11 | const clock = (ms: number): string => (ms === 0 ? "" : new Date(ms).toISOString().slice(11, 19)); | |
| 12 | const span = (ms: number): string => (ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`); | |
| 13 | ||
| 14 | /** The trace as the tree a reader scans: each turn, each step one line, a running total last. */ | |
| 15 | export function traceLines(trace: Trace): string[] { | |
| 16 | const out = [`session ${trace.id || "(unnamed)"}${trace.cwd === undefined ? "" : ` in ${trace.cwd}`}`]; | |
| 17 | for (const turn of trace.turns) { | |
| 18 | out.push(`▾ ${turn.index + 1}. ${turn.prompt || "(no prompt)"}`); | |
| 19 | for (const st of turn.steps) { | |
| 20 | const tokens = st.kind === "model" ? ` ${st.tokensIn}+${st.tokensCached}c in ${st.tokensOut} out` : ""; | |
| 21 | const bad = st.outcome === "error" ? " ✗" : ""; | |
| 22 | out.push(` ${clock(st.startMs)} ${st.line}${tokens} ${span(st.endMs - st.startMs)}${bad}`); | |
| 23 | } | |
| 24 | } | |
| 25 | const t = totalsOf(trace); | |
| 26 | out.push(`${t.steps} steps in ${span(t.endMs - t.startMs)}, ${t.tokensIn} in (${t.tokensCached} cached), ${t.tokensOut} out, ${t.errors} failed`); | |
| 27 | if (trace.skipped > 0) out.push(`${trace.skipped} lines were not records and were skipped`); | |
| 28 | return out; | |
| 29 | } | |
| 30 | ||
| 31 | export const command: Command = { | |
| 32 | name: "trace", | |
| 33 | usage: { synopsis: "forge trace <session.jsonl>", flags: "[--otlp] read a Claude Code session as a trace" }, | |
| 34 | async run(out, args) { | |
| 35 | const file = args.positional[0]; | |
| 36 | if (file === undefined) { | |
| 37 | out.err("forge trace: which file? e.g. forge trace ~/.claude/projects/app/session.jsonl"); | |
| 38 | return EXIT.usage; | |
| 39 | } | |
| 40 | let text: string; | |
| 41 | try { | |
| 42 | if ((await stat(file)).size > MAX_SESSION_BYTES) { | |
| 43 | out.err(`forge trace: ${file} is over ${MAX_SESSION_BYTES / 1024 / 1024} MB`); | |
| 44 | return EXIT.usage; | |
| 45 | } | |
| 46 | text = await readFile(file, "utf8"); | |
| 47 | } catch { | |
| 48 | out.err(`forge trace: cannot read ${file}`); | |
| 49 | return EXIT.failed; | |
| 50 | } | |
| 51 | const trace = parseClaudeSession(text); | |
| 52 | if (trace.turns.length === 0) { | |
| 53 | out.err(`forge trace: ${file} holds no Claude Code session records`); | |
| 54 | return EXIT.failed; | |
| 55 | } | |
| 56 | if (args.flag("otlp")) out.line(JSON.stringify(toOtlp(trace))); | |
| 57 | else for (const line of traceLines(trace)) out.line(line); | |
| 58 | return EXIT.ok; | |
| 59 | }, | |
| 60 | }; |
src/trace/claude_code.ts added +139
| @@ -0,0 +1,139 @@ | ||
| 1 | /** | |
| 2 | * Claude Code's session JSONL, read into a `Trace` (#17929). One record per | |
| 3 | * line: `user` and `assistant` messages whose content blocks are text, | |
| 4 | * `tool_use` and `tool_result`. Claude Code writes one line per content block | |
| 5 | * of a model reply, each repeating the reply's `message.id` and usage, so a | |
| 6 | * reply is counted once. A line that is not a record is counted in `skipped`. | |
| 7 | */ | |
| 8 | import type { Outcome, Step, Trace, Turn } from "./model.ts"; | |
| 9 | ||
| 10 | const MAX_LINE = 4 * 1024 * 1024; | |
| 11 | const LINE_CHARS = 120; | |
| 12 | ||
| 13 | type Json = Record<string, unknown>; | |
| 14 | const obj = (v: unknown): Json | undefined => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Json) : undefined); | |
| 15 | const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined); | |
| 16 | const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0); | |
| 17 | ||
| 18 | /** A terminal line is one line of printable text, cut to a width. */ | |
| 19 | export function oneLine(text: string, max = LINE_CHARS): string { | |
| 20 | const flat = text.replace(/[\x00-\x1f\x7f-\x9f\u00a0\u2028\u2029]+/g, " ").trim(); | |
| 21 | return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat; | |
| 22 | } | |
| 23 | ||
| 24 | const lines = (s: string): number => (s === "" ? 0 : s.split("\n").length); | |
| 25 | ||
| 26 | /** `Edit foo.ts +12 −3`, `Bash ls -l`, `Read a.ts`: the tool and what it was pointed at. */ | |
| 27 | export function toolLine(name: string, input: Json): string { | |
| 28 | const target = str(input.file_path) ?? str(input.path) ?? str(input.command) ?? str(input.pattern) ?? str(input.url) ?? str(input.description) ?? ""; | |
| 29 | const old = str(input.old_string); | |
| 30 | const next = str(input.new_string) ?? str(input.content); | |
| 31 | let delta = ""; | |
| 32 | if (name === "Edit" && old !== undefined && next !== undefined) delta = ` +${lines(next)} −${lines(old)}`; | |
| 33 | else if (name === "Write" && next !== undefined) delta = ` +${lines(next)}`; | |
| 34 | return oneLine(`${name} ${target}${delta}`); | |
| 35 | } | |
| 36 | ||
| 37 | const textOf = (content: unknown): string => { | |
| 38 | if (typeof content === "string") return content; | |
| 39 | if (!Array.isArray(content)) return ""; | |
| 40 | return content.map((b) => (str(obj(b)?.type) === "text" ? (str(obj(b)?.text) ?? "") : "")).join("\n"); | |
| 41 | }; | |
| 42 | ||
| 43 | export function parseClaudeSession(text: string): Trace { | |
| 44 | const trace: Trace = { source: "claude-code", id: "", cwd: undefined, turns: [], skipped: 0 }; | |
| 45 | const open = new Map<string, Step>(); | |
| 46 | const replies = new Map<string, Step>(); | |
| 47 | let turn: Turn | undefined; | |
| 48 | let last = 0; | |
| 49 | ||
| 50 | const turnAt = (ms: number): Turn => { | |
| 51 | if (turn === undefined) { | |
| 52 | turn = { index: 0, prompt: "", startMs: ms, steps: [] }; | |
| 53 | trace.turns.push(turn); | |
| 54 | } | |
| 55 | return turn; | |
| 56 | }; | |
| 57 | ||
| 58 | for (const raw of text.split("\n")) { | |
| 59 | if (raw.trim() === "") continue; | |
| 60 | let rec: Json | undefined; | |
| 61 | if (raw.length <= MAX_LINE) { | |
| 62 | try { | |
| 63 | rec = obj(JSON.parse(raw)); | |
| 64 | } catch { | |
| 65 | rec = undefined; | |
| 66 | } | |
| 67 | } | |
| 68 | const kind = str(rec?.type); | |
| 69 | const message = obj(rec?.message); | |
| 70 | if (rec === undefined || message === undefined || (kind !== "user" && kind !== "assistant")) { | |
| 71 | trace.skipped += 1; | |
| 72 | continue; | |
| 73 | } | |
| 74 | const at = Date.parse(str(rec.timestamp) ?? ""); | |
| 75 | const ms = Number.isFinite(at) ? at : last; | |
| 76 | last = ms; | |
| 77 | if (trace.id === "") trace.id = str(rec.sessionId) ?? ""; | |
| 78 | trace.cwd ??= str(rec.cwd); | |
| 79 | const content = message.content; | |
| 80 | const blocks = Array.isArray(content) ? content.map(obj) : []; | |
| 81 | ||
| 82 | if (kind === "user") { | |
| 83 | const results = blocks.filter((b) => str(b?.type) === "tool_result"); | |
| 84 | for (const b of results) { | |
| 85 | const step = open.get(str(b?.tool_use_id) ?? ""); | |
| 86 | if (step === undefined) continue; | |
| 87 | step.endMs = Math.max(ms, step.startMs); | |
| 88 | step.outcome = b?.is_error === true ? "error" : "ok"; | |
| 89 | open.delete(str(b?.tool_use_id) ?? ""); | |
| 90 | } | |
| 91 | const prompt = results.length > 0 || rec.isMeta === true ? "" : textOf(content); | |
| 92 | if (prompt.trim() !== "") { | |
| 93 | turn = { index: trace.turns.length, prompt: oneLine(prompt, 300), startMs: ms, steps: [] }; | |
| 94 | trace.turns.push(turn); | |
| 95 | } | |
| 96 | continue; | |
| 97 | } | |
| 98 | ||
| 99 | const into = turnAt(ms); | |
| 100 | const usage = obj(message.usage); | |
| 101 | const id = str(message.id) ?? str(rec.uuid) ?? `m${into.steps.length}`; | |
| 102 | let reply = replies.get(id); | |
| 103 | if (reply === undefined) { | |
| 104 | reply = { id, kind: "model", name: str(message.model) ?? "unknown", line: "", startMs: ms, endMs: ms, model: str(message.model), tokensIn: 0, tokensCached: 0, tokensOut: 0, outcome: "ok" }; | |
| 105 | replies.set(id, reply); | |
| 106 | into.steps.push(reply); | |
| 107 | } | |
| 108 | reply.endMs = Math.max(reply.endMs, ms); | |
| 109 | if (usage !== undefined) { | |
| 110 | // Later lines of one reply carry the final counts; take the largest. | |
| 111 | reply.tokensIn = Math.max(reply.tokensIn, num(usage.input_tokens)); | |
| 112 | reply.tokensCached = Math.max(reply.tokensCached, num(usage.cache_read_input_tokens)); | |
| 113 | reply.tokensOut = Math.max(reply.tokensOut, num(usage.output_tokens)); | |
| 114 | } | |
| 115 | const said = textOf(content); | |
| 116 | reply.line = oneLine(`${reply.name} ${said !== "" ? said : reply.line.slice(reply.name.length + 1)}`); | |
| 117 | for (const b of blocks) { | |
| 118 | if (str(b?.type) !== "tool_use") continue; | |
| 119 | const name = str(b?.name) ?? "tool"; | |
| 120 | const toolId = str(b?.id) ?? `${id}:${into.steps.length}`; | |
| 121 | const step: Step = { | |
| 122 | id: toolId, | |
| 123 | kind: name === "Task" || rec.isSidechain === true ? "subagent" : "tool", | |
| 124 | name, | |
| 125 | line: toolLine(name, obj(b?.input) ?? {}), | |
| 126 | startMs: ms, | |
| 127 | endMs: ms, | |
| 128 | model: undefined, | |
| 129 | tokensIn: 0, | |
| 130 | tokensCached: 0, | |
| 131 | tokensOut: 0, | |
| 132 | outcome: "unknown" satisfies Outcome, | |
| 133 | }; | |
| 134 | open.set(toolId, step); | |
| 135 | into.steps.push(step); | |
| 136 | } | |
| 137 | } | |
| 138 | return trace; | |
| 139 | } |
src/trace/model.ts added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | /** | |
| 2 | * The normalized shape of a trace (#17929): thread → turns → steps. Plain data; | |
| 3 | * every reader (the terminal, OTLP export) is handed one of these, and each is | |
| 4 | * rebuilt from raw bytes, never stored in place of them. | |
| 5 | */ | |
| 6 | ||
| 7 | export type StepKind = "model" | "tool" | "subagent"; | |
| 8 | export type Outcome = "ok" | "error" | "unknown"; | |
| 9 | ||
| 10 | export interface Step { | |
| 11 | id: string; | |
| 12 | kind: StepKind; | |
| 13 | /** The model's name for a model step; the tool's for a tool or subagent step. */ | |
| 14 | name: string; | |
| 15 | /** One line a reader scans: `Edit foo.ts +12 −3`. */ | |
| 16 | line: string; | |
| 17 | startMs: number; | |
| 18 | endMs: number; | |
| 19 | model: string | undefined; | |
| 20 | tokensIn: number; | |
| 21 | tokensCached: number; | |
| 22 | tokensOut: number; | |
| 23 | outcome: Outcome; | |
| 24 | } | |
| 25 | ||
| 26 | export interface Turn { | |
| 27 | index: number; | |
| 28 | prompt: string; | |
| 29 | startMs: number; | |
| 30 | steps: Step[]; | |
| 31 | } | |
| 32 | ||
| 33 | export interface Trace { | |
| 34 | source: "claude-code"; | |
| 35 | id: string; | |
| 36 | cwd: string | undefined; | |
| 37 | turns: Turn[]; | |
| 38 | /** Lines of the file that were not a record; counted, never fatal. */ | |
| 39 | skipped: number; | |
| 40 | } | |
| 41 | ||
| 42 | /** Every step of a trace in order. */ | |
| 43 | export function stepsOf(trace: Trace): Step[] { | |
| 44 | return trace.turns.flatMap((t) => t.steps); | |
| 45 | } | |
| 46 | ||
| 47 | export interface Totals { | |
| 48 | steps: number; | |
| 49 | tokensIn: number; | |
| 50 | tokensCached: number; | |
| 51 | tokensOut: number; | |
| 52 | errors: number; | |
| 53 | startMs: number; | |
| 54 | endMs: number; | |
| 55 | } | |
| 56 | ||
| 57 | /** The running total the trace page and the terminal state beside the tree. */ | |
| 58 | export function totalsOf(trace: Trace): Totals { | |
| 59 | const all = stepsOf(trace); | |
| 60 | const t: Totals = { steps: all.length, tokensIn: 0, tokensCached: 0, tokensOut: 0, errors: 0, startMs: 0, endMs: 0 }; | |
| 61 | for (const s of all) { | |
| 62 | t.tokensIn += s.tokensIn; | |
| 63 | t.tokensCached += s.tokensCached; | |
| 64 | t.tokensOut += s.tokensOut; | |
| 65 | if (s.outcome === "error") t.errors += 1; | |
| 66 | } | |
| 67 | let start = Infinity; | |
| 68 | for (const x of trace.turns) if (x.startMs < start) start = x.startMs; | |
| 69 | let end = -Infinity; | |
| 70 | for (const s of all) { | |
| 71 | if (s.startMs < start) start = s.startMs; | |
| 72 | if (s.endMs > end) end = s.endMs; | |
| 73 | } | |
| 74 | if (Number.isFinite(start)) { | |
| 75 | t.startMs = start; | |
| 76 | t.endMs = Math.max(end, start); | |
| 77 | } | |
| 78 | return t; | |
| 79 | } |
src/trace/otlp.ts added +66
| @@ -0,0 +1,66 @@ | ||
| 1 | /** | |
| 2 | * A `Trace` as OTLP/JSON with the OpenTelemetry GenAI conventions (#17929): | |
| 3 | * one span for the thread, one per turn, one per step, so a trace stays | |
| 4 | * portable. Ids are derived from the session and step ids, so exporting twice | |
| 5 | * gives the same document. | |
| 6 | */ | |
| 7 | import { stepsOf, type Step, type Trace } from "./model.ts"; | |
| 8 | ||
| 9 | type Attr = { key: string; value: { stringValue: string } | { intValue: string } }; | |
| 10 | const s = (key: string, value: string): Attr => ({ key, value: { stringValue: value } }); | |
| 11 | const n = (key: string, value: number): Attr => ({ key, value: { intValue: String(value) } }); | |
| 12 | ||
| 13 | const hex = (text: string, chars: number): string => new Bun.CryptoHasher("sha256").update(text).digest("hex").slice(0, chars); | |
| 14 | const nano = (ms: number): string => String(BigInt(Math.max(0, ms)) * 1_000_000n); | |
| 15 | ||
| 16 | const OPERATION = { model: "chat", tool: "execute_tool", subagent: "invoke_agent" } as const; | |
| 17 | ||
| 18 | function stepAttrs(step: Step): Attr[] { | |
| 19 | const a = [s("gen_ai.operation.name", OPERATION[step.kind])]; | |
| 20 | if (step.kind === "model") { | |
| 21 | a.push(s("gen_ai.request.model", step.model ?? step.name), n("gen_ai.usage.input_tokens", step.tokensIn), n("gen_ai.usage.output_tokens", step.tokensOut), n("gen_ai.usage.cache_read.input_tokens", step.tokensCached)); | |
| 22 | } else { | |
| 23 | a.push(s("gen_ai.tool.name", step.name)); | |
| 24 | if (step.kind === "subagent") a.push(s("gen_ai.agent.name", step.name)); | |
| 25 | } | |
| 26 | if (step.outcome === "error") a.push(s("error.type", "tool_error")); | |
| 27 | return a; | |
| 28 | } | |
| 29 | ||
| 30 | export function toOtlp(trace: Trace): object { | |
| 31 | const traceId = hex(`trace:${trace.id}`, 32); | |
| 32 | const rootId = hex(`root:${trace.id}`, 16); | |
| 33 | const span = (id: string, parent: string | undefined, name: string, from: number, to: number, attributes: Attr[]) => ({ | |
| 34 | traceId, | |
| 35 | spanId: id, | |
| 36 | ...(parent === undefined ? {} : { parentSpanId: parent }), | |
| 37 | name, | |
| 38 | kind: 1, | |
| 39 | startTimeUnixNano: nano(from), | |
| 40 | endTimeUnixNano: nano(Math.max(from, to)), | |
| 41 | attributes, | |
| 42 | status: attributes.some((x) => x.key === "error.type") ? { code: 2 } : { code: 1 }, | |
| 43 | }); | |
| 44 | const all = stepsOf(trace); | |
| 45 | let first = Infinity; | |
| 46 | for (const t of trace.turns) if (t.startMs < first) first = t.startMs; | |
| 47 | let last = -Infinity; | |
| 48 | for (const x of all) { | |
| 49 | if (x.startMs < first) first = x.startMs; | |
| 50 | if (x.endMs > last) last = x.endMs; | |
| 51 | } | |
| 52 | last = Math.max(last, first); | |
| 53 | const spans = [span(rootId, undefined, "invoke_agent claude-code", Number.isFinite(first) ? first : 0, Number.isFinite(last) ? last : 0, [s("gen_ai.operation.name", "invoke_agent"), s("gen_ai.conversation.id", trace.id), s("gen_ai.provider.name", "anthropic")])]; | |
| 54 | for (const turn of trace.turns) { | |
| 55 | const turnId = hex(`turn:${trace.id}:${turn.index}`, 16); | |
| 56 | let end = turn.startMs; | |
| 57 | for (const x of turn.steps) if (x.endMs > end) end = x.endMs; | |
| 58 | spans.push(span(turnId, rootId, `turn ${turn.index + 1}`, turn.startMs, end, [s("gen_ai.conversation.id", trace.id), n("forge.turn.index", turn.index)])); | |
| 59 | for (const step of turn.steps) { | |
| 60 | spans.push(span(hex(`step:${trace.id}:${step.id}`, 16), turnId, `${OPERATION[step.kind]} ${step.name}`, step.startMs, step.endMs, stepAttrs(step))); | |
| 61 | } | |
| 62 | } | |
| 63 | return { | |
| 64 | resourceSpans: [{ resource: { attributes: [s("service.name", "forge-traces"), s("forge.trace.source", trace.source)] }, scopeSpans: [{ scope: { name: "forge.traces" }, spans }] }], | |
| 65 | }; | |
| 66 | } |
test/trace.test.ts added +75
| @@ -0,0 +1,75 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { parseClaudeSession } from "../src/trace/claude_code.ts"; | |
| 3 | import { totalsOf } from "../src/trace/model.ts"; | |
| 4 | import { toOtlp } from "../src/trace/otlp.ts"; | |
| 5 | import { traceLines, command } from "../src/cli/commands/trace.ts"; | |
| 6 | import { createOut } from "../src/cli/out.ts"; | |
| 7 | import { parseArgs } from "../src/cli/args.ts"; | |
| 8 | import { mkdtempSync, writeFileSync } from "node:fs"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | ||
| 12 | const rec = (o: object): string => JSON.stringify({ sessionId: "s1", cwd: "/w", ...o }); | |
| 13 | const SESSION = [ | |
| 14 | rec({ type: "user", timestamp: "2026-12-01T09:00:00Z", message: { role: "user", content: "fix the login bug" } }), | |
| 15 | rec({ type: "assistant", timestamp: "2026-12-01T09:00:01Z", message: { id: "m1", model: "claude-x", role: "assistant", content: [{ type: "text", text: "Looking" }], usage: { input_tokens: 5, cache_read_input_tokens: 7, output_tokens: 1 } } }), | |
| 16 | rec({ type: "assistant", timestamp: "2026-12-01T09:00:02Z", message: { id: "m1", model: "claude-x", role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Edit", input: { file_path: "a.ts", old_string: "a", new_string: "a\nb\nc" } }], usage: { input_tokens: 5, cache_read_input_tokens: 7, output_tokens: 9 } } }), | |
| 17 | rec({ type: "user", timestamp: "2026-12-01T09:00:04Z", message: { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }] } }), | |
| 18 | rec({ type: "assistant", timestamp: "2026-12-01T09:00:05Z", message: { id: "m2", model: "claude-x", role: "assistant", content: [{ type: "tool_use", id: "t2", name: "Bash", input: { command: "bun test\nx" } }] } }), | |
| 19 | rec({ type: "user", timestamp: "2026-12-01T09:00:06Z", message: { role: "user", content: [{ type: "tool_result", tool_use_id: "t2", is_error: true, content: "no" }] } }), | |
| 20 | "not json", | |
| 21 | rec({ type: "summary" }), | |
| 22 | ].join("\n"); | |
| 23 | ||
| 24 | test("a session becomes turns and steps, a reply counted once", () => { | |
| 25 | const t = parseClaudeSession(SESSION); | |
| 26 | expect(t.id).toBe("s1"); | |
| 27 | expect(t.skipped).toBe(2); | |
| 28 | expect(t.turns.length).toBe(1); | |
| 29 | const [reply, edit, bash] = [t.turns[0]!.steps[0]!, t.turns[0]!.steps[1]!, t.turns[0]!.steps[3]!]; | |
| 30 | expect(reply).toMatchObject({ kind: "model", tokensIn: 5, tokensCached: 7, tokensOut: 9 }); | |
| 31 | expect(edit).toMatchObject({ kind: "tool", line: "Edit a.ts +3 −1", outcome: "ok", endMs: Date.parse("2026-12-01T09:00:04Z") }); | |
| 32 | expect(bash).toMatchObject({ line: "Bash bun test x", outcome: "error" }); | |
| 33 | expect(totalsOf(t)).toMatchObject({ steps: 4, tokensIn: 5, tokensOut: 9, errors: 1 }); | |
| 34 | expect(traceLines(t).at(-2)).toContain("4 steps in 6.0s"); | |
| 35 | }); | |
| 36 | ||
| 37 | test("OTLP carries the GenAI attributes and is stable", () => { | |
| 38 | const t = parseClaudeSession(SESSION); | |
| 39 | const doc = JSON.stringify(toOtlp(t)); | |
| 40 | expect(doc).toBe(JSON.stringify(toOtlp(t))); | |
| 41 | expect(doc).toContain('"gen_ai.usage.output_tokens"'); | |
| 42 | expect(doc).toContain('"gen_ai.tool.name"'); | |
| 43 | const spans = (toOtlp(t) as { resourceSpans: { scopeSpans: { spans: { traceId: string; parentSpanId?: string }[] }[] }[] }).resourceSpans[0]!.scopeSpans[0]!.spans; | |
| 44 | expect(spans.length).toBe(1 + 1 + 4); | |
| 45 | expect(new Set(spans.map((s) => s.traceId)).size).toBe(1); | |
| 46 | expect(spans[0]!.traceId).toHaveLength(32); | |
| 47 | }); | |
| 48 | ||
| 49 | test("forge trace reads a file, and says so when it holds nothing", async () => { | |
| 50 | const dir = mkdtempSync(join(tmpdir(), "trace-")); | |
| 51 | writeFileSync(join(dir, "s.jsonl"), SESSION); | |
| 52 | writeFileSync(join(dir, "e.jsonl"), "hello\n"); | |
| 53 | const run = async (argv: string[]) => { | |
| 54 | const said: string[] = []; | |
| 55 | const out = { ...createOut(), line: (x = "") => void said.push(x), err: (x: string) => void said.push(x) }; | |
| 56 | const code = await command.run(out, parseArgs(["trace", ...argv]), () => {}, { ask: async () => null }, argv); | |
| 57 | return { code, said: said.join("\n") }; | |
| 58 | }; | |
| 59 | expect((await run([join(dir, "s.jsonl")])).said).toContain("▾ 1. fix the login bug"); | |
| 60 | expect(JSON.parse((await run([join(dir, "s.jsonl"), "--otlp"])).said).resourceSpans).toBeArray(); | |
| 61 | expect((await run([join(dir, "e.jsonl")])).code).toBe(1); | |
| 62 | expect((await run([])).code).toBe(2); | |
| 63 | }); | |
| 64 | ||
| 65 | test("a very long session totals and exports without a stack overflow", () => { | |
| 66 | const steps = Array.from({ length: 200_000 }, (_, i) => ({ | |
| 67 | id: `s${i}`, kind: "tool" as const, name: "Edit", line: "Edit a.ts", startMs: 1000 + i, endMs: 1001 + i, | |
| 68 | model: undefined, tokensIn: 1, tokensCached: 0, tokensOut: 1, outcome: "ok" as const, | |
| 69 | })); | |
| 70 | const trace = { source: "claude-code" as const, id: "big", cwd: undefined, skipped: 0, turns: [{ index: 0, prompt: "p", startMs: 1000, steps }] }; | |
| 71 | const totals = totalsOf(trace); | |
| 72 | expect(totals).toMatchObject({ steps: 200_000, startMs: 1000, endMs: 1001 + 199_999 }); | |
| 73 | const doc = toOtlp(trace) as { resourceSpans: { scopeSpans: { spans: unknown[] }[] }[] }; | |
| 74 | expect(doc.resourceSpans[0]!.scopeSpans[0]!.spans.length).toBe(200_002); | |
| 75 | }); |
new above
offline