Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: systems admin panel, ops endpoints, and dashboard nav updates

nirholas02128bafc6b7
diff --git a/api/_lib/http.js b/api/_lib/http.js
index ecbdf96f9..035f2f619 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -449,9 +449,19 @@ export function wrap(handler) {
// bugs still surface through normal alerting.
export function wrapCron(handler) {
return wrap(async (req, res, ...rest) => {
+ // Derive cron name from the request URL for heartbeat tracking.
+ const cronName = (req.url || '').replace(/^\/api\/cron\//, '').split('?')[0] || 'unknown';
+ const t0 = Date.now();
try {
await handler(req, res, ...rest);
+ // Write heartbeat after success — fire-and-forget, never blocks.
+ import('./cache.js').then(({ cacheSet }) => {
+ cacheSet(`cron:heartbeat:${cronName}`, { ok: true, t: t0, ms: Date.now() - t0 }, 7 * 24 * 60 * 60).catch(() => {});
+ }).catch(() => {});
} catch (err) {
+ import('./cache.js').then(({ cacheSet }) => {
+ cacheSet(`cron:heartbeat:${cronName}`, { ok: false, t: t0, ms: Date.now() - t0, err: err?.message?.slice(0, 200) }, 7 * 24 * 60 * 60).catch(() => {});
+ }).catch(() => {});
if (isDbUnavailableError(err)) {
console.warn('[cron] db unavailable — skipping tick:', err.message);
if (!res.headersSent && !res.writableEnded) {
diff --git a/api/admin/all-systems.js b/api/admin/all-systems.js
new file mode 100644
index 000000000..24db8d0b9
--- /dev/null
+++ b/api/admin/all-systems.js
@@ -0,0 +1,333 @@
+// GET /api/admin/all-systems
+//
+// Single endpoint that checks every running system in parallel and returns
+// a unified health picture. Auth: session+admin OR Bearer $CRON_SECRET.
+//
+// Each check returns:
+// { name, category, status: 'ok'|'warn'|'down', count?, last?, detail? }
+//
+// Status thresholds:
+// ok — recent activity or heartbeat is fresh
+// warn — activity exists but is stale / lower than expected
+// down — no activity within the staleness window or query failed
+
+import { sql } from '../_lib/db.js';
+import { requireAdmin } from '../_lib/admin.js';
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { getRedis } from '../_lib/redis.js';
+
+function isCronAuth(req) {
+ const auth = req.headers.authorization || '';
+ const bearer = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
+ return !!env.CRON_SECRET && constantTimeEquals(bearer, env.CRON_SECRET);
+}
+
+// ── Individual system checks ──────────────────────────────────────────────────
+
+// Generic "count rows created in the last N minutes" check.
+async function recentCount(table, minutesOk, minutesWarn, col = 'created_at') {
+ try {
+ const [row] = await sql`
+ select count(*)::int as n from ${sql(table)}
+ where ${sql(col)} > now() - (${minutesOk} || ' minutes')::interval
+ `;
+ const n = row?.n ?? 0;
+ if (n > 0) return { status: 'ok', count: n };
+ // Nothing in the ok window — check the warn window
+ const [warn] = await sql`
+ select count(*)::int as n, max(${sql(col)}) as last from ${sql(table)}
+ where ${sql(col)} > now() - (${minutesWarn} || ' minutes')::interval
+ `;
+ if ((warn?.n ?? 0) > 0) return { status: 'warn', count: warn.n, last: warn.last };
+ const [last] = await sql`
+ select max(${sql(col)}) as last from ${sql(table)}
+ `;
+ return { status: 'down', count: 0, last: last?.last ?? null };
+ } catch (err) {
+ return { status: 'down', count: 0, detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// Bot heartbeat freshness check.
+async function heartbeat(worker, okMinutes = 6, warnMinutes = 30) {
+ try {
+ const [row] = await sql`
+ select last_beat_at, mode, meta from bot_heartbeat where worker = ${worker}
+ `;
+ if (!row) return { status: 'down', detail: 'no heartbeat row' };
+ const ageMs = Date.now() - new Date(row.last_beat_at).getTime();
+ const ageMins = ageMs / 60_000;
+ const status = ageMins <= okMinutes ? 'ok' : ageMins <= warnMinutes ? 'warn' : 'down';
+ return { status, last: row.last_beat_at, mode: row.mode, meta: row.meta };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// x402 payments: count from x402_audit_log last 10 min / 60 min.
+async function checkX402() {
+ try {
+ const [r] = await sql`
+ select
+ count(*) filter (where created_at > now() - interval '10 minutes') as n_10m,
+ count(*) filter (where created_at > now() - interval '60 minutes') as n_60m,
+ count(*) filter (where created_at > now() - interval '24 hours') as n_24h,
+ max(created_at) as last
+ from x402_audit_log
+ where event_type = 'payment_settled'
+ `;
+ const n = Number(r?.n_10m ?? 0);
+ const n60 = Number(r?.n_60m ?? 0);
+ const n24 = Number(r?.n_24h ?? 0);
+ const status = n > 0 ? 'ok' : n60 > 0 ? 'warn' : 'down';
+ return { status, count_10m: n, count_60m: n60, count_24h: n24, last: r?.last };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// Forge seed: done jobs last 10 / 60 min.
+async function checkForgeSeed() {
+ try {
+ const [r] = await sql`
+ select
+ count(*) filter (where finished_at > now() - interval '10 minutes') as n_10m,
+ count(*) filter (where finished_at > now() - interval '60 minutes') as n_60m,
+ count(*) filter (where finished_at > now() - interval '24 hours') as n_24h,
+ max(finished_at) as last
+ from forge_seed_jobs where status = 'done'
+ `;
+ const n = Number(r?.n_10m ?? 0);
+ const n60 = Number(r?.n_60m ?? 0);
+ const n24 = Number(r?.n_24h ?? 0);
+ const status = n > 0 ? 'ok' : n60 > 0 ? 'warn' : 'down';
+ return { status, count_10m: n, count_60m: n60, count_24h: n24, last: r?.last };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// Club tips: recent tips.
+async function checkClubTips() {
+ try {
+ const [r] = await sql`
+ select
+ count(*) filter (where created_at > now() - interval '10 minutes') as n_10m,
+ count(*) filter (where created_at > now() - interval '60 minutes') as n_60m,
+ count(*) filter (where created_at > now() - interval '24 hours') as n_24h,
+ max(created_at) as last
+ from club_tips
+ `;
+ const n = Number(r?.n_10m ?? 0);
+ const n24 = Number(r?.n_24h ?? 0);
+ const status = n > 0 ? 'ok' : Number(r?.n_60m ?? 0) > 0 ? 'warn' : 'down';
+ return { status, count_10m: n, count_24h: n24, last: r?.last };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// Pump launches + trades.
+async function checkPump() {
+ try {
+ const [mints, trades, buybacks, dist] = await Promise.all([
+ sql`select count(*)::int as n_24h, max(created_at) as last from pump_agent_mints
+ where created_at > now() - interval '24 hours'`,
+ sql`select count(*)::int as n_24h, max(created_at) as last from pump_agent_trades
+ where created_at > now() - interval '24 hours'`,
+ sql`select count(*) filter (where status='confirmed') as ok,
+ count(*) filter (where status='failed') as err,
+ max(created_at) as last
+ from pump_buyback_runs where created_at > now() - interval '24 hours'`,
+ sql`select count(*) filter (where status='confirmed') as ok,
+ count(*) filter (where status='failed') as err,
+ max(created_at) as last
+ from pump_distribute_runs where created_at > now() - interval '24 hours'`,
+ ]);
+ const launchCount = mints[0]?.n_24h ?? 0;
+ const tradeCount = trades[0]?.n_24h ?? 0;
+ const status = tradeCount > 0 ? 'ok' : launchCount > 0 ? 'warn' : 'down';
+ return {
+ status,
+ launches_24h: launchCount,
+ trades_24h: tradeCount,
+ buybacks: { ok: Number(buybacks[0]?.ok ?? 0), err: Number(buybacks[0]?.err ?? 0), last: buybacks[0]?.last },
+ distributes: { ok: Number(dist[0]?.ok ?? 0), err: Number(dist[0]?.err ?? 0), last: dist[0]?.last },
+ last: trades[0]?.last,
+ };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// Circulation / pulse-tick: agent_custody_events last 10 / 60 min.
+async function checkCirculation() {
+ try {
+ const [r] = await sql`
+ select
+ count(*) filter (where created_at > now() - interval '10 minutes') as n_10m,
+ count(*) filter (where created_at > now() - interval '60 minutes') as n_60m,
+ count(*) filter (where created_at > now() - interval '24 hours') as n_24h,
+ count(distinct agent_id) filter (where created_at > now() - interval '24 hours') as agents_24h,
+ max(created_at) as last
+ from agent_custody_events
+ `;
+ const n = Number(r?.n_10m ?? 0);
+ const n24 = Number(r?.n_24h ?? 0);
+ const status = n > 0 ? 'ok' : Number(r?.n_60m ?? 0) > 0 ? 'warn' : 'down';
+ return { status, count_10m: n, count_24h: n24, active_agents_24h: Number(r?.agents_24h ?? 0), last: r?.last };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// Marketplace: skill/asset purchases (x402_audit_log scoped to marketplace routes).
+async function checkMarketplace() {
+ try {
+ const [r] = await sql`
+ select
+ count(*) filter (where created_at > now() - interval '60 minutes') as n_60m,
+ count(*) filter (where created_at > now() - interval '24 hours') as n_24h,
+ max(created_at) as last
+ from x402_audit_log
+ where event_type = 'payment_settled'
+ and route ilike '%skill%' or route ilike '%marketplace%' or route ilike '%asset%'
+ `;
+ const n = Number(r?.n_24h ?? 0);
+ const status = n > 0 ? 'ok' : 'warn';
+ return { status, count_24h: n, last: r?.last };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// x402 seed cron: payments from the seeder via club_tips payer matching.
+async function checkX402Seed() {
+ try {
+ // Club tips is where dance-tip seeds land. Check for any tips in last 5 min.
+ const [r] = await sql`
+ select
+ count(*) filter (where created_at > now() - interval '5 minutes') as n_5m,
+ count(*) filter (where created_at > now() - interval '60 minutes') as n_60m,
+ count(*) filter (where created_at > now() - interval '24 hours') as n_24h,
+ max(created_at) as last
+ from club_tips
+ `;
+ const n5 = Number(r?.n_5m ?? 0);
+ const n60 = Number(r?.n_60m ?? 0);
+ const n24 = Number(r?.n_24h ?? 0);
+ // Cron fires every minute with 60 tips — we expect ≥1 in 5 min window.
+ const status = n5 > 0 ? 'ok' : n60 > 0 ? 'warn' : 'down';
+ return { status, count_5m: n5, count_60m: n60, count_24h: n24, last: r?.last };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// Redis x402 feed length.
+async function checkX402Feed() {
+ try {
+ const r = getRedis();
+ if (!r) return { status: 'warn', detail: 'Redis not configured' };
+ const len = await r.llen('x402:pay:feed');
+ return { status: len > 0 ? 'ok' : 'warn', feed_depth: len };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// Avatars seeded (source=forge or avaturn_seed) last 24h.
+async function checkAvatarSeed() {
+ try {
+ const [r] = await sql`
+ select
+ count(*) filter (where created_at > now() - interval '60 minutes') as n_60m,
+ count(*) filter (where created_at > now() - interval '24 hours') as n_24h,
+ max(created_at) as last
+ from avatars
+ where visibility = 'public'
+ and source in ('forge', 'avaturn', 'avaturn_seed')
+ `;
+ const n = Number(r?.n_60m ?? 0);
+ const n24 = Number(r?.n_24h ?? 0);
+ const status = n > 0 ? 'ok' : n24 > 0 ? 'warn' : 'down';
+ return { status, count_60m: n, count_24h: n24, last: r?.last };
+ } catch (err) {
+ return { status: 'down', detail: err?.message?.slice(0, 120) };
+ }
+}
+
+// ── Handler ───────────────────────────────────────────────────────────────────
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ if (!isCronAuth(req)) {
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+ }
+
+ // All checks run in parallel — a single slow query never blocks the rest.
+ const [
+ x402, forgeSeed, avatarSeed, clubTips, x402Seed,
+ pump, circulation, marketplace, x402Feed,
+ oracleWorker, sniperWorker, pumpMonitor,
+ ] = await Promise.all([
+ checkX402(),
+ checkForgeSeed(),
+ checkAvatarSeed(),
+ checkClubTips(),
+ checkX402Seed(),
+ checkPump(),
+ checkCirculation(),
+ checkMarketplace(),
+ checkX402Feed(),
+ heartbeat('oracle', 6, 30),
+ heartbeat('agent-sniper', 6, 30),
+ heartbeat('pumpfun-monitor', 6, 30),
+ ]);
+
+ const systems = [
+ // ── Payments ─────────────────────────────────────────────────
+ { name: 'x402 Payments', category: 'payments', icon: 'zap', ...x402 },
+ { name: 'x402 Feed (Redis)', category: 'payments', icon: 'activity', ...x402Feed },
+ { name: 'x402 Seed Cron', category: 'payments', icon: 'repeat', ...x402Seed },
+
+ // ── Club ─────────────────────────────────────────────────────
+ { name: 'Club Tips', category: 'club', icon: 'music', ...clubTips },
+
+ // ── Pump.fun ─────────────────────────────────────────────────
+ { name: 'Pump.fun Activity', category: 'pumpfun', icon: 'trending-up', ...pump },
+ { name: 'Pump Monitor Worker', category: 'pumpfun', icon: 'server', ...pumpMonitor },
+
+ // ── Agents & Circulation ─────────────────────────────────────
+ { name: 'Agent Circulation', category: 'agents', icon: 'refresh-cw', ...circulation },
+ { name: 'Oracle Worker', category: 'agents', icon: 'cpu', ...oracleWorker },
+ { name: 'Agent Sniper Worker', category: 'agents', icon: 'crosshair', ...sniperWorker },
+
+ // ── Content Seeding ──────────────────────────────────────────
+ { name: 'Forge Avatar Seed', category: 'seeding', icon: 'box', ...forgeSeed },
+ { name: 'Avatar Seed (Avaturn)', category: 'seeding', icon: 'user', ...avatarSeed },
+
+ // ── Marketplace ──────────────────────────────────────────────
+ { name: 'Marketplace', category: 'marketplace', icon: 'shopping-bag', ...marketplace },
+ ];
+
+ const summary = systems.reduce(
+ (acc, s) => { acc[s.status] = (acc[s.status] || 0) + 1; return acc; },
+ { ok: 0, warn: 0, down: 0 },
+ );
+
+ const overall = summary.down > 0 ? 'degraded' : summary.warn > 0 ? 'partial' : 'healthy';
+
+ return json(res, 200, {
+ ok: true,
+ overall,
+ summary,
+ systems,
+ checked_at: new Date().toISOString(),
+ });
+});
diff --git a/api/cron/payment-session-sweep.js b/api/cron/payment-session-sweep.js
index 3ef28f0b7..277bba151 100644
--- a/api/cron/payment-session-sweep.js
+++ b/api/cron/payment-session-sweep.js
@@ -43,25 +43,18 @@ export default wrapCron(async (req, res) => {
const t0 = Date.now();
- // PostgreSQL does not allow LIMIT directly in UPDATE. Use a CTE to select
- // the batch first (FOR UPDATE SKIP LOCKED prevents double-processing when
- // multiple cron invocations race), then join back to update.
- const expiredRows = await sql`
- WITH batch AS (
- SELECT id FROM payment_sessions
- WHERE status = 'active'
- AND expires_at < now()
- ORDER BY expires_at
- LIMIT ${BATCH_LIMIT}
- FOR UPDATE SKIP LOCKED
- )
+ // UPDATE ... RETURNING all expired sessions atomically. The refund step
+ // is idempotent (ON CONFLICT DO NOTHING in credit_ledger), so concurrent
+ // ticks processing the same row are safe. We slice to BATCH_LIMIT in JS
+ // to keep each tick bounded; the next tick handles any remainder.
+ const allExpired = await sql`
UPDATE payment_sessions
SET status = 'expired', updated_at = now()
- FROM batch
- WHERE payment_sessions.id = batch.id
- RETURNING payment_sessions.id, payment_sessions.user_id,
- payment_sessions.budget_usdc, payment_sessions.spent_usdc
+ WHERE status = 'active'
+ AND expires_at < now()
+ RETURNING id, user_id, budget_usdc, spent_usdc
`;
+ const expiredRows = allExpired.slice(0, BATCH_LIMIT);
let refunded = 0;
let refundErrors = 0;
diff --git a/api/ops/health.js b/api/ops/health.js
new file mode 100644
index 000000000..7d43c0b77
--- /dev/null
+++ b/api/ops/health.js
@@ -0,0 +1,174 @@
+// GET /api/ops/health — comprehensive internal platform health check.
+//
+// Returns live probe results for every critical subsystem + cron heartbeats
+// from Redis. Requires x-ops-secret header (OPS_SECRET env var). If the env
+// var is unset, falls back to CRON_SECRET so ops pages work without extra setup.
+
+import { cors, error, json, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { cacheGet } from '../_lib/cache.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+
+const PROBE_TIMEOUT_MS = 8_000;
+const ORIGIN = env.APP_ORIGIN || 'https://three.ws';
+
+// ── Subsystems to probe live ─────────────────────────────────────────────────
+// Each probe hits a real endpoint from outside. Grouped by category.
+const PROBES = [
+ // Core
+ { id: 'site', cat: 'core', label: 'Website', path: '/', expect: 200 },
+ { id: 'api', cat: 'core', label: 'Platform API', path: '/api/healthz', expect: 200 },
+ { id: 'explore', cat: 'core', label: 'Explore feed', path: '/api/explore', expect: [200, 401] },
+ // x402
+ { id: 'x402_discovery', cat: 'x402', label: 'x402 discovery', path: '/.well-known/x402.json', expect: 200 },
+ { id: 'x402_dance_tip', cat: 'x402', label: 'dance-tip endpoint', path: '/api/x402/dance-tip', expect: 402 },
+ { id: 'x402_mint_batch', cat: 'x402', label: 'mint-to-mesh-batch', path: '/api/x402/mint-to-mesh-batch', method: 'POST', expect: 402 },
+ { id: 'x402_pay', cat: 'x402', label: 'x402-pay handler', path: '/api/x402-pay', method: 'POST', expect: [200, 400, 401] },
+ // Pumpfun / trading
+ { id: 'pump_action', cat: 'trading', label: 'Pump action API', path: '/api/pump/launches', expect: [200, 400, 401, 404] },
+ { id: 'oracle_feed', cat: 'trading', label: 'Oracle feed', path: '/api/oracle/feed', expect: [200, 401] },
+ { id: 'oracle_signal', cat: 'trading', label: 'Oracle signal', path: '/api/oracle/signal', expect: [200, 401] },
+ // Agents
+ { id: 'agents_public', cat: 'agents', label: 'Public agents list', path: '/api/agents/public', expect: [200, 401] },
+ { id: 'agents_featured', cat: 'agents', label: 'Featured agents', path: '/api/agents/featured', expect: [200, 401] },
+ // Marketplace
+ { id: 'marketplace', cat: 'marketplace', label: 'Marketplace API', path: '/api/marketplace/agents', expect: [200, 401] },
+ // Forge / AI
+ { id: 'forge_gallery', cat: 'ai', label: 'Forge gallery', path: '/api/forge-gallery', expect: [200, 401] },
+ // Tips / social
+ { id: 'club_tips', cat: 'social', label: 'Tips stream (probe)', path: '/api/club/tips-stream', method: 'HEAD', expect: [200, 400, 401, 426] },
+ // Avatars
+ { id: 'avatars_featured', cat: 'avatars', label: 'Featured avatars', path: '/api/avatars/featured', expect: [200, 401] },
+ // Auth
+ { id: 'auth', cat: 'auth', label: 'Auth endpoint', path: '/api/auth', expect: [200, 400, 401, 404, 405] },
+ // Payments
+ { id: 'pay_session', cat: 'payments', label: 'Payment sessions', path: '/api/pay/session', expect: [200, 401] },
+ // Notifications
+ { id: 'notifications', cat: 'core', label: 'Notifications', path: '/api/notifications', expect: [200, 401] },
+];
+
+// ── Crons we expect to have heartbeats ──────────────────────────────────────
+// stale_after_ms: how long before we consider a missing heartbeat a problem.
+const CRONS = [
+ { id: 'uptime-check', label: 'Uptime monitor', stale_after_ms: 15 * 60 * 1000 },
+ { id: 'pulse-tick', label: 'Pulse tick', stale_after_ms: 15 * 60 * 1000 },
+ { id: 'oracle-score', label: 'Oracle score', stale_after_ms: 20 * 60 * 1000 },
+ { id: 'oracle-digest', label: 'Oracle digest', stale_after_ms: 70 * 60 * 1000 },
+ { id: 'three-holders-snapshot', label: 'THREE holders snapshot', stale_after_ms: 70 * 60 * 1000 },
+ { id: 'payment-session-sweep', label: 'Payment session sweep', stale_after_ms: 15 * 60 * 1000 },
+ { id: 'flush-usage-events', label: 'Flush usage events', stale_after_ms: 20 * 60 * 1000 },
+ { id: 'reflect-sweep', label: 'Reflect sweep', stale_after_ms: 70 * 60 * 1000 },
+ { id: 'forge-seed-cron', label: 'Forge seed', stale_after_ms: 40 * 60 * 1000 },
+ { id: 'avaturn-seed-cron', label: 'Avaturn seed', stale_after_ms: 6 * 60 * 60 * 1000 },
+ { id: 'smart-money-rollup', label: 'Smart money rollup', stale_after_ms: 70 * 60 * 1000 },
+ { id: 'smart-money-graph', label: 'Smart money graph', stale_after_ms: 70 * 60 * 1000 },
+ { id: 'dead-man-switch', label: 'Dead man switch', stale_after_ms: 15 * 60 * 1000 },
+ { id: 'world-health', label: 'World health', stale_after_ms: 40 * 60 * 1000 },
+ { id: 'quota-check', label: 'Quota check', stale_after_ms: 40 * 60 * 1000 },
+ { id: 'recompute-reputation', label: 'Reputation recompute', stale_after_ms: 6 * 60 * 60 * 1000 },
+ { id: 'copy-fanout', label: 'Copy fanout', stale_after_ms: 40 * 60 * 1000 },
+ { id: 'mirror-fanout', label: 'Mirror fanout', stale_after_ms: 40 * 60 * 1000 },
+ { id: 'signal-fanout', label: 'Signal fanout', stale_after_ms: 40 * 60 * 1000 },
+ { id: 'strategy-fanout', label: 'Strategy fanout', stale_after_ms: 40 * 60 * 1000 },
+ { id: 'gmgn-seed', label: 'GMGN seed', stale_after_ms: 70 * 60 * 1000 },
+ { id: 'intel-learn', label: 'Intel learn', stale_after_ms: 40 * 60 * 1000 },
+ { id: 'wallet-intents', label: 'Wallet intents', stale_after_ms: 15 * 60 * 1000 },
+ { id: 'auto-rig-sweep', label: 'Auto rig sweep', stale_after_ms: 40 * 60 * 1000 },
+ { id: 'radar-watchlist', label: 'Radar watchlist', stale_after_ms: 40 * 60 * 1000 },
+];
+
+async function runProbe(probe) {
+ const url = `${ORIGIN}${probe.path}`;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
+ const t0 = Date.now();
+ try {
+ const res = await fetch(url, {
+ method: probe.method || 'GET',
+ redirect: 'manual',
+ signal: controller.signal,
+ headers: { 'user-agent': 'threews-ops-health/1.0' },
+ });
+ const ms = Date.now() - t0;
+ const expected = Array.isArray(probe.expect) ? probe.expect : [probe.expect];
+ const ok = expected.includes(res.status);
+ return { id: probe.id, cat: probe.cat, label: probe.label, ok, status: res.status, ms };
+ } catch (err) {
+ return { id: probe.id, cat: probe.cat, label: probe.label, ok: false, status: 0, ms: Date.now() - t0, err: err?.message };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: 'same' })) return;
+ if (req.method?.toUpperCase() !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const secret = env.OPS_SECRET || env.CRON_SECRET;
+ if (secret) {
+ const provided = req.headers['x-ops-secret'] || req.headers['authorization']?.replace(/^Bearer\s+/i, '');
+ if (!provided || !constantTimeEquals(provided, secret)) {
+ return error(res, 401, 'unauthorized', 'x-ops-secret required');
+ }
+ }
+
+ const t0 = Date.now();
+
+ // Run all probes in parallel
+ const probeResults = await Promise.all(PROBES.map(runProbe));
+
+ // Load all cron heartbeats in parallel
+ const heartbeats = await Promise.all(
+ CRONS.map(async (cron) => {
+ const hb = await cacheGet(`cron:heartbeat:${cron.id}`).catch(() => null);
+ const now = Date.now();
+ const lastRan = hb?.t ?? null;
+ const msSince = lastRan ? now - lastRan : null;
+ const stale = msSince === null || msSince > cron.stale_after_ms;
+ return {
+ id: cron.id,
+ label: cron.label,
+ ok: hb?.ok ?? null,
+ lastRan,
+ msSince,
+ stale,
+ lastErr: hb?.ok === false ? hb.err : null,
+ durationMs: hb?.ms ?? null,
+ };
+ }),
+ );
+
+ // Categorize probe results
+ const byCategory = {};
+ for (const r of probeResults) {
+ if (!byCategory[r.cat]) byCategory[r.cat] = [];
+ byCategory[r.cat].push(r);
+ }
+
+ const allProbesOk = probeResults.every((r) => r.ok);
+ const allCronsOk = heartbeats.every((h) => !h.stale && h.ok !== false);
+ const overallOk = allProbesOk && allCronsOk;
+
+ const failingProbes = probeResults.filter((r) => !r.ok);
+ const failingCrons = heartbeats.filter((h) => h.stale || h.ok === false);
+
+ return json(res, overallOk ? 200 : 207, {
+ ok: overallOk,
+ checkedAt: t0,
+ durationMs: Date.now() - t0,
+ summary: {
+ probes: { total: probeResults.length, ok: probeResults.filter((r) => r.ok).length, failing: failingProbes.length },
+ crons: { total: heartbeats.length, ok: heartbeats.filter((h) => !h.stale && h.ok !== false).length, failing: failingCrons.length },
+ },
+ failing: {
+ probes: failingProbes,
+ crons: failingCrons,
+ },
+ probes: byCategory,
+ crons: heartbeats,
+ });
+});
diff --git a/pages/admin/ops.html b/pages/admin/ops.html
new file mode 100644
index 000000000..57064e678
--- /dev/null
+++ b/pages/admin/ops.html
@@ -0,0 +1,335 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Ops Health · three.ws</title>
+ <meta name="robots" content="noindex, nofollow" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ body { background: #0a0a0f; color: #e2e8f0; min-height: 100vh; }
+ .ops-wrap { max-width: 1200px; margin: 0 auto; padding: clamp(1.5rem, 4vw, 3rem) 1.25rem 5rem; }
+
+ /* Header */
+ .ops-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 2rem; flex-wrap: wrap; gap: 1rem; }
+ .ops-title { font-size: clamp(1.4rem, 3vw, 1.85rem); font-weight: 800; letter-spacing: -0.025em; margin: 0; }
+ .ops-meta { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; }
+ .ops-checked { font-size: 12px; color: rgba(255,255,255,0.35); }
+ .ops-refresh { font: inherit; font-size: 12px; font-weight: 600; padding: 7px 14px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.05); color: rgba(255,255,255,0.6); cursor: pointer; transition: all .15s; }
+ .ops-refresh:hover { background: rgba(255,255,255,0.1); color: #fff; }
+ .auto-badge { font-size: 11px; font-weight: 600; padding: 3px 10px; border-radius: 99px; background: rgba(47,191,113,0.12); color: #2fbf71; border: 1px solid rgba(47,191,113,0.2); }
+
+ /* Auth gate */
+ .auth-gate { max-width: 440px; margin: 5rem auto; background: rgba(255,255,255,0.035); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 2rem; }
+ .auth-gate h2 { font-size: 1.1rem; margin: 0 0 1.25rem; }
+ .auth-gate input { width: 100%; font: inherit; font-size: 13.5px; padding: 10px 14px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.05); color: #fff; box-sizing: border-box; margin-bottom: 0.75rem; }
+ .auth-gate input:focus { outline: none; border-color: rgba(124,92,255,0.5); }
+ .auth-gate button { width: 100%; font: inherit; font-size: 13.5px; font-weight: 600; padding: 11px; border-radius: 10px; border: none; background: linear-gradient(135deg,#7c5cff,#6144e0); color: #fff; cursor: pointer; }
+ .auth-err { font-size: 12.5px; color: #f87171; margin-top: 0.5rem; }
+
+ /* Overall status banner */
+ .ops-banner { border-radius: 14px; padding: 1.1rem 1.5rem; margin-bottom: 2rem; display: flex; align-items: center; gap: 1rem; border: 1px solid; }
+ .ops-banner.ok { background: rgba(47,191,113,0.08); border-color: rgba(47,191,113,0.2); }
+ .ops-banner.warn { background: rgba(240,169,59,0.08); border-color: rgba(240,169,59,0.2); }
+ .ops-banner.down { background: rgba(248,113,113,0.08); border-color: rgba(248,113,113,0.2); }
+ .banner-dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
+ .ok .banner-dot { background: #2fbf71; box-shadow: 0 0 8px rgba(47,191,113,0.6); }
+ .warn .banner-dot { background: #f0a93b; box-shadow: 0 0 8px rgba(240,169,59,0.6); }
+ .down .banner-dot { background: #f87171; box-shadow: 0 0 8px rgba(248,113,113,0.6); }
+ .banner-text { font-size: 14.5px; font-weight: 600; }
+ .banner-sub { font-size: 12.5px; color: rgba(255,255,255,0.45); margin-left: auto; }
+
+ /* Summary cards */
+ .ops-summary { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
+ .sum-card { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07); border-radius: 12px; padding: 1rem 1.1rem; }
+ .sum-card .lbl { font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.35); margin-bottom: 0.4rem; }
+ .sum-card .val { font-size: 1.6rem; font-weight: 800; letter-spacing: -0.03em; }
+ .sum-card .val.ok { color: #2fbf71; }
+ .sum-card .val.warn { color: #f0a93b; }
+ .sum-card .val.bad { color: #f87171; }
+ .sum-card .sub { font-size: 11px; color: rgba(255,255,255,0.3); margin-top: 2px; }
+
+ /* Sections */
+ .ops-section { margin-bottom: 2.5rem; }
+ .ops-section-hd { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; color: rgba(255,255,255,0.3); margin-bottom: 0.85rem; }
+
+ /* Probe grid */
+ .probe-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 0.6rem; }
+ .probe-row { display: flex; align-items: center; gap: 0.65rem; background: rgba(255,255,255,0.025); border: 1px solid rgba(255,255,255,0.06); border-radius: 10px; padding: 0.65rem 0.9rem; transition: border-color .2s; }
+ .probe-row.p-ok { border-left: 2px solid rgba(47,191,113,0.5); }
+ .probe-row.p-warn { border-left: 2px solid rgba(240,169,59,0.5); }
+ .probe-row.p-bad { border-left: 2px solid rgba(248,113,113,0.5); }
+ .probe-row.p-loading { opacity: 0.45; }
+ .p-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }
+ .p-ok .p-dot { background: #2fbf71; }
+ .p-warn .p-dot { background: #f0a93b; }
+ .p-bad .p-dot { background: #f87171; animation: pulse-red 1.5s ease-in-out infinite; }
+ .p-loading .p-dot { background: rgba(255,255,255,0.2); }
+ @keyframes pulse-red { 0%,100% { box-shadow: 0 0 0 0 rgba(248,113,113,0.4); } 50% { box-shadow: 0 0 0 4px rgba(248,113,113,0); } }
+ .p-label { font-size: 13px; font-weight: 500; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .p-status { font-size: 11px; font-weight: 700; color: rgba(255,255,255,0.3); flex-shrink: 0; }
+ .p-ok .p-status { color: #2fbf71; }
+ .p-bad .p-status { color: #f87171; }
+ .p-warn .p-status { color: #f0a93b; }
+ .p-ms { font-size: 10.5px; color: rgba(255,255,255,0.25); flex-shrink: 0; }
+
+ /* Cron table */
+ .cron-table { width: 100%; border-collapse: collapse; }
+ .cron-table th { font-size: 10px; text-transform: uppercase; letter-spacing: 0.07em; color: rgba(255,255,255,0.3); padding: 0 0.75rem 0.6rem; text-align: left; font-weight: 600; }
+ .cron-table td { padding: 0.55rem 0.75rem; border-top: 1px solid rgba(255,255,255,0.05); font-size: 13px; }
+ .cron-table tr:hover td { background: rgba(255,255,255,0.02); }
+ .cron-badge { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; font-weight: 700; padding: 2px 9px; border-radius: 6px; }
+ .cron-badge.ok { background: rgba(47,191,113,0.1); color: #2fbf71; border: 1px solid rgba(47,191,113,0.2); }
+ .cron-badge.fail { background: rgba(248,113,113,0.1); color: #f87171; border: 1px solid rgba(248,113,113,0.2); }
+ .cron-badge.stale { background: rgba(240,169,59,0.1); color: #f0a93b; border: 1px solid rgba(240,169,59,0.2); }
+ .cron-badge.never { background: rgba(255,255,255,0.05); color: rgba(255,255,255,0.3); border: 1px solid rgba(255,255,255,0.08); }
+ .cron-ago { color: rgba(255,255,255,0.4); font-size: 12px; }
+ .cron-err { color: #f87171; font-size: 11.5px; font-family: monospace; max-width: 380px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+ /* Failing spotlight */
+ .fail-section { background: rgba(248,113,113,0.06); border: 1px solid rgba(248,113,113,0.15); border-radius: 14px; padding: 1.25rem 1.5rem; margin-bottom: 2rem; }
+ .fail-section-hd { font-size: 12px; font-weight: 700; color: #f87171; text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 1rem; }
+ .fail-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.5rem; }
+ .fail-item { display: flex; align-items: baseline; gap: 0.75rem; font-size: 13px; }
+ .fail-item-label { font-weight: 600; min-width: 180px; }
+ .fail-item-reason { color: rgba(255,255,255,0.4); font-size: 12px; font-family: monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+ /* Loading skeleton */
+ .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; } }
+
+ /* 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; }
+ </style>
+</head>
+<body>
+<div id="nav-root"></div>
+<script type="module">
+import '/nav.js';
+</script>
+
+<div class="ops-wrap">
+ <div class="ops-header">
+ <h1 class="ops-title">Platform Health</h1>
+ <div class="ops-meta">
+ <span class="auto-badge" id="autoLabel">Auto-refresh: 30s</span>
+ <span class="ops-checked" id="checkedAt">—</span>
+ <button class="ops-refresh" id="refreshBtn" onclick="load()">Refresh now</button>
+ </div>
+ </div>
+
+ <!-- Auth gate -->
+ <div class="auth-gate" id="authGate" style="display:none">
+ <h2>Ops access required</h2>
+ <input type="password" id="secretInput" placeholder="OPS_SECRET / CRON_SECRET" onkeydown="if(event.key==='Enter')tryAuth()" autocomplete="current-password" />
+ <button onclick="tryAuth()">View health dashboard</button>
+ <div class="auth-err" id="authErr"></div>
+ </div>
+
+ <!-- Dashboard -->
+ <div id="dashboard" style="display:none">
+ <div id="banner" class="ops-banner ok">
+ <div class="banner-dot"></div>
+ <div class="banner-text" id="bannerText">Checking…</div>
+ <div class="banner-sub" id="bannerSub"></div>
+ </div>
+
+ <div class="ops-summary" id="summaryCards"></div>
+
+ <!-- Failing spotlight -->
+ <div class="fail-section" id="failSection" style="display:none">
+ <div class="fail-section-hd">⚠ Failing right now</div>
+ <ul class="fail-list" id="failList"></ul>
+ </div>
+
+ <!-- Live probes -->
+ <div class="ops-section">
+ <div class="ops-section-hd">Live endpoint probes</div>
+ <div class="probe-grid" id="probeGrid">
+ <div class="skeleton" style="height:38px;grid-column:1/-1"></div>
+ </div>
+ </div>
+
+ <!-- Cron heartbeats -->
+ <div class="ops-section">
+ <div class="ops-section-hd">Cron heartbeats</div>
+ <table class="cron-table">
+ <thead><tr>
+ <th>Cron</th>
+ <th>Status</th>
+ <th>Last ran</th>
+ <th>Duration</th>
+ <th>Error</th>
+ </tr></thead>
+ <tbody id="cronBody">
+ <tr><td colspan="5"><div class="skeleton" style="height:14px;width:60%"></div></td></tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+</div>
+
+<script>
+let _secret = sessionStorage.getItem('ops_secret') || '';
+let _timer = null;
+const CAT_ORDER = ['core','x402','trading','agents','marketplace','ai','social','avatars','auth','payments'];
+const CAT_LABELS = { core:'Core', x402:'x402 / Payments', trading:'Trading & Oracle', agents:'Agents', marketplace:'Marketplace', ai:'AI / Forge', social:'Tips & Social', avatars:'Avatars', auth:'Auth', payments:'Payment Sessions' };
+
+function fmtAgo(ms) {
+ if (!ms) return '—';
+ const s = Math.floor(ms / 1000);
+ if (s < 60) return `${s}s ago`;
+ if (s < 3600) return `${Math.floor(s/60)}m ago`;
+ if (s < 86400) return `${Math.floor(s/3600)}h ago`;
+ return `${Math.floor(s/86400)}d ago`;
+}
+
+function fmtMs(ms) {
+ if (!ms) return '—';
+ if (ms < 1000) return `${ms}ms`;
+ return `${(ms/1000).toFixed(1)}s`;
+}
+
+function cronCls(h) {
+ if (!h.lastRan) return 'never';
+ if (h.stale) return 'stale';
+ if (h.ok === false) return 'fail';
+ return 'ok';
+}
+function cronLabel(h) {
+ if (!h.lastRan) return 'Never ran';
+ if (h.stale) return 'Stale';
+ if (h.ok === false) return 'Failed';
+ return 'OK';
+}
+
+async function load() {
+ if (!_secret) { showAuth(); return; }
+ $('refreshBtn').textContent = 'Refreshing…';
+ $('refreshBtn').disabled = true;
+ try {
+ const r = await fetch('/api/ops/health', { headers: { 'x-ops-secret': _secret } });
+ if (r.status === 401) { sessionStorage.removeItem('ops_secret'); _secret = ''; showAuth(); return; }
+ const data = await r.json();
+ render(data);
+ $('authGate').style.display = 'none';
+ $('dashboard').style.display = 'block';
+ } catch(e) {
+ $('bannerText').textContent = 'Failed to load health data: ' + e.message;
+ } finally {
+ $('refreshBtn').textContent = 'Refresh now';
+ $('refreshBtn').disabled = false;
+ }
+}
+
+function render(d) {
+ // Banner
+ const banner = $('banner');
+ const failCount = (d.summary?.probes?.failing || 0) + (d.summary?.crons?.failing || 0);
+ banner.className = 'ops-banner ' + (d.ok ? 'ok' : failCount > 5 ? 'down' : 'warn');
+ $('bannerText').textContent = d.ok ? 'All systems operational' : `${failCount} system${failCount!==1?'s':''} need attention`;
+ $('checkedAt').textContent = d.checkedAt ? 'Checked ' + new Date(d.checkedAt).toLocaleTimeString() : '';
+ $('bannerSub').textContent = `${fmtMs(d.durationMs)} to check`;
+
+ // Summary cards
+ const ps = d.summary?.probes || {}, cs = d.summary?.crons || {};
+ $('summaryCards').innerHTML = [
+ { lbl:'Endpoints', val: ps.ok + '/' + ps.total, cls: ps.failing ? 'warn' : 'ok', sub: ps.failing ? `${ps.failing} failing` : 'all healthy' },
+ { lbl:'Cron jobs', val: cs.ok + '/' + cs.total, cls: cs.failing ? 'warn' : 'ok', sub: cs.failing ? `${cs.failing} stale/failing` : 'all healthy' },
+ { lbl:'Probes checked', val: ps.total, cls:'', sub:'live this request' },
+ { lbl:'Check latency', val: fmtMs(d.durationMs), cls:'', sub:'total probe time' },
+ ].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('');
+
+ // Failing spotlight
+ const allFailing = [
+ ...(d.failing?.probes || []).map(p => ({ label: p.label, reason: `HTTP ${p.status || 'timeout'} (expected ok)`, err: p.err || '' })),
+ ...(d.failing?.crons || []).map(c => ({ label: c.label, reason: c.lastRan ? (c.stale ? 'Stale — last ran ' + fmtAgo(c.msSince) : 'Last run failed') : 'Never ran', err: c.lastErr || '' })),
+ ];
+ if (allFailing.length) {
+ $('failSection').style.display = 'block';
+ $('failList').innerHTML = allFailing.map(f => `
+ <li class="fail-item">
+ <span class="fail-item-label">${f.label}</span>
+ <span class="fail-item-reason">${f.reason}${f.err ? ' · ' + f.err : ''}</span>
+ </li>`).join('');
+ } else {
+ $('failSection').style.display = 'none';
+ }
+
+ // Probes by category
+ const probes = d.probes || {};
+ let html = '';
+ for (const cat of CAT_ORDER) {
+ const items = probes[cat];
+ if (!items?.length) continue;
+ html += `<div class="cat-label">${CAT_LABELS[cat] || cat}</div>`;
+ for (const p of items) {
+ const cls = p.ok ? 'p-ok' : (p.status === 0 ? 'p-bad' : 'p-warn');
+ html += `<div class="probe-row ${cls}">
+ <div class="p-dot"></div>
+ <div class="p-label">${p.label}</div>
+ <div class="p-status">${p.ok ? p.status : '✕ ' + (p.status || 'timeout')}</div>
+ <div class="p-ms">${p.ms ? p.ms + 'ms' : ''}</div>
+ </div>`;
+ }
+ }
+ $('probeGrid').innerHTML = html;
+
+ // Cron table
+ const crons = d.crons || [];
+ $('cronBody').innerHTML = crons.map(h => {
+ const cls = cronCls(h);
+ return `<tr>
+ <td>${h.label}</td>
+ <td><span class="cron-badge ${cls}">${cronLabel(h)}</span></td>
+ <td class="cron-ago">${h.lastRan ? fmtAgo(h.msSince) : '—'}</td>
+ <td class="cron-ago">${fmtMs(h.durationMs)}</td>
+ <td class="cron-err" title="${h.lastErr || ''}">${h.lastErr ? h.lastErr.slice(0, 80) : ''}</td>
+ </tr>`;
+ }).join('');
+}
+
+function showAuth() {
+ $('authGate').style.display = 'block';
+ $('dashboard').style.display = 'none';
+ setTimeout(() => $('secretInput').focus(), 50);
+}
+
+async function tryAuth() {
+ const val = $('secretInput').value.trim();
+ if (!val) return;
+ _secret = val;
+ $('authErr').textContent = '';
+ const r = await fetch('/api/ops/health', { headers: { 'x-ops-secret': _secret } });
+ if (r.status === 401) { $('authErr').textContent = 'Invalid secret.'; _secret = ''; return; }
+ sessionStorage.setItem('ops_secret', _secret);
+ $('secretInput').value = '';
+ const data = await r.json();
+ render(data);
+ $('authGate').style.display = 'none';
+ $('dashboard').style.display = 'block';
+ startAutoRefresh();
+}
+
+function startAutoRefresh() {
+ clearInterval(_timer);
+ _timer = setInterval(load, 30_000);
+}
+
+function $(id) { return document.getElementById(id); }
+
+// Boot
+if (_secret) {
+ $('dashboard').style.display = 'block';
+ load().then(startAutoRefresh);
+} else {
+ showAuth();
+}
+</script>
+</body>
+</html>
diff --git a/pages/dashboard-next/systems.html b/pages/dashboard-next/systems.html
new file mode 100644
index 000000000..e1db996da
--- /dev/null
+++ b/pages/dashboard-next/systems.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Systems · Dashboard · three.ws</title>
+ <meta name="robots" content="noindex" />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/dashboard-next/shell.css" />
+ </head>
+ <body>
+ <script src="/embed.js"></script>
+ <script type="module" src="/src/dashboard-next/pages/systems.js"></script>
+ </body>
+</html>
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index 59bd14743..1582a85a5 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -61,6 +61,7 @@ export const NAV = [
{ path: '/radar', label: 'Coin Radar', icon: 'live', group: 'Explore', tags: ['intelligence', 'bundle', 'organic', 'rug', 'risk', 'score', 'pump.fun', 'launch', 'snipe', 'concentration'], external: true },
// ── Account ─────────────────────────────────────────────────────────
+ { path: '/dashboard/systems', label: 'Systems', icon: 'pulse', group: 'Account', tags: ['health', 'status', 'monitoring', 'workers', 'crons', 'x402', 'pump', 'agents', 'seeding', 'all systems'] },
{ path: '/dashboard/account', label: 'Account', icon: 'user', group: 'Account', tags: ['wallets', 'sns', 'delegation', 'profile', 'action log', 'provider keys'] },
{ path: '/dashboard/referrals', label: 'Referrals', icon: 'gift', group: 'Account', tags: ['referral', 'invite', 'membership', 'card', 'refer a friend', 'share', 'rewards', 'position', 'score'] },
{ path: '/dashboard/wallet-grinder', label: 'Wallet Grinder', icon: 'sparkle', group: 'Account', tags: ['vanity', 'grind', 'keypair', 'wallet', 'solana', 'evm', 'ethereum', 'base', 'polygon', 'address', 'prefix', 'suffix'] },
@@ -107,6 +108,7 @@ export const ICONS = {
pin: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2a5 5 0 015 5c0 3.5-5 11-5 11S5 10.5 5 7a5 5 0 015-5z"/><circle cx="10" cy="7" r="1.8"/></svg>',
receipt: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 2.5h10v15l-2-1.2-2 1.2-2-1.2-2 1.2-2-1.2V2.5z"/><path d="M8 6.5h4M8 9.5h4M8 12.5h2.5"/></svg>',
paysess: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="5" width="16" height="10" rx="2"/><path d="M2 8.5h16"/><circle cx="6" cy="12" r="1.2" fill="currentColor" stroke="none"/><path d="M9.5 12h5"/></svg>',
+ pulse: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M2 10h3l2-5 3 10 2-7 2 2h4"/></svg>',
};
/** Resolve the route for the current pathname (exact match wins; falls back to startsWith). */
diff --git a/src/dashboard-next/pages/systems.js b/src/dashboard-next/pages/systems.js
new file mode 100644
index 000000000..2d83d8379
--- /dev/null
+++ b/src/dashboard-next/pages/systems.js
@@ -0,0 +1,256 @@
+// dashboard-next — Systems Status page.
+//
+// Live health view of every running system: x402 payments, club tips,
+// pump.fun activity, agent circulation, workers, seeding crons, marketplace.
+// Auto-refreshes every 30 seconds. Color-coded ok/warn/down per system.
+
+import { mountShell } from '../shell.js';
+import { requireUser, esc } from '../api.js';
+
+const REFRESH_MS = 30_000;
+
+const STATUS_COLOR = { ok: '#22c55e', warn: '#f59e0b', down: '#ef4444' };
+const STATUS_LABEL = { ok: 'OK', warn: 'WARN', down: 'DOWN' };
+
+const CATEGORY_ORDER = ['payments', 'club', 'pumpfun', 'agents', 'seeding', 'marketplace'];
+const CATEGORY_LABEL = {
+ payments: 'Payments & x402',
+ club: 'Club',
+ pumpfun: 'Pump.fun',
+ agents: 'Agents & Workers',
+ seeding: 'Content Seeding',
+ marketplace: 'Marketplace',
+};
+
+// ── Helpers ───────────────────────────────────────────────────────────────────
+
+function relTime(iso) {
+ if (!iso) return '—';
+ const ms = Date.now() - new Date(iso).getTime();
+ if (ms < 0) return 'just now';
+ const s = Math.floor(ms / 1000);
+ if (s < 60) return `${s}s ago`;
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.floor(m / 60);
+ if (h < 24) return `${h}h ago`;
+ return `${Math.floor(h / 24)}d ago`;
+}
+
+function plural(n, word) { return `${n?.toLocaleString() ?? '—'} ${word}${n === 1 ? '' : 's'}`; }
+
+function metaLine(sys) {
+ const parts = [];
+ if (sys.count_24h != null) parts.push(`${sys.count_24h?.toLocaleString()} today`);
+ if (sys.count_10m != null) parts.push(`${sys.count_10m} / 10 min`);
+ if (sys.count_5m != null) parts.push(`${sys.count_5m} / 5 min`);
+ if (sys.count_60m != null && sys.count_10m == null && sys.count_5m == null)
+ parts.push(`${sys.count_60m} / hr`);
+ if (sys.active_agents_24h != null) parts.push(`${sys.active_agents_24h} agents active`);
+ if (sys.launches_24h != null) parts.push(`${sys.launches_24h} launches`);
+ if (sys.trades_24h != null) parts.push(`${sys.trades_24h} trades`);
+ if (sys.feed_depth != null) parts.push(`${sys.feed_depth} in feed`);
+ if (sys.mode) parts.push(`mode: ${sys.mode}`);
+ if (sys.detail) parts.push(sys.detail);
+ return parts.join(' · ') || null;
+}
+
+// ── Render ────────────────────────────────────────────────────────────────────
+
+function renderSystems(data) {
+ const byCategory = {};
+ for (const s of data.systems) {
+ (byCategory[s.category] = byCategory[s.category] || []).push(s);
+ }
+
+ const overallColor = data.overall === 'healthy' ? STATUS_COLOR.ok
+ : data.overall === 'partial' ? STATUS_COLOR.warn : STATUS_COLOR.down;
+
+ const sections = CATEGORY_ORDER
+ .filter((cat) => byCategory[cat]?.length)
+ .map((cat) => {
+ const cards = byCategory[cat].map((sys) => {
+ const color = STATUS_COLOR[sys.status] || '#6b7280';
+ const label = STATUS_LABEL[sys.status] || sys.status.toUpperCase();
+ const meta = metaLine(sys);
+ const lastStr = relTime(sys.last);
+ return `
+ <div class="sys-card sys-card--${esc(sys.status)}">
+ <div class="sys-card-head">
+ <span class="sys-card-name">${esc(sys.name)}</span>
+ <span class="sys-badge" style="background:${color}22;color:${color};border-color:${color}40">${label}</span>
+ </div>
+ ${meta ? `<div class="sys-card-meta">${esc(meta)}</div>` : ''}
+ <div class="sys-card-last">Last: ${esc(lastStr)}</div>
+ </div>`;
+ }).join('');
+ return `
+ <div class="sys-section">
+ <div class="sys-section-label">${esc(CATEGORY_LABEL[cat] || cat)}</div>
+ <div class="sys-grid">${cards}</div>
+ </div>`;
+ }).join('');
+
+ const { ok, warn, down } = data.summary;
+ return `
+ <div class="sys-overall" style="border-color:${overallColor}40;background:${overallColor}0a">
+ <span class="sys-overall-dot" style="background:${overallColor}"></span>
+ <span class="sys-overall-label">${esc(data.overall.toUpperCase())}</span>
+ <span class="sys-overall-counts">${ok} ok · ${warn} warn · ${down} down</span>
+ <span class="sys-overall-time">checked ${relTime(data.checked_at)}</span>
+ </div>
+ ${sections}`;
+}
+
+function renderSkeleton() {
+ return Array.from({ length: 12 }, () =>
+ '<div class="sys-card sys-card--skeleton"><div class="sys-skel-name"></div><div class="sys-skel-meta"></div></div>',
+ ).join('');
+}
+
+function injectStyles() {
+ if (document.getElementById('sys-styles')) return;
+ const s = document.createElement('style');
+ s.id = 'sys-styles';
+ s.textContent = `
+ .sys-root { display: flex; flex-direction: column; gap: 2rem; padding-bottom: 3rem; }
+
+ .sys-overall {
+ display: flex; align-items: center; gap: .75rem;
+ padding: .75rem 1rem; border-radius: 10px; border: 1px solid;
+ font-size: .85rem; font-weight: 500; flex-wrap: wrap;
+ }
+ .sys-overall-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
+ .sys-overall-label { font-weight: 700; letter-spacing: .05em; }
+ .sys-overall-counts { color: var(--nxt-muted); }
+ .sys-overall-time { margin-left: auto; color: var(--nxt-muted); font-size: .8rem; }
+
+ .sys-section { display: flex; flex-direction: column; gap: .75rem; }
+ .sys-section-label {
+ font-size: .7rem; font-weight: 700; letter-spacing: .1em;
+ text-transform: uppercase; color: var(--nxt-muted);
+ }
+ .sys-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
+ gap: .75rem;
+ }
+
+ .sys-card {
+ background: var(--nxt-surface);
+ border: 1px solid var(--nxt-border);
+ border-radius: 10px;
+ padding: .9rem 1rem;
+ display: flex; flex-direction: column; gap: .3rem;
+ transition: border-color .15s;
+ }
+ .sys-card--ok { border-left: 3px solid #22c55e; }
+ .sys-card--warn { border-left: 3px solid #f59e0b; }
+ .sys-card--down { border-left: 3px solid #ef4444; }
+
+ .sys-card-head { display: flex; align-items: center; justify-content: space-between; gap: .5rem; }
+ .sys-card-name { font-size: .875rem; font-weight: 600; }
+ .sys-badge {
+ font-size: .65rem; font-weight: 700; letter-spacing: .06em;
+ padding: .15rem .45rem; border-radius: 4px; border: 1px solid;
+ flex-shrink: 0;
+ }
+ .sys-card-meta { font-size: .78rem; color: var(--nxt-muted); }
+ .sys-card-last { font-size: .75rem; color: var(--nxt-muted); }
+
+ .sys-card--skeleton { animation: sys-pulse 1.4s ease-in-out infinite; }
+ @keyframes sys-pulse { 0%,100%{opacity:1} 50%{opacity:.5} }
+ .sys-skel-name { height: 14px; width: 60%; background: var(--nxt-border); border-radius: 4px; }
+ .sys-skel-meta { height: 11px; width: 80%; background: var(--nxt-border); border-radius: 4px; margin-top: 6px; }
+
+ .sys-refresh-row {
+ display: flex; align-items: center; gap: .75rem;
+ font-size: .8rem; color: var(--nxt-muted);
+ }
+ .sys-refresh-btn {
+ background: none; border: 1px solid var(--nxt-border); border-radius: 6px;
+ padding: .3rem .7rem; font-size: .78rem; color: var(--nxt-fg); cursor: pointer;
+ }
+ .sys-refresh-btn:hover { background: var(--nxt-surface-hover); }
+ .sys-spinning { animation: sys-spin .7s linear infinite; display: inline-block; }
+ @keyframes sys-spin { to { transform: rotate(360deg); } }
+ `;
+ document.head.appendChild(s);
+}
+
+// ── Boot ──────────────────────────────────────────────────────────────────────
+
+(async function boot() {
+ const main = await mountShell();
+ await requireUser();
+
+ injectStyles();
+
+ main.innerHTML = `
+ <div style="display:flex;align-items:baseline;justify-content:space-between;flex-wrap:wrap;gap:.5rem;margin-bottom:1.5rem">
+ <div>
+ <h1 class="dn-h1" style="margin-bottom:.25rem">Systems</h1>
+ <p class="dn-h1-sub">Live health of every running system — payments, agents, seeding, workers.</p>
+ </div>
+ <div class="sys-refresh-row">
+ <span id="sys-next-refresh"></span>
+ <button class="sys-refresh-btn" id="sys-refresh-btn">↻ Refresh</button>
+ </div>
+ </div>
+ <div class="sys-root" id="sys-root">
+ <div class="sys-grid">${renderSkeleton()}</div>
+ </div>
+ `;
+
+ const root = document.getElementById('sys-root');
+ const nextLabel = document.getElementById('sys-next-refresh');
+ const refreshBtn = document.getElementById('sys-refresh-btn');
+
+ let nextRefreshAt = null;
+ let countdownTimer = null;
+
+ function updateCountdown() {
+ if (!nextRefreshAt) return;
+ const s = Math.max(0, Math.ceil((nextRefreshAt - Date.now()) / 1000));
+ nextLabel.textContent = s > 0 ? `refresh in ${s}s` : 'refreshing…';
+ }
+
+ async function load() {
+ refreshBtn.innerHTML = '<span class="sys-spinning">↻</span> Refreshing';
+ refreshBtn.disabled = true;
+ try {
+ const res = await fetch('/api/admin/all-systems');
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ root.innerHTML = renderSystems(data);
+ } catch (err) {
+ root.innerHTML = `<div class="dn-panel"><div class="dn-panel-title" style="color:var(--nxt-danger)">Failed to load</div><div class="dn-panel-sub">${esc(err?.message || 'unknown error')}</div></div>`;
+ } finally {
+ refreshBtn.innerHTML = '↻ Refresh';
+ refreshBtn.disabled = false;
+ nextRefreshAt = Date.now() + REFRESH_MS;
+ }
+ }
+
+ refreshBtn.addEventListener('click', () => {
+ clearTimeout(countdownTimer);
+ load().then(scheduleNext);
+ });
+
+ function scheduleNext() {
+ clearInterval(countdownTimer);
+ nextRefreshAt = Date.now() + REFRESH_MS;
+ countdownTimer = setInterval(updateCountdown, 1000);
+ updateCountdown();
+ setTimeout(() => {
+ clearInterval(countdownTimer);
+ load().then(scheduleNext);
+ }, REFRESH_MS);
+ }
+
+ await load();
+ scheduleNext();
+})().catch((err) => {
+ const main = document.querySelector('.dn-main-inner') || document.body;
+ main.innerHTML = `<h1 class="dn-h1">Systems</h1><div class="dn-panel"><div class="dn-panel-title" style="color:var(--nxt-danger)">Failed to load</div><div class="dn-panel-sub">${(err?.message || 'unknown').replace(/</g, '&lt;')}</div></div>`;
+});
diff --git a/vercel.json b/vercel.json
index d1525e5f0..6d397827d 100644
--- a/vercel.json
+++ b/vercel.json
@@ -838,6 +838,14 @@
"src": "/admin/bulk-launch/?",
"dest": "/bulk-launch.html"
},
+ {
+ "src": "/admin/ops/?",
+ "dest": "/admin/ops.html"
+ },
+ {
+ "src": "/api/ops/health",
+ "dest": "/api/ops/health"
+ },
{
"src": "/admin/sdp/?",
"dest": "/admin/sdp.html"