Skip to content

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

feat: Add tasks for next-gen trading features including signal marketplace, trading swarms, launch copilot, mission control terminal, trading arena tournaments, and end-to-end testing harness

roundtrippedf5e70277fc2b
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 80b991d84..684d68381 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -14,9 +14,10 @@ import {
} from '@solana/web3.js';
import {
getAssociatedTokenAddressSync, createTransferCheckedInstruction,
- createAssociatedTokenAccountIdempotentInstruction, getMint,
+ createAssociatedTokenAccountIdempotentInstruction, createCloseAccountInstruction, getMint,
TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
} from '@solana/spl-token';
+import { grindMintKeypair, estimateAttempts, BASE58_ALPHABET } from '../_lib/pump-vanity.js';
import { webcrypto, randomUUID } from 'node:crypto';
import { env } from '../_lib/env.js';
import { recordEvent } from '../_lib/usage.js';
diff --git a/tasks/next-gen-trading/05-nl-strategy-compiler-backtester.md b/tasks/next-gen-trading/05-nl-strategy-compiler-backtester.md
new file mode 100644
index 000000000..9a8730137
--- /dev/null
+++ b/tasks/next-gen-trading/05-nl-strategy-compiler-backtester.md
@@ -0,0 +1,102 @@
+# Task 05 — Natural-Language Strategy Compiler + Historical Backtester
+
+> **Operating bar (applies to the whole task).** Senior engineer + product thinker building
+> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no
+> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%
+> end-to-end with REAL APIs and real data. Every state designed. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade
+> plumbing are the only exception and are never promoted. After it works, self-review and ship
+> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the
+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.
+
+## The invention
+
+Sniper config today is a wall of numeric fields most users can't reason about. We let a user
+**describe a strategy in plain English** — "snipe coins from creators who've graduated at least
+two, market cap under $30k, organic wallet distribution, smart money buying, take profit at 3x,
+stop loss 40%, max 0.3 SOL per trade" — an LLM compiles it to a **validated**
+`agent_sniper_strategies` row, and then we **backtest it against our own real historical data**
+(`pump_coin_intel` + `pump_coin_outcomes`) so the user sees an honest projected win-rate, ROI
+distribution, and worst-drawdown *before risking a lamport*. Nobody else can backtest pump.fun
+strategies because nobody else has captured the structural history. We do.
+
+## Context (real, verified)
+
+- Historical truth: `pump_coin_intel` (per-launch signals: bundle/organic/concentration/
+ snipe_ratio/fresh_wallet_ratio, quality_score, category, narrative) joined to
+ `pump_coin_outcomes` (graduated/pumped/flat/rugged, `ath_multiple`, `ath_market_cap_usd`).
+- Strategy schema + scoring semantics to compile *to* and replay *with*:
+ `api/_lib/migrations/20260615020000_agent_sniper.sql`, `workers/agent-sniper/scorer.js`
+ (`scoreMint`, `scoreIntel`) and exit logic `workers/agent-sniper/positions.js#decideExit`
+ (stop/trailing/take-profit/timeout). Reuse the *exact* gate + scoring functions so the
+ backtest matches live behavior.
+- LLM access: worker proxies for OpenAI/Anthropic already exist in the platform (per CLAUDE.md
+ "Real APIs in use … OpenAI/Anthropic via worker proxies"). Use the platform's existing LLM
+ proxy/util — do not add a new key path or call providers directly from the browser.
+- Strategy CRUD endpoint: `api/sniper/strategy.js`. Wallet-hub snipe tab: `src/agent-wallet-hub/tabs/snipe.js`.
+
+## Goal
+
+`POST /api/sniper/compile` (NL → validated strategy JSON + rationale) and
+`POST /api/sniper/backtest` (strategy → replay over historical intel/outcomes → metrics),
+surfaced as a conversational strategy builder in the snipe UI that ends in a one-click "Arm this".
+
+## What to build
+
+1. **Compiler** — `api/_lib/strategy-compiler.js`: send the user's text + a strict JSON schema of
+ the real strategy fields to the LLM (function-calling / structured output), then **validate
+ hard** against allowed ranges (stop_loss mandatory > 0, budgets sane, slippage bounded). Return
+ the compiled strategy, a plain-language summary of what it will do, and any clamped/assumed
+ fields called out explicitly. Reject incoherent requests with a helpful message — never emit an
+ unsafe config.
+2. **Backtester** — `api/_lib/strategy-backtest.js`: load the historical universe (windowed,
+ e.g. last 30/90 days, network-scoped) from `pump_coin_intel ⋈ pump_coin_outcomes`. For each
+ historical launch, apply the **same** hard gates/score from `scorer.js` to decide if the
+ strategy would have entered; simulate the exit using `decideExit` semantics against the
+ recorded `ath_multiple` / outcome (entry slippage + price-impact modeled honestly from recorded
+ structure). Produce: entries taken, win-rate, median + p90/p10 ROI, expected value per trade,
+ max drawdown, exposure, and a sample of representative hits/misses with real mints. Be explicit
+ about survivorship/labeling limits — show sample size and a confidence caveat.
+3. **API** — `/api/sniper/compile` + `/api/sniper/backtest` (auth, rate-limited). Backtest must be
+ pure read-only over real data; cache by strategy hash.
+4. **UI — conversational strategy builder** in `src/agent-wallet-hub/tabs/snipe.js`: a chat-style
+ input ("describe your strategy"), the compiled strategy rendered as editable chips (every field
+ adjustable), a live backtest report (distribution chart, win-rate, EV, drawdown, example
+ trades), and an "Arm this strategy" button that writes via `api/sniper/strategy.js`. Designed
+ loading (real async, skeletons), empty (prompt examples), error (LLM/data failure with retry),
+ and populated states. Accessible + responsive.
+5. **Backtest-vs-live honesty** — store each backtest snapshot (`strategy_backtests` table:
+ strategy hash, window, metrics jsonb, sample_size, ran_at) and, once a strategy is armed and
+ trading, show projected-vs-realized side by side on the trader profile so the projection is
+ accountable, not marketing.
+
+## Constraints
+
+- The backtest replays **real captured history** only — never synthesize launches or outcomes,
+ never inflate win-rates. If the historical window is too thin, say "insufficient data" rather
+ than show a flattering number. This honesty is the product.
+- The compiler must never produce a strategy that bypasses spend guards or the firewall; clamp to
+ the same limits enforced at runtime (`agent-trade-guards.js`).
+- LLM calls go through the existing platform proxy with real keys; handle timeouts/failures at the
+ boundary with a clear retry path. No browser-side provider keys.
+- $THREE-only; example mints in copy must be $THREE or clearly synthetic.
+
+## Success criteria
+
+- A plain-English description compiles to a valid, range-checked strategy with a readable summary.
+- Backtest returns honest metrics computed from real `pump_coin_intel`/`pump_coin_outcomes` using
+ the same gates/exits as live, with sample size + caveats shown.
+- "Arm this" persists the strategy; projected-vs-realized appears once it trades.
+- Build/typecheck/test clean. Changelog entry (tags: feature, improvement). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file
+
+```bash
+git rm "tasks/next-gen-trading/05-nl-strategy-compiler-backtester.md"
+```
+
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/next-gen-trading/06-signal-marketplace-x402.md b/tasks/next-gen-trading/06-signal-marketplace-x402.md
new file mode 100644
index 000000000..b661b6733
--- /dev/null
+++ b/tasks/next-gen-trading/06-signal-marketplace-x402.md
@@ -0,0 +1,99 @@
+# Task 06 — Reputation-Gated Signal Marketplace (x402 paid alpha feeds)
+
+> **Operating bar (applies to the whole task).** Senior engineer + product thinker building
+> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no
+> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%
+> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade
+> plumbing are the only exception and are never promoted. After it works, self-review and ship
+> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the
+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.
+>
+> **Depends on task 03 (smart-money graph).** Reputation gating uses real track records.
+
+## The invention
+
+We have **verifiable on-chain track records** (`trader-stats.js` composite score + verification
+badge) and **x402 agent-to-agent micropayments**. Combine them into the first **trust-gated
+signal marketplace**: a trader whose track record is verified can publish their live entry/exit
+signals as an x402-metered feed; a follower's *agent* pays per signal (or per epoch) and mirrors
+the trade automatically from its own wallet, with the firewall + spend guards intact. Signals are
+**performance-bonded and accountable** — every published signal's realized outcome is tracked, so
+the marketplace ranks sellers by *proven* edge, not follower count. This is copy-trading with
+real economics and real accountability, which no one in this space has.
+
+## Context (real, verified)
+
+- Track record + verification: `api/_lib/trader-stats.js` (`computeTraderMetrics`, `verified`
+ badge: 12+ closed, 5+ coins, ≤40% churn, >0 realized SOL). Leaderboard: `api/sniper/leaderboard.js`.
+- x402 micropayments: `api/x402-pay.js` (per-agent USDC settlement, SSE, spend tracking via
+ `agent-trade-guards.js`); A2A scaffolding: `api/agents/a2a-*.js`, `agent_payments` ledger.
+- Copy scaffolding already present: `copy_subscriptions` table + `activeCopierCounts` /
+ `copierCountForAgent` in `trader-stats.js`. Build the marketplace ON this — finish it.
+- Live position events: `api/sniper/stream.js` (SSE open/buy/sell/close) — the raw signal source.
+- Mirror execution reuses `api/agents/agent-trade.js`/`executor.js`, the firewall (01), MEV (02).
+
+## Goal
+
+A signal marketplace where verified traders publish x402-metered signal feeds and follower agents
+subscribe + auto-mirror, with per-signal accountability and a ranked, real-performance directory.
+
+## What to build
+
+1. **Publisher side** — let a verified agent (gate on `trader-stats` `verified === true`) create a
+ **signal feed**: pricing (x402 per-signal USDC and/or per-epoch subscription), what it emits
+ (entries, exits, sizing %), and visibility. New `signal_feeds` + `signal_emissions` tables
+ (feed config; each emission: mint, side, size_pct, conviction, emitted_at, realized_outcome
+ filled in later). Emissions are generated **from the publisher's real trades** (hook the
+ position lifecycle / sniper fills) — never hand-authored, never fake.
+2. **x402 metering** — gate feed reads behind `api/x402-pay.js`: a subscriber agent pays USDC from
+ its own wallet per signal or per epoch; settlement flows through the existing per-agent path
+ with custody audit (`agent_custody_events`, category `signal`) and spend guards. Idempotent;
+ respect daily caps + kill switch. Publisher earns real USDC.
+3. **Subscriber auto-mirror** — `signal_subscriptions` (subscriber_agent_id, feed_id, mode
+ simulate|live, size_scaling, max_per_trade, slippage, firewall_level). On a new paid emission,
+ the subscriber agent mirrors the trade from its own wallet: scale size, run the firewall (01),
+ submit via MEV engine (02), record a position tagged with the source feed. All spend guards
+ apply. Simulate mode mirrors without spending for trust-building.
+4. **Accountability + ranking** — when a mirrored/published signal closes, record realized outcome
+ on the emission and roll up per-feed stats (hit-rate, avg follower ROI, latency from emit→fill).
+ `GET /api/signals/marketplace` ranks feeds by **proven realized edge** (not follower count),
+ reusing `trader-stats` confidence regression so thin feeds don't top the board.
+5. **API + UI** — `/api/signals/feeds` (CRUD, publisher), `/api/signals/marketplace` (public,
+ ranked), `/api/signals/subscribe` (subscriber), `/api/signals/stream` (paid SSE of emissions).
+ Build a **Signals** product surface: marketplace directory (each feed shows verified track
+ record + realized signal accuracy + price), a feed detail page, and a subscriber control panel
+ in the wallet hub (mode, sizing, kill). Designed empty/loading/error/populated; accessible;
+ responsive.
+
+## Constraints
+
+- Only **verified** track records can publish; the verification + score come from real closed
+ trades via `trader-stats.js`, never self-declared. Sellers cannot fake performance — emissions
+ bind to real on-chain fills and realized outcomes.
+- Real x402 USDC settlement only — no simulated payments in live mode; simulate mode is clearly
+ labeled and spends nothing. Every payment audited and spend-guarded.
+- Mirror trades obey the firewall + spend limits + kill switch with no exception; a subscriber can
+ always halt instantly and withdraw.
+- $THREE-only rule; the marketplace ranks *traders/feeds*, never promotes a token. Mints shown are
+ runtime trade data only.
+
+## Success criteria
+
+- A verified agent publishes a feed; a subscriber agent pays real x402 USDC and auto-mirrors a
+ real trade through the firewall + MEV engine, fully audited.
+- Emissions accrue realized outcomes; marketplace ranks by proven edge with confidence regression.
+- Signals UI (marketplace, feed detail, subscriber panel) renders all states; instant kill works.
+- Build/typecheck/test clean. Changelog entry (tags: feature, sdk). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file
+
+```bash
+git rm "tasks/next-gen-trading/06-signal-marketplace-x402.md"
+```
+
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/next-gen-trading/07-trading-swarms.md b/tasks/next-gen-trading/07-trading-swarms.md
new file mode 100644
index 000000000..05d00d330
--- /dev/null
+++ b/tasks/next-gen-trading/07-trading-swarms.md
@@ -0,0 +1,100 @@
+# Task 07 — Agent Trading Swarms (pooled treasury + shared signals + pro-rata x402 payouts)
+
+> **Operating bar (applies to the whole task).** Senior engineer + product thinker building
+> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no
+> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%
+> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade
+> plumbing are the only exception and are never promoted. After it works, self-review and ship
+> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the
+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.
+>
+> **Depends on task 06 (signal marketplace) and tasks 01/02/03.**
+
+## The invention
+
+Solo snipers are capital- and signal-limited. A **trading swarm** lets multiple agents pool
+capital into a shared, auditable treasury and combine their individual signals into one
+**consensus conviction** — the swarm only fires when enough reputable members agree, sizing by
+combined edge. Profits and losses distribute **pro-rata to each member's contribution via real
+x402 settlement**, with a transparent on-chain-auditable ledger. It's a self-organizing,
+permissionless trading guild of AI agents — a primitive that simply does not exist anywhere.
+
+## Context (real, verified)
+
+- Per-agent custodial wallets + signing: `api/_lib/agent-wallet.js` (`recoverSolanaAgentKeypair`),
+ custody audit `agent_custody_events`, spend guards `api/_lib/agent-trade-guards.js`.
+- x402 agent-to-agent settlement for payouts: `api/x402-pay.js`, `agent_payments` ledger,
+ `api/agents/a2a-*.js`.
+- Member signals come from task 06 `signal_emissions` and/or each member's own sniper score
+ (`workers/agent-sniper/scorer.js`). Smart-money consensus from task 03.
+- Execution reuses `executor.js` / `agent-trade.js`, firewall (01), MEV engine (02).
+- Reputation weighting: `api/_lib/trader-stats.js` composite score.
+
+## Goal
+
+A swarm primitive: create/join a swarm, contribute capital to a swarm treasury wallet, a
+consensus engine that fires trades on weighted member agreement, and a real pro-rata
+profit-distribution settlement — all auditable, all spend-guarded, with a clean exit.
+
+## What to build
+
+1. **Swarm + treasury model** — `swarms` (id, name, owner_agent_id, network, policy jsonb:
+ min_consensus, max_per_trade, daily_budget, fee_bps to creator, join rules) and
+ `swarm_members` (swarm_id, agent_id, contribution_lamports, share_bps, joined_at, status).
+ The treasury is a dedicated custodial Solana wallet provisioned via the existing
+ `agent-wallet.js` provisioning path (a swarm is itself an agent-owned wallet) — real on-chain,
+ real custody audit. Members fund it by real SOL transfer; shares computed from net
+ contributions.
+2. **Consensus engine** — a worker loop (extend `workers/agent-sniper/`) that, per candidate mint,
+ gathers member signals (their sniper scores + task-06 emissions + task-03 smart-money), weights
+ them by each member's verified `trader-stats` score, and fires a buy from the **treasury wallet**
+ only when weighted agreement ≥ `min_consensus`. Size from combined conviction, bounded by swarm
+ policy + the firewall (01), executed via the MEV engine (02). Every decision logged with the
+ vote breakdown.
+3. **Pro-rata settlement** — on each closed position, compute realized PnL and distribute net
+ proceeds back to members **pro-rata by share** via real x402/SOL transfers from the treasury,
+ minus an optional creator fee (bps). Record every payout in `agent_payments` +
+ `agent_custody_events` (category `swarm_payout`). Idempotent, audited, spend-guarded. A member
+ can **exit** at any time: their share is settled out to their own wallet from current treasury
+ value (open positions handled by policy — settle-at-mark or wait-to-close, made explicit).
+4. **Anti-abuse** — cap any single member's share to prevent treasury capture; require the
+ firewall on every swarm buy; honor a swarm-level kill switch any member-with-threshold or the
+ creator can trigger; never let consensus override per-treasury spend limits.
+5. **API + UI** — `/api/swarms` (CRUD, join, contribute, exit), `/api/swarms/:id` (state, members,
+ positions, vote log, payout history), `/api/swarms/:id/stream` (SSE live decisions). Build a
+ **Swarms** surface: directory of open swarms (with verified aggregate track record), a swarm
+ dashboard (treasury balance, live consensus votes, open positions, member shares, payout
+ ledger), and join/contribute/exit flows with clear, honest disclosure of risk and fees. All
+ states designed; accessible; responsive.
+
+## Constraints
+
+- The treasury is real custodial SOL — every movement (contribution, trade, payout, exit) is a
+ real on-chain tx, spend-guarded and audited. No internal "virtual balances" that don't reconcile
+ to the on-chain treasury balance; the ledger must always tie out to chain.
+- Consensus fires only on real member signals; never fabricate a vote or a member.
+- Member funds are theirs: exit + withdraw must always be possible; never trap capital. Make the
+ open-position settlement policy explicit and fair.
+- $THREE-only rule; swarms trade arbitrary runtime mints but promote no token.
+
+## Success criteria
+
+- A swarm can be created, funded by multiple agents (real SOL), and its treasury balance ties to
+ chain; consensus fires a real firewall-gated buy from the treasury.
+- Closed positions distribute real pro-rata payouts via x402/SOL, fully audited; a member can exit
+ and withdraw their settled share.
+- Swarms UI (directory, dashboard, join/exit) renders all states; kill switch + caps enforced.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file
+
+```bash
+git rm "tasks/next-gen-trading/07-trading-swarms.md"
+```
+
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/next-gen-trading/08-launch-copilot-mm.md b/tasks/next-gen-trading/08-launch-copilot-mm.md
new file mode 100644
index 000000000..77ec8e7f1
--- /dev/null
+++ b/tasks/next-gen-trading/08-launch-copilot-mm.md
@@ -0,0 +1,100 @@
+# Task 08 — Launch Copilot: Autonomous Fair-Launch Market-Maker
+
+> **Operating bar (applies to the whole task).** Senior engineer + product thinker building
+> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no
+> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%
+> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade
+> plumbing are the only exception and are never promoted. After it works, self-review and ship
+> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the
+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.
+>
+> **Depends on tasks 01 (firewall) and 02 (MEV engine).**
+
+## The invention
+
+Launching a coin today is fire-and-forget: you mint and hope. We make the launching agent
+**run the book**. When a user launches through three.ws, their agent becomes an autonomous
+**fair-launch market-maker**: it seeds the configured initial buy, defends a floor by buying
+dips within a budget, takes measured profit into strength to recycle liquidity, manages the
+bonding-curve→AMM graduation transition smoothly, and provides/withdraws liquidity post-grad per
+policy — all transparently, all from the agent's own audited wallet. A launch on three.ws comes
+with a built-in, rules-based, non-manipulative market-maker. Nobody offers that.
+
+## Context (real, verified)
+
+- Launch flow: `api/pump/[action].js#handleLaunchPrep` (~L1194), metadata + token creation
+ `api/_lib/pump-launch.js` (`uploadPumpMetadata`, `launchPumpToken`), `pump_agent_mints`,
+ agent-payments PDA + `buyback_bps` config already exist (`getPumpAgentOffline`).
+- Trading primitives to reuse: `api/_lib/pump.js` (curve + AMM quotes, `getAmmPoolState`),
+ `api/_lib/pump-swap-ix.js`, `executor.js`/`positions.js` patterns, firewall (01), MEV (02).
+- Graduation handling already exists: `workers/agent-sniper/amm-exit.js` (`isGraduated`,
+ `quoteAmmSell`, `buildAmmSellInstructions`) — extend to two-sided MM, not just exit.
+- Spend guards + custody: `api/_lib/agent-trade-guards.js`, `agent_custody_events`.
+- Launch UI: `pages/create-agent.html` success path; `/launches` feed.
+
+## Goal
+
+A `market_maker_policies` model + a worker loop that lets a launcher attach an autonomous,
+rules-based MM to a coin launched via three.ws, executing real floor-defense / profit-recycling /
+graduation-transition trades from the agent wallet, with a live control panel.
+
+## What to build
+
+1. **Policy model** — `market_maker_policies` (mint, network, agent_id, owner user_id, enabled,
+ mode simulate|live, floor_price / floor_band, dip_buy_budget_lamports, take_profit_band,
+ recycle_pct, max_inventory, graduation_action [provide_lp|hold|distribute], daily_budget,
+ kill_switch). Attachable at launch (in `handleLaunchPrep`) or after, from the launch's detail
+ page. Dated migration.
+2. **MM engine** — a worker loop (extend `workers/agent-sniper/` or a sibling MM worker) that, per
+ active policy, re-quotes the coin (curve pre-grad, AMM post-grad), and within budget: buys when
+ price falls through the floor band (defend), sells measured size into spikes above the take
+ band (recycle liquidity, lock realized SOL), and rebalances toward `max_inventory`. Every action
+ runs through the firewall (01) and MEV engine (02), spend-guarded + audited. Bounded,
+ non-reflexive sizing — never chase, never wash trade against itself.
+3. **Graduation transition** — detect approach to graduation and execute the configured
+ `graduation_action`: provide LP into the canonical AMM pool, hold inventory, or distribute. Use
+ the existing AMM plumbing; make the curve→AMM handoff seamless (no parked inventory). Honest
+ logging of each step.
+4. **Anti-manipulation guardrails (explicit, non-negotiable)** — the MM defends and recycles
+ within a transparent published policy; it must **not** wash-trade to fake volume, spoof, or
+ paint the tape. Encode hard caps: no self-cross within N seconds, max % of volume, disclosed
+ policy. This is honest liquidity provision, not manipulation — build it that way and document
+ the limits in code + UI.
+5. **API + UI** — `/api/launch/mm` (CRUD policy, pause, kill), `/api/launch/mm/:mint` (live state:
+ inventory, realized PnL, recent MM actions, budget remaining), SSE for live actions. Build a
+ **Launch Copilot** panel on the launch success screen + the coin's detail page: configure the
+ policy with plain-language presets ("gentle floor defense", "aggressive recycle"), a live action
+ log, inventory + realized chart, budget + kill controls. All states designed; accessible;
+ responsive.
+
+## Constraints
+
+- Every MM trade is real, firewall-gated, spend-guarded, audited; the kill switch halts instantly
+ and the owner can always withdraw remaining inventory + SOL.
+- Strictly non-manipulative: no wash trading, no fake volume — codify and surface the guardrails.
+ If a requested policy would cross that line, refuse to enable it with a clear explanation.
+- Simulate mode runs the full logic without spending, clearly labeled, for confidence.
+- $THREE-only rule. The MM operates on the user's launched coin (a runtime mint) and promotes no
+ token; never reference any coin other than $THREE in copy.
+
+## Success criteria
+
+- A coin launched via three.ws can attach an MM policy; the worker executes real
+ floor-defense/recycle trades from the agent wallet, firewall-gated + audited.
+- Graduation transition runs the configured action with no parked inventory.
+- Anti-manipulation caps enforced in code; kill + withdraw always work.
+- Launch Copilot UI renders all states with live action log + controls.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file
+
+```bash
+git rm "tasks/next-gen-trading/08-launch-copilot-mm.md"
+```
+
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/next-gen-trading/09-mission-control-terminal.md b/tasks/next-gen-trading/09-mission-control-terminal.md
new file mode 100644
index 000000000..6da708a50
--- /dev/null
+++ b/tasks/next-gen-trading/09-mission-control-terminal.md
@@ -0,0 +1,96 @@
+# Task 09 — Mission Control: Real-Time Trading Terminal (the capstone UI)
+
+> **Operating bar (applies to the whole task).** Senior engineer + product thinker building
+> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no
+> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%
+> end-to-end with REAL APIs and real data. Every state designed. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade
+> plumbing are the only exception and are never promoted. After it works, self-review and ship
+> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the
+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.
+>
+> **Depends on tasks 01, 03, 04 (and consumes 02/05/06 data where present).**
+
+## The invention
+
+Pump.fun traders juggle ten tabs. We give them one screen that makes them feel like they have a
+superpower: a **real-time trading terminal** that fuses everything three.ws computes — the live
+launch feed with intel scores + firewall verdicts + smart-money flow + pre-launch radar
+precursors, the user's live positions with streaming PnL, and one-click (or one-keystroke) snipe/
+exit from the agent wallet. This is the surface people screenshot and share. Bloomberg-grade
+density, Linear-grade polish, zero jank, fully keyboard-driven.
+
+## Context (real, verified)
+
+- Live data sources to fuse (all real, all existing or built by this epic):
+ - Launch feed: `api/_lib/pumpfun-ws-feed.js` (server) → expose via an SSE/stream endpoint.
+ - Intel scores: `pump_coin_intel`; oracle conviction: `oracle_conviction`.
+ - Firewall verdict: task 01 `GET /api/pump/safety`.
+ - Smart-money: task 03 `GET /api/intel/smart-money`.
+ - Pre-launch radar: task 04 `GET /api/sniper/radar` + SSE.
+ - Positions + PnL: `api/sniper/stream.js` (SSE), `api/_lib/trader-stats.js`.
+ - Execute: `api/agents/agent-trade.js` / `api/agents/solana-trade.js` (firewall + MEV-gated).
+- UI conventions + design tokens: `src/agent-wallet-hub/index.js`, `src/agent-wallet-hub/tabs/trade.js`,
+ `src/game/coin-buy.js`. SSE client patterns already used in the sniper UI.
+- Frontend: vanilla JS modules + Vite. Keep it performant — virtualize lists, debounce, rAF.
+
+## Goal
+
+A dedicated `/terminal` (or `/mission-control`) page + `src/mission-control/` module that streams
+real data into a multi-pane, keyboard-driven trading cockpit, executing real trades from the agent
+wallet through the firewall + MEV engine.
+
+## What to build
+
+1. **Layout** — a responsive multi-pane terminal: (a) **live launch feed** (new mints streaming
+ in, each row showing intel score, firewall verdict chip, smart-money count, age, market cap),
+ (b) **radar** precursors (task 04), (c) **your positions** with live streaming PnL + quick exit,
+ (d) a **focus/detail** pane for the selected coin (chart, intel breakdown, safety panel, smart-
+ money graph, buy/sell). Collapses gracefully to a stacked mobile layout at 320/768/1440.
+2. **Real-time plumbing** — consume all SSE/stream endpoints with robust reconnect/backoff, a
+ shared event bus, and virtualized rendering so a fast feed never janks. No polling where SSE
+ exists; no fake `setTimeout` ticks. Show connection state honestly (live / reconnecting / down).
+3. **One-keystroke trading** — keyboard-first: arrow/jk to move the selection, `b` to buy preset
+ size, `s` to sell, number keys for size presets, `/` to filter, `?` for a shortcut overlay.
+ Every execution runs through the firewall (block disables the action) and the MEV engine, from
+ the agent wallet, spend-guarded + audited. Confirm-on-first-use, then express mode.
+4. **Filters + saved views** — filter the feed by intel score, firewall verdict, smart-money,
+ creator pedigree, market-cap band; persist named views per user. Empty/loading/error states for
+ every pane (skeletons, not spinners).
+5. **Polish that makes it screenshot-worthy** — micro-interactions on new-row entry, smooth PnL
+ number transitions, color-coded verdicts, a tasteful "alpha" density without clutter, focus
+ rings, ARIA live regions for the streaming feed, reduced-motion support. Navigable from main nav
+ and from the wallet hub. Add it to `data/pages.json` so the changelog records the new page.
+
+## Constraints
+
+- Every datum is real and streaming from real endpoints — no seeded rows, no demo coins, no fake
+ feed. If a source is down, that pane shows an honest degraded state, not stale or fake data.
+- Trades execute only through the existing guarded paths (firewall + spend guards + MEV + custody
+ audit); the terminal is a fast UI over real execution, never a bypass.
+- Performance is a feature: 60fps feed, virtualized lists, lazy-loaded heavy panes, debounced
+ input. No memory leaks on long-lived SSE (clean up on unmount/route change).
+- $THREE-only rule. The feed shows arbitrary runtime mints as market data; it promotes no token
+ and never names any coin other than $THREE in chrome/copy.
+
+## Success criteria
+
+- `/terminal` streams real launches, intel, firewall verdicts, smart-money, radar, and live
+ positions simultaneously, reconnecting cleanly; reachable from main navigation.
+- Keyboard-driven buy/sell executes real firewall+MEV-gated trades from the agent wallet, audited.
+- Filters + saved views work; every pane has designed loading/empty/error/populated states;
+ responsive 320/768/1440; accessible; console-clean; no jank under a fast feed.
+- New page added to `data/pages.json`. Build/typecheck/test clean. Changelog entry (tags: feature).
+ Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file
+
+```bash
+git rm "tasks/next-gen-trading/09-mission-control-terminal.md"
+```
+
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/next-gen-trading/10-trading-arena-tournaments.md b/tasks/next-gen-trading/10-trading-arena-tournaments.md
new file mode 100644
index 000000000..7de83c0a4
--- /dev/null
+++ b/tasks/next-gen-trading/10-trading-arena-tournaments.md
@@ -0,0 +1,100 @@
+# Task 10 — Social Trading Arena: On-Chain PvP Tournaments ($THREE prizes)
+
+> **Operating bar (applies to the whole task).** Senior engineer + product thinker building
+> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no
+> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%
+> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade
+> plumbing are the only exception and are never promoted. After it works, self-review and ship
+> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the
+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.
+
+## The invention
+
+We have **verifiable, tamper-evident track records** (`trader-stats.js`, on-chain attestations).
+Turn trading into a spectator sport: **time-boxed PvP tournaments** where agents compete on
+*real, verified* PnL over a window, ranked live, with results settled and attested on-chain and
+**$THREE prizes** for winners. Entry can be gated or open; performance can't be faked because it's
+computed from real closed positions. This converts the leaderboard from a static table into a
+recurring, social, competitive product loop that drives engagement and showcases the platform's
+real edge — a trading esport for AI agents.
+
+## Context (real, verified)
+
+- Canonical metrics: `api/_lib/trader-stats.js` (`computeTraderMetrics`, composite score,
+ verification, ROI, drawdown, Sharpe). Leaderboard + SSE: `api/sniper/{leaderboard,trader,
+ stream}.js`. Positions: `agent_sniper_positions`.
+- On-chain attestation for tamper-evident results: Solana attestations
+ (`solana_attestations`, kinds like `threews.*`), `contracts/src/ReputationRegistry.sol`, and the
+ attestation helpers in `@three-ws/sdk` (`attestValidation`, `listAttestations`).
+- $THREE is the only coin (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — prizes are $THREE.
+ Use the existing platform launch records / $THREE plumbing for prize accounting; never reference
+ any other token.
+- Identity + reputation: `agent_identities`, ERC-8004 (`erc8004_agents_index`). Real-time:
+ `api/sniper/stream.js` SSE pattern.
+
+## Goal
+
+A tournament engine: create/join time-boxed competitions scored on real verified PnL, a live
+leaderboard with anti-cheat, on-chain attestation of final standings, and $THREE prize settlement
+— surfaced as an Arena product with live spectating.
+
+## What to build
+
+1. **Tournament model** — `tournaments` (id, name, network, scoring [roi_pct|realized_pnl|score],
+ starts_at, ends_at, entry_rules jsonb, prize_pool_three, status) and `tournament_entries`
+ (tournament_id, agent_id, joined_at, starting_snapshot jsonb, status). Scoring uses only trades
+ **opened within the window** to be fair; snapshot each entrant's baseline at join.
+2. **Live scoring engine** — compute each entrant's window-scoped metrics from real
+ `agent_sniper_positions` via `trader-stats.js`, ranked live. Anti-cheat: reuse the verification
+ gates (min trades, min unique coins, churn cap) + a wash/self-trade check (reject coins traded
+ only against the entrant's own related wallets — leverage task 03 clustering if present). No
+ simulated/paper trades count toward prizes (separate "practice" bracket allowed, clearly
+ labeled).
+3. **On-chain attestation** — at tournament close, write the final standings as a Solana
+ attestation (`threews.tournament.v1` kind) so results are tamper-evident and independently
+ verifiable; link the attestation from the results page. Use the existing attestation path; no
+ new signing key handling.
+4. **Prize settlement** — distribute the $THREE prize pool to winners per the published structure,
+ recorded with a real tx + an entry in the relevant ledger, audited. Honest accounting; if prize
+ funding is unavailable in an environment, the tournament still runs and ranks, and settlement
+ reports BLOCKED(reason) rather than faking a payout.
+5. **API + UI — the Arena** — `/api/tournaments` (CRUD, join), `/api/tournaments/:id` (state,
+ live standings, prize, attestation link), `/api/tournaments/:id/stream` (SSE live rank changes).
+ Build an **Arena** page: list of upcoming/live/finished tournaments, a live competition view
+ (animated ranking, each agent's 3D avatar + verified badge + live PnL, recent trades ticker),
+ join flow, and a results page with the on-chain attestation + prize distribution. Make it feel
+ alive and competitive — this is a showcase surface. Add to `data/pages.json`. All states
+ designed; accessible; responsive; reduced-motion friendly.
+
+## Constraints
+
+- Rankings derive only from **real verified closed trades** — never fabricate PnL, never count
+ unverifiable or wash trades toward prizes. The integrity is the entire point.
+- Prizes are **$THREE only**. Never introduce, name, or reference any other token anywhere in the
+ arena (copy, schema, fixtures). Mints shown are runtime trade data, not promotions.
+- On-chain attestation must be real (real Solana tx) or honestly reported as unavailable — no fake
+ proof links.
+- Settlement is real and audited; BLOCKED is a first-class honest outcome when funding is absent.
+
+## Success criteria
+
+- A tournament can be created and joined; live standings compute from real `trader-stats` metrics
+ over the window with anti-cheat enforced.
+- Final standings are attested on-chain (real tx) and linked from results; $THREE prizes settle
+ (or report BLOCKED honestly with the unblock step).
+- Arena UI (list, live competition, results) renders all states, is responsive + accessible, and
+ is reachable from main navigation; new page in `data/pages.json`.
+- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file
+
+```bash
+git rm "tasks/next-gen-trading/10-trading-arena-tournaments.md"
+```
+
+A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.
diff --git a/tasks/next-gen-trading/11-e2e-and-dod-sweep.md b/tasks/next-gen-trading/11-e2e-and-dod-sweep.md
new file mode 100644
index 000000000..ff6072af6
--- /dev/null
+++ b/tasks/next-gen-trading/11-e2e-and-dod-sweep.md
@@ -0,0 +1,104 @@
+# Task 11 — End-to-End Devnet Smoke Harness + Definition-of-Done Sweep (epic gate)
+
+> **Operating bar (applies to the whole task).** Senior engineer + product thinker building
+> three.ws to beat the best in the world. No mocks, no fake/sample data, no placeholders, no
+> TODO/stubs, no `setTimeout` fake-loading. Real APIs and real on-chain data only. Simulate-first
+> with **honest BLOCKED reporting** — never a fake PASS. Only coin is **$THREE**
+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only
+> exception and are never promoted. `data/changelog.json` entry for user-visible changes. Run the
+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.
+>
+> **Final gate. Run after tasks 01–10 are shipped (their files deleted).**
+
+## Context
+
+Tasks 01–10 build the three.ws trading edge: firewall (01), MEV execution (02), smart-money graph
+(03), pre-launch radar (04), NL strategy compiler + backtester (05), signal marketplace (06),
+trading swarms (07), launch copilot MM (08), Mission Control terminal (09), and the trading arena
+(10). This task proves the **whole edge works end-to-end** and runs one Definition-of-Done pass
+across every new surface so nothing ships half-wired. It is the gate before the epic is called done.
+
+Known funding constraint (memories `pump-devnet-smoke`, `three-ws-self-registration`): devnet
+airdrops are rate-limited and platform signers may be unfunded, so the harness runs simulate-first
+and degrades to clearly-reported "blocked: needs funded devnet signer" rather than failing or
+faking. Mirror the existing pattern in `scripts/pump-devnet-smoke.mjs` / `scripts/onchain-smoke.mjs`.
+
+## Files to read first
+
+- All of `tasks/next-gen-trading/` (this README + any task files still present) — the success
+ criteria each task promised.
+- `scripts/pump-devnet-smoke.mjs`, `scripts/onchain-smoke.mjs` — the simulate-first, funding-gated
+ smoke pattern + CI-runnable shape to mirror.
+- `scripts/page-audit.mjs` + the console-audit baseline (memories `page-audit-tooling`,
+ `console-audit-baseline`) — for the UI sweep + distinguishing real errors from known noise.
+- The endpoints built by this epic (firewall safety, smart-money, radar, compile/backtest,
+ signals marketplace, swarms, launch MM, tournaments) + `CLAUDE.md` "Definition of done".
+
+## What to build / do
+
+1. **End-to-end smoke** — `scripts/next-gen-trading-smoke.mjs` covering, in order, each printing
+ PASS / BLOCKED(reason) / FAIL with simulate fallbacks and zero fake passes:
+ 1. Create + fund an agent (assert wallet provisioned).
+ 2. **Firewall**: assert `assessTradeSafety` blocks a honeypot-shaped simulated round-trip and
+ allows a healthy one, on real RPC.
+ 3. **MEV**: assert a buy routes through `submitProtected` (Jito on mainnet, protected fallback
+ on devnet) with real telemetry.
+ 4. **Smart-money**: assert `wallet_reputation`/clusters compute from real data and
+ `getSmartMoneyForMint` returns a real verdict.
+ 5. **Radar**: assert the watchlist builds and a real precursor event is detected (or BLOCKED if
+ no webhook/RPC).
+ 6. **Strategy compiler/backtester**: compile a plain-English strategy → valid config; backtest
+ returns honest metrics from real history.
+ 7. **Signal marketplace**: a verified feed publishes; a subscriber pays real x402 (simulate if
+ unfunded) and mirrors a firewall-gated trade.
+ 8. **Swarm**: create + fund a swarm; consensus fires a treasury buy; a payout settles pro-rata.
+ 9. **Launch MM**: attach a policy to a launched coin; assert an MM action executes (simulate).
+ 10. **Arena**: create a tournament, compute live standings from real metrics, attest standings
+ on-chain (or BLOCKED), settle $THREE prize (or BLOCKED with unblock step).
+ - Each live step degrades to BLOCKED with the exact missing credential/funding, never a fake PASS.
+2. **DoD sweep across all new UI** (firewall safety panel, smart-money panel, radar view, strategy
+ builder, signals marketplace + subscriber panel, swarms dashboard, launch copilot, Mission
+ Control terminal, arena): use `scripts/page-audit.mjs` + a real browser pass to verify for each
+ surface — designed loading/empty/error/populated states; hover/active/focus on every interactive
+ element; responsive at 320/768/1440; semantic HTML + ARIA + keyboard nav + focus rings; no dead
+ buttons/links; console-clean (filtered against the known-noise baseline). File a punch-list; fix
+ every real issue or hand specific items back to the owning task with specifics.
+3. **Build gates** — confirm `npm run build`, `npm run typecheck`, `npm test` clean across the
+ epic; confirm every user-visible change has a `data/changelog.json` entry and new pages are in
+ `data/pages.json`.
+4. **Epic completion report** — a short summary of what is fully live vs. built-but-blocked-on-
+ credentials/funding (Cloud Run deploy, funded devnet signer, Jito, prize funding), with the
+ exact unblock step for each. Do not claim done for anything you could not verify.
+
+## Constraints
+
+- Simulate-first, honest reporting: never fabricate an on-chain result; BLOCKED is first-class with
+ the precise reason + unblock step.
+- Synthetic agent authorities + the $THREE mint (or a clearly-synthetic placeholder) in tests —
+ never a real third-party wallet or any non-$THREE mint.
+- Re-runnable + idempotent (cleans up or reuses test agents); no secrets committed; lives under
+ `scripts/`, not the repo root.
+- The DoD sweep fixes real defects but must not silently rewrite another task's scope.
+
+## Success criteria
+
+- `node scripts/next-gen-trading-smoke.mjs` runs end-to-end, printing PASS/BLOCKED/FAIL per step,
+ with simulate fallbacks and zero fake passes.
+- The DoD punch-list is resolved: every new surface has all states, is responsive + accessible, has
+ no dead paths, and is console-clean.
+- `npm run build`, `npm run typecheck`, `npm test` clean; changelog + pages entries present.
+- A completion report distinguishes live vs. blocked with unblock steps — no overclaiming.
+- Changelog entry (tag: infra). Completionist passes on the epic's changed files.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file
+
+```bash
+git rm "tasks/next-gen-trading/11-e2e-and-dod-sweep.md"
+```
+
+When every numbered task file is gone, delete the epic `README.md` too. A file that still exists is
+unfinished work; a file that is gone has shipped. Do not delete early.