From a80fa4b349053316052d4a67d43f2e95110ecf7a Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 9 Oct 2026 00:40:55 +0000 Subject: [PATCH] Harden Pi native session v3 trace projection (GEN-2139) --- docs/execution-trace-stream.md | 5 +- docs/pi-session-contract.md | 46 ++++++++++ packages/app/src/agent-driver.ts | 5 +- packages/app/src/pi-trace.ts | 86 ++++++++++++++++++ packages/app/src/trace.ts | 22 +---- packages/app/test/fixtures/pi/1.1.0/README.md | 18 ++++ .../app/test/fixtures/pi/1.1.0/capture.py | 27 ++++++ .../fixtures/pi/1.1.0/documented-v3.jsonl | 17 ++++ .../fixtures/pi/1.1.0/native-session.jsonl | 8 ++ packages/app/test/pi-trace.test.ts | 89 +++++++++++++++++++ .../postgres-live-trace-repository.test.ts | 24 +++++ 11 files changed, 323 insertions(+), 24 deletions(-) create mode 100644 docs/pi-session-contract.md create mode 100644 packages/app/src/pi-trace.ts create mode 100644 packages/app/test/fixtures/pi/1.1.0/README.md create mode 100644 packages/app/test/fixtures/pi/1.1.0/capture.py create mode 100644 packages/app/test/fixtures/pi/1.1.0/documented-v3.jsonl create mode 100644 packages/app/test/fixtures/pi/1.1.0/native-session.jsonl create mode 100644 packages/app/test/pi-trace.test.ts diff --git a/docs/execution-trace-stream.md b/docs/execution-trace-stream.md index 0305dac9..3a5ed82a 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 Claude retain native-primary compatibility until their stream producers +are enabled. Pi keeps its published native session as primary; see +[Pi session contract](pi-session-contract.md). Execution streams contain UTF-8, newline-terminated JSON objects in append order: diff --git a/docs/pi-session-contract.md b/docs/pi-session-contract.md new file mode 100644 index 00000000..d22380ba --- /dev/null +++ b/docs/pi-session-contract.md @@ -0,0 +1,46 @@ +# Pi native session projection + +Factorize supports the exe.dev **@earendil-works/pi-coding-agent 1.1.0** +binary and its published **session JSONL v3** contract. Pi launches check +`pi --version` before passing the prompt to the CLI; a different version fails +with a harness diagnostic. Guest image owners must install the supported release. +An upgrade requires reviewing the release's session/message contracts, capturing +new versioned fixtures, and changing the version constant and tests together. + +The compatibility reference is the release's +[session format](https://github.com/earendil-works/pi/blob/v1.1.0/packages/coding-agent/docs/session-format.md) +and [message types](https://github.com/earendil-works/pi/blob/v1.1.0/packages/coding-agent/docs/message-types.md), +also shipped in the binary's docs directory. Fixtures live in +`packages/app/test/fixtures/pi/1.1.0`; their README documents reproduction. + +Pi's primary source is the native session discovered under its run-specific +`--session-dir`. Both live projection and terminal reconciliation read this file. +Source receipts record `native_session`, CLI version `1.1.0`, and format version +`3`. Plain print-mode stdout remains terminal output and is never advertised as +a complete execution stream. + +Projection retains all branches in append order, including abandoned history. +It does not rebuild only the active model context or apply context edits to +historical display content. Every event retains its native entry ID, parent, +and ISO timestamp; display provenance also retains null roots and the nested +Unix-millisecond message timestamp. Several content-block or usage events may +share one native entry ID. `display.blockIndex` identifies content blocks; +`display.toolCallId` links tool calls and results independently of entry IDs. + +The UI shows text/thinking, tool arguments/results, direct bash executions, +usage, compaction and branch summaries. Metadata retains model/thinking changes, +system prompt/tool patches, context edits, labels, session info, custom entries, +unknown roles and future records. Compaction retains `firstKeptEntryId`, +checkpoint, and token counts; branches retain `fromId` and their actual parent. +Arguments, results and extension metadata are bounded for display; images and +opaque replay signatures are omitted. The native artifact remains exact. + +The projector never rewrites or migrates stored artifacts. Pi itself migrates +v1 (linear) to v2 (tree) and v2 `hookMessage` to v3 `custom` on load. Historical +headers without a version or with non-v3 versions are marked +`best_effort_unmigrated`; available IDs are preserved and absent ancestry is +not invented. Legacy `hookMessage` is displayed as custom metadata. Unknown +future types use bounded metadata, malformed JSON uses warning events, and +invalid timestamps remain display metadata rather than invalid database dates. +This fallback is for retained artifacts, not authorization to launch unreviewed +CLI versions. diff --git a/packages/app/src/agent-driver.ts b/packages/app/src/agent-driver.ts index 5f25ccb2..2a69763f 100644 --- a/packages/app/src/agent-driver.ts +++ b/packages/app/src/agent-driver.ts @@ -1,3 +1,4 @@ +import { PI_CLI_VERSION, PI_SESSION_VERSION } from "./pi-trace"; import type { TraceSources } from "./trace-source"; export type AgentKind = "codex" | "claude" | "pi"; @@ -50,7 +51,9 @@ class PiDriver implements AgentDriver { const args = ["-p", "--session-id", runId, "--session-dir", sessionDir]; if (config.model?.trim()) args.push("--model", config.model.trim()); if (config.effort?.trim()) args.push("--thinking", config.effort.trim()); - return { executable: "pi", args, env: {}, stdin: "prompt", artifacts: { roots: [sessionDir], fileNameIncludes: ".jsonl", sessionId: runId, discoverCommand: `find '${sessionDir}' -type f -name '*.jsonl' -print | head -1` } }; + const discoverCommand = `find '${sessionDir}' -type f -name '*.jsonl' -print | head -1`; + // Guest images own installation. Refuse version drift before consuming stdin. + return { executable: "/bin/sh", args: ["-c", `test "$(pi --version)" = "${PI_CLI_VERSION}" || { echo "Factorize requires Pi ${PI_CLI_VERSION}" >&2; exit 1; }; exec pi "$@"`, "factorize-pi", ...args], env: {}, stdin: "prompt", artifacts: { roots: [sessionDir], fileNameIncludes: ".jsonl", sessionId: runId, discoverCommand }, traceSources: { primary: { kind: "native_session", path: sessionDir, mediaType: "application/x-ndjson", provider: "pi", cliVersion: PI_CLI_VERSION, formatVersion: PI_SESSION_VERSION, discoverCommand } } }; } } diff --git a/packages/app/src/pi-trace.ts b/packages/app/src/pi-trace.ts new file mode 100644 index 00000000..caaa4ef2 --- /dev/null +++ b/packages/app/src/pi-trace.ts @@ -0,0 +1,86 @@ +import type { TraceEvent, TraceEventType } from "./trace"; + +/** The exe.dev Pi binary and its published session contract, not stdout events. */ +export const PI_CLI_VERSION = "1.1.0"; +export const PI_SESSION_VERSION = "3"; +const LIMIT = 32_768; +const clip = (value: unknown): string => { + const text = typeof value === "string" ? value : JSON.stringify(value ?? ""); + return text.length <= LIMIT ? text : text.slice(0, LIMIT) + "\n… output truncated in trace view"; +}; +const object = (value: any): value is Record => !!value && typeof value === "object" && !Array.isArray(value); + +/** Bound arbitrary extension payloads; omit binary images and opaque replay signatures. */ +function safe(value: any, depth = 0): any { + if (typeof value === "string") return clip(value); + if (value === null || typeof value !== "object") return value; + if (depth >= 6) return "[nested metadata omitted]"; + if (Array.isArray(value)) return value.slice(0, 64).map(item => safe(item, depth + 1)); + if (value.type === "image") return { type: "image", mimeType: clip(value.mimeType), omitted: true }; + return Object.fromEntries(Object.entries(value).slice(0, 64).filter(([key]) => !["thinkingSignature", "thoughtSignature", "textSignature"].includes(key)).map(([key, item]) => [clip(key), safe(item, depth + 1)])); +} +function bounded(value: any): any { + const result = safe(value); + const json = JSON.stringify(result ?? null); + return json.length <= LIMIT ? result : { truncated: true, preview: clip(json) }; +} +const text = (content: any): string => Array.isArray(content) + ? clip(content.map(block => object(block) ? block.type === "image" ? `[Image: ${clip(block.mimeType)}; binary omitted]` : block.text ?? block.thinking ?? `[Content block: ${clip(block.type)}]` : "").join("\n")) + : clip(content); + +/** Each derived event retains the native entry ID/parent; tool IDs are separate links. */ +export function parsePi(input: any, sequence: number): TraceEvent[] { + const value = object(input) ? input : { type: "invalid_record", data: input }; + const message = object(value.message) ? value.message : {}; + const provenance = { + entryType: value.type ?? "unknown", entryId: value.id ?? null, + parentId: value.parentId ?? null, timestamp: value.timestamp ?? null, + ...(message.timestamp !== undefined ? { messageTimestamp: message.timestamp } : {}), + }; + const make = (type: TraceEventType, title: string, preview: any, extra: Record = {}): TraceEvent => ({ + sequence, id: String(value.id ?? `pi:${sequence}`), + ...(typeof value.parentId === "string" ? { parentId: value.parentId } : {}), + type, title: clip(title), preview: clip(preview), + ...(typeof message.role === "string" ? { role: message.role } : {}), + ...(typeof value.timestamp === "string" && Number.isFinite(Date.parse(value.timestamp)) ? { occurredAt: value.timestamp } : {}), + display: { ...bounded(provenance), ...extra }, + }); + const metadata = (title: string, record: any = value) => make("metadata", title, bounded(record), { metadata: bounded(record) }); + if (value.type === "session") return [make("metadata", "Session started", value.cwd ?? "", { + version: value.version ?? 1, cwd: clip(value.cwd), parentSession: value.parentSession ? clip(value.parentSession) : null, + compatibility: value.version === 3 ? "supported" : "best_effort_unmigrated", + })]; + if (value.type === "compaction" || value.type === "branch_summary") return [make(value.type === "compaction" ? "compaction" : "branch", value.type === "compaction" ? "Context compacted" : "Branch summary", value.summary, { + firstKeptEntryId: value.firstKeptEntryId ?? null, fromId: value.fromId ?? null, + tokensBefore: value.tokensBefore, fromHook: value.fromHook, details: bounded(value.details), + usage: bounded(value.usage), systemMessage: bounded(value.systemMessage), + })]; + if (value.type === "usage") return [make("usage", `Usage: ${clip(value.kind)}`, bounded(value.usage), { kind: clip(value.kind), provider: clip(value.provider), model: clip(value.model), usage: bounded(value.usage) })]; + const titles: Record = { model_change: "Model changed", thinking_level_change: "Thinking level changed", custom: "Custom entry", custom_message: "Custom message", label: "Entry label", session_info: "Session info", context_edit: "Context edited" }; + if (value.type !== "message") return [metadata(Object.hasOwn(titles, value.type) ? titles[value.type]! : `Unknown entry: ${clip(value.type)}`)]; + const role = message.role; + if (role === "user") return [make("user_message", "User", text(message.content))]; + if (role === "toolResult") return [make("tool_result", message.toolName ?? "Tool result", text(message.content), { + toolCallId: message.toolCallId, isError: message.isError, details: bounded(message.details), + usage: bounded(message.usage), nestedCalls: bounded(message.nestedCalls), + })]; + if (role === "bashExecution") return [make("command", message.command ?? "Command", message.output, { + exitCode: message.exitCode, cancelled: message.cancelled, truncated: message.truncated, + fullOutputPath: message.fullOutputPath ? clip(message.fullOutputPath) : undefined, excludeFromContext: message.excludeFromContext, + })]; + if (role === "branchSummary" || role === "compactionSummary") return [make(role === "branchSummary" ? "branch" : "compaction", role === "branchSummary" ? "Branch summary" : "Context compacted", message.summary, { fromId: message.fromId, tokensBefore: message.tokensBefore })]; + if (role !== "assistant") return [metadata(role === "system" ? "System prompt changed" : role === "custom" || role === "hookMessage" ? "Custom message" : `Unknown message role: ${clip(role)}`, message)]; + const entries: TraceEvent[] = []; + for (const [blockIndex, block] of (Array.isArray(message.content) ? message.content : []).entries()) { + const extra = { blockIndex, provider: clip(message.provider), model: clip(message.model), thinkingLevel: message.thinkingLevel, stopReason: message.stopReason }; + if (!object(block)) { entries.push(metadata("Invalid content block", block)); continue; } + if (block.type === "thinking") entries.push(make("reasoning", "Reasoning", block.redacted ? "[Redacted thinking]" : block.thinking, { ...extra, redacted: block.redacted })); + else if (block.type === "toolCall") entries.push(make("tool_call", block.name ?? "Tool call", bounded(block.arguments ?? {}), { ...extra, toolCallId: block.id, namespace: block.namespace, arguments: bounded(block.arguments ?? {}) })); + else if (block.type === "text") entries.push(make("assistant_message", "Assistant", block.text, extra)); + else entries.push(make("metadata", `Unknown content block: ${clip(block.type)}`, bounded(block), { ...extra, metadata: bounded(block) })); + } + if (!entries.length) entries.push(make("assistant_message", "Assistant", text(message.content))); + if (message.usage) entries.push(make("usage", "Model usage", bounded(message.usage), { provider: clip(message.provider), model: clip(message.model), usage: bounded(message.usage) })); + if (message.errorMessage || ["error", "aborted"].includes(message.stopReason)) entries.push(make(message.stopReason === "error" ? "error" : "warning", "Assistant " + message.stopReason, message.errorMessage ?? message.stopReason)); + return entries.map((entry, index) => ({ ...entry, sequence: sequence + index })); +} diff --git a/packages/app/src/trace.ts b/packages/app/src/trace.ts index a9b4977d..ef4d85da 100644 --- a/packages/app/src/trace.ts +++ b/packages/app/src/trace.ts @@ -1,3 +1,4 @@ +import { parsePi } from "./pi-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"; @@ -26,27 +27,6 @@ function event(sequence: number, type: TraceEventType, title: string, preview: u return { sequence, id: String(source.id ?? source.uuid ?? `${sequence}`), ...(source.parentId || source.parentUuid ? { parentId: String(source.parentId ?? source.parentUuid) } : {}), type, ...(source.role ? { role: String(source.role) } : {}), title, preview: clipped(preview), ...(source.timestamp ? { occurredAt: String(source.timestamp) } : {}), display: {} }; } -function parsePi(value: any, sequence: number): TraceEvent[] { - if (value.type === "session") return [event(sequence, "metadata", "Session started", value.cwd ?? "", value)]; - if (value.type === "compaction") return [event(sequence, "compaction", "Context compacted", value.summary, value)]; - if (value.type === "branch_summary") return [event(sequence, "branch", "Branch summary", value.summary, value)]; - if (value.type !== "message") return [event(sequence, "metadata", String(value.type ?? "Event"), value, value)]; - const message = value.message ?? {}, role = message.role; - if (role === "user") return [event(sequence, "user_message", "User", contentText(message.content), { ...value, role })]; - if (role === "toolResult") return [event(sequence, "tool_result", String(message.toolName ?? "Tool result"), contentText(message.content), { ...value, role })]; - if (role === "bashExecution") return [event(sequence, "command", String(message.command ?? "Command"), message.output, { ...value, role })]; - if (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, role })); - else if (block.type === "toolCall") entries.push({ ...event(sequence + entries.length, "tool_call", String(block.name ?? "Tool call"), block.arguments, { ...value, id: block.id, role }), display: { arguments: block.arguments ?? {} } }); - else if (block.type === "text") entries.push(event(sequence + entries.length, "assistant_message", "Assistant", block.text, { ...value, role })); - } - return entries.length ? entries : [event(sequence, "assistant_message", "Assistant", contentText(message.content), { ...value, role })]; - } - return [event(sequence, "metadata", String(role ?? "Message"), message.content, { ...value, role })]; -} - function parseCodex(value: any, sequence: number): TraceEvent[] { const payload = value.payload ?? {}; if (value.type === "session_meta") return [event(sequence, "metadata", "Session started", payload.cwd ?? "", { ...value, id: payload.id ?? payload.session_id })]; diff --git a/packages/app/test/fixtures/pi/1.1.0/README.md b/packages/app/test/fixtures/pi/1.1.0/README.md new file mode 100644 index 00000000..35b6ff55 --- /dev/null +++ b/packages/app/test/fixtures/pi/1.1.0/README.md @@ -0,0 +1,18 @@ +These fixtures target the deployed **@earendil-works/pi-coding-agent 1.1.0**, +session JSONL **v3**. + +- `documented-v3.jsonl` is a representative contract fixture covering every + published entry type, multi-tool assistant blocks, image omission, usage, + prompt patches, compaction checkpoints, and sibling branches. It includes a + future entry to exercise forward-compatible metadata. +- `native-session.jsonl` is unmodified session output captured from the exe.dev + Pi 1.1.0 binary. The only model is a local deterministic OpenAI-compatible + fixture server; Pi itself serializes the session, invokes bash, and stores its + result. No external credentials or existing sessions are used. +- `python3 capture.py` regenerates the actual-output fixture using the documented + compatible-endpoint configuration. IDs, timestamps, and temporary paths vary. + +Compatibility references shipped with that release: +[session format](https://github.com/earendil-works/pi/blob/v1.1.0/packages/coding-agent/docs/session-format.md) +and [message types](https://github.com/earendil-works/pi/blob/v1.1.0/packages/coding-agent/docs/message-types.md). +The installed release copies were used when creating the fixtures. diff --git a/packages/app/test/fixtures/pi/1.1.0/capture.py b/packages/app/test/fixtures/pi/1.1.0/capture.py new file mode 100644 index 00000000..44e6efaf --- /dev/null +++ b/packages/app/test/fixtures/pi/1.1.0/capture.py @@ -0,0 +1,27 @@ +"""Capture native JSONL from Pi 1.1.0 using a local, deterministic model. +Run with python3 capture.py. No external model service or credentials are used. +""" +import json, os, pathlib, subprocess, tempfile, threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +assert subprocess.check_output(["pi", "--version"], text=True).strip() == "1.1.0" +class Model(BaseHTTPRequestHandler): + def log_message(self, *args): pass + def do_POST(self): + request = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + done = any(m["role"] == "tool" for m in request["messages"]) + delta = {"content": "Captured tool result."} if done else {"tool_calls": [{"index": 0, "id": "fixture-call", "type": "function", "function": {"name": "bash", "arguments": '{"command":"printf fixture-output"}'}}]} + chunks = [{"id": "fixture-response", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}, + {"id": "fixture-response", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop" if done else "tool_calls"}], "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}] + body = "".join("data: " + json.dumps(c) + "\n\n" for c in chunks) + "data: [DONE]\n\n" + self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.end_headers(); self.wfile.write(body.encode()) +server = HTTPServer(("127.0.0.1", 0), Model) +threading.Thread(target=server.serve_forever, daemon=True).start() +with tempfile.TemporaryDirectory(prefix="factorize-pi-fixture-") as root: + config = pathlib.Path(root, "config"); config.mkdir() + (config / "models.json").write_text(json.dumps({"providers": {"fixture": {"baseUrl": f"http://127.0.0.1:{server.server_port}/v1", "api": "openai-completions", "apiKey": "local-fixture", "models": [{"id": "mock", "reasoning": False, "input": ["text"], "contextWindow": 128000, "maxTokens": 1024}]}}})) + subprocess.run(["pi", "--offline", "--no-extensions", "--no-mcp", "--no-skills", "--no-prompt-templates", "--no-context-files", "--no-approve", "--model", "fixture/mock", "--tools", "bash", "--session-id", "factorize-fixture", "--session-dir", root + "/sessions", "-p", "Run printf fixture-output using bash, then report completion."], cwd=root, env={**os.environ, "PI_CODING_AGENT_DIR": str(config), "PI_TELEMETRY": "0"}, check=True, stdout=subprocess.DEVNULL, timeout=60) + files = list(pathlib.Path(root, "sessions").glob("*.jsonl")) + assert len(files) == 1 + pathlib.Path(__file__).with_name("native-session.jsonl").write_bytes(files[0].read_bytes()) +server.shutdown() diff --git a/packages/app/test/fixtures/pi/1.1.0/documented-v3.jsonl b/packages/app/test/fixtures/pi/1.1.0/documented-v3.jsonl new file mode 100644 index 00000000..ebd79fad --- /dev/null +++ b/packages/app/test/fixtures/pi/1.1.0/documented-v3.jsonl @@ -0,0 +1,17 @@ +{"type": "session", "version": 3, "id": "documented-v3", "cwd": "/repo", "parentSession": "/repo/parent.jsonl", "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "model_change", "id": "model", "parentId": null, "provider": "openai", "modelId": "mock", "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "thinking_level_change", "id": "thinking", "parentId": "model", "thinkingLevel": "high", "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "message", "id": "system", "parentId": "thinking", "message": {"role": "system", "content": "", "sections": {"preamble": "Instructions", "skills": null}, "toolsAdded": [{"name": "read", "parameters": {}}], "toolsRemoved": [{"name": "write"}], "timestamp": 1733234400000}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "message", "id": "user", "parentId": "system", "message": {"role": "user", "content": [{"type": "text", "text": "Inspect"}, {"type": "image", "mimeType": "image/png", "data": "BINARY_MUST_NOT_PROJECT"}]}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "message", "id": "assistant", "parentId": "user", "message": {"role": "assistant", "content": [{"type": "thinking", "thinking": "Inspect first", "thinkingSignature": "OPAQUE_MUST_NOT_PROJECT"}, {"type": "toolCall", "id": "call-1", "name": "read", "arguments": {"path": "a.ts"}}, {"type": "toolCall", "id": "call-2", "name": "bash", "arguments": {"command": "pwd"}}, {"type": "text", "text": "Working"}], "provider": "openai", "model": "mock", "thinkingLevel": "high", "usage": {"input": 10, "output": 5, "cacheRead": 2, "cacheWrite": 3, "totalTokens": 20, "cost": {"total": 0.01}}, "stopReason": "toolUse", "timestamp": 1733234401000}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "message", "id": "result", "parentId": "assistant", "message": {"role": "toolResult", "toolCallId": "call-1", "toolName": "read", "content": [{"type": "text", "text": "file contents"}, {"type": "image", "mimeType": "image/png", "data": "BINARY_MUST_NOT_PROJECT"}], "details": {"path": "a.ts"}, "isError": false}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "message", "id": "bash", "parentId": "result", "message": {"role": "bashExecution", "command": "pwd", "output": "/repo", "exitCode": 0, "cancelled": false, "truncated": true, "fullOutputPath": "/tmp/output", "excludeFromContext": true}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "compaction", "id": "compact", "parentId": "bash", "summary": "Earlier work", "firstKeptEntryId": "result", "tokensBefore": 50000, "fromHook": true, "details": {"readFiles": ["a.ts"]}, "systemMessage": {"role": "system", "content": "Checkpoint"}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "branch_summary", "id": "branch", "parentId": "user", "fromId": "compact", "summary": "Abandoned path", "usage": {"totalTokens": 10}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "custom", "id": "custom", "parentId": "branch", "customType": "extension", "data": {"count": 42}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "custom_message", "id": "custom-msg", "parentId": "custom", "customType": "extension", "content": "Context", "display": false, "details": {"source": "extension"}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "label", "id": "label", "parentId": "custom-msg", "targetId": "user", "label": "checkpoint", "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "session_info", "id": "info", "parentId": "label", "name": "Example", "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "usage", "id": "usage", "parentId": "info", "kind": "future-operation", "provider": "openai", "model": "mock", "usage": {"totalTokens": 50}, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "context_edit", "id": "edit", "parentId": "usage", "targetId": "result", "replacement": null, "timestamp": "2024-12-03T14:00:00.000Z"} +{"type": "future_type", "id": "future", "parentId": "edit", "data": {"unknown": "retained"}, "timestamp": "2024-12-03T14:00:00.000Z"} diff --git a/packages/app/test/fixtures/pi/1.1.0/native-session.jsonl b/packages/app/test/fixtures/pi/1.1.0/native-session.jsonl new file mode 100644 index 00000000..e3c0f6aa --- /dev/null +++ b/packages/app/test/fixtures/pi/1.1.0/native-session.jsonl @@ -0,0 +1,8 @@ +{"type":"session","version":3,"id":"factorize-fixture","timestamp":"2026-10-09T00:36:55.655Z","cwd":"/tmp/factorize-pi-fixture-7xmp9j4u"} +{"type":"model_change","id":"ef0a25bc","parentId":null,"timestamp":"2026-10-09T00:36:55.706Z","provider":"fixture","modelId":"mock"} +{"type":"thinking_level_change","id":"30ab8b49","parentId":"ef0a25bc","timestamp":"2026-10-09T00:36:55.706Z","thinkingLevel":"off"} +{"type":"message","id":"0ed5ae3a","parentId":"30ab8b49","timestamp":"2026-10-09T00:36:55.717Z","message":{"role":"system","content":"","sections":{"preamble":"You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.","tools":"\n- bash: Execute bash commands (ls, grep, find, etc.)\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n","rules":"\n- Use bash for file operations like ls, rg, find\n- You can inspect PI_* environment variables for current model and session details.\n- Be concise in your responses\n- Show file paths clearly when working with files\n","docs":"\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: /home/exedev/.local/pi/README.md\n- Additional docs: /home/exedev/.local/pi/docs\n- Examples: /home/exedev/.local/pi/examples (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)\n","cwd":"\n/tmp/factorize-pi-fixture-7xmp9j4u\n"},"timestamp":1791506215715,"toolsAdded":[{"name":"bash","description":"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.","parameters":{"type":"object","required":["command"],"properties":{"command":{"type":"string","description":"Shell command to execute"},"timeout":{"type":"number","description":"Timeout in seconds (optional, no default timeout)"}}},"constrainedSampling":{"type":"json_schema","strict":"prefer"}}]}} +{"type":"message","id":"46405d1a","parentId":"0ed5ae3a","timestamp":"2026-10-09T00:36:55.717Z","message":{"role":"user","content":[{"type":"text","text":"Run printf fixture-output using bash, then report completion."}],"timestamp":1791506215714}} +{"type":"message","id":"7ce0a9bf","parentId":"46405d1a","timestamp":"2026-10-09T00:36:55.749Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"fixture-call","name":"bash","arguments":{"command":"printf fixture-output"}}],"api":"openai-completions","provider":"fixture","model":"mock","usage":{"input":10,"output":5,"cacheRead":0,"cacheWrite":0,"reasoning":0,"totalTokens":15,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"toolUse","timestamp":1791506215729,"responseId":"fixture-response","rawStopReason":"tool_calls","durationMs":20,"thinkingLevel":"off"}} +{"type":"message","id":"b9cbcf3a","parentId":"7ce0a9bf","timestamp":"2026-10-09T00:36:55.756Z","message":{"role":"toolResult","toolCallId":"fixture-call","toolName":"bash","content":[{"type":"text","text":"fixture-output"}],"isError":false,"durationMs":5,"timestamp":1791506215756}} +{"type":"message","id":"e913019d","parentId":"b9cbcf3a","timestamp":"2026-10-09T00:36:55.763Z","message":{"role":"assistant","content":[{"type":"text","text":"Captured tool result."}],"api":"openai-completions","provider":"fixture","model":"mock","usage":{"input":10,"output":5,"cacheRead":0,"cacheWrite":0,"reasoning":0,"totalTokens":15,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1791506215758,"responseId":"fixture-response","rawStopReason":"stop","durationMs":5,"thinkingLevel":"off"}} diff --git a/packages/app/test/pi-trace.test.ts b/packages/app/test/pi-trace.test.ts new file mode 100644 index 00000000..77c25576 --- /dev/null +++ b/packages/app/test/pi-trace.test.ts @@ -0,0 +1,89 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { consumeTraceStream, parseTrace } from "../src/trace"; +import { agentDriver } from "../src/agent-driver"; + +const fixture = (name: string) => readFileSync(new URL(`./fixtures/pi/1.1.0/${name}.jsonl`, import.meta.url), "utf8"); + +describe("Pi 1.1.0 / native session v3", () => { + it("pins the runtime and declares the native artifact with version provenance", () => { + const launch = agentDriver("pi").launch("run", {}); + expect(launch.executable).toBe("/bin/sh"); + expect(launch.args[1]).toContain('test "$(pi --version)" = "1.1.0"'); + expect(launch.traceSources?.primary).toMatchObject({ kind: "native_session", provider: "pi", cliVersion: "1.1.0", formatVersion: "3" }); + }); + + it("preserves native entry provenance and links multiple calls and results", () => { + const events = parseTrace("pi", fixture("documented-v3")); + const calls = events.filter(e => e.type === "tool_call"); + expect(calls.map(e => e.display.toolCallId)).toEqual(["call-1", "call-2"]); + for (const call of calls) { + expect(call.id).toBe("assistant"); + expect(call.parentId).toBe("user"); + expect(call.occurredAt).toBe("2024-12-03T14:00:00.000Z"); + expect(call.display.entryId).toBe("assistant"); + expect(call.display.messageTimestamp).toBe(1733234401000); + } + expect(events.find(e => e.id === "result")).toMatchObject({ type: "tool_result", parentId: "assistant", display: { toolCallId: "call-1", isError: false } }); + expect(events.find(e => e.id === "model")?.display.parentId).toBeNull(); + expect(events.find(e => e.id === "bash")).toMatchObject({ type: "command", display: { exitCode: 0, truncated: true, excludeFromContext: true } }); + expect(events.find(e => e.type === "usage")?.display.usage).toMatchObject({ totalTokens: 20 }); + }); + + it("retains branches, compaction boundaries, prompt patches and custom/future metadata", () => { + const events = parseTrace("pi", fixture("documented-v3")); + expect(events.find(e => e.id === "compact")).toMatchObject({ type: "compaction", parentId: "bash", display: { firstKeptEntryId: "result", tokensBefore: 50000, systemMessage: { content: "Checkpoint" } } }); + expect(events.find(e => e.id === "branch")).toMatchObject({ type: "branch", parentId: "user", display: { fromId: "compact" } }); + for (const id of ["system", "custom", "custom-msg", "label", "info", "edit", "future"]) expect(events.find(e => e.id === id)?.type).toBe("metadata"); + expect(events.find(e => e.id === "system")?.display.metadata).toMatchObject({ sections: { skills: null }, toolsRemoved: [{ name: "write" }] }); + expect(events.find(e => e.id === "edit")?.display.metadata).toMatchObject({ targetId: "result", replacement: null }); + expect(events.find(e => e.id === "future")?.display.metadata).toMatchObject({ data: { unknown: "retained" } }); + expect(events.find(e => e.id === "usage")).toMatchObject({ type: "usage", display: { kind: "future-operation" } }); + expect(JSON.stringify(events)).not.toMatch(/BINARY_MUST_NOT_PROJECT|OPAQUE_MUST_NOT_PROJECT/); + }); + + it("projects actual deployed binary output and matches byte-stream parsing", async () => { + const jsonl = fixture("native-session"); + const events = parseTrace("pi", jsonl); + expect(events.find(e => e.type === "tool_call")).toMatchObject({ title: "bash", display: { toolCallId: "fixture-call", arguments: { command: "printf fixture-output" } } }); + expect(events.find(e => e.type === "tool_result")).toMatchObject({ preview: "fixture-output", display: { toolCallId: "fixture-call", isError: false } }); + expect(events.some(e => e.type === "usage")).toBe(true); + const bytes = new TextEncoder().encode(jsonl); + const stream = new ReadableStream({ start(controller) { for (let i = 0; i < bytes.length; i += 17) controller.enqueue(bytes.slice(i, i + 17)); controller.close(); } }); + const streamed: typeof events = []; + await consumeTraceStream("pi", stream, async batch => { streamed.push(...batch); }, 2); + expect(streamed).toEqual(events); + }); + + it("marks legacy sessions as unmigrated without inventing tree ancestry", () => { + for (const version of [undefined, 1, 2]) { + const events = parseTrace("pi", [ + { type: "session", id: "legacy", version }, + { type: "message", id: "legacy-entry", message: { role: "hookMessage", content: "legacy extension" } }, + ].map(record => JSON.stringify(record)).join("\n")); + expect(events[0]?.display).toMatchObject({ version: version ?? 1, compatibility: "best_effort_unmigrated" }); + expect(events[1]).toMatchObject({ id: "legacy-entry", type: "metadata", title: "Custom message" }); + expect(events[1]?.parentId).toBeUndefined(); + expect(events[1]?.display.parentId).toBeNull(); + } + }); + + it("bounds arguments/results and tolerates unknown blocks, roles and invalid values", () => { + const records = [ + null, [], { type: "constructor", id: "prototype-name" }, { type: "session", version: 99, id: "future" }, + { type: "message", id: "a", timestamp: "invalid", message: { role: "assistant", content: [null, { type: "future-block", data: "x".repeat(100000) }, { type: "toolCall", id: "c", name: "tool", arguments: { large: "x".repeat(100000) } }, { type: "thinking", redacted: true, thinkingSignature: "opaque" }], stopReason: "error", errorMessage: "failure" } }, + { type: "message", id: "r", message: { role: "toolResult", toolCallId: "c", content: [{ type: "text", text: "x".repeat(100000) }], isError: true, details: { large: "x".repeat(100000) } } }, + { type: "message", message: { role: "future-role", content: "safe" } }, + { type: "message", message: { role: "hookMessage", content: "legacy" } }, + ]; + const events = parseTrace("pi", records.map(r => JSON.stringify(r)).join("\n")); + expect(events.find(e => e.id === "future")?.display.compatibility).toBe("best_effort_unmigrated"); + expect(events.every(e => e.preview.length < 33000)).toBe(true); + expect(JSON.stringify(events.find(e => e.type === "tool_call")?.display.arguments).length).toBeLessThan(34000); + expect(events.find(e => e.type === "tool_result")?.display.isError).toBe(true); + expect(events.find(e => e.type === "reasoning")?.preview).toBe("[Redacted thinking]"); + expect(events.find(e => e.id === "a")?.occurredAt).toBeUndefined(); + expect(events.some(e => e.type === "error")).toBe(true); + expect(events.at(-1)?.title).toBe("Custom message"); + }); +}); diff --git a/packages/app/test/postgres-live-trace-repository.test.ts b/packages/app/test/postgres-live-trace-repository.test.ts index 66c4327d..94d49885 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"; @@ -71,4 +72,27 @@ describe("LiveTraceRepository", () => { expect(fake.state().cursor.pending_bytes).toHaveLength(0); }); + it("preserves Pi native tree and tool links across chunk retries and reconciliation", async () => { + const text = readFileSync(new URL("./fixtures/pi/1.1.0/documented-v3.jsonl", import.meta.url), "utf8"); + const fake = fakeDatabase(), repository = new LiveTraceRepository(fake.database, "tenant-1"); + let offset = 0, previousHash = zero; + for (let index = 0; index < text.length; index += 317) { + const part = text.slice(index, index + 317), bytes = new TextEncoder().encode(part); + const chunk = { generation: "pi-native", expectedGeneration: offset ? "pi-native" : null, startOffset: offset, chunkSha256: await digest(part), previousHash, bytes }; + const receipt = await repository.append("run-1", "pi", chunk, "native_session"); + expect((await repository.append("run-1", "pi", chunk, "native_session")).duplicate).toBe(true); + offset = receipt.offset; previousHash = receipt.rollingHash; + } + const expected = parseTrace("pi", text); + const stored = fake.state().events; + expect(stored).toEqual(expected.map(e => ({ + sequence: e.sequence, id: e.id, parent_id: e.parentId ?? null, + event_type: e.type, role: e.role ?? null, title: e.title, + preview_text: e.preview, display_data: JSON.parse(JSON.stringify(e.display)), + occurred_at: e.occurredAt ?? null, + }))); + expect(stored.filter(e => e.event_type === "tool_call")).toHaveLength(2); + expect(stored.find(e => e.id === "branch").display_data.fromId).toBe("compact"); + }); + });