Files
Ashish Kumar Singh dc66b410e3 Replace the eval tasks with four harder ones (#525)
* Replace the eval tasks with four multi-turn tasks

The three tasks were single-request contracts in toy domains, and the
one that looked saturated (project-doc, 8/10) was failing on a verifier
that rejected a literal reading of its own prompt. None was
long-horizon, only one had a second turn, and nothing checked whether
the agent's words matched the data.

Four tasks replace them, all multi-turn, verified through the Gadget's
RPC against references the verifier owns:

- change-calendar: a maintenance-window calendar built to an exact
  contract, written up as a Document from its own data, changed under
  new rules, committed and reloaded, then asked a question whose
  answer is in the seeded schedule.
- worker-logs: a Workers request-log analyser fed a seeded day of
  events with one planted bad hour; filters and rankings are added,
  then the agent is asked which Worker had the worst hour, in a fixed
  reply shape checked against the data.
- incident-desk: an on-call desk where twenty responders acknowledge
  at once and exactly one may win, then escalation and metrics.
- chess: a complete engine written without a library, then PGN, then
  draw detection, each checked differentially against chess.js on
  curated positions and seeded random games. Either en passant FEN
  convention is accepted.

The verifier now sees the agent's chat replies for the question turns,
and the verification budget grows to four minutes: these checks make
hundreds of RPC calls a turn.

* Regenerate the lockfile after the rebase

The rebase onto main left pnpm-lock.yaml referencing a vitest 4.1.11 entry that no
longer existed, so vp install failed with ERR_PNPM_LOCKFILE_MISSING_DEPENDENCY. Rebuilt
from main's lockfile; the only difference is the chess.js dependency this branch adds.

* Close the verifier gaps the review found

Each check now fails for the wrong implementation it was meant to catch.

change-calendar: conflict ids are compared element by element, not through a joined string;
the plan needs one distinct bullet per window; the seeded-windows check also asks conflicts()
over a range that overlaps both api-gateway windows, so the RPC is exercised after the rule
change and after commit.

incident-desk: every incident turn 1 left is compared on service, severity, summary, owner,
timestamps and escalations, not just id and status; a race winner's owner must be the
responder, and UNKNOWN_INCIDENT and ALREADY_RESOLVED must carry owner: null; escalation is
exercised on an acknowledged incident and must keep its owner; metrics are checked on a
service holding an open, an acknowledged and a resolved incident, and the empty service on
all five fields.

worker-logs: failures now include 501 and 504; three worker+route pairs share a planted slow
tail so slowestRoutes has to break the p95 tie by worker then route, with a module-load guard
that the data still does; turn 2 resets and re-ingests to prove reset() survived the edit.

chess: a refused move must also leave the game's PGN unchanged once PGN exists; six plausible
six-field FENs must be refused; Black castling, en passant and promotion have fixtures the
oracle is checked to offer; the post-draw random game compares the draw fields.

* Check the game record after a rejected PGN and the winning open's severity

A refused loadPgn must leave pgn() as it was, not only the position. The one open() that wins
the simultaneous-opens race must have stored the severity it was sent, not a default.

* Verify each check from the contract, not from one correct gadget

One pass over the four verifiers with three rules: after a mutation, assert the return and
re-read the whole record; give every parser one input shape a lazy parser gets wrong; for
rules that interact, one case where the order matters. Each check stays satisfiable by any
correct reading of its prompt: the offset-timestamp probe asserts only that scheduling fails,
since the prompt fixes no code for it, and K+NN vs K is left out because the prompt does not
define insufficient material and engines disagree.

incident-desk: the turn-one predicate covers inc-1 after resolve too; escalation must change
severity and the count and nothing else, and is read back after every call including the
refused one; race-open's severity is checked against the attempt its summary names; the opens
a check depends on fail the check when refused.

chess: compareHere also reads fen(), so the stored position is checked wherever moves and
status are, including after each special move; the PGN self-comparison strips tag pairs so a
Gadget that adds a Date tag is not failed for it; the repetition and fifty-move moves are
asserted.

change-calendar: the touching window is mw-100 so conflicts() has to sort; two new windows in
one turn 22 hours apart; a +05:00 start that is outside hours in UTC must fail; a bullet may
state its length as hours and minutes.

worker-logs: the planted slow tail sits in one colo, so a colo-filtered ranking differs from
the day's; one summary range has endpoints inside an hour.

* Check state after refusals, grandfathered windows and loadFen resets

incident-desk: a refused escalation of a resolved incident must leave it unchanged, and one of an
unknown id must not create it.

change-calendar: seed a six-hour billing window, valid under turn 1's cap and over turn 2's, so a
migration that drops windows the new rules would refuse fails "everything already scheduled stays".

chess: after the start position has occurred three times, loading it again must not report a
repetition, and the loaded fifty-move position must match the oracle before the move that draws.

* Run each eval task on its own runner

A run took as long as the sum of two lanes of slowest trials, because two eval files shared
one runner at a time: chess 316 s plus change-calendar 135 s made the last run 451 s. Each
eval file of each measured revision now gets its own runner, so a run takes as long as its
slowest task, and a runner hosts 10 Workshops instead of 20.

A plan job lists the eval files at each revision from a sparse checkout, and an assemble job
per revision joins the per-task reports. It fails unless it has exactly the planned files,
since a missing task would otherwise read as removed and be cached that way. The push
baseline goes through the same jobs, so main and pull requests are measured the same way,
and the cache key records the layout so older baselines are measured again rather than
compared against. A failed candidate no longer stops a complete baseline from being cached.

* Measure evals on GPT-6 Luna

Makes GPT-6 Luna, which #556 added to the suggested models, the model eval baselines are
measured on.

* Probe DUPLICATE_ID with a window that breaks no other rule

The probe resubmitted mw-101 unchanged, so it also overlapped mw-101, and the prompt does not
say whether DUPLICATE_ID or OVERLAP wins. GPT 6 Luna answered OVERLAP in 3 of 10 trials, a
defensible reading the check failed. The probe now reuses mw-101's id at a time that overlaps
nothing.

* Close the gaps in Bonk's last two reviews

chess: turn 3 checks that malformed FENs are still refused, and reaches insufficient material
by a capture as well as by loading; PGN export must replay to the played position, not only
the same moves; imports include games ending 0-1 and 1/2-1/2. Before turn 3 defines draws,
only a dead position may list no legal moves.

incident-desk: a turn-two open reads back exactly as submitted.

change-calendar: no bullet anywhere in the plan, including before the first heading, may
list a window outside the week.

worker-logs: events arrive in a seeded random order, so ordering by first appearance fails.

* Show eval pass rates as bars and mark each change's direction

The comparison comment opens with every cohort's pass rate as a ten-cell bar, green for
passed and red for failed, compared or not, and marks each pass delta green, red or grey.
The Bonk review gets a coloured verdict, marks deltas as rising or falling, and copies the
bars from the comparison instead of drawing its own, so its numbers stay the comparison's.

* Lead the eval results comment with a verdict and failure details

The comment now opens with one verdict (improved, regressed, unchanged
or inconclusive) and the files the evals exercise that the PR changed.
The score table shows pass bars for every task and colours a pass-rate
change only when it is significant. Under the table, each task with
failures lists its failing checks, the first failing evidence, its most
common tool errors, and infrastructure errors apart from the agent's.

Bonk reuses the computed verdict instead of deciding its own.

* Keep the eval results comment short

Show file names rather than paths, one tool error per task rather than
five, and no raw evidence line; comparison.json keeps the evidence for
Bonk. Drop the red marker on check counts, which went up on noise.

* Key the eval baseline by the files the evals exercise

A baseline was cached per commit, so every main commit needed its own
measurement even when it changed nothing the evals depend on. Key it by
the blob ids of the workflow's trigger paths instead: commits that leave
them alone share one measurement, whichever PR or push made it. Bonk's
diff now starts at the PR's base, since the baseline may be older.

Record why each eval file keeps its own runner: all four on one runner
ran it out of memory.

* Have Bonk explain why each task failed

Bonk's review stopped at 'nothing is comparable' on any PR that changes
the tasks, and otherwise named one difference. It now gives one line per
task with failed runs: what the agent did wrong, one cause (system
prompt, tool design, harness bug, verifier or model error) and a fix,
reading the system prompt and tool definitions to tell them apart.

Key the baseline by commit again. Keying it by the trigger paths' content
reused baselines across main commits that changed code the evals run but
the paths do not list, such as files overseer.ts imports and the lockfile.
Keep the note on why each eval file has its own runner.

* Post eval results at the end of the PR, replacing earlier ones

The results comment was edited in place, so after a few pushes it sat
far above the conversation, and every run added another Bonk review.
Each run now deletes this workflow's earlier results comments and
Bonk's earlier eval reviews, then posts the new results; Bonk's review
follows. Bonk's code reviews and people's comments are left alone.

Let Bonk grep and list files as well as read them: a run's trajectories
are about 25,000 lines, too long to page through.

* Share one Workshop across an eval file's trials

Each trial started its own Workshop, about 340 MB, so 40 trials ran a
16 GB runner out of memory and every task needed its own runner. Now an
eval file starts one Workshop per model and its trials share it, each
with its own user and workspace. With all four files running at once on
one runner, the probe peaked at 7.7 GB with no infrastructure errors in
40 trials, so Vitest now runs every file at once.

The Workshop closes after the file's last trial and before the network
filter comes off, so no worker outlives the filter.

* Reuse each task's eval result until something it runs changes

Every push measured both sides of the comparison, and every relevant
merge measured main again, even when nothing a task runs had changed.
Now each task's result is stored under a key of the files its run
executes: the Worker's inputs, the harness, the shared helpers, the task
file, and the workflow's eval settings. A run measures only the tasks
with no stored result, in at most one job per side, and a key both sides
share is measured once. The comparison and Bonk's review run again only
when their own code or a task's key changed, or on a manual re-run.

The rules that decide whether a result is stored move into results.ts,
which is part of every key, as is the validator script. Whether a task
is comparable, and which files differ, now come from the keys instead of
a git diff, so a task's id must match its file name. A newer push waits
for the run in progress instead of cancelling it, and the results
comment is posted before the earlier ones are deleted.

* Keep test edits out of the report key and say results are reused

Editing a test under scripts/evals changed the report key, so it reposted the same results and
ran Bonk again. Test files now change no key. The results header said each task ran once per
commit, but a task's result can come from an earlier run with the same inputs, so the header now
says so. The key's comment now states the rule the code follows: files that can change a result,
not every file a run executes.

* Simplify the eval results comment and restructure Bonk's review

The results comment is now the verdict and one table. Each row gives
the task's score on both sides, the change, Fisher's exact test, and
the average minutes, cost and steps per run. The file list, the commit
line, the pass-rate tiles and the per-task failure breakdown are gone,
and the eval keys no longer list changed files, since only that line
read them. Headers are short and values do not break, so the table
fits a pull request comment.

Bonk's review now gives performance, failure modes with their cause,
whether this PR caused each one, and what to do, then the verdict in
caps. A failure is this PR's only when the code at fault changed, and
REGRESSION needs a significant fall in comparison.json. The heading is
main's "Eval runs review" again, so reviews that main posted are still
replaced.

* Show scores as percentages and close two verifier gaps

The results table shows each score as a pass rate, for example
90% → 70%, next to the change in percentage points.

The plan document's own title must now be the name the prompt asks
for. Turn 2 of incident-desk must give back every turn-1 record
exactly, including who won each race and when; it may only add the
escalation count. Each trial keeps its turn-1 board by its Desk,
because trials share the module. All ten real trials of each task
already pass both checks.

* Pool turn one's incident records instead of keying them by Workpiece id

Workpiece ids are workspace-local, so every trial's Desk is id 0 and the
ten concurrent trials overwrote each other's turn-one snapshot: eight of
ten turn-two checks compared against another trial's board. Turn one now
adds each record to one pool, and turn two requires each of its records
to be in it. A record holds its own trial's timestamps and race winners,
so one that changed matches no trial's copy.

Replayed on the real boards of run 36057910489: the old code flags all
seven records in 8 of 9 intact trials, the new code flags none, and it
still flags a swapped owner, a 1 ms timestamp shift, reset timestamps
and a dropped record.

* Keep a closing session connected until its workspace's abort lands

Closing a trial's session deletes its workspace, and deleteSelf() aborts
the workspace DO about 100 ms later. close() disposed its stubs at once,
so the abort found no client left. When the DO has started a Gadget
facet, that segfaults local workerd. Miniflare restarts it, and every
other session on the same Workshop loses its socket: turns reconnect,
but a verifier call in flight fails and counts as the agent's failure.
With one Workshop per eval file, most trial closes crashed it (33 times
in one 40-trial run).

close() now waits for the Workshop to drop the session, which the abort
causes, before disposing. A drop that never comes fails close() instead
of passing silently. The target.ts comment said this crash had not
happened; it now states what sharing a Workshop costs.

A model-free repro on Node 24 goes from 10 crashes and 24 failed
in-flight calls in 24 closes to none. close() takes about 110 ms.

* Move the eval workflow's plan, join and post steps into TypeScript

These steps were about 120 lines of bash and jq inside the workflow, with
no tests. scripts/evals/workflow.ts now holds them as subcommands, and
workflow.test.ts covers the decisions a plausible bug would break: which
stored results are reused, which revision measures a shared key, when the
posted comments are current, and which comments a new one replaces.

On valid input the behaviour is the same. On real stored results and on
crafted commits, plan wrote byte-identical outputs in every scenario and
join wrote byte-identical results files. Run against a stand-in for the
GitHub API, post built the same comment and deleted the same comments.
The measurement settings are unchanged, so every stored result stays
valid. On malformed input the script no longer guesses: an artifact with
no recorded run is not reused, a clean list that does not parse fails the
join, and a comment with no body is skipped.

Only Node built-ins are imported, so the plan job still needs no install
step. eval-keys.ts now exports evalKeys(); its command line is unchanged.

* Remove the JSON reader layer from workflow.ts

workflow.ts had one reader per JSON shape (field, stringField,
numberField, listOf, revisionOf, sourceOf, artifactOf, commentsOf,
readJson) that copied each input into a typed object before use. Now one
isRecord guard narrows each input where it is read, and a step checks
only the fields it uses. download() is inlined, and a directory check
replaces the set of downloaded artifacts.

A malformed artifact or comment from GitHub is now skipped instead of
failing the step. Plan, join and post outputs stay byte-identical to the
old bash in every scenario.

* Keep Workshop crashes out of stored eval results

A check that failed because the shared Workshop crashed counted as the
agent's failure, and later runs reused it from the stored results.
WorkshopAgentSession now counts dropped connections. When a check fails
while one drops, EvalVerifier.collect throws, so the harness records a
run error, which is never stored. A timeout is no longer the only way
verification ends early, so its check ids become *.incomplete.

* Leave test files under evals/ out of task keys

Test files elsewhere already stay out of the keys. One next to the tasks
would change all four keys and force a full re-measure.
2026-09-25 12:19:21 -05:00

329 lines
16 KiB
TypeScript

// The plan, join and post steps of .github/workflows/workshop-evals-pr.yml:
// node scripts/evals/workflow.ts plan <baseline-sha> [<candidate-sha>]
// node scripts/evals/workflow.ts join <runs-dir> <out-dir>
// node scripts/evals/workflow.ts post <comparison.md>
// Only Node built-ins are imported, so the plan job needs no install step.
// This file runs under Node's native TypeScript stripping, so imports name real .ts files and only
// erasable syntax may appear here.
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { appendFileSync, existsSync } from "node:fs";
import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { evalKeys, type EvalKeys } from "./eval-keys.ts";
const WORKFLOW = ".github/workflows/workshop-evals-pr.yml";
const RESULTS_MARKER = "<!-- workshop-evals-comparison";
const PER_PAGE = 100;
/** How long a stored result must outlive the run that reuses it, so compare can still download it. */
const OUTLIVES_RUN_MS = 4 * 60 * 60 * 1000;
type Revision = "baseline" | "candidate";
const REVISIONS: readonly Revision[] = ["baseline", "candidate"];
/** One revision's task, under the name its result is stored as. */
type TaskRun = { revision: Revision; sha: string; task: string; name: string };
/** Where a revision's result for a task comes from: a stored artifact, or one leg of this run. */
type Source = TaskRun & ({ artifact: number } | { run: Revision });
type Plan = {
sources: Source[];
/** The results this run measures, each stored for later runs to reuse. */
store: { revision: Revision; task: string; name: string }[];
/** One job per revision with anything to measure. */
legs: { revision: Revision; sha: string; tasks: string[] }[];
};
/** An issue comment, as far as recognising results comments and eval reviews needs. */
type Comment = { id: number; login: string | undefined; createdAt: string; body: string };
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function env(name: string): string {
const value = process.env[name];
if (value === undefined || value === "") throw new Error(`${name} is not set`);
return value;
}
/** Parsed JSON that is an object, so its fields can be checked one by one. */
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function resultName(task: string, key: string): string {
return `${task}-${key}`;
}
async function github(method: string, path: string, body?: { body: string }): Promise<Response> {
const response = await fetch(`https://api.github.com/${path}`, {
method,
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${env("GITHUB_TOKEN")}`,
"Content-Type": "application/json",
"User-Agent": "cloudflare-os-workshop-evals",
},
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!response.ok) {
throw new Error(`GitHub API ${method} ${path} failed with ${response.status}: ` +
(await response.text()).slice(0, 300));
}
return response;
}
/** Every item of a GitHub list, read a page at a time until a short page. */
async function githubList(path: string): Promise<unknown[]> {
const items: unknown[] = [];
for (let page = 1; ; page++) {
const batch: unknown = await (await github("GET", `${path}?per_page=${PER_PAGE}&page=${page}`)).json();
if (!Array.isArray(batch)) throw new Error(`GitHub API GET ${path} did not return a list`);
items.push(...batch);
if (batch.length < PER_PAGE) return items;
}
}
function setOutputs(outputs: Record<string, string>): void {
appendFileSync(env("GITHUB_OUTPUT"),
Object.entries(outputs).map(([name, value]) => `${name}=${value}\n`).join(""));
}
/** JSON with every object's keys sorted, so a digest does not depend on the order yq prints them in. */
function canonicalJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
if (isRecord(value)) {
return `{${Object.keys(value).toSorted()
.map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
}
return JSON.stringify(value);
}
function workflowDigest(sections: string): string {
const settings = execFileSync("yq", ["-o=json", sections, WORKFLOW], { encoding: "utf8" });
return createHash("sha256").update(`${canonicalJson(JSON.parse(settings))}\n`).digest("hex");
}
/**
* The stored result an artifacts listing offers for reuse: the newest one that outlives this run
* and that this repository's own run stored, since a fork's run can upload any name.
*/
export function reusableArtifact(listing: unknown, now: number): number | undefined {
const artifacts: unknown[] = isRecord(listing) && Array.isArray(listing.artifacts) ? listing.artifacts : [];
let newest: { id: number; createdAt: string } | undefined;
for (const artifact of artifacts) {
if (!isRecord(artifact)) continue;
const { id, expired, created_at: createdAt, expires_at: expiresAt, workflow_run: run } = artifact;
if (typeof id === "number" && typeof createdAt === "string" && typeof expiresAt === "string" &&
expired === false && Date.parse(expiresAt) > now + OUTLIVES_RUN_MS &&
isRecord(run) && typeof run.repository_id === "number" && run.head_repository_id === run.repository_id &&
(newest === undefined || createdAt >= newest.createdAt)) {
newest = { id, createdAt };
}
}
return newest?.id;
}
/**
* Where each revision's result for each task comes from: a stored result, or one leg of this run.
* A key both revisions share is measured once, by the candidate: equal keys are the same run. A
* push's one commit is the baseline, as later pull requests use it.
*/
export function planRuns(keys: EvalKeys, stored: ReadonlyMap<string, number>): Plan {
const runs = keys.commits.flatMap(({ sha, tasks }, side) => Object.entries(tasks).map(([task, { key }]): TaskRun =>
({ revision: side === 0 ? "baseline" : "candidate", sha, task, name: resultName(task, key) })));
const candidate = new Set(runs.filter(({ revision }) => revision === "candidate").map(({ name }) => name));
const sources = runs.map((run): Source => {
const artifact = stored.get(run.name);
return artifact === undefined
? { ...run, run: candidate.has(run.name) ? "candidate" : "baseline" }
: { ...run, artifact };
});
const measured = sources.filter(source => "run" in source && source.run === source.revision);
return {
sources,
store: measured.map(({ revision, task, name }) => ({ revision, task, name })),
legs: REVISIONS.flatMap(revision => {
const leg = measured.filter(source => source.revision === revision);
return leg.length === 0 ? [] : [{ revision, sha: leg[0].sha, tasks: leg.map(({ task }) => task) }];
}),
};
}
/** The plan step's outputs. Legs and store are left out when nothing is measured: a matrix with no entries fails the run. */
export function planOutputs(keys: EvalKeys, plan: Plan, report: boolean): Record<string, string> {
return {
keys: JSON.stringify(keys),
sources: JSON.stringify(plan.sources),
report: String(report),
...(plan.store.length === 0 ? {} : {
legs: JSON.stringify({ include: plan.legs }),
store: JSON.stringify({ include: plan.store }),
}),
};
}
function commentsIn(listing: readonly unknown[]): Comment[] {
return listing.flatMap(comment => {
if (!isRecord(comment)) return [];
const { id, user, created_at: createdAt, body } = comment;
return typeof id === "number" && typeof createdAt === "string" && typeof body === "string"
? [{ id, login: isRecord(user) && typeof user.login === "string" ? user.login : undefined, createdAt, body }]
: [];
});
}
function isResultsComment({ login, body }: Comment): boolean {
return login === "github-actions[bot]" && body.startsWith(RESULTS_MARKER);
}
/** Bonk's review of the eval runs, recognised by the heading trajectory-review's prompt asks for. */
function isEvalReview({ login, body }: Comment): boolean {
return login === "ask-bonk[bot]" && /^## (🔬 )?Eval runs review/u.test(body);
}
function marker(report: string | undefined): string {
return `${RESULTS_MARKER}${report === undefined ? "" : ` report=${report}`} -->`;
}
/**
* A results comment. Its marker carries the report key only when every result it shows is stored,
* so the next run can tell whether it is still current.
*/
export function resultsComment(markdown: string, runUrl: string, report: string | undefined): string {
return `${marker(report)}\n${markdown}\n[Run](${runUrl}) · [trajectories and raw results](${runUrl}#artifacts)\n`;
}
/** Whether the newest results comment reports these exact inputs and Bonk has reviewed it since. */
export function commentsAreCurrent(listing: readonly unknown[], report: string): boolean {
const comments = commentsIn(listing);
const posted = comments.filter(isResultsComment).reduce<Comment | undefined>(
(newest, comment) => newest === undefined || comment.createdAt >= newest.createdAt ? comment : newest,
undefined);
return posted !== undefined && posted.body.startsWith(marker(report)) &&
comments.some(comment => isEvalReview(comment) && comment.createdAt > posted.createdAt);
}
/** The comments a new results comment replaces: every earlier results comment and Bonk eval review. */
export function staleComments(listing: readonly unknown[]): number[] {
return commentsIn(listing).filter(comment => isResultsComment(comment) || isEvalReview(comment))
.map(({ id }) => id);
}
/**
* Whether to post the comparison: not when the posted comments report these exact inputs, every
* result they show is stored, Bonk reviewed them afterwards, and nobody asked for a re-run.
* Comments that cannot be read count as stale, since posting again costs one review and failing
* here would skip every run.
*/
async function shouldReport(repo: string, report: string, plan: Plan): Promise<boolean> {
if (env("GITHUB_EVENT_NAME") !== "pull_request") return false;
if (env("GITHUB_RUN_ATTEMPT") !== "1" || plan.store.length > 0) return true;
try {
return !commentsAreCurrent(await githubList(`repos/${repo}/issues/${env("PR_NUMBER")}/comments`), report);
} catch (error) {
console.warn(`::warning::Posting the comparison again, as the posted comments cannot be read: ${errorMessage(error)}`);
return true;
}
}
async function planStep(shas: readonly string[]): Promise<void> {
// What decides a task's result or whether it is stored, and what decides the comments.
const keys = evalKeys(workflowDigest("[.env, .jobs.evals, .jobs.store]"),
workflowDigest('[.jobs.compare, .jobs["trajectory-review"]]'), shas);
const repo = env("GITHUB_REPOSITORY");
const now = Date.now();
const names = new Set(keys.commits.flatMap(({ tasks }) =>
Object.entries(tasks).map(([task, { key }]) => resultName(task, key))));
const stored = new Map<string, number>();
await Promise.all([...names].map(async name => {
const listing = await github("GET", `repos/${repo}/actions/artifacts?name=workshop-evals-${name}&per_page=${PER_PAGE}`);
const id = reusableArtifact(await listing.json(), now);
if (id !== undefined) stored.set(name, id);
}));
const plan = planRuns(keys, stored);
setOutputs(planOutputs(keys, plan, await shouldReport(repo, keys.report, plan)));
}
/**
* Writes <out-dir>/<revision>/results.json from this run's <runs-dir> or from stored results, as
* the plan's SOURCES say, and outputs `complete`: false when a result from this run was not clean
* enough to store, so a comment built on it must not count as current.
*/
async function joinStep(runsDir: string, outDir: string): Promise<void> {
const sources: unknown = JSON.parse(env("SOURCES"));
if (!Array.isArray(sources) || !sources.every(isRecord)) throw new Error("SOURCES is not a list of sources");
const repo = env("GITHUB_REPOSITORY");
const storedDir = await mkdtemp(join(tmpdir(), "workshop-evals-stored-"));
let complete = true;
for (const revision of REVISIONS) {
const testResults: unknown[] = [];
for (const { task, artifact, run } of sources.filter(source => source.revision === revision)) {
if (typeof task !== "string") throw new Error("SOURCES names a source with no task");
let file: string;
if (typeof artifact === "number") {
const dir = join(storedDir, String(artifact));
if (!existsSync(dir)) {
const zip = await github("GET", `repos/${repo}/actions/artifacts/${artifact}/zip`);
await writeFile(`${dir}.zip`, new Uint8Array(await zip.arrayBuffer()));
execFileSync("unzip", ["-q", `${dir}.zip`, "-d", dir]);
}
file = join(dir, `${task}.json`);
} else {
if (run !== "baseline" && run !== "candidate") throw new Error(`SOURCES gives ${task} no artifact or run`);
file = join(runsDir, run, `${task}.json`);
// A leg lists the tasks clean enough to store; one with no list stored none.
const clean = join(runsDir, run, "clean.json");
const listed: unknown = existsSync(clean) ? JSON.parse(await readFile(clean, "utf8")) : [];
if (!Array.isArray(listed) || !listed.includes(task)) complete = false;
}
const result: unknown = JSON.parse(await readFile(file, "utf8"));
if (!isRecord(result) || !Array.isArray(result.testResults)) throw new Error(`${file} holds no testResults`);
testResults.push(...result.testResults);
}
await mkdir(join(outDir, revision), { recursive: true });
await writeFile(join(outDir, revision, "results.json"), `${JSON.stringify({ testResults }, null, 2)}\n`);
}
setOutputs({ complete: String(complete) });
}
/**
* Posts the comparison fresh at the end of the conversation, then deletes every earlier results
* comment and Bonk eval review, so the latest pair is the only one and sits where readers look.
* Bonk's review follows this comment. Bonk's code reviews and anything a person wrote stay.
*/
async function postStep(markdownPath: string): Promise<void> {
const repo = env("GITHUB_REPOSITORY");
const comments = `repos/${repo}/issues/${env("PR_NUMBER")}/comments`;
const runUrl = `${env("GITHUB_SERVER_URL")}/${repo}/actions/runs/${env("GITHUB_RUN_ID")}`;
const report = env("COMPLETE") === "true" ? env("REPORT_KEY") : undefined;
const body = resultsComment(await readFile(markdownPath, "utf8"), runUrl, report);
// Listed before any deletion, which would shift the pages still to be read.
const earlier = staleComments(await githubList(comments));
await github("POST", comments, { body });
for (const id of earlier) {
try {
await github("DELETE", `repos/${repo}/issues/comments/${id}`);
} catch (error) {
// Someone may have deleted it already.
console.warn(`::warning::${errorMessage(error)}`);
}
}
}
async function main([command, ...args]: readonly string[]): Promise<void> {
if (command === "plan" && args.length >= 1 && args.length <= REVISIONS.length) return planStep(args);
if (command === "join" && args.length === 2) return joinStep(args[0], args[1]);
if (command === "post" && args.length === 1) return postStep(args[0]);
throw new Error("Usage: node scripts/evals/workflow.ts plan <baseline-sha> [<candidate-sha>] | " +
"join <runs-dir> <out-dir> | post <comparison.md>");
}
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
main(process.argv.slice(2)).catch((error: unknown) => {
console.error(`::error::${errorMessage(error)}`);
process.exitCode = 1;
});
}