Skip to content

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.

fix(api): guard the $THREE stats window and earnings cursor, and land three concurrent audit batches

nirholas16a4f9817120
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a8dc0f609..6507e635c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-08-16
+- **Live stage hosts stop swallowing hyphens, and only confirmed tippers get greeted by name**: Two repairs to the Living Stages host. The cleanup pass that tidies the host's spoken line was stripping hyphens along with the invisible characters it was meant to remove, so every show heard "on chain" where the host said "on-chain" and "state of the art" for "state-of-the-art"; punctuation now survives and only invisible characters are removed. Separately, the host's memory of returning regulars counted tips whose on-chain settlement had not been confirmed yet, which meant anyone could post an unconfirmed tip under a name of their choosing and hear the host greet it aloud. That memory now reads confirmed tips only, matching the public leaderboard. Smaller repairs in the same pass: a stage that has not opened its first show is no longer cached as empty at the edge, an over-long coin address is refused instead of quietly trimmed into a different plaza, and the running tip total is written before the response returns. (`/stage`) `[fix, security]`
+- **Sharing an agent link posts the agent's picture again**: Pasting a link to an agent into a chat app, a social post or a group thread is supposed to unfurl into a card with the agent's name, its description and a picture of it. For every agent that actually has an avatar picture, which is nearly all of them, the page that builds that card was crashing instead, so the link unfurled as a bare URL with nothing attached. The card now renders with the agent's own thumbnail, falls back to a freshly rendered portrait when an agent has no thumbnail yet, and an unknown or malformed agent link sends the visitor to the app instead of erroring. `[fix]`
+- **The $THREE economy dashboard no longer errors out on an odd date range**: Asking the public $THREE economy stats endpoint for a window it could not read (a non-numeric range, or one longer than ten years) returned a server error instead of an answer. It now replies with a clear message for a range it cannot parse, caps an oversized one at ten years of history, and treats a blank range as all-time again. The creator earnings ledger does the same for a bad page cursor. `[fix]`
+- **The public profile sitemap now lists people, not the seed crons**: The sitemap Google and Bing crawl is split into one file per kind of page, and the profiles file was handing search engines every account row with a username. That was 29,600 machine accounts minted by the avatar and forge seed crons against 42 real people, growing by about one a minute, so the profiles that belong to actual members were buried under auto-generated ones whose content (the avatars and agents they own) was already listed in its own sitemap. Machine accounts are now excluded from both the profiles sitemap and the last-updated stamp the sitemap index publishes for it, so that stamp changes when a person updates their profile rather than every time a cron runs. Separately, a handful of URLs under the sitemap API answered scanners with a server error instead of a plain not-found, which also filed a false internal alert each time; those now return a normal not-found listing the sitemap types that do exist. `[fix, infra]`
+- **The sniper's laddered-exit settings can finally be saved**: An armed sniper strategy has two knobs that decide how a winner is taken off the table: the multiple of your entry at which it sells enough to recover what you put in, and the minimum slice of the position it always keeps riding afterwards. Both were documented and both were read by the trading worker, but the arm API quietly threw them away on the way in, so every strategy kept the fleet default no matter what you sent. They now save, an explicit null on the multiple switches the strategy back to a single-shot exit, and reading your strategies back reports both values plus whether the treasury is allowed to refill that agent's wallet. Sending the treasury-refill consent flag now returns a clear error instead of a success that changed nothing, because that permission is granted by the platform, not by the arm call. (`/dashboard/sniper`) `[fix, improvement]`
+- **Token-gated scene shares survive a slow RPC, and a gate that could never open is refused up front**: Three repairs to the holder-only chat scene shares. When the blockchain read behind a gate failed (a provider down, a missing provider key), visitors were told they did not hold enough tokens, which was untrue and also handed the provider's raw error text to anyone who asked; a failed read now says plainly that verification is unavailable and invites a retry, while a genuine shortfall still says exactly how much is missing. The Solana read itself now rotates through the same pool of providers the rest of the platform uses instead of leaning on one endpoint, NFT collection gates use the indexer that can actually answer them, and gates on Ethereum work without a paid provider key. Finally, a gate whose chain and asset type did not match (a Solana scene gated on an Ethereum token) used to be accepted and then locked everyone out forever; that combination, and an address in the wrong format for its chain, are now refused when the share link is created. (`/chat`) `[fix, improvement]`
- **Trending: muted text on the board is readable, and the Tip button that only navigated is gone**: Ten pieces of text on the Trending board sat below the WCAG AA contrast floor: the subtitle, the two unselected tabs, the 7d and all-time buttons, the column headers, agent descriptions and the unit labels next to each number. They are all legible now, and the Oracle link in the footnote is underlined instead of being told apart by colour alone. The wallet chip on each row carried a Tip button and a hover card, but the whole row is a link, so the browser followed the row instead of running either one: pressing Tip took you to the agent's wallet page rather than opening a tip. Both controls are gone from the board and tipping stays where it works, on the agent page the row opens, while the chip keeps showing the wallet address and its live balance. An automated accessibility scan now reports zero violations on all three boards and on their loading, empty and error states. (`/trending`) `[fix, improvement]`
## 2026-08-15
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 776745ca8..b74e61c19 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -1075,6 +1075,16 @@ export const limits = {
embedGateVerifyIp: (ip) => getLimiter('embed:gate:verify:ip', { limit: 30, window: '5 m' }).limit(ip),
embedGateVerifyWallet: (addr) =>
getLimiter('embed:gate:verify:wallet', { limit: 10, window: '5 m' }).limit(addr),
+ // Token-gated scene shares (api/scene/gate-check.js). Same anonymous-visitor
+ // shape as the embed gate above, so it gets the same pairing: a per-IP flood
+ // guard plus the per-wallet ceiling that a distributed-IP attacker cannot
+ // rotate around. Its own buckets rather than the embed ones so a busy embed
+ // does not lock a scene visitor out (and vice versa). The IP bucket is looser
+ // than the wallet bucket because one visitor spends two calls (nonce, then
+ // signature) per attempt and may legitimately switch wallets.
+ sceneGateCheckIp: (ip) => getLimiter('scene:gate:check:ip', { limit: 30, window: '5 m' }).limit(ip),
+ sceneGateCheckWallet: (addr) =>
+ getLimiter('scene:gate:check:wallet', { limit: 10, window: '5 m' }).limit(addr),
avatarRollback: (userId) =>
getLimiter('avatar:rollback', { limit: 10, window: '1 h' }).limit(userId),
// Chat inference spends real money on the host's LLM keys, so these are
diff --git a/api/scene/gate-check.js b/api/scene/gate-check.js
index 1ecc7a953..214c95497 100644
--- a/api/scene/gate-check.js
+++ b/api/scene/gate-check.js
@@ -1,14 +1,58 @@
+// POST /api/scene/gate-check
+//
+// Two-phase wallet-ownership proof for a token-gated scene share created by
+// api/scene/gate-create.js. The chat client (chat/src/App.svelte) calls it twice:
+//
+// Phase 1 - { gateId, walletAddress } -> { message, chain }
+// Issues a one-time nonce inside a human-readable message the visitor's wallet
+// signs. Nothing is granted yet.
+//
+// Phase 2 - { gateId, walletAddress, signature, message } -> { allowed, reason? }
+// Verifies the signature (ed25519 for Solana, personal_sign for EVM), burns the
+// nonce, then reads the wallet's REAL on-chain holding for the gate's asset.
+//
+// Fail-closed, and honest about WHY it failed: a denial ({ allowed: false }) means
+// the chain answered and the wallet is short. An RPC outage or a missing provider
+// key is an infrastructure fault, so it returns 5xx with a generic message rather
+// than a denial carrying the upstream error text (which both lies to the visitor
+// and leaks internals to an unauthenticated caller).
+//
+// The nonce is burned BEFORE the chain read, so a failed read costs the visitor a
+// fresh phase 1. That is deliberate: a replayable nonce is worse than a retry.
import { z } from 'zod';
-import { verifyMessage } from 'ethers';
+import { verifyMessage, Contract, formatUnits, isAddress } from 'ethers';
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { randomToken } from '../_lib/crypto.js';
import { verifySiwsSignature } from '../_lib/siws.js';
import { parse } from '../_lib/validate.js';
+// getSplTokenBalance rotates the shared Solana lane pool (api/_lib/solana/connection.js)
+// instead of pinning one endpoint; dasSearchAssets targets Helius, the only provider
+// in our stack that implements the DAS methods collection gating needs.
+import { getSplTokenBalance } from '../_lib/embed-gate.js';
+import { dasRpcUrl, dasSearchAssets, isValidSolanaAddress } from '../_lib/nft-gate.js';
+import { evmFallbackProvider } from '../_lib/evm/rpc.js';
const NONCE_TTL_SEC = 10 * 60;
+// EVM gates carry a bare contract address with no chain id (see the scene_gates
+// schema), so they resolve on Ethereum mainnet. evmRpcEndpoints(1) puts the
+// public endpoints behind any configured/Alchemy URL, so gating still works on a
+// deployment with no provider key rather than hard-failing on ALCHEMY_API_KEY.
+const EVM_CHAIN_ID = 1;
+
+// DAS pages at 1000 assets. A gate only needs to know whether the wallet reaches
+// min_balance, so paging stops as soon as the threshold is met; the cap bounds the
+// work an unauthenticated caller can trigger with a huge wallet.
+const DAS_PAGE_SIZE = 1000;
+const DAS_MAX_PAGES = 5;
+
+const ERC_BALANCE_ABI = [
+ 'function balanceOf(address owner) view returns (uint256)',
+ 'function decimals() view returns (uint8)',
+];
+
const phase1Schema = z.object({
gateId: z.string().trim().min(1).max(32),
walletAddress: z.string().trim().min(1).max(128),
@@ -24,16 +68,23 @@ const phase2Schema = z.object({
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
+ res.setHeader('cache-control', 'no-store');
- const rl = await limits.authedReadIp(clientIp(req));
+ const rl = await limits.sceneGateCheckIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const raw = await readJson(req);
- if (raw.signature != null) return handlePhase2(res, raw);
+ if (raw && raw.signature != null) return handlePhase2(res, raw);
return handlePhase1(res, raw);
});
+/** A wallet the gate's chain can actually verify. Catches a Solana address pasted
+ * into an EVM gate before it reaches an RPC that would answer with noise. */
+function walletMatchesChain(chain, walletAddress) {
+ return chain === 'solana' ? isValidSolanaAddress(walletAddress) : isAddress(walletAddress);
+}
+
async function handlePhase1(res, raw) {
const body = parse(phase1Schema, raw);
@@ -41,6 +92,9 @@ async function handlePhase1(res, raw) {
select id, chain from scene_gates where id = ${body.gateId} limit 1
`;
if (!gate) return error(res, 404, 'not_found', 'gate not found');
+ if (!walletMatchesChain(gate.chain, body.walletAddress)) {
+ return error(res, 400, 'validation_error', `walletAddress is not a valid ${gate.chain} address`);
+ }
let nonce = '';
while (nonce.length < 16) {
@@ -73,6 +127,15 @@ async function handlePhase2(res, raw) {
from scene_gates where id = ${body.gateId} limit 1
`;
if (!gate) return error(res, 404, 'not_found', 'gate not found');
+ if (!walletMatchesChain(gate.chain, body.walletAddress)) {
+ return error(res, 400, 'validation_error', `walletAddress is not a valid ${gate.chain} address`);
+ }
+
+ // A per-wallet ceiling on top of the per-IP flood guard: IPs are cheap to
+ // rotate, a wallet's signing key is not, so this is the bucket that actually
+ // bounds a determined attacker replaying signature attempts against one gate.
+ const wl = await limits.sceneGateCheckWallet(body.walletAddress);
+ if (!wl.success) return rateLimited(res, wl);
// Verify signature
if (gate.chain === 'solana') {
@@ -117,15 +180,30 @@ async function handlePhase2(res, raw) {
`;
if (!burned[0]) return error(res, 400, 'nonce_reused', 'nonce already used');
+ const minBalance = Number(gate.min_balance);
+
// Query chain holdings
let balance;
try {
- balance = await queryBalance(gate, body.walletAddress);
+ balance = await queryBalance(gate, body.walletAddress, minBalance);
} catch (e) {
- return json(res, 200, { allowed: false, reason: e.message || 'Balance check failed' });
+ console.warn(`[scene-gate] balance check failed for gate ${gate.id} (${gate.chain}/${gate.kind}):`, e?.message || e);
+ if (e?.status === 503) {
+ return error(
+ res,
+ 503,
+ 'not_configured',
+ 'This gate cannot be verified right now: its chain provider is not configured.',
+ );
+ }
+ return error(
+ res,
+ 502,
+ 'gate_check_unavailable',
+ 'Could not read your on-chain balance right now. Try verifying again in a moment.',
+ );
}
- const minBalance = Number(gate.min_balance);
if (balance >= minBalance) {
return json(res, 200, { allowed: true });
}
@@ -135,101 +213,54 @@ async function handlePhase2(res, raw) {
});
}
-async function queryBalance(gate, walletAddress) {
- if (gate.chain === 'solana') return querySolanaBalance(gate, walletAddress);
+async function queryBalance(gate, walletAddress, minBalance) {
+ if (gate.chain === 'solana') return querySolanaBalance(gate, walletAddress, minBalance);
return queryEvmBalance(gate, walletAddress);
}
-async function querySolanaBalance(gate, walletAddress) {
- const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-
- if (gate.kind === 'spl') {
- const resp = await fetch(rpcUrl, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- signal: AbortSignal.timeout(8000),
- body: JSON.stringify({
- jsonrpc: '2.0', id: 1,
- method: 'getTokenAccountsByOwner',
- params: [walletAddress, { mint: gate.address }, { encoding: 'jsonParsed' }],
- }),
+async function querySolanaBalance(gate, walletAddress, minBalance) {
+ if (gate.kind === 'spl') return getSplTokenBalance(walletAddress, gate.address);
+ return countCollectionAssets(walletAddress, gate.address, minBalance);
+}
+
+/** How many NFTs of `collectionMint` the wallet holds, counted only as far as
+ * `minBalance` (the answer past the threshold does not change the decision). */
+async function countCollectionAssets(walletAddress, collectionMint, minBalance) {
+ if (!dasRpcUrl()) {
+ throw Object.assign(new Error('HELIUS_API_KEY not configured'), { status: 503 });
+ }
+ const needed = Math.max(1, Math.ceil(minBalance));
+ let held = 0;
+ for (let page = 1; page <= DAS_MAX_PAGES; page++) {
+ const result = await dasSearchAssets({
+ ownerAddress: walletAddress,
+ grouping: ['collection', collectionMint],
+ // Burnt assets are not held, and a burn must not keep a gate open.
+ burnt: false,
+ page,
+ limit: DAS_PAGE_SIZE,
});
- if (!resp.ok) throw new Error(`Helius RPC error ${resp.status}`);
- const data = await resp.json();
- if (data.error) throw new Error(`Helius: ${data.error.message || JSON.stringify(data.error)}`);
- const accounts = data.result?.value || [];
- return accounts.reduce((sum, a) => sum + (a.account?.data?.parsed?.info?.tokenAmount?.uiAmount || 0), 0);
+ const items = Array.isArray(result.items) ? result.items : [];
+ held += items.length;
+ if (held >= needed || items.length < DAS_PAGE_SIZE) break;
}
-
- // NFT collection via DAS getAssetsByOwner
- const resp = await fetch(rpcUrl, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- signal: AbortSignal.timeout(8000),
- body: JSON.stringify({
- jsonrpc: '2.0', id: 1,
- method: 'getAssetsByOwner',
- params: {
- ownerAddress: walletAddress,
- page: 1,
- limit: 1000,
- displayOptions: { showCollectionMetadata: false },
- },
- }),
- });
- if (!resp.ok) throw new Error(`Helius DAS error ${resp.status}`);
- const data = await resp.json();
- if (data.error) throw new Error(`Helius: ${data.error.message || JSON.stringify(data.error)}`);
- const assets = data.result?.items || [];
- return assets.filter((a) =>
- (a.grouping || []).some((g) => g.group_key === 'collection' && g.group_value === gate.address),
- ).length;
+ return held;
}
async function queryEvmBalance(gate, walletAddress) {
- const alchemyKey = process.env.ALCHEMY_API_KEY;
- if (!alchemyKey) {
- const e = new Error('ALCHEMY_API_KEY not configured');
- e.status = 503;
- throw e;
- }
- const rpcUrl = `https://eth-mainnet.g.alchemy.com/v2/${alchemyKey}`;
-
- // balanceOf(address) — 0x70a08231
- const callData = '0x70a08231' + walletAddress.replace(/^0x/i, '').padStart(64, '0');
- const resp = await fetch(rpcUrl, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- signal: AbortSignal.timeout(8000),
- body: JSON.stringify({
- jsonrpc: '2.0', id: 1,
- method: 'eth_call',
- params: [{ to: gate.address, data: callData }, 'latest'],
- }),
- });
- if (!resp.ok) throw new Error(`Alchemy error ${resp.status}`);
- const data = await resp.json();
- if (data.error) throw new Error(`EVM RPC: ${data.error.message || JSON.stringify(data.error)}`);
+ const provider = await evmFallbackProvider(EVM_CHAIN_ID);
+ const token = new Contract(gate.address, ERC_BALANCE_ABI, provider);
+ const rawBalance = await token.balanceOf(walletAddress);
- const rawBalance = BigInt(data.result || '0x0');
+ // ERC-721 balances are whole tokens; ERC-20 needs the contract's own scale, and
+ // a token that omits decimals() is 18 by convention.
+ if (gate.kind === 'erc721') return Number(rawBalance);
- if (gate.kind === 'erc721') {
- return Number(rawBalance);
+ let decimals = 18;
+ try {
+ decimals = Number(await token.decimals());
+ } catch {
+ decimals = 18;
}
-
- // ERC-20: fetch decimals() — 0x313ce567
- const decResp = await fetch(rpcUrl, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- signal: AbortSignal.timeout(8000),
- body: JSON.stringify({
- jsonrpc: '2.0', id: 2,
- method: 'eth_call',
- params: [{ to: gate.address, data: '0x313ce567' }, 'latest'],
- }),
- });
- if (!decResp.ok) throw new Error(`Alchemy decimals error ${decResp.status}`);
- const decData = await decResp.json();
- const decimals = decData.result && decData.result !== '0x' ? Number(BigInt(decData.result)) : 18;
- return Number(rawBalance) / Math.pow(10, decimals);
+ return Number(formatUnits(rawBalance, decimals));
}
diff --git a/api/scene/gate-create.js b/api/scene/gate-create.js
index f46c1d37b..83d2318dd 100644
--- a/api/scene/gate-create.js
+++ b/api/scene/gate-create.js
@@ -1,3 +1,18 @@
+// POST /api/scene/gate-create
+//
+// Turns a chat scene share into a token-gated one: the caller supplies the scene
+// ref (a sync.three.ws short id or an inline blob) plus a holding requirement, and
+// gets back a share URL carrying the gate id. Visitors opening that URL must prove
+// the holding through api/scene/gate-check.js before the scene loads.
+//
+// The gate asset is a runtime parameter (the coin-agnostic plumbing exception in
+// CLAUDE.md) so any community can gate with its own token or collection; this
+// endpoint never defaults to or suggests a mint.
+//
+// chain and kind are validated as a PAIR. A gate stored as solana/erc20 would pass
+// per-field validation and then be unverifiable forever, since gate-check reads
+// Solana kinds on Solana and EVM kinds on Ethereum. Rejecting the combination here
+// is the only place it can be caught before it becomes a dead share link.
import { z } from 'zod';
import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
@@ -7,19 +22,47 @@ import { env } from '../_lib/env.js';
import { parse } from '../_lib/validate.js';
import { randomToken } from '../_lib/crypto.js';
-const bodySchema = z.object({
- sceneRef: z.string().trim().min(1).max(8000),
- gate: z.object({
- chain: z.enum(['solana', 'evm']),
- kind: z.enum(['spl', 'collection', 'erc20', 'erc721']),
- address: z.string().trim().min(1).max(128),
- minBalance: z.number().positive().default(1),
- }),
-});
+const KINDS_BY_CHAIN = {
+ solana: ['spl', 'collection'],
+ evm: ['erc20', 'erc721'],
+};
+
+const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
+
+const bodySchema = z
+ .object({
+ sceneRef: z.string().trim().min(1).max(8000),
+ gate: z.object({
+ chain: z.enum(['solana', 'evm']),
+ kind: z.enum(['spl', 'collection', 'erc20', 'erc721']),
+ address: z.string().trim().min(1).max(128),
+ minBalance: z.number().positive().default(1),
+ }),
+ })
+ .superRefine((value, ctx) => {
+ const { chain, kind, address } = value.gate;
+ if (!KINDS_BY_CHAIN[chain].includes(kind)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['gate', 'kind'],
+ message: `kind must be one of ${KINDS_BY_CHAIN[chain].join(', ')} for chain ${chain}`,
+ });
+ }
+ const addressOk = chain === 'solana' ? SOLANA_ADDRESS_RE.test(address) : EVM_ADDRESS_RE.test(address);
+ if (!addressOk) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['gate', 'address'],
+ message: chain === 'solana' ? 'address must be a base58 Solana address' : 'address must be a 0x-prefixed EVM address',
+ });
+ }
+ });
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
+ res.setHeader('cache-control', 'no-store');
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
@@ -42,7 +85,7 @@ export default wrap(async (req, res) => {
values (${gateId}, ${userId}, ${body.sceneRef}, ${body.gate.chain}, ${body.gate.kind}, ${body.gate.address}, ${body.gate.minBalance})
`;
- // Short refs (sync.three.ws shortIds) are ≤40 alphanumeric chars; blobs are much longer
+ // Short refs (sync.three.ws shortIds) are up to 40 alphanumeric chars; blobs are much longer
const isShortRef = body.sceneRef.length <= 40 && /^[A-Za-z0-9_-]+$/.test(body.sceneRef);
const shareUrl = isShortRef
? `${env.APP_ORIGIN}/chat?sl=${body.sceneRef}&gate=${gateId}`
diff --git a/api/stage/host.js b/api/stage/host.js
index a0e8168f2..1717a665e 100644
--- a/api/stage/host.js
+++ b/api/stage/host.js
@@ -166,6 +166,10 @@ function formatThree(amountAtomic, mint) {
export function sanitizeLine(s) {
if (typeof s !== 'string') return '';
let t = s.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
+ // The line is shown as live captions, which is platform copy: no em/en dash
+ // reaches a three.ws surface, whoever wrote it. A comma keeps the spoken
+ // pacing the model was reaching for. The plain hyphen above is untouched.
+ t = t.replace(/\s*[\u2013\u2014]\s*/g, ', ');
t = t.replace(/^["'“”]+|["'“”]+$/g, '').trim();
t = t.replace(/^[A-Za-z .]{0,24}:\s*/, ''); // drop a leaked speaker label
return t.slice(0, 400);
diff --git a/api/stage/index.js b/api/stage/index.js
index db5028fdd..df83edd30 100644
--- a/api/stage/index.js
+++ b/api/stage/index.js
@@ -186,8 +186,7 @@ async function stageDetail(stageId) {
}
export default wrap(async (req, res) => {
- cors(req, res, { methods: ['GET', 'POST', 'OPTIONS'] });
- if (req.method === 'OPTIONS') return res.end();
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
await ensureTables();
@@ -219,7 +218,7 @@ async function handleGet(req, res) {
// only needs the show state, so an UNCLAIMED plaza is a 200 with stage:null,
// the quiet-landmark case is normal, not an error.
if (req.query.coin) {
- const mint = cleanStr(req.query.coin, MAX_MINT);
+ const mint = cleanMint(req.query.coin);
if (!mint) return json(res, 400, { error: 'invalid coin mint' });
const stageId = plazaStageId(mint);
const detail = await stageDetail(stageId);
@@ -331,7 +330,7 @@ async function claimPlaza(req, res, session, body) {
const agent = await ownedAgent(body.agentId, session.id);
if (!agent) return json(res, 403, { error: 'you do not own this agent' });
- const mint = cleanStr(body.coinMint, MAX_MINT);
+ const mint = cleanMint(body.coinMint);
if (!mint) return json(res, 400, { error: 'coinMint is required' });
const stageId = plazaStageId(mint);
@@ -400,7 +399,8 @@ async function goLive(req, res, session, body) {
`;
await sql`UPDATE stages SET status = 'live', updated_at = NOW() WHERE id = ${stage.id}`;
- // Tell holders the show is starting, in-app bell + a best-effort Telegram ping.
+ // Put the show on the owner's bell and ping the ops channel, so a live start is
+ // visible without watching the directory.
insertNotification(session.id, 'stage_live', {
stage_id: stage.id,
agent_id: stage.agent_id,
@@ -468,6 +468,15 @@ function shapeShow(s) {
};
}
+// A mint is an identity, never a string to trim into shape: the browser derives
+// the plaza stage id from the mint it is standing in, so truncating an over-long
+// value here would claim (and read) a DIFFERENT stage than the world joins.
+// Reject it instead.
+function cleanMint(v) {
+ const m = cleanStr(v, MAX_MINT + 1);
+ return m.length > MAX_MINT ? '' : m;
+}
+
function cleanStr(v, max) {
if (typeof v !== 'string') return '';
return v.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
diff --git a/api/stage/tip.js b/api/stage/tip.js
index 1050a6c5e..8c10246b4 100644
--- a/api/stage/tip.js
+++ b/api/stage/tip.js
@@ -1,5 +1,5 @@
/**
- * Living Stages — record a real $THREE tip and make the host react (Moonshot 04).
+ * Living Stages: record a real $THREE tip and make the host react (Moonshot 04).
*
* The audience member transfers $THREE (or USDC, where the platform's pay path
* already allows it) directly to the host agent's wallet on-chain, then POSTs the
@@ -11,7 +11,7 @@
* security review, M4) let anyone POST a well-formed but unrelated signature
* with a huge amount and buy the top of the leaderboard plus a host
* shout-out for free,
- * 2. is IDEMPOTENT per signature — one settlement records exactly one tip row
+ * 2. is IDEMPOTENT per signature: one settlement records exactly one tip row
* (a unique index + ON CONFLICT DO NOTHING is the guarantee, so a client
* retry returns the existing row, never a double-credit),
* 3. computes the host/venue accounting split (the full amount already landed
@@ -42,12 +42,11 @@ import { verifySettlement } from '../_lib/settlement-verify.js';
import { hostPayoutWallets } from '../_lib/stage-wallets.js';
const MAX_MESSAGE = 140;
-// A tip is "loud" when it clears 10k $THREE (6 decimals) — worth a Telegram ping.
+// A tip is "loud" when it clears 10k $THREE (6 decimals), worth a Telegram ping.
const LOUD_TIP_ATOMIC = 10_000 * 1_000_000;
export default wrap(async (req, res) => {
- cors(req, res, { methods: ['GET', 'POST', 'OPTIONS'] });
- if (req.method === 'OPTIONS') return res.end();
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (req.method === 'GET') return handleGet(req, res);
if (req.method !== 'POST') return json(res, 405, { error: 'method_not_allowed' });
@@ -67,7 +66,7 @@ export default wrap(async (req, res) => {
// A cookie-borne (session) request is a CSRF target; an anonymous,
// settlement-proven tip has no ambient credential to abuse, so it is allowed
- // without CSRF (the on-chain signature is the proof) — same posture as the IRL
+ // without CSRF (the on-chain signature is the proof), the same posture as the IRL
// anonymous pay path. When signed in, enforce CSRF + attribute the tipper.
const session = await getSessionUser(req).catch(() => null);
if (session && !(await requireCsrf(req, res, session.id))) return;
@@ -91,7 +90,7 @@ export default wrap(async (req, res) => {
SELECT id FROM shows WHERE stage_id = ${stageId} AND ended_at IS NULL
ORDER BY started_at DESC LIMIT 1
`;
- if (!show) return json(res, 409, { error: 'no live show — tips open when the host goes live' });
+ if (!show) return json(res, 409, { error: 'no live show, tips open when the host goes live' });
const label = tipperLabel(session, body.tipperName);
const { hostCredit, venueCut, splitBps } = splitTip(valid.amount, stage.tip_split_bps);
@@ -168,7 +167,10 @@ export default wrap(async (req, res) => {
// Roll the show total (the row is already written, so a failed bump is logged,
// never fatal: the per-tip rows remain the source of truth for the leaderboard).
- sql`
+ // Awaited like promoteTip does it: an unawaited write can be lost when the
+ // container is reclaimed right after the response, which would understate the
+ // running total for the rest of the show.
+ await sql`
UPDATE shows SET total_tips_atomic = total_tips_atomic + ${valid.amount}, tip_count = tip_count + 1
WHERE id = ${show.id}
`.catch((err) => console.warn('[stage/tip] show total bump failed', { showId: show.id, reason: err?.message }));
@@ -226,7 +228,11 @@ async function handleGet(req, res) {
WHERE stage_id = ${stageId}
ORDER BY (ended_at IS NULL) DESC, started_at DESC LIMIT 1
`;
- if (!show) return json(res, 200, { leaderboard: [], totalTipsAtomic: 0, tipCount: 0 });
+ if (!show) {
+ // no-store like the populated branch: a stage that has not opened its first
+ // show yet must not be edge-cached as empty for the moment it goes live.
+ return json(res, 200, { leaderboard: [], totalTipsAtomic: 0, tipCount: 0 }, { 'cache-control': 'no-store' });
+ }
// Verified tips only: a quarantined row must never reach a public total.
const rows = await sql`
SELECT COALESCE(tipper_label, 'someone') AS label,
diff --git a/data/changelog.json b/data/changelog.json
index 30cdf9f6e..7aedaf542 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-16",
+ "title": "Sharing an agent link posts the agent's picture again",
+ "summary": "Pasting a link to an agent into a chat app, a social post or a group thread is supposed to unfurl into a card with the agent's name, its description and a picture of it. For every agent that actually has an avatar picture, which is nearly all of them, the page that builds that card was crashing instead, so the link unfurled as a bare URL with nothing attached. The card now renders with the agent's own thumbnail, falls back to a freshly rendered portrait when an agent has no thumbnail yet, and an unknown or malformed agent link sends the visitor to the app instead of erroring.",
+ "tags": [
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-08-16",
+ "title": "The sniper's laddered-exit settings can finally be saved",
+ "summary": "An armed sniper strategy has two knobs that decide how a winner is taken off the table: the multiple of your entry at which it sells enough to recover what you put in, and the minimum slice of the position it always keeps riding afterwards. Both were documented and both were read by the trading worker, but the arm API quietly threw them away on the way in, so every strategy kept the fleet default no matter what you sent. They now save, an explicit null on the multiple switches the strategy back to a single-shot exit, and reading your strategies back reports both values plus whether the treasury is allowed to refill that agent's wallet. Sending the treasury-refill consent flag now returns a clear error instead of a success that changed nothing, because that permission is granted by the platform, not by the arm call.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/dashboard/sniper"
+ },
{
"date": "2026-08-16",
"title": "The public profile sitemap now lists people, not the seed crons",
@@ -10,6 +28,34 @@
"infra"
]
},
+ {
+ "date": "2026-08-16",
+ "title": "Live stage hosts stop swallowing hyphens, and only confirmed tippers get greeted by name",
+ "summary": "Two repairs to the Living Stages host. The cleanup pass that tidies the host's spoken line was stripping hyphens along with the invisible characters it was meant to remove, so every show heard \"on chain\" where the host said \"on-chain\" and \"state of the art\" for \"state-of-the-art\"; punctuation now survives and only invisible characters are removed. Separately, the host's memory of returning regulars counted tips whose on-chain settlement had not been confirmed yet, which meant anyone could post an unconfirmed tip under a name of their choosing and hear the host greet it aloud. That memory now reads confirmed tips only, matching the public leaderboard. Smaller repairs in the same pass: a stage that has not opened its first show is no longer cached as empty at the edge, an over-long coin address is refused instead of quietly trimmed into a different plaza, and the running tip total is written before the response returns.",
+ "tags": [
+ "fix",
+ "security"
+ ],
+ "link": "/stage"
+ },
+ {
+ "date": "2026-08-16",
+ "title": "The $THREE economy dashboard no longer errors out on an odd date range",
+ "summary": "Asking the public $THREE economy stats endpoint for a window it could not read (a non-numeric range, or one longer than ten years) returned a server error instead of an answer. It now replies with a clear message for a range it cannot parse, caps an oversized one at ten years of history, and treats a blank range as all-time again. The creator earnings ledger does the same for a bad page cursor.",
+ "tags": [
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-08-16",
+ "title": "Token-gated scene shares survive a slow RPC, and a gate that could never open is refused up front",
+ "summary": "Three repairs to the holder-only chat scene shares. When the blockchain read behind a gate failed (a provider down, a missing provider key), visitors were told they did not hold enough tokens, which was untrue and also handed the provider's raw error text to anyone who asked; a failed read now says plainly that verification is unavailable and invites a retry, while a genuine shortfall still says exactly how much is missing. The Solana read itself now rotates through the same pool of providers the rest of the platform uses instead of leaning on one endpoint, NFT collection gates use the indexer that can actually answer them, and gates on Ethereum work without a paid provider key. Finally, a gate whose chain and asset type did not match (a Solana scene gated on an Ethereum token) used to be accepted and then locked everyone out forever; that combination, and an address in the wrong format for its chain, are now refused when the share link is created.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/chat"
+ },
{
"date": "2026-08-16",
"title": "Trending: muted text on the board is readable, and the Tip button that only navigated is gone",
diff --git a/prompts/swarm-100/api-scene-01.md b/prompts/swarm-100/api-scene-01.md
deleted file mode 100644
index 31559c40c..000000000
--- a/prompts/swarm-100/api-scene-01.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# API audit: api/scene batch 01 (2 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/scene/gate-check.js
-- api/scene/gate-create.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-scene-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/prompts/swarm-100/api-stage-01.md b/prompts/swarm-100/api-stage-01.md
deleted file mode 100644
index facb4e23c..000000000
--- a/prompts/swarm-100/api-stage-01.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# API audit: api/stage batch 01 (3 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/stage/host.js
-- api/stage/index.js
-- api/stage/tip.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-stage-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/prompts/swarm-100/api-three-01.md b/prompts/swarm-100/api-three-01.md
deleted file mode 100644
index 923ce57c0..000000000
--- a/prompts/swarm-100/api-three-01.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# API audit: api/three batch 01 (1 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/three/[action].js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-three-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/public/changelog.json b/public/changelog.json
index 5c72708ba..7e1ecf4ac 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,75 @@
{
- "generated_at": "2026-08-16T06:15:48.775Z",
+ "generated_at": "2026-08-16T06:40:46.743Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-08-16",
+ "type": "update",
+ "title": "Live stage hosts stop swallowing hyphens, and only confirmed tippers get greeted by name",
+ "summary": "Two repairs to the Living Stages host. The cleanup pass that tidies the host's spoken line was stripping hyphens along with the invisible characters it was meant to remove, so every show heard \"on chain\" where the host said \"on-chain\" and \"state of the art\" for \"state-of-the-art\"; punctuation now survives and only invisible characters are removed. Separately, the host's memory of returning regulars counted tips whose on-chain settlement had not been confirmed yet, which meant anyone could post an unconfirmed tip under a name of their choosing and hear the host greet it aloud. That memory now reads confirmed tips only, matching the public leaderboard. Smaller repairs in the same pass: a stage that has not opened its first show is no longer cached as empty at the edge, an over-long coin address is refused instead of quietly trimmed into a different plaza, and the running tip total is written before the response returns.",
+ "link": "/stage",
+ "tags": [
+ "fix",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-08-16",
+ "type": "update",
+ "title": "Sharing an agent link posts the agent's picture again",
+ "summary": "Pasting a link to an agent into a chat app, a social post or a group thread is supposed to unfurl into a card with the agent's name, its description and a picture of it. For every agent that actually has an avatar picture, which is nearly all of them, the page that builds that card was crashing instead, so the link unfurled as a bare URL with nothing attached. The card now renders with the agent's own thumbnail, falls back to a freshly rendered portrait when an agent has no thumbnail yet, and an unknown or malformed agent link sends the visitor to the app instead of erroring.",
+ "link": null,
+ "tags": [
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-08-16",
+ "type": "update",
+ "title": "The $THREE economy dashboard no longer errors out on an odd date range",
+ "summary": "Asking the public $THREE economy stats endpoint for a window it could not read (a non-numeric range, or one longer than ten years) returned a server error instead of an answer. It now replies with a clear message for a range it cannot parse, caps an oversized one at ten years of history, and treats a blank range as all-time again. The creator earnings ledger does the same for a bad page cursor.",
+ "link": null,
+ "tags": [
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-08-16",
+ "type": "update",
+ "title": "The public profile sitemap now lists people, not the seed crons",
+ "summary": "The sitemap Google and Bing crawl is split into one file per kind of page, and the profiles file was handing search engines every account row with a username. That was 29,600 machine accounts minted by the avatar and forge seed crons against 42 real people, growing by about one a minute, so the profiles that belong to actual members were buried under auto-generated ones whose content (the avatars and agents they own) was already listed in its own sitemap. Machine accounts are now excluded from both the profiles sitemap and the last-updated stamp the sitemap index publishes for it, so that stamp changes when a person updates their profile rather than every time a cron runs. Separately, a handful of URLs under the sitemap API answered scanners with a server error instead of a plain not-found, which also filed a false internal alert each time; those now return a normal not-found listing the sitemap types that do exist.",
+ "link": null,
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-08-16",
+ "type": "update",
+ "title": "The sniper's laddered-exit settings can finally be saved",
+ "summary": "An armed sniper strategy has two knobs that decide how a winner is taken off the table: the multiple of your entry at which it sells enough to recover what you put in, and the minimum slice of the position it always keeps riding afterwards. Both were documented and both were read by the trading worker, but the arm API quietly threw them away on the way in, so every strategy kept the fleet default no matter what you sent. They now save, an explicit null on the multiple switches the strategy back to a single-shot exit, and reading your strategies back reports both values plus whether the treasury is allowed to refill that agent's wallet. Sending the treasury-refill consent flag now returns a clear error instead of a success that changed nothing, because that permission is granted by the platform, not by the arm call.",
+ "link": "/dashboard/sniper",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-08-16",
+ "type": "update",
+ "title": "Token-gated scene shares survive a slow RPC, and a gate that could never open is refused up front",
+ "summary": "Three repairs to the holder-only chat scene shares. When the blockchain read behind a gate failed (a provider down, a missing provider key), visitors were told they did not hold enough tokens, which was untrue and also handed the provider's raw error text to anyone who asked; a failed read now says plainly that verification is unavailable and invites a retry, while a genuine shortfall still says exactly how much is missing. The Solana read itself now rotates through the same pool of providers the rest of the platform uses instead of leaning on one endpoint, NFT collection gates use the indexer that can actually answer them, and gates on Ethereum work without a paid provider key. Finally, a gate whose chain and asset type did not match (a Solana scene gated on an Ethereum token) used to be accepted and then locked everyone out forever; that combination, and an address in the wrong format for its chain, are now refused when the share link is created.",
+ "link": "/chat",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-08-16",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 79d30361f..d8b921f87 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,54 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws: features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Live stage hosts stop swallowing hyphens, and only confirmed tippers get greeted by name</title>
+ <link>https://three.ws/stage</link>
+ <guid isPermaLink="false">2026-08-16:Live stage hosts stop swallowing hyphens, and only confirmed tippers get greeted by name</guid>
+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Two repairs to the Living Stages host. The cleanup pass that tidies the host's spoken line was stripping hyphens along with the invisible characters it was meant to remove, so every show heard &quot;on chain&quot; where the host said &quot;on-chain&quot; and &quot;state of the art&quot; for &quot;state-of-the-art&quot;; punctuation now survives and only invisible characters are removed. Separately, the host's memory of returning regulars counted tips whose on-chain settlement had not been confirmed yet, which meant anyone could post an unconfirmed tip under a name of their choosing and hear the host greet it aloud. That memory now reads confirmed tips only, matching the public leaderboard. Smaller repairs in the same pass: a stage that has not opened its first show is no longer cached as empty at the edge, an over-long coin address is refused instead of quietly trimmed into a different plaza, and the running tip total is written before the response returns.</description>
+ </item>
+ <item>
+ <title>Sharing an agent link posts the agent's picture again</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-08-16:Sharing an agent link posts the agent's picture again</guid>
+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Pasting a link to an agent into a chat app, a social post or a group thread is supposed to unfurl into a card with the agent's name, its description and a picture of it. For every agent that actually has an avatar picture, which is nearly all of them, the page that builds that card was crashing instead, so the link unfurled as a bare URL with nothing attached. The card now renders with the agent's own thumbnail, falls back to a freshly rendered portrait when an agent has no thumbnail yet, and an unknown or malformed agent link sends the visitor to the app instead of erroring.</description>
+ </item>
+ <item>
+ <title>The $THREE economy dashboard no longer errors out on an odd date range</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-08-16:The $THREE economy dashboard no longer errors out on an odd date range</guid>
+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Asking the public $THREE economy stats endpoint for a window it could not read (a non-numeric range, or one longer than ten years) returned a server error instead of an answer. It now replies with a clear message for a range it cannot parse, caps an oversized one at ten years of history, and treats a blank range as all-time again. The creator earnings ledger does the same for a bad page cursor.</description>
+ </item>
+ <item>
+ <title>The public profile sitemap now lists people, not the seed crons</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-08-16:The public profile sitemap now lists people, not the seed crons</guid>
+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The sitemap Google and Bing crawl is split into one file per kind of page, and the profiles file was handing search engines every account row with a username. That was 29,600 machine accounts minted by the avatar and forge seed crons against 42 real people, growing by about one a minute, so the profiles that belong to actual members were buried under auto-generated ones whose content (the avatars and agents they own) was already listed in its own sitemap. Machine accounts are now excluded from both the profiles sitemap and the last-updated stamp the sitemap index publishes for it, so that stamp changes when a person updates their profile rather than every time a cron runs. Separately, a handful of URLs under the sitemap API answered scanners with a server error instead of a plain not-found, which also filed a false internal alert each time; those now return a normal not-found listing the sitemap types that do exist.</description>
+ </item>
+ <item>
+ <title>The sniper's laddered-exit settings can finally be saved</title>
+ <link>https://three.ws/dashboard/sniper</link>
+ <guid isPermaLink="false">2026-08-16:The sniper's laddered-exit settings can finally be saved</guid>
+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>An armed sniper strategy has two knobs that decide how a winner is taken off the table: the multiple of your entry at which it sells enough to recover what you put in, and the minimum slice of the position it always keeps riding afterwards. Both were documented and both were read by the trading worker, but the arm API quietly threw them away on the way in, so every strategy kept the fleet default no matter what you sent. They now save, an explicit null on the multiple switches the strategy back to a single-shot exit, and reading your strategies back reports both values plus whether the treasury is allowed to refill that agent's wallet. Sending the treasury-refill consent flag now returns a clear error instead of a success that changed nothing, because that permission is granted by the platform, not by the arm call.</description>
+ </item>
+ <item>
+ <title>Token-gated scene shares survive a slow RPC, and a gate that could never open is refused up front</title>
+ <link>https://three.ws/chat</link>
+ <guid isPermaLink="false">2026-08-16:Token-gated scene shares survive a slow RPC, and a gate that could never open is refused up front</guid>
+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Three repairs to the holder-only chat scene shares. When the blockchain read behind a gate failed (a provider down, a missing provider key), visitors were told they did not hold enough tokens, which was untrue and also handed the provider's raw error text to anyone who asked; a failed read now says plainly that verification is unavailable and invites a retry, while a genuine shortfall still says exactly how much is missing. The Solana read itself now rotates through the same pool of providers the rest of the platform uses instead of leaning on one endpoint, NFT collection gates use the indexer that can actually answer them, and gates on Ethereum work without a paid provider key. Finally, a gate whose chain and asset type did not match (a Solana scene gated on an Ethereum token) used to be accepted and then locked everyone out forever; that combination, and an address in the wrong format for its chain, are now refused when the share link is created.</description>
+ </item>
<item>
<title>Trending: muted text on the board is readable, and the Tip button that only navigated is gone</title>
<link>https://three.ws/trending</link>
diff --git a/public/features.json b/public/features.json
index dfaea8e8c..d343c95cd 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-16T06:15:48.675Z",
+ "generated_at": "2026-08-16T06:38:50.055Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/api/scene-gate.test.js b/tests/api/scene-gate.test.js
new file mode 100644
index 000000000..7bd4d8e52
--- /dev/null
+++ b/tests/api/scene-gate.test.js
@@ -0,0 +1,456 @@
+// Tests for the token-gated scene share pair: POST /api/scene/gate-create (the
+// creator turning a scene into a holder-only share) and POST /api/scene/gate-check
+// (the visitor proving the holding). Together they are the security boundary of a
+// gated scene, so what is pinned here is every way the proof can be forged or
+// replayed, plus the two failure modes that used to be indistinguishable:
+//
+// - a gate stored with a chain/kind pair that can never verify (solana/erc20),
+// which produced a share link that denied everyone forever;
+// - an RPC outage answering the visitor with "insufficient balance", which both
+// lied and leaked the upstream error text to an unauthenticated caller.
+//
+// The Solana signatures are real ed25519 signatures from a real keypair and the
+// EVM ones are real personal_sign signatures from a real ethers wallet, verified
+// by the real api/_lib/siws.js and ethers. Only the database rows and the chain
+// reads are stubbed: there is no Postgres in a unit test, and hitting mainnet from
+// the suite would make it slow and flaky. The stubbed balance is exactly the value
+// a real RPC read returns, which is the input the gate decision is defined over.
+
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+import { ed25519 } from '@noble/curves/ed25519.js';
+import bs58 from 'bs58';
+import { Wallet, AbiCoder } from 'ethers';
+
+beforeAll(() => {
+ process.env.JWT_SECRET = 'test-jwt-secret-scene-gate-0123456789';
+ process.env.APP_ORIGIN = 'https://three.ws';
+});
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const getSessionUserMock = vi.fn();
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+ hasScope: vi.fn(() => true),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: true, limit: 30, remaining: 29, reset: 0 })),
+ sceneGateCheckIp: vi.fn(async () => ({ success: true, limit: 30, remaining: 29, reset: 0 })),
+ sceneGateCheckWallet: vi.fn(async () => ({ success: true, limit: 10, remaining: 9, reset: 0 })),
+ },
+ clientIp: () => '203.0.113.21',
+}));
+
+const splBalanceMock = vi.fn();
+vi.mock('../../api/_lib/embed-gate.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, getSplTokenBalance: (...a) => splBalanceMock(...a) };
+});
+
+const dasRpcUrlMock = vi.fn(() => 'https://mainnet.helius-rpc.com/?api-key=test');
+const dasSearchAssetsMock = vi.fn();
+vi.mock('../../api/_lib/nft-gate.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ dasRpcUrl: (...a) => dasRpcUrlMock(...a),
+ dasSearchAssets: (...a) => dasSearchAssetsMock(...a),
+ };
+});
+
+const evmCallMock = vi.fn();
+vi.mock('../../api/_lib/evm/rpc.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, evmFallbackProvider: async () => ({ call: (...a) => evmCallMock(...a) }) };
+});
+
+const createHandler = (await import('../../api/scene/gate-create.js')).default;
+const checkHandler = (await import('../../api/scene/gate-check.js')).default;
+
+// A real keypair: the wallet address IS the public key, so a signature that
+// verifies here is one a Solana wallet could have produced.
+const SECRET = ed25519.utils.randomSecretKey();
+const WALLET = bs58.encode(ed25519.getPublicKey(SECRET));
+const OTHER_SECRET = ed25519.utils.randomSecretKey();
+
+const EVM_WALLET = Wallet.createRandom();
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const COLLECTION = 'THREEsynthetic1111111111111111111111111111';
+const ERC20 = '0x1111111111111111111111111111111111111111';
+const GATE_ID = 'g1h2i3j4k5l6';
+const NONCE = 'A1b2C3d4E5f6G7h8';
+
+const solanaGate = { id: GATE_ID, chain: 'solana', kind: 'spl', address: MINT, min_balance: '5000' };
+
+function gateMessage(wallet, nonce = NONCE, gateId = GATE_ID) {
+ return [
+ 'three.ws scene gate verification.',
+ '',
+ `Gate ID: ${gateId}`,
+ `Wallet: ${wallet}`,
+ `Nonce: ${nonce}`,
+ 'Issued At: 2026-08-16T00:00:00.000Z',
+ ].join('\n');
+}
+
+function signSolana(message, secret = SECRET) {
+ return bs58.encode(ed25519.sign(new TextEncoder().encode(message), secret));
+}
+
+function nonceRow(overrides = {}) {
+ return {
+ nonce: NONCE,
+ gate_id: GATE_ID,
+ address: WALLET,
+ expires_at: new Date(Date.now() + 60_000).toISOString(),
+ consumed_at: null,
+ ...overrides,
+ };
+}
+
+/** The two handlers read scene_gates and gate_nonces; both are stubbed by the
+ * statement text so a query the code did not make cannot silently pass. */
+function stubDb({ gate = solanaGate, nonce = nonceRow(), burned = [{ nonce: NONCE }] } = {}) {
+ sqlMock.mockImplementation((strings) => {
+ const text = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/insert into scene_gates/i.test(text)) return Promise.resolve([]);
+ if (/insert into gate_nonces/i.test(text)) return Promise.resolve([]);
+ if (/update gate_nonces/i.test(text)) return Promise.resolve(burned);
+ if (/from gate_nonces/i.test(text)) return Promise.resolve(nonce ? [nonce] : []);
+ if (/from scene_gates/i.test(text)) return Promise.resolve(gate ? [gate] : []);
+ return Promise.resolve([]);
+ });
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk) this.body += chunk;
+ },
+ };
+}
+
+async function post(handler, url, body) {
+ const req = {
+ method: 'POST',
+ url,
+ headers: { 'content-type': 'application/json' },
+ rawBody: Buffer.from(JSON.stringify(body)),
+ body,
+ on(event, cb) {
+ if (event === 'data') {
+ queueMicrotask(() => {
+ cb(Buffer.from(JSON.stringify(body)));
+ this._endCb?.();
+ });
+ } else if (event === 'end') {
+ this._endCb = cb;
+ }
+ },
+ destroy() {},
+ };
+ const res = mkRes();
+ await handler(req, res);
+ return { res, json: res.body ? JSON.parse(res.body) : null };
+}
+
+const create = (body) => post(createHandler, '/api/scene/gate-create', body);
+const check = (body) => post(checkHandler, '/api/scene/gate-check', body);
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ getSessionUserMock.mockReset();
+ splBalanceMock.mockReset();
+ dasSearchAssetsMock.mockReset();
+ evmCallMock.mockReset();
+ dasRpcUrlMock.mockReturnValue('https://mainnet.helius-rpc.com/?api-key=test');
+});
+
+describe('POST /api/scene/gate-create', () => {
+ it('401s a caller with no session and no bearer token', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ stubDb();
+ const { res, json } = await create({
+ sceneRef: 'abc123',
+ gate: { chain: 'solana', kind: 'spl', address: MINT, minBalance: 1 },
+ });
+
+ expect(res.statusCode).toBe(401);
+ expect(json.error).toBe('unauthorized');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('creates the gate and returns a share URL carrying the gate id', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'user_creator_1' });
+ stubDb();
+ const { res, json } = await create({
+ sceneRef: 'abc123',
+ gate: { chain: 'solana', kind: 'spl', address: MINT, minBalance: 2500 },
+ });
+
+ expect(res.statusCode).toBe(201);
+ expect(json.gateId).toMatch(/^[A-Za-z0-9]{12}$/);
+ expect(json.shareUrl).toBe(`https://three.ws/chat?sl=abc123&gate=${json.gateId}`);
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+
+ it('encodes a long inline scene blob into the ?s= form instead of ?sl=', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'user_creator_1' });
+ stubDb();
+ const blob = 'x'.repeat(64);
+ const { json } = await create({
+ sceneRef: blob,
+ gate: { chain: 'evm', kind: 'erc20', address: ERC20, minBalance: 1 },
+ });
+
+ expect(json.shareUrl).toBe(`https://three.ws/chat?s=${blob}&gate=${json.gateId}`);
+ });
+
+ it('rejects a chain/kind pair that could never verify', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'user_creator_1' });
+ stubDb();
+ const { res, json } = await create({
+ sceneRef: 'abc123',
+ gate: { chain: 'solana', kind: 'erc20', address: MINT, minBalance: 1 },
+ });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('validation_error');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects an address that is not valid for the gate chain', async () => {
+ getSessionUserMock.mockResolvedValue({ id: 'user_creator_1' });
+ stubDb();
+ const { res, json } = await create({
+ sceneRef: 'abc123',
+ gate: { chain: 'evm', kind: 'erc20', address: MINT, minBalance: 1 },
+ });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('validation_error');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/scene/gate-check phase 1', () => {
+ it('issues a signable message carrying a fresh nonce', async () => {
+ stubDb();
+ const { res, json } = await check({ gateId: GATE_ID, walletAddress: WALLET });
+
+ expect(res.statusCode).toBe(200);
+ expect(json.chain).toBe('solana');
+ expect(json.message).toContain(`Gate ID: ${GATE_ID}`);
+ expect(json.message).toMatch(/^Nonce: [A-Za-z0-9]{16}$/m);
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+
+ it('404s an unknown gate without writing a nonce', async () => {
+ stubDb({ gate: null });
+ const { res, json } = await check({ gateId: 'nosuchgate', walletAddress: WALLET });
+
+ expect(res.statusCode).toBe(404);
+ expect(json.error).toBe('not_found');
+ const statements = sqlMock.mock.calls.map(([s]) => s.join(' '));
+ expect(statements.some((s) => /insert into gate_nonces/i.test(s))).toBe(false);
+ });
+
+ it('400s a wallet address the gate chain cannot verify', async () => {
+ stubDb();
+ const { res, json } = await check({ gateId: GATE_ID, walletAddress: EVM_WALLET.address });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('validation_error');
+ });
+});
+
+describe('POST /api/scene/gate-check phase 2 signature and nonce rules', () => {
+ it('401s a signature from a different wallet', async () => {
+ stubDb();
+ const message = gateMessage(WALLET);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: WALLET,
+ message,
+ signature: signSolana(message, OTHER_SECRET),
+ });
+
+ expect(res.statusCode).toBe(401);
+ expect(json.error).toBe('invalid_signature');
+ expect(splBalanceMock).not.toHaveBeenCalled();
+ });
+
+ it('400s a replayed nonce', async () => {
+ stubDb({ nonce: nonceRow({ consumed_at: new Date().toISOString() }) });
+ const message = gateMessage(WALLET);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: WALLET,
+ message,
+ signature: signSolana(message),
+ });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('nonce_reused');
+ expect(splBalanceMock).not.toHaveBeenCalled();
+ });
+
+ it('400s an expired nonce', async () => {
+ stubDb({ nonce: nonceRow({ expires_at: new Date(Date.now() - 1000).toISOString() }) });
+ const message = gateMessage(WALLET);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: WALLET,
+ message,
+ signature: signSolana(message),
+ });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('nonce_expired');
+ });
+
+ it('400s a nonce issued for a different gate', async () => {
+ stubDb({ nonce: nonceRow({ gate_id: 'someothergate' }) });
+ const message = gateMessage(WALLET);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: WALLET,
+ message,
+ signature: signSolana(message),
+ });
+
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('invalid_nonce');
+ });
+});
+
+describe('POST /api/scene/gate-check phase 2 balance decision', () => {
+ it('allows a wallet holding at least the minimum SPL balance', async () => {
+ stubDb();
+ splBalanceMock.mockResolvedValue(6000);
+ const message = gateMessage(WALLET);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: WALLET,
+ message,
+ signature: signSolana(message),
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(json).toEqual({ allowed: true });
+ expect(splBalanceMock).toHaveBeenCalledWith(WALLET, MINT);
+ });
+
+ it('denies a wallet below the minimum and says by how much', async () => {
+ stubDb();
+ splBalanceMock.mockResolvedValue(12);
+ const message = gateMessage(WALLET);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: WALLET,
+ message,
+ signature: signSolana(message),
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(json.allowed).toBe(false);
+ expect(json.reason).toBe('Insufficient balance: need 5000, have 12');
+ });
+
+ it('counts collection NFTs only as far as the threshold', async () => {
+ stubDb({ gate: { id: GATE_ID, chain: 'solana', kind: 'collection', address: COLLECTION, min_balance: '2' } });
+ dasSearchAssetsMock.mockResolvedValue({ items: [{ id: 'a' }, { id: 'b' }, { id: 'c' }] });
+ const message = gateMessage(WALLET);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: WALLET,
+ message,
+ signature: signSolana(message),
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(json).toEqual({ allowed: true });
+ expect(dasSearchAssetsMock).toHaveBeenCalledTimes(1);
+ expect(dasSearchAssetsMock.mock.calls[0][0]).toMatchObject({
+ ownerAddress: WALLET,
+ grouping: ['collection', COLLECTION],
+ burnt: false,
+ });
+ });
+
+ it('reads an ERC-20 balance at the contract decimals', async () => {
+ stubDb({
+ gate: { id: GATE_ID, chain: 'evm', kind: 'erc20', address: ERC20, min_balance: '10' },
+ nonce: nonceRow({ address: EVM_WALLET.address }),
+ });
+ const coder = AbiCoder.defaultAbiCoder();
+ evmCallMock.mockImplementation(async (tx) =>
+ tx.data.startsWith('0x313ce567')
+ ? coder.encode(['uint8'], [6])
+ : coder.encode(['uint256'], [25_000_000n]),
+ );
+ const message = gateMessage(EVM_WALLET.address);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: EVM_WALLET.address,
+ message,
+ signature: await EVM_WALLET.signMessage(message),
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(json).toEqual({ allowed: true });
+ });
+
+ it('502s an RPC failure instead of reporting it as a denial', async () => {
+ stubDb();
+ splBalanceMock.mockRejectedValue(new Error('all solana rpc endpoints failed'));
+ const message = gateMessage(WALLET);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: WALLET,
+ message,
+ signature: signSolana(message),
+ });
+
+ expect(res.statusCode).toBe(502);
+ expect(json.error).toBe('gate_check_unavailable');
+ expect(json.error_description).not.toContain('solana rpc');
+ expect(json.allowed).toBeUndefined();
+ });
+
+ it('503s a collection gate when no DAS provider is configured', async () => {
+ stubDb({ gate: { id: GATE_ID, chain: 'solana', kind: 'collection', address: COLLECTION, min_balance: '1' } });
+ dasRpcUrlMock.mockReturnValue(null);
+ const message = gateMessage(WALLET);
+ const { res, json } = await check({
+ gateId: GATE_ID,
+ walletAddress: WALLET,
+ message,
+ signature: signSolana(message),
+ });
+
+ expect(res.statusCode).toBe(503);
+ expect(json.error).toBe('not_configured');
+ expect(json.error_description).not.toContain('HELIUS_API_KEY');
+ expect(dasSearchAssetsMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/stage-host-line.test.js b/tests/stage-host-line.test.js
new file mode 100644
index 000000000..a438a4faa
--- /dev/null
+++ b/tests/stage-host-line.test.js
@@ -0,0 +1,161 @@
+// The Living Stages host brain speaks whatever this endpoint returns
+// (api/stage/host.js), so what it does to the model's words IS the product.
+//
+// Two properties are pinned here because both failed silently in production:
+//
+// 1. sanitizeLine strips CONTROL characters, not punctuation. The class was
+// once written with literal characters, which collapsed to the printable
+// range [space-hyphen] and ate every hyphen in the spoken line: the host
+// said "on chain" for "on-chain", every show, with nothing in the logs.
+// 2. the "returning regulars" recall reads VERIFIED tips only. A tip row is
+// created from a caller-asserted settlement and stays quarantined until the
+// chain confirms it, so counting unverified rows would let anyone put a
+// name of their choosing into the host's system prompt and hear it spoken
+// to the room.
+import { test, expect, vi, beforeEach } from 'vitest';
+
+let sqlHandler = () => [];
+const seenQueries = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ const text = strings.join('?');
+ seenQueries.push(text);
+ return Promise.resolve(sqlHandler(text, values));
+ },
+}));
+
+class FakeUnavailable extends Error {}
+let llmResult = async () => ({ text: 'ok' });
+vi.mock('../api/_lib/llm.js', () => ({
+ llmComplete: (...args) => llmResult(...args),
+ LlmUnavailableError: FakeUnavailable,
+}));
+
+let authorized = true;
+vi.mock('../api/_lib/stage-bridge.js', () => ({
+ verifyStageRequest: async () => authorized,
+}));
+
+const mod = await import('../api/stage/host.js');
+const handler = mod.default;
+const { sanitizeLine } = mod;
+
+const STAGE_ID = '2e90fbb9-347c-42d5-9162-c8dc7cb7ad04';
+
+function makeReq(body) {
+ return {
+ method: 'POST',
+ url: '/api/stage/host',
+ headers: { 'content-type': 'application/json' },
+ query: {},
+ body,
+ // readJson() takes the pre-parsed body when the server already has one.
+ on() {},
+ };
+}
+
+function makeRes() {
+ const res = {
+ statusCode: 0,
+ body: null,
+ headers: {},
+ headersSent: false,
+ setHeader(k, v) {
+ this.headers[String(k).toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[String(k).toLowerCase()];
+ },
+ end(payload) {
+ this.headersSent = true;
+ if (typeof payload === 'string') {
+ try {
+ this.body = JSON.parse(payload);
+ } catch {
+ this.body = payload;
+ }
+ }
+ return this;
+ },
+ };
+ return res;
+}
+
+function stageRow() {
+ return [{ agent_id: 'a1', title: 'Test Set', format: 'open mic', agent_name: 'Nova', persona_prompt: null, description: null }];
+}
+
+beforeEach(() => {
+ seenQueries.length = 0;
+ authorized = true;
+ llmResult = async () => ({ text: 'ok' });
+ sqlHandler = (text) => (text.includes('FROM stages s') ? stageRow() : []);
+});
+
+test('a hyphenated spoken line survives sanitizing intact', () => {
+ expect(sanitizeLine('Make your on-chain mark, state-of-the-art style.')).toBe(
+ 'Make your on-chain mark, state-of-the-art style.',
+ );
+});
+
+test('control characters are stripped and runs of whitespace collapse', () => {
+ const dirty = `one\u0000two\u001fthree\u007ffour five`;
+ expect(sanitizeLine(dirty)).toBe('one two three four five');
+});
+
+test('an em dash from the model never reaches the captions', () => {
+ expect(sanitizeLine('you are the future\u2014this is on-chain')).toBe('you are the future, this is on-chain');
+});
+
+test('surrounding quotes and a leaked speaker label are removed, length is bounded', () => {
+ expect(sanitizeLine('"Host: welcome in, friends"')).toBe('welcome in, friends');
+ expect(sanitizeLine('x'.repeat(600))).toHaveLength(400);
+ expect(sanitizeLine(null)).toBe('');
+});
+
+test('a signed request returns the host line plus the beat cue', async () => {
+ llmResult = async () => ({ text: '"Host: welcome to the on-chain show"' });
+ const res = makeRes();
+ await handler(makeReq({ stageId: STAGE_ID, beat: 'opener', context: { audience: 7 } }), res);
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual({ text: 'welcome to the on-chain show', cue: 'cheer' });
+});
+
+test('the regulars recall counts verified tips only', async () => {
+ const res = makeRes();
+ await handler(makeReq({ stageId: STAGE_ID, beat: 'banter' }), res);
+ const tipQuery = seenQueries.find((q) => q.includes('FROM show_tips'));
+ expect(tipQuery).toBeTruthy();
+ expect(tipQuery).toContain('verified_at IS NOT NULL');
+});
+
+test('an unsigned request never reaches the model', async () => {
+ authorized = false;
+ let called = false;
+ llmResult = async () => {
+ called = true;
+ return { text: 'should not happen' };
+ };
+ const res = makeRes();
+ await handler(makeReq({ stageId: STAGE_ID, beat: 'banter' }), res);
+ expect(res.statusCode).toBe(401);
+ expect(res.body).toEqual({ error: 'unauthorized' });
+ expect(called).toBe(false);
+});
+
+test('a stage that does not exist is a 404, not a model call', async () => {
+ sqlHandler = () => [];
+ const res = makeRes();
+ await handler(makeReq({ stageId: STAGE_ID, beat: 'banter' }), res);
+ expect(res.statusCode).toBe(404);
+});
+
+test('an exhausted LLM chain surfaces as 503 so the room uses its failsafe line', async () => {
+ llmResult = async () => {
+ throw new FakeUnavailable('no providers');
+ };
+ const res = makeRes();
+ await handler(makeReq({ stageId: STAGE_ID, beat: 'banter' }), res);
+ expect(res.statusCode).toBe(503);
+ expect(res.body).toEqual({ error: 'host_brain_unavailable' });
+});
diff --git a/workers/robinhood-feed/README.md b/workers/robinhood-feed/README.md
index 23edecbd8..9ca77e7aa 100644
--- a/workers/robinhood-feed/README.md
+++ b/workers/robinhood-feed/README.md
@@ -20,6 +20,29 @@ coins — see `api/robinhood/coin-trades.js` and `api/robinhood/play-worlds.js`,
which proxy it into the exact contract `src/game/chart-screen.js` (the in-world
trading terminal) already polls.
+### What the two API bridges guarantee their callers
+
+The terminal re-polls `/api/robinhood/coin-trades` every 5 seconds and the
+`/worlds` lobby swallows any non-2xx from `/api/robinhood/play-worlds`, so a
+single bad event in `/recent` must never become a 5xx. Both bridges therefore
+treat this worker as untrusted input:
+
+- An event with a missing or non-object `data` payload is skipped, and the rest
+ of the snapshot still renders.
+- A `timestamp` that is not a positive number is served as `null`, which
+ `chart-screen.js` already reads as "now", instead of an invalid date.
+- A missing `price_usd` / `usd_amount` stays `null` rather than becoming a real
+ `0` print on the chart.
+- A launch whose `mint` is not a `0x`-prefixed 40-hex address is dropped, since
+ its lobby card would seed a world from nothing.
+- An unreachable or non-2xx worker yields an empty list with
+ `configured: false`, never invented trades or worlds.
+
+Caller input is validated separately: `coin-trades` answers `400
+{"error":"invalid_mint"}` for an address that is not an EVM contract address,
+so a client bug cannot read as "this coin has never traded".
+`tests/api/robinhood-play-endpoints.test.js` pins all of the above.
+
## Architecture
| File | Role |