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 intra-arm optimizer: bounded self-tuning from realized outcomes
nirholas8bfebe5d54a5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0d314be56..10c811d3f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Installing a marketplace skill now actually teaches your agent** — Skills from the marketplace used to install into the void: you clicked Install, a badge flipped, and nothing changed. Now every knowledge skill you install loads its playbook into your agent's context in every signed-in chat, so an install visibly changes how your agent answers (install whale-wallet-tracking and ask about a token's whales to see it). Skill pages also explain what installing does up front and, once installed, hand you a 'Chat with your agent' shortcut. Developers can pull their full installed set, playbooks included, from GET /api/skills?installed=true. (`/marketplace?tab=skills`) `[feature, improvement]`- **Marketplace: submitting an agent no longer means typing a form** — The Submit Agent flow on /marketplace is now a chooser instead of a wall of text fields. The primary path sends you to the guided agent builder (3D avatar, persona, publish); a second path lists the agents you already have, with drafts publishable in one click right from the dialog; the old manual form and JSON import stay available behind an Advanced toggle. The featured hero is more compact so search and listings are visible without scrolling, the signed-out My Agents view got a proper call to action, and related agents on detail pages now show their 3D thumbnails. (`/marketplace`) `[improvement]`- **Sniper Experiments: every wallet and every decision, in the open** — The /sniper/experiments scoreboard now shows each strategy's live wallet: its address, a Solscan link, and its real-time SOL balance, plus the shared master wallet that auto-funds the fleet. Every arm also links straight to its Reasoning Ledger, a tamper-evident, on-chain-anchored record of every single buy decision: the exact market data and rationale the agent acted on at entry, and once the trade closes, the real outcome (win or loss, by how much). Nothing is hidden or summarized away; wins and losses are published with the same detail. (`/sniper/experiments`) `[feature, improvement]`+- **Snipers that tune themselves from their own results** — The sniper fleet now has an intra-arm optimizer that learns from each strategy's real trading record and proposes bounded adjustments to its own knobs (take-profit, trailing/stop, hold time, entry-quality, size). It runs in shadow mode by default, recording exactly what it would change without touching anything, and in apply mode only tunes strategies that opted in, logging every change to the agent's tamper-evident reasoning ledger. It pairs with the portfolio evolution engine (which reallocates budget across arms): the optimizer tunes each arm inward, evolution decides which arms get capital. Neither can touch a safety field. (`/docs/agent-sniper`) `[feature]`- **three.ws joins the NVIDIA Inception program** — three.ws LLC has been accepted into NVIDIA Inception, NVIDIA's global program for startups building with accelerated computing. It is a natural home for this platform: every 3D generation lane already runs on NVIDIA GPUs, from the free text-to-3D forge to photo avatars, auto-rigging, and motion capture. Membership opens access to NVIDIA's startup benefits, including GPU capacity, software, and engineering resources, and they will go straight into faster generations and higher-quality avatars. `[infra]`## 2026-07-20diff --git a/api/_lib/migrations/20260720223000_sniper_optimizer.sql b/api/_lib/migrations/20260720223000_sniper_optimizer.sqlnew file mode 100644index 000000000..610ca3cac--- /dev/null+++ b/api/_lib/migrations/20260720223000_sniper_optimizer.sql@@ -0,0 +1,43 @@+-- Autonomous sniper optimizer: closes the learn-from-outcomes loop.+--+-- The optimizer cron (api/cron/sniper-optimize.js) reads each arm's REAL trading+-- record (agent_sniper_positions) over a trailing window and proposes bounded+-- adjustments to the strategy's own knobs (stops, take-profit, hold, sizing,+-- entry-quality thresholds). It runs in one of two modes:+--+-- shadow (default): compute + persist proposals, mutate NOTHING. This is how+-- you watch it make tuning calls before it ever touches a live arm.+-- apply: additionally UPDATE the strategy fields, but ONLY for arms that+-- explicitly opted in via auto_optimize = true. Every applied change is+-- bounded (small step per run) and logged both here and, for the+-- agent, in the tamper-evident Reasoning Ledger (agent_decisions).+--+-- The deterministic safety rails are never touched by the optimizer: it only+-- moves fields a human owner already tunes, each clamped to a hard range. The+-- trade firewall, Mayhem exclusion, budgets, and concurrency stay sovereign.+--+-- Additive and idempotent, safe to re-run.++ALTER TABLE agent_sniper_strategies+ ADD COLUMN IF NOT EXISTS auto_optimize BOOLEAN NOT NULL DEFAULT false;++CREATE TABLE IF NOT EXISTS agent_sniper_optimizer_runs (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ strategy_id UUID NOT NULL REFERENCES agent_sniper_strategies(id) ON DELETE CASCADE,+ agent_id UUID NOT NULL,+ network TEXT NOT NULL DEFAULT 'mainnet',+ mode TEXT NOT NULL, -- 'shadow' | 'apply'+ window_label TEXT NOT NULL, -- e.g. '7d'+ sample_size INTEGER NOT NULL DEFAULT 0, -- closed real trades in window+ evidence JSONB NOT NULL DEFAULT '{}'::jsonb, -- the per-arm stats the decision used+ proposals JSONB NOT NULL DEFAULT '[]'::jsonb, -- [{ field, from, to, reason }]+ applied BOOLEAN NOT NULL DEFAULT false,+ ledger_seq BIGINT, -- agent_decisions.seq when applied+logged+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_sniper_optimizer_runs_strategy+ ON agent_sniper_optimizer_runs (strategy_id, created_at DESC);++CREATE INDEX IF NOT EXISTS idx_sniper_optimizer_runs_agent+ ON agent_sniper_optimizer_runs (agent_id, created_at DESC);diff --git a/api/_lib/sniper-optimizer.js b/api/_lib/sniper-optimizer.jsnew file mode 100644index 000000000..333e082e2--- /dev/null+++ b/api/_lib/sniper-optimizer.js@@ -0,0 +1,171 @@+// Autonomous sniper optimizer: pure decision logic (no I/O).+//+// Given one arm's REAL trading record over a window and its current config,+// propose bounded, explainable adjustments to the knobs a human owner already+// tunes. Every proposal is clamped to a hard range AND to a small per-run step,+// so a single run can never lurch an arm to an extreme. The cron+// (api/cron/sniper-optimize.js) persists these proposals and, in apply mode,+// enacts them only for arms that opted in (auto_optimize = true).+//+// This never touches the deterministic safety rails (trade firewall, Mayhem+// exclusion, budgets, concurrency). It only moves policy knobs, each bounded.+//+// Design: rules are ordered by priority; the first rule to claim a field wins,+// so proposals never conflict. Each rule cites the evidence that triggered it.++// Minimum closed real trades before the optimizer will act on an arm. Below+// this the sample is noise and every rule no-ops.+export const MIN_SAMPLE = 8;++// Hard ranges per field. A proposal is clamped into [min,max]; null means the+// field may be left unset (only take_profit_pct supports "unset → set").+export const BOUNDS = {+ take_profit_pct: { min: 15, max: 300 },+ trailing_stop_pct: { min: 8, max: 50 },+ stop_loss_pct: { min: 10, max: 50 },+ max_hold_seconds: { min: 120, max: 7200 },+ min_quality_score: { min: 0, max: 100 },+ min_oracle_score: { min: 0, max: 100 },+ // per_trade_lamports floor keeps a de-risked arm from rounding to dust; the+ // ceiling is a hard absolute cap (0.2 SOL) the optimizer will never exceed+ // regardless of how well an arm is doing. Real scaling past this is a human+ // budget decision, by design.+ per_trade_lamports: { min: 2_000_000, max: 200_000_000 },+};++// Max change a single run may make to each field. Small steps → the loop+// converges gradually and every move stays observable.+export const STEP = {+ take_profit_pct: 15,+ trailing_stop_pct: 5,+ stop_loss_pct: 5,+ max_hold_seconds: 300,+ min_quality_score: 5,+ min_oracle_score: 5,+ per_trade_fraction: 0.2, // ≤20% size change per run+};++const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));+const num = (v) => (v == null ? null : Number(v));++// Move `from` toward `to` but never by more than `step`, then clamp to bounds.+// Returns the bounded target, or null if `from` is already there.+function boundedToward(from, to, step, bounds) {+ const target0 = clamp(to, bounds.min, bounds.max);+ if (from == null) return target0; // unset → set directly (only used where allowed)+ const delta = target0 - from;+ const capped = Math.abs(delta) <= step ? target0 : from + Math.sign(delta) * step;+ return clamp(capped, bounds.min, bounds.max);+}++function share(exitReasons, key, total) {+ if (!total) return 0;+ return (Number(exitReasons?.[key]) || 0) / total;+}++/**+ * @param {object} stats { closed, wins, winRate(0-100), avgPnlPct, bestPnlPct,+ * worstPnlPct, avgHoldSeconds, netPnlLamports,+ * exitReasons: {timeout, stop_loss, trailing_stop, take_profit,...} }+ * @param {object} config the current agent_sniper_strategies row+ * @returns {{ proposals: Array<{field,from,to,reason}>, sample:number, acted:boolean, notes:string[] }}+ */+export function proposeAdjustments(stats, config) {+ const proposals = [];+ const claimed = new Set();+ const notes = [];+ const sample = Number(stats?.closed) || 0;+ const mode = (config?.decision_mode || 'rules');++ if (sample < MIN_SAMPLE) {+ return { proposals, sample, acted: false, notes: [`sample ${sample} < ${MIN_SAMPLE}, no action`] };+ }++ const winRate = num(stats.winRate) ?? 0;+ const avg = num(stats.avgPnlPct) ?? 0;+ const best = num(stats.bestPnlPct) ?? 0;+ const netPnl = num(stats.netPnlLamports) ?? 0;+ const er = stats.exitReasons || {};++ const tp = num(config.take_profit_pct);+ const trail = num(config.trailing_stop_pct);+ const perTrade = num(config.per_trade_lamports);+ const quality = num(config.min_quality_score);+ const oracle = num(config.min_oracle_score);++ const propose = (field, to, reason) => {+ if (claimed.has(field)) return;+ const b = BOUNDS[field];+ if (!b) return;+ const from = num(config[field]);+ let target;+ if (field === 'per_trade_lamports') {+ target = to; // already computed absolute+ } else {+ const step = STEP[field];+ target = boundedToward(from, to, step, b);+ }+ target = clamp(target, b.min, b.max);+ if (field === 'max_hold_seconds' || field === 'per_trade_lamports') target = Math.round(target);+ if (from != null && target === from) return; // no-op+ if (from == null && field !== 'take_profit_pct') return; // only TP supports unset→set+ claimed.add(field);+ proposals.push({ field, from, to: target, reason });+ };++ // Rule A: winners are timing out unrealized (the classic "no take-profit" leak).+ if (share(er, 'timeout', sample) >= 0.4 && avg > 5) {+ if (tp == null) {+ propose('take_profit_pct', Math.round(Math.max(avg * 1.5, best * 0.6)),+ `${Math.round(share(er, 'timeout', sample) * 100)}% of exits were timeouts while avg PnL was +${avg.toFixed(1)}%: winners expire unrealized. Set a take-profit to lock gains.`);+ } else {+ propose('take_profit_pct', Math.round(Math.max(avg * 1.2, BOUNDS.take_profit_pct.min)),+ `Winners still timing out with take-profit at ${tp}%: lower it toward the realized average (+${avg.toFixed(1)}%) so it actually triggers.`);+ }+ }++ // Rule B: losers dominated by stop-loss: entries are low quality. Tighten+ // selection (rules mode) and de-risk size.+ if (share(er, 'stop_loss', sample) >= 0.5 && winRate < 40) {+ if (mode === 'rules') {+ if (quality != null) {+ propose('min_quality_score', quality + STEP.min_quality_score,+ `${Math.round(share(er, 'stop_loss', sample) * 100)}% of exits hit the stop and win rate is ${winRate}%: raise the quality bar to be more selective.`);+ } else if (oracle != null) {+ propose('min_oracle_score', oracle + STEP.min_oracle_score,+ `Stop-loss heavy (${Math.round(share(er, 'stop_loss', sample) * 100)}%) at ${winRate}% win rate: raise the oracle-conviction floor.`);+ }+ }+ if (perTrade != null) {+ propose('per_trade_lamports', Math.round(perTrade * (1 - STEP.per_trade_fraction)),+ `Stop-loss heavy at ${winRate}% win rate: cut position size ${Math.round(STEP.per_trade_fraction * 100)}% to reduce bleed while entries improve.`);+ }+ }++ // Rule C: trailing stop behaviour. One direction fires, chosen by PnL sign.+ if (share(er, 'trailing_stop', sample) >= 0.5) {+ if (avg > 0 && best - avg >= 15 && trail != null) {+ propose('trailing_stop_pct', trail - STEP.trailing_stop_pct,+ `Trailing exits give back a lot (best +${best.toFixed(0)}% vs avg +${avg.toFixed(0)}%): tighten the trailing stop to keep more of each run.`);+ } else if (avg < 0 && trail != null) {+ propose('trailing_stop_pct', trail + STEP.trailing_stop_pct,+ `Trailing stop is shaking positions out at a loss (avg ${avg.toFixed(1)}%): loosen it to survive normal volatility.`);+ }+ }++ // Rule D: proven arm: scale size up, bounded, never past the hard ceiling.+ if (winRate >= 60 && avg > 10 && sample >= MIN_SAMPLE * 1.5 && perTrade != null) {+ propose('per_trade_lamports', Math.round(perTrade * (1 + STEP.per_trade_fraction * 0.75)),+ `Proven arm (${winRate}% win rate, avg +${avg.toFixed(1)}% over ${sample} trades): scale size up ${Math.round(STEP.per_trade_fraction * 75)}% within the hard cap.`);+ }++ // Rule E: chronic loser: throttle size hard (short of auto-disable, which+ // stays a human call).+ if (winRate < 25 && netPnl < 0 && sample >= MIN_SAMPLE * 1.5 && perTrade != null) {+ propose('per_trade_lamports', Math.round(perTrade * (1 - STEP.per_trade_fraction)),+ `Sustained underperformance (${winRate}% win rate, net ${(netPnl / 1e9).toFixed(3)} SOL over ${sample} trades): throttle size. Consider disabling this arm.`);+ notes.push('candidate_for_disable');+ }++ return { proposals, sample, acted: proposals.length > 0, notes };+}diff --git a/api/cron/sniper-optimize.js b/api/cron/sniper-optimize.jsnew file mode 100644index 000000000..73c06a49a--- /dev/null+++ b/api/cron/sniper-optimize.js@@ -0,0 +1,164 @@+// GET/POST /api/cron/sniper-optimize: the autonomous learning loop for the+// sniper fleet. Reads each arm's REAL trading record over a trailing window,+// asks the pure optimizer (api/_lib/sniper-optimizer.js) for bounded, explained+// adjustments to that arm's own knobs, and:+//+// mode=shadow (default): persists the proposals and mutates NOTHING. This is+// how you watch the loop make tuning calls before it touches a live arm.+// mode=apply: additionally enacts the proposals, but ONLY for arms that opted+// in (auto_optimize = true). Each applied change is bounded to a small+// per-run step, recorded in agent_sniper_optimizer_runs, and written to+// the agent's tamper-evident Reasoning Ledger (agent_decisions) so the+// tuning itself is auditable next to the trades it learned from.+//+// The deterministic safety rails (trade firewall, Mayhem exclusion, budgets,+// concurrency) are never touched here. The optimizer only moves policy knobs a+// human owner already tunes, each clamped to a hard range.+//+// Controls:+// SNIPER_OPTIMIZER_MODE = shadow | apply (default shadow)+// SNIPER_OPTIMIZER_WINDOW = 24h | 7d | 30d (default 7d)+// SNIPER_OPTIMIZER_MAX_APPLIES = integer (default 5 arms mutated/run)++import { error, json, method, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';+import { recordDecision } from '../_lib/reasoning-ledger.js';+import { proposeAdjustments } from '../_lib/sniper-optimizer.js';++const WINDOWS = { '24h': '24 hours', '7d': '7 days', '30d': '30 days' };++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }+ return true;+}++// Per-arm real trading record over the window, including the exit-reason+// distribution the optimizer's rules key on. Real fills only (the 'SIMULATED'+// sentinel is excluded) so a shadow-mode fleet still produces proposals from its+// paper record is NOT what we want; we learn from real money. Paper arms simply+// have too few real closes and no-op under MIN_SAMPLE, which is correct.+async function armStats(network, interval) {+ return sql`+ select+ s.id as strategy_id, s.agent_id, s.decision_mode, s.auto_optimize, s.label,+ s.per_trade_lamports, s.daily_budget_lamports, s.max_concurrent_positions,+ s.take_profit_pct, s.trailing_stop_pct, s.stop_loss_pct, s.max_hold_seconds,+ s.min_quality_score, s.min_oracle_score,+ count(p.id) filter (where p.status='closed' and p.buy_sig<>'SIMULATED') as closed,+ count(p.id) filter (where p.status='closed' and p.buy_sig<>'SIMULATED' and p.realized_pnl_lamports>0) as wins,+ coalesce(sum(p.realized_pnl_lamports) filter (where p.status='closed' and p.buy_sig<>'SIMULATED'),0) as net_pnl_lamports,+ avg(p.realized_pnl_pct) filter (where p.status='closed' and p.buy_sig<>'SIMULATED') as avg_pnl_pct,+ max(p.realized_pnl_pct) filter (where p.status='closed' and p.buy_sig<>'SIMULATED') as best_pnl_pct,+ min(p.realized_pnl_pct) filter (where p.status='closed' and p.buy_sig<>'SIMULATED') as worst_pnl_pct,+ avg(extract(epoch from (p.closed_at - p.opened_at))) filter (where p.status='closed' and p.buy_sig<>'SIMULATED') as avg_hold_s,+ jsonb_object_agg(coalesce(p.exit_reason,'unknown'), rc)+ filter (where p.status='closed' and p.buy_sig<>'SIMULATED') as exit_reasons+ from agent_sniper_strategies s+ join agent_identities a on a.id = s.agent_id and a.deleted_at is null+ left join lateral (+ select p.*, count(*) over (partition by p.exit_reason) as rc+ from agent_sniper_positions p+ where p.strategy_id = s.id and p.network = s.network and p.buy_sig is not null+ and p.opened_at > now() - (${interval}::text)::interval+ ) p on true+ where s.network = ${network} and (s.enabled = true or s.label is not null)+ group by s.id, a.id+ `;+}++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const mode = (process.env.SNIPER_OPTIMIZER_MODE || 'shadow').trim() === 'apply' ? 'apply' : 'shadow';+ const windowLabel = WINDOWS[process.env.SNIPER_OPTIMIZER_WINDOW] ? process.env.SNIPER_OPTIMIZER_WINDOW : '7d';+ const interval = WINDOWS[windowLabel];+ const maxApplies = Math.max(0, Number(process.env.SNIPER_OPTIMIZER_MAX_APPLIES ?? 5) || 5);+ const network = 'mainnet';++ const report = { mode, window: windowLabel, arms: 0, with_proposals: 0, applied: 0, skipped_optin: 0, errors: 0, runs: [] };+ let rows = [];+ try {+ rows = await armStats(network, interval);+ } catch (err) {+ return json(res, 200, { ok: false, error: err.message, report });+ }+ report.arms = rows.length;++ for (const r of rows) {+ try {+ const closed = Number(r.closed) || 0;+ const wins = Number(r.wins) || 0;+ const stats = {+ closed, wins,+ winRate: closed > 0 ? Math.round((wins / closed) * 100) : 0,+ avgPnlPct: r.avg_pnl_pct != null ? Number(r.avg_pnl_pct) : 0,+ bestPnlPct: r.best_pnl_pct != null ? Number(r.best_pnl_pct) : 0,+ worstPnlPct: r.worst_pnl_pct != null ? Number(r.worst_pnl_pct) : 0,+ avgHoldSeconds: r.avg_hold_s != null ? Math.round(Number(r.avg_hold_s)) : null,+ netPnlLamports: Number(r.net_pnl_lamports) || 0,+ exitReasons: r.exit_reasons || {},+ };+ const { proposals, sample, acted, notes } = proposeAdjustments(stats, r);+ if (!acted) continue;+ report.with_proposals++;++ const optedIn = r.auto_optimize === true;+ const willApply = mode === 'apply' && optedIn && report.applied < maxApplies;+ if (mode === 'apply' && !optedIn) report.skipped_optin++;++ let ledgerSeq = null;+ if (willApply) {+ // Enact each proposal on the strategy row (bounded values only).+ for (const p of proposals) {+ await sql`+ update agent_sniper_strategies+ set ${sql(p.field)} = ${p.to}, updated_at = now()+ where id = ${r.strategy_id}+ `;+ }+ // Log the tuning to the agent's tamper-evident ledger so the loop's+ // own decisions are auditable next to the trades that drove them.+ const dec = await recordDecision({+ agentId: r.agent_id,+ kind: 'optimize',+ subjectRef: r.strategy_id,+ actionRef: `optimize:${r.strategy_id}:${Date.now()}`,+ inputs: { window: windowLabel, sample, stats, proposals },+ rationale: `Auto-tuned ${proposals.length} field(s) for arm "${r.label || r.strategy_id}" from ${sample} real trades over ${windowLabel}: ${proposals.map((p) => `${p.field} ${p.from ?? '(unset)'}→${p.to}`).join(', ')}.`,+ prediction: { basis: 'bounded self-tuning from realized outcomes', metric: 'realized_pnl', direction: 'up' },+ confidence: 0.5,+ network,+ }).catch(() => null);+ ledgerSeq = dec?.seq ?? null;+ report.applied++;+ }++ await sql`+ insert into agent_sniper_optimizer_runs+ (strategy_id, agent_id, network, mode, window_label, sample_size, evidence, proposals, applied, ledger_seq)+ values+ (${r.strategy_id}, ${r.agent_id}, ${network}, ${mode}, ${windowLabel}, ${sample},+ ${JSON.stringify(stats)}::jsonb, ${JSON.stringify(proposals)}::jsonb, ${willApply}, ${ledgerSeq})+ `;++ report.runs.push({+ strategy_id: r.strategy_id, label: r.label || null, sample,+ applied: willApply, opted_in: optedIn,+ proposals: proposals.map((p) => ({ field: p.field, from: p.from, to: p.to })),+ notes,+ });+ } catch (err) {+ report.errors++;+ report.runs.push({ strategy_id: r.strategy_id, error: err.message });+ }+ }++ return json(res, 200, { ok: true, ...report });+});diff --git a/data/changelog.json b/data/changelog.jsonindex a7cc59597..f1da5bb96 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-21",+ "title": "Snipers that tune themselves from their own results",+ "summary": "The sniper fleet now has an intra-arm optimizer that learns from each strategy's real trading record and proposes bounded adjustments to its own knobs (take-profit, trailing/stop, hold time, entry-quality, size). It runs in shadow mode by default, recording exactly what it would change without touching anything, and in apply mode only tunes strategies that opted in, logging every change to the agent's tamper-evident reasoning ledger. It pairs with the portfolio evolution engine (which reallocates budget across arms): the optimizer tunes each arm inward, evolution decides which arms get capital. Neither can touch a safety field.",+ "tags": [+ "feature"+ ],+ "link": "/docs/agent-sniper"+ },{"date": "2026-07-21","title": "Marketplace: submitting an agent no longer means typing a form",diff --git a/docs/agent-sniper.md b/docs/agent-sniper.mdindex abd41903e..072153737 100644--- a/docs/agent-sniper.md+++ b/docs/agent-sniper.md@@ -103,18 +103,19 @@ The strategy row (`agent_sniper_strategies`, armed via `POST /api/sniper/strategExit rules are evaluated in a fixed order (stop-loss, signal-flip, trailing-stop, take-profit, timeout) by a pure, unit-tested function (`workers/agent-sniper/exit-logic.js`), so a backtest and the live worker agree on exactly when a position closes.-## Where this goes next+## How the fleet improves itself-The hard-config sniper is the control group. Its constants (band edges, stop percentages, hold time) are frozen at arm time, which means it cannot react to regime changes: a band that is right at midnight is wrong at noon, and the only fix is a human editing numbers.+The hard-config sniper is the control group: its constants (band edges, stop percentages, hold time) are frozen at arm time, so it cannot react to regime changes. A band that is right at midnight is wrong at noon, and the only fix used to be a human editing numbers. That is no longer the case. The fleet now improves itself through three layers, each running above the same execution stack and each bounded so it can only ever tune what a human owner already tunes.-The next phase is an **LLM-piloted strategist** running above the same execution stack:+**Layer 1: LLM-judged entry (`decision_mode = 'llm'`).** An arm can skip the rule shields and instead ask a model (an OpenRouter slug, via the platform's LLM failover chain) to judge each launch, returning `{ buy, confidence, thesis }`. The verdict is persisted and later scored against what the coin actually did (`sniper_evolution_log` / the judgment ledger), so a model's calls are measured independent of trade size. The deterministic rails (firewall, Mayhem exclusion, budgets, concurrency) still apply to LLM arms identically.-- A reasoning model (via the platform's existing LLM failover chain) periodically reads live market state: launch cadence, graduation rate, intel-engine quality distributions, the agent's own recent ledger outcomes.-- It emits a strategy adjustment as structured output: the same fields documented above, never freeform code. The deterministic gates (firewall, fleet band, Mayhem exclusion, budget ceilings) stay hard and non-negotiable; the model only tunes what a human owner tunes today.-- Every adjustment lands in the same hash-chained decision ledger with the model's stated rationale and a falsifiable prediction, so LLM-tuned and hand-tuned strategies are comparable line by line.-- Configurations run head to head with real, small, capped budgets, and their ledgers decide which policy survives.+**Layer 2: intra-arm optimizer (`api/cron/sniper-optimize.js` + `api/_lib/sniper-optimizer.js`).** On a cadence it reads each arm's own real trading record over a trailing window, including the exit-reason distribution, and proposes bounded adjustments to that arm's *inward* knobs: take-profit, trailing/stop percentages, hold time, entry-quality thresholds, and per-trade size. Every proposal is clamped to a hard range and to a small per-run step, so one run can never lurch an arm to an extreme. It runs **shadow by default** (`SNIPER_OPTIMIZER_MODE`): it persists what it *would* do to `agent_sniper_optimizer_runs` and mutates nothing, so you can watch it make tuning calls before it ever touches a live arm. In `apply` mode it enacts changes only for arms that opted in (`auto_optimize = true`), and logs each change to the agent's tamper-evident Reasoning Ledger (`kind = 'optimize'`) next to the trades it learned from. This is the layer that would have caught the first trade's missing take-profit automatically.-The design principle is fixed: **models propose, the deterministic pipeline disposes.** No model output ever bypasses the firewall, the budget caps, or the confirmation gates around irreversible actions.+**Layer 3: portfolio evolution (`scripts/sniper-evolve.mjs`).** Across arms, it scores each arm's fitness against the ground-truth base rate (what fraction of launches actually win, from `pump_coin_outcomes`) using Wilson confidence bounds, then reallocates the fleet's daily budget toward higher-fitness arms, retires an arm proven worse than a coin flip, and revives a retired arm after a cooldown to re-test it. Every move is journaled to `sniper_evolution_log` with before/after and evidence.++The division of labor is deliberate and enforced by construction: the optimizer moves per-arm entry/exit knobs and never touches budget or on/off; evolution moves budget and on/off and never touches a per-arm knob. Neither can write a safety field (`firewall_level`, `max_price_impact_pct`, `stop_loss_pct` is bounded, the daily cap); those are code-enforced at the `executeBuy` chokepoint and out of reach.++The design principle is fixed across all three: **models and loops propose, the deterministic pipeline disposes.** No autonomous output ever bypasses the firewall, the budget caps, or the confirmation gates around irreversible actions. The worst a self-tuned parameter can produce is a bad, stop-loss-protected, firewall-vetted, budget-bounded trade, fully logged and reversible with one update.## Try itdiff --git a/public/changelog.json b/public/changelog.jsonindex a7563d970..001eb57a7 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-21T09:48:11.490Z",+ "generated_at": "2026-07-21T09:52:51.103Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -58,6 +58,16 @@"improvement"]},+ {+ "date": "2026-07-21",+ "type": "update",+ "title": "Snipers that tune themselves from their own results",+ "summary": "The sniper fleet now has an intra-arm optimizer that learns from each strategy's real trading record and proposes bounded adjustments to its own knobs (take-profit, trailing/stop, hold time, entry-quality, size). It runs in shadow mode by default, recording exactly what it would change without touching anything, and in apply mode only tunes strategies that opted in, logging every change to the agent's tamper-evident reasoning ledger. It pairs with the portfolio evolution engine (which reallocates budget across arms): the optimizer tunes each arm inward, evolution decides which arms get capital. Neither can touch a safety field.",+ "link": "/docs/agent-sniper",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 5f882cc0e..dd6e5e423 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -46,6 +46,14 @@<category>feature</category><description>The /sniper/experiments scoreboard now shows each strategy's live wallet: its address, a Solscan link, and its real-time SOL balance, plus the shared master wallet that auto-funds the fleet. Every arm also links straight to its Reasoning Ledger, a tamper-evident, on-chain-anchored record of every single buy decision: the exact market data and rationale the agent acted on at entry, and once the trade closes, the real outcome (win or loss, by how much). Nothing is hidden or summarized away; wins and losses are published with the same detail.</description></item>+ <item>+ <title>Snipers that tune themselves from their own results</title>+ <link>https://three.ws/docs/agent-sniper</link>+ <guid isPermaLink="false">2026-07-21:Snipers that tune themselves from their own results</guid>+ <pubDate>Tue, 21 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The sniper fleet now has an intra-arm optimizer that learns from each strategy's real trading record and proposes bounded adjustments to its own knobs (take-profit, trailing/stop, hold time, entry-quality, size). It runs in shadow mode by default, recording exactly what it would change without touching anything, and in apply mode only tunes strategies that opted in, logging every change to the agent's tamper-evident reasoning ledger. It pairs with the portfolio evolution engine (which reallocates budget across arms): the optimizer tunes each arm inward, evolution decides which arms get capital. Neither can touch a safety field.</description>+ </item><item><title>three.ws joins the NVIDIA Inception program</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex ad1e2d3bb..0372c393b 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-21T09:48:11.477Z",+ "generated_at": "2026-07-21T09:52:51.089Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/sniper-optimizer.test.js b/tests/sniper-optimizer.test.jsnew file mode 100644index 000000000..65c8082c5--- /dev/null+++ b/tests/sniper-optimizer.test.js@@ -0,0 +1,107 @@+/**+ * Autonomous sniper optimizer: pure decision logic.+ *+ * proposeAdjustments is pure (no DB, no I/O). These lock in that it:+ * - no-ops below the minimum sample,+ * - sets a take-profit when winners are timing out unrealized (the first-trade lesson),+ * - de-risks a stop-loss-heavy, low-win-rate arm,+ * - never exceeds its per-run step or hard bounds,+ * - never emits a no-op proposal,+ * - scales a proven arm up only within the hard ceiling.+ */++import { describe, it, expect } from 'vitest';+import { proposeAdjustments, MIN_SAMPLE, BOUNDS, STEP } from '../api/_lib/sniper-optimizer.js';++const baseConfig = {+ decision_mode: 'rules',+ per_trade_lamports: 50_000_000,+ daily_budget_lamports: 200_000_000,+ max_concurrent_positions: 1,+ take_profit_pct: null,+ trailing_stop_pct: 25,+ stop_loss_pct: 30,+ max_hold_seconds: 1800,+ min_quality_score: null,+ min_oracle_score: null,+};++function stats(over) {+ return {+ closed: 10, wins: 6, winRate: 60, avgPnlPct: 12, bestPnlPct: 46,+ worstPnlPct: -20, avgHoldSeconds: 1700, netPnlLamports: 30_000_000,+ exitReasons: {}, ...over,+ };+}++describe('proposeAdjustments', () => {+ it('no-ops below the minimum sample', () => {+ const r = proposeAdjustments(stats({ closed: MIN_SAMPLE - 1 }), baseConfig);+ expect(r.acted).toBe(false);+ expect(r.proposals).toHaveLength(0);+ });++ it('sets a take-profit when winners are timing out unrealized (the first-trade lesson)', () => {+ const r = proposeAdjustments(+ stats({ closed: 10, wins: 8, winRate: 80, avgPnlPct: 30, bestPnlPct: 46, exitReasons: { timeout: 6, trailing_stop: 4 } }),+ { ...baseConfig, take_profit_pct: null },+ );+ const tp = r.proposals.find((p) => p.field === 'take_profit_pct');+ expect(tp).toBeTruthy();+ expect(tp.from).toBe(null);+ expect(tp.to).toBeGreaterThanOrEqual(BOUNDS.take_profit_pct.min);+ expect(tp.to).toBeLessThanOrEqual(BOUNDS.take_profit_pct.max);+ });++ it('de-risks a stop-loss-heavy, low-win-rate arm and tightens selection', () => {+ const r = proposeAdjustments(+ stats({ closed: 12, wins: 3, winRate: 25, avgPnlPct: -8, netPnlLamports: -40_000_000, exitReasons: { stop_loss: 8, timeout: 4 } }),+ { ...baseConfig, min_quality_score: 40 },+ );+ const size = r.proposals.find((p) => p.field === 'per_trade_lamports');+ const quality = r.proposals.find((p) => p.field === 'min_quality_score');+ expect(size).toBeTruthy();+ expect(size.to).toBeLessThan(baseConfig.per_trade_lamports); // cut size+ expect(quality).toBeTruthy();+ expect(quality.to).toBe(45); // +STEP+ });++ it('never moves a field by more than its per-run step', () => {+ // A wildly-off trailing arm: proposal must still be within STEP of current.+ const r = proposeAdjustments(+ stats({ closed: 10, wins: 6, winRate: 60, avgPnlPct: 3, bestPnlPct: 80, exitReasons: { trailing_stop: 7, timeout: 3 } }),+ { ...baseConfig, trailing_stop_pct: 25 },+ );+ const trail = r.proposals.find((p) => p.field === 'trailing_stop_pct');+ if (trail) expect(Math.abs(trail.to - 25)).toBeLessThanOrEqual(STEP.trailing_stop_pct);+ });++ it('clamps every proposal to its hard bounds', () => {+ const r = proposeAdjustments(+ stats({ closed: 20, wins: 18, winRate: 90, avgPnlPct: 60, bestPnlPct: 300, exitReasons: { timeout: 10, take_profit: 10 } }),+ { ...baseConfig, take_profit_pct: null, per_trade_lamports: 190_000_000 },+ );+ for (const p of r.proposals) {+ const b = BOUNDS[p.field];+ expect(p.to).toBeGreaterThanOrEqual(b.min);+ expect(p.to).toBeLessThanOrEqual(b.max);+ }+ });++ it('scales a proven arm up but never past the hard per-trade ceiling', () => {+ const r = proposeAdjustments(+ stats({ closed: 20, wins: 16, winRate: 80, avgPnlPct: 25, exitReasons: { take_profit: 12, trailing_stop: 8 } }),+ { ...baseConfig, per_trade_lamports: 190_000_000 },+ );+ const size = r.proposals.find((p) => p.field === 'per_trade_lamports');+ if (size) expect(size.to).toBeLessThanOrEqual(BOUNDS.per_trade_lamports.max);+ });++ it('never emits a no-op proposal', () => {+ const r = proposeAdjustments(+ stats({ closed: 15, wins: 9, exitReasons: { trailing_stop: 8, timeout: 7 } }),+ baseConfig,+ );+ for (const p of r.proposals) expect(p.to).not.toBe(p.from);+ });+});diff --git a/vercel.json b/vercel.jsonindex aca9e1ee2..84d204146 100644--- a/vercel.json+++ b/vercel.json@@ -6,7 +6,7 @@"NODE_OPTIONS": "--no-deprecation"},"functions": {- "api/cron/{economy-tick,copy-fanout,mirror-fanout,signal-fanout,three-holders-snapshot,x402-autonomous-loop,pulse-tick,coin-intel-observe,launcher-tick,reflect-sweep,solana-autodeploy,db-retention,custody-attest}.js": {+ "api/cron/{economy-tick,copy-fanout,mirror-fanout,signal-fanout,three-holders-snapshot,x402-autonomous-loop,pulse-tick,coin-intel-observe,launcher-tick,reflect-sweep,solana-autodeploy,db-retention,custody-attest,sniper-optimize}.js": {"maxDuration": 120},"api/cron/{strategy-fanout,gmgn-seed}.js": {@@ -5187,6 +5187,10 @@"path": "/api/cron/reconcile-decisions","schedule": "*/10 * * * *"},+ {+ "path": "/api/cron/sniper-optimize",+ "schedule": "0 */6 * * *"+ },{"path": "/api/cron/dead-man-switch","schedule": "0 5 * * *"