tiny-adventure / commits / 127599d
Add full-campaign playthrough harness and share the driver with verify
Co-Authored-By: Claude Sonnet 5.5
@@ -17,6 +17,14 @@ Needs `go`, `node`, `ffmpeg` (for the recording), `python3`, and `agent-browser`
1717
1818 `VERIFY_ONLY=1280x720,390x844` limits the resolutions. `VERIFY_ATTEMPTS=n` caps POI clicks (default 14).
1919
20+## Playthrough
21+
22+```
23+scripts/playthrough.sh <outdir> <seed> [width height name]
24+```
25+
26+Plays one full campaign on `<seed>` through input only: clicks Begin, opens the journal, then clicks the next main POI until the end screen shows, opening the inventory and pressing `Equip best` before each leg. After two defeats at one POI it walks to a lower level POI first. It records `<name>.webm`, saves screenshots and `<name>.md`/`<name>.json`, and exits non-zero on any failed step, layout problem or console error. `PLAY_MAX_CLICKS` caps clicks (default 60).
27+
2028 ## Output
2129
2230 - `report.md` and `report.json`: per resolution, a table of every interaction with the server state after it (from `/api/state`), the layout checks and console errors.
@@ -0,0 +1,65 @@
1+import { execFileSync } from 'node:child_process';
2+
3+export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4+
5+export function createDriver({ session, baseUrl, w, h }) {
6+ const ab = (...args) => execFileSync('agent-browser', ['--session', session, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60000 });
7+ const ev = (expr) => {
8+ const out = JSON.parse(ab('--json', 'eval', expr));
9+ if (out.error) throw new Error(out.error);
10+ return out.data.result;
11+ };
12+ const api = async (path, body) => {
13+ const res = await fetch(baseUrl + path, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
14+ return res.json();
15+ };
16+ const gameState = async () => JSON.parse(ev('JSON.stringify(window.__game.state())'));
17+ const rects = async () => JSON.parse(ev('JSON.stringify(window.__game.rects())'));
18+ const mode = async () => ev('window.__game.mode');
19+ const clickAt = (x, y) => {
20+ ab('mouse', 'move', String(x), String(y));
21+ ab('mouse', 'down');
22+ ab('mouse', 'up');
23+ };
24+ const clickRect = async (name) => {
25+ const r = (await rects()).find((q) => q.name === name);
26+ if (!r) throw new Error(`no rect ${name}`);
27+ clickAt(Math.round(r.x + r.w / 2), Math.round(r.y + r.h / 2));
28+ };
29+ const waitIdle = async (observe) => {
30+ const t0 = Date.now();
31+ const seen = new Set();
32+ while (Date.now() - t0 < 90000) {
33+ const [b, m] = JSON.parse(ev('JSON.stringify([window.__game.busy, window.__game.mode])'));
34+ if (!seen.has(m)) {
35+ seen.add(m);
36+ await observe?.(m);
37+ }
38+ if (!b) return [...seen];
39+ await sleep(200);
40+ }
41+ throw new Error('game stayed busy for 90s');
42+ };
43+ const clickTile = async (t, observe) => {
44+ ev(`window.__game.focusTile(${t.x},${t.y})`);
45+ await sleep(1800);
46+ const p = JSON.parse(ev(`JSON.stringify(window.__game.tileScreen(${t.x},${t.y}))`));
47+ if (p.x < 0 || p.y < 0 || p.x > w || p.y > h) throw new Error(`tile ${t.x},${t.y} projects off-screen at ${p.x | 0},${p.y | 0}`);
48+ clickAt(Math.round(p.x), Math.round(p.y));
49+ ev('window.__game.focusTile(null)');
50+ await sleep(300);
51+ return waitIdle(observe);
52+ };
53+ const openPage = async (want) => {
54+ ab('open', baseUrl);
55+ const t0 = Date.now();
56+ while (Date.now() - t0 < 30000) {
57+ try {
58+ if (ev('typeof window.__game') === 'object' && (await mode()) === want) return;
59+ } catch {}
60+ await sleep(300);
61+ }
62+ throw new Error(`page did not reach mode ${want}`);
63+ };
64+ return { ab, ev, api, gameState, rects, mode, clickAt, clickRect, waitIdle, clickTile, openPage };
65+}
@@ -0,0 +1,18 @@
1+export function layoutIssues(rects, w, h) {
2+ const issues = [];
3+ for (const r of rects) {
4+ if (!r.essential) continue;
5+ if (r.x < -0.5 || r.y < -0.5 || r.x + r.w > w + 0.5 || r.y + r.h > h + 0.5) issues.push(`${r.name} outside viewport: x=${r.x | 0} y=${r.y | 0} w=${r.w | 0} h=${r.h | 0} in ${w}x${h}`);
6+ }
7+ const contains = (a, b) => a.x <= b.x + 1 && a.y <= b.y + 1 && a.x + a.w >= b.x + b.w - 1 && a.y + a.h >= b.y + b.h - 1;
8+ for (let i = 0; i < rects.length; i++) {
9+ for (let j = i + 1; j < rects.length; j++) {
10+ const a = rects[i];
11+ const b = rects[j];
12+ const ox = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
13+ const oy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
14+ if (ox > 1 && oy > 1 && !contains(a, b) && !contains(b, a)) issues.push(`${a.name} overlaps ${b.name} by ${ox | 0}x${oy | 0}px`);
15+ }
16+ }
17+ return issues;
18+}
@@ -0,0 +1,114 @@
1+import { mkdirSync, writeFileSync } from 'node:fs';
2+import { join } from 'node:path';
3+import { createDriver, sleep } from './driver.mjs';
4+import { layoutIssues } from './layout.mjs';
5+
6+const [outDir, baseUrl, seedArg, wArg, hArg, name] = process.argv.slice(2);
7+const SEED = Number(seedArg);
8+const W = Number(wArg || 1280);
9+const H = Number(hArg || 720);
10+const TAG = name || `seed${SEED}`;
11+const SESSION = `play-${process.pid}`;
12+const MAX_CLICKS = Number(process.env.PLAY_MAX_CLICKS || 60);
13+
14+mkdirSync(outDir, { recursive: true });
15+const d = createDriver({ session: SESSION, baseUrl, w: W, h: H });
16+const { ab, api, rects, mode, clickRect, clickTile, gameState } = d;
17+const log = [];
18+let failures = 0;
19+
20+const brief = (s) => `phase=${s.phase} at=${s.party.x},${s.party.y} battles=${s.summary.battles} kills=${s.summary.kills} loot=${s.summary.loot} steps=${s.summary.steps} gold=${s.party.gold} levels=${s.party.units.map((u) => u.level).join('/')}`;
21+const record = (action, ok, detail) => {
22+ if (!ok) failures++;
23+ log.push({ action, ok, detail });
24+ console.log(`${ok ? 'ok ' : 'FAIL'} ${action} | ${detail}`);
25+};
26+const shot = (label) => ab('screenshot', join(outDir, `${TAG}-${label}.png`));
27+const layout = async (label) => {
28+ for (const i of layoutIssues(await rects(), W, H)) record(`layout ${label}`, false, i);
29+};
30+const presses = async (key, settle = 500) => {
31+ ab('press', key);
32+ await sleep(settle);
33+};
34+
35+ab('set', 'viewport', String(W), String(H));
36+await api('/api/new', { seed: SEED });
37+await d.openPage('title');
38+ab('errors', '--clear');
39+ab('record', 'start', join(outDir, `${TAG}.webm`), '--fps', '10');
40+
41+await layout('title');
42+await clickRect('button-0');
43+await sleep(600);
44+record('click Begin Adventure', (await mode()) === 'explore', `mode=${await mode()}`);
45+
46+await presses('j');
47+record('press J opens journal', (await rects()).some((r) => r.name === 'panel-journal'), 'journal rect');
48+shot('journal');
49+await presses('Escape');
50+
51+async function gear() {
52+ const before = JSON.stringify((await api('/api/state')).party.units.map((u) => u.gear));
53+ await presses('i');
54+ const open = (await rects()).some((r) => r.name === 'panel-inv');
55+ await layout('inventory');
56+ if (!open) return record('press I opens inventory', false, 'no inventory rect');
57+ await clickRect('equip-best');
58+ await sleep(1500);
59+ const after = JSON.stringify((await api('/api/state')).party.units.map((u) => u.gear));
60+ if (!log.some((l) => l.action === 'equip best')) shot('inventory');
61+ record('equip best', true, before === after ? 'no upgrade available' : 'gear changed');
62+ await presses('Escape');
63+}
64+
65+const defeatsAt = {};
66+let clicks = 0;
67+let s = await api('/api/state');
68+while (!s.winner && clicks < MAX_CLICKS) {
69+ const next = s.campaign.main.steps.find((q) => !q.done);
70+ let poi = s.map.pois.find((p) => p.id === next.poi);
71+ const stuck = (defeatsAt[poi.id] || 0) >= 2;
72+ if (stuck) {
73+ const side = s.map.pois.filter((p) => !p.cleared && p.id !== poi.id && p.level < poi.level).sort((a, b) => a.level - b.level)[0];
74+ if (side) poi = side;
75+ }
76+ clicks++;
77+ const before = s;
78+ await gear();
79+ let shots = 0;
80+ await clickTile(poi, async (m) => {
81+ if (m === 'combat' && shots++ === 0 && !log.some((l) => l.action.includes('combat'))) {
82+ await sleep(900);
83+ shot('combat');
84+ await layout('combat');
85+ }
86+ });
87+ s = await api('/api/state');
88+ const lv = (x) => x.party.units.reduce((n, u) => n + u.level, 0);
89+ const progressed = s.summary.battles > before.summary.battles || s.party.x !== before.party.x || s.party.y !== before.party.y;
90+ if (s.phase === 'defeat') defeatsAt[poi.id] = (defeatsAt[poi.id] || 0) + 1;
91+ const local = await gameState();
92+ const synced = local.party.x === s.party.x && local.party.y === s.party.y;
93+ record(`click ${poi.kind} "${poi.name}" Lv${poi.level} (${stuck ? 'level-up detour' : `main: ${next.text}`})`, progressed && synced, `${brief(s)} levelsum ${lv(before)}->${lv(s)} client=${local.party.x},${local.party.y}`);
94+ if (clicks === 2) shot('explore');
95+}
96+
97+await sleep(800);
98+const m = await mode();
99+record('end screen reached', !!s.winner && m === 'end', `winner=${s.winner || 'none'} mode=${m} ${brief(s)}`);
100+if (m === 'end') {
101+ shot('end');
102+ await layout('end');
103+}
104+ab('record', 'stop');
105+const errs = ab('errors').trim();
106+const clean = !errs || /no (page )?errors/i.test(errs);
107+record('console errors', clean, clean ? 'none' : errs.split('\n')[0]);
108+
109+writeFileSync(join(outDir, `${TAG}.json`), JSON.stringify({ seed: SEED, w: W, h: H, clicks, failures, log }, null, 2));
110+const md = [`# Playthrough ${TAG} (seed ${SEED}, ${W}x${H})`, '', `Failures: **${failures}**, clicks: ${clicks}`, '', '| # | Interaction | Result | Observed |', '|---|---|---|---|', ...log.map((l, i) => `| ${i + 1} | ${l.action} | ${l.ok ? 'ok' : '**FAIL**'} | ${l.detail} |`), ''];
111+writeFileSync(join(outDir, `${TAG}.md`), md.join('\n'));
112+try { ab('close'); } catch {}
113+console.log(`${failures} failure(s)`);
114+process.exit(failures ? 1 : 0);
@@ -0,0 +1,18 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+out=${1:?usage: scripts/playthrough.sh <outdir> <seed> [width height name]}
4+seed=${2:?seed}
5+root=$(cd "$(dirname "$0")/.." && pwd)
6+mkdir -p "$out"
7+out=$(cd "$out" && pwd)
8+export DISPLAY=${DISPLAY:-:0}
9+export AGENT_BROWSER_HEADED=1
10+export AGENT_BROWSER_ARGS="--no-sandbox,--disable-dev-shm-usage,--use-angle=swiftshader,--enable-unsafe-swiftshader"
11+port=$(python3 -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1])')
12+bin=$(mktemp -d)/server
13+(cd "$root" && go build -o "$bin" ./cmd/server)
14+"$bin" --seed "$seed" --addr "127.0.0.1:$port" --web "$root/web" >"$out/server-seed$seed.log" 2>&1 &
15+pid=$!
16+trap 'kill $pid 2>/dev/null || true' EXIT
17+for _ in $(seq 50); do curl -sf "http://127.0.0.1:$port/api/seed" >/dev/null && break; sleep 0.2; done
18+node "$root/scripts/playthrough.mjs" "$out" "http://127.0.0.1:$port" "$seed" "${3:-1280}" "${4:-720}" ${5:+"$5"}
@@ -1,49 +1,22 @@
1-import { execFileSync } from 'node:child_process';
21 import { mkdirSync, writeFileSync } from 'node:fs';
32 import { join } from 'node:path';
3+import { createDriver, sleep } from './driver.mjs';
4+import { layoutIssues } from './layout.mjs';
45
56 const [outDir, baseUrl, seedArg] = process.argv.slice(2);
67 const SEED = Number(seedArg || 7);
78 const SESSION = `verify-${process.pid}`;
89 const RESOLUTIONS = [[1280, 720], [1920, 1080], [2560, 1440], [1366, 768], [800, 600], [390, 844]];
910 const ONLY = process.env.VERIFY_ONLY ? process.env.VERIFY_ONLY.split(',') : null;
10-const FULL_ATTEMPTS = Number(process.env.VERIFY_ATTEMPTS || 8);
11+const FULL_ATTEMPTS = Number(process.env.VERIFY_ATTEMPTS || 14);
1112 const SHORT_ATTEMPTS = 2;
12-const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1313
14-const ab = (...args) => execFileSync('agent-browser', ['--session', SESSION, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60000 });
15-const ev = (expr) => {
16- const out = JSON.parse(ab('--json', 'eval', expr));
17- if (out.error) throw new Error(out.error);
18- return out.data.result;
19-};
20-const api = async (path, body) => {
21- const res = await fetch(baseUrl + path, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
22- return res.json();
23-};
14+const driver = createDriver({ session: SESSION, baseUrl, w: 0, h: 0 });
15+const { ab, ev, api } = driver;
2416
2517 const sum = (s) => ({ phase: s.phase, x: s.party.x, y: s.party.y, battles: s.summary.battles, kills: s.summary.kills, loot: s.summary.loot, steps: s.summary.steps, gold: s.party.gold, inv: s.party.inventory?.length ?? 0, levels: s.party.units.map((u) => u.level).join('/'), winner: s.winner || null });
2618 const fmt = (o) => Object.entries(o).map(([k, v]) => `${k}=${v}`).join(' ');
2719
28-export function layoutIssues(rects, w, h) {
29- const issues = [];
30- for (const r of rects) {
31- if (!r.essential) continue;
32- if (r.x < -0.5 || r.y < -0.5 || r.x + r.w > w + 0.5 || r.y + r.h > h + 0.5) issues.push(`${r.name} outside viewport: x=${r.x | 0} y=${r.y | 0} w=${r.w | 0} h=${r.h | 0} in ${w}x${h}`);
33- }
34- const contains = (a, b) => a.x <= b.x + 1 && a.y <= b.y + 1 && a.x + a.w >= b.x + b.w - 1 && a.y + a.h >= b.y + b.h - 1;
35- for (let i = 0; i < rects.length; i++) {
36- for (let j = i + 1; j < rects.length; j++) {
37- const a = rects[i];
38- const b = rects[j];
39- const ox = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
40- const oy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
41- if (ox > 1 && oy > 1 && !contains(a, b) && !contains(b, a)) issues.push(`${a.name} overlaps ${b.name} by ${ox | 0}x${oy | 0}px`);
42- }
43- }
44- return issues;
45-}
46-
4720 const report = { seed: SEED, baseUrl, startedAt: new Date().toISOString(), resolutions: [] };
4821 let failures = 0;
4922
@@ -59,9 +32,8 @@ async function runResolution([w, h], record) {
5932 ab('screenshot', file);
6033 return file;
6134 };
62- const gameState = async () => JSON.parse(ev('JSON.stringify(window.__game.state())'));
63- const rects = async () => JSON.parse(ev('JSON.stringify(window.__game.rects())'));
64- const mode = async () => ev('window.__game.mode');
35+ const d = createDriver({ session: SESSION, baseUrl, w, h });
36+ const { gameState, rects, mode, clickAt, clickRect, waitIdle, clickTile } = d;
6537 const checkLayout = async (label) => {
6638 const issues = layoutIssues(await rects(), w, h);
6739 res.layout.push({ label, issues });
@@ -95,34 +67,6 @@ async function runResolution([w, h], record) {
9567 console.log(` ${ok ? 'ok ' : 'FAIL'} [${tag}] ${action} | mode=${m} | ${fmt(apiAfter)}${detail ? ' | ' + detail : ''}`);
9668 return ok;
9769 };
98- const clickAt = (x, y) => { ab('mouse', 'move', String(x), String(y)); ab('mouse', 'down'); ab('mouse', 'up'); };
99- const clickRect = async (name) => {
100- const r = (await rects()).find((q) => q.name === name);
101- if (!r) throw new Error(`no rect ${name}`);
102- clickAt(Math.round(r.x + r.w / 2), Math.round(r.y + r.h / 2));
103- };
104- const waitIdle = async (observe) => {
105- const t0 = Date.now();
106- const seen = new Set();
107- while (Date.now() - t0 < 90000) {
108- const [b, m] = JSON.parse(ev('JSON.stringify([window.__game.busy, window.__game.mode])'));
109- if (!seen.has(m)) { seen.add(m); await observe?.(m); }
110- if (!b) return [...seen];
111- await sleep(200);
112- }
113- throw new Error('game stayed busy for 90s');
114- };
115- const clickTile = async (t, observe) => {
116- ev(`window.__game.focusTile(${t.x},${t.y})`);
117- await sleep(1800);
118- const p = JSON.parse(ev(`JSON.stringify(window.__game.tileScreen(${t.x},${t.y}))`));
119- if (p.x < 0 || p.y < 0 || p.x > w || p.y > h) throw new Error(`tile ${t.x},${t.y} projects off-screen at ${p.x | 0},${p.y | 0}`);
120- clickAt(Math.round(p.x), Math.round(p.y));
121- ev('window.__game.focusTile(null)');
122- await sleep(300);
123- return waitIdle(observe);
124- };
125-
12670 await api('/api/new', { seed: SEED });
12771 ab('open', baseUrl);
12872 const t0 = Date.now();