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(api): add MCP Tool Latency Monitor SLA dashboard feed endpoint
nirholas7b47b26ce09a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f8ff2e121..f7e7618b6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Avatar Optimization Pipeline — nightly analysis of top avatars** — The platform now runs a nightly optimization sweep across the 50 most-viewed public avatars. Each model is analyzed for geometry and texture inefficiencies — Draco/Meshopt compression opportunities, oversized textures ready for KTX2 transcoding, non-indexed primitives, and redundant materials. Results are stored per-avatar so we can surface actionable improvement suggestions to creators. The pipeline runs autonomously via the x402 agent spend loop, paying $0.001 USDC per nightly batch. `[feature, infra]`- **Capabilities dashboard — live command center for all 4 autonomous features** — New /dashboard/capabilities page surfaces live status for Alpha Hunt, Coin Launcher, Auto-Claim, and Market Maker in one view. KPI strips show daily budget, total volume, claimable fees, and net P&L per capability. Tabbed tables show launched coins, schedule status, per-market inventory bars, and recent MM trades. Alpha Hunt trigger is now also configurable directly from the Sniper Strategies dashboard — full field set including min smart-money count, quality score, organic score, max market cap, and narrative keywords. (`/dashboard/capabilities`) `[feature, improvement]`- **CAPTCHA relief for rate-limited sign-ins** — Users who hit the sign-in rate limit (e.g. shared office/home network) now see a lightweight proof-of-work puzzle instead of a hard countdown. Solve it in a second or two and you can keep signing in immediately — no waiting, no support ticket. Built on Altcha (open source, MIT-licensed, no tracking or third-party service). (`/login`) `[improvement, security]`+- **Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive** — Every hour an autonomous agent runs the cheapest possible end-to-end test of the platform's payment rails. It reads the live payment challenge from a $0.001 endpoint and confirms a valid settlement route is still advertised on all three supported networks — Solana, Base, and BSC — then makes one real $0.001 USDC payment on Solana to prove the full build → verify → settle → receipt path actually completes on-chain, not just that the route exists. The per-network result is stored (x402_circuit_breaker) and folded into the internal health dashboard, so the moment a facilitator route goes dark or settlement breaks, it trips and shows up immediately instead of being discovered by a failed user payment. `[infra]`- **Design your own Memetic Launcher** — Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu. (`/launcher`) `[feature]`- **Fixed /play getting stuck on "too many requests"** — Opening /play could dead-end on a "Something went wrong — too many requests" screen, especially from a shared network or after a couple of reloads. The wallet sign-in step was sharing the same strict rate limit as login and trading, so a small burst of page loads exhausted it. Sign-in now has its own generous limit sized for a busy world, and if that check ever can't be reached, /play opens anyway instead of blocking — the game server still verifies token-gated worlds on entry. (`/play`) `[fix]`- **Hardened how the platform reads its rate-limit store credentials** — Fixed a configuration failure mode where the rate-limiter and cache store's address and access token could be drawn from two different sources and silently mismatch, which made every limiter and cache fall back to a weaker local mode and caused intermittent 'too many requests' errors and failed paid calls. The credentials are now always read together as one pair (and trimmed of stray whitespace), so a mismatch can't happen — keeping rate limits, paid endpoints, and caching reliable. (`/status`) `[fix, infra]`@@ -41,6 +42,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Production stability fixes — genome lineage, screen streaming, and x402 seeder** — Several reliability issues addressed: the agent genome breeding lineage page (/genome/lineage) was returning errors for all visitors due to a missing database table — now resolved. The live agent screen-streaming panel now correctly finds agents and loads their names. The x402 dance-tip seeder cron no longer floods the platform with thousands of failed payment attempts when Redis is temporarily unavailable — it detects the outage and skips the tick gracefully. Forge error logs now include the full vendor message from Replicate for faster ops triage. `[fix, infra]`- **Production stability fixes — payment sessions, Redis error handling, infra resilience** — Fixed a SQL syntax error that blocked payment session expiry and refunds (PostgreSQL does not allow LIMIT directly in UPDATE — now uses a CTE with FOR UPDATE SKIP LOCKED). Fixed esbuild class-name minification breaking NeonDB error detection in production — infrastructure errors (wrong DB credentials, Redis auth) now correctly return 503 and suppress alert storms instead of crashing every endpoint with 500. Added graceful Redis-unavailable handling to the usage flush buffer and the bounty board API. Fixed Express-style response methods in pulse-tick cron. `[fix, infra]`- **Restored token-launch, agent payments, and on-chain endpoints** — Fixed a class of missing API route mappings that left several backend endpoints unreachable in production: token launch (quote, prep, confirm), agent-to-agent payments, on-chain transaction prep/confirm, Solana and EVM checkout, and live-walk session control. The handlers were deployed but never wired to their public paths; they now respond correctly. Part of a wider audit that also restored wallet sign-in. `[fix]`+- **Reviews anchored on-chain — Solana attestations + ERC-8004 reputation** — Every agent and skill review is now permanently anchored on Solana via a platform-signed SPL-Memo attestation (threews.review.v1) the moment it's submitted. The review's rating and a SHA-256 hash of the text go on-chain — tamper-evident, publicly verifiable on Solscan. These attestations feed directly into the agent reputation score's on-chain identity pillar, so a well-reviewed agent earns higher trust points automatically. Users with MetaMask connected can also add a second, user-signed anchor on Base via the ERC-8004 ReputationRegistry for cross-chain provenance — a one-click "Anchor on Base" step appears after submitting a review. Both layers together make every review a real, verifiable act — not just a database row. (`/marketplace`) `[feature, improvement]`- **Sign-in cooldown is now exact — and there's more headroom before it trips** — If you ever hit "too many attempts" while signing in, the form now shows the real countdown the server hands back — a live timer on the button that ticks down and re-arms the form the instant you can try again, instead of a vague "try later". We also raised the per-network attempt allowance, so people signing in from shared office or campus connections are far less likely to be told to wait at all. Wrong-password and network-drop messages are now clearer and distinct, too. (`/login`) `[improvement]`- **Sign-in restored during rate-limiter outages** — Fixed an issue where a temporary outage of the distributed rate limiter could block every sign-in attempt platform-wide. The login and registration limiters now degrade gracefully to a local per-instance cap during such an outage — keeping sign-in available while still throttling brute-force attempts — instead of denying everyone. Money-moving limits are unchanged and still fail safe. `[fix, security]`- **Sign-up and 3D avatar reliability fixes** — Two fixes to the front door. The 3D avatar on the sign-up page — and on roughly fifty other pages that show a preview model — now loads reliably the first time, instead of occasionally staying blank until you reloaded; a timing race meant the model viewer could start loading a compressed avatar before its decoder was ready. Separately, the sign-up username field again enforces its rules (3–30 characters; letters, numbers, underscore and hyphen) as you type in the latest Chrome, where a stricter pattern-matching mode had quietly switched that live validation off. No action needed — both are automatic. (`/register`) `[fix]`diff --git a/api/_lib/migrations/20260629110000_x402_volume_metrics.sql b/api/_lib/migrations/20260629110000_x402_volume_metrics.sqlnew file mode 100644index 000000000..8d9da7e5c--- /dev/null+++ b/api/_lib/migrations/20260629110000_x402_volume_metrics.sql@@ -0,0 +1,42 @@+-- Per-endpoint volume ledger for the x402 Volume Bootstrap Loop.+--+-- Populated by the "Volume Bootstrap Loop" autonomous x402 pipeline+-- (api/_lib/x402/autonomous-registry.js → volume-bootstrap-loop, implemented in+-- api/_lib/x402/pipelines/volume-bootstrap-loop.js). On each run the loop+-- round-robins through the catalog of paid, cheap self x402 endpoints, pays each+-- a real on-chain USDC payment, and upserts one row per endpoint here —+-- accumulating call / success / fail counts and total + last USDC spent.+--+-- Downstream consumer: the platform's growth + status surfaces read this table+-- for proof-of-volume (total settled calls and USDC volume per endpoint — the+-- metric agentic.market ranks facilitators on) and per-endpoint liveness+-- (last_success / last_called_at confirms each paid endpoint is live). It+-- complements x402_autonomous_log (per-call history) with a compact rolling+-- aggregate keyed on endpoint.+--+-- The pipeline also creates this lazily (ensureSchema), so this migration is+-- belt-and-suspenders for environments that run db:migrate.++create table if not exists x402_volume_metrics (+ endpoint_key text primary key,+ service_name text,+ endpoint_path text,+ network text not null default 'solana:mainnet',+ asset text,+ call_count bigint not null default 0,+ success_count bigint not null default 0,+ fail_count bigint not null default 0,+ total_spent_atomic bigint not null default 0,+ last_amount_atomic bigint not null default 0,+ last_success boolean,+ last_status integer,+ last_tx_signature text,+ last_error text,+ last_run_id uuid,+ first_called_at timestamptz default now(),+ last_called_at timestamptz default now()+);++-- Status surfaces rank by most-recently swept endpoint.+create index if not exists x402_volume_metrics_last_called+ on x402_volume_metrics (last_called_at desc);diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex 5aa55aee0..7d8d4b984 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -38,9 +38,11 @@ import { run as volumeBootstrapLoop } from './pipelines/volume-bootstrap-loop.jsimport { run as cosmeticPricingAudit } from './pipelines/cosmetic-pricing-audit.js';import { run as modelMetadataEnrichment } from './pipelines/model-metadata-enrichment.js';import { run as forgeContentGeneration } from './pipelines/forge-content.js';+import { run as runAnimationRetargetQa, hasCanaryClips as hasAnimationQaCanaries } from './pipelines/animation-retarget-qa.js';import { runCircuitBreaker } from './circuit-breaker.js';import { mcpLatencySweep } from './mcp-latency-sweep.js';import { runStreamingMcpHealth } from './pipelines/streaming-mcp-health.js';+import { publicUrl } from '../r2.js';import {runSceneCaptureProcessor,SCENE_CAPTURE_ENDPOINT,@@ -65,13 +67,6 @@ const MCP_PERF_CANARY_MODEL =(process.env.X402_MCP_PERF_CANARY_MODEL || '').trim() ||'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/main/2.0/Box/glTF-Binary/Box.glb';-// Canary clip the Animation Retargeting QA probe pays to download. Designate a-// stable, paid, listed marketplace clip (an animation that exercises the-// retarget/canonicalize delivery path) via this env var. Unset → the probe stays-// disabled instead of paying for a non-existent id. Mirrors the well-known-mint-// canary pattern used by the token-intel health check.-const ANIM_QA_CLIP_ID = (process.env.X402_ANIMATION_QA_CLIP_ID || '').trim();-// ── GLB Canonicalization Pipeline (USE-011) ──────────────────────────────────// Real rig-reference avatars served from three.ws/avatars/*.glb. Each covers a// distinct skeleton convention that src/glb-canonicalize.js maps onto thediff --git a/api/_lib/x402/granite-health.js b/api/_lib/x402/granite-health.jsnew file mode 100644index 000000000..741a82ca7--- /dev/null+++ b/api/_lib/x402/granite-health.js@@ -0,0 +1,390 @@+// api/_lib/x402/granite-health.js+//+// IBM Granite Inference Health Check — the canary batch, response summariser,+// and value store for the `granite-inference-health` autonomous-loop entry+// (autonomous-registry.js).+//+// The autonomous loop makes ONE real x402-paid call to /api/ibm-mcp per tick: a+// single JSON-RPC batch that invokes all five paid IBM Granite tools (chat, code,+// embed, analyze, forecast) with tiny canary arguments. One payment settles the+// summed price of the batch (the IBM MCP server prices the whole request), and+// the loop records that paid round-trip to x402_autonomous_log like every other+// call. This module is the "extract and store value" stage:+//+// • summarizeGraniteHealth(responseBody) — parses the batch response, verifies+// each tool answered with its expected schema, and tallies token throughput.+// Wired as the entry's extractSignal → x402_autonomous_log.signal_data.+// • storeGraniteHealth(ctx) — upserts the per-tool verdict + throughput into+// `granite_inference_health`. Wired as the entry's storeValue.+// • readGraniteHealth() — the downstream read, consumed by+// GET /api/x402/granite-health (the watsonx backend SLA dashboard feed).+//+// Why a paid batch rather than five separate calls: the IBM MCP server charges+// the per-request total of every priced tools/call in the body, so a single+// batched request exercises the full watsonx inference surface for one on-chain+// payment (and one signed transaction) instead of five.++import { sql } from '../db.js';+import { logger } from '../usage.js';++const log = logger('granite-health');++export const GRANITE_SERVER = 'ibm-x402-mcp';++// The five paid Granite tools this health check exercises, in batch order. The+// JSON-RPC request `id` for each message is the tool name, so the summariser can+// match responses back to tools regardless of server-side ordering.+export const GRANITE_HEALTH_TOOLS = Object.freeze([+ 'ibm_granite_chat',+ 'ibm_granite_code',+ 'ibm_granite_embed',+ 'ibm_granite_analyze',+ 'ibm_granite_forecast',+]);++// Granite TTM (forecast) zero-shot models need a full context window; the+// smallest, ibm/granite-ttm-512-96-r2, expects 512 history points. Send exactly+// that so the canary forecast is a valid call rather than a context-underflow+// false negative. Generated once at module load.+const FORECAST_CONTEXT = 512;+const FORECAST_CANARY = (() => {+ // A deterministic synthetic hourly series (gentle trend + daily seasonality).+ // Anchored to a fixed epoch so the payload is identical on every run/instance.+ const startMs = Date.UTC(2026, 0, 1, 0, 0, 0);+ const hourMs = 3_600_000;+ const timestamps = new Array(FORECAST_CONTEXT);+ const values = new Array(FORECAST_CONTEXT);+ for (let i = 0; i < FORECAST_CONTEXT; i++) {+ timestamps[i] = new Date(startMs + i * hourMs).toISOString();+ values[i] = Number((100 + i * 0.05 + 8 * Math.sin((i / 24) * 2 * Math.PI)).toFixed(4));+ }+ return { timestamps, values, freq: '1h', prediction_length: 12, label: 'granite_health_canary' };+})();++// One JSON-RPC tools/call message per tool, each with minimal valid arguments.+// Generative tools cap their output (max_new_tokens / short prompts) so the+// canary stays cheap to run and small to store. `id === tool name` is what the+// summariser keys on.+function graniteHealthMessage(toolName) {+ const base = { jsonrpc: '2.0', id: toolName, method: 'tools/call' };+ switch (toolName) {+ case 'ibm_granite_chat':+ return {+ ...base,+ params: {+ name: toolName,+ arguments: {+ messages: [{ role: 'user', content: 'Health check. Reply with the single word: OK.' }],+ max_new_tokens: 8,+ temperature: 0,+ },+ },+ };+ case 'ibm_granite_code':+ return {+ ...base,+ params: {+ name: toolName,+ arguments: {+ task: 'explain',+ prompt: 'function add(a, b) { return a + b; }',+ language: 'JavaScript',+ },+ },+ };+ case 'ibm_granite_embed':+ return {+ ...base,+ params: { name: toolName, arguments: { inputs: ['health check canary'] } },+ };+ case 'ibm_granite_analyze':+ return {+ ...base,+ params: {+ name: toolName,+ arguments: {+ document: 'System health check ping. All subsystems nominal. No action required.',+ analysis_type: 'general',+ },+ },+ };+ case 'ibm_granite_forecast':+ return {+ ...base,+ params: { name: toolName, arguments: { ...FORECAST_CANARY } },+ };+ default:+ return { ...base, params: { name: toolName, arguments: {} } };+ }+}++// The full batch body the autonomous-loop entry sends as its `body`. Built once.+export const GRANITE_HEALTH_BATCH = GRANITE_HEALTH_TOOLS.map(graniteHealthMessage);++// Token usage is OpenAI-shaped on watsonx chat (prompt_tokens/completion_tokens/+// total_tokens). Read defensively in case a model returns the older+// input_token_count/generated_token_count naming.+function readUsage(structured) {+ const u = structured?.usage || {};+ const prompt = Number(u.prompt_tokens ?? u.input_tokens ?? u.input_token_count ?? 0) || 0;+ const completion = Number(u.completion_tokens ?? u.output_tokens ?? u.generated_token_count ?? 0) || 0;+ const total = Number(u.total_tokens ?? (prompt + completion)) || prompt + completion;+ return { prompt, completion, total };+}++// Does a tool's structuredContent match the shape that tool is contracted to+// return? A 200 response with a malformed body is a backend regression even+// though the JSON-RPC envelope succeeded — so schema conformance is tracked+// separately from "did it answer".+function schemaOk(toolName, s) {+ if (!s || s.ok === false) return false;+ switch (toolName) {+ case 'ibm_granite_chat':+ case 'ibm_granite_code':+ return typeof s.text === 'string';+ case 'ibm_granite_embed':+ return Array.isArray(s.vectors) && Number(s.dimensions) > 0 && Number(s.inputCount) > 0;+ case 'ibm_granite_analyze':+ // Either a parsed analysis (summary) or the documented raw fallback.+ return typeof s.summary === 'string' || typeof s.raw_response === 'string';+ case 'ibm_granite_forecast':+ return Array.isArray(s.forecast) && Number(s.forecastSteps) > 0;+ default:+ return true;+ }+}++/**+ * Parse the batched /api/ibm-mcp response into a health summary.+ * Verifies every Granite tool answered with its expected schema and tallies+ * token throughput. Pure + defensive — never throws, accepts a single response+ * object or an array (JSON-RPC batch).+ *+ * @param {object|Array} responseBody+ * @returns {object} summary stored to signal_data and granite_inference_health+ */+export function summarizeGraniteHealth(responseBody) {+ const list = Array.isArray(responseBody) ? responseBody : (responseBody != null ? [responseBody] : []);+ // Index responses by JSON-RPC id (== tool name in our batch).+ const byId = new Map();+ for (const msg of list) {+ if (msg && msg.id != null) byId.set(String(msg.id), msg);+ }++ const perTool = {};+ let toolsOk = 0;+ let schemaOkCount = 0;+ let promptTokens = 0;+ let completionTokens = 0;+ let totalTokens = 0;+ let embedDimensions = 0;+ let embedInputs = 0;+ let forecastSteps = 0;++ for (const tool of GRANITE_HEALTH_TOOLS) {+ const msg = byId.get(tool);+ if (!msg) {+ perTool[tool] = { ok: false, schema_ok: false, error: 'no_response' };+ continue;+ }+ if (msg.error) {+ perTool[tool] = {+ ok: false,+ schema_ok: false,+ error: msg.error?.message || `rpc_error_${msg.error?.code ?? 'unknown'}`,+ };+ continue;+ }+ const structured = msg.result?.structuredContent || null;+ const ok = !!structured && structured.ok !== false;+ const conform = ok && schemaOk(tool, structured);+ if (ok) toolsOk++;+ if (conform) schemaOkCount++;++ const usage = readUsage(structured);+ promptTokens += usage.prompt;+ completionTokens += usage.completion;+ totalTokens += usage.total;++ const entry = { ok, schema_ok: conform };+ if (usage.total) entry.tokens = usage.total;+ if (tool === 'ibm_granite_embed' && structured) {+ embedDimensions = Number(structured.dimensions) || 0;+ embedInputs = Number(structured.inputCount) || 0;+ entry.dimensions = embedDimensions;+ }+ if (tool === 'ibm_granite_forecast' && structured) {+ forecastSteps = Number(structured.forecastSteps) || 0;+ entry.forecast_steps = forecastSteps;+ }+ if (!conform && ok) entry.error = 'schema_mismatch';+ perTool[tool] = entry;+ }++ const toolsTotal = GRANITE_HEALTH_TOOLS.length;+ return {+ server: GRANITE_SERVER,+ tools_total: toolsTotal,+ tools_ok: toolsOk,+ tools_failed: toolsTotal - toolsOk,+ schema_ok_count: schemaOkCount,+ watsonx_responding: toolsOk > 0,+ all_healthy: toolsOk === toolsTotal && schemaOkCount === toolsTotal,+ prompt_tokens: promptTokens,+ completion_tokens: completionTokens,+ total_tokens: totalTokens,+ embed_dimensions: embedDimensions,+ embed_inputs: embedInputs,+ forecast_steps: forecastSteps,+ per_tool: perTool,+ };+}++let schemaReady = false;++export async function ensureGraniteHealthSchema(client = sql) {+ if (schemaReady) return;+ try {+ await client`+ CREATE TABLE IF NOT EXISTS granite_inference_health (+ id bigserial PRIMARY KEY,+ checked_at timestamptz NOT NULL DEFAULT now(),+ run_id uuid,+ server text NOT NULL DEFAULT 'ibm-x402-mcp',+ tools_total int NOT NULL,+ tools_ok int NOT NULL,+ tools_failed int NOT NULL,+ schema_ok_count int NOT NULL DEFAULT 0,+ watsonx_responding boolean NOT NULL DEFAULT false,+ all_healthy boolean NOT NULL DEFAULT false,+ prompt_tokens int NOT NULL DEFAULT 0,+ completion_tokens int NOT NULL DEFAULT 0,+ total_tokens int NOT NULL DEFAULT 0,+ embed_dimensions int NOT NULL DEFAULT 0,+ embed_inputs int NOT NULL DEFAULT 0,+ forecast_steps int NOT NULL DEFAULT 0,+ latency_ms int,+ per_tool jsonb+ )+ `;+ await client`CREATE INDEX IF NOT EXISTS granite_inference_health_checked_at_idx ON granite_inference_health (checked_at DESC)`;+ schemaReady = true;+ } catch (err) {+ // Non-fatal: a migration system or a concurrent run may own the table.+ if (!/already exists/i.test(err?.message || '')) {+ log.warn('granite_health_schema_failed', { message: err?.message });+ }+ schemaReady = true;+ }+}++/**+ * Persist one health-check verdict to granite_inference_health.+ * Wired as the registry entry's storeValue — the loop calls it after a+ * successful paid call. Receives the loop's storeValue ctx; never throws+ * (the loop also wraps it, but we degrade cleanly regardless).+ *+ * @param {object} ctx loop storeValue ctx+ * @param {Function} ctx.sql db tag (defaults to the shared client)+ * @param {object|Array} ctx.responseBody batched JSON-RPC response+ * @param {object} [ctx.signalData] summary from extractSignal (reused if present)+ * @param {string} [ctx.runId] loop run id (FK into x402_autonomous_log)+ * @param {number} [ctx.durationMs] paid round-trip latency+ * @returns {Promise<object|null>} the stored summary, or null if nothing stored+ */+export async function storeGraniteHealth(ctx = {}) {+ const client = ctx.sql || sql;+ const summary = ctx.signalData || summarizeGraniteHealth(ctx.responseBody);+ if (!summary || !summary.tools_total) return null;++ await ensureGraniteHealthSchema(client);+ await client`+ INSERT INTO granite_inference_health+ (run_id, server, tools_total, tools_ok, tools_failed, schema_ok_count,+ watsonx_responding, all_healthy, prompt_tokens, completion_tokens,+ total_tokens, embed_dimensions, embed_inputs, forecast_steps,+ latency_ms, per_tool, checked_at)+ VALUES+ (${ctx.runId || null}, ${summary.server}, ${summary.tools_total},+ ${summary.tools_ok}, ${summary.tools_failed}, ${summary.schema_ok_count},+ ${summary.watsonx_responding}, ${summary.all_healthy},+ ${summary.prompt_tokens}, ${summary.completion_tokens}, ${summary.total_tokens},+ ${summary.embed_dimensions}, ${summary.embed_inputs}, ${summary.forecast_steps},+ ${Number(ctx.durationMs) || null}, ${JSON.stringify(summary.per_tool || {})}, now())+ `;++ if (!summary.all_healthy) {+ log.warn('granite_health_degraded', {+ run_id: ctx.runId,+ tools_ok: summary.tools_ok,+ tools_failed: summary.tools_failed,+ schema_ok: summary.schema_ok_count,+ watsonx_responding: summary.watsonx_responding,+ });+ }+ return summary;+}++/**+ * Downstream read: latest health snapshot + recent token-throughput trend.+ * Consumed by GET /api/x402/granite-health.+ *+ * @param {object} [opts]+ * @param {number} [opts.windowHours=24] rolling window for the throughput rollup+ * @returns {Promise<object>}+ */+export async function readGraniteHealth({ windowHours = 24 } = {}) {+ await ensureGraniteHealthSchema();+ const latestRows = await sql`+ SELECT checked_at, run_id, server, tools_total, tools_ok, tools_failed,+ schema_ok_count, watsonx_responding, all_healthy,+ prompt_tokens, completion_tokens, total_tokens,+ embed_dimensions, embed_inputs, forecast_steps, latency_ms, per_tool+ FROM granite_inference_health+ ORDER BY checked_at DESC+ LIMIT 1+ `;+ const latest = latestRows[0] || null;++ const agg = await sql`+ SELECT count(*)::int AS checks,+ coalesce(sum(total_tokens), 0)::bigint AS tokens,+ coalesce(avg(latency_ms), 0)::int AS avg_latency_ms,+ coalesce(sum((all_healthy)::int), 0)::int AS healthy_checks+ FROM granite_inference_health+ WHERE checked_at > now() - (${windowHours} || ' hours')::interval+ `;+ const a = agg[0] || {};+ const checks = Number(a.checks) || 0;++ return {+ ok: true,+ server: GRANITE_SERVER,+ healthy: latest ? latest.all_healthy : true,+ watsonx_responding: latest ? latest.watsonx_responding : null,+ window_hours: windowHours,+ latest: latest+ ? {+ checked_at: latest.checked_at,+ run_id: latest.run_id,+ tools_total: latest.tools_total,+ tools_ok: latest.tools_ok,+ tools_failed: latest.tools_failed,+ schema_ok_count: latest.schema_ok_count,+ all_healthy: latest.all_healthy,+ total_tokens: latest.total_tokens,+ embed_dimensions: latest.embed_dimensions,+ forecast_steps: latest.forecast_steps,+ latency_ms: latest.latency_ms,+ per_tool: latest.per_tool,+ }+ : null,+ window: {+ checks,+ healthy_checks: Number(a.healthy_checks) || 0,+ uptime_pct: checks ? Math.round((Number(a.healthy_checks) / checks) * 1000) / 10 : null,+ total_tokens: Number(a.tokens) || 0,+ avg_latency_ms: Number(a.avg_latency_ms) || 0,+ },+ };+}diff --git a/api/_lib/x402/pay.js b/api/_lib/x402/pay.jsindex 329490ade..46cd77999 100644--- a/api/_lib/x402/pay.js+++ b/api/_lib/x402/pay.js@@ -68,7 +68,7 @@ export function parseSolanaAccept(challenge) {) || null;}-export function buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists }) {+export function buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists, nonce = 0 }) {const mint = new PublicKey(accept.asset);const payTo = new PublicKey(accept.payTo);const feePayer = new PublicKey(accept.extra.feePayer);@@ -81,9 +81,15 @@ export function buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtamint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,);+ // `nonce` perturbs the priority fee so a batch pipeline firing several+ // identical-amount payments (same payer/payTo/mint) against the one shared+ // blockhash produces a DISTINCT signature per call. Two byte-identical+ // transfers compile to the same message → same signature → the second is+ // rejected as already-processed. Single-call/inline callers leave nonce at 0+ // and pay the unchanged baseline of 5 µlamports.const ixs = [ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),- ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 }),+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 + (Number(nonce) % 997) }),];if (!receiverAtaExists) {ixs.push(createAssociatedTokenAccountIdempotentInstruction(diff --git a/api/_lib/x402/revenue-reconciliation.js b/api/_lib/x402/revenue-reconciliation.jsnew file mode 100644index 000000000..38564fb04--- /dev/null+++ b/api/_lib/x402/revenue-reconciliation.js@@ -0,0 +1,411 @@+// api/_lib/x402/revenue-reconciliation.js+//+// Payment Revenue Reconciliation — the work behind the `revenue-reconciliation`+// autonomous-registry entry (self/027). Runs daily.+//+// Financial integrity is non-negotiable for a live payment platform. Every row+// in our books that claims an on-chain settlement must correspond to a real,+// successful transaction on Solana — and a settlement that silently failed+// on-chain while our DB recorded success is exactly the kind of drift that+// corrupts revenue accounting. This pipeline cross-checks both directions:+//+// 1. Calls the free /api/x402-status probe through the shared x402 client+// (real payment if it ever becomes gated; today it answers 200 free) to+// confirm the payment wiring is live and to read the configured pay-to+// addresses the reconciliation is being measured against.+// 2. Pulls recent payment records that claim settlement from two books:+// • x402_autonomous_log — outbound spend (this loop's own payments)+// • agent_payment_intents — inbound revenue (user → agent payments)+// 3. Verifies each Solana settlement signature on-chain via+// getSignatureStatuses (batched, with full history search) and classifies:+// confirmed — tx exists, no error → reconciled+// failed_onchain — tx exists but reverted → DISCREPANCY+// missing_onchain — DB says settled, no tx on-chain → DISCREPANCY+// missing_signature — DB says settled, no signature kept → DISCREPANCY+// skipped_non_solana— EVM/Base settlement (not checked here)+// 4. Upserts a verdict row per record into `payment_reconciliation` and writes+// a compact summary into x402_autonomous_log.value_extracted.+//+// Wiring: declared as a run()-style entry in autonomous-registry.js. Reconciliation+// is READ-ONLY, so unlike paying pipelines it does not require the spend wallet —+// when the seed keypair is absent it falls back to a keyless RPC connection and+// still verifies the books (the status endpoint is free, so no payment is owed).+//+// Downstream consumer: the financial-integrity surface reads+// `payment_reconciliation WHERE NOT reconciled` to alert operators on unsettled+// or failed payments; the per-run summary in x402_autonomous_log.value_extracted+// gives the autonomous-loop status view an at-a-glance discrepancy count.++import { randomUUID } from 'node:crypto';++import { sql } from '../db.js';+import { env } from '../env.js';+import { logger } from '../usage.js';+import { solanaConnection } from '../solana/connection.js';+import {+ payX402, bootstrapSolanaContext, fetchWithTimeout,+ USDC_MINT, SOLANA_RPC,+} from './pay.js';++const log = logger('x402-revenue-reconciliation');++const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// How far back each run looks. A daily cadence with a 7-day window means every+// settlement is re-verified across roughly seven runs before it ages out — a+// transient RPC miss on one day self-heals on the next instead of latching a+// false discrepancy.+const LOOKBACK = '7 days';+// Cap rows pulled per book so a backlog can never make one tick unbounded; the+// rolling window guarantees full coverage across consecutive daily runs.+const MAX_RECORDS_PER_SOURCE = 250;+// getSignatureStatuses accepts up to 256 signatures per call.+const STATUS_BATCH = 256;++// Solana tx signatures are base58 (no 0x, 64-ish bytes → ~87–88 chars). An EVM+// hash is 0x + 64 hex. Used to route a record to the right verifier.+function isSolanaSignature(sig, network) {+ if (typeof sig !== 'string' || sig.length < 64) return false;+ if (sig.startsWith('0x')) return false;+ const net = String(network || '').toLowerCase();+ if (net.includes('base') || net.includes('evm') || net.includes('eip155')) return false;+ return /^[1-9A-HJ-NP-Za-km-z]+$/.test(sig); // base58 alphabet+}++async function ensureSchema() {+ await sql`+ CREATE TABLE IF NOT EXISTS payment_reconciliation (+ id bigserial PRIMARY KEY,+ source text NOT NULL, -- 'autonomous_log' | 'payment_intent'+ source_ref text NOT NULL, -- row id within that book+ tx_signature text,+ network text,+ amount_atomic bigint,+ db_status text NOT NULL, -- what the book claims+ chain_status text NOT NULL, -- confirmed|failed_onchain|missing_onchain|missing_signature|skipped_non_solana+ reconciled boolean NOT NULL,+ discrepancy text, -- null when reconciled+ detail jsonb,+ run_id uuid,+ first_seen_at timestamptz NOT NULL DEFAULT now(),+ checked_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (source, source_ref)+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS payment_reconciliation_open_idx+ ON payment_reconciliation (checked_at DESC) WHERE reconciled = false`;+ await sql`CREATE INDEX IF NOT EXISTS payment_reconciliation_sig_idx+ ON payment_reconciliation (tx_signature)`;+ // The autonomous log predates this pipeline; ensure the column it records its+ // reconciliation summary into exists (idempotent — shared with other run()s).+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;+}++// Pull outbound settlements this loop recorded as paid. Each should carry a+// tx_signature; a paid row missing one is itself a discrepancy.+async function loadOutboundRecords() {+ try {+ const rows = await sql`+ SELECT id, service_name, tx_signature, amount_atomic, network, ts+ FROM x402_autonomous_log+ WHERE success = true+ AND amount_atomic > 0+ AND ts > now() - ${LOOKBACK}::interval+ ORDER BY ts DESC+ LIMIT ${MAX_RECORDS_PER_SOURCE}+ `;+ return rows.map((r) => ({+ source: 'autonomous_log',+ source_ref: String(r.id),+ tx_signature: r.tx_signature || null,+ network: r.network || 'solana:mainnet',+ amount_atomic: Number(r.amount_atomic || 0),+ db_status: 'paid',+ label: r.service_name || null,+ }));+ } catch (err) {+ if (!err?.message?.includes('does not exist')) {+ log.warn('reconcile_outbound_load_failed', { message: err?.message });+ }+ return [];+ }+}++// Pull inbound revenue intents the platform marked settled. Table may not exist+// in a fresh env — treat that as "no inbound book", not an error.+async function loadInboundRecords() {+ try {+ const rows = await sql`+ SELECT id, status, tx_signature, amount, currency_mint, cluster, paid_at+ FROM agent_payment_intents+ WHERE status IN ('paid', 'settled', 'confirmed', 'completed')+ AND coalesce(paid_at, created_at) > now() - ${LOOKBACK}::interval+ ORDER BY coalesce(paid_at, created_at) DESC+ LIMIT ${MAX_RECORDS_PER_SOURCE}+ `;+ return rows.map((r) => ({+ source: 'payment_intent',+ source_ref: String(r.id),+ tx_signature: r.tx_signature || null,+ // Intents store cluster ('mainnet'/'devnet'); normalize to a network tag.+ network: r.cluster ? `solana:${r.cluster}` : 'solana:mainnet',+ amount_atomic: Number(r.amount || 0),+ db_status: r.status,+ label: r.currency_mint || null,+ }));+ } catch (err) {+ if (!err?.message?.includes('does not exist')) {+ log.warn('reconcile_inbound_load_failed', { message: err?.message });+ }+ return [];+ }+}++// Resolve the on-chain status of a batch of Solana signatures. Returns a Map of+// signature → { found, err } (err is the tx-level error object, null on success).+// A connection / RPC fault returns an empty map so callers degrade to "unknown"+// rather than crashing the run.+async function fetchOnChainStatuses(conn, signatures) {+ const out = new Map();+ for (let i = 0; i < signatures.length; i += STATUS_BATCH) {+ const batch = signatures.slice(i, i + STATUS_BATCH);+ try {+ const { value } = await conn.getSignatureStatuses(batch, { searchTransactionHistory: true });+ batch.forEach((sig, j) => {+ const st = value?.[j];+ out.set(sig, st ? { found: true, err: st.err ?? null } : { found: false, err: null });+ });+ } catch (err) {+ log.warn('reconcile_status_batch_failed', { from: i, message: err?.message });+ // Leave this batch unresolved — callers map a missing entry to 'unknown'+ // and do NOT flag a discrepancy on an RPC failure.+ }+ }+ return out;+}++// Classify one record given its on-chain status lookup. Pure.+function classifyRecord(rec, statuses) {+ const sig = rec.tx_signature;++ if (!sig) {+ return { chain_status: 'missing_signature', reconciled: false, discrepancy: 'missing_signature' };+ }+ if (!isSolanaSignature(sig, rec.network)) {+ // EVM/Base settlement — out of scope for the Solana verifier. Not a+ // discrepancy, just not checked on this rail.+ return { chain_status: 'skipped_non_solana', reconciled: true, discrepancy: null };+ }+ const st = statuses.get(sig);+ if (!st) {+ // RPC could not resolve the signature this run (no entry returned). Unknown,+ // not a discrepancy — the next daily run re-checks within the same window.+ return { chain_status: 'unknown', reconciled: true, discrepancy: null };+ }+ if (!st.found) {+ return { chain_status: 'missing_onchain', reconciled: false, discrepancy: 'db_settled_no_chain_tx' };+ }+ if (st.err != null) {+ return { chain_status: 'failed_onchain', reconciled: false, discrepancy: 'chain_tx_failed' };+ }+ return { chain_status: 'confirmed', reconciled: true, discrepancy: null };+}++async function upsertVerdict(runId, rec, verdict) {+ try {+ await sql`+ INSERT INTO payment_reconciliation+ (source, source_ref, tx_signature, network, amount_atomic,+ db_status, chain_status, reconciled, discrepancy, detail, run_id, checked_at)+ VALUES+ (${rec.source}, ${rec.source_ref}, ${rec.tx_signature}, ${rec.network},+ ${rec.amount_atomic}, ${rec.db_status}, ${verdict.chain_status},+ ${verdict.reconciled}, ${verdict.discrepancy},+ ${JSON.stringify({ label: rec.label || null })}, ${runId}, now())+ ON CONFLICT (source, source_ref) DO UPDATE SET+ tx_signature = EXCLUDED.tx_signature,+ network = EXCLUDED.network,+ amount_atomic = EXCLUDED.amount_atomic,+ db_status = EXCLUDED.db_status,+ chain_status = EXCLUDED.chain_status,+ reconciled = EXCLUDED.reconciled,+ discrepancy = EXCLUDED.discrepancy,+ detail = EXCLUDED.detail,+ run_id = EXCLUDED.run_id,+ checked_at = now()+ `;+ } catch (err) {+ log.warn('reconcile_upsert_failed', { ref: `${rec.source}:${rec.source_ref}`, message: err?.message });+ }+}++// Record this run's call + summary into x402_autonomous_log, including the+// value_extracted reconciliation summary. The loop also records its own aggregate+// summary row for run()-style entries; this is the granular row that carries the+// extracted value (the loop's recordLog does not write value_extracted).+async function recordLogRow(runId, { endpointUrl, amountAtomic, txSig, durationMs, success, errorMsg, summary }) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${'self'}, ${'Payment Revenue Reconciliation'}, ${endpointUrl},+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},+ ${summary ? JSON.stringify(summary) : null},+ ${summary ? JSON.stringify(summary) : null},+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'reconciliation'})+ `;+ } catch (err) {+ log.warn('reconcile_log_insert_failed', { message: err?.message });+ }+}++/**+ * Run the reconciliation. Conforms to the run()-style registry contract: the loop+ * hands { origin, buyer, conn, blockhash, mintInfo, remainingCap, runId }. Called+ * standalone (manual test) it bootstraps its own context; reconciliation is+ * read-only, so a missing spend wallet degrades to a keyless RPC connection+ * rather than skipping.+ *+ * Returns the aggregate outcome the loop records as one summary row:+ * { success, amountAtomic, txSig, errorMsg, responseData, skipped, note }+ */+export async function run(ctx = {}) {+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const statusUrl = `${origin}/api/x402-status`;+ const remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;+ const t0 = Date.now();++ // ── Schema first: without the sink there is nothing to store, so don't probe.+ try {+ await ensureSchema();+ } catch (err) {+ log.warn('reconcile_schema_failed', { message: err?.message });+ return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };+ }++ // ── Connection: reuse the loop's, else bootstrap. Reconciliation is read-only,+ // so a missing spend wallet is not fatal — fall back to a keyless RPC+ // connection (the status endpoint is free, so no payment is owed).+ let { buyer, conn, blockhash, mintInfo } = ctx;+ if (!conn) {+ try {+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));+ } catch (err) {+ log.info('reconcile_no_wallet', { reason: err.message });+ buyer = null; blockhash = null; mintInfo = null;+ conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });+ }+ }++ // ── Step 1: probe /api/x402-status. Pay through the real client when a wallet+ // is available (so a future gated status endpoint still settles); otherwise+ // fetch the free endpoint directly. Either way the call is recorded.+ let statusOk = false;+ let amountAtomic = 0;+ let txSig = null;+ let statusErr = null;+ let payTo = null;+ try {+ if (buyer && blockhash && mintInfo) {+ const r = await payX402({ url: statusUrl, method: 'GET', buyer, conn, blockhash, mintInfo, remainingCap });+ statusOk = r.success;+ amountAtomic = r.paid ? r.amountAtomic : 0;+ txSig = r.txSig || null;+ statusErr = r.errorMsg || null;+ payTo = r.responseBody?.env?.X402_PAY_TO_SOLANA || null;+ } else {+ const r = await fetchWithTimeout(statusUrl, {+ method: 'GET',+ headers: { 'content-type': 'application/json', 'user-agent': 'threews-x402-autonomous/1.0' },+ });+ statusOk = r.ok;+ statusErr = r.ok ? null : `http_${r.status}`;+ payTo = r.body?.env?.X402_PAY_TO_SOLANA || null;+ }+ } catch (err) {+ statusErr = err?.message || 'status_probe_failed';+ }++ // ── Step 2: gather the books and verify each settlement on-chain. A probe+ // failure does not block reconciliation — the books are read from our DB and+ // the chain directly, independent of the status endpoint.+ const records = [...(await loadOutboundRecords()), ...(await loadInboundRecords())];++ const solSigs = [...new Set(+ records.filter((r) => isSolanaSignature(r.tx_signature, r.network)).map((r) => r.tx_signature),+ )];+ const statuses = solSigs.length ? await fetchOnChainStatuses(conn, solSigs) : new Map();++ const summary = {+ checked: records.length,+ outbound: records.filter((r) => r.source === 'autonomous_log').length,+ inbound: records.filter((r) => r.source === 'payment_intent').length,+ reconciled: 0,+ confirmed: 0,+ discrepancies: 0,+ missing_onchain: 0,+ failed_onchain: 0,+ missing_signature: 0,+ skipped_non_solana: 0,+ unknown: 0,+ status_probe_ok: statusOk,+ pay_to_solana: payTo,+ };+ const flagged = [];++ for (const rec of records) {+ const verdict = classifyRecord(rec, statuses);+ summary[verdict.chain_status] = (summary[verdict.chain_status] || 0) + 1;+ if (verdict.reconciled) summary.reconciled += 1;+ else {+ summary.discrepancies += 1;+ flagged.push({ source: rec.source, ref: rec.source_ref, sig: rec.tx_signature, status: verdict.chain_status, amount_atomic: rec.amount_atomic });+ }+ await upsertVerdict(runId, rec, verdict);+ }+ // Keep only a bounded sample of flagged rows in the log summary; the full set+ // lives in payment_reconciliation.+ summary.flagged_sample = flagged.slice(0, 20);++ const durationMs = Date.now() - t0;+ const success = statusOk || records.length > 0;+ const errorMsg = success ? null : (statusErr || 'reconcile_no_data');++ await recordLogRow(runId, {+ endpointUrl: statusUrl, amountAtomic, txSig, durationMs, success, errorMsg, summary,+ });++ log.info('reconcile_complete', {+ run_id: runId,+ checked: summary.checked,+ reconciled: summary.reconciled,+ discrepancies: summary.discrepancies,+ missing_onchain: summary.missing_onchain,+ failed_onchain: summary.failed_onchain,+ status_probe_ok: statusOk,+ duration_ms: durationMs,+ });++ return {+ success,+ amountAtomic,+ txSig,+ errorMsg,+ skipped: false,+ responseData: {+ checked: summary.checked,+ reconciled: summary.reconciled,+ discrepancies: summary.discrepancies,+ missing_onchain: summary.missing_onchain,+ failed_onchain: summary.failed_onchain,+ missing_signature: summary.missing_signature,+ status_probe_ok: statusOk,+ },+ signalData: null,+ note: `reconcile checked=${summary.checked} ok=${summary.reconciled} disc=${summary.discrepancies}`,+ };+}diff --git a/data/changelog.json b/data/changelog.jsonindex 3080bb809..fa9ecd426 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,12 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-27",+ "title": "Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive",+ "summary": "Every hour an autonomous agent runs the cheapest possible end-to-end test of the platform's payment rails. It reads the live payment challenge from a $0.001 endpoint and confirms a valid settlement route is still advertised on all three supported networks — Solana, Base, and BSC — then makes one real $0.001 USDC payment on Solana to prove the full build → verify → settle → receipt path actually completes on-chain, not just that the route exists. The per-network result is stored (x402_circuit_breaker) and folded into the internal health dashboard, so the moment a facilitator route goes dark or settlement breaks, it trips and shows up immediately instead of being discovered by a failed user payment.",+ "tags": ["infra"]+ },{"date": "2026-06-27","title": "Reviews anchored on-chain — Solana attestations + ERC-8004 reputation",diff --git a/public/changelog.json b/public/changelog.jsonindex dd938d42c..9e854eab5 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T23:01:09.161Z",+ "generated_at": "2026-06-27T23:06:31.898Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -173,6 +173,16 @@"security"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive",+ "summary": "Every hour an autonomous agent runs the cheapest possible end-to-end test of the platform's payment rails. It reads the live payment challenge from a $0.001 endpoint and confirms a valid settlement route is still advertised on all three supported networks — Solana, Base, and BSC — then makes one real $0.001 USDC payment on Solana to prove the full build → verify → settle → receipt path actually completes on-chain, not just that the route exists. The per-network result is stored (x402_circuit_breaker) and folded into the internal health dashboard, so the moment a facilitator route goes dark or settlement breaks, it trips and shows up immediately instead of being discovered by a failed user payment.",+ "link": null,+ "tags": [+ "infra"+ ]+ },{"date": "2026-06-27","type": "update",@@ -377,6 +387,17 @@"fix"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Reviews anchored on-chain — Solana attestations + ERC-8004 reputation",+ "summary": "Every agent and skill review is now permanently anchored on Solana via a platform-signed SPL-Memo attestation (threews.review.v1) the moment it's submitted. The review's rating and a SHA-256 hash of the text go on-chain — tamper-evident, publicly verifiable on Solscan. These attestations feed directly into the agent reputation score's on-chain identity pillar, so a well-reviewed agent earns higher trust points automatically. Users with MetaMask connected can also add a second, user-signed anchor on Base via the ERC-8004 ReputationRegistry for cross-chain provenance — a one-click \"Anchor on Base\" step appears after submitting a review. Both layers together make every review a real, verifiable act — not just a database row.",+ "link": "/marketplace",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-27","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex e3887d373..b9ba0308e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -134,6 +134,14 @@<category>improvement</category><description>Users who hit the sign-in rate limit (e.g. shared office/home network) now see a lightweight proof-of-work puzzle instead of a hard countdown. Solve it in a second or two and you can keep signing in immediately — no waiting, no support ticket. Built on Altcha (open source, MIT-licensed, no tracking or third-party service).</description></item>+ <item>+ <title>Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-27:Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>infra</category>+ <description>Every hour an autonomous agent runs the cheapest possible end-to-end test of the platform's payment rails. It reads the live payment challenge from a $0.001 endpoint and confirms a valid settlement route is still advertised on all three supported networks — Solana, Base, and BSC — then makes one real $0.001 USDC payment on Solana to prove the full build → verify → settle → receipt path actually completes on-chain, not just that the route exists. The per-network result is stored (x402_circuit_breaker) and folded into the internal health dashboard, so the moment a facilitator route goes dark or settlement breaks, it trips and shows up immediately instead of being discovered by a failed user payment.</description>+ </item><item><title>Design your own Memetic Launcher</title><link>https://three.ws/launcher</link>@@ -286,6 +294,14 @@<category>fix</category><description>Fixed a class of missing API route mappings that left several backend endpoints unreachable in production: token launch (quote, prep, confirm), agent-to-agent payments, on-chain transaction prep/confirm, Solana and EVM checkout, and live-walk session control. The handlers were deployed but never wired to their public paths; they now respond correctly. Part of a wider audit that also restored wallet sign-in.</description></item>+ <item>+ <title>Reviews anchored on-chain — Solana attestations + ERC-8004 reputation</title>+ <link>https://three.ws/marketplace</link>+ <guid isPermaLink="false">2026-06-27:Reviews anchored on-chain — Solana attestations + ERC-8004 reputation</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Every agent and skill review is now permanently anchored on Solana via a platform-signed SPL-Memo attestation (threews.review.v1) the moment it's submitted. The review's rating and a SHA-256 hash of the text go on-chain — tamper-evident, publicly verifiable on Solscan. These attestations feed directly into the agent reputation score's on-chain identity pillar, so a well-reviewed agent earns higher trust points automatically. Users with MetaMask connected can also add a second, user-signed anchor on Base via the ERC-8004 ReputationRegistry for cross-chain provenance — a one-click "Anchor on Base" step appears after submitting a review. Both layers together make every review a real, verifiable act — not just a database row.</description>+ </item><item><title>Sign-in cooldown is now exact — and there's more headroom before it trips</title><link>https://three.ws/login</link>diff --git a/public/features.json b/public/features.jsonindex 801f9740b..cfb138f8f 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T23:01:09.135Z",+ "generated_at": "2026-06-27T23:06:31.432Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/test-scene-capture-processor.mjs b/scripts/test-scene-capture-processor.mjsnew file mode 100644index 000000000..cb5df0a71--- /dev/null+++ b/scripts/test-scene-capture-processor.mjs@@ -0,0 +1,90 @@+#!/usr/bin/env node+// Manual smoke test for the Scene Capture Video Queue Processor.+//+// Drives the real run() against the live DB + Solana + GPU worker — no mocks.+// Exercises the same path the autonomous loop invokes, then prints the outcome,+// the affected scene_capture_queue rows, and the most recent x402_autonomous_log+// entry so you can confirm a row was recorded and the value stored.+//+// Usage:+// # enqueue a video then process it (pays $0.01, submits to the GPU worker)+// node scripts/test-scene-capture-processor.mjs --enqueue https://host/clip.mp4+//+// # just run one processing tick over whatever is already queued+// node scripts/test-scene-capture-processor.mjs+//+// Requires (degrades gracefully when missing): DATABASE_URL, the x402 seed+// wallet (X402_SEED_SOLANA_SECRET_BASE58 / X402_AGENT_SOLANA_SECRET_BASE58),+// X402_ASSET_MINT_SOLANA + SOLANA_RPC_URL, and GCP_VIDEO2SCENE_URL ++// GCP_RECONSTRUCTION_KEY for the GPU worker.++import { randomUUID } from 'node:crypto';+import { sql } from '../api/_lib/db.js';+import {+ runSceneCaptureProcessor,+ enqueueSceneCapture,+ SCENE_CAPTURE_ENDPOINT,+} from '../api/_lib/x402/scene-capture-processor.js';++function arg(flag) {+ const i = process.argv.indexOf(flag);+ return i >= 0 ? process.argv[i + 1] : null;+}++async function main() {+ const enqueueUrl = arg('--enqueue');+ if (enqueueUrl) {+ const id = await enqueueSceneCapture({ videoUrl: enqueueUrl, params: { fps: 8 }, enqueuedBy: 'manual-test' });+ console.log(`enqueued scene_capture_queue row #${id} for ${enqueueUrl}`);+ }++ console.log(`\nrunning processor (metering endpoint: ${SCENE_CAPTURE_ENDPOINT}) …\n`);+ const outcome = await runSceneCaptureProcessor({});+ console.log('run() outcome:');+ console.dir(outcome, { depth: 6 });++ // Demonstrate the recording the autonomous loop performs for every run() —+ // the loop owns this insert in production; here we replicate it so the manual+ // test can confirm a row lands with the extracted value in signal_data.+ const runId = randomUUID();+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url, network,+ amount_atomic, asset, tx_signature, response_data, signal_data,+ duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, 'self', 'Scene Capture Video Queue Processor',+ ${SCENE_CAPTURE_ENDPOINT}, 'solana:mainnet',+ ${outcome.amountAtomic || 0}, ${process.env.X402_ASSET_MINT_SOLANA || null},+ ${outcome.txSig || null},+ ${outcome.responseData ? JSON.stringify(outcome.responseData) : null},+ ${outcome.signalData ? JSON.stringify(outcome.signalData) : null},+ ${0}, ${outcome.success ?? false}, ${outcome.errorMsg || null}, 'self')+ `;+ console.log(`\nrecorded x402_autonomous_log row (run_id=${runId})`);+ } catch (err) {+ console.warn(`\ncould not record log row: ${err?.message}`);+ }++ const queue = await sql`+ SELECT id, status, job_id, result_url, num_points, frames, tx_signature, amount_atomic, error_msg, updated_at+ FROM scene_capture_queue ORDER BY updated_at DESC LIMIT 5+ `.catch((e) => { console.warn('queue read failed:', e?.message); return []; });+ console.log('\nscene_capture_queue (latest 5):');+ console.table(queue);++ const logRows = await sql`+ SELECT service_name, amount_atomic, tx_signature, success, error_msg, signal_data, ts+ FROM x402_autonomous_log+ WHERE service_name = 'Scene Capture Video Queue Processor'+ ORDER BY ts DESC LIMIT 3+ `.catch(() => []);+ console.log('\nx402_autonomous_log (latest 3 for this pipeline):');+ console.dir(logRows, { depth: 6 });+}++main().then(() => process.exit(0)).catch((err) => {+ console.error('manual test failed:', err);+ process.exit(1);+});diff --git a/vercel.json b/vercel.jsonindex 97eafb4d1..4c9e5cc4c 100644--- a/vercel.json+++ b/vercel.json@@ -76,6 +76,10 @@"api/cron/x402-autonomous-loop.js": {"maxDuration": 120},+ "api/cron/avatar-thumbnail-render.js": {+ "maxDuration": 120,+ "memory": 1024+ },"api/cron/pulse-tick.js": {"maxDuration": 120},@@ -4662,6 +4666,10 @@"path": "/api/cron/x402-autonomous-loop","schedule": "*/5 * * * *"},+ {+ "path": "/api/cron/avatar-thumbnail-render",+ "schedule": "*/10 * * * *"+ },{"path": "/api/cron/pulse-tick","schedule": "*/2 * * * *"