// Execute the fenced shell walkthroughs, cutout tutorial, quick-start command templates, inline help commands and // literal MCP calls against this checkout. Each call starts in a fresh folder with its inputs. // Run one guide with `node scripts/verify-docs.mjs docs/agent-quick-start.md` or omit it for all. import assert from 'node:assert/strict'; import { execFileSync, spawn, spawnSync } from 'node:child_process'; import { copyFile, cp, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'; import { once } from 'node:events'; import { createInterface } from 'node:readline'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { renderProject } from '../src/core.js'; import { createBundle } from '../src/export.js'; import { BLOB_MASKS } from '../src/autotile.js'; import { readEmbeddedRecipe, readShareLink } from '../src/share.js'; import { decodePNG } from '../src/import.js'; import { HELP_TOPICS, isSchema, SECTIONED } from '../src/help.js'; const root = fileURLToPath(new URL('../', import.meta.url)); const cli = path.join(root, 'bin/pixelbolt.js'); export async function previewSource(args, cwd, route = '/project.json') { const child = spawn(process.execPath, [cli, ...args], { cwd, stdio: ['ignore', 'pipe', 'pipe'] }); const closed = once(child, 'close'); let errors = ''; child.stderr.on('data', chunk => { errors += chunk; }); try { for await (const line of createInterface({ input: child.stdout })) { const address = /^Pixelbolt studio: (http:\/\/127\.0\.0\.1:\d+)$/.exec(line); if (address) { const response = await fetch(address[1] + route); assert.equal(response.status, 200); return await response.json(); } } throw new Error(`preview failed to start: ${errors}`); } finally { child.kill(); await closed; } } const outputFlags = ['--out', '--image', '--preview', '--metadata', '--sheet']; // These examples invoke other applications or a separate repository workflow. A new shell // command must run or match an explicit entry here. Report each exclusion with its location. const skips = [ [/^inspect --region$/, 'option reference without a recipe or coordinates'], [/^git clone |^cd Pixelbolt$/, 'setup for a checkout, which the runner already has'], [/^(?:claude plugin install|codex plugin (?:add|marketplace add)) /, 'installs into an external client'], [/^npm (?:test|run demo)$/, 'repository maintenance command'], [/^(?:gh |node scripts\/(?:build|verify)-(?:studio|mcpb)\.mjs\b|npx --yes @anthropic-ai\/mcpb@)/, 'packaging or release workflow'], [/^(?:node bin\/pixelbolt\.js|pixelbolt) preview\b.* --open\b/, 'opens the user’s default browser; Studio QA exercises the browser separately'] ]; // Supply the shore asset named by the workflow's tilemap placement. A one-pixel tile // makes the rendered image readable cell by cell. Pink exposes a disconnected shore. function workflowTilemap(text) { const sample = /^### Tilemaps\n[\s\S]*?^```json\n([\s\S]+?)\n```/m.exec(text); assert.ok(sample, 'missing workflow tilemap placement'); const placement = JSON.parse(sample[1]); const palette = { w: '#0000ff', s: '#ffff00', x: '#ff00ff' }; const frames = [['water-a0', 'w'], ['water-b0', 'w'], ['sand', 's'], ['isolated', 'x']].map(([name, color]) => ({ name, ops: [{ op: 'pixel', x: 0, y: 0, color }] })); const animations = Object.fromEntries(BLOB_MASKS.map(mask => ['shore-' + mask, { frames: [mask ? 'sand' : 'isolated'] }])); const shore = { version: 1, name: 'shore', width: 1, height: 1, palette, frames, animations }; const scene = { format: 'pixelforge-scene', version: 1, name: 'shore-map', width: 4, height: 3, assets: { shore }, instances: [placement] }; return { line: text.slice(0, sample.index).split('\n').length, tool: 'pixel_scene', command: 'pixel_scene (Tilemaps placement)', args: { scene, scale: 1 }, check: checkTilemap }; } function checkTilemap(parts, answer) { assert.deepEqual(JSON.parse(answer).tilemaps, [{ name: 'ground', tiles: 12 }]); const png = parts.find(part => part.type === 'image'); assert.ok(png, 'the scene must return its preview'); const { width, height, data } = decodePNG(Buffer.from(png.data, 'base64')); assert.deepEqual([width, height], [4, 3]); const rows = ['wwss', 'wsss', 'wwss']; for (const [y, row] of rows.entries()) { for (let x = 0; x < width; x++) { const offset = 4 * (y * width + x); const expected = row[x] === 'w' ? [0, 0, 255, 255] : [255, 255, 0, 255]; assert.deepEqual([...data.subarray(offset, offset + 4)], expected, 'shore map at ' + [x, y]); } } } // The README supplies a project placeholder and an optional frame rate. One extra clipped // operation makes both the location list and its omission count observable in the same reply. function readmeValidation(line) { const spans = [...line.matchAll(/`([^`]+)`/g)].map(match => match[1]); const [tool, projectTemplate] = spans; const fps = spans.find(span => span.startsWith('"fps"')); const ops = Array.from({ length: 17 }, (_, i) => ({ op: 'pixel', x: i + 1, y: 0, color: '#fff' })); const project = { version: 1, name: 'clipped', width: 1, height: 1, frames: [{ name: 'still', duration: 50, ops }] }; const args = { ...JSON.parse(projectTemplate.replace('...', JSON.stringify(project))), ...JSON.parse('{' + fps + '}') }; return { tool, args, command: tool + ' ' + projectTemplate + ' with ' + fps, check(_parts, answer) { const report = JSON.parse(answer); assert.equal(report.ok, true); assert.match(report.revision, /^[0-9a-f]{12}$/); assert.deepEqual(report.clipping, ops.slice(0, 16).map((_, i) => ({ path: 'project.frames[0].ops[' + i + ']', pixels: 1 }))); assert.equal(report.clippingOmitted, ops.length - report.clipping.length); assert.deepEqual(report.frameGrid.offGrid, [{ frame: 'still', duration: 50, videoFrames: 1.5 }]); assert.match(line, /first 16\b/i, 'give the clipping limit in the tool reference'); assert.ok(line.includes('clippingOmitted'), 'name the field that counts omitted locations'); } }; } // Find CLI code spans that none of the walkthroughs claimed. A command name in prose is // a reference. Complete option examples run on a suitable input; option names without a // value have their own exclusion. An unrecognised command with arguments fails the walk. function remainingCli(page, text, found) { const commands = /^(?:autotile|build|compile|gif|gif-frames|help|import|init|inspect|mcp|overlay|patch|presets|preview|render|scene|schema|sequence|share|skill|validate)(?:\s|$)/; const attachments = [ [/^render --(?:scale \d+|columns \d+ --expect .+|expect '.+'|gif)$/, 'sample-for-options.json', '--out rendered'], [/^compile --(?:expand|metadata \S+)$/, 'examples/hero.poses.json', ''], [/^compile --frames \d+$/, 'examples/campfire.fluid.json', '--out compiled.json'], [/^compile --slices$/, 'examples/copper-rally.stack.json', '--out compiled.json'], [/^inspect --layers --frames --grid$/, 'hero.poses.json', ''], [/^inspect --view tile$/, 'examples/iso-tiles.json', ''], [/^inspect --view parts --animation $/, 'examples/hero.poses.json', ''], [/^inspect --(?:scale \d+|diagnostics)$/, 'sample-for-options.json', ''] ]; const incomplete = /^(?:inspect --(?:pin|rotate|region|reference|motion)|compile --(?:size|preset|draft-views)|import --cutout|gif --sheet|patch --(?:image|out)|scene --(?:out|image)|sequence --size|presets --find)$/; let fenced = false; for (const [i, line] of text.split('\n').entries()) { if (line.startsWith('\x60\x60\x60')) { fenced = !fenced; continue; } if (fenced) continue; for (const [, span] of line.matchAll(/\x60([^\x60]+)\x60/g)) { if (found.some(item => item.line === i + 1 && item.command === span)) continue; const launcher = /^(?:node bin\/pixelbolt\.js|pixelbolt|npx (?:-y )?pixelbolt@(?:<[^>]+>|\S+))(?= |$)\s*/.exec(span); const cmd = launcher ? span.slice(launcher[0].length) : span; if (!launcher && !commands.test(cmd)) continue; const item = { line: i + 1, block: 'option-' + i + '-' + found.length, command: span, inline: true }; const attached = attachments.find(([pattern]) => pattern.test(cmd)); if (attached) { const [, input, end] = attached, split = cmd.indexOf(' '); item.attached = cmd.slice(0, split) + ' ' + input + cmd.slice(split) + (end ? ' ' + end : ''); if (cmd.startsWith('compile --metadata ')) item.attached += ' --out compiled.json'; } else if (cmd === '' || !cmd) item.skip = 'launcher or version pin without a subcommand'; else if (!cmd.includes(' ')) item.skip = 'command name used as a reference, without an example invocation'; else if (incomplete.test(cmd)) item.skip = 'option name only, without its value or input'; else assert.fail(page + ':' + (i + 1) + ' unhandled documented CLI example: ' + span); found.push(item); } } } // The pose walkthroughs print small JSON argument templates. Their four placeholders // refer to outputs of earlier calls. All remaining values come directly from the example. function poseToolExamples(line, section) { const cases = []; const cutout = section === 'Cutout walks from a PNG'; if (cutout && line.includes('call \x60pixel_import\x60 with')) { for (const [, field] of line.matchAll(/\x60(path|data)\x60/g)) cases.push({ tool: 'pixel_import', form: field, command: 'pixel_import ' + field + ' with cutout' }); } const spans = [...line.matchAll(/\x60([^\x60]+)\x60/g)].map(match => match[1]); if (spans.includes('pixel_inspect')) { for (const template of spans.filter(span => /^\{(?:source,|revision,|"source":|"revision":)/.test(span) && /\b(?:walks|motion)\b/.test(span))) { const parsed = JSON.parse(template.replace('', '""') .replace(/([{,]\s*)(source|revision|metadata)(?=\s*[,}])/g, '$1"$2":"<$2>"') .replace(/([{,]\s*)(\w+)\s*:/g, '$1"$2":')); cases.push({ tool: 'pixel_inspect', template: parsed, command: 'pixel_inspect ' + template }); } if (cutout && line.includes('as \x60track\x60 on')) { const fields = spans.filter(span => /^(?:view|animation):/.test(span)); const template = Object.assign({ revision: '', track: JSON.parse(spans.find(s => s.startsWith('{"part":'))) }, ...fields.map(field => JSON.parse('{' + field.replace(/^(\w+):/, '"$1":') + '}'))); cases.push({ tool: 'pixel_inspect', template, command: 'pixel_inspect track ' + fields.join(', ') }); } } const metadata = spans.find(s => /^metadata:\s*true$/.test(s)); if (metadata && spans.includes('pixel_compile')) { cases.unshift({ tool: 'pixel_compile', template: { source: '', metadata: true }, command: 'pixel_compile ' + metadata }); if (cutout) cases.push({ tool: 'pixel_inspect', template: { revision: '', metadata: '', view: 'walks' }, command: 'pixel_inspect walks with the compiled revision and companion metadata' }); } const draft = spans.find(s => s.startsWith('draftViews: {')); if (draft && spans.includes('pixel_compile')) cases.push({ tool: 'pixel_compile', command: 'pixel_compile ' + draft, template: { source: '', draftViews: JSON.parse(draft.slice(draft.indexOf(':') + 1)) } }); return cases.map(item => ({ ...item, poseTool: true, cutout })); } // Bind the public index's optional launcher and sequence arguments without changing their names. function indexSyntax(span, line) { if (span.includes(' mcp --out ')) return [{ indexServer: true }]; if (span.includes('preview [recipe.json]')) return [ { attached: span.replace(' [recipe.json] [--open] [--port N]', '') }, { attached: span.replace('[recipe.json]', 'sample.json').replace(' [--open]', '').replace('[--port N]', '--port 0') }, { skip: 'the optional --open launches a browser; Studio QA covers the browser' } ]; if (span.includes('sequence ')) { const cases = []; const sceneOptions = /For a scene, omit \x60(--[\w-]+)\x60 and \x60(--[\w-]+)\x60/.exec(line); const bodyOptions = /For a rigid-body source, omit \x60(--[\w-]+)\x60/.exec(line); const inputs = [['sample.json', 'idle'], ['examples/portal.wave.json', 'open'], ['clip.bodies.json', 'bouncing-pixel'], ['clip.powder.json', 'quarry-blast'], ['room.scene.json', 'idle']]; for (const [input, animation] of inputs) { const omit = input.endsWith('.scene.json') ? sceneOptions?.slice(1) : input.endsWith('.bodies.json') ? bodyOptions?.slice(1) : []; const base = span.replace('', input).replace('<24|25|29.97|30|60|n/d>', '30'); cases.push({ attached: base.replace(/ \[[^\]]+\]/g, '') }); const options = base.replace('[--size 720p|1080p|1440p|4k|vertical|square|WxH]', '--size 256x192') .replace('[--scale 1-256]', '--scale 1').replace('[--fit contain|cover]', '--fit contain') .replace('[--align top-left..bottom-right]', '--align top-left').replace('[--offset x,y]', '--offset 1,2') .replace('[--animation name]', omit?.includes('--animation') ? '' : '--animation ' + animation).replace('[--step n]', omit?.includes('--step') ? '' : '--step 2'); for (const duration of ['--loops 1', '--seconds 0.1']) cases.push({ attached: options.replace('[--loops n | --seconds s]', duration) }); } return cases; } if (/^(?:preview room\.scene\.json|(?:compile|inspect) )/.test(span)) return [{}]; return []; } // A code span can contain a single MCP option or the value following a named option in prose. function exportToolExamples(line) { const tools = ['pixel_render', 'pixel_scene'].filter(tool => line.includes('\x60' + tool + '\x60')); if (!tools.length) return []; const spans = [...line.matchAll(/\x60([^\x60]+)\x60/g)].map(match => match[1]); const cases = []; for (const tool of tools) { const add = (field, value) => cases.push({ tool, command: tool + ' ' + field + ' ' + JSON.stringify(value), exportExample: true, options: { [field]: value } }); for (const span of spans) { const pair = /^"?(gif|sequence|saveAs|share|embedRecipe|export|listFiles|animation|view)"?\s*:\s*(.*)$/.exec(span); if (pair) { const [, field, value] = pair; // A prose paragraph can describe several tools in separate sentences. if (tools.length > 1 && tool === 'pixel_scene' && ['saveAs', 'listFiles', 'share', 'embedRecipe'].includes(field)) continue; if (field === 'view' && (tool !== 'pixel_scene' || value !== '"depth"')) continue; if (field === 'animation' && (tool !== 'pixel_render' || value !== '"idle"')) continue; if (field === 'export' && tool !== 'pixel_scene') continue; if (!value.startsWith('{') && !['true', '"idle"', '"depth"'].includes(value)) continue; const normalized = value.replace(/([{,]\s*)(\w+)\s*:/g, '$1"$2":'); add(field, JSON.parse(normalized)); } else if (tool === 'pixel_render' && /^\{\s*"sheet"\s*:/.test(span) && line.includes('\x60saveAs\x60')) { add('saveAs', JSON.parse(span)); } else if (tool === 'pixel_render' && /^\{\s*"scale"\s*:/.test(span) && line.includes('"gif": {}')) { add('gif', JSON.parse(span)); } } } return cases; } // Both JSON configuration shapes, the TOML/YAML arrays and the Windows wrapper describe // the same server. Parse the written argv, check the launcher, then run this checkout's CLI. function clientLaunchers(text) { const cases = []; const add = (index, executable, args) => cases.push({ line: text.slice(0, index).split('\n').length, command: [executable, ...args].join(' '), clientArgs: [executable, ...args] }); for (const block of text.matchAll(/^([ \t]*)\x60\x60\x60(json|toml|yaml)\n([\s\S]*?)^\1\x60\x60\x60/gm)) { const [, , language, body] = block; if (!body.includes('pixelbolt@latest') || !body.includes('mcp')) continue; if (language === 'json') { const config = JSON.parse(body); if (config.mcpServers) add(block.index, config.mcpServers.pixelbolt.command, config.mcpServers.pixelbolt.args); else { assert.equal(config.mcp.pixelbolt.type, 'local'); add(block.index, config.mcp.pixelbolt.command[0], config.mcp.pixelbolt.command.slice(1)); } } else { const [, executable] = /^\s*command\s*[=:]\s*"?([\w-]+)"?\s*$/m.exec(body); const [, args] = /^\s*args\s*[=:]\s*(\[[^\n]*\])/m.exec(body); add(block.index, executable, JSON.parse(args.replaceAll("'", '"'))); } } for (const pair of text.matchAll(/\x60"command": "([^"]+)"\x60 with \x60"args": (\[[^\x60]+\])\x60/g)) { add(pair.index, pair[1], JSON.parse(pair[2])); } return cases; } // The frame-edit guide calls for the same two changes through the CLI and MCP. function frameEditTools(text, line) { const steps = [...text.matchAll(/^pixelbolt patch (\S+) --changes (\S+) --out (\S+) --image (\S+)$/gm)]; assert.equal(steps.length, 2); const cases = steps.map(([, input, changesFile, result, image]) => ({ tool: 'pixel_patch', command: 'pixel_patch changes ' + changesFile, input, changesFile, result, image })); const selected = /\x60frames: (\[[^\x60]+\])\x60/.exec(line); assert.ok(selected && line.includes('\x60grid: true\x60')); cases.push({ tool: 'pixel_inspect', command: 'pixel_inspect ' + selected[0] + ' grid: true', frames: JSON.parse(selected[1]) }); return cases.map(item => ({ ...item, editExample: true })); } // Use the worked source when a guide supplies one. For a format reference, use one shipped // source of that kind. These are ordinary CLI/MCP inputs, including sources with relative assets. const compileExamples = { poses: 'hero', autotile: 'meadow', fx: 'healing-circle', fluid: 'smoke-puff', wave: 'portal', crystal: 'quartz-cluster', powder: 'stilt-hut', bodies: 'bouncing-pixel', stack: 'iso-barrel', normals: 'forest-spirit' }; function compileToolExamples(page, line, text) { const calls = []; const tool = 'pixel_compile'; const add = (kind, extra = {}) => { assert.ok(Object.hasOwn(compileExamples, kind), 'unhandled source format ' + kind); calls.push({ tool, kind, command: tool + ' ' + kind, ...extra }); }; if (page === 'docs/wave-effects.md' && line.includes('\x60pixel_compile\x60 with \x60source\x60')) { const source = /^## Small example\s+\x60\x60\x60json\n([\s\S]*?)\n\x60\x60\x60/m.exec(text); assert.ok(source); add('wave', { document: JSON.parse(source[1]), chain: 'save' }); for (const [, next] of line.matchAll(/\x60(pixel_inspect|pixel_render)\x60/g)) calls.push({ tool: next, command: next + ' wave revision', chain: 'use' }); } else if (page === 'README.md' && line.includes('compile them with MCP \x60pixel_compile\x60')) { add(/\x60\*\.([\w-]+)\.json\x60/.exec(line)[1]); } else if (page === 'README.md' && line.startsWith('- **\x60pixel_compile\x60**') || page === 'docs/agent-guide.md' && line.startsWith('\x60pixel_compile\x60 turns a')) { for (const [, kind] of line.matchAll(/\x60pixelforge-([\w-]+)\x60/g)) add(kind); } else if (page === 'docs/agent-guide.md' && line.includes('\x60pixel_compile\x60 with the source or the')) { const preset = /or the \x60([\w-]+)\x60 preset/.exec(line)[1]; add('stack', { filename: preset + '.stack.json' }); add('stack', { preset, command: 'pixel_compile preset ' + preset }); } else if (line.includes('\x60pixel_compile\x60 with \x60"slices": true\x60')) { add('stack', { options: { slices: true } }); } else if (page === 'docs/art-workflow.md' && line.includes('MCP \x60pixel_compile\x60 returns it as a second image')) { add('autotile', { secondImage: true }); } else if (page === 'docs/art-workflow.md' && line.includes('MCP \x60pixel_compile\x60 takes the same source')) { add(/\x60topic: "([\w-]+)"\x60/.exec(line)[1]); } else if (line.includes('\x60pixel_compile\x60 with') && line.includes('pixelbolt sequence ') && page === 'docs/art-workflow.md') { const cli = /\x60pixelbolt sequence (\S+?\.(\w+)\.json) --out \S+ --fps (\d+) --size (\w+)\x60/.exec(line); assert.ok(cli, 'the CLI shows the simulation and its sequence options'); const explicit = /\x60"sequence": (\{[^\x60]+\})\x60/.exec(line); const sequence = explicit ? JSON.parse(explicit[1]) : { fps: Number(cli[3]), size: cli[4] }; add(cli[2], { suppliedFile: cli[1], options: { sequence } }); } else if (page === 'docs/art-workflow.md' && line.includes('\x60pixel_compile\x60') && line.includes('the recipe may also be \x60{"revision": id}')) { calls.push({ tool: 'pixel_validate', command: 'pixel_validate normal pass input', chain: 'normal-base' }); add('normals', { chain: 'normal-use' }); } else if (page === 'docs/agent-guide.md' && line.includes('call \x60pixel_inspect\x60 with \x60source\x60 and the same object as \x60poseSheet\x60')) { for (const mode of ['source', 'sourceRevision', 'revision']) calls.push({ tool: 'pixel_inspect', command: 'pixel_inspect ' + mode, study: mode }); } return calls.map(item => ({ ...item, compileExample: true })); } function guideReviewExamples(page, line) { const spans = [...line.matchAll(/\x60([^\x60]+)\x60/g)].map(match => match[1]); const cases = []; const add = (tool, options = {}, data = {}) => cases.push({ tool, options, command: tool + ' ' + JSON.stringify(options), reviewExample: true, ...data }); if (page === 'docs/agent-craft.md' && line.includes('A scene from pieces:')) { const scene = JSON.parse(spans.find(span => span.startsWith('{"format": "pixelforge-scene"'))); const scale = Number(/\x60pixelbolt scene [^\x60]+--scale (\d+)\x60/.exec(line)[1]); add('pixel_scene', { scale }, { camp: scene }); add('pixel_scene', { export: true }, { camp: scene }); add('pixel_scene', { gif: { scale: Number(/\x60pixelbolt gif [^\x60]+--scale (\d+)\x60/.exec(line)[1]) } }, { camp: scene }); } if (spans.includes('pixel_render') && spans.includes('normal') && ['docs/agent-craft.md', 'docs/art-workflow.md'].includes(page)) { const call = spans.find(span => span.includes(' --normal ')); if (call) { const [, recipe, normal] = /\brender (\S+) --normal (\S+)/.exec(call); add('pixel_render', {}, { material: [recipe, normal] }); } } if (page === 'docs/art-workflow.md' && line.startsWith('- **Guides.**')) { const guides = spans.filter(span => span.startsWith('{"horizon":') || span.startsWith('{"tile":')).map(span => JSON.parse(span)); for (const guide of guides) for (const tool of ['pixel_inspect', 'pixel_scene']) add(tool, { guides: guide.tile ? { iso: guide } : guide, scale: 2 }); } if (page === 'docs/art-workflow.md' && line.startsWith('The CLI and MCP \x60pixel_inspect\x60 support')) { const views = spans.find(span => span.startsWith('view: ')).slice(6).split('|'); for (const view of views) add('pixel_inspect', { view, native: true, diagnostics: true, ...(view === 'onion' && { animation: 'idle' }) }); } if (page === 'docs/agent-craft.md' && spans.includes('draftViews') && spans.includes('pixel_compile')) { const [, part, degrees] = /--draft-views (\w+):([\d,]+)/.exec(line); add('pixel_compile', { draftViews: { [part]: degrees.split(',').map(Number) } }, { character: true }); } if (page.startsWith('skills/') && spans.includes('pixel_inspect') && spans.includes('view: "walks"')) { const [, preset] = /\x60presets ([\w-]+) --out actor\.poses\.json\x60/.exec(line); add('pixel_inspect', { view: 'walks' }, { preset }); } if (page.startsWith('skills/') && spans.includes('pixel_compile') && spans.includes('preset') && spans.includes('size')) { const [, size] = /\x60--size (\d+x\d+)\x60/.exec(line), [, count] = /\x60--frames (\d+)\x60/.exec(line); add('pixel_compile', { preset: 'smoke-puff', size, frames: Number(count) }); } if (spans.includes('pixel_validate') && spans.includes('"fps": 30')) add('pixel_validate', { fps: 30 }); if (spans.includes('pixel_render') && spans.includes('scale') && line.includes('\x60pixelbolt render --scale ')) { add('pixel_render', { scale: Number(/\x60pixelbolt render --scale (\d+)\x60/.exec(line)[1]) }); } if (spans.includes('pixel_render') && spans.includes('expect') && spans.includes('{"rows": 1}')) { const sheet = JSON.parse(spans.find(span => span.startsWith('{"rows"'))); const frames = JSON.parse(spans.find(span => span.startsWith('{"idle"'))); add('pixel_render', { expect: { frames, sheet } }, { frameCounts: frames }); } return cases; } // Follow the data passed between tools in the text, including the alternative of sending // the same project by value or by its saved revision. Only revision files cross server restarts. function referenceToolExamples(page, line) { const cases = []; const add = (tool, input, more = {}) => cases.push({ tool, referenceExample: true, command: tool + ' ' + input, input, ...more }); if (line.includes('\x60pixel_help\x60') && (/call \x60pixel_help\x60|\x60pixel_help\x60 alone/.test(line))) { cases.push({ tool: 'pixel_help', command: 'pixel_help without a topic', args: {}, check(_parts, answer) { assert.match(answer, /^# Pixelbolt quick start/); } }); } if (page === 'llms.txt' && line.includes('Validate, inspect, patch and render take')) { const templates = [...line.matchAll(/\{ "(project|revision)": <(?:recipe|id)> \}/g)].map(m => m[1]); assert.deepEqual(templates, ['project', 'revision']); for (const input of templates) for (const tool of ['pixel_validate', 'pixel_inspect', 'pixel_patch', 'pixel_render']) add(tool, input); } if (page === 'docs/agent-guide.md' && line.includes('\x60{ "project": }\x60 to \x60pixel_inspect\x60')) { for (const tool of ['pixel_inspect', 'pixel_validate']) add(tool, 'project'); assert.ok(line.includes('\x60{ "revision": }\x60')); for (const tool of ['pixel_inspect', 'pixel_validate', 'pixel_patch', 'pixel_render']) add(tool, 'revision'); } if (page.startsWith('skills/') && line.includes('same steps are \x60pixel_compile\x60')) { for (const [, tool] of line.matchAll(/\x60(pixel_\w+)\x60/g)) add(tool, tool === 'pixel_compile' ? 'preset' : tool === 'pixel_validate' ? 'project' : 'revision', { withGif: tool === 'pixel_render' }); } if (['README.md', 'docs/agent-guide.md'].includes(page) && line.includes('\x60pixel_import\x60') && /base64/.test(line) && !line.includes('cutout')) { add('pixel_import', 'path'); add('pixel_import', 'data'); } if (['docs/art-workflow.md', 'docs/agent-craft.md'].includes(page) && line.includes('\x60pixel_scene\x60') && line.includes('\x60{"revision": id}\x60')) { add('pixel_validate', 'project'); add('pixel_scene', 'revision-asset'); } return cases; } // llms.txt uses prose for several invocations. Capture the associated CLI example's // arguments where the MCP form names its fields but leaves their values to the reader. function indexToolExamples(line) { const cases = []; const add = item => cases.push(item); if (line.startsWith('Canvas corrections:')) { const change = JSON.parse(/add (\{.+?\}) to patch changes/.exec(line)[1]); add({ tool: 'pixel_patch', command: 'pixel_patch ' + JSON.stringify(change), editExample: true, paint: change }); } if (line.includes('pixel_compile') && !line.startsWith('MCP:')) { const kind = /^(?:Rigid bodies|Crystal growth|Falling sand|Looping interference|[-] \[Fluid effects)/.exec(line); if (kind) { const format = { 'Rigid bodies': 'bodies', 'Crystal growth': 'crystal', 'Falling sand': 'powder', 'Looping interference': 'wave', '- [Fluid effects': 'fluid' }[kind[0]]; add({ tool: 'pixel_compile', kind: format, compileExample: true, command: 'pixel_compile ' + format }); if (line.includes('pixel_compile with sequence')) add({ tool: 'pixel_compile', kind: format, suppliedFile: 'clip.' + format + '.json', compileExample: true, command: 'pixel_compile with sequence', options: { sequence: { fps: 30 } } }); } if (line.includes('pixel_compile draftViews')) { const [, part, angles] = /--draft-views (\w+):([\d,]+)/.exec(line); add({ tool: 'pixel_compile', command: 'pixel_compile draftViews', reviewExample: true, character: true, options: { draftViews: { [part]: angles.split(',').map(Number) } } }); } } if (line.includes('pixel_inspect source + view: motion')) { const [, animation, speed] = /--motion (\w+) --speed (\d+)/.exec(line); add({ tool: 'pixel_inspect', command: 'pixel_inspect source + view: motion', reviewExample: true, character: true, options: { view: 'motion', animation, speed: Number(speed) } }); } if (line.startsWith('MCP:')) { for (const input of ['path', 'data']) add({ tool: 'pixel_import', command: 'pixel_import ' + input, referenceExample: true, input }); add({ tool: 'pixel_compile', command: 'pixel_compile preset', compileExample: true, preset: 'smoke-puff', kind: 'fluid' }); add({ tool: 'pixel_scene', command: 'pixel_scene with revision asset', referenceExample: true, input: 'revision-asset' }); } for (const match of line.matchAll(/MCP (pixel_render(?: \/ pixel_scene)?) with "(gif|sequence)": (\{[^}]*\})/g)) { for (const tool of match[1].split(' / ')) add({ tool, command: match[0], exportExample: true, options: { [match[2]]: JSON.parse(match[3]) } }); } if (line.includes('MCP pixel_validate "fps"')) add({ tool: 'pixel_validate', command: 'pixel_validate fps', reviewExample: true, options: { fps: Number(/validate --fps (\d+)/.exec(line)[1]) } }); return cases; } // A few paragraphs direct the reader from an explanation to a tool without printing JSON. function proseTools(page, line) { const cases = []; const add = (tool, flags = {}) => cases.push({ tool, command: tool + ' (prose example)', ...flags }); if (page === 'README.md' && line.includes("MCP's \x60pixel_help\x60. Write a recipe")) { add('pixel_help', { args: {} }); add('pixel_inspect', { referenceExample: true, input: 'project' }); } if (page === 'README.md' && line.startsWith('- **\x60pixel_inspect\x60**')) add('pixel_inspect', { referenceExample: true, input: 'project' }); if (page === 'README.md' && line.startsWith('- **\x60pixel_scene\x60**')) add('pixel_scene', { exportExample: true, options: { export: true } }); if (page === 'docs/agent-craft.md' && line.startsWith('| Learn the format ')) { for (const [, topic] of line.slice(line.indexOf('topics such as')).matchAll(/\x60(\w+)\x60/g)) add('pixel_help', { args: { topic } }); } if (page === 'docs/agent-guide.md' && line.includes('Use \x60pixel_patch\x60\'s \x60paint\x60')) { add('pixel_patch', { referenceExample: true, input: 'project' }); } if (page === 'docs/agent-guide.md' && line.includes('Use \x60pixel_inspect\x60 with a narrower selection')) { add('pixel_inspect', { reviewExample: true, options: { frames: ['rest'], maxCells: 1 } }); } if (page === 'docs/agent-guide.md' && line.includes('\x60pixel_inspect\x60 with \x60view: "motion"\x60 and the \x60animation\x60')) { add('pixel_inspect', { reviewExample: true, options: { view: 'motion', animation: 'idle' } }); } if (line.includes('\x60pixel_compile\x60 accepts \x60pixelforge-wave\x60 sources')) { add('pixel_compile', { compileExample: true, kind: 'wave' }); } if (page === 'docs/art-workflow.md' && line.includes('\x60pixel_compile\x60 (or \x60pixelbolt compile\x60) builds it')) { add('pixel_compile', { compileExample: true, kind: /\x60pixelforge-(\w+)\x60/.exec(line)[1] }); } if (page === 'docs/agent-guide.md' && line.includes('or \x60sequence\x60 on \x60pixel_compile\x60')) { for (const kind of ['bodies', 'powder']) add('pixel_compile', { compileExample: true, kind, suppliedFile: 'clip.' + kind + '.json', options: { sequence: { fps: 30 } } }); } if (page === 'docs/agent-guide.md' && line.includes('send to \x60pixel_compile\x60 as \x60source\x60')) { for (const [name, tool] of [['smoke-puff', 'pixel_compile'], ['coin', 'pixel_validate']]) { add('pixel_help', { presetExample: true, name }); add(tool, { presetExample: true, name }); } } if (page === 'docs/game-integration.md' && line.includes('\x60pixel_scene\x60') && line.includes('tileset.tsx')) { add('pixel_scene', { exportExample: true, options: { export: true }, tiledAssets: true }); } if (page === 'docs/art-workflow.md' && line.includes('Renders report \x60lights\x60:')) { add('pixel_scene', { reviewExample: true, lighting: true, options: {} }); } if (page.startsWith('skills/') && line.includes('\x60pixel_help\x60 with \x60topic\x60 and \x60name\x60')) { add('pixel_help', { args: { topic: 'craft', name: 'Rules' }, check(_parts, answer) { assert.match(answer, /## Rules\b/); } }); } return cases; } function patchTableExamples(page, section, text, line) { const groups = []; if (page === 'docs/art-workflow.md' && line.startsWith('\x60pixel_patch\x60, CLI \x60patch\x60')) { const sample = /accept these canvas-coordinate changes:\s+\x60\x60\x60json\n([\s\S]*?)\n\x60\x60\x60/.exec(text); assert.ok(sample, 'missing regional changes array'); groups.push(JSON.parse(sample[1])); } if (section === 'Patching' && line.startsWith('| ') || section === 'Regional corrections and scope' && line.startsWith('Another canvas change')) { for (const [, value] of line.matchAll(/\x60(\{"(?:set|insert|remove|paint|grid|move|recolor|cleanup)":[^\x60]+\})\x60/g)) { // The first three rows illustrate the syntax with path and v as metavariables. const change = value.startsWith('{"insert": path') ? value.replace(': path', ': "frames[blink].ops[0]"').replace(': v', ': {"op":"pixel","x":4,"y":4,"color":"k"}') : value.replace(': path', ': "frames[blink].duration"').replace(': v', ': 200'); groups.push([JSON.parse(change)]); } } return groups.flatMap(changes => ['cli', 'mcp'].map(via => ({ patchTable: true, via, changes, ...(via === 'mcp' && { tool: 'pixel_patch' }), command: (via === 'cli' ? 'patch' : 'pixel_patch') + ' ' + JSON.stringify(changes) }))); } // A tool mentioned by name in an architecture note, a command cross-reference or a // description of return fields is not a sample invocation. New uses outside these // particular passages must have executable examples or an explicit reason to skip. const toolReferences = [ ['README.md', /^(?:Codex and other Agent Plugins|\x60pixel_patch\x60 also supports)/, 'describes client paths or capabilities without a call payload'], ['docs/PUBLISHING.md', /^(?:Agent Plugins clients start|The workspace defaults)/, 'explains the launcher and the destinations of saved copies'], ['docs/agent-craft.md', /^\| (?:Check a recipe|See the frames|Edit|Export|Compile a source or preset|Scenes|Import a PNG) \|/, 'CLI-to-MCP name in the lookup table'], ['docs/agent-guide.md', /^(?:Change a recipe with small edits|Large \x60pixel_render\x60 previews)/, 'explains returned revisions or preview limits'], ['docs/agent-quick-start.md', /^\x60pixel_help\x60 with \x60topic\x60/, 'introduces the topic calls run from the following list'], ['docs/art-workflow.md', /^(?:With \x60--out review.png --native\x60|Four things that catch people out)/, 'describes preview sampling or compiler warnings'], ['docs/competitive-review.md', /^1\. \*\*Inspection and targeted corrections/, 'comparison of tool capabilities'], ['docs/modules.md', /^(?:- \x60src\/(?:core|stack|resize|export|help|check|presets)\.js\x60| \x60draftViews\x60 drafts)/, 'module ownership and return-value reference'], ['docs/physics-model.md', /^An effect with \x60loop\x60/, 'explains simulation looping'], ['llms.txt', /^(?:Quality review:|[-] \[Agent quick start\])/, 'describes the quick start or preview sampling'] ]; function remainingMentions(page, text, found) { let fence = false; for (const [index, line] of text.split('\n').entries()) { if (/^\s*\x60{3}/.test(line)) { fence = !fence; continue; } if (fence) continue; const lineNumber = index + 1; const tools = new Set([...line.matchAll(/\bpixel_[a-z][a-z_]*\b/g)].map(match => match[0])); for (const tool of tools) { if (found.some(item => item.line === lineNumber && item.tool === tool)) continue; const reason = toolReferences.find(([file, matching]) => file === page && matching.test(line))?.[2]; assert.ok(reason, page + ':' + lineNumber + ' unclassified MCP reference: ' + tool); found.push({ line: lineNumber, command: tool, skip: reason }); } } } // Option-only code spans are attached to the command the surrounding example describes. // References to optional tools and incomplete fragments are reported by location. function optionFragments(page, line) { const examples = []; for (const [, span] of line.matchAll(/\x60(--[a-z][\w-]* [^\x60]+)\x60/g)) { let kind, skip; if (/^--(?:node-archive|base|godot|tiled) /.test(span)) skip = 'option of the packaging, engine verification or repository scripts'; else if (span === '--grid --region') skip = 'names two flags without region coordinates; the guide also shows the complete command'; else if (span.startsWith('--out ')) kind = 'scene-export'; else if (span.startsWith('--out new.poses.json')) kind = 'expand'; else if (/^--(?:changes|image) |^--out sprite-v2\.json/.test(span)) kind = 'patch'; else if (/^--metadata (?:character\.meta\.json|meta\.json)$/.test(span)) kind = line.includes('compile --metadata meta.json') ? 'compile' : 'review-metadata'; else if (span.startsWith('--ground ')) kind = 'motion'; else if (span.startsWith('--view depth') || span.startsWith('--sheet ') && line.includes('gif ')) kind = span.startsWith('--view') ? 'scene' : 'scene-gif'; else if (span.startsWith('--preview ')) kind = 'autotile'; else if (span.startsWith('--normal ')) kind = 'normal'; else if (/^--(?:expect|columns|gif-scale) /.test(span)) kind = 'render'; else if (/^--(?:only|keep) /.test(span)) kind = 'build'; else if (/^--(?:frame|atlas|name) /.test(span) || span === '--frames N' && /(PNG|import|sheet takes)/.test(line)) kind = 'import'; else if (/^--(?:loops|seconds|fit) /.test(span) || span === '--offset x,y' || (page === 'README.md' && span === '--step 2')) kind = 'sequence'; else if (span.startsWith('--port ')) kind = 'preview'; else if (span.startsWith('--time-limit ')) kind = 'server'; else if (span.startsWith('--dir ')) kind = 'skill'; else if (span.startsWith('--preset ') || span.startsWith('--sheet ') || span.startsWith('--background ') || span === '--scale <1-16>') kind = 'gif'; else if (span.startsWith('--metadata ') || span.startsWith('--draft-views ') || span.startsWith('--size ') || /^--frames (?:8|N)$/.test(span)) kind = 'compile'; else if (span.startsWith('--animation ') && (line.includes('--gif') || line.includes('gif --preset '))) kind = 'gif'; else if (/^--(?:port|frames|animation|region|scale|view|grid|step|every|native|diagnostics|out|layers|reference|guides|stack|under|beside) /.test(span)) kind = 'inspect'; else assert.fail(page + ' unclassified documented option: ' + span); const opts = span.includes('--view silhouette|') ? span.slice('--view '.length).split('|').map(view => '--view ' + view) : [span]; for (const option of opts) examples.push({ command: span, option, kind, ...(skip ? { skip } : { optionExample: true }) }); } return examples; } // Shell fences and inline code cover the commands in the Markdown guides. The plain-text // index also names two bare launchers and two commands without operands. A new unquoted // invocation needs a runnable case so it cannot fall between the two extractors. function remainingPlainCli(page, text, found) { let fence = false; for (const [index, line] of text.split('\n').entries()) { if (/^\s*\x60{3}/.test(line)) { fence = !fence; continue; } if (fence) continue; const prose = line.replace(/\x60[^\x60]*\x60/g, ' '); for (const match of prose.matchAll(/\b(?:node (?:bin\/|\/absolute\/[^ ]*\/)?pixelbolt\.js(?: [\w-]+)?|npx (?:-y )?pixelbolt@(?:<[^>]+>|[\w.-]+)|pixelbolt (?:validate|help|compile|inspect|render|mcp|build|presets|scene|skill|sequence|gif|share|import)\b)/g)) { const command = match[0], number = index + 1; if (found.some(item => item.line === number && item.command === command)) continue; let reason; if (page === 'llms.txt' && /^npx (?:-y )?pixelbolt@/.test(command) && /^(?: and reads the guides|, and never replaces)/.test(prose.slice(match.index + command.length))) { reason = 'package launcher without a subcommand'; } else if (page === 'llms.txt' && /^(?:pixelbolt sequence|pixelbolt compile)$/.test(command) && /^(?:, or | or MCP)/.test(prose.slice(match.index + command.length))) { reason = 'command name used as a cross-reference without its input'; } assert.ok(reason, page + ':' + number + ' unclassified command in prose: ' + prose.slice(match.index, match.index + 95)); found.push({ line: number, command, skip: reason }); } } } // Fenced tool examples may use the compact help form or the JSON-RPC tools/call envelope. // An unrecognized example that mentions a tool must be classified at its source location. function fencedTools(body, page, line) { if (!/\bpixel_[a-z]/.test(body)) return []; const compact = /^\s*(pixel_[\w]+)(?:\s+(\{[\s\S]*\}))?\s*$/.exec(body); const json = value => { try { return JSON.parse(value); } catch (error) { throw new Error(page + ':' + line + ' invalid fenced MCP example: ' + error.message); } }; const data = compact ? { name: compact[1], arguments: json(compact[2] ?? '{}') } : json(body); return (Array.isArray(data) ? data : [data]).map(message => { const call = message?.method === 'tools/call' ? message.params : message; assert.match(call?.name ?? '', /^pixel_[a-z_]+$/, page + ':' + line + ' unclassified fenced MCP example'); return { line, command: call.name, tool: call.name, args: call.arguments ?? {} }; }); } function examples(page, text) { const found = []; let fence = null, start = 0, section; const lines = text.split(/\r?\n/); for (const [i, line] of lines.entries()) { if (/^```/.test(line)) { if (fence !== null) found.push(...fencedTools(lines.slice(start + 1, i).join('\n'), page, start + 2)); fence = fence === null ? line.slice(3).trim() : null; start = i; } else if ((['sh', 'bash', 'shell', 'console'].includes(fence) || (fence === '' && /^\s*(?:node |npx |pixelbolt |claude |codex |npm |git )/.test(line))) && line.trim() && !line.trimStart().startsWith('#')) { found.push({ line: i + 1, block: start, command: line.trim() }); } else if (fence === 'yaml' && /^- run: npx pixelbolt@ build\b/.test(line.trim())) { found.push({ line: i + 1, command: line.trim().slice(7), build: true, ...(page === 'docs/game-integration.md' && { checkGuide: text.match(/^`--check` exits .*$/m)[0] }) }); } else if (fence === null) { if (line.startsWith('## ')) section = line.slice(3).trim(); for (const item of optionFragments(page, line)) found.push({ line: i + 1, ...item }); if (page === 'README.md' && line.startsWith('- **\x60pixel_help\x60**')) { const schema = /\x60(pixel_help \{[^\x60]+\})\x60 returns the complete recipe JSON Schema/.exec(line); assert.ok(schema, 'show how to get the whole recipe schema in the tool reference'); for (const topic of ['guide', 'workflow']) { found.push({ line: i + 1, tool: 'pixel_help', command: 'pixel_help topic ' + topic, args: { topic }, check(_parts, answer) { assert.match(answer, /To read one section, call pixel_help/); } }); assert.ok(line.includes('\x60"all"\x60 for the full guide')); found.push({ line: i + 1, tool: 'pixel_help', command: 'pixel_help topic ' + topic + ' with name all', args: { topic, name: 'all' }, check(_parts, answer) { assert.match(answer, /^# /); assert.ok(answer.includes('\n### ')); } }); } } if (page === 'docs/agent-guide.md' || page === 'docs/art-workflow.md') { for (const item of poseToolExamples(line, section)) found.push({ line: i + 1, ...item }); } if (['README.md', 'docs/agent-guide.md', 'docs/agent-craft.md', 'docs/game-integration.md', 'docs/art-workflow.md'].includes(page)) { for (const item of exportToolExamples(line)) found.push({ line: i + 1, ...item }); } if (['README.md', 'docs/agent-guide.md', 'docs/art-workflow.md', 'docs/wave-effects.md'].includes(page)) { for (const item of compileToolExamples(page, line, text)) found.push({ line: i + 1, ...item }); } if (['docs/agent-guide.md', 'docs/agent-craft.md', 'docs/art-workflow.md', 'skills/pixelbolt-pixel-art/SKILL.md'].includes(page)) { for (const item of guideReviewExamples(page, line)) found.push({ line: i + 1, ...item }); } for (const item of referenceToolExamples(page, line)) found.push({ line: i + 1, ...item }); if (page === 'docs/agent-quick-start.md' && section === 'More help' && line.startsWith('- \x60')) { const spans = [...line.matchAll(/\x60([^\x60]+)\x60/g)].map(match => match[1]); const topic = spans[0]; const help = (args, flags = {}) => found.push({ line: i + 1, tool: 'pixel_help', command: 'pixel_help ' + JSON.stringify(args), args, ...flags }); if (topic === 'workflow') { for (const sample of spans.filter(s => s.startsWith('"'))) { const name = JSON.parse(sample); help({ topic, name }, { check(_parts, answer) { assert.ok(answer.toLowerCase().includes(name.toLowerCase()), name); } }); } } else if (topic === 'schema') { help({ topic }, { outline: true }); const key = /as JSON \(\x60([^\x60]+)\x60\)/.exec(line)[1]; help({ topic, name: key }, { check(_parts, answer) { assert.equal(JSON.parse(answer).type, 'array'); } }); help({ topic, name: 'all' }, { fullSchema: true }); } else if (topic === 'presets') { const find = JSON.parse(spans.find(s => s.startsWith('"'))); help({ topic, find }, { check(_parts, answer) { assert.ok(answer.toLowerCase().includes(find)); } }); help({ topic: 'preset', name: 'smoke-puff' }, { check(_parts, answer) { assert.equal(JSON.parse(answer).source.format, 'pixelforge-fluid'); } }); } else if (topic === 'example') { help({ topic }, { check(_parts, answer) { assert.ok(renderProject(JSON.parse(answer)).frames.length > 1); } }); } else if (isSchema(topic)) { for (const schema of spans.slice(0, line.split(': the JSON Schema')[0].split(',').length)) { assert.ok(isSchema(schema)); help({ topic: schema }, { outline: true }); } const pair = /\x60(\w+)\x60 with \x60name: "([^"]+)"\x60/.exec(line); help({ topic: pair[1], name: pair[2] }, { check(_parts, answer) { assert.ok(JSON.parse(answer).items.properties.shape); } }); } else { assert.ok(SECTIONED.has(topic), 'unhandled quick start topic ' + topic); help({ topic }); } } for (const item of proseTools(page, line)) found.push({ line: i + 1, ...item }); if (page === 'docs/agent-guide.md' || page === 'docs/art-workflow.md') { for (const item of patchTableExamples(page, section, text, line)) found.push({ line: i + 1, ...item }); } if (page === 'docs/agent-quick-start.md' && section === 'The tools' && /^\d+\. /.test(line)) { for (const match of line.matchAll(/\*\*\x60(pixel_\w+)\x60\*\*(?: \x60(\{[^\x60]+\})\x60)?/g)) { const [, tool, shorthand] = match; const item = { line: i + 1, tool, command: match[0], quickStep: true, keys: shorthand?.slice(1, -1).split(', ') ?? [] }; found.push(item); if (tool === 'pixel_compile') { const preset = /\x60\{preset: "([^"]+)"\}\x60/.exec(line); assert.ok(preset, 'compile gives a preset example'); found.push({ ...item, keys: ['preset'], preset: preset[1] }); } if (tool === 'pixel_render') { for (const gif of line.matchAll(/\x60gif: \{(?:scale: (\d+))?\}\x60/g)) found.push({ ...item, gif: gif[1] ? { scale: Number(gif[1]) } : {} }); } } } if (page === 'docs/fix-one-frame.md' && section === 'The same edits through MCP' && line.startsWith('\x60pixel_patch\x60')) { for (const item of frameEditTools(text, line)) found.push({ ...item, line: i + 1 }); } if (page === 'README.md' && line.startsWith('- **\x60pixel_patch\x60**')) { const example = /For example, \x60(\{[^\x60]+\})\x60/.exec(line); assert.ok(example, 'supply a runnable paint example'); found.push({ tool: 'pixel_patch', line: i + 1, command: 'pixel_patch ' + example[1], paint: JSON.parse(example[1]), editExample: true }); } if (page === 'README.md' && line.startsWith('- **`pixel_validate`**')) { found.push({ line: i + 1, ...readmeValidation(line) }); } // These guides show MCP arguments in consecutive code spans, e.g. pixel_help with // topic "wave" and name "all". Run the printed combination and check its promised format. const helpCalls = /`pixel_help` (?:topic `([\w-]+)`|with `topic: "([\w-]+)"`)(?: and `(name|find)(?:: "([^"]+)")?`)?/g; for (const match of line.matchAll(helpCalls)) { const [, bare, quoted, key, value] = match; const args = { topic: bare ?? quoted }; if (key) args[key] = value ?? (key === 'find' ? 'torch' : 'Rules'); const promise = line.slice(match.index + match[0].length); const fullSchema = /^ returns (?:their|the) (?:JSON )?schema\b/.test(promise); found.push({ line: i + 1, tool: 'pixel_help', command: match[0], args, fullSchema }); if (fullSchema && /Omit `name` for an outline|The topic alone gives an outline/.test(promise)) { found.push({ line: i + 1, tool: 'pixel_help', command: 'pixel_help topic ' + args.topic, args: { topic: args.topic }, outline: true }); } } if (page === 'llms.txt' && line.startsWith('MCP:')) { const example = /\x60pixel_help (\{[^\x60]+\})\x60 returns the complete recipe JSON Schema/.exec(line); assert.ok(example, 'show how to request the complete recipe schema from the index'); const args = JSON.parse(example[1]); const sources = /Use the same name for a complete ([\w, ]+) schema/.exec(line); assert.ok(sources, 'list the source schema topics'); const topics = [args.topic, ...sources[1].split(/, | or /)]; assert.deepEqual(topics.toSorted(), Object.keys(HELP_TOPICS).filter(isSchema).sort()); for (const topic of topics) { found.push({ line: i + 1, tool: 'pixel_help', command: 'pixel_help topic ' + topic, args: { topic }, outline: true }); if (topic !== args.topic) found.push({ line: i + 1, tool: 'pixel_help', args: { ...args, topic }, command: 'pixel_help topic ' + topic + ' with name ' + args.name, fullSchema: true }); } } if (page === 'llms.txt' && line.startsWith('Use pixelforge-poses')) { const saved = /\x60(compile [^\x60]+)\x60 saves the expansion\b/.exec(line); assert.ok(saved, 'the index should show how to save an expanded pose source'); found.push({ line: i + 1, command: saved[1], inline: true, expansion: true }); } if (page === 'llms.txt') for (const item of indexToolExamples(line)) found.push({ line: i + 1, ...item }); if (page === 'llms.txt' && line.startsWith('Project builds:')) { for (const match of line.matchAll(/node bin\/pixelbolt\.js build\b|\bbuild --[\w-]+/g)) { found.push({ line: i + 1, command: match[0], build: true }); } } for (const [, span] of line.matchAll(/`([^`]+)`/g)) { if (/^(?:pixelbolt |node bin\/pixelbolt\.js )build\b/.test(span)) { found.push({ line: i + 1, command: span, build: true }); continue; } const workflowCall = page === 'docs/art-workflow.md' && /^(?:pixelbolt )?(?:compile|inspect|render|autotile|sequence|scene|presets|validate|import|preview) (?!--)/.test(span); const craftCall = page === 'docs/agent-craft.md' && /^(?:pixelbolt )?(?:compile|inspect|gif|gif-frames|render|autotile|sequence|presets|validate|import|preview) (?!--)/.test(span); const craftPresetGIF = page === 'docs/agent-craft.md' && /^(?:pixelbolt )?gif --preset /.test(span); const guideCall = page === 'docs/agent-guide.md' && /^(?:(?:pixelbolt |node bin\/pixelbolt\.js )?(?:presets|inspect|patch|render|gif|gif-frames|compile|sequence|validate|preview)) (?!--)/.test(span); const presetCompile = /^(?:pixelbolt )?compile --preset /.test(span); const presetLookup = /^(?:pixelbolt )?presets --(?:find \S+|full$)/.test(span); if (/^(?:pixelbolt )?sequence (?: |$)/.test(span)) { for (const kind of page === 'docs/agent-craft.md' ? ['bodies'] : ['bodies', 'powder']) { found.push({ line: i + 1, inline: true, block: 'simulation-' + i + '-' + kind, command: span, simulation: kind }); } continue; } if (page === 'docs/game-integration.md' && span.startsWith('pixelbolt scene ') && span.includes('--out')) { found.push({ line: i + 1, command: span, inline: true, materialGuide: line }); continue; } if (span.includes('')) { for (const file of ['forest-spirit-normal.json', 'forest-spirit.normals.json']) found.push({ line: i + 1, block: file, command: span, inline: true, normalFile: file }); continue; } const skillVideo = page === 'skills/pixelbolt-pixel-art/SKILL.md' && span.startsWith('sequence '); const skillWalk = page === 'skills/pixelbolt-pixel-art/SKILL.md' && span.startsWith('inspect actor.poses.json --view walks'); const gameSlices = page === 'docs/game-integration.md' && span.startsWith('pixelbolt compile '); if (page === 'llms.txt') { const calls = indexSyntax(span, line); if (calls.length) { for (const call of calls) found.push({ line: i + 1, command: span, inline: true, block: 'index-' + found.length, ...call }); continue; } } if (span.startsWith('pixelbolt share ') && span.includes('')) { for (const fixture of ['coin.json', 'portal.wave.json', 'snowflakes.crystal.json', 'stilt-hut.powder.json', 'bouncing-pixel.bodies.json']) { for (const stdin of [false, true]) found.push({ line: i + 1, command: span, share: true, fixture, stdin }); } continue; } if (span.startsWith('import ') && span.includes(' --embedded ')) { const embedFlag = line.match(/`(--embed-recipe)`/); assert.ok(embedFlag, 'name the option that embeds the recipe'); for (const exporter of ['render', 'scene']) { assert.ok(line.includes('`' + exporter + '`'), 'name the exporter ' + exporter); found.push({ line: i + 1, command: span, share: true, fixture: 'coin.json', exporter, embedFlag: embedFlag[1] }); } continue; } const readmeCall = page === 'README.md' && /^(?:preview hero\.pixel\.json|(?:validate|gif) hero\.pixel\.json |node bin\/pixelbolt\.js sequence examples\/caption\.json )/.test(span); const skillInstall = /^(?:npx -y pixelbolt@latest |pixelbolt )skill install(?: |$)/.test(span); if (readmeCall || skillInstall) { found.push({ line: i + 1, block: 'inline-' + found.length, inline: true, command: span, ...(span.includes('sequence examples/caption.json') && { captionFrames: Number(line.match(/into (\d+) frames/)[1]) }) }); continue; } if (/^mcp --no-skill --root /.test(span)) { found.push({ line: i + 1, command: span, pluginLaunch: true }); continue; } const simple = /^(?:node bin\/pixelbolt\.js |pixelbolt )(?:schema|init|presets|preview(?: --open)?)$/.test(span) || /^npx -y pixelbolt@X\.Y\.Z --help$/.test(span); const help = /^(?:pixelbolt |node bin\/pixelbolt\.js |npx -y pixelbolt@\S+ )?help(?: |$)/.test(span); const tool = /^(pixel_\w+) (\{.*\})$/.exec(span); const quick = page === 'docs/agent-quick-start.md' && /^(?:pixelbolt presets$| --help|(?:pixelbolt |node bin\/pixelbolt\.js )?(?:validate|inspect|patch|render|gif|sequence|compile|autotile|scene|import|presets) )/.test(span); const patchGuide = ['README.md', 'docs/agent-quick-start.md', 'llms.txt'].includes(page) && /^(?:node bin\/pixelbolt\.js )?patch \S+ --changes /.test(span); const publicIndex = page === 'llms.txt' && span.startsWith('node bin/pixelbolt.js '); const sweep = /^(?:pixelbolt )?inspect (\S+) --rotate /.exec(span); const craftScene = page === 'docs/agent-craft.md' && section === 'Tiles and scenes' && /^(?:pixelbolt )?(?:scene|gif) .*(?:--image|--out) /.test(span); const skillStart = page === 'skills/pixelbolt-pixel-art/SKILL.md' && section === 'Where to start' && /^(?:presets |compile |autotile |gif (?:--preset | )|scene |render |init |import |inspect )/.test(span); const skillLoop = page === 'skills/pixelbolt-pixel-art/SKILL.md' && section === 'The loop' && /^(?:node bin\/pixelbolt\.js (?:validate|inspect|patch|render|gif) |inspect )/.test(span); const tutorial = page === 'docs/animate-your-sprite.md' || page === 'docs/fix-one-frame.md' || (page === 'docs/agent-guide.md' && section === 'Cutout walks from a PNG'); if (tutorial && span.startsWith('pixelbolt ')) { found.push({ line: i + 1, block: section, command: span }); } else if (tool) found.push({ line: i + 1, tool: tool[1], command: span, args: JSON.parse(tool[2]), fullSchema: tool[1] === 'pixel_help' && line.includes('\x60' + span + '\x60 returns the complete recipe JSON Schema') }); else if (simple || quick || help || skillVideo || skillWalk || gameSlices || guideCall || workflowCall || craftCall || craftPresetGIF || presetCompile || presetLookup || craftScene || skillStart || skillLoop || publicIndex || patchGuide || sweep) { found.push({ line: i + 1, block: 'inline-' + found.length, inline: true, command: span, ...(patchGuide && { patchGuide: line.slice(line.indexOf(span) + span.length) }), ...(skillWalk && { walkPreset: line.match(/\x60presets ([\w-]+) --out actor\.poses\.json\x60/)[1] }) }); if (sweep) { const rotation = /`(?:"rotate":|rotate:\s*)(\{[^`]+\})`/.exec(line); if (rotation) found.push({ line: i + 1, command: 'pixel_inspect ' + rotation[0], tool: 'pixel_inspect', args: { rotate: JSON.parse(rotation[1]) }, sourceFile: sweep[1], compareImage: atFlag(words(inlineCommand(span)), '--out') }); } } } } } if (page === 'README.md') found.push(...clientLaunchers(text)); if (page === 'docs/art-workflow.md') found.push(workflowTilemap(text)); remainingCli(page, text, found); remainingMentions(page, text, found); remainingPlainCli(page, text, found); return found.sort((a, b) => a.line - b.line); } // Shell examples use whole quoted arguments, including colours beginning with #. No shell is // launched. Refuse syntax we cannot read, so the check cannot accidentally execute another command. function words(line) { const result = []; let rest = line; while (rest && !rest.startsWith('#')) { const word = /^(?:"([^"]*)"|'([^']*)'|([^\s"';&|<>\x60]+))(?=\s|$)/.exec(rest); assert.ok(word, 'unsupported shell syntax in ' + line); result.push(word[1] ?? word[2] ?? word[3]); rest = rest.slice(word[0].length).trimStart(); } return result; } function inside(dir, relative) { const file = path.resolve(dir, relative); assert.ok(file.startsWith(path.resolve(dir) + path.sep), 'expected a path inside the example folder: ' + relative); return file; } async function copy(from, to) { await mkdir(path.dirname(to), { recursive: true }); await cp(from, to, { recursive: true }); } const atFlag = (args, flag) => args.includes(flag) ? args[args.indexOf(flag) + 1] : undefined; const jsonFile = async file => JSON.parse(await readFile(file, 'utf8')); function savedExamples(text) { const saved = new Map(); for (const match of text.matchAll(/Save this (?:JSON )?as `([^`]+)`[^\n]*\n\n```(?:json|js)\n([\s\S]*?)^```/gmi)) saved.set(match[1], match[2]); return saved; } // Inputs the prose asks the reader to supply. Missing checkout paths and misspelled outputs from // an earlier step must fail. Only the pages that introduce these particular inputs get a fixture. async function userInputs(page, text, dir) { const saved = savedExamples(text); if (page === 'README.md') { // The CLI walkthrough creates hero.pixel.json with init. Supply the reader's edit to its palette. saved.set('fix.json', JSON.stringify([{ set: 'palette.k', value: '#112233' }])); } if (page === 'llms.txt') { const tile = { version: 1, name: 'tile', width: 8, height: 8, palette: { k: '#000000' }, frames: [{ name: 'full', ops: [{ op: 'rect', w: 8, h: 8, color: 'k' }] }] }; tile.animations = { idle: { frames: ['full'] } }; saved.set('sample.json', JSON.stringify(tile)); saved.set('changes.json', JSON.stringify([{ set: 'palette.k', value: '#112233' }])); } if (page === 'skills/pixelbolt-pixel-art/SKILL.md') { // Its example delivery asks for 24 × 24 and six playback frames. Use the shipped // spirit's six distinct frames as one animation so that the promised check can pass. const spirit = await jsonFile(path.join(root, 'examples/forest-spirit.json')); spirit.animations = { idle: { frames: spirit.frames.map(frame => frame.name) } }; saved.set('sample.json', JSON.stringify(spirit)); saved.set('changes.json', JSON.stringify([{ set: 'frames[rest].duration', value: 150 }])); } if (page === 'docs/agent-guide.md') { await copyFile(path.join(root, 'examples/forest-spirit.json'), path.join(dir, 'sprite.json')); await copyFile(path.join(root, 'examples/forest-spirit.json'), path.join(dir, 'sample.json')); await copyFile(path.join(root, 'examples/hero.poses.json'), path.join(dir, 'actor.poses.json')); await copyFile(path.join(root, 'examples/iso-villager.stack.json'), path.join(dir, 'villager.stack.json')); await copyFile(path.join(root, 'examples/copper-rally.stack.json'), path.join(dir, 'car.stack.json')); saved.set('fix.json', JSON.stringify([{ paint: 'frames[rest]', value: [{ x: 0, y: 0, color: 'k' }] }])); const model = await jsonFile(path.join(root, 'examples/copper-rally.stack.json')); const jointed = text.split('### Jointed paths and wing membranes\n')[1].match(/\x60\x60\x60json\n([\s\S]+?)\n\x60\x60\x60/); Object.assign(model, JSON.parse(jointed[1])); Object.assign(model.palette, { s: '#234', k: '#121', g: '#567', c: '#987' }); saved.set('model.stack.json', JSON.stringify(model)); const study = text.match(/--pose-sheet study\.json[^\n]+?such as \x60(\{[^\x60]+\})\x60/); saved.set('study.json', study[1]); const chapter = text.split('## Cutout walks from a PNG\n')[1].split('\n## ')[0]; const manifest = chapter.match(/a cutout manifest for the bundled .*?`(examples\/[^`]+\.png)` is:\n\n```json\n([\s\S]*?)\n```/i); saved.set('cuts.json', manifest[2]); await copyFile(inside(root, manifest[1]), path.join(dir, 'sprite.png')); const track = chapter.match(/\x60(\{[^\x60]+\})\x60 as \x60track\.json\x60/); assert.ok(track, 'the walkthrough must supply a mask for its example sprite'); saved.set('track.json', track[1]); execFileSync(process.execPath, [cli, 'import', 'sprite.png', '--out', 'imported.pixel.json'], { cwd: dir }); } if (page === 'docs/agent-quick-start.md') { saved.set('sample.json', text.match(/```json\n([\s\S]+?)\n```/)[1]); const paint = text.match(/^- `(\{"paint": [^`]+\})`/m); saved.set('changes.json', JSON.stringify([JSON.parse(paint[1])])); // The walkthrough recommends its first rig as the starting character. A different kind // of rig could make an inapplicable inspect command appear to work. const rig = text.match(/For a character that walks[^\n]*?`(examples\/[^`]+\.poses\.json)`/)[1]; await copyFile(inside(root, rig), path.join(dir, 'actor.poses.json')); } if (['README.md', 'llms.txt', 'docs/agent-guide.md', 'docs/agent-quick-start.md', 'skills/pixelbolt-pixel-art/SKILL.md'].includes(page)) { await mkdir(path.join(dir, 'shots/prism'), { recursive: true }); for (const frame of ['prism_0001.png', 'prism_0002.png']) await copyFile(path.join(root, 'examples/sprite-walk.png'), path.join(dir, 'shots/prism', frame)); for (const name of ['forest-spirit.json', 'forest-spirit-normal.json', 'forest-spirit-lit.scene.json']) { await copyFile(path.join(root, 'examples', name), path.join(dir, name === 'forest-spirit-lit.scene.json' ? 'room.scene.json' : name)); } } if (['llms.txt', 'docs/agent-craft.md', 'docs/agent-guide.md', 'docs/art-workflow.md'].includes(page)) { // Both simulation formats stream a source directly. Short clips keep the all-guides walk small. for (const [kind, example] of [['bodies', 'bouncing-pixel'], ['powder', 'quarry-blast']]) { const source = await jsonFile(path.join(root, 'examples', example + '.' + kind + '.json')); (source.effects ?? source.clips)[example].frames = 4; const name = page === 'docs/art-workflow.md' ? (kind === 'bodies' ? 'match' : 'sand') : 'clip'; saved.set(name + '.' + kind + '.json', JSON.stringify(source)); } } if (page === 'docs/agent-craft.md') { const writeCompiled = (example, filename) => execFileSync(process.execPath, [cli, 'compile', path.join(root, 'examples', example), '--out', inside(dir, filename)], { cwd: dir }); writeCompiled('hero.poses.json', 'sample.json'); await copyFile(path.join(root, 'examples/hero.poses.json'), path.join(dir, 'actor.poses.json')); const sample = await jsonFile(path.join(dir, 'sample.json')); for (const [name, color] of [['variant.json', '#331100'], ['other.json', '#001133']]) { const variant = structuredClone(sample); variant.palette[Object.keys(sample.palette)[0]] = color; saved.set(name, JSON.stringify(variant)); } const parts = { version: 1, name: 'parts', width: 3, height: 1, palette: { k: '#fff' }, frames: ['body', 'plate', 'fin'].map((name, x) => ({ name, ops: [{ op: 'pixel', x, y: 0, color: 'k' }] })) }; saved.set('stack-parts.json', JSON.stringify(parts)); writeCompiled('iso-barrel.stack.json', 'barrel.json'); const barrel = await jsonFile(path.join(dir, 'barrel.json')); await writeFile(path.join(dir, 'barrel.json'), JSON.stringify({ ...barrel, name: 'barrel' })); saved.set('barrel.normals.json', text.match(/\x60(\{ "format": "pixelforge-normals", "version": 1, "recipe": "barrel.json" \})\x60/)[1]); await mkdir(path.join(dir, 'shots/prism'), { recursive: true }); for (const index of ['0001', '0002']) await copyFile(path.join(root, 'examples/sprite-walk.png'), path.join(dir, 'shots/prism/prism_' + index + '.png')); const camera = JSON.parse(text.match(/`"camera": (\[[^`]+\])`/)[1]); saved.set('room.scene.json', JSON.stringify({ format: 'pixelforge-scene', version: 1, name: 'hills', width: 48, height: 32, duration: 1200, camera, assets: { hill: await jsonFile(path.join(root, 'examples/forest-spirit.json')) }, instances: [{ name: 'background', asset: 'hill', at: [4, 4], frame: 'rest', parallax: 0.25 }] })); } if (page === 'docs/game-integration.md') { const scene = await jsonFile(path.join(root, 'examples/forest-spirit-lit.scene.json')); scene.assets.unlit = 'forest-spirit.json'; scene.assets.glow = { recipe: 'forest-spirit.json', emissive: 'forest-spirit.json' }; saved.set('room.scene.json', JSON.stringify(scene)); for (const name of ['forest-spirit.json', 'forest-spirit-normal.json', 'forest-spirit.normals.json']) await copyFile(path.join(root, 'examples', name), path.join(dir, name)); await copyFile(path.join(dir, 'forest-spirit.json'), path.join(dir, 'sample.json')); await copyFile(path.join(root, 'examples/copper-rally.stack.json'), path.join(dir, 'car.stack.json')); } if (page === 'docs/art-workflow.md') { await copyFile(path.join(root, 'examples/hero.poses.json'), path.join(dir, 'actor.poses.json')); await copyFile(path.join(root, 'examples/hero.poses.json'), path.join(dir, 'character.poses.json')); await copyFile(path.join(root, 'examples/forest-spirit-lit.scene.json'), path.join(dir, 'room.scene.json')); for (const pass of ['forest-spirit.json', 'forest-spirit-normal.json']) await copyFile(path.join(root, 'examples', pass), path.join(dir, pass)); const lamp = await jsonFile(path.join(root, 'examples/forest-spirit.json')); saved.set('lamp.json', JSON.stringify({ ...lamp, name: 'lamp' })); saved.set('lamp.normals.json', text.match(/\x60(\{ "format": "pixelforge-normals", "version": 1, "recipe": "lamp.json" \})\x60/)[1]); for (const name of ['base.json', 'rebuilt-base.json']) await copyFile(path.join(root, 'examples/forest-spirit.json'), path.join(dir, name)); saved.set('edits.json', JSON.stringify([{ paint: 'frames[rest]', value: [{ x: 0, y: 0, color: 'k' }] }])); saved.set('regions.json', JSON.stringify({ 'fern-tip': { space: 'canvas', x: 0, y: 0, w: 1, h: 1 } })); const sheet = await createBundle(await jsonFile(path.join(root, 'examples/forest-spirit.json'))); for (const name of ['corrected.png', 'sheet.png']) await writeFile(path.join(dir, name), sheet.files.get('forest-spirit.png')); await writeFile(path.join(dir, 'optional.atlas.json'), sheet.files.get('forest-spirit.atlas.json')); } for (const [name, body] of saved) { const dest = inside(dir, name); await mkdir(path.dirname(dest), { recursive: true }); await writeFile(dest, body, { flag: 'wx' }); } return saved; } async function checkOutput(dest) { if ((await stat(dest)).isDirectory()) { assert.ok((await readdir(dest)).length, 'empty export folder ' + dest); } else if (dest.endsWith('.json')) { await jsonFile(dest); } else { const bytes = await readFile(dest); assert.ok(bytes.length > 0, 'empty file ' + dest); if (dest.endsWith('.png')) assert.deepEqual([...bytes.subarray(0, 8)], [137, 80, 78, 71, 13, 10, 26, 10], dest); if (dest.endsWith('.gif')) assert.match(bytes.toString('ascii', 0, 6), /^GIF8[79]a$/, dest); } } // Instantiate the documentation's metavariables. Preserve every literal argument and output name. function inlineCommand(command) { const bindings = { '': 'variant.json', '': 'other.json', '': 'compare.png', '': 'look.png', '': 'drafts.png', '': 'new.scene.json', '': 'patched.json', '': 'actor.poses.json', '': 'bundle', '': 'shots/prism', '': 'sample.json', '': command.includes('--stack ') ? 'stack-parts.json' : 'sample.json', '': 'patched.json', '': 'assets', '': 'frames.png', '': 'validate', '': 'sample.json', '': 'patched.json', '': 'changes.json', '': 'contact.png', '': 'patched.json', '': 'diff.png', '': 'sprite.gif', '': 'assets', '': 'assets', '': command.startsWith('autotile ') ? 'examples/meadow.autotile.json' : 'actor.poses.json', '': 'map.png', '': 'room.scene.json', '': 'start.png', '': 'end.png', '': 'view.png', '': 'examples/sprite-walk.png', '': 'examples/hero.poses.json', '': 'examples/meadow.autotile.json', '': (command.includes('--draft-views') || command.includes('--motion')) ? 'actor.poses.json' : 'examples/forest-spirit.normals.json', '': command.includes('--animation ') ? 'run' : 'smoke-puff', '': 'craft', '': 'Operations', '': command.startsWith('presets ') ? 'smoke' : 'text', '
': command.includes('workflow') ? 'Fluid effects' : 'Rules' }; const bound = command.replace('[name]', 'smoke-puff').replace('[--animation name]', '--animation idle') .replace('[--scale 1-16]', '--scale 2').replace('[--background color]', '--background "#14213d"') .replace('[--prefix name_]', '--prefix prism_').replace(/\[(--[^\]]+)\]/g, '$1') .replace('--out ', '--out result.json').replace('--out ', '--out preset-source.json') .replace(/^init $/, 'init started.json') .replace(/\["?
"?\]|\[section\]/g, '"
"') .replace(/<[^>]+>/g, key => { assert.ok(Object.hasOwn(bindings, key), 'unbound placeholder ' + key); return bindings[key]; }); return /^(?:node |npx |pixelbolt )/.test(bound) ? bound : 'pixelbolt ' + bound; } async function runTool(item, cwd, products) { const args = item.sourceFile ? { ...item.args, source: await jsonFile(inside(root, item.sourceFile)) } : item.args; const messages = [ { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'docs', version: '1' } } }, { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: item.tool, arguments: args } } ]; const wire = execFileSync(process.execPath, [cli, ...(item.launchArgs ?? ['mcp', '--root', cwd, '--out', 'exports'])], { cwd, encoding: 'utf8', input: messages.map(m => JSON.stringify(m)).join('\n') + '\n', maxBuffer: 16 * 1024 * 1024 }); const reply = wire.trim().split('\n').map(line => JSON.parse(line)).find(message => message.id === 2); assert.ok(reply?.result && !reply.result.isError, item.command + ': ' + String(JSON.stringify(reply)).slice(0, 500)); const answer = reply.result.content.find(part => part.type === 'text')?.text; assert.ok(answer?.trim(), item.command); if (item.fullSchema) { const schema = new URL(HELP_TOPICS[item.args.topic], new URL('../src/help.js', import.meta.url)); assert.ok(answer.startsWith('{'), item.command + ' promises the schema but returned ' + answer.split('\n')[0]); assert.deepEqual(JSON.parse(answer), await jsonFile(schema)); } if (item.outline) assert.match(answer, /^# [^\n]+\n\n> A schema .*outlined\./); if (item.check) item.check(reply.result.content, answer); if (item.compareImage) { const info = JSON.parse(answer), image = reply.result.content.find(part => part.type === 'image'); assert.equal(info.frames, args.rotate.degrees.length); assert.match(info.sourceRevision, /^[0-9a-f]{12}$/); assert.ok(image && products.has(item.compareImage), 'expected both contact sheets'); assert.deepEqual(Buffer.from(image.data, 'base64'), await readFile(products.get(item.compareImage).file)); } if (item.tool === 'pixel_compile' && args.draftViews === undefined && args.sequence === undefined) { const info = JSON.parse(answer); assert.equal(info.ok, true); assert.match(info.revision, /^[\da-f]{12}$/); const recipe = await jsonFile(path.join(cwd, 'exports', '.revisions', info.revision + '.json')); assert.ok(recipe.frames.length, 'compiled revision has no frames'); } return answer; } async function checkReply(argv, reply, cwd, command) { assert.equal(reply.ok, true, command); if (argv[0] === 'inspect' && argv.includes('--motion')) { assert.equal(reply.motion.animation, atFlag(argv, '--motion')); if (argv.includes('--track')) { const track = reply.motion.cutout.track; assert.ok(track, 'missing pixel tracking results'); if (command.includes('hero.poses.json --motion walk-left --track track.json')) { assert.equal(track.checked, 4); assert.ok(track.passed && track.steps.every(step => step.visible === 4)); } } } if (argv[0] === 'inspect' && argv.includes('--rotate')) { assert.equal(reply.frames, atFlag(argv, '--rotate').split(',').length - 2); } if (argv[0] === 'skill') { assert.equal(reply.status, 'installed'); if (argv.includes('--dir')) assert.equal(path.dirname(reply.skill), atFlag(argv, '--dir')); const installed = inside(cwd, path.relative(cwd, path.join(reply.skill, 'SKILL.md'))); assert.match(await readFile(installed, 'utf8'), /pixelbolt-pixel-art/); } if (argv[0] === 'render') { const folder = inside(cwd, atFlag(argv, '--out')); await checkOutput(inside(folder, reply.sheet)); await checkOutput(inside(folder, reply.atlas)); if (argv.includes('--look')) await checkOutput(path.join(folder, 'look.png')); if (argv.includes('--expect')) assert.equal(reply.check.ok, true, JSON.stringify(reply.check)); } if (argv[0] === 'scene' && argv.includes('--out')) { const folder = inside(cwd, atFlag(argv, '--out')); for (const name of ['scene.png', 'scene.json']) { assert.ok(reply.files.includes(name), name); await checkOutput(inside(folder, name)); } } if (argv[0] === 'validate' && argv.includes('--fps')) { assert.equal(reply.frameGrid.fps, atFlag(argv, '--fps')); assert.ok(Array.isArray(reply.frameGrid.offGrid)); } if (argv[0] === 'sequence') { const folder = inside(cwd, atFlag(argv, '--out')); const manifest = await jsonFile(path.join(folder, 'sequence.json')); assert.equal((await readdir(folder)).filter(x => x.endsWith('.png')).length, manifest.frames); assert.equal(manifest.frames, reply.frames); } } async function executeCommand(page, item, cwd, argv, script) { if (argv[0] === 'preview') { const input = argv[1] ? await jsonFile(inside(cwd, argv[1])) : null; const route = input?.format === 'pixelforge-scene' ? '/scene-source.json' : '/project.json'; const served = await previewSource(argv, cwd, route); if (!input || served?.format === input.format) assert.deepEqual(served, input); else assert.ok(served?.frames?.length && served.name === input.name, 'preview must serve the compiled example'); return; } const env = { ...process.env, HOME: cwd, USERPROFILE: cwd }; // The module guide illustrates the error that sends a reader from a misplaced schema // path to its own help topic. Follow the actual suggestion in a second invocation. if (page === 'docs/modules.md' && item.command === 'help schema scenes') { const misplaced = spawnSync(process.execPath, [cli, ...argv], { cwd, env, encoding: 'utf8' }); assert.equal(misplaced.status, 1, item.command); const suggested = /run pixelbolt (help scenes)$/.exec(JSON.parse(misplaced.stderr).error); assert.ok(suggested, misplaced.stderr); assert.match(execFileSync(process.execPath, [cli, ...words(suggested[1])], { cwd, env, encoding: 'utf8' }), /schema/i); return; } const stdout = execFileSync(process.execPath, [script, ...argv], { cwd, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024, windowsHide: true }); if (item.expansion) { const dest = atFlag(argv, '--out'); assert.ok(dest, 'the documented command must save the expansion to a file'); const expanded = await jsonFile(inside(cwd, dest)); assert.equal(expanded.format, 'pixelforge-poses'); assert.ok(expanded.poses.length); assert.equal(expanded.motions, undefined); } if (argv[0] === 'schema') { assert.deepEqual(JSON.parse(stdout), await jsonFile(path.join(root, 'schema.json'))); } else if (argv[0] === 'presets') { assert.ok(Object.keys(JSON.parse(stdout)).length, 'expected a preset reply'); } else if (argv[0] === 'help' || argv.includes('--help')) { assert.ok(stdout.trim(), 'expected help or preset text'); } else if (script === cli) { const reply = JSON.parse(stdout); if (argv[0] === 'compile' && argv.includes('--expand') && !argv.includes('--out')) { assert.equal(reply.format, 'pixelforge-poses'); assert.ok(reply.poses.length); assert.equal(reply.motions, undefined); return reply; } await checkReply(argv, reply, cwd, item.command); if (page === 'docs/agent-craft.md' && argv[0] === 'scene' && argv.includes('--out')) { const folder = inside(cwd, atFlag(argv, '--out')); const godot = await readFile(path.join(folder, 'scene.tscn'), 'utf8'); assert.match(godot, /type="Camera2D"/); assert.match(godot, /type="Parallax2D"/); assert.match(await readFile(path.join(folder, 'scene.tmx'), 'utf8'), / clip.direction).sort(), ['down', 'left', 'right', 'up']); if (item.materialGuide) { const out = inside(cwd, atFlag(argv, '--out')); const { assets } = await jsonFile(path.join(out, 'alignment.json')); for (const [id, passes] of Object.entries({ spirit: ['color', 'normal', 'normalYUp'], unlit: ['color'], glow: ['color', 'emissive'] })) { const asset = assets[id]; assert.deepEqual(Object.keys(asset.passes).sort(), passes.sort()); for (const file of Object.values(asset.passes)) await checkOutput(inside(out, file)); const resource = await readFile(inside(out, asset.godot), 'utf8'); assert.ok(resource.includes(id === 'spirit' ? 'canvas_texture.tres' : 'color.png')); } assert.match(item.materialGuide, /when the asset supplies (?:those|these) passes/i, 'identify optional material PNGs'); } if (item.normalFile) { const folder = inside(cwd, atFlag(argv, '--out')); for (const suffix of ['.png', '.normal.png', '.normal_y_up.png', '.canvas.tres', '.tres']) await checkOutput(inside(folder, reply.name + suffix)); assert.ok((await readFile(path.join(folder, reply.name + '.tres'), 'utf8')).includes(reply.name + '.canvas.tres')); } if (page === 'docs/art-workflow.md' && argv[0] === 'scene' && atFlag(argv, '--view') === 'depth') assert.ok(reply.depth); if (item.simulation) { const manifest = await jsonFile(inside(cwd, atFlag(argv, '--out') + '/sequence.json')); assert.equal(manifest.source, item.simulation); assert.ok(manifest.frames > 1); } if (item.captionFrames) { const manifest = await jsonFile(inside(cwd, atFlag(argv, '--out') + '/sequence.json')); assert.deepEqual([manifest.frames, manifest.width, manifest.height], [item.captionFrames, 1920, 1080]); assert.equal(manifest.placement.y + manifest.placement.height, manifest.height - 64); } if (item.patchGuide) { const changed = reply.frames.changed; const entries = Array.isArray(changed) ? changed : [changed]; assert.ok(entries.length && entries.every(entry => entry.pixels > 0 && entry.box), 'patch must show the affected area'); if (page === 'llms.txt') { const [tile] = entries; assert.deepEqual(tile.box, { x: 0, y: 0, w: 8, h: 8 }); assert.equal(tile.pixels, 64); assert.equal(tile.changes, undefined); assert.deepEqual(tile.transitions, [{ from: '#000000', to: '#112233 (k)', pixels: 64 }]); } assert.match(item.patchGuide, /\bbox\b/i, 'show readers where to find the affected pixels'); assert.match(item.patchGuide, /--region\b/, 'explain how to inspect the reported box'); } if (page === 'docs/animate-your-sprite.md' && atFlag(argv, '--view') === 'walks') { const directions = reply.walkReview.clips.map(clip => clip.direction).sort(); assert.deepEqual(directions, ['down', 'left', 'right', 'up']); } if (page === 'docs/animate-your-sprite.md' && item.block === 'Four-direction walks from drawn parts' && argv[0] === 'render') { const folder = inside(cwd, atFlag(argv, '--out')); const resource = await readFile(inside(folder, reply.name + '.tres'), 'utf8'); for (const name of ['walk-down', 'walk-left', 'walk-right', 'walk-up']) assert.ok(resource.includes('"' + name + '"'), name); } if (page === 'llms.txt' && argv[0] === 'inspect' && argv.includes('--region')) { assert.deepEqual(reply.grids, [{ frame: 'full', rows: Array(8).fill('kkkkkkkk') }]); const saved = await jsonFile(inside(cwd, argv[1])); assert.equal(saved.palette.k, '#112233'); } return reply; } } async function runShell(page, item, cwd, supplied, saved, products) { // Copy auxiliary files as a group, since, e.g., the scene reads its diffuse and normal assets. await cp(supplied, cwd, { recursive: true }); let attached = item.attached; if (attached?.includes('sample-for-options.json')) { const frames = Array.from({ length: 12 }, (_, index) => ({ name: 'f' + index, ops: [{ op: 'pixel', x: index % 4, y: 0, color: '#fff' }] })); await writeFile(inside(cwd, 'sample-for-options.json'), JSON.stringify({ version: 1, name: 'sample', width: 4, height: 4, frames })); if (attached.includes('')) { await writeFile(inside(cwd, 'expect.json'), JSON.stringify({ width: 4, height: 4 })); attached = attached.replace('', 'expect.json'); } } if (attached?.includes('')) { const source = await jsonFile(products.get('hero.poses.json').file); const pose = source.poses.find(pose => pose.name.startsWith('stand-')); attached = attached.replace('', pose.parts[0].name).replace('', pose.name); } const command = item.simulation ? item.command.replace('', 'clip.' + item.simulation + '.json') : item.normalFile ? item.command.replace('', item.normalFile) : attached ?? item.command; const argv = words(item.inline ? inlineCommand(command) : command).map( arg => arg.startsWith('$HOME/') ? inside(cwd, arg.slice(6)) : arg); if (page === 'README.md' && item.command === 'preview hero.pixel.json') { // The reader previews their own existing recipe before the separate init walkthrough. await copyFile(path.join(root, 'examples/forest-spirit.json'), inside(cwd, 'hero.pixel.json')); } const region = argv.indexOf('x,y,w,h'); if (region >= 0 && argv[region - 1] === '--region') { const box = argv.map(name => products.get(name)?.box).find(Boolean); argv[region] = box ? [box.x, box.y, box.w, box.h].join(',') : '0,0,2,2'; } const launcher = argv.shift(); const script = launcher === 'node' ? argv.shift() : undefined; if (launcher === 'npx') { assert.equal(argv.shift(), '-y'); assert.ok(['pixelbolt@latest', 'pixelbolt@X.Y.Z'].includes(argv.shift()), 'expected a Pixelbolt package pin'); } else assert.ok(launcher === 'pixelbolt' || launcher === 'node', 'unknown launcher ' + launcher); if (script && script !== 'bin/pixelbolt.js') assert.ok(saved.has(script) && script.endsWith('.mjs'), 'undocumented script ' + script); const helper = saved.get(script); const names = helper ? [...helper.matchAll(/fs\.readFileSync\('([^']+)'/g)].map(m => m[1]) : argv; const outputs = helper ? [...helper.matchAll(/fs\.writeFileSync\('([^']+)'/g)].map(m => m[1]) : outputFlags.map(flag => atFlag(argv, flag)).filter(Boolean); if (argv[0] === 'init') outputs.push(argv[1] ?? 'sprite.pixel.json'); for (const name of outputs) inside(cwd, name); for (const name of new Set(names)) { if (name.startsWith('examples/') || name.startsWith('showcase/diorama/art/')) await copy(inside(root, path.dirname(name)), inside(cwd, path.dirname(name))); const prior = products.get(name); if (prior && (!outputs.includes(name) || prior.block === item.block)) await copy(prior.file, inside(cwd, name)); } const reply = await executeCommand(page, item, cwd, argv, helper ? inside(cwd, script) : cli); for (const name of outputs) { const file = inside(cwd, name); await checkOutput(file); const changed = argv[0] === 'patch' && name === atFlag(argv, '--out') && reply?.frames.changed; const box = (Array.isArray(changed) ? changed[0] : changed)?.box; products.set(name, { file, block: item.block, box }); } } // Each build starts in its own project. The game-integration guide supplies the manifest and // the reader supplies three art files. A successful build provides the record for subsequent checks. async function runDocumentedBuild(item, cwd, products) { const args = item.command.replace(/^(?:pixelbolt |node bin\/pixelbolt\.js |npx pixelbolt@ )/, '').split(/\s+/); const run = argv => JSON.parse(execFileSync(process.execPath, [cli, ...argv], { cwd, encoding: 'utf8' })); const manifest = 'pixelbolt.build.json'; const logo = { version: 1, name: 'logo', width: 32, height: 32, palette: { k: '#000' }, frames: [{ name: 'on', ops: [{ op: 'fill', color: 'k' }] }] }; await mkdir(path.join(cwd, 'art')); await writeFile(path.join(cwd, 'art/logo.pixel.json'), JSON.stringify(logo)); if (args.includes('--init')) { const result = run(args); assert.ok(result.ok); const source = await jsonFile(inside(cwd, result.manifest)); assert.deepEqual(source.entries.map(entry => entry.file), ['art/logo.pixel.json']); assert.equal(source.pixelbolt, (await jsonFile(path.join(root, 'package.json'))).version); return; } const built = products.get('built-manifest'); if (built) { await cp(built, cwd, { recursive: true }); } else { const guide = await readFile(path.join(root, 'docs/game-integration.md'), 'utf8'); const sample = guide.split('## Build every asset from a manifest')[1].match(/```json\s*([\s\S]*?)\s*```/); await writeFile(path.join(cwd, manifest), sample[1]); await copyFile(path.join(root, 'examples/forest-spirit.json'), path.join(cwd, 'art/hero.pixel.json')); await copyFile(path.join(root, 'examples/smoke-puff.fluid.json'), path.join(cwd, 'art/smoke.fluid.json')); if (args.includes('--check')) assert.ok(run(['build']).ok); } const result = run(args); assert.ok(result.ok); assert.deepEqual(Object.keys((await jsonFile(inside(cwd, result.record))).entries).sort(), ['hero', 'logo', 'smoke', 'torch']); for (const name of ['docs/hero.gif', 'public/sprites/forest-spirit.png', 'public/sprites/forest-spirit.atlas.json', 'public/fx/campfire.png', 'public/fx/campfire.atlas.json', 'build/smoke/preview.html']) await checkOutput(inside(cwd, name)); for (const size of [32, 192]) { const image = decodePNG(await readFile(path.join(cwd, 'public/icon-' + size + '.png'))); assert.deepEqual([image.width, image.height], [size, size]); } if (built || args.includes('--check')) assert.equal(result.written?.length ?? 0, 0); else assert.ok(result.written.length); if (!built) products.set('built-manifest', cwd); if (item.checkGuide !== undefined) { const hero = path.join(cwd, 'art/hero.pixel.json'); const source = await jsonFile(hero); source.palette.k = '#123456'; await writeFile(hero, JSON.stringify(source)); const stale = spawnSync(process.execPath, [cli, ...args], { cwd, encoding: 'utf8' }); assert.equal(stale.status, 1); assert.equal(stale.stdout, ''); const report = JSON.parse(stale.stderr); const sheet = report.problems.find(problem => problem.reason === 'stale' && problem.entry === 'hero' && problem.output?.startsWith('sheet ')); assert.equal(sheet?.output, 'sheet public/sprites'); assert.equal(sheet.file, undefined); assert.match(item.checkGuide, /output group/i, 'explain which output group the stale-input check identifies'); const atlas = path.join(cwd, 'public/sprites/forest-spirit.atlas.json'); const image = path.join(cwd, 'public/sprites/forest-spirit.png'); const originalImage = await readFile(image), originalAtlas = await readFile(atlas); assert.ok(run(['build']).ok); assert.deepEqual(await readFile(atlas), originalAtlas); assert.notDeepEqual(await readFile(image), originalImage); } } // Exercise both input forms advertised for share, and import the actual PNG produced by // each exporter named alongside --embed-recipe. Each source is complete in its fresh folder. async function runShareExample(item, cwd) { const recipe = await jsonFile(path.join(root, 'examples', item.fixture)); const source = item.exporter === 'scene' ? { format: 'pixelforge-scene', version: 1, name: 'room', width: 48, height: 32, assets: { actor: recipe }, instances: [{ name: 'actor', asset: 'actor', at: [0, 0] }] } : recipe; const text = JSON.stringify(source); await writeFile(path.join(cwd, 'source.json'), text); const run = (args, input) => JSON.parse(execFileSync(process.execPath, [cli, ...args], { cwd, encoding: 'utf8', input })); if (item.exporter) { const bundle = run([item.exporter, 'source.json', '--out', 'bundle', item.embedFlag]); const args = words(item.command); const inputs = args.slice(args[0] === 'pixelbolt' ? 1 : 0); await copyFile(inside(cwd, 'bundle/' + (bundle.sheet ?? 'scene.png')), inside(cwd, inputs[1])); const restored = run(inputs); assert.deepEqual(await jsonFile(inside(cwd, atFlag(inputs, '--out'))), source); assert.equal(restored.embedded.kind, item.exporter === 'render' ? 'project' : 'scene'); } else { const input = item.stdin ? '-' : 'source.json'; const args = words(item.command.replace('', input)); const reply = run(args.slice(1), item.stdin ? text : undefined); const recovered = await readShareLink(reply.link); assert.deepEqual(recovered.recipe, source); assert.equal(recovered.kind, reply.kind); assert.equal(recovered.version, reply.version); assert.equal(reply.characters, reply.link.length); } } async function runPoseTool(item, cwd, supplied, products) { const prior = products.get('cutout-import'), compiled = products.get(item.cutout ? 'cutout-compiled' : 'rig-compiled'); const args = {}; if (item.tool === 'pixel_import') { const bytes = await readFile(inside(supplied, 'sprite.png')); if (item.form === 'data') args.data = bytes.toString('base64'); else { args.path = 'sprite.png'; await copyFile(inside(supplied, args.path), inside(cwd, args.path)); } args.cutout = await jsonFile(inside(supplied, 'cuts.json')); args.name = 'hero'; } else { for (const [key, value] of Object.entries(item.template)) { if (value === '') args[key] = await jsonFile(item.cutout ? prior.sourceFile : path.join(root, 'examples/hero.poses.json')); else if (value === '') args[key] = compiled.metadata; else if (value === '' || value === '') { const stored = value === '' ? prior : compiled; const id = value === '' ? stored.sourceRevision : stored.revision; await copy(inside(stored.directory, 'exports/.revisions/' + id + '.json'), inside(cwd, 'exports/.revisions/' + id + '.json')); args[key] = id; } else args[key] = value; } } const answer = JSON.parse(await runTool({ ...item, args, check(parts) { assert.ok(parts.some(part => part.type === 'image' && decodePNG(Buffer.from(part.data, 'base64')).width > 0), item.command); } }, cwd)); if (item.tool === 'pixel_import') { assert.match(answer.revision, /^[0-9a-f]{12}$/); assert.match(answer.sourceRevision, /^[0-9a-f]{12}$/); const source = await jsonFile(answer.sourceFile); assert.equal(source.format, 'pixelforge-poses'); assert.deepEqual(source, await jsonFile(inside(cwd, 'exports/.revisions/' + answer.sourceRevision + '.json'))); if (prior) assert.deepEqual([answer.revision, answer.sourceRevision], [prior.revision, prior.sourceRevision]); products.set('cutout-import', { ...answer, directory: cwd }); } else if (args.metadata === true) { assert.ok(answer.metadata); products.set(item.cutout ? 'cutout-compiled' : 'rig-compiled', { ...answer, directory: cwd }); } else if (args.draftViews) { for (const [name, degrees] of Object.entries(args.draftViews)) { for (const degree of degrees) assert.ok(answer.drafts[name].views[degree].rows.length); } assert.equal(answer.revision, undefined); } else if (args.view === 'walks') { const cutout = await jsonFile(inside(supplied, 'cuts.json')); const facings = Object.keys(cutout.views); for (const [facing, view] of Object.entries(cutout.views)) { if (view.mirror) facings.push({ left: 'right', right: 'left' }[facing]); } assert.deepEqual(answer.walkReview.clips.map(clip => clip.direction).sort(), facings.sort()); } else { assert.equal(answer.motion.animation, args.animation); if (args.track) { const tracked = answer.motion.cutout.track; assert.equal(tracked.checked, 4); assert.ok(tracked.passed && tracked.steps.every(step => step.visible === 4)); } } } // Keep one short animation so the published GIF and saveAs examples have an unambiguous target. async function runExportExample(item, cwd) { const project = { version: 1, name: 'spirit', width: 4, height: 3, frames: [{ name: 'rest', duration: 100, ops: [{ op: 'pixel', x: 1, y: 1, color: '#fff' }] }, { name: 'blink', duration: 200, ops: [{ op: 'pixel', x: 2, y: 1, color: '#abc' }] }], animations: { idle: { frames: ['rest', 'blink', 'rest'] } } }; const opts = item.options, scene = { format: 'pixelforge-scene', version: 1, name: 'room', width: 8, height: 6, duration: 120, assets: { actor: project }, instances: [{ name: 'actor', asset: 'actor', at: [1, 1] }] }; const args = item.tool === 'pixel_scene' ? { scene, ...opts } : { project, ...opts }; if (opts.saveAs?.godot) { await mkdir(inside(cwd, 'game')); await writeFile(inside(cwd, 'game/project.godot'), 'config_version=5\n'); } const report = JSON.parse(await runTool({ ...item, args }, cwd)); if (opts.saveAs) { assert.equal(report.saved.length, Object.keys(opts.saveAs).length); for (const [key, dest] of Object.entries(opts.saveAs)) { const target = inside(cwd, dest), entry = report.saved.find(saved => saved.path === target); assert.ok(entry, 'missing saved ' + key + ' at ' + target); await checkOutput(target); if (key === 'godot') assert.ok((await readFile(target, 'utf8')).includes(path.basename(opts.saveAs.sheet))); else if (key === 'atlas') assert.equal((await jsonFile(target)).meta.image, path.basename(opts.saveAs.sheet)); else assert.deepEqual(await readFile(target), await readFile(inside(report.directory, entry.file))); } } if (opts.share) assert.deepEqual((await readShareLink(report.share.link)).recipe, project); if (opts.embedRecipe) assert.deepEqual((await readEmbeddedRecipe(await readFile(inside(report.directory, 'spirit.png')))).recipe, project); if (opts.gif) { if (args.scene) await checkOutput(inside(report.directory, report.gif.file)); else { for (const animation of Object.keys(project.animations)) { const bytes = await readFile(inside(report.directory, 'gifs/' + animation + '.gif')); const scale = opts.gif.scale ?? 1; assert.deepEqual([bytes.readUInt16LE(6), bytes.readUInt16LE(8)], [project.width * scale, project.height * scale]); } } } if (opts.sequence) { const dir = inside(report.directory, report.sequence.directory), info = await jsonFile(inside(dir, 'sequence.json')); assert.equal(info.frames, (await readdir(dir)).filter(name => name.endsWith('.png')).length); assert.deepEqual([info.width, info.height], [report.sequence.width, report.sequence.height]); if (opts.sequence.size === '1080p') assert.deepEqual([info.width, info.height], [1920, 1080]); } if (opts.export) await checkOutput(inside(report.directory, 'scene.tscn')); if (item.tiledAssets) { const alignment = await jsonFile(inside(report.directory, 'alignment.json')); assert.match(await readFile(inside(report.directory, alignment.tiled), 'utf8'), / name + ': ' + project.frames.find(frame => frame.name === name).duration + ' ms'); assert.deepEqual(report.preview.cells, timing); } } async function runEditExample(item, cwd, products) { let args; const prior = products.get('edited-revision'); if (prior) { await copy(prior.file, inside(cwd, 'exports/.revisions/' + prior.id + '.json')); args = { revision: prior.id }; } else if (item.paint) { const project = { version: 1, name: 'actor', width: 16, height: 16, palette: { k: '#17191d' }, frames: [{ name: 'blink', ops: [{ op: 'fill', color: '#fff' }] }] }; args = { project, changes: [item.paint] }; } else args = { project: await jsonFile(inside(root, item.input)) }; if (item.changesFile) args.changes = await jsonFile(inside(root, item.changesFile)); if (item.frames) Object.assign(args, { frames: item.frames, grid: true }); let gridText; const info = JSON.parse(await runTool({ ...item, args, check(parts) { assert.ok(parts.some(part => part.type === 'image' && decodePNG(Buffer.from(part.data, 'base64')).height > 0)); if (item.frames) gridText = parts.find(part => part.type === 'text' && part.text.startsWith('Palette-key grids'))?.text; } }, cwd)); const revisionFile = inside(cwd, 'exports/.revisions/' + info.revision + '.json'); if (item.paint) { const saved = await jsonFile(revisionFile); assert.deepEqual(saved.frames[0].pixels, item.paint.value); assert.equal(info.frames.changed[0]?.pixels ?? info.frames.changed.pixels, 1); } else if (item.changesFile) { assert.ok(info.edits.length && info.frames.changed.length); assert.deepEqual(await jsonFile(revisionFile), await jsonFile(products.get(item.result).file)); products.set('edited-revision', { id: info.revision, file: revisionFile }); } else { assert.equal(info.revision, prior.id); const cliGrid = JSON.parse(execFileSync(process.execPath, [cli, 'inspect', revisionFile, '--frames', item.frames.join(','), '--grid'], { cwd, encoding: 'utf8' })); assert.ok(gridText, 'MCP must return the selected palette-key grids'); assert.deepEqual(cliGrid.grids.map(g => g.frame), item.frames); for (const { frame, rows } of cliGrid.grids) { const block = gridText.split('\n\n').find(text => text.startsWith(frame + '\n')); const pixels = block.split('\n').slice(-rows.length).map(row => row.replace(/^\s*\d+ /, '')); assert.deepEqual(pixels, rows); } } } async function runCompileExample(item, cwd, supplied, products) { const args = { ...item.options }; const prior = products.get('compile-example'); if (item.study) { if (item.study === 'source') args.source = await jsonFile(inside(supplied, 'model.stack.json')); else { const id = prior[item.study]; await copy(inside(prior.cwd, 'exports/.revisions/' + id + '.json'), inside(cwd, 'exports/.revisions/' + id + '.json')); args.revision = id; } if (item.study !== 'revision') args.poseSheet = await jsonFile(inside(supplied, 'study.json')); } else if (item.chain === 'normal-base') args.project = await jsonFile(path.join(root, 'examples/forest-spirit.json')); else if (item.chain === 'use' || item.chain === 'normal-use') { await copy(inside(prior.cwd, 'exports/.revisions/' + prior.revision + '.json'), inside(cwd, 'exports/.revisions/' + prior.revision + '.json')); if (item.chain === 'use') args.revision = prior.revision; else args.source = { format: 'pixelforge-normals', version: 1, recipe: { revision: prior.revision } }; } else if (item.preset) args.preset = item.preset; else if (item.suppliedFile) args.source = await jsonFile(inside(supplied, item.suppliedFile)); else { args.source = item.document ?? await jsonFile(path.join(root, 'examples', item.filename ?? compileExamples[item.kind] + '.' + item.kind + '.json')); if (item.kind === 'normals') await copyFile(path.join(root, 'examples', args.source.recipe), inside(cwd, args.source.recipe)); } const info = JSON.parse(await runTool({ ...item, args, check(parts) { if (item.secondImage) assert.equal(parts.filter(part => part.type === 'image').length, 2); } }, cwd)); if (item.chain === 'normal-base' || item.chain === 'save' || item.study === 'source') products.set('compile-example', { ...info, cwd }); if (item.study && item.study !== 'revision') { assert.match(info.sourceRevision, /^[0-9a-f]{12}$/); if (item.study === 'sourceRevision') assert.equal(info.revision, prior.revision); } if (item.options?.sequence) { const sequence = await jsonFile(inside(info.directory, 'sequence/sequence.json')); assert.equal(info.sequence.frames, sequence.frames); assert.ok(item.kind === 'bodies' ? sequence.figures : sequence.ended); const files = (await readdir(inside(info.directory, 'sequence'))).filter(name => name.endsWith('.png')).sort(); assert.equal(files.length, sequence.frames); const image = decodePNG(await readFile(inside(info.directory, 'sequence/' + files[0]))); assert.deepEqual([image.width, image.height], [sequence.width, sequence.height]); } else if (item.options?.slices) { const recipe = await jsonFile(inside(cwd, 'exports/.revisions/' + info.revision + '.json')); const names = recipe.frames.map(frame => frame.name); assert.equal(names[0], 'slice-0'); assert.deepEqual(recipe.animations.slices.frames, names); } else if (item.tool === 'pixel_render') { assert.equal(info.revision, prior.revision); await checkOutput(inside(info.directory, 'twin-ripple.png')); } } async function runReviewExample(item, cwd, supplied) { const args = { ...item.options }; let project = await jsonFile(path.join(root, 'examples/forest-spirit.json')); if (item.camp) { args.scene = item.camp; for (const [source, dest] of [['meadow.autotile.json', 'meadow.json'], ['campfire.fluid.json', 'campfire.json']]) { execFileSync(process.execPath, [cli, 'compile', path.join(root, 'examples', source), '--out', dest], { cwd }); } for (const [src, dest] of [['forest-spirit.json', 'spirit.json'], ['forest-spirit-normal.json', 'spirit-normal.json']]) await copyFile(path.join(root, 'examples', src), inside(cwd, dest)); } else if (item.material) { const [recipe, normal] = item.material; project = await jsonFile(inside(supplied, recipe)); args.normal = await jsonFile(inside(supplied, normal)); await copyFile(inside(supplied, recipe), inside(cwd, recipe)); args.project = project; } else if (item.frameCounts) { project.animations = Object.fromEntries(Object.entries(item.frameCounts).map(([name, count]) => [name, { frames: Array.from({ length: count }, (_, index) => project.frames[index % project.frames.length].name) }])); args.project = project; } else if (item.character || item.preset) { args.source = await jsonFile(path.join(root, 'examples', (item.preset ?? 'hero') + '.poses.json')); } else if (item.tool === 'pixel_scene') { args.scene = { format: 'pixelforge-scene', version: 1, name: 'room', width: 72, height: 48, assets: { actor: project }, instances: [{ name: 'actor', asset: 'actor', at: [12, 16] }] }; } else if (item.tool !== 'pixel_compile') args.project = project; if (item.lighting) { args.scene = await jsonFile(path.join(root, 'examples/forest-spirit-lit.scene.json')); for (const pass of ['forest-spirit.json', 'forest-spirit-normal.json']) await copyFile(path.join(root, 'examples', pass), inside(cwd, pass)); } const info = JSON.parse(await runTool({ ...item, args, check(parts) { if (item.tool !== 'pixel_validate') assert.ok(parts.find(part => part.type === 'image'), item.command); } }, cwd)); if (item.camp && args.export) await checkOutput(inside(info.directory, 'scene.tscn')); if (item.camp && args.gif) await checkOutput(info.gif.file); if (item.material) { for (const suffix of ['.normal.png', '.normal_y_up.png', '.canvas.tres', '.tres']) await checkOutput(inside(info.directory, project.name + suffix)); } if (args.draftViews) for (const [part, angles] of Object.entries(args.draftViews)) { assert.deepEqual(Object.keys(info.drafts[part].views).sort(), angles.map(String).sort()); } if (args.view === 'walks') assert.deepEqual(info.walkReview.clips.map(c => c.direction).sort(), ['down', 'left', 'right', 'up']); if (args.view === 'motion') assert.equal(info.motion.animation, args.animation); if (item.lighting) assert.equal(info.lights.length, args.scene.lighting.lights.length); if (typeof args.frames === 'number') assert.equal(info.frames, args.frames); if (Array.isArray(args.frames)) assert.equal(info.cells.length, args.frames.length); if (args.expect) assert.equal(info.check.ok, true, JSON.stringify(info.check)); if (args.fps) assert.ok(info.frameGrid.animations); if (args.scale && item.tool === 'pixel_render') { const recipe = await jsonFile(inside(cwd, 'exports/.revisions/' + info.revision + '.json')); assert.equal(recipe.sheet.scale, args.scale); } } async function runReferenceExample(item, cwd, products) { const project = { version: 1, name: 'badge', width: 2, height: 2, palette: { a: '#123456' }, frames: [{ name: 'on', duration: 100, ops: [{ op: 'pixel', x: 0, y: 0, color: 'a' }] }, { name: 'off', duration: 100, ops: [] }], animations: { idle: { frames: ['on', 'off'] } } }; const prior = products.get('reference-example'); const args = {}; if (item.input === 'data' || item.input === 'path') { const src = path.join(root, 'examples/sprite-walk.png'); if (item.input === 'data') args.data = (await readFile(src)).toString('base64'); else { args.path = 'sprite-walk.png'; await copyFile(src, inside(cwd, args.path)); } } else if (item.input === 'project') args.project = project; else if (item.input === 'preset') args.preset = 'smoke-puff'; else { await copy(prior.file, inside(cwd, 'exports/.revisions/' + prior.id + '.json')); if (item.input === 'revision') args.revision = prior.id; else args.scene = { format: 'pixelforge-scene', version: 1, name: 'room', width: 4, height: 4, assets: { badge: { revision: prior.id } }, instances: [{ name: 'badge', asset: 'badge', at: [1, 1] }] }; } if (item.tool === 'pixel_patch') args.changes = [{ paint: 'frames[on]', value: [{ x: 1, y: 1, color: 'a' }] }]; if (item.withGif) args.gif = {}; const info = JSON.parse(await runTool({ ...item, args, check(parts) { if (item.tool !== 'pixel_validate') assert.ok(parts.some(part => part.type === 'image')); } }, cwd)); if (item.tool === 'pixel_validate' || item.tool === 'pixel_patch') { const file = inside(cwd, 'exports/.revisions/' + info.revision + '.json'); const result = await jsonFile(file); if (item.tool === 'pixel_patch') assert.deepEqual(result.frames[0].pixels, args.changes[0].value); else { assert.deepEqual(result, args.project ?? await jsonFile(prior.file)); products.set('reference-example', { id: info.revision, file }); } if (item.tool === 'pixel_patch' && item.input === 'revision') products.set('reference-example', { id: info.revision, file }); } else if (item.tool === 'pixel_import') { const recipe = await jsonFile(inside(cwd, 'exports/.revisions/' + info.revision + '.json')); const png = decodePNG(await readFile(path.join(root, 'examples/sprite-walk.png'))); const frame = renderProject(recipe).frames[0]; assert.deepEqual(Buffer.from(frame.data), Buffer.from(png.data)); assert.deepEqual([recipe.width, recipe.height], [png.width, png.height]); } else if (item.tool === 'pixel_render') { await checkOutput(inside(info.directory, project.name + '.png')); if (item.withGif) await checkOutput(inside(info.directory, 'gifs/idle.gif')); } } async function runPresetExample(item, cwd, products) { if (item.tool === 'pixel_help') { const info = JSON.parse(await runTool({ ...item, args: { topic: 'preset', name: item.name } }, cwd)); assert.equal(info.name, item.name); products.set('help-preset', info.source); } else { const source = products.get('help-preset'); const args = item.tool === 'pixel_compile' ? { source } : { project: source }; const info = JSON.parse(await runTool({ ...item, args }, cwd)); assert.match(info.revision, /^[0-9a-f]{12}$/); } } async function runPatchTable(item, cwd, products) { const frames = ['still', 'blink', 'run-2'].map(name => ({ name, duration: 100, ops: [{ op: 'rect', x: 9, y: 7, w: 3, h: 2, color: 'g' }, { op: 'pixel', x: 10, y: 7, color: 'k' }, { op: 'pixel', x: 22, y: 18, color: 'h' }], layers: [{ name: 'plume', ops: [{ op: 'pixel', x: 1, y: 2, color: 's' }] }] })); const project = { version: 1, name: 'actor', width: 32, height: 54, palette: { k: '#212', g: '#389', h: '#edc', s: '#345' }, symbols: { stump: ['k'] }, frames }; const key = 'table-' + JSON.stringify(item.changes); if (item.via === 'cli') { await writeFile(inside(cwd, 'actor.json'), JSON.stringify(project)); await writeFile(inside(cwd, 'edits.json'), JSON.stringify(item.changes)); const report = JSON.parse(execFileSync(process.execPath, [cli, 'patch', 'actor.json', '--changes', 'edits.json', '--out', 'edited.json'], { cwd, encoding: 'utf8' })); assert.ok(report.ok && report.edits.length === item.changes.length); const edited = await jsonFile(inside(cwd, 'edited.json')); assert.notDeepEqual(edited, project); products.set(key, edited); } else { const report = JSON.parse(await runTool({ ...item, args: { project, changes: item.changes } }, cwd)); assert.deepEqual(await jsonFile(inside(cwd, 'exports/.revisions/' + report.revision + '.json')), products.get(key)); assert.equal(report.edits.length, item.changes.length); } } // One input exposes every selector in the inspection syntax. Auxiliary examples live in // the call's folder, so standard input, relative paths and protected outputs work as published. async function runOptionExample(item, cwd) { const write = (name, value) => writeFile(inside(cwd, name), JSON.stringify(value)); const names = ['a', 'b', 'flash-1', 'walk-1', 'body', 'plate', 'fin', 'tile']; const frames = names.map((name, index) => ({ name, duration: 100, layers: [ { name: 'body', ops: [{ op: 'rect', x: index, y: 2, w: 3, h: 4, color: 'm' }] }, { name: 'head', ops: [{ op: 'pixel', x: index + 1, y: 1, color: 'm' }] }] })); const project = { version: 1, name: 'sample', width: 32, height: 32, palette: { m: '#452' }, frames, animations: Object.fromEntries(['idle', 'walk', 'run'].map(name => [name, { frames: names }])) }; await write('sample.json', project); const rig = path.join(root, 'examples/hero.poses.json'); const sprite = 'sample.json'; let option = item.option; const bindings = { '': '{"horizon":3}', '': '4', '': '8', '': 'body', '<1-16>': '2', '': 'sheet.atlas.json', '': 'normal.json', '': 'preview.png', '': '30', '': 'metadata.json', '': 'exported', '': 'frames.png', '': item.kind === 'gif' && option.startsWith('--preset ') ? 'smoke-puff' : 'idle', '': 'kept', '': 'ground.json', '': 'tile', '': '"#17191d"' }; option = option.replace(/<[^>]+>/g, key => { assert.ok(Object.hasOwn(bindings, key), key); return bindings[key]; }) .replace('x,y,w,h', '4,6,8,6').replace('--offset x,y', '--offset 0,0').replace('--step n', '--step 2') .replace('--offset k', '--offset 1').replace('--loops n', '--loops 1').replace('--seconds s', '--seconds 0.2') .replace('--ground row', '--ground 31').replace('--frames N', '--frames 2').replace('--port N', '--port 0'); const flags = words(option), kind = item.kind; const call = (args, input) => JSON.parse(execFileSync(process.execPath, [cli, ...args], { cwd, encoding: 'utf8', input, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, HOME: cwd, USERPROFILE: cwd } })); let argv, stdin; if (kind === 'inspect') { argv = ['inspect', sprite]; if ((flags.includes('onion') || flags.includes('--every')) && !flags.includes('--animation')) argv.push('--animation', 'run'); for (const name of ['earlier.json', 'previous.json', 'ground.json', 'blue.json', 'green.json']) { if (option.includes(name)) await write(name, { ...project, name: 'variant', palette: { m: '#8ab' } }); } } else if (kind === 'render' || kind === 'normal') { argv = ['render', sprite, '--out', 'bundle']; if (kind === 'normal') await write('normal.json', { format: 'pixelforge-normals', version: 1, recipe: sprite }); } else if (kind.startsWith('scene')) { const scene = { format: 'pixelforge-scene', version: 1, name: 'room', width: 32, height: 32, duration: 160, assets: { actor: project }, instances: [{ name: 'actor', asset: 'actor', at: [0,0] }] }; await write('room.json', scene); argv = kind === 'scene-gif' ? ['gif', 'room.json', '--out', 'room.gif'] : ['scene', 'room.json']; if (kind === 'scene') argv.push('--image', 'scene.png'); } else if (kind === 'gif') argv = ['gif', ...(flags.includes('--preset') ? [] : [sprite]), '--out', 'clip.gif']; else if (kind === 'sequence') argv = ['sequence', sprite, '--out', 'frames', '--fps', '30', '--size', '64x64']; else if (kind === 'compile' || kind === 'expand') { argv = ['compile', rig]; if (kind === 'expand') argv.push('--expand'); else if (!flags.includes('--draft-views')) argv.push('--out', 'compiled.json'); } else if (kind === 'autotile') argv = ['autotile', path.join(root, 'examples/meadow.autotile.json'), '--out', 'tiles.json']; else if (kind === 'review-metadata' || kind === 'motion') { if (kind === 'review-metadata') call(['compile', rig, '--out', 'compiled.json', ...flags]); argv = ['inspect', kind === 'motion' ? rig : 'compiled.json', '--motion', 'run']; } else if (kind === 'import') { const strip = { ...project, width: 24, height: 24, frames: frames.slice(0, 2), animations: { idle: { frames: names.slice(0, 2) } } }; const bundle = await createBundle(strip); for (const [key, file] of [['sample.png', 'sheet.png'], ['sample.atlas.json', 'sheet.atlas.json']]) await writeFile(inside(cwd, file), bundle.files.get(key)); argv = ['import', 'sheet.png', '--out', 'restored.json']; if (flags.includes('--frames')) argv.push('--frame', '24x24'); } else if (kind === 'patch') { const changes = [{ paint: 'frames[a]', value: [{ x: 7, y: 7, color: 'm' }] }]; argv = ['patch', sprite]; if (flags.includes('--changes')) stdin = JSON.stringify(changes); else { await write('changes.json', changes); argv.push('--changes', 'changes.json'); } } else if (kind === 'build') { const entries = ['hero', 'torch', 'icon'].map(name => ({ name, file: name + '.json', outputs: [{ still: name + '.png', frame: 'a' }] })); for (const entry of entries) await write(entry.file, { ...project, name: entry.name }); await write('pixelbolt.build.json', { entries }); argv = ['build']; } else if (kind === 'server') { const answer = JSON.parse(await runTool({ ...item, tool: 'pixel_validate', launchArgs: ['mcp', '--out', 'exports', ...flags], args: { project } }, cwd)); assert.deepEqual(await jsonFile(inside(cwd, 'exports/.revisions/' + answer.revision + '.json')), project); return; } else if (kind === 'preview') { assert.deepEqual(await previewSource(['preview', sprite, ...flags], cwd), project); return; } else if (kind === 'skill') { const dir = inside(cwd, '.agents/skills'); assert.deepEqual(flags, ['--dir', '%USERPROFILE%\\.agents\\skills']); const reply = call(['skill', 'install', '--dir', dir]); assert.equal(path.dirname(reply.skill), dir); return; } else assert.fail('unknown option example ' + kind); argv.push(...flags); const reply = call(argv, stdin); assert.equal(reply.ok, true, item.command); for (const flag of outputFlags.filter(flag => argv.includes(flag))) await checkOutput(inside(cwd, atFlag(argv, flag))); if (flags.includes('--expect')) assert.equal(reply.check.ok, true); if (flags.includes('--native') && flags.includes('--out')) await checkOutput(inside(cwd, 'review.native.png')); if (kind === 'build') { for (const entry of flags.includes('--only') ? ['hero', 'torch'] : ['hero', 'torch', 'icon']) await checkOutput(inside(cwd, entry + '.png')); if (flags.includes('--keep')) assert.equal((await readdir(inside(cwd, 'kept'))).length, 3); } } // Play the quick start with its own recipe and paint operation. Each call opens a fresh server // and receives only the earlier revision file and, for PNG import, the exported first frame. async function runQuickStep(item, cwd, supplied, products) { const project = await jsonFile(inside(supplied, 'sample.json')), prior = products.get('quick-revision'); const args = {}; for (const key of item.keys) { if (key === 'project') args.project = project; else if (key === 'revision') args.revision = prior.id; else if (key === 'changes') args.changes = await jsonFile(inside(supplied, 'changes.json')); else if (key === 'expect') args.expect = { width: project.width, height: project.height }; else if (key === 'source') args.source = await jsonFile(path.join(root, 'examples/hero.poses.json')); else if (key === 'preset') args.preset = item.preset; else assert.fail('unknown quick-start argument ' + key); } if (prior) await copy(prior.file, inside(cwd, 'exports/.revisions/' + prior.id + '.json')); if (item.gif) { args.gif = item.gif; if (item.gif.scale) args.expect.gifScale = item.gif.scale; } if (item.tool === 'pixel_scene') args.scene = { format: 'pixelforge-scene', version: 1, name: 'room', width: project.width, height: project.height, assets: { actor: { revision: prior.id } }, instances: [{ name: 'actor', asset: 'actor', at: [0, 0] }] }; if (item.tool === 'pixel_import') { args.path = 'rest.png'; await copyFile(products.get('quick-frame'), inside(cwd, args.path)); } let png; const reply = JSON.parse(await runTool({ ...item, args, check(parts) { png = parts.find(part => part.type === 'image'); } }, cwd)); assert.equal(reply.ok, true, item.command); if (item.tool === 'pixel_validate' || item.tool === 'pixel_patch') { const file = inside(cwd, 'exports/.revisions/' + reply.revision + '.json'); if (item.tool === 'pixel_validate') assert.deepEqual(await jsonFile(file), project); else { assert.notEqual(reply.revision, prior.id); assert.ok(png && reply.frames.changed.length, 'the painted pixel should be visible in the comparison'); } products.set('quick-revision', { id: reply.revision, file }); } if (item.tool === 'pixel_inspect' || item.tool === 'pixel_scene') assert.equal(png?.mimeType, 'image/png'); if (item.tool === 'pixel_render') { assert.equal(reply.check.ok, true, JSON.stringify(reply.check)); const frame = path.join(reply.directory, 'frames', project.frames[0].name + '.png'); await checkOutput(frame); products.set('quick-frame', frame); if (args.gif) { const folder = path.join(reply.directory, 'gifs'); const files = (await readdir(folder)).sort(); assert.deepEqual(files, Object.keys(project.animations).map(name => name + '.gif').sort()); for (const name of files) { const gif = await readFile(inside(folder, name)), scale = args.gif.scale ?? 1; assert.match(gif.toString('ascii', 0, 6), /^GIF8[79]a$/); assert.deepEqual([gif.readUInt16LE(6), gif.readUInt16LE(8)], [project.width * scale, project.height * scale]); } } } if (item.tool === 'pixel_import') { const imported = await jsonFile(inside(cwd, 'exports/.revisions/' + reply.revision + '.json')); assert.deepEqual([imported.width, imported.height, imported.frames.length], [project.width, project.height, 1]); } } export async function runPage(page, text, tmp, skipsSeen) { const cases = examples(page, text); if (!cases.length) return 0; const supplied = await mkdtemp(path.join(tmp, 'inputs-')); const saved = await userInputs(page, text, supplied); const products = new Map(); let count = 0; for (const item of cases) { const where = page + ':' + item.line; const skip = item.skip ?? skips.find(([pattern]) => pattern.test(item.command))?.[1]; if (skip) { skipsSeen.push(where + ' ' + item.command + ' — ' + skip); continue; } try { const cwd = await mkdtemp(path.join(tmp, 'call-')); if (item.build) { await runDocumentedBuild(item, cwd, products); count++; continue; } if (item.share) { await runShareExample(item, cwd); count++; continue; } if (item.clientArgs) { const args = [...item.clientArgs]; if (args[0] === 'cmd') assert.deepEqual(args.splice(0, 2), ['cmd', '/c']); if (args[0] === 'node') assert.deepEqual(args.splice(0, 2), ['node', '/absolute/path/to/Pixelbolt/bin/pixelbolt.js']); else assert.deepEqual(args.splice(0, 3), ['npx', '-y', 'pixelbolt@latest']); assert.deepEqual(args.slice(0, -1), ['mcp', '--out']); assert.ok(path.posix.isAbsolute(args.at(-1)) || path.win32.isAbsolute(args.at(-1))); args[args.length - 1] = inside(cwd, 'configured exports'); const project = { version: 1, name: 'one', width: 1, height: 1, frames: [{ name: 'one', ops: [] }] }; const reply = JSON.parse(await runTool({ ...item, tool: 'pixel_validate', launchArgs: args, args: { project } }, cwd)); assert.deepEqual(await jsonFile(inside(args.at(-1), '.revisions/' + reply.revision + '.json')), project); count++; continue; } if (item.indexServer) { const out = inside(cwd, 'exports'); const syntax = item.command.slice(item.command.indexOf('mcp --out ')) .replace('', '').replace('/absolute/path/to/output', '') .replace('[--root /absolute/path/to/project]', '--root ') .replace('[--time-limit seconds]', '--time-limit 30').replace('[--no-skill]', '--no-skill'); const launchArgs = syntax.split(' ').map(word => word === '' ? out : word === '' ? cwd : word); const project = await jsonFile(inside(supplied, 'sample.json')); const info = JSON.parse(await runTool({ ...item, tool: 'pixel_validate', launchArgs, args: { project } }, cwd)); assert.deepEqual(await jsonFile(inside(out, '.revisions/' + info.revision + '.json')), project); count++; continue; } if (item.pluginLaunch) { const data = inside(cwd, 'plugin-data'); await mkdir(data); const launchArgs = words(item.command).map(word => word.replace('${PLUGIN_DATA}', data)); const args = { project: { version: 1, name: 'icon', width: 1, height: 1, frames: [{ name: 'one', ops: [{ op: 'fill', color: '#fff' }] }] }, saveAs: { sheet: 'copy.png' } }; const report = JSON.parse(await runTool({ ...item, tool: 'pixel_render', launchArgs, args }, cwd)); const expected = inside(data, 'output/' + path.basename(report.directory) + '/icon.png'); assert.deepEqual(await readFile(expected), await readFile(inside(data, 'copy.png'))); assert.equal(report.saved.length, 1); assert.ok(path.isAbsolute(report.saved[0].path) && path.isAbsolute(report.directory)); count++; continue; } if (item.poseTool) { await runPoseTool(item, cwd, supplied, products); count++; continue; } if (item.exportExample) { await runExportExample(item, cwd); count++; continue; } if (item.editExample) { await runEditExample(item, cwd, products); count++; continue; } if (item.compileExample) { await runCompileExample(item, cwd, supplied, products); count++; continue; } if (item.reviewExample) { await runReviewExample(item, cwd, supplied); count++; continue; } if (item.referenceExample) { await runReferenceExample(item, cwd, products); count++; continue; } if (item.presetExample) { await runPresetExample(item, cwd, products); count++; continue; } if (item.patchTable) { await runPatchTable(item, cwd, products); count++; continue; } if (item.optionExample) { await runOptionExample(item, cwd); count++; continue; } if (item.quickStep) { await runQuickStep(item, cwd, supplied, products); count++; continue; } if (item.tool) { await runTool(item, cwd, products); count++; continue; } await runShell(page, item, cwd, supplied, saved, products); count++; } catch (cause) { throw new Error(where + ' ' + item.command + '\n' + cause.message, { cause }); } } return count; } // Run the instructions from each guide's header. Every offered heading, part and whole-section // form must return that section of the shipped document, on the interface that printed it. async function generatedGuideHelp(tmp) { let count = 0; for (const topic of SECTIONED) { const source = (await readFile(new URL(HELP_TOPICS[topic], new URL('../src/help.js', import.meta.url)), 'utf8')).replace(/\r\n/g, '\n'); const title = source.split('\n')[0]; for (const via of ['cli', 'mcp']) { let printedTopic = topic; const ask = async name => { const cwd = await mkdtemp(path.join(tmp, 'guide-')); count++; return via === 'cli' ? execFileSync(process.execPath, [cli, 'help', printedTopic, ...(name ? [name] : [])], { cwd, encoding: 'utf8' }).replace(/\r\n/g, '\n') : await runTool({ tool: 'pixel_help', command: 'pixel_help ' + printedTopic + ' ' + (name ?? ''), args: { topic: printedTopic, name } }, cwd); }; const outline = await ask(); const instruction = outline.split('\n').find(line => line.startsWith('> ')); const invocation = via === 'cli' ? /run pixelbolt help ([\w-]+) ""/ : /call pixel_help with topic "([\w-]+)" and name set to its heading/; assert.ok(invocation.test(instruction), 'missing ' + via + ' heading instruction for ' + topic); printedTopic = instruction.match(invocation)[1]; const headings = list => [...list.matchAll(/(?:^|; )([^;]+?) \(\d+ KB\)/g)].map(match => match[1]); const sectionNames = headings(instruction.split(': ').at(-1)); assert.ok(sectionNames.length, instruction); assert.equal((await ask('all')).trimEnd(), source.trimEnd()); for (const name of sectionNames) { const answer = await ask(name); assert.ok(answer.startsWith(title + '\n\n## ' + name + '\n'), via + ' ' + topic + ' ' + name); const next = answer.split('\n').find(line => line.startsWith('> ') && line.includes('Its parts,')); if (!next) continue; const partNames = headings(next.split('as a section is: ')[1]); assert.ok(partNames.length, next); const wholeName = /\. "([^"]+ all)" is the whole section\./.exec(next)?.[1]; assert.ok(wholeName, next); const whole = await ask(wholeName); assert.ok(whole.startsWith(title + '\n\n## ' + name + '\n')); for (const part of partNames) { const section = await ask(part); assert.ok(section.startsWith(title + '\n\n## ' + name + '\n\n### ' + part + '\n'), via + ' help ' + topic + ' "' + part + '" opened a different section from "' + name + '"'); assert.ok(whole.includes('\n### ' + part + '\n')); } } } } return count; } // Try the two ways a reader can look for a command or topic under the wrong heading, // then execute the corrective instruction returned by that interface. async function generatedHelpRedirects(tmp) { let count = 0; const fresh = () => mkdtemp(path.join(tmp, 'redirect-')); const usage = execFileSync(process.execPath, [cli, 'help'], { cwd: await fresh(), encoding: 'utf8' }); count++; const commands = new Set([...usage.matchAll(/^ pixelbolt ([a-z-]+)\b/gm)].map(match => match[1])); assert.ok(commands.has('inspect')); for (const command of commands) { const result = spawnSync(process.execPath, [cli, 'help', command], { cwd: await fresh(), encoding: 'utf8' }); count++; if (result.status === 0) continue; assert.equal(result.status, 1); if (command === 'help') { const topic = /; topics: ([^,]+)/.exec(JSON.parse(result.stderr).error)?.[1]; assert.equal(topic, 'quickstart'); const quick = execFileSync(process.execPath, [cli, 'help', topic], { cwd: await fresh(), encoding: 'utf8' }); assert.match(quick, /^# /); count++; continue; } const hint = /run pixelbolt ([\w-]+) (--help)$/.exec(JSON.parse(result.stderr).error); assert.ok(hint, result.stderr); const output = execFileSync(process.execPath, [cli, ...hint.slice(1)], { cwd: await fresh(), encoding: 'utf8' }); count++; assert.ok(output.includes('pixelbolt ' + command), command); } for (const mistaken of ['scenes', 'terrain']) { const folder = await fresh(); const lines = [{ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'docs', version: '1' } } }, { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'pixel_help', arguments: { topic: 'schema', name: mistaken } } }]; const wire = execFileSync(process.execPath, [cli, 'mcp', '--out', 'exports'], { cwd: folder, input: lines.map(msg => JSON.stringify(msg)).join('\n') + '\n', encoding: 'utf8' }); const message = wire.trim().split('\n').map(line => JSON.parse(line)).find(msg => msg.id === 2); assert.equal(message.result.isError, true); const hint = /call pixel_help with topic "([^"]+)"(?: and name "([^"]+)")?$/.exec(JSON.parse(message.result.content[0].text).error); assert.ok(hint, message.result.content[0].text); const result = await runTool({ tool: 'pixel_help', command: 'pixel_help ' + hint[1], args: { topic: hint[1], name: hint[2] } }, await fresh()); assert.ok(result.startsWith('# ') || JSON.parse(result).type); count += 2; } return count; } // Follow the commands printed by the help implementation, including a large property's next outline. async function generatedSchemaHelp(tmp) { let count = 0; for (const topic of Object.keys(HELP_TOPICS).filter(isSchema)) { const terminal = []; for (const via of ['cli', 'mcp']) { let name, promised; let args = [topic]; while (true) { const cwd = await mkdtemp(path.join(tmp, 'help-')); const answer = via === 'cli' ? execFileSync(process.execPath, [cli, 'help', ...args], { cwd, encoding: 'utf8' }) : await runTool({ tool: 'pixel_help', command: 'pixel_help ' + args.join(' '), args: { topic: args[0], name: args[1] } }, cwd); count++; const outline = answer.startsWith('# '); if (promised) assert.equal(outline ? 'an outline' : 'JSON', promised, via + ' help ' + args.join(' ') + ' promises ' + promised); if (!outline) { assert.ok(name, 'the root schema should have an outline'); terminal.push({ name, schema: JSON.parse(answer) }); break; } if (!name) { const sources = answer.split('\n').find(line => line.startsWith('Shipped sources in this format,')); if (sources) { const command = via === 'cli' ? /\(pixelbolt presets \): (.+)\.$/ : /\(pixel_help with topic "preset" and name\): (.+)\.$/; const names = command.exec(sources)?.[1].split(', '); assert.ok(names?.length, sources); for (const preset of names) { const folder = await mkdtemp(path.join(tmp, 'preset-')); const result = via === 'cli' ? execFileSync(process.execPath, [cli, 'presets', preset], { cwd: folder, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }) : await runTool({ tool: 'pixel_help', command: 'pixel_help preset ' + preset, args: { topic: 'preset', name: preset } }, folder); const info = JSON.parse(result); assert.equal(info.name, preset); assert.equal(info.source.format, 'pixelforge-' + (topic === 'scenes' ? 'scene' : topic)); count++; } } } const heading = answer.split('\n').find(line => line.startsWith('> A schema')); const form = /To read one part as (JSON|an outline), /.exec(heading); assert.ok(form, 'the outline must say what its next example returns'); promised = form[1]; const next = via === 'cli' ? /run pixelbolt help (\S+) (\S+) \(/.exec(heading) : /call pixel_help with topic "([^"]+)" and name "([^"]+)"/.exec(heading); assert.ok(next, heading); args = next.slice(1); assert.equal(args[0], topic); assert.ok(args[1] && (!name || args[1].startsWith(name + '.')), 'the next path must go deeper'); name = args[1]; } } assert.deepEqual(terminal[0], terminal[1], topic); } return count; } async function main() { const tmp = await mkdtemp(path.join(os.tmpdir(), 'pixelbolt-docs-')); try { const guides = (await readdir(path.join(root, 'docs'))).filter(name => name.endsWith('.md')).sort(); const files = ['README.md', ...guides.map(name => 'docs/' + name), 'llms.txt', 'skills/pixelbolt-pixel-art/SKILL.md', 'src/help.js']; const requested = process.argv.slice(2); for (const page of requested) assert.ok(files.includes(page), 'unknown documentation file ' + page); const skipped = []; let count = 0; for (const page of requested.length ? requested : files) { const text = (await readFile(path.join(root, page), 'utf8')).replace(/\r\n/g, '\n'); const checked = page === 'src/help.js' ? await generatedSchemaHelp(tmp) + await generatedGuideHelp(tmp) + await generatedHelpRedirects(tmp) : await runPage(page, text, tmp, skipped); if (checked) console.log(page + ': ' + checked + ' passed'); count += checked; } console.log('Passed ' + count + ' documentation calls.'); for (const reason of skipped) console.log('Skipped ' + reason); } finally { await rm(tmp, { recursive: true, force: true }); } } if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) await main();