diff --git a/.github/workflows/eval-refresh.yml b/.github/workflows/eval-refresh.yml index 41fabf8..263d17d 100644 --- a/.github/workflows/eval-refresh.yml +++ b/.github/workflows/eval-refresh.yml @@ -455,6 +455,31 @@ jobs: exit 1 fi + # The same treatment for a sandbox that fails its own self-check + # (`packages/sandbox/src/toolchain-check.ts`). It runs before the + # agent is installed and errors the cell when the pinned Hookdeck CLI + # is not what the agent's shells resolve. Every job builds the same + # image from the same Dockerfile, so one failure means all of them + # will fail, and the run should stop rather than error every remaining + # cell one at a time. The string is the error's own prefix, and a test in + # `packages/sandbox` fails if the two drift apart. + # + # Only a deterministic answer carries it: `command -v hookdeck` + # resolving nothing, or the wrong version. A probe that times out or + # hits a dead container is retried once and then throws + # "sandbox self-check could not complete", which errors that cell + # alone and does not match here. + sandbox_broken="sandbox self-check failed" + if [ "$eval_status" -ne 0 ] && grep -qF "$sandbox_broken" "$run_log"; then + echo "::error::The sandbox image failed its self-check (pinned Hookdeck CLI missing from PATH or wrong version). Cancelling the run: every remaining job builds the same image." + { + echo "experiment=${{ matrix.experiment }}" + echo "eval=${{ matrix.eval_id }}" + echo "matched=${sandbox_broken}" + } > sandbox-broken.marker + exit 1 + fi + if [ "$eval_status" -ne 0 ]; then exit "$eval_status" fi @@ -490,13 +515,25 @@ jobs: # later still sees it. retention-days: 90 + # The same fallback for a sandbox that failed its self-check: if the + # cancel below does not take, `publish-results` still refuses the run. + - name: Record broken sandbox + if: ${{ failure() && hashFiles('sandbox-broken.marker') != '' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: sandbox-broken-${{ matrix.experiment }}__${{ matrix.eval_id }} + path: sandbox-broken.marker + if-no-files-found: error + retention-days: 90 + - name: Cancel the run # Fails closed. This used to be `gh run cancel … || true` inside the # step above, so a cancel that did not take let every remaining job run # and pay. Retried, and if it still fails the error says so: the # marker above still stops `publish-results`, but the remaining cells - # will run until somebody cancels by hand. - if: ${{ failure() && hashFiles('provider-refused.marker') != '' }} + # will run until somebody cancels by hand. Either marker cancels: a + # provider refusal and a broken sandbox both fail every remaining job. + if: ${{ failure() && hashFiles('provider-refused.marker', 'sandbox-broken.marker') != '' }} shell: bash run: | for attempt in 1 2 3; do @@ -507,7 +544,7 @@ jobs: echo "gh run cancel failed (attempt ${attempt}), retrying" sleep $((attempt * 10)) done - echo "::error::Could not cancel run ${{ github.run_id }} after three attempts. The provider-refusal marker stops publish-results, but the remaining cells will keep running and billing: cancel the run by hand." + echo "::error::Could not cancel run ${{ github.run_id }} after three attempts. The marker uploaded above stops publish-results, but the remaining cells will keep running and billing: cancel the run by hand." exit 1 - name: Upload raw results @@ -723,6 +760,14 @@ jobs: echo "::error::A provider refused requests during this run, so it is not published, whatever the floor says: $(paste -sd, - <<< "$refused")" exit 1 fi + # Likewise a sandbox that failed its self-check. Every job builds the + # same image, so whatever came back is a run with a broken instrument, + # and a merge would fill its holes with carried-forward rows. + broken="$(grep -E '^sandbox-broken-' <<< "$available" || true)" + if [ -n "$broken" ]; then + echo "::error::The sandbox image failed its self-check during this run, so it is not published, whatever the floor says: $(paste -sd, - <<< "$broken")" + exit 1 + fi while IFS= read -r name; do if grep -qxF "$name" <<< "$available"; then gh run download ${{ github.run_id }} --name "$name" --dir "downloaded-results/$name" diff --git a/AGENTS.md b/AGENTS.md index 1e27bef..d57d8cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -770,8 +770,10 @@ with a plausible partial score, and one was written as a `2/6` agent failure), a run that failed while its own report claims success (nine of twelve baselines in one run, every one of them confidently building on the wrong product), a declared credential the agent never referenced, a skill offered and never -opened, a baseline that self-installed a product skill, and a cell whose only -green checks are the ones an idle agent satisfies. +opened, a baseline that self-installed a product skill, a cell whose only +green checks are the ones an idle agent satisfies, and a cell whose agent could +not find the pinned CLI or ran a different one (69 of the 76 Codex cells in run +42044644850). Nothing flagged is not the same as nothing to learn. It means no cell tripped a signal the script knows about, and the signals it knows about are the ones that @@ -1320,6 +1322,25 @@ deleted through the API, so a shared project accumulates history, and a scorer that just asks "did an event arrive?" will eventually say yes because of an earlier run. +**Codex runs most commands in a login shell, and a login shell rebuilds PATH.** +In release run 42044644850, 2,233 of Codex's 2,456 shell commands were +`/bin/bash -lc '…'`; the rest were `bash -c`. A login shell runs Debian's +`/etc/profile`, which replaces whatever PATH the harness passed in with a fixed +list. Claude Code runs `bash -c` and inherits it. Of the Codex attempts in that +run that invoked the pinned `hookdeck`, 26/26, 18/22, 16/16 and 19/19 across +the four arms met `command not found`, and the four that did not had run it +only through `bash -c`. The agents carried on by absolute path, by `npx`, by an +unpinned `npx -y hookdeck-cli@latest`, or through the REST API — all of it +scored as though both agents had the same baseline. So anything an agent needs +on PATH has to be on it for both kinds of shell: the image sets it in `ENV` and +again in `/etc/profile.d/`, and `toolchain-check.ts` errors a cell before it +starts if either shell does not resolve the pinned version. A missing or wrong +CLI is treated in CI like a provider refusal: it leaves a `sandbox-broken` +marker that `publish-results` refuses on and cancels the run, because every +job builds the same image. A probe that times out or hits a dead container is +retried once and then errors only its own cell. Setting `PATH` on +`docker exec` alone is not enough. + **Credentials reach the agent through `EvalSession.sandboxEnv`.** The session is created before the sandbox because the sandbox needs the lease. Disposal runs in reverse, so the container is torn down before the project is released. diff --git a/apps/framework/lib/pinned-cli.ts b/apps/framework/lib/pinned-cli.ts new file mode 100644 index 0000000..7e0fa31 --- /dev/null +++ b/apps/framework/lib/pinned-cli.ts @@ -0,0 +1,162 @@ +import { HOOKDECK_CLI_VERSION } from '@hookdeck-evals/sandbox'; + +/** + * Whether a cell's agent ran without the pinned Hookdeck CLI, and how it got + * round that. + * + * Every experiment is supposed to get the CLI baked into the sandbox image, so + * a row differs from its neighbour by skills and nothing else. On the Codex + * arms it was mostly not on PATH: Codex runs most commands in a login shell + * (`bash -lc`), and Debian's `/etc/profile` drops the npm prefix the CLI lives + * in. In release run 42044644850, of the Codex attempts that invoked + * `hookdeck`, 26/26, 18/22, 16/16 and 19/19 across the four arms met + * `command not found`; the four that did not had run it only through + * `bash -c`. The agents carried on through an absolute path into the package, + * `npx`, an unpinned `npx -y hookdeck-cli@latest`, or the REST API. The first + * two still ran the pinned 2.5.0; the third did not; none of them is the + * baseline the row claims, a CLI that is simply there. + * + * The image now fixes the PATH and the sandbox refuses to start a cell whose + * shells cannot run the pin, so this should not fire on a new run for the + * first reason. It stays for two: rows already on disk carry it, and the + * self-check cannot see a CLI the agent fetches for itself mid-run. Flagged + * whether the cell passed or failed, because a passing row whose agent had to + * find the CLI, or ran a different one, is still not comparable. + * + * Kept outside `scripts/triage.ts` because that file runs `main()` at module + * scope and so cannot be imported by a test. + */ +export interface PinnedCliEvidence { + /** The shell said `hookdeck` does not exist (bash's wording, or dash's). */ + notFound: boolean; + /** `hookdeck-cli` package specs the agent ran or installed that are not the pin. */ + unpinned: string[]; + /** It ran the platform binary inside the package directly. */ + absolutePath: boolean; +} + +const NOT_FOUND = /hookdeck: (command )?not found/; + +/** + * `npx hookdeck-cli@`, `npm install -g hookdeck-cli@`, and the bare + * `hookdeck-cli@` inside either. A spec with no version is not counted: npx + * resolved it to the installed 2.5.0 in every case run 42044644850 reported a + * version. + */ +const PACKAGE_SPEC = /hookdeck-cli@([A-Za-z0-9][\w.-]*)/g; + +const BINARY_PATH = /hookdeck-cli\/binaries\/[\w-]+\/hookdeck/; + +/** What a cell ran in a shell, and what came back, across every attempt. */ +export interface ShellActivity { + commands: string[]; + outputs: string[]; +} + +interface TranscriptLike { + type?: string; + input?: { command?: unknown }; + output?: unknown; + error?: unknown; +} + +export interface RowLike { + transcript?: TranscriptLike[]; + toolCalls?: unknown[]; + priorAttempts?: Array<{ transcript?: TranscriptLike[] }>; +} + +function asText(value: unknown): string { + if (value === undefined || value === null) return ''; + return typeof value === 'string' ? value : JSON.stringify(value); +} + +/** + * Shell commands only, by design. A docs page the agent fetched, or a README + * it wrote for the user, can say `npx hookdeck-cli@latest` without the agent + * having run it, and flagging that would make this cry wolf. Outputs are read + * only for the shell's own `not found`. + */ +export function shellActivity(row: RowLike): ShellActivity { + const commands: string[] = []; + const outputs: string[] = []; + const transcripts = [ + row.transcript ?? [], + ...(row.priorAttempts ?? []).map((attempt) => attempt.transcript ?? []), + ]; + for (const transcript of transcripts) { + for (const part of transcript) { + if (part?.type !== 'tool_call') continue; + const command = part.input?.command; + if (typeof command !== 'string') continue; + commands.push(command); + outputs.push(`${asText(part.output)}\n${asText(part.error)}`); + } + } + for (const raw of row.toolCalls ?? []) { + const call = raw as { + command?: unknown; + result?: unknown; + error?: unknown; + }; + if (typeof call?.command !== 'string') continue; + commands.push(call.command); + outputs.push(`${asText(call.result)}\n${asText(call.error)}`); + } + return { commands, outputs }; +} + +export function pinnedCliEvidence( + activity: ShellActivity, + pinned: string = HOOKDECK_CLI_VERSION +): PinnedCliEvidence | undefined { + const notFound = activity.outputs.some((output) => NOT_FOUND.test(output)); + const commands = activity.commands.join('\n'); + const unpinned = [ + ...new Set( + [...commands.matchAll(PACKAGE_SPEC)] + .map((match) => match[1]) + .filter((version) => version !== pinned && version !== `v${pinned}`) + .map((version) => `hookdeck-cli@${version}`) + ), + ].sort(); + const absolutePath = BINARY_PATH.test(commands); + if (!notFound && unpinned.length === 0) return undefined; + return { notFound, unpinned, absolutePath }; +} + +/** + * The `triage` flags for this evidence: up to two, because they say different + * things. A CLI that was not on PATH leaves a row that may still have run the + * pinned version — reached by absolute path, or by an unversioned `npx` that + * resolved to the install — but whose agent had to go looking for a tool the + * other agent was handed. Only a `hookdeck-cli@` that actually ran + * makes the row unpinned. + */ +export function pinnedCliFlags( + evidence: PinnedCliEvidence, + pinned: string = HOOKDECK_CLI_VERSION +): Array<{ label: string; detail: string }> { + const flags: Array<{ label: string; detail: string }> = []; + if (evidence.notFound) { + const workaround = evidence.absolutePath + ? ', then called the binary inside the package by absolute path' + : ''; + flags.push({ + label: 'PINNED CLI NOT ON PATH', + detail: + `\`hookdeck: command not found\` in its shell${workaround}. The pinned ` + + 'CLI was installed but not on PATH, so this agent had to find a tool ' + + 'the baseline promises is simply there; do not compare the row across agents', + }); + } + if (evidence.unpinned.length > 0) { + flags.push({ + label: 'UNPINNED CLI', + detail: + `ran ${evidence.unpinned.join(', ')} instead of ${pinned}, so this ` + + 'row was not measured with the pinned CLI', + }); + } + return flags; +} diff --git a/apps/framework/lib/provenance.ts b/apps/framework/lib/provenance.ts index c29e609..9e75f83 100644 --- a/apps/framework/lib/provenance.ts +++ b/apps/framework/lib/provenance.ts @@ -5,6 +5,7 @@ import { join } from 'node:path'; import { HOOKDECK_CLI_VERSION, SKILLS_CLI_VERSION, + sandboxImageDefinition, } from '@hookdeck-evals/sandbox'; /** @@ -36,7 +37,10 @@ import { * instead of making it by default. */ export interface Provenance { - /** The harness every scenario shares: base prompt, CLI pin, skills pin. */ + /** + * The harness every scenario shares: base prompt, CLI pin, skills pin, + * sandbox image definition. + */ harness: string; /** The scenario's own files. Changes when its prompt, seed or scorer does. */ scenario: string; @@ -110,14 +114,26 @@ export function skillsPin(root: string): string { * exactly what happened on 27 August and is why this module exists now rather * than later. The skill *context* is deliberately excluded: that varies by arm * and is the treatment being measured, not a change to the instrument. + * + * The sandbox image definition is in here because the image decides what an + * agent's shell can run. Until it was, a Dockerfile change meant to put the + * pinned CLI on PATH for Codex's login shells, where it had been + * `command not found`, would have left every row's harness hash where it was, + * so rows either side of it would read as measured under one instrument + * whether or not the change worked. */ -export function harnessFingerprint(basePrompt: string, root: string): string { +export function harnessFingerprint( + basePrompt: string, + root: string, + imageDefinition: string = sandboxImageDefinition() +): string { return short( [ `base-prompt:${basePrompt}`, `hookdeck-cli:${HOOKDECK_CLI_VERSION}`, `skills-cli:${SKILLS_CLI_VERSION}`, `skills-pin:${skillsPin(root)}`, + `sandbox-image:${imageDefinition}`, ].join('\n') ); } diff --git a/apps/framework/scripts/triage.ts b/apps/framework/scripts/triage.ts index df72c41..397a80e 100644 --- a/apps/framework/scripts/triage.ts +++ b/apps/framework/scripts/triage.ts @@ -6,6 +6,12 @@ import { ERRORED_RUNS_DIRNAME, readErroredEvidenceTree, } from '../harness/errored-cell.js'; +import { + pinnedCliEvidence, + pinnedCliFlags, + type RowLike, + shellActivity, +} from '../lib/pinned-cli.js'; /** * Which cells of a run you have to read, and why. @@ -48,7 +54,7 @@ interface Check { passed?: boolean; } -interface Row { +interface Row extends RowLike { experiment: string; eval: string; passed?: boolean; @@ -237,6 +243,12 @@ function flagsFor(row: Row, requiredEnv: string[]): Flag[] { flags.push({ label: 'NO TOOL CALLS', detail: 'scored without acting' }); } + // Pass or fail: a row whose agent could not find the pinned CLI, or ran a + // different one, is not the baseline it claims to be either way. See + // `lib/pinned-cli.ts`. + const cli = pinnedCliEvidence(shellActivity(row)); + if (cli) flags.push(...pinnedCliFlags(cli)); + return flags; } diff --git a/apps/framework/test/pinned-cli.test.ts b/apps/framework/test/pinned-cli.test.ts new file mode 100644 index 0000000..2d48752 --- /dev/null +++ b/apps/framework/test/pinned-cli.test.ts @@ -0,0 +1,141 @@ +import { describe, expect, it } from 'vitest'; +import { + pinnedCliEvidence, + pinnedCliFlags, + shellActivity, +} from '../lib/pinned-cli.js'; + +const call = (command: string, out: { output?: unknown; error?: string }) => ({ + type: 'tool_call', + name: 'command_execution', + input: { command }, + ...out, +}); + +describe('pinnedCliEvidence', () => { + it('flags the login-shell miss as Codex recorded it in run 42044644850', () => { + // Shape copied from a raw result: the error lands on the transcript part + // and on the tool call record alike. + const row = { + transcript: [ + call("/bin/bash -lc 'hookdeck ci && hookdeck whoami'", { + error: '/bin/bash: line 1: hookdeck: command not found\n', + }), + call( + '/home/node/.npm-global/lib/node_modules/hookdeck-cli/binaries/linux-amd64/hookdeck ci', + { output: 'Logged in' } + ), + ], + toolCalls: [ + { + command: "/bin/bash -lc 'hookdeck ci && hookdeck whoami'", + error: '/bin/bash: line 1: hookdeck: command not found\n', + }, + ], + }; + const evidence = pinnedCliEvidence(shellActivity(row), '2.5.0'); + expect(evidence).toEqual({ + notFound: true, + unpinned: [], + absolutePath: true, + }); + // Not "unpinned": the absolute path reached the pinned 2.5.0. What is + // wrong with the row is that the agent had to go and find it. + const flags = pinnedCliFlags(evidence!, '2.5.0'); + expect(flags.map((f) => f.label)).toEqual(['PINNED CLI NOT ON PATH']); + expect(flags[0].detail).toMatch( + /command not found.*absolute path.*installed but not on PATH/ + ); + expect(flags[0].detail).not.toMatch(/not measured with the pinned CLI/); + }); + + it('says unpinned only when a different hookdeck-cli actually ran', () => { + const flags = pinnedCliFlags( + { + notFound: true, + unpinned: ['hookdeck-cli@latest'], + absolutePath: false, + }, + '2.5.0' + ); + expect(flags.map((f) => f.label)).toEqual([ + 'PINNED CLI NOT ON PATH', + 'UNPINNED CLI', + ]); + expect(flags[1].detail).toBe( + 'ran hookdeck-cli@latest instead of 2.5.0, so this row was not measured with the pinned CLI' + ); + }); + + it("recognises dash's wording too", () => { + const row = { + transcript: [ + call('sh -lc "hookdeck listen 3000"', { + error: 'sh: 1: hookdeck: not found', + }), + ], + }; + expect(pinnedCliEvidence(shellActivity(row), '2.5.0')?.notFound).toBe(true); + }); + + it('flags an unpinned CLI the agent fetched, in an earlier attempt too', () => { + const row = { + transcript: [], + priorAttempts: [ + { + transcript: [ + call("/bin/bash -lc 'npx -y hookdeck-cli@latest project list'", { + output: "You aren't authenticated yet.", + }), + call('npm install -g hookdeck-cli@3.1.0', { + output: 'added 1 package', + }), + ], + }, + ], + }; + expect(pinnedCliEvidence(shellActivity(row), '2.5.0')).toEqual({ + notFound: false, + unpinned: ['hookdeck-cli@3.1.0', 'hookdeck-cli@latest'], + absolutePath: false, + }); + }); + + it('does not flag the pin itself, or an unversioned npx that resolved to it', () => { + const row = { + transcript: [ + call('npx -y hookdeck-cli@2.5.0 --version', { + output: 'hookdeck version 2.5.0', + }), + call('npx --yes hookdeck-cli --version', { + output: 'hookdeck version 2.5.0', + }), + call('hookdeck listen 3000 stripe --output compact', { + output: 'Ready', + }), + ], + }; + expect(pinnedCliEvidence(shellActivity(row), '2.5.0')).toBeUndefined(); + }); + + it('reads commands, not documents the agent read or wrote', () => { + // A docs page or a README the agent wrote can mention an unpinned CLI + // without the agent having run one. + const row = { + transcript: [ + call('curl -s https://hookdeck.com/docs/cli', { + output: 'Run `npx hookdeck-cli@latest listen 3000`', + }), + { + type: 'tool_call', + name: 'file_change', + input: { + path: 'README.md', + content: 'npx hookdeck-cli@latest listen 3000', + }, + }, + ], + }; + expect(pinnedCliEvidence(shellActivity(row), '2.5.0')).toBeUndefined(); + }); +}); diff --git a/apps/framework/test/provenance.test.ts b/apps/framework/test/provenance.test.ts index 782ae46..b62ca65 100644 --- a/apps/framework/test/provenance.test.ts +++ b/apps/framework/test/provenance.test.ts @@ -3,7 +3,9 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; +import { sandboxImageDefinition } from '@hookdeck-evals/sandbox'; import { + harnessFingerprint, SKILLS_PIN_DIRTY_SUFFIX, SKILLS_PIN_UNAVAILABLE, scenarioFingerprint, @@ -137,3 +139,31 @@ describe('skillsPin', () => { expect(skillsPin(root)).not.toBe(git(root, 'rev-parse', 'HEAD')); }); }); + +describe('harnessFingerprint', () => { + // A root with no skills submodule, so the pin is constant across calls. + const root = () => { + const dir = mkdtempSync(join(tmpdir(), 'prov-root-')); + dirs.push(dir); + return dir; + }; + + it('changes when the sandbox image definition does', () => { + // The login-shell PATH fix changed only the Dockerfile, and gave Codex a + // CLI it had not had. Rows either side of it must not share a harness. + const r = root(); + expect(harnessFingerprint('prompt', r, 'aaaaaaaaaaaa')).not.toBe( + harnessFingerprint('prompt', r, 'bbbbbbbbbbbb') + ); + }); + + it('reads the real Dockerfile by default, and is stable', () => { + const r = root(); + expect(harnessFingerprint('prompt', r)).toBe( + harnessFingerprint('prompt', r, sandboxImageDefinition()) + ); + expect(harnessFingerprint('prompt', r)).toBe( + harnessFingerprint('prompt', r) + ); + }); +}); diff --git a/packages/core/src/eval-metadata.ts b/packages/core/src/eval-metadata.ts index f9ad9e4..5bace16 100644 --- a/packages/core/src/eval-metadata.ts +++ b/packages/core/src/eval-metadata.ts @@ -490,7 +490,8 @@ const evalResultShape = { runId: z.string().optional(), /** * What the row was measured under: a fingerprint of the harness every - * scenario shares (base prompt, CLI pin, skills pin) and one of the + * scenario shares (base prompt, CLI pin, skills pin, sandbox image + * definition) and one of the * scenario's own files. `export-results --merge` compares a carried row's * against the fresh rows' to say whether it is still current. * diff --git a/packages/sandbox/Dockerfile b/packages/sandbox/Dockerfile index 4510ccf..8f88164 100644 --- a/packages/sandbox/Dockerfile +++ b/packages/sandbox/Dockerfile @@ -7,13 +7,37 @@ RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \ ca-certificates curl git docker.io \ && rm -rf /var/lib/apt/lists/* -# Global npm installs (both the baked-in skills CLI below and the agent's own -# `npm install -g supabase` at setup time) land in a node-owned prefix instead -# of /usr/local, so they work without root/sudo — matching a typical user's +# Global npm installs (both the baked-in CLIs below and anything the agent +# installs with `npm install -g`) land in a node-owned prefix instead of +# /usr/local, so they work without root/sudo — matching a typical user's # machine, where global npm installs "just work" unelevated. +ENV NPM_CONFIG_PREFIX=/home/node/.npm-global + +# That prefix has to be on PATH in every shell an agent can start, and there +# are two kinds. A non-login shell (`bash -c`, which Claude Code and the +# harness use) inherits PATH from the environment, so the ENV below covers it. +# A login shell (`bash -lc`, which is how Codex runs most commands) does not: +# Debian's /etc/profile overwrites PATH with a fixed list that has no npm +# prefix in it, so the pinned `hookdeck` was `command not found` in Codex's +# login shells on all four Codex arms (found in run 42044644850; +# `toolchain-check.ts` now refuses to start a cell without it). /etc/profile +# then sources /etc/profile.d/*.sh, which is where the prefix is put back. +# +# A profile.d entry rather than symlinks into /usr/local/bin, because it covers +# the whole prefix: `skills`, and anything the agent itself installs globally +# mid-run, which a symlink made at build time cannot know about. +ENV PATH=/home/node/.npm-global/bin:$PATH +RUN printf '%s\n' \ + '# hookdeck-evals sandbox: /etc/profile resets PATH; put the npm prefix back.' \ + 'case ":${PATH}:" in' \ + ' *:/home/node/.npm-global/bin:*) ;;' \ + ' *) PATH="/home/node/.npm-global/bin:${PATH}"; export PATH ;;' \ + 'esac' \ + > /etc/profile.d/npm-global.sh \ + && chmod 0644 /etc/profile.d/npm-global.sh + USER node RUN mkdir -p /home/node/.npm-global -ENV NPM_CONFIG_PREFIX=/home/node/.npm-global # Vercel's agent-skills CLI, used to install agent skills from local sources # into each session's workspace (both modes). Baked in (pinned) so installs are diff --git a/packages/sandbox/src/agent-environment.ts b/packages/sandbox/src/agent-environment.ts index 6437684..f1aeab5 100644 --- a/packages/sandbox/src/agent-environment.ts +++ b/packages/sandbox/src/agent-environment.ts @@ -23,6 +23,7 @@ import type { SkillSource } from '@hookdeck-evals/core'; import { DockerSandbox } from './docker-sandbox.js'; import { ensureSandboxImage } from './image.js'; import { installSkills, type SkillEntry } from './skills.js'; +import { assertPinnedToolchain } from './toolchain-check.js'; export interface AgentEnvironmentOptions { /** Host directory whose contents seed the workspace. */ @@ -55,6 +56,10 @@ export async function createAgentEnvironment( // internet. Upstream used host networking only for the local stack. const sandbox = await DockerSandbox.create({ image }); try { + // Before anything is seeded or installed, and before credentials are in + // the environment: a sandbox whose shells cannot run the pinned CLI must + // error the cell rather than be scored. See `toolchain-check.ts`. + await assertPinnedToolchain(sandbox); if (options.localDir) { const seeded = expandSeedPlaceholders( options.localDir, diff --git a/packages/sandbox/src/docker-sandbox.ts b/packages/sandbox/src/docker-sandbox.ts index dbfd098..8bb06bd 100644 --- a/packages/sandbox/src/docker-sandbox.ts +++ b/packages/sandbox/src/docker-sandbox.ts @@ -57,6 +57,12 @@ export const SANDBOX_CONTAINER_LABEL = 'supabase-evals-sandbox'; */ const CLIENT_TIMEOUT_HEADROOM_MS = 20_000; +/** + * PATH for commands the harness runs. Covers a non-login shell only: a login + * shell (`bash -lc`, which Codex uses for most commands) re-reads + * /etc/profile and replaces it, which is why the image also puts the npm + * prefix back from /etc/profile.d. See the Dockerfile and `toolchain-check.ts`. + */ const SANDBOX_PATH = [ '/home/node/.npm-global/bin', '/usr/local/sbin', diff --git a/packages/sandbox/src/image.ts b/packages/sandbox/src/image.ts index 2265114..e784ccc 100644 --- a/packages/sandbox/src/image.ts +++ b/packages/sandbox/src/image.ts @@ -8,6 +8,7 @@ * retry helper, with no Supabase-specific logic to strip. */ +import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { dockerCli } from './docker-sandbox.js'; @@ -72,15 +73,47 @@ export const SANDBOX_DOCKERFILE_PATH = fileURLToPath( new URL('../Dockerfile', import.meta.url) ); +/** + * The tag a given Dockerfile builds to. + * + * The Dockerfile's own hash is part of it, not only the two pins. An image is + * reused whenever its tag exists, so a tag made of the pins alone meant an edit + * to the Dockerfile never reached a machine that had built the image before: + * the PATH fix for login shells would have been silently skipped on every + * machine with a cached image, and the toolchain check would then have refused + * every cell there. + */ +export function sandboxImageTag(dockerfile: string): string { + return ( + `${SANDBOX_IMAGE_REPOSITORY}:` + + `skills-${SKILLS_CLI_VERSION}-hookdeck-${HOOKDECK_CLI_VERSION}-` + + sandboxImageDefinition(dockerfile) + ); +} + +/** + * A short hash of the image definition: the Dockerfile's bytes. + * + * Exported for provenance as well as the tag. The image is part of the + * instrument, and the case that made it so is the login-shell PATH: with the + * same pins, prompt and skills, Codex's login shells had no `hookdeck` on PATH + * before the Dockerfile changed, and the change is meant to give them the + * pinned one. A row's provenance has to tell those apart, and the pins alone + * cannot. + */ +export function sandboxImageDefinition( + dockerfile: string = readFileSync(SANDBOX_DOCKERFILE_PATH, 'utf8') +): string { + return createHash('sha256').update(dockerfile).digest('hex').slice(0, 12); +} + /** Build (or reuse) the sandbox image and return its tag. */ export async function ensureSandboxImage(): Promise { - const tag = - `${SANDBOX_IMAGE_REPOSITORY}:` + - `skills-${SKILLS_CLI_VERSION}-hookdeck-${HOOKDECK_CLI_VERSION}`; + const dockerfile = readFileSync(SANDBOX_DOCKERFILE_PATH, 'utf8'); + const tag = sandboxImageTag(dockerfile); const existing = await dockerCli(['image', 'inspect', tag]); if (existing.ok) return tag; - const dockerfile = readFileSync(SANDBOX_DOCKERFILE_PATH, 'utf8'); await withTransientRetries( `build ${tag}`, () => diff --git a/packages/sandbox/src/index.ts b/packages/sandbox/src/index.ts index 6710de8..516a17c 100644 --- a/packages/sandbox/src/index.ts +++ b/packages/sandbox/src/index.ts @@ -5,6 +5,9 @@ export type { } from './docker-sandbox.js'; export { ensureSandboxImage, + sandboxImageTag, + // Also for provenance: the image definition is part of the instrument. + sandboxImageDefinition, SANDBOX_DOCKERFILE_PATH, // Exported for provenance: the CLI pin is part of what a published row was // measured under, and a bump changes the product under test. See #60. @@ -31,4 +34,12 @@ export type { AgentEnvironment, AgentEnvironmentOptions, } from './agent-environment.js'; +export { + assertPinnedToolchain, + classifyToolchainProbe, + SANDBOX_SELF_CHECK_FAILED, + SANDBOX_SELF_CHECK_INCONCLUSIVE, + TOOLCHAIN_PROBES, +} from './toolchain-check.js'; +export type { ToolchainOutcome } from './toolchain-check.js'; export type { SandboxCommandResult } from './types.js'; diff --git a/packages/sandbox/src/toolchain-check.ts b/packages/sandbox/src/toolchain-check.ts new file mode 100644 index 0000000..d4f2fcf --- /dev/null +++ b/packages/sandbox/src/toolchain-check.ts @@ -0,0 +1,237 @@ +/** + * A sandbox self-check: is the pinned Hookdeck CLI what an agent's shell + * actually runs? + * + * Every experiment is meant to differ from its neighbour by skills and nothing + * else, and the pinned CLI is part of the baseline both arms share. Nothing + * checked that it was reachable, and for most Codex commands it was not. Codex + * runs most commands in a login shell (`/bin/bash -lc`), and Debian's + * `/etc/profile` overwrites PATH with a fixed list that leaves out the npm + * prefix the CLI is installed into. In release matrix run 42044644850, 2,233 of + * Codex's 2,456 shell commands were `bash -lc`. Of the Codex attempts that + * invoked `hookdeck`, 26/26, 18/22, 16/16 and 19/19 across the four arms met + * `command not found`; the four that did not ran it only through `bash -c`. + * The agents worked around it with an absolute path into the package, + * `npx hookdeck`, an unpinned `npx -y hookdeck-cli@latest`, or the REST API. + * Claude Code runs a non-login shell, inherits the harness's PATH, and was + * unaffected. Those rows were scored and published as though both agents had + * the same CLI on PATH. + * + * So this runs both kinds of shell before the agent is installed, and refuses + * the cell when either does not resolve the pinned version. Throwing is the + * point: `createAgentEnvironment` throws, `runOne` throws, and the cell lands + * in `errored` with no result file — the same route as the empty-transcript + * and dead-process guards in `run-eval.ts`. An agent working without the tool + * the scenario assumes is not a result about the agent. + * + * Two kinds of failure, and only one of them cancels the run. A shell that + * resolves no `hookdeck`, or resolves the wrong version, is a fact about the + * image, so every cell will see it: that throws {@link SANDBOX_SELF_CHECK_FAILED}, + * which CI treats as a run-level failure. Anything else — an in-container + * timeout, a `docker exec` the daemon refused, a container that died — could + * be one cell's bad minute. That probe is retried once and, if it still says + * nothing conclusive, throws {@link SANDBOX_SELF_CHECK_INCONCLUSIVE}, which + * errors this cell and leaves the rest of the matrix running. Cancelling five + * hours of work for a transient hiccup is the opposite mistake. + * + * `--version` rather than `hookdeck version`, deliberately. Cobra answers the + * flag before any of the CLI's own initialisation runs, so it creates no + * config file and makes no network call. `hookdeck version` does both — it + * initialises (and if absent, creates) `~/.config/hookdeck/config.toml` and + * asks GitHub for the latest release — which would change the state the agent + * finds and add a dependency that can fail a cell for reasons no agent caused. + */ + +import { HOOKDECK_CLI_VERSION } from './image.js'; +import type { SandboxCommandResult } from './types.js'; + +/** + * Printed, with exit 3, when `command -v` resolves nothing. A sentinel on + * stdout rather than an exit status alone, because `docker exec` itself exits + * 1 when the container has gone, and that must not read as a missing CLI. + */ +export const NOT_ON_PATH = 'HOOKDECK_NOT_ON_PATH'; +const NOT_ON_PATH_EXIT = 3; + +// No single quotes: the login probe wraps this in them. +const PROBE = + `if ! command -v hookdeck; then echo ${NOT_ON_PATH}; exit ${NOT_ON_PATH_EXIT}; fi; ` + + 'hookdeck --version'; + +/** + * The prefix of the error thrown when the image itself is wrong. The + * `Run evals` step in `eval-refresh.yml` greps the job log for it, treats it as + * a run-level failure like a provider refusal, leaves a `sandbox-broken` marker + * that `publish-results` refuses on, and cancels the run: every job builds the + * same image, so one broken sandbox means all of them are. A test fails if the + * workflow and this string drift apart. + */ +export const SANDBOX_SELF_CHECK_FAILED = 'sandbox self-check failed'; + +/** + * The prefix of the error thrown when the check could not get an answer. Must + * not contain {@link SANDBOX_SELF_CHECK_FAILED}, or a transient error would + * cancel the whole matrix; a test holds it to that. + */ +export const SANDBOX_SELF_CHECK_INCONCLUSIVE = + 'sandbox self-check could not complete'; + +/** + * The two shells an agent can be handed. `runShell` already runs `bash -c` + * with the harness's PATH, so the login probe nests a `bash -lc` inside it, + * which is what Codex does for most commands. + */ +export const TOOLCHAIN_PROBES = [ + { shell: 'non-login (bash -c)', command: PROBE }, + { shell: 'login (bash -lc)', command: `bash -lc '${PROBE}'` }, +] as const; + +const PROBE_TIMEOUT_MS = 60_000; + +export interface ToolchainProbeResult { + shell: string; + result: SandboxCommandResult; +} + +/** + * What one probe says. `not-on-path` and `wrong-version` are facts about the + * image; `inconclusive` is anything that could be this cell's bad luck. + */ +export type ToolchainOutcome = + | { kind: 'ok' } + | { kind: 'not-on-path' | 'wrong-version' | 'inconclusive'; detail: string }; + +/** Classify one probe's result. Pure, so the rule can be tested without Docker. */ +export function classifyToolchainProbe( + probe: ToolchainProbeResult, + expectedVersion: string = HOOKDECK_CLI_VERSION +): ToolchainOutcome { + const { shell, result } = probe; + // Colour is stripped before anything is matched. A CLI release that styles + // `--version` would otherwise put an escape code against the version + // number, fail the whole-token match on every cell of a working image, and + // cancel the run. + const stdout = stripAnsi(result.stdout); + const output = + oneLine(`${stdout}\n${stripAnsi(result.stderr)}`) || 'no output'; + const stdoutLines = stdout.split('\n').map((line) => line.trim()); + + if ( + result.exitCode === NOT_ON_PATH_EXIT && + stdoutLines.includes(NOT_ON_PATH) + ) { + return { + kind: 'not-on-path', + detail: `${shell}: \`command -v hookdeck\` resolved nothing`, + }; + } + if (!result.ok) { + return { + kind: 'inconclusive', + detail: `${shell}: probe exited ${result.exitCode ?? 'without a status'}: ${output}`, + }; + } + // A whole whitespace-delimited token, so 12.5.0 and 2.5.0-beta.1 do not + // pass for 2.5.0. + const pinned = new RegExp(`(^|\\s)v?${escapeRegExp(expectedVersion)}(\\s|$)`); + if (pinned.test(stdout)) return { kind: 'ok' }; + // Only a recognisable version line counts as the wrong version. Output that + // says nothing about a version is not evidence about the image. + if (/\bversion\s+\S+/.test(stdout)) { + return { + kind: 'wrong-version', + detail: `${shell}: \`hookdeck\` is not the pinned ${expectedVersion}: ${output}`, + }; + } + return { + kind: 'inconclusive', + detail: `${shell}: \`hookdeck --version\` printed no version: ${output}`, + }; +} + +interface ShellRunner { + runShell( + command: string, + options?: { timeoutMs?: number } + ): Promise; +} + +async function runProbe( + sandbox: ShellRunner, + shell: string, + command: string +): Promise { + try { + const result = await sandbox.runShell(command, { + timeoutMs: PROBE_TIMEOUT_MS, + }); + return classifyToolchainProbe({ shell, result }); + } catch (err) { + // `dockerCli` throws rather than returning when its own client times out. + return { + kind: 'inconclusive', + detail: `${shell}: probe threw: ${err instanceof Error ? err.message : String(err)}`, + }; + } +} + +/** + * Run every probe and throw if any shell would not hand the agent the pinned + * CLI. Accepts the narrow `runShell` surface so it can be exercised with a + * fake. + */ +export async function assertPinnedToolchain( + sandbox: ShellRunner +): Promise { + const broken: string[] = []; + const unknown: string[] = []; + for (const { shell, command } of TOOLCHAIN_PROBES) { + let outcome = await runProbe(sandbox, shell, command); + if (outcome.kind === 'inconclusive') { + outcome = await runProbe(sandbox, shell, command); + } + if (outcome.kind === 'ok') continue; + (outcome.kind === 'inconclusive' ? unknown : broken).push(outcome.detail); + } + if (broken.length > 0) { + throw new Error( + `${SANDBOX_SELF_CHECK_FAILED}: the pinned Hookdeck CLI is not what an ` + + `agent's shell runs, so this cell was not started and is not scored. ` + + `${[...broken, ...unknown].join('; ')}. The PATH for both shells is ` + + 'set in packages/sandbox/Dockerfile.' + ); + } + if (unknown.length > 0) { + throw new Error( + `${SANDBOX_SELF_CHECK_INCONCLUSIVE}: the probe for the pinned Hookdeck ` + + 'CLI got no answer after a retry, so this cell was not started and is ' + + `not scored. ${unknown.join('; ')}. Not a verdict on the image: re-run ` + + 'the cell.' + ); + } +} + +const ESC = String.fromCharCode(0x1b); +const BEL = String.fromCharCode(0x07); +/** + * ANSI escape sequences: CSI (`ESC [ … final`, which covers SGR colour) and + * OSC (`ESC ] … BEL` or `ESC ] … ESC \`, which covers hyperlinks). Built from + * character codes so the source carries no literal control characters. + */ +const ANSI = new RegExp( + `${ESC}\\[[0-?]*[ -/]*[@-~]|${ESC}\\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)`, + 'g' +); + +export function stripAnsi(text: string): string { + return text.replace(ANSI, ''); +} + +function oneLine(text: string): string { + const flat = text.replace(/\s+/g, ' ').trim(); + return flat.length > 300 ? `${flat.slice(0, 300)}…` : flat; +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} diff --git a/packages/sandbox/test/toolchain-check.test.ts b/packages/sandbox/test/toolchain-check.test.ts new file mode 100644 index 0000000..1978432 --- /dev/null +++ b/packages/sandbox/test/toolchain-check.test.ts @@ -0,0 +1,384 @@ +import { spawnSync } from 'node:child_process'; +import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + HOOKDECK_CLI_VERSION, + SANDBOX_DOCKERFILE_PATH, + sandboxImageTag, +} from '../src/image.js'; +import { + assertPinnedToolchain, + classifyToolchainProbe, + NOT_ON_PATH, + SANDBOX_SELF_CHECK_FAILED, + SANDBOX_SELF_CHECK_INCONCLUSIVE, + TOOLCHAIN_PROBES, +} from '../src/toolchain-check.js'; +import type { SandboxCommandResult } from '../src/types.js'; + +const NPM_BIN = '/home/node/.npm-global/bin'; +/** What Debian's /etc/profile sets for a non-root login shell. */ +const DEBIAN_LOGIN_PATH = + '/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games'; + +const ok = (stdout: string): SandboxCommandResult => ({ + ok: true, + exitCode: 0, + stdout, + stderr: '', +}); +/** What the real probe returns when `command -v hookdeck` resolves nothing. */ +const notOnPath: SandboxCommandResult = { + ok: false, + exitCode: 3, + stdout: `${NOT_ON_PATH}\n`, + stderr: '', +}; +const resolved = ok( + `${NPM_BIN}/hookdeck\nhookdeck version ${HOOKDECK_CLI_VERSION}\n` +); +/** coreutils `timeout` firing inside the container. */ +const timedOut: SandboxCommandResult = { + ok: false, + exitCode: 124, + stdout: '', + stderr: '[command timed out after 60s and was terminated]', +}; +/** `docker exec` against a container that has gone: exit 1, nothing on stdout. */ +const deadContainer: SandboxCommandResult = { + ok: false, + exitCode: 1, + stdout: '', + stderr: 'Error response from daemon: container abc is not running', +}; + +/** Run a probe for real, in a local shell with the given PATH. */ +function runLocally(command: string, path: string): SandboxCommandResult { + const result = spawnSync('bash', ['-c', command], { + env: { PATH: path }, + encoding: 'utf8', + }); + return { + ok: result.status === 0, + exitCode: result.status, + stdout: result.stdout, + stderr: result.stderr, + }; +} + +/** A directory holding a stand-in `hookdeck` that prints the given version. */ +function fakeCliDir(version: string): string { + const dir = mkdtempSync(join(tmpdir(), 'hd-fake-cli-')); + const bin = join(dir, 'hookdeck'); + writeFileSync( + bin, + `#!/bin/sh\n[ "$1" = "--version" ] && echo "hookdeck version ${version}"\n` + ); + chmodSync(bin, 0o755); + return dir; +} + +/** + * The login probe with `-l` dropped, so it runs here without this machine's + * own /etc/profile deciding the PATH. What it checks is that the probe + * survives being nested in single quotes. + */ +const nestedProbe = TOOLCHAIN_PROBES[1].command.replace( + /^bash -lc /, + 'bash -c ' +); + +describe('the probe, run for real', () => { + it('reports a missing CLI with the sentinel and exit 3', () => { + for (const command of [TOOLCHAIN_PROBES[0].command, nestedProbe]) { + const result = runLocally(command, '/usr/bin:/bin'); + expect(result.exitCode).toBe(3); + expect(result.stdout.trim()).toBe(NOT_ON_PATH); + expect(classifyToolchainProbe({ shell: 's', result }).kind).toBe( + 'not-on-path' + ); + } + }); + + it('accepts the pin and refuses another version', () => { + for (const command of [TOOLCHAIN_PROBES[0].command, nestedProbe]) { + const pinned = runLocally( + command, + `${fakeCliDir(HOOKDECK_CLI_VERSION)}:/usr/bin:/bin` + ); + expect(classifyToolchainProbe({ shell: 's', result: pinned })).toEqual({ + kind: 'ok', + }); + const other = runLocally(command, `${fakeCliDir('3.1.0')}:/usr/bin:/bin`); + expect(classifyToolchainProbe({ shell: 's', result: other }).kind).toBe( + 'wrong-version' + ); + } + }); +}); + +describe('classifyToolchainProbe', () => { + it('accepts a shell that resolves the pinned version', () => { + expect( + classifyToolchainProbe({ shell: 'login', result: resolved }) + ).toEqual({ kind: 'ok' }); + expect( + classifyToolchainProbe({ + shell: 'login', + result: ok(`hookdeck version v${HOOKDECK_CLI_VERSION}\n`), + }) + ).toEqual({ kind: 'ok' }); + }); + + it('calls a missing CLI a fact about the image, which is what Codex got', () => { + const outcome = classifyToolchainProbe({ + shell: 'login', + result: notOnPath, + }); + expect(outcome.kind).toBe('not-on-path'); + }); + + it('calls a different version a fact about the image, including one that contains the pin', () => { + for (const other of ['2.5.1', '12.5.0', '2.5.0-beta.1', '3.1.0']) { + const outcome = classifyToolchainProbe( + { shell: 'login', result: ok(`hookdeck version ${other}\n`) }, + '2.5.0' + ); + expect(outcome.kind).toBe('wrong-version'); + } + }); + + it('reads through colour, so a styled --version does not cancel every run', () => { + const esc = '\u001b'; + const bel = '\u0007'; + const coloured = (version: string) => + ok( + `${esc}[1mhookdeck${esc}[0m version ${esc}[32m${version}${esc}[0m\r\n` + ); + expect( + classifyToolchainProbe({ + shell: 'login', + result: coloured(HOOKDECK_CLI_VERSION), + }) + ).toEqual({ kind: 'ok' }); + // An OSC 8 hyperlink around the version, terminated either way. + for (const end of [bel, `${esc}\\`]) { + expect( + classifyToolchainProbe({ + shell: 'login', + result: ok( + `hookdeck version ${esc}]8;;https://example.test${end}${HOOKDECK_CLI_VERSION}${esc}]8;;${end}\n` + ), + }) + ).toEqual({ kind: 'ok' }); + } + // Stripping colour must not turn a different version into the pin. + const other = classifyToolchainProbe( + { shell: 'login', result: coloured('3.1.0') }, + '2.5.0' + ); + expect(other.kind).toBe('wrong-version'); + expect(other.kind === 'ok' ? '' : other.detail).not.toContain(esc); + }); + + it('calls a timeout, a dead container or no version line inconclusive', () => { + for (const result of [ + timedOut, + deadContainer, + { ...timedOut, exitCode: 137 }, + { ...timedOut, exitCode: null }, + ok(`${NPM_BIN}/hookdeck\n`), + ]) { + expect(classifyToolchainProbe({ shell: 'login', result }).kind).toBe( + 'inconclusive' + ); + } + }); +}); + +describe('assertPinnedToolchain', () => { + const fake = ( + byCommand: (command: string, call: number) => SandboxCommandResult + ) => { + const seen: string[] = []; + return { + seen, + runShell: async (command: string) => { + seen.push(command); + return byCommand(command, seen.length); + }, + }; + }; + + it('probes a non-login shell and a nested login shell', async () => { + const sandbox = fake(() => resolved); + await assertPinnedToolchain(sandbox); + expect(sandbox.seen).toEqual(TOOLCHAIN_PROBES.map((p) => p.command)); + expect(sandbox.seen.some((c) => c.startsWith('bash -lc '))).toBe(true); + // `--version` is answered before the CLI initialises, so the probe + // creates no config file and makes no network call. `hookdeck version` + // would do both inside the agent's sandbox. + for (const command of sandbox.seen) { + expect(command).toContain('hookdeck --version'); + expect(command).not.toMatch(/hookdeck version/); + } + }); + + it('cancels-the-run error when only the login shell is missing the CLI', async () => { + const sandbox = fake((command) => + command.startsWith('bash -lc') ? notOnPath : resolved + ); + const error = await assertPinnedToolchain(sandbox).catch((e) => e); + expect(error.message).toMatch( + /^sandbox self-check failed.*not scored.*login \(bash -lc\).*resolved nothing/s + ); + // A deterministic outcome is not retried. + expect(sandbox.seen).toHaveLength(2); + }); + + it('retries a transient failure once and passes if the retry does', async () => { + const sandbox = fake((_, call) => (call === 1 ? timedOut : resolved)); + await assertPinnedToolchain(sandbox); + expect(sandbox.seen).toHaveLength(3); + }); + + it('errors only this cell when a probe stays inconclusive', async () => { + const sandbox = fake((command) => + command.startsWith('bash -lc') ? deadContainer : resolved + ); + const error = await assertPinnedToolchain(sandbox).catch((e) => e); + expect( + String(error.message).startsWith(SANDBOX_SELF_CHECK_INCONCLUSIVE) + ).toBe(true); + // Must not carry the string CI cancels the whole run on. + expect(error.message).not.toContain(SANDBOX_SELF_CHECK_FAILED); + expect(sandbox.seen).toHaveLength(3); + }); + + it('treats a probe that throws as inconclusive', async () => { + const sandbox = { + runShell: async () => { + throw new Error('sandbox command timed out after 80000ms'); + }, + }; + const error = await assertPinnedToolchain(sandbox).catch((e) => e); + expect( + String(error.message).startsWith(SANDBOX_SELF_CHECK_INCONCLUSIVE) + ).toBe(true); + }); + + it('fails with the string CI cancels the run on, and CI is wired to it', async () => { + // `eval-refresh.yml` greps the job log for this prefix to cancel the run + // and leave a `sandbox-broken` marker that blocks publishing. If the two + // drift, a broken image goes back to erroring every cell one at a time. + const workflow = readFileSync( + new URL('../../../.github/workflows/eval-refresh.yml', import.meta.url), + 'utf8' + ); + const step = (name: string) => { + const start = workflow.indexOf(`- name: ${name}\n`); + expect(start, `step "${name}"`).toBeGreaterThan(-1); + const next = workflow.indexOf('- name: ', start + 1); + return workflow.slice(start, next === -1 ? undefined : next); + }; + + expect(workflow).toContain(`sandbox_broken="${SANDBOX_SELF_CHECK_FAILED}"`); + expect(workflow).toContain('> sandbox-broken.marker'); + expect(workflow).toMatch(/grep -E '\^sandbox-broken-'/); + + const record = step('Record broken sandbox'); + expect(record).toContain("hashFiles('sandbox-broken.marker')"); + expect(record).toContain('path: sandbox-broken.marker'); + expect(record).toContain('name: sandbox-broken-'); + + const cancel = step('Cancel the run'); + const cancelIf = cancel.split('\n').find((line) => /^\s+if:/.test(line)); + expect(cancelIf).toContain("'sandbox-broken.marker'"); + expect(cancelIf).toContain("'provider-refused.marker'"); + + const sandbox = fake(() => notOnPath); + const error = await assertPinnedToolchain(sandbox).catch((e) => e); + expect(String(error.message).startsWith(SANDBOX_SELF_CHECK_FAILED)).toBe( + true + ); + }); +}); + +/** + * The /etc/profile.d entry, extracted from the Dockerfile and run under `sh` + * the way Debian's /etc/profile sources it: after PATH has been reset to the + * login list. Docker is not needed, so this runs in CI on every pull request, + * where the image itself is only built by an eval run. + */ +describe('sandbox Dockerfile PATH for login shells', () => { + const dockerfile = readFileSync(SANDBOX_DOCKERFILE_PATH, 'utf8'); + + const profileScript = () => { + const start = dockerfile.indexOf("RUN printf '%s\\n' \\"); + const end = dockerfile.indexOf('> /etc/profile.d/npm-global.sh', start); + expect(start).toBeGreaterThan(-1); + expect(end).toBeGreaterThan(start); + const lines = dockerfile + .slice(start, end) + .split('\n') + .slice(1) + .map((line) => line.trim()) + .filter((line) => line.startsWith("'")) + .map((line) => line.replace(/^'/, '').replace(/' \\$/, '')); + expect(lines.length).toBeGreaterThan(0); + const dir = mkdtempSync(join(tmpdir(), 'hd-profile-')); + const path = join(dir, 'npm-global.sh'); + writeFileSync(path, `${lines.join('\n')}\n`); + return path; + }; + + const sourced = (script: string, times: number) => { + const body = Array.from({ length: times }, () => '. "$1"').join('; '); + const result = spawnSync( + 'sh', + ['-c', `${body}; printf %s "$PATH"`, 'sh', script], + { + env: { PATH: DEBIAN_LOGIN_PATH }, + encoding: 'utf8', + } + ); + expect(result.status, result.stderr).toBe(0); + return result.stdout; + }; + + it('puts the npm prefix back in front of the login PATH', () => { + expect(sourced(profileScript(), 1)).toBe(`${NPM_BIN}:${DEBIAN_LOGIN_PATH}`); + }); + + it('adds it once however often it is sourced', () => { + expect(sourced(profileScript(), 3)).toBe(`${NPM_BIN}:${DEBIAN_LOGIN_PATH}`); + }); + + it('writes it as root, before the image switches to the node user', () => { + expect(dockerfile.indexOf('/etc/profile.d/npm-global.sh')).toBeLessThan( + dockerfile.indexOf('USER node') + ); + }); + + it('covers non-login shells through the image environment as well', () => { + expect(dockerfile).toContain(`ENV PATH=${NPM_BIN}:$PATH`); + expect(dockerfile).toContain( + 'ENV NPM_CONFIG_PREFIX=/home/node/.npm-global' + ); + }); +}); + +describe('sandboxImageTag', () => { + it('changes when the Dockerfile does, so an edit reaches a cached machine', () => { + const dockerfile = readFileSync(SANDBOX_DOCKERFILE_PATH, 'utf8'); + expect(sandboxImageTag(dockerfile)).not.toBe( + sandboxImageTag(`${dockerfile}\n# edit\n`) + ); + expect(sandboxImageTag(dockerfile)).toBe(sandboxImageTag(dockerfile)); + expect(sandboxImageTag(dockerfile)).toContain( + `hookdeck-${HOOKDECK_CLI_VERSION}` + ); + }); +}); diff --git a/reference/results-format.md b/reference/results-format.md index c63e561..83ebce5 100644 --- a/reference/results-format.md +++ b/reference/results-format.md @@ -73,8 +73,14 @@ with a warning rather than published as a failure. `low` | `medium` | `high` | `max`. `provenance`: what the row was measured under. `harness` covers what every -scenario shares — the base prompt, the sandbox CLI pin, the skills CLI and the -skills submodule pin — and `scenario` covers the scenario's own files. Two rows +scenario shares — the base prompt, the sandbox CLI pin, the skills CLI, the +skills submodule pin and the sandbox image definition (the Dockerfile) — and +`scenario` covers the scenario's own files. The image definition joined in +November 2026, so every row recorded before then has a different `harness` +from every row after it. That is intended: the image change that came with it +puts the pinned CLI on PATH for Codex's login shells (`bash -lc`), where in +earlier runs it was `command not found`. Whether it does so in practice is for +the first run on the new image to confirm. Two rows with the same `scenario` and different `harness` measured the same task under a different instrument. Opaque: compare for equality, do not parse. `skillsPin` is the skills submodule commit the row ran against, in the clear, possibly with a