// Exercise option mistakes through the public CLI and MCP interfaces. Each rejection must name // the option under test, so a missing file or an unrelated validation failure cannot pass the case. import assert from 'node:assert/strict'; import { mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { encodePNG } from '../src/png.js'; import { runCLI, rejectedPreview, mcpRequest, mcpRequests } from './check-cli.mjs'; const dir = await mkdtemp(path.join(await realpath(os.tmpdir()), 'pixelbolt-options-')); const failures = []; let count = 0; async function check(label, verify) { count++; try { await verify(); } catch (error) { failures.push(label + '\n' + error.message); } } async function cliError(args, ...details) { const reply = args[0] === 'preview' ? await rejectedPreview(args, dir) : runCLI(args, dir); assert.equal(reply.status, 1, args.join(' ') + ' returned ' + reply.status); assert.equal(reply.stdout, ''); const problem = JSON.parse(reply.stderr); for (const detail of details) assert.ok(problem.error.includes(detail), problem.error); } async function cliOptions() { const help = runCLI(['help'], dir); assert.equal(help.status, 0, help.stderr); const commands = new Set([...help.stdout.matchAll(/^ pixelbolt ([a-z][a-z-]*)\b/gm)].map(match => match[1])); assert.ok(commands.has('help') && commands.has('render') && commands.has('mcp')); for (const command of commands) { const foreign = command === 'presets' ? '--port' : '--find'; await check(command + ' unknown option', () => cliError([command, '--scalle'], '--scalle')); await check(command + ' option belonging to another command', () => cliError(command === 'help' ? ['help', foreign] : [command, foreign, '1'], foreign)); await check(command + ' short option', () => cliError([command, '-f'], '-f', ...(command === 'help' ? [] : ['Unknown option']))); } await check('init suggests --force and leaves the directory empty', async () => { await cliError(['init', '-f'], '-f', '--force', './-f'); assert.deepEqual(await readdir(dir), []); }); await check('an explicit path still names a file beginning with a dash', async () => { const created = runCLI(['init', './-f'], dir); assert.equal(created.status, 0, created.stderr); const project = JSON.parse(await readFile(path.join(dir, '-f'), 'utf8')); const valid = runCLI(['validate', '-'], dir, JSON.stringify(project)); assert.equal(valid.status, 0, valid.stderr); }); await check('CLI presence flag with a value', () => cliError(['init', '--force=false'], '--force=false')); await writeFile(path.join(dir, 'scene.json'), JSON.stringify(scene)); const sourceFile = path.join(dir, 'poses.json'), spriteFile = path.join(dir, 'sprite.json'); await writeFile(sourceFile, await readFile(new URL('../examples/slime-idle.poses.json', import.meta.url))); await writeFile(spriteFile, JSON.stringify(project)); await writeFile(path.join(dir, 'timing.json'), JSON.stringify([{ set: 'frames[one].duration', value: 200 }])); for (const args of [['inspect', spriteFile], ['patch', spriteFile, '--changes', 'timing.json'], ['presets', 'coin'], ['compile', sourceFile, '--expand'], ['compile', sourceFile, '--draft-views', 'eyes:30']]) { await check(args[0] + ' --force without output ' + args.at(-1), () => cliError([...args, '--force'], '--force', '--out')); } await check('inspect can use --force with an actual output', async () => { const file = path.join(dir, 'replace.png'); await writeFile(file, 'old'); const reply = runCLI(['inspect', spriteFile, '--out', file, '--force'], dir); assert.equal(reply.status, 0, reply.stderr); assert.equal((await readFile(file)).subarray(0, 8).toString('hex'), '89504e470d0a1a0a'); }); await check('scene file listing needs a bundle', () => cliError( ['scene', 'scene.json', '--image', 'view.png', '--list-files'], '--list-files', '--out')); await writeFile(path.join(dir, 'dot.json'), JSON.stringify(project)); await writeFile(path.join(dir, 'dot.png'), Buffer.from(inputs.pixel_import.data, 'base64')); await writeFile(path.join(dir, 'edits.json'), JSON.stringify([{ cleanup: 'frames[one]', value: { corners: 'true' } }])); await writeFile(path.join(dir, 'cuts.json'), JSON.stringify({ views: { right: { miror: true } } })); const cases = [ [['render', 'dot.json', '--out', 'out', '--expect', '{"sheet":{"colums":2}}'], 'expect.sheet.colums'], [['render', 'dot.json', '--out', 'out', '--expect', '{"transparent":"true"}'], 'expect.transparent'], [['inspect', 'dot.json', '--guides', '{"iso":{"tile":[4,2],"offst":[0,0]}}'], 'guides.iso.offst'], [['scene', 'scene.json', '--image', 'view.png', '--guides', '{"horizon":"1"}'], 'guides.horizon'], [['patch', 'dot.json', '--changes', 'edits.json', '--out', 'patched.json'], 'changes[0].value.corners'], [['import', 'dot.png', '--out', 'imported.json', '--cutout', 'cuts.json'], 'cutout.views.right.miror'], [['render', 'dot.json', '--out', 'out', '--scale', 'large'], '--scale'], [['scene', 'scene.json', '--image', 'view.png', '--scale', '2.1'], '--scale'], [['sequence', 'dot.json', '--out', 'frames', '--fps', '10', '--scale', 'large'], 'scale'], [['inspect', 'dot.json', '--ground', '1'], '--ground', '--motion'], [['scene', 'scene.json', '--out', 'out', '--time', '0'], '--time', '--image'], [['import', 'dot.png', '--out', 'imported.json', '--embedded', '--frame', '1x1'], '--frame', '--embedded'], [['build', '--check', '--force'], '--force', '--check'], [['skill', 'install', '--project', '--dir', 'skills'], '--project', '--dir'] ]; for (const [args, ...details] of cases) await check(args.join(' '), () => cliError(args, ...details)); } const project = { version: 1, name: 'dot', width: 2, height: 2, palette: { k: '#234' }, frames: [{ name: 'one', ops: [{ op: 'pixel', x: 0, y: 0, color: 'k' }] }] }; const scene = { format: 'pixelforge-scene', version: 1, name: 'room', width: 4, height: 4, assets: { dot: project }, instances: [{ asset: 'dot', at: [0, 0] }] }; const inputs = { pixel_help: {}, pixel_validate: { project }, pixel_inspect: { project }, pixel_render: { project }, pixel_patch: { project, changes: [{ set: 'frames[one].duration', value: 120 }] }, pixel_compile: { preset: 'coin' }, pixel_scene: { scene }, pixel_import: { data: Buffer.from(encodePNG(Uint8Array.of(34, 51, 68, 255), 1, 1)).toString('base64') } }; function call(name, args) { return mcpRequest('tools/call', { name, arguments: args }, dir); } function toolError(name, args, key) { return checkToolError(call(name, args), name, key); } function checkToolError(reply, name, key) { assert.equal(reply.error, undefined, JSON.stringify(reply.error)); assert.equal(reply.result?.isError, true, name + ' accepted ' + key); const problem = JSON.parse(reply.result.content[0].text); assert.ok(problem.path === key || problem.path?.endsWith('.' + key), 'expected ' + key + ': ' + problem.error); } // The listing leaves source documents and edits' replacement values to their own validators. function valueCases(schema, route = []) { const cases = []; if (route.length && (schema.type || schema.enum || schema.oneOf)) { const types = [schema.type].flat(); cases.push([route, null], [route, schema.type === 'boolean' ? 'true' : true]); if (types.includes('integer')) cases.push([route, 1.5]); if (types.some(type => type === 'integer' || type === 'number') && !types.includes('string')) cases.push([route, '2']); if (types.includes('object') && !types.includes('array')) cases.push([route, []]); if (types.includes('array') && !types.includes('object')) cases.push([route, {}]); } for (const [key, spec] of Object.entries(schema.properties ?? {})) cases.push(...valueCases(spec, [...route, key])); if (schema.items) cases.push(...valueCases(schema.items, [...route, 0])); if (schema.additionalProperties && typeof schema.additionalProperties === 'object') { const key = { draftViews: 'eyes', frames: 'default', saveAs: 'sheet' }[route.at(-1)] ?? 'sample'; cases.push(...valueCases(schema.additionalProperties, [...route, key])); } // A union may have an array branch that also constrains its members. for (const variant of schema.oneOf ?? []) if (variant.items) cases.push(...valueCases(variant.items, [...route, 0])); return cases; } const powder = { format: 'pixelforge-powder', version: 1, name: 'pile', base: 'sandbox', width: 16, height: 16, scene: [{ material: 'stone', rect: [0, 12, 16, 4] }], clips: { rest: { frames: 1, every: 1 } } }; const chest = JSON.parse(await readFile(new URL('../examples/iso-chest.stack.json', import.meta.url), 'utf8')); const hand = { format: 'pixelforge-stack', version: 1, name: 'hand', palette: { k: '#abc' }, slices: [['.']], paths: { digit: { colors: 'k', nodes: [{ name: 'base', radius: 1, at: [0, 0, 1] }, { name: 'tip', radius: 0, at: [0, 0, 5] }] } }, poses: { open: {} } }; function exampleArguments(name, route, value) { const args = structuredClone(inputs[name]), [key] = route; if (key === 'revision' || (name === 'pixel_inspect' && key === 'source')) delete args.project; if (key === 'source') delete args.preset; if (name === 'pixel_compile' && key === 'sequence') { delete args.preset; args.source = powder; } if (key === 'path') delete args.data; if (key === 'overlay') delete args.changes; if (name === 'pixel_inspect' && ['rotate', 'poseSheet'].includes(key)) { delete args.project; args.source = key === 'rotate' ? chest : hand; } if (name === 'pixel_compile' && key === 'draftViews') args.preset = 'slime-idle'; if (name === 'pixel_import' && ['frames', 'padding'].includes(key)) args.frame = '1x1'; const defaults = { region: { x: 0, y: 0, w: 1, h: 1 }, sequence: { fps: 10 }, rotate: { socket: 'hinge', heading: 0, degrees: 45 }, poseSheet: { poses: ['open'], headings: [0], focus: 'digit' } }; if (route.length > 1 && defaults[key]) args[key] = defaults[key]; let target = args; for (let i = 0; i < route.length - 1; i++) { const part = route[i], array = typeof route[i + 1] === 'number'; if (target[part] === null || typeof target[part] !== 'object' || Array.isArray(target[part]) !== array) target[part] = array ? [] : {}; target = target[part]; } target[route.at(-1)] = value; return args; } async function checkValueCases(name, schema) { const cases = valueCases(schema); for (let start = 0; start < cases.length; start += 8) { const batch = cases.slice(start, start + 8); const replies = mcpRequests(batch.map(([route, value]) => ({ method: 'tools/call', params: { name, arguments: exampleArguments(name, route, value) } })), dir); for (const [i, [route, value]] of batch.entries()) { const key = route.map((part, depth) => typeof part === 'number' ? '[' + part + ']' : (depth ? '.' : '') + part).join(''); await check(name + ' ' + key + ' = ' + JSON.stringify(value), () => checkToolError(replies[i], name, key)); } } } async function closedOptions(name, schema, route = []) { if (route.length && schema.additionalProperties === false) { const path = [...route, 'unlistedOption']; const key = path.map((part, i) => typeof part === 'number' ? '[' + part + ']' : (i ? '.' : '') + part).join(''); await check(name + ' unknown ' + key, () => toolError(name, exampleArguments(name, path, 2), key)); } for (const [key, child] of Object.entries(schema.properties ?? {})) await closedOptions(name, child, [...route, key]); if (schema.items) await closedOptions(name, schema.items, [...route, 0]); } function optionConflict(name, args, ...details) { const reply = call(name, args); assert.equal(reply.error, undefined, JSON.stringify(reply.error)); assert.equal(reply.result?.isError, true, name + ' accepted the conflicting options'); const { error } = JSON.parse(reply.result.content[0].text); for (const detail of details) assert.ok(error.includes(detail), error); } async function conditionalOptions() { const crosses = [ ['pixel_help', { topic: 'guide', full: true }, 'full', 'presets'], ['pixel_validate', { project, revision: '0123456789ab' }, 'project', 'revision'], ['pixel_inspect', { project, ground: 0 }, 'ground', 'motion'], ['pixel_patch', { ...inputs.pixel_patch, overlay: {} }, 'changes', 'overlay'], ['pixel_render', { project, sequence: { fps: 10, fit: 'cover' } }, 'fit', 'size'], ['pixel_compile', { preset: 'coin', slices: true }, 'slices', 'stack'], ['pixel_scene', { scene, sequence: { fps: 10, step: 2 } }, 'sequence.step'], ['pixel_import', { ...inputs.pixel_import, padding: 1 }, 'padding', 'frame'] ]; assert.deepEqual(crosses.map(([name]) => name).sort(), Object.keys(inputs).sort()); for (const [name, args, ...details] of crosses) await check(name + ' incompatible options', () => optionConflict(name, args, ...details)); // These public option objects are described compactly in tools/list. Their own readers check the fields. for (const [name, args, key] of [ ...['pixel_inspect', 'pixel_scene'].flatMap(name => [ [name, { ...inputs[name], guides: { horzon: 0 } }, 'guides.horzon'], [name, { ...inputs[name], guides: { iso: { tile: [4, 2], offst: [0, 0] } } }, 'guides.iso.offst'], [name, { ...inputs[name], guides: { horizon: '1' } }, 'guides.horizon'] ]), ['pixel_render', { project, sequence: { fps: 10, scle: 2 } }, 'sequence.scle'], ['pixel_scene', { scene, sequence: { fps: 10, scle: 2 } }, 'sequence.scle'], ['pixel_compile', { source: powder, sequence: { fps: 10, scle: 2 } }, 'sequence.scle'], ['pixel_patch', { project, changes: [{ paint: 'frames[one]', value: [{ x: 0, y: 0, color: 'k', colour: 'k' }] }] }, 'changes[0].value[0].colour'], ['pixel_patch', { project, changes: [{ cleanup: 'frames[one]', value: { corners: 'true' } }] }, 'changes[0].value.corners'], ['pixel_import', { ...inputs.pixel_import, cutout: { views: { right: { miror: true } } } }, 'cutout.views.right.miror'], ['pixel_import', { ...inputs.pixel_import, cutout: { views: { right: { mirror: 'true' } } } }, 'cutout.views.right.mirror'] ]) await check(name + ' nested ' + key, () => toolError(name, args, key)); const serialized = call('pixel_patch', { project: JSON.stringify(project), changes: JSON.stringify(inputs.pixel_patch.changes) }).result; await check('documented serialized arguments retain their decoding note', () => { assert.ok(serialized && !serialized.isError); assert.match(serialized.content.at(-1).text, /project arrived as JSON text.*changes arrived as JSON text/); }); } async function mcpOptions() { const tools = mcpRequest('tools/list', {}, dir).result.tools; assert.deepEqual(tools.map(tool => tool.name).sort(), Object.keys(inputs).sort(), 'provide a valid control for every tool'); for (const { name, inputSchema } of tools) { await check(name + ' valid control', () => { const reply = call(name, inputs[name]); assert.equal(reply.error, undefined, JSON.stringify(reply.error)); assert.ok(reply.result?.content.length && !reply.result.isError, reply.result?.content[0]?.text); }); await check(name + ' unknown option', () => { const reply = call(name, { ...inputs[name], scalle: 2 }); assert.equal(reply.error?.code, -32602); assert.ok(reply.error.message.includes('scalle'), reply.error.message); }); let properties = inputSchema.properties; if (properties.sequence && !properties.sequence.properties) { // Compile and scene refer to render's sequence options to keep the tool listing short. const shared = tools.find(tool => tool.name === 'pixel_render').inputSchema.properties.sequence; const fields = { ...shared.properties }; if (name === 'pixel_scene') { delete fields.animation; delete fields.step; } properties = { ...properties, sequence: { ...shared, properties: fields } }; const base = name === 'pixel_scene' ? { scene } : { source: powder }; await check(name + ' writes a sequence at the requested scale', () => { const reply = call(name, { ...base, sequence: { fps: 10, scale: 2 } }); assert.ok(reply.result && !reply.result.isError, reply.result?.content[0]?.text); assert.equal(JSON.parse(reply.result.content[0].text).sequence.width, 2 * (base.scene ?? base.source).width); }); } await checkValueCases(name, { ...inputSchema, properties }); await closedOptions(name, inputSchema); if (inputSchema.properties.gif?.additionalProperties === false) { await check(name + ' misspelled GIF scale', () => toolError(name, { ...inputs[name], gif: { scle: 2 } }, 'gif.scle')); } if (name === 'pixel_render') { for (const value of [true, false]) await check('overwrite ' + value + ' requires saved copies', () => toolError(name, { ...inputs[name], overwrite: value }, 'overwrite')); } if (name === 'pixel_scene') { await check('scene GIF refuses a sheet option', () => toolError(name, { ...inputs[name], gif: { sheet: true } }, 'gif.sheet')); await check('scene GIF uses the requested scale', () => { const reply = call(name, { ...inputs[name], gif: { scale: 2 } }); assert.equal(reply.result?.isError, undefined, reply.result?.content[0]?.text); const { gif } = JSON.parse(reply.result.content[0].text); assert.deepEqual([gif.width, gif.height], [scene.width * 2, scene.height * 2]); }); } for (const [key, schema] of Object.entries(inputSchema.properties)) { if (schema.type === 'boolean') await check(name + ' ' + key + ' as text', () => toolError(name, { ...inputs[name], [key]: 'true' }, key)); } } } try { await cliOptions(); await mcpOptions(); await conditionalOptions(); if (failures.length) { process.stderr.write(failures.join('\n\n') + '\n'); process.exitCode = 1; } console.log((count - failures.length) + ' of ' + count + ' strict option cases passed.'); } finally { await rm(dir, { recursive: true, force: true }); }