Skip to content

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

Sniper evolution engine: run the portfolio layer autonomously on a cron

nirholas783ec653a699
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 10c811d3f..f745ef6b7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Marketplace: submitting an agent no longer means typing a form** — The Submit Agent flow on /marketplace is now a chooser instead of a wall of text fields. The primary path sends you to the guided agent builder (3D avatar, persona, publish); a second path lists the agents you already have, with drafts publishable in one click right from the dialog; the old manual form and JSON import stay available behind an Advanced toggle. The featured hero is more compact so search and listings are visible without scrolling, the signed-out My Agents view got a proper call to action, and related agents on detail pages now show their 3D thumbnails. (`/marketplace`) `[improvement]`
- **Sniper Experiments: every wallet and every decision, in the open** — The /sniper/experiments scoreboard now shows each strategy's live wallet: its address, a Solscan link, and its real-time SOL balance, plus the shared master wallet that auto-funds the fleet. Every arm also links straight to its Reasoning Ledger, a tamper-evident, on-chain-anchored record of every single buy decision: the exact market data and rationale the agent acted on at entry, and once the trade closes, the real outcome (win or loss, by how much). Nothing is hidden or summarized away; wins and losses are published with the same detail. (`/sniper/experiments`) `[feature, improvement]`
- **Snipers that tune themselves from their own results** — The sniper fleet now has an intra-arm optimizer that learns from each strategy's real trading record and proposes bounded adjustments to its own knobs (take-profit, trailing/stop, hold time, entry-quality, size). It runs in shadow mode by default, recording exactly what it would change without touching anything, and in apply mode only tunes strategies that opted in, logging every change to the agent's tamper-evident reasoning ledger. It pairs with the portfolio evolution engine (which reallocates budget across arms): the optimizer tunes each arm inward, evolution decides which arms get capital. Neither can touch a safety field. (`/docs/agent-sniper`) `[feature]`
+- **The sniper fleet now runs its full self-improvement loop autonomously** — Both halves of the fleet's learning loop now run on their own schedule with no human in the loop. The intra-arm optimizer (every 6h) tunes each strategy's own knobs from its real results, and the portfolio evolution engine (every 12h) reallocates budget toward the arms that actually win and retires the ones that provably don't. Every change is bounded, reversible, and journaled; neither loop can touch a safety field or raise the total spend cap. (`/docs/agent-sniper`) `[feature, infra]`
- **three.ws joins the NVIDIA Inception program** — three.ws LLC has been accepted into NVIDIA Inception, NVIDIA's global program for startups building with accelerated computing. It is a natural home for this platform: every 3D generation lane already runs on NVIDIA GPUs, from the free text-to-3D forge to photo avatars, auto-rigging, and motion capture. Membership opens access to NVIDIA's startup benefits, including GPU capacity, software, and engineering resources, and they will go straight into faster generations and higher-quality avatars. `[infra]`
## 2026-07-20
diff --git a/api/cron/sniper-evolve.js b/api/cron/sniper-evolve.js
new file mode 100644
index 000000000..8ec6174f6
--- /dev/null
+++ b/api/cron/sniper-evolve.js
@@ -0,0 +1,53 @@
+// GET/POST /api/cron/sniper-evolve: the autonomous PORTFOLIO layer of the sniper
+// fleet's self-improvement loop. On a schedule it scores every labeled arm's
+// fitness against the ground-truth base rate (what fraction of launches actually
+// win) and mutates the fleet's ALLOCATION: reallocate the fixed daily budget
+// toward higher-fitness arms, retire an arm proven worse than a coin flip, revive
+// a retired arm after a cooldown to re-test it.
+//
+// It is the complement to the intra-arm optimizer (api/cron/sniper-optimize.js):
+// evolve moves budget/on-off across arms and never touches a per-arm entry/exit
+// knob; the optimizer tunes each arm's knobs inward and never moves budget.
+// Neither can write a safety field. The shared engine lives in
+// scripts/sniper-evolve.mjs (runEvolve), the single source of truth for both the
+// CLI and this cron.
+//
+// Controls:
+// SNIPER_EVOLVE_APPLY = 1 enact mutations (default: dry-run, log only)
+// plus the EVOLVE_* tunables read by runEvolve (fleet budget, floors, samples).
+
+import { error, json, method, wrapCron } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { runEvolve } from '../../scripts/sniper-evolve.mjs';
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }
+ return true;
+}
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const apply = String(process.env.SNIPER_EVOLVE_APPLY || '') === '1';
+ const lines = [];
+ try {
+ const result = await runEvolve({ apply, log: (m) => lines.push(String(m)) });
+ return json(res, 200, {
+ ok: true,
+ mode: apply ? 'apply' : 'dry-run',
+ run_id: result.runId,
+ base_rate: result.baseRate,
+ active_arms: result.activeArms,
+ proposals: result.proposals.map((p) => ({ action: p.action, label: p.label, field: p.field, before: p.before, after: p.after })),
+ applied: result.applied,
+ });
+ } catch (err) {
+ return json(res, 200, { ok: false, error: err.message, log: lines.slice(-8) });
+ }
+});
diff --git a/data/changelog.json b/data/changelog.json
index f1da5bb96..f6395709e 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-21",
+ "title": "The sniper fleet now runs its full self-improvement loop autonomously",
+ "summary": "Both halves of the fleet's learning loop now run on their own schedule with no human in the loop. The intra-arm optimizer (every 6h) tunes each strategy's own knobs from its real results, and the portfolio evolution engine (every 12h) reallocates budget toward the arms that actually win and retires the ones that provably don't. Every change is bounded, reversible, and journaled; neither loop can touch a safety field or raise the total spend cap.",
+ "tags": [
+ "feature",
+ "infra"
+ ],
+ "link": "/docs/agent-sniper"
+ },
{
"date": "2026-07-21",
"title": "Snipers that tune themselves from their own results",
diff --git a/docs/agent-sniper.md b/docs/agent-sniper.md
index 072153737..3c24f267b 100644
--- a/docs/agent-sniper.md
+++ b/docs/agent-sniper.md
@@ -111,7 +111,7 @@ The hard-config sniper is the control group: its constants (band edges, stop per
**Layer 2: intra-arm optimizer (`api/cron/sniper-optimize.js` + `api/_lib/sniper-optimizer.js`).** On a cadence it reads each arm's own real trading record over a trailing window, including the exit-reason distribution, and proposes bounded adjustments to that arm's *inward* knobs: take-profit, trailing/stop percentages, hold time, entry-quality thresholds, and per-trade size. Every proposal is clamped to a hard range and to a small per-run step, so one run can never lurch an arm to an extreme. It runs **shadow by default** (`SNIPER_OPTIMIZER_MODE`): it persists what it *would* do to `agent_sniper_optimizer_runs` and mutates nothing, so you can watch it make tuning calls before it ever touches a live arm. In `apply` mode it enacts changes only for arms that opted in (`auto_optimize = true`), and logs each change to the agent's tamper-evident Reasoning Ledger (`kind = 'optimize'`) next to the trades it learned from. This is the layer that would have caught the first trade's missing take-profit automatically.
-**Layer 3: portfolio evolution (`scripts/sniper-evolve.mjs`).** Across arms, it scores each arm's fitness against the ground-truth base rate (what fraction of launches actually win, from `pump_coin_outcomes`) using Wilson confidence bounds, then reallocates the fleet's daily budget toward higher-fitness arms, retires an arm proven worse than a coin flip, and revives a retired arm after a cooldown to re-test it. Every move is journaled to `sniper_evolution_log` with before/after and evidence.
+**Layer 3: portfolio evolution (`scripts/sniper-evolve.mjs` + `api/cron/sniper-evolve.js`).** Across arms, it scores each arm's fitness against the ground-truth base rate (what fraction of launches actually win, from `pump_coin_outcomes`) using Wilson confidence bounds, then reallocates the fleet's daily budget toward higher-fitness arms, retires an arm proven worse than a coin flip, and revives a retired arm after a cooldown to re-test it. It runs autonomously on a 12-hour cron (dry-run unless `SNIPER_EVOLVE_APPLY=1`) and is also runnable by hand (`node scripts/sniper-evolve.mjs --apply`); both paths share the one `runEvolve()` engine. Every move is journaled to `sniper_evolution_log` with before/after and evidence.
The division of labor is deliberate and enforced by construction: the optimizer moves per-arm entry/exit knobs and never touches budget or on/off; evolution moves budget and on/off and never touches a per-arm knob. Neither can write a safety field (`firewall_level`, `max_price_impact_pct`, `stop_loss_pct` is bounded, the daily cap); those are code-enforced at the `executeBuy` chokepoint and out of reach.
diff --git a/public/changelog.json b/public/changelog.json
index 001eb57a7..e80cf7a29 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-21T09:52:51.103Z",
+ "generated_at": "2026-07-21T12:46:50.016Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -68,6 +68,17 @@
"feature"
]
},
+ {
+ "date": "2026-07-21",
+ "type": "update",
+ "title": "The sniper fleet now runs its full self-improvement loop autonomously",
+ "summary": "Both halves of the fleet's learning loop now run on their own schedule with no human in the loop. The intra-arm optimizer (every 6h) tunes each strategy's own knobs from its real results, and the portfolio evolution engine (every 12h) reallocates budget toward the arms that actually win and retires the ones that provably don't. Every change is bounded, reversible, and journaled; neither loop can touch a safety field or raise the total spend cap.",
+ "link": "/docs/agent-sniper",
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-07-21",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index dd6e5e423..40f1f746f 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -54,6 +54,14 @@
<category>feature</category>
<description>The sniper fleet now has an intra-arm optimizer that learns from each strategy's real trading record and proposes bounded adjustments to its own knobs (take-profit, trailing/stop, hold time, entry-quality, size). It runs in shadow mode by default, recording exactly what it would change without touching anything, and in apply mode only tunes strategies that opted in, logging every change to the agent's tamper-evident reasoning ledger. It pairs with the portfolio evolution engine (which reallocates budget across arms): the optimizer tunes each arm inward, evolution decides which arms get capital. Neither can touch a safety field.</description>
</item>
+ <item>
+ <title>The sniper fleet now runs its full self-improvement loop autonomously</title>
+ <link>https://three.ws/docs/agent-sniper</link>
+ <guid isPermaLink="false">2026-07-21:The sniper fleet now runs its full self-improvement loop autonomously</guid>
+ <pubDate>Tue, 21 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Both halves of the fleet's learning loop now run on their own schedule with no human in the loop. The intra-arm optimizer (every 6h) tunes each strategy's own knobs from its real results, and the portfolio evolution engine (every 12h) reallocates budget toward the arms that actually win and retires the ones that provably don't. Every change is bounded, reversible, and journaled; neither loop can touch a safety field or raise the total spend cap.</description>
+ </item>
<item>
<title>three.ws joins the NVIDIA Inception program</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 0372c393b..67ac836be 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-21T09:52:51.089Z",
+ "generated_at": "2026-07-21T12:46:50.002Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/sniper-evolve.mjs b/scripts/sniper-evolve.mjs
index 90162c4e9..0ccdbb08e 100644
--- a/scripts/sniper-evolve.mjs
+++ b/scripts/sniper-evolve.mjs
@@ -3,12 +3,17 @@
// node scripts/sniper-evolve.mjs # dry-run: print the proposals, write nothing
// node scripts/sniper-evolve.mjs --apply # apply the mutations to the DB
//
+// Autonomous cadence: api/cron/sniper-evolve.js calls runEvolve() on a schedule
+// (dry-run unless SNIPER_EVOLVE_APPLY=1), so the portfolio layer evolves without
+// a human running the script. The exported runEvolve() is the single source of
+// truth for both the CLI and the cron.
+//
// This is the PORTFOLIO layer of the fleet's self-improvement loop. It is the
// complement to the intra-arm optimizer (api/_lib/sniper-optimizer.js +
// api/cron/sniper-optimize.js), which tunes each arm's OWN knobs (stops,
// take-profit, hold, sizing) inward. Evolve works ACROSS arms: it decides which
// arms deserve capital and which should stop trading, against the ground-truth
-// base rate. Division of labor is deliberate — evolve never touches a per-arm
+// base rate. Division of labor is deliberate: evolve never touches a per-arm
// entry/exit knob, the optimizer never moves budget between arms.
//
// Reads each labeled arm's REAL + paper trading evidence and the base rate
@@ -16,14 +21,14 @@
// and mutates the fleet's ALLOCATION. Three moves, all bounded and reversible:
//
// retire an arm with enough samples whose win rate is provably below the
-// base rate (Wilson 95% upper bound < base rate) — stop paying to be wrong.
+// base rate (Wilson 95% upper bound < base rate): stop paying to be wrong.
// 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.
//
// 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
-// loss cap, or push a size past the fleet ceiling — those are code-enforced in
+// loss cap, or push a size past the fleet ceiling: those are code-enforced in
// executeBuy and out of reach. The worst an evolved param can do is a bad,
// stop-loss-protected, firewall-vetted, budget-bounded trade. Every proposal is
// journaled to sniper_evolution_log (before/after + the evidence) so the whole
@@ -34,8 +39,8 @@ import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const { Pool } = require('@neondatabase/serverless');
-const APPLY = process.argv.includes('--apply');
const NETWORK = 'mainnet';
+const LAMPORTS = 1e9;
// ── tunables (env-overridable; the optimizer's own guardrails) ────────────────
const num = (k, d) => (process.env[k] ? Number(process.env[k]) : d);
@@ -43,10 +48,9 @@ const FLEET_DAILY_SOL = num('EVOLVE_FLEET_DAILY_SOL', 0.5); // total budge
const PER_ARM_FLOOR_SOL = num('EVOLVE_ARM_FLOOR_SOL', 0.02); // no active arm starves below this (keeps exploring)
const MIN_SAMPLES_RETIRE = num('EVOLVE_MIN_SAMPLES', 15); // don't retire on noise
const REVIVE_AFTER_HOURS = num('EVOLVE_REVIVE_HOURS', 24); // re-test a retired arm after this long
-const LAMPORTS = 1e9;
// The ONLY columns evolve may write: the portfolio surface. Per-arm entry/exit
-// knobs are intentionally absent — those belong to the intra-arm optimizer. A
+// knobs are intentionally absent: those belong to the intra-arm optimizer. A
// safety field appearing here would be a bug; the list is short and reviewed.
const WRITABLE = new Set(['enabled', 'daily_budget_lamports']);
@@ -74,135 +78,155 @@ function wilson(wins, n, z = 1.96) {
return { lo: Math.max(0, (c - s) / d), hi: Math.min(1, (c + s) / d), p };
}
-const runId = `evolve-${new Date().toISOString().replace(/[^0-9]/g, '').slice(0, 14)}`;
-const pool = new Pool({ connectionString: resolveDatabaseUrl() });
-
-// Ground truth: the base rate every arm has to beat to be worth funding.
-const [{ base_rate }] = (await pool.query(`
- select coalesce(
- count(*) filter (where outcome in ('pumped','graduated'))::float / nullif(count(*),0),
- 0.12) as base_rate
- from pump_coin_outcomes`)).rows;
-const baseRate = Number(base_rate);
-
-// Every labeled arm + its real and paper evidence. Paper fills still teach which
-// coins WOULD have won, so they count (discounted) when real fills are thin.
-const arms = (await pool.query(`
- select s.id, s.label, s.experiment_group, s.decision_mode, s.enabled, s.llm_model,
- s.llm_min_confidence, s.min_oracle_score, s.min_market_cap_usd, s.max_market_cap_usd,
- s.daily_budget_lamports, s.updated_at,
- 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,
- 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_w
- from agent_sniper_strategies s
- left join agent_sniper_positions p on p.strategy_id=s.id and p.network=s.network
- where s.network=$1 and s.label is not null
- group by s.id
- order by s.label`, [NETWORK])).rows;
-
-// Fitness: conservative win-edge over the base rate (Wilson lower bound) plus a
-// realized-ROI term, using 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 and a chance to prove itself.
-function 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 wl = wilson(w, Math.max(1, Math.round(n)));
- const edge = wl.lo - baseRate; // provable edge over ground truth
- const 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 };
+function castParam(field, v) {
+ if (field === 'enabled') return v === 'true';
+ if (['llm_min_confidence', 'min_oracle_score', 'min_market_cap_usd', 'max_market_cap_usd'].includes(field)) {
+ return v === 'null' ? null : Number(v);
+ }
+ return v;
}
-const proposals = [];
-function propose(a, action, field, before, after, fit, evidence) {
- proposals.push({ id: a.id, label: a.label, action, field, before, after, fitness: fit.score, evidence });
-}
+/**
+ * One evolution pass over the fleet. Pure of side effects unless `apply` is true,
+ * in which case it enacts the portfolio mutations (only WRITABLE fields) and logs
+ * every proposal to sniper_evolution_log. Returns a summary for the caller (CLI
+ * or cron). `log` defaults to console.log; the cron passes a no-op to stay quiet.
+ *
+ * @param {{ apply?: boolean, log?: (msg:string)=>void }} [opts]
+ * @returns {Promise<{ runId:string, baseRate:number, activeArms:number, proposals:Array, applied:boolean }>}
+ */
+export async function runEvolve({ apply = false, log = console.log } = {}) {
+ const runId = `evolve-${new Date().toISOString().replace(/[^0-9]/g, '').slice(0, 14)}`;
+ const pool = new Pool({ connectionString: resolveDatabaseUrl() });
+ try {
+ // Ground truth: the base rate every arm has to beat to be worth funding.
+ const [{ base_rate }] = (await pool.query(`
+ select coalesce(
+ count(*) filter (where outcome in ('pumped','graduated'))::float / nullif(count(*),0),
+ 0.12) as base_rate
+ from pump_coin_outcomes`)).rows;
+ const baseRate = Number(base_rate);
+
+ // Every labeled arm + its real and paper evidence. Paper fills still teach
+ // which coins WOULD have won, so they count (discounted) when real fills are thin.
+ const arms = (await pool.query(`
+ select s.id, s.label, s.experiment_group, s.decision_mode, s.enabled, s.llm_model,
+ s.llm_min_confidence, s.min_oracle_score, s.min_market_cap_usd, s.max_market_cap_usd,
+ s.daily_budget_lamports, s.updated_at,
+ 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,
+ 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_w
+ from agent_sniper_strategies s
+ left join agent_sniper_positions p on p.strategy_id=s.id and p.network=s.network
+ where s.network=$1 and s.label is not null
+ group by s.id
+ order by s.label`, [NETWORK])).rows;
+
+ // 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.
+ 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 wl = wilson(w, Math.max(1, Math.round(n)));
+ const edge = wl.lo - baseRate; // provable edge over ground truth
+ const 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 proposals = [];
+ const propose = (a, action, field, before, after, fit, evidence) => {
+ proposals.push({ id: a.id, label: a.label, action, field, before, after, fitness: fit.score, evidence });
+ };
+
+ // 1. RETIRE arms proven worse than a coin flip, and REVIVE stale retirees to re-test.
+ for (const a of arms) {
+ const fit = fitness(a);
+ if (a.enabled && fit.samples >= MIN_SAMPLES_RETIRE && fit.wl.hi < baseRate) {
+ propose(a, 'retire', 'enabled', 'true', 'false', fit,
+ { samples: fit.samples, win_hi: +fit.wl.hi.toFixed(3), base_rate: +baseRate.toFixed(3), reason: 'upper bound below base rate' });
+ } else if (!a.enabled) {
+ const ageH = (Date.now() - new Date(a.updated_at).getTime()) / 3.6e6;
+ if (ageH >= REVIVE_AFTER_HOURS) {
+ propose(a, 'revive', 'enabled', 'false', 'true', fit,
+ { retired_hours: Math.round(ageH), reason: 're-test after cooldown' });
+ }
+ }
+ }
-// 1. RETIRE arms proven worse than a coin flip, and REVIVE stale retirees to re-test.
-for (const a of arms) {
- const fit = fitness(a);
- if (a.enabled && fit.samples >= MIN_SAMPLES_RETIRE && fit.wl.hi < baseRate) {
- propose(a, 'retire', 'enabled', 'true', 'false', fit,
- { samples: fit.samples, win_hi: +fit.wl.hi.toFixed(3), base_rate: +baseRate.toFixed(3), reason: 'upper bound below base rate' });
- } else if (!a.enabled) {
- const ageH = (Date.now() - new Date(a.updated_at).getTime()) / 3.6e6;
- if (ageH >= REVIVE_AFTER_HOURS) {
- propose(a, 'revive', 'enabled', 'false', 'true', fit,
- { retired_hours: Math.round(ageH), reason: 're-test after cooldown' });
+ // 2. REALLOCATE the fixed fleet budget across active arms, fitness-weighted with
+ // a floor. The core "put money where it works" move, bounded so the total can
+ // never grow and exploration never dies.
+ const active = arms.filter((a) => a.enabled && !proposals.find((p) => p.id === a.id && p.action === 'retire'));
+ if (active.length) {
+ const fits = active.map((a) => ({ a, f: fitness(a) }));
+ const floor = PER_ARM_FLOOR_SOL;
+ const floorTotal = floor * active.length;
+ const discretionary = Math.max(0, FLEET_DAILY_SOL - floorTotal);
+ const sumScore = fits.reduce((s, x) => s + x.f.score, 0) || 1;
+ for (const { a, f } of fits) {
+ const share = floor + discretionary * (f.score / sumScore);
+ 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) });
+ }
}
- }
-}
-// 2. REALLOCATE the fixed fleet budget across active arms, fitness-weighted with a
-// floor. This is the core "put money where it works" move, bounded so the total
-// can never grow and exploration never dies.
-const active = arms.filter((a) => a.enabled && !proposals.find((p) => p.id === a.id && p.action === 'retire'));
-if (active.length) {
- const fits = active.map((a) => ({ a, f: fitness(a) }));
- const floor = PER_ARM_FLOOR_SOL;
- const floorTotal = floor * active.length;
- const discretionary = Math.max(0, FLEET_DAILY_SOL - floorTotal);
- const sumScore = fits.reduce((s, x) => s + x.f.score, 0) || 1;
- for (const { a, f } of fits) {
- const share = floor + discretionary * (f.score / sumScore);
- 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) });
- }
-}
+ // ── report + (optional) apply ────────────────────────────────────────────
+ log(`\nEvolution run ${runId}: base rate ${(baseRate * 100).toFixed(1)}% (fraction of launches that win)`);
+ 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(`\n${proposals.length} proposed mutation(s):`);
+ for (const p of proposals) {
+ const fmt = (v) => p.field?.includes('lamports') ? (Number(v) / LAMPORTS).toFixed(3) + ' SOL' : v;
+ log(` [${p.action}] ${p.label}: ${p.field} ${fmt(p.before)} -> ${fmt(p.after)} ${JSON.stringify(p.evidence)}`);
+ }
-// ── report + (optional) apply ─────────────────────────────────────────────────
-console.log(`\nEvolution run ${runId} — base rate ${(baseRate * 100).toFixed(1)}% (fraction of launches that win)`);
-console.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);
- console.log(` ${(a.label || '?').padEnd(17)} ${a.enabled ? 'ON ' : 'off'} fitness ${f.score.toFixed(4)} · ${f.samples} samples · edge ${(f.edge * 100).toFixed(1)}pt`);
-}
-console.log(`\n${proposals.length} proposed mutation(s):`);
-for (const p of proposals) {
- const fmt = (v) => p.field?.includes('lamports') ? (Number(v) / LAMPORTS).toFixed(3) + ' SOL' : v;
- console.log(` [${p.action}] ${p.label}: ${p.field} ${fmt(p.before)} -> ${fmt(p.after)} ${JSON.stringify(p.evidence)}`);
-}
+ // The WRITABLE guard is the safety contract, not a formality: a field outside
+ // the set is refused loudly before any write.
+ for (const p of proposals) {
+ if (p.field && !WRITABLE.has(p.field)) {
+ throw new Error(`REFUSED: ${p.action} tried to write non-writable field '${p.field}'`);
+ }
+ }
+ if (apply) {
+ for (const p of proposals) {
+ await pool.query(
+ `update agent_sniper_strategies set ${p.field} = $1, updated_at = now() where id = $2 and network = $3`,
+ [p.action === 'reallocate' || p.field?.includes('lamports') ? p.after : castParam(p.field, p.after), p.id, NETWORK],
+ );
+ }
+ }
+ for (const p of proposals) {
+ await pool.query(
+ `insert into sniper_evolution_log (run_id, network, strategy_id, label, action, field, before_val, after_val, fitness, evidence, applied)
+ values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
+ [runId, NETWORK, p.id, p.label, p.action, p.field, String(p.before), String(p.after), p.fitness, JSON.stringify(p.evidence), apply],
+ );
+ }
-// Log every proposal (applied flag reflects whether we wrote it), then apply the
-// writable ones. A field outside WRITABLE is refused loudly — that guard is the
-// safety contract, not a formality.
-for (const p of proposals) {
- if (p.field && !WRITABLE.has(p.field)) {
- throw new Error(`REFUSED: ${p.action} tried to write non-writable field '${p.field}'`);
- }
-}
-if (APPLY) {
- for (const p of proposals) {
- await pool.query(
- `update agent_sniper_strategies set ${p.field} = $1, updated_at = now() where id = $2 and network = $3`,
- [p.action === 'reallocate' || p.field?.includes('lamports') ? p.after : castParam(p.field, p.after), p.id, NETWORK],
- );
+ log(`\n${apply ? 'Applied and logged' : 'Logged (dry-run)'} ${proposals.length} mutation(s) as ${runId}.`);
+ if (!apply) log('Re-run with --apply to let the fleet evolve.');
+ return { runId, baseRate, activeArms: active.length, proposals, applied: apply };
+ } finally {
+ await pool.end();
}
}
-for (const p of proposals) {
- await pool.query(
- `insert into sniper_evolution_log (run_id, network, strategy_id, label, action, field, before_val, after_val, fitness, evidence, applied)
- values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
- [runId, NETWORK, p.id, p.label, p.action, p.field, String(p.before), String(p.after), p.fitness, JSON.stringify(p.evidence), APPLY],
- );
-}
-function castParam(field, v) {
- if (field === 'enabled') return v === 'true';
- if (['llm_min_confidence', 'min_oracle_score', 'min_market_cap_usd', 'max_market_cap_usd'].includes(field)) {
- return v === 'null' ? null : Number(v);
- }
- return v;
+// CLI entrypoint: run directly with `node scripts/sniper-evolve.mjs [--apply]`.
+if (process.argv[1] && process.argv[1].endsWith('sniper-evolve.mjs')) {
+ runEvolve({ apply: process.argv.includes('--apply') }).catch((e) => {
+ console.error(e);
+ process.exit(1);
+ });
}
-
-console.log(`\n${APPLY ? 'Applied and logged' : 'Logged (dry-run)'} ${proposals.length} mutation(s) as ${runId}.`);
-if (!APPLY) console.log('Re-run with --apply to let the fleet evolve.');
-await pool.end();
diff --git a/vercel.json b/vercel.json
index 84d204146..eea6f567c 100644
--- a/vercel.json
+++ b/vercel.json
@@ -6,7 +6,7 @@
"NODE_OPTIONS": "--no-deprecation"
},
"functions": {
- "api/cron/{economy-tick,copy-fanout,mirror-fanout,signal-fanout,three-holders-snapshot,x402-autonomous-loop,pulse-tick,coin-intel-observe,launcher-tick,reflect-sweep,solana-autodeploy,db-retention,custody-attest,sniper-optimize}.js": {
+ "api/cron/{economy-tick,copy-fanout,mirror-fanout,signal-fanout,three-holders-snapshot,x402-autonomous-loop,pulse-tick,coin-intel-observe,launcher-tick,reflect-sweep,solana-autodeploy,db-retention,custody-attest,sniper-optimize,sniper-evolve}.js": {
"maxDuration": 120
},
"api/cron/{strategy-fanout,gmgn-seed}.js": {
@@ -5191,6 +5191,10 @@
"path": "/api/cron/sniper-optimize",
"schedule": "0 */6 * * *"
},
+ {
+ "path": "/api/cron/sniper-evolve",
+ "schedule": "30 */12 * * *"
+ },
{
"path": "/api/cron/dead-man-switch",
"schedule": "0 5 * * *"