diff --git a/docs/contributors/code/agents-and-skills.md b/docs/contributors/code/agents-and-skills.md index 2124a06db39299..54b74f6f5a05f3 100644 --- a/docs/contributors/code/agents-and-skills.md +++ b/docs/contributors/code/agents-and-skills.md @@ -74,4 +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. Run `npm run lint:md:docs`. +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/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/README.md b/test/ai-development/README.md new file mode 100644 index 00000000000000..1baf6ca4651e66 --- /dev/null +++ b/test/ai-development/README.md @@ -0,0 +1,78 @@ +# 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 + +# 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 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. +- 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 + +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. `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 + // 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: + +- `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 evidence. diff --git a/test/ai-development/agent.mjs b/test/ai-development/agent.mjs new file mode 100644 index 00000000000000..83e41fdd957cc2 --- /dev/null +++ b/test/ai-development/agent.mjs @@ -0,0 +1,423 @@ +/** + * 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 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 { 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'; +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 repoRoot = path.resolve( here, '..', '..' ); +const artifactsDir = path.join( here, 'artifacts' ); + +/** + * 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 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 = { + claude: { + command: 'claude', + buildArgs( query, model ) { + const args = [ + '-p', + query, + '--verbose', + '--output-format', + 'stream-json', + ]; + if ( model ) { + args.push( '--model', model ); + } + return args; + }, + parse( raw ) { + const evidence = []; + 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 ) { + evidence.push( + fileEvidence( 'read', input.file_path ) + ); + } else if ( + [ 'Edit', 'Write', 'NotebookEdit' ].includes( + block.name + ) && + input.file_path + ) { + evidence.push( + fileEvidence( 'write', input.file_path ) + ); + } else if ( block.name === 'Bash' && input.command ) { + evidence.push( commandEvidence( input.command ) ); + } + } + if ( obj?.type === 'result' ) { + result = obj.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( { evidence, result, artifact } ) { + this.evidence = evidence; + this.result = result; + this.artifact = artifact; + 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 ); + } + + /** + * Evidence index of the first matching item, 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.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 ); + } + + 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, + model = process.env.AI_EVAL_MODEL, + timeoutSeconds = 10 * 60, + } = {} +) { + agent = resolveAgentName( agent ); + const adapter = ADAPTERS[ agent ]; + if ( ! adapter ) { + throw new Error( + `Unknown agent '${ agent }'. Available: ${ Object.keys( + ADAPTERS + ).join( ', ' ) }` + ); + } + 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, + `${ name }-${ Date.now() }.jsonl` + ); + fs.writeFileSync( artifact, out.stdout ?? '' ); + 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 } session failed: ${ parsed.failure }. Transcript: ${ artifact }` + ); + } + return new Transcript( { + ...parsed, + artifact, + } ); +} diff --git a/test/ai-development/artifacts/.gitignore b/test/ai-development/artifacts/.gitignore new file mode 100644 index 00000000000000..d6b7ef32c8478a --- /dev/null +++ b/test/ai-development/artifacts/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/test/ai-development/playwright.config.mjs b/test/ai-development/playwright.config.mjs new file mode 100644 index 00000000000000..e9f1bf0a605c58 --- /dev/null +++ b/test/ai-development/playwright.config.mjs @@ -0,0 +1,25 @@ +/** + * 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', + // 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/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/testing.spec.mjs b/test/ai-development/specs/testing.spec.mjs new file mode 100644 index 00000000000000..91db85283a8f06 --- /dev/null +++ b/test/ai-development/specs/testing.spec.mjs @@ -0,0 +1,91 @@ +/** + * 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.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' ); + 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.consulted( 'skills/testing/SKILL.md' ) ) + .toBe( true ); + expect + .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' ); + 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() ); + } ); +} );