Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add sniper experiments styles and implement autonomy classification tests
nirholasff1af355d0fc
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 91136eddf..dab1e62be 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -116,6 +116,7 @@ bottom.| Ring economy operator dashboard | [pages/admin/ring.html](pages/admin/ring.html) + [src/admin-ring.js](src/admin-ring.js) `→ /admin/ring`, backend [api/admin/ring-dashboard.js](api/admin/ring-dashboard.js) | In-repo (admin, noindex) | Live eyes on the closed-loop x402 ring: per-minute settlement pulse (green/amber/red heartbeat), loop diagram with live wallet balances + floors, streaming activity feed (agent attribution, Solscan links, skip/fail reasons), fee-burn vs daily budget, integrity (leak scan + reconciliation), per-endpoint coverage. One aggregate read model composes [/api/x402-ring](api/x402-ring.js); admin/Bearer-secret authed. Labels volume as internal dogfooding. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md#watching-it--the-operator-dashboard) || 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) |+| Earned autonomy (sniper fleet) | tier engine [api/_lib/sniper-autonomy.js](api/_lib/sniper-autonomy.js), tier-scaled optimizer [api/_lib/sniper-optimizer.js](api/_lib/sniper-optimizer.js) + cron [api/cron/sniper-optimize.js](api/cron/sniper-optimize.js), tier-weighted portfolio layer [scripts/sniper-evolve.mjs](scripts/sniper-evolve.mjs) + cron [api/cron/sniper-evolve.js](api/cron/sniper-evolve.js), judge knowledge pack [workers/agent-sniper/judge-knowledge.js](workers/agent-sniper/judge-knowledge.js) → [workers/agent-sniper/llm-judge.js](workers/agent-sniper/llm-judge.js), board [api/sniper/experiments.js](api/sniper/experiments.js) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments` | Live | A trading arm's own realized record decides how much rope it gets, recomputed every optimizer run: `probation → standard → trusted → autonomous`. The tier scales how far and how fast the optimizer may move a knob, which fields it may touch at all (trusted unlocks the entry universe, the LLM confidence bar, and the take-initials ladder), how much of the fixed fleet budget the evolution loop concentrates on the arm, and how much real evidence the LLM judge is handed before it rules (base rate, learned signal weights, the arm's own record, the realized win-rate table, the model's own calibration). Decided on realized net P&L and average edge, never win rate, so a 36%-hit-rate arm that actually makes money earns room while a 60%-hit-rate arm that loses money does not. Symmetric: an arm that stops paying loses its tier on the next pass. No tier can reach a safety rail (firewall, Mayhem exclusion, price impact, concurrency, loss cap, fleet ceiling) and a bounded stop-loss survives every tier. Tests: [tests/sniper-autonomy.test.js](tests/sniper-autonomy.test.js), [tests/sniper-optimizer.test.js](tests/sniper-optimizer.test.js), [tests/sniper-judge-knowledge.test.js](tests/sniper-judge-knowledge.test.js). See [docs/sniper-autonomy.md](docs/sniper-autonomy.md) || 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) |diff --git a/api/_lib/migrations/20260725080000_sniper_earned_autonomy.sql b/api/_lib/migrations/20260725080000_sniper_earned_autonomy.sqlnew file mode 100644index 000000000..2b8b897c5--- /dev/null+++ b/api/_lib/migrations/20260725080000_sniper_earned_autonomy.sql@@ -0,0 +1,26 @@+-- Earned autonomy: an arm's tier, recorded next to the tuning it drove.+--+-- The autonomy engine (api/_lib/sniper-autonomy.js) classifies every arm from its+-- own realized record on each optimizer run: probation | standard | trusted |+-- autonomous. The tier decides how wide the optimizer's bounds are, how big its+-- per-run step is, which fields it may write at all, how much of the fleet budget+-- the evolution loop concentrates on the arm, and how much evidence the LLM judge+-- is handed before it rules on a launch.+--+-- Storing the tier on each run makes the whole progression auditable after the+-- fact: you can see exactly which tier an arm held when a given knob moved, and+-- watch an arm earn its way up (or fall back) over time.+--+-- Additive and idempotent, safe to re-run.++ALTER TABLE agent_sniper_optimizer_runs+ ADD COLUMN IF NOT EXISTS autonomy_tier TEXT,+ ADD COLUMN IF NOT EXISTS autonomy_reason TEXT;++COMMENT ON COLUMN agent_sniper_optimizer_runs.autonomy_tier IS+ 'Earned-autonomy tier this run was decided under: probation | standard | trusted | autonomous.';+COMMENT ON COLUMN agent_sniper_optimizer_runs.autonomy_reason IS+ 'Human-readable evidence for the tier (realized sample, net PnL, average edge).';++CREATE INDEX IF NOT EXISTS idx_sniper_optimizer_runs_tier+ ON agent_sniper_optimizer_runs (autonomy_tier, created_at DESC);diff --git a/api/_lib/sniper-autonomy.js b/api/_lib/sniper-autonomy.jsnew file mode 100644index 000000000..3a5de021f--- /dev/null+++ b/api/_lib/sniper-autonomy.js@@ -0,0 +1,285 @@+// Earned autonomy: how much rope an arm gets, decided by its own realized record.+//+// The fleet's two self-improvement loops (api/cron/sniper-optimize.js tunes each+// arm's knobs, scripts/sniper-evolve.mjs moves budget between arms) used to treat+// every arm identically: the same hard bounds, the same per-run step, the same+// short list of writable fields, the same context in front of the LLM judge. That+// is backwards. An arm that has proven it makes money should be allowed to explore+// further and be told more; an arm that has proven it loses money should be held+// tighter until it recovers.+//+// This module is the pure policy that decides that. Given one arm's real trading+// record it returns a TIER, and the tier scales four things:+//+// 1. BOUNDS — how far the optimizer may move each knob.+// 2. STEP — how fast it may move it per run.+// 3. WRITABLE — which knobs it may touch at all (higher tiers unlock the entry+// universe, the LLM confidence bar, and the take-initials ladder).+// 4. KNOWLEDGE — how much evidence the LLM judge is handed before it decides.+//+// Plus a budget weight the evolution loop uses to concentrate the fixed fleet+// budget on earned arms.+//+// WHAT THIS NEVER TOUCHES. The deterministic safety rails are not "guardrails" in+// the sense meant here and no tier can reach them: the trade firewall's real+// buy→sell round-trip, Mayhem exclusion, max_price_impact, SOL headroom, the daily+// loss cap, max_concurrent_positions, and the fleet daily budget ceiling are all+// enforced in executeBuy and out of this module's reach. A tier widens the space+// an arm may search; it never removes the floor under it. The worst an autonomous+// arm can do is take a firewall-vetted, stop-loss-protected, budget-bounded trade.+//+// Pure: no I/O, no clock, no DB. Every input is passed in, so the whole policy is+// unit-testable and the same function decides the tier everywhere it is read.++/** Tiers, least to most rope. */+export const TIER_ORDER = ['probation', 'standard', 'trusted', 'autonomous'];++/** A per-trade realized average this close to zero is noise, not profit. */+export const MIN_EDGE_PCT = 0.5;++/** Evidence gates. Sample sizes are real closed fills, never paper. */+export const GATES = {+ trusted: { closed: 12, avgPnlPct: MIN_EDGE_PCT },+ autonomous: { closed: 40, avgPnlPct: 5 },+ // Aligned with the evolution loop's MIN_SAMPLES_RETIRE: below this an arm has+ // not lost enough times for the loss to mean anything.+ probation: { closed: 15, avgPnlPct: -MIN_EDGE_PCT },+};++// Hard ranges per tier. `standard` is the historical behaviour byte-for-byte, so+// an un-tiered caller is unchanged. Higher tiers widen the search space; probation+// narrows it. per_trade_lamports ceilings rise with tier, but the arm's daily+// budget (set by the evolution loop out of a fixed fleet total) remains the real+// spend ceiling regardless of what is allowed here.+export const TIER_BOUNDS = {+ probation: {+ take_profit_pct: { min: 15, max: 150 },+ trailing_stop_pct: { min: 8, max: 40 },+ stop_loss_pct: { min: 10, max: 40 },+ max_hold_seconds: { min: 120, max: 3_600 },+ min_quality_score: { min: 0, max: 100 },+ min_oracle_score: { min: 0, max: 100 },+ per_trade_lamports: { min: 2_000_000, max: 50_000_000 },+ },+ standard: {+ 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: 7_200 },+ min_quality_score: { min: 0, max: 100 },+ min_oracle_score: { min: 0, max: 100 },+ per_trade_lamports: { min: 2_000_000, max: 200_000_000 },+ },+ trusted: {+ take_profit_pct: { min: 10, max: 500 },+ trailing_stop_pct: { min: 5, max: 60 },+ stop_loss_pct: { min: 10, max: 60 },+ max_hold_seconds: { min: 60, max: 21_600 },+ min_quality_score: { min: 0, max: 100 },+ min_oracle_score: { min: 0, max: 100 },+ per_trade_lamports: { min: 2_000_000, max: 350_000_000 },+ // Unlocked at this tier.+ llm_min_confidence: { min: 0.35, max: 0.95 },+ min_market_cap_usd: { min: 1_000, max: 500_000 },+ max_market_cap_usd: { min: 10_000, max: 5_000_000 },+ initials_out_multiple: { min: 1.5, max: 5 },+ moonbag_min_pct: { min: 5, max: 60 },+ },+ autonomous: {+ take_profit_pct: { min: 5, max: 1_000 },+ trailing_stop_pct: { min: 3, max: 75 },+ // Never null, never absent: the stop is the one thing every tier keeps.+ stop_loss_pct: { min: 10, max: 65 },+ max_hold_seconds: { min: 30, max: 86_400 },+ min_quality_score: { min: 0, max: 100 },+ min_oracle_score: { min: 0, max: 100 },+ per_trade_lamports: { min: 2_000_000, max: 500_000_000 },+ llm_min_confidence: { min: 0.25, max: 0.95 },+ min_market_cap_usd: { min: 500, max: 1_000_000 },+ max_market_cap_usd: { min: 5_000, max: 10_000_000 },+ initials_out_multiple: { min: 1.5, max: 10 },+ moonbag_min_pct: { min: 5, max: 75 },+ max_creator_launches: { min: 1, max: 100 },+ },+};++/** Per-run step multiplier: earned arms converge (and explore) faster. */+export const TIER_STEP_SCALE = {+ probation: 0.5,+ standard: 1,+ trusted: 1.75,+ autonomous: 2.5,+};++/**+ * Fitness multiplier the evolution loop applies before splitting the fixed fleet+ * budget. Concentrates capital on earned arms without changing the fleet total or+ * removing the per-arm exploration floor.+ */+export const TIER_BUDGET_WEIGHT = {+ probation: 0.6,+ standard: 1,+ trusted: 1.5,+ autonomous: 2.2,+};++/**+ * How much evidence the LLM judge is handed before it rules on a launch.+ * base — the launch brief + market-realness read (the historical prompt).+ * informed — plus the ground-truth base rate, the learned signal weights, and+ * this arm's own realized track record.+ * full — plus the conditional win-rate table (which signal buckets actually+ * win) and the arm's own verdict calibration.+ */+export const TIER_KNOWLEDGE = {+ probation: 'base',+ standard: 'base',+ trusted: 'informed',+ autonomous: 'full',+};++/** Fields every tier may write (the historical set). */+const BASE_WRITABLE = [+ 'take_profit_pct', 'trailing_stop_pct', 'stop_loss_pct', 'max_hold_seconds',+ 'min_quality_score', 'min_oracle_score', 'per_trade_lamports',+];++/** Fields each tier unlocks on top of BASE_WRITABLE. */+const TIER_UNLOCKS = {+ probation: [],+ standard: [],+ // An arm that makes money earns the right to widen its own hunting ground,+ // lower its own confidence bar, and let its winners run on the ladder.+ trusted: ['llm_min_confidence', 'min_market_cap_usd', 'max_market_cap_usd', 'initials_out_multiple', 'moonbag_min_pct'],+ autonomous: ['llm_min_confidence', 'min_market_cap_usd', 'max_market_cap_usd', 'initials_out_multiple', 'moonbag_min_pct', 'max_creator_launches'],+};++/**+ * Fields that may be set from unset (null).+ *+ * trailing_stop_pct is here for every tier on purpose: an arm carrying a null+ * trailing stop has no way out of a fading position except the hard stop or the+ * timeout, and setting one only ever protects. The ladder fields need unset→set+ * because that is precisely how the take-initials exit gets turned on.+ */+const BASE_UNSET_OK = ['take_profit_pct', 'min_oracle_score', 'min_quality_score', 'trailing_stop_pct'];+const TIER_UNSET_OK = {+ probation: [],+ standard: [],+ trusted: ['initials_out_multiple'],+ autonomous: ['initials_out_multiple'],+};++const norm = (tier) => (TIER_ORDER.includes(tier) ? tier : 'standard');++/** Rank comparison helper: `atLeast('trusted', tier)`. */+export function atLeast(minTier, tier) {+ return TIER_ORDER.indexOf(norm(tier)) >= TIER_ORDER.indexOf(norm(minTier));+}++/** Hard ranges for a tier. */+export function boundsFor(tier) {+ return TIER_BOUNDS[norm(tier)];+}++/** Per-run step ceilings for a tier, derived from the standard steps. */+export function stepsFor(tier, baseSteps) {+ const scale = TIER_STEP_SCALE[norm(tier)];+ const out = {};+ for (const [field, step] of Object.entries(baseSteps)) {+ // Fractional steps (per_trade_fraction) scale but stay a sane fraction.+ out[field] = field.endsWith('_fraction') ? Math.min(0.75, step * scale) : step * scale;+ }+ return out;+}++/** The set of fields a tier's optimizer may write. */+export function writableFor(tier) {+ return new Set([...BASE_WRITABLE, ...TIER_UNLOCKS[norm(tier)]]);+}++/** The set of fields a tier may set from null. */+export function unsetOkFor(tier) {+ return new Set([...BASE_UNSET_OK, ...TIER_UNSET_OK[norm(tier)]]);+}++/** Budget concentration weight for the evolution loop. */+export function budgetWeightFor(tier) {+ return TIER_BUDGET_WEIGHT[norm(tier)];+}++/** How deep a knowledge pack this tier's judge receives. */+export function knowledgeFor(tier) {+ return TIER_KNOWLEDGE[norm(tier)];+}++/**+ * Classify one arm from its realized record. Recomputed from scratch on every+ * optimizer run against a trailing window, so a tier is always current: an arm+ * that stops making money loses its rope on the next pass without anyone+ * intervening, and a demoted arm earns it back the same way.+ *+ * `avgPnlPct` (mean realized P&L per closed trade) is the edge measure rather+ * than win rate on purpose: an arm can win 36% of the time and still be the most+ * profitable on the board, and that arm is exactly the one that has earned room.+ *+ * @param {object} record+ * @param {number} record.closed real closed fills in the window+ * @param {number} [record.wins] real winning fills (reported, not gating)+ * @param {number} record.netPnlLamports realized net P&L over the window+ * @param {number} record.avgPnlPct mean realized P&L % per closed trade+ * @returns {{ tier:string, reason:string, evidence:object }}+ */+export function classifyAutonomy(record) {+ const closed = Number(record?.closed) || 0;+ const net = Number(record?.netPnlLamports) || 0;+ const avg = Number(record?.avgPnlPct) || 0;+ const wins = Number(record?.wins) || 0;+ const evidence = {+ closed, wins, net_pnl_sol: Number((net / 1e9).toFixed(6)), avg_pnl_pct: Number(avg.toFixed(2)),+ win_rate_pct: closed > 0 ? Math.round((wins / closed) * 100) : 0,+ };++ const profitable = net > 0 && avg >= MIN_EDGE_PCT;+ const bleeding = net < 0 && avg <= -MIN_EDGE_PCT;++ if (profitable && closed >= GATES.autonomous.closed && avg >= GATES.autonomous.avgPnlPct) {+ return {+ tier: 'autonomous',+ reason: `Sustained profit: +${avg.toFixed(1)}% average over ${closed} real trades (net ${evidence.net_pnl_sol} SOL). Full field access, widest bounds, complete knowledge pack.`,+ evidence,+ };+ }+ if (profitable && closed >= GATES.trusted.closed) {+ return {+ tier: 'trusted',+ reason: `Profitable with a real sample: +${avg.toFixed(1)}% average over ${closed} real trades (net ${evidence.net_pnl_sol} SOL). Entry universe, confidence bar and take-initials ladder unlocked.`,+ evidence,+ };+ }+ if (bleeding && closed >= GATES.probation.closed) {+ return {+ tier: 'probation',+ reason: `Proven bleed: ${avg.toFixed(1)}% average over ${closed} real trades (net ${evidence.net_pnl_sol} SOL). Bounds narrowed and steps halved until the record recovers.`,+ evidence,+ };+ }+ return {+ tier: 'standard',+ reason: closed < GATES.trusted.closed+ ? `Insufficient evidence: ${closed} real trades. Standard bounds until the record can carry a verdict.`+ : `No decisive edge: ${avg.toFixed(1)}% average over ${closed} real trades. Standard bounds.`,+ evidence,+ };+}++/** One-line human summary of what a tier grants. For reports and the UI. */+export function describeTier(tier) {+ const t = norm(tier);+ return {+ probation: 'Held tight: narrowed bounds, half steps, size capped at 0.05 SOL, base knowledge.',+ standard: 'Default: historical bounds and steps, base knowledge.',+ trusted: 'Earned: wider bounds, 1.75x steps, entry universe + confidence bar + ladder unlocked, informed knowledge pack.',+ autonomous: 'Fully earned: widest bounds, 2.5x steps, every tunable field unlocked, complete knowledge pack.',+ }[t];+}diff --git a/api/_lib/sniper-optimizer.js b/api/_lib/sniper-optimizer.jsindex d7af8b708..84c60f196 100644--- a/api/_lib/sniper-optimizer.js+++ b/api/_lib/sniper-optimizer.js@@ -10,31 +10,34 @@// This never touches the deterministic safety rails (trade firewall, Mayhem// exclusion, budgets, concurrency). It only moves policy knobs, each bounded.//+// EARNED AUTONOMY. The range, the step, and the set of writable fields are not+// fixed: they come from the arm's tier (api/_lib/sniper-autonomy.js), which is+// recomputed from its realized record on every run. A profitable arm gets wider+// bounds, bigger steps, and access to fields a losing arm cannot touch (its entry+// universe, its LLM confidence bar, the take-initials ladder); an arm that is+// bleeding gets narrower bounds and half steps until it recovers. Callers that+// pass no tier get 'standard', which is the historical behaviour exactly.+//// 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.+// Rules O/A/B/C/E tighten and run for every tier. Rules D/F/G/H hand room back to+// an arm that earned it and are gated on tier + realized profit.++import { atLeast, boundsFor, stepsFor, unsetOkFor, writableFor } from './sniper-autonomy.js';// 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 },-};+// Hard ranges for the DEFAULT tier. Every tier's ranges live in+// api/_lib/sniper-autonomy.js (TIER_BOUNDS); this export is the 'standard' row,+// kept as the public constant so existing callers and tests read one source of+// truth rather than a second copy that can drift.+export const BOUNDS = boundsFor('standard');-// Max change a single run may make to each field. Small steps → the loop-// converges gradually and every move stays observable.+// Max change a single run may make to each field at the DEFAULT tier. Small steps+// → the loop converges gradually and every move stays observable. Higher tiers+// scale these up (TIER_STEP_SCALE), probation halves them.export const STEP = {take_profit_pct: 15,trailing_stop_pct: 5,@@ -43,12 +46,20 @@ export const STEP = {min_quality_score: 5,min_oracle_score: 5,per_trade_fraction: 0.2, // ≤20% size change per run+ // Tier-unlocked fields. Only reachable once an arm has earned the field.+ llm_min_confidence: 0.05,+ min_market_cap_usd: 5_000,+ max_market_cap_usd: 25_000,+ initials_out_multiple: 0.5,+ moonbag_min_pct: 5,+ max_creator_launches: 5,};-// Fields that may be set from unset (null). For a filter threshold, null means-// "no filter" and turning one on is a safe tightening; for take-profit it locks-// gains. Stops/hold are deliberately excluded: null there is load-bearing.-const UNSET_OK = new Set(['take_profit_pct', 'min_oracle_score', 'min_quality_score']);+// Fields written as whole numbers. Everything else keeps its natural precision+// (llm_min_confidence and initials_out_multiple are fractional by nature).+const INTEGER_FIELDS = new Set([+ 'max_hold_seconds', 'per_trade_lamports', 'min_market_cap_usd', 'max_market_cap_usd', 'max_creator_launches',+]);const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));const num = (v) => (v == null ? null : Number(v));@@ -108,17 +119,26 @@ function share(exitReasons, key, total) {* 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[] }}+ * @param {{ tier?: string }} [opts] earned-autonomy tier; omitted = 'standard'+ * @returns {{ proposals: Array<{field,from,to,reason}>, sample:number, acted:boolean, notes:string[], tier:string }}*/-export function proposeAdjustments(stats, config) {+export function proposeAdjustments(stats, config, opts = {}) {const proposals = [];const claimed = new Set();const notes = [];const sample = Number(stats?.closed) || 0;const mode = (config?.decision_mode || 'rules');+ // Tier decides how far, how fast, and which fields at all.+ const tier = opts.tier || 'standard';+ const bounds = boundsFor(tier);+ const steps = stepsFor(tier, STEP);+ const writable = writableFor(tier);+ const unsetOk = unsetOkFor(tier);+ const earned = atLeast('trusted', tier);+if (sample < MIN_SAMPLE) {- return { proposals, sample, acted: false, notes: [`sample ${sample} < ${MIN_SAMPLE}, no action`] };+ return { proposals, sample, acted: false, tier, notes: [`sample ${sample} < ${MIN_SAMPLE}, no action`] };}const winRate = num(stats.winRate) ?? 0;@@ -132,23 +152,29 @@ export function proposeAdjustments(stats, config) {const perTrade = num(config.per_trade_lamports);const quality = num(config.min_quality_score);const oracle = num(config.min_oracle_score);+ const confidence = num(config.llm_min_confidence);+ const mcapMin = num(config.min_market_cap_usd);+ const mcapMax = num(config.max_market_cap_usd);+ const ladder = num(config.initials_out_multiple);+ const creatorCap = num(config.max_creator_launches);const propose = (field, to, reason) => {if (claimed.has(field)) return;- const b = BOUNDS[field];+ if (!writable.has(field)) return; // the tier has not earned this field+ 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 = boundedToward(from, to, steps[field], b);}target = clamp(target, b.min, b.max);- if (field === 'max_hold_seconds' || field === 'per_trade_lamports') target = Math.round(target);+ if (INTEGER_FIELDS.has(field)) target = Math.round(target);+ else target = Number(target.toFixed(2));if (from != null && target === from) return; // no-op- if (from == null && !UNSET_OK.has(field)) return; // some fields must not be set from unset+ if (from == null && !unsetOk.has(field)) return; // some fields must not be set from unsetclaimed.add(field);proposals.push({ field, from, to: target, reason });};@@ -203,19 +229,83 @@ export function proposeAdjustments(stats, config) {}}- // 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 D: proven arm: scale size up, bounded, never past the tier's ceiling.+ // Two ways to qualify. The classic one is a high win rate. The second exists+ // because win rate is the wrong measure for a momentum arm: one that wins 36%+ // of the time but is net profitable has a real edge and has earned more size.+ // That second path is tier-gated, so only an arm the autonomy engine already+ // judged profitable can take it.+ const provenByWinRate = winRate >= 60 && avg > 10;+ const provenByProfit = earned && netPnl > 0;+ if ((provenByWinRate || provenByProfit) && sample >= MIN_SAMPLE * 1.5 && perTrade != null) {+ const pct = Math.round(steps.per_trade_fraction * 75);+ propose('per_trade_lamports', Math.round(perTrade * (1 + steps.per_trade_fraction * 0.75)),+ provenByWinRate+ ? `Proven arm (${winRate}% win rate, avg +${avg.toFixed(1)}% over ${sample} trades): scale size up ${pct}% within the hard cap.`+ : `Net profitable over ${sample} real trades (${(netPnl / 1e9).toFixed(4)} SOL, avg +${avg.toFixed(1)}%) despite a ${winRate}% win rate: an edge that pays does not need a high hit rate. Scale size up ${pct}% within the tier 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)),+ propose('per_trade_lamports', Math.round(perTrade * (1 - steps.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 };+ // ── Earned freedom. Everything below hands room BACK to an arm that has proven+ // it makes money, instead of only ever tightening it. All of it is gated on+ // tier (trusted+) and on realized profit, all of it is bounded and reversible,+ // and every field here is one a losing arm cannot reach at all.+ const profitable = earned && netPnl > 0;++ // Rule F: a profitable judge earns a lower bar. An LLM arm in the money is+ // passing on launches it would have won; walk its confidence floor down so it+ // takes more shots. Demotion reverses this automatically on the next run.+ if (profitable && mode === 'llm' && confidence != null) {+ propose('llm_min_confidence', confidence - steps.llm_min_confidence,+ `Profitable judgment (net ${(netPnl / 1e9).toFixed(4)} SOL, avg +${avg.toFixed(1)}% over ${sample} trades): lower the confidence floor from ${confidence} so the model acts on more of what it sees. Widening exploration where the record says the judgment is sound.`);+ }++ // Rule G: a profitable arm earns a wider hunting ground. Widen the market-cap+ // band outward on both sides and, at the top tier, loosen the serial-launcher+ // cap. Only widens a band that exists: an arm with no band is already+ // unrestricted and nothing here would restrict it.+ if (profitable) {+ if (mcapMin != null) {+ propose('min_market_cap_usd', mcapMin - steps.min_market_cap_usd,+ `Profitable over ${sample} trades: lower the entry floor from $${Math.round(mcapMin).toLocaleString('en-US')} to explore earlier launches this arm currently never sees.`);+ }+ if (mcapMax != null) {+ propose('max_market_cap_usd', mcapMax + steps.max_market_cap_usd,+ `Profitable over ${sample} trades: raise the entry ceiling from $${Math.round(mcapMax).toLocaleString('en-US')} to explore larger launches this arm currently never sees.`);+ }+ if (creatorCap != null) {+ propose('max_creator_launches', creatorCap + steps.max_creator_launches,+ `Profitable over ${sample} trades: loosen the serial-launcher cap from ${creatorCap} — a prolific creator is not automatically a bad one, and this arm has earned the right to test that.`);+ }+ }++ // Rule H: a profitable arm whose winners run well past its average exit earns+ // the take-initials ladder: recover the stake at 2x, keep a moon bag, let the+ // rest ride the trailing stop. This is the one exit change that raises the+ // ceiling instead of lowering it, so it is gated on an arm having shown it+ // actually catches runners (best far above avg).+ if (profitable && best - avg >= 25) {+ if (ladder == null) {+ propose('initials_out_multiple', 2,+ `Winners run far past the average exit (best +${best.toFixed(0)}% vs avg +${avg.toFixed(1)}% over ${sample} trades) and the arm is net profitable: turn on the take-initials ladder. Recover the stake at 2x, keep the moon bag, let the remainder ride the trailing stop instead of full-exiting every winner.`);+ notes.push('ladder_enabled');+ } else {+ // Ladder already on and still leaving upside on the table: keep more of+ // each position riding after the initials come out.+ const moonbag = num(config.moonbag_min_pct);+ if (moonbag != null) {+ propose('moonbag_min_pct', moonbag + steps.moonbag_min_pct,+ `Ladder is on and winners still run well past the average exit (best +${best.toFixed(0)}% vs avg +${avg.toFixed(1)}%): raise the moon-bag floor from ${moonbag}% so more of each winner keeps riding after the stake is recovered.`);+ }+ }+ }++ return { proposals, sample, acted: proposals.length > 0, notes, tier };}diff --git a/api/cron/sniper-optimize.js b/api/cron/sniper-optimize.jsindex 9ca782f1c..d26bfd3a9 100644--- a/api/cron/sniper-optimize.js+++ b/api/cron/sniper-optimize.js@@ -15,6 +15,14 @@// concurrency) are never touched here. The optimizer only moves policy knobs a// human owner already tunes, each clamped to a hard range.//+// How wide that range is depends on the arm. Each run classifies every arm with+// the earned-autonomy engine (api/_lib/sniper-autonomy.js) from its own realized+// record: a profitable arm gets wider bounds, bigger steps, and unlocks fields a+// losing arm cannot touch (its entry universe, its LLM confidence bar, the+// take-initials ladder); a bleeding arm gets narrowed bounds and half steps. The+// tier is recomputed from scratch every pass, so freedom is continuously earned+// rather than granted once, and it is recorded on the run row and in the ledger.+//// Controls:// SNIPER_OPTIMIZER_MODE = shadow | apply (default shadow)// SNIPER_OPTIMIZER_WINDOW = 24h | 7d | 30d (default 7d)@@ -26,6 +34,7 @@ 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';+import { classifyAutonomy, describeTier } from '../_lib/sniper-autonomy.js';const WINDOWS = { '24h': '24 hours', '7d': '7 days', '30d': '30 days' };@@ -50,6 +59,20 @@ async function applyProposal(strategyId, field, value) {return sql`update agent_sniper_strategies set min_oracle_score = ${value}, updated_at = now() where id = ${strategyId}`;case 'per_trade_lamports':return sql`update agent_sniper_strategies set per_trade_lamports = ${value}, updated_at = now() where id = ${strategyId}`;+ // Tier-unlocked fields. The optimizer only ever emits these for an arm the+ // autonomy engine placed at trusted or above; the switch is the second gate.+ case 'llm_min_confidence':+ return sql`update agent_sniper_strategies set llm_min_confidence = ${value}, updated_at = now() where id = ${strategyId}`;+ case 'min_market_cap_usd':+ return sql`update agent_sniper_strategies set min_market_cap_usd = ${value}, updated_at = now() where id = ${strategyId}`;+ case 'max_market_cap_usd':+ return sql`update agent_sniper_strategies set max_market_cap_usd = ${value}, updated_at = now() where id = ${strategyId}`;+ case 'initials_out_multiple':+ return sql`update agent_sniper_strategies set initials_out_multiple = ${value}, updated_at = now() where id = ${strategyId}`;+ case 'moonbag_min_pct':+ return sql`update agent_sniper_strategies set moonbag_min_pct = ${value}, updated_at = now() where id = ${strategyId}`;+ case 'max_creator_launches':+ return sql`update agent_sniper_strategies set max_creator_launches = ${value}, updated_at = now() where id = ${strategyId}`;default:throw new Error(`optimizer refused to write unknown field '${field}'`);}@@ -76,6 +99,8 @@ async function armStats(network, interval) {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,+ s.llm_min_confidence, s.min_market_cap_usd, s.max_market_cap_usd,+ s.initials_out_multiple, s.moonbag_min_pct, s.max_creator_launches,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,@@ -128,7 +153,7 @@ export default wrapCron(async (req, res) => {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: [] };+ const report = { mode, window: windowLabel, arms: 0, with_proposals: 0, applied: 0, skipped_optin: 0, errors: 0, tiers: {}, runs: [] };let rows = [];let oracleByArm = new Map();try {@@ -159,7 +184,13 @@ export default wrapCron(async (req, res) => {exitReasons: r.exit_reasons || {},oracleBuckets: oracleByArm.get(r.strategy_id) || [],};- const { proposals, sample, acted, notes } = proposeAdjustments(stats, r);+ // Earned autonomy: the arm's own realized record decides how much rope it+ // gets this run. Recomputed every pass, so a profitable arm widens as it+ // keeps earning and a fading one narrows again without anyone stepping in.+ const autonomy = classifyAutonomy(stats);+ report.tiers[autonomy.tier] = (report.tiers[autonomy.tier] || 0) + 1;++ const { proposals, sample, acted, notes } = proposeAdjustments(stats, r, { tier: autonomy.tier });if (!acted) continue;report.with_proposals++;@@ -180,8 +211,8 @@ export default wrapCron(async (req, res) => {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(', ')}.`,+ inputs: { window: windowLabel, sample, stats, proposals, autonomy },+ rationale: `Auto-tuned ${proposals.length} field(s) for arm "${r.label || r.strategy_id}" from ${sample} real trades over ${windowLabel} at autonomy tier "${autonomy.tier}" (${autonomy.reason}): ${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,@@ -192,15 +223,18 @@ export default wrapCron(async (req, res) => {await sql`insert into agent_sniper_optimizer_runs- (strategy_id, agent_id, network, mode, window_label, sample_size, evidence, proposals, applied, ledger_seq)+ (strategy_id, agent_id, network, mode, window_label, sample_size, evidence, proposals, applied, ledger_seq,+ autonomy_tier, autonomy_reason)values(${r.strategy_id}, ${r.agent_id}, ${network}, ${mode}, ${windowLabel}, ${sample},- ${JSON.stringify(stats)}::jsonb, ${JSON.stringify(proposals)}::jsonb, ${willApply}, ${ledgerSeq})+ ${JSON.stringify({ ...stats, autonomy })}::jsonb, ${JSON.stringify(proposals)}::jsonb, ${willApply}, ${ledgerSeq},+ ${autonomy.tier}, ${autonomy.reason})`;report.runs.push({strategy_id: r.strategy_id, label: r.label || null, sample,applied: willApply, opted_in: optedIn,+ tier: autonomy.tier, tier_reason: autonomy.reason, tier_grants: describeTier(autonomy.tier),proposals: proposals.map((p) => ({ field: p.field, from: p.from, to: p.to })),notes,});diff --git a/api/sniper/experiments.js b/api/sniper/experiments.jsindex 5072fc7a4..598ee64b6 100644--- a/api/sniper/experiments.js+++ b/api/sniper/experiments.js@@ -20,6 +20,7 @@ import { sql } from '../_lib/db.js';import { cacheGet, cacheSet } from '../_lib/cache.js';import { solanaConnection } from '../_lib/solana/connection.js';import { getSolBalance } from '../_lib/avatar-wallet.js';+import { classifyAutonomy, describeTier } from '../_lib/sniper-autonomy.js';const NETWORKS = new Set(['mainnet', 'devnet']);const WINDOWS = { '24h': '24 hours', '7d': '7 days', '30d': '30 days', all: null };@@ -100,6 +101,7 @@ export default wrap(async (req, res) => {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,+ s.initials_out_multiple, s.moonbag_min_pct, s.max_creator_launches, s.auto_optimize,a.id as agent_id, a.name as agent_name, a.meta->>'solana_address' as wallet_address,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,@@ -131,6 +133,15 @@ export default wrap(async (req, res) => {const experiments = rows.map((r) => {const closed = Number(r.closed) || 0;const wins = Number(r.wins) || 0;+ // Earned autonomy over the same window this board reports. The optimizer+ // recomputes this independently on its own schedule; showing it here is what+ // makes "why did that arm get a wider band" answerable without a DB query.+ const autonomy = classifyAutonomy({+ closed,+ wins,+ netPnlLamports: Number(r.realized_pnl_lamports) || 0,+ avgPnlPct: r.avg_pnl_pct != null ? Number(r.avg_pnl_pct) : 0,+ });return {strategy_id: r.strategy_id,label: r.label || `${(r.decision_mode || 'rules') === 'llm' ? 'llm' : 'rules'}:${String(r.strategy_id).slice(0, 8)}`,@@ -151,6 +162,15 @@ export default wrap(async (req, res) => {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,+ // Laddered exit: null multiple = classic single-shot full exit.+ initials_out_multiple: r.initials_out_multiple != null ? Number(r.initials_out_multiple) : null,+ moonbag_min_pct: r.moonbag_min_pct != null ? Number(r.moonbag_min_pct) : null,+ max_creator_launches: r.max_creator_launches != null ? Number(r.max_creator_launches) : null,+ // Earned autonomy: what this arm's own record has bought it.+ autonomy_tier: autonomy.tier,+ autonomy_reason: autonomy.reason,+ autonomy_grants: describeTier(autonomy.tier),+ auto_optimize: r.auto_optimize === true,closed,wins,losses: Math.max(0, closed - wins),diff --git a/data/pages.json b/data/pages.jsonindex ea0a38945..84989540b 100644--- a/data/pages.json+++ b/data/pages.json@@ -2919,6 +2919,14 @@"changefreq": "monthly","added": "2026-07-19"},+ {+ "path": "/docs/sniper-autonomy",+ "title": "Earned Autonomy: Freedom the Sniper Fleet Has to Trade For",+ "description": "How a trading arm's own realized record decides how much rope it gets: the four tiers, what each unlocks in the optimizer and the fleet budget, how much evidence the LLM judge is handed, and the safety rails no amount of profit can unlock.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-25"+ },{"path": "/tutorials/agent-personality","title": "Tutorial: Agent Personality",diff --git a/docs/sniper-autonomy.md b/docs/sniper-autonomy.mdnew file mode 100644index 000000000..3bb8979b0--- /dev/null+++ b/docs/sniper-autonomy.md@@ -0,0 +1,171 @@+# Earned autonomy: freedom the fleet has to trade for++The sniper fleet runs several strategies ("arms") side by side against the same+market. Two loops improve them without a human in the seat: the+[optimizer](../api/cron/sniper-optimize.js) tunes each arm's own knobs, and the+[evolution loop](../scripts/sniper-evolve.mjs) moves budget between arms.++Both used to treat every arm identically. Same hard bounds, same per-run step,+same short list of writable fields, same context in front of the LLM judge. An+arm that had been profitable for weeks was allowed to search exactly as narrow a+space as one that had never had a winning day, and was told exactly as little+before deciding.++Earned autonomy fixes that. An arm's own realized record decides how much rope it+gets, and the decision is recomputed from scratch every run.++## The tiers++| Tier | Earned by | What it grants |+|---|---|---|+| `probation` | net negative with an average per-trade edge at or below -0.5%, over 15+ real trades | Narrowed bounds, half-size steps, per-trade size capped at 0.05 SOL, base knowledge |+| `standard` | the default: too few trades to judge, or no decisive edge | Historical bounds and steps, base knowledge |+| `trusted` | net positive with an average edge of at least +0.5%, over 12+ real trades | Wider bounds, 1.75x steps, unlocks the entry universe, the LLM confidence bar and the take-initials ladder, informed knowledge pack |+| `autonomous` | net positive with an average edge of at least +5%, over 40+ real trades | Widest bounds, 2.5x steps, every tunable field, complete knowledge pack |++The gates live in [`api/_lib/sniper-autonomy.js`](../api/_lib/sniper-autonomy.js)+as `GATES`, and the whole policy is pure: no I/O, no clock, no DB, so the same+function decides the tier everywhere it is read and the entire thing is+unit-testable ([tests](../tests/sniper-autonomy.test.js)).++### Why average edge and not win rate++An arm can win 36% of the time and still be the most profitable on the board,+because the winners are far larger than the losers. Win rate would demote that+arm. The tier is decided on realized net P&L plus average per-trade edge, so the+arm that actually makes money is the one that earns room, whatever its hit rate.++The reverse case is just as important: an arm that wins 60% of its trades and is+still net negative (small winners, large losers) is not succeeding, and gets+`probation` rather than a reward.++### It is symmetric, and it is continuous++A tier is not granted once. Every optimizer run recomputes it against a trailing+window, so an arm that stops making money loses its rope on the next pass without+anyone intervening, and a demoted arm earns it back the same way. Freedom is+rented, never owned.++## What a tier changes++### 1. How far and how fast the optimizer may move a knob++Each tier carries its own `TIER_BOUNDS` and a step multiplier. Higher tiers widen+the search space in both directions and let a single run move further; probation+narrows it and halves the step. `standard` is the historical behaviour exactly,+so anything that does not pass a tier is unchanged.++### 2. Which fields the optimizer may touch at all++Every tier can tune stops, take-profit, hold time, the quality and oracle floors,+and position size. Reaching `trusted` unlocks four more:++- `llm_min_confidence` — a profitable judge earns a lower bar, so it acts on more+ of what it sees instead of passing on launches it would have won.+- `min_market_cap_usd` / `max_market_cap_usd` — a wider hunting ground, widened+ outward only. An arm with no band set is already unrestricted and nothing here+ will restrict it.+- `initials_out_multiple` — the [take-initials ladder](./trading-experiment.md):+ recover the stake at 2x, keep a moon bag, let the rest ride the trailing stop.+ Turned on only for an arm whose winners demonstrably run past its average exit.++`autonomous` adds `max_creator_launches`, so a proven arm can test whether a+prolific creator is really a bad one.++### 3. How much of the fleet budget an arm concentrates++The evolution loop multiplies each arm's fitness by its tier weight (0.6 on+probation up to 2.2 at autonomous) before splitting the fixed fleet budget. The+fleet total never changes and the per-arm floor still keeps exploration alive:+this only decides how the same pot is divided.++### 4. How much the LLM judge is told++This is the "more knowledge" half, and it is built in+[`workers/agent-sniper/judge-knowledge.js`](../workers/agent-sniper/judge-knowledge.js).++- **base** (probation, standard) — the launch brief and the market-realness read.+ Exactly the prompt the judge has always received.+- **informed** (trusted) — plus the ground-truth base rate (what fraction of+ launches actually win, so the model knows how skeptical its prior should be),+ the learned signal weights retrained every 15 minutes from labeled outcomes,+ and the arm's own realized record.+- **full** (autonomous) — plus the conditional win-rate table (per signal bucket,+ the realized win rate versus baseline: what actually happened, not a+ correlation the model has to interpret) and the model's own calibration, so it+ can correct its own bias.++Every line of it is read from real rows. When a table is empty or the database is+unreachable the pack degrades to a shorter block or to nothing at all, and the+judge falls back to the prompt it used before. An arm is told what is true or it+is told nothing.++**Cost note.** Verdicts are cached per `(mint, model, knowledge depth)`. Arms at+base depth still share one call across a same-model fleet exactly as before. An+arm with earned context is asking a materially different question, so it pays for+its own call. Only a profitable arm has one.++## What no tier can ever touch++Earned autonomy widens the space an arm may search. It never removes the floor+under it. These are enforced at the `executeBuy` chokepoint and are out of reach+of both loops at every tier:++- the trade firewall's real buy → sell round-trip+- Mayhem exclusion+- `max_price_impact_pct` and slippage caps+- SOL headroom and the daily loss cap+- `max_concurrent_positions`+- the fleet daily budget ceiling+- the kill switch++A hard stop-loss also survives every tier. The range widens (up to 65% at+`autonomous`) but it can never be unset and never reach zero, so "no stop" is not+a state any amount of profit can unlock. The worst an autonomous arm can do is+take a firewall-vetted, stop-loss-protected, budget-bounded trade.++A test asserts this directly: no safety field appears in any tier's writable set,+and every tier keeps a bounded stop.++## Reading it++The tier is visible in three places:++- **[/sniper/experiments](https://three.ws/sniper/experiments)** — a badge on any+ arm that has moved off `standard`, with the evidence in its tooltip, plus an+ "Earned autonomy" summary tile. `GET /api/sniper/experiments` returns+ `autonomy_tier`, `autonomy_reason` and `autonomy_grants` per arm.+- **`agent_sniper_optimizer_runs`** — every run records the `autonomy_tier` and+ `autonomy_reason` it acted under, so you can see which tier an arm held when a+ given knob moved.+- **the Reasoning Ledger** — an applied tuning names the tier and its evidence in+ the rationale, next to the trades it learned from.++## Worked example++The fleet as of 2026-07-25, classified over its all-time record:++| Arm | Closed | Net SOL | Avg edge | Tier |+|---|---|---|---|---|+| llm-grok | 33 | +0.0027 | +0.81% | `trusted` |+| llm-auto | 20 | +0.0001 | +0.04% | `standard` (noise, not profit) |+| llm-claude | 13 | -0.0116 | -8.89% | `standard` (sample below the demotion gate) |+| boost-ride | 62 | -0.0201 | -3.24% | `probation` |+| oracle-open | 30 | -0.0234 | -15.4% | `probation` |++`llm-grok` is the only arm that has earned anything, which is the correct read:+it is the only one with a real sample and a real profit. Its budget share rises+by roughly half, its judge starts seeing the base rate and the learned weights,+and the optimizer may now walk its confidence floor down and turn its ladder on.+`boost-ride` wins 60% of its trades and is still net negative, so it is held+tighter rather than rewarded for the hit rate.++## Related++- [Agent Sniper](./agent-sniper.md) — the trading pipeline the arms run on+- [The 10 SOL trading experiment](./trading-experiment.md) — the exit thesis the+ ladder implements+- [`api/_lib/sniper-optimizer.js`](../api/_lib/sniper-optimizer.js) — the tuning+ rules, tier-scaled+- [`scripts/sniper-evolve.mjs`](../scripts/sniper-evolve.mjs) — the portfolio+ layer, tier-weighteddiff --git a/pages/sniper-experiments.html b/pages/sniper-experiments.htmlindex 0c3b9f122..3806fca68 100644--- a/pages/sniper-experiments.html+++ b/pages/sniper-experiments.html@@ -52,6 +52,7 @@<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="/src/sniper-experiments.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" />diff --git a/scripts/sniper-evolve.mjs b/scripts/sniper-evolve.mjsindex 0ccdbb08e..3266c7936 100644--- a/scripts/sniper-evolve.mjs+++ b/scripts/sniper-evolve.mjs@@ -25,6 +25,11 @@// revive a retired arm once enough time has passed to re-test it (exploration).// reallocate shift the fixed fleet daily budget toward higher-fitness arms,// with a floor so no arm starves and the experiment keeps exploring.+// Fitness is scaled by the arm's earned-autonomy tier+// (api/_lib/sniper-autonomy.js), so an arm with a proven profit+// concentrates more of the fleet budget and one that bleeds+// concentrates less. The fleet total and the per-arm floor are+// unchanged: this only decides how the same pot is divided.//// SAFETY BY CONSTRUCTION. The engine writes ONLY the fields in WRITABLE below.// It can never touch stop_loss_pct, firewall_level, max_price_impact, the daily@@ -36,6 +41,7 @@import { execSync } from 'node:child_process';import { createRequire } from 'node:module';+import { budgetWeightFor, classifyAutonomy } from '../api/_lib/sniper-autonomy.js';const require = createRequire(import.meta.url);const { Pool } = require('@neondatabase/serverless');@@ -116,6 +122,7 @@ export async function runEvolve({ apply = false, log = console.log } = {}) {count(p.id) filter (where p.status='closed' and p.buy_sig<>'SIMULATED') real_n,count(p.id) filter (where p.status='closed' and p.buy_sig<>'SIMULATED' and p.realized_pnl_lamports>0) real_w,coalesce(avg(p.realized_pnl_pct) filter (where p.status='closed' and p.buy_sig<>'SIMULATED'),0) real_avg_pct,+ coalesce(sum(p.realized_pnl_lamports) filter (where p.status='closed' and p.buy_sig<>'SIMULATED'),0) real_net_lamports,count(p.id) filter (where p.status='closed' and p.buy_sig='SIMULATED') paper_n,count(p.id) filter (where p.status='closed' and p.buy_sig='SIMULATED' and p.realized_pnl_lamports>0) paper_wfrom agent_sniper_strategies s@@ -127,17 +134,31 @@ export async function runEvolve({ apply = false, log = console.log } = {}) {// Fitness: conservative win-edge over the base rate (Wilson lower bound) plus// a realized-ROI term, real fills at full weight and paper at 1/3. An arm with// no evidence yet gets a neutral exploration fitness so it keeps a budget floor.+ //+ // The earned-autonomy tier then scales the result. Win rate alone underrates+ // an arm that hits rarely but pays well when it does, which is the normal+ // shape of a profitable momentum arm; the tier is computed from realized net+ // P&L and average edge, so an arm that actually makes money concentrates more+ // of the fixed fleet budget and one that bleeds concentrates less. The fleet+ // total never changes and the per-arm floor still keeps exploration alive.const fitness = (a) => {const realN = +a.real_n, realW = +a.real_w;const paperN = +a.paper_n, paperW = +a.paper_w;const n = realN + paperN / 3;const w = realW + paperW / 3;- if (n < 1) return { score: baseRate, samples: 0, edge: 0, wl: wilson(0, 0) };+ const autonomy = classifyAutonomy({+ closed: realN,+ wins: realW,+ netPnlLamports: Number(a.real_net_lamports) || 0,+ avgPnlPct: Number(a.real_avg_pct) || 0,+ });+ const weight = budgetWeightFor(autonomy.tier);+ if (n < 1) return { score: baseRate, samples: 0, edge: 0, wl: wilson(0, 0), tier: autonomy.tier, weight };const wl = wilson(w, Math.max(1, Math.round(n)));const edge = wl.lo - baseRate; // provable edge over ground truthconst roi = Math.max(-1, Math.min(2, Number(a.real_avg_pct) / 100));- const score = Math.max(0, baseRate + edge * 2 + roi * 0.05);- return { score, samples: Math.round(n), edge, wl, roi };+ const score = Math.max(0, (baseRate + edge * 2 + roi * 0.05) * weight);+ return { score, samples: Math.round(n), edge, wl, roi, tier: autonomy.tier, weight };};const proposals = [];@@ -175,7 +196,7 @@ export async function runEvolve({ apply = false, log = console.log } = {}) {const nextLamports = String(Math.round(share * LAMPORTS));const cur = String(a.daily_budget_lamports);if (nextLamports !== cur) propose(a, 'reallocate', 'daily_budget_lamports', cur, nextLamports, f,- { share_sol: +share.toFixed(4), fleet_sol: FLEET_DAILY_SOL, fitness: +f.score.toFixed(4) });+ { share_sol: +share.toFixed(4), fleet_sol: FLEET_DAILY_SOL, fitness: +f.score.toFixed(4), tier: f.tier, tier_weight: f.weight });}}@@ -184,7 +205,7 @@ export async function runEvolve({ apply = false, log = console.log } = {}) {log(`Fleet daily budget ${FLEET_DAILY_SOL} SOL across ${active.length} active arms. ${apply ? 'APPLYING' : 'DRY-RUN (no writes)'}.\n`);for (const a of arms) {const f = fitness(a);- log(` ${(a.label || '?').padEnd(17)} ${a.enabled ? 'ON ' : 'off'} fitness ${f.score.toFixed(4)} · ${f.samples} samples · edge ${(f.edge * 100).toFixed(1)}pt`);+ log(` ${(a.label || '?').padEnd(17)} ${a.enabled ? 'ON ' : 'off'} ${f.tier.padEnd(10)} (x${f.weight}) fitness ${f.score.toFixed(4)} · ${f.samples} samples · edge ${(f.edge * 100).toFixed(1)}pt`);}log(`\n${proposals.length} proposed mutation(s):`);for (const p of proposals) {diff --git a/src/sniper-experiments.css b/src/sniper-experiments.cssnew file mode 100644index 000000000..ca37401a1--- /dev/null+++ b/src/sniper-experiments.css@@ -0,0 +1,200 @@+/* /sniper/experiments — the strategy A/B scoreboard.+ *+ * Built entirely on the shared --cv-* design tokens from coin-pages.css, so the+ * board inherits both themes and every surface/border/text colour stays in step+ * with the rest of the crypto pages. Nothing here hardcodes a palette colour+ * except the four tier accents, which are semantic (earned vs held back) and are+ * defined against the token set so they invert with the theme.+ */++/* ── strategy cell ───────────────────────────────────────────────────────── */+.xp-label {+ font-weight: 600;+ color: var(--cv-text);+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+}++.xp-agent {+ margin-top: 2px;+ font-size: 0.8125rem;+ color: var(--cv-text-2);+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+}++.xp-agent a {+ color: var(--cv-accent);+ text-decoration: none;+ border-radius: var(--cv-radius-sm);+ transition: color 0.15s ease;+}++.xp-agent a:hover { color: var(--cv-accent-hover); text-decoration: underline; }+.xp-agent a:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: 2px; }++.xp-wallet {+ margin-top: 3px;+ font-family: var(--cv-font-mono);+ font-size: 0.75rem;+ color: var(--cv-text-3);+ display: flex;+ align-items: center;+ gap: 8px;+}++.xp-wallet a { color: var(--cv-text-2); text-decoration: none; }+.xp-wallet a:hover { color: var(--cv-accent); }+.xp-wallet a:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: 2px; }+.xp-wallet-none { color: var(--cv-text-3); font-style: italic; }++/* ── badges ──────────────────────────────────────────────────────────────── */+.xp-badge {+ display: inline-flex;+ align-items: center;+ padding: 1px 7px;+ border-radius: 999px;+ border: 1px solid var(--cv-border);+ background: var(--cv-surface-2);+ color: var(--cv-text-2);+ font-size: 0.6875rem;+ font-weight: 600;+ letter-spacing: 0.01em;+ white-space: nowrap;+ cursor: help;+}++.xp-badge-llm {+ border-color: color-mix(in srgb, var(--cv-accent) 40%, transparent);+ background: color-mix(in srgb, var(--cv-accent) 12%, transparent);+ color: var(--cv-accent);+}++.xp-badge-rules { font-family: var(--cv-font-mono); }++/* Earned autonomy. Only rendered off the default tier, so any colour on the+ * board means the arm's own record moved it up or down. */+.xp-badge-tier { text-transform: uppercase; letter-spacing: 0.04em; }++.xp-tier-trusted {+ border-color: color-mix(in srgb, var(--cv-green) 45%, transparent);+ background: var(--cv-green-soft);+ color: var(--cv-green);+}++.xp-tier-autonomous {+ border-color: var(--cv-green);+ background: color-mix(in srgb, var(--cv-green) 22%, transparent);+ color: var(--cv-green);+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--cv-green) 25%, transparent);+}++.xp-tier-probation {+ border-color: color-mix(in srgb, var(--cv-red) 45%, transparent);+ background: var(--cv-red-soft);+ color: var(--cv-red);+}++.xp-paused {+ font-size: 0.6875rem;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--cv-text-3);+}++/* ── conditions cell ─────────────────────────────────────────────────────── */+.xp-cond { max-width: 340px; color: var(--cv-text-2); font-size: 0.8125rem; }++.xp-cond-sub {+ margin-top: 3px;+ font-family: var(--cv-font-mono);+ font-size: 0.6875rem;+ color: var(--cv-text-3);+}++/* ── record cell ─────────────────────────────────────────────────────────── */+.xp-open {+ font-size: 0.75rem;+ color: var(--cv-accent);+ font-weight: 600;+}++.xp-paper {+ margin-top: 2px;+ font-size: 0.6875rem;+ color: var(--cv-text-3);+ font-style: italic;+}++/* ── P&L ─────────────────────────────────────────────────────────────────── */+.xp-pos { color: var(--cv-green); font-weight: 600; }+.xp-neg { color: var(--cv-red); font-weight: 600; }++/* ── table + rows ────────────────────────────────────────────────────────── */+.xp-table { width: 100%; font-size: 0.875rem; }+.xp-table td { vertical-align: top; padding: 10px 12px; }+.xp-table tbody tr { transition: background 0.15s ease; }+.xp-table tbody tr:hover { background: var(--cv-surface-2); }+.xp-off { opacity: 0.55; }++/* ── window switch ───────────────────────────────────────────────────────── */+.xp-seg {+ display: inline-flex;+ padding: 3px;+ gap: 2px;+ border: 1px solid var(--cv-border);+ border-radius: var(--cv-radius-md);+ background: var(--cv-surface-2);+}++.xp-seg-btn {+ appearance: none;+ border: 0;+ background: transparent;+ color: var(--cv-text-2);+ font: inherit;+ font-size: 0.8125rem;+ font-weight: 500;+ padding: 5px 12px;+ border-radius: var(--cv-radius);+ cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease;+}++.xp-seg-btn:hover { background: var(--cv-surface-3); color: var(--cv-text); }+.xp-seg-btn:focus-visible { outline: 2px solid var(--cv-accent); outline-offset: 1px; }++.xp-seg-btn.on {+ background: var(--cv-surface);+ color: var(--cv-text);+ box-shadow: var(--cv-shadow-card);+}++/* ── summary tiles ───────────────────────────────────────────────────────── */+.xp-tiles {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));+ gap: 12px;+}++.xp-tile {+ padding: 14px 16px;+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.xp-tile span { font-size: 0.75rem; color: var(--cv-text-3); }+.xp-tile b { font-size: 1.25rem; font-weight: 650; color: var(--cv-text); }+.xp-tile i { font-size: 0.75rem; font-style: normal; color: var(--cv-text-3); }++@media (max-width: 640px) {+ .xp-cond { max-width: none; }+ .xp-table { font-size: 0.8125rem; }+ .xp-table td { padding: 8px; }+}diff --git a/src/sniper-experiments.js b/src/sniper-experiments.jsindex d0d7c441e..bdea87052 100644--- a/src/sniper-experiments.js+++ b/src/sniper-experiments.js@@ -86,6 +86,28 @@ function modeBadge(x) {return `<span class="xp-badge xp-badge-rules">rules</span>`;}+// Earned autonomy: how much rope this arm's own record has bought it. Only shown+// once an arm has moved off the default, so the board stays quiet by default and+// a tier badge always means something happened.+function tierBadge(x) {+ const tier = x.autonomy_tier;+ if (!tier || tier === 'standard') return '';+ const title = `${x.autonomy_reason || ''} ${x.autonomy_grants || ''}`.trim();+ return ` <span class="xp-badge xp-badge-tier xp-tier-${esc(tier)}" title="${esc(title)}">${esc(tier)}</span>`;+}++// The exit shape in one glance. A null ladder is the classic single-shot full+// exit; a set one recovers the stake at Nx and keeps a moon bag riding.+function exitLine(x) {+ const bits = [`SL ${pct(-Math.abs(x.stop_loss_pct ?? 0), false)}`];+ if (x.trailing_stop_pct != null) bits.push(`trail ${pct(x.trailing_stop_pct, false)}`);+ if (x.max_hold_seconds != null) bits.push(`max ${holdFmt(x.max_hold_seconds)}`);+ bits.push(x.initials_out_multiple != null+ ? `ladder ${x.initials_out_multiple}x, ${x.moonbag_min_pct ?? 15}% moon bag`+ : 'no ladder');+ return bits.join(' · ');+}+function renderControls() {$('xp-controls').innerHTML = `<div class="xp-seg" role="group" aria-label="Time window">@@ -105,6 +127,21 @@ function renderControls() {});}+// How much of the fleet has traded its way into extra freedom. An arm at trusted+// or above gets wider tuning bounds, more of the fleet budget, and a richer+// evidence pack in front of its judge; one on probation gets held tighter.+function earnedTile(experiments) {+ const count = (tier) => experiments.filter((x) => x.autonomy_tier === tier).length;+ const earned = count('trusted') + count('autonomous');+ const probation = count('probation');+ return `+ <div class="cv-card xp-tile" title="Tiers are recomputed from each arm's own realized record every optimizer run — freedom is continuously earned, never granted once.">+ <span>Earned autonomy</span>+ <b class="${earned > 0 ? 'xp-pos' : ''}">${earned} earned</b>+ <i>${probation} on probation · ${experiments.length - earned - probation} standard</i>+ </div>`;+}+function renderSummary(experiments, masterWallet) {const active = experiments.filter((x) => x.enabled);const traded = experiments.filter((x) => x.closed > 0);@@ -126,6 +163,7 @@ function renderSummary(experiments, masterWallet) {<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>Fleet SOL on hand</span><b>${fleetSol.toFixed(3)} SOL</b><i>across ${experiments.filter((x) => x.wallet_address).length} wallets</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>+ ${earnedTile(experiments)}${masterTile}</div>`;}@@ -148,11 +186,11 @@ function renderBoard(experiments) {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-label">${esc(x.label)}${x.enabled ? '' : ' <span class="xp-paused">paused</span>'}${tierBadge(x)}</div><div class="xp-agent"><a href="/a/${esc(x.agent_id)}">${esc(x.agent_name || 'agent')}</a> ${modeBadge(x)} · <a href="${esc(x.ledger_url)}" title="Full decision-by-decision reasoning ledger, tamper-evident and on-chain anchored">ledger →</a></div>${walletLine(x)}</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 class="xp-cond">${esc(x.conditions)}<div class="xp-cond-sub">${esc(String(x.per_trade_sol ?? '·'))} SOL/trade · ${esc(exitLine(x))}</div></td><td>${esc(record)}${x.open > 0 ? ` <span class="xp-open">+${x.open} open</span>` : ''}${paper}</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>diff --git a/tests/sniper-autonomy.test.js b/tests/sniper-autonomy.test.jsnew file mode 100644index 000000000..9b3e13d6b--- /dev/null+++ b/tests/sniper-autonomy.test.js@@ -0,0 +1,203 @@+/**+ * Earned autonomy: an arm's realized record decides how much rope it gets.+ *+ * These lock in the policy that matters when real money is behind it:+ * - profit earns freedom, and a flat/noise record does not,+ * - a bleeding arm is demoted, not merely left alone,+ * - the tier is symmetric: it can be lost as easily as it is gained,+ * - higher tiers only ever WIDEN bounds and unlock fields, never narrow them,+ * - no tier can remove the stop-loss or reach a safety rail.+ */++import { describe, expect, it } from 'vitest';+import {+ GATES,+ MIN_EDGE_PCT,+ TIER_ORDER,+ atLeast,+ boundsFor,+ budgetWeightFor,+ classifyAutonomy,+ describeTier,+ knowledgeFor,+ stepsFor,+ unsetOkFor,+ writableFor,+} from '../api/_lib/sniper-autonomy.js';++const record = (over) => ({ closed: 20, wins: 8, netPnlLamports: 5_000_000, avgPnlPct: 2, ...over });++describe('classifyAutonomy', () => {+ it('promotes a profitable arm with a real sample to trusted', () => {+ const r = classifyAutonomy(record({ closed: 33, wins: 12, netPnlLamports: 2_671_000, avgPnlPct: 0.81 }));+ expect(r.tier).toBe('trusted');+ expect(r.evidence.closed).toBe(33);+ expect(r.reason).toMatch(/profitable/i);+ });++ it('does not promote on a win rate alone when the arm loses money', () => {+ // 60% of trades win but the losers are bigger: this is not an edge.+ const r = classifyAutonomy(record({ closed: 62, wins: 37, netPnlLamports: -20_105_000, avgPnlPct: -3.24 }));+ expect(r.tier).toBe('probation');+ });++ it('promotes a low-hit-rate arm that is genuinely profitable', () => {+ // The case the win-rate-only view gets wrong: rare but large winners. A 16%+ // hit rate would look like a failing arm; the P&L says it is the best one.+ const r = classifyAutonomy(record({ closed: 45, wins: 7, netPnlLamports: 90_000_000, avgPnlPct: 12 }));+ expect(r.tier).toBe('autonomous');+ expect(r.evidence.win_rate_pct).toBeLessThan(20);+ });++ it('treats a noise-level edge as no edge', () => {+ const r = classifyAutonomy(record({ closed: 40, wins: 10, netPnlLamports: 81_000, avgPnlPct: 0.04 }));+ expect(r.tier).toBe('standard');+ expect(r.reason).toMatch(/no decisive edge/i);+ });++ it('holds back on an insufficient sample regardless of the numbers', () => {+ const hot = classifyAutonomy(record({ closed: 3, wins: 3, netPnlLamports: 500_000_000, avgPnlPct: 400 }));+ expect(hot.tier).toBe('standard');+ const cold = classifyAutonomy(record({ closed: 6, wins: 0, netPnlLamports: -40_000_000, avgPnlPct: -60 }));+ expect(cold.tier).toBe('standard');+ });++ it('demotes a proven bleed to probation', () => {+ const r = classifyAutonomy(record({ closed: 30, wins: 1, netPnlLamports: -23_442_000, avgPnlPct: -13 }));+ expect(r.tier).toBe('probation');+ expect(r.reason).toMatch(/bleed/i);+ });++ it('is symmetric: the same arm loses its tier when the record turns', () => {+ const good = { closed: 50, wins: 20, netPnlLamports: 60_000_000, avgPnlPct: 8 };+ expect(classifyAutonomy(good).tier).toBe('autonomous');+ // Same sample size, record has gone negative.+ expect(classifyAutonomy({ ...good, netPnlLamports: -60_000_000, avgPnlPct: -8 }).tier).toBe('probation');+ });++ it('requires the autonomous gate on both sample and edge', () => {+ // Enough edge, not enough sample → trusted, not autonomous.+ expect(classifyAutonomy(record({ closed: GATES.autonomous.closed - 1, netPnlLamports: 9e7, avgPnlPct: 20 })).tier).toBe('trusted');+ // Enough sample, edge below the autonomous bar → trusted.+ expect(classifyAutonomy(record({ closed: GATES.autonomous.closed + 10, netPnlLamports: 9e6, avgPnlPct: 2 })).tier).toBe('trusted');+ });++ it('never throws on missing or malformed input', () => {+ expect(classifyAutonomy(undefined).tier).toBe('standard');+ expect(classifyAutonomy({}).tier).toBe('standard');+ expect(classifyAutonomy({ closed: 'x', netPnlLamports: null, avgPnlPct: NaN }).tier).toBe('standard');+ });++ it('reports evidence a human can check', () => {+ const r = classifyAutonomy(record({ closed: 20, wins: 5, netPnlLamports: 1e9, avgPnlPct: 6 }));+ expect(r.evidence).toMatchObject({ closed: 20, wins: 5, net_pnl_sol: 1, win_rate_pct: 25 });+ });+});++describe('tier grants', () => {+ it('only ever widens as the tier rises', () => {+ const fields = ['take_profit_pct', 'trailing_stop_pct', 'max_hold_seconds', 'per_trade_lamports'];+ for (let i = 1; i < TIER_ORDER.length; i++) {+ const lower = boundsFor(TIER_ORDER[i - 1]);+ const higher = boundsFor(TIER_ORDER[i]);+ for (const f of fields) {+ expect(higher[f].max, `${TIER_ORDER[i]}.${f}.max`).toBeGreaterThanOrEqual(lower[f].max);+ expect(higher[f].min, `${TIER_ORDER[i]}.${f}.min`).toBeLessThanOrEqual(lower[f].min);+ }+ }+ });++ it('keeps a hard stop-loss at every tier, including the most autonomous', () => {+ for (const tier of TIER_ORDER) {+ const b = boundsFor(tier).stop_loss_pct;+ expect(b).toBeTruthy();+ expect(b.min).toBeGreaterThan(0); // a 0% stop would be no stop+ expect(b.max).toBeLessThanOrEqual(65); // and it can never widen to "never sell"+ }+ });++ it('never exposes a safety rail as writable at any tier', () => {+ // These are enforced in executeBuy and must stay out of every loop's reach.+ const rails = [+ 'max_concurrent_positions', 'firewall_level', 'max_price_impact_pct',+ 'daily_budget_lamports', 'kill_switch', 'enabled', 'slippage_bps',+ ];+ for (const tier of TIER_ORDER) {+ const writable = writableFor(tier);+ for (const rail of rails) expect(writable.has(rail), `${tier} must not write ${rail}`).toBe(false);+ }+ });++ it('unlocks the exploration fields only once an arm is trusted', () => {+ const earnedOnly = ['llm_min_confidence', 'min_market_cap_usd', 'max_market_cap_usd', 'initials_out_multiple'];+ for (const f of earnedOnly) {+ expect(writableFor('probation').has(f)).toBe(false);+ expect(writableFor('standard').has(f)).toBe(false);+ expect(writableFor('trusted').has(f)).toBe(true);+ expect(writableFor('autonomous').has(f)).toBe(true);+ }+ });++ it('lets any tier set a missing trailing stop, since that only protects', () => {+ for (const tier of TIER_ORDER) expect(unsetOkFor(tier).has('trailing_stop_pct')).toBe(true);+ });++ it('lets only an earned arm switch the ladder on from unset', () => {+ expect(unsetOkFor('standard').has('initials_out_multiple')).toBe(false);+ expect(unsetOkFor('trusted').has('initials_out_multiple')).toBe(true);+ });++ it('scales steps and budget weight monotonically with tier', () => {+ const base = { take_profit_pct: 15, per_trade_fraction: 0.2 };+ let prevStep = 0;+ let prevWeight = 0;+ for (const tier of TIER_ORDER) {+ const step = stepsFor(tier, base).take_profit_pct;+ expect(step).toBeGreaterThan(prevStep);+ prevStep = step;+ const w = budgetWeightFor(tier);+ expect(w).toBeGreaterThan(prevWeight);+ prevWeight = w;+ }+ });++ it('keeps a scaled size step a sane fraction', () => {+ for (const tier of TIER_ORDER) {+ const f = stepsFor(tier, { per_trade_fraction: 0.2 }).per_trade_fraction;+ expect(f).toBeGreaterThan(0);+ expect(f).toBeLessThanOrEqual(0.75);+ }+ });++ it('deepens the knowledge pack only for earned tiers', () => {+ expect(knowledgeFor('probation')).toBe('base');+ expect(knowledgeFor('standard')).toBe('base');+ expect(knowledgeFor('trusted')).toBe('informed');+ expect(knowledgeFor('autonomous')).toBe('full');+ });++ it('falls back to standard for an unknown tier rather than guessing', () => {+ expect(boundsFor('bogus')).toEqual(boundsFor('standard'));+ expect(writableFor(undefined)).toEqual(writableFor('standard'));+ expect(budgetWeightFor(null)).toBe(budgetWeightFor('standard'));+ expect(knowledgeFor('')).toBe('base');+ });++ it('orders tiers correctly', () => {+ expect(atLeast('trusted', 'autonomous')).toBe(true);+ expect(atLeast('trusted', 'trusted')).toBe(true);+ expect(atLeast('trusted', 'standard')).toBe(false);+ expect(atLeast('trusted', 'probation')).toBe(false);+ });++ it('describes every tier', () => {+ for (const tier of TIER_ORDER) expect(describeTier(tier)).toBeTruthy();+ });++ it('treats the edge floor as the profit/noise boundary', () => {+ const justUnder = classifyAutonomy(record({ closed: 20, netPnlLamports: 1, avgPnlPct: MIN_EDGE_PCT - 0.01 }));+ const justOver = classifyAutonomy(record({ closed: 20, netPnlLamports: 1, avgPnlPct: MIN_EDGE_PCT }));+ expect(justUnder.tier).toBe('standard');+ expect(justOver.tier).toBe('trusted');+ });+});diff --git a/tests/sniper-judge-knowledge.test.js b/tests/sniper-judge-knowledge.test.jsnew file mode 100644index 000000000..aeb748285--- /dev/null+++ b/tests/sniper-judge-knowledge.test.js@@ -0,0 +1,68 @@+/**+ * The judge's earned knowledge pack: bucket selection.+ *+ * The conditional win-rate table can carry dozens of near-baseline rows. Handing+ * all of them to a model teaches it nothing and costs tokens; the pack must+ * surface the buckets that actually diverge from the baseline, in both+ * directions, since "this bucket loses badly" is as actionable as the reverse.+ */++import { describe, expect, it } from 'vitest';+import { topBuckets } from '../workers/agent-sniper/judge-knowledge.js';++const table = {+ bundle_score: {+ clean: { win_rate: 0.31, count: 400, baseline_win_rate: 0.12 }, // +19pt+ high: { win_rate: 0.02, count: 250, baseline_win_rate: 0.12 }, // -10pt+ medium: { win_rate: 0.13, count: 180, baseline_win_rate: 0.12 }, // +1pt+ },+ unique_buyers: {+ '>=50': { win_rate: 0.44, count: 90, baseline_win_rate: 0.12 }, // +32pt+ '<5': { win_rate: 0.11, count: 900, baseline_win_rate: 0.12 }, // -1pt+ },+};++describe('topBuckets', () => {+ it('ranks by absolute divergence from the baseline', () => {+ const top = topBuckets(table, 3);+ expect(top.map((b) => b.bucket)).toEqual(['>=50', 'clean', 'high']);+ });++ it('keeps strongly negative buckets, not just winners', () => {+ const top = topBuckets(table, 3);+ const negative = top.find((b) => b.bucket === 'high');+ expect(negative).toBeTruthy();+ expect(negative.lift).toBeLessThan(0);+ });++ it('honours the limit', () => {+ expect(topBuckets(table, 2)).toHaveLength(2);+ expect(topBuckets(table, 99)).toHaveLength(5);+ });++ it('carries the sample count so the model can weigh the evidence', () => {+ const [best] = topBuckets(table, 1);+ expect(best).toMatchObject({ signal: 'unique_buyers', bucket: '>=50', count: 90 });+ });++ it('drops malformed rows instead of emitting NaN into a prompt', () => {+ const dirty = {+ ok: { a: { win_rate: 0.5, count: 10, baseline_win_rate: 0.1 } },+ bad: {+ noCount: { win_rate: 0.9, count: 0, baseline_win_rate: 0.1 },+ noRate: { win_rate: null, count: 10, baseline_win_rate: 0.1 },+ garbage: { win_rate: 'x', count: 'y', baseline_win_rate: 'z' },+ },+ };+ const out = topBuckets(dirty);+ expect(out).toHaveLength(1);+ expect(out[0].signal).toBe('ok');+ });++ it('returns nothing rather than throwing on absent input', () => {+ expect(topBuckets(null)).toEqual([]);+ expect(topBuckets(undefined)).toEqual([]);+ expect(topBuckets({})).toEqual([]);+ expect(topBuckets('not an object')).toEqual([]);+ });+});diff --git a/tests/sniper-optimizer.test.js b/tests/sniper-optimizer.test.jsindex a9356a32f..89b13564f 100644--- a/tests/sniper-optimizer.test.js+++ b/tests/sniper-optimizer.test.js@@ -12,6 +12,9 @@import { describe, it, expect } from 'vitest';import { proposeAdjustments, bestOracleThreshold, MIN_SAMPLE, BOUNDS, STEP } from '../api/_lib/sniper-optimizer.js';+import { boundsFor } from '../api/_lib/sniper-autonomy.js';++const BOUNDS_TRUSTED = boundsFor('trusted');const baseConfig = {decision_mode: 'rules',@@ -106,6 +109,129 @@ describe('proposeAdjustments', () => {});});+describe('earned autonomy: the optimizer scales with the arm', () => {+ // A profitable arm: net positive, real sample, winners that run past the average+ // exit. This is the record that buys extra freedom.+ const profitable = stats({+ closed: 33, wins: 12, winRate: 36, avgPnlPct: 6, bestPnlPct: 71,+ netPnlLamports: 2_671_000, exitReasons: { trailing_stop: 12, timeout: 11, stop_loss: 10 },+ });++ it('defaults to standard behaviour when no tier is passed', () => {+ const untiered = proposeAdjustments(profitable, baseConfig);+ const standard = proposeAdjustments(profitable, baseConfig, { tier: 'standard' });+ expect(untiered.proposals).toEqual(standard.proposals);+ expect(untiered.tier).toBe('standard');+ });++ it('refuses to touch an unlocked field for an arm that has not earned it', () => {+ const config = { ...baseConfig, decision_mode: 'llm', llm_min_confidence: 0.65, min_market_cap_usd: 10_000 };+ for (const tier of ['standard', 'probation']) {+ const r = proposeAdjustments(profitable, config, { tier });+ expect(r.proposals.find((p) => p.field === 'llm_min_confidence')).toBeFalsy();+ expect(r.proposals.find((p) => p.field === 'min_market_cap_usd')).toBeFalsy();+ expect(r.proposals.find((p) => p.field === 'initials_out_multiple')).toBeFalsy();+ }+ });++ it('lowers a profitable LLM arm’s confidence floor so it takes more shots', () => {+ const r = proposeAdjustments(+ profitable,+ { ...baseConfig, decision_mode: 'llm', llm_min_confidence: 0.65 },+ { tier: 'trusted' },+ );+ const conf = r.proposals.find((p) => p.field === 'llm_min_confidence');+ expect(conf).toBeTruthy();+ expect(conf.to).toBeLessThan(0.65);+ expect(conf.to).toBeGreaterThanOrEqual(BOUNDS_TRUSTED.llm_min_confidence.min);+ // Float dust must never reach the DB.+ expect(String(conf.to)).toMatch(/^0\.\d{1,2}$/);+ });++ it('widens a profitable arm’s market-cap band outward on both sides', () => {+ const r = proposeAdjustments(+ profitable,+ { ...baseConfig, min_market_cap_usd: 10_000, max_market_cap_usd: 100_000 },+ { tier: 'trusted' },+ );+ const lo = r.proposals.find((p) => p.field === 'min_market_cap_usd');+ const hi = r.proposals.find((p) => p.field === 'max_market_cap_usd');+ expect(lo.to).toBeLessThan(10_000);+ expect(hi.to).toBeGreaterThan(100_000);+ });++ it('never narrows the universe of an arm with no band set', () => {+ const r = proposeAdjustments(profitable, { ...baseConfig, min_market_cap_usd: null, max_market_cap_usd: null }, { tier: 'trusted' });+ expect(r.proposals.find((p) => p.field === 'min_market_cap_usd')).toBeFalsy();+ expect(r.proposals.find((p) => p.field === 'max_market_cap_usd')).toBeFalsy();+ });++ it('turns the take-initials ladder on for an earned arm whose winners run', () => {+ const r = proposeAdjustments(profitable, { ...baseConfig, initials_out_multiple: null }, { tier: 'trusted' });+ const ladder = r.proposals.find((p) => p.field === 'initials_out_multiple');+ expect(ladder).toBeTruthy();+ expect(ladder.from).toBe(null);+ expect(ladder.to).toBe(2);+ expect(r.notes).toContain('ladder_enabled');+ });++ it('scales a net-profitable arm up even at a low win rate', () => {+ // 36% hit rate: Rule D's win-rate path never fires, the profit path must.+ const r = proposeAdjustments(profitable, baseConfig, { tier: 'trusted' });+ const size = r.proposals.find((p) => p.field === 'per_trade_lamports');+ expect(size).toBeTruthy();+ expect(size.to).toBeGreaterThan(baseConfig.per_trade_lamports);+ expect(size.reason).toMatch(/does not need a high hit rate/);+ });++ it('still de-risks a losing arm at every tier, including the top one', () => {+ const bleeding = stats({+ closed: 30, wins: 1, winRate: 3, avgPnlPct: -13, netPnlLamports: -23_442_000,+ exitReasons: { stop_loss: 24, timeout: 6 },+ });+ for (const tier of ['probation', 'standard', 'trusted', 'autonomous']) {+ const r = proposeAdjustments(bleeding, baseConfig, { tier });+ const size = r.proposals.find((p) => p.field === 'per_trade_lamports');+ expect(size, `${tier} must cut size on a bleeding arm`).toBeTruthy();+ expect(size.to).toBeLessThan(baseConfig.per_trade_lamports);+ // A losing arm never gets a freedom proposal, whatever tier it holds.+ expect(r.proposals.find((p) => p.field === 'llm_min_confidence')).toBeFalsy();+ expect(r.proposals.find((p) => p.field === 'initials_out_multiple')).toBeFalsy();+ }+ });++ it('clamps every proposal to the acting tier’s bounds', () => {+ for (const tier of ['probation', 'standard', 'trusted', 'autonomous']) {+ const r = proposeAdjustments(+ profitable,+ { ...baseConfig, decision_mode: 'llm', llm_min_confidence: 0.4, min_market_cap_usd: 2_000, per_trade_lamports: 190_000_000 },+ { tier },+ );+ const b = boundsFor(tier);+ for (const p of r.proposals) {+ expect(p.to, `${tier}.${p.field}`).toBeGreaterThanOrEqual(b[p.field].min);+ expect(p.to, `${tier}.${p.field}`).toBeLessThanOrEqual(b[p.field].max);+ }+ }+ });++ it('holds a probation arm to a smaller step than a standard one', () => {+ const heavy = stats({+ closed: 20, wins: 4, winRate: 20, avgPnlPct: -9, netPnlLamports: -30_000_000,+ exitReasons: { stop_loss: 14, timeout: 6 },+ });+ const config = { ...baseConfig, min_quality_score: 40 };+ const onProbation = proposeAdjustments(heavy, config, { tier: 'probation' });+ const onStandard = proposeAdjustments(heavy, config, { tier: 'standard' });+ const q = (r) => r.proposals.find((p) => p.field === 'min_quality_score')?.to;+ expect(q(onProbation) - 40).toBeLessThan(q(onStandard) - 40);+ });++ it('reports the tier it acted under', () => {+ expect(proposeAdjustments(profitable, baseConfig, { tier: 'autonomous' }).tier).toBe('autonomous');+ });+});+describe('bestOracleThreshold (Bridge 2)', () => {it('finds the conviction floor where wins concentrate', () => {// Low-conviction coins mostly lose; >=70 mostly win.diff --git a/workers/agent-sniper/judge-knowledge.js b/workers/agent-sniper/judge-knowledge.jsnew file mode 100644index 000000000..f0c06a33e--- /dev/null+++ b/workers/agent-sniper/judge-knowledge.js@@ -0,0 +1,265 @@+// What the LLM judge is allowed to know, scaled by what the arm has earned.+//+// The judge used to see one thing: the launch in front of it. Name, socials,+// creator history, market cap, and the market-realness read. That is the same+// context whether the arm has been printing for a month or has never closed a+// profitable trade, which means a proven arm was being asked to decide with its+// hands tied to the same information as a failing one.+//+// This module builds the extra context an earned arm gets, straight out of the+// tables the fleet already fills:+//+// informed (trusted tier)+// • the ground-truth base rate: what fraction of launches actually win, so+// the model knows how skeptical the prior should be.+// • the learned signal weights (pump_intel_weights), retrained every 15 min+// from labeled outcomes: which launch-time signals correlate with wins.+// • the arm's OWN realized record: how many trades, what it won and lost,+// and what its winners actually looked like.+//+// full (autonomous tier)+// • the conditional win-rate table: per signal bucket, the realized win rate+// versus the baseline. This is the "what actually works" evidence, not a+// correlation coefficient the model has to interpret.+// • the model's own calibration: how its past buy calls on this network+// actually turned out, so it can correct its own bias.+//+// Everything here is read from real rows. When a table is empty or the DB is+// unreachable the pack degrades to a shorter block or to nothing at all, and the+// judge falls back to exactly the prompt it used before. There is no synthetic+// or placeholder knowledge anywhere in this file: an arm is told what is true or+// it is told nothing.++import { sql } from '../../api/_lib/db.js';+import { classifyAutonomy, knowledgeFor } from '../../api/_lib/sniper-autonomy.js';+import { log } from './log.js';++const FLEET_TTL_MS = 5 * 60_000; // base rate + weights: fleet-wide, changes slowly+const ARM_TTL_MS = 5 * 60_000; // per-arm record: cheap query, still worth caching++let _fleet = null;+let _fleetAt = 0;+const _arms = new Map(); // strategyId → { value, ts }+const _calibration = new Map(); // model → { value, ts }++/** Ground-truth base rate + the latest trained weights and win-rate table. */+async function fleetKnowledge(network) {+ if (_fleet && Date.now() - _fleetAt < FLEET_TTL_MS) return _fleet;+ try {+ const [[rate], [trained]] = await Promise.all([+ sql`+ select+ count(*) filter (where outcome in ('pumped','graduated'))::float+ / nullif(count(*), 0) as base_rate,+ count(*) as labeled+ from pump_coin_outcomes+ `,+ sql`+ select weights, sample_size, conditional_win_rates+ from pump_intel_weights+ where network = ${network}+ order by trained_at desc limit 1+ `,+ ]);+ _fleet = {+ baseRate: rate?.base_rate != null ? Number(rate.base_rate) : null,+ labeled: Number(rate?.labeled) || 0,+ weights: trained?.weights || null,+ sampleSize: Number(trained?.sample_size) || 0,+ conditional: trained?.conditional_win_rates || null,+ };+ _fleetAt = Date.now();+ return _fleet;+ } catch (err) {+ log.warn('judge knowledge: fleet read failed', { err: err?.message });+ return null;+ }+}++/**+ * One arm's own realized record, and the tier it earns. Real fills only: paper+ * trades teach the fleet but they are not this arm's money and do not buy it rope.+ */+export async function armRecord(strategyId, network) {+ const cached = _arms.get(strategyId);+ if (cached && Date.now() - cached.ts < ARM_TTL_MS) return cached.value;+ try {+ const [row] = await sql`+ select+ count(*) as closed,+ count(*) filter (where realized_pnl_lamports > 0) as wins,+ coalesce(sum(realized_pnl_lamports), 0) as net_lamports,+ coalesce(avg(realized_pnl_pct), 0) as avg_pct,+ max(realized_pnl_pct) as best_pct,+ min(realized_pnl_pct) as worst_pct,+ coalesce(avg(extract(epoch from (closed_at - opened_at))), 0) as avg_hold_s+ from agent_sniper_positions+ where strategy_id = ${strategyId} and network = ${network}+ and status = 'closed' and buy_sig <> 'SIMULATED'+ `;+ const record = {+ closed: Number(row?.closed) || 0,+ wins: Number(row?.wins) || 0,+ netPnlLamports: Number(row?.net_lamports) || 0,+ avgPnlPct: Number(row?.avg_pct) || 0,+ bestPnlPct: row?.best_pct != null ? Number(row.best_pct) : null,+ worstPnlPct: row?.worst_pct != null ? Number(row.worst_pct) : null,+ avgHoldSeconds: Math.round(Number(row?.avg_hold_s) || 0),+ };+ const value = { record, autonomy: classifyAutonomy(record) };+ _arms.set(strategyId, { value, ts: Date.now() });+ return value;+ } catch (err) {+ log.warn('judge knowledge: arm record read failed', { strategyId, err: err?.message });+ return null;+ }+}++/**+ * How this model's own past calls actually turned out. Buy verdicts scored+ * against the labeled outcome of the coin they were made on: the counterfactual+ * a trade record cannot capture, because it also covers the ones it skipped.+ */+async function modelCalibration(model, network) {+ const cached = _calibration.get(model);+ if (cached && Date.now() - cached.ts < FLEET_TTL_MS) return cached.value;+ try {+ const [row] = await sql`+ select+ count(*) filter (where v.buy) as buy_calls,+ count(*) filter (where v.buy and o.outcome in ('pumped','graduated')) as buy_right,+ count(*) filter (where not v.buy) as skip_calls,+ count(*) filter (where not v.buy and o.outcome in ('pumped','graduated')) as skip_wrong+ from sniper_llm_verdicts v+ join pump_coin_outcomes o on o.mint = v.mint+ where v.model = ${model} and v.network = ${network} and o.outcome <> 'unknown'+ `;+ const value = {+ buyCalls: Number(row?.buy_calls) || 0,+ buyRight: Number(row?.buy_right) || 0,+ skipCalls: Number(row?.skip_calls) || 0,+ skipWrong: Number(row?.skip_wrong) || 0,+ };+ _calibration.set(model, { value, ts: Date.now() });+ return value;+ } catch (err) {+ log.warn('judge knowledge: calibration read failed', { model, err: err?.message });+ return null;+ }+}++/**+ * Pick the most informative buckets out of the conditional win-rate table: the+ * ones whose realized win rate diverges most from the baseline. A model handed+ * forty near-baseline rows learns nothing; handed the eight that actually move+ * the needle, it can act on them.+ *+ * Pure, exported for tests.+ */+export function topBuckets(conditional, limit = 8) {+ if (!conditional || typeof conditional !== 'object') return [];+ const rows = [];+ for (const [signal, buckets] of Object.entries(conditional)) {+ if (!buckets || typeof buckets !== 'object') continue;+ for (const [bucket, stat] of Object.entries(buckets)) {+ // Number(null) is 0, not NaN: without the explicit null check a missing+ // win rate would render as a confident "0%" in the prompt. The judge is+ // told what is true or it is told nothing.+ if (stat?.win_rate == null || stat?.baseline_win_rate == null) continue;+ const rate = Number(stat.win_rate);+ const baseline = Number(stat.baseline_win_rate);+ const count = Number(stat.count) || 0;+ if (!Number.isFinite(rate) || !Number.isFinite(baseline) || !count) continue;+ rows.push({ signal, bucket, rate, baseline, count, lift: rate - baseline });+ }+ }+ rows.sort((a, b) => Math.abs(b.lift) - Math.abs(a.lift));+ return rows.slice(0, limit);+}++const pct = (n) => `${(n * 100).toFixed(0)}%`;++/**+ * Build the extra context block for one arm's judge call.+ *+ * @param {{ strategyId:string, network:string, model:string }} arm+ * @returns {Promise<{ tier:string, depth:string, block:string }>}+ * `block` is '' when the arm has earned no extra context or no real data+ * exists yet, in which case the judge prompt is unchanged from its original.+ */+export async function buildKnowledgePack({ strategyId, network = 'mainnet', model }) {+ const armed = strategyId ? await armRecord(strategyId, network) : null;+ const tier = armed?.autonomy?.tier || 'standard';+ const depth = knowledgeFor(tier);+ if (depth === 'base') return { tier, depth, block: '' };++ const fleet = await fleetKnowledge(network);+ const lines = [];++ if (fleet?.baseRate != null && fleet.labeled > 0) {+ lines.push(+ `BASE RATE: ${pct(fleet.baseRate)} of ${fleet.labeled.toLocaleString('en-US')} labeled launches actually went on to pump or graduate. ` ++ `Most launches fail; a verdict that would buy far more than ${pct(fleet.baseRate)} of what it sees is miscalibrated.`,+ );+ }++ const r = armed?.record;+ if (r && r.closed > 0) {+ const wr = Math.round((r.wins / r.closed) * 100);+ const net = (r.netPnlLamports / 1e9).toFixed(4);+ lines.push(+ `YOUR OWN RECORD ON THIS ARM: ${r.closed} closed trades, ${r.wins} winners (${wr}% hit rate), ` ++ `net ${net} SOL, average ${r.avgPnlPct >= 0 ? '+' : ''}${r.avgPnlPct.toFixed(1)}% per trade` ++ (r.bestPnlPct != null ? `, best +${r.bestPnlPct.toFixed(0)}%` : '') ++ (r.worstPnlPct != null ? `, worst ${r.worstPnlPct.toFixed(0)}%` : '') ++ (r.avgHoldSeconds ? `, average hold ${Math.round(r.avgHoldSeconds / 60)} min` : '') + '. ' ++ `This is the record that earned you the extra context below. A low hit rate is fine if the winners pay for the losers.`,+ );+ }++ if (fleet?.weights && fleet.sampleSize > 0) {+ const ranked = Object.entries(fleet.weights)+ .filter(([, w]) => Number.isFinite(Number(w)))+ .sort((a, b) => Math.abs(Number(b[1])) - Math.abs(Number(a[1])))+ .slice(0, 8)+ .map(([k, w]) => `${k} ${Number(w) >= 0 ? '+' : ''}${Number(w).toFixed(3)}`);+ if (ranked.length) {+ lines.push(+ `LEARNED SIGNAL WEIGHTS (correlation with a winning outcome, trained on ${fleet.sampleSize.toLocaleString('en-US')} labeled launches): ` ++ `${ranked.join(', ')}. Positive means the signal tracks winners, negative means it tracks losers.`,+ );+ }+ }++ if (depth === 'full') {+ const buckets = topBuckets(fleet?.conditional);+ if (buckets.length) {+ lines.push(+ 'REALIZED WIN RATES BY SIGNAL BUCKET (what actually happened, not a correlation): ' ++ buckets.map((b) => `${b.signal}=${b.bucket} → ${pct(b.rate)} vs ${pct(b.baseline)} baseline (n=${b.count})`).join('; ') + '.',+ );+ }+ const cal = model ? await modelCalibration(model, network) : null;+ if (cal && (cal.buyCalls > 0 || cal.skipCalls > 0)) {+ const parts = [];+ if (cal.buyCalls > 0) parts.push(`of your ${cal.buyCalls} past BUY calls, ${cal.buyRight} (${pct(cal.buyRight / cal.buyCalls)}) landed on a coin that pumped or graduated`);+ if (cal.skipCalls > 0) parts.push(`of your ${cal.skipCalls} past SKIP calls, ${cal.skipWrong} (${pct(cal.skipWrong / cal.skipCalls)}) were on coins that went on to win anyway`);+ lines.push(`YOUR OWN CALIBRATION: ${parts.join('; ')}. Correct for your own bias.`);+ }+ }++ if (!lines.length) return { tier, depth, block: '' };+ return {+ tier,+ depth,+ block: `\n\nEARNED CONTEXT (this arm's track record has unlocked the evidence below; use it):\n${lines.map((l) => `- ${l}`).join('\n')}`,+ };+}++/** Test seam: drop every cache. */+export function _resetKnowledgeCache() {+ _fleet = null;+ _fleetAt = 0;+ _arms.clear();+ _calibration.clear();+}diff --git a/workers/agent-sniper/llm-judge.js b/workers/agent-sniper/llm-judge.jsindex ce04cdd90..7dfa64d2b 100644--- a/workers/agent-sniper/llm-judge.js+++ b/workers/agent-sniper/llm-judge.js@@ -9,8 +9,17 @@// every mode: Mayhem exclusion, the trade firewall's real buy→sell round-trip,// budgets, concurrency, SOL headroom, and the shared spend policy.//+// Earned context: an arm that has proven it makes money is handed more to decide+// with (the ground-truth base rate, the learned signal weights, its own realized+// record, and at the top tier the realized win-rate table and the model's own+// calibration). See judge-knowledge.js. An arm that has not earned it sees+// exactly the prompt this file has always sent.+//// Cost + latency control:-// • One verdict per (mint, model), agents sharing a model share the call.+// • One verdict per (mint, model, knowledge depth). Arms at base depth still+// share a single call across a same-model fleet exactly as before; an arm+// with earned context is asking a different question, so it pays for its own+// call. That extra cost is the tier's, and only a profitable arm has one.// • 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@@ -21,6 +30,7 @@ import { log } from './log.js';import { sql } from '../../api/_lib/db.js';import { llmComplete } from '../../api/_lib/llm.js';import { assessMarketRealness } from '../../api/_lib/market-realness.js';+import { buildKnowledgePack } from './judge-knowledge.js';const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';@@ -49,7 +59,7 @@ const SYSTEM_PROMPT = ['{"buy": true|false, "confidence": <0..1>, "thesis": "<one short sentence>"}',].join(' ');-function launchBrief(mint) {+function launchBrief(mint, knowledge = '') {const fields = {symbol: mint.symbol || null,name: mint.name || null,@@ -79,7 +89,7 @@ function launchBrief(mint) {if (m.painted) lines.push('WARNING: this matches a painted-stairstep pattern (a rise with no real two-sided market), which historically wins far below the base rate.');}}- return `New pump.fun launch:\n${lines.join('\n')}`;+ return `New pump.fun launch:\n${lines.join('\n')}${knowledge}`;}// Parse the model's reply into a verdict. Tolerates fences/prose around the@@ -135,8 +145,8 @@ async function askOpenRouter({ model, user }) {}}-async function judge(mint, model) {- const user = launchBrief(mint);+async function judge(mint, model, knowledge = '') {+ const user = launchBrief(mint, knowledge);const t0 = Date.now();try {const text = await askOpenRouter({ model, user });@@ -176,7 +186,21 @@ function recordVerdict({ mint, network, requestedModel, verdict }) {*/export async function judgeLaunch(mint, strat) {const model = strat.llm_model || 'openrouter/auto';- const key = `${mint.mint}:${model}`;+ const network = strat.network || 'mainnet';++ // What this arm has earned the right to know. A read failure or an arm with no+ // record yields an empty block, and the call proceeds on the original prompt.+ const pack = await buildKnowledgePack({ strategyId: strat.id, network, model })+ .catch((err) => {+ log.warn('knowledge pack failed, judging on the base brief', { mint: mint.mint, model, err: err?.message });+ return { tier: 'standard', depth: 'base', block: '' };+ });++ // Arms at base depth share one call per (mint, model) exactly as before. An arm+ // with earned context is asking a materially different question, so it keys on+ // its own strategy and pays for its own call.+ const scope = pack.block ? `${pack.depth}:${strat.id}` : 'base';+ const key = `${mint.mint}:${model}:${scope}`;const cached = _verdicts.get(key);if (cached && Date.now() - cached.ts < VERDICT_TTL_MS) return cached.promise;@@ -185,9 +209,16 @@ export async function judgeLaunch(mint, strat) {return null;}_active++;- const promise = judge(mint, model)+ const promise = judge(mint, model, pack.block).then((verdict) => {- if (verdict) recordVerdict({ mint: mint.mint, network: strat.network || 'mainnet', requestedModel: model, verdict });+ if (verdict) {+ recordVerdict({ mint: mint.mint, network, requestedModel: model, verdict });+ if (pack.block) {+ log.info('llm judge ruled with earned context', {+ mint: mint.mint, model, tier: pack.tier, knowledge: pack.depth, buy: verdict.buy, confidence: verdict.confidence,+ });+ }+ }return verdict;}).catch((err) => {