Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(play): stand up /play/war as a real page, expand event-readiness coverage
nirholas0d28dfb98665
diff --git a/api/_lib/pricing/catalog.js b/api/_lib/pricing/catalog.jsindex 66f0a1129..474cc6bcb 100644--- a/api/_lib/pricing/catalog.js+++ b/api/_lib/pricing/catalog.js@@ -48,7 +48,7 @@ export const TTS_ELEVEN_USD_PER_1K = 0.3;// OpenAI TTS (gpt-4o-mini-tts / tts-1): retail USD per 1,000 synthesized// characters on the platform key. Upstream is ~$0.015/1k chars; $0.03 retail-// keeps the same margin shape as the ElevenLabs rung. Same policy applies —+// keeps the same margin shape as the ElevenLabs rung. Same policy applies:// a vendor-billed lane never has a free tier (owner policy 2026-08-06), so// every platform-key OpenAI synthesis is metered to the caller's credits.export const TTS_OPENAI_USD_PER_1K = 0.03;diff --git a/api/_lib/sniper-solvency.js b/api/_lib/sniper-solvency.jsindex 49cb41c10..00e9016cd 100644--- a/api/_lib/sniper-solvency.js+++ b/api/_lib/sniper-solvency.js@@ -1,12 +1,12 @@// @ts-check/**- * Agent Sniper — fleet solvency.+ * Agent Sniper: fleet solvency.** The failure this module exists to make visible: between 2026-07-29 and* 2026-08-08 the sniper fleet booked over a thousand consecutive failed entries* and closed zero trades, while `/api/sniper/status` reported `state: "live"`- * the entire time. Everything the status endpoint measured was true — the- * process was up, the feed was connected, strategies were armed — and none of+ * the entire time. Everything the status endpoint measured was true (the+ * process was up, the feed was connected, strategies were armed), and none of* it was the thing that mattered. The wallets were too poor to place a single* buy, and the funding master they refill from was itself down to dust, so the* auto-funder could not fix it either.@@ -17,7 +17,7 @@* every check that only looks at the process.** The rule that keeps this honest: a wallet's trade state is decided by- * `resolveEntrySize` — the SAME function the executor calls to size or skip a+ * `resolveEntrySize`, the SAME function the executor calls to size or skip a* real entry (api/_lib/agent-trade-guards.js, used at workers/agent-sniper/* executor.js step 4). Duplicating its thresholds here is how this surface* would drift into claiming "tradeable" for a wallet the executor skips, which@@ -52,10 +52,10 @@ function toLamports(sol) {/*** What one wallet can do with its next entry, per the executor's own sizing rule.*- * 'funded' — can place the arm's configured size- * 'shrunk' — can still trade, but only below the configured size (the+ * 'funded' : can place the arm's configured size+ * 'shrunk' : can still trade, but only below the configured size (the* executor shrinks rather than skips: learning > profit)- * 'starved' — cannot place any entry; the executor sits this wallet out+ * 'starved' : cannot place any entry; the executor sits this wallet out** @param {number} balanceSol current wallet balance* @param {number} perTradeSol the arm's configured per-trade size@@ -79,16 +79,16 @@ export function walletTradeState(balanceSol, perTradeSol, minTradeLamports = DEF* `state` is the headline, and it is deliberately about capability rather than* count: a fleet where every wallet is starved is `starved` no matter how many* strategies are armed, because the honest answer to "is the sniper working" is- * no. One tradeable wallet among starved ones is `degraded` — it still trades,+ * no. One tradeable wallet among starved ones is `degraded`: it still trades,* just not at fleet strength.*- * 'unknown' — nothing measured yet (no armed wallets, or balances unread)- * 'funded' — every wallet can place its configured size- * 'degraded' — at least one wallet can still trade, at least one cannot- * 'starved' — no wallet can place any entry; the fleet is financially dead+ * 'unknown' : nothing measured yet (no armed wallets, or balances unread)+ * 'funded' : every wallet can place its configured size+ * 'degraded' : at least one wallet can still trade, at least one cannot+ * 'starved' : no wallet can place any entry; the fleet is financially dead** `deficitSol` is what it would cost to lift every starved wallet back to its- * own refill target — i.e. the number to hand an operator who asks "how much+ * own refill target, i.e. the number to hand an operator who asks "how much* SOL does this need?". `masterCanCover` answers whether the auto-funder can* close that gap by itself, which is the difference between "it will heal in* five minutes" and "a human has to move money".@@ -167,7 +167,7 @@ export function summarizeFleetSolvency({ wallets, masterSol = null, minTradeLamp* (nothing else can be true). Solvency outranks the feed checks: "no wallet can* pay for a trade" is both more specific and more actionable than "the feed is* quiet", and it is the condition that went unreported for ten days. An- * unmeasured fleet ('unknown') never downgrades anything — absence of a+ * unmeasured fleet ('unknown') never downgrades anything: absence of a* measurement is not evidence of insolvency.** Pure. Exported so the verdict is testable without a DB or a live worker.diff --git a/api/sniper/status.js b/api/sniper/status.jsindex 54ccc8e19..bcee5c8ac 100644--- a/api/sniper/status.js+++ b/api/sniper/status.js@@ -14,7 +14,7 @@* feedLive — the worker reports its feed subscription is currently up* degraded — alive but the feed has been silent past its watchdog window* (up but deaf), or part of the fleet can no longer trade- * starved — alive, feed fine, and NO armed wallet can afford an entry+ * starved : alive, feed fine, and NO armed wallet can afford an entry** That last state is why this endpoint no longer answers liveness alone. From* 2026-07-29 to 2026-08-08 it reported `live` continuously while the fleet@@ -134,7 +134,7 @@ export default wrap(async (req, res) => {// Money before mechanics: a worker that cannot fund an entry is not 'live', no// matter how healthy its feed is. Absent (older worker build, first tick not- // yet run) degrades to 'unknown', which never overrides the feed verdict — an+ // yet run) degrades to 'unknown', which never overrides the feed verdict (an// unmeasured fleet must not read as a broke one.const solvency = meta.solvency && typeof meta.solvency === 'object' ? meta.solvency : null;const state = deriveSniperState({diff --git a/docs/play-hardening.md b/docs/play-hardening.mdnew file mode 100644index 000000000..dbbf1972a--- /dev/null+++ b/docs/play-hardening.md@@ -0,0 +1,128 @@+# How `/play` stays safe, honest, and light++`/play` is the GTA-style coin-community world at [three.ws/play](https://three.ws/play). It is the largest interactive surface on the platform: a shared 3D city per pump.fun coin, with a server-authoritative economy, combat, quests, vehicles, voice chat, and live peers.++It is also the surface with the least trusted input. Its entry URL is a link strangers share:++```+/play?coin=<mint>&name=<name>&symbol=<sym>&image=<url>+```++Every part of that URL, every display name a peer picks, and every field of the pump.fun coin metadata is text an attacker chose. This document records the invariants that keep the world safe and honest, so that a future change does not quietly undo one of them. Each section names the failure it prevents, because each of these actually shipped once.++Related docs: [in-game economy](./in-game-economy.md), [architecture](./architecture.md), [security](./security.md).++---++## 1. Untrusted text never becomes markup++**Invariant: every user- or network-controlled string is written with `textContent`, never `innerHTML`.**++The `/play` UI modules share an `el()` helper that supports an `html:` property. That property is for *static literals only*. If you find yourself interpolating a variable into it, you have found a bug.++The one place this was violated was the tombstone loot prompt in [src/game/combat-system.js](../src/game/combat-system.js). It built its prompt as a template string containing `nearest.t.owner`, which is a remote player's chosen display name, replicated to every client:++```js+// WRONG: shipped, and exploitable+this.prompt.innerHTML = `<span class="combat-key">E</span> Loot ${nearest.t.owner}…`;+```++The server's only name gate is a hate-slur word list ([multiplayer/src/display-name-safety.js](../multiplayer/src/display-name-safety.js)), which is not an HTML escaper. A player could name themselves `<img src=x onerror=…>`, die in a danger zone, and have the payload execute for every player who walked near their tombstone. The fix builds the prompt from real nodes:++```js+const key = document.createElement('span');+key.className = 'combat-key';+key.textContent = 'E';+this.prompt.replaceChildren(key, document.createTextNode(` Loot ${nearest.t.owner}…`));+```++**When you add a prompt, label, nameplate, chat line, or panel row that shows a name, a coin symbol, quest text, or anything from an API: use `textContent`.**++## 2. A coin image cannot escape its CSS declaration++**Invariant: a URL that lands inside a CSS `url(...)` value goes through `cssBgImage()` in [src/game/coincommunities-ui.js](../src/game/coincommunities-ui.js).**++Lobby cards paint the coin's artwork as a background image. `proxiedImageURL()` ([src/ipfs.js](../src/ipfs.js)) only URL-encodes values matching `^(https?|ipfs|ar):`; anything else is returned unchanged. So a coin minted with an `image_uri` of++```+x");position:fixed;inset:0;z-index:99999;background:#000 url(//evil/phish.png);content:"+```++would close the `url()`, close the declaration, and paint a full-viewport overlay (a fake wallet prompt, say) over the lobby of everyone browsing trending coins. The same raw value rides in `?image=` on a shared link.++`cssBgImage()` refuses script-bearing schemes and percent-encodes every character that could terminate the value:++```js+el('div', { class: 'cc-card-img', style: cssBgImage(c.image) }, …)+```++The payload may still be *present* in the output, but only ever as inert text inside one URL. [tests/play-deeplink-safety.test.js](../tests/play-deeplink-safety.test.js) proves this with a real CSS parser: it sets the returned style on a jsdom element and asserts that `position`, `inset`, `z-index` and `content` are all empty and only `background-image` is set.++## 3. A broken world link says so++**Invariant: `?coin=` is validated against `isPlausibleMint()` before any world is built.**++A mint is either a Solana base58 address (pump.fun mints, including `$THREE`) or an EVM `0x` address (Robinhood Chain coins). `/play?coin=notarealmint` used to build a complete, convincing world: a real district, a totem reading "COMMUNITY", a Colyseus room keyed on the garbage string, and a persistent build layer no other player would ever see. Nothing anywhere told the visitor the link was broken.++Now a malformed mint leaves the player in the lobby with a plain explanation, one tap from every real world. `name` and `symbol` are separately clamped by `clampParam()` to the same caps the room server enforces, with control characters, line breaks, bidi overrides and zero-width characters stripped, so a 10 KB `name=` cannot rewrap the HUD.++## 4. Losing the connection recovers cleanly++**Invariant: a reconnect must retire the peers who left while you were offline.**++`CommunityNet` reconnects with a fresh `joinOrCreate`, and it removes the old room's listeners *before* leaving it (deliberately, to avoid duplicate-socket bugs). Two consequences follow, and both are load-bearing:++1. The old room's `onRemove` never fires, so peers from before the drop are never cleaned up by the normal path.+2. Colyseus reissues session ids, so the same human can come back under a new key.++`_markRemotesStale()` flags every current peer when the socket goes to `connecting`; the fresh room's `add` events clear the flag; `_pruneStaleRemotes()` retires whatever is still flagged once the snapshot lands. Both live in [src/game/coincommunities.js](../src/game/coincommunities.js).++These two methods were *called* on every drop but never *defined*, so a reconnect threw a `TypeError` and ghosts accumulated: two drops in a ten-person world left thirty avatars on screen, twenty of them frozen, with the online count reporting triple the truth. If you rename or move them, update both call sites and [scripts/play-desktop-audit.mjs](../scripts/play-desktop-audit.mjs), which asserts they are callable in a real browser.++Related: the death overlay hides on a `respawn` notice, but a reconnect re-sends the authoritative profile without any notice. `_applyVitals()` in [src/game/combat-system.js](../src/game/combat-system.js) clears the overlay whenever the server says `hp > 0`, so nobody rejoins a live world stuck behind "You died".++## 5. The world frees what it loads++**Invariant: anything that allocates GPU memory has a disposal path, and that path runs when the player leaves.**++This is the difference between "works on a laptop" and "works on a phone". Detaching an object from the scene graph (`scene.remove(...)`) drops the JS reference but leaks the geometry, materials and textures. On iOS Safari, the accumulated pressure shows up as a `webglcontextlost` event and a killed tab, which reads to the player as being randomly kicked out of the world.++The rules:++- **Avatars go through `releaseAvatar(rig)`** from [src/game/avatar-rig.js](../src/game/avatar-rig.js), never a bare `scene.remove()`. That module keeps one download + parse per distinct model URL and hands out `SkeletonUtils` clones; `releaseAvatar` disposes the per-rig materials, drops the template's refcount, and evicts idle templates past the memory budget. NPCs ([src/game/npc/npc.js](../src/game/npc/npc.js)), ambient pedestrians ([src/game/npc/ambient-life.js](../src/game/npc/ambient-life.js)) and the local player all call it. **A rig disposed while its GLB is still downloading must also call it in the `then`,** or the clone that lands on the detached rig holds its template resident forever. Pedestrians churn on every peer join/leave, so that path is hot.+- **Lights need explicit disposal.** A `traverse` that only handles `isMesh` skips them, and the sun's 2048x2048 shadow map is one of the largest allocations in the world. `world-env.js`'s `dispose()` frees it directly.+- **`leave()` disposes, it does not merely detach.** The totem, jumbotron and dance floor go through `_disposeObject3D()`; the environment, district and day/night cycle are freed on the way out rather than being held until the *next* `enter()`, so returning to the lobby no longer keeps a whole city resident with nothing rendering it.++## 6. Every failure has a designed, actionable state++**Invariant: no indefinite spinner, no blank void, no green checkmark on a failure.**++Examples currently holding the line:++- The **jobs board** ([src/game/quests-ui.js](../src/game/quests-ui.js)) shows "Loading the jobs board…" until the first server snapshot lands. It used to render "No jobs on the board right now" before the server had answered, telling players on a slow link that there was no work a beat before it all appeared.+- The **Wheel of Fortune** ([src/game/spin-wheel-ui.js](../src/game/spin-wheel-ui.js)) reaches its documented `error` phase: if `spinInfo` never arrives it says so and offers a retry, instead of sitting on "Loading the wheel…" forever with both buttons dead. It also ships its own stylesheet ([src/game/spin-wheel.css](../src/game/spin-wheel.css)), because it is a lazy chunk and cannot assume `coincommunities.css` loaded.+- **Closing the wheel mid-payment does not discard a paid spin.** Once the transaction is broadcast, real money has moved; closing the modal detaches it but keeps the server subscriptions alive and delivers the outcome (and its Solscan receipt) in a background pill. Previously, dismissing the wallet overlay with <kbd>Esc</kbd> unsubscribed the result handlers and the player lost $3 with nothing shown.+- The **boutique purchase flow** ([src/game/boutique-purchase.js](../src/game/boutique-purchase.js)) rejects on the server's own failure notices rather than treating any `boutique` notice as success.+- The **boot loader** cannot strand: an inline watchdog in [pages/play.html](../pages/play.html) replaces the spinner with a real error card (with a retry) if a script or stylesheet fails, and `enter()` failures tear down and return a working lobby.++## Verifying a change++```bash+# Pure-logic guards: CSS-injection, mint validation, param clamping.+npx vitest run tests/play-deeplink-safety.test.js++# Everything else that touches the surface.+npx vitest run tests/play-gate.test.js tests/play-pass.test.js \+ tests/minimap-projection.test.js tests/quests-vehicle-delivery.test.js \+ tests/play-friends-presence.test.js++# A real browser: console errors, boot, reconnect helpers, CSS injection,+# malformed mints, wheel styles. Point it at prod or a local `npm run dev`.+node scripts/play-desktop-audit.mjs "https://three.ws/play?coin=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"++# Phone emulation: transferred bytes, heap growth, WebSocket lifecycle, and+# every GLB load attributed to the code that asked for it.+ENGINE=webkit node scripts/play-mobile-repro.mjs "https://three.ws/play" 120000+```++The mobile harness is the one that catches memory regressions. It reports total transferred bytes grouped by path, so a change that starts re-downloading avatars shows up as a jump in the `/avatars/*` and `/r2-proxy/*` rows rather than as a mysterious crash report weeks later.diff --git a/multiplayer/src/world-features.js b/multiplayer/src/world-features.jsindex dd512b9f0..eee839d83 100644--- a/multiplayer/src/world-features.js+++ b/multiplayer/src/world-features.js@@ -124,7 +124,7 @@ export const WHEEL_REACH = 3.0;export function nearestWheel(x, z) { return nearestNode(x, z, WHEEL, WHEEL_REACH); }export function wheelInRange(x, z) { return nodeInRange(x, z, WHEEL, WHEEL_REACH); }-// The cash counters — the general store's vendor stalls and the bank/ATM (W04).+// The cash counters: the general store's vendor stalls and the bank/ATM (W04).//// Mirrors of the 'vendor' and 'atm' spawns in src/game/world-zones.js, where the// economy NPCs stand (tests/play-counters.test.js pins the two lists equal, so adiff --git a/pages/play/war.html b/pages/play/war.htmlnew file mode 100644index 000000000..286d01409--- /dev/null+++ b/pages/play/war.html@@ -0,0 +1,102 @@+<!doctype html>+<html lang="en" data-theme="dark">+<head>+ <style>/* three.ws hidden-guard — make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>Coin Wars arena — fight for your community · three.ws</title>+ <meta name="description" content="The live Coin Wars arena: two coin communities meet in one 3D battlefield, fight to the kill cap, and the result lands on the war league ladder. You fight for the coin you hold." />+ <meta property="og:title" content="Coin Wars arena · three.ws" />+ <meta property="og:description" content="Two coin communities, one battlefield. Hold the coin, enlist from your world's war portal, and fight for the ladder." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/play/war" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Coin+Wars+arena&d=Two+coin+communities+meet+in+one+3D+battlefield.+Hold+the+coin%2C+enlist+at+your+world%27s+war+portal%2C+and+fight+for+the+league+ladder.&p=%2Fplay%2Fwar" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Coin Wars arena · three.ws" />+ <meta name="twitter:description" content="Two coin communities, one battlefield. Hold the coin, enlist from your world's war portal, and fight for the ladder." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Coin+Wars+arena&d=Two+coin+communities+meet+in+one+3D+battlefield.+Hold+the+coin%2C+enlist+at+your+world%27s+war+portal%2C+and+fight+for+the+league+ladder.&p=%2Fplay%2Fwar" />+ <link rel="canonical" href="https://three.ws/play/war" />+ <link rel="icon" href="/favicon.ico" />+ <link rel="preload" href="/animations/manifest.json" as="fetch" crossorigin />+ <link rel="preload" href="/avatars/default.glb" as="fetch" crossorigin />+ <meta name="robots" content="index, follow, max-image-preview:large" />+</head>+<body>+ <canvas id="scene" aria-label="Coin Wars battlefield"></canvas>+ <div class="war-vignette" aria-hidden="true"></div>+ <div id="labels" aria-hidden="true"></div>++ <!-- Loading / working. Never a spinner alone: it always says what it is doing. -->+ <div id="status" class="war-status" role="status" aria-live="polite">+ <span class="war-spinner" aria-hidden="true"></span>+ <span id="status-text">Preparing the arena…</span>+ </div>++ <!-- The battle HUD. Hidden until the room is joined. -->+ <header id="hud" class="war-hud" hidden>+ <div class="war-side war-side-us">+ <span id="score-us" class="war-score">0</span>+ <span class="war-side-meta">+ <span id="name-us" class="war-side-name">Your community</span>+ <span id="roster-us" class="war-side-roster">0 fighting</span>+ </span>+ </div>+ <div class="war-mid">+ <span id="clock" class="war-clock">—</span>+ <span id="cap" class="war-cap"></span>+ <span class="war-coin">+ <img id="coin-img" class="war-coin-img" alt="" hidden />+ <span id="coin-label"></span>+ </span>+ </div>+ <div class="war-side war-side-them">+ <span id="score-them" class="war-score">0</span>+ <span class="war-side-meta">+ <span id="name-them" class="war-side-name">Opponent</span>+ <span id="roster-them" class="war-side-roster">0 fighting</span>+ </span>+ </div>+ </header>++ <p id="phase" class="war-phase" role="status" aria-live="polite" hidden></p>+ <p id="lobby-note" class="war-lobby-note" hidden></p>++ <!-- Controls. Hidden until joined; the stick is thumb-sized on phones. -->+ <div id="controls" class="war-controls" hidden>+ <div id="stick" class="war-stick no-orbit" aria-label="Move">+ <span id="stick-nub" class="war-stick-nub" aria-hidden="true"></span>+ </div>+ <div class="war-right">+ <dl class="war-vitals" aria-label="Your record this battle">+ <div><dt>Kills</dt><dd id="kills">0</dd></div>+ <div><dt>Downs</dt><dd id="deaths">0</dd></div>+ </dl>+ <button id="attack" class="war-attack no-orbit" type="button">Fire<small>space</small></button>+ <button id="leave" class="war-leave no-orbit" type="button">Leave</button>+ </div>+ <p id="downed" class="war-downed" role="status" hidden>You are down — respawning shortly.</p>+ </div>++ <!-- Terminal states. Both are designed cards with the one way out. -->+ <div id="result" class="war-modal" role="dialog" aria-modal="true" aria-labelledby="result-title" hidden>+ <div class="war-modal-card">+ <h1 id="result-title" class="war-result-title">Battle over</h1>+ <p id="result-score" class="war-result-score"></p>+ <p id="result-reason" class="war-modal-b"></p>+ <p id="result-mvp" class="war-modal-b war-modal-faint"></p>+ <button id="result-back" class="war-modal-btn" type="button">Back to the world</button>+ </div>+ </div>++ <div id="fail" class="war-modal" role="dialog" aria-modal="true" aria-labelledby="fail-title" hidden>+ <div class="war-modal-card">+ <h1 id="fail-title" class="war-fail-title">No battle to join</h1>+ <p id="fail-detail" class="war-modal-b"></p>+ <button id="fail-back" class="war-modal-btn" type="button">Back to the world</button>+ </div>+ </div>++ <script type="module" src="/src/play/war.js"></script>+</body>+</html>diff --git a/scripts/meetup-audit.mjs b/scripts/meetup-audit.mjsindex c864f6207..91c8732dc 100644--- a/scripts/meetup-audit.mjs+++ b/scripts/meetup-audit.mjs@@ -127,14 +127,22 @@ check('zen mode hides the event UI', await page.evaluate(() => {await page.keyboard.press('z');await page.waitForTimeout(600);-// --- photo --------------------------------------------------------------------+// --- photo ----------------------------------------------------------------------+// The agenda's photo action hands off to /play's shared photo mode+// (src/game/photo-mode.js), which stamps the shot with this same event.await page.evaluate(() => document.getElementById('cc-meetup-chip')?.click());await page.waitForSelector('#cc-meetup-panel.cc-meetup-panel--open', { timeout: 8000 }).catch(() => {});-const download = page.waitForEvent('download', { timeout: 30_000 }).catch(() => null);await page.evaluate(() => document.querySelector('.cc-meetup-photo-btn')?.click());-const dl = await download;-check('commemorative photo downloads a framed image', !!dl, dl ? dl.suggestedFilename() : 'no download event');-if (dl) await dl.saveAs(`${SHOTS}/03-photo.jpg`).catch(() => {});+const photoCard = await page.waitForSelector('.cc-photo-card', { timeout: 30_000 }).catch(() => null);+check('photo action opens the shared photo mode', photoCard);+check('agenda drawer gets out of the shot', await page.evaluate(() =>+ !document.querySelector('#cc-meetup-panel.cc-meetup-panel--open')));+check('photo card offers a download of the framed shot', await page.evaluate(() => {+ const a = document.querySelector('.cc-photo-card a.cc-photo-primary[download]');+ return !!a && /^blob:/.test(a.href);+}));+await page.screenshot({ path: `${SHOTS}/03-photo.png`, timeout: 60_000 }).catch(() => {});+await page.keyboard.press('Escape');// --- mobile ---------------------------------------------------------------------await page.setViewportSize({ width: 390, height: 844 });diff --git a/scripts/play-economy-audit.mjs b/scripts/play-economy-audit.mjsindex 2a396006e..bdb9d05a7 100644--- a/scripts/play-economy-audit.mjs+++ b/scripts/play-economy-audit.mjs@@ -30,7 +30,7 @@ const log = (...a) => console.log(...a);const results = [];function check(name, pass, detail) {results.push({ name, pass });- log(`${pass ? ' ok ' : ' FAIL '} ${name}${detail ? ` — ${detail}` : ''}`);+ log(`${pass ? ' ok ' : ' FAIL '} ${name}${detail ? `: ${detail}` : ''}`);}// Every targeted message the economy speaks, captured as it arrives. The roomdiff --git a/scripts/play-journey-audit.mjs b/scripts/play-journey-audit.mjsindex 26ef260b2..1329e1cb1 100644--- a/scripts/play-journey-audit.mjs+++ b/scripts/play-journey-audit.mjs@@ -155,7 +155,17 @@ async function touchScan(label) {async function focusSweep(label) {const res = await page.evaluate(() => {const TABBABLE = 'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';- const ring = (cs) => `${cs.outlineStyle}|${cs.outlineWidth}|${cs.outlineColor}|${cs.boxShadow}|${cs.borderColor}|${cs.backgroundColor}`;+ // A focus indicator is often painted on a ::before/::after ring rather than+ // the control itself, so the fingerprint has to cover the pseudo-elements+ // too or a perfectly visible ring reads as missing.+ const style = (n) => {+ const parts = [];+ for (const pseudo of [null, '::before', '::after']) {+ const cs = getComputedStyle(n, pseudo);+ parts.push(`${cs.outlineStyle}|${cs.outlineWidth}|${cs.outlineColor}|${cs.boxShadow}|${cs.borderColor}|${cs.backgroundColor}|${cs.opacity}`);+ }+ return parts.join('##');+ };const out = { total: 0, noRing: [], notFocusable: [] };const prev = document.activeElement;for (const n of document.querySelectorAll(TABBABLE)) {@@ -164,7 +174,7 @@ async function focusSweep(label) {const cs0 = getComputedStyle(n);if (r.width === 0 || r.height === 0 || cs0.visibility === 'hidden' || cs0.display === 'none') continue;out.total++;- const resting = ring(cs0);+ const resting = style(n);n.focus({ preventScroll: true });const focused = document.activeElement === n;const desc = {@@ -172,7 +182,7 @@ async function focusSweep(label) {label: (n.getAttribute('aria-label') || n.title || n.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 34),};if (!focused) { out.notFocusable.push(desc); continue; }- if (ring(getComputedStyle(n)) === resting) out.noRing.push(desc);+ if (style(n) === resting) out.noRing.push(desc);n.blur();}if (prev && prev.focus) prev.focus({ preventScroll: true });@@ -267,7 +277,11 @@ const introDismissed = await page.evaluate(() => {});if (introDismissed) console.log(at(), '[dismissed] cold-open intro');await page.waitForTimeout(600);-await tabTrapCheck('lobby');+// Opt-in: a real Tab press costs a page round trip, and on a machine rendering+// this world in software that is seconds each. focusSweep above already proves+// reachability, so the trap check is only worth its minutes when something+// looks wrong with the tab order specifically.+if (process.env.TAB_CHECK === '1') await tabTrapCheck('lobby');// ── 2. search: a query with hits, then one with none ───────────────────────const search = await page.$('.cc-search input');diff --git a/scripts/play-multiplayer-e2e.mjs b/scripts/play-multiplayer-e2e.mjsindex d71aba080..aefd8adf1 100644--- a/scripts/play-multiplayer-e2e.mjs+++ b/scripts/play-multiplayer-e2e.mjs@@ -43,13 +43,24 @@ function check(name, ok, detail = '') {return ok;}+// page.evaluate has no timeout of its own: a page whose main thread is wedged+// (a stuck render loop, a renderer starved on a loaded box) never resolves it,+// and a polling loop built on it hangs forever instead of failing its check.+// Race every probe so a hung page reads as a failed assertion, not a dead run.+function evalWithTimeout(page, fn, arg, ms = 15000) {+ return Promise.race([+ page.evaluate(fn, arg),+ new Promise((resolve) => setTimeout(() => resolve({ evalError: `page did not answer in ${ms}ms` }), ms)),+ ]);+}+// Poll a page expression until it is truthy or the deadline passes. Returns the// last value seen, so a failed wait can report what it actually got.async function until(page, fn, { timeout = 30000, every = 250, arg } = {}) {const deadline = Date.now() + timeout;let last;for (;;) {- try { last = await page.evaluate(fn, arg); } catch (err) { last = { evalError: String(err).slice(0, 120) }; }+ try { last = await evalWithTimeout(page, fn, arg); } catch (err) { last = { evalError: String(err).slice(0, 120) }; }if (last && !last.evalError && (last === true || last.ok !== false)) {if (last === true || last.ok === true) return last;}@@ -149,7 +160,7 @@ async function openClient(browser, tag, name) {// Onboarding cards and the intro sheet sit over the world; clear whatever is up.async function dismissOverlays(page, rounds = 4) {for (let i = 0; i < rounds; i++) {- const clicked = await page.evaluate(() => {+ const clicked = await evalWithTimeout(page, () => {const btn = [...document.querySelectorAll('button')].find((b) => /^(continue|enter the world|got it|start|close|skip|drop in now)$/i.test(b.textContent.trim()) && b.offsetParent,);@@ -169,7 +180,7 @@ async function sendChat(page, text) {// Drive the local avatar to a position and let the send loop publish it. Uses the// same sendMove the input handler calls, so this exercises the real wire.async function moveTo(page, x, z) {- await page.evaluate(({ x, z }) => {+ await evalWithTimeout(page, ({ x, z }) => {const cc = window.__CC__;cc.localPos.x = x; cc.localPos.z = z;cc.net.sendMove({ x, y: cc.localPos.y, z, yaw: cc.localYaw, motion: 'walk' });@@ -204,7 +215,7 @@ try {check('B sees A', bSees?.ok === true, JSON.stringify(bSees));// ------------------------------------------------------- name + look sync- let bSnap = await b.page.evaluate(snapshot);+ let bSnap = await evalWithTimeout(b.page, snapshot);check('B renders A\'s display name on the nameplate',bSnap.remotes.some((r) => r.name === 'AliceQA'),JSON.stringify(bSnap.remotes.map((r) => r.name)));@@ -224,7 +235,7 @@ try {check('A\'s movement reaches B', moved?.ok === true, `${Date.now() - moveStart}ms · ${JSON.stringify(moved)}`);// --------------------------------------------------------------- emotes- await a.page.evaluate(() => window.__CC__.net.sendEmote('wave'));+ await evalWithTimeout(a.page, () => window.__CC__.net.sendEmote('wave'));const emoted = await until(b.page, () => {const st = window.__CC__?.net?.state;const players = st?.players ? [...st.players.values()] : [];@@ -254,7 +265,7 @@ try {const xss = '<img src=x onerror="window.__XSS__=1"><b>bold</b>';await sendChat(a.page, xss);await b.page.waitForTimeout(1200);- const escaped = await b.page.evaluate((raw) => {+ const escaped = await evalWithTimeout(b.page, (raw) => {const rows = [...document.querySelectorAll('.cc-chat-msg .cc-chat-text')];const row = rows.find((n) => n.textContent === raw);return {@@ -273,16 +284,16 @@ try {const burst = Date.now();for (let i = 0; i < 8; i++) await sendChat(a.page, `spam-${burst}-${i}`);await b.page.waitForTimeout(2000);- const delivered = await b.page.evaluate((tag) =>+ const delivered = await evalWithTimeout(b.page, (tag) =>[...document.querySelectorAll('.cc-chat-msg .cc-chat-text')].filter((n) => n.textContent.startsWith(`spam-${tag}-`)).length, burst);check('chat burst is throttled server-side', delivered < 8, `${delivered}/8 relayed`);// The log must not grow without bound — the UI caps it.- const capped = await b.page.evaluate(() => document.querySelectorAll('.cc-chat-msg').length <= 200);+ const capped = await evalWithTimeout(b.page, () => document.querySelectorAll('.cc-chat-msg').length <= 200);check('chat log is capped in the DOM', capped === true);// ------------------------------------------------------- forced disconnect- const aBefore = await a.page.evaluate(snapshot);+ const aBefore = await evalWithTimeout(a.page, snapshot);console.log(`${at()} [A] going offline for ${OFFLINE_MS}ms (session ${aBefore.sessionId})`);await a.ctx.setOffline(true);const dropped = await until(a.page, () => {@@ -290,14 +301,14 @@ try {return { ok: s !== 'online', status: s };}, { timeout: 30000, every: 250 });check('A notices the drop', dropped?.ok === true, JSON.stringify(dropped));- const pill = await a.page.evaluate(() => document.querySelector('#cc-hud [role]')?.textContent || document.body.innerText.match(/reconnecting…|offline, tap to retry/i)?.[0] || null);+ const pill = await evalWithTimeout(a.page, () => document.querySelector('#cc-hud [role]')?.textContent || document.body.innerText.match(/reconnecting…|offline, tap to retry/i)?.[0] || null);check('A shows a reconnect indicator while down', /reconnect|offline/i.test(String(pill)), String(pill).slice(0, 60));await a.page.waitForTimeout(OFFLINE_MS);await a.ctx.setOffline(false);// Simulate the tab coming back to the foreground: the same path a phone takes// after Safari froze the page, and the fast lane out of the retry backoff.- await a.page.evaluate(() => {+ await evalWithTimeout(a.page, () => {document.dispatchEvent(new Event('visibilitychange'));dispatchEvent(new Event('online'));});@@ -307,7 +318,7 @@ try {}, { timeout: 20000, every: 250 });check('A reconnects automatically after the network returns', back?.ok === true, JSON.stringify(back));- const aAfter = await a.page.evaluate(snapshot);+ const aAfter = await evalWithTimeout(a.page, snapshot);check('A gets a fresh session on reconnect', !!aAfter.sessionId && aAfter.sessionId !== aBefore.sessionId,`${aBefore.sessionId} → ${aAfter.sessionId}`);check('A\'s roster after resync holds exactly one peer (no ghosts)', aAfter.remotes.length === 1,diff --git a/scripts/play-scene-cost.mjs b/scripts/play-scene-cost.mjsnew file mode 100644index 000000000..27cdf9b40--- /dev/null+++ b/scripts/play-scene-cost.mjs@@ -0,0 +1,104 @@+// Scene-cost probe for a /play world: how many objects the renderer has to+// submit per frame, and how much geometry/texture memory the world holds.+//+// node scripts/play-scene-cost.mjs "<url>" [settleSeconds]+//+// These are the numbers that decide frame rate on a real GPU, and unlike a+// frames-per-second reading they are hardware-independent: a draw call is a+// draw call whether the rasterizer is a laptop GPU or the software fallback CI+// runs on. Deliberately small viewport and short run so it finishes in a minute+// even under swiftshader; use scripts/play-perf-audit.mjs for network, frame+// timing and heap growth.+import { chromium } from 'playwright';++const TARGET = process.argv[2] || 'http://localhost:3000/play';+const SETTLE_MS = Number(process.argv[3] || 25) * 1000;+const LABEL = process.env.LABEL || 'scene';++const browser = await chromium.launch({+ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'],+});+const page = await browser.newPage({ viewport: { width: 640, height: 400 } });+const t0 = Date.now();+const at = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;+const notes = [];+page.on('console', (m) => {+ const t = m.text();+ // The world environment reports its own batching totals; capture them.+ if (/\[world-env]/.test(t)) notes.push(t.slice(0, 200));+ if (m.type() === 'error') notes.push('[error] ' + t.slice(0, 160));+});+page.on('pageerror', (e) => notes.push('[pageerror] ' + String(e).slice(0, 200)));++await page.goto(TARGET, { waitUntil: 'domcontentloaded', timeout: 240000 });+console.log(at(), 'domcontentloaded');++try {+ await page.waitForSelector('.pi-btn-primary', { timeout: 30000 });+ await page.click('.pi-btn-primary');+} catch { /* deep link drops straight in */ }++// The environment is the last thing world entry builds before it waits on the+// room socket, so it is the right readiness signal for a scene-cost read: it+// does not depend on multiplayer being reachable from wherever this runs.+await page.waitForFunction(() => !!window.__CC__?.env, null, { timeout: 240000 });+console.log(at(), 'world environment built');+await page.waitForTimeout(SETTLE_MS);++const cost = await page.evaluate(() => {+ const g = window.__CC__;+ const r = g.renderer;+ const geoms = new Set(), mats = new Set(), texes = new Set();+ let meshes = 0, instanced = 0, instances = 0, skinned = 0, lights = 0, sprites = 0, shadowCasters = 0;+ let attrBytes = 0, texPixels = 0;+ g.scene.traverse((o) => {+ if (o.isLight) lights++;+ if (o.isSprite) sprites++;+ if (o.isInstancedMesh) { instanced++; instances += o.count; }+ else if (o.isSkinnedMesh) skinned++;+ else if (o.isMesh) meshes++;+ if (o.castShadow && (o.isMesh || o.isInstancedMesh)) shadowCasters++;+ if (o.geometry && !geoms.has(o.geometry.uuid)) {+ geoms.add(o.geometry.uuid);+ for (const a of Object.values(o.geometry.attributes || {})) attrBytes += a?.array?.byteLength || 0;+ attrBytes += o.geometry.index?.array?.byteLength || 0;+ }+ for (const m of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {+ if (mats.has(m.uuid)) continue;+ mats.add(m.uuid);+ for (const v of Object.values(m)) {+ if (v?.isTexture && !texes.has(v.uuid)) {+ texes.add(v.uuid);+ if (v.image?.width) texPixels += v.image.width * v.image.height;+ }+ }+ }+ });+ return {+ drawCalls: r.info.render.calls,+ triangles: r.info.render.triangles,+ programs: r.info.programs?.length || 0,+ geometriesResident: r.info.memory.geometries,+ texturesResident: r.info.memory.textures,+ sceneObjects: (() => { let n = 0; g.scene.traverse(() => n++); return n; })(),+ meshes, instancedMeshes: instanced, instances, skinnedMeshes: skinned,+ lights, sprites, shadowCasters,+ uniqueGeometries: geoms.size,+ uniqueMaterials: mats.size,+ uniqueTextures: texes.size,+ geometryMB: +(attrBytes / 1048576).toFixed(2),+ textureMB: +((texPixels * 4) / 1048576).toFixed(2),+ biome: g.env?.biome?.id || null,+ phase: g.phase,+ };+});++console.log(`\n===== SCENE COST (${LABEL}) =====`);+for (const [k, v] of Object.entries(cost)) console.log(' ' + k.padEnd(20), v);+if (notes.length) {+ console.log('\n--- console ---');+ for (const n of [...new Set(notes)].slice(0, 10)) console.log(' ' + n);+}++if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT, timeout: 30000 }).catch(() => {});+await browser.close();diff --git a/scripts/play-souvenir-e2e.mjs b/scripts/play-souvenir-e2e.mjsnew file mode 100644index 000000000..f53869524--- /dev/null+++ b/scripts/play-souvenir-e2e.mjs@@ -0,0 +1,354 @@+// End-to-end conformance run for the /play event souvenir drop.+//+// Proves the four properties the feature promises, against a real browser, a+// real Colyseus server and a real persistence round-trip:+//+// 1. LIVE WINDOW → the souvenir is granted on join, announced once, equips,+// and shows on the avatar and in the wardrobe.+// 2. IDEMPOTENT → a full reconnect as the same account re-grants nothing:+// no second announcement, no duplicate in the owned list, and the item is+// still worn (it persisted).+// 3. VISIBLE TO PEERS → a second player in the world sees the wearer's+// loadout on the shared schema, which is what makes a souvenir social.+// 4. CLOSED WINDOW → a fresh account joining after the event ends is granted+// nothing, while an account that earned it earlier still wears it.+//+// The event config is served from THIS process (a throwaway static endpoint) so+// nothing in the repo is edited to fake a live window, and the window can be+// opened and closed between phases of one run. Point the game server at it with+// EVENT_CONFIG_URL — see below.+//+// Requires vite on :3000 and colyseus on :2567 with the config override:+//+// node scripts/play-souvenir-e2e.mjs # boots both servers itself+// EXTERNAL=1 node scripts/play-souvenir-e2e.mjs # you started them yourself+//+// Exit code is 0 only when every check passes.++import { chromium } from 'playwright';+import { createServer } from 'node:http';+import { spawn } from 'node:child_process';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const BASE = (process.env.BASE || 'http://localhost:3000').replace(/\/$/, '');+const MINT = process.env.COIN || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const WORLD = `${BASE}/play?coin=${encodeURIComponent(MINT)}&name=three.ws&symbol=three`;+const SOUVENIR_ID = 'laurel-meetup';+const CONFIG_PORT = Number(process.env.CONFIG_PORT || 4599);+const EXTERNAL = process.env.EXTERNAL === '1';+const LOAD_MS = Number(process.env.LOAD_MS || 300_000);+const JOIN_MS = Number(process.env.JOIN_MS || 180_000);++const t0 = Date.now();+const at = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;+const results = [];++function check(name, ok, detail = '') {+ results.push({ name, ok, detail });+ console.log(`${at()} ${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`);+ return ok;+}++// ── the event config this run controls ─────────────────────────────────────++// `live` flips the window between "happening right now" and "ended an hour ago"+// without touching public/event.json. The game server re-reads on its own TTL,+// so a phase change is a matter of flipping this and waiting out the cache.+let windowState = 'live';++function configDoc() {+ const now = Date.now();+ const [startsAt, endsAt] = windowState === 'live'+ ? [now - 10 * 60_000, now + 60 * 60_000]+ : [now - 3 * 60 * 60_000, now - 60 * 60_000];+ return {+ id: 'souvenir-e2e',+ name: '$THREE Community Day 2026',+ tagline: 'Conformance run for the souvenir drop.',+ startsAt: new Date(startsAt).toISOString(),+ endsAt: new Date(endsAt).toISOString(),+ link: `/play?coin=${MINT}&name=three.ws&symbol=three`,+ souvenir: { cosmeticId: SOUVENIR_ID },+ agenda: [],+ };+}++function serveConfig() {+ const server = createServer((req, res) => {+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });+ res.end(JSON.stringify(configDoc()));+ });+ return new Promise((r) => server.listen(CONFIG_PORT, '127.0.0.1', () => r(server)));+}++// ── servers ────────────────────────────────────────────────────────────────++const procs = [];+function start(name, cmd, args, { cwd = ROOT, env = {} } = {}) {+ const child = spawn(cmd, args, { cwd, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] });+ procs.push(child);+ for (const stream of [child.stdout, child.stderr]) {+ stream.setEncoding('utf8');+ stream.on('data', (c) => {+ for (const line of c.split('\n')) {+ // Only surface what this run is about; a Colyseus log line per join+ // would bury the checks.+ if (line && /souvenir|event-drop|error|Error|listening|ready in/i.test(line)) {+ console.log(`${at()} [${name}] ${line.trim().slice(0, 200)}`);+ }+ }+ });+ }+ return child;+}++async function waitFor(url, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ try {+ const res = await fetch(url);+ if (res.ok || res.status === 404) return true;+ } catch { /* not up yet */ }+ if (Date.now() > deadline) return false;+ await new Promise((r) => setTimeout(r, 1000));+ }+}++// ── browser helpers ────────────────────────────────────────────────────────++async function until(page, fn, { timeout = 30_000, every = 300, arg } = {}) {+ const deadline = Date.now() + timeout;+ let last;+ for (;;) {+ try { last = await page.evaluate(fn, arg); } catch (err) { last = { evalError: String(err).slice(0, 140) }; }+ if (last === true || last?.ok === true) return last;+ if (Date.now() > deadline) return last;+ await page.waitForTimeout(every);+ }+}++async function dismissOverlays(page, rounds = 6) {+ for (let i = 0; i < rounds; i++) {+ const clicked = await page.evaluate(() => {+ const btn = [...document.querySelectorAll('button')].find(+ (b) => /^(continue|enter the world|got it|start|close|skip|drop in now)$/i.test(b.textContent.trim()) && b.offsetParent,+ );+ if (btn) { btn.click(); return btn.textContent.trim(); }+ return null;+ });+ if (!clicked) break;+ await page.waitForTimeout(500);+ }+}++// A browser context is one player: its own storage means its own guest id, which+// is the identity the souvenir is granted against.+async function openPlayer(browser, tag, storageState) {+ const ctx = await browser.newContext(storageState ? { storageState } : {});+ const page = await ctx.newPage();+ const consoleErrors = [];+ page.on('console', (m) => {+ if (m.type() !== 'error') return;+ const text = m.text();+ // A dev origin logs unrelated noise (source maps, favicon, HMR); only the+ // page's own failures matter here.+ if (/favicon|sourcemap|Failed to load resource/i.test(text)) return;+ consoleErrors.push(text.slice(0, 200));+ });+ page.on('pageerror', (e) => consoleErrors.push(`pageerror: ${String(e.message).slice(0, 200)}`));+ // Record every souvenir announcement this client receives, so "exactly once"+ // is measurable rather than assumed. Installed before any app code runs.+ await page.addInitScript(() => {+ window.__SOUVENIRS__ = [];+ const tick = setInterval(() => {+ const net = window.__CC__?.net;+ if (!net || net.__souvenirTap) return;+ net.__souvenirTap = true;+ try { net.on('souvenir', (m) => window.__SOUVENIRS__.push(m)); } catch { /* older build */ }+ clearInterval(tick);+ }, 200);+ });+ await page.goto(WORLD, { waitUntil: 'domcontentloaded', timeout: LOAD_MS });+ await dismissOverlays(page);+ const joined = await until(page, () => {+ const net = window.__CC__?.net;+ return { ok: net?.status === 'online' && window.__CC__?.phase === 'world', status: net?.status, phase: window.__CC__?.phase };+ }, { timeout: JOIN_MS });+ if (joined?.ok !== true) throw new Error(`[${tag}] never joined the world: ${JSON.stringify(joined)}`);+ console.log(`${at()} [${tag}] in the world`);+ return { tag, ctx, page, consoleErrors };+}++// The client's own view of what it owns and wears, straight off the live scene.+const cosmeticsState = () => {+ const cc = window.__CC__;+ const snap = cc?._cosmeticsSnap?.cosmetics || {};+ return {+ owned: [...(snap.owned || [])],+ equipped: { ...(snap.equipped || {}) },+ wire: cc?.net?.state?.players?.get?.(cc.net.sessionId)?.cosmetics ?? null,+ souvenirs: window.__SOUVENIRS__ || [],+ cardVisible: !!document.querySelector('.es-card'),+ cardName: document.querySelector('.es-card .es-name')?.textContent || '',+ };+};++async function main() {+ const configServer = await serveConfig();+ console.log(`${at()} event config served at http://127.0.0.1:${CONFIG_PORT}/event.json (window: ${windowState})`);++ if (!EXTERNAL) {+ start('vite', 'npx', ['vite', '--port', '3000']);+ // The game server reads the event config from THIS process, not from+ // three.ws, which is what lets the run open and close the window at will.+ start('colyseus', 'node', ['src/index.js'], {+ cwd: resolve(ROOT, 'multiplayer'),+ env: { PORT: '2567', EVENT_CONFIG_URL: `http://127.0.0.1:${CONFIG_PORT}/event.json` },+ });+ if (!await waitFor('http://127.0.0.1:2567/health', 90_000)) throw new Error('colyseus never came up');+ if (!await waitFor(BASE, 120_000)) throw new Error('vite never came up');+ console.log(`${at()} servers up`);+ }++ const browser = await chromium.launch();+ const players = [];+ try {+ // ── Phase 1: window LIVE ───────────────────────────────────────────────+ const alice = await openPlayer(browser, 'alice');+ players.push(alice);++ const granted = await until(alice.page, () => {+ const s = window.__SOUVENIRS__ || [];+ return { ok: s.length > 0, n: s.length };+ }, { timeout: 60_000 });+ check('live window: souvenir announced on join', granted?.ok === true, JSON.stringify(granted));++ const afterGrant = await alice.page.evaluate(cosmeticsState);+ check('live window: announcement names the item', afterGrant.souvenirs[0]?.id === SOUVENIR_ID,+ JSON.stringify(afterGrant.souvenirs[0] || null));+ check('live window: owned exactly once', afterGrant.owned.filter((i) => i === SOUVENIR_ID).length === 1,+ `owned=${JSON.stringify(afterGrant.owned)}`);+ check('live window: drop card is on screen', afterGrant.cardVisible, afterGrant.cardName);++ // Wear it from the card, exactly as a player would.+ await alice.page.click('.es-card .es-btn-primary');+ const worn = await until(alice.page, ([id]) => {+ const eq = window.__CC__?._cosmeticsSnap?.cosmetics?.equipped || {};+ return { ok: eq.headwear === id, equipped: eq };+ }, { timeout: 30_000, arg: [SOUVENIR_ID] });+ check('live window: "Wear it" equips the souvenir', worn?.ok === true, JSON.stringify(worn?.equipped || worn));++ const onWire = await until(alice.page, ([id]) => {+ const cc = window.__CC__;+ const wire = cc?.net?.state?.players?.get?.(cc.net.sessionId)?.cosmetics || '';+ return { ok: wire.split(',').includes(id), wire };+ }, { timeout: 30_000, arg: [SOUVENIR_ID] });+ check('live window: souvenir published on the shared schema', onWire?.ok === true, JSON.stringify(onWire));++ // A peer must actually see it — that is what a souvenir is for.+ const bob = await openPlayer(browser, 'bob');+ players.push(bob);+ // `_cosWire` is the loadout string the peer's RemotePlayer last rendered, so+ // this asserts the souvenir actually reached another client's rig, not just+ // that the schema carried it.+ const peerSees = await until(bob.page, ([id]) => {+ const remotes = [...(window.__CC__?.remotes || new Map())].map(([, r]) => r);+ const wires = remotes.map((r) => String(r._cosWire || ''));+ return { ok: wires.some((w) => w.split(',').includes(id)), n: remotes.length, wires };+ }, { timeout: 60_000, arg: [SOUVENIR_ID] });+ check('live window: another player sees the souvenir worn', peerSees?.ok === true, JSON.stringify(peerSees));++ // The wardrobe is the other half of the moment.+ await alice.page.evaluate(() => window.__CC__._toggleWardrobe());+ const inWardrobe = await until(alice.page, ([id]) => {+ const card = document.querySelector(`.cw-card[data-id="${id}"]`);+ if (!card) return { ok: false, reason: 'no card' };+ return {+ ok: !card.classList.contains('cw-locked'),+ tier: card.getAttribute('data-tier'),+ label: card.querySelector('.cw-price')?.textContent || '',+ equipped: card.classList.contains('cw-equipped'),+ };+ }, { timeout: 30_000, arg: [SOUVENIR_ID] });+ check('live window: wardrobe shows it owned, event-tier and equipped',+ inWardrobe?.ok === true && inWardrobe.tier === 'event' && inWardrobe.equipped === true,+ JSON.stringify(inWardrobe));+ await alice.page.evaluate(() => window.__CC__._wardrobe?.close());++ // ── Phase 2: reconnect as the SAME account ─────────────────────────────+ const aliceState = await alice.ctx.storageState();+ await alice.page.close();+ await alice.ctx.close();+ players.pop();++ const aliceAgain = await openPlayer(browser, 'alice-rejoin', aliceState);+ players.push(aliceAgain);+ // Give the server the same amount of time it took to announce the first+ // time; a duplicate would have landed well inside it.+ await aliceAgain.page.waitForTimeout(15_000);+ const rejoin = await aliceAgain.page.evaluate(cosmeticsState);+ check('rejoin: no second announcement', rejoin.souvenirs.length === 0,+ `announcements=${rejoin.souvenirs.length}`);+ check('rejoin: still owned exactly once', rejoin.owned.filter((i) => i === SOUVENIR_ID).length === 1,+ `owned=${JSON.stringify(rejoin.owned)}`);+ check('rejoin: still worn (persisted across the reconnect)', rejoin.equipped.headwear === SOUVENIR_ID,+ JSON.stringify(rejoin.equipped));+ check('rejoin: no drop card (nothing new happened)', rejoin.cardVisible === false);++ // ── Phase 3: window CLOSED ─────────────────────────────────────────────+ windowState = 'ended';+ console.log(`${at()} event window flipped to ENDED; waiting out the server's config TTL`);+ // The reader caches for 120s; wait past it so the next join reads the+ // closed window rather than the cached live one.+ await new Promise((r) => setTimeout(r, 125_000));++ const carol = await openPlayer(browser, 'carol-after');+ players.push(carol);+ await carol.page.waitForTimeout(15_000);+ const after = await carol.page.evaluate(cosmeticsState);+ check('closed window: a new player is granted nothing', after.souvenirs.length === 0 && !after.owned.includes(SOUVENIR_ID),+ `announcements=${after.souvenirs.length} owned=${JSON.stringify(after.owned)}`);+ check('closed window: no drop card', after.cardVisible === false);++ const aliceStill = await aliceAgain.page.evaluate(cosmeticsState);+ check('closed window: an earlier attendee still owns and wears it',+ aliceStill.owned.includes(SOUVENIR_ID) && aliceStill.equipped.headwear === SOUVENIR_ID,+ JSON.stringify({ owned: aliceStill.owned, equipped: aliceStill.equipped }));++ // Someone who missed it sees the item, learns it was earned live, and is+ // offered no way to buy it.+ await carol.page.evaluate(() => window.__CC__._toggleWardrobe());+ const lockedCard = await until(carol.page, ([id]) => {+ const card = document.querySelector(`.cw-card[data-id="${id}"]`);+ if (!card) return { ok: false, reason: 'no card' };+ return { ok: true, locked: card.classList.contains('cw-locked'), label: card.querySelector('.cw-price')?.textContent || '' };+ }, { timeout: 30_000, arg: [SOUVENIR_ID] });+ check('closed window: wardrobe shows it locked and not for sale',+ lockedCard?.locked === true && /not for sale/i.test(lockedCard.label || ''),+ JSON.stringify(lockedCard));++ // ── console hygiene ────────────────────────────────────────────────────+ for (const p of players) {+ check(`${p.tag}: no console errors`, p.consoleErrors.length === 0, p.consoleErrors.slice(0, 3).join(' | '));+ }+ } finally {+ await browser.close().catch(() => {});+ configServer.close();+ for (const c of procs) { try { c.kill('SIGTERM'); } catch { /* already gone */ } }+ }++ const failed = results.filter((r) => !r.ok);+ console.log(`\n${at()} ${results.length - failed.length}/${results.length} checks passed`);+ if (failed.length) {+ for (const f of failed) console.log(` FAIL ${f.name} — ${f.detail}`);+ process.exit(1);+ }+}++main().catch((err) => {+ console.error(err);+ for (const c of procs) { try { c.kill('SIGTERM'); } catch { /* already gone */ } }+ process.exit(1);+});diff --git a/scripts/verify-event-countdown.mjs b/scripts/verify-event-countdown.mjsindex 87da8d10e..ef108bf15 100644--- a/scripts/verify-event-countdown.mjs+++ b/scripts/verify-event-countdown.mjs@@ -90,17 +90,19 @@ async function newPage({ body, viewport, reducedMotion, storage }) {return { ctx, page, errors };}-// A dev server shared with other work restarts under you; a single navigation is-// not a reliable signal of whether the site is reachable.+// A dev server shared with other work restarts under you, and a Vite config+// reload takes it offline for up to half a minute. A single failed navigation+// says nothing about the feature, so ride the restart out rather than reporting+// someone else's edit as a countdown failure.async function go(page, path) {let last;- for (let attempt = 0; attempt < 4; attempt++) {+ for (let attempt = 0; attempt < 12; attempt++) {try {await page.goto(BASE + path, { waitUntil: 'commit', timeout: PAGE_TIMEOUT });return;} catch (err) {last = err;- await page.waitForTimeout(3000);+ await page.waitForTimeout(10000);}}throw last;diff --git a/src/game/community-net.js b/src/game/community-net.jsindex e7ca07a1f..2c75b97f0 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -111,7 +111,7 @@ export class CommunityNet {xpgain: new Set(), // ({skill, amount, xp, level, levelXp, nextXp})levelup: new Set(), // ({skill, level})notice: new Set(), // ({kind, text, ...}) — activity result toast (fish/eat/tool/full/quest)- souvenir: new Set(), // ({id, name, slot, eventId, eventName}) — a live event just granted this account its free commemorative wearable (once, ever)+ souvenir: new Set(), // ({id, name, slot, eventId, eventName}): a live event just granted this account its free commemorative wearable (once, ever)// General store, bank/ATM & the $THREE boutique (W04).store: new Set(), // ({sell:[{item,label,price}], buy:[{item,qty,price,label}]})boutique: new Set(), // ({listings, owned, configured}) — premium cosmetics priced in $THREEdiff --git a/src/game/event-souvenir.js b/src/game/event-souvenir.jsindex e31679bb9..bff7c2fb1 100644--- a/src/game/event-souvenir.js+++ b/src/game/event-souvenir.js@@ -1,4 +1,4 @@-// Event souvenir drop — the in-world moment when a live event hands you a+// Event souvenir drop: the in-world moment when a live event hands you a// commemorative wearable.//// The server grants the item (multiplayer/src/event-drop.js →@@ -14,7 +14,7 @@// both reach it; nothing traps focus; Escape dismisses.//// Rendering reads the shared catalog, so the card shows the item's real poster-// and name rather than re-describing it — an event that swaps its souvenir needs+// and name rather than re-describing it (an event that swaps its souvenir needs// no change here.import { getCosmetic } from '../../multiplayer/src/cosmetics-catalog.js';@@ -125,8 +125,8 @@ function injectStyles() {export class SouvenirDrop {/*** @param {object} h handlers:- * onEquip(id) — player wants to wear it now (scene sends equip-cosmetic)- * onWardrobe() — player wants to see it in the wardrobe instead+ * onEquip(id) : player wants to wear it now (scene sends equip-cosmetic)+ * onWardrobe() : player wants to see it in the wardrobe instead*/constructor(h = {}) {this.h = h;@@ -143,7 +143,7 @@ export class SouvenirDrop {const id = typeof msg?.id === 'string' ? msg.id : '';const item = getCosmetic(id);// An id this build's catalog doesn't know (a server running ahead of this- // client) is still granted and still persists — it just has no poster to+ // client) is still granted and still persists, it just has no poster to// show, so there is no honest moment to render. Staying silent beats a// card describing an item we cannot name.if (!item) return;@@ -198,7 +198,7 @@ export class SouvenirDrop {}// Retire on a timer, but never out from under someone who is reading or- // tabbing through it — the CSS pauses the hairline, and these listeners pause+ // tabbing through it: the CSS pauses the hairline, and these listeners pause// the real clock with it._arm() {const start = () => {@@ -220,7 +220,7 @@ export class SouvenirDrop {}try { this.h.onEquip?.(item.id); } catch { /* net unavailable; card still retires */ }// Leave the confirmation up briefly so the click reads as accepted, then- // clear the screen — the avatar itself is the real confirmation.+ // clear the screen, the avatar itself is the real confirmation.clearTimeout(this._timer);this._timer = setTimeout(() => this.dismiss(), 900);}diff --git a/src/game/play-onboard.js b/src/game/play-onboard.jsindex 6ec763972..003687d86 100644--- a/src/game/play-onboard.js+++ b/src/game/play-onboard.js@@ -25,7 +25,7 @@ const ONBOARD_KEY = 'cc-onboarded-v1';// `essential` marks the handful a first-timer needs in the 3-step overlay; the// Controls help panel always shows the full reference. Keep both in sync with-// _bindInput() — a control listed here that no longer exists is worse than one+// _bindInput(): a control listed here that no longer exists is worse than one// that is missing, because the player trusts it and it silently does nothing.const DESK_CONTROLS = [@@ -42,7 +42,7 @@ const DESK_CONTROLS = [{ key: 'E', desc: 'Talk to whoever is near: townsfolk, kiosk, agent exchange', essential: true },{ key: 'F', desc: 'Drive a nearby vehicle, work a station, or cast a line', essential: true },{ key: 'X', desc: 'Attack with the equipped weapon' },- { key: '1 – 6', desc: 'Hotbar slot' },+ { key: '1-6', desc: 'Hotbar slot' },{ key: 'I', desc: 'Inspect the nearest avatar' },{ key: 'Click', desc: 'Tap a player, agent, vehicle, or screen to use it' },@@ -54,7 +54,7 @@ const DESK_CONTROLS = [{ group: 'Build' },{ key: 'B', desc: 'Build mode' },- { key: '1 – 0', desc: 'Pick a block (while building)' },+ { key: '1-0', desc: 'Pick a block (while building)' },{ key: 'R', desc: 'Rotate the armed prop or piece' },{ key: 'Right-click', desc: 'Break a block (hold also works)' },{ key: 'Ctrl/⌘ + Z', desc: 'Undo your last build edit' },@@ -195,6 +195,11 @@ export class PlayOnboard {this._keyFn = (e) => {if (!this._overlay) return;if (e.key === 'Escape') { e.preventDefault(); this._dismiss(); }+ // Arrows page the card ONLY while it holds focus. They are also the+ // avatar's movement keys, and this card is deliberately non-blocking+ // ("start walking the moment the world loads"), so swallowing left/right+ // globally made that promise false for anyone not using WASD.+ if (!this._overlay.contains(document.activeElement)) return;if (e.key === 'ArrowRight') { e.preventDefault(); this._stepTo(this._step + 1); }if (e.key === 'ArrowLeft') { e.preventDefault(); this._stepTo(this._step - 1); }};@@ -515,8 +520,14 @@ body.po-onboarding #cc-joystick { z-index: 60; }display: flex; flex-direction: column; gap: 6px;pointer-events: auto;}-/* Hide on narrow screens — the onboarding overlay covers economy info there */-@media (max-width: 640px) { #po-strip { display: none; } }+/* Phones kept the whole strip hidden, which took the Controls button with it:+ once the first-join card was dismissed there was no way back to the control+ reference on the device that needs it most. Keep the button, drop the economy+ label (it is the part that does not fit), and sit clear of the coin banner. */+@media (max-width: 640px) {+ #po-strip { top: 84px; left: 12px; }+ #po-strip .po-econ-row { display: none; }+}.po-econ-row {display: inline-flex; align-items: center; gap: 7px;diff --git a/src/game/war-portal.css b/src/game/war-portal.cssindex d138511f8..2d7476b21 100644--- a/src/game/war-portal.css+++ b/src/game/war-portal.css@@ -1,4 +1,4 @@-/* War Portal (F18) — the in-world Coin Wars panel and its prompt button.+/* War Portal (F18): the in-world Coin Wars panel and its prompt button.** Scoped entirely to .wp-* so it can never reach into the rest of the /play HUD.* Colours come from the world's existing dark UI vocabulary; the only accents arediff --git a/src/game/war-portal.js b/src/game/war-portal.jsindex f513edd11..4417a2a14 100644--- a/src/game/war-portal.js+++ b/src/game/war-portal.js@@ -1,8 +1,8 @@-// War Portal — the Coin Wars door standing in every /play coin world (F18).+// War Portal: the Coin Wars door standing in every /play coin world (F18).//// Coin Wars is a finished game: ClashRoom runs real community-vs-community// battles with a countdown, a round clock, sudden death and an Elo league behind-// it. Until this landed, none of that was reachable from inside a world — a+// it. Until this landed, none of that was reachable from inside a world, a// player standing in their coin's plaza had no way to know wars existed. This is// the door.//@@ -11,13 +11,13 @@// the chart jumbotron) painted with this community's real league standing,// the last battles it fought, and any war running right now. Data comes// from /api/wars, which folds the battle ledger through the SAME Elo math-// the arena uses (multiplayer/src/war-standings.js) — nothing is recomputed+// the arena uses (multiplayer/src/war-standings.js): nothing is recomputed// here.// 2. THE QUEUE. Press E and the portal runs this coin's holder gate (the exact// gate the Holders world runs), queues the community for a battle, and the// moment a second community is waiting hands the player through to the// arena at /play/war with a signed war ticket and a return link that-// carries the full coin identity — so walking back in lands in this same+// carries the full coin identity, so walking back in lands in this same// world, not the lobby.// 3. SPECTATING. While a war involving this coin is live, the board becomes a// scoreboard: score, round clock, kill feed. Text and numbers off a cheap@@ -104,16 +104,6 @@ function label(side) {return side?.symbol ? `$${side.symbol}` : (side?.name || 'Community');}-function roundRect(ctx, x, y, w, h, r) {- ctx.beginPath();- ctx.moveTo(x + r, y);- ctx.arcTo(x + w, y, x + w, y + h, r);- ctx.arcTo(x + w, y + h, x, y + h, r);- ctx.arcTo(x, y + h, x, y, r);- ctx.arcTo(x, y, x + w, y, r);- ctx.closePath();-}-export class WarPortal {/*** @param {object} opts@@ -296,7 +286,7 @@ export class WarPortal {}}- // Public: act if in range. SYNCHRONOUS for the same reason WheelStation's is —+ // Public: act if in range. SYNCHRONOUS for the same reason WheelStation's is:// coincommunities' E-key chain calls each system's interact() looking for the// one that consumed the press, and a Promise is always truthy.interact() {@@ -418,10 +408,10 @@ export class WarPortal {const won = battle.winner === mint;const drew = battle.winner === 'draw';const line = drew- ? `⚔ War drawn with ${label(them)} — ${us.score}:${them.score}`+ ? `⚔ War drawn with ${label(them)}: ${us.score}:${them.score}`: won- ? `⚔ ${label(us)} won the war against ${label(them)} — ${us.score}:${them.score}`- : `⚔ ${label(them)} took the war — ${them.score}:${us.score}`;+ ? `⚔ ${label(us)} won the war against ${label(them)}: ${us.score}:${them.score}`+ : `⚔ ${label(them)} took the war: ${them.score}:${us.score}`;this.ui?.toast?.(line, won ? 'success' : drew ? 'info' : 'warn');if (won) {this._hype = { until: Date.now() + HYPE_MS, battle, us, them };@@ -445,7 +435,7 @@ export class WarPortal {if (this._hype) this._paintHype(ctx);else if (this._loading && !this._board) this._paintCentred(ctx, 'READING THE LEAGUE', 'Standings load as you walk up.');- else if (this._boardError && !this._board) this._paintCentred(ctx, 'LEAGUE UNREACHABLE', this._boardError + ' — press E to retry.');+ else if (this._boardError && !this._board) this._paintCentred(ctx, 'LEAGUE UNREACHABLE', this._boardError + ', press E to retry.');else {const live = this._liveHere();if (live) this._paintLive(ctx, live);@@ -500,7 +490,7 @@ export class WarPortal {ctx.fillText('WAR WON', CW / 2, 130);ctx.fillStyle = COL.text;ctx.font = '800 30px Inter, system-ui, sans-serif';- ctx.fillText(`${label(us)} ${us.score} — ${them.score} ${label(them)}`, CW / 2, 196);+ ctx.fillText(`${label(us)} ${us.score} - ${them.score} ${label(them)}`, CW / 2, 196);ctx.fillStyle = COL.dim;ctx.font = '600 18px Inter, system-ui, sans-serif';ctx.fillText(reasonLine(battle.reason), CW / 2, 236);@@ -588,7 +578,7 @@ export class WarPortal {}// The resting board: where this community sits in the league, and the last- // battles it fought. Both have designed empty states — an unranked community+ // battles it fought. Both have designed empty states: an unranked community// is told exactly what to do about it._paintStandings(ctx) {const standing = this._board?.standing || null;@@ -654,7 +644,7 @@ export class WarPortal {ctx,waiting.length? `${waiting.length} ${waiting.length === 1 ? 'community is' : 'communities are'} queued right now. Press E to take the fight.`- : 'No wars fought yet. Press E to queue this community — the arena opens as soon as a second one does.',+ : 'No wars fought yet. Press E to queue this community, the arena opens as soon as a second one does.',26, 214, CW - 52, 24,);} else {@@ -670,7 +660,7 @@ export class WarPortal {ctx.fillText(drew ? 'DRAW' : won ? 'WIN' : 'LOSS', 26, y);ctx.fillStyle = COL.text;ctx.font = '600 15px Inter, system-ui, sans-serif';- ctx.fillText(`${us.score}–${them.score} vs ${clipText(label(them), 18)}`, 92, y);+ ctx.fillText(`${us.score}-${them.score} vs ${clipText(label(them), 18)}`, 92, y);ctx.fillStyle = COL.faint;ctx.textAlign = 'right';ctx.fillText(relTime(b.endedAt), CW - 26, y);@@ -682,7 +672,7 @@ export class WarPortal {ctx.fillStyle = COL.faint;ctx.font = '600 15px Inter, system-ui, sans-serif';ctx.textAlign = 'center';- ctx.fillText('Press E — enter the war', CW / 2, CH - 24);+ ctx.fillText('Press E: enter the war', CW / 2, CH - 24);ctx.textAlign = 'left';}@@ -763,7 +753,7 @@ export class WarPortal {if (d) {parts.push(d.standing ? standingCard(d.standing) : emptyCard('Unranked',- 'This community has not fought a war yet. The first battle puts it on the ladder — win or lose.',+ 'This community has not fought a war yet. The first battle puts it on the ladder, win or lose.',));}@@ -806,7 +796,7 @@ export class WarPortal {if (this._queue?.status === 'waiting') {cta.textContent = 'Waiting for an opponent…';cta.disabled = true;- note.textContent = 'Stay here — the arena opens the moment another community queues.';+ note.textContent = 'Stay here, the arena opens the moment another community queues.';return;}cta.disabled = false;@@ -824,7 +814,7 @@ export class WarPortal {const them = m.a?.mint === mint ? m.b : m.a;const remaining = m.phase === 'countdown' ? (m.countdownEndsAt || 0) - Date.now() : (m.endsAt || 0) - Date.now();const status = m.phase === 'countdown' ? `Starts in ${clock(remaining)}`- : m.phase === 'sudden_death' ? 'Sudden death — the next kill takes it'+ : m.phase === 'sudden_death' ? 'Sudden death: the next kill takes it': m.phase === 'ended' ? 'Battle over': `${clock(remaining)} left · first to ${m.scoreCap || 25}`;const kills = (m.kills || []).slice(-6).reverse();@@ -854,7 +844,7 @@ export class WarPortal {el('span', { class: 'wp-row-vs', text: `${clipText(k.killer, 18)} → ${clipText(k.victim, 18)}` }),el('span', { class: 'wp-row-when', text: relTime(k.ts) }),])))- : el('p', { class: 'wp-empty-b', text: 'No knockdowns yet — the first one lands here.' }),+ : el('p', { class: 'wp-empty-b', text: 'No knockdowns yet, the first one lands here.' }),]);}@@ -867,14 +857,14 @@ export class WarPortal {this._renderCta();try {// The same gate the Holders world runs. A community whose world is open- // still gates the war on holding the coin — you cannot wear a+ // still gates the war on holding the coin: you cannot wear a// community's colours without holding its coin, which is the rule// ClashRoom.onAuth enforces server-side too.const pass = await this.ensureHolderPass?.();if (!pass || !pass.holderPass) {// Two clean refusals, neither an error. A null means the player// backed out of the gate; the string 'general' means they chose the- // open world from inside it, which for a war means declining — you+ // open world from inside it, which for a war means declining, you// cannot wear a community's colours without holding its coin, and// ClashRoom.onAuth enforces exactly that server-side.this._busy = false;@@ -951,7 +941,7 @@ export class WarPortal {// Hand the player to the arena. The return link carries the FULL coin identity// plus the match key, so coming back lands in this exact world with the result- // already in hand — no lobby detour, no re-picking a community.+ // already in hand, no lobby detour, no re-picking a community._handoff(match) {const q = new URLSearchParams({match: match.matchKey,@@ -965,7 +955,7 @@ export class WarPortal {if (this.coin.symbol) q.set('symbol', this.coin.symbol);if (this.coin.image) q.set('image', this.coin.image);if (this._holderPass) q.set('holderPass', this._holderPass);- this.ui?.toast?.(`⚔ Matched against ${label(match.opponent)} — entering the arena`, 'success');+ this.ui?.toast?.(`⚔ Matched against ${label(match.opponent)}: entering the arena`, 'success');location.href = `/play/war?${q}`;}@@ -1068,7 +1058,7 @@ function recentCard(recent, mint) {const won = b.winner === mint;return el('li', { class: `wp-row wp-row-${drew ? 'draw' : won ? 'win' : 'loss'}` }, [el('span', { class: 'wp-row-tag', text: drew ? 'DRAW' : won ? 'WIN' : 'LOSS' }),- el('span', { class: 'wp-row-score', text: `${us.score}–${them.score}` }),+ el('span', { class: 'wp-row-score', text: `${us.score}-${them.score}` }),el('span', { class: 'wp-row-vs', text: label(them) }),el('span', { class: 'wp-row-when', text: relTime(b.endedAt) }),]);@@ -1094,7 +1084,7 @@ function ladderCard(standings, mint) {// ── formatting helpers ───────────────────────────────────────────────────────function streakLabel(streak) {- if (!streak) return '—';+ if (!streak) return '-';return streak > 0 ? `${streak}W` : `${-streak}L`;}@@ -1113,7 +1103,7 @@ function clipText(s, max) {return t.length > max ? `${t.slice(0, max - 1)}…` : t;}-// Shrink a label until it fits the canvas column rather than bleeding off it —+// Shrink a label until it fits the canvas column rather than bleeding off it,// a pump.fun name can be far longer than the space a scoreboard gives it.function clip(ctx, text, maxW) {let t = String(text ?? '');diff --git a/src/physics/physics-world.js b/src/physics/physics-world.jsindex a01342185..310bb048c 100644--- a/src/physics/physics-world.js+++ b/src/physics/physics-world.js@@ -21,7 +21,7 @@// one. The `-compat` build base64s a ~1.6 MB WASM binary into its JavaScript,// which Rollup then folds into whatever chunk statically imports it: a static// import here put 2.27 MB of parsed JS (774 KB over the wire) on the critical-// path of every page that draws a physics scene — /play and /walk both+// path of every page that draws a physics scene: /play and /walk both// modulepreloaded it before the first frame, and the browser paid a multi-second// parse for a module nothing needs until the world is already standing. Loading// it from inside initRapier() gives it its own async chunk that downloadsdiff --git a/src/play/war-world.js b/src/play/war-world.jsindex ba712e980..18b970822 100644--- a/src/play/war-world.js+++ b/src/play/war-world.js@@ -1,8 +1,8 @@-// war-world.js — the 3D arena a Coin Wars battle is fought in.+// war-world.js: the 3D arena a Coin Wars battle is fought in.//// ClashRoom (multiplayer/src/rooms/ClashRoom.js) is fully authoritative: it owns// positions, targeting, damage, respawns, the round clock and the score. This-// module is the eyes and hands for that room and nothing more — it renders the+// module is the eyes and hands for that room and nothing more: it renders the// arena and every fighter in it, walks the local fighter around (sending intent,// never claiming an outcome), and plays the feedback the server broadcasts.//diff --git a/src/play/war.css b/src/play/war.cssnew file mode 100644index 000000000..9a3f7e242--- /dev/null+++ b/src/play/war.css@@ -0,0 +1,382 @@+/* Coin Wars arena (/play/war) — the battle HUD over the 3D field.+ *+ * A fighting HUD has one job: never get between the player and the fight. So it+ * lives at the screen edges, uses opaque-enough panels to stay readable over a+ * bright floodlit floor, and every control is thumb-reachable on a phone with the+ * canvas still fully visible between them.+ *+ * The two sides of a war are colour-coded (us / them) but never colour-ONLY:+ * every score carries its community's name beside it. */++:root {+ --war-bg: #05060a;+ --war-panel: rgba(12, 14, 20, 0.78);+ --war-line: rgba(255, 255, 255, 0.1);+ --war-ink: #e9edf6;+ --war-muted: #8b93a7;+ --war-us: #7fd8ff;+ --war-them: #ff9d7a;+ --war-win: #5fd08a;+ --war-loss: #e06c75;+ --war-draw: #c9a227;+ --war-blur: saturate(150%) blur(14px);+ --war-mono: ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, monospace;+}++* { box-sizing: border-box; }++html, body {+ margin: 0;+ height: 100%;+ overflow: hidden;+ background: var(--war-bg);+ color: var(--war-ink);+ font: 14px/1.5 Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;+ -webkit-font-smoothing: antialiased;+ overscroll-behavior: none;+}++button { font: inherit; color: inherit; cursor: pointer; }++#scene {+ position: fixed;+ inset: 0;+ width: 100%;+ height: 100%;+ display: block;+ touch-action: none;+ z-index: 0;+}++.war-vignette {+ position: fixed;+ inset: 0;+ z-index: 1;+ pointer-events: none;+ background: radial-gradient(130% 100% at 50% 20%, transparent 55%, rgba(0, 0, 0, 0.6) 100%);+}++#labels { position: fixed; inset: 0; z-index: 4; pointer-events: none; }++.war-tag {+ position: absolute;+ top: 0;+ left: 0;+ padding: 2px 8px;+ border: 1px solid var(--war-line);+ border-radius: 999px;+ background: var(--war-panel);+ backdrop-filter: var(--war-blur);+ -webkit-backdrop-filter: var(--war-blur);+ font: 600 11px/1.5 Inter, system-ui, sans-serif;+ white-space: nowrap;+ will-change: transform;+ transition: opacity 0.2s ease;+}++.war-tag-a { border-color: color-mix(in srgb, var(--war-us) 45%, var(--war-line)); color: var(--war-us); }+.war-tag-b { border-color: color-mix(in srgb, var(--war-them) 45%, var(--war-line)); color: var(--war-them); }+.war-tag-me { box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.18); }++/* ── status ──────────────────────────────────────────────────────────────── */++.war-status {+ position: fixed;+ inset: auto 0 auto 0;+ top: 50%;+ z-index: 6;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 10px;+ color: var(--war-muted);+ font-size: 14px;+ pointer-events: none;+}++.war-spinner {+ width: 14px;+ height: 14px;+ border: 2px solid rgba(255, 255, 255, 0.16);+ border-top-color: var(--war-us);+ border-radius: 50%;+ animation: war-spin 0.9s linear infinite;+}++@keyframes war-spin { to { transform: rotate(360deg); } }++@media (prefers-reduced-motion: reduce) {+ .war-spinner { animation-duration: 3s; }+}++/* ── scoreboard ──────────────────────────────────────────────────────────── */++.war-hud {+ position: fixed;+ top: max(10px, env(safe-area-inset-top));+ left: 50%;+ transform: translateX(-50%);+ z-index: 5;+ display: grid;+ grid-template-columns: 1fr auto 1fr;+ align-items: center;+ gap: 14px;+ width: min(620px, calc(100vw - 20px));+ padding: 10px 14px;+ border: 1px solid var(--war-line);+ border-radius: 14px;+ background: var(--war-panel);+ backdrop-filter: var(--war-blur);+ -webkit-backdrop-filter: var(--war-blur);+ box-shadow: 0 18px 50px -20px rgba(0, 0, 0, 0.85);+}++.war-side { display: flex; align-items: center; gap: 10px; min-width: 0; }+.war-side-them { flex-direction: row-reverse; text-align: right; }++.war-score { font: 900 30px/1 var(--war-mono); }+.war-side-us .war-score { color: var(--war-us); }+.war-side-them .war-score { color: var(--war-them); }++.war-side-meta { display: flex; flex-direction: column; min-width: 0; }++.war-side-name {+ font-weight: 700;+ font-size: 13px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.war-side-roster { color: var(--war-muted); font-size: 11px; }++.war-mid { display: flex; flex-direction: column; align-items: center; gap: 1px; }+.war-clock { font: 800 20px/1 var(--war-mono); }+.war-cap { color: var(--war-muted); font-size: 11px; }++.war-coin {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ margin-top: 3px;+ color: var(--war-muted);+ font-size: 11px;+}++.war-coin-img { width: 14px; height: 14px; border-radius: 50%; object-fit: cover; }++/* ── phase banner ────────────────────────────────────────────────────────── */++.war-phase {+ position: fixed;+ top: 34%;+ left: 0;+ right: 0;+ z-index: 5;+ margin: 0;+ text-align: center;+ font: 900 clamp(28px, 7vw, 56px)/1 Inter, system-ui, sans-serif;+ letter-spacing: 0.02em;+ text-shadow: 0 4px 30px rgba(0, 0, 0, 0.8);+ pointer-events: none;+ animation: war-pop 0.35s cubic-bezier(0.2, 0.9, 0.3, 1);+}++.war-phase[data-phase="live"] { color: var(--war-win); }+.war-phase[data-phase="sudden_death"] { color: var(--war-them); font-size: clamp(20px, 4.5vw, 34px); }+.war-phase[data-phase="countdown"] { color: var(--war-ink); }+.war-phase[data-phase="lobby"] { color: var(--war-muted); font-size: clamp(18px, 4vw, 30px); }++@keyframes war-pop {+ from { opacity: 0; transform: scale(0.9); }+ to { opacity: 1; transform: scale(1); }+}++@media (prefers-reduced-motion: reduce) {+ .war-phase { animation: none; }+}++.war-lobby-note {+ position: fixed;+ top: 46%;+ left: 50%;+ transform: translateX(-50%);+ z-index: 5;+ max-width: min(420px, calc(100vw - 32px));+ margin: 0;+ text-align: center;+ color: var(--war-muted);+ font-size: 13px;+ pointer-events: none;+}++/* ── controls ────────────────────────────────────────────────────────────── */++.war-controls {+ position: fixed;+ inset: auto 0 0 0;+ z-index: 5;+ display: flex;+ align-items: flex-end;+ justify-content: space-between;+ padding: 0 max(14px, env(safe-area-inset-left)) max(16px, env(safe-area-inset-bottom)) max(14px, env(safe-area-inset-right));+ pointer-events: none;+}++.war-controls > * { pointer-events: auto; }++.war-stick {+ position: relative;+ width: 116px;+ height: 116px;+ border: 1px solid var(--war-line);+ border-radius: 50%;+ background: rgba(12, 14, 20, 0.5);+ backdrop-filter: var(--war-blur);+ -webkit-backdrop-filter: var(--war-blur);+ touch-action: none;+}++.war-stick-nub {+ position: absolute;+ top: 50%;+ left: 50%;+ width: 46px;+ height: 46px;+ margin: -23px 0 0 -23px;+ border-radius: 50%;+ background: rgba(255, 255, 255, 0.16);+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2);+}++.war-right { display: flex; flex-direction: column; align-items: flex-end; gap: 10px; }++.war-vitals {+ display: flex;+ gap: 14px;+ margin: 0;+ padding: 6px 12px;+ border: 1px solid var(--war-line);+ border-radius: 10px;+ background: var(--war-panel);+ backdrop-filter: var(--war-blur);+ -webkit-backdrop-filter: var(--war-blur);+}++.war-vitals div { display: flex; flex-direction: column; align-items: center; }+.war-vitals dt { color: var(--war-muted); font: 700 9px/1 Inter, system-ui, sans-serif; letter-spacing: 0.08em; text-transform: uppercase; }+.war-vitals dd { margin: 3px 0 0; font: 800 16px/1 var(--war-mono); }++.war-attack {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 2px;+ width: 108px;+ padding: 14px 0;+ border: 1px solid color-mix(in srgb, var(--war-us) 50%, var(--war-line));+ border-radius: 14px;+ background: linear-gradient(180deg, rgba(127, 216, 255, 0.26), rgba(127, 216, 255, 0.1));+ color: #eaf7ff;+ font: 800 16px/1 Inter, system-ui, sans-serif;+ transition: transform 90ms ease, opacity 140ms ease, background 140ms ease;+}++.war-attack small { color: var(--war-muted); font: 600 10px/1 Inter, system-ui, sans-serif; }+.war-attack:hover:not(:disabled) { background: linear-gradient(180deg, rgba(127, 216, 255, 0.36), rgba(127, 216, 255, 0.15)); }+.war-attack:active:not(:disabled) { transform: scale(0.95); }+.war-attack:focus-visible { outline: 2px solid var(--war-us); outline-offset: 3px; }+.war-attack:disabled { opacity: 0.4; cursor: default; }+.war-attack.is-cooling { opacity: 0.55; }++.war-leave {+ padding: 7px 14px;+ border: 1px solid var(--war-line);+ border-radius: 10px;+ background: rgba(12, 14, 20, 0.6);+ color: var(--war-muted);+ font: 600 12px/1 Inter, system-ui, sans-serif;+ transition: color 120ms ease, border-color 120ms ease;+}++.war-leave:hover { color: var(--war-ink); border-color: rgba(255, 255, 255, 0.24); }+.war-leave:focus-visible { outline: 2px solid var(--war-us); outline-offset: 2px; }++.war-downed {+ position: fixed;+ left: 50%;+ bottom: max(160px, calc(env(safe-area-inset-bottom) + 160px));+ transform: translateX(-50%);+ margin: 0;+ padding: 7px 14px;+ border: 1px solid color-mix(in srgb, var(--war-loss) 45%, var(--war-line));+ border-radius: 999px;+ background: var(--war-panel);+ color: var(--war-loss);+ font: 700 12px/1 Inter, system-ui, sans-serif;+ pointer-events: none;+}++/* ── terminal cards ──────────────────────────────────────────────────────── */++.war-modal {+ position: fixed;+ inset: 0;+ z-index: 7;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 20px;+ background: rgba(4, 5, 8, 0.72);+ backdrop-filter: blur(3px);+}++.war-modal-card {+ width: min(420px, 100%);+ padding: 26px 24px;+ border: 1px solid var(--war-line);+ border-radius: 18px;+ background: linear-gradient(180deg, #14161e, #0a0b10);+ box-shadow: 0 28px 70px -22px rgba(0, 0, 0, 0.9);+ text-align: center;+}++.war-result-title,+.war-fail-title {+ margin: 0 0 6px;+ font: 900 32px/1.1 Inter, system-ui, sans-serif;+}++.war-result-title[data-outcome="win"] { color: var(--war-win); }+.war-result-title[data-outcome="loss"] { color: var(--war-loss); }+.war-result-title[data-outcome="draw"] { color: var(--war-draw); }++.war-result-score { margin: 0 0 12px; font: 800 26px/1 var(--war-mono); }+.war-modal-b { margin: 0 0 8px; color: var(--war-muted); font-size: 13px; }+.war-modal-faint { color: rgba(255, 255, 255, 0.4); }++.war-modal-btn {+ width: 100%;+ margin-top: 14px;+ padding: 12px 16px;+ border: 1px solid color-mix(in srgb, var(--war-us) 50%, var(--war-line));+ border-radius: 12px;+ background: linear-gradient(180deg, rgba(127, 216, 255, 0.24), rgba(127, 216, 255, 0.1));+ color: #eaf7ff;+ font: 700 15px/1 Inter, system-ui, sans-serif;+ transition: background 140ms ease, transform 90ms ease;+}++.war-modal-btn:hover { background: linear-gradient(180deg, rgba(127, 216, 255, 0.34), rgba(127, 216, 255, 0.15)); }+.war-modal-btn:active { transform: scale(0.985); }+.war-modal-btn:focus-visible { outline: 2px solid var(--war-us); outline-offset: 3px; }++/* ── small screens ───────────────────────────────────────────────────────── */++@media (max-width: 520px) {+ .war-hud { gap: 8px; padding: 8px 10px; }+ .war-score { font-size: 24px; }+ .war-side-name { font-size: 12px; }+ .war-stick { width: 100px; height: 100px; }+ .war-attack { width: 92px; padding: 12px 0; }+}diff --git a/src/play/war.js b/src/play/war.jsindex 39abb3f63..9f29c3598 100644--- a/src/play/war.js+++ b/src/play/war.js@@ -1,4 +1,4 @@-// war.js — the Coin Wars arena page (/play/war).+// war.js: the Coin Wars arena page (/play/war).//// A player presses "Enter the war" at the portal in their coin's world; the// matchmaker pairs their community with another and hands both sides the same@@ -156,7 +156,7 @@ let attackCooldownUntil = 0;sendTimer = setInterval(sendPose, 1000 / SEND_HZ);// The round clock is derived from `endsAt`, which only changes when the match- // starts — so it has to be ticked locally or it would freeze between the+ // starts, so it has to be ticked locally or it would freeze between the// state patches that carry a score change.clockTimer = setInterval(tickClock, 500);addEventListener('beforeunload', () => { try { room?.leave(); } catch { /* closing anyway */ } });@@ -232,7 +232,7 @@ function onPhase(next, s) {lobby: 'Waiting for the other community',countdown: 'Get ready',live: 'Fight',- sudden_death: 'Sudden death — next kill takes it',+ sudden_death: 'Sudden death: next kill takes it',ended: 'Battle over',}[next] || next;banner.textContent = text;@@ -241,7 +241,7 @@ function onPhase(next, s) {if (next === 'live') setTimeout(() => { if (phase === 'live') banner.hidden = true; }, 1800);if (next === 'lobby') {$('lobby-note').hidden = false;- $('lobby-note').textContent = `Holding the line for ${factionLabel(s, cfg.side)} — the battle starts when ${factionLabel(s, cfg.side === 'a' ? 'b' : 'a')} fields a fighter.`;+ $('lobby-note').textContent = `Holding the line for ${factionLabel(s, cfg.side)}: the battle starts when ${factionLabel(s, cfg.side === 'a' ? 'b' : 'a')} fields a fighter.`;} else {$('lobby-note').hidden = true;}@@ -294,7 +294,7 @@ function tickClock() {const s = room?.state;if (!s) return;if (s.phase === 'sudden_death') { $('clock').textContent = 'OT'; return; }- if (s.phase === 'lobby') { $('clock').textContent = '—'; return; }+ if (s.phase === 'lobby') { $('clock').textContent = '-'; return; }const target = s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt;$('clock').textContent = clock(target - Date.now());}@@ -355,10 +355,10 @@ function showResult(m) {$('result-title').textContent = drew ? 'Draw' : won ? 'Victory' : 'Defeat';$('result-title').dataset.outcome = drew ? 'draw' : won ? 'win' : 'loss';- $('result-score').textContent = `${mine} — ${theirs}`;+ $('result-score').textContent = `${mine} - ${theirs}`;$('result-reason').textContent = reasonLine(m.reason);$('result-mvp').textContent = m.mvp- ? `MVP: ${m.mvp.kills} kills, ${m.mvp.deaths} deaths, ${m.mvp.damage} damage${m.mvp.id === localId ? ' — that was you' : ''}`+ ? `MVP: ${m.mvp.kills} kills, ${m.mvp.deaths} deaths, ${m.mvp.damage} damage${m.mvp.id === localId ? ', that was you' : ''}`: 'No knockdowns were scored.';$('result').hidden = false;$('controls').hidden = true;@@ -392,7 +392,7 @@ function wireChrome() {});mountJoystick();// The coin the player fights for, painted into the page chrome the moment it- // loads — before any room state arrives — so the page is never anonymous.+ // loads, before any room state arrives, so the page is never anonymous.$('coin-label').textContent = coinLabel();if (cfg.image) {const img = $('coin-img');@@ -402,7 +402,7 @@ function wireChrome() {}}-// A thumb stick for phones. Pointer events only — no library, no dependency, and+// A thumb stick for phones. Pointer events only: no library, no dependency, and// it releases cleanly if the finger leaves the screen mid-drag.function mountJoystick() {const pad = $('stick');@@ -460,7 +460,7 @@ function fail(title, detail, action = 'Back to the world') {// The room throws named errors; each one has a player-readable cause.function joinErrorText(err) {const msg = String(err?.message || '');- if (msg.includes('war_ticket')) return 'This pairing has expired. Walk back to the war portal and queue again — it only takes a moment.';+ if (msg.includes('war_ticket')) return 'This pairing has expired. Walk back to the war portal and queue again, it only takes a moment.';if (msg.includes('holder_pass_mismatch')) return 'Your holding was verified for a different coin than the one this battle seats you under.';if (msg.includes('holder_pass_required')) return 'The arena needs a fresh proof that you hold this coin. Queue again from the portal.';if (msg.includes('play_pass')) return 'This deployment gates play on a token balance and yours did not clear it.';diff --git a/src/shared/game-server-url.js b/src/shared/game-server-url.jsindex 8c9268c41..cd16103db 100644--- a/src/shared/game-server-url.js+++ b/src/shared/game-server-url.js@@ -1,8 +1,8 @@// Where the Colyseus game server lives, as seen from a browser.//-// Every realtime surface on the site has to answer this identically — /play+// Every realtime surface on the site has to answer this identically: /play// (community-net.js), the Coin Wars arena (src/play/war.js), and anything that-// joins a room next — because the resolution order is full of environment+// joins a room next, because the resolution order is full of environment// specifics that are easy to get subtly wrong: a Codespace forwards each port as// its own subdomain, a local dev server must ignore the production <meta> baked// into the static page, and production with nothing configured must return ''@@ -12,8 +12,8 @@/*** Resolve the websocket origin for the game server, in priority order:- * 1. `window.GAME_SERVER_URL` — a runtime override (ops, embeds)- * 2. localhost — always the local server, never the baked meta+ * 1. `window.GAME_SERVER_URL` : a runtime override (ops, embeds)+ * 2. localhost : always the local server, never the baked meta* 3. `<meta name="game-server">` / `<meta name="walk-server">`* 4. `VITE_GAME_SERVER_URL` / `VITE_WALK_SERVER_URL`* 5. the Codespaces/Gitpod port-forward subdomain, then same-host:2567 in devdiff --git a/tests/event-souvenir.test.js b/tests/event-souvenir.test.jsindex 9e8d2c471..2000d4296 100644--- a/tests/event-souvenir.test.js+++ b/tests/event-souvenir.test.js@@ -1,4 +1,4 @@-// Coverage for the event souvenir drop — the free commemorative wearable every+// Coverage for the event souvenir drop: the free commemorative wearable every// attendee of a live /play event keeps forever.//// The whole feature rests on two properties that are easy to state and easy to@@ -10,7 +10,7 @@// the one thing a souvenir is: proof you were there.// 2. GRANT IDEMPOTENCY (multiplayer/src/economy.js). A player reconnects,// hops rooms, or refreshes ten times during the event and ends up with-// exactly one copy — and, just as importantly, the souvenir SURVIVES a+// exactly one copy, and, just as importantly, the souvenir SURVIVES a// persistence round-trip, because after the window closes there is no path// that could ever re-grant it.//@@ -149,7 +149,7 @@ describe('granting the souvenir', () => {const restored = restoreProfile(JSON.parse(JSON.stringify(serializeProfile(profile))), 'wallet-under-test');expect(restored.cosmetics.owned).toContain(SOUVENIR_ID);expect(restored.cosmetics.equipped.headwear).toBe(SOUVENIR_ID);- // And still wearable after the window has long closed — the item is owned,+ // And still wearable after the window has long closed: the item is owned,// and ownership is not time-scoped.expect(canWear(SOUVENIR_ID, ownedCosmeticSet(restored))).toBe(true);});diff --git a/tests/meetup-event-ui.test.js b/tests/meetup-event-ui.test.jsnew file mode 100644index 000000000..cce9a6ae3--- /dev/null+++ b/tests/meetup-event-ui.test.js@@ -0,0 +1,297 @@+// @vitest-environment jsdom+//+// Meetup event layer DOM contract — what /play actually paints during a live+// community event. The schedule math is covered in meetup-schedule.test.js;+// these tests lock the view: when the chip mounts (and when it must NOT), the+// agenda drawer's active/done marking, the one-shot go-live moment (including+// the join-mid-event case that must never replay it), the fireworks handoff,+// and full teardown.+//+// The frame loop is driven by hand: requestAnimationFrame is stubbed to a no-op+// so nothing runs behind the test's back, and each test steps `_loop` itself.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { MeetupEvent } from '../src/game/meetup-event.js';+import { parseEvent, PRESHOW_MS, SOON_MS } from '../src/game/meetup-schedule.js';++// Mirrors MAX_LIVE_BURSTS in src/game/meetup-event.js: the ceiling a single+// frame may ever launch, which is what the backlog clamp has to respect.+const MAX_LIVE_BURSTS = 14;++const HOME = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const OTHER = 'THREEsynthetic1111111111111111111111111111111';+const START = Date.parse('2026-08-07T17:00:00Z');++const EVENT = parseEvent({+ id: 'three-first-meetup',+ name: '$THREE First Holders Meetup',+ tagline: 'The first live gathering',+ startsAt: '2026-08-07T17:00:00Z',+ endsAt: '2026-08-07T19:00:00Z',+ agenda: [+ { atMin: 0, title: 'Doors open', detail: 'Say hi', icon: '👋' },+ { atMin: 20, title: 'Totem showdown', detail: 'Hold the ring', icon: '👑' },+ { atMin: 105, title: 'Fireworks finale', detail: 'Look up', icon: '🎆' },+ ],+});++// A Fireworks stand-in: records launches without touching WebGL.+class FakeFireworks {+ constructor({ scene }) { this.scene = scene; this.launches = []; this.ticks = 0; this.disposed = false; }+ launch(x, z, opts) { this.launches.push({ x, z, ...opts }); return true; }+ get liveCount() { return this.launches.length; }+ tick() { this.ticks++; }+ dispose() { this.disposed = true; }+}++function fakeCc({ mint = HOME, phase = 'world' } = {}) {+ return {+ phase,+ coin: { mint },+ scene: { name: 'scene' },+ ui: { toast: vi.fn() },+ env: { flashRing: vi.fn() },+ _openBuy: vi.fn(),+ };+}++let raf;+function mount(cc = fakeCc(), event = EVENT) {+ return new MeetupEvent({ event, cc, Fireworks: FakeFireworks });+}++// Step the hand-driven loop. `at` is wall-clock ms; frame timestamps only need+// to advance monotonically for dt.+let frameT = 0;+function step(m, at, frames = 1) {+ vi.setSystemTime(at);+ for (let i = 0; i < frames; i++) { frameT += 600; m._loop(frameT); }+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(START - 60_000);+ frameT = 0;+ raf = vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(0);+ vi.spyOn(window, 'cancelAnimationFrame').mockReturnValue(undefined);+ document.body.className = '';+ document.body.innerHTML = '';+});++afterEach(() => {+ raf.mockRestore();+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe('mounting rules', () => {+ it('mounts the chip in the home town during the pre-show', () => {+ const m = mount();+ step(m, START - PRESHOW_MS + 1000);+ const chip = document.getElementById('cc-meetup-chip');+ expect(chip).toBeTruthy();+ expect(chip.textContent).toContain('Starts in');+ expect(document.body.classList.contains('cc-meetup-ui')).toBe(true);+ m.destroy();+ });++ it('never mounts in another coin world', () => {+ const m = mount(fakeCc({ mint: OTHER }));+ step(m, START + 60_000);+ expect(document.getElementById('cc-meetup-chip')).toBeNull();+ m.destroy();+ });++ it('never mounts from the lobby', () => {+ const m = mount(fakeCc({ phase: 'lobby' }));+ step(m, START + 60_000);+ expect(document.getElementById('cc-meetup-chip')).toBeNull();+ m.destroy();+ });++ it('stays hidden while the event is more than a day out', () => {+ const m = mount();+ step(m, START - SOON_MS - 60_000);+ expect(document.getElementById('cc-meetup-chip')).toBeNull();+ m.destroy();+ });++ it('unmounts when the player leaves the world', () => {+ const cc = fakeCc();+ const m = mount(cc);+ step(m, START + 60_000);+ expect(document.getElementById('cc-meetup-chip')).toBeTruthy();+ cc.phase = 'lobby';+ step(m, START + 61_000);+ expect(document.getElementById('cc-meetup-chip')).toBeNull();+ expect(document.body.classList.contains('cc-meetup-ui')).toBe(false);+ m.destroy();+ });++ it('tears itself down once the event is fully over', () => {+ const m = mount();+ step(m, START + 60_000);+ expect(document.getElementById('cc-meetup-chip')).toBeTruthy();+ step(m, EVENT.endsAt + 60 * 60 * 1000);+ expect(document.getElementById('cc-meetup-chip')).toBeNull();+ m.destroy();+ });+});++describe('the live chip', () => {+ it('marks itself live and names the next segment', () => {+ const m = mount();+ step(m, START + 60_000);+ const chip = document.getElementById('cc-meetup-chip');+ expect(chip.classList.contains('cc-meetup-islive')).toBe(true);+ expect(chip.querySelector('.cc-meetup-live-dot')).toBeTruthy();+ expect(chip.textContent).toContain('LIVE');+ expect(chip.textContent).toContain('next');+ m.destroy();+ });++ it('invites a photo during the afterglow', () => {+ const m = mount();+ step(m, EVENT.endsAt + 60_000);+ expect(document.getElementById('cc-meetup-chip').textContent).toContain('photo');+ m.destroy();+ });+});++describe('the agenda drawer', () => {+ it('opens from the chip and renders every segment', () => {+ const m = mount();+ step(m, START + 60_000);+ document.getElementById('cc-meetup-chip').click();+ const panel = document.getElementById('cc-meetup-panel');+ expect(panel.classList.contains('cc-meetup-panel--open')).toBe(true);+ expect(panel.querySelectorAll('.cc-meetup-seg')).toHaveLength(3);+ expect(document.getElementById('cc-meetup-chip').getAttribute('aria-expanded')).toBe('true');+ m.destroy();+ });++ it('marks the running segment active and past ones done', () => {+ const m = mount();+ step(m, START + 25 * 60_000); // inside the 20-minute segment+ document.getElementById('cc-meetup-chip').click();+ const segs = [...document.querySelectorAll('.cc-meetup-seg')];+ expect(segs[0].classList.contains('cc-meetup-seg--done')).toBe(true);+ expect(segs[1].classList.contains('cc-meetup-seg--active')).toBe(true);+ expect(segs[2].classList.contains('cc-meetup-seg--active')).toBe(false);+ m.destroy();+ });++ it('closes on Escape', () => {+ const m = mount();+ step(m, START + 60_000);+ document.getElementById('cc-meetup-chip').click();+ window.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape' }));+ expect(document.getElementById('cc-meetup-panel').classList.contains('cc-meetup-panel--open')).toBe(false);+ m.destroy();+ });++ it('routes Buy $THREE into the app trade widget', () => {+ const cc = fakeCc();+ const m = mount(cc);+ step(m, START + 60_000);+ document.getElementById('cc-meetup-chip').click();+ document.querySelector('.cc-meetup-buy-btn').click();+ expect(cc._openBuy).toHaveBeenCalled();+ m.destroy();+ });+});++describe('moments', () => {+ it('fires the go-live banner when the event starts under the player', () => {+ const cc = fakeCc();+ const m = mount(cc);+ step(m, START - 10_000); // pre-show: seeds the phase+ expect(document.getElementById('cc-meetup-banner')).toBeNull();+ step(m, START + 1000); // crosses into live+ const banner = document.getElementById('cc-meetup-banner');+ expect(banner).toBeTruthy();+ expect(banner.textContent).toContain(EVENT.title);+ expect(banner.classList.contains('cc-meetup-banner--show')).toBe(true);+ expect(cc.env.flashRing).toHaveBeenCalled();+ m.destroy();+ });++ it('never replays the go-live moment for someone joining mid-event', () => {+ const m = mount();+ step(m, START + 30 * 60_000, 3);+ expect(document.getElementById('cc-meetup-banner')).toBeNull();+ m.destroy();+ });++ it('announces each new agenda segment exactly once', () => {+ const m = mount();+ step(m, START + 60_000); // segment 1 (seeded, no banner)+ expect(document.getElementById('cc-meetup-banner')).toBeNull();+ step(m, START + 21 * 60_000); // segment 2 starts+ const banner = document.getElementById('cc-meetup-banner');+ expect(banner.textContent).toContain('Totem showdown');+ banner.classList.remove('cc-meetup-banner--show');+ step(m, START + 22 * 60_000); // still segment 2: no repeat+ expect(banner.classList.contains('cc-meetup-banner--show')).toBe(false);+ m.destroy();+ });+});++describe('fireworks', () => {+ it('launches a synchronized show while live and disposes it on teardown', () => {+ const m = mount();+ step(m, START + 60_000);+ step(m, START + 64_000);+ step(m, START + 68_000);+ expect(m.fireworks).toBeTruthy();+ expect(m.fireworks.launches.length).toBeGreaterThan(0);+ const fw = m.fireworks;+ m.destroy();+ expect(fw.disposed).toBe(true);+ });++ it('keeps every burst inside the plaza ring', () => {+ const m = mount();+ step(m, START + 1000);+ for (let t = 4000; t < 120_000; t += 4000) step(m, START + t);+ expect(m.fireworks.launches.length).toBeGreaterThan(0);+ for (const l of m.fireworks.launches) {+ expect(Math.hypot(l.x, l.z)).toBeLessThanOrEqual(38);+ }+ m.destroy();+ });++ it('stays quiet before the event starts', () => {+ const m = mount();+ step(m, START - 20 * 60_000, 4);+ expect(m.fireworks).toBeNull();+ m.destroy();+ });++ // requestAnimationFrame is paused while a tab is hidden. Without a clamp, the+ // first frame back would detonate every bucket missed while away.+ it('does not replay a backlog after the tab was hidden', () => {+ const m = mount();+ step(m, START + 60_000); // first live frame only anchors the show clock+ step(m, START + 68_000); // ...the next one actually launches+ const beforeGap = m.fireworks.launches.length;+ step(m, START + 68_000 + 10 * 60_000); // ten minutes of missed frames+ const burst = m.fireworks.launches.length - beforeGap;+ expect(burst).toBeLessThanOrEqual(MAX_LIVE_BURSTS);+ m.destroy();+ });+});++describe('teardown', () => {+ it('leaves no DOM, class, or listener behind', () => {+ const m = mount();+ step(m, START + 60_000);+ document.getElementById('cc-meetup-chip').click();+ m.destroy();+ expect(document.getElementById('cc-meetup-chip')).toBeNull();+ expect(document.getElementById('cc-meetup-panel')).toBeNull();+ expect(document.body.classList.contains('cc-meetup-ui')).toBe(false);+ // A stray Escape after teardown must not throw.+ expect(() => window.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape' }))).not.toThrow();+ });+});diff --git a/tests/play-a11y.test.js b/tests/play-a11y.test.jsnew file mode 100644index 000000000..72753690f--- /dev/null+++ b/tests/play-a11y.test.js@@ -0,0 +1,304 @@+// @vitest-environment jsdom+//+// The /play accessibility contract (audit 09).+//+// These pin the four behaviours that made the world reachable but not operable+// for a keyboard or screen-reader player, each of which regressed silently+// before because nothing asserted it:+//+// 1. The shared modal contract (src/game/a11y.js): Escape closes the TOP+// panel only, Tab stays inside an open dialog, focus moves in on open and+// returns to the opener on close.+// 2. The live announcer: a message with the same text twice still re-reads,+// because a screen reader only speaks a live region when its text changes.+// 3. `isActivationTarget`, the guard that stops the world's global Enter/Space+// bindings ("open chat", "jump") from swallowing the browser's activation+// gesture for whatever HUD control has focus.+// 4. Play copy actually goes through the i18n layer: every `play.*` key the+// HUD references exists in the source catalog, and `t()` falls back to the+// English source instead of printing a raw key when it does not.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { join, dirname } from 'node:path';++import {+ openModal, registerOverlay, trapFocus, focusableIn, announce, hasOpenOverlay,+} from '../src/game/a11y.js';+import { t } from '../src/game/i18n-play.js';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++// jsdom gives every element a zero-size box, which the module's own visibility+// filter would (correctly, in a browser) treat as hidden. Stub a real box so+// the focus helpers see the controls under test.+function withLayout() {+ const spy = vi+ .spyOn(window.HTMLElement.prototype, 'getBoundingClientRect')+ .mockReturnValue({ width: 100, height: 24, top: 0, left: 0, right: 100, bottom: 24, x: 0, y: 0, toJSON() {} });+ return () => spy.mockRestore();+}++// requestAnimationFrame drives the deferred initial focus in trapFocus.+const nextFrame = () => new Promise((r) => requestAnimationFrame(() => r()));++function dialog(id, buttons = ['one', 'two']) {+ const card = document.createElement('div');+ card.id = id;+ card.setAttribute('role', 'dialog');+ card.setAttribute('aria-modal', 'true');+ for (const label of buttons) {+ const b = document.createElement('button');+ b.type = 'button';+ b.textContent = label;+ card.appendChild(b);+ }+ document.body.appendChild(card);+ return card;+}++const esc = (opts = {}) =>+ document.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true, ...opts }));++describe('play a11y: modal contract', () => {+ let restore;+ beforeEach(() => { document.body.innerHTML = ''; restore = withLayout(); });+ afterEach(() => { restore(); });++ it('Escape closes the top panel only, then the one beneath it', () => {+ const first = dialog('first');+ const second = dialog('second');+ const closed = [];+ const relA = registerOverlay(first, () => { closed.push('first'); relA(); });+ const relB = registerOverlay(second, () => { closed.push('second'); relB(); });++ expect(hasOpenOverlay()).toBe(true);+ esc();+ expect(closed).toEqual(['second']);+ esc();+ expect(closed).toEqual(['second', 'first']);+ expect(hasOpenOverlay()).toBe(false);+ // Nothing open: Escape is the world's again.+ esc();+ expect(closed).toEqual(['second', 'first']);+ });++ it('does not let the world hotkey handler see a panel Escape', () => {+ const card = dialog('trapped');+ const worldSaw = vi.fn();+ window.addEventListener('keydown', worldSaw);+ const release = registerOverlay(card, () => {});+ esc();+ expect(worldSaw).not.toHaveBeenCalled();+ release();+ window.removeEventListener('keydown', worldSaw);+ });++ it('moves focus into the dialog and back to the opener on close', async () => {+ const opener = document.createElement('button');+ opener.type = 'button';+ document.body.appendChild(opener);+ opener.focus();+ expect(document.activeElement).toBe(opener);++ const card = dialog('focus-me');+ const release = openModal(card, { close: () => {} });+ await nextFrame();+ expect(card.contains(document.activeElement)).toBe(true);++ release();+ expect(document.activeElement).toBe(opener);+ });++ it('honours an explicit initialFocus', async () => {+ const card = dialog('initial', ['first', 'close']);+ const closeBtn = card.lastElementChild;+ const release = openModal(card, { close: () => {}, initialFocus: closeBtn });+ await nextFrame();+ expect(document.activeElement).toBe(closeBtn);+ release();+ });++ it('cycles Tab inside the dialog instead of escaping to the page behind it', async () => {+ const outside = document.createElement('button');+ outside.type = 'button';+ document.body.appendChild(outside);++ const card = dialog('cycle', ['a', 'b', 'c']);+ const release = trapFocus(card);+ await nextFrame();++ const items = focusableIn(card);+ expect(items).toHaveLength(3);++ // Forward past the last control wraps to the first.+ items[2].focus();+ const fwd = new window.KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true });+ card.dispatchEvent(fwd);+ expect(fwd.defaultPrevented).toBe(true);+ expect(document.activeElement).toBe(items[0]);++ // Backward past the first wraps to the last.+ const back = new window.KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, bubbles: true, cancelable: true });+ card.dispatchEvent(back);+ expect(back.defaultPrevented).toBe(true);+ expect(document.activeElement).toBe(items[2]);++ release();+ });++ it('leaves focus alone when the player already moved it elsewhere', async () => {+ const opener = document.createElement('button');+ const elsewhere = document.createElement('button');+ document.body.append(opener, elsewhere);+ opener.focus();++ const card = dialog('no-steal');+ const release = openModal(card, { close: () => {} });+ await nextFrame();+ elsewhere.focus();+ release();+ expect(document.activeElement).toBe(elsewhere);+ });++ it('releases are idempotent, so a double close cannot unstack a sibling panel', () => {+ const a = dialog('a');+ const b = dialog('b');+ const closed = [];+ const relA = openModal(a, { close: () => closed.push('a') });+ const relB = openModal(b, { close: () => closed.push('b') });+ relB();+ relB();+ relB();+ esc();+ expect(closed).toEqual(['a']);+ relA();+ });+});++describe('play a11y: live announcer', () => {+ beforeEach(() => { document.body.innerHTML = ''; document.head.innerHTML = ''; });++ it('creates one polite and one assertive region, lazily', () => {+ expect(document.querySelectorAll('.cc-sr-live')).toHaveLength(0);+ announce('Cash on hand 120.');+ const regions = [...document.querySelectorAll('.cc-sr-live')];+ expect(regions).toHaveLength(2);+ expect(regions.map((r) => r.getAttribute('aria-live')).sort()).toEqual(['assertive', 'polite']);+ const polite = regions.find((r) => r.getAttribute('aria-live') === 'polite');+ expect(polite.textContent).toContain('Cash on hand 120.');+ });++ it('re-reads an identical message by changing the text node', () => {+ announce('Spent 30.');+ const polite = document.querySelector('[aria-live="polite"]');+ const first = polite.textContent;+ announce('Spent 30.');+ expect(polite.textContent).not.toBe(first);+ expect(polite.textContent).toContain('Spent 30.');+ });++ it('routes assertive messages to the alert region, not the polite one', () => {+ announce('Removed from the world.', { assertive: true });+ expect(document.querySelector('[aria-live="assertive"]').textContent).toContain('Removed from the world.');+ expect(document.querySelector('[aria-live="polite"]').textContent).toBe('');+ });++ it('ignores empty messages rather than blanking a region mid-read', () => {+ announce('Jobs Board');+ const polite = document.querySelector('[aria-live="polite"]');+ const before = polite.textContent;+ announce('');+ announce(null);+ expect(polite.textContent).toBe(before);+ });+});++// The world binds Enter and Space globally (open chat / jump). Those are also+// the browser's activation gesture, so the handler has to stand down whenever a+// control has focus. This is the exact predicate coincommunities.js uses; it+// lives there rather than in a11y.js, so assert it against the same source.+describe('play a11y: hotkeys never swallow a focused control', () => {+ const src = readFileSync(join(ROOT, 'src', 'game', 'coincommunities.js'), 'utf8');++ it('defines an activation-target guard covering buttons, links and ARIA widgets', () => {+ const sel = src.match(/const ACTIVATION_TARGET = '([^']+)'/)?.[1];+ expect(sel, 'coincommunities.js must define ACTIVATION_TARGET').toBeTruthy();+ for (const part of ['button', 'a[href]', '[role="button"]', '[role="tab"]', '[role="menuitem"]']) {+ expect(sel).toContain(part);+ }+ });++ it('matches a focused HUD button but not the world canvas', () => {+ const sel = src.match(/const ACTIVATION_TARGET = '([^']+)'/)[1];+ document.body.innerHTML = `+ <canvas id="kx-canvas" tabindex="0" role="application"></canvas>+ <div id="cc-hud"><button class="cc-shop-btn"><span class="cc-shop-btn-ico">S</span><span>Shop</span></button></div>`;+ const icon = document.querySelector('.cc-shop-btn-ico');+ const canvas = document.getElementById('kx-canvas');+ // A click/keypress lands on the icon span inside the button, so the guard+ // has to walk up, not just test the target itself.+ expect(icon.closest(sel)).toBe(document.querySelector('.cc-shop-btn'));+ expect(canvas.closest(sel)).toBe(null);+ });++ it('gates both activation keys and the overlay check on that guard', () => {+ expect(src).toContain('const onControl = isActivationTarget(e.target);');+ expect(src).toMatch(/e\.key === 'Enter' && this\.phase === 'world' && !onControl/);+ expect(src).toMatch(/e\.code === 'Space' && !onControl/);+ // A modal panel owns the keyboard while it is open.+ expect(src).toContain('if (hasOpenOverlay()) return;');+ });+});++describe('play a11y: HUD copy goes through the i18n layer', () => {+ const catalog = JSON.parse(readFileSync(join(ROOT, 'public', 'locales', 'en.json'), 'utf8'));+ const sources = [+ 'src/game/coincommunities-ui.js',+ 'src/game/economy-ui.js',+ 'src/game/quests-ui.js',+ 'src/game/spin-wheel-ui.js',+ 'src/game/cosmetics-shop.js',+ 'src/game/cosmetics-wardrobe.js',+ 'pages/play.html',+ ].map((rel) => readFileSync(join(ROOT, rel), 'utf8')).join('\n');++ it('every play.* key the world references exists in the source catalog', () => {+ const referenced = new Set([...sources.matchAll(/\bplay\.[a-z0-9_]+/g)].map((m) => m[0]));+ expect(referenced.size).toBeGreaterThan(40);+ const missing = [...referenced].filter((key) => catalog.play?.[key.slice('play.'.length)] === undefined);+ expect(missing, `keys used by /play but absent from public/locales/en.json: ${missing.join(', ')}`).toEqual([]);+ });++ it('annotates the HUD, not just the page metadata', () => {+ const hud = readFileSync(join(ROOT, 'src', 'game', 'coincommunities-ui.js'), 'utf8');+ // Before this audit the whole in-world HUD was hardcoded English and the+ // only annotated strings on /play were the <meta> tags.+ expect((hud.match(/data-i18n/g) || []).length).toBeGreaterThan(20);+ });++ it('the world canvas carries a translatable text alternative', () => {+ const html = readFileSync(join(ROOT, 'pages', 'play.html'), 'utf8');+ const canvas = html.match(/<canvas[^>]*id="kx-canvas"[\s\S]*?>/)[0];+ expect(canvas).toContain('role="application"');+ expect(canvas).toContain('tabindex="0"');+ expect(canvas).toContain('aria-label=');+ expect(canvas).toContain('aria-label:play.canvas_label');+ expect(catalog.play.canvas_label).toMatch(/W A S D/);+ });++ it('t() falls back to the English source rather than printing a raw key', () => {+ delete globalThis.threewsI18n;+ expect(t('play.nope_not_a_key', 'Free spin')).toBe('Free spin');+ expect(t('play.online', '{{n}} online', { n: 7 })).toBe('7 online');+ });++ it('t() prefers the runtime catalog once /i18n.js has loaded', () => {+ globalThis.threewsI18n = { t: (key, vars) => (key === 'play.online' ? `${vars.n} en ligne` : key) };+ expect(t('play.online', '{{n}} online', { n: 7 })).toBe('7 en ligne');+ // A key the catalog does not carry echoes back, and must not reach the UI.+ expect(t('play.unknown', 'Shop')).toBe('Shop');+ delete globalThis.threewsI18n;+ });+});diff --git a/tests/play-account-identity.test.js b/tests/play-account-identity.test.jsnew file mode 100644index 000000000..227d0cc7c--- /dev/null+++ b/tests/play-account-identity.test.js@@ -0,0 +1,144 @@+// The /play account identity contract: which credential is allowed to claim a+// saved profile (gold, bank, pack, unlocked cosmetics, quest log).+//+// Before this, `playerId` fell back to a raw `pid` join option, so any client+// could join as `pid=<victim's wallet or guest id>`, land in that profile, spend+// it, and persist its own mutations back over it. guest-token.js existed with+// exactly the right fix in its header and had zero callers. These tests lock the+// wiring in place: a bare pid is never an account key again, and the signed+// token is the only thing that carries a guest's progression forward.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { WalkRoom } from '../multiplayer/src/rooms/WalkRoom.js';+import { newGuestId, signGuestToken, verifyGuestToken } from '../multiplayer/src/guest-token.js';+import { playerStore, savePlayer, loadPlayer } from '../multiplayer/src/playerStore.js';++// A WalkRoom instance without the Colyseus constructor: _resolveIdentity only+// touches the player store and the token helpers.+function makeRoom() {+ return Object.create(WalkRoom.prototype);+}++function client(userData = null) {+ return { sessionId: 'sess-' + Math.random().toString(36).slice(2, 8), userData };+}++describe('guest-token', () => {+ it('round-trips a server-minted guest id', () => {+ const gid = newGuestId();+ expect(gid.startsWith('gs_')).toBe(true);+ expect(verifyGuestToken(signGuestToken(gid))).toBe(gid);+ });++ it('refuses a tampered payload, a tampered signature, and junk', () => {+ const token = signGuestToken(newGuestId());+ const [body, sig] = token.split('.');+ const otherBody = Buffer.from(JSON.stringify({ k: 'guest', gid: 'gs_victim', iat: 1, exp: 4102444800 }))+ .toString('base64').replace(/=+$/, '');+ expect(verifyGuestToken(`${otherBody}.${sig}`)).toBe(null);+ expect(verifyGuestToken(`${body}.${'A'.repeat(sig.length)}`)).toBe(null);+ expect(verifyGuestToken('not-a-token')).toBe(null);+ expect(verifyGuestToken('')).toBe(null);+ expect(verifyGuestToken(null)).toBe(null);+ });++ it('refuses an expired token', () => {+ const past = Math.floor(Date.now() / 1000) - 10;+ const body = Buffer.from(JSON.stringify({ k: 'guest', gid: 'gs_x', iat: past - 100, exp: past }))+ .toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');+ // Sign it the same way the module does so only expiry can reject it.+ const signed = signGuestToken('gs_x');+ expect(verifyGuestToken(signed)).toBe('gs_x'); // control: a fresh one passes+ expect(verifyGuestToken(`${body}.${signed.split('.')[1]}`)).toBe(null);+ });++ it('never accepts a wallet-shaped id as a guest id', () => {+ // A wallet address sealed as a guest id would let the guest lane claim a+ // wallet account's profile. The prefix check is what prevents it.+ const walletish = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+ const body = Buffer.from(JSON.stringify({+ k: 'guest', gid: walletish, iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 60,+ })).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');+ expect(verifyGuestToken(`${body}.${signGuestToken('gs_a').split('.')[1]}`)).toBe(null);+ });+});++describe('WalkRoom._resolveIdentity — who may claim a saved profile', () => {+ let room;+ beforeEach(() => {+ room = makeRoom();+ playerStore._mem.clear();+ });++ it('THE EXPLOIT: a bare pid naming a victim can no longer claim their profile', async () => {+ // The victim has played before and their guest id has been upgraded to the+ // signed-token flow (as every active guest's is on their next join).+ const victim = 'guest-victimaccount';+ savePlayer(victim, { gold: 999999, guestUpgraded: true });++ const id = await room._resolveIdentity(client(), { pid: victim });++ expect(id.playerId).not.toBe(victim);+ expect(id.playerId.startsWith('gs_')).toBe(true); // a fresh guest instead+ expect(loadPlayer(victim).gold).toBe(999999); // untouched+ });++ it('a bare pid naming a WALLET is never honored, upgraded or not', async () => {+ const wallet = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+ savePlayer(wallet, { gold: 500 });+ const id = await room._resolveIdentity(client(), { pid: wallet });+ expect(id.playerId).not.toBe(wallet);+ expect(id.playerId.startsWith('gs_')).toBe(true);+ });++ it('binds the wallet onAuth verified, above every client-supplied option', async () => {+ const authed = 'AuthedWallet1111111111111111111111111111111';+ const id = await room._resolveIdentity(+ client({ account: authed }),+ { pid: 'guest-someone-else', guestToken: signGuestToken(newGuestId()) },+ );+ expect(id.playerId).toBe(authed);+ expect(id.guestToken).toBe('');+ });++ it('honors a guest id ONLY when it arrives inside a valid signed token', async () => {+ const gid = newGuestId();+ savePlayer(gid, { gold: 42 });++ const withToken = await room._resolveIdentity(client(), { guestToken: signGuestToken(gid) });+ expect(withToken.playerId).toBe(gid);+ expect(verifyGuestToken(withToken.guestToken)).toBe(gid); // re-issued, so it never lapses++ // The same id asserted bare gets a brand-new guest, not that profile.+ const bare = await room._resolveIdentity(client(), { pid: gid });+ expect(bare.playerId).not.toBe(gid);+ });++ it('migrates a legacy guest-… pid exactly once, then locks it to the token', async () => {+ const legacy = 'guest-abc123def';+ savePlayer(legacy, { gold: 77 });++ // First contact: the device still holds only the old localStorage id, so it+ // keeps its progression and receives a signed token to use from now on.+ const first = await room._resolveIdentity(client(), { pid: legacy });+ expect(first.playerId).toBe(legacy);+ expect(verifyGuestToken(first.guestToken)).toBe(legacy);+ expect(loadPlayer(legacy).guestUpgraded).toBe(true);++ // Anyone asserting the same id bare afterwards is a stranger.+ const second = await room._resolveIdentity(client(), { pid: legacy });+ expect(second.playerId).not.toBe(legacy);++ // The device that holds the token keeps its profile.+ const holder = await room._resolveIdentity(client(), { guestToken: first.guestToken });+ expect(holder.playerId).toBe(legacy);+ });++ it('mints a fresh guest for a first-time visitor with no credential at all', async () => {+ const a = await room._resolveIdentity(client(), {});+ const b = await room._resolveIdentity(client(), {});+ expect(a.playerId.startsWith('gs_')).toBe(true);+ expect(a.playerId).not.toBe(b.playerId); // unguessable, never shared+ expect(verifyGuestToken(a.guestToken)).toBe(a.playerId);+ });+});diff --git a/tests/play-deeplink-safety.test.js b/tests/play-deeplink-safety.test.jsindex 80b233f42..cf89792d8 100644Binary files a/tests/play-deeplink-safety.test.js and b/tests/play-deeplink-safety.test.js differdiff --git a/tests/sniper-solvency.test.js b/tests/sniper-solvency.test.jsindex 3842ec8e6..a4c3cf61f 100644--- a/tests/sniper-solvency.test.js+++ b/tests/sniper-solvency.test.js@@ -36,7 +36,7 @@ describe('walletTradeState', () => {});it('reports starved for the exact balance that produced the live outage', () => {- // 0.0048 SOL — above the entry headroom, below the operational floor, so+ // 0.0048 SOL, above the entry headroom, below the operational floor, so// every attempt died at a simulation the wallet could not afford to run.expect(walletTradeState(0.0048, 0.05)).toBe('starved');});@@ -76,7 +76,7 @@ describe('summarizeFleetSolvency', () => {expect(s.deficitSol).toBe(0);});- it('is starved when no wallet can place any entry — the live outage shape', () => {+ it('is starved when no wallet can place any entry, the live outage shape', () => {const s = summarizeFleetSolvency({wallets: [wallet(0.0048, 0.05, 'a'), wallet(0.0002, 0.05, 'b')],masterSol: 0.0018,diff --git a/tests/static-batch.test.js b/tests/static-batch.test.jsindex f7ca3ba2d..bafd242a4 100644--- a/tests/static-batch.test.js+++ b/tests/static-batch.test.js@@ -1,5 +1,5 @@/**- * Static geometry batcher — unit tests.+ * Static geometry batcher: unit tests.** The batcher is what keeps the /play world dressing (hundreds of trees, boxes* and posts cut from a handful of shared buffers) down to a handful of drawdiff --git a/tests/war-matchmaking.test.js b/tests/war-matchmaking.test.jsnew file mode 100644index 000000000..6457deb86--- /dev/null+++ b/tests/war-matchmaking.test.js@@ -0,0 +1,197 @@+// Unit tests for Coin Wars matchmaking: the pure pairing math that decides which+// two communities meet in one arena (multiplayer/src/war-matchmaking.js), and the+// signed ticket that stops a fighter from inventing the opponent+// (api/_lib/war-ticket.js signs, multiplayer/src/war-ticket.js verifies).+//+// Both are dependency-free, so they run without Redis, a Colyseus room, or a+// browser — the same isolation clash.js and war-standings.js already rely on.++import { describe, it, expect } from 'vitest';+import {+ joinQueue, leaveQueue, waitingCommunities, mintMatchKey, parseMatchKey,+ matchKeyNames, sideOf, entryLive, orderMints, QUEUE_TTL_MS, PAIR_TTL_MS,+} from '../multiplayer/src/war-matchmaking.js';+import { signWarTicket } from '../api/_lib/war-ticket.js';+import { verifyWarTicket } from '../multiplayer/src/war-ticket.js';++// Two synthetic mints of a realistic length. ALPHA sorts below BRAVO, so ALPHA is+// always faction A — that ordering is the whole point of the key format.+const ALPHA = 'ALPHAsynthetic11111111111111111111111111111';+const BRAVO = 'BRAVOsynthetic11111111111111111111111111111';+const CHARLIE = 'CHARLIEsynthetic111111111111111111111111111';++const coin = (mint, symbol) => ({ mint, name: `${symbol} Community`, symbol, image: '' });+const T0 = 1_770_000_000_000;++describe('matchKey format', () => {+ it('is identical whichever community mints it', () => {+ const one = mintMatchKey({ mintA: ALPHA, mintB: BRAVO, slot: T0 });+ const two = mintMatchKey({ mintA: BRAVO, mintB: ALPHA, slot: T0 });+ expect(one).toBe(two);+ });++ it('names its two communities and nobody else', () => {+ const key = mintMatchKey({ mintA: ALPHA, mintB: BRAVO, slot: T0 });+ expect(matchKeyNames(key, ALPHA, BRAVO)).toBe(true);+ expect(matchKeyNames(key, BRAVO, ALPHA)).toBe(true);+ expect(matchKeyNames(key, ALPHA, CHARLIE)).toBe(false);+ });++ it('puts the lower mint on side a', () => {+ const key = mintMatchKey({ mintA: BRAVO, mintB: ALPHA, slot: T0 });+ expect(orderMints(BRAVO, ALPHA)).toEqual([ALPHA, BRAVO]);+ expect(sideOf(key, ALPHA)).toBe('a');+ expect(sideOf(key, BRAVO)).toBe('b');+ expect(sideOf(key, CHARLIE)).toBe(null);+ });++ it('gives a rematch its own key so a finished room never absorbs it', () => {+ const first = mintMatchKey({ mintA: ALPHA, mintB: BRAVO, slot: T0 });+ const second = mintMatchKey({ mintA: ALPHA, mintB: BRAVO, slot: T0 + 60_000 });+ expect(second).not.toBe(first);+ });++ it('refuses a community fighting itself, or a mint that is not one', () => {+ expect(mintMatchKey({ mintA: ALPHA, mintB: ALPHA, slot: T0 })).toBe(null);+ expect(mintMatchKey({ mintA: 'short', mintB: BRAVO, slot: T0 })).toBe(null);+ });++ it('rejects a hand-crafted key', () => {+ expect(parseMatchKey('w1:mainnet:' + ALPHA + ':' + BRAVO)).toBe(null); // too few parts+ expect(parseMatchKey('w9:mainnet:' + ALPHA + ':' + BRAVO + ':abc')).toBe(null); // wrong version+ expect(parseMatchKey('w1:mainnet:' + BRAVO + ':' + ALPHA + ':abc')).toBe(null); // unordered mints+ expect(parseMatchKey(42)).toBe(null);+ });+});++describe('joinQueue', () => {+ it('parks the first community and pairs the second', () => {+ const first = joinQueue({ queue: [], coin: coin(ALPHA, 'ALPHA'), now: T0 });+ expect(first.status).toBe('waiting');+ expect(first.matchKey).toBe(null);+ expect(first.waiting).toBe(1);++ const second = joinQueue({ queue: first.queue, coin: coin(BRAVO, 'BRAVO'), now: T0 + 1000 });+ expect(second.status).toBe('matched');+ expect(second.matchKey).toBeTruthy();+ expect(second.opponent.mint).toBe(ALPHA);+ expect(second.side).toBe('b');+ });++ it('hands the first community the same key when it polls back', () => {+ const first = joinQueue({ queue: [], coin: coin(ALPHA, 'ALPHA'), now: T0 });+ const second = joinQueue({ queue: first.queue, coin: coin(BRAVO, 'BRAVO'), now: T0 + 1000 });+ const poll = joinQueue({ queue: second.queue, coin: coin(ALPHA, 'ALPHA'), now: T0 + 2000 });++ expect(poll.status).toBe('paired');+ expect(poll.matchKey).toBe(second.matchKey);+ expect(poll.side).toBe('a');+ expect(poll.opponent.mint).toBe(BRAVO);+ });++ it('never pairs a community with itself', () => {+ const first = joinQueue({ queue: [], coin: coin(ALPHA, 'ALPHA'), now: T0 });+ const again = joinQueue({ queue: first.queue, coin: coin(ALPHA, 'ALPHA'), now: T0 + 5000 });+ expect(again.status).toBe('waiting');+ expect(again.queue).toHaveLength(1);+ });++ it('pairs the community that has waited longest', () => {+ // Two unpaired entries at once is a real state: concurrent writers on+ // different worlds can both take a place in line before either pairs.+ const queue = [+ { ...coin(CHARLIE, 'CHAR'), network: 'mainnet', at: T0 + 5000, matchKey: null, opponent: null },+ { ...coin(ALPHA, 'ALPHA'), network: 'mainnet', at: T0, matchKey: null, opponent: null },+ ];+ const matched = joinQueue({ queue, coin: coin(BRAVO, 'BRAVO'), now: T0 + 9000 });+ expect(matched.status).toBe('matched');+ expect(matched.opponent.mint).toBe(ALPHA);+ // CHARLIE is untouched and still looking for a fight.+ expect(waitingCommunities({ queue: matched.queue, now: T0 + 9001 }).map((c) => c.mint)).toEqual([CHARLIE]);+ });++ it('ignores a community that walked away', () => {+ const stale = joinQueue({ queue: [], coin: coin(ALPHA, 'ALPHA'), now: T0 });+ const later = joinQueue({ queue: stale.queue, coin: coin(BRAVO, 'BRAVO'), now: T0 + QUEUE_TTL_MS + 1 });+ expect(later.status).toBe('waiting');+ expect(later.queue.map((e) => e.mint)).toEqual([BRAVO]);+ });++ it('keeps a pairing claimable for longer than a bare wait', () => {+ const paired = { mint: ALPHA, at: T0, matchKey: 'w1:mainnet:x:y:z' };+ const waiting = { mint: BRAVO, at: T0 };+ expect(entryLive(waiting, T0 + QUEUE_TTL_MS + 1)).toBe(false);+ expect(entryLive(paired, T0 + QUEUE_TTL_MS + 1)).toBe(true);+ expect(entryLive(paired, T0 + PAIR_TTL_MS + 1)).toBe(false);+ });++ it('refuses a mint that is not one', () => {+ const res = joinQueue({ queue: [], coin: { mint: 'nope' }, now: T0 });+ expect(res.status).toBe('invalid');+ });++ it('keeps networks apart', () => {+ const main = joinQueue({ queue: [], coin: coin(ALPHA, 'ALPHA'), network: 'mainnet', now: T0 });+ const dev = joinQueue({ queue: main.queue, coin: coin(BRAVO, 'BRAVO'), network: 'devnet', now: T0 + 1000 });+ expect(dev.status).toBe('waiting');+ });+});++describe('leaveQueue / waitingCommunities', () => {+ it('drops the leaver and prunes the stale in one pass', () => {+ const queue = [+ { ...coin(ALPHA, 'ALPHA'), network: 'mainnet', at: T0, matchKey: null, opponent: null },+ { ...coin(CHARLIE, 'CHAR'), network: 'mainnet', at: T0 - QUEUE_TTL_MS - 1, matchKey: null, opponent: null },+ ];+ // ALPHA walks away; CHARLIE's entry was already dead and goes with it.+ expect(leaveQueue({ queue, mint: ALPHA, now: T0 + 10 })).toEqual([]);+ });++ it('lists only communities still looking for an opponent', () => {+ const first = joinQueue({ queue: [], coin: coin(ALPHA, 'ALPHA'), now: T0 });+ expect(waitingCommunities({ queue: first.queue, now: T0 + 10 })).toHaveLength(1);+ const second = joinQueue({ queue: first.queue, coin: coin(BRAVO, 'BRAVO'), now: T0 + 1000 });+ // Both are now paired, so neither is still waiting for someone.+ expect(waitingCommunities({ queue: second.queue, now: T0 + 1010 })).toHaveLength(0);+ });+});++describe('war ticket', () => {+ const key = mintMatchKey({ mintA: ALPHA, mintB: BRAVO, slot: T0 });++ it('round-trips a pairing in canonical order', () => {+ // Signed from BRAVO's side; the ticket still lists ALPHA as faction A,+ // because that is what the key encodes and what the arena scoreboard reads.+ const token = signWarTicket({ matchKey: key, coinA: coin(BRAVO, 'BRAVO'), coinB: coin(ALPHA, 'ALPHA') });+ const payload = verifyWarTicket(token);+ expect(payload).toBeTruthy();+ expect(payload.a.mint).toBe(ALPHA);+ expect(payload.b.mint).toBe(BRAVO);+ expect(payload.matchKey).toBe(key);+ });++ it('rejects a tampered signature', () => {+ const token = signWarTicket({ matchKey: key, coinA: coin(ALPHA, 'ALPHA'), coinB: coin(BRAVO, 'BRAVO') });+ expect(verifyWarTicket(token.slice(0, -2) + 'xx')).toBe(null);+ });++ it('rejects a tampered payload', () => {+ const token = signWarTicket({ matchKey: key, coinA: coin(ALPHA, 'ALPHA'), coinB: coin(BRAVO, 'BRAVO') });+ const [body, sig] = token.split('.');+ const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));+ payload.b.mint = CHARLIE;+ const forged = `${Buffer.from(JSON.stringify(payload)).toString('base64url')}.${sig}`;+ expect(verifyWarTicket(forged)).toBe(null);+ });++ it('refuses to sign a pairing its key does not describe', () => {+ expect(signWarTicket({ matchKey: key, coinA: coin(ALPHA, 'ALPHA'), coinB: coin(CHARLIE, 'CHAR') })).toBe(null);+ expect(signWarTicket({ matchKey: 'not-a-key', coinA: coin(ALPHA, 'ALPHA'), coinB: coin(BRAVO, 'BRAVO') })).toBe(null);+ });++ it('rejects junk', () => {+ expect(verifyWarTicket('')).toBe(null);+ expect(verifyWarTicket(null)).toBe(null);+ expect(verifyWarTicket('a.b')).toBe(null);+ });+});diff --git a/workers/agent-sniper/alerts.js b/workers/agent-sniper/alerts.jsindex efd5f8acd..e7acbe4a6 100644--- a/workers/agent-sniper/alerts.js+++ b/workers/agent-sniper/alerts.js@@ -46,14 +46,14 @@ export function alertFeedDown({ network, mode }) {}/**- * The fleet cannot place a single entry — every armed wallet is below the size+ * The fleet cannot place a single entry: every armed wallet is below the size* its own executor would accept. This is the alert the 2026-07-29 outage did not* have: the worker stayed green for ten days while booking a thousand failed* buys, because nothing watched the money.*/export function alertFleetStarved({ summary, network, mode }) {alert(- 'fleet starved — no wallet can trade',+ 'fleet starved, no wallet can trade',`${summary} Network ${network} (${mode}). Nothing will fill until SOL reaches these wallets.`,'sniper:fleet-starved',);diff --git a/workers/agent-sniper/auto-funder.js b/workers/agent-sniper/auto-funder.jsindex db678160d..1eb0a9d6b 100644--- a/workers/agent-sniper/auto-funder.js+++ b/workers/agent-sniper/auto-funder.js@@ -245,10 +245,10 @@ async function publishSolvency(cfg, addresses, conn) {const summary = describeSolvency(snapshot);if (snapshot.state === 'starved') {- log.error('fleet starved — no armed wallet can place an entry', {+ log.error('fleet starved, no armed wallet can place an entry', {network: cfg.network, agents: snapshot.agents, deficit_sol: snapshot.deficitSol, master_sol: snapshot.masterSol,});- screenPush('Sniper fleet is out of SOL — no wallet can trade', 'guard');+ screenPush('Sniper fleet is out of SOL, no wallet can trade', 'guard');// Live money only: a simulate-mode fleet is starved by design (it never// funds anything), and paging on that would train operators to ignore this.if (cfg.mode === 'live') alertFleetStarved({ summary, network: cfg.network, mode: cfg.mode });@@ -302,7 +302,7 @@ async function tick(cfg) {break;}- // From the solvency pass above — an unreadable balance is absent, and a+ // From the solvency pass above: an unreadable balance is absent, and a// wallet we could not measure is never funded on a guess.const balanceSol = balances.get(agentId);if (balanceSol == null) continue;diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.jsindex 2a46019f1..4b1f8e01b 100644--- a/workers/agent-sniper/index.js+++ b/workers/agent-sniper/index.js@@ -380,7 +380,7 @@ async function main() {//// Started unconditionally: the same loop measures fleet solvency, and a fleet// running with auto-funding OFF is the one most likely to starve unnoticed- // (nothing refills it at all). Funding itself still requires cfg.autoFund —+ // (nothing refills it at all). Funding itself still requires cfg.autoFund,// the loop measures always, moves money only when armed to.const stopAutoFunder = startAutoFunderWatch({ cfg, signal: abort.signal });