From d6f572eaf77b49de2c1d66864b92dda41dbbb6c6 Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Sat, 7 Nov 2026 13:11:45 +0000 Subject: [PATCH 1/2] Add a preflight that checks a matrix before it is dispatched `pnpm preflight` runs the fourteen checks #131 lists, plus its canary requirement, and exits non-zero when an assertion fails. Decisions (CLI pins, skills pin, model IDs, base prompt) print the pin, the latest and "decision required: record in the release notes", and never fail. It is read-only against Hookdeck, Outpost, GitHub and both providers, apart from one real completion per provider. Those requests, the secret and variable names, and the refusal pattern are parsed out of eval-refresh.yml rather than copied, and the spend estimate reads the measured cost table out of AGENTS.md. basePromptFor moves to lib/base-prompt.ts so the preflight can import it without running the runner; the prompt string is unchanged, so no harness fingerprint moves. core exports registeredAgentPins() and hookdeck exports its trigger matcher and Outpost baseline, read-only. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 32 + apps/framework/harness/run-eval.ts | 37 +- apps/framework/lib/base-prompt.ts | 70 + apps/framework/lib/preflight/args.ts | 171 +++ apps/framework/lib/preflight/canary.ts | 113 ++ apps/framework/lib/preflight/links.ts | 89 ++ apps/framework/lib/preflight/matrix.ts | 107 ++ apps/framework/lib/preflight/models.ts | 57 + apps/framework/lib/preflight/report.ts | 149 ++ apps/framework/lib/preflight/semver.ts | 65 + apps/framework/lib/preflight/spend.ts | 242 ++++ apps/framework/lib/preflight/workflow.ts | 173 +++ apps/framework/package.json | 3 +- apps/framework/scripts/preflight.ts | 1679 ++++++++++++++++++++++ apps/framework/test/preflight.test.ts | 567 ++++++++ package.json | 1 + packages/core/src/agents/registry.ts | 22 + packages/core/src/index.ts | 6 +- packages/hookdeck/src/index.ts | 3 + packages/hookdeck/src/project-source.ts | 7 +- 20 files changed, 3555 insertions(+), 38 deletions(-) create mode 100644 apps/framework/lib/base-prompt.ts create mode 100644 apps/framework/lib/preflight/args.ts create mode 100644 apps/framework/lib/preflight/canary.ts create mode 100644 apps/framework/lib/preflight/links.ts create mode 100644 apps/framework/lib/preflight/matrix.ts create mode 100644 apps/framework/lib/preflight/models.ts create mode 100644 apps/framework/lib/preflight/report.ts create mode 100644 apps/framework/lib/preflight/semver.ts create mode 100644 apps/framework/lib/preflight/spend.ts create mode 100644 apps/framework/lib/preflight/workflow.ts create mode 100644 apps/framework/scripts/preflight.ts create mode 100644 apps/framework/test/preflight.test.ts diff --git a/AGENTS.md b/AGENTS.md index eac7b31..1ac2454 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -333,6 +333,38 @@ gh workflow disable eval-refresh.yml # stops the cron and dispatch gh workflow enable eval-refresh.yml # both again ``` +### Before dispatching a matrix + +Run the preflight, with the same inputs the dispatch will take, from a checkout of `main`: + +```bash +pnpm preflight --suite benchmark --experiment-suite benchmark,no-skills --runs 3 +pnpm preflight --help # every flag, and the check ids --skip takes +``` + +Every defect v0.5.0 found was discoverable before the run that found it (#131), and +a matrix costs about $100 and six hours. The preflight takes minutes. It is read-only +apart from one real completion per provider, the same request the workflow's own +preflight makes. + +- **Assertions fail the script.** Do not dispatch on a non-zero exit. Spend needs + `--confirm-balance` (or a `y` on a terminal) because no provider exposes a balance + to a project key. Open `harness` issues need `--accept-harness `, so each + one is accepted for the run by name. +- **Decisions never fail it.** A pin behind `latest`, a skills pin behind `main`, a + model with a newer sibling, a changed base prompt: each prints the current and the + latest, and the release notes record what was chosen. +- **A moved instrument needs a canary.** When the image definition, a CLI pin or a + model differs from the newest published rows, it prints the two-cell + `gh workflow run` command with `EVALS_PUBLISH=false`. Verify the finished run with + `--canary-run ` before the matrix. +- **`--skip ` is an escape hatch, not a pass.** The report prints skipped checks + as a banner. Name them in the release notes. + +It reads `.env` for the provider and project keys, so it checks your keys, not the +repository secrets. It checks those by name only, and the workflow checks their +liveness before its matrix. + ## What to work on next **GitHub Issues is the source of truth for work, and #24 is the order to do it diff --git a/apps/framework/harness/run-eval.ts b/apps/framework/harness/run-eval.ts index 718fecb..e1bb816 100644 --- a/apps/framework/harness/run-eval.ts +++ b/apps/framework/harness/run-eval.ts @@ -72,6 +72,7 @@ import { scenarioFingerprint, skillsPin, } from '../lib/provenance.js'; +import { basePromptFor } from '../lib/base-prompt.js'; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = join(__dirname, '..', '..', '..'); @@ -370,41 +371,7 @@ function copyWithheldTests(ev: EvalManifest, workspace: string) { } } -/** - * The base prompt is a treatment, not neutral scaffolding. - * - * The last sentence was added on 27 August, borrowed verbatim from - * [clerk/clerk-evals](https://github.com/clerk/clerk-evals), which prepends the - * same line to every eval prompt on its agentic path — the closest architectural - * match to ours, running the same two agent CLIs. - * - * It exists because this benchmark is single-turn: a question gets no reply, and - * the agent is scored on whatever state it left, usually nothing. Four cells in - * the stored runs ended that way, against a skills delta measured at two cells in - * twenty-four, so the noise was larger than the signal it sat next to. - * - * **This is not a claim that asking is wrong.** τ-bench's airline policy requires - * an agent to "list the action details and obtain explicit user confirmation - * (yes) to proceed" before any action that updates the booking database — the - * behaviour penalised here is a *pass requirement* there, because that harness - * has a user to answer. Ours does not. So the line is a property of our - * instrument, and a cell that trips `ASKED_AND_STOPPED` must never be published - * as a capability failure. See the survey on hookdeck/evals#57 for the full - * option space; four other benchmarks answer this four different ways. - * - * Everything measured before this date was measured without it, so results - * either side are not comparable — the same rule as a scenario or CLI change, - * and for the same reason. - */ -function basePromptFor(_mode: EvalMode): string { - return ( - 'You are an agent working on a real Hookdeck project, as a developer would. ' + - 'Use the provided tools to inspect and change the project. ' + - 'When you are done, end your turn with a short summary of what you did ' + - '(or for investigation tasks, your findings). ' + - 'Do not ask clarifying questions. Complete the task with the information provided.' - ); -} +// `basePromptFor` lives in `../lib/base-prompt.ts`; see the note there. function buildSystemPrompt( mode: EvalMode, diff --git a/apps/framework/lib/base-prompt.ts b/apps/framework/lib/base-prompt.ts new file mode 100644 index 0000000..f601252 --- /dev/null +++ b/apps/framework/lib/base-prompt.ts @@ -0,0 +1,70 @@ +import type { EvalMode } from '../harness/types.js'; + +/** + * The base prompt is a treatment, not neutral scaffolding. + * + * The last sentence was added on 27 August, borrowed verbatim from + * [clerk/clerk-evals](https://github.com/clerk/clerk-evals), which prepends the + * same line to every eval prompt on its agentic path — the closest architectural + * match to ours, running the same two agent CLIs. + * + * It exists because this benchmark is single-turn: a question gets no reply, and + * the agent is scored on whatever state it left, usually nothing. Four cells in + * the stored runs ended that way, against a skills delta measured at two cells in + * twenty-four, so the noise was larger than the signal it sat next to. + * + * **This is not a claim that asking is wrong.** τ-bench's airline policy requires + * an agent to "list the action details and obtain explicit user confirmation + * (yes) to proceed" before any action that updates the booking database — the + * behaviour penalised here is a *pass requirement* there, because that harness + * has a user to answer. Ours does not. So the line is a property of our + * instrument, and a cell that trips `ASKED_AND_STOPPED` must never be published + * as a capability failure. See the survey on hookdeck/evals#57 for the full + * option space; four other benchmarks answer this four different ways. + * + * Everything measured before this date was measured without it, so results + * either side are not comparable — the same rule as a scenario or CLI change, + * and for the same reason. + * + * Lives here rather than in `run-eval.ts` so `preflight` can read the prompt a + * dispatch would use without importing the runner, which executes on import. + * Keep it a single `return` of concatenated string literals: + * `extractBasePrompt` reads it back out of the source at an earlier release, + * where it may still be in `run-eval.ts`. + */ +export function basePromptFor(_mode: EvalMode): string { + return ( + 'You are an agent working on a real Hookdeck project, as a developer would. ' + + 'Use the provided tools to inspect and change the project. ' + + 'When you are done, end your turn with a short summary of what you did ' + + '(or for investigation tasks, your findings). ' + + 'Do not ask clarifying questions. Complete the task with the information provided.' + ); +} + +/** + * The base prompt as written in a source file, or undefined when the file has + * no `basePromptFor`. + * + * For comparing against a release, where the function may sit in a different + * file. Reads the string literals of its `return` and joins them, which is what + * the concatenation evaluates to, so a reflowed line does not read as a change. + */ +export function extractBasePrompt(source: string): string | undefined { + const start = source.search(/function\s+basePromptFor\s*\(/); + if (start < 0) return undefined; + const body = source.slice(start); + const ret = body.search(/\breturn\b/); + if (ret < 0) return undefined; + // The function's closing brace, at the start of a line. Not the first `;`, + // which a prompt is free to contain. + const end = body.indexOf('\n}', ret); + const expression = body.slice(ret, end < 0 ? undefined : end); + const literals = [ + ...expression.matchAll(/'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"/g), + ]; + if (literals.length === 0) return undefined; + return literals + .map((m) => (m[1] ?? m[2] ?? '').replace(/\\(.)/g, '$1')) + .join(''); +} diff --git a/apps/framework/lib/preflight/args.ts b/apps/framework/lib/preflight/args.ts new file mode 100644 index 0000000..78d5d5a --- /dev/null +++ b/apps/framework/lib/preflight/args.ts @@ -0,0 +1,171 @@ +import { readRepeatedFlag } from '../cli-args.js'; +import { DISPATCH_DEFAULTS, type DispatchInputs } from './matrix.js'; + +/** + * Every check, by the id `--skip` takes and its number in #131. The canary is + * the requirement #131 attaches to checks 1, 2 and 4, numbered after them. + */ +export const CHECKS = [ + { number: 1, id: 'hookdeck-cli-pin', title: 'Hookdeck CLI pin' }, + { number: 2, id: 'agent-cli-pins', title: 'Agent CLI pins' }, + { number: 3, id: 'skills-pin', title: 'Skills pin' }, + { number: 4, id: 'model-ids', title: 'Model IDs' }, + { number: 5, id: 'base-prompt', title: 'Base prompt' }, + { number: 6, id: 'provider-keys', title: 'Provider keys work' }, + { number: 7, id: 'spend', title: 'Spend' }, + { number: 8, id: 'secrets', title: 'Secrets' }, + { number: 9, id: 'main-green', title: 'Main is green' }, + { number: 10, id: 'nothing-running', title: 'Nothing else is running' }, + { number: 11, id: 'repo-variables', title: 'Repository variables' }, + { number: 12, id: 'projects-pristine', title: 'Projects are pristine' }, + { number: 13, id: 'skill-links', title: 'Skill links resolve' }, + { number: 14, id: 'harness-issues', title: 'Open harness issues' }, + { number: 15, id: 'canary', title: 'Canary' }, +] as const; + +export type CheckId = (typeof CHECKS)[number]['id']; + +export interface PreflightArgs { + json: boolean; + help: boolean; + skip: CheckId[]; + confirmBalance: boolean; + dispatch: DispatchInputs; + /** What `EVALS_PUBLISH` should be for this run: publish unless held. */ + holdPublish: boolean; + /** What `EVALS_MAX_MISSING_FRACTION` should resolve to. */ + maxMissingFraction: string; + acceptHarness: number[]; + canaryRun?: string; + canaryEval: string; +} + +export const DEFAULT_MAX_MISSING_FRACTION = '0.1'; +export const DEFAULT_CANARY_EVAL = 'benchmark-localdev-001-listen-locally'; + +function single(raw: string[], name: string): string | undefined { + const values = readRepeatedFlag(raw, name); + if (values.length > 1) throw new Error(`--${name} takes one value`); + return values[0]; +} + +const KNOWN_FLAGS = new Set([ + 'json', + 'help', + 'skip', + 'confirm-balance', + 'experiments', + 'eval', + 'suite', + 'experiment-suite', + 'runs', + 'timeout-sec', + 'merge', + 'hold-publish', + 'max-missing-fraction', + 'accept-harness', + 'canary-run', + 'canary-eval', +]); + +/** + * Flags mirror the `workflow_dispatch` inputs, so the command that checks a + * matrix reads like the command that dispatches it. `--timeout-sec` and + * `--merge` are accepted and do not change any check. + */ +export function parsePreflightArgs(argv: string[]): PreflightArgs { + const raw = argv.filter((a) => a !== '--'); + for (const arg of raw) { + if (!arg.startsWith('--')) continue; + const name = arg.slice(2).split('=')[0] as string; + if (!KNOWN_FLAGS.has(name)) throw new Error(`unknown flag ${arg}`); + } + + const known = new Set(CHECKS.map((c) => c.id)); + const skip = readRepeatedFlag(raw, 'skip'); + const unknown = skip.filter((s) => !known.has(s)); + if (unknown.length > 0) { + throw new Error( + `--skip: no check named ${unknown.join(', ')}. Checks: ${[...known].join(', ')}` + ); + } + + const runsRaw = single(raw, 'runs'); + const runs = runsRaw === undefined ? DISPATCH_DEFAULTS.runs : Number(runsRaw); + if (!Number.isInteger(runs) || runs < 1) { + throw new Error(`--runs must be a positive integer, got ${runsRaw}`); + } + + const listOr = (name: string, fallback: string[]) => { + const v = readRepeatedFlag(raw, name); + return v.length > 0 ? v : fallback; + }; + + const accept = readRepeatedFlag(raw, 'accept-harness').map((v) => { + const n = Number(v.replace(/^#/, '')); + if (!Number.isInteger(n)) throw new Error(`--accept-harness: ${v}`); + return n; + }); + + const maxMissing = single(raw, 'max-missing-fraction'); + if (maxMissing !== undefined && !/^\d*\.?\d+$/.test(maxMissing)) { + throw new Error( + `--max-missing-fraction must be a number, got ${maxMissing}` + ); + } + + return { + json: raw.includes('--json'), + help: raw.includes('--help') || raw.includes('-h'), + skip: skip as CheckId[], + confirmBalance: raw.includes('--confirm-balance'), + dispatch: { + suites: listOr('suite', DISPATCH_DEFAULTS.suites), + experimentSuites: listOr( + 'experiment-suite', + DISPATCH_DEFAULTS.experimentSuites + ), + experiments: readRepeatedFlag(raw, 'experiments'), + evalIds: readRepeatedFlag(raw, 'eval'), + runs, + }, + holdPublish: raw.includes('--hold-publish'), + maxMissingFraction: maxMissing ?? DEFAULT_MAX_MISSING_FRACTION, + acceptHarness: accept, + canaryRun: single(raw, 'canary-run'), + canaryEval: single(raw, 'canary-eval') ?? DEFAULT_CANARY_EVAL, + }; +} + +export const USAGE = `pnpm preflight [options] + +Checks a matrix before it is dispatched. Read-only, except one real completion +per provider (pennies). Exits non-zero when an assertion fails. + +What the dispatch will run (mirrors the workflow_dispatch inputs; defaults are +the workflow's, which is the regression suite): + --suite eval suites (default regression) + --experiment-suite experiment suites (default regression) + --experiments experiment names (default: all in the suites) + --eval eval ids (overrides --suite, as in the workflow) + --runs attempts per cell (default 2) + --timeout-sec, --merge accepted; change nothing here + +What the run intends: + --hold-publish expect EVALS_PUBLISH=false (default: expect publishing) + --max-missing-fraction expect this EVALS_MAX_MISSING_FRACTION (default 0.1) + --accept-harness open harness issues accepted for this run, by number + --confirm-balance confirm both provider balances cover the estimate + (asked interactively instead when on a TTY) + --canary-run verify a finished two-cell canary run + --canary-eval scenario the canary command uses + (default ${DEFAULT_CANARY_EVAL}) + +Output: + --json machine-readable report + --skip skip checks by id; printed loudly. Ids: + ${CHECKS.map((c) => c.id).join(', ')} + +A full benchmark matrix: + pnpm preflight --suite benchmark --experiment-suite benchmark,no-skills --runs 3 +`; diff --git a/apps/framework/lib/preflight/canary.ts b/apps/framework/lib/preflight/canary.ts new file mode 100644 index 0000000..f615959 --- /dev/null +++ b/apps/framework/lib/preflight/canary.ts @@ -0,0 +1,113 @@ +/** + * Whether the instrument has moved since the last published rows, and the + * two-cell canary that has to pass before a matrix runs under a moved one. + * + * #114 is the case: a Dockerfile change meant to put the pinned CLI on PATH for + * Codex's login shells shipped straight into a matrix, and the matrix is where + * it was found not to have worked. Two cells, one per agent CLI, with publishing + * held, would have found it for the price of two cells. + */ + +export interface Instrument { + /** `sandboxImageDefinition()`: a hash of the Dockerfile's bytes. */ + imageDefinition?: string; + hookdeckCli?: string; + /** Agent id to pinned CLI version, for agents an experiment uses. */ + agentClis: Record; + /** Experiment name to model id. */ + models: Record; +} + +export interface InstrumentChange { + what: string; + published: string; + current: string; +} + +const UNKNOWN = 'unknown'; + +/** + * Every part of the instrument that differs from what the published rows were + * measured under. An unknown published value counts as a change: a canary is + * cheap and a matrix under an instrument nobody could compare is not. + */ +export function diffInstrument( + published: Instrument, + current: Instrument +): InstrumentChange[] { + const changes: InstrumentChange[] = []; + const compare = (what: string, p?: string, c?: string) => { + if (c === undefined) return; + if (p === c) return; + changes.push({ what, published: p ?? UNKNOWN, current: c }); + }; + compare( + 'sandbox image definition', + published.imageDefinition, + current.imageDefinition + ); + compare('Hookdeck CLI pin', published.hookdeckCli, current.hookdeckCli); + for (const [agent, version] of Object.entries(current.agentClis).sort()) { + compare(`${agent} CLI pin`, published.agentClis[agent], version); + } + for (const [experiment, model] of Object.entries(current.models).sort()) { + // An experiment with no published rows is new, and a new experiment is a + // model nobody has run here, so it is a change too. + compare(`${experiment} model`, published.models[experiment], model); + } + return changes; +} + +/** + * A pinned string in a source file at some commit: `NAME = '1.2.3'` or + * `name: '1.2.3'`. For reading pins at the commit that produced a published + * run, where importing the module is not an option. + */ +export function readPin(source: string, name: string): string | undefined { + const re = new RegExp(`\\b${name}\\s*[:=]\\s*['"]([^'"]+)['"]`); + return re.exec(source)?.[1]; +} + +export interface CanaryPlan { + experiments: string[]; + evalId: string; + commands: string[]; +} + +/** + * The exact commands for a two-cell canary with publishing held. + * + * `EVALS_PUBLISH=false` is a repository variable, so it is set before the + * dispatch and deleted after; check 11 fails a later matrix if it is left set. + */ +export function canaryPlan( + experiments: string[], + evalId: string, + evalSuite: string, + experimentSuites: string[] +): CanaryPlan { + return { + experiments, + evalId, + commands: [ + 'gh variable set EVALS_PUBLISH --body false', + 'gh workflow run eval-refresh.yml' + + ` -f suite=${evalSuite}` + + ` -f experiment_suite=${[...new Set(experimentSuites)].join(',')}` + + ` -f experiments=${experiments.join(',')}` + + ` -f eval=${evalId}` + + ' -f runs=1', + '# when it finishes:', + 'pnpm preflight --canary-run ', + 'gh variable delete EVALS_PUBLISH', + ], + }; +} + +export const CANARY_CRITERIA = [ + 'the run concluded success, with one cell per agent', + 'no cell failed the sandbox self-check', + 'no cell shows PINNED CLI NOT ON PATH', + 'every cell passed the credential check on its artifacts', + 'the publish job did not run', +]; diff --git a/apps/framework/lib/preflight/links.ts b/apps/framework/lib/preflight/links.ts new file mode 100644 index 0000000..fed24c9 --- /dev/null +++ b/apps/framework/lib/preflight/links.ts @@ -0,0 +1,89 @@ +/** + * Hookdeck docs URLs in skill files. + * + * A dead link in a skill is worse than none: an agent that follows it gets a + * 404 and falls back to search, a guess or memory (#104, #100). The check is + * every `hookdeck.com/docs` URL in the pinned skills, because those are the + * links we can fix; third-party links are someone else's to keep alive. + */ + +const DOCS_URL = /https?:\/\/(?:www\.)?hookdeck\.com\/docs[^\s)\]>"'`<|]*/g; + +/** Punctuation that ends a sentence, not a URL. */ +const TRAILING = /[.,;:!?*_]+$/; + +/** + * A root-relative docs path, as skills write them in tables: `` `/docs/x.md` `` + * or `[x](/docs/x.md)`. #104's dead links in `referencing-docs.md` are this + * form, and the file tells the agent they are hookdeck.com paths, so they are + * checked as such. + */ +const RELATIVE_DOCS = /`(\/docs\/[^`\s]*)`|\]\((\/docs\/[^)\s]*)\)/g; + +export const DOCS_ORIGIN = 'https://hookdeck.com'; + +/** + * Every docs URL in the text, absolute or root-relative, in order of first + * appearance, deduplicated. Relative paths come back absolute. + */ +export function extractDocsUrls(text: string): string[] { + const found: Array<{ index: number; url: string }> = []; + for (const m of text.matchAll(DOCS_URL)) { + found.push({ index: m.index ?? 0, url: m[0].replace(TRAILING, '') }); + } + for (const m of text.matchAll(RELATIVE_DOCS)) { + const path = (m[1] ?? m[2] ?? '').replace(TRAILING, ''); + found.push({ index: m.index ?? 0, url: `${DOCS_ORIGIN}${path}` }); + } + found.sort((a, b) => a.index - b.index); + const seen = new Set(); + const out: string[] = []; + for (const { url } of found) { + if (seen.has(url)) continue; + seen.add(url); + out.push(url); + } + return out; +} + +/** The URL a request goes to: a fragment is never sent to the server. */ +export function fetchableUrl(url: string): string { + const hash = url.indexOf('#'); + return hash < 0 ? url : url.slice(0, hash); +} + +export interface LinkOccurrence { + url: string; + files: string[]; +} + +/** Group URLs across files by what is actually fetched. */ +export function collectLinks( + files: Array<{ path: string; text: string }> +): LinkOccurrence[] { + const byUrl = new Map>(); + for (const file of files) { + for (const url of extractDocsUrls(file.text)) { + const key = fetchableUrl(url); + const set = byUrl.get(key) ?? new Set(); + set.add(file.path); + byUrl.set(key, set); + } + } + return [...byUrl] + .map(([url, set]) => ({ url, files: [...set].sort() })) + .sort((a, b) => a.url.localeCompare(b.url)); +} + +/** + * Which skills a list of changed paths touches, for the skills-pin decision. + * `skills//...` in hookdeck/agent-skills. + */ +export function changedSkills(paths: string[]): string[] { + const out = new Set(); + for (const p of paths) { + const m = /^skills\/([^/]+)\//.exec(p); + if (m) out.add(m[1] as string); + } + return [...out].sort(); +} diff --git a/apps/framework/lib/preflight/matrix.ts b/apps/framework/lib/preflight/matrix.ts new file mode 100644 index 0000000..c12b45c --- /dev/null +++ b/apps/framework/lib/preflight/matrix.ts @@ -0,0 +1,107 @@ +import type { PlannedCell } from './spend.js'; + +/** + * The cells a dispatch would run, worked out the way `eval-refresh.yml`'s + * "Discover eval pairs" step works them out. + * + * Mirrored rather than shared, because that step is shell; the tests pin the + * rules it follows. The two that matter for cost: a benchmark scenario runs + * under both the `benchmark` and `no-skills` experiment suites, and naming + * scenarios with `eval` overrides the suite filter entirely. + */ + +export interface DispatchInputs { + suites: string[]; + experimentSuites: string[]; + /** Blank means every experiment in the requested experiment suites. */ + experiments: string[]; + /** Blank means every scenario in the requested suites. */ + evalIds: string[]; + runs: number; +} + +/** The workflow_dispatch defaults, which are the regression suite. */ +export const DISPATCH_DEFAULTS: DispatchInputs = { + suites: ['regression'], + experimentSuites: ['regression'], + experiments: [], + evalIds: [], + runs: 2, +}; + +export interface PlannableEval { + id: string; + suite: string; + metadata: { minAttempts?: number; requires?: string[] } & Record< + string, + unknown + >; +} + +export interface PlannableExperiment { + name: string; + suites: string[]; + skipEval?: (ev: { id: string; metadata: never }) => boolean; +} + +/** `min_attempts` is a floor on `--runs`, capped at five. */ +export function attemptsFor(runs: number, minAttempts?: number): number { + return Math.min(5, Math.max(runs, minAttempts ?? 0)); +} + +export function experimentSuitesForEval(evalSuite: string): string[] { + switch (evalSuite) { + case 'benchmark': + return ['benchmark', 'no-skills']; + case 'regression': + return ['regression']; + default: + return []; + } +} + +export interface PlannedPair extends PlannedCell { + experimentSuite: string; +} + +export function planCells( + evals: PlannableEval[], + experiments: PlannableExperiment[], + inputs: DispatchInputs +): PlannedPair[] { + const chosen = + inputs.evalIds.length > 0 + ? evals.filter((e) => inputs.evalIds.includes(e.id)) + : evals.filter((e) => inputs.suites.includes(e.suite)); + + const cells: PlannedPair[] = []; + for (const ev of chosen) { + for (const experimentSuite of experimentSuitesForEval(ev.suite)) { + if (!inputs.experimentSuites.includes(experimentSuite)) continue; + for (const experiment of experiments) { + if (!experiment.suites.includes(experimentSuite)) continue; + if ( + inputs.experiments.length > 0 && + !inputs.experiments.includes(experiment.name) + ) { + continue; + } + if ( + experiment.skipEval?.({ + id: ev.id, + metadata: ev.metadata as never, + }) + ) { + continue; + } + cells.push({ + experiment: experiment.name, + eval: ev.id, + experimentSuite, + runs: attemptsFor(inputs.runs, ev.metadata.minAttempts), + }); + } + } + } + return cells; +} diff --git a/apps/framework/lib/preflight/models.ts b/apps/framework/lib/preflight/models.ts new file mode 100644 index 0000000..500507c --- /dev/null +++ b/apps/framework/lib/preflight/models.ts @@ -0,0 +1,57 @@ +/** + * Comparing a pinned model id against a provider's models list. + * + * Providers name models `-[-]` with a dated snapshot + * suffix on some, and do not mark which is newest, so "is there something newer + * in this family" is answered from the version numbers in the id. That is a + * heuristic and the report says so; the decision belongs to a person. + */ + +const DATED = /-\d{4}-\d{2}-\d{2}$|-\d{8}$/; + +/** `claude-sonnet-5-5` and `claude-sonnet-5` share `claude-sonnet-N`. */ +export function modelFamily(id: string): string { + return id.replace(DATED, '').replace(/\d+(?:[.-]\d+)*/, 'N'); +} + +/** `[5, 5]` for `claude-sonnet-5-5`, `[5, 4]` for `gpt-5.4-mini`. */ +export function modelVersion(id: string): number[] { + const m = /\d+(?:[.-]\d+)*/.exec(id.replace(DATED, '')); + return m ? m[0].split(/[.-]/).map(Number) : []; +} + +function compareVersions(a: number[], b: number[]): number { + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const x = a[i] ?? 0; + const y = b[i] ?? 0; + if (x !== y) return x < y ? -1 : 1; + } + return 0; +} + +export interface ModelStanding { + model: string; + listed: boolean; + /** Listed ids that extend this one, e.g. `gpt-5.6-sol` for `gpt-5.6`. */ + variants: string[]; + /** Same family, higher version, excluding dated snapshots. */ + newer: string[]; +} + +export function modelStanding(model: string, listed: string[]): ModelStanding { + const family = modelFamily(model); + const version = modelVersion(model); + return { + model, + listed: listed.includes(model), + variants: listed.filter((id) => id.startsWith(`${model}-`)).sort(), + newer: listed + .filter( + (id) => + !DATED.test(id) && + modelFamily(id) === family && + compareVersions(modelVersion(id), version) > 0 + ) + .sort((a, b) => compareVersions(modelVersion(b), modelVersion(a))), + }; +} diff --git a/apps/framework/lib/preflight/report.ts b/apps/framework/lib/preflight/report.ts new file mode 100644 index 0000000..9fed71e --- /dev/null +++ b/apps/framework/lib/preflight/report.ts @@ -0,0 +1,149 @@ +/** + * The shape of a preflight result and how it is printed. + * + * Two kinds of check, because #131 separates them and the difference decides + * the exit code. An **assertion** is a fact that has to hold before a matrix is + * worth paying for, and a failed one fails the script. A **decision** is a gap + * somebody has to choose about — a pin behind `latest`, a prompt that moved — and + * it never fails, because staying on an old pin is a legitimate choice. What is + * not legitimate is making it silently, so a decision with a gap says so and + * says where the choice is recorded. + */ + +export type CheckKind = 'decision' | 'assertion'; + +/** + * - `pass`: nothing to do. + * - `fail`: an assertion that does not hold. Fails the script. + * - `decide`: a decision with a gap. Never fails the script. + * - `warn`: holds, or could not be decided, with something worth reading. + * - `skipped`: the operator passed `--skip`. Printed loudly, never silently. + */ +export type CheckStatus = 'pass' | 'fail' | 'decide' | 'warn' | 'skipped'; + +export interface CheckResult { + /** The id `--skip` takes. */ + id: string; + /** Its number in #131, so the report and the issue can be read side by side. */ + number: number; + title: string; + kind: CheckKind; + status: CheckStatus; + summary: string; + details: string[]; +} + +export const DECISION_FOOTER = 'decision required: record in the release notes'; + +export interface ReportMeta { + generatedAt: string; + headSha?: string; + dispatchSha?: string; + skipped: string[]; + notes: string[]; +} + +const LABEL: Record = { + pass: 'PASS ', + fail: 'FAIL ', + decide: 'DECIDE', + warn: 'WARN ', + skipped: 'SKIP ', +}; + +/** Non-zero when any assertion failed. Decisions and skips never fail. */ +export function exitCodeFor(results: CheckResult[]): number { + return results.some((r) => r.kind === 'assertion' && r.status === 'fail') + ? 1 + : 0; +} + +export function summarise(results: CheckResult[]): { + failed: CheckResult[]; + decisions: CheckResult[]; + skipped: CheckResult[]; + warnings: CheckResult[]; +} { + return { + failed: results.filter( + (r) => r.kind === 'assertion' && r.status === 'fail' + ), + decisions: results.filter((r) => r.status === 'decide'), + skipped: results.filter((r) => r.status === 'skipped'), + warnings: results.filter((r) => r.status === 'warn'), + }; +} + +function section(title: string, results: CheckResult[]): string[] { + if (results.length === 0) return []; + const lines = ['', title, '-'.repeat(title.length)]; + for (const r of [...results].sort((a, b) => a.number - b.number)) { + lines.push( + `${LABEL[r.status]} ${String(r.number).padStart(2)}. ${r.title}: ${r.summary}` + ); + for (const d of r.details) lines.push(` ${d}`); + if (r.status === 'decide') lines.push(` -> ${DECISION_FOOTER}`); + } + return lines; +} + +export function formatReport(results: CheckResult[], meta: ReportMeta): string { + const lines: string[] = [`Preflight, ${meta.generatedAt}`]; + if (meta.headSha) lines.push(` checked at HEAD ${meta.headSha}`); + if (meta.dispatchSha) + lines.push(` a dispatch runs main ${meta.dispatchSha}`); + for (const note of meta.notes) lines.push(` NOTE: ${note}`); + if (meta.skipped.length > 0) { + lines.push( + '', + '!!! SKIPPED BY REQUEST: ' + meta.skipped.join(', ') + ' !!!', + '!!! Nothing below says these hold. Name them in the release notes. !!!' + ); + } + + lines.push( + ...section( + 'Decisions', + results.filter((r) => r.kind === 'decision') + ), + ...section( + 'Assertions', + results.filter((r) => r.kind === 'assertion') + ) + ); + + const { failed, decisions, skipped } = summarise(results); + lines.push(''); + lines.push( + failed.length === 0 + ? 'Result: every assertion that ran holds.' + : `Result: ${failed.length} assertion${failed.length === 1 ? '' : 's'} failed: ` + + failed.map((r) => r.id).join(', ') + + '. Do not dispatch.' + ); + if (decisions.length > 0) { + lines.push( + `${decisions.length} decision${decisions.length === 1 ? '' : 's'} to record in the release notes: ` + + decisions.map((r) => r.id).join(', ') + ); + } + if (skipped.length > 0) { + lines.push(`Skipped by request: ${skipped.map((r) => r.id).join(', ')}`); + } + return lines.join('\n'); +} + +/** + * Remove secret values from text before it is printed. + * + * Belt and braces: no check prints a credential on purpose, but a provider's + * error body or a URL can echo one back, and the report gets pasted into issues. + */ +export function maskSecrets(text: string, secrets: string[]): string { + let out = text; + for (const secret of [...secrets].sort((a, b) => b.length - a.length)) { + if (secret.length < 8) continue; + out = out.split(secret).join('****'); + } + return out; +} diff --git a/apps/framework/lib/preflight/semver.ts b/apps/framework/lib/preflight/semver.ts new file mode 100644 index 0000000..9292807 --- /dev/null +++ b/apps/framework/lib/preflight/semver.ts @@ -0,0 +1,65 @@ +/** + * Just enough semver to say how far a pin is behind `latest`. + * + * Not a dependency: the inputs are npm `latest` tags and our own pins, both of + * which are plain `MAJOR.MINOR.PATCH`, and a prerelease only needs to sort + * before its release. + */ + +export interface Semver { + major: number; + minor: number; + patch: number; + prerelease?: string; +} + +export function parseSemver(version: string): Semver | undefined { + const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec( + version.trim() + ); + if (!m) return undefined; + return { + major: Number(m[1]), + minor: Number(m[2]), + patch: Number(m[3]), + ...(m[4] ? { prerelease: m[4] } : {}), + }; +} + +/** -1, 0 or 1. Throws on input that is not a version, rather than guessing. */ +export function compareSemver(a: string, b: string): number { + const x = parseSemver(a); + const y = parseSemver(b); + if (!x || !y) throw new Error(`not a version: ${!x ? a : b}`); + for (const key of ['major', 'minor', 'patch'] as const) { + if (x[key] !== y[key]) return x[key] < y[key] ? -1 : 1; + } + if (x.prerelease === y.prerelease) return 0; + if (x.prerelease === undefined) return 1; + if (y.prerelease === undefined) return -1; + return x.prerelease < y.prerelease ? -1 : 1; +} + +/** + * "2 major versions behind (2.5.0 -> 3.1.0)", or "up to date". + * + * Names the largest component that moved, because that is the one that decides + * how much reading the bump needs: a major is a changelog to read, a patch + * usually is not. + */ +export function describeVersionGap(current: string, latest: string): string { + const x = parseSemver(current); + const y = parseSemver(latest); + if (!x || !y) return `cannot compare ${current} with ${latest}`; + const order = compareSemver(current, latest); + if (order === 0) return `up to date (${current})`; + if (order > 0) return `ahead of latest (${current} > ${latest})`; + const plural = (n: number, word: string) => + `${n} ${word} version${n === 1 ? '' : 's'} behind`; + let gap: string; + if (y.major !== x.major) gap = plural(y.major - x.major, 'major'); + else if (y.minor !== x.minor) gap = plural(y.minor - x.minor, 'minor'); + else if (y.patch !== x.patch) gap = plural(y.patch - x.patch, 'patch'); + else gap = 'prerelease behind'; + return `${gap} (${current} -> ${latest})`; +} diff --git a/apps/framework/lib/preflight/spend.ts b/apps/framework/lib/preflight/spend.ts new file mode 100644 index 0000000..384c499 --- /dev/null +++ b/apps/framework/lib/preflight/spend.ts @@ -0,0 +1,242 @@ +/** + * What a requested matrix is likely to cost, from the figures AGENTS.md + * records as measured. + * + * Read from AGENTS.md rather than copied here, because that table is where the + * measurements live and where they get corrected; a second copy is how the + * judge came to be reported at twenty-eight times its real cost. The figures + * are per full pass at a stated denominator, and AGENTS.md is explicit that + * scaling them is arithmetic rather than measurement, so the estimate says + * which figures it scaled. + * + * Neither provider exposes a credit balance to a project key, so this never + * claims to know one. It prints the estimate and a person confirms the balance + * covers it. + */ + +export interface CostTable { + /** Scenarios in the pass the figures were measured over. */ + denominator: number; + /** Dollars per full pass, keyed by experiment name without `-no-skills`. */ + perPass: Record; + /** Dollars per full pass for the LLM judge. */ + judgePerPass?: number; +} + +const WORD_NUMBERS: Record = { + ten: 10, + eleven: 11, + twelve: 12, + thirteen: 13, + fourteen: 14, + fifteen: 15, + sixteen: 16, + seventeen: 17, + eighteen: 18, + nineteen: 19, + twenty: 20, +}; + +/** + * The per-pass cost table in AGENTS.md, or undefined when it cannot be found. + * Undefined is a failure for the caller: an estimate with no figures behind it + * is worse than none. + */ +export function parseCostTable(agentsMd: string): CostTable | undefined { + const heading = + /Measured per full pass of \*{0,2}([a-z]+|\d+)\*{0,2} scenarios/i.exec( + agentsMd + ); + if (!heading) return undefined; + const word = (heading[1] as string).toLowerCase(); + const denominator = /^\d+$/.test(word) ? Number(word) : WORD_NUMBERS[word]; + if (!denominator) return undefined; + + const after = agentsMd.slice(heading.index); + const perPass: Record = {}; + let judgePerPass: number | undefined; + let inTable = false; + for (const line of after.split('\n').slice(1)) { + if (!line.startsWith('|')) { + if (inTable) break; + continue; + } + inTable = true; + const m = /^\|\s*(.+?)\s*\|\s*about \$([\d.]+)\s*\|/.exec(line); + if (!m) continue; + const label = m[1] as string; + const dollars = Number(m[2]); + if (/full matrix/i.test(label)) continue; + if (/judge/i.test(label)) { + judgePerPass = dollars; + continue; + } + const name = /`([^`]+)`/.exec(label)?.[1]; + if (name) perPass[name] = dollars; + } + if (Object.keys(perPass).length === 0) return undefined; + return { denominator, perPass, judgePerPass }; +} + +export interface PlannedCell { + experiment: string; + eval: string; + /** Attempts allowed for this cell: `--runs`, raised by `min_attempts`. */ + runs: number; +} + +export interface SpendRow { + experiment: string; + cells: number; + /** Dollars for one attempt of one cell, agent plus judge. */ + perAttempt: number; + /** Probability an attempt fails, which is what buys a retry. */ + failRate: number; + failRateSource: string; + /** Every cell run exactly once. */ + firstAttempts: number; + low: number; + high: number; + /** False when no measured figure covers this experiment. */ + priced: boolean; +} + +export interface SpendEstimate { + rows: SpendRow[]; + firstAttempts: number; + low: number; + high: number; + unpriced: string[]; + assumptions: string[]; +} + +export function costKey(experiment: string): string { + return experiment.replace(/-no-skills$/, ''); +} + +/** + * Expected cost of one cell relative to one typical attempt. + * + * `--runs` stops at the first pass, so attempt `i` (counting from 0) runs only + * when the `i` before it failed: probability `f^i`. Each of those costs `k` + * times a typical attempt, because the attempts that repeat are by construction + * the failed ones and a failing cell tends to run to its timeout. AGENTS.md + * writes the three-attempt case as `1 + 0.114k`. + */ +export function attemptMultiplier( + failRate: number, + runs: number, + k: number +): number { + let extra = 0; + for (let i = 1; i < runs; i++) extra += failRate ** i; + return 1 + k * extra; +} + +/** `k` is unmeasured (#6). AGENTS.md brackets it with 1 and 3. */ +export const FAILED_ATTEMPT_COST = { low: 1, high: 3 }; + +/** Used when the published results carry no rows for an experiment. */ +export const DEFAULT_FAIL_RATE = 0.25; + +export function estimateSpend( + cells: PlannedCell[], + costs: CostTable, + failRates: Record +): SpendEstimate { + const judgePerCell = (costs.judgePerPass ?? 0) / costs.denominator; + const priced = Object.values(costs.perPass).map((v) => v / costs.denominator); + // An experiment with no measured figure is priced at the dearest one we have, + // and named, so an estimate never quietly drops a model it cannot price. + const fallback = Math.max(...priced); + + const byExperiment = new Map(); + for (const cell of cells) { + const list = byExperiment.get(cell.experiment) ?? []; + list.push(cell); + byExperiment.set(cell.experiment, list); + } + + const rows: SpendRow[] = []; + const unpriced: string[] = []; + for (const [experiment, list] of [...byExperiment].sort()) { + const perPass = costs.perPass[costKey(experiment)]; + const isPriced = perPass !== undefined; + if (!isPriced) unpriced.push(experiment); + const perAttempt = + (isPriced ? perPass / costs.denominator : fallback) + judgePerCell; + const fail = failRates[experiment] ?? { + rate: DEFAULT_FAIL_RATE, + source: 'no published rows; assumed', + }; + let low = 0; + let high = 0; + for (const cell of list) { + low += + perAttempt * + attemptMultiplier(fail.rate, cell.runs, FAILED_ATTEMPT_COST.low); + high += + perAttempt * + attemptMultiplier(fail.rate, cell.runs, FAILED_ATTEMPT_COST.high); + } + rows.push({ + experiment, + cells: list.length, + perAttempt, + failRate: fail.rate, + failRateSource: fail.source, + firstAttempts: perAttempt * list.length, + low, + high, + priced: isPriced, + }); + } + + const sum = (key: 'firstAttempts' | 'low' | 'high') => + rows.reduce((acc, r) => acc + r[key], 0); + return { + rows, + firstAttempts: sum('firstAttempts'), + low: sum('low'), + high: sum('high'), + unpriced, + assumptions: [ + `per-pass figures from AGENTS.md, measured over ${costs.denominator} scenarios and divided by ${costs.denominator}: scaled, not re-measured`, + `a failed attempt costs ${FAILED_ATTEMPT_COST.low}x to ${FAILED_ATTEMPT_COST.high}x a typical one; unmeasured (#6)`, + 'fail rates are per attempt, from the published rows that needed more than one attempt or failed', + ], + }; +} + +/** + * Per-attempt fail rate for each experiment, from published rows. + * + * A row that took more than one attempt, or failed, had at least one failed + * attempt. A row that failed every attempt is still counted once, so where + * failures repeat this understates the rate; the source string says how it was + * derived so nobody reads it as a measurement of attempts. + */ +export function failRatesFromRows( + rows: Array<{ experiment?: string; passed?: boolean; attempts?: number }> +): Record { + const tally = new Map(); + for (const row of rows) { + if (!row.experiment) continue; + const t = tally.get(row.experiment) ?? { failed: 0, total: 0 }; + t.total += 1; + if (row.passed === false || (row.attempts ?? 1) > 1) t.failed += 1; + tally.set(row.experiment, t); + } + const out: Record = {}; + for (const [experiment, t] of tally) { + out[experiment] = { + rate: t.failed / t.total, + source: `${t.failed}/${t.total} published rows needed a retry or failed`, + }; + } + return out; +} + +export function dollars(n: number): string { + return `$${n.toFixed(2)}`; +} diff --git a/apps/framework/lib/preflight/workflow.ts b/apps/framework/lib/preflight/workflow.ts new file mode 100644 index 0000000..9bca9c8 --- /dev/null +++ b/apps/framework/lib/preflight/workflow.ts @@ -0,0 +1,173 @@ +/** + * What `eval-refresh.yml` reads and does, parsed from the workflow itself. + * + * The workflow is the source of truth for which secrets and variables a run + * uses and for how its provider preflight is made, so this reads them out of + * the YAML rather than keeping a second list. A list kept here would be the + * mistake AGENTS.md describes: `OUTPOST_API_KEY` was documented as a secret + * before it existed, and the first full matrix scored `outpost-001` as six + * agent failures because of it. + * + * Text parsing rather than a YAML library, because what is wanted is inside + * shell scripts in `run:` blocks, which YAML returns as one opaque string + * anyway. The tests run these parsers against the real workflow, so a change to + * its shape fails a test rather than quietly emptying a list. + */ + +/** Lines that are not YAML comments. A `secrets.X` in prose is not a read. */ +function codeLines(yaml: string): string[] { + return yaml.split('\n').filter((line) => !/^\s*#/.test(line)); +} + +function referenced(yaml: string, namespace: 'secrets' | 'vars'): string[] { + const out = new Set(); + const re = new RegExp(`\\b${namespace}\\.([A-Za-z_][A-Za-z0-9_]*)`, 'g'); + for (const line of codeLines(yaml)) { + for (const m of line.matchAll(re)) out.add(m[1] as string); + } + return [...out].sort(); +} + +/** + * Every `secrets.NAME` the workflow reads. `GITHUB_TOKEN` is excluded: GitHub + * provides it, so it never appears in `gh secret list` and is never missing. + */ +export function workflowSecrets(yaml: string): string[] { + return referenced(yaml, 'secrets').filter((s) => s !== 'GITHUB_TOKEN'); +} + +/** Every `vars.NAME` the workflow reads. */ +export function workflowVariables(yaml: string): string[] { + return referenced(yaml, 'vars'); +} + +export interface ProviderProbe { + /** The API host, which is how the two probes are told apart. */ + host: string; + provider: 'openai' | 'anthropic' | 'unknown'; + url: string; + /** Header templates, with `${VAR}` left in for the caller to fill. */ + headers: Record; + body: string; + model?: string; +} + +/** The `run:` script of a step, by its exact name. */ +export function stepScript(yaml: string, stepName: string): string | undefined { + const lines = yaml.split('\n'); + const start = lines.findIndex( + (l) => + l.trim() === `- name: ${stepName}` || l.trim() === `name: ${stepName}` + ); + if (start < 0) return undefined; + const indent = (lines[start] as string).search(/\S/); + const out: string[] = []; + for (let i = start + 1; i < lines.length; i++) { + const line = lines[i] as string; + const lineIndent = line.search(/\S/); + // The next step at the same indent, or the end of this job, ends the step. + if (lineIndent >= 0 && lineIndent <= indent && line.trim() !== '') break; + out.push(line); + } + return out.join('\n'); +} + +export const PROVIDER_PREFLIGHT_STEP = 'Check provider keys are live'; + +/** + * The provider requests the workflow's preflight makes, so a local preflight + * makes the same ones: same endpoint, same model, same body. + * + * #42 asks for this check to run locally and suggests moving it into the run + * path. Until it moves, the workflow holds the one copy, and this reads it. + */ +export function providerProbes(yaml: string): ProviderProbe[] { + const script = stepScript(yaml, PROVIDER_PREFLIGHT_STEP); + if (!script) return []; + const probes: ProviderProbe[] = []; + // Each probe is one `curl ... || echo 000` invocation, continued with `\`. + const invocations = codeLines(script) + .join('\n') + .split(/\bcurl\b/) + .slice(1); + for (const invocation of invocations) { + const text = invocation.split('|| echo')[0] ?? invocation; + const url = /-X\s+POST\s+(https:\/\/[^\s\\"']+)/.exec(text)?.[1]; + if (!url) continue; + const headers: Record = {}; + for (const m of text.matchAll(/-H\s+"([^"]+)"/g)) { + const raw = m[1] as string; + const colon = raw.indexOf(':'); + if (colon < 0) continue; + headers[raw.slice(0, colon).trim()] = raw.slice(colon + 1).trim(); + } + const body = /-d\s+'([^']*)'/.exec(text)?.[1] ?? ''; + let model: string | undefined; + try { + model = (JSON.parse(body) as { model?: string }).model; + } catch { + model = undefined; + } + const host = new URL(url).host; + probes.push({ + host, + provider: host.endsWith('openai.com') + ? 'openai' + : host.endsWith('anthropic.com') + ? 'anthropic' + : 'unknown', + url, + headers, + body, + model, + }); + } + return probes; +} + +/** + * Fill `${VAR}` placeholders from the environment. Returns the names that were + * missing rather than sending a request with an empty key, which a provider + * answers with a 401 that reads like a revoked key. + */ +export function fillTemplate( + template: string, + env: Record +): { value: string; missing: string[] } { + const missing: string[] = []; + const value = template.replace( + /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, + (_, name) => { + const v = env[name]; + if (!v) { + missing.push(name); + return ''; + } + return v; + } + ); + return { value, missing }; +} + +/** + * The pattern the workflow uses to recognise a provider refusing requests + * (credit, quota, auth), so a failed probe is described in the same words the + * run would use to cancel itself. + */ +export function refusalPattern(yaml: string): RegExp | undefined { + const m = /refusals="([^"]+)"/.exec(yaml); + return m ? new RegExp(m[1] as string, 'i') : undefined; +} + +/** Statuses `gh run list` reports for a run that has not finished. */ +const UNFINISHED = new Set([ + 'queued', + 'in_progress', + 'pending', + 'waiting', + 'requested', +]); + +export function unfinishedRuns(runs: T[]): T[] { + return runs.filter((r) => UNFINISHED.has(String(r.status))); +} diff --git a/apps/framework/package.json b/apps/framework/package.json index 68797fa..6f49891 100644 --- a/apps/framework/package.json +++ b/apps/framework/package.json @@ -16,7 +16,8 @@ "report-results": "node --import tsx/esm scripts/report-results.ts", "triage": "node --import tsx/esm scripts/triage.ts", "check-artifacts": "node --env-file-if-exists=../../.env --import tsx/esm scripts/check-artifacts.ts", - "scenario-criteria": "node --import tsx/esm scripts/scenario-criteria.ts" + "scenario-criteria": "node --import tsx/esm scripts/scenario-criteria.ts", + "preflight": "node --env-file-if-exists=../../.env --import tsx/esm scripts/preflight.ts" }, "dependencies": { "@ai-sdk/anthropic": "catalog:", diff --git a/apps/framework/scripts/preflight.ts b/apps/framework/scripts/preflight.ts new file mode 100644 index 0000000..ae6ef07 --- /dev/null +++ b/apps/framework/scripts/preflight.ts @@ -0,0 +1,1679 @@ +import { execFile } from 'node:child_process'; +import { lookup } from 'node:dns/promises'; +import { + existsSync, + mkdtempSync, + readdirSync, + readFileSync, + readlinkSync, + rmSync, + statSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createInterface } from 'node:readline/promises'; +import { registeredAgentPins } from '@hookdeck-evals/core'; +import { + DEFAULT_ISSUE_TRIGGERS, + HookdeckClient, + OUTPOST_GATEWAY_PRISTINE, + OutpostClient, + RESOURCE_KINDS, + collectEnvSecretValues, + issueTriggerMatchesDeclared, + redactSecrets, + type HookdeckResource, + type OperatorEventDestination, +} from '@hookdeck-evals/hookdeck'; +import { + HOOKDECK_CLI_VERSION, + SANDBOX_SELF_CHECK_FAILED, + sandboxImageDefinition, +} from '@hookdeck-evals/sandbox'; +import { basePromptFor, extractBasePrompt } from '../lib/base-prompt.js'; +import { + discoverEvals, + EVALS_ROOT, + loadExperiments, +} from '../lib/discovery.js'; +import { + pinnedCliEvidence, + pinnedCliFlags, + shellActivity, + type RowLike, +} from '../lib/pinned-cli.js'; +import { + CHECKS, + parsePreflightArgs, + USAGE, + type CheckId, + type PreflightArgs, +} from '../lib/preflight/args.js'; +import { + CANARY_CRITERIA, + canaryPlan, + diffInstrument, + readPin, + type Instrument, +} from '../lib/preflight/canary.js'; +import { changedSkills, collectLinks } from '../lib/preflight/links.js'; +import { planCells, type PlannedPair } from '../lib/preflight/matrix.js'; +import { modelStanding } from '../lib/preflight/models.js'; +import { + exitCodeFor, + formatReport, + maskSecrets, + type CheckResult, + type CheckStatus, +} from '../lib/preflight/report.js'; +import { compareSemver, describeVersionGap } from '../lib/preflight/semver.js'; +import { + dollars, + estimateSpend, + failRatesFromRows, + parseCostTable, + type SpendEstimate, +} from '../lib/preflight/spend.js'; +import { + fillTemplate, + providerProbes, + refusalPattern, + unfinishedRuns, + workflowSecrets, + workflowVariables, +} from '../lib/preflight/workflow.js'; + +/** + * Everything a matrix dispatch should not find out by failing. + * + * ```bash + * pnpm preflight # the regression suite + * pnpm preflight --suite benchmark --experiment-suite benchmark,no-skills --runs 3 + * pnpm preflight --help + * ``` + * + * Every defect v0.5.0 found was discoverable before the run that found it — a + * Codex PATH miss, a skills pin three months behind, a CLI pin two minors + * behind, leftovers in the Outpost project, two dispatches publishing over each + * other (#131). A matrix costs about $100 and six hours; this runs in minutes. + * + * **Read-only**, against Hookdeck, Outpost, GitHub and both providers, with one + * exception: one real completion per provider, the same request the workflow's + * own preflight makes, because a models list answers 200 with a zero balance. + * It never prints a secret value: the report is passed through the same + * redaction the artifact export uses before it is written. + * + * Network and process calls go through `Deps`, so the logic in `lib/preflight/` + * is tested without either. + */ + +interface ExecResult { + code: number; + stdout: string; + stderr: string; +} + +export interface Deps { + root: string; + env: Record; + exec( + cmd: string, + args: string[], + opts?: { cwd?: string; timeoutMs?: number } + ): Promise; + fetch: typeof fetch; + resolveHost(host: string): Promise; +} + +const realDeps: Deps = { + root: EVALS_ROOT, + env: process.env, + exec: (cmd, args, opts) => + new Promise((resolve) => { + execFile( + cmd, + args, + { + cwd: opts?.cwd ?? EVALS_ROOT, + timeout: opts?.timeoutMs ?? 120_000, + maxBuffer: 256 * 1024 * 1024, + encoding: 'utf8', + }, + (error, stdout, stderr) => { + const code = + error && typeof (error as { code?: unknown }).code === 'number' + ? ((error as { code: number }).code as number) + : error + ? 1 + : 0; + resolve({ code, stdout: String(stdout), stderr: String(stderr) }); + } + ); + }), + fetch: (...args) => fetch(...args), + resolveHost: async (host) => { + try { + await lookup(host); + return true; + } catch { + return false; + } + }, +}; + +const DECISIONS = new Set([ + 'hookdeck-cli-pin', + 'agent-cli-pins', + 'skills-pin', + 'model-ids', + 'base-prompt', +]); + +function result( + id: CheckId, + status: CheckStatus, + summary: string, + details: string[] = [] +): CheckResult { + const meta = CHECKS.find((c) => c.id === id); + if (!meta) throw new Error(`no check ${id}`); + return { + id, + number: meta.number, + title: meta.title, + kind: DECISIONS.has(id) ? 'decision' : 'assertion', + status, + summary, + details, + }; +} + +/** Everything several checks read, gathered once. */ +interface Context { + deps: Deps; + args: PreflightArgs; + repo: string; + headSha: string; + dirty: boolean; + dispatchSha?: string; + lastRelease?: string; + workflow: string; + experiments: Array<{ + name: string; + agent: string; + provider?: string; + model?: string; + suites: string[]; + }>; + cells: PlannedPair[]; + /** Experiments the requested matrix runs; all of them when it runs none. */ + experimentsInPlan: Set; + agentsInPlan: Set; + evalsRequiringOutpost: string[]; + latest?: { + results: Array>; + composition?: { runs?: Array<{ runId: string; latest: string }> }; + runId?: string; + }; + skills: { slug: string; pin?: string; names: string[]; dirs: string[] }; +} + +async function sh(ctx: { deps: Deps }, cmd: string, args: string[]) { + const r = await ctx.deps.exec(cmd, args); + if (r.code !== 0) { + throw new Error( + `${cmd} ${args.slice(0, 3).join(' ')} exited ${r.code}: ${r.stderr.trim().slice(0, 300)}` + ); + } + return r.stdout; +} + +async function ghJson(ctx: { deps: Deps }, args: string[]): Promise { + return JSON.parse(await sh(ctx, 'gh', args)) as T; +} + +/** A file at a commit: local objects first, the GitHub API when absent. */ +async function fileAt( + ctx: Context, + ref: string, + path: string +): Promise { + const local = await ctx.deps.exec('git', ['show', `${ref}:${path}`]); + if (local.code === 0) return local.stdout; + const remote = await ctx.deps.exec('gh', [ + 'api', + `repos/${ctx.repo}/contents/${path}?ref=${ref}`, + '-H', + 'Accept: application/vnd.github.raw', + ]); + return remote.code === 0 ? remote.stdout : undefined; +} + +function repoSlug(remoteUrl: string): string { + const m = /github\.com[:/]([^/]+\/[^/.\s]+)(?:\.git)?\s*$/.exec(remoteUrl); + if (!m) throw new Error(`cannot read a GitHub repo from ${remoteUrl}`); + return m[1] as string; +} + +async function buildContext(deps: Deps, args: PreflightArgs): Promise { + const base = { deps }; + const repo = repoSlug(await sh(base, 'git', ['remote', 'get-url', 'origin'])); + const headSha = (await sh(base, 'git', ['rev-parse', 'HEAD'])).trim(); + const dirty = + (await sh(base, 'git', ['status', '--porcelain'])).trim().length > 0; + const dispatch = await deps.exec('gh', [ + 'api', + `repos/${repo}/commits/main`, + '--jq', + '.sha', + ]); + const release = await deps.exec('gh', [ + 'release', + 'list', + '--exclude-drafts', + '--limit', + '1', + '--json', + 'tagName', + '--jq', + '.[0].tagName', + ]); + + const workflow = readFileSync( + join(deps.root, '.github/workflows/eval-refresh.yml'), + 'utf8' + ); + + const loaded = await loadExperiments(deps.root); + const experiments = loaded.map(({ name, config }) => ({ + name, + agent: config.agent.id, + provider: config.agent.metadata?.modelProvider, + model: config.agent.metadata?.modelId, + suites: [...(config.suite ?? [])], + })); + const evals = discoverEvals(deps.root); + const cells = planCells( + evals.map((e) => ({ + id: e.id, + suite: e.suite, + metadata: e.metadata as never, + })), + loaded.map(({ name, config }) => ({ + name, + suites: [...(config.suite ?? [])], + skipEval: config.skipEval as never, + })), + args.dispatch + ); + const experimentsInPlan = new Set( + cells.length > 0 + ? cells.map((c) => c.experiment) + : loaded.map((e) => e.name) + ); + const agentsInPlan = new Set( + experiments.filter((e) => experimentsInPlan.has(e.name)).map((e) => e.agent) + ); + const plannedEvals = new Set(cells.map((c) => c.eval)); + const evalsRequiringOutpost = evals + .filter( + (e) => + plannedEvals.has(e.id) && + (e.metadata.requires ?? []).some((r) => String(r) === 'outpost') + ) + .map((e) => e.id); + + const latestPath = join(deps.root, 'results/latest.json'); + const latest = existsSync(latestPath) + ? (JSON.parse(readFileSync(latestPath, 'utf8')) as Context['latest']) + : undefined; + + // The pinned skills are what `skills/` links into the submodule. + const gitmodules = readFileSync(join(deps.root, '.gitmodules'), 'utf8'); + const slug = repoSlug( + /url\s*=\s*(\S+agent-skills\S*)/.exec(gitmodules)?.[1] ?? + 'https://github.com/hookdeck/agent-skills.git' + ); + const tree = await deps.exec('git', [ + 'ls-tree', + 'HEAD', + 'submodules/agent-skills', + ]); + const pin = /\bcommit\s+([0-9a-f]{40})\b/.exec(tree.stdout)?.[1]; + const names: string[] = []; + const dirs: string[] = []; + const skillsDir = join(deps.root, 'skills'); + for (const name of existsSync(skillsDir) ? readdirSync(skillsDir) : []) { + let target: string; + try { + target = readlinkSync(join(skillsDir, name)); + } catch { + continue; + } + const m = /submodules\/agent-skills\/(.+)$/.exec(target); + if (!m) continue; + names.push(name); + dirs.push((m[1] as string).replace(/\/$/, '')); + } + + return { + deps, + args, + repo, + headSha, + dirty, + dispatchSha: dispatch.code === 0 ? dispatch.stdout.trim() : undefined, + lastRelease: + release.code === 0 && release.stdout.trim() + ? release.stdout.trim() + : undefined, + workflow, + experiments, + cells, + experimentsInPlan, + agentsInPlan, + evalsRequiringOutpost, + latest, + skills: { slug, pin, names, dirs }, + }; +} + +async function npmLatest(ctx: Context, pkg: string): Promise { + const res = await ctx.deps.fetch( + `https://registry.npmjs.org/${pkg.replace('/', '%2F')}/latest` + ); + if (!res.ok) throw new Error(`npm ${pkg}: HTTP ${res.status}`); + return ((await res.json()) as { version: string }).version; +} + +function gapStatus(current: string, latest: string): CheckStatus { + return compareSemver(current, latest) < 0 ? 'decide' : 'pass'; +} + +// 1 --------------------------------------------------------------------------- + +async function checkHookdeckCli(ctx: Context): Promise { + const latest = await npmLatest(ctx, 'hookdeck-cli'); + const details = [ + `pinned: ${HOOKDECK_CLI_VERSION} (packages/sandbox/src/image.ts)`, + `npm latest: ${latest}`, + ]; + if (ctx.lastRelease) { + const source = await fileAt( + ctx, + ctx.lastRelease, + 'packages/sandbox/src/image.ts' + ); + const then = source && readPin(source, 'HOOKDECK_CLI_VERSION'); + if (then) details.push(`pinned at ${ctx.lastRelease}: ${then}`); + } + details.push( + 'a bump changes the product under test: results either side are not comparable' + ); + return result( + 'hookdeck-cli-pin', + gapStatus(HOOKDECK_CLI_VERSION, latest), + describeVersionGap(HOOKDECK_CLI_VERSION, latest), + details + ); +} + +// 2 --------------------------------------------------------------------------- + +async function checkAgentClis(ctx: Context): Promise { + const pins = registeredAgentPins().filter((p) => ctx.agentsInPlan.has(p.id)); + const details: string[] = []; + let behind = 0; + for (const pin of pins) { + const latest = await npmLatest(ctx, pin.cliPackage); + if (compareSemver(pin.defaultCliVersion, latest) < 0) behind += 1; + let then = ''; + if (ctx.lastRelease) { + const source = await fileAt( + ctx, + ctx.lastRelease, + `packages/core/src/agents/${pin.id}/runner.ts` + ); + const v = source && readPin(source, 'defaultCliVersion'); + if (v) then = `; pinned at ${ctx.lastRelease}: ${v}`; + } + details.push( + `${pin.cliPackage}: ${describeVersionGap(pin.defaultCliVersion, latest)}${then}` + ); + } + details.push( + 'a bump changes the transcript format the parser reads: re-check the parser' + ); + return result( + 'agent-cli-pins', + behind > 0 ? 'decide' : 'pass', + behind > 0 + ? `${behind} of ${pins.length} behind npm latest` + : `all ${pins.length} at npm latest`, + details + ); +} + +// 3 --------------------------------------------------------------------------- + +async function checkSkillsPin(ctx: Context): Promise { + const { slug, pin, names } = ctx.skills; + if (!pin) { + return result( + 'skills-pin', + 'warn', + 'no submodules/agent-skills gitlink at HEAD' + ); + } + const main = ( + await sh(ctx, 'gh', ['api', `repos/${slug}/commits/main`, '--jq', '.sha']) + ).trim(); + if (main === pin) { + return result('skills-pin', 'pass', `at ${slug} main (${pin.slice(0, 7)})`); + } + const compare = await ghJson<{ + ahead_by: number; + behind_by: number; + files?: Array<{ filename: string }>; + }>(ctx, ['api', `repos/${slug}/compare/${pin}...${main}`]); + const changed = changedSkills((compare.files ?? []).map((f) => f.filename)); + const pinnedChanged = changed.filter((s) => names.includes(s)); + const details = [ + `pinned: ${pin.slice(0, 7)}; main: ${main.slice(0, 7)}`, + `skills changed between them: ${changed.length > 0 ? changed.join(', ') : 'none'}`, + `of the skills this repo installs (${names.join(', ')}): ${pinnedChanged.length > 0 ? pinnedChanged.join(', ') : 'none changed'}`, + 'a move alters what a skills arm reads and nothing a baseline arm sees', + ]; + return result( + 'skills-pin', + 'decide', + `${compare.ahead_by} commit${compare.ahead_by === 1 ? '' : 's'} behind ${slug} main`, + details + ); +} + +// 4 --------------------------------------------------------------------------- + +async function listModels( + ctx: Context, + provider: string +): Promise { + if (provider === 'anthropic') { + const key = ctx.deps.env.ANTHROPIC_API_KEY; + if (!key) return 'ANTHROPIC_API_KEY not set'; + const ids: string[] = []; + let after: string | undefined; + for (;;) { + const res = await ctx.deps.fetch( + `https://api.anthropic.com/v1/models?limit=1000${after ? `&after_id=${after}` : ''}`, + { headers: { 'x-api-key': key, 'anthropic-version': '2023-06-01' } } + ); + if (!res.ok) return `Anthropic models list: HTTP ${res.status}`; + const page = (await res.json()) as { + data: Array<{ id: string }>; + has_more?: boolean; + last_id?: string; + }; + ids.push(...page.data.map((m) => m.id)); + if (!page.has_more || !page.last_id) return ids; + after = page.last_id; + } + } + if (provider === 'openai') { + const key = ctx.deps.env.OPENAI_API_KEY; + if (!key) return 'OPENAI_API_KEY not set'; + const res = await ctx.deps.fetch('https://api.openai.com/v1/models', { + headers: { Authorization: `Bearer ${key}` }, + }); + if (!res.ok) return `OpenAI models list: HTTP ${res.status}`; + return ((await res.json()) as { data: Array<{ id: string }> }).data.map( + (m) => m.id + ); + } + return `no models list for provider ${provider}`; +} + +async function checkModelIds(ctx: Context): Promise { + const byProvider = new Map>(); + for (const e of ctx.experiments) { + if (!ctx.experimentsInPlan.has(e.name) || !e.model || !e.provider) continue; + const models = byProvider.get(e.provider) ?? new Map(); + models.set(e.model, [...(models.get(e.model) ?? []), e.name]); + byProvider.set(e.provider, models); + } + const details: string[] = []; + let decide = false; + let unknown = false; + for (const [provider, models] of [...byProvider].sort()) { + const listed = await listModels(ctx, provider); + for (const [model, experiments] of [...models].sort()) { + const who = `${model} (${experiments.join(', ')})`; + if (typeof listed === 'string') { + unknown = true; + details.push(`${who}: not checked, ${listed}`); + continue; + } + const s = modelStanding(model, listed); + const parts = [s.listed ? 'listed' : 'NOT in the models list']; + if (!s.listed && s.variants.length > 0) { + parts.push(`variants listed: ${s.variants.join(', ')}`); + } + if (s.newer.length > 0) + parts.push(`newer in family: ${s.newer.join(', ')}`); + if (!s.listed || s.newer.length > 0) decide = true; + details.push(`${who}: ${parts.join('; ')}`); + } + } + details.push( + "newer-in-family is read from version numbers in the ids, a heuristic; the list itself is the provider's" + ); + return result( + 'model-ids', + decide ? 'decide' : unknown ? 'warn' : 'pass', + decide + ? 'a model is unlisted or has a newer sibling' + : unknown + ? 'could not read every models list' + : 'every model is listed and newest in its family', + details + ); +} + +// 5 --------------------------------------------------------------------------- + +async function checkBasePrompt(ctx: Context): Promise { + const current = basePromptFor('tools'); + if (!ctx.lastRelease) { + return result( + 'base-prompt', + 'warn', + 'no published release to compare with' + ); + } + const then = + extractBasePrompt( + (await fileAt( + ctx, + ctx.lastRelease, + 'apps/framework/lib/base-prompt.ts' + )) ?? '' + ) ?? + extractBasePrompt( + (await fileAt( + ctx, + ctx.lastRelease, + 'apps/framework/harness/run-eval.ts' + )) ?? '' + ); + if (then === undefined) { + return result( + 'base-prompt', + 'warn', + `could not read the base prompt at ${ctx.lastRelease}` + ); + } + if (then === current) { + return result('base-prompt', 'pass', `unchanged since ${ctx.lastRelease}`); + } + return result( + 'base-prompt', + 'decide', + `changed since ${ctx.lastRelease}: every cell moves at once`, + [ + `at ${ctx.lastRelease}: ${JSON.stringify(then)}`, + `now: ${JSON.stringify(current)}`, + ] + ); +} + +// 6 --------------------------------------------------------------------------- + +async function checkProviderKeys(ctx: Context): Promise { + const probes = providerProbes(ctx.workflow); + if (probes.length === 0) { + return result( + 'provider-keys', + 'fail', + 'found no provider requests in the workflow preflight step to repeat' + ); + } + const refusal = refusalPattern(ctx.workflow); + const details: string[] = []; + let failed = 0; + for (const probe of probes) { + const headers: Record = {}; + const missing: string[] = []; + for (const [name, template] of Object.entries(probe.headers)) { + const filled = fillTemplate(template, ctx.deps.env); + missing.push(...filled.missing); + headers[name] = filled.value; + } + const label = `${probe.provider} (${probe.model ?? 'no model'})`; + if (missing.length > 0) { + failed += 1; + details.push(`${label}: ${missing.join(', ')} not set in .env`); + continue; + } + const res = await ctx.deps.fetch(probe.url, { + method: 'POST', + headers, + body: probe.body, + }); + const text = await res.text(); + if (res.status === 200) { + details.push(`${label}: HTTP 200`); + continue; + } + failed += 1; + const matched = refusal ? refusal.exec(text)?.[0] : undefined; + details.push( + `${label}: HTTP ${res.status}` + + (matched ? ` (refusing: ${matched})` : '') + + ` ${text.slice(0, 200).replace(/\s+/g, ' ')}` + ); + } + details.push( + 'these are the keys in your .env; the workflow repeats this against the repository secrets before its matrix' + ); + return result( + 'provider-keys', + failed > 0 ? 'fail' : 'pass', + failed > 0 + ? `${failed} of ${probes.length} providers refused a real completion` + : `${probes.length} providers answered a real completion`, + details + ); +} + +// 7 --------------------------------------------------------------------------- + +function spendEstimate(ctx: Context): SpendEstimate | string { + const costs = parseCostTable( + readFileSync(join(ctx.deps.root, 'AGENTS.md'), 'utf8') + ); + if (!costs) return 'could not find the per-pass cost table in AGENTS.md'; + const failRates = failRatesFromRows( + (ctx.latest?.results ?? []) as Array<{ + experiment?: string; + passed?: boolean; + attempts?: number; + }> + ); + return estimateSpend(ctx.cells, costs, failRates); +} + +async function checkSpend(ctx: Context): Promise { + const estimate = spendEstimate(ctx); + if (typeof estimate === 'string') return result('spend', 'fail', estimate); + if (ctx.cells.length === 0) { + return result('spend', 'fail', 'the requested matrix has no cells'); + } + const details = [ + `${ctx.cells.length} cells, ${ctx.args.dispatch.runs} attempt${ctx.args.dispatch.runs === 1 ? '' : 's'} each (min_attempts can raise a scenario's), stopping at the first pass`, + ...estimate.rows.map( + (r) => + `${r.experiment}: ${r.cells} cells x ${dollars(r.perAttempt)}, fail rate ${(r.failRate * 100).toFixed(0)}% (${r.failRateSource}) -> ${dollars(r.low)}-${dollars(r.high)}` + + (r.priced ? '' : ' [NO MEASURED FIGURE: priced at the dearest]') + ), + `every cell once: ${dollars(estimate.firstAttempts)}; expected with retries: ${dollars(estimate.low)}-${dollars(estimate.high)}`, + ...estimate.assumptions.map((a) => `assumes ${a}`), + 'neither provider exposes a balance to a project key: this cannot read one', + ]; + const summary = `estimated ${dollars(estimate.low)}-${dollars(estimate.high)}`; + + if (ctx.args.confirmBalance) { + return result( + 'spend', + 'pass', + `${summary}; balance confirmed by --confirm-balance`, + details + ); + } + if (process.stdin.isTTY && process.stdout.isTTY && !ctx.args.json) { + process.stdout.write( + `\nSpend: ${summary}\n${details.map((d) => ` ${d}`).join('\n')}\n` + ); + const rl = createInterface({ + input: process.stdin, + output: process.stdout, + }); + const answer = await rl.question( + `Do the Anthropic and OpenAI balances both cover ${dollars(estimate.high)}? [y/N] ` + ); + rl.close(); + if (/^y(es)?$/i.test(answer.trim())) { + return result( + 'spend', + 'pass', + `${summary}; balance confirmed interactively`, + details + ); + } + return result( + 'spend', + 'fail', + `${summary}; balance not confirmed`, + details + ); + } + return result( + 'spend', + 'fail', + `${summary}; confirm the balances cover it with --confirm-balance`, + details + ); +} + +// 8 --------------------------------------------------------------------------- + +async function checkSecrets(ctx: Context): Promise { + const wanted = workflowSecrets(ctx.workflow); + const have = new Set( + ( + await ghJson>(ctx, [ + 'secret', + 'list', + '--json', + 'name', + ]) + ).map((s) => s.name) + ); + const missing = wanted.filter((s) => !have.has(s)); + // A missing key for an agent no experiment uses is not a gap in this run: + // the workflow writes it into .env empty and nothing reads it. + const usedAgents = new Set(ctx.experiments.map((e) => e.agent)); + const unneeded = missing.filter((name) => { + const agents = registeredAgentPins().filter((p) => p.apiKeyEnvVar === name); + return agents.length > 0 && agents.every((a) => !usedAgents.has(a.id)); + }); + const fatal = missing.filter((m) => !unneeded.includes(m)); + const details = [ + `the workflow reads: ${wanted.join(', ')}`, + ...unneeded.map( + (n) => + `${n} is missing and is the key of an agent no experiment uses, so nothing reads it` + ), + 'names only: GitHub does not return secret values, so liveness is check 6 and the workflow preflight', + ]; + return result( + 'secrets', + fatal.length > 0 ? 'fail' : 'pass', + fatal.length > 0 + ? `missing from the repository: ${fatal.join(', ')}` + : `all ${wanted.length - unneeded.length} needed secrets exist`, + details + ); +} + +// 9 --------------------------------------------------------------------------- + +async function checkMainGreen(ctx: Context): Promise { + const sha = ctx.dispatchSha; + if (!sha) + return result('main-green', 'fail', 'could not read main from GitHub'); + + if (ctx.headSha === sha && !ctx.dirty) { + // Checked out at exactly what a dispatch runs: run the same four commands + // the Checks workflow runs, here. + const commands: Array<[string, string[]]> = [ + ['pnpm', ['format:check']], + ['pnpm', ['typecheck']], + ['pnpm', ['-r', 'test']], + ['pnpm', ['-r', 'build']], + ]; + const details: string[] = []; + let failed = 0; + for (const [cmd, args] of commands) { + const r = await ctx.deps.exec(cmd, args, { timeoutMs: 900_000 }); + details.push( + `${cmd} ${args.join(' ')}: ${r.code === 0 ? 'ok' : `exit ${r.code}`}` + ); + if (r.code !== 0) { + failed += 1; + details.push( + ` ${(r.stdout + r.stderr).trim().split('\n').slice(-5).join(' | ')}` + ); + } + } + return result( + 'main-green', + failed > 0 ? 'fail' : 'pass', + failed > 0 + ? `${failed} of 4 checks fail at main ${sha.slice(0, 7)}` + : `format, typecheck, tests and build pass locally at main ${sha.slice(0, 7)}`, + details + ); + } + + // Not checked out at main: the Checks workflow runs on pull requests only, so + // read the run for the pull request that produced main. + const pulls = await ghJson< + Array<{ number: number; merge_commit_sha: string; head: { sha: string } }> + >(ctx, ['api', `repos/${ctx.repo}/commits/${sha}/pulls`]); + const pr = pulls.find((p) => p.merge_commit_sha === sha); + const why = `HEAD ${ctx.headSha.slice(0, 7)}${ctx.dirty ? ' (dirty)' : ''} is not main ${sha.slice(0, 7)}`; + if (!pr) { + return result( + 'main-green', + 'fail', + `main ${sha.slice(0, 7)} was not merged from a pull request, so no Checks run covers it`, + [why, 'check out main and re-run to run the checks locally'] + ); + } + const runs = await ghJson< + Array<{ + databaseId: number; + conclusion: string; + headSha: string; + event: string; + }> + >(ctx, [ + 'run', + 'list', + '--workflow', + 'biome.yml', + '--commit', + pr.head.sha, + '--json', + 'databaseId,conclusion,headSha,event', + ]); + const run = runs.find((r) => r.event === 'pull_request'); + if (!run) { + return result('main-green', 'fail', `no Checks run for #${pr.number}`, [ + why, + ]); + } + const view = await ghJson<{ + conclusion: string; + jobs: Array<{ steps: Array<{ name: string; conclusion: string }> }>; + }>(ctx, ['run', 'view', String(run.databaseId), '--json', 'conclusion,jobs']); + const steps = view.jobs.flatMap((j) => j.steps); + const wanted = [/format/i, /typecheck/i, /test/i, /build/i]; + const missing = wanted.filter( + (re) => !steps.some((s) => re.test(s.name) && s.conclusion === 'success') + ); + const details = [ + why, + `read from the Checks run on #${pr.number} (run ${run.databaseId}), which tested the pull request merged into its base at the time`, + ...steps + .filter((s) => wanted.some((re) => re.test(s.name))) + .map((s) => `${s.name}: ${s.conclusion}`), + ]; + const ok = view.conclusion === 'success' && missing.length === 0; + return result( + 'main-green', + ok ? 'pass' : 'fail', + ok + ? `#${pr.number}'s Checks passed format, typecheck, tests and build` + : `#${pr.number}'s Checks did not pass every step (${view.conclusion})`, + details + ); +} + +// 10 -------------------------------------------------------------------------- + +async function checkNothingRunning(ctx: Context): Promise { + const runs = await ghJson< + Array<{ + databaseId: number; + status: string; + event: string; + createdAt: string; + url: string; + }> + >(ctx, [ + 'run', + 'list', + '--workflow', + 'eval-refresh.yml', + '--limit', + '30', + '--json', + 'databaseId,status,event,createdAt,url', + ]); + const open = unfinishedRuns(runs); + return result( + 'nothing-running', + open.length > 0 ? 'fail' : 'pass', + open.length > 0 + ? `${open.length} eval-refresh run${open.length === 1 ? '' : 's'} not finished` + : 'no eval-refresh run in progress or pending', + [ + ...open.map( + (r) => + `${r.databaseId} ${r.status} (${r.event}, ${r.createdAt}) ${r.url}` + ), + 'the concurrency group cancels a third dispatch, and overlapping merge runs publish against stale results (#127)', + ] + ); +} + +// 11 -------------------------------------------------------------------------- + +async function checkVariables(ctx: Context): Promise { + const vars = new Map( + ( + await ghJson>(ctx, [ + 'variable', + 'list', + '--json', + 'name,value', + ]) + ).map((v) => [v.name, v.value]) + ); + const problems: string[] = []; + const details: string[] = []; + + const publish = vars.get('EVALS_PUBLISH'); + const publishing = publish !== 'false'; + details.push( + `EVALS_PUBLISH: ${publish === undefined ? 'unset' : JSON.stringify(publish)}, so this run ${publishing ? 'publishes' : 'does not publish'}` + ); + if (ctx.args.holdPublish && publishing) { + problems.push('--hold-publish given but EVALS_PUBLISH is not "false"'); + } + if (!ctx.args.holdPublish && !publishing) { + problems.push( + 'EVALS_PUBLISH is "false", so this run would not publish; pass --hold-publish if that is intended, or `gh variable delete EVALS_PUBLISH`' + ); + } + + const fraction = vars.get('EVALS_MAX_MISSING_FRACTION'); + const effective = fraction ?? '0.1'; + details.push( + `EVALS_MAX_MISSING_FRACTION: ${fraction === undefined ? 'unset (0.1)' : JSON.stringify(fraction)}` + ); + if (Number(effective) !== Number(ctx.args.maxMissingFraction)) { + problems.push( + `EVALS_MAX_MISSING_FRACTION resolves to ${effective}, expected ${ctx.args.maxMissingFraction}` + ); + } + + for (const name of workflowVariables(ctx.workflow)) { + if (name === 'EVALS_PUBLISH' || name === 'EVALS_MAX_MISSING_FRACTION') + continue; + details.push( + `${name}: ${vars.has(name) ? JSON.stringify(vars.get(name)) : 'unset'} (read by the workflow)` + ); + } + return result( + 'repo-variables', + problems.length > 0 ? 'fail' : 'pass', + problems.length > 0 + ? problems.join('; ') + : 'variables match what the run intends', + details + ); +} + +// 12 -------------------------------------------------------------------------- + +function describe(r: HookdeckResource): string { + return `${r.id}${r.name ? ` (${r.name})` : ''}`; +} + +async function checkProjects(ctx: Context): Promise { + const fails: string[] = []; + const warns: string[] = []; + const details: string[] = []; + const { env } = ctx.deps; + + // evals-ci: nothing but the declared default issue triggers. + if (!env.HOOKDECK_API_KEY) { + fails.push('HOOKDECK_API_KEY not set in .env: evals-ci not checked'); + } else { + const gateway = new HookdeckClient({ apiKey: env.HOOKDECK_API_KEY }); + for (const kind of RESOURCE_KINDS) { + if (kind === 'issue-triggers') continue; + const rows = await gateway.list(kind); + if (rows.length > 0) { + fails.push( + `evals-ci holds ${rows.length} ${kind}: ${rows.map(describe).join(', ')}` + ); + } + } + const triggers = await gateway.list('issue-triggers'); + const declared = new Set(DEFAULT_ISSUE_TRIGGERS.map((d) => d.type)); + for (const d of DEFAULT_ISSUE_TRIGGERS) { + const ofType = triggers.filter((t) => t.type === d.type); + if (ofType.length === 0) + fails.push(`evals-ci has no ${d.type} issue trigger`); + if (ofType.length > 1) { + fails.push( + `evals-ci has ${ofType.length} ${d.type} issue triggers: ${ofType.map(describe).join(', ')}` + ); + } + for (const t of ofType) { + if (!issueTriggerMatchesDeclared(t, d.configs)) { + fails.push( + `evals-ci ${d.type} trigger ${t.id} differs from DEFAULT_ISSUE_TRIGGERS (configs, channels, name or enabled)` + ); + } + } + } + for (const t of triggers.filter((t) => !declared.has(String(t.type)))) { + fails.push( + `evals-ci has an undeclared ${String(t.type)} issue trigger ${t.id}` + ); + } + details.push( + `evals-ci: ${triggers.length} issue triggers against ${DEFAULT_ISSUE_TRIGGERS.length} declared` + ); + } + + const outpostKey = env.OUTPOST_API_KEY; + const outpostNeeded = ctx.evalsRequiringOutpost.length > 0; + if (!outpostKey) { + (outpostNeeded ? fails : warns).push( + `OUTPOST_API_KEY not set in .env: the Outpost project was not checked${outpostNeeded ? `, and ${ctx.evalsRequiringOutpost.length} planned scenarios need it` : ''}` + ); + } else if (outpostKey === env.HOOKDECK_API_KEY) { + fails.push( + 'OUTPOST_API_KEY is the evals-ci key: it must belong to a dedicated Outpost project (#111)' + ); + } else { + // The Outpost project's Event Gateway side: declared empty. + const declaredKinds = Object.keys(OUTPOST_GATEWAY_PRISTINE.ids); + const og = new HookdeckClient({ apiKey: outpostKey }); + let gatewayCount = 0; + for (const kind of RESOURCE_KINDS) { + const rows = await og.list(kind); + gatewayCount += rows.length; + if (rows.length > 0 && !declaredKinds.includes(kind)) { + fails.push( + `the Outpost project's gateway side holds ${rows.length} ${kind}: ${rows.map(describe).join(', ')}` + ); + } + } + details.push( + `Outpost project gateway side: ${gatewayCount} resources, declared empty` + ); + + const outpost = new OutpostClient({ apiKey: outpostKey }); + const tenants = await outpost.tenants(); + if (tenants.length > 0) { + fails.push( + `stray Outpost tenants: ${tenants.map((t) => t.id).join(', ')}` + ); + } + details.push(`Outpost tenants: ${tenants.length}`); + + const destinations = await operatorEventDestinations(outpost); + const enabled = destinations.filter((d) => !d.disabled_at); + if (enabled.length === 0) { + fails.push( + `no enabled operator event destination (${destinations.length} disabled): nothing hears a failure` + ); + } + for (const d of enabled) { + const verdict = await destinationTarget(ctx, d, [ + env.HOOKDECK_API_KEY, + outpostKey, + ]); + details.push( + `operator event destination ${d.id} (${d.type}, ${(d.topics ?? []).join(', ')}): ${verdict.detail}` + ); + if (verdict.status === 'fail') + fails.push(`operator event destination ${d.id}: ${verdict.detail}`); + if (verdict.status === 'warn') + warns.push(`operator event destination ${d.id}: ${verdict.detail}`); + const attempts = await outpost + .request<{ models?: Array<{ status?: string; time?: string }> }>( + 'GET', + `/operator-events/attempts?destination_id=${encodeURIComponent(String(d.id))}&limit=20` + ) + .catch(() => undefined); + const rows = attempts?.models ?? []; + const failed = rows.filter((a) => a.status && a.status !== 'success'); + details.push( + ` last ${rows.length} attempts: ${rows.length - failed.length} succeeded, ${failed.length} did not` + ); + if (failed.length > 0) + warns.push( + `operator event destination ${d.id}: ${failed.length} recent attempts did not succeed` + ); + } + } + + details.push(...warns.map((w) => `warning: ${w}`)); + return result( + 'projects-pristine', + fails.length > 0 ? 'fail' : warns.length > 0 ? 'warn' : 'pass', + fails.length > 0 + ? fails.join('; ') + : warns.length > 0 + ? 'pristine, with something that could not be verified' + : 'both projects are pristine', + details + ); +} + +async function operatorEventDestinations( + outpost: OutpostClient +): Promise { + try { + const rows = await outpost.request< + OperatorEventDestination[] | { models?: OperatorEventDestination[] } + >('GET', '/operator-events/destinations'); + return Array.isArray(rows) ? rows : (rows.models ?? []); + } catch (error) { + // A project that has never had one answers 404 "tenant not found". + if (String((error as Error).message).includes('404')) return []; + throw error; + } +} + +const HOOKDECK_SOURCE_HOSTS = new Set(['hkdk.events', 'events.hookdeck.com']); + +/** + * Whether a destination's URL is somewhere that exists, without sending it + * anything: a request to a Hookdeck source URL is ingested and recorded in + * whichever project owns it, which is a write. + */ +async function destinationTarget( + ctx: Context, + d: OperatorEventDestination, + keys: Array +): Promise<{ status: 'pass' | 'warn' | 'fail'; detail: string }> { + const raw = d.config?.url; + if (d.type !== 'webhook' || typeof raw !== 'string') { + return { + status: 'warn', + detail: `type ${d.type}: only webhook destinations are checked`, + }; + } + let url: URL; + try { + url = new URL(raw); + } catch { + return { status: 'fail', detail: `URL does not parse: ${raw}` }; + } + if (url.host === 'mock.hookdeck.com') { + return { + status: 'fail', + detail: `delivers to a mock endpoint (${url.host}), which is a scenario's, not an alert destination`, + }; + } + if (HOOKDECK_SOURCE_HOSTS.has(url.host)) { + for (const key of keys) { + if (!key) continue; + const sources = await new HookdeckClient({ apiKey: key }).list('sources'); + const owner = sources.find((s) => s.url === raw); + if (owner) + return { status: 'pass', detail: `Hookdeck source ${describe(owner)}` }; + } + return { + status: 'warn', + detail: `${raw} is a Hookdeck source in a project neither key can see; confirm it exists in the dashboard`, + }; + } + return (await ctx.deps.resolveHost(url.hostname)) + ? { status: 'pass', detail: `${url.host} resolves` } + : { status: 'fail', detail: `${url.host} does not resolve` }; +} + +// 13 -------------------------------------------------------------------------- + +async function pinnedSkillFiles( + ctx: Context +): Promise> { + const { slug, pin, dirs } = ctx.skills; + if (!pin) throw new Error('no skills pin at HEAD'); + const sub = join(ctx.deps.root, 'submodules/agent-skills'); + const files: Array<{ path: string; text: string }> = []; + const textFile = /\.(md|mdx|mdc|txt|ya?ml|json)$/i; + + const hasLocal = + existsSync(join(sub, '.git')) && + ( + await ctx.deps.exec('git', [ + '-C', + sub, + 'cat-file', + '-e', + `${pin}^{commit}`, + ]) + ).code === 0; + if (hasLocal) { + const list = await sh(ctx, 'git', [ + '-C', + sub, + 'ls-tree', + '-r', + '--name-only', + pin, + '--', + ...dirs, + ]); + for (const path of list.split('\n').filter((p) => textFile.test(p))) { + files.push({ + path, + text: await sh(ctx, 'git', ['-C', sub, 'show', `${pin}:${path}`]), + }); + } + return files; + } + + // Not checked out here: read the pinned tree from GitHub. + const tree = await ghJson<{ tree: Array<{ path: string; type: string }> }>( + ctx, + ['api', `repos/${slug}/git/trees/${pin}?recursive=1`] + ); + const paths = tree.tree + .filter((t) => t.type === 'blob' && textFile.test(t.path)) + .map((t) => t.path) + .filter((p) => dirs.some((d) => p.startsWith(`${d}/`))); + await pool(paths, 8, async (path) => { + const res = await ctx.deps.fetch( + `https://raw.githubusercontent.com/${slug}/${pin}/${path}` + ); + if (!res.ok) + throw new Error(`${path} at ${pin.slice(0, 7)}: HTTP ${res.status}`); + files.push({ path, text: await res.text() }); + }); + return files; +} + +async function pool( + items: T[], + size: number, + fn: (item: T) => Promise +) { + let next = 0; + await Promise.all( + Array.from({ length: Math.min(size, items.length) }, async () => { + while (next < items.length) { + const item = items[next++] as T; + await fn(item); + } + }) + ); +} + +async function linkStatus(ctx: Context, url: string): Promise { + for (let attempt = 0; attempt < 2; attempt++) { + try { + const res = await ctx.deps.fetch(url, { + redirect: 'follow', + signal: AbortSignal.timeout(20_000), + }); + await res.body?.cancel(); + return res.status; + } catch { + // One retry for a dropped connection; a second failure is reported as 0. + } + } + return 0; +} + +async function checkSkillLinks(ctx: Context): Promise { + const files = await pinnedSkillFiles(ctx); + const links = collectLinks(files); + const bad: Array<{ url: string; status: number; files: string[] }> = []; + await pool(links, 6, async (link) => { + const status = await linkStatus(ctx, link.url); + if (status !== 200) bad.push({ ...link, status }); + }); + bad.sort((a, b) => a.url.localeCompare(b.url)); + return result( + 'skill-links', + bad.length > 0 ? 'fail' : 'pass', + bad.length > 0 + ? `${bad.length} of ${links.length} docs URLs in the pinned skills do not return 200` + : `all ${links.length} docs URLs in the pinned skills return 200`, + [ + `skills ${ctx.skills.names.join(', ')} at ${ctx.skills.pin?.slice(0, 7)}, ${files.length} files`, + ...bad.map( + (b) => + `${b.status || 'no response'} ${b.url} (in ${b.files.join(', ')})` + ), + ] + ); +} + +// 14 -------------------------------------------------------------------------- + +async function checkHarnessIssues(ctx: Context): Promise { + const issues = await ghJson>(ctx, [ + 'issue', + 'list', + '--label', + 'harness', + '--state', + 'open', + '--limit', + '200', + '--json', + 'number,title', + ]); + const accepted = new Set(ctx.args.acceptHarness); + const open = issues.filter((i) => !accepted.has(i.number)); + return result( + 'harness-issues', + open.length > 0 ? 'fail' : 'pass', + open.length > 0 + ? `${open.length} open harness issue${open.length === 1 ? '' : 's'} neither fixed nor accepted; accept by name with --accept-harness ${open.map((i) => i.number).join(',')}` + : `${issues.length} open harness issues, every one accepted for this run`, + issues.map( + (i) => + `#${i.number} (${i.title})${accepted.has(i.number) ? ': accepted' : ''}` + ) + ); +} + +// 15 -------------------------------------------------------------------------- + +async function publishedInstrument( + ctx: Context +): Promise<{ instrument: Instrument; source: string }> { + const runs = ctx.latest?.composition?.runs ?? []; + const newest = [...runs].sort((a, b) => b.latest.localeCompare(a.latest))[0]; + const runId = newest?.runId ?? ctx.latest?.runId; + const models: Record = {}; + for (const row of ctx.latest?.results ?? []) { + const experiment = row.experiment as string | undefined; + const display = row.experimentDisplay as { modelId?: string } | undefined; + if (!experiment || !display?.modelId) continue; + // Prefer the newest run's row when an experiment's rows disagree. + if (models[experiment] === undefined || row.runId === runId) { + models[experiment] = display.modelId; + } + } + if (!runId) + return { + instrument: { agentClis: {}, models }, + source: 'no published run', + }; + const view = await ghJson<{ headSha: string }>(ctx, [ + 'run', + 'view', + runId, + '--json', + 'headSha', + ]); + const sha = view.headSha; + const dockerfile = await fileAt(ctx, sha, 'packages/sandbox/Dockerfile'); + const image = await fileAt(ctx, sha, 'packages/sandbox/src/image.ts'); + const agentClis: Record = {}; + for (const agent of ctx.agentsInPlan) { + const src = await fileAt( + ctx, + sha, + `packages/core/src/agents/${agent}/runner.ts` + ); + agentClis[agent] = src ? readPin(src, 'defaultCliVersion') : undefined; + } + return { + instrument: { + imageDefinition: dockerfile + ? sandboxImageDefinition(dockerfile) + : undefined, + hookdeckCli: image ? readPin(image, 'HOOKDECK_CLI_VERSION') : undefined, + agentClis, + models, + }, + source: `run ${runId} at ${sha.slice(0, 7)}`, + }; +} + +async function checkCanary(ctx: Context): Promise { + const current: Instrument = { + imageDefinition: sandboxImageDefinition(), + hookdeckCli: HOOKDECK_CLI_VERSION, + agentClis: Object.fromEntries( + registeredAgentPins() + .filter((p) => ctx.agentsInPlan.has(p.id)) + .map((p) => [p.id, p.defaultCliVersion]) + ), + models: Object.fromEntries( + ctx.experiments + .filter((e) => ctx.experimentsInPlan.has(e.name)) + .map((e) => [e.name, e.model]) + ), + }; + const { instrument, source } = await publishedInstrument(ctx); + const changes = diffInstrument(instrument, current); + if (changes.length === 0) { + return result( + 'canary', + 'pass', + `not required: image, CLI pins and models match ${source}` + ); + } + const details = [ + `against the newest published rows (${source}):`, + ...changes.map((c) => ` ${c.what}: ${c.published} -> ${c.current}`), + ]; + + if (ctx.args.canaryRun) { + const verdict = await verifyCanary(ctx, ctx.args.canaryRun); + return result( + 'canary', + verdict.problems.length > 0 ? 'fail' : 'pass', + verdict.problems.length > 0 + ? `canary run ${ctx.args.canaryRun} does not clear the change: ${verdict.problems.join('; ')}` + : `canary run ${ctx.args.canaryRun} clears the change`, + [...details, ...verdict.details] + ); + } + + // One Claude and one Codex cell, preferring an experiment whose model moved. + const changed = new Set( + changes.map((c) => /^(.+) model$/.exec(c.what)?.[1]).filter(Boolean) + ); + const pick = (agent: string) => + ctx.experiments + .filter((e) => e.agent === agent) + .sort( + (a, b) => + Number(changed.has(b.name)) - Number(changed.has(a.name)) || + Number(b.suites.includes('benchmark')) - + Number(a.suites.includes('benchmark')) || + a.name.localeCompare(b.name) + )[0]; + const chosen = [pick('claude-code'), pick('codex')].filter( + (e): e is NonNullable => e !== undefined + ); + const suites = chosen.map((e) => + e.suites.includes('benchmark') + ? 'benchmark' + : e.suites.includes('no-skills') + ? 'no-skills' + : (e.suites[0] ?? 'benchmark') + ); + const plan = canaryPlan( + chosen.map((e) => e.name), + ctx.args.canaryEval, + 'benchmark', + suites + ); + return result( + 'canary', + 'fail', + 'the instrument moved: a two-cell canary with EVALS_PUBLISH=false is required before the matrix', + [ + ...details, + 'run:', + ...plan.commands.map((c) => ` ${c}`), + 'it passes when:', + ...CANARY_CRITERIA.map((c) => ` - ${c}`), + ] + ); +} + +async function verifyCanary( + ctx: Context, + runId: string +): Promise<{ problems: string[]; details: string[] }> { + const problems: string[] = []; + const details: string[] = []; + const view = await ghJson<{ + conclusion: string; + headSha: string; + jobs: Array<{ + name: string; + conclusion: string; + steps: Array<{ name: string; conclusion: string }>; + }>; + }>(ctx, ['run', 'view', runId, '--json', 'conclusion,headSha,jobs']); + if (view.conclusion !== 'success') + problems.push(`run concluded ${view.conclusion || 'unfinished'}`); + if (ctx.dispatchSha && view.headSha !== ctx.dispatchSha) { + problems.push( + `ran at ${view.headSha.slice(0, 7)}, not main ${ctx.dispatchSha.slice(0, 7)}` + ); + } + const cells = view.jobs.filter((j) => j.name.startsWith('run-evals')); + for (const agent of ['claude-code', 'codex']) { + if (!cells.some((j) => j.name.includes(agent))) + problems.push(`no ${agent} cell`); + } + for (const job of cells) { + for (const step of ['Run evals', 'Check artifacts for credentials']) { + const s = job.steps.find((x) => x.name === step); + if (s?.conclusion !== 'success') { + problems.push(`${job.name}: ${step} ${s?.conclusion ?? 'did not run'}`); + } + } + } + const publish = view.jobs.find((j) => j.name.startsWith('publish-results')); + if (publish && publish.conclusion !== 'skipped') { + problems.push( + `publish-results ${publish.conclusion}: publishing was not held` + ); + } + const log = await ctx.deps.exec('gh', ['run', 'view', runId, '--log']); + if (log.stdout.includes(SANDBOX_SELF_CHECK_FAILED)) + problems.push('a cell failed the sandbox self-check'); + + const dir = mkdtempSync(join(tmpdir(), 'preflight-canary-')); + try { + await sh(ctx, 'gh', [ + 'run', + 'download', + runId, + '-p', + 'raw-results-*', + '-D', + dir, + ]); + let rows = 0; + for (const file of walkJson(dir)) { + const row = JSON.parse(readFileSync(file, 'utf8')) as RowLike & { + eval?: string; + experiment?: string; + }; + if (!row.transcript && !row.toolCalls) continue; + rows += 1; + const evidence = pinnedCliEvidence(shellActivity(row)); + const flags = evidence ? pinnedCliFlags(evidence) : []; + for (const f of flags.filter( + (f) => f.label === 'PINNED CLI NOT ON PATH' + )) { + problems.push(`${row.experiment} x ${row.eval}: ${f.label}`); + } + } + details.push(`read ${rows} raw result rows from the canary's artifacts`); + if (rows === 0) problems.push('no raw results in the canary artifacts'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + return { problems, details }; +} + +function* walkJson(dir: string): Generator { + for (const entry of readdirSync(dir)) { + const full = join(dir, entry); + if (statSync(full).isDirectory()) yield* walkJson(full); + else if (entry.endsWith('.json')) yield full; + } +} + +// ----------------------------------------------------------------------------- + +const RUNNERS: Record Promise> = { + 'hookdeck-cli-pin': checkHookdeckCli, + 'agent-cli-pins': checkAgentClis, + 'skills-pin': checkSkillsPin, + 'model-ids': checkModelIds, + 'base-prompt': checkBasePrompt, + 'provider-keys': checkProviderKeys, + spend: checkSpend, + secrets: checkSecrets, + 'main-green': checkMainGreen, + 'nothing-running': checkNothingRunning, + 'repo-variables': checkVariables, + 'projects-pristine': checkProjects, + 'skill-links': checkSkillLinks, + 'harness-issues': checkHarnessIssues, + canary: checkCanary, +}; + +async function guarded(ctx: Context, id: CheckId): Promise { + if (ctx.args.skip.includes(id)) { + return result(id, 'skipped', 'SKIPPED BY --skip: not checked'); + } + try { + return await RUNNERS[id](ctx); + } catch (error) { + // A check that cannot run has not passed. A decision that cannot run has + // nothing to decide, so it warns instead. + return result( + id, + DECISIONS.has(id) ? 'warn' : 'fail', + `could not run: ${(error as Error).message}` + ); + } +} + +export async function runPreflight( + argv: string[], + deps: Deps = realDeps +): Promise<{ output: string; code: number }> { + const args = parsePreflightArgs(argv); + if (args.help) return { output: USAGE, code: 0 }; + const ctx = await buildContext(deps, args); + + // Spend last and alone, because it may ask a question on the terminal. + const ids = CHECKS.map((c) => c.id).filter((id) => id !== 'spend'); + const results = await Promise.all(ids.map((id) => guarded(ctx, id))); + results.push(await guarded(ctx, 'spend')); + + const notes: string[] = []; + if (ctx.dispatchSha && ctx.headSha !== ctx.dispatchSha) { + notes.push( + `pins, experiments and the base prompt were read from HEAD, which is not what a dispatch runs; check out main for a preflight that describes the dispatch` + ); + } + if (ctx.dirty) notes.push('the working tree has uncommitted changes'); + notes.push( + `matrix: ${ctx.cells.length} cells (suites ${args.dispatch.suites.join(',')}; experiment suites ${args.dispatch.experimentSuites.join(',')}${args.dispatch.experiments.length ? `; experiments ${args.dispatch.experiments.join(',')}` : ''}${args.dispatch.evalIds.length ? `; evals ${args.dispatch.evalIds.join(',')}` : ''}; runs ${args.dispatch.runs})` + ); + + const meta = { + generatedAt: new Date().toISOString(), + headSha: ctx.headSha, + dispatchSha: ctx.dispatchSha, + skipped: args.skip, + notes, + }; + const code = exitCodeFor(results); + const secrets = collectEnvSecretValues(); + const text = args.json + ? JSON.stringify({ ...meta, exitCode: code, results }, null, 2) + : formatReport(results, meta); + return { output: maskSecrets(redactSecrets(text), secrets), code }; +} + +async function main() { + try { + const { output, code } = await runPreflight(process.argv.slice(2)); + console.log(output); + process.exitCode = code; + } catch (error) { + console.error(`preflight: ${(error as Error).message}`); + process.exitCode = 2; + } +} + +await main(); diff --git a/apps/framework/test/preflight.test.ts b/apps/framework/test/preflight.test.ts new file mode 100644 index 0000000..0c0221b --- /dev/null +++ b/apps/framework/test/preflight.test.ts @@ -0,0 +1,567 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { basePromptFor, extractBasePrompt } from '../lib/base-prompt.js'; +import { EVALS_ROOT } from '../lib/discovery.js'; +import { CHECKS, parsePreflightArgs } from '../lib/preflight/args.js'; +import { + canaryPlan, + diffInstrument, + readPin, +} from '../lib/preflight/canary.js'; +import { + changedSkills, + collectLinks, + extractDocsUrls, + fetchableUrl, +} from '../lib/preflight/links.js'; +import { attemptsFor, planCells } from '../lib/preflight/matrix.js'; +import { + modelFamily, + modelStanding, + modelVersion, +} from '../lib/preflight/models.js'; +import { + DECISION_FOOTER, + exitCodeFor, + formatReport, + maskSecrets, + type CheckResult, +} from '../lib/preflight/report.js'; +import { + compareSemver, + describeVersionGap, + parseSemver, +} from '../lib/preflight/semver.js'; +import { + attemptMultiplier, + costKey, + estimateSpend, + failRatesFromRows, + parseCostTable, +} from '../lib/preflight/spend.js'; +import { + fillTemplate, + providerProbes, + refusalPattern, + stepScript, + unfinishedRuns, + workflowSecrets, + workflowVariables, +} from '../lib/preflight/workflow.js'; + +const read = (path: string) => readFileSync(join(EVALS_ROOT, path), 'utf8'); +const WORKFLOW = read('.github/workflows/eval-refresh.yml'); + +describe('semver', () => { + it('parses plain and prefixed versions and rejects anything else', () => { + expect(parseSemver('2.5.0')).toEqual({ major: 2, minor: 5, patch: 0 }); + expect(parseSemver('v3.1.0-beta.1')).toEqual({ + major: 3, + minor: 1, + patch: 0, + prerelease: 'beta.1', + }); + expect(parseSemver('latest')).toBeUndefined(); + }); + + it('orders numerically, not lexically, and puts a prerelease first', () => { + expect(compareSemver('2.1.191', '2.1.319')).toBe(-1); + expect(compareSemver('0.138.0', '0.67.0')).toBe(1); + expect(compareSemver('1.0.0-rc.1', '1.0.0')).toBe(-1); + expect(compareSemver('1.0.0', '1.0.0')).toBe(0); + expect(() => compareSemver('x', '1.0.0')).toThrow(/not a version/); + }); + + it('names the largest component that moved', () => { + expect(describeVersionGap('2.5.0', '3.1.0')).toBe( + '1 major version behind (2.5.0 -> 3.1.0)' + ); + expect(describeVersionGap('0.138.0', '0.167.0')).toBe( + '29 minor versions behind (0.138.0 -> 0.167.0)' + ); + expect(describeVersionGap('2.1.191', '2.1.319')).toBe( + '128 patch versions behind (2.1.191 -> 2.1.319)' + ); + expect(describeVersionGap('2.5.0', '2.5.0')).toBe('up to date (2.5.0)'); + expect(describeVersionGap('3.0.0', '2.9.9')).toMatch(/^ahead of latest/); + }); +}); + +describe('workflow parsing, against the real eval-refresh.yml', () => { + it('reads every secret the workflow references, without GITHUB_TOKEN', () => { + const secrets = workflowSecrets(WORKFLOW); + for (const name of [ + 'ANTHROPIC_API_KEY', + 'OPENAI_API_KEY', + 'HOOKDECK_API_KEY', + 'HOOKDECK_WEBHOOK_SECRET', + 'OUTPOST_API_KEY', + ]) { + expect(secrets).toContain(name); + } + expect(secrets).not.toContain('GITHUB_TOKEN'); + }); + + it('ignores names that appear only in comments', () => { + const yaml = [ + '# secrets.ONLY_IN_PROSE is mentioned here', + ' env:', + ' A: ${{ secrets.REAL_ONE }}', + ' B: ${{ vars.SOME_VAR || 1 }}', + ' T: ${{ secrets.GITHUB_TOKEN }}', + ].join('\n'); + expect(workflowSecrets(yaml)).toEqual(['REAL_ONE']); + expect(workflowVariables(yaml)).toEqual(['SOME_VAR']); + }); + + it('reads both repository variables the publish job depends on', () => { + expect(workflowVariables(WORKFLOW)).toEqual( + expect.arrayContaining(['EVALS_PUBLISH', 'EVALS_MAX_MISSING_FRACTION']) + ); + }); + + it('extracts the provider preflight requests the workflow makes', () => { + const probes = providerProbes(WORKFLOW); + expect(probes.map((p) => p.provider).sort()).toEqual([ + 'anthropic', + 'openai', + ]); + const openai = probes.find((p) => p.provider === 'openai'); + expect(openai?.url).toBe('https://api.openai.com/v1/responses'); + expect(openai?.headers.Authorization).toBe('Bearer ${OPENAI_API_KEY}'); + expect(openai?.model).toBeTruthy(); + const anthropic = probes.find((p) => p.provider === 'anthropic'); + expect(anthropic?.headers['x-api-key']).toBe('${ANTHROPIC_API_KEY}'); + expect(JSON.parse(anthropic?.body ?? '{}').max_tokens).toBe(1); + }); + + it('bounds a step at the next step', () => { + const yaml = [ + ' steps:', + ' - name: First', + ' run: echo one', + ' - name: Second', + ' run: echo two', + ].join('\n'); + expect(stepScript(yaml, 'First')).toContain('echo one'); + expect(stepScript(yaml, 'First')).not.toContain('echo two'); + expect(stepScript(yaml, 'Missing')).toBeUndefined(); + }); + + it('fills placeholders and names the missing ones instead of sending empty', () => { + expect(fillTemplate('Bearer ${KEY}', { KEY: 'abc' })).toEqual({ + value: 'Bearer abc', + missing: [], + }); + expect(fillTemplate('Bearer ${KEY}', {}).missing).toEqual(['KEY']); + }); + + it('recognises a refusal in the words the run cancels on', () => { + const re = refusalPattern(WORKFLOW); + expect(re?.test('{"error":{"code":"insufficient_quota"}}')).toBe(true); + expect(re?.test('{"ok":true}')).toBe(false); + }); + + it('treats every unfinished status as running', () => { + const runs = [ + { status: 'completed' }, + { status: 'in_progress' }, + { status: 'queued' }, + { status: 'pending' }, + { status: 'waiting' }, + ]; + expect(unfinishedRuns(runs)).toHaveLength(4); + }); +}); + +describe('spend', () => { + it('reads the measured table out of AGENTS.md', () => { + const table = parseCostTable(read('AGENTS.md')); + expect(table?.denominator).toBe(15); + expect(Object.keys(table?.perPass ?? {}).sort()).toEqual([ + 'claude-code-sonnet-5', + 'codex-gpt-5.4-mini', + 'codex-gpt-5.6', + ]); + expect(table?.judgePerPass).toBeGreaterThan(0); + }); + + it('returns nothing rather than guessing when the table is absent', () => { + expect(parseCostTable('# no table here')).toBeUndefined(); + }); + + it('prices the no-skills twin with its skills arm', () => { + expect(costKey('codex-gpt-5.6-no-skills')).toBe('codex-gpt-5.6'); + }); + + it('pays for a retry only when the attempt before it failed', () => { + expect(attemptMultiplier(0.5, 1, 1)).toBe(1); + expect(attemptMultiplier(0.5, 3, 1)).toBeCloseTo(1.75); + expect(attemptMultiplier(0.5, 3, 3)).toBeCloseTo(3.25); + expect(attemptMultiplier(0, 5, 3)).toBe(1); + }); + + it('estimates per experiment and names one it cannot price', () => { + const costs = { + denominator: 10, + perPass: { a: 10, b: 20 }, + judgePerPass: 1, + }; + const estimate = estimateSpend( + [ + { experiment: 'a', eval: 'x', runs: 1 }, + { experiment: 'a-no-skills', eval: 'x', runs: 1 }, + { experiment: 'mystery', eval: 'x', runs: 1 }, + ], + costs, + { a: { rate: 0, source: 't' } } + ); + const byName = Object.fromEntries( + estimate.rows.map((r) => [r.experiment, r]) + ); + expect(byName.a?.perAttempt).toBeCloseTo(1.1); + expect(byName['a-no-skills']?.perAttempt).toBeCloseTo(1.1); + // Priced at the dearest measured figure, and flagged. + expect(byName.mystery?.perAttempt).toBeCloseTo(2.1); + expect(estimate.unpriced).toEqual(['mystery']); + expect(estimate.low).toBeCloseTo(4.3); + expect(estimate.high).toBeGreaterThanOrEqual(estimate.low); + }); + + it('derives a fail rate from rows that retried or failed', () => { + const rates = failRatesFromRows([ + { experiment: 'a', passed: true, attempts: 1 }, + { experiment: 'a', passed: true, attempts: 2 }, + { experiment: 'a', passed: false, attempts: 3 }, + { experiment: 'a', passed: true }, + ]); + expect(rates.a?.rate).toBe(0.5); + expect(rates.a?.source).toMatch(/2\/4/); + }); +}); + +describe('links', () => { + it('finds absolute and root-relative docs URLs and drops trailing punctuation', () => { + const text = [ + 'See https://hookdeck.com/docs/connections.md.', + 'curl https://hookdeck.com/docs/filters.md', + '| Sources | `/docs/sources.md` |', + 'and [publish](/docs/api/publish.md#send), or `/docs/sources.md` again', + 'not https://example.com/docs/x or https://hookdeck.com/pricing', + ].join('\n'); + expect(extractDocsUrls(text)).toEqual([ + 'https://hookdeck.com/docs/connections.md', + 'https://hookdeck.com/docs/filters.md', + 'https://hookdeck.com/docs/sources.md', + 'https://hookdeck.com/docs/api/publish.md#send', + ]); + }); + + it('fetches without the fragment and groups files by what is fetched', () => { + expect(fetchableUrl('https://hookdeck.com/docs/a.md#x')).toBe( + 'https://hookdeck.com/docs/a.md' + ); + const links = collectLinks([ + { path: 'one.md', text: 'https://hookdeck.com/docs/a.md#x' }, + { path: 'two.md', text: '`/docs/a.md`' }, + ]); + expect(links).toEqual([ + { url: 'https://hookdeck.com/docs/a.md', files: ['one.md', 'two.md'] }, + ]); + }); + + it('maps changed paths to the skills they belong to', () => { + expect( + changedSkills([ + 'skills/hookdeck/SKILL.md', + 'skills/hookdeck/references/x.md', + 'skills/inspect/SKILL.md', + 'README.md', + ]) + ).toEqual(['hookdeck', 'inspect']); + }); +}); + +describe('models', () => { + it('groups ids into families by stripping the version', () => { + expect(modelFamily('claude-sonnet-5')).toBe('claude-sonnet-N'); + expect(modelFamily('claude-sonnet-5-5')).toBe('claude-sonnet-N'); + expect(modelFamily('gpt-5.4-mini')).toBe('gpt-N-mini'); + expect(modelVersion('gpt-5.4-mini-2026-03-17')).toEqual([5, 4]); + }); + + it('reports newer siblings and listed variants, ignoring dated snapshots', () => { + const listed = [ + 'claude-sonnet-5', + 'claude-sonnet-5-5', + 'claude-sonnet-4-6', + 'claude-sonnet-4-5-20250929', + 'gpt-5.6-sol', + 'gpt-5.6-luna', + 'gpt-5.5', + 'gpt-5.4-mini', + 'gpt-5.4-mini-2026-03-17', + ]; + expect(modelStanding('claude-sonnet-5', listed)).toEqual({ + model: 'claude-sonnet-5', + listed: true, + variants: ['claude-sonnet-5-5'], + newer: ['claude-sonnet-5-5'], + }); + const codex = modelStanding('gpt-5.6', listed); + expect(codex.listed).toBe(false); + expect(codex.variants).toEqual(['gpt-5.6-luna', 'gpt-5.6-sol']); + expect(codex.newer).toEqual([]); + expect(modelStanding('gpt-5.4-mini', listed).newer).toEqual([]); + }); +}); + +describe('canary', () => { + const base = { + imageDefinition: 'aaa', + hookdeckCli: '2.5.0', + agentClis: { codex: '0.138.0' }, + models: { 'codex-gpt-5.6': 'gpt-5.6' }, + }; + + it('needs nothing when the instrument matches', () => { + expect(diffInstrument(base, base)).toEqual([]); + }); + + it('names each moved part, and counts an unknown published value as moved', () => { + const changes = diffInstrument( + { ...base, imageDefinition: undefined }, + { + ...base, + hookdeckCli: '3.1.0', + models: { ...base.models, 'new-experiment': 'gpt-6' }, + } + ); + expect(changes).toEqual([ + { + what: 'sandbox image definition', + published: 'unknown', + current: 'aaa', + }, + { what: 'Hookdeck CLI pin', published: '2.5.0', current: '3.1.0' }, + { what: 'new-experiment model', published: 'unknown', current: 'gpt-6' }, + ]); + }); + + it('reads pins out of the real sources', () => { + expect( + readPin(read('packages/sandbox/src/image.ts'), 'HOOKDECK_CLI_VERSION') + ).toMatch(/^\d+\.\d+\.\d+$/); + expect( + readPin( + read('packages/core/src/agents/codex/runner.ts'), + 'defaultCliVersion' + ) + ).toMatch(/^\d+\.\d+\.\d+$/); + }); + + it('prints the exact dispatch for two cells with publishing held', () => { + const plan = canaryPlan( + ['claude-code-sonnet-5', 'codex-gpt-5.6'], + 'benchmark-localdev-001-listen-locally', + 'benchmark', + ['benchmark', 'benchmark'] + ); + expect(plan.commands[0]).toBe('gh variable set EVALS_PUBLISH --body false'); + expect(plan.commands[1]).toBe( + 'gh workflow run eval-refresh.yml -f suite=benchmark -f experiment_suite=benchmark' + + ' -f experiments=claude-code-sonnet-5,codex-gpt-5.6' + + ' -f eval=benchmark-localdev-001-listen-locally -f runs=1' + ); + expect(plan.commands).toContain('gh variable delete EVALS_PUBLISH'); + }); +}); + +describe('matrix planning, mirroring the workflow', () => { + const evals = [ + { id: 'bm-1', suite: 'benchmark', metadata: {} }, + { id: 'bm-2', suite: 'benchmark', metadata: { minAttempts: 3 } }, + { id: 'reg-1', suite: 'regression', metadata: {} }, + ]; + const experiments = [ + { name: 'skills', suites: ['benchmark', 'regression'] }, + { + name: 'skills-no-skills', + suites: ['no-skills', 'regression'], + skipEval: (ev: { id: string }) => ev.id === 'bm-1', + }, + ]; + + it('runs a benchmark scenario under both arms, honouring skipEval', () => { + const cells = planCells(evals, experiments as never, { + suites: ['benchmark'], + experimentSuites: ['benchmark', 'no-skills'], + experiments: [], + evalIds: [], + runs: 2, + }); + expect(cells.map((c) => `${c.experiment}/${c.eval}/${c.runs}`)).toEqual([ + 'skills/bm-1/2', + 'skills/bm-2/3', + 'skills-no-skills/bm-2/3', + ]); + }); + + it('lets named evals override the suite filter, as the workflow does', () => { + const cells = planCells(evals, experiments as never, { + suites: ['regression'], + experimentSuites: ['benchmark'], + experiments: ['skills'], + evalIds: ['bm-1'], + runs: 1, + }); + expect(cells.map((c) => c.eval)).toEqual(['bm-1']); + }); + + it('caps min_attempts at five and never lowers --runs', () => { + expect(attemptsFor(2, 3)).toBe(3); + expect(attemptsFor(4, 3)).toBe(4); + expect(attemptsFor(2, 9)).toBe(5); + }); +}); + +describe('arguments', () => { + it('defaults to what a bare workflow_dispatch runs', () => { + const args = parsePreflightArgs([]); + expect(args.dispatch).toEqual({ + suites: ['regression'], + experimentSuites: ['regression'], + experiments: [], + evalIds: [], + runs: 2, + }); + expect(args.holdPublish).toBe(false); + expect(args.maxMissingFraction).toBe('0.1'); + }); + + it('accepts the dispatch flags and issue numbers in either form', () => { + const args = parsePreflightArgs([ + '--', + '--suite', + 'benchmark', + '--experiment-suite=benchmark,no-skills', + '--runs', + '3', + '--accept-harness', + '#42,131', + '--skip', + 'skill-links', + '--json', + ]); + expect(args.dispatch.experimentSuites).toEqual(['benchmark', 'no-skills']); + expect(args.dispatch.runs).toBe(3); + expect(args.acceptHarness).toEqual([42, 131]); + expect(args.skip).toEqual(['skill-links']); + expect(args.json).toBe(true); + }); + + it('refuses an unknown check, flag or run count', () => { + expect(() => parsePreflightArgs(['--skip', 'everything'])).toThrow( + /no check named everything/ + ); + expect(() => parsePreflightArgs(['--yolo'])).toThrow(/unknown flag/); + expect(() => parsePreflightArgs(['--runs', '0'])).toThrow(/positive/); + }); + + it('numbers the checks as #131 does', () => { + expect(CHECKS.map((c) => c.number)).toEqual( + Array.from({ length: 15 }, (_, i) => i + 1) + ); + }); +}); + +describe('report', () => { + const check = (over: Partial): CheckResult => ({ + id: 'x', + number: 1, + title: 'X', + kind: 'assertion', + status: 'pass', + summary: 'ok', + details: [], + ...over, + }); + + it('fails only on a failed assertion', () => { + expect(exitCodeFor([check({ kind: 'decision', status: 'decide' })])).toBe( + 0 + ); + expect(exitCodeFor([check({ status: 'skipped' })])).toBe(0); + expect(exitCodeFor([check({ status: 'warn' })])).toBe(0); + expect(exitCodeFor([check({ status: 'fail' })])).toBe(1); + }); + + it('says where a decision is recorded and shouts about a skip', () => { + const text = formatReport( + [ + check({ + id: 'pin', + kind: 'decision', + status: 'decide', + summary: 'behind', + }), + check({ + id: 'links', + number: 13, + status: 'skipped', + summary: 'skipped', + }), + check({ id: 'spend', number: 7, status: 'fail', summary: 'no' }), + ], + { + generatedAt: 'now', + skipped: ['links'], + notes: [], + } + ); + expect(text).toContain(DECISION_FOOTER); + expect(text).toContain('!!! SKIPPED BY REQUEST: links !!!'); + expect(text).toContain( + 'Result: 1 assertion failed: spend. Do not dispatch.' + ); + expect(text).toContain('1 decision to record in the release notes: pin'); + expect(text.indexOf('Decisions')).toBeLessThan(text.indexOf('Assertions')); + }); + + it('masks secret values, longest first', () => { + expect( + maskSecrets('key sk-abcdefgh123 and sk-abcdefgh', [ + 'sk-abcdefgh', + 'sk-abcdefgh123', + 'short', + ]) + ).toBe('key **** and ****'); + }); +}); + +describe('base prompt', () => { + it('reads back what basePromptFor returns from its own source', () => { + expect(extractBasePrompt(read('apps/framework/lib/base-prompt.ts'))).toBe( + basePromptFor('tools') + ); + }); + + it('reads the older shape inside run-eval.ts, including a semicolon', () => { + const source = [ + 'function other() { return 1; }', + 'function basePromptFor(_mode: EvalMode): string {', + ' return (', + " 'First sentence; with a semicolon. ' +", + ' "Second, double-quoted. " +', + " 'It\\'s escaped.'", + ' );', + '}', + 'function buildSystemPrompt() {}', + ].join('\n'); + expect(extractBasePrompt(source)).toBe( + "First sentence; with a semicolon. Second, double-quoted. It's escaped." + ); + expect(extractBasePrompt('no prompt here')).toBeUndefined(); + }); +}); diff --git a/package.json b/package.json index 77664fa..301d89f 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "score-only": "pnpm --filter @hookdeck-evals/framework score-only", "compare-snapshots": "pnpm --filter @hookdeck-evals/framework compare-snapshots", "export-results": "pnpm --filter @hookdeck-evals/framework export-results", + "preflight": "pnpm --silent --filter @hookdeck-evals/framework preflight", "typecheck": "pnpm --filter @hookdeck-evals/framework typecheck && pnpm --filter @hookdeck-evals/web typecheck", "web": "pnpm --filter @hookdeck-evals/web dev", "web:build": "pnpm --filter @hookdeck-evals/web build", diff --git a/packages/core/src/agents/registry.ts b/packages/core/src/agents/registry.ts index 58db31b..b4d9efa 100644 --- a/packages/core/src/agents/registry.ts +++ b/packages/core/src/agents/registry.ts @@ -38,3 +38,25 @@ export function createParser(agent: AgentHarnessId): AgentTranscriptParser { } return definition.parser; } + +/** + * What each registered agent installs and which key it reads, without the + * runner's behaviour. For `preflight`, which compares the pins against npm and + * the keys against the repository's secrets, and should read both from the + * objects a run uses rather than from a copy that drifts. + */ +export function registeredAgentPins(): Array<{ + id: AgentHarnessId; + displayName: string; + cliPackage: string; + defaultCliVersion: string; + apiKeyEnvVar: string; +}> { + return AGENTS.map(({ runner }) => ({ + id: runner.id, + displayName: runner.displayName, + cliPackage: runner.cliPackage, + defaultCliVersion: runner.defaultCliVersion, + apiKeyEnvVar: runner.apiKeyEnvVar, + })); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7d73068..fe26257 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -86,7 +86,11 @@ export type { RunnerExecResult, AgentDefinition, } from './agents/types.js'; -export { createParser, supportedParsers } from './agents/registry.js'; +export { + createParser, + registeredAgentPins, + supportedParsers, +} from './agents/registry.js'; export { adaptTranscript } from './parsers/adapt.js'; export type { AdaptedTranscript } from './parsers/adapt.js'; export type { AgentTranscriptParser } from './parsers/types.js'; diff --git a/packages/hookdeck/src/index.ts b/packages/hookdeck/src/index.ts index ff18a89..fd7177c 100644 --- a/packages/hookdeck/src/index.ts +++ b/packages/hookdeck/src/index.ts @@ -12,9 +12,12 @@ export type { export { DEFAULT_ISSUE_TRIGGERS, FixedProjectSource, + OUTPOST_GATEWAY_PRISTINE, + matchesDeclared as issueTriggerMatchesDeclared, muteIssueTriggerNotifications, resetIssueTriggersToDefaults, } from './project-source.js'; +export type { OperatorEventDestination } from './project-source.js'; export type { IssueTriggerChange, ProjectSource, diff --git a/packages/hookdeck/src/project-source.ts b/packages/hookdeck/src/project-source.ts index 896b8c6..019ddc6 100644 --- a/packages/hookdeck/src/project-source.ts +++ b/packages/hookdeck/src/project-source.ts @@ -301,7 +301,12 @@ export async function resetIssueTriggersToDefaults( } } -function matchesDeclared( +/** + * Whether a trigger is one of the declared defaults, as the reset leaves it. + * Exported for `preflight`, which asserts the project is already in that state + * rather than putting it there. + */ +export function matchesDeclared( trigger: HookdeckResource, configs: Record ): boolean { From faf4f562f6439e6bbdbd8b5a32a872b9ec1bba1f Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Sat, 7 Nov 2026 13:33:20 +0000 Subject: [PATCH 2/2] Compare the canary per agent and test the preflight checks Review of the preflight found the canary read every agent's image and pins from the newest published run, even when that run had no cells for the agent. The newest run today is Claude-only, so a Dockerfile change or Codex pin bump followed by a Claude-only publish read "not required" with no Codex cell ever run on the new image: #114 again. Each agent is now compared against the newest run that has rows for one of its experiments. - The skills CLI pin, a build arg of the same image, is in the canary comparison and is a decision against npm latest (check 16). - Main-green from a pull request's Checks run fails when main's first parent was committed after the run started, since the merged tree was then never tested. - Hookdeck and Outpost reads go through Deps, the entry point is guarded, and the checks are tested against fakes: canary run selection, the main-green fallback, the secrets filter and the projects-pristine evaluation. - The operator event destination URL is printed with its path masked, attempts that cannot be read say so, and every result string is redacted before the report is laid out. - A docs link that redirects to 200 warns with its final URL (a trailing-slash redirect is not counted), and a 429 backs off once before failing. - Prerelease versions compare as semver does; the skills-pin decision notes the compare API's caps and a diverged pin; the Outpost gateway check compares ids against its baseline. - `pnpm -s preflight --json` is documented for clean JSON. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 16 +- apps/framework/lib/preflight/args.ts | 8 +- apps/framework/lib/preflight/canary.ts | 109 +++- apps/framework/lib/preflight/evaluate.ts | 191 ++++++ apps/framework/lib/preflight/links.ts | 54 ++ apps/framework/lib/preflight/report.ts | 18 + apps/framework/lib/preflight/semver.ts | 26 +- apps/framework/scripts/preflight.ts | 593 +++++++++++-------- apps/framework/test/preflight-checks.test.ts | 524 ++++++++++++++++ apps/framework/test/preflight.test.ts | 200 ++++++- packages/hookdeck/src/index.ts | 7 +- 11 files changed, 1475 insertions(+), 271 deletions(-) create mode 100644 apps/framework/lib/preflight/evaluate.ts create mode 100644 apps/framework/test/preflight-checks.test.ts diff --git a/AGENTS.md b/AGENTS.md index 1ac2454..a997886 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -340,6 +340,7 @@ Run the preflight, with the same inputs the dispatch will take, from a checkout ```bash pnpm preflight --suite benchmark --experiment-suite benchmark,no-skills --runs 3 pnpm preflight --help # every flag, and the check ids --skip takes +pnpm -s preflight --json # -s keeps pnpm's banner out of the JSON ``` Every defect v0.5.0 found was discoverable before the run that found it (#131), and @@ -351,13 +352,16 @@ preflight makes. `--confirm-balance` (or a `y` on a terminal) because no provider exposes a balance to a project key. Open `harness` issues need `--accept-harness `, so each one is accepted for the run by name. -- **Decisions never fail it.** A pin behind `latest`, a skills pin behind `main`, a - model with a newer sibling, a changed base prompt: each prints the current and the - latest, and the release notes record what was chosen. +- **Decisions never fail it.** A CLI pin behind `latest` (Hookdeck, skills or an + agent's), a skills pin behind `main`, a model with a newer sibling, a changed base + prompt: each prints the current and the latest, and the release notes record what + was chosen. - **A moved instrument needs a canary.** When the image definition, a CLI pin or a - model differs from the newest published rows, it prints the two-cell - `gh workflow run` command with `EVALS_PUBLISH=false`. Verify the finished run with - `--canary-run ` before the matrix. + model differs from what the newest published cells of that agent ran under, it + prints the two-cell `gh workflow run` command with `EVALS_PUBLISH=false`. Per + agent, not per snapshot: a Claude-only partial publish says nothing about the image + Codex last ran on. Verify the finished run with `--canary-run ` before the + matrix. - **`--skip ` is an escape hatch, not a pass.** The report prints skipped checks as a banner. Name them in the release notes. diff --git a/apps/framework/lib/preflight/args.ts b/apps/framework/lib/preflight/args.ts index 78d5d5a..61bce80 100644 --- a/apps/framework/lib/preflight/args.ts +++ b/apps/framework/lib/preflight/args.ts @@ -3,7 +3,9 @@ import { DISPATCH_DEFAULTS, type DispatchInputs } from './matrix.js'; /** * Every check, by the id `--skip` takes and its number in #131. The canary is - * the requirement #131 attaches to checks 1, 2 and 4, numbered after them. + * the requirement #131 attaches to checks 1, 2 and 4, numbered after them. The + * skills CLI pin is a sixteenth decision #131 did not list: it is a build arg + * of the same image as the Hookdeck CLI, and nothing compared it either. */ export const CHECKS = [ { number: 1, id: 'hookdeck-cli-pin', title: 'Hookdeck CLI pin' }, @@ -21,6 +23,7 @@ export const CHECKS = [ { number: 13, id: 'skill-links', title: 'Skill links resolve' }, { number: 14, id: 'harness-issues', title: 'Open harness issues' }, { number: 15, id: 'canary', title: 'Canary' }, + { number: 16, id: 'skills-cli-pin', title: 'Skills CLI pin' }, ] as const; export type CheckId = (typeof CHECKS)[number]['id']; @@ -162,7 +165,8 @@ What the run intends: (default ${DEFAULT_CANARY_EVAL}) Output: - --json machine-readable report + --json machine-readable report; run as \`pnpm -s preflight --json\` + so pnpm's banner stays out of the JSON --skip skip checks by id; printed loudly. Ids: ${CHECKS.map((c) => c.id).join(', ')} diff --git a/apps/framework/lib/preflight/canary.ts b/apps/framework/lib/preflight/canary.ts index f615959..feeda23 100644 --- a/apps/framework/lib/preflight/canary.ts +++ b/apps/framework/lib/preflight/canary.ts @@ -8,12 +8,27 @@ * held, would have found it for the price of two cells. */ -export interface Instrument { +/** + * What an agent's cells were measured under. Per agent, because a published + * snapshot is a merge of runs: the newest run may have had no cells for one of + * the agents, and comparing that agent against it would clear a change no cell + * of that agent ever ran under. That is #114 again, for the price of a partial + * publish. + */ +export interface AgentInstrument { /** `sandboxImageDefinition()`: a hash of the Dockerfile's bytes. */ imageDefinition?: string; hookdeckCli?: string; - /** Agent id to pinned CLI version, for agents an experiment uses. */ - agentClis: Record; + /** Vercel's `skills` CLI, a build arg of the same image. */ + skillsCli?: string; + agentCli?: string; + /** Where the published values were read from, for the report. */ + source?: string; +} + +export interface Instrument { + /** Agent id to what its cells ran under, for agents an experiment uses. */ + byAgent: Record; /** Experiment name to model id. */ models: Record; } @@ -22,6 +37,8 @@ export interface InstrumentChange { what: string; published: string; current: string; + /** The agent whose cells would run under the change, when it is per agent. */ + agent?: string; } const UNKNOWN = 'unknown'; @@ -36,19 +53,38 @@ export function diffInstrument( current: Instrument ): InstrumentChange[] { const changes: InstrumentChange[] = []; - const compare = (what: string, p?: string, c?: string) => { + const compare = ( + what: string, + p: string | undefined, + c: string | undefined, + agent?: string + ) => { if (c === undefined) return; if (p === c) return; - changes.push({ what, published: p ?? UNKNOWN, current: c }); + changes.push({ + what, + published: p ?? UNKNOWN, + current: c, + ...(agent ? { agent } : {}), + }); }; - compare( - 'sandbox image definition', - published.imageDefinition, - current.imageDefinition - ); - compare('Hookdeck CLI pin', published.hookdeckCli, current.hookdeckCli); - for (const [agent, version] of Object.entries(current.agentClis).sort()) { - compare(`${agent} CLI pin`, published.agentClis[agent], version); + for (const [agent, now] of Object.entries(current.byAgent).sort()) { + const then = published.byAgent[agent] ?? {}; + const cells = `${agent} cells, ${then.source ?? 'no published run'}`; + compare( + `sandbox image definition (${cells})`, + then.imageDefinition, + now.imageDefinition, + agent + ); + compare( + `Hookdeck CLI pin (${cells})`, + then.hookdeckCli, + now.hookdeckCli, + agent + ); + compare(`skills CLI pin (${cells})`, then.skillsCli, now.skillsCli, agent); + compare(`${agent} CLI pin (${cells})`, then.agentCli, now.agentCli, agent); } for (const [experiment, model] of Object.entries(current.models).sort()) { // An experiment with no published rows is new, and a new experiment is a @@ -58,6 +94,53 @@ export function diffInstrument( return changes; } +export interface PublishedRowLike { + experiment?: string; + runId?: string; + ranAt?: string; + experimentDisplay?: { agent?: string; modelId?: string }; +} + +/** + * For each agent, the newest published run that has rows for an experiment + * using it, by the latest `ranAt` of that agent's rows. Not the newest run + * overall: a Claude-only partial publish says nothing about the image Codex + * cells last ran on. + */ +export function newestRunPerAgent( + rows: PublishedRowLike[], + agentOf: (experiment: string) => string | undefined +): Record { + const best = new Map(); + for (const row of rows) { + if (!row.experiment || !row.runId) continue; + const agent = agentOf(row.experiment) ?? row.experimentDisplay?.agent; + if (!agent) continue; + const ranAt = row.ranAt ?? ''; + const held = best.get(agent); + if (!held || ranAt > held.ranAt) + best.set(agent, { runId: row.runId, ranAt }); + } + return Object.fromEntries([...best].map(([agent, v]) => [agent, v.runId])); +} + +/** Each experiment's model, from its newest published row. */ +export function modelsFromRows( + rows: PublishedRowLike[] +): Record { + const best = new Map(); + for (const row of rows) { + const model = row.experimentDisplay?.modelId; + if (!row.experiment || !model) continue; + const ranAt = row.ranAt ?? ''; + const held = best.get(row.experiment); + if (!held || ranAt > held.ranAt) { + best.set(row.experiment, { model, ranAt }); + } + } + return Object.fromEntries([...best].map(([e, v]) => [e, v.model])); +} + /** * A pinned string in a source file at some commit: `NAME = '1.2.3'` or * `name: '1.2.3'`. For reading pins at the commit that produced a published diff --git a/apps/framework/lib/preflight/evaluate.ts b/apps/framework/lib/preflight/evaluate.ts new file mode 100644 index 0000000..60788d6 --- /dev/null +++ b/apps/framework/lib/preflight/evaluate.ts @@ -0,0 +1,191 @@ +import { + DEFAULT_ISSUE_TRIGGERS, + issueTriggerMatchesDeclared, + type HookdeckResource, + type PristineSnapshot, +} from '@hookdeck-evals/hookdeck'; + +/** + * The judgements behind several checks, separated from the calls that gather + * their inputs so they can be tested without a network. + */ + +// Secrets --------------------------------------------------------------------- + +export interface MissingSecrets { + /** Missing and needed: fails the check. */ + fatal: string[]; + /** Missing, and only the key of an agent no experiment uses. */ + unneeded: string[]; +} + +/** + * Which missing secrets matter. A missing key for an agent no experiment uses + * is not a gap in a run: the workflow writes it into `.env` empty and nothing + * reads it. Anything else the workflow reads and the repository lacks is. + */ +export function classifyMissingSecrets( + wanted: string[], + have: Set, + agents: Array<{ id: string; apiKeyEnvVar: string }>, + usedAgents: Set +): MissingSecrets { + const missing = wanted.filter((s) => !have.has(s)); + const unneeded = missing.filter((name) => { + const owners = agents.filter((a) => a.apiKeyEnvVar === name); + return owners.length > 0 && owners.every((a) => !usedAgents.has(a.id)); + }); + return { + fatal: missing.filter((m) => !unneeded.includes(m)), + unneeded, + }; +} + +// Main is green, from a pull request's Checks run ----------------------------- + +export interface ChecksRunEvidence { + mainSha: string; + prNumber: number; + runId: number; + runCreatedAt: string; + conclusion: string; + steps: Array<{ name: string; conclusion: string }>; + /** + * The committer time of main's first parent: the base the pull request was + * merged onto. Undefined when it could not be read. + */ + baseCommittedAt?: string; +} + +const REQUIRED_STEPS = [/format/i, /typecheck/i, /test/i, /build/i]; + +/** + * Whether a pull request's Checks run covers the main it produced. + * + * The run tested the pull request merged into its base *as of when the run + * started*. If the base moved after that, main is a merge nobody tested: two + * pull requests can each pass and still break each other. So a base commit + * newer than the run fails the check rather than passing on a stale tree; the + * remedy is to check out main and run the four commands, which this script + * does itself when it is run from a clean checkout of main. + */ +export function evaluateChecksRun(e: ChecksRunEvidence): { + status: 'pass' | 'fail'; + summary: string; + details: string[]; +} { + const missing = REQUIRED_STEPS.filter( + (re) => !e.steps.some((s) => re.test(s.name) && s.conclusion === 'success') + ); + const details = [ + `read from the Checks run on #${e.prNumber} (run ${e.runId}, started ${e.runCreatedAt})`, + ...e.steps + .filter((s) => REQUIRED_STEPS.some((re) => re.test(s.name))) + .map((s) => `${s.name}: ${s.conclusion}`), + ]; + if (e.conclusion !== 'success' || missing.length > 0) { + return { + status: 'fail', + summary: `#${e.prNumber}'s Checks did not pass every step (${e.conclusion || 'unfinished'})`, + details, + }; + } + if (!e.baseCommittedAt) { + return { + status: 'fail', + summary: `could not read the base main ${e.mainSha.slice(0, 7)} was merged onto, so cannot tell whether #${e.prNumber}'s Checks tested it`, + details: [ + ...details, + 'check out main and re-run to run the checks locally', + ], + }; + } + if (Date.parse(e.baseCommittedAt) > Date.parse(e.runCreatedAt)) { + return { + status: 'fail', + summary: `main's base moved after #${e.prNumber}'s Checks started, so main ${e.mainSha.slice(0, 7)} is a merge nobody tested`, + details: [ + ...details, + `base committed ${e.baseCommittedAt}, after the run started`, + 'check out main and re-run to run the checks locally', + ], + }; + } + return { + status: 'pass', + summary: `#${e.prNumber}'s Checks passed format, typecheck, tests and build on the base main was merged onto`, + details: [ + ...details, + `base committed ${e.baseCommittedAt}, before the run started`, + ], + }; +} + +// Projects are pristine -------------------------------------------------------- + +function describe(r: HookdeckResource): string { + return `${r.id}${r.name ? ` (${r.name})` : ''}`; +} + +/** + * `evals-ci` at rest: the declared default issue triggers, exactly as the reset + * leaves them, and nothing else. A new project ships with no sources, + * connections, destinations or transformations. + */ +export function evaluateGatewayProject( + resources: Record +): string[] { + const fails: string[] = []; + for (const [kind, rows] of Object.entries(resources).sort()) { + if (kind === 'issue-triggers' || rows.length === 0) continue; + fails.push( + `evals-ci holds ${rows.length} ${kind}: ${rows.map(describe).join(', ')}` + ); + } + const triggers = resources['issue-triggers'] ?? []; + const declared = new Set(DEFAULT_ISSUE_TRIGGERS.map((d) => d.type)); + for (const d of DEFAULT_ISSUE_TRIGGERS) { + const ofType = triggers.filter((t) => t.type === d.type); + if (ofType.length === 0) + fails.push(`evals-ci has no ${d.type} issue trigger`); + if (ofType.length > 1) { + fails.push( + `evals-ci has ${ofType.length} ${d.type} issue triggers: ${ofType.map(describe).join(', ')}` + ); + } + for (const t of ofType) { + if (!issueTriggerMatchesDeclared(t, d.configs)) { + fails.push( + `evals-ci ${d.type} trigger ${t.id} differs from DEFAULT_ISSUE_TRIGGERS (configs, channels, name or enabled)` + ); + } + } + } + for (const t of triggers.filter((t) => !declared.has(String(t.type)))) { + fails.push( + `evals-ci has an undeclared ${String(t.type)} issue trigger ${t.id}` + ); + } + return fails; +} + +/** + * The Outpost project's Event Gateway side against its declared baseline, by + * id: anything the baseline does not list is a leftover. + */ +export function evaluateOutpostGateway( + resources: Record, + baseline: PristineSnapshot +): string[] { + const fails: string[] = []; + for (const [kind, rows] of Object.entries(resources).sort()) { + const allowed = new Set(baseline.ids[kind] ?? []); + const extra = rows.filter((r) => !allowed.has(r.id)); + if (extra.length > 0) { + fails.push( + `the Outpost project's gateway side holds ${extra.length} ${kind} its baseline does not declare: ${extra.map(describe).join(', ')}` + ); + } + } + return fails; +} diff --git a/apps/framework/lib/preflight/links.ts b/apps/framework/lib/preflight/links.ts index fed24c9..b2b083b 100644 --- a/apps/framework/lib/preflight/links.ts +++ b/apps/framework/lib/preflight/links.ts @@ -87,3 +87,57 @@ export function changedSkills(paths: string[]): string[] { } return [...out].sort(); } + +export interface LinkCheck { + url: string; + /** The final status, after redirects. 0 when nothing answered. */ + status: number; + /** Where a redirect ended, when it did not end at `url`. */ + finalUrl?: string; +} + +/** + * Fetch a docs URL the way an agent would, following redirects. + * + * A redirect that ends in 200 still works for an agent, but the skill points + * at a moved page, so the caller reports the final URL. A 429 is the site + * asking us to slow down, not a dead link: wait and try once more before + * calling it a failure. A dropped connection gets one retry too. + */ +export async function checkLink( + fetchFn: typeof fetch, + url: string, + sleep: (ms: number) => Promise = (ms) => + new Promise((resolve) => setTimeout(resolve, ms)) +): Promise { + let last: LinkCheck = { url, status: 0 }; + for (let attempt = 0; attempt < 2; attempt++) { + let res: Response; + try { + res = await fetchFn(url, { + redirect: 'follow', + signal: AbortSignal.timeout(20_000), + }); + } catch { + continue; + } + await res.body?.cancel().catch(() => undefined); + // A trailing-slash redirect is the site's canonical form, not a moved page. + const bare = (u: string) => u.replace(/\/+$/, ''); + const finalUrl = + res.redirected && res.url && bare(res.url) !== bare(url) + ? res.url + : undefined; + last = { url, status: res.status, ...(finalUrl ? { finalUrl } : {}) }; + if (res.status !== 429) return last; + if (attempt === 0) { + const retryAfter = Number(res.headers.get('retry-after')); + await sleep( + Number.isFinite(retryAfter) && retryAfter > 0 + ? Math.min(retryAfter, 30) * 1000 + : 5_000 + ); + } + } + return last; +} diff --git a/apps/framework/lib/preflight/report.ts b/apps/framework/lib/preflight/report.ts index 9fed71e..ae06dfd 100644 --- a/apps/framework/lib/preflight/report.ts +++ b/apps/framework/lib/preflight/report.ts @@ -147,3 +147,21 @@ export function maskSecrets(text: string, secrets: string[]): string { } return out; } + +/** + * A delivery URL with its path masked: `https://hkdk.events/****`. + * + * A Hookdeck source URL is a bearer credential in all but name, since anyone + * holding it can post into that project, and `redact.ts` treats delivery URLs + * as secrets for the same reason. The host is kept so a reader can still tell + * a source from a mock endpoint. Anything that does not parse is masked whole. + */ +export function maskUrlPath(raw: string): string { + try { + const url = new URL(raw); + const hasPath = url.pathname !== '/' || url.search !== ''; + return `${url.protocol}//${url.host}${hasPath ? '/****' : '/'}`; + } catch { + return '****'; + } +} diff --git a/apps/framework/lib/preflight/semver.ts b/apps/framework/lib/preflight/semver.ts index 9292807..4744008 100644 --- a/apps/framework/lib/preflight/semver.ts +++ b/apps/framework/lib/preflight/semver.ts @@ -37,7 +37,31 @@ export function compareSemver(a: string, b: string): number { if (x.prerelease === y.prerelease) return 0; if (x.prerelease === undefined) return 1; if (y.prerelease === undefined) return -1; - return x.prerelease < y.prerelease ? -1 : 1; + return comparePrerelease(x.prerelease, y.prerelease); +} + +/** + * Semver's prerelease order: dot-separated identifiers, numeric ones compared + * as numbers and sorting before alphanumeric ones, and a shorter list first + * when one is a prefix of the other. So `rc.2` < `rc.10`. + */ +function comparePrerelease(a: string, b: string): number { + const x = a.split('.'); + const y = b.split('.'); + for (let i = 0; i < Math.max(x.length, y.length); i++) { + const p = x[i]; + const q = y[i]; + if (p === undefined) return -1; + if (q === undefined) return 1; + if (p === q) continue; + const pn = /^\d+$/.test(p); + const qn = /^\d+$/.test(q); + if (pn && qn) return Number(p) < Number(q) ? -1 : 1; + if (pn) return -1; + if (qn) return 1; + return p < q ? -1 : 1; + } + return 0; } /** diff --git a/apps/framework/scripts/preflight.ts b/apps/framework/scripts/preflight.ts index ae6ef07..022c979 100644 --- a/apps/framework/scripts/preflight.ts +++ b/apps/framework/scripts/preflight.ts @@ -12,6 +12,7 @@ import { import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createInterface } from 'node:readline/promises'; +import { pathToFileURL } from 'node:url'; import { registeredAgentPins } from '@hookdeck-evals/core'; import { DEFAULT_ISSUE_TRIGGERS, @@ -19,15 +20,16 @@ import { OUTPOST_GATEWAY_PRISTINE, OutpostClient, RESOURCE_KINDS, - collectEnvSecretValues, - issueTriggerMatchesDeclared, - redactSecrets, + redactArtifactDeep, + redactSecretsForArtifact, type HookdeckResource, type OperatorEventDestination, + type ResourceKind, } from '@hookdeck-evals/hookdeck'; import { HOOKDECK_CLI_VERSION, SANDBOX_SELF_CHECK_FAILED, + SKILLS_CLI_VERSION, sandboxImageDefinition, } from '@hookdeck-evals/sandbox'; import { basePromptFor, extractBasePrompt } from '../lib/base-prompt.js'; @@ -53,16 +55,30 @@ import { CANARY_CRITERIA, canaryPlan, diffInstrument, + modelsFromRows, + newestRunPerAgent, readPin, + type AgentInstrument, type Instrument, + type PublishedRowLike, } from '../lib/preflight/canary.js'; -import { changedSkills, collectLinks } from '../lib/preflight/links.js'; +import { + classifyMissingSecrets, + evaluateChecksRun, + evaluateGatewayProject, + evaluateOutpostGateway, +} from '../lib/preflight/evaluate.js'; +import { + changedSkills, + checkLink, + collectLinks, +} from '../lib/preflight/links.js'; import { planCells, type PlannedPair } from '../lib/preflight/matrix.js'; import { modelStanding } from '../lib/preflight/models.js'; import { exitCodeFor, formatReport, - maskSecrets, + maskUrlPath, type CheckResult, type CheckStatus, } from '../lib/preflight/report.js'; @@ -89,6 +105,7 @@ import { * ```bash * pnpm preflight # the regression suite * pnpm preflight --suite benchmark --experiment-suite benchmark,no-skills --runs 3 + * pnpm -s preflight --json # -s keeps pnpm's banner out of the JSON * pnpm preflight --help * ``` * @@ -100,11 +117,12 @@ import { * **Read-only**, against Hookdeck, Outpost, GitHub and both providers, with one * exception: one real completion per provider, the same request the workflow's * own preflight makes, because a models list answers 200 with a zero balance. - * It never prints a secret value: the report is passed through the same - * redaction the artifact export uses before it is written. + * It never prints a secret value: every string in the results is passed through + * the same redaction the artifact export uses before the report is built, and a + * delivery URL is printed with its path masked. * - * Network and process calls go through `Deps`, so the logic in `lib/preflight/` - * is tested without either. + * Every process, HTTP, DNS, Hookdeck and Outpost call goes through `Deps`, so + * the checks run in tests against fakes; `test/preflight-checks.test.ts` does. */ interface ExecResult { @@ -113,6 +131,17 @@ interface ExecResult { stderr: string; } +/** The slice of the Event Gateway API the checks read. */ +export interface GatewayReader { + list(kind: ResourceKind): Promise; +} + +/** The slice of the Outpost API the checks read. Only `GET` is ever sent. */ +export interface OutpostReader { + tenants(): Promise>; + get(path: string): Promise; +} + export interface Deps { root: string; env: Record; @@ -123,6 +152,9 @@ export interface Deps { ): Promise; fetch: typeof fetch; resolveHost(host: string): Promise; + gateway(apiKey: string): GatewayReader; + outpost(apiKey: string): OutpostReader; + sleep(ms: number): Promise; } const realDeps: Deps = { @@ -159,6 +191,18 @@ const realDeps: Deps = { return false; } }, + gateway: (apiKey) => { + const client = new HookdeckClient({ apiKey }); + return { list: (kind) => client.list(kind) }; + }, + outpost: (apiKey) => { + const client = new OutpostClient({ apiKey }); + return { + tenants: () => client.tenants(), + get: (path) => client.request('GET', path), + }; + }, + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), }; const DECISIONS = new Set([ @@ -167,6 +211,7 @@ const DECISIONS = new Set([ 'skills-pin', 'model-ids', 'base-prompt', + 'skills-cli-pin', ]); function result( @@ -189,7 +234,7 @@ function result( } /** Everything several checks read, gathered once. */ -interface Context { +export interface Context { deps: Deps; args: PreflightArgs; repo: string; @@ -212,7 +257,6 @@ interface Context { evalsRequiringOutpost: string[]; latest?: { results: Array>; - composition?: { runs?: Array<{ runId: string; latest: string }> }; runId?: string; }; skills: { slug: string; pin?: string; names: string[]; dirs: string[] }; @@ -390,34 +434,63 @@ function gapStatus(current: string, latest: string): CheckStatus { return compareSemver(current, latest) < 0 ? 'decide' : 'pass'; } -// 1 --------------------------------------------------------------------------- - -async function checkHookdeckCli(ctx: Context): Promise { - const latest = await npmLatest(ctx, 'hookdeck-cli'); - const details = [ - `pinned: ${HOOKDECK_CLI_VERSION} (packages/sandbox/src/image.ts)`, - `npm latest: ${latest}`, - ]; +/** + * A pin baked into the sandbox image, against npm `latest` and against what it + * was at the last release. Checks 1 and 16 differ only in which pin. + */ +async function imagePinDecision( + ctx: Context, + id: 'hookdeck-cli-pin' | 'skills-cli-pin', + pkg: string, + pinned: string, + constant: string, + file: string, + consequence: string +): Promise { + const latest = await npmLatest(ctx, pkg); + const details = [`pinned: ${pinned} (${file})`, `npm latest: ${latest}`]; if (ctx.lastRelease) { - const source = await fileAt( - ctx, - ctx.lastRelease, - 'packages/sandbox/src/image.ts' - ); - const then = source && readPin(source, 'HOOKDECK_CLI_VERSION'); + const source = await fileAt(ctx, ctx.lastRelease, file); + const then = source && readPin(source, constant); if (then) details.push(`pinned at ${ctx.lastRelease}: ${then}`); } - details.push( - 'a bump changes the product under test: results either side are not comparable' - ); + details.push(consequence); return result( - 'hookdeck-cli-pin', - gapStatus(HOOKDECK_CLI_VERSION, latest), - describeVersionGap(HOOKDECK_CLI_VERSION, latest), + id, + gapStatus(pinned, latest), + describeVersionGap(pinned, latest), details ); } +// 1 --------------------------------------------------------------------------- + +function checkHookdeckCli(ctx: Context): Promise { + return imagePinDecision( + ctx, + 'hookdeck-cli-pin', + 'hookdeck-cli', + HOOKDECK_CLI_VERSION, + 'HOOKDECK_CLI_VERSION', + 'packages/sandbox/src/image.ts', + 'a bump changes the product under test: results either side are not comparable' + ); +} + +// 16 -------------------------------------------------------------------------- + +function checkSkillsCli(ctx: Context): Promise { + return imagePinDecision( + ctx, + 'skills-cli-pin', + 'skills', + SKILLS_CLI_VERSION, + 'SKILLS_CLI_VERSION', + 'packages/sandbox/src/skills.ts', + 'a bump changes how skills are installed into the sandbox: skills arms either side are not comparable' + ); +} + // 2 --------------------------------------------------------------------------- async function checkAgentClis(ctx: Context): Promise { @@ -456,6 +529,10 @@ async function checkAgentClis(ctx: Context): Promise { // 3 --------------------------------------------------------------------------- +/** GitHub's compare API lists at most this many files and commits. */ +const COMPARE_FILE_CAP = 300; +const COMPARE_COMMIT_CAP = 250; + async function checkSkillsPin(ctx: Context): Promise { const { slug, pin, names } = ctx.skills; if (!pin) { @@ -476,18 +553,36 @@ async function checkSkillsPin(ctx: Context): Promise { behind_by: number; files?: Array<{ filename: string }>; }>(ctx, ['api', `repos/${slug}/compare/${pin}...${main}`]); - const changed = changedSkills((compare.files ?? []).map((f) => f.filename)); + const files = compare.files ?? []; + const changed = changedSkills(files.map((f) => f.filename)); const pinnedChanged = changed.filter((s) => names.includes(s)); const details = [ `pinned: ${pin.slice(0, 7)}; main: ${main.slice(0, 7)}`, `skills changed between them: ${changed.length > 0 ? changed.join(', ') : 'none'}`, `of the skills this repo installs (${names.join(', ')}): ${pinnedChanged.length > 0 ? pinnedChanged.join(', ') : 'none changed'}`, - 'a move alters what a skills arm reads and nothing a baseline arm sees', ]; + if ( + files.length >= COMPARE_FILE_CAP || + compare.ahead_by >= COMPARE_COMMIT_CAP + ) { + details.push( + `the compare API lists at most ${COMPARE_FILE_CAP} files and ${COMPARE_COMMIT_CAP} commits, so the changed-skills list may be incomplete` + ); + } + if (compare.behind_by > 0) { + details.push( + `the pin is not an ancestor of main: it carries ${compare.behind_by} commit${compare.behind_by === 1 ? '' : 's'} main does not, so moving it to main drops them` + ); + } + details.push( + 'a move alters what a skills arm reads and nothing a baseline arm sees' + ); return result( 'skills-pin', 'decide', - `${compare.ahead_by} commit${compare.ahead_by === 1 ? '' : 's'} behind ${slug} main`, + compare.behind_by > 0 + ? `diverged from ${slug} main: ${compare.ahead_by} behind, ${compare.behind_by} ahead` + : `${compare.ahead_by} commit${compare.ahead_by === 1 ? '' : 's'} behind ${slug} main`, details ); } @@ -766,7 +861,7 @@ async function checkSpend(ctx: Context): Promise { // 8 --------------------------------------------------------------------------- -async function checkSecrets(ctx: Context): Promise { +export async function checkSecrets(ctx: Context): Promise { const wanted = workflowSecrets(ctx.workflow); const have = new Set( ( @@ -778,15 +873,12 @@ async function checkSecrets(ctx: Context): Promise { ]) ).map((s) => s.name) ); - const missing = wanted.filter((s) => !have.has(s)); - // A missing key for an agent no experiment uses is not a gap in this run: - // the workflow writes it into .env empty and nothing reads it. - const usedAgents = new Set(ctx.experiments.map((e) => e.agent)); - const unneeded = missing.filter((name) => { - const agents = registeredAgentPins().filter((p) => p.apiKeyEnvVar === name); - return agents.length > 0 && agents.every((a) => !usedAgents.has(a.id)); - }); - const fatal = missing.filter((m) => !unneeded.includes(m)); + const { fatal, unneeded } = classifyMissingSecrets( + wanted, + have, + registeredAgentPins(), + new Set(ctx.experiments.map((e) => e.agent)) + ); const details = [ `the workflow reads: ${wanted.join(', ')}`, ...unneeded.map( @@ -807,10 +899,11 @@ async function checkSecrets(ctx: Context): Promise { // 9 --------------------------------------------------------------------------- -async function checkMainGreen(ctx: Context): Promise { +export async function checkMainGreen(ctx: Context): Promise { const sha = ctx.dispatchSha; - if (!sha) + if (!sha) { return result('main-green', 'fail', 'could not read main from GitHub'); + } if (ctx.headSha === sha && !ctx.dirty) { // Checked out at exactly what a dispatch runs: run the same four commands @@ -847,11 +940,11 @@ async function checkMainGreen(ctx: Context): Promise { // Not checked out at main: the Checks workflow runs on pull requests only, so // read the run for the pull request that produced main. + const why = `HEAD ${ctx.headSha.slice(0, 7)}${ctx.dirty ? ' (dirty)' : ''} is not main ${sha.slice(0, 7)}`; const pulls = await ghJson< Array<{ number: number; merge_commit_sha: string; head: { sha: string } }> >(ctx, ['api', `repos/${ctx.repo}/commits/${sha}/pulls`]); const pr = pulls.find((p) => p.merge_commit_sha === sha); - const why = `HEAD ${ctx.headSha.slice(0, 7)}${ctx.dirty ? ' (dirty)' : ''} is not main ${sha.slice(0, 7)}`; if (!pr) { return result( 'main-green', @@ -866,6 +959,7 @@ async function checkMainGreen(ctx: Context): Promise { conclusion: string; headSha: string; event: string; + createdAt: string; }> >(ctx, [ 'run', @@ -875,9 +969,11 @@ async function checkMainGreen(ctx: Context): Promise { '--commit', pr.head.sha, '--json', - 'databaseId,conclusion,headSha,event', + 'databaseId,conclusion,headSha,event,createdAt', ]); - const run = runs.find((r) => r.event === 'pull_request'); + const run = runs + .filter((r) => r.event === 'pull_request') + .sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0]; if (!run) { return result('main-green', 'fail', `no Checks run for #${pr.number}`, [ why, @@ -887,27 +983,37 @@ async function checkMainGreen(ctx: Context): Promise { conclusion: string; jobs: Array<{ steps: Array<{ name: string; conclusion: string }> }>; }>(ctx, ['run', 'view', String(run.databaseId), '--json', 'conclusion,jobs']); - const steps = view.jobs.flatMap((j) => j.steps); - const wanted = [/format/i, /typecheck/i, /test/i, /build/i]; - const missing = wanted.filter( - (re) => !steps.some((s) => re.test(s.name) && s.conclusion === 'success') - ); - const details = [ + + // The base the pull request was merged onto is main's first parent. + const commit = await ghJson<{ parents: Array<{ sha: string }> }>(ctx, [ + 'api', + `repos/${ctx.repo}/commits/${sha}`, + ]); + const parent = commit.parents[0]?.sha; + let baseCommittedAt: string | undefined; + if (parent) { + const r = await ctx.deps.exec('gh', [ + 'api', + `repos/${ctx.repo}/commits/${parent}`, + '--jq', + '.commit.committer.date', + ]); + if (r.code === 0 && r.stdout.trim()) baseCommittedAt = r.stdout.trim(); + } + + const verdict = evaluateChecksRun({ + mainSha: sha, + prNumber: pr.number, + runId: run.databaseId, + runCreatedAt: run.createdAt, + conclusion: view.conclusion, + steps: view.jobs.flatMap((j) => j.steps), + baseCommittedAt, + }); + return result('main-green', verdict.status, verdict.summary, [ why, - `read from the Checks run on #${pr.number} (run ${run.databaseId}), which tested the pull request merged into its base at the time`, - ...steps - .filter((s) => wanted.some((re) => re.test(s.name))) - .map((s) => `${s.name}: ${s.conclusion}`), - ]; - const ok = view.conclusion === 'success' && missing.length === 0; - return result( - 'main-green', - ok ? 'pass' : 'fail', - ok - ? `#${pr.number}'s Checks passed format, typecheck, tests and build` - : `#${pr.number}'s Checks did not pass every step (${view.conclusion})`, - details - ); + ...verdict.details, + ]); } // 10 -------------------------------------------------------------------------- @@ -1012,7 +1118,15 @@ function describe(r: HookdeckResource): string { return `${r.id}${r.name ? ` (${r.name})` : ''}`; } -async function checkProjects(ctx: Context): Promise { +async function readKinds( + reader: GatewayReader +): Promise> { + const out: Record = {}; + for (const kind of RESOURCE_KINDS) out[kind] = await reader.list(kind); + return out; +} + +export async function checkProjects(ctx: Context): Promise { const fails: string[] = []; const warns: string[] = []; const details: string[] = []; @@ -1022,42 +1136,10 @@ async function checkProjects(ctx: Context): Promise { if (!env.HOOKDECK_API_KEY) { fails.push('HOOKDECK_API_KEY not set in .env: evals-ci not checked'); } else { - const gateway = new HookdeckClient({ apiKey: env.HOOKDECK_API_KEY }); - for (const kind of RESOURCE_KINDS) { - if (kind === 'issue-triggers') continue; - const rows = await gateway.list(kind); - if (rows.length > 0) { - fails.push( - `evals-ci holds ${rows.length} ${kind}: ${rows.map(describe).join(', ')}` - ); - } - } - const triggers = await gateway.list('issue-triggers'); - const declared = new Set(DEFAULT_ISSUE_TRIGGERS.map((d) => d.type)); - for (const d of DEFAULT_ISSUE_TRIGGERS) { - const ofType = triggers.filter((t) => t.type === d.type); - if (ofType.length === 0) - fails.push(`evals-ci has no ${d.type} issue trigger`); - if (ofType.length > 1) { - fails.push( - `evals-ci has ${ofType.length} ${d.type} issue triggers: ${ofType.map(describe).join(', ')}` - ); - } - for (const t of ofType) { - if (!issueTriggerMatchesDeclared(t, d.configs)) { - fails.push( - `evals-ci ${d.type} trigger ${t.id} differs from DEFAULT_ISSUE_TRIGGERS (configs, channels, name or enabled)` - ); - } - } - } - for (const t of triggers.filter((t) => !declared.has(String(t.type)))) { - fails.push( - `evals-ci has an undeclared ${String(t.type)} issue trigger ${t.id}` - ); - } + const resources = await readKinds(ctx.deps.gateway(env.HOOKDECK_API_KEY)); + fails.push(...evaluateGatewayProject(resources)); details.push( - `evals-ci: ${triggers.length} issue triggers against ${DEFAULT_ISSUE_TRIGGERS.length} declared` + `evals-ci: ${(resources['issue-triggers'] ?? []).length} issue triggers against ${DEFAULT_ISSUE_TRIGGERS.length} declared` ); } @@ -1072,24 +1154,15 @@ async function checkProjects(ctx: Context): Promise { 'OUTPOST_API_KEY is the evals-ci key: it must belong to a dedicated Outpost project (#111)' ); } else { - // The Outpost project's Event Gateway side: declared empty. - const declaredKinds = Object.keys(OUTPOST_GATEWAY_PRISTINE.ids); - const og = new HookdeckClient({ apiKey: outpostKey }); - let gatewayCount = 0; - for (const kind of RESOURCE_KINDS) { - const rows = await og.list(kind); - gatewayCount += rows.length; - if (rows.length > 0 && !declaredKinds.includes(kind)) { - fails.push( - `the Outpost project's gateway side holds ${rows.length} ${kind}: ${rows.map(describe).join(', ')}` - ); - } - } + // The Outpost project's Event Gateway side, against its declared baseline. + const resources = await readKinds(ctx.deps.gateway(outpostKey)); + fails.push(...evaluateOutpostGateway(resources, OUTPOST_GATEWAY_PRISTINE)); + const count = Object.values(resources).reduce((n, r) => n + r.length, 0); details.push( - `Outpost project gateway side: ${gatewayCount} resources, declared empty` + `Outpost project gateway side: ${count} resources, declared empty` ); - const outpost = new OutpostClient({ apiKey: outpostKey }); + const outpost = ctx.deps.outpost(outpostKey); const tenants = await outpost.tenants(); if (tenants.length > 0) { fails.push( @@ -1110,28 +1183,41 @@ async function checkProjects(ctx: Context): Promise { env.HOOKDECK_API_KEY, outpostKey, ]); + const label = `operator event destination ${d.id}`; details.push( - `operator event destination ${d.id} (${d.type}, ${(d.topics ?? []).join(', ')}): ${verdict.detail}` + `${label} (${d.type}, ${(d.topics ?? []).join(', ')}): ${verdict.detail}` ); - if (verdict.status === 'fail') - fails.push(`operator event destination ${d.id}: ${verdict.detail}`); - if (verdict.status === 'warn') - warns.push(`operator event destination ${d.id}: ${verdict.detail}`); - const attempts = await outpost - .request<{ models?: Array<{ status?: string; time?: string }> }>( - 'GET', + if (verdict.status === 'fail') fails.push(`${label}: ${verdict.detail}`); + if (verdict.status === 'warn') warns.push(`${label}: ${verdict.detail}`); + + let attempts: Array<{ status?: string }> | undefined; + try { + const page = await outpost.get<{ + models?: Array<{ status?: string }>; + }>( `/operator-events/attempts?destination_id=${encodeURIComponent(String(d.id))}&limit=20` - ) - .catch(() => undefined); - const rows = attempts?.models ?? []; - const failed = rows.filter((a) => a.status && a.status !== 'success'); - details.push( - ` last ${rows.length} attempts: ${rows.length - failed.length} succeeded, ${failed.length} did not` - ); - if (failed.length > 0) - warns.push( - `operator event destination ${d.id}: ${failed.length} recent attempts did not succeed` ); + attempts = page.models ?? []; + } catch (error) { + details.push( + ` could not read attempts: ${(error as Error).message.slice(0, 120)}` + ); + } + if (attempts) { + const failed = attempts.filter( + (a) => a.status && a.status !== 'success' + ); + details.push( + attempts.length === 0 + ? ' no attempts on record' + : ` last ${attempts.length} attempts: ${attempts.length - failed.length} succeeded, ${failed.length} did not` + ); + if (failed.length > 0) { + warns.push( + `${label}: ${failed.length} recent attempts did not succeed` + ); + } + } } } @@ -1149,12 +1235,12 @@ async function checkProjects(ctx: Context): Promise { } async function operatorEventDestinations( - outpost: OutpostClient + outpost: OutpostReader ): Promise { try { - const rows = await outpost.request< + const rows = await outpost.get< OperatorEventDestination[] | { models?: OperatorEventDestination[] } - >('GET', '/operator-events/destinations'); + >('/operator-events/destinations'); return Array.isArray(rows) ? rows : (rows.models ?? []); } catch (error) { // A project that has never had one answers 404 "tenant not found". @@ -1168,7 +1254,8 @@ const HOOKDECK_SOURCE_HOSTS = new Set(['hkdk.events', 'events.hookdeck.com']); /** * Whether a destination's URL is somewhere that exists, without sending it * anything: a request to a Hookdeck source URL is ingested and recorded in - * whichever project owns it, which is a write. + * whichever project owns it, which is a write. The URL is reported with its + * path masked, because a source URL lets anyone who holds it post events. */ async function destinationTarget( ctx: Context, @@ -1182,11 +1269,12 @@ async function destinationTarget( detail: `type ${d.type}: only webhook destinations are checked`, }; } + const shown = maskUrlPath(raw); let url: URL; try { url = new URL(raw); } catch { - return { status: 'fail', detail: `URL does not parse: ${raw}` }; + return { status: 'fail', detail: 'its URL does not parse' }; } if (url.host === 'mock.hookdeck.com') { return { @@ -1197,19 +1285,23 @@ async function destinationTarget( if (HOOKDECK_SOURCE_HOSTS.has(url.host)) { for (const key of keys) { if (!key) continue; - const sources = await new HookdeckClient({ apiKey: key }).list('sources'); + const sources = await ctx.deps.gateway(key).list('sources'); const owner = sources.find((s) => s.url === raw); - if (owner) - return { status: 'pass', detail: `Hookdeck source ${describe(owner)}` }; + if (owner) { + return { + status: 'pass', + detail: `${shown} is Hookdeck source ${describe(owner)}`, + }; + } } return { status: 'warn', - detail: `${raw} is a Hookdeck source in a project neither key can see; confirm it exists in the dashboard`, + detail: `${shown} is a Hookdeck source in a project neither key can see; confirm it exists in the dashboard`, }; } return (await ctx.deps.resolveHost(url.hostname)) - ? { status: 'pass', detail: `${url.host} resolves` } - : { status: 'fail', detail: `${url.host} does not resolve` }; + ? { status: 'pass', detail: `${shown}: ${url.host} resolves` } + : { status: 'fail', detail: `${shown}: ${url.host} does not resolve` }; } // 13 -------------------------------------------------------------------------- @@ -1267,8 +1359,9 @@ async function pinnedSkillFiles( const res = await ctx.deps.fetch( `https://raw.githubusercontent.com/${slug}/${pin}/${path}` ); - if (!res.ok) + if (!res.ok) { throw new Error(`${path} at ${pin.slice(0, 7)}: HTTP ${res.status}`); + } files.push({ path, text: await res.text() }); }); return files; @@ -1290,43 +1383,40 @@ async function pool( ); } -async function linkStatus(ctx: Context, url: string): Promise { - for (let attempt = 0; attempt < 2; attempt++) { - try { - const res = await ctx.deps.fetch(url, { - redirect: 'follow', - signal: AbortSignal.timeout(20_000), - }); - await res.body?.cancel(); - return res.status; - } catch { - // One retry for a dropped connection; a second failure is reported as 0. - } - } - return 0; -} - async function checkSkillLinks(ctx: Context): Promise { const files = await pinnedSkillFiles(ctx); const links = collectLinks(files); const bad: Array<{ url: string; status: number; files: string[] }> = []; + const moved: Array<{ url: string; finalUrl: string; files: string[] }> = []; await pool(links, 6, async (link) => { - const status = await linkStatus(ctx, link.url); - if (status !== 200) bad.push({ ...link, status }); + const checked = await checkLink(ctx.deps.fetch, link.url, ctx.deps.sleep); + if (checked.status !== 200) { + bad.push({ ...link, status: checked.status }); + } else if (checked.finalUrl) { + moved.push({ ...link, finalUrl: checked.finalUrl }); + } }); bad.sort((a, b) => a.url.localeCompare(b.url)); + moved.sort((a, b) => a.url.localeCompare(b.url)); + const status: CheckStatus = + bad.length > 0 ? 'fail' : moved.length > 0 ? 'warn' : 'pass'; return result( 'skill-links', - bad.length > 0 ? 'fail' : 'pass', + status, bad.length > 0 ? `${bad.length} of ${links.length} docs URLs in the pinned skills do not return 200` - : `all ${links.length} docs URLs in the pinned skills return 200`, + : moved.length > 0 + ? `all ${links.length} docs URLs return 200, ${moved.length} only after a redirect` + : `all ${links.length} docs URLs in the pinned skills return 200`, [ `skills ${ctx.skills.names.join(', ')} at ${ctx.skills.pin?.slice(0, 7)}, ${files.length} files`, ...bad.map( (b) => `${b.status || 'no response'} ${b.url} (in ${b.files.join(', ')})` ), + ...moved.map( + (m) => `redirected ${m.url} -> ${m.finalUrl} (in ${m.files.join(', ')})` + ), ] ); } @@ -1363,67 +1453,75 @@ async function checkHarnessIssues(ctx: Context): Promise { // 15 -------------------------------------------------------------------------- -async function publishedInstrument( - ctx: Context -): Promise<{ instrument: Instrument; source: string }> { - const runs = ctx.latest?.composition?.runs ?? []; - const newest = [...runs].sort((a, b) => b.latest.localeCompare(a.latest))[0]; - const runId = newest?.runId ?? ctx.latest?.runId; - const models: Record = {}; - for (const row of ctx.latest?.results ?? []) { - const experiment = row.experiment as string | undefined; - const display = row.experimentDisplay as { modelId?: string } | undefined; - if (!experiment || !display?.modelId) continue; - // Prefer the newest run's row when an experiment's rows disagree. - if (models[experiment] === undefined || row.runId === runId) { - models[experiment] = display.modelId; +/** + * What each agent's newest published cells ran under. + * + * Per agent rather than per snapshot: a published file merges runs, and the + * newest of them may carry no cells for an agent at all. Reading that agent's + * image and pins from it would clear a change no cell of that agent ran under. + */ +export async function publishedInstrument(ctx: Context): Promise { + const rows = (ctx.latest?.results ?? []) as PublishedRowLike[]; + const agentOf = new Map(ctx.experiments.map((e) => [e.name, e.agent])); + const runs = newestRunPerAgent(rows, (e) => agentOf.get(e)); + const shas = new Map(); + const byAgent: Record = {}; + for (const agent of [...ctx.agentsInPlan].sort()) { + const runId = runs[agent]; + if (!runId) { + byAgent[agent] = {}; + continue; } - } - if (!runId) - return { - instrument: { agentClis: {}, models }, - source: 'no published run', - }; - const view = await ghJson<{ headSha: string }>(ctx, [ - 'run', - 'view', - runId, - '--json', - 'headSha', - ]); - const sha = view.headSha; - const dockerfile = await fileAt(ctx, sha, 'packages/sandbox/Dockerfile'); - const image = await fileAt(ctx, sha, 'packages/sandbox/src/image.ts'); - const agentClis: Record = {}; - for (const agent of ctx.agentsInPlan) { - const src = await fileAt( + let sha = shas.get(runId); + if (!sha) { + sha = ( + await ghJson<{ headSha: string }>(ctx, [ + 'run', + 'view', + runId, + '--json', + 'headSha', + ]) + ).headSha; + shas.set(runId, sha); + } + const dockerfile = await fileAt(ctx, sha, 'packages/sandbox/Dockerfile'); + const image = await fileAt(ctx, sha, 'packages/sandbox/src/image.ts'); + const skills = await fileAt(ctx, sha, 'packages/sandbox/src/skills.ts'); + const runner = await fileAt( ctx, sha, `packages/core/src/agents/${agent}/runner.ts` ); - agentClis[agent] = src ? readPin(src, 'defaultCliVersion') : undefined; - } - return { - instrument: { + byAgent[agent] = { imageDefinition: dockerfile ? sandboxImageDefinition(dockerfile) : undefined, hookdeckCli: image ? readPin(image, 'HOOKDECK_CLI_VERSION') : undefined, - agentClis, - models, - }, - source: `run ${runId} at ${sha.slice(0, 7)}`, - }; + skillsCli: skills ? readPin(skills, 'SKILLS_CLI_VERSION') : undefined, + agentCli: runner ? readPin(runner, 'defaultCliVersion') : undefined, + source: `run ${runId} at ${sha.slice(0, 7)}`, + }; + } + return { byAgent, models: modelsFromRows(rows) }; } -async function checkCanary(ctx: Context): Promise { - const current: Instrument = { - imageDefinition: sandboxImageDefinition(), - hookdeckCli: HOOKDECK_CLI_VERSION, - agentClis: Object.fromEntries( - registeredAgentPins() - .filter((p) => ctx.agentsInPlan.has(p.id)) - .map((p) => [p.id, p.defaultCliVersion]) +function currentInstrument(ctx: Context): Instrument { + const pins = new Map( + registeredAgentPins().map((p) => [p.id, p.defaultCliVersion]) + ); + const imageDefinition = sandboxImageDefinition(); + return { + byAgent: Object.fromEntries( + [...ctx.agentsInPlan].map((agent) => [ + agent, + { + imageDefinition, + hookdeckCli: HOOKDECK_CLI_VERSION, + skillsCli: SKILLS_CLI_VERSION, + agentCli: pins.get(agent), + }, + ]) ), models: Object.fromEntries( ctx.experiments @@ -1431,17 +1529,24 @@ async function checkCanary(ctx: Context): Promise { .map((e) => [e.name, e.model]) ), }; - const { instrument, source } = await publishedInstrument(ctx); - const changes = diffInstrument(instrument, current); +} + +export async function checkCanary(ctx: Context): Promise { + const published = await publishedInstrument(ctx); + const changes = diffInstrument(published, currentInstrument(ctx)); + const sources = Object.entries(published.byAgent) + .map(([agent, i]) => `${agent}: ${i.source ?? 'no published run'}`) + .join('; '); if (changes.length === 0) { return result( 'canary', 'pass', - `not required: image, CLI pins and models match ${source}` + 'not required: image, CLI pins and models match the newest published cells of each agent', + [sources] ); } const details = [ - `against the newest published rows (${source}):`, + 'against the newest published cells of each agent:', ...changes.map((c) => ` ${c.what}: ${c.published} -> ${c.current}`), ]; @@ -1516,8 +1621,9 @@ async function verifyCanary( steps: Array<{ name: string; conclusion: string }>; }>; }>(ctx, ['run', 'view', runId, '--json', 'conclusion,headSha,jobs']); - if (view.conclusion !== 'success') + if (view.conclusion !== 'success') { problems.push(`run concluded ${view.conclusion || 'unfinished'}`); + } if (ctx.dispatchSha && view.headSha !== ctx.dispatchSha) { problems.push( `ran at ${view.headSha.slice(0, 7)}, not main ${ctx.dispatchSha.slice(0, 7)}` @@ -1525,8 +1631,9 @@ async function verifyCanary( } const cells = view.jobs.filter((j) => j.name.startsWith('run-evals')); for (const agent of ['claude-code', 'codex']) { - if (!cells.some((j) => j.name.includes(agent))) + if (!cells.some((j) => j.name.includes(agent))) { problems.push(`no ${agent} cell`); + } } for (const job of cells) { for (const step of ['Run evals', 'Check artifacts for credentials']) { @@ -1543,8 +1650,9 @@ async function verifyCanary( ); } const log = await ctx.deps.exec('gh', ['run', 'view', runId, '--log']); - if (log.stdout.includes(SANDBOX_SELF_CHECK_FAILED)) + if (log.stdout.includes(SANDBOX_SELF_CHECK_FAILED)) { problems.push('a cell failed the sandbox self-check'); + } const dir = mkdtempSync(join(tmpdir(), 'preflight-canary-')); try { @@ -1607,6 +1715,7 @@ const RUNNERS: Record Promise> = { 'skill-links': checkSkillLinks, 'harness-issues': checkHarnessIssues, canary: checkCanary, + 'skills-cli-pin': checkSkillsCli, }; async function guarded(ctx: Context, id: CheckId): Promise { @@ -1636,13 +1745,13 @@ export async function runPreflight( // Spend last and alone, because it may ask a question on the terminal. const ids = CHECKS.map((c) => c.id).filter((id) => id !== 'spend'); - const results = await Promise.all(ids.map((id) => guarded(ctx, id))); - results.push(await guarded(ctx, 'spend')); + const raw = await Promise.all(ids.map((id) => guarded(ctx, id))); + raw.push(await guarded(ctx, 'spend')); const notes: string[] = []; if (ctx.dispatchSha && ctx.headSha !== ctx.dispatchSha) { notes.push( - `pins, experiments and the base prompt were read from HEAD, which is not what a dispatch runs; check out main for a preflight that describes the dispatch` + 'pins, experiments and the base prompt were read from HEAD, which is not what a dispatch runs; check out main for a preflight that describes the dispatch' ); } if (ctx.dirty) notes.push('the working tree has uncommitted changes'); @@ -1650,19 +1759,21 @@ export async function runPreflight( `matrix: ${ctx.cells.length} cells (suites ${args.dispatch.suites.join(',')}; experiment suites ${args.dispatch.experimentSuites.join(',')}${args.dispatch.experiments.length ? `; experiments ${args.dispatch.experiments.join(',')}` : ''}${args.dispatch.evalIds.length ? `; evals ${args.dispatch.evalIds.join(',')}` : ''}; runs ${args.dispatch.runs})` ); - const meta = { + // Redact every string before it is laid out, so a value is caught whole + // rather than after JSON escaping or line-wrapping has changed its shape. + const results = redactArtifactDeep(raw) as CheckResult[]; + const meta = redactArtifactDeep({ generatedAt: new Date().toISOString(), headSha: ctx.headSha, dispatchSha: ctx.dispatchSha, skipped: args.skip, notes, - }; + }) as Parameters[1]; const code = exitCodeFor(results); - const secrets = collectEnvSecretValues(); - const text = args.json + const output = args.json ? JSON.stringify({ ...meta, exitCode: code, results }, null, 2) : formatReport(results, meta); - return { output: maskSecrets(redactSecrets(text), secrets), code }; + return { output, code }; } async function main() { @@ -1671,9 +1782,17 @@ async function main() { console.log(output); process.exitCode = code; } catch (error) { - console.error(`preflight: ${(error as Error).message}`); + console.error( + `preflight: ${redactSecretsForArtifact((error as Error).message)}` + ); process.exitCode = 2; } } -await main(); +// Only when run as a script, so the checks can be imported by tests. +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + await main(); +} diff --git a/apps/framework/test/preflight-checks.test.ts b/apps/framework/test/preflight-checks.test.ts new file mode 100644 index 0000000..5f52426 --- /dev/null +++ b/apps/framework/test/preflight-checks.test.ts @@ -0,0 +1,524 @@ +import { + DEFAULT_ISSUE_TRIGGERS, + type HookdeckResource, +} from '@hookdeck-evals/hookdeck'; +import { + HOOKDECK_CLI_VERSION, + SKILLS_CLI_VERSION, + sandboxImageDefinition, +} from '@hookdeck-evals/sandbox'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { EVALS_ROOT } from '../lib/discovery.js'; +import { parsePreflightArgs } from '../lib/preflight/args.js'; +import { + classifyMissingSecrets, + evaluateChecksRun, + evaluateGatewayProject, + evaluateOutpostGateway, +} from '../lib/preflight/evaluate.js'; +import { + checkCanary, + checkMainGreen, + checkProjects, + checkSecrets, + publishedInstrument, + type Context, + type Deps, +} from '../scripts/preflight.js'; + +/** + * The checks themselves, run against fakes. Everything they reach goes through + * `Deps`, so nothing here touches a network, a project or GitHub. + */ + +const read = (path: string) => readFileSync(join(EVALS_ROOT, path), 'utf8'); + +type Exec = Deps['exec']; + +function fakeDeps(over: Partial = {}): Deps { + return { + root: EVALS_ROOT, + env: {}, + exec: async () => ({ code: 1, stdout: '', stderr: 'not faked' }), + fetch: (async () => { + throw new Error('fetch not faked'); + }) as unknown as typeof fetch, + resolveHost: async () => true, + gateway: () => ({ list: async () => [] }), + outpost: () => ({ + tenants: async () => [], + get: async () => { + throw new Error('outpost not faked'); + }, + }), + sleep: async () => undefined, + ...over, + }; +} + +function fakeContext(over: Partial = {}): Context { + return { + deps: fakeDeps(), + args: parsePreflightArgs([]), + repo: 'hookdeck/evals', + headSha: 'h'.repeat(40), + dirty: false, + dispatchSha: 'm'.repeat(40), + lastRelease: 'v0.4.0', + workflow: read('.github/workflows/eval-refresh.yml'), + experiments: [ + { + name: 'claude-code-sonnet-5', + agent: 'claude-code', + provider: 'anthropic', + model: 'claude-sonnet-5', + suites: ['benchmark', 'regression'], + }, + { + name: 'codex-gpt-5.6', + agent: 'codex', + provider: 'openai', + model: 'gpt-5.6', + suites: ['benchmark', 'regression'], + }, + ], + cells: [], + experimentsInPlan: new Set(['claude-code-sonnet-5', 'codex-gpt-5.6']), + agentsInPlan: new Set(['claude-code', 'codex']), + evalsRequiringOutpost: [], + skills: { slug: 'hookdeck/agent-skills', names: [], dirs: [] }, + ...over, + }; +} + +/** An `exec` that answers by matching the joined command line. */ +function scriptedExec( + answers: Array<[RegExp, string | { code: number; stdout?: string }]> +): Exec { + return async (cmd, args) => { + const line = [cmd, ...args].join(' '); + for (const [re, answer] of answers) { + if (!re.test(line)) continue; + return typeof answer === 'string' + ? { code: 0, stdout: answer, stderr: '' } + : { code: answer.code, stdout: answer.stdout ?? '', stderr: '' }; + } + return { code: 1, stdout: '', stderr: `unexpected: ${line}` }; + }; +} + +// Finding 1: the canary compares each agent against its own newest cells ----- + +describe('canary run selection', () => { + const currentDockerfile = read('packages/sandbox/Dockerfile'); + const runner = (agent: string) => + read(`packages/core/src/agents/${agent}/runner.ts`); + + /** + * Two published runs: `old-run` had Codex and Claude cells on an older + * Dockerfile; `new-run`, newer, was a Claude-only partial publish on the + * current one. A Codex cell has never run on the current image. + */ + const rows = [ + { + experiment: 'codex-gpt-5.6', + runId: 'old-run', + ranAt: '2026-11-05T10:00:00Z', + experimentDisplay: { agent: 'codex', modelId: 'gpt-5.6' }, + }, + { + experiment: 'claude-code-sonnet-5', + runId: 'old-run', + ranAt: '2026-11-05T11:00:00Z', + experimentDisplay: { agent: 'claude-code', modelId: 'claude-sonnet-5' }, + }, + { + experiment: 'claude-code-sonnet-5', + runId: 'new-run', + ranAt: '2026-11-06T17:00:00Z', + experimentDisplay: { agent: 'claude-code', modelId: 'claude-sonnet-5' }, + }, + ]; + + const exec = scriptedExec([ + [ + /gh run view old-run --json headSha/, + JSON.stringify({ headSha: 'oldsha' }), + ], + [ + /gh run view new-run --json headSha/, + JSON.stringify({ headSha: 'newsha' }), + ], + // The old run's image is a different Dockerfile; everything else matches. + [ + /git show oldsha:packages\/sandbox\/Dockerfile/, + `${currentDockerfile}\n# older\n`, + ], + [/git show newsha:packages\/sandbox\/Dockerfile/, currentDockerfile], + [ + /git show \w+:packages\/sandbox\/src\/image.ts/, + read('packages/sandbox/src/image.ts'), + ], + [ + /git show \w+:packages\/sandbox\/src\/skills.ts/, + read('packages/sandbox/src/skills.ts'), + ], + [ + /git show \w+:packages\/core\/src\/agents\/codex\/runner.ts/, + runner('codex'), + ], + [ + /git show \w+:packages\/core\/src\/agents\/claude-code\/runner.ts/, + runner('claude-code'), + ], + ]); + + const ctx = () => + fakeContext({ + deps: fakeDeps({ exec }), + latest: { results: rows }, + }); + + it('reads Codex from the newest run that had Codex cells, not the newest run', async () => { + const published = await publishedInstrument(ctx()); + expect(published.byAgent['claude-code']?.source).toBe( + 'run new-run at newsha' + ); + expect(published.byAgent.codex?.source).toBe('run old-run at oldsha'); + expect(published.byAgent['claude-code']?.imageDefinition).toBe( + sandboxImageDefinition() + ); + expect(published.byAgent.codex?.imageDefinition).not.toBe( + sandboxImageDefinition() + ); + expect(published.byAgent.codex?.hookdeckCli).toBe(HOOKDECK_CLI_VERSION); + expect(published.byAgent.codex?.skillsCli).toBe(SKILLS_CLI_VERSION); + }); + + it('requires a canary for Codex after a Claude-only publish on a new image', async () => { + const result = await checkCanary(ctx()); + expect(result.status).toBe('fail'); + const moved = result.details.filter( + (d) => d.includes('->') && d.startsWith(' ') + ); + expect(moved).toHaveLength(1); + expect(moved[0]).toContain( + 'sandbox image definition (codex cells, run old-run at oldsha)' + ); + expect(result.details.join('\n')).toContain( + 'gh workflow run eval-refresh.yml' + ); + expect(result.details.join('\n')).toContain('codex-gpt-5.6'); + }); + + it('requires nothing when every agent last ran on the current instrument', async () => { + const same = scriptedExec([ + [/gh run view \S+ --json headSha/, JSON.stringify({ headSha: 'newsha' })], + [/git show newsha:packages\/sandbox\/Dockerfile/, currentDockerfile], + [ + /git show newsha:packages\/sandbox\/src\/image.ts/, + read('packages/sandbox/src/image.ts'), + ], + [ + /git show newsha:packages\/sandbox\/src\/skills.ts/, + read('packages/sandbox/src/skills.ts'), + ], + [ + /git show newsha:packages\/core\/src\/agents\/codex\/runner.ts/, + runner('codex'), + ], + [ + /git show newsha:packages\/core\/src\/agents\/claude-code\/runner.ts/, + runner('claude-code'), + ], + ]); + const result = await checkCanary( + fakeContext({ deps: fakeDeps({ exec: same }), latest: { results: rows } }) + ); + expect(result.status).toBe('pass'); + }); +}); + +// Finding 3: main-green from a pull request's Checks run ---------------------- + +describe('main is green, from a pull request', () => { + const steps = [ + { name: 'Check formatting', conclusion: 'success' }, + { name: 'Typecheck', conclusion: 'success' }, + { name: 'Unit tests', conclusion: 'success' }, + { name: 'Build', conclusion: 'success' }, + ]; + const evidence = { + mainSha: 'm'.repeat(40), + prNumber: 130, + runId: 1, + runCreatedAt: '2026-11-06T12:00:00Z', + conclusion: 'success', + steps, + }; + + it('passes when the base was committed before the run started', () => { + expect( + evaluateChecksRun({ + ...evidence, + baseCommittedAt: '2026-11-06T11:00:00Z', + }).status + ).toBe('pass'); + }); + + it('fails when the base moved after the run started', () => { + const verdict = evaluateChecksRun({ + ...evidence, + baseCommittedAt: '2026-11-06T13:00:00Z', + }); + expect(verdict.status).toBe('fail'); + expect(verdict.summary).toMatch(/base moved after #130's Checks started/); + }); + + it('fails when the base cannot be read, or a step did not pass', () => { + expect(evaluateChecksRun(evidence).status).toBe('fail'); + expect( + evaluateChecksRun({ + ...evidence, + baseCommittedAt: '2026-11-06T11:00:00Z', + steps: steps.map((s) => + s.name === 'Typecheck' ? { ...s, conclusion: 'failure' } : s + ), + }).status + ).toBe('fail'); + }); + + it('reads main, its pull request, the run and the base through Deps', async () => { + const main = 'm'.repeat(40); + const exec = scriptedExec([ + [ + /commits\/m+\/pulls/, + JSON.stringify([ + { number: 130, merge_commit_sha: main, head: { sha: 'prhead' } }, + ]), + ], + [ + /gh run list --workflow biome.yml --commit prhead/, + JSON.stringify([ + { + databaseId: 7, + conclusion: 'success', + headSha: 'prhead', + event: 'pull_request', + createdAt: '2026-11-06T12:00:00Z', + }, + ]), + ], + [ + /gh run view 7 --json conclusion,jobs/, + JSON.stringify({ conclusion: 'success', jobs: [{ steps }] }), + ], + [/commits\/base --jq/, '2026-11-06T13:30:00Z\n'], + [ + /repos\/hookdeck\/evals\/commits\/m+$/, + JSON.stringify({ parents: [{ sha: 'base' }] }), + ], + ]); + const result = await checkMainGreen( + fakeContext({ deps: fakeDeps({ exec }) }) + ); + expect(result.status).toBe('fail'); + expect(result.details.join('\n')).toContain( + 'base committed 2026-11-06T13:30:00Z' + ); + }); +}); + +// Secrets --------------------------------------------------------------------- + +describe('secrets', () => { + const agents = [ + { id: 'claude-code', apiKeyEnvVar: 'ANTHROPIC_API_KEY' }, + { id: 'codex', apiKeyEnvVar: 'OPENAI_API_KEY' }, + { id: 'opencode', apiKeyEnvVar: 'AI_GATEWAY_API_KEY' }, + ]; + + it('excuses only the key of an agent no experiment uses', () => { + expect( + classifyMissingSecrets( + ['AI_GATEWAY_API_KEY', 'OPENAI_API_KEY', 'OUTPOST_API_KEY'], + new Set(), + agents, + new Set(['claude-code', 'codex']) + ) + ).toEqual({ + fatal: ['OPENAI_API_KEY', 'OUTPOST_API_KEY'], + unneeded: ['AI_GATEWAY_API_KEY'], + }); + }); + + it('does not excuse a key once an experiment uses its agent', () => { + expect( + classifyMissingSecrets( + ['AI_GATEWAY_API_KEY'], + new Set(), + agents, + new Set(['opencode']) + ).fatal + ).toEqual(['AI_GATEWAY_API_KEY']); + }); + + it('fails the check on a needed secret the repository lacks', async () => { + const exec = scriptedExec([ + [ + /gh secret list/, + JSON.stringify([ + { name: 'ANTHROPIC_API_KEY' }, + { name: 'OPENAI_API_KEY' }, + ]), + ], + ]); + const result = await checkSecrets( + fakeContext({ deps: fakeDeps({ exec }) }) + ); + expect(result.status).toBe('fail'); + expect(result.summary).toContain('HOOKDECK_API_KEY'); + expect(result.summary).not.toContain('AI_GATEWAY_API_KEY'); + }); +}); + +// Projects are pristine ------------------------------------------------------- + +const defaults = (): HookdeckResource[] => + DEFAULT_ISSUE_TRIGGERS.map((d, i) => ({ + id: `it_${i}`, + type: d.type, + configs: d.configs, + channels: {}, + disabled_at: null, + name: null, + created_at: '2026-08-07T00:00:00Z', + })); + +describe('projects are pristine', () => { + it('accepts exactly the declared default triggers and nothing else', () => { + expect( + evaluateGatewayProject({ 'issue-triggers': defaults(), sources: [] }) + ).toEqual([]); + }); + + it('names a leftover, a duplicate, a rewritten default and an undeclared type', () => { + const triggers = defaults(); + triggers[0] = { + ...triggers[0], + channels: { email: {} }, + } as HookdeckResource; + triggers.push({ + id: 'it_dup', + type: DEFAULT_ISSUE_TRIGGERS[1]?.type, + configs: {}, + }); + triggers.push({ id: 'it_new', type: 'mystery' }); + const fails = evaluateGatewayProject({ + 'issue-triggers': triggers, + sources: [{ id: 'src_1', name: 'stripe' }], + }); + expect(fails.join('\n')).toContain( + 'evals-ci holds 1 sources: src_1 (stripe)' + ); + expect(fails.join('\n')).toContain(`differs from DEFAULT_ISSUE_TRIGGERS`); + expect(fails.join('\n')).toContain( + `2 ${DEFAULT_ISSUE_TRIGGERS[1]?.type} issue triggers` + ); + expect(fails.join('\n')).toContain( + 'undeclared mystery issue trigger it_new' + ); + }); + + it('compares the Outpost gateway side by id against its baseline', () => { + const baseline = { capturedAt: 'declared', ids: { sources: ['src_ok'] } }; + expect( + evaluateOutpostGateway( + { sources: [{ id: 'src_ok' }, { id: 'src_left' }], connections: [] }, + baseline + ) + ).toEqual([ + "the Outpost project's gateway side holds 1 sources its baseline does not declare: src_left", + ]); + }); + + it('passes both projects, and masks the destination URL, through Deps', async () => { + const sourceUrl = 'https://hkdk.events/secretpath123'; + const deps = fakeDeps({ + env: { HOOKDECK_API_KEY: 'gateway-key', OUTPOST_API_KEY: 'outpost-key' }, + gateway: (key) => ({ + list: async (kind) => { + if (key === 'gateway-key' && kind === 'issue-triggers') + return defaults(); + if (key === 'gateway-key' && kind === 'sources') return []; + return []; + }, + }), + outpost: () => ({ + tenants: async () => [], + get: async (path: string) => { + if (path === '/operator-events/destinations') { + return [ + { + id: 'des_1', + type: 'webhook', + topics: ['*'], + config: { url: sourceUrl }, + }, + ] as T; + } + throw new Error('Outpost GET failed: 500'); + }, + }), + }); + const result = await checkProjects(fakeContext({ deps })); + // The source is in neither project these keys see, so it cannot be verified. + expect(result.status).toBe('warn'); + const text = [result.summary, ...result.details].join('\n'); + expect(text).toContain('https://hkdk.events/****'); + expect(text).not.toContain('secretpath123'); + expect(text).toContain('could not read attempts'); + expect(text).not.toContain('0 attempts'); + }); + + it('fails on a stray tenant and on a mock endpoint as the alert destination', async () => { + const deps = fakeDeps({ + env: { HOOKDECK_API_KEY: 'gateway-key', OUTPOST_API_KEY: 'outpost-key' }, + gateway: (key) => ({ + list: async (kind) => + key === 'gateway-key' && kind === 'issue-triggers' ? defaults() : [], + }), + outpost: () => ({ + tenants: async () => [{ id: 'acme' }], + get: async (path: string) => + (path === '/operator-events/destinations' + ? [ + { + id: 'des_1', + type: 'webhook', + config: { url: 'https://mock.hookdeck.com/x' }, + }, + ] + : { models: [] }) as T, + }), + }); + const result = await checkProjects(fakeContext({ deps })); + expect(result.status).toBe('fail'); + expect(result.summary).toContain('stray Outpost tenants: acme'); + expect(result.summary).toContain('mock endpoint'); + }); + + it('refuses an Outpost key that is the gateway key', async () => { + const deps = fakeDeps({ + env: { HOOKDECK_API_KEY: 'same', OUTPOST_API_KEY: 'same' }, + gateway: () => ({ + list: async (kind) => (kind === 'issue-triggers' ? defaults() : []), + }), + }); + const result = await checkProjects(fakeContext({ deps })); + expect(result.status).toBe('fail'); + expect(result.summary).toContain('#111'); + }); +}); diff --git a/apps/framework/test/preflight.test.ts b/apps/framework/test/preflight.test.ts index 0c0221b..980f2eb 100644 --- a/apps/framework/test/preflight.test.ts +++ b/apps/framework/test/preflight.test.ts @@ -7,10 +7,13 @@ import { CHECKS, parsePreflightArgs } from '../lib/preflight/args.js'; import { canaryPlan, diffInstrument, + modelsFromRows, + newestRunPerAgent, readPin, } from '../lib/preflight/canary.js'; import { changedSkills, + checkLink, collectLinks, extractDocsUrls, fetchableUrl, @@ -26,6 +29,7 @@ import { exitCodeFor, formatReport, maskSecrets, + maskUrlPath, type CheckResult, } from '../lib/preflight/report.js'; import { @@ -73,6 +77,13 @@ describe('semver', () => { expect(() => compareSemver('x', '1.0.0')).toThrow(/not a version/); }); + it('orders prerelease identifiers as semver does', () => { + expect(compareSemver('1.0.0-rc.2', '1.0.0-rc.10')).toBe(-1); + expect(compareSemver('1.0.0-alpha', '1.0.0-alpha.1')).toBe(-1); + expect(compareSemver('1.0.0-1', '1.0.0-alpha')).toBe(-1); + expect(compareSemver('1.0.0-beta', '1.0.0-alpha.9')).toBe(1); + }); + it('names the largest component that moved', () => { expect(describeVersionGap('2.5.0', '3.1.0')).toBe( '1 major version behind (2.5.0 -> 3.1.0)' @@ -271,6 +282,76 @@ describe('links', () => { ]); }); + const respond = ( + status: number, + over: { redirected?: boolean; url?: string; retryAfter?: string } = {} + ) => + ({ + status, + redirected: over.redirected ?? false, + url: over.url ?? '', + headers: new Headers( + over.retryAfter ? { 'retry-after': over.retryAfter } : {} + ), + body: null, + }) as unknown as Response; + + it('reports where a redirect ended', async () => { + const result = await checkLink( + async () => + respond(200, { + redirected: true, + url: 'https://hookdeck.com/docs/api/configure.md', + }), + 'https://hookdeck.com/docs/api/sources.md' + ); + expect(result).toEqual({ + url: 'https://hookdeck.com/docs/api/sources.md', + status: 200, + finalUrl: 'https://hookdeck.com/docs/api/configure.md', + }); + }); + + it('does not report a trailing-slash redirect as a moved page', async () => { + const result = await checkLink( + async () => + respond(200, { redirected: true, url: 'https://hookdeck.com/docs' }), + 'https://hookdeck.com/docs/' + ); + expect(result.finalUrl).toBeUndefined(); + }); + + it('backs off once on a 429, honouring Retry-After, then reports what it got', async () => { + const answers = [respond(429, { retryAfter: '2' }), respond(200)]; + const sleeps: number[] = []; + const result = await checkLink( + async () => answers.shift() as Response, + 'https://hookdeck.com/docs/a.md', + async (ms) => { + sleeps.push(ms); + } + ); + expect(result.status).toBe(200); + expect(sleeps).toEqual([2000]); + + const limited = await checkLink( + async () => respond(429), + 'https://hookdeck.com/docs/a.md', + async () => undefined + ); + expect(limited.status).toBe(429); + }); + + it('retries a dropped connection once and reports 0 if it stays down', async () => { + let calls = 0; + const result = await checkLink(async () => { + calls += 1; + throw new Error('ECONNRESET'); + }, 'https://hookdeck.com/docs/a.md'); + expect(calls).toBe(2); + expect(result.status).toBe(0); + }); + it('maps changed paths to the skills they belong to', () => { expect( changedSkills([ @@ -318,41 +399,126 @@ describe('models', () => { }); describe('canary', () => { - const base = { + const agent = { imageDefinition: 'aaa', hookdeckCli: '2.5.0', - agentClis: { codex: '0.138.0' }, + skillsCli: '1.5.11', + agentCli: '0.138.0', + }; + const base = { + byAgent: { codex: agent }, models: { 'codex-gpt-5.6': 'gpt-5.6' }, }; it('needs nothing when the instrument matches', () => { - expect(diffInstrument(base, base)).toEqual([]); + expect( + diffInstrument( + { ...base, byAgent: { codex: { ...agent, source: 'run 1 at abc' } } }, + base + ) + ).toEqual([]); }); - it('names each moved part, and counts an unknown published value as moved', () => { + it('names each moved part per agent, and counts an unknown published value as moved', () => { const changes = diffInstrument( - { ...base, imageDefinition: undefined }, { - ...base, - hookdeckCli: '3.1.0', + byAgent: { + codex: { + ...agent, + imageDefinition: undefined, + source: 'run 1 at abc', + }, + }, + models: base.models, + }, + { + byAgent: { + codex: { ...agent, hookdeckCli: '3.1.0', skillsCli: '1.6.0' }, + }, models: { ...base.models, 'new-experiment': 'gpt-6' }, } ); expect(changes).toEqual([ { - what: 'sandbox image definition', + what: 'sandbox image definition (codex cells, run 1 at abc)', published: 'unknown', current: 'aaa', + agent: 'codex', + }, + { + what: 'Hookdeck CLI pin (codex cells, run 1 at abc)', + published: '2.5.0', + current: '3.1.0', + agent: 'codex', + }, + { + what: 'skills CLI pin (codex cells, run 1 at abc)', + published: '1.5.11', + current: '1.6.0', + agent: 'codex', }, - { what: 'Hookdeck CLI pin', published: '2.5.0', current: '3.1.0' }, { what: 'new-experiment model', published: 'unknown', current: 'gpt-6' }, ]); }); + it('treats an agent with no published cells as entirely unknown', () => { + const changes = diffInstrument( + { byAgent: {}, models: {} }, + { byAgent: { codex: agent }, models: {} } + ); + expect(changes.map((c) => c.published)).toEqual([ + 'unknown', + 'unknown', + 'unknown', + 'unknown', + ]); + expect(changes[0]?.what).toContain('no published run'); + }); + + it('picks, per agent, the newest run that has that agent’s rows', () => { + const agentOf = (e: string) => + e.startsWith('claude') ? 'claude-code' : 'codex'; + const rows = [ + { + experiment: 'codex-gpt-5.6', + runId: 'older', + ranAt: '2026-11-05T10:00:00Z', + }, + { + experiment: 'claude-code-sonnet-5', + runId: 'older', + ranAt: '2026-11-05T11:00:00Z', + }, + // A Claude-only partial publish, newer than anything Codex ran in. + { + experiment: 'claude-code-sonnet-5', + runId: 'newest', + ranAt: '2026-11-06T17:00:00Z', + }, + ]; + expect(newestRunPerAgent(rows, agentOf)).toEqual({ + 'claude-code': 'newest', + codex: 'older', + }); + }); + + it('takes each experiment’s model from its newest row', () => { + expect( + modelsFromRows([ + { experiment: 'a', ranAt: '1', experimentDisplay: { modelId: 'old' } }, + { experiment: 'a', ranAt: '2', experimentDisplay: { modelId: 'new' } }, + { experiment: 'b', ranAt: '1' }, + ]) + ).toEqual({ a: 'new' }); + }); + it('reads pins out of the real sources', () => { expect( readPin(read('packages/sandbox/src/image.ts'), 'HOOKDECK_CLI_VERSION') ).toMatch(/^\d+\.\d+\.\d+$/); + expect( + readPin(read('packages/sandbox/src/skills.ts'), 'SKILLS_CLI_VERSION') + ).toMatch(/^\d+\.\d+\.\d+$/); expect( readPin( read('packages/core/src/agents/codex/runner.ts'), @@ -469,10 +635,11 @@ describe('arguments', () => { expect(() => parsePreflightArgs(['--runs', '0'])).toThrow(/positive/); }); - it('numbers the checks as #131 does', () => { + it('numbers the checks as #131 does, with the skills CLI after the canary', () => { expect(CHECKS.map((c) => c.number)).toEqual( - Array.from({ length: 15 }, (_, i) => i + 1) + Array.from({ length: 16 }, (_, i) => i + 1) ); + expect(CHECKS[15]?.id).toBe('skills-cli-pin'); }); }); @@ -538,6 +705,17 @@ describe('report', () => { ]) ).toBe('key **** and ****'); }); + + it('masks a delivery URL down to its host', () => { + expect(maskUrlPath('https://hkdk.events/hV1wGFnIHOex')).toBe( + 'https://hkdk.events/****' + ); + expect(maskUrlPath('https://example.com/?token=abc')).toBe( + 'https://example.com/****' + ); + expect(maskUrlPath('https://example.com/')).toBe('https://example.com/'); + expect(maskUrlPath('not a url')).toBe('****'); + }); }); describe('base prompt', () => { diff --git a/packages/hookdeck/src/index.ts b/packages/hookdeck/src/index.ts index fd7177c..fb96f40 100644 --- a/packages/hookdeck/src/index.ts +++ b/packages/hookdeck/src/index.ts @@ -35,7 +35,12 @@ export type { } from './seed.js'; export { hookdeckRuntime, hookdeckMcpServer } from './runtime.js'; export type { HookdeckRuntimeOptions } from './runtime.js'; -export { collectEnvSecretValues, redactSecrets } from './redact.js'; +export { + collectEnvSecretValues, + redactArtifactDeep, + redactSecrets, + redactSecretsForArtifact, +} from './redact.js'; export { OutpostClient, OUTPOST_API_BASE } from './outpost-client.js'; export type { OutpostClientOptions } from './outpost-client.js'; export { setConnectionRules } from './solutions.js';