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
Sniper experiment fleet: rules vs LLM judgment, plus the three fixes that unblocked buying
nirholasc3cfeadf68ab
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 969bc27eb..6599201bd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Motion Swap: replace yourself in a video with your 3D avatar** — Upload a video of yourself (a house tour, a demo, a walk-through) at /motion-swap and get it back with your avatar performing your exact motion instead of you. The platform tracks your body pose in every frame, masks you out, and pins your chosen avatar over you, matching your position and size; you stay pixelated underneath. Compositing and video export run right in your browser, and any rigged humanoid GLB works, including avatars you generated or captured from a selfie. (`/motion-swap`) `[feature]`- **Switch any coin chart between CoinGecko, TradingView, DexScreener, and GeckoTerminal** — The chart on every /coin page now has a source switcher. Start on the fast native CoinGecko line chart, then flip to TradingView's advanced candlesticks, or to the DexScreener or GeckoTerminal on-chain terminal for the token's live DEX pair. Each option only appears when it can actually chart that coin, your pick is remembered across coins and visits, and every view follows the site theme. (`/coin/bitcoin`) `[feature, improvement]`- **The assistant widget ships as an npm package and an MCP server** — The 3D avatar assistant widget is now installable three ways. Beyond the one-tag script, there is an npm package, @three-ws/assistant, for bundler projects (the one-tag build is generated from it, so they never drift), and a free MCP server, @three-ws/assistant-mcp, published to the official Model Context Protocol registry as io.github.nirholas/assistant-widget. Any AI agent (Claude Code, Cursor, Claude Desktop) can now ask for a widget in plain language and get back a paste-ready embed: build_assistant_widget turns a config into a script tag, a frame URL, and a ThreeAssistant.init() call, and list_assistant_options returns every avatar, background, and mode. Full developer docs at /docs/assistant-widget and a step-by-step tutorial walk through every option, the JavaScript API, and the agent workflow. (`/docs/assistant-widget`) `[sdk, feature, docs]`+- **The sniper fleet becomes a live experiment: rules vs AI judgment** — The autonomous pump.fun sniper now runs ten labeled strategies side by side to learn which entry conditions actually make money. Some agents trade strict rule shields (market-cap bands, socials, Oracle conviction), and three new agents have no rules at all: an AI model (Grok, Claude, or an auto-router) reads every launch and decides with a written thesis, while the same hard safety rails (no Mayhem tokens, honeypot firewall, budgets and stop-losses) protect every trade. A new scoreboard at /sniper/experiments compares each arm by real on-chain results. Under the hood the sniper also got three reliability fixes that unblocked buying: safety reads now rotate across many RPC providers with retries, provisional Oracle scores on brand-new coins no longer disqualify launch snipes, and a stuck position whose sell had already landed on-chain is now reconciled from the chain instead of retrying forever. (`/sniper/experiments`) `[feature, improvement, fix]`- **TradingView charts on every coin page** — Every /coin page (like /coin/bitcoin) now has a chart-source toggle. Keep the fast native line chart, or switch to a full advanced candlestick chart with indicators and drawing tools. Listed coins open on TradingView; Solana DEX tokens that TradingView doesn't carry open on DexScreener instead, so the advanced view works on every coin. Your choice is remembered across coins and visits, and the chart follows the site theme. (`/coin/bitcoin`) `[feature]`## 2026-07-18diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 49c3cc8d8..d1fef6f8a 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -106,6 +106,7 @@ bottom.| Economy funding root (master wallet) | [api/_lib/economy-master.js](api/_lib/economy-master.js), cron [api/cron/treasury-topup.js](api/cron/treasury-topup.js), registry [api/_lib/solana-signers.js](api/_lib/solana-signers.js) | In-repo (inert until keyed) | One master wallet (`WwwuGbq…T3WwW`, `ECONOMY_MASTER_SECRET_BASE58`) auto-tops-up every other Solana engine below its floor. Funder-only — never trades/settles; reserve/per-engine/per-run guarded; allowlisted to registry wallets; fee-minimized. See [docs/economy-master.md](docs/economy-master.md) + the signer registry [api/_lib/solana-signers.js](api/_lib/solana-signers.js) || Economy master audit ledger + breach monitor | ledger [api/_lib/economy-ledger.js](api/_lib/economy-ledger.js) ([schema](api/_lib/migrations/20260702010000_economy_master_ledger.sql)), reconcile cron [api/cron/economy-reconcile.js](api/cron/economy-reconcile.js), export [scripts/economy-ledger-export.mjs](scripts/economy-ledger-export.mjs) | In-repo | Tamper-evident (SHA-256 hash-chained) accounting book of every SOL movement from the master, with running balance + USD-at-transfer-time. The reconcile cron checks it every 30 min for tamper, unrecorded on-chain outbound (breach/key-compromise), and on-chain integrity; findings land in `payment_reconciliation`. Accounting CSV/JSON export. See [docs/economy-master.md](docs/economy-master.md#audit-accounting--breach-monitoring) || Autonomous trading experiment | policy [scripts/trading-experiment-setup.mjs](scripts/trading-experiment-setup.mjs), laddered exit [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`decideLadderedExit`), no-Mayhem gate [workers/agent-sniper/mayhem-gate.js](workers/agent-sniper/mayhem-gate.js), journal [workers/agent-sniper/journal.js](workers/agent-sniper/journal.js) → [api/sniper/journal.js](api/sniper/journal.js) | In-repo | One agent, ~10 SOL, newer pump.fun launches ($10k–$100k mcap, no Mayhem). Take-initials-at-2× laddered exit keeps a moon bag (never a 100% exit up), hard stop-loss underneath. Every decision journaled with its reasoning. UI-funded, simulate-first. See [docs/trading-experiment.md](docs/trading-experiment.md) |+| Sniper Experiments (rules vs LLM A/B fleet) | [pages/sniper-experiments.html](pages/sniper-experiments.html) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments`, aggregate [api/sniper/experiments.js](api/sniper/experiments.js), LLM judge [workers/agent-sniper/llm-judge.js](workers/agent-sniper/llm-judge.js), fleet seeding [scripts/seed-sniper-experiments.mjs](scripts/seed-sniper-experiments.mjs) | Live | The sniper fleet runs labeled rule-set variants side by side (strict shields, oracle-gated, and `decision_mode=llm` arms judged per-launch by Grok / Claude / OpenRouter auto with no shields), all behind the same safety rails. The page is the live scoreboard of which entry conditions actually make money; real on-chain fills only. || Trading Copilot (conversational) | client [src/agent-copilot.js](src/agent-copilot.js), hub tab [src/agent-wallet-hub/tabs/copilot.js](src/agent-wallet-hub/tabs/copilot.js), server [api/agents/copilot.js](api/agents/copilot.js) `→ POST /api/agents/:id/copilot` (SSE) | In-repo | Owner-only chat over an agent's Solana wallet: text/voice in, markdown replies, live **data cards** (portfolio, firewall, quote, smart-money, intel) and **confirm-before-execute** trade/limits cards. Read-only tools run server-side; state-changing intents return as proposals the browser re-quotes and runs through the existing spend guards + firewall + custody audit. Slash commands, copy/regenerate, localStorage persistence. See [docs/trading-copilot.md](docs/trading-copilot.md) || Real-funds risk acknowledgment | gate [public/risk-ack.js](public/risk-ack.js) `→ /legal/risk`, app wrapper [src/shared/risk-ack.js](src/shared/risk-ack.js), record endpoint [api/legal/risk-ack.js](api/legal/risk-ack.js), disclosure [public/legal/risk.html](public/legal/risk.html) | In-repo | Versioned, once-per-browser acceptance dialog every money-committing surface awaits before executing (trade, snipe, withdraw, swap, launch, x402, onramp — devnet exempt). Acceptances persist in `audit_log` (`risk-ack-accept`). See [docs/risk-acknowledgment.md](docs/risk-acknowledgment.md) || Global markets + coin detail pages | [pages/coins.html](pages/coins.html) + [src/coins-index.js](src/coins-index.js) `→ /coins`, [pages/coin.html](pages/coin.html) + [src/coin-page.js](src/coin-page.js) `→ /coin/:id`, backend [api/coin/](api/coin) (detail, tickers, ohlc, pool, markets, news, global over [api/_lib/coingecko.js](api/_lib/coingecko.js)) | In-repo | CoinGecko-style markets index (global stats bar, sortable top-coins table, search, sparklines) + a rich detail page per coin: interactive chart with a source switcher (native CoinGecko line chart, TradingView advanced candlesticks, or the DexScreener / GeckoTerminal on-chain terminal — each shown only when it can chart the coin; GeckoTerminal's pool resolved via [api/coin/pool.js](api/coin/pool.js)), 1h→1y price-performance matrix, market-stats grid, circulating/max supply bar with Mcap/FDV ratio, ATH/ATL with drawdown & recovery multiple, community sentiment vote split, community + developer (GitHub) activity grids, a paginated exchange-listings table (`api/coin/tickers`, ±2% depth + trust) linking into exchange detail, related news, and full link pills (site/social/whitepaper/forum/chat/explorers). Design adopted from cryptocurrency.cv; accepts CoinGecko slugs or Solana mints. Docs: [docs/coin-pages.md](docs/coin-pages.md) |diff --git a/api/_lib/migrations/20260719120000_sniper_llm_experiments.sql b/api/_lib/migrations/20260719120000_sniper_llm_experiments.sqlnew file mode 100644index 000000000..8d832abd3--- /dev/null+++ b/api/_lib/migrations/20260719120000_sniper_llm_experiments.sql@@ -0,0 +1,20 @@+-- Sniper strategy experiments + LLM-judged decision mode.+--+-- decision_mode: 'rules' (default, the existing scorer/oracle gate chain) or+-- 'llm', the strategy skips the rule shields (mcap band, socials, oracle+-- threshold, creator gates) and asks a model to judge each launch instead. The+-- non-negotiable safety rails (Mayhem exclusion, trade firewall, budgets,+-- concurrency, headroom, spend policy) still apply to BOTH modes at the+-- executeBuy chokepoint.+--+-- label / experiment_group: human-readable identity for the A/B fleet so+-- performance can be compared per rule set ("which conditions actually win?")+-- rather than per anonymous strategy id. Read by /api/sniper/experiments.+--+-- Additive and idempotent, safe to re-run.+ALTER TABLE agent_sniper_strategies+ ADD COLUMN IF NOT EXISTS decision_mode TEXT NOT NULL DEFAULT 'rules',+ ADD COLUMN IF NOT EXISTS llm_model TEXT,+ ADD COLUMN IF NOT EXISTS llm_min_confidence NUMERIC,+ ADD COLUMN IF NOT EXISTS label TEXT,+ ADD COLUMN IF NOT EXISTS experiment_group TEXT;diff --git a/api/sniper/experiments.js b/api/sniper/experiments.jsnew file mode 100644index 000000000..17bf82fc9--- /dev/null+++ b/api/sniper/experiments.js@@ -0,0 +1,135 @@+/**+ * Agent Sniper, strategy experiment comparison.+ *+ * GET /api/sniper/experiments?network=mainnet&window=7d+ *+ * The sniper fleet runs deliberately different rule sets side by side, rule+ * shields with different thresholds, and LLM-judged arms with no shields at+ * all, to learn which entry conditions actually make money. This endpoint is+ * the scoreboard: one row per armed strategy, its human-readable label and+ * config fingerprint, and its REAL trading record (on-chain fills only, the+ * 'SIMULATED' sentinel excluded) over the window.+ *+ * Public + IP rate-limited, same trust model as /api/sniper/leaderboard: the+ * tx signatures are the proof.+ */++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';++const NETWORKS = new Set(['mainnet', 'devnet']);+const WINDOWS = { '24h': '24 hours', '7d': '7 days', '30d': '30 days', all: null };++function lamportsToSol(v) {+ return v == null ? null : Number((Number(BigInt(v)) / 1e9).toFixed(6));+}++// One-line human fingerprint of a strategy's entry conditions, so the+// scoreboard reads as "what rules produced this record" without a schema tour.+function conditionSummary(s) {+ if ((s.decision_mode || 'rules') === 'llm') {+ const conf = s.llm_min_confidence != null ? ` ≥${Math.round(Number(s.llm_min_confidence) * 100)}%` : '';+ return `LLM judge (${s.llm_model || 'openrouter/auto'}${conf}), no rule shields`;+ }+ const parts = [`trigger ${s.trigger || 'new_mint'}`];+ if (s.min_market_cap_usd != null || s.max_market_cap_usd != null) {+ parts.push(`mcap $${Number(s.min_market_cap_usd || 0) / 1000}k-$${s.max_market_cap_usd != null ? Number(s.max_market_cap_usd) / 1000 + 'k' : '∞'}`);+ }+ if (s.require_socials) parts.push('socials required');+ if (s.min_oracle_score != null) parts.push(`oracle ≥${s.min_oracle_score}`);+ if (s.min_quality_score != null) parts.push(`quality ≥${s.min_quality_score}`);+ if (s.max_bundle_score != null) parts.push(`bundle ≤${s.max_bundle_score}`);+ if (s.require_smart_money) parts.push('smart money required');+ return parts.join(', ');+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';+ const window = Object.prototype.hasOwnProperty.call(WINDOWS, params.get('window')) ? params.get('window') : '7d';+ const interval = WINDOWS[window];++ const rows = await sql`+ select+ s.id as strategy_id,+ s.label, s.experiment_group, s.decision_mode, s.llm_model, s.llm_min_confidence,+ s.trigger, s.enabled,+ s.per_trade_lamports, s.daily_budget_lamports, s.max_concurrent_positions,+ s.min_market_cap_usd, s.max_market_cap_usd, s.require_socials,+ s.min_oracle_score, s.min_quality_score, s.max_bundle_score, s.require_smart_money,+ s.stop_loss_pct, s.trailing_stop_pct, s.take_profit_pct, s.max_hold_seconds,+ a.id as agent_id, a.name as agent_name,+ count(p.id) filter (where p.status = 'closed') as closed,+ count(p.id) filter (where p.status = 'closed' and p.realized_pnl_lamports > 0) as wins,+ count(p.id) filter (where p.status = 'open') as open,+ coalesce(sum(p.realized_pnl_lamports) filter (where p.status = 'closed'), 0) as realized_pnl_lamports,+ coalesce(sum(p.entry_quote_lamports) filter (where p.status = 'closed'), 0) as deployed_lamports,+ avg(p.realized_pnl_pct) filter (where p.status = 'closed') as avg_pnl_pct,+ max(p.realized_pnl_pct) filter (where p.status = 'closed') as best_pnl_pct,+ min(p.realized_pnl_pct) filter (where p.status = 'closed') as worst_pnl_pct,+ avg(extract(epoch from (p.closed_at - p.opened_at))) filter (where p.status = 'closed') as avg_hold_s,+ max(p.closed_at) as last_closed_at+ from agent_sniper_strategies s+ join agent_identities a on a.id = s.agent_id and a.deleted_at is null+ left join agent_sniper_positions p+ on p.strategy_id = s.id+ and p.network = s.network+ and p.buy_sig is not null and p.buy_sig <> 'SIMULATED'+ and (${interval}::text is null or p.opened_at > now() - (${interval}::text)::interval)+ where s.network = ${network}+ group by s.id, a.id, a.name+ order by realized_pnl_lamports desc, closed desc+ `;++ const experiments = rows.map((r) => {+ const closed = Number(r.closed) || 0;+ const wins = Number(r.wins) || 0;+ return {+ strategy_id: r.strategy_id,+ label: r.label || `${(r.decision_mode || 'rules') === 'llm' ? 'llm' : 'rules'}:${String(r.strategy_id).slice(0, 8)}`,+ experiment_group: r.experiment_group || null,+ agent_id: r.agent_id,+ agent_name: r.agent_name,+ decision_mode: r.decision_mode || 'rules',+ llm_model: r.llm_model || null,+ trigger: r.trigger || 'new_mint',+ enabled: r.enabled === true,+ conditions: conditionSummary(r),+ per_trade_sol: lamportsToSol(r.per_trade_lamports),+ daily_budget_sol: lamportsToSol(r.daily_budget_lamports),+ stop_loss_pct: r.stop_loss_pct != null ? Number(r.stop_loss_pct) : null,+ trailing_stop_pct: r.trailing_stop_pct != null ? Number(r.trailing_stop_pct) : null,+ take_profit_pct: r.take_profit_pct != null ? Number(r.take_profit_pct) : null,+ max_hold_seconds: r.max_hold_seconds != null ? Number(r.max_hold_seconds) : null,+ closed,+ wins,+ losses: Math.max(0, closed - wins),+ open: Number(r.open) || 0,+ win_rate: closed > 0 ? Math.round((wins / closed) * 100) : null,+ realized_pnl_sol: lamportsToSol(r.realized_pnl_lamports),+ deployed_sol: lamportsToSol(r.deployed_lamports),+ roi_pct: Number(r.deployed_lamports) > 0+ ? Number(((Number(r.realized_pnl_lamports) / Number(r.deployed_lamports)) * 100).toFixed(2))+ : null,+ avg_pnl_pct: r.avg_pnl_pct != null ? Number(Number(r.avg_pnl_pct).toFixed(2)) : null,+ best_pnl_pct: r.best_pnl_pct != null ? Number(Number(r.best_pnl_pct).toFixed(2)) : null,+ worst_pnl_pct: r.worst_pnl_pct != null ? Number(Number(r.worst_pnl_pct).toFixed(2)) : null,+ avg_hold_seconds: r.avg_hold_s != null ? Math.round(Number(r.avg_hold_s)) : null,+ last_closed_at: r.last_closed_at || null,+ };+ });++ return json(res, 200, {+ network,+ window,+ experiments,+ t: Date.now(),+ }, { 'cache-control': 'public, max-age=15, s-maxage=30' });+});diff --git a/api/sniper/strategy.js b/api/sniper/strategy.jsindex ee138f5bc..c4478d900 100644--- a/api/sniper/strategy.js+++ b/api/sniper/strategy.js@@ -106,6 +106,13 @@ const STRATEGY_SCHEMA = z.object({// Notifications: personal Telegram chat ID for this strategy's buy/sell alerts.// Must be a numeric chat ID (positive = user/group, negative = supergroup/channel).telegram_chat_id: z.string().regex(/^-?[0-9]+$/).nullable().optional(),+ // Experiment identity + decision mode. 'llm' replaces the rule shields with a+ // model verdict per launch (safety rails still enforced at executeBuy).+ decision_mode: z.enum(['rules', 'llm']).optional(),+ llm_model: z.string().max(120).nullable().optional(),+ llm_min_confidence: z.union([z.string(), z.number()]).nullable().optional(),+ label: z.string().max(80).nullable().optional(),+ experiment_group: z.string().max(80).nullable().optional(),});const atomicStr = (v, fallback = '0') => {@@ -240,6 +247,11 @@ async function listStrategies(req, res, userId) {alpha_max_mcap_usd: s.alpha_max_mcap_usd != null ? Number(s.alpha_max_mcap_usd) : null,alpha_narrative_keywords: s.alpha_narrative_keywords || null,alpha_min_quality_score: s.alpha_min_quality_score != null ? Number(s.alpha_min_quality_score) : null,+ decision_mode: s.decision_mode || 'rules',+ llm_model: s.llm_model || null,+ llm_min_confidence: s.llm_min_confidence != null ? Number(s.llm_min_confidence) : null,+ label: s.label || null,+ experiment_group: s.experiment_group || null,summary: {open_positions: sum ? Number(sum.open_positions) : 0,closed_positions: sum ? Number(sum.closed_positions) : 0,@@ -299,6 +311,8 @@ async function upsertStrategy(req, res, userId) {telegram_chat_id: null,alpha_min_smart_money: null, alpha_min_organic_score: null, alpha_max_mcap_usd: null,alpha_narrative_keywords: null, alpha_min_quality_score: null,+ decision_mode: 'rules', llm_model: null, llm_min_confidence: null,+ label: null, experiment_group: null,};const next = {@@ -350,6 +364,13 @@ async function upsertStrategy(req, res, userId) {// null = classic single-shot exit. moonbag_min_pct = the floor always kept.initials_out_multiple: 'initials_out_multiple' in p ? (p.initials_out_multiple == null || p.initials_out_multiple === '' ? null : Math.max(1.01, Number(p.initials_out_multiple))) : (cur.initials_out_multiple != null ? Number(cur.initials_out_multiple) : null),moonbag_min_pct: 'moonbag_min_pct' in p ? Math.max(0, Math.min(95, Number(p.moonbag_min_pct))) : (cur.moonbag_min_pct != null ? Number(cur.moonbag_min_pct) : 15),+ // Experiment identity + decision mode. 'llm' replaces the rule shields with+ // a per-launch model verdict; safety rails still hold at executeBuy.+ decision_mode: p.decision_mode ?? cur.decision_mode ?? 'rules',+ llm_model: 'llm_model' in p ? (p.llm_model || null) : (cur.llm_model || null),+ llm_min_confidence: 'llm_min_confidence' in p ? (p.llm_min_confidence == null || p.llm_min_confidence === '' ? null : Math.min(1, Math.max(0, Number(p.llm_min_confidence)))) : (cur.llm_min_confidence != null ? Number(cur.llm_min_confidence) : null),+ label: 'label' in p ? (p.label || null) : (cur.label || null),+ experiment_group: 'experiment_group' in p ? (p.experiment_group || null) : (cur.experiment_group || null),};// Mandatory stop-loss — never let the DB constraint be the first line of defense.@@ -383,7 +404,8 @@ async function upsertStrategy(req, res, userId) {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, auto_fund_enabled,- initials_out_multiple, moonbag_min_pct, updated_at)+ initials_out_multiple, moonbag_min_pct,+ decision_mode, llm_model, llm_min_confidence, label, experiment_group, 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},@@ -398,7 +420,8 @@ async function upsertStrategy(req, res, userId) {${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}, ${next.auto_fund_enabled},- ${next.initials_out_multiple}, ${next.moonbag_min_pct}, now())+ ${next.initials_out_multiple}, ${next.moonbag_min_pct},+ ${next.decision_mode}, ${next.llm_model}, ${next.llm_min_confidence}, ${next.label}, ${next.experiment_group}, now())on conflict (agent_id, network) do update setenabled = excluded.enabled,kill_switch = excluded.kill_switch,@@ -442,6 +465,11 @@ async function upsertStrategy(req, res, userId) {auto_fund_enabled = excluded.auto_fund_enabled,initials_out_multiple = excluded.initials_out_multiple,moonbag_min_pct = excluded.moonbag_min_pct,+ decision_mode = excluded.decision_mode,+ llm_model = excluded.llm_model,+ llm_min_confidence = excluded.llm_min_confidence,+ label = excluded.label,+ experiment_group = excluded.experiment_group,updated_at = now()returning *`;@@ -493,6 +521,11 @@ async function upsertStrategy(req, res, userId) {auto_fund_enabled: row.auto_fund_enabled ?? false,initials_out_multiple: row.initials_out_multiple != null ? Number(row.initials_out_multiple) : null,moonbag_min_pct: row.moonbag_min_pct != null ? Number(row.moonbag_min_pct) : 15,+ decision_mode: row.decision_mode || 'rules',+ llm_model: row.llm_model || null,+ llm_min_confidence: row.llm_min_confidence != null ? Number(row.llm_min_confidence) : null,+ label: row.label || null,+ experiment_group: row.experiment_group || null,},});}diff --git a/data/changelog.json b/data/changelog.jsonindex 7a07004bc..04aa5f32d 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -14875,6 +14875,17 @@"infra"],"link": "/coins"+ },+ {+ "date": "2026-07-19",+ "title": "The sniper fleet becomes a live experiment: rules vs AI judgment",+ "summary": "The autonomous pump.fun sniper now runs ten labeled strategies side by side to learn which entry conditions actually make money. Some agents trade strict rule shields (market-cap bands, socials, Oracle conviction), and three new agents have no rules at all: an AI model (Grok, Claude, or an auto-router) reads every launch and decides with a written thesis, while the same hard safety rails (no Mayhem tokens, honeypot firewall, budgets and stop-losses) protect every trade. A new scoreboard at /sniper/experiments compares each arm by real on-chain results. Under the hood the sniper also got three reliability fixes that unblocked buying: safety reads now rotate across many RPC providers with retries, provisional Oracle scores on brand-new coins no longer disqualify launch snipes, and a stuck position whose sell had already landed on-chain is now reconciled from the chain instead of retrying forever.",+ "tags": [+ "feature",+ "improvement",+ "fix"+ ],+ "link": "/sniper/experiments"}]}diff --git a/data/pages.json b/data/pages.jsonindex 8bfb2f0d7..257630200 100644--- a/data/pages.json+++ b/data/pages.json@@ -1159,6 +1159,14 @@"changefreq": "daily","added": "2026-06-15"},+ {+ "path": "/sniper/experiments",+ "title": "Sniper Experiments: rules vs LLM judgment, scored live",+ "description": "The sniper fleet runs different rule sets side by side, including LLM-judged agents with no rules at all. The live scoreboard of which entry conditions actually make money, every fill verifiable on-chain.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-07-19"+ },{"path": "/play/ufo","title": "Flappin UFO — retired demo",diff --git a/packages/agent-sniper/src/mayhem-filter.js b/packages/agent-sniper/src/mayhem-filter.jsindex b1a40516d..a7fb60137 100644--- a/packages/agent-sniper/src/mayhem-filter.js+++ b/packages/agent-sniper/src/mayhem-filter.js@@ -13,16 +13,39 @@import { Connection, PublicKey } from '@solana/web3.js';+/**+ * Re-run `fn` while it resolves null, with exponential backoff. A brand-new+ * mint's curve account exists from creation, so a null read is an RPC hiccup+ * (throttled endpoint, not-yet-synced node); a short backoff usually resolves+ * it to a real answer instead of forfeiting the buy on a strict gate. Exported+ * for unit tests; the answer being retried is immutable, so retrying is safe.+ */+export async function retryWhileNull(fn, { retries = 2, delayMs = 350 } = {}) {+ let v = await fn();+ for (let attempt = 0; v === null && attempt < retries; attempt++) {+ await new Promise((r) => setTimeout(r, delayMs * 2 ** attempt));+ v = await fn();+ }+ return v;+}+/*** @param {object} o* @param {string} [o.rpcUrl] RPC endpoint (falls back to public mainnet)+ * @param {object} [o.connection] pre-built web3 Connection (e.g. the platform's+ * rotating multi-endpoint connection). Takes precedence over rpcUrl, so a single+ * throttled provider can't starve the gate into permanent "unknown".* @param {boolean} [o.strictOnUnknown=false] if the curve can't be read, skip the buy* (honor the rule strictly) instead of allowing it. Default allows-on-unknown so a* flaky RPC read doesn't silently halt all trading — unknowns are logged.+ * @param {number} [o.retries=2] extra read attempts before resolving "unknown".+ * The flag is immutable per mint, so retrying is always safe; on a strict gate each+ * retry converts a would-be skipped buy into a definitive pass/fail.+ * @param {number} [o.retryDelayMs=350] base backoff between attempts (doubles per retry)* @returns {{ oracleGate: Function, isMayhem: Function, stats: Function }}*/-export function createMayhemFilter({ rpcUrl, strictOnUnknown = false } = {}) {- const conn = new Connection(rpcUrl || 'https://api.mainnet-beta.solana.com', 'confirmed');+export function createMayhemFilter({ rpcUrl, connection = null, strictOnUnknown = false, retries = 2, retryDelayMs = 350 } = {}) {+ const conn = connection || new Connection(rpcUrl || 'https://api.mainnet-beta.solana.com', 'confirmed');const cache = new Map(); // mint → boolean (true = mayhem)const inflight = new Map(); // mint → Promise<boolean|null>let sdkPromise = null;@@ -62,7 +85,7 @@ export function createMayhemFilter({ rpcUrl, strictOnUnknown = false } = {}) {if (!mint) return null;if (cache.has(mint)) return cache.get(mint);if (inflight.has(mint)) return inflight.get(mint);- const p = readMayhem(mint).then((v) => {+ const p = retryWhileNull(() => readMayhem(mint), { retries, delayMs: retryDelayMs }).then((v) => {inflight.delete(mint);if (v !== null) cache.set(mint, v); // only cache definitive answersreturn v;diff --git a/pages/play/arena.html b/pages/play/arena.htmlindex 60cbeea15..4cd50e6bb 100644--- a/pages/play/arena.html+++ b/pages/play/arena.html@@ -380,6 +380,7 @@Be the first — arm a trader and enter the arena.<button class="btn primary" id="emptyPick" style="margin:12px auto 0" data-i18n="play_arena.pick_an_avatar_watch">Pick an avatar & watch</button></div>+ <a href="/sniper/experiments" style="display:block;text-align:center;font-size:11.5px;padding:8px 0 2px;color:var(--faint,#888);text-decoration:none">Which rule set wins? Experiments scoreboard →</a></section><!-- right: live tape -->diff --git a/pages/sniper-experiments.html b/pages/sniper-experiments.htmlnew file mode 100644index 000000000..0d29c0f5c--- /dev/null+++ b/pages/sniper-experiments.html@@ -0,0 +1,92 @@+<!doctype html>+<html lang="en" class="cv-page">+ <head>+ <script>+ /* three.ws theme boot, no-flash; runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Sniper Experiments · three.ws</title>+ <meta+ name="description"+ content="The sniper fleet runs different rule sets side by side: rule shields, oracle gates, and LLM-judged agents with no rules at all. This is the live scoreboard of which entry conditions actually make money, every trade verifiable on-chain."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/sniper/experiments" />+ <meta property="og:title" content="Sniper Experiments · three.ws" />+ <meta+ property="og:description"+ content="Rules vs LLM judgment: the live scoreboard of which sniper entry conditions actually make money."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=Sniper+Experiments&d=Rules+vs+LLM+judgment%3A+the+live+scoreboard+of+which+sniper+entry+conditions+actually+make+money.&p=%2Fsniper%2Fexperiments"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Sniper Experiments · three.ws" />+ <meta+ name="twitter:description"+ content="Rules vs LLM judgment: the live scoreboard of which sniper entry conditions actually make money."+ />+ <meta name="theme-color" content="#09090b" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/coin-pages.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/sniper/experiments" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cv-container">+ <nav class="cv-crumbs" aria-label="Breadcrumb">+ <a href="/play/arena">Sniper Arena</a><span class="sep">/</span><span class="here">Experiments</span>+ </nav>+ <h1 class="cv-h1">Sniper Experiments</h1>+ <p class="cv-sub">+ The fleet runs deliberately different rule sets side by side: strict rule+ shields, oracle-gated entries, and LLM-judged agents with no rules at all.+ Same market, same safety rails, different brains. This scoreboard shows+ which entry conditions actually make money; every fill is signed by the+ agent's own wallet and verifiable on-chain.+ </p>++ <!-- Window switch + summary tiles. Hydrated by src/sniper-experiments.js. -->+ <section id="xp-controls" class="cv-section" aria-label="Window"></section>+ <section id="xp-summary" class="cv-section" aria-label="Summary"></section>++ <!-- The comparison board. Hydrated by src/sniper-experiments.js. -->+ <section id="xp-board" class="cv-section" aria-label="Strategy comparison"></section>++ <p class="cv-updated" id="xp-updated"></p>+ </main>++ <script type="module" src="/src/sniper-experiments.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex bc7928fbb..b790f4a1b 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-19T13:33:34.481Z",+ "generated_at": "2026-07-19T14:03:19.061Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -157,6 +157,18 @@"docs"]},+ {+ "date": "2026-07-19",+ "type": "update",+ "title": "The sniper fleet becomes a live experiment: rules vs AI judgment",+ "summary": "The autonomous pump.fun sniper now runs ten labeled strategies side by side to learn which entry conditions actually make money. Some agents trade strict rule shields (market-cap bands, socials, Oracle conviction), and three new agents have no rules at all: an AI model (Grok, Claude, or an auto-router) reads every launch and decides with a written thesis, while the same hard safety rails (no Mayhem tokens, honeypot firewall, budgets and stop-losses) protect every trade. A new scoreboard at /sniper/experiments compares each arm by real on-chain results. Under the hood the sniper also got three reliability fixes that unblocked buying: safety reads now rotate across many RPC providers with retries, provisional Oracle scores on brand-new coins no longer disqualify launch snipes, and a stuck position whose sell had already landed on-chain is now reconciled from the chain instead of retrying forever.",+ "link": "/sniper/experiments",+ "tags": [+ "feature",+ "improvement",+ "fix"+ ]+ },{"date": "2026-07-19","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 2ab65f858..e216527e3 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -118,6 +118,14 @@<category>sdk</category><description>The 3D avatar assistant widget is now installable three ways. Beyond the one-tag script, there is an npm package, @three-ws/assistant, for bundler projects (the one-tag build is generated from it, so they never drift), and a free MCP server, @three-ws/assistant-mcp, published to the official Model Context Protocol registry as io.github.nirholas/assistant-widget. Any AI agent (Claude Code, Cursor, Claude Desktop) can now ask for a widget in plain language and get back a paste-ready embed: build_assistant_widget turns a config into a script tag, a frame URL, and a ThreeAssistant.init() call, and list_assistant_options returns every avatar, background, and mode. Full developer docs at /docs/assistant-widget and a step-by-step tutorial walk through every option, the JavaScript API, and the agent workflow.</description></item>+ <item>+ <title>The sniper fleet becomes a live experiment: rules vs AI judgment</title>+ <link>https://three.ws/sniper/experiments</link>+ <guid isPermaLink="false">2026-07-19:The sniper fleet becomes a live experiment: rules vs AI judgment</guid>+ <pubDate>Sun, 19 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The autonomous pump.fun sniper now runs ten labeled strategies side by side to learn which entry conditions actually make money. Some agents trade strict rule shields (market-cap bands, socials, Oracle conviction), and three new agents have no rules at all: an AI model (Grok, Claude, or an auto-router) reads every launch and decides with a written thesis, while the same hard safety rails (no Mayhem tokens, honeypot firewall, budgets and stop-losses) protect every trade. A new scoreboard at /sniper/experiments compares each arm by real on-chain results. Under the hood the sniper also got three reliability fixes that unblocked buying: safety reads now rotate across many RPC providers with retries, provisional Oracle scores on brand-new coins no longer disqualify launch snipes, and a stuck position whose sell had already landed on-chain is now reconciled from the chain instead of retrying forever.</description>+ </item><item><title>TradingView charts on every coin page</title><link>https://three.ws/coin/bitcoin</link>diff --git a/public/features.json b/public/features.jsonindex 7056d3f1a..63622aaf3 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-19T13:33:34.467Z",+ "generated_at": "2026-07-19T14:03:19.047Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/seed-sniper-experiments.mjs b/scripts/seed-sniper-experiments.mjsnew file mode 100644index 000000000..ce852cd8d--- /dev/null+++ b/scripts/seed-sniper-experiments.mjs@@ -0,0 +1,174 @@+// Seed the sniper experiment fleet: label every armed strategy and shape the+// A/B arms so different entry-condition philosophies trade side by side.+//+// node scripts/seed-sniper-experiments.mjs # dry-run (prints the plan)+// node scripts/seed-sniper-experiments.mjs --apply # write to the database+//+// DATABASE_URL is read from the environment; when unset, the script reads it+// from the production Cloud Run service (same source of truth the worker uses).+// Requires the 20260719120000_sniper_llm_experiments.sql migration.+//+// The arms (one strategy per agent, unique on (agent_id, network)):+// rules group: shield-based entries at different strictness levels+// oracle group: conviction-gated entries (bite after score maturity)+// llm group: no rule shields; a model judges each launch (grok / claude /+// openrouter auto-router), safety rails still enforced++import { execSync } from 'node:child_process';+import { createRequire } from 'node:module';++const require = createRequire(import.meta.url);+const { Pool } = require('@neondatabase/serverless');++const APPLY = process.argv.includes('--apply');+const NETWORK = 'mainnet';++// agent_id (unique per arm) → the experiment definition. `set` contains only+// the columns that arm changes; omitted columns keep their current values.+const ARMS = [+ {+ agent: '4c0e4d18-0544-4c95-a0db-a16896b029be',+ label: 'rules-proven',+ group: 'rules',+ note: 'the arm that landed the first profitable snipe; unchanged',+ set: {},+ },+ {+ agent: 'adba030a-2536-4476-a34d-7ce096d2e033',+ label: 'intel-quality',+ group: 'rules',+ note: 'intel_confirmed with quality/bundle gates; unchanged',+ set: {},+ },+ {+ agent: '0846c27e-6258-4859-bc1c-3148d59951c5',+ label: 'oracle-open',+ group: 'oracle',+ note: 'oracle >= 35 once the score matures; no other shields',+ set: {},+ },+ {+ agent: '6287faf3-d41b-43cb-97bb-d305c1ac6e45',+ label: 'oracle-strict',+ group: 'oracle',+ note: 'oracle >= 65 once the score matures; no other shields',+ set: {},+ },+ {+ agent: '15e98de5-2695-427b-b746-4558a0933a4e',+ label: 'rules-classic',+ group: 'rules',+ note: 'control: $10k-$100k band + socials + oracle 55, untouched',+ set: {},+ },+ {+ agent: '2b8a5101-6572-4dd5-8f11-d9fdb5e31490',+ label: 'rules-no-socials',+ group: 'rules',+ note: 'the proven band without the socials requirement',+ set: {+ require_socials: false, min_market_cap_usd: 5000, max_market_cap_usd: 25000,+ min_oracle_score: null, per_trade_lamports: '10000000', daily_budget_lamports: '50000000',+ max_concurrent_positions: 1,+ },+ },+ {+ agent: '781b75a3-86f9-44ee-b29b-6f71d1acad79',+ label: 'rules-wide-band',+ group: 'rules',+ note: 'socials + a wider $5k-$50k band, no oracle gate',+ set: {+ require_socials: true, min_market_cap_usd: 5000, max_market_cap_usd: 50000,+ min_oracle_score: null, per_trade_lamports: '10000000', daily_budget_lamports: '50000000',+ max_concurrent_positions: 1,+ },+ },+ {+ agent: 'bcb8c86f-92d2-496d-bb2c-b9442f97a4fa',+ label: 'llm-grok',+ group: 'llm',+ note: 'no shields; Grok judges every launch',+ set: {+ decision_mode: 'llm', llm_model: 'x-ai/grok-4.3', llm_min_confidence: 0.65,+ require_socials: false, min_market_cap_usd: null, max_market_cap_usd: null,+ min_oracle_score: null, per_trade_lamports: '10000000', daily_budget_lamports: '50000000',+ max_concurrent_positions: 1,+ },+ },+ {+ agent: 'c7b23f0f-a7fc-412d-81c8-2b2b06119af2',+ label: 'llm-claude',+ group: 'llm',+ note: 'no shields; Claude Haiku judges every launch',+ set: {+ decision_mode: 'llm', llm_model: 'anthropic/claude-haiku-4.5', llm_min_confidence: 0.65,+ require_socials: false, min_market_cap_usd: null, max_market_cap_usd: null,+ min_oracle_score: null, per_trade_lamports: '10000000', daily_budget_lamports: '50000000',+ max_concurrent_positions: 1,+ },+ },+ {+ agent: 'd10aae1b-c56f-4780-88cb-e9b7405ef29e',+ label: 'llm-auto',+ group: 'llm',+ note: 'no shields; the OpenRouter auto-router picks the judge',+ set: {+ decision_mode: 'llm', llm_model: 'openrouter/auto', llm_min_confidence: 0.65,+ require_socials: false, min_market_cap_usd: null, max_market_cap_usd: null,+ min_oracle_score: null, per_trade_lamports: '10000000', daily_budget_lamports: '50000000',+ max_concurrent_positions: 1,+ },+ },+];++function resolveDatabaseUrl() {+ if (process.env.DATABASE_URL) return process.env.DATABASE_URL;+ const svc = JSON.parse(execSync(+ 'gcloud run services describe three-ws-api --region us-central1 --project aerial-vehicle-466722-p5 --format=json',+ { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },+ ));+ const env = svc.spec.template.spec.containers[0].env || [];+ const url = env.find((e) => e.name === 'DATABASE_URL')?.value;+ if (!url) throw new Error('DATABASE_URL not found in env or on the Cloud Run service');+ return url;+}++const pool = new Pool({ connectionString: resolveDatabaseUrl() });++const { rows: existing } = await pool.query(+ 'select agent_id, label, decision_mode, llm_model, per_trade_lamports, daily_budget_lamports, enabled from agent_sniper_strategies where network = $1',+ [NETWORK],+);+const byAgent = new Map(existing.map((r) => [r.agent_id, r]));++let updated = 0;+for (const arm of ARMS) {+ const cur = byAgent.get(arm.agent);+ if (!cur) {+ console.log(`SKIP ${arm.label}: no ${NETWORK} strategy exists for agent ${arm.agent} (arms only reshape existing strategies)`);+ continue;+ }+ const set = {+ label: arm.label,+ experiment_group: arm.group,+ // Every experiment arm consents to auto top-ups from the launcher master so+ // an unfunded wallet can't silently sit out the experiment. The worker's+ // SNIPER_AUTO_FUND_* caps bound every transfer.+ auto_fund_enabled: true,+ ...arm.set,+ };+ const cols = Object.keys(set);+ console.log(`${APPLY ? 'APPLY' : 'PLAN '} ${arm.label.padEnd(16)} agent ${arm.agent.slice(0, 8)}: ${arm.note}`);+ for (const c of cols) console.log(` ${c} = ${JSON.stringify(set[c])}`);+ if (!APPLY) continue;+ const assignments = cols.map((c, i) => `${c} = $${i + 3}`).join(', ');+ await pool.query(+ `update agent_sniper_strategies set ${assignments}, updated_at = now() where agent_id = $1 and network = $2`,+ [arm.agent, NETWORK, ...cols.map((c) => set[c])],+ );+ updated++;+}++if (APPLY) console.log(`\nDone: ${updated} strategies updated.`);+else console.log('\nDry-run only. Re-run with --apply to write.');+await pool.end();diff --git a/src/sniper-experiments.js b/src/sniper-experiments.jsnew file mode 100644index 000000000..ae42f2f8b--- /dev/null+++ b/src/sniper-experiments.js@@ -0,0 +1,214 @@+// /sniper/experiments, the strategy A/B scoreboard.+//+// One row per armed sniper strategy: its human label, the entry conditions it+// trades (rule shields or an LLM judge), and its REAL on-chain record over the+// selected window via /api/sniper/experiments. No simulation rows, no mock+// data; when an arm hasn't traded yet it honestly shows zero.++import { escapeHtml as esc } from './shared/coin-format.js';++const $ = (id) => document.getElementById(id);+const REFRESH_MS = 30_000;+const WINDOWS = [+ { key: '24h', label: '24h' },+ { key: '7d', label: '7 days' },+ { key: '30d', label: '30 days' },+ { key: 'all', label: 'All time' },+];++let windowKey = '7d';+let timer = null;++async function getJson(url) {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) {+ const err = new Error(`fetch ${url} → ${res.status}`);+ err.status = res.status;+ throw err;+ }+ return res.json();+}++function sol(n) {+ if (n == null || !Number.isFinite(Number(n))) return '·';+ const v = Number(n);+ const s = v.toFixed(Math.abs(v) < 0.01 && v !== 0 ? 4 : 3);+ return `${v > 0 ? '+' : ''}${s} SOL`;+}++function pct(n, signed = true) {+ if (n == null || !Number.isFinite(Number(n))) return '·';+ const v = Number(n);+ return `${signed && v > 0 ? '+' : ''}${v.toFixed(1)}%`;+}++function holdFmt(s) {+ if (s == null || !Number.isFinite(Number(s))) return '·';+ const v = Number(s);+ if (v < 90) return `${Math.round(v)}s`;+ return `${Math.round(v / 60)}m`;+}++function ago(iso) {+ if (!iso) return 'never';+ const ms = Date.now() - new Date(iso).getTime();+ if (ms < 60_000) return 'just now';+ if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m ago`;+ if (ms < 86_400_000) return `${Math.round(ms / 3_600_000)}h ago`;+ return `${Math.round(ms / 86_400_000)}d ago`;+}++function pnlClass(v) {+ if (v == null || Number(v) === 0) return '';+ return Number(v) > 0 ? 'xp-pos' : 'xp-neg';+}++function modeBadge(x) {+ if (x.decision_mode === 'llm') {+ return `<span class="xp-badge xp-badge-llm" title="No rule shields: an LLM judges each launch">LLM · ${esc((x.llm_model || 'auto').split('/').pop())}</span>`;+ }+ return `<span class="xp-badge xp-badge-rules">rules</span>`;+}++function renderControls() {+ $('xp-controls').innerHTML = `+ <div class="xp-seg" role="group" aria-label="Time window">+ ${WINDOWS.map(+ (w) => `+ <button class="xp-seg-btn${w.key === windowKey ? ' on' : ''}" data-window="${w.key}" aria-pressed="${w.key === windowKey}">+ ${esc(w.label)}+ </button>`,+ ).join('')}+ </div>`;+ $('xp-controls').querySelectorAll('[data-window]').forEach((btn) => {+ btn.addEventListener('click', () => {+ windowKey = btn.dataset.window;+ renderControls();+ refresh();+ });+ });+}++function renderSummary(experiments) {+ const active = experiments.filter((x) => x.enabled);+ const traded = experiments.filter((x) => x.closed > 0);+ const totalPnl = experiments.reduce((a, x) => a + (Number(x.realized_pnl_sol) || 0), 0);+ const totalTrades = experiments.reduce((a, x) => a + x.closed, 0);+ const best = traded.slice().sort((a, b) => (b.realized_pnl_sol || 0) - (a.realized_pnl_sol || 0))[0];+ $('xp-summary').innerHTML = `+ <div class="xp-tiles">+ <div class="cv-card xp-tile"><span>Armed strategies</span><b>${active.length}</b><i>${experiments.length - active.length} paused</i></div>+ <div class="cv-card xp-tile"><span>Closed trades</span><b>${totalTrades}</b><i>${experiments.reduce((a, x) => a + x.open, 0)} open now</i></div>+ <div class="cv-card xp-tile"><span>Fleet realized P&L</span><b class="${pnlClass(totalPnl)}">${esc(sol(totalPnl))}</b><i>window: ${esc(windowKey)}</i></div>+ <div class="cv-card xp-tile"><span>Best arm</span><b>${best ? esc(best.label) : 'no trades yet'}</b><i>${best ? esc(sol(best.realized_pnl_sol)) : 'waiting on fills'}</i></div>+ </div>`;+}++function renderBoard(experiments) {+ if (!experiments.length) {+ $('xp-board').innerHTML = `+ <div class="cv-card" style="text-align:center;padding:32px">+ <p style="margin:0 0 6px;font-weight:600">No strategies armed on this network yet</p>+ <p style="margin:0;color:var(--cv-text-3)">Arm an agent on <a href="/arm">/arm</a> and its record shows up here automatically.</p>+ </div>`;+ return;+ }+ const rows = experiments+ .map((x) => {+ const record = x.closed > 0 ? `${x.wins}W · ${x.losses}L` : 'no fills';+ return `+ <tr class="${x.enabled ? '' : 'xp-off'}">+ <td>+ <div class="xp-label">${esc(x.label)}${x.enabled ? '' : ' <span class="xp-paused">paused</span>'}</div>+ <div class="xp-agent"><a href="/a/${esc(x.agent_id)}">${esc(x.agent_name || 'agent')}</a> ${modeBadge(x)}</div>+ </td>+ <td class="xp-cond">${esc(x.conditions)}<div class="xp-cond-sub">${esc(String(x.per_trade_sol ?? '·'))} SOL/trade · SL ${esc(pct(-Math.abs(x.stop_loss_pct ?? 0), false))}${x.trailing_stop_pct != null ? ` · trail ${esc(pct(x.trailing_stop_pct, false))}` : ''}${x.max_hold_seconds != null ? ` · max ${esc(holdFmt(x.max_hold_seconds))}` : ''}</div></td>+ <td>${esc(record)}${x.open > 0 ? ` <span class="xp-open">+${x.open} open</span>` : ''}</td>+ <td>${x.win_rate != null ? esc(String(x.win_rate)) + '%' : '·'}</td>+ <td class="${pnlClass(x.realized_pnl_sol)}">${esc(sol(x.realized_pnl_sol))}</td>+ <td class="${pnlClass(x.roi_pct)}">${esc(pct(x.roi_pct))}</td>+ <td class="${pnlClass(x.avg_pnl_pct)}">${esc(pct(x.avg_pnl_pct))}</td>+ <td>${esc(holdFmt(x.avg_hold_seconds))}</td>+ <td>${esc(ago(x.last_closed_at))}</td>+ </tr>`;+ })+ .join('');+ $('xp-board').innerHTML = `+ <div class="cv-card" style="overflow-x:auto">+ <table class="cv-table xp-table">+ <thead>+ <tr>+ <th>Strategy</th><th>Entry conditions</th><th>Record</th><th>Win rate</th>+ <th>Realized</th><th>ROI</th><th>Avg trade</th><th>Avg hold</th><th>Last trade</th>+ </tr>+ </thead>+ <tbody>${rows}</tbody>+ </table>+ </div>`;+}++async function refresh() {+ try {+ const data = await getJson(`/api/sniper/experiments?network=mainnet&window=${encodeURIComponent(windowKey)}`);+ renderSummary(data.experiments);+ renderBoard(data.experiments);+ $('xp-updated').textContent = `Updated ${new Date(data.t).toLocaleTimeString()} · real on-chain fills only`;+ } catch (err) {+ $('xp-board').innerHTML = `+ <div class="cv-card" style="text-align:center;padding:32px">+ <p style="margin:0 0 6px;font-weight:600">Couldn't load the scoreboard</p>+ <p style="margin:0;color:var(--cv-text-3)">${esc(err.message)}. Retrying automatically.</p>+ </div>`;+ }+}++function injectStyles() {+ const css = `+ .xp-seg{display:inline-flex;gap:4px;background:var(--cv-bg-2,rgba(255,255,255,.04));border:1px solid var(--cv-border,rgba(255,255,255,.08));border-radius:10px;padding:3px}+ .xp-seg-btn{appearance:none;border:0;background:transparent;color:var(--cv-text-2,#aaa);font:inherit;font-size:12.5px;padding:5px 12px;border-radius:8px;cursor:pointer;transition:background .15s,color .15s}+ .xp-seg-btn:hover{color:var(--cv-text,#eee)}+ .xp-seg-btn:focus-visible{outline:2px solid var(--cv-accent,#7c6cff);outline-offset:1px}+ .xp-seg-btn.on{background:var(--cv-bg-3,rgba(255,255,255,.09));color:var(--cv-text,#fff)}+ .xp-tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px}+ .xp-tile{display:flex;flex-direction:column;gap:2px;padding:14px 16px}+ .xp-tile span{font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--cv-text-3,#888)}+ .xp-tile b{font-size:19px;font-weight:650}+ .xp-tile i{font-style:normal;font-size:12px;color:var(--cv-text-3,#888)}+ .xp-table{width:100%;border-collapse:collapse;font-size:13px;min-width:860px}+ .xp-table th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--cv-text-3,#888);padding:8px 10px;border-bottom:1px solid var(--cv-border,rgba(255,255,255,.08))}+ .xp-table td{padding:10px;border-bottom:1px solid var(--cv-border,rgba(255,255,255,.05));vertical-align:top}+ .xp-table tr:last-child td{border-bottom:0}+ .xp-table tr:hover td{background:var(--cv-bg-2,rgba(255,255,255,.03))}+ .xp-label{font-weight:600}+ .xp-agent{font-size:12px;color:var(--cv-text-3,#888);margin-top:2px}+ .xp-agent a{color:inherit}+ .xp-agent a:hover{color:var(--cv-text,#eee)}+ .xp-cond{max-width:300px;color:var(--cv-text-2,#bbb)}+ .xp-cond-sub{font-size:11.5px;color:var(--cv-text-3,#888);margin-top:3px}+ .xp-badge{display:inline-block;font-size:10.5px;padding:1px 7px;border-radius:99px;border:1px solid var(--cv-border,rgba(255,255,255,.12));vertical-align:1px}+ .xp-badge-llm{color:#c9b8ff;border-color:rgba(150,120,255,.4)}+ .xp-badge-rules{color:var(--cv-text-3,#999)}+ .xp-pos{color:#4ade80}+ .xp-neg{color:#f87171}+ .xp-open{font-size:11px;color:#93c5fd}+ .xp-paused{font-size:10.5px;color:var(--cv-text-3,#888);font-weight:400}+ .xp-off td{opacity:.55}+ `;+ const el = document.createElement('style');+ el.textContent = css;+ document.head.appendChild(el);+}++injectStyles();+renderControls();+refresh();+timer = setInterval(refresh, REFRESH_MS);+document.addEventListener('visibilitychange', () => {+ if (document.hidden) {+ clearInterval(timer);+ timer = null;+ } else if (!timer) {+ refresh();+ timer = setInterval(refresh, REFRESH_MS);+ }+});diff --git a/tests/sniper-experiments.test.js b/tests/sniper-experiments.test.jsnew file mode 100644index 000000000..8c0d04bfe--- /dev/null+++ b/tests/sniper-experiments.test.js@@ -0,0 +1,65 @@+// Sniper experiment fleet: the pieces that decide whether an arm trades.+//+// 1. mayhem-filter retry: a transient null read resolves to a definitive+// answer instead of forfeiting the buy on a strict gate (the fix for the+// fleet-wide "mayhem_unknown" starvation on a throttled RPC).+// 2. LLM judge verdict parsing: strict shape, tolerant of fences/prose,+// anything malformed never buys.+// 3. Oracle maturity: a below-threshold score on a minutes-old coin defers+// the gate (fail open) instead of disqualifying every launch snipe.+//+// Pure logic only: no DB, no network, no pump SDK.++import { describe, it, expect } from 'vitest';+import { retryWhileNull } from '../packages/agent-sniper/src/mayhem-filter.js';+import { parseVerdict } from '../workers/agent-sniper/llm-judge.js';++describe('mayhem read retries (strict gate must not starve on RPC blips)', () => {+ it('retries a null read and returns the first definitive answer', async () => {+ let calls = 0;+ const read = async () => (++calls < 3 ? null : false);+ const v = await retryWhileNull(read, { retries: 2, delayMs: 1 });+ expect(v).toBe(false);+ expect(calls).toBe(3);+ });++ it('stops immediately on a definitive first answer', async () => {+ let calls = 0;+ const v = await retryWhileNull(async () => { calls++; return true; }, { retries: 2, delayMs: 1 });+ expect(v).toBe(true);+ expect(calls).toBe(1);+ });++ it('gives up after the retry budget and stays unknown', async () => {+ let calls = 0;+ const v = await retryWhileNull(async () => { calls++; return null; }, { retries: 2, delayMs: 1 });+ expect(v).toBe(null);+ expect(calls).toBe(3);+ });+});++describe('llm-judge parseVerdict (malformed never buys)', () => {+ it('parses a clean verdict', () => {+ expect(parseVerdict('{"buy": true, "confidence": 0.8, "thesis": "strong meta"}')).toEqual({+ buy: true, confidence: 0.8, thesis: 'strong meta',+ });+ });++ it('parses through code fences and prose', () => {+ const text = 'Here is my verdict:\n```json\n{"buy": false, "confidence": 0.3, "thesis": "dead ticker"}\n```';+ expect(parseVerdict(text)).toEqual({ buy: false, confidence: 0.3, thesis: 'dead ticker' });+ });++ it('rejects missing buy / bad confidence / non-JSON', () => {+ expect(parseVerdict('{"confidence": 0.8}')).toBe(null);+ expect(parseVerdict('{"buy": true, "confidence": 1.4}')).toBe(null);+ expect(parseVerdict('{"buy": "yes", "confidence": 0.5}')).toBe(null);+ expect(parseVerdict('no json at all')).toBe(null);+ expect(parseVerdict('')).toBe(null);+ });++ it('truncates a runaway thesis', () => {+ const v = parseVerdict(`{"buy": true, "confidence": 0.7, "thesis": "${'x'.repeat(500)}"}`);+ expect(v.thesis.length).toBe(280);+ });+});diff --git a/vercel.json b/vercel.jsonindex 78208b663..2dd02967d 100644--- a/vercel.json+++ b/vercel.json@@ -1230,6 +1230,10 @@"src": "/play/arena/?","dest": "/play/arena.html"},+ {+ "src": "/sniper/experiments/?",+ "dest": "/sniper-experiments.html"+ },{"src": "/arena/?","dest": "/arena.html"@@ -3052,6 +3056,10 @@"src": "/api/sniper/leaderboard","dest": "/api/sniper/leaderboard.js"},+ {+ "src": "/api/sniper/experiments",+ "dest": "/api/sniper/experiments.js"+ },{"src": "/api/sniper/status","dest": "/api/sniper/status.js"diff --git a/vite.config.js b/vite.config.jsindex 7bec46b5b..489ccf57c 100644--- a/vite.config.js+++ b/vite.config.js@@ -502,6 +502,7 @@ const appConfig = {'markets-trending': resolve(__dirname, 'pages/markets-trending.html'),'markets-robinhood': resolve(__dirname, 'pages/markets-robinhood.html'),fees: resolve(__dirname, 'pages/fees.html'),+ 'sniper-experiments': resolve(__dirname, 'pages/sniper-experiments.html'),'dex-volumes': resolve(__dirname, 'pages/dex-volumes.html'),hacks: resolve(__dirname, 'pages/hacks.html'),bnb: resolve(__dirname, 'pages/bnb.html'),@@ -1126,6 +1127,8 @@ support: resolve(__dirname, 'pages/support.html'),'/yields/': resolve(root, 'pages/yields.html'),'/fees': resolve(root, 'pages/fees.html'),'/fees/': resolve(root, 'pages/fees.html'),+ '/sniper/experiments': resolve(root, 'pages/sniper-experiments.html'),+ '/sniper/experiments/': resolve(root, 'pages/sniper-experiments.html'),'/dex-volumes': resolve(root, 'pages/dex-volumes.html'),'/dex-volumes/': resolve(root, 'pages/dex-volumes.html'),'/hacks': resolve(root, 'pages/hacks.html'),diff --git a/workers/agent-sniper/README.md b/workers/agent-sniper/README.mdindex af42fd6d6..fab6922d3 100644--- a/workers/agent-sniper/README.md+++ b/workers/agent-sniper/README.md@@ -62,7 +62,7 @@ Enforced in `executeBuy`, short-circuiting before any transaction:5. **Mandatory stop-loss** — DB `CHECK (stop_loss_pct > 0)` + runtime filter.6. **Price-impact circuit breaker** — `max_price_impact_pct` checked against a fresh `quoteForBuy`.7. **Idempotency** — `INSERT … ON CONFLICT (agent_id, mint, network) DO NOTHING` claims the slot before the tx; one shot per mint per agent.-8. **Mayhem exclusion (owner rule)** — the first gate: never buy pump.fun "Mayhem"-mode tokens, only regular launches. Reads `isMayhemMode` off the on-chain bonding curve (cached per mint) via `mayhem-gate.js`. Applies to **every** trigger path, since it lives in the `executeBuy` chokepoint. `SNIPER_MAYHEM_FILTER=0` disables; `SNIPER_MAYHEM_STRICT=1` also skips when the curve can't be read.+8. **Mayhem exclusion (owner rule)** — the first gate: never buy pump.fun "Mayhem"-mode tokens, only regular launches. Reads `isMayhemMode` off the on-chain bonding curve (cached per mint) via `mayhem-gate.js`, through the platform's **rotating multi-endpoint RPC chain** with bounded retries; a single throttled provider can no longer starve the gate into permanent "unknown". Applies to **every** trigger path, since it lives in the `executeBuy` chokepoint. `SNIPER_MAYHEM_FILTER=0` disables; strict-on-unknown is the default (`SNIPER_MAYHEM_STRICT=0` restores allow-on-unknown).9. **Market-cap band (owner rule)** — buy only inside a market-cap window. Enforced at the `executeBuy` chokepoint (`marketCapBandReason`), so `new_mint`, `intel`, `alpha`, `first_claim`, `radar` and `swarm` all obey it. **Fails closed**: a coin whose market cap can't be confirmed inside the band is skipped, not bought. A per-strategy `min/max_market_cap_usd` only *tightens* the fleet-wide floor/ceil (`SNIPER_MIN_MC_FLOOR_USD` / `SNIPER_MAX_MC_CEIL_USD`) — it can never loosen it. On a blind `new_mint` snipe the create-event cap is ~$4k, so a $10k floor correctly rejects brand-new launches; use the `intel_confirmed` trigger to buy a coin *after* it pumps into the band.10. **Realized-loss circuit breaker (portfolio layer)** — once an agent's **net realized loss over the trailing 24 h** crosses its cap, it stops opening new positions for the rest of the window. Catches a fleet that bleeds one losing entry at a time — each trade passes the per-trade caps yet the wallet still grinds down. A profitable or break-even day never trips it; a DB hiccup never blocks (the lamports caps stay the backstop). The fleet-wide `SNIPER_MAX_DAILY_LOSS_SOL` protects every agent at once and is tightened by an optional per-strategy `daily_loss_limit_lamports`. **The same breaker gates the auto-funder** — a wallet past its loss cap stops being refilled, so the master can't keep pouring SOL after a wallet that only loses.11. **Agent scoping** — `SNIPER_AGENT_IDS` restricts the worker to a specific set of agents, so a bounded run against the shared DB can't act on every other armed strategy.@@ -80,6 +80,44 @@ Enforced in `executeBuy`, short-circuiting before any transaction:> (`api/_lib/launcher-funding.js`). This is a hard backstop that a loose per-call> cap can't bypass — recommended whenever armed strategies auto-fund from the master.+> **Exit reconciliation (chain over DB).** A sell whose confirmation times out may+> still land. On a RETRY of a previously-failed sell, `executeSell` first reads the+> wallet's real token balance (`reconcile.js`): balance zero means a prior broadcast+> landed, so the worker finds the transaction that emptied the bag and closes the+> position with its actual proceeds (`error = 'reconciled_onchain'`) instead of+> retrying a sell that can only revert (pump error 6023, `NotEnoughTokensToSell`);+> a short balance clamps the sell to what the wallet really holds.++## Decision modes and the experiment fleet++Every strategy row carries a `decision_mode`:++- **`rules`** (default): the scorer/oracle gate chain documented above.+- **`llm`**: no rule shields at all (no market-cap band, no socials requirement,+ no oracle threshold, no creator gates). Each new launch is judged by a model+ (`llm-judge.js`): the strategy's `llm_model` (an OpenRouter slug, e.g.+ `x-ai/grok-4.3`, `anthropic/claude-haiku-4.5`, `openrouter/auto`) returns+ `{buy, confidence, thesis}`; the buy fires only at `confidence >=+ llm_min_confidence` (default 0.6). The thesis is journaled with the position and+ written to the reasoning ledger. Verdicts are shared per (mint, model), a small+ concurrency cap (`SNIPER_LLM_MAX_CONCURRENT`) drops launches instead of queueing+ unboundedly, and the platform's free-first `llmComplete` chain backstops an+ OpenRouter outage. The non-negotiable safety rails (Mayhem exclusion, trade+ firewall round-trip, budgets, concurrency, headroom, spend policy) still apply+ to both modes at the `executeBuy` chokepoint.++Strategies also carry a human `label` + `experiment_group` so deliberately+different rule sets can trade side by side and be compared honestly:+`scripts/seed-sniper-experiments.mjs` shapes the fleet (dry-run by default,+`--apply` writes), `/api/sniper/experiments` aggregates each arm's REAL on-chain+record, and **/sniper/experiments** is the public scoreboard.++Oracle-gated arms get one more fairness rule: a below-threshold conviction score+on a coin younger than `SNIPER_ORACLE_MATURITY_S` (default 900 s) is treated as+*unscored* (fail open, logged as `oracle_immature`): brand-new mints score 15-25+on thin data, which used to disqualify every `min_oracle_score` strategy from+ever sniping a launch.+## Environment| Var | Required | Default | Notes |@@ -93,7 +131,11 @@ Enforced in `executeBuy`, short-circuiting before any transaction:| `SNIPER_POLL_MS` | | `5000` | Position re-quote cadence. || `SNIPER_MAX_GLOBAL_BUYS_PER_MIN` | | `10` | Platform-wide buy throttle backstop. || `SNIPER_MAYHEM_FILTER` | | `1` | Enforce the no-Mayhem rule (skip pump.fun Mayhem-mode tokens). `0` disables. |-| `SNIPER_MAYHEM_STRICT` | | `0` | `1` = skip a buy when the bonding curve can't be read (default allows-on-unknown, logged). |+| `SNIPER_MAYHEM_STRICT` | | `1` | Skip a buy when the bonding curve can't be read even after retries (never buy Mayhem, not "buy when unsure"). `0` restores allow-on-unknown. |+| `SNIPER_ORACLE_MATURITY_S` | | `900` | A below-threshold Oracle score on a coin younger than this counts as unscored (fail open); provisional thin-data scores must not disqualify launch snipes. |+| `SNIPER_LLM_MAX_CONCURRENT` | | `3` | LLM-judge concurrency cap; launches beyond it are skipped with a log line, never queued unboundedly. |+| `SNIPER_LLM_TIMEOUT_MS` | | `9000` | Per-verdict LLM time budget. |+| `OPENROUTER_API_KEY` | llm arms | unset | One key serves every experiment model; the free-first `llmComplete` chain backstops an outage. || `SNIPER_AGENT_IDS` | | — | Comma/space-separated agent UUID allowlist. Unset = all agents for the network. || `SNIPER_MIN_MC_FLOOR_USD` | | — | Fleet-wide market-cap floor (USD). Buys below it are skipped across every agent; a per-strategy `min_market_cap_usd` only tightens it. Unset = no floor. || `SNIPER_MAX_MC_CEIL_USD` | | — | Fleet-wide market-cap ceiling (USD). Buys above it are skipped; a per-strategy `max_market_cap_usd` only tightens it. Unset = no ceiling. |diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex 2805c3600..9c0f4d779 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -22,6 +22,7 @@ import {SOL_FEE_HEADROOM_LAMPORTS,} from '../../api/_lib/agent-trade-guards.js';import { buildAmmSellInstructions } from './amm-exit.js';+import { getWalletBaseBalance, reconcileVanishedBag } from './reconcile.js';import { assessTradeSafety, recordFirewallDecision, criticalFirewallReason } from '../../api/_lib/trade-firewall.js';import { recordDecision } from '../../api/_lib/reasoning-ledger.js';import { screenPush } from './screen-push.js';@@ -72,6 +73,7 @@ async function recordSnipeDecision({ strat, network, mint, posId, sig, mode, pribuy_sig: sig && sig !== 'SIMULATED' ? sig : null,mode,symbol: mint.symbol || null,+ llm: mint.llm ? { model: mint.llm.model, confidence: mint.llm.confidence, thesis: mint.llm.thesis } : null,},prediction: { direction: 'up', basis: 'snipe entry expects a profitable exit', metric: 'realized_pnl' },rationale,@@ -469,7 +471,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {await journalEntry({cfg, strat, mint, posId, sig,score: mint.score ?? null,- rationale: `Entered on ${mint.entry_trigger || 'new_mint'}${mint.market_cap_usd != null ? ` at ~$${Math.round(mint.market_cap_usd).toLocaleString()} mcap` : ''}${firewallSnapshot ? ` (firewall ${firewallSnapshot.verdict}, score ${firewallSnapshot.score})` : ''}; ${lamportsToSol(perTrade).toFixed(4)} SOL, impact ${Number(quote.priceImpactPct).toFixed(2)}%.`,+ rationale: `Entered on ${mint.entry_trigger || 'new_mint'}${mint.market_cap_usd != null ? ` at ~$${Math.round(mint.market_cap_usd).toLocaleString()} mcap` : ''}${firewallSnapshot ? ` (firewall ${firewallSnapshot.verdict}, score ${firewallSnapshot.score})` : ''}; ${lamportsToSol(perTrade).toFixed(4)} SOL, impact ${Number(quote.priceImpactPct).toFixed(2)}%.${mint.llm ? ` LLM ${mint.llm.model} judged buy at ${Math.round(mint.llm.confidence * 100)}%: ${mint.llm.thesis}` : ''}`,});screenPush(`Bought $${(mint.symbol || mint.mint.slice(0, 6)).toUpperCase()} at ${lamportsToSol(perTrade).toFixed(4)} SOL — position open`, 'trade');notifyBuy({ agentName: strat.agent_name || strat.agent_id, symbol: mint.symbol, mint: mint.mint, solSpent: lamportsToSol(perTrade), mode: cfg.mode, sig, chatId: strat.telegram_chat_id || null });@@ -510,6 +512,31 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recoverconst { keypair } = loaded;const ctx = await getTradeCtx(cfg.network);++ // Retry of a previously-failed sell → make the CHAIN the source of truth+ // before re-broadcasting. A sell whose confirmation timed out may have+ // landed anyway; retrying it then simulates a sell of tokens the wallet no+ // longer holds and fails forever (pump 6023 NotEnoughTokensToSell), burning+ // RPC every sweep. Balance 0 → find the landed tx and book its real+ // proceeds; balance short of the DB amount → sell what's actually there.+ if (position.error) {+ const realBalance = await getWalletBaseBalance(ctx, keypair.publicKey, position.mint);+ if (realBalance != null) {+ if (realBalance === 0n) {+ const reconciled = await reconcileVanishedBag({ ctx, position, reason });+ if (reconciled) return { status: 'closed', reason: 'reconciled_onchain' };+ // Emptying tx not found yet (history lag); hold for the next sweep+ // rather than re-broadcasting a sell that cannot succeed.+ await sql`UPDATE agent_sniper_positions SET status = 'open', error = 'reconcile_pending', last_quoted_at = now() WHERE id = ${position.id}`;+ return { status: 'retry', reason: 'reconcile_pending' };+ }+ if (realBalance < sellBaseBig) {+ log.warn('sell clamped to real wallet balance', { ...tag, db_base: sellBaseBig.toString(), real_base: realBalance.toString() });+ sellBaseBig = realBalance;+ }+ }+ }+const mintPk = new ctx.web3.PublicKey(position.mint);const baseAmount = bn(ctx, sellBaseBig);const slippagePct = (position.slippage_bps ?? 500) / 100;diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.jsindex fc22397f3..615dd883e 100644--- a/workers/agent-sniper/index.js+++ b/workers/agent-sniper/index.js@@ -17,6 +17,7 @@ import { refreshStrategies, cachedStrategies, logStrategyLoad } from './strategyimport { scoreMint, scoreIntel } from './scorer.js';import { executeBuy } from './executor.js';import { oracleGate } from './oracle-gate.js';+import { judgeLaunch } from './llm-judge.js';import { runPositionSweep } from './positions.js';import { runSwarmConsensus, runSwarmSettlement } from './swarm.js';import { startFirstClaimWatch } from './first-claim-watch.js';@@ -137,6 +138,29 @@ async function main() {// The new-mint feed only drives new_mint strategies; first_claim// strategies are driven by the on-chain claim poll loop below.if ((strat.trigger || 'new_mint') !== 'new_mint') continue;++ // LLM-judged experiment arm: no rule shields, no oracle gate: a model+ // reads the launch and decides. The executeBuy chokepoint still enforces+ // every safety rail (Mayhem, firewall round-trip, budgets, headroom).+ if ((strat.decision_mode || 'rules') === 'llm') {+ queue.push(async () => {+ const verdict = await judgeLaunch(data, strat);+ if (!verdict) return;+ const minConf = Number(strat.llm_min_confidence ?? 0.6);+ if (!verdict.buy || verdict.confidence < minConf) {+ log.info('llm judge pass', { agent: strat.agent_id, mint: data.mint, model: verdict.model, buy: verdict.buy, confidence: verdict.confidence });+ return;+ }+ log.info('llm judge buy', { agent: strat.agent_id, mint: data.mint, model: verdict.model, confidence: verdict.confidence, thesis: verdict.thesis });+ screenPush(`$${sym} LLM verdict: BUY at ${Math.round(verdict.confidence * 100)}%: ${verdict.thesis}`, 'trade');+ await executeBuy({+ cfg, strat, throttle,+ mint: { ...data, entry_trigger: 'llm_judge', trigger_ref: verdict.model, score: verdict.confidence, llm: verdict },+ });+ });+ continue;+ }+const { pass, score, reasons } = scoreMint(data, strat);if (!pass) continue;log.info('candidate', { agent: strat.agent_id, mint: data.mint, symbol: data.symbol, score, reasons });diff --git a/workers/agent-sniper/llm-judge.js b/workers/agent-sniper/llm-judge.jsnew file mode 100644index 000000000..7327f4f74--- /dev/null+++ b/workers/agent-sniper/llm-judge.js@@ -0,0 +1,172 @@+// agent-sniper, LLM-judged entries (decision_mode = 'llm').+//+// Some strategies deliberately carry NO rule shields: no market-cap band, no+// socials requirement, no oracle threshold. Instead, each new launch is put in+// front of a model (per-strategy, e.g. x-ai/grok-*, anthropic/claude-*, or+// openrouter/auto) which returns a buy/skip verdict with a confidence and a+// one-line thesis. This is an EXPERIMENT ARM to compare judgment against rules;+// the non-negotiable safety rails still apply at the executeBuy chokepoint for+// every mode: Mayhem exclusion, the trade firewall's real buy→sell round-trip,+// budgets, concurrency, SOL headroom, and the shared spend policy.+//+// Cost + latency control:+// • One verdict per (mint, model), agents sharing a model share the call.+// • A small global concurrency cap; when the firehose outruns it, launches+// are skipped with a log line (never queued unboundedly).+// • OpenRouter is the primary route (one key, every experiment model). When+// it fails, the platform's free-first llmComplete chain is the backstop and+// the verdict is tagged with the model that actually answered.++import { log } from './log.js';+import { llmComplete } from '../../api/_lib/llm.js';++const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';++const MAX_CONCURRENT = Math.max(1, Number(process.env.SNIPER_LLM_MAX_CONCURRENT || 3));+const TIMEOUT_MS = Math.max(2_000, Number(process.env.SNIPER_LLM_TIMEOUT_MS || 9_000));+const VERDICT_TTL_MS = 10 * 60_000;++let _active = 0;+const _verdicts = new Map(); // `${mint}:${model}` → { promise|value, ts }++const SYSTEM_PROMPT = [+ 'You are the buy-side judge for an autonomous pump.fun sniper on Solana.',+ 'You will be shown one brand-new token launch. Decide whether a small,',+ 'time-boxed momentum position (held minutes, hard stop-loss) is worth taking.',+ 'Weigh: name/ticker memetic quality, narrative timing, socials, the creator\'s',+ 'launch history, the size of the dev\'s initial buy, and market cap.',+ 'Most launches are worthless; be selective, but you are the only judge, there',+ 'are no other filters after you besides honeypot/safety checks.',+ 'Respond with ONLY a JSON object, no prose, no code fences:',+ '{"buy": true|false, "confidence": <0..1>, "thesis": "<one short sentence>"}',+].join(' ');++function launchBrief(mint) {+ const fields = {+ symbol: mint.symbol || null,+ name: mint.name || null,+ description: mint.description || null,+ twitter: mint.twitter || null,+ telegram: mint.telegram || null,+ website: mint.website || null,+ market_cap_usd: mint.market_cap_usd != null ? Math.round(Number(mint.market_cap_usd)) : null,+ dev_initial_buy_sol: mint.initial_buy_sol != null ? Number(mint.initial_buy_sol) : null,+ creator_prior_launches: mint.creator_launches ?? null,+ creator_graduated_coins: mint.creator_graduated ?? null,+ };+ const lines = Object.entries(fields)+ .filter(([, v]) => v != null && v !== '')+ .map(([k, v]) => `${k}: ${v}`);+ return `New pump.fun launch:\n${lines.join('\n')}`;+}++// Parse the model's reply into a verdict. Tolerates fences/prose around the+// JSON but rejects anything without the three required fields.+export function parseVerdict(text) {+ if (!text) return null;+ const match = String(text).match(/\{[\s\S]*\}/);+ if (!match) return null;+ let obj;+ try {+ obj = JSON.parse(match[0]);+ } catch {+ return null;+ }+ if (typeof obj.buy !== 'boolean') return null;+ const confidence = Number(obj.confidence);+ if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) return null;+ return { buy: obj.buy, confidence, thesis: String(obj.thesis || '').slice(0, 280) };+}++async function askOpenRouter({ model, user }) {+ const key = process.env.OPENROUTER_API_KEY;+ if (!key) throw new Error('OPENROUTER_API_KEY not configured');+ const ac = new AbortController();+ const timer = setTimeout(() => ac.abort(), TIMEOUT_MS);+ try {+ const resp = await fetch(OPENROUTER_URL, {+ method: 'POST',+ signal: ac.signal,+ headers: {+ authorization: `Bearer ${key}`,+ 'content-type': 'application/json',+ 'x-title': 'three.ws agent-sniper',+ },+ body: JSON.stringify({+ model,+ max_tokens: 200,+ temperature: 0.2,+ messages: [+ { role: 'system', content: SYSTEM_PROMPT },+ { role: 'user', content: user },+ ],+ }),+ });+ if (!resp.ok) {+ const body = await resp.text().catch(() => '');+ throw new Error(`openrouter ${resp.status}: ${body.slice(0, 160)}`);+ }+ const body = await resp.json();+ return body?.choices?.[0]?.message?.content || '';+ } finally {+ clearTimeout(timer);+ }+}++async function judge(mint, model) {+ const user = launchBrief(mint);+ const t0 = Date.now();+ try {+ const text = await askOpenRouter({ model, user });+ const verdict = parseVerdict(text);+ if (verdict) return { ...verdict, model, latencyMs: Date.now() - t0 };+ throw new Error('unparseable verdict');+ } catch (err) {+ // Free-first platform chain as the backstop, the experiment arm keeps+ // running through an OpenRouter outage, honestly labeled.+ log.warn('llm judge openrouter failed, free-chain fallback', { mint: mint.mint, model, err: err?.message });+ const res = await llmComplete({ system: SYSTEM_PROMPT, user, maxTokens: 200, timeoutMs: TIMEOUT_MS });+ const verdict = parseVerdict(res?.text ?? res);+ if (!verdict) return null;+ return { ...verdict, model: `fallback:${res?.provider || 'free-chain'}`, latencyMs: Date.now() - t0 };+ }+}++/**+ * Judge one launch for one strategy. Returns a verdict+ * `{ buy, confidence, thesis, model, latencyMs }` or null (saturated / failed,+ * null never buys). Verdicts are shared per (mint, model) and cached briefly so+ * a fleet of same-model strategies costs one call per launch.+ */+export async function judgeLaunch(mint, strat) {+ const model = strat.llm_model || 'openrouter/auto';+ const key = `${mint.mint}:${model}`;+ const cached = _verdicts.get(key);+ if (cached && Date.now() - cached.ts < VERDICT_TTL_MS) return cached.promise;++ if (_active >= MAX_CONCURRENT) {+ log.info('llm judge saturated, skipping launch', { mint: mint.mint, model, active: _active });+ return null;+ }+ _active++;+ const promise = judge(mint, model)+ .catch((err) => {+ log.warn('llm judge failed', { mint: mint.mint, model, err: err?.message });+ return null;+ })+ .finally(() => {+ _active--;+ });+ _verdicts.set(key, { promise, ts: Date.now() });+ if (_verdicts.size > 500) {+ const cutoff = Date.now() - VERDICT_TTL_MS;+ for (const [k, v] of _verdicts) if (v.ts < cutoff) _verdicts.delete(k);+ }+ return promise;+}++/** Test seam: reset shared state. */+export function _resetLlmJudge() {+ _verdicts.clear();+ _active = 0;+}diff --git a/workers/agent-sniper/mayhem-gate.js b/workers/agent-sniper/mayhem-gate.jsindex 232475f6e..31ac9afe2 100644--- a/workers/agent-sniper/mayhem-gate.js+++ b/workers/agent-sniper/mayhem-gate.js@@ -12,11 +12,14 @@// 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.+// SNIPER_MAYHEM_STRICT=0: allow-on-unknown (default: strict, skip the buy+// when the curve can't be read even after retries;+// the owner rule is NEVER buy Mayhem, not "buy when+// unsure"). Reads rotate the platform RPC chain and+// retry, so unknowns are rare, not the common case.import { createMayhemFilter } from '../../packages/agent-sniper/src/mayhem-filter.js';+import { getConnection } from '../../api/_lib/pump.js';import { log } from './log.js';/**@@ -37,7 +40,14 @@ export function mayhemVerdict(isMayhem, { strict = false } = {}) {let _filter = null;function getFilter(cfg) {if (_filter) return _filter;- _filter = createMayhemFilter({ rpcUrl: cfg?.rpcUrl || undefined, strictOnUnknown: !!cfg?.mayhemStrict });+ // Use the platform's rotating multi-endpoint connection (same chain as the+ // trade path), NOT a raw Connection pinned to one provider: a single throttled+ // endpoint used to fail every read into "unknown", which on a strict gate+ // skipped every buy fleet-wide. Retries are safe; the flag is immutable.+ _filter = createMayhemFilter({+ connection: getConnection({ network: cfg?.network || 'mainnet' }),+ strictOnUnknown: !!cfg?.mayhemStrict,+ });return _filter;}diff --git a/workers/agent-sniper/oracle-gate.js b/workers/agent-sniper/oracle-gate.jsindex b17c38cb4..cc2d5cdb1 100644--- a/workers/agent-sniper/oracle-gate.js+++ b/workers/agent-sniper/oracle-gate.js@@ -18,9 +18,17 @@import { sql } from '../../api/_lib/db.js';import { log } from './log.js';-const _cache = new Map(); // key → { score, ts }+const _cache = new Map(); // key → { score, firstSeenAt, ts }const CACHE_TTL_MS = 30_000;+// A conviction score only GATES once the coin is old enough for the Oracle to+// have real data. Brand-new mints score 15-25 on thin defaults, which silently+// disqualified every min_oracle_score strategy from ever sniping a launch: the+// gate saw a "low score" where there was really "no signal yet". Younger than+// this, a below-threshold score is treated exactly like an unscored coin (fail+// open, logged); at or past it, the threshold bites for real.+const ORACLE_MATURITY_S = Math.max(0, Number(process.env.SNIPER_ORACLE_MATURITY_S || 900));+// Rugpull verdict cache (separate from the conviction cache).const _rugCache = new Map(); // key → { rejected, score, level, ts }const RUG_CACHE_TTL_MS = 30_000;@@ -203,7 +211,8 @@ export async function coinSentimentAdjustment(mint, network) {* Returns:* { pass: true } — scored and above threshold (or no threshold)* { pass: false, reason: string } — scored and below threshold- * { pass: true, skipped: true } — no Oracle score yet; gate deferred+ * { pass: true, skipped: true }: no Oracle score yet, or a provisional+ * below-threshold score on a coin younger than SNIPER_ORACLE_MATURITY_S; gate deferred* All results include macro_adjustment when a threshold was evaluated.** @param {string} mint@@ -224,17 +233,20 @@ export async function oracleGate(mint, network, strat) {const cacheKey = `${network}:${mint}`;const cached = _cache.get(cacheKey);let score;+ let firstSeenAt;if (cached && Date.now() - cached.ts < CACHE_TTL_MS) {score = cached.score;+ firstSeenAt = cached.firstSeenAt;} else {try {const [row] = await sql`- select score from oracle_conviction+ select score, coin_first_seen_at from oracle_convictionwhere mint = ${mint} and network = ${network}limit 1`;score = row?.score != null ? n(row.score) : null;- _cache.set(cacheKey, { score, ts: Date.now() });+ firstSeenAt = row?.coin_first_seen_at ? new Date(row.coin_first_seen_at).getTime() : null;+ _cache.set(cacheKey, { score, firstSeenAt, ts: Date.now() });// Prune the cache when it grows large.if (_cache.size > 2000) {const cutoff = Date.now() - CACHE_TTL_MS;@@ -260,6 +272,14 @@ export async function oracleGate(mint, network, strat) {const effectiveMin = minScore + macroAdj + coinAdj;if (score < effectiveMin) {+ // Provisional score on a coin the Oracle has barely seen → same treatment as+ // unscored: fail open. A minutes-old launch cannot have earned a meaningful+ // conviction score, and gating on the thin-data default (~15-25) meant a+ // min_oracle_score strategy could never snipe a launch at all.+ const coinAgeMs = firstSeenAt != null ? Date.now() - firstSeenAt : null;+ if (coinAgeMs != null && coinAgeMs < ORACLE_MATURITY_S * 1000) {+ return { pass: true, skipped: true, reason: `oracle_immature:${Math.round(coinAgeMs / 1000)}s<${ORACLE_MATURITY_S}s` };+ }const parts = [];if (macroAdj !== 0) parts.push(`macro:${macroAdj}`);if (coinAdj !== 0) parts.push(`coin:${coinAdj}`);diff --git a/workers/agent-sniper/reconcile.js b/workers/agent-sniper/reconcile.jsnew file mode 100644index 000000000..81d26cb20--- /dev/null+++ b/workers/agent-sniper/reconcile.js@@ -0,0 +1,109 @@+// agent-sniper, on-chain position reconciliation.+//+// A sell whose confirmation times out may still LAND. The old behaviour trusted+// the DB alone: the position stayed 'open', every sweep retried the sell, and the+// retry simulated a sell of tokens the wallet no longer holds, pump program+// error 6023 (NotEnoughTokensToSell), forever. One stuck position burned RPC+// quota for 37 hours that way. These helpers make the chain the source of truth+// on a retry: read the wallet's REAL base-token balance, and when the bag is+// already gone, find the transaction that emptied it and book its actual+// proceeds instead of retrying a sell that can never succeed.++import { sql } from '../../api/_lib/db.js';+import { log } from './log.js';++/**+ * The wallet's actual balance of `mint` (raw base units), summed across token+ * accounts (pump coins are token-2022; the mint filter covers both programs).+ * Returns null when the read fails, callers must treat null as "unknown", not 0.+ * @returns {Promise<bigint|null>}+ */+export async function getWalletBaseBalance(ctx, ownerPk, mint) {+ try {+ const res = await ctx.connection.getParsedTokenAccountsByOwner(ownerPk, {+ mint: new ctx.web3.PublicKey(mint),+ });+ let total = 0n;+ for (const { account } of res?.value || []) {+ const amt = account?.data?.parsed?.info?.tokenAmount?.amount;+ if (amt != null) total += BigInt(amt);+ }+ return total;+ } catch (err) {+ log.warn('wallet balance read failed', { mint, err: err?.message });+ return null;+ }+}++/**+ * The position's tokens are gone from the wallet, find the transaction that+ * emptied them and close the position with its REAL proceeds. Scans the token+ * account's recent history (newest first), skipping the buy signature, for a+ * successful tx where this owner's balance for the mint dropped to zero, and+ * books the owner's net SOL delta from that tx as the exit.+ *+ * Returns true when the position was closed, false when the emptying tx could+ * not be found (caller leaves the position for the next sweep, never guess).+ */+export async function reconcileVanishedBag({ ctx, position, reason }) {+ const tag = { agent: position.agent_id, mint: position.mint, symbol: position.symbol };+ try {+ const owner = position.wallet;+ const mintPk = new ctx.web3.PublicKey(position.mint);+ const ownerPk = new ctx.web3.PublicKey(owner);+ const accounts = await ctx.connection.getParsedTokenAccountsByOwner(ownerPk, { mint: mintPk });+ const tokenAccounts = (accounts?.value || []).map((a) => a.pubkey);+ if (!tokenAccounts.length) return false;++ for (const ata of tokenAccounts) {+ const sigs = await ctx.connection.getSignaturesForAddress(ata, { limit: 20 });+ for (const s of sigs || []) {+ if (s.err || s.signature === position.buy_sig) continue;+ const tx = await ctx.connection.getParsedTransaction(s.signature, {+ maxSupportedTransactionVersion: 0,+ });+ if (!tx || tx.meta?.err) continue;+ const pre = (tx.meta?.preTokenBalances || []).find(+ (b) => b.owner === owner && b.mint === position.mint,+ );+ const post = (tx.meta?.postTokenBalances || []).find(+ (b) => b.owner === owner && b.mint === position.mint,+ );+ const preAmt = pre ? BigInt(pre.uiTokenAmount.amount) : 0n;+ const postAmt = post ? BigInt(post.uiTokenAmount.amount) : 0n;+ if (preAmt <= 0n || postAmt !== 0n) continue;++ // This is the tx that emptied the bag. The owner's net SOL delta is the+ // honest proceeds (sale minus fees it paid in the same tx).+ const keys = tx.transaction.message.accountKeys || [];+ const ownerIdx = keys.findIndex((k) => (k.pubkey?.toBase58?.() || String(k.pubkey)) === owner);+ if (ownerIdx < 0) continue;+ const solDelta = BigInt(tx.meta.postBalances[ownerIdx]) - BigInt(tx.meta.preBalances[ownerIdx]);+ const proceeds = solDelta > 0n ? solDelta : 0n;++ const entry = BigInt(position.entry_quote_lamports || '0');+ const prior = BigInt(position.realized_pnl_lamports || '0');+ const realized = prior + proceeds - entry;+ const pct = entry > 0n ? (Number(realized) / Number(entry)) * 100 : 0;+ await sql`+ UPDATE agent_sniper_positions SET+ status = 'closed', exit_reason = ${reason}, sell_sig = ${s.signature},+ exit_quote_lamports = ${proceeds.toString()},+ realized_pnl_lamports = ${realized.toString()},+ realized_pnl_pct = ${pct},+ error = 'reconciled_onchain',+ closed_at = now()+ WHERE id = ${position.id}+ `;+ log.trade('sell reconciled from chain', {+ ...tag, sig: s.signature, proceeds_sol: Number(proceeds) / 1e9, pnl_pct: pct.toFixed(1),+ });+ return true;+ }+ }+ return false;+ } catch (err) {+ log.warn('reconcile failed, will retry next sweep', { ...tag, err: err?.message });+ return false;+ }+}