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: Implement comprehensive x402 ring economy tasks for production readiness
nrpof91ae68f20f0
diff --git a/packages/agent-sniper/package-lock.json b/packages/agent-sniper/package-lock.jsonindex 58516c570..d61eda79b 100644--- a/packages/agent-sniper/package-lock.json+++ b/packages/agent-sniper/package-lock.json@@ -18,6 +18,8 @@"@three-ws/x402-server": "^0.1.0","bn.js": "^5.2.3","bs58": "^6.0.0",+ "express": "^5.2.1",+ "playwright": "^1.61.1","ws": "^8.21.0","zod": "^3.23.8"},@@ -6626,20 +6628,6 @@"node": ">= 0.8.0"}},- "node_modules/@react-native/dev-middleware/node_modules/utf-8-validate": {- "version": "5.0.10",- "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",- "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",- "extraneous": true,- "hasInstallScript": true,- "license": "MIT",- "dependencies": {- "node-gyp-build": "^4.3.0"- },- "engines": {- "node": ">=6.14.2"- }- },"node_modules/@react-native/dev-middleware/node_modules/ws": {"version": "7.5.11","resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz",@@ -9837,16 +9825,6 @@}}},- "node_modules/colyseus/node_modules/zod": {- "version": "4.4.3",- "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",- "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",- "extraneous": true,- "license": "MIT",- "funding": {- "url": "https://github.com/sponsors/colinhacks"- }- },"node_modules/combined-stream": {"version": "1.0.8","resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",@@ -12216,20 +12194,6 @@"node": ">=14.0"}},- "node_modules/hardhat/node_modules/utf-8-validate": {- "version": "5.0.10",- "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",- "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",- "extraneous": true,- "hasInstallScript": true,- "license": "MIT",- "dependencies": {- "node-gyp-build": "^4.3.0"- },- "engines": {- "node": ">=6.14.2"- }- },"node_modules/hardhat/node_modules/ws": {"version": "7.5.11","resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz",@@ -13926,20 +13890,6 @@"url": "https://github.com/sponsors/sindresorhus"}},- "node_modules/jayson/node_modules/utf-8-validate": {- "version": "5.0.10",- "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",- "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",- "extraneous": true,- "hasInstallScript": true,- "license": "MIT",- "dependencies": {- "node-gyp-build": "^4.3.0"- },- "engines": {- "node": ">=6.14.2"- }- },"node_modules/jayson/node_modules/ws": {"version": "7.5.11","resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz",@@ -16661,20 +16611,6 @@"node": ">=0.10.0"}},- "node_modules/metro/node_modules/utf-8-validate": {- "version": "5.0.10",- "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",- "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",- "extraneous": true,- "hasInstallScript": true,- "license": "MIT",- "dependencies": {- "node-gyp-build": "^4.3.0"- },- "engines": {- "node": ">=6.14.2"- }- },"node_modules/metro/node_modules/ws": {"version": "7.5.11","resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz",@@ -18141,6 +18077,50 @@"node": ">=8"}},+ "node_modules/playwright": {+ "version": "1.61.1",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",+ "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.61.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.61.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",+ "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/playwright/node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },"node_modules/possible-typed-array-names": {"version": "1.1.0","resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",@@ -18553,20 +18533,6 @@"ws": "^7"}},- "node_modules/react-devtools-core/node_modules/utf-8-validate": {- "version": "5.0.10",- "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",- "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",- "extraneous": true,- "hasInstallScript": true,- "license": "MIT",- "dependencies": {- "node-gyp-build": "^4.3.0"- },- "engines": {- "node": ">=6.14.2"- }- },"node_modules/react-devtools-core/node_modules/ws": {"version": "7.5.11","resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz",@@ -18704,20 +18670,6 @@"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==","license": "MIT"},- "node_modules/react-native/node_modules/utf-8-validate": {- "version": "5.0.10",- "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",- "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",- "extraneous": true,- "hasInstallScript": true,- "license": "MIT",- "dependencies": {- "node-gyp-build": "^4.3.0"- },- "engines": {- "node": ">=6.14.2"- }- },"node_modules/react-native/node_modules/ws": {"version": "7.5.11","resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz",diff --git a/packages/agent-sniper/package.json b/packages/agent-sniper/package.jsonindex f997af7fd..b411213b4 100644--- a/packages/agent-sniper/package.json+++ b/packages/agent-sniper/package.json@@ -61,12 +61,13 @@"@modelcontextprotocol/sdk": "^1.29.0","@pump-fun/pump-sdk": "^1.36.0","@pump-fun/pump-swap-sdk": "^1.17.0",- "@three-ws/agent-payments": "^3.2.0","@solana/spl-token": "^0.4.14","@solana/web3.js": "^1.98.4",+ "@three-ws/agent-payments": "^3.2.0","@three-ws/x402-server": "^0.1.0","bn.js": "^5.2.3","bs58": "^6.0.0",+ "playwright": "^1.61.1","ws": "^8.21.0","zod": "^3.23.8"},diff --git a/packages/agent-sniper/runbooks/scenes/caster.json b/packages/agent-sniper/runbooks/scenes/caster.jsonnew file mode 100644index 000000000..378550032--- /dev/null+++ b/packages/agent-sniper/runbooks/scenes/caster.json@@ -0,0 +1,30 @@+[+ {+ "key": "console",+ "url": "http://localhost:8787/",+ "caption": "I control 33 wallets. Watch me arm them and hunt pump.fun launches.",+ "waitFor": "body",+ "dwellMs": 12000+ },+ {+ "key": "console-positions",+ "url": "http://localhost:8787/",+ "caption": "Open positions, live PnL — every fill is a real on-chain buy.",+ "waitFor": "body",+ "dwellMs": 12000+ },+ {+ "key": "theater",+ "url": "https://three.ws/theater",+ "caption": "This is the platform my fleet trades on — the Live Trading Theater.",+ "waitFor": "canvas, main",+ "dwellMs": 9000+ },+ {+ "key": "arena",+ "url": "https://three.ws/play/arena",+ "caption": "The Sniper Arena — autonomous agents, real trades, live.",+ "waitFor": "canvas, main",+ "dwellMs": 9000+ }+]diff --git a/packages/agent-sniper/runbooks/scenes/onchain-truth.json b/packages/agent-sniper/runbooks/scenes/onchain-truth.jsonnew file mode 100644index 000000000..597b28db2--- /dev/null+++ b/packages/agent-sniper/runbooks/scenes/onchain-truth.json@@ -0,0 +1,37 @@+[+ {+ "key": "console",+ "url": "http://localhost:8787/",+ "caption": "33 autonomous agents. One throwaway funder. 3 SOL. All real.",+ "waitFor": "body",+ "dwellMs": 9000+ },+ {+ "key": "console-activity",+ "url": "http://localhost:8787/",+ "caption": "Live decision feed — every agent scores each new pump.fun launch.",+ "waitFor": "body",+ "dwellMs": 9000+ },+ {+ "key": "solscan-funder",+ "url": "https://solscan.io/account/GiE8RvENLjJSEsQRZdmUzoivDWDdJnXtL8PPAwWPdVRk",+ "caption": "The funder wallet — funded once, fanned out to 33.",+ "waitFor": "body",+ "dwellMs": 8000+ },+ {+ "key": "theater",+ "url": "https://three.ws/theater",+ "caption": "Live Trading Theater — the platform these agents trade on.",+ "waitFor": "canvas, main",+ "dwellMs": 7000+ },+ {+ "key": "trades",+ "url": "https://three.ws/trades",+ "caption": "Live Trade Feed — real pump.fun fills, on-chain.",+ "waitFor": "main, body",+ "dwellMs": 7000+ }+]diff --git a/packages/agent-sniper/scripts/fleet.js b/packages/agent-sniper/scripts/fleet.jsindex ecf6cdd9d..85dbdde77 100644--- a/packages/agent-sniper/scripts/fleet.js+++ b/packages/agent-sniper/scripts/fleet.js@@ -31,7 +31,10 @@ import {} from '@solana/web3.js';import bs58 from 'bs58';-import { presets } from '../src/index.js';+import {+ presets, createSniper, createMemoryStore, createSelfCustodyWallet,+ createPumpClient, createWeb3Executor, createPumpPortalFeed,+} from '../src/index.js';const HERE = path.dirname(fileURLToPath(import.meta.url));@@ -253,8 +256,30 @@ async function cmdRun(flags) {console.log(`\n Starting sniper — ${keys.agents.length} agents · ${mode.toUpperCase()} · ${keys.network} · ${perTrade} SOL/trade`);console.log(` RPC: ${rpcUrl ? rpcUrl.replace(/api-key=[^&]+/i, 'api-key=***') : 'default'}\n`);- const sniper = await presets.local({ network: keys.network, mode, rpcUrl, strategies, secrets });- await sniper.start();+ // --serve mounts the package's own HTTP API + web console over THIS fleet's+ // live sniper/store, so packages/agent-sniper/web/console.html (and the+ // recorder's dashboard scene) shows our exact 33 agents, not a fresh engine.+ let sniper;+ if (flags.serve) {+ const port = Number(flags.port) || 8787;+ const store = createMemoryStore({ strategies });+ const solana = await createPumpClient({ network: keys.network, rpcUrl });+ sniper = createSniper({+ config: { network: keys.network, mode, rpcUrl },+ store,+ wallet: createSelfCustodyWallet({ secrets }),+ solana,+ executor: createWeb3Executor(),+ feed: createPumpPortalFeed({ network: keys.network }),+ });+ const { serve } = await import('../src/faces/api.js');+ await serve({ sniper, store, adminToken: process.env.SNIPER_ADMIN_TOKEN }, { port });+ sniper.__started = true; // serve() already called start()+ console.log(` Console + API on http://localhost:${port}/ (film this)\n`);+ } else {+ sniper = await presets.local({ network: keys.network, mode, rpcUrl, strategies, secrets });+ await sniper.start();+ }const tick = setInterval(() => {const s = sniper.stats();diff --git a/packages/agent-sniper/scripts/reel.js b/packages/agent-sniper/scripts/reel.jsnew file mode 100644index 000000000..a417de4b2--- /dev/null+++ b/packages/agent-sniper/scripts/reel.js@@ -0,0 +1,173 @@+#!/usr/bin/env node+// reel.js — a scene-driven Playwright recorder that films the three.ws UI while+// the throwaway sniper fleet funds itself and trades live. Produces one webm of+// the full run plus a screenshot per scene. Pairs with fleet.js: fleet.js does+// the real on-chain work, reel.js films the platform surfaces that visualize it.+//+// Each SCENE is { url, caption, waitFor?, dwellMs?, act? }. A fixed caption bar+// is injected into every page so the recording narrates itself. WebGL/3D pages+// render via swiftshader (same flags the repo's other browser scripts use).+//+// node scripts/reel.js # film the default fleet story vs production+// BASE=http://localhost:3000 node scripts/reel.js+// OUT=/path node scripts/reel.js # video + shots dir+// SCENES=theater,arena,trades node scripts/reel.js # subset by key+//+// It films whatever the pages show; to film THIS fleet's trades by name you must+// either run the standalone console (packages/agent-sniper/web/console.html) or+// provision the 33 as platform agents. See fleet.js and the README.++import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import process from 'node:process';+import { chromium } from 'playwright';++const BASE = (process.env.BASE || 'https://three.ws').replace(/\/$/, '');+const OUT = process.env.OUT || path.join(os.tmpdir(), 'three-reel', String(Date.now?.() ?? 'run'));+const VIEWPORT = { width: 1280, height: 720 };++// ── the story ─────────────────────────────────────────────────────────────────+// Ordered beats over real, live three.ws surfaces. `waitFor` is a selector that+// proves real data rendered before we start the dwell; `dwellMs` is on-camera+// hold time; `act` is an optional async (page) => {} for interaction.+const STORY = [+ { key: 'theater', url: '/theater', caption: '33 autonomous agents. 3 SOL. One live sniper fleet.',+ waitFor: 'canvas, .theater-stage, main', dwellMs: 6000 },+ { key: 'arena', url: '/play/arena', caption: 'The Sniper Arena — agents trade pump.fun in real time.',+ waitFor: 'canvas, main', dwellMs: 7000 },+ { key: 'terminal', url: '/terminal', caption: 'Mission Control — live launches, intel scores, streaming PnL.',+ waitFor: 'main, .terminal, body', dwellMs: 6000 },+ { key: 'trades', url: '/trades', caption: 'Live Trade Feed — every fill is a real on-chain buy.',+ waitFor: 'main, body', dwellMs: 6000 },+ { key: 'pulse', url: '/pulse', caption: 'Money Pulse — the fleet’s heartbeat, on-chain.',+ waitFor: 'canvas, main', dwellMs: 6000 },+];++// A scene's `url` may be an absolute URL (filmed as-is, e.g. a localhost console+// or Solscan) or a path (joined to BASE). SCENE_FILE=<path.json> replaces STORY+// entirely with a custom array so each recording cut ships its own story.+function resolveUrl(u) { return /^https?:\/\//i.test(u) ? u : BASE + u; }+function loadStory() {+ const f = process.env.SCENE_FILE;+ if (!f) return STORY;+ const arr = JSON.parse(fs.readFileSync(f, 'utf8'));+ if (!Array.isArray(arr) || !arr.length) throw new Error(`SCENE_FILE ${f} must be a non-empty JSON array`);+ return arr;+}++const CAPTION_CSS = `+#__reel_bar{position:fixed;left:0;right:0;bottom:0;z-index:2147483647;+ font:600 22px/1.35 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;+ color:#fff;background:linear-gradient(0deg,rgba(6,8,15,.92),rgba(6,8,15,0));+ padding:44px 40px 24px;letter-spacing:.2px;text-shadow:0 2px 12px rgba(0,0,0,.6);+ opacity:0;transition:opacity .5s ease}+#__reel_bar.on{opacity:1}+#__reel_bar b{color:#7cf6c8}+#__reel_dot{display:inline-block;width:10px;height:10px;border-radius:50%;+ background:#ff4d5e;margin-right:12px;box-shadow:0 0 12px #ff4d5e;+ animation:__reel_pulse 1.4s ease-in-out infinite;vertical-align:middle}+@keyframes __reel_pulse{0%,100%{opacity:1}50%{opacity:.35}}`;++async function caption(page, text) {+ await page.evaluate(({ text, css }) => {+ let bar = document.getElementById('__reel_bar');+ if (!bar) {+ const style = document.createElement('style'); style.textContent = css; document.head.appendChild(style);+ bar = document.createElement('div'); bar.id = '__reel_bar'; document.body.appendChild(bar);+ }+ bar.innerHTML = `<span id="__reel_dot"></span>${text}`;+ requestAnimationFrame(() => bar.classList.add('on'));+ }, { text, css: CAPTION_CSS }).catch(() => {});+}++// ── optional live cast: screenshot this browser → three.ws agent-screen ─────────+// When CAST=1 (with AGENT_JWT + AGENT_ID), every ~5s we POST a base64 PNG of the+// current page to /api/agent-screen-push, so the exact browser being filmed also+// streams live at /agent-screen?agentId=<AGENT_ID>. Contract: JSON body+// { agentId, frame:{ data, activity, type } }, Bearer auth, <=6fps, 90s frame TTL.+function startCaster(page, getCaption) {+ const agentId = process.env.AGENT_ID;+ const jwt = process.env.AGENT_JWT;+ const pushUrl = process.env.PUSH_URL || 'https://three.ws/api/agent-screen-push';+ if (!process.env.CAST || !agentId || !jwt) return () => {};+ const everyMs = Math.max(5000, Number(process.env.CAST_INTERVAL_MS) || 6000);+ let stopped = false;+ console.log(` ⇉ casting live to /agent-screen?agentId=${agentId} every ${everyMs}ms`);+ const tick = async () => {+ if (stopped) return;+ try {+ const buf = await page.screenshot({ type: 'png', fullPage: false });+ const body = JSON.stringify({+ agentId,+ frame: { data: 'data:image/png;base64,' + buf.toString('base64'),+ activity: (getCaption() || 'Working').slice(0, 320), type: 'screenshot' },+ });+ const res = await fetch(pushUrl, { method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${jwt}` }, body });+ if (!res.ok) console.log(` [cast] push ${res.status}`);+ } catch (e) { console.log(' [cast]', e.message.slice(0, 80)); }+ };+ const id = setInterval(tick, everyMs);+ tick();+ return () => { stopped = true; clearInterval(id); };+}++async function main() {+ fs.mkdirSync(OUT, { recursive: true });+ const story = loadStory();+ const only = (process.env.SCENES || '').split(',').map((s) => s.trim()).filter(Boolean);+ const scenes = only.length ? story.filter((s) => only.includes(s.key)) : story;++ const browser = await chromium.launch({+ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-webgl',+ '--ignore-gpu-blocklist', '--no-sandbox', '--disable-dev-shm-usage'],+ });+ const context = await browser.newContext({+ viewport: VIEWPORT,+ recordVideo: { dir: OUT, size: VIEWPORT },+ deviceScaleFactor: 1,+ });+ const page = await context.newPage();+ page.on('pageerror', (e) => console.log(' [pageerror]', e.message.slice(0, 120)));++ let currentCaption = 'Starting the fleet';+ const stopCaster = startCaster(page, () => currentCaption);++ const log = [];+ for (const scene of scenes) {+ currentCaption = scene.caption;+ const url = resolveUrl(scene.url);+ process.stdout.write(` ▸ ${scene.key.padEnd(9)} ${url} … `);+ const t0 = Date.now?.() ?? 0;+ try {+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45_000 });+ if (scene.waitFor) await page.waitForSelector(scene.waitFor, { timeout: 20_000 }).catch(() => {});+ // let live feeds / 3D settle a beat before the caption+ await page.waitForTimeout(2500);+ await caption(page, scene.caption);+ if (scene.act) await scene.act(page).catch((e) => console.log('act:', e.message));+ await page.waitForTimeout(scene.dwellMs ?? 5000);+ const shot = path.join(OUT, `${scene.key}.png`);+ await page.screenshot({ path: shot });+ console.log(`ok (${((Date.now?.() ?? 0) - t0) / 1000 | 0}s)`);+ log.push({ key: scene.key, url, ok: true, shot });+ } catch (e) {+ console.log(`FAIL ${e.message.slice(0, 80)}`);+ log.push({ key: scene.key, url, ok: false, error: e.message });+ }+ }++ stopCaster();+ await page.waitForTimeout(500);+ await context.close(); // flushes the video file+ const video = fs.readdirSync(OUT).find((f) => f.endsWith('.webm'));+ await browser.close();++ fs.writeFileSync(path.join(OUT, 'manifest.json'), JSON.stringify({ base: BASE, video, scenes: log }, null, 2));+ console.log(`\n Reel → ${OUT}`);+ if (video) console.log(` Video: ${path.join(OUT, video)}`);+ console.log(` Scenes ok: ${log.filter((s) => s.ok).length}/${log.length}`);+}++main().catch((e) => { console.error(e); process.exit(1); });diff --git a/tasks/x402-ring/01-audit-live-state.md b/tasks/x402-ring/01-audit-live-state.mdnew file mode 100644index 000000000..74c2fdcbf--- /dev/null+++ b/tasks/x402-ring/01-audit-live-state.md@@ -0,0 +1,89 @@+# Task 01 — Live-State Audit of the x402 Ring (READ-ONLY)++## Mission++Produce a definitive, evidence-backed snapshot of why the closed-loop x402 ring+economy is producing zero volume **in the deployed environment right now**, and+write it to `tasks/x402-ring/STATUS.md`. You change nothing: no code edits, no+env writes, no funds moved. Every claim in your report must carry the command+you ran and its real output.++## Context you must know++- Design doc: `docs/x402-ring-economy.md`. The loop: payer wallet pays+ `/api/x402/ring-settle` (and the wider paid catalog) in USDC → self-hosted+ facilitator `/api/x402-facilitator` verifies + settles → treasury receives →+ `ring-rebalance` sweeps treasury→payer so the float recirculates. Sponsor (or+ self-pay) covers SOL fees.+- Static root-cause hypotheses already found by code reading (verify each against+ the LIVE deployment — env, chain, DB):+ 1. `X402_FACILITATOR_URL_SOLANA` defaults to `https://facilitator.payai.network`+ (`api/_lib/env.js:742-748`); `facilitatorFor()` (`api/_lib/x402-spec.js:242-248`)+ routes purely off it.+ 2. `X402_SELF_FACILITATOR_ENABLED` defaults false → facilitator 503+ (`api/_lib/x402/self-facilitator.js:62-63`, `api/x402-facilitator/[action].js:89-96`).+ 3. `ring-settle` default price 1_000_000 atomic ($1.00, `api/x402/ring-settle.js:36`)+ vs `VOLUME_PER_RUN_CAP_ATOMIC` default 50_000 ($0.05,+ `volume-bootstrap-loop.js:59-62`) → `cap_would_exceed` skip (`pay.js:182-184`).+ 4. `ring-rebalance` no-ops without `X402_TREASURY_SECRET_BASE58`+ (`ring-rebalance.js:71-72`).+ 5. Solana accept dropped when `X402_FEE_PAYER_SOLANA` unset+ (`api/_lib/x402-paid-endpoint.js:175-179`).+ 6. Only driver is `/api/cron/x402-autonomous-loop` @ `*/5 * * * *`+ (`vercel.json:4872-4875`); `X402_AUTONOMOUS_ENABLED='false'` would kill it+ (`x402-autonomous-loop.js:226`).++## Tasks++1. **Env truth table.** `vercel env ls` (production). For every var below record+ SET / NOT SET (never print secret values — names and presence only):+ `X402_SELF_FACILITATOR_ENABLED`, `X402_FACILITATOR_URL_SOLANA`,+ `X402_PAY_TO_SOLANA`, `X402_TREASURY_SECRET_BASE58`, `X402_FEE_PAYER_SOLANA`,+ `X402_FEE_PAYER_SECRET_BASE58`, `X402_SEED_SOLANA_SECRET_BASE58`,+ `X402_AGENT_SOLANA_SECRET_BASE58`, `X402_RING_SELF_PAY`,+ `X402_PRICE_RING_SETTLE`, `X402_VOLUME_PER_RUN_CAP_ATOMIC`,+ `X402_AUTONOMOUS_DAILY_CAP_ATOMIC`, `X402_AUTONOMOUS_ENABLED`,+ `X402_EXTERNAL_ENABLED`, `X402_CHARITY_AUDIT_BPS`,+ `X402_SPONSOR_SOL_FLOOR_LAMPORTS`, `X402_SELF_FACILITATOR_PAYTO_ALLOWLIST`,+ `SOLANA_RPC_URL` / `HELIUS_API_KEY`, `DATABASE_URL`.+2. **Live probes** (production, with `curl -sS`, record status + body):+ - `GET https://three.ws/api/x402-facilitator/supported` — 503 = facilitator off.+ - `GET https://three.ws/api/x402-ring?period=7d` — volume, tx count, balances.+ - `GET https://three.ws/api/x402/ring-settle` unauthenticated — inspect the 402+ challenge: does an `exact/solana` accept exist? What `payTo`, what facilitator?+ - `GET https://three.ws/api/x402-status` — which facilitators probe healthy.+ - One cheap catalog endpoint (e.g. `GET https://three.ws/api/x402/dance-tip`)+ — same 402-challenge inspection.+3. **Database evidence.** Against production `DATABASE_URL` (read-only queries):+ - Do tables `x402_self_facilitator_log`, `x402_ring_ledger`, `x402_ring_wallets`+ exist (was the migration `api/_lib/migrations/2026-07-01-x402-ring-economy.sql`+ ever applied)? Row counts + most recent `created_at` of each.+ - `x402_autonomous_log`: last 50 rows — when did outbound paid calls last+ succeed? Group by `status`/`detail` to surface `cap_would_exceed`,+ `no_payable_accept`, facilitator errors. **This tells us when and how "it was+ working" stopped.**+ - `x402_volume_metrics`: per-endpoint last-paid timestamps.+4. **Wallet state on chain.** From env pubkeys (and `x402_ring_wallets` if+ populated): SOL balance, USDC ATA + balance, and the last 20 signatures for+ payer, treasury, sponsor. Note the last real settlement signature and date.+5. **Chronology.** Correlate 3+4: identify the exact date/mechanism the loop+ stopped (cap exceeded? float drained? env removed? facilitator flipped 503?).+6. **Write `tasks/x402-ring/STATUS.md`:** env truth table, probe outputs, DB+ evidence, chain evidence, the confirmed failure chain in one paragraph, and a+ checklist of which of tasks 02–11 each finding maps to. Mark each static+ hypothesis CONFIRMED / REFUTED / PARTIAL with evidence.++## Constraints++- READ-ONLY: no env writes, no code changes, no funds moved, no DB writes.+- Never print secret values, only presence. Redact any base58 secret that leaks+ into command output.++## Acceptance criteria++- [ ] `STATUS.md` exists with all six sections and real command output.+- [ ] Every hypothesis marked CONFIRMED/REFUTED/PARTIAL with evidence.+- [ ] The stop-date and stop-mechanism of the previously-working loop identified+ (or explicitly proven undeterminable, with what evidence is missing).+- [ ] Zero mutations performed (state this and show `git status` is clean apart+ from STATUS.md).diff --git a/tasks/x402-ring/02-facilitator-routing.md b/tasks/x402-ring/02-facilitator-routing.mdnew file mode 100644index 000000000..9704f7634--- /dev/null+++ b/tasks/x402-ring/02-facilitator-routing.md@@ -0,0 +1,91 @@+# Task 02 — Self-Hosted Facilitator: Routing, Defaults, and Truthful Docs++## Mission++Make the self-hosted facilitator the settlement path for the ring so that **no+third party ever touches a ring settlement**, and make the configuration+truthful: today `.env.example` claims the self-hosted facilitator is+"always-on" while the code defaults Solana settlement to PayAI and the+facilitator itself to disabled. After this task, a correctly-enveloped deploy+settles ring payments through `/api/x402-facilitator`, and a mis-enveloped one+says so loudly instead of silently routing volume elsewhere.++## Context you must know++- `api/_lib/env.js:742-748` — `X402_FACILITATOR_URL_SOLANA` defaults to+ `https://facilitator.payai.network`.+- `api/_lib/x402-spec.js:242-248` — `facilitatorFor()` is a pure env lookup; no+ awareness of the self-hosted facilitator.+- `api/_lib/x402/self-facilitator.js:62-63` — `SELF_FACILITATOR_ENABLED` is+ `X402_SELF_FACILITATOR_ENABLED === 'true'`, default false.+- `api/x402-facilitator/[action].js:89-96` — 503 `self_facilitator_disabled`+ when off; `/supported` (78-85) is the public probe; every op logged to+ `x402_self_facilitator_log` (44-55).+- `.env.example:357` documents the PayAI default; `.env.example:365` **falsely**+ says the Solana self-hosted facilitator is "always-on".+- `api/x402-status.js` — `probeFacilitators()` checks configured facilitators'+ `/supported`.+- Buyer-side settlement call sites route through `facilitatorFor()` — trace all+ of them (`api/_lib/x402/pay.js`, `api/_lib/x402-buyer-fetch.js`,+ `api/_lib/x402-buyer-axios.js`, `packages/x402-mcp/src/lib/x402-buyer.js`)+ before changing behavior.++## Tasks++1. **Route to self when enabled.** In `facilitatorFor()` (or a thin wrapper it+ calls — pick the seam that covers ALL call sites), when+ `SELF_FACILITATOR_ENABLED` is true and the network is Solana, resolve to our+ own facilitator URL (`https://three.ws/api/x402-facilitator`, overridable via+ `X402_FACILITATOR_URL_SOLANA` still winning if explicitly set to a different+ self URL — an explicit env always wins; the *default* is what changes when+ the flag is on). External facilitators remain the default only when the+ self-facilitator is off.+2. **Fail loud, not silent.** When `X402_RING_SELF_PAY=true` or a ring pipeline+ is invoked while settlement would route to an external facilitator, log one+ structured warning per boot (not per call) naming the misconfiguration, and+ surface it in `/api/x402-ring` output as `config_warnings: [...]`.+3. **Boot-time config validation.** Add a `validateRingConfig()` export (new,+ in `api/_lib/x402/self-facilitator.js` or a sibling `ring-config.js`) that+ returns a list of structured findings: facilitator off, URL pointing+ external, missing treasury secret, missing fee-payer pubkey, price>cap+ contradiction (`priceFor('ring-settle')` vs `VOLUME_PER_RUN_CAP_ATOMIC`),+ self-pay off. Wire it into `/api/x402-ring` and `/api/x402-status`.+4. **Truthful `.env.example`.** Fix line ~365 and the surrounding x402 block:+ document the real defaults, the exact env set required for the ring+ (mirror `scripts/x402-ring-setup.mjs:79-92`), and that+ `X402_SELF_FACILITATOR_ENABLED=true` + self URL are BOTH required.+5. **Probe coverage.** Ensure `api/x402-status.js` always probes the self-hosted+ facilitator's `/supported` when the flag is on (even if an external URL is+ also configured) and reports it as a distinct entry.+6. **Tests.** Extend the existing x402 test files (find them with+ `ls tests/ | grep -i x402` and match their style): `facilitatorFor()`+ resolution matrix (flag on/off × env set/unset), `validateRingConfig()`+ finding matrix. Pure logic — no network.+7. **Docs.** Update `docs/x402-ring-economy.md` "Turning it on" to match the new+ resolution behavior. Add a `data/changelog.json` entry (tags: `fix`,+ `infra`) in holder-readable language.++## Files you own++`api/_lib/x402-spec.js`, `api/_lib/x402/self-facilitator.js` (additive only),+`api/x402-status.js`, `api/x402-ring.js` (config_warnings only),+`.env.example`, `docs/x402-ring-economy.md`, tests, `data/changelog.json`.+Do NOT touch the pipelines (`volume-bootstrap-loop.js`, `ring-rebalance.js`) —+task 04 owns them.++## Constraints++- Never weaken `validateRingTransaction` or the anti-drain gate.+- Explicit env vars always beat computed defaults — no surprise re-routing for+ existing non-ring x402 users (Base lane untouched).+- No new dependency.++## Acceptance criteria++- [ ] With `X402_SELF_FACILITATOR_ENABLED=true` and no facilitator URL set, a+ Solana settlement resolves to `/api/x402-facilitator` (test proves it).+- [ ] With the flag off, behavior is byte-identical to today (test proves it).+- [ ] `validateRingConfig()` catches all six misconfigurations (tests).+- [ ] `/api/x402-ring` and `/api/x402-status` expose the warnings.+- [ ] `.env.example` no longer contradicts the code.+- [ ] `npm test` green. Changelog entry added.diff --git a/tasks/x402-ring/03-wallets-provisioning.md b/tasks/x402-ring/03-wallets-provisioning.mdnew file mode 100644index 000000000..a26afe8fc--- /dev/null+++ b/tasks/x402-ring/03-wallets-provisioning.md@@ -0,0 +1,99 @@+# Task 03 — Ring Wallets: Provision, Register, Monitor, Floor-Guard++## Mission++Get the three ring wallets (payer, treasury, sponsor) into a verified,+registered, monitored state so the loop can run unattended without draining or+stalling. After this task every ring wallet is: resolvable from env, registered+in `x402_ring_wallets`, watched by the balance monitor with alert floors, and+covered by the platform's signer conventions — and no wallet outside this set+can ever be a settlement recipient.++## Context you must know++- Roles + env (docs/x402-ring-economy.md:66-77):+ payer = `X402_SEED_SOLANA_SECRET_BASE58` (fallback+ `X402_AGENT_SOLANA_SECRET_BASE58`; loader `loadSeedKeypair()`+ `api/_lib/x402/pay.js:34-49`); treasury = `X402_PAY_TO_SOLANA` ++ `X402_TREASURY_SECRET_BASE58`; sponsor = `X402_FEE_PAYER_SOLANA` ++ `X402_FEE_PAYER_SECRET_BASE58` (loader `loadFeePayerKeypair()`+ `self-facilitator.js:76-97`, asserts pubkey match).+- Setup script `scripts/x402-ring-setup.mjs` generates keys →+ `.x402-ring-secrets.json` (gitignored, chmod 600); `--register` upserts+ `x402_ring_wallets` (migration+ `api/_lib/migrations/2026-07-01-x402-ring-economy.sql`).+- Ring wallets are NOT in `api/_lib/solana-signers.js` (that registry holds+ coin-treasury, club-treasury, platform-treasury, gasless fee-payer at+ lines 77-110) and NOT watched by+ `api/_lib/x402/wallet-balance-monitor.js`.+- Allowlist: `payToAllowlist()` (`self-facilitator.js:103-112`) =+ `{X402_PAY_TO_SOLANA} ∪ X402_SELF_FACILITATOR_PAYTO_ALLOWLIST`.+- SOL floor: `SPONSOR_SOL_FLOOR_LAMPORTS` default 0.02 SOL+ (`self-facilitator.js:68-70`).+- Task 01's `tasks/x402-ring/STATUS.md` tells you which wallets already exist+ and hold funds. **Read it first. Reuse existing funded wallets — do not+ generate replacements for wallets that already hold platform money.**++## Tasks++1. **Inventory then provision.** From STATUS.md + env, determine which of the+ three roles have valid keys. For any missing role, run+ `node scripts/x402-ring-setup.mjs` (extend it with a `--roles payer,sponsor`+ flag if partial generation is needed — currently it's all-or-nothing) and+ `--register`. Never overwrite an existing role secret.+2. **Registry parity.** Ensure `x402_ring_wallets` has exactly one active row+ per role matching the env pubkeys. Add a small idempotent+ `scripts/x402-ring-verify.mjs` that: resolves each role from env, compares+ against `x402_ring_wallets`, checks the treasury pubkey equals+ `X402_PAY_TO_SOLANA`, checks the payer/sponsor secrets decode to their+ declared pubkeys, prints a table, exits non-zero on any mismatch. (Presence+ checks only — never print secrets.)+3. **Balance monitoring.** Wire all three wallets into+ `api/_lib/x402/wallet-balance-monitor.js` with role-appropriate floors:+ sponsor/payer SOL floor ≥ `X402_SPONSOR_SOL_FLOOR_LAMPORTS`, payer USDC+ floor (new env `X402_RING_PAYER_USDC_FLOOR_ATOMIC`, default $5), treasury+ unbounded (it fills and gets swept). Breach → existing `sendOpsAlert` path.+4. **Signer-registry decision.** Add the ring sponsor (and payer if self-pay)+ to `api/_lib/solana-signers.js` with a `minSol` so the economy master's+ `treasury-topup` cron (`api/cron/treasury-topup.js`) can auto-top-up their+ fee SOL — this closes the "sponsor runs dry and the ring silently halts"+ failure. Follow the existing entry shape exactly (lines 77-110). The+ treasury does NOT go in (it must never be topped up; it only receives and+ gets swept).+5. **Funding runbook (no funds moved by you).** Write+ `tasks/x402-ring/FUNDING.md`: exact amounts (payer: USDC float sized to+ `X402_AUTONOMOUS_DAILY_CAP_ATOMIC`, e.g. $50; payer or sponsor: 0.1 SOL ≈+ ~20k self-pay settlements), which wallet address to send to (read from env+ at runtime, printed by the verify script), and the check commands to confirm+ arrival. Funding itself is task 11's activation step, executed by the owner.+6. **Docs + changelog.** Update `docs/x402-ring-economy.md` wallet section with+ the monitor + auto-topup behavior; changelog entry (tags: `infra`,+ `security`).++## Files you own++`scripts/x402-ring-setup.mjs`, `scripts/x402-ring-verify.mjs` (new),+`api/_lib/x402/wallet-balance-monitor.js`, `api/_lib/solana-signers.js`+(additive entries only), `tasks/x402-ring/FUNDING.md`,+`docs/x402-ring-economy.md`, `data/changelog.json`.++## Constraints++- NEVER move funds. NEVER print or commit a secret. `.x402-ring-secrets.json`+ stays gitignored — verify with `git check-ignore`.+- Never regenerate a key for a role whose wallet holds a balance.+- Adding signers to `solana-signers.js` must not change any existing entry.+- The economy master (`WwwuGbq…T3WwW`) tops up ring wallets **only via the+ existing guarded `treasury-topup` path** — no new transfer code.++## Acceptance criteria++- [ ] `node scripts/x402-ring-verify.mjs` exits 0 and prints a 3-row table with+ role, pubkey, registry-match ✓, secret-decodes ✓, balances.+- [ ] All three wallets appear in the balance monitor with correct floors+ (show the config/output).+- [ ] Sponsor (and payer if applicable) present in `SOLANA_SIGNERS` with+ `minSol`; `treasury-topup` plan includes them when below floor (show a+ dry-run plan).+- [ ] `FUNDING.md` written with exact amounts and verification commands.+- [ ] No secrets in `git diff`; `npm test` green; changelog entry added.diff --git a/tasks/x402-ring/04-per-minute-cadence.md b/tasks/x402-ring/04-per-minute-cadence.mdnew file mode 100644index 000000000..081a04ef8--- /dev/null+++ b/tasks/x402-ring/04-per-minute-cadence.md@@ -0,0 +1,114 @@+# Task 04 — Per-Minute Ring Tick: Many Paid Hits Every Minute, Cap-Coherent++## Mission++The owner's requirement is explicit: **x402 endpoints being hit every minute,+many times** — tips, payments, services bought and sold, continuously. Today the+only driver is `/api/cron/x402-autonomous-loop` at `*/5 * * * *` with 300s+pipeline cooldowns, and the flagship `ring-settle` call is skipped every cycle+because its price ($1.00) exceeds the volume loop's per-run cap ($0.05). Build a+dedicated per-minute ring tick that produces steady, capped, fee-minimal paid+traffic across the catalog, and make the cap system coherent so nothing is ever+silently skipped.++## Context you must know++- Vercel per-minute crons are already in use: `/api/cron/x402-seed-cron` @+ `* * * * *` (`vercel.json:4869`). Crons array starts `vercel.json:4623`.+- Payment primitive: `payX402` (`api/_lib/x402/pay.js:141-`) — builds the USDC+ `TransferChecked` (`buildPaymentTx` :71-116), self-pay flag at :150, cap skip+ `cap_would_exceed` at :182-184. Logs to `x402_autonomous_log`.+- Volume loop: `api/_lib/x402/pipelines/volume-bootstrap-loop.js` —+ `VOLUME_ENDPOINTS` (:70-88, 12 entries), `VOLUME_BATCH_PER_RUN` (:52, default+ 4), `VOLUME_PER_RUN_CAP_ATOMIC` (:59-62, default $0.05), metrics upsert+ `x402_volume_metrics` (:119-140).+- Autonomous loop: `api/cron/x402-autonomous-loop.js` — `wrapCron`, registry+ selection, `DAILY_CAP_ATOMIC` default $15+ (`api/_lib/x402/autonomous-registry.js:3778`), `MAX_PER_TICK` 12 (:3771),+ kill switch `X402_AUTONOMOUS_ENABLED==='false'` (:226). Registry entries+ `volume-bootstrap-loop` (:2647-2659) and `ring-rebalance` (:2670-2681), both+ cooldown 300.+- Rebalancer: `api/_lib/x402/pipelines/ring-rebalance.js` — treasury→payer+ sweep, `MIN_SWEEP_ATOMIC` $0.10 (:49), no-op without treasury secret+ (:71-72), cap-neutral (`amountAtomic:0`).+- Facilitator SOL floor pauses settlement below 0.02 SOL+ (`self-facilitator.js:383-389`) — your tick must treat that as back-pressure,+ not an error storm.+- Task 02 landed `validateRingConfig()` — call it, don't re-implement.++## Tasks++1. **New cron endpoint `api/cron/x402-ring-tick.js`** (follow `wrapCron` ++ `CRON_SECRET` auth conventions of `x402-autonomous-loop.js`):+ - Every minute, pay `X402_RING_TICK_CALLS` endpoints (default 3) drawn from+ the catalog: weighted rotation so cheap tips/services ($0.001–$0.01)+ dominate the count while one `ring-settle` at+ `X402_PRICE_RING_SETTLE` lands every `X402_RING_SETTLE_EVERY_N_TICKS`+ ticks (default 5) to carry volume cheaply (fewer/larger — docs cost model+ lines 19-48).+ - Reuse `payX402` and the volume loop's metrics/log recording; do not fork a+ second payment path. Extract shared helpers from+ `volume-bootstrap-loop.js` rather than duplicating.+ - Per-tick spend cap `X402_RING_TICK_CAP_ATOMIC` (default $0.25) and its own+ daily cap `X402_RING_DAILY_CAP_ATOMIC` (default $50), enforced from+ `x402_autonomous_log` sums — **the ring tick budget is separate from, and+ must not consume,** the autonomous loop's `DAILY_CAP_ATOMIC`.+ - Kill switches honored: global `X402_AUTONOMOUS_ENABLED=false` AND its own+ `X402_RING_TICK_ENABLED` (default **true** once envs are valid — gate on+ `validateRingConfig()` returning clean; if findings exist, log them and+ no-op).+ - Back-pressure: on `sponsor_sol_floor`, insufficient payer USDC, or RPC+ failure — skip the tick with a structured log row, alert (throttled, max+ 1/hour) via `sendOpsAlert`, never retry-storm.+2. **Register the cron** in `vercel.json`: `* * * * *`, `maxDuration` ≤ 60.+3. **Fix the cap contradiction at the source.** In `payX402`/volume loop:+ when an endpoint's price exceeds the applicable per-run cap, the skip must+ be loud — one throttled warning naming endpoint, price, cap, and the env to+ change — and `validateRingConfig()` (task 02) must flag it. Additionally+ raise the documented defaults so stock config is coherent:+ `VOLUME_PER_RUN_CAP_ATOMIC` must accommodate the ring-settle price it+ rotates (document the pair in `.env.example`).+4. **Rebalance cadence.** The payer float now cycles faster; ensure+ `ring-rebalance` keeps up: lower its registry cooldown to 120s and make+ `MIN_SWEEP_ATOMIC` env-tunable (`X402_RING_MIN_SWEEP_ATOMIC`). Sweep stays+ treasury→payer only.+5. **Tests.** Pure-logic tests: rotation weighting (per-minute counts,+ ring-settle every Nth), cap enforcement (tick + daily), back-pressure no-op+ on floor breach, budget separation from the autonomous loop. Match existing+ x402 test style; no network.+6. **Docs + changelog.** New "Cadence" section in `docs/x402-ring-economy.md`+ with the throughput/fee math at defaults (3 calls/min ≈ 4,320 tx/day ≈+ ~0.0216 SOL/day at the 1-sig floor — show the real numbers for your final+ defaults). Changelog entry (tags: `feature`, `infra`).++## Files you own++`api/cron/x402-ring-tick.js` (new), `vercel.json` (crons array — add one entry+only), `api/_lib/x402/pipelines/volume-bootstrap-loop.js`,+`api/_lib/x402/pipelines/ring-rebalance.js`,+`api/_lib/x402/autonomous-registry.js` (cooldown only), `api/_lib/x402/pay.js`+(loud-skip only), `.env.example`, tests, `docs/x402-ring-economy.md`,+`data/changelog.json`.++## Constraints++- Only OUR endpoints get paid: the tick's catalog is hardcoded to internal+ paths; `X402_EXTERNAL_ENABLED` has no effect on it and it must never read+ external endpoint lists.+- Fees: self-pay 1-sig assumed (task 05 enforces); priority fee stays at the+ existing ~5 µlamport formula; do not add per-call ATA creates (ATAs exist+ after the first settlement).+- Never weaken existing caps or guards; you are adding a *separately budgeted*+ driver, not raising the autonomous loop's spend.+- Every skipped/failed tick leaves a structured, queryable log row.++## Acceptance criteria++- [ ] Local simulated run (env-complete, RPC live, funded wallets or devnet):+ 10 consecutive ticks produce ≥ 3 paid calls each, with ring-settle landing+ on the configured cadence — show the `x402_autonomous_log` rows.+- [ ] Tick + daily caps enforced (test-proven); autonomous-loop budget untouched.+- [ ] Price-vs-cap contradiction impossible to hit silently (test + warning).+- [ ] Back-pressure path proven: below-floor → clean no-op + single alert.+- [ ] `vercel.json` cron entry present and valid JSON.+- [ ] `npm test` green; docs + changelog landed.diff --git a/tasks/x402-ring/05-fee-minimization.md b/tasks/x402-ring/05-fee-minimization.mdnew file mode 100644index 000000000..2e55a35a0--- /dev/null+++ b/tasks/x402-ring/05-fee-minimization.md@@ -0,0 +1,91 @@+# Task 05 — Lowest Fees Always: Self-Pay Everywhere, Fee Audit, Rent Reclaim++## Mission++The owner's rule is "the lowest fees ALWAYS". Enforce the fee floor across the+entire ring: 1-signature self-pay settlement as the operative mode, priority+fees pinned at the floor, ATA rent reclaimed, and a continuous fee audit that+measures the real SOL burned per dollar of volume and alarms when it drifts+above budget.++## Context you must know++- Two fee levers (docs/x402-ring-economy.md:19-48): fewer/larger payments+ (`X402_PRICE_RING_SETTLE`), and self-pay 1-sig = 5,000 lamports vs sponsor+ 2-sig = 10,000 (`X402_RING_SELF_PAY`, default **false** — `pay.js:150`;+ `buildPaymentTx` picks feePayer at :78).+- Priority fee already ~floor: `ComputeUnitPrice = 5 + (nonce%997)` µlamports,+ `ComputeUnitLimit 60_000` (`pay.js:94-96`; rebalance `ring-rebalance.js:134-135`).+- Facilitator guards cap CU price/limit and priority lamports+ (`self-facilitator.js:51-60`): `MAX_CU_LIMIT` 300k, `MAX_CU_PRICE` 100k+ µlamports, `MAX_PRIORITY_LAMPORTS` 20k.+- ATA rent = 2,039,280 lamports per new ATA, one-time, **reclaimable by closing+ the ATA** (`self-facilitator.js:59-60,288,448`; `pay.js:98-102`;+ `ring-rebalance.js:137-141`).+- Real fee is read back from chain: `getParsedTransaction().meta.fee`+ (`self-facilitator.js:441-450`) → logged in `x402_self_facilitator_log`.+- `/api/x402-ring` (`api/x402-ring.js`) already reports SOL burned per period.+- In self-pay the facilitator broadcasts without co-signing; the SOL floor+ guard then watches the **payer** (docs:37-43).++## Tasks++1. **Self-pay as the operative default for the ring.** Flip the effective+ default of `X402_RING_SELF_PAY` to true for ring-internal payments (explicit+ `false` still honored). Verify the whole path works with zero sponsor+ involvement: `buildPaymentTx` 1-sig, facilitator validation of a+ self-paid tx (`validateRingTransaction` self-pay branch :270-275),+ broadcast, fee logging. The payer's SOL balance becomes the watched floor —+ confirm task 03's monitor covers it.+2. **Fee-floor regression guard.** Add a pure function+ `expectedFeeLamports({selfPay, priorityMicrolamports, cuLimit})` and assert+ in tests that the ring's builders never produce a tx whose worst-case fee+ exceeds `X402_RING_MAX_FEE_PER_TX_LAMPORTS` (default 10_000). Wire the same+ ceiling as a runtime check in `payX402` — refuse to send a ring payment+ whose priority config would exceed it (structured skip, not throw).+3. **Fee audit rollup.** Nightly pipeline (register in the autonomous registry+ following the existing entry shape, cooldown 86400): sum real fees from+ `x402_self_facilitator_log` + `x402_autonomous_log` for the day, compute+ lamports-per-settlement and SOL-per-$100-volume, upsert into+ `x402_volume_metrics` (or a small `x402_fee_audit` table if metrics doesn't+ fit — reuse the migration pattern in `api/_lib/migrations/`), and+ `sendOpsAlert` if lamports-per-settlement > 1.5× the 1-sig floor or daily+ burn > `X402_RING_DAILY_FEE_BUDGET_LAMPORTS` (default 0.05 SOL).+4. **ATA rent reclaim.** Extend the fee audit pipeline: enumerate token+ accounts owned by ring wallets; any USDC ATA with zero balance that is not+ one of the three active role ATAs → close it (owner-signed+ `closeAccount`, rent returns to the owner wallet). Idempotent, logged,+ capped at 5 closes/run. NEVER close an active role ATA or any account with+ a balance.+5. **Expose the number.** Add `fees.lamports_per_settlement` and+ `fees.sol_per_100_usd` to `/api/x402-ring` so the dashboard (task 10) and+ the acceptance run (task 11) can read the real efficiency.+6. **Docs + changelog.** Update the cost-model section of+ `docs/x402-ring-economy.md` with measured (not theoretical) numbers from+ your verification run; changelog entry (tags: `improvement`, `infra`).++## Files you own++`api/_lib/x402/pay.js` (fee ceiling + self-pay default), fee-audit pipeline+(new file under `api/_lib/x402/pipelines/`), `api/_lib/x402/autonomous-registry.js`+(one new entry), `api/x402-ring.js` (fees block), migration if needed, tests,+`docs/x402-ring-economy.md`, `data/changelog.json`.++## Constraints++- Never raise a facilitator guard ceiling (`MAX_CU_*`, `MAX_PRIORITY_LAMPORTS`).+- Rent reclaim must be provably safe: test the "never closes active/funded+ ATA" invariant with unit tests before any live run.+- No new dependency; use existing `@solana/spl-token` helpers already in the tree.+- Sponsor mode must keep working (it's the fallback for gasless buyers) — you+ are changing the ring's default, not deleting the mode.++## Acceptance criteria++- [ ] A live (or devnet) self-paid settlement lands with `meta.fee` ≤ 5,100+ lamports — paste the signature and logged fee.+- [ ] Fee ceiling enforced in code + tests; audit pipeline registered and runs+ (show one real run's output row).+- [ ] Rent-reclaim closes only zero-balance non-role ATAs (tests + dry-run log).+- [ ] `/api/x402-ring` exposes the two fee-efficiency metrics.+- [ ] `npm test` green; docs show measured numbers; changelog added.diff --git a/tasks/x402-ring/06-leak-proofing.md b/tasks/x402-ring/06-leak-proofing.mdnew file mode 100644index 000000000..25859ddd4--- /dev/null+++ b/tasks/x402-ring/06-leak-proofing.md@@ -0,0 +1,102 @@+# Task 06 — Leak-Proofing: Runtime Invariants + On-Chain Leak Scanner++## Mission++The owner's invariant: **no SOL or USDC leaves the controlled-wallet set —+ever.** Not to other users, not to charities, not to external facilitators or+fees beyond the network's own. Today the guards are good but passive (env flags+that could be flipped or forgotten) and nothing watches the chain for money+actually leaving. Make the invariant active: asserted at runtime, monitored on+chain, and alarmed within minutes of any violation.++## Context you must know++- Existing guards (do not weaken, build on them):+ - `payToAllowlist()` (`api/_lib/x402/self-facilitator.js:103-112`) + enforcement+ in `validateRingTransaction` (:160-162, `pay_to_not_allowlisted`).+ - Anti-drain instruction gate (:175-254): only `{ComputeBudget, ATA-create for+ our recipient, exactly one TransferChecked to the expected receiver ATA}`;+ System instructions forbidden (:181-184); address-table lookups rejected (:144).+ - Rebalancer only moves treasury→payer, treasury pubkey must equal+ `X402_PAY_TO_SOLANA` (`ring-rebalance.js:81-87`).+ - `X402_EXTERNAL_ENABLED !== 'false'` gates external spending+ (`autonomous-registry.js:3784`); `X402_CHARITY_AUDIT_BPS=0` keeps splits at+ zero (docs/x402-ring-economy.md:128, setup script :85).+ - SOL floor hard-stop (`self-facilitator.js:383-389`).+- The controlled-wallet universe: the three ring wallets (env ++ `x402_ring_wallets`), plus platform signers in `api/_lib/solana-signers.js`,+ plus the USDC mint's ATAs thereof.+- Precedent for on-chain breach detection: `api/cron/economy-reconcile.js`+ (lines 118-234) — pulls `getSignaturesForAddress`, flags unrecorded outbound+ above a fee floor, writes `payment_reconciliation` verdicts, CRITICAL+ `sendOpsAlert`. **Mirror this pattern; do not invent a new one.**+- Task 03's `scripts/x402-ring-verify.mjs` resolves the wallet set.++## Tasks++1. **Runtime invariant assertions.** In the ring tick (task 04) and the+ autonomous loop entry point, assert before any spend:+ `X402_EXTERNAL_ENABLED === 'false'`, `X402_CHARITY_AUDIT_BPS` parses to 0,+ facilitator resolves to self (task 02's `validateRingConfig()` clean). Any+ violation → spend path no-ops + single throttled CRITICAL alert naming the+ flipped flag. The ring must fail CLOSED.+2. **Allowlist unification.** Build `ringAllowedAddresses()` in a new+ `api/_lib/x402/ring-allowlist.js`: the three role wallets + their USDC ATAs+ + `SOLANA_SIGNERS` pubkeys + explicit extras from+ `X402_SELF_FACILITATOR_PAYTO_ALLOWLIST`. Use it everywhere an allowlist is+ consulted (facilitator payTo check may keep its narrower set — receiving is+ stricter than membership; document the distinction in the module docstring).+3. **On-chain leak scanner — `api/cron/x402-ring-leak-scan.js`** (cron every 10+ min, `CRON_SECRET` auth, read-only on chain):+ - For each ring wallet: `getSignaturesForAddress` (limit 100 since last+ scan cursor, cursor persisted in DB), parse each tx, and classify every+ SOL/USDC debit: `internal` (counterparty ∈ `ringAllowedAddresses()`),+ `network_fee` (tx fee paid by our wallet), or `LEAK` (anything else —+ including token transfers of non-USDC mints, System transfers to unknown+ addresses, and approvals/delegations).+ - Any `LEAK` → CRITICAL `sendOpsAlert` with signature, counterparty,+ amount, and the recommendation to rotate the affected secret; verdict row+ in `payment_reconciliation` (source `x402_ring_onchain`), mirroring+ `economy-reconcile.js:191`'s shape.+ - Also flag `delegation` risk: any SPL `Approve` on a ring ATA is a leak+ vector even before funds move — alert on sight.+4. **Register the cron** in `vercel.json` (`*/10 * * * *`).+5. **Fee-leak line item.** The scanner sums per-day `network_fee` debits and+ cross-checks against task 05's fee audit — a >20% mismatch means something+ is paying fees outside the ring's accounting → WARN alert.+6. **Tests.** Pure-logic classification tests: internal transfer, fee-only,+ USDC to unknown address (LEAK), non-USDC token out (LEAK), SPL Approve+ (alert), cursor resumption. Fixture txs as JSON parsed-transaction shapes —+ synthetic addresses only.+7. **Docs + changelog.** New "Leak-proofing" section in+ `docs/x402-ring-economy.md`: the invariant, the assertion points, the+ scanner, and the response runbook (rotate key, drain to treasury, re-verify).+ Changelog entry (tags: `security`).++## Files you own++`api/_lib/x402/ring-allowlist.js` (new), `api/cron/x402-ring-leak-scan.js`+(new), `vercel.json` (one cron entry), invariant assertions in+`api/cron/x402-ring-tick.js` + `api/cron/x402-autonomous-loop.js` (assertion+block only), migration for the scan cursor table, tests,+`docs/x402-ring-economy.md`, `data/changelog.json`.++## Constraints++- Scanner is strictly read-only on chain; it never moves funds, never rotates+ keys itself.+- False-negative is worse than false-positive here: when classification is+ ambiguous, classify as LEAK and alert.+- Do not modify `validateRingTransaction` semantics; extend around it.+- Keep RPC usage bounded: batched `getParsedTransactions`, cursor-based, ≤ 100+ sigs per wallet per run.++## Acceptance criteria++- [ ] Flipping any guard env in a local run makes the spend path no-op with a+ single CRITICAL alert (show logs for all three flags).+- [ ] Scanner classifies the six fixture cases correctly (tests green).+- [ ] A real scan over the live ring wallets completes, writes its cursor, and+ reports zero leaks (or real findings) — paste the run output.+- [ ] `payment_reconciliation` receives verdicts with source `x402_ring_onchain`.+- [ ] `npm test` green; docs + changelog landed.diff --git a/tasks/x402-ring/07-reconciliation.md b/tasks/x402-ring/07-reconciliation.mdnew file mode 100644index 000000000..e2c8b722e--- /dev/null+++ b/tasks/x402-ring/07-reconciliation.md@@ -0,0 +1,89 @@+# Task 07 — Close the Reconciliation Blind Spot++## Mission++The financial-integrity system currently reconciles `x402_autonomous_log` and+`agent_payment_intents` against the chain — but **never reads+`x402_self_facilitator_log` or `x402_ring_ledger`**. Ring settlements that+exist only in the facilitator log are unverified, and ledger sweeps are+unchecked. Extend reconciliation so every ring row is proven on chain and every+on-chain ring movement is proven in a ledger — the same standard the economy+master already meets.++## Context you must know++- Existing reconciler: `api/_lib/x402/revenue-reconciliation.js` — `run(ctx)`,+ outbound from `x402_autonomous_log` (`loadOutboundRecords` :107-133), inbound+ from `agent_payment_intents` (`loadInboundRecords` :137-163), verdicts →+ `payment_reconciliation` (schema :76-103), ops alert on discrepancy+ (:381-393). Registered in the autonomous registry (`revenue-reconciliation`+ entry :2858-2870).+- Gold standard to mirror: `api/cron/economy-reconcile.js` — three checks+ (tamper, unrecorded outbound, ledger-vs-chain integrity) with+ `getSignatureStatuses` over a 72h window, `upsertVerdict` (:58).+- Ring tables (migration `2026-07-01-x402-ring-economy.sql`):+ `x402_self_facilitator_log` (every verify/settle op, tx signature, real fee),+ `x402_ring_ledger` (kinds `settle|sweep|fund`), `x402_ring_wallets`.+- Facilitator logs real fees from `getParsedTransaction().meta.fee`+ (`self-facilitator.js:441-450`).+- Task 06 provides `ringAllowedAddresses()` and the on-chain leak scanner —+ your job is the *ledger↔chain* direction; the scanner covers *chain→alert*.+ Don't duplicate its work; share the cursor/verdict conventions.++## Tasks++1. **Extend `revenue-reconciliation.js`** (or a sibling `ring-reconciliation.js`+ registered separately if mixing scopes would muddy the existing module —+ your call, justify it in the module docstring):+ - **Settle integrity:** every `x402_self_facilitator_log` settle row from+ the last 72h with a `tx_signature` → `getSignatureStatuses` batch check:+ missing or failed on chain → verdict (`x402_ring_settle_missing` /+ `x402_ring_settle_failed`).+ - **Amount fidelity:** for a sampled subset (≤ 50/run), parse the tx and+ verify the USDC amount and receiver match the log row → mismatch is a+ CRITICAL verdict (`x402_ring_amount_mismatch`).+ - **Sweep integrity:** every `x402_ring_ledger` `sweep` row → same+ signature + amount + direction (treasury→payer only) verification.+ - **Cross-log coherence:** ring-tick payments (task 04) land in BOTH+ `x402_autonomous_log` (buyer side) and `x402_self_facilitator_log`+ (settlement side). Join on signature over the window; orphans on either+ side → verdict (`x402_ring_log_orphan`) — a settlement with no buyer+ record is exactly the "leak through our own facilitator" case.+ - **Fee coherence:** daily sum of logged fees vs task 05's audit numbers;+ >20% divergence → WARN verdict.+2. **Verdict plumbing.** Reuse `upsertVerdict`/`payment_reconciliation` shapes;+ distinct `source` values so the ops board separates ring findings. Alerts+ via the existing `sendOpsAlert` path, CRITICAL only for+ missing/failed/mismatch — coherence WARNs are throttled daily.+3. **Zero-volume tripwire.** If the ring is enabled (`validateRingConfig()`+ clean) and `x402_self_facilitator_log` shows zero settles in a 30-minute+ window → WARN alert "ring enabled but silent". This is the alarm that was+ missing when "it was working but now it's not" happened silently.+4. **Tests.** Fixture-driven: each verdict class triggered by a crafted+ log/chain mismatch; the tripwire; batch-size bounds. No network.+5. **Docs + changelog.** Extend `docs/x402-ring-economy.md` (reconciliation+ section referencing the ops board) and `docs/financial-controls.md` if it+ indexes reconcilers. Changelog entry (tags: `security`, `infra`).++## Files you own++`api/_lib/x402/revenue-reconciliation.js` (or new sibling + registry entry),+tests, `docs/x402-ring-economy.md`, `docs/financial-controls.md`,+`data/changelog.json`.++## Constraints++- Read-only against chain; bounded RPC (batched `getSignatureStatuses`, ≤ 50+ parsed-tx fetches per run).+- Never mutate the logs being audited; verdicts are the only write.+- Keep the existing reconciler's behavior for non-ring scopes byte-identical.++## Acceptance criteria++- [ ] All five check classes implemented with fixture tests (green).+- [ ] A real run against the live DB+chain completes and reports coverage+ counts (rows checked per class) — paste the output.+- [ ] The zero-volume tripwire fires in a test where config is clean but the+ log is empty.+- [ ] Ops board (`payment_reconciliation`) shows ring sources distinctly.+- [ ] `npm test` green; docs + changelog landed.diff --git a/tasks/x402-ring/08-endpoint-coverage.md b/tasks/x402-ring/08-endpoint-coverage.mdnew file mode 100644index 000000000..207a32fac--- /dev/null+++ b/tasks/x402-ring/08-endpoint-coverage.md@@ -0,0 +1,110 @@+# Task 08 — Full Catalog Coverage: Every Tip, Payment, and Service Actually Settles++## Mission++The economy is only "working" if the whole catalog works — tips, payments,+services bought and sold — not just `ring-settle`. Today the rotation covers 12+of ~35 paid endpoints, and nobody has proven the other 23 settle correctly when+actually paid. Exercise EVERY paid endpoint end-to-end with a real settlement,+fix every one that fails, and wire the full catalog into the rotation so+coverage is continuous, not a one-time audit.++## Context you must know++- Full paid-endpoint inventory (slug → default price → file):+ ring-settle $1.00 `api/x402/ring-settle.js`; pump-launch $5.00+ `api/x402/pump-launch.js`; mint-to-mesh-batch + billboard $0.05+ (`api/x402/mint-to-mesh-batch.js`, `api/x402/billboard.js`);+ pump-agent-audit $0.02; $0.01 tier: endpoint-shopper-run,+ unstoppable-status (`api/agents/…`), three-intel, crypto_intel, token-intel,+ agent-reputation, club-cover, agent-bouncer, spend-session; $0.005 tier:+ cross_chain_bridge_status, analytics, symbol-availability-batch,+ onchain-identity-verify; $0.001 tier: dance-tip, skill-marketplace,+ symbol-availability, telegram-health, api-key-health, did_verify, notify,+ bazaar-feed, auth_health, model-validation-sweep, rate-limit-probe,+ wallet-connect-health, solana-register-health, feed-health, schema-check,+ permit2-paid-demo; plus cosmetic-purchase (own pricing module). All priced+ via `priceFor(slug, default)` (`api/_lib/x402-prices.js:25`, env override+ `X402_PRICE_<SLUG>`); all USDC (`$THREE` optional second accept via+ `X402_ACCEPT_THREE_SOLANA` — leave that flag alone).+- Current rotation: `VOLUME_ENDPOINTS` (`volume-bootstrap-loop.js:70-88`) — 12+ entries including a `fact-check` and `pay-by-name` — verify those two resolve+ to live paths; the map may be stale.+- Buyer primitive: `payX402` (`api/_lib/x402/pay.js:141-`). A2A service flows:+ `api/x402/service.js`, `api/_lib/x402/a2a-server.js` / `a2a-client.js`,+ manifest/invoke `api/agents/x402/[action].js`.+- Task 04's ring tick consumes the catalog you produce here.++## Tasks++1. **Canonical catalog module.** Create `api/_lib/x402/ring-catalog.js`: one+ exported array of `{slug, path, method, body(), priceAtomicDefault, tier,+ kind}` where `kind ∈ tip|service|intel|health|commerce|settle`, covering+ EVERY paid endpoint above. `body()` must produce a real, valid request body+ per endpoint (read each handler to learn its contract — no guessing, no+ empty bodies that 400). Endpoints that are genuinely unsafe to auto-buy+ (e.g. `pump-launch` mints a real coin — $5 and an on-chain artifact per+ call) get `autobuy:false` with a comment saying why; they are still covered+ by the one-time verification in step 2, on devnet or with explicit owner+ sign-off.+2. **Prove every endpoint settles.** Env-complete, self-facilitator on, funded+ payer (tiny amounts — the whole sweep at default prices costs ≈ $0.30 for+ the autobuy set): for each catalog entry, `payX402` it once. Record: 402+ challenge OK → payment accepted → facilitator settle signature → 200+ business response with real (non-stub) payload. Produce+ `tasks/x402-ring/COVERAGE.md` — a table: slug, price, settle signature,+ response OK, notes.+3. **Fix what fails.** Every endpoint that 500s, returns a stub, mis-prices,+ drops its Solana accept, or fails settlement gets fixed in this task — read+ the handler, fix the root cause, re-run, update COVERAGE.md. No endpoint is+ skipped without an `autobuy:false` justification. (Concurrent-agent+ caution: if a fix touches a file another task owns, coordinate via the+ smallest possible diff — the catalog + endpoint handlers are yours; the+ payment/pipeline plumbing is not.)+4. **Wire rotation to the catalog.** Replace the hardcoded `VOLUME_ENDPOINTS`+ and the ring tick's list with imports of `ring-catalog.js` filtered by+ `autobuy && tier`, weighted so every autobuy endpoint is exercised **at+ least once per hour** at default cadence (do the math against task 04's+ calls/minute; the catalog defines weights, the tick owns the loop). Delete+ the stale duplicate list.+5. **Tips and commerce are load-bearing.** dance-tip, club-cover, billboard,+ cosmetic-purchase, skill-marketplace are the "tips and services bought and+ sold" the owner named: confirm each writes its real business effect (tip+ recorded, cover charged, listing purchase recorded) — not just the payment+ log — and add the assertion to COVERAGE.md.+6. **Tests.** Catalog schema test (every entry has valid path/price/kind;+ `body()` returns parseable JSON); rotation-coverage test (every autobuy slug+ appears within a simulated hour); stale-path test (every `path` resolves to+ a file under `api/`).+7. **Docs + changelog.** `docs/x402-ring-economy.md`: replace the 12-endpoint+ mention with the catalog reference + coverage guarantee. Changelog entry+ (tags: `feature`, `improvement`).++## Files you own++`api/_lib/x402/ring-catalog.js` (new), `api/_lib/x402/pipelines/volume-bootstrap-loop.js`+(list → catalog import only), endpoint handler fixes under `api/x402/` ++`api/agents/`, `tasks/x402-ring/COVERAGE.md`, tests,+`docs/x402-ring-economy.md`, `data/changelog.json`.++## Constraints++- Payments only from the ring payer to our own endpoints; total verification+ spend ≤ $2 without owner sign-off (the autobuy sweep is ~cents; `pump-launch`+ and other `autobuy:false` entries need explicit approval or devnet).+- Fixing an endpoint must not change its public price without a changelog note.+- No endpoint gets a mock response to "pass" — the business effect must be real+ (CLAUDE.md hard rules apply).+- `bazaar.discoverable` flags stay as they are — ring-settle stays+ `discoverable:false`.++## Acceptance criteria++- [ ] `ring-catalog.js` covers 100% of paid endpoints (count asserted in test+ against a grep of `paidEndpoint(` usages — new endpoints fail the test+ until cataloged).+- [ ] COVERAGE.md shows a real settle signature + verified business effect for+ every autobuy endpoint, and a justification for every `autobuy:false`.+- [ ] Rotation guarantees hourly coverage (test-proven).+- [ ] All endpoint fixes listed with root cause, one line each.+- [ ] `npm test` green; docs + changelog landed.diff --git a/tasks/x402-ring/09-agents-onchain-activity.md b/tasks/x402-ring/09-agents-onchain-activity.mdnew file mode 100644index 000000000..6b6bf43ca--- /dev/null+++ b/tasks/x402-ring/09-agents-onchain-activity.md@@ -0,0 +1,115 @@+# Task 09 — Platform Agents as Real Buyers + On-Chain Deployments in the Loop++## Mission++The owner's vision is an agent-to-agent economy, not a cron paying itself:+autonomous agents and on-chain deployments should be the ones generating the+tips, purchases, and service calls. Wire the platform's existing autonomous+agents to be genuine x402 buyers inside the ring (their spend funded from and+returning to controlled wallets), and make the platform's on-chain programs+part of the visible economic activity — so the ring's volume is real agents+doing real work, every minute.++## Context you must know++- Buyer-side clients already exist: `api/_lib/x402/pay.js` (`payX402`),+ `api/_lib/x402-buyer-fetch.js`, `api/_lib/x402-buyer-axios.js`,+ `packages/x402-mcp/src/lib/x402-buyer.js` + `tools/pay-and-call.js`.+- Existing autonomous actors to enlist (read each before wiring):+ - **Endpoint shopper** — `api/agents/endpoint-shopper-run.js` (itself a paid+ endpoint): an agent that shops endpoints. Natural ring citizen.+ - **Agora citizens** — `workers/agora-citizens/` + `api/agora/[action].js`:+ agents that post/claim/work/earn (devnet AgenC). They have wallets and+ action loops already.+ - **Live-feed seeder** — registry entry `live-feed-seeder`+ (`autonomous-registry.js:2699-2711`).+ - **Agent identities with custodial Solana wallets** —+ `api/_lib/agent-wallet.js` (`ensureAgentWallet`,+ `recoverSolanaAgentKeypair`) with spend limits enforced by+ `api/_lib/agent-trade-guards.js` (`enforceSpendLimit`, custody events).+- On-chain programs in the tree: skill licenses+ (`contracts/skill-license/` + `api/_lib/skill-license-onchain.js` →+ 1/1 SPL NFT + PDA per purchased skill), agent invocation events+ (`contracts/agent-invocation/` + `agent-protocol-sdk/`), AgenC task+ marketplace (`packages/agenc-mcp/`, `api/agenc/`).+- Money rule: every buyer wallet in this task is platform-controlled (agent+ custodial wallets ARE platform-controlled — encrypted secrets in+ `agent_identities.meta`, `WALLET_ENCRYPTION_KEY`). Their USDC comes from the+ ring treasury and their revenue flows back to it. Task 06's+ `ringAllowedAddresses()` must include any wallet you enlist.++## Tasks++1. **Agent-buyer roster.** Pick 3–6 existing platform agents (real+ `agent_identities` rows with custodial Solana wallets — create them via the+ normal `ensureAgentWallet` path if none are suitable). For each, define a+ persona-consistent buying behavior over the task-08 catalog: the shopper+ buys intel + health checks; an agora citizen tips dancers and pays club+ cover after completing work; a curator agent buys skill-marketplace+ listings + billboards. Encode these as small behavior modules under+ `api/_lib/x402/agents/` (one file per persona) that the ring tick (task 04)+ can invoke as alternative buyers — the payment still goes through `payX402`+ with the agent's keypair, spend-limit-checked via `enforceSpendLimit`, and+ custody-logged.+2. **Fund + recycle agent floats.** Extend `ring-rebalance` semantics (without+ touching its treasury→payer core): a `float-top-up` step that keeps each+ roster agent's USDC between floor and ceiling (env+ `X402_RING_AGENT_FLOAT_ATOMIC`, default $2) from the treasury, and sweeps+ overflow back. Every movement logged to `x402_ring_ledger` (kind `fund`).+ All counterparties must pass `ringAllowedAddresses()`.+3. **Revenue flows back.** Where a bought service pays out to a seller (tips to+ a dancer agent, marketplace sale proceeds), confirm the seller wallet is+ also platform-controlled and its earnings are visible in the ledger — the+ loop stays closed through the *business* layer, not just the settlement+ layer. Document each flow's path in the module docstring.+4. **On-chain deployments in the loop.** Wire ONE real on-chain program+ interaction into the rotation at low cadence (e.g. hourly): an agent+ purchasing a skill license mints the real license NFT+ (`skill-license-onchain.js`), or an AgenC/agora task completion emits its+ real on-chain event (devnet per existing config). Fee payer must be a ring+ wallet; frequency and rent bounded (`X402_RING_ONCHAIN_EVERY_N_TICKS`,+ default 60; skip cleanly if program env is absent). This is the+ "on-chain deployments being utilized" requirement — real program calls,+ visibly logged, not simulated.+5. **Attribution surface.** Agent-driven purchases must be attributable:+ include `agent_id` in the `x402_autonomous_log` rows (column exists or add+ via migration) so the dashboard (task 10) can show *which agent* bought+ *what* — that's what makes it an agent economy on the surface, not a cron.+6. **Tests.** Persona behavior selection (deterministic given a tick seed),+ float top-up bounds, allowlist enforcement on every new counterparty,+ spend-limit integration (over-limit agent purchase is refused by+ `enforceSpendLimit` and logged, not thrown through the tick).+7. **Docs + changelog.** New `docs/x402-ring-economy.md` section "Agents in the+ ring": roster, personas, float mechanics, on-chain cadence. Changelog entry+ (tags: `feature`) — holders should read "platform agents now buy and sell+ services from each other on-chain, continuously".++## Files you own++`api/_lib/x402/agents/` (new), `ring-rebalance.js` float step (coordinate: task+04 owns its cadence consts), migration for `agent_id` attribution if needed,+tests, `docs/x402-ring-economy.md`, `data/changelog.json`.++## Constraints++- Every wallet added to the flow is platform-controlled and registered in+ `ringAllowedAddresses()` — verify with task 03's verify script extended to+ list roster agents.+- Agent spend limits (`agent-trade-guards.js`) are enforced on every agent+ purchase — no bypass because "it's internal".+- On-chain program calls follow the programs' existing network config (devnet+ where that's what's deployed) — no new mainnet program deploys in this task.+- No $THREE or third-party-coin purchases here — USDC service payments only+ (the commit gate in CLAUDE.md applies to anything else).+- Personas are labeled internal in logs — never presented as organic users.++## Acceptance criteria++- [ ] ≥3 agent personas actively buying in a 10-tick local run — show+ `x402_autonomous_log` rows with distinct `agent_id`s and settle sigs.+- [ ] Floats topped up and swept within bounds across the run (ledger rows).+- [ ] One real on-chain program interaction landed and linked (signature ++ explorer link, devnet acceptable).+- [ ] Over-limit purchase refused via `enforceSpendLimit` (test).+- [ ] All new counterparties pass the leak scanner (task 06) clean.+- [ ] `npm test` green; docs + changelog landed.diff --git a/tasks/x402-ring/10-ring-dashboard.md b/tasks/x402-ring/10-ring-dashboard.mdnew file mode 100644index 000000000..5e2c4d9e2--- /dev/null+++ b/tasks/x402-ring/10-ring-dashboard.md@@ -0,0 +1,107 @@+# Task 10 — Ring Dashboard: See the Economy Breathe++## Mission++The ring has a JSON scoreboard (`/api/x402-ring`) and no eyes. Build the live+operator dashboard that makes the closed-loop economy visible at a glance —+per-minute settlement pulse, who bought what, fees burned vs budget, wallet+balances vs floors, leak status, config health — so "it stopped working" can+never again go unnoticed for days. This is an owner/ops surface: polished to+the platform bar, but access-controlled and never marketing organic volume.++## Context you must know++- Data sources (all real, no mocks):+ - `GET /api/x402-ring?period=24h|7d|30d|all` (`api/x402-ring.js`) — gross+ volume, tx count, SOL burned (+USD), sweep totals, live+ treasury/payer/sponsor balances, `sponsor.below_floor`, and (post task 02/05)+ `config_warnings` + fee-efficiency metrics.+ - `x402_volume_metrics` — per-endpoint counts/last-paid (via a small admin+ read endpoint you may add).+ - `x402_autonomous_log` — the live activity feed (buyer `agent_id` per task+ 09, slug, price, status incl. skips like `cap_would_exceed`).+ - `payment_reconciliation` (sources `x402_ring_*`) — leak scanner + reconcile+ verdicts (tasks 06/07).+- Precedents to match, not reinvent: admin analytics dashboard+ `dashboard/x402-admin.html` (routed in `vercel.json:1723-1728`), admin+ seeder control room (`pages/admin/seeder.html` + `src/admin-seeder.js`,+ backend `api/admin/seeder.js`) — follow its auth pattern and its+ noindex/admin conventions.+- Frontend stack: vanilla JS modules + Vite; design tokens/CSS variables from+ existing pages (read a current page's CSS before writing yours).+- Internal-volume labeling rule (docs/x402-ring-economy.md:11-17): this+ dashboard must label ring volume as internal dogfooding — it is the+ anti-"fake organic revenue" surface, not a growth chart.++## Tasks++1. **Backend read model — `api/admin/ring-dashboard.js`**: one admin-authed+ endpoint aggregating: ring report, per-endpoint metrics, last 100 activity+ rows (with agent attribution), open reconciliation verdicts, config+ validation findings, and a `minutes_since_last_settle` scalar. Admin auth+ identical to `api/admin/seeder.js`. Efficient: single handler, parallel+ queries, no N+1.+2. **Page — `pages/admin/ring.html` + `src/admin-ring.js`** (route+ `/admin/ring`, noindex, follow the seeder page's wiring in `vercel.json` /+ `vite.config.js`):+ - **Pulse strip**: settlements per minute over the last 60 min (task 04's+ tick makes this the heartbeat) — a live bar/spark strip where a gap is+ instantly visible; `minutes_since_last_settle` as a big status number with+ green/amber/red thresholds (≤1 / ≤5 / >5 min).+ - **Loop diagram**: payer → endpoint → treasury → (sweep) → payer with live+ balances on each node and floor indicators (sponsor optional in self-pay).+ - **Activity feed**: streaming table of paid calls — time, agent persona,+ endpoint slug, kind (tip/service/intel/commerce/settle), price, settle+ sig (Solscan link), skips/failures in amber/red with their structured+ reason.+ - **Fees panel**: lamports/settlement vs the 5,000 1-sig floor,+ SOL-per-$100 volume, daily burn vs `X402_RING_DAILY_FEE_BUDGET_LAMPORTS`.+ - **Integrity panel**: leak-scan status (last run, findings count),+ reconciliation verdict counts by class, config warnings — all green =+ one calm row; any finding = expanded red detail.+ - **Coverage panel**: per-endpoint last-paid age from `x402_volume_metrics`+ (task 08's hourly guarantee made visible; stale >2h = amber).+ - Poll every 15s (`setInterval` + fetch, abort on hidden tab); relative+ timestamps; skeleton loading states; designed empty state ("ring idle —+ run the activation runbook") and error state (API unreachable, with the+ curl to debug). Keyboard: `r` refresh, `p` pause polling. Every+ interactive element has hover/focus/active states. 320/768/1440 widths.+ - Persistent header badge: "INTERNAL DOGFOODING VOLUME — not organic+ revenue" per the labeling rule.+3. **Wire navigation**: link from the existing admin surfaces (wherever+ `/admin/seeder` is linked) so it's findable; add to `data/pages.json`+ (admin/noindex flags per existing admin entries).+4. **Tests**: read-model shape test for `api/admin/ring-dashboard.js` (fixture+ DB rows → aggregated payload), threshold logic (pulse status color), and a+ route smoke test if the repo has one for admin pages.+5. **Docs + changelog.** `docs/x402-ring-economy.md` gains a "Watching it"+ section with a screenshot-worthy description + the `/admin/ring` path;+ `STRUCTURE.md` row for the new surface; changelog entry (tags: `feature`).++## Files you own++`api/admin/ring-dashboard.js` (new), `pages/admin/ring.html` (new),+`src/admin-ring.js` (new), `vercel.json`/`vite.config.js` (routing for the one+page), `data/pages.json`, tests, `docs/x402-ring-economy.md`, `STRUCTURE.md`,+`data/changelog.json`.++## Constraints++- Admin-authed and noindexed; zero secrets in the client bundle; balances and+ pubkeys are fine, secret names are not.+- Real data only — every panel renders from the live read model; no sample+ arrays shipped (CLAUDE.md hard rule 6).+- Don't modify `/api/x402-ring` beyond what tasks 02/05 already added — the+ admin read model composes, it doesn't fork the public report.+- Performance: one aggregate fetch per poll, not seven; payload < 100KB.++## Acceptance criteria++- [ ] `/admin/ring` loads with real data from the deployed (or locally-run)+ stack — screenshot or DOM-dump evidence of every panel populated.+- [ ] Pulse strip visibly reflects task 04's per-minute cadence; killing the+ tick turns the status amber→red within thresholds.+- [ ] All designed states verified: loading, empty (ring off), error (API+ down), populated — per the Definition of Done in CLAUDE.md.+- [ ] No console errors; network tab shows the single aggregate call.+- [ ] `npm test` green; pages.json + STRUCTURE.md + changelog landed.diff --git a/tasks/x402-ring/11-activation-acceptance.md b/tasks/x402-ring/11-activation-acceptance.mdnew file mode 100644index 000000000..0260cdcc3--- /dev/null+++ b/tasks/x402-ring/11-activation-acceptance.md@@ -0,0 +1,104 @@+# Task 11 — Activation, 60-Minute Acceptance Run, and the PASS/FAIL Verdict++## Mission++Everything is built; now prove it in production. Execute the go-live sequence,+run the ring for a supervised 60 minutes, measure it against the owner's+requirements verbatim — endpoints hit every minute, many times; tips, payments,+services bought and sold; agents and on-chain deployments utilized; zero+leakage; lowest fees — and deliver a PASS/FAIL report with real numbers. If any+gate fails, fix or roll back, and rerun until PASS. This task is the definition+of "it's working again".++## Context you must know++- Prior tasks landed: self-facilitator routing + `validateRingConfig()` (02),+ wallets provisioned/monitored/verified (03, incl. `scripts/x402-ring-verify.mjs`+ and `FUNDING.md`), per-minute tick with separate budget (04), self-pay fee+ floor + fee audit (05), runtime invariants + leak scanner (06), full+ reconciliation (07), 100% catalog coverage (08), agent buyers + on-chain+ cadence (09), `/admin/ring` dashboard (10).+- The env block required is documented in `.env.example` (per task 02) and+ `scripts/x402-ring-setup.mjs:79-92`. Funding amounts in+ `tasks/x402-ring/FUNDING.md`.+- Kill switches, in escalation order: `X402_RING_TICK_ENABLED=false` (tick+ only) → `X402_AUTONOMOUS_ENABLED=false` (all autonomous spend) →+ `X402_SELF_FACILITATOR_ENABLED=false` (nothing settles).++## Tasks++1. **Preflight (no funds yet).**+ - `node scripts/x402-ring-verify.mjs` → exit 0.+ - All env set in Vercel production; `validateRingConfig()` via+ `/api/x402-ring` shows zero `config_warnings`.+ - Migrations applied; `npm test` green on main; latest main deployed.+ - Leak scanner + reconciliation crons live in `vercel.json` and executing+ (check cron logs).+2. **Funding (owner-executed, you verify).** Present the owner the exact+ FUNDING.md transfers (payer USDC float, fee SOL), wait for confirmation,+ verify arrival on chain, and record funding signatures in the report. **Do+ not move funds yourself; do not proceed on partial funding.**+3. **Ignition.** Enable the tick. Watch `/admin/ring`: first settlement within+ 2 minutes. If the first tick fails, halt via the tick kill switch, diagnose+ from the structured logs, fix, redeploy, restart the 60-minute clock.+4. **60-minute supervised acceptance run.** Gates, measured over the full hour+ (pull final numbers from `/api/x402-ring?period=24h`, the admin read model,+ and the DB):+ - **Cadence**: ≥ 55 of 60 minutes contain ≥ 1 settlement; mean paid+ calls/minute ≥ 3 ("every minute, many times").+ - **Breadth**: ≥ 8 distinct endpoint kinds settled, including ≥ 1 tip, ≥ 1+ commerce/marketplace purchase, ≥ 1 service/intel call, and ring-settle on+ its configured cadence ("tips, payments, services bought and sold").+ - **Agency**: ≥ 3 distinct agent personas attributed in the hour's log; ≥ 1+ on-chain program interaction within the last 24h linked (task 09 cadence).+ - **Closed loop**: leak scanner run during the window reports ZERO leaks;+ every settlement counterparty ∈ `ringAllowedAddresses()`; net USDC+ position change ≈ 0 minus nothing (principal conserved) — reconcile+ payer+treasury+agent floats before vs after: |Δ| < $0.05.+ - **Fees**: mean lamports/settlement ≤ 5,100 (1-sig floor + jitter); total+ hour burn within the tick's fee math from task 04's docs; zero+ sponsor-mode settlements unless deliberately configured.+ - **Integrity**: reconciliation run during/after the window produces zero+ CRITICAL verdicts; zero-volume tripwire silent; dashboard pulse green+ throughout (screenshot).+ - **Recirculation**: ≥ 1 treasury→payer sweep landed and ledgered.+5. **The report — `tasks/x402-ring/ACCEPTANCE.md`.** Every gate with its+ measured value, evidence (signatures, log counts, screenshots, query+ output), PASS/FAIL per gate, overall verdict. If FAIL: root cause, fix+ commit, and the rerun's numbers appended — the file is the history of runs+ until the first full PASS.+6. **Steady-state handoff.** On PASS: document the standing posture in+ `docs/x402-ring-economy.md` ("Operating the ring" section): daily budgets in+ force, alert channels, the kill-switch ladder, the weekly ledger-export+ habit (`scripts/economy-ledger-export.mjs` pattern), and what "healthy"+ looks like on `/admin/ring`. Update `STRUCTURE.md` ring row status to+ live/on. Changelog entry (tags: `feature`, `infra`) — holders read: "the+ agent-to-agent economy is live: platform agents continuously buying and+ selling services, settled on-chain by our own facilitator."+7. **Rollback discipline.** Any CRITICAL leak/reconcile alert during the run:+ kill-switch ladder immediately, snapshot state, report — never "watch it for+ a bit". Funds-at-risk beats uptime.++## Files you own++`tasks/x402-ring/ACCEPTANCE.md` (new), `docs/x402-ring-economy.md`,+`STRUCTURE.md` (ring row), `data/changelog.json`. Fix commits may touch prior+tasks' files — smallest possible diffs, respecting their structure.++## Constraints++- You verify funding; the owner sends it. Never initiate a transfer from any+ non-ring wallet.+- Production env changes are recorded in the report (name + old→new, values+ redacted for secrets).+- The 60-minute clock restarts after any fix that touches the money path.+- No gate is waived. A "close enough" FAIL is a FAIL with a rerun.++## Acceptance criteria++- [ ] ACCEPTANCE.md exists with all gates measured, evidenced, and an overall+ PASS.+- [ ] The dashboard screenshot shows a green hour.+- [ ] Steady-state docs + STRUCTURE.md + changelog landed.+- [ ] Kill-switch ladder tested once live (flip tick off → pulse amber →+ flip on → recovers) and documented.diff --git a/tasks/x402-ring/README.md b/tasks/x402-ring/README.mdnew file mode 100644index 000000000..7b5a29b63--- /dev/null+++ b/tasks/x402-ring/README.md@@ -0,0 +1,62 @@+# x402 Ring Economy — Repair & Production-Readiness Prompt Set++The closed-loop agent-to-agent economy (docs/x402-ring-economy.md) is fully+implemented but currently produces **zero volume**. Root-cause audit (2026-07-03):++1. `X402_FACILITATOR_URL_SOLANA` defaults to PayAI (`api/_lib/env.js:742-748`) —+ settlements never reach our self-hosted facilitator.+2. `X402_SELF_FACILITATOR_ENABLED` defaults false → `/api/x402-facilitator`+ returns 503 (`api/x402-facilitator/[action].js:89-96`).+3. `ring-settle` price ($1.00) exceeds the volume loop's per-run cap ($0.05) →+ skipped with `cap_would_exceed` on every cycle+ (`api/_lib/x402/pipelines/volume-bootstrap-loop.js:59-62`, `api/_lib/x402/pay.js:182-184`).+4. Rebalancer is a permanent no-op without `X402_TREASURY_SECRET_BASE58`+ (`api/_lib/x402/pipelines/ring-rebalance.js:71-72`) → the payer float drains once and halts.+5. The Solana accept is dropped from every 402 challenge when+ `X402_FEE_PAYER_SOLANA` is unset (`api/_lib/x402-paid-endpoint.js:175-179`).+6. Cadence is one 5-minute cron (`vercel.json:4872-4875`), not per-minute.+7. Reconciliation never reads `x402_self_facilitator_log` / `x402_ring_ledger`.+8. No dashboard; ring wallets are not balance-monitored.++Each prompt below is a self-contained task for one agent. **Run them in order** —+later prompts assume earlier ones landed. 01 is read-only diagnosis; 02–10 are+code; 11 is the live activation + acceptance gate.++| # | File | Task | Depends on |+|---|---|---|---|+| 01 | [01-audit-live-state.md](01-audit-live-state.md) | Read-only live-state audit → STATUS.md | — |+| 02 | [02-facilitator-routing.md](02-facilitator-routing.md) | Route settlement to the self-hosted facilitator; fix env defaults + docs lies | 01 |+| 03 | [03-wallets-provisioning.md](03-wallets-provisioning.md) | Provision/verify the 3 ring wallets; register, monitor, floor-guard them | 01 |+| 04 | [04-per-minute-cadence.md](04-per-minute-cadence.md) | Dedicated per-minute ring tick — many paid hits/minute, cap-coherent | 02, 03 |+| 05 | [05-fee-minimization.md](05-fee-minimization.md) | Self-pay 1-sig everywhere, fee audit, ATA rent reclaim, fee budget alarm | 04 |+| 06 | [06-leak-proofing.md](06-leak-proofing.md) | Runtime leak invariants + on-chain leak scanner over all ring wallets | 03 |+| 07 | [07-reconciliation.md](07-reconciliation.md) | Close the reconciliation blind spot (facilitator log + ring ledger vs chain) | 04 |+| 08 | [08-endpoint-coverage.md](08-endpoint-coverage.md) | Every paid endpoint (tips, services, intel) exercised and actually settling | 04 |+| 09 | [09-agents-onchain-activity.md](09-agents-onchain-activity.md) | Platform agents as real x402 buyers; on-chain deployments in the loop | 08 |+| 10 | [10-ring-dashboard.md](10-ring-dashboard.md) | Live ring dashboard: per-minute hits, fees, balances, leak status | 04 |+| 11 | [11-activation-acceptance.md](11-activation-acceptance.md) | Funding, go-live, 60-minute acceptance run, PASS/FAIL report, docs | all |++## Ground rules (every agent, every prompt)++- **CLAUDE.md governs.** No mocks, no placeholders, no TODOs, real APIs only.+- **Closed loop is sacred.** Money may only move between the three ring wallets+ (payer, treasury, sponsor) and platform-controlled wallets already in+ `api/_lib/solana-signers.js`. Never add a route that can send SOL or USDC to+ any other address. `X402_EXTERNAL_ENABLED=false` and `X402_CHARITY_AUDIT_BPS=0`+ are load-bearing.+- **Lowest fees always.** Self-pay (1 signature) is the default mode; priority+ fees stay at the ~5 µlamport floor; prefer fewer/larger settlements when a+ choice exists. Any change that adds a transaction must justify it.+- **Never weaken a guard.** The anti-drain gate, allowlists, SOL floors, spend+ caps, and kill switches in `api/_lib/x402/self-facilitator.js` and+ `api/_lib/x402/pay.js` may be extended, never relaxed.+- **Secrets never touch git.** Key material lives in Vercel env /+ `.x402-ring-secrets.json` (gitignored). Verify `git diff --staged` contains no+ base58 secrets before every commit.+- **Concurrent agents share this worktree.** Stage explicit paths only; re-check+ `git status` and `git diff --staged` immediately before committing. Respect the+ "Files you own" section of your prompt.+- **Env changes** go through `vercel env` (production) AND `.env.example`+ (documented, with the correct default described). Local `.env` for testing only.+- **Prove it.** Every prompt ends with acceptance criteria. Run the verification+ commands and paste real output in your report. "Should work" is a failed task.