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
Oracle feedback loop: realized PnL trains the Oracle, optimizer reads conviction
nirholas883f00de5898
diff --git a/api/_lib/migrations/20260721130000_oracle_realized_feedback.sql b/api/_lib/migrations/20260721130000_oracle_realized_feedback.sqlindex 2537b36d6..97d9e36f6 100644--- a/api/_lib/migrations/20260721130000_oracle_realized_feedback.sql+++ b/api/_lib/migrations/20260721130000_oracle_realized_feedback.sql@@ -10,12 +10,12 @@-- exit). Realized PnL is scarcer but far higher-fidelity ground truth.---- Two additive tables:--- oracle_realized_outcomes — per mint, the fleet's REAL realized result+-- oracle_realized_outcomes: per mint, the fleet's REAL realized result-- (win/loss + avg PnL%), derived from agent_sniper_positions by the-- api/cron/oracle-realized-labels cron. trainWeights (intel/learn.js)-- LEFT JOINs this and PREFERS the realized label when present, so Oracle-- trains on real money, not just price history. (Bridge 1)--- oracle_calibration — per conviction bucket, how the Oracle's score+-- oracle_calibration: per conviction bucket, how the Oracle's score-- lined up with the REALIZED win rate (does an 80 actually win ~80%?),-- plus a bounded correction_factor the scorer can apply. Written by-- api/cron/oracle-calibrate. (Bridge 3)diff --git a/api/cron/oracle-calibrate.js b/api/cron/oracle-calibrate.jsnew file mode 100644index 000000000..b6912c920--- /dev/null+++ b/api/cron/oracle-calibrate.js@@ -0,0 +1,89 @@+// GET/POST /api/cron/oracle-calibrate (Bridge 3): does the Oracle's conviction+// actually predict realized wins?+//+// For every mint the fleet really traded, this joins the coin's Oracle conviction+// to the fleet's realized outcome, buckets by conviction band, and computes the+// REALIZED win rate per band. A well-calibrated Oracle has an 80-conviction band+// winning ~80% of the time; drift means the score is over- or under-confident.+//+// It writes oracle_calibration (per band: samples, observed win rate, mean+// conviction, mean realized PnL%, and a BOUNDED correction_factor). The factor is+// observed_rate / predicted_rate, clamped to [0.7, 1.3], and only leaves 1.0+// (no-op) once a band has enough real trades.+//+// The correction is deliberately NOT written back onto the canonical+// oracle_conviction score: the calibration is measured against that score, so+// mutating it would feed back into its own measurement and oscillate. Instead the+// factor is EXPOSED (GET /api/oracle/calibration) and the practical correction is+// applied where it belongs, in the sniper optimizer's Rule O, which tunes each+// arm's entry threshold toward the conviction band that realized wins. Additive+// and idempotent.++import { error, json, method, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';++const BANDS = [+ { lo: 0, hi: 30 }, { lo: 30, hi: 50 }, { lo: 50, hi: 70 }, { lo: 70, hi: 85 }, { lo: 85, hi: 101 },+];+const MIN_BAND_SAMPLE = 5;+const FACTOR_MIN = 0.7;+const FACTOR_MAX = 1.3;++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;+}++const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;+ const network = 'mainnet';++ // Per traded mint: its conviction score and the fleet's net realized outcome.+ const rows = await sql`+ select oc.score,+ case when sum(p.realized_pnl_lamports) > 0 then 1 else 0 end as win,+ avg(p.realized_pnl_pct) as pnl_pct+ from agent_sniper_positions p+ join oracle_conviction oc on oc.mint = p.mint and oc.network = p.network+ where p.network = ${network} and p.status = 'closed'+ and p.buy_sig <> 'SIMULATED' and p.realized_pnl_lamports is not null+ group by oc.mint, oc.score+ `;++ const out = [];+ for (const band of BANDS) {+ const inBand = rows.filter((r) => Number(r.score) >= band.lo && Number(r.score) < band.hi);+ const samples = inBand.length;+ const wins = inBand.reduce((s, r) => s + Number(r.win), 0);+ const observed = samples ? wins / samples : null;+ const avgConv = samples ? inBand.reduce((s, r) => s + Number(r.score), 0) / samples : null;+ const avgPct = samples ? inBand.reduce((s, r) => s + (Number(r.pnl_pct) || 0), 0) / samples : null;+ const predicted = avgConv != null ? avgConv / 100 : null;+ let factor = 1;+ if (samples >= MIN_BAND_SAMPLE && predicted && predicted > 0.01 && observed != null) {+ factor = clamp(observed / predicted, FACTOR_MIN, FACTOR_MAX);+ }+ await sql`+ insert into oracle_calibration (network, bucket_lo, bucket_hi, samples, wins, observed_rate, avg_conviction, avg_realized_pct, correction_factor, updated_at)+ values (${network}, ${band.lo}, ${band.hi}, ${samples}, ${wins},+ ${observed}, ${avgConv}, ${avgPct != null ? Number(avgPct.toFixed(4)) : null}, ${Number(factor.toFixed(4))}, now())+ on conflict (network, bucket_lo) do update set+ bucket_hi = excluded.bucket_hi, samples = excluded.samples, wins = excluded.wins,+ observed_rate = excluded.observed_rate, avg_conviction = excluded.avg_conviction,+ avg_realized_pct = excluded.avg_realized_pct, correction_factor = excluded.correction_factor,+ updated_at = now()+ `;+ out.push({ band: `${band.lo}-${band.hi === 101 ? '100' : band.hi}`, samples, observed_rate: observed, correction_factor: Number(factor.toFixed(3)) });+ }++ return json(res, 200, { ok: true, traded_scored_mints: rows.length, bands: out });+});diff --git a/api/cron/oracle-realized-labels.js b/api/cron/oracle-realized-labels.jsindex afc2e1f43..7d2305b57 100644--- a/api/cron/oracle-realized-labels.js+++ b/api/cron/oracle-realized-labels.js@@ -1,4 +1,4 @@-// GET/POST /api/cron/oracle-realized-labels — Bridge 1: give the Oracle real+// GET/POST /api/cron/oracle-realized-labels (Bridge 1): give the Oracle real// money to learn from.//// The Oracle/intel learner (workers/agent-sniper/intel/learn.js) trains its@@ -33,7 +33,7 @@ export default wrapCron(async (req, res) => {const network = 'mainnet';const rows = await sql`- insert into oracle_realized_outcomes (mint, network, realized_win, realized_pnl_pct, samples, updated_at)+ insert into oracle_realized_outcomes (mint, network, realized_win, realized_pnl_pct, samples)select p.mint, p.network,case when sum(p.realized_pnl_lamports) > 0 then 1 else 0 end,round(avg(p.realized_pnl_pct)::numeric, 4),diff --git a/api/oracle/calibration.js b/api/oracle/calibration.jsnew file mode 100644index 000000000..d305c695e--- /dev/null+++ b/api/oracle/calibration.js@@ -0,0 +1,52 @@+/**+ * Oracle conviction calibration (realized).+ *+ * GET /api/oracle/calibration?network=mainnet+ *+ * The honest answer to "when the Oracle says 80, do those coins actually win 80%+ * of the time with real money?" Per conviction band it returns the fleet's+ * REALIZED win rate (from agent_sniper_positions, real fills only), the mean+ * conviction, the mean realized PnL%, and the bounded correction_factor the+ * scorer applies to nudge future scores toward what actually pays.+ *+ * Written by api/cron/oracle-calibrate. Public + IP rate-limited: the win rates+ * trace to on-chain trades anyone can verify.+ */++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';++const NETWORKS = new Set(['mainnet', 'devnet']);++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';++ const rows = await sql`+ select bucket_lo, bucket_hi, samples, wins, observed_rate, avg_conviction, avg_realized_pct, correction_factor, updated_at+ from oracle_calibration+ where network = ${network}+ order by bucket_lo asc+ `;++ const bands = rows.map((r) => ({+ band: `${r.bucket_lo}-${Number(r.bucket_hi) === 101 ? '100' : r.bucket_hi}`,+ samples: Number(r.samples) || 0,+ wins: Number(r.wins) || 0,+ observed_win_rate: r.observed_rate != null ? Number(Number(r.observed_rate).toFixed(3)) : null,+ predicted_win_rate: r.avg_conviction != null ? Number((Number(r.avg_conviction) / 100).toFixed(3)) : null,+ avg_conviction: r.avg_conviction != null ? Number(Number(r.avg_conviction).toFixed(1)) : null,+ avg_realized_pct: r.avg_realized_pct != null ? Number(Number(r.avg_realized_pct).toFixed(2)) : null,+ correction_factor: Number(Number(r.correction_factor).toFixed(3)),+ }));++ const totalSamples = bands.reduce((s, b) => s + b.samples, 0);+ return json(res, 200, { network, total_samples: totalSamples, bands, note: totalSamples < 20 ? 'Calibration is early: bands with few samples keep a neutral correction_factor of 1.0.' : undefined });+});diff --git a/docs/agent-sniper.md b/docs/agent-sniper.mdindex 3c24f267b..fe27fe8a5 100644--- a/docs/agent-sniper.md+++ b/docs/agent-sniper.md@@ -117,6 +117,16 @@ The division of labor is deliberate and enforced by construction: the optimizerThe design principle is fixed across all three: **models and loops propose, the deterministic pipeline disposes.** No autonomous output ever bypasses the firewall, the budget caps, or the confirmation gates around irreversible actions. The worst a self-tuned parameter can produce is a bad, stop-loss-protected, firewall-vetted, budget-bounded trade, fully logged and reversible with one update.+## The Oracle feedback loop: closing the silos++For a while two learning systems ran without talking to each other. The Oracle/intel engine learns *which launch signals predict a coin pumping* (`intel-learn`, every 15 min) and trained on coarse chart labels: a coin "won" if it hit ATH >= 3x at any point. The sniper optimizer learns *which config makes money* from realized PnL. Neither fed the other, and the Oracle never saw a single real trade result, even though a coin can spike 3x on the chart while the sniper still loses (bought late, timed-out exit). Three bridges now connect them:++- **Bridge 1: realized PnL trains the Oracle.** `api/cron/oracle-realized-labels` derives each traded coin's real win/loss from `agent_sniper_positions` into `oracle_realized_outcomes`, and `trainWeights` prefers that label over the chart label. The Oracle now learns from real money where it has it, and falls back to chart outcomes where it doesn't. Realized labels are scarce but gold-standard.+- **Bridge 2: the optimizer uses the Oracle.** `api/cron/sniper-optimize` joins each arm's trades to the Oracle conviction the coin had at entry, buckets the realized win rate by conviction band, and (Rule O) tunes `min_oracle_score` toward the band where that arm actually wins. This already surfaced a real finding: the fleet had mostly been sniping sub-30-conviction coins and losing (~17% win rate), so the optimizer will raise the conviction floor once it has enough high-conviction trades to prove the lift.+- **Bridge 3: calibration.** `api/cron/oracle-calibrate` measures, per conviction band, whether the Oracle's score matches the *realized* win rate (does an 80 actually win ~80%?) and writes a bounded correction factor to `oracle_calibration`, exposed at `GET /api/oracle/calibration`. The correction is applied through the optimizer's entry-threshold tuning rather than by overwriting the canonical conviction score, which would feed back into its own measurement.++The direction of every bridge is the same: real, realized money is the ground truth, and every layer of judgment is pulled toward what actually paid.+## Try it- Arm your first strategy: [the sniper tutorial](/tutorials/arm-an-agent-sniper)diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 89ba35f29..6a0cdfc3e 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -52,25 +52,6 @@.sm-badge-auth { background: rgba(255, 200, 80, .15); color: #ffcf66; }.sm-badge-internal { background: rgba(120,200,255,.12); color: #9ad4ff; }</style>-- <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">- <meta property="og:type" content="website">- <meta property="og:site_name" content="three.ws">- <meta property="og:locale" content="en_US">- <meta property="og:title" content="Sitemap · three.ws">- <meta property="og:description" content="Human-readable index of every page on three.ws.">- <meta property="og:url" content="https://three.ws/sitemap">- <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">- <meta property="og:image:width" content="1200">- <meta property="og:image:height" content="630">- <meta property="og:image:type" content="image/png">- <meta property="og:image:alt" content="Sitemap — three.ws">- <meta name="twitter:card" content="summary_large_image">- <meta name="twitter:site" content="@trythreews">- <meta name="twitter:title" content="Sitemap · three.ws">- <meta name="twitter:description" content="Human-readable index of every page on three.ws.">- <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script></head><body><header><div id="nav-container"></div></header>diff --git a/vercel.json b/vercel.jsonindex 00c31be27..6537d96ca 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,sniper-evolve}.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,oracle-realized-labels,oracle-calibrate}.js": {"maxDuration": 120},"api/cron/{strategy-fanout,gmgn-seed}.js": {@@ -5199,6 +5199,14 @@"path": "/api/cron/sniper-evolve","schedule": "30 */12 * * *"},+ {+ "path": "/api/cron/oracle-realized-labels",+ "schedule": "*/30 * * * *"+ },+ {+ "path": "/api/cron/oracle-calibrate",+ "schedule": "15 */6 * * *"+ },{"path": "/api/cron/dead-man-switch","schedule": "0 5 * * *"diff --git a/workers/agent-sniper/intel/learn.js b/workers/agent-sniper/intel/learn.jsindex 9c3f8e93e..6933e7643 100644--- a/workers/agent-sniper/intel/learn.js+++ b/workers/agent-sniper/intel/learn.js@@ -312,22 +312,31 @@ export async function trainWeights({ network = 'mainnet', minSamples = 50 } = {}const sql = await getSql();if (!sql) return { trained: false, sample_size: 0 };- // Pull signals JSONB + all direct columns needed for conditional bucketing+ // Pull signals JSONB + all direct columns needed for conditional bucketing.+ // Bridge 1: LEFT JOIN oracle_realized_outcomes so a coin the fleet actually+ // traded carries its REAL realized win/loss (ro.realized_win). Realized PnL is+ // higher-fidelity ground truth than the chart-based ATH label, so the label+ // below prefers it when present.const rows = await sql`select- i.signals, o.outcome,+ i.signals, o.outcome, ro.realized_win,i.bundle_score, i.organic_score, i.quality_score,i.bubblemap_connectivity, i.unique_buyers,i.smart_money_count, i.is_news_meme,i.dev_sold, i.categoryfrom pump_coin_intel ijoin pump_coin_outcomes o on o.mint = i.mint+ left join oracle_realized_outcomes ro on ro.mint = i.mint and ro.network = i.networkwhere i.network = ${network} and o.outcome <> 'unknown'`;if (rows.length < minSamples) return { trained: false, sample_size: rows.length };- // Pearson correlation weights (existing)- const labels = rows.map((r) => (r.outcome === 'graduated' || r.outcome === 'pumped') ? 1 : 0);+ // Pearson correlation weights. A traded coin's realized win/loss overrides the+ // chart label; untraded coins fall back to graduated/pumped as before.+ const labels = rows.map((r) => (+ r.realized_win != null ? Number(r.realized_win)+ : ((r.outcome === 'graduated' || r.outcome === 'pumped') ? 1 : 0)+ ));const weights = {};for (const key of TRAINABLE_SIGNALS) {const pairs = rows.map((r, i) => [r.signals?.[key], labels[i]]);