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
fix(solana-crawl): rotate the RPC lane for getProgramAccounts and split the v1/v2 identity scans
nirholase23e1b2ff0eb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d85029b7e..72cec9ca1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,10 +7,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-08-16- **A coin world link now unfurls as the live world, and only ever points at three.ws**: Pasting a coin community link into WordPress, Ghost, Discord, Notion or any editor built on embed.ly or iframely now turns it into the live 3D world instead of a plain link. The service that answers those editors existed but nothing on the page told them where to find it, so it was never called. Two problems in that service are fixed at the same time. It used to build the embed from the address in the incoming request rather than from the site address, so a crafted request could hand an editor an embed that framed somebody else site under the three.ws name; the embed is now always built from three.ws itself. And it used to answer for any link at all, returning a generic three.ws world card for a link that was never ours; it now says plainly that the link is not one of ours. It also answers in both of the formats the standard defines, and ignores a coin address that is not a real Solana address instead of putting it in the embed. Separately, the share images for pages and coin worlds, the holder leaderboard card, the free model verification check and the Oracle coin page now accept only read requests, and answer anything else with a clear message rather than doing the work anyway. (`/play`) `[fix, security]`+- **A GitHub seed that stores nothing no longer costs you six hours**: Seeding an agent from your GitHub profile, repositories and READMEs is allowed once every six hours per agent. Two failures used to spend that window without storing a single fact. The first is entirely ours: when every model provider is busy at once, nothing is read and nothing is written, and you were still locked out for six hours over an outage you did not cause. The second is the run that comes back with no usable facts, which tells you to add a README or another repository, advice you could not act on until the window expired. Both now hand the window straight back, so you can try again as soon as a provider frees up or as soon as you have widened your selection, and the reply says which of the two happened. Nothing else changes: your existing memories are untouched by a failed run, the seed still reads only the profile, repositories and READMEs you ticked, and disconnecting GitHub still deletes every fact it wrote across all your agents. (`/docs/github-memory-seeding`) `[improvement, fix]`- **A mistyped id on the signal marketplace answers plainly, and the live feed links to the right chain**: The signal marketplace identifies a feed or a subscription by a number. Anything that was not one (a typo, a stray word, an empty box) went straight to the database, which threw the whole query out, so the caller got an opaque "something went wrong" and our alerting recorded a fault that was never a fault. Pausing a feed, killing or resyncing a subscription, and subscribing to a feed each now answer with a plain "that is not a valid id" instead. Separately, the paid live signal stream built its Solscan links from whichever network the request named rather than the one the feed actually publishes on, so a subscriber could be handed devnet explorer links for a mainnet call; the feed's own record now decides, and every proof link lands on the chain the trade really happened on. (`/signals`) `[fix]`- **Agent attestations that stopped indexing now recover on their own**: An agent's on-chain attestation history is indexed by walking Solana signatures newer than the last one we recorded. If that recorded signature aged out of the RPC node's history, the walk failed outright and kept failing: the same dead signature was replayed on every run, so that agent's attestations silently stopped appearing on its profile while the scheduled job still reported success. The crawler now recognises that case, re-scans from the most recent signatures instead, and clears the stale marker, so an agent that fell behind catches up by itself on the next pass. `[fix, infra]`- **Agent share cards survive an unconfigured bucket, and a mistyped payment mint is refused instead of listed**: An audit of the agent endpoints turned up four things worth fixing. A skill price set through /api/agents/:id/skills/set-price accepted any text as its payment mint and saved it, so a typo produced a listing nobody could actually pay; it now has to be a real base58 address, matching the other door onto the same table. The agent share page and its OG image used to answer a social crawler with a hard error whenever object storage was not configured, instead of falling back to the plain card they already knew how to draw. A mistyped agent id in the diary, skill-price and screen-push endpoints came back as a server error rather than the plain "that is not an agent id" it is. And an agent screen with no live frame store now tells you the agent is offline right away instead of leaving you on "Connecting" for five minutes. `[fix, improvement]`- **An expired X connection now offers to reconnect instead of sending you to the login page**: Posting a Walk screenshot or clip to X goes through your connected X account. When that connection could no longer be renewed, the share endpoint answered with the same code it uses for a signed-out visitor, so the capture panel told an already signed-in user to sign in to three.ws and linked them to the login page, which fixed nothing. That case now comes back as its own answer with the X connect link attached, and the panel offers a Reconnect X button that takes you straight to the flow that repairs it. The share caption also lost a stray dash. (`/walk`) `[fix]`+- **An unsubscribe now sticks, even if you click an old confirm link**: Every three.ws newsletter email carries a confirm link and an unsubscribe link that share one token, so a reader who unsubscribed and later opened an older email and clicked confirm was quietly put back on the list. That link no longer signs anyone up: it says you are unsubscribed and leaves it that way, and opting back in starts from the site. Three other fixes ship alongside it. The allocation planner at /meta-allocator no longer serves an empty basket when the model declines to answer, it falls back to the allocator that always produces a real spread across verified leaders. The motion capture uploader told you an upload link lasted ten minutes when it really lasted five, so a large video queued on that promise could fail with nothing explaining why. And an agent whose stablecoin payment is rejected by the x402 Bazaar now gets the Bazaar's own details back instead of a different server's, so its retry is aimed at the right place. (`/changelog`) `[fix]`+- **Avatar link previews stop rebuilding themselves, and two feeds answer a bad page link plainly**: An audit of the chat, media and board endpoints found three real breaks. When you share an avatar link, the preview image is drawn once and then kept, so every later share is instant. A mix-up between the stored image and its address meant every freshly drawn preview was mistaken for an old broken one: the saved copy was thrown away and the picture was redrawn from scratch on every single share. The preview is now kept, as it always should have been, and genuinely broken old records are repaired the next time they are drawn. Separately, the character directory answered a hand-edited or stale "next page" link with a server error instead of saying the value was not a timestamp, and the bounty board did the same when the page size in the address was not a number. Both now answer plainly, and the board simply falls back to its normal page size. (`/characters`) `[fix]`- **Avatar Studio trait library: the mirror can no longer be pointed at someone else's server**: Avatar Studio loads its hair, clothing and accessory traits through a three.ws address that mirrors the open-source trait library, so your browser never talks to an outside CDN. The list of where those traits live was being written using the address in the incoming request, and that address can be set by whoever sends the request. Because the mirror is cached at the edge for a day, one crafted request could have left every Avatar Studio visitor loading trait files from a stranger's server for the next 24 hours. That list is now written the same way for everybody, with no part of it taken from the request, so there is nothing left to steer. Three smaller repairs went in alongside it: asking the mirror how big a file is no longer answers with the compressed size (a trait manifest claimed 2 KB and delivered 20 KB), the mirror will not hand back a web page or script even if the upstream library ever served one, and a failure at the library now answers plainly as either not found or mirror is down instead of passing its raw status through as ours. (`/avatar-studio`) `[security, fix]`- **Corrected stale numbers across the avatar and animation docs**: An audit of eight documentation pages against the code they describe turned up four claims that had drifted. The Animations page said the motion-capture library held about 2,000 clips when it actually serves 2,874, so both the intro and the gallery section now quote the real size and point at the count the API itself returns. The selfie-to-avatar page listed the wrong default for the face-morph displacement clamp and credited a single tuning sweep instead of the two that chose it. The avatar-creation walkthrough still told people to pick a body type on the selfie flow, a control that was deliberately removed because it changed nothing, and named the wrong fields on the event the page dispatches. The architecture page now says plainly that the whitelist trust mode is reserved rather than enforced. (`/docs/animations`) `[docs]`- **Creator subscription tiers save their edits again, and a mistyped subscription link says so plainly**: Editing an existing subscription tier from the creator dashboard silently failed: the save never reached the server, so the new name, price or status was lost every time. Saving works now. Alongside it, a mistyped or truncated subscription or tier link used to answer with a generic server failure; it now says the id is not valid, which is what a reader can actually act on. Tier pages are also directly addressable, so a single tier can be linked and read on its own, with unpublished drafts still visible only to the creator who wrote them. `[fix, improvement]`diff --git a/api/_lib/forge-consumption-payment.js b/api/_lib/forge-consumption-payment.jsindex 2dca498c2..750b87c79 100644--- a/api/_lib/forge-consumption-payment.js+++ b/api/_lib/forge-consumption-payment.js@@ -37,6 +37,7 @@import { sql } from './db.js';import { priceForAction } from './pricing/catalog.js';+import { isUuid } from './validate.js';// How long after settlement a payment may be redeemed. Generous — a paid action is// normally redeemed seconds after settling, but a failed dispatch (released claim)@@ -97,6 +98,14 @@ export async function assertForgePurchase({ action, paymentId, refId, refType =if (!paymentId || !refId) {throw payErr('payment_id and ref_id are required', 400, 'bad_request');}+ // token_payments.id is a uuid column, so a malformed payment_id can never match+ // a settled payment. Answer that as the contract error it is, BEFORE the query:+ // otherwise Postgres raises 22P02 and the driver error escapes this module with+ // the raw SQLSTATE as `code` and the raw cast message as `message`, which the+ // gate handlers then echo verbatim to an unauthenticated caller.+ if (!isUuid(paymentId)) {+ throw payErr('No settled $THREE payment found for this request.', 402, 'payment_invalid');+ }const payment = await lookupPayment(paymentId);if (!payment) {diff --git a/api/_lib/forge-high-payment.js b/api/_lib/forge-high-payment.jsindex b4119bf9a..be322717a 100644--- a/api/_lib/forge-high-payment.js+++ b/api/_lib/forge-high-payment.js@@ -25,6 +25,7 @@import { sql } from './db.js';import { priceForAction } from './pricing/catalog.js';+import { isUuid } from './validate.js';// How long after settlement a payment may be redeemed. Generous — a paid// generation is normally redeemed seconds after settling, but a failed dispatch@@ -81,6 +82,14 @@ export async function assertForgePayment({ paymentId, refId, discountBps = 0 })if (!paymentId || !refId) {throw payErr('payment_id and ref_id are required', 400, 'bad_request');}+ // token_payments.id is a uuid column, so a malformed payment_id can never match+ // a settled payment. Answer that as the contract error it is, BEFORE the query:+ // otherwise Postgres raises 22P02 and the driver error escapes this module with+ // the raw SQLSTATE as `code` and the raw cast message as `message`, which the+ // gate handlers then echo verbatim to an unauthenticated caller.+ if (!isUuid(paymentId)) {+ throw payErr('No settled $THREE payment found for this generation.', 402, 'payment_invalid');+ }const payment = await lookupPayment(paymentId);if (!payment) {diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 990d33b1d..01e74b557 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -140,21 +140,6 @@ function failClosedLimiter({ limit, window }) {* commands are what keep the Upstash quota alive (June 2026 outage). Never* combine with `critical`.*/-/**- * Hand a consumed hit back to its bucket, for the one case that justifies it:- * the request was charged, then produced nothing at all because a dependency we- * own was unavailable. The caller keeps its window instead of paying for our- * outage. Only single-use windows may do this (see the Redis note in- * resilientLimiter), and the refund must be unconditional at that point in the- * handler: a refund on a path that DID something turns the limiter off.- */-export function refundLimit(name, opts, id) {- if (opts.limit !== 1) {- throw new Error(`refundLimit: ${name} is not a single-use window (limit ${opts.limit})`);- }- return getLimiter(name, opts).refund(id);-}-function getLimiter(name, opts) {const key = `${name}:${opts.limit}:${opts.window}`;if (limiters.has(key)) return limiters.get(key);@@ -181,6 +166,22 @@ function getLimiter(name, opts) {return resilient;}+/**+ * Hand a consumed hit back to its bucket, for the one case that justifies it:+ * the request was charged, then produced nothing at all because a dependency we+ * own was unavailable. The caller keeps its window instead of paying for our+ * outage. Two conditions, both load-bearing: the bucket must be a single-use+ * window (see the Redis note in resilientLimiter, which is why this refuses any+ * other ceiling), and the refund must be unconditional at that point in the+ * handler. A refund on a path that DID something turns the limiter off.+ */+export async function refundLimit(name, opts, id) {+ if (opts.limit !== 1) {+ throw new Error(`refundLimit: ${name} is not a single-use window (limit ${opts.limit})`);+ }+ return getLimiter(name, opts).refund(id);+}+// One warn per limiter name per cooldown — a Redis outage hits every request,// so unthrottled logging would itself become a denial-of-service on the logs.const _degradeWarnedAt = new Map();@@ -341,7 +342,7 @@ function resilientLimiter(rl, name, opts) {},// Upstash has no "give one token back": resetUsedTokens clears the whole// identifier. That equals a refund only on a single-use window, which is- // why getLimiter refuses to expose refund on any other bucket. A refund+ // why refundLimit refuses any other ceiling. A refund// that cannot reach Redis is dropped rather than retried: the cost of// losing it is one caller waiting out a window they should not have// spent, and failing the request they are already being apologised todiff --git a/api/_lib/solana-agents-crawl.js b/api/_lib/solana-agents-crawl.jsindex 3ef16e399..5795fc672 100644--- a/api/_lib/solana-agents-crawl.js+++ b/api/_lib/solana-agents-crawl.js@@ -12,7 +12,7 @@// module only pulls them in when the crawl cron actually runs.import { sql } from './db.js';-import { solanaRpcEndpoints } from './solana/connection.js';+import { solanaConnection, solanaRpcEndpoints } from './solana/connection.js';import { fetchSafePublicUrlPinned } from './ssrf-guard.js';import {truncate,@@ -29,6 +29,20 @@ import {// scan targets the right program even if the SDK's default ever drifts.const MPL_AGENT_IDENTITY_PROGRAM = '1DREGFgysWYxLnRnKQnwrxnJQeSMk2HmGaC6whw2B2p';+// The `key` account discriminator, byte 0 of every identity account+// (Uninitialized 0, AgentIdentityV1 1, AgentIdentityV2 2). Both GPA builders+// register `key` at offset 0 but neither filters on it, so an unfiltered+// getDeserialized() hands EVERY account in the program to one version's+// deserializer. Measured 2026-08-16: the program holds 1503 v2 and 68 v1+// accounts, and unfiltered the v2 scan threw on the first v1 account it met+// ("not of the expected type [AgentIdentityV2AccountData]") while the v1 scan+// silently accepted all 1571 and read v2 bytes through the v1 layout. Pinning+// each builder to its own key is what makes the two scans disjoint and correct;+// the filter is a memcmp the node applies, so it also shrinks the response.+// The SDK does not re-export its Key enum from the package root, so the values+// are named here against the on-chain contract they encode.+const IDENTITY_KEY = { v1: 1, v2: 2 };+const FETCH_TIMEOUT_MS = 6_000;// On-chain metadata JSON is small by convention; anything larger is not a// metadata document. Also the streaming cap the pinned guard enforces.@@ -40,10 +54,6 @@ const MAX_METADATA_BYTES = 1024 * 1024;// throttled, rate-limited, or 504-ing RPC.const SCAN_BUDGET_MS = 90_000;-// Per-HTTP-request cap for the Anchor account scan, so a stalled socket is-// released instead of held until the whole scan budget burns down.-const RPC_REQUEST_TIMEOUT_MS = 30_000;-/** Milliseconds left before `deadline`, or `fallbackMs` when the caller set none. */export function remainingMs(deadline, fallbackMs = SCAN_BUDGET_MS) {if (!deadline) return fallbackMs;@@ -84,12 +94,48 @@ export async function withDeadline(promise, ms, label) {// Pick the best available mainnet RPC. solanaRpcEndpoints prefers Helius (which// also answers DAS getAsset on the same URL), falling back to public nodes.+//+// This is the URL for the DAS `getAsset` enrichment ONLY, which is a+// vendor-specific method a generic lane cannot serve anyway, and whose failure is+// already soft (the structural row is upserted without a name/image). The+// registry ENUMERATION must never use it: see scanConnection below.function mainnetRpc() {const [url] = solanaRpcEndpoints('mainnet');if (!url) throw new Error('no Solana mainnet RPC configured (set SOLANA_RPC_URL or HELIUS_API_KEY)');return url;}+// The connection both registry scans enumerate over.+//+// Enumeration is getProgramAccounts, and gPA is the method free lanes are most+// likely to refuse: it is expensive, so providers gate it behind a paid plan, an+// IP allowlist, or nothing at all. Pinning the single highest-priority URL+// therefore fails in the one way that leaves no trace: the crawl records a+// per-stage error string, returns HTTP 200 to Cloud Scheduler, which discards the+// body, and writes nothing. Measured 2026-08-16 against the live lane chain, one+// gPA on the identity program per lane:+// rpc.magicblock.app 403 "Your IP or provider is blocked from this endpoint"+// solana-rpc.publicnode.com no answer in 25s+// api.mainnet-beta.solana.com 200, 1571 accounts in 1.1s+// solana.leorpc.com 200 + JSON-RPC -32603+// public.rpc.solanavibestation.com 200, 1571 accounts in 0.5s+// api.tatum.io / gateway.tatum.io 200 + -16401 "available for paid plans only"+// magicblock is the configured SOLANA_RPC_URL, so it is lane 0, so every tick+// since it became primary scanned nothing: solana_agents_index had not taken an+// upsert since 2026-08-06 while the cron reported 200 every 30 minutes.+//+// solanaConnection rotates the whole chain on exactly these signals (403 and 5xx+// rotate, a provider-tier error code fails the lane over, a 10s attempt timeout+// demotes the shape) so the scan lands on a lane that answers instead of dying on+// the first that does not. The full 1571-account scan is ~559 KB and answers in+// about a second, comfortably inside that attempt bound.+function scanConnection() {+ // Fail the same way mainnetRpc does when nothing is configured at all, rather+ // than handing web3.js a bare default and reporting a confusing lane error.+ mainnetRpc();+ return solanaConnection({ network: 'mainnet', commitment: 'confirmed' });+}+async function fetchJsonWithTimeout(url, timeoutMs = FETCH_TIMEOUT_MS) {const resolved = resolveGateway(url);if (!resolved) return null;@@ -186,7 +232,9 @@ export async function crawlMetaplexAgents({ deadline } = {}) {const { createUmi } = await import('@metaplex-foundation/umi-bundle-defaults');const { publicKey } = await import('@metaplex-foundation/umi');const reg = await import('@metaplex-foundation/mpl-agent-registry');- umi = createUmi(rpcUrl);+ // createUmi takes an endpoint string OR a ready web3.js Connection; the+ // Connection form is what lets the scan inherit the rotating lane chain.+ umi = createUmi(scanConnection());// The GPA builder reads the identity program id from umi via// context.programs.getPublicKey('mplAgentIdentity', <default>); the SDK's// baked-in default is MPL_AGENT_IDENTITY_PROGRAM, so an unmodified umi scans@@ -196,18 +244,19 @@ export async function crawlMetaplexAgents({ deadline } = {}) {umi.programs.add({ name: 'mplAgentIdentity', publicKey: publicKey(MPL_AGENT_IDENTITY_PROGRAM), getErrorFromCode: () => null, getErrorFromName: () => null, isOnCluster: () => true });} catch { /* already registered or registry shape differs — default still applies */ }gpaV2 = typeof reg.getAgentIdentityV2GpaBuilder === 'function'- ? reg.getAgentIdentityV2GpaBuilder(umi)+ ? reg.getAgentIdentityV2GpaBuilder(umi).whereField('key', IDENTITY_KEY.v2): null;gpaV1 = typeof reg.getAgentIdentityV1GpaBuilder === 'function'- ? reg.getAgentIdentityV1GpaBuilder(umi)+ ? reg.getAgentIdentityV1GpaBuilder(umi).whereField('key', IDENTITY_KEY.v1): null;} catch (err) {report.errors.push({ stage: 'init', error: err.message || String(err) });return report;}- // Enumerate both account versions. getDeserialized() returns every account of- // the type owned by the program — the full registry, not just ours.+ // Enumerate both account versions. Each builder is pinned to its own+ // discriminator above, so getDeserialized() reads every account of THAT type,+ // the full registry rather than just ours, and nothing else.const accounts = [];// Split whatever budget is left evenly across the scans still to run, so a// slow v2 cannot silently starve v1 of every remaining millisecond.@@ -267,22 +316,21 @@ function bytesToBase58(bytes, bs58) {export async function crawlAgencAgents({ deadline } = {}) {const report = { source: 'agenc', scanned: 0, upserted: 0, enriched: 0, errors: [] };- const rpcUrl = mainnetRpc();let program, bs58;try {- const { Connection, Keypair } = await import('@solana/web3.js');+ const { Keypair } = await import('@solana/web3.js');const anchor = await import('@coral-xyz/anchor');const { AGENC_COORDINATION_IDL } = await import('@tetsuo-ai/protocol');bs58 = (await import('bs58')).default;- // A per-request timeout on top of the scan-wide deadline below: without it- // a stalled socket is held for the whole budget, and Anchor's account- // fetcher offers no timeout of its own.- const connection = new Connection(rpcUrl, {- commitment: 'confirmed',- fetch: (input, init) => fetch(input, { ...init, signal: AbortSignal.timeout(RPC_REQUEST_TIMEOUT_MS) }),- });+ // Anchor's account fetcher offers no timeout of its own, and this scan is+ // the same getProgramAccounts that dies on a refusing lane 0 (see+ // scanConnection). The rotating connection supplies both halves: failover+ // across the chain, and a 10s per-attempt bound, stricter than the 30s+ // hand-rolled cap this replaced, so a stalled socket is released rather+ // than held for the whole scan budget.+ const connection = scanConnection();// Read-only provider: an ephemeral wallet that never signs. Anchor needs a// payer/publicKey slot to construct the provider; the account namespace we// use (.all()) only reads.diff --git a/api/forge-gallery.js b/api/forge-gallery.jsindex 6e60bd312..2d5465f2d 100644--- a/api/forge-gallery.js+++ b/api/forge-gallery.js@@ -18,7 +18,7 @@* rather than show a broken state.*/-import { cors, json, method, wrap, rateLimited } from './_lib/http.js';+import { cors, json, method, wrap, rateLimited, varyOn } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { hashClient, listCreations, listShowcase, countShowcase, forgeStoreEnabled } from './_lib/forge-store.js';@@ -57,6 +57,14 @@ export default wrap(async (req, res) => {]);// Per-voter reads can't be shared across browsers, so only the anonymous// (no client id) read is CDN-cacheable. A voted-state read is private.+ //+ // The body changes with x-forge-client, so the edge MUST key on it. Without+ // this Vary the anonymous copy (cacheable for 60s + 300s stale) was served+ // to browsers that DID send the header, so every card came back voted=false+ // for a voter who had already liked it and the like button rendered the+ // wrong state (confirmed live against three.ws before this fix). varyOn+ // merges rather than replaces, so cors()'s `vary: origin` survives.+ varyOn(res, 'x-forge-client');const headers = voterKey? { 'cache-control': 'private, no-store' }: { 'cache-control': 'public, s-maxage=60, stale-while-revalidate=300' };diff --git a/api/forge-gameready.js b/api/forge-gameready.jsindex 2c71a8aa2..c9c12c4de 100644--- a/api/forge-gameready.js+++ b/api/forge-gameready.js@@ -41,6 +41,17 @@ import { priceForAction } from './_lib/pricing/catalog.js';const GAMEREADY_ACTION = 'forge.gameready';+// The complete set of codes assertForgePurchase raises deliberately to describe a+// payment (api/_lib/forge-consumption-payment.js). Every one of them is part of+// this endpoint's documented contract and is safe to hand back; anything else is+// an internal fault and is rethrown rather than echoed.+const PAYMENT_ERROR_CODES = new Set([+ 'bad_request',+ 'payment_invalid',+ 'payment_expired',+ 'payment_already_used',+]);+// The composite job id is a base64url JSON envelope packing one upstream task per// requested format, so it is far longer than a raw worker task id.const JOB_ID_RE = /^[A-Za-z0-9_-]{24,16000}$/;@@ -129,6 +140,13 @@ async function startJob(req, res) {const proof = await assertForgePurchase({ action: GAMEREADY_ACTION, paymentId, refId: payRefId });paidExport = { paymentId, refId: payRefId, settledAt: proof.payment.settledAt };} catch (err) {+ // Only assertForgePurchase's own contract errors describe the payment, and+ // only those may be echoed. Anything else reaching here is infrastructure+ // (a database outage, an unexpected driver fault): rethrowing hands it to+ // wrap(), which logs it under a ref, alerts ops, and answers a sanitized+ // 5xx. Echoing it instead would both leak internals and lie to the caller,+ // telling them their settled payment is bad when the database is simply down.+ if (!PAYMENT_ERROR_CODES.has(err?.code)) throw err;let usd = null;try {usd = Number(priceForAction(GAMEREADY_ACTION).usd) || null;@@ -136,7 +154,7 @@ async function startJob(req, res) {usd = null;}return json(res, err.status || 402, {- error: err.code || 'payment_invalid',+ error: err.code,feature: GAMEREADY_ACTION,pay_per_use: usd ? { action: GAMEREADY_ACTION, usd } : null,message: err.message || 'That $THREE payment could not be verified.',diff --git a/data/changelog.json b/data/changelog.jsonindex 8d2e830b9..00bf2e7b1 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,35 @@{"$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": "The Solana agent directory is live again, and complete",+ "summary": "Explore and the deployments view list agents registered on the Metaplex Agent Registry, refreshed by a crawl that runs every half hour. The crawl had been reading nothing since 6 August: it asked one fixed Solana node for the registry, that node started refusing the request outright, and because it never tried any of the other nodes it fell back to, every run reported success while writing nothing. It now works its way down the same list of providers the rest of the platform uses, so one provider turning us away costs a second, not ten days. Fixing that surfaced a second fault underneath it: the registry holds two generations of agent records, and the crawl was reading both with the newer generation's layout, so older records came back as nonsense and the newer pass gave up entirely at the first old record it met. Each generation is now read on its own terms. The directory went from 1,558 stale entries to all 1,571 currently on chain, and new registrations show up within the half hour again. Separately, the treasury top-up that keeps the platform's wallets funded no longer fails outright when a Solana provider answers with something it cannot read: it treats that the same as a provider being busy and retries on the next pass, instead of skipping a funding cycle.",+ "tags": [+ "fix",+ "infra"+ ],+ "link": "/explore"+ },+ {+ "date": "2026-08-16",+ "title": "An unsubscribe now sticks, even if you click an old confirm link",+ "summary": "Every three.ws newsletter email carries a confirm link and an unsubscribe link that share one token, so a reader who unsubscribed and later opened an older email and clicked confirm was quietly put back on the list. That link no longer signs anyone up: it says you are unsubscribed and leaves it that way, and opting back in starts from the site. Three other fixes ship alongside it. The allocation planner at /meta-allocator no longer serves an empty basket when the model declines to answer, it falls back to the allocator that always produces a real spread across verified leaders. The motion capture uploader told you an upload link lasted ten minutes when it really lasted five, so a large video queued on that promise could fail with nothing explaining why. And an agent whose stablecoin payment is rejected by the x402 Bazaar now gets the Bazaar's own details back instead of a different server's, so its retry is aimed at the right place.",+ "tags": [+ "fix"+ ],+ "link": "/changelog"+ },+ {+ "date": "2026-08-16",+ "title": "A GitHub seed that stores nothing no longer costs you six hours",+ "summary": "Seeding an agent from your GitHub profile, repositories and READMEs is allowed once every six hours per agent. Two failures used to spend that window without storing a single fact. The first is entirely ours: when every model provider is busy at once, nothing is read and nothing is written, and you were still locked out for six hours over an outage you did not cause. The second is the run that comes back with no usable facts, which tells you to add a README or another repository, advice you could not act on until the window expired. Both now hand the window straight back, so you can try again as soon as a provider frees up or as soon as you have widened your selection, and the reply says which of the two happened. Nothing else changes: your existing memories are untouched by a failed run, the seed still reads only the profile, repositories and READMEs you ticked, and disconnecting GitHub still deletes every fact it wrote across all your agents.",+ "tags": [+ "improvement",+ "fix"+ ],+ "link": "/docs/github-memory-seeding"+ },{"date": "2026-08-16","title": "Avatar link previews stop rebuilding themselves, and two feeds answer a bad page link plainly",diff --git a/docs/motion-swap.md b/docs/motion-swap.mdindex 50f3dd02f..c376e5044 100644--- a/docs/motion-swap.md+++ b/docs/motion-swap.md@@ -54,7 +54,8 @@ only), and processing artifacts live under an unguessable job id.```POST /api/motion-swap { action: "upload", content_type, size_bytes }- → { upload_url, public_url, ... } # presigned direct-to-storage PUT+ → { upload_url, public_url, method, headers, expires_in }+ # presigned direct-to-storage PUTPOST /api/motion-swap { video_url, fps?, max_seconds? }→ 202 { job_id, status, eta_seconds }@@ -63,6 +64,11 @@ GET /api/motion-swap?job=<id>→ { status, clip_url, meta_url, video_url, mask_url, frames, fps }```+`content_type` must be `video/mp4`, `video/quicktime`, or `video/webm`, and+`size_bytes` must be between 1 byte and 256 MB. Start the PUT within+`expires_in` seconds of getting the URL: the signature is minted for exactly+that window, and storage rejects a late upload with a bare 403.+`clip_url` is a three.js `AnimationClip.toJSON()` document you can useanywhere the platform accepts a clip. `meta_url` carries `fps`, dimensions,and per-frame `anchors` (`{x, y, h, v}`: hip centre in normalized imagediff --git a/prompts/swarm-100/api-top-11.md b/prompts/swarm-100/api-top-11.mddeleted file mode 100644index 3f39c1f63..000000000--- a/prompts/swarm-100/api-top-11.md+++ /dev/null@@ -1,110 +0,0 @@-# API audit: api/*.js batch 11 (10 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/mcp-bazaar.js-- api/mcp-policy.js-- api/mcp-studio.js-- api/mcp.js-- api/me.js-- api/meta-allocator.js-- api/motion-swap.js-- api/newsletter-confirm.js-- api/newsletter-subscribe.js-- api/newsletter-unsubscribe.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-top-11.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.jsonindex daebb1bfc..187d5c478 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-16T16:06:49.920Z",+ "generated_at": "2026-08-16T16:23:14.437Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -17,6 +17,17 @@"security"]},+ {+ "date": "2026-08-16",+ "type": "update",+ "title": "A GitHub seed that stores nothing no longer costs you six hours",+ "summary": "Seeding an agent from your GitHub profile, repositories and READMEs is allowed once every six hours per agent. Two failures used to spend that window without storing a single fact. The first is entirely ours: when every model provider is busy at once, nothing is read and nothing is written, and you were still locked out for six hours over an outage you did not cause. The second is the run that comes back with no usable facts, which tells you to add a README or another repository, advice you could not act on until the window expired. Both now hand the window straight back, so you can try again as soon as a provider frees up or as soon as you have widened your selection, and the reply says which of the two happened. Nothing else changes: your existing memories are untouched by a failed run, the seed still reads only the profile, repositories and READMEs you ticked, and disconnecting GitHub still deletes every fact it wrote across all your agents.",+ "link": "/docs/github-memory-seeding",+ "tags": [+ "improvement",+ "fix"+ ]+ },{"date": "2026-08-16","type": "update",@@ -59,6 +70,26 @@"fix"]},+ {+ "date": "2026-08-16",+ "type": "update",+ "title": "An unsubscribe now sticks, even if you click an old confirm link",+ "summary": "Every three.ws newsletter email carries a confirm link and an unsubscribe link that share one token, so a reader who unsubscribed and later opened an older email and clicked confirm was quietly put back on the list. That link no longer signs anyone up: it says you are unsubscribed and leaves it that way, and opting back in starts from the site. Three other fixes ship alongside it. The allocation planner at /meta-allocator no longer serves an empty basket when the model declines to answer, it falls back to the allocator that always produces a real spread across verified leaders. The motion capture uploader told you an upload link lasted ten minutes when it really lasted five, so a large video queued on that promise could fail with nothing explaining why. And an agent whose stablecoin payment is rejected by the x402 Bazaar now gets the Bazaar's own details back instead of a different server's, so its retry is aimed at the right place.",+ "link": "/changelog",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-08-16",+ "type": "update",+ "title": "Avatar link previews stop rebuilding themselves, and two feeds answer a bad page link plainly",+ "summary": "An audit of the chat, media and board endpoints found three real breaks. When you share an avatar link, the preview image is drawn once and then kept, so every later share is instant. A mix-up between the stored image and its address meant every freshly drawn preview was mistaken for an old broken one: the saved copy was thrown away and the picture was redrawn from scratch on every single share. The preview is now kept, as it always should have been, and genuinely broken old records are repaired the next time they are drawn. Separately, the character directory answered a hand-edited or stale \"next page\" link with a server error instead of saying the value was not a timestamp, and the bounty board did the same when the page size in the address was not a number. Both now answer plainly, and the board simply falls back to its normal page size.",+ "link": "/characters",+ "tags": [+ "fix"+ ]+ },{"date": "2026-08-16","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 8de0282a3..d095d3ef2 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>fix</category><description>Pasting a coin community link into WordPress, Ghost, Discord, Notion or any editor built on embed.ly or iframely now turns it into the live 3D world instead of a plain link. The service that answers those editors existed but nothing on the page told them where to find it, so it was never called. Two problems in that service are fixed at the same time. It used to build the embed from the address in the incoming request rather than from the site address, so a crafted request could hand an editor an embed that framed somebody else site under the three.ws name; the embed is now always built from three.ws itself. And it used to answer for any link at all, returning a generic three.ws world card for a link that was never ours; it now says plainly that the link is not one of ours. It also answers in both of the formats the standard defines, and ignores a coin address that is not a real Solana address instead of putting it in the embed. Separately, the share images for pages and coin worlds, the holder leaderboard card, the free model verification check and the Oracle coin page now accept only read requests, and answer anything else with a clear message rather than doing the work anyway.</description></item>+ <item>+ <title>A GitHub seed that stores nothing no longer costs you six hours</title>+ <link>https://three.ws/docs/github-memory-seeding</link>+ <guid isPermaLink="false">2026-08-16:A GitHub seed that stores nothing no longer costs you six hours</guid>+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Seeding an agent from your GitHub profile, repositories and READMEs is allowed once every six hours per agent. Two failures used to spend that window without storing a single fact. The first is entirely ours: when every model provider is busy at once, nothing is read and nothing is written, and you were still locked out for six hours over an outage you did not cause. The second is the run that comes back with no usable facts, which tells you to add a README or another repository, advice you could not act on until the window expired. Both now hand the window straight back, so you can try again as soon as a provider frees up or as soon as you have widened your selection, and the reply says which of the two happened. Nothing else changes: your existing memories are untouched by a failed run, the seed still reads only the profile, repositories and READMEs you ticked, and disconnecting GitHub still deletes every fact it wrote across all your agents.</description>+ </item><item><title>A mistyped id on the signal marketplace answers plainly, and the live feed links to the right chain</title><link>https://three.ws/signals</link>@@ -46,6 +54,22 @@<category>fix</category><description>Posting a Walk screenshot or clip to X goes through your connected X account. When that connection could no longer be renewed, the share endpoint answered with the same code it uses for a signed-out visitor, so the capture panel told an already signed-in user to sign in to three.ws and linked them to the login page, which fixed nothing. That case now comes back as its own answer with the X connect link attached, and the panel offers a Reconnect X button that takes you straight to the flow that repairs it. The share caption also lost a stray dash.</description></item>+ <item>+ <title>An unsubscribe now sticks, even if you click an old confirm link</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-08-16:An unsubscribe now sticks, even if you click an old confirm link</guid>+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Every three.ws newsletter email carries a confirm link and an unsubscribe link that share one token, so a reader who unsubscribed and later opened an older email and clicked confirm was quietly put back on the list. That link no longer signs anyone up: it says you are unsubscribed and leaves it that way, and opting back in starts from the site. Three other fixes ship alongside it. The allocation planner at /meta-allocator no longer serves an empty basket when the model declines to answer, it falls back to the allocator that always produces a real spread across verified leaders. The motion capture uploader told you an upload link lasted ten minutes when it really lasted five, so a large video queued on that promise could fail with nothing explaining why. And an agent whose stablecoin payment is rejected by the x402 Bazaar now gets the Bazaar's own details back instead of a different server's, so its retry is aimed at the right place.</description>+ </item>+ <item>+ <title>Avatar link previews stop rebuilding themselves, and two feeds answer a bad page link plainly</title>+ <link>https://three.ws/characters</link>+ <guid isPermaLink="false">2026-08-16:Avatar link previews stop rebuilding themselves, and two feeds answer a bad page link plainly</guid>+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>An audit of the chat, media and board endpoints found three real breaks. When you share an avatar link, the preview image is drawn once and then kept, so every later share is instant. A mix-up between the stored image and its address meant every freshly drawn preview was mistaken for an old broken one: the saved copy was thrown away and the picture was redrawn from scratch on every single share. The preview is now kept, as it always should have been, and genuinely broken old records are repaired the next time they are drawn. Separately, the character directory answered a hand-edited or stale "next page" link with a server error instead of saying the value was not a timestamp, and the bounty board did the same when the page size in the address was not a number. Both now answer plainly, and the board simply falls back to its normal page size.</description>+ </item><item><title>Avatar Studio trait library: the mirror can no longer be pointed at someone else's server</title><link>https://three.ws/avatar-studio</link>diff --git a/tests/api/mcp-policy.test.js b/tests/api/mcp-policy.test.jsindex 67a0607ad..3415dc358 100644--- a/tests/api/mcp-policy.test.js+++ b/tests/api/mcp-policy.test.js@@ -139,3 +139,30 @@ describe('GET /api/mcp-policy', () => {expect(res.getHeader('content-type')).toContain('application/json');});});++// The preflight this endpoint answers advertises GET, HEAD, OPTIONS. It used to+// serve any other verb the same cacheable 200 policy body, so a POST looked to+// a caller (and to a caching intermediary) like a legitimate write that had+// been accepted.+describe('/api/mcp-policy: method contract', () => {+ async function call(httpMethod) {+ const req = { method: httpMethod, url: '/api/mcp-policy', headers: {} };+ const res = makeRes();+ await handler(req, res);+ return res;+ }++ it('answers a HEAD probe like a GET', async () => {+ const res = await call('HEAD');+ expect(res.statusCode).toBe(200);+ });++ it('refuses write verbs and says what is allowed', async () => {+ for (const httpMethod of ['POST', 'PUT', 'PATCH', 'DELETE']) {+ const res = await call(httpMethod);+ expect(res.statusCode).toBe(405);+ expect(String(res.getHeader('allow'))).toContain('GET');+ expect(JSON.parse(res.body).error).toBe('method_not_allowed');+ }+ });+});diff --git a/tests/api/meta-allocator-plan.test.js b/tests/api/meta-allocator-plan.test.jsnew file mode 100644index 000000000..f513ce9a7--- /dev/null+++ b/tests/api/meta-allocator-plan.test.js@@ -0,0 +1,111 @@+// buildAllocationPlan() is what /api/meta-allocator returns to a user asking how+// to split a budget across verified leader agents. Its contract is that it+// always answers with a real basket: the LLM shapes the narrative, and the+// deterministic allocator underneath guarantees an answer when the model does+// not give one.+//+// The gap was a model that replies with a syntactically valid but empty plan.+// `{"allocations": [], "excluded": []}` passed the Array.isArray check, so it+// was accepted verbatim and the endpoint served a plan with zero rows and zero+// exclusions while eight leaders qualified. Observed live on 2026-08-16. An+// empty allocation set is the model declining, not deciding, so it has to fall+// through to the deterministic allocator like any other non-answer.+//+// Only the LLM chain is stubbed; the allocator, the scoring, and the profile+// rules are the real ones.+import { describe, it, expect, vi, beforeEach } from 'vitest';++const llmComplete = vi.fn();+const llmConfigured = vi.fn(() => true);++vi.mock('../../api/_lib/llm.js', () => {+ class LlmUnavailableError extends Error {}+ return { llmComplete, llmConfigured, LlmUnavailableError };+});++vi.mock('../../api/_lib/db.js', () => ({ sql: () => Promise.resolve([]) }));++const { buildAllocationPlan } = await import('../../api/_lib/meta-allocator.js');++// Four leaders spread over three correlation groups, all past the profile bars.+const leaders = ['alpha', 'bravo', 'charlie', 'delta'].map((name, i) => ({+ agent_id: `00000000-0000-4000-8000-00000000000${i}`,+ name,+ settled: 40 + i,+ wins: 20 + i,+ win_rate_pct: 50 + i,+ roi_pct: 12 - i,+ pnl_sol: 1.5 - i * 0.1,+ max_drawdown_pct: 5 + i,+ capacity_quote: 10,+ follower_outcome_pnl: 0.4,+ followers: 3,+ active_followers: 2,+ correlation_group: ['momentum', 'moonshot', 'scalp', 'momentum'][i],+ risk_adjusted_score: 40 - i * 3,+}));++const plan = (over = {}) =>+ buildAllocationPlan({ budgetQuote: 5, riskProfile: 'balanced', leaders, ...over });++beforeEach(() => {+ llmComplete.mockReset();+ llmConfigured.mockReturnValue(true);+});++describe('buildAllocationPlan', () => {+ it('falls back to the deterministic basket when the model allocates to nobody', async () => {+ llmComplete.mockResolvedValue({ text: '{"allocations": [], "excluded": []}' });+ const out = await plan();+ expect(out.source).toBe('deterministic');+ expect(out.allocations.length).toBeGreaterThan(0);+ expect(out.leaders_considered).toBe(leaders.length);+ });++ it('uses the model plan when it actually allocates', async () => {+ llmComplete.mockResolvedValue({+ text: JSON.stringify({+ allocations: [+ { agent_id: leaders[0].agent_id, weight_pct: 60, why: 'steadiest record' },+ { agent_id: leaders[1].agent_id, weight_pct: 40, why: 'different style' },+ ],+ excluded: [{ agent_id: leaders[3].agent_id, reason: 'same group as the top pick' }],+ rebalance_rule: 'Rebalance monthly.',+ caution: 'Past results are not future ones.',+ }),+ });+ const out = await plan();+ expect(out.source).toBe('llm');+ expect(out.allocations).toHaveLength(2);+ });++ it('falls back when the model returns prose instead of a plan', async () => {+ llmComplete.mockResolvedValue({ text: 'I cannot advise on this.' });+ const out = await plan();+ expect(out.source).toBe('deterministic');+ expect(out.allocations.length).toBeGreaterThan(0);+ });++ it('falls back when the model errors', async () => {+ llmComplete.mockRejectedValue(new Error('provider 429'));+ const out = await plan();+ expect(out.source).toBe('deterministic');+ expect(out.allocations.length).toBeGreaterThan(0);+ });++ it('weights always sum to 100 and every leader is allocated or excluded', async () => {+ llmComplete.mockResolvedValue({ text: '{"allocations": []}' });+ const out = await plan();+ const sum = out.allocations.reduce((s, a) => s + a.weight_pct, 0);+ expect(Math.round(sum)).toBe(100);+ expect(out.allocations.length + out.excluded.length).toBe(leaders.length);+ });++ it('says so plainly when no leader clears the profile bar', async () => {+ llmConfigured.mockReturnValue(false);+ const out = await plan({ leaders: [{ ...leaders[0], settled: 0 }] });+ expect(out.source).toBe('empty');+ expect(out.allocations).toEqual([]);+ expect(out.rebalance_rule).toMatch(/no verified leaders/i);+ });+});diff --git a/tests/api/motion-swap-presign.test.js b/tests/api/motion-swap-presign.test.jsnew file mode 100644index 000000000..c2c7c5eba--- /dev/null+++ b/tests/api/motion-swap-presign.test.js@@ -0,0 +1,109 @@+// POST /api/motion-swap { action: "upload" } presigns a direct-to-storage PUT+// and tells the client how long that URL stays usable.+//+// The advertised `expires_in` and the signature's real lifetime have to be the+// same number. They were not: the handler reported 600 while presignUpload+// signs for 300, so a client that queued a large video on the strength of that+// promise could start the PUT after the signature had died and get a bare 403+// from R2 with nothing in our logs. This asserts the two against each other+// rather than against a literal, so the next change to either one is caught.+//+// The signer is the real one (AWS SigV4 is pure HMAC, no network), with throwaway+// credentials. Only the rate limiter is stubbed, since it needs Redis.+import { describe, it, expect, vi } from 'vitest';+import { Readable } from 'node:stream';++process.env.S3_ENDPOINT = 'https://example.r2.cloudflarestorage.com';+process.env.S3_BUCKET = 'test-bucket';+process.env.S3_PUBLIC_DOMAIN = 'https://cdn.example.com';+process.env.S3_ACCESS_KEY_ID = 'AKIAIOSFODNN7EXAMPLE';+process.env.S3_SECRET_ACCESS_KEY = 'wJalrXUtnFEMIK7MDENGbPxRfiCYEXAMPLEKEY';++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ upload: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ mcp3dGenerate: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ mcp3dStatus: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ },+ clientIp: vi.fn(() => '203.0.113.7'),+}));++const { default: handler } = await import('../../api/motion-swap.js');++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(k, v) {+ this.headers[String(k).toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[String(k).toLowerCase()];+ },+ end(body) {+ this.body = body ?? null;+ },+ };+}++function makeReq(body) {+ const payload = JSON.stringify(body);+ const req = Readable.from([Buffer.from(payload, 'utf8')]);+ req.method = 'POST';+ req.url = '/api/motion-swap';+ req.headers = { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.7' };+ return req;+}++async function presign(body) {+ const res = makeRes();+ await handler(makeReq(body), res);+ return { res, json: JSON.parse(res.body) };+}++describe('POST /api/motion-swap action=upload', () => {+ it('advertises exactly the lifetime the signature actually has', async () => {+ const { res, json } = await presign({+ action: 'upload',+ content_type: 'video/mp4',+ size_bytes: 1_048_576,+ });+ expect(res.statusCode).toBe(200);+ const signedFor = Number(new URL(json.upload_url).searchParams.get('X-Amz-Expires'));+ expect(signedFor).toBeGreaterThan(0);+ expect(json.expires_in).toBe(signedFor);+ });++ it('returns a PUT target and the public URL the video will land on', async () => {+ const { json } = await presign({+ action: 'upload',+ content_type: 'video/quicktime',+ size_bytes: 2048,+ });+ expect(json.method).toBe('PUT');+ expect(json.headers['content-type']).toBe('video/quicktime');+ expect(json.upload_url).toContain('.mov?');+ expect(json.public_url).toBe(+ `https://cdn.example.com/${new URL(json.upload_url).pathname.replace(/^\//, '')}`,+ );+ });++ it('rejects a content type the motion worker cannot decode', async () => {+ const { res, json } = await presign({+ action: 'upload',+ content_type: 'image/png',+ size_bytes: 2048,+ });+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('invalid_content_type');+ });++ it('rejects a size outside the 1 byte to 256 MB window', async () => {+ for (const size_bytes of [0, -1, 256 * 1024 * 1024 + 1]) {+ const { res, json } = await presign({ action: 'upload', content_type: 'video/mp4', size_bytes });+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('invalid_size');+ }+ });+});diff --git a/tests/api/newsletter-confirm-consent.test.js b/tests/api/newsletter-confirm-consent.test.jsnew file mode 100644index 000000000..25dfe9c3c--- /dev/null+++ b/tests/api/newsletter-confirm-consent.test.js@@ -0,0 +1,128 @@+// GET /api/newsletter-confirm decides whether a click puts an address back on+// the list, so the interesting cases are the ones where it must NOT.+//+// The confirm link and the unsubscribe link in a three.ws email carry the SAME+// token, and only a fresh POST /api/newsletter-subscribe rotates it. So an+// unsubscribed reader who later opened an older email and clicked "confirm"+// was silently re-subscribed: a consent failure with no way for them to see it+// happened. Opting back in has to start from the site.+//+// The DB is the only thing stubbed here (these are pure SQL branches), plus the+// Resend audience client, which is not configured in tests anyway.+import { describe, it, expect, vi, beforeEach } from 'vitest';++const rows = { current: [] };+const executed = [];++vi.mock('../../api/_lib/db.js', () => ({+ sql: (strings, ...values) => {+ const text = strings.join('?').replace(/\s+/g, ' ').trim();+ executed.push({ text, values });+ if (/^update/i.test(text)) {+ rows.current = rows.current.map((r) => ({ ...r, status: 'confirmed' }));+ return Promise.resolve([]);+ }+ return Promise.resolve(rows.current);+ },+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { newsletterConfirmIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })) },+ clientIp: vi.fn(() => '203.0.113.9'),+}));++const addToAudience = vi.fn(async () => {});+vi.mock('../../api/_lib/newsletter.js', async (importOriginal) => ({+ ...(await importOriginal()),+ addToAudience,+}));++const { default: handler } = await import('../../api/newsletter-confirm.js');++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ setHeader(k, v) {+ this.headers[String(k).toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[String(k).toLowerCase()];+ },+ end(body) {+ this.body = body ?? '';+ },+ };+}++async function confirm(token) {+ const res = makeRes();+ await handler(+ { method: 'GET', url: `/api/newsletter-confirm?token=${token}`, headers: {} },+ res,+ );+ return res;+}++const heading = (res) => (res.body.match(/<h1>([^<]*)<\/h1>/) || [])[1] || '';+const didUpdate = () => executed.some((q) => /^update/i.test(q.text));++beforeEach(() => {+ rows.current = [];+ executed.length = 0;+ addToAudience.mockClear();+});++describe('GET /api/newsletter-confirm', () => {+ it('confirms a pending subscriber and adds them to the audience', async () => {+ rows.current = [{ email: '[email protected]', status: 'pending', locale: 'en' }];+ const res = await confirm('a-valid-token');+ expect(res.statusCode).toBe(200);+ expect(heading(res)).toBe("You're in");+ expect(didUpdate()).toBe(true);+ expect(addToAudience).toHaveBeenCalledWith('[email protected]', 'en');+ });++ it('will not re-subscribe someone who unsubscribed, whatever the token says', async () => {+ rows.current = [{ email: '[email protected]', status: 'unsubscribed', locale: 'en' }];+ const res = await confirm('the-same-old-token');+ expect(res.statusCode).toBe(200);+ expect(heading(res)).toBe("You're unsubscribed");+ expect(didUpdate()).toBe(false);+ expect(addToAudience).not.toHaveBeenCalled();+ });++ it('is a no-op for an already-confirmed subscriber', async () => {+ rows.current = [{ email: '[email protected]', status: 'confirmed', locale: 'en' }];+ const res = await confirm('a-valid-token');+ expect(res.statusCode).toBe(200);+ expect(heading(res)).toBe("You're already subscribed");+ expect(didUpdate()).toBe(false);+ expect(addToAudience).not.toHaveBeenCalled();+ });++ it('shows a neutral page for an unknown token and touches nothing', async () => {+ rows.current = [];+ const res = await confirm('no-such-token');+ expect(res.statusCode).toBe(404);+ expect(heading(res)).toBe('Link expired');+ expect(didUpdate()).toBe(false);+ });++ it('rejects a missing or oversized token before it reaches the database', async () => {+ for (const token of ['', 'x'.repeat(129)]) {+ executed.length = 0;+ const res = await confirm(token);+ expect(res.statusCode).toBe(400);+ expect(heading(res)).toBe('Invalid link');+ expect(executed).toHaveLength(0);+ }+ });++ it('renders HTML, so the click lands on a page and not a JSON blob', async () => {+ rows.current = [{ email: '[email protected]', status: 'confirmed', locale: null }];+ const res = await confirm('a-valid-token');+ expect(res.headers['content-type']).toContain('text/html');+ });+});