Public: anyone can read this; the crew can change it.

A Codex rollout file imports as a trace, beside Claude Code sessions #18360

opened this

Merged 1h 51m ago, live in production

mason/forge:mason/18358-a-codex-rollout-file-imports-as-a-trace → main 0 commits fork 1 thread · 1 unresolved

  • Merged. mason/18358-a-codex-rollout-file-imports-as-a-trace was merged into main as 8900ff3.

Review

Sign in to review this change.
7 files changed +74 −20
docs/features/traces.md +5 −3
@@ -40,7 +40,7 @@ The file is read whole, then parsed, so the 256 MB limit is memory-bound: a sess
4040
4141 `GET /api/v1/traces` lists the trace index newest first as `{items, next_cursor}`: filters `repository` (an id or `owner/name`), `kind` (run, talk), `model`, `outcome` (ok, failed, cancelled, stopped), `since` and `until` (a date or an ISO instant with a zone); `limit` 1 to 200 (default 50) and `cursor`. A run is listed only to someone who may read its log (the rule the run page uses), a Talk turn to its person alone; any other row is absent, never a hint. Only the index is read, never a log. A bad filter value is a 400 (`invalid_since`, …); a bad limit or cursor, or an unknown parameter, a 422. Code: `src/http/api/traces.ts` over `listTraceIndex`.
4242
43 ## Importing a Claude Code session (#18071)
43 ## Importing a Claude Code session or a Codex rollout (#18071, #18358)
4444
4545 From a Mac, send the newest session (a token with `rw` scope in `FORGE_TOKEN`, the forge's address in `FORGE_URL`):
4646
@@ -48,9 +48,11 @@ From a Mac, send the newest session (a token with `rw` scope in `FORGE_TOKEN`, t
4848 curl -sS -X POST -H "authorization: Bearer $FORGE_TOKEN" -H "content-type: application/x-ndjson" --data-binary @"$(ls -t ~/.claude/projects/*/*.jsonl | head -1)" "$FORGE_URL/api/v1/traces/import"
4949 ```
5050
51 `POST /api/v1/traces/import` takes the session JSONL as the raw body, at most 32 MiB (a plain 413 past it; `traceImport` in `src/kernel/body_caps.ts`). The file is read by the one Claude Code reader (`src/trace/claude_code.ts`), stored gzipped as `traces/imported/<id>.jsonl.gz` under the data directory, and indexed as a trace of kind `imported`, attributed to the caller and private to them: `GET /api/v1/traces?kind=imported` lists it for them and for no one else. The id comes from the caller and the session's own id, so sending the same session again answers 200 and replaces its trace; a first send answers 201. A file that is not UTF-8, is empty, holds no session records or carries no usable `sessionId` is a 422 (`invalid_session`) that says which. An account keeps at most 256 MiB of imported sessions (compressed, as stored; `IMPORT_QUOTA_BYTES` in `src/trace/import.ts`): an import that would pass it is a 413 (`quota_exceeded`), and re-sending a session replaces its own copy in the count. A person's imported files are deleted with their account. A session caller's cross-origin request is a 403.
51 For Codex, point the same command at a rollout: `--data-binary @"$(ls -t ~/.codex/sessions/*/*/*/rollout-*.jsonl | head -1)"`. The format is sniffed from the file; a rollout's id is the `id` of its `session_meta` record, and one without it is a 422, never given an invented id.
5252
53 A new source is one file implementing `ImportAdapter` (`src/trace/import_adapter.ts`, see `import_claude_code.ts`) and one line in `ADAPTERS`; Codex is next. Not yet: Codex files, a page for an imported trace, deleting one.
53 `POST /api/v1/traces/import` takes the session JSONL (Claude Code or Codex) as the raw body, at most 32 MiB (a plain 413 past it; `traceImport` in `src/kernel/body_caps.ts`). The file is read by the reader of its source (`src/trace/claude_code.ts`, `src/trace/codex.ts`), stored gzipped as `traces/imported/<id>.jsonl.gz` under the data directory, and indexed as a trace of kind `imported`, attributed to the caller and private to them: `GET /api/v1/traces?kind=imported` lists it for them and for no one else. The id comes from the caller and the session's own id, so sending the same session again answers 200 and replaces its trace; a first send answers 201. A file that is not UTF-8, is empty, holds no session records or carries no usable `sessionId` is a 422 (`invalid_session`) that says which. An account keeps at most 256 MiB of imported sessions (compressed, as stored; `IMPORT_QUOTA_BYTES` in `src/trace/import.ts`): an import that would pass it is a 413 (`quota_exceeded`), and re-sending a session replaces its own copy in the count. A person's imported files are deleted with their account. A session caller's cross-origin request is a 403.
54
55 A new source is one file implementing `ImportAdapter` (`src/trace/import_adapter.ts`, see `import_claude_code.ts`) and one line in `ADAPTERS`; Codex rollouts are taken the same way (`import_codex.ts`). Not yet: a page for an imported trace, deleting one.
5456 ## One trace as a tree (#18022)
5557
5658 `GET /api/v1/traces/:id` answers the thread, its turns and their steps as one tree, rebuilt from the raw log with `parseRunLog` (a Talk turn's log is a run log): the thread's figures are the list's row (model, account, tokens in, cached and out, cost, outcome, started, ended, steps, errors), each step has its start and end in ms, kind, name, line, model, tokens and outcome (a run log holds no tokens per step, so those are 0). `timed` is false where the log kept no times. `truncated` is true when the log's start was cut (it is read from its last 512 KB) or it holds more than `MAX_STEPS` (20,000) steps. A trace the caller may not see answers exactly as an unknown id: 404 `not_found`. The tree is answered whole (about 15 ms for 5,000 steps). Code: `readTraceTree` in `src/http/api/traces.ts`.
src/trace/codex.ts +14
@@ -42,6 +42,20 @@ export function isCodexRecord(rec: Json | undefined): boolean {
4242 return obj(rec?.payload) !== undefined && (type === "session_meta" || type === "response_item" || type === "event_msg" || type === "turn_context");
4343 }
4444
45 /** True when the first record of a file (within its first lines) is Codex's. */
46 export function isCodexFile(text: string): boolean {
47 for (const raw of text.split("\n", 20)) {
48 if (raw.trim() === "") continue;
49 try {
50 const rec: unknown = JSON.parse(raw);
51 return typeof rec === "object" && rec !== null && isCodexRecord(rec as Json);
52 } catch {
53 return false;
54 }
55 }
56 return false;
57 }
58
4559 export function parseCodexSession(text: string): Trace {
4660 const trace: Trace = { source: "codex", id: "", cwd: undefined, turns: [], skipped: 0 };
4761 const open = new Map<string, Step>();
src/trace/import.ts +1
@@ -72,6 +72,7 @@ export async function importSession(db: Database, dataDir: string, owner: string
7272 for (const adapter of ADAPTERS) {
7373 const read = adapter.read(text);
7474 if ("refused" in read) {
75 if (read.foreign === undefined) return { ok: false, reason: read.refused };
7576 refused = read.refused;
7677 continue;
7778 }
src/trace/import_adapter.ts +7 −5
@@ -1,17 +1,19 @@
11 /**
22 * What a source of session files must be to be imported (#18071): a name, a way to say whether a
3 * file is its own, and a way to read it into a `Trace`. One file per source
4 * (`import_claude_code.ts`); Codex is the next file and one line in `ADAPTERS`, never a rewrite
5 * of the route or the store. Plain data in, plain data out.
3 * file is its own, and a way to read it into a `Trace`. `foreign` marks a refusal that only says
4 * "not my format", so the next adapter is tried and a later, more specific refusal wins. One file
5 * per source (`import_claude_code.ts`); a new one is a file and one line in `ADAPTERS`, never a
6 * rewrite of the route or the store. Plain data in, plain data out.
67 */
78 import type { Trace } from "./model.ts";
89 import { claudeCode } from "./import_claude_code.ts";
10 import { codexRollout } from "./import_codex.ts";
911
1012 export interface ImportAdapter {
1113 readonly source: Trace["source"];
1214 /** The file read into a trace, or why it is refused: a sentence for the person who sent it. */
13 read(text: string): { readonly trace: Trace } | { readonly refused: string };
15 read(text: string): { readonly trace: Trace } | { readonly refused: string; readonly foreign?: true };
1416 }
1517
1618 /** Every source the import takes, in the order a file is tried. */
17 export const ADAPTERS: readonly ImportAdapter[] = [claudeCode];
19 export const ADAPTERS: readonly ImportAdapter[] = [codexRollout, claudeCode];
src/trace/import_codex.ts added +22
@@ -0,0 +1,22 @@
1 /**
2 * The Codex source of the import (#18358): `parseCodexSession` is the one reader, this only
3 * decides whether the file is a rollout and whether what it read is worth keeping. A rollout
4 * names its session in `session_meta`; one that does not is refused, never given a made-up id,
5 * because a resend must find the same row.
6 */
7 import { isCodexFile, parseCodexSession } from "./codex.ts";
8 import type { ImportAdapter } from "./import_adapter.ts";
9
10 /** A session id is the file's own name for it: letters, digits, `-`, `_`, `.`, at most 100. */
11 const SESSION_ID = /^[\w.-]{1,100}$/;
12
13 export const codexRollout: ImportAdapter = {
14 source: "codex",
15 read(text) {
16 if (!isCodexFile(text)) return { refused: "not a Codex rollout", foreign: true };
17 const trace = parseCodexSession(text);
18 if (trace.turns.length === 0) return { refused: "no Codex messages or calls: a rollout is one JSON record per line, with response_item records" };
19 if (!SESSION_ID.test(trace.id)) return { refused: "the rollout's session_meta carries no usable id (1 to 100 letters, digits, - _ .)" };
20 return { trace };
21 },
22 };
src/trace/session.ts +2 −12
@@ -3,19 +3,9 @@
33 * sniffed from the first record, Codex's rollout or else Claude Code's.
44 */
55 import { parseClaudeSession } from "./claude_code.ts";
6 import { isCodexRecord, parseCodexSession } from "./codex.ts";
6 import { isCodexFile, parseCodexSession } from "./codex.ts";
77 import type { Trace } from "./model.ts";
88
99 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);
10 return isCodexFile(text) ? parseCodexSession(text) : parseClaudeSession(text);
2111 }
test/traces-import.test.ts +23
@@ -152,3 +152,26 @@ test("no query through listTraceIndex shows an imported row without asking for i
152152 expect(listTraceIndex(app.db, { kind: "run", limit: 200 }).rows.filter((r) => importedOwned(r.id))).toEqual([]);
153153 });
154154 const importedOwned = (id: string): boolean => app.db.query<{ owner: string }, [string]>("SELECT owner FROM trace_index WHERE id = ?1").get(id)?.owner !== "";
155
156 const crec = (type: string, payload: object, t = "2026-12-02T10:00:00Z"): string => JSON.stringify({ timestamp: t, type, payload });
157 const codexFile = (id: string | undefined): string =>
158 [
159 crec("session_meta", id === undefined ? { cwd: "/w" } : { id, cwd: "/w" }),
160 crec("turn_context", { model: "gpt-x" }),
161 crec("response_item", { type: "message", role: "user", content: [{ type: "input_text", text: "add a test" }] }, "2026-12-02T10:00:01Z"),
162 crec("response_item", { type: "function_call", name: "shell", call_id: "c1", arguments: JSON.stringify({ command: ["ls"] }) }, "2026-12-02T10:00:02Z"),
163 crec("response_item", { type: "function_call_output", call_id: "c1", output: "ok" }, "2026-12-02T10:00:03Z"),
164 ].join("\n");
165
166 test("a Codex rollout is 201 first, 200 on resend with one row; no session id is a 422; Claude Code still works", async () => {
167 const before = (await list(alice)).length;
168 const first = await send(alice, codexFile("codex-sess-1"));
169 expect(first.status).toBe(201);
170 expect(((await first.json()) as any).source).toBe("codex");
171 expect((await send(alice, codexFile("codex-sess-1"))).status).toBe(200);
172 expect((await list(alice)).length).toBe(before + 1);
173 const bad = await send(alice, codexFile(undefined));
174 expect(bad.status).toBe(422);
175 expect(JSON.stringify(await bad.json())).toContain("session_meta");
176 expect((await send(alice, SESSION)).status).toBeLessThan(300);

Assert the exact status and the source here instead of < 300, so a Claude Code regression that returned 200 for a new file would show.

177 });

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

Keyboard shortcuts

Docs