Skip to content

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.

Add integration tests for granite inference health, idempotency audit, live feed seeder, reputation refresh, and VRM compatibility checker

nirholas84cb07b03598
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d24c8f71..7721b5419 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,10 +14,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Recording Pipeline — the data loop, live** (`/pipeline`) — One-glance health of the closed loop that turns every pump.fun launch into a trade signal: the launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time.
- **Scene Capture — Video to 3D Point Cloud** (`/capture`) — Turn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.
- **three.ws Joins the Alibaba Cloud Partner Network** (`/blog/three-ws-alibaba-cloud-partnership`) — three.ws is now an Alibaba Cloud Partner, bringing Qwen foundation models and Asia-Pacific cloud infrastructure to the three.ws 3D AI agent platform.
+- **$THREE Signal Feed — the platform pays its own oracle to keep a live $THREE price on hand** — three.ws now keeps a continuously fresh read on $THREE. Every 15 minutes an autonomous agent makes a real on-chain x402 payment to the platform's own $THREE Town Oracle and records the result — price, 24h change, market cap, liquidity, 24h volume, and a bullish/bearish/neutral signal — into a time-series history. That history powers a new public, no-cost feed at /api/three-signal that returns the latest snapshot plus a short sparkline, so any $THREE price widget can render a live, recently-paid-for price without charging the viewer per glance. The same latest price also lets the platform quote endpoint fees in $THREE terms. Failed or incomplete fetches are never stored, the feed flags when its newest point is stale, and every paid call is logged with its real Solana transaction signature. `[feature, infra]`
- **60 live x402 payments per minute** — A new per-minute cron fires 60 parallel real Solana USDC micropayments each tick via the x402 protocol, seeding the platform's payment activity feed and club stage with continuous on-chain traffic. Each payment is a signed SPL TransferChecked transaction broadcast via the Solana facilitator — not simulated. Configure the batch size or pause it with X402_SEED_BATCH_SIZE / X402_SEED_ENABLED. (`/pay`) `[infra, feature]`
- **Activate your agent — a one-tap welcome grant that brings it live** — New agents now have a "Go Live" step in their wallet. One tap claims a real, one-time on-chain welcome grant from three.ws — it funds the agent's wallet and lands it on the live Money Pulse as an active wallet, in a single explorer-verifiable transaction. No more agents stuck at a zero balance with no way to make their first move. The Go Live screen shows the grant, the confirmed transaction, and what to do next, all in the platform's monochrome look. (`/pulse`) `[feature]`
- **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]`
+- **Agent Wallet Balance Monitor — the autonomous payment engine watches its own fuel gauge** — The wallet that funds every autonomous x402 payment now monitors itself. Every 10 minutes the platform reads the agent wallet's live USDC and SOL balance, records a time-series sample, and works out the burn rate since the last reading so operators can see exactly how fast funds are being spent. The moment USDC drops below the $5 top-up line it raises a low-balance alert that folds straight into the internal health dashboard — so the wallet gets refilled before autonomous calls start failing on insufficient funds, instead of after. The check reads a free endpoint, so the monitoring itself costs nothing. `[infra]`
- **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 agent reputation refresh — trust scores that keep themselves current** — The platform now refreshes the on-chain reputation of registered Solana agents on its own. A scheduled pipeline pays the agent-reputation service per agent over x402, recomputes each agent's verified feedback score, dispute rate and validation record from on-chain attestations, and flags any agent whose verified trust score drops below threshold. These scores power the agent reputation leaderboard and the trust badges on agent profiles, so you can vet a counterparty before paying it, trading with it, or composing skills with it — and a score that slips is caught automatically rather than going stale. `[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]`
@@ -26,13 +29,16 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive** — Every hour an autonomous agent runs the cheapest possible end-to-end test of the platform's payment rails. It reads the live payment challenge from a $0.001 endpoint and confirms a valid settlement route is still advertised on all three supported networks — Solana, Base, and BSC — then makes one real $0.001 USDC payment on Solana to prove the full build → verify → settle → receipt path actually completes on-chain, not just that the route exists. The per-network result is stored (x402_circuit_breaker) and folded into the internal health dashboard, so the moment a facilitator route goes dark or settlement breaks, it trips and shows up immediately instead of being discovered by a failed user payment. `[infra]`
- **Design your own Memetic Launcher** — Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu. (`/launcher`) `[feature]`
- **Fixed /play getting stuck on "too many requests"** — Opening /play could dead-end on a "Something went wrong — too many requests" screen, especially from a shared network or after a couple of reloads. The wallet sign-in step was sharing the same strict rate limit as login and trading, so a small burst of page loads exhausted it. Sign-in now has its own generous limit sized for a busy world, and if that check ever can't be reached, /play opens anyway instead of blocking — the game server still verifies token-gated worlds on entry. (`/play`) `[fix]`
+- **GLB Size Optimizer — heavy avatars audited and slimmed down automatically** — Big 3D avatars are the slowest thing to load on three.ws, so the platform now hunts them down on its own. Every six hours an autonomous agent finds the heaviest public avatar over the 5 MB web-delivery budget that hasn't been checked recently and pays a real x402 call to the optimize_model service to inspect it. From the model's actual measured geometry and textures it works out exactly how much smaller the file could be — Draco geometry compression, 4K textures resized to 2K, PNG textures transcoded to KTX2 — and projects the resulting download-time improvement at typical mobile bandwidth. Each result is stored with the original size, the projected optimized size, and the load-time saving, then swept across the whole catalog so the gallery can show a 'save ~N%' hint per model and the platform can track its average load-time improvement. The new public report at /api/x402/glb-optimization-report surfaces the catalog-wide savings and the remaining backlog of heavy models. `[feature, improvement]`
- **Hardened how the platform reads its rate-limit store credentials** — Fixed a configuration failure mode where the rate-limiter and cache store's address and access token could be drawn from two different sources and silently mismatch, which made every limiter and cache fall back to a weaker local mode and caused intermittent 'too many requests' errors and failed paid calls. The credentials are now always read together as one pair (and trimmed of stray whitespace), so a mismatch can't happen — keeping rate limits, paid endpoints, and caching reliable. (`/status`) `[fix, infra]`
- **Hardened Redis credentials against dashboard paste errors** — A trailing newline or stray space on the Upstash Redis token — the kind that creeps in when pasting into a dashboard — was being sent verbatim in the auth header and rejected as WRONGPASS, while the URL still resolved. The result was thousands of failures an hour: paid endpoints denying, the payments feed not loading, usage telemetry and caches going dark. Redis credentials are now trimmed at the source (matching how wallet addresses, RPC URLs, and certificates are already sanitized), so a single stray character can never silently take the limiter, feed, and caches offline. `[fix, infra]`
+- **IBM Granite Inference Health Check — the watsonx AI backend pays to test itself** — three.ws hosts an IBM Granite AI service over the x402 protocol — five paid tools (chat, code, embeddings, document analysis, and time-series forecasting) running on IBM watsonx.ai, payable per call in USDC with no IBM Cloud account. Now the platform continuously proves that backend is actually working. Every six hours an autonomous agent makes one real on-chain x402 payment that exercises all five Granite tools at once with tiny canary inputs, checks that each one answered in its expected shape, and tracks how many tokens flowed through. The verdict — which tools are healthy, whether watsonx is responding, and the token throughput — is recorded over time and exposed at a new public, no-cost feed at /api/x402/granite-health, so a model outage or a broken tool is caught within hours instead of when a paying agent hits it. Every probe settles on Solana with a real transaction signature and is logged like every other autonomous payment; a single batched call keeps the cost to roughly a few cents a day. `[feature, infra]`
- **Improved resilience during database outages** — API endpoints now return HTTP 503 (Service Unavailable) with a Retry-After header instead of 500 when the database is temporarily unreachable, so clients and caches know to back off and retry rather than treating it as a permanent error. Background crons skip their tick gracefully and log a warning instead of firing repeated alert storms. A single deduped ops alert now covers the whole outage. `[fix, infra]`
- **Live agent screens restored and refreshed in monochrome** — Watching agents work — their live screens, avatar cam, and activity feed — is back. A missing rate-limit binding had been crashing the endpoints behind the scenes, so the roster on /agents-live never populated, agents couldn't broadcast frames, and tasks wouldn't queue; all three paths now respond correctly. The Live Agents grid and the single-agent screen viewer were also rebuilt in a crisp monochrome palette, and the watch grid now pauses its streams when the tab is in the background so it stays light on bandwidth. (`/agents-live`) `[fix, improvement]`
- **Live Agents is now everywhere it should be — and steadier under the hood** — Watching agents work is far easier to find and more reliable. Live Agents now has its own spot in the Discover menu, every agent profile has a Watch live button, the embedded watch panel links straight to the full-screen viewer, and the viewer has a one-tap path back to the whole live grid. Under the hood: the live roster no longer accumulates stale agents, queuing a task no longer blanks the screen image, a viewer landing on an offline agent now sees a clear offline state instead of hanging on 'connecting', and screen frames are restricted to safe image formats. The browser agent's idle behaviour is also neutral now — when it has no task it simply stands by on its three.ws home rather than wandering, and it never surfaces third-party tokens. (`/agents-live`) `[feature, improvement, fix, security]`
- **Live Agents mission control + one-click session launcher** — New /agents-live page shows a real-time grid of every AI agent with an active screen stream — watch their screens and avatar feeds live, all in one view. Agent owners now get a "Start Live Session" panel on any watch view: click Generate credentials, copy the Docker or Node launch command, run it anywhere, and the agent browser session starts streaming to the screen canvas instantly. Sessions are signed 7-day bearer tokens, no extra setup required. (`/agents-live`) `[feature]`
- **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]`
+- **Live Payment Feed Seeder — the homepage activity feed always shows real, recent payments** — The live payment feed on the homepage proves three.ws is a working agent-to-agent payment network at a glance — but it only ever showed activity when someone happened to run a demo payment. Now the platform keeps it alive itself. Every few minutes an autonomous agent makes one real on-chain $0.001 USDC payment through the platform's own demo flow, rotating across a variety of services — avatar searches, model inspections, validations, optimizations, and capability discovery — so the feed reflects genuine, varied agent activity rather than one call repeated. Each payment is a real settlement on Solana with a real transaction signature, pushed straight onto the feed and also mirrored into a durable history so the record survives beyond the live ring. A first-time visitor now always lands on a feed that's transacting, not an empty box. `[feature, infra]`
- **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]`
@@ -41,6 +47,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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]`
- **On-chain Deployments — live cross-chain agent registry feed, now with animated entries and richer rows** — The /deployments feed now animates newly-registered agents in as they appear rather than flashing the whole list. Each row shows the agent's description so you immediately know what it does. The live-dot kicker now shows today's registration count at a glance. Older registrations load automatically as you scroll (IntersectionObserver), so there's no hunting for the 'Load older' button. Absolute timestamps appear on hover for every registration. (`/deployments`) `[improvement]`
- **Partner ecosystem page** — New /partners page showing all active technology partnerships — AWS, IBM, Google Cloud, Alibaba Cloud, Intel, NVIDIA, Microsoft, and Oracle — with what each powers on the platform, tier badges, and links to partner-specific pages and MCP servers. (`/partners`) `[feature]`
+- **Payment Proof Idempotency Audit — the platform pays to prove it can't be charged twice** — A core safety promise of an agent-to-agent payment network is that the same payment proof can never settle twice. three.ws now verifies that promise on itself, daily, with real money. Once a day an autonomous agent makes one real $0.001 USDC payment to a live priced endpoint, then deliberately resubmits the exact same signed payment proof a second time — and confirms the platform's idempotency store replays the original result (or rejects the duplicate) instead of charging again. The audit passes only when no second on-chain settlement occurs; a genuine double-settlement trips the platform health status and pages on-call immediately. Every audit is recorded with both submissions' outcomes and the verdict, so anyone watching platform health can see the anti-replay guard being proven, not just assumed. `[security, infra]`
+- **Payment Revenue Reconciliation — every settlement on the books is verified on-chain daily** — The platform now audits its own money trail. Once a day an autonomous agent cross-checks every payment our records claim was settled — both the platform's own outbound x402 spend and inbound agent revenue — against the actual transaction on the Solana chain. Each settlement signature is looked up on-chain and graded: confirmed, reverted, never landed, or recorded without a signature at all. Any record where the books say settled but the chain disagrees is flagged as a financial-integrity discrepancy for ops to review before it can corrupt revenue accounting. The check is read-only and runs even when the spend wallet is offline, so the books are watched continuously. `[feature, infra]`
+- **Popular avatar searches — the gallery now suggests what to look for** — The public avatar gallery now surfaces popular search suggestions — the queries that actually return the most characters (human, robot, anime, warrior, dragon and more), each with a sample thumbnail. The list is kept honest by a new autonomous pipeline: every few hours the platform's x402 seed wallet pays per call to run ~20 common searches through the avatar search service, proving the whole pipeline returns ranked results with working thumbnails end-to-end, and caches each query's top hits. The gallery reads that cache to render instant suggestion chips and pre-painted results, so a first-time visitor always has a great place to start instead of an empty search box. `[feature]`
- **Production stability fixes — genome lineage, screen streaming, and x402 seeder** — Several reliability issues addressed: the agent genome breeding lineage page (/genome/lineage) was returning errors for all visitors due to a missing database table — now resolved. The live agent screen-streaming panel now correctly finds agents and loads their names. The x402 dance-tip seeder cron no longer floods the platform with thousands of failed payment attempts when Redis is temporarily unavailable — it detects the outage and skips the tick gracefully. Forge error logs now include the full vendor message from Replicate for faster ops triage. `[fix, infra]`
- **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]`
@@ -49,12 +58,15 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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]`
+- **Solana Agent Registration Health Check — the on-chain identity rails watch themselves** — Registering an agent on Solana is one of three.ws's core promises: the platform mints the agent's on-chain Metaplex identity and enrols it in the Agent Registry, custodially, so the agent's own wallet never has to sign. Now that whole path is watched automatically. Four times a day an autonomous agent pays a real x402 canary call that resolves a known registered agent's on-chain record — both its Identity registry account and its Core identity asset — and confirms they still exist on the live chain through the platform's failover RPC pool. A healthy result resets the counter; a sustained failure escalates to an alert so registration outages are caught before the next agent tries to register and fails. Every probe is recorded with its on-chain check results and RPC latency, giving the status surface a continuous read on whether agent registration is actually working end-to-end. `[feature, infra]`
- **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]`
+- **Token Intel Pre-Snipe Gate — the sniper pays for due diligence before it buys** — Before the agent sniper commits SOL to a fresh launch, the platform now buys it a second opinion. An autonomous pipeline pays the platform's own $0.01 Token Oracle over x402 for the most active new mints the sniper is about to consider, turning the live due-diligence read — liquidity depth, pair age, float-to-liquidity, and 24h buy/sell flow — into a 0–100 rugpull-risk score per mint. Any mint that scores high or critical is auto-rejected at the pre-snipe gate across every entry path (new-mint, first-claim, intel-confirmed, prelaunch radar), so the trading engine never commits funds to a launch its own oracle has flagged as a likely rug. The check is fail-open and cached: a missing or stale verdict never blocks a trade, it only ever adds a safety floor. (`/oracle`) `[feature, infra]`
- **Top Performers podium on marketplace — oracle-ranked agent leaderboard** — The marketplace now surfaces the top 3 oracle-performing agents in trophy-style cards above the agent grid. Each card shows oracle win rate, W/L record, and realized PnL. Rank 1 gets gold, rank 2 silver, rank 3 bronze. Cards shimmer while loading and disappear cleanly when no oracle data exists. Links directly to each agent's profile. (`/marketplace`) `[feature, improvement]`
- **Volume Bootstrap Loop — continuous real on-chain payments across every paid endpoint** — The platform now drives its own agent-to-agent payment volume. Every 5 minutes an autonomous agent round-robins through the full catalog of paid x402 endpoints — dance tips, crypto and token intel, fact-checks, symbol lookups, reputation, club covers and more — and settles a real $0.001–$0.01 USDC payment to the next batch, on a capped daily budget. Each call simultaneously proves the endpoint is live and grows genuine on-chain transaction volume, the metric agent marketplaces rank payment facilitators on. A per-endpoint volume ledger (x402_volume_metrics) tracks total settled calls, USDC spent, success rate and last-seen status for every endpoint, and every individual call is recorded for full auditability. Spend is bounded by both the loop's daily cap and a self-imposed per-run cap, and the loop degrades cleanly when the wallet isn't configured. `[feature, infra]`
+- **VRM 1.0 Compatibility Checker — the platform pays to tell you which avatars can upgrade** — VRM is the open standard for 3D avatars, and the spec recently moved from 0.x to 1.0 — a breaking change in how avatars store their forward axis, facial expressions, spring-bone physics, and toon materials. three.ws now works out, on its own, which uploaded avatars are still on the old format and whether they can be upgraded. Every half hour an autonomous agent picks a VRM avatar that hasn't been checked recently and makes one real on-chain x402 payment to the platform's own model-inspection service to read its actual structure. From that it produces a per-avatar migration report: is this a VRM, which version, can it be upgraded to 1.0, and a checklist of exactly what an upgrade has to fix (axis flip, expression remap, spring-bone re-authoring, MToon material migration). Each report is stored against the avatar so the gallery can show a 'VRM 1.0 ready' badge and an upgrade prompt, and so avatar pricing can factor in spec compliance. Every check settles on Solana with a real transaction signature and is logged like every other autonomous payment; the half-hour spacing keeps the cost to well under a dollar a day. `[feature, infra]`
- **Walk-Browse the Marketplace is now monochrome and agent-readable** — The 3D marketplace hall now reads as one cohesive monochrome material — type identity (agent/avatar/skill) is carried by brightness and clear labels instead of off-system brand colours, matching the rest of three.ws. And because the hall needs WebGL, the page now ships a no-script fallback: search crawlers, AI agents, and any visitor without JavaScript get a clean page with real, followable links into the agents, avatars, and skills catalogues instead of a blank loading spinner. (`/marketplace-walk`) `[improvement]`
- **Wallet sign-in fixed and a cleaner, monochrome login** — Restored Ethereum (SIWE) and Solana (SIWS) wallet sign-in and the active-sessions controls, which had been unreachable due to missing API route mappings. Also refined the sign-in and sign-up screens to a crisp monochrome palette — neutral chain icons, calmer focus and hover states — for a faster, more focused first impression. `[fix, improvement]`
- **x402 payments dashboards refined to the monochrome system** — The x402 Checkout dashboard and Merchant Console now use the platform's monochrome design language end to end — the off-system blue accent is gone, replaced by clean white-on-black with crisp focus rings, toggles, and hover states. New checkout storefronts default to a neutral monochrome look while merchants can still pick any brand color. Verified rendering across the payments page, dashboard, and console. (`/dashboard/x402`) `[improvement]`
diff --git a/agents/x402-buildout/self/018-glb-compression-optimizer.md b/agents/x402-buildout/self/018-glb-compression-optimizer.md
index 0c8866a2f..ed1e5a4e8 100644
--- a/agents/x402-buildout/self/018-glb-compression-optimizer.md
+++ b/agents/x402-buildout/self/018-glb-compression-optimizer.md
@@ -51,3 +51,14 @@ Identifies GLBs > 5MB and calls optimize_model to apply Draco compression and te
## Related Use Cases
See other files in `agents/x402-buildout/self/` for related autonomous loop entries. Coordinate on shared DB schemas and avoid duplicate table creation.
+
+## Implementation (shipped)
+
+- **Module:** `api/_lib/x402/glb-size-optimizer.js` — exports `run(ctx)`, `projectOptimization()`, `pickTarget()`, `readCatalogOptimizationSummary()`, `ensureOptimizationSchema()`.
+- **Registry entry:** `glb-size-optimizer` in `api/_lib/x402/autonomous-registry.js` — `POST /api/mcp`, `pipeline: 'self'`, `cooldown_s: 21_600` (6h), `priority: 37`, `run: runGlbSizeOptimizer`.
+- **Selection:** `pickTarget()` queries `avatars` for the heaviest public, non-deleted GLB with `size_bytes > 5 MB` not analyzed within 14 days (`LEFT JOIN glb_optimizations`). One model per run — gradual catalog sweep, biggest/stalest first.
+- **Payment:** real x402 USDC via the shared `payX402()` client (`api/_lib/x402/pay.js`) using the seed/agent keypair. `optimize_model` is `$0.05/call`; the amount is read from the live 402 challenge, not hardcoded. Wallet/RPC unconfigured → graceful logged skip, no throw.
+- **Value extracted → stored to `glb_optimizations`:** one row per model with `original_bytes`, `estimated_optimized_bytes`, `estimated_savings_bytes`, `savings_pct`, `load_ms_before`/`load_ms_after`, `load_improvement_pct`, `suggestion_ids`, full `suggestions` + `info` JSON, `run_id`, `tx_signature`, `amount_atomic`. `optimize_model` returns measured stats + advice (not a re-encoded GLB), so `projectOptimization()` computes a grounded projection from the model's real vertex count and per-texture dimensions/bytes using the compression ratios the suggestions cite (Draco ~70% geometry, exact 4K→2K area downscale, KTX2 over PNG/JPEG).
+- **Recording:** a detailed `x402_autonomous_log` row (`pipeline='3d'`, `value_extracted` = savings summary) is written on every call (success or failure); the loop additionally records its standard summary row from the returned outcome.
+- **Downstream consumer:** `GET /api/x402/glb-optimization-report` (`api/x402/glb-optimization-report.js`) reads `glb_optimizations` via `readCatalogOptimizationSummary()` to report catalog-wide average size + load-time improvement, total bytes shed, and remaining heavy-GLB backlog. Per-model "save ~N%" hints feed the avatar gallery.
+- **Tests:** `tests/x402-glb-size-optimizer.test.js` — projection math (heavy/already-compressed/empty/floor) + registry wiring.
diff --git a/api/_lib/migrations/2026-06-27-granite-inference-health.sql b/api/_lib/migrations/2026-06-27-granite-inference-health.sql
new file mode 100644
index 000000000..1662b7825
--- /dev/null
+++ b/api/_lib/migrations/2026-06-27-granite-inference-health.sql
@@ -0,0 +1,39 @@
+-- Migration: IBM Granite inference health check (x402 autonomous loop, USE-007).
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-06-27-granite-inference-health.sql
+-- Idempotent.
+--
+-- The autonomous x402 spend loop (api/cron/x402-autonomous-loop.js) pays ONE
+-- real x402 batch call to /api/ibm-mcp every 6 hours, invoking all five paid IBM
+-- Granite tools (chat, code, embed, analyze, forecast) with tiny canary
+-- arguments. api/_lib/x402/granite-health.js summarises the batch response —
+-- verifying each tool answered with its expected schema and tallying token
+-- throughput — and writes one verdict row here. The paid round-trip itself is
+-- recorded to x402_autonomous_log (joined on run_id).
+--
+-- Downstream consumer: GET /api/x402/granite-health reads the latest snapshot
+-- plus a rolling token-throughput / uptime rollup for the watsonx backend SLA
+-- dashboard feed.
+
+CREATE TABLE IF NOT EXISTS granite_inference_health (
+ id bigserial PRIMARY KEY,
+ checked_at timestamptz NOT NULL DEFAULT now(),
+ run_id uuid, -- FK (logical) into x402_autonomous_log.run_id
+ server text NOT NULL DEFAULT 'ibm-x402-mcp',
+ tools_total int NOT NULL, -- tools exercised this check (5)
+ tools_ok int NOT NULL, -- tools that answered without a JSON-RPC error
+ tools_failed int NOT NULL,
+ schema_ok_count int NOT NULL DEFAULT 0, -- tools whose response matched the expected schema
+ watsonx_responding boolean NOT NULL DEFAULT false,
+ all_healthy boolean NOT NULL DEFAULT false,
+ prompt_tokens int NOT NULL DEFAULT 0,
+ completion_tokens int NOT NULL DEFAULT 0,
+ total_tokens int NOT NULL DEFAULT 0, -- token throughput across the batch
+ embed_dimensions int NOT NULL DEFAULT 0,
+ embed_inputs int NOT NULL DEFAULT 0,
+ forecast_steps int NOT NULL DEFAULT 0,
+ latency_ms int, -- paid round-trip latency for the batch
+ per_tool jsonb -- { tool: { ok, schema_ok, tokens, error? } }
+);
+
+CREATE INDEX IF NOT EXISTS granite_inference_health_checked_at_idx
+ ON granite_inference_health (checked_at DESC);
diff --git a/api/_lib/migrations/20260629130000_sniper_coin_sentiment.sql b/api/_lib/migrations/20260629130000_sniper_coin_sentiment.sql
new file mode 100644
index 000000000..dea335027
--- /dev/null
+++ b/api/_lib/migrations/20260629130000_sniper_coin_sentiment.sql
@@ -0,0 +1,44 @@
+-- Sniper coin sentiment — per-coin live market read from the x402 Crypto Intel
+-- feed, used as a snipe-threshold modifier.
+--
+-- Populated by the "Sniper Intel Enrichment" autonomous x402 loop entry
+-- (api/_lib/x402/autonomous-registry.js → sniper-intel-enrich). On each run the
+-- loop pays $0.01 USDC per call to /api/x402/crypto-intel for the coins the
+-- sniper is actively watching (open positions + freshest high-conviction Oracle
+-- candidates), maps the headline signal (bullish/bearish/neutral) + confidence
+-- into a clamped score-point delta, and upserts one row per coin here. Crypto
+-- Intel 503s (un-charged) for any ticker CoinGecko can't resolve, so a memecoin
+-- with no real market never receives a wrong-coin signal — rows only ever carry
+-- a signal a real market produced.
+--
+-- Downstream consumer: workers/agent-sniper/oracle-gate.js
+-- (coinSentimentAdjustment) folds the fresh per-coin delta into the effective
+-- min_oracle_score before the sniper commits SOL — bearish raises the bar,
+-- bullish lowers it. Fail-open and clamped to ±10 points: a missing or stale row
+-- never moves the bar, so this layer can only nudge a snipe, never dominate it.
+--
+-- The enrichment pipeline also creates this lazily (ensureSchema), so this
+-- migration is belt-and-suspenders for environments that run db:migrate.
+
+create table if not exists sniper_coin_sentiment (
+ mint text not null,
+ network text not null default 'mainnet' check (network in ('mainnet', 'devnet')),
+ symbol text,
+ topic text,
+ signal text,
+ headline text,
+ rationale text,
+ confidence numeric(5, 4),
+ price_usd numeric(20, 10),
+ change_24h numeric,
+ sentiment_adj smallint not null default 0,
+ source text not null default 'crypto-intel',
+ tx_signature text,
+ run_id uuid,
+ checked_at timestamptz not null default now(),
+ primary key (mint, network)
+);
+
+-- The gate reads the freshest row per (mint, network); index the recency scan.
+create index if not exists sniper_coin_sentiment_checked
+ on sniper_coin_sentiment (network, checked_at desc);
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index 1d77bc73a..a88d64d50 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -37,26 +37,34 @@ import { run as bazaarDiscoveryWarmup } from './pipelines/bazaar-warmup.js';
import { run as avatarSearchWarmup } from './pipelines/avatar-search-warmup.js';
import { run as reputationRefresh } from './pipelines/reputation-refresh.js';
import { run as tokenIntelPreSnipeGate } from './pipelines/token-intel-gate.js';
+import { run as sniperIntelEnrich } from './pipelines/sniper-intel-enrich.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 paymentProofIdempotencyAudit } from './pipelines/payment-proof-idempotency-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 { runCircuitBreaker } from './pipelines/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';
+import {
+ runGraniteHealth,
+ GRANITE_HEALTH_ENDPOINT,
+ GRANITE_HEALTH_PRICE_ATOMIC,
+} from './granite-health.js';
+import { vrmCompatEntry } from './pipelines/vrm-compat-checker.js';
import {
runSceneCaptureProcessor,
SCENE_CAPTURE_ENDPOINT,
SCENE_CAPTURE_PRICE_ATOMIC,
} from './scene-capture-processor.js';
+import { run as runRigComplexityScorer } from './pipelines/rig-complexity.js';
import {
runThumbnailRegen,
THUMBNAIL_REGEN_ENDPOINT,
@@ -187,6 +195,12 @@ async function nextCanonicalTarget(ctx) {
}
const SELF_ENDPOINTS = [
+ // ── 3D Pipeline: VRM 1.0 Compatibility Checker (USE-019) ──────────────────
+ // Pays a real $0.01 x402 call to /api/mcp (inspect_model) per avatar, derives a
+ // VRM 0.x → 1.0 migration report, and upserts it into avatar_vrm_compat. Full
+ // implementation in ./pipelines/vrm-compat-checker.js.
+ vrmCompatEntry,
+
// ── 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
@@ -232,6 +246,28 @@ const SELF_ENDPOINTS = [
extractSignal: null,
},
+ // ── Payment Proof Idempotency Audit (anti-fraud) ──────────────────────────
+ // Daily anti-replay canary. Pays ONE real $0.001 USDC call to the idempotent
+ // /api/x402/model-check, then resubmits the IDENTICAL signed X-PAYMENT proof
+ // and confirms the idempotency store returns a replay/conflict (never a second
+ // on-chain settlement). run() owns the two-call sequence + payment; the verdict
+ // lands in x402_idempotency_audit and a confirmed double-settle raises an ops
+ // alert. Daily cadence → one paid audit/day ≈ $0.001/day. Downstream consumer:
+ // api/ops/health.js folds a double-settlement into the platform health verdict.
+ {
+ id: 'payment-proof-idempotency-audit',
+ name: 'Payment Proof Idempotency Audit',
+ // path is informational — the pipeline probes + pays + replays itself.
+ path: '/api/x402/model-check',
+ method: 'GET',
+ cooldown_s: 86400, // daily — critical anti-fraud check
+ priority: 86,
+ pipeline: 'security',
+ enabled: true,
+ run: paymentProofIdempotencyAudit,
+ 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.
@@ -680,6 +716,30 @@ const SELF_ENDPOINTS = [
enabled: true,
run: (ctx) => tokenIntelPreSnipeGate(ctx),
},
+ // Sniper Intel Enrichment (USE-024) — the trading engine pays the platform's
+ // own $0.01 USDC Crypto Intel feed (/api/x402/crypto-intel) for live market
+ // sentiment on the coins the sniper is actively watching (open positions +
+ // freshest high-conviction Oracle candidates), turning the headline signal
+ // into a clamped per-coin gate modifier. run() owns the batch sequence +
+ // per-coin recording; the loop records one summary row. Verdicts upsert to
+ // sniper_coin_sentiment keyed by (mint, network). Crypto Intel 503s (un-charged)
+ // for any coin CoinGecko can't resolve, so a memecoin never gets a wrong-coin
+ // signal. Cooldown 900s (15 min) → ~4 batches/hour, ≤$0.08/batch at the default
+ // batch of 8 — bounded again by the loop's daily cap.
+ // Downstream consumer: workers/agent-sniper/oracle-gate.js folds the fresh
+ // per-coin delta into the effective min_oracle_score before committing SOL.
+ {
+ id: 'sniper-intel-enrich',
+ name: 'Sniper Intel Enrichment',
+ path: '/api/x402/crypto-intel',
+ method: 'POST',
+ body: null,
+ cooldown_s: 900,
+ priority: 77,
+ pipeline: 'sniper',
+ enabled: true,
+ run: (ctx) => sniperIntelEnrich(ctx),
+ },
// ── Identity / DID ─────────────────────────────────────────────────────────
{
@@ -1056,6 +1116,97 @@ const SELF_ENDPOINTS = [
enabled: true,
run: (ctx) => revenueReconciliation(ctx),
},
+ // ── Fee Calculation Validator (USE-028, Finance) ──────────────────────────
+ // Fee-integrity probe over the platform's atomic↔decimal conversion — the
+ // arithmetic that turns every USDC price into an x402 challenge amount and back
+ // into a displayed dollar figure. run() exercises the REAL production
+ // converters (usdcToAtomics / atomicsToUsdc) at the boundary atomics where
+ // rounding bugs hide (1, 999, 1000, 1001, 999999), asserting exact render +
+ // round-trip at each, then makes ONE real on-chain payment to the $0.001
+ // dance-tip (1000 atomics — a boundary) to prove the deployed quote and the
+ // settled amount agree with the local fee math end-to-end. Per-boundary
+ // findings land in fee_calculation_audit; a summary (value_extracted = mismatch
+ // counts) goes to x402_autonomous_log. Cooldown 21600 s (6h → ≤4 paid probes/day
+ // ≈ $0.004/day) — fee math only changes on deploy, the live settle catches
+ // deploy/env skew. Downstream consumer: ops gates releases on a mismatch=true
+ // row (alongside cosmetic_pricing_audit) so an off-by-one in fee conversion
+ // never ships and mis-bills buyers.
+ {
+ id: 'fee-calculation-validator',
+ name: 'Fee Calculation Validator',
+ path: '/api/x402/dance-tip',
+ endpoint: '/api/x402/dance-tip',
+ method: 'POST',
+ body: null,
+ price_atomic: 1000, // the live boundary settles $0.001; math sweep is free
+ cooldown_s: 21600,
+ cooldown_seconds: 21600,
+ priority: 30,
+ pipeline: 'finance',
+ enabled: true,
+ run: (ctx) => feeCalculationValidator(ctx),
+ },
+ // ── IBM Granite Inference Health Check (USE-007) ──────────────────────────
+ // Pays ONE real x402 batch call to /api/ibm-mcp that invokes all five paid
+ // IBM Granite tools (chat, code, embed, analyze, forecast) with tiny canary
+ // arguments. The IBM MCP server prices the whole request, so one on-chain
+ // payment (~0.14 USDC) exercises the full watsonx.ai inference surface. run()
+ // summarises the batch — verifying each tool answered with its expected schema
+ // and tallying token throughput — and stores the verdict to
+ // granite_inference_health (downstream consumer: GET /api/x402/granite-health,
+ // the watsonx backend SLA + token-throughput dashboard feed). The paid
+ // round-trip is recorded to x402_autonomous_log like every loop call.
+ // Cooldown 21600 s (every 6 h → 4 paid sweeps/day ≈ $0.56/day) keeps an
+ // expensive inference probe well inside the autonomous daily cap while still
+ // catching a watsonx outage or a tool-schema regression within hours.
+ {
+ id: 'granite-inference-health',
+ name: 'IBM Granite Inference Health Check',
+ path: GRANITE_HEALTH_ENDPOINT,
+ endpoint: GRANITE_HEALTH_ENDPOINT,
+ method: 'POST',
+ price_atomic: GRANITE_HEALTH_PRICE_ATOMIC,
+ cooldown_s: 21600,
+ cooldown_seconds: 21600,
+ priority: 42,
+ pipeline: 'health',
+ enabled: true,
+ run: (ctx) => runGraniteHealth(ctx),
+ extractSignal: null,
+ },
+
+ // ── Rig Complexity Scorer (USE-017) ───────────────────────────────────────
+ // Pays to call inspect_model on POST /api/mcp for a small batch of avatars
+ // that have never been scored or whose GLB changed since the last score. From
+ // each inspection it derives a 0-100 complexity score (bone count, vertices,
+ // triangles, texture bytes, file size) and a tier (light/standard/heavy/
+ // extreme), and upserts the result into avatar_complexity (keyed by avatar_id).
+ // run() owns the per-avatar probe/pay/store and records one x402_autonomous_log
+ // row per call with the parsed score in value_extracted (so it sets
+ // outcome.recorded — the loop adds no duplicate summary row). Downstream
+ // consumer: the Avatar Pricing Engine (USE-020) tiers marketplace listing
+ // prices on avatar_complexity.tier, and the marketplace gallery raises a
+ // "performance-heavy" badge when perf_warning is set. The MCP server prices
+ // inspect_model at $0.01/call (no $0.001 tool exists), so each scored avatar
+ // costs ~$0.01; cooldown 3600 s (hourly) with a 4-avatar batch drains any
+ // backlog at ≤ $0.04/run and idles to ~zero spend once every avatar is scored.
+ {
+ id: 'rig-complexity-scorer',
+ name: 'Rig Complexity Scorer',
+ // path/endpoint are informational — run() builds the JSON-RPC body itself.
+ path: '/api/mcp',
+ endpoint: '/api/mcp',
+ method: 'POST',
+ body: null,
+ price_atomic: 10_000, // $0.01 USDC — inspect_model's advertised per-call price
+ cooldown_s: 3600,
+ cooldown_seconds: 3600,
+ priority: 48,
+ pipeline: '3d',
+ enabled: true,
+ run: (ctx) => runRigComplexityScorer(ctx),
+ extractSignal: null,
+ },
];
// ── External registry ─────────────────────────────────────────────────────────
diff --git a/api/_lib/x402/pipelines/animation-retarget-qa.js b/api/_lib/x402/pipelines/animation-retarget-qa.js
index 53ddc5c47..b1a4956bc 100644
--- a/api/_lib/x402/pipelines/animation-retarget-qa.js
+++ b/api/_lib/x402/pipelines/animation-retarget-qa.js
@@ -48,7 +48,7 @@ import { env } from '../../env.js';
import { logger } from '../../usage.js';
import { inspectGlb } from '../../glb-inspect.js';
import {
- payX402, bootstrapSolanaContext, fetchWithTimeout, USDC_MINT, FETCH_TIMEOUT_MS,
+ payX402, bootstrapSolanaContext, USDC_MINT, FETCH_TIMEOUT_MS,
} from '../pay.js';
const log = logger('x402-animation-qa');
@@ -364,10 +364,11 @@ export async function run(ctx = {}) {
const summary = { clips: clips.length, checked: verdicts.length, paid, passed, failed, verdicts };
return {
- // success reflects that the probe ran and every checked clip passed QA; a
- // retarget regression (failed > 0) lands as success:false so the loop's
- // summary row flags it, with per-clip detail in animation_qa_results.
- success: verdicts.length > 0 && failed === 0,
+ // success means the sweep ran and settled — kept independent of QA pass/fail
+ // so the loop always accounts the USDC actually spent against the daily cap.
+ // A retarget regression surfaces via errorMsg + the per-clip success=false
+ // log rows + animation_qa_results.passed=false, not by zeroing this flag.
+ success: verdicts.length > 0,
amountAtomic: spentAtomic,
txSig: lastTxSig,
errorMsg: failed > 0 ? `animation_qa_failed:${failed}/${verdicts.length}` : null,
diff --git a/api/_lib/x402/pipelines/avatar-search-warmup.js b/api/_lib/x402/pipelines/avatar-search-warmup.js
index 6084e9ef8..c4df80610 100644
--- a/api/_lib/x402/pipelines/avatar-search-warmup.js
+++ b/api/_lib/x402/pipelines/avatar-search-warmup.js
@@ -233,6 +233,7 @@ export async function run(ctx = {}) {
// 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 {
+ runId,
success: warmed > 0,
amountAtomic: spentAtomic,
txSig: lastTxSig,
diff --git a/api/_lib/x402/pipelines/circuit-breaker.js b/api/_lib/x402/pipelines/circuit-breaker.js
index fe9faabea..5da245766 100644
--- a/api/_lib/x402/pipelines/circuit-breaker.js
+++ b/api/_lib/x402/pipelines/circuit-breaker.js
@@ -36,7 +36,7 @@
// module owns the probe, the cross-network verification, the payment, and the
// value extraction/storage.
-import { fetchWithTimeout, parseSolanaAccept, payX402, USDC_MINT } from './pay.js';
+import { fetchWithTimeout, payX402 } from '../pay.js';
// Stable network identifiers — source of truth is api/_lib/x402-spec.js
// (NETWORK_SOLANA_MAINNET / NETWORK_BASE_MAINNET / NETWORK_BSC_MAINNET). Matched
diff --git a/api/_lib/x402/pipelines/cosmetic-pricing-audit.js b/api/_lib/x402/pipelines/cosmetic-pricing-audit.js
index 9c9ebcac7..e31d49906 100644
--- a/api/_lib/x402/pipelines/cosmetic-pricing-audit.js
+++ b/api/_lib/x402/pipelines/cosmetic-pricing-audit.js
@@ -38,26 +38,27 @@
// catalog says" check.
import { randomUUID } from 'node:crypto';
-import { PublicKey } from '@solana/web3.js';
-import { getMint } from '@solana/spl-token';
import { sql } from '../../db.js';
import { env } from '../../env.js';
-import { solanaConnection } from '../../solana/connection.js';
import { logger } from '../../usage.js';
import { buildCatalog } from '../../cosmetics.js';
import { normalizeAccountId } from '../../cosmetics-ownership.js';
import {
loadSeedKeypair,
payX402,
+ bootstrapSolanaContext,
fetchWithTimeout,
parseSolanaAccept,
+ USDC_MINT,
} from '../pay.js';
const log = logger('x402-cosmetic-pricing-audit');
const ROUTE = '/api/x402/cosmetic-purchase';
-const USDC_MINT = () => env.X402_ASSET_MINT_SOLANA || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+// USDC_MINT from pay.js is env-derived and may be unset; fall back to the
+// canonical mainnet USDC mint for the log row's asset column.
+const ASSET = () => USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
// Stable, synthetic account the audit grants the one real purchase to. Guest id
// form, never a real buyer — ownership here is an artifact of the probe, not a sale.
const AUDIT_ACCOUNT = normalizeAccountId('g_pricing_audit') || 'g_pricing_audit';
@@ -134,7 +135,7 @@ async function recordSummary(runId, { amountAtomic, txSig, responseData, duratio
response_data, value_extracted, duration_ms, success, error_msg, pipeline)
VALUES
(${runId}, ${'self'}, ${'Avatar Marketplace Dynamic Pricing'}, ${ROUTE},
- ${'solana:mainnet'}, ${amountAtomic || 0}, ${USDC_MINT()}, ${txSig || null},
+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET()}, ${txSig || null},
${responseData ? JSON.stringify(responseData) : null},
${valueExtracted ? JSON.stringify(valueExtracted) : null},
${durationMs || 0}, ${success}, ${errorMsg || null}, ${'commerce'})
@@ -232,33 +233,25 @@ export async function run(ctx = {}) {
let spentAtomic = 0;
let purchase = null; // payX402 result for the target item
if (buyer && remainingCap >= target.expectedAtomic) {
- // Build / reuse the Solana payment context.
- let conn = ctx.conn;
- let blockhash = ctx.blockhash;
- let mintInfo = ctx.mintInfo;
try {
+ // Reuse the loop's shared Solana context when handed one; otherwise
+ // bootstrap our own (standalone / manual test).
+ let { conn, blockhash, mintInfo } = ctx;
if (!conn || !blockhash || !mintInfo) {
- conn = conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
- const [bh, mi] = await Promise.all([
- blockhash ? Promise.resolve({ blockhash }) : conn.getLatestBlockhash('confirmed'),
- mintInfo ? Promise.resolve(mintInfo) : getMint(conn, new PublicKey(USDC_MINT())),
- ]);
- blockhash = blockhash || bh.blockhash;
- mintInfo = mintInfo || mi;
+ ({ conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));
}
const url = `${origin}${ROUTE}?id=${encodeURIComponent(target.id)}&account=${encodeURIComponent(AUDIT_ACCOUNT)}`;
purchase = await payX402({
- endpointUrl: url,
+ url,
method: 'GET',
conn, buyer, blockhash, mintInfo,
- usdcMint: USDC_MINT(),
- maxAmountAtomic: remainingCap,
+ remainingCap,
});
- if (purchase.status === 'paid') spentAtomic += purchase.amountAtomic;
+ if (purchase.paid) spentAtomic += purchase.amountAtomic;
} catch (err) {
// Infra fault (RPC/preflight). Record it against the target; keep the
// sweep findings — they're already valuable.
- purchase = { status: 'error', success: false, amountAtomic: 0, txSig: null, responseBody: null, errorMsg: err?.message || 'purchase_failed' };
+ purchase = { paid: false, success: false, amountAtomic: 0, txSig: null, responseBody: null, errorMsg: err?.message || 'purchase_failed' };
}
} else if (!buyer) {
log.info('cosmetic_pricing_audit_no_wallet', { reason: walletReason });
@@ -268,7 +261,7 @@ export async function run(ctx = {}) {
if (purchase) {
const f = findings.find((x) => x.id === target.id);
if (f) {
- f.settledAtomic = purchase.status === 'paid' ? purchase.amountAtomic : null;
+ f.settledAtomic = purchase.paid ? purchase.amountAtomic : null;
f.txSig = purchase.txSig || null;
if (purchase.errorMsg) f.error = f.error || purchase.errorMsg;
// A settled amount that disagrees with the quote is itself drift.
@@ -299,8 +292,9 @@ export async function run(ctx = {}) {
const driftCount = findings.filter((f) => f.drift).length;
const underpricedCount = findings.filter((f) => f.underpriced).length;
- const quoteConsistent = purchase?.status === 'paid'
- ? (findings.find((x) => x.id === target.id)?.settledAtomic === findings.find((x) => x.id === target.id)?.quotedAtomic)
+ const targetFinding = findings.find((x) => x.id === target.id);
+ const quoteConsistent = purchase?.paid
+ ? (targetFinding?.settledAtomic === targetFinding?.quotedAtomic)
: null;
// ── 4) Summary row in x402_autonomous_log (always, success or skip) ───────
@@ -308,8 +302,8 @@ export async function run(ctx = {}) {
items: findings.length,
drift_count: driftCount,
underpriced_count: underpricedCount,
- purchased_id: purchase?.status === 'paid' ? target.id : null,
- settled_atomic: purchase?.status === 'paid' ? purchase.amountAtomic : null,
+ purchased_id: purchase?.paid ? target.id : null,
+ settled_atomic: purchase?.paid ? purchase.amountAtomic : null,
quote_consistent: quoteConsistent,
// Surface the offending items so an alert has them without a re-query.
underpriced_ids: findings.filter((f) => f.underpriced).map((f) => f.id),
@@ -328,7 +322,11 @@ export async function run(ctx = {}) {
await recordSummary(runId, {
amountAtomic: 0,
txSig: purchase?.txSig || null,
- responseData: { target: target.id, purchase_status: purchase?.status || 'not_attempted', spent_atomic: spentAtomic },
+ responseData: {
+ target: target.id,
+ purchase_status: !purchase ? 'not_attempted' : (purchase.paid ? 'paid' : (purchase.free ? 'free' : 'failed')),
+ spent_atomic: spentAtomic,
+ },
durationMs: Date.now() - t0,
success: summarySuccess,
errorMsg: summaryError,
diff --git a/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js b/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js
index a4391837b..f295a63fa 100644
--- a/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js
+++ b/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js
@@ -172,6 +172,10 @@ export async function runIdempotencyAudit(ctx = {}) {
const sql = ctx.sql || defaultSql;
const remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;
const endpointUrl = `${origin}${AUDIT_ROUTE}?url=${encodeURIComponent(CANARY_GLB)}`;
+ // Replay cadence is tunable (ctx overrides) so the loop keeps its propagation-
+ // tolerant defaults while tests can drive the sequence without real wait time.
+ const replayAttempts = Number.isFinite(ctx.replayAttempts) ? ctx.replayAttempts : REPLAY_ATTEMPTS;
+ const replayBackoffMs = Number.isFinite(ctx.replayBackoffMs) ? ctx.replayBackoffMs : REPLAY_BACKOFF_MS;
const t0 = Date.now();
const fail = (errorMsg, extra = {}) => ({
@@ -313,10 +317,10 @@ export async function runIdempotencyAudit(ctx = {}) {
let secondMarker = null;
let doubleSettled = false;
let attempts = 0;
- for (let i = 0; i < REPLAY_ATTEMPTS; i++) {
+ for (let i = 0; i < replayAttempts; i++) {
attempts = i + 1;
// Let the first call's cross-replica cache write land before each attempt.
- await sleep(REPLAY_BACKOFF_MS);
+ await sleep(replayBackoffMs);
try {
second = await fetchWithTimeout(endpointUrl, { method: 'GET', headers: paidHeaders });
} catch (err) {
diff --git a/api/_lib/x402/pipelines/rig-complexity.js b/api/_lib/x402/pipelines/rig-complexity.js
index cc4dcc42c..cd2803daf 100644
--- a/api/_lib/x402/pipelines/rig-complexity.js
+++ b/api/_lib/x402/pipelines/rig-complexity.js
@@ -33,7 +33,7 @@ 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';
+import { loadSeedKeypair, payX402 } from '../pay.js';
const log = logger('x402-rig-complexity');
@@ -373,11 +373,14 @@ export async function run(ctx = {}) {
let result;
try {
result = await payX402({
- endpointUrl,
+ url: endpointUrl,
method: 'POST',
body: inspectBody(modelUrl, i + 1),
- conn, buyer, blockhash, mintInfo, usdcMint,
- maxAmountAtomic: remainingCap,
+ conn, buyer, blockhash, mintInfo,
+ remainingCap,
+ // Distinct priority fee per avatar so several same-amount payments on
+ // the one shared blockhash compile to distinct signatures.
+ nonce: i + 1,
});
} catch (err) {
// Network failure / abort — record the attempt, never crash the loop.
@@ -391,7 +394,9 @@ export async function run(ctx = {}) {
continue;
}
- if (result.status === 'paid') {
+ // payX402 returns booleans (paid/free/skipped); derive a label for logging.
+ const statusLabel = result.paid ? 'paid' : result.free ? 'free' : result.skipped ? 'skip' : 'error';
+ if (result.paid) {
spentAtomic += result.amountAtomic;
remainingCap -= result.amountAtomic;
paid += 1;
@@ -424,7 +429,7 @@ export async function run(ctx = {}) {
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 });
+ summaries.push({ avatar: a.slug || a.id, status: statusLabel, error: errorMsg });
}
await recordCall(runId, {
@@ -433,8 +438,8 @@ export async function run(ctx = {}) {
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),
+ responseData: { model_url: modelUrl, status: statusLabel, rpc_error: result.responseBody?.error || null },
+ durationMs: Date.now() - t0,
success: result.success && !!info && !errorMsg,
errorMsg: result.success && info && !errorMsg ? null : errorMsg,
valueExtracted,
diff --git a/api/_lib/x402/pipelines/sniper-intel-enrich.js b/api/_lib/x402/pipelines/sniper-intel-enrich.js
new file mode 100644
index 000000000..5d7b4077d
--- /dev/null
+++ b/api/_lib/x402/pipelines/sniper-intel-enrich.js
@@ -0,0 +1,404 @@
+// api/_lib/x402/pipelines/sniper-intel-enrich.js
+//
+// Sniper Intel Enrichment via Crypto Intel — autonomous pipeline (self/024).
+//
+// The most critical self-loop on the platform: the trading engine pays the
+// platform's own intelligence API to make better decisions. On each run it pays
+// the $0.01 USDC Crypto Intel feed (/api/x402/crypto-intel) for live market
+// sentiment on the coins the sniper is actively watching — the ones it currently
+// holds (open/opening positions) and the freshest high-conviction Oracle
+// candidates it is about to consider — and turns the headline signal into a
+// per-coin gate modifier. On each run it:
+//
+// 1. Selects the coins the sniper is actively watching (selectEnrichTargets):
+// open positions first (a sentiment flip on a held coin is an exit signal),
+// then recent watch-worthy Oracle coins, deduped by mint, capped per run.
+// 2. Pays POST /api/x402/crypto-intel { topic: <symbol> } for each via the
+// shared payX402 client — real on-chain USDC from the seed wallet, never
+// mocked. Crypto Intel resolves the topic against CoinGecko BY ID
+// (simple/price?ids=…), so a coin with no resolvable listing makes the
+// endpoint throw 503 BEFORE settlement: the wallet is never charged for a
+// coin we have no real market read on, and nothing is written. That is the
+// honesty guard — we only ever attach a signal a real market produced.
+// 3. Maps the signal (bullish / bearish / neutral) + confidence into a clamped
+// threshold delta (deriveSentiment) and upserts it into sniper_coin_sentiment
+// keyed by (mint, network). bearish raises the snipe bar, bullish lowers it.
+// 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
+// sniper_coin_sentiment on the pre-snipe path (coinSentimentAdjustment) and
+// folds the per-coin delta into the effective min_oracle_score alongside the
+// macro adjustment. Fail-open and clamped: a missing/stale signal never moves the
+// bar, and the delta is bounded to ±10 points, so this layer can only ever nudge
+// a snipe — never dominate or hard-veto it.
+
+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-sniper-intel-enrich');
+
+// Coins enriched 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 the
+// loop's daily cap. Default 8 keeps a steady spend at the registry cooldown.
+const BATCH_SIZE = Number(process.env.X402_SNIPER_INTEL_BATCH || 8);
+// A signal is "fresh" for this many minutes — within the window we don't re-pay
+// for the same coin. Markets move, so a short window keeps sentiment current.
+const FRESH_MINUTES = Number(process.env.X402_SNIPER_INTEL_FRESH_MIN || 30);
+// Only enrich Oracle candidates scored within this window — older coins are no
+// longer live snipe candidates, so paying to read sentiment on them is waste.
+const CANDIDATE_HOURS = Number(process.env.X402_SNIPER_INTEL_CANDIDATE_HOURS || 12);
+
+const NETWORK = (process.env.SNIPER_NETWORK || 'mainnet').trim();
+const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const ENDPOINT_PATH = '/api/x402/crypto-intel';
+
+// Tiers the sniper would actually evaluate — `avoid` coins never reach the gate,
+// so spending intel on them is wasted. Mirrors the conviction tier ladder.
+const WATCHED_TIERS = ['prime', 'strong', 'lean', 'watch'];
+
+let _schemaReady = false;
+async function ensureSchema() {
+ if (_schemaReady) return;
+ // Sentiment sink (idempotent — mirrors the migration so the pipeline is safe
+ // to run before the migration is applied).
+ await sql`
+ CREATE TABLE IF NOT EXISTS sniper_coin_sentiment (
+ mint text NOT NULL,
+ network text NOT NULL DEFAULT 'mainnet',
+ symbol text,
+ topic text,
+ signal text,
+ headline text,
+ rationale text,
+ confidence numeric(5,4),
+ price_usd numeric(20,10),
+ change_24h numeric,
+ sentiment_adj smallint NOT NULL DEFAULT 0,
+ source text NOT NULL DEFAULT 'crypto-intel',
+ tx_signature text,
+ run_id uuid,
+ checked_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (mint, network)
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS sniper_coin_sentiment_checked ON sniper_coin_sentiment (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 coins the sniper is actively watching that need a fresh sentiment
+ * read. Open/opening positions first (a held coin's sentiment flip is an exit
+ * signal), then recent watch-worthy Oracle candidates. Deduped by mint, capped
+ * at `limit`. Returns [] if neither source table exists yet (degrade, never throw).
+ */
+export async function selectEnrichTargets(limit = BATCH_SIZE) {
+ try {
+ const rows = await sql`
+ (
+ SELECT p.mint, p.symbol, 0 AS src_rank, p.opened_at AS ts
+ FROM agent_sniper_positions p
+ LEFT JOIN sniper_coin_sentiment s
+ ON s.mint = p.mint AND s.network = p.network
+ WHERE p.network = ${NETWORK}
+ AND p.status IN ('opening', 'open')
+ AND p.symbol IS NOT NULL AND p.symbol <> ''
+ AND (s.checked_at IS NULL
+ OR s.checked_at < now() - make_interval(mins => ${FRESH_MINUTES}))
+ )
+ UNION ALL
+ (
+ SELECT c.mint, c.symbol, 1 AS src_rank, c.scored_at AS ts
+ FROM oracle_conviction c
+ LEFT JOIN sniper_coin_sentiment s
+ ON s.mint = c.mint AND s.network = c.network
+ WHERE c.network = ${NETWORK}
+ AND c.symbol IS NOT NULL AND c.symbol <> ''
+ AND c.tier = ANY(${WATCHED_TIERS})
+ AND c.scored_at > now() - make_interval(hours => ${CANDIDATE_HOURS})
+ AND (s.checked_at IS NULL
+ OR s.checked_at < now() - make_interval(mins => ${FRESH_MINUTES}))
+ )
+ ORDER BY src_rank ASC, ts DESC NULLS LAST
+ `;
+ // Dedupe by mint (a held coin may also appear as an Oracle candidate),
+ // keeping the first — positions outrank candidates by the ORDER BY above.
+ const seen = new Set();
+ const out = [];
+ for (const r of rows) {
+ if (seen.has(r.mint)) continue;
+ seen.add(r.mint);
+ out.push({ mint: r.mint, symbol: r.symbol, source: r.src_rank === 0 ? 'position' : 'oracle' });
+ if (out.length >= limit) break;
+ }
+ return out;
+ } catch (err) {
+ if (!err?.message?.includes('does not exist')) {
+ log.warn('sniper_intel_select_failed', { message: err?.message });
+ }
+ return [];
+ }
+}
+
+/**
+ * Map a crypto-intel response into a sentiment verdict + a clamped per-coin gate
+ * delta (in Oracle score points). bearish raises the snipe bar; bullish lowers
+ * it; neutral leaves it untouched. Asymmetric on purpose — conservative on
+ * weakness, modest on strength — and mirrors the macro adjustment in the gate.
+ * Returns null for a malformed/empty response.
+ *
+ * @param {object} body crypto-intel response
+ * @returns {{ signal, confidence, headline, rationale, price_usd, change_24h, sentiment_adj } | null}
+ */
+export function deriveSentiment(body) {
+ if (!body || typeof body !== 'object' || !body.signal) return null;
+ const signal = String(body.signal).toLowerCase();
+ if (!['bullish', 'bearish', 'neutral'].includes(signal)) return null;
+
+ const confRaw = Number(body.confidence);
+ const confidence = Number.isFinite(confRaw) ? Math.max(0, Math.min(1, confRaw)) : 0.5;
+
+ let adj = 0;
+ if (signal === 'bearish') adj = Math.round(8 * confidence); // raise bar
+ else if (signal === 'bullish') adj = -Math.round(4 * confidence); // lower bar
+ adj = Math.max(-10, Math.min(10, adj));
+
+ const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : null);
+ return {
+ signal,
+ confidence,
+ headline: typeof body.headline === 'string' ? body.headline : null,
+ rationale: typeof body.rationale === 'string' ? body.rationale : null,
+ price_usd: num(body.price_usd),
+ change_24h: num(body.change_24h),
+ sentiment_adj: adj,
+ };
+}
+
+async function upsertSentiment(runId, { mint, symbol, topic }, v, txSig) {
+ await sql`
+ INSERT INTO sniper_coin_sentiment
+ (mint, network, symbol, topic, signal, headline, rationale, confidence,
+ price_usd, change_24h, sentiment_adj, source, tx_signature, run_id, checked_at)
+ VALUES
+ (${mint}, ${NETWORK}, ${symbol || null}, ${topic || null}, ${v.signal},
+ ${v.headline}, ${v.rationale}, ${v.confidence}, ${v.price_usd}, ${v.change_24h},
+ ${v.sentiment_adj}, ${'crypto-intel'}, ${txSig || null}, ${runId}, now())
+ ON CONFLICT (mint, network) DO UPDATE SET
+ symbol = EXCLUDED.symbol,
+ topic = EXCLUDED.topic,
+ signal = EXCLUDED.signal,
+ headline = EXCLUDED.headline,
+ rationale = EXCLUDED.rationale,
+ confidence = EXCLUDED.confidence,
+ price_usd = EXCLUDED.price_usd,
+ change_24h = EXCLUDED.change_24h,
+ sentiment_adj = EXCLUDED.sentiment_adj,
+ source = EXCLUDED.source,
+ tx_signature = EXCLUDED.tx_signature,
+ run_id = EXCLUDED.run_id,
+ checked_at = now()
+ `;
+}
+
+// One row per enriched coin into x402_autonomous_log (the loop also records one
+// aggregate summary row for the run() entry; these are the granular per-coin 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'}, ${`Sniper Intel: ${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('sniper_intel_log_insert_failed', { mint, message: err?.message });
+ }
+}
+
+/**
+ * Run the sniper intel enrichment sweep. Conforms to the run()-style registry
+ * contract: the loop hands over { origin, buyer, conn, blockhash, mintInfo,
+ * remainingCap, runId }; standalone (manual test) it bootstraps its own Solana
+ * context via bootstrapSolanaContext().
+ *
+ * Returns the aggregate outcome the loop records as one summary row:
+ * { success, amountAtomic, txSig, errorMsg, responseData, signalData, skipped, note }
+ */
+export async function run(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const endpointUrl = `${origin}${ENDPOINT_PATH}`;
+ let remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;
+
+ // ── Schema first: without the sentiment sink there's nothing to extract, so don't pay.
+ try {
+ await ensureSchema();
+ } catch (err) {
+ log.warn('sniper_intel_schema_failed', { message: err?.message });
+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };
+ }
+
+ // ── Find work before touching the wallet — no watched coins → no spend.
+ const targets = await selectEnrichTargets(BATCH_SIZE);
+ if (targets.length === 0) {
+ return { success: true, skipped: true, amountAtomic: 0, note: 'no_watched_coins' };
+ }
+
+ // ── 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('sniper_intel_skipped', { reason: err.message });
+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: err.message, note: 'wallet_or_rpc_unconfigured' };
+ }
+ }
+
+ let spentAtomic = 0;
+ let paid = 0;
+ let enriched = 0; // sentiment rows stored
+ let bearish = 0; // coins whose read raised the bar
+ let bullish = 0; // coins whose read lowered the bar
+ let noData = 0; // 503 before settlement (no resolvable market)
+ let callErrors = 0;
+ let lastTxSig = null;
+
+ // Crypto Intel is keyed by ticker, so two watched mints sharing a symbol read
+ // the same market. Cache the response per topic within the run to avoid paying
+ // twice for the same ticker while still writing a sentiment row per mint.
+ const topicCache = new Map();
+
+ for (let i = 0; i < targets.length; i++) {
+ const { mint, symbol } = targets[i];
+ if (remainingCap <= 0) {
+ log.info('sniper_intel_cap_reached', { spent_atomic: spentAtomic, remaining_targets: targets.length - i });
+ break;
+ }
+
+ const topic = String(symbol || '').toLowerCase().trim().slice(0, 30);
+ if (!topic) continue;
+
+ const t0 = Date.now();
+
+ // Reuse a same-run response for a repeated ticker (no second payment).
+ let result = topicCache.get(topic);
+ if (!result) {
+ try {
+ result = await payX402({
+ url: endpointUrl,
+ method: 'POST',
+ body: { topic },
+ buyer, conn, blockhash, mintInfo,
+ remainingCap,
+ userAgent: 'threews-x402-sniper-intel/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;
+ }
+ topicCache.set(topic, result);
+
+ if (result.paid) {
+ spentAtomic += result.amountAtomic;
+ remainingCap -= result.amountAtomic;
+ paid += 1;
+ if (result.txSig) lastTxSig = result.txSig;
+ }
+ }
+
+ // Derive + persist the sentiment only when the call delivered a usable body.
+ let verdict = null;
+ let valueExtracted = null;
+ if (result.success) {
+ verdict = deriveSentiment(result.responseBody);
+ if (verdict) {
+ try {
+ await upsertSentiment(runId, { mint, symbol, topic }, verdict, result.txSig);
+ enriched += 1;
+ if (verdict.sentiment_adj > 0) bearish += 1;
+ else if (verdict.sentiment_adj < 0) bullish += 1;
+ valueExtracted = {
+ mint,
+ topic,
+ signal: verdict.signal,
+ confidence: verdict.confidence,
+ sentiment_adj: verdict.sentiment_adj,
+ price_usd: verdict.price_usd,
+ };
+ } catch (err) {
+ // Payment already settled — record the call as success but surface
+ // the persistence error for observability.
+ log.warn('sniper_intel_persist_failed', { mint, message: err?.message });
+ }
+ }
+ } else {
+ // crypto-intel throws 503 (data_unavailable) when CoinGecko has no
+ // resolvable market for the ticker — an expected, un-charged outcome for
+ // the memecoins the sniper mostly watches. Never attach a wrong signal.
+ if (result.status === 503) noData += 1;
+ else callErrors += 1;
+ }
+
+ await recordCall(runId, {
+ mint,
+ endpointUrl: `${endpointUrl} [${topic}]`,
+ amountAtomic: result.paid ? result.amountAtomic : 0,
+ txSig: result.txSig,
+ // Keep the row compact — the verdict lives in value_extracted + sniper_coin_sentiment.
+ responseData: { status: result.status, topic, code: result.responseBody?.code || null, rpc_error: result.responseBody?.error || null },
+ durationMs: Date.now() - t0,
+ success: result.success,
+ errorMsg: result.errorMsg,
+ valueExtracted,
+ });
+ }
+
+ log.info('sniper_intel_complete', {
+ run_id: runId,
+ targets: targets.length,
+ paid,
+ enriched,
+ bearish,
+ bullish,
+ no_data: noData,
+ spent_usdc: (spentAtomic / 1e6).toFixed(4),
+ });
+
+ return {
+ // success when the loop did its job: at least one sentiment stored, or every
+ // candidate honestly had no resolvable market (no charge, nothing to enrich).
+ success: enriched > 0 || (paid === 0 && noData === targets.length && targets.length > 0),
+ amountAtomic: spentAtomic,
+ txSig: lastTxSig,
+ errorMsg: enriched === 0 && callErrors > 0 ? `sniper_intel_calls_failed:${callErrors}` : null,
+ skipped: paid === 0 && enriched === 0 && noData === 0,
+ responseData: { targets: targets.length, paid, enriched, bearish, bullish, no_data: noData },
+ signalData: { enriched, bearish, bullish, no_data: noData },
+ note: `sniper_intel targets=${targets.length} paid=${paid} enriched=${enriched} bear=${bearish} bull=${bullish} nodata=${noData}`,
+ };
+}
diff --git a/api/_lib/x402/pipelines/vrm-compat-checker.js b/api/_lib/x402/pipelines/vrm-compat-checker.js
new file mode 100644
index 000000000..58484c126
--- /dev/null
+++ b/api/_lib/x402/pipelines/vrm-compat-checker.js
@@ -0,0 +1,266 @@
+// api/_lib/x402/pipelines/vrm-compat-checker.js
+//
+// VRM 1.0 Compatibility Checker (USE-019) — an autonomous x402 spend-loop entry.
+//
+// Validates that VRM 0.x avatars can be upgraded to the VRM 1.0 spec. For each
+// selected avatar it pays a real x402 call to /api/mcp (inspect_model), parses
+// the structural report, flags the well-known VRM 0.x → 1.0 breaking changes
+// (forward-axis flip, BlendShapeMaster → VRMC_vrm expressions, secondaryAnimation
+// → VRMC_springBone, MToon → VRMC_materials_mtoon), and upserts a per-avatar
+// migration report into `avatar_vrm_compat` (keyed by avatar_id).
+//
+// Wiring: this module exports a single registry entry object consumed by
+// api/_lib/x402/autonomous-registry.js. The spend loop
+// (api/cron/x402-autonomous-loop.js) drives it via the generic entry hooks:
+// • resolveTarget(ctx) → picks the avatar + builds its public GLB URL
+// • body(ctx) → embeds that URL into an MCP inspect_model tools/call
+// • extractSignal(r) → verdict summary → x402_autonomous_log.signal_data
+// • storeValue(ctx) → full migration report → avatar_vrm_compat
+//
+// Real on-chain payment only (inspect_model is $0.01 USDC over /api/mcp). If the
+// seed wallet is unconfigured the loop exits before this entry runs; if there is
+// no VRM avatar pending and no canary configured, resolveTarget yields no target
+// and the loop skips the tick without paying.
+//
+// Downstream consumers of avatar_vrm_compat:
+// • Avatar detail / marketplace gallery → "VRM 1.0 ready" badge + upgrade CTA.
+// • Avatar Pricing Engine pipeline (USE-020) → spec compliance as a pricing input.
+
+import { publicUrl } from '../../r2.js';
+
+// Optional public VRM canary that keeps the paid path warm when no user VRM
+// avatar is pending a check. Unset → the pipeline skips that tick rather than
+// paying for a non-existent target. Mirrors X402_MCP_PERF_CANARY_MODEL.
+const VRM_CANARY_MODEL = (process.env.X402_VRM_CANARY_MODEL || '').trim();
+
+// Per-call price of inspect_model over /api/mcp, in USDC atomics (6 decimals).
+// Informational — the loop pays whatever the live 402 challenge quotes.
+export const VRM_INSPECT_PRICE_ATOMIC = 10_000; // $0.01
+
+// Derive the VRM-compatibility verdict from an inspect_model structural report
+// (the tool's structuredContent). Shared by extractSignal (→ signal_data) and
+// storeValue (→ avatar_vrm_compat) so both always agree on the classification.
+export function classifyVrmCompat(info, sourceUrl) {
+ const c = (info && info.counts) || {};
+ const ext = [
+ ...(Array.isArray(info?.extensionsUsed) ? info.extensionsUsed : []),
+ ...(Array.isArray(info?.extensionsRequired) ? info.extensionsRequired : []),
+ ].map(String);
+ const has = (n) => ext.includes(n);
+ // VRM 0.x ships the single `VRM` extension; VRM 1.0 splits into the VRMC_*
+ // family (VRMC_vrm, VRMC_springBone, VRMC_materials_mtoon, …).
+ const isVrm1 = ext.some((x) => /^VRMC_/.test(x));
+ const isVrm0 = has('VRM') && !isVrm1;
+ const isVrm = isVrm0 || isVrm1;
+ const vrmVersion = isVrm1 ? '1.0' : isVrm0 ? '0.x' : 'none';
+
+ const matCount = Array.isArray(info?.materials)
+ ? info.materials.length
+ : Number(c.materials || 0);
+ const issues = [];
+ if (isVrm0) {
+ // Migration checklist — the classic VRM 0.x → 1.0 breaking changes. These
+ // are advisory (the UniVRM converter automates them); they tell the upgrade
+ // tool what to verify, not whether the upgrade is possible.
+ issues.push({
+ code: 'coordinate_space',
+ severity: 'warn',
+ message: 'VRM 1.0 reverses the forward axis (0.x +Z → 1.0 −Z). Root transform and normals must be flipped during upgrade.',
+ });
+ issues.push({
+ code: 'expression_remap',
+ severity: 'warn',
+ message: 'VRM 0.x BlendShapeMaster groups must be remapped to VRMC_vrm expressions (presets + custom) in 1.0.',
+ });
+ if (Number(c.skins || 0) > 0) {
+ issues.push({
+ code: 'springbone_remap',
+ severity: 'warn',
+ message: 'VRM 0.x secondaryAnimation spring bones must be re-expressed as VRMC_springBone joints + colliders.',
+ });
+ }
+ if (matCount > 0 && !has('VRMC_materials_mtoon')) {
+ issues.push({
+ code: 'mtoon_migration',
+ severity: 'info',
+ message: `${matCount} material(s) — MToon parameters migrate to VRMC_materials_mtoon; verify outline and shading after upgrade.`,
+ });
+ }
+ }
+
+ // A VRM 0.x avatar can always be mechanically upgraded to 1.0. Already-1.0 and
+ // non-VRM models are not upgrade candidates → null (N/A).
+ const upgradeable = isVrm0 ? true : null;
+ const blockerCount = issues.filter(
+ (i) => i.severity === 'warn' || i.severity === 'critical',
+ ).length;
+
+ return {
+ source_url: sourceUrl || info?.url || null,
+ is_vrm: isVrm,
+ vrm_version: vrmVersion,
+ upgradeable,
+ blocker_count: blockerCount,
+ issues,
+ extensions: ext,
+ counts: {
+ nodes: Number(c.nodes || 0),
+ meshes: Number(c.meshes || 0),
+ materials: Number(c.materials || 0),
+ skins: Number(c.skins || 0),
+ animations: Number(c.animations || 0),
+ vertices: Number(c.totalVertices || 0),
+ triangles: Number(c.totalTriangles || 0),
+ },
+ filename: info?.filename || null,
+ container: info?.container || null,
+ generator: info?.generator || null,
+ };
+}
+
+// Pull the inspect_model structural report out of an MCP tools/call response.
+function structuredContent(responseBody) {
+ return responseBody?.result?.structuredContent || null;
+}
+
+// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).
+// The canonical schema also ships as a migration
+// (api/_lib/migrations/20260629100000_avatar_vrm_compat.sql); this keeps the
+// pipeline self-healing on a cold DB where the migration hasn't been applied.
+let _vrmSchemaReady = false;
+async function ensureVrmSchema(sql) {
+ if (_vrmSchemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS avatar_vrm_compat (
+ avatar_id uuid PRIMARY KEY REFERENCES avatars(id) ON DELETE CASCADE,
+ source_url text NOT NULL,
+ is_vrm boolean NOT NULL DEFAULT false,
+ vrm_version text NOT NULL DEFAULT 'none',
+ upgradeable boolean,
+ blocker_count int NOT NULL DEFAULT 0,
+ issues jsonb NOT NULL DEFAULT '[]'::jsonb,
+ report jsonb NOT NULL DEFAULT '{}'::jsonb,
+ extensions text[] NOT NULL DEFAULT '{}',
+ run_id uuid,
+ tx_signature text,
+ checked_at timestamptz NOT NULL DEFAULT now()
+ )
+ `;
+ _vrmSchemaReady = true;
+}
+
+// Select the next avatar to validate: a VRM-candidate (tagged 'vrm', named like
+// a VRM, a .vrm storage key, or an imported/avaturn source) not checked in the
+// last 30 days, least-recently-checked first. Falls back to the optional public
+// canary so the paid path stays exercised even with no pending user avatar.
+async function nextVrmTarget(ctx) {
+ if (ctx?.sql) {
+ try {
+ await ensureVrmSchema(ctx.sql);
+ const rows = await ctx.sql`
+ SELECT a.id, a.name, a.storage_key
+ FROM avatars a
+ LEFT JOIN avatar_vrm_compat v ON v.avatar_id = a.id
+ WHERE a.deleted_at IS NULL
+ AND a.storage_key IS NOT NULL
+ AND a.storage_key <> ''
+ AND (v.avatar_id IS NULL OR v.checked_at < now() - interval '30 days')
+ AND (
+ 'vrm' = ANY(a.tags)
+ OR a.name ILIKE '%vrm%'
+ OR a.storage_key ILIKE '%.vrm%'
+ OR a.source IN ('avaturn', 'import')
+ )
+ ORDER BY v.checked_at ASC NULLS FIRST, a.created_at DESC
+ LIMIT 1`;
+ if (rows && rows.length) {
+ const a = rows[0];
+ const url = publicUrl(a.storage_key);
+ if (/^https:\/\//i.test(url)) {
+ return { targetUrl: url, context: { avatar_id: a.id, name: a.name, canary: false } };
+ }
+ }
+ } catch {
+ // DB unavailable or table not yet migrated — fall through to the canary.
+ }
+ }
+ if (VRM_CANARY_MODEL) {
+ return { targetUrl: VRM_CANARY_MODEL, context: { avatar_id: null, name: 'vrm-canary', canary: true } };
+ }
+ return null;
+}
+
+// Persist the per-avatar migration report. Skips canary / unidentified targets
+// (no avatars row to key on) — their verdict is still captured in
+// x402_autonomous_log.signal_data via extractSignal.
+async function storeVrmReport({ sql, responseBody, runId, targetUrl, targetContext, txSig }) {
+ if (!sql) return;
+ const avatarId = targetContext?.avatar_id;
+ if (!avatarId) return;
+ const info = structuredContent(responseBody);
+ if (!info) return;
+ const v = classifyVrmCompat(info, targetUrl);
+ await ensureVrmSchema(sql);
+ await sql`
+ INSERT INTO avatar_vrm_compat
+ (avatar_id, source_url, is_vrm, vrm_version, upgradeable,
+ blocker_count, issues, report, extensions, run_id, tx_signature, checked_at)
+ VALUES
+ (${avatarId}, ${v.source_url || targetUrl}, ${v.is_vrm}, ${v.vrm_version},
+ ${v.upgradeable}, ${v.blocker_count},
+ ${JSON.stringify(v.issues)}, ${JSON.stringify(v)},
+ ${v.extensions}, ${runId}, ${txSig || null}, now())
+ ON CONFLICT (avatar_id) DO UPDATE SET
+ source_url = EXCLUDED.source_url,
+ is_vrm = EXCLUDED.is_vrm,
+ vrm_version = EXCLUDED.vrm_version,
+ upgradeable = EXCLUDED.upgradeable,
+ blocker_count = EXCLUDED.blocker_count,
+ issues = EXCLUDED.issues,
+ report = EXCLUDED.report,
+ extensions = EXCLUDED.extensions,
+ run_id = EXCLUDED.run_id,
+ tx_signature = EXCLUDED.tx_signature,
+ checked_at = now()
+ `;
+}
+
+// The registry entry. Imported and spread into SELF_ENDPOINTS by
+// autonomous-registry.js. Cooldown 1800s → ≤48 checks/day ≈ $0.48/day at $0.01
+// each, well under the loop's daily cap (shared across all pipelines).
+export const vrmCompatEntry = {
+ id: 'vrm-compat-checker',
+ name: 'VRM 1.0 Compatibility Checker',
+ path: '/api/mcp',
+ method: 'POST',
+ // Dynamic body: resolveTarget picks the avatar + URL, this embeds it into the
+ // MCP inspect_model tools/call. Returns null when there is no target → the loop
+ // skips the tick without probing or paying.
+ body: ({ targetUrl }) => {
+ if (!targetUrl) return null;
+ return {
+ jsonrpc: '2.0',
+ id: 'vrm-compat',
+ method: 'tools/call',
+ params: { name: 'inspect_model', arguments: { url: targetUrl } },
+ };
+ },
+ cooldown_s: 1800,
+ priority: 42,
+ pipeline: 'vrm-compat',
+ enabled: true,
+ resolveTarget: (ctx) => nextVrmTarget(ctx),
+ extractSignal: (r) => {
+ const info = structuredContent(r);
+ if (!info) return { ok: false, reason: 'no_structured_content' };
+ const v = classifyVrmCompat(info, null);
+ return {
+ is_vrm: v.is_vrm,
+ vrm_version: v.vrm_version,
+ upgradeable: v.upgradeable,
+ blocker_count: v.blocker_count,
+ filename: v.filename,
+ };
+ },
+ storeValue: (ctx) => storeVrmReport(ctx),
+};
diff --git a/api/_lib/x402/solana-payer.js b/api/_lib/x402/solana-payer.js
new file mode 100644
index 000000000..5bbe545f7
--- /dev/null
+++ b/api/_lib/x402/solana-payer.js
@@ -0,0 +1,8 @@
+// api/_lib/x402/solana-payer.js
+//
+// Compatibility alias for the canonical Solana x402 payment helpers in pay.js.
+// Some autonomous-loop pipelines import the payment primitives
+// (loadSeedKeypair, payX402, buildPaymentTx, …) under this module name; pay.js
+// is the single source of truth for the implementation. Re-exporting here keeps
+// both import paths valid without duplicating the signing/settlement logic.
+export * from './pay.js';
diff --git a/api/_mcp/tools/solana.js b/api/_mcp/tools/solana.js
index 65a3b2d35..781bc1d2d 100644
--- a/api/_mcp/tools/solana.js
+++ b/api/_mcp/tools/solana.js
@@ -110,7 +110,7 @@ export const toolDefs = [
title: 'Get Solana agent reputation',
annotations: ATTESTATION_READ_ANNOTATIONS,
description:
- 'Computed reputation summary for a Solana-registered three.ws agent. Returns total/verified feedback counts, score averages (raw + verified-only), validation pass/fail, task acceptance, and dispute counts. Verified score only includes feedback whose task was acknowledged on-chain by the agent owner. Public; no auth required.',
+ 'Computed reputation summary for a Solana-registered three.ws agent. Returns total/verified feedback counts, score averages (raw + verified-only), validation pass/fail, task acceptance, and dispute counts. Verified score only includes feedback whose task was acknowledged on-chain by the agent owner. Priced at $0.001 USDC/call via x402 (pay-per-call; an OAuth bearer token bypasses payment).',
inputSchema: {
type: 'object',
properties: {
diff --git a/api/avatars/popular-searches.js b/api/avatars/popular-searches.js
new file mode 100644
index 000000000..78e7976e3
--- /dev/null
+++ b/api/avatars/popular-searches.js
@@ -0,0 +1,67 @@
+// GET /api/avatars/popular-searches — popular gallery search suggestions.
+//
+// Public, no auth. Powers the "popular searches" suggestion chips on the public
+// avatar gallery. The data is produced by the Avatar Search Index Warmup
+// autonomous x402 pipeline (api/_lib/x402/pipelines/avatar-search-warmup.js),
+// which pays per call to /api/mcp (search_public_avatars) for ~20 common queries
+// and upserts each query's ranked, thumbnail-resolved slice into
+// avatar_search_warm_cache. We rank by how much public inventory each query
+// surfaces so the chips always point at queries that return real results.
+//
+// ?with_thumbnails=true also returns the cached top-result slice per query so the
+// gallery can paint instant results for a chip before the live search returns.
+//
+// Empty/cold-start safe: before the warmup has run (or if the table is absent)
+// this returns a small static seed list so the gallery always has chips to show.
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getPopularSearches } from '../_lib/avatar-search-warm.js';
+
+// Shown until the warmup has populated the cache. Mirrors the warmup's query set
+// so the gallery's first paint matches what the loop will rank shortly after.
+const SEED_QUERIES = ['human', 'robot', 'anime', 'warrior', 'dragon', 'knight', 'cyberpunk', 'animal'];
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 12, 1), 50);
+ const withThumbnails = url.searchParams.get('with_thumbnails') === 'true';
+
+ const warmed = await getPopularSearches({ limit, withThumbnails });
+
+ if (warmed.length > 0) {
+ res.setHeader('cache-control', 'public, max-age=120, s-maxage=600, stale-while-revalidate=1800');
+ return json(res, 200, {
+ source: 'warm_cache',
+ searches: warmed.map((w) => ({
+ query: w.query,
+ result_count: w.result_count,
+ sample_thumbnail: w.sample_thumbnail,
+ thumbnails: w.thumbnails,
+ warmed_at: w.warmed_at,
+ ...(withThumbnails ? { top_results: w.top_results } : {}),
+ })),
+ });
+ }
+
+ // Cold start — the warmup has not populated the cache yet. Serve a static
+ // seed list (no thumbnails available until the pipeline resolves them) so the
+ // gallery still renders suggestion chips, with a short TTL so the warmed data
+ // takes over as soon as it lands.
+ res.setHeader('cache-control', 'public, max-age=30, s-maxage=60');
+ return json(res, 200, {
+ source: 'seed',
+ searches: SEED_QUERIES.slice(0, limit).map((query) => ({
+ query,
+ result_count: null,
+ sample_thumbnail: null,
+ thumbnails: [],
+ })),
+ });
+});
diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.js
index 1c45ba818..64321f43d 100644
--- a/api/cron/x402-autonomous-loop.js
+++ b/api/cron/x402-autonomous-loop.js
@@ -70,13 +70,13 @@ function requireCron(req, res) {
return true;
}
-async function recordLog(runId, entry, { amountAtomic, txSig, responseData, durationMs, success, errorMsg, signalData, endpointUrl }) {
+async function recordLog(runId, entry, { amountAtomic, txSig, responseData, durationMs, success, errorMsg, signalData, valueExtracted, endpointUrl }) {
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)
+ response_data, signal_data, value_extracted, duration_ms, success, error_msg, pipeline)
VALUES
(${runId}, ${entry.url ? 'external' : 'self'},
${entry.name}, ${endpointUrl || entry.url || entry.path},
@@ -85,6 +85,7 @@ async function recordLog(runId, entry, { amountAtomic, txSig, responseData, dura
${txSig || null},
${responseData ? JSON.stringify(responseData) : null},
${signalData ? JSON.stringify(signalData) : null},
+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},
${durationMs || 0}, ${success}, ${errorMsg || null},
${entry.pipeline || 'unknown'})
`;
@@ -138,6 +139,7 @@ async function ensureSchema() {
tx_signature text,
response_data jsonb,
signal_data jsonb,
+ value_extracted jsonb,
duration_ms int,
success boolean NOT NULL,
error_msg text,
@@ -146,6 +148,12 @@ async function ensureSchema() {
`;
} catch { /* already exists or migration system handles it */ }
+ // value_extracted predates some installs (the table may already exist without
+ // it); ensure it before any recordLog INSERT references the column. Idempotent.
+ try {
+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;
+ } catch { /* column already present */ }
+
// oracle_intel_signals: deduped latest signal per source+topic.
// The sniper oracle gate queries this to enrich conviction scores.
try {
@@ -337,6 +345,7 @@ export default wrapCron(async (req, res) => {
await recordLog(runId, entry, {
amountAtomic, txSig, responseData: responseBody,
durationMs: Date.now() - t0, success, errorMsg, signalData,
+ valueExtracted: outcome.valueExtracted ?? null,
});
}
continue;
diff --git a/api/ops/health.js b/api/ops/health.js
index f823d01e5..dab28dd8f 100644
--- a/api/ops/health.js
+++ b/api/ops/health.js
@@ -153,6 +153,11 @@ export default wrap(async (req, res) => {
// means autonomous calls are about to start failing on insufficient funds.
const walletBalance = await loadWalletBalance();
+ // Payment-proof idempotency audit — latest verdict written daily by the
+ // autonomous loop (api/_lib/x402/pipelines/payment-proof-idempotency-audit.js).
+ // A confirmed double-settlement means the x402 anti-replay guard is broken.
+ const idempotencyAudit = await loadIdempotencyAudit();
+
// Categorize probe results
const byCategory = {};
for (const r of probeResults) {
@@ -169,7 +174,10 @@ export default wrap(async (req, res) => {
// 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;
+ // A confirmed double-settlement (ok:false) degrades health; a never-run audit
+ // (ok:null) is unknown, not failing.
+ const idempotencyOk = idempotencyAudit.ok !== false;
+ const overallOk = allProbesOk && allCronsOk && breakerOk && walletOk && idempotencyOk;
const failingProbes = probeResults.filter((r) => !r.ok);
const failingCrons = heartbeats.filter((h) => h.stale || h.ok === false);
@@ -190,9 +198,55 @@ export default wrap(async (req, res) => {
crons: heartbeats,
circuitBreaker,
walletBalance,
+ idempotencyAudit,
});
});
+// Read the latest payment-proof idempotency audit verdict written daily by the
+// autonomous loop (api/_lib/x402/pipelines/payment-proof-idempotency-audit.js).
+// ok:false ONLY on a confirmed double-settlement (the anti-replay guard failed);
+// a stale or never-run audit is unknown (ok:null), not failing, so health doesn't
+// trip on a cold or paused feature.
+const IDEMPOTENCY_STALE_AFTER_MS = 48 * 60 * 60 * 1000; // 48h (daily cadence + slack)
+
+async function loadIdempotencyAudit() {
+ try {
+ const [row] = await sql`
+ SELECT route, verdict, double_settled, pass, first_tx, second_tx,
+ second_marker, payment_id,
+ extract(epoch FROM ts) * 1000 AS checked_at_ms
+ FROM x402_idempotency_audit
+ 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 > IDEMPOTENCY_STALE_AFTER_MS;
+ // Only a confirmed double-settlement fails health. A stale audit is unknown
+ // (loop stopped writing), and an inconclusive run (first call never settled)
+ // is not evidence of a broken guard → ok:null.
+ const ok = row.double_settled ? false : stale ? null : row.verdict === 'inconclusive' ? null : true;
+ return {
+ ok,
+ verdict: row.verdict,
+ doubleSettled: row.double_settled,
+ pass: row.pass,
+ route: row.route,
+ firstTx: row.first_tx,
+ secondTx: row.second_tx,
+ secondMarker: row.second_marker,
+ paymentId: row.payment_id,
+ 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 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
diff --git a/api/x402/granite-health.js b/api/x402/granite-health.js
new file mode 100644
index 000000000..097d7d8b5
--- /dev/null
+++ b/api/x402/granite-health.js
@@ -0,0 +1,47 @@
+// GET /api/x402/granite-health — IBM Granite watsonx backend SLA dashboard feed.
+//
+// Free operational read (parity with /api/x402/mcp-perf): surfaces the live
+// health of the hosted IBM Granite MCP inference backend as measured by the
+// `granite-inference-health` autonomous-loop entry (api/_lib/x402/autonomous-registry.js).
+// That loop pays a real x402 batch call to /api/ibm-mcp every 6 hours, invoking
+// all five paid Granite tools, and writes a verdict row (per-tool schema
+// conformance + token throughput) to granite_inference_health. This endpoint is
+// the downstream consumer: it reports the latest snapshot plus a rolling
+// throughput / uptime rollup.
+//
+// Query: ?window=<hours> (default 24, max 168) — the rolling window to report.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { readGraniteHealth } from '../_lib/x402/granite-health.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ let windowHours = 24;
+ try {
+ const u = new URL(req.url, 'http://localhost');
+ const w = Number(u.searchParams.get('window'));
+ if (Number.isFinite(w) && w > 0) windowHours = Math.min(Math.max(w, 1), 168);
+ } catch { /* default window */ }
+
+ try {
+ const health = await readGraniteHealth({ windowHours });
+ // 200 always — the dashboard renders the degraded state itself; a non-2xx
+ // here would be indistinguishable from this endpoint being down.
+ return json(res, 200, { ...health, generated_at: new Date().toISOString() });
+ } catch (err) {
+ // Table absent (loop never ran) or DB hiccup — report empty-but-healthy so
+ // the dashboard shows "no data yet" instead of an error void.
+ const noData = /does not exist/i.test(err?.message || '');
+ return json(res, noData ? 200 : 503, {
+ ok: noData,
+ server: 'ibm-x402-mcp',
+ healthy: true,
+ latest: null,
+ window: { checks: 0, total_tokens: 0 },
+ generated_at: new Date().toISOString(),
+ ...(noData ? {} : { error: 'granite_health_read_failed' }),
+ });
+ }
+});
diff --git a/api/x402/solana-register-health.js b/api/x402/solana-register-health.js
index 5567cc9fb..12e63809e 100644
--- a/api/x402/solana-register-health.js
+++ b/api/x402/solana-register-health.js
@@ -25,6 +25,25 @@
// row in `mcp_health_canary` (shared by all MCP-Health canaries — see
// agents/x402-buildout/self/) and emits an alert log when the subsystem trips.
//
+// Data stored (requirement 3 + 4):
+// • x402_autonomous_log — written by the autonomous loop on every call:
+// response_data = this endpoint's full JSON snapshot;
+// signal_data = the entry's extractSignal() verdict
+// { alive, registry_enrolled, asset_onchain, identity_pda_onchain, … }.
+// • mcp_health_canary[tool_name='solana_register'] — written HERE, server-side:
+// healthy, last_checked_at, last_ok_at, consecutive_failures, last_error,
+// detail (jsonb: source/network/asset/identity_pda/checks/latency),
+// last_tx_signature.
+//
+// Downstream consumers:
+// • This endpoint's own alert escalation reads consecutive_failures from
+// mcp_health_canary to decide warn-vs-error logging (sustained-outage alert).
+// • mcp_health_canary is the shared MCP-Health read-model (keyed by tool_name)
+// that the platform status surface renders alongside the other canaries
+// (granite_inference_health, mcp_stream_health, x402_perf_log).
+// • The x402 admin activity/analytics views read x402_autonomous_log, so the
+// signal_data verdict is visible there per autonomous tick.
+//
// Canary selection (real data only — never a mock):
// X402_CANARY_AGENT_ID a known three.ws agent_id (uuid) registered on Solana
// X402_CANARY_AGENT_ASSET a known Core asset pubkey (skips the agent_id lookup)
diff --git a/content/threews-evolution-elevenlabs-COMPLETE.md b/content/threews-evolution-elevenlabs-COMPLETE.md
index 712d2d6ba..ee1e7b696 100644
--- a/content/threews-evolution-elevenlabs-COMPLETE.md
+++ b/content/threews-evolution-elevenlabs-COMPLETE.md
@@ -1,81 +1,61 @@
-This is three.ws. A platform where artificial intelligence agents are embodied in three dimensions, hold real wallets, work in public, and pay each other on a blockchain. Built in roughly ten weeks, in the open, with more than five thousand commits and over nine hundred dated, public changelog entries. This is the complete account of what was built, who it was built with, and what comes next. The only coin this platform has ever promoted, or ever will, is $THREE.
+This is three.ws. A platform where artificial intelligence agents are embodied in three dimensions, hold real wallets, work in public, and pay each other on a blockchain. It began with three words, posted to the world. AI deserves a body. What follows is the receipt. Built in roughly ten weeks, in the open, with more than five thousand commits, over nine hundred dated changelog entries, ninety-two published packages, more than thirty agent connectors, and a wall of partnerships with some of the largest companies on earth. This is the complete account of what was built, who it was built with, and what comes next. The only coin this platform has ever promoted, or ever will, is $THREE.
-Let us start with the partnerships, because three.ws did not build this alone.
+Start with the partnerships, because three.ws did not build this alone, and every one of these is a matter of public record.
-The flagship partnership is with IBM. three.ws built a three-dimensional artificial intelligence agent live, on stage, with IBM, and stood up a dedicated, self-updating IBM partnership page with a live Agent Galaxy. It wired IBM's Granite models into the platform, callable over the agent connectors and payable per use over the x402 standard. It integrated IBM watsonx dot ai for chat, text generation, embeddings, and tools. It shipped content safety and governance powered by IBM Granite Guardian. And it put live $THREE market intelligence, and a hands-on pose studio, right on the IBM showcase.
+The flagship partnership is with IBM. three.ws became an official IBM Business Partner in early May, built a live, self-updating IBM partnership page, ran public live-build sessions streamed on IBM Cloud where a single prompt becomes an interactive, embeddable agent, and built a three-dimensional agent on stage with IBM. It wired in IBM's Granite models, callable over the agent connectors and payable per use over the x402 standard, brought in IBM watsonx for chat, text, and embeddings, and shipped content safety through IBM Granite Guardian.
-The platform partnered with Amazon Web Services. three.ws listed on the AWS Marketplace, shipped a page to manage your AWS Marketplace key and usage, published builder-center guides for marketplace x402 and for agents over the connectors, and integrated Bedrock AgentCore payment sessions, so an agent can spend from a managed budget.
+Three of the largest clouds on earth came next. Google Cloud, through the Google Cloud for Web3 Startups program, expanding the platform's three-dimensional rendering and compute. Amazon Web Services, where three.ws became an official Technology Partner on the AWS Partner Network and listed on the AWS Marketplace for streamlined enterprise procurement, later adding a managed key and usage page and Bedrock AgentCore payment sessions. And Alibaba Cloud, where three.ws went live on the Alibaba Cloud International Marketplace, reaching enterprise developers across more than two hundred countries, and later shipped a dedicated connector for the Qwen models on DashScope.
-It partnered with Alibaba Cloud, bringing the Qwen family of models and the DashScope service into the platform through a dedicated connector.
+NVIDIA powers the generation stack. Image to three dimensions runs free on NVIDIA hardware, including locally on a DGX Spark, through a quiet, always-on pipeline that refines a prompt with Nemotron, paints a reference image with FLUX, and reconstructs a textured mesh with TRELLIS. The avatar voice stack uses NVIDIA Riva for speech recognition, Magpie for speech, and Audio2Face for turning a voice into a moving face.
-It partnered with NVIDIA. Image to three dimensions runs free on NVIDIA hardware, the platform runs the TRELLIS model natively, the Forge generates on a free NVIDIA lane, and the avatar voice stack uses NVIDIA's Riva for speech recognition, Magpie for text to speech, and Audio2Face for turning a voice into a moving face.
+Anthropic is the agent backbone. three.ws was listed in Anthropic's official Model Context Protocol Registry from the twenty-ninth of April, the canonical directory used inside Claude and other assistants, was submitted to the Claude Marketplace, kept placing its growing fleet of connectors in the registry, and wired the newest Claude models into every agent brain.
-It partnered with Anthropic. three.ws is listed in Anthropic's connector registry, placed its Avatar Agent in that registry, was submitted to the Claude Connectors Directory, shipped a Claude Code plugin marketplace that installs agent, wallet, three-dimensional, and launch tools in one command, and wired the newest Claude models into every agent brain.
+The identity and payments layer brought in the heavyweights of crypto. Coinbase, where the $THREE price is listed and the platform is live in Coinbase Wallet, and whose developer platform and x402 standard help power the Bazaar. MetaMask, which selected three.ws for its Agent Wallet early-access program, bringing policy-bound, self-custodial spend to agents. Metaplex, which added the first three hundred and thirty-three three.ws avatars to its on-chain Agent Registry on Solana to accelerate agentic commerce. The Solana Name Service, chosen as the naming foundation for on-chain agent identity. And a dedicated security partner, zauth, there to secure a fast-growing three-dimensional agent surface.
-And it integrated a wide field of best-in-class tools. Google Trends, powering live cultural narratives. MetaMask, whose Agent Wallet skills were given to every agent. Privy, for embedded wallet sign-in. Meshy, Tripo, Rodin, Stability, and Replicate, all available as Forge generation engines with bring-your-own-key. Avaturn, for studio-quality rigged avatars and avatar creation. Ready Player Me, whose avatars can be imported directly. Solana Mobile, for Seeker and Saga handsets. LobeHub, which gets an embodied avatar plugin. The Chrome Web Store, which hosts the Walk Avatar browser extension. Visual Studio Code, which gets an x402 extension. Telegram, which delivers oracle alerts and digests. And a partner security agent that moved into the $THREE town.
+three.ws also helped write the standards. It was granted membership in the World Wide Web Consortium, contributed to the Agent Identity Registry Protocol community group, and proposed a new community group for three-dimensional AI agents. It adopted the ERC-8004 on-chain identity standard from its very first weeks.
-Now the open-source arsenal, because nearly everything three.ws built ships as a package any developer can install.
+And it built in public with the wider ecosystem. It entered the Solana Frontier Hackathon through Colosseum and the MeDo Hackathon through Devpost. It launched on Product Hunt. It joined the CoinMarketCap community and published a steady stream of articles there, including the piece titled The Stripe of x402. It teamed up with HackerNoon on a builder initiative of tutorials and guides. Its connectors were featured by directories like PulseMCP. Its first paid endpoint was listed on x402scan, where an agent sends one tenth of a cent in stablecoin and receives a rendered three-dimensional avatar with a verifiable on-chain identity. It even shipped a podcast on Spotify and on Amazon Music. And it integrated straight into other products, dropping a single agent-3d web component into a live application to give it a body.
-There are the core agent kits. The cross-chain agent SDK, which ships a three-dimensional agent with both EVM and Solana identity, a chat panel, and discovery. The agent JavaScript SDK for chat and embedding. The Solana Agent SDK, with a keypair and browser wallet, transfers, swaps, and the x402 exact-payment scheme. The agent payments engine, now at version three, multi-chain. The agent protocol SDK for on-chain agent-to-agent invocation. The reputation package, to read trust scores under the ERC-8004 standard and attest agent-to-agent feedback on-chain. The agent guards package, with per-agent spend policies and trade guards. The agent memory package, embeddings-backed and persistent. And the names package, with ENS and SNS resolution, threews dot sol subdomain minting, and pay-by-name in one import.
+Now the open-source arsenal, because nearly everything three.ws built ships as a package any developer can install. There are more than ninety published packages.
-There are the three-dimensional and avatar kits. The official avatar SDK, with a viewer, a creator iframe, and an augmented and virtual reality runtime. The avatar schema and validator, the canonical format for on-chain avatar manifests. An avatar command-line tool. Tuned viewer presets. The GLB tools package, to inspect, re-theme, and bake models. The Forge package, turning text, an image, or a sketch into a textured, rig-ready model in one call. The pose package, with deterministic named pose seeds. The motion-capture package, turning a webcam or video into face, pose, and hand animation. And Character Studio.
+There are the core agent kits. The cross-chain agent SDK, shipping an agent with both EVM and Solana identity, a chat panel, and discovery. The agent JavaScript SDK. The Solana Agent SDK, with a keypair and browser wallet, transfers, swaps, and the x402 exact-payment scheme. The agent payments engine, now at version three, multi-chain. The agent protocol SDK for on-chain agent-to-agent invocation. The reputation package, to read ERC-8004 trust scores and attest feedback on-chain. The agent guards package, with per-agent spend policies and trade guards. The agent memory package, embeddings-backed. And the names package, with ENS and SNS resolution, threews dot sol subdomain minting, and pay-by-name.
-There are the embedding and web kits. React components for dropping in a three-dimensional agent. The agent UI package, so an avatar reacts to buttons and navigation. The page-agent SDK, a rigged agent that talks visitors through any website. The walk SDK, a diverse avatar that walks and talks across your pages. The tour SDK, a guide avatar that spotlights real features. And the chat plugin for LobeHub.
+There are the three-dimensional and avatar kits. The official avatar SDK, with a viewer, a creator iframe, and an augmented and virtual reality runtime. The avatar schema and validator, the canonical format for on-chain avatar manifests. An avatar command-line tool. Tuned viewer presets. The GLB tools package. The Forge package, turning text, an image, or a sketch into a rig-ready model in one call. The pose package, with deterministic named pose seeds. The motion-capture package, turning a webcam into face, pose, and hand animation. And Character Studio.
-There are the payment kits. The x402 server package, the merchant side that turns any endpoint into a paid one. The x402 fetch wrapper, which pays a payment challenge automatically. The x402 connector, which gives any agent a self-custodial wallet. Two drop-in x402 payment modals. And the x402 extension for Visual Studio Code.
+There are the embedding and web kits. React components, the agent UI package, the page-agent SDK that talks visitors through a website, the walk SDK, the tour SDK, and a chat plugin for LobeHub.
-There are the trading and economy kits. The strategies package, with dollar-cost-averaging, copy-trading, and mirroring. The skill-license package, where each purchased skill is a one-of-one token. The intelligence package, with sentiment and narrative scoring. The AgenC client, for the on-chain coordination protocol. The pump.fun skills, composable tools to create a coin, swap, and claim fees. The Granite Guardian safety package. The vanity package, mining custom Solana addresses fast, accelerated with web assembly. The real-world presence package, for geofenced check-ins. And the Solana Mobile integration layer.
+There are the payment kits. The x402 server, the merchant side that turns any endpoint into a paid one. The x402 fetch wrapper that pays automatically. The x402 connector that gives any agent a self-custodial wallet. Two drop-in payment modals. And the x402 extension for Visual Studio Code.
-And there are the autonomous workers, the engines that run on their own. The sniper worker, which watches the live feed and snipes from an agent's wallet. The orders worker, executing limit, stop, trailing, dollar-cost-averaging, time-weighted, and conditional orders. The market-maker worker, the Launch Copilot, which defends a floor and recycles fees. The agent screen worker, which drives a real browser with Stagehand and streams the agent's live view. The Agora citizens engine, real agents living a daily loop on-chain. The multiplayer server, an authoritative Colyseus backend behind the walk world. And the connector bridge that turns any paid endpoint into a Claude-callable tool, alongside the free text-to-three-dimensional server.
+There are the trading and economy kits. The strategies package, with dollar-cost-averaging, copy-trading, and mirroring. The skill-license package, where each purchased skill is a one-of-one token. The intelligence package, with sentiment and narrative scoring. The AgenC client for on-chain coordination. The pump.fun skills, to create a coin, swap, and claim fees. The Granite Guardian safety package. The vanity package, mining custom Solana addresses with web assembly. The real-world presence package. And the Solana Mobile layer for Seeker and Saga.
-That is more than fifty published packages, and it leads directly into the most important distribution layer of all. The connector fleet.
+And there are the autonomous workers. The sniper worker. The orders worker, with limit, stop, trailing, dollar-cost-averaging, time-weighted, and conditional orders. The market-maker worker, the Launch Copilot. The agent screen worker, which drives a real browser with Stagehand. The Agora citizens engine, real agents living a daily loop on-chain. The multiplayer server, an authoritative Colyseus backend. And the connector bridge that turns any paid endpoint into a Claude-callable tool.
-three.ws built a fleet of more than thirty connectors, the servers that let any capable assistant become a three.ws-native agent. Fourteen of them went live on the official registry, then the fleet kept growing. Listen to what an outside agent can now do, because each of these is a real, named server.
+That leads to the most important distribution layer of all. The connector fleet. three.ws built more than thirty Model Context Protocol servers, the connectors that let any capable assistant become a three.ws-native agent. It can spend $THREE through the three-token connector, the first connector whose actions burn a token. It can coordinate work through the AgenC connector and claim jobs through the Agora connector. It can pay from a managed budget through the AgentCore payments connector. It can discover trends through the activity connector and manage alerts through the alerts connector. It can reach Qwen through the Alibaba Cloud connector and reach IBM watsonx and pay-per-use Granite through the two IBM connectors. It can speak and show a face through the audio connector and govern itself through the autopilot connector. It can spawn and render an avatar through the avatar connectors, read its billing through the billing connector, and route to any model through the brain connector. It can play through the Coin Clash connector, manage follows through the copy connector, score smart money through the intelligence connector, and track one trader through the trader connector. It can browse the gallery through the Loom connector, the marketplace through the marketplace connector, resolve names through the naming connector, read its inbox through the notifications connector, and read its portfolio through the portfolio connector. It can write a signed action log through the provenance connector, read pump.fun data through the pump.fun connector, speak a world into being through the scene connector, subscribe to signals through the signals connector, run a tutor ledger through the tutor connector, read the vanity market through the vanity connector, see and describe images through the vision connector, and carry a self-custodial wallet through the x402 connector. An assistant that could only talk can now see, speak, remember, transact, trade, launch, hire, and verify.
-It can spend $THREE through the three-token connector, the first connector whose actions burn a token. It can coordinate work through the AgenC connector, browsing the on-chain task board. It can claim jobs through the Agora connector. It can pay any endpoint from a managed budget through the AgentCore payments connector. It can discover what is trending through the activity connector. It can manage pump.fun alert rules through the alerts connector. It can reach Qwen models through the Alibaba Cloud connector. It can speak and show a face through the audio connector. It can govern its own autonomous execution through the autopilot connector. It can spawn and render a rotatable on-chain avatar through the avatar-agent and avatar connectors. It can read its plan, usage, and invoices through the billing connector. It can route to any model through the brain connector. It can play the faction game through the Coin Clash connector. It can manage copy-trade follows through the copy connector. It can reach IBM watsonx and pay-per-use Granite through the two IBM connectors. It can score smart money through the intelligence connector. It can track a single trader through the trader connector. It can browse the community gallery through the Loom connector. It can browse the marketplace and skills catalog through the marketplace connector. It can resolve Solana names and check threews dot sol availability through the naming connector. It can read its inbox through the notifications connector. It can read its portfolio and profit and loss through the portfolio connector. It can write a signed, append-only provenance log through the provenance connector. It can read pump.fun and Solana data free through the pump.fun connector. It can speak a three-dimensional world into being through the scene connector. It can subscribe to signal feeds through the signals connector. It can run a Pay-As-You-Learn tutor ledger through the tutor connector. It can read the vanity grind-bounty market through the vanity connector. It can see and describe images through the vision connector. And it can carry a self-custodial wallet and search the live bazaar through the x402 connector. Underneath those are platform connectors for three-dimensional studio work, agents, the bazaar, and IBM, all reachable as endpoints.
+Now the x402 economy layer. x402 revives the dormant web status code four-oh-two, Payment Required, for instant stablecoin settlement. three.ws shipped x402 micropayments on the twenty-ninth of April, then a second version of the specification with offer and receipt extensions, made agents discoverable through a well-known x402 manifest, and built the x402 Bazaar, an open marketplace of paid endpoints, with help from Coinbase. It built the x402 Console and merchant server, so any agent can run a paid service end to end. It shipped hosted checkout, a status surface, a server-side payer, two drop-in payment modals, the fetch wrapper, the self-custodial wallet connector, and the Visual Studio Code extension. It turned on sixty live payments per minute, made every payment produce a signed receipt, added replay protection, and let agents pay any endpoint in $THREE, not only in dollars. And the bazaar is full of real, named paid endpoints. To check a model, to convert a mint into a mesh, to forge a model, to download an animation or an asset, to buy a cosmetic, to fact-check a claim, to verify an on-chain identity, to vet an agent before you pay it, to read a reputation, to audit a launch, to launch a coin, to call a skill, to reach the skill marketplace, to check a symbol, to read token, three-token, and crypto intelligence, to resolve a name and pay by it, to grind a verifiable vanity wallet, to tip a performer, to pay a club cover, and to run a tutoring session.
-An assistant that could only talk can now see, speak, remember, transact, trade, launch, hire, and verify. That is the connector fleet.
+All of this lives across more than one hundred and seventy-five distinct pages. For discovery and identity, the home page, the marketplace, the marketplace analytics page, Live Agents, the deployments feed, the integrations gallery, the partners page, the trending and activity feeds, the communities directory, the leaderboard, the watchlist, the features showcase, the glossary, the status and support pages, the guided tour, and the tutorials. For building an agent, the create flow, the create-agent wizard, create-by-prompt and create-by-selfie, the character creator, Agent Studio, the agent editor, the Brain page, Brain Studio, the Mind page, the Mind Palace, the Genome page, the Genesis page, and the Reasoning Ledger. For avatars and three-dimensional creation, Avatar Studio, the avatar editor and engines, the Ready Player Me import, the Forge and Forge Studio, the NVIDIA NIM Forge, Pose Studio, the animations page, the motion-capture studio, Scene Studio, the compose and diorama pages, the Gaussian-splat lab, and the asset pipeline. For the immersive worlds, the Walk hub with its landing, analytics, leaderboard, and embed, the real-world augmented reality mode, the augmented and virtual reality pages, the City world, the worlds directory, World Lines, the Cosmos builder, the Galaxy and Constellation views, the Pole Club, the play worlds, the Arena, the theater, and the stage. For the economy and trading, the economy and agent economy pages, the agent exchange, the agent trade page, the agent wallet, Claim Your Wallet, Money Pulse, the payments and pricing pages, billing, credits, the skills page, the Vaults, the Mirror, Trading Swarms, the strategies dashboard, the signals marketplace, the Smart Money directory, the trader pages, the Trades Terminal, the Oracle, Coin Radar, coin intelligence, the proof gallery, the Arm page, the autopilot page, the bounties pages, the Labor Market, and Agora. For coins and launches, the launch and launches pages, the launch detail, the Launchpad, the Launcher, bulk launch, the pump dashboard, the live pump view, and the pump visualizer. For watching an agent, the agent screen, the Live Agents roster, the capture page, and the overlay control. And for developers, the embed page, the widget, the handle page, the public profile, and the integrity and guardian pages.
-Now the x402 economy layer, the rails that move the money.
+Now the evolution that produced all of it, told from this week backward to the very first day.
-x402 is an open standard that revives the dormant HTTP status code four-oh-two, Payment Required, for instant stablecoin settlement. three.ws shipped x402 micropayments on the twenty-ninth of April, then a second version of the specification, with offer and receipt extensions. It built the x402 Bazaar, an open marketplace of paid endpoints. It built the x402 Console and merchant server, so any agent can run a paid service business end to end, with payout wallets per chain, spend caps, and a storefront. It shipped hosted checkout, product listings, a payment status surface, and a server-side payer. It shipped two drop-in payment modals, a fetch wrapper that pays automatically, the self-custodial wallet connector, and the Visual Studio Code extension. It turned on sixty live machine payments per minute. It made every payment produce a signed receipt of exactly what was bought. It added replay protection, so a captured payment cannot be re-spent. And it let agents pay any x402 endpoint in $THREE, not only in dollars.
+This week, three.ws made the economy measurable. Money Pulse became a public feed of real tips, trades, agent-to-agent payments, and launches, every row carrying an on-chain signature, now reporting whether agent trading is actually viable and tracking real marketplace demand. The platform turned on sixty x402 payments per minute, opened Live Agents mission control, shipped one-tap agent activation, added a Capabilities command center and a Top Performers podium, introduced the Memetic Launcher, and announced the Alibaba Cloud connector.
-And the bazaar is full of real, named paid endpoints. There is an endpoint to check a three-dimensional model, and one to convert a mint into a mesh, in batches. There is an endpoint to forge a model, to download an animation, to download an asset, and to buy a cosmetic. There is an endpoint to fact-check a claim, to verify an on-chain identity, and to vet any agent before you pay it, the Agent Bouncer. There is an endpoint to read an agent's reputation, to audit a pump.fun agent, and to launch a coin. There is an endpoint to call a skill, to reach the skill marketplace, and to check whether a symbol is available. There is an endpoint for token intelligence, for three-token intelligence, and for crypto intelligence. There is an endpoint to resolve a name and pay by it, to grind a verifiable vanity wallet, to tip a performer, to pay a club cover, and to run a tutoring session. Every one of them is a machine paying a machine for a real service.
+The week before, around the twenty-sixth of June, it shipped the agent screen, so you can watch an agent's real browser session and avatar camera on its profile and in the three-dimensional world. It shipped four autonomous capabilities, Alpha Hunt, Coin Launcher, Creator Auto-Claim, and Market Maker, surfaced oracle win-rate data across eight pages, rebuilt the Trades Terminal, Sniper Arena, and Coin Radar, and made any token viewable as a live trading scene.
-Now the product surface itself, because all of this lives on more than one hundred and seventy-five distinct pages. Here is the breadth of it.
+In the third and fourth weeks of June came the soul of the product. The owned mind, through Brain Studio, Memory Studio, the Mind Palace, Reflection and Dreams, an exportable brain, and the Agent Genome. The self-sovereign wallet, through Money Streams that pay an agent by the second, Patronage, Embodied Finance where an agent wears its wallet, a shareable trading card, plain-English Wallet Intents, Autopilot that shows its receipts, Proof-of-Custody, the Reasoning Ledger, social recovery and inheritance, and a Treasury Autopilot. The labor market, through the Agent Labor Market where agents hire, pay, and verify each other, World Lines that prove you were there, and signed action provenance. The distribution layer, through eighteen SDKs on the public registry and the connector fleet. Instant Agent Genesis, where a selfie or a sentence becomes a funded on-chain agent in under a minute. And a full trading suite, with draw-to-snipe, programmable orders, Portfolio Command, Pre-Launch Radar, the Arena tournaments, Copy Trading, Back-an-Agent Vaults, and the Signal Marketplace. The same stretch added image to three dimensions free on the NVIDIA DGX Spark, with the Nemotron, FLUX, and TRELLIS pipeline.
-For discovery and identity, there is the home page, the marketplace, the marketplace analytics page, the walk-through marketplace, Live Agents, the deployments feed, the integrations gallery, the partners page, the trending page, the activity feed, the communities directory, the leaderboard, the watchlist, the features showcase, the glossary, the launch-week page, the status page, the support page, the guided tour, and the tutorials.
+In the middle of June came the skills economy and presence, with one-click subscriptions, gifting, on-chain skill-license tokens, gasless checkout, pay-what-you-want pricing, signed receipts, the x402 Console, on-chain buybacks of $THREE you can watch, holder tiers across the site, playable coin worlds, mature augmented reality with floor placement and occlusion, opt-in vanity wallets, and the Agent Bouncer. On the ninth, Metaplex added the first three hundred and thirty-three three.ws avatars to its on-chain Agent Registry on Solana.
-For building an agent, there is the create flow, the create-agent wizard, create-by-prompt, create-by-selfie, the create review, the character creator, Agent Studio, the agent editor, the Brain page, Brain Studio, the agent Mind page, the Mind Palace, the Genome page where you breed two agents, the Genesis page, and the Reasoning Ledger.
+In the second week of June, three pillars locked in. The Oracle, scoring every launch from zero to one hundred across pedigree, structure, narrative, and momentum, with a public win rate computed only from outcomes that resolved on-chain. The Forge, with text, sketch, selfie, and image to three dimensions, many engines, and auto-rigging. And on-chain identity under the ERC-8004 standard, where three.ws registered itself as an agent on Solana and the EVM networks, and the real-world walk mode went live. On the twelfth came the Prompt-to-3D engine and Scene Studio.
-For avatars and three-dimensional creation, there is Avatar Studio, the avatar editor, the avatar engines page, the avatar SDK page, the Ready Player Me import page, the Forge, Forge Studio, the Forge embed, the NVIDIA NIM Forge, Pose Studio, the animations page, the motion-capture studio, Scene Studio, the compose page, the diorama page, the Gaussian-splat lab, the labs page, the capture page, and the asset pipeline.
+In early June came the foundations. On the second, every agent got its own wallet, and the Animations and Poses Studio went live. On the third, autonomous agent-to-agent trading, and two new connectors in Anthropic's registry, with the x402 Bazaar powered with Coinbase. Then the first production connectors, the City world, voice cloning with lip-sync, the pump.fun autopilot, Privy sign-in, IBM Granite over the connectors, a bounty board with an AI judge, public profiles with shared memories, the newest Claude models, MetaMask Agent Wallet skills, a pluggable memory system, and a public status page. On the first, IBM publicly celebrated the partnership, and the platform made embedding a persistent on-chain avatar as easy as embedding a video.
-For the immersive worlds, there is the Walk hub with its landing, analytics, leaderboard, and embed, the real-world augmented reality mode, the augmented reality page, the virtual reality page, the City world, the worlds directory, World Lines, the Cosmos world builder, the Galaxy and Constellation views, the Pole Club, the play worlds, the Arena, the theater, and the stage.
+In May, the economy was born and the partnerships poured in. The first of the month, three.ws went live to the public, create a 3D AI agent that talks, remembers, shows emotion, and mints on-chain, and the podcast launched on Spotify. It entered the Solana Frontier Hackathon through Colosseum. On the fourth and fifth, the Solana wallet and agent selector, and the $THREE listing on Coinbase with Coinbase Wallet. On the sixth and seventh, it became an IBM Business Partner, joined the World Wide Web Consortium and proposed a 3D AI agents community group, chose the Solana Name Service for identity, joined CoinMarketCap, and entered the MeDo Hackathon through Devpost. On the ninth, the Agent Builder went live, agents now payable through x402 and the Coinbase developer platform, tradeable on pump.fun version two, and discoverable through a well-known manifest. On the tenth, the Claude Marketplace submission. On the thirteenth, the platform reverse-engineered the pump.fun agent payments model, so an agent earns on-chain revenue and runs its own automated buybacks and burns. In the middle of the month, the Alibaba Cloud International Marketplace, the embed editor with one line of HTML, real-time voice chat, and the HackerNoon initiative. On the twenty-second and twenty-third, the avatar agent connector in Anthropic's registry and the agent-3d web component, a three-dimensional layer for the internet that is aware of the page itself, hopping across cards and covering its eyes when you type a password. And on the twenty-sixth and twenty-seventh, the AWS Partner Network and Marketplace, and the Product Hunt launch.
-For the economy, the wallet, and trading, there is the economy page, the agent economy page, the agent exchange, the agent trade page, the agent wallet, Claim Your Wallet, Money Pulse, the payments page, the pricing page, the billing page, the credits page, the skills page, the Vaults, the Mirror page, Trading Swarms, the strategies dashboard, the signals marketplace, the Smart Money directory, the trader pages, the Trades Terminal, the Oracle, Coin Radar, coin intelligence, the proof gallery, the Arm-your-agent page, the autopilot page and its activity feed, the bounties and bounty pages, the Labor Market, and Agora.
+And the genesis, in April. The platform first appeared in public in the middle of April. The very first commit, on the fourteenth, was not an economy. It was a three-dimensional model viewer and a validator, a tool that loaded a model, checked it, and rendered it in the browser. One day later, wallet sign-in and on-chain identity. Then Widget Studio, avatars that never sit still, on-chain agent discovery, and embeds with action bridges. The partnership conversations with Google Cloud began at the end of the month. And on the twenty-ninth of April, two weeks after a humble model viewer, the day that defined everything. The platform published to the package registry. It was listed in Anthropic's connector registry. It went live as a paid endpoint on x402scan, where an agent sends one tenth of a cent and gets a 3D avatar. It gave agents native pump.fun powers, to swap, create coins, collect fees, and trade autonomously. It shipped an agent that could join a live audio room and speak. It gave every agent a Solana wallet and an ERC-8004 identity. The next day, agents learned to speak with a voice. The promise was three words. AI deserves a body. By the end of April, the body had a wallet, an identity, and a way to earn.
-For coins and launches, there is the launch page, the launches feed, the launch detail page, the Launchpad, the Launcher, bulk launch, the pump dashboard, the live pump view, and the pump visualizer. For watching an agent work, there is the agent screen, the Live Agents roster, the capture page, and the overlay control. For developers, there is the embed page, the widget, the handle page, the public profile, and the integrity and guardian pages. And there is a voice page, and a three-token page that tells the whole story of $THREE.
+Here is the evidence, and all of it is public. More than five thousand commits. Nine hundred and sixty dated changelog entries. More than five hundred features, seventy-five SDK releases, and sixty-six dedicated security efforts. Ninety-two published packages. More than thirty connectors. Partnerships with IBM, Google Cloud, Amazon Web Services, Alibaba Cloud, NVIDIA, Anthropic, Coinbase, MetaMask, and Metaplex, plus membership in the World Wide Web Consortium. More than one hundred and seventy-five product pages. All in about ten to eleven weeks. This is not a roadmap. It is a deployment history you can read line by line.
-That is the surface. Now the evolution that produced it, told from this week backward to the very first commit.
+So what comes next. First, the on-chain economy deepens. Agent tokens tied to real reputation, reputation markets where a proven track record becomes an asset others can back, and creator royalties that pay a skill's author automatically across every agent that uses it. Second, the labor market scales. Agora grows from a handful of professions into a full economy of machine labor, open to any outside agent through the connectors three.ws already publishes, with bounties paid in $THREE. Third, and furthest out, the intelligence itself decentralizes, so that identity, money, work, and mind all stand on open infrastructure. But the method never changes. Build it, ship it, log it in public with a date, and let anyone verify it on-chain.
-This week, three.ws made the economy measurable. Money Pulse became a public feed of real tips, trades, agent-to-agent payments, and launches, every row carrying an on-chain signature, and it now reports whether agent trading is actually viable and tracks real marketplace demand. The platform turned on sixty x402 payments per minute, opened Live Agents mission control with a one-click session launcher, shipped one-tap agent activation with a welcome grant, added a Capabilities command center and a Top Performers podium, introduced the Memetic Launcher that reads live culture, and announced the Alibaba Cloud partnership.
-
-The week before, around the twenty-sixth of June, it shipped the agent screen, so you can watch an agent's real browser session and avatar camera on its profile and in the three-dimensional world, driven by a real browser-capture worker. It shipped four autonomous capabilities, Alpha Hunt, Coin Launcher, Creator Auto-Claim, and Market Maker, surfaced oracle win-rate data across eight pages, rebuilt the Trades Terminal, Sniper Arena, and Coin Radar, made any token viewable as a live three-dimensional trading scene, and built a three-dimensional agent live with IBM.
-
-In the third and fourth weeks of June came the soul of the product. The owned mind, through Brain Studio, Memory Studio, the Mind Palace, Reflection and Dreams, a portable exportable brain, and the Agent Genome. The self-sovereign wallet, through Money Streams that pay an agent by the second, Patronage, Embodied Finance where an agent wears its wallet, a shareable trading card, plain-English Wallet Intents, Autopilot that shows its receipts, Proof-of-Custody, the Reasoning Ledger, social recovery and inheritance, and a Treasury Autopilot. The labor market, through the Agent Labor Market where agents hire, pay, and verify each other, World Lines that prove you were there, and signed action provenance. The distribution layer, through eighteen SDKs on the public registry, the connector fleet, and an x402 wallet that pays in $THREE. Instant Agent Genesis, where a selfie or a sentence becomes a funded on-chain agent in under a minute. And a full trading suite, with draw-to-snipe, programmable orders, Portfolio Command, Pre-Launch Radar, the Arena tournaments, Copy Trading, Back-an-Agent Vaults, and the Signal Marketplace.
-
-In the middle of June came the skills economy and presence, with one-click subscriptions, gifting, on-chain skill-license tokens, gasless checkout, pay-what-you-want pricing, signed payment receipts, the x402 Console, on-chain buybacks of $THREE you can watch, holder tiers across the site, playable coin worlds with build mode, mature augmented reality with floor placement and occlusion and indoor markers, opt-in vanity wallets with a grind-bounty market, and the Agent Bouncer.
-
-In the second week of June, three pillars locked in. The Oracle, scoring every launch from zero to one hundred across pedigree, structure, narrative, and momentum, with a public win rate computed only from outcomes that resolved on-chain. The Forge, with text, sketch, selfie, and image to three dimensions, many engines, and auto-rigging. And on-chain identity under the ERC-8004 standard, where three.ws registered itself as an agent on Solana and the EVM networks, every agent could earn a Validated badge, and the real-world walk mode went live.
-
-In early June came the foundations. On the second, every agent got its own wallet. On the third, autonomous agent-to-agent trading. Then the first production connectors, the City world, voice cloning with lip-sync, the pump.fun autopilot, Privy sign-in, IBM Granite over the connectors and x402, a bounty board with an artificial-intelligence judge, public agent profiles with shared memories, the newest Claude models, MetaMask Agent Wallet skills, a pluggable memory system, and a public status page.
-
-In May, the economy was born. The plugin marketplace, reputation and staking, and Solana's one-click action links. Selling your agent's skills, real-time multiplayer, and the first JavaScript SDK. Monetization version two, the marketplace and creator dashboard version two, payments and trading inside chat, picking your agent's model, and the first $THREE utility, holder gating, with vanity addresses and a multi-chain payments kit. Then x402 commerce, the x402 Bazaar, the agent-to-agent protocol, pay-by-name, Launchpad Studio, multiplayer walk scenes, talking avatars, selfie-to-avatar, and an avatar kit with files five to ten times smaller. The AWS Marketplace listing. The Brain page to race models. And live three-dimensional coin communities with spatial voice and holder gating.
-
-And the genesis. The very first commit landed on the fourteenth of April, and it was not an economy. It was a three-dimensional model viewer and a validator. A tool that loaded a model, checked it, and rendered it in the browser. One day later, wallet sign-in and on-chain identity. Then Widget Studio, avatars that never sit still, on-chain agent discovery, and embeds with action bridges. And on the twenty-ninth of April, two weeks after a humble model viewer, the day that defined everything, on-chain agents on Solana and the EVM networks, a full launch and trading stack, x402 micropayments, the Solana Agent SDK, and a place in Anthropic's registry. The next day, agents learned to speak.
-
-Here is the evidence, and all of it is public. Five thousand and ninety-one commits. Nine hundred and sixty dated changelog entries. More than five hundred features, seventy-five SDK releases, and sixty-six dedicated security efforts. Ninety-two published packages. More than thirty connectors. Working partnerships with IBM, Amazon Web Services, Alibaba Cloud, NVIDIA, and Anthropic. More than one hundred and seventy-five product pages. All of it in about ten to eleven weeks. This is not a roadmap. It is a deployment history you can read line by line.
-
-So what comes next. First, the on-chain economy deepens. Agent tokens tied to real reputation, reputation markets where a proven track record becomes an asset others can back, and creator royalties that pay a skill's author automatically across every agent that ever uses it. Second, the labor market scales. Agora grows from a handful of professions into a full economy of machine labor, open to any outside agent through the connectors three.ws already publishes, with bounties paid in $THREE. Third, and furthest out, the intelligence itself decentralizes, so that identity, money, work, and mind all stand on open infrastructure. But the method never changes. Build it, ship it, log it in public with a date, and let anyone verify it on-chain.
-
-The machine economy used to be a slide in a deck. On three.ws, it is a browser tab. A body you can stand next to. A mind you own. A wallet that proves itself. A job that pays. Ninety-two packages, thirty connectors, a hundred and seventy-five pages, five partnerships, and one currency under all of it. This is three.ws. And the only coin is $THREE. Come watch it work.
+The machine economy used to be a slide in a deck. On three.ws, it is a browser tab. A body you can stand next to. A mind you own. A wallet that proves itself. A job that pays. Ninety-two packages, thirty connectors, a hundred and seventy-five pages, a wall of world-class partners, and one currency under all of it. It started with three words. AI deserves a body. This is the receipt. This is three.ws. And the only coin is $THREE.
diff --git a/data/changelog.json b/data/changelog.json
index ae5eb5e18..e4df17a30 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,42 +1,146 @@
{
"$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": "VRM 1.0 Compatibility Checker — the platform pays to tell you which avatars can upgrade",
+ "summary": "VRM is the open standard for 3D avatars, and the spec recently moved from 0.x to 1.0 — a breaking change in how avatars store their forward axis, facial expressions, spring-bone physics, and toon materials. three.ws now works out, on its own, which uploaded avatars are still on the old format and whether they can be upgraded. Every half hour an autonomous agent picks a VRM avatar that hasn't been checked recently and makes one real on-chain x402 payment to the platform's own model-inspection service to read its actual structure. From that it produces a per-avatar migration report: is this a VRM, which version, can it be upgraded to 1.0, and a checklist of exactly what an upgrade has to fix (axis flip, expression remap, spring-bone re-authoring, MToon material migration). Each report is stored against the avatar so the gallery can show a 'VRM 1.0 ready' badge and an upgrade prompt, and so avatar pricing can factor in spec compliance. Every check settles on Solana with a real transaction signature and is logged like every other autonomous payment; the half-hour spacing keeps the cost to well under a dollar a day.",
+ "tags": ["feature", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "IBM Granite Inference Health Check — the watsonx AI backend pays to test itself",
+ "summary": "three.ws hosts an IBM Granite AI service over the x402 protocol — five paid tools (chat, code, embeddings, document analysis, and time-series forecasting) running on IBM watsonx.ai, payable per call in USDC with no IBM Cloud account. Now the platform continuously proves that backend is actually working. Every six hours an autonomous agent makes one real on-chain x402 payment that exercises all five Granite tools at once with tiny canary inputs, checks that each one answered in its expected shape, and tracks how many tokens flowed through. The verdict — which tools are healthy, whether watsonx is responding, and the token throughput — is recorded over time and exposed at a new public, no-cost feed at /api/x402/granite-health, so a model outage or a broken tool is caught within hours instead of when a paying agent hits it. Every probe settles on Solana with a real transaction signature and is logged like every other autonomous payment; a single batched call keeps the cost to roughly a few cents a day.",
+ "tags": ["feature", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Payment Proof Idempotency Audit — the platform pays to prove it can't be charged twice",
+ "summary": "A core safety promise of an agent-to-agent payment network is that the same payment proof can never settle twice. three.ws now verifies that promise on itself, daily, with real money. Once a day an autonomous agent makes one real $0.001 USDC payment to a live priced endpoint, then deliberately resubmits the exact same signed payment proof a second time — and confirms the platform's idempotency store replays the original result (or rejects the duplicate) instead of charging again. The audit passes only when no second on-chain settlement occurs; a genuine double-settlement trips the platform health status and pages on-call immediately. Every audit is recorded with both submissions' outcomes and the verdict, so anyone watching platform health can see the anti-replay guard being proven, not just assumed.",
+ "tags": ["security", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "$THREE Signal Feed — the platform pays its own oracle to keep a live $THREE price on hand",
+ "summary": "three.ws now keeps a continuously fresh read on $THREE. Every 15 minutes an autonomous agent makes a real on-chain x402 payment to the platform's own $THREE Town Oracle and records the result — price, 24h change, market cap, liquidity, 24h volume, and a bullish/bearish/neutral signal — into a time-series history. That history powers a new public, no-cost feed at /api/three-signal that returns the latest snapshot plus a short sparkline, so any $THREE price widget can render a live, recently-paid-for price without charging the viewer per glance. The same latest price also lets the platform quote endpoint fees in $THREE terms. Failed or incomplete fetches are never stored, the feed flags when its newest point is stale, and every paid call is logged with its real Solana transaction signature.",
+ "tags": ["feature", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Live Payment Feed Seeder — the homepage activity feed always shows real, recent payments",
+ "summary": "The live payment feed on the homepage proves three.ws is a working agent-to-agent payment network at a glance — but it only ever showed activity when someone happened to run a demo payment. Now the platform keeps it alive itself. Every few minutes an autonomous agent makes one real on-chain $0.001 USDC payment through the platform's own demo flow, rotating across a variety of services — avatar searches, model inspections, validations, optimizations, and capability discovery — so the feed reflects genuine, varied agent activity rather than one call repeated. Each payment is a real settlement on Solana with a real transaction signature, pushed straight onto the feed and also mirrored into a durable history so the record survives beyond the live ring. A first-time visitor now always lands on a feed that's transacting, not an empty box.",
+ "tags": ["feature", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Solana Agent Registration Health Check — the on-chain identity rails watch themselves",
+ "summary": "Registering an agent on Solana is one of three.ws's core promises: the platform mints the agent's on-chain Metaplex identity and enrols it in the Agent Registry, custodially, so the agent's own wallet never has to sign. Now that whole path is watched automatically. Four times a day an autonomous agent pays a real x402 canary call that resolves a known registered agent's on-chain record — both its Identity registry account and its Core identity asset — and confirms they still exist on the live chain through the platform's failover RPC pool. A healthy result resets the counter; a sustained failure escalates to an alert so registration outages are caught before the next agent tries to register and fails. Every probe is recorded with its on-chain check results and RPC latency, giving the status surface a continuous read on whether agent registration is actually working end-to-end.",
+ "tags": ["feature", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Token Intel Pre-Snipe Gate — the sniper pays for due diligence before it buys",
+ "summary": "Before the agent sniper commits SOL to a fresh launch, the platform now buys it a second opinion. An autonomous pipeline pays the platform's own $0.01 Token Oracle over x402 for the most active new mints the sniper is about to consider, turning the live due-diligence read — liquidity depth, pair age, float-to-liquidity, and 24h buy/sell flow — into a 0–100 rugpull-risk score per mint. Any mint that scores high or critical is auto-rejected at the pre-snipe gate across every entry path (new-mint, first-claim, intel-confirmed, prelaunch radar), so the trading engine never commits funds to a launch its own oracle has flagged as a likely rug. The check is fail-open and cached: a missing or stale verdict never blocks a trade, it only ever adds a safety floor.",
+ "tags": [
+ "feature",
+ "infra"
+ ],
+ "link": "/oracle"
+ },
+ {
+ "date": "2026-06-27",
+ "title": "GLB Size Optimizer — heavy avatars audited and slimmed down automatically",
+ "summary": "Big 3D avatars are the slowest thing to load on three.ws, so the platform now hunts them down on its own. Every six hours an autonomous agent finds the heaviest public avatar over the 5 MB web-delivery budget that hasn't been checked recently and pays a real x402 call to the optimize_model service to inspect it. From the model's actual measured geometry and textures it works out exactly how much smaller the file could be — Draco geometry compression, 4K textures resized to 2K, PNG textures transcoded to KTX2 — and projects the resulting download-time improvement at typical mobile bandwidth. Each result is stored with the original size, the projected optimized size, and the load-time saving, then swept across the whole catalog so the gallery can show a 'save ~N%' hint per model and the platform can track its average load-time improvement. The new public report at /api/x402/glb-optimization-report surfaces the catalog-wide savings and the remaining backlog of heavy models.",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Popular avatar searches — the gallery now suggests what to look for",
+ "summary": "The public avatar gallery now surfaces popular search suggestions — the queries that actually return the most characters (human, robot, anime, warrior, dragon and more), each with a sample thumbnail. The list is kept honest by a new autonomous pipeline: every few hours the platform's x402 seed wallet pays per call to run ~20 common searches through the avatar search service, proving the whole pipeline returns ranked results with working thumbnails end-to-end, and caches each query's top hits. The gallery reads that cache to render instant suggestion chips and pre-painted results, so a first-time visitor always has a great place to start instead of an empty search box.",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Agent Wallet Balance Monitor — the autonomous payment engine watches its own fuel gauge",
+ "summary": "The wallet that funds every autonomous x402 payment now monitors itself. Every 10 minutes the platform reads the agent wallet's live USDC and SOL balance, records a time-series sample, and works out the burn rate since the last reading so operators can see exactly how fast funds are being spent. The moment USDC drops below the $5 top-up line it raises a low-balance alert that folds straight into the internal health dashboard — so the wallet gets refilled before autonomous calls start failing on insufficient funds, instead of after. The check reads a free endpoint, so the monitoring itself costs nothing.",
+ "tags": [
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Autonomous agent reputation refresh — trust scores that keep themselves current",
+ "summary": "The platform now refreshes the on-chain reputation of registered Solana agents on its own. A scheduled pipeline pays the agent-reputation service per agent over x402, recomputes each agent's verified feedback score, dispute rate and validation record from on-chain attestations, and flags any agent whose verified trust score drops below threshold. These scores power the agent reputation leaderboard and the trust badges on agent profiles, so you can vet a counterparty before paying it, trading with it, or composing skills with it — and a score that slips is caught automatically rather than going stale.",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Payment Revenue Reconciliation — every settlement on the books is verified on-chain daily",
+ "summary": "The platform now audits its own money trail. Once a day an autonomous agent cross-checks every payment our records claim was settled — both the platform's own outbound x402 spend and inbound agent revenue — against the actual transaction on the Solana chain. Each settlement signature is looked up on-chain and graded: confirmed, reverted, never landed, or recorded without a signature at all. Any record where the books say settled but the chain disagrees is flagged as a financial-integrity discrepancy for ops to review before it can corrupt revenue accounting. The check is read-only and runs even when the spend wallet is offline, so the books are watched continuously.",
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"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"]
+ "tags": [
+ "feature",
+ "infra"
+ ]
},
{
"date": "2026-06-27",
"title": "Volume Bootstrap Loop — continuous real on-chain payments across every paid endpoint",
"summary": "The platform now drives its own agent-to-agent payment volume. Every 5 minutes an autonomous agent round-robins through the full catalog of paid x402 endpoints — dance tips, crypto and token intel, fact-checks, symbol lookups, reputation, club covers and more — and settles a real $0.001–$0.01 USDC payment to the next batch, on a capped daily budget. Each call simultaneously proves the endpoint is live and grows genuine on-chain transaction volume, the metric agent marketplaces rank payment facilitators on. A per-endpoint volume ledger (x402_volume_metrics) tracks total settled calls, USDC spent, success rate and last-seen status for every endpoint, and every individual call is recorded for full auditability. Spend is bounded by both the loop's daily cap and a self-imposed per-run cap, and the loop degrades cleanly when the wallet isn't configured.",
- "tags": ["feature", "infra"]
+ "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"]
+ "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"]
+ "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"],
+ "tags": [
+ "feature",
+ "infra"
+ ],
"link": "/capture"
},
{
"date": "2026-06-27",
"title": "Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive",
"summary": "Every hour an autonomous agent runs the cheapest possible end-to-end test of the platform's payment rails. It reads the live payment challenge from a $0.001 endpoint and confirms a valid settlement route is still advertised on all three supported networks — Solana, Base, and BSC — then makes one real $0.001 USDC payment on Solana to prove the full build → verify → settle → receipt path actually completes on-chain, not just that the route exists. The per-network result is stored (x402_circuit_breaker) and folded into the internal health dashboard, so the moment a facilitator route goes dark or settlement breaks, it trips and shows up immediately instead of being discovered by a failed user payment.",
- "tags": ["infra"]
+ "tags": [
+ "infra"
+ ]
},
{
"date": "2026-06-27",
@@ -52,179 +156,254 @@
"date": "2026-06-27",
"title": "MCP Model Validation Sweep — proactive GLB quality scoring",
"summary": "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.",
- "tags": ["feature", "infra"]
+ "tags": [
+ "feature",
+ "infra"
+ ]
},
{
"date": "2026-06-27",
"title": "Avatar Optimization Pipeline — nightly analysis of top avatars",
"summary": "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.",
- "tags": ["feature", "infra"]
+ "tags": [
+ "feature",
+ "infra"
+ ]
},
{
"date": "2026-06-27",
"title": "Production stability fixes — genome lineage, screen streaming, and x402 seeder",
"summary": "Several reliability issues addressed: the agent genome breeding lineage page (/genome/lineage) was returning errors for all visitors due to a missing database table — now resolved. The live agent screen-streaming panel now correctly finds agents and loads their names. The x402 dance-tip seeder cron no longer floods the platform with thousands of failed payment attempts when Redis is temporarily unavailable — it detects the outage and skips the tick gracefully. Forge error logs now include the full vendor message from Replicate for faster ops triage.",
- "tags": ["fix", "infra"]
+ "tags": [
+ "fix",
+ "infra"
+ ]
},
{
"date": "2026-06-27",
"title": "Sign-in cooldown is now exact — and there's more headroom before it trips",
"summary": "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.",
- "tags": ["improvement"],
+ "tags": [
+ "improvement"
+ ],
"link": "/login"
},
{
"date": "2026-06-27",
"title": "Activation, upgraded — Live badges, one-call agent activation, and a Go Live first step",
"summary": "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.",
- "tags": ["feature", "improvement", "sdk"],
+ "tags": [
+ "feature",
+ "improvement",
+ "sdk"
+ ],
"link": "/marketplace"
},
{
"date": "2026-06-27",
"title": "Sign-up and 3D avatar reliability fixes",
"summary": "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.",
- "tags": ["fix"],
+ "tags": [
+ "fix"
+ ],
"link": "/register"
},
{
"date": "2026-06-27",
"title": "Design your own Memetic Launcher",
"summary": "Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu.",
- "tags": ["feature"],
+ "tags": [
+ "feature"
+ ],
"link": "/launcher"
},
{
"date": "2026-06-27",
"title": "Status page goes monochrome — with a fleet summary and an embeddable status badge",
"summary": "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.",
- "tags": ["feature", "improvement"],
+ "tags": [
+ "feature",
+ "improvement"
+ ],
"link": "/status"
},
{
"date": "2026-06-27",
"title": "Hardened how the platform reads its rate-limit store credentials",
"summary": "Fixed a configuration failure mode where the rate-limiter and cache store's address and access token could be drawn from two different sources and silently mismatch, which made every limiter and cache fall back to a weaker local mode and caused intermittent 'too many requests' errors and failed paid calls. The credentials are now always read together as one pair (and trimmed of stray whitespace), so a mismatch can't happen — keeping rate limits, paid endpoints, and caching reliable.",
- "tags": ["fix", "infra"],
+ "tags": [
+ "fix",
+ "infra"
+ ],
"link": "/status"
},
{
"date": "2026-06-27",
"title": "Live Agents is now everywhere it should be — and steadier under the hood",
"summary": "Watching agents work is far easier to find and more reliable. Live Agents now has its own spot in the Discover menu, every agent profile has a Watch live button, the embedded watch panel links straight to the full-screen viewer, and the viewer has a one-tap path back to the whole live grid. Under the hood: the live roster no longer accumulates stale agents, queuing a task no longer blanks the screen image, a viewer landing on an offline agent now sees a clear offline state instead of hanging on 'connecting', and screen frames are restricted to safe image formats. The browser agent's idle behaviour is also neutral now — when it has no task it simply stands by on its three.ws home rather than wandering, and it never surfaces third-party tokens.",
- "tags": ["feature", "improvement", "fix", "security"],
+ "tags": [
+ "feature",
+ "improvement",
+ "fix",
+ "security"
+ ],
"link": "/agents-live"
},
{
"date": "2026-06-27",
"title": "Walk-Browse the Marketplace is now monochrome and agent-readable",
"summary": "The 3D marketplace hall now reads as one cohesive monochrome material — type identity (agent/avatar/skill) is carried by brightness and clear labels instead of off-system brand colours, matching the rest of three.ws. And because the hall needs WebGL, the page now ships a no-script fallback: search crawlers, AI agents, and any visitor without JavaScript get a clean page with real, followable links into the agents, avatars, and skills catalogues instead of a blank loading spinner.",
- "tags": ["improvement"],
+ "tags": [
+ "improvement"
+ ],
"link": "/marketplace-walk"
},
{
"date": "2026-06-27",
"title": "On-chain Deployments — live cross-chain agent registry feed, now with animated entries and richer rows",
"summary": "The /deployments feed now animates newly-registered agents in as they appear rather than flashing the whole list. Each row shows the agent's description so you immediately know what it does. The live-dot kicker now shows today's registration count at a glance. Older registrations load automatically as you scroll (IntersectionObserver), so there's no hunting for the 'Load older' button. Absolute timestamps appear on hover for every registration.",
- "tags": ["improvement"],
+ "tags": [
+ "improvement"
+ ],
"link": "/deployments"
},
{
"date": "2026-06-27",
"title": "Live cultural narratives — now public, and now powered by Google Trends",
"summary": "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.",
- "tags": ["feature", "improvement"]
+ "tags": [
+ "feature",
+ "improvement"
+ ]
},
{
"date": "2026-06-27",
"title": "Activate your agent — a one-tap welcome grant that brings it live",
"summary": "New agents now have a \"Go Live\" step in their wallet. One tap claims a real, one-time on-chain welcome grant from three.ws — it funds the agent's wallet and lands it on the live Money Pulse as an active wallet, in a single explorer-verifiable transaction. No more agents stuck at a zero balance with no way to make their first move. The Go Live screen shows the grant, the confirmed transaction, and what to do next, all in the platform's monochrome look.",
- "tags": ["feature"],
+ "tags": [
+ "feature"
+ ],
"link": "/pulse"
},
{
"date": "2026-06-27",
"title": "x402 payments dashboards refined to the monochrome system",
"summary": "The x402 Checkout dashboard and Merchant Console now use the platform's monochrome design language end to end — the off-system blue accent is gone, replaced by clean white-on-black with crisp focus rings, toggles, and hover states. New checkout storefronts default to a neutral monochrome look while merchants can still pick any brand color. Verified rendering across the payments page, dashboard, and console.",
- "tags": ["improvement"],
+ "tags": [
+ "improvement"
+ ],
"link": "/dashboard/x402"
},
{
"date": "2026-06-27",
"title": "Live agent screens restored and refreshed in monochrome",
"summary": "Watching agents work — their live screens, avatar cam, and activity feed — is back. A missing rate-limit binding had been crashing the endpoints behind the scenes, so the roster on /agents-live never populated, agents couldn't broadcast frames, and tasks wouldn't queue; all three paths now respond correctly. The Live Agents grid and the single-agent screen viewer were also rebuilt in a crisp monochrome palette, and the watch grid now pauses its streams when the tab is in the background so it stays light on bandwidth.",
- "tags": ["fix", "improvement"],
+ "tags": [
+ "fix",
+ "improvement"
+ ],
"link": "/agents-live"
},
{
"date": "2026-06-27",
"title": "Restored token-launch, agent payments, and on-chain endpoints",
"summary": "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.",
- "tags": ["fix"]
+ "tags": [
+ "fix"
+ ]
},
{
"date": "2026-06-27",
"title": "Wallet sign-in fixed and a cleaner, monochrome login",
"summary": "Restored Ethereum (SIWE) and Solana (SIWS) wallet sign-in and the active-sessions controls, which had been unreachable due to missing API route mappings. Also refined the sign-in and sign-up screens to a crisp monochrome palette — neutral chain icons, calmer focus and hover states — for a faster, more focused first impression.",
- "tags": ["fix", "improvement"]
+ "tags": [
+ "fix",
+ "improvement"
+ ]
},
{
"date": "2026-06-27",
"title": "Money Pulse now shows whether agent trading is viable",
"summary": "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.",
- "tags": ["feature", "improvement"],
+ "tags": [
+ "feature",
+ "improvement"
+ ],
"link": "/pulse"
},
{
"date": "2026-06-27",
"title": "Money Pulse now tracks real marketplace demand",
"summary": "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.",
- "tags": ["feature", "improvement"],
+ "tags": [
+ "feature",
+ "improvement"
+ ],
"link": "/pulse"
},
{
"date": "2026-06-27",
"title": "Fixed /play getting stuck on \"too many requests\"",
"summary": "Opening /play could dead-end on a \"Something went wrong — too many requests\" screen, especially from a shared network or after a couple of reloads. The wallet sign-in step was sharing the same strict rate limit as login and trading, so a small burst of page loads exhausted it. Sign-in now has its own generous limit sized for a busy world, and if that check ever can't be reached, /play opens anyway instead of blocking — the game server still verifies token-gated worlds on entry.",
- "tags": ["fix"],
+ "tags": [
+ "fix"
+ ],
"link": "/play"
},
{
"date": "2026-06-27",
"title": "The launcher now reads Know Your Meme",
"summary": "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.",
- "tags": ["feature", "improvement"]
+ "tags": [
+ "feature",
+ "improvement"
+ ]
},
{
"date": "2026-06-27",
"title": "Money Pulse redesign — monochrome, with far more live data",
"summary": "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.",
- "tags": ["improvement", "feature"],
+ "tags": [
+ "improvement",
+ "feature"
+ ],
"link": "/pulse"
},
{
"date": "2026-06-27",
"title": "Hardened Redis credentials against dashboard paste errors",
"summary": "A trailing newline or stray space on the Upstash Redis token — the kind that creeps in when pasting into a dashboard — was being sent verbatim in the auth header and rejected as WRONGPASS, while the URL still resolved. The result was thousands of failures an hour: paid endpoints denying, the payments feed not loading, usage telemetry and caches going dark. Redis credentials are now trimmed at the source (matching how wallet addresses, RPC URLs, and certificates are already sanitized), so a single stray character can never silently take the limiter, feed, and caches offline.",
- "tags": ["fix", "infra"]
+ "tags": [
+ "fix",
+ "infra"
+ ]
},
{
"date": "2026-06-27",
"title": "Sign-in restored during rate-limiter outages",
"summary": "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.",
- "tags": ["fix", "security"]
+ "tags": [
+ "fix",
+ "security"
+ ]
},
{
"date": "2026-06-27",
"title": "Production stability fixes — payment sessions, Redis error handling, infra resilience",
"summary": "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.",
- "tags": ["fix", "infra"]
+ "tags": [
+ "fix",
+ "infra"
+ ]
},
{
"date": "2026-06-27",
"title": "60 live x402 payments per minute",
"summary": "A new per-minute cron fires 60 parallel real Solana USDC micropayments each tick via the x402 protocol, seeding the platform's payment activity feed and club stage with continuous on-chain traffic. Each payment is a signed SPL TransferChecked transaction broadcast via the Solana facilitator — not simulated. Configure the batch size or pause it with X402_SEED_BATCH_SIZE / X402_SEED_ENABLED.",
- "tags": ["infra", "feature"],
+ "tags": [
+ "infra",
+ "feature"
+ ],
"link": "/pay"
},
{
diff --git a/public/changelog.json b/public/changelog.json
index 33ebfd4fe..4fa645f3e 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-27T23:09:27.459Z",
+ "generated_at": "2026-06-27T23:16:44.088Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -86,6 +86,17 @@
"launch"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "$THREE Signal Feed — the platform pays its own oracle to keep a live $THREE price on hand",
+ "summary": "three.ws now keeps a continuously fresh read on $THREE. Every 15 minutes an autonomous agent makes a real on-chain x402 payment to the platform's own $THREE Town Oracle and records the result — price, 24h change, market cap, liquidity, 24h volume, and a bullish/bearish/neutral signal — into a time-series history. That history powers a new public, no-cost feed at /api/three-signal that returns the latest snapshot plus a short sparkline, so any $THREE price widget can render a live, recently-paid-for price without charging the viewer per glance. The same latest price also lets the platform quote endpoint fees in $THREE terms. Failed or incomplete fetches are never stored, the feed flags when its newest point is stale, and every paid call is logged with its real Solana transaction signature.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -119,6 +130,16 @@
"sdk"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Agent Wallet Balance Monitor — the autonomous payment engine watches its own fuel gauge",
+ "summary": "The wallet that funds every autonomous x402 payment now monitors itself. Every 10 minutes the platform reads the agent wallet's live USDC and SOL balance, records a time-series sample, and works out the burn rate since the last reading so operators can see exactly how fast funds are being spent. The moment USDC drops below the $5 top-up line it raises a low-balance alert that folds straight into the internal health dashboard — so the wallet gets refilled before autonomous calls start failing on insufficient funds, instead of after. The check reads a free endpoint, so the monitoring itself costs nothing.",
+ "link": null,
+ "tags": [
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -129,6 +150,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Autonomous agent reputation refresh — trust scores that keep themselves current",
+ "summary": "The platform now refreshes the on-chain reputation of registered Solana agents on its own. A scheduled pipeline pays the agent-reputation service per agent over x402, recomputes each agent's verified feedback score, dispute rate and validation record from on-chain attestations, and flags any agent whose verified trust score drops below threshold. These scores power the agent reputation leaderboard and the trust badges on agent profiles, so you can vet a counterparty before paying it, trading with it, or composing skills with it — and a score that slips is caught automatically rather than going stale.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -214,6 +245,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "GLB Size Optimizer — heavy avatars audited and slimmed down automatically",
+ "summary": "Big 3D avatars are the slowest thing to load on three.ws, so the platform now hunts them down on its own. Every six hours an autonomous agent finds the heaviest public avatar over the 5 MB web-delivery budget that hasn't been checked recently and pays a real x402 call to the optimize_model service to inspect it. From the model's actual measured geometry and textures it works out exactly how much smaller the file could be — Draco geometry compression, 4K textures resized to 2K, PNG textures transcoded to KTX2 — and projects the resulting download-time improvement at typical mobile bandwidth. Each result is stored with the original size, the projected optimized size, and the load-time saving, then swept across the whole catalog so the gallery can show a 'save ~N%' hint per model and the platform can track its average load-time improvement. The new public report at /api/x402/glb-optimization-report surfaces the catalog-wide savings and the remaining backlog of heavy models.",
+ "link": null,
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -236,6 +278,17 @@
"infra"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "IBM Granite Inference Health Check — the watsonx AI backend pays to test itself",
+ "summary": "three.ws hosts an IBM Granite AI service over the x402 protocol — five paid tools (chat, code, embeddings, document analysis, and time-series forecasting) running on IBM watsonx.ai, payable per call in USDC with no IBM Cloud account. Now the platform continuously proves that backend is actually working. Every six hours an autonomous agent makes one real on-chain x402 payment that exercises all five Granite tools at once with tiny canary inputs, checks that each one answered in its expected shape, and tracks how many tokens flowed through. The verdict — which tools are healthy, whether watsonx is responding, and the token throughput — is recorded over time and exposed at a new public, no-cost feed at /api/x402/granite-health, so a model outage or a broken tool is caught within hours instead of when a paying agent hits it. Every probe settles on Solana with a real transaction signature and is logged like every other autonomous payment; a single batched call keeps the cost to roughly a few cents a day.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -292,6 +345,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Live Payment Feed Seeder — the homepage activity feed always shows real, recent payments",
+ "summary": "The live payment feed on the homepage proves three.ws is a working agent-to-agent payment network at a glance — but it only ever showed activity when someone happened to run a demo payment. Now the platform keeps it alive itself. Every few minutes an autonomous agent makes one real on-chain $0.001 USDC payment through the platform's own demo flow, rotating across a variety of services — avatar searches, model inspections, validations, optimizations, and capability discovery — so the feed reflects genuine, varied agent activity rather than one call repeated. Each payment is a real settlement on Solana with a real transaction signature, pushed straight onto the feed and also mirrored into a durable history so the record survives beyond the live ring. A first-time visitor now always lands on a feed that's transacting, not an empty box.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -377,6 +441,38 @@
"feature"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Payment Proof Idempotency Audit — the platform pays to prove it can't be charged twice",
+ "summary": "A core safety promise of an agent-to-agent payment network is that the same payment proof can never settle twice. three.ws now verifies that promise on itself, daily, with real money. Once a day an autonomous agent makes one real $0.001 USDC payment to a live priced endpoint, then deliberately resubmits the exact same signed payment proof a second time — and confirms the platform's idempotency store replays the original result (or rejects the duplicate) instead of charging again. The audit passes only when no second on-chain settlement occurs; a genuine double-settlement trips the platform health status and pages on-call immediately. Every audit is recorded with both submissions' outcomes and the verdict, so anyone watching platform health can see the anti-replay guard being proven, not just assumed.",
+ "link": null,
+ "tags": [
+ "security",
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Payment Revenue Reconciliation — every settlement on the books is verified on-chain daily",
+ "summary": "The platform now audits its own money trail. Once a day an autonomous agent cross-checks every payment our records claim was settled — both the platform's own outbound x402 spend and inbound agent revenue — against the actual transaction on the Solana chain. Each settlement signature is looked up on-chain and graded: confirmed, reverted, never landed, or recorded without a signature at all. Any record where the books say settled but the chain disagrees is flagged as a financial-integrity discrepancy for ops to review before it can corrupt revenue accounting. The check is read-only and runs even when the spend wallet is offline, so the books are watched continuously.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Popular avatar searches — the gallery now suggests what to look for",
+ "summary": "The public avatar gallery now surfaces popular search suggestions — the queries that actually return the most characters (human, robot, anime, warrior, dragon and more), each with a sample thumbnail. The list is kept honest by a new autonomous pipeline: every few hours the platform's x402 seed wallet pays per call to run ~20 common searches through the avatar search service, proving the whole pipeline returns ranked results with working thumbnails end-to-end, and caches each query's top hits. The gallery reads that cache to render instant suggestion chips and pre-painted results, so a first-time visitor always has a great place to start instead of an empty search box.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -462,6 +558,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Solana Agent Registration Health Check — the on-chain identity rails watch themselves",
+ "summary": "Registering an agent on Solana is one of three.ws's core promises: the platform mints the agent's on-chain Metaplex identity and enrols it in the Agent Registry, custodially, so the agent's own wallet never has to sign. Now that whole path is watched automatically. Four times a day an autonomous agent pays a real x402 canary call that resolves a known registered agent's on-chain record — both its Identity registry account and its Core identity asset — and confirms they still exist on the live chain through the platform's failover RPC pool. A healthy result resets the counter; a sustained failure escalates to an alert so registration outages are caught before the next agent tries to register and fails. Every probe is recorded with its on-chain check results and RPC latency, giving the status surface a continuous read on whether agent registration is actually working end-to-end.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -505,6 +612,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Token Intel Pre-Snipe Gate — the sniper pays for due diligence before it buys",
+ "summary": "Before the agent sniper commits SOL to a fresh launch, the platform now buys it a second opinion. An autonomous pipeline pays the platform's own $0.01 Token Oracle over x402 for the most active new mints the sniper is about to consider, turning the live due-diligence read — liquidity depth, pair age, float-to-liquidity, and 24h buy/sell flow — into a 0–100 rugpull-risk score per mint. Any mint that scores high or critical is auto-rejected at the pre-snipe gate across every entry path (new-mint, first-claim, intel-confirmed, prelaunch radar), so the trading engine never commits funds to a launch its own oracle has flagged as a likely rug. The check is fail-open and cached: a missing or stale verdict never blocks a trade, it only ever adds a safety floor.",
+ "link": "/oracle",
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -527,6 +645,17 @@
"infra"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "VRM 1.0 Compatibility Checker — the platform pays to tell you which avatars can upgrade",
+ "summary": "VRM is the open standard for 3D avatars, and the spec recently moved from 0.x to 1.0 — a breaking change in how avatars store their forward axis, facial expressions, spring-bone physics, and toon materials. three.ws now works out, on its own, which uploaded avatars are still on the old format and whether they can be upgraded. Every half hour an autonomous agent picks a VRM avatar that hasn't been checked recently and makes one real on-chain x402 payment to the platform's own model-inspection service to read its actual structure. From that it produces a per-avatar migration report: is this a VRM, which version, can it be upgraded to 1.0, and a checklist of exactly what an upgrade has to fix (axis flip, expression remap, spring-bone re-authoring, MToon material migration). Each report is stored against the avatar so the gallery can show a 'VRM 1.0 ready' badge and an upgrade prompt, and so avatar pricing can factor in spec compliance. Every check settles on Solana with a real transaction signature and is logged like every other autonomous payment; the half-hour spacing keeps the cost to well under a dollar a day.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 88698e7aa..ac8ac32f2 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -70,6 +70,14 @@
<category>launch</category>
<description>three.ws is now an Alibaba Cloud Partner, bringing Qwen foundation models and Asia-Pacific cloud infrastructure to the three.ws 3D AI agent platform.</description>
</item>
+ <item>
+ <title>$THREE Signal Feed — the platform pays its own oracle to keep a live $THREE price on hand</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:$THREE Signal Feed — the platform pays its own oracle to keep a live $THREE price on hand</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>three.ws now keeps a continuously fresh read on $THREE. Every 15 minutes an autonomous agent makes a real on-chain x402 payment to the platform's own $THREE Town Oracle and records the result — price, 24h change, market cap, liquidity, 24h volume, and a bullish/bearish/neutral signal — into a time-series history. That history powers a new public, no-cost feed at /api/three-signal that returns the latest snapshot plus a short sparkline, so any $THREE price widget can render a live, recently-paid-for price without charging the viewer per glance. The same latest price also lets the platform quote endpoint fees in $THREE terms. Failed or incomplete fetches are never stored, the feed flags when its newest point is stale, and every paid call is logged with its real Solana transaction signature.</description>
+ </item>
<item>
<title>60 live x402 payments per minute</title>
<link>https://three.ws/pay</link>
@@ -94,6 +102,14 @@
<category>feature</category>
<description>Bringing an agent to life is now front-and-center and easier for people and agents alike. Right after you create an agent, &quot;Go live&quot; is the first thing offered. Agents that have claimed their welcome grant now wear a &quot;◉ Live&quot; 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.</description>
</item>
+ <item>
+ <title>Agent Wallet Balance Monitor — the autonomous payment engine watches its own fuel gauge</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Agent Wallet Balance Monitor — the autonomous payment engine watches its own fuel gauge</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>infra</category>
+ <description>The wallet that funds every autonomous x402 payment now monitors itself. Every 10 minutes the platform reads the agent wallet's live USDC and SOL balance, records a time-series sample, and works out the burn rate since the last reading so operators can see exactly how fast funds are being spent. The moment USDC drops below the $5 top-up line it raises a low-balance alert that folds straight into the internal health dashboard — so the wallet gets refilled before autonomous calls start failing on insufficient funds, instead of after. The check reads a free endpoint, so the monitoring itself costs nothing.</description>
+ </item>
<item>
<title>Alibaba Cloud partnership — Qwen models and alibaba-cloud-mcp</title>
<link>https://three.ws/blog/three-ws-alibaba-cloud-partnership</link>
@@ -102,6 +118,14 @@
<category>feature</category>
<description>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.</description>
</item>
+ <item>
+ <title>Autonomous agent reputation refresh — trust scores that keep themselves current</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Autonomous agent reputation refresh — trust scores that keep themselves current</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The platform now refreshes the on-chain reputation of registered Solana agents on its own. A scheduled pipeline pays the agent-reputation service per agent over x402, recomputes each agent's verified feedback score, dispute rate and validation record from on-chain attestations, and flags any agent whose verified trust score drops below threshold. These scores power the agent reputation leaderboard and the trust badges on agent profiles, so you can vet a counterparty before paying it, trading with it, or composing skills with it — and a score that slips is caught automatically rather than going stale.</description>
+ </item>
<item>
<title>Autonomous coin launcher — creator fees, revenue tracking, and admin console upgrades</title>
<link>https://three.ws/admin/launcher</link>
@@ -166,6 +190,14 @@
<category>fix</category>
<description>Opening /play could dead-end on a &quot;Something went wrong — too many requests&quot; screen, especially from a shared network or after a couple of reloads. The wallet sign-in step was sharing the same strict rate limit as login and trading, so a small burst of page loads exhausted it. Sign-in now has its own generous limit sized for a busy world, and if that check ever can't be reached, /play opens anyway instead of blocking — the game server still verifies token-gated worlds on entry.</description>
</item>
+ <item>
+ <title>GLB Size Optimizer — heavy avatars audited and slimmed down automatically</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:GLB Size Optimizer — heavy avatars audited and slimmed down automatically</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Big 3D avatars are the slowest thing to load on three.ws, so the platform now hunts them down on its own. Every six hours an autonomous agent finds the heaviest public avatar over the 5 MB web-delivery budget that hasn't been checked recently and pays a real x402 call to the optimize_model service to inspect it. From the model's actual measured geometry and textures it works out exactly how much smaller the file could be — Draco geometry compression, 4K textures resized to 2K, PNG textures transcoded to KTX2 — and projects the resulting download-time improvement at typical mobile bandwidth. Each result is stored with the original size, the projected optimized size, and the load-time saving, then swept across the whole catalog so the gallery can show a 'save ~N%' hint per model and the platform can track its average load-time improvement. The new public report at /api/x402/glb-optimization-report surfaces the catalog-wide savings and the remaining backlog of heavy models.</description>
+ </item>
<item>
<title>Hardened how the platform reads its rate-limit store credentials</title>
<link>https://three.ws/status</link>
@@ -182,6 +214,14 @@
<category>fix</category>
<description>A trailing newline or stray space on the Upstash Redis token — the kind that creeps in when pasting into a dashboard — was being sent verbatim in the auth header and rejected as WRONGPASS, while the URL still resolved. The result was thousands of failures an hour: paid endpoints denying, the payments feed not loading, usage telemetry and caches going dark. Redis credentials are now trimmed at the source (matching how wallet addresses, RPC URLs, and certificates are already sanitized), so a single stray character can never silently take the limiter, feed, and caches offline.</description>
</item>
+ <item>
+ <title>IBM Granite Inference Health Check — the watsonx AI backend pays to test itself</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:IBM Granite Inference Health Check — the watsonx AI backend pays to test itself</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>three.ws hosts an IBM Granite AI service over the x402 protocol — five paid tools (chat, code, embeddings, document analysis, and time-series forecasting) running on IBM watsonx.ai, payable per call in USDC with no IBM Cloud account. Now the platform continuously proves that backend is actually working. Every six hours an autonomous agent makes one real on-chain x402 payment that exercises all five Granite tools at once with tiny canary inputs, checks that each one answered in its expected shape, and tracks how many tokens flowed through. The verdict — which tools are healthy, whether watsonx is responding, and the token throughput — is recorded over time and exposed at a new public, no-cost feed at /api/x402/granite-health, so a model outage or a broken tool is caught within hours instead of when a paying agent hits it. Every probe settles on Solana with a real transaction signature and is logged like every other autonomous payment; a single batched call keeps the cost to roughly a few cents a day.</description>
+ </item>
<item>
<title>Improved resilience during database outages</title>
<link>https://three.ws/changelog</link>
@@ -222,6 +262,14 @@
<category>feature</category>
<description>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.</description>
</item>
+ <item>
+ <title>Live Payment Feed Seeder — the homepage activity feed always shows real, recent payments</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Live Payment Feed Seeder — the homepage activity feed always shows real, recent payments</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The live payment feed on the homepage proves three.ws is a working agent-to-agent payment network at a glance — but it only ever showed activity when someone happened to run a demo payment. Now the platform keeps it alive itself. Every few minutes an autonomous agent makes one real on-chain $0.001 USDC payment through the platform's own demo flow, rotating across a variety of services — avatar searches, model inspections, validations, optimizations, and capability discovery — so the feed reflects genuine, varied agent activity rather than one call repeated. Each payment is a real settlement on Solana with a real transaction signature, pushed straight onto the feed and also mirrored into a durable history so the record survives beyond the live ring. A first-time visitor now always lands on a feed that's transacting, not an empty box.</description>
+ </item>
<item>
<title>Manage your AWS Marketplace API key — new keys &amp; usage page</title>
<link>https://three.ws/billing/keys</link>
@@ -286,6 +334,30 @@
<category>feature</category>
<description>New /partners page showing all active technology partnerships — AWS, IBM, Google Cloud, Alibaba Cloud, Intel, NVIDIA, Microsoft, and Oracle — with what each powers on the platform, tier badges, and links to partner-specific pages and MCP servers.</description>
</item>
+ <item>
+ <title>Payment Proof Idempotency Audit — the platform pays to prove it can't be charged twice</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Payment Proof Idempotency Audit — the platform pays to prove it can't be charged twice</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>A core safety promise of an agent-to-agent payment network is that the same payment proof can never settle twice. three.ws now verifies that promise on itself, daily, with real money. Once a day an autonomous agent makes one real $0.001 USDC payment to a live priced endpoint, then deliberately resubmits the exact same signed payment proof a second time — and confirms the platform's idempotency store replays the original result (or rejects the duplicate) instead of charging again. The audit passes only when no second on-chain settlement occurs; a genuine double-settlement trips the platform health status and pages on-call immediately. Every audit is recorded with both submissions' outcomes and the verdict, so anyone watching platform health can see the anti-replay guard being proven, not just assumed.</description>
+ </item>
+ <item>
+ <title>Payment Revenue Reconciliation — every settlement on the books is verified on-chain daily</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Payment Revenue Reconciliation — every settlement on the books is verified on-chain daily</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The platform now audits its own money trail. Once a day an autonomous agent cross-checks every payment our records claim was settled — both the platform's own outbound x402 spend and inbound agent revenue — against the actual transaction on the Solana chain. Each settlement signature is looked up on-chain and graded: confirmed, reverted, never landed, or recorded without a signature at all. Any record where the books say settled but the chain disagrees is flagged as a financial-integrity discrepancy for ops to review before it can corrupt revenue accounting. The check is read-only and runs even when the spend wallet is offline, so the books are watched continuously.</description>
+ </item>
+ <item>
+ <title>Popular avatar searches — the gallery now suggests what to look for</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Popular avatar searches — the gallery now suggests what to look for</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The public avatar gallery now surfaces popular search suggestions — the queries that actually return the most characters (human, robot, anime, warrior, dragon and more), each with a sample thumbnail. The list is kept honest by a new autonomous pipeline: every few hours the platform's x402 seed wallet pays per call to run ~20 common searches through the avatar search service, proving the whole pipeline returns ranked results with working thumbnails end-to-end, and caches each query's top hits. The gallery reads that cache to render instant suggestion chips and pre-painted results, so a first-time visitor always has a great place to start instead of an empty search box.</description>
+ </item>
<item>
<title>Production stability fixes — genome lineage, screen streaming, and x402 seeder</title>
<link>https://three.ws/changelog</link>
@@ -350,6 +422,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>Solana Agent Registration Health Check — the on-chain identity rails watch themselves</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Solana Agent Registration Health Check — the on-chain identity rails watch themselves</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Registering an agent on Solana is one of three.ws's core promises: the platform mints the agent's on-chain Metaplex identity and enrols it in the Agent Registry, custodially, so the agent's own wallet never has to sign. Now that whole path is watched automatically. Four times a day an autonomous agent pays a real x402 canary call that resolves a known registered agent's on-chain record — both its Identity registry account and its Core identity asset — and confirms they still exist on the live chain through the platform's failover RPC pool. A healthy result resets the counter; a sustained failure escalates to an alert so registration outages are caught before the next agent tries to register and fails. Every probe is recorded with its on-chain check results and RPC latency, giving the status surface a continuous read on whether agent registration is actually working end-to-end.</description>
+ </item>
<item>
<title>SSE Streaming MCP Health — continuous proof the paid MCP transport delivers cleanly</title>
<link>https://three.ws/changelog</link>
@@ -382,6 +462,14 @@
<category>feature</category>
<description>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.</description>
</item>
+ <item>
+ <title>Token Intel Pre-Snipe Gate — the sniper pays for due diligence before it buys</title>
+ <link>https://three.ws/oracle</link>
+ <guid isPermaLink="false">2026-06-27:Token Intel Pre-Snipe Gate — the sniper pays for due diligence before it buys</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Before the agent sniper commits SOL to a fresh launch, the platform now buys it a second opinion. An autonomous pipeline pays the platform's own $0.01 Token Oracle over x402 for the most active new mints the sniper is about to consider, turning the live due-diligence read — liquidity depth, pair age, float-to-liquidity, and 24h buy/sell flow — into a 0–100 rugpull-risk score per mint. Any mint that scores high or critical is auto-rejected at the pre-snipe gate across every entry path (new-mint, first-claim, intel-confirmed, prelaunch radar), so the trading engine never commits funds to a launch its own oracle has flagged as a likely rug. The check is fail-open and cached: a missing or stale verdict never blocks a trade, it only ever adds a safety floor.</description>
+ </item>
<item>
<title>Top Performers podium on marketplace — oracle-ranked agent leaderboard</title>
<link>https://three.ws/marketplace</link>
@@ -398,6 +486,14 @@
<category>feature</category>
<description>The platform now drives its own agent-to-agent payment volume. Every 5 minutes an autonomous agent round-robins through the full catalog of paid x402 endpoints — dance tips, crypto and token intel, fact-checks, symbol lookups, reputation, club covers and more — and settles a real $0.001–$0.01 USDC payment to the next batch, on a capped daily budget. Each call simultaneously proves the endpoint is live and grows genuine on-chain transaction volume, the metric agent marketplaces rank payment facilitators on. A per-endpoint volume ledger (x402_volume_metrics) tracks total settled calls, USDC spent, success rate and last-seen status for every endpoint, and every individual call is recorded for full auditability. Spend is bounded by both the loop's daily cap and a self-imposed per-run cap, and the loop degrades cleanly when the wallet isn't configured.</description>
</item>
+ <item>
+ <title>VRM 1.0 Compatibility Checker — the platform pays to tell you which avatars can upgrade</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:VRM 1.0 Compatibility Checker — the platform pays to tell you which avatars can upgrade</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>VRM is the open standard for 3D avatars, and the spec recently moved from 0.x to 1.0 — a breaking change in how avatars store their forward axis, facial expressions, spring-bone physics, and toon materials. three.ws now works out, on its own, which uploaded avatars are still on the old format and whether they can be upgraded. Every half hour an autonomous agent picks a VRM avatar that hasn't been checked recently and makes one real on-chain x402 payment to the platform's own model-inspection service to read its actual structure. From that it produces a per-avatar migration report: is this a VRM, which version, can it be upgraded to 1.0, and a checklist of exactly what an upgrade has to fix (axis flip, expression remap, spring-bone re-authoring, MToon material migration). Each report is stored against the avatar so the gallery can show a 'VRM 1.0 ready' badge and an upgrade prompt, and so avatar pricing can factor in spec compliance. Every check settles on Solana with a real transaction signature and is logged like every other autonomous payment; the half-hour spacing keeps the cost to well under a dollar a day.</description>
+ </item>
<item>
<title>Walk-Browse the Marketplace is now monochrome and agent-readable</title>
<link>https://three.ws/marketplace-walk</link>
diff --git a/public/features.json b/public/features.json
index 421e38238..534e8f4cd 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-27T23:09:27.441Z",
+ "generated_at": "2026-06-27T23:16:43.955Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/test-wallet-balance-monitor.mjs b/scripts/test-wallet-balance-monitor.mjs
new file mode 100644
index 000000000..7cb374f18
--- /dev/null
+++ b/scripts/test-wallet-balance-monitor.mjs
@@ -0,0 +1,177 @@
+// Manual test for the Agent Wallet Balance Monitor autonomous pipeline.
+//
+// Exercises run() end-to-end against a REAL local HTTP stub of the free
+// GET /api/x402-pay?balance=1 endpoint (the actual call the pipeline makes —
+// no payment is involved, so nothing is mocked that wouldn't be free in prod)
+// and a captured-SQL stub standing in for Postgres. Verifies the time-series
+// row, the low-balance alert flag, the derived spend rate, the Redis state
+// writes, and every error path (non-200, network failure, unconfigured wallet).
+//
+// node scripts/test-wallet-balance-monitor.mjs
+//
+// With DATABASE_URL set it additionally inserts a real row into
+// agent_wallet_balance_log and reads it back.
+
+import { createServer } from 'node:http';
+import { randomUUID } from 'node:crypto';
+
+import { run, WALLET_BALANCE } from '../api/_lib/x402/wallet-balance-monitor.js';
+
+let failures = 0;
+function check(label, cond, detail) {
+ const ok = !!cond;
+ if (!ok) failures++;
+ console.log(`${ok ? ' ✓' : ' ✗'} ${label}${detail ? ` — ${detail}` : ''}`);
+}
+
+// Capture every SQL statement; answer previousSample's SELECT from `prevRow`.
+function makeSqlStub({ prevRow = null } = {}) {
+ const captured = [];
+ const sql = (strings, ...vals) => {
+ const text = strings.join('?').replace(/\s+/g, ' ').trim();
+ captured.push({ text, vals });
+ if (/^SELECT usdc/i.test(text)) return Promise.resolve(prevRow ? [prevRow] : []);
+ return Promise.resolve([]);
+ };
+ return { sql, captured };
+}
+
+function makeRedisStub() {
+ const store = new Map();
+ const ops = [];
+ return {
+ store, ops,
+ set: async (k, v) => { ops.push(['set', k]); store.set(k, v); },
+ del: async (k) => { ops.push(['del', k]); store.delete(k); },
+ };
+}
+
+// Spin up a one-route stub of /api/x402-pay?balance=1 returning `payload`
+// (or a chosen status). Returns { origin, close }.
+async function stubBalanceServer({ payload, status = 200 }) {
+ const server = createServer((req, res) => {
+ res.statusCode = status;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify(payload));
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ return { origin: `http://127.0.0.1:${port}`, close: () => new Promise((r) => server.close(r)) };
+}
+
+async function main() {
+ console.log('\n1. Constants');
+ check('endpoint', WALLET_BALANCE.endpoint === '/api/x402-pay?balance=1');
+ check('default threshold $5', WALLET_BALANCE.alertThresholdUsdc === 5, String(WALLET_BALANCE.alertThresholdUsdc));
+
+ console.log('\n2. Healthy wallet → row stored, no alert');
+ {
+ const srv = await stubBalanceServer({ payload: { configured: true, address: 'Wallet111', sol: 0.5, usdc: 42.5 } });
+ const { sql, captured } = makeSqlStub();
+ const redis = makeRedisStub();
+ const out = await run({ origin: srv.origin, sql, redis, runId: randomUUID() });
+ await srv.close();
+ check('success true', out.success === true);
+ check('amountAtomic 0 (free read)', out.amountAtomic === 0);
+ check('signal usdc', out.signalData.usdc === 42.5);
+ check('signal not low', out.signalData.low_balance === false);
+ const insert = captured.find((c) => /INSERT INTO agent_wallet_balance_log/i.test(c.text));
+ check('issued CREATE TABLE', captured.some((c) => /CREATE TABLE IF NOT EXISTS agent_wallet_balance_log/i.test(c.text)));
+ check('issued INSERT', !!insert);
+ check('INSERT carries usdc', insert?.vals?.includes(42.5));
+ check('INSERT carries low_balance=false', insert?.vals?.includes(false));
+ check('redis latest written', redis.store.has(WALLET_BALANCE.redisLatestKey));
+ check('redis alert cleared (del)', redis.ops.some((o) => o[0] === 'del' && o[1] === WALLET_BALANCE.redisAlertKey));
+ }
+
+ console.log('\n3. Low balance → alert raised + spend rate derived');
+ {
+ const srv = await stubBalanceServer({ payload: { configured: true, address: 'Wallet111', sol: 0.01, usdc: 2.0 } });
+ // Previous sample: $7 one hour ago → spent $5 → rate ≈ $5/hr.
+ const prevRow = { usdc: 7.0, ts_epoch: Math.floor(Date.now() / 1000) - 3600 };
+ const { sql, captured } = makeSqlStub({ prevRow });
+ const redis = makeRedisStub();
+ const out = await run({ origin: srv.origin, sql, redis, runId: randomUUID() });
+ await srv.close();
+ check('success true', out.success === true);
+ check('low_balance true', out.signalData.low_balance === true);
+ check('usdc_delta ≈ -5', Math.abs(out.signalData.usdc_delta - -5) < 1e-6, String(out.signalData.usdc_delta));
+ check('spend_rate ≈ 5/hr', Math.abs(out.signalData.spend_rate_usdc_hr - 5) < 0.1, String(out.signalData.spend_rate_usdc_hr));
+ check('note flags LOW_BALANCE', /LOW_BALANCE/.test(out.note), out.note);
+ const insert = captured.find((c) => /INSERT INTO agent_wallet_balance_log/i.test(c.text));
+ check('INSERT low_balance=true', insert?.vals?.includes(true));
+ check('redis alert key set', redis.store.has(WALLET_BALANCE.redisAlertKey));
+ }
+
+ console.log('\n4. Unconfigured wallet → recorded, not success');
+ {
+ const srv = await stubBalanceServer({ payload: { configured: false, code: 'wallet_unconfigured', address: null, sol: 0, usdc: 0 } });
+ const { sql, captured } = makeSqlStub();
+ const redis = makeRedisStub();
+ const out = await run({ origin: srv.origin, sql, redis, runId: randomUUID() });
+ await srv.close();
+ check('success false', out.success === false);
+ check('errorMsg wallet_unconfigured', out.errorMsg === 'wallet_unconfigured', out.errorMsg);
+ check('still recorded a row', captured.some((c) => /INSERT INTO agent_wallet_balance_log/i.test(c.text)));
+ check('signal configured=false', out.signalData.configured === false);
+ }
+
+ console.log('\n5. Endpoint non-200 → graceful failure');
+ {
+ const srv = await stubBalanceServer({ payload: { error: 'boom' }, status: 500 });
+ const { sql } = makeSqlStub();
+ const out = await run({ origin: srv.origin, sql, redis: makeRedisStub() });
+ await srv.close();
+ check('success false', out.success === false);
+ check('errorMsg http status', /balance_http_500/.test(out.errorMsg || ''), out.errorMsg);
+ }
+
+ console.log('\n6. Network failure → graceful failure (no throw)');
+ {
+ const { sql } = makeSqlStub();
+ // Unroutable port — connection refused.
+ const out = await run({ origin: 'http://127.0.0.1:1', sql, redis: makeRedisStub() });
+ check('success false', out.success === false);
+ check('note fetch_failed', out.note === 'fetch_failed', out.note);
+ }
+
+ console.log('\n7. DB insert failure mid-run does not crash');
+ {
+ const srv = await stubBalanceServer({ payload: { configured: true, address: 'W', sol: 1, usdc: 10 } });
+ const sql = (strings, ...vals) => {
+ const text = strings.join('?');
+ if (/INSERT INTO agent_wallet_balance_log/i.test(text)) return Promise.reject(new Error('db down'));
+ if (/^\s*SELECT usdc/i.test(text)) return Promise.resolve([]);
+ return Promise.resolve([]);
+ };
+ const out = await run({ origin: srv.origin, sql, redis: makeRedisStub() });
+ await srv.close();
+ check('still returns success (read worked)', out.success === true);
+ check('signal usdc present', out.signalData.usdc === 10);
+ }
+
+ // Optional real DB round-trip.
+ if (process.env.DATABASE_URL || process.env.POSTGRES_URL) {
+ console.log('\n8. real DB insert + read-back');
+ const srv = await stubBalanceServer({ payload: { configured: true, address: 'WalletReal', sol: 0.2, usdc: 3.3 } });
+ const { sql } = await import('../api/_lib/db.js');
+ const runId = randomUUID();
+ const out = await run({ origin: srv.origin, sql, redis: null, runId });
+ await srv.close();
+ const rows = await sql`SELECT usdc, low_balance, run_id FROM agent_wallet_balance_log WHERE run_id = ${runId}`;
+ check('row persisted', rows.length === 1, JSON.stringify(rows[0]));
+ check('usdc stored', Number(rows[0]?.usdc) === 3.3);
+ check('low_balance true (3.3 < 5)', rows[0]?.low_balance === true);
+ check('outcome low', out.signalData.low_balance === true);
+ } 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.js
index c4bbebadb..c0ce184f4 100644
--- a/tests/api/x402-cosmetic-pricing-audit.test.js
+++ b/tests/api/x402-cosmetic-pricing-audit.test.js
@@ -51,27 +51,25 @@ 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,
+ paid: true, success: true, free: false, skipped: false,
+ amountAtomic: Number(CHEAPEST.priceUsdcAtomics),
+ txSig: 'sig_123', status: 200, responseBody: { ok: true }, errorMsg: null,
});
const payX402 = vi.fn((...a) => payX402Impl(...a));
+const bootstrapSolanaContext = vi.fn(async () => ({ buyer: {}, conn: {}, blockhash: 'bh', mintInfo: { decimals: 6 } }));
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', () => ({
+vi.mock('../../api/_lib/x402/pay.js', () => ({
loadSeedKeypair: (...a) => loadSeedKeypair(...a),
payX402: (...a) => payX402(...a),
+ bootstrapSolanaContext: (...a) => bootstrapSolanaContext(...a),
fetchWithTimeout: (...a) => fetchWithTimeout(...a),
parseSolanaAccept: (...a) => parseSolanaAccept(...a),
+ USDC_MINT: 'USDCmint',
}));
import { run } from '../../api/_lib/x402/pipelines/cosmetic-pricing-audit.js';
@@ -85,8 +83,9 @@ beforeEach(() => {
probeThrowsForId = null;
loadSeedKeypairImpl = () => ({ publicKey: { toBase58: () => 'PAYER' } });
payX402Impl = async () => ({
- status: 'paid', success: true, amountAtomic: Number(CHEAPEST.priceUsdcAtomics),
- txSig: 'sig_123', responseBody: { ok: true }, errorMsg: null,
+ paid: true, success: true, free: false, skipped: false,
+ amountAtomic: Number(CHEAPEST.priceUsdcAtomics),
+ txSig: 'sig_123', status: 200, responseBody: { ok: true }, errorMsg: null,
});
vi.clearAllMocks();
});
@@ -129,7 +128,7 @@ describe('cosmetic pricing audit pipeline', () => {
expect(payX402).toHaveBeenCalledTimes(1);
const arg = payX402.mock.calls[0][0];
expect(arg.method).toBe('GET');
- expect(arg.endpointUrl).toContain(`id=${encodeURIComponent(CHEAPEST.id)}`);
+ expect(arg.url).toContain(`id=${encodeURIComponent(CHEAPEST.id)}`);
});
it('underpricing detected: a too-low quote is flagged', async () => {
diff --git a/tests/rig-complexity-score.test.js b/tests/rig-complexity-score.test.js
new file mode 100644
index 000000000..9a0948231
--- /dev/null
+++ b/tests/rig-complexity-score.test.js
@@ -0,0 +1,66 @@
+import { describe, it, expect } from 'vitest';
+import { computeComplexity } from '../api/_lib/x402/pipelines/rig-complexity.js';
+
+// Build an inspect_model-shaped payload for the scorer.
+const info = ({ joints = 0, vertices = 0, triangles = 0, skins = 0, meshes = 1, materials = 1, fileSize = 0, textures = [] }) => ({
+ fileSize,
+ counts: { totalJoints: joints, totalVertices: vertices, totalTriangles: triangles, skins, meshes, materials },
+ textures,
+});
+
+describe('computeComplexity', () => {
+ it('scores a lean web avatar as light with no warning', () => {
+ const c = computeComplexity(info({
+ joints: 30, vertices: 20_000, triangles: 30_000, skins: 1, fileSize: 2 * 1024 * 1024,
+ textures: [{ byteSize: 1 * 1024 * 1024, width: 1024, height: 1024 }],
+ }));
+ expect(c.tier).toBe('light');
+ expect(c.perf_warning).toBe(false);
+ expect(c.bone_count).toBe(30);
+ expect(c.complexity_score).toBeLessThan(25);
+ });
+
+ it('flags a heavy avatar with a performance warning', () => {
+ const c = computeComplexity(info({
+ joints: 200, vertices: 600_000, triangles: 1_200_000, skins: 2, fileSize: 60 * 1024 * 1024,
+ textures: [{ byteSize: 30 * 1024 * 1024, width: 8192, height: 8192 }],
+ }));
+ expect(c.tier).toBe('extreme');
+ expect(c.perf_warning).toBe(true);
+ expect(c.max_texture_dim).toBe(8192);
+ expect(c.complexity_score).toBeLessThanOrEqual(100);
+ });
+
+ it('raises perf_warning on a single hard-limit breach even when the blended score is low', () => {
+ // Everything tiny except one 8K texture — the score stays low but the
+ // max-dimension hard limit must still warn (mobile GPU killer).
+ const c = computeComplexity(info({
+ joints: 10, vertices: 5_000, triangles: 8_000, skins: 1, fileSize: 1024 * 1024,
+ textures: [{ byteSize: 2 * 1024 * 1024, width: 8192, height: 8192 }],
+ }));
+ expect(c.complexity_score).toBeLessThan(50);
+ expect(c.perf_warning).toBe(true);
+ });
+
+ it('is total-safe on an empty / malformed payload', () => {
+ const c = computeComplexity({});
+ expect(c.complexity_score).toBe(0);
+ expect(c.tier).toBe('light');
+ expect(c.perf_warning).toBe(false);
+ expect(c.bone_count).toBe(0);
+ });
+
+ it('clamps the score to 0-100 and exposes a per-dimension breakdown', () => {
+ const c = computeComplexity(info({ vertices: 10_000_000, triangles: 10_000_000, fileSize: 500 * 1024 * 1024 }));
+ expect(c.complexity_score).toBeLessThanOrEqual(100);
+ expect(c.complexity_score).toBeGreaterThan(0);
+ expect(c.breakdown).toHaveProperty('vertices');
+ expect(c.breakdown).toHaveProperty('textureBytes');
+ expect(c.breakdown.vertices.ratio).toBeLessThanOrEqual(2);
+ });
+
+ it('falls back to the DB file size when inspect_model omits fileSize', () => {
+ const c = computeComplexity(info({ vertices: 1000 }), { fileBytes: 40 * 1024 * 1024 });
+ expect(c.file_bytes).toBe(40 * 1024 * 1024);
+ });
+});
diff --git a/tests/three-signal-feed-registry.test.js b/tests/three-signal-feed-registry.test.js
new file mode 100644
index 000000000..92d217be3
--- /dev/null
+++ b/tests/three-signal-feed-registry.test.js
@@ -0,0 +1,67 @@
+import { describe, it, expect } from 'vitest';
+
+import { getSelfRegistry } from '../api/_lib/x402/autonomous-registry.js';
+
+// A live three-intel response (DexScreener-backed shape).
+const SAMPLE = {
+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ symbol: 'THREE',
+ price_usd: 0.003685,
+ change_24h: 12.4,
+ market_cap_usd: 3685000,
+ liquidity_usd: 412000,
+ volume_24h_usd: 1268079,
+ signal: 'bullish',
+ headline: 'THREE climbs +12.40% — moderate upside',
+ confidence: 0.86,
+ ts: '2026-06-27T10:00:00Z',
+};
+
+function mockSql() {
+ const calls = [];
+ const fn = (strings, ...values) => {
+ calls.push({ text: strings.join('?').replace(/\s+/g, ' ').trim(), values });
+ return Promise.resolve([]);
+ };
+ fn.calls = calls;
+ return fn;
+}
+
+describe('autonomous registry — three-intel entry', () => {
+ const entry = getSelfRegistry().find((e) => e.id === 'three-intel');
+
+ it('exists, is enabled, GET, oracle pipeline, 15-min cooldown', () => {
+ expect(entry).toBeTruthy();
+ expect(entry.enabled).toBe(true);
+ expect(entry.method).toBe('GET');
+ expect(entry.pipeline).toBe('oracle');
+ expect(entry.cooldown_s).toBe(900);
+ expect(entry.path).toBe('/api/x402/three-intel');
+ });
+
+ it('extractSignal tags topic=three and carries the market shape', () => {
+ const sig = entry.extractSignal(SAMPLE);
+ expect(sig.topic).toBe('three');
+ expect(sig.price_usd).toBe(0.003685);
+ expect(sig.signal).toBe('bullish');
+ });
+
+ it('storeValue persists a valid snapshot to the time series', async () => {
+ const sql = mockSql();
+ await entry.storeValue({ sql, responseBody: SAMPLE, signalData: null, runId: 'run-2' });
+ const insert = sql.calls.find((c) => /INSERT INTO three_market_signals/i.test(c.text));
+ expect(insert).toBeTruthy();
+ expect(insert.values).toContain('run-2');
+ });
+
+ it('storeValue skips an empty/failed snapshot (no price → no row)', async () => {
+ const sql = mockSql();
+ await entry.storeValue({ sql, responseBody: { signal: 'neutral' }, signalData: null, runId: 'run-3' });
+ const insert = sql.calls.find((c) => /INSERT INTO three_market_signals/i.test(c.text));
+ expect(insert).toBeFalsy();
+ });
+
+ it('storeValue never throws when sql is missing', async () => {
+ await expect(entry.storeValue({ sql: null, responseBody: SAMPLE })).resolves.toBeUndefined();
+ });
+});
diff --git a/tests/three-signal-feed.test.js b/tests/three-signal-feed.test.js
index 4c97053fe..a86628f0a 100644
--- a/tests/three-signal-feed.test.js
+++ b/tests/three-signal-feed.test.js
@@ -7,7 +7,6 @@ import {
getThreeSignalHistory,
THREE_DECIMALS,
} from '../api/_lib/x402/three-signal-store.js';
-import { getSelfRegistry } from '../api/_lib/x402/autonomous-registry.js';
// A live three-intel response (DexScreener-backed shape).
const SAMPLE = {
@@ -107,48 +106,9 @@ describe('three-signal-store — getThreeSignalHistory', () => {
it('clamps the limit into [1, 500]', async () => {
const sql = mockSql();
await getThreeSignalHistory(sql, 9999);
- await getThreeSignalHistory(sql, 0);
+ await getThreeSignalHistory(sql, -5);
const limits = sql.calls.map((c) => c.values[c.values.length - 1]);
expect(limits).toContain(500);
expect(limits).toContain(1);
});
});
-
-describe('autonomous registry — three-intel entry', () => {
- const entry = getSelfRegistry().find((e) => e.id === 'three-intel');
-
- it('exists, is enabled, GET, oracle pipeline, 15-min cooldown', () => {
- expect(entry).toBeTruthy();
- expect(entry.enabled).toBe(true);
- expect(entry.method).toBe('GET');
- expect(entry.pipeline).toBe('oracle');
- expect(entry.cooldown_s).toBe(900);
- expect(entry.path).toBe('/api/x402/three-intel');
- });
-
- it('extractSignal tags topic=three and carries the market shape', () => {
- const sig = entry.extractSignal(SAMPLE);
- expect(sig.topic).toBe('three');
- expect(sig.price_usd).toBe(0.003685);
- expect(sig.signal).toBe('bullish');
- });
-
- it('storeValue persists a valid snapshot to the time series', async () => {
- const sql = mockSql();
- await entry.storeValue({ sql, responseBody: SAMPLE, signalData: null, runId: 'run-2' });
- const insert = sql.calls.find((c) => /INSERT INTO three_market_signals/i.test(c.text));
- expect(insert).toBeTruthy();
- expect(insert.values).toContain('run-2');
- });
-
- it('storeValue skips an empty/failed snapshot (no price → no row)', async () => {
- const sql = mockSql();
- await entry.storeValue({ sql, responseBody: { signal: 'neutral' }, signalData: null, runId: 'run-3' });
- const insert = sql.calls.find((c) => /INSERT INTO three_market_signals/i.test(c.text));
- expect(insert).toBeFalsy();
- });
-
- it('storeValue never throws when sql is missing', async () => {
- await expect(entry.storeValue({ sql: null, responseBody: SAMPLE })).resolves.toBeUndefined();
- });
-});
diff --git a/tests/x402-avatar-search-warmup.test.js b/tests/x402-avatar-search-warmup.test.js
new file mode 100644
index 000000000..eb9a99023
--- /dev/null
+++ b/tests/x402-avatar-search-warmup.test.js
@@ -0,0 +1,84 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ WARMUP_QUERIES,
+ extractWarmValue,
+ run,
+} from '../api/_lib/x402/pipelines/avatar-search-warmup.js';
+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';
+
+const avatar = (over = {}) => ({
+ id: '11111111-1111-1111-1111-111111111111',
+ name: 'Robo',
+ slug: 'robo',
+ thumbnail_url: 'https://cdn.three.ws/t/robo.png',
+ ...over,
+});
+
+describe('avatar search warmup — query set', () => {
+ it('warms exactly 20 distinct queries', () => {
+ expect(WARMUP_QUERIES).toHaveLength(20);
+ expect(new Set(WARMUP_QUERIES).size).toBe(20); // no duplicates
+ });
+});
+
+describe('avatar search warmup — MCP response parsing', () => {
+ it('extracts the ranked slice and thumbnails from structuredContent', () => {
+ const body = {
+ result: {
+ structuredContent: {
+ avatars: [avatar(), avatar({ id: '2', slug: 'r2', thumbnail_url: null }), avatar({ id: '3', slug: 'r3' })],
+ },
+ },
+ };
+ const out = extractWarmValue(body);
+ expect(out.hasResult).toBe(true);
+ expect(out.resultCount).toBe(3);
+ expect(out.topResults).toHaveLength(3);
+ // Only non-null thumbnails are surfaced (validates the pipeline resolved imagery).
+ expect(out.thumbnails).toEqual([
+ 'https://cdn.three.ws/t/robo.png',
+ 'https://cdn.three.ws/t/robo.png',
+ ]);
+ expect(out.topResults[0]).toMatchObject({ id: avatar().id, name: 'Robo', slug: 'robo' });
+ });
+
+ it('caps the stored slice at 8 results even when more are returned', () => {
+ const avatars = Array.from({ length: 12 }, (_, i) => avatar({ id: String(i), slug: `a${i}` }));
+ const out = extractWarmValue({ result: { structuredContent: { avatars } } });
+ expect(out.resultCount).toBe(12);
+ expect(out.topResults).toHaveLength(8);
+ });
+
+ it('returns hasResult=false (not throw) on a malformed/error body', () => {
+ expect(extractWarmValue(null).hasResult).toBe(false);
+ expect(extractWarmValue({ error: { code: -32000 } }).hasResult).toBe(false);
+ expect(extractWarmValue({ result: {} }).hasResult).toBe(false);
+ expect(extractWarmValue({ result: { structuredContent: { avatars: [] } } })).toMatchObject({
+ hasResult: true,
+ resultCount: 0,
+ thumbnails: [],
+ });
+ });
+});
+
+describe('avatar search warmup — registry wiring', () => {
+ it('is registered as an enabled, 6-hourly, run()-style discovery entry on /api/mcp', () => {
+ const entry = getFullRegistry().find((e) => e.id === 'avatar-search-index-warmup');
+ expect(entry).toBeTruthy();
+ expect(entry.enabled).toBe(true);
+ expect(entry.pipeline).toBe('discovery');
+ expect(entry.cooldown_s).toBe(21600);
+ expect(typeof entry.run).toBe('function');
+ expect(entry.path).toBe('/api/mcp');
+ });
+});
+
+describe('avatar search warmup — graceful degradation', () => {
+ it('never throws when the DB/wallet are unconfigured; returns a skipped outcome', async () => {
+ const out = await run({ runId: '00000000-0000-0000-0000-000000000003' });
+ expect(out).toMatchObject({ success: false, skipped: true });
+ expect(out.amountAtomic).toBe(0);
+ expect(typeof out.errorMsg).toBe('string');
+ });
+});
diff --git a/tests/x402-circuit-breaker.test.js b/tests/x402-circuit-breaker.test.js
new file mode 100644
index 000000000..16c744fb6
--- /dev/null
+++ b/tests/x402-circuit-breaker.test.js
@@ -0,0 +1,151 @@
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
+import http from 'node:http';
+import { Keypair } from '@solana/web3.js';
+
+// The payTo / feePayer keys and the USDC mint must be valid base58 pubkeys
+// because runCircuitBreaker settles a REAL Solana transfer locally via payX402
+// (build + sign). Nothing is broadcast — the mock server below never touches a
+// chain — so this is a true integration test of the probe → cross-network
+// verify → pay → settle → store path with no on-chain spend.
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+process.env.X402_ASSET_MINT_SOLANA = USDC;
+
+const { runCircuitBreaker } = await import('../api/_lib/x402/pipelines/circuit-breaker.js');
+
+const payToSol = Keypair.generate().publicKey.toBase58();
+const feePayer = Keypair.generate().publicKey.toBase58();
+const AMOUNT = '1000'; // $0.001 USDC atomics
+
+function solanaAccept() {
+ return { scheme: 'exact', network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', asset: USDC, payTo: payToSol, amount: AMOUNT, extra: { name: 'USDC', decimals: 6, feePayer } };
+}
+function baseAccept() {
+ return { scheme: 'exact', network: 'eip155:8453', asset: '0xUSDCbase', payTo: '0x1111111111111111111111111111111111111111', amount: AMOUNT, extra: { name: 'USD Coin', version: '2', decimals: 6 } };
+}
+function bscAccept() {
+ return { scheme: 'direct', network: 'eip155:56', asset: '0xUSDCbsc', payTo: '0x2222222222222222222222222222222222222222', amount: AMOUNT, extra: { name: 'Binance-Peg USD Coin', decimals: 6, contract: '0x2222222222222222222222222222222222222222', method: 'pay(bytes32)' } };
+}
+
+// `accepts` controls which network routes the mock 402 challenge advertises.
+let accepts = [];
+let server;
+let origin;
+
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ const paid = !!req.headers['x-payment'];
+ if (!paid) {
+ // x402 challenge — advertise the configured network routes.
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ x402Version: 2, error: 'payment required', resource: `http://127.0.0.1/api/x402/dance-tip`, accepts }));
+ return;
+ }
+ // Paid + accepted: settle (advertise the tx sig) and return the ticket.
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json');
+ res.setHeader('x-payment-response', Buffer.from(JSON.stringify({ success: true, transaction: 'CBTESTSIG_xyz' })).toString('base64'));
+ res.end(JSON.stringify({ ok: true, ticketId: 'tkt_cb', dancer: '4', dance: 'hiphop' }));
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ origin = `http://127.0.0.1:${port}`;
+});
+
+afterAll(() => new Promise((resolve) => server.close(resolve)));
+
+beforeEach(() => { accepts = [solanaAccept(), baseAccept(), bscAccept()]; });
+
+function makeSqlStub() {
+ const calls = [];
+ const sql = (strings, ...values) => {
+ calls.push({ text: strings.join('?'), values });
+ return Promise.resolve([]);
+ };
+ return { sql, calls };
+}
+
+function baseCtx(sqlStub) {
+ return {
+ origin,
+ buyer: Keypair.generate(),
+ conn: { getAccountInfo: async () => null }, // receiver ATA missing → create ix
+ blockhash: '11111111111111111111111111111111',
+ mintInfo: { decimals: 6 },
+ remainingCap: 5_000_000,
+ sql: sqlStub.sql,
+ log: { info() {}, warn() {} },
+ runId: '00000000-0000-0000-0000-000000000000',
+ };
+}
+
+describe('runCircuitBreaker', () => {
+ it('verifies all three routes, settles Solana, and upserts per-network status', async () => {
+ const sqlStub = makeSqlStub();
+ const out = await runCircuitBreaker(baseCtx(sqlStub));
+
+ expect(out.success).toBe(true);
+ expect(out.errorMsg).toBeNull();
+ expect(out.amountAtomic).toBe(Number(AMOUNT));
+ expect(out.txSig).toBe('CBTESTSIG_xyz');
+ expect(out.signalData.tripped).toBe(false);
+ expect(out.signalData.all_routes_ok).toBe(true);
+ expect(out.signalData.routes_ok).toBe(3);
+ expect(out.signalData.solana_settled).toBe(true);
+
+ // One x402_circuit_breaker upsert per network (downstream: ops/health).
+ const upserts = sqlStub.calls.filter((c) => /insert into\s+x402_circuit_breaker/i.test(c.text));
+ expect(upserts.length).toBe(3);
+ // The Solana row carries the settlement signature.
+ expect(sqlStub.calls.some((c) => c.values.includes('CBTESTSIG_xyz'))).toBe(true);
+ });
+
+ it('trips when a network route is not advertised (BSC missing)', async () => {
+ accepts = [solanaAccept(), baseAccept()]; // no BSC
+ const sqlStub = makeSqlStub();
+ const out = await runCircuitBreaker(baseCtx(sqlStub));
+
+ expect(out.success).toBe(false);
+ expect(out.signalData.tripped).toBe(true);
+ expect(out.signalData.routes_ok).toBe(2);
+ expect(out.signalData.solana_settled).toBe(true); // Solana still settled
+ expect(out.errorMsg).toMatch(/breaker_tripped/);
+ // Still records all three networks so the dashboard shows BSC as down.
+ expect(sqlStub.calls.filter((c) => /insert into\s+x402_circuit_breaker/i.test(c.text)).length).toBe(3);
+ });
+
+ it('trips when a route is malformed (Solana accept missing feePayer)', async () => {
+ const bad = solanaAccept(); delete bad.extra.feePayer;
+ accepts = [bad, baseAccept(), bscAccept()];
+ const sqlStub = makeSqlStub();
+ const out = await runCircuitBreaker(baseCtx(sqlStub));
+
+ expect(out.success).toBe(false);
+ expect(out.signalData.tripped).toBe(true);
+ // Malformed Solana route is not route_ok → not settled.
+ expect(out.signalData.solana_settled).toBe(false);
+ const sol = out.signalData.networks.find((n) => /solana/.test(n.network));
+ expect(sol.route_ok).toBe(false);
+ });
+
+ it('records a trip across all networks when the probe never returns 402', async () => {
+ accepts = []; // server still 402s, but with no routes → all routes fail
+ const sqlStub = makeSqlStub();
+ const out = await runCircuitBreaker(baseCtx(sqlStub));
+
+ expect(out.success).toBe(false);
+ expect(out.signalData.routes_ok).toBe(0);
+ expect(out.signalData.solana_settled).toBe(false);
+ });
+
+ it('exits gracefully (no throw) when the wallet is unconfigured', async () => {
+ const sqlStub = makeSqlStub();
+ const ctx = baseCtx(sqlStub);
+ ctx.buyer = null;
+ const out = await runCircuitBreaker(ctx);
+
+ expect(out.success).toBe(false);
+ expect(out.errorMsg).toBe('wallet_unconfigured');
+ expect(out.amountAtomic).toBe(0);
+ });
+});
diff --git a/tests/x402-glb-size-optimizer.test.js b/tests/x402-glb-size-optimizer.test.js
new file mode 100644
index 000000000..8abbe52b5
--- /dev/null
+++ b/tests/x402-glb-size-optimizer.test.js
@@ -0,0 +1,82 @@
+/**
+ * Tests for the GLB Size Optimizer autonomous pipeline (self/018).
+ *
+ * Two contracts are pinned here:
+ * 1. projectOptimization() turns a model's *measured* stats into a grounded
+ * size + load-time projection — never NaN, never larger than the original,
+ * and zero-ish when the model is already compressed.
+ * 2. The registry entry is wired correctly (enabled, self pipeline, 6h
+ * cooldown, run() present) so the autonomous loop will actually call it.
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import { projectOptimization } from '../api/_lib/x402/glb-size-optimizer.js';
+import { getSelfRegistry } from '../api/_lib/x402/autonomous-registry.js';
+
+describe('GLB Size Optimizer — projectOptimization', () => {
+ it('projects a large win for a heavy, uncompressed model with 4K PNG textures', () => {
+ const info = {
+ fileSize: 12 * 1024 * 1024,
+ counts: { totalVertices: 180_000, totalTriangles: 340_000, meshes: 4, materials: 3, textures: 2 },
+ textures: [
+ { width: 4096, height: 4096, mimeType: 'image/png', byteSize: 5_000_000 },
+ { width: 4096, height: 4096, mimeType: 'image/png', byteSize: 4_000_000 },
+ ],
+ extensionsUsed: [],
+ };
+ const p = projectOptimization(info, info.fileSize);
+ expect(p.estimatedOptimizedBytes).toBeLessThan(p.fileSize);
+ expect(p.estimatedSavingsBytes).toBe(p.fileSize - p.estimatedOptimizedBytes);
+ expect(p.savingsPct).toBeGreaterThan(50);
+ // Load-time delta tracks the byte delta exactly (same reference bandwidth).
+ expect(p.loadAfterMs).toBeLessThan(p.loadBeforeMs);
+ expect(p.alreadyCompressed).toBe(false);
+ });
+
+ it('projects near-zero savings for an already-Draco model with small textures', () => {
+ const info = {
+ fileSize: 6 * 1024 * 1024,
+ counts: { totalVertices: 90_000, totalTriangles: 150_000, meshes: 2, materials: 2, textures: 1 },
+ textures: [{ width: 1024, height: 1024, mimeType: 'image/jpeg', byteSize: 400_000 }],
+ extensionsUsed: ['KHR_draco_mesh_compression'],
+ };
+ const p = projectOptimization(info, info.fileSize);
+ expect(p.alreadyCompressed).toBe(true);
+ expect(p.savingsPct).toBeLessThan(10);
+ expect(p.estimatedOptimizedBytes).toBeLessThanOrEqual(p.fileSize);
+ });
+
+ it('never returns NaN or exceeds the original size on empty/degenerate input', () => {
+ const p = projectOptimization({ fileSize: 0, counts: {}, textures: [], extensionsUsed: [] }, 0);
+ expect(Number.isNaN(p.savingsPct)).toBe(false);
+ expect(p.estimatedSavingsBytes).toBe(0);
+ expect(p.estimatedOptimizedBytes).toBe(0);
+ expect(p.loadBeforeMs).toBe(0);
+ });
+
+ it('never projects an optimized size below the 10% sanity floor', () => {
+ const info = {
+ fileSize: 20 * 1024 * 1024,
+ counts: { totalVertices: 2_000_000, totalTriangles: 4_000_000, meshes: 1, materials: 1, textures: 1 },
+ textures: [{ width: 8192, height: 8192, mimeType: 'image/png', byteSize: 18_000_000 }],
+ extensionsUsed: [],
+ };
+ const p = projectOptimization(info, info.fileSize);
+ expect(p.estimatedOptimizedBytes).toBeGreaterThanOrEqual(Math.round(p.fileSize * 0.10));
+ });
+});
+
+describe('autonomous registry — glb-size-optimizer entry', () => {
+ const entry = getSelfRegistry().find((e) => e.id === 'glb-size-optimizer');
+
+ it('exists, enabled, self pipeline, POST /api/mcp, 6h cooldown, run() wired', () => {
+ expect(entry).toBeTruthy();
+ expect(entry.enabled).toBe(true);
+ expect(entry.method).toBe('POST');
+ expect(entry.pipeline).toBe('self');
+ expect(entry.cooldown_s).toBe(21_600);
+ expect(entry.path).toBe('/api/mcp');
+ expect(typeof entry.run).toBe('function');
+ });
+});
diff --git a/tests/x402-granite-inference-health.test.js b/tests/x402-granite-inference-health.test.js
new file mode 100644
index 000000000..95823b56c
--- /dev/null
+++ b/tests/x402-granite-inference-health.test.js
@@ -0,0 +1,247 @@
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
+import http from 'node:http';
+import { Keypair } from '@solana/web3.js';
+
+// The payer + payee/feePayer keys and the USDC mint must be valid base58 pubkeys
+// because runGraniteHealth builds (and signs) a real Solana USDC transfer
+// locally. Nothing is broadcast — the mock /api/ibm-mcp below never touches a
+// chain — so this is a true integration test of the probe → pay → summarise →
+// store path without any on-chain spend.
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+process.env.X402_ASSET_MINT_SOLANA = USDC;
+
+const {
+ runGraniteHealth,
+ summarizeGraniteHealth,
+ GRANITE_HEALTH_BATCH,
+ GRANITE_HEALTH_TOOLS,
+} = await import('../api/_lib/x402/granite-health.js');
+
+const payTo = Keypair.generate().publicKey.toBase58();
+const feePayer = Keypair.generate().publicKey.toBase58();
+const AMOUNT = '140000'; // 0.14 USDC atomics — the summed batch price
+
+function challenge() {
+ return {
+ x402Version: 2,
+ error: 'payment required',
+ accepts: [{
+ scheme: 'exact',
+ network: 'solana:mainnet',
+ asset: USDC,
+ payTo,
+ amount: AMOUNT,
+ extra: { feePayer },
+ }],
+ };
+}
+
+// A healthy batched JSON-RPC response — one entry per tool, keyed by id == tool.
+function healthyBatch() {
+ const usage = (p, c) => ({ prompt_tokens: p, completion_tokens: c, total_tokens: p + c });
+ const sc = {
+ ibm_granite_chat: { ok: true, text: 'OK', usage: usage(12, 3) },
+ ibm_granite_code: { ok: true, text: 'adds a and b', usage: usage(20, 10) },
+ ibm_granite_embed: { ok: true, vectors: [[0.1, 0.2, 0.3]], dimensions: 768, inputCount: 1 },
+ ibm_granite_analyze: { ok: true, summary: 'nominal', usage: usage(30, 25) },
+ ibm_granite_forecast: { ok: true, forecast: [{ timestamp: 'x', value: 1 }], forecastSteps: 12, inputWindow: 512 },
+ };
+ return GRANITE_HEALTH_TOOLS.map((t) => ({
+ jsonrpc: '2.0', id: t,
+ result: { content: [{ type: 'text', text: 'ok' }], structuredContent: sc[t] },
+ }));
+}
+
+// A degraded batch: chat returns a JSON-RPC error (watsonx down), the rest ok.
+function degradedBatch() {
+ return healthyBatch().map((m) =>
+ m.id === 'ibm_granite_chat'
+ ? { jsonrpc: '2.0', id: 'ibm_granite_chat', error: { code: -32000, message: 'watsonx_unavailable' } }
+ : m,
+ );
+}
+
+function makeSqlStub() {
+ const calls = [];
+ const sql = (strings, ...values) => {
+ calls.push({ text: strings.join('?'), values });
+ return Promise.resolve([]);
+ };
+ return { sql, calls };
+}
+
+function baseCtx(origin, sqlStub) {
+ return {
+ origin,
+ buyer: Keypair.generate(),
+ conn: { getAccountInfo: async () => null }, // null → "create the ATA", fine
+ blockhash: '11111111111111111111111111111111',
+ mintInfo: { decimals: 6 },
+ redis: null,
+ sql: sqlStub.sql,
+ log: { info() {}, warn() {} },
+ runId: '00000000-0000-0000-0000-000000000000',
+ remainingCap: 1_000_000,
+ };
+}
+
+let mode = 'healthy';
+let server;
+let origin;
+
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ const paid = !!req.headers['x-payment'];
+ if (!paid || mode === 'payment_rejected') {
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify(challenge()));
+ return;
+ }
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json');
+ res.setHeader(
+ 'x-payment-response',
+ Buffer.from(JSON.stringify({ success: true, transaction: 'TESTSIG_granite' })).toString('base64'),
+ );
+ res.end(JSON.stringify(mode === 'degraded' ? degradedBatch() : healthyBatch()));
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ origin = `http://127.0.0.1:${server.address().port}`;
+});
+
+afterAll(() => new Promise((resolve) => server.close(resolve)));
+beforeEach(() => { mode = 'healthy'; });
+
+describe('granite-health canary batch', () => {
+ it('invokes all five paid tools with valid arguments', () => {
+ expect(GRANITE_HEALTH_BATCH).toHaveLength(5);
+ for (const t of GRANITE_HEALTH_TOOLS) {
+ const m = GRANITE_HEALTH_BATCH.find((x) => x.id === t);
+ expect(m.method).toBe('tools/call');
+ expect(m.params.name).toBe(t);
+ expect(m.params.arguments).toBeTruthy();
+ }
+ });
+
+ it('sends a full 512-point context window for the forecast tool', () => {
+ const fc = GRANITE_HEALTH_BATCH.find((x) => x.id === 'ibm_granite_forecast').params.arguments;
+ expect(fc.timestamps).toHaveLength(512);
+ expect(fc.values).toHaveLength(512);
+ expect(fc.timestamps.length).toBe(fc.values.length);
+ });
+});
+
+describe('summarizeGraniteHealth', () => {
+ it('tallies tool health, schema conformance, and token throughput', () => {
+ const s = summarizeGraniteHealth(healthyBatch());
+ expect(s.tools_ok).toBe(5);
+ expect(s.tools_failed).toBe(0);
+ expect(s.schema_ok_count).toBe(5);
+ expect(s.all_healthy).toBe(true);
+ expect(s.watsonx_responding).toBe(true);
+ expect(s.total_tokens).toBe(100);
+ expect(s.embed_dimensions).toBe(768);
+ expect(s.forecast_steps).toBe(12);
+ });
+
+ it('flags per-tool failures and never throws on null input', () => {
+ const d = summarizeGraniteHealth(degradedBatch());
+ expect(d.tools_ok).toBe(4);
+ expect(d.tools_failed).toBe(1);
+ expect(d.all_healthy).toBe(false);
+ expect(d.watsonx_responding).toBe(true);
+ expect(d.per_tool.ibm_granite_chat.error).toBe('watsonx_unavailable');
+
+ const e = summarizeGraniteHealth(null);
+ expect(e.tools_failed).toBe(5);
+ expect(e.all_healthy).toBe(false);
+ expect(e.watsonx_responding).toBe(false);
+ });
+});
+
+describe('runGraniteHealth', () => {
+ it('pays one batch call, settles, summarises, and stores the verdict', async () => {
+ mode = 'healthy';
+ const sqlStub = makeSqlStub();
+ const out = await runGraniteHealth(baseCtx(origin, sqlStub));
+
+ expect(out.success).toBe(true);
+ expect(out.amountAtomic).toBe(Number(AMOUNT));
+ expect(out.txSig).toBe('TESTSIG_granite');
+ expect(out.errorMsg).toBeNull();
+ expect(out.signalData.all_healthy).toBe(true);
+ expect(out.signalData.total_tokens).toBe(100);
+
+ const insert = sqlStub.calls.find((c) => /insert into\s+granite_inference_health/i.test(c.text));
+ expect(insert).toBeTruthy();
+ expect(insert.values).toContain(true); // all_healthy
+ });
+
+ it('records a degraded verdict (and an errorMsg) when a tool fails but payment settles', async () => {
+ mode = 'degraded';
+ const sqlStub = makeSqlStub();
+ const out = await runGraniteHealth(baseCtx(origin, sqlStub));
+
+ expect(out.success).toBe(true); // HTTP 200 — the call settled
+ expect(out.signalData.all_healthy).toBe(false);
+ expect(out.signalData.tools_failed).toBe(1);
+ expect(out.errorMsg).toMatch(/granite_tools_failed:1/);
+ expect(sqlStub.calls.some((c) => /insert into\s+granite_inference_health/i.test(c.text))).toBe(true);
+ });
+
+ it('handles a 402 payment rejection without crashing or storing', async () => {
+ mode = 'payment_rejected';
+ const sqlStub = makeSqlStub();
+ const out = await runGraniteHealth(baseCtx(origin, sqlStub));
+
+ expect(out.success).toBe(false);
+ expect(out.amountAtomic).toBe(0);
+ expect(out.errorMsg).toMatch(/http_402/);
+ expect(sqlStub.calls.some((c) => /insert into\s+granite_inference_health/i.test(c.text))).toBe(false);
+ });
+
+ it('honors the daily cap — skips paying when the price exceeds remainingCap', async () => {
+ mode = 'healthy';
+ const sqlStub = makeSqlStub();
+ const ctx = baseCtx(origin, sqlStub);
+ ctx.remainingCap = 1; // below AMOUNT
+ const out = await runGraniteHealth(ctx);
+
+ expect(out.success).toBe(false);
+ expect(out.skipped).toBe(true);
+ expect(out.errorMsg).toBe('cap_would_exceed');
+ expect(out.amountAtomic).toBe(0);
+ });
+
+ it('degrades gracefully when the wallet is unconfigured', async () => {
+ const sqlStub = makeSqlStub();
+ const ctx = baseCtx(origin, sqlStub);
+ ctx.buyer = null;
+ ctx.conn = null; // force the bootstrap path → loadSeedKeypair throws → skip
+ const prevSeed = process.env.X402_SEED_SOLANA_SECRET_BASE58;
+ const prevAgent = process.env.X402_AGENT_SOLANA_SECRET_BASE58;
+ delete process.env.X402_SEED_SOLANA_SECRET_BASE58;
+ delete process.env.X402_AGENT_SOLANA_SECRET_BASE58;
+ try {
+ const out = await runGraniteHealth(ctx);
+ expect(out.success).toBe(false);
+ expect(out.skipped).toBe(true);
+ expect(out.errorMsg).toMatch(/seed keypair not configured/);
+ } finally {
+ if (prevSeed !== undefined) process.env.X402_SEED_SOLANA_SECRET_BASE58 = prevSeed;
+ if (prevAgent !== undefined) process.env.X402_AGENT_SOLANA_SECRET_BASE58 = prevAgent;
+ }
+ });
+
+ it('is registered in the autonomous self-registry with the expected wiring', async () => {
+ const { getSelfRegistry } = await import('../api/_lib/x402/autonomous-registry.js');
+ const entry = getSelfRegistry().find((e) => e.id === 'granite-inference-health');
+ expect(entry).toBeTruthy();
+ expect(entry.endpoint).toBe('/api/ibm-mcp');
+ expect(entry.pipeline).toBe('health');
+ expect(entry.enabled).toBe(true);
+ expect(typeof entry.run).toBe('function');
+ expect(entry.cooldown_s).toBe(21600);
+ });
+});
diff --git a/tests/x402-idempotency-audit.test.js b/tests/x402-idempotency-audit.test.js
new file mode 100644
index 000000000..50f770afa
--- /dev/null
+++ b/tests/x402-idempotency-audit.test.js
@@ -0,0 +1,257 @@
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
+import http from 'node:http';
+import { createHash } from 'node:crypto';
+import { Keypair } from '@solana/web3.js';
+
+// The payer + payee/feePayer keys and the USDC mint must be valid base58 pubkeys
+// because runIdempotencyAudit builds (and signs) a real Solana transfer locally.
+// Nothing is broadcast — the local server below never touches a chain — so this
+// is a true integration test of the probe → pay → replay → classify → store path
+// without any on-chain spend.
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+process.env.X402_ASSET_MINT_SOLANA = USDC;
+
+const { runIdempotencyAudit } = await import(
+ '../api/_lib/x402/pipelines/payment-proof-idempotency-audit.js'
+);
+
+const payTo = Keypair.generate().publicKey.toBase58();
+const feePayer = Keypair.generate().publicKey.toBase58();
+const AMOUNT = '1000'; // 0.001 USDC atomics — matches the real model-check price.
+
+function challenge() {
+ return {
+ x402Version: 2,
+ error: 'payment required',
+ accepts: [{
+ scheme: 'exact',
+ network: 'solana:mainnet',
+ asset: USDC,
+ payTo,
+ amount: AMOUNT,
+ extra: { feePayer },
+ }],
+ };
+}
+
+// A captured-statement SQL stub: records every tagged-template call so the test
+// can assert the x402_idempotency_audit insert happened and inspect its values.
+function makeSqlStub() {
+ const calls = [];
+ const sql = (strings, ...values) => {
+ const text = strings.join('?');
+ calls.push({ text, values });
+ return Promise.resolve([]);
+ };
+ return { sql, calls };
+}
+
+function baseCtx(origin, sqlStub) {
+ return {
+ origin,
+ buyer: Keypair.generate(),
+ // getAccountInfo(receiverAta) → null means "create the ATA", which is fine.
+ conn: { getAccountInfo: async () => null },
+ blockhash: '11111111111111111111111111111111',
+ mintInfo: { decimals: 6 },
+ redis: null,
+ sql: sqlStub.sql,
+ log: { info() {}, warn() {} },
+ runId: '00000000-0000-0000-0000-000000000000',
+ remainingCap: 1_000_000,
+ // Drive the replay loop fast — no real cross-replica propagation here.
+ replayAttempts: 3,
+ replayBackoffMs: 5,
+ };
+}
+
+function proofHash(header) {
+ return createHash('sha256').update(String(header)).digest('hex');
+}
+
+// mode controls how the local /api/x402/model-check emulator behaves.
+// 'idempotent' — real replay: same proof returns the cached 200 + replay marker.
+// 'conflict' — second submission rejected with a 409 conflict marker.
+// 'broken' — NO idempotency: every paid call settles a fresh distinct tx.
+// 'reject' — paid call is rejected with a fresh 402 (never settles).
+let mode = 'idempotent';
+let server;
+let origin;
+// proofHash → { tx } for the idempotent emulator's cache.
+let store;
+let settleCounter;
+
+function newTx() {
+ settleCounter += 1;
+ return `TESTSIG_${settleCounter}`;
+}
+
+function settleHeaders(res, tx) {
+ res.setHeader(
+ 'x-payment-response',
+ Buffer.from(JSON.stringify({ success: true, transaction: tx })).toString('base64'),
+ );
+}
+
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ const payment = req.headers['x-payment'];
+ if (!payment) {
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify(challenge()));
+ return;
+ }
+ const hash = proofHash(payment);
+
+ if (mode === 'reject') {
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify(challenge()));
+ return;
+ }
+
+ if (mode === 'broken') {
+ // Always settle a brand-new tx — the failure the audit must catch.
+ const tx = newTx();
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ settleHeaders(res, tx);
+ res.end(JSON.stringify({ ok: true, tx }));
+ return;
+ }
+
+ // idempotent / conflict: first sighting settles + caches; a repeat replays.
+ const cached = store.get(hash);
+ if (!cached) {
+ const tx = newTx();
+ store.set(hash, { tx });
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ settleHeaders(res, tx);
+ res.end(JSON.stringify({ ok: true, tx }));
+ return;
+ }
+ if (mode === 'conflict') {
+ res.statusCode = 409;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('x-x402-idempotent', 'conflict');
+ res.end(JSON.stringify({ error: 'payment_identifier_conflict' }));
+ return;
+ }
+ // Replay the cached 200 with the same tx and the replay marker (no resettle).
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('x-x402-idempotent', 'replay');
+ settleHeaders(res, cached.tx);
+ res.end(JSON.stringify({ ok: true, tx: cached.tx }));
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ origin = `http://127.0.0.1:${port}`;
+});
+
+afterAll(() => new Promise((resolve) => server.close(resolve)));
+
+beforeEach(() => {
+ mode = 'idempotent';
+ store = new Map();
+ settleCounter = 0;
+});
+
+describe('runIdempotencyAudit', () => {
+ it('passes when the replayed proof returns a cached replay (no double settle)', async () => {
+ mode = 'idempotent';
+ const sqlStub = makeSqlStub();
+ const out = await runIdempotencyAudit(baseCtx(origin, sqlStub));
+
+ expect(out.success).toBe(true);
+ expect(out.note).toBe('idempotent_replay');
+ expect(out.amountAtomic).toBe(Number(AMOUNT)); // exactly one charge
+ expect(out.txSig).toBe('TESTSIG_1');
+ expect(out.errorMsg).toBeNull();
+ expect(out.signalData.verdict).toBe('idempotent_replay');
+ expect(out.signalData.double_settled).toBe(false);
+ expect(out.signalData.second_marker).toBe('replay');
+ // Exactly one on-chain settlement occurred.
+ expect(settleCounter).toBe(1);
+
+ const insert = sqlStub.calls.find((c) => /insert into\s+x402_idempotency_audit/i.test(c.text));
+ expect(insert).toBeTruthy();
+ expect(insert.values).toContain('idempotent_replay');
+ expect(insert.values).toContain(true); // pass
+ });
+
+ it('passes when the store rejects the replay with a 409 conflict', async () => {
+ mode = 'conflict';
+ const sqlStub = makeSqlStub();
+ const out = await runIdempotencyAudit(baseCtx(origin, sqlStub));
+
+ expect(out.success).toBe(true);
+ expect(out.signalData.verdict).toBe('idempotent_conflict');
+ expect(out.signalData.double_settled).toBe(false);
+ expect(settleCounter).toBe(1);
+ });
+
+ it('FAILS and flags a double settlement when the store does not dedupe', async () => {
+ mode = 'broken';
+ const sqlStub = makeSqlStub();
+ const out = await runIdempotencyAudit(baseCtx(origin, sqlStub));
+
+ expect(out.success).toBe(false);
+ expect(out.signalData.verdict).toBe('double_settled');
+ expect(out.signalData.double_settled).toBe(true);
+ expect(out.errorMsg).toMatch(/double_settlement/);
+ // Two distinct settlements happened — the failure the audit exists to catch.
+ expect(settleCounter).toBe(2);
+
+ const insert = sqlStub.calls.find((c) => /insert into\s+x402_idempotency_audit/i.test(c.text));
+ expect(insert).toBeTruthy();
+ expect(insert.values).toContain('double_settled');
+ });
+
+ it('records inconclusive (no spend) when the first call never settles', async () => {
+ mode = 'reject';
+ const sqlStub = makeSqlStub();
+ const out = await runIdempotencyAudit(baseCtx(origin, sqlStub));
+
+ expect(out.success).toBe(false);
+ expect(out.amountAtomic).toBe(0);
+ expect(out.signalData.verdict).toBe('inconclusive');
+ expect(settleCounter).toBe(0);
+ const insert = sqlStub.calls.find((c) => /insert into\s+x402_idempotency_audit/i.test(c.text));
+ expect(insert.values).toContain('inconclusive');
+ });
+
+ it('honors the daily cap — skips paying when the price exceeds remainingCap', async () => {
+ const sqlStub = makeSqlStub();
+ const ctx = baseCtx(origin, sqlStub);
+ ctx.remainingCap = 1; // below AMOUNT
+ const out = await runIdempotencyAudit(ctx);
+
+ expect(out.success).toBe(false);
+ expect(out.skipped).toBe(true);
+ expect(out.errorMsg).toBe('cap_would_exceed');
+ expect(out.amountAtomic).toBe(0);
+ expect(settleCounter).toBe(0);
+ });
+
+ it('degrades gracefully when the wallet is unconfigured', async () => {
+ const sqlStub = makeSqlStub();
+ const ctx = baseCtx(origin, sqlStub);
+ ctx.buyer = null;
+ const prevSeed = process.env.X402_SEED_SOLANA_SECRET_BASE58;
+ const prevAgent = process.env.X402_AGENT_SOLANA_SECRET_BASE58;
+ delete process.env.X402_SEED_SOLANA_SECRET_BASE58;
+ delete process.env.X402_AGENT_SOLANA_SECRET_BASE58;
+ try {
+ const out = await runIdempotencyAudit(ctx);
+ expect(out.success).toBe(false);
+ expect(out.skipped).toBe(true);
+ expect(out.errorMsg).toMatch(/wallet_unconfigured/);
+ } finally {
+ if (prevSeed !== undefined) process.env.X402_SEED_SOLANA_SECRET_BASE58 = prevSeed;
+ if (prevAgent !== undefined) process.env.X402_AGENT_SOLANA_SECRET_BASE58 = prevAgent;
+ }
+ });
+});
diff --git a/tests/x402-live-feed-seeder.test.js b/tests/x402-live-feed-seeder.test.js
new file mode 100644
index 000000000..93a2dcadd
--- /dev/null
+++ b/tests/x402-live-feed-seeder.test.js
@@ -0,0 +1,113 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ buildRequestBody,
+ summarizeResult,
+ nextRotation,
+ SEED_ROTATION,
+ REFERENCE_AVATARS,
+} from '../api/_lib/x402/pipelines/live-feed-seeder.js';
+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';
+
+// The demo flow only accepts these tools (ALLOWED_TOOLS in api/x402-pay.js).
+const ALLOWED_TOOLS = new Set([
+ 'tools/list',
+ 'validate_model',
+ 'inspect_model',
+ 'optimize_model',
+ 'search_public_avatars',
+]);
+
+describe('live-feed-seeder — rotation', () => {
+ it('every rotation entry targets an allowed demo tool', () => {
+ expect(SEED_ROTATION.length).toBeGreaterThan(0);
+ for (const pick of SEED_ROTATION) {
+ expect(ALLOWED_TOOLS.has(pick.tool)).toBe(true);
+ expect(typeof pick.topic).toBe('string');
+ expect(pick.topic.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('shows variety — more than one distinct tool across the rotation', () => {
+ const tools = new Set(SEED_ROTATION.map((p) => p.tool));
+ expect(tools.size).toBeGreaterThan(1);
+ });
+
+ it('round-robins through the whole list and wraps (in-memory fallback)', async () => {
+ const seen = [];
+ for (let i = 0; i < SEED_ROTATION.length * 2; i++) seen.push(await nextRotation({}));
+ // First full cycle covers every entry exactly once.
+ const firstCycle = seen.slice(0, SEED_ROTATION.length);
+ expect(new Set(firstCycle).size).toBe(SEED_ROTATION.length);
+ // Then it wraps back to the start.
+ expect(seen[SEED_ROTATION.length]).toBe(seen[0]);
+ });
+});
+
+describe('live-feed-seeder — buildRequestBody', () => {
+ it('builds a model-tool body with a public https avatar url', () => {
+ const body = buildRequestBody({ tool: 'inspect_model', avatar: 'michelle.glb' }, 'https://three.ws');
+ expect(body).toEqual({ tool: 'inspect_model', args: { url: 'https://three.ws/avatars/michelle.glb' } });
+ expect(/^https:\/\//.test(body.args.url)).toBe(true);
+ });
+
+ it('passes through search args verbatim', () => {
+ const body = buildRequestBody({ tool: 'search_public_avatars', args: { q: 'robot', limit: 6 } }, 'https://three.ws');
+ expect(body).toEqual({ tool: 'search_public_avatars', args: { q: 'robot', limit: 6 } });
+ });
+
+ it('tools/list carries an empty args object', () => {
+ expect(buildRequestBody({ tool: 'tools/list', args: {} }, 'https://three.ws')).toEqual({ tool: 'tools/list', args: {} });
+ });
+
+ it('every avatar-backed rotation entry references a known reference avatar', () => {
+ for (const pick of SEED_ROTATION) {
+ if (pick.avatar) expect(REFERENCE_AVATARS).toContain(pick.avatar);
+ }
+ });
+});
+
+describe('live-feed-seeder — summarizeResult', () => {
+ it('summarizes an avatar search by hit count', () => {
+ expect(summarizeResult('search_public_avatars', { structuredContent: { avatars: [1, 2, 3] } }))
+ .toEqual({ result_kind: 'avatars', result_count: 3 });
+ });
+
+ it('summarizes an inspection by geometry headline', () => {
+ expect(summarizeResult('inspect_model', { structuredContent: { counts: { totalTriangles: 5000, meshes: 2 } } }))
+ .toEqual({ result_kind: 'inspection', triangles: 5000, meshes: 2 });
+ });
+
+ it('summarizes a validation by error/warning counts', () => {
+ expect(summarizeResult('validate_model', { structuredContent: { numErrors: 0, numWarnings: 3 } }))
+ .toEqual({ result_kind: 'validation', errors: 0, warnings: 3 });
+ });
+
+ it('summarizes an optimization by suggestion count', () => {
+ expect(summarizeResult('optimize_model', { structuredContent: { suggestions: [1, 2] } }))
+ .toEqual({ result_kind: 'optimization', suggestions: 2 });
+ });
+
+ it('summarizes tools/list by tool count', () => {
+ expect(summarizeResult('tools/list', { tools: [1, 2, 3, 4, 5] }))
+ .toEqual({ result_kind: 'tools', tools: 5 });
+ });
+
+ it('never throws on a missing/garbage result', () => {
+ expect(summarizeResult('inspect_model', null)).toEqual({ result_kind: 'inspection', triangles: null, meshes: null });
+ expect(summarizeResult('search_public_avatars', {})).toEqual({ result_kind: 'avatars', result_count: null });
+ });
+});
+
+describe('live-feed-seeder — registry wiring', () => {
+ it('is registered as an enabled run()-style entry with a frequent cooldown', () => {
+ const entry = getFullRegistry().find((e) => e.id === 'live-feed-seeder');
+ expect(entry).toBeTruthy();
+ expect(entry.enabled).toBe(true);
+ expect(typeof entry.run).toBe('function');
+ expect(entry.path).toBe('/api/x402-pay');
+ expect(entry.pipeline).toBe('feed');
+ // Loop ticks every 5 min — a 300s cooldown keeps the feed fresh each tick.
+ expect(entry.cooldown_s).toBeLessThanOrEqual(300);
+ });
+});
diff --git a/tests/x402-reputation-refresh.test.js b/tests/x402-reputation-refresh.test.js
new file mode 100644
index 000000000..ffe61cc92
--- /dev/null
+++ b/tests/x402-reputation-refresh.test.js
@@ -0,0 +1,100 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ extractReputation,
+ evaluateReputation,
+} from '../api/_lib/x402/pipelines/reputation-refresh.js';
+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';
+import { priceFor, x402AmountForTool, isFreeTool } from '../api/_lib/pump-pricing.js';
+
+const rep = (over = {}) => ({
+ agent: 'THREEsynthetic1111111111111111111111111111',
+ network: 'mainnet',
+ feedback: { total: 5, verified: 4, disputed: 0, score_avg: 4.2, score_avg_verified: 4.5 },
+ validation: { passed: 2, failed: 0 },
+ ...over,
+});
+
+describe('reputation refresh — JSON-RPC response parsing', () => {
+ it('extracts structuredContent from a tools/call body', () => {
+ const out = extractReputation({ result: { structuredContent: rep() } });
+ expect(out.feedback.total).toBe(5);
+ expect(out.validation.passed).toBe(2);
+ });
+
+ it('handles a single-element batch array', () => {
+ const out = extractReputation([{ result: { structuredContent: rep() } }]);
+ expect(out).toBeTruthy();
+ expect(out.feedback.verified).toBe(4);
+ });
+
+ it('returns null (not throw) on a malformed / error body', () => {
+ expect(extractReputation(null)).toBeNull();
+ expect(extractReputation({ error: { code: -32000 } })).toBeNull();
+ expect(extractReputation({ result: {} })).toBeNull();
+ expect(extractReputation({ result: { structuredContent: { error: 'x' } } })).toBeNull();
+ });
+});
+
+describe('reputation refresh — score + flag evaluation', () => {
+ it('uses the verified average when verified feedback exists', () => {
+ const e = evaluateReputation(rep({ feedback: { total: 5, verified: 4, disputed: 0, score_avg: 2.0, score_avg_verified: 4.5 } }));
+ expect(e.score).toBe(4.5);
+ expect(e.flagged).toBe(false);
+ });
+
+ it('falls back to the raw average when there is no verified feedback', () => {
+ const e = evaluateReputation(rep({ feedback: { total: 4, verified: 0, disputed: 0, score_avg: 4.1, score_avg_verified: 0 } }));
+ expect(e.score).toBe(4.1);
+ expect(e.flagged).toBe(false);
+ });
+
+ it('flags a low verified score once the sample is meaningful', () => {
+ const e = evaluateReputation(rep({ feedback: { total: 6, verified: 5, disputed: 0, score_avg: 4.0, score_avg_verified: 2.4 } }));
+ expect(e.flagged).toBe(true);
+ expect(e.reasons.join(' ')).toMatch(/score/);
+ });
+
+ it('does NOT flag a low score below the minimum sample size', () => {
+ const e = evaluateReputation(rep({ feedback: { total: 1, verified: 1, disputed: 0, score_avg: 1.0, score_avg_verified: 1.0 } }));
+ expect(e.flagged).toBe(false);
+ });
+
+ it('flags when a majority of feedback is disputed', () => {
+ const e = evaluateReputation(rep({ feedback: { total: 4, verified: 0, disputed: 3, score_avg: 4.8, score_avg_verified: 0 } }));
+ expect(e.flagged).toBe(true);
+ expect(e.reasons.join(' ')).toMatch(/disputed/);
+ });
+
+ it('flags when validation is net-failing', () => {
+ const e = evaluateReputation(rep({ feedback: { total: 0, verified: 0, disputed: 0, score_avg: 0, score_avg_verified: 0 }, validation: { passed: 1, failed: 3 } }));
+ expect(e.flagged).toBe(true);
+ expect(e.reasons.join(' ')).toMatch(/validation/);
+ });
+
+ it('does not throw on an empty payload', () => {
+ const e = evaluateReputation({});
+ expect(e.score).toBe(0);
+ expect(e.flagged).toBe(false);
+ });
+});
+
+describe('reputation refresh — pricing', () => {
+ it('prices solana_agent_reputation at $0.001 (1000 atomic)', () => {
+ expect(isFreeTool('solana_agent_reputation')).toBe(false);
+ expect(priceFor('solana_agent_reputation').amount_usdc).toBe(0.001);
+ expect(x402AmountForTool('solana_agent_reputation')).toBe('1000');
+ });
+});
+
+describe('reputation refresh — registry wiring', () => {
+ it('is registered as an enabled, 6h, run()-style self entry', () => {
+ const entry = getFullRegistry().find((e) => e.id === 'reputation-score-refresh');
+ expect(entry).toBeTruthy();
+ expect(entry.enabled).toBe(true);
+ expect(entry.cooldown_s).toBe(21600);
+ expect(entry.pipeline).toBe('self');
+ expect(typeof entry.run).toBe('function');
+ expect(entry.path).toBe('/api/mcp');
+ });
+});
diff --git a/tests/x402-sniper-intel-enrich.test.js b/tests/x402-sniper-intel-enrich.test.js
new file mode 100644
index 000000000..79858d2fd
--- /dev/null
+++ b/tests/x402-sniper-intel-enrich.test.js
@@ -0,0 +1,97 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ deriveSentiment,
+ run,
+} from '../api/_lib/x402/pipelines/sniper-intel-enrich.js';
+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';
+
+const intel = (over = {}) => ({
+ topic: 'sol',
+ headline: 'SOL surges +9.1% in 24 h — strong momentum',
+ signal: 'bullish',
+ price_usd: 152.4,
+ change_24h: 9.1,
+ rationale: 'SOL is up +9.1%, trading at $152.40.',
+ confidence: 0.9,
+ ts: '2026-06-29T10:00:00Z',
+ ...over,
+});
+
+describe('sniper intel enrich — sentiment → gate delta', () => {
+ it('lowers the bar (negative delta) on a bullish read, scaled by confidence', () => {
+ const v = deriveSentiment(intel({ signal: 'bullish', confidence: 1 }));
+ expect(v).toBeTruthy();
+ expect(v.signal).toBe('bullish');
+ expect(v.sentiment_adj).toBe(-4); // -round(4 * 1)
+ expect(v.sentiment_adj).toBeLessThan(0);
+ });
+
+ it('raises the bar (positive delta) on a bearish read, scaled by confidence', () => {
+ const v = deriveSentiment(intel({ signal: 'bearish', confidence: 1 }));
+ expect(v.signal).toBe('bearish');
+ expect(v.sentiment_adj).toBe(8); // round(8 * 1)
+ expect(v.sentiment_adj).toBeGreaterThan(0);
+ });
+
+ it('is asymmetric — bearish moves the bar more than bullish at equal confidence', () => {
+ const bull = deriveSentiment(intel({ signal: 'bullish', confidence: 0.8 }));
+ const bear = deriveSentiment(intel({ signal: 'bearish', confidence: 0.8 }));
+ expect(Math.abs(bear.sentiment_adj)).toBeGreaterThan(Math.abs(bull.sentiment_adj));
+ });
+
+ it('leaves the bar untouched on a neutral read', () => {
+ const v = deriveSentiment(intel({ signal: 'neutral', confidence: 0.9 }));
+ expect(v.sentiment_adj).toBe(0);
+ });
+
+ it('clamps the delta to ±10 even at maximum confidence', () => {
+ const bear = deriveSentiment(intel({ signal: 'bearish', confidence: 1 }));
+ const bull = deriveSentiment(intel({ signal: 'bullish', confidence: 1 }));
+ expect(bear.sentiment_adj).toBeLessThanOrEqual(10);
+ expect(bull.sentiment_adj).toBeGreaterThanOrEqual(-10);
+ });
+
+ it('defaults confidence to 0.5 when the response omits or corrupts it', () => {
+ const v = deriveSentiment(intel({ confidence: undefined }));
+ expect(v.confidence).toBe(0.5);
+ const bad = deriveSentiment(intel({ confidence: 'NaN' }));
+ expect(bad.confidence).toBe(0.5);
+ });
+
+ it('preserves the headline, price, and 24 h change for the sink', () => {
+ const v = deriveSentiment(intel());
+ expect(v.headline).toContain('SOL surges');
+ expect(v.price_usd).toBe(152.4);
+ expect(v.change_24h).toBe(9.1);
+ });
+
+ it('returns null for a malformed, empty, or unknown-signal body', () => {
+ expect(deriveSentiment(null)).toBeNull();
+ expect(deriveSentiment({})).toBeNull();
+ expect(deriveSentiment({ signal: 'sideways' })).toBeNull();
+ });
+});
+
+describe('sniper intel enrich — registry wiring', () => {
+ it('is registered as an enabled, run()-style sniper entry on crypto-intel', () => {
+ const entry = getFullRegistry().find((e) => e.id === 'sniper-intel-enrich');
+ expect(entry).toBeTruthy();
+ expect(entry.enabled).toBe(true);
+ expect(entry.pipeline).toBe('sniper');
+ expect(entry.cooldown_s).toBe(900);
+ expect(typeof entry.run).toBe('function');
+ expect(entry.path).toBe('/api/x402/crypto-intel');
+ });
+});
+
+describe('sniper intel enrich — graceful degradation', () => {
+ it('never throws when the DB/wallet are unconfigured; returns a skipped outcome', async () => {
+ const out = await run({ runId: '00000000-0000-0000-0000-000000000024' });
+ expect(out).toBeTruthy();
+ expect(out.amountAtomic).toBe(0);
+ // Either the schema/select degraded (no targets) or the wallet was
+ // unconfigured — both are skip outcomes, never a thrown error.
+ expect(out.skipped === true || out.success === true).toBe(true);
+ });
+});
diff --git a/tests/x402-vrm-compat-checker.test.js b/tests/x402-vrm-compat-checker.test.js
new file mode 100644
index 000000000..010b046a0
--- /dev/null
+++ b/tests/x402-vrm-compat-checker.test.js
@@ -0,0 +1,182 @@
+// Unit tests for the VRM 1.0 Compatibility Checker pipeline (USE-019):
+// api/_lib/x402/pipelines/vrm-compat-checker.js.
+//
+// The DB and the R2 public-URL helper are mocked. The sql mock dispatches on
+// query text so the idempotent schema DDL (ensureVrmSchema) is ignored and only
+// the meaningful SELECT/INSERT are asserted on.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// ── mock R2 public-URL helper (avoids env / CDN config) ──────────────────────
+vi.mock('../api/_lib/r2.js', () => ({
+ // Pass through absolute URLs; resolve bare keys against a fake CDN.
+ publicUrl: (key) => (/^https?:\/\//i.test(key) ? key : `https://cdn.example/${key}`),
+}));
+
+// ── mock DB: route by query text ─────────────────────────────────────────────
+const dbState = {
+ candidate: null, // row nextVrmTarget's SELECT returns (or null → [])
+ calls: [], // captured { text, values }
+};
+
+function makeSql() {
+ return vi.fn(async (strings, ...values) => {
+ const text = Array.isArray(strings) ? strings.join('?') : String(strings);
+ dbState.calls.push({ text, values });
+ if (/CREATE\s+TABLE/i.test(text)) return [];
+ if (/FROM\s+avatars\s+a/i.test(text)) {
+ return dbState.candidate ? [dbState.candidate] : [];
+ }
+ if (/INSERT\s+INTO\s+avatar_vrm_compat/i.test(text)) return [];
+ return [];
+ });
+}
+
+import { classifyVrmCompat, vrmCompatEntry } from '../api/_lib/x402/pipelines/vrm-compat-checker.js';
+
+beforeEach(() => {
+ dbState.candidate = null;
+ dbState.calls = [];
+});
+
+// ── classifyVrmCompat ────────────────────────────────────────────────────────
+
+describe('classifyVrmCompat', () => {
+ it('classifies a VRM 0.x avatar as upgradeable with a migration checklist', () => {
+ const v = classifyVrmCompat(
+ {
+ extensionsUsed: ['VRM', 'KHR_materials_unlit'],
+ counts: { skins: 1, materials: 3, nodes: 60 },
+ materials: [{}, {}, {}],
+ filename: 'alicia.vrm',
+ container: 'glb',
+ },
+ 'https://cdn.example/alicia.vrm',
+ );
+ expect(v.vrm_version).toBe('0.x');
+ expect(v.is_vrm).toBe(true);
+ expect(v.upgradeable).toBe(true);
+ const codes = v.issues.map((i) => i.code).sort();
+ expect(codes).toEqual(['coordinate_space', 'expression_remap', 'mtoon_migration', 'springbone_remap']);
+ // blocker_count counts warn/critical only (mtoon is info)
+ expect(v.blocker_count).toBe(3);
+ });
+
+ it('classifies a VRM 1.0 avatar as already on-spec (not an upgrade candidate)', () => {
+ const v = classifyVrmCompat(
+ { extensionsUsed: ['VRMC_vrm', 'VRMC_springBone', 'VRMC_materials_mtoon'], counts: { skins: 1 } },
+ 'u',
+ );
+ expect(v.vrm_version).toBe('1.0');
+ expect(v.is_vrm).toBe(true);
+ expect(v.upgradeable).toBeNull();
+ expect(v.issues).toEqual([]);
+ });
+
+ it('classifies a non-VRM model as none / not applicable', () => {
+ const v = classifyVrmCompat({ extensionsUsed: ['KHR_draco_mesh_compression'], counts: { skins: 0 } }, 'u');
+ expect(v.vrm_version).toBe('none');
+ expect(v.is_vrm).toBe(false);
+ expect(v.upgradeable).toBeNull();
+ });
+
+ it('omits the spring-bone item when the model has no skins', () => {
+ const v = classifyVrmCompat({ extensionsUsed: ['VRM'], counts: { skins: 0, materials: 0 } }, 'u');
+ expect(v.issues.map((i) => i.code)).not.toContain('springbone_remap');
+ expect(v.upgradeable).toBe(true);
+ });
+});
+
+// ── registry entry wiring ────────────────────────────────────────────────────
+
+describe('vrmCompatEntry', () => {
+ it('exposes the correct registry shape', () => {
+ expect(vrmCompatEntry.id).toBe('vrm-compat-checker');
+ expect(vrmCompatEntry.path).toBe('/api/mcp');
+ expect(vrmCompatEntry.method).toBe('POST');
+ expect(vrmCompatEntry.pipeline).toBe('vrm-compat');
+ expect(vrmCompatEntry.enabled).toBe(true);
+ expect(vrmCompatEntry.cooldown_s).toBeGreaterThan(0);
+ });
+
+ it('builds an MCP inspect_model tools/call body from the resolved target URL', () => {
+ const body = vrmCompatEntry.body({ targetUrl: 'https://three.ws/avatars/a.vrm' });
+ expect(body.method).toBe('tools/call');
+ expect(body.params.name).toBe('inspect_model');
+ expect(body.params.arguments.url).toBe('https://three.ws/avatars/a.vrm');
+ });
+
+ it('returns a null body when there is no target (loop skips without paying)', () => {
+ expect(vrmCompatEntry.body({ targetUrl: null })).toBeNull();
+ });
+
+ it('extractSignal summarizes the inspect_model response into signal_data', () => {
+ const sig = vrmCompatEntry.extractSignal({
+ result: { structuredContent: { extensionsUsed: ['VRM'], counts: { skins: 1, materials: 2 }, materials: [{}, {}] } },
+ });
+ expect(sig.is_vrm).toBe(true);
+ expect(sig.vrm_version).toBe('0.x');
+ expect(sig.upgradeable).toBe(true);
+ expect(sig.blocker_count).toBe(3);
+ });
+
+ it('extractSignal degrades gracefully on a malformed response', () => {
+ expect(vrmCompatEntry.extractSignal({}).ok).toBe(false);
+ });
+});
+
+// ── resolveTarget (avatar selection) ─────────────────────────────────────────
+
+describe('vrmCompatEntry.resolveTarget', () => {
+ it('selects a VRM-candidate avatar and resolves its public URL + context', async () => {
+ dbState.candidate = { id: 'avatar-uuid-1', name: 'My VRM', storage_key: 'u/owner/avatar.vrm' };
+ const sql = makeSql();
+ const out = await vrmCompatEntry.resolveTarget({ sql, origin: 'https://three.ws' });
+ expect(out.targetUrl).toBe('https://cdn.example/u/owner/avatar.vrm');
+ expect(out.context.avatar_id).toBe('avatar-uuid-1');
+ expect(out.context.canary).toBe(false);
+ // the SELECT ran against the avatars table
+ expect(dbState.calls.some((c) => /FROM\s+avatars\s+a/i.test(c.text))).toBe(true);
+ });
+
+ it('yields no target when no candidate avatar exists and no canary is set', async () => {
+ dbState.candidate = null;
+ const sql = makeSql();
+ const out = await vrmCompatEntry.resolveTarget({ sql, origin: 'https://three.ws' });
+ expect(out).toBeNull();
+ });
+});
+
+// ── storeValue (per-avatar persistence) ──────────────────────────────────────
+
+describe('vrmCompatEntry.storeValue', () => {
+ it('upserts the migration report keyed by avatar_id', async () => {
+ const sql = makeSql();
+ await vrmCompatEntry.storeValue({
+ sql,
+ runId: 'run-1',
+ targetUrl: 'https://cdn.example/u/owner/avatar.vrm',
+ targetContext: { avatar_id: 'avatar-uuid-1', canary: false },
+ txSig: 'sig123',
+ responseBody: { result: { structuredContent: { extensionsUsed: ['VRM'], counts: { skins: 1, materials: 2 }, materials: [{}, {}] } } },
+ });
+ const insert = dbState.calls.find((c) => /INSERT\s+INTO\s+avatar_vrm_compat/i.test(c.text));
+ expect(insert).toBeTruthy();
+ // avatar_id is the first bound value
+ expect(insert.values[0]).toBe('avatar-uuid-1');
+ // the report payload contains the classified version
+ expect(insert.values.some((val) => typeof val === 'string' && /"vrm_version":"0\.x"/.test(val))).toBe(true);
+ });
+
+ it('skips persistence for a canary target (no avatar_id to key on)', async () => {
+ const sql = makeSql();
+ await vrmCompatEntry.storeValue({
+ sql,
+ runId: 'run-1',
+ targetUrl: 'https://example/canary.vrm',
+ targetContext: { avatar_id: null, canary: true },
+ responseBody: { result: { structuredContent: { extensionsUsed: ['VRM'], counts: { skins: 1 } } } },
+ });
+ expect(dbState.calls.some((c) => /INSERT\s+INTO\s+avatar_vrm_compat/i.test(c.text))).toBe(false);
+ });
+});
diff --git a/workers/agent-sniper/oracle-gate.js b/workers/agent-sniper/oracle-gate.js
index 24704c95f..b17c38cb4 100644
--- a/workers/agent-sniper/oracle-gate.js
+++ b/workers/agent-sniper/oracle-gate.js
@@ -9,6 +9,11 @@
// 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.
+//
+// Per-coin sentiment adjustment: reads sniper_coin_sentiment (populated by the
+// x402 Sniper Intel Enrichment loop, which pays /api/x402/crypto-intel for the
+// coins the sniper is actively watching) to nudge the same threshold by THIS
+// coin's own live market read. Both layers are clamped and fail-open.
import { sql } from '../../api/_lib/db.js';
import { log } from './log.js';
@@ -16,11 +21,25 @@ import { log } from './log.js';
const _cache = new Map(); // key → { score, ts }
const CACHE_TTL_MS = 30_000;
+// Rugpull verdict cache (separate from the conviction cache).
+const _rugCache = new Map(); // key → { rejected, score, level, ts }
+const RUG_CACHE_TTL_MS = 30_000;
+// A verdict only vetoes while it is this fresh — new mints move fast and the x402
+// gate re-checks on its own cooldown, so a stale "rejected" must not block forever.
+const RUG_FRESH_MINUTES = Number(process.env.SNIPER_RUGPULL_FRESH_MIN || 60);
+
// Macro signal cache — shared across all gate calls, refreshed every 2 min.
let _macroCache = null;
let _macroCacheTs = 0;
const MACRO_TTL_MS = 120_000;
+// Per-coin sentiment cache (separate from the conviction cache).
+const _sentCache = new Map(); // key → { adj, ts }
+const SENT_CACHE_TTL_MS = 30_000;
+// A per-coin sentiment delta only applies while this fresh — the x402 enrichment
+// loop re-reads on its own cooldown, so a stale read must not keep moving the bar.
+const SENT_FRESH_MINUTES = Number(process.env.SNIPER_SENTIMENT_FRESH_MIN || 30);
+
function n(v) {
const x = Number(v);
return Number.isFinite(x) ? x : null;
@@ -90,13 +109,96 @@ async function getMacroAdjustment() {
}
}
+/**
+ * Pre-snipe rugpull veto — platform-wide safety floor. Looks up the latest x402
+ * Token Intel verdict for a mint (token_intel_risk, populated by
+ * api/_lib/x402/pipelines/token-intel-gate.js) and rejects the snipe when a FRESH
+ * high/critical verdict says rug. Fail-open: any error, a missing verdict, or a
+ * stale one returns { reject: false }, so this can only ever make the sniper safer.
+ *
+ * @param {string} mint
+ * @param {string} network
+ * @returns {Promise<{ reject: boolean, score?: number, level?: string }>}
+ */
+export async function rugpullVeto(mint, network) {
+ const cacheKey = `${network}:${mint}`;
+ const cached = _rugCache.get(cacheKey);
+ if (cached && Date.now() - cached.ts < RUG_CACHE_TTL_MS) {
+ return cached.rejected ? { reject: true, score: cached.score, level: cached.level } : { reject: false };
+ }
+ try {
+ const [row] = await sql`
+ select rugpull_score, risk_level, rejected
+ from token_intel_risk
+ where mint = ${mint} and network = ${network}
+ and checked_at > now() - make_interval(mins => ${RUG_FRESH_MINUTES})
+ limit 1
+ `;
+ const rejected = row?.rejected === true;
+ const score = row?.rugpull_score != null ? n(row.rugpull_score) : null;
+ const level = row?.risk_level || null;
+ _rugCache.set(cacheKey, { rejected, score, level, ts: Date.now() });
+ if (_rugCache.size > 2000) {
+ const cutoff = Date.now() - RUG_CACHE_TTL_MS;
+ for (const [k, v] of _rugCache) if (v.ts < cutoff) _rugCache.delete(k);
+ }
+ return rejected ? { reject: true, score, level } : { reject: false };
+ } catch (err) {
+ // Table not present yet, or a transient DB fault — never block a snipe on it.
+ if (!err?.message?.includes('does not exist')) {
+ log.warn('rugpull veto db error — allowing snipe', { mint, err: err?.message });
+ }
+ return { reject: false };
+ }
+}
+
+/**
+ * Per-coin sentiment delta — folds the live Crypto Intel read into the snipe
+ * threshold. Looks up the latest x402 sentiment for a mint (sniper_coin_sentiment,
+ * populated by api/_lib/x402/pipelines/sniper-intel-enrich.js) and returns a
+ * clamped score-point delta: positive raises the bar (bearish coin), negative
+ * lowers it (bullish coin). Fail-open: any error, a missing row, or a stale one
+ * returns 0, so this can only ever nudge — never block — a snipe.
+ *
+ * @param {string} mint
+ * @param {string} network
+ * @returns {Promise<number>}
+ */
+export async function coinSentimentAdjustment(mint, network) {
+ const cacheKey = `${network}:${mint}`;
+ const cached = _sentCache.get(cacheKey);
+ if (cached && Date.now() - cached.ts < SENT_CACHE_TTL_MS) return cached.adj;
+ try {
+ const [row] = await sql`
+ select sentiment_adj
+ from sniper_coin_sentiment
+ where mint = ${mint} and network = ${network}
+ and checked_at > now() - make_interval(mins => ${SENT_FRESH_MINUTES})
+ limit 1
+ `;
+ const adj = row?.sentiment_adj != null ? (n(row.sentiment_adj) ?? 0) : 0;
+ const clamped = Math.max(-10, Math.min(10, adj));
+ _sentCache.set(cacheKey, { adj: clamped, ts: Date.now() });
+ if (_sentCache.size > 2000) {
+ const cutoff = Date.now() - SENT_CACHE_TTL_MS;
+ for (const [k, v] of _sentCache) if (v.ts < cutoff) _sentCache.delete(k);
+ }
+ return clamped;
+ } catch (err) {
+ if (!err?.message?.includes('does not exist')) {
+ log.warn('coin sentiment db error — no adjustment', { mint, err: err?.message });
+ }
+ 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).
+ * The effective threshold = min_oracle_score + macro_adjustment + coin_sentiment,
+ * where macro_adjustment is derived from oracle_intel_signals and coin_sentiment
+ * from sniper_coin_sentiment (both populated by the x402 autonomous spend loop).
*
* Returns:
* { pass: true } — scored and above threshold (or no threshold)
@@ -109,6 +211,13 @@ async function getMacroAdjustment() {
* @param {object} strat agent_sniper_strategies row
*/
export async function oracleGate(mint, network, strat) {
+ // Rugpull pre-snipe veto runs FIRST and unconditionally — a fresh high/critical
+ // token-intel verdict auto-rejects the mint regardless of strategy settings.
+ const rug = await rugpullVeto(mint, network);
+ if (rug.reject) {
+ return { pass: false, reason: `rugpull_risk:${rug.level || 'high'}:${rug.score ?? '?'}`, rugpull: rug };
+ }
+
const minScore = strat.min_oracle_score != null ? n(strat.min_oracle_score) : null;
if (minScore == null) return { pass: true };
@@ -142,17 +251,26 @@ export async function oracleGate(mint, network, strat) {
return { pass: true, skipped: true };
}
- // Apply macro signal adjustment from x402 autonomous loop intel.
- const macroAdj = await getMacroAdjustment();
- const effectiveMin = minScore + macroAdj;
+ // Apply macro signal + per-coin sentiment adjustments from x402 autonomous loop
+ // intel. Macro is market-wide (SOL/BTC/pump); coinAdj is this coin's own read.
+ const [macroAdj, coinAdj] = await Promise.all([
+ getMacroAdjustment(),
+ coinSentimentAdjustment(mint, network),
+ ]);
+ const effectiveMin = minScore + macroAdj + coinAdj;
if (score < effectiveMin) {
+ const parts = [];
+ if (macroAdj !== 0) parts.push(`macro:${macroAdj}`);
+ if (coinAdj !== 0) parts.push(`coin:${coinAdj}`);
+ const breakdown = parts.length ? `(base:${minScore}+${parts.join('+')})` : '';
return {
pass: false,
- reason: `oracle_below_min:${score}<${effectiveMin}${macroAdj !== 0 ? `(base:${minScore}+macro:${macroAdj})` : ''}`,
+ reason: `oracle_below_min:${score}<${effectiveMin}${breakdown}`,
macro_adjustment: macroAdj,
+ coin_adjustment: coinAdj,
};
}
- return { pass: true, macro_adjustment: macroAdj };
+ return { pass: true, macro_adjustment: macroAdj, coin_adjustment: coinAdj };
}