Repository navigation
Expand file tree
/
Copy pathrun-evals.js
More file actions
508 lines (478 loc) · 18.2 KB
/
Copy pathrun-evals.js
File metadata and controls
508 lines (478 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#!/usr/bin/env node
// @ts-check
/**
* Pack the locally-built `next` package and run agent evals against it.
*
* pnpm eval <eval-name> run one eval and its configured variants
* pnpm eval --suite regression run a named eval suite
* pnpm eval <eval-name> --dry preview without executing
* pnpm eval --all run every eval (slow — normally only CI does this)
* NEXT_SKIP_PACK=1 pnpm eval ... reuse tarball from last run
*
* Mirrors run-tests.js: pack once, hand paths to child via env, forward args.
*
* We only pack `next`, not the whole workspace. The sandbox is remote Linux:
* - @next/swc: local darwin binary wouldn't run there; the sandbox downloads
* the right one at runtime (packages/next/src/build/swc/index.ts).
* - @next/env etc: resolved from npm at the pinned canary version.
*
* The experiments/ dir is generated fresh on every run and gitignored. This
* keeps the variants in one place instead of maintaining N committed
* experiment files that only differ by setup.
*/
const path = require('path')
const fs = require('fs')
const { spawnSync } = require('child_process')
const { packPackage } = require('./evals/lib/pack')
const { linkEnvironment } = require('./evals/lib/environment')
const ROOT = __dirname
const EVALS_DIR = path.join(ROOT, 'evals')
const FIXTURES_DIR = path.join(EVALS_DIR, 'evals')
const EVAL_CONFIG_PATH = path.join(EVALS_DIR, 'eval.config.json')
const EVAL_SUITES_PATH = path.join(EVALS_DIR, 'eval.suites.json')
const EXPERIMENTS_DIR = path.join(EVALS_DIR, 'experiments')
const TARBALL_DIR = path.join(EVALS_DIR, '.tarballs')
const TARBALL = path.join(TARBALL_DIR, 'next.tgz')
/** @typedef {{ skills?: string[], timeout?: number, agentFeedback?: boolean, publish?: boolean, browserJs?: boolean, metrics?: string }} EvalConfig */
/** @type {Record<string, EvalConfig>} */
const EVAL_CONFIG = JSON.parse(fs.readFileSync(EVAL_CONFIG_PATH, 'utf-8'))
// The two variants we always compare. Order matters for output readability:
// baseline first so a contributor sees "does the agent fail without docs?"
// before "does it pass with docs?".
const BASE_VARIANTS = [
{
suffix: 'baseline',
imports: `import { installNextJs, installPlaywright, prepareFixture } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await installPlaywright(sandbox)\n await prepareFixture(sandbox)`,
},
{
suffix: 'agents-md',
imports: `import { installNextJs, installPlaywright, prepareFixture, writeAgentsMd } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await installPlaywright(sandbox)\n await prepareFixture(sandbox)\n await writeAgentsMd(sandbox)`,
},
]
function pack() {
packPackage(path.join(ROOT, 'packages/next'), TARBALL)
}
/** @param {string[] | null} selectedEvals null means all evals */
function writeExperiments(
selectedEvals,
variants,
timeout,
runs,
options = {}
) {
fs.rmSync(EXPERIMENTS_DIR, { recursive: true, force: true })
fs.mkdirSync(EXPERIMENTS_DIR, { recursive: true })
for (const v of variants) {
const variantEvals = v.evals ?? selectedEvals
const evalsField = variantEvals
? `\n evals: ${JSON.stringify(variantEvals.length === 1 ? variantEvals[0] : variantEvals)},`
: ''
const browserJsFixtures = Object.fromEntries(
(variantEvals ?? listEvals())
.filter((name) => readFixtureConfig(name).browserJs)
.map((name) => {
const pkg = JSON.parse(
fs.readFileSync(
path.join(FIXTURES_DIR, name, 'package.json'),
'utf8'
)
)
return [name, pkg.name]
})
)
const measuresBrowserJs = Object.keys(browserJsFixtures).length > 0
let onRunComplete = v.onRunComplete
if (measuresBrowserJs) {
const runData = onRunComplete
? `${onRunComplete}(context)`
: 'context.runData'
onRunComplete = `(context) => browserJs.onRunComplete({ ...context, runData: ${runData} })`
}
const body = `import type { ExperimentConfig } from '@vercel/agent-eval'
${v.imports}
${options.metrics ? `import { recordAgentTime } from '../lib/metrics.js'` : ''}
${measuresBrowserJs ? `import { createBrowserJsHooks } from '../lib/bundle-optimizer/hooks.js'\n\nconst browserJs = createBrowserJsHooks(${JSON.stringify(browserJsFixtures)}, ${JSON.stringify(v.skills ?? [])})\n` : ''}
const config: ExperimentConfig = {
// Via the Vercel AI Gateway, so the OIDC token from \`vc env pull\` is the only
// credential needed (it auths the sandbox, the codegen model, and the judge).
agent: ${JSON.stringify(options.agent ?? 'vercel-ai-gateway/claude-code')},
model: ${JSON.stringify(options.model ?? 'claude-opus-4-8')},${evalsField}
// Cheap fixed grader for the agentic judge clauses in EVAL.ts files — every
// run is graded by the same model regardless of the model under test.
judge: { model: 'claude-haiku-4-5' },
scripts: ['build'],
runs: ${runs},
earlyExit: ${runs === 1},
timeout: ${timeout},
sandbox: 'auto',
${options.metrics ? `copyFiles: 'all',` : ''}
${onRunComplete ? `onRunComplete: ${onRunComplete},` : ''}
setup: async (sandbox) => {
${v.setup}
${options.metrics ? 'recordAgentTime(sandbox)' : ''}
${measuresBrowserJs ? 'return browserJs.setup(sandbox)' : ''}
},
}
export default config
`
fs.writeFileSync(path.join(EXPERIMENTS_DIR, `${v.suffix}.ts`), body)
}
}
function listEvals() {
return fs
.readdirSync(FIXTURES_DIR, { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name)
}
function readEvalSuites() {
/** @type {unknown} */
const parsed = JSON.parse(fs.readFileSync(EVAL_SUITES_PATH, 'utf-8'))
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
throw new Error(`${EVAL_SUITES_PATH} must contain an object of eval suites`)
}
const fixtureNames = new Set(listEvals())
const seen = new Map()
/** @type {Record<string, string[]>} */
const suites = {}
for (const [suite, evalNames] of Object.entries(parsed)) {
if (!Array.isArray(evalNames) || evalNames.length === 0) {
throw new Error(`${EVAL_SUITES_PATH}: ${suite} must be a non-empty array`)
}
for (const evalName of evalNames) {
if (typeof evalName !== 'string' || !fixtureNames.has(evalName)) {
throw new Error(`${EVAL_SUITES_PATH}: unknown eval ${String(evalName)}`)
}
const previousSuite = seen.get(evalName)
if (previousSuite) {
throw new Error(
`${EVAL_SUITES_PATH}: ${evalName} is in both ${previousSuite} and ${suite}`
)
}
seen.set(evalName, suite)
}
suites[suite] = evalNames
}
const unclassified = [...fixtureNames].filter(
(evalName) =>
EVAL_CONFIG[evalName]?.publish !== false && !seen.has(evalName)
)
if (unclassified.length > 0) {
throw new Error(
`${EVAL_SUITES_PATH}: public evals must belong to a suite: ${unclassified.join(', ')}`
)
}
return suites
}
function readFixtureConfig(evalName) {
const config = EVAL_CONFIG[evalName] ?? {}
const skillNames = config.skills ?? []
if (
!Array.isArray(skillNames) ||
skillNames.some((name) => typeof name !== 'string')
) {
throw new Error(
`${EVAL_CONFIG_PATH}: ${evalName}.skills must be an array of skill names`
)
}
if (
config.timeout !== undefined &&
(typeof config.timeout !== 'number' || config.timeout <= 0)
) {
throw new Error(
`${EVAL_CONFIG_PATH}: ${evalName}.timeout must be a positive number`
)
}
if (
config.agentFeedback !== undefined &&
typeof config.agentFeedback !== 'boolean'
) {
throw new Error(
`${EVAL_CONFIG_PATH}: ${evalName}.agentFeedback must be a boolean`
)
}
if (config.browserJs !== undefined && typeof config.browserJs !== 'boolean') {
throw new Error(
`${EVAL_CONFIG_PATH}: ${evalName}.browserJs must be a boolean`
)
}
return {
skills: skillNames,
timeout: config.timeout ?? 720,
agentFeedback: config.agentFeedback ?? false,
browserJs: config.browserJs ?? false,
}
}
function getExperimentSettings(selectedEvals) {
const skillEvals = (selectedEvals ?? listEvals()).map((name) => ({
name,
...readFixtureConfig(name),
}))
const timeout = Math.max(...skillEvals.map((config) => config.timeout))
const configuredSkillEvals = skillEvals.filter(
({ skills }) => skills.length > 0
)
/** @type {Map<string, { skills: string[], evals: string[] }>} */
const skillGroups = new Map()
for (const { name, skills } of configuredSkillEvals) {
const skillNames = [...new Set(skills)].sort()
const key = skillNames.join(',')
const group = skillGroups.get(key) ?? { skills: skillNames, evals: [] }
group.evals.push(name)
skillGroups.set(key, group)
}
const multipleSkillGroups = skillGroups.size > 1
const skillVariants = [...skillGroups.values()].map(({ skills, evals }) => ({
suffix: multipleSkillGroups ? `skills-${skills.join('-')}` : 'skills',
imports: `import { installLocalSkills, installNextJs, installPlaywright, prepareFixture } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await installPlaywright(sandbox)\n await prepareFixture(sandbox)\n await installLocalSkills(sandbox, ${JSON.stringify(skills)})`,
skills,
evals,
}))
/** @type {Map<string, { skills: string[], evals: string[] }>} */
const feedbackGroups = new Map()
for (const { name, skills, agentFeedback } of skillEvals) {
if (!agentFeedback) continue
const skillNames = [...new Set(skills)].sort()
const key = skillNames.join(',')
const group = feedbackGroups.get(key) ?? { skills: skillNames, evals: [] }
group.evals.push(name)
feedbackGroups.set(key, group)
}
const multipleFeedbackGroups = feedbackGroups.size > 1
const feedbackVariants = [...feedbackGroups.values()].map(
({ skills, evals }) => ({
suffix: multipleFeedbackGroups
? `agent-feedback-${skills.join('-') || 'no-skills'}`
: 'agent-feedback',
imports: `import { analyzeAgentFeedbackRun, installLocalSkills, installNextJs, prepareFixture, writeAgentFeedbackInstructions } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await prepareFixture(sandbox)${
skills.length > 0
? `\n await installLocalSkills(sandbox, ${JSON.stringify(skills)})`
: ''
}\n await writeAgentFeedbackInstructions(sandbox)`,
onRunComplete: 'analyzeAgentFeedbackRun',
evals,
})
)
return {
timeout,
variants: [...BASE_VARIANTS, ...skillVariants, ...feedbackVariants],
}
}
function main() {
const evalSuites = readEvalSuites()
const argv = require('yargs/yargs')(process.argv.slice(2))
.command(
'$0 [eval-name]',
'Run an eval (baseline + agents-md variants)',
(y) =>
y.positional('eval-name', {
type: 'string',
describe: 'Fixture directory name',
})
)
.boolean('all')
.describe('all', 'Run every eval (slow — normally only CI does this)')
.string('suite')
.choices('suite', Object.keys(evalSuites))
.describe('suite', 'Run every eval in a named suite')
.boolean('dry')
.describe('dry', 'Preview without executing')
.boolean('metrics')
.describe(
'metrics',
'Save the app and collect configured page and effort metrics'
)
.string('agent')
.describe('agent', 'Override the coding agent for every selected variant')
.string('model')
.describe('model', 'Override the coding model for every selected variant')
.string('pricing')
.describe('pricing', 'Gateway model pricing JSON for estimated model cost')
.implies('pricing', 'metrics')
.number('runs')
.default('runs', 1)
.describe('runs', 'Run each selected eval this many times')
.array('variant')
.string('variant')
.describe('variant', 'Run only the named generated variant (repeatable)')
.conflicts('all', 'eval-name')
.conflicts('suite', ['all', 'eval-name'])
.check((argv) => {
if (!argv.all && !argv.evalName && !argv.suite) {
throw new Error(
`Missing <eval-name>.\n\nAvailable evals:\n${listEvals()
.map((n) => ` ${n}`)
.join('\n')}`
)
}
if (
argv.evalName &&
!fs.existsSync(path.join(FIXTURES_DIR, argv.evalName))
) {
throw new Error(
`Unknown eval: ${argv.evalName}\n(looked in ${FIXTURES_DIR})`
)
}
if (!Number.isInteger(argv.runs) || argv.runs < 1) {
throw new Error('--runs must be a positive integer')
}
return true
})
.strict()
.help().argv
/** @type {string | undefined} */
const evalName = argv.evalName
/** @type {string[] | null} */
const selectedEvals = argv.suite
? evalSuites[argv.suite]
: argv.all
? null
: [/** @type {string} */ (evalName)]
if (
argv.metrics &&
(!selectedEvals ||
selectedEvals.length !== 1 ||
!/^[a-z0-9-]+$/.test(EVAL_CONFIG[selectedEvals[0]]?.metrics ?? '') ||
!fs.existsSync(
path.join(
EVALS_DIR,
'metrics',
`${EVAL_CONFIG[selectedEvals[0]].metrics}.mjs`
)
))
) {
throw new Error(
'--metrics requires one eval with a configured metrics collector'
)
}
const { variants: availableVariants, timeout } =
getExperimentSettings(selectedEvals)
if (argv.pricing) {
const pricing = JSON.parse(fs.readFileSync(argv.pricing, 'utf8'))
if (!pricing.pricing || typeof pricing.pricing !== 'object') {
throw new Error(
"--pricing must contain the model's Gateway pricing object"
)
}
}
const requestedVariants = argv.variant ?? []
const unknownVariants = requestedVariants.filter(
(name) => !availableVariants.some((variant) => variant.suffix === name)
)
if (unknownVariants.length > 0) {
throw new Error(
`Unknown variant: ${unknownVariants.join(', ')}\nAvailable variants: ${availableVariants
.map((variant) => variant.suffix)
.join(', ')}`
)
}
const variants =
requestedVariants.length > 0
? availableVariants.filter((variant) =>
requestedVariants.includes(variant.suffix)
)
: availableVariants
// agent-eval 1.3 dropped run-all/--dry: `run` takes explicit experiment names,
// and `status` is the read-only preview.
const agentEvalArgs = argv.dry
? ['status']
: ['run', ...variants.map((v) => v.suffix), '--force']
// Fixtures that install their own pinned app (such as Pokédex) do not use
// the local package. Match installNextJs's root-package check before packing.
const needsLocalNext = (selectedEvals ?? listEvals()).some((name) => {
const pkg = JSON.parse(
fs.readFileSync(path.join(FIXTURES_DIR, name, 'package.json'), 'utf8')
)
return Boolean(pkg.dependencies?.next ?? pkg.devDependencies?.next)
})
if (needsLocalNext) {
if (!fs.existsSync(path.join(ROOT, 'packages/next/dist'))) {
console.error(
'packages/next/dist not found. Run `pnpm --filter=next build` first.'
)
process.exit(1)
}
if (process.env.NEXT_SKIP_PACK && fs.existsSync(TARBALL)) {
console.log('> Reusing existing tarball (NEXT_SKIP_PACK=1)')
} else {
console.log('> Packing next...')
pack()
const mb = (fs.statSync(TARBALL).size / 1024 / 1024).toFixed(1)
console.log(` ${TARBALL} (${mb} MB)`)
}
}
// agent-eval loads .env / .env.local from its own cwd (evals/). `vc env pull`
// writes to the repo root, so symlink them into evals/ for agent-eval to find.
linkEnvironment(ROOT, EVALS_DIR)
writeExperiments(selectedEvals, variants, timeout, argv.runs, argv)
console.log(
evalName
? `> Running ${evalName} (${variants.map((v) => v.suffix).join(' + ')})`
: `> Running ${argv.suite ? `${argv.suite} suite` : 'all evals'} (${variants.map((v) => v.suffix).join(' + ')})`
)
// Same handoff pattern as run-tests.js with NEXT_TEST_PKG_PATHS. We invoke
// the bin directly rather than via `pnpm exec` because pnpm resets cwd to
// the workspace root, but agent-eval resolves experiments/ from process.cwd().
const bin = path.join(ROOT, 'node_modules/.bin/agent-eval')
const previousResults = new Map(
variants.map((variant) => {
const directory = path.join(EVALS_DIR, 'results', variant.suffix)
return [
variant.suffix,
new Set(fs.existsSync(directory) ? fs.readdirSync(directory) : []),
]
})
)
const result = spawnSync(bin, agentEvalArgs, {
cwd: EVALS_DIR,
stdio: 'inherit',
env: { ...process.env, NEXT_EVAL_TARBALL: TARBALL },
})
if (result.error) {
// ENOENT (missing bin), EACCES, etc. — spawnSync returns status: null
// without printing anything, so surface it.
console.error(`Failed to run ${bin}: ${result.error.message}`)
if (/** @type {NodeJS.ErrnoException} */ (result.error).code === 'ENOENT') {
console.error('Did you run `pnpm install`?')
}
process.exit(1)
}
let metricsFailed = false
if (argv.metrics && !argv.dry) {
for (const variant of variants) {
const directory = path.join(EVALS_DIR, 'results', variant.suffix)
if (!fs.existsSync(directory)) continue
for (const timestamp of fs.readdirSync(directory)) {
if (previousResults.get(variant.suffix).has(timestamp)) continue
const evalDirectory = path.join(directory, timestamp, selectedEvals[0])
if (!fs.existsSync(evalDirectory)) continue
for (const run of fs
.readdirSync(evalDirectory)
.filter((name) => /^run-\d+$/.test(name))) {
const measured = spawnSync(
process.execPath,
[
'--import=tsx',
path.join(EVALS_DIR, 'metrics/report.mjs'),
'collect',
path.join(evalDirectory, run),
EVAL_CONFIG[selectedEvals[0]].metrics,
...(argv.pricing ? [path.resolve(argv.pricing)] : []),
],
{ cwd: ROOT, stdio: 'inherit', env: process.env }
)
if (measured.error || measured.status !== 0) metricsFailed = true
}
}
}
}
if (metricsFailed)
console.error(
'Page measurement failed. Eval scores are unchanged; retry the collector on the saved run.'
)
process.exit((result.status ?? 1) || (metricsFailed ? 1 : 0))
}
main()