From c7570fa8cdbee85bb712566e79df5239529da69f Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 9 Oct 2026 00:40:55 +0000 Subject: [PATCH] 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!);