From 0c5e1ce47493f867bb7d4a904ed627216f384f21 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 9 Oct 2026 00:40:59 +0000 Subject: [PATCH 1/2] Ingest Codex exec JSONL as the primary job trace --- docs/execution-trace-stream.md | 16 +++-- packages/app/src/agent-driver.ts | 14 +++- packages/app/src/codex-trace.ts | 66 ++++++++++++++++++ packages/app/src/exe-vm-backend.ts | 8 ++- packages/app/src/harness-diagnostics.ts | 9 ++- .../app/src/postgres/live-trace-repository.ts | 7 +- packages/app/src/postgres/run-scheduler.ts | 13 +++- packages/app/src/trace-source.ts | 4 +- packages/app/src/trace.ts | 30 +++++--- packages/app/test/codex-trace.test.ts | 68 +++++++++++++++++++ packages/app/test/execution-backend.test.ts | 16 +++++ packages/app/test/fixtures/codex/README.md | 7 ++ .../test/fixtures/codex/exec-0.161.0.jsonl | 7 ++ .../test/fixtures/codex/native-calls.jsonl | 4 ++ .../postgres-live-trace-repository.test.ts | 29 ++++++++ packages/app/test/trace-source.test.ts | 8 +-- 16 files changed, 276 insertions(+), 30 deletions(-) create mode 100644 packages/app/src/codex-trace.ts create mode 100644 packages/app/test/codex-trace.test.ts create mode 100644 packages/app/test/fixtures/codex/README.md create mode 100644 packages/app/test/fixtures/codex/exec-0.161.0.jsonl create mode 100644 packages/app/test/fixtures/codex/native-calls.jsonl diff --git a/docs/execution-trace-stream.md b/docs/execution-trace-stream.md index 0305dac9..0e0f77a6 100644 --- a/docs/execution-trace-stream.md +++ b/docs/execution-trace-stream.md @@ -4,10 +4,12 @@ An agent launch may declare `traceSources.primary` with `kind: execution_stream` an absolute guest `path`, `mediaType: application/x-ndjson`, and its `provider`. `formatVersion`, `cliVersion`, and `harnessVersion` identify the producing harness when known. Declare the native audit session separately as `nativeSession`; -native discovery commands remain supported. Existing drivers declare a native -primary until GEN-2137/2138/2139 implement their stream producers. +native discovery commands remain supported. Codex declares raw `codex exec --json` stdout as its primary stream with +`formatVersion: codex-exec-jsonl`; other existing drivers retain native primaries. +Codex CLI version is probed in the guest at launch and persisted with the source +for run diagnostics and artifact provenance. -Execution streams contain UTF-8, newline-terminated JSON objects in append order: +Normalized execution streams contain UTF-8, newline-terminated JSON objects in append order: ```json {"version":1,"id":"event-1","type":"assistant_message","title":"Assistant","preview":"Hello","display":{}} @@ -25,7 +27,13 @@ The backend tails the declared primary file in bounded byte chunks. PostgreSQL commits offset, pending bytes, events and hash-chain receipt atomically. An incomplete trailing line waits for a later chunk; terminal reconciliation ignores an unterminated trailing line, preserving it in the exact artifact. Invalid -complete execution records reject the chunk/projection rather than create events. +complete normalized execution records reject the chunk/projection. Codex raw +JSONL instead emits a bounded warning for malformed JSON and bounded metadata for +unknown future event/item types, then continues. Known Codex items project +reasoning, assistant text, command/MCP/web tool calls and results, file changes, +plans, lifecycle, errors and usage. Tool results reference the item call ID and +use the command or server/tool from the completion snapshot for their title. +Previews are redacted before truncation; unknown payloads are never echoed. Retries use the same generation, offset and hash. Rename rotation starts a new projection generation; observable same-inode truncation does likewise. Producers must use rename rotation, never truncate and regrow between polls: an unobserved diff --git a/packages/app/src/agent-driver.ts b/packages/app/src/agent-driver.ts index 5f25ccb2..9bb8f4bc 100644 --- a/packages/app/src/agent-driver.ts +++ b/packages/app/src/agent-driver.ts @@ -25,11 +25,19 @@ export interface AgentDriver { class CodexDriver implements AgentDriver { readonly kind = "codex" as const; - launch(_runId: string, config: AgentConfiguration): AgentLaunchSpec { - const args = ["exec", "--dangerously-bypass-approvals-and-sandbox", "--color", "never", "-c", "model_provider=exe-llm", "-c", 'model_providers.exe-llm.name="exe-llm"', "-c", 'model_providers.exe-llm.base_url="https://llm.int.exe.xyz/v1"']; + launch(runId: string, config: AgentConfiguration): AgentLaunchSpec { + const args = ["exec", "--json", "--dangerously-bypass-approvals-and-sandbox", "--color", "never", "-c", "model_provider=exe-llm", "-c", 'model_providers.exe-llm.name="exe-llm"', "-c", 'model_providers.exe-llm.base_url="https://llm.int.exe.xyz/v1"']; if (config.model?.trim()) args.push("--model", config.model.trim()); if (config.effort?.trim()) args.push("-c", `model_reasoning_effort=${config.effort.trim()}`); - return { executable: "codex", args, env: {}, stdin: "prompt", artifacts: { roots: ["${CODEX_HOME:-$HOME/.codex}/sessions"], fileNameIncludes: "rollout-", discoverCommand: `find "\${CODEX_HOME:-$HOME/.codex}/sessions" -type f -name 'rollout-*.jsonl' -printf '%T@ %p\\n' | sort -nr | head -1 | cut -d' ' -f2-` } }; + const nativeSession = { kind: "native_session" as const, path: "${CODEX_HOME:-$HOME/.codex}/sessions", mediaType: "application/x-ndjson" as const, provider: this.kind, discoverCommand: `find "\${CODEX_HOME:-$HOME/.codex}/sessions" -type f -name 'rollout-*.jsonl' -printf '%T@ %p\\n' | sort -nr | head -1 | cut -d' ' -f2-` }; + return { + executable: "codex", args, env: {}, stdin: "prompt", + artifacts: { roots: [nativeSession.path], fileNameIncludes: "rollout-", discoverCommand: nativeSession.discoverCommand }, + traceSources: { + primary: { kind: "execution_stream", path: `/tmp/factorize-artifacts/${runId}/codex-exec.jsonl`, mediaType: "application/x-ndjson", provider: this.kind, formatVersion: "codex-exec-jsonl" }, + nativeSession, + }, + }; } } diff --git a/packages/app/src/codex-trace.ts b/packages/app/src/codex-trace.ts new file mode 100644 index 00000000..a91e97b2 --- /dev/null +++ b/packages/app/src/codex-trace.ts @@ -0,0 +1,66 @@ +import type { TraceEvent, TraceEventType } from "./trace"; +import { safeDiagnosticText } from "./harness-diagnostics"; + +export type CodexCalls = Map; +const safe = (value: unknown, limit = 32768) => safeDiagnosticText(typeof value === "string" ? value : JSON.stringify(value ?? ""), limit); +const argumentsValue = (value: unknown): unknown => { + if (typeof value !== "string") return value ?? {}; + try { return JSON.parse(value); } catch { return value; } +}; + +/** Raw exec events are self-contained snapshots; no tool state is needed across byte chunks. */ +export function parseCodexExec(value: any, sequence: number): TraceEvent[] { + const make = (type: TraceEventType, title: unknown, preview: unknown, id?: string, parentId?: string): TraceEvent => ({ + sequence, id: id ?? String(sequence), type, title: safe(title, 512), preview: safe(preview), + ...(parentId ? { parentId } : {}), display: { source: "codex exec --json", eventType: safe(value?.type, 128) }, + }); + if (!value || typeof value !== "object") return [make("warning", "Invalid Codex event", "Expected a JSON object")]; + if (value.type === "turn.completed") return [make("usage", "Token usage", value.usage)]; + if (value.type === "error" || value.type === "turn.failed") return [make("error", "Codex error", value.message ?? value.error?.message ?? value.error)]; + if (value.type === "thread.started" || value.type === "turn.started") return [make("metadata", value.type, value.thread_id ?? "")]; + if (!["item.started", "item.updated", "item.completed"].includes(value.type)) return [make("metadata", "Unknown Codex event", { type: safe(value.type, 128) })]; + const item = value.item; + if (!item || typeof item !== "object" || typeof item.id !== "string") return [make("warning", "Invalid Codex item", "Missing item identity")]; + const id = safe(item.id, 512), parent = typeof item.parent_id === "string" ? safe(item.parent_id, 512) : undefined; + const completed = value.type === "item.completed"; + const recordId = `${id}:${value.type}`; + const call = (title: unknown, args: unknown) => make("tool_call", title, argumentsValue(args), id, parent); + const result = (title: unknown, output: unknown) => make("tool_result", title, output, recordId, id); + switch (item.type) { + case "reasoning": return [make("reasoning", "Reasoning", item.text, recordId, parent)]; + case "agent_message": return [make("assistant_message", "Assistant", item.text, recordId, parent)]; + case "command_execution": + return completed ? [result(item.command ?? "Command result", { output: item.aggregated_output ?? "", exitCode: item.exit_code, status: item.status })] + : [call(item.command ?? "Command", { command: item.command })]; + case "mcp_tool_call": { + const title = `${item.server ?? "MCP"}: ${item.tool ?? "Tool"}`; + return completed ? [result(title, item.error ?? item.result)] : [call(title, item.arguments)]; + } + case "file_change": + return [make("file_change", "File changes", { changes: item.changes, status: item.status }, recordId, parent)]; + case "web_search": + return completed ? [result("Web search", item.action ?? item.query)] : [call("Web search", item.action ?? { query: item.query })]; + case "todo_list": return [make("metadata", "Plan", item.items, recordId, parent)]; + case "error": return [make("error", "Codex error", item.message, recordId, parent)]; + default: return [make("metadata", "Unknown Codex item", { type: safe(item.type, 128), status: safe(item.status, 128) }, recordId, parent)]; + } +} + +export function parseCodexNativeCall(value: any, sequence: number, calls: CodexCalls): TraceEvent[] | null { + const payload = value?.payload; + if (value?.type !== "response_item" || !payload) return null; + const kind = payload.type; + if (!["function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output"].includes(kind)) return null; + const callId = safe(payload.call_id ?? payload.id ?? String(sequence), 512); + const output = kind.endsWith("_output"); + const title = output ? calls.get(callId) ?? "Tool result" : safe(payload.name ?? "Tool call", 512); + if (!output) { + if (calls.size >= 4096) calls.delete(calls.keys().next().value!); + calls.set(callId, title); + } + const preview = safe(output ? payload.output : argumentsValue(payload.arguments ?? payload.input)); + return [{ sequence, id: output ? `${callId}:result` : callId, ...(output ? { parentId: callId } : payload.parent_id ? { parentId: safe(payload.parent_id, 512) } : {}), + type: output ? "tool_result" : "tool_call", title, preview, + ...(typeof value.timestamp === "string" && Number.isFinite(Date.parse(value.timestamp)) ? { occurredAt: value.timestamp } : {}), + display: { source: "codex native session", ...(!output ? { arguments: argumentsValue(preview) } : {}) } }]; +} diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index ac52d3a7..4241335e 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -100,16 +100,20 @@ export class ExeVmBackend implements ExecutionBackend { throw new Error(`exe.dev VM creation failed (${created.status}): ${created.body.slice(0, 500)}`); } - const prompt = base64(request.prompt), output = "/tmp/factorize.log", unit = vm; + const prompt = base64(request.prompt), output = request.traceSources?.primary.formatVersion === "codex-exec-jsonl" ? request.traceSources.primary.path : "/tmp/factorize.log", unit = vm; const work = [ "set -eu", "mkdir -p /home/exedev/workspace", "cd /home/exedev/workspace", ...(request.traceSources?.primary.kind === "execution_stream" ? [`mkdir -p -- ${shellAtom(request.traceSources.primary.path.slice(0, request.traceSources.primary.path.lastIndexOf("/")) || "/")}`, `touch -- ${shellAtom(request.traceSources.primary.path)}`] : []), `printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`, - `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`, + `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`, "echo started", ].join("; "); + if (request.traceSources?.primary.formatVersion === "codex-exec-jsonl") { + const version = await this.api(`ssh ${shellAtom(vm)} ${shellAtom("codex --version")}`).catch(() => null); + if (version?.ok && /^codex-cli [0-9][0-9A-Za-z.+-]*$/.test(version.body.trim())) request.traceSources.primary.cliVersion = version.body.trim(); + } let started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); const accepted = (result: BackendCommandResult) => result.ok && result.body.trim() === "started"; for (let attempt = 1; !accepted(started) && attempt < 5; attempt++) started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); diff --git a/packages/app/src/harness-diagnostics.ts b/packages/app/src/harness-diagnostics.ts index 7a09edad..c5b52ecf 100644 --- a/packages/app/src/harness-diagnostics.ts +++ b/packages/app/src/harness-diagnostics.ts @@ -10,7 +10,14 @@ export interface ExecutionDiagnostics { /** Redact before truncation so a cut cannot expose part of a recognized credential. */ export function safeDiagnosticText(value: string, limit = 2048): string { - const withoutAssignments = value.replace(/^.*["']?(?:[\w-]*(?:token|secret|password|passwd|api[_-]?key|authorization|cookie))["']?\s*[:=].*$/gim, "[REDACTED]"); + // Scan assignment keys once per line; a greedy prefix plus nested key + // quantifiers made long, ordinary tool output quadratic to redact. + const withoutAssignments = value.split("\n").map(line => { + for (const match of line.matchAll(/\b([\w-]+)["']?\s*[:=]/g)) { + if (/(?:token|secret|password|passwd|api[_-]?key|authorization|cookie)/i.test(match[1])) return "[REDACTED]"; + } + return line; + }).join("\n"); const safe = scrubSession(withoutAssignments) .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*/gi, "[REDACTED]") .replace(/\b[A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD)\s*=\s*[^\r\n]+/g, "[REDACTED]") diff --git a/packages/app/src/postgres/live-trace-repository.ts b/packages/app/src/postgres/live-trace-repository.ts index d8bfd304..e0099aad 100644 --- a/packages/app/src/postgres/live-trace-repository.ts +++ b/packages/app/src/postgres/live-trace-repository.ts @@ -60,7 +60,12 @@ export class LiveTraceRepository { start = index + 1; } } - const parsed = parseTrace(provider, new TextDecoder("utf-8", { fatal: true }).decode(complete), sourceKind); + const calls = new Map(); + if (provider === "codex" && sourceKind === "native_session") { + const previous = await client.query<{ id: string; title: string }>("SELECT id,title FROM app.run_trace_events WHERE tenant_id=$1 AND run_id=$2 AND event_type='tool_call' ORDER BY sequence DESC LIMIT 4096", [this.tenantId, runId]); + for (const item of [...previous.rows].reverse()) calls.set(item.id, item.title); + } + const parsed = parseTrace(provider, new TextDecoder("utf-8", { fatal: true }).decode(complete), sourceKind, Number(cursor.next_sequence), calls); const nextSequence = Number(cursor.next_sequence), events = parsed.map((item, index) => ({ ...item, sequence: nextSequence + index })); for (let offset = 0; offset < events.length; offset += 250) await this.insertBatch(client, runId, events.slice(offset, offset + 250)); const rollingHash = await sha256(`${cursor.rolling_hash}:${chunk.startOffset}:${endOffset}:${chunk.chunkSha256}`); diff --git a/packages/app/src/postgres/run-scheduler.ts b/packages/app/src/postgres/run-scheduler.ts index 62071f22..fb1b6e2e 100644 --- a/packages/app/src/postgres/run-scheduler.ts +++ b/packages/app/src/postgres/run-scheduler.ts @@ -104,13 +104,22 @@ export class RunScheduler { } private sources(run: PersistedRun): TraceSources { - return run.executionTarget.traceSources ?? driverTraceSources(run.executionTarget.agentKind as AgentKind, agentDriver(run.executionTarget.agentKind as AgentKind).launch(run.id, {})); + if (run.executionTarget.traceSources) return run.executionTarget.traceSources; + // Runs launched before a source declaration existed must keep their native + // trace even when the current driver now produces an execution stream. + return { primary: this.nativeSource(run) }; + } + + private nativeSource(run: PersistedRun): TraceSource { + const kind = run.executionTarget.agentKind as AgentKind; + const { traceSources: _sources, ...legacy } = agentDriver(kind).launch(run.id, {}); + return driverTraceSources(kind, legacy).primary; } private async collectArtifact(run: PersistedRun, backend: ExeVmBackend, source?: TraceSource, primary?: boolean) { if (!run.executionHandle) throw new Error("Execution handle is missing"); const sources = this.sources(run); - source ??= sources.nativeSession ?? (sources.primary.kind === "native_session" ? sources.primary : driverTraceSources(run.executionTarget.agentKind as AgentKind, agentDriver(run.executionTarget.agentKind as AgentKind).launch(run.id, {})).primary); + source ??= sources.nativeSession ?? (sources.primary.kind === "native_session" ? sources.primary : this.nativeSource(run)); primary ??= sources.primary.kind === "native_session"; const token = await issueArtifactUploadGrant({ tenantId: run.tenantId, runId: run.id, path: source.kind === "execution_stream" ? "trace/stream.jsonl" : "native/session.jsonl", contentType: source.mediaType, provider: source.provider, format: "jsonl", sourceKind: source.kind, sourcePath: source.path, formatVersion: source.formatVersion, cliVersion: source.cliVersion, harnessVersion: source.harnessVersion, primary, expiresAt: Date.now() + 10 * 60_000 }, this.env.SESSION_SIGNING_SECRET); return backend.collectArtifact(run.executionHandle, { source, contentType: source.mediaType, uploadUrl: `${this.env.APP_ORIGIN}/internal/run-artifacts/${encodeURIComponent(token)}` }); diff --git a/packages/app/src/trace-source.ts b/packages/app/src/trace-source.ts index 9be2f4d9..f17a07c5 100644 --- a/packages/app/src/trace-source.ts +++ b/packages/app/src/trace-source.ts @@ -1,6 +1,6 @@ import { shellAtom } from "./exe"; -/** A guest file, never a terminal log. Execution streams use Factorize JSONL v1. */ +/** A guest file, never a terminal log. Execution streams use Factorize JSONL v1 or declared provider stdout JSONL. */ export interface TraceSource { kind: "execution_stream" | "native_session"; path: string; @@ -23,7 +23,7 @@ export function validateTraceSources(sources: TraceSources): void { sourceCommand(source); if (source.mediaType !== "application/x-ndjson") throw new Error("Trace sources must be JSONL"); if (!["execution_stream", "native_session"].includes(source.kind) || !["codex", "claude", "pi"].includes(source.provider)) throw new Error("Invalid trace source"); - if (source.kind === "execution_stream" && source.formatVersion && source.formatVersion !== "1") throw new Error("Unsupported execution stream version"); + if (source.kind === "execution_stream" && source.formatVersion && source.formatVersion !== "1" && !(source.provider === "codex" && source.formatVersion === "codex-exec-jsonl")) throw new Error("Unsupported execution stream version"); } if (sources.primary.kind === "execution_stream" && ["/tmp/factorize.log", "/tmp/factorize.stderr", "/tmp/factorize-prompt.md"].includes(sources.primary.path)) throw new Error("Trace stream path is reserved for JSONL only"); if (sources.nativeSession) { diff --git a/packages/app/src/trace.ts b/packages/app/src/trace.ts index a9b4977d..9341c210 100644 --- a/packages/app/src/trace.ts +++ b/packages/app/src/trace.ts @@ -1,3 +1,5 @@ +import { safeDiagnosticText } from "./harness-diagnostics"; +import { parseCodexExec, parseCodexNativeCall, type CodexCalls } from "./codex-trace"; import type { TraceSource } from "./trace-source"; export type TraceEventType = "user_message" | "assistant_message" | "reasoning" | "tool_call" | "tool_result" | "command" | "file_change" | "compaction" | "branch" | "usage" | "warning" | "error" | "metadata"; @@ -48,16 +50,17 @@ function parsePi(value: any, sequence: number): TraceEvent[] { } function parseCodex(value: any, sequence: number): TraceEvent[] { + if (!value || typeof value !== "object") return [event(sequence, "warning", "Invalid Codex record", "Expected an object", {})]; const payload = value.payload ?? {}; - if (value.type === "session_meta") return [event(sequence, "metadata", "Session started", payload.cwd ?? "", { ...value, id: payload.id ?? payload.session_id })]; + if (value.type === "session_meta") return [event(sequence, "metadata", "Session started", safeDiagnosticText(String(payload.cwd ?? ""), MAX_PREVIEW), { ...value, id: payload.id ?? payload.session_id })]; if (value.type === "response_item") { const kind = payload.type; - if (kind === "message") return [event(sequence, payload.role === "user" ? "user_message" : "assistant_message", payload.role === "user" ? "User" : "Assistant", contentText(payload.content), { ...value, ...payload })]; + if (kind === "message") return [event(sequence, payload.role === "user" ? "user_message" : "assistant_message", payload.role === "user" ? "User" : "Assistant", safeDiagnosticText(contentText(payload.content), MAX_PREVIEW), { ...value, ...payload })]; if (kind === "function_call") return [{ ...event(sequence, "tool_call", String(payload.name ?? "Tool call"), payload.arguments, { ...value, ...payload }), display: { arguments: payload.arguments ?? {} } }]; if (kind === "function_call_output") return [event(sequence, "tool_result", "Tool result", payload.output, { ...value, ...payload })]; - if (kind === "reasoning") return [event(sequence, "reasoning", "Reasoning", contentText(payload.summary ?? payload.content), { ...value, ...payload })]; + if (kind === "reasoning") return [event(sequence, "reasoning", "Reasoning", safeDiagnosticText(contentText(payload.summary ?? payload.content), MAX_PREVIEW), { ...value, ...payload })]; } - if (value.type === "event_msg" && payload.type === "agent_reasoning") return [event(sequence, "reasoning", "Reasoning", payload.text, { ...value, ...payload })]; + if (value.type === "event_msg" && payload.type === "agent_reasoning") return [event(sequence, "reasoning", "Reasoning", safeDiagnosticText(String(payload.text ?? ""), MAX_PREVIEW), { ...value, ...payload })]; return []; } @@ -80,12 +83,16 @@ function parseClaude(value: any, sequence: number): TraceEvent[] { } /** Parses source JSONL into bounded, provider-neutral display events. */ -export function parseTrace(provider: "codex" | "claude" | "pi", jsonl: string, sourceKind: TraceSource["kind"] = "native_session"): TraceEvent[] { +export function parseTrace(provider: "codex" | "claude" | "pi", jsonl: string, sourceKind: TraceSource["kind"] = "native_session", startSequence = 1, calls: CodexCalls = new Map()): TraceEvent[] { const events: TraceEvent[] = []; for (const line of jsonl.split(/\r?\n/)) { if (!line.trim()) continue; let value: unknown; - try { value = JSON.parse(line); } catch { if (sourceKind === "execution_stream") throw new Error("Invalid execution stream JSON"); events.push(event(events.length + 1, "warning", "Unparseable session record", line, {})); continue; } + try { value = JSON.parse(line); } catch { if (sourceKind === "execution_stream" && provider !== "codex") throw new Error("Invalid execution stream JSON"); events.push(event(startSequence + events.length, "warning", "Unparseable session record", provider === "codex" ? "Invalid JSON record skipped" : line, {})); continue; } + if (sourceKind === "execution_stream" && provider === "codex" && (value as any)?.version !== 1) { + events.push(...parseCodexExec(value, startSequence + events.length)); + continue; + } if (sourceKind === "execution_stream") { const record = value as any; if (!record || record.version !== 1 || typeof record.id !== "string" || typeof record.title !== "string" || typeof record.preview !== "string" || !["user_message", "assistant_message", "reasoning", "tool_call", "tool_result", "command", "file_change", "compaction", "branch", "usage", "warning", "error", "metadata"].includes(record.type)) throw new Error("Invalid execution stream record"); @@ -93,10 +100,10 @@ export function parseTrace(provider: "codex" | "claude" | "pi", jsonl: string, s events.push({ sequence: events.length + 1, id: record.id, type: record.type, title: clipped(record.title), preview: clipped(record.preview), ...(typeof record.parentId === "string" ? { parentId: record.parentId } : {}), ...(typeof record.role === "string" ? { role: record.role } : {}), ...(typeof record.occurredAt === "string" ? { occurredAt: record.occurredAt } : {}), display: record.display && typeof record.display === "object" && !Array.isArray(record.display) ? record.display : {} }); continue; } - const parsed = provider === "codex" ? parseCodex(value, events.length + 1) : provider === "claude" ? parseClaude(value, events.length + 1) : parsePi(value, events.length + 1); - events.push(...parsed); + const parsed = provider === "codex" ? parseCodexNativeCall(value, startSequence + events.length, calls) ?? parseCodex(value, startSequence + events.length) : provider === "claude" ? parseClaude(value, events.length + 1) : parsePi(value, events.length + 1); + events.push(...(provider === "codex" ? parsed.map(item => ({ ...item, title: safeDiagnosticText(item.title, 512), preview: safeDiagnosticText(item.preview, MAX_PREVIEW) })) : parsed)); } - return events.map((item, index) => ({ ...item, sequence: index + 1 })); + return events.map((item, index) => ({ ...item, sequence: startSequence + index })); } /** Byte framing matches live ingestion, including an incomplete UTF-8 tail at exit. */ @@ -114,7 +121,7 @@ async function consumeExecutionStream(provider: "codex" | "claude" | "pi", strea for (let index = 0; index < combined.length; index++) { if (combined[index] !== 10) continue; if (index - start > 16 * 1024 * 1024) throw new Error("Execution stream record exceeds 16 MiB"); - const events = parseTrace(provider, decoder.decode(combined.subarray(start, index)), "execution_stream"); + const events = parseTrace(provider, decoder.decode(combined.subarray(start, index)), "execution_stream", sequence + 1); for (const item of events) { batch.push({ ...item, sequence: ++sequence }); if (batch.length >= batchSize) await flush(); } start = index + 1; } @@ -132,10 +139,11 @@ export async function consumeTraceStream(provider: "codex" | "claude" | "pi", st const reader = stream.getReader(), decoder = new TextDecoder(); let batch: TraceEvent[] = [], sequence = 0; let pending = ""; + const calls: CodexCalls = new Map(); const flush = async () => { if (!batch.length) return; const ready = batch; batch = []; await consumeBatch(ready); }; const consume = async (line: string) => { if (!line.trim()) return; - const parsed = parseTrace(provider, line, sourceKind); + const parsed = parseTrace(provider, line, sourceKind, sequence + 1, calls); for (const item of parsed) { batch.push({ ...item, sequence: ++sequence }); if (batch.length >= batchSize) await flush(); } }; for (;;) { diff --git a/packages/app/test/codex-trace.test.ts b/packages/app/test/codex-trace.test.ts new file mode 100644 index 00000000..c32c02c5 --- /dev/null +++ b/packages/app/test/codex-trace.test.ts @@ -0,0 +1,68 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { consumeTraceStream, parseTrace, type TraceEvent } from "../src/trace"; +import { agentDriver } from "../src/agent-driver"; + +const fixture = (name: string) => readFileSync(new URL(`./fixtures/codex/${name}`, import.meta.url), "utf8"); +describe("Codex traces", () => { + it("launches raw stdout as the primary source with a separate native audit", () => { + const launch = agentDriver("codex").launch("run-1", {}); + expect(launch.args).toContain("--json"); + expect(launch.traceSources?.primary).toMatchObject({ kind: "execution_stream", formatVersion: "codex-exec-jsonl" }); + expect(launch.traceSources?.nativeSession?.kind).toBe("native_session"); + }); + it("projects the captured CLI command immediately and correlates its completion", async () => { + const transcript = fixture("exec-0.161.0.jsonl"); + const expected = parseTrace("codex", transcript, "execution_stream"); + const call = expected.find(item => item.type === "tool_call")!; + const result = expected.find(item => item.type === "tool_result")!; + expect(call.preview).toContain("printf trace-fixture"); + expect(result.parentId).toBe(call.id); + expect(result.title).toBe(call.title); + const bytes = new TextEncoder().encode(transcript); + const actual: TraceEvent[] = []; + await consumeTraceStream("codex", new ReadableStream({ start(controller) { + for (const byte of bytes) controller.enqueue(new Uint8Array([byte])); + controller.close(); + } }), async batch => { actual.push(...batch); }, 1, "execution_stream"); + expect(actual).toEqual(expected); + // Live chunks use the persisted sequence and need no process-local state. + const live: TraceEvent[] = []; + for (const line of transcript.trim().split("\n")) live.push(...parseTrace("codex", line, "execution_stream", live.length + 1)); + expect(live).toEqual(expected); + }); + it("correlates current custom and legacy native calls across streamed records", async () => { + const text = fixture("native-calls.jsonl"); + const expected = parseTrace("codex", text); + expect(expected.map(item => item.type)).toEqual(["tool_call", "tool_result", "tool_call", "tool_result"]); + expect(expected[1]).toMatchObject({ parentId: "custom-1", title: "exec_command" }); + expect(expected[3]).toMatchObject({ parentId: "legacy-1", title: "shell" }); + expect(expected[0].display.arguments).toEqual({ cmd: "printf test" }); + const actual: TraceEvent[] = []; + await consumeTraceStream("codex", new Response(text).body!, async batch => { actual.push(...batch); }, 1); + expect(actual).toEqual(expected); + }); + it("handles every documented item, errors and future records without leaking secrets", () => { + const records = [ + { type: "item.completed", item: { id: "r", type: "reasoning", text: "Thinking 😀" } }, + { type: "item.started", item: { id: "m", parent_id: "r", type: "mcp_tool_call", server: "test", tool: "read", arguments: { password: "sensitive-value" } } }, + { type: "item.completed", item: { id: "m", type: "mcp_tool_call", server: "test", tool: "read", result: { content: "ok" } } }, + { type: "item.completed", item: { id: "f", type: "file_change", changes: [{ path: "a", kind: "update" }] } }, + { type: "item.started", item: { id: "w", type: "web_search", query: "test" } }, + { type: "item.completed", item: { id: "p", type: "todo_list", items: [] } }, + { type: "turn.failed", error: { message: "failed" } }, + { type: "error", message: "Bearer abcdefghijklmnop" }, + { type: "future.event", secret: "sensitive-value" }, + { type: "item.completed", item: { id: "u", type: "future.item", secret: "sensitive-value" } }, + { type: "item.completed", item: { id: "a", type: "agent_message", text: "x".repeat(100000) } }, + ]; + const events = parseTrace("codex", records.map(record => JSON.stringify(record)).join("\n") + "\ninvalid\n" + JSON.stringify({ type: "turn.completed", usage: { input_tokens: 1 } }), "execution_stream"); + expect(events.at(-1)?.type).toBe("usage"); + expect(events.filter(item => item.type === "error")).toHaveLength(2); + expect(events.find(item => item.type === "warning")).toBeDefined(); + expect(events[1].parentId).toBe("r"); + expect(JSON.stringify(events)).not.toContain("sensitive-value"); + expect(JSON.stringify(events)).not.toContain("abcdefghijklmnop"); + expect(events.every(item => item.preview.length <= 32768)).toBe(true); + }); +}); diff --git a/packages/app/test/execution-backend.test.ts b/packages/app/test/execution-backend.test.ts index 8912a262..dd221717 100644 --- a/packages/app/test/execution-backend.test.ts +++ b/packages/app/test/execution-backend.test.ts @@ -69,6 +69,22 @@ describe("ExeVmBackend", () => { expect(requests[1]).toContain("systemctl show"); }); + it("routes Codex JSON stdout exclusively to its stream and records the guest CLI version", async () => { + const requests: string[] = []; + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { + const body = String(init.body); requests.push(body); + return new Response(body.includes("codex --version") ? "codex-cli 0.161.0" : requests.length === 1 ? "{}" : "started", { headers: { "X-Exe-Exit": "0" } }); + })); + const launch = agentDriver("codex").launch("run-1", {}); + await new ExeVmBackend(connection).launch({ runId: "run-1", prompt: "test", harness: launch, traceSources: launch.traceSources }); + expect(launch.traceSources?.primary.cliVersion).toBe("codex-cli 0.161.0"); + const supervisor = requests.find(body => body.includes("systemd-run"))!; + expect(supervisor).toContain("append:/tmp/factorize-artifacts/run-1/codex-exec.jsonl"); + expect(supervisor).not.toContain("append:/tmp/factorize.log"); + expect(supervisor).toContain("StandardError=append:/tmp/factorize.stderr"); + expect(supervisor).toContain("--json"); + }); + it("uses the systemd unit as the authoritative run state", async () => { const states = [ "LoadState=loaded\nActiveState=active\nSubState=running\nResult=success\nExecMainCode=0\nExecMainStatus=0", diff --git a/packages/app/test/fixtures/codex/README.md b/packages/app/test/fixtures/codex/README.md new file mode 100644 index 00000000..1a2c17ee --- /dev/null +++ b/packages/app/test/fixtures/codex/README.md @@ -0,0 +1,7 @@ +exec-0.161.0.jsonl was captured from codex-cli 0.161.0 using codex exec --json +against the attached exe-llm provider, with a prompt to run printf trace-fixture +once and reply Done. It contains no credentials. native-calls.jsonl is a minimized +schema fixture for current custom_tool_call/custom_tool_call_output and historical +function_call/function_call_output session records. Additional documented item +shapes and error/future-event cases are exercised in codex-trace.test.ts. +Official stdout contract: https://developers.openai.com/codex/noninteractive/ diff --git a/packages/app/test/fixtures/codex/exec-0.161.0.jsonl b/packages/app/test/fixtures/codex/exec-0.161.0.jsonl new file mode 100644 index 00000000..fb31c71b --- /dev/null +++ b/packages/app/test/fixtures/codex/exec-0.161.0.jsonl @@ -0,0 +1,7 @@ +{"type":"thread.started","thread_id":"01a11e16-6004-7c63-9e3d-1c52f23cb96f"} +{"type":"turn.started"} +{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"I’ll run the shell command once."}} +{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"/bin/bash -lc 'printf trace-fixture'","aggregated_output":"","exit_code":null,"status":"in_progress"}} +{"type":"item.completed","item":{"id":"item_1","type":"command_execution","command":"/bin/bash -lc 'printf trace-fixture'","aggregated_output":"trace-fixture","exit_code":0,"status":"completed"}} +{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"Done."}} +{"type":"turn.completed","usage":{"input_tokens":20140,"cached_input_tokens":18176,"cache_write_input_tokens":0,"output_tokens":50,"reasoning_output_tokens":0}} diff --git a/packages/app/test/fixtures/codex/native-calls.jsonl b/packages/app/test/fixtures/codex/native-calls.jsonl new file mode 100644 index 00000000..2336ba2e --- /dev/null +++ b/packages/app/test/fixtures/codex/native-calls.jsonl @@ -0,0 +1,4 @@ +{"type":"response_item","payload":{"type":"custom_tool_call","call_id":"custom-1","name":"exec_command","input":"{\"cmd\":\"printf test\"}"}} +{"type":"response_item","payload":{"type":"custom_tool_call_output","call_id":"custom-1","output":"test"}} +{"type":"response_item","payload":{"type":"function_call","call_id":"legacy-1","name":"shell","arguments":"{\"command\":\"pwd\"}"}} +{"type":"response_item","payload":{"type":"function_call_output","call_id":"legacy-1","output":"/workspace"}} diff --git a/packages/app/test/postgres-live-trace-repository.test.ts b/packages/app/test/postgres-live-trace-repository.test.ts index 66c4327d..97f845b3 100644 --- a/packages/app/test/postgres-live-trace-repository.test.ts +++ b/packages/app/test/postgres-live-trace-repository.test.ts @@ -1,3 +1,4 @@ +import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; import { parseTrace, consumeTraceStream } from "../src/trace"; import { LiveTraceRepository } from "../src/postgres/live-trace-repository"; @@ -9,6 +10,7 @@ function fakeDatabase() { let cursor: any = null; const chunks = new Map(), events: any[] = []; const query = async (sql: string, values: any[] = []) => { + if (sql.startsWith("SELECT id,title FROM app.run_trace_events")) return { rows: events.filter(item => item.event_type === "tool_call").reverse().map(item => ({ id: item.id, title: item.title })), rowCount: 0 }; if (sql.startsWith("SELECT id FROM app.")) return { rows: [], rowCount: 0 }; if (sql.startsWith("SELECT generation,committed_offset") && sql.includes("FOR UPDATE")) return { rows: cursor ? [cursor] : [], rowCount: cursor ? 1 : 0 }; if (sql.startsWith("DELETE FROM app.run_trace_events")) { events.length = 0; return { rows: [], rowCount: 0 }; } @@ -71,4 +73,31 @@ describe("LiveTraceRepository", () => { expect(fake.state().cursor.pending_bytes).toHaveLength(0); }); + it("persists raw Codex projections identically across arbitrary live byte boundaries", async () => { + const fake = fakeDatabase(), repository = new LiveTraceRepository(fake.database, "tenant-1"); + const text = readFileSync(new URL("./fixtures/codex/exec-0.161.0.jsonl", import.meta.url), "utf8") + 'invalid\n{"type":"future.event"}\n'; + const bytes = new TextEncoder().encode(text); + let offset = 0, previousHash = zero; + while (offset < bytes.length) { + const part = bytes.slice(offset, offset + 53); + const hash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", part))].map(x => x.toString(16).padStart(2, "0")).join(""); + const receipt = await repository.append("run-1", "codex", { generation: "raw", expectedGeneration: offset ? "raw" : null, startOffset: offset, chunkSha256: hash, previousHash, bytes: part }, "execution_stream"); + offset = receipt.offset; previousHash = receipt.rollingHash; + } + const expected = parseTrace("codex", text, "execution_stream"); + expect(fake.state().events.map(item => ({ sequence: item.sequence, id: item.id, parentId: item.parent_id ?? undefined, type: item.event_type, title: item.title, preview: item.preview_text, display: item.display_data }))).toEqual(expected); + }); + it("correlates native calls from prior committed chunks", async () => { + const fake = fakeDatabase(), repository = new LiveTraceRepository(fake.database, "tenant-1"); + const text = readFileSync(new URL("./fixtures/codex/native-calls.jsonl", import.meta.url), "utf8"); + let offset = 0, previousHash = zero; + for (const line of text.trim().split("\n")) { + const record = line + "\n", bytes = new TextEncoder().encode(record); + const receipt = await repository.append("run-1", "codex", { generation: "native", expectedGeneration: offset ? "native" : null, startOffset: offset, chunkSha256: await digest(record), previousHash, bytes }); + offset = receipt.offset; previousHash = receipt.rollingHash; + } + expect(fake.state().events[1]).toMatchObject({ title: "exec_command", parent_id: "custom-1" }); + expect(fake.state().events[3]).toMatchObject({ title: "shell", parent_id: "legacy-1" }); + }); + }); diff --git a/packages/app/test/trace-source.test.ts b/packages/app/test/trace-source.test.ts index f2d5f783..7d20d6cb 100644 --- a/packages/app/test/trace-source.test.ts +++ b/packages/app/test/trace-source.test.ts @@ -7,10 +7,10 @@ const source: TraceSource = { kind: "execution_stream", path: "/tmp/trace/events export const record = JSON.stringify({ version: 1, id: "a", type: "assistant_message", title: "Assistant", preview: "hello 😀", display: { model: "test" } }); describe("execution stream contract", () => { - it("declares native-only compatibility explicitly for all existing drivers", () => { + it("declares the Codex primary stream and preserves other native drivers", () => { for (const provider of ["codex", "claude", "pi"] as const) { const launch = agentDriver(provider).launch("run-1", {}); - expect(launch.traceSources?.primary).toMatchObject({ kind: "native_session", mediaType: "application/x-ndjson", provider }); + expect(launch.traceSources?.primary).toMatchObject({ kind: provider === "codex" ? "execution_stream" : "native_session", mediaType: "application/x-ndjson", provider }); validateTraceSources(launch.traceSources!); } }); @@ -32,7 +32,7 @@ describe("execution stream contract", () => { const complete: any[] = []; await consumeTraceStream("codex", new Response(truncatedUtf8).body!, async items => { complete.push(...items); }, 250, "execution_stream"); expect(complete).toEqual(events); - expect(() => parseTrace("codex", "{}", "execution_stream")).toThrow("Invalid execution stream record"); - expect(() => parseTrace("codex", "invalid", "execution_stream")).toThrow("Invalid execution stream JSON"); + expect(() => parseTrace("claude", "{}", "execution_stream")).toThrow("Invalid execution stream record"); + expect(() => parseTrace("claude", "invalid", "execution_stream")).toThrow("Invalid execution stream JSON"); }); }); From df504dd215702e21f34b392b405aa5d7a499a972 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 9 Oct 2026 01:47:46 +0000 Subject: [PATCH 2/2] GEN-2142: Test trace rollback with a database projection failure --- packages/app/test/trace-source.postgres.test.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/app/test/trace-source.postgres.test.ts b/packages/app/test/trace-source.postgres.test.ts index be21c0b8..68519b99 100644 --- a/packages/app/test/trace-source.postgres.test.ts +++ b/packages/app/test/trace-source.postgres.test.ts @@ -65,11 +65,19 @@ describe.skipIf(!url)("trace sources with PostgreSQL", () => { await expect(f.live.append(f.runId, "codex", chunk, "execution_stream")).rejects.toThrow("already finalized"); }); - it("rolls back corrupt final projection and its receipt without losing live events", async () => { + it("rolls back failed final projection and its receipt without losing live events", async () => { const f = await fixture(), bytes = new TextEncoder().encode(record("live")); await f.live.append(f.runId, "codex", { generation: "file-1", expectedGeneration: null, startOffset: 0, chunkSha256: await hash(bytes), previousHash: zero, bytes }, "execution_stream"); const live = await f.trace.page(f.runId); - await expect(f.upload(record("new") + "invalid\n")).rejects.toThrow("Invalid execution stream JSON"); + // Malformed provider records may be tolerated. Force a real persistence failure + // after a complete batch was inserted to exercise the transaction rollback. + await database.pool.query("ALTER TABLE app.run_trace_events ADD CONSTRAINT reject_final_projection CHECK (preview_text <> 'reject-final-projection')"); + try { + const text = Array.from({ length: 250 }, (_, index) => record(`new-${index}`)).join("") + record("reject-final-projection"); + await expect(f.upload(text)).rejects.toThrow("reject_final_projection"); + } finally { + await database.pool.query("ALTER TABLE app.run_trace_events DROP CONSTRAINT reject_final_projection"); + } expect(await f.trace.page(f.runId)).toEqual(live); expect(await f.artifacts.list(f.runId)).toHaveLength(0); expect((await f.upload(record("live"))).status).toBe(201);