Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/skills/verify-open-pstack/scripts/runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ afterEach(async () => { for (const root of roots.splice(0)) await rm(root, { rec
const FAKE_CLAUDE = `#!/usr/bin/env bun
if (process.argv[2] === 'auth') { console.log(JSON.stringify({ loggedIn: true })); process.exit(0); }
await Bun.write('WRITTEN.md', 'PONG\\n');
console.log(JSON.stringify({ result: 'DONE', modelUsage: { 'claude-opus-9': {} } }));
console.log(JSON.stringify({ type: 'result', subtype: 'success', is_error: false, result: 'DONE', modelUsage: { 'claude-opus-9': {} } }));
`;

async function launch(f: Fixture, prompt: string): Promise<string> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ The runner refuses an access mode outside a provider's Access modes cell before
- Host prerequisites: none.
- State paths: the Claude config home (`CLAUDE_CONFIG_DIR`, else `~/.claude`).
- Child environment: read-only: inherited; isolated-write: inherited without `GIT_*`.
- `--verbose` makes Claude emit its event array, so the runner reports `child-failed` when every Bash call fails to start its sandbox (`apply-seccomp:` or `bwrap:`).
- The runner captures Claude's `--output-format stream-json --verbose` events in the private stdout sidecar as they arrive. It reports `child-failed` when every Bash call fails to start its sandbox (`apply-seccomp:` or `bwrap:`).
- The runner passes `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` from the `env` of `settings.json` in the Claude config home only when the shell sets none of `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, or `ANTHROPIC_API_KEY`.
- When the runner uses those settings, it also forwards `apiKeyHelper` if the settings `env` supplies neither `ANTHROPIC_API_KEY` nor `ANTHROPIC_AUTH_TOKEN`.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ Read-only mode maps to Claude plan mode with project-only settings and an explic

Every concurrent external lane needs distinct prompt, output, and receipt paths. The launcher exclusively reserves the output, receipt, and `<receipt>.stdout` / `<receipt>.stderr` sidecars with private (`0600`) permissions and refuses to overwrite existing files. For a provider whose notes name one, it also creates the private `<receipt>.provider/` directory (`0700`) that holds the provider's run-owned config and the file the CLI exports. All these paths must be distinct from each other and the prompt; a failed reservation rolls back only files created by that attempt. Schema-version-1 receipts add nullable `stdoutPath` and `stderrPath` fields identifying reserved artifacts. Sidecars retain the model process's raw stdout/stderr bytes, including on dropouts; they do not include authentication-preflight output. Cancellation and timeout retain every byte captured before the drain stops. Keep these private local files with the receipt; quote only operator-selected excerpts in public evidence.

For Claude, inspect `<receipt>.stdout` for complete JSON lines while the runner is active. A `system` event with subtype `init` shows Claude Code started. Use later event types to observe model activity. Confirm the served model and completion from the final receipt.

## Completion and dropouts

Success requires all of these:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const launchSettings = (args: readonly string[]): unknown =>
JSON.parse(args[args.indexOf("--settings") + 1] ?? "");
const parse = (stdout: string, request: Partial<LaneRequest> = {}) =>
claude.parse({ exitCode: 0, stdout, stderr: "", sidecar: null }, lane(request));
const stream = (...events: unknown[]) => events.map((event) => JSON.stringify(event) + "\n").join("");

const seccomp = "apply-seccomp: failed to apply seccomp filter: Operation not permitted";
const toolUse = (id: string, name = "Bash") =>
Expand Down Expand Up @@ -59,7 +60,7 @@ describe("claude launch", () => {
"--disallowed-tools",
"Agent,Task,WebSearch,WebFetch,Edit,Write,NotebookEdit",
"--output-format",
"json",
"stream-json",
"--verbose",
]);
expect(args).not.toContain("bypassPermissions");
Expand Down Expand Up @@ -180,7 +181,8 @@ describe("claude launch authentication", () => {

describe("claude parse", () => {
it("extracts Claude text, model, usage, cost, and session", () => {
expect(parse(JSON.stringify({
expect(parse(stream({
type: "result",
result: "CLAUDE_OK",
session_id: "claude-session",
usage: { input_tokens: 10, output_tokens: 3 },
Expand All @@ -199,25 +201,25 @@ describe("claude parse", () => {
});

it("extracts the last Claude result event and its terminal metadata", () => {
expect(parse(JSON.stringify([
{ type: "system", model: "claude-opus-9" },
expect(parse(stream(
{ type: "system", subtype: "init", model: "claude-opus-9" },
{ type: "result", result: "EARLIER_RESULT" },
null,
{ type: "assistant", message: { content: [{ type: "text", text: "progress" }] } },
{
type: "result", is_error: false, result: "CLAUDE_ARRAY_OK",
session_id: "claude-array-session",
type: "result", is_error: false, result: "CLAUDE_STREAM_OK",
session_id: "claude-stream-session",
usage: { input_tokens: 14, output_tokens: 4, cache_read_input_tokens: 2 },
total_cost_usd: 0.03,
modelUsage: { "claude-haiku-4-5-20251001": {}, "claude-fable-9-9": {} },
},
{ type: "system", result: "NOT_A_TERMINAL_RESULT" },
]))).toMatchObject({
))).toMatchObject({
kind: "complete",
text: "CLAUDE_ARRAY_OK",
text: "CLAUDE_STREAM_OK",
metadata: {
reportedModel: "claude-fable-9-9",
sessionId: "claude-array-session",
sessionId: "claude-stream-session",
usage: { inputTokens: 14, outputTokens: 4, cachedInputTokens: 2 },
costUsd: 0.03,
},
Expand All @@ -227,36 +229,37 @@ describe("claude parse", () => {
it("rejects Claude terminal errors before accepting partial or missing text", () => {
for (const result of ["partial text", undefined]) {
const terminal = { type: "result", is_error: true, result };
for (const raw of [terminal, [{ type: "result", result: "earlier success" }, terminal]]) {
expect(parse(JSON.stringify(raw)))
for (const events of [[terminal], [{ type: "result", result: "earlier success" }, terminal]]) {
expect(parse(stream(...events)))
.toEqual({ kind: "malformed", message: "claude reported an error result" });
}
}
});

it("rejects Claude arrays without a terminal result event", () => {
for (const raw of [[], [null, "text"], [{ type: "assistant", result: "progress" }]]) {
expect(parse(JSON.stringify(raw)))
it("requires a terminal result even when init or progress reports a model", () => {
const init = { type: "system", subtype: "init", model: "claude-fable-9-9" };
for (const events of [[], [null, "text"], [init], [init, { type: "assistant", result: "progress" }]]) {
expect(parse(stream(...events)))
.toEqual({ kind: "malformed", message: "claude result did not contain a terminal event" });
}
});

it("rejects Claude terminal results without final text", () => {
for (const result of [undefined, "", 42]) {
const terminal = { type: "result", is_error: false, result };
for (const raw of [terminal, [terminal]]) {
expect(parse(JSON.stringify(raw)))
.toEqual({ kind: "malformed", message: "claude result did not contain final text" });
}
expect(parse(stream(terminal)))
.toEqual({ kind: "malformed", message: "claude result did not contain final text" });
}
});

it("rejects malformed responses", () => {
expect(parse("not-json")).toEqual({ kind: "malformed", message: "claude did not emit valid JSON" });
expect(parse('{"type":"system","subtype":"init"}\nnot-json'))
.toEqual({ kind: "malformed", message: "claude emitted a non-JSON event" });
});

it("selects the requested Claude model when usage includes a side model", () => {
expect(parse(JSON.stringify({
expect(parse(stream({
type: "result",
result: "CLAUDE_OK",
modelUsage: {
"claude-haiku-4-5-20251001": {},
Expand Down Expand Up @@ -323,7 +326,7 @@ describe("claude Bash sandbox startup failure", () => {
},
]) {
it(`classifies ${name}`, () => {
expect(parse(JSON.stringify([...events, terminal]), { mode: mode ?? "isolated-write" }))
expect(parse(stream(...events, terminal), { mode: mode ?? "isolated-write" }))
.toMatchObject(expected);
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { adapter, isRevision, type Lane, type LaunchHostConfig, type ParseResult } from "../registry/contract.ts";
import { type AccessMode, evidence } from "../types.ts";
import { type AccessMode, evidence, modelFailureStatus } from "../types.ts";
import {
effortArgs,
exactOrSuffixed,
Expand Down Expand Up @@ -29,7 +29,7 @@ function tools(mode: AccessMode): string {
// Writers run Bash without prompts inside the OS sandbox, which confines writes to the cwd and a
// per-user temp directory. The model cannot opt a command out. When the sandbox is unavailable,
// Claude still exits 0 but every Bash call fails with an `apply-seccomp:` or `bwrap:` line, which
// only the verbose event array exposes; parse reports that as child-failed. A linked worktree's
// only the verbose stream exposes. A linked worktree's
// shared git directory is otherwise writable, so run.ts passes its literal path, which
// discoverSharedGitDir checked for glob characters.
function permissions(
Expand Down Expand Up @@ -75,8 +75,8 @@ function matches(lane: Lane, reported: string): boolean {
return rolling === null ? exactOrSuffixed(lane, reported) : isRevision(rolling, reported);
}

function blocks(event: JsonObject | null, type: string): JsonObject[] {
const content = object(event?.message)?.content;
function blocks(event: JsonObject, type: string): JsonObject[] {
const content = object(event.message)?.content;
if (!Array.isArray(content)) return [];
return content.map(object).filter((block): block is JsonObject => block?.type === type);
}
Expand All @@ -92,18 +92,16 @@ function resultText(content: unknown): string {

const SANDBOX_START_FAILURE = /(?:^|\n)\s*((?:apply-seccomp|bwrap): [^\n]*)/;

function sandboxStartFailure(events: readonly unknown[]): string | null {
function sandboxStartFailure(events: readonly JsonObject[]): string | null {
const bashIds = new Set(
events
.map(object)
.filter((event) => event?.type === "assistant")
.filter((event) => event.type === "assistant")
.flatMap((event) => blocks(event, "tool_use"))
.filter((block) => block.name === "Bash")
.map((block) => block.id)
);
const bashResults = events
.map(object)
.filter((event) => event?.type === "user")
.filter((event) => event.type === "user")
.flatMap((event) => blocks(event, "tool_result"))
.filter((block) => bashIds.has(block.tool_use_id));
const [firstLine, ...remainingLines] = bashResults.map((block) =>
Expand All @@ -115,35 +113,38 @@ function sandboxStartFailure(events: readonly unknown[]): string | null {

function parse(stdout: string, lane: Lane): ParseResult {
const malformed = (message: string): ParseResult => ({ kind: "malformed", message });
let raw: unknown;
try {
raw = JSON.parse(stdout);
} catch {
return malformed("claude did not emit valid JSON");
}
let value: JsonObject | null = null;
if (Array.isArray(raw)) {
for (const entry of raw) {
const event = object(entry);
if (event?.type === "result") value = event;
const events: JsonObject[] = [];
let result: JsonObject | null = null;
for (const line of stdout.split("\n")) {
if (line.trim().length === 0) continue;
try {
const event = object(JSON.parse(line));
if (event === null) continue;
events.push(event);
if (event.type === "result") result = event;
} catch {
return malformed("claude emitted a non-JSON event");
}
if (value === null) return malformed("claude result did not contain a terminal event");
} else {
value = object(raw);
if (value === null) return malformed("claude emitted a non-object result");
}

if (value.is_error === true) return malformed("claude reported an error result");
const text = nullableString(value.result);
if (text === null) return malformed("claude result did not contain final text");

if (result === null) return malformed("claude result did not contain a terminal event");
const metadata = {
reportedModel: modelFromUsage(value.modelUsage, lane, matches),
sessionId: nullableString(value.session_id ?? value.sessionId),
usage: normalizedUsage(value.usage),
costUsd: finiteNumber(value.total_cost_usd) ?? null,
reportedModel: modelFromUsage(result.modelUsage, lane, matches),
sessionId: nullableString(result.session_id ?? result.sessionId),
usage: normalizedUsage(result.usage),
costUsd: finiteNumber(result.total_cost_usd) ?? null,
};
const sandboxFailure = Array.isArray(raw) ? sandboxStartFailure(raw) : null;
if (result.is_error === true) {
const reason = Array.isArray(result.errors)
? result.errors.find((entry): entry is string => typeof entry === "string" && entry.trim().length > 0)
: undefined;
if (reason === undefined) return malformed("claude reported an error result");
return { kind: "provider-failure", status: modelFailureStatus(reason), message: reason, metadata };
}
const text = nullableString(result.result);
if (text === null) return malformed("claude result did not contain final text");

const sandboxFailure = sandboxStartFailure(events);
if (sandboxFailure !== null) {
return {
kind: "provider-failure",
Expand Down Expand Up @@ -237,7 +238,7 @@ export const claude = adapter({
"--disallowed-tools",
deniedTools(lane.access.mode),
"--output-format",
"json",
"stream-json",
"--verbose",
],
receiptArgv,
Expand All @@ -254,7 +255,7 @@ export const claude = adapter({
hostPrerequisites: [],
statePaths: ["the Claude config home (`CLAUDE_CONFIG_DIR`, else `~/.claude`)"],
notes: [
"`--verbose` makes Claude emit its event array, so the runner reports `child-failed` when every Bash call fails to start its sandbox (`apply-seccomp:` or `bwrap:`).",
"The runner captures Claude's `--output-format stream-json --verbose` events in the private stdout sidecar as they arrive. It reports `child-failed` when every Bash call fails to start its sandbox (`apply-seccomp:` or `bwrap:`).",
"The runner passes `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` from the `env` of `settings.json` in the Claude config home only when the shell sets none of `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, or `ANTHROPIC_API_KEY`.",
"When the runner uses those settings, it also forwards `apiKeyHelper` if the settings `env` supplies neither `ANTHROPIC_API_KEY` nor `ANTHROPIC_AUTH_TOKEN`.",
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export type ParseResult =
| { readonly kind: "complete"; readonly text: string; readonly metadata: ProviderMetadata }
| {
readonly kind: "provider-failure";
readonly status: "cancelled" | "child-failed";
readonly status: "cancelled" | "child-failed" | "unavailable-model";
readonly message: string;
readonly metadata: ProviderMetadata;
}
Expand Down
Loading
Loading