From c7570fa8cdbee85bb712566e79df5239529da69f Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 9 Oct 2026 00:40:55 +0000 Subject: [PATCH 1/3] Ingest Claude Code stdout as the primary live trace --- docs/execution-trace-stream.md | 46 ++++++- packages/app/src/agent-driver.ts | 8 +- packages/app/src/claude-stream.ts | 122 ++++++++++++++++++ packages/app/src/postgres/run-scheduler.ts | 4 +- packages/app/src/trace.ts | 24 +++- packages/app/test/claude-stream.test.ts | 121 +++++++++++++++++ .../test/fixtures/claude-2.1.293/native.jsonl | 2 + .../test/fixtures/claude-2.1.293/stream.jsonl | 6 + packages/app/test/run-finalization.test.ts | 8 ++ .../app/test/trace-source.postgres.test.ts | 12 +- packages/app/test/trace-source.test.ts | 4 +- 11 files changed, 337 insertions(+), 20 deletions(-) create mode 100644 packages/app/src/claude-stream.ts create mode 100644 packages/app/test/claude-stream.test.ts create mode 100644 packages/app/test/fixtures/claude-2.1.293/native.jsonl create mode 100644 packages/app/test/fixtures/claude-2.1.293/stream.jsonl diff --git a/docs/execution-trace-stream.md b/docs/execution-trace-stream.md index 0305dac9..7de88f76 100644 --- a/docs/execution-trace-stream.md +++ b/docs/execution-trace-stream.md @@ -4,8 +4,9 @@ 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 and Pi drivers retain a native +primary until their stream producers are implemented. Claude declares the stream +producer described below. Execution streams contain UTF-8, newline-terminated JSON objects in append order: @@ -44,3 +45,44 @@ Launch source declarations are persisted on the run (`trace_sources`), exposed by run detail and diagnostics. Artifact rows retain source kind, guest path, media type, provider, format/CLI/harness versions where supplied. Historical native-only runs still use their existing provider parser and artifact semantics. + +## Claude Code stdout producer (GEN-2138) + +New Claude jobs run print mode with `--output-format stream-json --verbose`. +A standalone Python 3 stdlib supervisor reads the CLI's stdout JSONL and appends +Factorize v1 records to `/tmp/factorize-artifacts//claude/trace.jsonl`, flushing +every event. Python 3 is required in the guest. The CLI inherits prompt stdin and +stderr; stderr stays in `/tmp/factorize.stderr`, never in the trace. The wrapper +preserves the child exit status and forwards SIGINT/SIGTERM, recording interruption +and abnormal exits. It bounds input records at 16 MiB and previews at 32 Ki characters and display payloads at 1 MiB. +Malformed/unknown records, unknown content blocks, oversized lines and incomplete +EOF records produce diagnostic warnings rather than poisoning the projection. +A partial line waits for LF while the CLI runs. At EOF it becomes a warning. + +`--forward-subagent-text` is deliberately **disabled**. Root Agent/Task calls and +results are the subagent activity visible by default; we do not invent child text +or replay transcripts into the root stream. If a CLI emits nested messages, their +`parent_tool_use_id` is preserved as `parentId`. Tool calls keep their native IDs; +all results in a user record are emitted separately with the matching name and +`parentId`, and `display.isError` retains tool failure status. System/task lifecycle +records retain their payload. Assistant and result usage remain separate usage +receipts (per-message versus total; do not sum both). The result receipt omits the +repeated final-answer text, avoiding duplicate assistant activity. +`--include-partial-messages` is also disabled to avoid duplicate delta/full-message +projection. `--json-schema` is not used. + +The normalized append-only stream is the primary live source and durable terminal +artifact, so terminal reconciliation uses the same bytes, IDs and ordering as +live projection. Native project-session JSONL remains a separate audit/recovery +artifact; it cannot overwrite an accepted primary stream. Historical runs with no +persisted source declaration continue to use native discovery. Native fallback +parsing retains tool IDs, result names and error flags, including across artifact +read chunks. + +`packages/app/test/fixtures/claude-2.1.293/` contains synthetic, version-pinned +schema fixtures for Claude Code 2.1.293 (the installed CLI version used during +implementation). They model default root/subagent-tool behavior, not forwarded +child text. Boundary tests execute the exact guest supervisor with a fake CLI, +including live pre-exit visibility, malformed/partial lines, UTF-8 fragmentation, +terminal reprojection, failure exits and native recovery. CLI flags follow +https://code.claude.com/docs/en/cli-reference . diff --git a/packages/app/src/agent-driver.ts b/packages/app/src/agent-driver.ts index 5f25ccb2..133b0b48 100644 --- a/packages/app/src/agent-driver.ts +++ b/packages/app/src/agent-driver.ts @@ -1,3 +1,4 @@ +import { CLAUDE_STREAM_HARNESS } from "./claude-stream"; import type { TraceSources } from "./trace-source"; export type AgentKind = "codex" | "claude" | "pi"; @@ -36,10 +37,13 @@ class CodexDriver implements AgentDriver { class ClaudeDriver implements AgentDriver { readonly kind = "claude" as const; launch(runId: string, config: AgentConfiguration): AgentLaunchSpec { - const args = ["-p", "--dangerously-skip-permissions", "--session-id", runId]; + const path = `/tmp/factorize-artifacts/${runId}/claude/trace.jsonl`; + const args = ["-u", "-c", CLAUDE_STREAM_HARNESS, path, "claude", "-p", "--output-format", "stream-json", "--verbose", "--dangerously-skip-permissions", "--session-id", runId]; if (config.model?.trim()) args.push("--model", config.model.trim()); if (config.effort?.trim()) args.push("--effort", config.effort.trim()); - return { executable: "claude", args, env: {}, stdin: "prompt", artifacts: { roots: ["$HOME/.claude/projects"], fileNameIncludes: runId, sessionId: runId, discoverCommand: `find "$HOME/.claude/projects" -type f -name '*${runId}.jsonl' -print | head -1` } }; + const artifacts: ArtifactLocator = { roots: ["$HOME/.claude/projects"], fileNameIncludes: runId, sessionId: runId, discoverCommand: `find "$HOME/.claude/projects" -type f -name '*${runId}.jsonl' -print | head -1` }; + const nativeSession = { kind: "native_session" as const, path: artifacts.roots[0], mediaType: "application/x-ndjson" as const, provider: this.kind, discoverCommand: artifacts.discoverCommand }; + return { executable: "python3", args, env: {}, stdin: "prompt", artifacts, traceSources: { primary: { kind: "execution_stream", path, mediaType: "application/x-ndjson", provider: this.kind, formatVersion: "1", harnessVersion: "claude-stream-v1" }, nativeSession } }; } } diff --git a/packages/app/src/claude-stream.ts b/packages/app/src/claude-stream.ts new file mode 100644 index 00000000..983a99e7 --- /dev/null +++ b/packages/app/src/claude-stream.ts @@ -0,0 +1,122 @@ +/** Standalone guest harness. Python's stdlib avoids a dependency on a Node install in the VM. */ +export const CLAUDE_STREAM_HARNESS = String.raw` +import json, os, signal, subprocess, sys + +path = sys.argv[1] +tools = {} +record_number = 0 +MAX_LINE = 16 * 1024 * 1024 + +def text(value): + if isinstance(value, str): + return value + if isinstance(value, list): + return "\n".join(text(x.get("text", x.get("thinking", ""))) if isinstance(x, dict) else text(x) for x in value) + return json.dumps(value, ensure_ascii=False) + +def emit(kind, title, preview, identity, parent=None, display=None): + preview = text(preview) + if len(preview) > 32768: + preview = preview[:32768] + "\n… output truncated in trace view" + display = display or {} + if len(json.dumps(display, ensure_ascii=False).encode("utf-8")) > 1024 * 1024: + display = dict(truncated=True, diagnostic="Display payload exceeded 1 MiB") + item = dict(version=1, id=str(identity), type=kind, title=str(title)[:1024], preview=preview, display=display) + if parent: + item["parentId"] = str(parent) + stream.write(json.dumps(item, ensure_ascii=False) + "\n") + stream.flush() + +def normalize(value): + global record_number + record_number += 1 + base = "claude:" + str(record_number) + if not isinstance(value, dict): + emit("warning", "Invalid Claude stream record", value, base) + return + base = str(value.get("uuid") or base) + parent = value.get("parent_tool_use_id") or (value.get("tool_use_id") if value.get("type") == "system" else None) + kind = value.get("type") + if kind in ("assistant", "user"): + message = value.get("message") or {} + content = message.get("content", []) + if isinstance(content, str): + content = [dict(type="text", text=content)] + if not isinstance(content, list): + emit("warning", "Invalid Claude message", value, base, parent) + return + for i, block in enumerate(content): + identity = base + ":" + str(i) + if not isinstance(block, dict): + emit("warning", "Unknown Claude content block", block, identity, parent) + continue + block_kind = block.get("type") + if block_kind == "tool_use": + tool_id = str(block.get("id") or identity) + name = str(block.get("name") or "Tool call") + tools[tool_id] = name + emit("tool_call", name, block.get("input", {}), tool_id, parent, dict(arguments=block.get("input", {}))) + elif block_kind == "tool_result": + tool_id = str(block.get("tool_use_id") or "") + emit("tool_result", tools.get(tool_id, "Tool result"), block.get("content", ""), identity, tool_id or parent, + dict(toolUseId=tool_id, isError=bool(block.get("is_error")), toolName=tools.get(tool_id))) + elif block_kind == "thinking": + emit("reasoning", "Reasoning", block.get("thinking", ""), identity, parent) + elif block_kind == "text": + emit("assistant_message" if kind == "assistant" else "user_message", "Assistant" if kind == "assistant" else "User", block.get("text", ""), identity, parent) + else: + emit("warning", "Unknown Claude content block", block, identity, parent) + if message.get("usage"): + emit("usage", "Usage", message["usage"], base + ":usage", parent, dict(usage=message["usage"])) + if value.get("error"): + emit("error", "Claude assistant error", value["error"], base + ":error", parent) + elif kind == "result": + failed = value.get("is_error") or value.get("subtype") != "success" + # result.result repeats the final assistant answer. Keep only the completion receipt. + details = {k: v for k, v in value.items() if k not in ("result", "type", "uuid")} + emit("error" if failed else "metadata", "Claude " + str(value.get("subtype", "result")), details, base, parent, details) + if value.get("usage"): + emit("usage", "Total usage", value["usage"], base + ":usage", parent, dict(usage=value["usage"], modelUsage=value.get("modelUsage", {}))) + elif kind in ("system", "error", "abort", "interrupt"): + subtype = str(value.get("subtype", kind)) + event_kind = "error" if kind in ("error", "abort", "interrupt") or any(x in subtype for x in ("error", "abort", "interrupt")) else "metadata" + emit(event_kind, "Claude " + subtype, value, base, parent, value) + else: + emit("warning", "Unknown Claude stream event", value, base, parent) + +os.makedirs(os.path.dirname(path), exist_ok=True) +with open(path, "a", encoding="utf-8") as stream: + try: + child = subprocess.Popen(sys.argv[2:], stdin=sys.stdin, stdout=subprocess.PIPE, stderr=sys.stderr) + except OSError as error: + emit("error", "Claude launch failed", str(error), "claude:launch-error") + sys.exit(127) + def stop(signum, frame): + emit("error", "Claude interrupted", dict(signal=signum), "claude:signal:" + str(signum)) + child.send_signal(signum) + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + while True: + line = child.stdout.readline(MAX_LINE + 1) + if not line: + break + if len(line) > MAX_LINE: + while line and not line.endswith(b"\n"): + line = child.stdout.readline(MAX_LINE + 1) + record_number += 1 + emit("warning", "Oversized Claude stream record", "Record exceeded 16 MiB", "claude:" + str(record_number)) + continue + if not line.strip(): + continue + try: + if not line.endswith(b"\n"): + raise ValueError("Unterminated JSONL record at EOF") + normalize(json.loads(line)) + except (ValueError, TypeError, AttributeError, RecursionError) as error: + record_number += 1 + emit("warning", "Unparseable Claude stream record", str(error) + ": " + line[:32768].decode("utf-8", errors="replace"), "claude:" + str(record_number)) + code = child.wait() + if code: + emit("error", "Claude process exited", dict(exitCode=code), "claude:exit") + sys.exit(code if code >= 0 else 128 - code) +`; diff --git a/packages/app/src/postgres/run-scheduler.ts b/packages/app/src/postgres/run-scheduler.ts index 62071f22..66f3fc11 100644 --- a/packages/app/src/postgres/run-scheduler.ts +++ b/packages/app/src/postgres/run-scheduler.ts @@ -104,7 +104,9 @@ 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, {})); + // Runs launched before source declarations must keep their native projection. + const launch = agentDriver(run.executionTarget.agentKind as AgentKind).launch(run.id, {}); + return run.executionTarget.traceSources ?? { primary: { kind: "native_session", path: launch.artifacts.roots[0], mediaType: "application/x-ndjson", provider: run.executionTarget.agentKind as AgentKind, discoverCommand: launch.artifacts.discoverCommand } }; } private async collectArtifact(run: PersistedRun, backend: ExeVmBackend, source?: TraceSource, primary?: boolean) { diff --git a/packages/app/src/trace.ts b/packages/app/src/trace.ts index a9b4977d..1e8ac150 100644 --- a/packages/app/src/trace.ts +++ b/packages/app/src/trace.ts @@ -61,17 +61,26 @@ function parseCodex(value: any, sequence: number): TraceEvent[] { return []; } -function parseClaude(value: any, sequence: number): TraceEvent[] { +function parseClaude(value: any, sequence: number, tools: Map): TraceEvent[] { + if (!value || typeof value !== "object") return [event(sequence, "warning", "Invalid Claude session record", value, {})]; const message = value.message ?? value; if (value.type === "user" || message.role === "user") { - const toolResult = Array.isArray(message.content) && message.content.find((x: any) => x?.type === "tool_result"); - return [event(sequence, toolResult ? "tool_result" : "user_message", toolResult ? "Tool result" : "User", contentText(toolResult?.content ?? message.content), value)]; + const blocks = Array.isArray(message.content) ? message.content : []; + const results = blocks.filter((block: any) => block?.type === "tool_result"); + if (results.length) return results.map((block: any, index: number) => ({ + ...event(sequence + index, "tool_result", tools.get(block.tool_use_id) ?? "Tool result", contentText(block.content), { ...value, id: `${value.uuid ?? sequence}:${index}`, parentId: block.tool_use_id }), + display: { toolUseId: block.tool_use_id, isError: Boolean(block.is_error) }, + })); + return [event(sequence, "user_message", "User", contentText(message.content), value)]; } if (value.type === "assistant" || message.role === "assistant") { const entries: TraceEvent[] = []; for (const block of Array.isArray(message.content) ? message.content : []) { if (block.type === "thinking") entries.push(event(sequence + entries.length, "reasoning", "Reasoning", block.thinking, value)); - else if (block.type === "tool_use") entries.push({ ...event(sequence + entries.length, "tool_call", String(block.name ?? "Tool call"), block.input, { ...value, id: block.id }), display: { arguments: block.input ?? {} } }); + else if (block.type === "tool_use") { + tools.set(block.id, String(block.name ?? "Tool call")); + entries.push({ ...event(sequence + entries.length, "tool_call", String(block.name ?? "Tool call"), block.input, { ...value, id: block.id }), display: { arguments: block.input ?? {} } }); + } else if (block.type === "text") entries.push(event(sequence + entries.length, "assistant_message", "Assistant", block.text, value)); } return entries; @@ -80,7 +89,7 @@ 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", claudeTools = new Map()): TraceEvent[] { const events: TraceEvent[] = []; for (const line of jsonl.split(/\r?\n/)) { if (!line.trim()) continue; @@ -93,7 +102,7 @@ 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); + const parsed = provider === "codex" ? parseCodex(value, events.length + 1) : provider === "claude" ? parseClaude(value, events.length + 1, claudeTools) : parsePi(value, events.length + 1); events.push(...parsed); } return events.map((item, index) => ({ ...item, sequence: index + 1 })); @@ -132,10 +141,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 claudeTools = 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, claudeTools); for (const item of parsed) { batch.push({ ...item, sequence: ++sequence }); if (batch.length >= batchSize) await flush(); } }; for (;;) { diff --git a/packages/app/test/claude-stream.test.ts b/packages/app/test/claude-stream.test.ts new file mode 100644 index 00000000..37dd2b36 --- /dev/null +++ b/packages/app/test/claude-stream.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from "vitest"; +import { spawn, spawnSync } from "node:child_process"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { CLAUDE_STREAM_HARNESS } from "../src/claude-stream"; +import { agentDriver } from "../src/agent-driver"; +import { consumeTraceStream, parseTrace } from "../src/trace"; + +const fixture = (name: string) => readFile(new URL(`./fixtures/claude-2.1.293/${name}.jsonl`, import.meta.url), "utf8"); +async function harness(input: string, code = 0) { + const directory = await mkdtemp(join(tmpdir(), "claude-stream-")), path = join(directory, "trace.jsonl"); + try { + // A fake CLI exercises the exact guest wrapper, byte framing, stdout/stderr and exit behavior. + const child = spawn("python3", ["-u", "-c", CLAUDE_STREAM_HARNESS, path, "python3", "-u", "-c", `import sys\nsys.stdout.buffer.write(sys.stdin.buffer.read())\nsys.stderr.write('diagnostic stderr')\nsys.exit(${code})`]); + child.stdin.end(input); + let stderr = "", stdout = ""; + child.stderr.on("data", bytes => { stderr += bytes; }); + child.stdout.on("data", bytes => { stdout += bytes; }); + const exit = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); }); + const jsonl = await readFile(path, "utf8"); + return { exit, stderr, stdout, jsonl, events: parseTrace("claude", jsonl, "execution_stream") }; + } finally { await rm(directory, { recursive: true, force: true }); } +} + +describe("Claude Code 2.1.293 stream-json boundary", () => { + it("declares a primary stream with native recovery and no forwarded or partial duplicates", () => { + const launch = agentDriver("claude").launch("run-1", { model: "sonnet", effort: "high" }); + expect(launch.args).toEqual(expect.arrayContaining(["--output-format", "stream-json", "--verbose", "--model", "sonnet", "--effort", "high"])); + expect(launch.args).not.toContain("--forward-subagent-text"); + expect(launch.args).not.toContain("--include-partial-messages"); + expect(launch.args).not.toContain("--json-schema"); + expect(launch.traceSources?.primary).toMatchObject({ kind: "execution_stream", formatVersion: "1", provider: "claude" }); + expect(launch.traceSources?.nativeSession?.kind).toBe("native_session"); + }); + it("projects calls/results, thinking, lifecycle and usage and reconciles identically", async () => { + const result = await harness(await fixture("stream")); + expect(result.exit).toBe(0); + expect(result.stdout).toBe(""); + expect(result.stderr).toBe("diagnostic stderr"); + expect(result.events.filter(event => event.type === "tool_call").map(event => event.id)).toEqual(["tool-bash", "tool-agent"]); + expect(result.events.filter(event => event.type === "tool_result")).toMatchObject([ + { title: "Bash", parentId: "tool-bash", display: { isError: false } }, + { title: "Agent", parentId: "tool-agent", display: { isError: true } }, + ]); + expect(result.events.filter(event => event.preview === "Done")).toHaveLength(1); + expect(result.events.some(event => event.type === "reasoning")).toBe(true); + expect(result.events.filter(event => event.type === "usage")).toHaveLength(3); + const bytes = new TextEncoder().encode(result.jsonl), live: any[] = []; + const stream = new ReadableStream({ start(controller) { for (const byte of bytes) controller.enqueue(new Uint8Array([byte])); controller.close(); } }); + await consumeTraceStream("claude", stream, async batch => { live.push(...batch); }, 1, "execution_stream"); + expect(live).toEqual(result.events); + expect(parseTrace("claude", result.jsonl, "execution_stream")).toEqual(result.events); + }); + it("makes unknown, malformed, abort, result errors and incomplete records diagnosable", async () => { + const input = 'null\n{"type":"new_event"}\nnot json\n{"type":"abort"}\n{"type":"result","subtype":"error_during_execution","is_error":true,"errors":["failed"]}\n{"type":"assistant"'; + const result = await harness(input, 7); + expect(result.exit).toBe(7); + expect(result.events.map(event => event.type)).toEqual(["warning", "warning", "warning", "error", "error", "warning", "error"]); + expect(result.events.some(event => event.preview.includes("Unterminated JSONL"))).toBe(true); + }); + it("retains nested parents defensively without enabling forwarding", async () => { + const result = await harness('{"type":"assistant","uuid":"nested","parent_tool_use_id":"tool-agent","message":{"content":[{"type":"text","text":"Child"}]}}\n'); + expect(result.events[0]).toMatchObject({ parentId: "tool-agent", preview: "Child" }); + }); + it("shows a tool result while the producing CLI is still running", async () => { + const directory = await mkdtemp(join(tmpdir(), "claude-live-")), path = join(directory, "trace.jsonl"); + const input = (await fixture("stream")).split("\n").slice(0, 3).join("\n") + "\n"; + const child = spawn("python3", ["-u", "-c", CLAUDE_STREAM_HARNESS, path, "python3", "-u", "-c", `import sys\nsys.stdout.write(${JSON.stringify(input)})\nsys.stdout.flush()\nsys.stdin.read()`]); + const closed = new Promise(resolve => child.on("close", resolve)); + try { + let events: ReturnType = []; + for (let i = 0; i < 100; i++) { + try { events = parseTrace("claude", await readFile(path, "utf8"), "execution_stream"); } catch { /* File/record may still be arriving. */ } + if (events.some(event => event.type === "tool_result")) break; + await new Promise(resolve => setTimeout(resolve, 10)); + } + expect(child.exitCode).toBeNull(); + expect(events.some(event => event.type === "tool_result")).toBe(true); + } finally { child.stdin.end(); await closed; await rm(directory, { recursive: true, force: true }); } + }); + it("bounds oversized records and display data without rejecting the stream", async () => { + const huge = "x".repeat(16 * 1024 * 1024 + 1); + const result = await harness(huge + "\n" + JSON.stringify({ type: "assistant", message: { content: [{ type: "tool_use", id: "big-tool", name: "Bash", input: { command: "x".repeat(1024 * 1024) } }] } }) + "\n"); + expect(result.events[0]).toMatchObject({ type: "warning", title: "Oversized Claude stream record" }); + expect(result.events[1]).toMatchObject({ id: "big-tool", display: { truncated: true } }); + expect(result.events[1].preview.length).toBeLessThan(33000); + }); + it("records spawn failures and forwards interruption with a nonzero exit", async () => { + const directory = await mkdtemp(join(tmpdir(), "claude-signal-")), path = join(directory, "trace.jsonl"); + try { + const failed = spawnSync("python3", ["-u", "-c", CLAUDE_STREAM_HARNESS, path, "/missing-factorize-claude"], { encoding: "utf8" }); + expect(failed.status).toBe(127); + expect(parseTrace("claude", await readFile(path, "utf8"), "execution_stream")[0].title).toBe("Claude launch failed"); + await rm(path); + const child = spawn("python3", ["-u", "-c", CLAUDE_STREAM_HARNESS, path, "python3", "-u", "-c", `import sys\nsys.stdout.write('{"type":"system","subtype":"init"}\\n')\nsys.stdout.flush()\nsys.stdin.read()`]); + const closed = new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); }); + try { + let ready = false; + for (let i = 0; i < 100; i++) { + try { ready = (await readFile(path, "utf8")).includes("init"); } catch { /* Wait for init. */ } + if (ready) break; + await new Promise(resolve => setTimeout(resolve, 10)); + } + expect(ready).toBe(true); + child.kill("SIGTERM"); + expect(await closed).toBe(143); + expect(parseTrace("claude", await readFile(path, "utf8"), "execution_stream")).toMatchObject([ + { type: "metadata" }, { type: "error", title: "Claude interrupted" }, { type: "error", title: "Claude process exited" }, + ]); + } finally { child.stdin.end(); child.kill(); await closed; } + } finally { await rm(directory, { recursive: true, force: true }); } + }); + it("parses native fallback tools and preserves IDs and errors across chunks", async () => { + const input = await fixture("native"), expected = parseTrace("claude", input); + expect(expected).toMatchObject([{ id: "native-bash", title: "Bash", type: "tool_call" }, { parentId: "native-bash", title: "Bash", type: "tool_result", display: { isError: true } }]); + const events: any[] = []; + await consumeTraceStream("claude", new Response(input).body!, async batch => { events.push(...batch); }, 1); + expect(events).toEqual(expected); + }); +}); diff --git a/packages/app/test/fixtures/claude-2.1.293/native.jsonl b/packages/app/test/fixtures/claude-2.1.293/native.jsonl new file mode 100644 index 00000000..8c3bb94f --- /dev/null +++ b/packages/app/test/fixtures/claude-2.1.293/native.jsonl @@ -0,0 +1,2 @@ +{"type":"assistant","uuid":"native-assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"native-bash","name":"Bash","input":{"command":"false"}}]}} +{"type":"user","uuid":"native-user","parentUuid":"native-assistant","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"native-bash","content":"Exit code 1","is_error":true}]}} diff --git a/packages/app/test/fixtures/claude-2.1.293/stream.jsonl b/packages/app/test/fixtures/claude-2.1.293/stream.jsonl new file mode 100644 index 00000000..1743de0d --- /dev/null +++ b/packages/app/test/fixtures/claude-2.1.293/stream.jsonl @@ -0,0 +1,6 @@ +{"type":"system","subtype":"init","session_id":"fixture-session","tools":["Bash","Agent"],"model":"fixture-model","uuid":"init"} +{"type":"assistant","uuid":"assistant-1","parent_tool_use_id":null,"message":{"role":"assistant","content":[{"type":"thinking","thinking":"Check the working directory"},{"type":"text","text":"Checking 😀"},{"type":"tool_use","id":"tool-bash","name":"Bash","input":{"command":"pwd"}},{"type":"tool_use","id":"tool-agent","name":"Agent","input":{"prompt":"Inspect files"}}],"usage":{"input_tokens":12,"output_tokens":8}}} +{"type":"user","uuid":"results-1","parent_tool_use_id":null,"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-bash","content":"/workspace","is_error":false},{"type":"tool_result","tool_use_id":"tool-agent","content":[{"type":"text","text":"Inspection failed"}],"is_error":true}]}} +{"type":"system","subtype":"task_started","uuid":"task-1","task_id":"nested-task","tool_use_id":"tool-agent","description":"Inspect files"} +{"type":"assistant","uuid":"answer","parent_tool_use_id":null,"message":{"role":"assistant","content":[{"type":"text","text":"Done"}],"usage":{"input_tokens":20,"output_tokens":4}}} +{"type":"result","subtype":"success","uuid":"result","is_error":false,"result":"Done","duration_ms":42,"num_turns":2,"usage":{"input_tokens":32,"output_tokens":12},"modelUsage":{"fixture-model":{"inputTokens":32,"outputTokens":12}},"total_cost_usd":0.001} diff --git a/packages/app/test/run-finalization.test.ts b/packages/app/test/run-finalization.test.ts index c051d06b..ac0de6ac 100644 --- a/packages/app/test/run-finalization.test.ts +++ b/packages/app/test/run-finalization.test.ts @@ -35,6 +35,14 @@ function fixture(exit = 42) { } describe("durable run finalization", () => { + it("keeps historical Claude runs on native discovery without a source declaration", async () => { + const f = fixture(0); + f.run.executionTarget.agentKind = "claude"; + expect(f.scheduler.sources(f.run).primary).toMatchObject({ kind: "native_session", provider: "claude", discoverCommand: expect.stringContaining(".claude/projects") }); + await f.scheduler.poll(f.run); + expect(f.native).toHaveBeenCalledOnce(); + expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "stored", undefined, true); + }); it("stores real nonzero harness stderr and exit metadata before deleting the VM", async () => { const f = fixture(); await f.scheduler.poll(f.run); diff --git a/packages/app/test/trace-source.postgres.test.ts b/packages/app/test/trace-source.postgres.test.ts index be21c0b8..ea137f63 100644 --- a/packages/app/test/trace-source.postgres.test.ts +++ b/packages/app/test/trace-source.postgres.test.ts @@ -24,7 +24,7 @@ describe.skipIf(!url)("trace sources with PostgreSQL", () => { }); afterAll(async () => { await database?.close(); if (admin) { await admin.pool.query(`DROP DATABASE IF EXISTS ${databaseName} WITH (FORCE)`); await admin.close(); } }); - async function fixture() { + async function fixture(provider: "codex" | "claude" = "codex") { const tenantId = crypto.randomUUID(), jobId = crypto.randomUUID(), triggerId = crypto.randomUUID(), invocationId = crypto.randomUUID(), runId = crypto.randomUUID(); await database.pool.query("INSERT INTO app.tenants(id) VALUES ($1)", [tenantId]); await database.pool.query("INSERT INTO app.jobs(tenant_id,id,name,slug,encrypted_prompt_template,execution_target,concurrency_limit) VALUES ($1,$2,'Trace test','trace-test','test','{}',1)", [tenantId, jobId]); @@ -38,16 +38,16 @@ describe.skipIf(!url)("trace sources with PostgreSQL", () => { } } as any; const upload = async (text: string, kind: "execution_stream" | "native_session" = "execution_stream") => { const bytes = new TextEncoder().encode(text), sha256 = await hash(bytes); - const token = await issueArtifactUploadGrant({ tenantId, runId, path: kind === "execution_stream" ? "trace/stream.jsonl" : "native/session.jsonl", contentType: "application/x-ndjson", provider: "codex", format: "jsonl", sourceKind: kind, sourcePath: "/tmp/trace.jsonl", formatVersion: "1", cliVersion: "p1", harnessVersion: "h1", primary: kind === "execution_stream", expiresAt: Date.now() + 60_000 }, secret); + const token = await issueArtifactUploadGrant({ tenantId, runId, path: kind === "execution_stream" ? "trace/stream.jsonl" : "native/session.jsonl", contentType: "application/x-ndjson", provider, format: "jsonl", sourceKind: kind, sourcePath: "/tmp/trace.jsonl", formatVersion: "1", cliVersion: "p1", harnessVersion: "h1", primary: kind === "execution_stream", expiresAt: Date.now() + 60_000 }, secret); return artifactUpload(new Request("https://app/upload", { method: "PUT", headers: { "Content-Type": "application/x-ndjson", "Content-Length": String(bytes.length), "X-Artifact-SHA256": sha256 }, body: bytes }), env, token); }; return { runId, upload, blobs, live: new LiveTraceRepository(database, tenantId), trace: new TraceRepository(database, tenantId), artifacts: new ArtifactRepository(database, tenantId) }; } - it("reconciles durable bytes, preserves native audit data, and rejects late chunks", async () => { - const f = await fixture(), text = record("event-1") + '{"partial":', bytes = new TextEncoder().encode(text); + it.each(["codex", "claude"] as const)("reconciles %s durable bytes, preserves native audit data, and rejects late chunks", async provider => { + const f = await fixture(provider), text = record("event-1") + '{"partial":', bytes = new TextEncoder().encode(text); const chunk = { generation: "file-1", expectedGeneration: null, startOffset: 0, chunkSha256: await hash(bytes), previousHash: zero, bytes }; - const receipts = await Promise.all([f.live.append(f.runId, "codex", chunk, "execution_stream"), f.live.append(f.runId, "codex", chunk, "execution_stream")]); + const receipts = await Promise.all([f.live.append(f.runId, provider, chunk, "execution_stream"), f.live.append(f.runId, provider, chunk, "execution_stream")]); expect(receipts.filter(receipt => receipt.duplicate)).toHaveLength(1); const live = await f.trace.page(f.runId); expect(live.items).toHaveLength(1); @@ -62,7 +62,7 @@ describe.skipIf(!url)("trace sources with PostgreSQL", () => { expect(new TextDecoder().decode(f.blobs.get(stream.object_key))).toBe(text); expect((await f.upload(text)).status).toBe(201); expect((await f.upload(record("replacement"))).status).toBe(409); - await expect(f.live.append(f.runId, "codex", chunk, "execution_stream")).rejects.toThrow("already finalized"); + await expect(f.live.append(f.runId, provider, chunk, "execution_stream")).rejects.toThrow("already finalized"); }); it("rolls back corrupt final projection and its receipt without losing live events", async () => { diff --git a/packages/app/test/trace-source.test.ts b/packages/app/test/trace-source.test.ts index f2d5f783..5e0c3b18 100644 --- a/packages/app/test/trace-source.test.ts +++ b/packages/app/test/trace-source.test.ts @@ -7,8 +7,8 @@ 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", () => { - for (const provider of ["codex", "claude", "pi"] as const) { + it("declares native-only compatibility explicitly for unchanged drivers", () => { + for (const provider of ["codex", "pi"] as const) { const launch = agentDriver(provider).launch("run-1", {}); expect(launch.traceSources?.primary).toMatchObject({ kind: "native_session", mediaType: "application/x-ndjson", provider }); validateTraceSources(launch.traceSources!); From 0c5e1ce47493f867bb7d4a904ed627216f384f21 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 9 Oct 2026 00:40:59 +0000 Subject: [PATCH 2/3] 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 3/3] 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);