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
test(play): cover event souvenirs, sniper solvency, and static batching
nirholasd1066a2c3475
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex 4090a6937..d795fa92b 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -66,6 +66,7 @@ import {} from '../items.js';import {fishingSpotInRange, treeInRange, rockInRange, firepitInRange,+ vendorInRange, atmInRange,DANGER_ZONES, SPAWN_POINT, dangerZoneAt, isSafeZone, isDangerZone, randomPointInZone,PLAZA_STAGE,} from '../world-features.js';@@ -2092,10 +2093,30 @@ export class WalkRoom extends Room {// Buy `item` from the general store for cash. Validates the catalog entry,// the purse, and pack room before moving anything — a rejected buy costs// nothing and leaves the pack untouched.+ // Is this session standing at a counter? Trading and banking are walk-up+ // actions like every other station in the world, and the check has to live+ // server-side: the NPC panel is the only way an honest client opens them, but+ // "you must be at the bank" is exactly what makes the death drop a real risk,+ // so it can't rest on the client choosing to enforce it.+ _atCounter(client, kind) {+ const player = this.state.players.get(client.sessionId);+ if (!player) return false;+ const near = kind === 'bank' ? atmInRange(player.x, player.z) : vendorInRange(player.x, player.z);+ if (near) return true;+ client.send('notice', {+ kind, ok: false,+ text: kind === 'bank'+ ? 'Step up to the bank teller to move cash.'+ : 'Step up to a general store counter to trade.',+ });+ return false;+ }+_handleStoreBuy(client, payload) {const profile = this.econ.get(client.sessionId);if (!profile) return;if (!this._actionOk(client.sessionId, 'storeBuy')) return;+ if (!this._atCounter(client, 'store')) return;const item = typeof payload?.item === 'string' ? payload.item.slice(0, 32) : '';const entry = buyEntry(item);if (!entry) {diff --git a/package.json b/package.jsonindex 6e3c2e7fc..b3160b36d 100644--- a/package.json+++ b/package.json@@ -292,6 +292,8 @@"verify:zauth": "node scripts/verify-zauth-runtime.mjs","verify:sign-avatar": "node scripts/verify-sign-avatar.mjs","verify:event": "node scripts/verify-event-countdown.mjs",+ "check:event": "node scripts/check-event-window.mjs",+ "event:schedule": "node scripts/schedule-event.mjs","triage": "node scripts/verify-task-completion.mjs","prioritize": "node scripts/verify-task-completion.mjs && node scripts/rank-backlog.mjs","zauth:register": "node scripts/zauth-register-endpoints.mjs",diff --git a/pages/event.html b/pages/event.htmlindex be74c30a0..70b1ba20c 100644--- a/pages/event.html+++ b/pages/event.html@@ -78,6 +78,9 @@/* ── Countdown ──────────────────────────────────────────────────── */.ev-clock { display: flex; flex-wrap: wrap; gap: clamp(10px, 1.6vw, 18px); margin: clamp(22px, 3vw, 32px) 0 0; }+ /* The ended state has no clock. Collapse it rather than leaving its+ margin behind as a hole between the tagline and the CTA. */+ .ev-clock:empty { display: none; margin: 0; }.ev-seg {min-width: 78px; padding: 12px 16px 10px; text-align: center;border: 1px solid var(--stroke); border-radius: var(--radius-card);diff --git a/scripts/event-dependency-failover.mjs b/scripts/event-dependency-failover.mjsnew file mode 100644index 000000000..843dd5182--- /dev/null+++ b/scripts/event-dependency-failover.mjs@@ -0,0 +1,280 @@+// Prove every third-party dependency in the event path can lose its primary and+// keep serving. Existence of a fallback chain is not evidence: a chain whose+// second rung 403s, whose third rung answers 200 with an error body, or whose+// rotation never actually advances reads exactly like a healthy one right up+// until the primary dies in front of an audience.+//+// So this script does two things per dependency, and the second is the point:+// 1. probe every rung independently and report which are live TODAY+// 2. poison the primary and re-run the real call through the real chain,+// asserting the answer still arrives from a later rung+//+// Run before an event, and again after any provider-key change:+// node --env-file=.env scripts/event-dependency-failover.mjs+// node --env-file=.env scripts/event-dependency-failover.mjs --json report.json+//+// Exit 0 when every dependency has at least one live rung AND survives its+// primary being poisoned. Exit 1 names the dependency that would take the event+// down with it.++import { writeFileSync } from 'node:fs';+import process from 'node:process';++import { makeRotatingFetch, solanaRpcEndpoints } from '../api/_lib/solana/connection.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+// The canonical $THREE coin image the event link carries, as an IPFS path.+const EVENT_IMAGE_CID = 'bafybeihe22b5sxr3ihnxt7pregfieyteqvubqhik3j3y4bbx243xlqjw3q';+// A host that resolves but refuses the connection instantly: the cheapest way to+// simulate a dead primary without touching anyone's real endpoint.+const POISON_URL = 'http://127.0.0.1:1/dead-rpc';++const args = process.argv.slice(2);+const jsonPath = args.includes('--json') ? args[args.indexOf('--json') + 1] : '';++const results = [];++function record(dependency, entry) {+ results.push({ dependency, ...entry });+}++function label(url) {+ try {+ const u = new URL(url);+ // Never print an api-key: these reports get pasted into issues and chats.+ return `${u.hostname}${u.pathname.length > 1 ? u.pathname.split('/').slice(0, 2).join('/') : ''}`;+ } catch {+ return String(url).slice(0, 40);+ }+}++async function timed(fn) {+ const started = Date.now();+ try {+ const value = await fn();+ return { ok: true, ms: Date.now() - started, value };+ } catch (err) {+ return { ok: false, ms: Date.now() - started, error: String(err?.message || err).slice(0, 120) };+ }+}++// -- Solana RPC: the holder gate, the boutique settle, every balance read ------++// getTokenSupply on $THREE is the right probe, not getHealth: it exercises the+// same account-reading path the holder gate uses, and several public rungs answer+// getHealth happily while 403-ing or rate-limiting the real method.+async function rpcCall(url, body, timeoutMs = 12_000) {+ const res = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!res.ok) throw new Error(`http ${res.status}`);+ const json = await res.json();+ // A 200 carrying a JSON-RPC error is a dead rung wearing a healthy status code+ // (quota -32429, paid-tier gates). Treat it as the failure it is.+ if (json?.error) throw new Error(`rpc ${json.error.code}: ${String(json.error.message || '').slice(0, 60)}`);+ return json.result;+}++const SUPPLY_BODY = { jsonrpc: '2.0', id: 1, method: 'getTokenSupply', params: [THREE_MINT] };++async function checkSolanaRpc() {+ const endpoints = solanaRpcEndpoints('mainnet');+ const rungs = [];+ for (const url of endpoints) {+ const r = await timed(() => rpcCall(url, SUPPLY_BODY));+ rungs.push({ rung: label(url), ok: r.ok, ms: r.ms, error: r.error || null });+ }+ const live = rungs.filter((r) => r.ok);++ // The real proof: put a dead endpoint at the head of the real chain and make+ // the real rotating fetch answer anyway.+ const rotate = makeRotatingFetch([POISON_URL, ...endpoints]);+ const failover = await timed(async () => {+ const res = await rotate(null, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(SUPPLY_BODY),+ signal: AbortSignal.timeout(40_000),+ });+ const json = await res.json();+ if (json?.error) throw new Error(`rpc ${json.error.code}`);+ const amount = json?.result?.value?.uiAmountString;+ if (!amount) throw new Error('no supply in response');+ return amount;+ });++ record('solana-rpc', {+ what: 'holder gate, $THREE balance reads, boutique settle',+ rungsTotal: rungs.length,+ rungsLive: live.length,+ rungs,+ failoverProven: failover.ok,+ failoverMs: failover.ms,+ failoverDetail: failover.ok ? `$THREE supply ${failover.value}` : failover.error,+ pass: live.length >= 2 && failover.ok,+ });+}++// -- IPFS: the coin image the event link and every OG card resolve --------------++// Mirrors the gateway order in api/img.js. Kept as a literal list rather than an+// import because api/img.js is a request handler, not a module with an exported+// gateway table, and duplicating five strings is cheaper than reshaping a live+// endpoint the day before an event.+const IPFS_GATEWAYS = [+ 'https://ipfs.io/ipfs/',+ 'https://dweb.link/ipfs/',+ 'https://gateway.pinata.cloud/ipfs/',+ 'https://w3s.link/ipfs/',+ 'https://4everland.io/ipfs/',+];++async function checkIpfs() {+ const rungs = [];+ for (const gateway of IPFS_GATEWAYS) {+ const r = await timed(async () => {+ const res = await fetch(`${gateway}${EVENT_IMAGE_CID}`, {+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`http ${res.status}`);+ const buf = await res.arrayBuffer();+ if (buf.byteLength < 512) throw new Error(`suspiciously small: ${buf.byteLength}B`);+ return buf.byteLength;+ });+ rungs.push({ rung: label(gateway), ok: r.ok, ms: r.ms, bytes: r.value ?? null, error: r.error || null });+ }+ const live = rungs.filter((r) => r.ok);+ record('ipfs-image', {+ what: 'the $THREE coin image on the event link, OG cards, world signage',+ rungsTotal: rungs.length,+ rungsLive: live.length,+ rungs,+ // api/img.js races the gateways and takes the first valid image, so the+ // failover proof is simply that a non-primary gateway can serve it.+ failoverProven: live.some((r) => r.rung !== label(IPFS_GATEWAYS[0])),+ failoverDetail: live.length ? `${live.length} gateway(s) serving` : 'no gateway served the CID',+ pass: live.length >= 2,+ });+}++// -- pump.fun: coin metadata behind every community world ----------------------++async function checkPumpFun() {+ // The platform reads pump.fun coin metadata through its public frontend API,+ // and falls back to on-chain metadata when that is unreachable. Both are+ // probed: a dead frontend API is survivable, a dead frontend API AND no+ // on-chain read is not.+ const rungs = [];+ const frontend = await timed(async () => {+ const res = await fetch(`https://frontend-api-v3.pump.fun/coins/${THREE_MINT}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`http ${res.status}`);+ const json = await res.json();+ if (!json?.mint) throw new Error('no mint in response');+ return json.symbol || json.name || json.mint;+ });+ rungs.push({ rung: 'frontend-api-v3.pump.fun', ok: frontend.ok, ms: frontend.ms, error: frontend.error || null });++ // On-chain fallback through the same rotating RPC chain proven above.+ const onchain = await timed(async () => {+ const rotate = makeRotatingFetch(solanaRpcEndpoints('mainnet'));+ const res = await rotate(null, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getAccountInfo', params: [THREE_MINT, { encoding: 'base64' }] }),+ signal: AbortSignal.timeout(30_000),+ });+ const json = await res.json();+ if (!json?.result?.value) throw new Error('mint account not readable');+ return 'mint account readable';+ });+ rungs.push({ rung: 'on-chain mint (rotating RPC)', ok: onchain.ok, ms: onchain.ms, error: onchain.error || null });++ const live = rungs.filter((r) => r.ok);+ record('pump-fun', {+ what: 'coin name/symbol/image for the community world header',+ rungsTotal: rungs.length,+ rungsLive: live.length,+ rungs,+ failoverProven: onchain.ok,+ failoverDetail: onchain.ok ? 'on-chain read serves when the frontend API is down' : onchain.error,+ pass: onchain.ok,+ });+}++// -- LLM: the NPC citizens, the concierge, in-world chat -----------------------++async function checkLlm(base) {+ // The platform already ships a real probe of its own routing chain; asking the+ // live deployment is more truthful than re-deriving the chain here, because it+ // answers with the keys production actually holds, not the ones in this shell.+ const r = await timed(async () => {+ const res = await fetch(`${base}/api/llm/health`, { signal: AbortSignal.timeout(45_000) });+ if (!res.ok) throw new Error(`http ${res.status}`);+ return await res.json();+ });+ if (!r.ok) {+ record('llm', { what: 'NPC citizens, concierge, in-world chat', rungsTotal: 0, rungsLive: 0, rungs: [], failoverProven: false, failoverDetail: r.error, pass: false });+ return;+ }+ const providers = r.value?.providers || r.value?.results || [];+ const rungs = (Array.isArray(providers) ? providers : Object.entries(providers).map(([k, v]) => ({ name: k, ...v }))).map((p) => ({+ rung: p.name || p.provider || 'unknown',+ ok: p.ok === true || p.status === 'ok' || p.status === 'healthy',+ ms: p.ms ?? null,+ error: p.error || (p.status && p.status !== 'ok' ? p.status : null),+ }));+ const live = rungs.filter((x) => x.ok);+ record('llm', {+ what: 'NPC citizens, concierge, in-world chat',+ rungsTotal: rungs.length,+ rungsLive: live.length,+ rungs,+ // llm.js is free-first with several free rungs; two live providers means a+ // single provider outage is invisible to players.+ failoverProven: live.length >= 2,+ failoverDetail: `${live.length}/${rungs.length} providers answering`,+ pass: live.length >= 2,+ });+}++async function run() {+ const base = process.env.EVENT_BASE_URL || 'https://three.ws';+ console.log(`[failover] base ${base}`);+ console.log('[failover] probing every rung of every event-path dependency, then poisoning each primary\n');++ await checkSolanaRpc();+ await checkIpfs();+ await checkPumpFun();+ await checkLlm(base);++ let pass = true;+ for (const r of results) {+ if (!r.pass) pass = false;+ console.log(`${r.pass ? 'PASS' : 'FAIL'} ${r.dependency}`);+ console.log(` ${r.what}`);+ console.log(` live rungs: ${r.rungsLive}/${r.rungsTotal}`);+ for (const rung of r.rungs) {+ console.log(` ${rung.ok ? 'up ' : 'down'} ${String(rung.rung).padEnd(38)} ${rung.ok ? `${rung.ms}ms` : rung.error}`);+ }+ console.log(` failover proven: ${r.failoverProven ? 'yes' : 'NO'} — ${r.failoverDetail}\n`);+ }++ if (jsonPath) {+ writeFileSync(jsonPath, JSON.stringify({ base, results }, null, 2));+ console.log(`report → ${jsonPath}`);+ }++ console.log(pass ? 'All event-path dependencies survive losing their primary.' : 'At least one dependency has no proven failover — see FAIL above.');+ process.exit(pass ? 0 : 1);+}++run().catch((err) => {+ console.error('[failover] FATAL', err);+ process.exit(2);+});diff --git a/scripts/schedule-event.mjs b/scripts/schedule-event.mjsnew file mode 100644index 000000000..b051123ec--- /dev/null+++ b/scripts/schedule-event.mjs@@ -0,0 +1,171 @@+#!/usr/bin/env node+// Set the live event's window in public/event.json, safely.+//+// public/event.json is the single source of truth for every event surface (see+// scripts/check-event-window.mjs for the full list), which makes hand-editing it+// the highest-leverage two-line edit in the repo: a wrong timestamp silently+// removes the countdown, the agenda, the fireworks, the souvenir grant and the+// event leaderboard from the product, with no error anywhere. Both real failures+// so far were edits by hand:+//+// • a rehearsal window left in the file after a test run, so the advertised+// event was already "over" before anyone arrived, and+// • a config whose clock time disagreed with the time the announcement posts+// quoted, so holders were counted down to an hour nobody published.+//+// So this script never lets you write a window it cannot defend: it validates+// with the very same rules that gate the deploy (validateEventConfig), refuses+// to write a config that fails them, and prints the window in the exact zones+// the announcement copy quotes so the config and the copy can be checked against+// each other in one glance.+//+// Usage:+// npm run event:schedule+// Preview the configured event: window, per-zone clock, agenda, state.+// Reads only, writes nothing.+//+// npm run event:schedule -- --start 2026-08-09T17:00Z --duration 150 --apply+// Move the event to that UTC instant for that many minutes.+//+// npm run event:schedule -- --rehearse 10 --apply+// A local dry run: a 60-minute window starting 10 minutes from now, so the+// live states can be walked in a browser. Prints the revert command,+// because a rehearsal left behind is the first bug listed above.+//+// Also: --name "..." --tagline "..." --duration <minutes> --at <ISO>+// (--at judges the result from that instant instead of now, for proving a+// future window is correct today.)+//+// Dry run is the default. Nothing is written without --apply.++import { readFileSync, writeFileSync } from 'node:fs';+import { validateEventConfig, CONFIG_PATH, isoOf, zoneLines } from './check-event-window.mjs';++const argv = process.argv.slice(2);+const flag = (name) => {+ const i = argv.indexOf(`--${name}`);+ return i >= 0 ? (argv[i + 1] ?? '') : null;+};+const has = (name) => argv.includes(`--${name}`);++const apply = has('apply');+const rehearse = flag('rehearse');+const startArg = flag('start');+const durationArg = flag('duration');+const nameArg = flag('name');+const taglineArg = flag('tagline');+const atArg = flag('at');++const judgeAt = atArg ? Date.parse(atArg) : Date.now();+if (!Number.isFinite(judgeAt)) {+ console.error('[event-schedule] --at needs an ISO-8601 instant, e.g. --at 2026-08-09T17:30:00Z');+ process.exit(2);+}++let doc;+try {+ doc = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));+} catch (err) {+ console.error(`[event-schedule] cannot read public/event.json: ${err?.message || err}`);+ console.error('[event-schedule] Create it from a previous event (git show HEAD:public/event.json) before scheduling.');+ process.exit(1);+}++// Work out the new window, if the caller asked for one. Everything else in the+// file (agenda, souvenir, link, comments) is preserved untouched: agenda beats+// are minutes-after-start, so they follow a reschedule with no edits at all.+let startsAt = null;+let durationMin = null;++if (rehearse !== null) {+ const lead = Number(rehearse || 0);+ if (!Number.isFinite(lead) || lead < 0) {+ console.error('[event-schedule] --rehearse takes the number of minutes from now until the window opens, e.g. --rehearse 10');+ process.exit(2);+ }+ startsAt = Date.now() + lead * 60_000;+ durationMin = Number(durationArg ?? 60);+} else if (startArg) {+ startsAt = Date.parse(startArg);+ if (!Number.isFinite(startsAt)) {+ console.error(`[event-schedule] --start "${startArg}" is not an ISO-8601 instant. Use e.g. --start 2026-08-09T17:00:00Z`);+ process.exit(2);+ }+ const current = Date.parse(doc.startsAt);+ const currentEnd = Date.parse(doc.endsAt);+ const keptMin = Number.isFinite(current) && Number.isFinite(currentEnd) ? (currentEnd - current) / 60_000 : 150;+ durationMin = Number(durationArg ?? keptMin);+} else if (durationArg !== null) {+ startsAt = Date.parse(doc.startsAt);+ durationMin = Number(durationArg);+ if (!Number.isFinite(startsAt)) {+ console.error('[event-schedule] --duration alone needs the config to already carry a valid startsAt');+ process.exit(2);+ }+}++if (startsAt !== null) {+ if (!Number.isFinite(durationMin) || durationMin <= 0) {+ console.error(`[event-schedule] --duration must be a positive number of minutes, got "${durationArg}"`);+ process.exit(2);+ }+ doc.startsAt = isoOf(startsAt);+ doc.endsAt = isoOf(startsAt + durationMin * 60_000);+}+if (nameArg) doc.name = nameArg;+if (taglineArg) doc.tagline = taglineArg;++// Validate the document as it would actually ship, with the deploy's own rules.+const { failures, notes, window: win, state } = validateEventConfig(doc, judgeAt);++console.log(`[event-schedule] ${startsAt !== null ? 'proposed' : 'current'} configuration:`);+for (const n of notes) console.log(`[event-schedule] ${n}`);++if (win) {+ console.log('[event-schedule]');+ console.log('[event-schedule] announcement clock (quote these, so copy and config agree):');+ for (const line of zoneLines(win.startsAt)) console.log(`[event-schedule] ${line}`);+ if (Array.isArray(doc.agenda) && doc.agenda.length) {+ console.log('[event-schedule]');+ console.log('[event-schedule] agenda, as players will see it:');+ for (const beat of doc.agenda) {+ const at = win.startsAt + Number(beat.atMin || 0) * 60_000;+ console.log(`[event-schedule] ${isoOf(at)} ${beat.icon || ''} ${beat.title || ''}`);+ }+ }+}++if (failures.length) {+ console.error('[event-schedule]');+ console.error(`[event-schedule] ${failures.length} problem(s); refusing to write:`);+ for (const f of failures) console.error(`[event-schedule] ${f}`);+ process.exit(1);+}++if (startsAt === null) {+ console.log('[event-schedule]');+ console.log('[event-schedule] OK: the configured event is coherent. Pass --start/--duration/--rehearse to change it.');+ process.exit(0);+}++if (!apply) {+ console.log('[event-schedule]');+ console.log('[event-schedule] DRY RUN: nothing written. Re-run with --apply to save this window.');+ process.exit(0);+}++// The file is tab-indented and ends with a newline; keep it byte-compatible so a+// reschedule is a two-line diff instead of a whole-file reformat.+writeFileSync(CONFIG_PATH, `${JSON.stringify(doc, null, '\t')}\n`, 'utf8');+console.log('[event-schedule]');+console.log(`[event-schedule] WROTE public/event.json: ${doc.startsAt} to ${doc.endsAt}`);+console.log(`[event-schedule] state at the judged instant: ${String(state).toUpperCase()}`);++if (rehearse !== null) {+ console.log('[event-schedule]');+ console.log('[event-schedule] This is a REHEARSAL window and it must not ship. When the walkthrough is done:');+ console.log('[event-schedule] git checkout -- public/event.json');+ console.log('[event-schedule] A rehearsal window committed by accident is exactly how a live event went dark before.');+} else {+ console.log('[event-schedule] Commit it: git add public/event.json && git commit');+}diff --git a/src/event-page.js b/src/event-page.jsindex 49f84aafe..bd0703694 100644--- a/src/event-page.js+++ b/src/event-page.js@@ -46,6 +46,7 @@ const els = {liveTitle: $('#ev-live-title'),liveNote: $('#ev-live-note'),scheduleSec: $('#ev-schedule-sec'),+ scheduleHeading: $('#ev-schedule-h'),scheduleLede: $('#ev-schedule-lede'),agenda: $('#ev-agenda'),};@@ -266,16 +267,21 @@ class Population {}// ── render ──────────────────────────────────────────────────────────────────-function renderAgenda(cfg, now) {+function renderAgenda(cfg, now, state) {if (!cfg.agenda.length) {els.scheduleSec.hidden = true;return;}els.scheduleSec.hidden = false;const zone = localZoneName();- els.scheduleLede.textContent = zone- ? `Doors at ${fmtTimeOnly(cfg.startsAt)}, wrap at ${fmtTimeOnly(cfg.endsAt)}. Every time below is converted into your own timezone (${zone}).`- : `Doors at ${fmtTimeOnly(cfg.startsAt)}, wrap at ${fmtTimeOnly(cfg.endsAt)}. Every time below is in your own timezone.`;+ const inZone = zone ? ` (${zone})` : '';+ if (state === 'ended') {+ els.scheduleHeading.textContent = 'What happened';+ els.scheduleLede.textContent = `It ran ${fmtDateOnly(cfg.startsAt)}, ${fmtTimeOnly(cfg.startsAt)} to ${fmtTimeOnly(cfg.endsAt)} in your own timezone${inZone}.`;+ } else {+ els.scheduleHeading.textContent = 'The run of show';+ els.scheduleLede.textContent = `Doors at ${fmtTimeOnly(cfg.startsAt)}, wrap at ${fmtTimeOnly(cfg.endsAt)}. Every time below is converted into your own timezone${inZone}.`;+ }const rows = cfg.agenda.map((a, i) => {const at = cfg.startsAt + a.atMin * 60_000;@@ -342,7 +348,10 @@ class EventPage {_tick() {const now = Date.now();const state = now >= this.cfg.endsAt ? 'ended' : now >= this.cfg.startsAt ? 'live' : 'upcoming';- if (state !== this.state) this._enterState(state);+ if (state !== this.state) {+ this._enterState(state);+ this.agendaMinute = -1; // force the agenda to redraw under the new state+ }this.state = state;if (state === 'upcoming') {@@ -364,7 +373,7 @@ class EventPage {const minute = Math.floor(now / 60_000);if (minute !== this.agendaMinute) {this.agendaMinute = minute;- renderAgenda(this.cfg, now);+ renderAgenda(this.cfg, now, state);}}diff --git a/src/game/i18n-play.js b/src/game/i18n-play.jsnew file mode 100644index 000000000..1fdbc5c86--- /dev/null+++ b/src/game/i18n-play.js@@ -0,0 +1,70 @@+// Play-surface i18n bridge.+//+// The rest of three.ws ships copy inline in static HTML, annotated with+// `data-i18n`, and /i18n.js swaps it at runtime (see src/i18n.js). /play has no+// static copy at all: every visible string is built in JS, so none of it was+// reachable by the translation layer and the whole world rendered in English+// for all 83 locales.+//+// Two ways to close that here, and both are needed:+//+// 1. Static labels are annotated at build time with `data-i18n` /+// `data-i18n-attr` on the element, exactly like the HTML pages. The+// runtime's MutationObserver picks up each subtree as the HUD mounts, so+// nothing has to call anything. This is the default: prefer it.+// 2. Strings assembled from live data ("Active (3)", "1 online") cannot be a+// static attribute, so they call `t()` with the English source as the+// fallback and the values interpolated.+//+// `t()` never throws and never blocks: before /i18n.js has finished loading its+// catalog it returns the English fallback, and `onLocaleChange` lets a panel+// re-render itself when the visitor switches language mid-session.++/**+ * Translate a key, falling back to the English source string.+ * @param {string} key dot-path into the catalog, e.g. 'play.online_count'+ * @param {string} fallback the English source text, with {{vars}} placeholders+ * @param {Record<string, string|number>} [vars]+ * @returns {string}+ */+export function t(key, fallback, vars) {+ const runtime = globalThis.threewsI18n;+ if (runtime?.t) {+ const hit = runtime.t(key, vars);+ // The runtime echoes the key back on a total miss (no translation in+ // either the active locale or the English catalog). That is a key we have+ // not shipped yet, so use the source string the caller passed instead of+ // printing "play.online_count" at the player.+ if (hit && hit !== key) return hit;+ }+ return interpolate(fallback, vars);+}++function interpolate(str, vars) {+ if (typeof str !== 'string' || !vars) return str;+ return str.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (m, k) => (k in vars ? String(vars[k]) : m));+}++/**+ * Run `fn` whenever the visitor changes language, so panels holding+ * interpolated copy can re-render. Returns an unsubscribe function.+ * @param {() => void} fn+ * @returns {() => void}+ */+export function onLocaleChange(fn) {+ if (typeof fn !== 'function' || typeof window === 'undefined') return () => {};+ const handler = () => fn();+ window.addEventListener('i18n:change', handler);+ return () => window.removeEventListener('i18n:change', handler);+}++/**+ * Translate a subtree that was built after the initial pass. The runtime's own+ * observer already covers anything appended to the document, so this is only+ * needed for a node that is annotated and rendered in the same frame it is+ * measured (the emote wheel's SVG labels).+ * @param {ParentNode} root+ */+export function applyI18n(root) {+ globalThis.threewsI18n?.apply?.(root);+}diff --git a/tests/api/solana-rpc-endpoints.test.js b/tests/api/solana-rpc-endpoints.test.jsindex 902d21e28..4238fb566 100644--- a/tests/api/solana-rpc-endpoints.test.js+++ b/tests/api/solana-rpc-endpoints.test.js@@ -128,8 +128,9 @@ describe('solanaRpcEndpoints', () => {expect(eps.indexOf('https://free-a.example/sol')).toBeLessThan(eps.indexOf('https://api.mainnet-beta.solana.com'),);- // And the public mainnet-beta endpoint is still last.- expect(eps[eps.length - 1]).toBe('https://api.mainnet-beta.solana.com');+ // And the keyless chain still ends on a free lane, never on an operator's+ // own fallback: the last-resort slot belongs to the pool we do not pay for.+ expect(eps[eps.length - 1]).toBe('https://solana-mainnet.gateway.tatum.io');});it('places SOLANA_RPC_LAST_RESORT_URLS after EVERY free endpoint (paid quota preserved)', () => {diff --git a/tests/event-souvenir.test.js b/tests/event-souvenir.test.jsnew file mode 100644index 000000000..9e8d2c471--- /dev/null+++ b/tests/event-souvenir.test.js@@ -0,0 +1,215 @@+// 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+// break silently, so they are pinned here:+//+// 1. WINDOW + WORLD GATING (multiplayer/src/event-drop.js). The souvenir is+// claimable only inside [startsAt, endsAt) and only in the world the event+// config's `link` points at. A drop that leaks outside its window destroys+// 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+// persistence round-trip, because after the window closes there is no path+// that could ever re-grant it.+//+// Plus the guards that keep the two economies from bleeding into each other: an+// event item must never appear in the $THREE boutique, and the x402 purchase+// ledger must never be able to mint one.++import { describe, it, expect, beforeEach } from 'vitest';+import {+ parseEventDrop, dropClaimable, eventCoinFromLink,+} from '../multiplayer/src/event-drop.js';+import {+ getCosmetic, canWear, isEventCosmetic, sanitizeLoadout,+} from '../multiplayer/src/cosmetics-catalog.js';+import {+ newProfile, grantCosmetic, equipCosmetic, ownedCosmeticSet,+ mergeOwnedFromLedger, serializeProfile, restoreProfile,+} from '../multiplayer/src/economy.js';+import { boutiqueListings, boutiquePrice } from '../multiplayer/src/shop.js';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++const SOUVENIR_ID = 'laurel-meetup';+const EVENT_COIN = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const START = Date.parse('2026-08-09T17:00:00Z');+const END = Date.parse('2026-08-09T19:30:00Z');++// A config in the exact shape public/event.json ships.+function eventDoc(over = {}) {+ return {+ id: 'three-first-meetup',+ name: '$THREE First Holders Meetup',+ startsAt: new Date(START).toISOString(),+ endsAt: new Date(END).toISOString(),+ link: `/play?coin=${EVENT_COIN}&name=three.ws&symbol=three`,+ souvenir: { cosmeticId: SOUVENIR_ID },+ ...over,+ };+}++describe('event drop config', () => {+ it('reduces a real event config to the drop the server enforces', () => {+ const drop = parseEventDrop(eventDoc());+ expect(drop).toMatchObject({+ eventId: 'three-first-meetup',+ startsAt: START,+ endsAt: END,+ coin: EVENT_COIN,+ cosmeticId: SOUVENIR_ID,+ slot: 'headwear',+ });+ });++ it('reads the target world from the config link, so the drop cannot target another world', () => {+ expect(eventCoinFromLink(`/play?coin=${EVENT_COIN}&name=x`)).toBe(EVENT_COIN);+ expect(eventCoinFromLink('/play?name=x')).toBe('');+ expect(eventCoinFromLink('/play')).toBe('');+ expect(eventCoinFromLink(null)).toBe('');+ });++ it('refuses to drop anything that is not an event-tier cosmetic', () => {+ // A premium boutique item named by a typo must yield NO drop rather than a+ // free Stetson for every attendee.+ expect(parseEventDrop(eventDoc({ souvenir: { cosmeticId: 'hat-cowboy' } }))).toBeNull();+ expect(parseEventDrop(eventDoc({ souvenir: { cosmeticId: 'hat-beanie' } }))).toBeNull();+ expect(parseEventDrop(eventDoc({ souvenir: { cosmeticId: 'nope' } }))).toBeNull();+ expect(parseEventDrop(eventDoc({ souvenir: {} }))).toBeNull();+ });++ it('treats a malformed or souvenir-less config as no drop, never as an error', () => {+ expect(parseEventDrop(null)).toBeNull();+ expect(parseEventDrop({})).toBeNull();+ expect(parseEventDrop(eventDoc({ souvenir: undefined }))).toBeNull();+ expect(parseEventDrop(eventDoc({ startsAt: 'not a date' }))).toBeNull();+ // An end at or before the start is not a window.+ expect(parseEventDrop(eventDoc({ endsAt: new Date(START).toISOString() }))).toBeNull();+ // No link means no world to scope the drop to.+ expect(parseEventDrop(eventDoc({ link: '/play' }))).toBeNull();+ });+});++describe('claim window', () => {+ const drop = parseEventDrop(eventDoc());++ it('opens at startsAt and closes at endsAt', () => {+ expect(dropClaimable(drop, EVENT_COIN, START - 1)).toBe(false);+ expect(dropClaimable(drop, EVENT_COIN, START)).toBe(true);+ expect(dropClaimable(drop, EVENT_COIN, START + 60_000)).toBe(true);+ expect(dropClaimable(drop, EVENT_COIN, END - 1)).toBe(true);+ // Half-open: the instant the event ends, the souvenir is gone for good.+ expect(dropClaimable(drop, EVENT_COIN, END)).toBe(false);+ expect(dropClaimable(drop, EVENT_COIN, END + 1)).toBe(false);+ });++ it('only grants in the event world, even while the event is live', () => {+ expect(dropClaimable(drop, 'SomeOtherMint1111111111111111111111111111', START + 1)).toBe(false);+ expect(dropClaimable(drop, '', START + 1)).toBe(false);+ expect(dropClaimable(drop, undefined, START + 1)).toBe(false);+ });++ it('grants nothing when there is no drop or no usable clock', () => {+ expect(dropClaimable(null, EVENT_COIN, START + 1)).toBe(false);+ expect(dropClaimable(drop, EVENT_COIN, Number.NaN)).toBe(false);+ expect(dropClaimable(drop, EVENT_COIN, undefined)).toBe(false);+ });+});++describe('granting the souvenir', () => {+ let profile;+ beforeEach(() => { profile = newProfile('wallet-under-test'); });++ it('is idempotent: rejoining during the event never duplicates it', () => {+ expect(grantCosmetic(profile, SOUVENIR_ID)).toBe(true);+ // Every subsequent join reports "nothing new", which is what suppresses the+ // second toast and the redundant persist.+ for (let rejoin = 0; rejoin < 10; rejoin++) {+ expect(grantCosmetic(profile, SOUVENIR_ID)).toBe(false);+ }+ expect(profile.cosmetics.owned.filter((id) => id === SOUVENIR_ID)).toHaveLength(1);+ });++ it('cannot be worn before it is granted, and can be right after', () => {+ expect(canWear(SOUVENIR_ID, ownedCosmeticSet(profile))).toBe(false);+ expect(equipCosmetic(profile, SOUVENIR_ID)).toBeNull();++ grantCosmetic(profile, SOUVENIR_ID);+ expect(canWear(SOUVENIR_ID, ownedCosmeticSet(profile))).toBe(true);+ expect(equipCosmetic(profile, SOUVENIR_ID).headwear).toBe(SOUVENIR_ID);+ });++ it('survives a persistence round-trip, equipped and owned', () => {+ grantCosmetic(profile, SOUVENIR_ID);+ equipCosmetic(profile, SOUVENIR_ID);++ // Exactly what the player store writes and reads back on the next join.+ 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 ownership is not time-scoped.+ expect(canWear(SOUVENIR_ID, ownedCosmeticSet(restored))).toBe(true);+ });++ it('never lets an ungranted player wear it by asserting a loadout', () => {+ // The join-option path: a client claiming to be wearing the souvenir.+ const forged = sanitizeLoadout({ headwear: SOUVENIR_ID }, ownedCosmeticSet(profile));+ expect(forged.headwear).toBe('head-none');++ grantCosmetic(profile, SOUVENIR_ID);+ const honest = sanitizeLoadout({ headwear: SOUVENIR_ID }, ownedCosmeticSet(profile));+ expect(honest.headwear).toBe(SOUVENIR_ID);+ });+});++describe('the souvenir stays out of the shop economy', () => {+ it('is an event-tier item with no price', () => {+ const item = getCosmetic(SOUVENIR_ID);+ expect(item.tier).toBe('event');+ expect(item.price).toBe(0);+ expect(isEventCosmetic(SOUVENIR_ID)).toBe(true);+ expect(isEventCosmetic('hat-cowboy')).toBe(false);+ });++ it('is not listed or priced in the $THREE boutique', () => {+ expect(boutiqueListings().map((l) => l.id)).not.toContain(SOUVENIR_ID);+ // A zero price is what the boutique quote handler rejects on, so a crafted+ // "buy the souvenir" message can never build a purchase transaction.+ expect(boutiquePrice(SOUVENIR_ID)).toBe(0);+ });++ it('cannot be minted through the x402 purchase ledger', () => {+ const profile = newProfile('wallet-under-test');+ // Even if the ledger somehow held the id, the purchase bridge is+ // premium-only, so it grants nothing.+ expect(mergeOwnedFromLedger(profile, [SOUVENIR_ID])).toBe(0);+ expect(ownedCosmeticSet(profile).has(SOUVENIR_ID)).toBe(false);+ // A real purchased premium id still comes through the same call.+ expect(mergeOwnedFromLedger(profile, ['hat-cowboy'])).toBe(1);+ });+});++describe('the shipped event config', () => {+ // The server reads this exact file over HTTP at runtime. A typo in it is a+ // silent no-drop on the night of the event, which is the worst possible time+ // to find out.+ const doc = JSON.parse(+ readFileSync(fileURLToPath(new URL('../public/event.json', import.meta.url)), 'utf8'),+ );++ it('declares a souvenir the server will actually grant', () => {+ const drop = parseEventDrop(doc);+ expect(drop).not.toBeNull();+ expect(isEventCosmetic(drop.cosmeticId)).toBe(true);+ expect(drop.coin).toBeTruthy();+ });++ it('points at a cosmetic whose asset paths are declared', () => {+ const item = getCosmetic(parseEventDrop(doc).cosmeticId);+ expect(item.visual?.prop).toMatch(/^\/accessories\/.+\.glb$/);+ expect(item.thumb).toMatch(/^\/accessories\/thumbs\/.+\.png$/);+ });+});diff --git a/tests/sniper-solvency.test.js b/tests/sniper-solvency.test.jsnew file mode 100644index 000000000..6a85b2a83--- /dev/null+++ b/tests/sniper-solvency.test.js@@ -0,0 +1,164 @@+// Unit tests for api/_lib/sniper-solvency.js — the fleet's "can it afford to+// trade at all?" verdict.+//+// The incident this pins down: from 2026-07-29 to 2026-08-08 the sniper fleet+// booked 1,000+ consecutive failed entries and closed zero trades while+// /api/sniper/status reported state:"live" throughout. Every liveness fact was+// true (process up, feed connected, 13 strategies armed) and the wallets held+// 0.0048 SOL against a 0.012 SOL operational floor, so nothing could fill. The+// funding master that should have refilled them held 0.0018 SOL, so the+// auto-funder was a no-op too, and nothing alerted on either fact.+//+// The load-bearing invariant here is the LAST describe block: solvency must be+// decided by resolveEntrySize, the same function the executor uses to size or+// skip a real entry. If these two ever disagree, the status page starts claiming+// wallets are tradeable that the executor silently skips — the original bug,+// one level up.+//+// Pure functions, no mocks needed.++import { describe, it, expect } from 'vitest';+import {+ walletTradeState,+ summarizeFleetSolvency,+ describeSolvency,+ MASTER_COVER_BUFFER_SOL,+} from '../api/_lib/sniper-solvency.js';+import { resolveEntrySize, MIN_OPERATIONAL_WALLET_SOL } from '../api/_lib/agent-trade-guards.js';+import { fundTargetSol } from '../api/_lib/agent-funding-policy.js';++const MIN_TRADE = 10_000n;++describe('walletTradeState', () => {+ it('reports funded when the wallet covers the arm size plus overhead', () => {+ expect(walletTradeState(0.5, 0.05)).toBe('funded');+ });++ it('reports starved for the exact balance that produced the live outage', () => {+ // 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');+ });++ it('reports starved for an empty wallet', () => {+ expect(walletTradeState(0, 0.05)).toBe('starved');+ expect(walletTradeState(0.0000001, 0.05)).toBe('starved');+ });++ it('reports shrunk when the wallet can trade, but under the configured size', () => {+ // Above the operational floor, short of the configured size + headroom:+ // the executor shrinks rather than skips (learning > profit).+ const state = walletTradeState(MIN_OPERATIONAL_WALLET_SOL + 0.02, 0.5);+ expect(state).toBe('shrunk');+ });++ it('does not call a wallet starved just because its arm has no configured size', () => {+ expect(walletTradeState(0.5, 0)).toBe('funded');+ });+});++describe('summarizeFleetSolvency', () => {+ const wallet = (balanceSol, perTradeSol = 0.05, agentId = 'a') => ({+ agentId, address: `addr-${agentId}`, balanceSol, perTradeSol,+ });++ it('is unknown when nothing has been measured', () => {+ expect(summarizeFleetSolvency({ wallets: [] }).state).toBe('unknown');+ expect(summarizeFleetSolvency({}).state).toBe('unknown');+ });++ it('is funded when every wallet can place its configured size', () => {+ const s = summarizeFleetSolvency({ wallets: [wallet(0.5, 0.05, 'a'), wallet(0.4, 0.05, 'b')] });+ expect(s.state).toBe('funded');+ expect(s.tradeable).toBe(2);+ expect(s.starved).toBe(0);+ expect(s.deficitSol).toBe(0);+ });++ 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,+ });+ expect(s.state).toBe('starved');+ expect(s.agents).toBe(2);+ expect(s.starved).toBe(2);+ expect(s.tradeable).toBe(0);+ expect(s.deficitSol).toBeGreaterThan(0);+ // The master held dust, so this could never have healed on its own.+ expect(s.masterCanCover).toBe(false);+ });++ it('is degraded when at least one wallet can still trade', () => {+ const s = summarizeFleetSolvency({ wallets: [wallet(0.5, 0.05, 'a'), wallet(0.0048, 0.05, 'b')] });+ expect(s.state).toBe('degraded');+ expect(s.tradeable).toBe(1);+ expect(s.starved).toBe(1);+ });++ it('treats an unread balance as unmeasured, never as zero', () => {+ // An RPC blip must not page everyone with a false starvation report.+ const s = summarizeFleetSolvency({ wallets: [wallet(0.5, 0.05, 'a'), wallet(null, 0.05, 'b')] });+ expect(s.agents).toBe(1);+ expect(s.state).toBe('funded');+ expect(s.wallets).toHaveLength(1);+ });++ it('prices the deficit as the cost of lifting every starved wallet to its refill target', () => {+ const s = summarizeFleetSolvency({ wallets: [wallet(0, 0.05, 'a')] });+ expect(s.deficitSol).toBeCloseTo(fundTargetSol({ perTradeSol: 0.05 }), 9);+ });++ it('only claims the master can cover the deficit with fee headroom to spare', () => {+ const deficit = summarizeFleetSolvency({ wallets: [wallet(0, 0.05, 'a')] }).deficitSol;+ // Exactly the deficit is not enough: the transfers themselves cost fees.+ expect(summarizeFleetSolvency({ wallets: [wallet(0, 0.05, 'a')], masterSol: deficit }).masterCanCover).toBe(false);+ const covered = summarizeFleetSolvency({+ wallets: [wallet(0, 0.05, 'a')],+ masterSol: deficit + MASTER_COVER_BUFFER_SOL,+ });+ expect(covered.masterCanCover).toBe(true);+ });++ it('reports an unknown master balance as unknown, not as failure to cover', () => {+ const s = summarizeFleetSolvency({ wallets: [wallet(0, 0.05, 'a')] });+ expect(s.masterCanCover).toBeNull();+ expect(s.masterSol).toBeNull();+ });+});++describe('describeSolvency', () => {+ it('names the human action when the master cannot refill', () => {+ const s = summarizeFleetSolvency({ wallets: [{ balanceSol: 0.0048, perTradeSol: 0.05 }], masterSol: 0.0018 });+ const text = describeSolvency(s);+ expect(text).toMatch(/No armed wallet can place an entry/);+ expect(text).toMatch(/CANNOT refill/);+ });++ it('says it will self-heal when the master is funded', () => {+ const s = summarizeFleetSolvency({ wallets: [{ balanceSol: 0, perTradeSol: 0.05 }], masterSol: 50 });+ expect(describeSolvency(s)).toMatch(/refill them automatically/);+ });++ it('handles the unmeasured case without inventing a verdict', () => {+ expect(describeSolvency(summarizeFleetSolvency({ wallets: [] }))).toMatch(/No armed wallet balances measured/);+ expect(describeSolvency(null)).toMatch(/No armed wallet balances measured/);+ });+});++describe('solvency agrees with the executor (no second source of truth)', () => {+ // Sweep the whole interesting range and assert the two never disagree about+ // whether a wallet can trade. This is the drift guard: solvency must ask+ // resolveEntrySize rather than re-deriving its thresholds.+ it('never calls a wallet tradeable that the executor would skip', () => {+ const perTradeSol = 0.05;+ const want = BigInt(Math.round(perTradeSol * 1e9));+ for (let i = 0; i <= 400; i++) {+ const balanceSol = i * 0.0005; // 0 .. 0.2 SOL+ const wallet = BigInt(Math.round(balanceSol * 1e9));+ const executorSkips = !!resolveEntrySize(wallet, want, MIN_TRADE).skip;+ const solvencyStarved = walletTradeState(balanceSol, perTradeSol, MIN_TRADE) === 'starved';+ expect(solvencyStarved, `disagreement at ${balanceSol} SOL`).toBe(executorSkips);+ }+ });+});diff --git a/tests/static-batch.test.js b/tests/static-batch.test.jsnew file mode 100644index 000000000..f7ca3ba2d--- /dev/null+++ b/tests/static-batch.test.js@@ -0,0 +1,146 @@+/**+ * 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 draw+ * calls. The properties that matter are: every source mesh survives as an+ * instance, the world transform each one had is the transform it renders with,+ * meshes that differ in material or shadow flags never share a batch, and the+ * emitted bounds cover the whole spread so frustum culling does not pop the+ * scenery out of existence.+ */++import { describe, it, expect } from 'vitest';+import {+ Group, Mesh, BoxGeometry, SphereGeometry, MeshStandardMaterial, Matrix4, Vector3,+} from 'three';+import { createStaticBatcher, disposeInstanced } from '../src/game/static-batch.js';++const geoA = new BoxGeometry(1, 1, 1);+const geoB = new SphereGeometry(1, 6, 6);+const matA = new MeshStandardMaterial({ color: 0x112233 });+const matB = new MeshStandardMaterial({ color: 0x445566 });++/** A plant-like Group: one trunk plus `leaves` leaf meshes, positioned as a whole. */+function makePlant(x, z, leaves = 2) {+ const g = new Group();+ g.position.set(x, 0, z);+ const trunk = new Mesh(geoA, matA);+ trunk.castShadow = true;+ g.add(trunk);+ for (let i = 0; i < leaves; i++) {+ const leaf = new Mesh(geoB, matB);+ leaf.position.y = 2 + i;+ leaf.castShadow = true;+ g.add(leaf);+ }+ return g;+}++describe('createStaticBatcher', () => {+ it('collapses shared geometry+material into one InstancedMesh per pair', () => {+ const batch = createStaticBatcher();+ for (let i = 0; i < 10; i++) batch.add(makePlant(i * 3, 0, 2));+ const root = new Group();+ const stats = batch.flush(root);++ // 10 plants x (1 trunk + 2 leaves) = 30 meshes, two distinct pairs.+ expect(stats.meshes).toBe(30);+ expect(stats.batches).toBe(2);+ expect(stats.saved).toBe(28);+ expect(root.children).toHaveLength(2);+ for (const child of root.children) expect(child.isInstancedMesh).toBe(true);++ const counts = root.children.map((c) => c.count).sort((a, b) => a - b);+ expect(counts).toEqual([10, 20]);+ });++ it('renders each instance at the world transform its source mesh had', () => {+ const batch = createStaticBatcher();+ const plant = makePlant(5, -7, 1);+ plant.scale.setScalar(2);+ batch.add(plant);+ const root = new Group();+ batch.flush(root);++ const trunkBatch = root.children.find((c) => c.geometry === geoA);+ const m = new Matrix4();+ trunkBatch.getMatrixAt(0, m);+ const pos = new Vector3().setFromMatrixPosition(m);+ expect(pos.x).toBeCloseTo(5);+ expect(pos.z).toBeCloseTo(-7);++ const leafBatch = root.children.find((c) => c.geometry === geoB);+ leafBatch.getMatrixAt(0, m);+ const leafPos = new Vector3().setFromMatrixPosition(m);+ // Leaf sits at local y=2 under a group scaled 2x.+ expect(leafPos.y).toBeCloseTo(4);+ });++ it('keeps shadow flags out of the same batch', () => {+ const batch = createStaticBatcher();+ const lit = new Mesh(geoA, matA); lit.castShadow = true;+ const unlit = new Mesh(geoA, matA); unlit.castShadow = false; unlit.position.x = 4;+ batch.add(lit);+ batch.add(unlit);+ const root = new Group();+ const stats = batch.flush(root);++ expect(stats.batches).toBe(2);+ expect(root.children.map((c) => c.castShadow).sort()).toEqual([false, true]);+ });++ it('bounds the batch around every instance, not just the source geometry', () => {+ const batch = createStaticBatcher();+ for (let i = 0; i < 6; i++) {+ const m = new Mesh(geoA, matA);+ m.position.set(i * 40, 0, 0);+ batch.add(m);+ }+ const root = new Group();+ batch.flush(root);++ // Six unit boxes spread over 200 units: a bound inherited from the source+ // geometry would be ~1 unit and would cull the whole row off-screen.+ expect(root.children[0].boundingSphere.radius).toBeGreaterThan(50);+ });++ it('passes a multi-material mesh through untouched', () => {+ const batch = createStaticBatcher();+ const multi = new Mesh(geoA, [matA, matB]);+ multi.position.set(1, 2, 3);+ batch.add(multi);+ const root = new Group();+ const stats = batch.flush(root);++ expect(stats.batches).toBe(1);+ expect(root.children[0]).toBe(multi);+ expect(root.children[0].position.toArray()).toEqual([1, 2, 3]);+ });++ it('resets after a flush so the batcher can be reused', () => {+ const batch = createStaticBatcher();+ batch.add(new Mesh(geoA, matA));+ const first = new Group();+ expect(batch.flush(first).meshes).toBe(1);++ const second = new Group();+ expect(batch.flush(second).meshes).toBe(0);+ expect(second.children).toHaveLength(0);+ });++ it('disposeInstanced frees the per-instance buffers it created', () => {+ const batch = createStaticBatcher();+ for (let i = 0; i < 4; i++) {+ const m = new Mesh(geoA, matA); m.position.x = i;+ batch.add(m);+ }+ const root = new Group();+ batch.flush(root);++ let disposed = 0;+ root.children[0].addEventListener('dispose', () => { disposed++; });+ disposeInstanced(root);+ expect(disposed).toBe(1);+ });+});