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(ops): payment-outcome board on /admin/ops
nirholasf195dcc4275a
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.jsindex a6203399f..28c99e579 100644--- a/api/_lib/x402-paid-endpoint.js+++ b/api/_lib/x402-paid-endpoint.js@@ -939,6 +939,22 @@ export function paidEndpoint(spec) {// Verify is a payment outcome too — record it so the invalid/rejected-// payment rate is visible alongside settlements. A 402 here is a rejected// proof (insufficient/invalid), distinct from an upstream verify fault.+ // The Axiom metric is fire-and-forget and unconfigured in most deploys,+ // so ALSO write the durable audit event: the verify-reject rate is one+ // of the three panels /api/ops/payment-outcomes exists to show, and a+ // griefing wave (junk X-PAYMENT floods) is invisible without it.+ logPaymentEvent({+ eventType: 'payment_verify_rejected',+ route,+ resourceUrl,+ durationMs: Date.now() - requestStartTime,+ ipAddress: clientIp(req),+ userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,+ metadata: {+ reason: err.code || (err.status === 402 ? 'verify_rejected' : 'verify_failed'),+ kind: err.status === 402 ? 'rejected_proof' : 'upstream_fault',+ },+ });recordPaymentMetric({kind: 'x402',status: 'failed',diff --git a/api/ops/payment-outcomes.js b/api/ops/payment-outcomes.jsnew file mode 100644index 000000000..a5561a2f6--- /dev/null+++ b/api/ops/payment-outcomes.js@@ -0,0 +1,181 @@+// GET /api/ops/payment-outcomes: the payment-outcome board.+//+// The fable-audit called out that the x402 griefing classes (verify-reject+// floods, settle failures, sponsor-fee starvation) only become visible after+// they halt the economy. This endpoint aggregates the durable payment ledger+// (x402_audit_log), the self-facilitator settle log, the outbound ring settle+// sensor, and the live ring wallet balances into one read-only JSON board:+//+// inbound : settle / verify-reject / replay-reject / unsettled-flush+// counts and rates over 1h / 3h / 24h windows, replay stage+// split, top failure reasons, settled volume.+// ring_settle : gatherX402SettleHealth(), the outbound settle-success-rate+// sensor (3h window, rail-fault allowlist).+// sponsor : fee-wallet SOL vs its floor plus measured burn (7d of+// fee_lamports) and the runway in days that implies.+//+// Auth: authorizeOps (admin session, or x-ops-secret / OPS_SECRET): the same+// gate as /api/ops/health, so the /admin/ops dashboard reuses its stored+// secret. Read-only; moves no funds; reads balances via RPC only.++import { cors, json, method, wrap, error } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { authorizeOps } from '../_lib/ops-auth.js';+import { gatherX402SettleHealth } from '../_lib/ops/x402-settle-health.js';+import { checkRingWallets } from '../_lib/x402/wallet-balance-monitor.js';++export const maxDuration = 30;++const INBOUND_EVENTS = [+ 'payment_settled',+ 'payment_failed',+ 'payment_verify_rejected',+ 'payment_replay_rejected',+ 'payment_unsettled_flush',+];++function rate(numerator, denominator) {+ if (!denominator) return null;+ return Math.round((numerator / denominator) * 1000) / 1000;+}++function windowStats(counts) {+ const settled = counts.payment_settled || 0;+ const settleFailed = counts.payment_failed || 0;+ const verifyRejected = counts.payment_verify_rejected || 0;+ const replayRejected = counts.payment_replay_rejected || 0;+ const unsettledFlush = counts.payment_unsettled_flush || 0;+ // Attempts that reached verify: replays are refused before verify, so they+ // are reported but excluded from both denominators.+ const verifyAttempts = settled + settleFailed + verifyRejected;+ const settleAttempts = settled + settleFailed;+ return {+ settled,+ settle_failed: settleFailed,+ verify_rejected: verifyRejected,+ replay_rejected: replayRejected,+ unsettled_flush: unsettledFlush,+ settle_success_rate: rate(settled, settleAttempts),+ verify_reject_rate: rate(verifyRejected, verifyAttempts),+ };+}++async function inboundBoard() {+ // One 24h index scan carries all three windows via FILTER.+ const rows = await sql`+ SELECT event_type,+ count(*) FILTER (WHERE created_at >= now() - interval '1 hour')::int AS h1,+ count(*) FILTER (WHERE created_at >= now() - interval '3 hours')::int AS h3,+ count(*)::int AS h24+ FROM x402_audit_log+ WHERE created_at >= now() - interval '24 hours'+ AND event_type = ANY(${INBOUND_EVENTS})+ GROUP BY event_type+ `;+ const byWindow = { h1: {}, h3: {}, h24: {} };+ for (const r of rows) {+ byWindow.h1[r.event_type] = r.h1;+ byWindow.h3[r.event_type] = r.h3;+ byWindow.h24[r.event_type] = r.h24;+ }++ const [replayStages, reasons, [volume]] = await Promise.all([+ sql`+ SELECT coalesce(metadata->>'stage', 'unknown') AS stage, count(*)::int AS n+ FROM x402_audit_log+ WHERE created_at >= now() - interval '24 hours'+ AND event_type = 'payment_replay_rejected'+ GROUP BY 1+ `,+ sql`+ SELECT coalesce(metadata->>'code', metadata->>'reason', 'unknown') AS reason,+ event_type, count(*)::int AS n+ FROM x402_audit_log+ WHERE created_at >= now() - interval '24 hours'+ AND event_type IN ('payment_failed', 'payment_verify_rejected')+ GROUP BY 1, 2+ ORDER BY n DESC+ LIMIT 12+ `,+ sql`+ SELECT coalesce(sum(+ CASE WHEN amount_atomics IS NOT NULL AND amount_atomics ~ '^[0-9]+$'+ THEN amount_atomics::numeric ELSE 0 END+ ), 0) AS atomics+ FROM x402_audit_log+ WHERE created_at >= now() - interval '24 hours'+ AND event_type = 'payment_settled'+ `,+ ]);++ return {+ windows: {+ '1h': windowStats(byWindow.h1),+ '3h': windowStats(byWindow.h3),+ '24h': windowStats(byWindow.h24),+ },+ replay_stages_24h: Object.fromEntries(replayStages.map((r) => [r.stage, r.n])),+ top_failure_reasons_24h: reasons.map((r) => ({+ reason: r.reason,+ stage: r.event_type === 'payment_failed' ? 'settle' : 'verify',+ count: r.n,+ })),+ settled_volume_usd_24h: Number(volume?.atomics || 0) / 1e6,+ };+}++async function sponsorBoard() {+ // Balances via the ring monitor with alerting disabled: a dashboard READ+ // must never page anyone; the scheduled monitor owns alerting.+ const ring = await checkRingWallets({ sendAlert: async () => {} });+ const sponsor = ring.wallets.find((w) => w.role === 'sponsor') || null;++ // Measured burn, not a remembered constant: fee_lamports over settled+ // settles for 7 days (ISSUES.md item 6 records the folklore number being+ // wrong by roughly 10x, so derive it every time).+ const [burn] = await sql`+ SELECT count(*)::int AS settles,+ coalesce(sum(fee_lamports), 0)::bigint AS lamports+ FROM x402_self_facilitator_log+ WHERE ts >= now() - interval '7 days'+ AND action = 'settle' AND ok = true+ `;+ const burnSolPerDay = Number(burn?.lamports || 0) / 7 / 1e9;+ const sol = sponsor?.sol ?? null;+ return {+ configured: Boolean(sponsor?.address),+ address: sponsor?.address || null,+ sol,+ sol_floor: sponsor?.sol_floor ?? null,+ below_floor: Boolean(sponsor?.sol_low),+ settles_7d: burn?.settles ?? 0,+ burn_sol_per_day_7d: Math.round(burnSolPerDay * 1e6) / 1e6,+ runway_days: sol != null && burnSolPerDay > 0+ ? Math.round((sol / burnSolPerDay) * 10) / 10+ : null,+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;+ const auth = await authorizeOps(req);+ if (!auth.ok) return error(res, 401, 'unauthorized', 'ops secret or admin session required');++ // The three boards are independent reads; one failing must not blank the+ // others (an RPC outage is exactly when the settle panels matter most).+ const [inbound, ringSettle, sponsor] = await Promise.allSettled([+ inboundBoard(),+ gatherX402SettleHealth(),+ sponsorBoard(),+ ]);+ const unwrap = (r) => (r.status === 'fulfilled' ? r.value : { error: r.reason?.message || 'unavailable' });++ return json(res, 200, {+ ok: true,+ generated_at: new Date().toISOString(),+ inbound: unwrap(inbound),+ ring_settle: unwrap(ringSettle),+ sponsor: unwrap(sponsor),+ }, { 'cache-control': 'no-store' });+});diff --git a/docs/ops/README.md b/docs/ops/README.mdindex 2ccf659ce..ef8345057 100644--- a/docs/ops/README.md+++ b/docs/ops/README.md@@ -12,6 +12,7 @@ Start with [gcp-production.md](gcp-production.md); it is the complete operationa| [gcp-model-workers.md](gcp-model-workers.md) | Self-hosted GPU generation lanes on Cloud Run: workers, weights, deploys. || [gcp-logs.md](gcp-logs.md) | Production log reading and automated triage tools for the Cloud Run fleet. || [production-log-triage.md](production-log-triage.md) | Known error/warning signature map: what each recurring log signature means and the fix. |+| [payment-outcomes.md](payment-outcomes.md) | The payment-outcome board (`/api/ops/payment-outcomes` + the `/admin/ops` panel): verify-reject, settle-fail, replay, and sponsor-runway signals and how to read them in an incident. || [solana-rpc-lanes.md](solana-rpc-lanes.md) | The Solana RPC tier end to end: one-sweep diagnosis, per-lane method capability, what must rotate vs fail, config traps, recovery. || [page-audit.md](page-audit.md) | `scripts/page-audit.mjs`: authed Chromium sweep of every public page, console-error gated. || [db-retention.md](db-retention.md) | Keeping the Neon Postgres branch under its storage cap: what grows, what gets pruned. |diff --git a/docs/ops/payment-outcomes.md b/docs/ops/payment-outcomes.mdnew file mode 100644index 000000000..4cb1dfed0--- /dev/null+++ b/docs/ops/payment-outcomes.md@@ -0,0 +1,87 @@+# Payment-outcome board++`GET /api/ops/payment-outcomes` is the single read that answers "are payments+healthy right now, and if not, which stage is failing?". It exists because the+x402 griefing classes (verify-reject floods, settle failures, sponsor-fee+starvation) historically became visible only after they halted the economy;+the 2026-07-11 fable audit filed the gap and this board closes it. The+`/admin/ops` dashboard renders it as the "Payment outcomes" section.++## Auth++Same gate as `/api/ops/health`: an admin session, or `x-ops-secret` matching+`OPS_SECRET` (never `CRON_SECRET`; see `api/_lib/ops-auth.js`). Unset secret+means open in dev and denied in production. Read-only; it moves no funds and+never fires alerts (balance reads go through the ring monitor with alerting+disabled; the scheduled monitor owns paging).++## The three panels++### `inbound` (from `x402_audit_log`)++Counts and rates over 1h / 3h / 24h windows for payments arriving at our paid+routes:++- `settled` / `settle_failed`: outcomes of `settlePayment` after a valid+ verify. `settle_success_rate` = settled / (settled + settle_failed).+- `verify_rejected`: `verifyPayment` refusals, written durably as+ `payment_verify_rejected` events (metadata carries `reason` and+ `rejected_proof` vs `upstream_fault`). A spike here with flat settles is the+ junk-X-PAYMENT griefing signature: the per-IP verify penalty bucket should+ be absorbing it, and this is the panel that proves whether it is.+- `replay_rejected`, split by stage in `replay_stages_24h`: `pre_handler`+ means the durable spent-payment guard refused a replayed proof before the+ handler ran; `post_settle` means a lost insert race was refused at claim+ time. Any sustained nonzero rate is someone re-sending captured headers.+- `top_failure_reasons_24h` names the dominant failure codes with the stage+ (verify vs settle) so a 502 cluster is distinguishable from a rejected-proof+ wave without a log dive.+- `settled_volume_usd_24h` from settled `amount_atomics` (USDC, 6 decimals).++Replays are excluded from both rate denominators: they are refused before+verify and would otherwise dilute the signal.++### `ring_settle` (from `gatherX402SettleHealth`)++The outbound settle-success sensor over `x402_autonomous_log` (3h window,+rail-fault allowlist), verbatim: status, human detail, triage hint, and the+top fault signatures. This is the same object `/api/healthz` consumes; it is+included here so the board is complete without a second request. Its triage+map lives in [production-log-triage.md](production-log-triage.md).++### `sponsor` (live RPC + `x402_self_facilitator_log`)++The fee wallet that pays every settle's SOL fee:++- `sol` vs `sol_floor` (`X402_SPONSOR_SOL_FLOOR_LAMPORTS`, default 0.02): at+ or below the floor the self-facilitator refuses settlement, which surfaces+ downstream as `fee_wallet_below_floor`.+- `burn_sol_per_day_7d` is MEASURED from `fee_lamports` over the last 7 days+ of successful settles, never quoted from memory: the folklore burn rate has+ been wrong by roughly 10x before (ISSUES.md item 6).+- `runway_days` = balance / measured burn. Under ~3 days the dashboard card+ turns amber; below the floor it turns red. Top up the SPONSOR, never+ per-agent wallets (that strands SOL and kills the rail).++## Reading it in an incident++1. `inbound.settle_success_rate` low but `verify_reject_rate` flat: the rail+ or facilitator is failing after verify. Check `ring_settle.detail` for the+ fault mix; `http_502` clusters with empty simulation logs are RPC/preflight+ faults (see [solana-rpc-lanes.md](solana-rpc-lanes.md)).+2. `verify_reject_rate` spiking: someone is flooding junk proofs. Confirm the+ verify penalty limiter is holding (the reasons list will be dominated by+ `verify_rejected` with `rejected_proof`).+3. Both fine but settles refused with 503s: look at `sponsor`. Floor breach or+ sub-day runway is the answer; fund the sponsor address shown.+4. `replay_stages_24h` nonzero: captured X-PAYMENT headers are being re-sent;+ the guard is working if the settles panel is unaffected.++## Related++- `api/ops/payment-outcomes.js` (the endpoint), `pages/admin/ops.html` (the+ panel), `api/_lib/ops/x402-settle-health.js` (the sensor),+ `api/_lib/x402/wallet-balance-monitor.js` (balances and floors),+ `api/_lib/x402/audit-log.js` (the durable ledger the inbound panel reads).+- `/api/ops/money-health` is the complementary board: open reconciliation+ verdicts per money subsystem rather than live payment outcomes.diff --git a/pages/admin/ops.html b/pages/admin/ops.htmlindex b047bb566..3d3341f37 100644--- a/pages/admin/ops.html+++ b/pages/admin/ops.html@@ -138,6 +138,16 @@.skeleton { background: linear-gradient(90deg, rgba(255,255,255,0.04) 25%, rgba(255,255,255,0.07) 50%, rgba(255,255,255,0.04) 75%); background-size: 200% 100%; animation: shimmer 1.5s infinite; border-radius: 6px; height: 14px; }@keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }+ /* Payment outcomes */+ .pay-detail { font-size: 12.5px; line-height: 1.55; color: rgba(255,255,255,0.55); border-radius: 10px; padding: 0.8rem 1rem; margin-bottom: 1rem; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07); }+ .pay-detail.ok { border-color: rgba(47,191,113,0.2); }+ .pay-detail.warn { border-color: rgba(240,169,59,0.3); }+ .pay-detail.down { border-color: rgba(248,113,113,0.35); }+ .pay-detail .pd-status { font-weight: 700; margin-right: 0.5rem; }+ .pay-detail.ok .pd-status { color: #2fbf71; }+ .pay-detail.warn .pd-status { color: #f0a93b; }+ .pay-detail.down .pd-status { color: var(--danger); }+/* Category headings inside probe grid */.cat-label { font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 700; color: rgba(255,255,255,0.25); margin: 1.25rem 0 0.5rem; grid-column: 1 / -1; }.cat-label:first-child { margin-top: 0; }@@ -202,6 +212,23 @@</div></div>+ <!-- Payment outcomes (from /api/ops/payment-outcomes) -->+ <div class="ops-section" id="paymentsSection">+ <div class="ops-section-hd">Payment outcomes</div>+ <div class="ops-summary" id="payCards">+ <div class="skeleton" style="height:72px;grid-column:1/-1"></div>+ </div>+ <div class="pay-detail" id="payRingSettle"></div>+ <table class="cron-table" id="payReasonsTable" style="display:none">+ <thead><tr>+ <th>Failure reason (24h)</th>+ <th>Stage</th>+ <th>Count</th>+ </tr></thead>+ <tbody id="payReasonsBody"></tbody>+ </table>+ </div>+<!-- Cron heartbeats --><div class="ops-section"><div class="ops-section-hd">Cron heartbeats</div>@@ -273,6 +300,72 @@ async function load() {$('refreshBtn').disabled = false;}loadAlerts();+ loadPayments();+}++async function loadPayments() {+ if (!_secret) return;+ try {+ const r = await fetch('/api/ops/payment-outcomes', { headers: { 'x-ops-secret': _secret } });+ if (!r.ok) throw new Error('HTTP ' + r.status);+ renderPayments(await r.json());+ } catch (e) {+ $('payCards').innerHTML = `<div class="alerts-empty" style="background:rgba(248,113,113,0.06);border-color:rgba(248,113,113,0.16);color:#f87171;grid-column:1/-1">Couldn't load payment outcomes: ${esc(e.message)}</div>`;+ $('payRingSettle').style.display = 'none';+ $('payReasonsTable').style.display = 'none';+ }+}++function pct(v) { return v == null ? 'n/a' : (v * 100).toFixed(1) + '%'; }++function renderPayments(d) {+ const w3 = d.inbound?.windows?.['3h'] || {};+ const w24 = d.inbound?.windows?.['24h'] || {};+ const sp = d.sponsor || {};+ const replay24 = w24.replay_rejected || 0;+ const stages = d.inbound?.replay_stages_24h || {};+ const stageTxt = replay24+ ? Object.entries(stages).map(([s, n]) => `${s}: ${n}`).join(' · ')+ : 'no replays seen';++ const settleCls = w3.settle_success_rate == null ? '' : w3.settle_success_rate >= 0.9 ? 'ok' : w3.settle_success_rate >= 0.7 ? 'warn' : 'bad';+ const verifyCls = w3.verify_reject_rate == null ? '' : w3.verify_reject_rate <= 0.05 ? 'ok' : w3.verify_reject_rate <= 0.2 ? 'warn' : 'bad';+ const sponsorCls = sp.error || sp.below_floor ? 'bad' : sp.runway_days != null && sp.runway_days < 3 ? 'warn' : 'ok';+ const sponsorVal = sp.error ? '✕' : sp.sol != null ? sp.sol.toFixed(4) + ' SOL' : sp.configured === false ? 'not set' : 'n/a';+ const sponsorSub = sp.error ? esc(sp.error)+ : sp.sol != null+ ? `floor ${sp.sol_floor != null ? sp.sol_floor.toFixed(2) : 'n/a'} · burn ${sp.burn_sol_per_day_7d ?? 'n/a'}/day · runway ${sp.runway_days != null ? sp.runway_days + 'd' : 'n/a'}`+ : 'sponsor wallet unconfigured';++ $('payCards').innerHTML = [+ { lbl: 'Inbound settle success (3h)', val: pct(w3.settle_success_rate), cls: settleCls, sub: `${w3.settled ?? 0} settled · ${w3.settle_failed ?? 0} failed` },+ { lbl: 'Verify rejects (3h)', val: pct(w3.verify_reject_rate), cls: verifyCls, sub: `${w3.verify_rejected ?? 0} rejected proofs` },+ { lbl: 'Replay rejects (24h)', val: String(replay24), cls: replay24 ? 'warn' : 'ok', sub: stageTxt },+ { lbl: 'Settled volume (24h)', val: '$' + Number(d.inbound?.settled_volume_usd_24h ?? 0).toFixed(2), cls: '', sub: `${w24.settled ?? 0} payments` },+ { lbl: 'Sponsor fee wallet', val: sponsorVal, cls: sponsorCls, sub: sponsorSub },+ ].map(c => `<div class="sum-card"><div class="lbl">${c.lbl}</div><div class="val ${c.cls}">${c.val}</div><div class="sub">${c.sub}</div></div>`).join('');++ const rs = d.ring_settle || {};+ const rsEl = $('payRingSettle');+ if (rs.status) {+ rsEl.style.display = 'block';+ rsEl.className = 'pay-detail ' + (rs.status === 'ok' ? 'ok' : rs.status === 'down' ? 'down' : 'warn');+ rsEl.innerHTML = `<span class="pd-status">Ring settle: ${esc(rs.status)}</span>${esc(rs.detail || '')}`;+ } else {+ rsEl.style.display = 'none';+ }++ const reasons = d.inbound?.top_failure_reasons_24h || [];+ if (reasons.length) {+ $('payReasonsTable').style.display = 'table';+ $('payReasonsBody').innerHTML = reasons.map(r => `<tr>+ <td>${esc(r.reason)}</td>+ <td class="cron-ago">${esc(r.stage)}</td>+ <td class="cron-ago">${r.count}</td>+ </tr>`).join('');+ } else {+ $('payReasonsTable').style.display = 'none';+ }}let _showResolved = false;@@ -454,6 +547,7 @@ async function tryAuth() {$('authGate').style.display = 'none';$('dashboard').style.display = 'block';loadAlerts();+ loadPayments();startAutoRefresh();}