Files
agentic-labs-challenge/body-snatcher/verify.js
T
2026-08-15 19:23:11 +02:00

447 lines
22 KiB
JavaScript

#!/usr/bin/env node
'use strict';
const fs = require('fs');
const vm = require('vm');
const assert = require('assert');
const VALID_STATES = new Set(['title', 'playing', 'possessed', 'shop', 'paused', 'won', 'lost']);
const TYPES = ['Brute', 'Skitterer', 'Sentinel', 'Shielder', 'Bomber', 'Healer', 'Phaser', 'Turret', 'Charger', 'Siren', 'Mimic', 'Leech'];
const DIRS = [
{ dx: 1, dy: 0, key: 'ArrowRight', facing: 'right' },
{ dx: -1, dy: 0, key: 'ArrowLeft', facing: 'left' },
{ dx: 0, dy: 1, key: 'ArrowDown', facing: 'down' },
{ dx: 0, dy: -1, key: 'ArrowUp', facing: 'up' }
];
function fail(message) { throw new Error(message); }
function check(value, message) { assert.ok(value, message); }
function tileType(tile) {
if (typeof tile === 'number') return tile;
if (!tile) return 1;
const type = tile.type;
if (typeof type === 'number') return type;
return ({ floor: 0, wall: 1, door: 2, exit: 3, stairs: 3, shop: 4, chest: 5 })[String(type).toLowerCase()] ?? (tile.solid ? 1 : 0);
}
function isWall(tile) { return tileType(tile) === 1 || (tile && typeof tile === 'object' && tile.solid === true); }
function isFloor(tile) { return !isWall(tile); }
function hp(enemy) { return Number(enemy && (enemy.hp ?? enemy.health)); }
function maxHp(enemy) { return Number(enemy && (enemy.maxHp ?? enemy.maxHP ?? enemy.hp)); }
function distance(a, b) { return Math.abs(a.x - b.x) + Math.abs(a.y - b.y); }
function truthyAchievements(value) {
if (!value) return 0;
const entries = Array.isArray(value) ? value : Object.values(value);
return entries.filter(v => v === true || (v && (v.unlocked || v.earned || v.complete))).length;
}
function makeRuntime(html) {
let audioCalls = 0;
const storage = new Map();
const storageStats = { sets: 0 };
const noop = () => {};
const gradient = { addColorStop: noop };
let canvas;
const ctx = new Proxy({
canvas: null,
createLinearGradient: () => gradient,
createRadialGradient: () => gradient,
createConicGradient: () => gradient,
createPattern: () => ({}),
measureText: text => ({ width: String(text).length * 8 }),
getImageData: () => ({ data: new Uint8ClampedArray(4) }),
isPointInPath: () => false,
isPointInStroke: () => false
}, {
get(target, prop) { return prop in target ? target[prop] : noop; },
set(target, prop, value) { target[prop] = value; return true; }
});
function element(tag = 'div') {
const node = {
tagName: String(tag).toUpperCase(), style: {}, children: [], dataset: {}, classList: { add: noop, remove: noop, toggle: noop },
appendChild(child) { this.children.push(child); return child; }, removeChild: noop, addEventListener: noop, removeEventListener: noop,
setAttribute(name, value) { this[name] = value; }, getAttribute(name) { return this[name] ?? null; }, focus: noop,
getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 640 }),
querySelector: () => null, querySelectorAll: () => []
};
if (node.tagName === 'CANVAS') {
node.width = 800; node.height = 640; node.getContext = () => ctx; node.toDataURL = () => 'data:image/png;base64,';
}
return node;
}
canvas = element('canvas');
ctx.canvas = canvas;
const canvasId = (html.match(/<canvas[^>]*\bid=["']([^"']+)/i) || [])[1] || 'game';
canvas.id = canvasId;
const elements = new Map([[canvasId, canvas]]);
const document = {
readyState: 'complete', body: element('body'), documentElement: element('html'), hidden: false,
createElement: element,
getElementById(id) {
if (id === canvasId || /canvas|game/i.test(id)) return canvas;
if (!elements.has(id)) elements.set(id, element('div'));
return elements.get(id);
},
querySelector(selector) { return selector === 'canvas' || selector.includes('canvas') ? canvas : null; },
querySelectorAll(selector) { return selector.includes('canvas') ? [canvas] : []; },
addEventListener: noop, removeEventListener: noop
};
class AudioParam { setValueAtTime() { audioCalls++; } exponentialRampToValueAtTime() { audioCalls++; } linearRampToValueAtTime() { audioCalls++; } }
class AudioNode { constructor() { this.frequency = new AudioParam(); this.gain = new AudioParam(); this.detune = new AudioParam(); } connect() { audioCalls++; return this; } start() { audioCalls++; } stop() { audioCalls++; } }
class AudioContextMock {
constructor() { audioCalls++; this.currentTime = 0; this.destination = new AudioNode(); this.state = 'running'; }
createOscillator() { audioCalls++; return new AudioNode(); }
createGain() { audioCalls++; return new AudioNode(); }
createBiquadFilter() { audioCalls++; return new AudioNode(); }
createBufferSource() { audioCalls++; return new AudioNode(); }
createBuffer() { audioCalls++; return { getChannelData: () => new Float32Array(64) }; }
resume() { audioCalls++; return Promise.resolve(); }
close() { return Promise.resolve(); }
}
const localStorage = {
getItem(key) { return storage.has(key) ? storage.get(key) : null; },
setItem(key, value) { storageStats.sets++; storage.set(key, String(value)); },
removeItem(key) { storage.delete(key); }, clear() { storage.clear(); }, key(i) { return [...storage.keys()][i] || null; },
get length() { return storage.size; }
};
const sandbox = {
console, document, localStorage, AudioContext: AudioContextMock, webkitAudioContext: AudioContextMock,
requestAnimationFrame: () => 1, cancelAnimationFrame: noop, setInterval: () => 1, clearInterval: noop,
setTimeout: () => 1, clearTimeout: noop, performance: { now: () => 0 }, navigator: { userAgent: 'verify.js' },
location: { reload: noop }, devicePixelRatio: 1, innerWidth: 800, innerHeight: 640,
Event: class Event {}, KeyboardEvent: class KeyboardEvent {}, HTMLElement: class HTMLElement {}, HTMLCanvasElement: class HTMLCanvasElement {},
Image: class Image {}, Uint8ClampedArray, Float32Array, Math, Date, JSON, Promise, Map, Set, WeakMap, WeakSet, Array, Object,
Number, String, Boolean, RegExp, Error, TypeError, parseInt, parseFloat, isNaN, Infinity, NaN
};
sandbox.window = sandbox;
sandbox.self = sandbox;
sandbox.globalThis = sandbox;
document.defaultView = sandbox;
vm.createContext(sandbox);
const scripts = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)]
.filter(match => !/\bsrc\s*=/.test(match[1]))
.map(match => match[2]);
check(scripts.length, 'index.html has no inline script');
scripts.forEach((script, i) => vm.runInContext(script, sandbox, { filename: `index.html#script-${i + 1}`, timeout: 3000 }));
return { sandbox, storage, storageStats, get audioCalls() { return audioCalls; } };
}
function boot() {
check(fs.existsSync('index.html'), 'index.html does not exist');
const html = fs.readFileSync('index.html', 'utf8');
const runtime = makeRuntime(html);
const game = runtime.sandbox.GAME || (runtime.sandbox.window && runtime.sandbox.window.GAME);
check(game, 'window.GAME is not exposed');
return { html, game, runtime };
}
function startPlaying(game) {
game.start();
if (game.state === 'title') game.input('Enter');
if (game.state === 'title' && typeof game.newRun === 'function') game.newRun();
check(game.state === 'playing' || game.state === 'possessed', `cannot enter play state (got ${game.state})`);
}
function resetFloor(game, n = 1) {
if (typeof game.setFloor === 'function') game.setFloor(n);
else startPlaying(game);
if (game.state === 'title') game.input('Enter');
if (game.player) {
game.player.ghost = true;
game.player.host = null;
if (!(game.player.timer > 10)) game.player.timer = 15;
}
if (game.state !== 'playing' && game.state !== 'possessed') {
try { game.state = 'playing'; } catch (_) {}
}
if (Array.isArray(game.enemies)) game.enemies.splice(0);
if (Array.isArray(game.projectiles)) game.projectiles.splice(0);
}
function carve(game, x0 = 2, y0 = 2, w = 12, h = 10) {
const grid = game.grid;
check(Array.isArray(grid) && grid.length > y0 + h, 'grid too small');
for (let y = y0; y < Math.min(grid.length - 1, y0 + h); y++) {
for (let x = x0; x < Math.min(grid[y].length - 1, x0 + w); x++) grid[y][x] = 0;
}
}
function setPlayer(game, x, y) {
game.player.x = x; game.player.y = y;
if ('renderX' in game.player) game.player.renderX = x;
if ('renderY' in game.player) game.player.renderY = y;
if ('fromX' in game.player) game.player.fromX = x;
if ('fromY' in game.player) game.player.fromY = y;
if ('toX' in game.player) game.player.toX = x;
if ('toY' in game.player) game.player.toY = y;
game.player.moveCooldown = 0;
}
function face(game, dir) { game.player.facing = dir.facing; }
function findOpenNeighbor(game, x, y) {
return DIRS.find(d => game.grid[y + d.dy] && isFloor(game.grid[y + d.dy][x + d.dx]));
}
function possess(game, type) {
resetFloor(game, type === 'Mimic' || type === 'Leech' ? 10 : 1);
carve(game);
setPlayer(game, 4, 5);
const dir = { dx: 1, dy: 0, key: 'ArrowRight', facing: 'right' };
face(game, dir);
const enemy = game.spawn(type, 5, 5);
check(enemy, `spawn(${type}) did not return an enemy`);
game.input('Space');
check(game.player.host, `could not possess ${type}`);
check(game.state === 'possessed' || game.player.ghost === false, `${type} possession did not change state`);
return enemy;
}
function exitFloor(game) {
const grid = game.grid;
let exit;
for (let y = 0; y < grid.length; y++) for (let x = 0; x < grid[y].length; x++) if (tileType(grid[y][x]) === 3) exit = { x, y };
check(exit, 'floor has no exit tile');
let dir = DIRS.find(d => grid[exit.y - d.dy] && isFloor(grid[exit.y - d.dy][exit.x - d.dx]));
if (!dir) {
dir = DIRS[0];
grid[exit.y][exit.x - 1] = 0;
}
setPlayer(game, exit.x - dir.dx, exit.y - dir.dy);
game.player.ghost = true; game.player.host = null; game.player.moveCooldown = 0;
game.input(dir.key);
if (game.state === 'playing' && game.player.x === exit.x && game.player.y === exit.y) game.tick(1);
}
function fieldPositive(obj, names) { return names.some(name => Number(obj && obj[name]) > 0); }
function phase1() {
const { html, game } = boot();
check(/<canvas\b/i.test(html), 'missing canvas');
check(/<script\b/i.test(html), 'missing script');
check(!/<script\b[^>]*\bsrc\s*=/i.test(html), 'external script src is forbidden');
check(!/<(?:img|audio|video|link)\b[^>]*(?:src|href)\s*=\s*["']https?:/i.test(html), 'external assets are forbidden');
check(!/(^|[;\n])\s*import\s+(?:[\w*{]|["'])/m.test(html), 'ES imports are forbidden');
['start', 'input', 'tick'].forEach(name => check(typeof game[name] === 'function', `GAME.${name} missing`));
game.start();
check(VALID_STATES.has(game.state), `invalid GAME.state: ${game.state}`);
check(game.state === 'title', 'GAME.start() must initialize the title screen');
check(Array.isArray(game.grid) && game.grid.length, 'GAME.grid missing');
const tiles = game.grid.flat().map(tileType);
check(tiles.includes(0), 'grid has no floor tiles');
check(tiles.includes(1), 'grid has no wall tiles');
const source = html.toLowerCase();
['wasd', 'arrow', 'space', 'q', 'e', 'enter', 'esc'].forEach(word => check(source.includes(word), `title/control text missing ${word.toUpperCase()}`));
check(source.includes('legend') || source.includes('bestiary'), 'title has no legend/bestiary entry point');
TYPES.forEach(type => check(source.includes(type.toLowerCase()), `legend missing ${type}`));
check(/possess(?:ed|ion)?/.test(source) && /(enemy|opponent|ai)/.test(source), 'legend must explain enemy behavior and possessed kits');
check(/fog|explored/.test(source), 'fog-of-war implementation not found');
check(game.player && Number(game.player.timer) >= 15, 'base ghost timer must start at 15 seconds or more');
game.input('l');
check(VALID_STATES.has(game.state), 'legend input left GAME in an invalid state');
if (game.state === 'title') game.input('Enter');
startPlaying(game);
if (Array.isArray(game.enemies)) game.enemies.splice(0);
let open = findOpenNeighbor(game, game.player.x, game.player.y);
if (!open) {
carve(game); setPlayer(game, 4, 4); open = DIRS[0];
}
const before = { x: game.player.x, y: game.player.y };
game.input(open.key);
check(game.player.x !== before.x || game.player.y !== before.y, 'ArrowRight/open-direction input did not move the ghost');
let wallCase;
for (let y = 1; y < game.grid.length - 1 && !wallCase; y++) for (let x = 1; x < game.grid[y].length - 1 && !wallCase; x++) {
if (!isFloor(game.grid[y][x])) continue;
const d = DIRS.find(dir => isWall(game.grid[y + dir.dy][x + dir.dx]));
if (d) wallCase = { x, y, d };
}
check(wallCase, 'could not find a floor next to a wall');
setPlayer(game, wallCase.x, wallCase.y);
game.input(wallCase.d.key);
check(game.player.x === wallCase.x && game.player.y === wallCase.y, 'ghost moved through a wall');
}
function phase2() {
const { game } = boot();
startPlaying(game);
['spawn'].forEach(name => check(typeof game[name] === 'function', `GAME.${name} missing`));
const brute = possess(game, 'Brute');
check(maxHp(brute) === 8 && Number(brute.damage) === 3, `Brute stats wrong: hp=${maxHp(brute)} damage=${brute.damage}`);
game.input('x');
check(game.player.ghost === true && !game.player.host && game.state === 'playing', 'X did not abandon host into ghost state');
check(game.enemies.includes(brute) && hp(brute) > 0, 'abandoned host did not survive in enemies');
check(Number(game.player.timer) > 0, 'abandon reset/expired ghost timer');
game.input('Space');
check(!game.player.host, 'abandoned host can be immediately re-possessed');
const skitter = game.spawn('Skitterer', 7, 5);
const sentinel = game.spawn('Sentinel', 8, 5);
check(maxHp(skitter) === 2 && Number(skitter.damage) === 1 && Number(skitter.speed) === 2, 'Skitterer stats/speed wrong');
check(maxHp(sentinel) === 4 && (Number(sentinel.damage) === 0 || sentinel.melee === false || sentinel.ranged), 'Sentinel must have 4 HP and no melee');
resetFloor(game, 1); carve(game); setPlayer(game, 4, 5);
const chaser = game.spawn('Brute', 9, 5);
const d0 = distance(chaser, game.player);
game.tick(6);
check(distance(chaser, game.player) < d0, 'aggroed Brute did not pathfind toward ghost');
resetFloor(game, 1); carve(game, 1, 1, 21, 15); setPlayer(game, 2, 2);
const idle = game.spawn('Brute', 17, 14);
const idleAt = { x: idle.x, y: idle.y };
game.tick(5);
check(idle.x === idleAt.x && idle.y === idleAt.y, 'enemy outside aggro radius did not stay docile');
resetFloor(game, 1); carve(game); setPlayer(game, 3, 3);
const a = game.spawn('Brute', 8, 8), b = game.spawn('Skitterer', 9, 8);
const ah = hp(a), bh = hp(b);
game.tick(5);
check(hp(a) === ah && hp(b) === bh, 'enemies damaged each other');
possess(game, 'Sentinel');
for (let i = 0; i < 3; i++) game.input('Space');
const host = game.player.host;
check(fieldPositive(host, ['overheatLeft', 'overheat', 'overheatTurns', 'cooldown']) || fieldPositive(game.player, ['overheatLeft', 'overheat', 'overheatTurns']), 'Sentinel did not enter overheat after its burst');
const projectileCount = Array.isArray(game.projectiles) ? game.projectiles.length : 0;
game.tick(2);
check(!Array.isArray(game.projectiles) || game.projectiles.length <= projectileCount, 'Sentinel fired new shots during overheat');
possess(game, 'Brute');
const victim = game.spawn('Skitterer', game.player.x + 1, game.player.y);
victim.hp = 1; game.player.facing = 'right';
const essenceBefore = Number(game.essence) || 0;
game.input('Space');
check(hp(victim) <= 0 || !game.enemies.includes(victim), 'host attack did not kill 1-HP enemy');
check(Number(game.essence) > essenceBefore, 'essence did not increase on kill');
possess(game, 'Brute');
game.player.host.hp = 1;
const attacker = game.spawn('Brute', game.player.x + 1, game.player.y);
attacker.aggro = true;
game.tick(4);
check(game.player.ghost === true && !game.player.host && Number(game.player.timer) > 0, 'host death did not eject a living ghost');
}
function phase3() {
const { game } = boot();
startPlaying(game);
const triples = new Set();
resetFloor(game, 10); carve(game, 1, 1, 22, 15);
TYPES.forEach((type, i) => {
const e = game.spawn(type, 2 + (i % 6) * 2, 3 + Math.floor(i / 6) * 3);
check(e && String(e.type).toLowerCase() === type.toLowerCase(), `cannot instantiate ${type}`);
const triple = `${maxHp(e)}|${Number(e.damage)}|${Number(e.speed)}`;
check(!triples.has(triple), `${type} shares HP+damage+speed tuple ${triple}`);
triples.add(triple);
});
TYPES.forEach(type => {
possess(game, type);
game.input('q'); game.input('e'); game.input('Space');
});
resetFloor(game, 1);
for (let y = 2; y < game.grid.length - 2; y++) for (let x = 2; x < game.grid[y].length - 2; x++) game.grid[y][x] = 0;
for (let y = 2; y < game.grid.length - 2; y++) game.grid[y][7] = 1;
game.grid[8][7] = 2;
setPlayer(game, 4, 8);
const navigator = game.spawn('Brute', 10, 8);
const d0 = distance(navigator, game.player);
for (let i = 0; i < 10; i++) {
game.tick(1);
check(!isWall(game.grid[navigator.y][navigator.x]), 'pathfinder moved an enemy through a wall');
}
check(distance(navigator, game.player) < d0, 'pathfinder did not navigate via the opening');
['Bomber', 'Charger', 'Turret'].forEach(type => {
const instance = boot().game;
startPlaying(instance); resetFloor(instance, 10); carve(instance); setPlayer(instance, 4, 5);
const source = instance.spawn(type, 6, 5), bystander = instance.spawn('Brute', 6, 6);
source.aggro = true;
const before = hp(bystander);
for (let i = 0; i < 10 && instance.state !== 'lost'; i++) instance.tick(1);
check(hp(bystander) === before, `${type} enemy attack damaged another enemy`);
});
possess(game, 'Turret');
for (let i = 0; i < 3; i++) { game.input('Space'); game.tick(1); }
check(fieldPositive(game.player.host, ['overheatLeft', 'overheat', 'overheatTurns', 'cooldown']) || fieldPositive(game.player, ['overheatLeft', 'overheat', 'overheatTurns']), 'Turret did not enter forced overheat');
}
function phase4() {
const { game, runtime } = boot();
startPlaying(game);
['newRun', 'setFloor', 'openShop', 'buy', 'save', 'load'].forEach(name => check(typeof game[name] === 'function', `GAME.${name} missing`));
const layouts = new Set();
for (let i = 0; i < 3; i++) {
game.newRun();
const grid = game.grid;
check(grid.flat().some(tile => tileType(tile) === 3), `generated dungeon ${i + 1} has no exit`);
layouts.add(grid.map(row => row.map(tile => isWall(tile) ? '1' : '0').join('')).join('\n'));
}
check(layouts.size === 3, 'three generated dungeon layouts were not all different');
game.setFloor(1);
exitFloor(game);
check(game.state === 'shop', `floor transition did not open shop (got ${game.state})`);
try { game.essence = 999; } catch (_) {}
if (Number(game.essence) < 100) {
const save = { floor: 1, essence: 999, upgrades: game.upgrades || {}, player: game.player, grid: game.grid, enemies: game.enemies || [] };
runtime.storage.set('bodysnatcher_save', JSON.stringify(save));
game.load(); game.openShop();
}
const upgradesBefore = JSON.stringify(game.upgrades);
game.buy(0);
check(JSON.stringify(game.upgrades) !== upgradesBefore, 'buy(0) did not change GAME.upgrades');
const saved = { floor: Number(game.floor), essence: Number(game.essence), upgrades: JSON.stringify(game.upgrades) };
game.save();
check(runtime.storageStats.sets > 0 && runtime.storage.has('bodysnatcher_save'), 'save() did not call localStorage.setItem with bodysnatcher_save');
game.setFloor(saved.floor === 3 ? 4 : 3);
try { game.essence = 1; } catch (_) {}
game.load();
check(Number(game.floor) === saved.floor, 'load() did not restore floor');
check(Number(game.essence) === saved.essence, 'load() did not restore essence');
check(JSON.stringify(game.upgrades) === saved.upgrades, 'load() did not restore upgrades');
}
function phase5() {
{
const { game } = boot(); startPlaying(game); game.setFloor(10); exitFloor(game);
check(game.state === 'won', `floor 10 exit did not reach won state (got ${game.state})`);
}
{
const { game } = boot(); startPlaying(game);
game.player.ghost = true; game.player.host = null; game.player.timer = 1;
game.tick(2);
check(game.state === 'lost', `expired ghost timer did not reach lost state (got ${game.state})`);
}
{
const { game } = boot(); startPlaying(game);
game.setFloor(7);
try { game.essence = 30; } catch (_) {}
game.tick(1);
possess(game, 'Brute');
game.tick(1);
check(truthyAchievements(game.achievements) >= 3, 'fewer than 3 achievements could be triggered');
}
{
const { game, runtime } = boot();
game.start(); game.input('Enter'); game.input('Space');
check(runtime.audioCalls > 0, 'Web Audio system was not initialized/called after input');
}
{
const { game } = boot(); startPlaying(game);
if (typeof game.setFloor === 'function') game.setFloor(1);
game.player.timer = 1000;
const keys = ['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp', 'Space', 'q', 'e'];
for (let i = 0; i < 200; i++) {
game.input(keys[i % keys.length]);
game.tick(1);
if (i === 49 || i === 99) { game.setFloor(i === 49 ? 2 : 3); game.player.timer = 1000; }
}
check(VALID_STATES.has(game.state), '200-tick stress test ended in invalid state');
}
}
const requested = Number(process.argv[2] || 5);
if (!Number.isInteger(requested) || requested < 1 || requested > 5) fail('Usage: node verify.js <phase 1-5>');
const phases = [phase1, phase2, phase3, phase4, phase5];
try {
for (let i = 0; i < requested; i++) {
phases[i]();
console.log(`PASS phase ${i + 1}`);
}
console.log(`ALL PHASES 1-${requested} PASSED`);
} catch (error) {
console.error(`FAIL phase gate ${requested}: ${error.stack || error.message}`);
process.exit(1);
}