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 #17968

opened this in answer to

Merged 16h 46m ago, live in production

scout/forge:scout/17929-traces-every-conversation-and-run-kept-a → main 0 commits fork

  • Merged. scout/17929-traces-every-conversation-and-run-kept-a was merged into main as 35a5490.

Review

Sign in to review this change.
8 files changed +203 −9
docs/CLI.md +1 −1
@@ -508,7 +508,7 @@ $ forge data notes "select name from users" --json
508508
509509 ## forge trace
510510
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.
511 Reads one session file, Claude Code's (the JSONL under `~/.claude/projects/`) or Codex's (a rollout under `~/.codex/sessions/`), the format sniffed from the first record, 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.
512512
513513 - `forge trace <session.jsonl>` prints the tree.
514514 - `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.
docs/features/traces.md +3 −2
@@ -4,7 +4,7 @@ row: Traces: read an outside agent session as turns and steps
44 ---
55 # Traces
66
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.
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 or a Codex rollout, sniffed from the first record.
88
99 - `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.
1010 - `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.
@@ -15,6 +15,7 @@ Every conversation and run is a record the forge keeps; a trace is the same reco
1515
1616 Each line a run appends is stamped in `<run id>.times` beside its log (`appendRunLog`), so a step shows what it took and when it ended (`2.3s, at 14s`, the last is the running total), and the strip puts each tick where and as wide as its time in the run: a slow tool or a long silence is a wide tick. A run from before the stamps shows order and says so. The log holds no tokens or cost, so a step carries neither; the run's cost is the only figure. Each run page lists a Trace fact (`runFacts`) and a Talk build card links its trace. Terminal door: `t` on a run's log opens `src/tui/screens/trace.ts` (the same rows, `traceRows`; `o` prints the web address). Reader: `src/trace/run_log.ts`, `src/trace/read.ts`.
1717
18 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, tokens and cost per step (the file holds none), compare, share.
18
19 Modules: `src/trace/model.ts` (the shape and totals), `src/trace/claude_code.ts` and `src/trace/codex.ts` (the readers), `src/trace/session.ts` (which one), `src/trace/otlp.ts` (the export). Not yet: storing an import, tokens and cost per step (the file holds none), compare, share.
1920
2021 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/trace.ts +4 −4
@@ -1,6 +1,6 @@
11 import { readFile, stat } from "node:fs/promises";
22 import { EXIT } from "../exit.ts";
3 import { parseClaudeSession } from "../../trace/claude_code.ts";
3 import { parseSession } from "../../trace/session.ts";
44 import { totalsOf, type Trace } from "../../trace/model.ts";
55 import { toOtlp } from "../../trace/otlp.ts";
66 import type { Command } from "./types.ts";
@@ -30,7 +30,7 @@ export function traceLines(trace: Trace): string[] {
3030
3131 export const command: Command = {
3232 name: "trace",
33 usage: { synopsis: "forge trace <session.jsonl>", flags: "[--otlp] read a Claude Code session as a trace" },
33 usage: { synopsis: "forge trace <session.jsonl>", flags: "[--otlp] read a Claude Code or Codex session as a trace" },
3434 async run(out, args) {
3535 const file = args.positional[0];
3636 if (file === undefined) {
@@ -48,9 +48,9 @@ export const command: Command = {
4848 out.err(`forge trace: cannot read ${file}`);
4949 return EXIT.failed;
5050 }
51 const trace = parseClaudeSession(text);
51 const trace = parseSession(text);
5252 if (trace.turns.length === 0) {
53 out.err(`forge trace: ${file} holds no Claude Code session records`);
53 out.err(`forge trace: ${file} holds no Claude Code or Codex session records`);
5454 return EXIT.failed;
5555 }
5656 if (args.flag("otlp")) out.line(JSON.stringify(toOtlp(trace)));
src/trace/codex.ts added +137
@@ -0,0 +1,137 @@
1 /**
2 * Codex's rollout JSONL, read into a `Trace` (#17929). One record per line,
3 * `{timestamp, type, payload}`: `session_meta` (id, cwd), `turn_context` (model),
4 * `response_item` (a `message`, a `function_call` and its `function_output`) and
5 * `event_msg` of `token_count`, whose `last_token_usage` belongs to the reply just
6 * made. A line that is not a record is counted in `skipped`.
7 */
8 import type { Step, Trace, Turn } from "./model.ts";
9 import { oneLine } from "./claude_code.ts";
10
11 const MAX_LINE = 4 * 1024 * 1024;
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 const textOf = (content: unknown): string =>
19 Array.isArray(content) ? content.map((b) => str(obj(b)?.text) ?? "").join("\n") : "";
20
21 /**
22 * What a function call was pointed at: its `command` (a string or an argv list), else its first
23 * string.
24 */
25 function callTarget(args: string | undefined): string {
26 let parsed: Json | undefined;
27 try {
28 parsed = obj(JSON.parse(args ?? ""));
29 } catch {
30 return "";
31 }
32 const cmd = parsed?.command ?? parsed?.cmd ?? parsed?.path;
33 if (Array.isArray(cmd)) return cmd.filter((x) => typeof x === "string").join(" ");
34 return str(cmd) ?? "";
35 }
36
37 /**
38 * True when the first record of a file looks like Codex's: the format sniffer in `session.ts` asks.
39 */
40 export function isCodexRecord(rec: Json | undefined): boolean {
41 const type = str(rec?.type);
42 return obj(rec?.payload) !== undefined && (type === "session_meta" || type === "response_item" || type === "event_msg" || type === "turn_context");
43 }
44
45 export function parseCodexSession(text: string): Trace {
46 const trace: Trace = { source: "codex", id: "", cwd: undefined, turns: [], skipped: 0 };
47 const open = new Map<string, Step>();
48 let turn: Turn | undefined;
49 let model: string | undefined;
50 let reply: Step | undefined;
51 let last = 0;
52
53 const turnAt = (ms: number): Turn => {
54 if (turn === undefined) {
55 turn = { index: 0, prompt: "", startMs: ms, steps: [] };
56 trace.turns.push(turn);
57 }
58 return turn;
59 };
60
61 for (const raw of text.split("\n")) {
62 if (raw.trim() === "") continue;
63 let rec: Json | undefined;
64 if (raw.length <= MAX_LINE) {
65 try {
66 rec = obj(JSON.parse(raw));
67 } catch {
68 rec = undefined;
69 }
70 }
71 const kind = str(rec?.type);
72 const p = obj(rec?.payload);
73 if (rec === undefined || p === undefined || !isCodexRecord(rec)) {
74 trace.skipped += 1;
75 continue;
76 }
77 const at = Date.parse(str(rec.timestamp) ?? "");
78 const ms = Number.isFinite(at) ? at : last;
79 last = ms;
80
81 if (kind === "session_meta") {
82 if (trace.id === "") trace.id = str(p.id) ?? "";
83 trace.cwd ??= str(p.cwd);
84 } else if (kind === "turn_context") {
85 model = str(p.model) ?? model;
86 } else if (kind === "event_msg") {
87 const usage = obj(obj(p.info)?.last_token_usage);
88 if (str(p.type) === "token_count" && usage !== undefined && reply !== undefined) {
89 const cached = num(usage.cached_input_tokens);
90 reply.tokensIn += Math.max(num(usage.input_tokens) - cached, 0);
91 reply.tokensCached += cached;
92 reply.tokensOut += num(usage.output_tokens);
93 reply.endMs = Math.max(reply.endMs, ms);
94 reply = undefined;
95 }
96 } else {
97 const type = str(p.type);
98 if (type === "message" && str(p.role) === "user") {
99 const prompt = textOf(p.content);
100 // Codex opens a session with its environment and instructions as user messages.
101 if (prompt.trim() !== "" && !prompt.trimStart().startsWith("<")) {
102 turn = { index: trace.turns.length, prompt: oneLine(prompt, 300), startMs: ms, steps: [] };
103 trace.turns.push(turn);
104 }
105 } else if (type === "message" || type === "reasoning") {
106 const into = turnAt(ms);
107 const said = type === "message" ? textOf(p.content) : "";
108 const name = model ?? "unknown";
109 reply = { id: `m${into.steps.length}:${ms}`, kind: "model", name, line: oneLine(`${name} ${said}`), startMs: ms, endMs: ms, model, tokensIn: 0, tokensCached: 0, tokensOut: 0, outcome: "ok" };
110 into.steps.push(reply);
111 } else if (type === "function_call" || type === "local_shell_call") {
112 const into = turnAt(ms);
113 const name = str(p.name) ?? "shell";
114 const id = str(p.call_id) ?? `c${into.steps.length}`;
115 const step: Step = { id, kind: "tool", name, line: oneLine(`${name} ${callTarget(str(p.arguments))}`), startMs: ms, endMs: ms, model: undefined, tokensIn: 0, tokensCached: 0, tokensOut: 0, outcome: "unknown" };
116 open.set(id, step);
117 into.steps.push(step);
118 } else if (type === "function_call_output") {
119 const id = str(p.call_id) ?? "";
120 const step = open.get(id);
121 if (step !== undefined) {
122 step.endMs = Math.max(ms, step.startMs);
123 // The output is a JSON string carrying `metadata.exit_code`, or plain text.
124 let code = 0;
125 try {
126 code = num(obj(obj(JSON.parse(str(p.output) ?? ""))?.metadata)?.exit_code);
127 } catch {
128 code = 0;
129 }
130 step.outcome = code === 0 ? "ok" : "error";
131 open.delete(id);
132 }
133 }
134 }
135 }
136 return trace;
137 }
src/trace/model.ts +1 −1
@@ -31,7 +31,7 @@ export interface Turn {
3131 }
3232
3333 export interface Trace {
34 source: "claude-code";
34 source: "claude-code" | "codex";
3535 id: string;
3636 cwd: string | undefined;
3737 turns: Turn[];
src/trace/otlp.ts +1 −1
@@ -50,7 +50,7 @@ export function toOtlp(trace: Trace): object {
5050 if (x.endMs > last) last = x.endMs;
5151 }
5252 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")])];
53 const spans = [span(rootId, undefined, `invoke_agent ${trace.source}`, 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", trace.source === "codex" ? "openai" : "anthropic")])];
5454 for (const turn of trace.turns) {
5555 const turnId = hex(`turn:${trace.id}:${turn.index}`, 16);
5656 let end = turn.startMs;
src/trace/session.ts added +21
@@ -0,0 +1,21 @@
1 /**
2 * Any outside agent's session file read into a `Trace` (#17929): the format is
3 * sniffed from the first record, Codex's rollout or else Claude Code's.
4 */
5 import { parseClaudeSession } from "./claude_code.ts";
6 import { isCodexRecord, parseCodexSession } from "./codex.ts";
7 import type { Trace } from "./model.ts";
8
9 export function parseSession(text: string): Trace {
10 for (const raw of text.split("\n", 20)) {
11 if (raw.trim() === "") continue;
12 try {
13 const rec: unknown = JSON.parse(raw);
14 if (typeof rec === "object" && rec !== null && isCodexRecord(rec as Record<string, unknown>)) return parseCodexSession(text);
15 } catch {
16 continue;
17 }
18 break;
19 }
20 return parseClaudeSession(text);
21 }
test/trace.test.ts +35
@@ -1,6 +1,7 @@
11 import { expect, test } from "bun:test";
22 import { parseClaudeSession } from "../src/trace/claude_code.ts";
33 import { totalsOf } from "../src/trace/model.ts";
4 import { parseSession } from "../src/trace/session.ts";
45 import { toOtlp } from "../src/trace/otlp.ts";
56 import { traceLines, command } from "../src/cli/commands/trace.ts";
67 import { createOut } from "../src/cli/out.ts";
@@ -73,3 +74,37 @@ test("a very long session totals and exports without a stack overflow", () => {
7374 const doc = toOtlp(trace) as { resourceSpans: { scopeSpans: { spans: unknown[] }[] }[] };
7475 expect(doc.resourceSpans[0]!.scopeSpans[0]!.spans.length).toBe(200_002);
7576 });
77
78 const crec = (ts: string, type: string, payload: object): string => JSON.stringify({ timestamp: ts, type, payload });
79 const CODEX = [
80 crec("2026-12-02T10:00:00Z", "session_meta", { id: "cx1", cwd: "/w" }),
81 crec("2026-12-02T10:00:00Z", "turn_context", { model: "gpt-x" }),
82 crec("2026-12-02T10:00:01Z", "response_item", { type: "message", role: "user", content: [{ type: "input_text", text: "<environment_context>x</environment_context>" }] }),
83 crec("2026-12-02T10:00:02Z", "response_item", { type: "message", role: "user", content: [{ type: "input_text", text: "add a health route" }] }),
84 crec("2026-12-02T10:00:03Z", "response_item", { type: "function_call", name: "shell", call_id: "c1", arguments: JSON.stringify({ command: ["bash", "-lc", "ls"] }) }),
85 crec("2026-12-02T10:00:03Z", "event_msg", { type: "token_count", info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 60, output_tokens: 7 } } }),
86 crec("2026-12-02T10:00:05Z", "response_item", { type: "function_call_output", call_id: "c1", output: JSON.stringify({ output: "x", metadata: { exit_code: 1 } }) }),
87 "garbage",
88 ].join("\n");
89
90 test("a Codex rollout is sniffed and read as turns and steps", () => {
91 const t = parseSession(CODEX);
92 expect(t).toMatchObject({ source: "codex", id: "cx1", cwd: "/w", skipped: 1 });
93 expect(t.turns.length).toBe(1);
94 expect(t.turns[0]!.prompt).toBe("add a health route");
95 const [call] = t.turns[0]!.steps;
96 expect(call).toMatchObject({ kind: "tool", line: "shell bash -lc ls", outcome: "error", endMs: Date.parse("2026-12-02T10:00:05Z") });
97 expect(parseSession(SESSION).source).toBe("claude-code");
98 expect(JSON.stringify(toOtlp(t))).toContain("openai");
99 });
100
101 test("a Codex model reply takes the token count that follows it", () => {
102 const t = parseSession([
103 crec("2026-12-02T10:00:00Z", "turn_context", { model: "gpt-x" }),
104 crec("2026-12-02T10:00:01Z", "response_item", { type: "message", role: "user", content: [{ text: "hi" }] }),
105 crec("2026-12-02T10:00:02Z", "response_item", { type: "message", role: "assistant", content: [{ text: "hello" }] }),
106 crec("2026-12-02T10:00:02Z", "event_msg", { type: "token_count", info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 60, output_tokens: 7 } } }),
107 ].join("\n"));
108 expect(t.turns[0]!.steps[0]).toMatchObject({ kind: "model", model: "gpt-x", tokensIn: 40, tokensCached: 60, tokensOut: 7 });
109 expect(totalsOf(t).tokensOut).toBe(7);
110 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs