Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(cron): bound every outbound call and stop reporting a failed tick as success
nirholas8c366b8e2e0f
diff --git a/api/_lib/changelog-push.js b/api/_lib/changelog-push.jsindex b18d1e6d7..27cc73dd7 100644--- a/api/_lib/changelog-push.js+++ b/api/_lib/changelog-push.js@@ -35,6 +35,10 @@ const X_PACE_MS = 10000;const X_DAILY_CAP = 15; // free tier caps user writes at ~17/24h, stay underconst LOCK_KEY = 'changelog_push_lock';const LOCK_TTL_S = 240;+// Bounded, and well under LOCK_TTL_S on purpose: a send that hangs longer than+// the lock it is holding lets the next tick acquire that lock and re-post the+// same entry, which is exactly the double-post the lock exists to prevent.+const TELEGRAM_TIMEOUT_MS = 20_000;const ANCHOR_TEXT = ['everything we ship at three.ws lands in this thread. one reply per release, straight from the changelog.',@@ -151,6 +155,7 @@ async function sendTelegram(botToken, chatId, text) {parse_mode: 'HTML',link_preview_options: { is_disabled: false, prefer_small_media: true },}),+ signal: AbortSignal.timeout(TELEGRAM_TIMEOUT_MS),});const body = await res.json().catch(() => ({}));if (!res.ok || !body.ok) {diff --git a/api/_lib/commit-feed-push.js b/api/_lib/commit-feed-push.jsindex 8149b7aab..9ef83fb13 100644--- a/api/_lib/commit-feed-push.js+++ b/api/_lib/commit-feed-push.js@@ -21,6 +21,14 @@ const TELEGRAM_PACE_MS = 3500;const LOCK_KEY = 'commit_feed_push_lock';const LOCK_TTL_S = 240;const STATE_KEY = 'commit_feed_push_telegram';+// Every outbound call is bounded, and deliberately well under LOCK_TTL_S. The+// lock is what stops two ticks posting the same commit twice, but it only holds+// for its TTL: a request that hangs longer than that outlives its own lock, and+// the next tick (this cron runs every 5 minutes, i.e. 300s > 240s) acquires it+// and re-posts commits the stalled tick is still working through. Bounding the+// requests is what keeps the lock's guarantee true.+const GITHUB_TIMEOUT_MS = 20_000;+const TELEGRAM_TIMEOUT_MS = 20_000;async function ensureTable() {await sql`@@ -67,7 +75,10 @@ async function fetchRecentCommits() {const headers = { accept: 'application/vnd.github+json', 'user-agent': 'three.ws-commit-feed' };const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || '';if (token) headers.authorization = `Bearer ${token}`;- const res = await fetch(`https://api.github.com/repos/${REPO}/commits?sha=main&per_page=30`, { headers });+ const res = await fetch(`https://api.github.com/repos/${REPO}/commits?sha=main&per_page=30`, {+ headers,+ signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS),+ });if (!res.ok) throw new Error(`GitHub commits fetch failed (${res.status})`);return res.json();}@@ -171,6 +182,7 @@ async function sendTelegram(botToken, chatId, text, previewUrl) {// sits in the text), rendered below the message like the changelog feed.link_preview_options: { is_disabled: false, url: previewUrl, show_above_text: false },}),+ signal: AbortSignal.timeout(TELEGRAM_TIMEOUT_MS),});const body = await res.json().catch(() => ({}));if (!res.ok || !body.ok) {diff --git a/api/_lib/quality-bench.js b/api/_lib/quality-bench.jsindex a62e414bc..06e1f5388 100644--- a/api/_lib/quality-bench.js+++ b/api/_lib/quality-bench.js@@ -91,7 +91,12 @@ export async function judgeOnce({ png, promptEntry, viewLabel }) {] },],};- const res = await fetch(vertexGeminiChatUrl(), { method: 'POST', headers, body: JSON.stringify(body) });+ const res = await fetch(vertexGeminiChatUrl(), {+ method: 'POST',+ headers,+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(JUDGE_TIMEOUT_MS),+ });const data = await res.json().catch(() => ({}));if (!res.ok) throw new Error(`judge call ${res.status}: ${JSON.stringify(data).slice(0, 300)}`);const content = data?.choices?.[0]?.message?.content || '';@@ -111,8 +116,22 @@ function sleep(ms) {return new Promise((r) => setTimeout(r, ms));}+// Per-request ceilings. Every outbound call here needs one: the cron caller's+// `deadlineAt` is only ever consulted BETWEEN steps, so a single request that+// hangs sails straight past the budget no matter how carefully the loop above it+// counts. That is not hypothetical, it is the 2026-08-10 failure recorded in+// api/cron/quality-bench.js's header (900s spent, 504 from Cloud Run, Scheduler+// left holding DEADLINE_EXCEEDED). A catalog read and a forge submit are small+// JSON round trips; a poll is one status read, not the generation itself.+const CATALOG_TIMEOUT_MS = 15_000;+const SUBMIT_TIMEOUT_MS = 60_000;+const POLL_TIMEOUT_MS = 30_000;+// The judge spends ~1300 reasoning tokens before its verdict, so it is the+// slowest call here by design. Generous, but still a ceiling.+const JUDGE_TIMEOUT_MS = 120_000;+export async function loadCatalog(baseUrl) {- const res = await fetch(`${baseUrl}/api/forge?catalog`);+ const res = await fetch(`${baseUrl}/api/forge?catalog`, { signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS) });if (!res.ok) throw new Error(`catalog fetch failed: ${res.status}`);return res.json();}@@ -136,6 +155,7 @@ export async function submitForge(baseUrl, { prompt, mode, referenceImageUrl, timethod: 'POST',headers: { 'content-type': 'application/json', ...forgeSeedHeaders() },body: JSON.stringify(body),+ signal: AbortSignal.timeout(SUBMIT_TIMEOUT_MS),});const data = await res.json().catch(() => ({}));if (!res.ok) {@@ -158,7 +178,21 @@ export async function pollForge(baseUrl, jobId, { timeoutMs = 10 * 60 * 1000, inconst budgetBound = deadlineAt < ownDeadline;const deadline = budgetBound ? deadlineAt : ownDeadline;while (Date.now() < deadline) {- const res = await fetch(`${baseUrl}/api/forge?job=${encodeURIComponent(jobId)}`);+ // Clamped to whatever runway is actually left, so the last poll of a run+ // cannot overshoot the deadline the caller is being held to.+ const pollMs = Math.max(1, Math.min(POLL_TIMEOUT_MS, deadline - Date.now()));+ let res;+ try {+ res = await fetch(`${baseUrl}/api/forge?job=${encodeURIComponent(jobId)}`, {+ signal: AbortSignal.timeout(pollMs),+ });+ } catch {+ // One status read stalling says nothing about the generation behind it,+ // so keep waiting on the next tick rather than failing a job that is+ // still healthy. The deadline above, not this request, ends the wait.+ await sleep(Math.max(0, Math.min(intervalMs, deadline - Date.now())));+ continue;+ }const data = await res.json().catch(() => ({}));if (!res.ok) throw new Error(data?.error || `poll ${res.status}`);if (data.status === 'done') return data;diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 442ab9356..fc5de58ab 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -592,6 +592,11 @@ export const limits = {// so it gets a dedicated, tighter-than-trading bucket: enough to iterate on a// strategy a few times, bounded so it can't be turned into a free LLM relay.sniperCompileIp: (ip) => getLimiter('sniper:compile:ip', { limit: 20, window: '10 m' }).limit(ip),+ // Tweet drafting (api/x/draft.js) fans one request out to up to three LLM+ // completions on platform-paid keys, so it gets its own bucket rather than+ // draining `authIp`, which gates the actual publish. 20 per 10 min is many+ // more rerolls than composing a tweet needs and still caps the fan-out.+ xDraftIp: (ip) => getLimiter('x:draft:ip', { limit: 20, window: '10 m' }).limit(ip),// Strategy backtest (api/sniper/backtest.js) is a read-only replay over captured// history; cached by strategy hash, so this only gates cache-miss origin work.sniperBacktestIp: (ip) => getLimiter('sniper:backtest:ip', { limit: 40, window: '5 m' }).limit(ip),diff --git a/api/_lib/sniper-loops-health.js b/api/_lib/sniper-loops-health.jsindex 00e097f5c..f211196ce 100644--- a/api/_lib/sniper-loops-health.js+++ b/api/_lib/sniper-loops-health.js@@ -19,6 +19,15 @@* Every autonomous loop the fleet's learning depends on. `table`/`column` name* the freshest-row probe (the cron builds `select max(column) from table`* with an optional network filter); `maxAgeMs` is the staleness verdict line.+ *+ * A loop only belongs here when its writer is UNCONDITIONAL, i.e. a healthy run+ * always advances the probed column. That is why oracle-realized-labels+ * (oracle_realized_outcomes) is deliberately absent: it derives one row per mint+ * the fleet actually closed a REAL position on, so a paper-only or simply idle+ * fleet leaves the table empty and a probe here would page forever about a loop+ * that is working correctly. Its liveness is already implied by the loops that+ * feed it (llm-judging, oracle-scoring) plus oracle-calibration below, which+ * upserts all five conviction bands on every pass regardless of sample count.*/export const LOOPS = [{@@ -69,6 +78,14 @@ export const LOOPS = [maxAgeMs: 30 * 60_000, // cron every 2 minwhy: 'The conviction score gates entries and the oracle_crossing trigger polls it; a stale table blinds both.',},+ {+ name: 'oracle-calibration',+ table: 'oracle_calibration',+ column: 'updated_at',+ networkColumn: 'network',+ maxAgeMs: 13 * 3600_000, // cron every 6h, so this is two consecutive misses+ why: 'Bridge 3: is an 80-conviction coin actually winning 80% of the time? A stale table means the optimizer\'s Rule O is tuning entry thresholds against a correction factor nobody is re-measuring.',+ },];/**diff --git a/api/_lib/solana-token-meta.js b/api/_lib/solana-token-meta.jsindex e5306fd85..a843c7db9 100644--- a/api/_lib/solana-token-meta.js+++ b/api/_lib/solana-token-meta.js@@ -9,6 +9,11 @@// the on-chain decode (no off-chain JSON or image bytes resolution).import { PublicKey } from '@solana/web3.js';+import {+ TOKEN_2022_PROGRAM_ID,+ TOKEN_PROGRAM_ID,+ getTokenMetadata,+} from '@solana/spl-token';import { getConnection, solanaPubkey } from './pump.js';const METADATA_PROGRAM = new PublicKey('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s');@@ -53,6 +58,27 @@ async function fetchOnchainMetadata(connection, mintPk) {};}+/**+ * Read the metadata a Token-2022 mint carries inside its own account, in the+ * `TokenMetadata` extension, instead of in a separate Metaplex PDA. Every+ * pump.fun launch since the Token-2022 cutover stores it this way (the platform+ * coin $THREE included), and those mints have NO Metaplex account at all, so a+ * PDA-only reader reports them as nameless and image-less.+ *+ * Returns the same { name, symbol, uri } shape as the Metaplex path, or null+ * when the mint is classic SPL or carries no metadata extension.+ */+async function fetchToken2022Metadata(connection, mintPk, ownerProgram) {+ if (ownerProgram !== TOKEN_2022_PROGRAM_ID.toBase58()) return null;+ const md = await getTokenMetadata(connection, mintPk, undefined, TOKEN_2022_PROGRAM_ID);+ if (!md) return null;+ return {+ name: (md.name || '').trim(),+ symbol: (md.symbol || '').trim(),+ uri: (md.uri || '').trim(),+ };+}+// Resolve common gateway-less URIs to a fetchable HTTPS URL. Pinata/IPFS hashes// (`ipfs://...`) get rewritten to a public gateway; everything else is returned// as-is (must already be http(s):).@@ -197,8 +223,20 @@ export async function fetchTokenMeta(mint, { network = 'mainnet', includeImage =err.status = 404;throw err;}+ // An address can exist on-chain without being a token mint at all (a program,+ // a PDA, a wallet). Reading metadata off one of those yields an untitled+ // husk, so reject it here rather than charging a caller for a nameless+ // result: only the two SPL token programs own real mints.+ const owner = accountInfo.owner?.toBase58?.() || '';+ if (owner !== TOKEN_PROGRAM_ID.toBase58() && owner !== TOKEN_2022_PROGRAM_ID.toBase58()) {+ const err = new Error(`address is not an SPL token mint on ${network}`);+ err.code = 'mint_not_found';+ err.status = 404;+ throw err;+ }- const onchain = await fetchOnchainMetadata(connection, pk);+ const onchain = (await fetchToken2022Metadata(connection, pk, owner))+ || (await fetchOnchainMetadata(connection, pk));const off = onchain?.uri ? await fetchOffchainJson(onchain.uri) : null;const name = (off?.name || onchain?.name || '').toString().trim() || null;diff --git a/api/_lib/trust/reputation-store.js b/api/_lib/trust/reputation-store.jsindex 43a83e86b..494379481 100644--- a/api/_lib/trust/reputation-store.js+++ b/api/_lib/trust/reputation-store.js@@ -176,6 +176,14 @@ export async function listStaleAgents(limit = 40) {`;return rows.map((r) => r.id);} catch (err) {+ // A DB outage must NOT read as "nobody needs scoring": swallowing it made+ // the recompute cron answer {ok:true, scored:0} and heartbeat healthy for+ // as long as the database was down, so the one signal that the durable+ // scores had stopped refreshing was invisible. Re-throw it and let the+ // caller's wrapCron classify it as db_unavailable. Every other failure+ // (a missing column mid-migration, a malformed row) still degrades to an+ // empty batch, which the next tick retries.+ if (isDbUnavailableError(err)) throw err;console.warn('[reputation-store] listStaleAgents failed:', err?.message || err);return [];}diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 76c0f811a..e05377f66 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -395,64 +395,80 @@ async function erc8004CrawlChain(chain) {// Adaptive per chain, seeded by the declared override for a restrictive RPC.// See nextChunkSize: a fixed window is why fast chains never caught up.- const chunkSize = nextChunkSize({+ let chunkSize = nextChunkSize({stored: cursor?.chunk_size,configured: chain.blockChunk,behind: latestBlock - fromBlock + 1,});- const toBlock = Math.min(fromBlock + chunkSize - 1, latestBlock);-- const range = {- fromBlock: '0x' + fromBlock.toString(16),- toBlock: '0x' + toBlock.toString(16),- };+ let toBlock;let logs;let reputationLogs;- try {- // Topic OR-set, not the single Registered topic: an agent's row used to- // freeze at its registration block because ownership transfers, URI updates- // and metadata writes were never requested from the RPC at all. See the- // coverage census in api/_lib/erc8004-registry-events.js.- logs = await erc8004RpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getLogs', [- { address: chain.registry, topics: [REGISTRY_TOPICS], ...range },- ]);-- // The reputation registry lives at its own CREATE2 address on the same- // network class; scan the identical block range so an agent's trust signals- // (feedback, revocations, responses) reach the index alongside its identity- // history. A chain with no reputation deployment yields an empty log list,- // not an error.- reputationLogs = await erc8004RpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getLogs', [- { address: reputationRegistryFor(chain.testnet), topics: [REPUTATION_TOPICS], ...range },- ]);- } catch (err) {- // A range the provider will not serve is the growth loop finding this- // chain's real ceiling, not an outage. Halve the window, leave the cursor- // where it is, and let the next tick retry the same blocks smaller. Any- // other RPC failure is a genuine error and propagates.- if (!RANGE_REJECTED.test(String(err?.message || err))) throw err;- const reduced = backoffChunkSize(chunkSize);- await sql`- INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at, head_block, blocks_behind, chunk_size, last_error)- VALUES (${chain.id}, ${Math.max(0, fromBlock - 1)}, now(), ${latestBlock},- ${Math.max(0, latestBlock - fromBlock + 1)}, ${reduced}, ${'range rejected at ' + chunkSize + ' blocks'})- ON CONFLICT (chain_id) DO UPDATE SET- updated_at = now(),- head_block = excluded.head_block,- blocks_behind = excluded.blocks_behind,- chunk_size = excluded.chunk_size,- last_error = excluded.last_error- `;- return {- inserted: 0,- scanned: 0,- lastBlock: fromBlock - 1,- fromBlock,- blocksBehind: Math.max(0, latestBlock - fromBlock + 1),- chunkSize: reduced,- rangeRejected: true,+ // A rejected range is the growth loop finding this chain's ceiling, not an+ // outage, so shrink and retry the SAME blocks now rather than ending the tick+ // empty. Retrying only on the next tick deadlocks a chain forever: the+ // rejection stores the halved window, then nextChunkSize sees a backlog wider+ // than it and doubles straight back to the size that was just refused, so the+ // cursor never moves. Measured on 2026-08-14: BSC Testnet and Moonbeam sat at+ // scanned=0 across four consecutive ticks while their backlogs grew.+ let narrowedFrom = null;+ for (;;) {+ toBlock = Math.min(fromBlock + chunkSize - 1, latestBlock);+ const range = {+ fromBlock: '0x' + fromBlock.toString(16),+ toBlock: '0x' + toBlock.toString(16),};+ try {+ // Topic OR-set, not the single Registered topic: an agent's row used to+ // freeze at its registration block because ownership transfers, URI updates+ // and metadata writes were never requested from the RPC at all. See the+ // coverage census in api/_lib/erc8004-registry-events.js.+ logs = await erc8004RpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getLogs', [+ { address: chain.registry, topics: [REGISTRY_TOPICS], ...range },+ ]);++ // The reputation registry lives at its own CREATE2 address on the same+ // network class; scan the identical block range so an agent's trust signals+ // (feedback, revocations, responses) reach the index alongside its identity+ // history. A chain with no reputation deployment yields an empty log list,+ // not an error.+ reputationLogs = await erc8004RpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getLogs', [+ { address: reputationRegistryFor(chain.testnet), topics: [REPUTATION_TOPICS], ...range },+ ]);+ break;+ } catch (err) {+ // Any RPC failure that is not the provider refusing the range is a genuine+ // error and propagates to the per-chain handler above.+ if (!RANGE_REJECTED.test(String(err?.message || err))) throw err;+ const reduced = backoffChunkSize(chunkSize);+ if (reduced >= chunkSize) {+ // Already at the floor: the provider will not serve even the smallest+ // window this tick. Record it and leave the cursor untouched so the next+ // tick retries the same blocks against the failover RPC.+ await sql`+ INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at, head_block, blocks_behind, chunk_size, last_error)+ VALUES (${chain.id}, ${Math.max(0, fromBlock - 1)}, now(), ${latestBlock},+ ${Math.max(0, latestBlock - fromBlock + 1)}, ${chunkSize}, ${'range rejected at ' + chunkSize + ' blocks (floor)'})+ ON CONFLICT (chain_id) DO UPDATE SET+ updated_at = now(),+ head_block = excluded.head_block,+ blocks_behind = excluded.blocks_behind,+ chunk_size = excluded.chunk_size,+ last_error = excluded.last_error+ `;+ return {+ inserted: 0,+ scanned: 0,+ lastBlock: fromBlock - 1,+ fromBlock,+ blocksBehind: Math.max(0, latestBlock - fromBlock + 1),+ chunkSize,+ rangeRejected: true,+ };+ }+ narrowedFrom = narrowedFrom ?? chunkSize;+ chunkSize = reduced;+ }}// Fetch block timestamps for any blocks that produced events.@@ -629,6 +645,10 @@ async function erc8004CrawlChain(chain) {byClass,headBlock: latestBlock,blocksBehind,+ // Present only when the tick overshot the provider's ceiling and recovered+ // by shrinking in place, so the report distinguishes "settled at its real+ // window" from "asked for too much and still delivered".+ ...(narrowedFrom ? { narrowedFrom } : {}),chunkSize,};}@@ -854,8 +874,31 @@ const IDX_RPC_TIMEOUT_MS = 10_000;// The next tick advances the cursor and picks up the buffered blocks once they// are safely confirmed.const IDX_HEAD_CONFIRMATIONS = 5;-// Hard time budget per cron invocation — leave 8 s headroom before Vercel's 30 s limit.+// Hard time budget per cron invocation, leaving 8 s headroom before the 30 s+// serverless limit. It covers the WHOLE tick, so it is divided across the chains+// still to be indexed rather than consumed by whichever one runs first (see+// idxChainDeadline).const IDX_TIME_BUDGET_MS = 22_000;+// Floor on one chain's slice of that budget. Ethereum mainnet is both first in+// DELEGATION_MANAGER_DEPLOYMENTS and the slowest (its nodes cap eth_getLogs at 25+// blocks), so with a single shared deadline it spent the entire budget and every+// later chain returned zero batches on every tick. A chain that indexes nothing+// also never writes an indexer_state cursor, so it re-derived its start block from+// the head each tick and never made progress at all: Base delegation revocations+// went permanently unindexed. Each chain now gets an equal share of whatever is+// left, never less than this.+const IDX_MIN_CHAIN_SLICE_MS = 2_500;+// One cron period, matching this job's `*/5` schedule in vercel.json. Used only+// to rotate which chain is indexed first, so the offset advances by exactly one+// per tick and every chain leads once per full rotation.+const IDX_ROTATION_PERIOD_MS = 5 * 60_000;++// Wall-clock deadline for the chain about to be indexed: an even split of the+// budget that remains across the chains that remain.+function idxChainDeadline(started, chainsRemaining) {+ const left = Math.max(0, IDX_TIME_BUDGET_MS - (Date.now() - started));+ return Date.now() + Math.max(IDX_MIN_CHAIN_SLICE_MS, Math.floor(left / Math.max(1, chainsRemaining)));+}// Approximate blocks per day, used only to seed the cursor on first run.const BLOCKS_PER_DAY = {@@ -975,14 +1018,31 @@ async function handleIndexDelegations(req, res) {if (!requireCron(req, res)) return;const started = Date.now();- const report = { chains: [], expiredSwept: 0, errors: [] };+ const report = { chains: [], skippedChains: [], expiredSwept: 0, errors: [] };// Index each chain independently — one chain's RPC failure must not abort others.- for (const [chainIdStr, contract] of Object.entries(DELEGATION_MANAGER_DEPLOYMENTS)) {+ //+ // The lead position is rotated per tick. Every chain is guaranteed at least one+ // batch once it is started (a chain that indexes nothing never writes a cursor,+ // so it would re-derive its start block from the head forever and never make+ // progress), which means a slow chain can push the tail of the list past the+ // budget. Rotating puts a different chain at the front each tick, so the tail+ // is never the same chain twice and the budget stays a real ceiling.+ const deployments = Object.entries(DELEGATION_MANAGER_DEPLOYMENTS);+ const offset = Math.floor(started / IDX_ROTATION_PERIOD_MS) % deployments.length;+ const ordered = deployments.map((_, i) => deployments[(i + offset) % deployments.length]);++ for (const [i, [chainIdStr, contract]] of ordered.entries()) {const chainId = Number(chainIdStr);+ // Budget spent: leave the rest for the next tick, which will lead with a+ // chain further along the rotation.+ if (i > 0 && Date.now() - started > IDX_TIME_BUDGET_MS) {+ report.skippedChains.push(chainId);+ continue;+ }const t0 = Date.now();try {- const r = await idxIndexChain(chainId, contract, started);+ const r = await idxIndexChain(chainId, contract, idxChainDeadline(started, ordered.length - i));const summary = { chainId, ...r, elapsedMs: Date.now() - t0 };report.chains.push(summary);console.log(JSON.stringify({ stage: 'index-delegations', ...summary }));@@ -1020,7 +1080,7 @@ async function handleIndexDelegations(req, res) {return json(res, 200, report);}-async function idxIndexChain(chainId, contract, cronStart = Date.now()) {+async function idxIndexChain(chainId, contract, deadline = Date.now() + IDX_TIME_BUDGET_MS) {const urls = idxRpcUrls(chainId);if (!urls.length) throw new Error(`no RPC URL configured for chain ${chainId}`);@@ -1041,27 +1101,34 @@ async function idxIndexChain(chainId, contract, cronStart = Date.now()) {: Math.max(0, latestBlock - (BLOCKS_PER_DAY[chainId] ?? 7200));let fromBlock = initialFrom;- let toBlock = latestBlock; // updated each iteration; reflects final processed range+ // Seeded one block BEFORE the start so a chain that runs no batch at all+ // reports the empty range it actually covered. Seeding it to latestBlock made+ // a starved chain's summary read as a full successful scan.+ let toBlock = initialFrom - 1; // updated each iteration; reflects final processed range+ let batches = 0;let revokedCount = 0;let redeemedCount = 0;let logErrorCount = 0;let earlyExit = false;while (fromBlock <= latestBlock) {- // Hard time budget: save cursor and break before the function times out.- if (Date.now() - cronStart > IDX_TIME_BUDGET_MS) {+ // Time budget: save cursor and break before the function times out. Checked+ // at the top of the loop, so a chain always gets at least one batch even+ // when the earlier chains overran.+ if (batches > 0 && Date.now() > deadline) {console.warn(JSON.stringify({stage: 'index-delegations',chainId,warning: 'time-budget-exceeded',- elapsedMs: Date.now() - cronStart,+ overrunMs: Date.now() - deadline,stoppedAtBlock: fromBlock,}),);earlyExit = true;break;}+ batches += 1;toBlock = Math.min(fromBlock + BATCH - 1, latestBlock);@@ -1215,6 +1282,7 @@ async function idxIndexChain(chainId, contract, cronStart = Date.now()) {return {fromBlock: initialFrom,toBlock,+ batches,revokedCount,redeemedCount,logErrorCount,@@ -3228,8 +3296,15 @@ async function handleRunSubscriptions(req, res) {});return json(res, 200, { ok: true, skipped: true, reason: 'table_not_ready' });}+ // Rethrow rather than answering 500 here, so the shared cron wrapper applies+ // the same degrade every other cron gets: a transient Neon connection+ // failure becomes a clean `db_unavailable` skip, while a real statement+ // fault (syntax, constraint, missing column) still surfaces as a 500.+ // Returning the 500 directly hid the outage class from that classifier, and+ // because economy-tick fires this engine every minute, a Neon blip read as a+ // per-minute 500 stream and a permanently failed engine on the heartbeat.subLogError('subscription_cron.select_failed', { runId, message: err.message });- return error(res, 500, 'internal_error', 'failed to load subscriptions');+ throw err;}subLog('subscription_cron.selected', { runId, count: rows.length });diff --git a/api/cron/garment-catalog-audit.js b/api/cron/garment-catalog-audit.jsindex 6d742f8e5..1314c4940 100644--- a/api/cron/garment-catalog-audit.js+++ b/api/cron/garment-catalog-audit.js@@ -25,6 +25,15 @@ import { requireCron } from '../_lib/cron-auth.js';const CATALOG_URL = 'https://storage.googleapis.com/three-ws-garments/garments/catalog.json';const SPEC_URI = 'https://three.ws/specs/garment-manifest-v1';+// This sweep makes one request per catalog entry (a reachability HEAD) plus a+// full GLB download for each entry in the rotating re-hash subset, so an+// unbounded stall on any single object would hold the whole audit open to Cloud+// Run's 900s request timeout, well past Cloud Scheduler's 320s attempt deadline.+// A HEAD against GCS is a metadata round trip; a GLB download moves real bytes,+// so it gets the longer ceiling.+const HEAD_TIMEOUT_MS = 15_000;+const CATALOG_TIMEOUT_MS = 20_000;+const DOWNLOAD_TIMEOUT_MS = 60_000;const SLOTS = new Set(['top', 'bottom', 'footwear', 'outerwear', 'hair', 'headwear', 'glasses', 'accessory',]);@@ -54,14 +63,20 @@ function structuralErrors(m) {}async function head(url) {- const res = await fetch(url, { method: 'HEAD' }).catch(() => null);+ const res = await fetch(url, { method: 'HEAD', signal: AbortSignal.timeout(HEAD_TIMEOUT_MS) }).catch(() => null);return res?.ok ? null : `HEAD ${url} -> ${res ? res.status : 'unreachable'}`;}async function sha256Of(url) {- const res = await fetch(url).catch(() => null);+ const res = await fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) }).catch(() => null);if (!res?.ok) return null;- const buf = await res.arrayBuffer();+ // The timeout covers the body stream too, so a download that stalls partway+ // rejects here rather than at the fetch. Fall back to the same null this+ // function already returns for an unreachable object: "not hashed this run",+ // which the caller skips. A slow object must not be reported as sha256 drift,+ // and must not fail the audit for the entries that did verify.+ const buf = await res.arrayBuffer().catch(() => null);+ if (!buf) return null;const digest = await crypto.subtle.digest('SHA-256', buf);return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');}@@ -70,7 +85,7 @@ export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;if (!requireCron(req, res)) return;- const catRes = await fetch(CATALOG_URL).catch(() => null);+ const catRes = await fetch(CATALOG_URL, { signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS) }).catch(() => null);if (!catRes?.ok) {reportServerError(new Error(`garment catalog unreachable (${catRes?.status ?? 'network'})`), {code: 'garment_catalog_unreachable',diff --git a/api/cron/garment-job-sweep.js b/api/cron/garment-job-sweep.jsindex b6bc51937..b4dc3f480 100644--- a/api/cron/garment-job-sweep.js+++ b/api/cron/garment-job-sweep.js@@ -21,6 +21,14 @@import { error, json, method, reportServerError, wrapCron } from '../_lib/http.js';import { requireCron } from '../_lib/cron-auth.js';+// The worker answers as soon as it has taken the lock and queued the claimable+// records; it does not hold the connection for the re-driven generations. So a+// response this call is still waiting on after two minutes means the worker is+// wedged, not busy. Without a ceiling that wait runs to Cloud Run's 900s request+// timeout, long past Cloud Scheduler's 320s attempt deadline, and a cron that+// fires every 10 minutes stacks a new hung request on top of the last one.+const SWEEP_TIMEOUT_MS = 120_000;+export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;if (!requireCron(req, res)) return;@@ -37,6 +45,7 @@ export default wrapCron(async (req, res) => {method: 'POST',headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },body: '{}',+ signal: AbortSignal.timeout(SWEEP_TIMEOUT_MS),}).catch((err) => {reportServerError(err instanceof Error ? err : new Error(String(err)), {code: 'garment_sweep_unreachable',diff --git a/api/cron/news-archive-append.js b/api/cron/news-archive-append.jsindex 59704f4cd..8bda25f67 100644--- a/api/cron/news-archive-append.js+++ b/api/cron/news-archive-append.js@@ -152,7 +152,24 @@ export default wrapCron(async (req, res) => {const month = nowIso.slice(0, 7); // YYYY-MMlet token = null;- if (!dryRun) token = await getGcpAccessToken();+ if (!dryRun) {+ // getGcpAccessToken() throws `unconfigured` both when no credentials are+ // set AND when the Cloud Run metadata server is momentarily unreachable.+ // Unguarded, that turned a transient credential blip into an opaque 500+ // ("internal error, quote ref …") and an ops page, for the same reason the+ // generation-guard race below is caught rather than thrown: the archiver+ // is content-addressed and hourly, so a skipped run costs nothing but a+ // delay. Degrade the way wrapCron degrades an unavailable DB - a 200 the+ // scheduler will not retry-storm, carrying ok:false so monitoring can see+ // the archiver is not writing.+ try {+ token = await getGcpAccessToken();+ } catch (err) {+ if (err?.code !== 'unconfigured') throw err;+ console.error('news-archive-append: no GCP credentials, skipping this run:', err.message);+ return json(res, 200, { ok: false, month, appended: 0, reason: 'gcp_unconfigured' });+ }+ }// Live sweep across every source - the aggregator serves from its// per-source cache, so this is one bounded fan-out at most. The limit mustdiff --git a/api/cron/recompute-reputation.js b/api/cron/recompute-reputation.jsindex 12ad2f1aa..73bceb249 100644--- a/api/cron/recompute-reputation.js+++ b/api/cron/recompute-reputation.js@@ -16,6 +16,7 @@import { json, method, wrapCron } from '../_lib/http.js';import { listStaleAgents, recomputeAgents } from '../_lib/trust/reputation-store.js';+import { isDbUnavailableError } from '../_lib/db.js';import { requireCron } from '../_lib/cron-auth.js';// How many agents to recompute per tick. Each is a handful of indexed DB reads@@ -41,7 +42,12 @@ export default wrapCron(async (req, res) => {console.log(`[recompute-reputation] scored ${scored}/${ids.length} (failed ${failed}, remaining ${remaining}${timedOut ? ', hit time budget' : ''}) in ${Date.now() - started}ms`);return json(res, 200, { ok: true, scored, failed, remaining, timed_out: timedOut, batch: ids.length, elapsed_ms: Date.now() - started });} catch (err) {- // Never throw: a failed run leaves the prior stored scores intact.+ // A database outage is the platform-wide case wrapCron already owns: let it+ // through so the tick heartbeats unhealthy and answers with the same+ // {ok:false, reason:'db_unavailable'} shape every other cron does. Anything+ // else is contained here, because a failed run leaves the prior stored+ // scores intact and the next tick retries the same stalest agents.+ if (isDbUnavailableError(err)) throw err;console.error('[recompute-reputation] failed:', err?.message || err);return json(res, 200, { ok: false, error: err?.message || String(err) });}diff --git a/api/cron/settlement-verify.js b/api/cron/settlement-verify.jsindex a27335478..15e893dd4 100644--- a/api/cron/settlement-verify.js+++ b/api/cron/settlement-verify.js@@ -16,10 +16,25 @@//// Idempotent and swarm-safe: promotion flips verified_at from null in a// conditional UPDATE, so overlapping ticks cannot double-count a tip.+//+// Failure reporting: each lane is caught so one broken lane cannot strand the+// other, but a caught error must never be invisible. wrapCron only heartbeats+// ok:false and pages ops when a handler THROWS, so a lane error swallowed into+// the 200 body would leave this sweep silently dead: tips stop being promoted,+// every tick still answers 200, and nothing reads the body. A lane that errors+// therefore flips ok:false and pages ops (deduped per lane per hour).+//+// The tables both lanes read are created lazily by their write endpoints+// (show_tips/stages by api/stage/index.js, irl_interactions by the IRL pay+// path), so a deployment that has never hosted a show or taken an IRL pay is+// missing them legitimately. Those are probed with to_regclass and reported as+// absent rather than as an error, the same guard api/cron/irl-reap.js uses, so+// a fresh deployment never pages for a table nobody has needed yet.import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { requireCron } from '../_lib/cron-auth.js';+import { sendOpsAlert } from '../_lib/alerts.js';import { verifySettlement } from '../_lib/settlement-verify.js';import { promoteTip } from '../stage/tip.js';import { hostPayoutWallets } from '../_lib/stage-wallets.js';@@ -35,6 +50,23 @@ const GRACE_MINUTES = 60;// the rest.const BATCH = 40;+// Which of the lazily-created tables this sweep reads actually exist yet. One+// round trip, no error path: to_regclass returns null for an absent relation+// instead of raising, so this can run against a database that has never served+// a show or an IRL pay.+async function presentTables() {+ const [row] = await sql`+ SELECT+ to_regclass('public.show_tips') AS show_tips,+ to_regclass('public.stages') AS stages,+ to_regclass('public.irl_interactions') AS irl_interactions+ `;+ return {+ stageTips: Boolean(row?.show_tips && row?.stages),+ irlPays: Boolean(row?.irl_interactions),+ };+}+async function sweepStageTips() {const rows = await sql`SELECT t.id, t.show_id, t.stage_id, t.amount_atomic, t.currency_mint, t.settlement_sig,@@ -80,7 +112,7 @@ async function sweepIrlPays() {WHERE type = 'pay' AND verified_at IS NULLORDER BY created_at ASCLIMIT ${BATCH}- `.catch(() => []);+ `;let promoted = 0; let discarded = 0; let stillPending = 0;for (const row of rows) {const recipients = await agentPayoutWallets(row.agent_id);@@ -113,10 +145,36 @@ export default wrapCron(async (req, res) => {if (!requireCron(req, res)) return;const t0 = Date.now();- // One failing lane must not strand the other: both run, both report.++ // A probe failure is a real database fault, not a missing table, so it is+ // left to throw into wrapCron (which classifies db-unavailable separately and+ // pages ops on anything else).+ const present = await presentTables();++ // One failing lane must not strand the other: both run, both report. A lane+ // whose tables do not exist yet reports skipped; a lane that genuinely errors+ // reports the error AND pages ops below.const [tips, pays] = await Promise.all([- sweepStageTips().catch((err) => ({ error: err?.message || String(err) })),- sweepIrlPays().catch((err) => ({ error: err?.message || String(err) })),+ present.stageTips+ ? sweepStageTips().catch((err) => ({ error: err?.message || String(err) }))+ : Promise.resolve({ skipped: 'table_absent' }),+ present.irlPays+ ? sweepIrlPays().catch((err) => ({ error: err?.message || String(err) }))+ : Promise.resolve({ skipped: 'table_absent' }),]);- return json(res, 200, { ok: true, tips, pays, took_ms: Date.now() - t0 });++ // Surface a swallowed lane failure. Without this the sweep answers 200+ // forever while no tip is ever promoted again. Deduped per lane per hour by+ // sendOpsAlert's signature so a persistent fault pages once, not every tick.+ const broken = [['tips', tips], ['pays', pays]].filter(([, lane]) => lane?.error);+ for (const [lane, result] of broken) {+ console.error('[settlement-verify] lane failed', { lane, error: result.error });+ sendOpsAlert(+ 'Settlement sweep lane failing',+ `The ${lane} lane of /api/cron/settlement-verify errored: ${result.error}. Settlements in that lane are not being resolved, so verified payments stay quarantined.`,+ { signature: `settlement-verify:${lane}:${Math.floor(Date.now() / 3_600_000)}` },+ );+ }++ return json(res, 200, { ok: broken.length === 0, tips, pays, took_ms: Date.now() - t0 });});diff --git a/api/cron/x402-directory-registrar.js b/api/cron/x402-directory-registrar.jsindex 2d9eb5b4e..0c533c8f4 100644--- a/api/cron/x402-directory-registrar.js+++ b/api/cron/x402-directory-registrar.js@@ -13,9 +13,9 @@// after they enter the service catalog, and description drift on the// directory heals itself on the next pass.// • 402index rate-limits registration to 10/hour/IP; WINDOW=8 stays under.-// • Each candidate is first probed against our own origin for a live 402 —-// registering a not-yet-deployed route burns a rate-limited slot on a-// probe failure at their end.+// • Each candidate is first probed against our own origin to confirm the+// route is deployed. Registering a not-yet-deployed route burns a+// rate-limited slot on a probe failure at their end.//// Registrar strategy + the manual surfaces (x402scan, Bazaar, PR-based lists):// docs/x402-distribution.md. One-off/local batches: scripts/x402-register-directories.mjs.@@ -28,7 +28,28 @@ const FOUR02INDEX_REGISTER = 'https://402index.io/api/v1/register';const WINDOW = 8;const HOUR_MS = 3_600_000;-async function serves402(entry) {+/**+ * Is this catalog endpoint actually deployed at our origin?+ *+ * The probe exists for exactly one reason: keep a not-yet-shipped route from+ * burning one of 402index's 10 registrations/hour. So the question it must+ * answer is "does this route exist", NOT "does a bare, parameterless request+ * come back 402". Those two differ for any endpoint whose paywall sits behind a+ * parameter: `/api/x402/vanity-premium` answers 200 to a bare GET (the free+ * inventory browse) and 402 only to `?address=<in-stock base58>` (the buy).+ * Demanding a bare 402 excluded every such paid endpoint from the directory+ * permanently and silently, on every hourly tick, forever, and the registrar has no+ * way to synthesize a valid paid request for an arbitrary endpoint, so there was+ * no tick on which it could ever have passed.+ *+ * An undeployed route answers a clean JSON 404 from our origin, so 404 / 5xx /+ * unreachable is the honest "not deployed" signal and every other status (402,+ * 200, 401, 405, …) proves the route is live and worth listing.+ *+ * @param {object} entry live x402 catalog entry+ * @returns {Promise<{ live: boolean, status?: number, reason?: string }>}+ */+export async function probeDeployed(entry) {try {const r = await fetch(entry.endpoint, {method: entry.method,@@ -39,9 +60,12 @@ async function serves402(entry) {...(entry.method === 'POST' ? { body: '{}' } : {}),signal: AbortSignal.timeout(10_000),});- return r.status === 402;+ if (r.status === 404 || r.status >= 500) {+ return { live: false, status: r.status, reason: `origin_${r.status}` };+ }+ return { live: true, status: r.status };} catch {- return false;+ return { live: false, reason: 'origin_unreachable' };}}@@ -98,14 +122,14 @@ export default wrapCron(async (req, res) => {const results = [];for (const entry of batch) {- const live = await serves402(entry);- if (!live) {- results.push({ slug: entry.slug, action: 'skipped', reason: 'no_402_in_production' });+ const probe = await probeDeployed(entry);+ if (!probe.live) {+ results.push({ slug: entry.slug, action: 'skipped', reason: probe.reason });continue;}try {const r = await upsertAt402Index(entry);- results.push({ slug: entry.slug, action: 'upserted', ok: r.ok, status: r.status });+ results.push({ slug: entry.slug, action: 'upserted', ok: r.ok, status: r.status, probe: probe.status });if (!r.ok) console.warn(`[x402-directory-registrar] ${entry.slug} → ${r.status} ${r.body}`);} catch (err) {results.push({ slug: entry.slug, action: 'error', error: err.message });diff --git a/api/ops/health.js b/api/ops/health.jsindex 52fa6e66d..3a1594a5f 100644--- a/api/ops/health.js+++ b/api/ops/health.js@@ -143,6 +143,19 @@ export const CRONS = [{ id: 'wallet-intents', label: 'Wallet intents' },{ id: 'auto-rig-sweep', label: 'Auto rig sweep' },{ id: 'radar-watchlist', label: 'Radar watchlist' },+ // Preview-coverage crons. Every agent card, forge card, and marketplace+ // listing renders a real image only because one of these keeps draining its+ // backlog; when one stops, the surfaces degrade to gradient placeholders+ // slowly enough that nobody notices for weeks. They all wrote heartbeats+ // already (wrapCron does it for every cron), but nothing surfaced them, so+ // the only way to tell a stalled one from a healthy one was gcloud.+ { id: 'agent-avatar-backfill', label: 'Agent avatar backfill' },+ { id: 'avatar-thumbnail-backfill', label: 'Avatar thumbnail backfill' },+ { id: 'avatar-thumbnail-render', label: 'Avatar thumbnail render' },+ { id: 'forge-thumbnail-backfill', label: 'Forge thumbnail backfill' },+ { id: 'coin-intel-observe', label: 'Coin intel observe' },+ { id: 'unstoppable-tick', label: 'Unstoppable agent tick' },+ { id: 'sketchfab-showcase', label: 'Sketchfab showcase' },].map((c) => {const schedule = CRON_SCHEDULES.get(c.driven_by || c.id) || null;return { ...c, schedule, stale_after_ms: deriveStaleAfterMs(schedule) };diff --git a/scripts/cron-local-proof.mjs b/scripts/cron-local-proof.mjsnew file mode 100644index 000000000..8c8e264c6--- /dev/null+++ b/scripts/cron-local-proof.mjs@@ -0,0 +1,393 @@+#!/usr/bin/env node+/**+ * cron-local-proof: invoke real /api/cron/* handlers against a real Postgres.+ *+ * Cron audits kept stalling on the same wall: the handlers are only reachable+ * through the deployed service, so "does this cron actually run" could not be+ * answered without production credentials. This harness answers it locally, with+ * no mocks in the request path: the real server (server/index.mjs), the real+ * vercel.json route table, the real cron auth gate (api/_lib/cron-auth.js), and+ * the real handler bodies, all talking to a real Postgres.+ *+ * The one shim is at the wire level, not the logic level. api/_lib/db.js speaks+ * Neon's SQL-over-HTTP protocol, which a plain Postgres does not serve, so a+ * tiny local endpoint translates those POSTs onto `pg` and returns rows in+ * Neon's exact wire shape (every column raw text, driver-side parsing). This is+ * the same bridge scripts/a2a-spend-hardening-proof.mjs and+ * scripts/genome-endpoints-proof.mjs already use; the SQL that runs is the SQL+ * the handler wrote.+ *+ * What it proves, per cron:+ * auth unauthenticated GET is rejected (401, or 503 when CRON_SECRET is+ * unset) and never executes the body+ * run an authenticated GET completes without an unhandled error+ * idempotent a second authenticated GET behaves the same as the first+ *+ * Setup (one time):+ * docker run -d --name cronb05-pg -e POSTGRES_PASSWORD=b05 \+ * -e POSTGRES_USER=b05 -e POSTGRES_DB=b05 -p 55705:5432 postgres:16-alpine+ * node scripts/cron-local-proof.mjs --bootstrap+ *+ * Usage:+ * node scripts/cron-local-proof.mjs # the default batch+ * node scripts/cron-local-proof.mjs --crons irl-reap,uptime-check+ * node scripts/cron-local-proof.mjs --bootstrap # apply schema first+ * node scripts/cron-local-proof.mjs --keep # leave the server up+ *+ * CRON_PROOF_DATABASE_URL overrides the local Postgres URL. Point it ONLY at a+ * throwaway database: these handlers DELETE and UPDATE rows for real.+ */++import http from 'node:http';+import net from 'node:net';+import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');++const PG_URL = process.env.CRON_PROOF_DATABASE_URL+ || 'postgresql://b05:[email protected]:55705/b05';++// A local-only secret. The gate compares it in constant time against whatever+// the caller presents, so a value generated here exercises the identical path a+// Cloud Scheduler OIDC bearer takes in production.+const CRON_SECRET = process.env.CRON_PROOF_SECRET || 'local-cron-proof-secret';++const DEFAULT_CRONS = [+ 'irl-reap',+ 'settlement-verify',+ 'expire-pending-purchases',+ 'confirm-pending-purchases',+ 'uptime-check',+ 'world-health',+ 'forge-smoke',+ 'forge-finalize',+];++const argv = process.argv.slice(2);+const flag = (name) => argv.includes(`--${name}`);+function opt(name, fallback) {+ const i = argv.indexOf(`--${name}`);+ return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;+}++const CRONS = opt('crons', DEFAULT_CRONS.join(',')).split(',').map((s) => s.trim()).filter(Boolean);+const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'cron-proof-'));++const cleanup = [];+async function shutdown() {+ for (const fn of cleanup.splice(0).reverse()) {+ try { await fn(); } catch { /* best effort */ }+ }+}+process.on('SIGINT', async () => { await shutdown(); process.exit(130); });++async function freePort(start) {+ for (let p = start; p < start + 200; p++) {+ const ok = await new Promise((resolve) => {+ const s = net.createServer();+ s.once('error', () => resolve(false));+ s.once('listening', () => s.close(() => resolve(true)));+ s.listen(p, '127.0.0.1');+ });+ if (ok) return p;+ }+ throw new Error(`no free port near ${start}`);+}++async function waitFor(fn, { tries = 120, delayMs = 500, label = 'dependency' } = {}) {+ let last;+ for (let i = 0; i < tries; i++) {+ try { const v = await fn(); if (v) return v; } catch (e) { last = e; }+ await new Promise((r) => setTimeout(r, delayMs));+ }+ throw new Error(`timed out waiting for ${label}${last ? `: ${last.message}` : ''}`);+}++// ── Neon HTTP bridge ─────────────────────────────────────────────────────────+// Neon's endpoint hands every column back as raw text and lets the driver's own+// pg-types parsers build the JS value. Parsing here as well would double-parse:+// a boolean re-entering parseBool as a non-string comes back false, and a+// pre-parsed jsonb object makes JSON.parse throw on "[object Object]". Only the+// types the driver cannot recover from text alone are coerced.+const NUMERIC_OIDS = new Set([700, 701, 1700]);+const INT_OIDS = new Set([20, 21, 23, 26]);+function coerce(value, oid) {+ if (value === null || value === undefined) return null;+ if (oid === 16) return value === 't' || value === 'true';+ if (INT_OIDS.has(oid)) {+ const n = BigInt(value);+ return n <= 9007199254740991n && n >= -9007199254740991n ? Number(n) : value;+ }+ if (NUMERIC_OIDS.has(oid)) return Number(value);+ return value;+}++async function startShim(pool) {+ const port = await freePort(54800);+ const server = http.createServer(async (req, res) => {+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return; }+ let body = '';+ for await (const c of req) body += c;+ try {+ const { query, params } = JSON.parse(body || '{}');+ const r = await pool.query({+ text: query,+ values: params || [],+ rowMode: 'array',+ types: { getTypeParser: () => (v) => v },+ });+ const rows = r.rows.map((row) => row.map((v, i) => coerce(v, r.fields[i].dataTypeID)));+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({+ fields: r.fields.map((f) => ({ name: f.name, dataTypeID: f.dataTypeID })),+ rows,+ rowCount: r.rowCount,+ command: r.command,+ }));+ } catch (e) {+ res.writeHead(500, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ message: String(e?.message || e), code: e?.code, constraint: e?.constraint }));+ }+ });+ await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve));+ cleanup.push(() => new Promise((r) => server.close(r)));++ const preload = path.join(TMP, 'preload.mjs');+ fs.writeFileSync(preload, `+import { neonConfig } from ${JSON.stringify(path.join(root, 'node_modules/@neondatabase/serverless/index.mjs'))};+neonConfig.fetchEndpoint = () => ${JSON.stringify(`http://127.0.0.1:${port}/sql`)};+`);+ return { port, preload };+}++// ── schema ───────────────────────────────────────────────────────────────────+// Split a .sql file into individual statements. Postgres' simple-query protocol+// runs a whole multi-statement string in one implicit transaction, so a single+// unsatisfiable statement rolls back every table the file would have created.+// Applying statement by statement keeps the 90% that does apply. Dollar-quoted+// bodies ($$ … $$, $tag$ … $tag$), single/double-quoted literals, and both+// comment styles are skipped so a semicolon inside one never splits a statement.+export function splitStatements(text) {+ const out = [];+ let buf = '';+ let i = 0;+ while (i < text.length) {+ const ch = text[i];+ const rest = text.slice(i);+ if (ch === '-' && text[i + 1] === '-') {+ const nl = text.indexOf('\n', i);+ i = nl === -1 ? text.length : nl;+ continue;+ }+ if (ch === '/' && text[i + 1] === '*') {+ const end = text.indexOf('*/', i + 2);+ i = end === -1 ? text.length : end + 2;+ continue;+ }+ if (ch === "'" || ch === '"') {+ const quote = ch;+ let j = i + 1;+ while (j < text.length) {+ if (text[j] === quote && text[j + 1] === quote) { j += 2; continue; }+ if (text[j] === quote) break;+ j++;+ }+ buf += text.slice(i, j + 1);+ i = j + 1;+ continue;+ }+ const dollar = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(rest);+ if (dollar) {+ const tag = dollar[0];+ const end = text.indexOf(tag, i + tag.length);+ const stop = end === -1 ? text.length : end + tag.length;+ buf += text.slice(i, stop);+ i = stop;+ continue;+ }+ if (ch === ';') {+ if (buf.trim()) out.push(buf.trim());+ buf = '';+ i++;+ continue;+ }+ buf += ch;+ i++;+ }+ if (buf.trim()) out.push(buf.trim());+ return out;+}++// Same order db-bootstrap.mjs uses: the three base files create the tables the+// incremental migrations then ALTER, so migrations must come last. Repeated+// passes resolve forward references (a migration that ALTERs a table a+// later-sorted file creates) without needing a dependency graph: each pass+// retries only what is still failing, and the loop stops as soon as a pass+// fixes nothing new.+async function bootstrapSchema(pool, { passes = 4 } = {}) {+ const base = [+ 'api/_lib/schema.sql',+ 'specs/schema/indexer_state.sql',+ 'specs/schema/agent_delegations.sql',+ ];+ const migrationsDir = path.join(root, 'api/_lib/migrations');+ const migrations = fs.readdirSync(migrationsDir)+ .filter((f) => f.endsWith('.sql'))+ .sort()+ .map((f) => path.join('api/_lib/migrations', f));++ let pending = [];+ for (const rel of [...base, ...migrations]) {+ const abs = path.join(root, rel);+ if (!fs.existsSync(abs)) continue;+ for (const stmt of splitStatements(fs.readFileSync(abs, 'utf8'))) {+ pending.push({ file: rel, stmt });+ }+ }++ const total = pending.length;+ let applied = 0;+ for (let pass = 0; pass < passes && pending.length; pass++) {+ const stillFailing = [];+ for (const item of pending) {+ try {+ await pool.query(item.stmt);+ applied++;+ } catch (e) {+ item.message = String(e?.message || e).split('\n')[0];+ stillFailing.push(item);+ }+ }+ if (stillFailing.length === pending.length) { pending = stillFailing; break; }+ pending = stillFailing;+ }+ return { total, applied, failed: pending };+}++// ── server ───────────────────────────────────────────────────────────────────+async function startServer(preload) {+ const port = await freePort(8410);+ const child = spawn('node', [path.join(root, 'server/index.mjs')], {+ cwd: root,+ env: {+ ...process.env,+ NODE_OPTIONS: `${process.env.NODE_OPTIONS || ''} --import ${JSON.stringify(preload)}`.trim(),+ PORT: String(port),+ DATABASE_URL: PG_URL,+ CRON_SECRET,+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ const logPath = path.join(TMP, 'server.log');+ const log = fs.createWriteStream(logPath);+ child.stdout.pipe(log);+ child.stderr.pipe(log);+ cleanup.push(() => { child.kill('SIGKILL'); });++ const base = `http://127.0.0.1:${port}`;+ await waitFor(async () => {+ const r = await fetch(`${base}/api/healthz`).catch(() => null);+ return r && r.status < 600;+ }, { label: `server on :${port}`, tries: 120 });+ return { base, logPath, child };+}++// ── probes ───────────────────────────────────────────────────────────────────+async function call(base, name, { auth }) {+ const t0 = Date.now();+ const res = await fetch(`${base}/api/cron/${name}`, {+ headers: auth ? { authorization: `Bearer ${CRON_SECRET}` } : {},+ }).catch((e) => ({ status: 0, _err: e }));+ if (!res || res.status === 0) {+ return { status: 0, ms: Date.now() - t0, body: String(res?._err?.message || 'fetch failed') };+ }+ const text = await res.text();+ let body;+ try { body = JSON.parse(text); } catch { body = text.slice(0, 400); }+ return { status: res.status, ms: Date.now() - t0, body };+}++function summarize(body) {+ if (body && typeof body === 'object') {+ const s = JSON.stringify(body);+ return s.length > 300 ? `${s.slice(0, 300)}…` : s;+ }+ return String(body).slice(0, 300);+}++async function main() {+ console.log(`cron-local-proof: ${CRONS.length} cron(s)`);+ console.log(` postgres : ${PG_URL.replace(/:[^:@/]+@/, ':***@')}`);++ const pgMod = await import('pg').catch(() => null);+ if (!pgMod) {+ console.error('\n`pg` is not installed. Run: npm i --no-save pg');+ process.exit(2);+ }+ const pool = new (pgMod.default || pgMod).Pool({ connectionString: PG_URL, max: 8 });+ cleanup.push(() => pool.end());+ await waitFor(() => pool.query('SELECT 1').then(() => true), { label: 'postgres', tries: 30 });++ if (flag('bootstrap')) {+ console.log('\n━━ schema ━━');+ const { total, applied, failed } = await bootstrapSchema(pool);+ console.log(` applied ${applied}/${total} statement(s)`);+ if (failed.length) {+ const byFile = new Map();+ for (const f of failed) byFile.set(f.file, (byFile.get(f.file) || 0) + 1);+ console.log(` ${failed.length} statement(s) across ${byFile.size} file(s) did not apply from scratch:`);+ for (const f of failed.slice(0, 10)) console.log(` ${f.file}: ${f.message}`);+ if (failed.length > 10) console.log(` …and ${failed.length - 10} more`);+ }+ }++ const { port: shimPort, preload } = await startShim(pool);+ console.log(` neon shim: http://127.0.0.1:${shimPort}/sql`);++ const { base, logPath } = await startServer(preload);+ console.log(` server : ${base}`);+ console.log(` log : ${logPath}`);++ const results = [];+ for (const name of CRONS) {+ const unauth = await call(base, name, { auth: false });+ const first = await call(base, name, { auth: true });+ const second = await call(base, name, { auth: true });++ const authOk = unauth.status === 401 || unauth.status === 503;+ const runOk = first.status >= 200 && first.status < 500 && first.status !== 0;+ const idemOk = runOk && second.status === first.status;++ results.push({ name, unauth, first, second, authOk, runOk, idemOk });++ const mark = (ok) => (ok ? 'PASS' : 'FAIL');+ console.log(`\n── ${name}`);+ console.log(` auth ${mark(authOk)} unauthenticated → ${unauth.status}`);+ console.log(` run ${mark(runOk)} ${first.status} in ${first.ms}ms ${summarize(first.body)}`);+ console.log(` idempotent ${mark(idemOk)} ${second.status} in ${second.ms}ms ${summarize(second.body)}`);+ }++ const failures = results.filter((r) => !r.authOk || !r.runOk || !r.idemOk);+ console.log('\n━━ summary ━━');+ for (const r of results) {+ console.log(` ${(!r.authOk || !r.runOk || !r.idemOk) ? 'FAIL' : 'PASS'} ${r.name} (auth ${r.unauth.status}, run ${r.first.status}, again ${r.second.status})`);+ }+ console.log(`\n${results.length - failures.length}/${results.length} cron(s) clean.`);++ if (flag('keep')) {+ console.log(`\nServer left running at ${base}. Ctrl-C to stop.`);+ await new Promise(() => {});+ }+ await shutdown();+ process.exit(failures.length ? 1 : 0);+}++main().catch(async (err) => {+ console.error(`\ncron-local-proof failed: ${err?.stack || err}`);+ await shutdown();+ process.exit(2);+});diff --git a/tests/quality-bench-budget.test.js b/tests/quality-bench-budget.test.jsindex 434ba1461..8fe4d77cc 100644--- a/tests/quality-bench-budget.test.js+++ b/tests/quality-bench-budget.test.js@@ -16,6 +16,11 @@* read as a quality regression.* 4. The per-view render/judge loop stops at the deadline too, instead of* running on past a response nobody is listening to.+ * 5. Every outbound request carries its own ceiling. `deadlineAt` is only ever+ * consulted BETWEEN steps, so one request that hangs sails past the budget+ * no matter how carefully the loop counts, which is the 900s overrun above.+ * A stalled poll must not be mistaken for a failed generation though: the+ * wait continues to the deadline instead of killing a healthy job.*/import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';@@ -79,6 +84,51 @@ describe('pollForge deadlineAt', () => {});});+describe('pollForge per-request ceiling', () => {+ it('bounds every status read so one hung request cannot outlive the budget', async () => {+ const signals = [];+ globalThis.fetch = vi.fn(async (url, init) => {+ if ((init?.method || 'GET') === 'POST') return { ok: true, json: async () => ({ job_id: 'j1' }) };+ signals.push(init?.signal);+ return { ok: true, json: async () => ({ status: 'done' }) };+ });+ await pollForge(BASE, 'j1', { intervalMs: 10, deadlineAt: Date.now() + 5000 });+ expect(signals).toHaveLength(1);+ // Without this the deadline is advisory: the loop only re-checks it once a+ // request comes back, so a request that never does is never checked at all.+ expect(signals[0]).toBeInstanceOf(AbortSignal);+ });++ it('keeps waiting when one status read stalls instead of failing a healthy job', async () => {+ let polls = 0;+ globalThis.fetch = vi.fn(async (url, init) => {+ if ((init?.method || 'GET') === 'POST') return { ok: true, json: async () => ({ job_id: 'j1' }) };+ polls += 1;+ // First read times out the way AbortSignal.timeout aborts a stalled+ // request; the generation behind it is untouched and finishes next tick.+ if (polls === 1) throw Object.assign(new Error('The operation was aborted'), { name: 'TimeoutError' });+ return { ok: true, json: async () => ({ status: 'done' }) };+ });+ await expect(pollForge(BASE, 'j1', { intervalMs: 10, deadlineAt: Date.now() + 5000 })).resolves.toMatchObject({+ status: 'done',+ });+ expect(polls).toBe(2);+ });++ it('still gives up at the deadline when every status read stalls', async () => {+ globalThis.fetch = vi.fn(async (url, init) => {+ if ((init?.method || 'GET') === 'POST') return { ok: true, json: async () => ({ job_id: 'j1' }) };+ throw Object.assign(new Error('The operation was aborted'), { name: 'TimeoutError' });+ });+ const started = Date.now();+ await expect(+ pollForge(BASE, 'j1', { timeoutMs: 10 * 60 * 1000, intervalMs: 10, deadlineAt: Date.now() + 60 }),+ ).rejects.toMatchObject({ code: 'budget_exhausted' });+ // Retrying a stalled read must not become a way to loop past the budget.+ expect(Date.now() - started).toBeLessThan(5000);+ });+});+describe('runOne under a budget', () => {it('reports an exhausted budget without scoring it as a zero', async () => {globalThis.fetch = stubForge({ submitResponse: { job_id: 'j1' } });diff --git a/tests/sniper-postmortem-fixes.test.js b/tests/sniper-postmortem-fixes.test.jsindex 32f033cdf..7fa0c0b0f 100644--- a/tests/sniper-postmortem-fixes.test.js+++ b/tests/sniper-postmortem-fixes.test.js@@ -108,6 +108,28 @@ describe('classifyLoopHealth (count rows, not status codes)', () => {expect(names).toContain('outcome-labeling');expect(names).toContain('llm-judging');expect(names).toContain('oracle-scoring');+ // Bridge 3 (api/cron/oracle-calibrate) writes every conviction band on every+ // pass, so it is exactly the kind of unconditional writer this watchdog can+ // hold to a deadline.+ expect(names).toContain('oracle-calibration');+ });++ it('leaves out loops whose writer is conditional on real trades', () => {+ // oracle-realized-labels only produces a row per mint the fleet really+ // closed. An idle or paper-only fleet writes nothing while working fine, so+ // probing it here would page forever. Guard the omission so it stays+ // deliberate rather than looking like something nobody got around to.+ expect(LOOPS.map((l) => l.table)).not.toContain('oracle_realized_outcomes');+ });++ it('holds the calibration loop to two missed 6h runs', () => {+ const calibration = LOOPS.find((l) => l.name === 'oracle-calibration');+ expect(calibration.table).toBe('oracle_calibration');+ expect(calibration.column).toBe('updated_at');+ expect(calibration.networkColumn).toBe('network');+ // One skipped run is fine; two in a row means the bridge stopped measuring.+ expect(classifyLoopHealth([probe('oracle-calibration', 7 * 3600_000)], NOW).stale).toHaveLength(0);+ expect(classifyLoopHealth([probe('oracle-calibration', 14 * 3600_000)], NOW).stale).toHaveLength(1);});it('passes loops with fresh rows', () => {diff --git a/tests/solana-token-meta-token2022.test.js b/tests/solana-token-meta-token2022.test.jsnew file mode 100644index 000000000..671b5a74f--- /dev/null+++ b/tests/solana-token-meta-token2022.test.js@@ -0,0 +1,169 @@+/**+ * api/_lib/solana-token-meta.js: which on-chain account a mint's name, symbol,+ * and off-chain `uri` actually come from.+ *+ * The reader used to look in exactly one place, the Metaplex Token Metadata+ * PDA. Every pump.fun launch since the Token-2022 cutover, the platform coin+ * $THREE included, stores that metadata INSIDE the mint account instead, in the+ * TokenMetadata extension, and has no Metaplex account at all. So the two paid+ * routes built on this reader (/api/x402/mint-to-mesh and its batch sibling)+ * charged a buyer $0.001 and handed back an untitled, untextured cube:+ * name null, symbol null, hasImage false, because the off-chain `uri` that+ * carries the image was never found either.+ *+ * The mint account bytes below are the real 411-byte $THREE mint account read+ * from mainnet, so the Token-2022 path is decoded here exactly as it is in+ * production, with no network and no stub decoder.+ *+ * Third rule pinned here: an address that exists on-chain but is not a token+ * mint at all (a program, a PDA, a wallet) is a 404, not a nameless husk a+ * caller gets billed for.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { PublicKey } from '@solana/web3.js';+import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const SYSTEM_PROGRAM = '11111111111111111111111111111112';++// Real mainnet bytes: the $THREE mint account, carrying the metadataPointer and+// tokenMetadata extensions (name "three.ws", symbol "three", ipfs.io uri).+const THREE_MINT_ACCOUNT_B64 =+ 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUIaigDGNAwAGAQAAAAAAAAAAAAAAAAAAAAAA' ++ 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' ++ 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARIAQAAAAAAAAAAAAAAAAAAA' ++ 'AAAAAAAAAAAAAAAAAAAAAAAAAANmVY1rrT6TOBsHGhgrWf58Jwp3c966+FFfgpUEBdj8fEwCtAAAAAAAAAAA' ++ 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2ZVjWutPpM4GwcaGCtZ/nwnCndz3rr4UV+ClQQF2Px8IAAAAdG' ++ 'hyZWUud3MFAAAAdGhyZWVQAAAAaHR0cHM6Ly9pcGZzLmlvL2lwZnMvYmFma3JlaWZ0b3JnczVrbm9xcjN6NT' ++ 'N1bmpwZG1neWhwNGFiam5xamthc3QzaXEzdGZvZmV0bTJvb20AAAAA';++const THREE_MINT_DATA = Buffer.from(THREE_MINT_ACCOUNT_B64, 'base64');++// A classic SPL mint: 82 bytes, owned by the original token program, metadata+// lives in a separate Metaplex PDA. Layout tail is what the reader parses.+const CLASSIC_MINT_DATA = Buffer.alloc(82);++// Metaplex metadata account body: key(1) updateAuthority(32) mint(32) then+// borsh name/symbol/uri, each length-prefixed and space-padded to its max.+function metaplexAccount({ name, symbol, uri }) {+ const parts = [Buffer.alloc(1 + 32 + 32)];+ const padded = (value, max) => {+ const len = Buffer.alloc(4);+ len.writeUInt32LE(value.length, 0);+ const body = Buffer.alloc(max);+ body.write(value, 'utf8');+ return Buffer.concat([len, body]);+ };+ parts.push(padded(name, 32), padded(symbol, 10), padded(uri, 200));+ return Buffer.concat(parts);+}++// Accounts keyed by address; anything not listed does not exist on chain.+let accounts = new Map();++vi.mock('../api/_lib/pump.js', () => ({+ solanaPubkey: (value) => {+ try {+ return new PublicKey(value);+ } catch {+ return null;+ }+ },+ getConnection: () => ({+ getAccountInfo: async (pk) => accounts.get(pk.toBase58()) || null,+ }),+}));++const { fetchTokenMeta } = await import('../api/_lib/solana-token-meta.js');++// The off-chain JSON document is a network read; every case here either has no+// uri or stubs the fetch, so no test touches the internet.+const originalFetch = globalThis.fetch;++beforeEach(() => {+ accounts = new Map();+ globalThis.fetch = originalFetch;+});++describe('fetchTokenMeta: Token-2022 inline metadata', () => {+ it('reads name, symbol, and uri out of the mint account itself', async () => {+ accounts.set(THREE_MINT, { owner: TOKEN_2022_PROGRAM_ID, data: THREE_MINT_DATA });+ // The reader follows the uri to the off-chain document for the image.+ globalThis.fetch = async () =>+ new Response(JSON.stringify({ description: 'the three.ws coin' }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });++ const meta = await fetchTokenMeta(THREE_MINT, { includeImage: false });++ expect(meta.name).toBe('three.ws');+ expect(meta.symbol).toBe('three');+ expect(meta.uri).toBe(+ 'https://ipfs.io/ipfs/bafkreiftorgs5knoqr3z53unjpdmgyhp4abjnqjkast3iq3tfofetm2oom',+ );+ expect(meta.description).toBe('the three.ws coin');+ });++ it('does not need a Metaplex account to exist for a Token-2022 mint', async () => {+ accounts.set(THREE_MINT, { owner: TOKEN_2022_PROGRAM_ID, data: THREE_MINT_DATA });+ globalThis.fetch = async () => new Response('{}', { status: 200 });++ // accounts holds ONLY the mint, so any PDA read resolves to null.+ await expect(fetchTokenMeta(THREE_MINT, { includeImage: false })).resolves.toMatchObject({+ symbol: 'three',+ });+ });+});++describe('fetchTokenMeta: classic SPL mints still read the Metaplex PDA', () => {+ it('resolves name and symbol from the metadata account', async () => {+ const mintPk = new PublicKey(THREE_MINT);+ const metadataProgram = new PublicKey('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s');+ const [pda] = PublicKey.findProgramAddressSync(+ [Buffer.from('metadata'), metadataProgram.toBuffer(), mintPk.toBuffer()],+ metadataProgram,+ );+ accounts.set(THREE_MINT, { owner: TOKEN_PROGRAM_ID, data: CLASSIC_MINT_DATA });+ accounts.set(pda.toBase58(), {+ owner: metadataProgram,+ data: metaplexAccount({ name: 'Legacy Coin', symbol: 'LEG', uri: '' }),+ });++ const meta = await fetchTokenMeta(THREE_MINT, { includeImage: false });++ expect(meta.name).toBe('Legacy Coin');+ expect(meta.symbol).toBe('LEG');+ });+});++describe('fetchTokenMeta: addresses that are not token mints', () => {+ it('rejects an on-chain account owned by some other program', async () => {+ // The system program address exists, so the "account not found" guard+ // alone waves it through. Only the owner check catches it.+ accounts.set(SYSTEM_PROGRAM, {+ owner: new PublicKey('11111111111111111111111111111111'),+ data: Buffer.alloc(0),+ });++ await expect(fetchTokenMeta(SYSTEM_PROGRAM)).rejects.toMatchObject({+ code: 'mint_not_found',+ status: 404,+ });+ });++ it('rejects an address with no account at all', async () => {+ await expect(fetchTokenMeta(THREE_MINT)).rejects.toMatchObject({+ code: 'mint_not_found',+ status: 404,+ });+ });++ it('rejects a string that is not a base58 pubkey', async () => {+ await expect(fetchTokenMeta('not-a-mint')).rejects.toMatchObject({+ code: 'invalid_mint',+ status: 400,+ });+ });+});diff --git a/tests/x402-directory-registrar.test.js b/tests/x402-directory-registrar.test.jsindex 693b08fa4..9112d5e6e 100644--- a/tests/x402-directory-registrar.test.js+++ b/tests/x402-directory-registrar.test.js@@ -8,8 +8,8 @@// - the window never exceeds the 402index rate-limit size;// - an empty catalog stays total (no modulo-by-zero NaN).-import { describe, it, expect } from 'vitest';-import { registrarWindow } from '../api/cron/x402-directory-registrar.js';+import { describe, it, expect, afterEach, vi } from 'vitest';+import { registrarWindow, probeDeployed } from '../api/cron/x402-directory-registrar.js';const HOUR_MS = 3_600_000;@@ -78,3 +78,72 @@ describe('registrarWindow', () => {expect(w.batch.length).toBe(5);});});++// The probe decides whether an entry is worth one of 402index's 10+// registrations/hour. It used to demand a bare 402, which permanently and+// silently excluded every endpoint that paywalls behind a parameter: three.ws's+// /api/x402/vanity-premium answers 200 to a parameterless GET (the free+// inventory browse) and 402 only to ?address=<in-stock base58>. The registrar+// cannot synthesize a valid paid request for an arbitrary endpoint, so there was+// no tick on which such an entry could ever have been listed. These pin the+// corrected contract: only a 404, a 5xx, or an unreachable origin means "not+// deployed".+describe('probeDeployed', () => {+ const entry = { slug: 'demo', endpoint: 'https://three.ws/api/x402/demo', method: 'GET' };++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ function stubStatus(status) {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({ status })),+ );+ }++ it('accepts a bare 402 (single-mode paid endpoint)', async () => {+ stubStatus(402);+ expect(await probeDeployed(entry)).toEqual({ live: true, status: 402 });+ });++ it('accepts a 200 browse response (paywall behind a query parameter)', async () => {+ stubStatus(200);+ expect(await probeDeployed(entry)).toEqual({ live: true, status: 200 });+ });++ it.each([401, 403, 405, 429])('accepts %i as proof the route is deployed', async (status) => {+ stubStatus(status);+ expect(await probeDeployed(entry)).toEqual({ live: true, status });+ });++ it('rejects a 404 as not deployed', async () => {+ stubStatus(404);+ expect(await probeDeployed(entry)).toEqual({ live: false, status: 404, reason: 'origin_404' });+ });++ it.each([500, 502, 503])('rejects %i as not deployed', async (status) => {+ stubStatus(status);+ expect(await probeDeployed(entry)).toEqual({ live: false, status, reason: `origin_${status}` });+ });++ it('rejects an unreachable origin', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => {+ throw new Error('connect ECONNREFUSED');+ }),+ );+ expect(await probeDeployed(entry)).toEqual({ live: false, reason: 'origin_unreachable' });+ });++ it('sends a JSON body on a POST entry and none on a GET entry', async () => {+ const spy = vi.fn(async () => ({ status: 402 }));+ vi.stubGlobal('fetch', spy);+ await probeDeployed({ ...entry, method: 'POST' });+ expect(spy.mock.calls[0][1].body).toBe('{}');+ expect(spy.mock.calls[0][1].headers['content-type']).toBe('application/json');+ await probeDeployed(entry);+ expect(spy.mock.calls[1][1].body).toBeUndefined();+ });+});