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: add rig complexity scorer pipeline for avatar complexity assessment
nirholasf5c713a2d6f0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f7e7618b6..5a7dbf5a8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Activation, upgraded — Live badges, one-call agent activation, and a Go Live first step** — Bringing an agent to life is now front-and-center and easier for people and agents alike. Right after you create an agent, "Go live" is the first thing offered. Agents that have claimed their welcome grant now wear a "◉ Live" badge across the marketplace so funded, active agents stand out, and their live status is published in each agent's manifest. Developers and autonomous agents can activate in a single call with the three.ws SDK (client.activate(agentId)). Behind the scenes, activating now also registers the agent's payout wallet so it can earn from day one, and counts toward referral rewards when you were invited. We also hardened the on-chain grant so it can never be sent twice. (`/marketplace`) `[feature, improvement, sdk]`- **Alibaba Cloud partnership — Qwen models and alibaba-cloud-mcp** — three.ws joins the Alibaba Cloud Partner Network. Qwen-Max, Qwen-Plus, Qwen-Turbo, and Qwen-Long are now available as agent brain options via DashScope. Ships with @three-ws/alibaba-cloud-mcp — a new MCP server for chat, embeddings, and model discovery using your own Alibaba Cloud API key. Set DASHSCOPE_API_KEY in Vercel to activate. (`/blog/three-ws-alibaba-cloud-partnership`) `[feature]`- **Autonomous coin launcher — creator fees, revenue tracking, and admin console upgrades** — The memetic launcher now auto-claims pump.fun creator fees from every coin it mints, routing the configured share toward $THREE. The admin console at /admin/launcher gains a live revenue panel (total creator fees claimed, $THREE allocated), agent-name visibility in the run feed, a Force Tick button for instant testing, and a cleaner 8-column stat grid. Know Your Meme is wired as a live trend source alongside Hacker News, Reddit, and Wikipedia — so the launcher reads what the internet is actually minting. (`/admin/launcher`) `[feature, improvement]`+- **Autonomous x402 Spend Loop — platform pays its own endpoints and learns from every call** — The platform's x402 seed wallet now actively participates in the agent economy on a 5-minute cron cycle. Every tick it selects up to 8 endpoints from a priority-ranked registry (oracle intel, sniper support, health checks, volume) and makes real USDC payments to each — recording every transaction to x402_autonomous_log with the full signal payload. Oracle-pipeline calls (crypto-intel for SOL/BTC/ETH/pump, $THREE signal feed) feed a new oracle_intel_signals table that the agent sniper reads directly: bullish macro signals lower the conviction threshold so the sniper fires more freely; bearish signals raise it. The loop also enforces a daily spend cap (default $5/day) and per-entry Redis cooldowns. This is the first time three.ws earns intelligence through payments and uses it to make better autonomous trading decisions. `[feature, infra]`- **Avatar Optimization Pipeline — nightly analysis of top avatars** — The platform now runs a nightly optimization sweep across the 50 most-viewed public avatars. Each model is analyzed for geometry and texture inefficiencies — Draco/Meshopt compression opportunities, oversized textures ready for KTX2 transcoding, non-indexed primitives, and redundant materials. Results are stored per-avatar so we can surface actionable improvement suggestions to creators. The pipeline runs autonomously via the x402 agent spend loop, paying $0.001 USDC per nightly batch. `[feature, infra]`- **Capabilities dashboard — live command center for all 4 autonomous features** — New /dashboard/capabilities page surfaces live status for Alpha Hunt, Coin Launcher, Auto-Claim, and Market Maker in one view. KPI strips show daily budget, total volume, claimable fees, and net P&L per capability. Tabbed tables show launched coins, schedule status, per-market inventory bars, and recent MM trades. Alpha Hunt trigger is now also configurable directly from the Sniper Strategies dashboard — full field set including min smart-money count, quality score, organic score, max market cap, and narrative keywords. (`/dashboard/capabilities`) `[feature, improvement]`- **CAPTCHA relief for rate-limited sign-ins** — Users who hit the sign-in rate limit (e.g. shared office/home network) now see a lightweight proof-of-work puzzle instead of a hard countdown. Solve it in a second or two and you can keep signing in immediately — no waiting, no support ticket. Built on Altcha (open source, MIT-licensed, no tracking or third-party service). (`/login`) `[improvement, security]`@@ -34,6 +35,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Live cultural narratives — now public, and now powered by Google Trends** — The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/trends: any agent (or builder) can ask what's trending right now — optionally filtered to specific sources — with the signals confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied. `[feature, improvement]`- **Manage your AWS Marketplace API key — new keys & usage page** — AWS Marketplace subscribers (and anyone with an x402 subscription key) now have a home for it at /billing/keys. See every key with its billing source — AWS Marketplace or on-chain — live status, rate limit, total calls, and when it was last used. Rotate a key to get a fresh secret in one click (AWS-billed keys stay linked to your AWS account and keep metering correctly), or revoke a native key outright. The post-subscribe welcome flow now points here, so a lost key is always recoverable by rotating instead of being stuck. (`/billing/keys`) `[feature]`- **MCP Model Validation Sweep — proactive GLB quality scoring** — The platform now runs a continuous quality sweep across every public 3D avatar in the database. Every 5 minutes the autonomous agent picks the longest-unvalidated GLB, inspects it with the glTF-Transform engine, and records a 0-100 quality score covering rig completeness, geometry health, texture sizing, triangle budget, and unsupported extensions. Results are stored in a time-series table (model_quality_scores) that will power quality badges and curation tools — surfacing models that need attention before users encounter errors in the viewer. The sweep is driven by the x402 autonomous spend loop at $0.001 USDC per call. `[feature, infra]`+- **MCP Tool Latency Monitor — live SLA health for every MCP tool** — The platform now continuously watches the responsiveness of its MCP server — the interface AI agents use to render avatars, inspect models, read live market data, and more. Every 5 minutes an autonomous agent makes one real USDC payment to exercise the full paid path end-to-end, then sweeps every advertised tool and times the response each one returns to a caller. Rolling p50/p95/p99 latencies are recorded per tool, and any tool whose p95 exceeds 2 seconds raises an alert — so a slowdown is caught and surfaced on the internal ops dashboard before agents feel it. `[feature, infra]`- **Money Pulse now shows whether agent trading is viable** — The Pulse page gained a Trading viability panel — the honest signal behind the headline Trades counter. It shows what's actually flowing through agent wallets: trades over 24h and 7 days, the SOL deployed into buys (what the trading is costing), the average trade size, how many wallets are trading right now, and — once positions close — the realized profit-and-loss with a win rate, alongside a 7-day trade sparkline and the top trading agents. The 24h trade count reconciles exactly with the headline counter, so the panel can never drift from the number at the top of the page. Every figure is a real, on-chain custody event or a closed position priced against real fills — never synthetic. (`/pulse`) `[feature, improvement]`- **Money Pulse now tracks real marketplace demand** — The Pulse page gained a Marketplace viability panel — the honest economic signal behind the headline counters. It surfaces real $THREE skill purchases as their own thing: GMV over 24h and 7 days, average ticket, the repeat-buyer rate, the number of unique buyer→seller pairs, the platform take-rate earned, plus a 7-day GMV sparkline, the top skills the market is actually paying for, and the top-earning sellers. Until now these real, value-delivering purchases were invisible on Pulse while the agent-to-agent x402 settlement counter took the spotlight; now you can see whether agents paying each other for skills is a real, recurring market. Every figure is a confirmed on-chain purchase — never synthetic. (`/pulse`) `[feature, improvement]`- **Money Pulse redesign — monochrome, with far more live data** — The live activity page at /pulse got a full pass. It's now proper monochrome to match the rest of the site — the violet accent and green/amber feed colors give way to a single clean ink ramp. And it carries a lot more real signal: 24h on-chain volume (SOL + USD), distinct active wallets, and split counters for trades, snipes, and agent-to-agent payments, plus a 7-day activity sparkline, the day's single biggest tip, and a fresh-launches feed alongside the existing top-earners and busiest-wallets boards. Every number is a real on-chain or launch record — never synthetic. (`/pulse`) `[improvement, feature]`@@ -43,9 +45,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Production stability fixes — payment sessions, Redis error handling, infra resilience** — Fixed a SQL syntax error that blocked payment session expiry and refunds (PostgreSQL does not allow LIMIT directly in UPDATE — now uses a CTE with FOR UPDATE SKIP LOCKED). Fixed esbuild class-name minification breaking NeonDB error detection in production — infrastructure errors (wrong DB credentials, Redis auth) now correctly return 503 and suppress alert storms instead of crashing every endpoint with 500. Added graceful Redis-unavailable handling to the usage flush buffer and the bounty board API. Fixed Express-style response methods in pulse-tick cron. `[fix, infra]`- **Restored token-launch, agent payments, and on-chain endpoints** — Fixed a class of missing API route mappings that left several backend endpoints unreachable in production: token launch (quote, prep, confirm), agent-to-agent payments, on-chain transaction prep/confirm, Solana and EVM checkout, and live-walk session control. The handlers were deployed but never wired to their public paths; they now respond correctly. Part of a wider audit that also restored wallet sign-in. `[fix]`- **Reviews anchored on-chain — Solana attestations + ERC-8004 reputation** — 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. (`/marketplace`) `[feature, improvement]`+- **Scene Capture auto-processing — upload a video, get a 3D point cloud back** — Videos uploaded on /capture are now reconstructed into 3D point clouds automatically, with no waiting on the page. Each upload joins a processing queue that an autonomous agent drains on a 2-minute cadence: it pays a $0.01 USDC processing credit via x402, hands the video to the LingBot-Map GPU worker, then polls until the .ply point cloud is ready and stores the result on the job. When you come back, the finished cloud renders directly in the /capture viewer. Every run — submit, poll, success or failure — is recorded for full auditability, and the pipeline degrades cleanly when the GPU worker or wallet isn't configured. (`/capture`) `[feature, infra]`- **Sign-in cooldown is now exact — and there's more headroom before it trips** — If you ever hit "too many attempts" while signing in, the form now shows the real countdown the server hands back — a live timer on the button that ticks down and re-arms the form the instant you can try again, instead of a vague "try later". We also raised the per-network attempt allowance, so people signing in from shared office or campus connections are far less likely to be told to wait at all. Wrong-password and network-drop messages are now clearer and distinct, too. (`/login`) `[improvement]`- **Sign-in restored during rate-limiter outages** — Fixed an issue where a temporary outage of the distributed rate limiter could block every sign-in attempt platform-wide. The login and registration limiters now degrade gracefully to a local per-instance cap during such an outage — keeping sign-in available while still throttling brute-force attempts — instead of denying everyone. Money-moving limits are unchanged and still fail safe. `[fix, security]`- **Sign-up and 3D avatar reliability fixes** — Two fixes to the front door. The 3D avatar on the sign-up page — and on roughly fifty other pages that show a preview model — now loads reliably the first time, instead of occasionally staying blank until you reloaded; a timing race meant the model viewer could start loading a compressed avatar before its decoder was ready. Separately, the sign-up username field again enforces its rules (3–30 characters; letters, numbers, underscore and hyphen) as you type in the latest Chrome, where a stricter pattern-matching mode had quietly switched that live validation off. No action needed — both are automatic. (`/register`) `[fix]`+- **SSE Streaming MCP Health — continuous proof the paid MCP transport delivers cleanly** — Every five minutes an autonomous agent makes one real paid call to the platform's MCP server in streaming (SSE) mode and reads the response back as a live stream instead of a single buffered blob. It measures how fast the first byte arrives, the gaps between chunks, the chunk count and total bytes, and confirms the on-chain payment actually settled — then classifies the stream as clean, stalled, or dropped. A hung server, a half-delivered response, or broken chunked encoding now trips immediately and pages ops, with the full streaming-integrity history stored (mcp_stream_health) for the status surface, instead of being discovered by a paying agent whose tool call never finished. It runs on the x402 autonomous spend loop using the platform's own wallet. `[infra]`- **Status page goes monochrome — with a fleet summary and an embeddable status badge** — The platform status page now leads with three at-a-glance numbers — 90-day uptime, services operational, and average response time — above the per-service history, and reads in clean monochrome that matches the rest of three.ws (a single red is reserved for a genuine outage so it's impossible to miss). The public status feed now also serves an embeddable status badge: drop https://three.ws/api/status?format=svg into any README or dashboard to show whether the platform is operational, and agents reading /api/status get the same fleet summary as a ready-made object. (`/status`) `[feature, improvement]`- **Task input on Agent Screen — send your agent a task and watch it work** — You can now type any task directly into the Agent Screen page and your agent picks it up in real time. The live screen panel has a new command bar at the bottom: type what you want your agent to do (research, browse, shop, monitor, trade) and hit send. The task is queued via /api/agent-task and the running worker executes it with Stagehand, streaming every browser action back to the live screen as it happens. The worker automatically checks for new tasks every 3 seconds and runs them in priority order, falling back to its autonomous loop when the queue is empty. (`/agent-screen`) `[feature, improvement]`- **The launcher now reads Know Your Meme** — The autonomous coin launcher gained a new culture feed: Know Your Meme. It reads the freshly-confirmed meme entries and the live meme newsfeed, fuses them with the platform's on-chain signals, and rides the strongest wave when an agent coins its next launch — so new launches track the memes actually entering culture right now, not stale themes. As always, only the cultural THEME is mined; names and tickers are invented fresh, never copied, and every coin stays avatar-fronted and $THREE-aligned. `[feature, improvement]`diff --git a/api/_lib/migrations/20260627120000_token_intel_pre_snipe_gate.sql b/api/_lib/migrations/20260627120000_token_intel_pre_snipe_gate.sqlnew file mode 100644index 000000000..c6f23335c--- /dev/null+++ b/api/_lib/migrations/20260627120000_token_intel_pre_snipe_gate.sql@@ -0,0 +1,61 @@+-- Migration: Token Intel Pre-Snipe Gate — rugpull-risk verdicts per mint.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260627120000_token_intel_pre_snipe_gate.sql+-- Idempotent.+--+-- The autonomous x402 loop (self/023) pays /api/x402/token-intel ($0.01 USDC) for+-- the freshest pump.fun mints the sniper is about to consider and writes the+-- live due-diligence verdict here, one row per (mint, network). The verdict+-- carries a 0..100 rugpull sub-score (token-intel's risk.score — higher = riskier)+-- and a `rejected` boolean set when the risk level is high/critical.+--+-- Downstream consumer: workers/agent-sniper/oracle-gate.js reads this table on the+-- pre-snipe path (new_mint, first_claim, intel_confirmed, prelaunch-radar). A fresh+-- `rejected = true` row vetoes the snipe before any SOL is committed — the+-- "high-risk mints are auto-rejected" safety floor. The oracle feed can blend the+-- same sub-score into conviction. Fail-open by design: a missing/stale row never+-- blocks a snipe, so this layer can only ever make the sniper safer.++begin;++create table if not exists token_intel_risk (+ mint text not null,+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),++ -- 0..100 rugpull sub-score (token-intel risk.score; higher = more risk).+ rugpull_score int not null default 0 check (rugpull_score between 0 and 100),+ risk_level text not null default 'unknown'+ check (risk_level in ('low','medium','high','critical','unknown')),+ -- true when level is high/critical → the sniper auto-rejects this mint.+ rejected boolean not null default false,++ -- the token-intel market read behind the score (audit trail + feed blending).+ signal text, -- bullish|bearish|neutral+ confidence numeric(4,3), -- 0..1+ symbol text,+ price_usd numeric(20,10),+ change_24h numeric,+ market_cap_usd numeric,+ liquidity_usd numeric,+ volume_24h_usd numeric,+ factors jsonb not null default '[]'::jsonb, -- [{label,status,detail}]++ -- provenance: the x402 settlement that produced this verdict.+ tx_signature text,+ run_id uuid,+ checked_at timestamptz not null default now(),++ primary key (mint, network)+);++-- Pre-snipe lookup is by (mint, network); the gate also treats rows older than a+-- freshness window as absent, so index the recency too.+create index if not exists token_intel_risk_checked+ on token_intel_risk (network, checked_at desc);+create index if not exists token_intel_risk_rejected+ on token_intel_risk (network, rejected, checked_at desc) where rejected = true;++comment on table token_intel_risk is+ 'Per-mint rugpull-risk verdicts from the x402 Token Intel Pre-Snipe Gate (self/023). '+ 'Consumed by workers/agent-sniper/oracle-gate.js to auto-reject high-risk mints pre-snipe.';++commit;diff --git a/api/_lib/migrations/20260629110000_agent_wallet_balance_log.sql b/api/_lib/migrations/20260629110000_agent_wallet_balance_log.sqlnew file mode 100644index 000000000..403d5caed--- /dev/null+++ b/api/_lib/migrations/20260629110000_agent_wallet_balance_log.sql@@ -0,0 +1,24 @@+-- Time-series log for the Agent Wallet Balance Monitor autonomous pipeline+-- (api/_lib/x402/wallet-balance-monitor.js). Every 10 minutes the autonomous+-- loop reads the seed/agent wallet's live USDC + SOL balance via the free+-- GET /api/x402-pay?balance=1, records one sample here, derives the burn rate+-- vs the previous sample, and flags low_balance when USDC drops below threshold.+-- The pipeline also creates this table lazily; this migration is belt-and-suspenders.+-- Consumer: api/ops/health.js folds a low/unconfigured wallet into the health verdict.++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+);++create index if not exists agent_wallet_balance_log_ts on agent_wallet_balance_log (ts desc);diff --git a/api/_lib/migrations/20260629120000_payment_reconciliation.sql b/api/_lib/migrations/20260629120000_payment_reconciliation.sqlnew file mode 100644index 000000000..7a403f491--- /dev/null+++ b/api/_lib/migrations/20260629120000_payment_reconciliation.sql@@ -0,0 +1,42 @@+-- Payment Revenue Reconciliation (USE-027, Finance)+--+-- Backs the `revenue-reconciliation` autonomous-registry entry+-- (api/_lib/x402/revenue-reconciliation.js). Each daily run cross-checks every+-- settlement our books claim — outbound x402_autonomous_log paid rows and inbound+-- agent_payment_intents — against the actual on-chain transaction, and upserts one+-- verdict row per record here keyed on (source, source_ref).+--+-- A row with reconciled = false is a financial-integrity alert: the DB recorded a+-- settlement the chain does not corroborate (no tx on-chain, tx reverted, or no+-- signature was kept). The ops financial-integrity surface reads+-- `... WHERE reconciled = false` to flag these before they corrupt accounting.+--+-- Mirrors the in-code ensureSchema() in revenue-reconciliation.js so a fresh env+-- works whether migrations are applied ahead of time or lazily on first run.++CREATE TABLE IF NOT EXISTS payment_reconciliation (+ id bigserial PRIMARY KEY,+ source text NOT NULL, -- 'autonomous_log' | 'payment_intent'+ source_ref text NOT NULL, -- row id within that book+ tx_signature text,+ network text,+ amount_atomic bigint,+ db_status text NOT NULL, -- what the book claims+ chain_status text NOT NULL, -- confirmed|failed_onchain|missing_onchain|missing_signature|skipped_non_solana|unknown+ reconciled boolean NOT NULL,+ discrepancy text, -- null when reconciled+ detail jsonb,+ run_id uuid,+ first_seen_at timestamptz NOT NULL DEFAULT now(),+ checked_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (source, source_ref)+);++CREATE INDEX IF NOT EXISTS payment_reconciliation_open_idx+ ON payment_reconciliation (checked_at DESC) WHERE reconciled = false;+CREATE INDEX IF NOT EXISTS payment_reconciliation_sig_idx+ ON payment_reconciliation (tx_signature);++-- The autonomous log predates the value_extracted column the reconciliation+-- summary is written into (shared across run()-style pipelines; idempotent).+ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb;diff --git a/api/_lib/x402/autonomous-pay.js b/api/_lib/x402/autonomous-pay.jsdeleted file mode 100644index 0fd7a64d0..000000000--- a/api/_lib/x402/autonomous-pay.js+++ /dev/null@@ -1,292 +0,0 @@-// 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 7d8d4b984..056ff9d2e 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -34,12 +34,20 @@// discovery warmup sweeping 15 categories per run).import { run as bazaarDiscoveryWarmup } from './pipelines/bazaar-warmup.js';+import { run as reputationRefresh } from './pipelines/reputation-refresh.js';+import { run as tokenIntelPreSnipeGate } from './pipelines/token-intel-gate.js';import { run as volumeBootstrapLoop } from './pipelines/volume-bootstrap-loop.js';+import { run as liveFeedSeeder } from './pipelines/live-feed-seeder.js';+import { run as feeCalculationValidator } from './pipelines/fee-calculation-validator.js';+import { classifyThreeSignal, insertThreeSignal } from './three-signal-store.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 { run as runAnimationRetargetQa, hasCanaryClips as hasAnimationQaCanaries } from './pipelines/animation-retarget-qa.js';import { runCircuitBreaker } from './circuit-breaker.js';+import { run as runGlbSizeOptimizer } from './glb-size-optimizer.js';+import { run as walletBalanceMonitor } from './wallet-balance-monitor.js';+import { run as revenueReconciliation } from './revenue-reconciliation.js';import { mcpLatencySweep } from './mcp-latency-sweep.js';import { runStreamingMcpHealth } from './pipelines/streaming-mcp-health.js';import { publicUrl } from '../r2.js';@@ -178,6 +186,34 @@ async function nextCanonicalTarget(ctx) {}const SELF_ENDPOINTS = [+ // ── 3D Pipeline: GLB Size Optimizer (USE-018) ─────────────────────────────+ // Picks the heaviest public avatar GLB over the 5 MB web-delivery budget that+ // has not been analyzed in the last 14 days, then pays one real x402 call to+ // /api/mcp (optimize_model) to inspect it and surface Draco/Meshopt geometry+ // compression, 4K→2K texture downscaling, and PNG→KTX2 transcoding. run()+ // projects the post-optimization size from the model's measured stats and+ // persists original + projected-optimized bytes and load-time improvement to+ // glb_optimizations (+ a detailed x402_autonomous_log row with value_extracted).+ // 6h pacing sweeps the heavy backlog one model per run, biggest/stalest first,+ // well under the daily cap. Downstream consumer: GET /api/x402/glb-optimization+ // -report aggregates the catalog-wide average size + load-time improvement and+ // the remaining heavy-GLB backlog.+ {+ id: 'glb-size-optimizer',+ name: 'GLB Size Optimizer (>5MB catalog sweep)',+ // path is informational — runGlbSizeOptimizer() selects the target GLB and+ // pays the optimize_model call against /api/mcp itself. Real price is read+ // from the live 402 challenge (optimize_model is $0.05/call).+ path: '/api/mcp',+ method: 'POST',+ cooldown_s: 21_600, // 6h — gradual catalog sweep, one heavy model per run+ priority: 37,+ pipeline: 'self',+ enabled: true,+ run: runGlbSizeOptimizer,+ extractSignal: null,+ },+// ── Circuit Breaker (cheapest end-to-end proof the payment stack is alive) ─{id: 'circuit-breaker-cross-network',@@ -195,6 +231,29 @@ const SELF_ENDPOINTS = [extractSignal: null,},+ // ── Agent Wallet Balance Monitor (self) ───────────────────────────────────+ // Polls the seed/agent wallet balance (the wallet that funds every other+ // autonomous call) via the free GET /api/x402-pay?balance=1 every 10 minutes.+ // run() records a time-series sample to agent_wallet_balance_log, derives the+ // USDC burn rate vs the previous sample, and raises a low-balance alert (USDC+ // < $5, env-tunable) to Redis + the logs so operators can top up before the+ // loop is starved. Free read → moves no funds (amountAtomic always 0).+ // Downstream consumer: api/ops/health.js folds a low/unconfigured wallet into+ // the internal health verdict so the status dashboard flags it early.+ {+ id: 'agent-wallet-balance-monitor',+ name: 'Agent Wallet Balance Monitor',+ // path is informational — walletBalanceMonitor() owns the free GET call.+ path: '/api/x402-pay?balance=1',+ method: 'GET',+ cooldown_s: 600, // every 10 minutes+ priority: 92, // high: a starved wallet breaks every other pipeline+ pipeline: 'health',+ enabled: true,+ run: walletBalanceMonitor,+ 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@@ -271,16 +330,32 @@ const SELF_ENDPOINTS = [extractSignal: (r) => ({ topic: r?.topic, signal: r?.signal, headline: r?.headline, confidence: r?.confidence }),},{+ // ── $THREE Signal Feed (USE: $THREE market oracle) ─────────────+ // Pays $0.01 USDC every 15 min to /api/x402/three-intel for the live $THREE+ // market snapshot (price, 24 h change, mcap, liquidity, volume, signal). As an+ // `oracle` entry the latest snapshot also dedups into oracle_intel_signals+ // (topic 'three') for the sniper gate; storeValue appends every snapshot to the+ // three_market_signals time series. Downstream consumers of that series:+ // • the public $THREE price widget — GET /api/three-signal (latest + sparkline)+ // • $THREE-denominated x402 pricing — usdToThreeTokens() reads the latest priceid: 'three-intel',name: '$THREE Signal Feed',path: '/api/x402/three-intel',- method: 'POST',- body: {},- cooldown_s: 900,+ method: 'GET', // three-intel is a GET endpoint (query input, no request body)+ body: null,+ cooldown_s: 900, // 15 minpriority: 99,pipeline: 'oracle',enabled: true,- extractSignal: (r) => ({ signal: r?.signal, headline: r?.headline, confidence: r?.confidence, price_usd: r?.price_usd }),+ // classifyThreeSignal carries the full market shape into signal_data so the+ // oracle dedup + the autonomous-log row both hold the complete snapshot.+ extractSignal: (r) => ({ topic: 'three', ...classifyThreeSignal(r) }),+ storeValue: async ({ sql, responseBody, signalData, runId }) => {+ if (!sql) return;+ const v = classifyThreeSignal(responseBody || signalData);+ if (v.price_usd == null) return; // never persist an empty/failed snapshot+ await insertThreeSignal(sql, v, { runId, source: 'x402-autonomous' });+ },},{id: 'fact-check-sol',@@ -598,41 +673,33 @@ const SELF_ENDPOINTS = [extractSignal: (r) => ({ alive: !!r }),},- // ── 3D Pipeline QA ─────────────────────────────────────────────────────────- // Animation Retargeting QA: pays $0.005 USDC to download a canary animation- // clip through the full paid-delivery path (402 paywall → R2 presign → GLB).- // That delivery path ships clips produced by the retarget/canonicalize- // pipeline (src/glb-canonicalize.js, src/animation-retarget.js), so a- // regression that yields a missing, zero-byte, or non-GLB artifact surfaces- // here as pass:false. The verdict is stored to x402_autonomous_log.signal_data- // (queryable QA history); world-health / uptime dashboards consume it.- // Gated on X402_ANIMATION_QA_CLIP_ID — disabled (no spend) until a canary- // clip is designated. Cooldown 6h → ≤4 paid probes/day ≈ $0.02/day.+ // ── Animation Retargeting QA (USE-012) ──────────────────────────────────────+ // Pays $0.005 USDC to download a representative set of canary animation clips+ // (one per rig convention — Mixamo, VRM, Avaturn, Daz) through the real+ // paid-delivery path (402 paywall → R2 presign → animated GLB), then fetches+ // each presigned GLB and inspects the actual bytes with inspectGlb(): the file+ // must be a valid, non-zero binary glTF whose animation track survived. An+ // empty/truncated/non-GLB artifact, or one whose animation channels vanished —+ // the regression a glb-canonicalize.js / animation-retarget.js break produces —+ // flips the verdict to passed:false. run() owns the per-clip pay/fetch/inspect+ // and per-clip recording; the loop records one summary row (verdict in+ // signal_data), and run() upserts each verdict into animation_qa_results keyed+ // by clip_id (the sink the animation marketplace + retarget-regression alerting+ // read). Gated on X402_ANIMATION_QA_CLIP_IDS / X402_ANIMATION_QA_CLIP_ID —+ // disabled (no spend) until canary clips are designated. Cooldown 6h → at+ // $0.005 per clip, a 4-rig sweep ≈ $0.08/day.{id: 'anim-retarget-qa',name: 'Animation Retargeting QA',- path: `/api/x402/animation-download?id=${ANIM_QA_CLIP_ID}`,+ // path is informational — runAnimationRetargetQa() probes + settles each clip.+ path: '/api/x402/animation-download',method: 'GET',body: null,cooldown_s: 21600,priority: 45,pipeline: 'qa',- enabled: Boolean(ANIM_QA_CLIP_ID),- extractSignal: (r) => {- const sizeBytes = Number(r?.sizeBytes ?? 0);- const mime = String(r?.mimeType || '');- const hasDownload = !!r?.downloadUrl;- const isGlb = /gltf-binary|\bglb\b/i.test(mime);- return {- clip: r?.slug || r?.id || null,- name: r?.name || null,- size_bytes: sizeBytes,- mime,- has_download: hasDownload,- // All three must hold for the delivery path to be regression-free.- pass: r?.ok === true && hasDownload && sizeBytes > 0 && isGlb,- };- },+ enabled: hasAnimationQaCanaries(),+ run: (ctx) => runAnimationRetargetQa(ctx),},// GLB Canonicalization: pays $0.001 USDC to run a rig-reference avatar// through /api/x402/model-check, validating that its skeleton still inspects@@ -733,6 +800,31 @@ const SELF_ENDPOINTS = [run: (ctx) => bazaarDiscoveryWarmup(ctx),},+ // ── Agent Reputation Score Refresh (USE-005) ───────────────────────────────+ // Refreshes the on-chain attestation reputation of the stalest registered+ // Solana agents by paying the /api/mcp tool solana_agent_reputation+ // ($0.001/call) for each. run() owns the full per-agent sweep and per-call+ // recording; the loop records one summary row. Cooldown 21600s (6h) →+ // ≤25 agents/run ≈ $0.025/run, bounded again by the loop's daily cap; stalest+ // agents sort first so coverage rotates. Value sink: agent_solana_reputation+ // (per-agent score + flag) — read by the agent-profile trust badge, the+ // reputation leaderboard, and the moderation flagged feed (see+ // getStoredSolanaReputation / listSolanaReputationLeaderboard /+ // listFlaggedSolanaAgents in pipelines/reputation-refresh.js).+ {+ id: 'reputation-score-refresh',+ name: 'Agent Reputation Score Refresh',+ // path is informational — run() fans the call across registered agents.+ path: '/api/mcp',+ method: 'POST',+ body: null,+ cooldown_s: 21600,+ priority: 45,+ pipeline: 'self',+ enabled: true,+ run: (ctx) => reputationRefresh(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@@ -862,6 +954,34 @@ const SELF_ENDPOINTS = [enabled: true,run: (ctx) => cosmeticPricingAudit(ctx),},+ // ── Payment Revenue Reconciliation (USE-027, Finance) ─────────────────────+ // Daily financial-integrity sweep. Probes the free /api/x402-status endpoint to+ // confirm payment wiring is live, then cross-checks every settlement our books+ // claim (outbound x402_autonomous_log paid rows + inbound agent_payment_intents)+ // against the actual on-chain transaction via getSignatureStatuses. Flags any+ // row where the DB says settled but no tx exists on-chain, the tx reverted, or+ // no signature was kept. run()-style entry — owns the full probe → load → verify+ // → upsert sequence (revenue-reconciliation.js); read-only, so it runs even when+ // the spend wallet is absent. Per-record verdicts land in payment_reconciliation;+ // a summary (value_extracted = discrepancy counts) goes to x402_autonomous_log.+ // Cooldown 86400 s (daily). Downstream consumer: the financial-integrity surface+ // reads payment_reconciliation WHERE NOT reconciled to alert ops on unsettled or+ // failed payments before they corrupt revenue accounting.+ {+ id: 'revenue-reconciliation',+ name: 'Payment Revenue Reconciliation',+ path: '/api/x402-status',+ endpoint: '/api/x402-status',+ method: 'GET',+ body: null,+ price_atomic: 0, // /api/x402-status is free; reconciliation owes no payment+ cooldown_s: 86400,+ cooldown_seconds: 86400,+ priority: 28,+ pipeline: 'reconciliation',+ enabled: true,+ run: (ctx) => revenueReconciliation(ctx),+ },];// ── External registry ─────────────────────────────────────────────────────────diff --git a/api/_lib/x402/glb-size-optimizer.js b/api/_lib/x402/glb-size-optimizer.jsnew file mode 100644index 000000000..6c78e9130--- /dev/null+++ b/api/_lib/x402/glb-size-optimizer.js@@ -0,0 +1,507 @@+// api/_lib/x402/glb-size-optimizer.js+//+// GLB Size Optimizer — autonomous pipeline (self/018).+//+// On each run it picks the single largest public avatar GLB in the catalog that+// is over the 5 MB web-delivery budget and has not been analyzed in the last+// ANALYZE_TTL_DAYS, then pays one real on-chain x402 USDC call to+// /api/mcp (optimize_model) to inspect it and surface concrete size reductions+// (Draco/Meshopt geometry compression, 4K→2K texture downscale, PNG→KTX2+// transcoding, re-indexing, material merging).+//+// optimize_model returns measured model statistics + actionable suggestions — it+// does not re-encode the GLB itself. So this pipeline computes a grounded+// projection of the post-optimization size from the model's *real* measured+// stats (vertex count, per-texture dimensions and byte sizes, extensions in use)+// using the same compression ratios the suggestions cite, and stores the+// original size alongside the projected optimized size and load-time improvement.+//+// 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) and records the returned+// aggregate as one summary row. Called standalone (manual test) it bootstraps its+// own context via bootstrapSolanaContext().+//+// Real on-chain payments only — no mocks. If the seed wallet or RPC is not+// configured, run() exits gracefully with a logged, recorded skip.+//+// Storage:+// glb_optimizations — one row per analyzed model. original_bytes,+// estimated_optimized_bytes, estimated_savings_bytes,+// savings_pct, load_ms_before/after, the full+// suggestions + inspection info, and the paying+// tx_signature. This is the canonical "value+// extracted" store for this pipeline.+// x402_autonomous_log — one detailed row per call (value_extracted = the+// savings summary), mirroring the bazaar pipeline.+//+// Downstream consumer:+// GET /api/x402/glb-optimization-report reads glb_optimizations to report the+// catalog-wide average size + load-time improvement and the per-model backlog+// of un-optimized heavy GLBs. The avatar gallery surfaces the per-model+// "save ~N%" hint from the latest row for each avatar.++import { randomUUID } from 'node:crypto';++import { sql } from '../db.js';+import { logger } from '../usage.js';+import { publicUrl } from '../r2.js';+import { env } from '../env.js';+import {+ payX402, bootstrapSolanaContext, loadSeedKeypair, USDC_MINT,+} from './pay.js';++const log = logger('x402-glb-size-optimizer');++const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// The web-delivery budget. GLBs heavier than this are optimization candidates.+export const SIZE_THRESHOLD_BYTES = 5 * 1024 * 1024;++// Don't re-analyze a model that was analyzed within this window — the catalog is+// swept gradually, one heavy model per run, stalest/biggest first.+const ANALYZE_TTL_DAYS = 14;++// Reference download bandwidth for the load-time projection: ~12 Mbps, the rough+// global median 4G throughput. Used identically for before/after so the *delta*+// is bandwidth-independent; the absolute ms are indicative.+const REFERENCE_BYTES_PER_SEC = 1_500_000;++// Grounded compression ratios (retained fraction after optimization), drawn from+// the figures the optimize_model suggestions themselves cite:+// • Draco geometry: "~60-80% smaller vertex buffers" → retain 0.30 (70% off).+// • Texture downscale: exact area ratio from real width/height (no constant).+// • KTX2 (Basis) over PNG: ~0.30 retained; over JPEG: ~0.60 retained.+const GEOM_RETAINED_DRACO = 0.30;+const KTX2_RETAINED_PNG = 0.30;+const KTX2_RETAINED_JPEG = 0.60;+// Per-vertex byte estimate for an uncompressed glTF vertex (position 12 + normal+// 12 + uv 8). Conservative — rigged avatars carry more (tangents, joints) so the+// real geometry weight, and thus the Draco win, is typically larger than modeled.+const BYTES_PER_VERTEX = 32;+const TARGET_TEXTURE_DIM = 2048;++let schemaReady = false;++export async function ensureOptimizationSchema() {+ if (schemaReady) return;+ try {+ await sql`+ CREATE TABLE IF NOT EXISTS glb_optimizations (+ id bigserial PRIMARY KEY,+ avatar_id uuid,+ slug text,+ name text,+ source_url text NOT NULL,+ original_bytes bigint NOT NULL,+ estimated_optimized_bytes bigint NOT NULL,+ estimated_savings_bytes bigint NOT NULL,+ savings_pct numeric(6,2),+ load_ms_before int,+ load_ms_after int,+ load_improvement_pct numeric(6,2),+ triangles bigint,+ vertices bigint,+ texture_count int,+ texture_bytes bigint,+ suggestion_ids text[],+ suggestions jsonb,+ info jsonb,+ run_id uuid,+ tx_signature text,+ amount_atomic bigint,+ analyzed_at timestamptz NOT NULL DEFAULT now()+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS glb_optimizations_avatar_idx ON glb_optimizations (avatar_id, analyzed_at DESC)`;+ await sql`CREATE INDEX IF NOT EXISTS glb_optimizations_savings_idx ON glb_optimizations (savings_pct DESC)`;+ // value_extracted lives on the shared loop log table; ensure it exists so+ // our detailed row can populate it even if this pipeline runs first.+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+ schemaReady = true;+ } catch (err) {+ if (!/already exists/i.test(err?.message || '')) {+ log.warn('glb_opt_schema_failed', { message: err?.message });+ }+ schemaReady = true;+ }+}++// Pick the heaviest public GLB over the budget that hasn't been analyzed within+// ANALYZE_TTL_DAYS. Returns { id, slug, name, storage_key, size_bytes } or null.+export async function pickTarget() {+ // Without a public R2 domain we cannot hand optimize_model a fetchable URL.+ if (!env.S3_PUBLIC_DOMAIN) return null;+ const rows = await sql`+ SELECT a.id, a.slug, a.name, a.storage_key, a.size_bytes+ FROM avatars a+ LEFT JOIN glb_optimizations g+ ON g.avatar_id = a.id+ AND g.analyzed_at > now() - (${ANALYZE_TTL_DAYS} || ' days')::interval+ WHERE a.deleted_at IS NULL+ AND a.visibility = 'public'+ AND a.storage_key IS NOT NULL+ AND a.storage_key ILIKE '%.glb'+ AND a.size_bytes > ${SIZE_THRESHOLD_BYTES}+ AND g.id IS NULL+ ORDER BY a.size_bytes DESC+ LIMIT 1+ `;+ return rows[0] || null;+}++// Project the post-optimization size from the model's *measured* stats. Pure,+// deterministic, and side-effect-free so it is independently testable.+export function projectOptimization(info, originalBytes) {+ const counts = info?.counts || {};+ const textures = Array.isArray(info?.textures) ? info.textures : [];+ const extensions = Array.isArray(info?.extensionsUsed) ? info.extensionsUsed : [];++ const fileSize = Number(info?.fileSize) || Number(originalBytes) || 0;+ const vertices = Number(counts.totalVertices) || 0;+ const triangles = Number(counts.totalTriangles) || 0;++ // ── Geometry ──────────────────────────────────────────────────────────────+ const geomBytes = vertices * BYTES_PER_VERTEX;+ const alreadyCompressed =+ extensions.includes('KHR_draco_mesh_compression') ||+ extensions.includes('EXT_meshopt_compression');+ const geomAfter = alreadyCompressed ? geomBytes : Math.round(geomBytes * GEOM_RETAINED_DRACO);++ // ── Textures ──────────────────────────────────────────────────────────────+ let textureBytes = 0;+ let textureAfter = 0;+ for (const t of textures) {+ const byteSize = Number(t?.byteSize) || 0;+ textureBytes += byteSize;+ if (byteSize <= 0) continue;+ const maxDim = Math.max(Number(t?.width) || 0, Number(t?.height) || 0);+ // Downscale oversized textures to the web target; area scales by the square.+ let after = byteSize;+ if (maxDim > TARGET_TEXTURE_DIM) {+ const ratio = (TARGET_TEXTURE_DIM / maxDim) ** 2;+ after = after * ratio;+ }+ // KTX2 / Basis transcode — already-compressed GPU formats are left as-is.+ const mime = String(t?.mimeType || '').toLowerCase();+ if (mime === 'image/png') after *= KTX2_RETAINED_PNG;+ else if (mime === 'image/jpeg' || mime === 'image/jpg') after *= KTX2_RETAINED_JPEG;+ textureAfter += after;+ }+ textureAfter = Math.round(textureAfter);++ // ── Everything else (animations, accessors, JSON) — left unchanged ─────────+ const otherBytes = Math.max(0, fileSize - geomBytes - textureBytes);++ let optimized = geomAfter + textureAfter + otherBytes;+ // Sanity clamp: a real-world re-encode rarely drops a complex model below 10%+ // of its original weight, and can never exceed it.+ optimized = Math.min(fileSize, Math.max(optimized, Math.round(fileSize * 0.10)));++ const savings = Math.max(0, fileSize - optimized);+ const savingsPct = fileSize > 0 ? (savings / fileSize) * 100 : 0;++ const loadBeforeMs = Math.round((fileSize / REFERENCE_BYTES_PER_SEC) * 1000);+ const loadAfterMs = Math.round((optimized / REFERENCE_BYTES_PER_SEC) * 1000);+ const loadImprovementPct = loadBeforeMs > 0 ? ((loadBeforeMs - loadAfterMs) / loadBeforeMs) * 100 : 0;++ return {+ fileSize,+ vertices,+ triangles,+ textureCount: textures.length,+ textureBytes,+ alreadyCompressed,+ estimatedOptimizedBytes: optimized,+ estimatedSavingsBytes: savings,+ savingsPct: Number(savingsPct.toFixed(2)),+ loadBeforeMs,+ loadAfterMs,+ loadImprovementPct: Number(loadImprovementPct.toFixed(2)),+ };+}++// Build the MCP JSON-RPC tools/call body for optimize_model.+function buildMcpBody(modelUrl) {+ return {+ jsonrpc: '2.0',+ id: randomUUID(),+ method: 'tools/call',+ params: { name: 'optimize_model', arguments: { url: modelUrl } },+ };+}++// Pull { suggestions, info } out of the (possibly batched) MCP response.+function parseOptimizeResult(responseBody) {+ const msg = Array.isArray(responseBody) ? responseBody[0] : responseBody;+ const sc = msg?.result?.structuredContent;+ if (sc && (sc.info || sc.suggestions)) {+ return { suggestions: Array.isArray(sc.suggestions) ? sc.suggestions : [], info: sc.info || null };+ }+ return null;+}++async function recordDetailRow(runId, fields) {+ const {+ serviceName, endpointUrl, amountAtomic, txSig, responseData,+ valueExtracted, durationMs, success, errorMsg,+ } = fields;+ 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'}, ${serviceName}, ${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('glb_opt_log_insert_failed', { message: err?.message });+ }+}++async function persistOptimization(runId, target, modelUrl, parsed, projection, amountAtomic, txSig) {+ const suggestionIds = parsed.suggestions.map((s) => s?.id).filter(Boolean);+ await sql`+ INSERT INTO glb_optimizations+ (avatar_id, slug, name, source_url, original_bytes,+ estimated_optimized_bytes, estimated_savings_bytes, savings_pct,+ load_ms_before, load_ms_after, load_improvement_pct,+ triangles, vertices, texture_count, texture_bytes,+ suggestion_ids, suggestions, info, run_id, tx_signature, amount_atomic)+ VALUES+ (${target.id}, ${target.slug}, ${target.name}, ${modelUrl}, ${projection.fileSize},+ ${projection.estimatedOptimizedBytes}, ${projection.estimatedSavingsBytes}, ${projection.savingsPct},+ ${projection.loadBeforeMs}, ${projection.loadAfterMs}, ${projection.loadImprovementPct},+ ${projection.triangles}, ${projection.vertices}, ${projection.textureCount}, ${projection.textureBytes},+ ${suggestionIds}, ${JSON.stringify(parsed.suggestions)}, ${JSON.stringify(parsed.info)},+ ${runId}, ${txSig || null}, ${amountAtomic || 0})+ `;+}++/**+ * Run the optimizer: pick a heavy GLB, pay the optimize_model call, project the+ * savings, and persist. Never throws — every fault is caught, logged, recorded,+ * and returned as a structured outcome for the loop's summary row.+ *+ * @param {object} [ctx] loop-supplied payment context. When buyer/conn/blockhash+ * /mintInfo are absent (manual test) the context is bootstrapped here.+ * @returns {Promise<object>} { success, amountAtomic, txSig, responseData,+ * signalData, skipped, note, errorMsg }+ */+export async function run(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const endpointUrl = `${origin}/api/mcp`;+ const remainingCap = Number.isFinite(ctx.remainingCap) ? ctx.remainingCap : Infinity;+ const t0 = Date.now();++ try {+ await ensureOptimizationSchema();+ } catch { /* ensureOptimizationSchema already swallows */ }++ // 1. Pick a target. No heavy GLB → nothing to do (no payment, no error).+ let target;+ try {+ target = await pickTarget();+ } catch (err) {+ log.warn('glb_opt_target_query_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `target_query_failed: ${err?.message}` };+ }+ if (!target) {+ return { success: true, skipped: true, amountAtomic: 0, note: 'no_oversized_glb', responseData: { reason: 'catalog_clear' } };+ }++ const modelUrl = publicUrl(target.storage_key);+ const serviceName = `GLB Size Optimizer: ${target.name || target.slug || target.id}`;++ // 2. Ensure we have a payment context (bootstrap when called standalone).+ let buyer = ctx.buyer, conn = ctx.conn, blockhash = ctx.blockhash, mintInfo = ctx.mintInfo;+ if (!buyer || !conn || !blockhash || !mintInfo) {+ try {+ loadSeedKeypair(); // fail fast + clearly if the wallet is unconfigured+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext());+ } catch (err) {+ log.info('glb_opt_skipped', { reason: err?.message });+ await recordDetailRow(runId, {+ serviceName, endpointUrl, amountAtomic: 0, txSig: null, responseData: null,+ valueExtracted: null, durationMs: Date.now() - t0, success: false,+ errorMsg: err?.message || 'wallet_or_rpc_unconfigured',+ });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: err?.message, note: 'wallet_or_rpc_unconfigured' };+ }+ }++ // 3. Pay the optimize_model call (real on-chain x402).+ let result;+ try {+ result = await payX402({+ url: endpointUrl,+ method: 'POST',+ body: buildMcpBody(modelUrl),+ buyer, conn, blockhash, mintInfo,+ remainingCap,+ userAgent: 'threews-glb-optimizer/1.0',+ });+ } catch (err) {+ await recordDetailRow(runId, {+ serviceName, endpointUrl, amountAtomic: 0, txSig: null, responseData: null,+ valueExtracted: null, durationMs: Date.now() - t0, success: false,+ errorMsg: err?.message || 'pay_failed',+ });+ return { success: false, skipped: false, amountAtomic: 0, errorMsg: err?.message || 'pay_failed' };+ }++ const parsed = result.success ? parseOptimizeResult(result.responseBody) : null;++ // 4. On a successful, parseable response: project + persist the value.+ if (result.success && parsed?.info) {+ let projection;+ try {+ projection = projectOptimization(parsed.info, target.size_bytes);+ await persistOptimization(runId, target, modelUrl, parsed, projection, result.amountAtomic, result.txSig);+ } catch (err) {+ log.warn('glb_opt_persist_failed', { id: target.id, message: err?.message });+ }++ const valueExtracted = projection ? {+ avatar_id: target.id,+ slug: target.slug,+ original_bytes: projection.fileSize,+ estimated_optimized_bytes: projection.estimatedOptimizedBytes,+ estimated_savings_bytes: projection.estimatedSavingsBytes,+ savings_pct: projection.savingsPct,+ load_improvement_pct: projection.loadImprovementPct,+ suggestions: parsed.suggestions.map((s) => s?.id).filter(Boolean),+ already_compressed: projection.alreadyCompressed,+ } : null;++ await recordDetailRow(runId, {+ serviceName, endpointUrl, amountAtomic: result.amountAtomic, txSig: result.txSig,+ responseData: { status: result.status, filename: parsed.info?.filename, suggestion_count: parsed.suggestions.length },+ valueExtracted, durationMs: Date.now() - t0, success: true, errorMsg: null,+ });++ log.info('glb_opt_complete', {+ run_id: runId, avatar_id: target.id, original_mb: (projection?.fileSize / 1048576).toFixed(2),+ savings_pct: projection?.savingsPct, amount_usdc: (result.amountAtomic / 1e6).toFixed(4),+ });++ return {+ success: true,+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ responseData: { avatar_id: target.id, slug: target.slug, ...valueExtracted },+ signalData: valueExtracted,+ note: projection+ ? `glb_optimizer saved≈${projection.savingsPct}% (${(projection.estimatedSavingsBytes / 1048576).toFixed(1)}MB) on ${target.slug || target.id}`+ : 'optimize_model ok (no projection)',+ };+ }++ // 5. Paid but unparseable, or the call failed / was rejected / capped.+ const errorMsg = result.errorMsg || (parsed ? 'no_inspection_info' : 'unparseable_response');+ await recordDetailRow(runId, {+ serviceName, endpointUrl, amountAtomic: result.amountAtomic || 0, txSig: result.txSig,+ responseData: result.responseBody ? { status: result.status, error: result.responseBody?.error || null } : null,+ valueExtracted: null, durationMs: Date.now() - t0, success: false, errorMsg,+ });+ return {+ success: false,+ skipped: !!result.skipped,+ amountAtomic: result.amountAtomic || 0,+ txSig: result.txSig || null,+ errorMsg,+ note: result.skipped ? `skipped:${errorMsg}` : undefined,+ };+}++/**+ * Downstream read: catalog-wide optimization summary. Consumed by+ * GET /api/x402/glb-optimization-report.+ *+ * Reports the average projected size + load-time improvement across every model+ * analyzed in the window, the total bytes the catalog would shed, and the+ * remaining backlog of heavy GLBs not yet analyzed.+ */+export async function readCatalogOptimizationSummary({ windowDays = 90, limit = 25 } = {}) {+ await ensureOptimizationSchema();++ // Latest analysis per avatar within the window.+ const latest = await sql`+ SELECT DISTINCT ON (avatar_id)+ avatar_id, slug, name, source_url, original_bytes,+ estimated_optimized_bytes, estimated_savings_bytes, savings_pct,+ load_ms_before, load_ms_after, load_improvement_pct,+ suggestion_ids, analyzed_at+ FROM glb_optimizations+ WHERE analyzed_at > now() - (${windowDays} || ' days')::interval+ ORDER BY avatar_id, analyzed_at DESC+ `;++ const analyzedCount = latest.length;+ const totalOriginal = latest.reduce((s, r) => s + Number(r.original_bytes || 0), 0);+ const totalOptimized = latest.reduce((s, r) => s + Number(r.estimated_optimized_bytes || 0), 0);+ const totalSavings = Math.max(0, totalOriginal - totalOptimized);+ const avgSavingsPct = analyzedCount+ ? latest.reduce((s, r) => s + Number(r.savings_pct || 0), 0) / analyzedCount : 0;+ const avgLoadImprovementPct = analyzedCount+ ? latest.reduce((s, r) => s + Number(r.load_improvement_pct || 0), 0) / analyzedCount : 0;++ // Remaining backlog of oversized, not-recently-analyzed GLBs.+ let backlog = 0;+ try {+ const [row] = await sql`+ SELECT count(*)::int AS n+ FROM avatars a+ LEFT JOIN glb_optimizations g+ ON g.avatar_id = a.id+ AND g.analyzed_at > now() - (${ANALYZE_TTL_DAYS} || ' days')::interval+ WHERE a.deleted_at IS NULL+ AND a.visibility = 'public'+ AND a.storage_key IS NOT NULL+ AND a.storage_key ILIKE '%.glb'+ AND a.size_bytes > ${SIZE_THRESHOLD_BYTES}+ AND g.id IS NULL+ `;+ backlog = row?.n || 0;+ } catch { /* avatars table absent in some envs */ }++ const top = latest+ .slice()+ .sort((a, b) => Number(b.estimated_savings_bytes || 0) - Number(a.estimated_savings_bytes || 0))+ .slice(0, limit)+ .map((r) => ({+ avatar_id: r.avatar_id,+ slug: r.slug,+ name: r.name,+ original_bytes: Number(r.original_bytes),+ estimated_optimized_bytes: Number(r.estimated_optimized_bytes),+ estimated_savings_bytes: Number(r.estimated_savings_bytes),+ savings_pct: Number(r.savings_pct),+ load_ms_before: r.load_ms_before,+ load_ms_after: r.load_ms_after,+ load_improvement_pct: Number(r.load_improvement_pct),+ suggestions: r.suggestion_ids || [],+ analyzed_at: r.analyzed_at,+ }));++ return {+ ok: true,+ window_days: windowDays,+ analyzed_count: analyzedCount,+ backlog_count: backlog,+ total_original_bytes: totalOriginal,+ total_optimized_bytes: totalOptimized,+ total_savings_bytes: totalSavings,+ total_savings_mb: Number((totalSavings / 1048576).toFixed(2)),+ avg_savings_pct: Number(avgSavingsPct.toFixed(2)),+ avg_load_improvement_pct: Number(avgLoadImprovementPct.toFixed(2)),+ reference_bandwidth_bytes_per_sec: REFERENCE_BYTES_PER_SEC,+ models: top,+ };+}diff --git a/api/_lib/x402/granite-health.js b/api/_lib/x402/granite-health.jsindex 741a82ca7..dc22ed43e 100644--- a/api/_lib/x402/granite-health.js+++ b/api/_lib/x402/granite-health.js@@ -26,9 +26,17 @@import { sql } from '../db.js';import { logger } from '../usage.js';+import { payX402, bootstrapSolanaContext } from './pay.js';const log = logger('granite-health');+// One paid batch covers all five tools; this is the advertised sum the IBM MCP+// server charges (chat 0.02 + code 0.025 + embed 0.005 + analyze 0.04 ++// forecast 0.05 = 0.14 USDC). The real amount paid still comes from the live 402+// challenge — this is the budgeting/expectation value the registry advertises.+export const GRANITE_HEALTH_PRICE_ATOMIC = 140_000;+export const GRANITE_HEALTH_ENDPOINT = '/api/ibm-mcp';+export const GRANITE_SERVER = 'ibm-x402-mcp';// The five paid Granite tools this health check exercises, in batch order. The@@ -121,6 +129,96 @@ function graniteHealthMessage(toolName) {// The full batch body the autonomous-loop entry sends as its `body`. Built once.export const GRANITE_HEALTH_BATCH = GRANITE_HEALTH_TOOLS.map(graniteHealthMessage);+/**+ * Run the IBM Granite inference health check: pay ONE real x402 batch call to+ * /api/ibm-mcp exercising all five Granite tools, summarise the response, and+ * persist the verdict to granite_inference_health.+ *+ * Wired as the `granite-inference-health` registry entry's run(). The autonomous+ * loop hands it { origin, buyer, conn, blockhash, mintInfo, redis, sql, log,+ * runId, remainingCap } and records the returned aggregate to x402_autonomous_log.+ * Also directly invocable for manual testing: with no Solana context in ctx it+ * bootstraps its own (loads the seed keypair, fetches a blockhash + mint).+ *+ * Never throws — every failure mode (wallet unconfigured, network timeout, 402+ * rejection, DB error) is caught and returned as a structured, recorded outcome+ * so the loop tick cannot crash.+ *+ * @param {object} [ctx] loop run() ctx (all fields optional for standalone use)+ * @returns {Promise<object>} { success, skipped, amountAtomic, txSig, errorMsg,+ * responseData, signalData, note }+ */+export async function runGraniteHealth(ctx = {}) {+ const ctxLog = ctx.log || log;+ const origin = ctx.origin || 'https://three.ws';+ const url = `${origin}${GRANITE_HEALTH_ENDPOINT}`;+ const dbClient = ctx.sql || sql;++ // Resolve the Solana payment context — reuse the loop's shared one, or+ // bootstrap a fresh context for a standalone/manual call. A missing seed+ // keypair surfaces here as a graceful skip (never a thrown tick).+ let { buyer, conn, blockhash, mintInfo } = ctx;+ if (!buyer || !conn || !blockhash || !mintInfo) {+ try {+ const boot = await bootstrapSolanaContext({ buyer });+ ({ buyer, conn, blockhash, mintInfo } = boot);+ } catch (err) {+ ctxLog.warn('granite_health_wallet_unconfigured', { message: err?.message });+ return {+ success: false, skipped: true, amountAtomic: 0, txSig: null,+ errorMsg: err?.message || 'wallet_unconfigured',+ note: 'granite-health skipped: payer wallet not configured',+ };+ }+ }++ const t0 = Date.now();+ let pay;+ try {+ pay = await payX402({+ url, method: 'POST', body: GRANITE_HEALTH_BATCH,+ buyer, conn, blockhash, mintInfo,+ remainingCap: ctx.remainingCap ?? Infinity,+ });+ } catch (err) {+ // Network timeout / RPC failure / transport error.+ ctxLog.warn('granite_health_call_failed', { message: err?.message });+ return {+ success: false, skipped: false, amountAtomic: 0, txSig: null,+ errorMsg: err?.message || 'granite_call_failed',+ note: 'granite-health call failed before settlement',+ };+ }+ const durationMs = Date.now() - t0;++ const summary = summarizeGraniteHealth(pay.responseBody);++ // Extract + store value only when the call actually settled (or was free).+ if (pay.success) {+ try {+ await storeGraniteHealth({+ sql: dbClient, responseBody: pay.responseBody,+ signalData: summary, runId: ctx.runId, durationMs,+ });+ } catch (err) {+ // DB failure must not fail the paid call — it already succeeded on-chain.+ ctxLog.warn('granite_health_store_failed', { message: err?.message });+ }+ }++ const degraded = pay.success && summary.tools_failed > 0;+ return {+ success: pay.success,+ skipped: pay.skipped || false,+ amountAtomic: pay.success ? pay.amountAtomic : 0,+ txSig: pay.txSig || null,+ errorMsg: pay.errorMsg || (degraded ? `granite_tools_failed:${summary.tools_failed}` : null),+ responseData: { granite_health: summary, http_status: pay.status },+ signalData: summary,+ note: `granite ${summary.tools_ok}/${summary.tools_total} ok · ${summary.total_tokens} tok · ${durationMs}ms`,+ };+}+// Token usage is OpenAI-shaped on watsonx chat (prompt_tokens/completion_tokens/// total_tokens). Read defensively in case a model returns the older// input_token_count/generated_token_count naming.diff --git a/api/_lib/x402/mcp-latency-sweep.js b/api/_lib/x402/mcp-latency-sweep.jsindex cba6311d7..6d69aabcf 100644--- a/api/_lib/x402/mcp-latency-sweep.js+++ b/api/_lib/x402/mcp-latency-sweep.js@@ -222,7 +222,7 @@ export async function mcpLatencySweep(ctx = {}) {const rows = await sql`SELECT tool_name, sample_msFROM x402_perf_log- WHERE ts > now() - (${WINDOW_HOURS} || ' hours')::interval+ WHERE ts > now() - make_interval(hours => ${WINDOW_HOURS})`;for (const r of rows) {const arr = history.get(r.tool_name) || [];@@ -297,13 +297,14 @@ export async function mcpLatencySweep(ctx = {}) {*/export async function readPerfHealth({ windowHours = WINDOW_HOURS } = {}) {await ensurePerfSchema();+ const hours = Math.max(1, Math.floor(Number(windowHours) || WINDOW_HOURS));// Latest row per tool (most recent percentile snapshot).const rows = await sql`SELECT DISTINCT ON (tool_name)tool_name, ts, sample_ms, observed_status, priced,p50_ms, p95_ms, p99_ms, sample_count, sla_breach, errorFROM x402_perf_log- WHERE ts > now() - (${windowHours} || ' hours')::interval+ WHERE ts > now() - make_interval(hours => ${hours})ORDER BY tool_name, ts DESC`;const tools = rows.map((r) => ({@@ -324,7 +325,7 @@ export async function readPerfHealth({ windowHours = WINDOW_HOURS } = {}) {ok: true,healthy: breaches.length === 0,sla_p95_ms: PERF_SLA_P95_MS,- window_hours: windowHours,+ window_hours: hours,tool_count: tools.length,breach_count: breaches.length,breaches: breaches.map((b) => ({ tool: b.tool, p95_ms: b.p95_ms, samples: b.samples })),diff --git a/api/_lib/x402/pay.js b/api/_lib/x402/pay.jsindex 46cd77999..58b38e840 100644--- a/api/_lib/x402/pay.js+++ b/api/_lib/x402/pay.js@@ -139,6 +139,7 @@ export async function payX402({buyer, conn, blockhash, mintInfo,remainingCap = Infinity,userAgent = 'threews-x402-autonomous/1.0',+ nonce = 0,}) {const reqInit = {method,@@ -185,6 +186,7 @@ export async function payX402({const txBase64 = buildPaymentTx({accept, buyer, blockhash, mintInfo,receiverAtaExists: receiverAtaInfo !== null,+ nonce,});const xPayment = Buffer.from(JSON.stringify({x402Version: 2,diff --git a/api/_lib/x402/pipelines/avatar-search-warmup.js b/api/_lib/x402/pipelines/avatar-search-warmup.jsnew file mode 100644index 000000000..6084e9ef8--- /dev/null+++ b/api/_lib/x402/pipelines/avatar-search-warmup.js@@ -0,0 +1,250 @@+// api/_lib/x402/pipelines/avatar-search-warmup.js+//+// Avatar Search Index Warmup — autonomous pipeline (self/003).+//+// On each run it pays for ~20 common gallery searches against the three.ws MCP+// server (/api/mcp → search_public_avatars). Each call is a real on-chain USDC+// payment from the seed wallet at the advertised $0.001/call. The pipeline:+//+// 1. Probes + pays each search via the shared payX402 client (real x402,+// never mocked). A per-call nonce keeps the 20 identical-amount payments+// distinct on-chain (otherwise equal transfers collide on one signature).+// 2. Validates the full search path returned ranked results WITH resolved+// thumbnails — the warmup's real job is to prove the pipeline (DB query →+// rig classifier → signed-thumbnail resolution) is live end-to-end.+// 3. Records a row in x402_autonomous_log for every call (success or failure),+// with the parsed result summary in value_extracted.+// 4. Upserts each query's ranked, thumbnail-resolved slice into+// avatar_search_warm_cache for the gallery's popular-search chips.+//+// 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().+//+// Downstream consumer: GET /api/avatars/popular-searches reads+// avatar_search_warm_cache (via getPopularSearches) to render "popular search"+// suggestion chips — with a sample thumbnail per query — on the public gallery,+// and lets the gallery paint instant cached results for a common query before+// the live DB round-trip returns.++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 { ensureWarmCacheSchema, upsertWarmedSearch } from '../../avatar-search-warm.js';++const log = logger('x402-avatar-search-warmup');++// Common entry-point queries an agent or a first-time gallery visitor would type.+// Broad coverage of the public corpus exercises the whole ranking path and tells+// the gallery which queries surface the most inventory.+export const WARMUP_QUERIES = Object.freeze([+ 'human', 'robot', 'anime', 'warrior', 'woman', 'man', 'dragon', 'cat',+ 'knight', 'ninja', 'alien', 'zombie', 'fantasy', 'sci-fi', 'cyberpunk',+ 'animal', 'monster', 'hero', 'mascot', 'character',+]);++const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// Anonymous x402 callers are capped at 10 results by the tool (bulk-enumeration+// guard in api/_mcp/tools/avatars.js); request exactly that.+function jsonRpcSearch(query, id) {+ return {+ jsonrpc: '2.0',+ id,+ method: 'tools/call',+ params: { name: 'search_public_avatars', arguments: { q: query, limit: 10 } },+ };+}++// Pull the ranked, render-ready slice out of an MCP tools/call response.+// Returns { topResults, thumbnails, resultCount, hasResult }. hasResult is false+// when the call errored or carried no structured avatars.+export function extractWarmValue(responseBody) {+ const sc = responseBody?.result?.structuredContent;+ const avatars = Array.isArray(sc?.avatars) ? sc.avatars : null;+ if (!avatars) return { topResults: [], thumbnails: [], resultCount: 0, hasResult: false };+ const topResults = avatars.slice(0, 8).map((a) => ({+ id: a?.id || null,+ name: a?.name || null,+ slug: a?.slug || null,+ thumbnail_url: a?.thumbnail_url || null,+ }));+ const thumbnails = topResults.map((r) => r.thumbnail_url).filter(Boolean);+ return { topResults, thumbnails, resultCount: avatars.length, hasResult: true };+}++async function ensureSchema() {+ await ensureWarmCacheSchema();+ // The autonomous log predates the run()-style pipelines; ensure the+ // value_extracted column the warmup records its parsed summary into exists+ // (idempotent; the bazaar pipeline adds the same column).+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+}++// Per-call row into x402_autonomous_log. The loop also records one aggregate+// summary row for the run() entry; these are the granular per-query rows.+async function recordCall(runId, { query, 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'}, ${`Avatar Search Warmup: ${query}`}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'discovery'})+ `;+ } catch (err) {+ log.warn('avatar_warmup_log_insert_failed', { query, message: err?.message });+ }+}++/**+ * Run the warmup. Conforms to the run()-style registry contract: the loop hands+ * over { origin, buyer, conn, blockhash, mintInfo, remainingCap, runId }; when+ * any Solana context is absent (standalone / manual test) it bootstraps its own+ * via bootstrapSolanaContext().+ *+ * 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}/api/mcp`;+ let 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('avatar_warmup_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('avatar_warmup_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 warmed = 0;+ let withThumbnails = 0;+ let callErrors = 0;+ let lastTxSig = null;++ for (let i = 0; i < WARMUP_QUERIES.length; i++) {+ const query = WARMUP_QUERIES[i];+ if (remainingCap <= 0) {+ log.info('avatar_warmup_cap_reached', { query, spent_atomic: spentAtomic });+ break;+ }++ const t0 = Date.now();+ let result;+ try {+ result = await payX402({+ url: endpointUrl,+ method: 'POST',+ body: jsonRpcSearch(query, i + 1),+ buyer, conn, blockhash, mintInfo,+ remainingCap,+ // Distinct priority fee per call so the 20 equal-amount payments+ // don't collide on one transaction signature.+ nonce: i + 1,+ });+ } catch (err) {+ // Network failure / abort — log the call, never crash the sweep.+ callErrors += 1;+ await recordCall(runId, {+ query, endpointUrl, amountAtomic: 0, txSig: null, responseData: null,+ durationMs: Date.now() - t0, success: false, errorMsg: err?.message || 'fetch_failed', valueExtracted: null,+ });+ continue;+ }++ const value = extractWarmValue(result.responseBody);++ // Store the warmed slice only when the call delivered structured avatars+ // (paid or free success). Failed / 402-rejected calls still get a log row.+ if (result.success && value.hasResult) {+ const stored = await upsertWarmedSearch({+ query,+ resultCount: value.resultCount,+ topResults: value.topResults,+ thumbnails: value.thumbnails,+ runId,+ });+ if (stored) warmed += 1;+ if (value.thumbnails.length > 0) withThumbnails += 1;+ } else {+ callErrors += 1;+ }++ if (result.paid) {+ spentAtomic += result.amountAtomic;+ remainingCap -= result.amountAtomic;+ paid += 1;+ if (result.txSig) lastTxSig = result.txSig;+ }++ await recordCall(runId, {+ query,+ endpointUrl,+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ // Keep the audit row lean: the warm-cache row holds the avatar slice;+ // here we keep just the call status and any rpc-level error.+ responseData: { status: result.status, count: value.resultCount, has_thumbnails: value.thumbnails.length > 0, rpc_error: result.responseBody?.error || null },+ durationMs: Date.now() - t0,+ success: result.success && value.hasResult,+ errorMsg: result.errorMsg || (result.success && !value.hasResult ? 'no_structured_avatars' : null),+ valueExtracted: value.hasResult+ ? { result_count: value.resultCount, thumbnails: value.thumbnails.length, sample: value.topResults.slice(0, 3) }+ : null,+ });+ }++ log.info('avatar_warmup_complete', {+ run_id: runId,+ queries: WARMUP_QUERIES.length,+ paid,+ warmed,+ with_thumbnails: withThumbnails,+ errors: callErrors,+ spent_usdc: (spentAtomic / 1e6).toFixed(4),+ });++ // Aggregate outcome for the loop's single summary row. success=true when at+ // least one query warmed the cache; per-call detail lives in the rows above.+ return {+ success: warmed > 0,+ amountAtomic: spentAtomic,+ txSig: lastTxSig,+ errorMsg: warmed === 0 ? `avatar_warmup_no_results:errors=${callErrors}` : null,+ skipped: paid === 0 && warmed === 0,+ responseData: {+ queries: WARMUP_QUERIES.length,+ paid,+ warmed,+ with_thumbnails: withThumbnails,+ errors: callErrors,+ },+ note: `avatar_warmup paid=${paid} warmed=${warmed} thumbs=${withThumbnails}`,+ };+}diff --git a/api/_lib/x402/pipelines/cosmetic-pricing-audit.js b/api/_lib/x402/pipelines/cosmetic-pricing-audit.jsindex 62c7dd657..d20dc6592 100644--- a/api/_lib/x402/pipelines/cosmetic-pricing-audit.js+++ b/api/_lib/x402/pipelines/cosmetic-pricing-audit.js@@ -45,7 +45,7 @@ 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 { buildCatalog } from '../../cosmetics.js';import { normalizeAccountId } from '../../cosmetics-ownership.js';import {loadSeedKeypair,diff --git a/api/_lib/x402/pipelines/fee-calculation-validator.js b/api/_lib/x402/pipelines/fee-calculation-validator.jsnew file mode 100644index 000000000..be420540e--- /dev/null+++ b/api/_lib/x402/pipelines/fee-calculation-validator.js@@ -0,0 +1,403 @@+// api/_lib/x402/pipelines/fee-calculation-validator.js+//+// Fee Calculation Validator — autonomous pipeline (self/028).+//+// USDC is a 6-decimal asset: every x402 price the platform quotes is an integer+// number of atomic units, and every price it DISPLAYS is that integer divided by+// 1_000_000. The conversion both ways is the platform's single most safety-+// critical bit of arithmetic — an off-by-one or a float-rounding slip in+// atomic↔decimal means buyers get over- or under-charged on every paid call.+//+// This validator exercises the REAL production conversion functions+// (usdcToAtomics / atomicsToUsdc in api/_lib/agent-paid-services.js, the same+// ones every paid endpoint and the monetize_endpoint tool use to build their 402+// challenge amount and render prices) at the boundary atomics where rounding bugs+// hide: 1 ($0.000001 — the minimum), 999 / 1000 / 1001 (the milli-dollar tier+// edge), and 999999 (just under $1). For each boundary it asserts two things:+//+// 1. RENDER — atomicsToUsdc(B).toFixed(6) equals the BigInt ground-truth+// decimal string (integer math, no float). Catches precision drift.+// 2. ROUND-TRIP — usdcToAtomics(that decimal) returns exactly B. Catches the+// off-by-one class (e.g. a Math.floor regression that drops a unit).+//+// Then it makes ONE real on-chain payment: the $0.001 dance-tip endpoint quotes+// exactly 1000 atomics (priceFor('dance-tip')), which IS one of the boundaries,+// so a live probe→pay→settle proves the deployed quote and the settled amount+// agree with the local fee math end-to-end (deploy/env skew a same-process unit+// test can't see). Real USDC from the seed wallet, never mocked.+//+// Tables:+// fee_calculation_audit — one row per boundary per run. Columns receiving the+// extracted value: boundary_atomic, expected_decimal,+// rendered_decimal, round_trip_atomic, mismatch, kind,+// tx_signature, error.+// x402_autonomous_log — one summary row per run; value_extracted carries+// { boundaries, mismatch_count, mismatched,+// live_quoted_atomic, live_settled_atomic,+// live_consistent }.+//+// Downstream consumer: fee_calculation_audit is the fee-integrity audit trail.+// Ops gates deploys on it alongside cosmetic_pricing_audit (self/020) — a+// `mismatch=true` row is the signal that an atomic↔decimal change would mis-bill+// buyers and must be held. The latest per-boundary state answers "does the+// deployed fee math still convert every tier exactly".++import { randomUUID } from 'node:crypto';++import { sql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { usdcToAtomics, atomicsToUsdc } from '../../agent-paid-services.js';+import { priceFor } from '../../x402-prices.js';+import {+ loadSeedKeypair,+ bootstrapSolanaContext,+ payX402,+ fetchWithTimeout,+ parseSolanaAccept,+ USDC_MINT,+} from '../pay.js';++const log = logger('x402-fee-calculation-validator');++// Boundary atomics where atomic↔decimal rounding bugs surface (USDC, 6 decimals):+// 1 — the $0.000001 minimum (one atomic)+// 999 — just below the milli-dollar tier+// 1000 — exactly $0.001 (the dance-tip live-payment boundary)+// 1001 — just above the milli-dollar tier+// 999999 — just below $1.00+const BOUNDARY_ATOMICS = [1, 999, 1000, 1001, 999999];++// The live boundary we actually settle on-chain. dance-tip quotes exactly $0.001+// (1000 atomics) via priceFor — one of the boundaries above — so a real payment+// closes the loop on the deployed quote vs. the local fee math.+const LIVE_ROUTE = '/api/x402/dance-tip';+const LIVE_BODY = { dancer: '1', dance: 'hiphop' };+const LIVE_EXPECTED_ATOMIC = Number(priceFor('dance-tip', '1000'));++const MINT = () => USDC_MINT || env.X402_ASSET_MINT_SOLANA || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// BigInt ground-truth: integer atomic → fixed 6-decimal string, no float anywhere.+// 1 → "0.000001", 1000 → "0.001000", 999999 → "0.999999", 1000000 → "1.000000".+// This is the reference the float-based platform render is checked against.+export function atomicToDecimalString(atomic) {+ const n = BigInt(atomic);+ const whole = n / 1_000_000n;+ const frac = n % 1_000_000n;+ return `${whole}.${frac.toString().padStart(6, '0')}`;+}++// Validate one boundary atomic through the real production conversion functions.+// Pure — no I/O, never throws (a thrown usdcToAtomics is captured as the error).+export function validateBoundary(atomic) {+ const expectedDecimal = atomicToDecimalString(atomic);++ // 1) RENDER: the platform's atomic→decimal path must format to the ground truth.+ let renderedDecimal = null;+ let renderOk = false;+ try {+ renderedDecimal = atomicsToUsdc(atomic).toFixed(6);+ renderOk = renderedDecimal === expectedDecimal;+ } catch (err) {+ return {+ boundaryAtomic: atomic,+ expectedDecimal,+ renderedDecimal,+ roundTripAtomic: null,+ mismatch: true,+ error: `render_threw: ${err?.message || 'error'}`,+ };+ }++ // 2) ROUND-TRIP: decimal→atomic must land back exactly on the boundary.+ let roundTripAtomic = null;+ let roundTripOk = false;+ let error = null;+ try {+ roundTripAtomic = Number(usdcToAtomics(expectedDecimal));+ roundTripOk = roundTripAtomic === atomic;+ } catch (err) {+ error = `round_trip_threw: ${err?.message || 'error'}`;+ }++ const mismatch = !renderOk || !roundTripOk;+ if (mismatch && !error) {+ error = !renderOk+ ? `render_mismatch: got ${renderedDecimal} want ${expectedDecimal}`+ : `round_trip_mismatch: got ${roundTripAtomic} want ${atomic}`;+ }++ return { boundaryAtomic: atomic, expectedDecimal, renderedDecimal, roundTripAtomic, mismatch, error };+}++async function ensureSchema() {+ await sql`+ CREATE TABLE IF NOT EXISTS fee_calculation_audit (+ id bigserial PRIMARY KEY,+ run_id uuid NOT NULL,+ ts timestamptz DEFAULT now(),+ boundary_atomic bigint NOT NULL,+ expected_decimal text NOT NULL,+ rendered_decimal text,+ round_trip_atomic bigint,+ mismatch boolean NOT NULL DEFAULT false,+ kind text NOT NULL DEFAULT 'math',+ tx_signature text,+ error text+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS fee_calculation_audit_boundary_ts ON fee_calculation_audit (boundary_atomic, ts DESC)`;+ await sql`CREATE INDEX IF NOT EXISTS fee_calculation_audit_mismatch ON fee_calculation_audit (mismatch) WHERE mismatch`;+ // x402_autonomous_log predates value_extracted; add it idempotently (mirrors+ // the cosmetic-pricing-audit + bazaar-warmup pipelines so they 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 fee_calculation_audit+ (run_id, boundary_atomic, expected_decimal, rendered_decimal,+ round_trip_atomic, mismatch, kind, tx_signature, error)+ VALUES+ (${runId}, ${row.boundaryAtomic}, ${row.expectedDecimal},+ ${row.renderedDecimal ?? null}, ${row.roundTripAtomic ?? null},+ ${!!row.mismatch}, ${row.kind || 'math'}, ${row.txSig || null},+ ${row.error || null})+ `;+ } catch (err) {+ log.warn('fee_calculation_audit_insert_failed', { boundary: row.boundaryAtomic, 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'}, ${'Fee Calculation Validator'}, ${LIVE_ROUTE},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${MINT()}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'finance'})+ `;+ } catch (err) {+ log.warn('fee_calculation_summary_failed', { run_id: runId, message: err?.message });+ }+}++// Free probe of the live endpoint's 402 challenge — reads the advertised atomic+// amount without paying. Never throws: a fault returns a null quote + reason.+async function probeLiveQuote(origin) {+ const url = `${origin}${LIVE_ROUTE}`;+ try {+ const res = await fetchWithTimeout(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'user-agent': 'threews-x402-autonomous/1.0' },+ body: JSON.stringify(LIVE_BODY),+ });+ if (res.status !== 402) {+ return { quotedAtomic: null, error: `unexpected_status_${res.status}` };+ }+ const accept = parseSolanaAccept(res.body);+ if (!accept) return { quotedAtomic: null, error: 'no_solana_accept' };+ const quoted = Number(accept.amount || 0);+ if (!Number.isFinite(quoted) || quoted <= 0) {+ return { quotedAtomic: null, error: `bad_quote:${accept.amount}` };+ }+ return { quotedAtomic: quoted, error: null };+ } catch (err) {+ return { quotedAtomic: null, error: err?.message || 'probe_failed' };+ }+}++/**+ * Run the fee-calculation 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 live 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.remainingCap] spend ceiling for this run (atomics)+ */+export async function run(ctx = {}) {+ const t0 = Date.now();+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;++ // Schema is the only durable sink — without it there's nothing to record to.+ try {+ await ensureSchema();+ } catch (err) {+ log.warn('fee_calculation_schema_failed', { message: err?.message });+ return {+ success: false, skipped: true, amountAtomic: 0, txSig: null,+ errorMsg: `schema_failed: ${err?.message}`, note: 'schema unavailable',+ };+ }++ // ── 1) Pure fee-math sweep over the boundaries (free, always runs) ──────────+ const findings = BOUNDARY_ATOMICS.map(validateBoundary);++ // ── 2) Live probe: read the deployed dance-tip quote (free) ────────────────+ const { quotedAtomic, error: probeError } = await probeLiveQuote(origin);+ // The deployed quote is itself a boundary check at 1000 atomics: it must equal+ // the local fee math's expected amount AND render to the ground-truth decimal.+ let liveQuoteMismatch = false;+ let liveQuoteError = probeError;+ if (quotedAtomic != null) {+ const expectedDecimal = atomicToDecimalString(quotedAtomic);+ const renderOk = atomicsToUsdc(quotedAtomic).toFixed(6) === expectedDecimal;+ const matchesExpected = quotedAtomic === LIVE_EXPECTED_ATOMIC;+ liveQuoteMismatch = !renderOk || !matchesExpected;+ if (liveQuoteMismatch && !liveQuoteError) {+ liveQuoteError = matchesExpected+ ? `render_mismatch: ${quotedAtomic}`+ : `deploy_skew: quoted ${quotedAtomic} want ${LIVE_EXPECTED_ATOMIC}`;+ }+ }++ // ── 3) One real on-chain payment at the 1000-atomic boundary ────────────────+ let buyer = ctx.buyer;+ let walletReason = null;+ if (!buyer) {+ try { buyer = loadSeedKeypair(); } catch (err) { walletReason = err.message; }+ }++ let settledAtomic = null;+ let liveSettleError = null;+ let txSig = null;+ let spentAtomic = 0;+ let payResponse = null;++ if (buyer && quotedAtomic != null && remainingCap >= quotedAtomic) {+ try {+ let { conn, blockhash, mintInfo } = ctx;+ if (!conn || !blockhash || !mintInfo) {+ const boot = await bootstrapSolanaContext({ buyer });+ conn = conn || boot.conn;+ blockhash = blockhash || boot.blockhash;+ mintInfo = mintInfo || boot.mintInfo;+ }+ const r = await payX402({+ url: `${origin}${LIVE_ROUTE}`,+ method: 'POST',+ body: LIVE_BODY,+ buyer, conn, blockhash, mintInfo,+ remainingCap,+ userAgent: 'threews-x402-fee-validator/1.0',+ });+ payResponse = r.responseBody || null;+ if (r.paid) {+ settledAtomic = r.amountAtomic || 0;+ txSig = r.txSig || null;+ spentAtomic = settledAtomic;+ // The settled amount MUST equal the advertised quote, else the fee+ // charged on-chain drifts from what the buyer was quoted.+ if (settledAtomic !== quotedAtomic) {+ liveSettleError = `settle_drift: settled ${settledAtomic} quoted ${quotedAtomic}`;+ }+ } else {+ liveSettleError = r.errorMsg || `settle_status_${r.status || 0}`;+ }+ } catch (err) {+ liveSettleError = err?.message || 'pay_failed';+ }+ } else if (!buyer) {+ log.info('fee_calculation_no_wallet', { reason: walletReason });+ } else if (quotedAtomic != null && remainingCap < quotedAtomic) {+ liveSettleError = 'cap_would_exceed';+ }++ const liveSettleMismatch = settledAtomic != null && settledAtomic !== quotedAtomic;++ // ── 4) Persist per-boundary findings (math sweep + the live boundary) ──────+ for (const f of findings) {+ await recordAuditRow(runId, { ...f, kind: 'math' });+ }+ // The live boundary lands as its own row: expected/rendered from the deployed+ // quote, round_trip_atomic = settled amount, tx = on-chain signature.+ if (quotedAtomic != null || probeError) {+ await recordAuditRow(runId, {+ boundaryAtomic: quotedAtomic ?? LIVE_EXPECTED_ATOMIC,+ expectedDecimal: atomicToDecimalString(LIVE_EXPECTED_ATOMIC),+ renderedDecimal: quotedAtomic != null ? atomicsToUsdc(quotedAtomic).toFixed(6) : null,+ roundTripAtomic: settledAtomic,+ mismatch: liveQuoteMismatch || liveSettleMismatch,+ kind: 'live',+ txSig,+ error: liveSettleError || liveQuoteError,+ });+ }++ // ── 5) Summary row in x402_autonomous_log (always, success or skip) ────────+ const mathMismatches = findings.filter((f) => f.mismatch);+ const mismatchCount = mathMismatches.length + (liveQuoteMismatch || liveSettleMismatch ? 1 : 0);+ const liveConsistent = quotedAtomic != null && !liveQuoteMismatch+ ? (settledAtomic != null ? settledAtomic === quotedAtomic : null)+ : false;++ const valueExtracted = {+ boundaries: findings.length,+ mismatch_count: mismatchCount,+ mismatched: mathMismatches.map((f) => ({ atomic: f.boundaryAtomic, error: f.error })),+ live_quoted_atomic: quotedAtomic,+ live_expected_atomic: LIVE_EXPECTED_ATOMIC,+ live_settled_atomic: settledAtomic,+ live_consistent: liveConsistent,+ live_error: liveSettleError || liveQuoteError || null,+ };++ // success = all boundary math holds AND (no payment attempted OR it settled at+ // the quoted amount). A wallet that's simply unconfigured is not a failure —+ // the deterministic math sweep is the primary signal and it still ran.+ const mathOk = mathMismatches.length === 0 && !liveQuoteMismatch;+ const settleOk = settledAtomic == null ? true : !liveSettleMismatch;+ const success = mathOk && settleOk && !probeError;+ const errorMsg = mismatchCount > 0+ ? `fee_mismatch:${mismatchCount}`+ : (probeError ? `probe:${probeError}` : (walletReason ? `wallet_unconfigured: ${walletReason}` : liveSettleError));++ await recordSummary(runId, {+ amountAtomic: spentAtomic,+ txSig,+ responseData: { quoted_atomic: quotedAtomic, settled_atomic: settledAtomic, live_response: payResponse },+ durationMs: Date.now() - t0,+ success,+ errorMsg,+ valueExtracted,+ });++ if (mismatchCount > 0) {+ log.warn('fee_calculation_mismatch', { run_id: runId, count: mismatchCount, mismatched: valueExtracted.mismatched });+ }+ log.info('fee_calculation_complete', {+ run_id: runId,+ boundaries: findings.length,+ mismatch: mismatchCount,+ live_quoted: quotedAtomic,+ live_settled: settledAtomic,+ spent_usdc: (spentAtomic / 1e6).toFixed(6),+ });++ return {+ success,+ amountAtomic: spentAtomic,+ txSig,+ network: 'solana:mainnet',+ responseData: valueExtracted,+ signalData: { mismatch_count: mismatchCount, live_consistent: liveConsistent },+ errorMsg,+ note: `boundaries ${findings.length}, mismatch ${mismatchCount}, live ${settledAtomic != null ? 'settled' : 'not_settled'}`,+ ...(walletReason ? { skipped: true } : {}),+ };+}diff --git a/api/_lib/x402/pipelines/live-feed-seeder.js b/api/_lib/x402/pipelines/live-feed-seeder.jsnew file mode 100644index 000000000..0e52b5a86--- /dev/null+++ b/api/_lib/x402/pipelines/live-feed-seeder.js@@ -0,0 +1,310 @@+// api/_lib/x402/pipelines/live-feed-seeder.js+//+// Live Payment Feed Seeder — autonomous pipeline (self/025).+//+// The homepage "live payment feed" (the /pay page, the in-world jumbotron and+// the exchange NPCs) reads from GET /api/x402-pay?feed=1, which is backed ONLY+// by the Redis ring `x402:pay:feed`. That ring is populated EXCLUSIVELY by real+// /api/x402-pay demo-flow payments — nothing else writes to it. With no organic+// demo traffic the feed goes stale and a first-time visitor sees a dead system.+//+// This pipeline keeps that feed alive: on each run it makes ONE real, on-chain+// $0.001 USDC demo payment through /api/x402-pay (the platform-wallet demo flow,+// signed by X402_AGENT_SOLANA_SECRET_BASE58 server-side), rotating across a set+// of MCP tools so the feed shows a variety of recent agent-to-agent activity+// (avatar searches, model inspections, validations, optimizations, capability+// discovery) rather than the same call repeated.+//+// Two sinks, both real:+// 1. The /api/x402-pay call itself pushes the receipt onto `x402:pay:feed`+// (the hot path the homepage actually renders) — that IS the live feed.+// 2. This module mirrors every successful receipt into `x402_demo_feed`+// (Postgres) — a durable, queryable history that survives the 50-entry+// Redis ring's eviction and feeds activity analytics.+//+// Wiring: declared as a run()-style entry in autonomous-registry.js. The+// per-tick loop (api/cron/x402-autonomous-loop.js) hands run() its shared+// context and records the single summary row (with value_extracted) to+// x402_autonomous_log. We never sign here — /api/x402-pay owns the payment — so+// the only Solana context this pipeline needs is the origin to call.+//+// Downstream consumers of the data written here:+// - Homepage / jumbotron / exchange-NPC live feed → GET /api/x402-pay?feed=1+// (Redis ring written by the demo call).+// - x402_demo_feed table → durable activity history + Redis-eviction backstop+// for the same feed; queryable for "recent live payments" analytics.++import { randomUUID } from 'node:crypto';++import { sql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { fetchWithTimeout, USDC_MINT } from '../pay.js';++const log = logger('x402-live-feed-seeder');++const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// Public rig-reference avatars served from three.ws/avatars/*.glb. The model+// tools (inspect/validate/optimize) fetch their `url` server-side through the+// SSRF-guarded safeFetchModel, so the target must be a public https URL — these+// are. (Defined locally rather than imported from autonomous-registry.js to keep+// the registry → pipeline import one-directional.)+const REFERENCE_AVATARS = ['michelle.glb', 'xbot.glb', 'cz.glb', 'realistic-male.glb', 'fox.glb'];++const avatarUrl = (origin, file) => `${origin}/avatars/${file}`;++// Rotation of demo calls. Every entry maps to one ALLOWED_TOOLS tool on+// /api/x402-pay (tools/list, validate_model, inspect_model, optimize_model,+// search_public_avatars) so the live feed shows varied, real agent activity.+// `topic` is the human label that lands in the feed mirror + value_extracted.+const SEED_ROTATION = [+ { tool: 'search_public_avatars', args: { q: 'robot', limit: 6 }, topic: 'avatar search · robot' },+ { tool: 'inspect_model', avatar: 'michelle.glb', topic: 'model inspect · michelle' },+ { tool: 'search_public_avatars', args: { q: 'dancer', limit: 6 }, topic: 'avatar search · dancer' },+ { tool: 'validate_model', avatar: 'xbot.glb', topic: 'model validate · xbot' },+ { tool: 'search_public_avatars', args: { q: 'anime', limit: 6 }, topic: 'avatar search · anime' },+ { tool: 'optimize_model', avatar: 'cz.glb', topic: 'model optimize · cz' },+ { tool: 'search_public_avatars', args: { q: 'character', limit: 6 }, topic: 'avatar search · character' },+ { tool: 'inspect_model', avatar: 'realistic-male.glb', topic: 'model inspect · realistic-male' },+ { tool: 'tools/list', args: {}, topic: 'capability discovery' },+ { tool: 'optimize_model', avatar: 'fox.glb', topic: 'model optimize · fox' },+];++export { SEED_ROTATION, REFERENCE_AVATARS };++// Round-robin cursor over SEED_ROTATION. Redis-backed when available so the+// rotation advances coherently across warm instances; per-instance fallback+// otherwise. Mirrors the GLB-canonicalization rotation idiom in the registry.+let _cursor = 0;+export async function nextRotation(ctx = {}) {+ const list = SEED_ROTATION;+ let idx;+ if (ctx.redis) {+ try {+ const n = await ctx.redis.incr('x402:auto:feed-seeder:cursor');+ idx = (Number(n) - 1) % list.length;+ } catch {+ idx = _cursor++ % list.length;+ }+ } else {+ idx = _cursor++ % list.length;+ }+ return list[idx];+}++// Resolve a rotation entry into the concrete /api/x402-pay request body.+export function buildRequestBody(pick, origin) {+ if (pick.tool === 'tools/list') return { tool: 'tools/list', args: {} };+ if (pick.avatar) return { tool: pick.tool, args: { url: avatarUrl(origin, pick.avatar) } };+ return { tool: pick.tool, args: pick.args || {} };+}++// Compact, human-readable summary of a tool result for the feed mirror ++// value_extracted. Pulls only the headline numbers — never the bulky payload.+export function summarizeResult(tool, result) {+ const sc = (result && result.structuredContent) || {};+ switch (tool) {+ case 'search_public_avatars':+ return { result_kind: 'avatars', result_count: Array.isArray(sc.avatars) ? sc.avatars.length : null };+ case 'inspect_model':+ return { result_kind: 'inspection', triangles: sc.counts?.totalTriangles ?? null, meshes: sc.counts?.meshes ?? null };+ case 'validate_model':+ return { result_kind: 'validation', errors: sc.numErrors ?? null, warnings: sc.numWarnings ?? null };+ case 'optimize_model':+ return { result_kind: 'optimization', suggestions: Array.isArray(sc.suggestions) ? sc.suggestions.length : null };+ case 'tools/list':+ return { result_kind: 'tools', tools: Array.isArray(result?.tools) ? result.tools.length : null };+ default:+ return { result_kind: 'unknown' };+ }+}++function argsSummary(body) {+ const a = body?.args || {};+ if (a.url) {+ try { return new URL(a.url).pathname.split('/').pop() || a.url; }+ catch { return String(a.url).slice(0, 40); }+ }+ if (a.q) return `q=${String(a.q).slice(0, 24)}`;+ const keys = Object.keys(a);+ return keys.length ? keys.map((k) => `${k}=${String(a[k]).slice(0, 16)}`).join(' ') : '';+}++// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).+let _schemaReady = false;+export async function ensureSchema() {+ if (_schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS x402_demo_feed (+ id bigserial PRIMARY KEY,+ run_id uuid NOT NULL,+ ts timestamptz DEFAULT now(),+ tool text NOT NULL,+ topic text,+ args_summary text,+ tx_signature text,+ network text,+ amount_atomic bigint NOT NULL DEFAULT 0,+ asset text,+ payer text,+ pay_to text,+ explorer text,+ total_ms int,+ result_summary jsonb+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS x402_demo_feed_ts ON x402_demo_feed (ts DESC)`;+ await sql`CREATE UNIQUE INDEX IF NOT EXISTS x402_demo_feed_tx ON x402_demo_feed (tx_signature) WHERE tx_signature IS NOT NULL`;+ _schemaReady = true;+}++// Persist a successful demo-payment receipt into the durable feed mirror.+// Idempotent on tx_signature so a retried run never double-rows the same payment.+async function storeFeedRow(row) {+ try {+ await sql`+ INSERT INTO x402_demo_feed+ (run_id, tool, topic, args_summary, tx_signature, network,+ amount_atomic, asset, payer, pay_to, explorer, total_ms, result_summary)+ VALUES+ (${row.runId}, ${row.tool}, ${row.topic}, ${row.argsSummary},+ ${row.txSig}, ${row.network}, ${row.amountAtomic}, ${row.asset},+ ${row.payer}, ${row.payTo}, ${row.explorer}, ${row.totalMs},+ ${row.resultSummary ? JSON.stringify(row.resultSummary) : null})+ ON CONFLICT (tx_signature) WHERE tx_signature IS NOT NULL DO NOTHING+ `;+ } catch (err) {+ log.warn('demo_feed_store_failed', { tx: row.txSig, message: err?.message });+ }+}++/**+ * Run the seeder. Conforms to the run()-style registry contract: the per-tick+ * loop hands { origin, redis, runId, ... }; the demo payment is made by+ * /api/x402-pay (platform wallet), so no Solana signing context is needed here.+ *+ * Returns the aggregate outcome the loop records as one x402_autonomous_log row:+ * { success, amountAtomic, txSig, errorMsg, responseData, valueExtracted, skipped, note }+ * The loop decrements the daily cap by amountAtomic on success and persists+ * value_extracted onto that summary row.+ */+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-pay`;++ // Schema first — without the durable mirror there is no sink for the value,+ // so don't spend. A schema failure exits logged, never crashes the tick.+ try {+ await ensureSchema();+ } catch (err) {+ log.warn('feed_seeder_schema_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };+ }++ const pick = await nextRotation(ctx);+ const body = buildRequestBody(pick, origin);+ const argSum = argsSummary(body);++ const t0 = Date.now();+ let res;+ try {+ res = await fetchWithTimeout(endpointUrl, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json',+ 'user-agent': 'threews-x402-autonomous/1.0',+ },+ body: JSON.stringify(body),+ });+ } catch (err) {+ const errorMsg = err?.message || 'fetch_failed';+ log.warn('feed_seeder_fetch_failed', { topic: pick.topic, message: errorMsg });+ return { success: false, amountAtomic: 0, txSig: null, errorMsg, note: `feed_seeder ${pick.topic} fetch_failed` };+ }++ const durationMs = Date.now() - t0;+ const respBody = res.body && typeof res.body === 'object' ? res.body : null;++ // Wallet unconfigured: /api/x402-pay returns 503 config_missing. Exit gracefully.+ if (res.status === 503 || respBody?.code === 'config_missing' || respBody?.code === 'wallet_unconfigured' || respBody?.code === 'wallet_misconfigured') {+ const errorMsg = respBody?.error || respBody?.code || 'wallet_unconfigured';+ log.info('feed_seeder_wallet_unconfigured', { code: respBody?.code });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg, note: 'wallet_unconfigured' };+ }++ // Any non-success (HTTP error, 402 rejection bubbled as ok:false, rate limit).+ if (!res.ok || !respBody || respBody.ok !== true || !respBody.payment) {+ const errorMsg = respBody?.code || respBody?.error || `http_${res.status}`;+ log.warn('feed_seeder_call_failed', { topic: pick.topic, status: res.status, code: respBody?.code });+ return { success: false, amountAtomic: 0, txSig: null, errorMsg, note: `feed_seeder ${pick.topic} ${errorMsg}` };+ }++ // Success — real on-chain demo payment settled.+ const payment = respBody.payment || {};+ const amountAtomic = Number(payment.amount) || 0;+ const txSig = payment.tx || null;+ const network = payment.network || 'solana:mainnet';+ const totalMs = respBody.durations?.total_ms ?? durationMs;+ const resultSummary = summarizeResult(pick.tool, respBody.result);++ const valueExtracted = {+ tool: pick.tool,+ topic: pick.topic,+ args_summary: argSum,+ tx: txSig,+ network,+ amount_atomic: amountAtomic,+ amount_usdc: amountAtomic / 1e6,+ payer: payment.payer || null,+ pay_to: payment.payTo || null,+ asset: payment.asset || ASSET,+ explorer: payment.explorer || (txSig ? `https://solscan.io/tx/${txSig}` : null),+ total_ms: totalMs,+ ...resultSummary,+ };++ // Mirror the receipt into the durable feed table (the /api/x402-pay call has+ // already pushed it onto the Redis ring the homepage renders).+ await storeFeedRow({+ runId,+ tool: pick.tool,+ topic: pick.topic,+ argsSummary: argSum,+ txSig,+ network,+ amountAtomic,+ asset: payment.asset || ASSET,+ payer: payment.payer || null,+ payTo: payment.payTo || null,+ explorer: valueExtracted.explorer,+ totalMs,+ resultSummary,+ });++ log.info('feed_seeder_paid', {+ run_id: runId,+ topic: pick.topic,+ tool: pick.tool,+ tx: txSig,+ amount_usdc: (amountAtomic / 1e6).toFixed(4),+ });++ return {+ success: true,+ amountAtomic,+ txSig,+ responseData: {+ tool: pick.tool,+ topic: pick.topic,+ tx: txSig,+ network,+ amount_usdc: amountAtomic / 1e6,+ ...resultSummary,+ },+ valueExtracted,+ note: `feed_seeder ${pick.topic} tx=${txSig ? txSig.slice(0, 8) : 'none'}`,+ };+}diff --git a/api/_lib/x402/pipelines/reputation-refresh.js b/api/_lib/x402/pipelines/reputation-refresh.jsnew file mode 100644index 000000000..7b3a56260--- /dev/null+++ b/api/_lib/x402/pipelines/reputation-refresh.js@@ -0,0 +1,410 @@+// api/_lib/x402/pipelines/reputation-refresh.js+//+// Agent Reputation Score Refresh — autonomous pipeline (self/005).+//+// On each run it refreshes the on-chain attestation reputation of the stalest+// registered Solana agents. For every agent it makes a REAL paid x402 call to+// the /api/mcp tool `solana_agent_reputation` ($0.001 USDC/call) using the seed+// wallet — never mocked. The pipeline:+//+// 1. Selects the stalest agents that have an on-chain Metaplex Core asset+// (agent_identities.meta.sol_mint_address). Stalest-first ordering rotates+// coverage across runs, exactly like the recompute-reputation cron.+// 2. Probes + pays each call via the shared payX402 client (real on-chain USDC).+// 3. Extracts the reputation summary and writes it to agent_solana_reputation,+// flagging agents whose verified score drops below the trust threshold.+// 4. Records a row in x402_autonomous_log for every call (success or failure),+// with the extracted score 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().+//+// DATA OUT (value extraction):+// Table : agent_solana_reputation+// Columns: score (headline trust number — the verified feedback average when+// any verified feedback exists, else the raw average), feedback_total,+// feedback_verified, feedback_disputed, validation_passed,+// validation_failed, flagged, raw, refreshed_at.+//+// DOWNSTREAM CONSUMERS (read 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 (signed feedback + validation+// memos), deliberately separate from the financial reputation in+// agent_reputation_scores (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 { payX402, bootstrapSolanaContext, USDC_MINT } from '../pay.js';++const log = logger('x402-reputation-refresh');++const TOOL = 'solana_agent_reputation';+const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+// Advertised price of the tool: $0.001 USDC (6 decimals). Used only to pre-check+// the daily cap; the authoritative amount comes from the 402 challenge.+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.+const REFRESH_BATCH = Math.max(1, Number(process.env.SOLANA_REPUTATION_REFRESH_BATCH || 25));++async function ensureSchema() {+ 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 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 this loop.+ await sql`create index if not exists agent_solana_reputation_refreshed_idx on agent_solana_reputation (refreshed_at asc)`;+ // The autonomous log predates the value_extracted column some pipelines use;+ // add it idempotently so this pipeline records its parsed summary into it.+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+}++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 jsonRpcReputation(asset, network, id) {+ return {+ jsonrpc: '2.0',+ id,+ method: 'tools/call',+ params: { name: TOOL, arguments: { asset, network } },+ };+}++// Pull the solana_agent_reputation structuredContent out of a JSON-RPC body.+export function extractReputation(responseBody) {+ const msg = Array.isArray(responseBody) ? responseBody[0] : responseBody;+ const sc = msg?.result?.structuredContent;+ if (!sc || sc.error) return null;+ return sc; // { agent, network, feedback:{...}, validation:{...} }+}++// Derive the headline trust score and the flag verdict from a reputation+// payload. Exported for unit coverage.+export function evaluateReputation(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()+ `;+}++// Per-call row into x402_autonomous_log, including value_extracted. The loop+// also records one aggregate summary row for the run() entry; these are the+// granular per-agent rows this pipeline owns.+async function recordCall(runId, { agent, 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'}, ${`Reputation Refresh: ${agent.name || agent.asset}`}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'self'})+ `;+ } catch (err) {+ log.warn('reputation_refresh_log_insert_failed', { asset: agent.asset, message: err?.message });+ }+}++/**+ * Run the reputation refresh. Conforms to the run()-style registry contract: the+ * loop hands over { origin, buyer, conn, blockhash, mintInfo, remainingCap,+ * runId }; called 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, 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/mcp`;+ let 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('reputation_refresh_schema_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };+ }++ // ── Eligible agents. A DB failure here is logged and the run exits cleanly.+ let agents;+ try {+ agents = await listAgentsToRefresh(REFRESH_BATCH);+ } catch (err) {+ log.error('reputation_refresh_list_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `db_list_failed: ${err?.message}` };+ }+ if (!agents.length) {+ log.info('reputation_refresh_no_agents');+ return { success: true, skipped: true, amountAtomic: 0, note: 'no_registered_agents' };+ }++ // ── 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('reputation_refresh_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 stored = 0;+ let flaggedCount = 0;+ let callErrors = 0;+ let lastTxSig = null;++ 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.+ if (Number.isFinite(remainingCap) && remainingCap < PRICE_ATOMIC) {+ log.info('reputation_refresh_cap_reached', { spent_atomic: spentAtomic });+ break;+ }++ const t0 = Date.now();+ let result;+ try {+ result = await payX402({+ url: endpointUrl,+ method: 'POST',+ body: jsonRpcReputation(agent.asset, agent.network, i + 1),+ buyer, conn, blockhash, mintInfo,+ remainingCap,+ // Distinct nonce per call so these identical-amount ($0.001) payments+ // against the one shared blockhash each produce a unique signature.+ nonce: i + 1,+ });+ } catch (err) {+ // Network failure / abort — log the call, never crash the sweep.+ callErrors += 1;+ await recordCall(runId, {+ agent, 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;+ }++ let valueExtracted = null;+ let success = result.success;+ let errorMsg = result.errorMsg;++ if (result.success) {+ const rep = extractReputation(result.responseBody);+ if (!rep) {+ success = false;+ errorMsg = 'unparseable_response';+ callErrors += 1;+ } else {+ const evald = evaluateReputation(rep);+ valueExtracted = {+ agent_id: agent.id, asset: agent.asset, network: agent.network,+ score: evald.score, flagged: evald.flagged, reasons: evald.reasons,+ feedback_total: evald.total, feedback_verified: evald.verified,+ feedback_disputed: evald.disputed,+ validation_passed: evald.passed, validation_failed: evald.failed,+ };+ try {+ await upsertReputation(agent, rep, evald);+ stored += 1;+ if (evald.flagged) flaggedCount += 1;+ } catch (dbErr) {+ // Payment already settled; persisting the value failed. Mark the row+ // a failure so the agent is retried next tick.+ success = false;+ errorMsg = `store_failed: ${dbErr?.message || 'unknown'}`;+ callErrors += 1;+ }+ }+ } else {+ callErrors += 1;+ }++ await recordCall(runId, {+ agent,+ endpointUrl,+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ // Keep the granular row lean — value_extracted holds the useful shape.+ responseData: { status: result.status, rpc_error: result.responseBody?.error || null },+ durationMs: Date.now() - t0,+ success,+ errorMsg,+ valueExtracted,+ });+ }++ log.info('reputation_refresh_complete', {+ run_id: runId, scanned: agents.length, paid, stored,+ flagged: flaggedCount, errors: callErrors, spent_usdc: (spentAtomic / 1e6).toFixed(4),+ });++ // Aggregate outcome for the loop's single summary row. success=true when at+ // least one agent's score was stored; per-agent detail lives in the rows above.+ return {+ success: stored > 0,+ amountAtomic: spentAtomic,+ txSig: lastTxSig,+ errorMsg: stored === 0 && callErrors > 0 ? `reputation_refresh_calls_failed:${callErrors}` : null,+ skipped: paid === 0 && stored === 0,+ responseData: { scanned: agents.length, paid, stored, flagged: flaggedCount, errors: callErrors },+ signalData: { scanned: agents.length, stored, flagged: flaggedCount },+ note: `reputation_refresh stored=${stored} flagged=${flaggedCount} paid=${paid}`,+ };+}++// ── 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/pipelines/rig-complexity.js b/api/_lib/x402/pipelines/rig-complexity.jsnew file mode 100644index 000000000..cc4dcc42c--- /dev/null+++ b/api/_lib/x402/pipelines/rig-complexity.js@@ -0,0 +1,467 @@+// api/_lib/x402/pipelines/rig-complexity.js+//+// Rig Complexity Scorer — autonomous pipeline (self/017).+//+// On each run it scores a small batch of avatars that have never been scored or+// whose GLB changed since the last score. For each avatar it pays the advertised+// price ($0.01 USDC) to call inspect_model on the three.ws MCP server+// (/api/mcp) — a real on-chain USDC payment from the seed wallet, never mocked —+// then derives a 0-100 complexity score from the returned structure (bone count,+// vertex count, texture bytes, triangles, file size) and a performance tier.+//+// The pipeline:+// 1. Selects avatars needing a score (new or GLB-changed) from `avatars`.+// 2. Probes + pays inspect_model for each (real x402; degrades gracefully when+// the wallet is unconfigured, the RPC is down, or a single call fails).+// 3. Upserts the score + tier + raw metrics into `avatar_complexity`.+// 4. Records one row per call in x402_autonomous_log (success OR failure),+// with the parsed score in value_extracted.+//+// Downstream consumer: `avatar_complexity` is read by the Avatar Pricing Engine+// (self/020) to tier marketplace listing prices, and by the marketplace gallery+// to surface a "performance-heavy" warning badge on avatars whose perf_warning+// flag is set. Keyed by avatar_id so any avatar surface can join against it.+//+// Real on-chain payments only — no mocks, no simulations.++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 { publicUrl } from '../../r2.js';+import { solanaConnection } from '../../solana/connection.js';+import { logger } from '../../usage.js';+import { loadSeedKeypair, payX402 } from '../solana-payer.js';++const log = logger('x402-rig-complexity');++const USDC_MINT = () => env.X402_ASSET_MINT_SOLANA || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// How many avatars to score per run. With the registry cooldown (1h) this drains+// any backlog steadily while bounding spend (≤ BATCH × $0.01 per run); at steady+// state only newly-uploaded or changed avatars qualify, so most runs do nothing.+const BATCH = Number(process.env.X402_RIG_COMPLEXITY_BATCH || 4);++// ── Complexity model ──────────────────────────────────────────────────────────+// Per-dimension "full budget" for a web-delivered avatar. A value at budget+// contributes its full weight; the ratio is allowed to run to 2× so a single+// runaway dimension can still pull the score up before the final 0-100 clamp.+const BUDGETS = Object.freeze({+ vertices: 150_000,+ triangles: 300_000,+ textureBytes: 16 * 1024 * 1024, // 16 MB decoded+ bones: 120,+ fileBytes: 30 * 1024 * 1024, // 30 MB+});++const WEIGHTS = Object.freeze({+ vertices: 0.30,+ triangles: 0.20,+ textureBytes: 0.25,+ bones: 0.10,+ fileBytes: 0.15,+});++// Hard ceilings that flag an avatar as performance-heavy regardless of the+// blended score (one pathological dimension is enough to stutter on mobile).+const HARD_LIMITS = Object.freeze({+ vertices: 500_000,+ triangles: 1_000_000,+ textureBytes: 48 * 1024 * 1024,+ maxTextureDim: 8192,+ fileBytes: 75 * 1024 * 1024,+ bones: 256,+});++function clamp(n, lo, hi) {+ return Math.max(lo, Math.min(hi, n));+}++function tierForScore(score) {+ if (score < 25) return 'light';+ if (score < 50) return 'standard';+ if (score < 75) return 'heavy';+ return 'extreme';+}++// Pure: turn an inspect_model structuredContent payload into a complexity record.+// Exported so it can be unit-tested without any network or DB.+export function computeComplexity(info, { fileBytes = 0 } = {}) {+ const counts = info?.counts || {};+ const textures = Array.isArray(info?.textures) ? info.textures : [];++ const boneCount = Number(counts.totalJoints || 0);+ const vertexCount = Number(counts.totalVertices || 0);+ const triangleCount = Number(counts.totalTriangles || 0);+ const textureBytes = textures.reduce((a, t) => a + Number(t?.byteSize || 0), 0);+ const maxTextureDim = textures.reduce(+ (m, t) => Math.max(m, Number(t?.width || 0), Number(t?.height || 0)),+ 0,+ );+ // inspect_model reports fileSize; fall back to the DB size_bytes when absent.+ const fileSize = Number(info?.fileSize || fileBytes || 0);++ const dims = {+ vertices: vertexCount,+ triangles: triangleCount,+ textureBytes,+ bones: boneCount,+ fileBytes: fileSize,+ };++ const breakdown = {};+ let score = 0;+ for (const key of Object.keys(WEIGHTS)) {+ const budget = BUDGETS[key];+ const ratio = budget > 0 ? clamp(dims[key] / budget, 0, 2) : 0;+ const weighted = ratio * WEIGHTS[key] * 100;+ score += weighted;+ breakdown[key] = {+ value: dims[key],+ budget,+ ratio: Number(ratio.toFixed(3)),+ weighted: Number(weighted.toFixed(2)),+ };+ }+ score = Number(clamp(score, 0, 100).toFixed(2));++ const overHardLimit =+ vertexCount > HARD_LIMITS.vertices ||+ triangleCount > HARD_LIMITS.triangles ||+ textureBytes > HARD_LIMITS.textureBytes ||+ maxTextureDim >= HARD_LIMITS.maxTextureDim ||+ fileSize > HARD_LIMITS.fileBytes ||+ boneCount > HARD_LIMITS.bones;++ const tier = tierForScore(score);+ const perfWarning = overHardLimit || tier === 'heavy' || tier === 'extreme';++ return {+ bone_count: boneCount,+ vertex_count: vertexCount,+ triangle_count: triangleCount,+ texture_bytes: textureBytes,+ texture_count: textures.length,+ max_texture_dim: maxTextureDim,+ file_bytes: fileSize,+ mesh_count: Number(counts.meshes || 0),+ material_count: Number(counts.materials || 0),+ skin_count: Number(counts.skins || 0),+ complexity_score: score,+ tier,+ perf_warning: perfWarning,+ breakdown,+ };+}++// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).+let _schemaReady = false;+async function ensureSchema() {+ if (_schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS avatar_complexity (+ avatar_id uuid PRIMARY KEY REFERENCES avatars(id) ON DELETE CASCADE,+ model_url text,+ bone_count int NOT NULL DEFAULT 0,+ vertex_count bigint NOT NULL DEFAULT 0,+ triangle_count bigint NOT NULL DEFAULT 0,+ texture_bytes bigint NOT NULL DEFAULT 0,+ texture_count int NOT NULL DEFAULT 0,+ max_texture_dim int NOT NULL DEFAULT 0,+ file_bytes bigint NOT NULL DEFAULT 0,+ mesh_count int NOT NULL DEFAULT 0,+ material_count int NOT NULL DEFAULT 0,+ skin_count int NOT NULL DEFAULT 0,+ complexity_score numeric(6,2) NOT NULL DEFAULT 0,+ tier text NOT NULL DEFAULT 'light'+ CHECK (tier IN ('light','standard','heavy','extreme')),+ perf_warning boolean NOT NULL DEFAULT false,+ breakdown jsonb,+ source_updated_at timestamptz,+ run_id uuid,+ scored_at timestamptz DEFAULT now()+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS avatar_complexity_tier_idx ON avatar_complexity (tier, complexity_score DESC)`;+ await sql`CREATE INDEX IF NOT EXISTS avatar_complexity_warn_idx ON avatar_complexity (perf_warning) WHERE perf_warning`;+ // The autonomous log predates this pipeline; add the value_extracted column it+ // records the parsed score into (idempotent — shared with sibling pipelines).+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+ _schemaReady = true;+}++// Avatars that need (re)scoring: never scored, or whose GLB changed since the+// last score. New avatars first, then the stalest. Scoped to marketplace-visible+// avatars with a GLB storage key (the rows whose pricing/badge actually consume+// the result, and whose objects are publicly fetchable by inspect_model).+async function selectAvatarsToScore(limit) {+ return sql`+ SELECT a.id, a.slug, a.name, a.storage_key, a.size_bytes, a.updated_at+ FROM avatars a+ LEFT JOIN avatar_complexity c ON c.avatar_id = a.id+ WHERE a.deleted_at IS NULL+ AND a.visibility IN ('public', 'unlisted')+ AND a.storage_key ILIKE '%.glb'+ AND (c.avatar_id IS NULL OR c.source_updated_at IS DISTINCT FROM a.updated_at)+ ORDER BY (c.avatar_id IS NULL) DESC, c.scored_at ASC NULLS FIRST, a.updated_at DESC+ LIMIT ${limit}+ `;+}++async function upsertComplexity(avatarId, modelUrl, sourceUpdatedAt, runId, c) {+ await sql`+ INSERT INTO avatar_complexity+ (avatar_id, model_url, bone_count, vertex_count, triangle_count,+ texture_bytes, texture_count, max_texture_dim, file_bytes,+ mesh_count, material_count, skin_count, complexity_score, tier,+ perf_warning, breakdown, source_updated_at, run_id, scored_at)+ VALUES+ (${avatarId}, ${modelUrl}, ${c.bone_count}, ${c.vertex_count}, ${c.triangle_count},+ ${c.texture_bytes}, ${c.texture_count}, ${c.max_texture_dim}, ${c.file_bytes},+ ${c.mesh_count}, ${c.material_count}, ${c.skin_count}, ${c.complexity_score}, ${c.tier},+ ${c.perf_warning}, ${JSON.stringify(c.breakdown)}, ${sourceUpdatedAt}, ${runId}, now())+ ON CONFLICT (avatar_id) DO UPDATE SET+ model_url = EXCLUDED.model_url,+ bone_count = EXCLUDED.bone_count,+ vertex_count = EXCLUDED.vertex_count,+ triangle_count = EXCLUDED.triangle_count,+ texture_bytes = EXCLUDED.texture_bytes,+ texture_count = EXCLUDED.texture_count,+ max_texture_dim = EXCLUDED.max_texture_dim,+ file_bytes = EXCLUDED.file_bytes,+ mesh_count = EXCLUDED.mesh_count,+ material_count = EXCLUDED.material_count,+ skin_count = EXCLUDED.skin_count,+ complexity_score = EXCLUDED.complexity_score,+ tier = EXCLUDED.tier,+ perf_warning = EXCLUDED.perf_warning,+ breakdown = EXCLUDED.breakdown,+ source_updated_at = EXCLUDED.source_updated_at,+ run_id = EXCLUDED.run_id,+ scored_at = now()+ `;+}++async function recordCall(runId, { serviceName, 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'}, ${serviceName}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${USDC_MINT()}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'3d'})+ `;+ } catch (err) {+ log.warn('rig_complexity_log_insert_failed', { message: err?.message });+ }+}++function inspectBody(modelUrl, id) {+ return {+ jsonrpc: '2.0',+ id,+ method: 'tools/call',+ params: { name: 'inspect_model', arguments: { url: modelUrl } },+ };+}++// Pull inspect_model's structuredContent out of a JSON-RPC tools/call response.+function extractInspect(responseBody) {+ const rpcError = responseBody?.error || responseBody?.result?.isError || null;+ const sc = responseBody?.result?.structuredContent;+ if (!sc || !sc.counts) return { info: null, rpcError };+ return { info: sc, rpcError };+}++/**+ * Run the scorer. Self-contained: builds its own Solana payment context when the+ * cron loop doesn't supply one, so it can be invoked directly (manual test) or+ * handed the loop's shared blockhash + keypair. Records its own log rows, so it+ * returns { recorded: true } and the loop skips its generic recordLog.+ *+ * @param {object} [ctx]+ * @param {string} [ctx.runId] correlation id (defaults to a fresh uuid)+ * @param {string} [ctx.origin] base origin for /api/mcp+ * @param {object} [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.remainingCap] spend ceiling for this run (atomics)+ * @returns {Promise<object>} loop-compatible outcome+ */+export async function run(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const endpointUrl = `${origin}/api/mcp`;+ const usdcMint = USDC_MINT();+ let remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;++ const fail = (reason, extra = {}) => ({+ ok: false, recorded: true, skipped: true, success: false,+ amountAtomic: 0, txSig: null, note: reason, ...extra,+ });++ // ── Wallet pre-flight: exit gracefully (logged) if unconfigured ───────────+ let buyer = ctx.buyer;+ if (!buyer) {+ try { buyer = loadSeedKeypair(); } catch (err) {+ log.info('rig_complexity_skipped', { reason: err.message });+ return fail(err.message);+ }+ }++ try {+ await ensureSchema();+ } catch (err) {+ log.warn('rig_complexity_schema_failed', { message: err?.message });+ return fail(`schema_failed: ${err?.message}`);+ }++ let targets;+ try {+ targets = await selectAvatarsToScore(BATCH);+ } catch (err) {+ log.warn('rig_complexity_select_failed', { message: err?.message });+ return fail(`select_failed: ${err?.message}`);+ }+ if (!targets.length) {+ return { ok: true, recorded: true, skipped: false, success: true, amountAtomic: 0, txSig: null, note: 'no_avatars_due', scored: 0 };+ }++ // ── Solana payment context (reuse the 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: 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(usdcMint)),+ ]);+ blockhash = blockhash || bh.blockhash;+ mintInfo = mintInfo || mi;+ } catch (err) {+ log.warn('rig_complexity_solana_preflight_failed', { message: err?.message });+ return fail(`solana_preflight_failed: ${err?.message}`);+ }+ }++ let spentAtomic = 0;+ let paid = 0;+ let scored = 0;+ let lastTxSig = null;+ const summaries = [];++ for (let i = 0; i < targets.length; i++) {+ if (remainingCap <= 0) {+ log.info('rig_complexity_cap_reached', { spent_atomic: spentAtomic });+ break;+ }+ const a = targets[i];+ const modelUrl = publicUrl(a.storage_key);+ const serviceName = `Rig Complexity: ${a.slug || a.id}`;+ const t0 = Date.now();++ let result;+ try {+ result = await payX402({+ endpointUrl,+ method: 'POST',+ body: inspectBody(modelUrl, i + 1),+ conn, buyer, blockhash, mintInfo, usdcMint,+ maxAmountAtomic: remainingCap,+ });+ } catch (err) {+ // Network failure / abort — record the attempt, never crash the loop.+ await recordCall(runId, {+ serviceName, endpointUrl, amountAtomic: 0, txSig: null,+ responseData: { model_url: modelUrl },+ durationMs: Date.now() - t0, success: false,+ errorMsg: err?.message || 'fetch_failed', valueExtracted: null,+ });+ summaries.push({ avatar: a.slug || a.id, error: err?.message || 'fetch_failed' });+ continue;+ }++ if (result.status === 'paid') {+ spentAtomic += result.amountAtomic;+ remainingCap -= result.amountAtomic;+ paid += 1;+ lastTxSig = result.txSig || lastTxSig;+ }++ const { info, rpcError } = extractInspect(result.responseBody);+ let valueExtracted = null;+ let errorMsg = result.errorMsg;++ if (result.success && info) {+ const complexity = computeComplexity(info, { fileBytes: Number(a.size_bytes || 0) });+ try {+ await upsertComplexity(a.id, modelUrl, a.updated_at, runId, complexity);+ scored += 1;+ } catch (err) {+ errorMsg = `db_upsert_failed: ${err?.message}`;+ log.warn('rig_complexity_upsert_failed', { avatar: a.id, message: err?.message });+ }+ valueExtracted = {+ avatar_id: a.id,+ score: complexity.complexity_score,+ tier: complexity.tier,+ perf_warning: complexity.perf_warning,+ bones: complexity.bone_count,+ vertices: complexity.vertex_count,+ triangles: complexity.triangle_count,+ texture_bytes: complexity.texture_bytes,+ };+ summaries.push({ avatar: a.slug || a.id, ...valueExtracted });+ } else {+ if (!errorMsg) errorMsg = rpcError ? 'rpc_error' : 'no_inspect_data';+ summaries.push({ avatar: a.slug || a.id, status: result.status, error: errorMsg });+ }++ await recordCall(runId, {+ serviceName,+ endpointUrl,+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ // Keep the log row slim — the parsed score lives in value_extracted.+ responseData: { model_url: modelUrl, status: result.status, rpc_error: result.responseBody?.error || null },+ durationMs: result.durationMs ?? (Date.now() - t0),+ success: result.success && !!info && !errorMsg,+ errorMsg: result.success && info && !errorMsg ? null : errorMsg,+ valueExtracted,+ });+ }++ const heavy = summaries.filter((s) => s.perf_warning).length;+ log.info('rig_complexity_complete', {+ run_id: runId,+ candidates: targets.length,+ scored,+ paid,+ heavy,+ spent_usdc: (spentAtomic / 1e6).toFixed(4),+ });++ return {+ ok: true,+ recorded: true,+ skipped: false,+ success: scored > 0 || paid > 0,+ amountAtomic: spentAtomic,+ txSig: lastTxSig,+ signalData: { scored, paid, heavy, candidates: targets.length },+ note: `scored ${scored}/${targets.length}`,+ scored,+ paid,+ summaries,+ };+}diff --git a/api/_lib/x402/pipelines/token-intel-gate.js b/api/_lib/x402/pipelines/token-intel-gate.jsnew file mode 100644index 000000000..d5dabbbfd--- /dev/null+++ b/api/_lib/x402/pipelines/token-intel-gate.js@@ -0,0 +1,343 @@+// api/_lib/x402/pipelines/token-intel-gate.js+//+// Token Intel Pre-Snipe Gate — autonomous pipeline (self/023).+//+// Before the sniper commits SOL to a new mint, this loop pays the platform's own+// $0.01 USDC Token Oracle (/api/x402/token-intel) for live due-diligence on the+// freshest pump.fun mints the sniper is about to consider, and turns the verdict+// into a rugpull-risk gate. On each run it:+//+// 1. Selects a batch of recent mints from pump_coin_intel that lack a FRESH+// risk verdict (selectGateTargets), ordered most-active-first (the ones+// most likely to already have a tradeable DexScreener pair).+// 2. Pays GET /api/x402/token-intel?mint=<mint> for each via the shared payX402+// client — real on-chain USDC from the seed wallet, never mocked. Mints with+// no live market yet make the endpoint throw 503 BEFORE settlement, so the+// wallet is never charged for missing data (recorded as a free/failed probe).+// 3. Extracts the 0..100 rugpull sub-score (token-intel risk.score) + level,+// and upserts the verdict into token_intel_risk keyed by (mint, network).+// `rejected` is set when the level is high/critical.+// 4. Records a row in x402_autonomous_log for every call (success or failure)+// with the verdict 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: workers/agent-sniper/oracle-gate.js reads token_intel_risk+// on the pre-snipe path (new_mint, first_claim, intel_confirmed, prelaunch-radar).+// A fresh `rejected = true` row vetoes the snipe — high-risk mints are auto-+// rejected before any SOL moves. Fail-open: a missing/stale verdict never blocks+// a snipe, so this layer can only ever make the sniper safer.++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';++const log = logger('x402-token-intel-gate');++// Mints risk-checked per run. Each is one $0.01 USDC payment, so a full batch is+// ≤ $0.0BATCH — bounded again by the remainingCap the loop passes in and by the+// loop's daily cap. Default 3 keeps a steady ~$0.x/day at the registry cooldown.+const BATCH_SIZE = Number(process.env.X402_TOKEN_INTEL_GATE_BATCH || 3);+// A verdict is "fresh" for this many minutes — within the window we don't re-pay+// for the same mint. New mints move fast, so a short window keeps risk current.+const FRESH_MINUTES = Number(process.env.X402_TOKEN_INTEL_GATE_FRESH_MIN || 30);+// Only gate mints first seen within this window — older mints are no longer+// snipe candidates, so paying to risk-check them is wasted spend.+const CANDIDATE_HOURS = Number(process.env.X402_TOKEN_INTEL_GATE_CANDIDATE_HOURS || 24);++const NETWORK = (process.env.SNIPER_NETWORK || 'mainnet').trim();+const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const ENDPOINT_PATH = '/api/x402/token-intel';++let _schemaReady = false;+async function ensureSchema() {+ if (_schemaReady) return;+ // Verdict sink (idempotent — mirrors the migration so the pipeline is safe to+ // run before the migration is applied).+ await sql`+ CREATE TABLE IF NOT EXISTS token_intel_risk (+ mint text NOT NULL,+ network text NOT NULL DEFAULT 'mainnet',+ rugpull_score int NOT NULL DEFAULT 0,+ risk_level text NOT NULL DEFAULT 'unknown',+ rejected boolean NOT NULL DEFAULT false,+ signal text,+ confidence numeric(4,3),+ symbol text,+ price_usd numeric(20,10),+ change_24h numeric,+ market_cap_usd numeric,+ liquidity_usd numeric,+ volume_24h_usd numeric,+ factors jsonb NOT NULL DEFAULT '[]'::jsonb,+ tx_signature text,+ run_id uuid,+ checked_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (mint, network)+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS token_intel_risk_checked ON token_intel_risk (network, checked_at DESC)`;+ // The autonomous log predates the value_extracted column on some envs.+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+ _schemaReady = true;+}++/**+ * Pick the next batch of snipe-candidate mints needing a fresh risk verdict.+ * Recent mints first by activity (most-traded → most likely already listed on a+ * DEX, so token-intel returns real data instead of a 503). Returns [] if the+ * pump_coin_intel brain table isn't present yet (degrade, never throw).+ */+export async function selectGateTargets(limit = BATCH_SIZE) {+ try {+ const rows = await sql`+ SELECT pci.mint, pci.symbol+ FROM pump_coin_intel pci+ LEFT JOIN token_intel_risk tir+ ON tir.mint = pci.mint AND tir.network = pci.network+ WHERE pci.network = ${NETWORK}+ AND pci.first_seen_at > now() - make_interval(hours => ${CANDIDATE_HOURS})+ AND (tir.checked_at IS NULL+ OR tir.checked_at < now() - make_interval(mins => ${FRESH_MINUTES}))+ ORDER BY pci.buy_volume_lamports DESC NULLS LAST, pci.first_seen_at DESC+ LIMIT ${limit}+ `;+ return rows.map((r) => ({ mint: r.mint, symbol: r.symbol || null }));+ } catch (err) {+ if (!err?.message?.includes('does not exist')) {+ log.warn('token_intel_gate_select_failed', { message: err?.message });+ }+ return [];+ }+}++// Map a token-intel response into the verdict row. The rugpull sub-score IS the+// endpoint's due-diligence risk.score (0 safe … 100 critical); high/critical+// levels flip `rejected`. Returns null for a malformed/empty response.+export function deriveVerdict(body) {+ if (!body || typeof body !== 'object' || !body.risk) return null;+ const level = String(body.risk.level || 'unknown').toLowerCase();+ const score = Number(body.risk.score);+ return {+ rugpull_score: Number.isFinite(score) ? Math.max(0, Math.min(100, Math.round(score))) : 0,+ risk_level: ['low', 'medium', 'high', 'critical'].includes(level) ? level : 'unknown',+ rejected: level === 'high' || level === 'critical',+ signal: body.signal || null,+ confidence: Number.isFinite(Number(body.confidence)) ? Number(body.confidence) : null,+ symbol: body.symbol || null,+ price_usd: Number.isFinite(Number(body.price_usd)) ? Number(body.price_usd) : null,+ change_24h: Number.isFinite(Number(body.change_24h)) ? Number(body.change_24h) : null,+ market_cap_usd: Number.isFinite(Number(body.market_cap_usd)) ? Number(body.market_cap_usd) : null,+ liquidity_usd: Number.isFinite(Number(body.liquidity_usd)) ? Number(body.liquidity_usd) : null,+ volume_24h_usd: Number.isFinite(Number(body.volume_24h_usd)) ? Number(body.volume_24h_usd) : null,+ factors: Array.isArray(body.risk.factors) ? body.risk.factors : [],+ };+}++async function upsertVerdict(runId, mint, v, txSig) {+ await sql`+ INSERT INTO token_intel_risk+ (mint, network, rugpull_score, risk_level, rejected, signal, confidence,+ symbol, price_usd, change_24h, market_cap_usd, liquidity_usd, volume_24h_usd,+ factors, tx_signature, run_id, checked_at)+ VALUES+ (${mint}, ${NETWORK}, ${v.rugpull_score}, ${v.risk_level}, ${v.rejected},+ ${v.signal}, ${v.confidence}, ${v.symbol}, ${v.price_usd}, ${v.change_24h},+ ${v.market_cap_usd}, ${v.liquidity_usd}, ${v.volume_24h_usd},+ ${JSON.stringify(v.factors)}, ${txSig || null}, ${runId}, now())+ ON CONFLICT (mint, network) DO UPDATE SET+ rugpull_score = EXCLUDED.rugpull_score,+ risk_level = EXCLUDED.risk_level,+ rejected = EXCLUDED.rejected,+ signal = EXCLUDED.signal,+ confidence = EXCLUDED.confidence,+ symbol = EXCLUDED.symbol,+ price_usd = EXCLUDED.price_usd,+ change_24h = EXCLUDED.change_24h,+ market_cap_usd = EXCLUDED.market_cap_usd,+ liquidity_usd = EXCLUDED.liquidity_usd,+ volume_24h_usd = EXCLUDED.volume_24h_usd,+ factors = EXCLUDED.factors,+ tx_signature = EXCLUDED.tx_signature,+ run_id = EXCLUDED.run_id,+ checked_at = now()+ `;+}++// One row per gated mint into x402_autonomous_log (the loop also records one+// aggregate summary row for the run() entry; these are the granular per-mint ones).+async function recordCall(runId, { mint, 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'}, ${`Pre-Snipe Gate: ${mint.slice(0, 8)}…`}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},+ ${responseData ? JSON.stringify(responseData) : null},+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'sniper'})+ `;+ } catch (err) {+ log.warn('token_intel_gate_log_insert_failed', { mint, message: err?.message });+ }+}++/**+ * Run the pre-snipe gate 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, 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;++ // ── Schema first: without the verdict sink there's nothing to extract, so don't pay.+ try {+ await ensureSchema();+ } catch (err) {+ log.warn('token_intel_gate_schema_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };+ }++ // ── Find work before touching the wallet — no candidates → no spend.+ const targets = await selectGateTargets(BATCH_SIZE);+ if (targets.length === 0) {+ return { success: true, skipped: true, amountAtomic: 0, note: 'no_snipe_candidates' };+ }++ // ── 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('token_intel_gate_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 gated = 0; // verdicts stored+ let rejected = 0; // high/critical → auto-reject+ let noData = 0; // 503 before settlement (no live market yet)+ let callErrors = 0;+ let lastTxSig = null;++ for (let i = 0; i < targets.length; i++) {+ const { mint } = targets[i];+ if (remainingCap <= 0) {+ log.info('token_intel_gate_cap_reached', { spent_atomic: spentAtomic, remaining_targets: targets.length - i });+ break;+ }++ const endpointUrl = `${origin}${ENDPOINT_PATH}?mint=${encodeURIComponent(mint)}`;+ const t0 = Date.now();+ let result;+ try {+ result = await payX402({+ url: endpointUrl,+ method: 'GET',+ buyer, conn, blockhash, mintInfo,+ remainingCap,+ userAgent: 'threews-x402-presnipe-gate/1.0',+ });+ } catch (err) {+ // Network failure / abort — log the call, never crash the sweep.+ callErrors += 1;+ await recordCall(runId, {+ mint, 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 verdict only when the call delivered a usable body.+ let verdict = null;+ let valueExtracted = null;+ if (result.success) {+ verdict = deriveVerdict(result.responseBody);+ if (verdict) {+ try {+ await upsertVerdict(runId, mint, verdict, result.txSig);+ gated += 1;+ if (verdict.rejected) rejected += 1;+ valueExtracted = {+ mint,+ rugpull_score: verdict.rugpull_score,+ risk_level: verdict.risk_level,+ rejected: verdict.rejected,+ signal: verdict.signal,+ liquidity_usd: verdict.liquidity_usd,+ };+ } catch (err) {+ // Payment already settled — record the call as a success but surface+ // the persistence error for observability.+ log.warn('token_intel_gate_persist_failed', { mint, message: err?.message });+ }+ }+ } else {+ // token-intel throws 503 (data_unavailable) for mints with no live market+ // yet — an expected, un-charged outcome for brand-new pre-bonding mints.+ if (result.status === 503) noData += 1;+ else callErrors += 1;+ }++ await recordCall(runId, {+ mint,+ endpointUrl,+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ // Keep the row compact — the verdict lives in value_extracted + token_intel_risk.+ responseData: { status: result.status, code: result.responseBody?.code || null, rpc_error: result.responseBody?.error || null },+ durationMs: Date.now() - t0,+ success: result.success,+ errorMsg: result.errorMsg,+ valueExtracted,+ });+ }++ log.info('token_intel_gate_complete', {+ run_id: runId,+ targets: targets.length,+ paid,+ gated,+ rejected,+ no_data: noData,+ spent_usdc: (spentAtomic / 1e6).toFixed(4),+ });++ return {+ // success when the gate did its job: at least one verdict stored, or every+ // candidate honestly had no live market yet (no charge, nothing to gate).+ success: gated > 0 || (paid === 0 && noData === targets.length),+ amountAtomic: spentAtomic,+ txSig: lastTxSig,+ errorMsg: gated === 0 && callErrors > 0 ? `token_intel_gate_calls_failed:${callErrors}` : null,+ skipped: paid === 0 && gated === 0 && noData === 0,+ responseData: { targets: targets.length, paid, gated, rejected, no_data: noData },+ signalData: { gated, rejected, no_data: noData },+ note: `presnipe_gate targets=${targets.length} paid=${paid} gated=${gated} rejected=${rejected} nodata=${noData}`,+ };+}diff --git a/api/_lib/x402/run-reputation-refresh.js b/api/_lib/x402/run-reputation-refresh.jsdeleted file mode 100644index d9d36fc33..000000000--- a/api/_lib/x402/run-reputation-refresh.js+++ /dev/null@@ -1,410 +0,0 @@-// 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/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.jsindex 30b1a58e0..1c45ba818 100644--- a/api/cron/x402-autonomous-loop.js+++ b/api/cron/x402-autonomous-loop.js@@ -329,10 +329,16 @@ export default wrapCron(async (req, res) => {tx: txSig,...(outcome.note ? { note: outcome.note } : {}),});- await recordLog(runId, entry, {- amountAtomic, txSig, responseData: responseBody,- durationMs: Date.now() - t0, success, errorMsg, signalData,- });+ // A pipeline that records its own granular per-call rows (one per+ // resource it fanned across) sets outcome.recorded so the loop does not+ // add a duplicate summary row. Entries that don't self-record still get+ // the single canonical row here.+ if (!outcome.recorded) {+ await recordLog(runId, entry, {+ amountAtomic, txSig, responseData: responseBody,+ durationMs: Date.now() - t0, success, errorMsg, signalData,+ });+ }continue;}diff --git a/api/ops/health.js b/api/ops/health.jsindex e686e7000..f823d01e5 100644--- a/api/ops/health.js+++ b/api/ops/health.js@@ -148,6 +148,11 @@ export default wrap(async (req, res) => {// route or failed Solana settlement means the payment stack is degraded.const circuitBreaker = await loadCircuitBreaker();+ // Agent wallet balance — latest sample written every 10 min by the autonomous+ // loop (api/_lib/x402/wallet-balance-monitor.js). A low/unconfigured wallet+ // means autonomous calls are about to start failing on insufficient funds.+ const walletBalance = await loadWalletBalance();+// Categorize probe resultsconst byCategory = {};for (const r of probeResults) {@@ -161,7 +166,10 @@ export default wrap(async (req, res) => {// 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;+ // A low or unconfigured wallet degrades health (autonomous spend will fail);+ // a never-run monitor (ok:null) is unknown, not failing.+ const walletOk = walletBalance.ok !== false;+ const overallOk = allProbesOk && allCronsOk && breakerOk && walletOk;const failingProbes = probeResults.filter((r) => !r.ok);const failingCrons = heartbeats.filter((h) => h.stale || h.ok === false);@@ -181,9 +189,53 @@ export default wrap(async (req, res) => {probes: byCategory,crons: heartbeats,circuitBreaker,+ walletBalance,});});+// Read the latest agent-wallet balance sample written every 10 min by the+// autonomous loop (api/_lib/x402/wallet-balance-monitor.js). A sample older than+// the staleness window means the monitor stopped writing; ok:null when it has+// never run (table absent / no rows) so health doesn't fail on a cold feature.+const WALLET_STALE_AFTER_MS = 30 * 60 * 1000; // 30m (10-min cadence + slack)++async function loadWalletBalance() {+ try {+ const [row] = await sql`+ SELECT address, configured, usdc, sol, low_balance, threshold_usdc,+ usdc_delta, spend_rate_usdc_hr,+ extract(epoch FROM ts) * 1000 AS checked_at_ms+ FROM agent_wallet_balance_log+ ORDER BY ts DESC+ LIMIT 1+ `;+ if (!row) return { ok: null, reason: 'no_data' };+ const checkedAt = row.checked_at_ms ? Number(row.checked_at_ms) : null;+ const stale = checkedAt === null || Date.now() - checkedAt > WALLET_STALE_AFTER_MS;+ // Degraded when the wallet is below threshold or unconfigured. A stale+ // sample is unknown (monitor stopped), not a balance failure → ok:null.+ const ok = stale ? null : !(row.low_balance || row.configured === false);+ return {+ ok,+ configured: row.configured,+ address: row.address,+ usdc: row.usdc != null ? Number(row.usdc) : null,+ sol: row.sol != null ? Number(row.sol) : null,+ lowBalance: row.low_balance,+ thresholdUsdc: row.threshold_usdc != null ? Number(row.threshold_usdc) : null,+ usdcDelta: row.usdc_delta != null ? Number(row.usdc_delta) : null,+ spendRateUsdcHr: row.spend_rate_usdc_hr != null ? Number(row.spend_rate_usdc_hr) : null,+ lastChecked: checkedAt,+ stale,+ };+ } catch (err) {+ if (/does not exist|relation .* does not exist/i.test(err?.message || '')) {+ return { ok: null, reason: 'table_absent' };+ }+ return { ok: null, reason: `query_failed:${err?.message || 'unknown'}` };+ }+}+// 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 thediff --git a/api/three-signal.js b/api/three-signal.jsnew file mode 100644index 000000000..e51dc82fd--- /dev/null+++ b/api/three-signal.js@@ -0,0 +1,67 @@+// GET /api/three-signal+//+// Public, free read of the $THREE Signal Feed — the latest market snapshot plus+// a short sparkline history. This is NOT the paid oracle (/api/x402/three-intel);+// it serves the data the x402 autonomous loop already paid to fetch and stored in+// the three_market_signals time series (writer: the `three-intel` registry entry,+// every 15 min). The $THREE price widget reads this so it can render a live price+// without charging the viewer per glance.+//+// Query:+// history optional int (1..500) — sparkline points to return (default 48)+//+// Response:+// {+// latest: { mint, symbol, price_usd, change_24h, market_cap_usd,+// liquidity_usd, volume_24h_usd, signal, headline, confidence, ts } | null,+// history: [{ ts, price_usd, change_24h, signal }], // oldest → newest+// stale: boolean, // true when the latest point is older than 45 min+// age_seconds: number|null+// }++import { cors, json, method, error, wrap } from './_lib/http.js';+import { sql, isDbUnavailableError } from './_lib/db.js';+import { getLatestThreeSignal, getThreeSignalHistory } from './_lib/x402/three-signal-store.js';++// The feed writes every 15 min; flag anything older than 3 missed ticks as stale+// so the widget can show a "last updated" hint instead of a misleadingly live price.+const STALE_AFTER_MS = 45 * 60 * 1000;++export default wrap(async (req, res) => {+ cors(res);+ if (!method(req, res, ['GET'])) return;++ const rawHistory = parseInt(req.query?.history ?? '48', 10);+ const historyLimit = Number.isFinite(rawHistory) ? Math.max(1, Math.min(500, rawHistory)) : 48;++ let latest = null;+ let history = [];+ try {+ [latest, history] = await Promise.all([+ getLatestThreeSignal(sql),+ getThreeSignalHistory(sql, historyLimit),+ ]);+ } catch (err) {+ // During a DB outage the feed simply has nothing to serve yet — degrade to a+ // 503 the widget can retry, rather than a hard 500. Unknown errors rethrow to+ // wrap()'s alerting path.+ if (isDbUnavailableError(err)) {+ return error(res, 503, 'feed_unavailable', 'the $THREE signal feed is temporarily unavailable');+ }+ throw err;+ }++ let ageSeconds = null;+ let stale = true;+ if (latest?.ts) {+ const ageMs = Date.now() - new Date(latest.ts).getTime();+ ageSeconds = Math.max(0, Math.round(ageMs / 1000));+ stale = ageMs > STALE_AFTER_MS;+ }++ return json(res, 200, { latest, history, stale, age_seconds: ageSeconds }, {+ // Cache for a fraction of the 15-min write cadence — fresh enough, but the CDN+ // absorbs widget traffic so the DB isn't hit on every page load.+ 'Cache-Control': 'public, max-age=60, s-maxage=60',+ });+});diff --git a/data/changelog.json b/data/changelog.jsonindex fa9ecd426..726333e9d 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,31 @@{"$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": "Autonomous x402 Spend Loop — platform pays its own endpoints and learns from every call",+ "summary": "The platform's x402 seed wallet now actively participates in the agent economy on a 5-minute cron cycle. Every tick it selects up to 8 endpoints from a priority-ranked registry (oracle intel, sniper support, health checks, volume) and makes real USDC payments to each — recording every transaction to x402_autonomous_log with the full signal payload. Oracle-pipeline calls (crypto-intel for SOL/BTC/ETH/pump, $THREE signal feed) feed a new oracle_intel_signals table that the agent sniper reads directly: bullish macro signals lower the conviction threshold so the sniper fires more freely; bearish signals raise it. The loop also enforces a daily spend cap (default $5/day) and per-entry Redis cooldowns. This is the first time three.ws earns intelligence through payments and uses it to make better autonomous trading decisions.",+ "tags": ["feature", "infra"]+ },+ {+ "date": "2026-06-27",+ "title": "MCP Tool Latency Monitor — live SLA health for every MCP tool",+ "summary": "The platform now continuously watches the responsiveness of its MCP server — the interface AI agents use to render avatars, inspect models, read live market data, and more. Every 5 minutes an autonomous agent makes one real USDC payment to exercise the full paid path end-to-end, then sweeps every advertised tool and times the response each one returns to a caller. Rolling p50/p95/p99 latencies are recorded per tool, and any tool whose p95 exceeds 2 seconds raises an alert — so a slowdown is caught and surfaced on the internal ops dashboard before agents feel it.",+ "tags": ["feature", "infra"]+ },+ {+ "date": "2026-06-27",+ "title": "SSE Streaming MCP Health — continuous proof the paid MCP transport delivers cleanly",+ "summary": "Every five minutes an autonomous agent makes one real paid call to the platform's MCP server in streaming (SSE) mode and reads the response back as a live stream instead of a single buffered blob. It measures how fast the first byte arrives, the gaps between chunks, the chunk count and total bytes, and confirms the on-chain payment actually settled — then classifies the stream as clean, stalled, or dropped. A hung server, a half-delivered response, or broken chunked encoding now trips immediately and pages ops, with the full streaming-integrity history stored (mcp_stream_health) for the status surface, instead of being discovered by a paying agent whose tool call never finished. It runs on the x402 autonomous spend loop using the platform's own wallet.",+ "tags": ["infra"]+ },+ {+ "date": "2026-06-27",+ "title": "Scene Capture auto-processing — upload a video, get a 3D point cloud back",+ "summary": "Videos uploaded on /capture are now reconstructed into 3D point clouds automatically, with no waiting on the page. Each upload joins a processing queue that an autonomous agent drains on a 2-minute cadence: it pays a $0.01 USDC processing credit via x402, hands the video to the LingBot-Map GPU worker, then polls until the .ply point cloud is ready and stores the result on the job. When you come back, the finished cloud renders directly in the /capture viewer. Every run — submit, poll, success or failure — is recorded for full auditability, and the pipeline degrades cleanly when the GPU worker or wallet isn't configured.",+ "tags": ["feature", "infra"],+ "link": "/capture"+ },{"date": "2026-06-27","title": "Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive",diff --git a/public/changelog.json b/public/changelog.jsonindex 9e854eab5..ad8a4a7ce 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T23:06:31.898Z",+ "generated_at": "2026-06-27T23:09:05.881Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -140,6 +140,17 @@"improvement"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Autonomous x402 Spend Loop — platform pays its own endpoints and learns from every call",+ "summary": "The platform's x402 seed wallet now actively participates in the agent economy on a 5-minute cron cycle. Every tick it selects up to 8 endpoints from a priority-ranked registry (oracle intel, sniper support, health checks, volume) and makes real USDC payments to each — recording every transaction to x402_autonomous_log with the full signal payload. Oracle-pipeline calls (crypto-intel for SOL/BTC/ETH/pump, $THREE signal feed) feed a new oracle_intel_signals table that the agent sniper reads directly: bullish macro signals lower the conviction threshold so the sniper fires more freely; bearish signals raise it. The loop also enforces a daily spend cap (default $5/day) and per-entry Redis cooldowns. This is the first time three.ws earns intelligence through payments and uses it to make better autonomous trading decisions.",+ "link": null,+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-06-27","type": "update",@@ -302,6 +313,17 @@"infra"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "MCP Tool Latency Monitor — live SLA health for every MCP tool",+ "summary": "The platform now continuously watches the responsiveness of its MCP server — the interface AI agents use to render avatars, inspect models, read live market data, and more. Every 5 minutes an autonomous agent makes one real USDC payment to exercise the full paid path end-to-end, then sweeps every advertised tool and times the response each one returns to a caller. Rolling p50/p95/p99 latencies are recorded per tool, and any tool whose p95 exceeds 2 seconds raises an alert — so a slowdown is caught and surfaced on the internal ops dashboard before agents feel it.",+ "link": null,+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-06-27","type": "update",@@ -398,6 +420,17 @@"improvement"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Scene Capture auto-processing — upload a video, get a 3D point cloud back",+ "summary": "Videos uploaded on /capture are now reconstructed into 3D point clouds automatically, with no waiting on the page. Each upload joins a processing queue that an autonomous agent drains on a 2-minute cadence: it pays a $0.01 USDC processing credit via x402, hands the video to the LingBot-Map GPU worker, then polls until the .ply point cloud is ready and stores the result on the job. When you come back, the finished cloud renders directly in the /capture viewer. Every run — submit, poll, success or failure — is recorded for full auditability, and the pipeline degrades cleanly when the GPU worker or wallet isn't configured.",+ "link": "/capture",+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-06-27","type": "update",@@ -429,6 +462,16 @@"fix"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "SSE Streaming MCP Health — continuous proof the paid MCP transport delivers cleanly",+ "summary": "Every five minutes an autonomous agent makes one real paid call to the platform's MCP server in streaming (SSE) mode and reads the response back as a live stream instead of a single buffered blob. It measures how fast the first byte arrives, the gaps between chunks, the chunk count and total bytes, and confirms the on-chain payment actually settled — then classifies the stream as clean, stalled, or dropped. A hung server, a half-delivered response, or broken chunked encoding now trips immediately and pages ops, with the full streaming-integrity history stored (mcp_stream_health) for the status surface, instead of being discovered by a paying agent whose tool call never finished. It runs on the x402 autonomous spend loop using the platform's own wallet.",+ "link": null,+ "tags": [+ "infra"+ ]+ },{"date": "2026-06-27","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex b9ba0308e..07954d0bb 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -110,6 +110,14 @@<category>feature</category><description>The memetic launcher now auto-claims pump.fun creator fees from every coin it mints, routing the configured share toward $THREE. The admin console at /admin/launcher gains a live revenue panel (total creator fees claimed, $THREE allocated), agent-name visibility in the run feed, a Force Tick button for instant testing, and a cleaner 8-column stat grid. Know Your Meme is wired as a live trend source alongside Hacker News, Reddit, and Wikipedia — so the launcher reads what the internet is actually minting.</description></item>+ <item>+ <title>Autonomous x402 Spend Loop — platform pays its own endpoints and learns from every call</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-27:Autonomous x402 Spend Loop — platform pays its own endpoints and learns from every call</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The platform's x402 seed wallet now actively participates in the agent economy on a 5-minute cron cycle. Every tick it selects up to 8 endpoints from a priority-ranked registry (oracle intel, sniper support, health checks, volume) and makes real USDC payments to each — recording every transaction to x402_autonomous_log with the full signal payload. Oracle-pipeline calls (crypto-intel for SOL/BTC/ETH/pump, $THREE signal feed) feed a new oracle_intel_signals table that the agent sniper reads directly: bullish macro signals lower the conviction threshold so the sniper fires more freely; bearish signals raise it. The loop also enforces a daily spend cap (default $5/day) and per-entry Redis cooldowns. This is the first time three.ws earns intelligence through payments and uses it to make better autonomous trading decisions.</description>+ </item><item><title>Avatar Optimization Pipeline — nightly analysis of top avatars</title><link>https://three.ws/changelog</link>@@ -230,6 +238,14 @@<category>feature</category><description>The platform now runs a continuous quality sweep across every public 3D avatar in the database. Every 5 minutes the autonomous agent picks the longest-unvalidated GLB, inspects it with the glTF-Transform engine, and records a 0-100 quality score covering rig completeness, geometry health, texture sizing, triangle budget, and unsupported extensions. Results are stored in a time-series table (model_quality_scores) that will power quality badges and curation tools — surfacing models that need attention before users encounter errors in the viewer. The sweep is driven by the x402 autonomous spend loop at $0.001 USDC per call.</description></item>+ <item>+ <title>MCP Tool Latency Monitor — live SLA health for every MCP tool</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-27:MCP Tool Latency Monitor — live SLA health for every MCP tool</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The platform now continuously watches the responsiveness of its MCP server — the interface AI agents use to render avatars, inspect models, read live market data, and more. Every 5 minutes an autonomous agent makes one real USDC payment to exercise the full paid path end-to-end, then sweeps every advertised tool and times the response each one returns to a caller. Rolling p50/p95/p99 latencies are recorded per tool, and any tool whose p95 exceeds 2 seconds raises an alert — so a slowdown is caught and surfaced on the internal ops dashboard before agents feel it.</description>+ </item><item><title>Money Pulse now shows whether agent trading is viable</title><link>https://three.ws/pulse</link>@@ -302,6 +318,14 @@<category>feature</category><description>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.</description></item>+ <item>+ <title>Scene Capture auto-processing — upload a video, get a 3D point cloud back</title>+ <link>https://three.ws/capture</link>+ <guid isPermaLink="false">2026-06-27:Scene Capture auto-processing — upload a video, get a 3D point cloud back</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Videos uploaded on /capture are now reconstructed into 3D point clouds automatically, with no waiting on the page. Each upload joins a processing queue that an autonomous agent drains on a 2-minute cadence: it pays a $0.01 USDC processing credit via x402, hands the video to the LingBot-Map GPU worker, then polls until the .ply point cloud is ready and stores the result on the job. When you come back, the finished cloud renders directly in the /capture viewer. Every run — submit, poll, success or failure — is recorded for full auditability, and the pipeline degrades cleanly when the GPU worker or wallet isn't configured.</description>+ </item><item><title>Sign-in cooldown is now exact — and there's more headroom before it trips</title><link>https://three.ws/login</link>@@ -326,6 +350,14 @@<category>fix</category><description>Two fixes to the front door. The 3D avatar on the sign-up page — and on roughly fifty other pages that show a preview model — now loads reliably the first time, instead of occasionally staying blank until you reloaded; a timing race meant the model viewer could start loading a compressed avatar before its decoder was ready. Separately, the sign-up username field again enforces its rules (3–30 characters; letters, numbers, underscore and hyphen) as you type in the latest Chrome, where a stricter pattern-matching mode had quietly switched that live validation off. No action needed — both are automatic.</description></item>+ <item>+ <title>SSE Streaming MCP Health — continuous proof the paid MCP transport delivers cleanly</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-27:SSE Streaming MCP Health — continuous proof the paid MCP transport delivers cleanly</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>infra</category>+ <description>Every five minutes an autonomous agent makes one real paid call to the platform's MCP server in streaming (SSE) mode and reads the response back as a live stream instead of a single buffered blob. It measures how fast the first byte arrives, the gaps between chunks, the chunk count and total bytes, and confirms the on-chain payment actually settled — then classifies the stream as clean, stalled, or dropped. A hung server, a half-delivered response, or broken chunked encoding now trips immediately and pages ops, with the full streaming-integrity history stored (mcp_stream_health) for the status surface, instead of being discovered by a paying agent whose tool call never finished. It runs on the x402 autonomous spend loop using the platform's own wallet.</description>+ </item><item><title>Status page goes monochrome — with a fleet summary and an embeddable status badge</title><link>https://three.ws/status</link>diff --git a/public/features.json b/public/features.jsonindex cfb138f8f..53fff8313 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T23:06:31.432Z",+ "generated_at": "2026-06-27T23:09:05.819Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/test-scene-capture-processor.mjs b/scripts/test-scene-capture-processor.mjsindex cb5df0a71..ae4f5e975 100644--- a/scripts/test-scene-capture-processor.mjs+++ b/scripts/test-scene-capture-processor.mjs@@ -67,21 +67,29 @@ async function main() {console.warn(`\ncould not record log row: ${err?.message}`);}- const queue = await sql`- SELECT id, status, job_id, result_url, num_points, frames, tx_signature, amount_atomic, error_msg, updated_at- FROM scene_capture_queue ORDER BY updated_at DESC LIMIT 5- `.catch((e) => { console.warn('queue read failed:', e?.message); return []; });- console.log('\nscene_capture_queue (latest 5):');- console.table(queue);+ try {+ const queue = await sql`+ SELECT id, status, job_id, result_url, num_points, frames, tx_signature, amount_atomic, error_msg, updated_at+ FROM scene_capture_queue ORDER BY updated_at DESC LIMIT 5+ `;+ console.log('\nscene_capture_queue (latest 5):');+ console.table(queue);+ } catch (err) {+ console.warn('\nqueue read failed:', err?.message);+ }- const logRows = await sql`- SELECT service_name, amount_atomic, tx_signature, success, error_msg, signal_data, ts- FROM x402_autonomous_log- WHERE service_name = 'Scene Capture Video Queue Processor'- ORDER BY ts DESC LIMIT 3- `.catch(() => []);- console.log('\nx402_autonomous_log (latest 3 for this pipeline):');- console.dir(logRows, { depth: 6 });+ try {+ const logRows = await sql`+ SELECT service_name, amount_atomic, tx_signature, success, error_msg, signal_data, ts+ FROM x402_autonomous_log+ WHERE service_name = 'Scene Capture Video Queue Processor'+ ORDER BY ts DESC LIMIT 3+ `;+ console.log('\nx402_autonomous_log (latest 3 for this pipeline):');+ console.dir(logRows, { depth: 6 });+ } catch (err) {+ console.warn('\nlog read failed:', err?.message);+ }}main().then(() => process.exit(0)).catch((err) => {diff --git a/scripts/test-volume-bootstrap.mjs b/scripts/test-volume-bootstrap.mjsnew file mode 100644index 000000000..d02e82fc9--- /dev/null+++ b/scripts/test-volume-bootstrap.mjs@@ -0,0 +1,193 @@+// Manual test for the Volume Bootstrap Loop autonomous pipeline (USE-026).+//+// Exercises the round-robin selection, per-endpoint ledger upsert, per-call+// x402_autonomous_log recording, budget enforcement and graceful-failure paths+// of the 'volume-bootstrap-loop' registry entry — WITHOUT making real on-chain+// payments. It stubs the payment context (so payX402 short-circuits before+// touching Solana) and captures the SQL the pipeline issues. The only thing not+// exercised here is the on-chain USDC transfer itself (that requires the seed+// wallet + mainnet and is driven by the cron loop in production).+//+// node scripts/test-volume-bootstrap.mjs+//+// With DATABASE_URL set it additionally runs the real schema + a real ledger+// upsert and reads the row back.++import { randomUUID } from 'node:crypto';++import {+ run as volumeRun,+ VOLUME_ENDPOINTS,+ VOLUME_BATCH_PER_RUN,+} from '../api/_lib/x402/pipelines/volume-bootstrap-loop.js';++// The full registry transitively imports every sibling pipeline; if a concurrent+// agent's in-progress pipeline has a broken import, the registry won't load. The+// registry-shape check below degrades to a warning in that case rather than+// failing this pipeline's own test.+async function loadRegistryEntry() {+ try {+ const { getSelfRegistry } = await import('../api/_lib/x402/autonomous-registry.js');+ return { entry: getSelfRegistry().find((e) => e.id === 'volume-bootstrap-loop'), loaded: true };+ } catch (err) {+ return { entry: null, loaded: false, error: err?.message };+ }+}++let failures = 0;+function check(label, cond, detail) {+ const ok = !!cond;+ if (!ok) failures++;+ console.log(`${ok ? ' ✓' : ' ✗'} ${label}${detail ? ` — ${detail}` : ''}`);+}++// In-memory SQL stub: tagged-template that records every statement and serves a+// minimal x402_volume_metrics ledger so RETURNING comes back populated.+function makeSqlStub() {+ const statements = [];+ const ledger = new Map();+ const sql = (strings, ...vals) => {+ const text = strings.join('?').replace(/\s+/g, ' ').trim();+ statements.push({ text, vals });+ if (/INSERT INTO x402_volume_metrics/i.test(text)) {+ const key = vals[0];+ const prev = ledger.get(key) || { call_count: 0, success_count: 0, fail_count: 0, total_spent_atomic: 0 };+ const success = vals[10] === true; // last_success position+ const amount = Number(vals[8]) || 0; // last_amount_atomic position+ const row = {+ call_count: prev.call_count + 1,+ success_count: prev.success_count + (success ? 1 : 0),+ fail_count: prev.fail_count + (success ? 0 : 1),+ total_spent_atomic: prev.total_spent_atomic + amount,+ };+ ledger.set(key, row);+ return Promise.resolve([row]);+ }+ return Promise.resolve([]);+ };+ sql.statements = statements;+ sql.ledger = ledger;+ return sql;+}++// Stubbed payment context: present buyer/conn/blockhash/mintInfo so the pipeline+// skips bootstrapSolanaContext. payX402 will still issue a real fetch to the+// origin; we point origin at an unreachable host so every call resolves to a+// recorded failure (no payment, no network success) — which is exactly the path+// we want to verify records cleanly without spending.+function stubPaymentCtx(extra = {}) {+ return {+ buyer: { publicKey: { toBase58: () => 'TestBuyer1111111111111111111111111111111111' } },+ conn: { getAccountInfo: async () => null },+ blockhash: 'TestBlockhash1111111111111111111111111111111',+ mintInfo: { decimals: 6 },+ origin: 'http://127.0.0.1:1', // unreachable → payX402 fetch fails fast+ redis: null,+ ...extra,+ };+}++async function main() {+ console.log('\n1. Registry entry shape');+ const { entry, loaded, error } = await loadRegistryEntry();+ if (!loaded) {+ console.log(` ⚠ registry import failed (unrelated sibling pipeline): ${error}`);+ console.log(' → skipping registry-shape checks; pipeline checks below still run.');+ } else {+ check('entry present', !!entry);+ check('pipeline tag volume', entry?.pipeline === 'volume', entry?.pipeline);+ check('cooldown 300s', entry?.cooldown_s === 300);+ check('enabled', entry?.enabled === true);+ check('has run()', typeof entry?.run === 'function');+ }++ console.log('\n2. Endpoint catalog');+ check('non-empty catalog', VOLUME_ENDPOINTS.length > 0, `${VOLUME_ENDPOINTS.length} endpoints`);+ check('every entry has key+path+method', VOLUME_ENDPOINTS.every((e) => e.key && e.path && e.method));+ check('keys are unique', new Set(VOLUME_ENDPOINTS.map((e) => e.key)).size === VOLUME_ENDPOINTS.length);+ check('paths are all self /api/x402 or /api', VOLUME_ENDPOINTS.every((e) => e.path.startsWith('/api/')));+ check('never lists itself (no recursion)', !VOLUME_ENDPOINTS.some((e) => e.key === 'volume-bootstrap-loop'));++ console.log('\n3. run() — sweeps a window, records each call, no real spend');+ const sql = makeSqlStub();+ const out = await volumeRun({ ...stubPaymentCtx(), sql, runId: randomUUID() });+ check('returns an outcome object', out && typeof out === 'object');+ check('amountAtomic is 0 (no payment settled)', out.amountAtomic === 0, String(out.amountAtomic));+ check('not skipped (calls were made)', out.skipped === false);+ check('window matches batch size', out.responseData?.window === VOLUME_BATCH_PER_RUN, String(out.responseData?.window));+ check('one log row per swept endpoint',+ sql.statements.filter((s) => /INSERT INTO x402_autonomous_log/i.test(s.text)).length === VOLUME_BATCH_PER_RUN);+ check('one ledger upsert per swept endpoint',+ sql.statements.filter((s) => /INSERT INTO x402_volume_metrics/i.test(s.text)).length === VOLUME_BATCH_PER_RUN);+ check('issued CREATE TABLE for ledger',+ sql.statements.some((s) => /CREATE TABLE IF NOT EXISTS x402_volume_metrics/i.test(s.text)));+ check('ensured value_extracted column',+ sql.statements.some((s) => /ADD COLUMN IF NOT EXISTS value_extracted/i.test(s.text)));+ const logRows = sql.statements.filter((s) => /INSERT INTO x402_autonomous_log/i.test(s.text));+ check('log rows tagged pipeline=volume', logRows.every((s) => s.vals.includes('volume')));+ check('log rows tagged endpoint_type=self', logRows.every((s) => s.vals.includes('self')));++ console.log('\n4. round-robin advances across runs (in-memory cursor)');+ const sweptKeys = (o) => (o.responseData?.swept || []).map((s) => s.key).join(',');+ const r1 = await volumeRun({ ...stubPaymentCtx(), sql: makeSqlStub(), runId: randomUUID() });+ const r2 = await volumeRun({ ...stubPaymentCtx(), sql: makeSqlStub(), runId: randomUUID() });+ check('consecutive runs sweep different windows', sweptKeys(r1) !== sweptKeys(r2), `${sweptKeys(r1)} | ${sweptKeys(r2)}`);++ console.log('\n5. per-run budget cap halts the sweep');+ const cappedSql = makeSqlStub();+ // remainingCap below one call's worth → window selected but cap guard trips.+ const capped = await volumeRun({ ...stubPaymentCtx(), sql: cappedSql, runId: randomUUID(), remainingCap: 0 });+ check('zero cap → no calls, skipped', capped.skipped === true && capped.responseData?.calls === 0, JSON.stringify(capped.responseData));+ check('zero cap → no log rows', !cappedSql.statements.some((s) => /INSERT INTO x402_autonomous_log/i.test(s.text)));++ console.log('\n6. graceful skip when wallet/RPC unconfigured');+ // No buyer/conn → bootstrapSolanaContext runs; with no seed wallet + no mint+ // it throws and the pipeline returns a logged skip (note set). In CI where a+ // test wallet/mint may be present it instead proceeds — accept either as long+ // as it never throws.+ let threw = false;+ let res6;+ try { res6 = await volumeRun({ sql: makeSqlStub(), origin: 'http://127.0.0.1:1', redis: null, runId: randomUUID() }); }+ catch { threw = true; }+ check('never throws on unconfigured wallet', threw === false);+ check('returns a structured outcome', res6 && typeof res6.success === 'boolean');++ console.log('\n7. DB failure inside ledger upsert never crashes the sweep');+ const flakySql = (strings, ...vals) => {+ const text = strings.join('?');+ if (/INSERT INTO x402_volume_metrics/i.test(text)) return Promise.reject(new Error('simulated db outage'));+ return Promise.resolve([]);+ };+ let crashed = false;+ let res7;+ try { res7 = await volumeRun({ ...stubPaymentCtx(), sql: flakySql, runId: randomUUID() }); }+ catch { crashed = true; }+ check('sweep survives ledger DB faults', crashed === false && !!res7);++ // Optional: real DB round-trip when DATABASE_URL is configured.+ if (process.env.DATABASE_URL || process.env.POSTGRES_URL) {+ console.log('\n8. real DB schema + ledger upsert + read-back');+ const { sql: realSql } = await import('../api/_lib/db.js');+ const { default: pipeline } = { default: null };+ void pipeline;+ // Re-import the internal upsert path by running a single-window sweep with a+ // real sql but unreachable origin (records failures, exercises real DDL+DML).+ const runId = randomUUID();+ const before = await realSql`SELECT count(*)::int AS n FROM x402_volume_metrics`.catch(() => [{ n: 0 }]);+ await volumeRun({ ...stubPaymentCtx(), sql: realSql, runId });+ const rows = await realSql`SELECT endpoint_key, call_count, last_run_id FROM x402_volume_metrics ORDER BY last_called_at DESC LIMIT ${VOLUME_BATCH_PER_RUN}`;+ check('ledger rows persisted', rows.length > 0, `${rows.length} rows`);+ check('call_count >= 1', rows.every((r) => Number(r.call_count) >= 1));+ void before;+ } else {+ console.log('\n8. 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/tests/api/x402-cosmetic-pricing-audit.test.js b/tests/api/x402-cosmetic-pricing-audit.test.jsnew file mode 100644index 000000000..c4bbebadb--- /dev/null+++ b/tests/api/x402-cosmetic-pricing-audit.test.js@@ -0,0 +1,157 @@+// Avatar Marketplace Dynamic Pricing — autonomous pipeline branch coverage.+//+// Exercises run() from api/_lib/x402/pipelines/cosmetic-pricing-audit.js in+// isolation: the DB, the Solana connection, and the x402 payment client are all+// stubbed so no network / no chain is touched. We assert:+// • wallet unconfigured → free drift sweep still runs, no payment, skip+// • happy path (quotes match) → cheapest item purchased, 0 drift/underpriced+// • underpricing detected → flagged in findings + value_extracted summary+// • probe network failure → recorded per item, never crashes the run++import { describe, it, expect, vi, beforeEach } from 'vitest';++// Real, pure catalog helpers — these drive the "expected" prices the audit+// compares quotes against, so we derive test fixtures from the same source.+import { buildCatalog } from '../../api/_lib/cosmetics.js';++const PREMIUM = buildCatalog().filter((c) => c.premium);+const CHEAPEST = [...PREMIUM].sort(+ (a, b) => Number(a.priceUsdcAtomics) - Number(b.priceUsdcAtomics) || a.id.localeCompare(b.id),+)[0];++// ── Mocks ────────────────────────────────────────────────────────────────────+const sqlLog = [];+const sql = vi.fn((strings) => {+ sqlLog.push(strings.join(' ? ').replace(/\s+/g, ' ').trim());+ return Promise.resolve([]);+});++// Quote returned by the live endpoint per cosmetic id. Defaults to the catalog+// price (no drift); a test overrides individual ids to simulate drift.+let quoteFor = {};+let probeThrowsForId = null;++const fetchWithTimeout = vi.fn(async (url) => {+ const id = decodeURIComponent(new URL(url).searchParams.get('id') || '');+ if (probeThrowsForId && id === probeThrowsForId) throw new Error('network_down');+ const item = PREMIUM.find((c) => c.id === id);+ const amount = String(quoteFor[id] ?? item?.priceUsdcAtomics ?? '0');+ return {+ status: 402,+ ok: false,+ headers: new Map(),+ body: { accepts: [{ network: 'solana:mainnet', asset: 'USDCmint', amount, extra: { feePayer: 'FP' }, payTo: 'PT' }] },+ };+});++const parseSolanaAccept = (challenge) =>+ (challenge?.accepts || []).find((a) => typeof a?.network === 'string' && a.network.startsWith('solana')) || null;++let loadSeedKeypairImpl = () => ({ publicKey: { toBase58: () => 'PAYER' } });+const loadSeedKeypair = vi.fn(() => loadSeedKeypairImpl());++let payX402Impl = async () => ({+ status: 'paid', success: true, amountAtomic: Number(CHEAPEST.priceUsdcAtomics),+ txSig: 'sig_123', responseBody: { ok: true }, errorMsg: null,+});+const payX402 = vi.fn((...a) => payX402Impl(...a));++vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sql(...a) }));+vi.mock('../../api/_lib/env.js', () => ({+ env: { APP_ORIGIN: 'https://three.ws', X402_ASSET_MINT_SOLANA: 'USDCmint', SOLANA_RPC_URL: 'http://rpc' },+}));+vi.mock('../../api/_lib/usage.js', () => ({ logger: () => ({ info() {}, warn() {} }) }));+vi.mock('../../api/_lib/solana/connection.js', () => ({+ solanaConnection: () => ({+ getLatestBlockhash: async () => ({ blockhash: 'bh' }),+ getAccountInfo: async () => null,+ }),+}));+vi.mock('../../api/_lib/x402/solana-payer.js', () => ({+ loadSeedKeypair: (...a) => loadSeedKeypair(...a),+ payX402: (...a) => payX402(...a),+ fetchWithTimeout: (...a) => fetchWithTimeout(...a),+ parseSolanaAccept: (...a) => parseSolanaAccept(...a),+}));++import { run } from '../../api/_lib/x402/pipelines/cosmetic-pricing-audit.js';++// A payment context that avoids any real Solana lookups.+const PAID_CTX = { conn: {}, blockhash: 'bh', mintInfo: { decimals: 6 }, origin: 'https://three.ws', remainingCap: 5_000_000 };++beforeEach(() => {+ sqlLog.length = 0;+ quoteFor = {};+ probeThrowsForId = null;+ loadSeedKeypairImpl = () => ({ publicKey: { toBase58: () => 'PAYER' } });+ payX402Impl = async () => ({+ status: 'paid', success: true, amountAtomic: Number(CHEAPEST.priceUsdcAtomics),+ txSig: 'sig_123', responseBody: { ok: true }, errorMsg: null,+ });+ vi.clearAllMocks();+});++describe('cosmetic pricing audit pipeline', () => {+ it('there is at least one premium item to audit (fixture sanity)', () => {+ expect(PREMIUM.length).toBeGreaterThan(0);+ expect(Number(CHEAPEST.priceUsdcAtomics)).toBeGreaterThan(0);+ });++ it('wallet unconfigured: runs the free drift sweep, never pays, returns skipped', async () => {+ loadSeedKeypairImpl = () => { throw new Error('seed keypair not configured'); };++ const out = await run({ ...PAID_CTX, buyer: undefined });++ expect(payX402).not.toHaveBeenCalled();+ expect(out.skipped).toBe(true);+ expect(out.reason).toBe('wallet_unconfigured');+ expect(out.amountAtomic).toBe(0);+ expect(out.items).toBe(PREMIUM.length);+ // Probed every premium item even without a wallet.+ expect(fetchWithTimeout).toHaveBeenCalledTimes(PREMIUM.length);+ // One audit row per item + one summary row at minimum.+ expect(sqlLog.some((t) => t.includes('INSERT INTO cosmetic_pricing_audit'))).toBe(true);+ expect(sqlLog.some((t) => t.includes('INSERT INTO x402_autonomous_log'))).toBe(true);+ });++ it('happy path: purchases the cheapest item, reports zero drift', async () => {+ const out = await run({ ...PAID_CTX, buyer: loadSeedKeypair() });++ expect(out.ok).toBe(true);+ expect(out.success).toBe(true);+ expect(out.driftCount).toBe(0);+ expect(out.underpricedCount).toBe(0);+ expect(out.purchasedId).toBe(CHEAPEST.id);+ expect(out.amountAtomic).toBe(Number(CHEAPEST.priceUsdcAtomics));+ expect(out.txSig).toBe('sig_123');++ // Exactly one real payment, against the cheapest premium item, over GET.+ expect(payX402).toHaveBeenCalledTimes(1);+ const arg = payX402.mock.calls[0][0];+ expect(arg.method).toBe('GET');+ expect(arg.endpointUrl).toContain(`id=${encodeURIComponent(CHEAPEST.id)}`);+ });++ it('underpricing detected: a too-low quote is flagged', async () => {+ const victim = PREMIUM.find((c) => c.id !== CHEAPEST.id) || PREMIUM[0];+ quoteFor[victim.id] = Number(victim.priceUsdcAtomics) - 1; // 1 atomic under++ const out = await run({ ...PAID_CTX, buyer: loadSeedKeypair() });++ expect(out.underpricedCount).toBeGreaterThanOrEqual(1);+ expect(out.driftCount).toBeGreaterThanOrEqual(1);+ // The summary signal carries the offending id for alerting.+ expect(out.signalData.underpriced_ids).toContain(victim.id);+ });++ it('probe network failure on one item is recorded, run still completes', async () => {+ probeThrowsForId = PREMIUM[0].id;++ const out = await run({ ...PAID_CTX, buyer: loadSeedKeypair() });++ expect(out.ok).toBe(true);+ // Still wrote an audit row for every item (including the failed probe).+ const auditInserts = sqlLog.filter((t) => t.includes('INSERT INTO cosmetic_pricing_audit')).length;+ expect(auditInserts).toBe(PREMIUM.length);+ });+});diff --git a/tests/x402-model-metadata-enrichment.test.js b/tests/x402-model-metadata-enrichment.test.jsnew file mode 100644index 000000000..c5d39fc43--- /dev/null+++ b/tests/x402-model-metadata-enrichment.test.js@@ -0,0 +1,110 @@+import { describe, it, expect } from 'vitest';++import {+ deriveModelMetadata,+ parseInspectResult,+ inspectModelRpcBody,+} from '../api/_lib/x402/enrich-model-metadata.js';+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';++// A minimal inspect_model structuredContent shape (matches src/gltf-inspect.js).+const inspection = (over = {}) => ({+ url: 'https://cdn.three.ws/u/x/model.glb',+ filename: 'model.glb',+ container: 'glb',+ generator: 'Khronos Blender glTF 2.0 exporter',+ version: '2.0',+ extensionsUsed: [],+ counts: {+ scenes: 1, nodes: 5, meshes: 1, materials: 1, textures: 1,+ animations: 0, skins: 0, totalVertices: 4000, totalTriangles: 5000,+ indexedPrimitives: 1, nonIndexedPrimitives: 0,+ ...(over.counts || {}),+ },+ ...over,+});++describe('model metadata enrichment — deriveModelMetadata', () => {+ it('tags a static, single-mesh, textured low-poly glb', () => {+ const { tags, model_category } = deriveModelMetadata(inspection());+ expect(tags).toContain('glb');+ expect(tags).toContain('static');+ expect(tags).toContain('single-mesh');+ expect(tags).toContain('textured');+ expect(tags).toContain('low-poly');+ expect(tags).not.toContain('animated');+ expect(model_category).toBe('prop');+ });++ it('classifies a skinned, animated mesh as an avatar', () => {+ const info = inspection({ counts: { skins: 1, animations: 3, meshes: 2, textures: 2, materials: 2, totalTriangles: 45000 } });+ const { tags, model_category } = deriveModelMetadata(info);+ expect(tags).toContain('rigged');+ expect(tags).toContain('animated');+ expect(tags).toContain('multi-mesh');+ expect(tags).toContain('multi-material');+ expect(tags).toContain('mid-poly');+ expect(model_category).toBe('avatar');+ });++ it('buckets triangles into low / mid / high poly tiers', () => {+ expect(deriveModelMetadata(inspection({ counts: { totalTriangles: 9000 } })).tags).toContain('low-poly');+ expect(deriveModelMetadata(inspection({ counts: { totalTriangles: 50000 } })).tags).toContain('mid-poly');+ expect(deriveModelMetadata(inspection({ counts: { totalTriangles: 250000 } })).tags).toContain('high-poly');+ });++ it('marks an untextured mesh and compression extensions', () => {+ const info = inspection({+ counts: { textures: 0, materials: 0 },+ extensionsUsed: ['KHR_draco_mesh_compression', 'KHR_texture_basisu', 'EXT_meshopt_compression'],+ });+ const { tags } = deriveModelMetadata(info);+ expect(tags).toContain('untextured');+ expect(tags).toContain('draco');+ expect(tags).toContain('ktx2');+ expect(tags).toContain('meshopt');+ });++ it('caps the tag set at 20 and never returns duplicates', () => {+ const { tags } = deriveModelMetadata(inspection());+ expect(tags.length).toBeLessThanOrEqual(20);+ expect(new Set(tags).size).toBe(tags.length);+ });+});++describe('model metadata enrichment — parseInspectResult', () => {+ it('pulls structuredContent out of a JSON-RPC tools/call response', () => {+ const body = { jsonrpc: '2.0', id: 1, result: { structuredContent: inspection() } };+ expect(parseInspectResult(body)).toMatchObject({ container: 'glb' });+ });++ it('returns null on a tool error, a JSON-RPC error, or a malformed envelope', () => {+ expect(parseInspectResult({ result: { isError: true, structuredContent: inspection() } })).toBeNull();+ expect(parseInspectResult({ error: { code: -32000, message: 'boom' } })).toBeNull();+ expect(parseInspectResult({ result: { structuredContent: { no: 'counts' } } })).toBeNull();+ expect(parseInspectResult(null)).toBeNull();+ });+});++describe('model metadata enrichment — inspectModelRpcBody', () => {+ it('builds a tools/call envelope for inspect_model with the GLB url', () => {+ const body = inspectModelRpcBody('https://cdn.three.ws/a.glb');+ expect(body).toMatchObject({+ jsonrpc: '2.0',+ method: 'tools/call',+ params: { name: 'inspect_model', arguments: { url: 'https://cdn.three.ws/a.glb' } },+ });+ });+});++describe('model metadata enrichment — registry wiring', () => {+ it('is registered as an enabled, hourly, run()-style 3d entry on /api/mcp', () => {+ const entry = getFullRegistry().find((e) => e.id === 'enrich-model-metadata');+ expect(entry).toBeTruthy();+ expect(entry.enabled).toBe(true);+ expect(entry.pipeline).toBe('3d');+ expect(entry.cooldown_s).toBe(3600);+ expect(entry.path).toBe('/api/mcp');+ expect(typeof entry.run).toBe('function');+ });+});diff --git a/tests/x402-thumbnail-regen.test.js b/tests/x402-thumbnail-regen.test.jsnew file mode 100644index 000000000..d42220770--- /dev/null+++ b/tests/x402-thumbnail-regen.test.js@@ -0,0 +1,204 @@+// Unit tests for the Avatar Thumbnail Regeneration pipeline (USE-015):+// api/_lib/x402/thumbnail-regen.js.+//+// The DB and the shared x402 payment client are mocked. The sql mock dispatches+// on query text so the (idempotent) schema DDL in ensureRegenSchema is ignored+// and only the meaningful SELECT/INSERT/UPDATE results are asserted on.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// ── mock DB: route by query text ────────────────────────────────────────────+const dbState = {+ staleAsset: null, // row selectStaleAsset returns (or null → [])+ enqueueId: 99, // RETURNING id from enqueue (null → conflict/no-op)+ calls: [], // captured { text } for assertions+};++vi.mock('../api/_lib/db.js', () => {+ const sql = vi.fn(async (strings, ...values) => {+ const text = Array.isArray(strings) ? strings.join('?') : String(strings);+ dbState.calls.push({ text, values });+ if (/FROM\s+paid_assets\s+pa/i.test(text)) {+ return dbState.staleAsset ? [dbState.staleAsset] : [];+ }+ if (/INSERT\s+INTO\s+avatar_thumbnail_regen_jobs/i.test(text)) {+ return dbState.enqueueId == null ? [] : [{ id: dbState.enqueueId }];+ }+ if (/UPDATE\s+avatar_thumbnail_regen_jobs/i.test(text) && /RETURNING/i.test(text)) {+ return dbState.claim || [];+ }+ return [];+ });+ return { sql };+});++// ── mock payment client ─────────────────────────────────────────────────────+const payState = { result: null, lastArgs: null };+vi.mock('../api/_lib/x402/pay.js', () => ({+ payX402: vi.fn(async (args) => {+ payState.lastArgs = args;+ if (payState.result instanceof Error) throw payState.result;+ return payState.result;+ }),+}));++import {+ runThumbnailRegen,+ enqueueRegenJob,+ thumbnailKeyFor,+ THUMBNAIL_REGEN_ENDPOINT,+ STALE_DAYS,+} from '../api/_lib/x402/thumbnail-regen.js';+import { payX402 } from '../api/_lib/x402/pay.js';++const SOLANA_CTX = {+ origin: 'https://three.ws',+ buyer: { publicKey: { toBase58: () => 'BuyerPubkey1111' } },+ conn: {},+ blockhash: 'hash',+ mintInfo: { decimals: 6 },+ remainingCap: 5_000_000,+ runId: '11111111-2222-3333-4444-555555555555',+ log: { info() {}, warn() {} },+};++const ASSET = {+ id: 'asset-uuid-1',+ slug: 'pole-dancer-rumba',+ title: 'Pole Dancer (Rumba)',+ r2_key: 'assets/pole-dancer-rumba.glb',+ avatar_id: 'avatar-uuid-1',+ price_atomics: '5000',+};++beforeEach(() => {+ dbState.staleAsset = null;+ dbState.enqueueId = 99;+ dbState.claim = [];+ dbState.calls = [];+ payState.result = null;+ payState.lastArgs = null;+ payX402.mockClear();+});++describe('thumbnailKeyFor', () => {+ it('is deterministic, slug-safe, and run-scoped', () => {+ const k = thumbnailKeyFor('pole-dancer-rumba', 'abcdef0123456789');+ expect(k).toBe('thumbnails/assets/pole-dancer-rumba-abcdef01.png');+ });+ it('sanitizes unsafe slug characters', () => {+ const k = thumbnailKeyFor('weird/slug name!', 'run');+ expect(k).toMatch(/^thumbnails\/assets\/weird-slug-name--run\.png$/);+ });+});++describe('runThumbnailRegen — guards', () => {+ it('skips gracefully when the Solana context (wallet) is unavailable', async () => {+ const out = await runThumbnailRegen({ origin: 'https://three.ws' });+ expect(out.skipped).toBe(true);+ expect(out.success).toBe(false);+ expect(out.amountAtomic).toBe(0);+ expect(payX402).not.toHaveBeenCalled();+ });++ it('skips (no spend) when nothing is stale', async () => {+ dbState.staleAsset = null;+ const out = await runThumbnailRegen(SOLANA_CTX);+ expect(out.skipped).toBe(true);+ expect(out.success).toBe(true);+ expect(out.note).toBe('no_stale_assets');+ expect(payX402).not.toHaveBeenCalled();+ });+});++describe('runThumbnailRegen — happy path', () => {+ it('pays asset-download for the stale slug and queues a regen job', async () => {+ dbState.staleAsset = ASSET;+ payState.result = {+ success: true, paid: true, free: false, skipped: false,+ amountAtomic: 5000, txSig: 'TxSig123', status: 200,+ responseBody: { ok: true, slug: ASSET.slug, sizeBytes: 6_492_840, downloadUrl: 'https://r2.dev/x?sig=secret' },+ };++ const out = await runThumbnailRegen(SOLANA_CTX);++ // Paid the correct per-asset URL via GET.+ expect(payX402).toHaveBeenCalledTimes(1);+ expect(payState.lastArgs.method).toBe('GET');+ expect(payState.lastArgs.url).toBe(`https://three.ws${THUMBNAIL_REGEN_ENDPOINT}?slug=${ASSET.slug}`);+ expect(payState.lastArgs.remainingCap).toBe(SOLANA_CTX.remainingCap);++ // Outcome reflects a real settlement + queued job.+ expect(out.success).toBe(true);+ expect(out.amountAtomic).toBe(5000);+ expect(out.txSig).toBe('TxSig123');+ expect(out.signalData.job_id).toBe(99);+ expect(out.signalData.downloaded).toBe(true);+ expect(out.note).toContain('queued regen');++ // The short-lived presigned URL is never persisted verbatim.+ expect(out.responseData.download_url).toBe('[presigned]');+ expect(JSON.stringify(out)).not.toContain('secret');++ // A regen job INSERT happened.+ const insert = dbState.calls.find((c) => /INSERT\s+INTO\s+avatar_thumbnail_regen_jobs/i.test(c.text));+ expect(insert).toBeTruthy();+ });++ it('counts no spend and does not enqueue when payment fails (402 reject)', async () => {+ dbState.staleAsset = ASSET;+ payState.result = {+ success: false, paid: false, free: false, skipped: false,+ amountAtomic: 5000, txSig: null, status: 402,+ responseBody: { error: 'verify_failed' }, errorMsg: 'http_402',+ };++ const out = await runThumbnailRegen(SOLANA_CTX);++ expect(out.success).toBe(false);+ expect(out.amountAtomic).toBe(0); // only on-chain settlement counts+ expect(out.errorMsg).toContain('http_402');+ const insert = dbState.calls.find((c) => /INSERT\s+INTO\s+avatar_thumbnail_regen_jobs/i.test(c.text));+ expect(insert).toBeFalsy();+ });++ it('never throws when payX402 throws (network fault)', async () => {+ dbState.staleAsset = ASSET;+ payState.result = new Error('ECONNRESET');+ const out = await runThumbnailRegen(SOLANA_CTX);+ expect(out.success).toBe(false);+ expect(out.errorMsg).toContain('pay_failed');+ expect(out.amountAtomic).toBe(0);+ });++ it('reports a duplicate (in-flight) job as job=dup without failing', async () => {+ dbState.staleAsset = ASSET;+ dbState.enqueueId = null; // ON CONFLICT DO NOTHING → no id+ payState.result = {+ success: true, paid: true, amountAtomic: 5000, txSig: 'TxDup',+ status: 200, responseBody: { ok: true, slug: ASSET.slug, sizeBytes: 1 },+ };+ const out = await runThumbnailRegen(SOLANA_CTX);+ expect(out.success).toBe(true);+ expect(out.signalData.job_id).toBe(null);+ expect(out.note).toContain('job=dup');+ });+});++describe('enqueueRegenJob', () => {+ it('requires slug and r2_key', async () => {+ await expect(enqueueRegenJob({ asset: { slug: 'x' } })).rejects.toThrow(/r2_key/);+ });+ it('returns the inserted job id', async () => {+ dbState.enqueueId = 7;+ const id = await enqueueRegenJob({ asset: ASSET, runId: 'r', txSig: 't', amountAtomic: 5000, responseBody: { slug: ASSET.slug, sizeBytes: 10 } });+ expect(id).toBe(7);+ });+});++describe('constants', () => {+ it('targets asset-download with a sane staleness window', () => {+ expect(THUMBNAIL_REGEN_ENDPOINT).toBe('/api/x402/asset-download');+ expect(STALE_DAYS).toBe(30);+ });+});diff --git a/workers/agent-sniper/oracle-gate.js b/workers/agent-sniper/oracle-gate.jsindex 7cb58cab4..24704c95f 100644--- a/workers/agent-sniper/oracle-gate.js+++ b/workers/agent-sniper/oracle-gate.js@@ -5,6 +5,10 @@// the coin has no Oracle score yet (e.g. brand-new mints that haven't been// classified). Caches each result within a 30-second window so repeated// lookups within a burst share one DB round-trip.+//+// Macro signal adjustment: reads oracle_intel_signals (populated by the+// x402 autonomous loop) to widen or tighten the min_oracle_score threshold+// based on current SOL/BTC/pump market sentiment.import { sql } from '../../api/_lib/db.js';import { log } from './log.js';@@ -12,19 +16,93 @@ import { log } from './log.js';const _cache = new Map(); // key → { score, ts }const CACHE_TTL_MS = 30_000;+// Macro signal cache — shared across all gate calls, refreshed every 2 min.+let _macroCache = null;+let _macroCacheTs = 0;+const MACRO_TTL_MS = 120_000;+function n(v) {const x = Number(v);return Number.isFinite(x) ? x : null;}+/**+ * Fetch recent macro signals from oracle_intel_signals and compute a+ * threshold adjustment in score points.+ *+ * Returns a number: positive = raise bar (bearish), negative = lower bar (bullish).+ * Returns 0 on any error (fail-open).+ */+async function getMacroAdjustment() {+ if (_macroCache !== null && Date.now() - _macroCacheTs < MACRO_TTL_MS) {+ return _macroCache;+ }+ try {+ const rows = await sql`+ select source_id, topic, signal, confidence, ts+ from oracle_intel_signals+ where topic in ('solana', 'bitcoin', 'pump')+ and ts > now() - interval '1 hour'+ order by ts desc+ `;++ if (!rows.length) {+ _macroCache = 0;+ _macroCacheTs = Date.now();+ return 0;+ }++ // Latest signal per topic (rows already ordered desc by ts).+ const latest = {};+ for (const row of rows) {+ if (!latest[row.topic]) latest[row.topic] = row;+ }++ let adjustment = 0;+ const WEIGHTS = { solana: 1.2, bitcoin: 0.8, pump: 1.5 };++ for (const [topic, row] of Object.entries(latest)) {+ const w = WEIGHTS[topic] ?? 1.0;+ const conf = n(row.confidence) ?? 50;+ const confFactor = conf / 100;+ const sig = (row.signal ?? '').toLowerCase();++ if (sig === 'bearish') {+ // Raise threshold — harder to snipe in bearish macro.+ adjustment += Math.round(10 * w * confFactor);+ } else if (sig === 'bullish') {+ // Lower threshold — easier to snipe in bullish macro.+ adjustment -= Math.round(5 * w * confFactor);+ }+ // 'neutral' → no adjustment.+ }++ // Clamp: never move the bar more than ±15 points.+ adjustment = Math.max(-15, Math.min(15, adjustment));+ _macroCache = adjustment;+ _macroCacheTs = Date.now();+ return adjustment;+ } catch (err) {+ log.warn('oracle gate macro signal error — no adjustment', { err: err?.message });+ _macroCache = 0;+ _macroCacheTs = Date.now();+ return 0;+ }+}+/*** Look up the Oracle conviction score for a mint and decide whether the* strategy's min_oracle_score threshold is met.*+ * The effective threshold = min_oracle_score + macro_adjustment, where+ * macro_adjustment is derived from oracle_intel_signals (populated by+ * the x402 autonomous spend loop every 5 minutes).+ ** Returns:- * { pass: true } — scored and above threshold (or no threshold)- * { pass: false, reason: string } — scored and below threshold- * { pass: true, skipped: true } — no Oracle score yet; gate deferred+ * { pass: true } — scored and above threshold (or no threshold)+ * { pass: false, reason: string } — scored and below threshold+ * { pass: true, skipped: true } — no Oracle score yet; gate deferred+ * All results include macro_adjustment when a threshold was evaluated.** @param {string} mint* @param {string} network@@ -64,9 +142,17 @@ export async function oracleGate(mint, network, strat) {return { pass: true, skipped: true };}- if (score < minScore) {- return { pass: false, reason: `oracle_below_min:${score}<${minScore}` };+ // Apply macro signal adjustment from x402 autonomous loop intel.+ const macroAdj = await getMacroAdjustment();+ const effectiveMin = minScore + macroAdj;++ if (score < effectiveMin) {+ return {+ pass: false,+ reason: `oracle_below_min:${score}<${effectiveMin}${macroAdj !== 0 ? `(base:${minScore}+macro:${macroAdj})` : ''}`,+ macro_adjustment: macroAdj,+ };}- return { pass: true };+ return { pass: true, macro_adjustment: macroAdj };}