towerdef/docs/review-2026-10-09/phase2-workflow.js
Claude 72c49eee1f Wrap up: review findings, balance baseline, bot tool and next-session notes
- docs/NEXT.md: where to pick up, prioritised, with the known wall-selling bug
  and its two-line fix
- docs/review-2026-10-09/: 85 reviewer findings (touch, co-op, client code,
  visual, reverse proxy) with verification status, repro scripts archive and
  the review workflow script; nothing fixed yet by design
- docs/BALANCE.md + tools/bot.js: headless balance bot and the untuned baseline
  (IDS Sniper dominates, maze is a near-guaranteed win, credits snowball)
- test/sim.test.js derives tunable numbers from the tables, plus a shape test
- README status note

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
2026-10-09 21:38:59 +00:00

178 lines
19 KiB
JavaScript

export const meta = {
name: 'netwall-client-and-proxy-hardening',
description: 'Independent reviewers (touch UX, co-op chaos, client code, visual QA, reverse proxy) -> adversarial verification -> single fixer -> final regression check',
phases: [
{ title: 'Review', detail: 'five reviewers probe the real game in real browsers' },
{ title: 'Verify', detail: 'each finding is independently re-checked; only reproduced ones survive' },
{ title: 'Fix', detail: 'one agent applies the verified findings and adds regression tests' },
{ title: 'Final', detail: 'fresh agent re-runs everything and hunts regressions' },
],
}
const SP = '/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad'
const ROOT = '/home/jav/git/towerdefence'
const COMMON = `
PROJECT: "Netwall", an HTML5 maze-building tower defence game with solo play and two-player co-op. Repo: ${ROOT} (a git repo; do NOT run git commit/push; the lead does that).
Read ${ROOT}/README.md first, then as needed ${ROOT}/docs/PROTOCOL.md and ${ROOT}/docs/DEPLOY.md.
Layout: public/ (static client: index.html, css/style.css, js/sim.js shared pure rules, js/controllers.js Local+Remote controllers, js/render.js canvas renderer incl. 90-degree portrait rotation,
js/main.js UI/input/lobby, js/audio.js, sw.js), server/ (Node, ws: static files + authoritative co-op rooms), test/ (node:test; ONLY real test files there), e2e/ (Playwright scenarios; run with "npm run e2e [-- filter]"), tools/bot.js (balance bot).
The user plays on desktop AND phones (portrait + landscape, touch), solo and co-op, with the server behind nginx Proxy Manager on Debian 13, dual stack.
ENVIRONMENT (no system Node/browser): source ${SP}/pwenv.sh -> puts Node 24 on PATH, sets LD_LIBRARY_PATH for headless Chromium and PLAYWRIGHT_BROWSERS_PATH.
Playwright: require('playwright-core') works from ${ROOT} (node_modules). Launch with chromium.launch({args:['--no-sandbox']}). Working examples of every kind of browser test are in ${ROOT}/e2e/scenarios/*.js
and ${SP}/{smoke,touch,coop,endflow,matrix,perf}.js. Screenshots can be looked at with the Read tool (it renders PNGs): use that, it is the best way to judge visuals.
Start the real server with: cd ${ROOT} && PORT=<your port> HOST=127.0.0.1 node server/index.js (it serves public/ too; kill it when done). Use ONLY the port range given in your brief so parallel agents do not collide.
Put scratch scripts/screenshots under ${SP}/reviews/<your-key>/ (create it), never in the repo, except regression tests when your brief says so.
Do not edit repo files unless your brief explicitly says you may (reviewers are report-only). Report only what you reproduced; quote exact steps, observed vs expected, and numbers.
Be skeptical of the code and of earlier claims; the author is an AI and the happy paths were only lightly exercised.`
const FINDINGS = {
type: 'object',
properties: {
findings: {
type: 'array',
items: {
type: 'object',
properties: {
title: { type: 'string' },
severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low'] },
area: { type: 'string' },
repro: { type: 'string', description: 'exact steps or script path that reproduces it' },
observed: { type: 'string' },
expected: { type: 'string' },
suggestedFix: { type: 'string' },
},
required: ['title', 'severity', 'repro', 'observed', 'expected'],
},
},
coverage: { type: 'string', description: 'what you tested, and what you could not test' },
},
required: ['findings', 'coverage'],
}
const VERDICT = {
type: 'object',
properties: {
confirmed: { type: 'boolean' },
severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'none'] },
evidence: { type: 'string' },
betterFix: { type: 'string' },
},
required: ['confirmed', 'evidence'],
}
const FIX = {
type: 'object',
properties: {
fixed: { type: 'array', items: { type: 'object', properties: { title: { type: 'string' }, how: { type: 'string' }, files: { type: 'array', items: { type: 'string' } } }, required: ['title', 'how'] } },
notFixed: { type: 'array', items: { type: 'object', properties: { title: { type: 'string' }, why: { type: 'string' } }, required: ['title', 'why'] } },
testsAdded: { type: 'array', items: { type: 'string' } },
unitTests: { type: 'string' },
e2e: { type: 'string' },
},
required: ['fixed', 'notFixed', 'unitTests', 'e2e'],
}
const DIMS = [
{
key: 'touch',
ports: '8210-8219',
prompt: `${COMMON}
YOUR BRIEF (reviewer "touch-ux", ports ${'8210-8219'}): find bugs and UX problems for TOUCH play on phones and tablets. Drive Chromium with real touch via CDP Input.dispatchTouchEvent and Playwright device emulation
(iPhone SE 375x667, iPhone 14 390x844, Pixel 7 412x915, small Android 360x640, landscape variants 667x375 / 844x390 / 915x412, iPad 768x1024 and 1024x768). Serve public/ (via the real server).
Probe at least: tap-to-preview then confirm for every tower type; tapping the preview cell again; wall drag-painting incl. very fast drags and drags that leave the board; pinch zoom/pan clamping and recovery, zoom then rotate the device mid-game
(resize the viewport while a pending placement, a selected tower, a zoomed camera and an open menu exist); two-finger gestures that start while one finger is painting; long-press ping vs scroll; tapping tiny cells at the minimum cell size
(is the intended cell hit? check cellToScreen/screenToCell round trips under rotation + zoom + pan); the confirm bar/hint overlap with the board; top bar wrapping, buttons >= 44px tall on coarse pointers, text clipped,
the info panel/palette scrolling in portrait, sticky palette; sound unlock on first touch; lobby inputs with a soft keyboard (16px font, viewport resize), the page never scrolling/bouncing/zooming; safe-area insets (emulate with env()
overrides if you can); the stage 'touchmove preventDefault' not breaking palette scrolling; prefers-reduced-motion. Also check what happens when pointercancel fires mid-gesture (browser steals the touch).
Report real defects with exact repro.`,
},
{
key: 'coop',
ports: '8220-8229',
prompt: `${COMMON}
YOUR BRIEF (reviewer "coop-chaos", ports ${'8220-8229'}): attack the CO-OP experience end to end with 2-3 real browser contexts against the real server (and raw 'ws' clients where useful). Probe: both players building on the same cell at the same instant;
both selling/upgrading the same tower; a player placing while the partner's sell is in flight; selling the tower the partner has selected (their info panel must close, no stale actions); new game started by the host while the guest is mid-gesture, has a pending
placement, or the end overlay open; map change on new game (renderer board swap, camera reset); a guest who joins mid-wave (does the snapshot/interpolation start cleanly? any ghost monsters?); reconnect during a wave, during pause, during the end screen,
with the server's tw/rev changing while offline (state must be correct after resume); socket killed uncleanly (page.route abort / context.setOffline / kill the websocket from the server side) and the visible 'Reconnecting' overlay lifecycle; server restart while two
clients are connected (what does each client show? can they recover or are they stranded? is the message sensible?); the server process receiving SIGTERM; invalid/expired invite codes, lowercase codes, ?room= with garbage, a third player joining a full room, the same
browser tab reloading mid-game (sessionStorage resume) and a duplicated tab (same pid, close code 4001: what does the old tab show?), localStorage 'Resume' button flows, leaving the room via menu/leave, then creating another; host leaves -> guest promoted -> end screen 'Play again' available?;
cursor/ping behaviour with different viewport sizes and a rotated (portrait) partner; pause/speed commands from both; sound/toasts on join/leave; interpolation smoothness (render a few hundred frames and look for monster teleports/backwards motion in the interpolated positions);
long sessions (run 3x speed for a couple of minutes: memory growth in the page, snapshot buffer sizes, listener leaks). Report defects with exact repro. You may write throwaway scripts only in your scratch folder.`,
},
{
key: 'code',
ports: '8230-8239',
prompt: `${COMMON}
YOUR BRIEF (reviewer "client-code", ports ${'8230-8239'}): do a rigorous line-by-line review of ${ROOT}/public/js/main.js, controllers.js, render.js, audio.js, sw.js, index.html and css/style.css, then PROVE each suspected bug in a real browser before reporting it.
Hunt for: null/undefined derefs and races between async events (controller 'joined'/'newgame'/'state' vs renderer.setBoard), stale state after leaving a room / starting a new solo game (selection, pending, hover, preview, ui flags, end overlay, music state, timers such as banner/long-press,
wake lock), event listener and timer leaks (useController attaches listeners per controller; RemoteController timers/visibility listeners), per-frame allocations or O(n^2) work, memory growth in the renderer maps (aim/trk) and particle arrays, division by zero / NaN in camera math
(zero-size stage during layout, orientation change), rotation math errors (screenToCell/cellToScreen inverse property under rotation, zoom and pan: write a randomised property test in the page), keyboard handling when overlays/inputs are focused, Space/Enter triggering a focused button AND the hotkey,
innerHTML construction with any server- or user-supplied string (player names, room codes: XSS!), CSP compatibility (the server sends default-src 'self'; style-src 'unsafe-inline'), service worker behaviour (does it ever serve a stale game after an update? does it cache the websocket upgrade or /healthz? cache.put on partial content?),
audio edge cases with the REAL files now in public/assets/music (menu/battle/boss are several MB, win/lose are 13 s stingers; tracks.json maps them; autoplay policy, rapid music()/stinger() calls, a track failing to load mid-game, the service worker and HTTP 206 range responses for audio, mute while a fade is running, switching map/leaving a room while music plays, iOS-style first-gesture unlock), accessibility basics (labels, focus order, focus trap in overlays, contrast), localStorage/sessionStorage failures (Safari private mode: simulate by making Storage throw), the first-run flow (help overlay), and browsers lacking APIs
(no ResizeObserver, no AudioContext, no wakeLock, no clipboard). Fix nothing; report with proof (page.evaluate outputs, console errors, screenshots).`,
},
{
key: 'visual',
ports: '8240-8249',
prompt: `${COMMON}
YOUR BRIEF (reviewer "visual-qa", ports ${'8240-8249'}): act as a picky game UI/UX designer. Take screenshots (and LOOK at them with the Read tool) of every screen and state at desktop 1280x800, 1920x1080, tablet portrait/landscape, phone portrait 390x844 and 360x640, phone landscape 844x390 and 667x375:
main menu (each map selected), help, lobby (empty, error message, joined waiting for partner), playing: empty board, after building a maze, with a long route preview (amber route + hint), invalid placement (red ghost + hint), selected tower with range ring, each tower type at levels 1-3 (glyphs readable? upgrade
clearly visible?), each enemy type (shapes distinguishable at small size? air units clearly different from ground?), health bars, slow ring, boss wave banner, many monsters at once, explosions/arcs/tracers, partner cursor labels in rotated portrait mode, co-op ownership markers, end screens (win/lose), toasts, the reconnect overlay, paused state (is it obvious the game is paused?), low-lives warning.
Judge: legibility, contrast (WCAG AA for text), tap-target sizes, alignment, clipped/overlapping elements, inconsistent spacing, anything confusing for a first-time player, whether the route preview and 'blocks the route' feedback are understandable, whether the board looks good (not just correct). Also test 200% browser zoom/large system font and the 'prefers-reduced-motion' and 'forced-colors' cases.
Report concrete, fixable problems with the file/selector involved and a specific proposed change (CSS values, drawing tweaks). Rank by how much they hurt a new player. Do not report pure taste unless it hurts clarity.`,
},
{
key: 'proxy',
ports: '8250-8259',
prompt: `${COMMON}
YOUR BRIEF (reviewer "reverse-proxy", ports ${'8250-8259'}): verify the server works behind nginx exactly the way nginx Proxy Manager runs it. There is no system nginx and no root. Obtain nginx WITHOUT root: in ${SP}/reviews/proxy/ run "apt-get download nginx nginx-common libnginx-mod-... (only what is needed; check apt-cache depends)"
plus any missing shared libraries, extract with "dpkg-deb -x" into a private prefix, and run it as an unprivileged user with your own nginx.conf (listen on a high port, pid/log/temp paths under your folder, daemon off, include mime types). If nginx genuinely cannot be run this way after a serious attempt, say so and fall back to a faithful Node reverse proxy
(http + upgrade handling, HTTP/1.1, same header behaviour) while clearly stating the difference.
Configure it like NPM does for a Proxy Host with Websockets Support: proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; Connection $connection_upgrade (map); Host $host; X-Forwarded-For $proxy_add_x_forwarded_for; X-Forwarded-Proto/Host/Port; X-Real-IP; proxy_pass http://127.0.0.1:<server port>;
plus the Advanced snippet from docs/DEPLOY.md (read/send timeouts). Then, THROUGH the proxy, run the real browser e2e scenarios (point E2E_URL at the proxy; see e2e/run.js) and extra probes: WebSocket survives > 60 s idle with a short proxy_read_timeout=30s (keep-alive pings must hold it), an idle paused 2-player room for 2+ minutes,
path-prefix deployment (location /netwall/ { proxy_pass http://127.0.0.1:<port>/; } with the client loading at /netwall/: do manifest, service worker scope, ws URL, css/js/icon URLs all resolve? check the browser console), HTTPS-like behaviour (X-Forwarded-Proto https; the client uses location.protocol, so also run nginx with a self-signed cert on a high port, use ignoreHTTPSErrors, and confirm wss:// works and the service worker registers),
the Origin check with Host rewritten (proxy_set_header Host an.internal.name) and with ALLOWED_ORIGINS/TRUST_PROXY variants, per-IP connection cap seeing real client IPs from X-Forwarded-For, IPv6 (listen [::]:port in nginx, connect via http://[::1]:port/ with a browser and with curl -6; server bound to ::), gzip of static assets at the proxy, large header/cookie cases, nginx returning 502 while the server restarts (what does the client show? does it recover?), HTTP/2 to the browser.
Also re-verify the claims in docs/DEPLOY.md against what you observe, and list every statement that is wrong or missing. Report findings; you may NOT edit repo files.`,
},
]
const verifyPrompt = (d, f) => `${COMMON}
YOUR BRIEF: you are an adversarial VERIFIER. A reviewer ("${d.key}") claims this defect in the Netwall repo. Your job is to try hard to REFUTE it: reproduce it yourself from scratch with your own script (ports ${d.ports}; scratch under ${SP}/reviews/verify-${d.key}/), check whether it is intended behaviour, a test artefact, or already handled elsewhere, and judge the real severity for a real player on a real phone/desktop.
Default to confirmed=false when you cannot reproduce it. If you confirm it, say precisely what evidence you saw, and propose a better/simpler fix if the suggestion is flawed. Do not edit repo files.
CLAIM: ${JSON.stringify(f)}`
const results = await pipeline(
DIMS,
(d) => agent(d.prompt, { label: 'review:' + d.key, phase: 'Review', schema: FINDINGS }),
(r, d) => parallel(((r && r.findings) || []).map((f, i) => () =>
agent(verifyPrompt(d, f), { label: 'verify:' + d.key + ':' + (i + 1), phase: 'Verify', schema: VERDICT })
.then((v) => ({ dim: d.key, finding: f, verdict: v })))),
)
const all = results.filter(Boolean).flat().filter(Boolean)
const confirmed = all.filter((x) => x.verdict && x.verdict.confirmed)
const dismissed = all.filter((x) => !(x.verdict && x.verdict.confirmed))
log('findings: ' + all.length + ', confirmed: ' + confirmed.length + ', dismissed: ' + dismissed.length)
phase('Fix')
const fix = confirmed.length === 0 ? { fixed: [], notFixed: [], unitTests: 'skipped (nothing confirmed)', e2e: 'skipped (nothing confirmed)' } : await agent(`${COMMON}
YOUR BRIEF (the FIXER): below are defects that independent reviewers found AND an independent verifier reproduced. You may edit repo files now (public/, server/, test/, e2e/, docs/, README, deploy/; NOT tools/bot.js or the balance constants in public/js/sim.js, those are being tuned elsewhere).
Work through them in order of severity. For each: understand the root cause (do not paper over symptoms), fix it with minimal clean changes that match the surrounding style, and add a regression test where feasible (unit test in test/ for server/sim; an e2e scenario or an added assertion in e2e/scenarios for browser behaviour; keep every scenario deterministic).
Respect the wire contract in docs/PROTOCOL.md; if a fix needs a protocol change, change server, client, tests AND the doc together. Re-run "cd ${ROOT} && node --test" and "cd ${ROOT} && npm run e2e" until both are green. If a finding is wrong or not worth fixing, say why in notFixed.
Use your own ports 8260-8269 for any server you start.
VERIFIED FINDINGS:
${JSON.stringify(confirmed.map((x) => ({ dim: x.dim, ...x.finding, verifierEvidence: x.verdict.evidence, verifierSeverity: x.verdict.severity, verifierBetterFix: x.verdict.betterFix })), null, 1)}`,
{ label: 'fix', phase: 'Fix', schema: FIX })
phase('Final')
const final = await agent(`${COMMON}
YOUR BRIEF (final QA, ports 8270-8279): a fixer just changed the repo to address these verified findings: ${JSON.stringify(fix)}.
Run "cd ${ROOT} && node --test" and "cd ${ROOT} && npm run e2e" yourself. Then review the full change (diff the repo against its last commit: "git -C ${ROOT} diff" and "git -C ${ROOT} status", read-only git commands are fine) for regressions, sloppy fixes, leftover debug code, broken styling, files that should not exist,
and anything inconsistent between server, client and docs/PROTOCOL.md. Play a short solo game and a short co-op game in a real browser at desktop and phone sizes and look at screenshots. Fix any trivial regression you find yourself (say what you changed); report anything bigger.`,
{ label: 'final', phase: 'Final', schema: {
type: 'object',
properties: { unitTests: { type: 'string' }, e2e: { type: 'string' }, regressions: { type: 'array', items: { type: 'string' } }, changedByMe: { type: 'array', items: { type: 'string' } }, verdict: { type: 'string' } },
required: ['unitTests', 'e2e', 'verdict'] } })
return { confirmed: confirmed.map((x) => ({ dim: x.dim, title: x.finding.title, severity: x.verdict.severity })), dismissed: dismissed.map((x) => ({ dim: x.dim, title: x.finding.title, why: x.verdict && x.verdict.evidence })), fix, final }