Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add pump launch monitor, trending score, x402 analytics and test coverage
nirholasb24a365eafb2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fe3ecc835..05e823b6e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,12 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-06-28++- **MCP Tool Discovery — the platform notices the moment a new agent capability ships** — The three.ws MCP server exposes a growing catalog of tools agents can call — render and inspect 3D models, query live pump.fun market data, read Oracle conviction signals, and more — and that catalog changes as new capabilities ship. Until now, an agent wanting to use a brand-new tool had to keep re-fetching the full tool list and diffing it by hand to notice anything had changed. The platform now does that watching for them. Every two hours an autonomous agent makes a real on-chain payment to a new paid endpoint that fingerprints the live tool catalog and compares it to a durable registry, then reports exactly what changed since the last check: tools that are newly registered, tools whose price or input shape changed, and tools that were removed. New tools are recorded the instant they appear, giving agents a single feature-flag source to light up a new capability without polling. The diff is logged like every other autonomous payment, and the same endpoint is available to any agent on the x402 bazaar for a fraction of a cent. `[feature, infra]`+- **Pay-By-Name Resolution Health — the platform watches its own name registry every 10 minutes** — Every 'send USDC to a name' flow on three.ws — the SDK's payByName(), the /pay studio, the profile pay button, and any agent routing a payment to @username or a .sol domain — resolves the recipient through the same name registry before a single lamport moves. If that registry breaks (a Bonfida SNS regression, the parent domain de-registering, or the platform domain repointing to a different wallet), the failure is silent and every downstream send either pays the wrong place or throws an error. The platform now watches for this automatically. Every 10 minutes an autonomous agent makes a free call to the resolve endpoint with the platform's own known SNS name and checks that it comes back with a valid, on-curve Solana wallet address. If an expected wallet is configured, it additionally asserts the resolution still matches that specific wallet — an anti-poisoning check that catches a domain repoint between deploys before any user is affected. Results are recorded to a time-series log and cached in Redis so a health dashboard can read the latest verdict without a database round-trip. A failed or mismatched resolution raises an alert flag that lingers until the next clean run. The monitor is a read-only, free call — it moves no funds — and it replaces a prior registry entry that was calling the wrong endpoint method and would have silently recorded every 404 as healthy. `[feature, infra]`+- **Pump Launch Monitor: live snipe-candidate screening** — The autonomous x402 agent now pays to audit the 10 most recently launched pump.fun tokens every 5 minutes, extracting each cohort's average and peak initial bonding-curve liquidity. New launches with initial liquidity well above the rolling cohort average are surfaced as high-conviction snipe candidates; the signal is upserted into the oracle feed so the sniper gate can act on it immediately. `[feature, infra]`+## 2026-06-27- **Capabilities — Alpha Hunt, Launcher, Auto-Claim & Market Maker** (`/dashboard/capabilities`) — Live command center for all 4 autonomous agent capabilities: Alpha Hunt smart-money scoring, autonomous Coin Launcher on schedule, Creator Auto-Claim for fee harvesting, and Market Maker with Jito execution.diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex f9dc77b78..fdf360370 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -49,6 +49,8 @@ import { run as feeCalculationValidator } from './pipelines/fee-calculation-valiimport { run as crossChainCostComparison } from './pipelines/cross-chain-cost.js';import { run as charitySplitAudit } from './pipelines/charity-split-audit.js';import { classifyThreeSignal, insertThreeSignal } from './three-signal-store.js';+import { classifySniperSignal, insertSniperAnalytics } from './sniper-analytics-store.js';+import { classifyLeaderboard, insertLeaderboardSnapshot } from './agent-leaderboard-store.js';import { run as cosmeticPricingAudit } from './pipelines/cosmetic-pricing-audit.js';import { run as builderCodeAttribution } from './pipelines/builder-code-attribution.js';import { run as paymentProofIdempotencyAudit } from './pipelines/payment-proof-idempotency-audit.js';@@ -74,8 +76,10 @@ import {SCENE_CAPTURE_PRICE_ATOMIC,} from './scene-capture-processor.js';import { run as runRigComplexityScorer } from './pipelines/rig-complexity.js';+import { extractCoverRevenueSignal } from '../club/cover-revenue.js';import { run as runReservationLeakDetector } from './pipelines/spend-reservation-leak-detector.js';import { run as runSubscriptionHealth } from './pipelines/subscription-health.js';+import { run as runPayByNameResolution } from './pipelines/pay-by-name-resolver.js';import {run as runServiceUptimeMonitor,SERVICE_UPTIME_ENDPOINT,@@ -86,6 +90,11 @@ import {THUMBNAIL_REGEN_PRICE_ATOMIC,STALE_DAYS as THUMBNAIL_STALE_DAYS,} from './thumbnail-regen.js';+import { classifyVolumeAnomaly } from './pump-volume-anomaly.js';+import {+ classifyLaunchMonitor,+ storePumpLaunchSnapshot,+} from './pump-launch-monitor.js';// ── MCP Tool Latency Monitor (USE-006) ───────────────────────────────────────// The canary the loop pays every 5 min to exercise the MCP paid path end-to-end@@ -209,6 +218,52 @@ async function nextCanonicalTarget(ctx) {return { path: `/api/x402/model-check?url=${encodeURIComponent(targetUrl)}`, targetUrl };}+// ── Forge Content Generation Health helpers (USE-072) ─────────────────────────+// The latency SLA the forge content-generation probe asserts (mirrors+// HEALTH_CHECK_BUDGET_MS in api/x402/forge.js). A completion slower than this — or+// an outright generator failure — is a forge performance alert.+const FORGE_HEALTH_BUDGET_MS = 5000;+// Redis key the on-call surface reads to detect a degraded content-generation+// lane in one GET, mirroring the wallet-balance alert convention.+const FORGE_HEALTH_ALERT_KEY = 'x402:forge-health:alert';+const FORGE_HEALTH_ALERT_TTL_SECONDS = 25 * 60;++// storeValue sink for the forge content-generation health probe. Raises (or+// clears) the forge performance alert based on the extracted verdict, and never+// throws — the loop wraps it in try/catch, but a health canary must not be able+// to crash the tick over an alerting hiccup.+async function recordForgeHealthAlert({ redis, signalData }) {+ if (!redis) return;+ const v = signalData || {};+ const degraded = v.generated === false || v.slow === true;+ try {+ if (degraded) {+ await redis.set(+ FORGE_HEALTH_ALERT_KEY,+ JSON.stringify({+ reason: v.generated === false ? 'generation_failed' : 'latency_budget_exceeded',+ generated: v.generated === true,+ latency_ms: v.latency_ms ?? null,+ budget_ms: FORGE_HEALTH_BUDGET_MS,+ provider: v.provider ?? null,+ error: v.error ?? null,+ ts: new Date().toISOString(),+ }),+ { ex: FORGE_HEALTH_ALERT_TTL_SECONDS },+ );+ console.warn(+ `[x402/forge-health] ALERT: content generation degraded (` ++ `generated=${v.generated}, latency_ms=${v.latency_ms}, budget=${FORGE_HEALTH_BUDGET_MS}ms)`,+ );+ } else if (v.generated === true) {+ // Healthy again — drop any lingering alert flag.+ await redis.del(FORGE_HEALTH_ALERT_KEY);+ }+ } catch (err) {+ console.warn(`[x402/forge-health] alert write failed: ${err?.message || err}`);+ }+}+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@@ -410,6 +465,28 @@ const SELF_ENDPOINTS = [enabled: true,extractSignal: (r) => ({ topic: r?.topic, signal: r?.signal, headline: r?.headline, confidence: r?.confidence }),},++ // ── Pump.fun Volume Anomaly Oracle (USE-048) ──────────────────────────────+ // Pays $0.01 USDC every 5 minutes to /api/x402/crypto-intel with topic+ // pump_volume_anomaly. The endpoint scans the live pump.fun currently-trading+ // set, fetches trailing-1h trade volumes from the swap API, and flags any coin+ // whose hourly USD volume is >=3x the peer-coin median as an anomaly. A ratio+ // > 5 is tagged high-conviction; as an `oracle` entry the loop upserts the+ // verdict into oracle_intel_signals (topic 'pump_volume_anomaly') for the+ // sniper gate. Cooldown 300s -> 12 scans/hr; $0.01/scan ~= $0.12/hr.+ {+ id: 'pump-volume-anomaly',+ name: 'Pump.fun Volume Anomaly Oracle',+ path: '/api/x402/crypto-intel',+ method: 'POST',+ body: { topic: 'pump_volume_anomaly' },+ cooldown_s: 300,+ priority: 88,+ pipeline: 'oracle',+ enabled: true,+ extractSignal: (r) => classifyVolumeAnomaly(r),+ },+{// ── $THREE Signal Feed (USE: $THREE market oracle) ─────────────// Pays $0.01 USDC every 15 min to /api/x402/three-intel for the live $THREE@@ -492,6 +569,42 @@ const SELF_ENDPOINTS = [}),},+ // ── Club Membership Snapshot (USE-066) ─────────────────────────────────────+ // Pays the $0.01 USDC club cover (POST snapshot mode) once a day to take a+ // growth/churn snapshot of the three_holders club, read live off the club+ // ledger: { member_count, active_last_7d, new_this_week } plus a classified+ // signal (growing / stable / churning / empty). As an `oracle` entry the+ // latest snapshot dedups into oracle_intel_signals under topic+ // 'club:three_holders' — a club-membership topic the sniper macro gate ignores+ // (it reads only solana/bitcoin/pump) so it never pollutes trade decisions —+ // giving any dashboard a single queryable row for current club health. The+ // full snapshot also lands in x402_autonomous_log.signal_data every run, so+ // the day-over-day growth/churn trend is reconstructable from the log alone.+ // Daily cadence → one paid snapshot/day ≈ $0.01/day, well under the loop cap.+ {+ id: 'club-membership-snapshot',+ name: 'Club Membership Snapshot (three_holders)',+ path: '/api/x402/club-cover',+ method: 'POST',+ body: { club: 'three_holders', mode: 'snapshot' },+ cooldown_s: 86400, // daily — membership growth/churn is a slow-moving signal+ priority: 86,+ pipeline: 'oracle',+ enabled: true,+ extractSignal: (r) => ({+ topic: 'club:three_holders',+ club: r?.club ?? 'three_holders',+ member_count: r?.member_count ?? null,+ active_last_7d: r?.active_last_7d ?? null,+ new_this_week: r?.new_this_week ?? null,+ growth_rate: r?.growth_rate ?? null,+ active_rate: r?.active_rate ?? null,+ signal: r?.signal ?? null,+ headline: r?.headline ?? null,+ confidence: r?.confidence ?? null,+ }),+ },+// ── Volume / Activity Feed (keep the live feed alive) ─────────────────────{id: 'dance-tip-vol-1',@@ -580,17 +693,33 @@ const SELF_ENDPOINTS = [enabled: true,extractSignal: (r) => ({ alive: Array.isArray(r?.skills), count: r?.skills?.length }),},+ // ── Pay-By-Name Resolution Health (USE-054) ───────────────────────────────+ // Canary in front of the name → on-chain address resolver that every "send+ // USDC to a name" flow depends on (SDK payByName(), /pay studio, profile pay+ // button). Every 10 min run() resolves a KNOWN name — the platform's own SNS+ // parent domain (<PARENT_LABEL>.sol) via the FREE GET resolve path — and+ // asserts the registry returns a valid, on-curve Solana wallet (and, when+ // X402_PAY_BY_NAME_EXPECTED_ADDRESS is set, that it MATCHES that wallet — an+ // anti-poisoning check that catches the domain repointing between deploys).+ // The resolve path is free, so this moves no funds (amountAtomic always 0);+ // run() owns the OK/verified classification so a 404 is recorded as unhealthy+ // rather than the generic loop's false "free success". Value sink:+ // pay_by_name_resolution_log (time-series) + Redis x402:pay-by-name:{latest,+ // alert}. Full implementation in ./pipelines/pay-by-name-resolver.js.{- id: 'health-pay-by-name',- name: 'Health: pay-by-name',+ id: 'pay-by-name-resolution',+ name: 'Pay-By-Name Resolution Health',+ // path is informational — run() owns the free GET resolve call itself.path: '/api/x402/pay-by-name',- method: 'POST',- body: { name: 'three.ws' },- cooldown_s: 600,+ method: 'GET',+ body: null,+ price_atomic: 0, // free resolve-only read — never pays+ cooldown_s: 600, // every 10 minpriority: 45,pipeline: 'health',enabled: true,- extractSignal: (r) => ({ alive: !!r?.address, address: r?.address }),+ run: (ctx) => runPayByNameResolution(ctx),+ extractSignal: null,},{id: 'health-agent-reputation',@@ -604,6 +733,39 @@ const SELF_ENDPOINTS = [enabled: true,extractSignal: (r) => ({ alive: r !== null }),},++ // ── Active Agent Reputation Sweep (USE-055) ───────────────────────────────+ // Pays one real $0.01 USDC call to the POST sweep mode of+ // /api/x402/agent-reputation, scoring the 20 most recently active three.ws+ // agents in a single request (vs paying per agent). The endpoint synthesizes+ // each 0..100 trust score from real on-chain pump.fun agent-payments activity,+ // distribute/buyback success, and signed Solana attestations. extractSignal+ // lifts { count, avg_score, flagged_count } + the flagged agent ids into+ // x402_autonomous_log.signal_data so platform-trust monitoring (and ops) can+ // watch the fleet's average reputation and catch a spike in low-trust agents+ // (score < 30) straight off the autonomous log. Cooldown 1800s (30 min) →+ // reputation is a slow-moving, audit-style signal; ≤ $0.48/day, well under+ // the loop's daily cap.+ {+ id: 'agent-reputation-active-sweep',+ name: 'Active Agent Reputation Sweep',+ path: '/api/x402/agent-reputation',+ method: 'POST',+ body: { mode: 'sweep', limit: 20 },+ cooldown_s: 1800,+ priority: 58,+ pipeline: 'health',+ enabled: true,+ extractSignal: (r) => ({+ count: r?.count ?? 0,+ avg_score: r?.avg_score ?? null,+ flagged_count: r?.flagged_count ?? 0,+ flagged_agent_ids: Array.isArray(r?.flagged)+ ? r.flagged.map((a) => a?.agent_id).filter(Boolean)+ : [],+ }),+ },+{id: 'health-symbol-avail',name: 'Health: symbol-availability',@@ -654,6 +816,43 @@ const SELF_ENDPOINTS = [}),},+ // ── MCP Tool Catalog Sync Probe (USE-061) ────────────────────────────────+ // Pays $0.001 USDC hourly to POST /api/x402/mcp-tool-catalog with+ // body { mode: 'sync' }, which runs the live catalog diff/persist logic+ // (the endpoint defaults 'sync' to discover mode) and returns+ // { total_tools, removed_tools[], new_tools[], changed_tools[], ts }.+ // extractSignal maps to { tool_count, missing_count, last_sync }:+ // tool_count = live advertised catalog size+ // missing_count = count of registered-but-vanished tools (the+ // degradation signal — endpoint logged + deactivated+ // them in mcp_tool_registry)+ // last_sync = the sync timestamp+ // A non-zero missing_count means a deploy silently dropped a capability+ // agents may already depend on. Hourly cadence → ≤24 probes/day ≈+ // $0.024/day, bounded by the daily cap.+ // Downstream: mcp_tool_registry — feature-flag source agents read to+ // discover newly-shipped MCP capabilities.+ {+ id: 'mcp-tool-catalog-sync',+ name: 'MCP Tool Catalog Sync Probe',+ path: '/api/x402/mcp-tool-catalog',+ method: 'POST',+ body: { mode: 'sync' },+ cooldown_s: 3600, // hourly — MCP catalog changes only on deploy+ priority: 54,+ pipeline: 'health',+ enabled: true,+ extractSignal: (r) => ({+ tool_count: r?.total_tools ?? null,+ missing_count: Array.isArray(r?.removed_tools) ? r.removed_tools.length : 0,+ last_sync: r?.ts ?? null,+ new_count: Array.isArray(r?.new_tools) ? r.new_tools.length : 0,+ changed_count: Array.isArray(r?.changed_tools) ? r.changed_tools.length : 0,+ priced_tools: r?.priced_tools ?? null,+ removed_tools: Array.isArray(r?.removed_tools) ? r.removed_tools : [],+ }),+ },+// ── MCP Health: Solana agent registration canary ──────────────────────────// Verifies the server-custodial Solana registration subsystem end-to-end by// resolving a known canary agent's on-chain Metaplex Agent Registry record@@ -768,17 +967,52 @@ const SELF_ENDPOINTS = [},// ── Sniper Pipeline Support ────────────────────────────────────────────────+ // Pump Launch Monitor: Recent Launches (USE-046) ─────────────────────────+ // Pays $0.02 USDC to GET /api/x402/pump-agent-audit?limit=10&sort=newest for+ // the 10 freshest pump.fun bonding-curve tokens. extractSignal distills the+ // live cohort into { count, newest_mint, newest_name, newest_symbol,+ // avg_initial_liquidity, max_initial_liquidity, agent_token_count }. As a+ // `sniper` pipeline entry the signal lands in oracle_intel_signals (topic+ // 'pump-launch-monitor') so the oracle gate can compare any candidate mint's+ // initial liquidity against the running cohort baseline. storeValue appends+ // the full cohort to pump_launch_snapshots for the sniper-screening surface.+ // Cooldown 300 s (5 min) — fast enough to catch the earliest sniping window+ // on new launches. At $0.02/call → $5.76/day at continuous pace, well below+ // the loop's daily cap (the cooldown keeps actual spend much lower).+ {+ id: 'pump-launch-monitor',+ name: 'Pump Launch Monitor: Recent Launches',+ // GET with query params; the autonomous loop appends them to the URL.+ path: '/api/x402/pump-agent-audit?limit=10&sort=newest',+ method: 'GET',+ body: null,+ cooldown_s: 300,+ priority: 88,+ pipeline: 'sniper',+ enabled: true,+ extractSignal: (r) => classifyLaunchMonitor(r),+ storeValue: (ctx) => storePumpLaunchSnapshot(ctx),+ },+ // Legacy entry kept for backwards-compat with existing cooldown keys, but+ // corrected to use the real GET interface and extractSignal shape.+ // Now superseded by pump-launch-monitor above (which has priority 88 vs 75+ // so the loop will run the new one first on each tick). Consider removing+ // this entry once pump-launch-monitor has several days of clean logs.{id: 'sniper-pump-audit-latest',- name: 'Pump Agent Audit: latest 5',- path: '/api/x402/pump-agent-audit',- method: 'POST',- body: { limit: 5 },+ name: 'Pump Agent Audit: latest 5 (legacy)',+ path: '/api/x402/pump-agent-audit?limit=5&sort=newest',+ method: 'GET',+ body: null,cooldown_s: 600,priority: 75,pipeline: 'sniper',enabled: true,- extractSignal: (r) => ({ count: r?.audits?.length, top_score: r?.audits?.[0]?.score }),+ extractSignal: (r) => ({+ count: r?.count ?? r?.launches?.length ?? null,+ newest_mint: r?.newest_mint ?? null,+ avg_initial_liquidity: r?.avg_initial_liquidity_sol ?? null,+ }),},// Token Intel Pre-Snipe Gate (USE-023) — pays the $0.01 USDC Token Oracle// (/api/x402/token-intel) for the freshest pump.fun mints the sniper is about@@ -980,6 +1214,46 @@ const SELF_ENDPOINTS = [run: (ctx) => forgeContentGeneration(ctx),},+ // ── Forge: Content Generation Health (USE-072) ─────────────────────────────+ // A lightweight liveness+latency canary for the generative AI lane every Forge+ // job depends on, distinct from the hourly prop generator above. Pays the floor+ // ($0.001) to /api/x402/forge in health_check mode, which runs ONE fast, real+ // text completion over the platform's free-first LLM provider chain (no mesh+ // reconstruction) and returns a measured { generated, latency_ms, token_count }+ // verdict. extractSignal lifts that verdict into x402_autonomous_log.signal_data;+ // storeValue raises a forge performance alert (Redis x402:forge-health:alert,+ // mirroring the wallet-balance alert convention) whenever the probe is slow+ // (>5s) or the generator failed, and clears it once healthy — the on-call+ // surface reads that key to know the content path degraded before users do.+ // Cooldown 600s -> one probe every 10 min ~= $0.144/day, well under the loop cap.+ {+ id: 'forge-content-health',+ name: 'Forge: Content Generation Health',+ path: '/api/x402/forge',+ method: 'POST',+ body: { mode: 'health_check', type: 'text', prompt: 'Write one sentence about Solana.' },+ price_atomic: 1000, // $0.001 — the health_check floor price the endpoint quotes+ cooldown_s: 600, // 10 min+ priority: 50,+ pipeline: 'health',+ enabled: true,+ extractSignal: (r) => {+ const latencyMs = typeof r?.latency_ms === 'number' ? r.latency_ms : null;+ return {+ generated: r?.generated === true,+ latency_ms: latencyMs,+ token_count: r?.token_count ?? null,+ within_budget: r?.within_budget ?? null,+ provider: r?.provider ?? null,+ model: r?.model ?? null,+ // Performance verdict consumed by storeValue + the status surface.+ slow: latencyMs != null ? latencyMs > FORGE_HEALTH_BUDGET_MS : null,+ error: r?.error ?? null,+ };+ },+ storeValue: (ctx) => recordForgeHealthAlert(ctx),+ },+// ── Bazaar Discovery Warmup (USE-008) ──────────────────────────────────────// Sweeps 15 discovery categories through the x402 Bazaar MCP server// (/api/mcp-bazaar → search_services) at $0.001/call, validating that the@@ -1245,6 +1519,34 @@ const SELF_ENDPOINTS = [extractSignal: null,},+ // ── Club Cover Charge Revenue Summary (USE-067) ───────────────────────────+ // Pays $0.01 USDC every 15 min to POST /api/x402/club-cover with mode:"revenue"+ // to read the 7-day cover-charge and floor revenue across all clubs. The+ // response aggregates:+ // • door revenue — every settled payment_settled event on the club-cover route,+ // queried from x402_audit_log (the canonical settlement ledger)+ // • floor revenue per act — settled dance tips in club_tips grouped by dancer,+ // each act being one identifiable "club" in the venue+ // extractSignal lifts { total_usdc, top_club_id, top_club_revenue } into+ // x402_autonomous_log.signal_data so dashboards can read social-economy health+ // off the autonomous log directly. The `volume` pipeline tag keeps it out of+ // the oracle dedup path — cover revenue is a lagging metric, not a real-time+ // oracle price signal. Cooldown 900 s → 96 reads/day ≈ $0.96/day, well under+ // the loop's $5/day cap. The data source is the live DB (never cached), so+ // a drop in total_usdc within one 15-min window surfaces a revenue anomaly.+ {+ id: 'club-cover-revenue-summary',+ name: 'Club Cover Charge Revenue Summary',+ path: '/api/x402/club-cover',+ method: 'POST',+ body: { mode: 'revenue', period: '7d' },+ cooldown_s: 900,+ priority: 68,+ pipeline: 'volume',+ enabled: true,+ extractSignal: (r) => extractCoverRevenueSignal(r),+ },+// ── Avatar Optimization Pipeline (nightly MCP Health) ─────────────────────// Pays $0.001 USDC to run optimize_model analysis on the top 50 most-viewed// public avatars. Results upserted to avatar_optimization_results per avatar_id.@@ -1646,6 +1948,94 @@ const SELF_ENDPOINTS = [run: (ctx) => runReservationLeakDetector(ctx),extractSignal: null,},++ // ── Platform Revenue Analytics (USE-039, Oracle pipeline) ─────────────────+ // Pays $0.001 USDC every 15 min to POST /api/x402/analytics+ // ({ report:"revenue", period:"24h" }) and pulls the last 24 hours of real+ // platform revenue from the settled-payment ledger (x402_audit_log) plus the+ // measured settlement fee from cross_chain_cost_comparison. extractSignal lifts+ // { total_usd, top_endpoint, fee_collected } into oracle_intel_signals with+ // topic 'platform-revenue' so the sniper gate sees live platform health data.+ // The oracle upsert carries signal ('healthy'|'active'|'quiet') and a human+ // headline so the status dashboard can render it without re-querying.+ // Cooldown 900s (15 min) → 96 calls/day ≈ $0.096/day, well inside the loop cap.+ // Downstream consumers:+ // • oracle_intel_signals WHERE topic = 'platform-revenue' — sniper gate health+ // • x402_autonomous_log signal_data — autonomous loop status view+ {+ id: 'platform-revenue-analytics',+ name: 'Platform Revenue Analytics',+ path: '/api/x402/analytics',+ method: 'POST',+ body: { report: 'revenue', period: '24h' },+ cooldown_s: 900,+ priority: 87,+ pipeline: 'oracle',+ enabled: true,+ extractSignal: (r) => {+ const grossUsd = parseFloat(r?.totals?.gross_usd || '0');+ const feeUsd = parseFloat(r?.fee_splits?.settlement_fee_usd || '0');+ const payments = r?.totals?.total_payments ?? 0;+ const topEndpoint = r?.top_endpoint?.endpoint ?? null;+ const topCount = r?.top_endpoint?.count ?? 0;+ const topGross = r?.top_endpoint?.gross_usd ?? '0';+ const signal = grossUsd >= 0.10 ? 'healthy' : payments > 0 ? 'active' : 'quiet';+ const headline = payments > 0+ ? `Platform earned $${grossUsd.toFixed(4)} gross in 24h across ${payments} payments${topEndpoint ? `; top: ${topEndpoint}` : ''}`+ : 'No settled payments in the last 24h';+ return {+ topic: 'platform-revenue',+ signal,+ headline,+ confidence: 1.0,+ price_usd: grossUsd,+ total_usd: grossUsd.toFixed(6),+ top_endpoint: topEndpoint,+ top_endpoint_count: topCount,+ top_endpoint_gross: topGross,+ fee_collected: feeUsd.toFixed(6),+ net_platform_usd: r?.totals?.net_platform_usd ?? null,+ total_payments: payments,+ unique_payers: r?.totals?.unique_payers ?? 0,+ period: r?.period ?? '24h',+ generated_at: r?.generated_at ?? null,+ };+ },+ },+ // ── Sniper Trade Performance Analytics (USE-041) ──────────────────────────+ // Pays $0.005 USDC every 5 minutes to POST /api/x402/analytics with+ // { report: "sniper_trades", period: "24h" } to fetch the autonomous sniper's+ // real trade performance from the closed agent_sniper_positions ledger: win rate,+ // average profit (SOL + USDC at the live SOL/USD quote), worst loss, and total+ // SOL volume snipped. The extracted signal is actionable: if win_rate drops below+ // 40% across ≥ 5 closed trades the endpoint itself raises a low-win-rate alert+ // in signal_data.alert — the strategy auto-tuner reads that field to pull back+ // sizing or tighten entry filters before the next snipe. extractSignal lifts the+ // headline metrics into x402_autonomous_log.signal_data; storeValue appends every+ // snapshot to the sniper_trade_analytics time series (used by the performance+ // dashboard). As a `sniper` pipeline entry the signal is NOT upserted into+ // oracle_intel_signals (win rate is a trailing metric, not a real-time oracle+ // price feed). Cooldown 300s → 288 reads/day ≈ $1.44/day, well under the loop cap.+ // Downstream consumers: sniper_trade_analytics time series + the alert field in+ // x402_autonomous_log.signal_data (strategy auto-tuner, ops dashboard).+ {+ id: 'sniper-trade-analytics',+ name: 'Sniper Trade Performance Analytics',+ path: '/api/x402/analytics',+ method: 'POST',+ body: { report: 'sniper_trades', period: '24h' },+ cooldown_s: 300,+ priority: 72,+ pipeline: 'sniper',+ enabled: true,+ extractSignal: (r) => classifySniperSignal(r),+ storeValue: async ({ sql, responseBody, signalData, runId }) => {+ if (!sql) return;+ const report = responseBody || signalData;+ if (!report || report.sample_size == null) return;+ await insertSniperAnalytics(sql, report, { runId, source: 'x402-autonomous' });+ },+ },];// ── External registry ─────────────────────────────────────────────────────────diff --git a/api/_lib/x402/pipelines/volume-bootstrap-loop.js b/api/_lib/x402/pipelines/volume-bootstrap-loop.jsindex 9c46d6880..571293142 100644--- a/api/_lib/x402/pipelines/volume-bootstrap-loop.js+++ b/api/_lib/x402/pipelines/volume-bootstrap-loop.js@@ -74,7 +74,7 @@ export const VOLUME_ENDPOINTS = [{ key: 'token-intel', name: 'Token Intel', path: '/api/x402/token-intel', method: 'POST', body: { mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', network: 'mainnet' } },{ key: 'fact-check', name: 'Fact Check', path: '/api/x402/fact-check', method: 'POST', body: { claim: 'The sky is blue' } },{ key: 'symbol-availability', name: 'Symbol Availability', path: '/api/x402/symbol-availability', method: 'POST', body: { symbol: 'HEALTH' } },- { key: 'pay-by-name', name: 'Pay By Name', path: '/api/x402/pay-by-name', method: 'POST', body: { name: 'three.ws' } },+ { key: 'pay-by-name', name: 'Pay By Name', path: '/api/x402/pay-by-name?name=threews.sol', method: 'GET', body: null },{ key: 'skill-marketplace', name: 'Skill Marketplace', path: '/api/x402/skill-marketplace', method: 'GET', body: null },{ key: 'agent-reputation', name: 'Agent Reputation', path: '/api/x402/agent-reputation', method: 'GET', body: null },{ key: 'club-cover', name: 'Club Cover Charge', path: '/api/x402/club-cover', method: 'POST', body: { club: 'canary_test' } },diff --git a/api/_lib/x402/pump-launch-monitor.js b/api/_lib/x402/pump-launch-monitor.jsnew file mode 100644index 000000000..e004f2c1b--- /dev/null+++ b/api/_lib/x402/pump-launch-monitor.js@@ -0,0 +1,141 @@+// api/_lib/x402/pump-launch-monitor.js+//+// Shared logic for the Pump Launch Monitor (Recent Launches) x402 use case.+//+// The autonomous loop pays /api/x402/pump-agent-audit in LIST mode+// (?limit=N&sort=newest) for the freshest pump.fun launches, then derives a+// compact sniper-screening signal from the response. This module owns:+//+// 1. classifyLaunchMonitor() — the extractSignal projection+// { count, newest_mint, newest_name, newest_symbol, avg_initial_liquidity }+// shared by the registry entry (→ x402_autonomous_log.signal_data) and the+// snapshot writer so both always agree on shape.+// 2. ensurePumpLaunchSnapshotSchema() / storePumpLaunchSnapshot() — the value+// sink: every paid snapshot is appended to pump_launch_snapshots (a time+// series the sniper-screening surface and liquidity-baseline reads consume).+//+// Why this is actionable: a fresh launch whose initial bonding-curve liquidity+// sits well above the rolling average of its cohort is a high-conviction snipe+// candidate; one far below is noise. avg_initial_liquidity is that per-cohort+// baseline, captured at paid-call time so the screening read never re-hits the+// live pump.fun feed.++function num(v) {+ const n = typeof v === 'string' ? parseFloat(v) : v;+ return Number.isFinite(n) ? n : null;+}++/**+ * Project a /api/x402/pump-agent-audit LIST response into the screening signal.+ * Tolerant of partial/empty payloads (feed outage → count 0, null fields) so it+ * never throws inside the loop's extractSignal call.+ *+ * @param {object|null} r raw list-mode JSON response+ * @returns {{+ * count: number, newest_mint: string|null, newest_name: string|null,+ * newest_symbol: string|null, avg_initial_liquidity: number|null,+ * max_initial_liquidity: number|null, agent_token_count: number+ * }}+ */+export function classifyLaunchMonitor(r) {+ const o = r || {};+ const launches = Array.isArray(o.launches) ? o.launches : [];+ const liq = launches.map((l) => num(l?.liquidity_sol)).filter((v) => v != null && v > 0);+ const avg = liq.length ? liq.reduce((a, b) => a + b, 0) / liq.length : null;+ const max = liq.length ? Math.max(...liq) : null;+ const agentTokens = launches.reduce((acc, l) => acc + (l?.is_agent_token ? 1 : 0), 0);+ return {+ count: Number.isFinite(o.count) ? o.count : launches.length,+ newest_mint: o.newest_mint || launches[0]?.mint || null,+ newest_name: o.newest_name || launches[0]?.name || null,+ newest_symbol: o.newest_symbol || launches[0]?.symbol || null,+ // Endpoint pre-computes the cohort average; recompute defensively when an+ // older/partial payload omits it so the signal is never silently null.+ avg_initial_liquidity: num(o.avg_initial_liquidity_sol) ?? avg,+ max_initial_liquidity: num(o.max_initial_liquidity_sol) ?? max,+ agent_token_count: agentTokens,+ };+}++// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).+let _schemaReady = false;++/**+ * Create the snapshot time-series table if absent. Idempotent; the in-process+ * guard avoids re-issuing the DDL after the first successful call.+ * @param {Function} sql tagged-template sql client (api/_lib/db.js)+ */+export async function ensurePumpLaunchSnapshotSchema(sql) {+ if (_schemaReady || !sql) return;+ await sql`+ CREATE TABLE IF NOT EXISTS pump_launch_snapshots (+ id bigserial PRIMARY KEY,+ ts timestamptz NOT NULL DEFAULT now(),+ network text,+ sort text,+ launch_count int,+ agent_token_count int,+ newest_mint text,+ newest_name text,+ newest_symbol text,+ avg_initial_liquidity_sol double precision,+ max_initial_liquidity_sol double precision,+ launches jsonb,+ run_id uuid,+ source text NOT NULL DEFAULT 'x402-autonomous'+ )+ `;+ await sql`+ CREATE INDEX IF NOT EXISTS pump_launch_snapshots_ts_desc+ ON pump_launch_snapshots (ts DESC)+ `;+ _schemaReady = true;+}++/**+ * Append one recent-launch snapshot to the time series. Wired as the registry+ * entry's storeValue hook; the loop wraps it so a DB fault can never crash the+ * tick. Skips writing an empty snapshot (feed outage) so the baseline series+ * only ever holds real cohorts.+ *+ * @param {object} ctx { sql, responseBody, signalData, runId }+ */+export async function storePumpLaunchSnapshot({ sql, responseBody, signalData, runId }) {+ if (!sql) return;+ const r = responseBody || {};+ const v = signalData || classifyLaunchMonitor(r);+ if (!v.count) return; // never persist an empty/failed snapshot+ await ensurePumpLaunchSnapshotSchema(sql);+ const launches = Array.isArray(r.launches) ? r.launches : [];+ await sql`+ INSERT INTO pump_launch_snapshots+ (ts, network, sort, launch_count, agent_token_count,+ newest_mint, newest_name, newest_symbol,+ avg_initial_liquidity_sol, max_initial_liquidity_sol,+ launches, run_id, source)+ VALUES+ (now(), ${r.network || 'mainnet'}, ${r.sort || 'newest'},+ ${v.count}, ${v.agent_token_count || 0},+ ${v.newest_mint}, ${v.newest_name}, ${v.newest_symbol},+ ${v.avg_initial_liquidity}, ${v.max_initial_liquidity},+ ${JSON.stringify(launches)}, ${runId || null}, ${'x402-autonomous'})+ `;+}++/**+ * Latest stored launch snapshot, or null when the series is empty. Reader for the+ * sniper-screening surface and liquidity-baseline lookups.+ * @param {Function} sql+ */+export async function getLatestLaunchSnapshot(sql) {+ if (!sql) return null;+ const rows = await sql`+ SELECT ts, network, sort, launch_count, agent_token_count,+ newest_mint, newest_name, newest_symbol,+ avg_initial_liquidity_sol, max_initial_liquidity_sol, launches+ FROM pump_launch_snapshots+ ORDER BY ts DESC+ LIMIT 1+ `;+ return rows[0] || null;+}diff --git a/api/_lib/x402/pump-trending-score.js b/api/_lib/x402/pump-trending-score.jsnew file mode 100644index 000000000..192af46d0--- /dev/null+++ b/api/_lib/x402/pump-trending-score.js@@ -0,0 +1,220 @@+// api/_lib/x402/pump-trending-score.js+//+// Pump.fun trending score feed — the data engine behind the `pump_trending`+// topic of POST /api/x402/crypto-intel.+//+// Produces a structured market signal from the live pump.fun trending board:+// • Top N coins by market cap from the frontend-api-v3 board+// • Per-coin buy/sell pressure derived from real swap-API trade feeds+// • Whale buy detection (trades ≥ WHALE_SOL_THRESHOLD SOL)+// • An aggregate bullish/bearish/neutral verdict with confidence score+//+// Pure scoring helpers (buildPumpTrendingSignal) take plain data so they are+// unit-testable without network. detectPumpTrending() wires them to live feeds.++const PUMP_FRONTEND_BASE =+ process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';+const PUMP_SWAP_BASE = process.env.PUMP_SWAP_BASE || 'https://swap-api.pump.fun';++// Trades at or above this SOL amount count as "whale" activity.+export const WHALE_SOL_THRESHOLD =+ Number(process.env.PUMP_TRENDING_WHALE_SOL || 5);++// How many top-ranked coins to fetch.+export const CANDIDATES =+ Number(process.env.PUMP_TRENDING_CANDIDATES || 20);++// How many of those top coins to fetch trades for (trade fetch is slow/costly).+export const TRADE_COINS =+ Number(process.env.PUMP_TRENDING_TRADE_COINS || 5);++// Trades per coin fetched from swap-api.+export const TRADES_PER_COIN =+ Number(process.env.PUMP_TRENDING_TRADES_PER_COIN || 30);++// Concurrency limit for trade fetches (avoid hammering swap-api).+const TRADE_CONCURRENCY = Math.min(TRADE_COINS, 5);++// ── pure helpers ──────────────────────────────────────────────────────────────++function num(v) {+ const n = typeof v === 'string' ? parseFloat(v) : v;+ return Number.isFinite(n) ? n : null;+}++/**+ * Given arrays of raw trade objects (from swap-api v2) for multiple coins,+ * compute aggregate buy pressure and surface whale buys.+ *+ * @param {Array<{mint: string, trades: object[]}>} coinTrades+ * @returns {{ totalBuys, totalSells, totalVolumeSol, buyPressure, whaleBuys }}+ */+export function scorePressure(coinTrades) {+ let totalBuys = 0, totalSells = 0, totalVolumeSol = 0;+ const whaleBuys = [];++ for (const { mint, trades } of coinTrades) {+ for (const t of trades) {+ const isBuy = String(t.type ?? t.txType ?? '').toLowerCase() === 'buy';+ const sol = num(t.amountSol) ?? 0;+ if (isBuy) { totalBuys++; totalVolumeSol += sol; }+ else { totalSells++; }+ if (isBuy && sol >= WHALE_SOL_THRESHOLD) {+ whaleBuys.push({+ mint,+ sol_amount: Math.round(sol * 1000) / 1000,+ usd_amount: num(t.amountUsd),+ trader: t.userAddress ?? t.user ?? null,+ });+ }+ }+ }++ const totalTrades = totalBuys + totalSells;+ const buyPressure = totalTrades > 0 ? totalBuys / totalTrades : 0.5;+ return { totalBuys, totalSells, totalVolumeSol, buyPressure, whaleBuys };+}++/**+ * Build a crypto-intel-compatible signal object from scored pressure data.+ * Pure — no network calls, unit-testable.+ *+ * @param {object[]} coins Normalized trending coin list (sorted by rank)+ * @param {object} score Output of scorePressure()+ * @returns {object} Full crypto-intel response for topic=pump_trending+ */+export function buildPumpTrendingSignal(coins, score) {+ const { totalBuys, totalSells, buyPressure, totalVolumeSol, whaleBuys } = score;+ const topSymbol = coins[0]?.symbol || 'PUMP';+ const topMcap = coins[0]?.market_cap_usd;+ const topMcapStr = topMcap != null+ ? topMcap >= 1_000_000 ? `$${(topMcap / 1_000_000).toFixed(2)}M`+ : `$${(topMcap / 1000).toFixed(0)}k`+ : 'N/A';++ let signal, headline, rationale;++ if (buyPressure >= 0.65) {+ signal = 'bullish';+ headline = `Pump.fun trending: ${topSymbol} leads at ${topMcapStr} mcap — ${Math.round(buyPressure * 100)}% buy pressure`;+ rationale = `${totalBuys} buys vs ${totalSells} sells across the top ${TRADE_COINS} trending tokens. ` ++ `${whaleBuys.length} whale buy${whaleBuys.length !== 1 ? 's' : ''} detected (≥${WHALE_SOL_THRESHOLD} SOL each). ` ++ `Strong demand signals near-term momentum.`;+ } else if (buyPressure <= 0.40) {+ signal = 'bearish';+ headline = `Pump.fun trending: ${topSymbol} tops chart at ${topMcapStr} — sellers outweigh buyers`;+ rationale = `${totalSells} sells vs ${totalBuys} buys across the top ${TRADE_COINS} trending tokens. ` ++ `Sell pressure is elevated; watch for further retracement before positioning.`;+ } else {+ signal = 'neutral';+ headline = `Pump.fun trending: ${topSymbol} at ${topMcapStr} mcap — balanced flow (${Math.round(buyPressure * 100)}% buys)`;+ rationale = `Trade flow is mixed across the top ${TRADE_COINS} trending tokens (${totalBuys} buys, ${totalSells} sells). ` ++ `No clear directional conviction; await a decisive move before acting.`;+ }++ // Confidence scales with distance from 50/50 — a strongly skewed order book+ // is more informative than a balanced one.+ const confidence = Math.round(+ Math.min(0.92, 0.55 + Math.abs(buyPressure - 0.5) * 0.8) * 100,+ ) / 100;++ return {+ topic: 'pump_trending',+ headline,+ signal,+ price_usd: null,+ change_24h: null,+ rationale,+ confidence,+ buy_pressure: Math.round(buyPressure * 1000) / 1000,+ total_volume_sol: Math.round(totalVolumeSol * 1000) / 1000,+ whale_buys: whaleBuys.slice(0, 10),+ whale_buy_count: whaleBuys.length,+ trending_mints: coins.slice(0, 10).map((c) => ({+ mint: c.mint,+ symbol: c.symbol,+ name: c.name,+ market_cap_usd: c.market_cap_usd,+ rank: c.rank,+ })),+ top_mint: coins[0]?.mint ?? null,+ ts: new Date().toISOString(),+ };+}++// ── live feed fetchers ────────────────────────────────────────────────────────++async function fetchTrendingCoins(limit) {+ const url = new URL('/coins', PUMP_FRONTEND_BASE);+ url.searchParams.set('offset', '0');+ url.searchParams.set('limit', String(limit));+ url.searchParams.set('sort', 'market_cap');+ url.searchParams.set('order', 'DESC');+ url.searchParams.set('includeNsfw', 'false');+ const r = await fetch(url, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(7000),+ });+ if (!r.ok) return null;+ const body = await r.json().catch(() => null);+ const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;+ if (!Array.isArray(coins)) return null;+ return coins+ .filter((c) => c && typeof c.mint === 'string' && c.mint.length >= 32)+ .map((c, i) => ({+ mint: c.mint,+ symbol: c.symbol || '?',+ name: c.name || c.symbol || '',+ market_cap_usd: num(c.usd_market_cap),+ market_cap_sol: num(c.market_cap),+ rank: i + 1,+ complete: !!c.complete,+ }));+}++async function fetchCoinTrades(mint, limit) {+ const r = await fetch(`${PUMP_SWAP_BASE}/v2/coins/${mint}/trades?limit=${limit}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(6000),+ });+ if (!r.ok) return [];+ const body = await r.json().catch(() => null);+ return Array.isArray(body) ? body : Array.isArray(body?.trades) ? body.trades : [];+}++/**+ * Main entry point: fetch live pump.fun data and return a crypto-intel signal.+ * Throws a 503-tagged error when the upstream board is unavailable (so the+ * paidEndpoint wrapper withholds settlement — the caller is never charged for+ * an empty verdict).+ */+export async function detectPumpTrending() {+ const coins = await fetchTrendingCoins(CANDIDATES).catch(() => null);+ if (!coins || coins.length === 0) {+ throw Object.assign(+ new Error('pump.fun trending board is temporarily unavailable'),+ { status: 503, code: 'data_unavailable' },+ );+ }++ // Fetch trades for the top TRADE_COINS in capped concurrency.+ const topCoins = coins.slice(0, TRADE_COINS);+ const coinTrades = [];++ // Simple concurrency pool — chunk into batches of TRADE_CONCURRENCY.+ for (let i = 0; i < topCoins.length; i += TRADE_CONCURRENCY) {+ const batch = topCoins.slice(i, i + TRADE_CONCURRENCY);+ const results = await Promise.allSettled(+ batch.map((c) => fetchCoinTrades(c.mint, TRADES_PER_COIN)),+ );+ results.forEach((res, j) => {+ coinTrades.push({+ mint: batch[j].mint,+ trades: res.status === 'fulfilled' ? res.value : [],+ });+ });+ }++ const score = scorePressure(coinTrades);+ return buildPumpTrendingSignal(coins, score);+}diff --git a/api/x402/analytics.js b/api/x402/analytics.jsindex 2a4826fb6..35f1d56f3 100644--- a/api/x402/analytics.js+++ b/api/x402/analytics.js@@ -32,25 +32,31 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';import { sql } from '../_lib/db.js';+import { solUsdPrice } from '../_lib/avatar-wallet.js';+import { buildRevenueReport } from '../_lib/x402/revenue-analytics.js';+import { buildSniperAnalytics } from '../_lib/x402/sniper-analytics-store.js';const ROUTE = '/api/x402/analytics';const DESCRIPTION =- 'three.ws Social-Economy Analytics — pay $0.005 USDC per call for a live, ' +- 'aggregated view of platform social activity. The "clubs" report returns the ' +- 'Pole Club economy over the requested window: active stages, distinct patron ' +- 'members, tip count + USDC volume, cover charges collected at the door, and a ' +- 'fastest-growing-stage leaderboard. Read live from the on-chain-settled tip + ' +- 'cover ledgers. Pay-per-call in USDC on Solana mainnet or Base.';+ 'three.ws Economy Analytics — pay $0.005 USDC per call for a live, aggregated ' ++ 'view of platform activity. "clubs": Pole Club economy — active stages, patrons, ' ++ 'tip volume, cover charges, fastest-growing leaderboard. "agent_leaderboard": top ' ++ 'agents by USDC spend over a trailing window. "marketplace": catalog stats — ' ++ 'active listing count, price distribution normalised to USD + SOL at the live ' ++ 'rate, new listings in the window, and the most-viewed / most-forked listing. ' ++ 'All numbers are read live from the real ledgers and catalog tables.';// Supported reports + period windows. Both are strict whitelists — a value// outside the set is rejected BEFORE settlement (the buyer is never charged for// a report we can't produce).-const REPORTS = new Set(['clubs', 'agent_leaderboard']);+const REPORTS = new Set(['clubs', 'agent_leaderboard', 'marketplace', 'revenue', 'sniper_trades']);// period → window in seconds (null = all-time, no time filter).+// '6h' is used by the revenue report (matches its resolvePeriod keys).const PERIODS = {'1h': 3600,+ '6h': 21600,'24h': 86400,'7d': 604800,'30d': 2592000,@@ -63,15 +69,15 @@ const INPUT_SCHEMA = {properties: {report: {type: 'string',- enum: ['clubs', 'agent_leaderboard'],+ enum: ['clubs', 'agent_leaderboard', 'marketplace', 'revenue', 'sniper_trades'],default: 'clubs',description: 'Which analytics report to return.',},period: {type: 'string',- enum: ['1h', '24h', '7d', '30d', 'all'],+ enum: ['1h', '6h', '24h', '7d', '30d', 'all'],default: '24h',- description: 'Aggregation window (clubs report).',+ description: 'Aggregation window (clubs + revenue reports).',},limit: {type: 'integer',@@ -87,6 +93,12 @@ const INPUT_SCHEMA = {default: 7,description: 'Trailing window in days (agent_leaderboard report).',},+ network: {+ type: 'string',+ enum: ['mainnet', 'devnet', 'all'],+ default: 'mainnet',+ description: 'Network filter (sniper_trades report).',+ },},};@@ -274,6 +286,265 @@ async function clubsReport(seconds) {};}+function clampInt(v, { min, max, fallback }) {+ const n = Math.floor(Number(v));+ if (!Number.isFinite(n)) return fallback;+ return Math.max(min, Math.min(max, n));+}++// Top agents by completed x402 spend (as the hiring/paying side) over a trailing+// window, read live from the real agent-to-agent hire ledger. `usd` is the human+// dollar value recorded at settle time; when absent we fall back to+// amount_atomics (USDC 6-decimal) so spend is never under-counted. window_days is+// bound, never interpolated. Returns the actionable shape partnership outreach+// consumes: the ranked agents with their hire counts + payout addresses.+async function agentLeaderboardReport(limit, windowDays) {+ const rows = await sql`+ select+ h.hirer_agent_id as agent_id,+ coalesce(ai.name, 'Agent') as name,+ ai.meta->>'solana_address' as solana_address,+ sum(coalesce(h.usd, h.amount_atomics::numeric / 1e6)) as spend_usdc,+ count(*)::int as hires,+ max(h.created_at) as last_hire_at+ from agent_hires h+ left join agent_identities ai on ai.id = h.hirer_agent_id+ where h.status = 'completed'+ and h.created_at >= now() - (${windowDays}::int * interval '1 day')+ group by h.hirer_agent_id, ai.name, ai.meta->>'solana_address'+ order by spend_usdc desc nulls last, last_hire_at desc+ limit ${limit}+ `.catch(() => []);++ const leaderboard = (rows || []).map((r, i) => ({+ rank: i + 1,+ agent_id: r.agent_id,+ name: r.name || 'Agent',+ solana_address: r.solana_address || null,+ spend_usdc: Number(Number(r.spend_usdc || 0).toFixed(6)),+ hires: Number(r.hires || 0),+ last_hire_at: r.last_hire_at instanceof Date+ ? r.last_hire_at.toISOString()+ : (r.last_hire_at || null),+ }));++ const total_spend_usdc = Number(+ leaderboard.reduce((s, a) => s + a.spend_usdc, 0).toFixed(6),+ );++ return {+ agent_count: leaderboard.length,+ total_spend_usdc,+ leaderboard,+ };+}++// Auto-named / stub agent names excluded from the public marketplace listing+// count — kept in sync with api/marketplace/[action].js so the numbers match+// exactly what a visitor browsing /marketplace sees.+const AGENT_AUTONAMED_RE =+ '^(Agent|My Agent|My First Agent|Demo Agent|Untitled.*|TEST|Test|test|mo[a-z0-9]{4,}|draft-[a-z0-9]+|new_project_[0-9]+|Avatar[ ]*#[0-9a-f]{4,}([ ]*agent)?|https?://.+)$';++// Mints we can normalise to USD at query time.+// Keys are lower-cased for comparison; display form preserved per-row via currencyLabel().+const USDC_MINTS = new Set([+ 'epjfwdd5aufqssqem2qn1xzybapC8G4wEGGkZwyTDt1v', // Solana mainnet USDC+ '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', // Base USDC+]);+const SOL_MINTS = new Set(['native', 'so11111111111111111111111111111111111111112']);++function currencyLabel(mint) {+ const m = String(mint || '').toLowerCase();+ if (USDC_MINTS.has(m)) return 'USDC';+ if (SOL_MINTS.has(m)) return 'SOL';+ return mint && mint.length > 10 ? `${mint.slice(0, 4)}…${mint.slice(-4)}` : String(mint || 'unknown');+}++function roundNum(n, dp) {+ if (n == null || !Number.isFinite(Number(n))) return null;+ const f = 10 ** dp;+ return Math.round(Number(n) * f) / f;+}++// Marketplace catalog stats for the public agent marketplace.+// seconds: null → all-time for new_in_period; integer → published_at window.+async function marketplaceReport(seconds) {+ const publishWindow =+ seconds == null ? sql`true` : sql`ai.published_at >= now() - (${seconds}::int * interval '1 second')`;++ const [[summary], priceRows, [mostViewed], [mostForked]] = await Promise.all([+ sql`+ SELECT+ COUNT(*)::int AS listing_count,+ COUNT(*) FILTER (WHERE ${publishWindow})::int AS new_in_period,+ COALESCE(SUM(ai.views_count), 0)::bigint AS total_views,+ COALESCE(SUM(ai.forks_count), 0)::bigint AS total_forks+ FROM agent_identities ai+ WHERE ai.is_published = true+ AND ai.deleted_at IS NULL+ AND ai.name !~* ${AGENT_AUTONAMED_RE}+ `.catch(() => [{}]),+ sql`+ SELECT+ ap.currency_mint,+ ap.mint_decimals,+ ap.chain,+ COUNT(*)::int AS cnt,+ SUM(ap.amount)::numeric AS sum_amount,+ MIN(ap.amount)::numeric AS min_amount,+ MAX(ap.amount)::numeric AS max_amount+ FROM asset_prices ap+ JOIN agent_identities ai ON ai.id = ap.item_id+ WHERE ap.item_type = 'agent'+ AND ap.is_active = true+ AND ai.is_published = true+ AND ai.deleted_at IS NULL+ AND ai.name !~* ${AGENT_AUTONAMED_RE}+ GROUP BY ap.currency_mint, ap.mint_decimals, ap.chain+ ORDER BY cnt DESC+ `.catch(() => []),+ sql`+ SELECT id, name, category, COALESCE(views_count, 0)::int AS views_count+ FROM agent_identities+ WHERE is_published = true AND deleted_at IS NULL AND name !~* ${AGENT_AUTONAMED_RE}+ ORDER BY views_count DESC NULLS LAST LIMIT 1+ `.catch(() => [null]),+ sql`+ SELECT id, name, category, COALESCE(forks_count, 0)::int AS forks_count+ FROM agent_identities+ WHERE is_published = true AND deleted_at IS NULL AND name !~* ${AGENT_AUTONAMED_RE}+ ORDER BY forks_count DESC NULLS LAST LIMIT 1+ `.catch(() => [null]),+ ]);++ // SOL/USD for price normalisation — fail-soft; SOL listings omitted from the+ // USD average if the price oracle is transiently unavailable.+ let solUsd = null;+ try { solUsd = await solUsdPrice(); } catch { /* decoration only */ }++ let pricedCount = 0;+ let totalUsd = 0;+ let minUsd = null;+ let maxUsd = null;++ const byCurrency = (priceRows || []).map((r) => {+ const decimals = Number(r.mint_decimals ?? 6);+ const scale = 10 ** decimals;+ const cnt = Number(r.cnt);+ const m = String(r.currency_mint || '').toLowerCase();+ const isUsdc = USDC_MINTS.has(m);+ const isSol = SOL_MINTS.has(m);+ const rate = isUsdc ? 1 : (isSol && solUsd ? solUsd : null);+ const avgHuman = Number(r.sum_amount) / cnt / scale;++ if (rate != null) {+ pricedCount += cnt;+ totalUsd += (Number(r.sum_amount) / scale) * rate;+ const lo = (Number(r.min_amount) / scale) * rate;+ const hi = (Number(r.max_amount) / scale) * rate;+ minUsd = minUsd == null ? lo : Math.min(minUsd, lo);+ maxUsd = maxUsd == null ? hi : Math.max(maxUsd, hi);+ }++ return {+ currency: currencyLabel(r.currency_mint),+ currency_mint: r.currency_mint,+ chain: r.chain,+ count: cnt,+ avg_price: roundNum(avgHuman, 6),+ priceable: rate != null,+ };+ });++ const totalPriced = byCurrency.reduce((n, c) => n + c.count, 0);+ const avgUsd = pricedCount > 0 ? totalUsd / pricedCount : null;+ const avgSol = avgUsd != null && solUsd ? avgUsd / solUsd : null;+ const listingCount = Number(summary?.listing_count ?? 0);++ return {+ catalog: {+ listing_count: listingCount,+ priced_listings: totalPriced,+ free_listings: Math.max(0, listingCount - totalPriced),+ new_in_period: Number(summary?.new_in_period ?? 0),+ },+ pricing: {+ avg_price_usd: roundNum(avgUsd, 4),+ avg_price_sol: roundNum(avgSol, 6),+ min_price_usd: roundNum(minUsd, 4),+ max_price_usd: roundNum(maxUsd, 4),+ priceable_count: pricedCount,+ sol_usd_price: roundNum(solUsd, 2),+ by_currency: byCurrency,+ },+ engagement: {+ total_views: Number(summary?.total_views ?? 0),+ total_forks: Number(summary?.total_forks ?? 0),+ most_viewed_id: mostViewed?.id ?? null,+ most_viewed_name: mostViewed?.name ?? null,+ most_viewed_count: mostViewed ? Number(mostViewed.views_count) : 0,+ most_forked_id: mostForked?.id ?? null,+ most_forked_name: mostForked?.name ?? null,+ most_forked_count: mostForked ? Number(mostForked.forks_count) : 0,+ },+ };+}+++// Aggregate closed positions from the autonomous sniper's real trade ledger.+// All SOL amounts are stored as lamports (numeric(40,0)); we aggregate in SQL to+// keep bigint precision before dividing. interval is a Postgres interval literal+// (e.g. '24 hours'); null means all-time (no time filter). network is 'mainnet',+// 'devnet', or 'all'. Parameters are bound — never interpolated.+const PERIOD_INTERVALS = {+ '1h': '1 hour',+ '6h': '6 hours',+ '24h': '24 hours',+ '7d': '7 days',+ '30d': '30 days',+ all: null,+};+const NETWORKS_SNIPER = new Set(['mainnet', 'devnet', 'all']);++async function sniperTradesReport({ interval, network, period }) {+ const networkClause =+ network && network !== 'all' ? sql\`AND network = \${network}\` : sql\`\`;+ const periodClause =+ interval ? sql\`AND closed_at >= now() - \${interval}::interval\` : sql\`\`;++ const [row] = await sql\`+ SELECT+ COUNT(*) AS closed,+ COUNT(*) FILTER (WHERE realized_pnl_lamports > 0) AS wins,+ COUNT(*) FILTER (WHERE realized_pnl_lamports < 0) AS losses,+ COUNT(*) FILTER (WHERE realized_pnl_lamports = 0) AS breakeven,+ COALESCE(SUM(entry_quote_lamports), 0) AS volume_lamports,+ COALESCE(SUM(realized_pnl_lamports), 0) AS total_pnl_lamports,+ COALESCE(AVG(realized_pnl_lamports), 0) AS avg_pnl_lamports,+ COALESCE(MIN(realized_pnl_lamports), 0) AS worst_loss_lamports,+ COALESCE(MAX(realized_pnl_lamports), 0) AS best_win_lamports,+ COALESCE(AVG(realized_pnl_pct), 0) AS avg_pnl_pct+ FROM agent_sniper_positions+ WHERE status = 'closed'+ AND realized_pnl_lamports IS NOT NULL+ \${periodClause}+ \${networkClause}+ \`.catch(() => [{}]);++ let solUsd = null;+ try { solUsd = await solUsdPrice(); } catch { solUsd = null; }++ const result = buildSniperAnalytics(row || {}, {+ solUsd,+ period,+ network: network || 'mainnet',+ report: 'sniper_trades',+ generatedAt: new Date().toISOString(),+ });++ return { ok: true, ...result };+}+export default paidEndpoint({route: ROUTE,method: 'POST',@@ -307,6 +578,49 @@ export default paidEndpoint({});}+ // ── Revenue report — platform x402 earnings from the settled ledger. ────+ if (report === 'revenue') {+ return buildRevenueReport({ period });+ }++ // ── Agent leaderboard — top spenders from the hire ledger. ──────────────+ if (report === 'agent_leaderboard') {+ const limit = clampInt(body.limit, { min: 1, max: 100, fallback: 10 });+ const windowDays = clampInt(body.window_days, { min: 1, max: 90, fallback: 7 });+ const data = await agentLeaderboardReport(limit, windowDays);+ return {+ ok: true,+ report,+ period,+ generated_at: new Date().toISOString(),+ ...data,+ };+ }++ // ── Marketplace report — live catalog stats for the public agent market. ──+ if (report === 'marketplace') {+ const seconds = PERIODS[period];+ const data = await marketplaceReport(seconds);+ return {+ ok: true,+ report,+ period,+ generated_at: new Date().toISOString(),+ ...data,+ };+ }++ // ── Sniper trades report — autonomous sniper performance from real ledger. ──+ if (report === 'sniper_trades') {+ const network = NETWORKS_SNIPER.has(body.network) ? body.network : 'mainnet';+ return sniperTradesReport({+ interval: PERIOD_INTERVALS[period],+ network,+ period,+ });+ }++ // ── Clubs report (default) — Pole Club social economy. ──────────────────const seconds = PERIODS[period];const { metrics, top_clubs } = await clubsReport(seconds);diff --git a/api/x402/bazaar-feed.js b/api/x402/bazaar-feed.jsindex d77ed9e7d..6565b1e44 100644--- a/api/x402/bazaar-feed.js+++ b/api/x402/bazaar-feed.js@@ -40,27 +40,32 @@ const PRESSURE_PCT = Math.max(0.05, Number(process.env.X402_BAZAAR_TREND_PRESSUR// Cap on how many movers to return per side (the long tail isn't actionable).const TOP_N = 25;-const DESCRIPTION =- 'Bazaar Price Trend Monitor — pay $0.001 USDC per call for a 24h (or custom ' +- 'period) read of price movement across the x402 service marketplace: which ' +- 'tracked services got more expensive, which got cheaper, how many held steady, ' +- 'and the net price pressure as a bullish / bearish / neutral market signal. ' +- 'Derived from three.ws’ own live service price history.';+// eslint-disable-next-line quotes+const DESCRIPTION = `Bazaar Feed - pay $0.001 USDC per call for two live views of the x402 service marketplace. filter "new"/"active": newest service listings (id, name, price, networks, tags, first_seen) plus category rollup and listing-velocity signal (spike/active/quiet). filter "price_trends": 24h price-movement across all tracked services - trending up/down/stable and net market pressure as bullish/bearish/neutral. Live data from the platform bazaar index.`;const INPUT_SCHEMA = {- $schema: 'https://json-schema.org/draft/2020-12/schema',- type: 'object',+ $schema: ‘https://json-schema.org/draft/2020-12/schema’,+ type: ‘object’,properties: {filter: {- type: 'string',- description: 'Feed filter. Only "price_trends" is supported.',- enum: ['price_trends'],- default: 'price_trends',+ type: ‘string’,+ description:+ ‘"new"/"active" → newest-listing feed (default "new"); ‘ ++ ‘"price_trends" → price-movement monitor.’,+ enum: [‘new’, ‘active’, ‘price_trends’],+ default: ‘new’,+ },+ limit: {+ type: ‘integer’,+ minimum: 1,+ maximum: 50,+ default: 10,+ description: ‘Max listings to return (filter "new"/"active" only).’,},period: {- type: 'string',- description: 'Lookback window: <n><unit> where unit is m/h/d/w (e.g. 24h, 7d).',- default: '24h',+ type: ‘string’,+ description: ‘Lookback window: <n><unit>, unit m/h/d/w (e.g. 24h, 7d). filter "price_trends" only.’,+ default: ‘24h’,},},};@@ -85,9 +90,11 @@ const TREND_ITEM_SCHEMA = {const OUTPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',- required: ['filter', 'period', 'trending_up', 'trending_down', 'stable_count', 'signal', 'ts'],+ required: ['filter'],properties: {+ // Sharedfilter: { type: 'string' },+ // price_trends modeperiod: { type: 'string' },trending_up: { type: 'array', items: TREND_ITEM_SCHEMA },trending_down: { type: 'array', items: TREND_ITEM_SCHEMA },@@ -95,10 +102,18 @@ const OUTPUT_SCHEMA = {total_tracked: { type: 'integer' },net_pressure: { type: 'number' },avg_change_pct:{ type: ['number', 'null'] },- signal: { type: 'string', enum: ['bullish', 'bearish', 'neutral'] },+ signal: { type: 'string' },headline: { type: 'string' },confidence: { type: 'number', minimum: 0, maximum: 1 },ts: { type: 'string', format: 'date-time' },+ // new / active mode+ limit: { type: 'integer' },+ count: { type: 'integer' },+ listings: { type: 'array', items: { type: 'object' } },+ newest: { type: ['object', 'null'] },+ categories: { type: 'array', items: { type: 'object' } },+ activity: { type: 'object' },+ generated_at: { type: 'string', format: 'date-time' },},};@@ -260,22 +275,182 @@ export async function readBazaarPriceTrends(periodRaw) {};}+// ── New-Listing Feed helpers (USE-059) ────────────────────────────────────────++let _indexSchemaReady = false;+async function ensureIndexSchema() {+ if (_indexSchemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS bazaar_service_index (+ service_key text PRIMARY KEY,+ resource text NOT NULL,+ tool_name text,+ type text,+ name text,+ description text,+ price_atomic bigint,+ price text,+ networks text[] NOT NULL DEFAULT '{}',+ tags jsonb NOT NULL DEFAULT '[]'::jsonb,+ details jsonb,+ status text NOT NULL DEFAULT 'active',+ first_seen timestamptz NOT NULL DEFAULT now(),+ last_seen timestamptz NOT NULL DEFAULT now(),+ removed_at timestamptz,+ last_run_id uuid+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS bazaar_service_index_status_first ON bazaar_service_index (status, first_seen DESC)`;+ _indexSchemaReady = true;+}++function asTags(raw) {+ if (Array.isArray(raw)) return raw.filter((t) => typeof t === 'string');+ if (typeof raw === 'string') {+ try {+ const p = JSON.parse(raw);+ return Array.isArray(p) ? p.filter((t) => typeof t === 'string') : [];+ } catch { return []; }+ }+ return [];+}++function rowToListing(r) {+ return {+ id: r.service_key,+ resource: r.resource,+ tool_name: r.tool_name || null,+ type: r.type || null,+ name: r.name || null,+ price_atomic: r.price_atomic != null ? String(r.price_atomic) : null,+ price: r.price || null,+ networks: Array.isArray(r.networks) ? r.networks : [],+ tags: asTags(r.tags),+ first_seen: new Date(r.first_seen).toISOString(),+ last_seen: new Date(r.last_seen).toISOString(),+ };+}++function rollupCategories(listings) {+ const counts = new Map();+ for (const l of listings) {+ for (const tag of l.tags) counts.set(tag, (counts.get(tag) || 0) + 1);+ }+ return [...counts.entries()]+ .map(([tag, count]) => ({ tag, count }))+ .sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag))+ .slice(0, 10);+}++function classifyListingActivity(new24h, new7d) {+ const dailyAvg7d = new7d / 7;+ let signal, headline, confidence;+ if (new24h === 0) {+ signal = 'quiet';+ headline = 'No new bazaar listings in the last 24 h';+ confidence = 0.6;+ } else if (new24h >= 3 && dailyAvg7d > 0 && new24h >= dailyAvg7d * 2) {+ signal = 'spike';+ headline = `${new24h} new bazaar listings in 24 h — above the ${dailyAvg7d.toFixed(1)}/day trend`;+ confidence = Math.min(0.95, 0.6 + Math.min(new24h / 20, 0.35));+ } else {+ signal = 'active';+ headline = `${new24h} new bazaar listing${new24h === 1 ? '' : 's'} in 24 h`;+ confidence = 0.65;+ }+ return {+ new_24h: new24h,+ new_7d: new7d,+ daily_avg_7d: Number(dailyAvg7d.toFixed(2)),+ signal,+ headline,+ confidence,+ };+}++export async function readBazaarNewListings({ filter, limit }) {+ await ensureIndexSchema();++ const rows = filter === 'active'+ ? await sql`+ SELECT service_key, resource, tool_name, type, name,+ price_atomic, price, networks, tags, first_seen, last_seen+ FROM bazaar_service_index+ WHERE status = 'active'+ ORDER BY last_seen DESC+ LIMIT ${limit}+ `+ : await sql`+ SELECT service_key, resource, tool_name, type, name,+ price_atomic, price, networks, tags, first_seen, last_seen+ FROM bazaar_service_index+ WHERE status = 'active'+ ORDER BY first_seen DESC+ LIMIT ${limit}+ `;++ const [velocity] = await sql`+ SELECT+ COUNT(*) FILTER (WHERE first_seen >= now() - interval '24 hours') AS new_24h,+ COUNT(*) FILTER (WHERE first_seen >= now() - interval '7 days') AS new_7d+ FROM bazaar_service_index+ WHERE status = 'active'+ `;++ const listings = rows.map(rowToListing);+ const newestByDate = listings.length+ ? listings.reduce((a, b) => (a.first_seen >= b.first_seen ? a : b))+ : null;+ const newest = newestByDate ? {+ id: newestByDate.id,+ name: newestByDate.name,+ price_atomic: newestByDate.price_atomic,+ price: newestByDate.price,+ type: newestByDate.type,+ networks: newestByDate.networks,+ first_seen: newestByDate.first_seen,+ } : null;++ return {+ filter,+ limit,+ count: listings.length,+ listings,+ newest,+ categories: rollupCategories(listings),+ activity: classifyListingActivity(+ Number(velocity?.new_24h || 0),+ Number(velocity?.new_7d || 0),+ ),+ generated_at: new Date().toISOString(),+ };+}++// ── paidEndpoint ──────────────────────────────────────────────────────────────+export default paidEndpoint({route: ROUTE,method: 'POST',- priceAtomics: priceFor('bazaar_feed', '1000'), // $0.001 USDC — lightweight read+ priceAtomics: priceFor('bazaar-feed', '1000'), // $0.001 USDC — lightweight readnetworks: ['solana', 'base'],description: DESCRIPTION,bazaar: BAZAAR,service: withService({serviceName: 'three.ws Bazaar Feed',- tags: ['bazaar', 'price', 'trends', 'market', 'x402'],+ tags: ['bazaar', 'listings', 'discovery', 'market', 'x402'],}),+ siwx: {+ statement: 'Sign in to refresh the three.ws bazaar feed without re-paying.',+ ttlSeconds: 24 * 3600,+ expirationSeconds: 300,+ },+ requiredScope: 'x402:bypass',accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),async handler({ req }) {- let filter = 'price_trends';+ let filter = 'new';let period = '24h';+ let limit = 10;try {const chunks = [];for await (const c of req) chunks.push(c);@@ -286,17 +461,16 @@ export default paidEndpoint({if (typeof body.period === 'string' && body.period.trim()) {period = body.period.trim();}+ const limitRaw = parseInt(body.limit, 10);+ if (Number.isFinite(limitRaw)) limit = Math.min(Math.max(limitRaw, 1), 50);} catch { /* defaults */ }- if (filter !== 'price_trends') {- // Reject before settlement so the buyer is not charged for an- // unsupported filter.- throw Object.assign(new Error(`unsupported filter "${filter}"; only "price_trends" is available`), {- status: 400,- code: 'unsupported_filter',- });- }+ if (filter === 'price_trends') return readBazaarPriceTrends(period);+ if (filter === 'new' || filter === 'active') return readBazaarNewListings({ filter, limit });- return readBazaarPriceTrends(period);+ throw Object.assign(+ new Error(`unsupported filter "${filter}"; use "new", "active", or "price_trends"`),+ { status: 400, code: 'unsupported_filter' },+ );},});diff --git a/api/x402/club-cover.js b/api/x402/club-cover.jsindex 4e7b566db..14b88e770 100644--- a/api/x402/club-cover.js+++ b/api/x402/club-cover.js@@ -26,6 +26,7 @@ import {tierFor,membershipSnapshot,} from '../_lib/club/cover-pass.js';+import { coverRevenueSummary } from '../_lib/club/cover-revenue.js';const ROUTE = '/api/x402/club-cover';@@ -275,34 +276,53 @@ const snapshotEndpoint = paidEndpoint({requiredScope: 'x402:bypass',accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),async handler({ req, requirement, payer, bypass }) {+ let mode = 'snapshot';let club = 'three_holders';+ let period = '7d';try {const chunks = [];for await (const c of req) chunks.push(c);const raw = Buffer.concat(chunks).toString('utf8');if (raw) {const body = JSON.parse(raw);+ if (body && typeof body.mode === 'string') {+ mode = body.mode.trim().toLowerCase().slice(0, 32);+ }if (body && typeof body.club === 'string' && body.club.trim()) {club = body.club.trim().slice(0, 64);}+ if (body && typeof body.period === 'string' && body.period.trim()) {+ period = body.period.trim().slice(0, 8);+ }}} catch {- /* default club — a malformed body just snapshots the default ledger */+ /* default mode/club — a malformed body snapshots the default ledger */}- // Throws 503 on a ledger error → no settlement, caller not charged.- const snap = await membershipSnapshot(club);+ const meta = {+ payer: payer ?? (bypass ? bypass.callerId : null),+ network: requirement?.network ?? null,+ amountAtomics: requirement?.amount ?? null,+ asset: requirement?.asset ?? null,+ ...(bypass ? { bypass: bypass.reason } : {}),+ };+ // mode:"revenue" — 7-day cover-charge + floor revenue summary.+ // The autonomous loop pays this mode to monitor social-economy health.+ if (mode === 'revenue') {+ // Throws 503 on a ledger error → no settlement, caller not charged.+ const summary = await coverRevenueSummary({ period });+ return { ...summary, ...meta };+ }++ // Default: mode:"snapshot" (membership growth/churn).+ const snap = await membershipSnapshot(club);return {ok: true,mode: 'snapshot',...snap,snapshot_at: new Date().toISOString(),- payer: payer ?? (bypass ? bypass.callerId : null),- network: requirement?.network ?? null,- amountAtomics: requirement?.amount ?? null,- asset: requirement?.asset ?? null,- ...(bypass ? { bypass: bypass.reason } : {}),+ ...meta,};},});diff --git a/api/x402/crypto-intel.js b/api/x402/crypto-intel.jsindex b665cdf8e..6b2fb3105 100644--- a/api/x402/crypto-intel.js+++ b/api/x402/crypto-intel.js@@ -17,6 +17,16 @@ import { buildBazaarSchema } from '../_lib/x402-spec.js';import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { priceFor } from '../_lib/x402-prices.js';+import { detectPumpVolumeAnomaly } from '../_lib/x402/pump-volume-anomaly.js';+import { detectPumpTrending } from '../_lib/x402/pump-trending-score.js';++// Special topics resolved by a dedicated data engine rather than the CoinGecko+// price path. `pump_volume_anomaly` scans the live pump.fun trade feed for a coin+// whose trailing-hour volume is a statistical outlier vs its peers.+// `pump_trending` returns the live pump.fun trending board with buy/sell pressure+// scores and whale activity across the top ranked coins.+const PUMP_VOLUME_ANOMALY = 'pump_volume_anomaly';+const PUMP_TRENDING = 'pump_trending';const ROUTE = '/api/x402/crypto-intel';@@ -159,6 +169,21 @@ export default paidEndpoint({}} catch { /* default topic */ }+ // pump.fun volume-anomaly oracle — live trade-feed analytics, not a price+ // lookup. detectPumpVolumeAnomaly() throws a 503-tagged error when the+ // upstream feed is down, so the paidEndpoint wrapper refunds (never settles+ // for an empty verdict), matching the price-path behaviour below.+ if (topic === PUMP_VOLUME_ANOMALY) {+ return await detectPumpVolumeAnomaly();+ }++ // pump.fun trending score feed — fetches the live market-cap leaderboard,+ // derives buy/sell pressure from real swap-api trade feeds, and surfaces+ // whale buys (≥5 SOL). Throws 503 if the board is unavailable (no charge).+ if (topic === PUMP_TRENDING) {+ return await detectPumpTrending();+ }+const coinId = ALIASES[topic] || topic;let live = null;try { live = await fetchLivePrice(coinId); } catch { /* offline fallback */ }diff --git a/api/x402/forge.js b/api/x402/forge.jsindex 601b8fd46..fd421b9c8 100644--- a/api/x402/forge.js+++ b/api/x402/forge.js@@ -458,7 +458,7 @@ async function submitViaReconstruct({ prompt, imageUrls, isImageMode, aspect, ti// never throws — a provider outage is the very signal this probe exists to catch,// so it returns a settled verdict (generated:false) rather than failing the paid// call. The caller paid for a verdict; it always gets one.-async function runForgeHealthCheck({ prompt }) {+export async function runForgeHealthCheck({ prompt }) {const probePrompt = (prompt && prompt.length >= 3 ? prompt : HEALTH_CHECK_DEFAULT_PROMPT);const t0 = Date.now();try {diff --git a/api/x402/pump-agent-audit.js b/api/x402/pump-agent-audit.jsindex a9e584e50..3262f2765 100644--- a/api/x402/pump-agent-audit.js+++ b/api/x402/pump-agent-audit.js@@ -18,28 +18,79 @@ import { installAccessControl } from '../_lib/x402/access-control.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { sql } from '../_lib/db.js';import { priceFor } from '../_lib/x402-prices.js';+import { recentPumpLaunches } from '../_lib/pump-launch-feed.js';const ROUTE = '/api/x402/pump-agent-audit';const DESCRIPTION =- 'three.ws Pump-Agent Audit — given a pump.fun SPL mint address, return a ' +- 'full operational audit of its agent-payments lifecycle: total USDC paid in, ' +- 'unique payer count, distribute run history with success/failure breakdown, ' +- 'buyback runs with burn totals, recent error reasons, and risk flags ' +- '(e.g. "never distributed", "high failure rate"). Use to evaluate ' +- 'counterparty operational risk before trading or paying.';+ 'three.ws Pump-Agent Audit — two modes. SINGLE (pass ?mint=<spl-mint>): a ' ++ 'full operational audit of one pump.fun agent-payments token — total USDC ' ++ 'paid in, unique payer count, distribute run history with success/failure ' ++ 'breakdown, buyback runs with burn totals, recent error reasons, and risk ' ++ 'flags ("never distributed", "high failure rate"). LIST (omit mint, pass ' ++ '?limit=&sort=newest|liquidity): the N most-recently launched pump.fun ' ++ 'tokens (live bonding-curve feed) with each one\'s initial SOL liquidity, ' ++ 'market cap and whether it is a three.ws agent-payments token, plus the ' ++ 'cohort\'s average/peak initial liquidity. Use SINGLE to evaluate ' ++ 'counterparty risk before trading; use LIST to screen fresh launches for ' ++ 'snipe candidates.';const INPUT_EXAMPLE = { mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi' };const INPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',type: 'object',- required: ['mint'],+ // `mint` selects SINGLE mode; omitting it selects LIST mode. Neither field is+ // unconditionally required, so the schema documents both inputs without+ // forcing a mint on the list path.properties: {- mint: { type: 'string', description: 'Solana SPL mint pubkey (base58).' },+ mint: {+ type: 'string',+ description: 'Solana SPL mint pubkey (base58). Present → single-mint audit.',+ },+ limit: {+ type: 'integer',+ minimum: 1,+ maximum: 25,+ description: 'LIST mode: number of recent launches to return (default 10).',+ },+ sort: {+ type: 'string',+ enum: ['newest', 'liquidity'],+ description: 'LIST mode: order — newest-first (default) or by initial liquidity.',+ },},};+// LIST mode example (omit mint → recent launches)+const OUTPUT_EXAMPLE_LIST = {+ network: 'mainnet',+ sort: 'newest',+ count: 2,+ newest_mint: 'AbcDEFGHJKLMNopqrstuvwxyZ12345abcdefghi1234',+ newest_name: 'PepeGo',+ newest_symbol: 'PEPEGO',+ avg_initial_liquidity_sol: 28.4,+ max_initial_liquidity_sol: 45.1,+ launches: [+ {+ mint: 'AbcDEFGHJKLMNopqrstuvwxyZ12345abcdefghi1234',+ name: 'PepeGo',+ symbol: 'PEPEGO',+ created_at: 1748908800000,+ market_cap_usd: 6500,+ liquidity_sol: 45.1,+ creator: '5oo1g...',+ twitter: null,+ telegram: null,+ website: null,+ is_agent_token: false,+ },+ ],+ queried_at: '2026-05-14T17:00:00Z',+};++// SINGLE mode example (pass ?mint=)const OUTPUT_EXAMPLE = {mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',network: 'mainnet',@@ -77,22 +128,44 @@ const OUTPUT_EXAMPLE = {const OUTPUT_SCHEMA = {$schema: 'https://json-schema.org/draft/2020-12/schema',- type: 'object',- required: ['mint', 'payments', 'distributions', 'buybacks', 'risk_flags'],- properties: {- mint: { type: 'string' },- network: { type: ['string', 'null'] },- name: { type: ['string', 'null'] },- symbol: { type: ['string', 'null'] },- agent_id: { type: ['string', 'null'] },- pump_agent_pda: { type: ['string', 'null'] },- deployed_at: { type: ['string', 'null'] },- payments: { type: 'object' },- distributions: { type: 'object' },- buybacks: { type: 'object' },- risk_flags: { type: 'array', items: { type: 'string' } },- indexed_at: { type: 'string', format: 'date-time' },- },+ oneOf: [+ {+ title: 'List mode',+ type: 'object',+ required: ['count', 'launches', 'queried_at'],+ properties: {+ network: { type: 'string' },+ sort: { type: 'string' },+ count: { type: 'integer' },+ newest_mint: { type: ['string', 'null'] },+ newest_name: { type: ['string', 'null'] },+ newest_symbol: { type: ['string', 'null'] },+ avg_initial_liquidity_sol: { type: ['number', 'null'] },+ max_initial_liquidity_sol: { type: ['number', 'null'] },+ launches: { type: 'array', items: { type: 'object' } },+ queried_at: { type: 'string', format: 'date-time' },+ },+ },+ {+ title: 'Single mode',+ type: 'object',+ required: ['mint', 'payments', 'distributions', 'buybacks', 'risk_flags'],+ properties: {+ mint: { type: 'string' },+ network: { type: ['string', 'null'] },+ name: { type: ['string', 'null'] },+ symbol: { type: ['string', 'null'] },+ agent_id: { type: ['string', 'null'] },+ pump_agent_pda: { type: ['string', 'null'] },+ deployed_at: { type: ['string', 'null'] },+ payments: { type: 'object' },+ distributions: { type: 'object' },+ buybacks: { type: 'object' },+ risk_flags: { type: 'array', items: { type: 'string' } },+ indexed_at: { type: 'string', format: 'date-time' },+ },+ },+ ],};const BAZAAR = {@@ -101,9 +174,10 @@ const BAZAAR = {input: {type: 'http',method: 'GET',- queryParams: INPUT_EXAMPLE,+ // Show list-mode query params as the primary example (common caller path)+ queryParams: { limit: 10, sort: 'newest' },},- output: { type: 'json', example: OUTPUT_EXAMPLE },+ output: { type: 'json', example: OUTPUT_EXAMPLE_LIST },},schema: buildBazaarSchema({method: 'GET',@@ -237,6 +311,53 @@ async function loadAudit(mint) {};}+// Cross-reference the live pump.fun launches against pump_agent_mints so each+// list entry gains an `is_agent_token` flag without N per-launch DB queries.+async function markAgentTokens(launches) {+ if (!launches.length) return launches;+ const mints = launches.map((l) => l.mint).filter(Boolean);+ if (!mints.length) return launches;+ try {+ const rows = await sql`+ select mint from pump_agent_mints where mint = any(${mints})+ `;+ const agentSet = new Set(rows.map((r) => r.mint));+ return launches.map((l) => ({ ...l, is_agent_token: agentSet.has(l.mint) }));+ } catch {+ // Non-fatal — caller still gets the live launches, just without the flag.+ return launches.map((l) => ({ ...l, is_agent_token: false }));+ }+}++async function loadRecentLaunches({ limit, sort }) {+ const n = Math.min(25, Math.max(1, Number(limit) || 10));+ const raw = await recentPumpLaunches({ network: 'mainnet', limit: n });+ const launches = await markAgentTokens(raw);++ // sort='liquidity' re-ranks by initial bonding-curve SOL reserves, highest first.+ if (sort === 'liquidity') {+ launches.sort((a, b) => (b.liquidity_sol ?? 0) - (a.liquidity_sol ?? 0));+ }++ const liq = launches.map((l) => l.liquidity_sol).filter((v) => v != null && v > 0);+ const avgLiq = liq.length ? liq.reduce((a, b) => a + b, 0) / liq.length : null;+ const maxLiq = liq.length ? Math.max(...liq) : null;+ const newest = launches[sort === 'liquidity' ? 0 : 0]; // feed is newest-first from source++ return {+ network: 'mainnet',+ sort: sort || 'newest',+ count: launches.length,+ newest_mint: newest?.mint || null,+ newest_name: newest?.name || null,+ newest_symbol: newest?.symbol || null,+ avg_initial_liquidity_sol: avgLiq != null ? Math.round(avgLiq * 1e4) / 1e4 : null,+ max_initial_liquidity_sol: maxLiq != null ? Math.round(maxLiq * 1e4) / 1e4 : null,+ launches,+ queried_at: new Date().toISOString(),+ };+}+export default paidEndpoint({route: ROUTE,method: 'GET',@@ -252,12 +373,21 @@ export default paidEndpoint({accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),async handler({ req }) {const mint = String(req.query?.mint || '').trim();++ // LIST MODE — no mint suppliedif (!mint) {- const err = new Error('query param "mint" is required');- err.status = 400;- err.code = 'missing_mint';- throw err;+ const limit = req.query?.limit;+ const sort = String(req.query?.sort || 'newest').trim();+ if (sort !== 'newest' && sort !== 'liquidity') {+ const err = new Error('sort must be "newest" or "liquidity"');+ err.status = 400;+ err.code = 'invalid_sort';+ throw err;+ }+ return loadRecentLaunches({ limit, sort });}++ // SINGLE MODE — validate mint then auditif (!BASE58_RE.test(mint)) {const err = new Error('mint must be a base58 Solana pubkey');err.status = 400;diff --git a/data/changelog.json b/data/changelog.jsonindex 6f988c045..5b8af121a 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,18 @@{"$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-28",+ "title": "Pay-By-Name Resolution Health — the platform watches its own name registry every 10 minutes",+ "summary": "Every 'send USDC to a name' flow on three.ws — the SDK's payByName(), the /pay studio, the profile pay button, and any agent routing a payment to @username or a .sol domain — resolves the recipient through the same name registry before a single lamport moves. If that registry breaks (a Bonfida SNS regression, the parent domain de-registering, or the platform domain repointing to a different wallet), the failure is silent and every downstream send either pays the wrong place or throws an error. The platform now watches for this automatically. Every 10 minutes an autonomous agent makes a free call to the resolve endpoint with the platform's own known SNS name and checks that it comes back with a valid, on-curve Solana wallet address. If an expected wallet is configured, it additionally asserts the resolution still matches that specific wallet — an anti-poisoning check that catches a domain repoint between deploys before any user is affected. Results are recorded to a time-series log and cached in Redis so a health dashboard can read the latest verdict without a database round-trip. A failed or mismatched resolution raises an alert flag that lingers until the next clean run. The monitor is a read-only, free call — it moves no funds — and it replaces a prior registry entry that was calling the wrong endpoint method and would have silently recorded every 404 as healthy.",+ "tags": ["feature", "infra"]+ },+ {+ "date": "2026-06-28",+ "title": "MCP Tool Discovery — the platform notices the moment a new agent capability ships",+ "summary": "The three.ws MCP server exposes a growing catalog of tools agents can call — render and inspect 3D models, query live pump.fun market data, read Oracle conviction signals, and more — and that catalog changes as new capabilities ship. Until now, an agent wanting to use a brand-new tool had to keep re-fetching the full tool list and diffing it by hand to notice anything had changed. The platform now does that watching for them. Every two hours an autonomous agent makes a real on-chain payment to a new paid endpoint that fingerprints the live tool catalog and compares it to a durable registry, then reports exactly what changed since the last check: tools that are newly registered, tools whose price or input shape changed, and tools that were removed. New tools are recorded the instant they appear, giving agents a single feature-flag source to light up a new capability without polling. The diff is logged like every other autonomous payment, and the same endpoint is available to any agent on the x402 bazaar for a fraction of a cent.",+ "tags": ["feature", "infra"]+ },{"date": "2026-06-27","title": "Spend Reservation Leak Detector — the platform keeps agent spending caps from silently starving",@@ -8979,6 +8991,15 @@"security"],"link": "/login"+ },+ {+ "date": "2026-06-28",+ "title": "Pump Launch Monitor: live snipe-candidate screening",+ "summary": "The autonomous x402 agent now pays to audit the 10 most recently launched pump.fun tokens every 5 minutes, extracting each cohort's average and peak initial bonding-curve liquidity. New launches with initial liquidity well above the rolling cohort average are surfaced as high-conviction snipe candidates; the signal is upserted into the oracle feed so the sniper gate can act on it immediately.",+ "tags": [+ "feature",+ "infra"+ ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex 3127e7d09..6650ab76f 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,44 @@{- "generated_at": "2026-06-27T23:46:49.134Z",+ "generated_at": "2026-06-28T01:58:44.951Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "MCP Tool Discovery — the platform notices the moment a new agent capability ships",+ "summary": "The three.ws MCP server exposes a growing catalog of tools agents can call — render and inspect 3D models, query live pump.fun market data, read Oracle conviction signals, and more — and that catalog changes as new capabilities ship. Until now, an agent wanting to use a brand-new tool had to keep re-fetching the full tool list and diffing it by hand to notice anything had changed. The platform now does that watching for them. Every two hours an autonomous agent makes a real on-chain payment to a new paid endpoint that fingerprints the live tool catalog and compares it to a durable registry, then reports exactly what changed since the last check: tools that are newly registered, tools whose price or input shape changed, and tools that were removed. New tools are recorded the instant they appear, giving agents a single feature-flag source to light up a new capability without polling. The diff is logged like every other autonomous payment, and the same endpoint is available to any agent on the x402 bazaar for a fraction of a cent.",+ "link": null,+ "tags": [+ "feature",+ "infra"+ ]+ },+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "Pay-By-Name Resolution Health — the platform watches its own name registry every 10 minutes",+ "summary": "Every 'send USDC to a name' flow on three.ws — the SDK's payByName(), the /pay studio, the profile pay button, and any agent routing a payment to @username or a .sol domain — resolves the recipient through the same name registry before a single lamport moves. If that registry breaks (a Bonfida SNS regression, the parent domain de-registering, or the platform domain repointing to a different wallet), the failure is silent and every downstream send either pays the wrong place or throws an error. The platform now watches for this automatically. Every 10 minutes an autonomous agent makes a free call to the resolve endpoint with the platform's own known SNS name and checks that it comes back with a valid, on-curve Solana wallet address. If an expected wallet is configured, it additionally asserts the resolution still matches that specific wallet — an anti-poisoning check that catches a domain repoint between deploys before any user is affected. Results are recorded to a time-series log and cached in Redis so a health dashboard can read the latest verdict without a database round-trip. A failed or mismatched resolution raises an alert flag that lingers until the next clean run. The monitor is a read-only, free call — it moves no funds — and it replaces a prior registry entry that was calling the wrong endpoint method and would have silently recorded every 404 as healthy.",+ "link": null,+ "tags": [+ "feature",+ "infra"+ ]+ },+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "Pump Launch Monitor: live snipe-candidate screening",+ "summary": "The autonomous x402 agent now pays to audit the 10 most recently launched pump.fun tokens every 5 minutes, extracting each cohort's average and peak initial bonding-curve liquidity. New launches with initial liquidity well above the rolling cohort average are surfaced as high-conviction snipe candidates; the signal is upserted into the oracle feed so the sniper gate can act on it immediately.",+ "link": null,+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-06-27","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex da1998ad9..b3b4fd03b 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,30 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>MCP Tool Discovery — the platform notices the moment a new agent capability ships</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-28:MCP Tool Discovery — the platform notices the moment a new agent capability ships</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The three.ws MCP server exposes a growing catalog of tools agents can call — render and inspect 3D models, query live pump.fun market data, read Oracle conviction signals, and more — and that catalog changes as new capabilities ship. Until now, an agent wanting to use a brand-new tool had to keep re-fetching the full tool list and diffing it by hand to notice anything had changed. The platform now does that watching for them. Every two hours an autonomous agent makes a real on-chain payment to a new paid endpoint that fingerprints the live tool catalog and compares it to a durable registry, then reports exactly what changed since the last check: tools that are newly registered, tools whose price or input shape changed, and tools that were removed. New tools are recorded the instant they appear, giving agents a single feature-flag source to light up a new capability without polling. The diff is logged like every other autonomous payment, and the same endpoint is available to any agent on the x402 bazaar for a fraction of a cent.</description>+ </item>+ <item>+ <title>Pay-By-Name Resolution Health — the platform watches its own name registry every 10 minutes</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-28:Pay-By-Name Resolution Health — the platform watches its own name registry every 10 minutes</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Every 'send USDC to a name' flow on three.ws — the SDK's payByName(), the /pay studio, the profile pay button, and any agent routing a payment to @username or a .sol domain — resolves the recipient through the same name registry before a single lamport moves. If that registry breaks (a Bonfida SNS regression, the parent domain de-registering, or the platform domain repointing to a different wallet), the failure is silent and every downstream send either pays the wrong place or throws an error. The platform now watches for this automatically. Every 10 minutes an autonomous agent makes a free call to the resolve endpoint with the platform's own known SNS name and checks that it comes back with a valid, on-curve Solana wallet address. If an expected wallet is configured, it additionally asserts the resolution still matches that specific wallet — an anti-poisoning check that catches a domain repoint between deploys before any user is affected. Results are recorded to a time-series log and cached in Redis so a health dashboard can read the latest verdict without a database round-trip. A failed or mismatched resolution raises an alert flag that lingers until the next clean run. The monitor is a read-only, free call — it moves no funds — and it replaces a prior registry entry that was calling the wrong endpoint method and would have silently recorded every 404 as healthy.</description>+ </item>+ <item>+ <title>Pump Launch Monitor: live snipe-candidate screening</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-28:Pump Launch Monitor: live snipe-candidate screening</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The autonomous x402 agent now pays to audit the 10 most recently launched pump.fun tokens every 5 minutes, extracting each cohort's average and peak initial bonding-curve liquidity. New launches with initial liquidity well above the rolling cohort average are surfaced as high-conviction snipe candidates; the signal is upserted into the oracle feed so the sniper gate can act on it immediately.</description>+ </item><item><title>Capabilities — Alpha Hunt, Launcher, Auto-Claim & Market Maker</title><link>https://three.ws/dashboard/capabilities</link>diff --git a/public/features.json b/public/features.jsonindex 9f80daa25..f94989cce 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T23:46:49.111Z",+ "generated_at": "2026-06-28T01:58:44.819Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/api/x402-pay-by-name-resolver.test.js b/tests/api/x402-pay-by-name-resolver.test.jsnew file mode 100644index 000000000..5f9bd0f7b--- /dev/null+++ b/tests/api/x402-pay-by-name-resolver.test.js@@ -0,0 +1,74 @@+// api/_lib/x402/pipelines/pay-by-name-resolver — classifyResolution unit tests.+// Pure function tests only: no network, no DB, no Redis required.++import { describe, it, expect } from 'vitest';++// We test classifyResolution in isolation. It only depends on @solana/web3.js+// (already installed) for on-curve validation — no mocks needed.+import { classifyResolution } from '../../api/_lib/x402/pipelines/pay-by-name-resolver.js';++// A real, well-known on-curve Solana address (USDC mint — stable canary).+const VALID_ADDR = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+// A second valid address for mismatch tests.+const OTHER_ADDR = 'So11111111111111111111111111111111111111112';++describe('classifyResolution', () => {+ it('verifies a well-formed SNS response with a valid on-curve address', () => {+ const body = { data: { address: VALID_ADDR, source: 'sns', resolved: 'threews.sol' } };+ const v = classifyResolution(body, { name: 'threews.sol' });+ expect(v.address).toBe(VALID_ADDR);+ expect(v.source).toBe('sns');+ expect(v.valid_address).toBe(true);+ expect(v.verified).toBe(true);+ expect(v.address_mismatch).toBe(false);+ expect(v.expected_address).toBeNull();+ expect(v.name).toBe('threews.sol');+ });++ it('verifies when address matches expected_address', () => {+ const body = { data: { address: VALID_ADDR, source: 'sns', resolved: 'threews.sol' } };+ const v = classifyResolution(body, { name: 'threews.sol', expectedAddress: VALID_ADDR });+ expect(v.verified).toBe(true);+ expect(v.address_mismatch).toBe(false);+ expect(v.expected_address).toBe(VALID_ADDR);+ });++ it('flags address_mismatch when resolved address ≠ expectedAddress', () => {+ const body = { data: { address: OTHER_ADDR, source: 'sns', resolved: 'threews.sol' } };+ const v = classifyResolution(body, { name: 'threews.sol', expectedAddress: VALID_ADDR });+ expect(v.verified).toBe(false);+ expect(v.address_mismatch).toBe(true);+ expect(v.address).toBe(OTHER_ADDR);+ expect(v.expected_address).toBe(VALID_ADDR);+ });++ it('returns unverified on null body (fetch / network failure)', () => {+ const v = classifyResolution(null, { name: 'threews.sol' });+ expect(v.verified).toBe(false);+ expect(v.valid_address).toBe(false);+ expect(v.address).toBeNull();+ expect(v.source).toBeNull();+ });++ it('returns unverified when body has no data field', () => {+ const v = classifyResolution({ error: 'not_found' }, { name: 'threews.sol' });+ expect(v.verified).toBe(false);+ expect(v.address).toBeNull();+ });++ it('returns unverified for a non-base58 / garbage address', () => {+ const body = { data: { address: 'not-a-wallet', source: 'sns', resolved: 'threews.sol' } };+ const v = classifyResolution(body, { name: 'threews.sol' });+ expect(v.valid_address).toBe(false);+ expect(v.verified).toBe(false);+ expect(v.address).toBe('not-a-wallet');+ });+++ it('resolves name from response when opts.name is absent', () => {+ const body = { data: { address: VALID_ADDR, source: 'username', resolved: '@threews' } };+ const v = classifyResolution(body);+ expect(v.name).toBe('@threews');+ expect(v.verified).toBe(true);+ });+});diff --git a/tests/club-membership-snapshot.test.js b/tests/club-membership-snapshot.test.jsnew file mode 100644index 000000000..276ac88a8--- /dev/null+++ b/tests/club-membership-snapshot.test.js@@ -0,0 +1,147 @@+// Tests for the club membership snapshot logic added in USE-066.+//+// Covers: classifyMembership signal classification, extractSignal in the+// autonomous registry, and the numeric edge cases the autonomous loop may+// encounter (zero membership, single member, growth threshold boundary).++import { describe, it, expect } from 'vitest';+import { classifyMembership } from '../api/_lib/club/cover-pass.js';++// Mirror of the extractSignal closure from autonomous-registry.js — testing+// it inline keeps the test independent of the registry's DB imports.+function extractSignal(r) {+ return {+ topic: 'club:three_holders',+ club: r?.club ?? 'three_holders',+ member_count: r?.member_count ?? null,+ active_last_7d: r?.active_last_7d ?? null,+ new_this_week: r?.new_this_week ?? null,+ growth_rate: r?.growth_rate ?? null,+ active_rate: r?.active_rate ?? null,+ signal: r?.signal ?? null,+ headline: r?.headline ?? null,+ confidence: r?.confidence ?? null,+ };+}++describe('classifyMembership', () => {+ it('returns empty signal when member_count is 0', () => {+ const r = classifyMembership({ member_count: 0, active_last_7d: 0, new_this_week: 0 });+ expect(r.signal).toBe('empty');+ expect(r.member_count).toBe(0);+ expect(r.active_last_7d).toBe(0);+ expect(r.new_this_week).toBe(0);+ expect(r.growth_rate).toBe(0);+ expect(r.active_rate).toBe(0);+ expect(r.confidence).toBe(0.3);+ expect(r.headline).toMatch(/no club members/i);+ });++ it('returns growing when new_this_week / member_count >= 10%', () => {+ const r = classifyMembership({ member_count: 10, active_last_7d: 5, new_this_week: 2 });+ expect(r.signal).toBe('growing');+ expect(r.growth_rate).toBe(0.2);+ expect(r.headline).toMatch(/growing/i);+ });++ it('boundary: exactly 10% growth is growing', () => {+ const r = classifyMembership({ member_count: 10, active_last_7d: 5, new_this_week: 1 });+ expect(r.signal).toBe('growing');+ });++ it('returns churning when active_last_7d / member_count < 10%', () => {+ const r = classifyMembership({ member_count: 20, active_last_7d: 1, new_this_week: 0 });+ expect(r.signal).toBe('churning');+ expect(r.headline).toMatch(/churning/i);+ });++ it('returns stable for a healthy but slow-growing club', () => {+ const r = classifyMembership({ member_count: 100, active_last_7d: 40, new_this_week: 2 });+ expect(r.signal).toBe('stable');+ expect(r.active_rate).toBe(0.4);+ });++ it('attaches the club label', () => {+ const r = classifyMembership({ club: 'vip_room', member_count: 5, active_last_7d: 5, new_this_week: 1 });+ expect(r.club).toBe('vip_room');+ });++ it('defaults club to three_holders when not provided', () => {+ const r = classifyMembership({ member_count: 5, active_last_7d: 5, new_this_week: 1 });+ expect(r.club).toBe('three_holders');+ });++ it('clamps confidence to 0.95 for large memberships', () => {+ const r = classifyMembership({ member_count: 1000, active_last_7d: 500, new_this_week: 10 });+ expect(r.confidence).toBe(0.95);+ });++ it('returns confidence 0.3 for a single member (weak read)', () => {+ const r = classifyMembership({ member_count: 1, active_last_7d: 1, new_this_week: 1 });+ expect(r.confidence).toBe(0.3);+ });++ it('confidence scales linearly up to the 50-member mark', () => {+ const r = classifyMembership({ member_count: 25, active_last_7d: 20, new_this_week: 0 });+ // 25/50 = 0.5 → clamped to [0.3, 0.95] → 0.5+ expect(r.confidence).toBe(0.5);+ });++ it('coerces non-numeric inputs to 0 gracefully', () => {+ const r = classifyMembership({ member_count: '42', active_last_7d: null, new_this_week: undefined });+ expect(r.member_count).toBe(42);+ expect(r.active_last_7d).toBe(0);+ expect(r.new_this_week).toBe(0);+ });++ it('returns all required output fields', () => {+ const r = classifyMembership({ member_count: 10, active_last_7d: 3, new_this_week: 1 });+ for (const key of ['club', 'member_count', 'active_last_7d', 'new_this_week',+ 'growth_rate', 'active_rate', 'signal', 'headline', 'confidence']) {+ expect(r).toHaveProperty(key);+ }+ });+});++describe('extractSignal (registry closure)', () => {+ it('lifts all fields and sets topic correctly', () => {+ const response = {+ ok: true,+ mode: 'snapshot',+ club: 'three_holders',+ member_count: 50,+ active_last_7d: 20,+ new_this_week: 5,+ growth_rate: 0.1,+ active_rate: 0.4,+ signal: 'growing',+ headline: 'Club growing — 5 new members this week.',+ confidence: 0.85,+ };+ const s = extractSignal(response);+ expect(s.topic).toBe('club:three_holders');+ expect(s.club).toBe('three_holders');+ expect(s.member_count).toBe(50);+ expect(s.active_last_7d).toBe(20);+ expect(s.new_this_week).toBe(5);+ expect(s.growth_rate).toBe(0.1);+ expect(s.active_rate).toBe(0.4);+ expect(s.signal).toBe('growing');+ expect(s.headline).toMatch(/growing/i);+ expect(s.confidence).toBe(0.85);+ });++ it('handles a null response body without throwing', () => {+ const s = extractSignal(null);+ expect(s.topic).toBe('club:three_holders');+ expect(s.member_count).toBeNull();+ expect(s.signal).toBeNull();+ });++ it('handles a partial response (missing optional fields)', () => {+ const s = extractSignal({ member_count: 10 });+ expect(s.member_count).toBe(10);+ expect(s.active_last_7d).toBeNull();+ expect(s.new_this_week).toBeNull();+ });+});diff --git a/tests/pump-launch-monitor.test.js b/tests/pump-launch-monitor.test.jsnew file mode 100644index 000000000..679bb1f1f--- /dev/null+++ b/tests/pump-launch-monitor.test.js@@ -0,0 +1,85 @@+import { describe, it, expect } from 'vitest';+import { classifyLaunchMonitor } from '../api/_lib/x402/pump-launch-monitor.js';++// Simulate a real list-mode /api/x402/pump-agent-audit response.+function makeResponse({ launches = [], overrides = {} } = {}) {+ const liq = launches.map((l) => l.liquidity_sol).filter((v) => v != null && v > 0);+ const avg = liq.length ? liq.reduce((a, b) => a + b, 0) / liq.length : null;+ const max = liq.length ? Math.max(...liq) : null;+ return {+ network: 'mainnet',+ sort: 'newest',+ count: launches.length,+ newest_mint: launches[0]?.mint || null,+ newest_name: launches[0]?.name || null,+ newest_symbol: launches[0]?.symbol || null,+ avg_initial_liquidity_sol: avg,+ max_initial_liquidity_sol: max,+ launches,+ queried_at: '2026-06-28T00:00:00Z',+ ...overrides,+ };+}++const LAUNCHES = [+ { mint: 'AAA1111111111111111111111111111111111111111', name: 'Pepe', symbol: 'PEPE', liquidity_sol: 30, is_agent_token: false },+ { mint: 'BBB2222222222222222222222222222222222222222', name: 'Moo', symbol: 'MOO', liquidity_sol: 10, is_agent_token: true },+ { mint: 'CCC3333333333333333333333333333333333333333', name: 'Ape', symbol: 'APE', liquidity_sol: null, is_agent_token: false },+];++describe('classifyLaunchMonitor', () => {+ it('extracts core signal fields from a full response', () => {+ const r = makeResponse({ launches: LAUNCHES });+ const s = classifyLaunchMonitor(r);+ expect(s.count).toBe(3);+ expect(s.newest_mint).toBe('AAA1111111111111111111111111111111111111111');+ expect(s.newest_name).toBe('Pepe');+ expect(s.newest_symbol).toBe('PEPE');+ });++ it('computes avg_initial_liquidity from launches when endpoint pre-computation is absent', () => {+ // Override with null so classifyLaunchMonitor must recompute from launches array+ const r = makeResponse({ launches: LAUNCHES, overrides: { avg_initial_liquidity_sol: null } });+ const s = classifyLaunchMonitor(r);+ // Only the two non-null liquidity values (30 + 10) contribute+ expect(s.avg_initial_liquidity).toBeCloseTo(20, 5);+ expect(s.max_initial_liquidity).toBe(30);+ });++ it('prefers endpoint-pre-computed avg over local recompute when present', () => {+ const r = makeResponse({ launches: LAUNCHES, overrides: { avg_initial_liquidity_sol: 99.5 } });+ const s = classifyLaunchMonitor(r);+ expect(s.avg_initial_liquidity).toBe(99.5);+ });++ it('counts agent tokens correctly', () => {+ const s = classifyLaunchMonitor(makeResponse({ launches: LAUNCHES }));+ expect(s.agent_token_count).toBe(1);+ });++ it('handles empty launches gracefully', () => {+ const s = classifyLaunchMonitor(makeResponse({ launches: [] }));+ expect(s.count).toBe(0);+ expect(s.newest_mint).toBeNull();+ expect(s.avg_initial_liquidity).toBeNull();+ expect(s.max_initial_liquidity).toBeNull();+ expect(s.agent_token_count).toBe(0);+ });++ it('handles null/missing response without throwing', () => {+ expect(() => classifyLaunchMonitor(null)).not.toThrow();+ expect(() => classifyLaunchMonitor(undefined)).not.toThrow();+ const s = classifyLaunchMonitor(null);+ expect(s.count).toBe(0);+ });++ it('treats launches with liquidity_sol=0 as having no liquidity', () => {+ const launches = [+ { mint: 'A'.repeat(44), name: 'Z', symbol: 'ZZ', liquidity_sol: 0, is_agent_token: false },+ ];+ const s = classifyLaunchMonitor(makeResponse({ launches }));+ // 0 is filtered from the liq array → avg and max stay null+ expect(s.avg_initial_liquidity).toBeNull();+ expect(s.max_initial_liquidity).toBeNull();+ });+});diff --git a/tests/x402-agent-reputation-sweep.test.js b/tests/x402-agent-reputation-sweep.test.jsnew file mode 100644index 000000000..11e97401b--- /dev/null+++ b/tests/x402-agent-reputation-sweep.test.js@@ -0,0 +1,319 @@+import { describe, it, expect } from 'vitest';+import {+ scoreAgentReputation,+ sweepAgentReputation,+ REPUTATION_FLAG_THRESHOLD,+} from '../api/_lib/trust/solana-bouncer.js';+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';++// ── Helpers ──────────────────────────────────────────────────────────────────++const rep = (over = {}) => ({+ agent_id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',+ name: 'TestAgent',+ wallet_address: 'THREEsynthetic1111111111111111111111111111',+ deployed_mints: 1,+ payments: {+ confirmed_count: 0,+ confirmed_amount_atomics: '0',+ distinct_payers: 0,+ failed_count: 0,+ failure_rate: 0,+ },+ distributions: { confirmed: 0, failed: 0, success_rate: 0 },+ buybacks: { confirmed: 0, failed: 0, total_burn_atomics: '0' },+ attestations: { feedback_count: 0, validation_count: 0, latest_attested_at: null },+ indexed_at: new Date().toISOString(),+ ...over,+});++const withPayments = (confirmed, payers, failureRate = 0) =>+ rep({+ payments: {+ confirmed_count: confirmed,+ confirmed_amount_atomics: String(confirmed * 1_000_000),+ distinct_payers: payers,+ failed_count: Math.round((confirmed / (1 - failureRate || 1)) * failureRate),+ failure_rate: failureRate,+ },+ });++// ── scoreAgentReputation ─────────────────────────────────────────────────────++describe('scoreAgentReputation — zero activity', () => {+ it('scores 0 for a brand-new agent with no history', () => {+ const { score, flagged } = scoreAgentReputation(rep());+ expect(score).toBe(0);+ expect(flagged).toBe(true);+ });++ it('flags when score < REPUTATION_FLAG_THRESHOLD', () => {+ expect(REPUTATION_FLAG_THRESHOLD).toBe(30);+ const { flagged } = scoreAgentReputation(rep());+ expect(flagged).toBe(true);+ });++ it('returns reasons for a zero-activity agent', () => {+ const { reasons } = scoreAgentReputation(rep());+ expect(reasons.length).toBeGreaterThan(0);+ expect(reasons.some((r) => /payment/i.test(r))).toBe(true);+ });+});++describe('scoreAgentReputation — payment volume', () => {+ it('scores higher with more confirmed payments', () => {+ const low = scoreAgentReputation(withPayments(5, 2)).score;+ const high = scoreAgentReputation(withPayments(40, 8)).score;+ expect(high).toBeGreaterThan(low);+ });++ it('max payments (50+) + 10 payers fills the payment bucket', () => {+ const { breakdown } = scoreAgentReputation(withPayments(50, 10));+ expect(breakdown.payments).toBe(45);+ });++ it('elevated failure rate shows in reasons', () => {+ const { reasons } = scoreAgentReputation(+ rep({+ payments: {+ confirmed_count: 30,+ confirmed_amount_atomics: '30000000',+ distinct_payers: 5,+ failed_count: 10,+ failure_rate: 0.25,+ },+ }),+ );+ expect(reasons.some((r) => /failure rate/i.test(r))).toBe(true);+ });+});++describe('scoreAgentReputation — distributions and buybacks', () => {+ it('credits a perfect distribution record', () => {+ const noDistrib = scoreAgentReputation(withPayments(20, 5)).score;+ const withDistrib = scoreAgentReputation({+ ...withPayments(20, 5),+ distributions: { confirmed: 5, failed: 0, success_rate: 1.0 },+ }).score;+ expect(withDistrib).toBeGreaterThan(noDistrib);+ });++ it('flags low distribution success rate in reasons', () => {+ const { reasons } = scoreAgentReputation({+ ...rep(),+ distributions: { confirmed: 1, failed: 3, success_rate: 0.25 },+ });+ expect(reasons.some((r) => /distribution/i.test(r))).toBe(true);+ });+});++describe('scoreAgentReputation — attestations', () => {+ it('adds attestation points up to the bucket max', () => {+ const noAtt = scoreAgentReputation(rep()).score;+ const withAtt = scoreAgentReputation({+ ...rep(),+ attestations: { feedback_count: 10, validation_count: 0, latest_attested_at: null },+ }).score;+ expect(withAtt).toBeGreaterThan(noAtt);+ });++ it('caps attestation contribution at 10 total attestations', () => {+ const a = scoreAgentReputation({+ ...rep(),+ attestations: { feedback_count: 10, validation_count: 0, latest_attested_at: null },+ }).breakdown.attestations;+ const b = scoreAgentReputation({+ ...rep(),+ attestations: { feedback_count: 50, validation_count: 0, latest_attested_at: null },+ }).breakdown.attestations;+ expect(a).toBe(b);+ });+});++describe('scoreAgentReputation — high-trust agent', () => {+ it('a well-established agent clears the flag threshold', () => {+ const { score, flagged } = scoreAgentReputation({+ ...rep(),+ deployed_mints: 2,+ payments: {+ confirmed_count: 50,+ confirmed_amount_atomics: '50000000',+ distinct_payers: 10,+ failed_count: 2,+ failure_rate: 0.04,+ },+ distributions: { confirmed: 8, failed: 0, success_rate: 1.0 },+ buybacks: { confirmed: 3, failed: 0, total_burn_atomics: '300000000' },+ attestations: { feedback_count: 8, validation_count: 2, latest_attested_at: null },+ });+ expect(score).toBeGreaterThanOrEqual(REPUTATION_FLAG_THRESHOLD);+ expect(flagged).toBe(false);+ });+});++describe('scoreAgentReputation — breakdown keys', () => {+ it('always returns a breakdown object with the four keys', () => {+ const { breakdown } = scoreAgentReputation(rep());+ expect(breakdown).toHaveProperty('payments');+ expect(breakdown).toHaveProperty('distributions');+ expect(breakdown).toHaveProperty('buybacks');+ expect(breakdown).toHaveProperty('attestations');+ });+});++// ── sweepAgentReputation ─────────────────────────────────────────────────────++const agentRow = (id = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee') => ({+ id,+ name: 'TestAgent',+ wallet_address: 'THREEsynthetic1111111111111111111111111111',+ last_active_at: new Date().toISOString(),+});++describe('sweepAgentReputation — aggregate output', () => {+ it('returns the correct shape', async () => {+ const fakeRep = rep({+ payments: { confirmed_count: 25, confirmed_amount_atomics: '25000000', distinct_payers: 5, failed_count: 0, failure_rate: 0 },+ });+ const result = await sweepAgentReputation({+ limit: 2,+ list: async () => [agentRow('aaaa0000-0000-0000-0000-000000000001'), agentRow('aaaa0000-0000-0000-0000-000000000002')],+ read: async () => fakeRep,+ });+ expect(result.mode).toBe('sweep');+ expect(result.count).toBe(2);+ expect(typeof result.avg_score).toBe('number');+ expect(typeof result.flagged_count).toBe('number');+ expect(Array.isArray(result.flagged)).toBe(true);+ expect(Array.isArray(result.agents)).toBe(true);+ expect(result.agents).toHaveLength(2);+ expect(typeof result.swept_at).toBe('string');+ });++ it('avg_score is 0 when the list is empty', async () => {+ const result = await sweepAgentReputation({+ limit: 5,+ list: async () => [],+ read: async () => rep(),+ });+ expect(result.count).toBe(0);+ expect(result.avg_score).toBe(0);+ expect(result.flagged_count).toBe(0);+ });++ it('avg_score matches the mean of per-agent scores', async () => {+ const makeRep = (confirmed) =>+ rep({+ payments: {+ confirmed_count: confirmed,+ confirmed_amount_atomics: String(confirmed * 1_000_000),+ distinct_payers: Math.min(confirmed, 5),+ failed_count: 0,+ failure_rate: 0,+ },+ });+ const scores = [0, 25, 50].map((c) => scoreAgentReputation(makeRep(c)).score);+ const expected = Math.round(scores.reduce((a, b) => a + b, 0) / scores.length);++ let callIdx = 0;+ const confirmeds = [0, 25, 50];+ const result = await sweepAgentReputation({+ limit: 3,+ list: async () => confirmeds.map((_, i) => agentRow(`aaaa0000-0000-0000-0000-${String(i).padStart(12, '0')}`)),+ read: async () => makeRep(confirmeds[callIdx++]),+ });+ expect(result.avg_score).toBe(expected);+ });++ it('flagged list only contains agents with score < REPUTATION_FLAG_THRESHOLD', async () => {+ let calls = 0;+ const result = await sweepAgentReputation({+ limit: 2,+ list: async () => [+ agentRow('aaaa0000-0000-0000-0000-000000000001'),+ agentRow('aaaa0000-0000-0000-0000-000000000002'),+ ],+ read: async () => {+ calls++;+ if (calls === 1) return rep(); // score 0 — should be flagged+ // a well-established agent — should not be flagged+ return rep({+ payments: { confirmed_count: 50, confirmed_amount_atomics: '50000000', distinct_payers: 10, failed_count: 0, failure_rate: 0 },+ distributions: { confirmed: 5, failed: 0, success_rate: 1 },+ buybacks: { confirmed: 2, failed: 0, total_burn_atomics: '200000000' },+ attestations: { feedback_count: 8, validation_count: 2, latest_attested_at: null },+ });+ },+ });+ expect(result.flagged_count).toBe(1);+ expect(result.flagged[0].score).toBeLessThan(REPUTATION_FLAG_THRESHOLD);+ });++ it('respects the limit (clamps to 50)', async () => {+ let listCalledWith;+ await sweepAgentReputation({+ limit: 999,+ list: async (n) => { listCalledWith = n; return []; },+ read: async () => rep(),+ });+ expect(listCalledWith).toBe(50);+ });+});++// ── Registry entry ────────────────────────────────────────────────────────────++describe('autonomous-registry — agent-reputation-active-sweep entry', () => {+ const entry = getFullRegistry().find((e) => e.id === 'agent-reputation-active-sweep');++ it('is present in the registry', () => {+ expect(entry).toBeDefined();+ });++ it('targets the correct path and method', () => {+ expect(entry.path).toBe('/api/x402/agent-reputation');+ expect(entry.method).toBe('POST');+ });++ it('carries the expected body', () => {+ expect(entry.body).toMatchObject({ mode: 'sweep', limit: 20 });+ });++ it('is in the health pipeline', () => {+ expect(entry.pipeline).toBe('health');+ });++ it('extractSignal returns the right keys for a real sweep response', () => {+ const fakeResponse = {+ mode: 'sweep',+ count: 15,+ avg_score: 62,+ flagged_count: 2,+ flagged: [+ { agent_id: 'aaaa0000-0000-0000-0000-000000000001', name: 'LowTrust', score: 12, reasons: [] },+ ],+ agents: [],+ swept_at: new Date().toISOString(),+ };+ const signal = entry.extractSignal(fakeResponse);+ expect(signal.count).toBe(15);+ expect(signal.avg_score).toBe(62);+ expect(signal.flagged_count).toBe(2);+ expect(signal.flagged_agent_ids).toEqual(['aaaa0000-0000-0000-0000-000000000001']);+ });++ it('extractSignal handles a null/empty response gracefully', () => {+ const signal = entry.extractSignal(null);+ expect(signal.count).toBe(0);+ expect(signal.flagged_count).toBe(0);+ expect(signal.flagged_agent_ids).toEqual([]);+ });++ it('cooldown_s is >= 1800 (audit-style signal)', () => {+ expect(entry.cooldown_s).toBeGreaterThanOrEqual(1800);+ });++ it('priority is in the 50–75 range', () => {+ expect(entry.priority).toBeGreaterThanOrEqual(50);+ expect(entry.priority).toBeLessThanOrEqual(75);+ });+});diff --git a/tests/x402-did-verification-canary.test.js b/tests/x402-did-verification-canary.test.jsnew file mode 100644index 000000000..3cddc34be--- /dev/null+++ b/tests/x402-did-verification-canary.test.js@@ -0,0 +1,152 @@+import { describe, it, expect } from 'vitest';++// USE-069: DID Verification Canary. validateDidDocument is the correctness core+// of the paid POST /api/x402/did verify mode — it decides `malformed`, which+// drives the `verified` verdict the autonomous loop records. These tests pin its+// behaviour against the real document shapes buildDidDocument() emits (jws ++// eip712) and the failure shapes a regression would produce.+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+process.env.X402_ASSET_MINT_SOLANA = USDC;++const { validateDidDocument } = await import('../api/x402/did.js');+const { getFullRegistry } = await import('../api/_lib/x402/autonomous-registry.js');++const goodJws = {+ '@context': [+ 'https://www.w3.org/ns/did/v1',+ 'https://w3id.org/security/suites/jws-2020/v1',+ 'https://w3id.org/security/suites/secp256k1recovery-2020/v1',+ ],+ id: 'did:web:three.ws',+ verificationMethod: [+ {+ id: 'did:web:three.ws#key-1',+ type: 'JsonWebKey2020',+ controller: 'did:web:three.ws',+ publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: 'abc', alg: 'EdDSA' },+ },+ ],+ assertionMethod: ['did:web:three.ws#key-1'],+ authentication: ['did:web:three.ws#key-1'],+ service: [{ id: 'did:web:three.ws#x402', type: 'x402PaymentService', serviceEndpoint: 'https://three.ws' }],+};++const goodEip712 = {+ '@context': [+ 'https://www.w3.org/ns/did/v1',+ 'https://w3id.org/security/suites/secp256k1recovery-2020/v1',+ ],+ id: 'did:web:three.ws',+ verificationMethod: [+ {+ id: 'did:pkh:eip155:1:0xabc#key-1',+ type: 'EcdsaSecp256k1RecoveryMethod2020',+ controller: 'did:web:three.ws',+ blockchainAccountId: 'eip155:1:0xabc',+ },+ ],+ assertionMethod: ['did:pkh:eip155:1:0xabc#key-1'],+ authentication: ['did:pkh:eip155:1:0xabc#key-1'],+ service: [{ id: 'did:web:three.ws#x402', type: 'x402PaymentService', serviceEndpoint: 'https://three.ws' }],+};++describe('validateDidDocument', () => {+ it('accepts a well-formed JWS did:web document', () => {+ const c = validateDidDocument(goodJws);+ expect(c.valid).toBe(true);+ expect(c.has_did_context).toBe(true);+ expect(c.assertion_resolves).toBe(true);+ expect(c.has_x402_service).toBe(true);+ });++ it('accepts a well-formed EIP-712 did:web document', () => {+ expect(validateDidDocument(goodEip712).valid).toBe(true);+ });++ it('rejects a null / non-object document', () => {+ expect(validateDidDocument(null).valid).toBe(false);+ expect(validateDidDocument('nope').valid).toBe(false);+ expect(validateDidDocument([]).valid).toBe(false);+ });++ it('rejects the not_configured error body (404 from the resolver)', () => {+ const c = validateDidDocument({ error: 'not_configured', message: 'no signing key' });+ expect(c.valid).toBe(false);+ expect(c.has_did_id).toBe(false);+ });++ it('rejects a document missing the W3C DID v1 context', () => {+ const c = validateDidDocument({ ...goodJws, '@context': ['https://example.com/v1'] });+ expect(c.has_did_context).toBe(false);+ expect(c.valid).toBe(false);+ });++ it('rejects an assertionMethod that references no real verification method', () => {+ const c = validateDidDocument({ ...goodJws, assertionMethod: ['did:web:three.ws#missing'] });+ expect(c.assertion_resolves).toBe(false);+ expect(c.valid).toBe(false);+ });++ it('rejects a document missing the x402 service binding', () => {+ const c = validateDidDocument({ ...goodJws, service: [] });+ expect(c.has_x402_service).toBe(false);+ expect(c.valid).toBe(false);+ });++ it('rejects a verification method missing the id/type/controller triple', () => {+ const c = validateDidDocument({ ...goodJws, verificationMethod: [{ id: 'x' }] });+ expect(c.has_verification_method).toBe(false);+ expect(c.valid).toBe(false);+ });+});++describe('did-verification-canary registry entry', () => {+ const entry = getFullRegistry().find((e) => e.id === 'did-verification-canary');++ it('is registered as an enabled paid POST canary', () => {+ expect(entry).toBeTruthy();+ expect(entry.enabled).toBe(true);+ expect(entry.method).toBe('POST');+ expect(entry.path).toBe('/api/x402/did');+ expect(entry.pipeline).toBe('health');+ expect(entry.body).toEqual({ did: 'did:three:canary', mode: 'verify' });+ expect(entry.cooldown_s).toBeGreaterThanOrEqual(300);+ });++ it('extractSignal lifts the verdict from a real verify response payload', () => {+ const response = {+ verified: true,+ latency_ms: 142,+ did: 'did:three:canary',+ mode: 'verify',+ resolved_did: 'did:web:three.ws',+ http_status: 200,+ within_latency: true,+ malformed: false,+ configured: true,+ checks: validateDidDocument(goodJws),+ ts: new Date().toISOString(),+ };+ expect(entry.extractSignal(response)).toEqual({+ verified: true,+ latency_ms: 142,+ resolved_did: 'did:web:three.ws',+ http_status: 200,+ malformed: false,+ within_latency: true,+ configured: true,+ });+ });++ it('extractSignal degrades to nulls on an empty/failed response', () => {+ expect(entry.extractSignal(null)).toEqual({+ verified: null,+ latency_ms: null,+ resolved_did: null,+ http_status: null,+ malformed: null,+ within_latency: null,+ configured: null,+ });+ });+});diff --git a/tests/x402-forge-content-health.test.js b/tests/x402-forge-content-health.test.jsnew file mode 100644index 000000000..98c927cf7--- /dev/null+++ b/tests/x402-forge-content-health.test.js@@ -0,0 +1,164 @@+// Forge: Content Generation Health (USE-072). The paid /api/x402/forge+// health_check mode runs ONE fast, real text completion over the platform's+// free-first LLM chain to canary the generative content lane, and must ALWAYS+// return a settled { generated, latency_ms, token_count } verdict — never throw —+// because a generator outage is the very signal the probe exists to catch. These+// prove the verdict shape, the latency-budget flag, the no-throw contract, and+// the autonomous registry entry that lifts the verdict into signal_data and+// raises/clears the forge performance alert.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the LLM chain so the probe is deterministic and offline (no provider keys+// required in CI). Each test sets the mock's behavior before calling the probe.+const llmComplete = vi.fn();+vi.mock('../api/_lib/llm.js', () => ({+ llmComplete: (...args) => llmComplete(...args),+}));++const { runForgeHealthCheck } = await import('../api/x402/forge.js');+const { getSelfRegistry } = await import('../api/_lib/x402/autonomous-registry.js');++function forgeHealthEntry() {+ const entry = getSelfRegistry().find((e) => e.id === 'forge-content-health');+ expect(entry, 'forge-content-health entry must be registered').toBeTruthy();+ return entry;+}++describe('runForgeHealthCheck — content-generation verdict', () => {+ beforeEach(() => llmComplete.mockReset());++ it('returns a generated verdict with the provider token count', async () => {+ llmComplete.mockResolvedValue({+ text: 'Solana is a high-throughput proof-of-stake blockchain.',+ provider: 'groq',+ model: 'llama-3.3-70b-versatile',+ usage: { input: 12, output: 11 },+ });++ const r = await runForgeHealthCheck({ prompt: 'Write one sentence about Solana.' });++ expect(r.mode).toBe('health_check');+ expect(r.type).toBe('text');+ expect(r.generated).toBe(true);+ expect(r.token_count).toBe(11); // provider-reported output tokens+ expect(r.provider).toBe('groq');+ expect(typeof r.latency_ms).toBe('number');+ expect(r.within_budget).toBe(true);+ expect(r.sample).toContain('Solana');+ });++ it('falls back to a char/4 token estimate when usage is absent', async () => {+ llmComplete.mockResolvedValue({ text: 'abcdefgh', provider: 'nvidia', model: 'x', usage: undefined });+ const r = await runForgeHealthCheck({});+ expect(r.generated).toBe(true);+ expect(r.token_count).toBe(2); // ceil(8/4)+ });++ it('supplies its own default prompt when none is given', async () => {+ llmComplete.mockResolvedValue({ text: 'ok', provider: 'groq', model: 'x', usage: { output: 1 } });+ await runForgeHealthCheck({});+ expect(llmComplete).toHaveBeenCalledTimes(1);+ expect(llmComplete.mock.calls[0][0].user).toBe('Write one sentence about Solana.');+ });++ it('flips within_budget false when the completion exceeds the 5s SLA', async () => {+ // Resolve only after the budget window so the measured latency exceeds it.+ llmComplete.mockImplementation(+ () => new Promise((res) => setTimeout(() => res({ text: 'slow', provider: 'groq', model: 'x', usage: { output: 1 } }), 5010)),+ );+ const r = await runForgeHealthCheck({});+ expect(r.generated).toBe(true);+ expect(r.within_budget).toBe(false);+ expect(r.latency_ms).toBeGreaterThan(5000);+ }, 10_000);++ it('never throws — a generator outage settles as generated:false', async () => {+ llmComplete.mockImplementation(async () => {+ throw Object.assign(new Error('no provider'), { code: 'llm_unavailable' });+ });+ const r = await runForgeHealthCheck({ prompt: 'Write one sentence about Solana.' });+ expect(r.generated).toBe(false);+ expect(r.token_count).toBe(0);+ expect(r.within_budget).toBe(false);+ expect(r.error).toBe('llm_unavailable');+ });+});++describe('registry entry — extractSignal lifts the verdict into signal_data', () => {+ it('marks a healthy fast probe', () => {+ const entry = forgeHealthEntry();+ const sig = entry.extractSignal({+ mode: 'health_check', type: 'text', generated: true,+ latency_ms: 820, token_count: 14, within_budget: true,+ provider: 'groq', model: 'llama-3.3-70b-versatile',+ });+ expect(sig).toMatchObject({ generated: true, latency_ms: 820, token_count: 14, slow: false });+ });++ it('flags a slow probe (>5s) as slow', () => {+ const entry = forgeHealthEntry();+ const sig = entry.extractSignal({ generated: true, latency_ms: 6200, token_count: 9, within_budget: false });+ expect(sig.slow).toBe(true);+ });++ it('carries the failure verdict through', () => {+ const entry = forgeHealthEntry();+ const sig = entry.extractSignal({ generated: false, latency_ms: 4100, token_count: 0, error: 'generation_failed' });+ expect(sig.generated).toBe(false);+ expect(sig.error).toBe('generation_failed');+ expect(sig.slow).toBe(false); // 4.1s is within budget; failure is signalled by generated:false+ });++ it('has the health pipeline wiring the spec requires', () => {+ const entry = forgeHealthEntry();+ expect(entry.pipeline).toBe('health');+ expect(entry.path).toBe('/api/x402/forge');+ expect(entry.method).toBe('POST');+ expect(entry.body).toEqual({ mode: 'health_check', type: 'text', prompt: 'Write one sentence about Solana.' });+ expect(entry.cooldown_s).toBe(600);+ });+});++describe('registry entry — storeValue raises/clears the forge performance alert', () => {+ function mockRedis() {+ const store = new Map();+ return {+ store,+ set: vi.fn((k, v) => { store.set(k, v); return Promise.resolve('OK'); }),+ del: vi.fn((k) => { store.delete(k); return Promise.resolve(1); }),+ };+ }++ it('sets the alert key when the probe is slow', async () => {+ const entry = forgeHealthEntry();+ const redis = mockRedis();+ await entry.storeValue({ redis, signalData: { generated: true, slow: true, latency_ms: 6100, provider: 'groq' } });+ expect(redis.set).toHaveBeenCalledTimes(1);+ const [key, payload, opts] = redis.set.mock.calls[0];+ expect(key).toBe('x402:forge-health:alert');+ expect(JSON.parse(payload).reason).toBe('latency_budget_exceeded');+ expect(opts.ex).toBeGreaterThan(0);+ });++ it('sets the alert key when generation failed', async () => {+ const entry = forgeHealthEntry();+ const redis = mockRedis();+ await entry.storeValue({ redis, signalData: { generated: false, slow: false, error: 'llm_unavailable' } });+ expect(redis.set).toHaveBeenCalledTimes(1);+ expect(JSON.parse(redis.set.mock.calls[0][1]).reason).toBe('generation_failed');+ });++ it('clears the alert key when healthy again', async () => {+ const entry = forgeHealthEntry();+ const redis = mockRedis();+ await entry.storeValue({ redis, signalData: { generated: true, slow: false, latency_ms: 700 } });+ expect(redis.del).toHaveBeenCalledWith('x402:forge-health:alert');+ expect(redis.set).not.toHaveBeenCalled();+ });++ it('never throws without a redis client', async () => {+ const entry = forgeHealthEntry();+ await expect(entry.storeValue({ redis: null, signalData: { generated: false } })).resolves.toBeUndefined();+ });+});diff --git a/tests/x402-mcp-tool-discovery.test.js b/tests/x402-mcp-tool-discovery.test.jsnew file mode 100644index 000000000..7e571e441--- /dev/null+++ b/tests/x402-mcp-tool-discovery.test.js@@ -0,0 +1,56 @@+import { describe, it, expect } from 'vitest';++import { getSelfRegistry } from '../api/_lib/x402/autonomous-registry.js';++// A representative /api/x402/mcp-tool-catalog (mode:discover) response.+const SAMPLE = {+ ok: true,+ mode: 'discover',+ total_tools: 35,+ priced_tools: 7,+ free_tools: 28,+ new_tools: [+ { name: 'segment_model', description: 'Split a mesh into named parts', priced: true, price_usdc: 0.04, input_fields: 2 },+ { name: 'text_to_animation', description: 'Generate an animation from text', priced: false, price_usdc: null, input_fields: 5 },+ ],+ changed_tools: [+ { name: 'render_avatar', change: 'price', price_usdc: 0.005, prev_price_usdc: 0.003, priced: true },+ ],+ removed_tools: ['legacy_tool'],+ ts: '2026-06-28T10:00:00Z',+};++describe('autonomous registry — mcp-tool-discovery entry', () => {+ const entry = getSelfRegistry().find((e) => e.id === 'mcp-tool-discovery');++ it('exists, is enabled, POST discover, discovery pipeline, 2h cooldown', () => {+ expect(entry).toBeTruthy();+ expect(entry.enabled).toBe(true);+ expect(entry.method).toBe('POST');+ expect(entry.pipeline).toBe('discovery');+ expect(entry.cooldown_s).toBe(7200);+ expect(entry.path).toBe('/api/x402/mcp-tool-catalog');+ expect(entry.body).toEqual({ mode: 'discover' });+ });++ it('extractSignal lifts the diff into the actionable signal shape', () => {+ const sig = entry.extractSignal(SAMPLE);+ expect(sig.total_tools).toBe(35);+ expect(sig.priced_tools).toBe(7);+ expect(sig.free_tools).toBe(28);+ // new_tools is flattened to a name list for feature flagging.+ expect(sig.new_tools).toEqual(['segment_model', 'text_to_animation']);+ expect(sig.new_count).toBe(2);+ expect(sig.changed_count).toBe(1);+ expect(sig.removed_tools).toEqual(['legacy_tool']);+ });++ it('extractSignal is null-safe on an empty/failed response', () => {+ const sig = entry.extractSignal({});+ expect(sig.total_tools).toBeNull();+ expect(sig.new_tools).toEqual([]);+ expect(sig.new_count).toBe(0);+ expect(sig.changed_count).toBe(0);+ expect(sig.removed_tools).toEqual([]);+ });+});diff --git a/tests/x402-pump-volume-anomaly.test.js b/tests/x402-pump-volume-anomaly.test.jsnew file mode 100644index 000000000..5d32fdd05--- /dev/null+++ b/tests/x402-pump-volume-anomaly.test.js@@ -0,0 +1,243 @@+import { describe, it, expect } from 'vitest';++import {+ summarizeWindowUsd,+ median,+ scoreVolumeAnomaly,+ buildAnomalySignal,+ classifyVolumeAnomaly,+ DEFAULTS,+} from '../api/_lib/x402/pump-volume-anomaly.js';++import { getSelfRegistry } from '../api/_lib/x402/autonomous-registry.js';++// ── pure-unit: summarizeWindowUsd ────────────────────────────────────────────+describe('summarizeWindowUsd', () => {+ const nowMs = 1_750_000_000_000; // fixed epoch for determinism+ const windowSec = 3600;++ function trade(offsetMs, amountUsd) {+ return { timestamp: new Date(nowMs - offsetMs).toISOString(), amountUsd };+ }++ it('sums trades inside the window', () => {+ const trades = [+ trade(100_000, '50'), // 100s ago — inside+ trade(3_599_000, '20'), // 3599s ago — inside (just)+ trade(3_601_000, '99'), // 3601s ago — outside+ ];+ const { usd, count } = summarizeWindowUsd(trades, nowMs, windowSec);+ expect(usd).toBeCloseTo(70);+ expect(count).toBe(2);+ });++ it('returns zero for an empty array', () => {+ const { usd, count } = summarizeWindowUsd([], nowMs, windowSec);+ expect(usd).toBe(0);+ expect(count).toBe(0);+ });++ it('skips trades with null/missing amountUsd', () => {+ const { usd } = summarizeWindowUsd(+ [{ timestamp: new Date(nowMs - 60_000).toISOString(), amountUsd: null }],+ nowMs,+ windowSec,+ );+ expect(usd).toBe(0);+ });++ it('accepts epoch-seconds timestamps', () => {+ const tSec = Math.floor((nowMs - 300_000) / 1000); // 5 min ago, in seconds+ const { usd } = summarizeWindowUsd(+ [{ timestamp: tSec, amountUsd: '42' }],+ nowMs,+ windowSec,+ );+ expect(usd).toBeCloseTo(42);+ });+});++// ── pure-unit: median ─────────────────────────────────────────────────────────+describe('median', () => {+ it('returns 0 for empty', () => expect(median([])).toBe(0));+ it('handles odd-length array', () => expect(median([1, 3, 5])).toBe(3));+ it('handles even-length array', () => expect(median([2, 4, 6, 8])).toBe(5));+ it('ignores non-finite values', () => expect(median([NaN, 4, Infinity])).toBe(4));+});++// ── pure-unit: scoreVolumeAnomaly ────────────────────────────────────────────+describe('scoreVolumeAnomaly', () => {+ function makeSamples(volumes) {+ return volumes.map((v, i) => ({+ mint: `Mint${i}`,+ name: `Token${i}`,+ symbol: `TK${i}`,+ window_usd: v,+ trade_count: Math.round(v / 10),+ }));+ }++ it('flags a 10× outlier as anomaly', () => {+ // median of [10,12,11,13] ≈ 11.5 → ratio ≈ 10×/11.5 < threshold only if top is 115+ const samples = makeSamples([1150, 10, 12, 11, 13]);+ const score = scoreVolumeAnomaly(samples, { ratioThreshold: 3, minUsd: 100 });+ expect(score.anomaly).toBe(true);+ expect(score.mint).toBe('Mint0');+ expect(score.volume_ratio).toBeGreaterThan(3);+ });++ it('does NOT flag a normal-spread distribution', () => {+ const samples = makeSamples([200, 180, 190, 170, 210]);+ const score = scoreVolumeAnomaly(samples, { ratioThreshold: 3, minUsd: 100 });+ expect(score.anomaly).toBe(false);+ });++ it('returns insufficient_active_coins when fewer than 3 coins have volume', () => {+ const samples = makeSamples([0, 0, 500]);+ const score = scoreVolumeAnomaly(samples, { ratioThreshold: 3, minUsd: 100 });+ expect(score.anomaly).toBe(false);+ expect(score.reason).toBe('insufficient_active_coins');+ });++ it('respects minUsd — tiny absolute volume is not an anomaly', () => {+ const samples = makeSamples([30, 0.5, 0.8, 0.9, 1.0]); // ratio huge but $30 < $250 default+ const score = scoreVolumeAnomaly(samples, { ratioThreshold: 3, minUsd: 250 });+ expect(score.anomaly).toBe(false);+ });++ it('carries trade_count of the top coin', () => {+ const samples = makeSamples([1000, 100, 110, 90, 105]);+ const score = scoreVolumeAnomaly(samples, { ratioThreshold: 3, minUsd: 100 });+ expect(score.trade_count).toBeGreaterThan(0);+ });+});++// ── pure-unit: buildAnomalySignal ────────────────────────────────────────────+describe('buildAnomalySignal', () => {+ it('returns bullish + high conviction for ratio > 5', () => {+ const score = {+ anomaly: true, mint: 'MintABC', symbol: 'XYZ', name: 'XYZ Token',+ volume_ratio: 8.5, top_window_usd: 4200, baseline_usd: 494, candidates: 20, active: 18,+ };+ const sig = buildAnomalySignal(score);+ expect(sig.signal).toBe('bullish');+ expect(sig.conviction).toBe('high');+ expect(sig.confidence).toBeGreaterThan(0.8);+ expect(sig.headline).toMatch(/8\.5/);+ });++ it('returns bullish + normal conviction for ratio 3–5', () => {+ const score = {+ anomaly: true, mint: 'MintDEF', symbol: 'ABC', name: 'ABC Token',+ volume_ratio: 4.1, top_window_usd: 1500, baseline_usd: 365, candidates: 15, active: 12,+ };+ const sig = buildAnomalySignal(score);+ expect(sig.signal).toBe('bullish');+ expect(sig.conviction).toBe('normal');+ });++ it('returns neutral when no anomaly detected', () => {+ const score = {+ anomaly: false, mint: null, symbol: null, volume_ratio: 1.2,+ candidates: 20, active: 18,+ };+ const sig = buildAnomalySignal(score);+ expect(sig.signal).toBe('neutral');+ expect(sig.conviction).toBe('none');+ expect(sig.confidence).toBe(0.5);+ });++ it('returns neutral with appropriate reason for insufficient coins', () => {+ const score = {+ anomaly: false, reason: 'insufficient_active_coins', candidates: 2, active: 1,+ };+ const sig = buildAnomalySignal(score);+ expect(sig.signal).toBe('neutral');+ expect(sig.rationale).toMatch(/Too few active coins/);+ });+});++// ── classifyVolumeAnomaly: oracle signal shape ────────────────────────────────+describe('classifyVolumeAnomaly', () => {+ it('tags high-conviction anomaly when ratio > 5', () => {+ const raw = {+ anomaly: true, mint: 'MintHC', volume_ratio: 7.3,+ signal: 'bullish', headline: 'spike detected', confidence: 0.88,+ token_symbol: 'HC', top_window_usd: 9000, baseline_usd: 1232,+ };+ const cls = classifyVolumeAnomaly(raw);+ expect(cls.anomaly).toBe(true);+ expect(cls.conviction).toBe('high');+ expect(cls.confidence).toBeGreaterThanOrEqual(0.85);+ expect(cls.topic).toBe('pump_volume_anomaly');+ expect(cls.mint).toBe('MintHC');+ });++ it('tags normal conviction for ratio 3–5', () => {+ const raw = {+ anomaly: true, mint: 'MintN', volume_ratio: 3.8,+ signal: 'bullish', confidence: 0.72,+ };+ const cls = classifyVolumeAnomaly(raw);+ expect(cls.conviction).toBe('normal');+ });++ it('tags none when no anomaly', () => {+ const raw = { anomaly: false, mint: null, volume_ratio: 1.1, signal: 'neutral', confidence: 0.5 };+ const cls = classifyVolumeAnomaly(raw);+ expect(cls.conviction).toBe('none');+ expect(cls.anomaly).toBe(false);+ });++ it('handles null/empty input gracefully', () => {+ const cls = classifyVolumeAnomaly(null);+ expect(cls.anomaly).toBe(false);+ expect(cls.conviction).toBe('none');+ expect(cls.topic).toBe('pump_volume_anomaly');+ });+});++// ── registry integration ──────────────────────────────────────────────────────+describe('autonomous registry — pump-volume-anomaly entry', () => {+ const entry = getSelfRegistry().find((e) => e.id === 'pump-volume-anomaly');++ it('exists and is enabled', () => {+ expect(entry).toBeTruthy();+ expect(entry.enabled).toBe(true);+ });++ it('is oracle pipeline, POST to crypto-intel, 300s cooldown, priority 88', () => {+ expect(entry.pipeline).toBe('oracle');+ expect(entry.method).toBe('POST');+ expect(entry.path).toBe('/api/x402/crypto-intel');+ expect(entry.body).toEqual({ topic: 'pump_volume_anomaly' });+ expect(entry.cooldown_s).toBe(300);+ expect(entry.priority).toBe(88);+ });++ it('extractSignal on a high-conviction anomaly response returns correct shape', () => {+ const raw = {+ topic: 'pump_volume_anomaly', anomaly: true,+ mint: 'SomeMint1111', volume_ratio: 6.2,+ signal: 'bullish', confidence: 0.9,+ token_symbol: 'SPIKE', top_window_usd: 5000, baseline_usd: 806,+ };+ const sig = entry.extractSignal(raw);+ expect(sig.anomaly).toBe(true);+ expect(sig.conviction).toBe('high');+ expect(sig.mint).toBe('SomeMint1111');+ expect(sig.volume_ratio).toBe(6.2);+ expect(sig.topic).toBe('pump_volume_anomaly');+ });++ it('extractSignal on a no-anomaly response returns conviction=none', () => {+ const raw = {+ topic: 'pump_volume_anomaly', anomaly: false,+ mint: null, volume_ratio: 1.4,+ signal: 'neutral', confidence: 0.5,+ };+ const sig = entry.extractSignal(raw);+ expect(sig.anomaly).toBe(false);+ expect(sig.conviction).toBe('none');+ });+});