Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: new assistant option in the app

ogsamrat7b3400ed6a98
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.ts
index 841fe975..f822016f 100644
--- a/apps/app/src/app/lib/desktop.ts
+++ b/apps/app/src/app/lib/desktop.ts
@@ -536,6 +536,16 @@ export async function desktopDownloadBinary(
);
}
+export async function desktopDownloadClaudeArchive(input: {url: string; headers?: Record<string, string>}, signal?: AbortSignal) {
+ const transferId = desktopTransferId();
+ const payload = { ...input, transferId };
+ return runCancellableDesktopTransfer(
+ transferId,
+ signal,
+ () => invokeElectronHelper("__downloadClaudeArchive", payload),
+ );
+}
+
type DesktopFetchMainOptions = {
timeoutMs?: number;
agentContextDiagnosticsDeadlineAtMs?: number;
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index d98116dc..b2b2f4b9 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -17,7 +17,7 @@ import {
AGENT_CONTEXT_DIAGNOSTICS_REQUEST_TIMEOUT_MS,
requestAgentContextDiagnosticsPayload,
} from "./agent-context-diagnostics-transport";
-import { desktopFetch, desktopFetchAgentContextDiagnostics, desktopUploadMultipart, electronLocalPathForFile } from "./desktop";
+import { desktopFetch, desktopFetchAgentContextDiagnostics, desktopUploadMultipart, desktopDownloadClaudeArchive, electronLocalPathForFile } from "./desktop";
import { isOmniRushGatewayRuntime } from "./gateway-runtime";
import { isDesktopRuntime } from "./runtime-env";
import type { ExecResult, OpencodeConfigFile, WorkspaceInfo, WorkspaceList } from "./desktop";
@@ -1895,6 +1895,16 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
const token = options.token;
const hostToken = options.hostToken;
+ const claudeExportError = (status: number, text: string) => {
+ try {
+ const body: unknown = JSON.parse(text);
+ if (body && typeof body === "object" && "message" in body && typeof body.message === "string" && body.message.trim()) {
+ return new Error(body.message);
+ }
+ } catch { /* Non-JSON errors retain the HTTP status. */ }
+ return new Error(`Claude export failed (${status})`);
+ };
+
const timeouts = {
health: 3_000,
capabilities: 6_000,
@@ -1916,6 +1926,24 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
return {
baseUrl,
token,
+ claude: {
+ request: <T,>(workspaceId: string, route: string, body?: unknown, signal?: AbortSignal) => requestJson<T>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/claude/${route}`, {token, hostToken, method: body === undefined ? "GET" : "POST", body, signal, timeoutMs: 15 * 60_000}),
+ export: async (workspaceId: string, sessionId: string, signal?: AbortSignal) => {
+ const url = `${baseUrl}/workspace/${encodeURIComponent(workspaceId)}/claude/sessions/${encodeURIComponent(sessionId)}/export`;
+ const response = await resolveFetch(url)(url, {method: "POST", headers: buildHeaders(token, hostToken), signal});
+ if (!response.ok) throw claudeExportError(response.status, await response.text());
+ return response.blob();
+ },
+ saveExport: async (workspaceId: string, sessionId: string, signal?: AbortSignal) => {
+ const result = await desktopDownloadClaudeArchive({
+ url: `${baseUrl}/workspace/${encodeURIComponent(workspaceId)}/claude/sessions/${encodeURIComponent(sessionId)}/export`,
+ headers: buildHeaders(token, hostToken),
+ }, signal);
+ if (!result) return null;
+ if (result.status !== 200 || !result.path) throw claudeExportError(result.status, result.body ?? "");
+ return result.path;
+ },
+ },
health: () =>
requestJson<{ ok: boolean; version: string; uptimeMs: number }>(baseUrl, "/health", { token, hostToken, timeoutMs: timeouts.health }),
runtimeVersions: () =>
diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
index f947b329..da6523be 100644
--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
@@ -1,5 +1,6 @@
/** @jsxImportSource react */
import * as React from "react";
+import { Link } from "react-router";
import {
AlertCircle,
AlertTriangle,
@@ -55,6 +56,7 @@ import { buildathonProjects, useBuildathonStore } from "../../../../app/lib/buil
import { OmniRushDenHelpLink } from "../../workspace/omnirush-den-help-link";
import { NotificationBell } from "../../../shell/notification-center";
import { useUiStateStore } from "../../../shell/ui-state-store";
+import { useClaudeSurface } from "../../../shell/claude-offer";
import type {
WorkspaceConnectionState,
WorkspaceSessionGroup,
@@ -194,6 +196,17 @@ const SidebarReorderContext = React.createContext<{
setIsReordering: (value: boolean) => void;
} | null>(null);
+/** The workspace menu's Claude Code entry: only while the server offers it, or to reach sessions saved earlier (claude-offer.ts). */
+function ClaudeMenuItem({ workspaceId }: { workspaceId: string }) {
+ const surface = useClaudeSurface(workspaceId);
+ if (surface !== "full" && surface !== "saved") return null;
+ return (
+ <DropdownMenuItem render={<Link to={`/workspace/${workspaceId}/claude`} />}>
+ <Sparkles className="size-4" />{surface === "full" ? "Claude Code" : "Saved sessions"}
+ </DropdownMenuItem>
+ );
+}
+
function SidebarReorderScope({ children }: { children: React.ReactNode }) {
const [isReordering, setIsReordering] = React.useState(false);
@@ -724,6 +737,7 @@ function WorkspaceActionsMenu({ workspace, isConnectionActionBusy, canRecover, c
}
/>
<DropdownMenuContent align="end" side="bottom" sideOffset={4} className="w-56">
+ <ClaudeMenuItem workspaceId={workspace.id} />
<DropdownMenuItem onClick={() => ctx.onOpenRenameWorkspace(workspace.id)}>
<Pencil className="size-4" />
{t("workspace_list.edit_name")}
diff --git a/apps/app/src/react-app/shell/app-root.tsx b/apps/app/src/react-app/shell/app-root.tsx
index 2d3a67d9..74537e5a 100644
--- a/apps/app/src/react-app/shell/app-root.tsx
+++ b/apps/app/src/react-app/shell/app-root.tsx
@@ -46,6 +46,7 @@ import {
} from "./control/control-provider";
import { OmniRushContextPublisher } from "./omnirush-context-publisher";
import { SessionRoute } from "./session-route";
+import { ClaudeRoute } from "./claude-route";
import { DesktopUpdaterProvider } from "../domains/settings/state/desktop-updater-provider";
import { SyncRestartGate } from "./sync-restart-banner";
import { UpdateGate } from "./update-gate";
@@ -407,6 +408,7 @@ export function AppRoot() {
<CloudWorkspaceStatusProvider>
<ComputerUseControls />
<Routes>
+ <Route path="/workspace/:workspaceId/claude" element={<ClaudeRoute />} />
<Route
path="/signin"
element={
diff --git a/apps/app/src/react-app/shell/claude-offer.ts b/apps/app/src/react-app/shell/claude-offer.ts
new file mode 100644
index 00000000..01398433
--- /dev/null
+++ b/apps/app/src/react-app/shell/claude-offer.ts
@@ -0,0 +1,96 @@
+// What the app shows of Claude Code for a workspace. While the server does not offer it to this account (status
+// `allowed` false: today's servers, the switch off) nothing advertises it: no menu entry, no Claude page. Sessions
+// saved earlier stay reachable for export and recovery, under a plain "saved sessions" view.
+import { useEffect, useState } from "react";
+
+import { createOmniRushServerClient } from "@/app/lib/omnirush-server";
+import { workspaceBootstrap } from "@/app/lib/desktop";
+import { isDesktopRuntime } from "@/app/lib/runtime-env";
+import { resolveWorkspaceEndpoint, type ResolvedWorkspaceEndpoint } from "@/app/lib/workspace-endpoint";
+import { resolveOmniRushConnection } from "./omnirush-connection";
+
+/** full: offered (new sessions); saved: not offered, saved sessions to export; none: nothing to show. */
+export type ClaudeSurface = "full" | "saved" | "none";
+
+export function claudeSurface(allowed: boolean, savedSessions: number): ClaudeSurface {
+ if (allowed) return "full";
+ return savedSessions > 0 ? "saved" : "none";
+}
+
+/** The workspace's server endpoint (the local server on the desktop). */
+export async function claudeEndpoint(workspaceId: string | undefined, signal?: AbortSignal): Promise<ResolvedWorkspaceEndpoint> {
+ const {normalizedBaseUrl: baseUrl, resolvedToken: token, resolvedHostToken: hostToken} = await resolveOmniRushConnection();
+ signal?.throwIfAborted();
+ if (!baseUrl) throw new Error("Connect to a workspace server first");
+ const local = { baseUrl, token, hostToken };
+ const localClient = createOmniRushServerClient(local);
+ const workspaces = (await localClient.listWorkspaces()).items;
+ signal?.throwIfAborted();
+ const workspace = workspaces.find((item) => item.id === workspaceId)
+ ?? (isDesktopRuntime() ? (await workspaceBootstrap()).workspaces.find((item) => item.id === workspaceId) : undefined);
+ signal?.throwIfAborted();
+ if (!workspace) throw new Error("Workspace not found");
+ const next = resolveWorkspaceEndpoint(workspace, local);
+ if (!next) throw new Error("Workspace server is unavailable");
+ // Host authority stays on the local server; the shared resolver supplies
+ // the owning remote workspace's own URL and credentials.
+ return {...next, client: next.isRemote ? next.client : localClient};
+}
+
+type ClaudeConnection = {
+ endpoint: (ResolvedWorkspaceEndpoint & {signal: AbortSignal}) | null;
+ pending: boolean;
+ error: string | null;
+};
+
+/** Shared route/menu lifetime: settings publication supersedes old requests. */
+export function useClaudeEndpoint(workspaceId: string | undefined): ClaudeConnection {
+ const [connection, setConnection] = useState<ClaudeConnection>({endpoint: null, pending: true, error: null});
+ useEffect(() => {
+ let controller: AbortController;
+ const connect = () => {
+ controller?.abort();
+ controller = new AbortController();
+ const {signal} = controller;
+ setConnection({endpoint: null, pending: true, error: null});
+ void claudeEndpoint(workspaceId, signal).then(endpoint => {
+ if (!signal.aborted) setConnection({endpoint: {...endpoint, signal}, pending: false, error: null});
+ }, error => {
+ if (!signal.aborted) setConnection({endpoint: null, pending: false, error: error instanceof Error ? error.message : "Workspace server is unavailable"});
+ });
+ };
+ const onStorage = (event: StorageEvent) => { if (!event.key || event.key.startsWith("omnirush.server.")) connect(); };
+ const onVisible = () => { if (document.visibilityState === "visible") connect(); };
+ connect();
+ window.addEventListener("omnirush-server-settings-changed", connect);
+ window.addEventListener("storage", onStorage);
+ document.addEventListener("visibilitychange", onVisible);
+ return () => {
+ controller.abort();
+ window.removeEventListener("omnirush-server-settings-changed", connect);
+ window.removeEventListener("storage", onStorage);
+ document.removeEventListener("visibilitychange", onVisible);
+ };
+ }, [workspaceId]);
+ return connection;
+}
+
+/** Null until known; a failed or interrupted connection never advertises Claude. */
+export function useClaudeSurface(workspaceId: string | undefined): ClaudeSurface | null {
+ const {endpoint, pending} = useClaudeEndpoint(workspaceId);
+ const [surface, setSurface] = useState<ClaudeSurface | null>(null);
+ useEffect(() => {
+ setSurface(null);
+ if (!endpoint) return;
+ let closed = false;
+ void (async () => {
+ const [status, sessions] = await Promise.all([
+ endpoint.client.claude.request<{ allowed: boolean }>(endpoint.workspaceId, "status", undefined, endpoint.signal),
+ endpoint.client.claude.request<unknown[]>(endpoint.workspaceId, "sessions", undefined, endpoint.signal),
+ ]);
+ return claudeSurface(status?.allowed === true, Array.isArray(sessions) ? sessions.length : 0);
+ })().then((next) => { if (!closed && !endpoint.signal.aborted) setSurface(next); }, () => { if (!closed && !endpoint.signal.aborted) setSurface("none"); });
+ return () => { closed = true; };
+ }, [endpoint]);
+ return pending ? null : endpoint ? surface : "none";
+}
diff --git a/apps/app/src/react-app/shell/claude-route.tsx b/apps/app/src/react-app/shell/claude-route.tsx
new file mode 100644
index 00000000..845cc0dc
--- /dev/null
+++ b/apps/app/src/react-app/shell/claude-route.tsx
@@ -0,0 +1,162 @@
+import { useCallback, useEffect, useState } from "react";
+import { Link, useParams } from "react-router";
+import { Button } from "@/components/ui/button";
+import { isDesktopRuntime } from "@/app/lib/runtime-env";
+import { useBootState } from "./boot-state";
+import { claudeSurface, useClaudeEndpoint } from "./claude-offer";
+
+type Session = {
+ id: string; createdAt: string; model: string; capture: string; replay: string; issues: string[];
+ turns: Array<{number: number; status: string; error?: string}>;
+ compatibility?: "current" | "legacy_unverified" | "contract_invalid" | "runtime_upgrade_required";
+ contract?: {execution: {os: string; architecture: string}};
+ modelIsolation?: {status: "pending" | "observed" | "unknown" | "invalid" | "legacy_unverified"};
+ authorization?: {budget: {status: "known" | "unknown"; asOf?: string; remainingTokens?: number | null; sessionRemainingTokens?: number | null; accountRemainingTokens?: number; accountScope?: string} | null};
+};
+type Event = {type: string; text: string; turn: number};
+export function ClaudeRoute() {
+ const {workspaceId} = useParams();
+ return <WorkspaceClaudeRoute key={workspaceId} workspaceId={workspaceId} />;
+}
+function WorkspaceClaudeRoute({workspaceId}: {workspaceId: string | undefined}) {
+ const {markRouteReady} = useBootState();
+ const {endpoint, pending: connecting} = useClaudeEndpoint(workspaceId);
+ const [downloadController, setDownloadController] = useState<AbortController | null>(null);
+ const [allowed, setAllowed] = useState(false), [ready, setReady] = useState(false), [loaded, setLoaded] = useState(false);
+ const [sessions, setSessions] = useState<Session[]>([]), [selected, setSelected] = useState<string>();
+ const [session, setSession] = useState<Session>(), [events, setEvents] = useState<Event[]>([]);
+ const [prompt, setPrompt] = useState(""), [command, setCommand] = useState("");
+ const [consent, setConsent] = useState(false), [busy, setBusy] = useState(false);
+ const [error, setError] = useState(""), [notice, setNotice] = useState("");
+ const request = useCallback(async <T,>(route: string, body?: unknown): Promise<T> => {
+ if (!endpoint) throw new Error("Workspace server is unavailable");
+ endpoint.signal.throwIfAborted();
+ const result = await endpoint.client.claude.request<T>(endpoint.workspaceId, route, body, endpoint.signal);
+ endpoint.signal.throwIfAborted();
+ return result;
+ }, [endpoint]);
+ useEffect(() => {
+ if (!connecting) markRouteReady();
+ }, [connecting, markRouteReady]);
+ const refresh = useCallback(async () => {
+ const [status, items] = await Promise.all([
+ request<{allowed: boolean; sandboxReady: boolean}>("status"),
+ request<Session[]>("sessions"),
+ ]);
+ setAllowed(status.allowed); setReady(status.sandboxReady);
+ setSessions(items); setLoaded(true);
+ }, [request]);
+ useEffect(() => {
+ setLoaded(false); setAllowed(false); setReady(false);
+ if (endpoint) void refresh().catch(e => {
+ if (!endpoint.signal.aborted) { setError(e.message); setSessions([]); setLoaded(true); }
+ });
+ }, [endpoint, refresh]);
+ useEffect(() => {
+ if (!selected) { setSession(undefined); setEvents([]); return; }
+ if (!endpoint) return;
+ let closed = false, timer: ReturnType<typeof setTimeout>;
+ const poll = async () => {
+ try {
+ const [next, items] = await Promise.all([request<Session>(`sessions/${selected}`), request<Event[]>(`sessions/${selected}/events`)]);
+ if (!closed && !endpoint.signal.aborted) { setSession(next); setEvents(items); }
+ } catch (e) { if (!closed && !endpoint.signal.aborted) { setSession(undefined); setEvents([]); setError(e instanceof Error ? e.message : "Session unavailable"); } }
+ if (!closed && !endpoint.signal.aborted) timer = setTimeout(poll, 1500);
+ };
+ void poll(); return () => { closed = true; clearTimeout(timer); };
+ }, [selected, request, endpoint]);
+ const act = async (work: () => Promise<void>) => { setBusy(true); setError(""); setNotice(""); try { await work(); } catch (e) { if (!endpoint?.signal.aborted) setError(e instanceof Error ? e.message : "Operation failed"); } finally { setBusy(false); } };
+ // A persisted unfinished turn does not prove a process is alive. Export
+ // asks the server to check ownership of the saved evidence.
+ const unfinishedTurn = session?.turns.at(-1)?.status === "running";
+ const continuationIssue = session?.modelIsolation?.status === "unknown"
+ ? "This session is missing provider model identity evidence. Keep its evidence and start a new session."
+ : session?.modelIsolation?.status === "invalid" || session?.compatibility === "contract_invalid"
+ ? "This session’s model or environment contract changed. Keep its evidence and start a new session."
+ : session?.compatibility === "runtime_upgrade_required"
+ ? "This session needs its recorded runtime version. Export its evidence or start a new session."
+ : session?.compatibility === "legacy_unverified"
+ ? "This older session can be exported. Start a new session to continue with a fixed model."
+ : undefined;
+ const budget = session?.authorization?.budget;
+ const remaining = (tokens: number | null | undefined) => tokens === null ? "no limit" : typeof tokens === "number" ? `${tokens.toLocaleString()} tokens` : "unknown";
+ const download = async () => {
+ if (!endpoint || !session) return;
+ const controller = new AbortController();
+ const signal = AbortSignal.any([endpoint.signal, controller.signal]);
+ setDownloadController(controller);
+ const filename = `claude-${session.id}.zip`;
+ try {
+ if (isDesktopRuntime()) {
+ if (!await endpoint.client.claude.saveExport(endpoint.workspaceId, session.id, signal)) return;
+ } else {
+ const blob = await endpoint.client.claude.export(endpoint.workspaceId, session.id, signal);
+ signal.throwIfAborted();
+ const url = URL.createObjectURL(blob), link = document.createElement("a");
+ link.href = url; link.download = filename; link.click(); setTimeout(() => URL.revokeObjectURL(url), 60_000);
+ }
+ signal.throwIfAborted();
+ setNotice("Private session ZIP downloaded.");
+ } catch (e) {
+ if (!signal.aborted) throw e;
+ if (!endpoint.signal.aborted) setNotice("Download cancelled.");
+ } finally { setDownloadController(null); }
+ };
+ const surface = endpoint ? claudeSurface(allowed, sessions.length) : "none";
+ if (connecting || endpoint && !loaded) return <main className="mx-auto h-full max-w-5xl p-6" aria-busy="true" />;
+ if (surface === "none") {
+ return <main className="mx-auto h-full max-w-5xl space-y-4 p-6" data-testid="claude-unavailable">
+ <p>This page is not available.</p><Link to={`/workspace/${workspaceId}/session`}>Back to chats</Link>
+ </main>;
+ }
+ return <main className="mx-auto h-full max-w-5xl space-y-4 overflow-auto p-6" aria-label={surface === "full" ? "Claude Code workspace" : "Saved sessions"}>
+ <header className="flex items-center justify-between">{surface === "full"
+ ? <div><h1 className="text-xl font-semibold">Claude Code</h1><p className="text-sm text-muted-foreground">Opus 5.5 · Private sandbox sessions</p></div>
+ : <div><h1 className="text-xl font-semibold">Saved sessions</h1><p className="text-sm text-muted-foreground">Export or recover the sessions saved here.</p></div>}<Link to={`/workspace/${workspaceId}/session`}>Back to chats</Link></header>
+ {error && <p role="alert" className="rounded border border-destructive p-3">{error}</p>}
+ {notice && <p role="status" data-testid="claude-notice" className="sticky top-0 z-10 rounded border bg-background p-3">{notice}</p>}
+ <>
+ {allowed && !ready && <p>Start Docker Desktop or Docker Engine, then <button onClick={() => void act(refresh)}>check again</button>.</p>}
+ <section className="flex flex-wrap items-center gap-3 rounded border p-3" aria-label="Session controls">
+ <select aria-label="Claude session" value={selected ?? ""} onChange={e => { setSession(undefined); setEvents([]); setSelected(e.target.value || undefined); }} className="max-w-64 rounded border bg-background p-2"><option value="">Choose a session</option>{sessions.map(item => <option key={item.id} value={item.id}>{new Date(item.createdAt).toLocaleString()} · {item.id.slice(0,8)}</option>)}</select>
+ {surface === "full" && <><label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={consent} onChange={e => setConsent(e.target.checked)} />Retain private traces and full project snapshots</label>
+ <Button disabled={!allowed || !ready || busy || !consent} onClick={() => void act(async () => { setNotice("Preparing the sandbox and copying your project. The first setup may take several minutes."); const created = await request<Session>("sessions", {captureConsent: true}); await refresh(); setSelected(created.id); setNotice("Sandbox ready. Changes stay in this session’s project copy."); })}>New Claude session</Button></>}
+ </section>
+ {session && <>
+ <div className="space-y-1 text-sm" aria-label="Fixed session model">
+ <p><strong>{session.model}</strong> · {session.contract ? "Fixed for this session and its subagents" : "Legacy capture; model isolation unverified"}{session.contract && ` · ${session.contract.execution.os} / ${session.contract.execution.architecture}`}</p>
+ <p className="text-muted-foreground" aria-label="Model allowance">{budget?.status === "known"
+ ? `Allowance at last authorization${budget.asOf ? ` (${new Date(budget.asOf).toLocaleTimeString()})` : ""}: model ${remaining(budget.remainingTokens)} · Session: ${remaining(budget.sessionRemainingTokens)} · Account ${budget.accountScope ?? ""}: ${remaining(budget.accountRemainingTokens)}`
+ : "Model allowance has not been reported by the backend."}</p>
+ {session.modelIsolation?.status === "unknown" && <p role="status">The provider did not report a model identity for every request. This session needs review.</p>}
+ {continuationIssue && <p role="status">{continuationIssue}</p>}
+ </div>
+ <p className="text-sm" aria-label="Capture status">Capture: {session.capture} · Environment: {session.replay} · {session.turns.length} turns</p>
+ {session.issues.length > 0 && <p role="status">Evidence needs recovery: {session.issues.join(", ")}</p>}
+ <section aria-label="Claude conversation" className="min-h-52 space-y-3 rounded border p-4">
+ {events.length === 0 && <p className="text-muted-foreground">Describe what you want to build or fix.</p>}
+ {events.map((event, index) => event.type === "thinking" ? <details key={index}><summary>Reasoning summary</summary><p className="whitespace-pre-wrap">{event.text}</p></details> : <article key={index} className="whitespace-pre-wrap"><strong>{event.type === "user" ? "You" : event.type === "assistant" ? "Claude" : event.type === "tool" ? "Tool" : "Status"}</strong><p>{event.text}</p></article>)}
+ </section>
+ <form onSubmit={e => { e.preventDefault(); void act(async () => { await request(`sessions/${session.id}/turns`, {prompt}); setPrompt(""); setSession({...session, turns: [...session.turns, {number: session.turns.length + 1, status: "running"}]}); }); }} className="flex gap-2">
+ <textarea aria-label="Message Claude" value={prompt} onChange={e => setPrompt(e.target.value)} className="min-h-24 flex-1 rounded border bg-background p-3" placeholder="Describe the development task…" disabled={!endpoint || busy || unfinishedTurn || Boolean(continuationIssue)} />
+ <Button type="submit" disabled={!endpoint || busy || unfinishedTurn || Boolean(continuationIssue) || !prompt.trim()}>Send</Button>
+ {unfinishedTurn && <Button type="button" variant="outline" disabled={!endpoint || busy} onClick={() => void act(async () => { await request(`sessions/${session.id}/stop`, {}); })}>Stop</Button>}
+ </form>
+ <section className="flex flex-wrap items-center gap-2" aria-label="Evidence controls">
+ <input aria-label="Verification command" value={command} onChange={e => setCommand(e.target.value)} placeholder="Project test command (optional)" className="min-w-64 rounded border bg-background p-2" />
+ <Button variant="outline" disabled={!endpoint || busy || unfinishedTurn || !session.turns.length} onClick={() => void act(async () => { await request(`sessions/${session.id}/verify`, command.trim() ? {command} : {}); setNotice("Environment restored and verification passed with network access disabled."); })}>Verify restore</Button>
+ <Button variant="outline" disabled={!endpoint || busy || unfinishedTurn} onClick={() => void act(async () => { await request(`sessions/${session.id}/recover`, {}); setNotice("Recovery finished. Check capture status before exporting."); })}>Recover evidence</Button>
+ <Button variant="outline" disabled={!endpoint || busy || !session.turns.length} onClick={() => void act(download)}>Download private ZIP</Button>
+ {downloadController && <Button variant="outline" onClick={() => downloadController.abort()}>Cancel download</Button>}
+ <Button variant="outline" disabled={!endpoint || busy || unfinishedTurn || !session.turns.length} onClick={() => void act(async () => {
+ const result = await request<{status: string; native: {status: string}; checkpoint: {status: string}}>(`sessions/${session.id}/upload`, {});
+ setNotice(result.native.status === "uploaded" && result.checkpoint.status === "uploaded" ? "Private session uploaded. Backend receipts confirm the native traces and environment arrived."
+ : result.native.status === "uploaded" && result.checkpoint.status === "disabled" ? "Native traces uploaded. Environment upload is disabled by the backend; the complete ZIP remains on this device."
+ : "Upload is incomplete. Local evidence is retained; retry to resume.");
+ })}>Upload private session</Button>
+ </section>
+ <p className="text-xs text-muted-foreground">The ZIP includes native Claude Code transcripts, available reasoning summaries, tool and subagent activity, and complete environment snapshots. Restore verification checks the saved environment; generated answers may differ on a new run.</p>
+ </>}
+ </>
+ </main>;
+}
diff --git a/apps/app/tests/claude-offer.test.tsx b/apps/app/tests/claude-offer.test.tsx
new file mode 100644
index 00000000..95bbc07b
--- /dev/null
+++ b/apps/app/tests/claude-offer.test.tsx
@@ -0,0 +1,115 @@
+/** @jsxImportSource react */
+import { afterAll, describe, expect, mock, test } from "bun:test";
+import { GlobalRegistrator } from "@happy-dom/global-registrator";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { MemoryRouter, Route, Routes } from "react-router";
+
+const registered = typeof globalThis.document === "undefined";
+if (registered) GlobalRegistrator.register({ url: "http://localhost/" });
+afterAll(async () => { if (registered) await GlobalRegistrator.unregister(); });
+
+// The pure rule, without the module's app imports (they read window at load).
+const claudeSurface = (allowed: boolean, saved: number) => (allowed ? "full" : saved > 0 ? "saved" : "none");
+
+
+let status = { allowed: false, sandboxReady: true };
+let sessions: unknown[] = [];
+// Stable, as the real boot state is (a new function each render would re-run the route's effects forever).
+const bootState = { markRouteReady: () => {} };
+mock.module("../src/react-app/shell/boot-state", () => ({ useBootState: () => bootState }));
+const connection = {
+ pending: false,
+ endpoint: {
+ signal: new AbortController().signal,
+ workspaceId: "ws",
+ client: { claude: { request: async (_ws: string, route: string) => (route === "status" ? status : route === "sessions" ? sessions : []) } },
+ },
+};
+mock.module("../src/react-app/shell/claude-offer", () => ({
+ claudeSurface,
+ useClaudeEndpoint: () => connection,
+}));
+
+async function renderRoute(): Promise<string> {
+ const { ClaudeRoute } = await import("../src/react-app/shell/claude-route");
+ Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(<MemoryRouter initialEntries={["/workspace/ws/claude"]}><Routes><Route path="/workspace/:workspaceId/claude" element={<ClaudeRoute />} /></Routes></MemoryRouter>);
+ });
+ for (let i = 0; i < 50 && container.querySelector("[aria-busy]"); i++) await act(async () => { await new Promise((r) => setTimeout(r, 10)); });
+ const text = container.textContent ?? "";
+ await act(async () => root.unmount());
+ container.remove();
+ return text;
+}
+
+describe("the /claude route", () => {
+ const T = 60_000;
+ test("off and nothing saved: no Claude content, only 'not available'", async () => {
+ status = { allowed: false, sandboxReady: true }; sessions = [];
+ const text = await renderRoute();
+ expect(text).toContain("This page is not available.");
+ expect(text).not.toMatch(/claude|opus|pilot|selected accounts/i);
+ }, T);
+
+ test("off with a saved session: a plain saved-sessions view, no new-session control, no advertising", async () => {
+ status = { allowed: false, sandboxReady: true };
+ sessions = [{ id: "s1", createdAt: "2026-10-24T00:00:00Z", model: "m", capture: "ok", replay: "ok", issues: [], turns: [] }];
+ const text = await renderRoute();
+ expect(text).toContain("Saved sessions");
+ expect(text).not.toMatch(/New Claude session|selected accounts|Opus|pilot/i);
+ }, T);
+
+ test("on: the Claude Code page with its new-session control", async () => {
+ status = { allowed: true, sandboxReady: true }; sessions = [];
+ const text = await renderRoute();
+ expect(text).toContain("Claude Code");
+ expect(text).toContain("New Claude session");
+ }, T);
+});
+
+test("native Claude save sends host authority and aborts the same registered transfer", async () => {
+ const {createOmniRushServerClient} = await import("../src/app/lib/omnirush-server");
+ const controller = new AbortController();
+ const commands: Array<{command: string; input: unknown}> = [];
+ let refuseExport = false;
+ let rejectDownload: (error: Error) => void = () => { throw new Error("Download was not started"); };
+ const pending = new Promise((_resolve, reject) => { rejectDownload = reject; });
+ const previous = Object.getOwnPropertyDescriptor(window, "__OMNIRUSH_ELECTRON__");
+ Object.defineProperty(window, "__OMNIRUSH_ELECTRON__", {configurable: true, value: {
+ invokeDesktop(command: string, input: unknown) {
+ commands.push({command, input});
+ if (command === "__downloadClaudeArchive") return refuseExport
+ ? Promise.resolve({status: 409, statusText: "Conflict", headers: [], path: null, bytes: 0, body: JSON.stringify({message: "Another process is using this session or its operation owner is unknown"})})
+ : pending;
+ if (command === "__cancelTransfer") { rejectDownload(new DOMException("Cancelled", "AbortError")); return Promise.resolve(true); }
+ throw new Error(`Unexpected native operation: ${command}`);
+ },
+ }});
+ try {
+ const client = createOmniRushServerClient({baseUrl: "http://127.0.0.1:39876", token: "fixture-client", hostToken: "fixture-current-host"});
+ const downloading = client.claude.saveExport("ws", "00000000-0000-4000-8000-000000000001", controller.signal);
+ const outcome = downloading.then(() => "completed", error => error.name);
+ expect(commands).toHaveLength(1);
+ expect(commands[0]).toMatchObject({command: "__downloadClaudeArchive", input: {
+ transferId: expect.any(String), headers: {Authorization: "Bearer fixture-client", "X-OmniRush-Host-Token": "fixture-current-host"},
+ url: "http://127.0.0.1:39876/workspace/ws/claude/sessions/00000000-0000-4000-8000-000000000001/export",
+ }});
+ controller.abort();
+ expect(await outcome).toBe("AbortError");
+ expect(commands).toHaveLength(2);
+ expect(commands[1].command).toBe("__cancelTransfer");
+ expect(commands[0].input).toMatchObject({transferId: commands[1].input});
+ await expect(client.claude.saveExport("ws", "same-session", controller.signal)).rejects.toMatchObject({name: "AbortError"});
+ expect(commands).toHaveLength(2);
+ refuseExport = true;
+ await expect(client.claude.saveExport("ws", "locked-session")).rejects.toThrow("Another process is using this session or its operation owner is unknown");
+ } finally {
+ if (previous) Object.defineProperty(window, "__OMNIRUSH_ELECTRON__", previous);
+ else Reflect.deleteProperty(window, "__OMNIRUSH_ELECTRON__");
+ }
+}, 5000);
diff --git a/apps/app/tests/claude-surface.test.ts b/apps/app/tests/claude-surface.test.ts
new file mode 100644
index 00000000..f9b71816
--- /dev/null
+++ b/apps/app/tests/claude-surface.test.ts
@@ -0,0 +1,13 @@
+import { afterAll, expect, test } from "bun:test";
+import { GlobalRegistrator } from "@happy-dom/global-registrator";
+
+const registered = typeof globalThis.document === "undefined";
+if (registered) GlobalRegistrator.register({ url: "http://localhost/" });
+afterAll(async () => { if (registered) await GlobalRegistrator.unregister(); });
+
+test("claudeSurface: off with nothing saved shows nothing; off with saved sessions keeps them; on is the full page", async () => {
+ const { claudeSurface } = await import("../src/react-app/shell/claude-offer");
+ expect(claudeSurface(false, 0)).toBe("none");
+ expect(claudeSurface(false, 2)).toBe("saved");
+ expect(claudeSurface(true, 0)).toBe("full");
+});
diff --git a/apps/desktop/electron/binary-transfer.mjs b/apps/desktop/electron/binary-transfer.mjs
index 1c44502f..01a23420 100644
--- a/apps/desktop/electron/binary-transfer.mjs
+++ b/apps/desktop/electron/binary-transfer.mjs
@@ -39,13 +39,13 @@ function boundedRecord(value, label, maximumEntries) {
]));
}
-function boundedByteCount(value, label, { allowUndefined = false } = {}) {
+function boundedByteCount(value, label, { allowUndefined = false, maximum = DESKTOP_TRANSFER_MAX_BYTES } = {}) {
if (allowUndefined && value === undefined) return DESKTOP_TRANSFER_MAX_BYTES;
if (!Number.isSafeInteger(value)) throw transferError(`${label} must be an integer.`, "invalid-size");
if (value === 0) throw transferError(`${label} must be greater than zero.`, "zero-byte-file");
if (value < 0) throw transferError(`${label} must be greater than zero.`, "invalid-size");
- if (value > DESKTOP_TRANSFER_MAX_BYTES) {
- throw transferError(`${label} exceeds the ${DESKTOP_TRANSFER_MAX_BYTES}-byte limit.`, "file-too-large");
+ if (value > maximum) {
+ throw transferError(`${label} exceeds the ${maximum}-byte limit.`, "file-too-large");
}
return value;
}
@@ -63,7 +63,7 @@ function urlWithinPrefix(candidate, prefixValue) {
return !prefixPath || candidate.pathname === prefixPath || candidate.pathname.startsWith(`${prefixPath}/`);
}
-function remoteUrl(value, allowedUrlPrefixes) {
+function remoteUrl(value, allowedUrlPrefixes, allowLoopback = false) {
const raw = boundedString(value, "URL", { required: true, maxLength: 8_192 });
let parsed;
try {
@@ -74,7 +74,7 @@ function remoteUrl(value, allowedUrlPrefixes) {
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw transferError("URL must use HTTP or HTTPS.", "invalid-url");
}
- if (["127.0.0.1", "localhost", "[::1]"].includes(parsed.hostname)) {
+ if (!allowLoopback && ["127.0.0.1", "localhost", "[::1]"].includes(parsed.hostname)) {
throw transferError("Dedicated file transfers are only available for remote destinations.", "loopback-url");
}
// The renderer never gets to pick an arbitrary destination: the URL must sit
@@ -259,10 +259,10 @@ export async function uploadMultipartFromBytes(input, options) {
// through the verified handle, and never unlinked by path: failure cleanup
// truncates through the handle instead.
export async function downloadBinaryToPath(input, options) {
- const url = remoteUrl(input?.url, options?.allowedUrlPrefixes);
+ const url = remoteUrl(input?.url, options?.allowedUrlPrefixes, options?.allowLoopback === true);
const destination = await resolveAuthorizedPath(input?.destinationPath, options?.authorizedRoots);
const destinationPath = destination.path;
- const maxBytes = boundedByteCount(input?.maxBytes, "Maximum download size", { allowUndefined: true });
+ const maxBytes = boundedByteCount(input?.maxBytes, "Maximum download size", { allowUndefined: true, maximum: options?.downloadMaximum ?? DESKTOP_TRANSFER_MAX_BYTES });
const headers = boundedRecord(input?.headers, "Headers", MAX_HEADERS);
const method = boundedString(input?.method ?? "GET", "Method", { required: true, maxLength: 16 });
const signal = timeoutSignal(input?.timeoutMs, options?.signal);
@@ -273,7 +273,10 @@ export async function downloadBinaryToPath(input, options) {
let stagingPath;
let stagingFile;
let destinationFile;
+ let reader;
+ const cancelReader = () => { void reader?.cancel().catch(() => undefined); };
try {
+ signal?.throwIfAborted();
const response = await options.fetcher(url, {
method,
headers,
@@ -294,12 +297,14 @@ export async function downloadBinaryToPath(input, options) {
await mkdir(stagingDir, { recursive: true });
stagingPath = path.join(stagingDir, `download-${randomUUID()}.part`);
stagingFile = await open(stagingPath, "wx+");
- const reader = response.body?.getReader();
+ reader = response.body?.getReader();
+ signal?.addEventListener("abort", cancelReader, { once: true });
let bytes = 0;
if (reader) {
while (true) {
signal?.throwIfAborted();
const { done, value } = await reader.read();
+ signal?.throwIfAborted();
if (done) break;
bytes += value.byteLength;
if (bytes > maxBytes) {
@@ -310,6 +315,7 @@ export async function downloadBinaryToPath(input, options) {
}
}
if (bytes === 0) throw transferError("Download response was empty.", "zero-byte-file");
+ signal?.throwIfAborted();
// Only a complete download reaches the workspace. Revalidate the
// destination, create it exclusively ("wx" never follows a final
// symlink), and prove by device and inode that the created file resides
@@ -336,6 +342,7 @@ export async function downloadBinaryToPath(input, options) {
position += bytesRead;
}
await destinationFile.sync();
+ signal?.throwIfAborted();
await destinationFile.close();
destinationFile = undefined;
return { ...responseMetadata(response), path: destinationPath, bytes };
@@ -348,9 +355,33 @@ export async function downloadBinaryToPath(input, options) {
}
throw error;
} finally {
+ signal?.removeEventListener("abort", cancelReader);
+ await reader?.cancel().catch(() => undefined);
+ reader?.releaseLock();
await stagingFile?.close().catch(() => undefined);
if (stagingPath) {
await rm(stagingPath, { force: true }).catch(() => undefined);
}
}
}
+
+// Native evidence is larger than ordinary inbox files. This separate operation
+// uses the app's save dialog and known server endpoints as its authorities;
+// neither the output path nor the larger limit comes from renderer input.
+export async function downloadClaudeArchive(input, options) {
+ options.signal?.throwIfAborted();
+ const url = new URL(input.url);
+ if (url.username || url.password || url.search || url.hash || !/\/workspace\/[^/]+\/claude\/sessions\/[a-f0-9-]{36}\/export$/.test(url.pathname)) {
+ throw transferError("Invalid Claude archive endpoint.", "unauthorized-url");
+ }
+ const prefixes = [...options.allowedUrlPrefixes, ...(options.localServerUrl ? [options.localServerUrl] : [])];
+ remoteUrl(url.toString(), prefixes, true);
+ const session = url.pathname.split("/").at(-2);
+ const destination = await options.chooseDestination(`claude-${session}.zip`);
+ options.signal?.throwIfAborted();
+ if (!destination) return null;
+ return downloadBinaryToPath({url: url.toString(), destinationPath: destination, headers: input.headers, method: "POST", maxBytes: 2 ** 32 - 1, timeoutMs: 15 * 60_000}, {
+ ...options, allowedUrlPrefixes: prefixes, allowLoopback: true, downloadMaximum: 2 ** 32 - 1,
+ authorizedRoots: [path.dirname(destination)],
+ });
+}
diff --git a/apps/desktop/electron/binary-transfer.test.mjs b/apps/desktop/electron/binary-transfer.test.mjs
index 6824417a..3be832d9 100644
--- a/apps/desktop/electron/binary-transfer.test.mjs
+++ b/apps/desktop/electron/binary-transfer.test.mjs
@@ -7,11 +7,87 @@ import test from "node:test";
import {
DESKTOP_TRANSFER_MAX_BYTES,
downloadBinaryToPath,
+ downloadClaudeArchive,
uploadMultipartFromBytes,
} from "./binary-transfer.mjs";
const allowedUrlPrefixes = ["https://worker.example.test"];
+test("Claude archive saving uses a dialog path and only the app's exact server", async () => {
+ await withWorkspace(async (root, stagingDir) => {
+ const localServerUrl = "http://127.0.0.1:39876";
+ const route = "/workspace/project/claude/sessions/00000000-0000-4000-8000-000000000001/export";
+ let fetched = 0, dialogs = 0;
+ const options = {localServerUrl, allowedUrlPrefixes: [], stagingDir,
+ chooseDestination: async filename => { dialogs++; return path.join(root, filename); },
+ fetcher: async (url, init) => { fetched++; assert.equal(url, localServerUrl + route); assert.equal(init.method, "POST"); assert.equal(init.redirect, "error"); return remoteResponse(new Uint8Array([1,2,3]), {headers: {"content-length": String(DESKTOP_TRANSFER_MAX_BYTES + 1)}}); },
+ };
+ for (const url of ["http://127.0.0.1:39877" + route, localServerUrl + "/private", localServerUrl + route + "?redirect=1"]) await assert.rejects(downloadClaudeArchive({url}, options));
+ assert.equal(dialogs, 0); assert.equal(fetched, 0);
+ assert.equal(await downloadClaudeArchive({url: localServerUrl + route}, {...options, chooseDestination: async () => null}), null);
+ assert.equal(fetched, 0);
+ const result = await downloadClaudeArchive({url: localServerUrl + route}, options);
+ assert.equal(result.bytes, 3); assert.deepEqual(await readFile(result.path), Buffer.from([1,2,3]));
+ await assert.rejects(downloadClaudeArchive({url: localServerUrl + route}, options)); // exclusive creation
+ });
+});
+
+test("Claude archive cancellation before or during the dialog never starts a fetch", {timeout: 5000}, async () => {
+ await withWorkspace(async (root, stagingDir) => {
+ for (const beforeDialog of [true, false]) {
+ const controller = new AbortController();
+ let dialogs = 0, fetched = 0;
+ if (beforeDialog) controller.abort();
+ await assert.rejects(downloadClaudeArchive({url: "http://127.0.0.1:39876/workspace/project/claude/sessions/00000000-0000-4000-8000-000000000001/export"}, {
+ localServerUrl: "http://127.0.0.1:39876", allowedUrlPrefixes: [], stagingDir, signal: controller.signal,
+ chooseDestination: async filename => { dialogs++; controller.abort(); return path.join(root, filename); },
+ fetcher: async () => { fetched++; return remoteResponse(new Uint8Array([1])); },
+ }), {name: "AbortError"});
+ assert.equal(dialogs, beforeDialog ? 0 : 1);
+ assert.equal(fetched, 0);
+ assert.deepEqual(await readdir(root), []);
+ }
+ });
+});
+
+test("Claude archive abort cancels a stalled stream and removes private staging bytes", {timeout: 5000}, async () => {
+ await withWorkspace(async (root, stagingDir) => {
+ const controller = new AbortController();
+ let streamCancelled = false;
+ let signal;
+ const filename = "claude-00000000-0000-4000-8000-000000000001.zip";
+ const downloading = downloadClaudeArchive({
+ url: "http://127.0.0.1:39876/workspace/project/claude/sessions/00000000-0000-4000-8000-000000000001/export",
+ headers: {authorization: "Bearer fixture-client", "X-OmniRush-Host-Token": "fixture-host"},
+ }, {
+ localServerUrl: "http://127.0.0.1:39876", allowedUrlPrefixes: [], stagingDir, signal: controller.signal,
+ chooseDestination: async () => path.join(root, filename),
+ fetcher: async (_url, init) => {
+ signal = init.signal;
+ assert.equal(init.headers["X-OmniRush-Host-Token"], "fixture-host");
+ return new Response(new ReadableStream({
+ start(stream) { stream.enqueue(new Uint8Array([80, 75, 255, 0])); },
+ cancel() { streamCancelled = true; },
+ }));
+ },
+ });
+ const rejected = assert.rejects(downloading, {name: "AbortError"});
+ // Wait for bytes on disk, so this exercises an in-flight body read.
+ for (let attempt = 0; attempt < 100; attempt++) {
+ const files = await readdir(stagingDir).catch(() => []);
+ if (files.length && (await readFile(path.join(stagingDir, files[0]))).length) break;
+ assert.ok(attempt < 99, "download never staged a chunk");
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ controller.abort();
+ await rejected;
+ assert.equal(signal.aborted, true);
+ assert.equal(streamCancelled, true);
+ assert.deepEqual(await readdir(stagingDir), []);
+ assert.deepEqual(await readdir(root), []);
+ });
+});
+
async function withWorkspace(run) {
const base = await mkdtemp(path.join(os.tmpdir(), "omnirush-binary-transfer-"));
const root = path.join(base, "root");
@@ -170,6 +246,7 @@ test("rejects zero-byte and oversized downloads without leaving partial files",
test("cancellation removes the incomplete download", async () => {
await withWorkspace(async (root, stagingDir) => {
+ await mkdir(stagingDir);
const destinationPath = path.join(root, "cancelled.bin");
const controller = new AbortController();
const response = new Response(new ReadableStream({
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 5f765e2e..cd46abb2 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -89,7 +89,7 @@ import { createDesktopFeedback, EVENT_CHANNEL as FEEDBACK_EVENT_CHANNEL } from "
import { classifyLocalOpen, isNetworkPath, localPathFromFileUrl } from "./open-local-path.mjs";
import { resolveAppIdentifier, resolveUserDataPath } from "./dev-profile.mjs";
import { fetchAgentContextDiagnosticsResponse } from "./agent-context-diagnostics-fetch.mjs";
-import { downloadBinaryToPath, uploadMultipartFromBytes } from "./binary-transfer.mjs";
+import { downloadBinaryToPath, downloadClaudeArchive, uploadMultipartFromBytes } from "./binary-transfer.mjs";
import {
createLinuxDesktopIntegration,
} from "./linux-desktop-integration.mjs";
@@ -2916,6 +2916,19 @@ const desktopCommandHandlers = {
"__downloadBinary": async (event, ...args) => {
return runDesktopTransfer(event, args[0] ?? {}, downloadBinaryToPath);
},
+ "__downloadClaudeArchive": async (event, ...args) => {
+ return runDesktopTransfer(event, args[0] ?? {}, async (input, options) => {
+ const info = await runtimeManager.omnirushServerInfo();
+ return downloadClaudeArchive(input, {
+ ...options,
+ localServerUrl: info?.baseUrl,
+ chooseDestination: async filename => {
+ const result = await dialog.showSaveDialog(activeWindowFromEvent(event), {title: "Save private Claude session", defaultPath: filename, filters: [{name: "ZIP archive", extensions: ["zip"]}]});
+ return result.canceled ? null : result.filePath;
+ },
+ });
+ });
+ },
"__cancelTransfer": async (event, ...args) => {
const controller = activeDesktopTransfers.get(desktopTransferKey(event, args[0]));
if (!controller) return false;
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index 439d3fff..35a440fd 100644
--- a/apps/server/src/capture-client.ts
+++ b/apps/server/src/capture-client.ts
@@ -11,6 +11,8 @@
* again with a growing pause, and the calls made meanwhile wait for it.
*/
import type { ApprovalMode } from "./approval-mode.js";
+import type { ClaudeCaptureContext } from "./capture-host.js";
+import type { NativeCaptureAction, NativeCaptureManifest } from "./claude-code/native-capture.js";
import { Worker } from "node:worker_threads";
import { lstat } from "node:fs/promises";
import { resolve } from "node:path";
@@ -73,6 +75,8 @@ export type CaptureServiceOptions = Omit<CaptureHostOptions, "onSessionClosed">
export type CaptureMode = "starting" | "worker" | "local" | "restarting" | "down";
export type CaptureService = {
+ /** Durable native evidence; failure rejects so a Claude runner cannot continue silently. */
+ captureClaude(context: ClaudeCaptureContext, action: NativeCaptureAction): Promise<NativeCaptureManifest>;
/** The session uploader has an account to upload to (the sign-in gate's question). */
readonly uploadEnabled: boolean;
/** Where capture runs right now. */
@@ -226,6 +230,29 @@ class CaptureClient implements CaptureService {
this.send({ kind: "call", id: null, method: "pinPolicy", args: [sessionId, policy] });
}
+ async captureClaude(context: ClaudeCaptureContext, action: NativeCaptureAction): Promise<NativeCaptureManifest> {
+ const call: CaptureCall = { kind: "call", id: null, method: "captureClaude", args: [context, action] };
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ let value: unknown;
+ try {
+ value = await Promise.race([
+ this.query(call),
+ new Promise<never>((_, reject) => {
+ timeout = setTimeout(() => {
+ if (call.id !== null) this.replies.delete(call.id);
+ this.queue = this.queue.filter((item) => item.call !== call);
+ reject(new Error("Claude native capture acknowledgement timed out; stop the runner"));
+ }, 30_000);
+ }),
+ ]);
+ } finally { clearTimeout(timeout); }
+ if (typeof value !== "object" || value === null || !("format" in value) || value.format !== "claude-code" || !("sessionId" in value) || value.sessionId !== context.sessionId || !("revision" in value) || typeof value.revision !== "number") {
+ throw new Error("Claude native capture was not durably acknowledged; stop the runner");
+ }
+ // The typed CaptureHost produced this object across a structured-clone boundary.
+ return value as NativeCaptureManifest;
+ }
+
boxSession(sessionId: string, box: BoxCaptureInfo | null): void {
this.send({ kind: "call", id: null, method: "boxSession", args: [sessionId, box] });
}
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index d975b993..e7bc33dc 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -9,6 +9,7 @@
* cross the thread boundary unchanged.
*/
import { createMediaRewriter } from "./computer-use/media-capture.js";
+import { NativeCapture, type NativeCaptureOptions, type NativeCaptureAction, type NativeCaptureManifest } from "./claude-code/native-capture.js";
import type { ApprovalMode } from "./approval-mode.js";
import type { ContextOptions } from "./context/index.js";
import { defaultRedactionPolicy } from "./context/redact-policy.js";
@@ -43,6 +44,7 @@ import { SessionUploader, type RecoveredTurn, type TraceCapabilities, type Uploa
export type { EngineReplacement, EngineTarget } from "./session-upload-observer.js";
export type CaptureLog = ArchiveLifecycleLog;
+export type ClaudeCaptureContext = Pick<NativeCaptureOptions, "sessionId" | "configDir" | "producerVersion" | "transport">;
/** Prompt bodies larger than this are not parsed for the trace (nor for attachments). */
const MAX_TRACED_REQUEST_BYTES = 4 * 1024 * 1024;
@@ -142,6 +144,8 @@ function requestPayload(body: Uint8Array | null): unknown {
}
export class CaptureHost {
+ private readonly nativeCaptures = new Map<string, { identity: string; capture: NativeCapture }>();
+ private readonly accountId: CaptureHostOptions["accountId"];
readonly sessionUploader: SessionUploader;
readonly archive: ProjectArchiveLifecycle;
private readonly observers: SessionObservers = createSessionObservers();
@@ -161,6 +165,7 @@ export class CaptureHost {
private readonly log: CaptureLog;
constructor(options: CaptureHostOptions) {
+ this.accountId = options.accountId;
this.engineTarget = options.engineTarget;
this.log = options.log;
this.sessionUploader = new SessionUploader({
@@ -235,6 +240,28 @@ export class CaptureHost {
this.sessionUploader.startSession(sessionId, workspaceId, root, { turnsBefore });
}
+ /** Awaited, durable Claude evidence. Kept outside the lossy display/event queue
+ * and the scrubbed legacy upload format. The runner stops on a missing ack.
+ * configDir is the runner's dedicated persistent volume, never a user home.
+ */
+ async captureClaude(context: ClaudeCaptureContext, action: NativeCaptureAction): Promise<NativeCaptureManifest> {
+ const owner = await this.accountId?.();
+ if (!owner) throw new Error("Claude native capture requires an account owner");
+ const key = `${owner}/${context.sessionId}`;
+ const identity = JSON.stringify(context);
+ let entry = this.nativeCaptures.get(key);
+ if (entry && entry.identity !== identity) throw new Error("Claude capture source or producer changed");
+ if (!entry) {
+ // One immutable owner per native UUID, including across sign-out/restart.
+ // Changing accounts must not silently create a second copy owned by B.
+ entry = { identity, capture: new NativeCapture({ ...context, directory: join(this.stateDir, "claude-native", context.sessionId), owner, surface: "gui" }) };
+ this.nativeCaptures.set(key, entry);
+ }
+ if (action.type === "stream") return entry.capture.recordStream(action.channel, action.bytes, action.offset);
+ if (action.type === "finish") return entry.capture.finish(action);
+ return entry.capture.scan();
+ }
+
/** The app's permission mode, named in the setup record of the sessions started after it (sent before each startSession). */
permissionMode(mode: ApprovalMode | null): void {
this.sessionUploader.setPermissionMode(mode);
diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.ts
index 3f55e302..d5b3c8db 100644
--- a/apps/server/src/capture-protocol.ts
+++ b/apps/server/src/capture-protocol.ts
@@ -7,7 +7,8 @@
* logs and closed sessions. Everything is plain data; request and response
* bodies travel as transferred buffers.
*/
-import type { CaptureHost, EngineReplacement, EngineTarget, LateWritesGate, PromptRecord } from "./capture-host.js";
+import type { CaptureHost, ClaudeCaptureContext, EngineReplacement, EngineTarget, LateWritesGate, PromptRecord } from "./capture-host.js";
+import type { NativeCaptureAction } from "./claude-code/native-capture.js";
import type { ApprovalMode } from "./approval-mode.js";
import type { BoxCaptureInfo } from "./box/service.js";
import type { CommandEventType } from "./command-events.js";
@@ -19,6 +20,7 @@ export type CaptureStopOptions = { archiveFinals: boolean };
/** CaptureHost methods callable from the main thread, with their arguments. */
export type CaptureCalls = {
+ captureClaude: [context: ClaudeCaptureContext, action: NativeCaptureAction];
startSession: [sessionId: string, workspaceId: string, root: string, turnsBefore?: number];
boxSession: [sessionId: string, box: BoxCaptureInfo | null];
sessionPolicy: [sessionId: string];
@@ -173,6 +175,8 @@ export function transferables(value: HostRequest | SerializedResponse | null): A
/** Runs one call on a host (the worker's, or the in-process fallback). */
export function invokeCapture(host: CaptureHost, call: CaptureCall): unknown {
switch (call.method) {
+ case "captureClaude":
+ return host.captureClaude(...call.args);
case "startSession":
return host.startSession(...call.args);
case "boxSession":
diff --git a/apps/server/src/claude-code/README.md b/apps/server/src/claude-code/README.md
new file mode 100644
index 00000000..df65dcd2
--- /dev/null
+++ b/apps/server/src/claude-code/README.md
@@ -0,0 +1,64 @@
+# Claude native evidence
+
+The CLI and dedicated GUI Claude route use this shared native runtime. The
+pinned official Agent SDK launches Claude Code inside Docker. This path does
+not use the existing OpenCode conversation engine. Backend enablement remains
+separate from local implementation and verification.
+
+`NativeCapture` preserves the original root JSONL, every discovered child JSONL
+and its metadata, and uncoalesced transport/hook journals. It never reconstructs
+native records from OmniRush display messages or walks only a selected parent
+chain. Unknown fields and opaque thinking signatures remain in private evidence.
+Thinking text is the model's exposed summary, not hidden chain-of-thought.
+
+The source must be a session-scoped persistent `CLAUDE_CONFIG_DIR`. Only the
+requested UUID and its `subagents` files are read. Authentication files, other
+sessions and symlinks are excluded. The private store is mode 0700 with 0600
+files, content-addressed 1 MiB chunks and atomic fsynced manifests. Originals
+have no redaction pass and must not enter the legacy scrubbed collector.
+
+The caller awaits `captureClaude(context, action)` through `CaptureService`.
+Stream actions carry byte offsets; duplicate retries must match the stored
+bytes. Gaps, conflicting retries, missing acknowledgements, owner changes and
+integrity failures reject. The runner must stop on rejection. A worker restart
+can retry the same offset. A scan reconciles native files after a restart and
+before finalization. Partial lines remain exact evidence and block completion;
+replacement/truncation retains the previous generation. Unchanged files are
+not reread; obsolete append-prefix chunks are pruned after manifest durability.
+
+`finish` requires a stopped producer and successful terminal result. It checks
+root presence, JSON validity, partial lines, unmatched tool calls and child
+transcripts referenced by native launch results or supplied by the runner.
+`complete` means the captured evidence passed these checks; `replay` remains
+`unverified`. The caller must establish whole-process-tree termination and
+perform environment/checkpoint and replay checks separately.
+
+`exportTo` produces a private directory with `claude/`, `events/`, optional
+`history/`, and `native-manifest.json`. Original bytes are hash-verified during
+export. Do not claim a redacted derivative is byte-exact or resumable. Export
+only behind the session's single-writer barrier.
+
+The canonical source is this directory. Copy and check the CLI consumer with:
+
+```sh
+node scripts/sync-claude-capture.mjs /path/to/omnirush-cli
+node scripts/sync-claude-capture.mjs /path/to/omnirush-cli --check
+pnpm evals:pr specs/claude-native-capture.test.ts
+```
+
+`runtime.ts` records an immutable model/harness/image/capture contract and
+brokers only that model, including SDK children. `access.ts` validates the
+backend's session/model/contract binding and keeps short-lived tokens in host
+memory. Unknown or conflicting provider identity blocks continuation; old
+captures remain exportable without claiming retroactive model isolation.
+
+The native manifest includes a versioned QC summary: human-prompt candidates,
+synthetic events, compaction, tool/results, child transcripts, exposed thinking
+and opaque blocks. Counts never replace original bytes. `verify.py` binds replay
+to the exact ZIP and independently checks the contract and model journal.
+Exact replay, soft differences, tools-ran and unverified outcomes stay distinct.
+Missing actual shell argv/exit evidence prevents a strict shell replay claim.
+
+See `docs/claude-native-pilot.md` for the product path, backend dependencies and
+verification commands. Production enablement requires backend token/capture
+adoption, usage matching, packaged OS validation and the native conversion lane.
diff --git a/apps/server/src/claude-code/access.ts b/apps/server/src/claude-code/access.ts
new file mode 100644
index 00000000..e5c96a7e
--- /dev/null
+++ b/apps/server/src/claude-code/access.ts
@@ -0,0 +1,146 @@
+import { createHash } from "node:crypto";
+import type { ClaudeAccess, ClaudeAuthorization, ClaudeBudgetSnapshot, ClaudeGrant } from "./runtime.js";
+import { MODEL } from "./sandbox-assets.js";
+import { SDK_INSTALL_PIN } from "./sandbox-lock.js";
+
+export type ClaudeDeviceRequest = (route: string, init?: { method: "POST"; body: string }, owner?: string) => Promise<Response>;
+const record = (value: unknown): value is Record<string, unknown> => Boolean(value && typeof value === "object" && !Array.isArray(value));
+const tokens = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
+const limit = (value: unknown): value is number | null => value === null || tokens(value);
+const timestamp = (value: unknown): value is string => typeof value === "string" && Number.isFinite(Date.parse(value));
+/** Neutral quota metadata is useful to the SDK; provider and credential headers stay private. */
+export function claudeResponseHeaders(headers: Headers): Record<string, string> {
+ const result: Record<string, string> = {};
+ for (const name of ["content-type", "retry-after", "x-should-retry", "x-omnirush-grant-scope", "x-omnirush-grant-bucket", "x-omnirush-grant-resets-at", "x-ratelimit-limit-tokens", "x-ratelimit-remaining-tokens", "x-ratelimit-reset-tokens"]) {
+ const value = headers.get(name);
+ if (value !== null) result[name] = value;
+ }
+ return result;
+}
+export class ClaudeAccessError extends Error {
+ constructor(readonly status: number, message: string, readonly retryAfter?: string, readonly responseHeaders: Record<string, string> = {}) { super(message); }
+}
+
+function budgetSnapshot(value: unknown, context: ClaudeAuthorization): ClaudeBudgetSnapshot {
+ if (value === undefined || value === null) return {status: "unknown", model: context.model};
+ if (!record(value) || !record(value.allowance) || !record(value.model) || !record(value.session)) throw new Error("Invalid Claude budget response");
+ const {allowance, model, session} = value;
+ if (!timestamp(value.as_of) || !["day", "week"].includes(String(allowance.scope)) || !tokens(allowance.limit) || !tokens(allowance.remaining) || !timestamp(allowance.resets_at)
+ || model.key !== context.model || !limit(model.limit) || !limit(model.remaining) || !(model.resets_at === null || timestamp(model.resets_at))
+ || session.root_session_id !== context.sessionId || !limit(session.limit) || !tokens(session.used) || !limit(session.remaining)
+ || (model.limit === null) !== (model.remaining === null) || (session.limit === null) !== (session.remaining === null)) throw new Error("Claude budget does not match this session");
+ return {
+ status: "known", model: context.model, asOf: value.as_of,
+ limitTokens: model.limit, remainingTokens: model.remaining, resetAt: model.resets_at,
+ sessionLimitTokens: session.limit, sessionUsedTokens: session.used, sessionRemainingTokens: session.remaining,
+ accountLimitTokens: allowance.limit, accountRemainingTokens: allowance.remaining,
+ accountScope: allowance.scope === "day" ? "day" : "week", accountResetAt: allowance.resets_at,
+ };
+}
+
+async function read(response: Response): Promise<unknown> {
+ // Device responses contain credentials. Never include their bodies in errors.
+ if (!response.ok) {
+ const reason = response.status === 409 ? "The session's model or capture contract conflicts with its backend binding"
+ : response.status === 429 ? response.headers.get("x-should-retry") === "false"
+ ? "The Claude allowance is exhausted; wait for its reset" : "Claude is busy; retry after the indicated delay"
+ : response.status === 401 ? "Sign in to OmniRush to use Claude Code"
+ : "Claude Code is unavailable for this account";
+ const retryAfter = response.headers.get("retry-after") ?? undefined;
+ await response.body?.cancel();
+ throw new ClaudeAccessError(response.status, `${reason} (${response.status})`, retryAfter, claudeResponseHeaders(response.headers));
+ }
+ const reader = response.body?.getReader();
+ if (!reader) throw new Error("Empty Claude authorization response");
+ const chunks: Uint8Array[] = []; let bytes = 0;
+ try {
+ while (true) {
+ const next = await reader.read(); if (next.done) break;
+ bytes += next.value.byteLength;
+ if (bytes > 64 * 1024) throw new Error("Invalid Claude authorization response");
+ chunks.push(next.value);
+ }
+ try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); }
+ catch { throw new Error("Invalid Claude authorization response"); }
+ } finally { await reader.cancel().catch(() => {}); reader.releaseLock(); }
+}
+
+/** The same session-bound device contract is used by the CLI and desktop. */
+export class ClaudeDeviceAccess {
+ private readonly grants = new Map<string, { grant: ClaudeGrant; refreshAt: number }>();
+ private readonly pending = new Map<string, Promise<ClaudeGrant>>();
+ private capability?: {owner: string; expiresAt: number; enabled: boolean};
+ constructor(private readonly request: ClaudeDeviceRequest, private readonly client: string) {}
+
+ async access(): Promise<ClaudeAccess> {
+ const account = await read(await this.request("device/me"));
+ if (!record(account) || typeof account.id !== "string" || !account.id) throw new Error("Sign in to OmniRush to use Claude Code");
+ if (!this.capability || this.capability.owner !== account.id || Date.now() >= this.capability.expiresAt) {
+ let enabled = false;
+ try {
+ const value = await read(await this.request("collect/capabilities"));
+ const code = record(value) ? value.claude_code : null;
+ // The pilot supports this exact SDK/Code pair and one fixed model.
+ // An enabled relay with an empty catalog is not permission to run it.
+ enabled = record(code) && code.enabled === true && record(code.sdk)
+ && code.sdk.package === SDK_INSTALL_PIN.package && code.sdk.version === SDK_INSTALL_PIN.version
+ && code.sdk.integrity === SDK_INSTALL_PIN.integrity
+ && Array.isArray(code.models) && code.models.includes(MODEL)
+ && code.models.every(model => typeof model === "string" && model.length > 0);
+ } catch { /* Failed eligibility checks deny new sessions, but never hide saved evidence. */ }
+ this.capability = {owner: account.id, expiresAt: Date.now() + 30_000, enabled};
+ }
+ return { owner: account.id, capabilities: this.capability.enabled ? ["claude-code"] : [] };
+ }
+
+ async authorize(context: ClaudeAuthorization): Promise<ClaudeGrant> {
+ const key = `${context.owner}/${context.sessionId}/${context.model}/${context.contractSha256}`;
+ if (context.refresh) this.grants.delete(key);
+ const cached = this.grants.get(key);
+ if (cached && Date.now() < cached.refreshAt) return cached.grant;
+ const existing = this.pending.get(key); if (existing) return existing;
+ const pending = this.mint(context, key);
+ this.pending.set(key, pending);
+ try { return await pending; } finally { this.pending.delete(key); }
+ }
+
+ private async mint(context: ClaudeAuthorization, key: string): Promise<ClaudeGrant> {
+ const requestedAt = Date.now();
+ const value = await read(await this.request("device/claude-token", {
+ method: "POST", body: JSON.stringify({
+ session_id: context.sessionId,
+ project_key: createHash("sha256").update(context.workspaceId).digest("hex").slice(0, 12),
+ model: context.model, contract_hash: context.contractSha256, client: this.client,
+ }),
+ }, context.owner));
+ if (!record(value) || !record(value.binding)) throw new ClaudeAccessError(409, "Claude authorization has no immutable session binding");
+ const binding = value.binding;
+ if (binding.session_id !== context.sessionId || binding.root_session_id !== context.sessionId || binding.model !== context.model || binding.contract_hash !== context.contractSha256
+ || typeof binding.binding_id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(binding.binding_id) || binding.upstream_model !== context.model) {
+ throw new ClaudeAccessError(409, "Claude authorization does not match this session's fixed model and capture contract");
+ }
+ if (typeof value.token !== "string" || !/^orc_[A-Za-z0-9_-]{43}$/.test(value.token) || typeof value.base_url !== "string"
+ || typeof value.expires_in !== "number" || !Number.isFinite(value.expires_in) || value.expires_in <= 0 || value.expires_in > 900
+ || typeof value.refresh_after !== "number" || !Number.isFinite(value.refresh_after) || value.refresh_after < 1 || value.refresh_after > value.expires_in) {
+ throw new Error("Invalid short-lived Claude authorization");
+ }
+ const base = new URL(value.base_url);
+ if (base.username || base.password || base.search || base.hash || !(base.protocol === "https:" || base.protocol === "http:" && ["127.0.0.1", "localhost"].includes(base.hostname))) throw new Error("Invalid Claude relay address");
+ const grant: ClaudeGrant = {
+ owner: context.owner, sessionId: context.sessionId, model: context.model,
+ bindingId: binding.binding_id, contractSha256: context.contractSha256, baseUrl: value.base_url, token: value.token,
+ upstreamModel: binding.upstream_model, client: this.client,
+ budget: budgetSnapshot(value.budget, context),
+ };
+ this.grants.set(key, { grant, refreshAt: requestedAt + Math.min(value.refresh_after, Math.max(0, value.expires_in - 5)) * 1000 });
+ return grant;
+ }
+
+ async revoke(context: ClaudeAuthorization): Promise<void> {
+ const prefix = `${context.owner}/${context.sessionId}/`;
+ for (const key of this.grants.keys()) if (key.startsWith(prefix)) this.grants.delete(key);
+ const response = await this.request("device/claude-token/revoke", { method: "POST", body: JSON.stringify({session_id: context.sessionId}) }, context.owner);
+ if (!response.ok) await read(response);
+ else await response.body?.cancel();
+ }
+}
diff --git a/apps/server/src/claude-code/bundle-manifest.ts b/apps/server/src/claude-code/bundle-manifest.ts
new file mode 100644
index 00000000..de587bac
--- /dev/null
+++ b/apps/server/src/claude-code/bundle-manifest.ts
@@ -0,0 +1,38 @@
+import fs from "node:fs";
+import fsp from "node:fs/promises";
+import path from "node:path";
+import { createHash } from "node:crypto";
+
+export const BUNDLE_MANIFEST = "__omnirush__/manifest.json";
+export async function writeBundleManifest(directory: string, context: {
+ sessionId: string; bindingId: string; contractHash: string; engineVersion: string;
+}, payload: "claude_native" | "claude_checkpoint") {
+ const files: Array<{path: string; size: number; sha256: string}> = [];
+ const walk = async (dir: string): Promise<void> => {
+ for (const entry of await fsp.readdir(dir, {withFileTypes: true})) {
+ const file = path.join(dir, entry.name), name = path.relative(directory, file).split(path.sep).join("/");
+ if (name === BUNDLE_MANIFEST) continue;
+ if (entry.isDirectory()) { await walk(file); continue; }
+ const hash = createHash("sha256"); let size = 0;
+ if (entry.isSymbolicLink()) {
+ // A ZIP symlink member contains its link text, never the target bytes.
+ const bytes = Buffer.from(await fsp.readlink(file)); hash.update(bytes); size = bytes.length;
+ } else if (entry.isFile()) {
+ for await (const chunk of fs.createReadStream(file)) { hash.update(chunk); size += chunk.length; }
+ } else throw new Error("Unsupported native archive member");
+ files.push({path: name, size, sha256: hash.digest("hex")});
+ }
+ };
+ await walk(directory);
+ files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
+ const manifest = {
+ schema: payload === "claude_native" ? "omnirush.claude.native.v1" : "omnirush.claude.checkpoint.v1",
+ session_id: context.sessionId, root_session_id: context.sessionId,
+ binding_id: context.bindingId, contract_hash: context.contractHash,
+ harness: "claude-code", engine_version: context.engineVersion, payload, files,
+ };
+ const bytes = Buffer.from(JSON.stringify(manifest) + "\n"), target = path.join(directory, BUNDLE_MANIFEST);
+ await fsp.mkdir(path.dirname(target), {recursive: true, mode: 0o700});
+ await fsp.writeFile(target, bytes, {mode: 0o600});
+ return createHash("sha256").update(bytes).digest("hex");
+}
diff --git a/apps/server/src/claude-code/native-capture.test.ts b/apps/server/src/claude-code/native-capture.test.ts
new file mode 100644
index 00000000..a02bdbf5
--- /dev/null
+++ b/apps/server/src/claude-code/native-capture.test.ts
@@ -0,0 +1,984 @@
+import { afterEach, expect, spyOn, test } from "bun:test";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { spawn, spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { fileURLToPath } from "node:url";
+import { NativeCapture } from "./native-capture.js";
+import { ClaudeAccessError, ClaudeDeviceAccess } from "./access.js";
+import { CLAUDE_VERSION, MODEL } from "./sandbox-assets.js";
+import { SDK_INSTALL_PIN } from "./sandbox-lock.js";
+import { ClaudeRuntime } from "./runtime.js";
+
+test("managed Claude availability requires an enabled compatible catalog, never just relay access", async () => {
+ const valid = {enabled: true, version: CLAUDE_VERSION, sdk: SDK_INSTALL_PIN, models: [MODEL]};
+ for (const [code, allowed] of [
+ [valid, true], [{...valid, enabled: false}, false], [{...valid, models: []}, false],
+ [{...valid, models: ["claude-haiku-4-5-20251001"]}, false], [{...valid, sdk: {...SDK_INSTALL_PIN, version: "0.0.0"}}, false],
+ [{...valid, sdk: null}, false], [{...valid, sdk: {...SDK_INSTALL_PIN, integrity: "sha512-wrong"}}, false],
+ [{...valid, sdk: {...SDK_INSTALL_PIN, package: "@anthropic-ai/claude-code"}}, false],
+ [{...valid, models: [MODEL, null]}, false], [{enabled: true}, false], [null, false],
+ ] as const) {
+ const routes: string[] = [];
+ const access = new ClaudeDeviceAccess(async route => {
+ routes.push(route);
+ return Response.json(route === "device/me" ? {id: "owner"} : {claude_code: code});
+ }, "cli/2.7.0");
+ expect((await access.access()).capabilities?.includes("claude-code")).toBe(allowed);
+ expect(routes).toEqual(["device/me", "collect/capabilities"]);
+ }
+});
+
+test("managed grants reject provider keys and zero refresh, refresh from request time, and revoke the root", async () => {
+ const context = {owner: "owner", sessionId: "00000000-0000-4000-8000-000000000001", workspaceId: "project", model: MODEL, contractSha256: "a".repeat(64)};
+ const response = {token: "orc_" + "a".repeat(43), expires_in: 900, refresh_after: 600,
+ base_url: "https://omnirush.ai/claude", budget: null,
+ binding: {binding_id: "00000000-0000-4000-8000-000000000002", session_id: context.sessionId,
+ root_session_id: context.sessionId, model: MODEL, upstream_model: MODEL, contract_hash: context.contractSha256}};
+ for (const fault of [{token: "provider-key-fixture"}, {refresh_after: 0}, {refresh_after: 901}]) {
+ const access = new ClaudeDeviceAccess(async () => Response.json({...response, ...fault}), "desktop/3.7.5");
+ await expect(access.authorize(context)).rejects.toThrow("Invalid short-lived Claude authorization");
+ }
+ let now = 100_000, mints = 0;
+ const clock = spyOn(Date, "now").mockImplementation(() => now);
+ const requests: Array<{route: string; body: unknown; owner?: string}> = [];
+ const access = new ClaudeDeviceAccess(async (route, init, owner) => {
+ requests.push({route, body: JSON.parse(init!.body), owner});
+ if (route.endsWith("/revoke")) return new Response(null, {status: 204});
+ mints++; now += 2_000; // Mint latency consumes token lifetime.
+ return Response.json(response);
+ }, "desktop/3.7.5");
+ try {
+ const first = await access.authorize(context);
+ expect(first.baseUrl).toBe("https://omnirush.ai/claude");
+ expect(first.budget?.status).toBe("unknown");
+ now = 699_999; await access.authorize(context); expect(mints).toBe(1);
+ now = 700_000; await access.authorize(context); expect(mints).toBe(2);
+ await access.authorize({...context, refresh: true}); expect(mints).toBe(3);
+ expect(requests[0]).toMatchObject({route: "device/claude-token", owner: "owner", body: {
+ session_id: context.sessionId, model: MODEL, contract_hash: context.contractSha256, client: "desktop/3.7.5",
+ }});
+ await access.revoke(context);
+ expect(requests.at(-1)).toEqual({route: "device/claude-token/revoke", owner: "owner", body: {session_id: context.sessionId}});
+ await access.authorize(context); expect(mints).toBe(4);
+ } finally { clock.mockRestore(); }
+});
+
+test("managed access distinguishes retryable capacity from terminal allowance without exposing response bodies", async () => {
+ const context = {owner: "owner", sessionId: "00000000-0000-4000-8000-000000000001", workspaceId: "project", model: MODEL, contractSha256: "a".repeat(64)};
+ for (const retry of ["true", "false"]) {
+ let requests = 0;
+ const access = new ClaudeDeviceAccess(async () => {
+ requests++;
+ return Response.json({credential: "private-fixture-canary"}, {status: 429, headers: {"x-should-retry": retry, "retry-after": "30"}});
+ }, "cli/2.7.0");
+ try { await access.authorize(context); throw new Error("Expected rejection"); }
+ catch (error) {
+ expect(error).toBeInstanceOf(ClaudeAccessError);
+ if (!(error instanceof ClaudeAccessError)) throw error;
+ expect(error.message).toContain(retry === "false" ? "allowance" : "busy");
+ expect(error.message).not.toContain("private-fixture-canary");
+ expect(error.responseHeaders["x-should-retry"]).toBe(retry);
+ expect(error.retryAfter).toBe("30");
+ }
+ expect(requests).toBe(1);
+ }
+});
+
+test("session broker re-mints once on rejected authentication and never replays quota or server failures", async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-broker-contract-")); roots.push(root);
+ const id = "00000000-0000-4000-8000-000000000001", contractSha256 = "a".repeat(64);
+ let status = 401, attempts = 0, successful = 0, authorizations = 0, refreshes = 0, first401 = true;
+ const relay = Bun.serve({hostname: "127.0.0.1", port: 0, async fetch(req) {
+ attempts++;
+ expect(req.headers.get("x-api-key")).toMatch(/^orc_/);
+ expect(req.headers.get("x-omnirush-session-id")).toBe(id);
+ expect(req.headers.get("x-omnirush-box")).toBe("1");
+ expect(req.headers.get("x-omnirush-client")).toBe("desktop/3.7.5");
+ if (status === 200 || status === 401 && !first401) {
+ successful++;
+ return Response.json({type: "message", model: MODEL, content: [], stop_reason: "end_turn"});
+ }
+ first401 = false;
+ return Response.json({type: "error", error: {type: "api_error", message: "fixture"}}, {status,
+ headers: {"x-should-retry": status === 429 ? "false" : "true", "retry-after": "30"}});
+ }});
+ const runtime = new ClaudeRuntime({directory: root, surface: "gui", access: async () => ({owner: "owner", capabilities: ["claude-code"]}),
+ authorize: async context => {
+ authorizations++; if (context.refresh) refreshes++;
+ return {owner: "owner", sessionId: id, model: MODEL, upstreamModel: MODEL, client: "desktop/3.7.5",
+ baseUrl: `http://127.0.0.1:${relay.port}`, token: "orc_" + "a".repeat(43), contractSha256};
+ }});
+ // Isolate the actual HTTP broker from Docker setup; private access is confined to this boundary test.
+ const session = {owner: "owner", id, model: MODEL, workspaceId: "project", contract: {}, contractSha256, turns: []};
+ const broker = await Reflect.get(runtime, "broker").call(runtime, session, () => {});
+ const endpoint = broker.baseUrl.replace("host.docker.internal", "127.0.0.1") + "/v1/messages";
+ const request = () => fetch(endpoint, {method: "POST", headers: {authorization: `Bearer ${broker.token}`, "content-type": "application/json"},
+ body: JSON.stringify({model: MODEL, messages: [], max_tokens: 1}), signal: AbortSignal.timeout(5_000)});
+ try {
+ const accepted = await request(); expect(accepted.status).toBe(200); await accepted.arrayBuffer();
+ expect({attempts, successful, authorizations, refreshes}).toEqual({attempts: 2, successful: 1, authorizations: 2, refreshes: 1});
+ const journal = fs.readFileSync(path.join(Reflect.get(runtime, "dir").call(runtime, "owner", id), "policy", "model-requests.jsonl"), "utf8").trim().split("\n").map(line => JSON.parse(line));
+ expect(journal.map(event => event.type)).toEqual(["request", "provider_identity", "response"]);
+ expect(journal.at(-1)).toMatchObject({status: 200, authorizationFailures: [401], completed: true});
+ for (status of [429, 503]) {
+ const before = attempts, renewed = refreshes;
+ const denied = await request(); expect(denied.status).toBe(status);
+ expect(denied.headers.get("x-should-retry")).toBe(status === 429 ? "false" : "true");
+ expect(denied.headers.get("retry-after")).toBe("30"); await denied.arrayBuffer();
+ expect(attempts).toBe(before + 1); expect(refreshes).toBe(renewed); expect(successful).toBe(1);
+ }
+ } finally { await broker.close(); relay.stop(true); }
+});
+
+const roots: string[] = [];
+afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
+function fixture() {
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "claude-native-"))); roots.push(root);
+ const options = { directory: path.join(root, "capture"), configDir: path.join(root, "config"), sessionId: "00000000-0000-4000-8000-000000000001", producerVersion: "fixture", surface: "gui" as const, transport: "sdk" as const, owner: "actor-a" };
+ const project = path.join(options.configDir, "projects", "-workspace");
+ fs.mkdirSync(project, { recursive: true });
+ const source = path.join(project, `${options.sessionId}.jsonl`);
+ const capture = new NativeCapture(options);
+ return { root, options, project, source, capture };
+}
+const line = (value: unknown) => JSON.stringify(value) + "\n";
+const user = (uuid: string) => ({ type: "user", uuid, parentUuid: null, message: { content: "hello" } });
+const finish = { type: "finish" as const, processStopped: true, successfulResult: true };
+
+test("copies every branch, unknown field, thinking signature and five child files byte for byte; excludes auth and other sessions", () => {
+ const f = fixture();
+ const original = line(user("prompt")) + line({ type: "assistant", uuid: "a", parentUuid: "prompt", future: { keep: true }, message: { content: [{ type: "thinking", thinking: "Visible summary", signature: "opaque-fixture" }, { type: "tool_use", id: "one", name: "Read" }, { type: "tool_use", id: "two", name: "Read" }] } })
+ + line({ type: "user", uuid: "side", parentUuid: "a", message: { content: [{ type: "tool_result", tool_use_id: "one", content: "branch one" }] } })
+ + line({ type: "user", uuid: "selected", parentUuid: "a", message: { content: [{ type: "tool_result", tool_use_id: "two", content: "branch two" }] } })
+ + line({ type: "api-request-blob", message: { content: [{ type: "tool_use", id: "cached-context-only", name: "Bash" }, {type: "thinking", thinking: "Repeated context"}] } });
+ fs.writeFileSync(f.source, original);
+ fs.writeFileSync(path.join(f.project, "another-session.jsonl"), "DO_NOT_EXPORT_OTHER_SESSION");
+ fs.writeFileSync(path.join(f.options.configDir, "credentials.json"), "DO_NOT_EXPORT_AUTH");
+ const agents = ["child1", "child2", "child3", "child4", "child5"];
+ const children = path.join(f.project, f.options.sessionId, "subagents"); fs.mkdirSync(children, { recursive: true });
+ for (const agent of agents) {
+ fs.writeFileSync(path.join(children, `agent-${agent}.jsonl`), line(user(agent)));
+ fs.writeFileSync(path.join(children, `agent-${agent}.meta.json`), '{ "agentType": "test", "unknown": 5 }');
+ }
+ const manifest = f.capture.finish({ ...finish, expectedAgents: agents });
+ expect(manifest.status).toBe("complete"); expect(manifest.replay).toBe("unverified");
+ expect(manifest.files).toHaveLength(11);
+ expect(manifest.qc).toMatchObject({ schema: 1, humanPromptCandidates: 1, childPromptRecords: 5, exposedThinkingBlocks: 1, opaqueThinkingBlocks: 0, reviewRequired: false });
+ expect(manifest.files.find((file) => file.path.endsWith(`${f.options.sessionId}.jsonl`))).toMatchObject({ toolCalls: 2, toolResults: 2, thinkingBlocks: 1, pendingTools: [] });
+ const out = path.join(f.root, "export"); f.capture.exportTo(out);
+ expect(fs.readFileSync(path.join(out, "claude/projects/-workspace", `${f.options.sessionId}.jsonl`), "utf8")).toBe(original);
+ expect(fs.readdirSync(path.join(out, "claude/projects/-workspace"))).toEqual([f.options.sessionId, `${f.options.sessionId}.jsonl`]);
+ expect(fs.existsSync(path.join(out, "credentials.json"))).toBe(false);
+});
+
+test("partial native lines survive restart and prevent completeness until their real bytes arrive", () => {
+ const f = fixture(); fs.writeFileSync(f.source, line(user("a")) + '{"type":"user","message":');
+ const first = f.capture.finish(finish);
+ expect(first.status).toBe("incomplete"); expect(first.files[0].tailBytes).toBeGreaterThan(0);
+ const recovered = new NativeCapture(f.options);
+ fs.appendFileSync(f.source, '{"content":"continued"}}\n');
+ expect(recovered.finish(finish).status).toBe("complete");
+ expect(recovered.verify().files[0].completeLines).toBe(2);
+});
+
+test("durable stream retries are idempotent, reject conflicting bytes and gaps, and recover an unacknowledged partial write", () => {
+ const f = fixture(), bytes = Buffer.from(line(user("stream")));
+ f.capture.recordStream("sdk", bytes, 0);
+ const recovered = new NativeCapture(f.options);
+ expect(recovered.recordStream("sdk", bytes, 0).streams.sdk).toBe(bytes.length);
+ expect(() => recovered.recordStream("sdk", Buffer.from("bad"), 0)).toThrow("Conflicting");
+ expect(() => recovered.recordStream("sdk", bytes, bytes.length + 1)).toThrow("offset gap");
+ const next = Buffer.from(line(user("next")));
+ fs.appendFileSync(path.join(f.options.directory, "events/sdk.jsonl"), next.subarray(0, 5));
+ recovered.recordStream("sdk", next, bytes.length);
+ expect(fs.readFileSync(path.join(f.options.directory, "events/sdk.jsonl"))).toEqual(Buffer.concat([bytes, next]));
+});
+
+test("rewritten transcripts retain prior generations and corrupt or missing durable chunks reject recovery", () => {
+ const f = fixture(), original = line(user("original")); fs.writeFileSync(f.source, original); f.capture.scan();
+ fs.writeFileSync(f.source, line(user("replacement"))); f.capture.scan();
+ const manifest = f.capture.verify(); expect(manifest.history).toHaveLength(1);
+ const out = path.join(f.root, "export"); f.capture.exportTo(out);
+ expect(fs.readFileSync(path.join(out, "history/0/claude/projects/-workspace", `${f.options.sessionId}.jsonl`), "utf8")).toBe(original);
+ fs.unlinkSync(path.join(f.options.directory, "chunks", manifest.history[0].chunks[0].sha256));
+ expect(() => new NativeCapture(f.options)).toThrow();
+});
+
+test("missing children, unmatched calls and a live or failed producer cannot yield complete capture", () => {
+ const f = fixture(); fs.writeFileSync(f.source, line({ type: "assistant", message: { content: [{ type: "tool_use", id: "pending", name: "Bash" }] } }) + line({ type: "user", toolUseResult: { status: "async_launched", agentId: "native-child" }, message: { content: [] } }));
+ const manifest = f.capture.finish({ ...finish, processStopped: false, successfulResult: false, expectedAgents: ["missing"] });
+ expect(manifest.status).toBe("incomplete");
+ expect(manifest.issues).toContain("producer_still_running");
+ expect(manifest.issues).toContain("successful_result_missing");
+ expect(manifest.issues).toContain("child_transcript_missing:missing");
+ expect(manifest.issues).toContain("child_transcript_missing:native-child");
+ expect(manifest.issues.some((issue) => issue.startsWith("pending_tools:"))).toBe(true);
+});
+
+test("append scans keep storage proportional to referenced chunks, while invalid UTF-8 remains incomplete", () => {
+ const f = fixture(); fs.writeFileSync(f.source, line(user("first")));
+ for (let turn = 0; turn < 8; turn++) { fs.appendFileSync(f.source, line(user(`turn-${turn}`))); f.capture.scan(); }
+ expect(fs.readdirSync(path.join(f.options.directory, "chunks"))).toHaveLength(1);
+ fs.appendFileSync(f.source, Buffer.concat([Buffer.from('{"message":{"content":"'), Buffer.from([0xff]), Buffer.from('"}}\n')]));
+ expect(f.capture.finish(finish).status).toBe("incomplete");
+ expect(f.capture.verify().files[0].invalidLines).toBeGreaterThan(0);
+});
+
+test("owner, source, version and transcript symlink changes fail closed", () => {
+ const f = fixture();
+ expect(() => new NativeCapture({ ...f.options, owner: "actor-b" })).toThrow("identity mismatch");
+ expect(() => new NativeCapture({ ...f.options, producerVersion: "different" })).toThrow("identity mismatch");
+ expect(() => new NativeCapture({ ...f.options, configDir: f.root })).toThrow("identity mismatch");
+ const secret = path.join(f.root, "secret"); fs.writeFileSync(secret, "private"); fs.symlinkSync(secret, f.source);
+ expect(() => f.capture.scan()).toThrow("symlinks");
+ expect(f.capture.verify().files).toHaveLength(0);
+});
+
+test("quality distinguishes human candidates, synthetic compaction and notifications, opaque reasoning and unknown native semantics without rewriting them", () => {
+ const f = fixture();
+ const original = line(user("human")) + line(user("human"))
+ + line({ ...user("compact"), isCompactSummary: true })
+ + line({ ...user("notice"), message: { content: "<task-notification>background result</task-notification>" } })
+ + line({ type: "system", subtype: "compact_boundary", uuid: "boundary" })
+ + line({ type: "assistant", uuid: "answer", message: { content: [{ type: "thinking", thinking: "exposed", signature: "sig" }, { type: "redacted_thinking", data: "opaque" }, { type: "future_block", payload: { preserve: true } }] } })
+ + line({ type: "future_record", payload: { preserve: true } });
+ fs.writeFileSync(f.source, original);
+ const manifest = f.capture.finish(finish);
+ expect(manifest.status).toBe("complete");
+ expect(manifest.qc).toMatchObject({ humanPromptCandidates: 1, syntheticUserRecords: 2, compactionRecords: 2, exposedThinkingBlocks: 1, opaqueThinkingBlocks: 1, unknownRecordTypes: ["future_record"], unknownBlockTypes: ["future_block"], reviewRequired: true });
+ const out = path.join(f.root, "export"); f.capture.exportTo(out);
+ expect(fs.readFileSync(path.join(out, "claude/projects/-workspace", `${f.options.sessionId}.jsonl`), "utf8")).toBe(original);
+});
+
+test("orphan results and conflicting execution identities remain captured but cannot be called complete", () => {
+ const f = fixture();
+ const original = line({ type: "assistant", uuid: "a", message: { content: [{ type: "tool_use", id: "same", name: "Read", input: { file_path: "/one" } }] } })
+ + line({ type: "assistant", uuid: "b", message: { content: [{ type: "tool_use", id: "same", name: "Read", input: { file_path: "/two" } }] } })
+ + line({ type: "user", uuid: "c", message: { content: [{ type: "tool_result", tool_use_id: "orphan", content: "not fabricated" }] } });
+ fs.writeFileSync(f.source, original);
+ const manifest = f.capture.finish(finish);
+ expect(manifest.status).toBe("incomplete");
+ expect(manifest.issues.some((issue) => issue.startsWith("orphan_results:"))).toBe(true);
+ expect(manifest.issues.some((issue) => issue.startsWith("conflicting_tool_identity:"))).toBe(true);
+ const out = path.join(f.root, "export"); f.capture.exportTo(out);
+ expect(fs.readFileSync(path.join(out, "claude/projects/-workspace", `${f.options.sessionId}.jsonl`), "utf8")).toBe(original);
+});
+
+function checkReplay(script: string): void {
+ const adapter = fileURLToPath(new URL("../../../../tools/claude-native/verify.py", import.meta.url));
+ const result = spawnSync("python3", ["-c", "import importlib.util, sys\nspec=importlib.util.spec_from_file_location('native_verify',sys.argv[1])\nm=importlib.util.module_from_spec(spec)\nspec.loader.exec_module(m)\n" + script, adapter], { encoding: "utf8" });
+ expect({ status: result.status, error: result.stderr }).toEqual({ status: 0, error: "" });
+}
+
+test("native replay preserves command and hook cwd, reports unobserved shell evidence as soft, and never promotes ran-only or missing coverage", () => {
+ checkReplay(`
+import subprocess, types
+seen=[]
+def run(argv, **kwargs):
+ seen.append(argv)
+ return subprocess.CompletedProcess(argv,0,b'ok\\n',b'')
+m.subprocess.run=run
+call={'id':'one','tool':'Bash','input':{'command':'sudo -n printf ok'},'native_cwd':'/outside/workspace','status':'completed','meta':{'native_tool_result':{'stdout':'ok','stderr':''}}}
+out=m.native_bash(types.SimpleNamespace(classify=lambda cmd:'command'),'container',call,{})
+assert len(seen)==1 and seen[0][-1]=='sudo -n printf ok'
+assert seen[0][seen[0].index('-w')+1]=='/outside/workspace'
+assert out['outcome']=='diverge-soft' and out['actual_shell_argv_observed'] is False
+assert out['numeric_recorded_exit'] is None
+assert m.replay_verdict({'per_call':[['one','match']]},{},[call])==('VERIFIED',True,[])
+assert m.replay_verdict({'per_call':[['one','diverge-soft']]},{},[call])[0]=='VERIFIED_WITH_SOFT_DIFFS'
+assert m.replay_verdict({'per_call':[['one','tool-worked']]},{},[call])[:2]==('TOOLS_RAN',False)
+assert m.replay_verdict({'per_call':[]},{},[call])[:2]==('UNVERIFIED',False)
+assert m.replay_verdict({'per_call':[['one','match']]},{'/workspace':['lost']},[call])[:2]==('DIFFERS',False)
+`);
+});
+
+test("native literal replay never invents redacted bytes or loosely matches edits", () => {
+ checkReplay(`
+import json, pathlib, subprocess, tempfile
+with tempfile.TemporaryDirectory() as directory:
+ file=pathlib.Path(directory)/'example.py'
+ content='@toolkit.register(\\ncredentials: [credential, ...current.credentials]\\n[REDACTED]\\n'
+ result=subprocess.run([sys.executable,'-c',m.NATIVE_EDIT],input=json.dumps({'tool':'Write','input':{'file_path':str(file),'content':content}}).encode(),capture_output=True)
+ assert result.returncode==0 and file.read_text()==content
+ result=subprocess.run([sys.executable,'-c',m.NATIVE_EDIT],input=json.dumps({'tool':'Edit','input':{'file_path':str(file),'old_string':'@toolkit. register(','new_string':'invented'}}).encode(),capture_output=True)
+ assert result.returncode!=0 and file.read_text()==content
+ result=subprocess.run([sys.executable,'-c',m.NATIVE_EDIT],input=json.dumps({'tool':'Edit','input':{'file_path':str(file),'old_string':'[REDACTED]','new_string':'literal placeholder in source'}}).encode(),capture_output=True)
+ assert result.returncode==0 and file.read_text()==content.replace('[REDACTED]','literal placeholder in source')
+`);
+});
+
+test("native replay derives executions from preserved generations and rejects result identities without calls", () => {
+ checkReplay(`
+import io, json, zipfile
+def lines(items): return ''.join(json.dumps(x)+'\\n' for x in items)
+tool={'id':'one','type':'tool_use','name':'Write','input':{'file_path':'/workspace/x','content':'original'}}
+result={'type':'tool_result','tool_use_id':'one','content':'written'}
+events=[{'type':'assistant','uuid':'a','message':{'content':[tool]}},{'type':'user','uuid':'b','message':{'content':[result]}}]
+hooks=[{'time':'2026-01-01T00:00:00Z','turn':1,'input':{'hook_event_name':kind,'tool_use_id':'one','tool_name':'Write','tool_input':tool['input'],'cwd':'/workspace'}} for kind in ('PreToolUse','PostToolUse')]
+file='claude/projects/-workspace/root.jsonl'
+manifest={'files':[{'path':file}],'history':[{'path':file,'generation':0}]}
+def bundle(records):
+ data=io.BytesIO()
+ with zipfile.ZipFile(data,'w') as z:
+ z.writestr('events/hooks.jsonl',lines(hooks));z.writestr(file,lines([{'type':'user','message':{'content':'compacted'}}]));z.writestr('history/0/'+file,lines(records))
+ return zipfile.ZipFile(data)
+with bundle(events) as z:
+ calls=m.calls_from(z,{'id':'root'},manifest)
+ assert len(calls)==1 and calls[0]['input']==tool['input']
+ assert calls[0]['source']['path'].startswith('history/0/')
+with bundle(events+[{'type':'user','message':{'content':[dict(result,tool_use_id='orphan')]}}]) as z:
+ try: m.calls_from(z,{'id':'root'},manifest)
+ except ValueError as error: assert 'complete set' in str(error)
+ else: raise AssertionError('orphan result accepted')
+`);
+});
+
+test("native replay keeps corroborated forced Agent model omission explicit and soft; other differences fail closed", () => {
+ checkReplay(`
+import copy, io, json, zipfile
+def lines(rows): return ''.join(json.dumps(row)+'\\n' for row in rows).encode()
+model='claude-opus-fixture'
+session={'id':'root','owner':'owner','workspaceId':'workspace','model':model,'sdkVersion':'0.3.306','claudeVersion':'2.1.306','base':{'image':'sha256:base'},'authorization':{'upstreamModel':model}}
+contract={'schema':1,'sessionId':'root','owner':'owner','workspaceId':'workspace','model':model,'execution':{'baseImage':'sha256:base','kind':'docker','os':'linux','shell':'/bin/bash','workingDirectory':'/workspace'},'harness':{'name':'claude-code','sdkVersion':'0.3.306','claudeVersion':'2.1.306','controllerSha256':'fd1d3a901953f38fc866d6ce62ec5f80ef247f878d029ae47bb581832b26ab00'},'capture':{'scope':'managed-inference','modelIsolation':'exact'}}
+session['contract']=contract;session['contractSha256']=m.sha(json.dumps(contract,separators=(',',':')).encode())
+journal=[{'schema':1,'sessionId':'root','type':'request','requestId':'r','route':'messages','requestedModel':model,'resolvedModel':model,'contractSha256':session['contractSha256']},{'schema':1,'sessionId':'root','type':'provider_identity','requestId':'r','requestedModel':model,'resolvedModel':model,'providerModel':model,'source':'response-body'},{'schema':1,'sessionId':'root','type':'response','requestId':'r','status':200,'completed':True,'streamComplete':True,'identity':'reported','providerModels':[model]}]
+session['modelIsolation']={'status':'observed','expectedModel':model,'resolvedModel':model,'observedModels':[model],'evidenceSha256':m.sha(lines(journal)),'evidenceBytes':len(lines(journal))}
+requested={'description':'check','prompt':'preserve exactly','subagent_type':'general-purpose','model':'haiku'}
+effective={k:v for k,v in requested.items() if k!='model'}
+tool={'type':'tool_use','id':'one','name':'Agent','input':requested}
+result={'type':'tool_result','tool_use_id':'one','content':'launched'}
+native={'status':'async_launched','agentId':'child','resolvedModel':model}
+events=[{'type':'assistant','uuid':'a','message':{'content':[tool]}},{'type':'user','uuid':'b','message':{'content':[result]},'toolUseResult':native}]
+hooks=[{'time':'2026-01-01T00:00:00Z','turn':1,'input':{'hook_event_name':kind,'tool_use_id':'one','tool_name':'Agent','tool_input':copy.deepcopy(effective),'cwd':'/workspace'}} for kind in ('PreToolUse','PostToolUse')]
+hooks[1]['input']['tool_response']=copy.deepcopy(native)
+sdk=[dict(events[0],session_id='root'),{'type':'user','message':{'content':[result]},'tool_use_result':native},{'type':'assistant','parent_tool_use_id':'one','agent_id':'child','message':{'model':model,'content':[{'type':'text','text':'done'}]}}]
+file='claude/projects/-workspace/root.jsonl'
+base={'session':session,'events':events,'hooks':hooks,'sdk':sdk,'journal':journal}
+def calls(data):
+ buf=io.BytesIO();stream=lines(data['sdk'])
+ manifest={'files':[{'path':file},{'path':'events/sdk.jsonl','sha256':m.sha(stream),'bytes':len(stream)}]}
+ if data.get('bad_sdk_hash'): manifest['files'][1]['sha256']='0'*64
+ if data.get('unmanifested_sdk'): manifest['files'].pop()
+ with zipfile.ZipFile(buf,'w') as z:
+ z.writestr(file,lines(data['events']));z.writestr('events/hooks.jsonl',lines(data['hooks']))
+ if not data.get('missing_sdk'): z.writestr('events/sdk.jsonl',stream)
+ z.writestr('policy/contract.json',json.dumps({'contract':data['session']['contract'],'sha256':data['session']['contractSha256']}))
+ z.writestr('policy/model-requests.jsonl',lines(data['journal']))
+ with zipfile.ZipFile(buf) as z: return m.calls_from(z,data['session'],manifest)
+before=copy.deepcopy(base)
+accepted=calls(base);call=accepted[0]
+assert base==before and call['input']==requested and call['native_effective_input']==effective
+assert call['native_input_normalization']['requested_input']['model']=='haiku'
+assert call['native_input_normalization']['strict_verified'] is False
+assert all(call['native_input_normalization']['sdk_witnesses'].values())
+selected=accepted+[{'id':'write'}];replay={'per_call':[['one','subagent'],['write','match']]}
+assert m.replay_verdict(replay,{},selected)==('VERIFIED_WITH_SOFT_DIFFS',True,[])
+assert m.replay_verdict(replay,{'/workspace':['changed']},selected)[0]=='DIFFERS'
+assert m.replay_verdict({'per_call':[['one','subagent']]},{},selected)[0]=='UNVERIFIED'
+def reject(change):
+ data=copy.deepcopy(base);change(data)
+ try: calls(data)
+ except ValueError: pass
+ else: raise AssertionError('uncorroborated or tampered omission accepted')
+for field in ('prompt','description','subagent_type','extra'):
+ reject(lambda d,field=field:d['hooks'][0]['input']['tool_input'].update({field:'altered'}))
+reject(lambda d:d['hooks'][0]['input'].update(tool_name='Task'))
+reject(lambda d:d['hooks'][1]['input']['tool_input'].update(model='haiku'))
+reject(lambda d:d['hooks'][1]['input']['tool_input'].update(prompt='altered'))
+reject(lambda d:d['hooks'][1]['input']['tool_response'].update(resolvedModel='haiku'))
+reject(lambda d:d['hooks'][1]['input'].update(hook_event_name='PostToolUseFailure'))
+reject(lambda d:d['session']['contract']['harness'].update(controllerSha256='0'*64))
+reject(lambda d:d['session'].update(sdkVersion='future'))
+reject(lambda d:d['session'].pop('modelIsolation'))
+reject(lambda d:d['journal'][1].update(providerModel='haiku'))
+reject(lambda d:d.update(sdk=[]))
+reject(lambda d:d.update(sdk=d['sdk'][:-1]))
+reject(lambda d:d['sdk'][2]['message'].update(model='haiku'))
+reject(lambda d:d['sdk'][2].update(agent_id='wrong-child'))
+reject(lambda d:d['sdk'][0].update(session_id='another-session'))
+reject(lambda d:d['sdk'][1].update(tool_use_result={}))
+reject(lambda d:d.update(sdk=[dict(d['sdk'][0],message={'content':[dict(tool,input=dict(requested,model='sonnet'))]})]+d['sdk'][1:]))
+for flag in ('missing_sdk','unmanifested_sdk','bad_sdk_hash'): reject(lambda d,flag=flag:d.update({flag:True}))
+# Exact inputs retain the existing path without requiring normalization witnesses.
+exact=copy.deepcopy(base)
+for hook in exact['hooks']: hook['input']['tool_input']=copy.deepcopy(requested)
+assert 'native_input_normalization' not in calls(exact)[0]
+`);
+});
+
+test("model provenance is checked independently of replay and never inferred for legacy or mixed-model evidence", () => {
+ checkReplay(`
+import copy, io, json, zipfile
+session={'id':'session','owner':'owner','workspaceId':'workspace','model':'claude-opus-fixture','sdkVersion':'sdk','claudeVersion':'cli','base':{'image':'sha256:base'},'authorization':{'upstreamModel':'claude-opus-fixture'}}
+contract={'schema':1,'sessionId':'session','owner':'owner','workspaceId':'workspace','model':session['model'],'execution':{'baseImage':'sha256:base','kind':'docker','os':'linux','shell':'/bin/bash','workingDirectory':'/workspace'},'harness':{'name':'claude-code','sdkVersion':'sdk','claudeVersion':'cli'},'capture':{'scope':'managed-inference','modelIsolation':'exact'}}
+session['contract']=contract;session['contractSha256']=m.sha(json.dumps(contract,separators=(',',':')).encode())
+resolved=session['authorization']['upstreamModel']
+events=[{'type':'request','requestId':'r','route':'messages','requestedModel':session['model'],'resolvedModel':resolved,'contractSha256':session['contractSha256']},{'type':'provider_identity','requestId':'r','requestedModel':session['model'],'resolvedModel':resolved,'providerModel':resolved,'source':'response-body'},{'type':'response','requestId':'r','status':200,'completed':True,'streamComplete':True,'identity':'reported','providerModels':[resolved]}]
+def bundle(records):
+ data=io.BytesIO();raw=''.join(json.dumps(dict(schema=1,sessionId='session',**x))+'\\n' for x in records).encode()
+ session['modelIsolation']={'status':'observed','expectedModel':session['model'],'resolvedModel':resolved,'observedModels':[resolved],'evidenceSha256':m.sha(raw),'evidenceBytes':len(raw)}
+ with zipfile.ZipFile(data,'w') as z:
+ z.writestr('policy/contract.json',json.dumps({'contract':contract,'sha256':session['contractSha256']}));z.writestr('policy/model-requests.jsonl',raw)
+ return zipfile.ZipFile(data)
+with bundle(events) as z:
+ assert m.model_evidence(z,session)['eligible'] is True
+ session['authorization']['upstreamModel']='claude-haiku-fixture'
+ session['modelIsolation']['resolvedModel']='claude-haiku-fixture'
+ assert m.model_evidence(z,session)['blockers']==['bound_upstream_model_mismatch']
+ session['authorization']['upstreamModel']=resolved
+ session['modelIsolation']['resolvedModel']=resolved
+ session['modelIsolation']['evidenceSha256']='0'*64
+ assert m.model_evidence(z,session)['status']=='invalid'
+mixed=copy.deepcopy(events);mixed[1]['providerModel']='another-model'
+with bundle(mixed) as z:
+ result=m.model_evidence(z,session)
+ assert result['status']=='invalid' and not result['eligible']
+with bundle(events[:-1]) as z:
+ assert 'model_journal_incomplete' in m.model_evidence(z,session)['blockers']
+refreshed=copy.deepcopy(events);refreshed[-1]['authorizationFailures']=[401]
+with bundle(refreshed) as z:
+ assert m.model_evidence(z,session)['eligible'] is True
+unknown=copy.deepcopy(events);unknown.insert(1,{'type':'authorization_retry','requestId':'r','status':401})
+with bundle(unknown) as z:
+ assert 'unknown_model_event' in m.model_evidence(z,session)['blockers']
+with bundle(events) as z:
+ assert m.model_evidence(z,{'id':'legacy'})['status']=='legacy_unverified'
+`);
+});
+
+test("canonical sealed archives resume native uploads, preserve ZIP bytes and keep checkpoint gates independent", async () => {
+ const {createHash} = await import("node:crypto");
+ const {zstdDecompressSync} = await import("node:zlib");
+ const {parseNativeCaptureCapabilities, uploadNativeBundle} = await import("./upload.js");
+ const {writeBundleManifest} = await import("./bundle-manifest.js");
+ const {zipDirectory} = await import("./zip.js");
+ const {ArchiveUploader} = await import("../session-archive/upload.js");
+ const {SealStream, sealKeyring, openSealedBuffer} = await import("../session-archive/seal.js");
+ const {tarMemberHeader} = await import("../session-archive/pack.js");
+ const f = fixture(), nativeDirectory = path.join(f.root, "native-export"), stateDirectory = path.join(f.root, "uploads");
+ fs.writeFileSync(f.source, line(user("first"))); f.capture.finish(finish); f.capture.exportTo(nativeDirectory);
+ const raw = Buffer.from('[email protected](\ncredentials = ["value"]\n{"type":"redacted_thinking","data":"opaque"}\n');
+ fs.writeFileSync(path.join(nativeDirectory, "literal-evidence.txt"), raw);
+ const binding = {sessionId: f.options.sessionId, bindingId: "01928f3e-7c41-7b2a-9d05-4e6f8a1b2c3d", contractHash: "a".repeat(64), engineVersion: "2.1.306"};
+ await writeBundleManifest(nativeDirectory, binding, "claude_native");
+ const checkpointDirectory = path.join(f.root, "checkpoint"); fs.cpSync(nativeDirectory, checkpointDirectory, {recursive: true});
+ const checkpointManifestSha256 = await writeBundleManifest(checkpointDirectory, binding, "claude_checkpoint");
+ const checkpointFile = path.join(f.root, "checkpoint.zip"); await zipDirectory(checkpointDirectory, checkpointFile);
+ const keyring = sealKeyring([Buffer.alloc(32, 7)]), key = [...keyring.values()][0]!;
+ const hash = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
+ type Held = {request: import("./upload.js").NativeArchiveCreate; parts: Map<number, Buffer>; uploaded: boolean};
+ const held = new Map<string, Held>(); let failPart = true, wrongReceipt = true, rejectNative = false, keyReads = 0, puts = 0;
+ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), {status, headers: {"Content-Type": "application/json"}});
+ const url = (id: string, part: number) => `https://archive-fixture.invalid/${id}/${part}`;
+ const uploader = new ArchiveUploader({
+ retry: {attempts: 1, sleep: async () => {}},
+ request: async (route, init) => {
+ if (route === "archives/key") { keyReads++; return json({kid: key.kid, public_key: key.publicRaw.toString("base64"), alg: "X25519-HKDF-SHA256-A256GCM", limits: {max_upload_bytes: null, max_session_bytes: null, claude: options.capabilities}, policy: {all_folders: false, touched_files: false}}); }
+ if (route === "archives") {
+ const request: import("./upload.js").NativeArchiveCreate = JSON.parse(init.body!);
+ expect(request.harness).toBe("claude-code"); expect(request.binding_id).toBe(binding.bindingId);
+ expect(request.contract_hash).toBe(binding.contractHash); expect(request.kind).toBe("base");
+ expect(request.parent_archive_id).toBeNull(); expect(request.marker).toBe("project"); expect(request).not.toHaveProperty("media_bytes");
+ expect(request.content).toBe(request.payload === "claude_native" ? "tar+zstd" : "zip");
+ if (request.payload === "claude_native") expect(request).not.toHaveProperty("box_image");
+ else expect(request.box_image).toMatch(/^sha256:[0-9a-f]{64}$/);
+ if (rejectNative && request.payload === "claude_native") return json({detail: "archive_payload_disabled"}, 409);
+ const existing = held.get(request.archive_id);
+ if (existing) expect(request).toEqual(existing.request);
+ else for (const prior of held.values()) {
+ if (prior.request.session_id === request.session_id && prior.request.payload === request.payload) expect(request.sequence).toBeGreaterThan(prior.request.sequence);
+ }
+ if (existing?.uploaded) return json({archive_id: request.archive_id, status: "uploaded"});
+ if (!existing) held.set(request.archive_id, {request, parts: new Map(), uploaded: false});
+ const count = Math.ceil(request.size / 128);
+ return json({archive_id: request.archive_id, status: "uploading", upload_id: request.archive_id, object_key: request.archive_id, part_size: 128, part_count: count, parts: Array.from({length: count}, (_, i) => ({part_number: i + 1, url: url(request.archive_id, i + 1)}))}, 201);
+ }
+ const match = /^archives\/([^/]+)\/(parts|complete)$/.exec(route); if (!match) throw new Error("Unexpected archive API route");
+ const item = held.get(match[1]!)!;
+ if (match[2] === "parts") {
+ const wanted: {part_numbers: number[]} = JSON.parse(init.body!);
+ return json({archive_id: match[1], parts: wanted.part_numbers.map(n => ({part_number: n, url: url(match[1]!, n)})), uploaded: [...item.parts].map(([n, bytes]) => ({part_number: n, etag: `"${n}"`, size: bytes.length}))});
+ }
+ const bytes = Buffer.concat([...item.parts].sort(([a], [b]) => a - b).map(([, data]) => data));
+ expect(bytes.length).toBe(item.request.size); expect(hash(bytes)).toBe(item.request.sha256);
+ item.uploaded = true;
+ if (wrongReceipt) { wrongReceipt = false; return json({archive_id: "another-session", status: "uploaded", size: bytes.length}); }
+ return json({archive_id: match[1], status: "uploaded", size: bytes.length});
+ },
+ fetch: async (address, init) => {
+ expect(init?.method).toBe("PUT"); expect(init?.headers).toBeUndefined(); puts++;
+ if (failPart) { failPart = false; return new Response("", {status: 503}); }
+ const [, id, part] = new URL(address).pathname.split("/");
+ const bytes = await new Response(init?.body).arrayBuffer(); held.get(id!)!.parts.set(Number(part), Buffer.from(bytes));
+ return new Response("", {headers: {etag: `"${part}"`}});
+ },
+ });
+ const options: import("./upload.js").NativeUploadOptions = {
+ ...binding, owner: f.options.owner, turn: 1, nativeDirectory, stateDirectory, checkpointFile, checkpointManifestSha256, boxImage: `sha256:${"b".repeat(64)}`,
+ capabilities: {schema: 1, native: {enabled: true, max_bytes: 1024 * 1024}, checkpoint: {enabled: false, max_bytes: 1024 * 1024, retention_days: null}},
+ driver: {fetchKey: signal => uploader.fetchKey(signal), upload: (job, persist, signal) => uploader.upload(job, persist, signal), sealer: options => new SealStream(options), tarHeader: tarMemberHeader},
+ };
+ expect(parseNativeCaptureCapabilities(options.capabilities)).toEqual(options.capabilities);
+ for (const invalid of [undefined, {schema: 1}, {...options.capabilities, schema: 2},
+ {...options.capabilities, native: {enabled: true, max_bytes: 0}},
+ {...options.capabilities, checkpoint: {enabled: false, max_bytes: 1024 * 1024}},
+ {...options.capabilities, checkpoint: {...options.capabilities.checkpoint, enabled: "false"}}]) {
+ expect(parseNativeCaptureCapabilities(invalid)).toBeNull();
+ }
+ options.capabilities.native.max_bytes = 1;
+ const nativeCap = await uploadNativeBundle(options);
+ expect(nativeCap.native.code).toBe("archive_too_large"); expect(held.size).toBe(0); expect(puts).toBe(0);
+ if (!nativeCap.native.bytes || !nativeCap.native.plainBytes) throw new Error("Missing retained sealed job");
+ expect(nativeCap.native.bytes).toBeGreaterThan(nativeCap.native.plainBytes);
+ options.capabilities.native.max_bytes = nativeCap.native.plainBytes;
+ expect((await uploadNativeBundle(options)).native.code).toBe("archive_too_large"); expect(held.size).toBe(0);
+ options.capabilities.native.max_bytes = nativeCap.native.bytes;
+ const interrupted = await uploadNativeBundle(options);
+ expect(interrupted.native.status).toBe("pending"); expect(interrupted.checkpoint.status).toBe("disabled"); expect(held.size).toBe(1);
+ expect(interrupted.native.archiveId).toBe(nativeCap.native.archiveId);
+ const mismatchedReceipt = await uploadNativeBundle(options);
+ expect(mismatchedReceipt.native.status).toBe("pending"); expect(mismatchedReceipt.native.code).toBe("invalid completion receipt");
+ const resumed = await uploadNativeBundle(options);
+ expect(resumed.status).toBe("uploaded"); expect(resumed.native.archiveId).toBe(interrupted.native.archiveId);
+ expect(resumed.native.sha256).toBe(interrupted.native.sha256); expect(keyReads).toBe(1);
+ const native = held.get(resumed.native.archiveId!)!;
+ const sealed = Buffer.concat([...native.parts].sort(([a], [b]) => a - b).map(([, bytes]) => bytes));
+ const plaintext = await openSealedBuffer(sealed, keyring), tar = zstdDecompressSync(plaintext);
+ expect(hash(plaintext)).toBe(native.request.plain_sha256); expect(plaintext.length).toBe(native.request.plain_size);
+ expect(tar.subarray(0, 100).toString("utf8").split("\0")[0]).toBe("__omnirush__/manifest.json");
+ expect(tar.includes(raw)).toBe(true);
+ const beforeCapPuts = puts;
+ options.capabilities.checkpoint = {enabled: true, max_bytes: 1, retention_days: 3};
+ const capped = await uploadNativeBundle(options);
+ expect(capped.status).toBe("partial"); expect(capped.native.status).toBe("uploaded"); expect(capped.checkpoint.code).toBe("archive_too_large");
+ expect(puts).toBe(beforeCapPuts); expect(fs.readFileSync(path.join(nativeDirectory, "literal-evidence.txt"))).toEqual(raw);
+ options.capabilities.checkpoint.max_bytes = fs.statSync(checkpointFile).size;
+ const sealedCheckpointCap = await uploadNativeBundle(options);
+ expect(sealedCheckpointCap.checkpoint.code).toBe("archive_too_large"); expect(puts).toBe(beforeCapPuts); expect(held.size).toBe(1);
+ if (!sealedCheckpointCap.checkpoint.bytes) throw new Error("Missing retained checkpoint seal");
+ expect(sealedCheckpointCap.checkpoint.bytes).toBeGreaterThan(options.capabilities.checkpoint.max_bytes);
+ options.capabilities.checkpoint.max_bytes = sealedCheckpointCap.checkpoint.bytes;
+ const completed = await uploadNativeBundle(options); expect(completed.checkpoint.status).toBe("uploaded"); expect(held.size).toBe(2);
+ expect(completed.checkpoint.archiveId).toBe(sealedCheckpointCap.checkpoint.archiveId);
+ const checkpoint = held.get(completed.checkpoint.archiveId!)!;
+ expect(checkpoint.request.sequence).toBe(0); expect(native.request.sequence).toBe(0); expect(checkpoint.request.content).toBe("zip");
+ const zipSeal = Buffer.concat([...checkpoint.parts].sort(([a], [b]) => a - b).map(([, bytes]) => bytes));
+ await expect(openSealedBuffer(zipSeal, keyring)).rejects.toThrow("bad_header");
+ const zip = await openSealedBuffer(zipSeal, keyring, {expectedContent: "zip"});
+ expect(zip).toEqual(fs.readFileSync(checkpointFile)); expect(hash(zip)).toBe(checkpoint.request.plain_sha256);
+ fs.appendFileSync(path.join(nativeDirectory, "literal-evidence.txt"), "changed");
+ const inconsistent = await uploadNativeBundle(options); expect(inconsistent.native.status).toBe("pending"); expect(inconsistent.checkpoint.status).toBe("uploaded");
+ expect(inconsistent.native.code).toBe("archive_manifest_members_mismatch");
+ expect(JSON.parse(fs.readFileSync(path.join(stateDirectory, "last-upload.json"), "utf8")).native.code).toBe("archive_manifest_members_mismatch");
+ expect(held.size).toBe(2); expect(fs.existsSync(checkpointFile)).toBe(true);
+ options.capabilities.native.max_bytes = 1024 * 1024;
+ await writeBundleManifest(nativeDirectory, binding, "claude_native"); rejectNative = true;
+ const disabled = await uploadNativeBundle(options); expect(disabled.native.status).toBe("disabled"); expect(disabled.native.code).toBe("archive_payload_disabled");
+ expect(disabled.checkpoint.status).toBe("uploaded"); expect(held.size).toBe(2);
+ expect(disabled.native.sequence).toBe(1);
+ rejectNative = false; fs.appendFileSync(path.join(nativeDirectory, "literal-evidence.txt"), "next snapshot");
+ await writeBundleManifest(nativeDirectory, binding, "claude_native");
+ const next = await uploadNativeBundle(options);
+ expect(next.native.status).toBe("uploaded"); expect(next.native.sequence).toBe(2); expect(held.size).toBe(3);
+ expect(next.checkpoint.archiveId).toBe(completed.checkpoint.archiveId);
+ expect(fs.readFileSync(path.join(stateDirectory, "upload-events.jsonl"), "utf8")).toContain("archive_manifest_members_mismatch");
+});
+
+function savedRuntimeFixture(access?: () => Promise<{owner: string; capabilities?: string[]}>) {
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "claude-offline-"))); roots.push(root);
+ const owner = "local-owner", id = "00000000-0000-4000-8000-000000000001";
+ const hash = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");
+ const dir = path.join(root, hash(owner), id); fs.mkdirSync(path.join(dir, "images"), {recursive: true});
+ const image = Buffer.from("saved environment fixture"); fs.writeFileSync(path.join(dir, "images/base.tar.gz"), image);
+ const session = {schema: 1, id, owner, workspaceId: "workspace", surface: "gui", model: MODEL, sdkVersion: "legacy", claudeVersion: CLAUDE_VERSION,
+ createdAt: new Date(0).toISOString(), container: `omnirush-claude-${id}`, base: {image: "sha256:" + "a".repeat(64), file: "images/base.tar.gz", sha256: hash(image), bytes: image.length},
+ turns: [], capture: "incomplete", replay: "unverified", issues: ["interrupted"]};
+ fs.writeFileSync(path.join(dir, "session.json"), JSON.stringify(session));
+ const configDir = path.join(dir, "config"), project = path.join(configDir, "projects", "-workspace"); fs.mkdirSync(project, {recursive: true});
+ const raw = '{ "type":"future-record", "opaque":"original bytes" }\n'; fs.writeFileSync(path.join(project, `${id}.jsonl`), raw);
+ const collector = new NativeCapture({directory: path.join(dir, "native"), configDir, sessionId: id, owner, producerVersion: CLAUDE_VERSION, surface: "gui", transport: "sdk"});
+ collector.finish({type: "finish", processStopped: true, successfulResult: false});
+ let accessCalls = 0, grants = 0;
+ const runtime = new ClaudeRuntime({directory: root, surface: "gui", docker: path.join(root, "docker-is-unavailable"),
+ access: async () => { accessCalls++; if (access) return access(); throw new Error("account unavailable"); },
+ authorize: async () => { grants++; throw new Error("must not mint"); }});
+ return {root, dir, id, owner, raw, session, runtime, counts: () => ({accessCalls, grants})};
+}
+
+test("offline export reclaims a proven-dead operation owner and preserves the original evidence", async () => {
+ const f = savedRuntimeFixture();
+ const dead = spawnSync(process.execPath, ["-e", "process.exit(0)"], {timeout: 5_000});
+ expect(dead.status).toBe(0);
+ fs.writeFileSync(path.join(f.dir, "operation.lock"), JSON.stringify({pid: dead.pid, nonce: "crashed-owner"}));
+ const originalState = fs.readFileSync(path.join(f.dir, "session.json")), originalManifest = fs.readFileSync(path.join(f.dir, "native/manifest.json"));
+ const exported = await f.runtime.export(f.id);
+ const check = spawnSync("python3", ["-c", "import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); assert z.read(sys.argv[2]) == sys.argv[3].encode(); assert z.read('images/base.tar.gz') == b'saved environment fixture'", exported, `claude/projects/-workspace/${f.id}.jsonl`, f.raw], {timeout: 5_000});
+ expect(check.status).toBe(0);
+ expect(fs.readFileSync(path.join(f.dir, "session.json"))).toEqual(originalState);
+ expect(fs.readFileSync(path.join(f.dir, "native/manifest.json"))).toEqual(originalManifest);
+ expect(fs.existsSync(path.join(f.dir, "operation.lock"))).toBe(false);
+ expect((await f.runtime.get(f.id)).id).toBe(f.id);
+ expect((await f.runtime.list("workspace")).map(session => session.id)).toEqual([f.id]);
+ expect(f.counts()).toEqual({accessCalls: 0, grants: 0});
+ await expect(f.runtime.start(f.id, "continue")).rejects.toThrow("account unavailable");
+ expect(f.counts().grants).toBe(0);
+});
+
+test("offline export refuses live and unknown lock owners without clearing their lock", async () => {
+ const f = savedRuntimeFixture(async () => ({owner: "local-owner"}));
+ for (const owner of [{pid: process.pid, nonce: "live"}, {pid: 0, nonce: "unknown"}, {pid: "bad"}, {pid: process.pid, nonce: "live", identity: {boot: "unverifiable"}}]) {
+ const lock = JSON.stringify(owner); fs.writeFileSync(path.join(f.dir, "operation.lock"), lock);
+ await expect(f.runtime.export(f.id)).rejects.toThrow();
+ expect(fs.readFileSync(path.join(f.dir, "operation.lock"), "utf8")).toBe(lock);
+ expect(fs.existsSync(path.join(f.dir, `${f.id}.zip`))).toBe(false);
+ }
+});
+
+test("offline lookup rejects owner and session path mismatches, ambiguous IDs and symlink escapes", async () => {
+ const f = savedRuntimeFixture(async () => ({owner: f.owner}));
+ const state = path.join(f.dir, "session.json"), original = fs.readFileSync(state);
+ for (const changed of [{owner: "another-owner"}, {id: "00000000-0000-4000-8000-000000000002"}, {workspaceId: ""}]) {
+ fs.writeFileSync(state, JSON.stringify({...f.session, ...changed}));
+ await expect(f.runtime.get(f.id)).rejects.toThrow();
+ }
+ fs.writeFileSync(state, original);
+ const outside = path.join(f.root, "outside.json"); fs.renameSync(state, outside); fs.symlinkSync(outside, state);
+ await expect(f.runtime.get(f.id)).rejects.toThrow(); fs.unlinkSync(state); fs.renameSync(outside, state);
+ const otherRoot = path.join(f.root, "b".repeat(64)); fs.mkdirSync(otherRoot);
+ fs.symlinkSync(f.dir, path.join(otherRoot, f.id)); await expect(f.runtime.get(f.id)).rejects.toThrow();
+ fs.unlinkSync(path.join(otherRoot, f.id)); fs.cpSync(f.dir, path.join(otherRoot, f.id), {recursive: true});
+ await expect(f.runtime.get(f.id)).rejects.toThrow();
+ fs.rmSync(otherRoot, {recursive: true});
+ fs.writeFileSync(outside, "outside-canary");
+ for (const target of [path.join(f.dir, "images", "escape"), path.join(f.dir, `${f.id}.zip.tmp`)]) {
+ fs.symlinkSync(outside, target);
+ await expect(f.runtime.export(f.id)).rejects.toThrow();
+ expect(fs.readFileSync(outside, "utf8")).toBe("outside-canary"); fs.unlinkSync(target);
+ }
+});
+
+function gate<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>(done => { resolve = done; });
+ return {promise, resolve};
+}
+
+test("shutdown fences startup blocked on access and never mints or starts Docker after access resolves", async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-startup-")); roots.push(root);
+ const entered = gate<void>(), access = gate<{owner: string; capabilities: string[]}>(); let grants = 0, dockerCalls = 0;
+ const runtime = new ClaudeRuntime({directory: root, surface: "gui", access: () => { entered.resolve(); return access.promise; }, authorize: async () => { grants++; throw new Error("must not mint"); }});
+ Reflect.set(runtime, "docker", async () => { dockerCalls++; throw new Error("must not start Docker"); });
+ const creation = runtime.create(root, "workspace").then(() => "created", () => "cancelled");
+ await entered.promise;
+ const shutdown = runtime.shutdown();
+ access.resolve({owner: "local-owner", capabilities: ["claude-code"]});
+ expect(await creation).toBe("cancelled"); await shutdown;
+ expect({grants, dockerCalls}).toEqual({grants: 0, dockerCalls: 0});
+ await expect(runtime.prepare()).rejects.toThrow();
+});
+
+test("offline export reclaims a dead legacy PID even with account available, but not a live PID", async () => {
+ const f = savedRuntimeFixture(async () => ({owner: "local-owner"}));
+ const dead = spawnSync(process.execPath, ["-e", "process.exit(0)"], {timeout: 5_000});
+ fs.writeFileSync(path.join(f.dir, "operation.lock"), JSON.stringify({pid: dead.pid, nonce: "dead"}));
+ expect(fs.existsSync(await f.runtime.export(f.id))).toBe(true);
+ const live = JSON.stringify({pid: process.pid, nonce: "live"}); fs.writeFileSync(path.join(f.dir, "operation.lock"), live);
+ await expect(f.runtime.export(f.id)).rejects.toThrow();
+ expect(fs.readFileSync(path.join(f.dir, "operation.lock"), "utf8")).toBe(live);
+});
+
+test("operation locks distinguish reused PIDs from the live process birth identity", async () => {
+ if (process.platform !== "linux") return;
+ const f = savedRuntimeFixture(async () => ({owner: "local-owner"}));
+ const stat = fs.readFileSync(`/proc/${process.pid}/stat`, "utf8");
+ const identity = {host: os.hostname(), boot: fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), namespace: fs.readlinkSync("/proc/self/ns/pid"), start: stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]};
+ const lockPath = path.join(f.dir, "operation.lock"), live = JSON.stringify({pid: process.pid, nonce: "live-birth", identity});
+ fs.writeFileSync(lockPath, live); await expect(f.runtime.export(f.id)).rejects.toThrow();
+ expect(fs.readFileSync(lockPath, "utf8")).toBe(live);
+ for (const changed of [{start: String(BigInt(identity.start) - 1n)}, {boot: "00000000-0000-4000-8000-000000000099"}]) {
+ fs.writeFileSync(lockPath, JSON.stringify({pid: process.pid, nonce: "previous-birth", identity: {...identity, ...changed}}));
+ expect(fs.existsSync(await f.runtime.export(f.id))).toBe(true);
+ }
+ const unknown = JSON.stringify({pid: process.pid, nonce: "other-namespace", identity: {...identity, namespace: "pid:[unknown]"}});
+ fs.writeFileSync(lockPath, unknown); await expect(f.runtime.export(f.id)).rejects.toThrow();
+ expect(fs.readFileSync(lockPath, "utf8")).toBe(unknown);
+});
+
+async function waitForFixture(file: string) {
+ for (let attempt = 0; attempt < 200; attempt++) {
+ if (fs.existsSync(file)) return;
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ throw new Error(`Fixture did not reach ${path.basename(file)}`);
+}
+async function cancellationResult(work: Promise<string>) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try { return await Promise.race([work, new Promise<string>(resolve => { timer = setTimeout(() => resolve("still-running"), 1_000); })]); }
+ finally { clearTimeout(timer); }
+}
+
+function startupDockerFixture(stage: "build" | "create" | "cp" | "exec" | "restore") {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-docker-fixture-")); roots.push(root);
+ const workspace = path.join(root, "workspace"); fs.mkdirSync(workspace);
+ const docker = path.join(root, "docker-fixture.mjs"), ready = path.join(root, "ready"), release = path.join(root, "release"), log = path.join(root, "calls.jsonl");
+ const runtime = new ClaudeRuntime({directory: path.join(root, "state"), surface: "gui", docker,
+ access: async () => ({owner: "local-owner", capabilities: ["claude-code"]}),
+ authorize: async () => { grants++; throw new Error("must not authorize after cancellation"); }});
+ let grants = 0;
+ const fingerprint = createHash("sha256").update(JSON.stringify(Reflect.get(runtime, "harnessContract").call(runtime))).digest("hex");
+ fs.writeFileSync(docker, `#!${process.execPath}
+import fs from 'node:fs';
+const root=${JSON.stringify(root)}, stage=${JSON.stringify(stage)}, args=process.argv.slice(2);
+const state=root+'/container.json', ready=root+'/ready';
+fs.appendFileSync(root+'/calls.jsonl',JSON.stringify(args)+'\\n');
+const own='c'.repeat(64), foreign='f'.repeat(64), image='sha256:'+'a'.repeat(64);
+const pause=async()=>{fs.writeFileSync(ready,JSON.stringify({pid:process.pid,args}));for(let i=0;i<200;i++){if(fs.existsSync(root+'/release'))return;await new Promise(r=>setTimeout(r,10));}process.exit(42);};
+if(args[0]==='create'){
+ const label=args.find(a=>a.startsWith('org.omnirush.claude.operation='));
+ fs.writeFileSync(state,JSON.stringify({Id:own,Config:{Labels:{'org.omnirush.claude.operation':label?.split('=')[1]}},Name:args[args.indexOf('--name')+1]}));
+ if(stage==='create')await pause();console.log(own);
+}else if(args[0]==='container'&&args[1]==='ls')console.log((fs.existsSync(state)?own+'\\n':'')+foreign);
+else if(args[0]==='image'&&args[1]==='ls')console.log(image);
+else if(args[1]==='inspect'){
+ if(args[0]==='container'&&stage==='restore'&&args[2].startsWith('omnirush-'))await pause();
+ if(args[2]===foreign)console.log(JSON.stringify([{Id:foreign,Config:{Labels:{'org.omnirush.claude.operation':'another-operation'}}}]));
+ else if(args[2]===own)console.log('['+fs.readFileSync(state,'utf8')+']');
+ else console.log(JSON.stringify([{Id:image,Os:'linux',Architecture:'amd64',Config:{Labels:{'org.omnirush.claude.runtime':stage==='build'?'old':${JSON.stringify(fingerprint)}}}}]));
+}else if(args[0]==='build'||args[0]===stage)await pause();
+else if(args[0]==='commit')console.log(image);
+else if(args[0]==='save')fs.writeFileSync(args[args.indexOf('--output')+1],'fixture image archive');
+else if(args[0]==='rm'||args[0]==='container'&&args[1]==='rm')fs.rmSync(state,{force:true});
+`, {mode: 0o700});
+ return {root, workspace, runtime, ready, release, log, grants: () => grants,
+ calls: (): string[][] => fs.existsSync(log) ? fs.readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line)) : []};
+}
+
+for (const stage of ["build", "create", "cp", "exec"] as const) test(`startup request abort kills Docker ${stage}, waits for owned cleanup and never authorizes`, async () => {
+ const f = startupDockerFixture(stage), controller = new AbortController();
+ const result = f.runtime.create(f.workspace, "workspace", controller.signal).then(() => "created", () => "cancelled");
+ try {
+ await waitForFixture(f.ready); const witness = JSON.parse(fs.readFileSync(f.ready, "utf8"));
+ controller.abort();
+ expect(await cancellationResult(result)).toBe("cancelled");
+ await f.runtime.shutdown();
+ expect(() => process.kill(witness.pid, 0)).toThrow();
+ expect(f.grants()).toBe(0);
+ expect(fs.existsSync(path.join(f.root, "container.json"))).toBe(false);
+ const calls = f.calls();
+ expect(calls.some(args => args.includes("/opt/claude/controller.mjs"))).toBe(false);
+ expect(calls.filter(args => args.includes("rm")).every(args => args.at(-1) === "c".repeat(64))).toBe(true);
+ expect(calls.some(args => args[0] === "commit")).toBe(false);
+ const owners = fs.readdirSync(path.join(f.root, "state")).filter(name => /^[a-f0-9]{64}$/.test(name));
+ for (const owner of owners) for (const id of fs.readdirSync(path.join(f.root, "state", owner))) expect(fs.existsSync(path.join(f.root, "state", owner, id, "session.json"))).toBe(false);
+ } finally { fs.writeFileSync(f.release, "release"); await result; await f.runtime.shutdown(); }
+}, 10_000);
+
+test("Stop and shutdown abort pending turn restoration before mint or controller execution", async () => {
+ for (const action of ["stop", "shutdown"] as const) {
+ const f = startupDockerFixture("restore");
+ const session = await f.runtime.create(f.workspace, "workspace");
+ const result = f.runtime.start(session.id, "must not run").then(() => "started", () => "cancelled");
+ try {
+ await waitForFixture(f.ready); const witness = JSON.parse(fs.readFileSync(f.ready, "utf8"));
+ const stopping = action === "stop" ? f.runtime.stop(session.id) : f.runtime.shutdown();
+ expect(await result).toBe("cancelled"); await stopping;
+ expect(() => process.kill(witness.pid, 0)).toThrow();
+ expect(f.grants()).toBe(0);
+ expect(f.calls().some(args => args.includes("/opt/claude/controller.mjs"))).toBe(false);
+ expect((await f.runtime.get(session.id)).turns).toEqual([]);
+ } finally { fs.writeFileSync(f.release, "release"); await result; await f.runtime.shutdown(); }
+ }
+}, 10_000);
+
+test("shutdown drains pending sandbox creation and fences subsequent startup", async () => {
+ const f = startupDockerFixture("create");
+ const result = f.runtime.create(f.workspace, "workspace").then(() => "created", () => "cancelled");
+ try {
+ await waitForFixture(f.ready); const witness = JSON.parse(fs.readFileSync(f.ready, "utf8"));
+ await f.runtime.shutdown();
+ expect(await result).toBe("cancelled");
+ expect(() => process.kill(witness.pid, 0)).toThrow();
+ expect(fs.existsSync(path.join(f.root, "container.json"))).toBe(false);
+ const before = f.calls();
+ await expect(f.runtime.prepare()).rejects.toThrow("shutting down");
+ await expect(f.runtime.create(f.workspace, "workspace")).rejects.toThrow("shutting down");
+ expect(f.calls()).toEqual(before); expect(f.grants()).toBe(0);
+ } finally { fs.writeFileSync(f.release, "release"); await result; await f.runtime.shutdown(); }
+}, 10_000);
+
+test("broker cancellation during account access prevents both mint and provider calls", async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-broker-abort-")); roots.push(root);
+ const access = gate<{owner: string}>(), entered = gate<void>(), controller = new AbortController();
+ let grants = 0, providerCalls = 0;
+ const relay = Bun.serve({hostname: "127.0.0.1", port: 0, fetch() { providerCalls++; return Response.json({type: "message", model: MODEL, content: [], stop_reason: "end_turn"}); }});
+ const id = "00000000-0000-4000-8000-000000000001", contractSha256 = "a".repeat(64);
+ const runtime = new ClaudeRuntime({directory: root, surface: "gui", access: () => { entered.resolve(); return access.promise; },
+ authorize: async () => { grants++; return {owner: "owner", sessionId: id, model: MODEL, upstreamModel: MODEL, client: "desktop/3.7.5", baseUrl: `http://127.0.0.1:${relay.port}`, token: "orc_" + "a".repeat(43), contractSha256}; }});
+ const broker = await Reflect.get(runtime, "broker").call(runtime, {owner: "owner", id, model: MODEL, workspaceId: "workspace", contract: {}, contractSha256, turns: []}, () => {}, controller.signal);
+ try {
+ const response = fetch(broker.baseUrl.replace("host.docker.internal", "127.0.0.1") + "/v1/messages", {method: "POST", headers: {authorization: `Bearer ${broker.token}`, "content-type": "application/json"}, body: JSON.stringify({model: MODEL, messages: [], max_tokens: 1}), signal: AbortSignal.timeout(3_000)});
+ await entered.promise; controller.abort(); access.resolve({owner: "owner"});
+ await (await response).arrayBuffer();
+ expect({grants, providerCalls}).toEqual({grants: 0, providerCalls: 0});
+ } finally { access.resolve({owner: "owner"}); await broker.close(); relay.stop(true); }
+});
+
+test("Claude routes export offline only within the requested workspace and pass startup request cancellation", async () => {
+ const {registerClaudeRoutes} = await import("./routes.js");
+ const {matchRoute} = await import("../routes/registry.js");
+ const f = savedRuntimeFixture(), routes: import("../routes/registry.js").Route[] = [];
+ let ownerChecks = 0;
+ registerClaudeRoutes({routes, runtime: f.runtime, workspace: async ctx => ({id: ctx.params.id, name: "Fixture", path: f.root, preset: "default", workspaceType: "local"}),
+ owner: () => { ownerChecks++; }, writable: () => {}, upload: async () => { throw new Error("not used"); }});
+ const call = (request: Request) => {
+ const route = matchRoute(routes, request.method, new URL(request.url).pathname); if (!route) throw new Error("route not found");
+ return Reflect.apply(route.handler, undefined, [{request, params: route.params}]);
+ };
+ const response: Response = await call(new Request(`http://localhost/workspace/workspace/claude/sessions/${f.id}/export`, {method: "POST"}));
+ expect(response.status).toBe(200); expect(response.headers.get("content-type")).toBe("application/zip");
+ expect((await response.arrayBuffer()).byteLength).toBeGreaterThan(0);
+ await expect(call(new Request(`http://localhost/workspace/another-workspace/claude/sessions/${f.id}/export`, {method: "POST"}))).rejects.toThrow("Session not found in this workspace");
+ expect(f.counts()).toEqual({accessCalls: 0, grants: 0}); expect(ownerChecks).toBe(2);
+ const controller = new AbortController(); controller.abort();
+ for (const suffix of ["prepare", "sessions", `sessions/${f.id}/turns`]) {
+ await expect(call(new Request(`http://localhost/workspace/workspace/claude/${suffix}`, {method: "POST", signal: controller.signal, headers: {"content-type": "application/json"}, body: JSON.stringify({captureConsent: true, prompt: "must not run"})}))).rejects.toThrow();
+ }
+ expect(f.counts()).toEqual({accessCalls: 0, grants: 0});
+});
+
+
+function guardWorker(f: ReturnType<typeof savedRuntimeFixture>) {
+ const script = path.join(f.root, "guard-worker.mjs");
+ fs.writeFileSync(script, `
+import fs from 'node:fs';
+import path from 'node:path';
+import {ClaudeRuntime} from ${JSON.stringify(new URL("./runtime.ts", import.meta.url).href)};
+const root=${JSON.stringify(f.root)}, dir=${JSON.stringify(f.dir)}, id=${JSON.stringify(f.id)};
+const [mode,name='crash']=process.argv.slice(2), guard=path.join(dir,'recovery.lock');
+const rename=fs.renameSync, open=fs.openSync, link=fs.linkSync;
+const wait=file=>{for(let n=0;n<1000;n++){if(fs.existsSync(file))return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10);}throw new Error('bounded fixture wait expired');};
+fs.openSync=function(file,...args){const fd=open.call(fs,file,...args);if(mode==='crash-publish'&&file===guard){fs.writeFileSync(path.join(root,'publication.json'),JSON.stringify({empty:fs.statSync(guard).size===0}));process.exit(77);}return fd;};
+fs.linkSync=function(from,to){const result=link.call(fs,from,to);if(mode==='crash-operation'&&to===path.join(dir,'operation.lock')){fs.writeFileSync(path.join(root,'operation-publication.json'),fs.readFileSync(to));process.exit(79);}return result;};
+fs.renameSync=function(from,to){
+ const reaping=from===guard&&path.basename(String(to)).startsWith('.recovery-dead-');
+ if(mode==='contend'&&reaping){fs.writeFileSync(path.join(root,'ready-'+name),'ready');wait(path.join(root,'go-'+name));}
+ const result=rename.call(fs,from,to);
+ if(mode==='crash-reclaim'&&reaping)process.exit(78);
+ if(to===guard){
+ if(mode==='crash-publish'){fs.writeFileSync(path.join(root,'publication.json'),fs.readFileSync(path.join(guard,'owner.json')));process.exit(77);}
+ if(mode==='contend'){fs.writeFileSync(path.join(root,'holding-'+name),fs.readFileSync(path.join(guard,'owner.json')));wait(path.join(root,'release-'+name));}
+ }
+ return result;
+};
+const runtime=new ClaudeRuntime({directory:root,surface:'gui',docker:path.join(root,'no-docker'),access:async()=>{throw new Error('offline');},authorize:async()=>{throw new Error('must not mint');}});
+try{const zip=await runtime.export(id);fs.writeFileSync(path.join(root,'result-'+name),JSON.stringify({status:'exported',zip}));}
+catch(error){fs.writeFileSync(path.join(root,'result-'+name),JSON.stringify({status:'rejected',message:error.message}));}
+`);
+ return script;
+}
+function staleOperation(f: ReturnType<typeof savedRuntimeFixture>) {
+ const child = spawnSync(process.execPath, ["-e", "process.exit(0)"], {timeout: 5_000});
+ expect(child.status).toBe(0);
+ const owner = {pid: child.pid, nonce: "dead-operation"};
+ fs.writeFileSync(path.join(f.dir, "operation.lock"), JSON.stringify(owner));
+ return owner;
+}
+function seedGuard(f: ReturnType<typeof savedRuntimeFixture>, owner: unknown) {
+ const guard = path.join(f.dir, "recovery.lock"); fs.mkdirSync(guard);
+ fs.writeFileSync(path.join(guard, "owner.json"), typeof owner === "string" ? owner : JSON.stringify(owner));
+ return guard;
+}
+
+test("recovery guard crash at publication or reclamation still permits byte-exact offline export", async () => {
+ for (const point of ["publication", "reclamation", "operation"]) {
+ const f = savedRuntimeFixture(); staleOperation(f); const script = guardWorker(f);
+ const state = fs.readFileSync(path.join(f.dir, "session.json")), manifest = fs.readFileSync(path.join(f.dir, "native", "manifest.json"));
+ const crash = spawnSync(process.execPath, [script, "crash-publish"], {timeout: 5_000});
+ expect(crash.status).toBe(77);
+ if (point === "reclamation") {
+ const second = spawnSync(process.execPath, [script, "crash-reclaim"], {timeout: 5_000});
+ expect(second.status).toBe(78);
+ }
+ if (point === "operation") {
+ const second = spawnSync(process.execPath, [script, "crash-operation"], {timeout: 5_000});
+ expect(second.status).toBe(79);
+ const published = JSON.parse(fs.readFileSync(path.join(f.root, "operation-publication.json"), "utf8"));
+ expect(published.pid).toBe(second.pid); expect(typeof published.nonce).toBe("string");
+ }
+ const zip = await f.runtime.export(f.id);
+ const publication = JSON.parse(fs.readFileSync(path.join(f.root, "publication.json"), "utf8"));
+ expect(publication.pid).toBe(crash.pid); expect(typeof publication.nonce).toBe("string");
+ expect(publication).not.toHaveProperty("empty");
+ if (process.platform === "linux") expect(publication.identity.start).toMatch(/^\d+$/);
+ expect(fs.readFileSync(path.join(f.dir, "session.json"))).toEqual(state);
+ expect(fs.readFileSync(path.join(f.dir, "native", "manifest.json"))).toEqual(manifest);
+ const check = spawnSync("python3", ["-c", "import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); assert z.read(sys.argv[2]) == sys.argv[3].encode()", zip, `claude/projects/-workspace/${f.id}.jsonl`, f.raw], {timeout: 5_000});
+ expect(check.status).toBe(0); expect(f.counts()).toEqual({accessCalls: 0, grants: 0});
+ expect(fs.existsSync(path.join(f.dir, "recovery.lock"))).toBe(false);
+ expect(fs.readdirSync(f.dir).some(name => name.startsWith(".recovery-dead-"))).toBe(true);
+ }
+});
+
+test("recovery guard refuses live and unknown owners, including legacy empty files, without changing either lock", async () => {
+ const f = savedRuntimeFixture(); staleOperation(f);
+ const operation = fs.readFileSync(path.join(f.dir, "operation.lock"));
+ for (const owner of [{pid: process.pid, nonce: "live"}, {pid: 0, nonce: "unknown"}, {pid: process.pid, nonce: "unknown-birth", identity: {boot: "unverifiable"}}, ""]) {
+ const guard = seedGuard(f, owner), bytes = fs.readFileSync(path.join(guard, "owner.json"));
+ await expect(f.runtime.export(f.id)).rejects.toThrow();
+ expect(fs.readFileSync(path.join(guard, "owner.json"))).toEqual(bytes);
+ expect(fs.readFileSync(path.join(f.dir, "operation.lock"))).toEqual(operation);
+ fs.rmSync(guard, {recursive: true});
+ }
+ const guard = path.join(f.dir, "recovery.lock"); fs.writeFileSync(guard, "");
+ await expect(f.runtime.export(f.id)).rejects.toThrow(); expect(fs.readFileSync(guard).length).toBe(0);
+ expect(fs.readFileSync(path.join(f.dir, "operation.lock"))).toEqual(operation);
+ fs.unlinkSync(guard); fs.mkdirSync(guard);
+ await expect(f.runtime.export(f.id)).rejects.toThrow(); expect(fs.readdirSync(guard)).toEqual([]);
+ expect(fs.readFileSync(path.join(f.dir, "operation.lock"))).toEqual(operation);
+});
+
+test.skipIf(process.platform !== "linux")("recovery guard distinguishes reused PID birth from live and unknown namespace owners", async () => {
+ const f = savedRuntimeFixture(), dead = staleOperation(f);
+ const stat = fs.readFileSync(`/proc/${process.pid}/stat`, "utf8");
+ const identity = {host: os.hostname(), boot: fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), namespace: fs.readlinkSync("/proc/self/ns/pid"), start: stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]};
+ for (const changed of [{}, {namespace: "pid:[unknown]"}]) {
+ const guard = seedGuard(f, {pid: process.pid, nonce: "live-or-unknown", identity: {...identity, ...changed}}), bytes = fs.readFileSync(path.join(guard, "owner.json"));
+ await expect(f.runtime.export(f.id)).rejects.toThrow();
+ expect(fs.readFileSync(path.join(guard, "owner.json"))).toEqual(bytes); fs.rmSync(guard, {recursive: true});
+ }
+ seedGuard(f, {pid: process.pid, nonce: "reused", identity: {...identity, start: String(BigInt(identity.start) - 1n)}});
+ expect(fs.existsSync(await f.runtime.export(f.id))).toBe(true);
+ // A dead guard is never permission to remove a separate live operation.
+ seedGuard(f, dead); const live = JSON.stringify({pid: process.pid, nonce: "live-operation", identity});
+ fs.writeFileSync(path.join(f.dir, "operation.lock"), live);
+ await expect(f.runtime.export(f.id)).rejects.toThrow();
+ expect(fs.readFileSync(path.join(f.dir, "operation.lock"), "utf8")).toBe(live);
+});
+
+test("recovery guard concurrent reclaimers cannot displace the winner's live replacement", async () => {
+ const f = savedRuntimeFixture(), dead = staleOperation(f); seedGuard(f, dead);
+ const script = guardWorker(f), operation = fs.readFileSync(path.join(f.dir, "operation.lock"));
+ const launch = (name: string) => {
+ const child = spawn(process.execPath, [script, "contend", name], {stdio: "ignore"});
+ const done = new Promise<number | null>(resolve => child.once("exit", resolve));
+ return {child, done};
+ };
+ const a = launch("a"), b = launch("b");
+ try {
+ await Promise.all([waitForFixture(path.join(f.root, "ready-a")), waitForFixture(path.join(f.root, "ready-b"))]);
+ fs.writeFileSync(path.join(f.root, "go-a"), "go"); await waitForFixture(path.join(f.root, "holding-a"));
+ const winner = fs.readFileSync(path.join(f.dir, "recovery.lock", "owner.json"));
+ expect(JSON.parse(winner.toString()).pid).toBe(a.child.pid);
+ fs.writeFileSync(path.join(f.root, "go-b"), "go"); await waitForFixture(path.join(f.root, "result-b"));
+ expect(JSON.parse(fs.readFileSync(path.join(f.root, "result-b"), "utf8")).status).toBe("rejected");
+ expect(fs.readFileSync(path.join(f.dir, "recovery.lock", "owner.json"))).toEqual(winner);
+ expect(fs.readFileSync(path.join(f.dir, "operation.lock"))).toEqual(operation);
+ fs.writeFileSync(path.join(f.root, "release-a"), "release"); await waitForFixture(path.join(f.root, "result-a"));
+ expect(JSON.parse(fs.readFileSync(path.join(f.root, "result-a"), "utf8")).status).toBe("exported");
+ expect(await a.done).toBe(0); expect(await b.done).toBe(0);
+ expect(fs.existsSync(path.join(f.dir, "recovery.lock"))).toBe(false);
+ expect(fs.existsSync(path.join(f.dir, "operation.lock"))).toBe(false);
+ } finally { a.child.kill("SIGKILL"); b.child.kill("SIGKILL"); await Promise.all([a.done, b.done]); }
+}, 10_000);
diff --git a/apps/server/src/claude-code/native-capture.ts b/apps/server/src/claude-code/native-capture.ts
new file mode 100644
index 00000000..9091f7ff
--- /dev/null
+++ b/apps/server/src/claude-code/native-capture.ts
@@ -0,0 +1,424 @@
+/** Private, lossless Claude Code evidence. Never send this through the display scrubber.
+ * The native files are the authority, including branches omitted by SDK readers.
+ * Only transcript paths for this root session are eligible; never copy the config tree.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { createHash, randomUUID } from "node:crypto";
+
+const CHUNK_BYTES = 1024 * 1024;
+const MAX_FILE_BYTES = 256 * CHUNK_BYTES;
+const MAX_TOTAL_BYTES = 1024 * CHUNK_BYTES;
+const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const CHILD_FILE = /^agent-[a-zA-Z0-9_-]+\.(jsonl|meta\.json)$/;
+const sha = (bytes: Uint8Array | string) => createHash("sha256").update(bytes).digest("hex");
+
+export type NativeCaptureOptions = {
+ directory: string;
+ configDir: string;
+ sessionId: string;
+ producerVersion: string;
+ surface: "cli" | "gui";
+ transport: "cli" | "sdk";
+ owner: string;
+};
+type Chunk = { sha256: string; bytes: number };
+/** Observation only: these counts never delete, merge or rewrite native records.
+ * Human prompt candidates are not billable turns; the runtime's durable ingress
+ * journal is the authority for user submissions (a harness can synthesize users).
+ */
+export type NativeQuality = {
+ schema: 1;
+ nativeRecords: number;
+ recordTypes: Record<string, number>;
+ blockTypes: Record<string, number>;
+ humanPromptCandidates: number;
+ syntheticUserRecords: number;
+ childPromptRecords: number;
+ compactionRecords: number;
+ exposedThinkingBlocks: number;
+ opaqueThinkingBlocks: number;
+ unknownRecordTypes: string[];
+ unknownBlockTypes: string[];
+ preservedRevisions: number;
+ reviewRequired: boolean;
+};
+export type NativeFile = {
+ path: string;
+ generation: number;
+ bytes: number;
+ sha256: string;
+ chunks: Chunk[];
+ completeLines: number;
+ tailBytes: number;
+ invalidLines: number;
+ thinkingBlocks: number;
+ toolCalls: number;
+ toolResults: number;
+ pendingTools: string[];
+ referencedAgents: string[];
+ orphanResults?: string[];
+ conflictingToolIds?: string[];
+ quality?: NativeQuality;
+};
+export type NativeCaptureManifest = {
+ schema: 1;
+ format: "claude-code";
+ sessionId: string;
+ producerVersion: string;
+ surface: "cli" | "gui";
+ transport: "cli" | "sdk";
+ owner: string;
+ source: string;
+ revision: number;
+ status: "capturing" | "complete" | "incomplete";
+ replay: "unverified";
+ confidential: true;
+ redacted: false;
+ files: NativeFile[];
+ history: NativeFile[];
+ issues: string[];
+ streams: { cli: number; sdk: number; hooks: number };
+ qc?: NativeQuality;
+};
+export type NativeCaptureAction =
+ | { type: "scan" }
+ | { type: "stream"; channel: "cli" | "sdk" | "hooks"; offset: number; bytes: Uint8Array }
+ | { type: "finish"; processStopped: boolean; successfulResult: boolean; expectedAgents?: string[] };
+
+function object(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function mkdir(dir: string): void {
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ if (!fs.lstatSync(dir).isDirectory() || fs.realpathSync(dir) !== path.resolve(dir)) throw new Error("Capture directory must not traverse symlinks");
+ fs.chmodSync(dir, 0o700);
+}
+function syncDir(dir: string): void {
+ // Directory fsync is unsupported on Windows. File fsync is still required.
+ if (process.platform === "win32") return;
+ const fd = fs.openSync(dir, "r");
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+}
+function atomic(file: string, bytes: Uint8Array | string): void {
+ mkdir(path.dirname(file));
+ const temp = `${file}.${randomUUID()}.tmp`;
+ const fd = fs.openSync(temp, "wx", 0o600);
+ try { fs.writeFileSync(fd, bytes); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+ try { fs.renameSync(temp, file); syncDir(path.dirname(file)); }
+ finally { fs.rmSync(temp, { force: true }); }
+}
+function readRegular(file: string): Buffer {
+ // Check ancestors as well as O_NOFOLLOW on the leaf; config is a session-owned volume.
+ if (fs.realpathSync(file) !== path.resolve(file)) throw new Error("Native transcript must not traverse symlinks");
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
+ try {
+ const before = fs.fstatSync(fd);
+ if (!before.isFile() || before.size > MAX_FILE_BYTES) throw new Error("Invalid or oversized native transcript");
+ const bytes = fs.readFileSync(fd);
+ const after = fs.fstatSync(fd);
+ if (bytes.length !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs) throw new Error("Native transcript changed while capturing; retry scan");
+ return bytes;
+ } finally { fs.closeSync(fd); }
+}
+
+function emptyQuality(): NativeQuality {
+ return { schema: 1, nativeRecords: 0, recordTypes: {}, blockTypes: {}, humanPromptCandidates: 0, syntheticUserRecords: 0, childPromptRecords: 0, compactionRecords: 0, exposedThinkingBlocks: 0, opaqueThinkingBlocks: 0, unknownRecordTypes: [], unknownBlockTypes: [], preservedRevisions: 0, reviewRequired: false };
+}
+const RECORD_TYPES = new Set(["user", "assistant", "system", "attachment", "progress", "queue-operation", "last-prompt", "atis-latch", "cost-state", "mode", "summary", "file-history-snapshot", "custom-title", "agent-name", "agent-color", "tag", "pr-link", "api-request", "api-request-blob", "api-request-shape"]);
+const BLOCK_TYPES = new Set(["text", "image", "document", "tool_use", "tool_result", "thinking", "redacted_thinking"]);
+function increment(counts: Record<string, number>, key: string): void { counts[key] = (counts[key] ?? 0) + 1; }
+function inspect(bytes: Buffer, jsonl: boolean, native = false): Pick<NativeFile, "completeLines" | "tailBytes" | "invalidLines" | "thinkingBlocks" | "toolCalls" | "toolResults" | "pendingTools" | "referencedAgents" | "orphanResults" | "conflictingToolIds" | "quality"> {
+ const quality = emptyQuality();
+ const result = { completeLines: 0, tailBytes: 0, invalidLines: 0, thinkingBlocks: 0, toolCalls: 0, toolResults: 0, pendingTools: [] as string[], referencedAgents: [] as string[], orphanResults: [] as string[], conflictingToolIds: [] as string[], ...(native ? { quality } : {}) };
+ if (!jsonl) {
+ try { JSON.parse(bytes.toString("utf8")); } catch { result.invalidLines = 1; }
+ return result;
+ }
+ const end = bytes.lastIndexOf(10) + 1;
+ result.tailBytes = bytes.length - end;
+ const calls = new Set<string>(), results = new Set<string>(), thinking = new Set<string>();
+ const toolIdentities = new Map<string, string>(), promptIds = new Set<string>();
+ const agents = new Set<string>();
+ let text: string;
+ try { text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, end)); }
+ catch { result.invalidLines = 1; return result; }
+ // Inspect every record, not just the selected parentUuid chain. Keep bytes unchanged.
+ for (const line of text.split("\n")) {
+ if (!line.trim()) continue;
+ result.completeLines++;
+ let record: unknown;
+ try { record = JSON.parse(line); } catch { result.invalidLines++; continue; }
+ if (!object(record)) { result.invalidLines++; continue; }
+ if (native) {
+ const type = typeof record.type === "string" ? record.type : "<missing>";
+ quality.nativeRecords++; increment(quality.recordTypes, type);
+ if (!RECORD_TYPES.has(type) && !quality.unknownRecordTypes.includes(type)) quality.unknownRecordTypes.push(type);
+ if (type === "summary" || record.isCompactSummary === true || (type === "system" && typeof record.subtype === "string" && /compact/i.test(record.subtype))) quality.compactionRecords++;
+ }
+ const toolResult = record.toolUseResult ?? record.tool_use_result;
+ if (object(toolResult) && typeof toolResult.agentId === "string") agents.add(toolResult.agentId);
+ if (record.type === "system" && record.subtype === "task_started" && typeof record.agent_id === "string") agents.add(record.agent_id);
+ // Native request-cache blobs repeat older messages. Preserve every byte,
+ // but do not count cached context as a new execution or reasoning block.
+ if (record.type !== "assistant" && record.type !== "user") continue;
+ if (!object(record.message)) { result.invalidLines++; continue; }
+ const content = record.message.content;
+ const blocks = Array.isArray(content) ? content.filter(object) : [];
+ if (record.type === "user" && native && !blocks.some((block) => block.type === "tool_result")) {
+ const text = typeof content === "string" ? content : blocks.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
+ const synthetic = record.isMeta === true || record.isCompactSummary === true || /^\s*<(task-notification|local-command|command-name|system-reminder)[\s>]/.test(text);
+ if (synthetic) quality.syntheticUserRecords++;
+ else if (record.isSidechain === true || typeof record.agentId === "string") quality.childPromptRecords++;
+ else if (text.trim()) {
+ const id = typeof record.uuid === "string" ? record.uuid : `line:${result.completeLines}`;
+ if (!promptIds.has(id)) { promptIds.add(id); quality.humanPromptCandidates++; }
+ }
+ }
+ if (!Array.isArray(content)) continue;
+ for (const [index, block] of content.entries()) {
+ if (!object(block)) { result.invalidLines++; continue; }
+ if (native) {
+ const type = typeof block.type === "string" ? block.type : "<missing>";
+ increment(quality.blockTypes, type);
+ if (!BLOCK_TYPES.has(type) && !quality.unknownBlockTypes.includes(type)) quality.unknownBlockTypes.push(type);
+ }
+ if (block.type === "tool_use" && typeof block.id === "string") calls.add(block.id);
+ if (block.type === "tool_result" && typeof block.tool_use_id === "string") results.add(block.tool_use_id);
+ if (block.type === "tool_use" || block.type === "tool_result") {
+ const id = block.type === "tool_use" ? block.id : block.tool_use_id;
+ if (typeof id !== "string" || !id) result.invalidLines++;
+ else {
+ const identity = `${block.type}:${id}`, fingerprint = JSON.stringify(block);
+ if (toolIdentities.has(identity) && toolIdentities.get(identity) !== fingerprint) result.conflictingToolIds.push(id);
+ toolIdentities.set(identity, fingerprint);
+ }
+ }
+ if (block.type === "thinking" || block.type === "redacted_thinking") {
+ const identity = `${String(record.uuid ?? result.completeLines)}:${index}`;
+ if (!thinking.has(identity)) {
+ thinking.add(identity);
+ if (native && block.type === "thinking") quality.exposedThinkingBlocks++;
+ if (native && block.type === "redacted_thinking") quality.opaqueThinkingBlocks++;
+ }
+ }
+ }
+ }
+ result.thinkingBlocks = thinking.size; result.toolCalls = calls.size; result.toolResults = results.size;
+ result.pendingTools = [...calls].filter((id) => !results.has(id));
+ result.orphanResults = [...results].filter((id) => !calls.has(id));
+ result.referencedAgents = [...agents];
+ quality.reviewRequired = quality.unknownRecordTypes.length > 0 || quality.unknownBlockTypes.length > 0;
+ return result;
+}
+
+/** One writer per session. The runner must await acknowledgements before progressing.
+ * Every acknowledgement follows file fsync and atomic manifest replacement. Recovery
+ * reuses persisted chunks; a missing/corrupt chunk is an error, never an empty trace.
+ */
+export class NativeCapture {
+ private manifest: NativeCaptureManifest;
+ private readonly scanned = new Map<string, string>();
+ constructor(private readonly options: NativeCaptureOptions) {
+ if (!SESSION_ID.test(options.sessionId) || !options.owner || !options.producerVersion) throw new Error("Native capture identity is required");
+ mkdir(options.directory);
+ const file = path.join(options.directory, "manifest.json");
+ if (fs.existsSync(file)) {
+ // State is private to this writer, but validate identity before reading any evidence.
+ const saved: NativeCaptureManifest = JSON.parse(readRegular(file).toString("utf8"));
+ if (saved.schema !== 1 || saved.format !== "claude-code" || saved.sessionId !== options.sessionId || saved.owner !== options.owner || saved.source !== sha(path.resolve(options.configDir)) || saved.producerVersion !== options.producerVersion || saved.surface !== options.surface || saved.transport !== options.transport) throw new Error("Native capture identity mismatch");
+ this.manifest = saved;
+ this.verify();
+ } else {
+ this.manifest = { schema: 1, format: "claude-code", sessionId: options.sessionId, producerVersion: options.producerVersion, surface: options.surface, transport: options.transport, owner: options.owner, source: sha(path.resolve(options.configDir)), revision: 0, status: "capturing", replay: "unverified", confidential: true, redacted: false, files: [], history: [], issues: [], streams: { cli: 0, sdk: 0, hooks: 0 } };
+ this.persist();
+ }
+ }
+
+ private persist(): NativeCaptureManifest {
+ this.manifest.revision++;
+ atomic(path.join(this.options.directory, "manifest.json"), JSON.stringify(this.manifest, null, 2) + "\n");
+ return structuredClone(this.manifest);
+ }
+
+ private content(file: NativeFile): Buffer {
+ const chunks = file.chunks.map((chunk) => {
+ if (!/^[a-f0-9]{64}$/.test(chunk.sha256)) throw new Error("Invalid native chunk reference");
+ const bytes = readRegular(path.join(this.options.directory, "chunks", chunk.sha256));
+ if (bytes.length !== chunk.bytes || sha(bytes) !== chunk.sha256) throw new Error("Native chunk integrity failure");
+ return bytes;
+ });
+ const bytes = Buffer.concat(chunks);
+ if (bytes.length !== file.bytes || sha(bytes) !== file.sha256) throw new Error("Native file integrity failure");
+ return bytes;
+ }
+
+ verify(): NativeCaptureManifest {
+ for (const file of [...this.manifest.files, ...this.manifest.history]) this.content(file);
+ return structuredClone(this.manifest);
+ }
+
+ private capture(name: string, bytes: Buffer): void {
+ const previous = this.manifest.files.find((file) => file.path === name);
+ const digest = sha(bytes);
+ if (previous?.sha256 === digest) return;
+ let generation = previous?.generation ?? 0;
+ if (previous) {
+ if (bytes.length < previous.bytes || sha(bytes.subarray(0, previous.bytes)) !== previous.sha256) {
+ this.manifest.history.push(previous);
+ generation++;
+ }
+ }
+ const chunks: Chunk[] = [];
+ for (let offset = 0; offset < bytes.length; offset += CHUNK_BYTES) {
+ const part = bytes.subarray(offset, offset + CHUNK_BYTES), digest = sha(part);
+ const target = path.join(this.options.directory, "chunks", digest);
+ if (!fs.existsSync(target)) atomic(target, part);
+ else if (sha(readRegular(target)) !== digest) throw new Error("Native chunk integrity failure");
+ chunks.push({ sha256: digest, bytes: part.length });
+ }
+ this.manifest.files = this.manifest.files.filter((file) => file.path !== name);
+ this.manifest.files.push({ path: name, generation, bytes: bytes.length, sha256: digest, chunks, ...inspect(bytes, name.endsWith(".jsonl"), name.startsWith("claude/projects/") && name.endsWith(".jsonl")) });
+ }
+
+ scan(): NativeCaptureManifest {
+ this.manifest.status = "capturing";
+ this.manifest.issues = [];
+ const projects = path.join(this.options.configDir, "projects");
+ const found = new Set<string>();
+ let total = 0;
+ const take = (file: string, name: string) => {
+ try {
+ const stat = fs.lstatSync(file, { bigint: true });
+ if (!stat.isFile()) throw new Error("Native transcript must be a regular file without symlinks");
+ total += Number(stat.size);
+ if (total > MAX_TOTAL_BYTES) throw new Error("Native session exceeds capture budget");
+ const fingerprint = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
+ if (this.scanned.get(name) !== fingerprint) {
+ this.capture(name, readRegular(file));
+ this.scanned.set(name, fingerprint);
+ }
+ found.add(name);
+ } catch (error) {
+ // Keep every already captured byte and record the gap before failing.
+ this.manifest.status = "incomplete";
+ this.manifest.issues.push(`source_capture_failed:${name}`);
+ this.persist();
+ throw error;
+ }
+ };
+ if (fs.existsSync(projects)) {
+ if (fs.realpathSync(projects) !== path.resolve(projects)) throw new Error("Native projects directory must not traverse symlinks");
+ for (const project of fs.readdirSync(projects, { withFileTypes: true })) {
+ if (!project.isDirectory()) continue;
+ const base = path.join(projects, project.name), prefix = `claude/projects/${project.name}`;
+ const root = path.join(base, `${this.options.sessionId}.jsonl`);
+ if (fs.existsSync(root)) take(root, `${prefix}/${this.options.sessionId}.jsonl`);
+ const children = path.join(base, this.options.sessionId, "subagents");
+ if (!fs.existsSync(children)) continue;
+ if (fs.realpathSync(children) !== children) throw new Error("Native subagents directory must not traverse symlinks");
+ for (const child of fs.readdirSync(children, { withFileTypes: true })) {
+ if (!CHILD_FILE.test(child.name)) continue;
+ take(path.join(children, child.name), `${prefix}/${this.options.sessionId}/subagents/${child.name}`);
+ }
+ }
+ }
+ for (const channel of ["cli", "sdk", "hooks"] as const) {
+ const file = path.join(this.options.directory, "events", `${channel}.jsonl`);
+ if (fs.existsSync(file)) {
+ take(file, `events/${channel}.jsonl`);
+ this.manifest.streams[channel] = fs.statSync(file).size;
+ }
+ }
+ this.manifest.issues = this.manifest.files.filter((file) => !found.has(file.path)).map((file) => `source_missing:${file.path}`);
+ this.manifest.files.sort((a, b) => a.path.localeCompare(b.path));
+ const qc = emptyQuality();
+ for (const file of this.manifest.files) {
+ if (!file.path.startsWith("claude/projects/") || !file.path.endsWith(".jsonl")) continue;
+ // Older manifests are upgraded from original bytes, never assumed empty.
+ if (!file.quality) Object.assign(file, inspect(this.content(file), true, true));
+ const quality = file.quality;
+ if (!quality) continue;
+ for (const key of ["nativeRecords", "syntheticUserRecords", "childPromptRecords", "compactionRecords", "exposedThinkingBlocks", "opaqueThinkingBlocks"] as const) qc[key] += quality[key];
+ if (file.path.includes("/subagents/")) qc.childPromptRecords += quality.humanPromptCandidates;
+ else qc.humanPromptCandidates += quality.humanPromptCandidates;
+ for (const key of ["recordTypes", "blockTypes"] as const) for (const [type, count] of Object.entries(quality[key])) qc[key][type] = (qc[key][type] ?? 0) + count;
+ for (const key of ["unknownRecordTypes", "unknownBlockTypes"] as const) qc[key] = [...new Set([...qc[key], ...quality[key]])].sort();
+ }
+ qc.preservedRevisions = this.manifest.history.length;
+ qc.reviewRequired = qc.unknownRecordTypes.length > 0 || qc.unknownBlockTypes.length > 0 || qc.preservedRevisions > 0;
+ this.manifest.qc = qc;
+ const manifest = this.persist();
+ // A growing final chunk supersedes its previous prefix. Prune only after
+ // the new manifest is durable; retain every referenced rewrite generation.
+ const referenced = new Set([...this.manifest.files, ...this.manifest.history].flatMap((file) => file.chunks.map((chunk) => chunk.sha256)));
+ const chunks = path.join(this.options.directory, "chunks");
+ if (fs.existsSync(chunks)) for (const name of fs.readdirSync(chunks)) {
+ if (/^[a-f0-9]{64}$/.test(name) && !referenced.has(name)) fs.unlinkSync(path.join(chunks, name));
+ }
+ return manifest;
+ }
+
+ recordStream(channel: "cli" | "sdk" | "hooks", bytes: Uint8Array, offset: number): NativeCaptureManifest {
+ if (!["cli", "sdk", "hooks"].includes(channel) || bytes.length > 8 * CHUNK_BYTES) throw new Error("Invalid native stream chunk");
+ const file = path.join(this.options.directory, "events", `${channel}.jsonl`);
+ mkdir(path.dirname(file));
+ if (fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink()) throw new Error("Native event stream must not be a symlink");
+ const fd = fs.openSync(file, fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
+ try {
+ const existing = fs.fstatSync(fd);
+ if (!existing.isFile() || !Number.isSafeInteger(offset) || offset < 0 || offset > existing.size) throw new Error("Native stream offset gap");
+ const overlap = Math.min(bytes.length, existing.size - offset);
+ const prefix = Buffer.alloc(overlap);
+ if (overlap && (fs.readSync(fd, prefix, 0, overlap, offset) !== overlap || !prefix.equals(bytes.subarray(0, overlap)))) throw new Error("Conflicting native stream retry");
+ const remaining = bytes.subarray(overlap);
+ if (existing.size + remaining.length > MAX_FILE_BYTES) throw new Error("Native event stream exceeds capture budget");
+ fs.writeFileSync(fd, remaining); fs.fsyncSync(fd);
+ this.manifest.streams[channel] = existing.size + remaining.length;
+ } finally { fs.closeSync(fd); }
+ syncDir(path.dirname(file));
+ // The stream itself is the durable journal; chunk it at scan/turn barriers.
+ this.manifest.status = "capturing";
+ return this.persist();
+ }
+
+ finish(input: Extract<NativeCaptureAction, { type: "finish" }>): NativeCaptureManifest {
+ this.scan();
+ const issues = this.manifest.issues;
+ if (!input.processStopped) issues.push("producer_still_running");
+ if (!input.successfulResult) issues.push("successful_result_missing");
+ const roots = this.manifest.files.filter((file) => file.path.endsWith(`/${this.options.sessionId}.jsonl`));
+ if (roots.length !== 1 || roots[0].completeLines === 0) issues.push("root_transcript_missing_or_ambiguous");
+ for (const file of this.manifest.files) {
+ if (file.tailBytes) issues.push(`partial_line:${file.path}`);
+ if (file.invalidLines) issues.push(`invalid_json:${file.path}`);
+ if (file.pendingTools.length) issues.push(`pending_tools:${file.path}`);
+ if (file.orphanResults?.length && file.path.startsWith("claude/")) issues.push(`orphan_results:${file.path}`);
+ if (file.conflictingToolIds?.length) issues.push(`conflicting_tool_identity:${file.path}`);
+ }
+ const expectedAgents = new Set([...(input.expectedAgents ?? []), ...this.manifest.files.flatMap((file) => file.referencedAgents)]);
+ for (const agent of expectedAgents) {
+ if (!/^[a-zA-Z0-9_-]+$/.test(agent) || !this.manifest.files.some((file) => file.path.endsWith(`/subagents/agent-${agent}.jsonl`) && file.completeLines > 0)) issues.push(`child_transcript_missing:${agent}`);
+ }
+ this.manifest.status = issues.length ? "incomplete" : "complete";
+ this.verify();
+ return this.persist();
+ }
+
+ /** Private byte-exact export only. A public export needs a separately audited
+ * redacted derivative and must not claim these hashes or resumability.
+ */
+ exportTo(destination: string): NativeCaptureManifest {
+ if (fs.existsSync(destination)) throw new Error("Native export destination already exists");
+ this.verify();
+ mkdir(destination);
+ for (const file of [...this.manifest.files, ...this.manifest.history]) {
+ if (!/^(claude\/projects\/|events\/)/.test(file.path) || file.path.split("/").some((part) => !part || part === "." || part === ".." || part.includes("\\"))) throw new Error("Invalid native export path");
+ const historic = this.manifest.history.includes(file);
+ const target = historic ? `history/${file.generation}/${file.path}` : file.path;
+ atomic(path.join(destination, target), this.content(file));
+ }
+ atomic(path.join(destination, "native-manifest.json"), JSON.stringify(this.manifest, null, 2) + "\n");
+ return structuredClone(this.manifest);
+ }
+}
diff --git a/apps/server/src/claude-code/replay-adapter.ts b/apps/server/src/claude-code/replay-adapter.ts
new file mode 100644
index 00000000..e723657d
--- /dev/null
+++ b/apps/server/src/claude-code/replay-adapter.ts
@@ -0,0 +1,2 @@
+// Generated from tools/claude-native/verify.py by scripts/sync-claude-capture.mjs.
+export const REPLAY_ADAPTER = "#!/usr/bin/env python3\n\"\"\"Private native-Claude ingress for omniconv's recorded-tool replay engine.\n\nRun on an isolated conversion worker with the reviewed omniconv checkout on\nPYTHONPATH. Never run uploaded code on the worker host. Original Claude JSONL\nis authoritative; calls.json is a derived verifier input, not an OpenCode trace.\nThis verifies tool replay and selected filesystem scopes, not model inference\nor approval to distribute unmasked data.\n\"\"\"\nimport argparse\nimport hashlib\nimport json\nimport os\nfrom pathlib import Path\nimport re\nimport subprocess\nimport tarfile\nimport tempfile\nimport time\nimport uuid\nimport zipfile\nfrom datetime import datetime\nfrom contextlib import contextmanager\n\n\ndef sha(data):\n return hashlib.sha256(data).hexdigest()\n\n\ndef file_digest(path):\n digest, size = hashlib.sha256(), 0\n with path.open('rb') as source:\n for chunk in iter(lambda: source.read(1024 * 1024), b''):\n digest.update(chunk)\n size += len(chunk)\n return {'sha256': digest.hexdigest(), 'bytes': size}\n\n\ndef evidence_members(manifest):\n \"\"\"Every preserved generation participates in integrity and execution checks.\"\"\"\n for item in manifest['files']:\n yield item['path'], item\n for item in manifest.get('history', []):\n generation = item['generation']\n if type(generation) is not int or generation < 0:\n raise ValueError('Invalid evidence generation')\n yield f\"history/{generation}/{item['path']}\", item\n\n\ndef jsonl(bundle, name):\n data = bundle.read(name)\n if data and not data.endswith(b'\\n'):\n raise ValueError('Truncated native evidence: ' + name)\n for line in data.decode('utf-8', errors='strict').splitlines():\n if not line.strip():\n continue\n value = json.loads(line)\n if not isinstance(value, dict):\n raise ValueError('Native record must be an object: ' + name)\n yield value\n\n\ndef semantic_gaps(bundle, manifest):\n \"\"\"Recompute admission from bytes, not a client-supplied quality verdict.\"\"\"\n records = {'user', 'assistant', 'system', 'attachment', 'progress', 'queue-operation', 'last-prompt', 'atis-latch',\n 'cost-state', 'mode', 'summary', 'file-history-snapshot', 'custom-title', 'agent-name', 'agent-color',\n 'tag', 'pr-link', 'api-request', 'api-request-blob', 'api-request-shape'}\n blocks = {'text', 'image', 'document', 'tool_use', 'tool_result', 'thinking', 'redacted_thinking'}\n unknown_records, unknown_blocks = set(), set()\n for name, item in evidence_members(manifest):\n if not item['path'].startswith('claude/projects/') or not name.endswith('.jsonl'):\n continue\n for event in jsonl(bundle, name):\n kind = event.get('type') if isinstance(event.get('type'), str) else '<missing>'\n if kind not in records:\n unknown_records.add(kind)\n if kind not in ('user', 'assistant'):\n continue\n message = event.get('message')\n content = message.get('content') if isinstance(message, dict) else None\n if isinstance(content, str):\n continue\n if not isinstance(content, list):\n unknown_blocks.add('<invalid-content>')\n continue\n for block in content:\n kind = block.get('type') if isinstance(block, dict) and isinstance(block.get('type'), str) else '<missing>'\n if kind not in blocks:\n unknown_blocks.add(kind)\n return {'unknown_record_types': sorted(unknown_records), 'unknown_block_types': sorted(unknown_blocks)}\n\n\ndef model_evidence(bundle, session):\n \"\"\"A separate quality check: tool replay cannot prove model provenance.\"\"\"\n result = {'status': 'unknown', 'scope': 'managed-inference',\n 'identity_basis': 'provider-response-body', 'initial_workspace_provenance': 'user-supplied-unattested',\n 'eligible': False, 'blockers': []}\n contract, isolation = session.get('contract'), session.get('modelIsolation')\n if not isinstance(contract, dict) or not isinstance(isolation, dict):\n return {**result, 'status': 'legacy_unverified', 'blockers': ['model_contract_or_journal_missing']}\n try:\n saved = json.loads(bundle.read('policy/contract.json'))\n contract_bytes = json.dumps(contract, ensure_ascii=False, separators=(',', ':')).encode()\n expected = session.get('contractSha256')\n valid = (saved.get('contract') == contract and saved.get('sha256') == expected and sha(contract_bytes) == expected\n and contract.get('schema') == 1 and contract.get('sessionId') == session['id']\n and contract.get('owner') == session['owner'] and contract.get('workspaceId') == session['workspaceId']\n and contract.get('model') == session['model']\n and contract.get('execution', {}).get('baseImage') == session['base']['image']\n and contract.get('execution', {}).get('kind') == 'docker'\n and contract.get('execution', {}).get('os') == 'linux'\n and contract.get('execution', {}).get('shell') == '/bin/bash'\n and contract.get('execution', {}).get('workingDirectory') == '/workspace'\n and contract.get('harness', {}).get('name') == 'claude-code'\n and contract.get('harness', {}).get('sdkVersion') == session.get('sdkVersion')\n and contract.get('harness', {}).get('claudeVersion') == session.get('claudeVersion')\n and contract.get('capture', {}).get('scope') == 'managed-inference'\n and contract.get('capture', {}).get('modelIsolation') == 'exact')\n if not valid:\n return {**result, 'status': 'invalid', 'blockers': ['model_contract_integrity_mismatch']}\n raw = bundle.read('policy/model-requests.jsonl')\n resolved = isolation.get('resolvedModel')\n if not isinstance(resolved, str) or not resolved or session.get('authorization', {}).get('upstreamModel') != resolved:\n return {**result, 'blockers': ['bound_upstream_model_missing']}\n if resolved != session['model']:\n return {**result, 'status': 'invalid', 'blockers': ['bound_upstream_model_mismatch']}\n result['catalog_model'], result['resolved_upstream_model'] = session['model'], resolved\n result['contract_sha256'] = expected\n result['journal'] = {'sha256': sha(raw), 'bytes': len(raw)}\n if sha(raw) != isolation.get('evidenceSha256') or len(raw) != isolation.get('evidenceBytes'):\n return {**result, 'status': 'invalid', 'blockers': ['model_journal_integrity_mismatch']}\n requests, responses, identities = {}, {}, {}\n problems = set()\n for event in jsonl(bundle, 'policy/model-requests.jsonl'):\n if event.get('schema') != 1 or event.get('sessionId') != session['id']:\n problems.add('model_event_identity_mismatch')\n request_id = event.get('requestId')\n if not isinstance(request_id, str) or not request_id:\n problems.add('model_request_identity_missing')\n continue\n kind = event.get('type')\n if kind == 'request':\n if request_id in requests:\n problems.add('duplicate_model_request')\n requests[request_id] = event\n if event.get('requestedModel') != session['model'] or event.get('resolvedModel') != resolved or event.get('contractSha256') != expected:\n problems.add('requested_model_mismatch')\n if event.get('route') not in ('messages', 'count_tokens'):\n problems.add('unknown_model_route')\n elif kind == 'response':\n if request_id in responses:\n problems.add('duplicate_model_response')\n responses[request_id] = event\n elif kind == 'provider_identity':\n identities.setdefault(request_id, set()).add(event.get('providerModel'))\n if event.get('providerModel') != resolved or event.get('requestedModel') != session['model'] or event.get('resolvedModel') != resolved or event.get('source') != 'response-body':\n problems.add('observed_model_mismatch')\n elif kind == 'rejected':\n problems.add('rejected_model_request')\n else:\n problems.add('unknown_model_event')\n if set(requests) != set(responses) or set(identities) - set(requests):\n problems.add('model_journal_incomplete')\n completed = 0\n for request_id, request in requests.items():\n if request.get('route') != 'messages':\n continue\n response = responses.get(request_id, {})\n status = response.get('status')\n if type(status) is int and status >= 400:\n # Failed upstream attempts remain in evidence. They do not\n # establish another model or count as completed inference.\n if response.get('providerModels') or identities.get(request_id):\n problems.add('model_identity_on_failed_response')\n continue\n if type(status) is not int or not 200 <= status < 300 or response.get('completed') is not True or response.get('streamComplete') is not True:\n problems.add('inference_response_incomplete')\n if response.get('identity') != 'reported' or response.get('providerModels') != [resolved] or identities.get(request_id) != {resolved}:\n problems.add('inference_identity_missing_or_mixed')\n completed += 1\n if not completed:\n problems.add('no_completed_model_inference')\n if isolation.get('status') != 'observed' or isolation.get('expectedModel') != session['model'] or isolation.get('observedModels') != [resolved]:\n problems.add('model_summary_not_observed')\n invalid = bool(problems & {'model_event_identity_mismatch', 'requested_model_mismatch', 'observed_model_mismatch', 'rejected_model_request'})\n result.update(status='invalid' if invalid else 'unknown' if problems else 'observed', eligible=not problems,\n completed_inference_requests=completed, blockers=sorted(problems))\n return result\n except (KeyError, ValueError, TypeError, AttributeError, UnicodeDecodeError):\n return {**result, 'status': 'unknown', 'blockers': ['model_evidence_unreadable']}\n\n\ndef stamp(value):\n return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp() * 1000\n\n\ndef docker(*args, timeout=180):\n result = subprocess.run(['docker', *args], capture_output=True, timeout=timeout)\n if result.returncode:\n raise RuntimeError('Docker operation failed: ' + result.stderr.decode(errors='replace')[-1000:])\n return result.stdout.decode().strip()\n\n\ndef write(path, value):\n path.write_text(json.dumps(value, indent=2) + '\\n')\n path.chmod(0o600)\n\n\n@contextmanager\ndef record_failure(path, report):\n try:\n yield\n except Exception as error:\n report.update(status='UNVERIFIED', strict_verified=False,\n failure={'type': type(error).__name__, 'message': str(error)})\n write(path, report)\n raise\n\n\ndef text_content(content):\n if isinstance(content, str):\n return content\n return '\\n'.join(block.get('text', '') for block in content or [] if block.get('type') == 'text')\n\n\ndef agent_model_omission(bundle, session, manifest, call, result, stop):\n \"\"\"Corroborate one reviewed SDK transform; retain the discrepancy as SOFT.\n\n SDK 0.3.306 / Claude 2.1.306's Agent schema omits model when\n CLAUDE_CODE_SUBAGENT_MODEL_FORCE is set. Its executor safeParse strips that\n field before hooks. This controller hash pins the reviewed force setting\n and unchanged hook callback. It is applicability evidence, not attestation.\n \"\"\"\n def reject():\n raise ValueError('Uncorroborated native Agent model omission: ' + call['id'])\n\n controller = session.get('contract', {}).get('harness', {}).get('controllerSha256')\n if (session.get('sdkVersion'), session.get('claudeVersion'), controller) != (\n '0.3.306', '2.1.306', 'fd1d3a901953f38fc866d6ce62ec5f80ef247f878d029ae47bb581832b26ab00'):\n reject()\n if not model_evidence(bundle, session)['eligible']:\n reject()\n native = result['native']\n if (result['block'].get('is_error') or not isinstance(native, dict)\n or not isinstance(native.get('agentId'), str) or not native['agentId']\n or native.get('status') not in ('async_launched', 'completed')\n or native.get('resolvedModel') != session['model']\n or stop['input'].get('hook_event_name') != 'PostToolUse'\n or stop['input'].get('tool_response') != native):\n reject()\n member = 'events/sdk.jsonl'\n entries = [item for item in manifest['files'] if item['path'] == member]\n if len(entries) != 1 or member not in bundle.namelist():\n reject()\n raw = bundle.read(member)\n if entries[0].get('sha256') != sha(raw) or entries[0].get('bytes') != len(raw):\n reject()\n # Validate framing and JSON before inspecting physical line witnesses.\n list(jsonl(bundle, member))\n witnesses = {'requested': [], 'result': [], 'child': []}\n for number, line in enumerate(raw.splitlines(), 1):\n if not line.strip():\n continue\n event = json.loads(line)\n message = event.get('message', {})\n content = message.get('content', [])\n reference = {'path': member, 'line': number, 'sha256': sha(line), 'uuid': event.get('uuid')}\n for block in content if isinstance(content, list) else []:\n if event.get('type') == 'assistant' and block.get('type') == 'tool_use' and block.get('id') == call['id']:\n if (block.get('name') != call['tool'] or block.get('input') != call['input']\n or (event.get('agent_id') or event.get('session_id')) != call['session']):\n reject()\n witnesses['requested'].append(reference)\n if event.get('type') == 'user' and block.get('type') == 'tool_result' and block.get('tool_use_id') == call['id']:\n if block != result['block'] or event.get('tool_use_result') != native:\n reject()\n witnesses['result'].append(reference)\n if event.get('type') == 'assistant' and event.get('parent_tool_use_id') == call['id']:\n if event.get('agent_id') != native['agentId'] or message.get('model') != session['model']:\n reject()\n witnesses['child'].append(reference)\n if not all(witnesses.values()):\n reject()\n return {'kind': 'sdk_agent_model_omission', 'strict_verified': False,\n 'requested_input': call['input'], 'effective_input': call['native_effective_input'],\n 'resolved_model': native['resolvedModel'], 'controller_sha256': controller,\n 'sdk_witnesses': witnesses, 'model_journal_sha256': session['modelIsolation']['evidenceSha256']}\n\n\ndef calls_from(bundle, session, manifest):\n hooks = list(jsonl(bundle, 'events/hooks.jsonl'))\n starts, stops = {}, {}\n for event in hooks:\n item = event['input']\n if item.get('hook_event_name') == 'PreToolUse':\n key = item['tool_use_id']\n if key in starts:\n raise ValueError('Ambiguous repeated tool execution: ' + key)\n starts[key] = event\n elif item.get('hook_event_name') in ('PostToolUse', 'PostToolUseFailure'):\n key = item['tool_use_id']\n if key in stops:\n raise ValueError('Ambiguous repeated tool completion: ' + key)\n stops[key] = event\n calls, results = {}, {}\n for name, file in evidence_members(manifest):\n if not file['path'].startswith('claude/projects/') or not file['path'].endswith('.jsonl'):\n continue\n for event in jsonl(bundle, name):\n if event.get('type') not in ('assistant', 'user'):\n continue # Request-cache blobs repeat context; they are not executions.\n content = event.get('message', {}).get('content')\n if not isinstance(content, list):\n continue\n for block in content:\n if block.get('type') == 'tool_use':\n key = block['id']\n hook = starts.get(key)\n if hook is None:\n raise ValueError('No execution hook for native call: ' + key)\n item = hook['input']\n if item['tool_name'] != block['name']:\n raise ValueError('Native transcript and hook disagree: ' + key)\n requested, effective = block['input'], item['tool_input']\n if requested != effective and not (\n block['name'] == 'Agent' and isinstance(requested, dict) and isinstance(effective, dict)\n and isinstance(requested.get('model'), str) and requested['model']\n and {k: v for k, v in requested.items() if k != 'model'} == effective):\n raise ValueError('Native transcript and hook disagree: ' + key)\n call = {'id': key, 'tool': block['name'], 'input': block['input'],\n 'start': stamp(hook['time']), 'turn': hook['turn'],\n 'session': item.get('agent_id') or event.get('agentId') or session['id'], 'status': 'pending',\n 'source': {'path': name, 'uuid': event.get('uuid')}, 'native_read_witness': hook.get('witness'),\n 'native_cwd': item.get('cwd')}\n if requested != effective:\n call['native_effective_input'] = effective\n if key in calls and (calls[key]['tool'], calls[key]['input']) != (call['tool'], call['input']):\n raise ValueError('Conflicting native call identity: ' + key)\n if key not in calls:\n call['sources'] = [call['source']]\n calls[key] = call\n elif call['source'] not in calls[key]['sources']:\n calls[key]['sources'].append(call['source'])\n elif block.get('type') == 'tool_result':\n key = block['tool_use_id']\n value = {'block': block, 'native': event.get('toolUseResult'), 'end': event.get('timestamp')}\n if key in results and (results[key]['block'], results[key]['native']) != (block, value['native']):\n raise ValueError('Conflicting native result identity: ' + key)\n results[key] = value\n if set(starts) != set(calls):\n raise ValueError('Execution hooks and native calls do not form a complete set')\n if set(results) != set(calls):\n raise ValueError('Native calls and results do not form a complete set')\n for key, call in calls.items():\n if key not in results:\n raise ValueError('Native tool result missing: ' + key)\n result = results[key]\n block, native = result['block'], result['native']\n stop = stops.get(key)\n if stop is None:\n raise ValueError('Native tool completion hook missing: ' + key)\n if stop['turn'] != call['turn'] or stop['input']['tool_name'] != call['tool'] or stop['input']['tool_input'] != call.get('native_effective_input', call['input']):\n raise ValueError('Native tool completion hook disagrees: ' + key)\n if 'native_effective_input' in call:\n call['native_input_normalization'] = agent_model_omission(bundle, session, manifest, call, result, stop)\n call.update(status='error' if block.get('is_error') else 'completed',\n output=text_content(block.get('content')), end=stamp(stop['time']))\n if call['end'] < call['start']:\n raise ValueError('Native execution interval runs backwards: ' + key)\n call['meta'] = {'native_tool_result': native}\n if isinstance(native, dict):\n if native.get('agentId'):\n call['meta']['child_session_id'] = native['agentId']\n # Structured stdout/stderr avoid comparing Claude's no-output UI\n # placeholder as if it were bytes printed by the user's command.\n if call['tool'] == 'Bash' and isinstance(native.get('stdout'), str) and isinstance(native.get('stderr'), str):\n call['output'] = native['stdout'] + native['stderr']\n if native.get('type') == 'file_unchanged':\n # This SDK optimization contains no read bytes. It cannot prove\n # that a replayed read matched; never invent bytes from after.\n call['native_file_unchanged'] = True\n return sorted(calls.values(), key=lambda call: (call['start'], call['id']))\n\n\ndef native_bash(verify, ctr, call, state):\n \"\"\"Replay the recorded command without the generic converter's shell fixes.\n\n Claude's Bash result does not expose its numeric exit or actual shell argv.\n Command/cwd are evidence; /bin/bash -lc is a declared reproduction recipe.\n Therefore even matching stdout and success are SOFT, never strict proof.\n \"\"\"\n inp, native = call['input'], call['meta']['native_tool_result']\n cmd, cwd = inp.get('command'), call.get('native_cwd')\n if not isinstance(cmd, str) or not cmd.strip():\n return {'outcome': 'not_replayable', 'reason': 'native_command_missing'}\n if not isinstance(cwd, str) or not cwd.startswith('/') or '\\0' in cwd:\n return {'outcome': 'not_replayable', 'reason': 'native_cwd_missing'}\n if not isinstance(native, dict) or not all(isinstance(native.get(k), str) for k in ('stdout', 'stderr')):\n return {'outcome': 'no_evidence', 'why': 'native Bash stdout/stderr are missing'}\n if native.get('interrupted') or inp.get('run_in_background') or native.get('backgroundTaskId'):\n return {'outcome': 'not_replayable', 'reason': 'native_background_or_interrupted'}\n if any(native.get(key) for key in ('truncated', 'truncation', 'fullOutputPath', 'outputFile', 'isImage')):\n return {'outcome': 'not_replayable', 'reason': 'native_output_not_text_complete'}\n if verify.classify(cmd) in ('skipped_side_effect', 'server'):\n return {'outcome': 'not_replayable', 'reason': 'native_external_effect_or_server'}\n state.setdefault('commands', []).append(cmd)\n timeout_ms = inp.get('timeout', 120000)\n if type(timeout_ms) is not int or timeout_ms < 1 or timeout_ms > 600000:\n return {'outcome': 'not_replayable', 'reason': 'native_timeout_unsupported'}\n argv = ['docker', 'exec', '-w', cwd, ctr, 'timeout', str(timeout_ms / 1000), '/bin/bash', '-lc', cmd]\n began = time.monotonic()\n try:\n result = subprocess.run(argv, capture_output=True, timeout=timeout_ms / 1000 + 30)\n except subprocess.TimeoutExpired:\n return {'outcome': 'harness_error', 'reason': 'native_command_timeout'}\n stdout, stderr = result.stdout.decode(errors='replace'), result.stderr.decode(errors='replace')\n rec = {'recorded_command_sha256': sha(cmd.encode()), 'cwd': cwd, 'shell_recipe': ['/bin/bash', '-lc'],\n 'actual_shell_argv_observed': False, 'numeric_recorded_exit': None, 'replay_exit': result.returncode,\n 'recorded_stdout_sha256': sha(native['stdout'].encode()), 'recorded_stderr_sha256': sha(native['stderr'].encode()),\n 'replay_stdout_sha256': sha(result.stdout), 'replay_stderr_sha256': sha(result.stderr),\n 'seconds': round(time.monotonic() - began, 3)}\n if result.returncode == 124:\n return {**rec, 'outcome': 'harness_error', 'reason': 'native_command_timeout'}\n if (result.returncode != 0) != (call['status'] == 'error'):\n return {**rec, 'outcome': 'diverge', 'why': 'native Bash success/failure differs'}\n exact = stdout == native['stdout'] and stderr == native['stderr']\n # SDK output formatting can strip final newlines. Show that difference,\n # with separate raw hashes; never silently count it as an exact match.\n formatted = stdout.rstrip('\\n') == native['stdout'].rstrip('\\n') and stderr.rstrip('\\n') == native['stderr'].rstrip('\\n')\n if not exact and not formatted:\n return {**rec, 'outcome': 'diverge-soft', 'why': 'native Bash output differs; shell invocation is unobserved', 'output_exact': False, 'output': {'stdout': stdout, 'stderr': stderr}}\n return {**rec, 'outcome': 'diverge-soft', 'why': 'native Bash actual shell argv and numeric exit are unobserved',\n 'output_exact': exact, 'output_diff': None if exact else 'trailing_newlines'}\n\n\nNATIVE_EDIT = r'''\nimport hashlib, json, os, sys\nrequest = json.load(sys.stdin)\ntool, inp = request['tool'], request['input']\nname = inp['file_path']\ntry:\n with open(name, 'rb') as source:\n original = source.read()\nexcept FileNotFoundError:\n original = None\nif tool == 'Write':\n result = inp['content'].encode('utf-8')\nelif tool == 'Edit':\n if original is None:\n raise ValueError('native_edit_file_missing')\n old, new = inp['old_string'].encode('utf-8'), inp['new_string'].encode('utf-8')\n if not old:\n raise ValueError('native_empty_edit_unsupported')\n count = original.count(old)\n if not count or (count != 1 and not inp.get('replace_all', False)):\n raise ValueError('native_edit_exact_match_missing_or_ambiguous')\n result = original.replace(old, new, -1 if inp.get('replace_all', False) else 1)\nelse:\n raise ValueError('unsupported_native_edit')\nos.makedirs(os.path.dirname(os.path.abspath(name)), exist_ok=True)\nwith open(name, 'wb') as target:\n target.write(result)\n target.flush()\n os.fsync(target.fileno())\nprint(json.dumps({'before_sha256': hashlib.sha256(original).hexdigest() if original is not None else None,\n 'after_sha256': hashlib.sha256(result).hexdigest(), 'bytes': len(result)}))\n'''\n\n\ndef native_edit(ctr, call, state):\n \"\"\"Apply literal native input; no redaction repair or whitespace matching.\"\"\"\n inp, cwd = call['input'], call.get('native_cwd')\n if call['status'] != 'completed':\n return {'outcome': 'not_replayable', 'reason': 'native_failed_edit_semantics'}\n if not isinstance(cwd, str) or not cwd.startswith('/') or not isinstance(inp.get('file_path'), str):\n return {'outcome': 'not_replayable', 'reason': 'native_edit_path_missing'}\n fields = ('content',) if call['tool'] == 'Write' else ('old_string', 'new_string')\n if not all(isinstance(inp.get(key), str) for key in fields):\n return {'outcome': 'not_replayable', 'reason': 'native_edit_input_missing'}\n payload = json.dumps({'tool': call['tool'], 'input': inp}).encode()\n result = subprocess.run(['docker', 'exec', '-i', '-w', cwd, ctr, 'python3', '-c', NATIVE_EDIT],\n input=payload, capture_output=True, timeout=60)\n if result.returncode:\n return {'outcome': 'diverge', 'why': 'native literal edit could not be applied', 'path': inp['file_path']}\n state.setdefault('touched', set()).add(inp['file_path'])\n return {'outcome': 'match', 'path': inp['file_path'], 'literal_input': True, **json.loads(result.stdout)}\n\n\ndef replay_verdict(replay, differences, selected):\n \"\"\"Admission cannot inherit a permissive generic-verifier success label.\"\"\"\n pairs = replay.get('per_call', [])\n if len(pairs) != len(selected) or {pair[0] for pair in pairs} != {call['id'] for call in selected}:\n return 'UNVERIFIED', False, ['execution_coverage_incomplete']\n outcomes = [pair[1].split(':', 1)[0] for pair in pairs]\n if any(differences.values()) or 'diverge' in outcomes:\n return 'DIFFERS', False, ['filesystem_or_tool_result_differs']\n allowed = {'match', 'diverge-soft', 'subagent'}\n blocked = sorted(set(outcomes) - allowed)\n if blocked:\n return ('TOOLS_RAN' if set(blocked) == {'tool-worked'} else 'UNVERIFIED'), False, blocked\n if not outcomes or all(outcome == 'subagent' for outcome in outcomes):\n return 'UNVERIFIED', False, ['no_tool_result_compared']\n soft = ('diverge-soft' in outcomes or bool(replay.get('matches_leaning_on'))\n or any(call.get('native_input_normalization') for call in selected))\n return ('VERIFIED_WITH_SOFT_DIFFS' if soft else 'VERIFIED'), True, []\n\n\ndef tree(container, scope):\n proc = subprocess.Popen(['docker', 'cp', container + ':' + scope, '-'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output = {}\n try:\n with tarfile.open(fileobj=proc.stdout, mode='r|') as archive:\n for member in archive:\n record = {'mode': member.mode, 'type': member.type.decode('ascii'), 'link': member.linkname,\n 'uid': member.uid, 'gid': member.gid}\n if member.isfile():\n digest = hashlib.sha256()\n with archive.extractfile(member) as data:\n for chunk in iter(lambda: data.read(1024 * 1024), b''):\n digest.update(chunk)\n record.update(sha256=digest.hexdigest(), bytes=member.size)\n if member.name in output:\n raise ValueError('Ambiguous filesystem archive member')\n output[member.name] = record\n if proc.wait(timeout=30):\n raise RuntimeError('Cannot inspect replay filesystem')\n return output\n finally:\n if proc.poll() is None:\n proc.kill()\n proc.communicate()\n\n\ndef main():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('zip', type=Path)\n parser.add_argument('--out', required=True, type=Path)\n parser.add_argument('--check-path', action='append', default=[], help='Additional absolute filesystem scope to compare after every turn')\n args = parser.parse_args()\n from omniconv import verify\n original_replay = verify.replay_one\n def replay_native(ctr, root, call, index, calls, state, context):\n if call['tool'] == 'Bash':\n return native_bash(verify, ctr, call, state)\n if call['tool'] in ('Write', 'Edit'):\n return native_edit(ctr, call, state)\n if not call.get('native_file_unchanged') and not (call['tool'] == 'Read' and call.get('native_read_witness')):\n # Absolute native paths pass unchanged. Relative paths resolve from\n # the recorded hook cwd, never a guessed root or a repaired cwd.\n cwd = call.get('native_cwd')\n if not isinstance(cwd, str) or not cwd.startswith('/'):\n return {'outcome': 'not_replayable', 'reason': 'native_cwd_missing'}\n kind = verify.RT.kind_of(call['tool'])[0]\n if kind == 'shell':\n return {'outcome': 'not_replayable', 'reason': 'unsupported_native_shell'}\n if kind == 'edit':\n return {'outcome': 'not_replayable', 'reason': 'unsupported_native_edit'}\n return original_replay(ctr, cwd, call, index, calls, state, context)\n witness = call.get('native_read_witness')\n if call['status'] != 'completed':\n return {'outcome': 'not_replayable', 'reason': 'native_failed_read_semantics'}\n if not witness or witness.get('path') != call['input'].get('file_path') or not re.fullmatch(r'[a-f0-9]{64}', str(witness.get('sha256', ''))):\n return {'outcome': 'not_replayable', 'reason': 'native_cached_read_without_witness'}\n script = \"import hashlib,json,os,stat,sys\\np=sys.argv[1];s=os.stat(p)\\nassert stat.S_ISREG(s.st_mode)\\nh=hashlib.sha256()\\nwith open(p,'rb') as f:\\n for b in iter(lambda:f.read(1048576),b''):h.update(b)\\nprint(json.dumps({'sha256':h.hexdigest(),'bytes':s.st_size,'mode':s.st_mode}))\"\n code, output, _ = verify.sh(['docker', 'exec', ctr, 'python3', '-c', script, witness['path']], 60)\n actual = json.loads(output) if code == 0 and output.strip() else None\n expected = {key: witness.get(key) for key in ('sha256', 'bytes', 'mode')}\n return {'outcome': 'match' if actual == expected else 'diverge',\n 'why': 'native cached read checked against the pre-tool byte witness',\n 'recorded_witness': expected, 'replay_witness': actual, 'path': witness['path']}\n verify.replay_one = replay_native\n os.umask(0o077)\n args.out.mkdir(parents=True, exist_ok=False)\n scopes = ['/workspace', *args.check_path]\n if any(not scope.startswith('/') or '..' in Path(scope).parts for scope in scopes):\n raise ValueError('Check paths must be absolute')\n report = {'schema': 2, 'format': 'claude-code-native', 'verifier': verify.fingerprint(),\n 'adapter_sha256': sha(Path(__file__).read_bytes()), 'network': 'none',\n 'input_artifact': file_digest(args.zip),\n 'filesystem_scopes': scopes, 'private': True, 'delivery_ready': False,\n 'meaning': 'Recorded tool replay with explicit strict/soft outcomes. Original evidence is never rewritten. Delivery selection is separate.',\n 'status': 'UNVERIFIED', 'turns': []}\n write(args.out / 'replay.json', report)\n with record_failure(args.out / 'replay.json', report), zipfile.ZipFile(args.zip) as bundle:\n if len(bundle.namelist()) != len(set(bundle.namelist())):\n raise ValueError('Duplicate ZIP member')\n session_bytes, manifest_bytes = bundle.read('session.json'), bundle.read('native-manifest.json')\n session, manifest = json.loads(session_bytes), json.loads(manifest_bytes)\n report['adapter_source'] = 'external'\n report['embedded_adapter_sha256'] = sha(bundle.read('verify.py')) if 'verify.py' in bundle.namelist() else None\n report['embedded_adapter_matches_external'] = report['embedded_adapter_sha256'] == report['adapter_sha256']\n report['session_sha256'], report['manifest_sha256'] = sha(session_bytes), sha(manifest_bytes)\n report['model_isolation'] = model_evidence(bundle, session)\n report['session_id'] = session['id']\n if manifest['sessionId'] != session['id'] or manifest['status'] != 'complete' or session['capture'] != 'complete':\n raise ValueError('Incomplete native session cannot pass replay admission')\n checked = set()\n for name, item in evidence_members(manifest):\n if name in checked or '\\\\' in name or name.startswith('/') or '..' in name.split('/'):\n raise ValueError('Ambiguous native evidence path')\n checked.add(name)\n content = bundle.read(name)\n if len(content) != item['bytes'] or sha(content) != item['sha256']:\n raise ValueError('Native evidence integrity failure: ' + name)\n if 'events/hooks.jsonl' not in checked:\n raise ValueError('Execution hooks are not covered by the native manifest')\n report['evidence_generations_checked'] = len(checked)\n report['semantic_gaps'] = semantic_gaps(bundle, manifest)\n report['semantic_review_required'] = any(report['semantic_gaps'].values())\n calls = calls_from(bundle, session, manifest)\n report['input_normalizations'] = [{'id': call['id'], **call['native_input_normalization']}\n for call in calls if call.get('native_input_normalization')]\n if any(call['turn'] not in {turn['number'] for turn in session['turns']} for call in calls):\n raise ValueError('A native call lies outside the captured turn sequence')\n write(args.out / 'calls.json', calls)\n report['calls_artifact'] = file_digest(args.out / 'calls.json')\n checkpoints = [session['base'], *[turn['after'] for turn in session['turns']]]\n if not session['turns'] or any(turn['status'] != 'complete' for turn in session['turns']):\n raise ValueError('Every admitted turn must have completed')\n if [turn['number'] for turn in session['turns']] != list(range(1, len(session['turns']) + 1)):\n raise ValueError('Native user turn sequence is incomplete or ambiguous')\n loaded = set()\n for cp in checkpoints:\n if not re.fullmatch(r'sha256:[a-f0-9]{64}', cp['image']):\n raise ValueError('Invalid image digest')\n if cp['file'] in loaded:\n continue\n if not re.fullmatch(r'images/[a-f0-9]{64}\\.tar\\.gz', cp['file']):\n raise ValueError('Invalid image archive path')\n with tempfile.NamedTemporaryFile(suffix='.tar.gz') as target:\n digest = hashlib.sha256(); size = 0\n with bundle.open(cp['file']) as source:\n for chunk in iter(lambda: source.read(1024 * 1024), b''):\n digest.update(chunk); size += len(chunk); target.write(chunk)\n target.flush()\n if digest.hexdigest() != cp['sha256'] or size != cp['bytes']:\n raise ValueError('Environment archive integrity failure')\n docker('load', '--input', target.name, timeout=600)\n loaded.add(cp['file'])\n for turn in session['turns']:\n if turn['number'] < 1 or turn['before']['image'] != checkpoints[turn['number'] - 1]['image']:\n raise ValueError('Broken before/after environment chain')\n selected = [call for call in calls if call['turn'] == turn['number']]\n name = 'omnirush-native-replay-' + uuid.uuid4().hex\n expected = name + '-expected'\n try:\n common = ['--network=none', '--cap-drop=ALL', '--security-opt=no-new-privileges', '--pids-limit=256', '--memory=4g', '--cpus=2']\n docker('run', '-d', '--name', name, *common, turn['before']['image'], 'sleep', 'infinity')\n docker('create', '--name', expected, *common, turn['after']['image'])\n replay = verify.replay_calls(name, '/workspace', selected, context={'main': session['id'], 'sessions': sorted({call['session'] for call in calls})})\n differences = {}\n for scope in scopes:\n actual_tree, expected_tree = tree(name, scope), tree(expected, scope)\n differences[scope] = [key for key in sorted(set(actual_tree) | set(expected_tree)) if actual_tree.get(key) != expected_tree.get(key)]\n status, accepted, blockers = replay_verdict(replay, differences, selected)\n if report['semantic_review_required']:\n status, accepted = 'UNVERIFIED', False\n blockers.append('unknown_native_semantics')\n report['turns'].append({'number': turn['number'], 'before_image': turn['before']['image'], 'after_image': turn['after']['image'],\n 'calls': len(selected), 'accepted': accepted, 'strict_verified': status == 'VERIFIED',\n 'status': status, 'blockers': blockers, 'replay': replay, 'filesystem_differences': differences})\n write(args.out / 'replay.json', report)\n finally:\n subprocess.run(['docker', 'rm', '-f', name, expected], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n if file_digest(args.zip) != report['input_artifact']:\n report.update(status='UNVERIFIED', strict_verified=False, failure={'type': 'input_integrity', 'message': 'Input artifact changed during replay'})\n write(args.out / 'replay.json', report)\n raise ValueError('Input artifact changed during replay')\n if all(turn['accepted'] for turn in report['turns']):\n report['status'] = 'VERIFIED' if all(turn['strict_verified'] for turn in report['turns']) else 'VERIFIED_WITH_SOFT_DIFFS'\n elif any(turn['status'] == 'DIFFERS' for turn in report['turns']):\n report['status'] = 'DIFFERS'\n elif any(turn['status'] == 'TOOLS_RAN' for turn in report['turns']):\n report['status'] = 'TOOLS_RAN'\n report['strict_verified'] = report['status'] == 'VERIFIED'\n blockers = list(report['model_isolation']['blockers'])\n if report['status'] not in ('VERIFIED', 'VERIFIED_WITH_SOFT_DIFFS'):\n blockers.append('tool_replay_not_verified')\n if report['semantic_review_required']:\n blockers.append('unknown_native_semantics')\n report['quality_admission'] = {'eligible': not blockers, 'blockers': blockers,\n 'retained': True, 'delivery_selection': 'separate'}\n write(args.out / 'replay.json', report)\n print(json.dumps({'session_id': report['session_id'], 'status': report['status'], 'turns': len(report['turns']), 'report': str(args.out / 'replay.json')}))\n return 0 if report['status'] in ('VERIFIED', 'VERIFIED_WITH_SOFT_DIFFS') else 1\n\n\nif __name__ == '__main__':\n raise SystemExit(main())\n";
diff --git a/apps/server/src/claude-code/routes.ts b/apps/server/src/claude-code/routes.ts
new file mode 100644
index 00000000..ea3037a9
--- /dev/null
+++ b/apps/server/src/claude-code/routes.ts
@@ -0,0 +1,64 @@
+import { ClaudeRuntime } from "./runtime.js";
+import { createReadStream } from "node:fs";
+import { Readable } from "node:stream";
+import { addRoute, type RequestContext, type Route } from "../routes/registry.js";
+import { ApiError } from "../errors.js";
+import type { WorkspaceInfo } from "../types.js";
+import type { NativeUploadReceipt } from "./upload.js";
+
+export function registerClaudeRoutes(input: {
+ routes: Route[]; runtime: ClaudeRuntime;
+ workspace: (ctx: RequestContext) => Promise<WorkspaceInfo>;
+ owner: (ctx: RequestContext) => void;
+ writable: () => void;
+ upload: (sessionId: string) => Promise<NativeUploadReceipt>;
+}) {
+ const {runtime} = input;
+ const register = (method: string, suffix: string, handler: (ctx: RequestContext, workspace: WorkspaceInfo) => Promise<Response>) => {
+ addRoute(input.routes, method, `/workspace/:id/claude${suffix}`, "client", async ctx => {
+ input.owner(ctx);
+ if (method !== "GET") input.writable();
+ const workspace = await input.workspace(ctx);
+ if (ctx.params.session) {
+ const session = await runtime.get(ctx.params.session);
+ if (session.workspaceId !== workspace.id) throw new ApiError(404, "session_not_found", "Session not found in this workspace");
+ }
+ const response = await handler(ctx, workspace); response.headers.set("cache-control", "no-store"); return response;
+ });
+ };
+ register("GET", "/status", async () => {
+ try { return Response.json(await runtime.available()); }
+ catch { return Response.json({allowed: false, sandboxReady: false}); }
+ });
+ register("POST", "/prepare", async ctx => { await runtime.prepare(ctx.request.signal); return Response.json({ready: true}); });
+ register("GET", "/sessions", async (_, workspace) => Response.json(await runtime.list(workspace.id)));
+ register("POST", "/sessions", async (ctx, workspace) => {
+ const body = await ctx.request.json();
+ if (body?.captureConsent !== true) throw new ApiError(400, "capture_consent_required", "Confirm private trace and environment capture");
+ return Response.json(await runtime.create(workspace.path, workspace.id, ctx.request.signal), {status: 201});
+ });
+ register("GET", "/sessions/:session", async ctx => Response.json(await runtime.get(ctx.params.session)));
+ register("GET", "/sessions/:session/events", async ctx => Response.json(await runtime.events(ctx.params.session)));
+ register("POST", "/sessions/:session/turns", async ctx => {
+ const body = await ctx.request.json();
+ if (typeof body?.prompt !== "string") throw new ApiError(400, "prompt_required", "Enter a prompt");
+ await runtime.start(ctx.params.session, body.prompt, ctx.request.signal); return Response.json({started: true}, {status: 202});
+ });
+ register("POST", "/sessions/:session/stop", async ctx => Response.json(await runtime.stop(ctx.params.session)));
+ register("POST", "/sessions/:session/recover", async ctx => Response.json(await runtime.recover(ctx.params.session)));
+ register("POST", "/sessions/:session/verify", async ctx => {
+ const body = await ctx.request.json();
+ if (body?.command !== undefined && (typeof body.command !== "string" || body.command.length > 10_000)) throw new ApiError(400, "invalid_command", "Invalid verification command");
+ return Response.json(await runtime.verify(ctx.params.session, body?.command));
+ });
+ register("POST", "/sessions/:session/export", async ctx => {
+ const file = await runtime.export(ctx.params.session);
+ // The packaged desktop embeds the Node server; stream without Bun globals
+ // or buffering a complete environment archive in the renderer/server heap.
+ const stream = Readable.toWeb(createReadStream(file)) as unknown as ReadableStream<Uint8Array>;
+ return new Response(stream, {headers: {"content-type": "application/zip", "content-disposition": `attachment; filename="claude-${ctx.params.session}.zip"`}});
+ });
+ register("POST", "/sessions/:session/upload", async ctx => {
+ return Response.json(await input.upload(ctx.params.session));
+ });
+}
diff --git a/apps/server/src/claude-code/runtime.ts b/apps/server/src/claude-code/runtime.ts
new file mode 100644
index 00000000..bf4a3a15
--- /dev/null
+++ b/apps/server/src/claude-code/runtime.ts
@@ -0,0 +1,944 @@
+/** The shared CLI/desktop Claude runtime. The SDK and every tool run in the
+ * container. There are no host workspace, home, credential or socket mounts.
+ * Stopped-container images are the checkpoint authority, not a guessed list of
+ * changed files. The host only brokers inference, copies evidence and seals it.
+ */
+import fs from "node:fs";
+import fsp from "node:fs/promises";
+import path from "node:path";
+import http from "node:http";
+import os from "node:os";
+import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+import { pipeline } from "node:stream/promises";
+import { createGzip, createGunzip } from "node:zlib";
+import { NativeCapture } from "./native-capture.js";
+import { CAPTURE_POLICY_VERSION, CLAUDE_VERSION, CONTROLLER, DOCKERFILE, IMAGE, MANAGED_SETTINGS, MODEL, SDK_VERSION } from "./sandbox-assets.js";
+import { PACKAGE_JSON, LOCKFILE } from "./sandbox-lock.js";
+import { zipDirectory } from "./zip.js";
+import { REPLAY_ADAPTER } from "./replay-adapter.js";
+import { writeBundleManifest } from "./bundle-manifest.js";
+import { ClaudeAccessError, claudeResponseHeaders } from "./access.js";
+
+export type ClaudeBudgetSnapshot = {
+ status: "known" | "unknown"; model: string; revision?: string;
+ asOf?: string; limitTokens?: number | null; remainingTokens?: number | null; resetAt?: string | null;
+ sessionLimitTokens?: number | null; sessionUsedTokens?: number; sessionRemainingTokens?: number | null;
+ accountLimitTokens?: number; accountRemainingTokens?: number; accountScope?: "day" | "week"; accountResetAt?: string;
+};
+export type ClaudeAccess = { owner: string; capabilities?: string[]; budget?: ClaudeBudgetSnapshot };
+export type ClaudeAuthorization = { sessionId: string; owner: string; model: string; workspaceId: string; contractSha256: string; refresh?: boolean };
+export type ClaudeGrant = {
+ owner: string; baseUrl: string; token: string; sessionId: string; model: string;
+ upstreamModel: string; client: string;
+ bindingId?: string; contractSha256?: string; policyVersion?: string; budget?: ClaudeBudgetSnapshot;
+};
+export type RuntimeOptions = {
+ directory: string; surface: "cli" | "gui";
+ access: () => Promise<ClaudeAccess>;
+ authorize: (session: ClaudeAuthorization) => Promise<ClaudeGrant>;
+ revoke?: (session: ClaudeAuthorization) => Promise<void>;
+ docker?: string;
+};
+export type ClaudeSessionContract = {
+ schema: 1; sessionId: string; owner: string; workspaceId: string; model: string;
+ harness: {name: "claude-code"; sdkVersion: string; claudeVersion: string; controllerSha256: string; lockSha256: string; managedSettingsSha256: string; dockerfileSha256: string};
+ execution: {kind: "docker"; os: "linux"; architecture: string; workingDirectory: "/workspace"; shell: "/bin/bash"; runtimeImage: string; baseImage: string; workspace: "session-copy"};
+ capture: {policyVersion: string; originals: "private"; modelIsolation: "exact"; scope: "managed-inference"; network: "development-network-enabled"; initialWorkspaceProvenance: "user-supplied-unattested"};
+};
+export type ClaudeModelIsolation = {
+ status: "pending" | "observed" | "unknown" | "invalid" | "legacy_unverified";
+ expectedModel: string; resolvedModel?: string; observedModels: string[]; inferenceRequests: number; completedRequests: number;
+ missingIdentityRequests: number; interruptedRequests: number; rejectedRequests: number;
+ issues: string[]; evidenceSha256?: string; evidenceBytes?: number;
+};
+type Checkpoint = { image: string; file: string; sha256: string; bytes: number };
+type Turn = { number: number; prompt: string; startedAt: string; finishedAt?: string; sdkStart: number; sdkEnd?: number;
+ status: "running" | "complete" | "interrupted" | "failed"; before: Checkpoint;
+ after?: Checkpoint; error?: string };
+export type ClaudeSession = {
+ schema: 1; id: string; owner: string; workspaceId: string; surface: "cli" | "gui";
+ model: string; sdkVersion: string; claudeVersion: string; createdAt: string;
+ container: string; base: Checkpoint; turns: Turn[];
+ capture: "capturing" | "complete" | "incomplete";
+ replay: "unverified" | "restored"; issues: string[];
+ contract?: ClaudeSessionContract; contractSha256?: string;
+ compatibility?: "current" | "legacy_unverified" | "contract_invalid" | "runtime_upgrade_required";
+ modelIsolation?: ClaudeModelIsolation;
+ authorization?: {binding: "session-model" | "session-model-contract"; bindingId?: string; upstreamModel: string; policyVersion: string | null; budget: ClaudeBudgetSnapshot | null};
+};
+export type DisplayEvent = { type: "user" | "assistant" | "thinking" | "tool" | "result"; text: string; turn: number };
+const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
+const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
+const digest = (value: string) => createHash("sha256").update(value).digest("hex");
+function interrupted(signal?: AbortSignal) { signal?.throwIfAborted(); }
+async function abortable<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
+ interrupted(signal);
+ if (!signal) return work;
+ let abort!: () => void;
+ const cancelled = new Promise<never>((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, {once: true}); });
+ try { return await Promise.race([work, cancelled]); }
+ finally { signal.removeEventListener("abort", abort); }
+}
+// A PID alone cannot distinguish a live owner from a reused PID. Linux exposes
+// an exact birth identity; elsewhere a live/uninspectable PID stays locked.
+function processIdentity(pid: number) {
+ if (process.platform !== "linux") return undefined;
+ try {
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8"), start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
+ const boot = fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), namespace = fs.readlinkSync("/proc/self/ns/pid");
+ if (!/^\d+$/.test(start) || !UUID.test(boot)) return undefined;
+ return {host: os.hostname(), boot, namespace, start};
+ } catch { return undefined; }
+}
+function deadLockOwner(prior: unknown): boolean {
+ if (!isRecord(prior) || typeof prior.pid !== "number" || !Number.isSafeInteger(prior.pid) || prior.pid < 1 || typeof prior.nonce !== "string") return false;
+ const identity = prior.identity, current = processIdentity(prior.pid);
+ if (identity !== undefined) {
+ // An unfamiliar host/namespace or malformed birth record is not proof.
+ const self = processIdentity(process.pid);
+ if (!isRecord(identity) || !self || identity.host !== self.host || identity.namespace !== self.namespace ||
+ typeof identity.boot !== "string" || !UUID.test(identity.boot) || typeof identity.start !== "string" || !/^\d+$/.test(identity.start)) return false;
+ if (identity.boot !== self.boot) return true;
+ if (current && identity.start !== current.start) return true;
+ }
+ try { process.kill(prior.pid, 0); return false; }
+ catch (error) { return isRecord(error) && error.code === "ESRCH"; }
+}
+function privateDir(dir: string) { fs.mkdirSync(dir, {recursive: true, mode: 0o700}); fs.chmodSync(dir, 0o700); }
+function syncDirectory(dir: string) {
+ if (process.platform === "win32") return;
+ const fd = fs.openSync(dir, "r"); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+}
+function save(file: string, data: unknown) {
+ privateDir(path.dirname(file));
+ const tmp = `${file}.${randomUUID()}.tmp`, fd = fs.openSync(tmp, "wx", 0o600);
+ try { fs.writeFileSync(fd, JSON.stringify(data, null, 2) + "\n"); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+ fs.renameSync(tmp, file);
+ if (process.platform !== "win32") { const dir = fs.openSync(path.dirname(file), "r"); try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); } }
+}
+async function fileHash(file: string) {
+ const hash = createHash("sha256");
+ for await (const bytes of fs.createReadStream(file)) hash.update(bytes);
+ return hash.digest("hex");
+}
+function validateGrant(grant: ClaudeGrant, session: ClaudeAuthorization): ClaudeGrant {
+ const url = new URL(grant.baseUrl);
+ if (!grant.owner || !grant.token || /\s/.test(grant.token) || /^sk-ant-/.test(grant.token) || url.username || url.password || url.search || url.hash ||
+ /(^|\.)(anthropic\.com|claude\.ai)$/.test(url.hostname) ||
+ !(url.protocol === "https:" || url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) throw new Error("An active internal Claude grant is required");
+ if (grant.owner !== session.owner || grant.sessionId !== session.sessionId || grant.model !== session.model ||
+ grant.contractSha256 !== undefined && grant.contractSha256 !== session.contractSha256) throw new Error("Claude authorization does not match this session's fixed model and contract");
+ if (!identityLabel(grant.upstreamModel) || grant.upstreamModel !== session.model || !/^(cli|desktop|gui)\/[A-Za-z0-9][A-Za-z0-9.+_-]{0,63}$/.test(grant.client)) throw new Error("Claude authorization does not match the exact upstream model and client binding");
+ return {...grant, baseUrl: grant.baseUrl.replace(/\/$/, "")};
+}
+
+function initialModelIsolation(model: string, legacy = false): ClaudeModelIsolation {
+ return {status: legacy ? "legacy_unverified" : "pending", expectedModel: model, observedModels: [], inferenceRequests: 0, completedRequests: 0, missingIdentityRequests: 0, interruptedRequests: 0, rejectedRequests: 0, issues: legacy ? ["capture_predates_model_enforcement"] : []};
+}
+function identityLabel(value: unknown): string | null {
+ return typeof value === "string" && /^claude-[a-z0-9._-]{1,128}$/.test(value) ? value : null;
+}
+
+/** Observes identity without changing a single response byte. Only a provider's
+ * actual message envelope is identity evidence; a requested model is not. */
+class ResponseIdentity {
+ readonly models = new Set<string>();
+ malformed = false;
+ complete = false;
+ private readonly decoder = new TextDecoder();
+ private pending = "";
+ constructor(private readonly stream: boolean, private readonly observed: (model: string) => void) {}
+ private event(value: unknown) {
+ if (!isRecord(value)) return;
+ const message = value.type === "message_start" && isRecord(value.message) ? value.message : value.type === "message" ? value : null;
+ if (message) {
+ const model = identityLabel(message.model);
+ if (!model) { this.malformed = true; return; }
+ this.models.add(model); this.observed(model);
+ }
+ if (value.type === "message_stop" || value.type === "message" && value.stop_reason !== null && value.stop_reason !== undefined) this.complete = true;
+ }
+ private parse(text: string) {
+ if (!text.trim() || text.trim() === "[DONE]") return;
+ let parsed: unknown;
+ try { parsed = JSON.parse(text); } catch { this.malformed = true; return; }
+ this.event(parsed);
+ }
+ push(bytes: Uint8Array) {
+ this.pending += this.decoder.decode(bytes, {stream: true});
+ if (this.stream) {
+ for (;;) {
+ const match = /\r?\n\r?\n/.exec(this.pending);
+ if (!match || match.index === undefined) break;
+ const frame = this.pending.slice(0, match.index); this.pending = this.pending.slice(match.index + match[0].length);
+ const data = frame.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
+ this.parse(data);
+ }
+ }
+ if (this.pending.length > (this.stream ? 4 : 32) * 1024 * 1024) { this.pending = ""; this.malformed = true; }
+ }
+ finish() {
+ this.pending += this.decoder.decode();
+ if (this.stream) { if (this.pending.trim()) this.malformed = true; }
+ else this.parse(this.pending);
+ this.pending = "";
+ }
+}
+
+export class ClaudeRuntime {
+ private readonly running = new Map<string, { stop: AbortController; done: Promise<void> }>();
+ private preparing?: Promise<void>;
+ private closed = false;
+ private readonly root: string;
+ constructor(private readonly options: RuntimeOptions) { privateDir(options.directory); this.root = fs.realpathSync(options.directory); }
+ private reserve(id: string, signal?: AbortSignal) {
+ interrupted(signal);
+ if (this.closed) throw new Error("Claude runtime is shutting down");
+ if (this.running.has(id)) throw new Error("This session already has an active operation");
+ const stop = new AbortController(), abort = () => stop.abort(signal?.reason);
+ signal?.addEventListener("abort", abort, {once: true});
+ let complete!: () => void;
+ const done = new Promise<void>(resolve => { complete = resolve; });
+ this.running.set(id, {stop, done});
+ return {signal: stop.signal, finish: () => { signal?.removeEventListener("abort", abort); this.running.delete(id); complete(); }};
+ }
+ private async access(owner?: string, signal?: AbortSignal) {
+ interrupted(signal);
+ const access = await abortable(this.options.access(), signal);
+ interrupted(signal);
+ if (!access.owner || owner && access.owner !== owner) throw new Error("This Claude session belongs to another account");
+ return access;
+ }
+ private authorizationContext(session: ClaudeSession): ClaudeAuthorization {
+ if (!session.contractSha256 || !session.contract) throw new Error("This legacy capture has no immutable model contract; export it and start a new session");
+ return {sessionId: session.id, owner: session.owner, model: session.model, workspaceId: session.workspaceId, contractSha256: session.contractSha256};
+ }
+ private async grant(session: ClaudeSession, refresh = false, signal?: AbortSignal) {
+ await this.access(session.owner, signal);
+ interrupted(signal);
+ const context = {...this.authorizationContext(session), refresh};
+ const grant = validateGrant(await this.options.authorize(context), context);
+ interrupted(signal);
+ const isolation = session.modelIsolation ??= initialModelIsolation(session.model);
+ if (isolation.resolvedModel && isolation.resolvedModel !== grant.upstreamModel || session.authorization?.upstreamModel && session.authorization.upstreamModel !== grant.upstreamModel) {
+ isolation.status = "invalid"; isolation.issues.push("upstream_binding_changed");
+ this.modelEvidence(session, {type: "rejected_authorization", reason: "upstream_binding_changed"});
+ throw new Error("The backend changed this session's upstream model binding");
+ }
+ isolation.resolvedModel = grant.upstreamModel;
+ if (session.authorization?.bindingId && grant.bindingId !== session.authorization.bindingId) throw new Error("The backend changed this session's immutable binding");
+ session.authorization = {binding: grant.contractSha256 ? "session-model-contract" : "session-model", bindingId: grant.bindingId, upstreamModel: grant.upstreamModel, policyVersion: grant.policyVersion ?? null, budget: grant.budget ?? null};
+ return grant;
+ }
+ private dir(owner: string, id: string) {
+ if (!UUID.test(id)) throw new Error("Invalid Claude session ID");
+ return path.join(this.root, digest(owner), id);
+ }
+ private async docker(args: string[], options: { input?: string; signal?: AbortSignal; stdout?: (bytes: Buffer) => void; timeout?: number } = {}): Promise<string> {
+ interrupted(options.signal);
+ return await new Promise((resolve, reject) => {
+ const child = spawn(this.options.docker ?? "docker", args, {stdio: ["pipe", "pipe", "pipe"], windowsHide: true});
+ const output: Buffer[] = []; let bytes = 0, error = "", failed: Error | undefined;
+ const abort = () => { failed = new Error("Claude sandbox operation interrupted"); child.kill("SIGKILL"); };
+ const timer = setTimeout(abort, options.timeout ?? 120_000);
+ options.signal?.addEventListener("abort", abort, {once: true});
+ child.stdout.on("data", (chunk: Buffer) => {
+ try {
+ if (options.stdout) options.stdout(chunk);
+ else { bytes += chunk.length; if (bytes > 16 * 1024 * 1024) throw new Error("Sandbox output exceeds limit"); output.push(chunk); }
+ } catch (e) { failed = e instanceof Error ? e : new Error(String(e)); child.kill("SIGKILL"); }
+ });
+ child.stderr.on("data", (chunk: Buffer) => { error = (error + chunk.toString("utf8")).slice(-8192); });
+ child.on("error", (e) => { failed = e; });
+ child.on("close", (code) => {
+ clearTimeout(timer); options.signal?.removeEventListener("abort", abort);
+ if (failed) reject(failed);
+ else if (code !== 0) reject(new Error(`Sandbox ${args[0]} failed (${code}): ${error.trim()}`));
+ else resolve(Buffer.concat(output).toString("utf8").trim());
+ });
+ child.stdin.on("error", () => {});
+ child.stdin.end(options.input);
+ if (options.signal?.aborted) abort();
+ });
+ }
+ async available() {
+ const access = await this.access();
+ if (!access.capabilities?.includes("claude-code")) return {allowed: false, sandboxReady: false, model: MODEL, sdkVersion: SDK_VERSION};
+ try { await this.docker(["info", "--format", "{{.ServerVersion}}"], {timeout: 10_000}); return {allowed: true, sandboxReady: true, model: MODEL, sdkVersion: SDK_VERSION}; }
+ catch { return {allowed: true, sandboxReady: false, model: MODEL, sdkVersion: SDK_VERSION}; }
+ }
+ async prepare(signal?: AbortSignal) {
+ const job = this.reserve(`prepare:${randomUUID()}`, signal);
+ try {
+ if (!(await this.access(undefined, job.signal)).capabilities?.includes("claude-code")) throw new Error("Claude Code capture is not enabled for this account");
+ interrupted(job.signal);
+ if (this.preparing) return await abortable(this.preparing, job.signal);
+ const preparing = this.prepareImage(job.signal); this.preparing = preparing;
+ try { await preparing; } finally { if (this.preparing === preparing) this.preparing = undefined; }
+ } finally { job.finish(); }
+ }
+ private async prepareImage(signal: AbortSignal) {
+ const fingerprint = digest(JSON.stringify(this.harnessContract()));
+ try {
+ const inspected = JSON.parse(await this.docker(["image", "inspect", IMAGE], {signal}));
+ interrupted(signal);
+ if (inspected?.[0]?.Config?.Labels?.["org.omnirush.claude.runtime"] === fingerprint) return;
+ } catch { interrupted(signal); /* build the pinned runtime */ }
+ const build = path.join(this.root, "build", fingerprint); privateDir(build);
+ fs.writeFileSync(path.join(build, "Dockerfile"), DOCKERFILE);
+ fs.writeFileSync(path.join(build, "controller.mjs"), CONTROLLER);
+ fs.writeFileSync(path.join(build, "managed-settings.json"), MANAGED_SETTINGS);
+ fs.writeFileSync(path.join(build, "package.json"), PACKAGE_JSON);
+ fs.writeFileSync(path.join(build, "pnpm-lock.yaml"), LOCKFILE);
+ await this.docker(["build", "--label", `org.omnirush.claude.runtime=${fingerprint}`, "--tag", IMAGE, build], {signal, timeout: 15 * 60_000, stdout: () => {}});
+ interrupted(signal);
+ }
+ private async checkpoint(container: string, dir: string, prior: Checkpoint[] = [], signal?: AbortSignal): Promise<Checkpoint> {
+ // Container is stopped: no tool or background child can race the checkpoint.
+ const image = await this.docker(["commit", container], {signal});
+ if (!/^sha256:[a-f0-9]{64}$/.test(image)) throw new Error("Invalid sandbox checkpoint identity");
+ const file = `images/${image.slice(7)}.tar.gz`, target = path.join(dir, file);
+ privateDir(path.dirname(target));
+ const tar = `${target}.tar.tmp`, tmp = `${target}.tmp`;
+ try {
+ const loaded = new Set<string>();
+ for (const cp of prior) {
+ try { await this.docker(["image", "inspect", cp.image], {signal}); }
+ catch { interrupted(signal); if (!loaded.has(cp.file)) { await this.loadCheckpoint(cp, dir, signal); loaded.add(cp.file); } }
+ }
+ // Docker's multi-image archive stores common layers once while retaining
+ // the exact config/image digest of every before/after environment.
+ await this.docker(["save", "--output", tar, ...new Set([...prior.map(cp => cp.image), image])], {signal, timeout: 5 * 60_000});
+ await pipeline(fs.createReadStream(tar), createGzip({level: 1}), fs.createWriteStream(tmp, {mode: 0o600}), {signal});
+ interrupted(signal);
+ const fd = fs.openSync(tmp, "r"); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+ fs.renameSync(tmp, target);
+ if (process.platform !== "win32") { const parent = fs.openSync(path.dirname(target), "r"); try { fs.fsyncSync(parent); } finally { fs.closeSync(parent); } }
+ return {image, file, sha256: await fileHash(target), bytes: fs.statSync(target).size};
+ } finally { await fsp.rm(tar, {force: true}); await fsp.rm(tmp, {force: true}); }
+ }
+ private checkpoints(session: ClaudeSession) { return [session.base, ...session.turns.flatMap(turn => turn.after ? [turn.after] : [])]; }
+ private repointArchive(session: ClaudeSession, current: Checkpoint) {
+ for (const cp of [session.base, ...session.turns.flatMap(turn => turn.after ? [turn.before, turn.after] : [turn.before])]) Object.assign(cp, {file: current.file, sha256: current.sha256, bytes: current.bytes});
+ }
+ private async pruneArchives(session: ClaudeSession) {
+ const dir = this.dir(session.owner, session.id), keep = new Set(this.checkpoints(session).map(cp => path.basename(cp.file)));
+ for (const name of await fsp.readdir(path.join(dir, "images"))) if (/^[a-f0-9]{64}\.tar\.gz$/.test(name) && !keep.has(name)) await fsp.rm(path.join(dir, "images", name));
+ }
+ private async loadCheckpoint(checkpoint: Checkpoint, dir: string, signal?: AbortSignal) {
+ if (await fileHash(path.join(dir, checkpoint.file)) !== checkpoint.sha256) throw new Error("Environment archive integrity failure");
+ const tar = path.join(dir, `restore-${randomUUID()}.tar.tmp`);
+ try {
+ await pipeline(fs.createReadStream(path.join(dir, checkpoint.file)), createGunzip(), fs.createWriteStream(tar, {mode: 0o600}), {signal});
+ await this.docker(["load", "--input", tar], {signal, timeout: 5 * 60_000});
+ } finally { await fsp.rm(tar, {force: true}); }
+ }
+ private createContainer(name: string, image: string, bootstrap = false, signal?: AbortSignal, ownership?: string) {
+ return this.docker(["create", "--name", name, "--label", "omnirush.claude=true", ...(ownership ? ["--label", `org.omnirush.claude.operation=${ownership}`] : []), "--init", "--cap-drop=ALL", ...(bootstrap ? ["--cap-add=CHOWN"] : []), "--security-opt=no-new-privileges", "--pids-limit=512", "--memory=4g", "--cpus=2", "--add-host=host.docker.internal:host-gateway", image], {signal});
+ }
+ private async restoreContainerIfMissing(session: ClaudeSession, signal?: AbortSignal) {
+ try { await this.docker(["container", "inspect", session.container], {signal}); interrupted(signal); return; } catch { interrupted(signal); /* validate the saved image before reconstructing */ }
+ const turn = session.turns.at(-1);
+ if (turn && (turn.status !== "complete" || !turn.after)) throw new Error("The interrupted container is missing; retain its partial evidence for review");
+ const checkpoint = turn?.after ?? session.base;
+ await this.loadCheckpoint(checkpoint, this.dir(session.owner, session.id), signal);
+ const ownership = randomUUID();
+ try { await this.createContainer(session.container, checkpoint.image, false, signal, ownership); interrupted(signal); }
+ catch (error) { await this.cleanupStartup(ownership); throw error; }
+ }
+ async create(workspace: string, workspaceId: string, signal?: AbortSignal): Promise<ClaudeSession> {
+ const id = randomUUID(), job = this.reserve(id, signal), ownership = randomUUID();
+ const container = `omnirush-claude-${id}`;
+ let attempted = false;
+ try {
+ const {owner} = await this.access(undefined, job.signal); await this.prepare(job.signal);
+ interrupted(job.signal);
+ const root = await fsp.realpath(workspace);
+ if (!(await fsp.stat(root)).isDirectory() || root === path.parse(root).root) throw new Error("Choose a project directory");
+ interrupted(job.signal);
+ if (!workspaceId.trim()) throw new Error("Workspace identity is required");
+ const dir = this.dir(owner, id); privateDir(dir);
+ const inspected = JSON.parse(await this.docker(["image", "inspect", IMAGE], {signal: job.signal}));
+ const image = inspected?.[0];
+ if (!isRecord(image) || typeof image.Id !== "string" || !/^sha256:[a-f0-9]{64}$/.test(image.Id) || image.Os !== "linux" || typeof image.Architecture !== "string") throw new Error("The Claude runtime image must have an exact Linux identity");
+ attempted = true;
+ await this.createContainer(container, image.Id, true, job.signal, ownership);
+ // Copy, never bind-mount: tools cannot reach the host through a symlink.
+ await this.docker(["cp", `${root}${path.sep}.`, `${container}:/workspace/`], {signal: job.signal, timeout: 5 * 60_000});
+ await this.docker(["start", container], {signal: job.signal});
+ await this.docker(["exec", "--user", "root", container, "chown", "-R", "node:node", "/workspace"], {signal: job.signal});
+ await this.docker(["stop", "--time", "2", container], {signal: job.signal});
+ const base = await this.checkpoint(container, dir, [], job.signal);
+ await this.docker(["rm", container], {signal: job.signal});
+ await this.createContainer(container, base.image, false, job.signal, ownership);
+ interrupted(job.signal);
+ const contract: ClaudeSessionContract = {
+ schema: 1, sessionId: id, owner, workspaceId, model: MODEL,
+ harness: this.harnessContract(),
+ execution: {kind: "docker", os: "linux", architecture: image.Architecture, workingDirectory: "/workspace", shell: "/bin/bash", runtimeImage: image.Id, baseImage: base.image, workspace: "session-copy"},
+ capture: {policyVersion: CAPTURE_POLICY_VERSION, originals: "private", modelIsolation: "exact", scope: "managed-inference", network: "development-network-enabled", initialWorkspaceProvenance: "user-supplied-unattested"},
+ };
+ const contractSha256 = digest(JSON.stringify(contract));
+ const session: ClaudeSession = {schema: 1, id, owner, workspaceId, surface: this.options.surface, model: MODEL, sdkVersion: SDK_VERSION, claudeVersion: CLAUDE_VERSION, createdAt: new Date().toISOString(), container, base, turns: [], capture: "capturing", replay: "unverified", issues: [], contract, contractSha256, compatibility: "current", modelIsolation: initialModelIsolation(MODEL)};
+ save(path.join(dir, "policy", "contract.json"), {contract, sha256: contractSha256});
+ save(path.join(dir, "session.json"), session); return session;
+ } catch (e) {
+ if (attempted) await this.cleanupStartup(ownership);
+ throw e;
+ } finally { job.finish(); }
+ }
+ private async cleanupStartup(ownership: string) {
+ // The operation label is minted before create and inherited by checkpoints.
+ // Never remove a container by an unverified name or a shared runtime image.
+ for (const kind of ["container", "image"] as const) {
+ try {
+ const ids = await this.docker([kind, "ls", "--all", "--quiet", "--no-trunc", "--filter", `label=org.omnirush.claude.operation=${ownership}`], {timeout: 10_000});
+ for (const id of new Set(ids.split(/\s+/).filter(value => /^(sha256:)?[a-f0-9]{64}$/.test(value)))) {
+ const inspected = JSON.parse(await this.docker([kind, "inspect", id], {timeout: 10_000}));
+ if (inspected?.[0]?.Config?.Labels?.["org.omnirush.claude.operation"] === ownership) await this.docker([kind, "rm", "--force", id], {timeout: 10_000});
+ }
+ } catch { /* Docker may be unavailable; keep the operation-labelled resources for recovery. */ }
+ }
+ }
+ private localPath(file: string, directory: boolean) {
+ const stat = fs.lstatSync(file);
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
+ typeof process.getuid === "function" && stat.uid !== process.getuid() || fs.realpathSync(file) !== file) throw new Error("Claude evidence path is not a private local path");
+ }
+ private ownerDirectories() {
+ this.localPath(this.root, true);
+ return fs.readdirSync(this.root).filter(name => /^[a-f0-9]{64}$/.test(name));
+ }
+ async list(workspaceId: string): Promise<ClaudeSession[]> {
+ const sessions: ClaudeSession[] = [];
+ for (const owner of this.ownerDirectories()) {
+ const root = path.join(this.root, owner); this.localPath(root, true);
+ for (const id of fs.readdirSync(root).filter(id => UUID.test(id))) {
+ try { const session = await this.get(id); if (session.workspaceId === workspaceId) sessions.push(session); }
+ catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
+ }
+ }
+ return sessions.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
+ }
+ async get(id: string): Promise<ClaudeSession> {
+ if (!UUID.test(id)) throw new Error("Invalid Claude session ID");
+ let found: ClaudeSession | undefined;
+ for (const owner of this.ownerDirectories()) {
+ const root = path.join(this.root, owner); this.localPath(root, true);
+ const dir = path.join(root, id);
+ try { this.localPath(dir, true); } catch (error) { if (isRecord(error) && error.code === "ENOENT") continue; throw error; }
+ const file = path.join(dir, "session.json"); this.localPath(file, false);
+ const session: ClaudeSession = JSON.parse(fs.readFileSync(file, "utf8"));
+ if (!session || typeof session.owner !== "string" || !session.owner || digest(session.owner) !== owner || session.id !== id ||
+ typeof session.workspaceId !== "string" || !session.workspaceId.trim() || session.container !== `omnirush-claude-${id}` ||
+ session.contract && (session.contract.owner !== session.owner || session.contract.sessionId !== id || session.contract.workspaceId !== session.workspaceId)) throw new Error("Claude session identity mismatch");
+ if (found) throw new Error("Ambiguous local Claude session identity");
+ found = session;
+ }
+ if (!found) throw Object.assign(new Error("Claude session not found"), {code: "ENOENT"});
+ if (found.contract) {
+ const policy = path.join(this.dir(found.owner, id), "policy");
+ try { this.localPath(policy, true); this.localPath(path.join(policy, "contract.json"), false); }
+ catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
+ }
+ found.compatibility = this.compatibility(found);
+ found.modelIsolation ??= initialModelIsolation(found.model, true);
+ return found;
+ }
+ private harnessContract(): ClaudeSessionContract["harness"] {
+ return {name: "claude-code", sdkVersion: SDK_VERSION, claudeVersion: CLAUDE_VERSION, controllerSha256: digest(CONTROLLER), lockSha256: digest(PACKAGE_JSON + "\n" + LOCKFILE), managedSettingsSha256: digest(MANAGED_SETTINGS), dockerfileSha256: digest(DOCKERFILE)};
+ }
+ private compatibility(session: ClaudeSession): NonNullable<ClaudeSession["compatibility"]> {
+ if (!session.contract || !session.contractSha256) return "legacy_unverified";
+ const c = session.contract;
+ let saved: unknown;
+ try { saved = JSON.parse(fs.readFileSync(path.join(this.dir(session.owner, session.id), "policy", "contract.json"), "utf8")); } catch { return "contract_invalid"; }
+ if (!isRecord(saved) || !isRecord(saved.contract) || saved.sha256 !== session.contractSha256 || digest(JSON.stringify(saved.contract)) !== session.contractSha256 || digest(JSON.stringify(c)) !== session.contractSha256 ||
+ c.schema !== 1 || c.sessionId !== session.id || c.owner !== session.owner || c.workspaceId !== session.workspaceId || c.model !== session.model || c.model !== MODEL || c.execution?.baseImage !== session.base.image || c.execution?.kind !== "docker" || c.execution.os !== "linux" || c.execution.shell !== "/bin/bash" || c.execution.workingDirectory !== "/workspace") return "contract_invalid";
+ if (session.sdkVersion !== SDK_VERSION || session.claudeVersion !== CLAUDE_VERSION || JSON.stringify(c.harness) !== JSON.stringify(this.harnessContract()) || c.capture?.policyVersion !== CAPTURE_POLICY_VERSION) return "runtime_upgrade_required";
+ return "current";
+ }
+ private assertResumable(session: ClaudeSession) {
+ const compatibility = this.compatibility(session);
+ if (compatibility !== "current") throw new Error(compatibility === "legacy_unverified" ? "This legacy capture has no immutable model contract; export it and start a new session" : compatibility === "runtime_upgrade_required" ? "This session requires its recorded Claude runtime; start a new session for this runtime version" : "This Claude session's immutable model or environment contract changed");
+ if (session.modelIsolation?.status === "invalid") throw new Error("This session failed model isolation; retain its evidence and start a new session");
+ if (session.modelIsolation?.status === "unknown") throw new Error("This session has incomplete provider model identity; retain its evidence and start a new session");
+ if (session.modelIsolation?.status === "legacy_unverified") throw new Error("This session has no trustworthy model evidence; start a new session");
+ const evidence = path.join(this.dir(session.owner, session.id), "policy", "model-requests.jsonl");
+ const isolation = session.modelIsolation;
+ if (isolation?.expectedModel !== session.model || (fs.existsSync(evidence) || isolation.inferenceRequests > 0) && !isolation.evidenceSha256) throw new Error("The session's model evidence is incomplete; retain it for review");
+ if (isolation.evidenceSha256) {
+ if (!fs.existsSync(evidence)) throw new Error("The model evidence journal is missing; retain this session for review");
+ const bytes = fs.readFileSync(evidence);
+ if (createHash("sha256").update(bytes).digest("hex") !== isolation.evidenceSha256 || bytes.length !== isolation.evidenceBytes) throw new Error("The model evidence journal changed; retain this session for review");
+ const pending = new Map<string, boolean>(), seen = new Set<string>();
+ try {
+ for (const line of bytes.toString("utf8").split("\n").filter(Boolean)) {
+ const event: unknown = JSON.parse(line);
+ if (!isRecord(event)) throw new Error();
+ if (event.type === "request") {
+ if (typeof event.requestId !== "string" || seen.has(event.requestId)) throw new Error();
+ seen.add(event.requestId); pending.set(event.requestId, event.route === "messages");
+ } else if (event.type === "response") {
+ if (typeof event.requestId !== "string" || !pending.delete(event.requestId)) throw new Error();
+ }
+ }
+ } catch { throw new Error("The model evidence journal is invalid; retain this session for review"); }
+ if ([...pending.values()].some(inference => inference)) throw new Error("A previous model request has no terminal evidence; retain this session and start a new one");
+ }
+ }
+ private modelEvidence(session: ClaudeSession, event: Record<string, unknown>) {
+ const dir = this.dir(session.owner, session.id), file = path.join(dir, "policy", "model-requests.jsonl");
+ privateDir(path.dirname(file));
+ const fd = fs.openSync(file, "a", 0o600);
+ try { fs.writeFileSync(fd, JSON.stringify({schema: 1, time: new Date().toISOString(), sessionId: session.id, turn: session.turns.at(-1)?.number ?? 0, ...event}) + "\n"); fs.fsyncSync(fd); }
+ finally { fs.closeSync(fd); }
+ const isolation = session.modelIsolation ??= initialModelIsolation(session.model);
+ const bytes = fs.readFileSync(file);
+ isolation.evidenceSha256 = createHash("sha256").update(bytes).digest("hex"); isolation.evidenceBytes = bytes.length;
+ save(path.join(dir, "session.json"), session);
+ }
+ private collector(session: ClaudeSession, savedOnly = false) {
+ const dir = this.dir(session.owner, session.id);
+ if (savedOnly) this.localPath(path.join(dir, "native", "manifest.json"), false);
+ else privateDir(path.join(dir, "config"));
+ return new NativeCapture({directory: path.join(dir, "native"), configDir: path.join(dir, "config"), sessionId: session.id, owner: session.owner, producerVersion: savedOnly ? session.claudeVersion : CLAUDE_VERSION, surface: session.surface, transport: "sdk"});
+ }
+ private async collect(session: ClaudeSession, stopped: boolean, success: boolean) {
+ const dir = this.dir(session.owner, session.id), config = path.join(dir, "config"); privateDir(config);
+ const staging = path.join(dir, `capture-${randomUUID()}`); privateDir(staging);
+ try {
+ await this.docker(["cp", `${session.container}:/home/node/.claude/projects`, staging]);
+ await fsp.rm(path.join(config, "projects"), {recursive: true, force: true});
+ await fsp.rename(path.join(staging, "projects"), path.join(config, "projects"));
+ } finally { await fsp.rm(staging, {recursive: true, force: true}); }
+ const evidence = path.join(dir, "transport"); privateDir(evidence);
+ await this.docker(["cp", `${session.container}:/home/node/evidence/.`, evidence]);
+ const collector = this.collector(session);
+ for (const channel of ["sdk", "hooks"] as const) {
+ const file = path.join(evidence, `${channel}.jsonl`);
+ if (!fs.existsSync(file)) continue;
+ const bytes = fs.readFileSync(file), offset = collector.verify().streams[channel];
+ if (bytes.length < offset) throw new Error("Sandbox evidence was truncated");
+ // Compare the acknowledged prefix too: a tool cannot silently rewrite
+ // events already persisted outside the sandbox.
+ for (let position = 0; position < bytes.length; position += 8 * 1024 * 1024) collector.recordStream(channel, bytes.subarray(position, position + 8 * 1024 * 1024), position);
+ }
+ const starts = new Set<string>(), stops = new Set<string>();
+ const hooks = await fsp.readFile(path.join(evidence, "hooks.jsonl"), "utf8").catch(() => "");
+ for (const line of hooks.split("\n")) {
+ if (!line) continue;
+ const record = JSON.parse(line), input = record.input;
+ if (typeof input?.agent_id !== "string") continue;
+ if (input.hook_event_name === "SubagentStart") starts.add(input.agent_id);
+ if (input.hook_event_name === "SubagentStop") stops.add(input.agent_id);
+ }
+ const childrenStopped = [...starts].every(id => stops.has(id));
+ const manifest = stopped ? collector.finish({type: "finish", processStopped: true, successfulResult: success && childrenStopped, expectedAgents: [...starts]}) : collector.scan();
+ session.capture = manifest.status; session.issues = manifest.issues;
+ return manifest;
+ }
+ private async broker(session: ClaudeSession, onInvalid: () => void, signal?: AbortSignal) {
+ interrupted(signal);
+ const token = randomUUID();
+ const active = new Set<AbortController>(), pending = new Set<Promise<void>>();
+ const isolation = session.modelIsolation ??= initialModelIsolation(session.model);
+ const invalid = () => isolation.status === "invalid";
+ const unidentified = () => {
+ if (!invalid()) isolation.status = "unknown";
+ if (!isolation.issues.includes("provider_identity_missing_or_malformed")) isolation.issues.push("provider_identity_missing_or_malformed");
+ for (const request of active) request.abort();
+ onInvalid();
+ throw new Error("The provider did not establish this session's model identity");
+ };
+ const invalidate = (reason: string) => {
+ isolation.status = "invalid";
+ if (!isolation.issues.includes(reason)) isolation.issues.push(reason);
+ for (const request of active) request.abort();
+ onInvalid();
+ };
+ const handle = async (req: http.IncomingMessage, res: http.ServerResponse) => {
+ const supplied = Buffer.from(req.headers.authorization ?? ""), expected = Buffer.from(`Bearer ${token}`);
+ if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) { res.writeHead(403).end(); return; }
+ if (req.method !== "POST" || !/^\/v1\/messages(?:\/count_tokens)?(?:\?[^#]*)?$/.test(req.url ?? "")) { res.writeHead(404).end(); return; }
+ const url = new URL(req.url ?? "", "http://claude-session-broker");
+ if ([...url.searchParams].some(([name, value]) => name !== "beta" || value !== "true")) { res.writeHead(400, {"content-type": "application/json"}).end(JSON.stringify({type: "error", error: {type: "invalid_request_error", message: "Unsupported session routing parameter"}})); return; }
+ if (invalid() || isolation.status === "unknown") { res.writeHead(409, {"content-type": "application/json", "x-should-retry": "false"}).end(JSON.stringify({type: "error", error: {type: "invalid_request_error", message: "Session model isolation failed"}})); return; }
+ const abort = new AbortController(), cancel = () => abort.abort(signal?.reason); active.add(abort);
+ signal?.addEventListener("abort", cancel, {once: true});
+ if (signal?.aborted) cancel();
+ res.on("close", () => { if (!res.writableFinished) abort.abort(); });
+ const requestId = randomUUID(), inference = !req.url?.startsWith("/v1/messages/count_tokens");
+ const authorizationFailures: number[] = [];
+ let observer: ResponseIdentity | undefined, admitted = false, responseStatus: number | null = null, finished = false;
+ try {
+ const chunks: Buffer[] = []; let size = 0;
+ for await (const chunk of req) { size += chunk.length; if (size > 32 * 1024 * 1024) throw new Error("Request too large"); chunks.push(chunk); }
+ const originalBody = Buffer.concat(chunks), body = JSON.parse(originalBody.toString("utf8"));
+ if (!isRecord(body) || body.model !== session.model) {
+ isolation.rejectedRequests++; invalidate("request_model_mismatch");
+ this.modelEvidence(session, {type: "rejected", requestId, route: inference ? "messages" : "count_tokens", requestedModel: identityLabel(body?.model), resolvedModel: session.model, reason: "request_model_mismatch"});
+ res.writeHead(400, {"content-type": "application/json"}).end(JSON.stringify({type: "error", error: {type: "invalid_request_error", message: "This session accepts only its fixed model"}})); return;
+ }
+ let grant = await this.grant(session, false, abort.signal);
+ if (isolation.status === "invalid" || abort.signal.aborted) throw new Error("Model isolation failed");
+ // Routing/model override headers never cross this boundary. SDK version
+ // and beta negotiation are explicitly listed rather than prefix-trusted.
+ const headers: Record<string, string> = {"content-type": "application/json", "x-api-key": grant.token, "x-omnirush-session-id": session.id, "x-omnirush-request-id": requestId, "x-omnirush-client": grant.client, "x-omnirush-box": "1"};
+ for (const name of ["anthropic-version", "anthropic-beta", "user-agent", "x-app"]) { const value = req.headers[name]; if (typeof value === "string") headers[name] = value; }
+ // Ask for the provider-exposed summary; never fabricate hidden reasoning.
+ const transformations: string[] = [];
+ if (isRecord(body.thinking) && body.thinking.type === "adaptive" && body.thinking.display !== "summarized") { body.thinking.display = "summarized"; transformations.push("thinking.display=summarized"); }
+ const forwardedBody = JSON.stringify(body);
+ if (inference) isolation.inferenceRequests++;
+ admitted = true;
+ this.modelEvidence(session, {type: "request", requestId, route: inference ? "messages" : "count_tokens", requestedModel: body.model, resolvedModel: grant.upstreamModel, binding: session.authorization?.binding, contractSha256: session.contractSha256, policyVersion: grant.policyVersion ?? null, budget: grant.budget ?? null, transformations, originalBodySha256: createHash("sha256").update(originalBody).digest("hex"), forwardedBodySha256: digest(forwardedBody)});
+ let upstream = await fetch(grant.baseUrl + req.url, {method: "POST", headers, body: forwardedBody, redirect: "error", signal: abort.signal});
+ if (upstream.status === 401 && !abort.signal.aborted) {
+ // A rejected token has not admitted inference. Re-mint exactly once;
+ // never replay a started stream, a quota refusal, or a provider error.
+ await upstream.body?.cancel();
+ authorizationFailures.push(401);
+ grant = await this.grant(session, true, abort.signal);
+ interrupted(abort.signal);
+ headers["x-api-key"] = grant.token;
+ upstream = await fetch(grant.baseUrl + req.url, {method: "POST", headers, body: forwardedBody, redirect: "error", signal: abort.signal});
+ }
+ responseStatus = upstream.status; res.statusCode = upstream.status;
+ for (const [name, value] of Object.entries(claudeResponseHeaders(upstream.headers))) res.setHeader(name, value);
+ const streaming = upstream.headers.get("content-type")?.includes("text/event-stream") === true;
+ if (inference && upstream.ok) observer = new ResponseIdentity(streaming, model => {
+ if (!isolation.observedModels.includes(model)) isolation.observedModels.push(model);
+ this.modelEvidence(session, {type: "provider_identity", requestId, requestedModel: session.model, resolvedModel: grant.upstreamModel, providerModel: model, source: "response-body"});
+ if (model !== grant.upstreamModel) { invalidate("provider_model_mismatch"); throw new Error("The provider served another model"); }
+ });
+ const buffered: Uint8Array[] = []; let responseBytes = 0;
+ if (upstream.body) for await (const bytes of upstream.body) {
+ observer?.push(bytes);
+ if (observer?.malformed) unidentified();
+ if (observer) {
+ responseBytes += bytes.length;
+ if (responseBytes > 32 * 1024 * 1024) throw new Error("Non-streaming model response exceeded the evidence bound");
+ buffered.push(bytes);
+ // No provider text or tool call reaches the SDK until the actual
+ // message envelope identifies the pinned model. Preserve bytes.
+ if (streaming && observer.models.size) {
+ for (const chunk of buffered) if (!res.write(chunk)) await once(res, "drain", {signal: abort.signal});
+ buffered.length = 0; responseBytes = 0;
+ }
+ } else if (!res.write(bytes)) await once(res, "drain", {signal: abort.signal});
+ }
+ observer?.finish();
+ if (observer && (!observer.models.size || observer.malformed)) unidentified();
+ for (const bytes of buffered) if (!res.write(bytes)) await once(res, "drain", {signal: abort.signal});
+ finished = true;
+ res.end();
+ } catch (error) {
+ if (invalid()) onInvalid();
+ if (!res.headersSent) {
+ const status = error instanceof ClaudeAccessError ? error.status : 502;
+ const headers: Record<string, string> = {...(error instanceof ClaudeAccessError ? error.responseHeaders : {}), "content-type": "application/json"};
+ if (status < 500 && status !== 429) headers["x-should-retry"] = "false";
+ if (error instanceof ClaudeAccessError && error.retryAfter) headers["retry-after"] = error.retryAfter;
+ res.writeHead(status, headers).end(JSON.stringify({type: "error", error: {type: status === 429 ? "rate_limit_error" : status === 401 ? "authentication_error" : status === 403 ? "permission_error" : status < 500 ? "invalid_request_error" : "api_error", message: error instanceof ClaudeAccessError ? error.message : "Internal Claude access is unavailable"}}));
+ } else res.destroy();
+ }
+ finally {
+ active.delete(abort); signal?.removeEventListener("abort", cancel);
+ if (admitted) {
+ if (inference && observer) {
+ if (observer.complete && finished) isolation.completedRequests++;
+ else isolation.interruptedRequests++;
+ if (!observer.models.size || observer.malformed) isolation.missingIdentityRequests++;
+ } else if (inference && responseStatus === null) { isolation.interruptedRequests++; isolation.missingIdentityRequests++; }
+ if (isolation.status !== "invalid") isolation.status = isolation.missingIdentityRequests ? "unknown" : isolation.observedModels.length ? "observed" : "pending";
+ this.modelEvidence(session, {type: "response", requestId, status: responseStatus, ...(authorizationFailures.length ? {authorizationFailures} : {}), completed: finished && observer?.complete === true, providerModels: observer ? [...observer.models] : [], identity: observer?.models.size && !observer.malformed ? "reported" : "unknown", streamComplete: observer?.complete ?? false});
+ }
+ }
+ };
+ const server = http.createServer((req, res) => {
+ const work = handle(req, res); pending.add(work);
+ void work.catch(() => { invalidate("model_evidence_persistence_failed"); res.destroy(); }).finally(() => pending.delete(work));
+ });
+ server.listen(0, "0.0.0.0"); await once(server, "listening");
+ const address = server.address(); if (!address || typeof address === "string") throw new Error("Inference broker did not start");
+ return {token, baseUrl: `http://host.docker.internal:${address.port}`, close: async () => { for (const request of active) request.abort(); server.closeAllConnections(); server.close(); await Promise.allSettled([...pending]); }};
+ }
+ async start(id: string, prompt: string, signal?: AbortSignal): Promise<void> {
+ if (!prompt.trim() || prompt.length > 100_000) throw new Error("Enter a prompt of at most 100,000 characters");
+ const job = this.reserve(id, signal);
+ let release: (() => void) | undefined;
+ try {
+ let session = await this.get(id);
+ await this.access(session.owner, job.signal);
+ interrupted(job.signal);
+ release = this.lock(session);
+ session = await this.get(id);
+ if (session.turns.at(-1)?.status === "running") throw new Error("Recover the interrupted session before continuing");
+ if (session.turns.length && !session.turns.at(-1)?.after) throw new Error("Recover the missing environment checkpoint before continuing");
+ this.assertResumable(session);
+ await this.restoreContainerIfMissing(session, job.signal);
+ interrupted(job.signal);
+ const unlock = release;
+ void this.run(session, prompt, job.signal).catch(() => {}).finally(() => { try { unlock(); } finally { job.finish(); } }).catch(() => {});
+ } catch (e) { try { release?.(); } finally { job.finish(); } throw e; }
+ }
+ async wait(id: string) { await this.running.get(id)?.done; return this.get(id); }
+ async stop(id: string) {
+ // Abort first, including startup before session.json exists or access resolves.
+ this.running.get(id)?.stop.abort();
+ return this.wait(id);
+ }
+ private async run(session: ClaudeSession, prompt: string, signal: AbortSignal) {
+ const dir = this.dir(session.owner, session.id), state = path.join(dir, "session.json");
+ const collector = this.collector(session); let offset = collector.verify().streams.sdk;
+ const turn: Turn = {number: session.turns.length + 1, prompt, startedAt: new Date().toISOString(), sdkStart: offset, status: "running", before: session.turns.at(-1)?.after ?? session.base};
+ session.turns.push(turn); session.capture = "capturing"; session.replay = "unverified"; save(state, session);
+ let broker: Awaited<ReturnType<ClaudeRuntime["broker"]>> | undefined;
+ let outcome: Turn["status"] = "failed";
+ const isolationStop = new AbortController();
+ const executionSignal = AbortSignal.any([signal, isolationStop.signal]);
+ try {
+ interrupted(executionSignal);
+ await this.grant(session, false, executionSignal);
+ interrupted(executionSignal);
+ await this.docker(["start", session.container], {signal: executionSignal});
+ interrupted(executionSignal);
+ broker = await this.broker(session, () => isolationStop.abort(), executionSignal);
+ interrupted(executionSignal);
+ const actual = await this.docker(["exec", session.container, "sha256sum", "/opt/claude/controller.mjs", "/etc/claude-code/managed-settings.json"], {signal: executionSignal});
+ if (actual.split("\n").map(line => line.split(/\s+/)[0]).join(":") !== `${digest(CONTROLLER)}:${digest(MANAGED_SETTINGS)}`) throw new Error("The sandbox controller or managed model policy changed");
+ await this.docker(["exec", "-i", session.container, "node", "/opt/claude/controller.mjs"], {
+ input: JSON.stringify({sessionId: session.id, resume: turn.number > 1, turn: turn.number, prompt, model: session.model, baseUrl: broker.baseUrl, token: broker.token}), signal: executionSignal, timeout: 60 * 60_000,
+ stdout: bytes => { collector.recordStream("sdk", bytes, offset); offset += bytes.length; },
+ });
+ if (session.modelIsolation?.status === "invalid") throw new Error("Session model isolation failed");
+ outcome = "complete";
+ } catch { outcome = signal.aborted ? "interrupted" : "failed"; turn.error = signal.aborted ? "Turn stopped; partial evidence retained" : "Claude turn failed; inspect the private diagnostic bundle"; }
+ finally {
+ await broker?.close();
+ if (this.options.revoke) {
+ try { await this.options.revoke(this.authorizationContext(session)); }
+ catch { this.modelEvidence(session, {type: "authorization_revocation", status: "failed"}); }
+ }
+ try {
+ await this.docker(["stop", "--time", "3", session.container]);
+ turn.after = await this.checkpoint(session.container, dir, this.checkpoints(session));
+ this.repointArchive(session, turn.after);
+ const manifest = await this.collect(session, true, outcome === "complete");
+ if (manifest.status !== "complete" && outcome === "complete") { outcome = "failed"; turn.error = "Native capture is incomplete"; }
+ } catch (e) { session.capture = "incomplete"; session.issues = ["checkpoint_or_capture_failed"]; outcome = "failed"; turn.error = "Evidence could not be finalized; recover before continuing"; }
+ turn.sdkEnd = fs.existsSync(path.join(dir, "native/events/sdk.jsonl")) ? fs.statSync(path.join(dir, "native/events/sdk.jsonl")).size : offset;
+ // Persist replacement checkpoint references before pruning their old files.
+ // Keep the turn running until cleanup ends: a terminal status enables the
+ // next prompt/export, which must not race this operation's lock.
+ save(state, session);
+ await this.pruneArchives(session).catch(() => {});
+ turn.status = outcome; turn.finishedAt = new Date().toISOString(); save(state, session);
+ }
+ }
+ private recoveryGuard(dir: string) {
+ const guard = path.join(dir, "recovery.lock"), staging = path.join(dir, `.recovery-stage-${randomUUID()}`);
+ const owner = JSON.stringify({pid: process.pid, nonce: randomUUID(), identity: processIdentity(process.pid)});
+ fs.mkdirSync(staging, {mode: 0o700});
+ try {
+ const fd = fs.openSync(path.join(staging, "owner.json"), "wx", 0o600);
+ try { fs.writeFileSync(fd, owner); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+ syncDirectory(staging);
+ // Publish a complete, nonempty directory. A legacy empty file/directory
+ // has no trustworthy owner and is deliberately never reclaimed.
+ for (let attempt = 0; attempt < 3; attempt++) {
+ let present = true;
+ try { this.localPath(guard, true); }
+ catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; present = false; }
+ if (present) {
+ const record = path.join(guard, "owner.json"); this.localPath(record, false);
+ const bytes = fs.readFileSync(record, "utf8"), prior: unknown = JSON.parse(bytes);
+ if (!deadLockOwner(prior)) throw new Error("Another process is recovering this session or its recovery owner is unknown");
+ // Keep this nonempty tombstone permanently. If two reclaimers read
+ // the same dead owner, only one rename can succeed: the loser cannot
+ // overwrite the tombstone with a newer live guard (the ABA race).
+ const tombstone = path.join(dir, `.recovery-dead-${digest(bytes)}`);
+ if (fs.existsSync(tombstone)) throw new Error("The recovery guard generation already changed; retry the operation");
+ try { fs.renameSync(guard, tombstone); syncDirectory(dir); }
+ catch (error) { if (!isRecord(error) || !["ENOENT", "EEXIST", "ENOTEMPTY"].includes(String(error.code))) throw error; }
+ continue;
+ }
+ try { fs.renameSync(staging, guard); }
+ catch (error) { if (!isRecord(error) || !["EEXIST", "ENOTEMPTY"].includes(String(error.code))) throw error; continue; }
+ syncDirectory(dir);
+ return () => {
+ this.localPath(guard, true); this.localPath(path.join(guard, "owner.json"), false);
+ if (fs.readFileSync(path.join(guard, "owner.json"), "utf8") !== owner) throw new Error("The recovery guard owner changed");
+ // Remove only our uniquely named directory after unpublishing it.
+ // A crash on either side leaves a recoverable guard or harmless stage.
+ fs.renameSync(guard, staging); syncDirectory(dir);
+ fs.rmSync(staging, {recursive: true});
+ };
+ }
+ throw new Error("Another process is recovering this session; retry the operation");
+ } finally { fs.rmSync(staging, {recursive: true, force: true}); }
+ }
+ private lock(session: ClaudeSession, recover = false) {
+ const dir = this.dir(session.owner, session.id), file = path.join(dir, "operation.lock"), nonce = randomUUID();
+ const staged = path.join(dir, `.operation-${nonce}.tmp`);
+ let releaseGuard: (() => void) | undefined;
+ try {
+ const fd = fs.openSync(staged, "wx", 0o600);
+ try { fs.writeFileSync(fd, JSON.stringify({pid: process.pid, nonce, identity: processIdentity(process.pid)})); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+ if (recover) {
+ releaseGuard = this.recoveryGuard(dir);
+ if (fs.existsSync(file)) {
+ this.localPath(file, false);
+ const bytes = fs.readFileSync(file, "utf8"), prior: unknown = JSON.parse(bytes);
+ if (!deadLockOwner(prior)) throw new Error("Another process is using this session or its operation owner is unknown");
+ fs.unlinkSync(file);
+ }
+ }
+ // Atomic no-replace publication also prevents an ownerless operation
+ // lock if the process crashes between opening and writing its record.
+ try { fs.linkSync(staged, file); } catch { throw new Error("This session is in use or needs recovery after a process exit"); }
+ syncDirectory(dir);
+ } finally { try { releaseGuard?.(); } finally { fs.rmSync(staged, {force: true}); } }
+ return () => { if (JSON.parse(fs.readFileSync(file, "utf8")).nonce === nonce) fs.unlinkSync(file); };
+ }
+ private async exclusive<T>(id: string, work: (signal: AbortSignal) => Promise<T>, recover = false): Promise<T> {
+ const job = this.reserve(id);
+ let release: (() => void) | undefined;
+ try { const session = await this.get(id); interrupted(job.signal); release = this.lock(session, recover); return await work(job.signal); }
+ finally { try { release?.(); } finally { job.finish(); } }
+ }
+ async recover(id: string) { return this.exclusive(id, signal => this.recoverStopped(id, signal), true); }
+ private async recoverStopped(id: string, signal: AbortSignal) {
+ const session = await this.get(id), dir = this.dir(session.owner, id), turn = session.turns.at(-1);
+ if (!turn) return session;
+ await this.access(session.owner, signal);
+ await this.restoreContainerIfMissing(session, signal);
+ await this.docker(["stop", "--time", "3", session.container]);
+ turn.after = await this.checkpoint(session.container, dir, this.checkpoints(session));
+ this.repointArchive(session, turn.after);
+ if (turn.status === "running") turn.status = "interrupted";
+ const recovered = await this.collect(session, true, turn.status === "complete");
+ turn.sdkEnd = recovered.streams.sdk;
+ turn.finishedAt ??= new Date().toISOString();
+ save(path.join(dir, "session.json"), session); await this.pruneArchives(session); return session;
+ }
+ async events(id: string): Promise<DisplayEvent[]> {
+ const session = await this.get(id), dir = this.dir(session.owner, id), output: DisplayEvent[] = [];
+ const stream = path.join(dir, "native", "events", "sdk.jsonl");
+ const bytes = await fsp.readFile(stream).catch(() => Buffer.alloc(0));
+ // SDK init/result batches also occur for background-agent notifications.
+ // Only the host's submitted-turn byte boundaries define a user's turn.
+ for (const submitted of session.turns) {
+ const turn = submitted.number;
+ output.push({type: "user", text: submitted.prompt, turn});
+ if (!Number.isSafeInteger(submitted.sdkStart)) continue; // pre-pilot captures have no reliable SDK boundary
+ const text = bytes.subarray(submitted.sdkStart, submitted.sdkEnd ?? bytes.length).toString("utf8");
+ for (const line of text.split("\n")) {
+ let event: unknown; try { event = JSON.parse(line); } catch { continue; }
+ if (!isRecord(event)) continue;
+ if (event.type === "assistant" && isRecord(event.message) && Array.isArray(event.message.content)) for (const block of event.message.content) {
+ if (!isRecord(block)) continue;
+ if (block.type === "text" && typeof block.text === "string") output.push({type: "assistant", text: block.text, turn});
+ if (block.type === "thinking" && typeof block.thinking === "string") output.push({type: "thinking", text: block.thinking, turn});
+ if (block.type === "tool_use" && typeof block.name === "string") output.push({type: "tool", text: block.name, turn});
+ }
+ }
+ if (submitted.status !== "running") output.push({type: "result", text: submitted.status === "complete" ? "Turn finished" : submitted.status === "interrupted" ? "Turn interrupted" : "Turn failed", turn});
+ }
+ return output;
+ }
+ async verify(id: string, command = "node -e \"require('fs').accessSync('/workspace')\"") { return this.exclusive(id, () => this.verifyStopped(id, command)); }
+ private async verifyStopped(id: string, command: string) {
+ const session = await this.get(id), dir = this.dir(session.owner, id), checkpoint = session.turns.at(-1)?.after ?? session.base;
+ await this.access(session.owner);
+ this.collector(session).verify();
+ const checked = new Set<string>();
+ for (const cp of this.checkpoints(session)) {
+ if (checked.has(cp.file)) continue;
+ if (await fileHash(path.join(dir, cp.file)) !== cp.sha256) throw new Error("Environment archive integrity failure");
+ checked.add(cp.file);
+ }
+ await this.loadCheckpoint(checkpoint, dir);
+ const name = `omnirush-verify-${randomUUID()}`;
+ try {
+ const output = await this.docker(["run", "--name", name, "--network=none", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--pids-limit=128", "--memory=2g", checkpoint.image, "bash", "-lc", command]);
+ const report = {schema: 1, sessionId: id, checkpoint: checkpoint.image, verifiedAt: new Date().toISOString(), command, output, status: "restored", meaning: "Exact environment restored and verification command passed; model re-execution is not claimed"};
+ save(path.join(dir, "replay.json"), report); session.replay = "restored"; save(path.join(dir, "session.json"), session); return report;
+ } finally { await this.docker(["rm", "-f", name]).catch(() => {}); }
+ }
+ async export(id: string) { return this.exclusive(id, () => this.exportStopped(id), true); }
+ async prepareUpload(id: string, checkpoint: boolean) {
+ return this.exclusive(id, async () => {
+ const session = await this.get(id), stateDirectory = this.dir(session.owner, id);
+ const bindingId = session.authorization?.bindingId, contractHash = session.contractSha256;
+ if (!bindingId || !contractHash) throw new Error("This capture has no backend session binding; retain its local ZIP");
+ const nativeDirectory = path.join(stateDirectory, `native-upload-${randomUUID()}`);
+ this.collector(session).exportTo(nativeDirectory);
+ save(path.join(nativeDirectory, "session.json"), session);
+ await fsp.cp(path.join(stateDirectory, "policy"), path.join(nativeDirectory, "policy"), {recursive: true});
+ const diagnostics = path.join(stateDirectory, "transport", "stderr.jsonl");
+ if (fs.existsSync(diagnostics)) {
+ privateDir(path.join(nativeDirectory, "diagnostics"));
+ await fsp.copyFile(diagnostics, path.join(nativeDirectory, "diagnostics", "stderr.jsonl"));
+ }
+ const manifestSha256 = await writeBundleManifest(nativeDirectory, {sessionId: id, bindingId, contractHash, engineVersion: session.claudeVersion}, "claude_native");
+ let checkpointFile: string | undefined, checkpointManifestSha256: string | undefined;
+ if (checkpoint) {
+ const file = await this.exportStopped(id, hash => { checkpointManifestSha256 = hash; });
+ const sha = await fileHash(file);
+ checkpointFile = path.join(stateDirectory, `checkpoint-${sha}.zip`);
+ try { await fsp.link(file, checkpointFile); }
+ catch (error) {
+ if (!(isRecord(error) && error.code === "EEXIST") || await fileHash(checkpointFile) !== sha) throw error;
+ }
+ }
+ return {session, stateDirectory, nativeDirectory, manifestSha256, checkpointFile, checkpointManifestSha256};
+ });
+ }
+ private async exportStopped(id: string, onManifest?: (hash: string) => void) {
+ const session = await this.get(id), dir = this.dir(session.owner, id);
+ const validateTree = (file: string) => {
+ const stat = fs.lstatSync(file); this.localPath(file, stat.isDirectory());
+ if (stat.isDirectory()) for (const name of fs.readdirSync(file)) validateTree(path.join(file, name));
+ };
+ for (const name of ["native", "policy", "images", "transport", "replay.json"]) {
+ const file = path.join(dir, name);
+ try { validateTree(file); } catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
+ }
+ for (const name of [`${id}.zip`, `${id}.zip.tmp`]) {
+ try { this.localPath(path.join(dir, name), false); } catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
+ }
+ try { this.localPath(path.join(dir, "config"), true); } catch (error) { if (!isRecord(error) || error.code !== "ENOENT") throw error; }
+ const bundle = path.join(dir, `export-${randomUUID()}`); this.collector(session, true).exportTo(bundle);
+ try {
+ // Legacy/invalid classification is a derived observation, never a claim
+ // that old evidence was captured under today's model policy.
+ save(path.join(bundle, "session.json"), session);
+ if (fs.existsSync(path.join(dir, "policy"))) await fsp.cp(path.join(dir, "policy"), path.join(bundle, "policy"), {recursive: true});
+ if (fs.existsSync(path.join(dir, "replay.json"))) fs.copyFileSync(path.join(dir, "replay.json"), path.join(bundle, "replay.json"));
+ await fsp.cp(path.join(dir, "images"), path.join(bundle, "images"), {recursive: true});
+ // Diagnostics are private evidence too; they must not disappear from the
+ // downloadable bundle when an SDK turn or tool fails.
+ const diagnostics = path.join(dir, "transport", "stderr.jsonl");
+ if (fs.existsSync(diagnostics)) {
+ privateDir(path.join(bundle, "diagnostics"));
+ fs.copyFileSync(diagnostics, path.join(bundle, "diagnostics", "stderr.jsonl"));
+ }
+ fs.writeFileSync(path.join(bundle, "verify.py"), REPLAY_ADAPTER, {mode: 0o600});
+ // Saved evidence is sufficient for export, even if the process crashed
+ // while the container was running. Never contact Docker or copy mutable
+ // container state into this local snapshot; the saved images are authority.
+ save(path.join(bundle, "diagnostics", "export.json"), {schema: 1, workspaceCopy: "not-requested", source: "saved-evidence", savedImagesRetained: true});
+ fs.writeFileSync(path.join(bundle, "README.txt"), "Private Claude Code evidence. Contains original transcripts, provider-exposed thinking summaries and opaque signatures, SDK/hook events, complete environment images, and project files. Do not publish. Restore: gunzip -c images/<hash>.tar.gz | docker load; run the image digest recorded in session.json with --network=none. replay.json records environment restoration, not deterministic model re-execution. Recorded-tool replay: on an isolated worker with the reviewed omniconv verifier installed, run python3 verify.py <this-session.zip> --out <new-private-report-directory>. The adapter checks native evidence hashes, loads each exact before image, replays all root and child tool calls with networking disabled, and compares project files and modes with the captured after image. Add --check-path /absolute/path to compare additional filesystem scopes. Unsupported calls remain unverified. Reports and raw bundles require a separate masking/delivery review before distribution.\n", {mode: 0o600});
+ if (session.authorization?.bindingId && session.contractSha256) {
+ const hash = await writeBundleManifest(bundle, {sessionId: id, bindingId: session.authorization.bindingId, contractHash: session.contractSha256, engineVersion: session.claudeVersion}, "claude_checkpoint");
+ onManifest?.(hash);
+ }
+ const zip = path.join(dir, `${id}.zip`); await zipDirectory(bundle, zip); return zip;
+ } finally { await fsp.rm(bundle, {recursive: true, force: true}); }
+ }
+ async shutdown() { this.closed = true; for (const job of this.running.values()) job.stop.abort(); await Promise.all([...this.running.values()].map(job => job.done)); }
+}
diff --git a/apps/server/src/claude-code/sandbox-assets.ts b/apps/server/src/claude-code/sandbox-assets.ts
new file mode 100644
index 00000000..fba8899e
--- /dev/null
+++ b/apps/server/src/claude-code/sandbox-assets.ts
@@ -0,0 +1,102 @@
+// Embedded so the compiled desktop server and the CLI ship exactly the same runner.
+export const SDK_VERSION = "0.3.306";
+export const CLAUDE_VERSION = "2.1.306";
+export const IMAGE = `omnirush-claude-sdk:${SDK_VERSION}-3`;
+export const MODEL = "claude-opus-5-5";
+export const CAPTURE_POLICY_VERSION = "claude-native-2";
+// This is also passed as SDK managed policy. The on-disk copy is root-owned
+// so a project setting or tool cannot widen it for a nested Claude process.
+export const MANAGED_SETTINGS = JSON.stringify({availableModels: [MODEL], availableModelsMatch: "exact", enforceAvailableModels: true, deniedModels: ["sonnet", "haiku"], allowManagedHooksOnly: true});
+export const DOCKERFILE = `FROM node:22.21.1-bookworm-slim
+RUN apt-get update && apt-get install -y --no-install-recommends git ripgrep python3 python3-venv ca-certificates zip unzip procps && rm -rf /var/lib/apt/lists/*
+RUN corepack enable && corepack prepare [email protected] --activate
+WORKDIR /opt/claude
+COPY package.json pnpm-lock.yaml ./
+RUN pnpm install --frozen-lockfile --prod
+COPY controller.mjs ./
+COPY managed-settings.json /etc/claude-code/managed-settings.json
+RUN mkdir -p /workspace /home/node/.claude /home/node/evidence && chown -R node:node /workspace /home/node
+ENV HOME=/home/node CLAUDE_CONFIG_DIR=/home/node/.claude
+USER node
+WORKDIR /workspace
+CMD ["sleep", "infinity"]
+`;
+
+export const CONTROLLER = String.raw`
+import fs from 'node:fs';
+import { createHash } from 'node:crypto';
+import { query } from '@anthropic-ai/claude-agent-sdk';
+const input = [];
+for await (const chunk of process.stdin) input.push(chunk);
+const request = JSON.parse(Buffer.concat(input).toString('utf8'));
+const append = (file, value) => {
+ const fd = fs.openSync(file, 'a', 0o600);
+ try { fs.writeFileSync(fd, JSON.stringify(value) + '\n'); fs.fsyncSync(fd); }
+ finally { fs.closeSync(fd); }
+};
+const evidence = '/home/node/evidence';
+fs.mkdirSync(evidence, {recursive: true, mode: 0o700});
+const hooks = {};
+for (const event of ['PreToolUse','PostToolUse','PostToolUseFailure','SubagentStart','SubagentStop','PreCompact','PostCompact','SessionStart','SessionEnd','Stop','StopFailure']) {
+ hooks[event] = [{hooks: [async (input, toolUseId) => {
+ let witness;
+ if (event === 'PreToolUse' && input.tool_name === 'Read' && typeof input.tool_input?.file_path === 'string') {
+ const file = input.tool_input.file_path;
+ try {
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);
+ try {
+ const stat = fs.fstatSync(fd);
+ if (stat.isFile() && stat.size <= 512 * 1024 * 1024) {
+ const hash = createHash('sha256'), buffer = Buffer.alloc(1024 * 1024);
+ for (;;) { const count = fs.readSync(fd, buffer); if (!count) break; hash.update(buffer.subarray(0, count)); }
+ const after = fs.fstatSync(fd);
+ if (after.size === stat.size && after.mtimeMs === stat.mtimeMs && after.ctimeMs === stat.ctimeMs) witness = {path: file, bytes: stat.size, sha256: hash.digest('hex'), mode: stat.mode};
+ }
+ } finally { fs.closeSync(fd); }
+ } catch { /* Missing/unreadable files retain their actual failed tool result. */ }
+ }
+ append(evidence + '/hooks.jsonl', {time: new Date().toISOString(), turn: request.turn, input, toolUseId, witness});
+ return {};
+ }]}];
+}
+const env = {
+ PATH: process.env.PATH, HOME: '/home/node', LANG: 'C.UTF-8',
+ CLAUDE_CONFIG_DIR: '/home/node/.claude',
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_AUTOUPDATER: '1',
+ CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1',
+ CLAUDE_CODE_SHELL: '/bin/bash',
+ ANTHROPIC_MODEL: request.model, ANTHROPIC_DEFAULT_MODEL: request.model,
+ ANTHROPIC_DEFAULT_OPUS_MODEL: request.model,
+ ANTHROPIC_DEFAULT_SONNET_MODEL: request.model, ANTHROPIC_DEFAULT_HAIKU_MODEL: request.model,
+ ANTHROPIC_DEFAULT_FABLE_MODEL: request.model, ANTHROPIC_SMALL_FAST_MODEL: request.model,
+ CLAUDE_CODE_SUBAGENT_MODEL: request.model, CLAUDE_CODE_SUBAGENT_MODEL_FORCE: '1',
+ CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL: request.model,
+ CLAUDE_CODE_AUTO_MODE_MODEL: request.model, CLAUDE_CODE_BG_CLASSIFIER_MODEL: request.model,
+ CLAUDE_CODE_NO_MODEL_FALLBACK: '1', CLAUDE_CODE_DISABLE_MODEL_ACCESS_FALLBACK: '1',
+ ANTHROPIC_BASE_URL: request.baseUrl, ANTHROPIC_AUTH_TOKEN: request.token,
+};
+let success = false;
+try {
+ for await (const message of query({prompt: request.prompt, options: {
+ cwd: '/workspace', env, model: request.model,
+ ...(request.resume ? {resume: request.sessionId} : {sessionId: request.sessionId}),
+ persistSession: true, includePartialMessages: true, forwardSubagentText: true,
+ includeHookEvents: true, settingSources: [],
+ managedSettings: {availableModels: [request.model], availableModelsMatch: 'exact', enforceAvailableModels: true, deniedModels: ['sonnet', 'haiku'], allowManagedHooksOnly: true},
+ settings: {model: request.model, fallbackModel: []},
+ systemPrompt: {type: 'preset', preset: 'claude_code'},
+ permissionMode: 'bypassPermissions', allowDangerouslySkipPermissions: true,
+ thinking: {type: 'adaptive'}, effort: 'high',
+ maxTurns: 100, hooks,
+ stderr: text => append(evidence + '/stderr.jsonl', {turn: request.turn, text}),
+ }})) {
+ append(evidence + '/sdk.jsonl', message);
+ // A disk acknowledgement precedes every event delivered to the host.
+ process.stdout.write(JSON.stringify(message) + '\n');
+ if (message.type === 'result') success = message.subtype === 'success' && !message.is_error;
+ }
+} catch (error) {
+ append(evidence + '/stderr.jsonl', {turn: request.turn, text: String(error)});
+}
+process.exitCode = success ? 0 : 1;
+`;
diff --git a/apps/server/src/claude-code/sandbox-lock.ts b/apps/server/src/claude-code/sandbox-lock.ts
new file mode 100644
index 00000000..c3d8f200
--- /dev/null
+++ b/apps/server/src/claude-code/sandbox-lock.ts
@@ -0,0 +1,13 @@
+// pnpm lockfile v9; installed with pnpm 10.27.0 in the sandbox. Exact SDK and transitive package integrity pins.
+export const PACKAGE_JSON = "{\"name\": \"omnirush-claude-sandbox\", \"private\": true, \"type\": \"module\", \"dependencies\": {\"@anthropic-ai/claude-agent-sdk\": \"0.3.306\"}}";
+export const LOCKFILE = "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n excludeLinksFromLockfile: false\n\nimporters:\n\n .:\n dependencies:\n '@anthropic-ai/claude-agent-sdk':\n specifier: 0.3.306\n version: 0.3.306(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])\n\npackages:\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-R8WM+XIYCaWlT/4whzVgBWX2PGuFJ+/ReqSleYSCPzs7l+S4udnwayZFvyOyfIPiYC7GLhHoPiNmMDzjDdaCxw==}\n cpu: [arm64]\n os: [darwin]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-EcgDYECaPRe447QpH1vzKMJs7AE+U/KiHqflfGr6qTfzH+1SF0oHX1dMVhGzaJn7KdGrDH9N72yPZXw7rj5Qtg==}\n cpu: [x64]\n os: [darwin]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-ak/r1xhFJM1A/Eidjpu7LQ31GQK72spfEGb4yay0coWtcaAvHERGO2sKWeT/Tv3SyrigxdTPTveLSYS1Vb4fbg==}\n cpu: [arm64]\n os: [linux]\n libc: [musl]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-Vee1MIEqd7I8NKF2GOLxLJOuCghf/k4poEk7E/p6zXCIt7MmmtrK7ph9/WiYqOgEpOagXm8D6fRgEJvxWYGIXg==}\n cpu: [arm64]\n os: [linux]\n libc: [glibc]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-jbQf6HmNIDGI4YnoBc/IqOPKT3GxUSddor8yA9tmCpfKPU4Ln+gcN2Md/u2a0jODEo1hcx1Fn33xxTdcaLmD2Q==}\n cpu: [x64]\n os: [linux]\n libc: [musl]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-2taDjG+UI0+VrPdxqRhl7Y9m4PPscXKxRVBDLHVSeFrA600HXGqyOIm34Pao6UVNlhCD+pKU/s7++OFGy88h2Q==}\n cpu: [x64]\n os: [linux]\n libc: [glibc]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-6nbxfp8hQ6Of0oVcEHBGpbf56siAishGw8DBamGiqau+ji87DBWPW06V8lbuB9C94REnGk73wNLnFJ5PgPTKSg==}\n cpu: [arm64]\n os: [win32]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-oQPai3jCeSZdTasTGSA8TGALdPxTILdcan09LaKbMCrXXYRR9njxVgmeIqvoH9h8YzKebPHW+Ks0eKKptLrtUw==}\n cpu: [x64]\n os: [win32]\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-kmxcd+4WNhqhqnzODRPM5aOKb1EH2EdlRsf7ZeMx8uQsC1tHAHgHftQGFXGT8yMaYaYlDP9BGYJy1/aYv7IhkQ==}\n engines: {node: '>=18.0.0'}\n peerDependencies:\n '@anthropic-ai/sdk': '>=0.93.0'\n '@modelcontextprotocol/sdk': ^1.29.0\n zod: ^4.0.0\n\n '@anthropic-ai/[email protected]':\n resolution: {integrity: sha512-Op/fKMsfVwFCfObc87leLOFlORE0RjOvLzRzPCWWLI7Ww6bobpKR6YmYC8ZYgulRh+m2a/3/61VUXoWHFtCXIw==}\n hasBin: true\n peerDependencies:\n zod: ^3.25.0 || ^4.0.0\n peerDependenciesMeta:\n zod:\n optional: true\n\n '@babel/[email protected]':\n resolution: {integrity: sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==}\n engines: {node: '>=6.9.0'}\n\n '@hono/[email protected]':\n resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==}\n engines: {node: '>=20'}\n peerDependencies:\n hono: ^4 || ^5.0.0-0\n\n '@modelcontextprotocol/[email protected]':\n resolution: {integrity: sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==}\n engines: {node: '>=18'}\n peerDependencies:\n '@cfworker/json-schema': ^4.1.1\n zod: ^3.25 || ^4.0\n peerDependenciesMeta:\n '@cfworker/json-schema':\n optional: true\n\n '@opentelemetry/[email protected]':\n resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==}\n engines: {node: '>=8.0.0'}\n\n '@stablelib/[email protected]':\n resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}\n\n [email protected]:\n resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}\n peerDependencies:\n ajv: ^8.0.0\n peerDependenciesMeta:\n ajv:\n optional: true\n\n [email protected]:\n resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}\n\n [email protected]:\n resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==}\n engines: {node: '>=6.6.0'}\n\n [email protected]:\n resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}\n engines: {node: '>= 0.10'}\n\n [email protected]:\n resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}\n engines: {node: '>= 8'}\n\n [email protected]:\n resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}\n engines: {node: '>=6.0'}\n peerDependencies:\n supports-color: '*'\n peerDependenciesMeta:\n supports-color:\n optional: true\n\n [email protected]:\n resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}\n\n [email protected]:\n resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==}\n\n [email protected]:\n resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==}\n engines: {node: '>=18.0.0'}\n\n [email protected]:\n resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==}\n engines: {node: '>=18.0.0'}\n\n [email protected]:\n resolution: {integrity: sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==}\n engines: {node: '>= 16'}\n peerDependencies:\n express: '>= 4.11'\n\n [email protected]:\n resolution: {integrity: sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}\n\n [email protected]:\n resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==}\n\n [email protected]:\n resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==}\n\n [email protected]:\n resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==}\n engines: {node: '>= 18.0.0'}\n\n [email protected]:\n resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}\n\n [email protected]:\n resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==}\n engines: {node: '>=16.9.0'}\n\n [email protected]:\n resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}\n engines: {node: '>=0.10.0'}\n\n [email protected]:\n resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}\n\n [email protected]:\n resolution: {integrity: sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==}\n engines: {node: '>= 12'}\n\n [email protected]:\n resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}\n engines: {node: '>= 0.10'}\n\n [email protected]:\n resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}\n\n [email protected]:\n resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}\n\n [email protected]:\n resolution: {integrity: sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==}\n\n [email protected]:\n resolution: {integrity: sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==}\n engines: {node: '>=16'}\n\n [email protected]:\n resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}\n\n [email protected]:\n resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==}\n\n [email protected]:\n resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}\n\n [email protected]:\n resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==}\n engines: {node: '>=18'}\n\n [email protected]:\n resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}\n engines: {node: '>=0.10.0'}\n\n [email protected]:\n resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}\n\n [email protected]:\n resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}\n engines: {node: '>=8'}\n\n [email protected]:\n resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==}\n\n [email protected]:\n resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}\n engines: {node: '>=16.20.0'}\n\n [email protected]:\n resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}\n engines: {node: '>= 0.10'}\n\n [email protected]:\n resolution: {integrity: sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==}\n engines: {node: '>=0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==}\n engines: {node: '>= 0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}\n engines: {node: '>= 0.10'}\n\n [email protected]:\n resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}\n engines: {node: '>=0.10.0'}\n\n [email protected]:\n resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}\n\n [email protected]:\n resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}\n\n [email protected]:\n resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}\n engines: {node: '>=8'}\n\n [email protected]:\n resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}\n engines: {node: '>=8'}\n\n [email protected]:\n resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}\n engines: {node: '>= 0.4'}\n\n [email protected]:\n resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==}\n\n [email protected]:\n resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}\n engines: {node: '>=0.6'}\n\n [email protected]:\n resolution: {integrity: sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==}\n\n [email protected]:\n resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==}\n engines: {node: '>= 18'}\n\n [email protected]:\n resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}\n engines: {node: '>= 0.8'}\n\n [email protected]:\n resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}\n engines: {node: '>= 8'}\n hasBin: true\n\n [email protected]:\n resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}\n\n [email protected]:\n resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}\n peerDependencies:\n zod: ^3.25.28 || ^4\n\n [email protected]:\n resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}\n\nsnapshots:\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected]':\n optional: true\n\n '@anthropic-ai/[email protected](@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])':\n dependencies:\n '@anthropic-ai/sdk': 1.1.0([email protected])\n '@modelcontextprotocol/sdk': 1.32.1([email protected])\n zod: 4.6.7\n optionalDependencies:\n '@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-darwin-x64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-linux-arm64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-linux-arm64-musl': 0.3.306\n '@anthropic-ai/claude-agent-sdk-linux-x64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-linux-x64-musl': 0.3.306\n '@anthropic-ai/claude-agent-sdk-win32-arm64': 0.3.306\n '@anthropic-ai/claude-agent-sdk-win32-x64': 0.3.306\n\n '@anthropic-ai/[email protected]([email protected])':\n dependencies:\n '@opentelemetry/api': 1.10.0\n json-schema-to-ts: 3.1.1\n standardwebhooks: 1.1.1\n optionalDependencies:\n zod: 4.6.7\n\n '@babel/[email protected]': {}\n\n '@hono/[email protected]([email protected])':\n dependencies:\n hono: 4.13.13\n\n '@modelcontextprotocol/[email protected]([email protected])':\n dependencies:\n '@hono/node-server': 2.1.5([email protected])\n ajv: 8.20.0\n ajv-formats: 3.0.1([email protected])\n content-type: 1.0.5\n cors: 2.8.6\n cross-spawn: 7.0.6\n eventsource: 3.0.7\n eventsource-parser: 3.1.1\n express: 5.3.0\n express-rate-limit: 8.7.1([email protected])\n hono: 4.13.13\n jose: 6.2.13\n json-schema-typed: 8.0.2\n pkce-challenge: 5.0.1\n raw-body: 3.0.2\n zod: 4.6.7\n zod-to-json-schema: 3.25.2([email protected])\n transitivePeerDependencies:\n - supports-color\n\n '@opentelemetry/[email protected]': {}\n\n '@stablelib/[email protected]': {}\n\n [email protected]:\n dependencies:\n mime-types: 3.0.2\n negotiator: 1.1.0\n\n [email protected]([email protected]):\n optionalDependencies:\n ajv: 8.20.0\n\n [email protected]:\n dependencies:\n fast-deep-equal: 3.1.3\n fast-uri: 3.1.9\n json-schema-traverse: 1.0.0\n require-from-string: 2.0.2\n\n [email protected]:\n dependencies:\n bytes: 3.1.2\n content-type: 2.1.0\n debug: 4.4.3\n http-errors: 2.0.1\n iconv-lite: 0.7.3\n on-finished: 2.4.2\n qs: 6.16.1\n raw-body: 3.0.2\n type-is: 2.1.0\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n es-errors: 1.3.0\n function-bind: 1.1.2\n\n [email protected]:\n dependencies:\n call-bind-apply-helpers: 1.0.2\n get-intrinsic: 1.3.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n object-assign: 4.1.1\n vary: 1.1.2\n\n [email protected]:\n dependencies:\n path-key: 3.1.1\n shebang-command: 2.0.0\n which: 2.0.2\n\n [email protected]:\n dependencies:\n ms: 2.1.3\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n call-bind-apply-helpers: 1.0.2\n es-errors: 1.3.0\n gopd: 1.2.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n es-errors: 1.3.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n eventsource-parser: 3.1.1\n\n [email protected]([email protected]):\n dependencies:\n debug: 4.4.3\n express: 5.3.0\n ip-address: 10.7.4\n transitivePeerDependencies:\n - supports-color\n\n [email protected]:\n dependencies:\n accepts: 2.0.0\n body-parser: 2.4.0\n content-disposition: 2.0.1\n content-type: 2.1.0\n cookie: 0.7.2\n cookie-signature: 1.2.2\n debug: 4.4.3\n depd: 2.0.0\n encodeurl: 2.0.0\n escape-html: 1.0.3\n etag: 1.8.1\n finalhandler: 2.1.1\n fresh: 2.0.0\n http-errors: 2.0.1\n merge-descriptors: 2.0.0\n mime-types: 3.0.2\n on-finished: 2.4.2\n once: 1.4.0\n parseurl: 1.3.3\n proxy-addr: 2.0.8\n qs: 6.16.1\n range-parser: 1.3.0\n router: 2.2.0\n send: 1.2.1\n serve-static: 2.2.1\n statuses: 2.0.2\n type-is: 2.1.0\n vary: 1.1.2\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n debug: 4.4.3\n encodeurl: 2.0.0\n escape-html: 1.0.3\n on-finished: 2.4.2\n parseurl: 1.3.3\n statuses: 2.0.2\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n call-bind-apply-helpers: 1.0.2\n es-define-property: 1.0.1\n es-errors: 1.3.0\n es-object-atoms: 1.1.2\n function-bind: 1.1.2\n get-proto: 1.0.1\n gopd: 1.2.0\n has-symbols: 1.1.0\n hasown: 2.0.4\n math-intrinsics: 1.1.0\n\n [email protected]:\n dependencies:\n dunder-proto: 1.0.1\n es-object-atoms: 1.1.2\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n function-bind: 1.1.2\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n depd: 2.0.0\n inherits: 2.0.4\n setprototypeof: 1.2.0\n statuses: 2.0.2\n toidentifier: 1.0.1\n\n [email protected]:\n dependencies:\n safer-buffer: 2.1.2\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n '@babel/runtime': 7.29.10\n ts-algebra: 2.0.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n mime-db: 1.54.0\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n content-type: 2.1.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n ee-first: 1.1.1\n\n [email protected]:\n dependencies:\n wrappy: 1.0.2\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n forwarded: 0.2.0\n ipaddr.js: 1.9.1\n\n [email protected]:\n dependencies:\n es-define-property: 1.0.1\n side-channel: 1.1.1\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n bytes: 3.1.2\n http-errors: 2.0.1\n iconv-lite: 0.7.3\n unpipe: 1.0.0\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n debug: 4.4.3\n depd: 2.0.0\n is-promise: 4.0.0\n parseurl: 1.3.3\n path-to-regexp: 8.4.2\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n debug: 4.4.3\n encodeurl: 2.0.0\n escape-html: 1.0.3\n etag: 1.8.1\n fresh: 2.0.0\n http-errors: 2.0.1\n mime-types: 3.0.2\n ms: 2.1.3\n on-finished: 2.4.2\n range-parser: 1.3.0\n statuses: 2.0.2\n transitivePeerDependencies:\n - supports-color\n\n [email protected]:\n dependencies:\n encodeurl: 2.0.0\n escape-html: 1.0.3\n parseurl: 1.3.3\n send: 1.2.1\n transitivePeerDependencies:\n - supports-color\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n shebang-regex: 3.0.0\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n es-errors: 1.3.0\n object-inspect: 1.13.4\n\n [email protected]:\n dependencies:\n call-bound: 1.0.4\n es-errors: 1.3.0\n get-intrinsic: 1.3.0\n object-inspect: 1.13.4\n\n [email protected]:\n dependencies:\n call-bound: 1.0.4\n es-errors: 1.3.0\n get-intrinsic: 1.3.0\n object-inspect: 1.13.4\n side-channel-map: 1.0.1\n\n [email protected]:\n dependencies:\n es-errors: 1.3.0\n object-inspect: 1.13.4\n side-channel-list: 1.0.1\n side-channel-map: 1.0.1\n side-channel-weakmap: 1.0.2\n\n [email protected]:\n dependencies:\n '@stablelib/base64': 1.0.1\n fast-sha256: 1.3.0\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n content-type: 2.1.0\n media-typer: 1.1.1\n mime-types: 3.0.2\n\n [email protected]: {}\n\n [email protected]: {}\n\n [email protected]:\n dependencies:\n isexe: 2.0.0\n\n [email protected]: {}\n\n [email protected]([email protected]):\n dependencies:\n zod: 4.6.7\n\n [email protected]: {}\n";
+
+// Derive the backend admission pin from the exact lock used by the Docker build.
+export const SDK_INSTALL_PIN = (() => {
+ const name = "@anthropic-ai/claude-agent-sdk";
+ const version: string = JSON.parse(PACKAGE_JSON).dependencies[name];
+ const section = LOCKFILE.split("\n '" + name + "@" + version + "':\n")[1];
+ const integrity = /^ resolution: \{integrity: (sha512-[A-Za-z0-9+/]+={0,2})\}/.exec(section ?? "")?.[1];
+ if (!integrity) throw new Error("The Claude SDK lock has no package integrity pin");
+ return Object.freeze({package: name, version, integrity});
+})();
diff --git a/apps/server/src/claude-code/transfer.ts b/apps/server/src/claude-code/transfer.ts
new file mode 100644
index 00000000..c589e186
--- /dev/null
+++ b/apps/server/src/claude-code/transfer.ts
@@ -0,0 +1,23 @@
+import type { ClaudeRuntime } from "./runtime.js";
+import { parseNativeCaptureCapabilities, uploadNativeBundle, type NativeArchiveDriver, type NativeUploadRequest } from "./upload.js";
+
+export async function uploadClaudeSession(runtime: ClaudeRuntime, id: string,
+ request: (owner: string, ...args: Parameters<NativeUploadRequest>) => Promise<Response>,
+ driver: (owner: string) => NativeArchiveDriver) {
+ const {owner} = await runtime.get(id);
+ const response = await request(owner, "collect/capabilities", {method: "GET"});
+ if (!response.ok) throw new Error(`Native archive upload is unavailable (${response.status}); local evidence retained`);
+ const value: unknown = await response.json();
+ const code = value && typeof value === "object" && "claude_code" in value ? value.claude_code : null;
+ const capture = code && typeof code === "object" && "capture" in code ? code.capture : null;
+ const capabilities = parseNativeCaptureCapabilities(capture);
+ if (!capabilities) throw new Error("The backend has not enabled native archive capture; local evidence retained");
+ const prepared = await runtime.prepareUpload(id, capabilities.checkpoint.enabled);
+ const {session} = prepared, bindingId = session.authorization?.bindingId, contractHash = session.contractSha256;
+ if (session.owner !== owner || !bindingId || !contractHash) throw new Error("The archive must use its original account and session binding");
+ return uploadNativeBundle({
+ ...prepared, sessionId: id, owner, bindingId, contractHash, turn: session.turns.length,
+ engineVersion: session.claudeVersion, boxImage: session.turns.at(-1)?.after?.image ?? session.base.image,
+ capabilities, driver: driver(owner),
+ });
+}
diff --git a/apps/server/src/claude-code/upload.ts b/apps/server/src/claude-code/upload.ts
new file mode 100644
index 00000000..da9daec7
--- /dev/null
+++ b/apps/server/src/claude-code/upload.ts
@@ -0,0 +1,265 @@
+import fs from "node:fs";
+import fsp from "node:fs/promises";
+import path from "node:path";
+import { createHash, randomUUID } from "node:crypto";
+import { Readable, Transform } from "node:stream";
+import { pipeline } from "node:stream/promises";
+import { constants as zlibConstants, createZstdCompress } from "node:zlib";
+
+export type NativeUploadRequest = (route: string, init: {method: "GET" | "POST"; body?: string; signal?: AbortSignal; refresh?: false}) => Promise<Response>;
+export type NativeCaptureCapabilities = {
+ schema: 1;
+ native: {enabled: boolean; max_bytes: number};
+ checkpoint: {enabled: boolean; max_bytes: number; retention_days: number | null};
+};
+export type NativeArchivePayload = "claude_native" | "claude_checkpoint";
+export type NativeArchiveCreate = {
+ archive_id: string; session_id: string; kind: "base"; sequence: number; turn: number;
+ parent_archive_id: null; marker: "project"; payload: NativeArchivePayload; harness: "claude-code";
+ engine_version: string; binding_id: string; contract_hash: string; manifest_sha256: string;
+ content: "tar+zstd" | "zip"; size: number; sha256: string; kid: string;
+ plain_size: number; plain_sha256: string; box_image?: string;
+};
+export type NativeArchiveJob = {
+ request: NativeArchiveCreate; sealedPath: string;
+ upload: {upload_id: string; object_key: string; part_size: number; part_count: number; etags: Record<string, string>} | null;
+ recreates: number;
+};
+type ArchiveKeyResult =
+ | {status: "ok"; key: {kid: string; publicKey: Buffer; alg: string}}
+ | {status: "disabled"; code: string}
+ | {status: "unavailable"; reason: string};
+type ArchiveOutcome = {status: string; code?: string; reason?: string};
+type Sealer = Transform & {kid: string; result(): {size: number; sha256: string}};
+/** Each surface supplies its existing archive crypto, tar headers and multipart uploader. */
+export type NativeArchiveDriver = {
+ fetchKey(signal?: AbortSignal): Promise<ArchiveKeyResult>;
+ upload(job: NativeArchiveJob, persist: () => Promise<void>, signal?: AbortSignal): Promise<ArchiveOutcome>;
+ sealer(options: {publicKey: Uint8Array; content: "tar+zstd" | "zip"}): Sealer;
+ tarHeader(member: {name: string; mode: number; size: number; mtime: number; typeflag: "0"}): Buffer;
+};
+export type NativeUploadOptions = {
+ sessionId: string; owner: string; turn: number; bindingId: string; contractHash: string; engineVersion: string;
+ nativeDirectory: string; stateDirectory: string;
+ checkpointFile?: string; checkpointManifestSha256?: string; boxImage?: string;
+ capabilities: NativeCaptureCapabilities; driver: NativeArchiveDriver; signal?: AbortSignal;
+};
+export type NativePayloadReceipt = {
+ status: "uploaded" | "pending" | "disabled"; payload: NativeArchivePayload; retained: true;
+ code?: string; archiveId?: string; sequence?: number; sha256?: string; bytes?: number;
+ plainSha256?: string; plainBytes?: number; manifestSha256?: string;
+};
+export type NativeUploadReceipt = {
+ status: "uploaded" | "partial" | "pending" | "disabled";
+ native: NativePayloadReceipt; checkpoint: NativePayloadReceipt;
+};
+type Member = {name: string; file: string; bytes: number; sha256: string};
+type SavedJob = {schema: 1; owner: string; fingerprint: string; state: "pending" | "uploaded"; job: NativeArchiveJob};
+const MANIFEST = "__omnirush__/manifest.json";
+const sha = (bytes: Uint8Array | string) => createHash("sha256").update(bytes).digest("hex");
+const isHash = (value: unknown): value is string => typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
+const record = (value: unknown): value is Record<string, unknown> => Boolean(value && typeof value === "object" && !Array.isArray(value));
+const hasCode = (error: unknown, code: string) => Boolean(error && typeof error === "object" && "code" in error && error.code === code);
+class NativeArchiveFailure extends Error {
+ constructor(readonly code: string) { super(code); }
+}
+
+export function parseNativeCaptureCapabilities(value: unknown): NativeCaptureCapabilities | null {
+ if (!record(value) || value.schema !== 1 || !record(value.native) || !record(value.checkpoint)) return null;
+ const native = value.native, checkpoint = value.checkpoint;
+ if (typeof native.enabled !== "boolean" || typeof checkpoint.enabled !== "boolean"
+ || typeof native.max_bytes !== "number" || !Number.isSafeInteger(native.max_bytes) || native.max_bytes <= 0
+ || typeof checkpoint.max_bytes !== "number" || !Number.isSafeInteger(checkpoint.max_bytes) || checkpoint.max_bytes <= 0
+ || !(checkpoint.retention_days === null || typeof checkpoint.retention_days === "number" && Number.isSafeInteger(checkpoint.retention_days) && checkpoint.retention_days > 0)) return null;
+ return {schema: 1, native: {enabled: native.enabled, max_bytes: native.max_bytes}, checkpoint: {enabled: checkpoint.enabled, max_bytes: checkpoint.max_bytes, retention_days: checkpoint.retention_days}};
+}
+
+async function fileHash(file: string, signal?: AbortSignal): Promise<{bytes: number; sha256: string}> {
+ const digest = createHash("sha256"); let bytes = 0;
+ const handle = await fsp.open(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
+ try {
+ const before = await handle.stat(); if (!before.isFile()) throw new NativeArchiveFailure("archive_member_not_regular");
+ for await (const chunk of handle.createReadStream({autoClose: false})) { signal?.throwIfAborted(); digest.update(chunk); bytes += chunk.length; }
+ const after = await handle.stat();
+ if (before.size !== bytes || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw new NativeArchiveFailure("archive_source_changed");
+ return {bytes, sha256: digest.digest("hex")};
+ } finally { await handle.close(); }
+}
+
+async function members(directory: string, signal?: AbortSignal): Promise<Member[]> {
+ const out: Member[] = [];
+ const visit = async (dir: string): Promise<void> => {
+ const stat = await fsp.lstat(dir); if (!stat.isDirectory() || stat.isSymbolicLink()) throw new NativeArchiveFailure("archive_directory_invalid");
+ const entries = await fsp.readdir(dir, {withFileTypes: true}); entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
+ for (const entry of entries) {
+ signal?.throwIfAborted(); const file = path.join(dir, entry.name);
+ if (entry.isDirectory()) { await visit(file); continue; }
+ if (!entry.isFile()) throw new NativeArchiveFailure("archive_member_unsupported");
+ out.push({name: path.relative(directory, file).split(path.sep).join("/"), file, ...await fileHash(file, signal)});
+ }
+ };
+ await visit(directory); return out;
+}
+
+async function* exactBytes(member: Member, signal?: AbortSignal): AsyncGenerator<Buffer> {
+ const handle = await fsp.open(member.file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
+ const digest = createHash("sha256"); let bytes = 0;
+ try {
+ if (!(await handle.stat()).isFile()) throw new NativeArchiveFailure("archive_member_not_regular");
+ for await (const chunk of handle.createReadStream({autoClose: false})) {
+ signal?.throwIfAborted(); bytes += chunk.length; digest.update(chunk); yield chunk;
+ }
+ if (bytes !== member.bytes || digest.digest("hex") !== member.sha256) throw new NativeArchiveFailure("archive_source_changed");
+ } finally { await handle.close(); }
+}
+
+async function* nativeTar(input: Member[], driver: NativeArchiveDriver, signal?: AbortSignal): AsyncGenerator<Buffer> {
+ for (const member of input) {
+ signal?.throwIfAborted();
+ yield driver.tarHeader({name: member.name, mode: 0o600, size: member.bytes, mtime: 0, typeflag: "0"});
+ yield* exactBytes(member, signal);
+ if (member.bytes % 512) yield Buffer.alloc(512 - member.bytes % 512);
+ }
+ yield Buffer.alloc(1024);
+}
+
+async function persist(file: string, value: unknown): Promise<void> {
+ const temporary = `${file}.${randomUUID()}.tmp`, handle = await fsp.open(temporary, "wx", 0o600);
+ try { await handle.writeFile(JSON.stringify(value)); await handle.sync(); } finally { await handle.close(); }
+ await fsp.rename(temporary, file);
+ if (process.platform !== "win32") { const parent = await fsp.open(path.dirname(file), "r"); try { await parent.sync(); } finally { await parent.close(); } }
+}
+
+function receipt(saved: SavedJob, status: NativePayloadReceipt["status"], code?: string): NativePayloadReceipt {
+ const request = saved.job.request;
+ return {status, payload: request.payload, retained: true, ...(code ? {code} : {}), archiveId: request.archive_id,
+ sequence: request.sequence, sha256: request.sha256, bytes: request.size, plainSha256: request.plain_sha256,
+ plainBytes: request.plain_size, manifestSha256: request.manifest_sha256};
+}
+
+function validateManifest(bytes: Buffer, input: Member[], options: NativeUploadOptions): void {
+ let value: unknown;
+ try { value = JSON.parse(bytes.toString("utf8")); } catch { throw new NativeArchiveFailure("archive_manifest_invalid"); }
+ if (!record(value) || value.schema !== "omnirush.claude.native.v1" || value.session_id !== options.sessionId
+ || value.root_session_id !== options.sessionId || value.binding_id !== options.bindingId || value.contract_hash !== options.contractHash
+ || value.harness !== "claude-code" || value.engine_version !== options.engineVersion || value.payload !== "claude_native" || !Array.isArray(value.files)) throw new NativeArchiveFailure("archive_manifest_binding_mismatch");
+ const actual = input.filter(member => member.name !== MANIFEST).map(member => ({path: member.name, size: member.bytes, sha256: member.sha256})).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
+ if (JSON.stringify(value.files) !== JSON.stringify(actual)) throw new NativeArchiveFailure("archive_manifest_members_mismatch");
+}
+
+async function payload(options: NativeUploadOptions, kind: NativeArchivePayload): Promise<NativePayloadReceipt> {
+ const gate = kind === "claude_native" ? options.capabilities.native : options.capabilities.checkpoint;
+ const state = (status: NativePayloadReceipt["status"], code: string): NativePayloadReceipt => ({status, payload: kind, retained: true, code});
+ if (!gate.enabled) return state("disabled", "archive_payload_disabled");
+ if (options.signal?.aborted) return state("pending", "aborted");
+ if (kind === "claude_checkpoint" && (!options.checkpointFile || !isHash(options.checkpointManifestSha256) || !options.boxImage)) return state("pending", "checkpoint_not_prepared");
+ let input: Member[], manifestSha: string;
+ if (kind === "claude_native") {
+ input = await members(options.nativeDirectory, options.signal);
+ const manifest = input.find(member => member.name === MANIFEST);
+ if (!manifest) throw new NativeArchiveFailure("archive_manifest_missing");
+ const bytes = await fsp.readFile(manifest.file);
+ if (sha(bytes) !== manifest.sha256) throw new NativeArchiveFailure("archive_source_changed");
+ validateManifest(bytes, input, options); manifestSha = manifest.sha256;
+ input = [manifest, ...input.filter(member => member !== manifest)];
+ } else {
+ if (!options.checkpointFile || !options.checkpointManifestSha256) throw new Error("Checkpoint was not prepared");
+ input = [{name: "session.zip", file: options.checkpointFile, ...await fileHash(options.checkpointFile, options.signal)}];
+ manifestSha = options.checkpointManifestSha256;
+ if (input[0]!.bytes > gate.max_bytes) return state("pending", "archive_too_large");
+ }
+ const fingerprint = sha(JSON.stringify({session: options.sessionId, owner: options.owner, kind, binding: options.bindingId,
+ contract: options.contractHash, engine: options.engineVersion, turn: options.turn, manifestSha,
+ image: kind === "claude_checkpoint" ? options.boxImage : null, files: input.map(({name, bytes, sha256}) => ({name, bytes, sha256}))}));
+ const directory = path.join(options.stateDirectory, kind); await fsp.mkdir(directory, {recursive: true, mode: 0o700});
+ const savedPath = path.join(directory, `${fingerprint}.json`);
+ let saved: SavedJob | undefined;
+ try {
+ const value: SavedJob = JSON.parse(await fsp.readFile(savedPath, "utf8"));
+ if (value.schema !== 1 || value.owner !== options.owner || value.fingerprint !== fingerprint || value.job?.request?.session_id !== options.sessionId || value.job?.request?.payload !== kind) throw new NativeArchiveFailure("archive_resume_identity_mismatch");
+ saved = value;
+ } catch (error) { if (!hasCode(error, "ENOENT")) throw error; }
+ if (!saved) {
+ const key = await options.driver.fetchKey(options.signal);
+ if (key.status !== "ok") return state(key.status === "disabled" ? "disabled" : "pending", key.status === "disabled" ? key.code : key.reason);
+ let sequence = 0;
+ for (const name of await fsp.readdir(directory)) {
+ if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
+ const prior: SavedJob = JSON.parse(await fsp.readFile(path.join(directory, name), "utf8"));
+ if (prior.owner !== options.owner || prior.job?.request?.session_id !== options.sessionId || prior.job?.request?.payload !== kind || !Number.isSafeInteger(prior.job.request.sequence)) throw new NativeArchiveFailure("archive_sequence_ledger_invalid");
+ sequence = Math.max(sequence, prior.job.request.sequence + 1);
+ }
+ const archiveId = randomUUID(), sealedPath = path.join(directory, `${archiveId}.orseal`), temporary = `${sealedPath}.tmp`;
+ const content = kind === "claude_native" ? "tar+zstd" : "zip";
+ const sealer = options.driver.sealer({publicKey: key.key.publicKey, content});
+ const plainHash = createHash("sha256"); let plainBytes = 0;
+ const meter = new Transform({transform(chunk: Buffer, _encoding, callback) { plainBytes += chunk.length; plainHash.update(chunk); callback(null, chunk); }});
+ const output = fs.createWriteStream(temporary, {flags: "wx", mode: 0o600});
+ try {
+ if (kind === "claude_native") {
+ const compressor = createZstdCompress({params: {[zlibConstants.ZSTD_c_compressionLevel]: 3, [zlibConstants.ZSTD_c_checksumFlag]: 1}});
+ await pipeline(Readable.from(nativeTar(input, options.driver, options.signal)), compressor, meter, sealer, output, {signal: options.signal});
+ } else await pipeline(Readable.from(exactBytes(input[0]!, options.signal)), meter, sealer, output, {signal: options.signal});
+ const handle = await fsp.open(temporary, "r"); try { await handle.sync(); } finally { await handle.close(); }
+ await fsp.rename(temporary, sealedPath);
+ } catch (error) { await fsp.rm(temporary, {force: true}); throw error; }
+ const sealed = sealer.result();
+ if (sealer.kid !== key.key.kid) throw new NativeArchiveFailure("archive_key_mismatch");
+ saved = {schema: 1, owner: options.owner, fingerprint, state: "pending", job: {request: {
+ archive_id: archiveId, session_id: options.sessionId, kind: "base", sequence, turn: options.turn, parent_archive_id: null,
+ marker: "project", payload: kind, harness: "claude-code", engine_version: options.engineVersion, binding_id: options.bindingId,
+ contract_hash: options.contractHash, manifest_sha256: manifestSha, content, size: sealed.size, sha256: sealed.sha256,
+ kid: sealer.kid, plain_size: plainBytes, plain_sha256: plainHash.digest("hex"),
+ ...(kind === "claude_checkpoint" ? {box_image: options.boxImage} : {}),
+ }, sealedPath, upload: null, recreates: 0}};
+ await persist(savedPath, saved);
+ }
+ if (saved.state === "uploaded") return receipt(saved, "uploaded");
+ if (saved.job.request.size > gate.max_bytes) return receipt(saved, "pending", "archive_too_large");
+ const actual = await fileHash(saved.job.sealedPath, options.signal);
+ if (actual.bytes !== saved.job.request.size || actual.sha256 !== saved.job.request.sha256) return receipt(saved, "pending", "archive_file_corrupt");
+ const job = saved;
+ const outcome = await options.driver.upload(job.job, () => persist(savedPath, job), options.signal);
+ if (outcome.status === "uploaded") { job.state = "uploaded"; await persist(savedPath, job); return receipt(job, "uploaded"); }
+ return receipt(job, outcome.status === "disabled" || outcome.code === "archive_payload_disabled" ? "disabled" : "pending", outcome.code ?? outcome.reason ?? outcome.status);
+}
+
+/** Originals and sealed jobs remain local on every outcome, including caps and account gates. */
+export async function uploadNativeBundle(options: NativeUploadOptions): Promise<NativeUploadReceipt> {
+ if (!options.sessionId || !options.owner || !options.bindingId || !options.engineVersion || !isHash(options.contractHash)
+ || !Number.isSafeInteger(options.turn) || options.turn < 0 || !parseNativeCaptureCapabilities(options.capabilities)) throw new Error("Invalid native archive binding or capabilities");
+ await fsp.mkdir(options.stateDirectory, {recursive: true, mode: 0o700});
+ const lockFile = path.join(options.stateDirectory, "upload.lock");
+ let lock: Awaited<ReturnType<typeof fsp.open>>;
+ try { lock = await fsp.open(lockFile, "wx", 0o600); }
+ catch (error) {
+ if (!hasCode(error, "EEXIST")) throw error;
+ const pid = Number(await fsp.readFile(lockFile, "utf8"));
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("Archive upload lock needs recovery; evidence retained");
+ try { process.kill(pid, 0); throw new Error("A native archive upload is already in progress"); }
+ catch (probe) { if (!hasCode(probe, "ESRCH")) throw probe; }
+ await fsp.unlink(lockFile); lock = await fsp.open(lockFile, "wx", 0o600);
+ }
+ try {
+ await lock.writeFile(String(process.pid)); await lock.sync();
+ const run = async (kind: NativeArchivePayload): Promise<NativePayloadReceipt> => {
+ try { return await payload(options, kind); }
+ catch (error) {
+ const code = options.signal?.aborted ? "aborted" : error instanceof NativeArchiveFailure ? error.code
+ : hasCode(error, "ENOENT") ? "archive_source_missing" : hasCode(error, "ENOSPC") ? "archive_storage_full"
+ : hasCode(error, "EACCES") || hasCode(error, "EPERM") ? "archive_source_unreadable" : "archive_preparation_failed";
+ return {status: "pending", payload: kind, retained: true, code};
+ }
+ };
+ const native = await run("claude_native"), checkpoint = await run("claude_checkpoint");
+ const states = [native.status, checkpoint.status];
+ const status = states.every(value => value === "disabled") ? "disabled"
+ : states.includes("pending") ? states.includes("uploaded") ? "partial" : "pending" : "uploaded";
+ const result: NativeUploadReceipt = {status, native, checkpoint};
+ const observation = {schema: 1, sessionId: options.sessionId, owner: options.owner, at: new Date().toISOString(), ...result};
+ await persist(path.join(options.stateDirectory, "last-upload.json"), observation);
+ const audit = await fsp.open(path.join(options.stateDirectory, "upload-events.jsonl"), "a", 0o600);
+ try { await audit.writeFile(JSON.stringify(observation) + "\n"); await audit.sync(); } finally { await audit.close(); }
+ return result;
+ } finally { await lock.close(); await fsp.unlink(lockFile); }
+}
diff --git a/apps/server/src/claude-code/zip.ts b/apps/server/src/claude-code/zip.ts
new file mode 100644
index 00000000..7206ed74
--- /dev/null
+++ b/apps/server/src/claude-code/zip.ts
@@ -0,0 +1,50 @@
+// Streaming ZIP (stored entries): image archives are already compressed. Never
+// buffer an environment image in RAM. Refuse ZIP32 overflow rather than produce
+// a corrupt bundle; callers retain the source artifacts for recovery.
+import fs from "node:fs";
+import fsp from "node:fs/promises";
+import path from "node:path";
+import { once } from "node:events";
+
+const table = Uint32Array.from({length: 256}, (_, n) => {
+ let crc = n; for (let k = 0; k < 8; k++) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1; return crc >>> 0;
+});
+export async function zipDirectory(directory: string, target: string) {
+ const temporary = `${target}.tmp`, out = fs.createWriteStream(temporary, {mode: 0o600});
+ let offset = 0; const central: Buffer[] = [];
+ let failure: Error | undefined;
+ out.on("error", error => { failure = error; });
+ const write = async (bytes: Buffer) => { if (failure) throw failure; offset += bytes.length; if (offset > 0xffffffff) throw new Error("Bundle exceeds ZIP32 limit; retain split environment archives"); if (!out.write(bytes)) await once(out, "drain"); };
+ const walk = async (dir: string): Promise<void> => {
+ const entries = await fsp.readdir(dir, {withFileTypes: true});
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
+ for (const entry of entries) {
+ const file = path.join(dir, entry.name);
+ if (entry.isDirectory()) { await walk(file); continue; }
+ if (!entry.isFile() && !entry.isSymbolicLink()) throw new Error("Unsupported bundle file");
+ const name = Buffer.from(path.relative(directory, file).split(path.sep).join("/"));
+ const stat = await fsp.lstat(file), symlink = entry.isSymbolicLink();
+ const link = symlink ? Buffer.from(await fsp.readlink(file)) : undefined;
+ const size = link ? link.length : stat.size, start = offset;
+ if (size > 0xffffffff || name.length > 65535 || central.length >= 65535) throw new Error("Bundle exceeds ZIP32 limit");
+ const header = Buffer.alloc(30); header.writeUInt32LE(0x04034b50); header.writeUInt16LE(20, 4); header.writeUInt16LE(0x808, 6); header.writeUInt16LE(name.length, 26);
+ await write(header); await write(name); let crc = 0xffffffff, actual = 0;
+ const consume = async (bytes: Buffer) => { for (const byte of bytes) crc = table[(crc ^ byte) & 255] ^ (crc >>> 8); actual += bytes.length; await write(bytes); };
+ if (link) await consume(link); else for await (const chunk of fs.createReadStream(file)) await consume(chunk);
+ if (actual !== size) throw new Error("Bundle file changed while exporting");
+ crc = (crc ^ 0xffffffff) >>> 0;
+ const descriptor = Buffer.alloc(16); descriptor.writeUInt32LE(0x08074b50); descriptor.writeUInt32LE(crc, 4); descriptor.writeUInt32LE(size, 8); descriptor.writeUInt32LE(size, 12); await write(descriptor);
+ const index = Buffer.alloc(46); index.writeUInt32LE(0x02014b50); index.writeUInt16LE(0x0314, 4); index.writeUInt16LE(20, 6); index.writeUInt16LE(0x808, 8); index.writeUInt32LE(crc, 16); index.writeUInt32LE(size, 20); index.writeUInt32LE(size, 24); index.writeUInt16LE(name.length, 28); index.writeUInt32LE((stat.mode << 16) >>> 0, 38); index.writeUInt32LE(start, 42);
+ central.push(Buffer.concat([index, name]));
+ }
+ };
+ try {
+ await walk(directory); const start = offset;
+ for (const entry of central) await write(entry);
+ const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50); end.writeUInt16LE(central.length, 8); end.writeUInt16LE(central.length, 10); end.writeUInt32LE(offset - start, 12); end.writeUInt32LE(start, 16); await write(end);
+ out.end(); await once(out, "close"); if (failure) throw failure;
+ const fd = fs.openSync(temporary, "r"); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+ await fsp.rename(temporary, target);
+ if (process.platform !== "win32") { const parent = fs.openSync(path.dirname(target), "r"); try { fs.fsyncSync(parent); } finally { fs.closeSync(parent); } }
+ } catch (error) { out.destroy(); await fsp.rm(temporary, {force: true}); throw error; }
+}
diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.ts
index 81541878..169d05f4 100644
--- a/apps/server/src/omnirush-gateway-broker.test.ts
+++ b/apps/server/src/omnirush-gateway-broker.test.ts
@@ -39,6 +39,28 @@ function gatewayRequest(body: Record<string, unknown>, headers: Record<string, s
}
describe("OmniRush gateway broker", () => {
+ test("Claude device mint keeps the desktop client header consistent with its bound client", async () => {
+ const sessionId = "00000000-0000-4000-8000-000000000001", contractSha256 = "a".repeat(64);
+ let minted = 0;
+ const broker = new OmniRushGatewayBroker({clientVersion: "3.7.5", credentials: {
+ gatewayUrl: "https://gateway.example/omnirush/v1", accessToken: "device-access-fixture", refreshToken: "device-refresh-fixture",
+ }, fetch: async (input, init) => {
+ const url = new URL(String(input));
+ if (url.pathname.endsWith("/device/me")) return Response.json({id: "owner"});
+ expect(url.pathname).toBe("/omnirush/device/claude-token");
+ expect(new Headers(init?.headers).get("authorization")).toBe("Bearer device-access-fixture");
+ expect(new Headers(init?.headers).get("x-omnirush-client")).toBe("desktop/3.7.5");
+ if (typeof init?.body !== "string") throw new Error("Expected mint JSON");
+ expect(JSON.parse(init.body).client).toBe("desktop/3.7.5");
+ minted++;
+ return Response.json({token: "orc_" + "a".repeat(43), base_url: "https://gateway.example/claude", expires_in: 900, refresh_after: 600,
+ binding: {binding_id: "00000000-0000-4000-8000-000000000002", session_id: sessionId, root_session_id: sessionId,
+ model: "claude-opus-5-5", upstream_model: "claude-opus-5-5", contract_hash: contractSha256}});
+ }});
+ const grant = await broker.claudeGrant({owner: "owner", sessionId, workspaceId: "project", model: "claude-opus-5-5", contractSha256});
+ expect(minted).toBe(1); expect(grant.client).toBe("desktop/3.7.5");
+ });
+
test("refreshes one expired credential and retries concurrent requests with the rotated token", async () => {
let refreshCalls = 0;
const fetcher = async (input: string | URL | Request, init?: RequestInit) => {
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index bc0fd020..2819ab8a 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -17,6 +17,8 @@ import { RejectedAttachments, isRejectedAttachmentError, type Attachment } from
import { gatewayUrlAllowed, RELEASE_GATEWAY_ERROR } from "./release-guard.js";
import { BOX_HEADER, MODEL_NOT_IN_MODE, notInModeMessage, projectMode } from "./model-modes/model-modes.mjs";
import { MODE_NOT_BOUND, MODEL_NOT_BOUND, SESSION_BIND_UNCONFIRMED, SESSION_BINDING_CONFLICT, SESSION_MODEL_USED, VERIFICATION_REQUIRED, sessionBinder, strictSessions, type StrictSessions } from "./model-modes/strict-sessions.mjs";
+import { ClaudeDeviceAccess, type ClaudeDeviceRequest } from "./claude-code/access.js";
+import type { ClaudeAuthorization } from "./claude-code/runtime.js";
/** A main chat's request on another model than the one it started on (one model per chat). */
const SESSION_MODEL_FIXED = "session_model_fixed";
@@ -1298,6 +1300,7 @@ export class OmniRushGatewayBroker {
/** Strict sessions: each chat binds its model and mode once per process (model-modes/strict-sessions.mjs). */
private readonly reasoningSummaryFor: (model: string) => boolean | Promise<boolean>;
private readonly clientHeader: string | null;
+ private readonly claudeFetcher: typeof externalFetch;
private refreshInFlight: Promise<boolean> | null = null;
/** Whether the last failed refresh left the session as it was (unreachable, 5xx, contended). */
private lastRefreshTransient = false;
@@ -1344,6 +1347,7 @@ export class OmniRushGatewayBroker {
this.invalidate = options.credentials?.invalidate;
this.refreshOwner = options.credentials?.refresh;
const fetcher = options.fetch ?? externalFetch;
+ this.claudeFetcher = fetcher;
this.clientHeader = guiClientHeaderValue(options.clientVersion);
const clientHeader = this.clientHeader;
// Every call the broker makes goes to omnirush.ai (model, upload, archive
@@ -1673,6 +1677,7 @@ export class OmniRushGatewayBroker {
}
resetCapabilities(): void {
+ this.claudeDevice = undefined;
this.capabilityCache = null;
this.capabilityProbe = null;
this.capabilityFailure = null;
@@ -1841,6 +1846,48 @@ export class OmniRushGatewayBroker {
}));
}
+ private claudeDevice?: ClaudeDeviceAccess;
+ private claudeAccessClient() {
+ this.claudeDevice ??= new ClaudeDeviceAccess(this.claudeDeviceRequest, (this.clientHeader ?? "desktop/unknown").replace(/^gui\//, "desktop/"));
+ return this.claudeDevice;
+ }
+ private readonly claudeDeviceRequest: ClaudeDeviceRequest = (route, init, owner) => this.withDeviceBearer(async state => {
+ const client = (this.clientHeader ?? "desktop/unknown").replace(/^gui\//, "desktop/");
+ if (owner) {
+ const identity = await this.fetcher(apiUrl(state.gatewayUrl, "device/me"), {headers: {Authorization: `Bearer ${state.accessToken}`}, signal: AbortSignal.timeout(8_000)});
+ if (!identity.ok) return identity;
+ const account: unknown = await identity.json();
+ if (!isRecord(account) || account.id !== owner) return new Response(null, {status: 403});
+ }
+ return this.claudeFetcher(apiUrl(state.gatewayUrl, route), {
+ method: init?.method ?? "GET", body: init?.body,
+ headers: {Authorization: `Bearer ${state.accessToken}`, Accept: "application/json", "Content-Type": "application/json", "X-OmniRush-Client": client},
+ signal: AbortSignal.timeout(8_000),
+ });
+ });
+ claudeAccess() { return this.claudeAccessClient().access(); }
+ /** Session-bound tokens stay in this host process, outside the renderer and Docker. */
+ async claudeGrant(context: ClaudeAuthorization) {
+ const client = this.claudeAccessClient(), grant = await client.authorize(context);
+ if (client !== this.claudeDevice) throw new Error("OmniRush account routing changed; retry with the current account");
+ return grant;
+ }
+ revokeClaudeGrant(context: ClaudeAuthorization) { return this.claudeAccessClient().revoke(context); }
+
+ nativeCaptureRequest(owner: string, route: string, init: {method: "GET" | "POST"; body?: string; signal?: AbortSignal; refresh?: false}): Promise<Response> {
+ if (route !== "collect/capabilities" && !ARCHIVE_API_PATH.test(route)) return Promise.resolve(new Response(null, {status: 404}));
+ return this.withDeviceBearer(async state => {
+ const identity = await this.fetcher(apiUrl(state.gatewayUrl, "device/me"), {headers: {Authorization: `Bearer ${state.accessToken}`}, signal: AbortSignal.timeout(8_000)});
+ if (!identity.ok) return identity;
+ const account: unknown = await identity.json();
+ if (!isRecord(account) || account.id !== owner) return new Response(null, {status: 403});
+ return this.fetcher(apiUrl(state.gatewayUrl, route), {
+ method: init.method, headers: {Authorization: `Bearer ${state.accessToken}`, "content-type": "application/json"},
+ body: init.body, signal: init.signal ?? AbortSignal.timeout(30_000),
+ });
+ }, {refresh: init.refresh !== false});
+ }
+
/**
* One voice segment for the backend's POST /omnirush/v1/audio/transcriptions,
* authenticated like uploadSession(): the device bearer and the same bounded 401
@@ -2274,6 +2321,7 @@ export class OmniRushGatewayBroker {
if (this.state !== asked) return Boolean(this.state);
if (!current) {
this.state = null;
+ this.resetCapabilities();
void this.invalidate?.().catch(() => undefined);
return false;
}
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index b09d586e..708786da 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1,4 +1,8 @@
import { managedDesktopPolicy } from "./managed-desktop-policy.js";
+import { uploadClaudeSession } from "./claude-code/transfer.js";
+import { ArchiveUploader } from "./session-archive/upload.js";
+import { SealStream } from "./session-archive/seal.js";
+import { tarMemberHeader } from "./session-archive/pack.js";
import { parseApprovalMode, resolveApprovalMode, type ApprovalMode } from "./approval-mode.js";
import { createTaskRecovery, requeueTaskRecoveryAfterEngineLoss, setTaskRecovery } from "./task-recovery.js";
import {
@@ -247,6 +251,8 @@ import { GOOD_SESSION_ID_PATTERN, readGoodSession } from "./omnirush-good-sessio
import { PROJECT_ARCHIVE_BASE_IDLE_MS, PROJECT_ARCHIVE_BASE_MAX_DEFER_MS, projectArchiveSettings } from "./project-archive.js";
import type { ArchiveApiRequestInit } from "./session-archive/upload.js";
import { runtimeStorageDir } from "./runtime-db.js";
+import { ClaudeRuntime } from "./claude-code/runtime.js";
+import { registerClaudeRoutes } from "./claude-code/routes.js";
import { prepareDesktopInstallLog } from "./install-log-host.js";
import pkg from "../package.json" with { type: "json" };
import constants from "../../../constants.json" with { type: "json" };
@@ -1533,6 +1539,22 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
bestPracticesReloads,
);
+ const claudeRuntime = new ClaudeRuntime({
+ directory: join(runtimeStorageDir(config), "claude-sessions"), surface: "gui",
+ access: () => gatewayBroker.claudeAccess(),
+ authorize: context => gatewayBroker.claudeGrant(context),
+ revoke: context => gatewayBroker.revokeClaudeGrant(context),
+ });
+ registerClaudeRoutes({routes, runtime: claudeRuntime,
+ workspace: ctx => resolveWorkspaceWithoutBootstrap(config, ctx.params.id),
+ owner: ctx => requireClientScope(ctx, "owner"),
+ writable: () => ensureWritable(config),
+ upload: id => uploadClaudeSession(claudeRuntime, id, (owner, route, init) => gatewayBroker.nativeCaptureRequest(owner, route, init), owner => {
+ const uploader = new ArchiveUploader({fetch: externalFetch, request: (route, init) => gatewayBroker.nativeCaptureRequest(owner, route, init)});
+ return {fetchKey: signal => uploader.fetchKey(signal), upload: (job, persist, signal) => uploader.upload(job, persist, signal), sealer: options => new SealStream(options), tarHeader: tarMemberHeader};
+ }),
+ });
+
const serverOptions: {
hostname: string;
port: number;
@@ -1919,6 +1941,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
return {
...server,
stop: async () => {
+ const claudeStopped = claudeRuntime.shutdown();
// First, and synchronously: a stop is also how a user sign-out reaches
// this server (the desktop clears the account, then restarts it), so
// archive part uploads in flight are aborted before anything else runs.
@@ -1926,6 +1949,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
// is still stored (an app quit, a restart), never after a sign-out.
// Before them, each chat in a box gets its last checkpoint (bounded; only when chats ran in a
// box this run, and the account answers it is still stored within a second).
+ await claudeStopped;
stopBoxDefaultWatch();
stopWebSearchWatch();
stopMcpPolicyWatch();
diff --git a/apps/server/src/session-archive/seal.ts b/apps/server/src/session-archive/seal.ts
index 5586dfea..dbab85f8 100644
--- a/apps/server/src/session-archive/seal.ts
+++ b/apps/server/src/session-archive/seal.ts
@@ -23,6 +23,7 @@ import { Transform, type TransformCallback } from "node:stream";
export const SEAL_MAGIC = Buffer.from("ORSEAL01", "ascii");
export const SEAL_ALG = "X25519-HKDF-SHA256-A256GCM";
export const SEAL_CONTENT = "tar+zstd";
+export type SealContent = typeof SEAL_CONTENT | "zip";
/** The only chunk size production writers use. */
export const SEAL_CHUNK = 1 << 20;
export const SEAL_MIN_CHUNK = 16;
@@ -136,6 +137,8 @@ function decryptFrame(key: Buffer, headerHash: Buffer, index: number, final: boo
}
export type SealOptions = {
+ /** Native Claude checkpoints preserve their exact ZIP bytes; project archives retain tar+zstd. */
+ content?: SealContent;
/** The recipient's raw 32-byte X25519 public key (GET /omnirush/archives/key). */
publicKey: Uint8Array;
/** Plaintext bytes per frame. Production MUST leave the default (1 MiB); the vectors use 16. */
@@ -172,6 +175,8 @@ class FrameSealer {
private sealed: SealResult | null = null;
constructor(options: SealOptions) {
+ const content = options.content ?? SEAL_CONTENT;
+ if (content !== SEAL_CONTENT && content !== "zip") throw new TypeError("invalid seal content");
const chunk = options.chunk ?? SEAL_CHUNK;
if (!Number.isInteger(chunk) || chunk < SEAL_MIN_CHUNK || chunk > SEAL_MAX_CHUNK) throw new RangeError("invalid seal chunk size");
const serverPublicRaw = raw32(options.publicKey, "X25519 public key");
@@ -189,7 +194,7 @@ class FrameSealer {
const header = Buffer.from(JSON.stringify({
alg: SEAL_ALG,
chunk,
- content: SEAL_CONTENT,
+ content,
epk: epk.toString("base64"),
kid: this.kid,
salt: salt.toString("base64"),
@@ -376,7 +381,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {
type OpenedHeader = { chunk: number; key: Buffer; headerHash: Buffer; kid: string };
-async function openHeader(reader: ByteReader, keyring: SealKeyring): Promise<OpenedHeader> {
+async function openHeader(reader: ByteReader, keyring: SealKeyring, expectedContent: SealContent): Promise<OpenedHeader> {
const magic = await reader.read(8);
if (!magic.equals(SEAL_MAGIC)) throw new SealError("bad_magic");
const rawLength = await reader.read(4);
@@ -401,7 +406,7 @@ async function openHeader(reader: ByteReader, keyring: SealKeyring): Promise<Ope
keys.length !== HEADER_KEYS.size
|| !keys.every((key) => HEADER_KEYS.has(key))
|| header.alg !== SEAL_ALG
- || header.content !== SEAL_CONTENT
+ || header.content !== expectedContent
|| typeof chunk !== "number"
|| !Number.isInteger(chunk)
|| chunk < SEAL_MIN_CHUNK
@@ -437,10 +442,10 @@ async function openHeader(reader: ByteReader, keyring: SealKeyring): Promise<Ope
* stream can yield a verified prefix first, and a caller must discard
* everything it received when a SealError is thrown.
*/
-export async function* openSealed(source: AsyncIterable<Uint8Array>, keyring: SealKeyring): AsyncGenerator<Buffer, { kid: string }> {
+export async function* openSealed(source: AsyncIterable<Uint8Array>, keyring: SealKeyring, options: {expectedContent?: SealContent} = {}): AsyncGenerator<Buffer, { kid: string }> {
const reader = new ByteReader(source);
try {
- const { chunk, key, headerHash, kid } = await openHeader(reader, keyring);
+ const { chunk, key, headerHash, kid } = await openHeader(reader, keyring, options.expectedContent ?? SEAL_CONTENT);
for (let index = 0; ; index += 1) {
const rawLength = await reader.read(4);
if (rawLength.length < 4) throw new SealError("truncated");
@@ -474,8 +479,8 @@ async function* once(bytes: Uint8Array): AsyncGenerator<Uint8Array> {
}
/** Opens a whole sealed buffer; throws SealError on any failure. */
-export async function openSealedBuffer(sealed: Uint8Array, keyring: SealKeyring): Promise<Buffer> {
+export async function openSealedBuffer(sealed: Uint8Array, keyring: SealKeyring, options: {expectedContent?: SealContent} = {}): Promise<Buffer> {
const pieces: Buffer[] = [];
- for await (const piece of openSealed(once(sealed), keyring)) pieces.push(piece);
+ for await (const piece of openSealed(once(sealed), keyring, options)) pieces.push(piece);
return Buffer.concat(pieces);
}
diff --git a/apps/server/src/session-archive/upload.ts b/apps/server/src/session-archive/upload.ts
index 4dd427ee..2f4324fa 100644
--- a/apps/server/src/session-archive/upload.ts
+++ b/apps/server/src/session-archive/upload.ts
@@ -8,7 +8,7 @@ import { open, type FileHandle } from "node:fs/promises";
import { z } from "zod";
import { parseArchivePolicy, type ArchivePolicy } from "./policy.js";
-import { SEAL_ALG, SEAL_CONTENT, sealKid } from "./seal.js";
+import { SEAL_ALG, sealKid, type SealContent } from "./seal.js";
import { gatewayUrlAllowed } from "../release-guard.js";
export type ArchiveFetch = (input: string, init?: RequestInit) => Promise<Response>;
@@ -112,7 +112,7 @@ export function resolveArchiveApiRoot(rawGatewayUrl: string | undefined): string
}
}
-export type ArchiveCreateRequest = {
+export type ArchiveCreateRequest<Content extends SealContent = "tar+zstd"> = {
archive_id: string;
session_id: string;
kind: "base" | "delta";
@@ -122,8 +122,18 @@ export type ArchiveCreateRequest = {
size: number;
sha256: string;
kid: string;
- content: typeof SEAL_CONTENT;
+ content: Content;
marker: string;
+ /** Native harness evidence uses the same sealed multipart archive protocol. */
+ payload?: "project" | "claude_native" | "claude_checkpoint";
+ harness?: "claude-code";
+ engine_version?: string;
+ binding_id?: string;
+ contract_hash?: string;
+ plain_sha256?: string;
+ plain_size?: number;
+ manifest_sha256?: string;
+ box_image?: string;
/** Bytes of the `__media__/` files in this archive (media-store.ts): the server counts them apart from the project's. */
media_bytes?: number;
};
@@ -139,7 +149,7 @@ export type ArchiveUploadState = {
/** What the uploader needs from a queued job; it mutates `upload` and `recreates` and persists through the callback. */
export type ArchiveUploadJob = {
- request: ArchiveCreateRequest;
+ request: ArchiveCreateRequest<SealContent>;
sealedPath: string;
upload: ArchiveUploadState | null;
recreates: number;
@@ -357,6 +367,7 @@ export class ArchiveUploader {
if (result.kind === "ok") return null;
if (result.status === 401) return { status: "blocked", reason: "unauthorized" };
if (result.status === 403) return { status: "blocked", reason: result.code ?? "forbidden" };
+ if (result.status === 409 && result.code === "archive_payload_disabled") return { status: "disabled", code: result.code };
if (result.status === 428) return { status: "disabled", code: result.code ?? "archive_consent_required" };
if (result.status === 503) return { status: "disabled", code: result.code ?? "archive_disabled" };
if (result.status === 413) return { status: "stop_session", code: result.code ?? "archive_too_large" };
@@ -486,7 +497,13 @@ export class ArchiveUploader {
private async complete(job: ArchiveUploadJob, upload: ArchiveUploadState, signal?: AbortSignal): Promise<UploadOutcome | "recreate" | "relist" | { reupload: string }> {
const parts = Array.from({ length: upload.part_count }, (_, index) => ({ part_number: index + 1, etag: upload.etags[String(index + 1)] ?? "" }));
const result = await this.call("POST", `archives/${job.request.archive_id}/complete`, { parts }, signal);
- if (result.kind === "ok") return { status: "uploaded" };
+ if (result.kind === "ok") {
+ if (job.request.payload === "claude_native" || job.request.payload === "claude_checkpoint") {
+ const receipt = z.object({archive_id: z.string(), status: z.literal("uploaded"), size: z.number().int().positive()}).safeParse(result.body);
+ if (!receipt.success || receipt.data.archive_id !== job.request.archive_id || receipt.data.size !== job.request.size) return { status: "retry_later", reason: "invalid completion receipt" };
+ }
+ return { status: "uploaded" };
+ }
const outcome = this.common(result);
if (outcome) return outcome;
if (result.kind === "error") {
diff --git a/docs/claude-native-pilot.md b/docs/claude-native-pilot.md
new file mode 100644
index 00000000..67461662
--- /dev/null
+++ b/docs/claude-native-pilot.md
@@ -0,0 +1,245 @@
+# Native Claude Code pilot
+
+The CLI and GUI use the same pinned Claude Agent SDK runtime. The SDK launches
+Claude Code inside a Docker container; OpenCode is not involved in this path.
+The initial project is copied into `/workspace`. The controller, shell tools,
+subagents, dependencies, home directory and native transcripts all live inside
+the container. Edits remain in that session's copy and are included in its ZIP.
+
+## Run
+
+Prerequisites: Docker Engine or Docker Desktop, an OmniRush device login, and an
+active selected-account Claude access. The backend must advertise
+`collect/capabilities.claude_code.enabled`, the matching SDK package pin and a nonempty
+model catalog containing the pilot model, and provide the session-token and
+capture routes described below. There is no personal subscription fallback.
+
+In the GUI, open a workspace's actions and choose **Claude Code pilot**. Confirm
+private capture, create a session and send a prompt. Select an existing session
+to continue it, including after restarting the app. **Stop**, **Recover evidence**,
+**Verify restore**, **Download private ZIP**, and **Upload private session** are
+available on the same page. A native save dialog streams desktop ZIP downloads
+to disk; browser mode downloads through the browser.
+
+The matching CLI release exposes:
+
+```sh
+omnirush claude run --workspace ./project --capture-consent --prompt 'Implement the change and run tests'
+omnirush claude continue --session UUID --prompt 'Add coverage for edge cases'
+omnirush claude verify --session UUID --command 'node --test'
+omnirush claude export --session UUID --output session.zip
+omnirush claude upload --session UUID
+omnirush claude recover --session UUID
+```
+
+Omit `--prompt` for interactive CLI input. `list` and `inspect --session UUID`
+show local sessions. Ctrl-C stops an active CLI turn and retains partial evidence.
+The older `claude-pilot` command is a diagnostic harness, not this product path.
+
+## Sandbox startup barrier
+
+The native Claude path is box-only independently of `local_box.required`.
+`ClaudeRuntime.create()` awaits image preparation, container creation and the
+initial checkpoint before publishing a session. The GUI cannot send its first
+prompt until that session exists; the CLI also awaits creation before starting
+the turn. Every turn awaits container startup before invoking the SDK, and a
+concurrent send is refused while that operation is active.
+
+These routes do not use the existing-harness `BoxService.waitForBox` path.
+Unified-composer integration must dispatch Opus through this native runtime and
+retain its startup barrier, including under `offer`; it must never fall back to
+host execution while a sandbox is preparing. A delayed-startup server check is
+separate from GUI proof of the setup banner and pending-send presentation.
+
+## Evidence and reproducibility
+
+- Exact native root and child JSONL, metadata, every conversation branch, and
+ previous generations after rewrites are retained. Request-cache blobs remain
+ byte-exact but are not counted as new tool executions.
+- Exposed thinking summaries and opaque signatures remain in the private
+ native data. Hidden model reasoning is not exposed or reconstructed.
+- SDK events are durable before they are acknowledged. Hooks record tool and
+ subagent lifecycles, compaction, stops and failures. Read-time hashes allow
+ verification when Claude returns a cached “file unchanged” response.
+- The container stops before each checkpoint. Exact before/after image IDs are
+ recorded for every turn. Shared Docker layers are stored once in a multi-image
+ archive; the archive SHA-256 is checked before restoration.
+- Native completeness requires a stopped successful producer, valid complete
+ JSONL, matching calls/results, and all expected child transcripts and stops.
+ Interrupted, truncated or missing evidence remains incomplete.
+- A completed container removed by local cleanup is reconstructed from its saved
+ image on resume. A missing interrupted container cannot be reconstructed from
+ a later state; its incomplete evidence stays available for review.
+
+The ZIP includes `session.json`, `native-manifest.json`, `claude/`, `events/`,
+`diagnostics/`, `images/`, and `verify.py`. Saved images contain the project,
+git state, executable modes, installed dependencies and files outside
+`/workspace`. Export reads saved evidence without contacting Docker or requiring
+an account connection; it does not copy a possibly running container's mutable
+workspace. A proven-dead operation owner can be recovered for export, while
+live or unknown owners keep the session locked. Native JSONL is authoritative;
+SDK events are a transport mirror.
+Do not add their token/tool counts together.
+
+**Capture complete**, **environment restored**, **upload received**, and
+**recorded-tool replay verified** are separate claims. The GUI restore action
+runs a chosen command against the final saved image with networking disabled.
+It does not label the session reproducible just because Docker can start it.
+
+On an isolated conversion worker with the reviewed `omniconv` verifier installed:
+
+```sh
+python3 verify.py session.zip --out new-private-report-directory
+# Optional additional after-state comparison outside the project:
+python3 verify.py session.zip --out another-report --check-path /absolute/path
+```
+
+The included adapter verifies native evidence and image hashes, derives calls
+from native assistant/user records and execution hooks, restores each turn's
+before image, runs the existing `omniconv.verify` replay engine without network
+access, and compares project bytes, modes and symlinks to the after image. It
+includes all child calls and checks cached reads against their pre-tool hashes.
+Reports bind the exact ZIP SHA-256 and size, session, manifest, derived calls,
+verifier and adapter fingerprints. Strict replay is separate from soft replay;
+missing actual shell invocation/exit witnesses cannot earn a strict verdict. Unsupported calls,
+missing witnesses, side-effect skips and incomplete evidence are not silently
+accepted. Model inference is not rerun. These private reports do not authorize
+distribution; masking, quality admission and delivery review remain separate.
+
+The pinned SDK can strip an Agent request's `model` before emitting hooks when
+the session forces one model. The adapter accepts only this independently
+corroborated transform, preserves both requested and effective inputs, and
+marks it soft. Other unexplained input differences still fail. Reports identify
+the external adapter and the adapter embedded in the immutable ZIP separately.
+Filesystem qualification applies only to the listed paths. A complete saved
+home directory can restore correctly while recorded-tool replay differs in
+Claude's own journals, which tool execution does not regenerate; those
+differences remain visible in an extended-scope report.
+
+This is a native-format ingress adapter. The existing Astra/OpenCode
+`export_to_raw.py` and production autofeed do not automatically understand this
+ZIP; route it through `verify.py` on a separate native pilot lane. Keep the
+original JSONL instead of relabelling it as OpenCode data.
+
+The converter's `native_archive.read` accepts the decrypted native archive tree
+or checkpoint ZIP. Supply `session_id`, `binding_id`, `contract_hash`,
+`manifest_sha256` and `engine_version` from the authenticated archive row. It
+verifies every member and original transcript generation, then produces an
+explicitly derived view with record provenance. Conflicting generations,
+unknown ancestry or missing ingress require review. Successful parsing does
+not establish model purity or replay.
+
+The backend worker entry point `native_archive_qc.build_native_timeline`
+connects that verified input to the existing QC view. It requires the trusted
+identity fields and refuses incomplete or ambiguous input. Leading compaction
+context is preserved without adding a human turn. Deployment must refresh the
+vendored converter from the integrated native changes and shared compaction
+PR; local source overlays used during validation are not an upstream release
+pin. Archive decryption, worker scheduling and production admission remain
+backend integration steps.
+
+## Backend and boundaries
+
+`POST /device/claude-token` creates or refreshes the canonical immutable
+session binding. Its request names session, project hash, exact catalog model,
+capture-contract SHA and actual client version. The broker validates the echoed
+session, root, model, contract and exact upstream model, including the initial
+grant. A grant mapping Opus to another model is refused before inference. Short-lived `orc_`
+tokens stay in host memory, coalesced across parallel requests and refreshed
+before expiry. The sandbox receives only a disposable local broker credential;
+completed turns revoke their live backend tokens. The retired pilot raw-key
+endpoint is never used. Every inference remains subject to backend access and
+allowance checks. Backend budget snapshots are shown only when supplied;
+missing or null balances remain explicitly unknown. The refresh interval must
+be at least one second and no greater than the token lifetime. Mint request
+latency counts against that lifetime; cached grants refresh before expiry.
+Neutral quota scope, bucket, reset and token-limit headers reach the SDK;
+unrelated provider headers remain private.
+
+The host broker forwards to the mint's `base_url` with the current `orc_` token
+as `x-api-key`, plus the bound session, actual client version and box headers.
+It preserves Claude Code's own User-Agent, `x-app` and beta headers. This path
+refreshes credentials at the host broker for every request; the direct-to-relay
+`apiKeyHelper` recipe is not needed for this brokered SDK path. Neither a Packy
+key nor the former supplied test key is accepted by the device-grant consumer.
+Server-side account key routing (#514) and allowance pools (#513) need no
+provider credential in either client. Claude remains unavailable while the
+backend disables it or returns an empty catalog.
+
+The SDK pilot requires `claude_code.sdk = {package, version, integrity}` to
+match the SDK package in its frozen pnpm lock. Missing or mismatched metadata
+disables admission. The lock also verifies the Linux platform packages during
+installation. The separate direct-install `version`/`npm_integrity` fields
+describe the Claude Code npm package and cannot attest this SDK bundle.
+Backend deployment and configuration of the additive SDK capability remain
+enablement gates; no live-install test is claimed while Claude is disabled.
+
+The root, helpers, subagents and compaction use the session's model. Managed
+settings and the broker reject model overrides. Provider-reported identities
+are retained separately from requested identities. Response bytes are held until
+the provider identifies the pinned model; missing identity stops the SDK before
+it receives a tool call and blocks continuation. A mismatch invalidates isolation.
+The replay admission check also rejects an upstream binding to another model.
+This proves the managed
+inference path only: the initial project is user-supplied and network-enabled
+development tools could reach other services. The capture contract records
+those limits, not a claim that every byte was created by one model.
+
+ No host home directory, credentials, project mount or Docker socket
+is mounted. The container runs as a non-root user with dropped capabilities,
+resource limits and no-new-privileges. Docker isolation is intended for a
+farmer's own development machine or an isolated worker, not a hostile shared
+production host.
+
+Private upload reuses the project archive protocol: client-side ORSEAL01 sealing,
+then direct presigned multipart uploads. Device credentials are used only for
+archive API calls, never sent to object storage. Two independent payloads share
+the session binding: `claude_native` (original traces, histories, hooks, contract
+and QC in tar+zstd) and `claude_checkpoint` (the exact replay ZIP). Both contain
+`__omnirush__/manifest.json`, binding every member's path, size and SHA-256.
+Receipts retain plaintext and sealed hashes. Upload retries reuse durable sealed
+jobs and archive IDs; local originals remain available on every failure.
+
+The backend advertises independent payload switches/caps. Checkpoints default
+off until storage is approved; native traces can still upload and count toward
+capture matching. The UI explicitly reports native-only, pending or complete
+receipt status. Receipt means received, never replay-verified. Legacy captures
+without a backend binding remain locally exportable. The old pilot chunk routes
+are reference code only and are not the production integration.
+
+Pilot limits: Docker is required; ZIP32 bundles are under 4 GiB; native
+transcripts are capped at 256 MiB per file and 1 GiB per scan. Full snapshots can
+contain private project configuration and secrets supplied in the project.
+Upload and download are explicit, and raw bundles must stay private. There is
+no model-provider fallback. Existing provider selection and retry policy stay
+owned by the internal proxy.
+
+## Verification and rollout
+
+```sh
+pnpm evals:e2e claude-native
+pnpm evals:pr specs/claude-native-capture.test.ts
+pnpm --filter omnirush-server typecheck
+pnpm --filter @omnirush/app typecheck
+pnpm --filter @omnirush/types build
+pnpm --filter @omnirush/app build
+node --test apps/desktop/electron/binary-transfer.test.mjs
+node scripts/sync-claude-capture.mjs /path/to/omnirush-cli --check
+```
+
+The journey supports browser and packaged Electron modes. It uses the real
+product server, Docker, the pinned SDK and five
+real SDK subagents; its account and inference services are deterministic test
+fixtures. It covers three resumed turns, page reload, host isolation, native
+thinking/children/hooks, cached-read witnesses, restore, browser export,
+desktop streaming transfer, upload recovery, access rejection and long-chat
+layout. Packaged mode uses the embedded Node server, Electron preload and a native save
+dialog. A development-variant executable test is separate from validating a
+signed release installer. The current verification report states which mode
+actually ran.
+
+Ship the backend device/capture endpoints first, then CLI and GUI together,
+with selected-account gating. Before widening access, validate the hosted
+backend and real private object storage, package/sign the desktop releases,
+and connect the native pilot queue to the conversion worker. Repository tests
+and a Launchpad inference smoke do not establish those deployment checks.
diff --git a/evals/packages/labs/src/capture-efficiency.ts b/evals/packages/labs/src/capture-efficiency.ts
index 9b536b7e..b7a0988a 100644
--- a/evals/packages/labs/src/capture-efficiency.ts
+++ b/evals/packages/labs/src/capture-efficiency.ts
@@ -3,13 +3,15 @@ import { createReadStream } from "node:fs";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { Readable } from "node:stream";
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, rm, writeFile, readFile, appendFile } from "node:fs/promises";
+import { createHash } from "node:crypto";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { zstdDecompressSync } from "node:zlib";
import { startCaptureService, type CaptureService } from "../../../../apps/server/src/capture-client.js";
import type { TraceCapabilities } from "../../../../apps/server/src/session-uploader.js";
+import { NativeCapture } from "../../../../apps/server/src/claude-code/native-capture.js";
const CONTROL_TOKEN = "capture-lab-control";
const UPLOAD_TOKEN = "capture-lab-upload";
@@ -191,6 +193,8 @@ async function startCaptureEfficiencyLabRuntime(): Promise<CaptureEfficiencyLab>
let collectorUrl = "";
let stopped = false;
let services: CaptureService[] = [];
+ const signedIn: Record<Actor, string | null> = { "actor-a": "actor-a", "actor-b": "actor-b" };
+ const nativeContexts = new Map<string, { actor: Actor; configDir: string; source: string; expected: string }>();
const server = createServer((request, response) => {
void (async () => {
@@ -246,6 +250,65 @@ async function startCaptureEfficiencyLabRuntime(): Promise<CaptureEfficiencyLab>
const body = await readJson(request);
const requestedSessionId = stringValue(body, "sessionId");
+ if (path.startsWith("/control/native/")) {
+ if (!/^[a-f0-9-]{36}$/.test(requestedSessionId)) throw new Error("invalid native session id");
+ const actor = actorValue(body), index = ACTORS.indexOf(actor);
+ if (path === "/control/native/seed") {
+ const configDir = join(tempRoot, "native-sources", actor, requestedSessionId);
+ const project = join(configDir, "projects", "-fixture-workspace");
+ const source = join(project, `${requestedSessionId}.jsonl`);
+ await mkdir(project, { recursive: true });
+ const records = [
+ { type: "user", uuid: "prompt", parentUuid: null, message: { content: `task for ${actor}` } },
+ { type: "assistant", uuid: "tools", parentUuid: "prompt", futureNativeField: actor, message: { content: [{ type: "thinking", thinking: "Visible summary", signature: "opaque-fixture" }, { type: "tool_use", id: "side-call", name: "Read" }, { type: "tool_use", id: "main-call", name: "Read" }] } },
+ { type: "user", uuid: "side-result", parentUuid: "tools", message: { content: [{ type: "tool_result", tool_use_id: "side-call", content: "side branch" }] } },
+ { type: "user", uuid: "main-result", parentUuid: "tools", message: { content: [{ type: "tool_result", tool_use_id: "main-call", content: "main branch" }] } },
+ ];
+ const expected = records.map((record) => JSON.stringify(record) + "\n").join("");
+ await writeFile(source, expected.slice(0, -3));
+ await writeFile(join(configDir, "credentials.json"), "DO_NOT_EXPORT_AUTH");
+ await writeFile(join(project, "unrelated.jsonl"), "DO_NOT_EXPORT_OTHER_SESSION");
+ const subagents = join(project, requestedSessionId, "subagents"); await mkdir(subagents, { recursive: true });
+ for (let child = 0; child < 5; child++) {
+ await writeFile(join(subagents, `agent-child${child}.jsonl`), JSON.stringify({ type: "user", uuid: `child${child}`, parentUuid: null, message: { content: `child ${child}` } }) + "\n");
+ await writeFile(join(subagents, `agent-child${child}.meta.json`), '{"agentType":"fixture"}');
+ }
+ nativeContexts.set(requestedSessionId, { actor, configDir, source, expected });
+ sendJson(response, 202, { rootSha256: createHash("sha256").update(expected).digest("hex") }); return;
+ }
+ const context = nativeContexts.get(requestedSessionId);
+ if (!context || context.actor !== actor) { sendJson(response, 403, { error: "native owner mismatch" }); return; }
+ const captureContext = { sessionId: requestedSessionId, configDir: context.configDir, producerVersion: "native-lab", transport: "sdk" as const };
+ if (path === "/control/native/account") {
+ signedIn[actor] = isRecord(body) && body.signedIn === null ? null : stringValue(body, "signedIn");
+ sendJson(response, 202, { ok: true }); return;
+ }
+ if (path === "/control/native/repair") {
+ await appendFile(context.source, context.expected.slice(-3)); sendJson(response, 202, { ok: true }); return;
+ }
+ if (path === "/control/native/restart") {
+ await services[index].stop({ archiveFinals: false }); services[index] = makeService(actor);
+ sendJson(response, 202, { ok: true }); return;
+ }
+ if (path === "/control/native/stream") {
+ const text = stringValue(body, "text"), offset = numberValue(body, "offset");
+ if (offset === null) throw new Error("stream offset required");
+ const manifest = await services[index].captureClaude(captureContext, { type: "stream", channel: "sdk", offset, bytes: Buffer.from(text) });
+ sendJson(response, 202, manifest); return;
+ }
+ if (path === "/control/native/finish") {
+ const manifest = await services[index].captureClaude(captureContext, { type: "finish", processStopped: true, successfulResult: true, expectedAgents: ["child0", "child1", "child2", "child3", "child4"] });
+ sendJson(response, 202, manifest); return;
+ }
+ if (path === "/control/native/export") {
+ const capture = new NativeCapture({ ...captureContext, directory: join(stateRoot, actor, "claude-native", requestedSessionId), owner: actor, surface: "gui" });
+ const destination = join(tempRoot, "exports", requestedSessionId);
+ const manifest = capture.exportTo(destination);
+ const files = await Promise.all(manifest.files.map(async (file) => ({ path: file.path, text: await readFile(join(destination, file.path), "utf8") })));
+ sendJson(response, 202, { manifest, files }); return;
+ }
+ throw new Error("unknown native control");
+ }
if (path === "/control/start") {
const actor = actorValue(body);
const workspace = stringValue(body, "workspace");
@@ -320,13 +383,13 @@ async function startCaptureEfficiencyLabRuntime(): Promise<CaptureEfficiencyLab>
} finally { stream.destroy(); }
};
- try {
- services = ACTORS.map((actor) => startCaptureService({
+ const makeService = (actor: Actor) => startCaptureService({
stateDir: join(stateRoot, actor),
appVersion: "capture-efficiency-lab",
engineVersion: "capture-efficiency-lab",
log: () => undefined,
worker: true,
+ accountId: async () => signedIn[actor],
sessionUploader: {
uploadFile,
capabilities: capability(actor, capabilityCalls),
@@ -335,7 +398,9 @@ async function startCaptureEfficiencyLabRuntime(): Promise<CaptureEfficiencyLab>
enabled: false,
excludedDirs: [],
},
- }));
+ });
+ try {
+ services = ACTORS.map(makeService);
} catch (error) {
await close(server);
await rm(tempRoot, { recursive: true, force: true });
diff --git a/evals/packages/labs/src/claude-runtime-server.ts b/evals/packages/labs/src/claude-runtime-server.ts
new file mode 100644
index 00000000..c125365b
--- /dev/null
+++ b/evals/packages/labs/src/claude-runtime-server.ts
@@ -0,0 +1,299 @@
+// Bun-owned fixture: real product HTTP server + real SDK/container, only
+// inference and account services are synthetic. No personal credentials.
+import fs from "node:fs";
+import path from "node:path";
+import { createHash, randomUUID } from "node:crypto";
+import { zstdDecompressSync } from "node:zlib";
+import { execFileSync } from "node:child_process";
+import { FakeArchiveServer } from "../../../../apps/server/src/session-archive/fake-archive-server.js";
+import { readTar, testKeys } from "../../../../apps/server/src/session-archive/test-helpers.js";
+import { openSealedBuffer } from "../../../../apps/server/src/session-archive/seal.js";
+import type { ServerConfig } from "../../../../apps/server/src/types.js";
+declare const Bun: {serve(options: {hostname: string; port: number; fetch(req: Request): Response | Promise<Response>}): {port: number; stop(force?: boolean): void}};
+const root = process.env.CLAUDE_LAB_DIR;
+if (!root) throw new Error("CLAUDE_LAB_DIR required");
+fs.mkdirSync(root, {recursive: true});
+const project = path.join(root, "project"); fs.mkdirSync(project, {recursive: true});
+fs.writeFileSync(path.join(project, "seed.txt"), "seed stays on host\n");
+process.env.OMNIRUSH_RUNTIME_DB = path.join(root, "runtime.sqlite");
+process.env.OMNIRUSH_TOKEN_STORE = path.join(root, "tokens.json");
+const deviceToken = process.env.CLAUDE_LAB_DEVICE_TOKEN ?? "device-fixture";
+let access = true, owner = process.env.CLAUDE_LAB_OWNER ?? "fixture-owner", calls = 0;
+let responseModel: string | null | undefined;
+let mintStatus = 200;
+let expiresIn = 900, refreshAfter = 600;
+let budgetMode: "known" | "unlimited" | "unknown" | "null" | "wrong-model" | "wrong-session" = "known";
+let bindingFault: "session" | "model" | "upstream" | "contract" | null = null;
+const grants = new Map<string, {session: string; model: string; contract: string; client: string}>();
+const bindingIds = new Map<string, string>();
+const mintRequests: Array<Record<string, unknown>> = [];
+let revokedGrants = 0;
+let rejectInferenceOnce = false, tokenRejections = 0;
+const inferenceDenials: Array<Record<string, unknown>> = [];
+const requests: Array<Record<string, unknown>> = [];
+let checkpointEnabled = false;
+const archives = new Map(["claude_native", "claude_checkpoint"].map(payload => {
+ const server = new FakeArchiveServer(); server.token = deviceToken; server.partSize = 8 * 1024 * 1024; server.policy = {project_folders: true};
+ return [payload, server];
+}));
+const archiveOwners = new Map<string, FakeArchiveServer>();
+const archiveWitnesses = new Map<string, Record<string, unknown>>();
+let presignedAuthLeaks = 0;
+const captureCapabilities = () => ({schema: 1, native: {enabled: access, max_bytes: 67_108_864}, checkpoint: {enabled: access && checkpointEnabled, max_bytes: 536_870_912, retention_days: null}});
+let uploadRetryInjected = false, uploadLossInjected = false, uploadedBytes = 0, uploadsComplete = 0;
+const uploadRoot = path.join(root, "received"); fs.mkdirSync(uploadRoot, {recursive: true});
+const gateway = Bun.serve({hostname: "127.0.0.1", port: 0, async fetch(req) {
+ const url = new URL(req.url);
+ if (url.pathname === "/control") {
+ const body = await req.json();
+ if (typeof body.access === "boolean") access = body.access;
+ if (body.rejectInferenceOnce === true) rejectInferenceOnce = true;
+ if (typeof body.checkpointEnabled === "boolean") checkpointEnabled = body.checkpointEnabled;
+ if (typeof body.owner === "string") owner = body.owner;
+ if (body.responseModel === null || typeof body.responseModel === "string") responseModel = body.responseModel;
+ if (body.resetResponseModel === true) responseModel = undefined;
+ if (typeof body.mintStatus === "number") mintStatus = body.mintStatus;
+ if (typeof body.expiresIn === "number") expiresIn = body.expiresIn;
+ if (typeof body.refreshAfter === "number") refreshAfter = body.refreshAfter;
+ if (["known", "unlimited", "unknown", "null", "wrong-model", "wrong-session"].includes(body.budgetMode)) budgetMode = body.budgetMode;
+ if (body.bindingFault === null || ["session", "model", "upstream", "contract"].includes(body.bindingFault)) bindingFault = body.bindingFault;
+ return Response.json({ok: true});
+ }
+ if (url.pathname === "/witness") return Response.json({calls, requests, inferenceDenials, mintRequests, revokedGrants, tokenRejections, hostFiles: fs.readdirSync(project), uploadRetryInjected, uploadLossInjected, uploadedBytes, uploadsComplete, presignedAuthLeaks, archives: [...archiveWitnesses.values()]});
+ if (url.pathname === "/device/me") return Response.json({id: owner, status: "active", approval_state: "approved"});
+ if (url.pathname === "/collect/capabilities") return Response.json({claude_code: {enabled: access, version: "2.1.306",
+ sdk: {package: "@anthropic-ai/claude-agent-sdk", version: "0.3.306", integrity: "sha512-kmxcd+4WNhqhqnzODRPM5aOKb1EH2EdlRsf7ZeMx8uQsC1tHAHgHftQGFXGT8yMaYaYlDP9BGYJy1/aYv7IhkQ=="},
+ models: access ? ["claude-opus-5-5"] : [], capture: captureCapabilities()}});
+ if (url.pathname === "/device/claude-token") {
+ const body = await req.json(); mintRequests.push(body);
+ if (req.headers.get("x-omnirush-client") !== body.client) return Response.json({detail: "client_version_required"}, {status: 403});
+ if (!access) return Response.json({detail: "claude_not_available"}, {status: 403});
+ if (mintStatus !== 200) return Response.json({detail: "model_allowance_exhausted"}, {status: mintStatus});
+ const token = `orc_${createHash("sha256").update(`${owner}:${body.session_id}`).digest("base64url")}`;
+ let bindingId = bindingIds.get(body.session_id);
+ if (!bindingId) { bindingId = randomUUID(); bindingIds.set(body.session_id, bindingId); }
+ grants.set(token, {session: body.session_id, model: body.model, contract: body.contract_hash, client: body.client});
+ const asOf = new Date().toISOString(), resetsAt = new Date(Date.now() + 60 * 60_000).toISOString(), unlimited = budgetMode === "unlimited";
+ const budget = budgetMode === "unknown" ? undefined : budgetMode === "null" ? null : {as_of: asOf,
+ allowance: {scope: "day", limit: 20_000, remaining: 18_000, resets_at: resetsAt},
+ model: {key: budgetMode === "wrong-model" ? "claude-haiku-4-5-20251001" : body.model, limit: unlimited ? null : 8_000, remaining: unlimited ? null : 7_000, resets_at: unlimited ? null : resetsAt},
+ session: {root_session_id: budgetMode === "wrong-session" ? randomUUID() : body.session_id, limit: unlimited ? null : 5_000, used: 1_000, remaining: unlimited ? null : 4_000}};
+ return Response.json({token, budget, expires_in: expiresIn, refresh_after: refreshAfter, base_url: `http://127.0.0.1:${gateway.port}/inference`, binding: {
+ binding_id: bindingId, session_id: bindingFault === "session" ? randomUUID() : body.session_id,
+ root_session_id: body.session_id, model: bindingFault === "model" ? "claude-haiku-4-5-20251001" : body.model,
+ upstream_model: bindingFault === "upstream" ? "claude-haiku-4-5-20251001" : body.model, contract_hash: bindingFault === "contract" ? "0".repeat(64) : body.contract_hash,
+ created_at: new Date().toISOString(),
+ }});
+ }
+ if (url.pathname === "/device/claude-token/revoke") {
+ const body = await req.json();
+ for (const [token, grant] of grants) if (grant.session === body.session_id) { grants.delete(token); revokedGrants++; }
+ return new Response(null, {status: 204});
+ }
+ if (url.pathname === "/v1/models") return Response.json({data: []});
+ if (url.pathname === "/archives/key") return Response.json({kid: testKeys.kid, public_key: testKeys.publicB64, alg: "X25519-HKDF-SHA256-A256GCM", policy: {all_folders: false, touched_files: false, project_folders: true}, limits: {max_upload_bytes: null, max_session_bytes: null, claude: captureCapabilities()}});
+ if (url.pathname.startsWith("/s3/")) {
+ if (req.headers.has("authorization") || req.headers.has("x-api-key")) presignedAuthLeaks++;
+ const archiveId = url.pathname.split("/").at(-1)!.replace(/\.orseal$/, "");
+ const archive = archiveOwners.get(archiveId); if (!archive) return new Response(null, {status: 404});
+ if (!uploadRetryInjected) { uploadRetryInjected = true; return new Response(null, {status: 503}); }
+ return archive.respond(`https://bucket.s3.test/${url.pathname.slice(4)}${url.search}`, {method: req.method, body: await req.arrayBuffer()});
+ }
+ if (url.pathname === "/archives" || url.pathname.startsWith("/archives/")) {
+ if (!access) return Response.json({detail: "account_paused"}, {status: 403});
+ const body = await req.json(), id = url.pathname === "/archives" ? body.archive_id : url.pathname.split("/")[2];
+ let server = archiveOwners.get(id);
+ if (url.pathname === "/archives") {
+ if (!archives.has(body.payload) || body.harness !== "claude-code" || body.marker !== "project" || !body.binding_id || !/^[a-f0-9]{64}$/.test(body.contract_hash)) return Response.json({detail: "invalid_native_binding"}, {status: 422});
+ if (body.payload === "claude_checkpoint" && !checkpointEnabled) return Response.json({detail: "archive_payload_disabled"}, {status: 409});
+ server = archives.get(body.payload)!; archiveOwners.set(id, server);
+ }
+ if (!server) return Response.json({detail: "archive_not_found"}, {status: 404});
+ if (url.pathname.endsWith("/complete") && !uploadLossInjected) {
+ uploadLossInjected = true;
+ server.archives.get(id)?.parts?.delete(1);
+ }
+ const response = await server.respond(`https://api.omnirush.test/omnirush${url.pathname}`, {method: req.method, headers: req.headers, body: JSON.stringify(body)});
+ const result = await response.json();
+ if (Array.isArray(result.parts)) result.parts = result.parts.map((part: {url: string}) => ({...part, url: part.url.replace("https://bucket.s3.test/", `http://127.0.0.1:${gateway.port}/s3/`)}));
+ if (response.ok && url.pathname.endsWith("/complete") && !archiveWitnesses.has(id)) {
+ const archive = server.archives.get(id)!;
+ if (!archive.object || archive.status !== "uploaded") throw new Error("Archive completion omitted its object");
+ const hash = (value: Uint8Array) => createHash("sha256").update(value).digest("hex");
+ if (hash(archive.object) !== archive.request.sha256) throw new Error("Sealed upload hash mismatch");
+ const checkpoint = archive.request.payload === "claude_checkpoint";
+ const plain = await openSealedBuffer(archive.object, testKeys.keyring, {expectedContent: checkpoint ? "zip" : "tar+zstd"});
+ if (plain.length !== archive.request.plain_size || hash(plain) !== archive.request.plain_sha256) throw new Error("Unsealed upload hash mismatch");
+ let manifest: Record<string, unknown> | undefined;
+ if (checkpoint) {
+ const file = path.join(uploadRoot, `${id}.zip`);
+ fs.writeFileSync(file, plain, {mode: 0o600}); uploadedBytes = plain.length;
+ manifest = JSON.parse(execFileSync(process.platform === "win32" ? "python" : "python3", ["-c", `import hashlib,json,sys,zipfile
+with zipfile.ZipFile(sys.argv[1]) as archive:
+ raw=archive.read('__omnirush__/manifest.json')
+ assert hashlib.sha256(raw).hexdigest()==sys.argv[2]
+ manifest=json.loads(raw)
+ assert set(archive.namelist())=={'__omnirush__/manifest.json'}|{entry['path'] for entry in manifest['files']}
+ for entry in manifest['files']:
+ digest=hashlib.sha256(); size=0
+ with archive.open(entry['path']) as source:
+ while chunk:=source.read(1048576): digest.update(chunk); size+=len(chunk)
+ assert size==entry['size'] and digest.hexdigest()==entry['sha256']
+ print(json.dumps(manifest))`, file, String(archive.request.manifest_sha256)], {encoding: "utf8", maxBuffer: 8 * 1024 * 1024}));
+ } else {
+ const members = readTar(zstdDecompressSync(plain)), first = members[0];
+ if (first?.name !== "__omnirush__/manifest.json" || hash(first.content) !== archive.request.manifest_sha256) throw new Error("Authoritative native manifest mismatch");
+ manifest = JSON.parse(first.content.toString("utf8"));
+ const expected = (manifest!.files as Array<{path: string; size: number; sha256: string}>);
+ for (const member of members.slice(1)) {
+ const item = expected.find(entry => entry.path === member.name);
+ if (!item || item.size !== member.size || item.sha256 !== hash(member.content)) throw new Error("Native member mismatch");
+ }
+ if (expected.length !== members.length - 1) throw new Error("Native manifest includes missing members");
+ }
+ archiveWitnesses.set(id, {request: archive.request, manifest, sealedSha256: hash(archive.object), plainSha256: hash(plain), plainBytes: plain.length});
+ uploadsComplete++;
+ archive.parts?.clear(); archive.object = null;
+ }
+ return Response.json(result, {status: response.status});
+ }
+ if (!url.pathname.startsWith("/inference/v1/messages")) return Response.json({}, {status: 404});
+ const bearer = req.headers.get("x-api-key") ?? req.headers.get("authorization")?.replace(/^Bearer /i, "");
+ const grant = bearer ? grants.get(bearer) : undefined;
+ if (!access || !grant) return Response.json({error: {type: "authentication_error", message: "Grant refused"}}, {status: 403});
+ const body = await req.json();
+ if (url.pathname.endsWith("count_tokens")) {
+ if (body.metadata?.fixture_quota_probe === true) return Response.json({error: {type: "rate_limit_error", message: "The model allowance is exhausted"}}, {status: 429, headers: {
+ "x-should-retry": "false", "retry-after": "60", "x-omnirush-grant-scope": "model", "x-omnirush-grant-bucket": "model:claude-opus-5-5",
+ "x-omnirush-grant-resets-at": "2037-09-24T00:00:00Z", "x-ratelimit-limit-tokens": "8000", "x-ratelimit-remaining-tokens": "0", "x-private-provider-secret": "fixture-must-not-forward",
+ }});
+ return Response.json({input_tokens: 100});
+ }
+ if (body.model !== grant.model) return Response.json({error: {type: "permission_error", message: "Model binding mismatch"}}, {status: 403});
+ const wire = {userAgent: req.headers.get("user-agent"), model: body.model, thinking: body.thinking, session: req.headers.get("x-omnirush-session-id"), client: req.headers.get("x-omnirush-client"), app: req.headers.get("x-app"), beta: req.headers.get("anthropic-beta"), box: req.headers.get("x-omnirush-box")};
+ if (wire.app !== "cli" || !wire.userAgent?.startsWith("claude-cli/") || !wire.beta?.includes("claude-code-") || wire.box !== "1" || wire.session !== grant.session || wire.client !== grant.client || !/^(desktop|cli)\/[0-9][A-Za-z0-9.+_-]{0,63}$/.test(wire.client ?? "")) {
+ inferenceDenials.push(wire); return Response.json({error: {type: "permission_error", message: "Harness admission mismatch"}}, {status: 403});
+ }
+ if (rejectInferenceOnce) {
+ rejectInferenceOnce = false; tokenRejections++;
+ return Response.json({type: "error", error: {type: "authentication_error", message: "Fixture token expired before inference"}}, {status: 401});
+ }
+ calls++;
+ requests.push(wire);
+ const userText = (message: {role: string; content: unknown}) => message.role !== "user" ? "" : typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content.filter(b => b.type === "text").map(b => b.text).join("\n") : "";
+ const messages = body.messages;
+ let start = messages.findLastIndex((m: {role: string; content: unknown}) => userText(m).includes("fixture-turn") || userText(m).includes("fixture-child"));
+ if (start < 0) start = 0;
+ const prompt = userText(messages[start]);
+ const answered = messages.slice(start + 1).some((m: {content: unknown}) => Array.isArray(m.content) && m.content.some(b => b.type === "tool_result"));
+ const child = /fixture-child-(\d)/.exec(prompt)?.[1];
+ const tool = (name: string, input: Record<string, unknown>) => ({type: "tool_use", id: `toolu_${randomUUID().replaceAll("-", "")}`, name, input});
+ let content: Array<Record<string, unknown>>;
+ if (answered) content = [{type: "text", text: child ? `Child ${child} finished.` : "Development turn complete. Sandbox files updated."}];
+ else if (child) content = [tool("Write", {file_path: `/workspace/child-${child}.txt`, content: `child-${child}\n`})];
+ else if (prompt.includes("fixture-turn-1")) content = [
+ {type: "thinking", thinking: "I will implement and check the project in the sandbox.", signature: "opaque-fixture-signature"},
+ tool("Write", {file_path: "/workspace/answer.txt", content: "first turn\n"}),
+ tool("Bash", {command: "printf 'environment survives\\n' > /home/node/environment-marker; printf '#!/bin/sh\\nexit 0\\n' > /workspace/check.sh; chmod +x /workspace/check.sh"}),
+ ...Array.from({length: 5}, (_, i) => tool("Agent", {subagent_type: "general-purpose", ...(i === 0 ? {model: "haiku"} : {}), description: `Check module ${i + 1}`, prompt: `fixture-child-${i + 1}: Create your assigned child file.`})),
+ ];
+ else if (prompt.includes("fixture-turn-2")) content = [tool("Bash", {command: "test -f /home/node/environment-marker && test -x check.sh && printf 'second turn\\n' >> answer.txt; rm seed.txt"})];
+ else if (prompt.includes("fixture-turn-stop")) content = [tool("Bash", {command: "printf 'partial\\n' > partial.txt; sleep 90"})];
+ else if (prompt.includes("fixture-turn-broker-guard")) content = [tool("Bash", {command: `node --input-type=module -e 'const r=await fetch(process.env.ANTHROPIC_BASE_URL+"/v1/messages",{method:"POST",headers:{"authorization":"Bearer "+process.env.ANTHROPIC_AUTH_TOKEN,"content-type":"application/json"},body:JSON.stringify({model:"claude-haiku-4-5-20251001",max_tokens:20,messages:[{role:"user",content:"Model isolation probe"}]})});console.log("model guard status",r.status);'`})];
+ else if (prompt.includes("fixture-turn-authorization")) content = [tool("Bash", {command: `node --input-type=module <<'QUOTA_PROBE'
+import fs from 'node:fs';
+const response = await fetch(process.env.ANTHROPIC_BASE_URL + '/v1/messages/count_tokens', {
+ method: 'POST', headers: {'authorization': 'Bearer ' + process.env.ANTHROPIC_AUTH_TOKEN, 'content-type': 'application/json'},
+ body: JSON.stringify({model: 'claude-opus-5-5', metadata: {fixture_quota_probe: true}, messages: [{role: 'user', content: 'Quota metadata probe'}]}),
+});
+const proof = {status: response.status, headers: Object.fromEntries(response.headers)};
+await response.body?.cancel();
+fs.writeFileSync('/workspace/authorization-checked.json', JSON.stringify(proof));
+console.log('Quota probe recorded');
+QUOTA_PROBE`})];
+ else content = [tool("Read", {file_path: "/workspace/answer.txt"})];
+ const stop_reason = content.some(b => b.type === "tool_use") ? "tool_use" : "end_turn";
+ const message = {id: `msg_${calls}`, type: "message", role: "assistant", ...(responseModel === null ? {} : {model: responseModel ?? body.model}), content, stop_reason, stop_sequence: null, usage: {input_tokens: 100, output_tokens: 30}};
+ if (!body.stream) return Response.json(message);
+ let output = "";
+ const send = (type: string, data: Record<string, unknown>) => { output += `event: ${type}\ndata: ${JSON.stringify({type, ...data})}\n\n`; };
+ send("message_start", {message: {...message, content: [], stop_reason: null, usage: {input_tokens: 100, output_tokens: 0}}});
+ for (const [index, block] of content.entries()) {
+ send("content_block_start", {index, content_block: block.type === "tool_use" ? {...block, input: {}} : block.type === "thinking" ? {type: "thinking", thinking: "", signature: ""} : {type: "text", text: ""}});
+ send("content_block_delta", {index, delta: block.type === "tool_use" ? {type: "input_json_delta", partial_json: JSON.stringify(block.input)} : block.type === "thinking" ? {type: "thinking_delta", thinking: block.thinking} : {type: "text_delta", text: block.text}});
+ if (block.type === "thinking") send("content_block_delta", {index, delta: {type: "signature_delta", signature: block.signature}});
+ send("content_block_stop", {index});
+ }
+ send("message_delta", {delta: {stop_reason, stop_sequence: null}, usage: {output_tokens: 30}}); send("message_stop", {});
+ return new Response(output, {headers: {"content-type": "text/event-stream"}});
+}});
+if (process.env.CLAUDE_LAB_INFERENCE_ONLY === "1") {
+ fs.writeFileSync(path.join(root, "ready.json"), JSON.stringify({gateway: `http://127.0.0.1:${gateway.port}`, root, project}), {mode: 0o600});
+ const stop = () => { gateway.stop(true); process.exit(0); };
+ process.on("SIGTERM", stop); process.on("SIGINT", stop);
+} else {
+const { startServer } = await import("../../../../apps/server/src/server.js");
+const config: ServerConfig = {appVersion: "0.0.0-test", host: "127.0.0.1", port: 0, token: "owt_claude_fixture", hostToken: "owt_claude_host", approval: {mode: "auto", timeoutMs: 1000}, corsOrigins: ["*"], workspaces: [{id: "ws_claude", name: "Claude fixture", path: project, preset: "starter", workspaceType: "local"}], authorizedRoots: [project], readOnly: false, startedAt: Date.now(), tokenSource: "cli", hostTokenSource: "cli", logFormat: "pretty", logRequests: false, omnirushGatewayCredentials: {gatewayUrl: `http://127.0.0.1:${gateway.port}/v1`, accessToken: deviceToken, refreshToken: "refresh-fixture"}};
+const server = await startServer(config);
+const ownerToken = await (await fetch(`http://127.0.0.1:${server.port}/tokens`, {method: "POST", headers: {"x-omnirush-host-token": config.hostToken, "content-type": "application/json"}, body: JSON.stringify({scope: "owner", label: "Claude fixture"})})).json();
+// A small HTTP boundary fixture for renderer connection/cancellation checks.
+// It never prepares a sandbox or calls inference; full native proof stays above.
+let connectionServer: ReturnType<typeof Bun.serve> | undefined;
+if (process.env.CLAUDE_LAB_CONNECTION_ONLY === "1") {
+ let hostToken = "fixture-host-1", holdCreate = false, available = true;
+ let exportMode: "stream" | "blocked" | "complete" = "stream";
+ const boundaryRequests: Array<{route: string; method: string; accepted: boolean; remote: boolean; hostMatches: boolean; hostPresent: boolean}> = [];
+ let cancelledCreates = 0, cancelledExports = 0, startedExports = 0, completedExports = 0;
+ const session = {id: "00000000-0000-4000-8000-000000000001", createdAt: new Date().toISOString(), model: "claude-opus-5-5", capture: "complete", replay: "restored", issues: [],
+ turns: [{number: 1, status: "complete"}], compatibility: "current", modelIsolation: {status: "observed"}, contract: {execution: {os: "linux", architecture: "x64"}}};
+ connectionServer = Bun.serve({hostname: "127.0.0.1", port: 0, async fetch(req) {
+ const url = new URL(req.url);
+ const cors = {"access-control-allow-origin": "*", "access-control-allow-headers": "authorization, content-type, x-omnirush-host-token", "access-control-allow-methods": "GET, POST, OPTIONS"};
+ const json = (body: unknown, status = 200) => Response.json(body, {status, headers: cors});
+ if (req.method === "OPTIONS") return new Response(null, {headers: cors});
+ if (url.pathname === "/fixture/witness") return json({requests: boundaryRequests, cancelledCreates, cancelledExports, startedExports, completedExports, turns: session.turns.length, lastTurnStatus: session.turns.at(-1)?.status, available});
+ if (url.pathname === "/fixture/control") {
+ const body = await req.json();
+ if (typeof body.hostToken === "string") hostToken = body.hostToken;
+ if (typeof body.holdCreate === "boolean") holdCreate = body.holdCreate;
+ if (typeof body.available === "boolean") available = body.available;
+ if (body.crashedTurn === true) session.turns[session.turns.length - 1].status = "running";
+ if (body.exportMode === "stream" || body.exportMode === "blocked" || body.exportMode === "complete") exportMode = body.exportMode;
+ return json({ok: true});
+ }
+ const remote = url.pathname.startsWith("/remote/");
+ const hostMatches = req.headers.get("x-omnirush-host-token") === hostToken;
+ const hostPresent = req.headers.has("x-omnirush-host-token");
+ const accepted = remote ? req.headers.get("authorization") === "Bearer fixture-remote" && !hostPresent : hostMatches;
+ const pathname = remote ? url.pathname.slice("/remote".length) : url.pathname;
+ if (pathname === "/workspaces" || pathname.includes("/claude/")) {
+ boundaryRequests.push({route: pathname, method: req.method, accepted, remote, hostMatches, hostPresent});
+ if (!accepted) return json({message: "Fixture requires the current connection credentials"}, 403);
+ if (pathname === "/workspaces") return json({items: [config.workspaces[0], {id: "rem_ws_remote", name: "Remote Claude fixture", workspaceType: "remote", baseUrl: `${url.origin}/remote`, omnirushToken: "fixture-remote", omnirushWorkspaceId: "ws_remote"}]});
+ const route = pathname.split("/claude/")[1];
+ if (route === "status") return json({allowed: available, sandboxReady: available});
+ if (route === "sessions" && req.method === "GET") return json([session]);
+ if (route === "sessions" && holdCreate) return new Promise<Response>(resolve => {
+ req.signal.addEventListener("abort", () => { cancelledCreates++; resolve(json({cancelled: true}, 499)); }, {once: true});
+ });
+ if (route === "sessions") return json(session, 201);
+ if (route.endsWith("/turns")) { session.turns.push({number: session.turns.length + 1, status: "complete"}); return json({started: true}, 202); }
+ if (route.endsWith("/events")) return json([{type: "assistant", text: "Connection fixture ready", turn: 1}]);
+ if (route.endsWith("/export")) {
+ startedExports++;
+ if (exportMode === "blocked") return json({message: "Another process is using this session or its operation owner is unknown"}, 409);
+ if (exportMode === "complete") { completedExports++; return new Response(new Uint8Array([80, 75, 3, 4]), {headers: {...cors, "content-type": "application/zip"}}); }
+ return new Response(new ReadableStream({
+ start(stream) { stream.enqueue(new Uint8Array([80, 75, 3, 4])); },
+ cancel() { cancelledExports++; },
+ }), {headers: {...cors, "content-type": "application/zip"}});
+ }
+ return json(session);
+ }
+ return fetch(`http://127.0.0.1:${server.port}${url.pathname}${url.search}`, {method: req.method, headers: req.headers, body: req.method === "GET" || req.method === "HEAD" ? undefined : await req.arrayBuffer(), signal: req.signal});
+ }});
+}
+fs.writeFileSync(path.join(root, "ready.json"), JSON.stringify({baseUrl: `http://127.0.0.1:${connectionServer?.port ?? server.port}`, token: ownerToken.token, hostToken: connectionServer ? "fixture-host-1" : config.hostToken, gateway: `http://127.0.0.1:${gateway.port}`, workspaceId: "ws_claude", root}), {mode: 0o600});
+const stop = async () => { connectionServer?.stop(true); await server.stop(); gateway.stop(true); process.exit(0); };
+process.on("SIGTERM", () => void stop()); process.on("SIGINT", () => void stop());
+}
diff --git a/evals/specs/claude-native-capture.test.ts b/evals/specs/claude-native-capture.test.ts
new file mode 100644
index 00000000..82ef7803
--- /dev/null
+++ b/evals/specs/claude-native-capture.test.ts
@@ -0,0 +1,57 @@
+import { createHash } from "node:crypto";
+import { expect } from "vitest";
+import { startCaptureEfficiencyLab } from "@omnirush/labs";
+import { needs, test } from "@omnirush/testkit";
+
+test("Claude native evidence survives capture-worker restart and exports every conversation branch and child", { timeout: 60_000 }, async ({ evidence }) => {
+ needs({ placement: "local", commands: ["bun"] });
+ const lab = await startCaptureEfficiencyLab();
+ const sessionId = "00000000-0000-4000-8000-000000000001";
+ const actor = "actor-a";
+ const request = async (operation: string, extra: Record<string, unknown> = {}, status = 202) => {
+ const response = await fetch(`${lab.baseUrl}/control/native/${operation}`, {
+ method: "POST", headers: { authorization: `Bearer ${lab.controlToken}`, "content-type": "application/json" },
+ body: JSON.stringify({ sessionId, actor, ...extra }), signal: AbortSignal.timeout(10_000),
+ });
+ const body = await response.json(); expect(response.status, JSON.stringify(body)).toBe(status); return body;
+ };
+ try {
+ const seeded = await request("seed");
+ const partial = await request("finish");
+ expect(partial.status).toBe("incomplete");
+ expect(partial.issues).toContain(`partial_line:claude/projects/-fixture-workspace/${sessionId}.jsonl`);
+ await request("finish", { actor: "actor-b" }, 403);
+ await request("account", { signedIn: null });
+ await request("finish", {}, 500);
+ await request("account", { signedIn: "actor-b" });
+ await request("finish", {}, 500);
+ await request("account", { signedIn: actor });
+ const event = JSON.stringify({ type: "stream_event", event: { type: "content_block_delta", delta: { type: "thinking_delta", thinking: "visible delta" } } }) + "\n";
+ await request("stream", { text: event, offset: 0 });
+ await request("restart");
+ const duplicate = await request("stream", { text: event, offset: 0 });
+ expect(duplicate.streams.sdk).toBe(Buffer.byteLength(event));
+ await request("stream", { text: "conflicting", offset: 0 }, 500);
+ await request("repair");
+ const complete = await request("finish");
+ expect(complete.status).toBe("complete");
+ expect(complete.replay).toBe("unverified");
+ expect(complete.files).toHaveLength(12);
+ expect((await lab.witness()).modes).toEqual(["worker", "worker"]);
+ const exported = await request("export");
+ const files: Array<{ path: string; text: string }> = exported.files;
+ const root = files.find((file) => file.path.endsWith(`/${sessionId}.jsonl`));
+ if (!root) throw new Error("native root missing");
+ expect(createHash("sha256").update(root.text).digest("hex")).toBe(seeded.rootSha256);
+ expect(root.text).toContain("side-result"); expect(root.text).toContain("main-result");
+ expect(root.text).toContain("opaque-fixture"); expect(root.text).toContain("futureNativeField");
+ expect(files.filter((file) => file.path.includes("/subagents/") && file.path.endsWith(".jsonl"))).toHaveLength(5);
+ expect(files.filter((file) => file.path.endsWith(".meta.json"))).toHaveLength(5);
+ expect(files.find((file) => file.path === "events/sdk.jsonl")?.text).toBe(event);
+ expect(JSON.stringify(files)).not.toContain("DO_NOT_EXPORT_AUTH");
+ expect(JSON.stringify(files)).not.toContain("DO_NOT_EXPORT_OTHER_SESSION");
+ expect((await lab.witness()).attempts).toHaveLength(0);
+ evidence.recordAssertionEvidence("Native branches, subagents and opaque fields survive byte-exact private export", "The source SHA-256 matched; both branch results, five child JSONL files and five sidecars survived. Auth and unrelated-session canaries were absent; no raw evidence went to the legacy collector.", true);
+ evidence.recordAssertionEvidence("Incomplete capture fails closed and stream retries survive worker restart", "A truncated record stayed incomplete; a real suffix repaired it. Retrying the same offset after worker restart did not duplicate bytes, conflicting retry failed, and another actor was denied. Capture completion remained replay-unverified.", true);
+ } finally { await lab.stop(); }
+});
diff --git a/evals/specs/claude-native.e2e.test.ts b/evals/specs/claude-native.e2e.test.ts
new file mode 100644
index 00000000..54756eab
--- /dev/null
+++ b/evals/specs/claude-native.e2e.test.ts
@@ -0,0 +1,293 @@
+import { expect } from "vitest";
+import { spec } from "@omnirush/testkit";
+import { claudeNativeWorld, claudeConnectionWorld } from "../worlds/claude-native.ts";
+const test = spec.world(claudeNativeWorld, {needs: {placement: "local", commands: ["bun", "docker", "pnpm"]}, timeout: 120_000});
+
+test("Claude GUI runs three native sandbox turns with five children and exports a verified environment", {timeout: 15 * 60_000}, async ({world, user, probe, evidence}) => {
+ await user.see("New Claude session", {timeoutMs: 60_000});
+ expect((await world.request("sessions", {captureConsent: true}, "invalid-client")).status).toBe(401);
+ expect((await world.request("sessions", {captureConsent: true}, world.collaboratorToken)).status).toBe(403);
+ if (world.packaged) expect(await world.runtimeWitness()).toEqual({protocol: "file:", bridge: true, embeddedServerSelected: true});
+ await user.click("Retain private traces and full project snapshots");
+ await user.click("New Claude session");
+ const createPollStatuses: number[] = [];
+ await probe.eventually(async () => {
+ const response = await world.request("sessions"); createPollStatuses.push(response.status);
+ return response;
+ }, {within: 180_000, until: response => response.status === 200 && Array.isArray(response.body) && response.body.length === 1});
+ expect(createPollStatuses.every(status => status === 200)).toBe(true);
+ await user.see("Message Claude", {timeoutMs: 180_000, editable: true});
+ await world.control({rejectInferenceOnce: true});
+ const mintsBeforeTurns = (await world.witness()).mintRequests.length;
+ for (let turn = 1; turn <= 3; turn++) {
+ await user.type("Message Claude", `fixture-turn-${turn}: ${turn === 1 ? "Build the module and ask five subagents to check it." : "Continue developing and check the prior changes."}`);
+ await user.click("Send");
+ await probe.eventually(() => world.session(), {within: 180_000, until: session => session?.turns.length === turn && session.turns[turn - 1].status !== "running"});
+ const session = await world.session();
+ expect(session.turns[turn - 1].status, JSON.stringify(session)).toBe("complete");
+ expect(session.capture).toBe("complete");
+ expect(session.modelIsolation.status).toBe("observed");
+ expect(session.modelIsolation.observedModels).toEqual(["claude-opus-5-5"]);
+ const authorizationWitness = await world.witness();
+ expect(authorizationWitness.tokenRejections).toBe(1);
+ // One initial mint per turn, plus exactly one remint after the real 401.
+ expect(authorizationWitness.mintRequests.length - mintsBeforeTurns).toBe(turn + 1);
+ expect(session.authorization.budget.status).toBe(turn === 3 ? "unknown" : "known");
+ const budgetText = turn === 3 ? "Model allowance has not been reported by the backend." : turn === 2 ? "model no limit · Session: no limit · Account day: 18,000 tokens" : "model 7,000 tokens · Session: 4,000 tokens · Account day: 18,000 tokens";
+ await probe.eventually(() => probe.dom('[aria-label="Model allowance"]'), {within: 10_000, until: result => result.elements[0]?.text.includes(budgetText) === true});
+ await probe.eventually(() => probe.dom('textarea[aria-label="Message Claude"]:not(:disabled)'), {within: 10_000, until: result => result.elements.length === 1});
+ await user.see("Message Claude", {editable: true});
+ if (turn === 1) {
+ await user.reload(); await user.see("Claude session");
+ await probe.eventually(() => probe.dom('[aria-label="Claude session"] option'), {within: 30_000, until: result => result.elements.length === 2});
+ await user.click("Claude session"); await user.press("End"); await user.press("Enter");
+ await user.see("Message Claude", {editable: true});
+ }
+ await world.control({budgetMode: turn === 1 ? "unlimited" : "unknown"});
+ }
+ await user.type("Verification command", "test -f /home/node/environment-marker && test -x /workspace/check.sh && test ! -e /workspace/seed.txt && test $(ls /workspace/child-*.txt | wc -l) -eq 5 && grep 'second turn' /workspace/answer.txt");
+ await user.click("Verify restore");
+ await user.see({testId: "claude-notice"}, {text: "Environment restored and verification passed with network access disabled.", timeoutMs: 180_000});
+ world.prepareDownload();
+ await user.click("Download private ZIP");
+ await user.see({testId: "claude-notice"}, {text: "Private session ZIP downloaded.", timeoutMs: 180_000});
+ await world.control({checkpointEnabled: false});
+ await user.click("Upload private session");
+ await user.see({testId: "claude-notice"}, {text: "Native traces uploaded. Environment upload is disabled by the backend; the complete ZIP remains on this device.", timeoutMs: 180_000});
+ const nativeOnly = await world.witness();
+ expect(nativeOnly.archives.map((archive: {request: {payload: string}}) => archive.request.payload)).toEqual(["claude_native"]);
+ await world.control({checkpointEnabled: true});
+ await user.click("Upload private session");
+ await user.see({testId: "claude-notice"}, {text: "Private session uploaded. Backend receipts confirm the native traces and environment arrived.", timeoutMs: 180_000});
+ const session = await world.session(), result = await world.nativeEvidence(session.id), witness = await world.witness();
+ if (world.packaged) expect(await world.downloaded()).toBe(result.zipBytes);
+ const display = (await world.request(`sessions/${session.id}/events`)).body;
+ expect(display.filter((event: {type: string}) => event.type === "user")).toHaveLength(3);
+ expect(display.filter((event: {type: string}) => event.type === "result")).toHaveLength(3);
+ expect(display.some((event: {type: string; text: string; turn: number}) => event.type === "tool" && event.text === "Read" && event.turn === 3)).toBe(true);
+ expect(display.map((event: {turn: number}) => event.turn)).toEqual(display.map((event: {turn: number}) => event.turn).sort((a: number, b: number) => a-b));
+ const desktop = await world.desktopExport(session.id);
+ expect(desktop?.status).toBe(200); expect(desktop?.bytes).toBe(result.zipBytes);
+ if (world.packaged) expect(await world.cancelDesktopExport(session.id)).toEqual({active: true, outcome: "cancelled", stillActive: false});
+ expect(result.manifest.transport).toBe("sdk");
+ expect(result.manifest.status).toBe("complete");
+ expect(result.manifest.files.filter((file: {path: string}) => /subagents\/agent-.*\.jsonl$/.test(file.path))).toHaveLength(5);
+ expect(result.manifest.files.some((file: {thinkingBlocks: number}) => file.thinkingBlocks > 0)).toBe(true);
+ expect(result.manifest.streams.sdk).toBeGreaterThan(0); expect(result.manifest.streams.hooks).toBeGreaterThan(0);
+ expect(result.manifest.qc.humanPromptCandidates).toBe(3);
+ expect(result.manifest.qc.childPromptRecords).toBeGreaterThanOrEqual(5);
+ expect(result.manifest.qc.exposedThinkingBlocks).toBeGreaterThan(0);
+ expect(result.readWitnesses).toHaveLength(1);
+ expect(result.replay.status).toBe("restored"); expect(result.zipBytes).toBeGreaterThan(0);
+ expect(new Set([result.state.base.file, ...result.state.turns.map((turn: {after: {file: string}}) => turn.after.file)]).size).toBe(1);
+ expect(witness.uploadRetryInjected).toBe(true); expect(witness.uploadLossInjected).toBe(true);
+ expect(witness.uploadsComplete).toBe(2); expect(witness.uploadedBytes).toBe(result.zipBytes);
+ expect(witness.presignedAuthLeaks).toBe(0);
+ expect(witness.archives.map((archive: {request: {payload: string}}) => archive.request.payload).sort()).toEqual(["claude_checkpoint", "claude_native"]);
+ expect(witness.archives.every((archive: {request: {session_id: string; contract_hash: string}}) => archive.request.session_id === session.id && archive.request.contract_hash === result.state.contractSha256)).toBe(true);
+ expect(witness.hostFiles).toEqual(world.initialHostFiles);
+ const layout = await world.layout();
+ expect(layout.lastMessageBottom).toBeLessThanOrEqual(layout.conversationBottom);
+ expect(layout.composerTop).toBeGreaterThanOrEqual(layout.conversationBottom);
+ expect(witness.requests.every((r: {userAgent: string; model: string}) => /claude-cli/.test(r.userAgent) && r.model === "claude-opus-5-5")).toBe(true);
+ expect(witness.inferenceDenials).toEqual([]);
+ expect(witness.requests.every((r: {app: string; beta: string; box: string; client: string; session: string}) => r.app === "cli" && r.beta.includes("claude-code-") && r.box === "1" && /^desktop\/[0-9]/.test(r.client) && r.session === session.id)).toBe(true);
+ expect(result.state.modelIsolation.status).toBe("observed");
+ expect(result.state.modelIsolation.observedModels).toEqual(["claude-opus-5-5"]);
+ const authorizationRetries = result.modelRequests.filter((event: {authorizationFailures?: number[]}) => event.authorizationFailures?.length);
+ expect(authorizationRetries).toHaveLength(1);
+ expect(authorizationRetries[0]).toMatchObject({type: "response", status: 200, authorizationFailures: [401]});
+ expect(result.state.contract.model).toBe("claude-opus-5-5");
+ expect(result.state.contract.execution).toMatchObject({kind: "docker", os: "linux", workspace: "session-copy"});
+ const callsBeforeMutation = witness.calls;
+ const restoreModel = await world.mutateSession(session.id, "model");
+ try { expect((await world.request(`sessions/${session.id}/turns`, {prompt: "Do not reuse a changed model"})).status).not.toBe(202); }
+ finally { await restoreModel(); }
+ const restoreContract = await world.mutateSession(session.id, "legacy");
+ try {
+ expect((await world.request(`sessions/${session.id}/turns`, {prompt: "Do not resume an unattested legacy session"})).status).not.toBe(202);
+ expect((await world.exportReceipt(session.id)).status).toBe(200);
+ } finally { await restoreContract(); }
+ expect((await world.witness()).calls).toBe(callsBeforeMutation);
+ const before = witness.calls; await world.access(false);
+ const paused = await world.request(`sessions/${session.id}/turns`, {prompt: "This must not reach inference"});
+ if (paused.status === 202) {
+ const denied = await probe.eventually(() => world.session(), {within: 180_000, until: state => state.turns.length === 4 && state.turns[3].status !== "running"});
+ expect(denied.turns[3].status).toBe("failed");
+ }
+ expect((await world.witness()).calls).toBe(before);
+ expect((await world.request(`sessions/${session.id}`)).status).toBe(200);
+ expect((await world.exportReceipt(session.id)).status).toBe(200);
+ await world.access(true);
+ await user.screenshot();
+ if (world.packaged) {
+ await world.switchToEmptyWorkspace();
+ await user.see("New Claude session");
+ await probe.eventually(() => probe.dom('[aria-label="Claude conversation"]'), {within: 30_000, until: state => state.elements.length === 0});
+ expect((await probe.dom('textarea[aria-label="Message Claude"]')).elements).toHaveLength(0);
+ expect((await probe.dom('[aria-label="Claude session"] option')).elements).toHaveLength(1);
+ }
+ evidence.recordAssertionEvidence("GUI uses native Claude Code and captures every child inside the sandbox", "Three real SDK turns resumed one UUID across a page reload; five child transcripts, thinking blocks, SDK events and hooks were retained. Host project was unchanged. Unselected accounts and collaborator tokens could not start work.", true);
+ evidence.recordAssertionEvidence("One model remains fixed across children and resume", "A child explicitly requested Haiku, but all actual managed inference requests and provider identities stayed on Opus. A changed model and missing legacy contract both blocked continuation without upstream calls; the legacy evidence remained exportable.", true);
+ evidence.recordAssertionEvidence("GUI resumes after one rejected inference grant without contaminating model evidence", "The first turn received a real HTTP 401. Exactly one additional grant mint recovered it; the saved policy response records [401] followed by 200. All three GUI turns, including resume after reload, completed with observed Opus-only identity and a restored replay.", true);
+ evidence.recordAssertionEvidence("Private ZIP retains restorable full environments", "The exported checkpoint loaded into a separate network-disabled container. The verification command checked a file outside the project, executable mode, deletion, all five child outputs and the second-turn edit.", true);
+ evidence.recordAssertionEvidence("Sealed native and environment uploads recover independently", "Canonical ORSEAL01 multipart upload recovered from a transient 503 and a lost acknowledged part. The fixture decrypted both payloads, verified plaintext hashes and every native manifest member, and received no device bearer on presigned PUTs. Native traces completed while checkpoint upload was disabled, then the checkpoint resumed after enablement.", true);
+ evidence.recordAssertionEvidence("Desktop archive transfer streams the full local-server bundle", "The actual desktop transfer helper saved the same ZIP from the real product server to a test-selected save-dialog destination, beyond the ordinary inbox transfer size cap.", true);
+ if (world.packaged) evidence.recordAssertionEvidence("Packaged Electron runs the Claude journey through its embedded server", "The installed-layout binary loaded file assets and its actual preload bridge without a development renderer or server override. Three turns, five children, restore, upload and the real native save dialog completed against the packaged embedded server.", true);
+});
+
+const connectionTest = spec.world(claudeConnectionWorld, {needs: {placement: "local", commands: ["bun", "pnpm"]}, timeout: 120_000});
+connectionTest("Claude connection refresh keeps host authority, remote isolation and cancellation", {timeout: 120_000}, async ({world, user, probe, evidence}) => {
+ await user.see("New Claude session", {timeoutMs: 60_000});
+ await probe.eventually(() => probe.dom('[aria-label="Claude session"] option'), {within: 15_000, until: result => result.elements.length === 2});
+ await user.click("Claude session"); await user.press("End"); await user.press("Enter");
+ await user.see("Message Claude", {editable: true});
+ const initial = await world.connectionWitness();
+ expect(initial.requests.filter((request: {accepted: boolean}) => !request.accepted)).toEqual([]);
+ // The HTTP fixture requires host authority even with a valid owner bearer.
+ expect((await world.request("sessions")).status).toBe(403);
+ await world.connectionControl({hostToken: "fixture-host-2"});
+ expect((await world.request("sessions", undefined, undefined, "fixture-host-1")).status).toBe(403);
+ const beforeRotation = (await world.connectionWitness()).requests.length;
+ await world.publishHostToken("fixture-host-2");
+ await probe.eventually(() => world.connectionWitness(), {within: 15_000, until: state => state.requests.slice(beforeRotation).some((request: {route: string; accepted: boolean}) => request.route.endsWith("/events") && request.accepted)});
+ await user.type("Message Claude", "Resume after host-token rotation"); await user.click("Send");
+ await probe.eventually(() => probe.dom('[aria-label="Capture status"]'), {within: 10_000, until: result => result.elements[0]?.text.includes("2 turns") === true});
+ await user.click("Download private ZIP");
+ await probe.eventually(() => world.connectionWitness(), {within: 10_000, until: state => state.startedExports === 1});
+ await user.click("Cancel download");
+ await user.see({testId: "claude-notice"}, {text: "Download cancelled."});
+ await probe.eventually(() => world.connectionWitness(), {within: 10_000, until: state => state.cancelledExports === 1});
+ const local = (await world.connectionWitness()).requests.slice(beforeRotation);
+ expect(local.every((request: {accepted: boolean; hostMatches: boolean}) => request.accepted && request.hostMatches)).toBe(true);
+ expect(local.some((request: {route: string}) => request.route.endsWith("/turns"))).toBe(true);
+ expect(local.some((request: {route: string}) => request.route.endsWith("/export"))).toBe(true);
+
+ await world.navigateConnectionWorkspace(true);
+ await probe.eventually(() => probe.dom('[aria-label="Claude session"] option'), {within: 15_000, until: result => result.elements.length === 2});
+ await user.click("Claude session"); await user.press("End"); await user.press("Enter");
+ await user.see("Message Claude", {editable: true});
+ await user.type("Message Claude", "Use the remote workspace credentials"); await user.click("Send");
+ await probe.eventually(() => probe.dom('[aria-label="Capture status"]'), {within: 10_000, until: result => result.elements[0]?.text.includes("3 turns") === true});
+ const remote = (await world.connectionWitness()).requests.filter((request: {remote: boolean}) => request.remote);
+ expect(remote.length).toBeGreaterThan(0);
+ expect(remote.every((request: {accepted: boolean; hostPresent: boolean}) => request.accepted && !request.hostPresent)).toBe(true);
+
+ await world.connectionControl({holdCreate: true});
+ await user.click("Retain private traces and full project snapshots"); await user.click("New Claude session");
+ await probe.eventually(() => world.connectionWitness(), {within: 10_000, until: state => state.requests.some((request: {remote: boolean; method: string; route: string}) => request.remote && request.method === "POST" && request.route.endsWith("/sessions"))});
+ await world.navigateConnectionWorkspace(false);
+ await probe.eventually(() => world.connectionWitness(), {within: 10_000, until: state => state.cancelledCreates === 1});
+ await world.connectionControl({available: false, crashedTurn: true, exportMode: "blocked"});
+ await world.publishHostToken("fixture-host-2");
+ await user.see({text: "Saved sessions"}, {timeoutMs: 10_000});
+ await user.click("Claude session"); await user.press("End"); await user.press("Enter");
+ await user.see("Download private ZIP");
+ await user.click("Download private ZIP");
+ await user.see({text: "Another process is using this session or its operation owner is unknown"}, {timeoutMs: 10_000});
+ expect((await probe.dom('[data-testid="claude-notice"]')).elements).toHaveLength(0);
+ await world.connectionControl({exportMode: "complete"});
+ await user.click("Download private ZIP");
+ await user.see({testId: "claude-notice"}, {text: "Private session ZIP downloaded."});
+ const offline = await world.connectionWitness();
+ expect(offline.available).toBe(false); expect(offline.lastTurnStatus).toBe("running");
+ expect(offline.completedExports).toBe(1);
+ expect(offline.requests.some((request: {route: string}) => request.route.endsWith("/recover"))).toBe(false);
+ expect((await world.witness()).calls).toBe(0);
+ evidence.recordAssertionEvidence("Claude requests retain current local host authority and isolate remote credentials", "A missing host token was refused. The mounted route refreshed on settings publication and resumed polling, a turn and export with the rotated token. Remote polling and turns used the remote bearer and received no local host header.", true);
+ evidence.recordAssertionEvidence("Route cancellation reaches HTTP requests", "Cancelling a stalled archive closed its response stream without a download success notice. Navigating away from a pending session creation aborted its HTTP request. This focused fixture made zero inference calls and prepared no sandbox.", true);
+ evidence.recordAssertionEvidence("Saved evidence remains downloadable after an unfinished turn while Claude is unavailable", "A saved running turn did not disable export when both account access and sandbox readiness were off. The server's active-owner refusal remained visible; after that lock cleared, export succeeded without recovery or any inference call. The historical turn still read running.", true);
+});
+
+test("Claude rejects invalid session grants and quota denial without retrying or hiding saved evidence", {timeout: 12 * 60_000}, async ({world, probe, evidence}) => {
+ const faults = [
+ {bindingFault: "session"}, {bindingFault: "model"}, {bindingFault: "upstream"}, {bindingFault: "contract"},
+ {expiresIn: 901}, {expiresIn: 10, refreshAfter: 11}, {refreshAfter: 0}, {budgetMode: "wrong-model"}, {budgetMode: "wrong-session"}, {mintStatus: 429},
+ ];
+ const created = await world.request("sessions", {captureConsent: true});
+ expect(created.status).toBe(201);
+ const id = created.body.id;
+ for (const [index, fault] of faults.entries()) {
+ await world.control({bindingFault: null, expiresIn: 900, refreshAfter: 600, mintStatus: 200, budgetMode: "known", ...fault});
+ const before = await world.witness();
+ expect((await world.request(`sessions/${id}/turns`, {prompt: "fixture-turn-grant: This must not reach inference."})).status).toBe(202);
+ const state = await probe.eventually(async () => (await world.request(`sessions/${id}`)).body, {within: 180_000, until: session => session.turns.length === index + 1 && session.turns[index].status !== "running"});
+ expect(state.turns[index].status).toBe("failed");
+ const after = await world.witness();
+ expect(after.calls).toBe(before.calls);
+ expect(after.mintRequests.length).toBe(before.mintRequests.length + 1);
+ expect(after.mintRequests.at(-1)).toMatchObject({session_id: id, model: "claude-opus-5-5", contract_hash: state.contractSha256});
+ expect(after.mintRequests.at(-1).project_key).toMatch(/^[a-f0-9]{12}$/);
+ expect(after.mintRequests.at(-1).client).toBeTruthy();
+ }
+ expect((await world.exportReceipt(id)).status).toBe(200);
+ evidence.recordAssertionEvidence("Short-lived grants bind inference to the immutable session contract", "Wrong session, requested or upstream model, contract bindings and invalid expiration/refresh values all refused inference. Each failed attempt made exactly one token request and preserved an exportable session.", true);
+ evidence.recordAssertionEvidence("Model quota exhaustion does not create an automatic retry storm", "A 429 from the session token endpoint stopped before inference after one token request, while the saved environment remained readable and exportable.", true);
+});
+
+test("Claude accepts valid refresh boundaries and preserves model quota metadata", {timeout: 8 * 60_000}, async ({world, user, probe, evidence}) => {
+ await user.see("New Claude session", {timeoutMs: 60_000});
+ await world.control({refreshAfter: 1, expiresIn: 1, budgetMode: "null"});
+ await user.click("Retain private traces and full project snapshots");
+ await user.click("New Claude session");
+ await user.see("Message Claude", {timeoutMs: 180_000, editable: true});
+ for (let turn = 1; turn <= 2; turn++) {
+ const before = await world.witness();
+ await user.type("Message Claude", `fixture-turn-authorization-${turn}: Check the model allowance response from inside this sandbox.`);
+ await user.click("Send");
+ const session = await probe.eventually(() => world.session(), {within: 180_000, until: state => state?.turns.length === turn && state.turns[turn - 1].status !== "running"});
+ expect(session.turns[turn - 1].status).toBe("complete");
+ expect(session.capture).toBe("complete");
+ expect(session.modelIsolation.status).toBe("observed");
+ expect(session.authorization.budget.status).toBe(turn === 1 ? "unknown" : "known");
+ const after = await world.witness();
+ expect(after.calls - before.calls).toBe(2);
+ if (turn === 1) expect(after.mintRequests.length - before.mintRequests.length).toBeGreaterThan(1);
+ const label = turn === 1 ? "Model allowance has not been reported by the backend." : "model 7,000 tokens";
+ await probe.eventually(() => probe.dom('[aria-label="Model allowance"]'), {within: 10_000, until: value => value.elements[0]?.text.includes(label) === true});
+ await probe.eventually(() => probe.dom('textarea[aria-label="Message Claude"]:not(:disabled)'), {within: 10_000, until: value => value.elements.length === 1});
+ await world.control({refreshAfter: 900, expiresIn: 900, budgetMode: "known"});
+ }
+ const session = await world.session();
+ const proof = await world.request(`sessions/${session.id}/verify`, {command: `node -e 'const p=require("./authorization-checked.json"), h=p.headers; if(p.status!==429 || h["x-should-retry"]!=="false" || h["retry-after"]!=="60" || h["x-omnirush-grant-scope"]!=="model" || h["x-omnirush-grant-bucket"]!=="model:claude-opus-5-5" || h["x-omnirush-grant-resets-at"]!=="2037-09-24T00:00:00Z" || h["x-ratelimit-limit-tokens"]!=="8000" || h["x-ratelimit-remaining-tokens"]!=="0" || h["x-private-provider-secret"]!==undefined) process.exit(1)'`});
+ expect(proof.status).toBe(200); expect(proof.body.status).toBe("restored");
+ evidence.recordAssertionEvidence("Valid boundary grants run without inventing an allowance", "Two SDK turns completed with refresh_after one and equal to expires_in. The short-lived grant caused fresh mint requests; budget:null stayed visibly unknown and the next valid snapshot displayed the model allowance.", true);
+ evidence.recordAssertionEvidence("Quota refusal metadata survives the managed broker without provider secrets", "A sandbox tool observed 429, no-retry, Retry-After, model scope, bucket, reset and token limits. An unrelated provider-secret header was absent. Network-disabled restore verified the recorded response.", true);
+});
+
+test("Claude refuses contaminated provider identities and marks missing identity as unknown", {timeout: 12 * 60_000}, async ({world, probe, evidence}) => {
+ for (const responseModel of ["claude-haiku-4-5-20251001", null]) {
+ await world.control({responseModel});
+ const created = await world.request("sessions", {captureConsent: true});
+ expect(created.status).toBe(201);
+ const id = created.body.id;
+ const beforeCalls = (await world.witness()).calls;
+ expect((await world.request(`sessions/${id}/turns`, {prompt: "fixture-turn-identity: Inspect the project."})).status).toBe(202);
+ const state = await probe.eventually(async () => (await world.request(`sessions/${id}`)).body, {within: 180_000, until: session => session.turns.length === 1 && session.turns[0].status !== "running"});
+ expect(state.modelIsolation.status).toBe(responseModel ? "invalid" : "unknown");
+ if (responseModel) expect(state.modelIsolation.observedModels).toContain(responseModel);
+ else expect(state.modelIsolation.observedModels).toEqual([]);
+ expect(state.turns[0].status).toBe("failed");
+ const display = (await world.request(`sessions/${id}/events`)).body;
+ expect(display.filter((event: {type: string}) => event.type === "tool")).toEqual([]);
+ const before = (await world.witness()).calls;
+ expect(before).toBe(beforeCalls + 1);
+ expect((await world.request(`sessions/${id}/turns`, {prompt: "Do not continue unverified identity"})).status).not.toBe(202);
+ expect((await world.witness()).calls).toBe(before);
+ const archive = await world.exportReceipt(id);
+ expect(archive.status).toBe(200); expect(archive.bytes).toBeGreaterThan(0);
+ }
+ await world.control({resetResponseModel: true});
+ const guarded = await world.request("sessions", {captureConsent: true});
+ expect(guarded.status).toBe(201);
+ const beforeGuard = (await world.witness()).calls;
+ expect((await world.request(`sessions/${guarded.body.id}/turns`, {prompt: "fixture-turn-broker-guard: Probe the managed session model boundary."})).status).toBe(202);
+ const guardedState = await probe.eventually(async () => (await world.request(`sessions/${guarded.body.id}`)).body, {within: 180_000, until: session => session.turns.length === 1 && session.turns[0].status !== "running"});
+ expect(guardedState.modelIsolation.status).toBe("invalid");
+ expect(guardedState.modelIsolation.rejectedRequests).toBeGreaterThan(0);
+ const afterGuard = await world.witness();
+ expect(afterGuard.calls).toBe(beforeGuard + 1);
+ expect(afterGuard.requests.every((request: {model: string}) => request.model === "claude-opus-5-5")).toBe(true);
+ evidence.recordAssertionEvidence("Provider identity is checked before any tool can run", "A response naming another model made the session invalid; a response without identity made it unknown. Each stopped after exactly one upstream call and exposed no tool call to the SDK. Both refused another turn while preserving exportable evidence.", true);
+ evidence.recordAssertionEvidence("The managed broker blocks a tool-requested model switch", "A sandbox tool attempted to request Haiku using its own scoped session bearer. The request was recorded as rejected and invalidated the session; only the original Opus request reached upstream.", true);
+});
diff --git a/evals/worlds/claude-native.ts b/evals/worlds/claude-native.ts
new file mode 100644
index 00000000..0c9eb7be
--- /dev/null
+++ b/evals/worlds/claude-native.ts
@@ -0,0 +1,219 @@
+import fs from "node:fs/promises";
+import { mkdtempSync } from "node:fs";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { spawn, execFile, type ChildProcess } from "node:child_process";
+import { promisify } from "node:util";
+import { fileURLToPath } from "node:url";
+import { chrome, desktop, localHost } from "@omnirush/hosts";
+import { allocateFreePort, browserScript, evaluateOnSurface, navigate } from "@omnirush/cdp";
+import { eventually } from "@omnirush/testkit";
+// Electron's executable JavaScript module has no published declaration file.
+// @ts-expect-error Tests exercise the actual main-process transfer helper.
+import { downloadClaudeArchive } from "../../apps/desktop/electron/binary-transfer.mjs";
+
+const repo = fileURLToPath(new URL("../..", import.meta.url));
+const execute = promisify(execFile);
+export async function claudeNativeWorld() { return createClaudeWorld(false); }
+export async function claudeConnectionWorld() { return createClaudeWorld(true); }
+async function createClaudeWorld(connectionOnly: boolean) {
+ const packaged = !connectionOnly && Boolean(process.env.OMNIRUSH_EVAL_ELECTRON_BINARY);
+ const root = mkdtempSync(path.join(tmpdir(), "omnirush-claude-journey-"));
+ const log = await fs.open(path.join(root, "server.log"), "a");
+ const lab = spawn("bun", ["--conditions=development", "evals/packages/labs/src/claude-runtime-server.ts"], {cwd: repo, env: {...process.env, CLAUDE_LAB_DIR: root, CLAUDE_LAB_INFERENCE_ONLY: packaged ? "1" : "0", CLAUDE_LAB_CONNECTION_ONLY: connectionOnly ? "1" : "0"}, stdio: ["ignore", log.fd, log.fd]});
+ const ready: {baseUrl: string; token: string; hostToken: string; workspaceId: string; gateway: string} = await eventually(async () => JSON.parse(await fs.readFile(path.join(root, "ready.json"), "utf8")), {within: 60_000});
+ const viteLog = await fs.open(path.join(root, "vite.log"), "a");
+ let vite: ChildProcess | undefined;
+ let app!: Awaited<ReturnType<typeof chrome>> | Awaited<ReturnType<typeof desktop>>;
+ let collaboratorToken = "owt_claude_fixture";
+ try {
+ if (packaged) {
+ app = await desktop({name: "claude-native-packaged", host: localHost(), prepareSharedResources: false,
+ profileDir: path.join(root, "electron-profile"), timeoutMs: 90_000,
+ env: {OMNIRUSH_RUNTIME_DB: path.join(root, "runtime.sqlite"),
+ OMNIRUSH_ACCESS_TOKEN: "device-fixture", OMNIRUSH_REFRESH_TOKEN: "refresh-fixture", OMNIRUSH_GATEWAY_URL: `${ready.gateway}/v1`,
+ OMNIRUSH_ELECTRON_START_URL: "", ELECTRON_START_URL: "", OMNIRUSH_AUTO_UPDATE: "0"},
+ });
+ const connection = await evaluateOnSurface(app, browserScript(async folderPath => {
+ const bridge = window.__OMNIRUSH_ELECTRON__;
+ if (!bridge || location.protocol !== "file:") throw new Error("The installed-layout renderer/preload did not load");
+ const initial = await bridge.invokeDesktop("omnirushServerInfo");
+ const response = await fetch(`${initial.baseUrl}/workspaces/local`, {method: "POST", headers: {authorization: `Bearer ${initial.ownerToken}`, "content-type": "application/json"}, body: JSON.stringify({folderPath, name: "Claude fixture", preset: "starter"})});
+ if (!response.ok) throw new Error(`Packaged workspace registration failed: ${response.status}`);
+ const workspaces = await response.json();
+ const workspace = workspaces.workspaces.find((entry: {path: string; id: string}) => entry.path === folderPath);
+ if (!workspace) throw new Error("Packaged workspace registration did not return the project");
+ await bridge.invokeDesktop("workspaceSetSelected", workspace.id);
+ await bridge.invokeDesktop("workspaceSetRuntimeActive", workspace.id);
+ const info = await bridge.invokeDesktop("omnirushServerInfo");
+ if (!workspace || !info.baseUrl || !info.ownerToken || !info.clientToken) throw new Error("Packaged embedded server did not provide owner and collaborator endpoints");
+ location.hash = `/workspace/${workspace.id}/claude`;
+ return {baseUrl: info.baseUrl, token: info.ownerToken, clientToken: info.clientToken, workspaceId: workspace.id};
+ }, [path.join(root, "project")]));
+ Object.assign(ready, connection); collaboratorToken = connection.clientToken;
+ } else {
+ const port = await allocateFreePort();
+ vite = spawn("pnpm", ["--filter", "@omnirush/app", "dev", "--host", "127.0.0.1", "--port", String(port)], {cwd: repo, env: {...process.env, OMNIRUSH_DEV_MODE: "1"}, detached: true, stdio: ["ignore", viteLog.fd, viteLog.fd]});
+ const url = `http://127.0.0.1:${port}`;
+ await eventually(async () => (await fetch(url)).ok, {within: 60_000, until: value => value});
+ app = await chrome({name: "claude-native", host: localHost(), startUrl: url, headless: true});
+ await eventually(() => evaluateOnSurface(app, () => location.origin), {within: 30_000, until: origin => origin === url});
+ await evaluateOnSurface(app, browserScript((base, token, hostToken) => {
+ localStorage.setItem("omnirush.server.urlOverride", base);
+ localStorage.setItem("omnirush.server.token", token);
+ localStorage.setItem("omnirush.server.hostToken", hostToken);
+ }, [ready.baseUrl, ready.token, ready.hostToken]));
+ await navigate(app.client, `${url}/workspace/${ready.workspaceId}/claude`);
+ }
+ } catch (error) {
+ await app?.[Symbol.asyncDispose]();
+ lab.kill("SIGTERM");
+ if (vite?.pid) try { process.kill(-vite.pid, "SIGTERM"); } catch { /* already stopped */ }
+ await log.close(); await viteLog.close();
+ throw error;
+ }
+ const request = async (route: string, body?: unknown, token = ready.token, hostToken?: string) => {
+ const headers: Record<string, string> = {authorization: `Bearer ${token}`, "content-type": "application/json"};
+ if (hostToken) headers["x-omnirush-host-token"] = hostToken;
+ const response = await fetch(`${ready.baseUrl}/workspace/${ready.workspaceId}/claude/${route}`, {method: body === undefined ? "GET" : "POST", headers, body: body === undefined ? undefined : JSON.stringify(body)});
+ return {status: response.status, body: await response.json()};
+ };
+ let dialogTask: Promise<void> | undefined;
+ const initialHostFiles = await fs.readdir(path.join(root, "project"));
+ return {app, root, request, packaged, collaboratorToken, initialHostFiles,
+ async connectionWitness() { return (await fetch(`${ready.baseUrl}/fixture/witness`)).json(); },
+ async connectionControl(body: {hostToken?: string; holdCreate?: boolean; available?: boolean; crashedTurn?: boolean; exportMode?: "stream" | "blocked" | "complete"}) {
+ await fetch(`${ready.baseUrl}/fixture/control`, {method: "POST", body: JSON.stringify(body)});
+ },
+ async publishHostToken(hostToken: string) {
+ await evaluateOnSurface(app, browserScript(token => {
+ localStorage.setItem("omnirush.server.hostToken", token);
+ window.dispatchEvent(new CustomEvent("omnirush-server-settings-changed"));
+ }, [hostToken]));
+ },
+ async navigateConnectionWorkspace(remote: boolean) {
+ await evaluateOnSurface(app, browserScript(id => {
+ history.pushState(null, "", `/workspace/${id}/claude`);
+ window.dispatchEvent(new PopStateEvent("popstate"));
+ }, [remote ? "rem_ws_remote" : ready.workspaceId]));
+ },
+ async cancelDesktopExport(id: string) {
+ if (!packaged || process.platform !== "linux") throw new Error("Native cancellation proof requires packaged Linux Electron/xdotool");
+ const transferId = `claude-cancel-${id}`;
+ const pending = evaluateOnSurface(app, browserScript(async (baseUrl, token, sessionId, transfer) => {
+ const input = {url: `${baseUrl}/workspace/${sessionId.workspaceId}/claude/sessions/${sessionId.id}/export`, headers: {authorization: `Bearer ${token}`}, transferId: transfer};
+ try { await window.__OMNIRUSH_ELECTRON__.invokeDesktop("__downloadClaudeArchive", input); return "completed"; }
+ catch { return "cancelled"; }
+ }, [ready.baseUrl, ready.token, {id, workspaceId: ready.workspaceId}, transferId]));
+ const windowId = await eventually(async () => (await execute("xdotool", ["search", "--onlyvisible", "--name", "Save private Claude session"], {timeout: 2000})).stdout.trim().split("\n")[0], {within: 15_000, until: value => Boolean(value)});
+ const cancel = () => evaluateOnSurface(app, browserScript(transfer => window.__OMNIRUSH_ELECTRON__.invokeDesktop("__cancelTransfer", transfer), [transferId]));
+ const active = await cancel();
+ await execute("xdotool", ["windowfocus", "--sync", windowId]);
+ await execute("xdotool", ["key", "--clearmodifiers", "Escape"]);
+ return {active, outcome: await pending, stillActive: await cancel()};
+ },
+ async runtimeWitness() {
+ return evaluateOnSurface(app, async () => {
+ const bridge = window.__OMNIRUSH_ELECTRON__;
+ const info = await bridge.invokeDesktop("omnirushServerInfo");
+ // Normal desktop bootstrap stores its own embedded server URL here.
+ return {protocol: location.protocol, bridge: typeof bridge.invokeDesktop === "function", embeddedServerSelected: localStorage.getItem("omnirush.server.urlOverride") === info.baseUrl};
+ });
+ },
+ prepareDownload() {
+ if (!packaged) return;
+ if (process.platform !== "linux") throw new Error("The packaged native save-dialog driver currently requires Linux/xdotool");
+ dialogTask = (async () => {
+ const windowId = await eventually(async () => (await execute("xdotool", ["search", "--onlyvisible", "--name", "Save private Claude session"], {timeout: 2000})).stdout.trim().split("\n")[0], {within: 180_000, until: value => Boolean(value)});
+ await execute("xdotool", ["windowfocus", "--sync", windowId]);
+ await execute("xdotool", ["key", "--clearmodifiers", "ctrl+l"]);
+ await execute("xdotool", ["key", "--clearmodifiers", "ctrl+a"]);
+ await execute("xdotool", ["type", "--clearmodifiers", "--delay", "1", path.join(root, "desktop-download.zip")]);
+ await execute("xdotool", ["key", "--clearmodifiers", "alt+s"]);
+ })();
+ void dialogTask.catch(() => undefined);
+ },
+ async downloaded() {
+ await dialogTask;
+ if (!packaged) return null;
+ return eventually(async () => (await fs.stat(path.join(root, "desktop-download.zip"))).size, {within: 30_000, until: bytes => bytes > 0});
+ },
+ async layout() {
+ return evaluateOnSurface(app, () => {
+ const conversation = document.querySelector('[aria-label="Claude conversation"]');
+ const composer = document.querySelector('textarea[aria-label="Message Claude"]');
+ if (!conversation || !composer || !conversation.lastElementChild) throw new Error("Conversation layout unavailable");
+ return {composerTop: composer.getBoundingClientRect().top, conversationBottom: conversation.getBoundingClientRect().bottom, lastMessageBottom: conversation.lastElementChild.getBoundingClientRect().bottom};
+ });
+ },
+ async desktopExport(id: string) {
+ return downloadClaudeArchive({url: `${ready.baseUrl}/workspace/${ready.workspaceId}/claude/sessions/${id}/export`, headers: {authorization: `Bearer ${ready.token}`}}, {
+ localServerUrl: ready.baseUrl, allowedUrlPrefixes: [], stagingDir: path.join(root, "desktop-transfers"), fetcher: fetch,
+ chooseDestination: async (filename: string) => path.join(root, filename),
+ });
+ },
+ async session() { return (await request("sessions")).body[0]; },
+ async witness() { return (await fetch(`${ready.gateway}/witness`)).json(); },
+ async access(enabled: boolean) { await fetch(`${ready.gateway}/control`, {method: "POST", body: JSON.stringify({access: enabled})}); },
+ async control(body: Record<string, unknown>) { await fetch(`${ready.gateway}/control`, {method: "POST", body: JSON.stringify(body)}); },
+ async switchToEmptyWorkspace() {
+ if (!packaged) throw new Error("The workspace navigation witness requires the packaged desktop");
+ const folderPath = path.join(root, "other-project"); await fs.mkdir(folderPath);
+ await evaluateOnSurface(app, browserScript(async folder => {
+ const bridge = window.__OMNIRUSH_ELECTRON__;
+ const info = await bridge.invokeDesktop("omnirushServerInfo");
+ const response = await fetch(`${info.baseUrl}/workspaces/local`, {method: "POST", headers: {authorization: `Bearer ${info.ownerToken}`, "content-type": "application/json"}, body: JSON.stringify({folderPath: folder, name: "Other Claude project", preset: "starter"})});
+ if (!response.ok) throw new Error(`Second workspace registration failed: ${response.status}`);
+ const state = await response.json();
+ const workspace = state.workspaces.find((entry: {path: string; id: string}) => entry.path === folder);
+ if (!workspace) throw new Error("Second workspace was not created");
+ await bridge.invokeDesktop("workspaceSetSelected", workspace.id);
+ await bridge.invokeDesktop("workspaceSetRuntimeActive", workspace.id);
+ location.hash = `/workspace/${workspace.id}/claude`;
+ }, [folderPath]));
+ },
+ async exportReceipt(id: string) {
+ const response = await fetch(`${ready.baseUrl}/workspace/${ready.workspaceId}/claude/sessions/${id}/export`, {method: "POST", headers: {authorization: `Bearer ${ready.token}`}});
+ let bytes = 0;
+ const reader = response.body?.getReader();
+ if (reader) try { while (true) { const chunk = await reader.read(); if (chunk.done) break; bytes += chunk.value.byteLength; } }
+ finally { reader.releaseLock(); }
+ return {status: response.status, bytes};
+ },
+ async mutateSession(id: string, mutation: "model" | "legacy") {
+ for (const owner of await fs.readdir(path.join(root, "claude-sessions"))) {
+ const file = path.join(root, "claude-sessions", owner, id, "session.json");
+ const raw = await fs.readFile(file, "utf8").catch(() => null); if (!raw) continue;
+ const state = JSON.parse(raw);
+ if (mutation === "model") state.model = "claude-haiku-4-5-20251001";
+ else delete state.contract;
+ await fs.writeFile(file, JSON.stringify(state, null, 2));
+ return async () => { await fs.writeFile(file, raw); };
+ }
+ throw new Error("Session metadata unavailable");
+ },
+ async nativeEvidence(id: string) {
+ const owners = await fs.readdir(path.join(root, "claude-sessions"));
+ for (const owner of owners) {
+ const dir = path.join(root, "claude-sessions", owner, id);
+ try {
+ const manifest = JSON.parse(await fs.readFile(path.join(dir, "native", "manifest.json"), "utf8"));
+ const state = JSON.parse(await fs.readFile(path.join(dir, "session.json"), "utf8"));
+ const replay = JSON.parse(await fs.readFile(path.join(dir, "replay.json"), "utf8"));
+ const readWitnesses = (await fs.readFile(path.join(dir, "transport", "hooks.jsonl"), "utf8")).split("\n").filter(Boolean).map(line => JSON.parse(line)).filter(event => event.witness?.sha256);
+ const modelRequests = (await fs.readFile(path.join(dir, "policy", "model-requests.jsonl"), "utf8")).split("\n").filter(Boolean).map(line => JSON.parse(line));
+ const bundle = await fs.stat(path.join(dir, `${id}.zip`)).catch(() => null);
+ return {manifest, state, replay, readWitnesses, modelRequests, zipBytes: bundle?.size ?? 0};
+ } catch { /* owner directory not this session */ }
+ }
+ throw new Error("Complete session evidence unavailable");
+ },
+ async [Symbol.asyncDispose]() {
+ await fs.writeFile(path.join(root, "fixture-witness.json"), JSON.stringify(await (await fetch(`${ready.gateway}/witness`)).json(), null, 2)).catch(() => {});
+ await app[Symbol.asyncDispose](); lab.kill("SIGTERM");
+ if (vite?.pid) try { process.kill(-vite.pid, "SIGTERM"); } catch { /* already stopped */ }
+ await log.close(); await viteLog.close();
+ // Evidence remains in the isolated root for debugging a failing journey.
+ },
+ };
+}
diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.ts
index 63e0bed6..7726d6b3 100644
--- a/packages/types/src/desktop-ipc.ts
+++ b/packages/types/src/desktop-ipc.ts
@@ -1196,6 +1196,7 @@ export type DesktopCommandMap = {
__fetch: { args: [url: string, init?: DesktopFetchInit]; result: DesktopFetchResult };
__uploadMultipart: { args: [input: DesktopMultipartUploadInput]; result: DesktopFetchResult };
__downloadBinary: { args: [input: DesktopBinaryDownloadInput]; result: DesktopBinaryDownloadResult };
+ __downloadClaudeArchive: { args: [input: {transferId: string; url: string; headers?: Record<string, string>}]; result: DesktopBinaryDownloadResult | null };
__cancelTransfer: { args: [transferId: string]; result: boolean };
__homeDir: { args: []; result: string };
__joinPath: { args: [...segments: string[]]; result: string };
diff --git a/scripts/sync-claude-capture.mjs b/scripts/sync-claude-capture.mjs
new file mode 100644
index 00000000..6cf69717
--- /dev/null
+++ b/scripts/sync-claude-capture.mjs
@@ -0,0 +1,29 @@
+#!/usr/bin/env node
+// The GUI and CLI consume the same dependency-free native evidence collector.
+// Usage: node scripts/sync-claude-capture.mjs /path/to/omnirush-cli [--check]
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { createHash } from "node:crypto";
+
+const [cli, flag] = process.argv.slice(2);
+if (!cli || (flag && flag !== "--check")) throw new Error("Expected CLI checkout and optional --check");
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const adapterPath = path.join(root, "apps/server/src/claude-code/replay-adapter.ts");
+const adapter = `// Generated from tools/claude-native/verify.py by scripts/sync-claude-capture.mjs.\nexport const REPLAY_ADAPTER = ${JSON.stringify(fs.readFileSync(path.join(root, "tools/claude-native/verify.py"), "utf8"))};\n`;
+if (flag === "--check") {
+ if (fs.readFileSync(adapterPath, "utf8") !== adapter) throw new Error("Replay adapter changed; regenerate with sync-claude-capture.mjs");
+} else fs.writeFileSync(adapterPath, adapter);
+if (JSON.parse(fs.readFileSync(path.join(cli, "package.json"), "utf8")).name !== "omnirush") throw new Error("Destination is not the CLI checkout");
+for (const name of ["native-capture.ts", "runtime.ts", "access.ts", "bundle-manifest.ts", "transfer.ts", "sandbox-assets.ts", "sandbox-lock.ts", "zip.ts", "upload.ts", "replay-adapter.ts"]) {
+const source = path.join(root, "apps/server/src/claude-code", name);
+const target = path.join(path.resolve(cli), "src/claude-code", name);
+const bytes = fs.readFileSync(source);
+if (flag === "--check") {
+ if (!fs.readFileSync(target).equals(bytes)) throw new Error("CLI native collector differs; run sync-claude-capture.mjs");
+} else {
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, bytes);
+}
+console.log(`${flag === "--check" ? "verified" : "synced"} ${name} ${createHash("sha256").update(bytes).digest("hex")}`);
+}
diff --git a/tools/claude-native/verify.py b/tools/claude-native/verify.py
new file mode 100644
index 00000000..38b6d7d9
--- /dev/null
+++ b/tools/claude-native/verify.py
@@ -0,0 +1,689 @@
+#!/usr/bin/env python3
+"""Private native-Claude ingress for omniconv's recorded-tool replay engine.
+
+Run on an isolated conversion worker with the reviewed omniconv checkout on
+PYTHONPATH. Never run uploaded code on the worker host. Original Claude JSONL
+is authoritative; calls.json is a derived verifier input, not an OpenCode trace.
+This verifies tool replay and selected filesystem scopes, not model inference
+or approval to distribute unmasked data.
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import tarfile
+import tempfile
+import time
+import uuid
+import zipfile
+from datetime import datetime
+from contextlib import contextmanager
+
+
+def sha(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def file_digest(path):
+ digest, size = hashlib.sha256(), 0
+ with path.open('rb') as source:
+ for chunk in iter(lambda: source.read(1024 * 1024), b''):
+ digest.update(chunk)
+ size += len(chunk)
+ return {'sha256': digest.hexdigest(), 'bytes': size}
+
+
+def evidence_members(manifest):
+ """Every preserved generation participates in integrity and execution checks."""
+ for item in manifest['files']:
+ yield item['path'], item
+ for item in manifest.get('history', []):
+ generation = item['generation']
+ if type(generation) is not int or generation < 0:
+ raise ValueError('Invalid evidence generation')
+ yield f"history/{generation}/{item['path']}", item
+
+
+def jsonl(bundle, name):
+ data = bundle.read(name)
+ if data and not data.endswith(b'\n'):
+ raise ValueError('Truncated native evidence: ' + name)
+ for line in data.decode('utf-8', errors='strict').splitlines():
+ if not line.strip():
+ continue
+ value = json.loads(line)
+ if not isinstance(value, dict):
+ raise ValueError('Native record must be an object: ' + name)
+ yield value
+
+
+def semantic_gaps(bundle, manifest):
+ """Recompute admission from bytes, not a client-supplied quality verdict."""
+ records = {'user', 'assistant', 'system', 'attachment', 'progress', 'queue-operation', 'last-prompt', 'atis-latch',
+ 'cost-state', 'mode', 'summary', 'file-history-snapshot', 'custom-title', 'agent-name', 'agent-color',
+ 'tag', 'pr-link', 'api-request', 'api-request-blob', 'api-request-shape'}
+ blocks = {'text', 'image', 'document', 'tool_use', 'tool_result', 'thinking', 'redacted_thinking'}
+ unknown_records, unknown_blocks = set(), set()
+ for name, item in evidence_members(manifest):
+ if not item['path'].startswith('claude/projects/') or not name.endswith('.jsonl'):
+ continue
+ for event in jsonl(bundle, name):
+ kind = event.get('type') if isinstance(event.get('type'), str) else '<missing>'
+ if kind not in records:
+ unknown_records.add(kind)
+ if kind not in ('user', 'assistant'):
+ continue
+ message = event.get('message')
+ content = message.get('content') if isinstance(message, dict) else None
+ if isinstance(content, str):
+ continue
+ if not isinstance(content, list):
+ unknown_blocks.add('<invalid-content>')
+ continue
+ for block in content:
+ kind = block.get('type') if isinstance(block, dict) and isinstance(block.get('type'), str) else '<missing>'
+ if kind not in blocks:
+ unknown_blocks.add(kind)
+ return {'unknown_record_types': sorted(unknown_records), 'unknown_block_types': sorted(unknown_blocks)}
+
+
+def model_evidence(bundle, session):
+ """A separate quality check: tool replay cannot prove model provenance."""
+ result = {'status': 'unknown', 'scope': 'managed-inference',
+ 'identity_basis': 'provider-response-body', 'initial_workspace_provenance': 'user-supplied-unattested',
+ 'eligible': False, 'blockers': []}
+ contract, isolation = session.get('contract'), session.get('modelIsolation')
+ if not isinstance(contract, dict) or not isinstance(isolation, dict):
+ return {**result, 'status': 'legacy_unverified', 'blockers': ['model_contract_or_journal_missing']}
+ try:
+ saved = json.loads(bundle.read('policy/contract.json'))
+ contract_bytes = json.dumps(contract, ensure_ascii=False, separators=(',', ':')).encode()
+ expected = session.get('contractSha256')
+ valid = (saved.get('contract') == contract and saved.get('sha256') == expected and sha(contract_bytes) == expected
+ and contract.get('schema') == 1 and contract.get('sessionId') == session['id']
+ and contract.get('owner') == session['owner'] and contract.get('workspaceId') == session['workspaceId']
+ and contract.get('model') == session['model']
+ and contract.get('execution', {}).get('baseImage') == session['base']['image']
+ and contract.get('execution', {}).get('kind') == 'docker'
+ and contract.get('execution', {}).get('os') == 'linux'
+ and contract.get('execution', {}).get('shell') == '/bin/bash'
+ and contract.get('execution', {}).get('workingDirectory') == '/workspace'
+ and contract.get('harness', {}).get('name') == 'claude-code'
+ and contract.get('harness', {}).get('sdkVersion') == session.get('sdkVersion')
+ and contract.get('harness', {}).get('claudeVersion') == session.get('claudeVersion')
+ and contract.get('capture', {}).get('scope') == 'managed-inference'
+ and contract.get('capture', {}).get('modelIsolation') == 'exact')
+ if not valid:
+ return {**result, 'status': 'invalid', 'blockers': ['model_contract_integrity_mismatch']}
+ raw = bundle.read('policy/model-requests.jsonl')
+ resolved = isolation.get('resolvedModel')
+ if not isinstance(resolved, str) or not resolved or session.get('authorization', {}).get('upstreamModel') != resolved:
+ return {**result, 'blockers': ['bound_upstream_model_missing']}
+ if resolved != session['model']:
+ return {**result, 'status': 'invalid', 'blockers': ['bound_upstream_model_mismatch']}
+ result['catalog_model'], result['resolved_upstream_model'] = session['model'], resolved
+ result['contract_sha256'] = expected
+ result['journal'] = {'sha256': sha(raw), 'bytes': len(raw)}
+ if sha(raw) != isolation.get('evidenceSha256') or len(raw) != isolation.get('evidenceBytes'):
+ return {**result, 'status': 'invalid', 'blockers': ['model_journal_integrity_mismatch']}
+ requests, responses, identities = {}, {}, {}
+ problems = set()
+ for event in jsonl(bundle, 'policy/model-requests.jsonl'):
+ if event.get('schema') != 1 or event.get('sessionId') != session['id']:
+ problems.add('model_event_identity_mismatch')
+ request_id = event.get('requestId')
+ if not isinstance(request_id, str) or not request_id:
+ problems.add('model_request_identity_missing')
+ continue
+ kind = event.get('type')
+ if kind == 'request':
+ if request_id in requests:
+ problems.add('duplicate_model_request')
+ requests[request_id] = event
+ if event.get('requestedModel') != session['model'] or event.get('resolvedModel') != resolved or event.get('contractSha256') != expected:
+ problems.add('requested_model_mismatch')
+ if event.get('route') not in ('messages', 'count_tokens'):
+ problems.add('unknown_model_route')
+ elif kind == 'response':
+ if request_id in responses:
+ problems.add('duplicate_model_response')
+ responses[request_id] = event
+ elif kind == 'provider_identity':
+ identities.setdefault(request_id, set()).add(event.get('providerModel'))
+ if event.get('providerModel') != resolved or event.get('requestedModel') != session['model'] or event.get('resolvedModel') != resolved or event.get('source') != 'response-body':
+ problems.add('observed_model_mismatch')
+ elif kind == 'rejected':
+ problems.add('rejected_model_request')
+ else:
+ problems.add('unknown_model_event')
+ if set(requests) != set(responses) or set(identities) - set(requests):
+ problems.add('model_journal_incomplete')
+ completed = 0
+ for request_id, request in requests.items():
+ if request.get('route') != 'messages':
+ continue
+ response = responses.get(request_id, {})
+ status = response.get('status')
+ if type(status) is int and status >= 400:
+ # Failed upstream attempts remain in evidence. They do not
+ # establish another model or count as completed inference.
+ if response.get('providerModels') or identities.get(request_id):
+ problems.add('model_identity_on_failed_response')
+ continue
+ if type(status) is not int or not 200 <= status < 300 or response.get('completed') is not True or response.get('streamComplete') is not True:
+ problems.add('inference_response_incomplete')
+ if response.get('identity') != 'reported' or response.get('providerModels') != [resolved] or identities.get(request_id) != {resolved}:
+ problems.add('inference_identity_missing_or_mixed')
+ completed += 1
+ if not completed:
+ problems.add('no_completed_model_inference')
+ if isolation.get('status') != 'observed' or isolation.get('expectedModel') != session['model'] or isolation.get('observedModels') != [resolved]:
+ problems.add('model_summary_not_observed')
+ invalid = bool(problems & {'model_event_identity_mismatch', 'requested_model_mismatch', 'observed_model_mismatch', 'rejected_model_request'})
+ result.update(status='invalid' if invalid else 'unknown' if problems else 'observed', eligible=not problems,
+ completed_inference_requests=completed, blockers=sorted(problems))
+ return result
+ except (KeyError, ValueError, TypeError, AttributeError, UnicodeDecodeError):
+ return {**result, 'status': 'unknown', 'blockers': ['model_evidence_unreadable']}
+
+
+def stamp(value):
+ return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp() * 1000
+
+
+def docker(*args, timeout=180):
+ result = subprocess.run(['docker', *args], capture_output=True, timeout=timeout)
+ if result.returncode:
+ raise RuntimeError('Docker operation failed: ' + result.stderr.decode(errors='replace')[-1000:])
+ return result.stdout.decode().strip()
+
+
+def write(path, value):
+ path.write_text(json.dumps(value, indent=2) + '\n')
+ path.chmod(0o600)
+
+
+@contextmanager
+def record_failure(path, report):
+ try:
+ yield
+ except Exception as error:
+ report.update(status='UNVERIFIED', strict_verified=False,
+ failure={'type': type(error).__name__, 'message': str(error)})
+ write(path, report)
+ raise
+
+
+def text_content(content):
+ if isinstance(content, str):
+ return content
+ return '\n'.join(block.get('text', '') for block in content or [] if block.get('type') == 'text')
+
+
+def agent_model_omission(bundle, session, manifest, call, result, stop):
+ """Corroborate one reviewed SDK transform; retain the discrepancy as SOFT.
+
+ SDK 0.3.306 / Claude 2.1.306's Agent schema omits model when
+ CLAUDE_CODE_SUBAGENT_MODEL_FORCE is set. Its executor safeParse strips that
+ field before hooks. This controller hash pins the reviewed force setting
+ and unchanged hook callback. It is applicability evidence, not attestation.
+ """
+ def reject():
+ raise ValueError('Uncorroborated native Agent model omission: ' + call['id'])
+
+ controller = session.get('contract', {}).get('harness', {}).get('controllerSha256')
+ if (session.get('sdkVersion'), session.get('claudeVersion'), controller) != (
+ '0.3.306', '2.1.306', 'fd1d3a901953f38fc866d6ce62ec5f80ef247f878d029ae47bb581832b26ab00'):
+ reject()
+ if not model_evidence(bundle, session)['eligible']:
+ reject()
+ native = result['native']
+ if (result['block'].get('is_error') or not isinstance(native, dict)
+ or not isinstance(native.get('agentId'), str) or not native['agentId']
+ or native.get('status') not in ('async_launched', 'completed')
+ or native.get('resolvedModel') != session['model']
+ or stop['input'].get('hook_event_name') != 'PostToolUse'
+ or stop['input'].get('tool_response') != native):
+ reject()
+ member = 'events/sdk.jsonl'
+ entries = [item for item in manifest['files'] if item['path'] == member]
+ if len(entries) != 1 or member not in bundle.namelist():
+ reject()
+ raw = bundle.read(member)
+ if entries[0].get('sha256') != sha(raw) or entries[0].get('bytes') != len(raw):
+ reject()
+ # Validate framing and JSON before inspecting physical line witnesses.
+ list(jsonl(bundle, member))
+ witnesses = {'requested': [], 'result': [], 'child': []}
+ for number, line in enumerate(raw.splitlines(), 1):
+ if not line.strip():
+ continue
+ event = json.loads(line)
+ message = event.get('message', {})
+ content = message.get('content', [])
+ reference = {'path': member, 'line': number, 'sha256': sha(line), 'uuid': event.get('uuid')}
+ for block in content if isinstance(content, list) else []:
+ if event.get('type') == 'assistant' and block.get('type') == 'tool_use' and block.get('id') == call['id']:
+ if (block.get('name') != call['tool'] or block.get('input') != call['input']
+ or (event.get('agent_id') or event.get('session_id')) != call['session']):
+ reject()
+ witnesses['requested'].append(reference)
+ if event.get('type') == 'user' and block.get('type') == 'tool_result' and block.get('tool_use_id') == call['id']:
+ if block != result['block'] or event.get('tool_use_result') != native:
+ reject()
+ witnesses['result'].append(reference)
+ if event.get('type') == 'assistant' and event.get('parent_tool_use_id') == call['id']:
+ if event.get('agent_id') != native['agentId'] or message.get('model') != session['model']:
+ reject()
+ witnesses['child'].append(reference)
+ if not all(witnesses.values()):
+ reject()
+ return {'kind': 'sdk_agent_model_omission', 'strict_verified': False,
+ 'requested_input': call['input'], 'effective_input': call['native_effective_input'],
+ 'resolved_model': native['resolvedModel'], 'controller_sha256': controller,
+ 'sdk_witnesses': witnesses, 'model_journal_sha256': session['modelIsolation']['evidenceSha256']}
+
+
+def calls_from(bundle, session, manifest):
+ hooks = list(jsonl(bundle, 'events/hooks.jsonl'))
+ starts, stops = {}, {}
+ for event in hooks:
+ item = event['input']
+ if item.get('hook_event_name') == 'PreToolUse':
+ key = item['tool_use_id']
+ if key in starts:
+ raise ValueError('Ambiguous repeated tool execution: ' + key)
+ starts[key] = event
+ elif item.get('hook_event_name') in ('PostToolUse', 'PostToolUseFailure'):
+ key = item['tool_use_id']
+ if key in stops:
+ raise ValueError('Ambiguous repeated tool completion: ' + key)
+ stops[key] = event
+ calls, results = {}, {}
+ for name, file in evidence_members(manifest):
+ if not file['path'].startswith('claude/projects/') or not file['path'].endswith('.jsonl'):
+ continue
+ for event in jsonl(bundle, name):
+ if event.get('type') not in ('assistant', 'user'):
+ continue # Request-cache blobs repeat context; they are not executions.
+ content = event.get('message', {}).get('content')
+ if not isinstance(content, list):
+ continue
+ for block in content:
+ if block.get('type') == 'tool_use':
+ key = block['id']
+ hook = starts.get(key)
+ if hook is None:
+ raise ValueError('No execution hook for native call: ' + key)
+ item = hook['input']
+ if item['tool_name'] != block['name']:
+ raise ValueError('Native transcript and hook disagree: ' + key)
+ requested, effective = block['input'], item['tool_input']
+ if requested != effective and not (
+ block['name'] == 'Agent' and isinstance(requested, dict) and isinstance(effective, dict)
+ and isinstance(requested.get('model'), str) and requested['model']
+ and {k: v for k, v in requested.items() if k != 'model'} == effective):
+ raise ValueError('Native transcript and hook disagree: ' + key)
+ call = {'id': key, 'tool': block['name'], 'input': block['input'],
+ 'start': stamp(hook['time']), 'turn': hook['turn'],
+ 'session': item.get('agent_id') or event.get('agentId') or session['id'], 'status': 'pending',
+ 'source': {'path': name, 'uuid': event.get('uuid')}, 'native_read_witness': hook.get('witness'),
+ 'native_cwd': item.get('cwd')}
+ if requested != effective:
+ call['native_effective_input'] = effective
+ if key in calls and (calls[key]['tool'], calls[key]['input']) != (call['tool'], call['input']):
+ raise ValueError('Conflicting native call identity: ' + key)
+ if key not in calls:
+ call['sources'] = [call['source']]
+ calls[key] = call
+ elif call['source'] not in calls[key]['sources']:
+ calls[key]['sources'].append(call['source'])
+ elif block.get('type') == 'tool_result':
+ key = block['tool_use_id']
+ value = {'block': block, 'native': event.get('toolUseResult'), 'end': event.get('timestamp')}
+ if key in results and (results[key]['block'], results[key]['native']) != (block, value['native']):
+ raise ValueError('Conflicting native result identity: ' + key)
+ results[key] = value
+ if set(starts) != set(calls):
+ raise ValueError('Execution hooks and native calls do not form a complete set')
+ if set(results) != set(calls):
+ raise ValueError('Native calls and results do not form a complete set')
+ for key, call in calls.items():
+ if key not in results:
+ raise ValueError('Native tool result missing: ' + key)
+ result = results[key]
+ block, native = result['block'], result['native']
+ stop = stops.get(key)
+ if stop is None:
+ raise ValueError('Native tool completion hook missing: ' + key)
+ if stop['turn'] != call['turn'] or stop['input']['tool_name'] != call['tool'] or stop['input']['tool_input'] != call.get('native_effective_input', call['input']):
+ raise ValueError('Native tool completion hook disagrees: ' + key)
+ if 'native_effective_input' in call:
+ call['native_input_normalization'] = agent_model_omission(bundle, session, manifest, call, result, stop)
+ call.update(status='error' if block.get('is_error') else 'completed',
+ output=text_content(block.get('content')), end=stamp(stop['time']))
+ if call['end'] < call['start']:
+ raise ValueError('Native execution interval runs backwards: ' + key)
+ call['meta'] = {'native_tool_result': native}
+ if isinstance(native, dict):
+ if native.get('agentId'):
+ call['meta']['child_session_id'] = native['agentId']
+ # Structured stdout/stderr avoid comparing Claude's no-output UI
+ # placeholder as if it were bytes printed by the user's command.
+ if call['tool'] == 'Bash' and isinstance(native.get('stdout'), str) and isinstance(native.get('stderr'), str):
+ call['output'] = native['stdout'] + native['stderr']
+ if native.get('type') == 'file_unchanged':
+ # This SDK optimization contains no read bytes. It cannot prove
+ # that a replayed read matched; never invent bytes from after.
+ call['native_file_unchanged'] = True
+ return sorted(calls.values(), key=lambda call: (call['start'], call['id']))
+
+
+def native_bash(verify, ctr, call, state):
+ """Replay the recorded command without the generic converter's shell fixes.
+
+ Claude's Bash result does not expose its numeric exit or actual shell argv.
+ Command/cwd are evidence; /bin/bash -lc is a declared reproduction recipe.
+ Therefore even matching stdout and success are SOFT, never strict proof.
+ """
+ inp, native = call['input'], call['meta']['native_tool_result']
+ cmd, cwd = inp.get('command'), call.get('native_cwd')
+ if not isinstance(cmd, str) or not cmd.strip():
+ return {'outcome': 'not_replayable', 'reason': 'native_command_missing'}
+ if not isinstance(cwd, str) or not cwd.startswith('/') or '\0' in cwd:
+ return {'outcome': 'not_replayable', 'reason': 'native_cwd_missing'}
+ if not isinstance(native, dict) or not all(isinstance(native.get(k), str) for k in ('stdout', 'stderr')):
+ return {'outcome': 'no_evidence', 'why': 'native Bash stdout/stderr are missing'}
+ if native.get('interrupted') or inp.get('run_in_background') or native.get('backgroundTaskId'):
+ return {'outcome': 'not_replayable', 'reason': 'native_background_or_interrupted'}
+ if any(native.get(key) for key in ('truncated', 'truncation', 'fullOutputPath', 'outputFile', 'isImage')):
+ return {'outcome': 'not_replayable', 'reason': 'native_output_not_text_complete'}
+ if verify.classify(cmd) in ('skipped_side_effect', 'server'):
+ return {'outcome': 'not_replayable', 'reason': 'native_external_effect_or_server'}
+ state.setdefault('commands', []).append(cmd)
+ timeout_ms = inp.get('timeout', 120000)
+ if type(timeout_ms) is not int or timeout_ms < 1 or timeout_ms > 600000:
+ return {'outcome': 'not_replayable', 'reason': 'native_timeout_unsupported'}
+ argv = ['docker', 'exec', '-w', cwd, ctr, 'timeout', str(timeout_ms / 1000), '/bin/bash', '-lc', cmd]
+ began = time.monotonic()
+ try:
+ result = subprocess.run(argv, capture_output=True, timeout=timeout_ms / 1000 + 30)
+ except subprocess.TimeoutExpired:
+ return {'outcome': 'harness_error', 'reason': 'native_command_timeout'}
+ stdout, stderr = result.stdout.decode(errors='replace'), result.stderr.decode(errors='replace')
+ rec = {'recorded_command_sha256': sha(cmd.encode()), 'cwd': cwd, 'shell_recipe': ['/bin/bash', '-lc'],
+ 'actual_shell_argv_observed': False, 'numeric_recorded_exit': None, 'replay_exit': result.returncode,
+ 'recorded_stdout_sha256': sha(native['stdout'].encode()), 'recorded_stderr_sha256': sha(native['stderr'].encode()),
+ 'replay_stdout_sha256': sha(result.stdout), 'replay_stderr_sha256': sha(result.stderr),
+ 'seconds': round(time.monotonic() - began, 3)}
+ if result.returncode == 124:
+ return {**rec, 'outcome': 'harness_error', 'reason': 'native_command_timeout'}
+ if (result.returncode != 0) != (call['status'] == 'error'):
+ return {**rec, 'outcome': 'diverge', 'why': 'native Bash success/failure differs'}
+ exact = stdout == native['stdout'] and stderr == native['stderr']
+ # SDK output formatting can strip final newlines. Show that difference,
+ # with separate raw hashes; never silently count it as an exact match.
+ formatted = stdout.rstrip('\n') == native['stdout'].rstrip('\n') and stderr.rstrip('\n') == native['stderr'].rstrip('\n')
+ if not exact and not formatted:
+ return {**rec, 'outcome': 'diverge-soft', 'why': 'native Bash output differs; shell invocation is unobserved', 'output_exact': False, 'output': {'stdout': stdout, 'stderr': stderr}}
+ return {**rec, 'outcome': 'diverge-soft', 'why': 'native Bash actual shell argv and numeric exit are unobserved',
+ 'output_exact': exact, 'output_diff': None if exact else 'trailing_newlines'}
+
+
+NATIVE_EDIT = r'''
+import hashlib, json, os, sys
+request = json.load(sys.stdin)
+tool, inp = request['tool'], request['input']
+name = inp['file_path']
+try:
+ with open(name, 'rb') as source:
+ original = source.read()
+except FileNotFoundError:
+ original = None
+if tool == 'Write':
+ result = inp['content'].encode('utf-8')
+elif tool == 'Edit':
+ if original is None:
+ raise ValueError('native_edit_file_missing')
+ old, new = inp['old_string'].encode('utf-8'), inp['new_string'].encode('utf-8')
+ if not old:
+ raise ValueError('native_empty_edit_unsupported')
+ count = original.count(old)
+ if not count or (count != 1 and not inp.get('replace_all', False)):
+ raise ValueError('native_edit_exact_match_missing_or_ambiguous')
+ result = original.replace(old, new, -1 if inp.get('replace_all', False) else 1)
+else:
+ raise ValueError('unsupported_native_edit')
+os.makedirs(os.path.dirname(os.path.abspath(name)), exist_ok=True)
+with open(name, 'wb') as target:
+ target.write(result)
+ target.flush()
+ os.fsync(target.fileno())
+print(json.dumps({'before_sha256': hashlib.sha256(original).hexdigest() if original is not None else None,
+ 'after_sha256': hashlib.sha256(result).hexdigest(), 'bytes': len(result)}))
+'''
+
+
+def native_edit(ctr, call, state):
+ """Apply literal native input; no redaction repair or whitespace matching."""
+ inp, cwd = call['input'], call.get('native_cwd')
+ if call['status'] != 'completed':
+ return {'outcome': 'not_replayable', 'reason': 'native_failed_edit_semantics'}
+ if not isinstance(cwd, str) or not cwd.startswith('/') or not isinstance(inp.get('file_path'), str):
+ return {'outcome': 'not_replayable', 'reason': 'native_edit_path_missing'}
+ fields = ('content',) if call['tool'] == 'Write' else ('old_string', 'new_string')
+ if not all(isinstance(inp.get(key), str) for key in fields):
+ return {'outcome': 'not_replayable', 'reason': 'native_edit_input_missing'}
+ payload = json.dumps({'tool': call['tool'], 'input': inp}).encode()
+ result = subprocess.run(['docker', 'exec', '-i', '-w', cwd, ctr, 'python3', '-c', NATIVE_EDIT],
+ input=payload, capture_output=True, timeout=60)
+ if result.returncode:
+ return {'outcome': 'diverge', 'why': 'native literal edit could not be applied', 'path': inp['file_path']}
+ state.setdefault('touched', set()).add(inp['file_path'])
+ return {'outcome': 'match', 'path': inp['file_path'], 'literal_input': True, **json.loads(result.stdout)}
+
+
+def replay_verdict(replay, differences, selected):
+ """Admission cannot inherit a permissive generic-verifier success label."""
+ pairs = replay.get('per_call', [])
+ if len(pairs) != len(selected) or {pair[0] for pair in pairs} != {call['id'] for call in selected}:
+ return 'UNVERIFIED', False, ['execution_coverage_incomplete']
+ outcomes = [pair[1].split(':', 1)[0] for pair in pairs]
+ if any(differences.values()) or 'diverge' in outcomes:
+ return 'DIFFERS', False, ['filesystem_or_tool_result_differs']
+ allowed = {'match', 'diverge-soft', 'subagent'}
+ blocked = sorted(set(outcomes) - allowed)
+ if blocked:
+ return ('TOOLS_RAN' if set(blocked) == {'tool-worked'} else 'UNVERIFIED'), False, blocked
+ if not outcomes or all(outcome == 'subagent' for outcome in outcomes):
+ return 'UNVERIFIED', False, ['no_tool_result_compared']
+ soft = ('diverge-soft' in outcomes or bool(replay.get('matches_leaning_on'))
+ or any(call.get('native_input_normalization') for call in selected))
+ return ('VERIFIED_WITH_SOFT_DIFFS' if soft else 'VERIFIED'), True, []
+
+
+def tree(container, scope):
+ proc = subprocess.Popen(['docker', 'cp', container + ':' + scope, '-'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ output = {}
+ try:
+ with tarfile.open(fileobj=proc.stdout, mode='r|') as archive:
+ for member in archive:
+ record = {'mode': member.mode, 'type': member.type.decode('ascii'), 'link': member.linkname,
+ 'uid': member.uid, 'gid': member.gid}
+ if member.isfile():
+ digest = hashlib.sha256()
+ with archive.extractfile(member) as data:
+ for chunk in iter(lambda: data.read(1024 * 1024), b''):
+ digest.update(chunk)
+ record.update(sha256=digest.hexdigest(), bytes=member.size)
+ if member.name in output:
+ raise ValueError('Ambiguous filesystem archive member')
+ output[member.name] = record
+ if proc.wait(timeout=30):
+ raise RuntimeError('Cannot inspect replay filesystem')
+ return output
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+ proc.communicate()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('zip', type=Path)
+ parser.add_argument('--out', required=True, type=Path)
+ parser.add_argument('--check-path', action='append', default=[], help='Additional absolute filesystem scope to compare after every turn')
+ args = parser.parse_args()
+ from omniconv import verify
+ original_replay = verify.replay_one
+ def replay_native(ctr, root, call, index, calls, state, context):
+ if call['tool'] == 'Bash':
+ return native_bash(verify, ctr, call, state)
+ if call['tool'] in ('Write', 'Edit'):
+ return native_edit(ctr, call, state)
+ if not call.get('native_file_unchanged') and not (call['tool'] == 'Read' and call.get('native_read_witness')):
+ # Absolute native paths pass unchanged. Relative paths resolve from
+ # the recorded hook cwd, never a guessed root or a repaired cwd.
+ cwd = call.get('native_cwd')
+ if not isinstance(cwd, str) or not cwd.startswith('/'):
+ return {'outcome': 'not_replayable', 'reason': 'native_cwd_missing'}
+ kind = verify.RT.kind_of(call['tool'])[0]
+ if kind == 'shell':
+ return {'outcome': 'not_replayable', 'reason': 'unsupported_native_shell'}
+ if kind == 'edit':
+ return {'outcome': 'not_replayable', 'reason': 'unsupported_native_edit'}
+ return original_replay(ctr, cwd, call, index, calls, state, context)
+ witness = call.get('native_read_witness')
+ if call['status'] != 'completed':
+ return {'outcome': 'not_replayable', 'reason': 'native_failed_read_semantics'}
+ if not witness or witness.get('path') != call['input'].get('file_path') or not re.fullmatch(r'[a-f0-9]{64}', str(witness.get('sha256', ''))):
+ return {'outcome': 'not_replayable', 'reason': 'native_cached_read_without_witness'}
+ script = "import hashlib,json,os,stat,sys\np=sys.argv[1];s=os.stat(p)\nassert stat.S_ISREG(s.st_mode)\nh=hashlib.sha256()\nwith open(p,'rb') as f:\n for b in iter(lambda:f.read(1048576),b''):h.update(b)\nprint(json.dumps({'sha256':h.hexdigest(),'bytes':s.st_size,'mode':s.st_mode}))"
+ code, output, _ = verify.sh(['docker', 'exec', ctr, 'python3', '-c', script, witness['path']], 60)
+ actual = json.loads(output) if code == 0 and output.strip() else None
+ expected = {key: witness.get(key) for key in ('sha256', 'bytes', 'mode')}
+ return {'outcome': 'match' if actual == expected else 'diverge',
+ 'why': 'native cached read checked against the pre-tool byte witness',
+ 'recorded_witness': expected, 'replay_witness': actual, 'path': witness['path']}
+ verify.replay_one = replay_native
+ os.umask(0o077)
+ args.out.mkdir(parents=True, exist_ok=False)
+ scopes = ['/workspace', *args.check_path]
+ if any(not scope.startswith('/') or '..' in Path(scope).parts for scope in scopes):
+ raise ValueError('Check paths must be absolute')
+ report = {'schema': 2, 'format': 'claude-code-native', 'verifier': verify.fingerprint(),
+ 'adapter_sha256': sha(Path(__file__).read_bytes()), 'network': 'none',
+ 'input_artifact': file_digest(args.zip),
+ 'filesystem_scopes': scopes, 'private': True, 'delivery_ready': False,
+ 'meaning': 'Recorded tool replay with explicit strict/soft outcomes. Original evidence is never rewritten. Delivery selection is separate.',
+ 'status': 'UNVERIFIED', 'turns': []}
+ write(args.out / 'replay.json', report)
+ with record_failure(args.out / 'replay.json', report), zipfile.ZipFile(args.zip) as bundle:
+ if len(bundle.namelist()) != len(set(bundle.namelist())):
+ raise ValueError('Duplicate ZIP member')
+ session_bytes, manifest_bytes = bundle.read('session.json'), bundle.read('native-manifest.json')
+ session, manifest = json.loads(session_bytes), json.loads(manifest_bytes)
+ report['adapter_source'] = 'external'
+ report['embedded_adapter_sha256'] = sha(bundle.read('verify.py')) if 'verify.py' in bundle.namelist() else None
+ report['embedded_adapter_matches_external'] = report['embedded_adapter_sha256'] == report['adapter_sha256']
+ report['session_sha256'], report['manifest_sha256'] = sha(session_bytes), sha(manifest_bytes)
+ report['model_isolation'] = model_evidence(bundle, session)
+ report['session_id'] = session['id']
+ if manifest['sessionId'] != session['id'] or manifest['status'] != 'complete' or session['capture'] != 'complete':
+ raise ValueError('Incomplete native session cannot pass replay admission')
+ checked = set()
+ for name, item in evidence_members(manifest):
+ if name in checked or '\\' in name or name.startswith('/') or '..' in name.split('/'):
+ raise ValueError('Ambiguous native evidence path')
+ checked.add(name)
+ content = bundle.read(name)
+ if len(content) != item['bytes'] or sha(content) != item['sha256']:
+ raise ValueError('Native evidence integrity failure: ' + name)
+ if 'events/hooks.jsonl' not in checked:
+ raise ValueError('Execution hooks are not covered by the native manifest')
+ report['evidence_generations_checked'] = len(checked)
+ report['semantic_gaps'] = semantic_gaps(bundle, manifest)
+ report['semantic_review_required'] = any(report['semantic_gaps'].values())
+ calls = calls_from(bundle, session, manifest)
+ report['input_normalizations'] = [{'id': call['id'], **call['native_input_normalization']}
+ for call in calls if call.get('native_input_normalization')]
+ if any(call['turn'] not in {turn['number'] for turn in session['turns']} for call in calls):
+ raise ValueError('A native call lies outside the captured turn sequence')
+ write(args.out / 'calls.json', calls)
+ report['calls_artifact'] = file_digest(args.out / 'calls.json')
+ checkpoints = [session['base'], *[turn['after'] for turn in session['turns']]]
+ if not session['turns'] or any(turn['status'] != 'complete' for turn in session['turns']):
+ raise ValueError('Every admitted turn must have completed')
+ if [turn['number'] for turn in session['turns']] != list(range(1, len(session['turns']) + 1)):
+ raise ValueError('Native user turn sequence is incomplete or ambiguous')
+ loaded = set()
+ for cp in checkpoints:
+ if not re.fullmatch(r'sha256:[a-f0-9]{64}', cp['image']):
+ raise ValueError('Invalid image digest')
+ if cp['file'] in loaded:
+ continue
+ if not re.fullmatch(r'images/[a-f0-9]{64}\.tar\.gz', cp['file']):
+ raise ValueError('Invalid image archive path')
+ with tempfile.NamedTemporaryFile(suffix='.tar.gz') as target:
+ digest = hashlib.sha256(); size = 0
+ with bundle.open(cp['file']) as source:
+ for chunk in iter(lambda: source.read(1024 * 1024), b''):
+ digest.update(chunk); size += len(chunk); target.write(chunk)
+ target.flush()
+ if digest.hexdigest() != cp['sha256'] or size != cp['bytes']:
+ raise ValueError('Environment archive integrity failure')
+ docker('load', '--input', target.name, timeout=600)
+ loaded.add(cp['file'])
+ for turn in session['turns']:
+ if turn['number'] < 1 or turn['before']['image'] != checkpoints[turn['number'] - 1]['image']:
+ raise ValueError('Broken before/after environment chain')
+ selected = [call for call in calls if call['turn'] == turn['number']]
+ name = 'omnirush-native-replay-' + uuid.uuid4().hex
+ expected = name + '-expected'
+ try:
+ common = ['--network=none', '--cap-drop=ALL', '--security-opt=no-new-privileges', '--pids-limit=256', '--memory=4g', '--cpus=2']
+ docker('run', '-d', '--name', name, *common, turn['before']['image'], 'sleep', 'infinity')
+ docker('create', '--name', expected, *common, turn['after']['image'])
+ replay = verify.replay_calls(name, '/workspace', selected, context={'main': session['id'], 'sessions': sorted({call['session'] for call in calls})})
+ differences = {}
+ for scope in scopes:
+ actual_tree, expected_tree = tree(name, scope), tree(expected, scope)
+ differences[scope] = [key for key in sorted(set(actual_tree) | set(expected_tree)) if actual_tree.get(key) != expected_tree.get(key)]
+ status, accepted, blockers = replay_verdict(replay, differences, selected)
+ if report['semantic_review_required']:
+ status, accepted = 'UNVERIFIED', False
+ blockers.append('unknown_native_semantics')
+ report['turns'].append({'number': turn['number'], 'before_image': turn['before']['image'], 'after_image': turn['after']['image'],
+ 'calls': len(selected), 'accepted': accepted, 'strict_verified': status == 'VERIFIED',
+ 'status': status, 'blockers': blockers, 'replay': replay, 'filesystem_differences': differences})
+ write(args.out / 'replay.json', report)
+ finally:
+ subprocess.run(['docker', 'rm', '-f', name, expected], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ if file_digest(args.zip) != report['input_artifact']:
+ report.update(status='UNVERIFIED', strict_verified=False, failure={'type': 'input_integrity', 'message': 'Input artifact changed during replay'})
+ write(args.out / 'replay.json', report)
+ raise ValueError('Input artifact changed during replay')
+ if all(turn['accepted'] for turn in report['turns']):
+ report['status'] = 'VERIFIED' if all(turn['strict_verified'] for turn in report['turns']) else 'VERIFIED_WITH_SOFT_DIFFS'
+ elif any(turn['status'] == 'DIFFERS' for turn in report['turns']):
+ report['status'] = 'DIFFERS'
+ elif any(turn['status'] == 'TOOLS_RAN' for turn in report['turns']):
+ report['status'] = 'TOOLS_RAN'
+ report['strict_verified'] = report['status'] == 'VERIFIED'
+ blockers = list(report['model_isolation']['blockers'])
+ if report['status'] not in ('VERIFIED', 'VERIFIED_WITH_SOFT_DIFFS'):
+ blockers.append('tool_replay_not_verified')
+ if report['semantic_review_required']:
+ blockers.append('unknown_native_semantics')
+ report['quality_admission'] = {'eligible': not blockers, 'blockers': blockers,
+ 'retained': True, 'delivery_selection': 'separate'}
+ write(args.out / 'replay.json', report)
+ print(json.dumps({'session_id': report['session_id'], 'status': report['status'], 'turns': len(report['turns']), 'report': str(args.out / 'replay.json')}))
+ return 0 if report['status'] in ('VERIFIED', 'VERIFIED_WITH_SOFT_DIFFS') else 1
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())