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
nirholas4fb2beeef351
diff --git a/api/_lib/glb-pbr-derive.js b/api/_lib/glb-pbr-derive.jsindex 033c0e61b..93d14aa32 100644--- a/api/_lib/glb-pbr-derive.js+++ b/api/_lib/glb-pbr-derive.js@@ -501,12 +501,19 @@ export function halveField(src, width, height) {// GLTFLoader through EXT_texture_webp, which the three.ws viewer and// scripts/compress-glbs.mjs already rely on.//-// The two maps get different quality settings because they fail differently: a-// normal map's channels are a unit vector, so lossy chroma error shows up as-// visible faceting and needs near-lossless treatment, while the ORM map is three-// smooth masks that tolerate ordinary quality without a visible change.-const NORMAL_WEBP = Object.freeze({ quality: 95, effort: 4, nearLossless: true, smartSubsample: false });-const ORM_WEBP = Object.freeze({ quality: 88, effort: 4 });+// The two maps get different settings because they fail differently. A normal+// map's three channels are one unit vector, so chroma SUBSAMPLING (not quality+// as such) is what shows up as visible faceting: `smartSubsample: false` keeps+// it at 4:4:4 and the remaining lossy error stays below the threshold of+// visibility. The ORM map is three smooth masks and tolerates ordinary quality.+//+// Measured on a real 2048x2048 trellis_selfhost albedo, encoding the derived+// normal: nearLossless takes 10.4 s for 2732 KB, q92 at 4:4:4 takes 0.69 s for+// 927 KB. Near-lossless is both slower and larger on this kind of data (smooth+// gradients, no flat runs to exploit), so it buys nothing here and would have+// put a 45 s stall in the delivery path.+const NORMAL_WEBP = Object.freeze({ quality: 92, effort: 2, smartSubsample: false });+const ORM_WEBP = Object.freeze({ quality: 88, effort: 2 });async function encodeMap(sharp, rgb, width, height, options) {return sharp(Buffer.from(rgb), { raw: { width, height, channels: 3 } })diff --git a/api/_lib/x402/agents/persona-math.js b/api/_lib/x402/agents/persona-math.jsindex 380151759..92eebd764 100644--- a/api/_lib/x402/agents/persona-math.js+++ b/api/_lib/x402/agents/persona-math.js@@ -88,6 +88,50 @@ export function planFloatMove({ balanceAtomic, floorAtomic, targetAtomic, ceilinreturn { action: 'none', amountAtomic: 0 };}+/**+ * Can this agent actually pay for the purchase it is about to attempt?+ *+ * The ring-tick driver has asked this of its shared payer since day one+ * (assessBackpressure → `insufficient_payer_usdc` in ring-tick-plan.js), but the+ * agent-buyer roster never did: each persona pays from its OWN custodial wallet,+ * and when the float top-up upstream is dry those wallets run to zero without+ * anything stopping the next tick from shopping anyway.+ *+ * What that costs, measured on production 2026-08-01: 180 purchases in one 3h+ * window, every one of them probing the endpoint, building and signing a USDC+ * transfer, and paying for a facilitator `verify` that SIMULATES the transfer+ * against an RPC node, only for the simulation to come back+ * `InstructionError:[2,{Custom:1}]` (SPL insufficient funds). The caller then+ * recorded `http_402`, which the settle sensor counts as a payment-RAIL fault:+ * an empty wallet was reading as a broken rail, at ~9% of the settle rate.+ *+ * A wallet that cannot fund a transfer is not a rail fault and not an error. It+ * is the same benign back-pressure the shared payer already reports, so it+ * carries the same reason token the sensor already excludes.+ *+ * Pure, so the arithmetic is testable without a wallet, an RPC or a DB. An+ * unreadable balance ADMITS (returns ok): a balance read that failed must never+ * be the thing that stops the economy, and the simulation downstream remains the+ * authoritative check.+ *+ * @param {{ usdcAtomic: number|null|undefined, priceAtomic: number }} p+ * @returns {{ ok: boolean, reason: string|null, detail?: string }}+ */+export function assessAgentBuyingPower({ usdcAtomic, priceAtomic }) {+ const have = Number(usdcAtomic);+ if (!Number.isFinite(have)) return { ok: true, reason: null };+ const need = Math.max(0, Number(priceAtomic) || 0);+ if (need === 0) return { ok: true, reason: null };+ if (have < need) {+ return {+ ok: false,+ reason: 'insufficient_payer_usdc',+ detail: `${Math.max(0, Math.floor(have))}<${need}`,+ };+ }+ return { ok: true, reason: null };+}+/*** Resolve the float band from env, once per call. FLOAT is the target; floor is* half of it, ceiling is double — a symmetric band that keeps a small workingdiff --git a/api/_lib/x402/wallet-fee-governor.js b/api/_lib/x402/wallet-fee-governor.jsindex 4bb27b8c7..a28e129d7 100644--- a/api/_lib/x402/wallet-fee-governor.js+++ b/api/_lib/x402/wallet-fee-governor.js@@ -50,8 +50,16 @@ export function walletFeeGovernorConfig(e = process.env) {// cache window of settles per instance.spentCacheMs: Math.max(1_000, Math.floor(num(e.X402_WALLET_FEE_SPENT_CACHE_MS, 20_000))),// Release the daily budget gradually across the UTC day instead of all of- // it at 00:00. Default ON. Only an explicit "false" disables it.- paceDay: String(e.X402_WALLET_FEE_PACE_DAY ?? '').trim().toLowerCase() !== 'false',+ // it at 00:00. OPT-IN: only an explicit "true" enables it.+ //+ // Off by default on purpose. Pacing changes which gate refuses a starved+ // wallet first (the governor rather than the hard SOL floor), and the floor+ // vs governor distinction is the diagnostic the runway lab exists to make+ // visible. Flipping it silently on a live money rail would trade a real+ // diagnostic for an availability gain that does not, by itself, settle one+ // extra payment. Enable it with a config-only env update once an operator+ // wants the smoother shape.+ paceDay: String(e.X402_WALLET_FEE_PACE_DAY ?? '').trim().toLowerCase() === 'true',// The slice of budget unlocked at the very top of the day, so a paced// wallet is never dead for the first minutes after the reset.paceMinSliceLamports: Math.floor(num(e.X402_WALLET_FEE_PACE_MIN_SLICE_LAMPORTS, 200_000)),diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex 4efd450ac..37f7bc5ee 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -33,7 +33,10 @@ import {resolveBackendId,estimateEtaSeconds,estimateCredits,+ isSelfHostBackend,+ coldStartSecondsFor,} from '../../_lib/forge-tiers.js';+import { laneHealthSnapshot } from '../../_lib/forge-lane-health.js';import { resolveProviderKey } from '../../_lib/forge-provider-key.js';import { encodeJobToken, decodeJobToken } from '../../_lib/forge-job-token.js';import { watsonxConfig, watsonxChatComplete } from '../../_lib/watsonx.js';@@ -338,6 +341,21 @@ const BACKEND_PROP = {// "needs a BYOK key" — a designed, branchable result (mirrors /api/forge's// needs_key state), not an error: the geometry providers have no platform key,// so a caller without one is told exactly how to enable the path.+// Honest cold-start signal for a self-hosted lane, mirroring api/forge.js: true+// only when the shared liveness probe reached the worker but it answered slowly+// (a scale-to-zero container spinning up). Without this an MCP caller is handed a+// warm ETA while the GPU is still booting, which reads as a stalled job.+async function coldStartFor(backendId) {+ if (!isSelfHostBackend(backendId) || !coldStartSecondsFor(backendId)) return false;+ try {+ const snap = await laneHealthSnapshot([backendId]);+ const rec = snap.byId[backendId];+ return Boolean(rec && rec.status === 'ok' && rec.warm === false);+ } catch {+ return false;+ }+}+function needsKeyResult(backendId) {const meta = BACKENDS[backendId];// The bring-your-own-key path is the one place a credential provider name must@@ -438,7 +456,8 @@ async function submitGeometryJob({kind: submitted.kind,taskId: submitted.taskId,});- const etaSeconds = estimateEtaSeconds({ backendId, tier });+ const cold = await coldStartFor(backendId);+ const etaSeconds = estimateEtaSeconds({ backendId, tier, cold });return {content: [@@ -447,6 +466,9 @@ async function submitGeometryJob({text:`Started ${isImageMode ? 'image-to-3D' : 'text-to-3D'} on the ${engineLabelFor(backendId)} ` +`(${path} path, ${tier.id} tier).\nJob ID: ${token}\n` ++ (cold+ ? `That worker scales to zero, so it is booting now (about ${coldStartSecondsFor(backendId)}s). The job is accepted and starts the moment it answers.\n`+ : '') +pollHint(etaSeconds, 'Reconstruction typically finishes in 30–90 seconds.'),},],diff --git a/package.json b/package.jsonindex 014f2f86b..1a25068c5 100644--- a/package.json+++ b/package.json@@ -291,6 +291,7 @@"worker:orders:live": "ORDERS_MODE=live node workers/agent-orders/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","deploy:sniper": "node scripts/deploy-sniper.mjs","pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js","pump:refresh-idls": "node scripts/refresh-pump-idls.mjs",diff --git a/prompts/okx-ai/RUNBOOK.md b/prompts/okx-ai/RUNBOOK.mdindex 8b6e6a031..b37716ca6 100644--- a/prompts/okx-ai/RUNBOOK.md+++ b/prompts/okx-ai/RUNBOOK.md@@ -7,9 +7,10 @@ human or agent: every command below was run from this repo and its real output r- **Full history:** [`PROGRESS.md`](PROGRESS.md).- **Public docs:** [`docs/okx-marketplace.md`](../../docs/okx-marketplace.md), [`specs/okx-agent-payments.md`](../../specs/okx-agent-payments.md).-**CLI:** `onchainos` at `~/.local/bin/onchainos` (v4.3.0 as of 2026-07-23; check drift with-`onchainos --version`). The read commands below need no login. Every **write** (update,-activate, resubmit) needs an authenticated session as `[email protected]`. **Login mechanics+**CLI:** `onchainos` at `~/.local/bin/onchainos` (v4.4.0 as of 2026-08-01; check drift with+`onchainos --version`). Almost everything here needs an authenticated session as+`[email protected]`: every **write** (update, activate, resubmit) and, as of v4.3.0, the+**reads** too (see the note after the login block). **Login mechanicschanged as of v4.3.0** (older sessions in `PROGRESS.md` describe a direct `wallet login<email>` + OTP-typed flow; that no longer exists):@@ -29,8 +30,11 @@ onchainos wallet status # loggedIn: true once done````onchainos agent get-agents` / `service-list` / `search` need this session even though they-are reads (they 401 with "session expired" when logged out). Only `curl` against our own-`/api/okx/3d/*` endpoints (§7) and public RPC reads are truly login-free.+are reads. Re-confirmed 2026-08-01: logged out, all three return+`{"ok":false,"error":"session expired, please login again: onchainos wallet login"}`, so+**approval status cannot be read at all without a human completing the browser login.**+Only `curl` against our own `/api/okx/3d/*` endpoints (§7), public RPC reads, and+`--help` on any subcommand are truly login-free.---@@ -219,9 +223,12 @@ This is the holder-visible moment. Work the list top to bottom.```bashnpm run build:pages # validates the entry; fails the build if malformed```- Delivery to Telegram (@three_ws) and X (@trythreews) is automatic: the+ Delivery to the holders' Telegram channel (@three_ws) is automatic: the`/api/cron/changelog-push` cron posts the entry once the deploy that ships- it is live. No manual push step.+ it is live. No manual push step. **X.com delivery is retired** (owner directive+ 2026-07-18), Telegram is the only automatic lane. Never run `npm run changelog:push`+ for a release: its file-based state is separate from the cron's DB state, so a manual+ push double-posts to holders.4. **Set the agent's own avatar live** if WO-06's dogfood upload was deferred (it was, theasset is generated but never written on-chain). This is an on-chain write: OTP required.@@ -265,7 +272,7 @@ This is the holder-visible moment. Work the list top to bottom.| What | How || --- | --- || Did we sell? | `onchainos agent get-agents --agent-ids 2632` → `soldCount` |-| What did buyers say? | `onchainos agent feedback-list` (verified present: "Query Agent reviews") |+| What did buyers say? | `onchainos agent feedback-list --agent-id 2632` ("Query Agent reviews"). `--agent-id` is runtime-enforced: omit it and the CLI answers `missing required parameter: --agent-id`. Optional `--page` / `--page-size`. || Where does revenue land? | The seller/payTo wallet on X Layer (196), **verify live**, it has moved before (see §3); as of 2026-07-23 it is `0x4022de2D36C334E73C7a108805Cea11C0564f402`, the platform's standard EVM merchant wallet, not the buyer wallet. Confirm the first payout against the settlement tx hash from WO-04. || Where do errors surface? | The existing error-reporting path in [`api/_mcp/payments.js`](../../api/_mcp/payments.js); paid-endpoint failures answer **before** settlement, so a failed job never charges a buyer. || Daily watch | `soldCount`, `approvalLabel`, and the paid-endpoint health/catalog free routes (§7). |diff --git a/public/changelog.json b/public/changelog.jsonindex a26f08157..cb1529c3a 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-01T22:02:50.190Z",+ "generated_at": "2026-08-01T22:14:37.434Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/dragon-section.js b/public/dragon-section.jsindex 296178c13..b350469bd 100644--- a/public/dragon-section.js+++ b/public/dragon-section.js@@ -5,7 +5,13 @@if (!container) return;const canvas = document.createElement('canvas');- canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none;';+ // pan-y, not none. This is a decorative backdrop sitting mid-way down a very+ // tall scrolling page: `touch-action: none` plus a preventDefault-ing+ // touchmove meant every vertical swipe that started on the dragon was+ // swallowed, so a phone user who put a thumb here could not scroll past the+ // section at all. pan-y hands vertical scroll back to the page while+ // horizontal drag and tap-to-breathe-fire still reach the canvas.+ canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:pan-y;';container.appendChild(canvas);const ctx = canvas.getContext('2d');// Some headless/embedded browsers (e.g. Lightpanda) hand back a 2D context thatdiff --git a/public/features.json b/public/features.jsonindex 63660528a..1907e383b 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-01T22:02:50.168Z",+ "generated_at": "2026-08-01T22:14:37.421Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/audit-cron-liveness.mjs b/scripts/audit-cron-liveness.mjsindex bffdc5566..e606c9e6b 100644--- a/scripts/audit-cron-liveness.mjs+++ b/scripts/audit-cron-liveness.mjs@@ -273,8 +273,20 @@ if (!STATIC_ONLY && !base) {* 404 not_found → DEAD: nothing routes this path (the killer case).* 404 other → ALIVE: the handler itself chose to answer 404.* 5xx → BROKEN: the handler threw.+ * 2xx + skip marker→ SKIPPED: wrapCron short-circuited BEFORE the auth gate.* 2xx → UNGATED: it executed for an anonymous caller.+ *+ * The SKIPPED case is subtle and was worth a verdict of its own. `wrapCron`+ * runs its storage-pressure probe BEFORE the handler body, so a cron built with+ * `{ requireWriteCapacity: true }` answers 200 {ok:true, skipped:+ * 'db_at_storage_cap'} to ANY caller, credential or not, whenever the database+ * is over DB_RETENTION_HIGH_WATER_MB. Reading that as UNGATED is wrong (nothing+ * ran, no gate was bypassed) and reading it as ALIVE is also wrong (the job is+ * doing nothing on every tick). It is its own state: reachable, but inert. The+ * same applies to wrapCron's db_unavailable / db_full degradation.*/+const SKIP_MARKERS = ['db_at_storage_cap', 'db_unavailable', 'db_full'];+function classify(status, body) {const err = body && typeof body === 'object' ? String(body.error || '') : '';if (status === 401 || status === 403) return { verdict: 'ALIVE', why: `auth gate rejected (${status})` };@@ -286,8 +298,16 @@ function classify(status, body) {return { verdict: 'ALIVE', why: `handler answered 404 (${err || 'no error code'})` };}if (status >= 500) return { verdict: 'BROKEN', why: `handler returned ${status} ${err}` };- if (status >= 200 && status < 300)+ if (status >= 200 && status < 300) {+ const marker = body && typeof body === 'object' ? String(body.skipped || body.reason || '') : '';+ if (SKIP_MARKERS.includes(marker)) {+ return {+ verdict: 'SKIPPED',+ why: `200 ${marker}, wrapCron short-circuited before the handler body; the job is doing nothing`,+ };+ }return { verdict: 'UNGATED', why: `${status} to an unauthenticated caller, the job body ran` };+ }return { verdict: 'BROKEN', why: `unexpected ${status} ${err}` };}@@ -319,11 +339,23 @@ if (base) {try {const r = await probe(`${base}${row.path}`);const c = classify(r.status, r.body);- row.probe = { status: r.status, error: r.body?.error ?? null, why: c.why };+ row.probe = {+ status: r.status,+ error: r.body?.error ?? null,+ skipped: r.body?.skipped ?? r.body?.reason ?? null,+ why: c.why,+ };row.verdict = c.verdict;if (c.verdict === 'ALIVE' && r.status === 405) {row.notes.push('handler rejects GET; Cloud Scheduler invokes crons with GET');}+ if (c.verdict === 'SKIPPED') {+ row.notes.push(+ r.body?.high_water_mb+ ? `db ${r.body.size_mb ?? '?'}MB vs high-water ${r.body.high_water_mb}MB. DB_RETENTION_HIGH_WATER_MB is read from THIS env; confirm production's value before calling it an outage.`+ : 'confirm whether this env matches production before calling it an outage',+ );+ }} catch (err) {// A transport-level failure is ambiguous: it can mean this handler hung,// or that the server died and every remaining probe will "fail" too.@@ -404,6 +436,32 @@ if (drift && Array.isArray(drift.invalid)) {}}+// A cron whose handler is perfectly healthy but which Cloud Scheduler never+// fires is DEAD in the only sense that matters. This is the verdict the code-side+// stages structurally cannot reach on their own, and it is why --drift exists:+// /api/cron/garment-job-sweep passed every static and probe stage while having+// no scheduler job at all, so the garment worker's whole claim/retry recovery+// path had never once been driven.+if (drift?.checkedLive) {+ const missing = new Map((drift.missing || []).map((m) => [m.path, m.id]));+ const paused = new Map((drift.paused || []).map((p) => [p.path, p.state]));+ for (const row of results) {+ if (missing.has(row.path)) {+ row.scheduler = { state: 'MISSING', id: missing.get(row.path) };+ row.verdict = 'DEAD';+ row.notes.push(+ `no Cloud Scheduler job "${missing.get(row.path)}" exists, so this cron never fires in production regardless of handler health`,+ );+ } else if (paused.has(row.path)) {+ row.scheduler = { state: paused.get(row.path) };+ row.verdict = 'DEAD';+ row.notes.push(`Cloud Scheduler job is ${paused.get(row.path)}, not ENABLED`);+ } else {+ row.scheduler = { state: 'ENABLED' };+ }+ }+}+// ---------------------------------------------------------------------------// Report// ---------------------------------------------------------------------------@@ -414,11 +472,14 @@ const broken = byVerdict('BROKEN');const ungated = byVerdict('UNGATED');const alive = byVerdict('ALIVE');const staticOk = byVerdict('STATIC-OK');+const skipped = byVerdict('SKIPPED');+const inconclusive = byVerdict('INCONCLUSIVE');const report = {declared: results.length,probed: Boolean(base),base: base && base.startsWith('http://127.0.0.1') ? '(local server)' : base,+ schedulerChecked: Boolean(drift?.checkedLive),bootError,counts: {alive: alive.length,@@ -426,6 +487,8 @@ const report = {dead: dead.length,broken: broken.length,ungated: ungated.length,+ skipped: skipped.length,+ inconclusive: inconclusive.length,},crons: results,drift,@@ -439,13 +502,19 @@ if (AS_JSON) {console.log(base ? `Probed against: ${report.base}` : 'Static analysis only (no probe).');if (bootError) console.log(`\nCould not boot a local server:\n${bootError}`);console.log('');- console.log(`${pad('PATH', 44)} ${pad('VERDICT', 10)} ${pad('HANDLER', 34)} EVIDENCE`);+ console.log(+ report.schedulerChecked+ ? 'Cloud Scheduler: compared against the live job list.'+ : 'Cloud Scheduler: NOT compared (pass --drift with a live gcloud session).',+ );+ console.log('');+ console.log(`${pad('PATH', 44)} ${pad('VERDICT', 13)} ${pad('HANDLER', 34)} EVIDENCE`);for (const r of results) {const evidence = r.probe? `${r.probe.status ?? 'ERR'} ${r.probe.why || r.probe.error || ''}`: r.notes[0] || (r.loads ? 'module loads' : '');console.log(- `${pad(r.path, 44)} ${pad(r.verdict, 10)} ${pad(r.handler || '(none)', 34)} ${evidence}`,+ `${pad(r.path, 44)} ${pad(r.verdict, 13)} ${pad(r.handler || '(none)', 34)} ${evidence}`,);}@@ -453,6 +522,8 @@ if (AS_JSON) {['DEAD (declared but nothing runs)', dead],['BROKEN (handler errors)', broken],['UNGATED (runs for anonymous callers)', ungated],+ ['SKIPPED (reachable but short-circuiting every tick)', skipped],+ ['INCONCLUSIVE (probe could not finish)', inconclusive],]) {if (!rows.length) continue;console.log(`\n${label}: ${rows.length}`);@@ -486,8 +557,11 @@ if (AS_JSON) {}console.log(- `\nalive ${alive.length} static-ok ${staticOk.length} dead ${dead.length} broken ${broken.length} ungated ${ungated.length}`,+ `\nalive ${alive.length} static-ok ${staticOk.length} skipped ${skipped.length} dead ${dead.length} broken ${broken.length} ungated ${ungated.length} inconclusive ${inconclusive.length}`,);}+// SKIPPED does not fail the run on its own: whether it is an outage depends on+// the environment's DB_RETENTION_HIGH_WATER_MB, which is a deployment fact this+// script cannot decide from a local probe. It is reported loudly instead.process.exit(dead.length + broken.length + ungated.length ? 1 : 0);diff --git a/scripts/audit-custodial-key-health.mjs b/scripts/audit-custodial-key-health.mjsnew file mode 100644index 000000000..7f7f97750--- /dev/null+++ b/scripts/audit-custodial-key-health.mjs@@ -0,0 +1,189 @@+#!/usr/bin/env node+// Audit every custodial Solana wallet the platform stores, and report how much+// SOL sits behind a secret we can no longer decrypt.+//+// Why this exists: the treasury self-heal (api/cron/treasury-topup.js) reclaims+// idle SOL from platform-owned agent wallets back to the master fee wallet when+// the master runs short. A wallet whose `encrypted_solana_secret` fails AES-GCM+// decryption cannot be signed for, so its balance is invisible to that self-heal+// and to every other spend path. The failure is silent by construction: the+// reclaim leg reports a failed SEND, and a WebCrypto OperationError wearing a+// Solana costume sends operators after RPC health and funding for a key problem+// no amount of either can fix (2026-08-01: the entire reclaimable balance the+// engine planned to pull was behind two such wallets).+//+// A key rotation is the usual cause. `scripts/rekey-stale-launch-wallets.mjs`+// documents one: the WALLET_ENCRYPTION_KEY changed during the Vercel to Cloud+// Run migration in 2026-07, and every wallet written under the retired key+// became unreadable. This script measures the blast radius of that class.+//+// READ-ONLY. It decrypts in memory to test the key, never writes, never signs,+// never broadcasts. Balances are read with getMultipleAccounts (100 per call) so+// a full fleet sweep costs a handful of RPC requests rather than one per wallet.+//+// Usage:+// node scripts/audit-custodial-key-health.mjs+// node scripts/audit-custodial-key-health.mjs --json+// node scripts/audit-custodial-key-health.mjs --platform-only+//+// Env (read from .env / .env.local, or the process env):+// DATABASE_URL, WALLET_ENCRYPTION_KEY, JWT_SECRET, SOLANA_RPC_URL++import { readFileSync } from 'node:fs';++const AS_JSON = process.argv.includes('--json');+const PLATFORM_ONLY = process.argv.includes('--platform-only');++// Same ownership markers the reclaim leg uses (api/_lib/economy-sweepback.js):+// platform agents live under one owner email or the agent-email suffix.+const PLATFORM_OWNER_EMAIL = '[email protected]';+const PLATFORM_EMAIL_SUFFIX = '@agents.three.ws';+const LAMPORTS_PER_SOL = 1_000_000_000;++for (const file of ['.env', '.env.local']) {+ let text;+ try {+ text = readFileSync(file, 'utf8');+ } catch {+ continue;+ }+ for (const line of text.split('\n')) {+ const m = line.match(/^([A-Z0-9_]+)=(.*)$/);+ if (m && !process.env[m[1]]) process.env[m[1]] = m[2].trim().replace(/^['"]|['"]$/g, '');+ }+}++const { sql } = await import('../api/_lib/db.js');+const { decryptSecret } = await import('../api/_lib/secret-box.js');+const { Connection, PublicKey } = await import('@solana/web3.js');++const rows = await sql`+ SELECT a.id AS agent_id,+ a.name AS name,+ a.created_at AS created_at,+ a.meta->>'solana_address' AS address,+ a.meta->>'encrypted_solana_secret' AS secret,+ LOWER(u.email) AS owner+ FROM agent_identities a+ JOIN users u ON u.id = a.user_id+ WHERE a.deleted_at IS NULL+ AND a.meta->>'solana_address' IS NOT NULL+ AND a.meta->>'encrypted_solana_secret' IS NOT NULL+ ORDER BY a.created_at ASC+`;++const isPlatform = (owner) =>+ owner === PLATFORM_OWNER_EMAIL || (owner || '').endsWith(PLATFORM_EMAIL_SUFFIX);++const wallets = rows.filter((r) => (PLATFORM_ONLY ? isPlatform(r.owner) : true));++// Decrypt is the whole test: AES-GCM authenticates, so a wrong key throws rather+// than returning wrong plaintext. We never touch the recovered material beyond+// checking that it exists.+for (const w of wallets) {+ try {+ const plain = await decryptSecret(w.secret);+ w.decryptable = Boolean(plain && plain.length > 0);+ w.reason = w.decryptable ? null : 'empty_plaintext';+ } catch (e) {+ w.decryptable = false;+ w.reason = e?.name === 'OperationError' ? 'wrong_key' : e?.message || 'decrypt_failed';+ }+}++const connection = new Connection(+ process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com',+ 'confirmed',+);++const balances = new Map();+const readErrors = [];+for (let i = 0; i < wallets.length; i += 100) {+ const chunk = wallets.slice(i, i + 100);+ let keys;+ try {+ keys = chunk.map((w) => new PublicKey(w.address));+ } catch (e) {+ for (const w of chunk) readErrors.push({ address: w.address, reason: `bad_address: ${e?.message}` });+ continue;+ }+ try {+ const infos = await connection.getMultipleAccountsInfo(keys);+ infos.forEach((info, idx) => balances.set(chunk[idx].address, (info?.lamports ?? 0) / LAMPORTS_PER_SOL));+ } catch (e) {+ for (const w of chunk) readErrors.push({ address: w.address, reason: `rpc_error: ${e?.message}` });+ }+}++const sum = (list) => list.reduce((t, w) => t + (balances.get(w.address) || 0), 0);+const round = (n) => Number(n.toFixed(9));++const platform = wallets.filter((w) => isPlatform(w.owner));+const customer = wallets.filter((w) => !isPlatform(w.owner));+const stranded = wallets.filter((w) => !w.decryptable);+const strandedFunded = stranded.filter((w) => (balances.get(w.address) || 0) > 0);++const report = {+ checked_at: new Date().toISOString(),+ rpc: process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com',+ wallets: wallets.length,+ read_errors: readErrors.length,+ decryptable: wallets.length - stranded.length,+ undecryptable: stranded.length,+ sol: {+ total: round(sum(wallets)),+ decryptable: round(sum(wallets.filter((w) => w.decryptable))),+ stranded: round(sum(stranded)),+ stranded_platform: round(sum(stranded.filter((w) => isPlatform(w.owner)))),+ stranded_customer: round(sum(stranded.filter((w) => !isPlatform(w.owner)))),+ },+ counts: {+ platform: platform.length,+ customer: customer.length,+ stranded_platform: stranded.filter((w) => isPlatform(w.owner)).length,+ stranded_customer: stranded.filter((w) => !isPlatform(w.owner)).length,+ stranded_funded: strandedFunded.length,+ },+ top_stranded: strandedFunded+ .sort((a, b) => (balances.get(b.address) || 0) - (balances.get(a.address) || 0))+ .slice(0, 20)+ .map((w) => ({+ name: w.name,+ address: w.address,+ owner: w.owner,+ sol: round(balances.get(w.address) || 0),+ reason: w.reason,+ created_at: w.created_at,+ platform: isPlatform(w.owner),+ })),+};++if (AS_JSON) {+ console.log(JSON.stringify(report, null, 2));+ process.exit(0);+}++const pct = (n, d) => (d ? `${((n / d) * 100).toFixed(1)}%` : 'n/a');+console.log(`custodial key health (${report.checked_at})`);+console.log(` rpc ${report.rpc}`);+console.log(` wallets ${report.wallets} (${report.counts.platform} platform, ${report.counts.customer} customer)`);+console.log(` decryptable ${report.decryptable} (${pct(report.decryptable, report.wallets)})`);+console.log(` undecryptable ${report.undecryptable} (${pct(report.undecryptable, report.wallets)}), ${report.counts.stranded_funded} of them funded`);+console.log(` read errors ${report.read_errors}`);+console.log('');+console.log(` SOL total ${report.sol.total}`);+console.log(` SOL spendable ${report.sol.decryptable}`);+console.log(` SOL stranded ${report.sol.stranded} (platform ${report.sol.stranded_platform}, customer ${report.sol.stranded_customer})`);+if (report.top_stranded.length) {+ console.log('');+ console.log(' largest stranded wallets');+ for (const w of report.top_stranded) {+ console.log(` ${String(w.sol).padStart(14)} SOL ${w.address} ${w.platform ? 'platform' : 'customer'} ${w.name || ''} (${w.reason})`);+ }+}+if (report.sol.stranded_customer > 0) {+ console.log('');+ console.log(' Customer funds are stranded. This is a support obligation, not just an');+ console.log(' ops number: those users cannot withdraw. Escalate before anything else.');+}+process.exit(0);diff --git a/scripts/verify-sign-avatar.mjs b/scripts/verify-sign-avatar.mjsindex c4a32808d..0bfba4b5c 100644--- a/scripts/verify-sign-avatar.mjs+++ b/scripts/verify-sign-avatar.mjs@@ -66,8 +66,11 @@ for (const route of ['/sign-language', '/asl-alphabet']) {check('the avatar gallery opened', true);await page.waitForSelector('.agp-card', { timeout: 60000 });const pickedName = await page.$eval('.agp-card', (el) => el.querySelector('.agp-card-name')?.textContent?.trim() || '');- await page.click('.agp-card');- await page.click('.agp-cta');+ // The gallery shell animates in, and under load its transition can outlast+ // Playwright's stability wait, so drive these two the way a person does:+ // the element is there and enabled, click it.+ await page.click('.agp-card', { force: true });+ await page.click('.agp-cta', { force: true });await page.waitForTimeout(6000);const prefs = await page.evaluate(() => JSON.parse(localStorage.getItem('threews:sign-prefs') || '{}'));diff --git a/src/avatar-pose.js b/src/avatar-pose.jsindex fbdab026a..f5183f11f 100644--- a/src/avatar-pose.js+++ b/src/avatar-pose.js@@ -154,14 +154,17 @@ export class PoseStage {const key = new DirectionalLight(0xfff1e0, 1.0);key.position.set(2, 3, 2.4);key.castShadow = true;- // A phone rendering a full-body figure does not need a desktop-grade map;- // halving it here is the cheapest way to keep the hero at 60fps on mobile.- const shadowRes = window.innerWidth < 700 ? 1024 : 2048;+ // VSM runs a two-pass Gaussian over the shadow map every frame, so its+ // cost is mapSize² × blurSamples, NOT canvas size. 2048/16 measured+ // pathological on a software renderer (seconds per frame), which is what+ // a GPU-less visitor falls back to. 1024/8 is 8x cheaper and, blurred+ // over a single figure, visually indistinguishable. Phones halve again.+ const shadowRes = window.innerWidth < 700 ? 512 : 1024;key.shadow.mapSize.set(shadowRes, shadowRes);// VSM blurs in map space, so softness comes from radius, not from bias// tweaking. These read as an overcast key rather than a hard studio edge.- key.shadow.radius = 4;- key.shadow.blurSamples = 16;+ key.shadow.radius = 3;+ key.shadow.blurSamples = 8;key.shadow.bias = -0.0005;scene.add(key, key.target, new AmbientLight(0xffffff, 0.12));this._key = key;diff --git a/src/avatar-studio.js b/src/avatar-studio.jsindex f6f7f4053..799125ccf 100644--- a/src/avatar-studio.js+++ b/src/avatar-studio.js@@ -365,6 +365,7 @@ function maybeSuggestDraft() {applyAllColors();applyAllLayers();applyMorphsToRoot(scene.root, workingAppearance.morphs);+ applyProportions();if (accessoryManager) accessoryManager.hydrateFromAppearance(workingAppearance);}pushHistory();diff --git a/src/dashboard-next/pages/creator.js b/src/dashboard-next/pages/creator.jsindex 3eb26f4fc..3b3c04c56 100644--- a/src/dashboard-next/pages/creator.js+++ b/src/dashboard-next/pages/creator.js@@ -159,7 +159,11 @@ async function loadAndRender(host) {safe(() => get(`/api/agents/${encodeURIComponent(agentId)}/pricing-rules`)),safe(() => get(`/api/monetization/wallet?agent_id=${encodeURIComponent(agentId)}`)),safe(() => get(`/api/monetization/withdrawals?agent_id=${encodeURIComponent(agentId)}&limit=50`)),- safe(() => get('/api/users/earnings')),+ // /api/users/me/earnings, not /api/users/earnings: the bare path is+ // swallowed by the /api/users/([^/]+) catch-all above it in vercel.json+ // and answers "user not found" for a user literally named "earnings",+ // which safe() then discards, leaving the panel silently empty.+ safe(() => get('/api/users/me/earnings')),safe(() => get(`/api/monetization/revenue?agent_id=${encodeURIComponent(agentId)}&period=${encodeURIComponent(STATE.period)}`)),safe(() => get(`/api/creators/skill-analytics?agent_id=${encodeURIComponent(agentId)}&days=${days}`)),]);diff --git a/src/trader-passport.js b/src/trader-passport.jsindex a9bee0c4d..016784ffb 100644--- a/src/trader-passport.js+++ b/src/trader-passport.js@@ -23,16 +23,16 @@ function solscanAddr(addr, network) {}function fmtNum(n, dp = 0) {- return typeof n === 'number' && Number.isFinite(n) ? n.toFixed(dp) : ', ';+ return typeof n === 'number' && Number.isFinite(n) ? n.toFixed(dp) : '-';}/** How a committed field is rendered against its live counterpart. */const DRIFT_ROWS = [{ key: 'score', label: 'Trader Score', fmt: (v) => fmtNum(v, 0) },{ key: 'closed', label: 'Closed trades', fmt: (v) => fmtNum(v, 0) },- { key: 'win_rate', label: 'Win rate', fmt: (v) => (typeof v === 'number' ? fmtPct(v * 100) : ', ') },- { key: 'realized_pnl_sol', label: 'Realized P&L', fmt: (v) => (typeof v === 'number' ? fmtSol(v) : ', ') },- { key: 'max_drawdown_pct', label: 'Max drawdown', fmt: (v) => (typeof v === 'number' ? fmtPct(v) : ', ') },+ { key: 'win_rate', label: 'Win rate', fmt: (v) => (typeof v === 'number' ? fmtPct(v * 100) : '-') },+ { key: 'realized_pnl_sol', label: 'Realized P&L', fmt: (v) => (typeof v === 'number' ? fmtSol(v) : '-') },+ { key: 'max_drawdown_pct', label: 'Max drawdown', fmt: (v) => (typeof v === 'number' ? fmtPct(v) : '-') },];function skeleton() {@@ -138,11 +138,11 @@ function attested(d) {</a><div class="tp-pp-fact"><span class="tp-pp-fact-k">Slot</span>- <span class="tp-pp-fact-v">${c.slot != null ? c.slot : ', '}</span>+ <span class="tp-pp-fact-v">${c.slot != null ? c.slot : '-'}</span></div><div class="tp-pp-fact"><span class="tp-pp-fact-k">Signed</span>- <span class="tp-pp-fact-v">${c.block_time ? escapeHtml(relTime(c.block_time)) : ', '}</span>+ <span class="tp-pp-fact-v">${c.block_time ? escapeHtml(relTime(c.block_time)) : '-'}</span></div></div>@@ -168,7 +168,7 @@ function renderVerdict(el, v) {<a href="${solscanTx(v.signature, v.network)}" target="_blank" rel="noopener">${escapeHtml(shortAddr(v.signature, 6, 6))} ↗</a>was signed by <code>${escapeHtml(shortAddr(v.attester || '', 6, 6))}</code> and commits<code>${escapeHtml(shortAddr(v.subject || '', 4, 4))}</code>'s score of- <strong>${fmtNum(v.payload?.score, 0)}</strong> at slot ${v.slot ?? ', '}.`;+ <strong>${fmtNum(v.payload?.score, 0)}</strong> at slot ${v.slot ?? '-'}.`;return;}el.className = 'tp-pp-verdict is-bad';diff --git a/tests/api/llm-free-chain-reachability.test.js b/tests/api/llm-free-chain-reachability.test.jsnew file mode 100644index 000000000..86d2eca8d--- /dev/null+++ b/tests/api/llm-free-chain-reachability.test.js@@ -0,0 +1,186 @@+// Every rung of the free chain must be REACHABLE, proven by failing the rungs+// above it at the transport level.+//+// Why transport level specifically: this repo has already shipped a fallback+// that only caught parse errors, so it was bypassed exactly when the provider+// failed (a dead socket, a DNS failure, an abort) rather than when it returned+// a bad body. A chain tested only with `errResp(500)` looks healthy while the+// real failure mode walks straight past it. Each case here kills the rungs+// above with a thrown fetch (ECONNRESET / abort), the way a provider actually+// dies, and asserts the next rung answers.+//+// The free chain is not a degradation path any more, it is production: the+// OpenAI account is billing-dead (429 billing_not_active) and the OpenRouter+// platform key's balance is spent, so these rungs carry the traffic.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++vi.mock('../../api/_lib/gcp-auth.js', () => ({+ getGcpAccessToken: async () => 'fake-vertex-token',+}));++const HOSTS = {+ groq: 'api.groq.com',+ cerebras: 'api.cerebras.ai',+ openrouter: 'openrouter.ai',+ nvidia: 'integrate.api.nvidia.com',+ ovh: 'oai.endpoints.kepler.ai.cloud.ovh.net',+ gemini: 'generativelanguage.googleapis.com',+ vertex: 'aiplatform.googleapis.com',+ pollinations: 'text.pollinations.ai',+};++// The free chain in providerChain() order, with the env each rung needs. Groq+// appears twice on purpose: the 70B lane leads, and the instant lane is the+// last free rung (a separate per-model quota), so reaching it means every rung+// between them was tried and skipped.+const FREE_CHAIN = [+ { provider: 'groq', host: HOSTS.groq, model: 'llama-3.3-70b-versatile' },+ { provider: 'cerebras', host: HOSTS.cerebras, model: 'llama-3.3-70b' },+ { provider: 'openrouter', host: HOSTS.openrouter, model: 'openai/gpt-oss-20b:free' },+ { provider: 'nvidia', host: HOSTS.nvidia, model: 'meta/llama-3.3-70b-instruct' },+ { provider: 'ovh', host: HOSTS.ovh, model: 'Meta-Llama-3_3-70B-Instruct' },+ { provider: 'gemini', host: HOSTS.gemini, model: 'gemini-2.5-flash-lite' },+ { provider: 'vertex-gemini', host: HOSTS.vertex, model: 'google/gemini-2.5-flash' },+ { provider: 'pollinations', host: HOSTS.pollinations, model: 'openai-fast' },+ { provider: 'groq#instant', host: HOSTS.groq, model: 'llama-3.1-8b-instant' },+];++const ENV_KEYS = [+ 'GROQ_API_KEY',+ 'CEREBRAS_API_KEY',+ 'OPENROUTER_API_KEY',+ 'OPENROUTER_FALLBACK_KEYS',+ 'NVIDIA_API_KEY',+ 'GEMINI_API_KEY',+ 'GOOGLE_CLOUD_PROJECT',+ 'GOOGLE_CLOUD_LOCATION_GEMINI',+ 'ANTHROPIC_API_KEY',+ 'OPENAI_API_KEY',+ 'GROK_API_KEY',+ 'VERTEX_CLAUDE_ENABLED',+ 'VERTEX_CLAUDE_PRIMARY',+ 'OPENROUTER_CLAUDE_MIRROR_MODEL',+ 'NVIDIA_LANE_TIMEOUT_MS',+];++const saved = {};+let llm;++// Every free key configured, so the whole free chain is present in one run.+function configureFreeLanes() {+ process.env.GROQ_API_KEY = 'g';+ process.env.CEREBRAS_API_KEY = 'c';+ process.env.OPENROUTER_API_KEY = 'or';+ process.env.NVIDIA_API_KEY = 'nvapi-x';+ process.env.GEMINI_API_KEY = 'gem';+ process.env.GOOGLE_CLOUD_PROJECT = 'test-project';+ // The NIM lane's own cap is floored at 2s; keep it there so a transport+ // failure test never waits on it.+ process.env.NVIDIA_LANE_TIMEOUT_MS = '2000';+}++const okOpenAiShape = (content, model) => ({+ ok: true,+ status: 200,+ json: async () => ({ choices: [{ message: { content } }], usage: { prompt_tokens: 5, completion_tokens: 7 }, model }),+ text: async () => '{}',+});++// How a provider dies for real: the socket drops, or the attempt is aborted.+// Neither produces a response object, so a fallback that only inspects a parsed+// body never runs.+function transportFailure(kind) {+ if (kind === 'abort') return Object.assign(new Error('The operation was aborted'), { name: 'AbortError' });+ return Object.assign(new Error('fetch failed: ECONNRESET'), { cause: { code: 'ECONNRESET' } });+}++beforeEach(async () => {+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ vi.resetModules();+ llm = await import('../../api/_lib/llm.js');+});++afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ vi.restoreAllMocks();+});++describe('free chain: every rung is reachable through a transport-level failure', () => {+ it('lists the rungs in the documented order with every free key set', () => {+ configureFreeLanes();+ const names = llm.providerChain().map((p) => p.name);+ expect(names).toEqual(FREE_CHAIN.map((r) => r.provider));+ });++ // One case per rung: kill every rung above it the way a provider actually+ // dies (thrown fetch, not a 500 with a body), and require this rung to serve.+ 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) => {+ 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);+ // 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);+ });++ const out = await llm.llmComplete({ system: 's', user: 'u', timeoutMs: 30_000 });+ expect(out.provider).toBe(rung.provider);+ expect(out.model).toBe(rung.model);+ expect(out.text).toBe(`served by ${rung.provider}`);+ // Every rung above it was actually attempted, so this is a real failover+ // and not an accidental reordering of the chain.+ expect(tried.length).toBeGreaterThanOrEqual(i + 1);+ }, 30_000);+ }++ // A rung that dies at the transport level must not take its own retry budget+ // with it: the chain records the attempt and keeps going, and the thrown+ // error names every rung when nothing survives.+ it('reports every rung when the whole free chain dies at the transport level', async () => {+ configureFreeLanes();+ globalThis.fetch = vi.fn(async () => {+ throw transportFailure('reset');+ });+ const err = await llm.llmComplete({ user: 'u', timeoutMs: 20_000 }).catch((e) => e);+ expect(err.status).toBe(502);+ const reported = err.attempts.map((a) => a.provider);+ for (const rung of FREE_CHAIN) expect(reported).toContain(rung.provider);+ // Each attempt carries its own transport error, not a shared last-error.+ expect(err.attempts.every((a) => a.skipped || /unreachable/.test(a.error))).toBe(true);+ }, 30_000);++ // The keyless rungs are the floor of the platform: with zero env vars set the+ // chain must still answer, and a transport failure on the first keyless rung+ // must reach the second.+ it('serves from Pollinations when OVH dies at the transport level and nothing is configured', async () => {+ globalThis.fetch = vi.fn(async (url) => {+ const u = String(url);+ if (u.includes(HOSTS.ovh)) throw transportFailure('reset');+ if (u.includes(HOSTS.pollinations)) return okOpenAiShape('keyless floor', 'openai-fast');+ throw new Error(`unexpected fetch: ${u}`);+ });+ const out = await llm.llmComplete({ user: 'u', timeoutMs: 20_000 });+ expect(out.provider).toBe('pollinations');+ expect(out.text).toBe('keyless floor');+ }, 20_000);+});diff --git a/tests/trader-passport.test.js b/tests/trader-passport.test.jsindex 262086207..350d9e7ef 100644--- a/tests/trader-passport.test.js+++ b/tests/trader-passport.test.js@@ -37,6 +37,7 @@ function payload(over = {}) {score: 78, verified: true, closed: 41, win_rate: 0.61, realized_pnl_sol: 12.5,max_drawdown_pct: 18.4, unique_coins: 33, snipe_hit_rate: 0.42, snipe_sample: 12,self_dealing_excluded: 2, source: 'threews.trader-stats',+ ...over,};}@@ -190,7 +191,7 @@ describe('verifyOnChain', () => {expect(v).toMatchObject({ valid: true, found: true, attester: ATTESTER, subject: SUBJECT, slot: 300_123_456 });expect(v.reasons).toEqual([]);expect(v.payload.score).toBe(78);- expect(v.block_time).toBe('2026-06-14T09:35:00.000Z');+ expect(v.block_time).toBe(new Date(1_781_000_100 * 1000).toISOString());});it('rejects an attestation signed by someone other than the expected issuer', async () => {diff --git a/tests/x402-discovery-resources.test.js b/tests/x402-discovery-resources.test.jsindex 0f6460a9b..63dec03b6 100644--- a/tests/x402-discovery-resources.test.js+++ b/tests/x402-discovery-resources.test.js@@ -182,4 +182,33 @@ describe('projectDiscoveryResources', () => {expect(page.items).toEqual([]);expect(page.pagination.total).toBe(0);});++ // A crawler pages this catalog by offset with no cursor. Two builds that+ // hold the same resources in a different order must still page identically,+ // or a sweep reads some resources twice and never reads others at all.+ it('orders a page by resource regardless of catalog insertion order', () => {+ const urls = ['svc-c', 'svc-a', 'svc-b'].map((s) => `https://three.ws/api/x402/${s}`);+ const page = projectDiscoveryResources(+ doc(urls.map((url) => item({ url }))),+ {},+ );+ expect(page.items.map((i) => i.resource)).toEqual([...urls].sort());+ });++ it('pages two shuffled builds of one catalog to the same items', () => {+ const urls = Array.from({ length: 40 }, (_, i) => `https://three.ws/api/x402/svc-${i}`);+ const build = (order) => doc(order.map((url) => item({ url })));+ const forward = projectDiscoveryResources(build(urls), { limit: 10, offset: 20 });+ const reversed = projectDiscoveryResources(build([...urls].reverse()), { limit: 10, offset: 20 });+ expect(forward.items.map((i) => i.resource)).toEqual(reversed.items.map((i) => i.resource));+ });++ // The MCP transports publish one entry per tool at a single resource URL,+ // so `resource` alone is not a total order.+ it('breaks resource ties on tool name so same-url entries page stably', () => {+ const tool = (toolName) =>+ item({ url: 'https://three.ws/api/mcp', path: '/api/mcp', toolName });+ const page = projectDiscoveryResources(doc([tool('render'), tool('inspect'), tool('validate')]), {});+ expect(page.items.map((i) => i.metadata.toolName)).toEqual(['inspect', 'render', 'validate']);+ });});diff --git a/vite.config.js b/vite.config.jsindex ec3607f82..e9e09ed29 100644--- a/vite.config.js+++ b/vite.config.js@@ -509,6 +509,7 @@ const appConfig = {'exit-lab': resolve(__dirname, 'pages/exit-lab.html'),'claim-wallet': resolve(__dirname, 'pages/claim-wallet.html'),'meta-allocator': resolve(__dirname, 'pages/meta-allocator.html'),+ 'ghost-copy': resolve(__dirname, 'pages/ghost-copy.html'),'clip-director': resolve(__dirname, 'pages/clip-director.html'),'avatar-embed': resolve(__dirname, 'pages/avatar-embed.html'),'avatar-wallet-chat': resolve(__dirname, 'pages/avatar-wallet-chat.html'),