From 41724cf117cc69c8c3b43dd6bd029df4277310e4 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Fri, 24 Jul 2026 15:54:47 -0400 Subject: [PATCH 1/6] Add eval harness for verifying agent skill-following behavior MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Verifies that an agent, given a scenario's task prompt, consults the right guidance: reads the skill files and docs it should, doesn't read the ones it shouldn't, in the right order, and reaches for the right kind of command — with the evidence coming from the agent's transcript. - eval/harness/run.mjs: static sanity checks (skill frontmatter, scenario files parse) plus a live mode that runs scenario queries through a real agent session headlessly, normalizes the transcript into read/write/command events, and evaluates declarative assertions with pass rates (--scenario, --model, --agent, --repeat). Needs no running environment and grants no write permissions — a denied edit attempt is still evidence, and the checkout is never modified. - eval/scenarios/: two scenarios distilled from transcript-validated manual runs against the testing skill, plus a negative control that guards against over-triggering (trivial tasks must not read skills or contributor guides). - docs/contributors/code/agents-and-skills.md: adding a skill now includes adding an eval scenario. Verified live: testing-write-e2e passes all six assertions end to end; the negative control passes all three. Co-Authored-By: Claude Fable 5 --- docs/contributors/code/agents-and-skills.md | 3 +- eval/artifacts/.gitignore | 2 + eval/harness/run.mjs | 310 ++++++++++++++++++ eval/scenarios/README.md | 39 +++ .../negative-control-trivial-task.json | 20 ++ eval/scenarios/testing-run-e2e.json | 40 +++ eval/scenarios/testing-write-e2e.json | 30 ++ 7 files changed, 443 insertions(+), 1 deletion(-) create mode 100644 eval/artifacts/.gitignore create mode 100644 eval/harness/run.mjs create mode 100644 eval/scenarios/README.md create mode 100644 eval/scenarios/negative-control-trivial-task.json create mode 100644 eval/scenarios/testing-run-e2e.json create mode 100644 eval/scenarios/testing-write-e2e.json diff --git a/docs/contributors/code/agents-and-skills.md b/docs/contributors/code/agents-and-skills.md index 2124a06db39299..8736b20a77d452 100644 --- a/docs/contributors/code/agents-and-skills.md +++ b/docs/contributors/code/agents-and-skills.md @@ -74,4 +74,5 @@ Walking through how the live testing skill applies these conventions: 1. Confirm the public docs can't cover it — improve them first if they can. 2. Create `skills//SKILL.md` following the conventions above. 3. Add a routing entry to the root `AGENTS.md`. -4. Run `npm run lint:md:docs`. +4. Add at least one eval scenario under `eval/scenarios/` (see [its README](https://github.com/WordPress/gutenberg/blob/trunk/eval/scenarios/README.md)) describing a task the skill covers and how to verify an agent followed it. +5. Run `npm run lint:md:docs` and `node eval/harness/run.mjs`. diff --git a/eval/artifacts/.gitignore b/eval/artifacts/.gitignore new file mode 100644 index 00000000000000..d6b7ef32c8478a --- /dev/null +++ b/eval/artifacts/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/eval/harness/run.mjs b/eval/harness/run.mjs new file mode 100644 index 00000000000000..db328613719dc7 --- /dev/null +++ b/eval/harness/run.mjs @@ -0,0 +1,310 @@ +/** + * Eval harness for agent skills. + * + * Verifies that an agent, given a scenario's task prompt, consulted the right + * guidance: read the skill files and docs it should, didn't read the ones it + * shouldn't, in the right order, and reached for the right kind of command. + * Evidence comes from the agent's own transcript; nothing needs a running + * WordPress environment, and the agent is not granted write permissions — an + * attempted (denied) edit is still evidence, and your checkout is never + * touched. + * + * Static checks (default) — fast, free: + * + * node eval/harness/run.mjs + * + * Live mode — runs scenario queries through real agent sessions (minutes and + * real tokens per run): + * + * node eval/harness/run.mjs --live + * node eval/harness/run.mjs --live --scenario testing-run-e2e --model haiku --repeat 3 + * + * Options: --scenario , --agent (default: claude), --model + * (passed through to the agent CLI), --repeat . + * + * Supporting another agent CLI means adding one ADAPTERS entry that invokes + * it headless and normalizes its transcript into + * { events: [ { kind: read|write|command, value } ], result }. + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; + +const repoRoot = process.cwd(); +const scenariosDir = path.join( repoRoot, 'eval', 'scenarios' ); +const artifactsDir = path.join( repoRoot, 'eval', 'artifacts' ); + +/* ------------------------------------------------------------------------- + * Static checks + * ---------------------------------------------------------------------- */ + +function parseFrontmatter( markdown ) { + const lines = markdown.split( '\n' ); + if ( lines[ 0 ]?.trim() !== '---' ) { + return null; + } + const end = lines.findIndex( ( line, i ) => i > 0 && line.trim() === '---' ); + if ( end === -1 ) { + return null; + } + const metadata = {}; + for ( const line of lines.slice( 1, end ) ) { + const m = line.match( /^\s*([A-Za-z0-9_-]+)\s*:\s*(.*)\s*$/ ); + if ( m ) { + metadata[ m[ 1 ] ] = m[ 2 ] + .replace( /^"(.*)"$/, '$1' ) + .replace( /^'(.*)'$/, '$1' ) + .trim(); + } + } + return metadata; +} + +function assert( condition, message ) { + if ( ! condition ) { + throw new Error( message ); + } +} + +function staticChecks() { + const skillsRoot = path.join( repoRoot, 'skills' ); + const skillDirs = fs.existsSync( skillsRoot ) + ? fs + .readdirSync( skillsRoot, { withFileTypes: true } ) + .filter( ( d ) => d.isDirectory() ) + .map( ( d ) => path.join( skillsRoot, d.name ) ) + : []; + assert( skillDirs.length > 0, 'No skills found under ./skills' ); + + for ( const dir of skillDirs ) { + const skillPath = path.join( dir, 'SKILL.md' ); + const rel = path.relative( repoRoot, skillPath ); + assert( fs.existsSync( skillPath ), `Missing SKILL.md: ${ rel }` ); + const fm = parseFrontmatter( fs.readFileSync( skillPath, 'utf8' ) ); + assert( fm, `Missing YAML frontmatter in: ${ rel }` ); + assert( fm.name, `Missing frontmatter 'name' in: ${ rel }` ); + assert( fm.description, `Missing frontmatter 'description' in: ${ rel }` ); + assert( + fm.name === path.basename( dir ), + `Frontmatter name mismatch in ${ rel }: expected '${ path.basename( dir ) }', got '${ fm.name }'` + ); + } + return skillDirs.length; +} + +function loadScenarios() { + return fs + .readdirSync( scenariosDir ) + .filter( ( f ) => f.endsWith( '.json' ) ) + .map( ( f ) => ( { + slug: f.replace( /\.json$/, '' ), + ...JSON.parse( fs.readFileSync( path.join( scenariosDir, f ), 'utf8' ) ), + } ) ); +} + +/* ------------------------------------------------------------------------- + * Agent adapters + * ---------------------------------------------------------------------- */ + +const ADAPTERS = { + claude: { + command: 'claude', + buildArgs( scenario, model ) { + const args = [ '-p', scenario.query, '--verbose', '--output-format', 'stream-json' ]; + if ( model ) { + args.push( '--model', model ); + } + return args; + }, + parse( raw ) { + const events = []; + let result = null; + for ( const line of raw.split( '\n' ) ) { + let obj; + try { + obj = JSON.parse( line ); + } catch { + continue; + } + for ( const block of obj?.message?.content ?? [] ) { + if ( block?.type !== 'tool_use' ) { + continue; + } + const input = block.input ?? {}; + if ( block.name === 'Read' && input.file_path ) { + events.push( { kind: 'read', value: input.file_path } ); + } else if ( [ 'Edit', 'Write', 'NotebookEdit' ].includes( block.name ) && input.file_path ) { + events.push( { kind: 'write', value: input.file_path } ); + } else if ( block.name === 'Bash' && input.command ) { + events.push( { kind: 'command', value: input.command } ); + } + } + if ( obj?.type === 'result' ) { + result = obj.result ?? ''; + } + } + return { events, result }; + }, + }, +}; + +/* ------------------------------------------------------------------------- + * Assertions over the normalized event log + * ---------------------------------------------------------------------- */ + +function firstIndex( events, kind, needle ) { + return events.findIndex( ( e ) => e.kind === kind && e.value.includes( needle ) ); +} + +function checkAssertions( assertions, { events, result } ) { + const outcomes = []; + const record = ( label, pass, evidence = [] ) => outcomes.push( { label, pass, evidence } ); + const reads = events.filter( ( e ) => e.kind === 'read' ).map( ( e ) => e.value ); + const commands = events.filter( ( e ) => e.kind === 'command' ).map( ( e ) => e.value ); + const timeline = events.map( ( e ) => `${ e.kind }: ${ e.value.slice( 0, 100 ) }` ); + + for ( const needle of assertions.readsInclude ?? [] ) { + record( `reads include ${ needle }`, reads.some( ( r ) => r.includes( needle ) ), reads ); + } + for ( const needle of assertions.readsExclude ?? [] ) { + record( `reads exclude ${ needle }`, ! reads.some( ( r ) => r.includes( needle ) ), reads ); + } + for ( const { read, command } of assertions.readsBeforeCommand ?? [] ) { + const readIdx = firstIndex( events, 'read', read ); + const cmdIdx = firstIndex( events, 'command', command ); + record( + `read ${ read } before command '${ command }'`, + readIdx !== -1 && ( cmdIdx === -1 || readIdx < cmdIdx ), + timeline + ); + } + for ( const { read } of assertions.readsBeforeWrite ?? [] ) { + const readIdx = firstIndex( events, 'read', read ); + const writeIdx = events.findIndex( ( e ) => e.kind === 'write' ); + record( + `read ${ read } before first write attempt`, + readIdx !== -1 && ( writeIdx === -1 || readIdx < writeIdx ), + timeline + ); + } + for ( const [ before, after ] of assertions.commandOrder ?? [] ) { + const afterIdx = firstIndex( events, 'command', after ); + const beforeIdx = firstIndex( events, 'command', before ); + record( + `command '${ before }' before '${ after }'`, + afterIdx === -1 || ( beforeIdx !== -1 && beforeIdx < afterIdx ), + commands + ); + } + for ( const rule of assertions.commandRules ?? [] ) { + const matching = commands.filter( ( c ) => c.includes( rule.matching ) ); + record( `a command matching '${ rule.matching }' occurred`, matching.length > 0, commands ); + for ( const command of matching ) { + if ( rule.mustContain ) { + record( `'${ rule.matching }' command contains '${ rule.mustContain }'`, command.includes( rule.mustContain ), [ command ] ); + } + for ( const banned of rule.mustNotContain ?? [] ) { + record( `'${ rule.matching }' command avoids '${ banned }'`, ! command.includes( banned ), [ command ] ); + } + } + } + for ( const needle of assertions.resultIncludes ?? [] ) { + record( `result includes '${ needle }'`, ( result ?? '' ).includes( needle ), [ ( result ?? '' ).slice( 0, 300 ) ] ); + } + return outcomes; +} + +/* ------------------------------------------------------------------------- + * Live mode + * ---------------------------------------------------------------------- */ + +function runOnce( scenario, adapter, model, runIndex ) { + const out = spawnSync( adapter.command, adapter.buildArgs( scenario, model ), { + cwd: repoRoot, + encoding: 'utf8', + timeout: ( scenario.timeoutSeconds ?? 900 ) * 1000, + maxBuffer: 256 * 1024 * 1024, + } ); + fs.mkdirSync( artifactsDir, { recursive: true } ); + const artifact = path.join( artifactsDir, `${ scenario.slug }-${ Date.now() }-${ runIndex }.jsonl` ); + fs.writeFileSync( artifact, out.stdout ?? '' ); + if ( out.error ) { + throw new Error( `${ adapter.command } failed to run: ${ out.error.message }` ); + } + return { outcomes: checkAssertions( scenario.assertions, adapter.parse( out.stdout ?? '' ) ), artifact }; +} + +function runLive( scenarios, { only, agentName, model, repeat } ) { + const adapter = ADAPTERS[ agentName ]; + if ( ! adapter ) { + console.error( `Unknown agent '${ agentName }'. Available: ${ Object.keys( ADAPTERS ).join( ', ' ) }` ); + process.exit( 1 ); + } + let failed = false; + for ( const scenario of scenarios ) { + if ( only && scenario.slug !== only ) { + continue; + } + if ( ! scenario.assertions ) { + console.log( `SKIP ${ scenario.slug }: no assertions block` ); + continue; + } + console.log( `\nRUN ${ scenario.slug } [${ agentName }${ model ? `:${ model }` : '' }] "${ scenario.query }" (${ repeat }x)` ); + const totals = new Map(); + for ( let i = 0; i < repeat; i++ ) { + const { outcomes, artifact } = runOnce( scenario, adapter, model, i ); + console.log( ` transcript: ${ path.relative( repoRoot, artifact ) }` ); + for ( const { label, pass, evidence } of outcomes ) { + const t = totals.get( label ) ?? { pass: 0, total: 0, evidence: [] }; + t.total += 1; + if ( pass ) { + t.pass += 1; + } else { + t.evidence = evidence; + } + totals.set( label, t ); + } + } + for ( const [ label, t ] of totals ) { + const ok = t.pass === t.total; + console.log( ` ${ ok ? 'PASS' : 'FAIL' } (${ t.pass }/${ t.total }) ${ label }` ); + if ( ! ok ) { + for ( const line of t.evidence.slice( 0, 20 ) ) { + console.log( ` actual: ${ line }` ); + } + failed = true; + } + } + } + return failed; +} + +/* ------------------------------------------------------------------------- + * Main + * ---------------------------------------------------------------------- */ + +function argValue( argv, flag ) { + const i = argv.indexOf( flag ); + return i !== -1 ? argv[ i + 1 ] : null; +} + +function main() { + const argv = process.argv.slice( 2 ); + const skillCount = staticChecks(); + const scenarios = loadScenarios(); + console.log( `OK: ${ skillCount } skill(s) and ${ scenarios.length } scenario(s) passed sanity checks.` ); + + if ( ! argv.includes( '--live' ) ) { + return; + } + const failed = runLive( scenarios, { + only: argValue( argv, '--scenario' ), + agentName: argValue( argv, '--agent' ) ?? 'claude', + model: argValue( argv, '--model' ), + repeat: Number( argValue( argv, '--repeat' ) ) || 1, + } ); + process.exit( failed ? 1 : 0 ); +} + +main(); diff --git a/eval/scenarios/README.md b/eval/scenarios/README.md new file mode 100644 index 00000000000000..ae967e7139825f --- /dev/null +++ b/eval/scenarios/README.md @@ -0,0 +1,39 @@ +# Eval scenarios + +Scenarios verify that an agent, given a task prompt, **consults the right guidance**: reads the skill files and docs it should, doesn't read the ones it shouldn't, in the right order, and reaches for the right kind of command. The evidence is the agent's own transcript. + +Each `.json` defines a human-readable spec — `name`, `skills`, `query`, `expected_behavior`, `success_criteria` — plus a machine-checkable `assertions` block. When adding a skill, add at least one scenario for it. + +## Running + +```bash +# Static sanity checks — fast, free: +node eval/harness/run.mjs + +# Live mode — run scenario queries through real agent sessions and check the +# transcripts. Costs minutes and real tokens per run. +node eval/harness/run.mjs --live +node eval/harness/run.mjs --live --scenario testing-run-e2e --repeat 3 +node eval/harness/run.mjs --live --scenario testing-write-e2e --model haiku +``` + +`--model` is passed through to the agent CLI, so the same scenario can be checked against any model you have access to. `--agent` selects the CLI adapter (default `claude`); supporting another agent CLI means adding one adapter entry in `eval/harness/run.mjs` that invokes it headless and normalizes its transcript into read/write/command events — the assertions are agent-agnostic. + +Notes: + +- No environment is required: the point is what the agent *consults and attempts*, not whether Gutenberg's tests execute. Agents run without write permissions, so a denied edit still shows up in the transcript as the attempt the assertions need — and your checkout is never modified. +- Agent compliance is probabilistic: use `--repeat 3` before treating a failure as a regression, and read the reported rates (`PASS (3/3)`). +- Results are colored by your personal agent configuration (`~/.claude`, `CLAUDE.local.md`, memory). +- Transcripts are saved under `eval/artifacts/` for debugging; failures print the actual reads/commands next to the expectation. + +## Assertion vocabulary + +| Key | Checks | +| --- | --- | +| `readsInclude` | Each path substring matches some file the agent read | +| `readsExclude` | No read matches the path substring | +| `readsBeforeCommand` | The read occurs before the first shell command matching `command` | +| `readsBeforeWrite` | The read occurs before the agent's first attempted file edit | +| `commandOrder` | `[before, after]`: if `after` ever runs, `before` ran first | +| `commandRules` | A command matching `matching` occurred, containing / avoiding substrings | +| `resultIncludes` | The agent's final message contains the substring | diff --git a/eval/scenarios/negative-control-trivial-task.json b/eval/scenarios/negative-control-trivial-task.json new file mode 100644 index 00000000000000..0641ecc70ad391 --- /dev/null +++ b/eval/scenarios/negative-control-trivial-task.json @@ -0,0 +1,20 @@ +{ + "name": "Negative control: trivial task triggers no skills or docs", + "skills": [], + "query": "If the word 'seperate' (a misspelling of 'separate') appears anywhere in CONTRIBUTING.md, fix it; if it does not appear, just say so.", + "expected_behavior": [ + "Step 1: Search CONTRIBUTING.md for the misspelling", + "Step 2: Report the result (or make the one-word fix)" + ], + "success_criteria": [ + "No skill files or contributor guides are read for a task that does not need them — the progressive-discovery router must not cause over-reading" + ], + "timeoutSeconds": 600, + "assertions": { + "readsExclude": [ + "skills/", + "docs/contributors/code/e2e/", + "docs/contributors/code/coding-guidelines.md" + ] + } +} diff --git a/eval/scenarios/testing-run-e2e.json b/eval/scenarios/testing-run-e2e.json new file mode 100644 index 00000000000000..e588923e5a7c07 --- /dev/null +++ b/eval/scenarios/testing-run-e2e.json @@ -0,0 +1,40 @@ +{ + "name": "Run e2e tests for a specific block", + "skills": [ "testing" ], + "query": "Run the e2e tests for the paragraph block", + "expected_behavior": [ + "Step 1: Read skills/testing/SKILL.md, then skills/testing/references/e2e.md (not the Jest or PHP references)", + "Step 2: Check npm run wp-env-test status before any wp-env-test start", + "Step 3: Run the paragraph spec scoped and headless" + ], + "success_criteria": [ + "Discovery chain root AGENTS.md → SKILL.md → e2e reference is followed before the first test command", + "Test run is scoped to a spec path and headless, with the environment checked first" + ], + "timeoutSeconds": 1800, + "assertions": { + "readsInclude": [ + "skills/testing/SKILL.md", + "skills/testing/references/e2e.md" + ], + "readsExclude": [ + "skills/testing/references/php.md", + "skills/testing/references/jest.md" + ], + "readsBeforeCommand": [ + { "read": "skills/testing/SKILL.md", "command": "test:e2e" }, + { + "read": "skills/testing/references/e2e.md", + "command": "test:e2e" + } + ], + "commandOrder": [ [ "wp-env-test status", "wp-env-test start" ] ], + "commandRules": [ + { + "matching": "test:e2e", + "mustContain": ".spec.js", + "mustNotContain": [ "--headed", "--ui", "--debug" ] + } + ] + } +} diff --git a/eval/scenarios/testing-write-e2e.json b/eval/scenarios/testing-write-e2e.json new file mode 100644 index 00000000000000..5c399a82be63f1 --- /dev/null +++ b/eval/scenarios/testing-write-e2e.json @@ -0,0 +1,30 @@ +{ + "name": "Write an e2e test for a specific behavior", + "skills": [ "testing" ], + "query": "Add an e2e test for the paragraph block that checks that the `&` key is not output as `&` in the editor", + "expected_behavior": [ + "Step 1: Read skills/testing/SKILL.md and skills/testing/references/e2e.md", + "Step 2: Read the End-to-End Testing guide (docs/contributors/code/e2e/README.md) before writing any test body", + "Step 3: Surface the proposed test names for review (in the summary when running unattended)", + "Step 4: Extend the existing paragraph spec rather than creating a parallel file" + ], + "success_criteria": [ + "The right guidance is consulted: both testing skill files and the e2e authoring guide, the guide before the first attempted edit", + "The unrelated references (Jest, PHP) are not read" + ], + "timeoutSeconds": 900, + "assertions": { + "readsInclude": [ + "skills/testing/SKILL.md", + "skills/testing/references/e2e.md", + "docs/contributors/code/e2e/README.md" + ], + "readsExclude": [ + "skills/testing/references/php.md", + "skills/testing/references/jest.md" + ], + "readsBeforeWrite": [ + { "read": "docs/contributors/code/e2e/README.md" } + ] + } +} From e6e529f0d0de02ad87cb59a1d0baae99692828f6 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Fri, 24 Jul 2026 16:15:47 -0400 Subject: [PATCH 2/6] Move eval harness to test/ai-development and fix lint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Relocate eval/ to test/ai-development/ — test infrastructure lives under test/ — flattening the harness/ subdirectory. Scenario and artifact paths now resolve relative to the script itself. - Format run.mjs with the repo formatter and allow console output for this CLI script. The initial commit never met the formatter because lint-staged's patterns do not cover .mjs files; CI's lint job caught it. - Update path references in the scenarios README and the agents-and-skills.md checklist. Co-Authored-By: Claude Fable 5 --- docs/contributors/code/agents-and-skills.md | 4 +- .../ai-development}/artifacts/.gitignore | 0 {eval/harness => test/ai-development}/run.mjs | 189 ++++++++++++++---- .../ai-development}/scenarios/README.md | 12 +- .../negative-control-trivial-task.json | 0 .../scenarios/testing-run-e2e.json | 0 .../scenarios/testing-write-e2e.json | 0 7 files changed, 156 insertions(+), 49 deletions(-) rename {eval => test/ai-development}/artifacts/.gitignore (100%) rename {eval/harness => test/ai-development}/run.mjs (67%) rename {eval => test/ai-development}/scenarios/README.md (78%) rename {eval => test/ai-development}/scenarios/negative-control-trivial-task.json (100%) rename {eval => test/ai-development}/scenarios/testing-run-e2e.json (100%) rename {eval => test/ai-development}/scenarios/testing-write-e2e.json (100%) diff --git a/docs/contributors/code/agents-and-skills.md b/docs/contributors/code/agents-and-skills.md index 8736b20a77d452..4dbe7cc2ccbcee 100644 --- a/docs/contributors/code/agents-and-skills.md +++ b/docs/contributors/code/agents-and-skills.md @@ -74,5 +74,5 @@ Walking through how the live testing skill applies these conventions: 1. Confirm the public docs can't cover it — improve them first if they can. 2. Create `skills//SKILL.md` following the conventions above. 3. Add a routing entry to the root `AGENTS.md`. -4. Add at least one eval scenario under `eval/scenarios/` (see [its README](https://github.com/WordPress/gutenberg/blob/trunk/eval/scenarios/README.md)) describing a task the skill covers and how to verify an agent followed it. -5. Run `npm run lint:md:docs` and `node eval/harness/run.mjs`. +4. Add at least one eval scenario under `test/ai-development/scenarios/` (see [its README](https://github.com/WordPress/gutenberg/blob/trunk/test/ai-development/scenarios/README.md)) describing a task the skill covers and how to verify an agent followed it. +5. Run `npm run lint:md:docs` and `node test/ai-development/run.mjs`. diff --git a/eval/artifacts/.gitignore b/test/ai-development/artifacts/.gitignore similarity index 100% rename from eval/artifacts/.gitignore rename to test/ai-development/artifacts/.gitignore diff --git a/eval/harness/run.mjs b/test/ai-development/run.mjs similarity index 67% rename from eval/harness/run.mjs rename to test/ai-development/run.mjs index db328613719dc7..404bfdd38cbe1a 100644 --- a/eval/harness/run.mjs +++ b/test/ai-development/run.mjs @@ -11,13 +11,13 @@ * * Static checks (default) — fast, free: * - * node eval/harness/run.mjs + * node test/ai-development/run.mjs * * Live mode — runs scenario queries through real agent sessions (minutes and * real tokens per run): * - * node eval/harness/run.mjs --live - * node eval/harness/run.mjs --live --scenario testing-run-e2e --model haiku --repeat 3 + * node test/ai-development/run.mjs --live + * node test/ai-development/run.mjs --live --scenario testing-run-e2e --model haiku --repeat 3 * * Options: --scenario , --agent (default: claude), --model * (passed through to the agent CLI), --repeat . @@ -27,13 +27,17 @@ * { events: [ { kind: read|write|command, value } ], result }. */ +/* eslint-disable no-console -- CLI script; reports results to the terminal. */ + import fs from 'node:fs'; import path from 'node:path'; +import { fileURLToPath } from 'node:url'; import { spawnSync } from 'node:child_process'; const repoRoot = process.cwd(); -const scenariosDir = path.join( repoRoot, 'eval', 'scenarios' ); -const artifactsDir = path.join( repoRoot, 'eval', 'artifacts' ); +const here = path.dirname( fileURLToPath( import.meta.url ) ); +const scenariosDir = path.join( here, 'scenarios' ); +const artifactsDir = path.join( here, 'artifacts' ); /* ------------------------------------------------------------------------- * Static checks @@ -44,7 +48,9 @@ function parseFrontmatter( markdown ) { if ( lines[ 0 ]?.trim() !== '---' ) { return null; } - const end = lines.findIndex( ( line, i ) => i > 0 && line.trim() === '---' ); + const end = lines.findIndex( + ( line, i ) => i > 0 && line.trim() === '---' + ); if ( end === -1 ) { return null; } @@ -84,10 +90,15 @@ function staticChecks() { const fm = parseFrontmatter( fs.readFileSync( skillPath, 'utf8' ) ); assert( fm, `Missing YAML frontmatter in: ${ rel }` ); assert( fm.name, `Missing frontmatter 'name' in: ${ rel }` ); - assert( fm.description, `Missing frontmatter 'description' in: ${ rel }` ); + assert( + fm.description, + `Missing frontmatter 'description' in: ${ rel }` + ); assert( fm.name === path.basename( dir ), - `Frontmatter name mismatch in ${ rel }: expected '${ path.basename( dir ) }', got '${ fm.name }'` + `Frontmatter name mismatch in ${ rel }: expected '${ path.basename( + dir + ) }', got '${ fm.name }'` ); } return skillDirs.length; @@ -99,7 +110,9 @@ function loadScenarios() { .filter( ( f ) => f.endsWith( '.json' ) ) .map( ( f ) => ( { slug: f.replace( /\.json$/, '' ), - ...JSON.parse( fs.readFileSync( path.join( scenariosDir, f ), 'utf8' ) ), + ...JSON.parse( + fs.readFileSync( path.join( scenariosDir, f ), 'utf8' ) + ), } ) ); } @@ -111,7 +124,13 @@ const ADAPTERS = { claude: { command: 'claude', buildArgs( scenario, model ) { - const args = [ '-p', scenario.query, '--verbose', '--output-format', 'stream-json' ]; + const args = [ + '-p', + scenario.query, + '--verbose', + '--output-format', + 'stream-json', + ]; if ( model ) { args.push( '--model', model ); } @@ -134,10 +153,21 @@ const ADAPTERS = { const input = block.input ?? {}; if ( block.name === 'Read' && input.file_path ) { events.push( { kind: 'read', value: input.file_path } ); - } else if ( [ 'Edit', 'Write', 'NotebookEdit' ].includes( block.name ) && input.file_path ) { - events.push( { kind: 'write', value: input.file_path } ); + } else if ( + [ 'Edit', 'Write', 'NotebookEdit' ].includes( + block.name + ) && + input.file_path + ) { + events.push( { + kind: 'write', + value: input.file_path, + } ); } else if ( block.name === 'Bash' && input.command ) { - events.push( { kind: 'command', value: input.command } ); + events.push( { + kind: 'command', + value: input.command, + } ); } } if ( obj?.type === 'result' ) { @@ -154,21 +184,38 @@ const ADAPTERS = { * ---------------------------------------------------------------------- */ function firstIndex( events, kind, needle ) { - return events.findIndex( ( e ) => e.kind === kind && e.value.includes( needle ) ); + return events.findIndex( + ( e ) => e.kind === kind && e.value.includes( needle ) + ); } function checkAssertions( assertions, { events, result } ) { const outcomes = []; - const record = ( label, pass, evidence = [] ) => outcomes.push( { label, pass, evidence } ); - const reads = events.filter( ( e ) => e.kind === 'read' ).map( ( e ) => e.value ); - const commands = events.filter( ( e ) => e.kind === 'command' ).map( ( e ) => e.value ); - const timeline = events.map( ( e ) => `${ e.kind }: ${ e.value.slice( 0, 100 ) }` ); + const record = ( label, pass, evidence = [] ) => + outcomes.push( { label, pass, evidence } ); + const reads = events + .filter( ( e ) => e.kind === 'read' ) + .map( ( e ) => e.value ); + const commands = events + .filter( ( e ) => e.kind === 'command' ) + .map( ( e ) => e.value ); + const timeline = events.map( + ( e ) => `${ e.kind }: ${ e.value.slice( 0, 100 ) }` + ); for ( const needle of assertions.readsInclude ?? [] ) { - record( `reads include ${ needle }`, reads.some( ( r ) => r.includes( needle ) ), reads ); + record( + `reads include ${ needle }`, + reads.some( ( r ) => r.includes( needle ) ), + reads + ); } for ( const needle of assertions.readsExclude ?? [] ) { - record( `reads exclude ${ needle }`, ! reads.some( ( r ) => r.includes( needle ) ), reads ); + record( + `reads exclude ${ needle }`, + ! reads.some( ( r ) => r.includes( needle ) ), + reads + ); } for ( const { read, command } of assertions.readsBeforeCommand ?? [] ) { const readIdx = firstIndex( events, 'read', read ); @@ -198,19 +245,37 @@ function checkAssertions( assertions, { events, result } ) { ); } for ( const rule of assertions.commandRules ?? [] ) { - const matching = commands.filter( ( c ) => c.includes( rule.matching ) ); - record( `a command matching '${ rule.matching }' occurred`, matching.length > 0, commands ); + const matching = commands.filter( ( c ) => + c.includes( rule.matching ) + ); + record( + `a command matching '${ rule.matching }' occurred`, + matching.length > 0, + commands + ); for ( const command of matching ) { if ( rule.mustContain ) { - record( `'${ rule.matching }' command contains '${ rule.mustContain }'`, command.includes( rule.mustContain ), [ command ] ); + record( + `'${ rule.matching }' command contains '${ rule.mustContain }'`, + command.includes( rule.mustContain ), + [ command ] + ); } for ( const banned of rule.mustNotContain ?? [] ) { - record( `'${ rule.matching }' command avoids '${ banned }'`, ! command.includes( banned ), [ command ] ); + record( + `'${ rule.matching }' command avoids '${ banned }'`, + ! command.includes( banned ), + [ command ] + ); } } } for ( const needle of assertions.resultIncludes ?? [] ) { - record( `result includes '${ needle }'`, ( result ?? '' ).includes( needle ), [ ( result ?? '' ).slice( 0, 300 ) ] ); + record( + `result includes '${ needle }'`, + ( result ?? '' ).includes( needle ), + [ ( result ?? '' ).slice( 0, 300 ) ] + ); } return outcomes; } @@ -220,25 +285,44 @@ function checkAssertions( assertions, { events, result } ) { * ---------------------------------------------------------------------- */ function runOnce( scenario, adapter, model, runIndex ) { - const out = spawnSync( adapter.command, adapter.buildArgs( scenario, model ), { - cwd: repoRoot, - encoding: 'utf8', - timeout: ( scenario.timeoutSeconds ?? 900 ) * 1000, - maxBuffer: 256 * 1024 * 1024, - } ); + const out = spawnSync( + adapter.command, + adapter.buildArgs( scenario, model ), + { + cwd: repoRoot, + encoding: 'utf8', + timeout: ( scenario.timeoutSeconds ?? 900 ) * 1000, + maxBuffer: 256 * 1024 * 1024, + } + ); fs.mkdirSync( artifactsDir, { recursive: true } ); - const artifact = path.join( artifactsDir, `${ scenario.slug }-${ Date.now() }-${ runIndex }.jsonl` ); + const artifact = path.join( + artifactsDir, + `${ scenario.slug }-${ Date.now() }-${ runIndex }.jsonl` + ); fs.writeFileSync( artifact, out.stdout ?? '' ); if ( out.error ) { - throw new Error( `${ adapter.command } failed to run: ${ out.error.message }` ); + throw new Error( + `${ adapter.command } failed to run: ${ out.error.message }` + ); } - return { outcomes: checkAssertions( scenario.assertions, adapter.parse( out.stdout ?? '' ) ), artifact }; + return { + outcomes: checkAssertions( + scenario.assertions, + adapter.parse( out.stdout ?? '' ) + ), + artifact, + }; } function runLive( scenarios, { only, agentName, model, repeat } ) { const adapter = ADAPTERS[ agentName ]; if ( ! adapter ) { - console.error( `Unknown agent '${ agentName }'. Available: ${ Object.keys( ADAPTERS ).join( ', ' ) }` ); + console.error( + `Unknown agent '${ agentName }'. Available: ${ Object.keys( + ADAPTERS + ).join( ', ' ) }` + ); process.exit( 1 ); } let failed = false; @@ -250,13 +334,28 @@ function runLive( scenarios, { only, agentName, model, repeat } ) { console.log( `SKIP ${ scenario.slug }: no assertions block` ); continue; } - console.log( `\nRUN ${ scenario.slug } [${ agentName }${ model ? `:${ model }` : '' }] "${ scenario.query }" (${ repeat }x)` ); + console.log( + `\nRUN ${ scenario.slug } [${ agentName }${ + model ? `:${ model }` : '' + }] "${ scenario.query }" (${ repeat }x)` + ); const totals = new Map(); for ( let i = 0; i < repeat; i++ ) { - const { outcomes, artifact } = runOnce( scenario, adapter, model, i ); - console.log( ` transcript: ${ path.relative( repoRoot, artifact ) }` ); + const { outcomes, artifact } = runOnce( + scenario, + adapter, + model, + i + ); + console.log( + ` transcript: ${ path.relative( repoRoot, artifact ) }` + ); for ( const { label, pass, evidence } of outcomes ) { - const t = totals.get( label ) ?? { pass: 0, total: 0, evidence: [] }; + const t = totals.get( label ) ?? { + pass: 0, + total: 0, + evidence: [], + }; t.total += 1; if ( pass ) { t.pass += 1; @@ -268,7 +367,11 @@ function runLive( scenarios, { only, agentName, model, repeat } ) { } for ( const [ label, t ] of totals ) { const ok = t.pass === t.total; - console.log( ` ${ ok ? 'PASS' : 'FAIL' } (${ t.pass }/${ t.total }) ${ label }` ); + console.log( + ` ${ ok ? 'PASS' : 'FAIL' } (${ t.pass }/${ + t.total + }) ${ label }` + ); if ( ! ok ) { for ( const line of t.evidence.slice( 0, 20 ) ) { console.log( ` actual: ${ line }` ); @@ -293,7 +396,9 @@ function main() { const argv = process.argv.slice( 2 ); const skillCount = staticChecks(); const scenarios = loadScenarios(); - console.log( `OK: ${ skillCount } skill(s) and ${ scenarios.length } scenario(s) passed sanity checks.` ); + console.log( + `OK: ${ skillCount } skill(s) and ${ scenarios.length } scenario(s) passed sanity checks.` + ); if ( ! argv.includes( '--live' ) ) { return; @@ -308,3 +413,5 @@ function main() { } main(); + +/* eslint-enable no-console */ diff --git a/eval/scenarios/README.md b/test/ai-development/scenarios/README.md similarity index 78% rename from eval/scenarios/README.md rename to test/ai-development/scenarios/README.md index ae967e7139825f..315f42e03f5162 100644 --- a/eval/scenarios/README.md +++ b/test/ai-development/scenarios/README.md @@ -8,23 +8,23 @@ Each `.json` defines a human-readable spec — `name`, `skills`, `query`, ```bash # Static sanity checks — fast, free: -node eval/harness/run.mjs +node test/ai-development/run.mjs # Live mode — run scenario queries through real agent sessions and check the # transcripts. Costs minutes and real tokens per run. -node eval/harness/run.mjs --live -node eval/harness/run.mjs --live --scenario testing-run-e2e --repeat 3 -node eval/harness/run.mjs --live --scenario testing-write-e2e --model haiku +node test/ai-development/run.mjs --live +node test/ai-development/run.mjs --live --scenario testing-run-e2e --repeat 3 +node test/ai-development/run.mjs --live --scenario testing-write-e2e --model haiku ``` -`--model` is passed through to the agent CLI, so the same scenario can be checked against any model you have access to. `--agent` selects the CLI adapter (default `claude`); supporting another agent CLI means adding one adapter entry in `eval/harness/run.mjs` that invokes it headless and normalizes its transcript into read/write/command events — the assertions are agent-agnostic. +`--model` is passed through to the agent CLI, so the same scenario can be checked against any model you have access to. `--agent` selects the CLI adapter (default `claude`); supporting another agent CLI means adding one adapter entry in `test/ai-development/run.mjs` that invokes it headless and normalizes its transcript into read/write/command events — the assertions are agent-agnostic. Notes: - No environment is required: the point is what the agent *consults and attempts*, not whether Gutenberg's tests execute. Agents run without write permissions, so a denied edit still shows up in the transcript as the attempt the assertions need — and your checkout is never modified. - Agent compliance is probabilistic: use `--repeat 3` before treating a failure as a regression, and read the reported rates (`PASS (3/3)`). - Results are colored by your personal agent configuration (`~/.claude`, `CLAUDE.local.md`, memory). -- Transcripts are saved under `eval/artifacts/` for debugging; failures print the actual reads/commands next to the expectation. +- Transcripts are saved under `test/ai-development/artifacts/` for debugging; failures print the actual reads/commands next to the expectation. ## Assertion vocabulary diff --git a/eval/scenarios/negative-control-trivial-task.json b/test/ai-development/scenarios/negative-control-trivial-task.json similarity index 100% rename from eval/scenarios/negative-control-trivial-task.json rename to test/ai-development/scenarios/negative-control-trivial-task.json diff --git a/eval/scenarios/testing-run-e2e.json b/test/ai-development/scenarios/testing-run-e2e.json similarity index 100% rename from eval/scenarios/testing-run-e2e.json rename to test/ai-development/scenarios/testing-run-e2e.json diff --git a/eval/scenarios/testing-write-e2e.json b/test/ai-development/scenarios/testing-write-e2e.json similarity index 100% rename from eval/scenarios/testing-write-e2e.json rename to test/ai-development/scenarios/testing-write-e2e.json From 0f7fdc23ecd774f2ef31778eba0b3d770dbec7ba Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Fri, 24 Jul 2026 16:23:52 -0400 Subject: [PATCH 3/6] Update docs to include live test run --- docs/contributors/code/agents-and-skills.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/contributors/code/agents-and-skills.md b/docs/contributors/code/agents-and-skills.md index 4dbe7cc2ccbcee..39f55cddd6e7e4 100644 --- a/docs/contributors/code/agents-and-skills.md +++ b/docs/contributors/code/agents-and-skills.md @@ -75,4 +75,6 @@ Walking through how the live testing skill applies these conventions: 2. Create `skills//SKILL.md` following the conventions above. 3. Add a routing entry to the root `AGENTS.md`. 4. Add at least one eval scenario under `test/ai-development/scenarios/` (see [its README](https://github.com/WordPress/gutenberg/blob/trunk/test/ai-development/scenarios/README.md)) describing a task the skill covers and how to verify an agent followed it. -5. Run `npm run lint:md:docs` and `node test/ai-development/run.mjs`. +5. Run your scenario live and confirm it passes: `node test/ai-development/run.mjs --live --scenario `. +6. Run the full suite to confirm nothing else regressed: `node test/ai-development/run.mjs --live` (the static sanity checks run first automatically). +7. Once everything passes, run `npm run lint:md:docs`. From 1e84c8fde733f03f7c9cac14e4bbb8cb3af054ab Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Mon, 27 Jul 2026 15:37:54 -0400 Subject: [PATCH 4/6] Rebuild the agent eval on the Playwright test runner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Alternative to the standalone runner in #80703. The core survives unchanged in test/ai-development/agent.mjs: the claude adapter, transcript normalization into read/write/command events, and the declarative assertion evaluation. @playwright/test (already installed, runner only — no browsers) replaces the bespoke runner: repeats via --repeat-each, filtering via -g, standard reporting and exit codes. The static frontmatter checks are dropped. Run with `npm run test:ai-development`; select a model with AI_EVAL_MODEL. Verified: the negative-control scenario passes end to end through the new pipeline, and `npm run test:unit -- --listTests` confirms Jest never sweeps these tests up. Co-Authored-By: Claude Fable 5 --- docs/contributors/code/agents-and-skills.md | 4 +- package.json | 1 + test/ai-development/agent.mjs | 235 +++++++++++ test/ai-development/playwright.config.mjs | 21 + test/ai-development/run.mjs | 417 ------------------- test/ai-development/scenarios/README.md | 28 +- test/ai-development/specs/scenarios.spec.mjs | 48 +++ 7 files changed, 323 insertions(+), 431 deletions(-) create mode 100644 test/ai-development/agent.mjs create mode 100644 test/ai-development/playwright.config.mjs delete mode 100644 test/ai-development/run.mjs create mode 100644 test/ai-development/specs/scenarios.spec.mjs diff --git a/docs/contributors/code/agents-and-skills.md b/docs/contributors/code/agents-and-skills.md index 39f55cddd6e7e4..ddefe1bc95da73 100644 --- a/docs/contributors/code/agents-and-skills.md +++ b/docs/contributors/code/agents-and-skills.md @@ -75,6 +75,6 @@ Walking through how the live testing skill applies these conventions: 2. Create `skills//SKILL.md` following the conventions above. 3. Add a routing entry to the root `AGENTS.md`. 4. Add at least one eval scenario under `test/ai-development/scenarios/` (see [its README](https://github.com/WordPress/gutenberg/blob/trunk/test/ai-development/scenarios/README.md)) describing a task the skill covers and how to verify an agent followed it. -5. Run your scenario live and confirm it passes: `node test/ai-development/run.mjs --live --scenario `. -6. Run the full suite to confirm nothing else regressed: `node test/ai-development/run.mjs --live` (the static sanity checks run first automatically). +5. Run your scenario and confirm it passes: `npm run test:ai-development -- -g ""`. +6. Run the full suite to confirm nothing else regressed — including the negative control: `npm run test:ai-development`. 7. Once everything passes, run `npm run lint:md:docs`. diff --git a/package.json b/package.json index cc01d0bf0985e6..895e123c2b7ab3 100644 --- a/package.json +++ b/package.json @@ -157,6 +157,7 @@ "storybook:e2e:dev": "concurrently \"npm run dev\" \"wait-on .dev-ready && npm run --workspace @wordpress/storybook-playwright storybook:dev\"", "storybook:e2e:build": "npm run --workspace @wordpress/storybook-playwright storybook:build", "test": "npm-run-all lint test:unit", + "test:ai-development": "playwright test --config test/ai-development/playwright.config.mjs", "test:create-block": "npm run --workspace @wordpress/validation-tools test-create-block --", "test:e2e": "npm exec --workspace @wordpress/e2e-tests-playwright -- wp-scripts test-e2e --config playwright.config.ts", "test:e2e:debug": "npm exec --workspace @wordpress/e2e-tests-playwright -- wp-scripts test-e2e --config playwright.config.ts --ui", diff --git a/test/ai-development/agent.mjs b/test/ai-development/agent.mjs new file mode 100644 index 00000000000000..957f527de589da --- /dev/null +++ b/test/ai-development/agent.mjs @@ -0,0 +1,235 @@ +/** + * Agent-session helpers for the AI development tests. + * + * Runs a scenario's task prompt through a real agent CLI session and + * normalizes the transcript into ordered read/write/command events so tests + * can verify the agent consulted the right guidance. The agent is granted no + * write permissions — an attempted (denied) edit is still evidence, and the + * checkout is never modified. No running WordPress environment is required. + * + * Supporting another agent CLI means adding one ADAPTERS entry that invokes + * it headless and normalizes its transcript into + * { events: [ { kind: read|write|command, value } ], result }. + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawnSync } from 'node:child_process'; + +const here = path.dirname( fileURLToPath( import.meta.url ) ); +const scenariosDir = path.join( here, 'scenarios' ); +const artifactsDir = path.join( here, 'artifacts' ); + +export function loadScenarios() { + return fs + .readdirSync( scenariosDir ) + .filter( ( f ) => f.endsWith( '.json' ) ) + .map( ( f ) => ( { + slug: f.replace( /\.json$/, '' ), + ...JSON.parse( + fs.readFileSync( path.join( scenariosDir, f ), 'utf8' ) + ), + } ) ); +} + +const ADAPTERS = { + claude: { + command: 'claude', + buildArgs( scenario, model ) { + const args = [ + '-p', + scenario.query, + '--verbose', + '--output-format', + 'stream-json', + ]; + if ( model ) { + args.push( '--model', model ); + } + return args; + }, + parse( raw ) { + const events = []; + let result = null; + for ( const line of raw.split( '\n' ) ) { + let obj; + try { + obj = JSON.parse( line ); + } catch { + continue; + } + for ( const block of obj?.message?.content ?? [] ) { + if ( block?.type !== 'tool_use' ) { + continue; + } + const input = block.input ?? {}; + if ( block.name === 'Read' && input.file_path ) { + events.push( { + kind: 'read', + value: input.file_path, + } ); + } else if ( + [ 'Edit', 'Write', 'NotebookEdit' ].includes( + block.name + ) && + input.file_path + ) { + events.push( { + kind: 'write', + value: input.file_path, + } ); + } else if ( block.name === 'Bash' && input.command ) { + events.push( { + kind: 'command', + value: input.command, + } ); + } + } + if ( obj?.type === 'result' ) { + result = obj.result ?? ''; + } + } + return { events, result }; + }, + }, +}; + +export function runAgent( scenario, { agent = 'claude', model } = {} ) { + const adapter = ADAPTERS[ agent ]; + if ( ! adapter ) { + throw new Error( + `Unknown agent '${ agent }'. Available: ${ Object.keys( + ADAPTERS + ).join( ', ' ) }` + ); + } + const out = spawnSync( + adapter.command, + adapter.buildArgs( scenario, model ), + { + cwd: path.resolve( here, '..', '..' ), + encoding: 'utf8', + timeout: ( scenario.timeoutSeconds ?? 900 ) * 1000, + maxBuffer: 256 * 1024 * 1024, + } + ); + fs.mkdirSync( artifactsDir, { recursive: true } ); + const artifact = path.join( + artifactsDir, + `${ scenario.slug }-${ Date.now() }.jsonl` + ); + fs.writeFileSync( artifact, out.stdout ?? '' ); + if ( out.error ) { + throw new Error( + `${ adapter.command } failed to run: ${ out.error.message }` + ); + } + return { ...adapter.parse( out.stdout ?? '' ), artifact }; +} + +function firstIndex( events, kind, needle ) { + return events.findIndex( + ( e ) => e.kind === kind && e.value.includes( needle ) + ); +} + +/** + * Evaluates a scenario's declarative assertions against a normalized + * transcript. Returns outcomes: { label, pass, evidence }. + * + * @param {Object} assertions The scenario's `assertions` block. + * @param {Object} transcript Normalized transcript. + * @param {Array} transcript.events Ordered read/write/command events. + * @param {?string} transcript.result The agent's final message. + */ +export function checkAssertions( assertions, { events, result } ) { + const outcomes = []; + const record = ( label, pass, evidence = [] ) => + outcomes.push( { label, pass, evidence } ); + const reads = events + .filter( ( e ) => e.kind === 'read' ) + .map( ( e ) => e.value ); + const commands = events + .filter( ( e ) => e.kind === 'command' ) + .map( ( e ) => e.value ); + const timeline = events.map( + ( e ) => `${ e.kind }: ${ e.value.slice( 0, 100 ) }` + ); + + for ( const needle of assertions.readsInclude ?? [] ) { + record( + `reads include ${ needle }`, + reads.some( ( r ) => r.includes( needle ) ), + reads + ); + } + for ( const needle of assertions.readsExclude ?? [] ) { + record( + `reads exclude ${ needle }`, + ! reads.some( ( r ) => r.includes( needle ) ), + reads + ); + } + for ( const { read, command } of assertions.readsBeforeCommand ?? [] ) { + const readIdx = firstIndex( events, 'read', read ); + const cmdIdx = firstIndex( events, 'command', command ); + record( + `read ${ read } before command '${ command }'`, + readIdx !== -1 && ( cmdIdx === -1 || readIdx < cmdIdx ), + timeline + ); + } + for ( const { read } of assertions.readsBeforeWrite ?? [] ) { + const readIdx = firstIndex( events, 'read', read ); + const writeIdx = events.findIndex( ( e ) => e.kind === 'write' ); + record( + `read ${ read } before first write attempt`, + readIdx !== -1 && ( writeIdx === -1 || readIdx < writeIdx ), + timeline + ); + } + for ( const [ before, after ] of assertions.commandOrder ?? [] ) { + const afterIdx = firstIndex( events, 'command', after ); + const beforeIdx = firstIndex( events, 'command', before ); + record( + `command '${ before }' before '${ after }'`, + afterIdx === -1 || ( beforeIdx !== -1 && beforeIdx < afterIdx ), + commands + ); + } + for ( const rule of assertions.commandRules ?? [] ) { + const matching = commands.filter( ( c ) => + c.includes( rule.matching ) + ); + record( + `a command matching '${ rule.matching }' occurred`, + matching.length > 0, + commands + ); + for ( const command of matching ) { + if ( rule.mustContain ) { + record( + `'${ rule.matching }' command contains '${ rule.mustContain }'`, + command.includes( rule.mustContain ), + [ command ] + ); + } + for ( const banned of rule.mustNotContain ?? [] ) { + record( + `'${ rule.matching }' command avoids '${ banned }'`, + ! command.includes( banned ), + [ command ] + ); + } + } + } + for ( const needle of assertions.resultIncludes ?? [] ) { + record( + `result includes '${ needle }'`, + ( result ?? '' ).includes( needle ), + [ ( result ?? '' ).slice( 0, 300 ) ] + ); + } + return outcomes; +} diff --git a/test/ai-development/playwright.config.mjs b/test/ai-development/playwright.config.mjs new file mode 100644 index 00000000000000..a1dae42c5fd6bc --- /dev/null +++ b/test/ai-development/playwright.config.mjs @@ -0,0 +1,21 @@ +/** + * Playwright is used here purely as a test runner — no browsers are involved. + * Each test spawns a real, headless agent CLI session, which costs minutes + * and real tokens: this config must only ever be invoked explicitly via + * `npm run test:ai-development`, never swept up by CI or default test globs. + */ + +/** + * External dependencies + */ +import { defineConfig } from '@playwright/test'; + +export default defineConfig( { + testDir: './specs', + outputDir: './artifacts/test-results', + workers: 1, + fullyParallel: false, + reporter: 'list', + // Individual tests set their own timeout from the scenario file. + timeout: 30 * 60 * 1000, +} ); diff --git a/test/ai-development/run.mjs b/test/ai-development/run.mjs deleted file mode 100644 index 404bfdd38cbe1a..00000000000000 --- a/test/ai-development/run.mjs +++ /dev/null @@ -1,417 +0,0 @@ -/** - * Eval harness for agent skills. - * - * Verifies that an agent, given a scenario's task prompt, consulted the right - * guidance: read the skill files and docs it should, didn't read the ones it - * shouldn't, in the right order, and reached for the right kind of command. - * Evidence comes from the agent's own transcript; nothing needs a running - * WordPress environment, and the agent is not granted write permissions — an - * attempted (denied) edit is still evidence, and your checkout is never - * touched. - * - * Static checks (default) — fast, free: - * - * node test/ai-development/run.mjs - * - * Live mode — runs scenario queries through real agent sessions (minutes and - * real tokens per run): - * - * node test/ai-development/run.mjs --live - * node test/ai-development/run.mjs --live --scenario testing-run-e2e --model haiku --repeat 3 - * - * Options: --scenario , --agent (default: claude), --model - * (passed through to the agent CLI), --repeat . - * - * Supporting another agent CLI means adding one ADAPTERS entry that invokes - * it headless and normalizes its transcript into - * { events: [ { kind: read|write|command, value } ], result }. - */ - -/* eslint-disable no-console -- CLI script; reports results to the terminal. */ - -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { spawnSync } from 'node:child_process'; - -const repoRoot = process.cwd(); -const here = path.dirname( fileURLToPath( import.meta.url ) ); -const scenariosDir = path.join( here, 'scenarios' ); -const artifactsDir = path.join( here, 'artifacts' ); - -/* ------------------------------------------------------------------------- - * Static checks - * ---------------------------------------------------------------------- */ - -function parseFrontmatter( markdown ) { - const lines = markdown.split( '\n' ); - if ( lines[ 0 ]?.trim() !== '---' ) { - return null; - } - const end = lines.findIndex( - ( line, i ) => i > 0 && line.trim() === '---' - ); - if ( end === -1 ) { - return null; - } - const metadata = {}; - for ( const line of lines.slice( 1, end ) ) { - const m = line.match( /^\s*([A-Za-z0-9_-]+)\s*:\s*(.*)\s*$/ ); - if ( m ) { - metadata[ m[ 1 ] ] = m[ 2 ] - .replace( /^"(.*)"$/, '$1' ) - .replace( /^'(.*)'$/, '$1' ) - .trim(); - } - } - return metadata; -} - -function assert( condition, message ) { - if ( ! condition ) { - throw new Error( message ); - } -} - -function staticChecks() { - const skillsRoot = path.join( repoRoot, 'skills' ); - const skillDirs = fs.existsSync( skillsRoot ) - ? fs - .readdirSync( skillsRoot, { withFileTypes: true } ) - .filter( ( d ) => d.isDirectory() ) - .map( ( d ) => path.join( skillsRoot, d.name ) ) - : []; - assert( skillDirs.length > 0, 'No skills found under ./skills' ); - - for ( const dir of skillDirs ) { - const skillPath = path.join( dir, 'SKILL.md' ); - const rel = path.relative( repoRoot, skillPath ); - assert( fs.existsSync( skillPath ), `Missing SKILL.md: ${ rel }` ); - const fm = parseFrontmatter( fs.readFileSync( skillPath, 'utf8' ) ); - assert( fm, `Missing YAML frontmatter in: ${ rel }` ); - assert( fm.name, `Missing frontmatter 'name' in: ${ rel }` ); - assert( - fm.description, - `Missing frontmatter 'description' in: ${ rel }` - ); - assert( - fm.name === path.basename( dir ), - `Frontmatter name mismatch in ${ rel }: expected '${ path.basename( - dir - ) }', got '${ fm.name }'` - ); - } - return skillDirs.length; -} - -function loadScenarios() { - return fs - .readdirSync( scenariosDir ) - .filter( ( f ) => f.endsWith( '.json' ) ) - .map( ( f ) => ( { - slug: f.replace( /\.json$/, '' ), - ...JSON.parse( - fs.readFileSync( path.join( scenariosDir, f ), 'utf8' ) - ), - } ) ); -} - -/* ------------------------------------------------------------------------- - * Agent adapters - * ---------------------------------------------------------------------- */ - -const ADAPTERS = { - claude: { - command: 'claude', - buildArgs( scenario, model ) { - const args = [ - '-p', - scenario.query, - '--verbose', - '--output-format', - 'stream-json', - ]; - if ( model ) { - args.push( '--model', model ); - } - return args; - }, - parse( raw ) { - const events = []; - let result = null; - for ( const line of raw.split( '\n' ) ) { - let obj; - try { - obj = JSON.parse( line ); - } catch { - continue; - } - for ( const block of obj?.message?.content ?? [] ) { - if ( block?.type !== 'tool_use' ) { - continue; - } - const input = block.input ?? {}; - if ( block.name === 'Read' && input.file_path ) { - events.push( { kind: 'read', value: input.file_path } ); - } else if ( - [ 'Edit', 'Write', 'NotebookEdit' ].includes( - block.name - ) && - input.file_path - ) { - events.push( { - kind: 'write', - value: input.file_path, - } ); - } else if ( block.name === 'Bash' && input.command ) { - events.push( { - kind: 'command', - value: input.command, - } ); - } - } - if ( obj?.type === 'result' ) { - result = obj.result ?? ''; - } - } - return { events, result }; - }, - }, -}; - -/* ------------------------------------------------------------------------- - * Assertions over the normalized event log - * ---------------------------------------------------------------------- */ - -function firstIndex( events, kind, needle ) { - return events.findIndex( - ( e ) => e.kind === kind && e.value.includes( needle ) - ); -} - -function checkAssertions( assertions, { events, result } ) { - const outcomes = []; - const record = ( label, pass, evidence = [] ) => - outcomes.push( { label, pass, evidence } ); - const reads = events - .filter( ( e ) => e.kind === 'read' ) - .map( ( e ) => e.value ); - const commands = events - .filter( ( e ) => e.kind === 'command' ) - .map( ( e ) => e.value ); - const timeline = events.map( - ( e ) => `${ e.kind }: ${ e.value.slice( 0, 100 ) }` - ); - - for ( const needle of assertions.readsInclude ?? [] ) { - record( - `reads include ${ needle }`, - reads.some( ( r ) => r.includes( needle ) ), - reads - ); - } - for ( const needle of assertions.readsExclude ?? [] ) { - record( - `reads exclude ${ needle }`, - ! reads.some( ( r ) => r.includes( needle ) ), - reads - ); - } - for ( const { read, command } of assertions.readsBeforeCommand ?? [] ) { - const readIdx = firstIndex( events, 'read', read ); - const cmdIdx = firstIndex( events, 'command', command ); - record( - `read ${ read } before command '${ command }'`, - readIdx !== -1 && ( cmdIdx === -1 || readIdx < cmdIdx ), - timeline - ); - } - for ( const { read } of assertions.readsBeforeWrite ?? [] ) { - const readIdx = firstIndex( events, 'read', read ); - const writeIdx = events.findIndex( ( e ) => e.kind === 'write' ); - record( - `read ${ read } before first write attempt`, - readIdx !== -1 && ( writeIdx === -1 || readIdx < writeIdx ), - timeline - ); - } - for ( const [ before, after ] of assertions.commandOrder ?? [] ) { - const afterIdx = firstIndex( events, 'command', after ); - const beforeIdx = firstIndex( events, 'command', before ); - record( - `command '${ before }' before '${ after }'`, - afterIdx === -1 || ( beforeIdx !== -1 && beforeIdx < afterIdx ), - commands - ); - } - for ( const rule of assertions.commandRules ?? [] ) { - const matching = commands.filter( ( c ) => - c.includes( rule.matching ) - ); - record( - `a command matching '${ rule.matching }' occurred`, - matching.length > 0, - commands - ); - for ( const command of matching ) { - if ( rule.mustContain ) { - record( - `'${ rule.matching }' command contains '${ rule.mustContain }'`, - command.includes( rule.mustContain ), - [ command ] - ); - } - for ( const banned of rule.mustNotContain ?? [] ) { - record( - `'${ rule.matching }' command avoids '${ banned }'`, - ! command.includes( banned ), - [ command ] - ); - } - } - } - for ( const needle of assertions.resultIncludes ?? [] ) { - record( - `result includes '${ needle }'`, - ( result ?? '' ).includes( needle ), - [ ( result ?? '' ).slice( 0, 300 ) ] - ); - } - return outcomes; -} - -/* ------------------------------------------------------------------------- - * Live mode - * ---------------------------------------------------------------------- */ - -function runOnce( scenario, adapter, model, runIndex ) { - const out = spawnSync( - adapter.command, - adapter.buildArgs( scenario, model ), - { - cwd: repoRoot, - encoding: 'utf8', - timeout: ( scenario.timeoutSeconds ?? 900 ) * 1000, - maxBuffer: 256 * 1024 * 1024, - } - ); - fs.mkdirSync( artifactsDir, { recursive: true } ); - const artifact = path.join( - artifactsDir, - `${ scenario.slug }-${ Date.now() }-${ runIndex }.jsonl` - ); - fs.writeFileSync( artifact, out.stdout ?? '' ); - if ( out.error ) { - throw new Error( - `${ adapter.command } failed to run: ${ out.error.message }` - ); - } - return { - outcomes: checkAssertions( - scenario.assertions, - adapter.parse( out.stdout ?? '' ) - ), - artifact, - }; -} - -function runLive( scenarios, { only, agentName, model, repeat } ) { - const adapter = ADAPTERS[ agentName ]; - if ( ! adapter ) { - console.error( - `Unknown agent '${ agentName }'. Available: ${ Object.keys( - ADAPTERS - ).join( ', ' ) }` - ); - process.exit( 1 ); - } - let failed = false; - for ( const scenario of scenarios ) { - if ( only && scenario.slug !== only ) { - continue; - } - if ( ! scenario.assertions ) { - console.log( `SKIP ${ scenario.slug }: no assertions block` ); - continue; - } - console.log( - `\nRUN ${ scenario.slug } [${ agentName }${ - model ? `:${ model }` : '' - }] "${ scenario.query }" (${ repeat }x)` - ); - const totals = new Map(); - for ( let i = 0; i < repeat; i++ ) { - const { outcomes, artifact } = runOnce( - scenario, - adapter, - model, - i - ); - console.log( - ` transcript: ${ path.relative( repoRoot, artifact ) }` - ); - for ( const { label, pass, evidence } of outcomes ) { - const t = totals.get( label ) ?? { - pass: 0, - total: 0, - evidence: [], - }; - t.total += 1; - if ( pass ) { - t.pass += 1; - } else { - t.evidence = evidence; - } - totals.set( label, t ); - } - } - for ( const [ label, t ] of totals ) { - const ok = t.pass === t.total; - console.log( - ` ${ ok ? 'PASS' : 'FAIL' } (${ t.pass }/${ - t.total - }) ${ label }` - ); - if ( ! ok ) { - for ( const line of t.evidence.slice( 0, 20 ) ) { - console.log( ` actual: ${ line }` ); - } - failed = true; - } - } - } - return failed; -} - -/* ------------------------------------------------------------------------- - * Main - * ---------------------------------------------------------------------- */ - -function argValue( argv, flag ) { - const i = argv.indexOf( flag ); - return i !== -1 ? argv[ i + 1 ] : null; -} - -function main() { - const argv = process.argv.slice( 2 ); - const skillCount = staticChecks(); - const scenarios = loadScenarios(); - console.log( - `OK: ${ skillCount } skill(s) and ${ scenarios.length } scenario(s) passed sanity checks.` - ); - - if ( ! argv.includes( '--live' ) ) { - return; - } - const failed = runLive( scenarios, { - only: argValue( argv, '--scenario' ), - agentName: argValue( argv, '--agent' ) ?? 'claude', - model: argValue( argv, '--model' ), - repeat: Number( argValue( argv, '--repeat' ) ) || 1, - } ); - process.exit( failed ? 1 : 0 ); -} - -main(); - -/* eslint-enable no-console */ diff --git a/test/ai-development/scenarios/README.md b/test/ai-development/scenarios/README.md index 315f42e03f5162..4a53e98e064b67 100644 --- a/test/ai-development/scenarios/README.md +++ b/test/ai-development/scenarios/README.md @@ -6,25 +6,29 @@ Each `.json` defines a human-readable spec — `name`, `skills`, `query`, ## Running +The tests use Playwright purely as a test runner — no browsers are involved. Each test spawns a real, headless agent session, which costs minutes and real tokens per scenario, so they run only through this explicit command (never in CI or default test sweeps): + ```bash -# Static sanity checks — fast, free: -node test/ai-development/run.mjs - -# Live mode — run scenario queries through real agent sessions and check the -# transcripts. Costs minutes and real tokens per run. -node test/ai-development/run.mjs --live -node test/ai-development/run.mjs --live --scenario testing-run-e2e --repeat 3 -node test/ai-development/run.mjs --live --scenario testing-write-e2e --model haiku -``` +# All scenarios: +npm run test:ai-development + +# One scenario, by name: +npm run test:ai-development -- -g "Negative control" -`--model` is passed through to the agent CLI, so the same scenario can be checked against any model you have access to. `--agent` selects the CLI adapter (default `claude`); supporting another agent CLI means adding one adapter entry in `test/ai-development/run.mjs` that invokes it headless and normalizes its transcript into read/write/command events — the assertions are agent-agnostic. +# Repeat for confidence (agent compliance is probabilistic): +npm run test:ai-development -- --repeat-each=3 + +# Against a specific model (passed through to the agent CLI): +AI_EVAL_MODEL=haiku npm run test:ai-development +``` Notes: - No environment is required: the point is what the agent *consults and attempts*, not whether Gutenberg's tests execute. Agents run without write permissions, so a denied edit still shows up in the transcript as the attempt the assertions need — and your checkout is never modified. -- Agent compliance is probabilistic: use `--repeat 3` before treating a failure as a regression, and read the reported rates (`PASS (3/3)`). +- Treat a single-run failure as a smoke signal, not a verdict — re-run with `--repeat-each=3` before calling it a regression. - Results are colored by your personal agent configuration (`~/.claude`, `CLAUDE.local.md`, memory). -- Transcripts are saved under `test/ai-development/artifacts/` for debugging; failures print the actual reads/commands next to the expectation. +- Each run's raw transcript is saved under `test/ai-development/artifacts/` (failure messages include the exact path). +- Supporting another agent CLI means adding one adapter entry in `test/ai-development/agent.mjs` that invokes it headless and normalizes its transcript into read/write/command events — the assertions are agent-agnostic. ## Assertion vocabulary diff --git a/test/ai-development/specs/scenarios.spec.mjs b/test/ai-development/specs/scenarios.spec.mjs new file mode 100644 index 00000000000000..13f9fcf7f11aed --- /dev/null +++ b/test/ai-development/specs/scenarios.spec.mjs @@ -0,0 +1,48 @@ +/** + * Verifies that an agent, given each scenario's task prompt, consulted the + * right guidance: read the skill files and docs it should, didn't read the + * ones it shouldn't, in the right order, and reached for the right kind of + * command. Evidence comes from the agent's own transcript. + * + * Every test spawns a real agent session (minutes and real tokens). Run only + * via `npm run test:ai-development` — see ../scenarios/README.md. + */ + +/** + * External dependencies + */ +import { test, expect } from '@playwright/test'; + +/** + * Internal dependencies + */ +import { loadScenarios, runAgent, checkAssertions } from '../agent.mjs'; + +for ( const scenario of loadScenarios() ) { + if ( ! scenario.assertions ) { + continue; + } + test( scenario.name, async () => { + test.setTimeout( ( ( scenario.timeoutSeconds ?? 900 ) + 60 ) * 1000 ); + + const transcript = runAgent( scenario, { + model: process.env.AI_EVAL_MODEL, + } ); + + for ( const { label, pass, evidence } of checkAssertions( + scenario.assertions, + transcript + ) ) { + expect + .soft( + pass, + `${ label }\n actual:\n ${ evidence + .slice( 0, 20 ) + .join( '\n ' ) }\n transcript: ${ + transcript.artifact + }` + ) + .toBe( true ); + } + } ); +} From 7d6ee6532769f297d9a6ca64eb3cef4053aa7464 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Mon, 27 Jul 2026 16:32:42 -0400 Subject: [PATCH 5/6] Write agent eval specs directly with Playwright's built-in matchers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Following review: delete the JSON scenario files and the custom matcher layer; tests are now hand-written specs using stock expect. The adapter reports repo-relative file paths, so reads assert with exact matches ( expect( transcript.reads ).toContain( 'skills/testing/SKILL.md' ) ), directory exclusions are a filter, and ordering is a comparison of first-event indexes (Infinity when absent). Standard timeouts: 10-minute agent sessions in agent.mjs, 12-minute test ceiling in the config — the session timeout is the real backstop since spawnSync blocks the worker. Verified: negative control passes live through the final API; lint and formatting clean. Co-Authored-By: Claude Fable 5 --- docs/contributors/code/agents-and-skills.md | 4 +- test/ai-development/README.md | 62 +++++ test/ai-development/agent.mjs | 242 ++++++++---------- test/ai-development/playwright.config.mjs | 8 +- test/ai-development/scenarios/README.md | 43 ---- .../negative-control-trivial-task.json | 20 -- .../scenarios/testing-run-e2e.json | 40 --- .../scenarios/testing-write-e2e.json | 30 --- .../specs/negative-control.spec.mjs | 42 +++ test/ai-development/specs/scenarios.spec.mjs | 48 ---- test/ai-development/specs/testing.spec.mjs | 85 ++++++ 11 files changed, 303 insertions(+), 321 deletions(-) create mode 100644 test/ai-development/README.md delete mode 100644 test/ai-development/scenarios/README.md delete mode 100644 test/ai-development/scenarios/negative-control-trivial-task.json delete mode 100644 test/ai-development/scenarios/testing-run-e2e.json delete mode 100644 test/ai-development/scenarios/testing-write-e2e.json create mode 100644 test/ai-development/specs/negative-control.spec.mjs delete mode 100644 test/ai-development/specs/scenarios.spec.mjs create mode 100644 test/ai-development/specs/testing.spec.mjs diff --git a/docs/contributors/code/agents-and-skills.md b/docs/contributors/code/agents-and-skills.md index ddefe1bc95da73..54b74f6f5a05f3 100644 --- a/docs/contributors/code/agents-and-skills.md +++ b/docs/contributors/code/agents-and-skills.md @@ -74,7 +74,7 @@ Walking through how the live testing skill applies these conventions: 1. Confirm the public docs can't cover it — improve them first if they can. 2. Create `skills//SKILL.md` following the conventions above. 3. Add a routing entry to the root `AGENTS.md`. -4. Add at least one eval scenario under `test/ai-development/scenarios/` (see [its README](https://github.com/WordPress/gutenberg/blob/trunk/test/ai-development/scenarios/README.md)) describing a task the skill covers and how to verify an agent followed it. -5. Run your scenario and confirm it passes: `npm run test:ai-development -- -g ""`. +4. Add at least one behavioral test under `test/ai-development/specs/` (see [its README](https://github.com/WordPress/gutenberg/blob/trunk/test/ai-development/README.md)) running a task the skill covers and verifying the agent followed it. +5. Run your test and confirm it passes: `npm run test:ai-development -- -g ""`. 6. Run the full suite to confirm nothing else regressed — including the negative control: `npm run test:ai-development`. 7. Once everything passes, run `npm run lint:md:docs`. diff --git a/test/ai-development/README.md b/test/ai-development/README.md new file mode 100644 index 00000000000000..e957be4c507731 --- /dev/null +++ b/test/ai-development/README.md @@ -0,0 +1,62 @@ +# AI development tests + +These tests verify that an AI agent, given a task prompt, **consults the right guidance**: reads the skill files and docs it should, doesn't read the ones it shouldn't, in the right order, and reaches for the right kind of command. The evidence is the agent's own transcript. + +Playwright is used purely as a test runner — no browsers are involved. Each test spawns a real, headless agent session, which costs minutes and real tokens, so the tests run only through this explicit command (never in CI or default test sweeps): + +```bash +# All tests: +npm run test:ai-development + +# One test, by name: +npm run test:ai-development -- -g "trivial task" + +# Repeat for confidence (agent compliance is probabilistic): +npm run test:ai-development -- --repeat-each=3 + +# Against a specific model (passed through to the agent CLI): +AI_EVAL_MODEL=haiku npm run test:ai-development +``` + +Notes: + +- No environment is required: the point is what the agent *consults and attempts*, not whether Gutenberg's tests execute. Agents run without write permissions, so a denied edit still shows up in the transcript as the attempt the matchers need — and your checkout is never modified. +- Treat a single-run failure as a smoke signal, not a verdict — re-run with `--repeat-each=3` before calling it a regression. +- Results are colored by your personal agent configuration (`~/.claude`, `CLAUDE.local.md`, memory). +- Each run's raw transcript is saved under `artifacts/`; failure messages include the exact path. + +## Writing a test + +One spec file per skill under `specs/` (plus `negative-control.spec.mjs`, which guards against agents over-reading guidance on trivial tasks). A test runs a prompt and asserts over the transcript with Playwright's built-in matchers — use `expect.soft()` so one failed check doesn't hide the rest: + +```js +import { test, expect } from '@playwright/test'; +import { runAgent } from '../agent.mjs'; + +test( 'describes the behavior under test', async () => { + const transcript = runAgent( 'The task prompt', { name: 'artifact-slug' } ); + + // Consulted the right guidance, not the wrong guidance. Paths inside the + // repository are reported repo-relative, so exact matches work. + expect.soft( transcript.reads ).toContain( 'skills/testing/SKILL.md' ); + expect.soft( transcript.reads ).not.toContain( 'skills/testing/references/php.md' ); + + // Whole directories can be excluded with a filter — a failure lists the + // offending files. + expect.soft( transcript.reads.filter( ( r ) => r.startsWith( 'skills/' ) ) ).toEqual( [] ); + + // In the right order (indexes are Infinity when the event never happened, + // so "required before optional bound" is a single comparison). + expect + .soft( transcript.firstRead( 'docs/contributors/code/e2e/README.md' ) ) + .toBeLessThan( transcript.firstWrite() ); + + // Reached for the right kind of command. + expect.soft( transcript.commandsMatching( 'test:e2e' ).join( '\n' ) ).toContain( '.spec.js' ); + expect.soft( transcript.commandsMatching( 'test:e2e' ).join( '\n' ) ).not.toContain( '--headed' ); +} ); +``` + +The transcript exposes: `reads`, `writes`, `commands` (string arrays, in order — file paths inside the repository are repo-relative), `result` (the agent's final message), `artifact` (the saved transcript path), `firstRead( s )` / `firstWrite( s )` / `firstCommand( s )` (event index of the first substring match, `Infinity` if none), and `commandsMatching( s )`. + +Supporting another agent CLI means adding one adapter entry in `agent.mjs` that invokes it headless and normalizes its transcript into read/write/command events. diff --git a/test/ai-development/agent.mjs b/test/ai-development/agent.mjs index 957f527de589da..533bc46125cb6c 100644 --- a/test/ai-development/agent.mjs +++ b/test/ai-development/agent.mjs @@ -1,7 +1,7 @@ /** - * Agent-session helpers for the AI development tests. + * Agent-session helper for the AI development tests. * - * Runs a scenario's task prompt through a real agent CLI session and + * Runs a task prompt through a real, headless agent CLI session and * normalizes the transcript into ordered read/write/command events so tests * can verify the agent consulted the right guidance. The agent is granted no * write permissions — an attempted (denied) edit is still evidence, and the @@ -18,28 +18,28 @@ import { fileURLToPath } from 'node:url'; import { spawnSync } from 'node:child_process'; const here = path.dirname( fileURLToPath( import.meta.url ) ); -const scenariosDir = path.join( here, 'scenarios' ); +const repoRoot = path.resolve( here, '..', '..' ); const artifactsDir = path.join( here, 'artifacts' ); -export function loadScenarios() { - return fs - .readdirSync( scenariosDir ) - .filter( ( f ) => f.endsWith( '.json' ) ) - .map( ( f ) => ( { - slug: f.replace( /\.json$/, '' ), - ...JSON.parse( - fs.readFileSync( path.join( scenariosDir, f ), 'utf8' ) - ), - } ) ); +/** + * Paths inside the repository are reported repo-relative so tests can assert + * with exact matches ( `expect( transcript.reads ).toContain( 'skills/…' )` ); + * paths outside the repository stay absolute. + * + * @param {string} filePath + */ +function relativize( filePath ) { + const relative = path.relative( repoRoot, filePath ); + return relative.startsWith( '..' ) ? filePath : relative; } const ADAPTERS = { claude: { command: 'claude', - buildArgs( scenario, model ) { + buildArgs( query, model ) { const args = [ '-p', - scenario.query, + query, '--verbose', '--output-format', 'stream-json', @@ -67,7 +67,7 @@ const ADAPTERS = { if ( block.name === 'Read' && input.file_path ) { events.push( { kind: 'read', - value: input.file_path, + value: relativize( input.file_path ), } ); } else if ( [ 'Edit', 'Write', 'NotebookEdit' ].includes( @@ -77,7 +77,7 @@ const ADAPTERS = { ) { events.push( { kind: 'write', - value: input.file_path, + value: relativize( input.file_path ), } ); } else if ( block.name === 'Bash' && input.command ) { events.push( { @@ -95,7 +95,84 @@ const ADAPTERS = { }, }; -export function runAgent( scenario, { agent = 'claude', model } = {} ) { +/** + * A parsed agent transcript with the accessors tests assert against. + */ +class Transcript { + constructor( { events, result, artifact } ) { + this.events = events; + this.result = result; + this.artifact = artifact; + this.reads = events + .filter( ( e ) => e.kind === 'read' ) + .map( ( e ) => e.value ); + this.writes = events + .filter( ( e ) => e.kind === 'write' ) + .map( ( e ) => e.value ); + this.commands = events + .filter( ( e ) => e.kind === 'command' ) + .map( ( e ) => e.value ); + } + + /** + * Event index of the first `kind` event whose value contains `needle`, or + * Infinity when it never happened — so ordering comparisons read + * naturally: absent bounds pass, absent requirements fail. + * + * @param {string} kind read | write | command. + * @param {?string} needle Substring to match; undefined matches any event + * of that kind. + */ + firstIndex( kind, needle ) { + const i = this.events.findIndex( + ( e ) => + e.kind === kind && + ( needle === undefined || e.value.includes( needle ) ) + ); + return i === -1 ? Infinity : i; + } + + firstRead( needle ) { + return this.firstIndex( 'read', needle ); + } + + firstWrite( needle ) { + return this.firstIndex( 'write', needle ); + } + + firstCommand( needle ) { + return this.firstIndex( 'command', needle ); + } + + commandsMatching( needle ) { + return this.commands.filter( ( c ) => c.includes( needle ) ); + } +} + +/** + * Runs a task prompt through an agent session and returns its Transcript. + * + * @param {string} query The task prompt. + * @param {Object} options + * @param {string} options.name Slug for the saved transcript file. + * @param {string} options.agent Adapter name (default: claude). + * @param {string} options.model Model passed through to the agent + * CLI; defaults to AI_EVAL_MODEL. + * @param {number} options.timeoutSeconds Kill the session after this long. + * The default must stay below the test + * timeout in playwright.config.mjs so a + * hung session fails with evidence + * rather than a worker kill. + */ +export function runAgent( + query, + { + name = 'run', + agent = 'claude', + model = process.env.AI_EVAL_MODEL, + timeoutSeconds = 10 * 60, + } = {} +) { const adapter = ADAPTERS[ agent ]; if ( ! adapter ) { throw new Error( @@ -104,20 +181,16 @@ export function runAgent( scenario, { agent = 'claude', model } = {} ) { ).join( ', ' ) }` ); } - const out = spawnSync( - adapter.command, - adapter.buildArgs( scenario, model ), - { - cwd: path.resolve( here, '..', '..' ), - encoding: 'utf8', - timeout: ( scenario.timeoutSeconds ?? 900 ) * 1000, - maxBuffer: 256 * 1024 * 1024, - } - ); + const out = spawnSync( adapter.command, adapter.buildArgs( query, model ), { + cwd: repoRoot, + encoding: 'utf8', + timeout: timeoutSeconds * 1000, + maxBuffer: 256 * 1024 * 1024, + } ); fs.mkdirSync( artifactsDir, { recursive: true } ); const artifact = path.join( artifactsDir, - `${ scenario.slug }-${ Date.now() }.jsonl` + `${ name }-${ Date.now() }.jsonl` ); fs.writeFileSync( artifact, out.stdout ?? '' ); if ( out.error ) { @@ -125,111 +198,8 @@ export function runAgent( scenario, { agent = 'claude', model } = {} ) { `${ adapter.command } failed to run: ${ out.error.message }` ); } - return { ...adapter.parse( out.stdout ?? '' ), artifact }; -} - -function firstIndex( events, kind, needle ) { - return events.findIndex( - ( e ) => e.kind === kind && e.value.includes( needle ) - ); -} - -/** - * Evaluates a scenario's declarative assertions against a normalized - * transcript. Returns outcomes: { label, pass, evidence }. - * - * @param {Object} assertions The scenario's `assertions` block. - * @param {Object} transcript Normalized transcript. - * @param {Array} transcript.events Ordered read/write/command events. - * @param {?string} transcript.result The agent's final message. - */ -export function checkAssertions( assertions, { events, result } ) { - const outcomes = []; - const record = ( label, pass, evidence = [] ) => - outcomes.push( { label, pass, evidence } ); - const reads = events - .filter( ( e ) => e.kind === 'read' ) - .map( ( e ) => e.value ); - const commands = events - .filter( ( e ) => e.kind === 'command' ) - .map( ( e ) => e.value ); - const timeline = events.map( - ( e ) => `${ e.kind }: ${ e.value.slice( 0, 100 ) }` - ); - - for ( const needle of assertions.readsInclude ?? [] ) { - record( - `reads include ${ needle }`, - reads.some( ( r ) => r.includes( needle ) ), - reads - ); - } - for ( const needle of assertions.readsExclude ?? [] ) { - record( - `reads exclude ${ needle }`, - ! reads.some( ( r ) => r.includes( needle ) ), - reads - ); - } - for ( const { read, command } of assertions.readsBeforeCommand ?? [] ) { - const readIdx = firstIndex( events, 'read', read ); - const cmdIdx = firstIndex( events, 'command', command ); - record( - `read ${ read } before command '${ command }'`, - readIdx !== -1 && ( cmdIdx === -1 || readIdx < cmdIdx ), - timeline - ); - } - for ( const { read } of assertions.readsBeforeWrite ?? [] ) { - const readIdx = firstIndex( events, 'read', read ); - const writeIdx = events.findIndex( ( e ) => e.kind === 'write' ); - record( - `read ${ read } before first write attempt`, - readIdx !== -1 && ( writeIdx === -1 || readIdx < writeIdx ), - timeline - ); - } - for ( const [ before, after ] of assertions.commandOrder ?? [] ) { - const afterIdx = firstIndex( events, 'command', after ); - const beforeIdx = firstIndex( events, 'command', before ); - record( - `command '${ before }' before '${ after }'`, - afterIdx === -1 || ( beforeIdx !== -1 && beforeIdx < afterIdx ), - commands - ); - } - for ( const rule of assertions.commandRules ?? [] ) { - const matching = commands.filter( ( c ) => - c.includes( rule.matching ) - ); - record( - `a command matching '${ rule.matching }' occurred`, - matching.length > 0, - commands - ); - for ( const command of matching ) { - if ( rule.mustContain ) { - record( - `'${ rule.matching }' command contains '${ rule.mustContain }'`, - command.includes( rule.mustContain ), - [ command ] - ); - } - for ( const banned of rule.mustNotContain ?? [] ) { - record( - `'${ rule.matching }' command avoids '${ banned }'`, - ! command.includes( banned ), - [ command ] - ); - } - } - } - for ( const needle of assertions.resultIncludes ?? [] ) { - record( - `result includes '${ needle }'`, - ( result ?? '' ).includes( needle ), - [ ( result ?? '' ).slice( 0, 300 ) ] - ); - } - return outcomes; + return new Transcript( { + ...adapter.parse( out.stdout ?? '' ), + artifact, + } ); } diff --git a/test/ai-development/playwright.config.mjs b/test/ai-development/playwright.config.mjs index a1dae42c5fd6bc..e9f1bf0a605c58 100644 --- a/test/ai-development/playwright.config.mjs +++ b/test/ai-development/playwright.config.mjs @@ -16,6 +16,10 @@ export default defineConfig( { workers: 1, fullyParallel: false, reporter: 'list', - // Individual tests set their own timeout from the scenario file. - timeout: 30 * 60 * 1000, + // Safety net only. Tests run the agent with spawnSync, which blocks the + // worker — Playwright can't interrupt a session in progress, so a hung + // session is actually killed by the session timeout in agent.mjs. Keep + // this value larger than that one: the session then dies first and the + // test fails with a saved transcript instead of a torn-down worker. + timeout: 12 * 60 * 1000, } ); diff --git a/test/ai-development/scenarios/README.md b/test/ai-development/scenarios/README.md deleted file mode 100644 index 4a53e98e064b67..00000000000000 --- a/test/ai-development/scenarios/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# Eval scenarios - -Scenarios verify that an agent, given a task prompt, **consults the right guidance**: reads the skill files and docs it should, doesn't read the ones it shouldn't, in the right order, and reaches for the right kind of command. The evidence is the agent's own transcript. - -Each `.json` defines a human-readable spec — `name`, `skills`, `query`, `expected_behavior`, `success_criteria` — plus a machine-checkable `assertions` block. When adding a skill, add at least one scenario for it. - -## Running - -The tests use Playwright purely as a test runner — no browsers are involved. Each test spawns a real, headless agent session, which costs minutes and real tokens per scenario, so they run only through this explicit command (never in CI or default test sweeps): - -```bash -# All scenarios: -npm run test:ai-development - -# One scenario, by name: -npm run test:ai-development -- -g "Negative control" - -# Repeat for confidence (agent compliance is probabilistic): -npm run test:ai-development -- --repeat-each=3 - -# Against a specific model (passed through to the agent CLI): -AI_EVAL_MODEL=haiku npm run test:ai-development -``` - -Notes: - -- No environment is required: the point is what the agent *consults and attempts*, not whether Gutenberg's tests execute. Agents run without write permissions, so a denied edit still shows up in the transcript as the attempt the assertions need — and your checkout is never modified. -- Treat a single-run failure as a smoke signal, not a verdict — re-run with `--repeat-each=3` before calling it a regression. -- Results are colored by your personal agent configuration (`~/.claude`, `CLAUDE.local.md`, memory). -- Each run's raw transcript is saved under `test/ai-development/artifacts/` (failure messages include the exact path). -- Supporting another agent CLI means adding one adapter entry in `test/ai-development/agent.mjs` that invokes it headless and normalizes its transcript into read/write/command events — the assertions are agent-agnostic. - -## Assertion vocabulary - -| Key | Checks | -| --- | --- | -| `readsInclude` | Each path substring matches some file the agent read | -| `readsExclude` | No read matches the path substring | -| `readsBeforeCommand` | The read occurs before the first shell command matching `command` | -| `readsBeforeWrite` | The read occurs before the agent's first attempted file edit | -| `commandOrder` | `[before, after]`: if `after` ever runs, `before` ran first | -| `commandRules` | A command matching `matching` occurred, containing / avoiding substrings | -| `resultIncludes` | The agent's final message contains the substring | diff --git a/test/ai-development/scenarios/negative-control-trivial-task.json b/test/ai-development/scenarios/negative-control-trivial-task.json deleted file mode 100644 index 0641ecc70ad391..00000000000000 --- a/test/ai-development/scenarios/negative-control-trivial-task.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "Negative control: trivial task triggers no skills or docs", - "skills": [], - "query": "If the word 'seperate' (a misspelling of 'separate') appears anywhere in CONTRIBUTING.md, fix it; if it does not appear, just say so.", - "expected_behavior": [ - "Step 1: Search CONTRIBUTING.md for the misspelling", - "Step 2: Report the result (or make the one-word fix)" - ], - "success_criteria": [ - "No skill files or contributor guides are read for a task that does not need them — the progressive-discovery router must not cause over-reading" - ], - "timeoutSeconds": 600, - "assertions": { - "readsExclude": [ - "skills/", - "docs/contributors/code/e2e/", - "docs/contributors/code/coding-guidelines.md" - ] - } -} diff --git a/test/ai-development/scenarios/testing-run-e2e.json b/test/ai-development/scenarios/testing-run-e2e.json deleted file mode 100644 index e588923e5a7c07..00000000000000 --- a/test/ai-development/scenarios/testing-run-e2e.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "Run e2e tests for a specific block", - "skills": [ "testing" ], - "query": "Run the e2e tests for the paragraph block", - "expected_behavior": [ - "Step 1: Read skills/testing/SKILL.md, then skills/testing/references/e2e.md (not the Jest or PHP references)", - "Step 2: Check npm run wp-env-test status before any wp-env-test start", - "Step 3: Run the paragraph spec scoped and headless" - ], - "success_criteria": [ - "Discovery chain root AGENTS.md → SKILL.md → e2e reference is followed before the first test command", - "Test run is scoped to a spec path and headless, with the environment checked first" - ], - "timeoutSeconds": 1800, - "assertions": { - "readsInclude": [ - "skills/testing/SKILL.md", - "skills/testing/references/e2e.md" - ], - "readsExclude": [ - "skills/testing/references/php.md", - "skills/testing/references/jest.md" - ], - "readsBeforeCommand": [ - { "read": "skills/testing/SKILL.md", "command": "test:e2e" }, - { - "read": "skills/testing/references/e2e.md", - "command": "test:e2e" - } - ], - "commandOrder": [ [ "wp-env-test status", "wp-env-test start" ] ], - "commandRules": [ - { - "matching": "test:e2e", - "mustContain": ".spec.js", - "mustNotContain": [ "--headed", "--ui", "--debug" ] - } - ] - } -} diff --git a/test/ai-development/scenarios/testing-write-e2e.json b/test/ai-development/scenarios/testing-write-e2e.json deleted file mode 100644 index 5c399a82be63f1..00000000000000 --- a/test/ai-development/scenarios/testing-write-e2e.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "Write an e2e test for a specific behavior", - "skills": [ "testing" ], - "query": "Add an e2e test for the paragraph block that checks that the `&` key is not output as `&` in the editor", - "expected_behavior": [ - "Step 1: Read skills/testing/SKILL.md and skills/testing/references/e2e.md", - "Step 2: Read the End-to-End Testing guide (docs/contributors/code/e2e/README.md) before writing any test body", - "Step 3: Surface the proposed test names for review (in the summary when running unattended)", - "Step 4: Extend the existing paragraph spec rather than creating a parallel file" - ], - "success_criteria": [ - "The right guidance is consulted: both testing skill files and the e2e authoring guide, the guide before the first attempted edit", - "The unrelated references (Jest, PHP) are not read" - ], - "timeoutSeconds": 900, - "assertions": { - "readsInclude": [ - "skills/testing/SKILL.md", - "skills/testing/references/e2e.md", - "docs/contributors/code/e2e/README.md" - ], - "readsExclude": [ - "skills/testing/references/php.md", - "skills/testing/references/jest.md" - ], - "readsBeforeWrite": [ - { "read": "docs/contributors/code/e2e/README.md" } - ] - } -} diff --git a/test/ai-development/specs/negative-control.spec.mjs b/test/ai-development/specs/negative-control.spec.mjs new file mode 100644 index 00000000000000..c34d2d5c3f2eb8 --- /dev/null +++ b/test/ai-development/specs/negative-control.spec.mjs @@ -0,0 +1,42 @@ +/** + * Negative control: a trivial task must not trigger skill or doc reads. The + * progressive-discovery routing in AGENTS.md is only acceptable if agents + * apply it selectively — this test catches over-reading regressions when the + * routing wording changes. + * + * Spawns a real agent session. Run only via `npm run test:ai-development`. + */ + +/** + * External dependencies + */ +import { test, expect } from '@playwright/test'; + +/** + * Internal dependencies + */ +import { runAgent } from '../agent.mjs'; + +test( 'a trivial task reads no skills or contributor guides', async () => { + const transcript = runAgent( + "If the word 'seperate' (a misspelling of 'separate') appears anywhere in CONTRIBUTING.md, fix it; if it does not appear, just say so.", + { name: 'negative-control' } + ); + + // Expect no reads from these entire directories… + expect + .soft( transcript.reads.filter( ( r ) => r.startsWith( 'skills/' ) ) ) + .toEqual( [] ); + expect + .soft( + transcript.reads.filter( ( r ) => + r.startsWith( 'docs/contributors/code/e2e/' ) + ) + ) + .toEqual( [] ); + + // …and none of this specific guide. + expect + .soft( transcript.reads ) + .not.toContain( 'docs/contributors/code/coding-guidelines.md' ); +} ); diff --git a/test/ai-development/specs/scenarios.spec.mjs b/test/ai-development/specs/scenarios.spec.mjs deleted file mode 100644 index 13f9fcf7f11aed..00000000000000 --- a/test/ai-development/specs/scenarios.spec.mjs +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Verifies that an agent, given each scenario's task prompt, consulted the - * right guidance: read the skill files and docs it should, didn't read the - * ones it shouldn't, in the right order, and reached for the right kind of - * command. Evidence comes from the agent's own transcript. - * - * Every test spawns a real agent session (minutes and real tokens). Run only - * via `npm run test:ai-development` — see ../scenarios/README.md. - */ - -/** - * External dependencies - */ -import { test, expect } from '@playwright/test'; - -/** - * Internal dependencies - */ -import { loadScenarios, runAgent, checkAssertions } from '../agent.mjs'; - -for ( const scenario of loadScenarios() ) { - if ( ! scenario.assertions ) { - continue; - } - test( scenario.name, async () => { - test.setTimeout( ( ( scenario.timeoutSeconds ?? 900 ) + 60 ) * 1000 ); - - const transcript = runAgent( scenario, { - model: process.env.AI_EVAL_MODEL, - } ); - - for ( const { label, pass, evidence } of checkAssertions( - scenario.assertions, - transcript - ) ) { - expect - .soft( - pass, - `${ label }\n actual:\n ${ evidence - .slice( 0, 20 ) - .join( '\n ' ) }\n transcript: ${ - transcript.artifact - }` - ) - .toBe( true ); - } - } ); -} diff --git a/test/ai-development/specs/testing.spec.mjs b/test/ai-development/specs/testing.spec.mjs new file mode 100644 index 00000000000000..6ceb1e6ceba84c --- /dev/null +++ b/test/ai-development/specs/testing.spec.mjs @@ -0,0 +1,85 @@ +/** + * Verifies agents follow the `skills/testing` skill: read the right guidance, + * skip the unrelated references, and reach for scoped, headless commands. + * + * Every test spawns a real agent session (minutes and real tokens). Run only + * via `npm run test:ai-development` — see ../README.md. + */ + +/** + * External dependencies + */ +import { test, expect } from '@playwright/test'; + +/** + * Internal dependencies + */ +import { runAgent } from '../agent.mjs'; + +test.describe( 'testing skill', () => { + test( 'running e2e tests for a block follows the skill', async () => { + const transcript = runAgent( + 'Run the e2e tests for the paragraph block', + { name: 'testing-run-e2e' } + ); + const e2eCommands = transcript + .commandsMatching( 'test:e2e' ) + .join( '\n' ); + + // Discovery chain: the skill and its e2e reference, not the others. + expect.soft( transcript.reads ).toContain( 'skills/testing/SKILL.md' ); + expect + .soft( transcript.reads ) + .toContain( 'skills/testing/references/e2e.md' ); + expect + .soft( transcript.reads ) + .not.toContain( 'skills/testing/references/php.md' ); + expect + .soft( transcript.reads ) + .not.toContain( 'skills/testing/references/jest.md' ); + expect + .soft( transcript.firstRead( 'skills/testing/SKILL.md' ) ) + .toBeLessThan( transcript.firstCommand( 'test:e2e' ) ); + expect + .soft( transcript.firstRead( 'skills/testing/references/e2e.md' ) ) + .toBeLessThan( transcript.firstCommand( 'test:e2e' ) ); + + // Environment checked before started; run scoped and headless. + expect + .soft( transcript.firstCommand( 'wp-env-test status' ) ) + .toBeLessThan( transcript.firstCommand( 'wp-env-test start' ) ); + expect.soft( e2eCommands ).toContain( '.spec.js' ); + expect.soft( e2eCommands ).not.toContain( '--headed' ); + expect.soft( e2eCommands ).not.toContain( '--ui' ); + expect.soft( e2eCommands ).not.toContain( '--debug' ); + } ); + + test( 'writing an e2e test reads the authoring guide before editing', async () => { + const transcript = runAgent( + 'Add an e2e test for the paragraph block that checks that the `&` key is not output as `&` in the editor', + { name: 'testing-write-e2e' } + ); + + // The skill chain plus the canonical authoring guide it points to. + expect.soft( transcript.reads ).toContain( 'skills/testing/SKILL.md' ); + expect + .soft( transcript.reads ) + .toContain( 'skills/testing/references/e2e.md' ); + expect + .soft( transcript.reads ) + .toContain( 'docs/contributors/code/e2e/README.md' ); + expect + .soft( transcript.reads ) + .not.toContain( 'skills/testing/references/php.md' ); + expect + .soft( transcript.reads ) + .not.toContain( 'skills/testing/references/jest.md' ); + + // The guide must be consulted before the first attempted spec edit. + expect + .soft( + transcript.firstRead( 'docs/contributors/code/e2e/README.md' ) + ) + .toBeLessThan( transcript.firstWrite() ); + } ); +} ); From ffe1a3ebcf23058fa32790088cebb7c97e87d656 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Mon, 27 Jul 2026 17:07:44 -0400 Subject: [PATCH 6/6] Add Codex support to AI development tests --- test/ai-development/README.md | 32 ++- test/ai-development/agent.mjs | 304 ++++++++++++++++++--- test/ai-development/specs/testing.spec.mjs | 22 +- 3 files changed, 299 insertions(+), 59 deletions(-) diff --git a/test/ai-development/README.md b/test/ai-development/README.md index e957be4c507731..1baf6ca4651e66 100644 --- a/test/ai-development/README.md +++ b/test/ai-development/README.md @@ -2,7 +2,7 @@ These tests verify that an AI agent, given a task prompt, **consults the right guidance**: reads the skill files and docs it should, doesn't read the ones it shouldn't, in the right order, and reaches for the right kind of command. The evidence is the agent's own transcript. -Playwright is used purely as a test runner — no browsers are involved. Each test spawns a real, headless agent session, which costs minutes and real tokens, so the tests run only through this explicit command (never in CI or default test sweeps): +Playwright is used purely as a test runner — no browsers are involved. Each test spawns a real, headless agent session, which costs minutes and real tokens, so the tests run only through this explicit command (never in CI or default test sweeps). ```bash # All tests: @@ -16,13 +16,21 @@ npm run test:ai-development -- --repeat-each=3 # Against a specific model (passed through to the agent CLI): AI_EVAL_MODEL=haiku npm run test:ai-development + +# Against Codex: +AI_EVAL_AGENT=codex npm run test:ai-development + +# Against a specific Codex model: +AI_EVAL_AGENT=codex AI_EVAL_MODEL=gpt-5.4 npm run test:ai-development ``` Notes: -- No environment is required: the point is what the agent *consults and attempts*, not whether Gutenberg's tests execute. Agents run without write permissions, so a denied edit still shows up in the transcript as the attempt the matchers need — and your checkout is never modified. +- No WordPress environment is required: the point is what the agent *consults and attempts*, not whether Gutenberg's tests execute. Agents run without write permissions, so a denied edit still shows up in the transcript as the attempt the matchers need — and your checkout is never modified. - Treat a single-run failure as a smoke signal, not a verdict — re-run with `--repeat-each=3` before calling it a regression. -- Results are colored by your personal agent configuration (`~/.claude`, `CLAUDE.local.md`, memory). +- The default agent is Claude. Set `AI_EVAL_AGENT=codex` to use Codex instead. +- Model names are provider-specific. `AI_EVAL_MODEL` is passed directly to the selected agent. +- Results are colored by your personal agent configuration (for example `~/.claude`, `~/.codex`, local instruction files, and memory). - Each run's raw transcript is saved under `artifacts/`; failure messages include the exact path. ## Writing a test @@ -36,9 +44,9 @@ import { runAgent } from '../agent.mjs'; test( 'describes the behavior under test', async () => { const transcript = runAgent( 'The task prompt', { name: 'artifact-slug' } ); - // Consulted the right guidance, not the wrong guidance. Paths inside the - // repository are reported repo-relative, so exact matches work. - expect.soft( transcript.reads ).toContain( 'skills/testing/SKILL.md' ); + // Consulted the right guidance, not the wrong guidance. `consulted()` + // accepts exact repo-relative paths across provider transcript formats. + expect.soft( transcript.consulted( 'skills/testing/SKILL.md' ) ).toBe( true ); expect.soft( transcript.reads ).not.toContain( 'skills/testing/references/php.md' ); // Whole directories can be excluded with a filter — a failure lists the @@ -57,6 +65,14 @@ test( 'describes the behavior under test', async () => { } ); ``` -The transcript exposes: `reads`, `writes`, `commands` (string arrays, in order — file paths inside the repository are repo-relative), `result` (the agent's final message), `artifact` (the saved transcript path), `firstRead( s )` / `firstWrite( s )` / `firstCommand( s )` (event index of the first substring match, `Infinity` if none), and `commandsMatching( s )`. +The transcript exposes: + +- `evidence`: ordered normalized evidence records. File evidence includes its operation, outcome, source, and confidence, preserving whether an access was reported exactly by the provider or inferred from a shell command. +- `reads`, `writes`, and `commands`: convenient string arrays in evidence order. File paths inside the repository are repo-relative. +- `consulted( path )`, `attemptedWrite( path )`, and `ranCommandMatching( command )`: intent-focused checks that work across provider transcript formats. +- `firstRead( s )`, `firstWrite( s )`, and `firstCommand( s )`: evidence index of the first substring match, or `Infinity` if absent. +- `commandsMatching( s )`: all matching commands. +- `result`: the agent's final message. +- `artifact`: the saved raw transcript path. -Supporting another agent CLI means adding one adapter entry in `agent.mjs` that invokes it headless and normalizes its transcript into read/write/command events. +Supporting another agent CLI means adding one adapter entry in `agent.mjs` that invokes it headless and normalizes its transcript into evidence. diff --git a/test/ai-development/agent.mjs b/test/ai-development/agent.mjs index 533bc46125cb6c..83e41fdd957cc2 100644 --- a/test/ai-development/agent.mjs +++ b/test/ai-development/agent.mjs @@ -2,14 +2,15 @@ * Agent-session helper for the AI development tests. * * Runs a task prompt through a real, headless agent CLI session and - * normalizes the transcript into ordered read/write/command events so tests - * can verify the agent consulted the right guidance. The agent is granted no - * write permissions — an attempted (denied) edit is still evidence, and the - * checkout is never modified. No running WordPress environment is required. + * normalizes the transcript into ordered evidence so tests can verify the + * agent consulted the right guidance. The agent is granted no write + * permissions — an attempted (denied) edit is still evidence, and the checkout + * is never modified. No running WordPress environment is required. * * Supporting another agent CLI means adding one ADAPTERS entry that invokes - * it headless and normalizes its transcript into - * { events: [ { kind: read|write|command, value } ], result }. + * it headless and normalizes its transcript into { evidence, result, failure }. + * Evidence records what was observed and whether it came from an explicit + * provider event or was inferred from a shell command. */ import fs from 'node:fs'; @@ -29,8 +30,83 @@ const artifactsDir = path.join( here, 'artifacts' ); * @param {string} filePath */ function relativize( filePath ) { - const relative = path.relative( repoRoot, filePath ); - return relative.startsWith( '..' ) ? filePath : relative; + const absolute = path.isAbsolute( filePath ) + ? filePath + : path.resolve( repoRoot, filePath ); + const relative = path.relative( repoRoot, absolute ); + return relative.startsWith( '..' ) ? absolute : relative; +} + +function fileEvidence( + operation, + filePath, + { outcome = 'attempted', source = 'native_tool', confidence = 'exact' } = {} +) { + return { + type: 'file_access', + operation, + path: relativize( filePath ), + outcome, + source, + confidence, + }; +} + +function commandEvidence( command, outcome = 'attempted' ) { + return { + type: 'command', + command, + outcome, + source: 'native_tool', + confidence: 'exact', + }; +} + +/** + * Codex exposes shell commands rather than dedicated read events. Infer reads + * only for commands whose purpose includes displaying or searching file + * contents, and only for path-like arguments that resolve to existing files. + * + * @param {string} command Shell command reported by Codex. + * @return {string[]} Repo-relative or absolute paths read by the command. + */ +function inferReadPaths( command ) { + if ( + ! /(?:^|["';&|(\s])(?:cat|sed|head|tail|less|more|rg|grep|awk|wc|nl)(?:\s|$)/.test( + command + ) + ) { + return []; + } + + const pathLike = /(?:(?:\/|\.{0,2}\/)?(?:[\w@.+-]+\/)+[\w@.+-]+)/g; + const matches = command.match( pathLike ) ?? []; + const paths = new Set(); + const shellExecutables = new Set( [ + '/bin/bash', + '/bin/sh', + '/bin/zsh', + '/usr/bin/env', + ] ); + + for ( let candidate of matches ) { + candidate = candidate.replace( /[,:]\d+(?::\d+)?$/, '' ); + if ( shellExecutables.has( candidate ) ) { + continue; + } + const absolute = path.isAbsolute( candidate ) + ? candidate + : path.resolve( repoRoot, candidate ); + try { + if ( fs.statSync( absolute ).isFile() ) { + paths.add( relativize( absolute ) ); + } + } catch { + // Shell arguments that merely look like paths are not read evidence. + } + } + + return [ ...paths ]; } const ADAPTERS = { @@ -50,7 +126,7 @@ const ADAPTERS = { return args; }, parse( raw ) { - const events = []; + const evidence = []; let result = null; for ( const line of raw.split( '\n' ) ) { let obj; @@ -65,57 +141,166 @@ const ADAPTERS = { } const input = block.input ?? {}; if ( block.name === 'Read' && input.file_path ) { - events.push( { - kind: 'read', - value: relativize( input.file_path ), - } ); + evidence.push( + fileEvidence( 'read', input.file_path ) + ); } else if ( [ 'Edit', 'Write', 'NotebookEdit' ].includes( block.name ) && input.file_path ) { - events.push( { - kind: 'write', - value: relativize( input.file_path ), - } ); + evidence.push( + fileEvidence( 'write', input.file_path ) + ); } else if ( block.name === 'Bash' && input.command ) { - events.push( { - kind: 'command', - value: input.command, - } ); + evidence.push( commandEvidence( input.command ) ); } } if ( obj?.type === 'result' ) { result = obj.result ?? ''; } } - return { events, result }; + return { evidence, result, failure: null }; + }, + }, + codex: { + command: 'codex', + buildArgs( query, model ) { + const args = [ + 'exec', + '--json', + '--ephemeral', + '--sandbox', + 'read-only', + ]; + if ( model ) { + args.push( '--model', model ); + } + args.push( query ); + return args; + }, + parse( raw ) { + const evidence = []; + let result = null; + let failure = null; + for ( const line of raw.split( '\n' ) ) { + let obj; + try { + obj = JSON.parse( line ); + } catch { + continue; + } + + if ( obj?.type === 'turn.failed' ) { + failure = obj.error?.message ?? 'Codex turn failed'; + } else if ( obj?.type === 'error' ) { + failure = obj.message ?? 'Codex stream failed'; + } + + if ( obj?.type !== 'item.completed' ) { + continue; + } + + const item = obj.item ?? {}; + if ( item.type === 'command_execution' && item.command ) { + const outcome = + item.status === 'completed' ? 'completed' : 'failed'; + for ( const filePath of inferReadPaths( item.command ) ) { + evidence.push( + fileEvidence( 'read', filePath, { + outcome, + source: 'shell_command', + confidence: 'inferred', + } ) + ); + } + evidence.push( commandEvidence( item.command, outcome ) ); + } else if ( item.type === 'file_change' ) { + for ( const change of item.changes ?? [] ) { + if ( change.path ) { + evidence.push( + fileEvidence( 'write', change.path, { + outcome: + item.status === 'completed' + ? 'completed' + : 'failed', + source: 'file_change', + } ) + ); + } + } + } else if ( item.type === 'agent_message' ) { + result = item.text ?? ''; + } + } + return { evidence, result, failure }; }, }, }; +/** + * Parse provider output without running an agent. + * + * @param {string} agent Adapter name. + * @param {string} raw Raw JSONL output. + * @return {Object} Normalized provider output. + */ +function parseAgentOutput( agent, raw ) { + const adapter = ADAPTERS[ agent ]; + if ( ! adapter ) { + throw new Error( + `Unknown agent '${ agent }'. Available: ${ Object.keys( + ADAPTERS + ).join( ', ' ) }` + ); + } + return adapter.parse( raw ); +} + +function resolveAgentName( agent, env = process.env ) { + return agent ?? env.AI_EVAL_AGENT ?? 'claude'; +} + +function describeProcessFailure( out ) { + if ( ! out.error && out.status === 0 && ! out.signal ) { + return null; + } + return ( + out.error?.message ?? + `exit status ${ out.status ?? 'unknown' }${ + out.signal ? ` (signal ${ out.signal })` : '' + }` + ); +} + /** * A parsed agent transcript with the accessors tests assert against. */ class Transcript { - constructor( { events, result, artifact } ) { - this.events = events; + constructor( { evidence, result, artifact } ) { + this.evidence = evidence; this.result = result; this.artifact = artifact; - this.reads = events - .filter( ( e ) => e.kind === 'read' ) - .map( ( e ) => e.value ); - this.writes = events - .filter( ( e ) => e.kind === 'write' ) - .map( ( e ) => e.value ); - this.commands = events - .filter( ( e ) => e.kind === 'command' ) - .map( ( e ) => e.value ); + this.reads = evidence + .filter( + ( item ) => + item.type === 'file_access' && item.operation === 'read' + ) + .map( ( item ) => item.path ); + this.writes = evidence + .filter( + ( item ) => + item.type === 'file_access' && item.operation === 'write' + ) + .map( ( item ) => item.path ); + this.commands = evidence + .filter( ( item ) => item.type === 'command' ) + .map( ( item ) => item.command ); } /** - * Event index of the first `kind` event whose value contains `needle`, or + * Evidence index of the first matching item, or * Infinity when it never happened — so ordering comparisons read * naturally: absent bounds pass, absent requirements fail. * @@ -124,14 +309,31 @@ class Transcript { * of that kind. */ firstIndex( kind, needle ) { - const i = this.events.findIndex( - ( e ) => - e.kind === kind && - ( needle === undefined || e.value.includes( needle ) ) - ); + const i = this.evidence.findIndex( ( item ) => { + const isCommand = kind === 'command' && item.type === 'command'; + const isFileAccess = + item.type === 'file_access' && item.operation === kind; + const value = isCommand ? item.command : item.path; + return ( + ( isCommand || isFileAccess ) && + ( needle === undefined || value.includes( needle ) ) + ); + } ); return i === -1 ? Infinity : i; } + consulted( filePath ) { + return this.reads.includes( filePath ); + } + + attemptedWrite( needle ) { + return this.firstWrite( needle ) !== Infinity; + } + + ranCommandMatching( needle ) { + return this.firstCommand( needle ) !== Infinity; + } + firstRead( needle ) { return this.firstIndex( 'read', needle ); } @@ -168,11 +370,12 @@ export function runAgent( query, { name = 'run', - agent = 'claude', + agent, model = process.env.AI_EVAL_MODEL, timeoutSeconds = 10 * 60, } = {} ) { + agent = resolveAgentName( agent ); const adapter = ADAPTERS[ agent ]; if ( ! adapter ) { throw new Error( @@ -193,13 +396,28 @@ export function runAgent( `${ name }-${ Date.now() }.jsonl` ); fs.writeFileSync( artifact, out.stdout ?? '' ); - if ( out.error ) { + const stderrArtifact = `${ artifact }.stderr`; + if ( out.stderr ) { + fs.writeFileSync( stderrArtifact, out.stderr ); + } + const processFailure = describeProcessFailure( out ); + if ( processFailure ) { + throw new Error( + `${ + adapter.command + } failed to run: ${ processFailure }. Transcript: ${ artifact }${ + out.stderr ? `; stderr: ${ stderrArtifact }` : '' + }` + ); + } + const parsed = parseAgentOutput( agent, out.stdout ?? '' ); + if ( parsed.failure ) { throw new Error( - `${ adapter.command } failed to run: ${ out.error.message }` + `${ adapter.command } session failed: ${ parsed.failure }. Transcript: ${ artifact }` ); } return new Transcript( { - ...adapter.parse( out.stdout ?? '' ), + ...parsed, artifact, } ); } diff --git a/test/ai-development/specs/testing.spec.mjs b/test/ai-development/specs/testing.spec.mjs index 6ceb1e6ceba84c..91db85283a8f06 100644 --- a/test/ai-development/specs/testing.spec.mjs +++ b/test/ai-development/specs/testing.spec.mjs @@ -27,10 +27,12 @@ test.describe( 'testing skill', () => { .join( '\n' ); // Discovery chain: the skill and its e2e reference, not the others. - expect.soft( transcript.reads ).toContain( 'skills/testing/SKILL.md' ); expect - .soft( transcript.reads ) - .toContain( 'skills/testing/references/e2e.md' ); + .soft( transcript.consulted( 'skills/testing/SKILL.md' ) ) + .toBe( true ); + expect + .soft( transcript.consulted( 'skills/testing/references/e2e.md' ) ) + .toBe( true ); expect .soft( transcript.reads ) .not.toContain( 'skills/testing/references/php.md' ); @@ -61,13 +63,17 @@ test.describe( 'testing skill', () => { ); // The skill chain plus the canonical authoring guide it points to. - expect.soft( transcript.reads ).toContain( 'skills/testing/SKILL.md' ); expect - .soft( transcript.reads ) - .toContain( 'skills/testing/references/e2e.md' ); + .soft( transcript.consulted( 'skills/testing/SKILL.md' ) ) + .toBe( true ); expect - .soft( transcript.reads ) - .toContain( 'docs/contributors/code/e2e/README.md' ); + .soft( transcript.consulted( 'skills/testing/references/e2e.md' ) ) + .toBe( true ); + expect + .soft( + transcript.consulted( 'docs/contributors/code/e2e/README.md' ) + ) + .toBe( true ); expect .soft( transcript.reads ) .not.toContain( 'skills/testing/references/php.md' );