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
chore: sync working tree
nirholasb155b0c13bc8
diff --git a/.gcloudignore b/.gcloudignoreindex 526bdd971..5b02a487e 100644--- a/.gcloudignore+++ b/.gcloudignore@@ -51,6 +51,16 @@!/walk-sdk/!/tour-sdk/!/agents/+# tests/ stays out of the image, but tests/fixtures/ holds one runtime artifact:+# the 40-claim fact-check benchmark suite. api/fact-check-benchmark.js reads it+# to render the claim-count summary on /fact-check, and+# api/cron/fact-check-benchmark.js runs it. Without this re-include the endpoint+# answered `fixture: null` in every deployed revision and the scheduled re-run+# could not load its own suite. Re-include the parent, drop everything else under+# it, then re-include just the fixtures dir (236K).+!/tests/+/tests/*+!/tests/fixtures/!/character-studio//character-studio/*!/character-studio/package.jsondiff --git a/CLAUDE.md b/CLAUDE.mdindex b34292071..7382b9d8f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -294,7 +294,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).- 3D: Three.js with glTF/GLB.- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (101 as of 2026-07-29, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (102 as of 2026-08-02, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.jsindex bb34684ac..e0b091b49 100644--- a/api/_lib/solana/connection.js+++ b/api/_lib/solana/connection.js@@ -348,34 +348,54 @@ function publishCooldowns(now) {.catch(() => {});}-// Every way a provider says "not THIS call" while staying perfectly healthy for-// every other call. Three distinct phrasings live here because three distinct-// mechanisms produce them, and all three were previously scattered across two-// near-duplicate matchers that disagreed about which strings counted:-//-// • POLICY BLOCK — the node is configured to refuse a shape.-// PublicNode getTokenAccountsByOwner → `Request blocked. Details: blocked-// parameter: params.1.programId`; PublicNode getProgramAccounts → `… excluded-// from account secondary indexes; this RPC method unavailable for key`;-// MagicBlock getProgramAccounts → `Your IP or provider is blocked from this-// endpoint`.-// • TIER GATE — the method exists but the keyless/free plan may not call it.-// Tatum getBalance / getSignaturesForAddress → `available for paid plans only`.-// • METHOD DISABLED — an operator switched the shape off on that node.-//-// All three are lane-and-method specific: the next lane serves the same call-// normally, and this lane serves every other call normally. That is precisely the-// signature of a METHOD demotion, never of a lane bench, and never of an auth-// fault. Matching on wording (not on the JSON-RPC code) is deliberate: PublicNode-// returns -32602 for a policy block, the same code a genuine invalid-params error-// uses, and a genuine invalid-params error must NOT demote anything because every-// lane would reject it identically.-const METHOD_REFUSAL =- /request blocked|blocked parameter|excluded from account secondary indexes|this rpc method unavailable|blocked from this endpoint|method .*(?:not supported|is not available|disabled)|not available for anonymous access|available for paid plans only|upgrade your subscription|please register at/i;+// A provider refusing one CALL SHAPE, naming the shape in the refusal. The node is+// healthy and the credential is fine; this request, and only this request, cannot+// be served here. Measured phrasings:+// • PublicNode getTokenAccountsByOwner → `Request blocked. Details: blocked+// parameter: params.1.programId`+// • PublicNode getProgramAccounts → `… excluded from account secondary indexes;+// this RPC method unavailable for key`+// • an operator-disabled method → `method <x> is not available`+// Matching on wording rather than on the JSON-RPC code is deliberate: PublicNode+// returns -32602 for its policy block, the same code a genuine invalid-params+// error uses, and a genuine invalid-params error must never demote anything+// because every lane rejects it identically.+const CALL_SHAPE_REFUSAL =+ /request blocked|blocked parameter|excluded from account secondary indexes|this rpc method unavailable|method .*(?:not supported|is not available|disabled)/i;-/** True when `text` is a provider refusing one call shape rather than the caller. */+// A provider refusing the CALLER: our address, our plan, our lack of a key,+// rather than the call. The wording is the trap: the SAME sentence is emitted+// per-method by a healthy node and caller-wide by a node that has banned us.+// Measured 2026-08-01 with scripts/probe-rpc-lanes.mjs: MagicBlock and+// api.mainnet-beta.solana.com both answer `Your IP or provider is blocked from+// this endpoint` for getProgramAccounts alone while serving all six other shapes,+// and Tatum answers `available for paid plans only` for three shapes while still+// serving getLatestBlockhash and getSignatureStatuses. Nothing in the message+// separates those from a real ban, so the text cannot decide it; only the BREADTH+// can, which is what the rotating fetch's escalation counter measures. Benching the+// lane on first sight would have parked our best free primary (MagicBlock) for 30+// minutes over one holder-census call.+const CALLER_REFUSAL =+ /blocked from this endpoint|not available for anonymous access|available for paid plans only|upgrade your subscription|please register at/i;++/**+ * True when `text` is a provider declining to serve this request for a reason the+ * NEXT lane will not share and that says nothing about our credential, so the+ * request rotates and the (lane, method) pair is demoted, not the lane.+ */export function isMethodRefusal(text) {- return METHOD_REFUSAL.test(text || '');+ const t = text || '';+ return CALL_SHAPE_REFUSAL.test(t) || CALLER_REFUSAL.test(t);+}++/**+ * True when `text` names a call shape the node refuses. Narrower than+ * isMethodRefusal on purpose: this is the question cooldownMsFor asks once a lane+ * IS being benched, where a caller refusal must take the full auth window (it will+ * refuse the next request too) and a shape refusal must not.+ */+function isCallShapeRefusal(text) {+ return CALL_SHAPE_REFUSAL.test(text || '');}function cooldownMsFor(status, bodyText) {@@ -412,7 +432,7 @@ function cooldownMsFor(status, bodyText) {// the lane keeps serving every other call shape with no cooldown at all. The// branch stays because markEndpointCooldown is exported and must still classify// a blocked call shape as the cheapest window rather than a 30m auth bench.- if (status === 403 && isMethodRefusal(bodyText)) return NETWORK_COOLDOWN_MS;+ if (status === 403 && isCallShapeRefusal(bodyText)) return NETWORK_COOLDOWN_MS;if (status === 401 || status === 403) return AUTH_COOLDOWN_MS;// 404/410: the endpoint URL is dead or misrouted (expired Quicknode/Alchemy// app, wrong path) — a persistent misconfiguration, so park it like an auth@@ -492,14 +512,43 @@ export function isAnyMethodDemoted(url, methods) {return methods.some((m) => isMethodDemoted(url, m));}+/** How many distinct methods `url` is currently demoted for. */+export function methodDemotionBreadth(url, now = Date.now()) {+ let n = 0;+ const prefix = `${url} `;+ for (const [key, until] of _methodDemotion) {+ if (until > now && key.startsWith(prefix)) n++;+ }+ return n;+}++// A node refusing the CALLER and a node refusing a CALL SHAPE use the same words+// (see CALLER_REFUSAL). Breadth is the only thing that tells them apart: a real IP+// ban or a dead free tier refuses everything we ask, a policy block refuses one or+// two shapes and serves the rest. Measured 2026-08-01, the widest LEGITIMATE+// refusal set on any lane we run is three (Tatum's free tier gates getBalance,+// getTokenAccountsByOwner and getProgramAccounts while still serving+// getLatestBlockhash and getSignatureStatuses, which are worth keeping). A lane+// past that is refusing us, not a shape, so it earns the full lane bench instead of+// leaking one wasted request per method per window.+const DEMOTION_BREADTH_BENCH = 4;+/**- * Demote `url` for each of `methods` for METHOD_DEMOTION_MS. Returns the window- * so the caller can log it. Never touches the lane cooldown.+ * Demote `url` for each of `methods` for METHOD_DEMOTION_MS, and bench the whole+ * lane if the demotions have spread wide enough to mean the node is refusing us+ * rather than a call shape. Returns `{ ms, benched }` so the caller can log which+ * of the two happened.*/export function markMethodDemotion(url, methods, now = Date.now()) {const until = now + METHOD_DEMOTION_MS;for (const m of methods) _methodDemotion.set(methodKey(url, m), until);- return METHOD_DEMOTION_MS;+ if (methodDemotionBreadth(url, now) >= DEMOTION_BREADTH_BENCH) {+ // AUTH_COOLDOWN_MS, and marked through markEndpointCooldown, so this park is+ // published fleet-wide exactly like any other caller-level rejection. A node+ // that has banned our egress IP has banned every instance's.+ return { ms: markEndpointCooldown(url, 403, 'caller refused on every call shape'), benched: true };+ }+ return { ms: METHOD_DEMOTION_MS, benched: false };}/**@@ -932,12 +981,14 @@ export function makeRotatingFetch(endpoints) {const penalise = (url, status, bodyText, methodBlock, log) => {if (methodBlock && methods.length) {const fresh = methods.filter((m) => !isMethodDemoted(url, m));- const ms = markMethodDemotion(url, methods);+ const { ms, benched } = markMethodDemotion(url, methods);// Only the first caller to hit the refusal logs it; the rest see the// demotion already in place and stay quiet.if (fresh.length) {console.log(- `[solana-rpc] ${maskUrl(url)} refused ${fresh.join(',')}, demoting that method for ${formatCooldown(ms)}, failing over`,+ benched+ ? `[solana-rpc] ${maskUrl(url)} refused ${fresh.join(',')} and ${DEMOTION_BREADTH_BENCH}+ shapes in all, refusing the caller, not the call; cooling ${formatCooldown(ms)}, failing over`+ : `[solana-rpc] ${maskUrl(url)} refused ${fresh.join(',')}, demoting that method for ${formatCooldown(ms)}, failing over`,);}return;diff --git a/api/_lib/x402/agents/persona-kit.js b/api/_lib/x402/agents/persona-kit.jsindex abfe7b789..154ec366f 100644--- a/api/_lib/x402/agents/persona-kit.js+++ b/api/_lib/x402/agents/persona-kit.js@@ -27,6 +27,11 @@// row (`persona` + `internal:true`), never presented as organic users.import { PublicKey } from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';import { payX402, USDC_MINT } from '../pay.js';import {@@ -48,6 +53,7 @@ import {isRingAddress,summarizeLiveness,buildUrl,+ assessAgentBuyingPower,} from './persona-math.js';export {@@ -59,12 +65,61 @@ export {isRingAddress,summarizeLiveness,buildUrl,+ assessAgentBuyingPower,};// ── Guarded purchase path ──────────────────────────────────────────────────────const ATOMIC_PER_USD = 1_000_000;+// One tick's worth of buyer-balance reads. The driver runs every persona in the+// same tick against the same RPC context, and a persona may make several buys,+// so without this the pre-flight check would re-read the same ATA repeatedly.+// Deliberately shorter than the ring tick's cadence (60s), so a float top-up+// between ticks is visible immediately.+const USDC_BALANCE_CACHE_MS = 15_000;+const _usdcCache = new Map(); // addressB58 → { atomic, at }++/** Test seam: drop cached buyer balances. */+export function resetAgentUsdcCache() {+ _usdcCache.clear();+}++/**+ * Read one agent's USDC balance in atomic units, or null when it cannot be read.+ * null is NOT zero: a missing ATA is a genuine zero, but an RPC failure is an+ * unknown, and assessAgentBuyingPower() admits on unknown rather than freezing a+ * funded agent behind a lane outage.+ *+ * @param {any} conn Solana connection+ * @param {string} address buyer wallet, base58+ * @returns {Promise<number|null>}+ */+export async function readAgentUsdcAtomic(conn, address) {+ if (!conn || !address || !USDC_MINT) return null;+ const hit = _usdcCache.get(address);+ const now = Date.now();+ if (hit && now - hit.at < USDC_BALANCE_CACHE_MS) return hit.atomic;++ let atomic;+ try {+ const ata = getAssociatedTokenAddressSync(+ new PublicKey(USDC_MINT), new PublicKey(address),+ false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const bal = await conn.getTokenAccountBalance(ata, 'confirmed');+ atomic = Number(bal?.value?.amount ?? 0);+ if (!Number.isFinite(atomic)) atomic = null;+ } catch (err) {+ // An ATA that does not exist yet is a real, knowable zero. Anything else+ // (rate limit, lane cooldown, timeout) is unknown and must fail open.+ const msg = String(err?.message || err);+ atomic = /could not find account|account does not exist|Invalid param/i.test(msg) ? 0 : null;+ }+ _usdcCache.set(address, { atomic, at: now });+ return atomic;+}+/*** Execute ONE persona purchase through the full guard chain. Never throws — every* failure (spend-limit refusal, allowlist miss, protocol/network fault) is@@ -75,6 +130,10 @@ const ATOMIC_PER_USD = 1_000_000;* 1. enforceSpendLimit({ category:'x402', usdValue }) — the agent's own caps.* A SpendLimitError is caught and surfaced as { status:'refused' }, NOT* rethrown (the tick continues; the refusal is logged + custody-recorded).+ * 1b. assessAgentBuyingPower(), does the buyer's own USDC cover the price?+ * A dry wallet refuses here (`insufficient_payer_usdc`, the same benign+ * back-pressure token the shared ring payer reports) instead of paying for+ * a probe, a signature and a facilitator simulation to be told no.* 2. Probe the endpoint's 402 challenge via payX402 to learn payTo, then assert* payTo ∈ ringAllowedAddresses(). A non-ring recipient is refused BEFORE any* payment (defence in depth over the facilitator's own payTo allowlist).@@ -84,6 +143,8 @@ const ATOMIC_PER_USD = 1_000_000;** @param {object} p* @param {{ id:string, name?:string, address:string, keypair:import('@solana/web3.js').Keypair, meta?:object }} p.agent+ * `address` is the buyer wallet the pre-flight balance check reads; omit it and+ * the check admits (fail-open), exactly as an unreadable balance does.* @param {{ slug:string, url:string, method:string, body:any, priceAtomic:number, kind:string, memo?:string }} p.purchase* @param {{ conn:any, blockhash:string, mintInfo:any }} p.solana* @param {Set<string>} p.allowed pre-resolved ringAllowedAddresses()@@ -139,6 +200,21 @@ export async function executePurchase({ agent, purchase, solana, allowed, personreturn done({ status: 'error', reason: `enforce_error:${String(err?.message || err).slice(0, 120)}` });}+ // 1b: can this agent actually pay? The persona's own wallet funds the+ // transfer, and when the float top-up upstream is dry that wallet runs to+ // zero. Shopping anyway costs a probe, a signature and a facilitator `verify`+ // that simulates against an RPC node, and returns a 402 the settle sensor+ // counts as a payment-rail fault. Ask first, refuse cleanly, spend nothing.+ // Fails OPEN: an unreadable balance admits, and the simulation downstream is+ // still the authoritative check.+ const buyingPower = assessAgentBuyingPower({+ usdcAtomic: await readAgentUsdcAtomic(solana.conn, agent.address),+ priceAtomic: purchase.priceAtomic || 0,+ });+ if (!buyingPower.ok) {+ return done({ status: 'refused', reason: `${buyingPower.reason}:${buyingPower.detail}` });+ }+// 2 — probe first so we can allowlist the recipient BEFORE paying. payX402// returns a structured outcome; a thrown fault is caught below.let result;diff --git a/api/_lib/x402/agents/persona-math.js b/api/_lib/x402/agents/persona-math.jsindex 92eebd764..c89c50e5c 100644--- a/api/_lib/x402/agents/persona-math.js+++ b/api/_lib/x402/agents/persona-math.js@@ -118,6 +118,10 @@ export function planFloatMove({ balanceAtomic, floorAtomic, targetAtomic, ceilin* @returns {{ ok: boolean, reason: string|null, detail?: string }}*/export function assessAgentBuyingPower({ usdcAtomic, priceAtomic }) {+ // null/undefined is UNKNOWN, and `Number(null)` is 0, which would read as+ // "broke" and refuse a funded agent every time a balance read failed. Reject+ // the nullish case before the numeric one.+ if (usdcAtomic == null) return { ok: true, reason: null };const have = Number(usdcAtomic);if (!Number.isFinite(have)) return { ok: true, reason: null };const need = Math.max(0, Number(priceAtomic) || 0);diff --git a/api/_lib/x402/runway-sim.js b/api/_lib/x402/runway-sim.jsindex 9bcab2fa7..f4f729ae0 100644--- a/api/_lib/x402/runway-sim.js+++ b/api/_lib/x402/runway-sim.js@@ -84,7 +84,10 @@ export function simulateRunway(input = {}) {const hours = Math.min(24 * 90, Math.max(1, int(input.hours, 24 * 7)));const governorEnabled = input.governorEnabled !== false;const startHourOfDay = ((int(input.startHourOfDay) % 24) + 24) % 24;- const paceDay = input.paceDay !== false;+ // Opt-in, matching walletFeeGovernorConfig().paceDay: the lab must default to+ // the shape production actually runs, or its verdicts describe a rail nobody+ // is on.+ const paceDay = input.paceDay === true;const paceMinSliceLamports = Math.max(0, int(input.paceMinSliceLamports, 200_000));// The budget the wallet may draw on at a given hour of the UTC day. Mirrorsdiff --git a/package.json b/package.jsonindex 5d4819152..e7502b0be 100644--- a/package.json+++ b/package.json@@ -292,6 +292,7 @@"worker:sniper:live": "SNIPER_MODE=live node workers/agent-sniper/index.js","worker:orders": "node workers/agent-orders/index.js","worker:orders:live": "ORDERS_MODE=live node workers/agent-orders/index.js",+ "worker:okx-bot": "node workers/okx-chat-bot/index.js","worker:mm": "node workers/agent-mm/index.js","worker:mm:live": "MM_MODE=live node workers/agent-mm/index.js","worker:okx-bot": "node workers/okx-chat-bot/index.js",diff --git a/prompts/backlog/PROGRESS.md b/prompts/backlog/PROGRESS.mdindex 6c63c71df..124b03cc7 100644--- a/prompts/backlog/PROGRESS.md+++ b/prompts/backlog/PROGRESS.md@@ -152,3 +152,70 @@ Left (all owner-gated, none of it config):PLAINTEXT env var on the Cloud Run service, while `X402_FEE_PAYER_SECRET_BASE58`beside it is a Secret Manager `secretRef`. Any principal with `run.services.get`can read that master wallet key. Recommend rotate + move to Secret Manager.++## 2026-08-02: 03 sponsor-runway-automation (code complete, capital owner-gated)+Measured, before (`/api/ops/payment-outcomes` with the ops secret from Secret+Manager `ops-dashboard-secret`, plus `curl /api/x402/three-intel | jq+'.accepts[].network'`): sponsor `WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW`+at 0.0108 SOL, settle floor 0.002 (prod `X402_SPONSOR_SOL_FLOOR_LAMPORTS=2000000`,+not the 0.02 code default), measured burn 0.058981 SOL/day over 7d from 50,001+successful settles, runway 0.2d. Accepts carried BOTH networks; the settle sensor+read `cause: rail`. Fifteen minutes later, mid-verification, the same wallet+crossed its floor: 0.0018556 SOL, accepts collapsed to `['eip155:8453']` only,+and the sensor flipped to `cause: sponsor_floor` with `noSolanaAccept: 148`.+The failure this work order describes reproduced live, and the new sensor named+it correctly in both regimes without a code change between the two reads.++Did:+- New `api/_lib/x402/sponsor-runway.js`: `measureSponsorBurn()` (fee_lamports over+ a parameterised window, fail-soft), `computeSponsorRunway()` and+ `formatSponsorRunwayAlert()` (both pure). Runway is reported twice: `runway_days`+ to empty (what a funding ask is sized against) and `runway_days_to_floor`, which+ is what the status and the alert key off, because settling stops at the floor.+- `checkRingWallets()` now measures the burn every 10-minute tick and fires the+ alert through `sendOpsAlert` (dashboard row always, Telegram when wired).+ Thresholds: `X402_SPONSOR_RUNWAY_ALERT_DAYS` (3), `X402_SPONSOR_BURN_WINDOW_DAYS`+ (7). `unknown` (unreadable balance, or an idle rail with no measurable burn)+ never pages. The dashboard read passes a no-op sender, so it still cannot alert.+- `/api/ops/payment-outcomes` and the `/admin/ops` card now consume that one+ verdict instead of recomputing burn, so the board and the alert can never+ disagree. Both floors are reported separately: `settle_floor_sol` (where+ settling stops) and `sol_floor` (the ring's 1.5x watch floor).+- `recordAgentReclaim()` / `buildAgentReclaimRows()` in `economy-ledger.js`, called+ from `treasury-topup`: `inflow` per return, `inflow_failed` per failure with the+ stage (`read` / `recover` / `send`), and an `agent_reclaim` summary written even+ on a no-op, so "ran and found nothing" (`nothing_reclaimable`, needs money) and+ "could not run" (`blocked`, an RPC or key problem, free) stop being the same+ absence of rows. Read-error rows capped at 20/run with the true count kept in the+ summary. The chain-append loop was extracted and is now shared by all three+ recorders.+- Tests: `tests/x402-sponsor-runway.test.js` (14, arithmetic + the rendered alert+ string), `tests/x402-sponsor-runway-monitor.test.js` (6, that the monitor+ actually sends it), 7 added to `tests/economy-sweepback.test.js` for the ledger+ rows. Docs: `docs/ops/payment-outcomes.md` (thresholds table, statuses, why+ `unknown` never pages), `docs/x402-ring-economy.md`. Changelog entry (infra).+- Verified end to end against the real DB and live chain, not only in unit tests:+ the endpoint returned `runway_status: critical` and the `/admin/ops` card+ rendered `settle floor 0.002 - burn 0.058279/day over 7d (49557 settles) -+ runway 0d to floor (alerts under 3d)` in a headless browser, no console errors+ from page code.++Gate: `check:rules` clean on the 11 files (diff-scoped). `test:gate` 86/86,+`test:gate-3d` 527/527, all MCP/route/handler/page/x402/guard audits pass. Three+pre-existing reds, none mine and none regressed: `workers/okx-chat-bot` has no+README (another agent's WO-08, in flight), `pages/ghost-copy.html` has 1 token-hex+drift (another agent), and `audit:tour-atlas` reports the same 17 problems at base+commit `6cc0370dc` (verified in a detached worktree).++Left, both stop-and-ask gate 1, numbers rendered for the owner:+1. **Free first, no owner money.** `POST /api/cron/treasury-topup?dry=1` plans+ 0.122875505 SOL reclaimable into the master from two platform agent wallets+ (`Atlas #22` 6FL9viFy2WrYMWPd3HAQA4Bxm5qxQWoQMn3T9GbcwxEB 0.068390963 SOL,+ `Echo #22` 8u5raEaz7Qjm5hRzNxwzXiZtjTkdgQ3Co6G6S5WNxFTs 0.054484542 SOL), 0 read+ errors, 110 sources at floor. That is ~2 days at the measured burn. Firing it+ non-dry moves funds and needs an explicit yes.+2. **Capital.** 0.816 SOL to the SPONSOR or the economy master buys 14 days at the+ measured 0.0583 SOL/day. Never per-agent wallets. Note the master IS the+ sponsor here (same address, same balance).+3. **Deploy.** Production runs `6cc0370dc`; every item above ships with the next+ deploy, which is owner-gated. Until then the alert is dormant.diff --git a/prompts/okx-ai/05-relisting-resubmission.md b/prompts/okx-ai/05-relisting-resubmission.mdindex 8b2d2c2df..ea44d16fd 100644--- a/prompts/okx-ai/05-relisting-resubmission.md+++ b/prompts/okx-ai/05-relisting-resubmission.md@@ -31,15 +31,24 @@ Then be the reviewer for an hour, against production:```bashcurl -s https://three.ws/api/okx/3d/catalog | python3 -m json.tool | head -80-for s in $(node scripts/okx-listing-payload.mjs --slugs 2>/dev/null || echo text-to-3d); do++# probe every advertised endpoint unpaid, slugs read from the live catalog itself+for s in $(curl -s https://three.ws/api/okx/3d/catalog \+ | python3 -c "import sys,json;[print(x['endpoint'].rsplit('/',1)[-1]) for x in json.load(sys.stdin)['services']]"); doecho "== $s"; curl -si -X POST "https://three.ws/api/okx/3d/$s" \-H 'content-type: application/json' -d '{}' | head -12done+onchainos agent get-agents --agent-ids 2632-onchainos agent service-list --agent-id 2632-node scripts/okx-listing-payload.mjs --delta # feed it the service-list output per its usage+node scripts/okx-listing-payload.mjs | head -40 # the 11 create-format entries+onchainos agent service-list --agent-id 2632 \+ | node scripts/okx-listing-payload.mjs --delta # the full replace delta```+`scripts/okx-listing-payload.mjs` takes the live `service-list` output on stdin and supports+`--delta` and `--briefing` only. Adjust the slug extraction above if the catalog's JSON shape+has moved; the point is that the slugs come from the live catalog, never from this file.+1. Every endpoint in the catalog returns an OKX-valid 402 unpaid (or free content for the freelane). Any drift from what OKX-04 recorded: stop and fix that first.2. Three-way string diff: catalog module (`api/_lib/okx-catalog.js`), the live catalog endpoint,diff --git a/prompts/quality-bar/06-forge-ux-flow.md b/prompts/quality-bar/06-forge-ux-flow.mdindex fadc4159e..d90f259a3 100644--- a/prompts/quality-bar/06-forge-ux-flow.md+++ b/prompts/quality-bar/06-forge-ux-flow.md@@ -22,7 +22,7 @@ share-worthy 3D result should be legible, alive, and impossible to dead-end.npm run dev # port 3000, then walk /forge as a first-time user in a real browserls src/forge-compare.js src/forge-prompt-gen.js api/_lib/forge-lane-health.jsgrep -n "starter\|chip" pages/forge.html | head -20-npm run audit:web -- --only /forge 2>/dev/null || node scripts/page-audit.mjs+npm run audit:web -- /forge # page-audit takes explicit routes as positional args```Known shipped as of 2026-07-30, verify then skip: generation history persistence, thediff --git a/prompts/store-submissions/01-submission-closeout.md b/prompts/store-submissions/01-submission-closeout.mdindex 6bb912614..16129b560 100644--- a/prompts/store-submissions/01-submission-closeout.md+++ b/prompts/store-submissions/01-submission-closeout.md@@ -39,10 +39,21 @@ curl -s -X POST https://three.ws/api/mcp-studio -H 'content-type: application/jscurl -sI "https://three.ws/legal/privacy" | head -3curl -sI "https://three.ws/support" | head -3npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-catalog && npm run audit:mcp-safety-node scripts/build-mcp-listing-source.mjs && node scripts/build-mcp-directory-docs.mjs+ls scripts/ | grep -i mcp # the live generator set; see the note belowgit diff --stat prompts/store-submissions/_generated/```+**Generator note, verified 2026-08-01:** the two scripts the tracker's older entries name+(`build-mcp-listing-source.mjs`, `build-mcp-directory-docs.mjs`) no longer exist in the tree and+nothing else writes `_generated/mcp-listing-source.json` any more, so that file and+`_generated/mcp-registry-republish.sh` are now hand-maintained artifacts. The live tooling is+`npm run build:mcp-catalog` (writes `public/mcp-catalog.json`, gated by `audit:mcp-catalog`),+`npm run audit:mcp` (manifests), `npm run audit:mcp-golden` (contract snapshot) and+`npm run audit:mcp-safety` (annotations derived from each handler's AST). Reconcile the+`_generated/` artifacts against the real `server*.json` manifests plus `public/mcp-catalog.json`+by hand, and say in the tracker that they are hand-maintained, so the next agent does not go+looking for a generator that was retired.+Rewrite `_generated/TRACKER.md` from what you measured. Every row gets a status, today's date,and the command that produced it. Any claim you cannot reproduce is downgraded, not carriedforward.@@ -66,10 +77,13 @@ forward.## Task 2: keep the surfaces consistent-- The canonical metadata source is `_generated/mcp-listing-source.json`. Regenerate it and the- per-directory docs, and commit only if the output actually changed.-- `_generated/mcp-registry-republish.sh` holds the staged `mcp-publisher` commands. Regenerate- it against the live registry so the batch is accurate, and leave it unrun.+- `_generated/mcp-listing-source.json` is the canonical listing metadata and is hand-maintained+ (see the generator note above). Reconcile it against the real `server*.json` manifests, the+ live `tools/list` counts you captured in Step 0, and `public/mcp-catalog.json`. Commit only if+ something actually changed.+- `_generated/mcp-registry-republish.sh` holds the staged `mcp-publisher` commands. Check each+ entry against the live registry (`https://registry.modelcontextprotocol.io/?q=io.github.nirholas`)+ so the batch is accurate, and leave it unrun.- Compliance grep across manifests, directory docs and the canonical source: zero references toany crypto project other than `$THREE`, and zero coin surface anywhere in the OpenAI lane.- `STRUCTURE.md` and `docs/mcp.md` server counts must match the canonical source. Fix drift indiff --git a/scripts/check-gcloudignore.mjs b/scripts/check-gcloudignore.mjsindex 5fcf9be9c..de7da74cf 100644--- a/scripts/check-gcloudignore.mjs+++ b/scripts/check-gcloudignore.mjs@@ -115,6 +115,11 @@ const REQUIRED = [{ path: 'agents', kind: 'dir', why: 'api/x402/fact-check.js + tutor.js import ../../agents/*' },{ path: 'agent-payments-sdk', kind: 'dir', why: 'copied by the sniper image build' },{ path: 'data', kind: 'dir', why: 'handlers read data/*.json at runtime' },+ {+ path: 'tests/fixtures/fact-check-benchmark.json',+ kind: 'file',+ why: 'api/fact-check-benchmark.js renders it; api/cron/fact-check-benchmark.js runs it',+ },{ path: 'public', kind: 'dir', why: 'static assets served by the container' },];diff --git a/scripts/verify-sign-avatar.mjs b/scripts/verify-sign-avatar.mjsindex 0bfba4b5c..af5e77436 100644--- a/scripts/verify-sign-avatar.mjs+++ b/scripts/verify-sign-avatar.mjs@@ -19,7 +19,12 @@ function check(label, ok, detail = '') {}}-const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'] });+// Software WebGL, and /dev/shm off: a container's default 64 MB shared memory+// segment is not enough for a GLB-heavy renderer, which shows up as a bare+// "Page crashed" rather than any error the page could report.+const browser = await chromium.launch({+ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--disable-dev-shm-usage'],+});const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });// A shared dev server restarts under other work; give navigation and the first// module transform room rather than reporting a cold cache as a broken page.diff --git a/tests/api/fact-check-benchmark.test.js b/tests/api/fact-check-benchmark.test.jsindex ceaf662cc..7d097e393 100644--- a/tests/api/fact-check-benchmark.test.js+++ b/tests/api/fact-check-benchmark.test.js@@ -10,7 +10,12 @@ import { readFileSync } from 'node:fs';import { fileURLToPath } from 'node:url';import { dirname, join } from 'node:path';-import { scoreResults, validateFixture } from '../../scripts/fact-check-benchmark.mjs';+import {+ isDegraded,+ runClaims,+ scoreResults,+ validateFixture,+} from '../../api/_lib/fact-check-benchmark.js';const HERE = dirname(fileURLToPath(import.meta.url));const fixture = JSON.parse(readFileSync(join(HERE, '../fixtures/fact-check-benchmark.json'), 'utf8'));@@ -94,3 +99,89 @@ describe('scoreResults', () => {expect(scoreResults(zero).errors).toBe(fixture.claims.length);});});++describe('isDegraded', () => {+ // The refusal exists because a run that mostly errored measures provider+ // availability, not verdict accuracy: publishing it states a false accuracy+ // figure for a paid product.+ it('passes a clean run and a run at exactly the 10% ceiling', () => {+ expect(isDegraded({ total: 40, errors: 0 })).toBe(false);+ expect(isDegraded({ total: 40, errors: 4 })).toBe(false);+ });++ it('refuses a run above the ceiling, and an empty run', () => {+ expect(isDegraded({ total: 40, errors: 5 })).toBe(true);+ expect(isDegraded({ total: 40, errors: 30 })).toBe(true);+ expect(isDegraded({ total: 0, errors: 0 })).toBe(true);+ });+});++describe('runClaims', () => {+ const claims = Array.from({ length: 9 }, (_, i) => ({+ claim: `claim ${i}`,+ expected_verdict: 'supported',+ difficulty: 'easy',+ }));++ it('runs every claim and preserves fixture order regardless of completion order', async () => {+ // Reverse the latency so later claims finish first: results must still line+ // up with the input, otherwise the confusion matrix attributes verdicts to+ // the wrong claims.+ const results = await runClaims(+ claims,+ async (claim) => {+ const i = Number(claim.split(' ')[1]);+ await new Promise((r) => setTimeout(r, (claims.length - i) * 2));+ return `v${i}`;+ },+ { concurrency: 4 },+ );+ expect(results.map((r) => r.claim)).toEqual(claims.map((c) => c.claim));+ expect(results.map((r) => r.actual_verdict)).toEqual(claims.map((_, i) => `v${i}`));+ });++ it('never exceeds the concurrency cap', async () => {+ let inFlight = 0;+ let peak = 0;+ await runClaims(+ claims,+ async () => {+ peak = Math.max(peak, ++inFlight);+ await new Promise((r) => setTimeout(r, 5));+ inFlight--;+ return 'supported';+ },+ { concurrency: 3 },+ );+ expect(peak).toBeLessThanOrEqual(3);+ });++ it('records a thrown claim as an error rather than dropping it', async () => {+ const results = await runClaims(+ claims,+ async (claim) => {+ if (claim === 'claim 2') throw new Error('provider down');+ return 'supported';+ },+ { concurrency: 2 },+ );+ expect(results).toHaveLength(claims.length);+ expect(results[2].actual_verdict).toBeNull();+ expect(scoreResults(results).errors).toBe(1);+ });++ it('counts deadline-cut claims as errors, so a truncated run trips the refusal', async () => {+ const results = await runClaims(+ claims,+ async () => {+ await new Promise((r) => setTimeout(r, 30));+ return 'supported';+ },+ { concurrency: 1, deadlineMs: 45 },+ );+ expect(results).toHaveLength(claims.length);+ const score = scoreResults(results);+ expect(score.errors).toBeGreaterThan(0);+ expect(isDegraded(score)).toBe(true);+ });+});diff --git a/tests/api/llm-free-chain-reachability.test.js b/tests/api/llm-free-chain-reachability.test.jsindex 86d2eca8d..d181e20b8 100644--- a/tests/api/llm-free-chain-reachability.test.js+++ b/tests/api/llm-free-chain-reachability.test.js@@ -124,23 +124,22 @@ describe('free chain: every rung is reachable through a transport-level failure'for (const [i, rung] of FREE_CHAIN.entries()) {it(`reaches ${rung.provider} when the ${i} rung(s) above it fail at the transport level`, async () => {configureFreeLanes();- const above = FREE_CHAIN.slice(0, i);const tried = [];- globalThis.fetch = vi.fn(async (url) => {+ globalThis.fetch = vi.fn(async (url, opts) => {const u = String(url);- // The two Groq rungs share a host, so match on the requested model to- // tell them apart. Everything else is one host per rung.- const idx = FREE_CHAIN.findIndex((r) => u.includes(r.host));- const hit = FREE_CHAIN.find((r) => u.includes(r.host));- expect(hit, `unexpected fetch: ${u}`).toBeTruthy();- tried.push(hit.provider);+ // The two Groq rungs share a host, so a rung is identified by+ // host AND requested model. Matching on host alone would make the 70B+ // lane and the instant lane indistinguishable, which is exactly the+ // pair this suite has to tell apart.+ const requested = JSON.parse(opts.body).model;+ const idx = FREE_CHAIN.findIndex((r) => u.includes(r.host) && r.model === requested);+ expect(idx, `unexpected fetch: ${u} (${requested})`).toBeGreaterThanOrEqual(0);+ tried.push(FREE_CHAIN[idx].provider);// A rung above the target dies at the transport level. Alternate the// two shapes so both a dropped socket and an abort are covered.- if (idx < i || (idx === i && tried.filter((t) => t === hit.provider).length <= above.filter((a) => a.provider === hit.provider).length)) {- throw transportFailure(idx % 2 === 0 ? 'reset' : 'abort');- }- return okOpenAiShape(`served by ${hit.provider}`, rung.model);+ if (idx < i) throw transportFailure(idx % 2 === 0 ? 'reset' : 'abort');+ return okOpenAiShape(`served by ${FREE_CHAIN[idx].provider}`, rung.model);});const out = await llm.llmComplete({ system: 's', user: 'u', timeoutMs: 30_000 });diff --git a/tests/avatar-studio-save.test.js b/tests/avatar-studio-save.test.jsindex 0508910f7..49695d118 100644--- a/tests/avatar-studio-save.test.js+++ b/tests/avatar-studio-save.test.js@@ -114,7 +114,19 @@ describe('collapseAppearance', () => {// ── hydrateAppearance ─────────────────────────────────────────────────────────-const EMPTY = { outfit: null, accessories: [], morphs: {}, colors: {}, hidden: [], garments: [] };+// `proportions` is the skeleton-space body build (src/avatar-proportions.js).+// hydrateAppearance normalizes it like every other field, so the empty shape+// carries it too: a saved record from before the parametric editor shipped+// hydrates to `{}` rather than to a missing key.+const EMPTY = {+ outfit: null,+ accessories: [],+ morphs: {},+ colors: {},+ hidden: [],+ garments: [],+ proportions: {},+};describe('hydrateAppearance', () => {it('returns defaults for null', () => {@@ -145,10 +157,20 @@ describe('hydrateAppearance', () => {colors: { hair: '#0e0e0e' },hidden: ['outfit'],garments: [{ slot: 'outerwear', id: 'parka' }],+ proportions: { height: 1.08 },};expect(hydrateAppearance(raw)).toEqual(raw);});+ it('normalises proportions: neutral values drop out, unknown params are ignored', () => {+ // normalizeProportions keeps only known params that differ from neutral+ // (1), so a body saved at its defaults hydrates to {} rather than to a+ // record full of 1s that would compare unequal to "no build set".+ expect(hydrateAppearance({ proportions: { height: 1 } }).proportions).toEqual({});+ expect(hydrateAppearance({ proportions: { notAParam: 1.4 } }).proportions).toEqual({});+ expect(hydrateAppearance({ proportions: 'nope' }).proportions).toEqual({});+ });+it('copies arrays — mutations do not affect the source', () => {const raw = { accessories: ['hat-01'], morphs: {}, colors: {}, hidden: [] };const result = hydrateAppearance(raw);diff --git a/tests/llm-pricing-openrouter.test.js b/tests/llm-pricing-openrouter.test.jsnew file mode 100644index 000000000..4d9cdc4a9--- /dev/null+++ b/tests/llm-pricing-openrouter.test.js@@ -0,0 +1,118 @@+// The metering rule this file locks in: a lane that spends money must never+// report exactly $0.+//+// The defect it guards against was live and expensive. `openrouter` was on the+// blanket free-provider list, and OpenRouter namespaces every model by vendor+// (`anthropic/claude-opus-5`), which matched no key in the price table. So a+// $5/$25-per-MTok Claude turn on the platform key priced to 0 twice over, and+// the $30 balance drained with the dashboard reporting "served free" the whole+// way down. $0 and "we could not price it" must be different answers.++import { describe, it, expect } from 'vitest';+import {+ costMicroUsd,+ isPriced,+ isFreeLane,+ openRouterBaseId,+ isOpenRouterFreeModel,+} from '../api/_lib/llm-pricing.js';++describe('OpenRouter is free only on its :free routes', () => {+ it('prices a :free model at 0 on every key rung', () => {+ for (const provider of ['openrouter', 'openrouter#2', 'openrouter#3']) {+ expect(costMicroUsd({ provider, model: 'openai/gpt-oss-20b:free', input: 100_000, output: 50_000 })).toBe(0);+ }+ });++ it('prices a paid vendor mirror at the underlying model, not 0', () => {+ // 1M in / 1M out of Opus 5 at $5/$25 = $30.00 = 30,000,000 micro-USD.+ const cost = costMicroUsd({+ provider: 'openrouter',+ model: 'anthropic/claude-opus-5',+ input: 1_000_000,+ output: 1_000_000,+ });+ expect(cost).toBe(30_000_000);+ });++ it('resolves a dotted mirror id to its first-party price', () => {+ // OpenRouter writes Haiku 4.5 as `claude-haiku-4.5`; the table keys it+ // `claude-haiku-4-5`. $1/$5 per MTok.+ expect(costMicroUsd({ provider: 'openrouter', model: 'anthropic/claude-haiku-4.5', input: 1_000_000, output: 0 })).toBe(1_000_000);+ expect(isPriced('anthropic/claude-haiku-4.5')).toBe(true);+ });++ it('prices the OpenAI and xAI mirrors too', () => {+ expect(costMicroUsd({ provider: 'openrouter', model: 'openai/gpt-5.6-sol', input: 1_000_000, output: 0 })).toBe(5_000_000);+ expect(costMicroUsd({ provider: 'openrouter', model: 'x-ai/grok-4.5', input: 1_000_000, output: 0 })).toBe(2_000_000);+ });++ it('keeps the Granite BYOK lane metered (the pre-existing paid openrouter route)', () => {+ expect(costMicroUsd({ provider: 'openrouter', model: 'ibm-granite/granite-4.1-8b', input: 1_000_000, output: 1_000_000 })).toBe(150_000);+ });++ it('classifies lanes: :free is free, a mirror is not', () => {+ expect(isFreeLane('openrouter', 'openai/gpt-oss-20b:free')).toBe(true);+ expect(isFreeLane('openrouter#2', 'openai/gpt-oss-20b:free')).toBe(true);+ expect(isFreeLane('openrouter', 'anthropic/claude-sonnet-5')).toBe(false);+ expect(isFreeLane('openrouter', 'ibm-granite/granite-4.1-8b')).toBe(false);+ expect(isOpenRouterFreeModel('openai/gpt-oss-20b:free')).toBe(true);+ expect(isOpenRouterFreeModel('anthropic/claude-opus-5')).toBe(false);+ expect(openRouterBaseId('anthropic/claude-opus-5')).toBe('claude-opus-5');+ expect(openRouterBaseId('grok-4.5')).toBe('grok-4.5');+ });+});++describe('an unpriceable spending lane reports unknown, never 0', () => {+ it('returns null for a mirror of a model that is not in the price table', () => {+ const cost = costMicroUsd({ provider: 'openrouter', model: 'somevendor/unknown-model-9', input: 1000, output: 1000 });+ expect(cost).toBeNull();+ });++ it('returns null for an unpriced model on a first-party paid provider', () => {+ expect(costMicroUsd({ provider: 'anthropic', model: 'claude-unreleased-9', input: 1000, output: 1000 })).toBeNull();+ expect(costMicroUsd({ provider: 'openai', model: 'gpt-9-unreleased', input: 1000, output: 1000 })).toBeNull();+ });++ it('still returns 0 (not unknown) for the genuinely free lanes', () => {+ for (const [provider, model] of [+ ['groq', 'llama-3.3-70b-versatile'],+ ['groq#instant', 'llama-3.1-8b-instant'],+ ['nvidia', 'meta/llama-3.3-70b-instruct'],+ ['cerebras', 'llama-3.3-70b'],+ ['gemini', 'gemini-2.5-flash-lite'],+ ['ovh', 'Meta-Llama-3_3-70B-Instruct'],+ ['pollinations', 'openai-fast'],+ ]) {+ expect(costMicroUsd({ provider, model, input: 500_000, output: 500_000 }), `${provider}/${model}`).toBe(0);+ }+ });++ it('keeps the credits-billed Vertex lanes metered rather than free', () => {+ expect(costMicroUsd({ provider: 'vertex-gemini', model: 'google/gemini-2.5-flash', input: 1_000_000, output: 0 })).toBe(300_000);+ expect(costMicroUsd({ provider: 'vertex-anthropic', model: 'claude-sonnet-5', input: 1_000_000, output: 0 })).toBe(3_000_000);+ });+});++describe('a provider-reported cost outranks the table', () => {+ it('uses the reported charge when OpenRouter returns usage.cost', () => {+ // The table would say $30 for these tokens; OpenRouter says it charged+ // $0.0123, and OpenRouter is the one sending the invoice.+ const cost = costMicroUsd({+ provider: 'openrouter',+ model: 'anthropic/claude-opus-5',+ input: 1_000_000,+ output: 1_000_000,+ reportedCostUsd: 0.0123,+ });+ expect(cost).toBe(12_300);+ });++ it('prices an otherwise-unpriceable model from the reported charge', () => {+ expect(costMicroUsd({ provider: 'openrouter', model: 'newvendor/brand-new', input: 10, output: 10, reportedCostUsd: 0.002 })).toBe(2_000);+ });++ it('a reported 0 on a free route is a real zero, not unknown', () => {+ expect(costMicroUsd({ provider: 'openrouter', model: 'openai/gpt-oss-20b:free', input: 10, output: 10, reportedCostUsd: 0 })).toBe(0);+ });+});diff --git a/tests/solana-rpc-method-capability.test.js b/tests/solana-rpc-method-capability.test.jsindex 63e6da5be..125f7d811 100644--- a/tests/solana-rpc-method-capability.test.js+++ b/tests/solana-rpc-method-capability.test.js@@ -274,6 +274,50 @@ describe('makeRotatingFetch: a method refusal demotes the method, never the laneexpect((await out.json()).result).toEqual({ ok: true });});+ // The dangerous direction of "never bench on a refusal". `Your IP or provider is+ // blocked from this endpoint` is emitted per-method by MagicBlock (which serves+ // six other shapes perfectly) AND caller-wide by a node that has genuinely banned+ // our egress. The wording is identical, so only BREADTH separates them: a lane+ // that refuses one or two shapes is refusing a call, a lane that refuses+ // everything is refusing us and must leave the rotation properly.+ it('benches a lane that refuses call shape after call shape, that is a caller ban, not a policy block', async () => {+ const banned = 'https://cap-i1.test/';+ const healthy = 'https://cap-i2.test/';+ global.fetch = vi.fn(async (url) => (url === banned ? resp(MAGICBLOCK_IP_BLOCK) : resp(OK)));+ const rf = makeRotatingFetch([banned, healthy]);++ // Three distinct shapes refused is still inside the legitimate range: Tatum's+ // free tier gates exactly three while serving two more we want to keep.+ for (const m of ['getBalance', 'getTokenAccountsByOwner', 'getProgramAccounts']) {+ await rf(null, rpc(m));+ }+ expect(isEndpointCooling(banned)).toBe(false);++ // The fourth tips it: no real policy block is this wide.+ await rf(null, rpc('getAccountInfo'));+ expect(isEndpointCooling(banned)).toBe(true);+ });++ it('leaves a lane serving when only one shape is refused, however alarming the wording', async () => {+ const magicblock = 'https://cap-j1.test/';+ const healthy = 'https://cap-j2.test/';+ global.fetch = vi.fn(async (url, init) =>+ url === magicblock && JSON.parse(init.body).method === 'getProgramAccounts'+ ? resp(MAGICBLOCK_IP_BLOCK)+ : resp(OK),+ );+ const rf = makeRotatingFetch([magicblock, healthy]);++ // The real MagicBlock profile: refuse getProgramAccounts, serve everything+ // else. Hammer it with the other shapes and it must stay the primary.+ await rf(null, rpc('getProgramAccounts'));+ for (const m of ['getBalance', 'getLatestBlockhash', 'getSignatureStatuses', 'getAccountInfo', 'simulateTransaction']) {+ await rf(null, rpc(m));+ }+ expect(isEndpointCooling(magicblock)).toBe(false);+ expect(isMethodDemoted(magicblock, 'getProgramAccounts')).toBe(true);+ });+it('reports live demotions for the ops surface and reaps expired ones', async () => {const blocked = 'https://cap-h1.test/';const healthy = 'https://cap-h2.test/';diff --git a/tests/x402-ring-agents.test.js b/tests/x402-ring-agents.test.jsindex d791247a6..d101b8cc4 100644--- a/tests/x402-ring-agents.test.js+++ b/tests/x402-ring-agents.test.js@@ -8,6 +8,9 @@ import {floatBand,isRingAddress,executePurchase,+ assessAgentBuyingPower,+ readAgentUsdcAtomic,+ resetAgentUsdcCache,} from '../api/_lib/x402/agents/persona-kit.js';import {PERSONAS,diff --git a/vercel.json b/vercel.jsonindex bdbe5d2ec..56406009b 100644--- a/vercel.json+++ b/vercel.json@@ -15,7 +15,7 @@"api/cron/treasury-topup.js": {"maxDuration": 120},- "{api/cron/economy-reconcile,api/cron/x402-ring-leak-scan,api/cron/quality-bench}.js": {+ "{api/cron/economy-reconcile,api/cron/x402-ring-leak-scan,api/cron/quality-bench,api/cron/fact-check-benchmark}.js": {"maxDuration": 300},"{api/strategies,api/cron/payment-session-sweep,api/cron/three-market-refresh}.js": {@@ -5965,6 +5965,10 @@{"path": "/api/cron/garment-job-sweep","schedule": "*/10 * * * *"+ },+ {+ "path": "/api/cron/fact-check-benchmark",+ "schedule": "41 4 * * 1"}]}diff --git a/workers/okx-chat-bot/Dockerfile b/workers/okx-chat-bot/Dockerfilenew file mode 100644index 000000000..1307aa04d--- /dev/null+++ b/workers/okx-chat-bot/Dockerfile@@ -0,0 +1,71 @@+# okx-chat-bot: always-on host for the OKX.AI marketplace chat bot (agent #2632).+#+# Build from the REPO ROOT (it imports api/_lib/* for the catalog briefing, the+# GCS token minter, the alert sink and the DB client):+#+# docker build -f workers/okx-chat-bot/Dockerfile -t okx-chat-bot .+# docker run --env-file .env -e PORT=8080 -p 8080:8080 okx-chat-bot+#+# Three external pieces are baked in, and each one is here because installing it+# at runtime is exactly how the codespace version kept breaking:+#+# okx-a2a the XMTP daemon. Node >= 22.14 or it refuses to start.+# onchainos the OKX wallet CLI. Installed with the checksum-verified installer+# (.agents/skills/okx-agentic-wallet/_shared/preflight.md) under a+# THROWAWAY HOME, then relocated to /usr/local/bin: at runtime HOME+# is the restored state tree, so a binary living in $HOME/.local/bin+# would vanish the moment a snapshot was unpacked over it.+# an AI CLI the adapter spawns it to author replies and drive the task+# lifecycle. Both supported agentic CLIs ship so the provider can be+# switched by env alone (see workers/okx-chat-bot/config.js).++FROM node:24-slim++# tar/gzip drive the state snapshots; ca-certificates and curl serve the+# checksum-verified onchainos install below.+RUN apt-get update \+ && apt-get install -y --no-install-recommends ca-certificates curl tar gzip git \+ && rm -rf /var/lib/apt/lists/*++WORKDIR /app++# The two CLIs the adapter drives, plus the agentic AI CLIs it can spawn.+RUN npm install -g \+ @okxweb3/a2a-node@latest \+ @anthropic-ai/claude-code@latest \+ @openai/codex@latest++# onchainos: verify the installer against the release checksum before running it,+# then move the binary somewhere a state restore cannot overwrite.+RUN set -eux; \+ TAG="$(curl -sSL https://api.github.com/repos/okx/onchainos-skills/releases/latest | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>process.stdout.write(JSON.parse(s).tag_name))')"; \+ curl -sSL "https://raw.githubusercontent.com/okx/onchainos-skills/${TAG}/install.sh" -o /tmp/onchainos-install.sh; \+ curl -sSL "https://github.com/okx/onchainos-skills/releases/download/${TAG}/installer-checksums.txt" -o /tmp/installer-checksums.txt; \+ ACTUAL="$(sha256sum /tmp/onchainos-install.sh | cut -d' ' -f1)"; \+ grep -q "$ACTUAL" /tmp/installer-checksums.txt || { echo "onchainos installer checksum mismatch"; exit 1; }; \+ HOME=/opt/onchainos-install sh /tmp/onchainos-install.sh; \+ mv /opt/onchainos-install/.local/bin/onchainos /usr/local/bin/onchainos; \+ chmod +x /usr/local/bin/onchainos; \+ rm -rf /opt/onchainos-install /tmp/onchainos-install.sh /tmp/installer-checksums.txt; \+ onchainos --version++# Repo deps first for layer caching. .npmrc carries legacy-peer-deps; --ignore-scripts+# skips the postinstall git-hook wiring, which has no meaning in an image.+COPY .npmrc package.json package-lock.json* ./+RUN npm ci --ignore-scripts --omit=dev || npm install --ignore-scripts --omit=dev++# Only what the worker actually imports or stages: the api/_lib modules it uses,+# the worker itself, and the skills it copies into the AI workspace.+COPY api ./api+COPY workers/okx-chat-bot ./workers/okx-chat-bot+COPY .agents/skills ./.agents/skills++ENV NODE_ENV=production \+ OKX_BOT_HOME=/state \+ OKX_BOT_REPO_ROOT=/app++# The state tree is created here rather than by the entrypoint so a read-only+# rootfs or a stricter runtime user surfaces at build time, not at 3am.+RUN mkdir -p /state++CMD ["node", "workers/okx-chat-bot/index.js"]