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
feat: ERC-8004 on-chain anchor prompt in review form + changelog
nirholasc28d7b880c44
diff --git a/api/_lib/avatar-search-warm.js b/api/_lib/avatar-search-warm.jsnew file mode 100644index 000000000..cbc171d77--- /dev/null+++ b/api/_lib/avatar-search-warm.js@@ -0,0 +1,102 @@+// api/_lib/avatar-search-warm.js+//+// Warm-cache for the public avatar gallery search pipeline.+//+// Producer: the "Avatar Search Index Warmup" autonomous x402 loop entry+// (api/_lib/x402/autonomous-registry.js → avatar-search-warmup) pays per call to+// /api/mcp (search_public_avatars) for ~20 common queries, then upserts the+// ranked, thumbnail-resolved results here via upsertWarmedSearch().+//+// Consumer: GET /api/avatars/popular-searches reads getPopularSearches() to power+// "popular search" suggestion chips (with sample thumbnails) on the gallery.+//+// Table DDL lives in 20260629100000_avatar_search_warm_cache.sql; ensureSchema()+// creates it lazily so run() can be exercised before db:migrate has run.++import { sql } from './db.js';++let _ensured = false;++export async function ensureWarmCacheSchema() {+ if (_ensured) return;+ try {+ await sql`+ CREATE TABLE IF NOT EXISTS avatar_search_warm_cache (+ query text PRIMARY KEY,+ result_count integer NOT NULL DEFAULT 0,+ top_results jsonb NOT NULL DEFAULT '[]'::jsonb,+ thumbnails text[] NOT NULL DEFAULT '{}',+ has_thumbnails boolean NOT NULL DEFAULT false,+ warmed_at timestamptz NOT NULL DEFAULT now(),+ run_id uuid+ )+ `;+ await sql`+ CREATE INDEX IF NOT EXISTS avatar_search_warm_cache_rank+ ON avatar_search_warm_cache (result_count DESC, warmed_at DESC)+ `;+ _ensured = true;+ } catch { /* already exists or applied by the migration system */ }+}++/**+ * Upsert one warmed query's ranked results. `topResults` is the trimmed,+ * render-ready slice ([{ id, name, slug, thumbnail_url }]); `thumbnails` is the+ * non-null thumbnail URLs from that slice (used to validate the pipeline+ * resolved imagery and to paint suggestion chips).+ * @returns {Promise<boolean>} true on write+ */+export async function upsertWarmedSearch({ query, resultCount, topResults, thumbnails, runId }) {+ const q = String(query || '').trim();+ if (!q) return false;+ const results = Array.isArray(topResults) ? topResults : [];+ const thumbs = Array.isArray(thumbnails) ? thumbnails.filter(Boolean) : [];+ try {+ await sql`+ INSERT INTO avatar_search_warm_cache+ (query, result_count, top_results, thumbnails, has_thumbnails, warmed_at, run_id)+ VALUES+ (${q}, ${Number(resultCount) || 0}, ${JSON.stringify(results)}::jsonb,+ ${thumbs}, ${thumbs.length > 0}, now(), ${runId || null})+ ON CONFLICT (query) DO UPDATE SET+ result_count = EXCLUDED.result_count,+ top_results = EXCLUDED.top_results,+ thumbnails = EXCLUDED.thumbnails,+ has_thumbnails = EXCLUDED.has_thumbnails,+ warmed_at = now(),+ run_id = EXCLUDED.run_id+ `;+ return true;+ } catch {+ return false;+ }+}++/**+ * Popular warmed searches, ranked by how much public inventory each surfaces.+ * Returns [] when the table is empty or absent (cold start) so the consumer+ * endpoint degrades to a static fallback rather than erroring.+ * @param {{ limit?: number, withThumbnails?: boolean }} [opts]+ */+export async function getPopularSearches({ limit = 12, withThumbnails = false } = {}) {+ const lim = Math.min(Math.max(Number(limit) || 12, 1), 50);+ try {+ const rows = await sql`+ SELECT query, result_count, thumbnails, has_thumbnails, warmed_at, top_results+ FROM avatar_search_warm_cache+ WHERE result_count > 0+ ORDER BY result_count DESC, warmed_at DESC+ LIMIT ${lim}+ `;+ return rows.map((r) => ({+ query: r.query,+ result_count: Number(r.result_count) || 0,+ thumbnails: Array.isArray(r.thumbnails) ? r.thumbnails.slice(0, 4) : [],+ sample_thumbnail: Array.isArray(r.thumbnails) ? (r.thumbnails[0] || null) : null,+ top_results: withThumbnails ? (r.top_results || []) : [],+ warmed_at: r.warmed_at,+ }));+ } catch {+ return [];+ }+}diff --git a/api/_lib/migrations/20260627120000_three_market_signals.sql b/api/_lib/migrations/20260627120000_three_market_signals.sqlnew file mode 100644index 000000000..ae7e08010--- /dev/null+++ b/api/_lib/migrations/20260627120000_three_market_signals.sql@@ -0,0 +1,32 @@+-- Migration: $THREE Signal Feed time series.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260627120000_three_market_signals.sql+-- Idempotent.+--+-- Writers: api/cron/x402-autonomous-loop.js (registry entry `three-intel`, every+-- 15 min) via api/_lib/x402/three-signal-store.js insertThreeSignal().+-- Readers: api/three-signal.js (public $THREE price widget feed),+-- $THREE-denominated x402 pricing (usdToThreeTokens uses latest price).++begin;++create table if not exists three_market_signals (+ id bigserial primary key,+ ts timestamptz not null default now(),+ mint text,+ symbol text,+ price_usd double precision,+ change_24h double precision,+ market_cap_usd double precision,+ liquidity_usd double precision,+ volume_24h_usd double precision,+ signal text,+ headline text,+ confidence double precision,+ run_id uuid,+ source text not null default 'x402-autonomous'+);++create index if not exists three_market_signals_ts_desc+ on three_market_signals (ts desc);++commit;diff --git a/api/_lib/migrations/20260629100000_avatar_search_warm_cache.sql b/api/_lib/migrations/20260629100000_avatar_search_warm_cache.sqlnew file mode 100644index 000000000..81f3da793--- /dev/null+++ b/api/_lib/migrations/20260629100000_avatar_search_warm_cache.sql@@ -0,0 +1,29 @@+-- Warm-cache for the public avatar gallery search pipeline.+--+-- Populated by the "Avatar Search Index Warmup" autonomous x402 loop entry+-- (api/_lib/x402/autonomous-registry.js → avatar-search-warmup). On each run the+-- loop pays per call to /api/mcp (search_public_avatars) for ~20 common queries,+-- then upserts the ranked, thumbnail-resolved results here.+--+-- Downstream consumer: GET /api/avatars/popular-searches reads this table to+-- serve "popular search" suggestion chips (with sample thumbnails) on the public+-- gallery, and the cached payload lets the gallery paint instant results for a+-- common query before the live DB round-trip returns.+--+-- The warmup helper also creates this lazily (ensureWarmCacheSchema), so this+-- migration is belt-and-suspenders for environments that run db:migrate.++create table if not exists avatar_search_warm_cache (+ query text primary key,+ result_count integer not null default 0,+ top_results jsonb not null default '[]'::jsonb,+ thumbnails text[] not null default '{}',+ has_thumbnails boolean not null default false,+ warmed_at timestamptz not null default now(),+ run_id uuid+);++-- "Popular searches" ranks by how much public inventory a query surfaces, then+-- by recency of the warm pass.+create index if not exists avatar_search_warm_cache_rank+ on avatar_search_warm_cache (result_count desc, warmed_at desc);diff --git a/api/_lib/migrations/20260629100000_avatar_vrm_compat.sql b/api/_lib/migrations/20260629100000_avatar_vrm_compat.sqlnew file mode 100644index 000000000..4a3801a90--- /dev/null+++ b/api/_lib/migrations/20260629100000_avatar_vrm_compat.sql@@ -0,0 +1,30 @@+-- avatar_vrm_compat — VRM 1.0 migration reports per avatar.+--+-- Written by the "VRM 1.0 Compatibility Checker" autonomous x402 pipeline+-- (api/_lib/x402/autonomous-registry.js → entry id 'vrm-compat-checker').+-- Each row is the latest report for one avatar: whether it is a VRM, which+-- spec version, whether a VRM 0.x → 1.0 upgrade is possible, and the+-- migration checklist (spring-bone, expression, MToon, coordinate-flip items)+-- derived from a paid /api/mcp (inspect_model) call's structural report.+--+-- Downstream consumers:+-- • Avatar detail / marketplace gallery → "VRM 1.0 ready" badge + upgrade CTA.+-- • Avatar Pricing Engine pipeline (020) → spec compliance as a pricing input.+CREATE TABLE IF NOT EXISTS avatar_vrm_compat (+ avatar_id uuid PRIMARY KEY REFERENCES avatars(id) ON DELETE CASCADE,+ source_url text NOT NULL,+ is_vrm boolean NOT NULL DEFAULT false,+ vrm_version text NOT NULL DEFAULT 'none', -- 'none' | '0.x' | '1.0' | 'unknown'+ upgradeable boolean, -- VRM 0.x → 1.0 feasible; null when N/A+ blocker_count int NOT NULL DEFAULT 0, -- migration items needing manual review+ issues jsonb NOT NULL DEFAULT '[]'::jsonb, -- flagged incompatibilities+ report jsonb NOT NULL DEFAULT '{}'::jsonb, -- full migration report+ extensions text[] NOT NULL DEFAULT '{}', -- glTF extensionsUsed snapshot+ run_id uuid,+ tx_signature text,+ checked_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS avatar_vrm_compat_version_idx ON avatar_vrm_compat (vrm_version);+CREATE INDEX IF NOT EXISTS avatar_vrm_compat_upgradeable_idx ON avatar_vrm_compat (upgradeable) WHERE upgradeable IS TRUE;+CREATE INDEX IF NOT EXISTS avatar_vrm_compat_checked_idx ON avatar_vrm_compat (checked_at);diff --git a/api/_lib/x402/autonomous-pay.js b/api/_lib/x402/autonomous-pay.jsnew file mode 100644index 000000000..0fd7a64d0--- /dev/null+++ b/api/_lib/x402/autonomous-pay.js@@ -0,0 +1,292 @@+// api/_lib/x402/autonomous-pay.js+//+// Reusable Solana x402 payment primitive for the autonomous spend pipelines.+//+// The autonomous loop (api/cron/x402-autonomous-loop.js) inlines this same flow+// for its declarative registry entries. Batch pipelines that expose a custom+// run(ctx) — which make many paid calls per tick and write to their own tables —+// use this module so they don't duplicate the 100 lines of tx-building logic.+//+// Real on-chain payments only. Every call:+// 1. probes the resource for a 402 challenge (priced) or 200 (free),+// 2. selects the Solana accepts entry and validates asset + feePayer,+// 3. builds and signs a USDC TransferChecked against the seed keypair,+// 4. fires the request with the X-PAYMENT header,+// 5. parses the settlement signature from X-PAYMENT-RESPONSE.++import { readFileSync } from 'node:fs';+import bs58 from 'bs58';+import {+ PublicKey, Keypair, TransactionMessage, VersionedTransaction,+ ComputeBudgetProgram,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync, createTransferCheckedInstruction,+ createAssociatedTokenAccountIdempotentInstruction,+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, getMint,+} from '@solana/spl-token';++import { env } from '../env.js';+import { solanaConnection } from '../solana/connection.js';+import { sql } from '../db.js';++const FETCH_TIMEOUT_MS = 20_000;+const FALLBACK_USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++/**+ * Load the autonomous seed keypair. Prefers the seeder secret, falls back to the+ * agent secret, and (outside production only) a local test-wallet file. Throws+ * when none is configured so callers can record a graceful skip.+ * @returns {Keypair}+ */+export function loadSeedKeypair() {+ const b58 = process.env.X402_SEED_SOLANA_SECRET_BASE58+ || process.env.X402_AGENT_SOLANA_SECRET_BASE58;+ if (b58) {+ const raw = bs58.decode(b58);+ if (raw.length !== 64) throw new Error(`seed keypair: expected 64 bytes, got ${raw.length}`);+ return Keypair.fromSecretKey(raw);+ }+ if (process.env.NODE_ENV !== 'production') {+ try {+ const arr = JSON.parse(readFileSync('/home/codespace/.config/x402-test-wallets/solana.json', 'utf8'));+ return Keypair.fromSecretKey(Uint8Array.from(arr));+ } catch { /* fall through */ }+ }+ throw new Error('seed keypair not configured (set X402_SEED_SOLANA_SECRET_BASE58)');+}++/**+ * Build the shared per-tick Solana state a pipeline needs to pay: the signing+ * keypair, an RPC connection, a recent blockhash, and the USDC mint info. The+ * autonomous loop already builds these once per tick and passes them in; a+ * standalone caller (or a direct test) builds them here.+ * @param {{ usdcMint?: string, rpcUrl?: string }} [opts]+ */+export async function prepareSolanaContext({ usdcMint, rpcUrl } = {}) {+ const mint = usdcMint || env.X402_ASSET_MINT_SOLANA || FALLBACK_USDC_MINT;+ const buyer = loadSeedKeypair();+ const conn = solanaConnection({ url: rpcUrl || env.SOLANA_RPC_URL, commitment: 'confirmed' });+ const [{ blockhash }, mintInfo] = await Promise.all([+ conn.getLatestBlockhash('confirmed'),+ getMint(conn, new PublicKey(mint)),+ ]);+ return { buyer, conn, blockhash, mintInfo, usdcMint: mint };+}++async function fetchWithTimeout(url, opts = {}) {+ const ctrl = new AbortController();+ const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);+ try {+ const res = await fetch(url, { ...opts, signal: ctrl.signal, redirect: 'manual' });+ let body = null;+ try { body = await res.json(); } catch { try { body = await res.text(); } catch { body = null; } }+ return { ok: res.ok, status: res.status, headers: res.headers, body };+ } finally {+ clearTimeout(t);+ }+}++function parseSolanaAccept(challenge) {+ if (!challenge || !Array.isArray(challenge.accepts)) return null;+ return challenge.accepts.find(+ (a) => typeof a?.network === 'string' && a.network.startsWith('solana'),+ ) || null;+}++function buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists, nonce = 0 }) {+ const mint = new PublicKey(accept.asset);+ const payTo = new PublicKey(accept.payTo);+ const feePayer = new PublicKey(accept.extra.feePayer);+ const amount = BigInt(accept.amount);++ const senderAta = getAssociatedTokenAddressSync(+ mint, buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const receiverAta = getAssociatedTokenAddressSync(+ mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );++ // `nonce` perturbs the priority fee so a batch pipeline that fires many+ // identical-amount payments (same payer/payTo/mint) against one blockhash+ // produces a DISTINCT signature per call. Without it two equal transfers+ // compile to the same message → same signature → the second is rejected as+ // already-processed (and the platform's X-PAYMENT replay guard blocks it).+ // Single-call callers leave nonce at 0 and pay the baseline 5 µlamports.+ const ixs = [+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 + (Number(nonce) % 997) }),+ ];+ if (!receiverAtaExists) {+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(+ feePayer, receiverAta, payTo, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ ));+ }+ ixs.push(createTransferCheckedInstruction(+ senderAta, mint, receiverAta, buyer.publicKey,+ amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID,+ ));++ const msg = new TransactionMessage({+ payerKey: feePayer,+ recentBlockhash: blockhash,+ instructions: ixs,+ }).compileToV0Message();+ const vtx = new VersionedTransaction(msg);+ vtx.sign([buyer]);+ return Buffer.from(vtx.serialize()).toString('base64');+}++/**+ * Pay for and call an x402 resource. Returns a structured result whether the+ * resource was free (200 on probe), paid (402 → signed payment → 200), or+ * errored. Never throws on an HTTP/payment failure — callers inspect `.ok`.+ *+ * @param {object} args+ * @param {Keypair} args.buyer+ * @param {import('@solana/web3.js').Connection} args.conn+ * @param {string} args.blockhash+ * @param {object} args.mintInfo result of getMint() (for decimals)+ * @param {string} args.usdcMint expected accepts.asset+ * @param {string} args.url+ * @param {string} [args.method='POST']+ * @param {*} [args.body] JSON body (object) — stringified internally+ * @param {object} [args.headers] extra request headers+ * @returns {Promise<{ ok:boolean, status:number, body:*, amountAtomic:number, txSig:string|null, free:boolean, error:string|null }>}+ */+export async function payX402({ buyer, conn, blockhash, mintInfo, usdcMint, url, method = 'POST', body, headers = {}, nonce = 0 }) {+ const baseHeaders = {+ 'content-type': 'application/json',+ 'accept': 'application/json',+ 'user-agent': 'threews-x402-autonomous/1.0',+ ...headers,+ };+ const bodyInit = body != null ? { body: JSON.stringify(body) } : {};++ // Step 1 — probe for a 402 challenge.+ const probe = await fetchWithTimeout(url, { method, headers: baseHeaders, ...bodyInit });+ if (probe.status !== 402) {+ // Free resource (or a non-payment error surfaced verbatim to the caller).+ return { ok: probe.ok, status: probe.status, body: probe.body, amountAtomic: 0, txSig: null, free: true, error: probe.ok ? null : `http_${probe.status}` };+ }++ const accept = parseSolanaAccept(probe.body);+ if (!accept) return { ok: false, status: 402, body: probe.body, amountAtomic: 0, txSig: null, free: false, error: 'no_solana_accept' };+ if (!usdcMint || accept.asset !== usdcMint) return { ok: false, status: 402, body: probe.body, amountAtomic: 0, txSig: null, free: false, error: `unexpected_asset:${accept.asset}` };+ if (!accept.extra?.feePayer) return { ok: false, status: 402, body: probe.body, amountAtomic: 0, txSig: null, free: false, error: 'missing_fee_payer' };++ const amountAtomic = Number(accept.amount || 0);++ // Step 2 — does the receiver ATA already exist? (skip the idempotent create ix)+ const receiverAta = getAssociatedTokenAddressSync(+ new PublicKey(accept.asset), new PublicKey(accept.payTo),+ false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);++ // Step 3 — build + sign the payment tx.+ const txBase64 = buildPaymentTx({+ accept, buyer, blockhash, mintInfo, receiverAtaExists: receiverAtaInfo !== null, nonce,+ });++ const xPayment = Buffer.from(JSON.stringify({+ x402Version: 2,+ scheme: 'exact',+ network: accept.network,+ resource: { url, mimeType: 'application/json' },+ payload: { transaction: txBase64 },+ accepted: accept,+ })).toString('base64');++ // Step 4 — fire with payment.+ const paid = await fetchWithTimeout(url, {+ method,+ headers: { ...baseHeaders, 'x-payment': xPayment },+ ...bodyInit,+ });++ let txSig = null;+ if (paid.ok) {+ const responseHeader = paid.headers?.get?.('x-payment-response');+ if (responseHeader) {+ try {+ const settled = JSON.parse(Buffer.from(responseHeader, 'base64').toString('utf8'));+ txSig = settled?.transaction || null;+ } catch { /* non-fatal — payment succeeded, signature just not echoed */ }+ }+ }++ return {+ ok: paid.ok,+ status: paid.status,+ body: paid.body,+ amountAtomic,+ txSig,+ free: false,+ error: paid.ok ? null : `http_${paid.status}`,+ };+}++/**+ * Ensure the x402_autonomous_log table exists. The autonomous loop also creates+ * it; this lets a pipeline's run() be exercised directly (manual test) before+ * the loop has ever run. DDL is kept identical to the loop's definition.+ */+export async function ensureAutonomousLogTable() {+ try {+ await sql`+ CREATE TABLE IF NOT EXISTS x402_autonomous_log (+ id bigserial PRIMARY KEY,+ run_id uuid NOT NULL,+ ts timestamptz DEFAULT now(),+ endpoint_type text NOT NULL CHECK (endpoint_type IN ('self', 'external')),+ service_name text NOT NULL,+ endpoint_url text NOT NULL,+ network text NOT NULL DEFAULT 'solana:mainnet',+ amount_atomic bigint NOT NULL DEFAULT 0,+ asset text,+ tx_signature text,+ response_data jsonb,+ signal_data jsonb,+ duration_ms int,+ success boolean NOT NULL,+ error_msg text,+ pipeline text+ )+ `;+ } catch { /* already exists or handled by the migration system */ }+}++/**+ * Insert one row into x402_autonomous_log. Shared by every batch run() pipeline+ * so success AND failure are recorded identically to the cron loop's inline+ * path. Never throws — a logging failure must never crash the spend loop.+ *+ * The conceptual "value_extracted" payload is stored in the table's existing+ * `signal_data` jsonb column (the canonical extracted-value field across the+ * autonomous loop); pass it as `valueExtracted`.+ * @returns {Promise<void>}+ */+export async function recordAutonomousLog({+ runId, serviceName, endpointUrl, endpointType = 'self', pipeline = 'self',+ network = 'solana:mainnet', amountAtomic = 0, asset = null, txSig = null,+ responseData = null, durationMs = 0, success = false, errorMsg = null,+ valueExtracted = null,+}) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ response_data, signal_data, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${endpointType}, ${serviceName}, ${endpointUrl},+ ${network}, ${amountAtomic || 0},+ ${asset || env.X402_ASSET_MINT_SOLANA || FALLBACK_USDC_MINT},+ ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${pipeline})+ `;+ } catch { /* audit insert is best-effort — the loop must keep spending */ }+}diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex 831cc762d..5aa55aee0 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -13,7 +13,7 @@// body — request body (for POST), can be a function(ctx) => object// cooldown_s — minimum seconds between calls (enforced via Redis)// priority — 1-100; higher = more likely selected when multiple are ready-// pipeline — tag: 'oracle' | 'health' | 'volume' | 'sniper' | 'qa' | 'external'+// pipeline — tag: 'oracle' | 'health' | 'volume' | 'sniper' | 'qa' | 'forge' | 'discovery' | 'external'// enabled — boolean; set false to pause without removing// extractSignal — optional fn(responseBody) => object stored in x402_autonomous_log.signal_data// For oracle pipeline entries, return { mint?, signal, confidence, headline }@@ -22,8 +22,48 @@// For pipelines that rotate over a set of resources.// storeValue — optional async fn(ctx) that persists extracted value to a// dedicated table (ctx: { sql, redis, responseBody, signalData,-// runId, targetUrl, endpointUrl }). The loop wraps it in try/catch-// so a DB failure can never crash the tick.+// runId, targetUrl, endpointUrl, origin, durationMs, success }).+// The loop wraps it in try/catch so a DB failure can never+// crash the tick.+// run — optional async fn(ctx) that owns its full call sequence,+// payments (via the shared payX402 client), per-call recording+// and value extraction. The loop hands it { origin, buyer,+// conn, blockhash, mintInfo, redis, sql, log, runId,+// remainingCap } and records the returned aggregate as one+// summary row. Used for multi-call pipelines (e.g. the bazaar+// discovery warmup sweeping 15 categories per run).++import { run as bazaarDiscoveryWarmup } from './pipelines/bazaar-warmup.js';+import { run as volumeBootstrapLoop } from './pipelines/volume-bootstrap-loop.js';+import { run as cosmeticPricingAudit } from './pipelines/cosmetic-pricing-audit.js';+import { run as modelMetadataEnrichment } from './pipelines/model-metadata-enrichment.js';+import { run as forgeContentGeneration } from './pipelines/forge-content.js';+import { runCircuitBreaker } from './circuit-breaker.js';+import { mcpLatencySweep } from './mcp-latency-sweep.js';+import { runStreamingMcpHealth } from './pipelines/streaming-mcp-health.js';+import {+ runSceneCaptureProcessor,+ SCENE_CAPTURE_ENDPOINT,+ SCENE_CAPTURE_PRICE_ATOMIC,+} from './scene-capture-processor.js';+import {+ runThumbnailRegen,+ THUMBNAIL_REGEN_ENDPOINT,+ THUMBNAIL_REGEN_PRICE_ATOMIC,+ STALE_DAYS as THUMBNAIL_STALE_DAYS,+} from './thumbnail-regen.js';++// ── MCP Tool Latency Monitor (USE-006) ───────────────────────────────────────+// The canary the loop pays every 5 min to exercise the MCP paid path end-to-end+// (auth → price → pay → settle → dispatch). validate_model is the cheapest+// read-only priced MCP tool ($0.005); the Khronos Box.glb is a tiny, stable,+// public Khronos sample so the call is deterministic and always settles. The+// paid round-trip latency feeds x402_perf_log alongside the per-tool sweep that+// storeValue runs (see mcp-latency-sweep.js). Override the canary model via env+// without editing source.+const MCP_PERF_CANARY_MODEL =+ (process.env.X402_MCP_PERF_CANARY_MODEL || '').trim() ||+ 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/main/2.0/Box/glTF-Binary/Box.glb';// Canary clip the Animation Retargeting QA probe pays to download. Designate a// stable, paid, listed marketplace clip (an animation that exercises the@@ -143,6 +183,49 @@ async function nextCanonicalTarget(ctx) {}const SELF_ENDPOINTS = [+ // ── Circuit Breaker (cheapest end-to-end proof the payment stack is alive) ─+ {+ id: 'circuit-breaker-cross-network',+ name: 'Cross-Network Payment Circuit Breaker',+ // path is informational — runCircuitBreaker() probes + settles itself.+ // It pays the cheapest 402-gated endpoint ($0.001 dance-tip) on Solana and+ // route-verifies Base + BSC from the same live challenge.+ path: '/api/x402/dance-tip',+ method: 'POST',+ cooldown_s: 3600, // hourly — see agents/x402-buildout/self/009+ priority: 88,+ pipeline: 'circuit-breaker',+ enabled: true,+ run: runCircuitBreaker,+ extractSignal: null,+ },++ // ── 3D Pipeline: Avatar Thumbnail Regeneration (USE-015) ──────────────────+ // Pays asset-download for the stalest marketplace listing (thumbnail null /+ // older than STALE_DAYS / model bytes newer than last render), then queues a+ // re-render in avatar_thumbnail_regen_jobs. The drainer cron+ // (api/cron/avatar-thumbnail-render.js) renders the GLB to a fresh PNG and+ // writes it back onto paid_assets.thumbnail_r2_key + the linked avatars row so+ // listings always show current appearance. run() selects + pays + enqueues+ // and returns 'no_stale_assets' (skip, no spend) when nothing is overdue.+ {+ id: 'avatar-thumbnail-regen',+ name: `Avatar Thumbnail Regeneration (>${THUMBNAIL_STALE_DAYS}d stale)`,+ // path is informational — runThumbnailRegen() resolves the per-asset slug+ // and pays asset-download itself. price is per-listing; ref price below.+ path: THUMBNAIL_REGEN_ENDPOINT,+ method: 'GET',+ price_atomic: THUMBNAIL_REGEN_PRICE_ATOMIC,+ // 6h pacing: drains the stale backlog one listing per run (~4/day, well+ // under the daily cap) while the 30-day staleness gate decides actual work.+ cooldown_s: 21_600,+ priority: 38,+ pipeline: 'self',+ enabled: true,+ run: runThumbnailRegen,+ extractSignal: null,+ },+// ── Oracle / Intelligence (highest priority — feeds sniper decisions) ─────{id: 'crypto-intel-sol',@@ -413,6 +496,85 @@ const SELF_ENDPOINTS = [}),},+ // SSE Streaming MCP Health (USE-010): pays $0.01 USDC for a single priced+ // tools/call (validate_model on a tiny public canary GLB) against POST /api/mcp+ // in SSE mode (Accept: text/event-stream), then reads the paid response as a+ // STREAM to verify the streaming transport is intact before close — measuring+ // time-to-first-byte, inter-chunk gaps, chunk count and total bytes, and+ // flagging stalled streams, dropped connections, or broken chunked encoding.+ // run() owns the probe/pay/stream-read; the loop records one x402_autonomous_log+ // row (verdict in signal_data) and run() also persists the streaming-integrity+ // metrics to mcp_stream_health (the value sink the status surface + ops alerts+ // consume; complements the latency percentiles the MCP Latency Monitor writes+ // to x402_perf_log). Cooldown 300s → one paid probe every ~5 min ≈ $2.88/day at+ // $0.01, well under the loop's daily cap. The MCP server has no $0.001 tool, so+ // the minimum priced lightweight tool (validate_model, $0.01) governs the spend.+ {+ id: 'mcp-sse-stream-health',+ name: 'SSE Streaming MCP Health',+ // path is informational — runStreamingMcpHealth() probes + settles itself.+ path: '/api/mcp',+ method: 'POST',+ body: null,+ cooldown_s: 300,+ priority: 52,+ pipeline: 'health',+ enabled: true,+ run: runStreamingMcpHealth,+ },++ // ── MCP Observability: Tool Latency Monitor (USE-006) ─────────────────────+ // Every 5 min the loop makes ONE real x402 payment to /api/mcp — a+ // validate_model canary against a tiny, stable, public Khronos sample GLB.+ // That paid round-trip exercises the full paid MCP path (auth → price → pay →+ // settle → dispatch) and is recorded to x402_autonomous_log like every other+ // call. storeValue then runs the latency sweep (mcp-latency-sweep.js): it+ // lists every advertised tool and probes each with an unpaid, side-effect-free+ // tools/call, timing the caller-observed first response, then writes rolling+ // p50/p95/p99 per tool to x402_perf_log and alerts when any tool's p95 > 2s.+ // Downstream consumer: GET /api/x402/mcp-perf (the ops SLA dashboard) reads+ // x402_perf_log for live health + breach state.+ {+ id: 'mcp-latency-monitor',+ name: 'MCP Tool Latency Monitor',+ path: '/api/mcp',+ method: 'POST',+ body: {+ jsonrpc: '2.0',+ id: 'mcp-perf-canary',+ method: 'tools/call',+ params: {+ name: 'validate_model',+ arguments: { url: MCP_PERF_CANARY_MODEL, max_issues: 1 },+ },+ },+ cooldown_s: 300, // 5 min — matches the monitor's described schedule+ priority: 52,+ pipeline: 'observability',+ enabled: true,+ // Lift the canary's validation verdict into x402_autonomous_log.signal_data+ // so the autonomous log alone proves the paid MCP path returned real work.+ extractSignal: (r) => {+ const sc = r?.result?.structuredContent || null;+ return {+ canary_tool: 'validate_model',+ rpc_ok: !!(r?.result && !r?.error && !r?.result?.isError),+ file_size: sc?.fileSize ?? null,+ num_errors: sc?.numErrors ?? null,+ validator_version: sc?.validatorVersion ?? null,+ };+ },+ // Value extraction: full per-tool latency sweep → x402_perf_log.+ storeValue: ({ responseBody, runId, origin, durationMs, success }) =>+ mcpLatencySweep({+ responseBody,+ runId,+ origin,+ durationMs,+ success: success && !!(responseBody?.result && !responseBody?.error),+ }),+ },+// ── Sniper Pipeline Support ────────────────────────────────────────────────{id: 'sniper-pump-audit-latest',@@ -533,6 +695,98 @@ const SELF_ENDPOINTS = [},},+ // ── 3D Forge Content Generation (USE-014) ──────────────────────────────────+ // Pays the paid Forge ($0.05 draft) hourly to generate one procedural prop+ // (crate / barrel / furniture / terrain tile), rotating the category each hour+ // so the public asset library stays balanced. run() owns the pay→embed→persist+ // sequence: it inserts the prop into forge_autonomous_props (the asset-library ++ // diversity table the forge gallery/dashboard reads) and scores novelty + a+ // k-means cluster id over the recent catalog (the embedding-clustering diversity+ // measure). Cooldown 3600s → ≤24 props/day ≈ $1.20/day, well under the loop cap.+ {+ id: 'forge-content-gen',+ name: '3D Forge: procedural prop generation',+ path: '/api/x402/forge',+ method: 'POST',+ body: null,+ cooldown_s: 3600,+ priority: 55,+ pipeline: 'forge',+ enabled: true,+ run: (ctx) => forgeContentGeneration(ctx),+ },++ // ── Bazaar Discovery Warmup (USE-008) ──────────────────────────────────────+ // Sweeps 15 discovery categories through the x402 Bazaar MCP server+ // (/api/mcp-bazaar → search_services) at $0.001/call, validating that the+ // returned services are live + priced and snapshotting the catalog per+ // category into x402_bazaar_catalog for drift detection. run() owns the full+ // 15-call sequence and per-call recording; the loop records one summary row.+ // Cooldown 86400s (daily warmup) → 15 calls/day ≈ $0.015/day. The snapshots+ // are the source list for external x402 service onboarding (EXTERNAL_ENDPOINTS)+ // and the per-category drift flags feed the external pipeline.+ {+ id: 'bazaar-discovery-warmup',+ name: 'Bazaar Discovery Warmup',+ path: '/api/mcp-bazaar',+ method: 'POST',+ body: null,+ cooldown_s: 86400,+ priority: 35,+ pipeline: 'discovery',+ enabled: true,+ run: (ctx) => bazaarDiscoveryWarmup(ctx),+ },++ // ── Volume Bootstrap Loop (USE-026) ────────────────────────────────────────+ // The core growth/volume engine. Round-robins through the full catalog of+ // paid, cheap self x402 endpoints (VOLUME_ENDPOINTS in+ // pipelines/volume-bootstrap-loop.js), paying each a real on-chain USDC+ // payment so the platform accrues genuine agent-to-agent transaction volume —+ // the metric agentic.market ranks facilitators on — while continuously proving+ // every paid endpoint is live. run() owns the full sweep, per-call recording+ // and per-endpoint ledger upsert; the loop records one summary row. Budgeted+ // by both the loop's daily cap and a self-imposed per-run cap. Cooldown 300s →+ // a window every 5 min, full ~11-endpoint cycle ≈ 15 min. Value sink:+ // x402_volume_metrics (per-endpoint call/success/spend ledger) — read by the+ // growth + status surfaces for proof-of-volume and per-endpoint liveness.+ {+ id: 'volume-bootstrap-loop',+ name: 'Volume Bootstrap Loop',+ // path is informational — run() round-robins the VOLUME_ENDPOINTS catalog.+ path: '/api/x402/*',+ method: 'POST',+ body: null,+ cooldown_s: 300,+ priority: 25,+ pipeline: 'volume',+ enabled: true,+ run: (ctx) => volumeBootstrapLoop(ctx),+ },++ // ── Model Metadata Enrichment (USE-016) ────────────────────────────────────+ // Finds public avatars with no tags and pays inspect_model ($0.01/call via+ // /api/mcp) to parse each GLB, then derives searchable feature tags + a model+ // category from the structural report and writes them back to avatars.tags /+ // avatars.model_category. run() owns the per-avatar call sequence + recording+ // (value_extracted holds the derived tags); the loop records one summary row.+ // Cooldown 3600s (hourly) → up to 10 models/run ≈ $0.10/run, bounded again by+ // the loop's daily cap. Downstream consumer: listPublicAvatars({ tag, category })+ // search facets in api/_lib/avatars.js + the recommendation engine, both of+ // which read avatars.tags — an untagged avatar is invisible to them until enriched.+ {+ id: 'enrich-model-metadata',+ name: 'Model Metadata Enrichment',+ path: '/api/mcp',+ method: 'POST',+ body: null,+ cooldown_s: 3600,+ priority: 28,+ pipeline: '3d',+ enabled: true,+ run: (ctx) => modelMetadataEnrichment(ctx),+ },+// ── Club Cover Charge (social economy test) ────────────────────────────────{id: 'club-cover-health',@@ -569,6 +823,50 @@ const SELF_ENDPOINTS = [total_size_bytes: r?.total_size_bytes,}),},+ // ── Scene Capture Video Queue Processor (USE-013, 3D Pipeline) ────+ // Drains scene_capture_queue: pays $0.01 USDC for one processing credit, then+ // submits the queued user video to the LingBot-Map GPU worker; subsequent+ // ticks poll for completion (free) and store the finished .ply point-cloud URL+ // + telemetry back on the queue row. run()-style entry — owns the full+ // scan → pay → submit → poll → store sequence (scene-capture-processor.js).+ // Downstream consumer: src/scene-capture.js renders result_url as a THREE.Points+ // cloud on /capture. Cooldown 120 s so user uploads auto-process within minutes.+ {+ id: 'scene-capture-processor',+ name: 'Scene Capture Video Queue Processor',+ path: SCENE_CAPTURE_ENDPOINT,+ endpoint: SCENE_CAPTURE_ENDPOINT,+ method: 'GET',+ price_atomic: SCENE_CAPTURE_PRICE_ATOMIC,+ cooldown_s: 120,+ cooldown_seconds: 120,+ priority: 60,+ pipeline: 'self',+ enabled: true,+ run: (ctx) => runSceneCaptureProcessor(ctx),+ extractSignal: null,+ },+ // ── Avatar Marketplace Dynamic Pricing (USE-020) ──────────────────────────+ // Pricing-integrity probe across every premium cosmetic. run() sweeps each+ // item's live 402 quote (free), flags drift / underpricing vs the catalog's+ // server-owned price, and makes ONE real x402 purchase of the cheapest item to+ // validate quote → pay → settle end-to-end. Per-item findings land in+ // cosmetic_pricing_audit; a summary row (value_extracted = drift summary) goes+ // to x402_autonomous_log. Cooldown 86400 s (daily — cosmetic pricing is a+ // slow-changing config). Downstream consumer: ops gates avatar-shop releases on+ // the underpriced flag so a pricing bug never ships at a loss.+ {+ id: 'cosmetic-pricing-audit',+ name: 'Avatar Marketplace Dynamic Pricing',+ path: '/api/x402/cosmetic-purchase',+ method: 'GET',+ body: null,+ cooldown_s: 86400,+ priority: 32,+ pipeline: 'commerce',+ enabled: true,+ run: (ctx) => cosmeticPricingAudit(ctx),+ },];// ── External registry ─────────────────────────────────────────────────────────diff --git a/api/_lib/x402/circuit-breaker.js b/api/_lib/x402/circuit-breaker.jsindex 8de0f249a..fe9faabea 100644--- a/api/_lib/x402/circuit-breaker.js+++ b/api/_lib/x402/circuit-breaker.js@@ -3,8 +3,8 @@// Cross-Network Payment Circuit Breaker — the cheapest possible end-to-end// proof that the entire x402 payment stack is alive.//-// Once per hour the autonomous loop calls runCircuitBreaker() via the registry-// entry's run() hook. It:+// A run()-style registry entry (autonomous-registry.js → `circuit-breaker-cross-network`).+// Once per hour the autonomous loop calls runCircuitBreaker(ctx). It://// 1. Probes a real $0.001 402-gated three.ws endpoint (dance-tip) for a live// payment challenge.@@ -14,24 +14,29 @@// or malformed accept means a facilitator/config route has gone dark: the// breaker trips for that network.// 3. Settles a REAL $0.001 USDC payment on Solana — the only network with a-// configured autonomous outbound keypair (X402_AGENT_SOLANA_SECRET_BASE58)-// — to prove that build → verify → settle → receipt works end-to-end, not-// just that the route is advertised. Base/BSC outbound settlement is not-// attempted because no autonomous EVM signing wallet is provisioned; their-// route health is verified from the live challenge instead (real data, no-// mock). The moment an autonomous EVM payer is configured, settlement for-// those networks can be switched on here without touching the loop.+// configured autonomous outbound keypair (X402_SEED/AGENT_SOLANA_SECRET_BASE58)+// — via the shared payX402() client, proving build → verify → settle →+// receipt works end-to-end, not just that the route is advertised.+// Base/BSC outbound settlement is not attempted because no autonomous EVM+// signing wallet is provisioned; their route health is verified from the+// live challenge instead (real data, no mock). The day an autonomous EVM+// payer is configured, settlement for those networks switches on here+// without touching the loop.// 4. Upserts per-network status into `x402_circuit_breaker` (latest snapshot-// keyed by network) and returns a compact summary the loop records to-// `x402_autonomous_log`.+// keyed by network) and returns a compact outcome the loop records to+// `x402_autonomous_log` (response_data + signal_data).//// Downstream consumer: api/ops/health.js reads `x402_circuit_breaker` and-// surfaces the payment-stack liveness (per-network route + Solana settlement)-// in the internal health dashboard, and folds a tripped breaker into the-// overall `ok` verdict. The status page / on-call alerting consume that.+// surfaces payment-stack liveness (per-network route + Solana settlement) in the+// internal health dashboard, folding a tripped breaker into the overall `ok`+// verdict. On-call alerting / the status page consume that verdict.//// No mocks. Every check reads live challenge data or makes a real on-chain-// payment. If the Solana settlement fails the breaker is recorded as tripped.+// payment. The loop owns recording, cooldown, and daily-spend accounting; this+// module owns the probe, the cross-network verification, the payment, and the+// value extraction/storage.++import { fetchWithTimeout, parseSolanaAccept, payX402, USDC_MINT } from './pay.js';// Stable network identifiers — source of truth is api/_lib/x402-spec.js// (NETWORK_SOLANA_MAINNET / NETWORK_BASE_MAINNET / NETWORK_BSC_MAINNET). Matched@@ -41,11 +46,11 @@ const NET_BASE = 'eip155:8453';const NET_BSC = 'eip155:56';// The probe target: the cheapest real 402-gated endpoint on the platform-// ($0.001 USDC). A successful pay books one dance on the club stage — the same-// real side effect the volume entries already produce, so an hourly breaker tip-// is consistent with existing traffic.+// ($0.001 USDC). A settled pay books one dance on the club stage — the same real+// side effect the volume entries already produce, so an hourly breaker tip is+// consistent with existing traffic. A 402 challenge alone (the probe) books+// nothing; the ticket is created only after payment settles.const PROBE_PATH = '/api/x402/dance-tip';-const PROBE_METHOD = 'POST';const PROBE_BODY = { dancer: '4', dance: 'hiphop' };// Networks the breaker expects the platform to advertise. `settle` flags the one@@ -80,9 +85,7 @@ const TARGET_NETWORKS = [];function validateAccept(target, accept) {- if (!accept) {- return { advertised: false, route_ok: false, reason: 'route_not_advertised' };- }+ if (!accept) return { advertised: false, route_ok: false, reason: 'route_not_advertised', amount_atomic: null };const reasons = [];if (accept.scheme !== target.scheme) reasons.push(`scheme:${accept.scheme || 'none'}`);if (!accept.payTo) reasons.push('missing_payTo');@@ -93,18 +96,35 @@ function validateAccept(target, accept) {return {advertised: true,route_ok: reasons.length === 0,- network: accept.network,- scheme: accept.scheme,- asset: accept.asset,- pay_to: accept.payTo,amount_atomic: Number.isFinite(amount) ? amount : null,reason: reasons.length ? reasons.join(',') : null,};}-async function upsertStatus(ctx, runId, row) {- // Latest-status-per-network table consumed by api/ops/health.js.- await ctx.sql`+async function ensureTable(sql) {+ try {+ await sql`+ CREATE TABLE IF NOT EXISTS x402_circuit_breaker (+ network text PRIMARY KEY,+ label text NOT NULL,+ scheme text NOT NULL,+ advertised boolean NOT NULL DEFAULT false,+ route_ok boolean NOT NULL DEFAULT false,+ settled boolean NOT NULL DEFAULT false,+ receipt_valid boolean NOT NULL DEFAULT false,+ tx_signature text,+ amount_atomic bigint,+ error text,+ run_id uuid,+ checked_at timestamptz DEFAULT now()+ )+ `;+ } catch { /* already exists or migration system handles it */ }+}++async function upsertStatus(sql, runId, row) {+ // Latest-status-per-network snapshot consumed by api/ops/health.js.+ await sql`INSERT INTO x402_circuit_breaker(network, label, scheme, advertised, route_ok, settled,receipt_valid, tx_signature, amount_atomic, error, run_id, checked_at)@@ -128,31 +148,57 @@ async function upsertStatus(ctx, runId, row) {`;}+// Persist every per-network row, never crashing the loop on a DB fault.+async function persist(sql, log, runId, rows) {+ try {+ await ensureTable(sql);+ for (const row of rows) await upsertStatus(sql, runId, row);+ } catch (err) {+ log?.warn?.('circuit_breaker_persist_failed', { message: err?.message });+ }+}++function tripResult(errorMsg, stage) {+ return {+ success: false,+ amountAtomic: 0,+ txSig: null,+ network: 'multi',+ responseData: { stage },+ signalData: { tripped: true, reason: errorMsg },+ errorMsg,+ note: errorMsg,+ };+}+/*** Cross-network payment circuit breaker executor.*- * @param {object} ctx Capabilities injected by the autonomous loop:- * - runId string- * - origin string (e.g. 'https://three.ws')- * - sql db tagged-template- * - log logger- * - fetchWithTimeout (url, opts) => { ok, status, headers, body }- * - parseSolanaAccept(challenge) => accept | null- * - settleSolana(accept, endpointUrl, entry) =>- * { success, txSig, amountAtomic, responseBody, errorMsg, status }- * - remainingCap number (atomics still spendable under the daily cap)- * @returns result consumed by the loop for x402_autonomous_log:- * { success, amountAtomic, txSig, responseData, errorMsg, signalData, network, summary }+ * @param {object} ctx — supplied by the autonomous loop:+ * { origin, buyer, conn, blockhash, mintInfo, remainingCap, sql, log, runId }+ * @returns outcome recorded by the loop to x402_autonomous_log:+ * { success, amountAtomic, txSig, responseData, signalData, errorMsg, note }*/export async function runCircuitBreaker(ctx) {- const { runId, origin, fetchWithTimeout, parseSolanaAccept, settleSolana, log } = ctx;+ const { origin, buyer, conn, blockhash, mintInfo, remainingCap, sql, log, runId } = ctx;const endpointUrl = `${origin}${PROBE_PATH}`;+ // Wallet guard (defence in depth — the loop pre-flights the keypair).+ if (!buyer) {+ const rows = TARGET_NETWORKS.map((t) => ({+ network: t.label.toLowerCase(), label: t.label, scheme: t.scheme,+ advertised: false, route_ok: false, settled: false, receipt_valid: false,+ tx_signature: null, amount_atomic: null, error: 'wallet_unconfigured',+ }));+ await persist(sql, log, runId, rows);+ return { ...tripResult('wallet_unconfigured', 'preflight'), cooldown: false };+ }+// ── Step 1: probe for the live multi-network challenge ─────────────────────let challenge;try {const probe = await fetchWithTimeout(endpointUrl, {- method: PROBE_METHOD,+ method: 'POST',headers: {'content-type': 'application/json','user-agent': 'threews-x402-circuit-breaker/1.0',@@ -162,43 +208,34 @@ export async function runCircuitBreaker(ctx) {if (probe.status !== 402) {// A $0.001 paid endpoint that does NOT challenge is itself a stack fault.const errorMsg = `probe_not_402:http_${probe.status}`;- await safeUpsertTrip(ctx, runId, errorMsg);- return {- success: false,- amountAtomic: 0,- errorMsg,- network: 'multi',- responseData: { stage: 'probe', status: probe.status },- signalData: { tripped: true, reason: errorMsg },- summary: errorMsg,- };+ await persist(sql, log, runId, TARGET_NETWORKS.map((t) => ({+ network: t.label.toLowerCase(), label: t.label, scheme: t.scheme,+ advertised: false, route_ok: false, settled: false, receipt_valid: false,+ tx_signature: null, amount_atomic: null, error: errorMsg,+ })));+ return tripResult(errorMsg, 'probe');}challenge = probe.body;} catch (err) {- const errorMsg = `probe_failed:${err?.message || 'unknown'}`;- await safeUpsertTrip(ctx, runId, errorMsg);- return {- success: false,- amountAtomic: 0,- errorMsg,- network: 'multi',- responseData: { stage: 'probe' },- signalData: { tripped: true, reason: errorMsg },- summary: errorMsg,- };+ const errorMsg = `probe_failed:${err?.message || 'network'}`;+ await persist(sql, log, runId, TARGET_NETWORKS.map((t) => ({+ network: t.label.toLowerCase(), label: t.label, scheme: t.scheme,+ advertised: false, route_ok: false, settled: false, receipt_valid: false,+ tx_signature: null, amount_atomic: null, error: errorMsg,+ })));+ return tripResult(errorMsg, 'probe');}const accepts = Array.isArray(challenge?.accepts) ? challenge.accepts : [];// ── Step 2: verify each network route from the live challenge ──────────────- const networks = [];- let solanaTarget = null;+ const rows = [];+ let solanaRow = null;let solanaAccept = null;for (const target of TARGET_NETWORKS) {const accept = accepts.find((a) => target.match(a)) || null;const v = validateAccept(target, accept);const row = {- key: target.key,network: accept?.network || target.label.toLowerCase(),label: target.label,scheme: target.scheme,@@ -207,12 +244,12 @@ export async function runCircuitBreaker(ctx) {settled: false,receipt_valid: false,tx_signature: null,- amount_atomic: v.amount_atomic || null,+ amount_atomic: v.amount_atomic,error: v.reason,};- networks.push(row);+ rows.push(row);if (target.settle && accept && v.route_ok) {- solanaTarget = row;+ solanaRow = row;solanaAccept = accept;}}@@ -222,45 +259,38 @@ export async function runCircuitBreaker(ctx) {let txSig = null;let settleResp = null;if (solanaAccept) {- if (ctx.remainingCap != null && Number(solanaAccept.amount || 0) > ctx.remainingCap) {- solanaTarget.error = 'daily_cap_would_exceed';- } else {- try {- const r = await settleSolana(solanaAccept, endpointUrl, {- method: PROBE_METHOD,- body: PROBE_BODY,- });- amountAtomic = r.amountAtomic || 0;- txSig = r.txSig || null;- settleResp = r.responseBody || null;- solanaTarget.settled = !!r.success;- solanaTarget.receipt_valid = !!(r.success && r.txSig);- solanaTarget.tx_signature = txSig;- solanaTarget.amount_atomic = amountAtomic || solanaTarget.amount_atomic;- if (!r.success) solanaTarget.error = r.errorMsg || `settle_http_${r.status || '0'}`;- } catch (err) {- solanaTarget.error = `settle_threw:${err?.message || 'unknown'}`;- }- }- }-- // ── Step 4: persist per-network status (downstream: ops/health) ────────────- for (const row of networks) {try {- await upsertStatus(ctx, runId, row);+ const r = await payX402({+ url: endpointUrl,+ method: 'POST',+ body: PROBE_BODY,+ buyer, conn, blockhash, mintInfo,+ remainingCap: remainingCap ?? Infinity,+ userAgent: 'threews-x402-circuit-breaker/1.0',+ });+ amountAtomic = r.paid ? (r.amountAtomic || 0) : 0;+ txSig = r.txSig || null;+ settleResp = r.responseBody || null;+ solanaRow.settled = !!r.paid;+ solanaRow.receipt_valid = !!(r.paid && r.txSig);+ solanaRow.tx_signature = txSig;+ if (r.amountAtomic) solanaRow.amount_atomic = r.amountAtomic;+ if (!r.paid) solanaRow.error = r.errorMsg || `settle_status_${r.status || 0}`;} catch (err) {- // Table may not exist before its migration runs — the loop's ensureSchema- // creates it, so this is only a first-boot race. Never crash the loop.- if (!err?.message?.includes('does not exist')) {- log?.warn?.('circuit_breaker_upsert_failed', { network: row.network, message: err?.message });- }+ // Tx-build / RPC faults (malformed account, blockhash, RPC down) must not+ // crash the loop or skip the DB write — record the settlement as failed.+ solanaRow.error = `settle_threw:${err?.message || 'unknown'}`;}}- const routesOk = networks.filter((n) => n.route_ok).length;+ // ── Step 4: persist per-network status (downstream: ops/health) ────────────+ await persist(sql, log, runId, rows);++ const routesOk = rows.filter((n) => n.route_ok).length;const allRoutesOk = routesOk === TARGET_NETWORKS.length;- const solanaSettled = !!(solanaTarget && solanaTarget.settled);+ const solanaSettled = !!(solanaRow && solanaRow.settled);const tripped = !allRoutesOk || !solanaSettled;+ const summary = `routes ${routesOk}/${TARGET_NETWORKS.length} ok, solana ${solanaSettled ? 'settled' : 'FAILED'}`;const signalData = {tripped,@@ -269,47 +299,24 @@ export async function runCircuitBreaker(ctx) {routes_total: TARGET_NETWORKS.length,solana_settled: solanaSettled,solana_tx: txSig,- networks: networks.map((n) => ({ network: n.network, route_ok: n.route_ok, settled: n.settled, error: n.error })),+ networks: rows.map((n) => ({ network: n.network, route_ok: n.route_ok, settled: n.settled, error: n.error })),};- const summary = `routes ${routesOk}/${TARGET_NETWORKS.length} ok, solana ${solanaSettled ? 'settled' : 'FAILED'}`;log?.info?.('circuit_breaker_complete', { run_id: runId, ...signalData, tx: txSig });return {// success = the breaker's job (proving liveness) completed: all routes- // advertised + the real Solana settlement landed. A trip => success:false- // so the loop records it as a failure row and does not cool down — the- // breaker retries next tick instead of waiting the full hour.+ // advertised + the real Solana settlement landed. amountAtomic reflects+ // only what actually moved on-chain so the loop's spend accounting is exact.success: !tripped,amountAtomic,txSig,network: 'multi',- responseData: { challenge_resource: challenge?.resource || endpointUrl, networks, settle_response: settleResp },- errorMsg: tripped ? `breaker_tripped:${summary}` : null,+ responseData: { challenge_resource: challenge?.resource || endpointUrl, networks: rows, settle_response: settleResp },signalData,- summary,+ errorMsg: tripped ? `breaker_tripped:${summary}` : null,+ note: summary,};}-// Record a trip across all networks when we never reached the per-network stage-// (e.g. the probe itself failed) so ops/health still sees a fresh, failing row.-async function safeUpsertTrip(ctx, runId, error) {- for (const target of TARGET_NETWORKS) {- try {- await upsertStatus(ctx, runId, {- network: target.label.toLowerCase(),- label: target.label,- scheme: target.scheme,- advertised: false,- route_ok: false,- settled: false,- receipt_valid: false,- tx_signature: null,- amount_atomic: null,- error,- });- } catch { /* table may not exist yet — non-fatal */ }- }-}--export const CIRCUIT_BREAKER_PROBE = Object.freeze({ path: PROBE_PATH, method: PROBE_METHOD, body: PROBE_BODY });+export const CIRCUIT_BREAKER_PROBE = Object.freeze({ path: PROBE_PATH, body: PROBE_BODY });diff --git a/api/_lib/x402/enrich-model-metadata.js b/api/_lib/x402/enrich-model-metadata.jsnew file mode 100644index 000000000..3d991ae93--- /dev/null+++ b/api/_lib/x402/enrich-model-metadata.js@@ -0,0 +1,176 @@+// api/_lib/x402/enrich-model-metadata.js+//+// Model Metadata Enrichment — the work behind the `enrich-model-metadata`+// autonomous-registry entry (use case 016).+//+// The autonomous loop pays the x402 `inspect_model` MCP tool ($0.01 USDC/call)+// to parse a public avatar's GLB, then this module turns the structural report+// into searchable feature tags + a model category and writes them back to the+// `avatars` table.+//+// • selectUntaggedAvatar() — pick one public, tag-less avatar to enrich+// • inspectModelRpcBody() — build the JSON-RPC tools/call body for the loop+// • deriveModelMetadata() — pure: inspection report → { tags, model_category }+// • applyModelMetadata() — persist tags + category to avatars (untagged-only)+//+// Downstream consumers of the data written here:+// - Avatar search / marketplace filtering: `listPublicAvatars({ tag, category })`+// in api/_lib/avatars.js queries `any(tags)` and `model_category` — the only+// way these rows surface in tag/category facets is once they are enriched.+// - The recommendation engine reads the same `avatars.tags` array.++import { sql } from '../db.js';+import { publicUrl } from '../r2.js';++// Cap stored tags to the same ceiling the manual save path enforces (from-forge+// slices to 20) so an enriched avatar never has a larger tag set than a+// user-curated one.+const MAX_TAGS = 20;++// Select up to `limit` public avatars that have no tags yet and whose GLB is+// reachable at a public https URL (inspect_model fetches the URL server-side;+// private/local blobs can't be inspected). Highest-traffic avatars first so the+// most-seen models become searchable soonest. Returns [] when nothing is+// pending — the pipeline then skips without paying.+export async function selectUntaggedAvatars(limit = 10) {+ const want = Math.max(1, Math.min(50, Number(limit) || 10));+ let rows;+ try {+ rows = await sql`+ select id, slug, storage_key+ from avatars+ where deleted_at is null+ and visibility = 'public'+ and storage_key is not null+ and (tags is null or cardinality(tags) = 0)+ order by view_count desc nulls last, created_at desc+ limit ${want * 2}+ `;+ } catch {+ // Table/columns missing in a fresh env — nothing to enrich, not an error.+ return [];+ }++ const out = [];+ for (const row of rows) {+ if (out.length >= want) break;+ const url = publicUrl(row.storage_key);+ if (typeof url === 'string' && /^https:\/\//i.test(url)) {+ out.push({ id: row.id, slug: row.slug, glb_url: url });+ }+ }+ return out;+}++// JSON-RPC 2.0 envelope for a single `inspect_model` tool call against /api/mcp.+export function inspectModelRpcBody(glbUrl) {+ return {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'inspect_model', arguments: { url: glbUrl } },+ };+}++// Pull the inspection report out of the MCP tools/call response. Returns null on+// a JSON-RPC error, a tool-level error, or a malformed envelope.+export function parseInspectResult(responseBody) {+ const result = responseBody?.result;+ if (!result || result.isError) return null;+ const info = result.structuredContent;+ if (!info || typeof info !== 'object' || !info.counts) return null;+ return info;+}++// Pure: turn an inspect_model structural report into feature tags + a category.+// Every branch is grounded in a concrete geometry fact — no guessing.+export function deriveModelMetadata(info) {+ const c = info?.counts || {};+ const ext = Array.isArray(info?.extensionsUsed) ? info.extensionsUsed : [];+ const tags = new Set();++ // Container format.+ if (info?.container === 'glb' || info?.container === 'gltf') tags.add(info.container);++ // Rig + animation — the signals that decide whether a mesh can drive the+ // canonical clip library, so they double as the category heuristic below.+ const rigged = (c.skins || 0) > 0;+ const animated = (c.animations || 0) > 0;+ tags.add(rigged ? 'rigged' : 'static');+ if (animated) tags.add('animated');++ // Mesh composition.+ if ((c.meshes || 0) > 1) tags.add('multi-mesh');+ else if ((c.meshes || 0) === 1) tags.add('single-mesh');++ // Materials / textures.+ if ((c.textures || 0) > 0) tags.add('textured');+ else tags.add('untextured');+ if ((c.materials || 0) > 1) tags.add('multi-material');++ // Triangle budget — the practical web-delivery tier.+ const tris = c.totalTriangles || 0;+ if (tris > 0) {+ if (tris < 10_000) tags.add('low-poly');+ else if (tris < 100_000) tags.add('mid-poly');+ else tags.add('high-poly');+ }++ // Compression / advanced material extensions present in the asset.+ if (ext.includes('KHR_draco_mesh_compression')) tags.add('draco');+ if (ext.includes('EXT_meshopt_compression')) tags.add('meshopt');+ if (ext.includes('KHR_texture_basisu')) tags.add('ktx2');+ if (+ ext.includes('KHR_materials_pbrSpecularGlossiness') ||+ ext.includes('KHR_materials_emissive_strength') ||+ ext.includes('KHR_materials_clearcoat') ||+ ext.includes('KHR_materials_transmission')+ ) {+ tags.add('pbr');+ }++ // A skinned or animated mesh is treated as an avatar; an inert static mesh is+ // a prop. Mirrors how the rest of the platform splits humanoid avatars from+ // scene objects.+ const model_category = rigged || animated ? 'avatar' : 'prop';++ return { tags: [...tags].slice(0, MAX_TAGS), model_category };+}++// Persist derived tags + category, but only while the row is still untagged —+// never clobber tags a human or a concurrent process added between selection+// and write. Returns true when a row was updated.+export async function applyModelMetadata({ avatarId, tags, model_category }) {+ if (!avatarId || !Array.isArray(tags) || tags.length === 0) return false;+ const rows = await sql`+ update avatars+ set tags = ${tags}::text[],+ model_category = coalesce(${model_category ?? null}, model_category),+ updated_at = now()+ where id = ${avatarId}+ and deleted_at is null+ and (tags is null or cardinality(tags) = 0)+ returning id+ `;+ return rows.length > 0;+}++// End-to-end persistence used by the registry entry's `persist` hook: parse the+// MCP response, derive metadata, write it, and return a compact summary for the+// x402_autonomous_log.value_extracted column. Returns null when there is nothing+// useful to store (so the loop records the call without a value payload).+export async function enrichFromInspection({ responseBody, avatarId, slug }) {+ const info = parseInspectResult(responseBody);+ if (!info) return null;+ const { tags, model_category } = deriveModelMetadata(info);+ if (!tags.length) return null;+ const applied = await applyModelMetadata({ avatarId, tags, model_category });+ return {+ avatar_id: avatarId,+ slug: slug || null,+ applied,+ tags,+ model_category,+ triangles: info.counts?.totalTriangles ?? null,+ };+}diff --git a/api/_lib/x402/forge-prop-store.js b/api/_lib/x402/forge-prop-store.jsdeleted file mode 100644index 7b61408bc..000000000--- a/api/_lib/x402/forge-prop-store.js+++ /dev/null@@ -1,304 +0,0 @@-// api/_lib/x402/forge-prop-store.js-//-// Value-extraction + storage for the autonomous "3D Forge Content Generation"-// loop entry (autonomous-registry.js → id 'forge-content-gen'). The loop pays-// the paid /api/x402/forge endpoint $0.05/call to generate a procedural prop-// (crate, barrel, furniture, terrain tile); this module turns that response-// into a durable, queryable asset-library row and measures how diverse the-// generated catalog is via embedding clustering.-//-// What it does on every successful generation:-// 1. Picks the next prop prompt (rotating category, varied prompt) — exposed-// to the registry as nextForgeProp() so the request body is never static.-// 2. Embeds the prop prompt (free NIM / OpenAI when configured, deterministic-// feature-hash fallback otherwise — never blocks the loop).-// 3. Scores novelty = 1 − max cosine similarity to the recent catalog in the-// SAME vector space, and assigns a cluster id via k-means over that space.-// 4. Inserts a row into forge_autonomous_props (the public asset-library table-// for autonomously-forged props) carrying the public glb_url, the prompt,-// category, tier, embedding, novelty and cluster id.-//-// DOWNSTREAM CONSUMER: the forge gallery / diversity dashboard reads-// forge_autonomous_props — `glb_url` renders the prop, `novelty` + `cluster_id`-// drive the "how varied is the generated catalog" metric, `category` filters-// the feed. Inline-completed draft jobs carry a directly-renderable public R2-// `glb_url`; async jobs carry a `job_id` poll token (status stays 'queued'-// until the next observation), so the table is the single source of truth for-// what the autonomous forge has produced.-//-// All DB / embedding work is fail-soft: a hiccup here returns a summary the-// loop still logs, it never throws into the spend loop.--import { sql } from '../db.js';-import {- embeddingsConfigured,- defaultIngestEmbedderTag,- embedPassages,- cosine,-} from '../embeddings.js';-import { kmeans, suggestClusterCount, unit } from '../embedding-math.js';--// Vector space tag for the dependency-free fallback embedding. Tagged distinctly-// so it is NEVER compared against real NIM/OpenAI vectors — cosine only ever runs-// within a single embedder space (same rule embeddings.js enforces everywhere).-const LOCAL_EMBED_TAG = 'local/feature-hash@96';-const LOCAL_EMBED_DIM = 96;--// How many recent same-space rows to weigh novelty + clustering against. Bounded-// so the per-call k-means stays trivial inside the serverless window.-const DIVERSITY_WINDOW = 200;--// ── Procedural prop catalog ────────────────────────────────────────────────────-// Curated text→3D prompts grouped by the prop families named in the spec. Each-// call rotates the CATEGORY (so the catalog stays balanced across families) and-// varies the prompt within it (so successive same-category calls don't collide).-const PROP_CATALOG = Object.freeze({- crate: [- 'a weathered wooden shipping crate, iron banded corners, game-ready prop',- 'a stack of military supply crates, stenciled markings, matte finish',- 'a cracked sci-fi cargo container, glowing seams, low-poly',- 'an antique tea crate, rope handles, worn paint, stylized',- 'a reinforced steel ammo crate, latches and rivets, PBR textured',- ],- barrel: [- 'a rusted oil barrel, dented metal, peeling paint, game prop',- 'an oak wine barrel, iron hoops, cellar-aged wood grain',- 'a glowing toxic-waste barrel, hazard stripes, stylized',- 'a wooden gunpowder barrel, rope binding, weathered planks',- 'a sci-fi coolant drum, brushed aluminium, warning decals',- ],- furniture: [- 'a rustic wooden tavern stool, three legs, hand-carved, low-poly',- 'a medieval banquet table, heavy oak, worn surface, game-ready',- 'a worn leather armchair, brass studs, stylized PBR',- 'a sci-fi crew bunk, foldable metal frame, clean lowpoly',- 'an ornate Victorian writing desk, brass fittings, dark walnut',- ],- terrain: [- 'a modular rocky cliff terrain tile, mossy stone, seamless edges',- 'a desert dune terrain tile, rippled sand, sparse rocks, low-poly',- 'a snowy mountain terrain tile, jagged rock and ice, game-ready',- 'a lush grassland terrain tile, scattered boulders, stylized',- 'a volcanic terrain tile, cracked obsidian, glowing lava veins',- ],-});--const CATEGORIES = Object.freeze(Object.keys(PROP_CATALOG));--// Deterministic, non-random selector: rotate the category by UTC hour so the-// generated library cycles evenly across families, and step the prompt index by-// day so successive same-category hours don't repeat the same prompt. No-// Math.random — two ticks in the same hour pick the same prop, which the paid-// idempotency guard collapses rather than double-charging.-export function nextForgeProp(now = Date.now()) {- const hour = Math.floor(now / 3_600_000);- const day = Math.floor(now / 86_400_000);- const category = CATEGORIES[hour % CATEGORIES.length];- const prompts = PROP_CATALOG[category];- const prompt = prompts[(hour + day) % prompts.length];- return { category, prompt };-}--// Request body for the paid forge call. Draft tier ($0.05) — the price this loop-// is budgeted for; the 402 challenge quotes draft and the loop pays exactly that.-export function buildForgeRequestBody() {- const { category, prompt } = nextForgeProp();- return { prompt, tier: 'draft', aspect_ratio: '1:1', _prop_category: category };-}--// ── Embedding ──────────────────────────────────────────────────────────────────--// Signed feature hashing (FNV-1a → bucket, top bit → sign). A real, deterministic-// bag-of-words embedding used only when no embedding provider is configured, so-// the loop still produces a usable diversity signal with zero external calls.-function featureHashEmbed(text, dim = LOCAL_EMBED_DIM) {- const v = new Array(dim).fill(0);- const tokens = String(text).toLowerCase().match(/[a-z0-9]+/g) || [];- for (const tok of tokens) {- let h = 2166136261;- for (let i = 0; i < tok.length; i++) {- h ^= tok.charCodeAt(i);- h = Math.imul(h, 16777619);- }- const idx = (h >>> 0) % dim;- const sign = (h >>> 31) & 1 ? -1 : 1;- v[idx] += sign;- }- return v;-}--// Embed the prop prompt. Prefer the configured free-first provider; on any-// failure fall back to the local hash embedding so a provider outage degrades-// the diversity metric rather than failing the paid call's bookkeeping.-async function embedProp(prompt) {- if (embeddingsConfigured()) {- const tag = defaultIngestEmbedderTag();- if (tag) {- try {- const [vec] = await embedPassages(tag, [prompt]);- if (vec?.length) return { embedder: tag, vector: Array.from(vec) };- } catch {- /* provider hiccup — fall through to the deterministic local space */- }- }- }- return { embedder: LOCAL_EMBED_TAG, vector: featureHashEmbed(prompt) };-}--// ── Diversity (novelty + cluster) ──────────────────────────────────────────────--// novelty = 1 − max cosine similarity to the recent catalog in the SAME space,-// cluster_id = k-means assignment of the new prop within that space. First prop-// in a space is maximally novel (1) and forms cluster 0.-async function scoreDiversity(embedder, vector) {- let recent = [];- try {- recent = await sql`- select embedding from forge_autonomous_props- where embedder = ${embedder}- order by ts desc- limit ${DIVERSITY_WINDOW}- `;- } catch {- // Table may not exist on the very first run before ensureSchema commits, or- // the DB is briefly unavailable — treat as an empty catalog (max novelty).- return { novelty: 1, clusterId: 0, neighbors: 0 };- }-- const peers = recent- .map((r) => r.embedding)- .filter((a) => Array.isArray(a) && a.length === vector.length);-- if (peers.length === 0) return { novelty: 1, clusterId: 0, neighbors: 0 };-- let maxSim = 0;- for (const p of peers) {- const s = cosine(vector, p);- if (s > maxSim) maxSim = s;- }- const novelty = Math.max(0, Math.min(1, 1 - maxSim));-- // Cluster the new prop against the recent catalog. Unit-normalise so squared- // euclidean distance ranks the same as cosine (semantic clusters).- const all = [...peers, vector].map((v) => unit(v));- const k = suggestClusterCount(all.length);- const { assignments } = kmeans(all, k);- const clusterId = assignments[assignments.length - 1] ?? 0;-- return { novelty, clusterId, neighbors: peers.length };-}--// ── Schema (memoised, idempotent) ──────────────────────────────────────────────--let schemaReady = null;-function ensureSchema() {- if (schemaReady) return schemaReady;- schemaReady = (async () => {- await sql`- CREATE TABLE IF NOT EXISTS forge_autonomous_props (- id bigserial PRIMARY KEY,- run_id uuid,- ts timestamptz DEFAULT now(),- prompt text NOT NULL,- category text NOT NULL,- tier text,- mode text,- backend text,- job_id text,- glb_url text,- status text,- embedder text,- embedding jsonb,- novelty numeric(6,5),- cluster_id int- )- `;- await sql`- CREATE INDEX IF NOT EXISTS forge_autonomous_props_cat_ts_idx- ON forge_autonomous_props (category, ts DESC)- `;- })().catch((err) => {- // Reset so a transient failure retries next call rather than wedging.- schemaReady = null;- throw err;- });- return schemaReady;-}--// ── Public: persist one forge generation ───────────────────────────────────────--// Parse the paid /api/x402/forge response, embed + score the prop, and insert a-// row into forge_autonomous_props. Returns a compact summary the loop stores in-// x402_autonomous_log.value_extracted. Never throws — on DB/embedding failure it-// returns a summary carrying the error so the call is still recorded.-//-// `requestBody` is the body the loop sent (carries the rotated prompt + category-// via _prop_category); `responseBody` is the forge JSON response.-export async function persistForgeProp(responseBody, { runId, requestBody } = {}) {- const prompt =- (requestBody && typeof requestBody.prompt === 'string' && requestBody.prompt) || '';- const category =- (requestBody && requestBody._prop_category) || nextForgeProp().category;-- const r = responseBody && typeof responseBody === 'object' ? responseBody : {};- const tier = r.tier || (requestBody && requestBody.tier) || 'draft';- const mode = r.mode || 'text_to_3d';- const backend = r.backend || null;- const jobId = r.job_id || null;- const glbUrl = r.glb_url || null;- const status = r.status || (glbUrl ? 'done' : jobId ? 'queued' : 'unknown');-- // Without a prompt there is nothing to catalog — record a thin summary so the- // loop still logs the call, but skip the embed/insert.- if (!prompt) {- return { stored: false, reason: 'no_prompt', category, status, job_id: jobId, glb_url: glbUrl };- }-- let novelty = null;- let clusterId = null;- let embedder = null;- let neighbors = 0;- let stored = false;- let storeError = null;-- try {- await ensureSchema();- const embedded = await embedProp(prompt);- embedder = embedded.embedder;-- const diversity = await scoreDiversity(embedder, embedded.vector);- novelty = diversity.novelty;- clusterId = diversity.clusterId;- neighbors = diversity.neighbors;-- await sql`- INSERT INTO forge_autonomous_props- (run_id, prompt, category, tier, mode, backend,- job_id, glb_url, status, embedder, embedding, novelty, cluster_id)- VALUES- (${runId || null}, ${prompt}, ${category}, ${tier}, ${mode}, ${backend},- ${jobId}, ${glbUrl}, ${status}, ${embedder},- ${JSON.stringify(embedded.vector)}::jsonb,- ${novelty}, ${clusterId})- `;- stored = true;- } catch (err) {- storeError = err?.message || 'persist_failed';- }-- return {- stored,- category,- tier,- mode,- backend,- status,- job_id: jobId,- glb_url: glbUrl,- embedder,- novelty,- cluster_id: clusterId,- diversity_neighbors: neighbors,- ...(storeError ? { error: storeError } : {}),- };-}diff --git a/api/_lib/x402/pipelines/animation-retarget-qa.js b/api/_lib/x402/pipelines/animation-retarget-qa.jsnew file mode 100644index 000000000..53ddc5c47--- /dev/null+++ b/api/_lib/x402/pipelines/animation-retarget-qa.js@@ -0,0 +1,379 @@+// api/_lib/x402/pipelines/animation-retarget-qa.js+//+// Animation Retargeting QA — autonomous pipeline (self/012).+//+// On each run it pays to download a representative set of canary animation+// clips — one per rig convention (Mixamo, VRM, Avaturn, Daz, …) — through the+// real paid-delivery path (POST/GET /api/x402/animation-download → 402 paywall →+// R2 presign → animated GLB). Each call is a real on-chain USDC payment from the+// seed wallet at the clip's advertised price ($0.005/clip for the QA canaries).+// The pipeline:+//+// 1. Probes + pays each clip via the shared payX402 client (real x402, never+// mocked). A clip listed free returns 200 with no 402 and is graded too.+// 2. Fetches the returned short-lived presigned R2 URL and inspects the actual+// bytes with inspectGlb() — confirming a non-zero, valid binary glTF whose+// animation track survived. A baked clip that comes back empty, truncated,+// non-GLB, or with zero animation channels is exactly the regression a+// glb-canonicalize.js / animation-retarget.js break produces, so the verdict+// flips to passed:false here before a buyer ever hits it.+// 3. Records a row in x402_autonomous_log for every clip (success or failure),+// with the parsed QA verdict in value_extracted.+// 4. Upserts the per-clip verdict into animation_qa_results keyed by clip_id so+// the animation marketplace + ops alerting can read the latest QA state.+//+// Wiring: declared as a run()-style entry in autonomous-registry.js. The per-tick+// loop (api/cron/x402-autonomous-loop.js) hands run() a shared payment context+// (buyer, conn, blockhash, mintInfo, remainingCap); called standalone (manual+// test) it bootstraps its own context via bootstrapSolanaContext().+//+// Canary clips: designate them via env. Each is a stable, listed marketplace+// clip authored from a specific rig type so the sweep exercises every retarget+// path. Either form is accepted (comma-separated):+// X402_ANIMATION_QA_CLIP_IDS="mixamo=<uuid>,vrm=<uuid>,avaturn=<uuid>,daz=<uuid>"+// X402_ANIMATION_QA_CLIP_IDS="<uuid>,<uuid>" // unlabeled rigs+// X402_ANIMATION_QA_CLIP_ID="<uuid>" // single-clip fallback+// Unset → the pipeline is disabled in the registry and never pays.+//+// Downstream consumer: the verdicts in animation_qa_results are keyed by clip_id+// and read by (a) the animation marketplace health surface (world-health /+// uptime), and (b) retarget-regression alerting, which queries+// `... WHERE passed = false` to catch a delivery/retarget break the same day it+// lands — mirroring how glb_canonicalization_results gates the avatar pipeline.++import { randomUUID } from 'node:crypto';++import { sql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { inspectGlb } from '../../glb-inspect.js';+import {+ payX402, bootstrapSolanaContext, fetchWithTimeout, USDC_MINT, FETCH_TIMEOUT_MS,+} from '../pay.js';++const log = logger('x402-animation-qa');++const ROUTE = '/api/x402/animation-download';+const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++// Hard ceiling on the presigned GLB fetch — a single animation clip is tens to+// hundreds of KB; anything past this is treated as oversized rather than read+// into memory on a QA probe.+const MAX_GLB_BYTES = 96 * 1024 * 1024;++// Parse the canary clip set from env. Accepts "rig=uuid" pairs or bare uuids.+// Exported for the registry's enabled gate and for tests.+export function parseCanaryClips(+ raw = process.env.X402_ANIMATION_QA_CLIP_IDS || process.env.X402_ANIMATION_QA_CLIP_ID || '',+) {+ const seen = new Set();+ const out = [];+ for (const tok of String(raw).split(',')) {+ const t = tok.trim();+ if (!t) continue;+ const eq = t.indexOf('=');+ const rig = eq > 0 ? t.slice(0, eq).trim().toLowerCase() : null;+ const id = (eq > 0 ? t.slice(eq + 1) : t).trim();+ if (!UUID_RE.test(id) || seen.has(id)) continue;+ seen.add(id);+ out.push({ rig: rig || null, id });+ }+ return out;+}++export function hasCanaryClips() {+ return parseCanaryClips().length > 0;+}++let _schemaReady = false;+async function ensureSchema() {+ if (_schemaReady) return;+ // Per-clip QA verdict, latest state keyed by clip. History lives in+ // x402_autonomous_log; this table is the queryable current-state sink the+ // marketplace + alerting read.+ await sql`+ CREATE TABLE IF NOT EXISTS animation_qa_results (+ clip_id uuid PRIMARY KEY,+ rig_type text,+ clip_name text,+ slug text,+ declared_bytes bigint,+ fetched_bytes bigint,+ valid_glb boolean NOT NULL DEFAULT false,+ is_rigged boolean,+ animation_count int,+ passed boolean NOT NULL DEFAULT false,+ http_status int,+ amount_atomic bigint,+ tx_signature text,+ error_msg text,+ run_id uuid,+ checked_at timestamptz DEFAULT now()+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS animation_qa_results_passed_ts ON animation_qa_results (passed, checked_at DESC)`;+ // The autonomous log predates run()-style value extraction; add the column+ // the QA verdict is recorded into (idempotent — shared with other pipelines).+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+ _schemaReady = true;+}++// Per-call row into x402_autonomous_log (the loop records one aggregate summary+// row for the run() entry; these are the granular per-clip rows the QA owns).+async function recordCall(runId, { clip, endpointUrl, amountAtomic, txSig, durationMs, success, errorMsg, valueExtracted }) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${'self'},+ ${`Animation QA: ${clip.rig || 'clip'} ${clip.id.slice(0, 8)}`}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'qa'})+ `;+ } catch (err) {+ log.warn('animation_qa_log_insert_failed', { clip: clip.id, message: err?.message });+ }+}++async function upsertVerdict(runId, clip, v) {+ try {+ await sql`+ INSERT INTO animation_qa_results+ (clip_id, rig_type, clip_name, slug, declared_bytes, fetched_bytes,+ valid_glb, is_rigged, animation_count, passed, http_status,+ amount_atomic, tx_signature, error_msg, run_id, checked_at)+ VALUES+ (${clip.id}, ${clip.rig}, ${v.clip_name}, ${v.slug},+ ${v.declared_bytes}, ${v.fetched_bytes}, ${v.valid_glb},+ ${v.is_rigged}, ${v.animation_count}, ${v.passed}, ${v.http_status},+ ${v.amount_atomic}, ${v.tx_signature}, ${v.error_msg}, ${runId}, now())+ ON CONFLICT (clip_id) DO UPDATE SET+ rig_type = EXCLUDED.rig_type,+ clip_name = EXCLUDED.clip_name,+ slug = EXCLUDED.slug,+ declared_bytes = EXCLUDED.declared_bytes,+ fetched_bytes = EXCLUDED.fetched_bytes,+ valid_glb = EXCLUDED.valid_glb,+ is_rigged = EXCLUDED.is_rigged,+ animation_count = EXCLUDED.animation_count,+ passed = EXCLUDED.passed,+ http_status = EXCLUDED.http_status,+ amount_atomic = EXCLUDED.amount_atomic,+ tx_signature = EXCLUDED.tx_signature,+ error_msg = EXCLUDED.error_msg,+ run_id = EXCLUDED.run_id,+ checked_at = now()+ `;+ } catch (err) {+ log.warn('animation_qa_upsert_failed', { clip: clip.id, message: err?.message });+ }+}++// Fetch the presigned GLB bytes (real network). Returns a Buffer or throws.+async function fetchGlbBytes(url) {+ const ctrl = new AbortController();+ const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);+ try {+ const res = await fetch(url, { signal: ctrl.signal, redirect: 'follow' });+ if (!res.ok) throw new Error(`glb_fetch_http_${res.status}`);+ const len = Number(res.headers.get('content-length') || 0);+ if (len > MAX_GLB_BYTES) throw new Error(`glb_oversized:${len}`);+ const ab = await res.arrayBuffer();+ if (ab.byteLength > MAX_GLB_BYTES) throw new Error(`glb_oversized:${ab.byteLength}`);+ return Buffer.from(ab);+ } finally {+ clearTimeout(t);+ }+}++// Pay for + validate a single canary clip end-to-end. Never throws — every+// fault becomes a recorded verdict with passed:false.+async function gradeClip(runId, clip, ctx) {+ const { origin, buyer, conn, blockhash, mintInfo, remainingCap } = ctx;+ const endpointUrl = `${origin}${ROUTE}?id=${encodeURIComponent(clip.id)}`;+ const t0 = Date.now();++ const verdict = {+ clip_name: null, slug: null, declared_bytes: null, fetched_bytes: null,+ valid_glb: false, is_rigged: null, animation_count: null, passed: false,+ http_status: null, amount_atomic: 0, tx_signature: null, error_msg: null,+ };++ // Step 1 — probe + pay the paid-download endpoint.+ let pay;+ try {+ pay = await payX402({+ url: endpointUrl, method: 'GET',+ buyer, conn, blockhash, mintInfo, remainingCap,+ });+ } catch (err) {+ verdict.error_msg = err?.message || 'pay_failed';+ await finishClip(runId, clip, endpointUrl, verdict, t0, { paid: false, amountAtomic: 0 });+ return { verdict, amountAtomic: 0, paid: false, txSig: null, delivered: false };+ }++ verdict.http_status = pay.status ?? null;+ verdict.amount_atomic = pay.amountAtomic || 0;+ verdict.tx_signature = pay.txSig || null;++ const body = pay.responseBody;+ if (!pay.success || !body || typeof body !== 'object') {+ verdict.error_msg = pay.errorMsg || `delivery_failed_${pay.status || '0'}`;+ await finishClip(runId, clip, endpointUrl, verdict, t0, pay);+ return { verdict, amountAtomic: pay.amountAtomic || 0, paid: !!pay.paid, txSig: pay.txSig, delivered: false };+ }++ // Step 2 — the JSON unlock payload (id, name, sizeBytes, downloadUrl).+ verdict.clip_name = body.name || null;+ verdict.slug = body.slug || null;+ verdict.declared_bytes = body.sizeBytes != null ? Number(body.sizeBytes) : null;+ if (!body.downloadUrl) {+ verdict.error_msg = 'no_download_url';+ await finishClip(runId, clip, endpointUrl, verdict, t0, pay);+ return { verdict, amountAtomic: pay.amountAtomic || 0, paid: !!pay.paid, txSig: pay.txSig, delivered: false };+ }++ // Step 3 — fetch the actual GLB and inspect it. This is the regression guard:+ // the bytes must be a valid binary glTF whose animation track survived.+ let buf;+ try {+ buf = await fetchGlbBytes(body.downloadUrl);+ } catch (err) {+ verdict.error_msg = err?.message || 'glb_fetch_failed';+ await finishClip(runId, clip, endpointUrl, verdict, t0, pay);+ return { verdict, amountAtomic: pay.amountAtomic || 0, paid: !!pay.paid, txSig: pay.txSig, delivered: true };+ }++ verdict.fetched_bytes = buf.length;+ const glb = inspectGlb(buf);+ if (!glb || !glb.valid) {+ verdict.error_msg = 'invalid_glb';+ await finishClip(runId, clip, endpointUrl, verdict, t0, pay);+ return { verdict, amountAtomic: pay.amountAtomic || 0, paid: !!pay.paid, txSig: pay.txSig, delivered: true };+ }++ verdict.valid_glb = true;+ verdict.is_rigged = !!glb.isRigged;+ verdict.animation_count = Number(glb.animationCount || 0);+ // A delivered clip passes only when the bytes are a real, non-empty GLB that+ // still carries at least one animation channel — the retargeted/baked clip.+ verdict.passed = buf.length > 0 && verdict.animation_count >= 1;+ if (!verdict.passed) verdict.error_msg = 'no_animation_channels';++ await finishClip(runId, clip, endpointUrl, verdict, t0, pay);+ return { verdict, amountAtomic: pay.amountAtomic || 0, paid: !!pay.paid, txSig: pay.txSig, delivered: true };+}++// Persist a graded clip: the dedicated verdict row + the per-call log row.+async function finishClip(runId, clip, endpointUrl, verdict, t0, pay) {+ await upsertVerdict(runId, clip, verdict);+ await recordCall(runId, {+ clip,+ endpointUrl,+ amountAtomic: verdict.amount_atomic,+ txSig: verdict.tx_signature,+ durationMs: Date.now() - t0,+ success: !!(pay && pay.success) && verdict.passed,+ errorMsg: verdict.error_msg,+ valueExtracted: {+ rig: clip.rig, clip_id: clip.id, clip_name: verdict.clip_name,+ declared_bytes: verdict.declared_bytes, fetched_bytes: verdict.fetched_bytes,+ valid_glb: verdict.valid_glb, is_rigged: verdict.is_rigged,+ animation_count: verdict.animation_count, passed: verdict.passed,+ },+ });+}++/**+ * Run the Animation Retargeting QA sweep. Conforms to the run()-style registry+ * contract: the loop hands over { origin, buyer, conn, blockhash, mintInfo,+ * remainingCap, runId }; called standalone it bootstraps its own Solana context.+ *+ * Returns the aggregate outcome the loop records as one summary row:+ * { success, amountAtomic, txSig, errorMsg, responseData, signalData, skipped, note }+ */+export async function run(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ let remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;++ const clips = parseCanaryClips();+ if (clips.length === 0) {+ log.info('animation_qa_skipped', { reason: 'no_canary_clips' });+ return { success: false, skipped: true, amountAtomic: 0, note: 'no_canary_clips' };+ }++ // Schema first — without the sink there is no value to extract, so don't pay.+ try {+ await ensureSchema();+ } catch (err) {+ log.warn('animation_qa_schema_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };+ }++ // Solana payment context: reuse the loop's, else bootstrap (graceful on an+ // unconfigured wallet — bootstrap throws, we exit logged without paying).+ let { buyer, conn, blockhash, mintInfo } = ctx;+ if (!buyer || !conn || !blockhash || !mintInfo) {+ try {+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));+ } catch (err) {+ log.info('animation_qa_skipped', { reason: err.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: err.message, note: 'wallet_or_rpc_unconfigured' };+ }+ }++ let spentAtomic = 0;+ let paid = 0;+ let passed = 0;+ let lastTxSig = null;+ const verdicts = [];++ for (const clip of clips) {+ if (remainingCap <= 0) {+ log.info('animation_qa_cap_reached', { spent_atomic: spentAtomic });+ break;+ }+ const r = await gradeClip(runId, clip, { origin, buyer, conn, blockhash, mintInfo, remainingCap });+ verdicts.push({ rig: clip.rig, clip_id: clip.id, passed: r.verdict.passed, animations: r.verdict.animation_count, error: r.verdict.error_msg });+ if (r.paid) {+ spentAtomic += r.amountAtomic;+ remainingCap -= r.amountAtomic;+ paid += 1;+ if (r.txSig) lastTxSig = r.txSig;+ }+ if (r.verdict.passed) passed += 1;+ }++ const failed = verdicts.length - passed;+ log.info('animation_qa_complete', {+ run_id: runId,+ clips: clips.length,+ checked: verdicts.length,+ paid,+ passed,+ failed,+ spent_usdc: (spentAtomic / 1e6).toFixed(4),+ });++ const summary = { clips: clips.length, checked: verdicts.length, paid, passed, failed, verdicts };+ return {+ // success reflects that the probe ran and every checked clip passed QA; a+ // retarget regression (failed > 0) lands as success:false so the loop's+ // summary row flags it, with per-clip detail in animation_qa_results.+ success: verdicts.length > 0 && failed === 0,+ amountAtomic: spentAtomic,+ txSig: lastTxSig,+ errorMsg: failed > 0 ? `animation_qa_failed:${failed}/${verdicts.length}` : null,+ responseData: summary,+ signalData: summary,+ skipped: verdicts.length === 0,+ note: `animation_qa passed=${passed}/${verdicts.length} paid=${paid}`,+ };+}diff --git a/api/_lib/x402/pipelines/bazaar-warmup.js b/api/_lib/x402/pipelines/bazaar-warmup.jsindex 771cb7cdc..23d303ad7 100644--- a/api/_lib/x402/pipelines/bazaar-warmup.js+++ b/api/_lib/x402/pipelines/bazaar-warmup.js@@ -49,7 +49,7 @@ const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';// A bazaar listing is "live + priced" only when an agent could actually pay it:// it must carry a resource URL, a price (atomic units or label), and a network.-function isLivePricedService(s) {+export function isLivePricedService(s) {if (!s || typeof s.resource !== 'string' || !s.resource) return false;const hasPrice = s.price_atomic != null || (typeof s.price === 'string' && s.price.length > 0);const hasNetwork = Array.isArray(s.networks) && s.networks.length > 0;@@ -58,13 +58,13 @@ function isLivePricedService(s) {// Stable identifier for a service within a category — resource plus the MCP tool// name when present (one resource can expose many priced tools).-function serviceKey(s) {+export function serviceKey(s) {return s.tool_name ? `${s.resource}#${s.tool_name}` : s.resource;}// Deterministic hash of the live catalog for a category, used for drift// detection. Includes price so a reprice registers as drift, not just add/remove.-function catalogHash(services) {+export function catalogHash(services) {const lines = services.map((s) => `${serviceKey(s)}|${s.price_atomic ?? s.price ?? ''}`).sort();@@ -84,7 +84,7 @@ function jsonRpcSearch(category, id) {}// Pull the search_services structuredContent out of a JSON-RPC tools/call body.-function extractServices(responseBody) {+export function extractServices(responseBody) {const sc = responseBody?.result?.structuredContent;if (!sc || !Array.isArray(sc.services)) return { services: [], sources: null, errors: null, hasResult: !!responseBody?.result };return { services: sc.services, sources: sc.sources || null, errors: sc.errors || null, hasResult: true };diff --git a/api/_lib/x402/pipelines/cosmetic-pricing-audit.js b/api/_lib/x402/pipelines/cosmetic-pricing-audit.jsnew file mode 100644index 000000000..62c7dd657--- /dev/null+++ b/api/_lib/x402/pipelines/cosmetic-pricing-audit.js@@ -0,0 +1,378 @@+// api/_lib/x402/pipelines/cosmetic-pricing-audit.js+//+// Avatar Marketplace Dynamic Pricing — autonomous pipeline (self/020).+//+// A pricing-integrity probe across every premium avatar cosmetic. On each run it:+//+// 1. Enumerates the local catalog's premium items (api/_lib/cosmetics.js) and+// the USDC price each SHOULD settle at (priceUsdcAtomicsOf — server-owned,+// env-tunable). This is the "DB price" / source of truth.+// 2. Probes the live /api/x402/cosmetic-purchase endpoint for each item's 402+// challenge and reads the amount it QUOTES. Probing is free — no payment —+// so the full sweep costs nothing and runs even with no wallet configured.+// 3. Flags drift (quoted ≠ expected) and, critically, UNDERPRICING (quoted <+// expected) — the bug class that would silently ship revenue loss. The+// quoted price comes from the deployed endpoint's process/env, so this+// catches deploy skew and X402_PRICE_COSMETIC_* env misconfiguration that a+// same-process unit test never could.+// 4. Makes ONE real on-chain x402 purchase of the cheapest premium item to+// validate the whole quote → pay → settle path end-to-end (the settled+// amount must equal the quote). Real USDC from the seed wallet, never mocked.+// 5. Records a row per item in cosmetic_pricing_audit (the audit trail) and a+// summary row in x402_autonomous_log (value_extracted = drift summary).+//+// Tables:+// cosmetic_pricing_audit — per-item drift findings (one row per item per run).+// Columns receiving extracted value: expected_usdc_atomic,+// quoted_usdc_atomic, settled_usdc_atomic, drift,+// underpriced.+// x402_autonomous_log — one summary row per run; value_extracted (jsonb)+// carries { items, drift_count, underpriced_count,+// purchased_id, settled_atomic, quote_consistent }.+//+// Downstream consumer: cosmetic_pricing_audit is the pricing-integrity audit+// trail for the Avatar Shop (R21 catalog / R22 checkout). Ops reads it (alongside+// x402_autonomous_log) to gate releases — an `underpriced=true` row is the signal+// that a cosmetic pricing change would ship at a loss and must be held. The latest+// per-item drift state is the canonical "is the deployed shop charging what the+// catalog says" check.++import { randomUUID } from 'node:crypto';+import { PublicKey } from '@solana/web3.js';+import { getMint } from '@solana/spl-token';++import { sql } from '../../db.js';+import { env } from '../../env.js';+import { solanaConnection } from '../../solana/connection.js';+import { logger } from '../../usage.js';+import { buildCatalog, getCosmetic, priceUsdcAtomicsOf, priceOf } from '../../cosmetics.js';+import { normalizeAccountId } from '../../cosmetics-ownership.js';+import {+ loadSeedKeypair,+ payX402,+ fetchWithTimeout,+ parseSolanaAccept,+} from '../solana-payer.js';++const log = logger('x402-cosmetic-pricing-audit');++const ROUTE = '/api/x402/cosmetic-purchase';+const USDC_MINT = () => env.X402_ASSET_MINT_SOLANA || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+// Stable, synthetic account the audit grants the one real purchase to. Guest id+// form, never a real buyer — ownership here is an artifact of the probe, not a sale.+const AUDIT_ACCOUNT = normalizeAccountId('g_pricing_audit') || 'g_pricing_audit';++// Every premium catalog item plus the USDC atomics it should settle at locally.+// buildCatalog() is the same source the shop API serves, so `priceUsdcAtomics` is+// exactly the "DB price" the deployed endpoint is expected to quote back.+function premiumCatalog() {+ return buildCatalog()+ .filter((c) => c.premium)+ .map((c) => ({+ id: c.id,+ name: c.name,+ slot: c.slot,+ rarity: c.rarity,+ threePrice: c.price,+ expectedAtomic: Number(c.priceUsdcAtomics),+ }));+}++async function ensureSchema() {+ await sql`+ CREATE TABLE IF NOT EXISTS cosmetic_pricing_audit (+ id bigserial PRIMARY KEY,+ run_id uuid NOT NULL,+ ts timestamptz DEFAULT now(),+ cosmetic_id text NOT NULL,+ name text,+ slot text,+ rarity text,+ three_price numeric(20,4),+ expected_usdc_atomic bigint NOT NULL DEFAULT 0,+ quoted_usdc_atomic bigint,+ settled_usdc_atomic bigint,+ drift boolean NOT NULL DEFAULT false,+ underpriced boolean NOT NULL DEFAULT false,+ probe_status text,+ tx_signature text,+ error text+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS cosmetic_pricing_audit_id_ts ON cosmetic_pricing_audit (cosmetic_id, ts DESC)`;+ await sql`CREATE INDEX IF NOT EXISTS cosmetic_pricing_audit_underpriced ON cosmetic_pricing_audit (underpriced) WHERE underpriced`;+ // The autonomous log predates value_extracted; add it idempotently (mirrors+ // the bazaar-warmup pipeline so concurrent pipelines share one column).+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+}++async function recordAuditRow(runId, row) {+ try {+ await sql`+ INSERT INTO cosmetic_pricing_audit+ (run_id, cosmetic_id, name, slot, rarity, three_price,+ expected_usdc_atomic, quoted_usdc_atomic, settled_usdc_atomic,+ drift, underpriced, probe_status, tx_signature, error)+ VALUES+ (${runId}, ${row.cosmeticId}, ${row.name || null}, ${row.slot || null},+ ${row.rarity || null}, ${row.threePrice ?? null},+ ${row.expectedAtomic || 0}, ${row.quotedAtomic ?? null},+ ${row.settledAtomic ?? null}, ${!!row.drift}, ${!!row.underpriced},+ ${row.probeStatus || null}, ${row.txSig || null}, ${row.error || null})+ `;+ } catch (err) {+ log.warn('cosmetic_pricing_audit_insert_failed', { id: row.cosmeticId, message: err?.message });+ }+}++async function recordSummary(runId, { amountAtomic, txSig, responseData, durationMs, success, errorMsg, valueExtracted }) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${'self'}, ${'Avatar Marketplace Dynamic Pricing'}, ${ROUTE},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${USDC_MINT()}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'commerce'})+ `;+ } catch (err) {+ log.warn('cosmetic_pricing_audit_summary_failed', { run_id: runId, message: err?.message });+ }+}++// Probe one item's live 402 challenge and read the quoted USDC atomics. Free —+// no X-PAYMENT sent. Never throws: a network/abort fault returns an error shape.+async function probeQuote(origin, item) {+ const url = `${origin}${ROUTE}?id=${encodeURIComponent(item.id)}&account=${encodeURIComponent(AUDIT_ACCOUNT)}`;+ try {+ const res = await fetchWithTimeout(url, {+ method: 'GET',+ headers: { 'user-agent': 'threews-x402-autonomous/1.0' },+ });+ if (res.status !== 402) {+ // Premium items must always present a 402. A 200/4xx is itself an anomaly.+ return { quotedAtomic: null, probeStatus: `http_${res.status}`, error: res.status === 402 ? null : `unexpected_status_${res.status}` };+ }+ const accept = parseSolanaAccept(res.body);+ if (!accept) return { quotedAtomic: null, probeStatus: 'http_402', error: 'no_solana_accept' };+ const quoted = Number(accept.amount || 0);+ if (!Number.isFinite(quoted) || quoted <= 0) {+ return { quotedAtomic: null, probeStatus: 'http_402', error: `bad_quote:${accept.amount}` };+ }+ return { quotedAtomic: quoted, probeStatus: 'http_402', error: null };+ } catch (err) {+ return { quotedAtomic: null, probeStatus: 'fetch_error', error: err?.message || 'fetch_failed' };+ }+}++/**+ * Run the pricing audit. Self-contained: builds its own Solana payment context+ * when one isn't supplied, so it works both inside the per-tick autonomous loop+ * (handed shared blockhash + keypair) and as a direct manual test.+ *+ * @param {object} [ctx]+ * @param {string} [ctx.runId] correlation id (defaults to fresh uuid)+ * @param {string} [ctx.origin] base origin for the endpoint+ * @param {import('@solana/web3.js').Keypair} [ctx.buyer] seed keypair (loaded if absent)+ * @param {object} [ctx.conn] Solana connection (created if absent)+ * @param {string} [ctx.blockhash] recent blockhash (fetched if absent)+ * @param {object} [ctx.mintInfo] USDC mint info (fetched if absent)+ * @param {number} [ctx.remainingCapAtomic] spend ceiling for this run (atomics)+ * @returns {Promise<{ok:boolean, skipped?:boolean, reason?:string,+ * spentAtomic:number, items:number, driftCount:number, underpricedCount:number,+ * purchasedId:string|null, txSig:string|null}>}+ */+export async function run(ctx = {}) {+ const t0 = Date.now();+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ // The autonomous loop passes `remainingCap`; standalone callers may pass+ // `remainingCapAtomic`. Accept either, defaulting to unbounded.+ const remainingCap = ctx.remainingCap ?? ctx.remainingCapAtomic ?? Number.POSITIVE_INFINITY;++ const items = premiumCatalog();+ if (items.length === 0) {+ log.info('cosmetic_pricing_audit_no_premium');+ return { ok: true, skipped: true, reason: 'no_premium_items', spentAtomic: 0, items: 0, driftCount: 0, underpricedCount: 0, purchasedId: null, txSig: null };+ }++ // Schema is the only useful sink. If it can't be ensured, abort before any work.+ try {+ await ensureSchema();+ } catch (err) {+ log.warn('cosmetic_pricing_audit_schema_failed', { message: err?.message });+ return { ok: false, skipped: true, reason: `schema_failed: ${err?.message}`, spentAtomic: 0, items: items.length, driftCount: 0, underpricedCount: 0, purchasedId: null, txSig: null };+ }++ // ── 1) Free drift sweep across every premium item (no wallet needed) ──────+ const findings = [];+ for (const item of items) {+ const { quotedAtomic, probeStatus, error } = await probeQuote(origin, item);+ // Drift / underpricing only assessable when we actually got a quote.+ const drift = quotedAtomic != null && quotedAtomic !== item.expectedAtomic;+ const underpriced = quotedAtomic != null && quotedAtomic < item.expectedAtomic;+ findings.push({ ...item, quotedAtomic, probeStatus, error, drift, underpriced });+ }++ // ── 2) One real end-to-end purchase: cheapest premium item ────────────────+ // Validates quote → pay → settle consistency with a real on-chain payment.+ // Pick the cheapest by expected price to keep the audit's spend minimal.+ const target = [...items].sort((a, b) => a.expectedAtomic - b.expectedAtomic || a.id.localeCompare(b.id))[0];++ let buyer = ctx.buyer;+ let walletReason = null;+ if (!buyer) {+ try { buyer = loadSeedKeypair(); } catch (err) { walletReason = err.message; }+ }++ let spentAtomic = 0;+ let purchase = null; // payX402 result for the target item+ if (buyer && remainingCap >= target.expectedAtomic) {+ // Build / reuse the Solana payment context.+ let conn = ctx.conn;+ let blockhash = ctx.blockhash;+ let mintInfo = ctx.mintInfo;+ try {+ if (!conn || !blockhash || !mintInfo) {+ conn = conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });+ const [bh, mi] = await Promise.all([+ blockhash ? Promise.resolve({ blockhash }) : conn.getLatestBlockhash('confirmed'),+ mintInfo ? Promise.resolve(mintInfo) : getMint(conn, new PublicKey(USDC_MINT())),+ ]);+ blockhash = blockhash || bh.blockhash;+ mintInfo = mintInfo || mi;+ }+ const url = `${origin}${ROUTE}?id=${encodeURIComponent(target.id)}&account=${encodeURIComponent(AUDIT_ACCOUNT)}`;+ purchase = await payX402({+ endpointUrl: url,+ method: 'GET',+ conn, buyer, blockhash, mintInfo,+ usdcMint: USDC_MINT(),+ maxAmountAtomic: remainingCap,+ });+ if (purchase.status === 'paid') spentAtomic += purchase.amountAtomic;+ } catch (err) {+ // Infra fault (RPC/preflight). Record it against the target; keep the+ // sweep findings — they're already valuable.+ purchase = { status: 'error', success: false, amountAtomic: 0, txSig: null, responseBody: null, errorMsg: err?.message || 'purchase_failed' };+ }+ } else if (!buyer) {+ log.info('cosmetic_pricing_audit_no_wallet', { reason: walletReason });+ }++ // Fold the purchase outcome into the target's finding (settled amount + tx).+ if (purchase) {+ const f = findings.find((x) => x.id === target.id);+ if (f) {+ f.settledAtomic = purchase.status === 'paid' ? purchase.amountAtomic : null;+ f.txSig = purchase.txSig || null;+ if (purchase.errorMsg) f.error = f.error || purchase.errorMsg;+ // A settled amount that disagrees with the quote is itself drift.+ if (f.settledAtomic != null && f.quotedAtomic != null && f.settledAtomic !== f.quotedAtomic) {+ f.drift = true;+ }+ }+ }++ // ── 3) Persist per-item findings ──────────────────────────────────────────+ for (const f of findings) {+ await recordAuditRow(runId, {+ cosmeticId: f.id,+ name: f.name,+ slot: f.slot,+ rarity: f.rarity,+ threePrice: f.threePrice,+ expectedAtomic: f.expectedAtomic,+ quotedAtomic: f.quotedAtomic,+ settledAtomic: f.settledAtomic ?? null,+ drift: f.drift,+ underpriced: f.underpriced,+ probeStatus: f.probeStatus,+ txSig: f.txSig ?? null,+ error: f.error,+ });+ }++ const driftCount = findings.filter((f) => f.drift).length;+ const underpricedCount = findings.filter((f) => f.underpriced).length;+ const quoteConsistent = purchase?.status === 'paid'+ ? (findings.find((x) => x.id === target.id)?.settledAtomic === findings.find((x) => x.id === target.id)?.quotedAtomic)+ : null;++ // ── 4) Summary row in x402_autonomous_log (always, success or skip) ───────+ const valueExtracted = {+ items: findings.length,+ drift_count: driftCount,+ underpriced_count: underpricedCount,+ purchased_id: purchase?.status === 'paid' ? target.id : null,+ settled_atomic: purchase?.status === 'paid' ? purchase.amountAtomic : null,+ quote_consistent: quoteConsistent,+ // Surface the offending items so an alert has them without a re-query.+ underpriced_ids: findings.filter((f) => f.underpriced).map((f) => f.id),+ drift_ids: findings.filter((f) => f.drift).map((f) => f.id),+ };+ const summarySuccess = !walletReason && (purchase ? purchase.success : true);+ const summaryError = walletReason+ ? `wallet_unconfigured: ${walletReason}`+ : (purchase && !purchase.success ? purchase.errorMsg : null);++ // This is the authoritative value_extracted row. amount_atomic is recorded as 0+ // here on purpose: the autonomous loop writes its OWN summary row carrying the+ // billed amount (from the returned amountAtomic) and that row is what spend+ // analytics sum — duplicating the amount here would double-count it. The actual+ // settled amount + tx for the purchased item also live in cosmetic_pricing_audit.+ await recordSummary(runId, {+ amountAtomic: 0,+ txSig: purchase?.txSig || null,+ responseData: { target: target.id, purchase_status: purchase?.status || 'not_attempted', spent_atomic: spentAtomic },+ durationMs: Date.now() - t0,+ success: summarySuccess,+ errorMsg: summaryError,+ valueExtracted,+ });++ if (underpricedCount > 0) {+ log.warn('cosmetic_pricing_underpriced', {+ run_id: runId, count: underpricedCount,+ ids: valueExtracted.underpriced_ids,+ });+ }+ log.info('cosmetic_pricing_audit_complete', {+ run_id: runId,+ items: findings.length,+ drift: driftCount,+ underpriced: underpricedCount,+ purchased: valueExtracted.purchased_id,+ spent_usdc: (spentAtomic / 1e6).toFixed(4),+ });++ // Two shapes in one object:+ // • Loop-facing fields (success/amountAtomic/txSig/signalData/errorMsg/skipped/+ // note) — the autonomous loop reads these to account spend against the daily+ // cap, set the cooldown, and record its own summary row. amountAtomic mirrors+ // spentAtomic so the loop decrements the cap by what we actually paid.+ // • Caller-facing fields (ok/items/driftCount/…) — for the manual test and any+ // direct invocation that wants the audit outcome.+ return {+ // loop-facing+ success: summarySuccess,+ amountAtomic: spentAtomic,+ txSig: purchase?.txSig || null,+ signalData: valueExtracted,+ errorMsg: summaryError,+ note: `pricing-audit: ${findings.length} items, ${driftCount} drift, ${underpricedCount} underpriced`,+ ...(walletReason ? { skipped: true } : {}),+ // caller-facing+ ok: true,+ spentAtomic,+ items: findings.length,+ driftCount,+ underpricedCount,+ purchasedId: valueExtracted.purchased_id,+ reason: walletReason ? 'wallet_unconfigured' : undefined,+ };+}diff --git a/api/_lib/x402/pipelines/forge-content.js b/api/_lib/x402/pipelines/forge-content.jsnew file mode 100644index 000000000..bd0b19e3e--- /dev/null+++ b/api/_lib/x402/pipelines/forge-content.js@@ -0,0 +1,414 @@+// api/_lib/x402/pipelines/forge-content.js+//+// 3D Forge Content Generation — autonomous pipeline (self/014).+//+// On each run it pays the paid three.ws Forge ($0.05 draft) to generate one+// procedural prop (crate / barrel / furniture / terrain tile), rotating the+// category each hour so the public asset library stays balanced across families.+// Each call is a real on-chain USDC payment from the seed wallet via the shared+// payX402 client. The pipeline:+//+// 1. Picks the next prop prompt (deterministic category rotation, varied+// prompt) and pays /api/x402/forge for the generation (real x402, never+// mocked).+// 2. Embeds the prop prompt (free NIM / OpenAI when configured, deterministic+// feature-hash fallback otherwise) and scores its diversity against the+// recent catalog: novelty = 1 − max cosine similarity, plus a k-means+// cluster id — both within a single embedder vector space.+// 3. Inserts the generated prop into forge_autonomous_props (the asset-library+// + diversity table) carrying the public glb_url, prompt, category, tier,+// embedding, novelty and cluster id.+// 4. Records a row in x402_autonomous_log for the call (success or failure),+// with the extracted prop summary in value_extracted.+//+// Wiring: declared as a run()-style entry in autonomous-registry.js. The per-tick+// loop (api/cron/x402-autonomous-loop.js) hands run() a shared payment context+// (buyer, conn, blockhash, mintInfo, remainingCap); called standalone (manual+// test) it bootstraps its own via bootstrapSolanaContext().+//+// DOWNSTREAM CONSUMER: the forge gallery / diversity dashboard reads+// forge_autonomous_props — `glb_url` renders the prop, `category` filters the+// feed, and `novelty` + `cluster_id` drive the "how varied is the generated+// catalog" metric (the embedding-clustering diversity measure). Inline-completed+// draft jobs carry a directly-renderable public R2 `glb_url`; async jobs carry a+// `job_id` poll token with status 'queued', so the table is the single source of+// truth for everything the autonomous forge has produced.++import { randomUUID } from 'node:crypto';++import { sql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { payX402, bootstrapSolanaContext, USDC_MINT } from '../pay.js';+import {+ embeddingsConfigured,+ defaultIngestEmbedderTag,+ embedPassages,+ cosine,+} from '../../embeddings.js';+import { kmeans, suggestClusterCount, unit } from '../../embedding-math.js';++const log = logger('x402-forge-content');++const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// Vector space tag for the dependency-free fallback embedding. Tagged distinctly+// so it is NEVER compared against real NIM/OpenAI vectors — cosine only ever runs+// within a single embedder space (the rule embeddings.js enforces everywhere).+const LOCAL_EMBED_TAG = 'local/feature-hash@96';+const LOCAL_EMBED_DIM = 96;++// How many recent same-space rows to weigh novelty + clustering against. Bounded+// so the per-call k-means stays trivial inside the serverless window.+const DIVERSITY_WINDOW = 200;++// ── Procedural prop catalog ────────────────────────────────────────────────────+// Curated text→3D prompts grouped by the prop families named in the spec. Each+// run rotates the CATEGORY (so the catalog stays balanced) and varies the prompt+// within it (so successive same-category runs don't collide).+const PROP_CATALOG = Object.freeze({+ crate: [+ 'a weathered wooden shipping crate, iron banded corners, game-ready prop',+ 'a stack of military supply crates, stenciled markings, matte finish',+ 'a cracked sci-fi cargo container, glowing seams, low-poly',+ 'an antique tea crate, rope handles, worn paint, stylized',+ 'a reinforced steel ammo crate, latches and rivets, PBR textured',+ ],+ barrel: [+ 'a rusted oil barrel, dented metal, peeling paint, game prop',+ 'an oak wine barrel, iron hoops, cellar-aged wood grain',+ 'a glowing toxic-waste barrel, hazard stripes, stylized',+ 'a wooden gunpowder barrel, rope binding, weathered planks',+ 'a sci-fi coolant drum, brushed aluminium, warning decals',+ ],+ furniture: [+ 'a rustic wooden tavern stool, three legs, hand-carved, low-poly',+ 'a medieval banquet table, heavy oak, worn surface, game-ready',+ 'a worn leather armchair, brass studs, stylized PBR',+ 'a sci-fi crew bunk, foldable metal frame, clean lowpoly',+ 'an ornate Victorian writing desk, brass fittings, dark walnut',+ ],+ terrain: [+ 'a modular rocky cliff terrain tile, mossy stone, seamless edges',+ 'a desert dune terrain tile, rippled sand, sparse rocks, low-poly',+ 'a snowy mountain terrain tile, jagged rock and ice, game-ready',+ 'a lush grassland terrain tile, scattered boulders, stylized',+ 'a volcanic terrain tile, cracked obsidian, glowing lava veins',+ ],+});++const CATEGORIES = Object.freeze(Object.keys(PROP_CATALOG));++// Deterministic, non-random selector: rotate the category by UTC hour so the+// library cycles evenly across families, and step the prompt index by day so+// successive same-category hours don't repeat the same prompt. No Math.random —+// two runs in the same hour pick the same prop, which the paid endpoint's+// idempotency guard collapses rather than double-charging.+export function nextForgeProp(now = Date.now()) {+ const hour = Math.floor(now / 3_600_000);+ const day = Math.floor(now / 86_400_000);+ const category = CATEGORIES[hour % CATEGORIES.length];+ const prompts = PROP_CATALOG[category];+ const prompt = prompts[(hour + day) % prompts.length];+ return { category, prompt };+}++// ── Embedding ──────────────────────────────────────────────────────────────────++// Signed feature hashing (FNV-1a → bucket, top bit → sign). A real, deterministic+// bag-of-words embedding used only when no embedding provider is configured, so+// the diversity metric still works with zero external calls.+function featureHashEmbed(text, dim = LOCAL_EMBED_DIM) {+ const v = new Array(dim).fill(0);+ const tokens = String(text).toLowerCase().match(/[a-z0-9]+/g) || [];+ for (const tok of tokens) {+ let h = 2166136261;+ for (let i = 0; i < tok.length; i++) {+ h ^= tok.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ const idx = (h >>> 0) % dim;+ const sign = (h >>> 31) & 1 ? -1 : 1;+ v[idx] += sign;+ }+ return v;+}++// Embed the prop prompt. Prefer the configured free-first provider; on any+// failure fall back to the local hash embedding so a provider outage degrades+// the diversity metric rather than failing the call's bookkeeping.+async function embedProp(prompt) {+ if (embeddingsConfigured()) {+ const tag = defaultIngestEmbedderTag();+ if (tag) {+ try {+ const [vec] = await embedPassages(tag, [prompt]);+ if (vec?.length) return { embedder: tag, vector: Array.from(vec) };+ } catch {+ /* provider hiccup — fall through to the deterministic local space */+ }+ }+ }+ return { embedder: LOCAL_EMBED_TAG, vector: featureHashEmbed(prompt) };+}++// ── Diversity (novelty + cluster) ──────────────────────────────────────────────++// novelty = 1 − max cosine similarity to the recent catalog in the SAME space;+// cluster_id = k-means assignment of the new prop within that space. The first+// prop in a space is maximally novel (1) and forms cluster 0.+async function scoreDiversity(embedder, vector) {+ let recent = [];+ try {+ recent = await sql`+ SELECT embedding FROM forge_autonomous_props+ WHERE embedder = ${embedder}+ ORDER BY ts DESC+ LIMIT ${DIVERSITY_WINDOW}+ `;+ } catch {+ // Table briefly unavailable — treat as an empty catalog (max novelty).+ return { novelty: 1, clusterId: 0, neighbors: 0 };+ }++ const peers = recent+ .map((r) => r.embedding)+ .filter((a) => Array.isArray(a) && a.length === vector.length);++ if (peers.length === 0) return { novelty: 1, clusterId: 0, neighbors: 0 };++ let maxSim = 0;+ for (const p of peers) {+ const s = cosine(vector, p);+ if (s > maxSim) maxSim = s;+ }+ const novelty = Math.max(0, Math.min(1, 1 - maxSim));++ // Cluster the new prop against the recent catalog. Unit-normalise so squared+ // euclidean distance ranks the same as cosine (semantic clusters).+ const all = [...peers, vector].map((v) => unit(v));+ const k = suggestClusterCount(all.length);+ const { assignments } = kmeans(all, k);+ const clusterId = assignments[assignments.length - 1] ?? 0;++ return { novelty, clusterId, neighbors: peers.length };+}++// ── Schema ──────────────────────────────────────────────────────────────────────++async function ensureSchema() {+ // forge_autonomous_props: the public asset-library + diversity table for+ // autonomously-forged props. glb_url is the renderable asset; novelty ++ // cluster_id are the embedding-clustering diversity metric.+ await sql`+ CREATE TABLE IF NOT EXISTS forge_autonomous_props (+ id bigserial PRIMARY KEY,+ run_id uuid,+ ts timestamptz DEFAULT now(),+ prompt text NOT NULL,+ category text NOT NULL,+ tier text,+ mode text,+ backend text,+ job_id text,+ glb_url text,+ status text,+ embedder text,+ embedding jsonb,+ novelty numeric(6,5),+ cluster_id int+ )+ `;+ await sql`+ CREATE INDEX IF NOT EXISTS forge_autonomous_props_cat_ts_idx+ ON forge_autonomous_props (category, ts DESC)+ `;+ // The autonomous log predates the run()-style pipelines; add the+ // value_extracted column this pipeline records its prop summary into (idempotent).+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+}++// Per-call row into x402_autonomous_log including value_extracted. The loop also+// records one aggregate summary row for the run() entry; this is the granular+// row the pipeline owns (carrying the parsed prop value).+async function recordCall(runId, { endpointUrl, amountAtomic, txSig, responseData, durationMs, success, errorMsg, valueExtracted }) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${'self'}, ${'3D Forge: procedural prop generation'}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'forge'})+ `;+ } catch (err) {+ log.warn('forge_content_log_insert_failed', { message: err?.message });+ }+}++// Embed, score diversity, and insert the generated prop. Returns the compact+// summary used as value_extracted. Never throws — a DB/embedding hiccup returns a+// summary carrying the error so the call is still recorded.+async function persistProp({ runId, prompt, category, response }) {+ const r = response && typeof response === 'object' ? response : {};+ const tier = r.tier || 'draft';+ const mode = r.mode || 'text_to_3d';+ const backend = r.backend || null;+ const jobId = r.job_id || null;+ const glbUrl = r.glb_url || null;+ const status = r.status || (glbUrl ? 'done' : jobId ? 'queued' : 'unknown');++ let novelty = null;+ let clusterId = null;+ let embedder = null;+ let neighbors = 0;+ let stored = false;+ let storeError = null;++ try {+ const embedded = await embedProp(prompt);+ embedder = embedded.embedder;++ const diversity = await scoreDiversity(embedder, embedded.vector);+ novelty = diversity.novelty;+ clusterId = diversity.clusterId;+ neighbors = diversity.neighbors;++ await sql`+ INSERT INTO forge_autonomous_props+ (run_id, prompt, category, tier, mode, backend,+ job_id, glb_url, status, embedder, embedding, novelty, cluster_id)+ VALUES+ (${runId || null}, ${prompt}, ${category}, ${tier}, ${mode}, ${backend},+ ${jobId}, ${glbUrl}, ${status}, ${embedder},+ ${JSON.stringify(embedded.vector)}::jsonb, ${novelty}, ${clusterId})+ `;+ stored = true;+ } catch (err) {+ storeError = err?.message || 'persist_failed';+ log.warn('forge_content_persist_failed', { message: storeError });+ }++ return {+ stored,+ category,+ tier,+ mode,+ backend,+ status,+ job_id: jobId,+ glb_url: glbUrl,+ embedder,+ novelty,+ cluster_id: clusterId,+ diversity_neighbors: neighbors,+ ...(storeError ? { error: storeError } : {}),+ };+}++/**+ * Run the forge content generation. Conforms to the run()-style registry+ * contract: the loop hands over { origin, buyer, conn, blockhash, mintInfo,+ * remainingCap, runId }; standalone (manual test) it bootstraps its own Solana+ * context via bootstrapSolanaContext().+ *+ * Returns the aggregate outcome the loop records as one summary row:+ * { success, amountAtomic, txSig, errorMsg, responseData, signalData, skipped, note }+ */+export async function run(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const endpointUrl = `${origin}/api/x402/forge`;+ const remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;++ // Schema first: without the sink there is no value to extract, so don't pay.+ try {+ await ensureSchema();+ } catch (err) {+ log.warn('forge_content_schema_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };+ }++ // Solana payment context: reuse the loop's, else bootstrap. A bootstrap+ // failure means the wallet/RPC is unconfigured — exit gracefully, logged, no+ // payment attempted.+ let { buyer, conn, blockhash, mintInfo } = ctx;+ if (!buyer || !conn || !blockhash || !mintInfo) {+ try {+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));+ } catch (err) {+ log.info('forge_content_skipped', { reason: err.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: err.message, note: 'wallet_or_rpc_unconfigured' };+ }+ }++ const { category, prompt } = nextForgeProp();+ const body = { prompt, tier: 'draft', aspect_ratio: '1:1' };+ const t0 = Date.now();++ // Pay for the generation. payX402 never throws for protocol/network faults+ // (it returns a structured outcome) — but a hard fetch abort can still throw,+ // so guard it and record the failed call rather than crash the tick.+ let result;+ try {+ result = await payX402({ url: endpointUrl, method: 'POST', body, buyer, conn, blockhash, mintInfo, remainingCap });+ } catch (err) {+ const errorMsg = err?.message || 'forge_pay_error';+ await recordCall(runId, {+ endpointUrl, amountAtomic: 0, txSig: null, responseData: null,+ durationMs: Date.now() - t0, success: false, errorMsg, valueExtracted: null,+ });+ return { success: false, amountAtomic: 0, errorMsg, skipped: false, note: `forge ${category} fetch_failed` };+ }++ // Only extract + persist when the call actually produced a generation. A 402+ // rejection / cap-skip / HTTP error still gets a recorded log row below.+ let value = null;+ if (result.success) {+ value = await persistProp({ runId, prompt, category, response: result.responseBody });+ }++ await recordCall(runId, {+ endpointUrl,+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ // Keep the response lean — the prop row in forge_autonomous_props holds the+ // durable detail; log just the call status and key job pointers.+ responseData: result.responseBody+ ? { status: result.responseBody.status, job_id: result.responseBody.job_id || null, glb_url: result.responseBody.glb_url || null, backend: result.responseBody.backend || null }+ : { status: result.status },+ durationMs: Date.now() - t0,+ success: result.success,+ errorMsg: result.errorMsg,+ valueExtracted: value,+ });++ log.info('forge_content_complete', {+ run_id: runId,+ category,+ paid: result.paid,+ status: result.responseBody?.status || result.status,+ novelty: value?.novelty,+ cluster_id: value?.cluster_id,+ spent_usdc: (result.amountAtomic / 1e6).toFixed(4),+ });++ // Aggregate outcome for the loop's single summary row. signalData mirrors the+ // compact prop summary so the loop's row is useful on its own too.+ return {+ success: result.success,+ amountAtomic: result.paid ? result.amountAtomic : 0,+ txSig: result.txSig,+ errorMsg: result.errorMsg,+ skipped: result.skipped ?? false,+ responseData: { category, status: result.responseBody?.status || result.status, stored: value?.stored ?? false },+ signalData: value+ ? { category: value.category, status: value.status, novelty: value.novelty, cluster_id: value.cluster_id, glb_url: value.glb_url, job_id: value.job_id }+ : null,+ note: `forge ${category} ${value?.status || result.status}${value?.novelty != null ? ` novelty=${value.novelty}` : ''}`,+ };+}diff --git a/api/_lib/x402/pipelines/model-metadata-enrichment.js b/api/_lib/x402/pipelines/model-metadata-enrichment.jsnew file mode 100644index 000000000..f5bb0619a--- /dev/null+++ b/api/_lib/x402/pipelines/model-metadata-enrichment.js@@ -0,0 +1,212 @@+// api/_lib/x402/pipelines/model-metadata-enrichment.js+//+// Model Metadata Enrichment — autonomous pipeline (self/016).+//+// On each run it finds public avatars that have no tags yet and pays the x402+// `inspect_model` MCP tool ($0.01 USDC/call, advertised by /api/mcp) to parse+// each one's GLB. The structural report (mesh/skin/animation counts, triangle+// budget, compression extensions) is turned into searchable feature tags + a+// model category and written back to the avatars table — the input the search+// facets and the recommendation engine read from. The pipeline:+//+// 1. Selects a batch of untagged public avatars (selectUntaggedAvatars).+// 2. Pays inspect_model for each via the shared payX402 client (real on-chain+// USDC from the seed wallet — never mocked).+// 3. Derives { tags, model_category } from the inspection and writes them to+// avatars.tags / avatars.model_category (untagged-only, never clobbering).+// 4. Records a row in x402_autonomous_log for every call (success or failure),+// with the derived metadata in value_extracted.+//+// Wiring: declared as a run()-style entry in autonomous-registry.js. The per-tick+// loop (api/cron/x402-autonomous-loop.js) hands run() a shared payment context+// (buyer, conn, blockhash, mintInfo, remainingCap, runId, origin); called+// standalone (manual test) it bootstraps its own via bootstrapSolanaContext().+//+// Downstream consumer: api/_lib/avatars.js → listPublicAvatars({ tag, category })+// filters on `any(tags)` and `model_category`; until a row is enriched here it is+// invisible to those facets. The recommendation engine reads the same tags array.++import { randomUUID } from 'node:crypto';++import { sql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { payX402, bootstrapSolanaContext, USDC_MINT } from '../pay.js';+import {+ selectUntaggedAvatars,+ inspectModelRpcBody,+ enrichFromInspection,+} from '../enrich-model-metadata.js';++const log = logger('x402-model-enrich');++// Models inspected per run. Each is one $0.01 USDC payment, so a full batch is+// ≤ $0.10 — comfortably inside the loop's daily cap, and bounded again by the+// remainingCap the loop passes in.+const BATCH_SIZE = Number(process.env.X402_MODEL_ENRICH_BATCH || 10);++const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const ENDPOINT_PATH = '/api/mcp';++let _schemaReady = false;+async function ensureSchema() {+ if (_schemaReady) return;+ // The autonomous log predates the value_extracted column on some envs; add it+ // idempotently so this pipeline can record its derived metadata there.+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+ _schemaReady = true;+}++// One row per inspected avatar into x402_autonomous_log (the loop also records a+// single aggregate summary row for the run() entry; these are the granular ones).+async function recordCall(runId, { slug, endpointUrl, amountAtomic, txSig, responseData, durationMs, success, errorMsg, valueExtracted }) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${'self'}, ${`Model Enrichment: ${slug || 'unknown'}`}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'3d'})+ `;+ } catch (err) {+ log.warn('model_enrich_log_insert_failed', { slug, message: err?.message });+ }+}++/**+ * Run the enrichment sweep. Conforms to the run()-style registry contract: the+ * loop hands over { origin, buyer, conn, blockhash, mintInfo, remainingCap,+ * runId }; standalone (manual test) it bootstraps its own Solana context.+ *+ * Returns the aggregate outcome the loop records as one summary row:+ * { success, amountAtomic, txSig, errorMsg, responseData, skipped, note }+ */+export async function run(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const endpointUrl = `${origin}${ENDPOINT_PATH}`;+ let remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;++ // ── Schema first: without the value sink, don't pay.+ try {+ await ensureSchema();+ } catch (err) {+ log.warn('model_enrich_schema_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };+ }++ // ── Find work before touching the wallet — nothing untagged → no spend.+ const targets = await selectUntaggedAvatars(BATCH_SIZE);+ if (targets.length === 0) {+ return { success: true, skipped: true, amountAtomic: 0, note: 'no_untagged_avatars' };+ }++ // ── Solana payment context: reuse the loop's, else bootstrap (graceful on an+ // unconfigured wallet — bootstrap throws, we exit logged without paying).+ let { buyer, conn, blockhash, mintInfo } = ctx;+ if (!buyer || !conn || !blockhash || !mintInfo) {+ try {+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));+ } catch (err) {+ log.info('model_enrich_skipped', { reason: err.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: err.message, note: 'wallet_or_rpc_unconfigured' };+ }+ }++ let spentAtomic = 0;+ let paid = 0;+ let enriched = 0;+ let lastTxSig = null;+ let callErrors = 0;++ for (let i = 0; i < targets.length; i++) {+ const target = targets[i];+ if (remainingCap <= 0) {+ log.info('model_enrich_cap_reached', { spent_atomic: spentAtomic, remaining_targets: targets.length - i });+ break;+ }++ const t0 = Date.now();+ let result;+ try {+ result = await payX402({+ url: endpointUrl,+ method: 'POST',+ body: inspectModelRpcBody(target.glb_url),+ buyer, conn, blockhash, mintInfo,+ remainingCap,+ });+ } catch (err) {+ // Network failure / abort — log the call, never crash the sweep.+ callErrors += 1;+ await recordCall(runId, {+ slug: target.slug, endpointUrl, amountAtomic: 0, txSig: null, responseData: null,+ durationMs: Date.now() - t0, success: false, errorMsg: err?.message || 'fetch_failed', valueExtracted: null,+ });+ continue;+ }++ if (result.paid) {+ spentAtomic += result.amountAtomic;+ remainingCap -= result.amountAtomic;+ paid += 1;+ if (result.txSig) lastTxSig = result.txSig;+ }++ // Derive + persist the metadata only when the call delivered a result.+ let valueExtracted = null;+ if (result.success) {+ try {+ valueExtracted = await enrichFromInspection({+ responseBody: result.responseBody,+ avatarId: target.id,+ slug: target.slug,+ });+ if (valueExtracted?.applied) enriched += 1;+ } catch (err) {+ // DB write failed — the payment already settled, so record the call as+ // a success but surface the persistence error for observability.+ log.warn('model_enrich_persist_failed', { slug: target.slug, message: err?.message });+ }+ } else {+ callErrors += 1;+ }++ await recordCall(runId, {+ slug: target.slug,+ endpointUrl,+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ // Keep the row compact — the derived tags live in value_extracted; drop+ // the bulky inspection payload, retaining only call status + rpc error.+ responseData: { status: result.status, rpc_error: result.responseBody?.error || null },+ durationMs: Date.now() - t0,+ success: result.success,+ errorMsg: result.errorMsg,+ valueExtracted,+ });+ }++ log.info('model_enrich_complete', {+ run_id: runId,+ targets: targets.length,+ paid,+ enriched,+ spent_usdc: (spentAtomic / 1e6).toFixed(4),+ });++ return {+ success: paid > 0 || enriched > 0,+ amountAtomic: spentAtomic,+ txSig: lastTxSig,+ errorMsg: paid === 0 && callErrors > 0 ? `model_enrich_calls_failed:${callErrors}` : null,+ skipped: paid === 0 && enriched === 0,+ responseData: { targets: targets.length, paid, enriched },+ note: `model_enrich targets=${targets.length} paid=${paid} enriched=${enriched}`,+ };+}diff --git a/api/_lib/x402/pipelines/streaming-mcp-health.js b/api/_lib/x402/pipelines/streaming-mcp-health.jsnew file mode 100644index 000000000..91ae16ed6--- /dev/null+++ b/api/_lib/x402/pipelines/streaming-mcp-health.js@@ -0,0 +1,445 @@+// api/_lib/x402/pipelines/streaming-mcp-health.js+//+// SSE Streaming MCP Health — autonomous pipeline (self/010).+//+// A run()-style registry entry (autonomous-registry.js → `mcp-sse-stream-health`)+// that the per-tick spend loop invokes. Unlike the declarative health entries it+// can't be expressed as a buffered probe+pay: it has to read the paid HTTP+// response as a STREAM to judge transport integrity. On each run it:+//+// 1. Probes POST /api/mcp as a plain x402 agent to obtain the 402 challenge.+// 2. Builds a REAL Solana USDC payment for a single priced tools/call+// (validate_model on a tiny, public, self-hosted canary GLB) using the+// shared payment primitives in ../pay.js — never mocked.+// 3. Fires the paid request in *SSE mode* (Accept: text/event-stream) and reads+// the response as a stream, measuring time-to-first-byte, per-chunk gaps,+// chunk count and total bytes, and classifying the stream as clean /+// stalled / dropped. This is what verifies the response arrives intact+// before close and surfaces broken chunked encoding or a hung server.+// 4. Confirms settlement via the X-PAYMENT-RESPONSE header (the MCP server only+// broadcasts the payment after the tool produced a result) and extracts the+// on-chain tx signature.+// 5. Stores the streaming-integrity metrics to `mcp_stream_health` and fires an+// ops alert when a stream stalls or drops.+//+// Reality note: the /api/mcp POST handler returns a single JSON body (it does not+// yet emit token-by-token SSE frames), and GET /api/mcp answers 405 after auth —+// there is no long-lived server→client subscription to read. So this check+// honestly exercises the *paid streaming transport*: it advertises SSE support,+// streams the chunked response, and validates TTFB / inter-chunk liveness /+// complete delivery / chunked-encoding integrity. It does not fabricate token+// frames the server never sends. If the POST handler is upgraded to emit real SSE+// frames, parseStreamPayload() already handles the `data:`-framed shape.+//+// Recording: the loop records one x402_autonomous_log row per run (the returned+// signalData lands in signal_data). The dedicated value sink — the parsed+// streaming-integrity metrics — is the `mcp_stream_health` table written here.+//+// Downstream consumer: operators and the platform health/status surface query+// mcp_stream_health (latest healthy + ttfb/stall/drop history) to know the paid+// MCP streaming transport is live; it complements the per-tool latency+// percentiles the MCP Latency Monitor (self/006) writes to x402_perf_log. A+// stall or drop also raises an ops alert via sendOpsAlert.++import { randomUUID } from 'node:crypto';+import { PublicKey } from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync,+ getMint,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';++import { sql as defaultSql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { sendOpsAlert } from '../../alerts.js';+import { solanaConnection } from '../../solana/connection.js';+import {+ loadSeedKeypair,+ parseSolanaAccept,+ buildPaymentTx,+ fetchWithTimeout,+ USDC_MINT,+ SOLANA_RPC,+} from '../pay.js';++const log = logger('x402-streaming-mcp-health');++// Tiny, public, self-hosted Khronos sample (~160 KB) — always available at the+// canonical origin, validates cleanly, and keeps fetch+validate time low so the+// canary measures transport latency rather than model size. Pinned to the+// canonical public origin (not the loop's runtime origin) so validate_model's+// SSRF guard — which only fetches public https URLs — always has a real public+// asset to pull, regardless of where the loop runs.+const CANARY_TOOL = 'validate_model';+const CANARY_GLB = 'https://three.ws/avatars/fox.glb';++// Overall wall-clock budget for the paid streaming call (fits inside the loop's+// per-tick budget). STALL_MS is the quieter failure: no bytes for this long while+// the socket is still open counts as a stalled stream.+const STREAM_TIMEOUT_MS = 18_000;+const STALL_MS = 8_000;++const usdcMint = () => USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++function buildToolCallBody() {+ return {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: CANARY_TOOL, arguments: { url: CANARY_GLB, max_issues: 5 } },+ };+}++// Parse whatever the streaming read accumulated. The server returns a JSON body+// today; a future SSE upgrade would frame it as `data: {...}` lines — handle both+// so the canary keeps working across that change.+function parseStreamPayload(raw) {+ if (!raw || typeof raw !== 'string') return null;+ const trimmed = raw.trim();+ if (!trimmed) return null;+ try { return JSON.parse(trimmed); } catch { /* maybe SSE-framed */ }+ const dataLines = trimmed+ .split('\n')+ .filter((l) => l.startsWith('data:'))+ .map((l) => l.slice(5).trim())+ .filter(Boolean);+ for (let i = dataLines.length - 1; i >= 0; i--) {+ try { return JSON.parse(dataLines[i]); } catch { /* try the next-newest frame */ }+ }+ return null;+}++// Read an HTTP response body as a stream, recording streaming-integrity metrics.+// Resolves with metrics even on stall/drop — the caller decides health from them.+async function readStream(res, { stallMs, startedAt }) {+ const metrics = {+ status: res.status, ttfbMs: null, totalMs: 0, chunkCount: 0,+ totalBytes: 0, maxGapMs: 0, stalled: false, dropped: false, raw: '',+ };++ if (!res.body || typeof res.body.getReader !== 'function') {+ // No readable stream (e.g. an error envelope) — buffered fallback.+ try { metrics.raw = await res.text(); } catch { metrics.dropped = true; }+ metrics.totalBytes = Buffer.byteLength(metrics.raw || '');+ metrics.chunkCount = metrics.raw ? 1 : 0;+ metrics.ttfbMs = Date.now() - startedAt;+ metrics.totalMs = Date.now() - startedAt;+ return metrics;+ }++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let lastChunkAt = startedAt;++ try {+ for (;;) {+ let stallTimer = null;+ const stall = new Promise((_, reject) => {+ stallTimer = setTimeout(() => reject(new Error('stall_timeout')), stallMs);+ });+ let chunk;+ try {+ chunk = await Promise.race([reader.read(), stall]);+ } finally {+ if (stallTimer) clearTimeout(stallTimer);+ }++ if (chunk.done) break;+ const now = Date.now();+ if (metrics.ttfbMs === null) {+ metrics.ttfbMs = now - startedAt;+ } else {+ const gap = now - lastChunkAt;+ if (gap > metrics.maxGapMs) metrics.maxGapMs = gap;+ }+ lastChunkAt = now;+ metrics.chunkCount++;+ metrics.totalBytes += chunk.value?.byteLength || 0;+ metrics.raw += decoder.decode(chunk.value, { stream: true });+ }+ metrics.raw += decoder.decode();+ } catch (err) {+ if (err?.message === 'stall_timeout') metrics.stalled = true;+ else metrics.dropped = true; // abort / connection reset / overall timeout+ try { await reader.cancel(); } catch { /* already torn down */ }+ }++ if (metrics.ttfbMs === null) metrics.ttfbMs = Date.now() - startedAt;+ metrics.totalMs = Date.now() - startedAt;+ return metrics;+}++let _schemaReady = false;+async function ensureSchema(sql) {+ if (_schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS mcp_stream_health (+ id bigserial PRIMARY KEY,+ ts timestamptz DEFAULT now(),+ run_id uuid,+ endpoint text NOT NULL,+ tool text NOT NULL,+ status_code int,+ ttfb_ms int,+ total_ms int,+ chunk_count int,+ total_bytes bigint,+ max_gap_ms int,+ stalled boolean NOT NULL DEFAULT false,+ dropped boolean NOT NULL DEFAULT false,+ settled boolean NOT NULL DEFAULT false,+ healthy boolean NOT NULL,+ tx_signature text,+ error_msg text+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS mcp_stream_health_ts ON mcp_stream_health (ts DESC)`;+ _schemaReady = true;+}++async function storeStreamHealth(sql, runId, row) {+ try {+ await ensureSchema(sql);+ await sql`+ INSERT INTO mcp_stream_health+ (run_id, endpoint, tool, status_code, ttfb_ms, total_ms, chunk_count,+ total_bytes, max_gap_ms, stalled, dropped, settled, healthy,+ tx_signature, error_msg)+ VALUES+ (${runId || null}, ${row.endpoint}, ${row.tool}, ${row.status_code},+ ${row.ttfb_ms}, ${row.total_ms}, ${row.chunk_count}, ${row.total_bytes},+ ${row.max_gap_ms}, ${row.stalled}, ${row.dropped}, ${row.settled},+ ${row.healthy}, ${row.tx_signature || null}, ${row.error_msg || null})+ `;+ } catch (err) {+ // DB failure must never crash the loop — log and move on.+ log.warn('mcp_stream_health_insert_failed', { message: err?.message });+ }+}++/**+ * Run the SSE streaming health check. Self-contained: builds its own Solana+ * payment context when one isn't supplied, so it can be invoked directly (manual+ * test / standalone) or handed the per-tick loop's shared blockhash + keypair.+ *+ * @param {object} [ctx] — supplied by the loop:+ * { origin, buyer, conn, blockhash, mintInfo, redis, sql, log, runId, remainingCap }+ * @returns {Promise<{success:boolean, amountAtomic:number, txSig:string|null,+ * responseData:object|null, signalData:object, errorMsg:string|null,+ * skipped?:boolean}>} the outcome the loop records to x402_autonomous_log.+ */+export async function runStreamingMcpHealth(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const endpointUrl = `${origin}/api/mcp`;+ const sql = ctx.sql || defaultSql;+ const remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;++ const fail = (errorMsg, extra = {}) => ({+ success: false, amountAtomic: 0, txSig: null, responseData: null,+ signalData: { alive: false, tool: CANARY_TOOL, error: errorMsg },+ errorMsg, ...extra,+ });++ // ── Wallet pre-flight: exit gracefully (logged) if unconfigured ────────────+ let buyer = ctx.buyer;+ if (!buyer) {+ try { buyer = loadSeedKeypair(); } catch (err) {+ log.info('streaming_mcp_health_skipped', { reason: err.message });+ return fail(`wallet_unconfigured: ${err.message}`, { skipped: true });+ }+ }++ // ── Solana payment context (reuse loop's, else build our own) ──────────────+ let conn = ctx.conn;+ let blockhash = ctx.blockhash;+ let mintInfo = ctx.mintInfo;+ if (!conn || !blockhash || !mintInfo) {+ try {+ conn = conn || solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });+ const [bh, mi] = await Promise.all([+ blockhash ? Promise.resolve({ blockhash }) : conn.getLatestBlockhash('confirmed'),+ mintInfo ? Promise.resolve(mintInfo) : getMint(conn, new PublicKey(usdcMint())),+ ]);+ blockhash = blockhash || bh.blockhash;+ mintInfo = mintInfo || mi;+ } catch (err) {+ log.warn('streaming_mcp_health_solana_preflight_failed', { message: err?.message });+ return fail(`solana_preflight_failed: ${err?.message}`, { skipped: true });+ }+ }++ // ── Step 1: probe for the 402 challenge (plain x402 agent → real 402) ──────+ let probe;+ try {+ probe = await fetchWithTimeout(endpointUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'user-agent': 'threews-x402-autonomous/1.0' },+ body: JSON.stringify(buildToolCallBody()),+ });+ } catch (err) {+ return fail(`probe_failed: ${err?.message || 'network'}`);+ }++ // 402 (plain agent) or 401 (the server's MCP/OAuth challenge) both carry the+ // x402 envelope with `accepts` in the body. Anything else means the price gate+ // isn't where we expect — record and skip.+ if (probe.status !== 402 && probe.status !== 401) return fail(`unexpected_probe_status: ${probe.status}`);+ const accept = parseSolanaAccept(probe.body);+ if (!accept) return fail('no_solana_accept');+ if (accept.asset !== usdcMint()) return fail(`unexpected_asset: ${accept.asset}`);+ if (!accept.extra?.feePayer) return fail('missing_fee_payer');++ const amountAtomic = Number(accept.amount || 0);+ if (!(amountAtomic > 0)) return fail('zero_price');+ if (amountAtomic > remainingCap) return fail('cap_would_exceed', { skipped: true });++ // ── Step 2: build the signed payment tx + X-PAYMENT envelope ───────────────+ let xPayment;+ try {+ const receiverAta = getAssociatedTokenAddressSync(+ new PublicKey(accept.asset), new PublicKey(accept.payTo),+ false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);+ const txBase64 = buildPaymentTx({+ accept, buyer, blockhash, mintInfo, receiverAtaExists: receiverAtaInfo !== null,+ });+ xPayment = Buffer.from(JSON.stringify({+ x402Version: 2,+ scheme: 'exact',+ network: accept.network,+ resource: { url: endpointUrl, mimeType: 'application/json' },+ payload: { transaction: txBase64 },+ accepted: accept,+ })).toString('base64');+ } catch (err) {+ return fail(`build_payment_failed: ${err?.message || 'unknown'}`);+ }++ // ── Step 3: fire the paid call in SSE mode and read the response as a stream ─+ const startedAt = Date.now();+ const controller = new AbortController();+ const overall = setTimeout(() => controller.abort(), STREAM_TIMEOUT_MS);+ let metrics;+ try {+ const res = await fetch(endpointUrl, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ // Advertise SSE support — this is the "SSE mode" request; the server+ // negotiates the response transport off Accept.+ accept: 'text/event-stream, application/json',+ 'user-agent': 'threews-x402-autonomous/1.0',+ 'x-payment': xPayment,+ },+ body: JSON.stringify(buildToolCallBody()),+ signal: controller.signal,+ });+ metrics = await readStream(res, { stallMs: STALL_MS, startedAt });+ // Settlement is proven by the X-PAYMENT-RESPONSE header — the MCP server only+ // broadcasts the payment after the tool produced a result.+ const xpr = res.headers?.get?.('x-payment-response');+ metrics.settled = !!xpr;+ metrics.txSig = null;+ if (xpr) {+ try {+ const settled = JSON.parse(Buffer.from(xpr, 'base64').toString('utf8'));+ metrics.txSig = settled?.transaction || null;+ } catch { /* header present but unparseable — still settled */ }+ }+ } catch (err) {+ // Abort fires here when the overall budget is exceeded before any headers+ // arrive — treat as a dropped connection.+ metrics = {+ status: 0, ttfbMs: Date.now() - startedAt, totalMs: Date.now() - startedAt,+ chunkCount: 0, totalBytes: 0, maxGapMs: 0, stalled: false, dropped: true,+ raw: '', settled: false, txSig: null, abortMsg: err?.message || 'request_failed',+ };+ } finally {+ clearTimeout(overall);+ }++ // ── Step 4: classify health and extract value ──────────────────────────────+ const parsed = parseStreamPayload(metrics.raw);+ const rpcError = parsed?.error?.message || null;+ const toolError = parsed?.result?.isError === true;+ const hasResult = !!parsed?.result && !toolError && !rpcError;+ const streamClean = metrics.status === 200 && !metrics.stalled && !metrics.dropped && metrics.chunkCount > 0;+ const healthy = streamClean && hasResult && metrics.settled;++ let errorMsg = null;+ if (metrics.status === 402 || metrics.status === 401) errorMsg = `payment_rejected: ${metrics.status}`;+ else if (metrics.dropped) errorMsg = `stream_dropped${metrics.abortMsg ? `: ${metrics.abortMsg}` : ''}`;+ else if (metrics.stalled) errorMsg = 'stream_stalled';+ else if (rpcError) errorMsg = `rpc_error: ${rpcError}`;+ else if (toolError) errorMsg = 'tool_error';+ else if (!metrics.settled) errorMsg = 'not_settled';+ else if (!hasResult) errorMsg = 'no_result';++ const signalData = {+ alive: healthy,+ tool: CANARY_TOOL,+ status: metrics.status,+ ttfb_ms: metrics.ttfbMs,+ total_ms: metrics.totalMs,+ chunk_count: metrics.chunkCount,+ total_bytes: metrics.totalBytes,+ max_gap_ms: metrics.maxGapMs,+ stalled: metrics.stalled,+ dropped: metrics.dropped,+ settled: metrics.settled,+ };++ // ── Step 5: persist streaming-integrity metrics + alert on degradation ─────+ await storeStreamHealth(sql, runId, {+ endpoint: '/api/mcp',+ tool: CANARY_TOOL,+ status_code: metrics.status,+ ttfb_ms: metrics.ttfbMs,+ total_ms: metrics.totalMs,+ chunk_count: metrics.chunkCount,+ total_bytes: metrics.totalBytes,+ max_gap_ms: metrics.maxGapMs,+ stalled: metrics.stalled,+ dropped: metrics.dropped,+ settled: metrics.settled,+ healthy,+ tx_signature: metrics.txSig,+ error_msg: errorMsg,+ });++ if (metrics.stalled || metrics.dropped) {+ // Fire-and-forget: alerting must never block or crash the loop.+ sendOpsAlert(+ 'MCP SSE stream degraded',+ `POST /api/mcp (${CANARY_TOOL}) ${metrics.stalled ? 'STALLED' : 'DROPPED'} — ` ++ `status ${metrics.status}, ttfb ${metrics.ttfbMs}ms, ${metrics.chunkCount} chunks, ` ++ `${metrics.totalBytes}B, max gap ${metrics.maxGapMs}ms`,+ { signature: `mcp-sse-stream:${metrics.stalled ? 'stalled' : 'dropped'}` },+ ).catch(() => {});+ }++ log.info('streaming_mcp_health_complete', {+ run_id: runId, healthy, status: metrics.status, settled: metrics.settled,+ ttfb_ms: metrics.ttfbMs, total_ms: metrics.totalMs,+ chunks: metrics.chunkCount, bytes: metrics.totalBytes,+ stalled: metrics.stalled, dropped: metrics.dropped, error: errorMsg,+ });++ // amountAtomic reported to the loop reflects what was actually charged: only a+ // settled payment moved USDC on-chain.+ return {+ success: healthy,+ amountAtomic: metrics.settled ? amountAtomic : 0,+ txSig: metrics.txSig,+ responseData: parsed ?? (metrics.raw ? { raw: metrics.raw.slice(0, 2000) } : null),+ signalData,+ errorMsg,+ };+}++// Alias matching the pipelines convention (bazaar-warmup exports `run`).+export { runStreamingMcpHealth as run };diff --git a/api/_lib/x402/pipelines/volume-bootstrap-loop.js b/api/_lib/x402/pipelines/volume-bootstrap-loop.jsnew file mode 100644index 000000000..9c46d6880--- /dev/null+++ b/api/_lib/x402/pipelines/volume-bootstrap-loop.js@@ -0,0 +1,360 @@+// api/_lib/x402/pipelines/volume-bootstrap-loop.js+//+// x402 Volume Bootstrap Loop — autonomous pipeline (self/026).+//+// The core volume engine. Round-robins through the full catalog of paid, cheap+// three.ws self x402 endpoints, paying each one a real on-chain USDC payment from+// the seed wallet. It is NOT a single endpoint call — it is the sweep that proves+// every paid endpoint is live and continuously settles small ($0.001-$0.01)+// payments across all of them so the platform accrues genuine agent-to-agent+// transaction volume (the metric agentic.market ranks facilitators on).+//+// On each run it:+// 1. Advances a Redis-backed round-robin cursor and reserves the next window of+// VOLUME_BATCH_PER_RUN endpoints from VOLUME_ENDPOINTS (stable across warm+// instances; in-memory fallback when Redis is absent).+// 2. Pays each selected endpoint via the shared payX402 client — real 402+// probe → signed Solana USDC transfer → replay with X-PAYMENT. Never mocked.+// 3. Respects two budgets: the loop's remaining daily cap AND a self-imposed+// per-run cap (VOLUME_PER_RUN_CAP_ATOMIC) so one tick can't drain the day.+// 4. Records a row in x402_autonomous_log for EVERY call (success or failure),+// with the per-endpoint cumulative volume snapshot in value_extracted.+// 5. Upserts the per-endpoint volume ledger into x402_volume_metrics — call /+// success / fail counts, total + last USDC spent, last tx signature, last+// status, last error, first/last call timestamps.+//+// Wiring: declared as a run()-style entry in autonomous-registry.js+// (`volume-bootstrap-loop`). The per-tick spend loop (api/cron/x402-autonomous-loop.js)+// hands run() a shared payment context (buyer, conn, blockhash, mintInfo,+// remainingCap); called standalone (manual test) it bootstraps its own via+// bootstrapSolanaContext(), degrading gracefully if the wallet is unconfigured.+//+// Downstream consumer: x402_volume_metrics is the per-endpoint volume ledger the+// platform's growth + status surfaces read — total settled calls and USDC volume+// per endpoint (the proof-of-volume that bootstraps agentic.market ranking) and+// the per-endpoint last_success / last_called_at that confirms each paid endpoint+// is live. It complements x402_autonomous_log (per-call history) with a compact+// rolling aggregate keyed on endpoint.++import { randomUUID } from 'node:crypto';++import { sql as defaultSql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { payX402, bootstrapSolanaContext, USDC_MINT } from '../pay.js';++const log = logger('x402-volume-bootstrap');++const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// How many endpoints to sweep per run (cursor advances by this each tick). With+// the catalog below (~11 endpoints) a batch of 4 covers the full set in ~3 runs.+export const VOLUME_BATCH_PER_RUN = Math.max(+ 1,+ Number(process.env.X402_VOLUME_BATCH_PER_RUN || 4),+);++// Self-imposed per-run USDC budget (atomics, 6dp). Bounds a single tick on top of+// the loop's daily cap so one run can't drain the day. Default $0.05 = 50_000.+export const VOLUME_PER_RUN_CAP_ATOMIC = Math.max(+ 0,+ Number(process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC || 50_000),+);++// The canonical catalog of paid self x402 endpoints the loop round-robins. Each+// body is a proven, harmless canary payload (mirrors the per-endpoint health+// entries in autonomous-registry.js) so every sweep call is a valid paid request.+// To add an endpoint to the bootstrap volume, add it here — the cursor and the+// metrics ledger pick it up automatically. The volume loop itself is never listed+// (it is not an HTTP endpoint; no self-recursion).+export const VOLUME_ENDPOINTS = [+ { key: 'dance-tip', name: 'Dance Tip', path: '/api/x402/dance-tip', method: 'POST', body: { dancer: '1', dance: 'hiphop' } },+ { key: 'crypto-intel', name: 'Crypto Intel', path: '/api/x402/crypto-intel', method: 'POST', body: { topic: 'solana' } },+ { key: 'three-intel', name: '$THREE Signal Feed', path: '/api/x402/three-intel', method: 'POST', body: {} },+ { key: 'token-intel', name: 'Token Intel', path: '/api/x402/token-intel', method: 'POST', body: { mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', network: 'mainnet' } },+ { key: 'fact-check', name: 'Fact Check', path: '/api/x402/fact-check', method: 'POST', body: { claim: 'The sky is blue' } },+ { key: 'symbol-availability', name: 'Symbol Availability', path: '/api/x402/symbol-availability', method: 'POST', body: { symbol: 'HEALTH' } },+ { key: 'pay-by-name', name: 'Pay By Name', path: '/api/x402/pay-by-name', method: 'POST', body: { name: 'three.ws' } },+ { key: 'skill-marketplace', name: 'Skill Marketplace', path: '/api/x402/skill-marketplace', method: 'GET', body: null },+ { key: 'agent-reputation', name: 'Agent Reputation', path: '/api/x402/agent-reputation', method: 'GET', body: null },+ { key: 'club-cover', name: 'Club Cover Charge', path: '/api/x402/club-cover', method: 'POST', body: { club: 'canary_test' } },+ { key: 'cosmetic-purchase', name: 'Cosmetic Purchase', path: '/api/x402/cosmetic-purchase', method: 'POST', body: { item: 'canary_test', quantity: 1, _health_check: true } },+];++const CURSOR_KEY = 'x402:auto:volume:cursor';+let _memCursor = 0;++// Reserve the next window of `batch` endpoint indices, advancing the cursor+// atomically. Redis INCRBY gives a stable rotation across warm instances; the+// in-memory counter is the single-process fallback.+async function reserveWindow(redis, batch, len) {+ let end;+ if (redis) {+ try {+ end = Number(await redis.incrby(CURSOR_KEY, batch));+ } catch {+ end = (_memCursor += batch);+ }+ } else {+ end = (_memCursor += batch);+ }+ const start = end - batch;+ const out = [];+ for (let i = 0; i < batch; i++) out.push(((start + i) % len + len) % len);+ return out;+}++// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).+let _schemaReady = false;+async function ensureSchema(sql) {+ if (_schemaReady) return;+ // Per-endpoint cumulative volume ledger. PRIMARY KEY endpoint_key → one row+ // per paid endpoint, accumulated across every sweep.+ await sql`+ CREATE TABLE IF NOT EXISTS x402_volume_metrics (+ endpoint_key text PRIMARY KEY,+ service_name text,+ endpoint_path text,+ network text NOT NULL DEFAULT 'solana:mainnet',+ asset text,+ call_count bigint NOT NULL DEFAULT 0,+ success_count bigint NOT NULL DEFAULT 0,+ fail_count bigint NOT NULL DEFAULT 0,+ total_spent_atomic bigint NOT NULL DEFAULT 0,+ last_amount_atomic bigint NOT NULL DEFAULT 0,+ last_success boolean,+ last_status int,+ last_tx_signature text,+ last_error text,+ last_run_id uuid,+ first_called_at timestamptz DEFAULT now(),+ last_called_at timestamptz DEFAULT now()+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS x402_volume_metrics_last_called ON x402_volume_metrics (last_called_at DESC)`;+ // The autonomous log predates value_extracted; ensure the column exists+ // (idempotent — shared with other pipelines).+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+ _schemaReady = true;+}++// Compact, generic liveness summary of a paid response — keeps the log row small+// while still proving the endpoint returned something usable.+function summarizeResponse(body) {+ if (body == null) return { ok: false, shape: 'empty' };+ if (typeof body === 'string') return { ok: body.length > 0, shape: 'text', length: body.length };+ if (Array.isArray(body)) return { ok: body.length > 0, shape: 'array', length: body.length };+ if (typeof body === 'object') {+ const keys = Object.keys(body);+ return { ok: keys.length > 0 && !body.error, shape: 'object', keys: keys.slice(0, 12) };+ }+ return { ok: true, shape: typeof body };+}++// Upsert the per-endpoint volume ledger and return the resulting cumulative row.+// Wrapped by the caller so a DB fault is logged, never fatal.+async function upsertVolumeMetric(sql, ep, { amountAtomic, txSig, success, status, errorMsg, runId }) {+ const rows = await sql`+ INSERT INTO x402_volume_metrics+ (endpoint_key, service_name, endpoint_path, network, asset,+ call_count, success_count, fail_count, total_spent_atomic,+ last_amount_atomic, last_success, last_status, last_tx_signature,+ last_error, last_run_id, first_called_at, last_called_at)+ VALUES+ (${ep.key}, ${ep.name}, ${ep.path}, ${'solana:mainnet'}, ${ASSET},+ ${1}, ${success ? 1 : 0}, ${success ? 0 : 1}, ${amountAtomic || 0},+ ${amountAtomic || 0}, ${success}, ${status ?? null}, ${txSig || null},+ ${errorMsg || null}, ${runId}, now(), now())+ ON CONFLICT (endpoint_key) DO UPDATE SET+ service_name = EXCLUDED.service_name,+ endpoint_path = EXCLUDED.endpoint_path,+ asset = EXCLUDED.asset,+ call_count = x402_volume_metrics.call_count + 1,+ success_count = x402_volume_metrics.success_count + ${success ? 1 : 0},+ fail_count = x402_volume_metrics.fail_count + ${success ? 0 : 1},+ total_spent_atomic = x402_volume_metrics.total_spent_atomic + ${amountAtomic || 0},+ last_amount_atomic = EXCLUDED.last_amount_atomic,+ last_success = EXCLUDED.last_success,+ last_status = EXCLUDED.last_status,+ last_tx_signature = EXCLUDED.last_tx_signature,+ last_error = EXCLUDED.last_error,+ last_run_id = EXCLUDED.last_run_id,+ last_called_at = now()+ RETURNING call_count, success_count, fail_count, total_spent_atomic+ `;+ return rows[0] || null;+}++// Per-call row into x402_autonomous_log. The loop records one aggregate summary+// row for the run() entry; these are the granular per-endpoint sweep rows.+async function recordCall(sql, runId, ep, { endpointUrl, amountAtomic, txSig, responseData, durationMs, success, errorMsg, valueExtracted }) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${'self'}, ${`Volume: ${ep.name}`}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'volume'})+ `;+ } catch (err) {+ log.warn('volume_bootstrap_log_insert_failed', { endpoint: ep.key, message: err?.message });+ }+}++/**+ * Run the volume bootstrap sweep. Conforms to the run()-style registry contract:+ * the loop hands over { origin, buyer, conn, blockhash, mintInfo, remainingCap,+ * runId, sql }; standalone callers (manual test) get a bootstrapped context.+ *+ * Returns the aggregate outcome the loop records as one summary row:+ * { success, amountAtomic, txSig, errorMsg, responseData, skipped, note }+ */+export async function run(ctx = {}) {+ const sql = ctx.sql || defaultSql;+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const redis = ctx.redis || null;++ // ── Schema first: without the sink there is nothing to extract value into, so+ // don't pay. A schema failure is a graceful skip (no spend).+ try {+ await ensureSchema(sql);+ } catch (err) {+ log.warn('volume_bootstrap_schema_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };+ }++ // ── Solana payment context: reuse the loop's, else bootstrap. A bootstrap+ // failure (wallet/RPC unconfigured) exits logged, without paying.+ let { buyer, conn, blockhash, mintInfo } = ctx;+ if (!buyer || !conn || !blockhash || !mintInfo) {+ try {+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));+ } catch (err) {+ log.info('volume_bootstrap_skipped', { reason: err.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: err.message, note: 'wallet_or_rpc_unconfigured' };+ }+ }++ // ── Budget: the smaller of the loop's remaining daily cap and our per-run cap.+ const loopCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;+ let remaining = VOLUME_PER_RUN_CAP_ATOMIC > 0+ ? Math.min(loopCap, VOLUME_PER_RUN_CAP_ATOMIC)+ : loopCap;++ // ── Select this run's window of endpoints (round-robin).+ const indices = await reserveWindow(redis, VOLUME_BATCH_PER_RUN, VOLUME_ENDPOINTS.length);++ let spentAtomic = 0;+ let paid = 0;+ let calls = 0;+ let errors = 0;+ let lastTxSig = null;+ const swept = [];++ for (const idx of indices) {+ const ep = VOLUME_ENDPOINTS[idx];+ if (remaining <= 0) {+ log.info('volume_bootstrap_cap_reached', { endpoint: ep.key, spent_atomic: spentAtomic });+ break;+ }++ const endpointUrl = `${origin}${ep.path}`;+ const t0 = Date.now();++ // Pay (or detect free / skip). payX402 never throws for protocol/network+ // faults — it returns a structured outcome; a thrown error (rare) is still+ // caught so the sweep continues and the failure is recorded.+ let result;+ try {+ result = await payX402({+ url: endpointUrl,+ method: ep.method || 'POST',+ body: ep.body,+ buyer, conn, blockhash, mintInfo,+ remainingCap: remaining,+ });+ } catch (err) {+ result = { success: false, paid: false, amountAtomic: 0, txSig: null, status: 0, responseBody: null, errorMsg: err?.message || 'fetch_failed' };+ }++ calls += 1;+ if (!result.success) errors += 1;+ if (result.paid) {+ spentAtomic += result.amountAtomic;+ remaining -= result.amountAtomic;+ paid += 1;+ if (result.txSig) lastTxSig = result.txSig;+ }++ // Upsert the per-endpoint volume ledger; DB faults are logged, never fatal.+ let metric = null;+ try {+ metric = await upsertVolumeMetric(sql, ep, {+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ success: result.success,+ status: result.status,+ errorMsg: result.errorMsg,+ runId,+ });+ } catch (err) {+ log.warn('volume_metric_upsert_failed', { endpoint: ep.key, message: err?.message });+ }++ const valueExtracted = {+ endpoint_key: ep.key,+ paid: result.paid === true,+ amount_atomic: result.amountAtomic || 0,+ liveness: summarizeResponse(result.responseBody),+ ...(metric ? {+ cumulative_calls: Number(metric.call_count),+ cumulative_success: Number(metric.success_count),+ cumulative_spent_atomic: Number(metric.total_spent_atomic),+ } : {}),+ };++ await recordCall(sql, runId, ep, {+ endpointUrl,+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ // Trim the (possibly bulky) endpoint payload — the ledger holds the+ // useful aggregate; keep just the call status + liveness here.+ responseData: { status: result.status, liveness: valueExtracted.liveness },+ durationMs: Date.now() - t0,+ success: result.success,+ errorMsg: result.errorMsg,+ valueExtracted,+ });++ swept.push({ key: ep.key, paid: result.paid === true, success: result.success, status: result.status });+ }++ log.info('volume_bootstrap_complete', {+ run_id: runId,+ window: indices.length,+ calls,+ paid,+ errors,+ spent_usdc: (spentAtomic / 1e6).toFixed(4),+ });++ // Aggregate outcome for the loop's single summary row. success=true when at+ // least one endpoint settled or answered; per-call detail lives in the rows+ // above. skipped only when the window produced no calls at all.+ return {+ success: paid > 0 || (calls > 0 && errors < calls),+ amountAtomic: spentAtomic,+ txSig: lastTxSig,+ errorMsg: paid === 0 && errors > 0 ? `volume_bootstrap_calls_failed:${errors}/${calls}` : null,+ skipped: calls === 0,+ responseData: { window: indices.length, calls, paid, errors, swept },+ signalData: { calls, paid, errors, spent_atomic: spentAtomic },+ note: `volume_bootstrap calls=${calls} paid=${paid} errors=${errors}`,+ };+}diff --git a/api/_lib/x402/run-reputation-refresh.js b/api/_lib/x402/run-reputation-refresh.jsnew file mode 100644index 000000000..d9d36fc33--- /dev/null+++ b/api/_lib/x402/run-reputation-refresh.js@@ -0,0 +1,410 @@+// api/_lib/x402/run-reputation-refresh.js+//+// Agent Reputation Score Refresh — autonomous x402 pipeline.+//+// What it does each tick:+// • Selects the stalest registered Solana agents (those with an on-chain+// Metaplex Core asset in agent_identities.meta.sol_mint_address).+// • For each, makes a REAL paid x402 call to /api/mcp tool+// `solana_agent_reputation` ($0.001 USDC/call) using the platform seed+// keypair — the on-chain attestation reputation summary (feedback score+// averages, verified/disputed counts, validation pass/fail).+// • Writes the extracted score to agent_solana_reputation (one row per agent),+// flagging agents whose verified score drops below threshold.+// • Records every call — success or failure — to x402_autonomous_log.+//+// DATA OUT (value extraction):+// Table : agent_solana_reputation+// Columns: score (the headline trust number — verified feedback average when+// there is verified feedback, else the raw average), feedback_total,+// feedback_verified, feedback_disputed, validation_passed,+// validation_failed, flagged (boolean), raw (full response), refreshed_at.+//+// DOWNSTREAM CONSUMERS (read this table via the exported helpers below):+// • Agent-profile trust badge → getStoredSolanaReputation(agentId)+// • Reputation leaderboard → listSolanaReputationLeaderboard(limit)+// • Moderation / flagged feed → listFlaggedSolanaAgents(limit)+//+// This is the on-chain ATTESTATION reputation (feedback + validation memos),+// which is deliberately separate from the financial reputation in+// agent_reputation_scores (computed by api/cron/recompute-reputation.js). The+// two never share a table.++import { randomUUID } from 'node:crypto';++import { sql } from '../db.js';+import { env } from '../env.js';+import { logger } from '../usage.js';+import { prepareSolanaContext, payX402, ensureAutonomousLogTable } from './autonomous-pay.js';++const log = logger('x402-reputation-refresh');++const TOOL = 'solana_agent_reputation';+const SERVICE_NAME = 'Agent Reputation Score Refresh';+const PIPELINE = 'self';+const FALLBACK_USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+// Advertised price of the solana_agent_reputation tool: $0.001 USDC (6 decimals).+// Used only to pre-check the daily cap; the authoritative amount comes from the+// 402 challenge at call time.+const PRICE_ATOMIC = 1000;++// On-chain feedback scores use a 1–5 star scale. Flag an agent whose verified+// average drops below the threshold once it has a meaningful sample. Tunable.+const FLAG_THRESHOLD = Number(process.env.SOLANA_REPUTATION_FLAG_THRESHOLD || 3.0);+const FLAG_MIN_SAMPLE = Number(process.env.SOLANA_REPUTATION_FLAG_MIN_SAMPLE || 3);+// Agents refreshed per run — bounds per-tick spend and RPC/DB load. Stalest+// agents sort first, so coverage rotates across runs (same approach as the+// recompute-reputation cron).+const REFRESH_BATCH = Math.max(1, Number(process.env.SOLANA_REPUTATION_REFRESH_BATCH || 25));++let _ensured = null;+function ensureTable() {+ if (_ensured) return _ensured;+ _ensured = (async () => {+ await sql`+ create table if not exists agent_solana_reputation (+ agent_id uuid primary key,+ agent_asset text not null,+ network text not null default 'mainnet',+ score numeric(6,3) not null default 0,+ feedback_total int not null default 0,+ feedback_verified int not null default 0,+ feedback_disputed int not null default 0,+ validation_passed int not null default 0,+ validation_failed int not null default 0,+ flagged boolean not null default false,+ raw jsonb,+ refreshed_at timestamptz not null default now()+ )+ `;+ // Reputation leaderboard: rank agents by stored score cheaply.+ await sql`create index if not exists agent_solana_reputation_score_idx on agent_solana_reputation (score desc)`;+ // Moderation feed: list flagged agents without a full scan.+ await sql`create index if not exists agent_solana_reputation_flagged_idx on agent_solana_reputation (flagged) where flagged = true`;+ // Stalest-first selection for the refresh loop.+ await sql`create index if not exists agent_solana_reputation_refreshed_idx on agent_solana_reputation (refreshed_at asc)`;+ return true;+ })().catch((err) => {+ _ensured = null;+ log.warn('ensure_table_failed', { message: err?.message });+ throw err;+ });+ return _ensured;+}++async function listAgentsToRefresh(limit) {+ // Never-refreshed agents first, then stalest. Only agents with a registered+ // on-chain asset are eligible (those are the ones with attestations to read).+ return sql`+ select a.id,+ a.name,+ a.meta->>'sol_mint_address' as asset,+ coalesce(a.meta->>'network', 'mainnet') as network+ from agent_identities a+ left join agent_solana_reputation r on r.agent_id = a.id+ where a.deleted_at is null+ and a.meta->>'sol_mint_address' is not null+ order by (r.agent_id is null) desc, r.refreshed_at asc nulls first+ limit ${limit}+ `;+}++function toolBody(asset, network, id) {+ return {+ jsonrpc: '2.0',+ id,+ method: 'tools/call',+ params: { name: TOOL, arguments: { asset, network } },+ };+}++// MCP returns a single JSON-RPC response object (or a 1-element array for a+// batched body). The reputation payload lives in result.structuredContent.+function parseReputation(respBody) {+ const msg = Array.isArray(respBody) ? respBody[0] : respBody;+ const sc = msg?.result?.structuredContent;+ if (!sc || sc.error) return null;+ return sc;+}++// Derive the headline trust score and the flag verdict from a reputation+// payload: { feedback:{ total, verified, disputed, score_avg, score_avg_verified }, validation:{ passed, failed } }.+function evaluate(rep) {+ const fb = rep.feedback || {};+ const val = rep.validation || {};+ const verified = Number(fb.verified || 0);+ const total = Number(fb.total || 0);+ const disputed = Number(fb.disputed || 0);+ const passed = Number(val.passed || 0);+ const failed = Number(val.failed || 0);++ // Prefer the verified-only average (feedback whose task the owner acknowledged+ // on-chain) when any exists; otherwise the raw average.+ const score = Number(verified > 0 ? (fb.score_avg_verified || 0) : (fb.score_avg || 0));+ const sample = verified > 0 ? verified : total;++ const reasons = [];+ if (sample >= FLAG_MIN_SAMPLE && score < FLAG_THRESHOLD) reasons.push(`score ${score.toFixed(2)} < ${FLAG_THRESHOLD}`);+ if (total > 0 && disputed / total > 0.5) reasons.push('majority of feedback disputed');+ if (passed + failed > 0 && failed > passed) reasons.push('validation failing');++ return { score, flagged: reasons.length > 0, reasons, total, verified, disputed, passed, failed };+}++async function upsertReputation(agent, rep, evald) {+ await sql`+ insert into agent_solana_reputation+ (agent_id, agent_asset, network, score, feedback_total, feedback_verified,+ feedback_disputed, validation_passed, validation_failed, flagged, raw, refreshed_at)+ values+ (${agent.id}, ${agent.asset}, ${agent.network}, ${evald.score},+ ${evald.total}, ${evald.verified}, ${evald.disputed},+ ${evald.passed}, ${evald.failed}, ${evald.flagged},+ ${JSON.stringify(rep)}, now())+ on conflict (agent_id) do update set+ agent_asset = excluded.agent_asset,+ network = excluded.network,+ score = excluded.score,+ feedback_total = excluded.feedback_total,+ feedback_verified = excluded.feedback_verified,+ feedback_disputed = excluded.feedback_disputed,+ validation_passed = excluded.validation_passed,+ validation_failed = excluded.validation_failed,+ flagged = excluded.flagged,+ raw = excluded.raw,+ refreshed_at = now()+ `;+}++async function recordLog(usdcMint, { runId, endpointUrl, amountAtomic, txSig, responseData, durationMs, success, errorMsg, signalData }) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ response_data, signal_data, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${'self'}, ${SERVICE_NAME}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0},+ ${usdcMint || FALLBACK_USDC_MINT}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${signalData ? JSON.stringify(signalData) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${PIPELINE})+ `;+ } catch (err) {+ log.warn('autonomous_log_insert_failed', { message: err?.message });+ }+}++/**+ * Run the reputation refresh pipeline.+ *+ * Called by the autonomous loop with a shared Solana context, or directly (e.g.+ * a manual test) with no args — in which case it builds its own context.+ *+ * @param {object} [ctx]+ * @param {string} [ctx.runId]+ * @param {string} [ctx.origin] APP origin (defaults to env.APP_ORIGIN)+ * @param {import('@solana/web3.js').Keypair} [ctx.buyer]+ * @param {import('@solana/web3.js').Connection} [ctx.conn]+ * @param {string} [ctx.blockhash]+ * @param {object} [ctx.mintInfo]+ * @param {string} [ctx.usdcMint]+ * @param {number} [ctx.remainingCap] atomic USDC the daily cap still allows+ * @returns {Promise<{ ok:boolean, spentAtomic:number, error?:string, summary:object }>}+ */+export async function runReputationRefresh(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const usdcMint = ctx.usdcMint || env.X402_ASSET_MINT_SOLANA || FALLBACK_USDC_MINT;+ const endpointUrl = `${origin}/api/mcp`;+ const remainingCap = Number.isFinite(ctx.remainingCap) ? ctx.remainingCap : Infinity;++ await ensureAutonomousLogTable();++ // DB: load eligible agents. A failure here is logged and the run exits — never+ // crashes the loop.+ let agents;+ try {+ await ensureTable();+ agents = await listAgentsToRefresh(REFRESH_BATCH);+ } catch (err) {+ log.error('list_agents_failed', { message: err?.message });+ await recordLog(usdcMint, {+ runId, endpointUrl, amountAtomic: 0, success: false,+ errorMsg: `db_error: ${err?.message || 'unknown'}`, durationMs: 0,+ });+ return { ok: false, error: 'db_error', spentAtomic: 0, summary: { scanned: 0 } };+ }++ if (!agents.length) {+ log.info('no_registered_agents');+ return { ok: true, spentAtomic: 0, summary: { scanned: 0, note: 'no_registered_agents' } };+ }++ // Solana context: reuse the loop's shared per-tick state when provided; else+ // build our own. If the wallet is unconfigured (or RPC is down) we record one+ // log row and exit gracefully — no crash, no partial work.+ let solctx;+ try {+ solctx = (ctx.buyer && ctx.conn && ctx.blockhash && ctx.mintInfo)+ ? { buyer: ctx.buyer, conn: ctx.conn, blockhash: ctx.blockhash, mintInfo: ctx.mintInfo, usdcMint }+ : await prepareSolanaContext({ usdcMint });+ } catch (err) {+ log.warn('reputation_refresh_skipped', { reason: err?.message });+ await recordLog(usdcMint, {+ runId, endpointUrl, amountAtomic: 0, success: false,+ errorMsg: `wallet_or_rpc_unavailable: ${err?.message || 'unknown'}`, durationMs: 0,+ });+ return { ok: false, error: 'wallet_unconfigured', spentAtomic: 0, summary: { scanned: 0 } };+ }++ let spentAtomic = 0;+ let paid = 0;+ let stored = 0;+ let flaggedCount = 0;+ let errors = 0;++ for (let i = 0; i < agents.length; i++) {+ const agent = agents[i];++ // Stop before charging again if the next call would exceed the daily cap+ // the loop handed us (Infinity when run directly / uncapped).+ if (Number.isFinite(remainingCap) && spentAtomic + PRICE_ATOMIC > remainingCap) {+ log.info('reputation_cap_reached', { spentAtomic, remainingCap });+ break;+ }++ const t0 = Date.now();+ let amountAtomic = 0;+ let txSig = null;+ let success = false;+ let errorMsg = null;+ let responseData = null;+ let signalData = null;++ try {+ const pay = await payX402({+ ...solctx,+ url: endpointUrl,+ method: 'POST',+ body: toolBody(agent.asset, agent.network, i + 1),+ // Distinct nonce per call so these identical-amount ($0.001) payments+ // against the one shared blockhash each produce a unique signature.+ nonce: i + 1,+ });++ responseData = pay.body;+ amountAtomic = pay.amountAtomic || 0;+ txSig = pay.txSig || null;++ // Cap guard: if this call would push us past the daily cap, stop before+ // charging again. (The probe already happened, but no payment was sent+ // on a non-ok result; an ok result means we already paid — so we check+ // the cap on the NEXT iteration via the accumulated spend below.)+ if (!pay.ok) {+ errorMsg = pay.error || `http_${pay.status}`;+ errors++;+ } else {+ const rep = parseReputation(pay.body);+ if (!rep) {+ errorMsg = 'unparseable_response';+ errors++;+ } else {+ const evald = evaluate(rep);+ signalData = {+ agent_id: agent.id, asset: agent.asset, network: agent.network,+ score: evald.score, flagged: evald.flagged, reasons: evald.reasons,+ feedback: rep.feedback, validation: rep.validation,+ };+ try {+ await upsertReputation(agent, rep, evald);+ stored++;+ if (evald.flagged) flaggedCount++;+ } catch (dbErr) {+ // Payment already settled; persisting the value failed. Record the+ // row as a failure with the error so it is retried next tick.+ errorMsg = `store_failed: ${dbErr?.message || 'unknown'}`;+ errors++;+ }+ success = !errorMsg;+ paid++;+ spentAtomic += amountAtomic;+ }+ }+ } catch (err) {+ errorMsg = err?.message || 'unknown_error';+ errors++;+ }++ await recordLog(usdcMint, {+ runId, endpointUrl, amountAtomic, txSig,+ responseData, durationMs: Date.now() - t0, success, errorMsg, signalData,+ });+ }++ log.info('reputation_refresh_complete', {+ run_id: runId, scanned: agents.length, paid, stored,+ flagged: flaggedCount, errors, spent_usdc: (spentAtomic / 1e6).toFixed(4),+ });++ return {+ ok: true,+ spentAtomic,+ summary: { scanned: agents.length, paid, stored, flagged: flaggedCount, errors },+ };+}++// ── Downstream consumers ────────────────────────────────────────────────────+// The data this pipeline extracts is read back through these helpers.++/** Trust badge on an agent profile: the stored on-chain reputation, or null. */+export async function getStoredSolanaReputation(agentId) {+ if (!agentId) return null;+ try {+ const [row] = await sql`+ select agent_id, agent_asset, network, score, feedback_total, feedback_verified,+ feedback_disputed, validation_passed, validation_failed, flagged, refreshed_at+ from agent_solana_reputation where agent_id = ${agentId} limit 1+ `;+ return row || null;+ } catch {+ return null;+ }+}++/** Reputation leaderboard: top agents by stored on-chain score. */+export async function listSolanaReputationLeaderboard(limit = 50) {+ const n = Math.min(Math.max(1, Number(limit) || 50), 200);+ try {+ return await sql`+ select r.agent_id, r.agent_asset, r.network, r.score, r.feedback_total,+ r.feedback_verified, r.flagged, r.refreshed_at, a.name+ from agent_solana_reputation r+ join agent_identities a on a.id = r.agent_id and a.deleted_at is null+ where r.feedback_total > 0+ order by r.score desc, r.feedback_verified desc+ limit ${n}+ `;+ } catch {+ return [];+ }+}++/** Moderation feed: agents currently flagged below the trust threshold. */+export async function listFlaggedSolanaAgents(limit = 100) {+ const n = Math.min(Math.max(1, Number(limit) || 100), 500);+ try {+ return await sql`+ select r.agent_id, r.agent_asset, r.network, r.score, r.feedback_total,+ r.feedback_disputed, r.refreshed_at, a.name+ from agent_solana_reputation r+ join agent_identities a on a.id = r.agent_id and a.deleted_at is null+ where r.flagged = true+ order by r.score asc+ limit ${n}+ `;+ } catch {+ return [];+ }+}diff --git a/api/_lib/x402/scene-capture-processor.js b/api/_lib/x402/scene-capture-processor.jsnew file mode 100644index 000000000..a38694e2a--- /dev/null+++ b/api/_lib/x402/scene-capture-processor.js@@ -0,0 +1,327 @@+// api/_lib/x402/scene-capture-processor.js+//+// Scene Capture Video Queue Processor — the autonomous pipeline behind the+// /capture feature. Users upload a video on the /capture page; instead of+// blocking the request on a multi-minute GPU reconstruction, the upload is+// enqueued into `scene_capture_queue` and this processor drains it on the x402+// autonomous loop's schedule:+//+// pending → pay $0.01 USDC (x402) for one processing credit, then submit+// the video to the LingBot-Map GPU worker (workers/model-video2scene).+// processing → poll the worker; when the .ply point cloud is ready, store the+// result URL + telemetry back on the queue row.+//+// One scene = one metered x402 payment (at submit). Status polls are free internal+// status checks and never pay. The processor is invoked from the autonomous loop+// via the registry entry's run(ctx) — the loop records every invocation to+// x402_autonomous_log; this module owns the queue + result storage.+//+// Value extracted → stored to:+// scene_capture_queue.result_url (the finished .ply point-cloud URL)+// scene_capture_queue.num_points (reconstruction point count)+// scene_capture_queue.frames (frames fused)+// x402_autonomous_log.signal_data (the loop persists the run() outcome's+// signalData — job/result snapshot — here)+//+// Downstream consumer: src/scene-capture.js (the /capture page, pages/capture.html)+// fetches result_url and renders the .ply client-side as a THREE.Points cloud.++import { sql } from '../db.js';+import { env } from '../env.js';+import { logger } from '../usage.js';+import { assertPublicHttpsUrl, SsrfError } from '../ssrf.js';+import { createRegenProvider } from '../../_providers/gcp.js';+import { payX402, bootstrapSolanaContext } from './pay.js';++const log = logger('x402-scene-capture');++// One processing credit = $0.01 USDC = 10_000 atomics (USDC has 6 decimals).+export const SCENE_CAPTURE_CREDIT_SLUG = 'video2scene-processing-credit';+export const SCENE_CAPTURE_PRICE_ATOMIC = 10_000;+// Path of the x402 endpoint that meters a scene-processing credit.+export const SCENE_CAPTURE_ENDPOINT = `/api/x402/asset-download?slug=${SCENE_CAPTURE_CREDIT_SLUG}`;+// Stop retrying a video after this many failed submit/credit attempts.+const MAX_ATTEMPTS = 3;++let schemaReady = false;++// Idempotent schema + catalog setup. The queue table backs the /capture upload+// flow; the paid_assets credit row makes the metering payment resolvable against+// the existing /api/x402/asset-download endpoint without forking it. Payout+// recirculates to the platform wallet (env.X402_PAY_TO_SOLANA) — falls back to+// env inside the endpoint when the column is NULL.+export async function ensureSceneCaptureSchema() {+ if (schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS scene_capture_queue (+ id bigserial PRIMARY KEY,+ video_url text NOT NULL,+ params jsonb NOT NULL DEFAULT '{}'::jsonb,+ status text NOT NULL DEFAULT 'pending'+ CHECK (status IN ('pending','submitting','processing','done','failed')),+ job_id text,+ result_url text,+ num_points integer,+ frames integer,+ bytes bigint,+ error_msg text,+ attempts integer NOT NULL DEFAULT 0,+ tx_signature text,+ amount_atomic bigint,+ enqueued_by text,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now()+ )+ `;+ await sql`+ CREATE INDEX IF NOT EXISTS scene_capture_queue_status_idx+ ON scene_capture_queue (status, created_at)+ `;+ await sql`+ INSERT INTO paid_assets+ (slug, title, description, mime_type, size_bytes, r2_key, price_atomics, creator_payto_solana)+ VALUES+ (${SCENE_CAPTURE_CREDIT_SLUG},+ 'Scene Capture Processing Credit',+ 'One video-to-3D scene reconstruction credit. Meters a single GPU point-cloud job in the three.ws scene-capture pipeline.',+ 'application/json', 0,+ ${`credits/${SCENE_CAPTURE_CREDIT_SLUG}.json`},+ ${String(SCENE_CAPTURE_PRICE_ATOMIC)},+ ${env.X402_PAY_TO_SOLANA || null})+ ON CONFLICT (slug) DO NOTHING+ `;+ schemaReady = true;+}++// Enqueue a user-uploaded video for autonomous reconstruction. Called by the+// /capture upload path; validates the URL up front so a bad row never reaches+// the GPU worker. Returns the queue row id.+export async function enqueueSceneCapture({ videoUrl, params = {}, enqueuedBy = null }) {+ await ensureSceneCaptureSchema();+ const safeUrl = await assertPublicHttpsUrl(String(videoUrl || ''));+ const rows = await sql`+ INSERT INTO scene_capture_queue (video_url, params, enqueued_by)+ VALUES (${safeUrl}, ${JSON.stringify(params || {})}, ${enqueuedBy})+ RETURNING id+ `;+ return rows[0]?.id ?? null;+}++function resolveProvider() {+ try {+ const provider = createRegenProvider();+ return provider.supportsMode('video2scene') ? provider : null;+ } catch {+ return null;+ }+}++// Atomically claim the oldest pending row (marking it 'submitting' so a+// concurrent tick can't grab the same video) — FOR UPDATE SKIP LOCKED.+async function claimPending() {+ const rows = await sql`+ UPDATE scene_capture_queue+ SET status = 'submitting', attempts = attempts + 1, updated_at = now()+ WHERE id = (+ SELECT id FROM scene_capture_queue+ WHERE status = 'pending'+ ORDER BY created_at ASC+ LIMIT 1+ FOR UPDATE SKIP LOCKED+ )+ RETURNING *+ `;+ return rows[0] || null;+}++async function claimProcessing() {+ const rows = await sql`+ SELECT * FROM scene_capture_queue+ WHERE status = 'processing' AND job_id IS NOT NULL+ ORDER BY updated_at ASC+ LIMIT 1+ `;+ return rows[0] || null;+}++// Move a claimed-but-unsubmitted row back to a resting state.+async function releaseRow(id, { status, errorMsg = null }) {+ await sql`+ UPDATE scene_capture_queue+ SET status = ${status}, error_msg = ${errorMsg}, updated_at = now()+ WHERE id = ${id}+ `;+}++// Process one unit of queue work. Returns the structured outcome the autonomous+// loop records to x402_autonomous_log:+// { success, amountAtomic, txSig, responseData, signalData, errorMsg, skipped, note }+//+// `success` reflects whether the autonomous x402 call did its job (paid a credit,+// or completed a free status poll). Reconstruction-level failures live on the+// queue row (scene_capture_queue.error_msg), not on the metered call.+export async function runSceneCaptureProcessor(ctx = {}) {+ try {+ await ensureSceneCaptureSchema();+ } catch (err) {+ log.warn('schema_ensure_failed', { message: err?.message });+ return { success: false, amountAtomic: 0, txSig: null, errorMsg: `schema_failed: ${err?.message}`, note: 'schema_failed' };+ }++ const provider = resolveProvider();+ if (!provider) {+ // GPU worker not wired on this deployment — graceful no-op, recorded.+ log.info('video2scene_unconfigured');+ return {+ success: true, skipped: true, amountAtomic: 0, txSig: null,+ note: 'video2scene_unconfigured',+ responseData: { reason: 'GCP_VIDEO2SCENE_URL / GCP_RECONSTRUCTION_KEY not configured' },+ };+ }++ // Prefer draining in-flight jobs (free polls) before paying to submit new ones.+ let processing;+ try { processing = await claimProcessing(); } catch (err) {+ return { success: false, amountAtomic: 0, txSig: null, errorMsg: `db_failed: ${err?.message}`, note: 'db_failed' };+ }+ if (processing) return pollExisting(provider, processing);++ let pending;+ try { pending = await claimPending(); } catch (err) {+ return { success: false, amountAtomic: 0, txSig: null, errorMsg: `db_failed: ${err?.message}`, note: 'db_failed' };+ }+ if (pending) return payAndSubmit(ctx, provider, pending);++ // Nothing to do — still a successful, recorded tick (amount 0).+ return { success: true, amountAtomic: 0, txSig: null, note: 'queue_empty', responseData: { pending: 0, processing: 0 } };+}++async function pollExisting(provider, row) {+ let result;+ try {+ result = await provider.status(row.job_id);+ } catch (err) {+ // Transient worker/network fault — keep the job processing, retry next tick.+ await sql`UPDATE scene_capture_queue SET updated_at = now() WHERE id = ${row.id}`.catch(() => {});+ return { success: true, amountAtomic: 0, txSig: null, note: 'poll_failed_retry', errorMsg: err?.message,+ signalData: { action: 'poll', queue_id: Number(row.id), state: 'error' } };+ }++ if (result.status === 'done') {+ const resultUrl = result.resultPointCloudUrl || null;+ if (!resultUrl) {+ await releaseRow(row.id, { status: 'failed', errorMsg: 'worker reported done with no result URL' });+ return { success: true, amountAtomic: 0, txSig: null, note: 'done_no_result',+ signalData: { action: 'poll', queue_id: Number(row.id), state: 'failed' } };+ }+ await sql`+ UPDATE scene_capture_queue+ SET status = 'done', result_url = ${resultUrl},+ num_points = ${result.numPoints ?? null}, frames = ${result.frames ?? null},+ bytes = ${result.bytes ?? null}, error_msg = NULL, updated_at = now()+ WHERE id = ${row.id}+ `;+ const signalData = {+ action: 'poll', queue_id: Number(row.id), state: 'done',+ result_url: resultUrl, num_points: result.numPoints ?? null, frames: result.frames ?? null,+ };+ log.info('scene_done', { queue_id: Number(row.id), num_points: result.numPoints ?? null });+ return { success: true, amountAtomic: 0, txSig: null, note: 'completed', responseData: signalData, signalData };+ }++ if (result.status === 'failed') {+ await releaseRow(row.id, { status: 'failed', errorMsg: result.error || 'reconstruction failed' });+ return { success: true, amountAtomic: 0, txSig: null, note: 'reconstruction_failed', errorMsg: result.error || null,+ signalData: { action: 'poll', queue_id: Number(row.id), state: 'failed' } };+ }++ // queued / running — touch and wait for the next tick.+ await sql`UPDATE scene_capture_queue SET updated_at = now() WHERE id = ${row.id}`;+ return { success: true, amountAtomic: 0, txSig: null, note: 'still_processing',+ signalData: { action: 'poll', queue_id: Number(row.id), state: result.status } };+}++async function payAndSubmit(ctx, provider, row) {+ const id = Number(row.id);+ const attempts = Number(row.attempts) || 0;+ const giveUpStatus = attempts >= MAX_ATTEMPTS ? 'failed' : 'pending';++ // Defense-in-depth: re-validate the stored URL before handing it to the worker.+ let videoUrl;+ try {+ videoUrl = await assertPublicHttpsUrl(String(row.video_url || ''));+ } catch (err) {+ await releaseRow(id, { status: 'failed', errorMsg: err instanceof SsrfError ? `url_rejected: ${err.message}` : 'invalid_video_url' });+ return { success: false, amountAtomic: 0, txSig: null, note: 'invalid_video_url', errorMsg: err?.message };+ }++ // Resolve the payment context. Reuse the loop's shared per-tick Solana state+ // when present; bootstrap our own when called standalone (manual test).+ let buyer = ctx.buyer, conn = ctx.conn, blockhash = ctx.blockhash, mintInfo = ctx.mintInfo;+ if (!buyer || !conn || !blockhash || !mintInfo) {+ try {+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));+ } catch (err) {+ // Wallet not configured — leave the row pending and exit gracefully.+ await releaseRow(id, { status: 'pending', errorMsg: `payer_unconfigured: ${err?.message}` });+ log.info('payer_unconfigured', { queue_id: id, message: err?.message });+ return { success: true, skipped: true, amountAtomic: 0, txSig: null, note: 'payer_unconfigured', errorMsg: err?.message };+ }+ }++ // Step 1 — pay one processing credit via x402.+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ let pay;+ try {+ pay = await payX402({+ url: `${origin}${SCENE_CAPTURE_ENDPOINT}`,+ method: 'GET',+ buyer, conn, blockhash, mintInfo,+ remainingCap: ctx.remainingCap ?? Infinity,+ });+ } catch (err) {+ await releaseRow(id, { status: giveUpStatus, errorMsg: `pay_error: ${err?.message}` });+ return { success: false, amountAtomic: 0, txSig: null, note: 'pay_error', errorMsg: err?.message };+ }++ if (!pay.success) {+ // 402 rejection, cap exceeded, asset mismatch, etc. — don't burn GPU.+ await releaseRow(id, { status: giveUpStatus, errorMsg: `payment_failed: ${pay.errorMsg}` });+ return { success: false, skipped: !!pay.skipped, amountAtomic: pay.amountAtomic || 0, txSig: pay.txSig || null,+ note: 'payment_failed', errorMsg: pay.errorMsg, responseData: pay.responseBody };+ }++ // Step 2 — submit the paid scene to the GPU worker.+ let job;+ try {+ job = await provider.submit({ mode: 'video2scene', sourceUrl: videoUrl, params: row.params || {} });+ } catch (err) {+ // We paid; the submit failed. The credit is spent (recorded), the scene+ // retries next tick. Payment success is what the autonomous loop meters.+ await releaseRow(id, { status: giveUpStatus, errorMsg: `submit_failed: ${err?.message}` });+ log.warn('submit_failed_after_pay', { queue_id: id, tx: pay.txSig, message: err?.message });+ return {+ success: true, amountAtomic: pay.amountAtomic, txSig: pay.txSig,+ note: 'submit_failed_after_pay',+ signalData: { action: 'submit', queue_id: id, state: 'submit_failed', tx_signature: pay.txSig },+ responseData: pay.responseBody,+ };+ }++ await sql`+ UPDATE scene_capture_queue+ SET status = 'processing', job_id = ${job.extJobId},+ tx_signature = ${pay.txSig}, amount_atomic = ${pay.amountAtomic},+ error_msg = NULL, updated_at = now()+ WHERE id = ${id}+ `;+ const signalData = {+ action: 'submit', queue_id: id, state: 'processing',+ job_id: job.extJobId, eta_seconds: job.eta ?? null, tx_signature: pay.txSig,+ };+ log.info('scene_submitted', { queue_id: id, tx: pay.txSig, amount_usdc: pay.amountAtomic / 1e6 });+ return {+ success: true, amountAtomic: pay.amountAtomic, txSig: pay.txSig,+ note: 'submitted', responseData: signalData, signalData,+ };+}diff --git a/api/_lib/x402/streaming-mcp-health.js b/api/_lib/x402/streaming-mcp-health.jsdeleted file mode 100644index 5a75e7e5d..000000000--- a/api/_lib/x402/streaming-mcp-health.js+++ /dev/null@@ -1,406 +0,0 @@-// api/_lib/x402/streaming-mcp-health.js-//-// SSE Streaming MCP Health — a custom-execution entry for the x402 autonomous-// spend loop (see autonomous-registry.js → entry `mcp-sse-stream-health`).-//-// What it does, on every run:-// 1. Probes POST /api/mcp as a plain x402 agent to obtain the 402 challenge.-// 2. Builds a REAL Solana USDC payment for a single priced tools/call-// (validate_model on a tiny, public, self-hosted canary GLB).-// 3. Fires the paid request in *SSE mode* — Accept: text/event-stream — and-// reads the HTTP response as a STREAM, not a single buffered body. It-// measures time-to-first-byte, per-chunk gaps, chunk count, and total-// bytes, and classifies the stream as clean / stalled / dropped. This is-// what verifies the streaming response arrives intact before close and-// surfaces broken chunked encoding or a server that hangs mid-response.-// 4. Confirms settlement via the X-PAYMENT-RESPONSE header (the MCP server-// only broadcasts the payment when the tool actually produced a result),-// and pulls the on-chain tx signature out of it.-// 5. Stores the streaming-integrity metrics to `mcp_stream_health` and fires-// an ops alert when a stream stalls or drops.-//-// Reality note: the /api/mcp POST handler returns a single JSON body (it does-// not yet emit token-by-token SSE frames), and GET /api/mcp answers 405 after-// auth — there is no long-lived server→client subscription to read. So this-// check honestly exercises the *paid streaming transport*: it advertises SSE-// support, streams the chunked response, and validates TTFB / inter-chunk-// liveness / complete delivery / chunked-encoding integrity. It does not fake-// token frames the server never sends.-//-// The autonomous loop owns recording to x402_autonomous_log, cooldown, and-// daily-spend accounting. This module owns the probe, the payment, the-// streaming read, and the value extraction/storage. It returns a result the-// loop records:-// { success, amountAtomic, txSig, responseData, signalData, errorMsg,-// skipped?, cooldown? }--import {- PublicKey,-} from '@solana/web3.js';-import {- getAssociatedTokenAddressSync,- TOKEN_PROGRAM_ID,- ASSOCIATED_TOKEN_PROGRAM_ID,-} from '@solana/spl-token';-import { sendOpsAlert } from '../alerts.js';--// Tiny, public, self-hosted Khronos sample (~160 KB) — always available at the-// canonical origin, validates cleanly, and keeps fetch+validate time low so the-// canary measures transport latency, not model size. Pinned to the canonical-// public origin (not the loop's runtime origin) so validate_model's SSRF guard-// — which only fetches public https URLs — always has a real public asset to-// pull, regardless of where the loop executes.-const CANARY_TOOL = 'validate_model';-const CANARY_GLB = 'https://three.ws/avatars/fox.glb';--// Overall wall-clock budget for the paid streaming call (must fit inside the-// loop's per-tick budget). A stall is a quieter failure: no bytes for this long-// while the connection is still open is treated as a stalled stream.-const STREAM_TIMEOUT_MS = 18_000;-const STALL_MS = 8_000;--function buildToolCallBody() {- return {- jsonrpc: '2.0',- id: 1,- method: 'tools/call',- params: {- name: CANARY_TOOL,- arguments: { url: CANARY_GLB, max_issues: 5 },- },- };-}--// Parse whatever the streaming read accumulated. The server returns a JSON body-// today, but a future SSE upgrade would frame it as `data: {...}` lines — handle-// both so the canary keeps working across that change.-function parseStreamPayload(raw) {- if (!raw || typeof raw !== 'string') return null;- const trimmed = raw.trim();- if (!trimmed) return null;- try {- return JSON.parse(trimmed);- } catch { /* maybe SSE-framed */ }- const dataLines = trimmed- .split('\n')- .filter((l) => l.startsWith('data:'))- .map((l) => l.slice(5).trim())- .filter(Boolean);- for (let i = dataLines.length - 1; i >= 0; i--) {- try { return JSON.parse(dataLines[i]); } catch { /* try the next-to-last frame */ }- }- return null;-}--// Read an HTTP response body as a stream, recording streaming-integrity metrics.-// Resolves with metrics even on stall/drop — the caller decides health from them.-async function readStream(res, { stallMs, startedAt }) {- const metrics = {- status: res.status,- ttfbMs: null,- totalMs: 0,- chunkCount: 0,- totalBytes: 0,- maxGapMs: 0,- stalled: false,- dropped: false,- raw: '',- };-- if (!res.body || typeof res.body.getReader !== 'function') {- // No readable stream (e.g. an error envelope) — fall back to buffered read.- try { metrics.raw = await res.text(); } catch { metrics.dropped = true; }- metrics.totalBytes = Buffer.byteLength(metrics.raw || '');- metrics.chunkCount = metrics.raw ? 1 : 0;- metrics.ttfbMs = Date.now() - startedAt;- metrics.totalMs = Date.now() - startedAt;- return metrics;- }-- const reader = res.body.getReader();- const decoder = new TextDecoder();- let lastChunkAt = startedAt;-- try {- for (;;) {- let stallTimer = null;- const stall = new Promise((_, reject) => {- stallTimer = setTimeout(() => reject(new Error('stall_timeout')), stallMs);- });- let chunk;- try {- chunk = await Promise.race([reader.read(), stall]);- } finally {- if (stallTimer) clearTimeout(stallTimer);- }-- if (chunk.done) break;- const now = Date.now();- if (metrics.ttfbMs === null) {- metrics.ttfbMs = now - startedAt;- } else {- const gap = now - lastChunkAt;- if (gap > metrics.maxGapMs) metrics.maxGapMs = gap;- }- lastChunkAt = now;- metrics.chunkCount++;- metrics.totalBytes += chunk.value?.byteLength || 0;- metrics.raw += decoder.decode(chunk.value, { stream: true });- }- metrics.raw += decoder.decode();- } catch (err) {- if (err?.message === 'stall_timeout') metrics.stalled = true;- else metrics.dropped = true; // abort / connection reset / overall timeout- try { await reader.cancel(); } catch { /* already torn down */ }- }-- if (metrics.ttfbMs === null) metrics.ttfbMs = Date.now() - startedAt;- metrics.totalMs = Date.now() - startedAt;- return metrics;-}--async function ensureStreamHealthTable(sql) {- try {- await sql`- CREATE TABLE IF NOT EXISTS mcp_stream_health (- id bigserial PRIMARY KEY,- ts timestamptz DEFAULT now(),- endpoint text NOT NULL,- tool text NOT NULL,- status_code int,- ttfb_ms int,- total_ms int,- chunk_count int,- total_bytes bigint,- max_gap_ms int,- stalled boolean NOT NULL DEFAULT false,- dropped boolean NOT NULL DEFAULT false,- settled boolean NOT NULL DEFAULT false,- healthy boolean NOT NULL,- tx_signature text,- error_msg text- )- `;- } catch { /* already exists or migration system handles it */ }-}--async function storeStreamHealth(sql, log, row) {- try {- await ensureStreamHealthTable(sql);- await sql`- INSERT INTO mcp_stream_health- (endpoint, tool, status_code, ttfb_ms, total_ms, chunk_count,- total_bytes, max_gap_ms, stalled, dropped, settled, healthy,- tx_signature, error_msg)- VALUES- (${row.endpoint}, ${row.tool}, ${row.status_code},- ${row.ttfb_ms}, ${row.total_ms}, ${row.chunk_count},- ${row.total_bytes}, ${row.max_gap_ms}, ${row.stalled},- ${row.dropped}, ${row.settled}, ${row.healthy},- ${row.tx_signature || null}, ${row.error_msg || null})- `;- } catch (err) {- // DB failure must never crash the loop — log and move on.- log?.warn?.('mcp_stream_health_insert_failed', { message: err?.message });- }-}--/**- * Custom-execution handler invoked by the autonomous loop for the- * `mcp-sse-stream-health` registry entry.- *- * @param {object} ctx — supplied by the loop:- * origin, endpointUrl, buyer (Keypair), conn, blockhash, mintInfo,- * usdcMint, remainingCap, fetchWithTimeout, parseSolanaAccept,- * buildPaymentTx, sql, log, redis- * @returns {Promise<object>} result the loop records to x402_autonomous_log- */-export async function runStreamingMcpHealth(ctx) {- const {- endpointUrl, buyer, conn, blockhash, mintInfo, usdcMint, remainingCap,- fetchWithTimeout, parseSolanaAccept, buildPaymentTx, sql, log,- } = ctx;-- const fail = (errorMsg, extra = {}) => ({- success: false, amountAtomic: 0, txSig: null,- responseData: null, signalData: { alive: false, error: errorMsg },- errorMsg, ...extra,- });-- // Wallet guard (defence in depth — the loop already pre-flights the keypair).- if (!buyer) return { ...fail('wallet_unconfigured'), cooldown: false };-- // ── Step 1: probe for the 402 challenge (plain x402 agent → real 402) ──────- let probe;- try {- probe = await fetchWithTimeout(endpointUrl, {- method: 'POST',- headers: {- 'content-type': 'application/json',- 'user-agent': 'threews-x402-autonomous/1.0',- },- body: JSON.stringify(buildToolCallBody()),- });- } catch (err) {- return { ...fail(`probe_failed:${err?.message || 'network'}`), cooldown: false };- }-- // 402 (plain agent) or 401 (the server's MCP/OAuth challenge) both carry the- // x402 envelope with `accepts` in the body. Anything else means the price- // gate isn't where we expect — record and skip.- if (probe.status !== 402 && probe.status !== 401) {- return fail(`unexpected_probe_status:${probe.status}`);- }- const accept = parseSolanaAccept(probe.body);- if (!accept) return fail('no_solana_accept');- if (!usdcMint || accept.asset !== usdcMint) return fail(`unexpected_asset:${accept.asset}`);- if (!accept.extra?.feePayer) return fail('missing_fee_payer');-- const amountAtomic = Number(accept.amount || 0);- if (!(amountAtomic > 0)) return fail('zero_price');- if (amountAtomic > remainingCap) {- // Honor the loop's daily cap — skip without paying, retry next tick.- return { ...fail('cap_would_exceed'), skipped: true, cooldown: false };- }-- // ── Step 2: build the signed payment tx ────────────────────────────────────- let xPayment;- try {- const receiverAta = getAssociatedTokenAddressSync(- new PublicKey(accept.asset), new PublicKey(accept.payTo),- false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,- );- const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);- const txBase64 = buildPaymentTx({- accept, buyer, blockhash, mintInfo,- receiverAtaExists: receiverAtaInfo !== null,- });- xPayment = Buffer.from(JSON.stringify({- x402Version: 2,- scheme: 'exact',- network: accept.network,- resource: { url: endpointUrl, mimeType: 'application/json' },- payload: { transaction: txBase64 },- accepted: accept,- })).toString('base64');- } catch (err) {- return { ...fail(`build_payment_failed:${err?.message || 'unknown'}`), cooldown: false };- }-- // ── Step 3: fire the paid call in SSE mode and read the response as a stream ─- const startedAt = Date.now();- const controller = new AbortController();- const overall = setTimeout(() => controller.abort(), STREAM_TIMEOUT_MS);- let metrics;- try {- const res = await fetch(endpointUrl, {- method: 'POST',- headers: {- 'content-type': 'application/json',- // Advertise SSE support — this is the "SSE mode" request. The server- // negotiates the response transport off Accept.- accept: 'text/event-stream, application/json',- 'user-agent': 'threews-x402-autonomous/1.0',- 'x-payment': xPayment,- },- body: JSON.stringify(buildToolCallBody()),- signal: controller.signal,- });- metrics = await readStream(res, { stallMs: STALL_MS, startedAt });- // Settlement is proven by the X-PAYMENT-RESPONSE header — the MCP server- // only broadcasts the payment after the tool produced a result.- const xpr = res.headers?.get?.('x-payment-response');- metrics.settled = !!xpr;- metrics.txSig = null;- if (xpr) {- try {- const settled = JSON.parse(Buffer.from(xpr, 'base64').toString('utf8'));- metrics.txSig = settled?.transaction || null;- } catch { /* header present but unparseable — still settled */ }- }- } catch (err) {- // Abort fires as an error here when the overall budget is exceeded before- // any headers arrive — treat as a dropped connection.- metrics = {- status: 0, ttfbMs: Date.now() - startedAt, totalMs: Date.now() - startedAt,- chunkCount: 0, totalBytes: 0, maxGapMs: 0, stalled: false,- dropped: true, raw: '', settled: false, txSig: null,- abortMsg: err?.message || 'request_failed',- };- } finally {- clearTimeout(overall);- }-- // ── Step 4: classify health and extract value ──────────────────────────────- const parsed = parseStreamPayload(metrics.raw);- const rpcError = parsed?.error?.message || null;- const toolError = parsed?.result?.isError === true;- const hasResult = !!parsed?.result && !toolError && !rpcError;- const streamClean = metrics.status === 200 && !metrics.stalled && !metrics.dropped && metrics.chunkCount > 0;- const healthy = streamClean && hasResult && metrics.settled;-- // Payment-rejected paths: a 402/401 on the *paid* request means the payment- // was not accepted; no settlement, so nothing was charged.- let errorMsg = null;- if (metrics.status === 402 || metrics.status === 401) errorMsg = `payment_rejected:${metrics.status}`;- else if (metrics.dropped) errorMsg = `stream_dropped${metrics.abortMsg ? `:${metrics.abortMsg}` : ''}`;- else if (metrics.stalled) errorMsg = 'stream_stalled';- else if (rpcError) errorMsg = `rpc_error:${rpcError}`;- else if (toolError) errorMsg = 'tool_error';- else if (!metrics.settled) errorMsg = 'not_settled';- else if (!hasResult) errorMsg = 'no_result';-- const signalData = {- alive: healthy,- tool: CANARY_TOOL,- status: metrics.status,- ttfb_ms: metrics.ttfbMs,- total_ms: metrics.totalMs,- chunk_count: metrics.chunkCount,- total_bytes: metrics.totalBytes,- max_gap_ms: metrics.maxGapMs,- stalled: metrics.stalled,- dropped: metrics.dropped,- settled: metrics.settled,- };-- // ── Step 5: persist the streaming-integrity metrics + alert on degradation ──- await storeStreamHealth(sql, log, {- endpoint: '/api/mcp',- tool: CANARY_TOOL,- status_code: metrics.status,- ttfb_ms: metrics.ttfbMs,- total_ms: metrics.totalMs,- chunk_count: metrics.chunkCount,- total_bytes: metrics.totalBytes,- max_gap_ms: metrics.maxGapMs,- stalled: metrics.stalled,- dropped: metrics.dropped,- settled: metrics.settled,- healthy,- tx_signature: metrics.txSig,- error_msg: errorMsg,- });-- if (metrics.stalled || metrics.dropped) {- // Fire-and-forget: alerting must never block or crash the loop.- sendOpsAlert(- 'MCP SSE stream degraded',- `POST /api/mcp (${CANARY_TOOL}) ${metrics.stalled ? 'STALLED' : 'DROPPED'} — ` +- `status ${metrics.status}, ttfb ${metrics.ttfbMs}ms, ${metrics.chunkCount} chunks, ` +- `${metrics.totalBytes}B, max gap ${metrics.maxGapMs}ms`,- { signature: `mcp-sse-stream:${metrics.stalled ? 'stalled' : 'dropped'}` },- ).catch(() => {});- }-- // `amountAtomic` reported to the loop reflects what was actually charged:- // only a settled payment moved USDC on-chain.- return {- success: healthy,- amountAtomic: metrics.settled ? amountAtomic : 0,- txSig: metrics.txSig,- responseData: parsed ?? (metrics.raw ? { raw: metrics.raw.slice(0, 2000) } : null),- signalData,- errorMsg,- };-}diff --git a/api/_lib/x402/three-signal-store.js b/api/_lib/x402/three-signal-store.jsnew file mode 100644index 000000000..c9aed08d1--- /dev/null+++ b/api/_lib/x402/three-signal-store.js@@ -0,0 +1,171 @@+// api/_lib/x402/three-signal-store.js+//+// Time-series store for the $THREE Signal Feed.+//+// The x402 autonomous loop pays /api/x402/three-intel every 15 minutes (registry+// entry `three-intel`) and appends the live $THREE market snapshot here. This+// table is the historical record behind two consumers:+//+// 1. The public $THREE price widget — GET /api/three-signal reads the latest+// point plus a short sparkline history from here (no payment needed to+// *display* a price the platform already paid to fetch).+// 2. $THREE-denominated x402 pricing — usdToThreeTokens() converts a USDC+// amount into $THREE token units using the latest stored price, so callers+// can quote any endpoint's fee in $THREE without re-fetching the market.+//+// Schema ownership lives here so the writer (registry storeValue) and the reader+// (the endpoint) can never disagree on shape. ensureThreeSignalSchema() mirrors+// the idempotent CREATE-IF-NOT-EXISTS idiom the autonomous loop uses elsewhere;+// the canonical DDL is also in api/_lib/migrations/20260627120000_three_market_signals.sql.++import { env } from '../env.js';++// $THREE mint + on-chain decimals (pump.fun mints are 6-decimal).+const THREE_MINT = env.THREE_TOKEN_MINT;+const THREE_DECIMALS = 6;++function num(v) {+ const n = typeof v === 'string' ? parseFloat(v) : v;+ return Number.isFinite(n) ? n : null;+}++/**+ * Normalize a /api/x402/three-intel response into the time-series row shape.+ * Shared by the registry's extractSignal (→ x402_autonomous_log.signal_data) and+ * storeValue (→ three_market_signals) so both always agree on the snapshot.+ *+ * @param {object|null} r raw three-intel JSON response+ * @returns {{+ * mint: string|null, symbol: string|null, price_usd: number|null,+ * change_24h: number|null, market_cap_usd: number|null, liquidity_usd: number|null,+ * volume_24h_usd: number|null, signal: string|null, headline: string|null,+ * confidence: number|null, ts: string|null+ * }}+ */+export function classifyThreeSignal(r) {+ const o = r || {};+ return {+ mint: o.mint || THREE_MINT || null,+ symbol: o.symbol || 'THREE',+ price_usd: num(o.price_usd),+ change_24h: num(o.change_24h),+ market_cap_usd: num(o.market_cap_usd),+ liquidity_usd: num(o.liquidity_usd),+ volume_24h_usd: num(o.volume_24h_usd),+ signal: typeof o.signal === 'string' ? o.signal : null,+ headline: typeof o.headline === 'string' ? o.headline : null,+ confidence: num(o.confidence),+ ts: typeof o.ts === 'string' ? o.ts : null,+ };+}++// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).+let _schemaReady = false;++/**+ * Create the time-series table if absent. Idempotent and safe to call on every+ * write; the in-process guard avoids re-issuing the DDL after the first call.+ * @param {Function} sql tagged-template sql client (from api/_lib/db.js)+ */+export async function ensureThreeSignalSchema(sql) {+ if (_schemaReady || !sql) return;+ await sql`+ CREATE TABLE IF NOT EXISTS three_market_signals (+ id bigserial PRIMARY KEY,+ ts timestamptz NOT NULL DEFAULT now(),+ mint text,+ symbol text,+ price_usd double precision,+ change_24h double precision,+ market_cap_usd double precision,+ liquidity_usd double precision,+ volume_24h_usd double precision,+ signal text,+ headline text,+ confidence double precision,+ run_id uuid,+ source text NOT NULL DEFAULT 'x402-autonomous'+ )+ `;+ await sql`+ CREATE INDEX IF NOT EXISTS three_market_signals_ts_desc+ ON three_market_signals (ts DESC)+ `;+ _schemaReady = true;+}++/**+ * Append one market snapshot to the time series.+ * @param {Function} sql+ * @param {object} v a classifyThreeSignal() result+ * @param {{ runId?: string, source?: string }} [meta]+ */+export async function insertThreeSignal(sql, v, meta = {}) {+ if (!sql || !v) return;+ await ensureThreeSignalSchema(sql);+ await sql`+ INSERT INTO three_market_signals+ (ts, mint, symbol, price_usd, change_24h, market_cap_usd,+ liquidity_usd, volume_24h_usd, signal, headline, confidence, run_id, source)+ VALUES+ (now(), ${v.mint}, ${v.symbol}, ${v.price_usd}, ${v.change_24h},+ ${v.market_cap_usd}, ${v.liquidity_usd}, ${v.volume_24h_usd},+ ${v.signal}, ${v.headline}, ${v.confidence},+ ${meta.runId || null}, ${meta.source || 'x402-autonomous'})+ `;+}++/**+ * Latest stored $THREE snapshot, or null when the series is empty.+ * @param {Function} sql+ */+export async function getLatestThreeSignal(sql) {+ if (!sql) return null;+ const rows = await sql`+ SELECT mint, symbol, price_usd, change_24h, market_cap_usd, liquidity_usd,+ volume_24h_usd, signal, headline, confidence, ts+ FROM three_market_signals+ ORDER BY ts DESC+ LIMIT 1+ `;+ return rows[0] || null;+}++/**+ * Recent snapshots oldest→newest for a sparkline. Capped at 500 points.+ * @param {Function} sql+ * @param {number} [limit=48] points to return (default ~12 h at 15 min spacing)+ */+export async function getThreeSignalHistory(sql, limit = 48) {+ if (!sql) return [];+ const n = Math.max(1, Math.min(500, Number(limit) || 48));+ const rows = await sql`+ SELECT ts, price_usd, change_24h, signal+ FROM three_market_signals+ ORDER BY ts DESC+ LIMIT ${n}+ `;+ return rows.reverse();+}++/**+ * Convert a USD amount into $THREE token units using a known price.+ * Pure — the caller supplies the latest price (from getLatestThreeSignal) so the+ * conversion is testable and never makes its own network/DB call.+ *+ * @param {number} usd amount in US dollars+ * @param {number|null} priceUsd latest $THREE price in USD+ * @returns {{ tokens: number, atomics: number }|null} null when price is unusable+ */+export function usdToThreeTokens(usd, priceUsd) {+ const amount = num(usd);+ const price = num(priceUsd);+ if (amount == null || price == null || price <= 0) return null;+ const tokens = amount / price;+ return {+ tokens,+ atomics: Math.round(tokens * 10 ** THREE_DECIMALS),+ };+}++export { THREE_MINT, THREE_DECIMALS };diff --git a/api/_lib/x402/thumbnail-regen.js b/api/_lib/x402/thumbnail-regen.jsindex 92ddd6477..462532fcb 100644--- a/api/_lib/x402/thumbnail-regen.js+++ b/api/_lib/x402/thumbnail-regen.js@@ -18,6 +18,15 @@// spend-loop bundle stays lean.import { sql } from '../db.js';+import { payX402 } from './pay.js';++// The x402 endpoint this pipeline pays to fetch the current model bytes.+export const THUMBNAIL_REGEN_ENDPOINT = '/api/x402/asset-download';++// Reference price for the use case ($0.005). The real charge is per-listing+// (paid_assets.price_atomics); the loop's daily cap + payX402's remainingCap+// guard bound actual spend. Kept for registry documentation/analytics.+export const THUMBNAIL_REGEN_PRICE_ATOMIC = 5_000;// A thumbnail is stale once it is this many days old (or never rendered, or the// underlying model bytes changed after the last render).@@ -200,3 +209,112 @@ export function thumbnailKeyFor(slug, runId) {const suffix = runId ? String(runId).slice(0, 8) : 'r';return `thumbnails/assets/${safeSlug}-${suffix}.png`;}++// run(ctx) — the autonomous-loop entry point (USE-015 Avatar Thumbnail+// Regeneration). Selects the stalest listing, pays asset-download for its+// current GLB with a real on-chain USDC payment, and queues a re-render. The+// loop records the returned outcome as one summary row in x402_autonomous_log.+//+// Returns the standard run() outcome:+// { success, skipped?, amountAtomic, txSig, network, responseData, signalData, errorMsg, note }+//+// Never throws — selection, payment, and enqueue faults all degrade into a+// recorded outcome so a single bad listing can't crash the tick.+export async function runThumbnailRegen(ctx = {}) {+ const { origin, buyer, conn, blockhash, mintInfo, remainingCap, log, runId } = ctx;++ // Wallet not configured / no Solana context → exit gracefully. The loop only+ // invokes run() after loading the seed keypair, but a standalone/manual call+ // (the documented test path) may not have one.+ if (!buyer || !conn || !blockhash || !mintInfo) {+ return { success: false, skipped: true, amountAtomic: 0, note: 'solana_context_unavailable', errorMsg: 'solana_context_unavailable' };+ }++ let asset;+ try {+ asset = await selectStaleAsset();+ } catch (err) {+ log?.warn?.('thumbnail_regen_select_failed', { run_id: runId, message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, note: 'select_error', errorMsg: `select_failed:${err?.message || 'unknown'}` };+ }++ if (!asset) {+ return { success: true, skipped: true, amountAtomic: 0, note: 'no_stale_assets' };+ }++ const base = origin || 'https://three.ws';+ const url = `${base}${THUMBNAIL_REGEN_ENDPOINT}?slug=${encodeURIComponent(asset.slug)}`;++ let r;+ try {+ r = await payX402({+ url, method: 'GET', body: null,+ buyer, conn, blockhash, mintInfo,+ remainingCap: remainingCap ?? Infinity,+ userAgent: 'threews-x402-thumbnail-regen/1.0',+ });+ } catch (err) {+ log?.warn?.('thumbnail_regen_pay_failed', { run_id: runId, slug: asset.slug, message: err?.message });+ return {+ success: false, amountAtomic: 0, txSig: null, network: 'solana:mainnet',+ responseData: { slug: asset.slug }, errorMsg: `pay_failed:${err?.message || 'unknown'}`,+ note: `pay_error slug=${asset.slug}`,+ };+ }++ const downloaded = !!(r.success && r.responseBody && r.responseBody.ok);++ // Queue the re-render only after we hold a valid download confirmation.+ let jobId = null;+ let enqueueErr = null;+ if (downloaded) {+ try {+ jobId = await enqueueRegenJob({+ asset, runId, txSig: r.txSig,+ amountAtomic: r.amountAtomic, responseBody: r.responseBody,+ });+ } catch (err) {+ enqueueErr = err?.message || 'enqueue_failed';+ log?.warn?.('thumbnail_regen_enqueue_failed', { run_id: runId, slug: asset.slug, message: enqueueErr });+ }+ }++ const signalData = {+ slug: asset.slug,+ asset_id: asset.id || null,+ avatar_id: asset.avatar_id || null,+ downloaded,+ job_id: jobId,+ size_bytes: r.responseBody?.sizeBytes ?? null,+ tx: r.txSig || null,+ };++ log?.info?.('thumbnail_regen_complete', {+ run_id: runId, slug: asset.slug, downloaded, job_id: jobId,+ tx: r.txSig, paid_usdc: (r.amountAtomic || 0) / 1e6,+ });++ return {+ success: downloaded && !enqueueErr,+ // Only count what actually moved on-chain so the loop's spend accounting+ // stays exact (free/guard-skipped responses contribute 0).+ amountAtomic: r.paid ? (r.amountAtomic || 0) : 0,+ txSig: r.txSig || null,+ network: 'solana:mainnet',+ // NB: the presigned downloadUrl is a short-lived R2 credential — never+ // persist it verbatim into the log; record a marker instead.+ responseData: {+ slug: asset.slug,+ title: asset.title,+ download_ok: downloaded,+ download_url: r.responseBody?.downloadUrl ? '[presigned]' : null,+ size_bytes: r.responseBody?.sizeBytes ?? null,+ job_id: jobId,+ },+ signalData,+ errorMsg: enqueueErr+ ? `enqueue_failed:${enqueueErr}`+ : (downloaded ? null : (r.errorMsg || `download_failed:status_${r.status || 0}`)),+ note: downloaded ? `queued regen slug=${asset.slug} job=${jobId ?? 'dup'}` : `download_failed slug=${asset.slug}`,+ };+}diff --git a/api/_lib/x402/wallet-balance-monitor.js b/api/_lib/x402/wallet-balance-monitor.jsnew file mode 100644index 000000000..9182c28a5--- /dev/null+++ b/api/_lib/x402/wallet-balance-monitor.js@@ -0,0 +1,270 @@+// api/_lib/x402/wallet-balance-monitor.js+//+// Agent Wallet Balance Monitor — autonomous pipeline (self).+//+// The autonomous spend loop pays for everything else from the platform seed+// wallet. If that wallet runs dry, every other autonomous call silently starts+// failing with insufficient-funds. This monitor is the early-warning system:+// once every 10 minutes it reads the wallet's live USDC + SOL balance, records+// a time-series sample, derives the spend rate since the previous sample, and+// raises a low-balance alert before the autonomous loop can be starved.+//+// Endpoint: GET /api/x402-pay?balance=1 — a FREE read (no 402, no payment). It+// returns { configured, address, sol, usdc } for the wallet backed by+// X402_AGENT_SOLANA_SECRET_BASE58 (the same secret loadSeedKeypair() falls back+// to), i.e. the wallet that funds the autonomous loop. Because the call is free,+// this pipeline moves no funds — amountAtomic is always 0.+//+// Wiring: declared as a run()-style entry in autonomous-registry.js+// (`agent-wallet-balance-monitor`). The per-tick loop+// (api/cron/x402-autonomous-loop.js) hands run() { origin, redis, sql, log,+// runId } and records the returned outcome as one row in x402_autonomous_log.+// Called standalone (manual test) it derives its own origin/sql and still works.+//+// Value extracted & where it lands:+// • agent_wallet_balance_log — one time-series row per run. Columns:+// usdc, sol → the live balances+// low_balance → alert flag (usdc < threshold)+// threshold_usdc → the alert threshold in force at sample time+// usdc_delta → usdc change vs the previous sample (− = spent)+// spend_rate_usdc_hr → derived burn rate (USDC/hour) since last sample+// • Redis x402:wallet-balance:latest — newest sample (configured, usdc, sol,+// low_balance, ts) for cheap dashboard reads without a DB round-trip.+// • Redis x402:wallet-balance:alert — present (with TTL) only while the wallet+// is below threshold, so a consumer can detect the alert state in one GET.+//+// Downstream consumer: api/ops/health.js reads the latest balance sample and+// folds a low / unconfigured wallet into the internal health verdict, so the+// status dashboard and on-call alerting surface "top up the agent wallet"+// before autonomous calls begin to fail. The time-series rows back the spend-+// rate trend an operator reads to decide how much to top up.++import { randomUUID } from 'node:crypto';++import { fetchWithTimeout } from './pay.js';+import { sql as defaultSql } from '../db.js';+import { env } from '../env.js';+import { logger } from '../usage.js';++const log = logger('x402-wallet-balance-monitor');++// Low-balance alert threshold (USDC). Default $5 — below this the autonomous+// loop's own daily cap ($5) can no longer be fully funded, so it's the natural+// "top up now" line. Override via env without a redeploy.+const ALERT_THRESHOLD_USDC = Number(env.X402_WALLET_BALANCE_ALERT_USDC || process.env.X402_WALLET_BALANCE_ALERT_USDC || 5);++const REDIS_LATEST_KEY = 'x402:wallet-balance:latest';+const REDIS_ALERT_KEY = 'x402:wallet-balance:alert';+// Alert key TTL: a little over two monitor cycles (10 min) so a missed run+// lets the flag lapse to "unknown" rather than latching a stale alert forever.+const ALERT_TTL_SECONDS = 25 * 60;++// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).+let _schemaReady = false;+async function ensureSchema(sql) {+ if (_schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS agent_wallet_balance_log (+ id bigserial PRIMARY KEY,+ ts timestamptz NOT NULL DEFAULT now(),+ run_id uuid,+ address text,+ configured boolean NOT NULL DEFAULT true,+ usdc numeric(20,6),+ sol numeric(20,9),+ low_balance boolean NOT NULL DEFAULT false,+ threshold_usdc numeric(20,6),+ usdc_delta numeric(20,6),+ spend_rate_usdc_hr numeric(20,6),+ source text+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS agent_wallet_balance_log_ts ON agent_wallet_balance_log (ts DESC)`;+ _schemaReady = true;+}++// Most-recent prior sample, for delta + spend-rate derivation. Returns null on+// first run or any DB hiccup (the monitor still records the current sample).+async function previousSample(sql) {+ try {+ const [row] = await sql`+ SELECT usdc, extract(epoch FROM ts) AS ts_epoch+ FROM agent_wallet_balance_log+ WHERE configured = true AND usdc IS NOT NULL+ ORDER BY ts DESC+ LIMIT 1+ `;+ if (!row) return null;+ return { usdc: Number(row.usdc), tsEpoch: Number(row.ts_epoch) };+ } catch (err) {+ if (!/does not exist/i.test(err?.message || '')) {+ log.warn('balance_prev_sample_failed', { message: err?.message });+ }+ return null;+ }+}++// Persist the alert/latest state to Redis for cheap, DB-free consumer reads.+async function writeRedisState(redis, sample) {+ if (!redis) return;+ try {+ await redis.set(REDIS_LATEST_KEY, JSON.stringify(sample), { ex: ALERT_TTL_SECONDS });+ if (sample.low_balance) {+ await redis.set(REDIS_ALERT_KEY, JSON.stringify({+ usdc: sample.usdc,+ threshold: sample.threshold_usdc,+ address: sample.address,+ ts: sample.ts,+ }), { ex: ALERT_TTL_SECONDS });+ } else {+ // Cleared — wallet is healthy again, drop any lingering alert flag.+ await redis.del(REDIS_ALERT_KEY);+ }+ } catch (err) {+ log.warn('balance_redis_write_failed', { message: err?.message });+ }+}++/**+ * Run the wallet balance monitor. Conforms to the run()-style registry contract.+ *+ * @param {object} ctx — supplied by the autonomous loop:+ * { origin, redis, sql, log, runId }. All optional for standalone/manual runs.+ * @returns the aggregate outcome the loop records to x402_autonomous_log:+ * { success, amountAtomic, txSig, responseData, signalData, errorMsg, note }+ */+export async function run(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const sql = ctx.sql || defaultSql;+ const redis = ctx.redis || null;+ const endpointUrl = `${origin}/api/x402-pay?balance=1`;++ // Schema first: without the sink there's no time-series to write.+ try {+ await ensureSchema(sql);+ } catch (err) {+ log.warn('balance_schema_failed', { message: err?.message });+ return { success: false, amountAtomic: 0, txSig: null, skipped: true, errorMsg: `schema_failed: ${err?.message}` };+ }++ // ── Read the live balance (free GET — no 402, no payment) ─────────────────+ let body;+ try {+ const res = await fetchWithTimeout(endpointUrl, {+ method: 'GET',+ headers: { 'user-agent': 'threews-x402-wallet-monitor/1.0' },+ });+ if (!res.ok) {+ const errorMsg = `balance_http_${res.status}`;+ log.warn('balance_read_non_ok', { status: res.status });+ return {+ success: false, amountAtomic: 0, txSig: null,+ responseData: { status: res.status }, errorMsg, note: errorMsg,+ };+ }+ body = res.body;+ } catch (err) {+ // Network failure / timeout — never crash the loop.+ const errorMsg = `balance_fetch_failed: ${err?.message || 'network'}`;+ log.warn('balance_fetch_failed', { message: err?.message });+ return { success: false, amountAtomic: 0, txSig: null, errorMsg, note: 'fetch_failed' };+ }++ const configured = body?.configured === true;+ const address = body?.address || null;+ const usdc = configured ? Number(body?.usdc ?? 0) : null;+ const sol = configured ? Number(body?.sol ?? 0) : null;+ const lowBalance = configured && Number.isFinite(usdc) && usdc < ALERT_THRESHOLD_USDC;++ // ── Derive spend rate vs the previous sample ──────────────────────────────+ let usdcDelta = null;+ let spendRateUsdcHr = null;+ if (configured && Number.isFinite(usdc)) {+ const prev = await previousSample(sql);+ if (prev && Number.isFinite(prev.usdc)) {+ usdcDelta = usdc - prev.usdc; // negative = spent since last sample+ const hours = (Date.now() / 1000 - prev.tsEpoch) / 3600;+ if (hours > 0) {+ // Positive burn rate = USDC leaving the wallet per hour.+ spendRateUsdcHr = -usdcDelta / hours;+ }+ }+ }++ // ── Persist the time-series sample ────────────────────────────────────────+ try {+ await sql`+ INSERT INTO agent_wallet_balance_log+ (ts, run_id, address, configured, usdc, sol,+ low_balance, threshold_usdc, usdc_delta, spend_rate_usdc_hr, source)+ VALUES+ (now(), ${runId}, ${address}, ${configured}, ${usdc}, ${sol},+ ${lowBalance}, ${ALERT_THRESHOLD_USDC}, ${usdcDelta}, ${spendRateUsdcHr}, ${endpointUrl})+ `;+ } catch (err) {+ // DB failure on the sink is logged but must not crash the loop; the call+ // itself succeeded, so report the read result with a recording note.+ log.warn('balance_insert_failed', { message: err?.message });+ }++ // ── Publish alert/latest state for cheap consumer reads ───────────────────+ const sample = {+ ts: new Date().toISOString(),+ address,+ configured,+ usdc,+ sol,+ low_balance: lowBalance,+ threshold_usdc: ALERT_THRESHOLD_USDC,+ usdc_delta: usdcDelta,+ spend_rate_usdc_hr: spendRateUsdcHr,+ };+ await writeRedisState(redis, sample);++ if (lowBalance) {+ log.warn('agent_wallet_low_balance', {+ run_id: runId, address, usdc, threshold: ALERT_THRESHOLD_USDC,+ spend_rate_usdc_hr: spendRateUsdcHr,+ });+ } else if (!configured) {+ log.info('agent_wallet_unconfigured', { run_id: runId });+ } else {+ log.info('agent_wallet_balance_ok', {+ run_id: runId, usdc, sol, spend_rate_usdc_hr: spendRateUsdcHr,+ });+ }++ const signalData = {+ configured,+ address,+ usdc,+ sol,+ low_balance: lowBalance,+ threshold_usdc: ALERT_THRESHOLD_USDC,+ usdc_delta: usdcDelta,+ spend_rate_usdc_hr: spendRateUsdcHr,+ };++ return {+ // success = we obtained a live, usable reading from a configured wallet.+ // An unconfigured wallet is a real, recorded state (not a crash) but not a+ // healthy reading — surface it as not-success so health can flag it.+ success: configured,+ amountAtomic: 0,+ txSig: null,+ responseData: { configured, address, usdc, sol },+ signalData,+ errorMsg: configured ? null : (body?.code || 'wallet_unconfigured'),+ note: configured+ ? `usdc=${usdc?.toFixed?.(4) ?? usdc} sol=${sol?.toFixed?.(4) ?? sol}${lowBalance ? ' LOW_BALANCE' : ''}`+ : 'wallet_unconfigured',+ };+}++export const WALLET_BALANCE = Object.freeze({+ endpoint: '/api/x402-pay?balance=1',+ alertThresholdUsdc: ALERT_THRESHOLD_USDC,+ redisLatestKey: REDIS_LATEST_KEY,+ redisAlertKey: REDIS_ALERT_KEY,+});diff --git a/api/cron/avatar-thumbnail-render.js b/api/cron/avatar-thumbnail-render.jsnew file mode 100644index 000000000..c181dbff0--- /dev/null+++ b/api/cron/avatar-thumbnail-render.js@@ -0,0 +1,126 @@+// GET /api/cron/avatar-thumbnail-render+//+// Downstream consumer of the Avatar Thumbnail Regeneration pipeline (USE-015).+//+// The autonomous x402 spend loop (api/cron/x402-autonomous-loop.js, entry+// `avatar-thumbnail-regen`) pays /api/x402/asset-download for the stalest+// marketplace listing and enqueues a job in avatar_thumbnail_regen_jobs. This+// cron drains that queue: for each claimed job it re-presigns the source GLB,+// renders it to a fresh PNG with the same headless-chromium pipeline used for+// OG cards, uploads the PNG to R2, and writes the new key back onto+// paid_assets.thumbnail_r2_key (+ thumbnail_generated_at) and the linked+// avatars row's thumbnail_key — so marketplace listings always show the model's+// current appearance.+//+// Kept separate from the spend loop on purpose: chromium boot is heavy and the+// loop's presigned downloadUrl is short-lived (60s), so the render must run on+// its own schedule against the durable r2_key, not the loop's expiring URL.+//+// Env:+// CRON_SECRET required Vercel cron auth (Bearer)+// THUMBNAIL_RENDER_BATCH max jobs per tick (default 3)+// THUMBNAIL_RENDER_BG background color or 'transparent' (default #0a0a0a)++import { json, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { logger } from '../_lib/usage.js';+import { presignGet, putObject, publicUrl } from '../_lib/r2.js';+import { renderGlbToPng } from '../_lib/render-glb.js';+import {+ ensureRegenSchema,+ claimRegenJobs,+ completeRegenJob,+ failRegenJob,+ thumbnailKeyFor,+} from '../_lib/x402/thumbnail-regen.js';++export const maxDuration = 120;++const log = logger('avatar-thumbnail-render');++const BATCH = Math.max(1, Number(process.env.THUMBNAIL_RENDER_BATCH || 3));+const BACKGROUND = (process.env.THUMBNAIL_RENDER_BG || '#0a0a0a').trim();+// Source GLB presign lifetime — long enough for chromium to fetch the bytes.+const SOURCE_TTL_SECONDS = 120;++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { json(res, 503, { error: 'CRON_SECRET unset' }); return false; }+ const auth = req.headers['authorization'] || '';+ const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(token, secret)) { json(res, 401, { error: 'unauthorized' }); return false; }+ return true;+}++async function renderOne(job) {+ const t0 = Date.now();+ // 1. Re-presign the durable source key (the loop's downloadUrl has expired).+ const glbUrl = await presignGet({ key: job.r2_key, expiresIn: SOURCE_TTL_SECONDS });++ // 2. Render the current model to a PNG.+ const png = await renderGlbToPng({+ glbUrl,+ width: job.width || 768,+ height: job.height || 768,+ background: BACKGROUND,+ });++ // 3. Upload the fresh thumbnail to R2.+ const thumbKey = thumbnailKeyFor(job.asset_slug, job.run_id);+ await putObject({ key: thumbKey, body: png, contentType: 'image/png' });++ // 4. Write it back onto the listing + linked avatar and close the job.+ await completeRegenJob(job, thumbKey);++ return { thumbKey, bytes: png.length, ms: Date.now() - t0 };+}++export default wrapCron(async (req, res) => {+ if (req.method !== 'GET') return json(res, 405, { error: 'method_not_allowed' });+ if (!requireCron(req, res)) return;++ // Schema must exist before we can claim — the loop also ensures it, but the+ // drainer can win the race on a fresh deploy.+ try {+ await ensureRegenSchema();+ } catch (err) {+ return json(res, 200, { ok: false, reason: `schema_unavailable: ${err?.message}` });+ }++ let jobs;+ try {+ jobs = await claimRegenJobs(BATCH);+ } catch (err) {+ return json(res, 200, { ok: false, reason: `claim_failed: ${err?.message}` });+ }++ if (!jobs.length) {+ return json(res, 200, { ok: true, claimed: 0, rendered: 0, failed: 0 });+ }++ const results = [];+ for (const job of jobs) {+ try {+ const r = await renderOne(job);+ results.push({ id: Number(job.id), slug: job.asset_slug, status: 'done', thumb: publicUrl(r.thumbKey), bytes: r.bytes, ms: r.ms });+ log.info('thumbnail_rendered', { job_id: Number(job.id), slug: job.asset_slug, bytes: r.bytes, ms: r.ms });+ } catch (err) {+ const msg = err?.message || 'render_failed';+ try { await failRegenJob(job, msg); } catch { /* logged below */ }+ results.push({ id: Number(job.id), slug: job.asset_slug, status: 'failed', error: msg, attempts: job.attempts });+ log.warn('thumbnail_render_failed', { job_id: Number(job.id), slug: job.asset_slug, attempts: job.attempts, message: msg });+ }+ }++ const rendered = results.filter((r) => r.status === 'done').length;+ const failed = results.filter((r) => r.status === 'failed').length;++ return json(res, 200, {+ ok: true,+ claimed: jobs.length,+ rendered,+ failed,+ results,+ });+});diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.jsindex 3bb6857db..30b1a58e0 100644--- a/api/cron/x402-autonomous-loop.js+++ b/api/cron/x402-autonomous-loop.js@@ -284,6 +284,7 @@ export default wrapCron(async (req, res) => {let endpointUrl = entry.url || `${origin}${entry.path}`;let targetUrl = null;+ let targetContext = null;const t0 = Date.now();let amountAtomic = 0;let txSig = null;@@ -339,20 +340,35 @@ export default wrapCron(async (req, res) => {// resolveTarget computes the per-call path and the resource URL being checked.if (typeof entry.resolveTarget === 'function') {try {- const resolved = await entry.resolveTarget({ redis, origin, runId });+ const resolved = await entry.resolveTarget({ redis, sql, origin, runId });if (resolved?.path) endpointUrl = entry.url || `${origin}${resolved.path}`;if (resolved?.targetUrl) targetUrl = resolved.targetUrl;+ if (resolved?.context) targetContext = resolved.context;} catch (err) {log.warn('resolve_target_failed', { id: entry.id, message: err?.message });}}+ // Resolve the request body. Most entries carry a static `body`. Pipeline+ // entries provide `body` as a function of the resolved target — e.g. the VRM+ // compatibility checker embeds the selected avatar's public GLB URL into an+ // MCP inspect_model tools/call. A function body that returns null means+ // "no target to process this tick": skip without probing or paying.+ const requestBody = typeof entry.body === 'function'+ ? entry.body({ targetUrl, targetContext, origin, endpointUrl })+ : entry.body;+ if (typeof entry.body === 'function' && requestBody == null) {+ results.push({ id: entry.id, status: 'skip', reason: 'no_target' });+ await setCooldown(redis, entry); // back off so we don't re-query every tick+ continue;+ }+try {// Step 1: probe for 402 challengeconst probeRes = await fetchWithTimeout(endpointUrl, {method: entry.method || 'POST',headers: { 'content-type': 'application/json', 'user-agent': 'threews-x402-autonomous/1.0' },- ...(entry.body != null ? { body: JSON.stringify(entry.body) } : {}),+ ...(requestBody != null ? { body: JSON.stringify(requestBody) } : {}),});if (probeRes.status !== 402) {@@ -363,7 +379,7 @@ export default wrapCron(async (req, res) => {results.push({ id: entry.id, status: 'free', success });await recordLog(runId, entry, { amountAtomic: 0, txSig: null, responseData: responseBody, durationMs: Date.now() - t0, success, signalData, endpointUrl });if (signalData) await upsertOracleSignal(entry, signalData);- await runStoreValue(entry, { sql, redis, responseBody, signalData, runId, targetUrl, endpointUrl });+ await runStoreValue(entry, { sql, redis, responseBody, signalData, runId, targetUrl, targetContext, endpointUrl, origin, durationMs: Date.now() - t0, success, amountAtomic, txSig });await setCooldown(redis, entry);continue;}@@ -422,7 +438,7 @@ export default wrapCron(async (req, res) => {'user-agent': 'threews-x402-autonomous/1.0','x-payment': xPayment,},- ...(entry.body != null ? { body: JSON.stringify(entry.body) } : {}),+ ...(requestBody != null ? { body: JSON.stringify(requestBody) } : {}),});responseBody = paidRes.body;@@ -443,7 +459,7 @@ export default wrapCron(async (req, res) => {if (entry.extractSignal) signalData = entry.extractSignal(responseBody);await setCooldown(redis, entry);if (signalData) await upsertOracleSignal(entry, signalData);- await runStoreValue(entry, { sql, redis, responseBody, signalData, runId, targetUrl, endpointUrl });+ await runStoreValue(entry, { sql, redis, responseBody, signalData, runId, targetUrl, targetContext, endpointUrl, origin, durationMs: Date.now() - t0, success, amountAtomic, txSig });} else {errorMsg = `http_${paidRes.status}`;}diff --git a/api/ops/health.js b/api/ops/health.jsindex 7d43c0b77..e686e7000 100644--- a/api/ops/health.js+++ b/api/ops/health.js@@ -9,6 +9,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { cacheGet } from '../_lib/cache.js';import { env } from '../_lib/env.js';import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';const PROBE_TIMEOUT_MS = 8_000;const ORIGIN = env.APP_ORIGIN || 'https://three.ws';@@ -142,6 +143,11 @@ export default wrap(async (req, res) => {}),);+ // Cross-network payment circuit breaker — latest per-network status written+ // hourly by the autonomous loop (api/_lib/x402/circuit-breaker.js). A tripped+ // route or failed Solana settlement means the payment stack is degraded.+ const circuitBreaker = await loadCircuitBreaker();+// Categorize probe resultsconst byCategory = {};for (const r of probeResults) {@@ -151,7 +157,11 @@ export default wrap(async (req, res) => {const allProbesOk = probeResults.every((r) => r.ok);const allCronsOk = heartbeats.every((h) => !h.stale && h.ok !== false);- const overallOk = allProbesOk && allCronsOk;+ // A missing breaker row (never run / table absent) is unknown, not failing —+ // don't fail health on a feature that hasn't booted. Only a present-and-degraded+ // breaker folds into the verdict.+ const breakerOk = circuitBreaker.ok !== false;+ const overallOk = allProbesOk && allCronsOk && breakerOk;const failingProbes = probeResults.filter((r) => !r.ok);const failingCrons = heartbeats.filter((h) => h.stale || h.ok === false);@@ -170,5 +180,62 @@ export default wrap(async (req, res) => {},probes: byCategory,crons: heartbeats,+ circuitBreaker,});});++// Read the latest per-network circuit-breaker snapshot. The hourly breaker+// upserts one row per network into x402_circuit_breaker; a row older than the+// staleness window means the loop stopped writing. Returns ok:null when the+// feature has never run (table absent / no rows) so health doesn't fail on it.+const BREAKER_STALE_AFTER_MS = 2 * 60 * 60 * 1000; // 2h (hourly cadence + slack)++async function loadCircuitBreaker() {+ try {+ const rows = await sql`+ SELECT network, label, scheme, advertised, route_ok, settled,+ receipt_valid, tx_signature, error,+ extract(epoch FROM checked_at) * 1000 AS checked_at_ms+ FROM x402_circuit_breaker+ ORDER BY label ASC+ `;+ if (!rows.length) return { ok: null, reason: 'no_data', networks: [] };+ const now = Date.now();+ const networks = rows.map((r) => {+ const checkedAt = r.checked_at_ms ? Number(r.checked_at_ms) : null;+ const stale = checkedAt === null || now - checkedAt > BREAKER_STALE_AFTER_MS;+ return {+ network: r.network,+ label: r.label,+ scheme: r.scheme,+ advertised: r.advertised,+ routeOk: r.route_ok,+ settled: r.settled,+ receiptValid: r.receipt_valid,+ txSignature: r.tx_signature,+ error: r.error,+ lastChecked: checkedAt,+ stale,+ };+ });+ const routesOk = networks.every((n) => n.routeOk && !n.stale);+ // Solana is the network we actually settle on; its settlement is the+ // end-to-end proof. Base/BSC are route-verify only.+ const solana = networks.find((n) => /solana/i.test(n.label) || /solana/i.test(n.network));+ const settlementOk = solana ? solana.settled && !solana.stale : false;+ const ok = routesOk && settlementOk;+ return {+ ok,+ routesOk,+ settlementOk,+ solanaTx: solana?.txSignature || null,+ networks,+ };+ } catch (err) {+ // Table not yet created (first boot before the loop runs) → unknown, not failing.+ if (/does not exist|relation .* does not exist/i.test(err?.message || '')) {+ return { ok: null, reason: 'table_absent', networks: [] };+ }+ return { ok: null, reason: `query_failed:${err?.message || 'unknown'}`, networks: [] };+ }+}diff --git a/api/x402/mcp-perf.js b/api/x402/mcp-perf.jsnew file mode 100644index 000000000..407b1740f--- /dev/null+++ b/api/x402/mcp-perf.js@@ -0,0 +1,48 @@+// GET /api/x402/mcp-perf — MCP Tool Latency Monitor SLA dashboard feed.+//+// Free operational read (parity with /api/x402-status): surfaces the live SLA+// health of the three.ws MCP server as measured by the `mcp-latency-monitor`+// autonomous-loop entry (api/_lib/x402/autonomous-registry.js). That loop pays a+// real x402 canary call to /api/mcp every 5 minutes and sweeps every advertised+// tool, writing rolling p50/p95/p99 latencies to x402_perf_log. This endpoint is+// the downstream consumer: it reads the latest percentile snapshot per tool and+// reports whether any tool breaches the p95 SLA.+//+// Query: ?window=<hours> (default 24, max 168) — the rolling window to report.++import { cors, json, method, wrap } from '../_lib/http.js';+import { readPerfHealth } from '../_lib/x402/mcp-latency-sweep.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ let windowHours = 24;+ try {+ const u = new URL(req.url, 'http://localhost');+ const w = Number(u.searchParams.get('window'));+ if (Number.isFinite(w) && w > 0) windowHours = Math.min(Math.max(w, 1), 168);+ } catch { /* default window */ }++ try {+ const health = await readPerfHealth({ windowHours });+ // 200 always — the dashboard renders the breach state itself; a non-2xx+ // here would be indistinguishable from the endpoint being down.+ return json(res, 200, { ...health, generated_at: new Date().toISOString() });+ } catch (err) {+ // Table absent (loop never ran) or DB hiccup — report empty-but-healthy so+ // the dashboard shows "no data yet" instead of an error void.+ const noData = /does not exist/i.test(err?.message || '');+ return json(res, noData ? 200 : 503, {+ ok: noData,+ healthy: true,+ tool_count: 0,+ breach_count: 0,+ breaches: [],+ tools: [],+ note: noData ? 'no_samples_yet' : undefined,+ error: noData ? undefined : 'perf_read_failed',+ generated_at: new Date().toISOString(),+ });+ }+});diff --git a/api/x402/solana-register-health.js b/api/x402/solana-register-health.jsindex f8d778ee5..5567cc9fb 100644--- a/api/x402/solana-register-health.js+++ b/api/x402/solana-register-health.js@@ -45,9 +45,9 @@ import { logger } from '../_lib/usage.js';import { explorerUrl } from '../_lib/onchain-deploy.js';const ROUTE = '/api/x402/solana-register-health';-const TOOL_NAME = 'solana_register';+export const TOOL_NAME = 'solana_register';// Consecutive failures before the canary escalates from a warn to an alert log.-const ALERT_THRESHOLD = 3;+export const ALERT_THRESHOLD = 3;const log = logger('x402-solana-register-health');@@ -153,7 +153,7 @@ async function resolveCanaryAgent() {}// Pull the registration coordinates out of an agent's meta for either network.-function readRegistration(meta) {+export function readRegistration(meta) {const m = meta || {};const mainnet = m.sol_mint_address? { network: 'mainnet', asset: m.sol_mint_address, registry: m.agent_registry || null }@@ -164,6 +164,17 @@ function readRegistration(meta) {return mainnet || devnet || { network: 'mainnet', asset: null, registry: null };}+// The canary is healthy only when the agent is enrolled in the registry AND both+// the Core asset and the Identity PDA accounts currently resolve on-chain. Pure+// so the verdict is unit-testable without a DB or RPC.+export function evaluateHealthy(checks) {+ return (+ checks?.registry_enrolled === true &&+ checks?.asset_onchain === true &&+ checks?.identity_pda_onchain === true+ );+}+// Confirm an account exists on-chain. Returns false on a malformed pubkey or any// RPC error — the canary treats "couldn't confirm" as unhealthy, not a crash.async function accountExists(conn, pubkey) {@@ -287,7 +298,7 @@ export default paidEndpoint({checks.identity_pda_onchain = pdaOk;// Healthy = enrolled in the registry AND both on-chain accounts resolve.- const healthy = checks.registry_enrolled && checks.asset_onchain && checks.identity_pda_onchain;+ const healthy = evaluateHealthy(checks);const detail = {source, network: reg.network, agent_id: agent.id, asset, identity_pda: identityPda, checks, rpc_latency_ms: rpcLatencyMs,diff --git a/data/changelog.json b/data/changelog.jsonindex 9d5745b7c..3080bb809 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-27",+ "title": "Reviews anchored on-chain — Solana attestations + ERC-8004 reputation",+ "summary": "Every agent and skill review is now permanently anchored on Solana via a platform-signed SPL-Memo attestation (threews.review.v1) the moment it's submitted. The review's rating and a SHA-256 hash of the text go on-chain — tamper-evident, publicly verifiable on Solscan. These attestations feed directly into the agent reputation score's on-chain identity pillar, so a well-reviewed agent earns higher trust points automatically. Users with MetaMask connected can also add a second, user-signed anchor on Base via the ERC-8004 ReputationRegistry for cross-chain provenance — a one-click \"Anchor on Base\" step appears after submitting a review. Both layers together make every review a real, verifiable act — not just a database row.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/marketplace"+ },{"date": "2026-06-27","title": "MCP Model Validation Sweep — proactive GLB quality scoring",diff --git a/scripts/test-glb-canonicalize.mjs b/scripts/test-glb-canonicalize.mjsnew file mode 100644index 000000000..2b5fe1645--- /dev/null+++ b/scripts/test-glb-canonicalize.mjs@@ -0,0 +1,135 @@+// Manual test for the GLB Canonicalization autonomous pipeline (USE-011).+//+// Exercises the value-extraction + storage logic of the 'glb-canonicalize'+// registry entry against REAL model bytes (a Mixamo-rigged avatar shipped in+// public/avatars), using the same glTF inspector the live /api/x402/model-check+// endpoint runs. No mocks — the only thing not exercised here is the on-chain+// USDC payment itself (that requires the seed wallet + Solana mainnet and is+// driven by the cron loop in production).+//+// node scripts/test-glb-canonicalize.mjs+//+// With DATABASE_URL set it additionally upserts into glb_canonicalization_results+// for real and reads the row back.++import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { randomUUID } from 'node:crypto';++import { inspectModel, suggestOptimizations } from '../src/gltf-inspect.js';+import {+ getSelfRegistry,+ classifyCanonicalization,+ RIG_REFERENCE_AVATARS,+} from '../api/_lib/x402/autonomous-registry.js';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++let failures = 0;+function check(label, cond, detail) {+ const ok = !!cond;+ if (!ok) failures++;+ console.log(`${ok ? ' ✓' : ' ✗'} ${label}${detail ? ` — ${detail}` : ''}`);+}++function getEntry() {+ const entry = getSelfRegistry().find((e) => e.id === 'glb-canonicalize');+ if (!entry) throw new Error('glb-canonicalize entry not found in registry');+ return entry;+}++// Build the exact response shape /api/x402/model-check returns, from real bytes.+async function modelCheckResponseFor(file) {+ const bytes = new Uint8Array(await readFile(join(ROOT, 'public', 'avatars', file)));+ const model = await inspectModel(bytes, { fileSize: bytes.byteLength });+ return {+ url: `https://three.ws/avatars/${file}`,+ fetchedBytes: bytes.byteLength,+ model,+ suggestions: suggestOptimizations(model),+ };+}++async function main() {+ const entry = getEntry();++ console.log('\n1. Registry entry shape');+ check('id', entry.id === 'glb-canonicalize');+ check('method GET', entry.method === 'GET');+ check('pipeline tag', entry.pipeline === 'canonicalize', entry.pipeline);+ check('cooldown 300s', entry.cooldown_s === 300);+ check('enabled', entry.enabled === true);+ check('has resolveTarget', typeof entry.resolveTarget === 'function');+ check('has extractSignal', typeof entry.extractSignal === 'function');+ check('has storeValue', typeof entry.storeValue === 'function');++ console.log('\n2. resolveTarget rotation (stub redis)');+ let counter = 0;+ const redis = { incr: async () => ++counter };+ const seen = [];+ for (let i = 0; i < RIG_REFERENCE_AVATARS.length + 2; i++) {+ const t = await entry.resolveTarget({ redis, origin: 'https://three.ws' });+ seen.push(t.targetUrl.split('/').pop());+ check(`call ${i} → ${seen[i]}`, t.path.includes('/api/x402/model-check?url=') && t.targetUrl.startsWith('https://three.ws/avatars/'));+ }+ check('rotates through full set', new Set(seen).size === RIG_REFERENCE_AVATARS.length, `${new Set(seen).size}/${RIG_REFERENCE_AVATARS.length} unique`);+ check('wraps around', seen[0] === seen[RIG_REFERENCE_AVATARS.length]);++ console.log('\n3. extractSignal on a real skinned (Mixamo) avatar');+ const resp = await modelCheckResponseFor('xbot.glb');+ const sig = entry.extractSignal(resp);+ console.log(' signal:', JSON.stringify(sig));+ check('model_url present', sig.model_url === resp.url);+ check('detected skin', sig.is_skinned === true, `skins=${sig.skins}`);+ check('rig_type skinned/vrm', sig.rig_type === 'skinned' || sig.rig_type === 'vrm', sig.rig_type);+ check('canonical_ready true for skinned rig', sig.canonical_ready === true);+ check('classify agrees with extractSignal', JSON.stringify(sig) === JSON.stringify(classifyCanonicalization(resp)));++ console.log('\n4. static (non-skinned) classification');+ const staticResp = { url: 'https://three.ws/avatars/none.glb', model: { container: 'glb', counts: { skins: 0, animations: 0, nodes: 3 } }, suggestions: [] };+ const staticSig = entry.extractSignal(staticResp);+ check('rig_type static', staticSig.rig_type === 'static', staticSig.rig_type);+ check('canonical_ready false', staticSig.canonical_ready === false);++ console.log('\n5. storeValue → glb_canonicalization_results (captured SQL)');+ const captured = [];+ const stubSql = (strings, ...vals) => {+ captured.push({ sql: strings.join('?').replace(/\s+/g, ' ').trim(), vals });+ return Promise.resolve([]);+ };+ await entry.storeValue({ sql: stubSql, responseBody: resp, signalData: sig, runId: randomUUID(), targetUrl: resp.url });+ const insert = captured.find((c) => /INSERT INTO glb_canonicalization_results/i.test(c.sql));+ check('issued CREATE TABLE IF NOT EXISTS', captured.some((c) => /CREATE TABLE IF NOT EXISTS glb_canonicalization_results/i.test(c.sql)));+ check('issued upsert INSERT', !!insert);+ check('upsert carries model_url', insert?.vals?.includes(resp.url));+ check('upsert carries rig_type', insert?.vals?.includes(sig.rig_type));++ console.log('\n6. error handling');+ let threw = false;+ try { await entry.storeValue({ sql: null, responseBody: resp, signalData: sig, runId: 'x', targetUrl: resp.url }); }+ catch { threw = true; }+ check('no-sql is a no-op (no throw)', threw === false);++ // Optional: real DB round-trip when DATABASE_URL is configured.+ if (process.env.DATABASE_URL || process.env.POSTGRES_URL) {+ console.log('\n7. real DB upsert + read-back');+ const { sql } = await import('../api/_lib/db.js');+ const runId = randomUUID();+ await entry.storeValue({ sql, responseBody: resp, signalData: sig, runId, targetUrl: resp.url });+ const rows = await sql`SELECT model_url, rig_type, is_skinned, canonical_ready, run_id FROM glb_canonicalization_results WHERE model_url = ${resp.url}`;+ check('row persisted', rows.length === 1, JSON.stringify(rows[0]));+ check('rig_type stored', rows[0]?.rig_type === sig.rig_type);+ check('run_id stored', rows[0]?.run_id === runId);+ } else {+ console.log('\n7. real DB round-trip skipped (no DATABASE_URL)');+ }++ console.log(`\n${failures === 0 ? 'PASS' : 'FAIL'} — ${failures} failed check(s)\n`);+ process.exit(failures === 0 ? 0 : 1);+}++main().catch((err) => {+ console.error('test crashed:', err);+ process.exit(1);+});diff --git a/scripts/test-mcp-latency-sweep.mjs b/scripts/test-mcp-latency-sweep.mjsnew file mode 100644index 000000000..b7c5b2c79--- /dev/null+++ b/scripts/test-mcp-latency-sweep.mjs@@ -0,0 +1,87 @@+// Manual test for the MCP Tool Latency Monitor sweep (USE-006).+//+// node scripts/test-mcp-latency-sweep.mjs+//+// Stands up a local server that emulates /api/mcp (tools/list + tools/call with+// a realistic mix of priced 402s, a free public tool, and a deliberately slow+// tool) and drives mcpLatencySweep() against it. Verifies the sweep enumerates+// every tool, assembles the canary + discovery + per-tool samples, computes+// p50/p95/p99, flags the SLA breach, and never throws — independent of whether a+// DATABASE_URL is configured (DB writes are best-effort and caught).++import http from 'node:http';+import { mcpLatencySweep, PERF_SLA_P95_MS } from '../api/_lib/x402/mcp-latency-sweep.js';++const TOOLS = [+ { name: 'getting_started', priced: false, status: 200, delay: 5 },+ { name: 'validate_model', priced: true, status: 402, delay: 8 },+ { name: 'render_avatar', priced: true, status: 402, delay: 8 },+ { name: 'pumpfun_token_intel', priced: false, status: 200, delay: 12 },+ { name: 'oracle_coin', priced: false, status: 401, delay: 6 },+ { name: 'slow_tool', priced: false, status: 200, delay: PERF_SLA_P95_MS + 400 }, // forces a breach+];++function startMockMcp() {+ return new Promise((resolve) => {+ const server = http.createServer((req, res) => {+ let raw = '';+ req.on('data', (c) => (raw += c));+ req.on('end', () => {+ let msg = {};+ try { msg = JSON.parse(raw); } catch { /* ignore */ }+ if (msg.method === 'tools/list') {+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({+ jsonrpc: '2.0', id: msg.id,+ result: { tools: TOOLS.map((t) => ({ name: t.name, ...(t.priced ? { pricing: { amount_usdc: 0.005 } } : {}) })) },+ }));+ return;+ }+ if (msg.method === 'tools/call') {+ const tool = TOOLS.find((t) => t.name === msg.params?.name);+ const delay = tool?.delay ?? 5;+ setTimeout(() => {+ res.statusCode = tool?.status ?? 200;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: { ok: true } }));+ }, delay);+ return;+ }+ res.statusCode = 400;+ res.end('{}');+ });+ });+ server.listen(0, '127.0.0.1', () => resolve(server));+ });+}++function assert(cond, label) {+ if (!cond) { console.error(` ✗ ${label}`); process.exitCode = 1; }+ else console.log(` ✓ ${label}`);+}++const server = await startMockMcp();+const { port } = server.address();+const origin = `http://127.0.0.1:${port}`;+console.log(`mock /api/mcp on ${origin}\n`);++const summary = await mcpLatencySweep({+ runId: '00000000-0000-4000-8000-000000000006',+ origin,+ durationMs: 1234, // simulated canary paid round-trip+ success: true,+});++console.log('sweep summary:', JSON.stringify(summary), '\n');++// Expected samples: 1 canary paid + 1 tools/list + N per-tool probes.+const expectedSamples = TOOLS.length + 2;+assert(summary.skipped === undefined, 'sweep did not skip');+assert(summary.tools === TOOLS.length, `enumerated all ${TOOLS.length} tools`);+assert(summary.samples === expectedSamples, `assembled ${expectedSamples} samples (canary + list + ${TOOLS.length} tools)`);+assert(summary.breaches >= 1, 'detected the slow_tool SLA breach (p95 > 2s)');+assert(summary.alerted === true, 'raised an SLA alert');+console.log(`\n (note: inserted=${summary.inserted} — 0 is expected without DATABASE_URL; DB writes are best-effort)`);++server.close();+console.log(process.exitCode ? '\nFAIL' : '\nPASS');diff --git a/src/agent-detail.js b/src/agent-detail.jsindex fd7062cdf..d165c92f3 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -1501,6 +1501,104 @@ async function loadReviews(agentId, agentRec) {body.appendChild(list);}+/**+ * Show an inline "Anchor on Base?" prompt in the review form actions area.+ * The user can sign the review with MetaMask for an ERC-8004 on-chain record, or skip.+ * Resolves when the user makes a choice (either way).+ */+async function offerErc8004Anchor({ erc8004, rating, reviewId, statusEl, actions }) {+ return new Promise((resolve) => {+ // Replace the save button row with anchor / skip options.+ const prev = Array.from(actions.children);+ prev.forEach((c) => c.remove());++ statusEl.textContent = '';++ const anchorBtn = el('button', {+ class: 'ad-review-submit',+ type: 'button',+ text: 'Anchor on Base',+ style: 'font-size:0.85em',+ });+ const skipLink = el('button', {+ class: 'ad-review-delete',+ type: 'button',+ text: 'Skip',+ style: 'font-size:0.85em',+ });++ const hint = el('span', {+ class: 'ad-review-char-count',+ style: 'color:var(--ad-muted);font-size:0.8em',+ text: 'Immutable on-chain record via MetaMask',+ });++ actions.appendChild(hint);+ actions.appendChild(skipLink);+ actions.appendChild(anchorBtn);++ skipLink.addEventListener('click', () => resolve());++ anchorBtn.addEventListener('click', async () => {+ anchorBtn.disabled = true;+ skipLink.disabled = true;+ anchorBtn.textContent = 'Connecting…';+ statusEl.textContent = '';++ try {+ const [{ BrowserProvider }, { submitFeedback }, { REGISTRY_DEPLOYMENTS }] = await Promise.all([+ import('ethers'),+ import('./erc8004/reputation.js'),+ import('./erc8004/abi.js'),+ ]);++ const chainId = erc8004.chain_id ? Number(erc8004.chain_id) : 8453; // default to Base+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment?.reputationRegistry) {+ statusEl.textContent = 'Registry not deployed on this chain';+ statusEl.style.color = '#ff8a80';+ resolve();+ return;+ }++ // Switch MetaMask to the correct network before requesting signature.+ try {+ await window.ethereum.request({+ method: 'wallet_switchEthereumChain',+ params: [{ chainId: `0x${chainId.toString(16)}` }],+ });+ } catch {+ // Non-fatal — the provider may already be on the right chain.+ }++ anchorBtn.textContent = 'Sign in wallet…';+ const provider = new BrowserProvider(window.ethereum);+ const signer = await provider.getSigner();++ const txHash = await submitFeedback({+ agentId: BigInt(erc8004.agent_id),+ score: rating,+ comment: reviewId ? `threews:review:${reviewId}` : '',+ signer,+ chainId,+ });++ statusEl.innerHTML = `Anchored on-chain — <a href="https://basescan.org/tx/${txHash}" target="_blank" rel="noopener" style="color:var(--ad-violet)">view tx</a>`;+ statusEl.style.color = 'var(--ad-muted)';+ } catch (err) {+ if (err?.code === 4001 || err?.code === 'ACTION_REJECTED') {+ statusEl.textContent = 'Signature declined';+ } else {+ statusEl.textContent = err?.shortMessage || err?.message || 'Anchor failed';+ }+ statusEl.style.color = '#ff8a80';+ }++ resolve();+ });+ });+}+function buildReviewForm(agentId, existing, onSuccess) {let selectedRating = existing?.rating || 0;let submitting = false;@@ -1619,6 +1717,23 @@ function buildReviewForm(agentId, existing, onSuccess) {submitting = false;return;}++ submitBtn.textContent = 'Saved!';++ // If the agent has an ERC-8004 on-chain identity and the browser has an+ // injected wallet, offer a user-signed anchor on Base for stronger+ // provenance. The platform already anchored on Solana server-side.+ const erc8004 = json.data?.erc8004;+ if (erc8004?.agent_id && typeof window !== 'undefined' && window.ethereum) {+ await offerErc8004Anchor({+ erc8004,+ rating: selectedRating,+ reviewId: json.data.review?.id,+ statusEl,+ actions,+ });+ }+onSuccess(json.data);} catch (e) {statusEl.textContent = 'Network error';diff --git a/src/gltf-inspect.js b/src/gltf-inspect.jsindex 589f52aed..7d40baad4 100644--- a/src/gltf-inspect.js+++ b/src/gltf-inspect.js@@ -54,6 +54,12 @@ export async function inspectModel(bytes, opts = {}) {let nonIndexedPrimitives = 0;const primitiveModes = new Set();+ // Bone count = total skin joints across every skin. The honest measure of rig+ // weight (skins.length only says "is it rigged"), consumed by the rig+ // complexity scorer to tier marketplace pricing and flag heavy avatars.+ let totalJoints = 0;+ for (const skin of skins) totalJoints += skin.listJoints().length;+for (const mesh of meshes) {for (const prim of mesh.listPrimitives()) {const pos = prim.getAttribute('POSITION');@@ -111,6 +117,7 @@ export async function inspectModel(bytes, opts = {}) {textures: textures.length,animations: animations.length,skins: skins.length,+ totalJoints,totalVertices,totalTriangles,indexedPrimitives,diff --git a/tests/api/x402-scene-capture-processor.test.js b/tests/api/x402-scene-capture-processor.test.jsnew file mode 100644index 000000000..42c72fe1f--- /dev/null+++ b/tests/api/x402-scene-capture-processor.test.js@@ -0,0 +1,180 @@+// Scene Capture Video Queue Processor — autonomous pipeline branch coverage.+//+// Exercises runSceneCaptureProcessor() in isolation: the DB queue, the GPU+// provider, and the x402 payment client are all stubbed so no network / no chain+// is touched. We assert the full state machine:+// • GPU worker unconfigured → graceful skip, no payment+// • empty queue → idle ok, no payment+// • pending row → pay $0.01 then submit, row → processing+// • payment rejected (402 / cap) → no submit, row released, success=false+// • processing row, worker done → store .ply result, row → done, no payment+// • processing row, worker running → touch + wait, no payment++import { describe, it, expect, vi, beforeEach } from 'vitest';++// ── Mocks ────────────────────────────────────────────────────────────────────+// Mutable fixture the sql stub reads. Each test resets it.+const db = { processing: [], pending: [] };+const sqlLog = [];++function sqlText(strings) {+ return strings.join(' ? ').replace(/\s+/g, ' ').trim();+}++const sql = vi.fn((strings, ..._vals) => {+ const text = sqlText(strings);+ sqlLog.push(text);+ if (/^SELECT \* FROM scene_capture_queue WHERE status = 'processing'/.test(text)) {+ return Promise.resolve(db.processing);+ }+ if (/UPDATE scene_capture_queue SET status = 'submitting'/.test(text)) {+ return Promise.resolve(db.pending);+ }+ // CREATE TABLE / CREATE INDEX / INSERT INTO paid_assets / UPDATE …+ return Promise.resolve([]);+});++const provider = {+ supportsMode: vi.fn(() => true),+ submit: vi.fn(),+ status: vi.fn(),+};+let providerThrows = false;++const payX402 = vi.fn();++vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sql(...a) }));+vi.mock('../../api/_lib/ssrf.js', () => ({+ assertPublicHttpsUrl: vi.fn(async (u) => u),+ SsrfError: class SsrfError extends Error {},+}));+vi.mock('../../api/_providers/gcp.js', () => ({+ createRegenProvider: () => {+ if (providerThrows) throw new Error('GCP_RECONSTRUCTION_KEY env var is required');+ return provider;+ },+}));+vi.mock('../../api/_lib/x402/pay.js', () => ({+ payX402: (...a) => payX402(...a),+ bootstrapSolanaContext: vi.fn(async () => ({ buyer: {}, conn: {}, blockhash: 'bh', mintInfo: { decimals: 6 } })),+}));++const { runSceneCaptureProcessor } = await import('../../api/_lib/x402/scene-capture-processor.js');++// A full payment context so the processor never needs to bootstrap.+const CTX = {+ origin: 'https://three.ws',+ buyer: { publicKey: { toBase58: () => 'Buyer11111' } },+ conn: {}, blockhash: 'bh', mintInfo: { decimals: 6 },+ remainingCap: 5_000_000,+};++beforeEach(() => {+ db.processing = [];+ db.pending = [];+ sqlLog.length = 0;+ providerThrows = false;+ sql.mockClear();+ provider.supportsMode.mockReturnValue(true);+ provider.submit.mockReset();+ provider.status.mockReset();+ payX402.mockReset();+});++describe('runSceneCaptureProcessor', () => {+ it('skips gracefully when the GPU worker is unconfigured (no payment)', async () => {+ providerThrows = true;+ const out = await runSceneCaptureProcessor(CTX);+ expect(out.success).toBe(true);+ expect(out.skipped).toBe(true);+ expect(out.note).toBe('video2scene_unconfigured');+ expect(out.amountAtomic).toBe(0);+ expect(payX402).not.toHaveBeenCalled();+ });++ it('is an idle ok-tick when the queue is empty', async () => {+ const out = await runSceneCaptureProcessor(CTX);+ expect(out.success).toBe(true);+ expect(out.note).toBe('queue_empty');+ expect(out.amountAtomic).toBe(0);+ expect(payX402).not.toHaveBeenCalled();+ expect(provider.submit).not.toHaveBeenCalled();+ });++ it('pays $0.01 then submits a pending video to the worker', async () => {+ db.pending = [{ id: 7, video_url: 'https://cdn.example/clip.mp4', params: { fps: 8 }, attempts: 1 }];+ payX402.mockResolvedValue({ success: true, paid: true, amountAtomic: 10_000, txSig: 'TXSIG123', responseBody: { ok: true } });+ provider.submit.mockResolvedValue({ extJobId: 'JOB_ABC', eta: 60 });++ const out = await runSceneCaptureProcessor(CTX);++ // Real x402 payment against the metering credit endpoint, GET.+ expect(payX402).toHaveBeenCalledTimes(1);+ const payArg = payX402.mock.calls[0][0];+ expect(payArg.method).toBe('GET');+ expect(payArg.url).toContain('/api/x402/asset-download?slug=video2scene-processing-credit');+ expect(payArg.remainingCap).toBe(5_000_000);++ // Submitted to the GPU worker with the video2scene mode.+ expect(provider.submit).toHaveBeenCalledWith(+ expect.objectContaining({ mode: 'video2scene', sourceUrl: 'https://cdn.example/clip.mp4' }),+ );++ // Outcome carries the real payment for the loop to record + meter.+ expect(out.success).toBe(true);+ expect(out.amountAtomic).toBe(10_000);+ expect(out.txSig).toBe('TXSIG123');+ expect(out.note).toBe('submitted');+ expect(out.signalData).toMatchObject({ action: 'submit', queue_id: 7, state: 'processing', job_id: 'JOB_ABC' });++ // Row advanced to processing with job + tx persisted.+ expect(sqlLog.some((t) => /UPDATE scene_capture_queue SET status = 'processing', job_id/.test(t))).toBe(true);+ });++ it('does not submit when the x402 payment is rejected', async () => {+ db.pending = [{ id: 8, video_url: 'https://cdn.example/clip.mp4', params: {}, attempts: 1 }];+ payX402.mockResolvedValue({ success: false, skipped: true, amountAtomic: 10_000, txSig: null, errorMsg: 'http_402' });++ const out = await runSceneCaptureProcessor(CTX);++ expect(provider.submit).not.toHaveBeenCalled();+ expect(out.success).toBe(false);+ expect(out.note).toBe('payment_failed');+ expect(out.errorMsg).toBe('http_402');+ });++ it('stores the finished .ply result when a processing job completes', async () => {+ db.processing = [{ id: 5, job_id: 'JOB_ABC', status: 'processing' }];+ provider.status.mockResolvedValue({+ status: 'done',+ resultPointCloudUrl: 'https://r2.example/scene-5.ply',+ numPoints: 1_250_000,+ frames: 240,+ });++ const out = await runSceneCaptureProcessor(CTX);++ expect(payX402).not.toHaveBeenCalled(); // polls are free+ expect(out.success).toBe(true);+ expect(out.amountAtomic).toBe(0);+ expect(out.note).toBe('completed');+ expect(out.signalData).toMatchObject({+ action: 'poll', queue_id: 5, state: 'done',+ result_url: 'https://r2.example/scene-5.ply', num_points: 1_250_000,+ });+ expect(sqlLog.some((t) => /UPDATE scene_capture_queue SET status = 'done', result_url/.test(t))).toBe(true);+ });++ it('waits without paying while a job is still running', async () => {+ db.processing = [{ id: 6, job_id: 'JOB_XYZ', status: 'processing' }];+ provider.status.mockResolvedValue({ status: 'running' });++ const out = await runSceneCaptureProcessor(CTX);++ expect(payX402).not.toHaveBeenCalled();+ expect(out.success).toBe(true);+ expect(out.amountAtomic).toBe(0);+ expect(out.note).toBe('still_processing');+ expect(out.signalData).toMatchObject({ action: 'poll', queue_id: 6, state: 'running' });+ });+});diff --git a/tests/gltf-inspect-joints.test.js b/tests/gltf-inspect-joints.test.jsnew file mode 100644index 000000000..066299ecc--- /dev/null+++ b/tests/gltf-inspect-joints.test.js@@ -0,0 +1,31 @@+import { describe, it, expect } from 'vitest';+import { readFileSync, existsSync } from 'node:fs';+import { resolve } from 'node:path';+import { inspectModel } from '../src/gltf-inspect.js';++const avatar = (name) => resolve(process.cwd(), 'public/avatars', name);++// inspectModel powers /api/mcp (inspect_model), the endpoint the Rig Complexity+// Scorer pays to call. It must report counts.totalJoints (the avatar's bone+// count) — the scorer tiers marketplace pricing on it, so a regression to 0+// would silently mis-price every rig as bone-free.+const RIGGED = ['cesium-man.glb', 'fox.glb'];+const STATIC = ['mannequin.glb'];++describe('inspectModel counts.totalJoints (bone count)', () => {+ for (const name of RIGGED) {+ it.runIf(existsSync(avatar(name)))(`reports a positive bone count — ${name}`, async () => {+ const info = await inspectModel(new Uint8Array(readFileSync(avatar(name))));+ expect(info.counts.skins).toBeGreaterThan(0);+ expect(info.counts.totalJoints).toBeGreaterThan(0);+ });+ }++ for (const name of STATIC) {+ it.runIf(existsSync(avatar(name)))(`reports zero bones for a skin-less mesh — ${name}`, async () => {+ const info = await inspectModel(new Uint8Array(readFileSync(avatar(name))));+ expect(info.counts.skins).toBe(0);+ expect(info.counts.totalJoints).toBe(0);+ });+ }+});diff --git a/tests/x402-bazaar-warmup.test.js b/tests/x402-bazaar-warmup.test.jsnew file mode 100644index 000000000..d690a8d04--- /dev/null+++ b/tests/x402-bazaar-warmup.test.js@@ -0,0 +1,114 @@+import { describe, it, expect } from 'vitest';++import {+ WARMUP_CATEGORIES,+ isLivePricedService,+ serviceKey,+ catalogHash,+ extractServices,+ run,+} from '../api/_lib/x402/pipelines/bazaar-warmup.js';+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';++const svc = (over = {}) => ({+ resource: 'https://api.example.com/weather',+ price_atomic: 1000,+ networks: ['eip155:8453'],+ ...over,+});++describe('bazaar warmup — service validation (live + priced)', () => {+ it('accepts a service with a resource, price, and network', () => {+ expect(isLivePricedService(svc())).toBe(true);+ });++ it('accepts a price label when atomic price is absent', () => {+ expect(isLivePricedService(svc({ price_atomic: undefined, price: '$0.01' }))).toBe(true);+ });++ it('rejects a listing with no resource URL', () => {+ expect(isLivePricedService(svc({ resource: '' }))).toBe(false);+ expect(isLivePricedService(svc({ resource: undefined }))).toBe(false);+ });++ it('rejects a listing with no price', () => {+ expect(isLivePricedService(svc({ price_atomic: undefined, price: undefined }))).toBe(false);+ });++ it('rejects a listing with no network', () => {+ expect(isLivePricedService(svc({ networks: [] }))).toBe(false);+ expect(isLivePricedService(svc({ networks: undefined }))).toBe(false);+ });++ it('rejects null/garbage', () => {+ expect(isLivePricedService(null)).toBe(false);+ expect(isLivePricedService({})).toBe(false);+ });+});++describe('bazaar warmup — drift detection', () => {+ it('keys a service by resource, plus tool name for MCP tools', () => {+ expect(serviceKey(svc())).toBe('https://api.example.com/weather');+ expect(serviceKey(svc({ tool_name: 'forecast' }))).toBe('https://api.example.com/weather#forecast');+ });++ it('hash is stable regardless of service order', () => {+ const a = catalogHash([svc({ resource: 'a' }), svc({ resource: 'b' })]);+ const b = catalogHash([svc({ resource: 'b' }), svc({ resource: 'a' })]);+ expect(a).toBe(b);+ });++ it('hash changes when a service is added or removed', () => {+ const before = catalogHash([svc({ resource: 'a' })]);+ const after = catalogHash([svc({ resource: 'a' }), svc({ resource: 'b' })]);+ expect(before).not.toBe(after);+ });++ it('hash changes on a reprice (so a reprice registers as drift)', () => {+ const before = catalogHash([svc({ resource: 'a', price_atomic: 1000 })]);+ const after = catalogHash([svc({ resource: 'a', price_atomic: 2000 })]);+ expect(before).not.toBe(after);+ });+});++describe('bazaar warmup — JSON-RPC response parsing', () => {+ it('extracts services from a tools/call structuredContent body', () => {+ const body = { result: { structuredContent: { services: [svc(), svc()], sources: ['x402'], errors: [] } } };+ const out = extractServices(body);+ expect(out.services).toHaveLength(2);+ expect(out.hasResult).toBe(true);+ expect(out.sources).toEqual(['x402']);+ });++ it('returns an empty catalog (not throw) on a malformed/error body', () => {+ expect(extractServices(null).services).toEqual([]);+ expect(extractServices({ error: { code: -32000 } }).services).toEqual([]);+ expect(extractServices({ result: {} }).hasResult).toBe(true);+ });+});++describe('bazaar warmup — registry wiring', () => {+ it('sweeps exactly 15 categories', () => {+ expect(WARMUP_CATEGORIES).toHaveLength(15);+ expect(new Set(WARMUP_CATEGORIES).size).toBe(15); // no duplicates+ });++ it('is registered as an enabled, daily, run()-style discovery entry', () => {+ const entry = getFullRegistry().find((e) => e.id === 'bazaar-discovery-warmup');+ expect(entry).toBeTruthy();+ expect(entry.enabled).toBe(true);+ expect(entry.pipeline).toBe('discovery');+ expect(entry.cooldown_s).toBe(86400);+ expect(typeof entry.run).toBe('function');+ expect(entry.path).toBe('/api/mcp-bazaar');+ });+});++describe('bazaar warmup — graceful degradation', () => {+ it('never throws when the DB/wallet are unconfigured; returns a skipped outcome', async () => {+ const out = await run({ runId: '00000000-0000-0000-0000-000000000008' });+ expect(out).toMatchObject({ success: false, skipped: true });+ expect(out.amountAtomic).toBe(0);+ expect(typeof out.errorMsg).toBe('string');+ });+});diff --git a/tests/x402-solana-register-health.test.js b/tests/x402-solana-register-health.test.jsnew file mode 100644index 000000000..559e1ae8e--- /dev/null+++ b/tests/x402-solana-register-health.test.js@@ -0,0 +1,119 @@+import { describe, it, expect } from 'vitest';++import {+ TOOL_NAME,+ ALERT_THRESHOLD,+ readRegistration,+ evaluateHealthy,+} from '../api/x402/solana-register-health.js';+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';++describe('solana-register-health — registration coordinate extraction', () => {+ it('reads a mainnet enrolment off meta', () => {+ const reg = readRegistration({+ sol_mint_address: 'AssetMain111',+ agent_registry: { identity_pda: 'PdaMain111', registration_uri: 'https://three.ws/r.json' },+ });+ expect(reg.network).toBe('mainnet');+ expect(reg.asset).toBe('AssetMain111');+ expect(reg.registry.identity_pda).toBe('PdaMain111');+ });++ it('falls back to devnet when no mainnet asset is present', () => {+ const reg = readRegistration({+ devnet: { sol_mint_address: 'AssetDev111', agent_registry: { identity_pda: 'PdaDev111' } },+ });+ expect(reg.network).toBe('devnet');+ expect(reg.asset).toBe('AssetDev111');+ expect(reg.registry.identity_pda).toBe('PdaDev111');+ });++ it('returns an unregistered shape for empty/missing meta (never throws)', () => {+ for (const meta of [null, undefined, {}, { foo: 'bar' }]) {+ const reg = readRegistration(meta);+ expect(reg.network).toBe('mainnet');+ expect(reg.asset).toBeNull();+ expect(reg.registry).toBeNull();+ }+ });++ it('prefers mainnet over devnet when both exist', () => {+ const reg = readRegistration({+ sol_mint_address: 'AssetMain111',+ agent_registry: { identity_pda: 'PdaMain111' },+ devnet: { sol_mint_address: 'AssetDev111', agent_registry: { identity_pda: 'PdaDev111' } },+ });+ expect(reg.network).toBe('mainnet');+ expect(reg.asset).toBe('AssetMain111');+ });+});++describe('solana-register-health — health verdict', () => {+ it('is healthy only when enrolled AND both accounts resolve on-chain', () => {+ expect(evaluateHealthy({ registry_enrolled: true, asset_onchain: true, identity_pda_onchain: true })).toBe(true);+ });++ it('is unhealthy when any single check fails', () => {+ expect(evaluateHealthy({ registry_enrolled: false, asset_onchain: true, identity_pda_onchain: true })).toBe(false);+ expect(evaluateHealthy({ registry_enrolled: true, asset_onchain: false, identity_pda_onchain: true })).toBe(false);+ expect(evaluateHealthy({ registry_enrolled: true, asset_onchain: true, identity_pda_onchain: false })).toBe(false);+ });++ it('is unhealthy on a missing/garbage checks object (never throws)', () => {+ expect(evaluateHealthy(undefined)).toBe(false);+ expect(evaluateHealthy({})).toBe(false);+ expect(evaluateHealthy(null)).toBe(false);+ });++ it('exposes a sane alert threshold and canonical tool name', () => {+ expect(ALERT_THRESHOLD).toBeGreaterThanOrEqual(1);+ expect(TOOL_NAME).toBe('solana_register');+ });+});++describe('solana-register-health — autonomous registry wiring', () => {+ it('is registered as an enabled, 6-hour health canary on the paid endpoint', () => {+ const entry = getFullRegistry().find((e) => e.id === 'mcp-solana-register-health');+ expect(entry).toBeTruthy();+ expect(entry.enabled).toBe(true);+ expect(entry.pipeline).toBe('health');+ expect(entry.method).toBe('GET');+ expect(entry.cooldown_s).toBe(21600);+ expect(entry.path).toBe('/api/x402/solana-register-health');+ expect(typeof entry.extractSignal).toBe('function');+ });++ it('extractSignal lifts the health verdict from a healthy response', () => {+ const entry = getFullRegistry().find((e) => e.id === 'mcp-solana-register-health');+ const sig = entry.extractSignal({+ healthy: true, tool: 'solana_register', network: 'mainnet',+ canary_agent_id: 'agent-1', asset: 'Asset111', identity_pda: 'Pda111',+ checks: { registry_enrolled: true, asset_onchain: true, identity_pda_onchain: true },+ consecutive_failures: 0, rpc_latency_ms: 142,+ });+ expect(sig.alive).toBe(true);+ expect(sig.registry_enrolled).toBe(true);+ expect(sig.asset_onchain).toBe(true);+ expect(sig.identity_pda_onchain).toBe(true);+ expect(sig.asset).toBe('Asset111');+ });++ it('extractSignal marks alive:false for an unhealthy response without throwing', () => {+ const entry = getFullRegistry().find((e) => e.id === 'mcp-solana-register-health');+ const sig = entry.extractSignal({+ healthy: false, tool: 'solana_register', network: 'mainnet',+ checks: { registry_enrolled: true, asset_onchain: false, identity_pda_onchain: true },+ consecutive_failures: 4,+ });+ expect(sig.alive).toBe(false);+ expect(sig.asset_onchain).toBe(false);+ expect(sig.consecutive_failures).toBe(4);+ });++ it('extractSignal tolerates an empty/garbage body', () => {+ const entry = getFullRegistry().find((e) => e.id === 'mcp-solana-register-health');+ expect(() => entry.extractSignal(null)).not.toThrow();+ expect(entry.extractSignal(null).alive).toBe(false);+ expect(entry.extractSignal({}).tool).toBe('solana_register');+ });+});diff --git a/tests/x402-streaming-mcp-health.test.js b/tests/x402-streaming-mcp-health.test.jsnew file mode 100644index 000000000..89322bb9d--- /dev/null+++ b/tests/x402-streaming-mcp-health.test.js@@ -0,0 +1,198 @@+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';+import http from 'node:http';+import { Keypair } from '@solana/web3.js';++// The payer + payee/feePayer keys and the USDC mint must be valid base58 pubkeys+// because runStreamingMcpHealth builds (and signs) a real Solana transfer locally.+// Nothing is broadcast — the mock server below never touches a chain — so this is+// a true integration test of the probe → pay → stream-read → classify → store+// path without any on-chain spend.+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+process.env.X402_ASSET_MINT_SOLANA = USDC;++const { runStreamingMcpHealth } = await import('../api/_lib/x402/pipelines/streaming-mcp-health.js');++const payTo = Keypair.generate().publicKey.toBase58();+const feePayer = Keypair.generate().publicKey.toBase58();+const AMOUNT = '10000'; // 0.01 USDC atomics++function challenge() {+ return {+ x402Version: 2,+ error: 'payment required',+ accepts: [{+ scheme: 'exact',+ network: 'solana:mainnet',+ asset: USDC,+ payTo,+ amount: AMOUNT,+ extra: { feePayer },+ }],+ };+}++const RPC_RESULT = {+ jsonrpc: '2.0',+ id: 1,+ result: {+ content: [{ type: 'text', text: 'glTF-Validator report: 0 errors' }],+ structuredContent: { numErrors: 0, numWarnings: 0, fileSize: 162852 },+ },+};++// A captured-statement SQL stub: records every tagged-template call so the test+// can assert the mcp_stream_health insert happened.+function makeSqlStub() {+ const calls = [];+ const sql = (strings, ...values) => {+ const text = strings.join('?');+ calls.push({ text, values });+ return Promise.resolve([]);+ };+ return { sql, calls };+}++function baseCtx(origin, sqlStub) {+ return {+ origin,+ buyer: Keypair.generate(),+ // getAccountInfo(receiverAta) → null means "create the ATA", which is fine.+ conn: { getAccountInfo: async () => null },+ blockhash: '11111111111111111111111111111111',+ mintInfo: { decimals: 6 },+ redis: null,+ sql: sqlStub.sql,+ log: { info() {}, warn() {} },+ runId: '00000000-0000-0000-0000-000000000000',+ remainingCap: 1_000_000,+ };+}++// mode controls how the mock /api/mcp behaves on the PAID request.+let mode = 'healthy';+let server;+let origin;++beforeAll(async () => {+ server = http.createServer((req, res) => {+ const paid = !!req.headers['x-payment'];+ if (!paid) {+ // x402 challenge (plain agent → 402).+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify(challenge()));+ return;+ }+ if (mode === 'payment_rejected') {+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify(challenge()));+ return;+ }+ // Paid + accepted: settle (advertise the tx sig) and stream the JSON-RPC body.+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader(+ 'x-payment-response',+ Buffer.from(JSON.stringify({ success: true, transaction: 'TESTSIG_abc123' })).toString('base64'),+ );+ const payload = JSON.stringify(RPC_RESULT);+ if (mode === 'dropped') {+ // Write a partial chunk then destroy the socket → client sees a dropped stream.+ res.write(payload.slice(0, 10));+ setTimeout(() => res.socket?.destroy(), 20);+ return;+ }+ // healthy: write in two chunks then end cleanly.+ res.write(payload.slice(0, Math.floor(payload.length / 2)));+ setTimeout(() => res.end(payload.slice(Math.floor(payload.length / 2))), 15);+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ const { port } = server.address();+ origin = `http://127.0.0.1:${port}`;+});++afterAll(() => new Promise((resolve) => server.close(resolve)));++beforeEach(() => { mode = 'healthy'; });++describe('runStreamingMcpHealth', () => {+ it('pays, stream-reads a clean response, settles, and stores health', async () => {+ mode = 'healthy';+ const sqlStub = makeSqlStub();+ const out = await runStreamingMcpHealth(baseCtx(origin, sqlStub));++ expect(out.success).toBe(true);+ expect(out.amountAtomic).toBe(Number(AMOUNT));+ expect(out.txSig).toBe('TESTSIG_abc123');+ expect(out.errorMsg).toBeNull();+ expect(out.signalData.alive).toBe(true);+ expect(out.signalData.settled).toBe(true);+ expect(out.signalData.chunk_count).toBeGreaterThanOrEqual(1);+ expect(out.signalData.total_bytes).toBeGreaterThan(0);+ expect(out.signalData.stalled).toBe(false);+ expect(out.signalData.dropped).toBe(false);++ // The value sink got an INSERT into mcp_stream_health.+ const insert = sqlStub.calls.find((c) => /insert into\s+mcp_stream_health/i.test(c.text));+ expect(insert).toBeTruthy();+ expect(insert.values).toContain(true); // healthy+ });++ it('flags a dropped connection and charges nothing was settled if settle absent', async () => {+ mode = 'dropped';+ const sqlStub = makeSqlStub();+ const out = await runStreamingMcpHealth(baseCtx(origin, sqlStub));++ expect(out.success).toBe(false);+ expect(out.signalData.dropped).toBe(true);+ expect(out.errorMsg).toMatch(/stream_dropped/);+ // Server set x-payment-response before dropping, so settlement is recorded,+ // but the stream is unhealthy → success false.+ expect(out.signalData.settled).toBe(true);+ expect(sqlStub.calls.some((c) => /insert into\s+mcp_stream_health/i.test(c.text))).toBe(true);+ });++ it('handles a 402 payment rejection on the paid call without crashing', async () => {+ mode = 'payment_rejected';+ const sqlStub = makeSqlStub();+ const out = await runStreamingMcpHealth(baseCtx(origin, sqlStub));++ expect(out.success).toBe(false);+ expect(out.amountAtomic).toBe(0);+ expect(out.errorMsg).toMatch(/payment_rejected: 402/);+ expect(out.signalData.settled).toBe(false);+ });++ it('honors the daily cap — skips paying when the price exceeds remainingCap', async () => {+ const sqlStub = makeSqlStub();+ const ctx = baseCtx(origin, sqlStub);+ ctx.remainingCap = 1; // below AMOUNT+ const out = await runStreamingMcpHealth(ctx);++ expect(out.success).toBe(false);+ expect(out.skipped).toBe(true);+ expect(out.errorMsg).toBe('cap_would_exceed');+ expect(out.amountAtomic).toBe(0);+ });++ it('degrades gracefully when the wallet is unconfigured', async () => {+ const sqlStub = makeSqlStub();+ const ctx = baseCtx(origin, sqlStub);+ ctx.buyer = null;+ // No seed env + no local wallet file in CI → loadSeedKeypair throws → skip.+ const prevSeed = process.env.X402_SEED_SOLANA_SECRET_BASE58;+ const prevAgent = process.env.X402_AGENT_SOLANA_SECRET_BASE58;+ delete process.env.X402_SEED_SOLANA_SECRET_BASE58;+ delete process.env.X402_AGENT_SOLANA_SECRET_BASE58;+ try {+ const out = await runStreamingMcpHealth(ctx);+ expect(out.success).toBe(false);+ expect(out.skipped).toBe(true);+ expect(out.errorMsg).toMatch(/wallet_unconfigured/);+ } finally {+ if (prevSeed !== undefined) process.env.X402_SEED_SOLANA_SECRET_BASE58 = prevSeed;+ if (prevAgent !== undefined) process.env.X402_AGENT_SOLANA_SECRET_BASE58 = prevAgent;+ }+ });+});