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(agent-sniper): implement UI automation scripts for agent creation and login
nrpoa97c6ac41d5d
diff --git a/api/_lib/agent-strategy-runtime.js b/api/_lib/agent-strategy-runtime.jsindex cd228927e..bfb3746a3 100644--- a/api/_lib/agent-strategy-runtime.js+++ b/api/_lib/agent-strategy-runtime.js@@ -31,6 +31,7 @@ import { assessTradeSafety, recordFirewallDecision } from './trade-firewall.js';import { logAudit } from './audit.js';import { cacheSet } from './cache.js';import { WSOL_MINT } from './pump-trade-args.js';+import { pushGuardEvent } from './feed.js';import {getSpendLimits, getTradeLimits, enforceSpendLimit, SpendLimitError, lamportsToUsd,getDailySpendLamports, updateCustodyEvent,@@ -360,6 +361,16 @@ async function evaluateEntries({ equip, agent, launches, nowMs, maxEntries = 3 }results.push({ mint: launch.mint, action: 'entry', ...result, reasons: verdict.reasons });+ // Surface a SAFETY refusal (mayhem coin, rug/honeypot firewall) on the+ // public live tape — the platform declining a bad buy is a trust signal+ // worth showing, not hiding. Routine skips (cooldown, cap) stay quiet.+ if (result.status === 'skipped' && (result.code === 'mayhem' || result.code === 'firewall_blocked')) {+ pushGuardEvent({+ actor: agent.name, agentId: agent.id, mint: launch.mint, reason: result.code,+ label: result.code === 'mayhem' ? 'skipped a pump.fun mayhem coin' : 'blocked a buy at the rug/honeypot firewall',+ });+ }+if (result.status === 'executed' || result.status === 'unconfirmed') {const entryLamports = result.quote ? result.quote.inAtomics : null;const baseAmount = result.quote ? result.quote.outAtomics : null;diff --git a/api/_lib/balances.js b/api/_lib/balances.jsindex f117fc1b8..0a1c99a0c 100644--- a/api/_lib/balances.js+++ b/api/_lib/balances.js@@ -69,11 +69,34 @@ function warnThrottled(category, msg) {// re-discovers the exhausted quota once, then skips for the window.const HELIUS_QUOTA_COOLDOWN_MS = 10 * 60_000;let heliusCooldownUntil = 0; // epoch ms; 0 = available+let heliusQuotaTrips = 0; // cumulative since cold start — trend for /healthzfunction heliusAvailable(now = Date.now()) {return heliusCooldownUntil <= now;}+/**+ * Point-in-time health of the Helius balance-RPC breaker, for /healthz and the+ * status page. Pure read of module state. `degraded` means we're currently in a+ * quota cooldown and serving balances from the public RPC — functional, but the+ * premium path is throttled. No key configured is reported as `configured:false`,+ * not a degradation (the public-RPC path is the intended fallback).+ * @returns {{ configured: boolean, available: boolean, degraded: boolean,+ * cooldownRemainingMs: number, quotaTripsSinceStart: number }}+ */+export function heliusHealth() {+ const now = Date.now();+ const configured = !!heliusRpc();+ const available = heliusAvailable(now);+ return {+ configured,+ available,+ degraded: configured && !available,+ cooldownRemainingMs: available ? 0 : heliusCooldownUntil - now,+ quotaTripsSinceStart: heliusQuotaTrips,+ };+}+// True when an upstream error is a quota/rate-limit signal (vs. a transient blip// worth retrying). Covers Helius's -32429 "max usage reached", a bare HTTP 429,// and generic "quota/usage limit exceeded" bodies.@@ -84,6 +107,7 @@ function isQuotaError(err) {function tripHeliusCooldown(err, category) {heliusCooldownUntil = Date.now() + HELIUS_QUOTA_COOLDOWN_MS;+ heliusQuotaTrips++;warnThrottled(category,`[balances] helius quota/rate-limited — skipping it for ${Math.round(HELIUS_QUOTA_COOLDOWN_MS / 60_000)}min, using public RPC: ${err?.message}`,@@ -93,6 +117,7 @@ function tripHeliusCooldown(err, category) {/** Test seam: reset the Helius breaker + warn throttle between cases. */export function __resetBalancesBreaker() {heliusCooldownUntil = 0;+ heliusQuotaTrips = 0;_warnedAt.clear();}diff --git a/api/_lib/cache.js b/api/_lib/cache.jsindex 5a90ebb57..3fc313662 100644--- a/api/_lib/cache.js+++ b/api/_lib/cache.js@@ -141,6 +141,15 @@ const SET_SUPPRESS_MS = 60_000;let setFailures = 0;let setSuppressedUntil = 0; // epoch ms; 0 = writing normally+// Cumulative counters since this instance came up. Gauges (circuitOpen,+// setSuppressed) say "is it degraded right now"; these totals give the health+// snapshot in api/cron/uptime-check.js a trend to graph and let /healthz report+// "how bad has it been this instance's lifetime" — the texture a single point-in-+// time read can't show. Reset only on cold start, which is honest: a serverless+// instance's counter IS its lifetime.+let totalSetFailures = 0;+let totalCircuitOpens = 0;+// Thrown when the circuit is open. Callers treat it as a normal cache miss but// skip the per-request warning, since the open/close transitions log once each.class CircuitOpenError extends Error {@@ -176,6 +185,7 @@ function circuitRecordFailure() {circuitFailures++;if (circuitFailures >= CIRCUIT_FAIL_THRESHOLD) {circuitOpenUntil = Date.now() + CIRCUIT_COOLDOWN_MS;+ totalCircuitOpens++;warnThrottled('circuit',`[cache] redis degraded — circuit opened for ${CIRCUIT_COOLDOWN_MS / 1000}s after ${circuitFailures} consecutive failures; serving from memory`,@@ -304,6 +314,7 @@ export async function cacheSet(key, value, ttlSeconds = 60) {return;}setFailures++;+ totalSetFailures++;if (setFailures >= SET_FAIL_THRESHOLD) {setSuppressedUntil = now + SET_SUPPRESS_MS;warnThrottled(@@ -330,6 +341,37 @@ export function cacheBackend() {return redisConfigured() ? 'upstash' : 'memory';}+/**+ * Point-in-time health of the cache adapter, for /healthz and the status page.+ * Pure read of module state — no I/O. `degraded` is true whenever Redis is+ * configured but we're currently short-circuiting to memory (breaker open or+ * SET-suppression active), which is the exact production condition the log+ * export surfaced. When no Redis is configured we report the in-memory backend+ * as healthy (that's the intended dev/test posture, not a degradation).+ * @returns {{ backend: string, configured: boolean, degraded: boolean,+ * circuitOpen: boolean, circuitReopensInMs: number, setSuppressed: boolean,+ * consecutiveFailures: number, consecutiveSetFailures: number,+ * totalSetFailures: number, totalCircuitOpens: number }}+ */+export function cacheHealth() {+ const now = Date.now();+ const configured = redisConfigured();+ const circuitOpen = circuitOpenUntil !== 0 && now < circuitOpenUntil;+ const setSuppressed = setSuppressedUntil !== 0 && now < setSuppressedUntil;+ return {+ backend: cacheBackend(),+ configured,+ degraded: configured && (circuitOpen || setSuppressed),+ circuitOpen,+ circuitReopensInMs: circuitOpen ? circuitOpenUntil - now : 0,+ setSuppressed,+ consecutiveFailures: circuitFailures,+ consecutiveSetFailures: setFailures,+ totalSetFailures,+ totalCircuitOpens,+ };+}+/*** Best-effort cross-instance lock built on Redis `SET key val NX EX`. Returns* true if THIS caller acquired the lock, false if someone else holds it. Use todiff --git a/api/_lib/feed.js b/api/_lib/feed.jsindex 45506c13b..64e6250a3 100644--- a/api/_lib/feed.js+++ b/api/_lib/feed.js@@ -56,6 +56,7 @@ export const ALLOWED_TYPES = new Set(['payment', // skill/service payment confirmed; { usdcAtomic, recipientLabel, txSig, explorerUrl }'mission-complete', // /play job or co-op heist finished; { mission, gold, coop, coin }'member-join', // a person signed in to three.ws; { handle } (actor = display name)+ 'agent-guard', // an autonomous buy was REFUSED by a safety rule; { agentId, mint, reason, label } — trust made visible// Agora — the living agent economy (workers/agora-citizens). Each is a real// on-chain AgenC action projected onto the ticker; see docs/agora.md.'agora-registered', // a citizen registered on AgenC@@ -146,6 +147,31 @@ export async function publishFeedEvent(event) {* @param {string} [opts.txSig] Solana tx signature* @param {string} [opts.explorerUrl] full Solscan/explorer URL*/+/**+ * Convenience wrapper: publish an 'agent-guard' event when a safety rule refuses+ * an autonomous buy (a mayhem-mode coin, a rug/honeypot firewall block). Surfacing+ * these makes the platform's safety work visible in the live tape instead of+ * silent. Fire-and-forget; unknown/empty input is a safe no-op.+ *+ * @param {object} opts+ * @param {string} opts.actor the agent's display name+ * @param {string} [opts.agentId]+ * @param {string} [opts.mint] the coin that was refused+ * @param {string} opts.reason machine code ('mayhem' | 'firewall_blocked')+ * @param {string} opts.label human-readable one-liner for the tape+ */+export function pushGuardEvent({ actor, agentId, mint, reason, label } = {}) {+ if (!reason) return null;+ return publishFeedEvent({+ type: 'agent-guard',+ actor: String(actor || 'Agent').slice(0, 32),+ agentId: agentId ? String(agentId).slice(0, 64) : undefined,+ mint: mint ? String(mint).slice(0, 64) : undefined,+ reason: String(reason).slice(0, 32),+ label: label ? String(label).slice(0, 80) : undefined,+ });+}+export function pushPaymentEvent({ actor, usdcAtomic, recipientLabel, txSig, explorerUrl } = {}) {return publishFeedEvent({type: 'payment',diff --git a/api/_lib/launcher-funding.js b/api/_lib/launcher-funding.jsindex 379112a50..350b3bb60 100644--- a/api/_lib/launcher-funding.js+++ b/api/_lib/launcher-funding.js@@ -77,6 +77,59 @@ export async function dailySpentSol(scope, userId = null) {return Number(row?.spent || 0);}+// Optional hard ceiling on how much SOL may leave the master wallet PER UTC DAY,+// summed across every automated funder — enforced inside fundAgentForLaunch+// regardless of the per-call caps a caller passes. This is the backstop that a+// caller passing `dailyCapSol: null` (or a runaway loop) can't bypass. Opt-in:+// unset ⇒ no master cap (legacy behaviour). Set LAUNCHER_MASTER_DAILY_CAP_SOL to+// bound total master outflow.+const MASTER_DAILY_CAP_ENV = 'LAUNCHER_MASTER_DAILY_CAP_SOL';++/**+ * Pure cap check — extracted so the arithmetic is unit-testable. `capSol<=0`+ * (or non-finite) means "no cap".+ * @param {number} spentSol SOL already moved from the master today+ * @param {number} amountSol the transfer about to be made+ * @param {number} capSol the daily ceiling+ * @returns {{ ok: boolean, reason?: string }}+ */+export function withinMasterDailyCap(spentSol, amountSol, capSol) {+ if (!Number.isFinite(capSol) || capSol <= 0) return { ok: true };+ if (spentSol + amountSol > capSol + 1e-9) {+ return { ok: false, reason: `master_daily_cap: ${spentSol.toFixed(4)}+${amountSol} SOL > ${capSol} SOL/day` };+ }+ return { ok: true };+}++/**+ * SOL that has left the master wallet today (UTC) via the app's automated+ * funders. Sums the two known on-chain ledgers — launcher runs and sniper+ * wallet top-ups — and FAILS OPEN per-source (a missing table in some env+ * contributes 0 rather than throwing), so this can never break a funding call.+ * @param {'mainnet'|'devnet'} network+ * @returns {Promise<number>}+ */+export async function masterDailyOutflowSol(network = 'mainnet') {+ let total = 0;+ try {+ const [r] = await sql`+ select coalesce(sum(sol_spent), 0)::float8 as s from launcher_runs+ where status in ('funded', 'launched', 'confirmed')+ and created_at >= date_trunc('day', now())+ `;+ total += Number(r?.s || 0);+ } catch { /* launcher_runs absent in this env — fail open on this source */ }+ try {+ const [r] = await sql`+ select coalesce(sum(lamports), 0)::float8 / 1e9 as s from sniper_funding_events+ where mode = 'live' and network = ${network}+ and created_at >= date_trunc('day', now())+ `;+ total += Number(r?.s || 0);+ } catch { /* sniper_funding_events absent in this env — fail open on this source */ }+ return total;+}+/*** @typedef {Object} FundResult* @property {boolean} ok@@ -119,6 +172,15 @@ export async function fundAgentForLaunch({return { ok: false, reason: `daily SOL cap reached (${dailyCapSol} remaining)` };}+ // Hard master-wide daily outflow ceiling — independent of the caller's caps, so+ // a null/loose per-call cap can't drain the master. Opt-in via env; no-op unset.+ const masterCapSol = Number(process.env[MASTER_DAILY_CAP_ENV]);+ if (Number.isFinite(masterCapSol) && masterCapSol > 0) {+ const outflow = await masterDailyOutflowSol(network);+ const capCheck = withinMasterDailyCap(outflow, amount, masterCapSol);+ if (!capCheck.ok) return { ok: false, reason: capCheck.reason };+ }+const master = await loadMasterSigner();if (!master) return { ok: false, reason: 'master launch wallet not configured' };diff --git a/api/_lib/migrations/20260703120000_sniper_autofund_consent.sql b/api/_lib/migrations/20260703120000_sniper_autofund_consent.sqlnew file mode 100644index 000000000..e38e667ee--- /dev/null+++ b/api/_lib/migrations/20260703120000_sniper_autofund_consent.sql@@ -0,0 +1,17 @@+-- Explicit per-strategy funding consent for the sniper auto-funder.+--+-- Before this, merely having an enabled mainnet strategy row made the agent's+-- wallet eligible for auto top-ups from the launcher master (workers/agent-sniper/+-- auto-funder.js). That is an implicit fund-moving trigger: arming a strategy+-- silently authorized real SOL to leave a master wallet on the next 5-minute+-- tick. This column makes that consent explicit and OFF by default — arming a+-- strategy no longer moves any money; the operator must opt each strategy in.+--+-- Fail-safe: the worker treats a missing/false value as "do not fund", so until+-- a strategy is explicitly opted in, the auto-funder leaves it alone.++ALTER TABLE agent_sniper_strategies+ ADD COLUMN IF NOT EXISTS auto_fund_enabled boolean NOT NULL DEFAULT false;++COMMENT ON COLUMN agent_sniper_strategies.auto_fund_enabled IS+ 'Explicit consent: when true, the sniper auto-funder may top this agent''s wallet up from the launcher master (bounded by SNIPER_AUTO_FUND_* caps). Default false — arming a strategy never moves money on its own.';diff --git a/api/_lib/ops/subsystem-health.js b/api/_lib/ops/subsystem-health.jsnew file mode 100644index 000000000..abf8a4cea--- /dev/null+++ b/api/_lib/ops/subsystem-health.js@@ -0,0 +1,234 @@+// @ts-check+// Platform subsystem health — the single gatherer that answers "is the platform+// actually healthy right now?" beyond "did the endpoint return 200".+//+// The uptime monitor (api/cron/uptime-check.js) probes public-surface+// REACHABILITY. That's necessary but not sufficient: a surface can answer 200+// while Redis is on memory-fallback, the x402 ring is half-armed, Helius is in+// quota cooldown, or world.three.ws is unprotected — every one of these was+// live in the 2026-07-03 production log export yet invisible to a reachability+// probe. This module reads the in-process degradation state each subsystem+// already tracks (cache circuit breaker, Helius breaker, ring invariants) plus a+// live DB ping and the world-health cron's parked outcome, and rolls them into+// one structured verdict.+//+// Consumed by:+// - api/healthz.js → `subsystems` block (live, per-request)+// - api/status.js → public status feed + /status page+// - api/cron/uptime-check.js → rolling health snapshots + escalation digest+//+// Every check is defensive: a check that throws becomes `unknown`, never an+// exception into the caller. Reads are cheap (module-state gauges + one DB ping),+// so this is safe on a per-request path.+//+// Status vocabulary:+// ok — healthy.+// degraded — functional but running on a fallback / throttled path.+// down — not functional (a hard dependency is unreachable).+// paused — intentionally off (an operator switch), not a fault.+// unknown — no signal yet (a cron hasn't reported, a probe was skipped).+// Only `degraded` and `down` count against the overall roll-up; `paused` and+// `unknown` are surfaced but neutral.++import { cacheHealth, cacheGet } from '../cache.js';+import { heliusHealth } from '../balances.js';+import { checkRingInvariants } from '../x402/ring-allowlist.js';++const DB_PING_TIMEOUT_MS = 2_500;+const DB_SLOW_MS = 1_000;+const WORLD_HEALTH_CACHE_KEY = 'world:health';+// A parked world-health outcome older than this is treated as stale/unknown+// rather than trusted — the 15-min cron should refresh it well within the window.+const WORLD_STALE_MS = 90 * 60 * 1000;++/** Statuses that pull the overall roll-up down, worst first. */+const UNHEALTHY = ['down', 'degraded'];++function worstOf(statuses) {+ if (statuses.includes('down')) return 'down';+ if (statuses.includes('degraded')) return 'degraded';+ return 'ok';+}++// ── Individual subsystem checks. Each returns a subsystem record and never+// throws; a failure to determine state resolves to `unknown`. ──────────────++async function checkDatabase() {+ const base = { name: 'database', label: 'Database (Neon)' };+ try {+ const { sql } = await import('../db.js');+ const started = Date.now();+ await Promise.race([+ sql`SELECT 1`,+ new Promise((_, reject) =>+ setTimeout(() => reject(new Error('db ping exceeded deadline')), DB_PING_TIMEOUT_MS),+ ),+ ]);+ const ms = Date.now() - started;+ if (ms >= DB_SLOW_MS) {+ return { ...base, status: 'degraded', detail: `slow ping: ${ms}ms`, latencyMs: ms, hint: 'Neon compute may be saturated or cold — check the pooler and compute size.' };+ }+ return { ...base, status: 'ok', detail: `ping ${ms}ms`, latencyMs: ms };+ } catch (err) {+ return {+ ...base,+ status: 'down',+ detail: err?.message || 'ping failed',+ hint: 'DATABASE_URL missing/rotated or Neon compute suspended. Audit writes and reads fail until restored.',+ };+ }+}++function checkCache() {+ const base = { name: 'cache', label: 'Cache (Upstash Redis)' };+ try {+ const h = cacheHealth();+ if (!h.configured) {+ return { ...base, status: 'ok', detail: 'in-memory (no Redis configured)', backend: h.backend };+ }+ if (h.degraded) {+ const why = h.circuitOpen+ ? `circuit open, reopens in ${Math.round(h.circuitReopensInMs / 1000)}s`+ : 'SET writes suppressed';+ return {+ ...base,+ status: 'degraded',+ detail: `${why}; serving from memory (${h.totalSetFailures} SET fails, ${h.totalCircuitOpens} opens since start)`,+ backend: h.backend,+ metrics: { totalSetFailures: h.totalSetFailures, totalCircuitOpens: h.totalCircuitOpens },+ hint: 'Upstash is timing out — use a same-region cache store or raise CACHE_REDIS_CMD_TIMEOUT_MS. Reads keep serving.',+ };+ }+ return { ...base, status: 'ok', detail: `upstash healthy`, backend: h.backend, metrics: { totalSetFailures: h.totalSetFailures, totalCircuitOpens: h.totalCircuitOpens } };+ } catch (err) {+ return { ...base, status: 'unknown', detail: err?.message || 'unreadable' };+ }+}++function checkHelius() {+ const base = { name: 'helius', label: 'Helius RPC (balances)' };+ try {+ const h = heliusHealth();+ if (!h.configured) {+ return { ...base, status: 'ok', detail: 'public RPC (no Helius key)' };+ }+ if (h.degraded) {+ return {+ ...base,+ status: 'degraded',+ detail: `quota cooldown ${Math.round(h.cooldownRemainingMs / 60_000)}min left; on public RPC (${h.quotaTripsSinceStart} trips since start)`,+ metrics: { quotaTripsSinceStart: h.quotaTripsSinceStart },+ hint: 'Helius plan quota exhausted — raise the plan/quota. Balances still serve from the public RPC.',+ };+ }+ return { ...base, status: 'ok', detail: 'premium RPC healthy', metrics: { quotaTripsSinceStart: h.quotaTripsSinceStart } };+ } catch (err) {+ return { ...base, status: 'unknown', detail: err?.message || 'unreadable' };+ }+}++function checkRing() {+ const base = { name: 'x402_ring', label: 'x402 autonomous ring' };+ try {+ // An explicit operator pause is a chosen state, not a fault — report it as+ // `paused` so it's visible without dragging the platform to "degraded".+ if (process.env.X402_AUTONOMOUS_ENABLED === 'false') {+ return { ...base, status: 'paused', detail: 'spend loop paused (X402_AUTONOMOUS_ENABLED=false)' };+ }+ const { ok, violations } = checkRingInvariants();+ if (ok) {+ return { ...base, status: 'ok', detail: 'armed; closed-loop guards satisfied' };+ }+ // Enabled but guards unsatisfied: the loop fails CLOSED (no spend) and this+ // is the half-armed config the log export surfaced. Degraded, not down —+ // nothing is broken, money simply isn't moving.+ return {+ ...base,+ status: 'degraded',+ detail: `half-armed — guards unset: ${violations.map((v) => v.flag).join(', ')}`,+ hint: 'Set X402_AUTONOMOUS_ENABLED=false to pause cleanly, or finish the ring guard env to go live. See docs/ops/production-log-triage.md.',+ };+ } catch (err) {+ return { ...base, status: 'unknown', detail: err?.message || 'unreadable' };+ }+}++async function checkWorld() {+ const base = { name: 'world', label: 'world.three.ws (Hyperfy)' };+ try {+ const parked = await cacheGet(WORLD_HEALTH_CACHE_KEY);+ if (!parked || typeof parked !== 'object') {+ return { ...base, status: 'unknown', detail: 'no world-health report yet' };+ }+ const age = parked.checkedAt ? Date.now() - parked.checkedAt : Infinity;+ if (age > WORLD_STALE_MS) {+ return { ...base, status: 'unknown', detail: 'world-health report is stale' };+ }+ if (parked.protected === false) {+ return {+ ...base,+ status: 'degraded',+ detail: 'UNPROTECTED — ADMIN_CODE not set; every visitor has build rights',+ hint: 'Set ADMIN_CODE on the world service and re-run deploy/world/apply-hardening.sh.',+ };+ }+ if (parked.status === 'degraded') {+ return { ...base, status: 'degraded', detail: (parked.problems || []).join('; ') || 'degraded' };+ }+ return { ...base, status: 'ok', detail: 'protected; assets present' };+ } catch (err) {+ return { ...base, status: 'unknown', detail: err?.message || 'unreadable' };+ }+}++function checkX402Config() {+ const base = { name: 'x402_config', label: 'x402 payment config' };+ try {+ const hasSolanaPayTo = !!process.env.X402_PAY_TO_SOLANA || !!process.env.X402_PAY_TO;+ const hasSolanaFeePayer = !!process.env.X402_FEE_PAYER_SOLANA;+ if (hasSolanaPayTo && !hasSolanaFeePayer) {+ return {+ ...base,+ status: 'degraded',+ detail: 'X402_PAY_TO_SOLANA set without X402_FEE_PAYER_SOLANA — Solana accepts are dropped',+ hint: 'Set X402_FEE_PAYER_SOLANA or Solana-only paid endpoints (dance-tip, club-cover) fail closed.',+ };+ }+ const configured = !!process.env.X402_PAY_TO_BASE || (hasSolanaPayTo && hasSolanaFeePayer);+ if (!configured) {+ return { ...base, status: 'unknown', detail: 'no pay-to addresses configured' };+ }+ return { ...base, status: 'ok', detail: 'pay-to + fee payer configured' };+ } catch (err) {+ return { ...base, status: 'unknown', detail: err?.message || 'unreadable' };+ }+}++/**+ * Gather every subsystem's health and roll it into one verdict.+ * @param {{ probeDb?: boolean }} [opts] set probeDb:false to skip the live DB+ * ping (e.g. a caller that already knows the DB is out and wants a fast read).+ * @returns {Promise<{ status: 'ok'|'degraded'|'down', checkedAt: number,+ * counts: Record<string, number>, degraded: string[], subsystems: Array<object> }>}+ */+export async function gatherSubsystemHealth({ probeDb = true } = {}) {+ const checks = [+ probeDb ? checkDatabase() : Promise.resolve({ name: 'database', label: 'Database (Neon)', status: 'unknown', detail: 'ping skipped' }),+ Promise.resolve(checkCache()),+ Promise.resolve(checkHelius()),+ Promise.resolve(checkRing()),+ checkWorld(),+ Promise.resolve(checkX402Config()),+ ];+ const subsystems = await Promise.all(checks);++ const counts = subsystems.reduce((acc, s) => {+ acc[s.status] = (acc[s.status] || 0) + 1;+ return acc;+ }, /** @type {Record<string, number>} */ ({}));++ const status = worstOf(subsystems.map((s) => s.status));+ const degraded = subsystems.filter((s) => UNHEALTHY.includes(s.status)).map((s) => s.name);++ return { status, checkedAt: Date.now(), counts, degraded, subsystems };+}diff --git a/api/_lib/x402/audit-log.js b/api/_lib/x402/audit-log.jsindex c7feb8a87..ba1ae081e 100644--- a/api/_lib/x402/audit-log.js+++ b/api/_lib/x402/audit-log.js@@ -18,6 +18,22 @@import { sql } from '../db.js';import { withDbRetry } from '../db-retry.js';+import { getRedis, isRedisAuthError } from '../redis.js';++// ── Redis write buffer ────────────────────────────────────────────────────────+// The hot paid routes (e.g. /api/x402/dance-tip) queue one audit write PER+// request. Firing each as its own Neon HTTP fetch turned a slow-DB spell into a+// self-amplifying storm: dozens of concurrent single-row INSERTs pile onto an+// already-saturated Neon and every one blows the deadline (the production log+// export this fixes). So writes are coalesced into a Redis list and drained by a+// batch flusher (flushAuditBuffer) off the request path — the same buffer→cron+// pattern the usage-event pipeline already uses (api/_lib/usage.js). One flush+// does a single multi-row INSERT instead of N fetches, so DB load scales with+// flush cadence, not request rate. When Redis is absent/down we fall back to the+// original bounded direct insert so nothing silently stops being logged.+const BUFFER_KEY = 'x402:audit:buffer';+const BUFFER_MAX = 20_000; // safety cap — trim oldest if the flusher falls behind+const BUFFER_TTL_S = 7200; // 2h — a row should never sit buffered this long// This is best-effort telemetry on a fire-and-forget path: the payment has// already been decided and the response sent by the time this runs. So a write@@ -80,37 +96,157 @@ function logAuditFailure(event, err) {* @param {object|null} [event.metadata] — small JSON blob*/export function logPaymentEvent(event) {+ // Intentionally not awaited by callers; the payment is already decided and the+ // response sent by the time this runs. Failures are swallowed.queueMicrotask(async () => {+ const r = getRedis();+ if (r) {+ try {+ const len = await r.rpush(BUFFER_KEY, JSON.stringify(normalizeEvent(event)));+ // Hard cap: if the flusher is falling behind, shed the oldest rows+ // rather than let the list grow without bound.+ if (len > BUFFER_MAX) await r.ltrim(BUFFER_KEY, len - BUFFER_MAX, -1);+ // Set the TTL once on first push so the key self-cleans if the flusher+ // dies — the safety-net cron (api/cron/flush-usage-events.js) normally+ // drains it every minute.+ if (len === 1) await r.expire(BUFFER_KEY, BUFFER_TTL_S);+ return;+ } catch (err) {+ // The shared Redis breaker already logged an auth/credential failure+ // once and is fast-failing; a direct insert is the right fallback but+ // re-warning per event is noise.+ if (!err?.circuitOpen && !isRedisAuthError(err)) {+ console.warn('[x402-audit] buffer push failed, falling back to direct insert', err?.message);+ }+ }+ }+ // Direct-insert fallback when Redis is absent or the push failed. Bounded by+ // the short audit write timeout so a slow Neon spell can't hold this detached+ // work open per-event.try {- // A transient Neon "fetch failed" must not silently drop a payment- // event — retry the connection-level blip (the write never committed).- await withDbRetry(() => sql`- INSERT INTO x402_audit_log- (event_type, route, resource_url, payer, network, amount_atomics,- asset, tx_hash, settlement_status, facilitator_response,- duration_ms, ip_address, user_agent, metadata)- VALUES- (${event.eventType},- ${event.route},- ${event.resourceUrl ?? null},- ${event.payer ?? null},- ${event.network ?? null},- ${event.amountAtomics ?? null},- ${event.asset ?? null},- ${event.txHash ?? null},- ${event.settlementStatus ?? null},- ${event.facilitatorResponse ? JSON.stringify(event.facilitatorResponse) : null},- ${event.durationMs ?? null},- ${event.ipAddress ?? null},- ${event.userAgent ?? null},- ${event.metadata ? JSON.stringify(event.metadata) : null})- `, { timeoutMs: auditWriteTimeoutMs() });+ await insertAuditRows([event], { timeoutMs: auditWriteTimeoutMs() });} catch (err) {logAuditFailure(event, err);}});}+// Canonical column order for the audit table. Kept in one place so the buffered+// record shape, the multi-row INSERT, and any future migration stay in lockstep.+const AUDIT_COLUMNS = [+ 'event_type', 'route', 'resource_url', 'payer', 'network', 'amount_atomics',+ 'asset', 'tx_hash', 'settlement_status', 'facilitator_response',+ 'duration_ms', 'ip_address', 'user_agent', 'metadata',+];+// 0-based indexes of the JSONB columns, whose placeholders need a `::jsonb` cast.+const AUDIT_JSONB_COLS = new Set([9, 13]);++// Flatten an event into a positional row matching AUDIT_COLUMNS. JSON columns are+// pre-stringified here so both the buffer record and the INSERT bind the same+// value; the `::jsonb` cast on the placeholder does the parse server-side.+function normalizeEvent(event) {+ return [+ event.eventType ?? null,+ event.route ?? null,+ event.resourceUrl ?? null,+ event.payer ?? null,+ event.network ?? null,+ event.amountAtomics ?? null,+ event.asset ?? null,+ event.txHash ?? null,+ event.settlementStatus ?? null,+ event.facilitatorResponse ? JSON.stringify(event.facilitatorResponse) : null,+ event.durationMs ?? null,+ event.ipAddress ?? null,+ event.userAgent ?? null,+ event.metadata ? JSON.stringify(event.metadata) : null,+ ];+}++// Accepts either raw event objects (fallback path) or already-normalized rows+// (buffer path — arrays). Builds ONE multi-row INSERT and runs it under the retry+// guard so a transient Neon connection blip is retried (the write never committed).+async function insertAuditRows(events, opts) {+ const rows = events.map((e) => (Array.isArray(e) ? e : normalizeEvent(e)));+ if (rows.length === 0) return;++ const cols = AUDIT_COLUMNS.length;+ const params = [];+ const tuples = rows.map((row, i) => {+ const base = i * cols;+ const placeholders = row.map((val, c) => {+ params.push(val);+ return AUDIT_JSONB_COLS.has(c) ? `$${base + c + 1}::jsonb` : `$${base + c + 1}`;+ });+ return `(${placeholders.join(', ')})`;+ });++ const text =+ `INSERT INTO x402_audit_log (${AUDIT_COLUMNS.join(', ')}) VALUES ${tuples.join(', ')}`;+ await withDbRetry(() => sql(text, params), opts);+}++/**+ * Drain up to `limit` buffered audit rows from Redis and batch-insert them into+ * Neon, stopping after `deadlineMs` so a slow Neon spell can't push the caller+ * past its function timeout. Each batch is a single multi-row INSERT. Consumed+ * entries are trimmed regardless of insert success — re-inserting duplicates on+ * retry is worse than losing a few best-effort telemetry rows. Called by the+ * usage-flush cron and QStash job (they drain both telemetry buffers).+ *+ * @param {{ limit?: number, deadlineMs?: number }} [opts]+ * @returns {Promise<{ flushed: number, remaining: number, errors: number, timedOut?: boolean, skipped?: string }>}+ */+export async function flushAuditBuffer({ limit = 1000, deadlineMs = 45_000 } = {}) {+ const r = getRedis();+ if (!r) return { flushed: 0, remaining: 0, errors: 0, skipped: 'redis_unavailable' };++ const BATCH = 200;+ let flushed = 0;+ let errors = 0;+ let timedOut = false;+ const startedAt = Date.now();++ while (flushed < limit) {+ if (Date.now() - startedAt > deadlineMs) { timedOut = true; break; }+ const take = Math.min(BATCH, limit - flushed);++ let raw;+ try {+ raw = await r.lrange(BUFFER_KEY, 0, take - 1);+ } catch (err) {+ if (!err?.circuitOpen && !isRedisAuthError(err)) {+ console.warn('[x402-audit-flush] redis unavailable on lrange:', err?.message);+ }+ return { flushed, remaining: -1, errors, skipped: 'redis_unavailable' };+ }+ if (!raw || raw.length === 0) break;++ const rows = raw.map((item) => {+ try { return typeof item === 'string' ? JSON.parse(item) : item; }+ catch { return null; }+ }).filter((row) => Array.isArray(row) && row.length === AUDIT_COLUMNS.length);++ if (rows.length > 0) {+ try {+ await insertAuditRows(rows);+ } catch (err) {+ errors += 1;+ console.warn(`[x402-audit-flush] batch insert of ${rows.length} rows failed`, err?.message);+ }+ }++ // Trim the entries we read, whether or not the insert succeeded.+ await r.ltrim(BUFFER_KEY, raw.length, -1);+ flushed += raw.length;++ if (raw.length < take) break; // list exhausted+ }++ const remaining = await r.llen(BUFFER_KEY).catch(() => -1);+ return { flushed, remaining, errors, timedOut };+}+/*** Query the audit log with optional filters.*diff --git a/api/_lib/x402/ring-allowlist.js b/api/_lib/x402/ring-allowlist.jsindex 6146891a4..b0f172e38 100644--- a/api/_lib/x402/ring-allowlist.js+++ b/api/_lib/x402/ring-allowlist.js@@ -201,6 +201,18 @@ export function checkRingInvariants() {* @returns {Promise<{ ok: boolean, violations: Array<{ flag: string, expected: string, actual: string }> }>}*/export async function assertRingSpendInvariants({ context = 'unknown' } = {}) {+ // Intentional-pause switch. An operator who deliberately halts autonomous+ // spending sets X402_RING_PAUSED='true'; that must stop spending WITHOUT the+ // error+CRITICAL-alert treatment reserved for an *unexpected* guard violation.+ // Checked first so a clean pause is quiet regardless of the other guards, and+ // so the pause itself forces the fail-closed no-op (ok:false).+ if (process.env.X402_RING_PAUSED === 'true') {+ console.log(+ `[ring-invariants] spend path intentionally paused (X402_RING_PAUSED=true) — ${context} skipped, no spend`,+ );+ return { ok: false, paused: true, violations: [] };+ }+const result = checkRingInvariants();if (result.ok) return result;diff --git a/api/cron/db-retention.js b/api/cron/db-retention.jsindex 0ced34301..06c5418ed 100644--- a/api/cron/db-retention.js+++ b/api/cron/db-retention.js@@ -148,6 +148,39 @@ async function pruneFirehose(cutoffDays) {return { mints: totalMints, perTable };}+// ── B2. x402 payment audit-log retention ──────────────────────────────────────+// The payment audit ledger (x402_audit_log) grows one row per paid request on hot+// routes (e.g. /api/x402/dance-tip). Unbounded it both marches toward the storage+// cap and slows every dashboard aggregate (getPaymentStats full-scans it). Keep a+// generous window — long enough for revenue reporting — then prune by created_at,+// which the table's (event_type, created_at) indexes make cheap. Kept far longer+// than the intel firehose because these are money records, not churn; it tightens+// to a floor only under storage pressure via the shared valve.+const AUDIT_BATCH = 5000;+const AUDIT_MAX_PER_RUN = 100_000;++async function pruneAuditLog(cutoffDays) {+ if (!(await tableExists('x402_audit_log'))) return { deleted: 0 };++ let deleted = 0;+ const maxBatches = Math.ceil(AUDIT_MAX_PER_RUN / AUDIT_BATCH);+ for (let i = 0; i < maxBatches; i++) {+ // DELETE settles xmax in place (no file extension), so it works even at the+ // cap. Bounded subselect so a single statement never scans the whole table.+ const del = await sql`+ DELETE FROM x402_audit_log+ WHERE id IN (+ SELECT id FROM x402_audit_log+ WHERE created_at < now() - ${cutoffDays} * interval '1 day'+ LIMIT ${AUDIT_BATCH}+ ) RETURNING id+ `;+ deleted += del.length;+ if (del.length < AUDIT_BATCH) break;+ }+ return { deleted };+}+// ── B. avatar_regen_jobs hygiene ──────────────────────────────────────────────async function pruneRegenJobs() {if (!(await tableExists('avatar_regen_jobs'))) return { stripped: 0, deleted: 0 };@@ -220,6 +253,10 @@ export default wrapCron(async (req, res) => {const retentionDays = clampInt(process.env.PUMP_INTEL_RETENTION_DAYS, 2, 365, 14);const minDays = clampInt(process.env.PUMP_INTEL_MIN_RETENTION_DAYS, 1, retentionDays, 3);const highWaterMb = clampInt(process.env.DB_RETENTION_HIGH_WATER_MB, 128, 100_000, 470);+ // Audit ledger keeps its own, longer window (money records): default 90 days,+ // tightening to a 30-day floor while the branch is over the high-water mark.+ const auditDays = clampInt(process.env.X402_AUDIT_RETENTION_DAYS, 7, 3650, 90);+ const auditMinDays = clampInt(process.env.X402_AUDIT_MIN_RETENTION_DAYS, 1, auditDays, 30);const sizeBeforeMb = await dbSizeMb();const underPressure = sizeBeforeMb >= highWaterMb;@@ -227,12 +264,15 @@ export default wrapCron(async (req, res) => {// the high-water mark, so the cap is never actually reached; relax to the full// window once GC has returned the freed space and size drops back under it.const cutoffDays = underPressure ? minDays : retentionDays;+ const auditCutoffDays = underPressure ? auditMinDays : auditDays;const firehose = await pruneFirehose(cutoffDays);+ const audit = await pruneAuditLog(auditCutoffDays);const regen = await pruneRegenJobs();// VACUUM only tables we actually deleted from this tick.const touched = Object.keys(firehose.perTable).filter((t) => firehose.perTable[t] > 0);+ if (audit.deleted > 0) touched.push('x402_audit_log');if (regen.deleted > 0 || regen.stripped > 0) touched.push('avatar_regen_jobs');await vacuumTables(touched);@@ -258,7 +298,10 @@ export default wrapCron(async (req, res) => {under_pressure: underPressure,retention_days: retentionDays,cutoff_days: cutoffDays,+ audit_retention_days: auditDays,+ audit_cutoff_days: auditCutoffDays,firehose,+ audit,regen,vacuumed: touched,took_ms: Date.now() - started,diff --git a/api/cron/flush-usage-events.js b/api/cron/flush-usage-events.jsindex fd56e826e..9642f052e 100644--- a/api/cron/flush-usage-events.js+++ b/api/cron/flush-usage-events.js@@ -1,11 +1,12 @@// @ts-check-// GET /api/cron/flush-usage-events — 1-minute safety-net cron for the usage-// event buffer.+// GET /api/cron/flush-usage-events — 1-minute safety-net cron for the best-effort+// telemetry buffers.//-// recordEvent() pushes to a Redis list and triggers a QStash job when the-// buffer crosses a threshold. This cron catches everything else: low-traffic-// periods where the threshold is never crossed, QStash outages, and any events-// that slipped through while QStash was unavailable.+// Two Redis-buffered write paths ride this cron: usage events (recordEvent) and+// x402 payment-audit rows (logPaymentEvent). Each pushes to its own Redis list+// and this cron drains both every minute — catching low-traffic periods where an+// immediate flush never triggers, QStash outages, and anything that slipped+// through while QStash was unavailable.//// Kept as a concrete file (not [name].js) so the import graph stays minimal —// no shared SDK, skills, or data bundles needed for a telemetry flush.@@ -14,6 +15,7 @@ import { error, json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { constantTimeEquals } from '../_lib/crypto.js';import { flushUsageBuffer } from '../_lib/usage.js';+import { flushAuditBuffer } from '../_lib/x402/audit-log.js';import { sendOpsAlert } from '../_lib/alerts.js';function requireCron(req, res) {@@ -35,7 +37,12 @@ export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;if (!requireCron(req, res)) return;- const result = await flushUsageBuffer({ limit: 1000 });+ // Drain both telemetry buffers concurrently — independent Redis lists and Neon+ // writes, so one slow buffer must not delay the other.+ const [result, audit] = await Promise.all([+ flushUsageBuffer({ limit: 1000 }),+ flushAuditBuffer({ limit: 2000 }),+ ]);if (result.errors > 0) {sendOpsAlert(@@ -53,5 +60,21 @@ export default wrapCron(async (req, res) => {);}- return json(res, 200, result);+ if (audit.errors > 0) {+ sendOpsAlert(+ 'x402 audit buffer flush errors',+ `${audit.errors} batch inserts failed. flushed=${audit.flushed} remaining=${audit.remaining}`,+ { signature: 'x402-audit-flush-errors' },+ );+ }++ if (audit.remaining > 2000) {+ sendOpsAlert(+ 'x402 audit buffer backlog',+ `${audit.remaining} audit rows still queued after flush. Check Neon write latency.`,+ { signature: 'x402-audit-buffer-backlog' },+ );+ }++ return json(res, 200, { usage: result, audit });});diff --git a/api/cron/uptime-check.js b/api/cron/uptime-check.jsindex b1251b239..8bb9f06c3 100644--- a/api/cron/uptime-check.js+++ b/api/cron/uptime-check.js@@ -20,6 +20,7 @@ import { env } from '../_lib/env.js';import { cacheGet, cacheSet } from '../_lib/cache.js';import { sendOpsAlert } from '../_lib/alerts.js';import { constantTimeEquals } from '../_lib/crypto.js';+import { gatherSubsystemHealth } from '../_lib/ops/subsystem-health.js';// The surfaces that constitute "the platform is up". Each is a cheap public// GET — no auth, no side effects, no spend.@@ -43,6 +44,18 @@ const DAILY_KEY = 'uptime:daily';const SNAPSHOTS_TTL_S = 2 * 24 * 60 * 60;const DAILY_TTL_S = 100 * 24 * 60 * 60;+// Internal-dependency health (cache/ring/helius/db/world), gathered here and+// parked so /api/status can render it without a per-request DB ping.+const SUBSYSTEMS_KEY = 'uptime:subsystems';+const SUBSYSTEMS_TTL_S = 60 * 60; // 12× the 5-min cadence — a couple skipped ticks won't blank it+// Escalation memory: how many consecutive ticks each subsystem has been+// unhealthy, so a degradation that *persists* re-pages instead of dedup'ing into+// silence after the first hour. Keyed short; it only needs to survive tick-to-tick.+const DEGRADE_STREAK_KEY = 'uptime:subsystems:streak';+const DEGRADE_STREAK_TTL_S = 6 * 60 * 60;+// Re-page a still-degraded subsystem every this many ticks (5-min cadence → ~1h).+const RE_ESCALATE_EVERY_TICKS = 12;+async function probe(target, origin) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);@@ -136,6 +149,64 @@ export default wrapCron(async (req, res) => {}}+ // ── Internal subsystem health ─────────────────────────────────────────────+ // Reachability (above) says the door opens; this says the rooms behind it are+ // healthy. Gather, park for /api/status, and drive an escalation digest that+ // re-pages a *persistent* degradation rather than going quiet after dedup.+ let subsystems = null;+ try {+ subsystems = await gatherSubsystemHealth();+ await cacheSet(SUBSYSTEMS_KEY, subsystems, SUBSYSTEMS_TTL_S);+ await escalateSubsystems(subsystems);+ } catch (err) {+ console.warn('[uptime-check] subsystem health gather failed:', err?.message || err);+ }+const downCount = Object.values(results).filter((r) => !r.ok).length;- return json(res, 200, { ok: downCount === 0, down: downCount, results });+ return json(res, 200, {+ ok: downCount === 0 && (subsystems ? subsystems.status !== 'down' : true),+ down: downCount,+ results,+ subsystems: subsystems ? { status: subsystems.status, degraded: subsystems.degraded } : null,+ });});++// Config-drift + escalation digest. A subsystem that is degraded/down for the+// first time pages immediately (deduped 1h by sendOpsAlert). One that *stays*+// unhealthy re-pages every RE_ESCALATE_EVERY_TICKS so a half-armed ring or an+// unprotected world can't quietly persist for days behind a single stale alert.+// A subsystem that recovers pages a one-line "resolved". Streaks live in the+// cache so this survives across the stateless cron invocations.+async function escalateSubsystems(health) {+ const unhealthy = health.subsystems.filter((s) => s.status === 'down' || s.status === 'degraded');+ const prevStreaks = (await cacheGet(DEGRADE_STREAK_KEY)) || {};+ const nextStreaks = {};++ for (const s of unhealthy) {+ const streak = (prevStreaks[s.name] || 0) + 1;+ nextStreaks[s.name] = streak;+ // Page on the first tick, then once per RE_ESCALATE_EVERY_TICKS thereafter.+ const shouldPage = streak === 1 || streak % RE_ESCALATE_EVERY_TICKS === 0;+ if (!shouldPage) continue;+ const ageNote = streak === 1 ? 'new' : `degraded for ~${Math.round((streak * 5) / 60 * 10) / 10}h`;+ sendOpsAlert(+ `${s.status === 'down' ? 'DOWN' : 'DEGRADED'}: ${s.label}`,+ `${s.detail || ''}${s.hint ? `\n→ ${s.hint}` : ''}\n(${ageNote})`,+ // Rotate the signature each re-escalation window so the hourly dedup in+ // sendOpsAlert doesn't swallow the repeat, but hold it steady within a+ // window so a 5-min tick storm still collapses to one page.+ { signature: `subsystem:${s.status}:${s.name}:${Math.floor(streak / RE_ESCALATE_EVERY_TICKS)}` },+ );+ }++ // Recovery notices: anything that was unhealthy last tick and isn't now.+ for (const name of Object.keys(prevStreaks)) {+ if (nextStreaks[name]) continue;+ const rec = health.subsystems.find((s) => s.name === name);+ sendOpsAlert(`RESOLVED: ${rec?.label || name}`, rec?.detail || 'recovered', {+ signature: `subsystem:resolved:${name}:${Date.now()}`,+ });+ }++ await cacheSet(DEGRADE_STREAK_KEY, nextStreaks, DEGRADE_STREAK_TTL_S);+}diff --git a/api/cron/world-health.js b/api/cron/world-health.jsindex 5a5da709a..8a252b294 100644--- a/api/cron/world-health.js+++ b/api/cron/world-health.js@@ -18,6 +18,15 @@ import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { sendOpsAlert } from '../_lib/alerts.js';import { constantTimeEquals } from '../_lib/crypto.js';+import { cacheSet } from '../_lib/cache.js';++// Where this cron parks its last outcome so the platform health gatherer+// (api/_lib/ops/subsystem-health.js → /healthz + /status) can read it without+// re-probing the external world service on every page load. The world is a+// separate Cloud Run deploy, so its health can only be learned by this cron's+// cross-service probe; the cache is the hand-off.+export const WORLD_HEALTH_CACHE_KEY = 'world:health';+const WORLD_HEALTH_TTL_S = 60 * 60; // 1h: 4× the 15-min cadence, so a skipped tick doesn't blank itconst WORLD_STATUS_URL = process.env.WORLD_URL? `${process.env.WORLD_URL.replace(/\/+$/, '')}/status`@@ -143,6 +152,14 @@ export default wrapCron(async (req, res) => {console.warn(`[world-health] ${outcome} — ${problems.join('; ')}`);}+ // Park the outcome for the platform health gatherer. Best-effort: a cache+ // write failure here must never fail the monitor itself, so swallow it.+ await cacheSet(+ WORLD_HEALTH_CACHE_KEY,+ { status: outcome, protected: isProtected, problems, missingCount: missing.length, checkedAt: Date.now() },+ WORLD_HEALTH_TTL_S,+ ).catch(() => {});+return json(res, 200, {status: outcome,protected: isProtected,diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.jsindex 741ab5350..d6c1d7f5f 100644--- a/api/cron/x402-autonomous-loop.js+++ b/api/cron/x402-autonomous-loop.js@@ -238,7 +238,7 @@ export default wrapCron(async (req, res) => {return json(res, 200, {ok: false,skipped: true,- reason: 'ring_invariant_violation',+ reason: invariants.paused ? 'ring_paused' : 'ring_invariant_violation',violations: invariants.violations.map((v) => v.flag),});}diff --git a/api/healthz.js b/api/healthz.jsindex 4711a188d..68a3af99a 100644--- a/api/healthz.js+++ b/api/healthz.js@@ -9,6 +9,7 @@import { cors, json, method, wrap } from './_lib/http.js';import { countRecentPayments } from './_lib/x402/audit-log.js';+import { gatherSubsystemHealth } from './_lib/ops/subsystem-health.js';const STARTED_AT = Date.now();const VERSION = process.env.VERCEL_GIT_COMMIT_SHA || process.env.npm_package_version || 'dev';@@ -20,9 +21,14 @@ const RESEND_CACHE_TTL_MS = CACHE_TTL_MS;// doesn't flap the status.const HEARTBEAT_FRESH_MS = 6 * 60 * 1000;const MONITOR_CACHE_TTL_MS = 8 * 1000;+// Subsystem health is a live read of in-process breaker state + one DB ping.+// Cache it briefly so a burst of /healthz hits (dashboards poll it) doesn't fire+// a DB ping each — but keep the TTL short so a breaker tripping shows up fast.+const SUBSYSTEMS_CACHE_TTL_MS = 5 * 1000;let _resendCache = { value: null, expiresAt: 0 };let _x402Cache = { value: null, expiresAt: 0 };let _monitorCache = { value: null, expiresAt: 0 };+let _subsystemsCache = { value: null, expiresAt: 0 };// Exported for tests so each case starts with a cold cache.export function _resetResendCache() {@@ -34,6 +40,25 @@ export function _resetX402Cache() {export function _resetMonitorCache() {_monitorCache = { value: null, expiresAt: 0 };}+export function _resetSubsystemsCache() {+ _subsystemsCache = { value: null, expiresAt: 0 };+}++// Live subsystem health (cache breaker, Helius breaker, ring invariants, DB+// ping, world). Cached SUBSYSTEMS_CACHE_TTL_MS. Defensive: gatherSubsystemHealth+// never throws, but wrap anyway so /healthz stays green even if it did.+async function probeSubsystems() {+ const now = Date.now();+ if (_subsystemsCache.value && _subsystemsCache.expiresAt > now) return _subsystemsCache.value;+ let value;+ try {+ value = await gatherSubsystemHealth();+ } catch {+ value = { status: 'unknown', checkedAt: now, counts: {}, degraded: [], subsystems: [] };+ }+ _subsystemsCache = { value, expiresAt: now + SUBSYSTEMS_CACHE_TTL_MS };+ return value;+}// Real bot/monitor status, sourced from Postgres:// running — a bot_heartbeat row written by the pumpfun-monitor cron within@@ -198,6 +223,23 @@ async function probeX402() {result.siwx = 'unavailable';}+ // Ring spend status — surface whether the autonomous closed-loop spend path is+ // live as a dashboard field, so a fail-closed guard (or a deliberate pause) is+ // visible here instead of only as recurring cron error logs. checkRingInvariants+ // is a pure env read (no I/O); no key material is exposed, only flag names.+ try {+ const { checkRingInvariants } = await import('./_lib/x402/ring-allowlist.js');+ const inv = checkRingInvariants();+ const paused = process.env.X402_RING_PAUSED === 'true';+ result.ring = {+ spend_enabled: inv.ok && !paused,+ paused,+ violations: inv.violations.map((v) => v.flag),+ };+ } catch {+ result.ring = { spend_enabled: false, status: 'unavailable' };+ }+_x402Cache = { value: result, expiresAt: now + CACHE_TTL_MS };return result;}@@ -207,12 +249,16 @@ export default wrap(async (req, res) => {if (!method(req, res, ['GET'])) return;const uptimeMs = Date.now() - STARTED_AT;- const [resend, x402, monitorBlock] = await Promise.all([+ const [resend, x402, monitorBlock, subsystems] = await Promise.all([probeResend(),probeX402(),probeMonitor(),+ probeSubsystems(),]);return json(res, 200, {+ // Top-level liveness stays 'ok' (this function answering IS liveness); the+ // `subsystems` block carries the real health verdict so a degraded+ // dependency is visible without ever making the liveness probe flap.status: 'ok',service: '3d-agent',version: VERSION,@@ -225,5 +271,9 @@ export default wrap(async (req, res) => {// heartbeat exists or the DB is unreachable.monitor: monitorBlock.monitor,watches: monitorBlock.watches,+ // Live internal-dependency health: the exact degradation the reachability+ // probe can't see (Redis on memory-fallback, ring half-armed, Helius+ // throttled, DB slow, world unprotected). See api/_lib/ops/subsystem-health.js.+ subsystems,}, { 'cache-control': 'public, max-age=2, s-maxage=2' });});diff --git a/api/jobs/flush-usage-events.js b/api/jobs/flush-usage-events.jsindex 31debd639..b050dc2d8 100644--- a/api/jobs/flush-usage-events.js+++ b/api/jobs/flush-usage-events.js@@ -15,6 +15,7 @@import { error, json, method, wrap } from '../_lib/http.js';import { verifyQstashSignature } from '../_lib/qstash.js';import { flushUsageBuffer } from '../_lib/usage.js';+import { flushAuditBuffer } from '../_lib/x402/audit-log.js';export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;@@ -38,11 +39,17 @@ export default wrap(async (req, res) => {return error(res, 401, 'unauthorized', 'invalid qstash signature');}- const result = await flushUsageBuffer({ limit: 500 });+ const [result, audit] = await Promise.all([+ flushUsageBuffer({ limit: 500 }),+ flushAuditBuffer({ limit: 1000 }),+ ]);if (result.errors > 0) {console.warn('[usage-flush-job] completed with errors', result);}+ if (audit.errors > 0) {+ console.warn('[x402-audit-flush-job] completed with errors', audit);+ }- return json(res, 200, result);+ return json(res, 200, { usage: result, audit });});diff --git a/api/sniper/strategy.js b/api/sniper/strategy.jsindex 6fc80e5d4..fe69b7ca5 100644--- a/api/sniper/strategy.js+++ b/api/sniper/strategy.js@@ -341,6 +341,10 @@ async function upsertStrategy(req, res, userId) {alpha_max_mcap_usd: 'alpha_max_mcap_usd' in p ? (p.alpha_max_mcap_usd == null ? null : Math.max(0, Number(p.alpha_max_mcap_usd))) : (cur.alpha_max_mcap_usd != null ? Number(cur.alpha_max_mcap_usd) : null),alpha_narrative_keywords: 'alpha_narrative_keywords' in p ? (Array.isArray(p.alpha_narrative_keywords) ? p.alpha_narrative_keywords.filter(Boolean).slice(0, 10) : null) : (cur.alpha_narrative_keywords || null),alpha_min_quality_score: 'alpha_min_quality_score' in p ? (p.alpha_min_quality_score == null ? null : Math.min(100, Math.max(0, Math.round(Number(p.alpha_min_quality_score))))) : (cur.alpha_min_quality_score != null ? Number(cur.alpha_min_quality_score) : null),+ // Explicit, off-by-default consent for the auto-funder to top this agent's+ // wallet up from the launcher master. Arming a strategy never moves money+ // on its own — this must be turned on deliberately.+ auto_fund_enabled: 'auto_fund_enabled' in p ? Boolean(p.auto_fund_enabled) : (cur.auto_fund_enabled ?? false),};// Mandatory stop-loss — never let the DB constraint be the first line of defense.@@ -373,7 +377,7 @@ async function upsertStrategy(req, res, userId) {min_quality_score, max_bundle_score, max_concentration_top1,avoid_dev_dump, allowed_categories, telegram_chat_id,alpha_min_smart_money, alpha_min_organic_score, alpha_max_mcap_usd,- alpha_narrative_keywords, alpha_min_quality_score, updated_at)+ alpha_narrative_keywords, alpha_min_quality_score, auto_fund_enabled, updated_at)values(${p.agent_id}, ${userId}, ${p.network}, ${next.enabled}, ${next.kill_switch},${next.trigger}, ${next.buy_delay_ms}, ${next.min_claim_lamports}, ${next.max_claim_lamports}, ${next.first_claim_max_age_seconds},@@ -387,7 +391,7 @@ async function upsertStrategy(req, res, userId) {${next.min_quality_score}, ${next.max_bundle_score}, ${next.max_concentration_top1},${next.avoid_dev_dump}, ${next.allowed_categories}, ${next.telegram_chat_id},${next.alpha_min_smart_money}, ${next.alpha_min_organic_score}, ${next.alpha_max_mcap_usd},- ${next.alpha_narrative_keywords}, ${next.alpha_min_quality_score}, now())+ ${next.alpha_narrative_keywords}, ${next.alpha_min_quality_score}, ${next.auto_fund_enabled}, now())on conflict (agent_id, network) do update setenabled = excluded.enabled,kill_switch = excluded.kill_switch,@@ -428,6 +432,7 @@ async function upsertStrategy(req, res, userId) {alpha_max_mcap_usd = excluded.alpha_max_mcap_usd,alpha_narrative_keywords = excluded.alpha_narrative_keywords,alpha_min_quality_score = excluded.alpha_min_quality_score,+ auto_fund_enabled = excluded.auto_fund_enabled,updated_at = now()returning *`;@@ -476,6 +481,7 @@ async function upsertStrategy(req, res, userId) {alpha_max_mcap_usd: row.alpha_max_mcap_usd != null ? Number(row.alpha_max_mcap_usd) : null,alpha_narrative_keywords: row.alpha_narrative_keywords || null,alpha_min_quality_score: row.alpha_min_quality_score != null ? Number(row.alpha_min_quality_score) : null,+ auto_fund_enabled: row.auto_fund_enabled ?? false,},});}diff --git a/api/status.js b/api/status.jsindex 0fec29570..219a217ff 100644--- a/api/status.js+++ b/api/status.js@@ -54,13 +54,18 @@ export default wrap(async (req, res) => {const rl = await limits.publicIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const [snapshots, daily] = await Promise.all([+ const [snapshots, daily, subsystemsSnap] = await Promise.all([cacheGet('uptime:snapshots'),cacheGet('uptime:daily'),+ // Parked by api/cron/uptime-check.js every 5 min. We read the cron's+ // snapshot rather than re-gathering live so this public, cacheable endpoint+ // never fires a DB ping per request. null until the first post-deploy tick.+ cacheGet('uptime:subsystems'),]);const snaps = Array.isArray(snapshots) ? snapshots : [];const days = Array.isArray(daily) ? daily : [];const latest = snaps[snaps.length - 1] || null;+ const subsystems = subsystemsSnap && typeof subsystemsSnap === 'object' ? subsystemsSnap : null;const services = UPTIME_TARGETS.map((target) => {const current = latest?.results?.[target.id] || null;@@ -119,7 +124,18 @@ export default wrap(async (req, res) => {fleetUptime90d: u90Nums.length ? round(avg(u90Nums)) : null,};- const state = warming ? 'warming up' : allOk ? 'operational' : 'degraded';+ // Subsystem health (internal dependencies) can degrade the platform even when+ // every public surface is reachable — a half-armed ring or memory-fallback+ // cache is a real degradation a 200 can't reveal. Fold the worst of the two.+ const subDown = subsystems?.status === 'down';+ const subDegraded = subsystems?.status === 'degraded';+ const state = warming+ ? 'warming up'+ : subDown+ ? 'degraded' // an internal dependency being down is a platform degradation, not a total outage of public surfaces+ : allOk && !subDegraded+ ? 'operational'+ : 'degraded';// A total outage (everything probed is down) flips the badge to its inverted// 'down' treatment so it screams; partial disruption stays 'degraded'.const badgeState = !warming && up.length === 0 ? 'down' : state;@@ -152,12 +168,29 @@ export default wrap(async (req, res) => {res,200,{- ok: warming ? true : allOk,+ ok: warming ? true : allOk && !subDegraded && !subDown,monitoring: warming ? 'warming-up' : 'active',state,checkedAt: latest?.t ?? null,summary,services,+ // Internal-dependency health from the latest cron snapshot. Null until+ // the first post-deploy tick parks it. The page renders each entry with+ // its status + operator hint so a degradation is actionable, not cryptic.+ subsystems: subsystems+ ? {+ status: subsystems.status,+ checkedAt: subsystems.checkedAt ?? null,+ degraded: subsystems.degraded ?? [],+ items: (subsystems.subsystems || []).map((s) => ({+ name: s.name,+ label: s.label,+ status: s.status,+ detail: s.detail ?? null,+ hint: s.hint ?? null,+ })),+ }+ : null,},// json() defaults to no-store; status is probed every 5 minutes, so a// short shared cache absorbs page-load bursts without staleness.diff --git a/packages/agent-sniper/runbooks/LOG.md b/packages/agent-sniper/runbooks/LOG.mdindex edb64ec69..68146a107 100644--- a/packages/agent-sniper/runbooks/LOG.md+++ b/packages/agent-sniper/runbooks/LOG.md@@ -43,6 +43,29 @@ what was recorded, and what's next. Pairs with [PLAN.md](PLAN.md).wallets, no key import; (2) **funding fan-out is external** (on-chain transfer from thefunder, not a three.ws click); (3) **Avaturn not in normal UI** (gallery/upload only).+**Phase 1 — real-UI execution begins.**+- Owner provided the three.ws account login (`three-ws`) → stored in `~/.three-ws-fleet/env`.+- Owner rule reaffirmed (4×): do EVERYTHING via the real three.ws UI; flag any deviation.+- Vanity default set to **random UI wallets** (pure-UI) unless owner opts into the one+ non-UI import step.+- **Signed in via the real `/login` UI** (Playwright, recorded): filled form → landed on+ `https://three.ws/dashboard` as `three-ws`. Video + screenshots captured.+ Driver: `scripts/ui-login.mjs`.+- Hardened login (wait for the field before filling; `waitForURL` for success) after a+ timing-race failure (blank page). **Session persisted** to `~/.three-ws-fleet/state.json`+ (chmod 600) — reused by all later steps so we log in once. Driver: `scripts/ui-session.mjs`.+- **Captured the real `/create-agent` wizard** signed in: 5-step flow. Selectors:+ `#magic-input`+`#magic-go` (describe→Generate), `#f-name`, `#f-description`,+ `#f-tags-input`, `#btn-next`; avatar step + review follow. $THREE CA present in footer.+- ✅ **Agent #1 "Scout 01" CREATED via the real 5-step UI wizard, recorded.** Rigged+ **Saga** avatar (starter gallery), Pump.fun market-intel skill enabled, published.+ Platform confirmed "Scout 01 is ready — its own wallet and on-chain identity."+ Driver: `scripts/ui-create-agent.mjs` (5-step walk: basics → body → skills → persona →+ review → Create). Note for batch: success screen stays on `/create-agent`; capture the+ agent id via the "Open agent" button, not a URL change.+- Next: read Scout 01's agent id + Solana wallet → arm its sniper at `/dashboard/sniper`+ in **simulate** → watch at `/agent-screen`. Then batch the other 32, fund, go live.+**Open / next (blocking, owner decisions):**- Vanity vs random UI wallets? (vanity ⇒ a non-UI import step).- Account: register a fresh three.ws account in-UI, or use the owner's login?diff --git a/packages/agent-sniper/scripts/ui-agent-info.mjs b/packages/agent-sniper/scripts/ui-agent-info.mjsnew file mode 100644index 000000000..af64f5abc--- /dev/null+++ b/packages/agent-sniper/scripts/ui-agent-info.mjs@@ -0,0 +1,80 @@+// ui-agent-info.mjs — find an agent by name in the signed-in UI and read its id ++// Solana wallet address (from /agent/{id}/edit → Wallet panel). Recorded.+// Usage: NAME="Scout 01" node scripts/ui-agent-info.mjs++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { chromium } from 'playwright';++const BASE = process.env.BASE || 'https://three.ws';+const OUT = process.env.OUT || '/tmp/ui-agent-info';+const NAME = process.env.NAME || 'Scout 01';+const STATE = path.join(os.homedir(), '.three-ws-fleet', 'state.json');++fs.mkdirSync(OUT, { recursive: true });+const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--no-sandbox', '--disable-dev-shm-usage'] });+const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, storageState: STATE });+const page = await ctx.newPage();+const shot = (n) => page.screenshot({ path: path.join(OUT, `${n}.png`) }).catch(() => {});++try {+ await page.goto(`${BASE}/agents`, { waitUntil: 'domcontentloaded', timeout: 45_000 });+ await page.waitForTimeout(3500);+ await shot('agents-list');++ // find the agent link whose card text includes NAME, capture its id from href+ const info = await page.evaluate((name) => {+ const links = [...document.querySelectorAll('a[href]')];+ for (const a of links) {+ const txt = (a.innerText || '').trim();+ const href = a.getAttribute('href') || '';+ if (txt.includes(name)) {+ const m = href.match(/([0-9a-f-]{36})/i);+ if (m) return { id: m[1], href };+ }+ }+ // fallback: scan any element with the name, walk up to an <a>+ for (const el of document.querySelectorAll('*')) {+ if ((el.textContent || '').trim() === name) {+ const a = el.closest('a[href]');+ const m = a && a.getAttribute('href').match(/([0-9a-f-]{36})/i);+ if (m) return { id: m[1], href: a.getAttribute('href') };+ }+ }+ return null;+ }, NAME).catch(() => null);++ if (!info) { console.log(`✗ could not find agent "${NAME}" in /agents`); await shot('not-found'); throw new Error('agent not found in UI'); }+ console.log(`agent "${NAME}" id: ${info.id}`);++ // open its edit page → Wallet panel → read the Solana address+ await page.goto(`${BASE}/agent/${info.id}/edit`, { waitUntil: 'domcontentloaded', timeout: 45_000 });+ await page.waitForTimeout(3500);+ // try to click a "Wallet" tab/panel if present+ const walletTab = await page.$('text=Wallet');+ if (walletTab) { await walletTab.click().catch(() => {}); await page.waitForTimeout(1500); }+ await shot('agent-wallet');++ const addr = await page.evaluate(() => {+ const el = document.querySelector('#wallet-sol-address, [id*="sol-address"], [class*="sol-address"]');+ let a = el ? el.textContent.trim() : '';+ if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(a)) {+ // scan for a base58-looking pubkey on the page+ const m = document.body.innerText.match(/\b[1-9A-HJ-NP-Za-km-z]{32,44}\b/);+ a = m ? m[0] : '';+ }+ return a;+ }).catch(() => '');+ console.log(`solana wallet: ${addr || '(not found on page — check agent-wallet.png)'}`);++ fs.writeFileSync(path.join(OUT, 'info.json'), JSON.stringify({ name: NAME, id: info.id, wallet: addr }, null, 2));+} catch (err) {+ console.log('✗', err.message.slice(0, 160));+ await shot('error');+} finally {+ await page.waitForTimeout(300);+ await ctx.close();+ await browser.close();+ console.log('out:', OUT);+}diff --git a/packages/agent-sniper/scripts/ui-create-agent.mjs b/packages/agent-sniper/scripts/ui-create-agent.mjsnew file mode 100644index 000000000..349dd6035--- /dev/null+++ b/packages/agent-sniper/scripts/ui-create-agent.mjs@@ -0,0 +1,140 @@+// ui-create-agent.mjs — create ONE agent through the real three.ws 5-step wizard,+// signed in via the saved session, recorded. Walks each step, fills the basics,+// picks a starter (rigged) avatar, and completes — screenshotting + dumping the+// visible controls at every step so the exact click-path is captured for the+// batch-of-33 automation. Reports the new agent id/url.+//+// Usage: NAME="Scout 01" DESC="..." OUT=/path node scripts/ui-create-agent.mjs++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { chromium } from 'playwright';++const BASE = process.env.BASE || 'https://three.ws';+const OUT = process.env.OUT || '/tmp/ui-create';+const NAME = process.env.NAME || 'Scout 01';+const DESC = process.env.DESC || 'Autonomous pump.fun market scout — reads the tape, snipes fresh launches, skips the junk.';+const STATE = path.join(os.homedir(), '.three-ws-fleet', 'state.json');++fs.mkdirSync(OUT, { recursive: true });+if (!fs.existsSync(STATE)) { console.error('no saved session at', STATE, '— run ui-session.mjs first'); process.exit(1); }++const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--no-sandbox', '--disable-dev-shm-usage'] });+const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, storageState: STATE, recordVideo: { dir: OUT, size: { width: 1280, height: 800 } } });+const page = await ctx.newPage();+const shot = (n) => page.screenshot({ path: path.join(OUT, `${n}.png`) }).catch(() => {});++async function dumpControls(label) {+ const controls = await page.evaluate(() => {+ const vis = (el) => { const r = el.getBoundingClientRect(); const s = getComputedStyle(el); return r.width > 4 && r.height > 4 && s.visibility !== 'hidden' && s.display !== 'none'; };+ const out = [];+ for (const el of document.querySelectorAll('button, a[role="button"], input, textarea, [data-step], [class*="chip"], [class*="tab"], [class*="starter"], [class*="avatar"]')) {+ if (!vis(el)) continue;+ const t = (el.innerText || el.value || el.placeholder || el.getAttribute('aria-label') || '').trim().replace(/\s+/g, ' ').slice(0, 44);+ out.push(`${el.tagName.toLowerCase()}${el.id ? '#' + el.id : (el.className && typeof el.className === 'string' ? '.' + el.className.split(' ')[0] : '')}${t ? ' · "' + t + '"' : ''}`);+ }+ const heading = document.querySelector('h1, h2, [class*="step"]')?.innerText?.replace(/\s+/g, ' ').slice(0, 60) || '';+ return { heading, controls: [...new Set(out)].slice(0, 45) };+ }).catch(() => ({ heading: '', controls: [] }));+ console.log(`\n── ${label} ── ${controls.heading}`);+ for (const c of controls.controls) console.log(' ' + c);+ return controls;+}++async function firstVisible(sels) {+ for (const s of sels) {+ for (const el of await page.$$(s)) {+ if (await el.isVisible().catch(() => false)) return el;+ }+ }+ return null;+}++async function clickAdvance() {+ // only VISIBLE, enabled advance buttons (the wizard keeps hidden step panels in+ // the DOM, so #btn-next from a prior step lingers — don't click stale ones).+ const el = await firstVisible(['#btn-next',+ 'button:has-text("Continue")', 'button:has-text("Next")', 'button:has-text("Review")']);+ if (!el) return false;+ const label = (await el.innerText().catch(() => '')).trim();+ if (await el.isDisabled().catch(() => false)) { console.log(` advance "${label}" disabled`); return false; }+ await el.click().catch(() => {});+ console.log(` → clicked "${label}"`);+ return true;+}++try {+ await page.goto(`${BASE}/create-agent`, { waitUntil: 'domcontentloaded', timeout: 45_000 });+ await page.waitForTimeout(3500);++ for (let step = 1; step <= 7; step++) {+ await shot(`step${step}`);+ await dumpControls(`step ${step} (${page.url().replace(BASE, '')})`);++ // success: wizard finished → we're on an agent page, not /create-agent+ if (!/\/create-agent/.test(page.url())) { console.log('\n wizard left /create-agent →', page.url()); break; }++ // Step 1 basics: fill name + description if the field is present + empty.+ const nameEl = await page.$('#f-name');+ if (nameEl && !(await nameEl.inputValue())) {+ await nameEl.fill(NAME);+ const d = await page.$('#f-description'); if (d) await d.fill(DESC);+ console.log(` filled name="${NAME}"`);+ await page.waitForTimeout(400);+ }++ // Avatar step: pick the first starter tile if a gallery is present.+ const av = await page.$('#starter-grid img, #starter-grid button, [class*="starter"] img, [class*="starter"] button, [class*="avatar-grid"] button');+ if (av) { await av.click().catch(() => {}); console.log(' picked a starter avatar'); await page.waitForTimeout(800); }++ // Skills step: enable "Pump.fun market intel" (market data for trading decisions).+ const enabledIntel = await page.evaluate(() => {+ const rows = [...document.querySelectorAll('div, section, li, label')];+ for (const r of rows) {+ const txt = (r.innerText || '').toLowerCase();+ if (txt.includes('market intel') || (txt.includes('pump.fun') && txt.includes('market'))) {+ const t = r.querySelector('input[type="checkbox"], [role="switch"], button[class*="toggle"], .toggle');+ if (t) {+ const on = t.getAttribute('aria-checked') === 'true' || t.checked === true || (t.className || '').includes('on');+ if (!on) { t.click(); return true; }+ }+ }+ }+ return false;+ }).catch(() => false);+ if (enabledIntel) { console.log(' enabled Pump.fun market intel skill'); await page.waitForTimeout(500); }++ // Review step: the real submit is #btn-create ("Create agent"). Click it and+ // wait to leave /create-agent (the agent gets written here, not before).+ const createBtn = await page.$('#btn-create');+ if (createBtn && await createBtn.isVisible().catch(() => false) && !(await createBtn.isDisabled().catch(() => false))) {+ console.log(' → clicking "Create agent" (final submit)');+ await createBtn.click().catch(() => {});+ await page.waitForURL((u) => !/\/create-agent/.test(u.toString()), { timeout: 30_000 }).catch(() => {});+ await page.waitForTimeout(2500);+ break;+ }++ const advanced = await clickAdvance();+ await page.waitForTimeout(2500);+ if (!advanced) { console.log(' no advance possible — stopping to inspect'); break; }+ }++ await shot('final');+ const finalUrl = page.url();+ const m = finalUrl.match(/\/agent\/([0-9a-f-]{36})|\/a\/[^/]+\/([0-9a-f-]{36})|agentId=([0-9a-f-]{36})/i);+ const agentId = m ? (m[1] || m[2] || m[3]) : null;+ console.log(`\n RESULT url: ${finalUrl}`);+ console.log(` agent id: ${agentId || '(not detected — check final.png)'}`);+ fs.writeFileSync(path.join(OUT, 'result.json'), JSON.stringify({ finalUrl, agentId, name: NAME }, null, 2));+} catch (err) {+ console.log(' ✗ exception:', err.message.slice(0, 160));+ await shot('error');+} finally {+ await page.waitForTimeout(400);+ await ctx.close();+ const vid = fs.readdirSync(OUT).find((f) => f.endsWith('.webm'));+ await browser.close();+ console.log(`\n out: ${OUT} ${vid ? '(video: ' + vid + ')' : ''}`);+}diff --git a/packages/agent-sniper/scripts/ui-login.mjs b/packages/agent-sniper/scripts/ui-login.mjsnew file mode 100644index 000000000..9553326f5--- /dev/null+++ b/packages/agent-sniper/scripts/ui-login.mjs@@ -0,0 +1,92 @@+// ui-login.mjs — sign in to three.ws through the REAL UI, recorded.+// First step of the human-on-three.ws automation. Reads creds from+// ~/.three-ws-fleet/env, records video + a screenshot, and reports whether we+// actually landed signed-in (honest verdict — no assuming).++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { chromium } from 'playwright';++const BASE = process.env.BASE || 'https://three.ws';+const OUT = process.env.OUT || '/tmp/ui-login';++function env() {+ const f = path.join(os.homedir(), '.three-ws-fleet', 'env');+ const o = {};+ for (const line of fs.readFileSync(f, 'utf8').split('\n')) {+ if (!line || line.startsWith('#')) continue;+ const i = line.indexOf('='); if (i < 0) continue;+ o[line.slice(0, i)] = line.slice(i + 1);+ }+ return o;+}++const e = env();+const LOGIN = e.THREEWS_LOGIN, PASS = e.THREEWS_PASSWORD;+if (!LOGIN || !PASS) { console.error('no THREEWS_LOGIN/PASSWORD in env'); process.exit(1); }++fs.mkdirSync(OUT, { recursive: true });+const browser = await chromium.launch({+ args: ['--use-gl=angle', '--use-angle=swiftshader', '--no-sandbox', '--disable-dev-shm-usage'],+});+const ctx = await browser.newContext({ viewport: { width: 1280, height: 720 }, recordVideo: { dir: OUT, size: { width: 1280, height: 720 } } });+const page = await ctx.newPage();+const errors = [];+page.on('pageerror', (ev) => errors.push(ev.message.slice(0, 120)));++async function shot(name) { await page.screenshot({ path: path.join(OUT, `${name}.png`) }).catch(() => {}); }++try {+ console.log(`→ ${BASE}/login`);+ await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded', timeout: 45_000 });+ await page.waitForTimeout(2500);+ await shot('01-login-page');++ // Fill the identifier + password. Try the documented ids, then generic fallbacks.+ const idSel = ['#email', 'input[type="email"]', 'input[name="email"]', 'input[name="username"]', '#username'];+ const pwSel = ['#password', 'input[type="password"]', 'input[name="password"]'];+ let filledId = false, filledPw = false;+ for (const s of idSel) { const el = await page.$(s); if (el) { await el.fill(LOGIN); filledId = true; break; } }+ for (const s of pwSel) { const el = await page.$(s); if (el) { await el.fill(PASS); filledPw = true; break; } }+ console.log(` filled identifier=${filledId} password=${filledPw}`);+ await shot('02-filled');+ if (!filledId || !filledPw) { console.log(' ✗ could not find the email/password inputs on /login'); }++ // Submit: documented #submit, else a submit button / Enter.+ const submit = await page.$('#submit') || await page.$('button[type="submit"]')+ || await page.$('button:has-text("Sign in")') || await page.$('button:has-text("Log in")');+ if (submit) { await submit.click(); } else { await page.keyboard.press('Enter'); }+ console.log(' submitted, waiting for result…');++ // Success ≈ navigation away from /login (to /dashboard, /, etc.). Also capture any error text.+ await page.waitForTimeout(6000);+ const url = page.url();+ const signedIn = !/\/login/.test(url);+ await shot('03-after-submit');++ // Look for a visible error banner if still on /login.+ let errText = '';+ if (!signedIn) {+ errText = await page.evaluate(() => {+ const el = document.querySelector('.error, .alert, [role="alert"], .form-error, #error');+ return el ? el.textContent.trim().slice(0, 200) : '';+ }).catch(() => '');+ }++ console.log(`\n RESULT: ${signedIn ? 'SIGNED IN ✓' : 'still on /login ✗'}`);+ console.log(` final url: ${url}`);+ if (errText) console.log(` error on page: ${errText}`);+ if (errors.length) console.log(` page errors: ${errors.slice(0, 3).join(' | ')}`);++ fs.writeFileSync(path.join(OUT, 'result.json'), JSON.stringify({ signedIn, url, errText, pageErrors: errors }, null, 2));+} catch (err) {+ console.log(' ✗ exception:', err.message.slice(0, 160));+ await shot('99-error');+} finally {+ await page.waitForTimeout(500);+ await ctx.close();+ const vid = fs.readdirSync(OUT).find((f) => f.endsWith('.webm'));+ await browser.close();+ console.log(`\n Out: ${OUT} ${vid ? `(video: ${vid})` : ''}`);+}diff --git a/packages/agent-sniper/scripts/ui-session.mjs b/packages/agent-sniper/scripts/ui-session.mjsnew file mode 100644index 000000000..2ba845195--- /dev/null+++ b/packages/agent-sniper/scripts/ui-session.mjs@@ -0,0 +1,83 @@+// ui-session.mjs — sign in once, SAVE the session (storageState), and capture the+// real /create-agent wizard signed-in so the automation is built from the live UI.+// Session is reused by later steps so we never re-login mid-flow.++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { chromium } from 'playwright';++const BASE = process.env.BASE || 'https://three.ws';+const OUT = process.env.OUT || '/tmp/ui-session';+const DIR = path.join(os.homedir(), '.three-ws-fleet');+const STATE = path.join(DIR, 'state.json');++function env() {+ const o = {};+ for (const line of fs.readFileSync(path.join(DIR, 'env'), 'utf8').split('\n')) {+ if (!line || line.startsWith('#')) continue;+ const i = line.indexOf('='); if (i < 0) continue;+ o[line.slice(0, i)] = line.slice(i + 1);+ }+ return o;+}+const e = env();++fs.mkdirSync(OUT, { recursive: true });+const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--no-sandbox', '--disable-dev-shm-usage'] });+const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });+const page = await ctx.newPage();+const shot = (n) => page.screenshot({ path: path.join(OUT, `${n}.png`) }).catch(() => {});++try {+ // sign in — wait for the real form field before touching it (the login page+ // paints late; filling too early is what silently failed before).+ await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded', timeout: 45_000 });+ const pwEl = await page.waitForSelector('#password, input[type="password"]', { timeout: 25_000, state: 'visible' });+ const idEl = await page.$('#email') || await page.$('input[type="email"]') || await page.$('input[name="username"]');+ if (!idEl) throw new Error('identifier field not found on /login');+ await idEl.fill(e.THREEWS_LOGIN);+ await pwEl.fill(e.THREEWS_PASSWORD);+ await shot('login-filled');+ const sub = await page.$('#submit') || await page.$('button[type="submit"]');+ if (sub) await sub.click(); else await page.keyboard.press('Enter');+ // success = navigation off /login+ let signedIn = false;+ try { await page.waitForURL((u) => !/\/login/.test(u.toString()), { timeout: 20_000 }); signedIn = true; } catch {}+ console.log('signed in:', signedIn, '→', page.url());+ if (!signedIn) { await shot('login-failed'); throw new Error('login failed'); }++ // persist the session for later steps+ await ctx.storageState({ path: STATE });+ fs.chmodSync(STATE, 0o600);+ console.log('saved session →', STATE);++ // open the real create-agent wizard and capture it+ await page.goto(`${BASE}/create-agent`, { waitUntil: 'domcontentloaded', timeout: 45_000 });+ await page.waitForTimeout(3500);+ await shot('create-agent-01');++ // enumerate the visible interactive controls so we can script the exact click-path+ const controls = await page.evaluate(() => {+ const vis = (el) => { const r = el.getBoundingClientRect(); const s = getComputedStyle(el); return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; };+ const out = [];+ for (const el of document.querySelectorAll('button, a[role="button"], input, textarea, [data-step], [class*="chip"], [class*="tab"]')) {+ if (!vis(el)) continue;+ const t = (el.innerText || el.value || el.placeholder || el.getAttribute('aria-label') || '').trim().slice(0, 40);+ if (!t) continue;+ out.push(`${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''} · "${t}"`);+ }+ return [...new Set(out)].slice(0, 40);+ }).catch(() => []);+ console.log('\n/create-agent visible controls:');+ for (const c of controls) console.log(' ' + c);+ fs.writeFileSync(path.join(OUT, 'create-agent-controls.json'), JSON.stringify(controls, null, 2));+} catch (err) {+ console.log('✗', err.message.slice(0, 160));+ await shot('error');+} finally {+ await page.waitForTimeout(300);+ await ctx.close();+ await browser.close();+ console.log('\nout:', OUT);+}diff --git a/pages/status.html b/pages/status.htmlindex 873613bc1..d965c6204 100644--- a/pages/status.html+++ b/pages/status.html@@ -79,6 +79,12 @@.st-banner[data-state='ok'] {border-color: var(--ink);}+ /* Degraded: a dependency is on a fallback but surfaces are up. Dim ink,+ not red — red stays reserved for a genuine surface outage. */+ .st-banner[data-state='degraded'] {+ border-color: var(--ink-dim);+ border-style: dashed;+ }.st-banner[data-state='down'] {border-color: var(--danger);}@@ -256,6 +262,78 @@}}+ /* Internal-dependency health list */+ .st-subhead {+ font-family: var(--font-display);+ font-size: 1.1rem;+ margin: calc(var(--space-md) * 2) 0 0.4rem;+ }+ .st-subnote {+ color: var(--ink-dim);+ font: var(--text-sm) var(--font-body);+ margin: 0 0 var(--space-md);+ max-width: 60ch;+ }+ .st-sublist {+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ overflow: hidden;+ background: var(--surface-1);+ }+ .st-sub {+ display: grid;+ grid-template-columns: auto 1fr auto;+ align-items: baseline;+ gap: 0.6rem 0.75rem;+ padding: 0.85rem 1.1rem;+ border-top: 1px solid var(--stroke);+ }+ .st-sub:first-child {+ border-top: none;+ }+ .st-sub .st-dot {+ align-self: center;+ }+ /* degraded = dim ink (functional-but-throttled); paused/unknown = hollow;+ down = the single reserved red. Matches the monochrome status language. */+ .st-dot[data-state='degraded'] {+ background: var(--ink);+ opacity: 0.4;+ }+ .st-dot[data-state='paused'],+ .st-dot[data-state='unknown'] {+ background: transparent;+ box-shadow: inset 0 0 0 1.5px var(--ink-dim);+ }+ .st-sub-name {+ font-family: var(--font-display);+ font-size: 0.95rem;+ color: var(--ink);+ }+ .st-sub-state {+ font: var(--text-sm) var(--font-mono, monospace);+ color: var(--ink-dim);+ text-transform: uppercase;+ letter-spacing: 0.04em;+ white-space: nowrap;+ }+ .st-sub[data-state='down'] .st-sub-state {+ color: var(--danger);+ }+ .st-sub-detail {+ grid-column: 2 / -1;+ color: var(--ink-dim);+ font: var(--text-sm) var(--font-body);+ }+ .st-sub-hint {+ grid-column: 2 / -1;+ color: var(--ink);+ font: var(--text-sm) var(--font-body);+ margin-top: 0.15rem;+ padding-left: 0.75rem;+ border-left: 2px solid var(--stroke-strong);+ }+.st-note {border: 1px solid var(--stroke);border-radius: var(--radius-lg);@@ -329,6 +407,18 @@<div class="st-bar"></div></article></section>++ <!-- Internal dependency health — hidden until the API returns a+ subsystems block (older deploys / warming-up omit it). -->+ <section id="st-subsystems" aria-label="Internal dependency health" hidden>+ <h2 class="st-subhead">Internal dependencies</h2>+ <p class="st-subnote">+ Health of the systems behind the public surfaces — cache, database,+ payment ring, RPC. A green surface can still hide a degraded+ dependency; this is where it shows.+ </p>+ <div class="st-sublist" id="st-sublist"></div>+ </section></main><script type="module">@@ -337,6 +427,8 @@const bannerText = document.getElementById('st-banner-text');const meta = document.getElementById('st-meta');const list = document.getElementById('st-services');+ const subsWrap = document.getElementById('st-subsystems');+ const subsList = document.getElementById('st-sublist');const summaryEl = document.getElementById('st-summary');const kpiUptime = document.getElementById('st-kpi-uptime');const kpiServices = document.getElementById('st-kpi-services');@@ -372,22 +464,70 @@kpiLatency.textContent = s.avgLatencyMs == null ? '—' : `${s.avgLatencyMs}ms`;}+ // Human labels for the subsystem status vocabulary from the API.+ const SUB_STATE_WORD = {+ ok: 'operational',+ degraded: 'degraded',+ down: 'down',+ paused: 'paused',+ unknown: 'no data',+ };+ const esc = (s) =>+ String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);++ function renderSubsystems(subs) {+ // Older API shapes / warming-up omit the block — keep it hidden then.+ if (!subs || !Array.isArray(subs.items) || subs.items.length === 0) {+ subsWrap.hidden = true;+ return;+ }+ subsWrap.hidden = false;+ subsList.innerHTML = subs.items+ .map((it) => {+ const state = it.status || 'unknown';+ const word = SUB_STATE_WORD[state] || state;+ // Hint only earns screen space when there's an action to take.+ const showHint = it.hint && (state === 'degraded' || state === 'down');+ return `<div class="st-sub" data-state="${esc(state)}">+ <span class="st-dot" data-state="${esc(state)}" aria-hidden="true"></span>+ <span class="st-sub-name">${esc(it.label || it.name)}</span>+ <span class="st-sub-state">${esc(word)}</span>+ ${it.detail ? `<span class="st-sub-detail">${esc(it.detail)}</span>` : ''}+ ${showHint ? `<span class="st-sub-hint">${esc(it.hint)}</span>` : ''}+ </div>`;+ })+ .join('');+ }+function render(data) {renderSummary(data);+ renderSubsystems(data.subsystems);const probed = data.services.filter((s) => s.operational !== null);const down = probed.filter((s) => !s.operational);+ // Degraded internal dependencies (from the subsystems block) that the+ // public-surface probes can't see — surfaced so the banner is honest.+ const subItems = data.subsystems?.items || [];+ const subBad = subItems.filter((s) => s.status === 'degraded' || s.status === 'down');if (data.monitoring === 'warming-up') {bannerText.textContent = 'Monitoring is warming up — first probes land within minutes.';- } else if (down.length === 0) {+ } else if (down.length === 0 && subBad.length === 0) {banner.dataset.state = 'ok';bannerDot.dataset.state = 'ok';bannerText.textContent = 'All systems operational';+ } else if (down.length === 0) {+ // Surfaces are all up, but a dependency is degraded — honest amber.+ banner.dataset.state = 'degraded';+ bannerDot.dataset.state = 'degraded';+ bannerText.textContent = `Operational with ${subBad.length} degraded ${+ subBad.length === 1 ? 'dependency' : 'dependencies'+ }: ${subBad.map((s) => s.label).join(', ')}`;} else {banner.dataset.state = 'down';bannerDot.dataset.state = 'down';+ const extra = subBad.length ? ` · ${subBad.length} degraded dependency(ies)` : '';bannerText.textContent = `${down.length} of ${probed.length} services disrupted: ${down.map((s) => s.label)- .join(', ')}`;+ .join(', ')}${extra}`;}if (data.checkedAt) {const ago = Math.max(0, Math.round((Date.now() - data.checkedAt) / 60000));diff --git a/pages/theater.html b/pages/theater.htmlindex 65d2d893a..3cfbdd3ec 100644--- a/pages/theater.html+++ b/pages/theater.html@@ -56,6 +56,9 @@<h1 class="th-title">Live Trading Theater</h1><p class="th-room-hint" id="th-room-hint"></p></div>+ <button class="th-sound" id="th-sound" type="button" aria-pressed="false" aria-label="Sound off" title="Toggle fill sounds">+ <span class="th-sound-icon" aria-hidden="true">🔇</span>+ </button><div class="th-status th-dot-amber" id="th-status" role="status" aria-live="polite"><span class="th-status-dot" aria-hidden="true"></span><span class="th-status-label">Connecting</span>@@ -77,8 +80,11 @@<!-- quiet market --><div class="th-state th-quiet" id="th-quiet" hidden>- <h2>The market's quiet right now</h2>- <p class="th-muted">No agent is moving this second. Here's the most recent real activity — the stage lights up the instant the next on-chain buy fills.</p>+ <div class="th-quiet-head">+ <span class="th-status-dot th-quiet-pulse" aria-hidden="true"></span>+ <h2>Waiting on the next move</h2>+ </div>+ <p class="th-muted th-quiet-beat" data-beat>The stage lights up the instant the next on-chain buy fills.</p><div class="th-highlights" data-highlights></div></div>diff --git a/scripts/vercel-ignore-build.sh b/scripts/vercel-ignore-build.shnew file mode 100755index 000000000..57b0430ea--- /dev/null+++ b/scripts/vercel-ignore-build.sh@@ -0,0 +1,49 @@+#!/usr/bin/env bash+# Vercel "Ignored Build Step".+# Exit 0 => SKIP the build (no deploy, no cost).+# Exit 1 => PROCEED with the build.+#+# Policy: skip only when EVERY changed file in this commit is non-deployable+# (docs, runbooks, changelog markdown). If a single deployable file changed,+# we build. This is deliberately conservative — unknown paths always build,+# so we never skip a deploy that mattered.+set -euo pipefail++# Compare against the previous deployed commit when Vercel provides it,+# otherwise fall back to the parent of HEAD.+BASE="${VERCEL_GIT_PREVIOUS_SHA:-}"+if [ -z "$BASE" ] || ! git cat-file -e "$BASE^{commit}" 2>/dev/null; then+ BASE="HEAD^"+fi++# List changed files; if git can't diff (shallow clone edge case), build to be safe.+if ! CHANGED="$(git diff --name-only "$BASE" HEAD 2>/dev/null)"; then+ echo "vercel-ignore: cannot diff — building to be safe"+ exit 1+fi++if [ -z "$CHANGED" ]; then+ echo "vercel-ignore: no file changes — skipping build"+ exit 0+fi++# Non-deployable path patterns. Anything matching ALL of these => safe to skip.+is_ignorable() {+ case "$1" in+ *.md) return 0 ;; # all markdown docs (docs/, specs/, README, CHANGELOG)+ */runbooks/*|runbooks/*) return 0 ;; # agent runbooks / LOG churn+ LICENSE|.gitignore|.editorconfig) return 0 ;;+ *) return 1 ;;+ esac+}++while IFS= read -r f; do+ [ -z "$f" ] && continue+ if ! is_ignorable "$f"; then+ echo "vercel-ignore: deployable change detected ($f) — building"+ exit 1+ fi+done <<< "$CHANGED"++echo "vercel-ignore: only docs/runbooks changed — skipping build"+exit 0diff --git a/src/theater-feed.js b/src/theater-feed.jsindex 44db04ad9..362bfac7a 100644--- a/src/theater-feed.js+++ b/src/theater-feed.js@@ -47,6 +47,11 @@ export function normalizeEvent(e) {agentId: null,mint: null,href: null,+ // Numeric magnitudes (when the event carries them) so the stage can size the+ // spectacle to the real fill and the receipt can show the money.+ sol: Number.isFinite(Number(e.sol)) ? Number(e.sol) : null,+ usd: null,+ symbol: typeof e.symbol === 'string' ? e.symbol : null,};switch (e.type) {case 'coin-buy':@@ -56,7 +61,7 @@ export function normalizeEvent(e) {case 'agent-onchain':return { ...base, kind: 'verify', agentId: e.agentId || null, title: 'Verified on-chain', sub: e.name || base.actor, href: e.agentId ? `/agent/${e.agentId}` : null };case 'payment':- return { ...base, kind: 'pay', title: 'Payment', sub: fmtUsdc(e.usdcAtomic) || e.recipientLabel || base.actor, href: e.explorerUrl || null };+ return { ...base, kind: 'pay', title: 'Payment', usd: Number.isFinite(Number(e.usdcAtomic)) ? Number(e.usdcAtomic) / 1e6 : null, sub: fmtUsdc(e.usdcAtomic) || e.recipientLabel || base.actor, href: e.explorerUrl || null };case 'jackpot':return { ...base, kind: 'win', title: 'Jackpot', sub: e.reward ? `${e.reward}` : base.actor, href: null };case 'agora-registered':diff --git a/src/theater-stage.js b/src/theater-stage.jsindex c78e82d42..71164c8f8 100644--- a/src/theater-stage.js+++ b/src/theater-stage.js@@ -134,8 +134,9 @@ export function createStage({ canvas, overlay, onSelect, reducedMotion = false }const scene = new Scene();scene.fog = new Fog(0x05050a, 14, 38);+ const CAM_BASE_Z = 9.4;const camera = new PerspectiveCamera(42, 1, 0.1, 200);- camera.position.set(0, 2.35, 9.4);+ camera.position.set(0, 2.35, CAM_BASE_Z);camera.lookAt(0, 1.25, -2);// Lighting — a cool key from above the audience plus a warm rim so avatars@@ -265,6 +266,18 @@ export function createStage({ canvas, overlay, onSelect, reducedMotion = false }group.userData.agentId = agent.id;cast.add(group);+ // A soft contact shadow grounds the figure on the floor — always faintly+ // present so no performer ever reads as floating (the flat disc used to make+ // bodies look like they hovered). Sits just under the highlight pad.+ const shadow = new Mesh(+ new CircleGeometry(0.62, 40),+ new MeshBasicMaterial({ color: 0x000000, transparent: true, opacity: 0.34, side: DoubleSide, depthWrite: false }),+ );+ shadow.rotation.x = -Math.PI / 2;+ shadow.position.set(slot.x, 0.012, slot.z);+ shadow.renderOrder = -1;+ cast.add(shadow);+// A soft pedestal glow under each performer; brightens when highlighted.const pad = new Mesh(new CircleGeometry(0.78, 40),@@ -276,7 +289,7 @@ export function createStage({ canvas, overlay, onSelect, reducedMotion = false }if (drivable && !reducedMotion) anim.play('idle');- const rec = { agent, group, model, pad, anim, drivable, slot, busy: false, plate: null };+ const rec = { agent, group, model, pad, shadow, anim, drivable, slot, busy: false, plate: null };rec.plate = makePlate(rec, index);performers.set(agent.id, rec);}@@ -330,6 +343,7 @@ export function createStage({ canvas, overlay, onSelect, reducedMotion = false }rec.plate?.remove();rec.group?.parent?.remove(rec.group);rec.pad?.parent?.remove(rec.pad);+ if (rec.shadow) { rec.shadow.parent?.remove(rec.shadow); rec.shadow.geometry?.dispose?.(); disposeMaterial(rec.shadow.material); }rec.group?.traverse?.((n) => {if (n.isMesh) { n.geometry?.dispose?.(); disposeMaterial(n.material); }});@@ -382,21 +396,30 @@ export function createStage({ canvas, overlay, onSelect, reducedMotion = false }* coin rises from the stage floor, holds, then sinks and is removed. Driven* only by a real coin-buy/launch event.*/- function spawnCenterpiece({ tint = 0x8b5cf6 } = {}) {+ function spawnCenterpiece({ tint = 0x8b5cf6, magnitude = 0.4 } = {}) {+ // The coin's size and glow scale with the real fill magnitude (0..1), so a+ // whale buy visibly dwarfs a small one — the drama tracks the money.+ const mag = Math.max(0, Math.min(1, magnitude));+ const radius = 0.5 + mag * 0.5;const coin = new Mesh(- new CylinderGeometry(0.62, 0.62, 0.12, 40),- new MeshStandardMaterial({ color: tint, emissive: new Color(tint), emissiveIntensity: 0.9, metalness: 0.7, roughness: 0.25 }),+ new CylinderGeometry(radius, radius, 0.12, 40),+ new MeshStandardMaterial({ color: tint, emissive: new Color(tint), emissiveIntensity: 0.75 + mag * 0.5, metalness: 0.7, roughness: 0.25 }),);coin.rotation.x = Math.PI / 2;coin.position.set(0, 0.2, -1);coin.userData.born = performance.now();scene.add(coin);- const glow = new PointLight(tint, 2.4, 9, 2);+ const glow = new PointLight(tint, 1.8 + mag * 2.2, 9 + mag * 3, 2);glow.position.set(0, 1.6, -1);scene.add(glow);coin.userData.glow = glow;centerpieces.push(coin);}++ // A brief camera dolly toward the stage on a marquee moment (a center-stage+ // buy/launch). Eases in and back out over ~0.7s; a no-op under reduced motion.+ let punchStart = -1;+ function punchCamera() { if (!reducedMotion) punchStart = performance.now(); }const centerpieces = [];// ── Selection (raycast) ──────────────────────────────────────────────────────@@ -446,6 +469,14 @@ export function createStage({ canvas, overlay, onSelect, reducedMotion = false }cast.rotation.y = orbitYaw;ring.rotation.z += dt * 0.05;+ // Camera push-in: sin(0→π) over 0.7s pulls the camera ~1 unit toward the+ // stage and eases back, punctuating a marquee fill without disorienting.+ if (punchStart >= 0) {+ const t = (now - punchStart) / 700;+ if (t >= 1) { punchStart = -1; camera.position.z = CAM_BASE_Z; }+ else camera.position.z = CAM_BASE_Z - Math.sin(t * Math.PI) * 1.0;+ }+if (!reducedMotion) {for (const rec of performers.values()) {if (rec.drivable) rec.anim.update(dt);@@ -560,6 +591,7 @@ export function createStage({ canvas, overlay, onSelect, reducedMotion = false }setRoster,perform,spawnCenterpiece,+ punchCamera,highlight,resize,setReducedMotion,diff --git a/src/theater.css b/src/theater.cssindex ac51676ea..f07d03faf 100644--- a/src/theater.css+++ b/src/theater.css@@ -86,6 +86,39 @@100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }}+/* ── sound toggle ────────────────────────────────────────────────────────── */+.th-sound {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 34px;+ height: 34px;+ flex: 0 0 auto;+ border-radius: var(--radius-pill, 999px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ color: var(--ink-dim, #888);+ cursor: pointer;+ font-size: 14px;+ line-height: 1;+ transition: all var(--duration-fast, 140ms) var(--ease-standard, ease);+}+.th-sound:hover { border-color: var(--th-accent-stroke); background: var(--surface-2, rgba(255, 255, 255, 0.05)); }+.th-sound:focus-visible { outline: 2px solid var(--th-accent); outline-offset: 2px; }+.th-sound.is-on { border-color: var(--th-accent-stroke); background: var(--th-accent-fill); }+.th-sound-icon { pointer-events: none; }++/* ── receipt coin badge ──────────────────────────────────────────────────── */+.th-rec-coin {+ font-family: var(--font-mono, monospace);+ font-size: 0.6rem;+ font-weight: var(--weight-bold, 700);+ color: var(--th-accent);+ background: var(--th-accent-fill);+ border-radius: var(--radius-pill, 999px);+ padding: 1px 6px;+}+/* ── rooms ───────────────────────────────────────────────────────────────── */.th-rooms {display: flex;@@ -242,6 +275,10 @@}.th-quiet h2 { font-size: var(--text-md, 0.81rem); }.th-quiet > p { font-size: var(--text-xs, 0.7rem); }+.th-quiet-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }+.th-quiet-head h2 { margin: 0; }+.th-quiet-pulse { background: var(--success, #4ade80); color: var(--success, #4ade80); animation: th-pulse 2s infinite; flex: 0 0 auto; }+.th-quiet-beat { font-variant-numeric: tabular-nums; }.th-highlights { margin-top: var(--space-4, 16px); display: flex; flex-direction: column; gap: 6px; text-align: left; max-height: 38vh; overflow-y: auto; }.th-hl {@@ -332,6 +369,29 @@.th-btn-primary { background: var(--th-accent-fill); border-color: var(--th-accent-stroke); color: var(--ink-bright, #fff); }.th-btn-on { background: var(--th-accent-fill); border-color: var(--th-accent-stroke); color: var(--ink-bright, #fff); }.th-btn-sm { flex: 0 0 auto; padding: 5px 10px; font-size: var(--text-2xs, 0.69rem); }+/* ── copy-trade (mirror) affordance ──────────────────────────────────────── */+.th-mirror { margin-bottom: var(--space-3, 12px); }+.th-mirror-start { width: 100%; }+.th-mirror-hint { font-size: var(--text-2xs, 0.69rem); margin: 6px 0 0; line-height: var(--leading-normal, 1.6); }+.th-mirror-form { display: flex; flex-direction: column; gap: 8px; padding: 12px; border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255, 255, 255, 0.03)); border: 1px solid var(--th-accent-stroke); }+.th-mirror-field { display: flex; flex-direction: column; gap: 4px; font-size: 0.6rem; color: var(--ink-dim, #888); text-transform: uppercase; letter-spacing: 0.04em; }+.th-mirror-select, .th-mirror-size {+ padding: 8px 10px;+ border-radius: var(--radius-sm, 6px);+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink-bright, #fff);+ font-size: var(--text-sm, 0.78rem);+ font-family: var(--font-body, system-ui);+}+.th-mirror-select:focus-visible, .th-mirror-size:focus-visible { outline: 2px solid var(--th-accent); outline-offset: 1px; }+.th-mirror-actions { display: flex; gap: 8px; margin-top: 2px; }+.th-mirror-ok { font-size: var(--text-2xs, 0.69rem); color: var(--success, #4ade80); margin: 0; line-height: var(--leading-normal, 1.6); }+.th-mirror-msg { font-size: var(--text-2xs, 0.69rem); margin: 2px 0 0; }+.th-mirror-err { color: var(--danger, #f87171); }+.th-mirror-ok a, .th-mirror-msg a { color: var(--th-accent); text-decoration: none; }+.th-mirror-ok a:hover, .th-mirror-msg a:hover { text-decoration: underline; }+.th-panel-foot { font-size: var(--text-2xs, 0.69rem); line-height: var(--leading-normal, 1.6); margin: 0 0 var(--space-3, 12px); }.th-panel-foot a { color: var(--th-accent); text-decoration: none; }.th-panel-foot a:hover { text-decoration: underline; }@@ -413,7 +473,7 @@}@media (prefers-reduced-motion: reduce) {- .th-spinner, .th-dot-green .th-status-dot, .th-rail-dot { animation: none; }+ .th-spinner, .th-dot-green .th-status-dot, .th-rail-dot, .th-quiet-pulse { animation: none; }.th-tick { animation: none; }.th-receipt { transition: none; }}diff --git a/src/theater.js b/src/theater.jsindex 4f0967553..d43c7962e 100644--- a/src/theater.js+++ b/src/theater.js@@ -22,6 +22,61 @@ import { enterRow } from './ui-juice.js';const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';const WATCH_KEY = 'theater:watch:v1';+const SOUND_KEY = 'theater:sound:v1';++// Fill magnitude (0..1) from a real event's numeric size — drives centerpiece+// scale and stinger loudness so a whale buy lands harder than a dust trade.+function fillMagnitude(n) {+ if (Number.isFinite(n?.sol)) return Math.max(0.25, Math.min(1, n.sol / 3)); // ~3 SOL reads as full+ if (Number.isFinite(n?.usd)) return Math.max(0.25, Math.min(1, n.usd / 500)); // ~$500 reads as full+ return 0.4;+}++// A tasteful, opt-in WebAudio stinger for marquee fills. No asset — a short+// synthesized two-note arpeggio, envelope-shaped so it never grates. Off by+// default (a surprise sound is bad UX); the AudioContext is created lazily on a+// user gesture so it complies with autoplay policy.+function createStinger() {+ let ctx = null;+ let enabled = false;+ try { enabled = localStorage.getItem(SOUND_KEY) === 'on'; } catch {}+ const ensureCtx = () => {+ if (ctx) return ctx;+ const AC = window.AudioContext || window.webkitAudioContext;+ if (!AC) return null;+ try { ctx = new AC(); } catch { ctx = null; }+ return ctx;+ };+ function ding(kind = 'buy', magnitude = 0.4) {+ if (!enabled) return;+ const ac = ensureCtx();+ if (!ac) return;+ if (ac.state === 'suspended') ac.resume().catch(() => {});+ const t0 = ac.currentTime;+ const notes = kind === 'loss' ? [329.63, 246.94] : [659.25, 987.77]; // fall on loss, rise otherwise+ const peak = 0.03 + Math.min(0.05, magnitude * 0.05);+ for (let i = 0; i < notes.length; i++) {+ const osc = ac.createOscillator();+ const g = ac.createGain();+ osc.type = 'triangle';+ osc.frequency.value = notes[i];+ const start = t0 + i * 0.07;+ g.gain.setValueAtTime(0.0001, start);+ g.gain.linearRampToValueAtTime(peak, start + 0.012);+ g.gain.exponentialRampToValueAtTime(0.0001, start + 0.3);+ osc.connect(g).connect(ac.destination);+ osc.start(start);+ osc.stop(start + 0.32);+ }+ }+ function toggle() {+ enabled = !enabled;+ try { localStorage.setItem(SOUND_KEY, enabled ? 'on' : 'off'); } catch {}+ if (enabled) { ensureCtx()?.resume?.().catch(() => {}); ding('buy', 0.5); } // confirmation blip+ return enabled;+ }+ return { ding, toggle, get enabled() { return enabled; } };+}// Stage budget — keep the cast lively but 60fps. Tighter on small screens.const isMobile = () => window.matchMedia('(max-width: 768px)').matches;@@ -69,6 +124,103 @@ async function whoami() {return _me;}+// ── copy-trade (mirror) plumbing ────────────────────────────────────────────────+// Wires the theater to the real custodial mirror system: one of the caller's own+// agents (the follower) copies the staged agent's (the leader's) confirmed trades,+// server-signed and sized/capped by the follower's own spend policy.+// POST /api/agents/:follower/mirror { leader_agent_id, sizing_mode:'fixed', fixed_sol }.++// A fresh single-use CSRF token for a state-changing POST.+async function csrfToken() {+ try {+ const r = await fetch('/api/csrf-token', { credentials: 'include' });+ if (!r.ok) return null;+ const j = await r.json().catch(() => null);+ return j?.data?.token || j?.token || null;+ } catch { return null; }+}++// The caller's own agents that can act as a follower — they need a custodial+// Solana wallet to trade. Cached for the session.+let _myAgents;+async function mirrorableAgents() {+ if (_myAgents !== undefined) return _myAgents;+ try {+ const r = await fetch('/api/agents', { credentials: 'include', headers: { accept: 'application/json' } });+ const list = r.ok ? (await r.json().catch(() => null))?.agents || [] : [];+ _myAgents = list.filter((a) => a.solana_address).map((a) => ({ id: a.id, name: a.name || 'Agent' }));+ } catch { _myAgents = []; }+ return _myAgents;+}++async function createMirror({ follower, leader, sizeSol }) {+ const token = await csrfToken();+ const r = await fetch(`/api/agents/${encodeURIComponent(follower)}/mirror`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', ...(token ? { 'x-csrf-token': token } : {}) },+ body: JSON.stringify({ leader_agent_id: leader, network: 'mainnet', enabled: true, sizing_mode: 'fixed', fixed_sol: sizeSol }),+ });+ const d = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(d.error_description || d.message || d.error || `mirror failed (${r.status})`);+ return d.data?.follow || d;+}++// Inline "copy this trader" affordance for the read-only HUD: a signed-in visitor+// picks one of their agents + a per-trade SOL size and starts a real mirror.+function buildMirror(leaderId, leaderName) {+ const wrap = el('div', { class: 'th-mirror' });++ function collapsed() {+ wrap.replaceChildren(+ el('button', { class: 'th-btn th-btn-primary th-mirror-start', onClick: openForm, text: '⧉ Copy this trader' }),+ el('p', { class: 'th-mirror-hint th-muted', text: 'Your agent buys what this one buys — sized and capped by your own limits.' }),+ );+ }++ async function openForm() {+ wrap.replaceChildren(el('p', { class: 'th-mirror-hint th-muted', text: 'Loading your agents…' }));+ const mine = await mirrorableAgents();+ if (!mine.length) {+ wrap.replaceChildren(el('p', { class: 'th-panel-foot th-muted' }, [+ 'Copying a trader needs one of your own agents with a wallet. ',+ el('a', { href: '/agent/me', text: 'Create one →' }),+ ]));+ return;+ }+ const select = el('select', { class: 'th-mirror-select', 'aria-label': 'Your agent to mirror with' },+ mine.map((a) => el('option', { value: a.id, text: a.name })));+ const size = el('input', { class: 'th-mirror-size', type: 'number', min: '0.001', step: '0.01', value: '0.05', 'aria-label': 'SOL per copied trade' });+ const submit = el('button', { class: 'th-btn th-btn-primary', text: 'Start mirroring' });+ const err = el('p', { class: 'th-mirror-msg th-mirror-err', role: 'status' });+ submit.addEventListener('click', async () => {+ const follower = select.value;+ const sizeSol = Math.max(0.001, Number(size.value) || 0.05);+ submit.disabled = true; submit.textContent = 'Starting…'; err.textContent = '';+ try {+ await createMirror({ follower, leader: leaderId, sizeSol });+ const name = mine.find((a) => a.id === follower)?.name || 'Your agent';+ wrap.replaceChildren(el('p', { class: 'th-mirror-ok' }, [+ `✓ ${name} now copies ${leaderName || 'this trader'}. `,+ el('a', { href: `/agent/${follower}`, text: 'Manage mirror →' }),+ ]));+ } catch (e) {+ submit.disabled = false; submit.textContent = 'Start mirroring';+ err.textContent = e?.message || 'Could not start mirroring.';+ }+ });+ wrap.replaceChildren(el('div', { class: 'th-mirror-form' }, [+ el('label', { class: 'th-mirror-field' }, ['Mirror with', select]),+ el('label', { class: 'th-mirror-field' }, ['SOL per trade', size]),+ el('div', { class: 'th-mirror-actions' }, [submit, el('button', { class: 'th-btn', text: 'Cancel', onClick: collapsed })]),+ err,+ ]));+ }++ collapsed();+ return wrap;+}+// ── data layer ────────────────────────────────────────────────────────────────async function fetchLeaderboard(limit) {const r = await fetch(`/api/reputation/leaderboard?limit=${limit}`, { headers: { accept: 'application/json' } });@@ -136,6 +288,7 @@ export function initTheater(root) {stageWrap: root.querySelector('#th-stage'),rooms: root.querySelector('#th-rooms'),status: root.querySelector('#th-status'),+ sound: root.querySelector('#th-sound'),ticker: root.querySelector('#th-ticker'),replay: root.querySelector('#th-replay'),panel: root.querySelector('#th-panel'),@@ -153,6 +306,22 @@ export function initTheater(root) {onSelect: (id) => openPanel(id),});+ // Opt-in audio stinger on marquee fills, toggled from the top bar and+ // remembered per browser. Default off — a page that greets you with sound is+ // hostile; the toggle is a discoverable invitation, not a surprise.+ const stinger = createStinger();+ if (refs.sound) {+ const paintSound = () => {+ const on = stinger.enabled;+ refs.sound.setAttribute('aria-pressed', on ? 'true' : 'false');+ refs.sound.setAttribute('aria-label', on ? 'Sound on' : 'Sound off');+ refs.sound.classList.toggle('is-on', on);+ refs.sound.querySelector('.th-sound-icon').textContent = on ? '🔊' : '🔇';+ };+ refs.sound.addEventListener('click', () => { stinger.toggle(); paintSound(); });+ paintSound();+ }+const ro = new ResizeObserver(() => stage.resize());ro.observe(refs.stageWrap);window.addEventListener('resize', () => stage.resize());@@ -166,6 +335,7 @@ export function initTheater(root) {watch: new Set(loadWatch()),sessionEvents: [], // featured events captured this session (for replay)liveCount: 0,+ lastMoveTs: null, // ts of the newest real event seen (drives the quiet heartbeat)selected: null,};@@ -263,9 +433,14 @@ export function initTheater(root) {if (!featured) return;if (threeOnly && n.kind === 'buy' && !isThree) return;- if ((n.kind === 'buy' || n.kind === 'launch') && (state.room.centerpiece || isThree)) {- stage.spawnCenterpiece({ tint: isThree ? 0x8b5cf6 : 0x4ade80 });+ const mag = fillMagnitude(n);+ const marquee = (n.kind === 'buy' || n.kind === 'launch') && (state.room.centerpiece || isThree);+ if (marquee) {+ stage.spawnCenterpiece({ tint: isThree ? 0x8b5cf6 : 0x4ade80, magnitude: mag });+ stage.punchCamera();}+ // A stinger on the marquee fills and any win (opt-in; no-op when muted).+ if (marquee || n.kind === 'win') stinger.ding(n.kind, mag);// Attribute to a staged performer when the event names one; otherwise the// receipt rises center-stage (still a real event, just no avatar to own it).@@ -290,6 +465,7 @@ export function initTheater(root) {const node = el('div', { class: `th-receipt ${tone}` }, [el('span', { class: 'th-rec-title', text: n.title }),n.sub ? el('span', { class: 'th-rec-sub', text: n.sub }) : null,+ n.symbol ? el('span', { class: 'th-rec-coin', text: `$${n.symbol}` }) : null,n.href ? el('a', { class: 'th-rec-link', href: n.href, target: '_blank', rel: 'noopener', text: 'View ↗' }) : null,]);return node;@@ -298,6 +474,7 @@ export function initTheater(root) {// ── ticker ───────────────────────────────────────────────────────────────────function pushTicker(n) {state.liveCount++;+ state.lastMoveTs = n.ts;const row = el('li', { class: `th-tick th-tick-${n.kind}` }, [el('span', { class: 'th-tick-dot' }),el('div', { class: 'th-tick-body' }, [@@ -407,14 +584,17 @@ export function initTheater(root) {isOwner? el('p', { class: 'th-panel-foot th-muted', text: 'This agent is yours — act from its profile.' }): signedIn- ? el('p', { class: 'th-panel-foot th-muted' }, [- 'Fork to own a copy with its own wallet, or follow its alpha from ',- el('a', { href: `/agent/${id}`, text: 'its profile' }),- '.',+ ? el('div', {}, [+ buildMirror(id, agent.name),+ el('p', { class: 'th-panel-foot th-muted' }, [+ 'Or ',+ el('a', { href: `/agent/${id}`, text: 'open its profile' }),+ ' to fork it to your own wallet.',+ ]),]): el('p', { class: 'th-panel-foot th-muted' }, [el('a', { href: `/login?next=${encodeURIComponent(`/agent/${id}`)}`, text: 'Sign in' }),- ' to fork this agent to your own wallet or follow its alpha. Watching is always free.',+ ' to copy this agent to your own wallet or follow its alpha. Watching is always free.',]),recentForAgent(id),);@@ -447,8 +627,23 @@ export function initTheater(root) {if (state.selected === id) renderPanel(id);}- // ── quiet-market highlights (real recent activity) ───────────────────────────+ // ── quiet-market heartbeat + highlights (real recent activity) ───────────────+ // The heartbeat is honest: "last real move Xs ago" from the newest snapshot+ // event, ticking live — anticipation without a fabricated countdown (we can't+ // predict the next fill, so we never pretend to).+ function updateBeat() {+ const beat = refs.quiet.querySelector('[data-beat]');+ if (!beat) return;+ if (Number.isFinite(state.lastMoveTs)) {+ beat.textContent = `Last on-chain move ${timeAgo(state.lastMoveTs)} ago — the stage lights up the instant the next buy fills.`;+ } else {+ beat.textContent = 'The stage lights up the instant the next on-chain buy fills.';+ }+ }+loadSnapshot(40).then((events) => {+ if (events.length) state.lastMoveTs = Math.max(...events.map((e) => e.ts));+ updateBeat();const featured = events.filter((e) => ROOMS.some((r) => r.featured.has(e.kind)) && (e.href || e.sub));const host = refs.quiet.querySelector('[data-highlights]');if (!host) return;@@ -475,6 +670,7 @@ export function initTheater(root) {const dt = Date.parse(t.getAttribute('datetime'));if (Number.isFinite(dt)) t.textContent = timeAgo(dt);});+ if (!refs.quiet.hidden) updateBeat();}, 15000);// reduced-motion live toggle (system pref change)diff --git a/tests/sniper-safety-guards.test.js b/tests/sniper-safety-guards.test.jsnew file mode 100644index 000000000..b80914dfa--- /dev/null+++ b/tests/sniper-safety-guards.test.js@@ -0,0 +1,94 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Query-aware fake `sql` for launcher-funding's ledger reads. Each source can be+// toggled to throw (missing-table simulation) to prove the fail-open contract.+const H = vi.hoisted(() => ({ launcherRunsThrows: false, sniperEventsThrows: false, launcherSol: 0, sniperLamports: 0 }));+vi.mock('../api/_lib/db.js', () => {+ const sql = (strings) => {+ const q = Array.isArray(strings) ? strings.join(' ').toLowerCase() : '';+ if (q.includes('from launcher_runs')) {+ if (H.launcherRunsThrows) return Promise.reject(new Error('relation "launcher_runs" does not exist'));+ return Promise.resolve([{ s: H.launcherSol }]);+ }+ if (q.includes('from sniper_funding_events')) {+ if (H.sniperEventsThrows) return Promise.reject(new Error('relation "sniper_funding_events" does not exist'));+ return Promise.resolve([{ s: H.sniperLamports / 1e9 }]);+ }+ return Promise.resolve([]);+ };+ return { sql, LAMPORTS_PER_SOL: 1_000_000_000 };+});++import { parseAgentIds } from '../workers/agent-sniper/config.js';+import { mayhemVerdict, mayhemGate } from '../workers/agent-sniper/mayhem-gate.js';+import { withinMasterDailyCap, masterDailyOutflowSol } from '../api/_lib/launcher-funding.js';++describe('parseAgentIds (worker agent scoping)', () => {+ it('returns null for unset / empty / whitespace', () => {+ expect(parseAgentIds(undefined)).toBeNull();+ expect(parseAgentIds('')).toBeNull();+ expect(parseAgentIds(' ')).toBeNull();+ });+ it('parses comma/space/newline separated UUIDs, lowercased + de-duped', () => {+ const a = 'c315ac7e-1c9e-46f8-8921-909dd572024d';+ const b = 'A633660F-D013-407D-832D-6C505A9EA15A';+ expect(parseAgentIds(`${a}, ${b}\n${a}`)).toEqual([a, b.toLowerCase()]);+ });+ it('drops non-UUID tokens, returns null if none valid', () => {+ expect(parseAgentIds('not-a-uuid, also-bad')).toBeNull();+ expect(parseAgentIds('nope, c315ac7e-1c9e-46f8-8921-909dd572024d')).toEqual(['c315ac7e-1c9e-46f8-8921-909dd572024d']);+ });+});++describe('mayhemVerdict (owner rule: no pump.fun Mayhem tokens)', () => {+ it('skips a Mayhem token', () => {+ expect(mayhemVerdict(true)).toEqual({ pass: false, reason: 'mayhem_excluded' });+ });+ it('allows a normal (non-Mayhem) token', () => {+ expect(mayhemVerdict(false)).toEqual({ pass: true });+ });+ it('allows-on-unknown by default, but skips when strict', () => {+ expect(mayhemVerdict(null)).toEqual({ pass: true, unknown: true });+ expect(mayhemVerdict(null, { strict: true })).toEqual({ pass: false, reason: 'mayhem_unknown', unknown: true });+ expect(mayhemVerdict(undefined, { strict: true })).toEqual({ pass: false, reason: 'mayhem_unknown', unknown: true });+ });+});++describe('mayhemGate', () => {+ it('is a no-op pass-through when the filter is disabled (no RPC)', async () => {+ await expect(mayhemGate('AnyMint111', { mayhemFilter: false })).resolves.toEqual({ pass: true });+ });+});++describe('withinMasterDailyCap (hard master outflow ceiling)', () => {+ it('no cap when capSol is 0 / negative / non-finite', () => {+ expect(withinMasterDailyCap(5, 5, 0).ok).toBe(true);+ expect(withinMasterDailyCap(5, 5, -1).ok).toBe(true);+ expect(withinMasterDailyCap(5, 5, NaN).ok).toBe(true);+ });+ it('allows a transfer that stays within the cap (incl. exact boundary)', () => {+ expect(withinMasterDailyCap(1.0, 0.5, 2).ok).toBe(true);+ expect(withinMasterDailyCap(1.5, 0.5, 2).ok).toBe(true); // exactly at cap+ });+ it('refuses a transfer that would exceed the cap', () => {+ const r = withinMasterDailyCap(1.8, 0.5, 2);+ expect(r.ok).toBe(false);+ expect(r.reason).toMatch(/master_daily_cap/);+ });+});++describe('masterDailyOutflowSol (fails open per-source)', () => {+ beforeEach(() => { H.launcherRunsThrows = false; H.sniperEventsThrows = false; H.launcherSol = 0; H.sniperLamports = 0; });+ it('sums both ledgers', async () => {+ H.launcherSol = 0.7; H.sniperLamports = 300_000_000; // 0.3 SOL+ await expect(masterDailyOutflowSol('mainnet')).resolves.toBeCloseTo(1.0, 6);+ });+ it('does not throw when a ledger table is missing — contributes 0', async () => {+ H.launcherRunsThrows = true; H.sniperLamports = 500_000_000;+ await expect(masterDailyOutflowSol('mainnet')).resolves.toBeCloseTo(0.5, 6);+ });+ it('returns 0 when both sources are unavailable', async () => {+ H.launcherRunsThrows = true; H.sniperEventsThrows = true;+ await expect(masterDailyOutflowSol('mainnet')).resolves.toBe(0);+ });+});diff --git a/tests/subsystem-health.test.js b/tests/subsystem-health.test.jsnew file mode 100644index 000000000..62417d3bc--- /dev/null+++ b/tests/subsystem-health.test.js@@ -0,0 +1,143 @@+/**+ * api/_lib/ops/subsystem-health.js — unit tests.+ *+ * The gatherer reads each subsystem's in-process degradation state and rolls it+ * into one verdict. These pin the status vocabulary (ok/degraded/down/paused/+ * unknown), the roll-up (only degraded/down count against overall), and the two+ * cases the 2026-07-03 log export surfaced that a reachability probe can't see:+ * a half-armed x402 ring and an unprotected world.+ *+ * probeDb:false everywhere so the suite never needs a live Neon connection — the+ * DB ping has its own behavior (down when unreachable) that isn't the point here.+ */++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { gatherSubsystemHealth } from '../api/_lib/ops/subsystem-health.js';+import { cacheSet } from '../api/_lib/cache.js';++// Env the ring + x402-config checks read. Save/restore so cases don't leak.+const ENV_KEYS = [+ 'X402_AUTONOMOUS_ENABLED',+ 'X402_EXTERNAL_ENABLED',+ 'X402_CHARITY_AUDIT_BPS',+ 'X402_SELF_FACILITATOR_ENABLED',+ 'X402_FACILITATOR_URL_SOLANA',+ 'X402_PAY_TO_SOLANA',+ 'X402_PAY_TO',+ 'X402_PAY_TO_BASE',+ 'X402_FEE_PAYER_SOLANA',+ 'UPSTASH_CACHE_REST_URL',+ 'UPSTASH_CACHE_REST_TOKEN',+ 'UPSTASH_REDIS_REST_URL',+ 'UPSTASH_REDIS_REST_TOKEN',+];+let saved;++function sub(health, name) {+ return health.subsystems.find((s) => s.name === name);+}++beforeEach(() => {+ saved = {};+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+});++afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+});++describe('gatherSubsystemHealth', () => {+ it('reports the x402 ring as PAUSED when the loop is explicitly disabled', async () => {+ process.env.X402_AUTONOMOUS_ENABLED = 'false';+ const health = await gatherSubsystemHealth({ probeDb: false });+ const ring = sub(health, 'x402_ring');+ expect(ring.status).toBe('paused');+ // A paused ring is a chosen state, not a fault — must not drag overall down.+ expect(health.status).not.toBe('down');+ });++ it('reports the x402 ring as DEGRADED when enabled but guards are unset (half-armed)', async () => {+ // Enabled (not 'false') with the closed-loop guards unset — the exact+ // half-armed config the production log export showed.+ delete process.env.X402_AUTONOMOUS_ENABLED;+ delete process.env.X402_CHARITY_AUDIT_BPS;+ process.env.X402_SELF_FACILITATOR_ENABLED = 'false';+ const health = await gatherSubsystemHealth({ probeDb: false });+ const ring = sub(health, 'x402_ring');+ expect(ring.status).toBe('degraded');+ expect(ring.detail).toMatch(/half-armed/);+ expect(ring.hint).toBeTruthy();+ expect(health.status).toBe('degraded');+ expect(health.degraded).toContain('x402_ring');+ });++ it('reports the x402 ring as OK when all closed-loop guards are satisfied', async () => {+ delete process.env.X402_AUTONOMOUS_ENABLED;+ process.env.X402_EXTERNAL_ENABLED = 'false';+ process.env.X402_CHARITY_AUDIT_BPS = '0';+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';+ // Leave the facilitator URL unset so it defaults to self.+ const health = await gatherSubsystemHealth({ probeDb: false });+ expect(sub(health, 'x402_ring').status).toBe('ok');+ });++ it('flags x402 payment config as DEGRADED when Solana pay-to is set without a fee payer', async () => {+ process.env.X402_PAY_TO_SOLANA = 'THREEsynthetic1111111111111111111111111111111';+ delete process.env.X402_FEE_PAYER_SOLANA;+ const health = await gatherSubsystemHealth({ probeDb: false });+ const cfg = sub(health, 'x402_config');+ expect(cfg.status).toBe('degraded');+ expect(cfg.detail).toMatch(/fee.?payer/i);+ });++ it('reports world as UNKNOWN when no world-health report has been parked', async () => {+ const health = await gatherSubsystemHealth({ probeDb: false });+ expect(sub(health, 'world').status).toBe('unknown');+ });++ it('reports world as DEGRADED (unprotected) from a parked world-health outcome', async () => {+ await cacheSet(+ 'world:health',+ { status: 'degraded', protected: false, problems: ['unprotected'], missingCount: 0, checkedAt: Date.now() },+ 3600,+ );+ const health = await gatherSubsystemHealth({ probeDb: false });+ const world = sub(health, 'world');+ expect(world.status).toBe('degraded');+ expect(world.detail).toMatch(/UNPROTECTED/);+ expect(world.hint).toMatch(/ADMIN_CODE/);+ });++ it('reports cache as OK on the in-memory backend when no Redis is configured', async () => {+ const health = await gatherSubsystemHealth({ probeDb: false });+ const cache = sub(health, 'cache');+ expect(cache.status).toBe('ok');+ expect(cache.backend).toBe('memory');+ });++ it('reports Helius as OK (public RPC) when no Helius key is configured', async () => {+ const health = await gatherSubsystemHealth({ probeDb: false });+ expect(sub(health, 'helius').status).toBe('ok');+ });++ it('skips the DB ping when probeDb is false (database → unknown, not down)', async () => {+ const health = await gatherSubsystemHealth({ probeDb: false });+ expect(sub(health, 'database').status).toBe('unknown');+ });++ it('rolls the overall verdict to the worst subsystem and lists degraded names', async () => {+ process.env.X402_PAY_TO_SOLANA = 'THREEsynthetic1111111111111111111111111111111';+ delete process.env.X402_FEE_PAYER_SOLANA; // → x402_config degraded+ const health = await gatherSubsystemHealth({ probeDb: false });+ expect(health.status).toBe('degraded');+ expect(health.degraded).toContain('x402_config');+ // Counts is a tally of every status bucket.+ expect(Object.values(health.counts).reduce((a, b) => a + b, 0)).toBe(health.subsystems.length);+ });+});diff --git a/tests/x402-audit-buffer.test.js b/tests/x402-audit-buffer.test.jsnew file mode 100644index 000000000..4b56ccf67--- /dev/null+++ b/tests/x402-audit-buffer.test.js@@ -0,0 +1,132 @@+// Tests for the x402 audit-log write buffer (api/_lib/x402/audit-log.js).+//+// Hot paid routes queue one audit write per request. Firing each as its own Neon+// HTTP fetch turned a slow-DB spell into a self-amplifying storm, so writes are+// coalesced into a Redis list and drained by a batch flusher off the request path+// (the same buffer→cron pattern as usage events). These tests cover:+// 1. logPaymentEvent pushes to the Redis buffer instead of hitting Postgres.+// 2. logPaymentEvent falls back to a bounded direct insert when Redis is absent.+// 3. flushAuditBuffer drains the buffer as ONE multi-row INSERT and trims it.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// ── Fakes ─────────────────────────────────────────────────────────────────────+// A minimal in-memory Redis list supporting exactly the ops the buffer uses.+function makeFakeRedis() {+ let list = [];+ return {+ _list: () => list,+ _set: (v) => { list = v; },+ rpush: vi.fn(async (_k, v) => list.push(v)),+ lrange: vi.fn(async (_k, start, stop) => list.slice(start, stop + 1)),+ ltrim: vi.fn(async (_k, start, stop) => { list = list.slice(start, stop === -1 ? undefined : stop + 1); }),+ llen: vi.fn(async () => list.length),+ expire: vi.fn(async () => 1),+ };+}++let fakeRedis = null; // null → Redis unavailable+const sqlCalls = [];+const sqlImpl = vi.fn(async (...args) => { sqlCalls.push(args); return []; });++vi.mock('../api/_lib/redis.js', () => ({+ getRedis: () => fakeRedis,+ isRedisAuthError: () => false,+}));+vi.mock('../api/_lib/db.js', () => ({ sql: (...args) => sqlImpl(...args) }));+// Pass-through retry wrapper so the direct-insert path actually calls sql.+vi.mock('../api/_lib/db-retry.js', () => ({ withDbRetry: (run) => run() }));++const { logPaymentEvent, flushAuditBuffer } = await import('../api/_lib/x402/audit-log.js');++// logPaymentEvent runs its work in a queueMicrotask; let it settle.+const settle = () => new Promise((r) => setTimeout(r, 0));++const EVENT = {+ eventType: 'siwx_grant',+ route: '/api/x402/dance-tip',+ payer: 'Payer1111111111111111111111111111111111111',+ network: 'solana:mainnet',+ amountAtomics: '1000',+ metadata: { ttlSeconds: 3600 },+};++beforeEach(() => {+ fakeRedis = makeFakeRedis();+ sqlCalls.length = 0;+ sqlImpl.mockClear();+});++describe('logPaymentEvent — buffered write path', () => {+ it('pushes to the Redis buffer and does NOT touch Postgres', async () => {+ logPaymentEvent(EVENT);+ await settle();+ expect(fakeRedis.rpush).toHaveBeenCalledTimes(1);+ expect(sqlImpl).not.toHaveBeenCalled();+ // The buffered record is a normalized positional row (14 columns).+ const stored = JSON.parse(fakeRedis._list()[0]);+ expect(Array.isArray(stored)).toBe(true);+ expect(stored).toHaveLength(14);+ expect(stored[0]).toBe('siwx_grant');+ expect(stored[1]).toBe('/api/x402/dance-tip');+ // JSON columns are pre-stringified in the record.+ expect(stored[13]).toBe(JSON.stringify({ ttlSeconds: 3600 }));+ });++ it('sets the buffer TTL exactly once (on the first push)', async () => {+ logPaymentEvent(EVENT);+ await settle();+ logPaymentEvent(EVENT);+ await settle();+ expect(fakeRedis.expire).toHaveBeenCalledTimes(1);+ });++ it('falls back to a bounded direct insert when Redis is unavailable', async () => {+ fakeRedis = null;+ logPaymentEvent(EVENT);+ await settle();+ expect(sqlImpl).toHaveBeenCalledTimes(1);+ const [text, params] = sqlCalls[0];+ expect(text).toMatch(/INSERT INTO x402_audit_log/);+ expect(text).toMatch(/VALUES \(\$1/);+ expect(params).toHaveLength(14);+ expect(params[0]).toBe('siwx_grant');+ });+});++describe('flushAuditBuffer — batched drain', () => {+ it('drains many rows as ONE multi-row INSERT and empties the buffer', async () => {+ // Seed 3 buffered rows directly.+ for (let i = 0; i < 3; i++) { logPaymentEvent({ ...EVENT, amountAtomics: String(i) }); await settle(); }+ expect(fakeRedis._list()).toHaveLength(3);++ const res = await flushAuditBuffer({ limit: 100 });+ expect(res.flushed).toBe(3);+ expect(res.remaining).toBe(0);+ expect(res.errors).toBe(0);+ // A single INSERT statement carried all three rows: 3 rows × 14 cols = 42 params.+ expect(sqlImpl).toHaveBeenCalledTimes(1);+ const [text, params] = sqlCalls[0];+ expect(text).toMatch(/^INSERT INTO x402_audit_log/);+ expect(params).toHaveLength(42);+ // JSONB columns get a ::jsonb cast on their placeholders.+ expect(text).toContain('::jsonb');+ expect(fakeRedis._list()).toHaveLength(0);+ });++ it('no-ops cleanly when Redis is unavailable', async () => {+ fakeRedis = null;+ const res = await flushAuditBuffer({ limit: 100 });+ expect(res).toMatchObject({ flushed: 0, skipped: 'redis_unavailable' });+ expect(sqlImpl).not.toHaveBeenCalled();+ });++ it('trims consumed rows even when the batch INSERT fails (no infinite retry)', async () => {+ logPaymentEvent(EVENT); await settle();+ sqlImpl.mockRejectedValueOnce(new Error('db query exceeded 3000ms deadline'));+ const res = await flushAuditBuffer({ limit: 100 });+ expect(res.errors).toBe(1);+ expect(res.remaining).toBe(0); // consumed rows are dropped, not re-queued forever+ expect(fakeRedis._list()).toHaveLength(0);+ });+});diff --git a/tests/x402-ring-invariants.test.js b/tests/x402-ring-invariants.test.jsindex 68ae47d28..06e5695d9 100644--- a/tests/x402-ring-invariants.test.js+++ b/tests/x402-ring-invariants.test.js@@ -24,6 +24,7 @@ const RING_VARS = ['X402_FACILITATOR_URL_SOLANA', 'X402_FACILITATOR_URL', 'PUBLIC_APP_ORIGIN','X402_SEED_SOLANA_SECRET_BASE58', 'X402_AGENT_SOLANA_SECRET_BASE58','X402_PAY_TO_SOLANA', 'X402_FEE_PAYER_SOLANA', 'X402_SELF_FACILITATOR_PAYTO_ALLOWLIST',+ 'X402_RING_PAUSED',];function healthyEnv() {@@ -117,6 +118,25 @@ describe('assertRingSpendInvariants — fail closed + one throttled alert', () =// dedup signature keys on the sorted flag set so repeated ticks don't flood.expect(opts.signature).toContain('ring-invariant:');});++ it('X402_RING_PAUSED=true stops spending quietly (fail-closed, no alert)', async () => {+ healthyEnv(); // guards all hold — the pause, not a violation, is what stops it+ process.env.X402_RING_PAUSED = 'true';+ const r = await assertRingSpendInvariants({ context: 'x402-autonomous-loop' });+ expect(r.ok).toBe(false);+ expect(r.paused).toBe(true);+ expect(r.violations).toHaveLength(0);+ expect(sendOpsAlert).not.toHaveBeenCalled();+ });++ it('pause is checked before guard violations — a deliberate pause never alerts', async () => {+ process.env.X402_RING_PAUSED = 'true';+ process.env.X402_EXTERNAL_ENABLED = 'true'; // a real violation is also present+ const r = await assertRingSpendInvariants({ context: 'x402-ring-tick' });+ expect(r.ok).toBe(false);+ expect(r.paused).toBe(true);+ expect(sendOpsAlert).not.toHaveBeenCalled();+ });});describe('ringAllowedAddresses', () => {diff --git a/vercel.json b/vercel.jsonindex b9ea37a9e..08bca1689 100644--- a/vercel.json+++ b/vercel.json@@ -2,6 +2,7 @@"buildCommand": "npm run build:vercel","outputDirectory": "dist","installCommand": "npm ci --no-audit --no-fund",+ "ignoreCommand": "bash scripts/vercel-ignore-build.sh","env": {"NODE_OPTIONS": "--no-deprecation"},diff --git a/workers/agent-sniper/auto-funder.js b/workers/agent-sniper/auto-funder.jsindex 0877cee06..97ca84537 100644--- a/workers/agent-sniper/auto-funder.js+++ b/workers/agent-sniper/auto-funder.js@@ -41,15 +41,37 @@ const TARGET_SOL = Math.max(MIN_SOL, num('SNIPER_AUTO_FUND_TARGET_SOL', 0.05));const PER_TX_CAP_SOL = Math.max(0, num('SNIPER_AUTO_FUND_PER_TX_SOL', 0.1));const DAILY_CAP_SOL = Math.max(0, num('SNIPER_AUTO_FUND_DAILY_SOL', 1.0));-/** Unique agent ids across the armed strategy set for this network. */-function activeAgentIds(network) {+/**+ * Agent ids eligible for auto-funding on this network.+ *+ * Explicit consent only: a strategy must set `auto_fund_enabled = true` before+ * its agent's wallet may be topped up from the launcher master. Merely arming a+ * strategy (enabled=true) moves NO money — that implicit trigger was the+ * "arming a mainnet strategy silently pushes SOL from a master" footgun. A+ * missing/false flag (e.g. before the consent migration is applied) is treated+ * as "do not fund", so the safe default holds even mid-migration.+ *+ * Pure over its `strategies` arg so it can be unit-tested without the cache.+ *+ * @param {Array<{agent_id?: string, network?: string, auto_fund_enabled?: boolean}>} strategies+ * @param {string} network+ * @returns {string[]}+ */+export function optedInAgentIds(strategies, network) {const ids = new Set();- for (const s of cachedStrategies()) {- if (s.agent_id && s.network === network) ids.add(s.agent_id);+ for (const s of strategies || []) {+ if (s.agent_id && s.network === network && s.auto_fund_enabled === true) {+ ids.add(s.agent_id);+ }}return [...ids];}+/** Unique agent ids that have opted into auto-funding for this network. */+function activeAgentIds(network) {+ return optedInAgentIds(cachedStrategies(), network);+}+/** SOL actually moved (live) since the start of the UTC day — the daily-cap base. */async function dailyFundedSol(network) {const [row] = await sql`@@ -191,6 +213,8 @@ export function startAutoFunderWatch({ cfg, signal } = {}) {log.info('auto-funder armed', {network: cfg.network, mode: cfg.mode, pollMs: POLL_INTERVAL_MS,minSol: MIN_SOL, targetSol: TARGET_SOL, perTxCapSol: PER_TX_CAP_SOL, dailyCapSol: DAILY_CAP_SOL,+ // Consent is explicit and per-strategy — this is how many agents can be funded at all.+ optedInAgents: activeAgentIds(cfg.network).length,});// Warn loudly if live funding is armed but the master wallet is unconfigured —diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.jsindex 83b388205..89be1ee8b 100644--- a/workers/agent-sniper/config.js+++ b/workers/agent-sniper/config.js@@ -35,6 +35,31 @@ function bool(name, def = false) {return /^(1|true|yes|on)$/i.test(String(raw).trim());}+// Parse a comma/space/newline-separated allowlist of agent UUIDs. Returns a+// de-duped array, or null when unset/empty (null = "all agents", the default).+// Exported for unit testing — the scoping fix that keeps a worker from acting on+// every armed strategy in the shared DB depends on this being exact.+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+export function parseAgentIds(raw) {+ if (raw == null || String(raw).trim() === '') return null;+ const ids = String(raw)+ .split(/[\s,]+/)+ .map((s) => s.trim().toLowerCase())+ .filter(Boolean)+ .filter((s) => UUID_RE.test(s));+ if (!ids.length) return null;+ return [...new Set(ids)];+}++// Resolve the RPC endpoint the worker's read paths (e.g. the Mayhem curve read)+// should use. Prefer an explicit URL, then a Helius key, else empty (callers+// fall back to a public mainnet endpoint).+function resolveRpcUrl() {+ if (process.env.SOLANA_RPC_URL) return process.env.SOLANA_RPC_URL.trim();+ if (process.env.HELIUS_API_KEY) return `https://mainnet.helius-rpc.com/?api-key=${process.env.HELIUS_API_KEY.trim()}`;+ return '';+}+export function loadConfig() {// DATABASE_URL + JWT_SECRET are consumed transitively by db.js / agent-wallet.js.// We assert them here so the failure points at config, not a cryptic decrypt@@ -63,6 +88,23 @@ export function loadConfig() {return {network,mode,+ // Resolved RPC endpoint, shared by the worker's read paths (Mayhem curve read).+ rpcUrl: resolveRpcUrl(),+ // ── agent scoping ────────────────────────────────────────────────────────+ // Optional allowlist of agent UUIDs. When set, the worker acts ONLY on these+ // agents' strategies — the rest of the shared DB's armed strategies are+ // ignored. Unset (null) = every enabled strategy for the network, the legacy+ // behaviour. Set this to run a bounded experiment/fleet against the prod DB+ // without entangling it with every other armed agent.+ agentIds: parseAgentIds(process.env.SNIPER_AGENT_IDS),+ // ── Mayhem exclusion (owner rule) ────────────────────────────────────────+ // NEVER buy pump.fun "Mayhem"-mode tokens — only regular launches. Reads the+ // bonding curve's isMayhemMode once per mint (cached). On by default; set+ // SNIPER_MAYHEM_FILTER=0 to disable. SNIPER_MAYHEM_STRICT=1 skips a buy when+ // the curve can't be read (default allows-on-unknown so a flaky RPC read+ // can't silently halt trading).+ mayhemFilter: bool('SNIPER_MAYHEM_FILTER', true),+ mayhemStrict: bool('SNIPER_MAYHEM_STRICT', false),// Global emergency stop — set SNIPER_GLOBAL_KILL=1 to halt all new buys// while still letting the position loop manage/exit open positions.globalKill: bool('SNIPER_GLOBAL_KILL', false),diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex 9ec4ee234..f42d5445d 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -8,6 +8,7 @@import { sql } from '../../api/_lib/db.js';import { log } from './log.js';import { loadAgentKeypair } from './keys.js';+import { mayhemGate } from './mayhem-gate.js';import { getTradeCtx, signAndSend, submitProtectedTrade } from './trade-client.js';import { countOpenPositions, getDailySpend } from './strategy-store.js';import { notifyBuy, notifySell } from '../../api/_lib/sniper/notify.js';@@ -233,6 +234,14 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {const perTrade = BigInt(strat.per_trade_lamports);const tag = { agent: strat.agent_id, mint: mint.mint, symbol: mint.symbol };+ // 0. Mayhem exclusion (owner rule) — NEVER buy pump.fun Mayhem tokens, only+ // regular launches. First gate, so a Mayhem mint costs no throttle slot,+ // no decrypt, and no position row. This is the chokepoint every trigger+ // path (new_mint / intel / alpha / first_claim / radar / swarm) flows+ // through, so the rule holds everywhere, not just the standalone fleet.+ const mayhem = await mayhemGate(mint.mint, cfg);+ if (!mayhem.pass) return skip(tag, mayhem.reason);+// 1. global throttle (platform-wide backstop)if (!throttle.tryConsume()) return skip(tag, 'global_throttle');@@ -257,12 +266,35 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {if (policy.blocked) return skip(tag, policy.reason);const spendCapabilityId = policy.capabilityId || null;- // 4. idempotency lock — claim the (agent,mint,network) slot BEFORE the tx.+ // 4. wallet + funds PRE-CHECK, before claiming a slot. An agent with no+ // wallet or too little SOL can never fill the buy — skip it cleanly rather+ // than write a 'failed' position row that only noises up the feeds. (These+ // were the dominant 'failed' rows: every unfunded agent evaluating every+ // mint left one behind.)+ let keypair;+ let address;+ let ctx;+ let preBalance;+ try {+ const loaded = await loadAgentKeypair(strat.agent_id, strat.user_id, 'sniper_buy');+ if (!loaded) return skip(tag, 'no_wallet');+ ({ keypair, address } = loaded);+ ctx = await getTradeCtx(cfg.network);+ preBalance = BigInt(await ctx.connection.getBalance(keypair.publicKey, 'confirmed'));+ } catch (err) {+ log.warn('wallet precheck failed', { ...tag, err: err?.message });+ return skip(tag, 'wallet_precheck_failed');+ }+ const headroom = checkSolHeadroom(preBalance, perTrade, SOL_FEE_HEADROOM_LAMPORTS);+ if (headroom) return skip(tag, headroom.reason);++ // 5. idempotency lock — claim the (agent,mint,network) slot BEFORE the tx.+ // The wallet is known now, so it's written on the claim (no later UPDATE).const claimed = await sql`INSERT INTO agent_sniper_positions(strategy_id, agent_id, user_id, wallet, network, mint, symbol, name, status,entry_trigger, trigger_ref)- VALUES (${strat.id}, ${strat.agent_id}, ${strat.user_id}, ${'pending'}, ${cfg.network},+ VALUES (${strat.id}, ${strat.agent_id}, ${strat.user_id}, ${address}, ${cfg.network},${mint.mint}, ${mint.symbol || null}, ${mint.name || null}, 'opening',${mint.entry_trigger || 'new_mint'}, ${mint.trigger_ref || null})ON CONFLICT (agent_id, mint, network) DO NOTHING@@ -272,17 +304,6 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {const posId = claimed[0].id;try {- // 5. agent wallet + funds- const loaded = await loadAgentKeypair(strat.agent_id, strat.user_id, 'sniper_buy');- if (!loaded) return await fail(posId, tag, 'no_wallet');- const { keypair, address } = loaded;- await sql`UPDATE agent_sniper_positions SET wallet = ${address} WHERE id = ${posId}`;-- const ctx = await getTradeCtx(cfg.network);- const lamports = BigInt(await ctx.connection.getBalance(keypair.publicKey, 'confirmed'));- const headroom = checkSolHeadroom(lamports, perTrade, SOL_FEE_HEADROOM_LAMPORTS);- if (headroom) return await fail(posId, tag, headroom.reason);-const mintPk = new ctx.web3.PublicKey(mint.mint);const slippagePct = strat.slippage_bps / 100;diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.jsindex 682afbf45..633515371 100644--- a/workers/agent-sniper/index.js+++ b/workers/agent-sniper/index.js@@ -99,7 +99,9 @@ async function main() {let feedConnected = false;let reconnectCount = 0;- await refreshStrategies(cfg.network, 0).then(() => logStrategyLoad(cfg.network)).catch((err) =>+ if (cfg.agentIds) log.info('agent scope active', { agents: cfg.agentIds.length });+ log.info('mayhem filter', { enabled: cfg.mayhemFilter, strict: cfg.mayhemStrict });+ await refreshStrategies(cfg.network, 0, cfg.agentIds).then(() => logStrategyLoad(cfg.network)).catch((err) =>log.error('initial strategy load failed', { err: err?.message }),);@@ -263,7 +265,7 @@ async function main() {// Strategy cache refresh.const strategyTimer = setInterval(() => {- refreshStrategies(cfg.network, cfg.strategyRefreshMs)+ refreshStrategies(cfg.network, cfg.strategyRefreshMs, cfg.agentIds).then(() => logStrategyLoad(cfg.network)).catch((err) => log.error('strategy refresh failed', { err: err?.message }));}, cfg.strategyRefreshMs);diff --git a/workers/agent-sniper/mayhem-gate.js b/workers/agent-sniper/mayhem-gate.jsnew file mode 100644index 000000000..b2c42a3d7--- /dev/null+++ b/workers/agent-sniper/mayhem-gate.js@@ -0,0 +1,67 @@+// agent-sniper — Mayhem exclusion gate (owner rule).+//+// Owner rule: the autonomous sniper must NEVER buy pump.fun "Mayhem" tokens —+// only the regular (non-Mayhem) launches. Mayhem is a higher-fee, buyback-less+// "degen" mode flagged on the on-chain bonding curve as `isMayhemMode`; the+// new-mint firehose does NOT carry the flag, so it's read from the curve (one+// cached RPC read per mint, shared across every agent evaluating that mint).+//+// This wires the already-tested filter from @three-ws/agent-sniper+// (packages/agent-sniper/scripts/mayhem-filter.js) into the DB-coupled worker's+// buy chokepoint (executor.executeBuy), so EVERY trigger path — new_mint, intel,+// alpha, first_claim, radar, swarm — is covered, not just the standalone fleet.+//+// SNIPER_MAYHEM_FILTER=0 — disable the gate entirely (default: on)+// SNIPER_MAYHEM_STRICT=1 — skip the buy when the curve can't be read+// (default: allow-on-unknown, logged), so a flaky+// RPC read can't silently halt all trading.++import { createMayhemFilter } from '../../packages/agent-sniper/scripts/mayhem-filter.js';+import { log } from './log.js';++/**+ * Pure verdict from a resolved isMayhemMode read. Extracted so the decision is+ * unit-testable without an RPC/SDK. `null` = couldn't read the curve (unknown).+ * @param {boolean|null} isMayhem+ * @param {{ strict?: boolean }} [opts]+ * @returns {{ pass: boolean, reason?: string, unknown?: boolean }}+ */+export function mayhemVerdict(isMayhem, { strict = false } = {}) {+ if (isMayhem === true) return { pass: false, reason: 'mayhem_excluded' };+ if (isMayhem === null || isMayhem === undefined) {+ return strict ? { pass: false, reason: 'mayhem_unknown', unknown: true } : { pass: true, unknown: true };+ }+ return { pass: true };+}++let _filter = null;+function getFilter(cfg) {+ if (_filter) return _filter;+ _filter = createMayhemFilter({ rpcUrl: cfg?.rpcUrl || undefined, strictOnUnknown: !!cfg?.mayhemStrict });+ return _filter;+}++/**+ * Gate one mint. Returns { pass, reason }. Never throws — an internal failure is+ * treated as "unknown" and resolved by the strict flag, so the gate can't stall+ * the trader. No-op pass-through when the filter is disabled.+ * @param {string} mint+ * @param {object} cfg worker config (uses cfg.mayhemFilter, cfg.mayhemStrict, cfg.rpcUrl)+ * @returns {Promise<{ pass: boolean, reason?: string }>}+ */+export async function mayhemGate(mint, cfg) {+ if (!cfg?.mayhemFilter) return { pass: true };+ try {+ const isMayhem = await getFilter(cfg).isMayhem(mint);+ const v = mayhemVerdict(isMayhem, { strict: !!cfg.mayhemStrict });+ if (v.unknown) log.info('mayhem unknown', { mint, strict: !!cfg.mayhemStrict, pass: v.pass });+ return { pass: v.pass, reason: v.reason };+ } catch (err) {+ const v = mayhemVerdict(null, { strict: !!cfg.mayhemStrict });+ log.warn('mayhem check failed', { mint, err: err?.message, pass: v.pass });+ return { pass: v.pass, reason: v.reason };+ }+}++/** Test seam: reset the memoized filter singleton. */+export function _resetMayhemFilter() { _filter = null; }diff --git a/workers/agent-sniper/strategy-store.js b/workers/agent-sniper/strategy-store.jsindex d2c66abc5..80fc49447 100644--- a/workers/agent-sniper/strategy-store.js+++ b/workers/agent-sniper/strategy-store.js@@ -12,8 +12,14 @@ let _loadedAt = 0;* the mandatory-SL guarantee (the DB constraint is the other half) — a strategy* that somehow has a null/zero SL is dropped here rather than trusted.*/-export async function refreshStrategies(network, maxAgeMs) {+export async function refreshStrategies(network, maxAgeMs, agentIds = null) {if (Date.now() - _loadedAt < maxAgeMs && _strategies.length) return _strategies;+ // Optional agent-scoping: when an allowlist is supplied the worker acts ONLY on+ // those agents' strategies. This is the guard that lets a worker run against the+ // shared prod DB without touching every other armed agent's strategy — the+ // entanglement that otherwise makes an experiment spend on, and trade for, coins+ // it never provisioned.+ const scope = Array.isArray(agentIds) && agentIds.length ? sql`AND agent_id = ANY(${agentIds})` : sql``;const rows = await sql`SELECT * FROM agent_sniper_strategiesWHERE network = ${network}@@ -22,6 +28,7 @@ export async function refreshStrategies(network, maxAgeMs) {AND daily_budget_lamports > 0AND per_trade_lamports > 0AND stop_loss_pct > 0+ ${scope}`;_strategies = rows;_loadedAt = Date.now();