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
fix(oracle): grade conviction against the event it was trained to predict
nirholas63713aabdfac
diff --git a/api/_lib/oracle/conviction-calibration.json b/api/_lib/oracle/conviction-calibration.jsonnew file mode 100644index 000000000..9face5ff3--- /dev/null+++ b/api/_lib/oracle/conviction-calibration.json@@ -0,0 +1,102 @@+{+ "version": 1,+ "fitted_at": "2026-08-14T06:42:47.867Z",+ "source": "api:https://three.ws",+ "network": "mainnet",+ "win_definition": "graduated or (ath_multiple >= 2 and not rugged)",+ "resolved_n": 61916,+ "wins_n": 3373,+ "base_rate": 0.0545,+ "bands": [+ {+ "lo": 0,+ "hi": 10,+ "n": 7939,+ "wins": 56,+ "observed": 0.0071,+ "calibrated": 0.0071,+ "lift": 0.13+ },+ {+ "lo": 10,+ "hi": 20,+ "n": 24344,+ "wins": 1184,+ "observed": 0.0486,+ "calibrated": 0.0486,+ "lift": 0.89+ },+ {+ "lo": 20,+ "hi": 30,+ "n": 10724,+ "wins": 684,+ "observed": 0.0638,+ "calibrated": 0.0488,+ "lift": 0.9+ },+ {+ "lo": 30,+ "hi": 40,+ "n": 8037,+ "wins": 231,+ "observed": 0.0287,+ "calibrated": 0.0488,+ "lift": 0.9+ },+ {+ "lo": 40,+ "hi": 50,+ "n": 4549,+ "wins": 340,+ "observed": 0.0747,+ "calibrated": 0.0728,+ "lift": 1.34+ },+ {+ "lo": 50,+ "hi": 60,+ "n": 1947,+ "wins": 133,+ "observed": 0.0683,+ "calibrated": 0.0728,+ "lift": 1.34+ },+ {+ "lo": 60,+ "hi": 70,+ "n": 2231,+ "wins": 368,+ "observed": 0.1649,+ "calibrated": 0.1496,+ "lift": 2.75+ },+ {+ "lo": 70,+ "hi": 80,+ "n": 824,+ "wins": 89,+ "observed": 0.108,+ "calibrated": 0.1496,+ "lift": 2.75+ },+ {+ "lo": 80,+ "hi": 90,+ "n": 529,+ "wins": 80,+ "observed": 0.1512,+ "calibrated": 0.1512,+ "lift": 2.78+ },+ {+ "lo": 90,+ "hi": 100,+ "n": 792,+ "wins": 208,+ "observed": 0.2626,+ "calibrated": 0.2626,+ "lift": 4.82+ }+ ]+}diff --git a/api/_lib/oracle/conviction.js b/api/_lib/oracle/conviction.jsindex e779e3614..dda610772 100644--- a/api/_lib/oracle/conviction.js+++ b/api/_lib/oracle/conviction.js@@ -30,27 +30,76 @@// - One hard cap: a serial-rugger creator still ceilings the final score.// The data agrees with this one (5+ launches, 0 graduations: 0.26x base).//-// What the score MEANS now: the model's calibrated P(good) mapped through-// fixed probability anchors so the public tier boundaries land on real odds:-// Watch starts at P>=5%, Lean at 12%, Strong at 30%, Prime at 55%. On the-// holdout, the P>=0.55 band observed 73.5% good. A tier is now a claim about-// measured frequency, not a vibe.+// What the score MEANS: the model's P(good) mapped through fixed probability+// anchors onto the 0-100 line. That number is a RANK, and it is the training+// label's probability, not the platform's win rate. The two were never the+// same and for a long time nothing said so, which is how a card could read+// "conviction 99" while that band went on to win 26% of the time.+//+// So the tier ladder no longer sits on the training anchors. It sits on+// conviction-calibration.json: an isotonic fit of the REALIZED win rate per+// score band over every coin Oracle scored that the market has since resolved+// (61,916 coins at the 2026-08-14 fit, win = graduated or >= 2x ATH without+// rugging, base rate 5.4%). That fit exposes exactly five rungs the data can+// tell apart, and the tier boundaries are their edges:+//+// Avoid score 0-10 0.7% win 0.13x base+// Watch score 10-40 4.9% win 0.89x base+// Lean score 40-60 7.3% win 1.34x base+// Strong score 60-90 15.0% win 2.75x base+// Prime score 90-100 26.3% win 4.82x base+//+// The old ladder (86/72/56/34) split the flat 60-90 plateau into Prime and+// Strong, so those two tiers were statistically identical (12% vs 13%), while+// Watch sat below Avoid. Every rung above is now a distinct measured claim, and+// hitRateFor() serves the rate itself so the UI can quote the odds instead of+// letting a 99 imply 99%. Refit with scripts/oracle-calibrate.mjs.import MODEL_JSON from './conviction-model.json' with { type: 'json' };+import CALIBRATION_JSON from './conviction-calibration.json' with { type: 'json' };import { isProven, isFlagged } from './archetype.js';export const MODEL = MODEL_JSON;+export const CALIBRATION = CALIBRATION_JSON;-// Tier thresholds on the final 0-100 score (public ladder, unchanged from v1)-// and the P(good) each boundary is anchored to by the score map below.+// Tier thresholds on the final 0-100 score, set on the rung edges of the+// realized-outcome fit above.const TIERS = [- { min: 86, tier: 'prime', label: 'Prime' },- { min: 72, tier: 'strong', label: 'Strong' },- { min: 56, tier: 'lean', label: 'Lean' },- { min: 34, tier: 'watch', label: 'Watch' },+ { min: 90, tier: 'prime', label: 'Prime' },+ { min: 60, tier: 'strong', label: 'Strong' },+ { min: 40, tier: 'lean', label: 'Lean' },+ { min: 10, tier: 'watch', label: 'Watch' },{ min: 0, tier: 'avoid', label: 'Avoid' },];+/** The public tier for a 0-100 conviction score. Single source of the ladder. */+export function tierForScore(score) {+ const s = clamp(num(score));+ return TIERS.find((t) => s >= t.min) || TIERS[TIERS.length - 1];+}++/**+ * The realized hit rate for a score, straight from the production calibration.+ * This is what the score is worth in outcomes: of every resolved coin Oracle+ * scored into this band, `rate` is the fraction that won and `lift` is how many+ * times the market's own base rate that is.+ *+ * @param {number} score 0-100 conviction+ * @returns {{rate:number, lift:number, band:string, n:number, baseRate:number}}+ */+export function hitRateFor(score) {+ const s = clamp(num(score));+ const bands = CALIBRATION.bands || [];+ const band = bands.find((b) => s >= b.lo && s < b.hi) || bands[bands.length - 1] || null;+ return {+ rate: band ? band.calibrated : CALIBRATION.base_rate,+ lift: band ? band.lift : 1,+ band: band ? `${band.lo}-${band.hi}` : null,+ n: band ? band.n : 0,+ baseRate: CALIBRATION.base_rate,+ };+}+// Piecewise-linear map from model probability to the 0-100 score line, anchored// so each tier boundary corresponds to a fixed P(good). Monotone, invertible.const A = MODEL.tier_probability_anchors;@@ -63,6 +112,30 @@ const SCORE_ANCHORS = [[1, 100],];+export { SCORE_ANCHORS };++// What the score PREDICTS, stated once here so every surface can quote it+// instead of implying something broader. The training label is+// `outcome in ('graduated','pumped')`, where 'pumped' means the coin peaked at+// >= 3x its market cap at first sight (workers/agent-sniper/intel/learn.js), and+// that label is deliberately judged INDEPENDENTLY of a later collapse: a launch+// that ran 6x and then rugged is a hit. So conviction ranks the odds of a RUN,+// never the odds of a safe hold, and a high score on a coin whose chart is now+// dead is not necessarily a miss.+//+// Three surfaces grade the engine on a different, stricter question instead+// (graduated, or >= 2x while never rugging: api/oracle/{stats,backtest,wins}.js).+// That number is the right one for a holder and the wrong one for judging the+// ranking, so anything that shows it must show WHICH question it answers. Both+// are real; presenting one as the other is what made a working engine read as a+// broken one.+export const PREDICTED_EVENT = Object.freeze({+ id: 'spike_or_graduate',+ label: 'graduates, or peaks at 3x or more above its market cap at first sight',+ short: 'spikes 3x or graduates',+ caveat: 'A later collapse does not undo a hit. Conviction ranks the odds of a run, not the odds of a safe hold.',+});+const clamp = (n, lo = 0, hi = 100) => Math.max(lo, Math.min(hi, n));const num = (v, d = 0) => (Number.isFinite(Number(v)) ? Number(v) : d);const sigmoid = (z) => 1 / (1 + Math.exp(-z));@@ -78,6 +151,27 @@ export function scoreFromProbability(p) {return 100;}+/**+ * Inverse of scoreFromProbability: the P(PREDICTED_EVENT) a given score actually+ * claims. The score line is not a percentage (a score of 86 claims 55%, not+ * 86%), so any surface comparing a score to a realized rate has to convert+ * first. Every calibration table we shipped used score/100 as the prediction,+ * which overstated the engine's own claim by up to 4x and made a working ranking+ * look wildly overconfident on top of its real overconfidence.+ *+ * @param {number} score 0-100 conviction score+ * @returns {number} probability in [0,1]+ */+export function probabilityFromScore(score) {+ const s = clamp(num(score));+ for (let i = 1; i < SCORE_ANCHORS.length; i++) {+ const [p0, s0] = SCORE_ANCHORS[i - 1];+ const [p1, s1] = SCORE_ANCHORS[i];+ if (s <= s1) return s1 === s0 ? p1 : p0 + ((s - s0) / (s1 - s0)) * (p1 - p0);+ }+ return 1;+}+// ── Feature extraction ────────────────────────────────────────────────────────// The model was trained on the raw launch-time signals JSONB. intel.launch (from// sources.js) carries those exact values; the derived CoinIntel fields act asdiff --git a/api/cron/oracle-calibrate.js b/api/cron/oracle-calibrate.jsindex 86087a26e..16e6084a4 100644--- a/api/cron/oracle-calibrate.js+++ b/api/cron/oracle-calibrate.js@@ -3,8 +3,13 @@//// 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.+// REALIZED win rate per band. The band's claim is probabilityFromScore(mean+// score), because the score line is not a percentage (86 claims P=0.55, not+// 0.86); drift against that claim means the score is over- or under-confident.+// Note the fleet's "win" here is a positive realized PnL on a real fill, a third+// question again: neither the engine's trained event (a 3x spike or graduation)+// nor the site's rug-aware win rate. Exit timing belongs to the fleet, so a gap+// between this table and /api/oracle/backtest is expected, not a bug.//// It writes oracle_calibration (per band: samples, observed win rate, mean// conviction, mean realized PnL%, and a BOUNDED correction_factor). The factor is@@ -22,6 +27,7 @@import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { requireCron } from '../_lib/cron-auth.js';+import { probabilityFromScore } from '../_lib/oracle/conviction.js';const BANDS = [{ lo: 0, hi: 30 }, { lo: 30, hi: 50 }, { lo: 50, hi: 70 }, { lo: 70, hi: 85 }, { lo: 85, hi: 101 },@@ -57,7 +63,10 @@ export default wrapCron(async (req, res) => {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;+ // What the band CLAIMS, not the band's own number: the score line is not a+ // percentage (86 claims P=0.55), so avgConv/100 compared a probability to a+ // score and reported drift that was really a unit mismatch.+ const predicted = avgConv != null ? probabilityFromScore(avgConv) : null;let factor = 1;if (samples >= MIN_BAND_SAMPLE && predicted && predicted > 0.01 && observed != null) {factor = clamp(observed / predicted, FACTOR_MIN, FACTOR_MAX);diff --git a/api/oracle/backtest.js b/api/oracle/backtest.jsindex 641efd408..33c45f475 100644--- a/api/oracle/backtest.js+++ b/api/oracle/backtest.js@@ -22,6 +22,7 @@ import { cors, json, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';import { QUOTE_MINT_LIST } from '../_lib/quote-mints.js';+import { PREDICTED_EVENT, probabilityFromScore } from '../_lib/oracle/conviction.js';const PERIODS = { '1d': 1, '7d': 7, '30d': 30, '90d': 90, 'all': null };const TIERS = new Set(['prime', 'strong', 'lean', 'watch', 'avoid', 'all']);@@ -56,6 +57,37 @@ export function wilson(wins, n, z = 1.96) {return { lo, hi, width: hi - lo };}+/**+ * Is the ladder actually ordered? The old check allowed a 5-point drop per step+ * and then reported `monotonic: true` on a ladder that visibly dipped, which the+ * /oracle page turned into "the win rate climbs at every band, the ranking is+ * calibrated, not noise". This counts an inversion only when a higher band scores+ * WORSE than a lower one and their 95% intervals are disjoint, so noise cannot+ * explain it away and a real inversion cannot be tolerated away either.+ *+ * @param {Array<object>} bands calibration bands, ascending+ * @param {string} rateKey band field holding the realized rate+ * @param {string} ciKey band field holding that rate's Wilson interval+ * @param {number} minN bands thinner than this are too noisy to judge+ */+export function ladderCheck(bands, rateKey, ciKey, minN = 100) {+ const seq = bands.filter((b) => b.n >= minN && b[rateKey] != null && b[ciKey]);+ const inversions = [];+ for (let i = 1; i < seq.length; i++) {+ for (let j = 0; j < i; j++) {+ const lower = seq[j];+ const higher = seq[i];+ if (higher[rateKey] >= lower[rateKey]) continue;+ if (higher[ciKey].hi >= lower[ciKey].lo) continue; // intervals overlap: noise, not an inversion+ inversions.push({+ band: higher.band, realized: higher[rateKey],+ below_band: lower.band, below_realized: lower[rateKey],+ });+ }+ }+ return { monotonic: inversions.length === 0, judged_bands: seq.length, inversions: inversions.slice(0, 8) };+}+async function query(days, tier, network) {const key = cacheKey(days, tier, network);const hit = _cache.get(key);@@ -114,19 +146,28 @@ async function query(days, tier, network) {agg.ci = wilson(agg.wins, resolved);// ── score-band calibration + Brier score ───────────────────────────────────- // The conviction score claims to rank coins by win probability. Calibration is- // the proof: bucket every resolved coin by its score band and measure the- // REALIZED win rate per band. A trustworthy engine produces a monotonic ladder- // (higher band → higher realized rate) that tracks the band's own prediction.- // Brier = mean squared error of score/100 (treated as a probability) vs the- // 0/1 outcome: one number for "how well-calibrated overall" (lower is better).- // This pass is unconditional on tier so the baseline is the true market rate.- const calRows = await sql`+ // Calibration answers "does a score mean what it claims?", and that only works+ // if both halves speak the same language. Two bugs used to break that:+ //+ // 1. The band's prediction was its own midpoint, i.e. score/100 read as a+ // percentage. The score line is NOT a percentage: 86 claims P=0.55 and 34+ // claims P=0.05 (conviction.js SCORE_ANCHORS). Every published table+ // therefore overstated the engine's claim by up to 4x. probabilityFromScore+ // converts, so predicted is now what the engine actually said.+ // 2. Realized was the rug-aware win rate, which is NOT the event the model was+ // trained to predict. That grades the ranking on a stricter question and+ // makes a calibrated engine look broken. Both now ship side by side:+ // realized_spike is the trained event (PREDICTED_EVENT: graduated or >= 3x+ // ATH, a later collapse allowed), realized stays the holder-honest win.+ //+ // Grouping by exact score instead of by band keeps the Brier score exact (each+ // score carries its own claimed probability) and costs at most 101 rows.+ const scoreRows = await sql`select- least(width_bucket(c.score, 0, 100, 10), 10) as bucket,+ c.score::int as score,count(*)::int as n,- count(*) filter (where o.graduated or (o.ath_multiple >= 2 and not coalesce(o.rugged, false)))::int as wins,- round(avg(c.score)::numeric, 1) as avg_score+ count(*) filter (where o.graduated or o.ath_multiple >= 3)::int as spikes,+ count(*) filter (where o.graduated or (o.ath_multiple >= 2 and not coalesce(o.rugged, false)))::int as winsfrom oracle_conviction cjoin pump_coin_outcomes o on o.mint = c.mintwhere c.network = ${network}@@ -137,58 +178,78 @@ async function query(days, tier, network) {order by 1`.catch(() => []);- const calibration = calRows- .filter((r) => r.bucket >= 1 && r.bucket <= 10)- .map((r) => {- const lo = (r.bucket - 1) * 10;- const hi = r.bucket * 10;- const realized = r.n ? Math.round((r.wins / r.n) * 100) : null;- return {- band: `${lo}-${hi}`,- lo, hi,- n: r.n,- wins: r.wins,- avg_score: r.avg_score != null ? Number(r.avg_score) : (lo + hi) / 2,- predicted: Math.round((lo + hi) / 2), // band midpoint as a % prediction- realized, // realized win rate in the band- ci: wilson(r.wins, r.n),- };+ // Bands of 10, assembled from the per-score aggregate. `predicted` is the+ // sample-weighted mean of the probability each score in the band claims, so it+ // tracks where the coins actually sit rather than an assumed midpoint.+ const bands = [];+ for (let lo = 0; lo < 100; lo += 10) {+ const hi = lo + 10;+ const inBand = scoreRows.filter((r) => {+ const s = Number(r.score);+ return s >= lo && (hi === 100 ? s <= 100 : s < hi);+ });+ const n = inBand.reduce((a, r) => a + r.n, 0);+ if (!n) continue;+ const wins = inBand.reduce((a, r) => a + r.wins, 0);+ const spikes = inBand.reduce((a, r) => a + r.spikes, 0);+ const scoreSum = inBand.reduce((a, r) => a + Number(r.score) * r.n, 0);+ const claimSum = inBand.reduce((a, r) => a + probabilityFromScore(Number(r.score)) * r.n, 0);+ bands.push({+ band: `${lo}-${hi}`,+ lo, hi, n, wins, spikes,+ avg_score: Number((scoreSum / n).toFixed(1)),+ predicted: Math.round((claimSum / n) * 100),+ realized: Math.round((wins / n) * 100),+ realized_spike: Math.round((spikes / n) * 100),+ ci: wilson(wins, n),+ spike_ci: wilson(spikes, n),});+ }+ const calibration = bands;- // Market baseline: a coin drawn at random from everything Oracle scored.- const baseRow = await sql`- select- count(*)::int as n,- count(*) filter (where o.graduated or (o.ath_multiple >= 2 and not coalesce(o.rugged, false)))::int as wins,- round(avg(power((c.score / 100.0) - (case when o.graduated or (o.ath_multiple >= 2 and not coalesce(o.rugged, false)) then 1 else 0 end), 2))::numeric, 4) as brier- from oracle_conviction c- join pump_coin_outcomes o on o.mint = c.mint- where c.network = ${network}- and (o.graduated or o.rugged or o.ath_multiple is not null)- ${quoteFilter}- ${periodFilter}- `.then((r) => r[0] || {}).catch(() => ({}));+ // Brier against the event the model was trained on, using each score's own+ // claimed probability. Lower is better; 0.25 is a coin flip.+ let brierSum = 0;+ let brierN = 0;+ for (const r of scoreRows) {+ const p = probabilityFromScore(Number(r.score));+ brierSum += r.spikes * (1 - p) ** 2 + (r.n - r.spikes) * p ** 2;+ brierN += r.n;+ }+ const brier = brierN ? Number((brierSum / brierN).toFixed(4)) : null;- const baselineN = Number(baseRow.n) || 0;- const baselineWinRate = baselineN ? Math.round((Number(baseRow.wins) / baselineN) * 100) : null;- const brier = baseRow.brier != null ? Number(baseRow.brier) : null;+ // Market baseline: a coin drawn at random from everything Oracle scored.+ const baselineN = brierN;+ const baselineWins = scoreRows.reduce((a, r) => a + r.wins, 0);+ const baselineSpikes = scoreRows.reduce((a, r) => a + r.spikes, 0);+ const baselineWinRate = baselineN ? Math.round((baselineWins / baselineN) * 100) : null;+ const baselineSpikeRate = baselineN ? Math.round((baselineSpikes / baselineN) * 100) : null;// Edge summary: does conviction actually beat blind buying, and does the ladder- // climb in the right order?+ // climb in the right order? Reported on both metrics, because the engine ranks+ // the spike and the page quotes the clean win.const primeRow = rows.find((r) => r.tier === 'prime');const primeResolved = primeRow ? primeRow.wins + primeRow.losses : 0;const primeWinRate = primeResolved ? Math.round((primeRow.wins / primeResolved) * 100) : null;- const orderedRealized = calibration.map((c) => c.realized).filter((v) => v != null);- const monotonic = orderedRealized.length >= 2- && orderedRealized.every((v, i) => i === 0 || v >= orderedRealized[i - 1] - 5); // ≤5pt tolerance+ const primeSpikeRate = primeRow?.total ? Math.round((primeRow.three_x / primeRow.total) * 100) : null;+ const primeRugRate = primeRow?.total ? Math.round((primeRow.rugged / primeRow.total) * 100) : null;+ const cleanLadder = ladderCheck(bands, 'realized', 'ci');+ const spikeLadder = ladderCheck(bands, 'realized_spike', 'spike_ci');const edge = {+ predicts: PREDICTED_EVENT,baseline_win_rate: baselineWinRate,+ baseline_spike_rate: baselineSpikeRate,baseline_n: baselineN,prime_win_rate: primeWinRate,+ prime_spike_rate: primeSpikeRate,+ prime_rug_rate: primeRugRate,prime_lift: (primeWinRate != null && baselineWinRate != null) ? primeWinRate - baselineWinRate : null,edge_multiple: (primeWinRate != null && baselineWinRate) ? Number((primeWinRate / baselineWinRate).toFixed(2)) : null,- monotonic,+ spike_edge_multiple: (primeSpikeRate != null && baselineSpikeRate) ? Number((primeSpikeRate / baselineSpikeRate).toFixed(2)) : null,+ monotonic: cleanLadder.monotonic,+ ladder: { clean_win: cleanLadder, spike: spikeLadder },brier,+ brier_of: PREDICTED_EVENT.id,};// ── top performers in the period ─────────────────────────────────────────@@ -225,8 +286,17 @@ async function query(days, tier, network) {ten_x: r.ten_x,graduated: r.graduated,rugged: r.rugged,+ // Rates on the full resolved sample for this tier. spike_rate is the event+ // the score was fitted to predict, rug_rate is the part a holder feels and+ // the score never claimed to rule out. A tier card that shows only one of+ // the three is the reason a 100/prime call on a dead chart reads as a lie.+ spike_rate: r.total ? Math.round((r.three_x / r.total) * 100) : null,+ spike_ci: wilson(r.three_x, r.total),+ rug_rate: r.total ? Math.round((r.rugged / r.total) * 100) : null,+ graduated_rate: r.total ? Math.round((r.graduated / r.total) * 100) : null,})),aggregate: agg,+ predicts: PREDICTED_EVENT,calibration,edge,top_performers: top.map((r) => ({diff --git a/scripts/oracle-calibrate.mjs b/scripts/oracle-calibrate.mjsnew file mode 100644index 000000000..929b0e450--- /dev/null+++ b/scripts/oracle-calibrate.mjs@@ -0,0 +1,190 @@+// Fit the Oracle conviction CALIBRATION from realized production outcomes.+//+// scripts/oracle-fit.mjs fits the model's per-bucket weights against the+// labeled training set, where "good" = graduated or hit >= 3x ATH. This script+// answers the different, harder question the product actually makes to a user:+// of the coins Oracle has already scored and the market has already resolved,+// what fraction of each score band WON, where a win is the platform's own+// definition (graduated, or >= 2x ATH without rugging)?+//+// The two numbers were never the same, and nothing reconciled them, so a card+// reading "conviction 99" was quoting a training-label probability of 95%++// while the same band realized 26%. This script measures the realized rate,+// smooths it into a monotone ladder with pool-adjacent-violators (isotonic+// regression), and writes conviction-calibration.json. conviction.js then+// serves the realized hit rate alongside every score, and the public tier+// boundaries are set from the plateaus this fit exposes.+//+// node scripts/oracle-calibrate.mjs # fit + report+// node scripts/oracle-calibrate.mjs --write # also update the shipped JSON+//+// Data source: the production database when DATABASE_URL is set, otherwise the+// live /api/oracle/backtest endpoint, which runs this exact aggregation+// server-side. Both read the same two tables; neither invents a number.++import { readFileSync, writeFileSync } from 'node:fs';++const OUT_PATH = new URL('../api/_lib/oracle/conviction-calibration.json', import.meta.url);+const NETWORK = process.env.ORACLE_NETWORK || 'mainnet';+const API_ORIGIN = process.env.ORACLE_API_ORIGIN || 'https://three.ws';++// Keep in sync with api/oracle/backtest.js and tests/oracle/win-definition.test.js.+const WIN_DEFINITION = 'graduated or (ath_multiple >= 2 and not rugged)';++function databaseUrl() {+ if (process.env.DATABASE_URL) return process.env.DATABASE_URL;+ for (const file of ['../.env.local', '../.env']) {+ try {+ const m = readFileSync(new URL(file, import.meta.url), 'utf8').match(/^DATABASE_URL=(.+)$/m);+ if (m) return m[1].trim().replace(/^["']|["']$/g, '');+ } catch { /* try the next candidate */ }+ }+ return null;+}++/** Read the per-band resolved counts straight from the database. */+async function loadFromDb(url) {+ const { neon } = await import('@neondatabase/serverless');+ const sql = neon(url);+ const rows = await sql`+ select+ least(width_bucket(c.score, 0, 100, 10), 10) as bucket,+ count(*)::int as n,+ count(*) filter (where o.graduated or (o.ath_multiple >= 2 and not coalesce(o.rugged, false)))::int as wins+ from oracle_conviction c+ join pump_coin_outcomes o on o.mint = c.mint+ where c.network = ${NETWORK}+ and (o.graduated or o.rugged or o.ath_multiple is not null)+ group by 1+ order by 1+ `;+ const bands = rows+ .filter((r) => r.bucket >= 1 && r.bucket <= 10)+ .map((r) => ({ lo: (r.bucket - 1) * 10, hi: r.bucket * 10, n: Number(r.n), wins: Number(r.wins) }));+ return { source: 'database', bands };+}++/** Read the same aggregation from the live backtest endpoint. */+async function loadFromApi() {+ const url = `${API_ORIGIN}/api/oracle/backtest?period=all&network=${NETWORK}`;+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`backtest endpoint answered ${res.status} (${url})`);+ const body = await res.json();+ if (!Array.isArray(body.calibration) || !body.calibration.length) {+ throw new Error('backtest endpoint returned no calibration bands');+ }+ const bands = body.calibration.map((c) => ({ lo: c.lo, hi: c.hi, n: Number(c.n), wins: Number(c.wins) }));+ return { source: `api:${API_ORIGIN}`, bands };+}++/**+ * Pool-adjacent-violators: the standard isotonic-regression fit. Returns a+ * non-decreasing rate per band, sample-weighted, so a band that dips below its+ * neighbour (noise, not signal) is merged with it instead of published as a+ * ladder that goes backwards.+ *+ * @param {Array<{n:number, wins:number}>} bands+ * @returns {number[]} calibrated rate per input band+ */+export function isotonic(bands) {+ const blocks = bands.map((b) => ({ n: b.n, wins: b.wins, span: 1 }));+ for (let i = 1; i < blocks.length; i++) {+ while (i > 0 && rate(blocks[i - 1]) > rate(blocks[i])) {+ const merged = {+ n: blocks[i - 1].n + blocks[i].n,+ wins: blocks[i - 1].wins + blocks[i].wins,+ span: blocks[i - 1].span + blocks[i].span,+ };+ blocks.splice(i - 1, 2, merged);+ i -= 1;+ }+ }+ const out = [];+ for (const b of blocks) for (let k = 0; k < b.span; k++) out.push(rate(b));+ return out;+}++function rate(block) {+ return block.n > 0 ? block.wins / block.n : 0;+}++/**+ * Group adjacent bands the data cannot tell apart: the ladder's real rungs.+ * Isotonic already merges outright violations, but it leaves neighbours that+ * differ by a fraction of a point as separate blocks, and those are not+ * separate claims about the world. Bands within `tol` relative distance of each+ * other collapse into one rung, so the report shows the boundaries a tier+ * ladder can actually stand on.+ */+function plateaus(bands, tol = 0.05) {+ const out = [];+ for (const b of bands) {+ const last = out[out.length - 1];+ const close = last && Math.abs(last.calibrated - b.calibrated) <= tol * Math.max(last.calibrated, b.calibrated);+ if (close) {+ // Weighted mean of the CALIBRATED rates, never a re-pool of the raw+ // wins: recomputing wins/n here would undo the isotonic fit and can+ // hand back a rung ladder that steps backwards.+ last.calibrated = (last.calibrated * last.n + b.calibrated * b.n) / (last.n + b.n);+ last.hi = b.hi; last.n += b.n; last.wins += b.wins;+ } else {+ out.push({ lo: b.lo, hi: b.hi, n: b.n, wins: b.wins, calibrated: b.calibrated });+ }+ }+ return out;+}++const dbUrl = databaseUrl();+const { source, bands: raw } = dbUrl ? await loadFromDb(dbUrl) : await loadFromApi();++const resolved = raw.reduce((a, b) => a + b.n, 0);+const wins = raw.reduce((a, b) => a + b.wins, 0);+if (resolved < 5000) {+ console.error(`Only ${resolved} resolved coins; refusing to calibrate on so little.`);+ process.exit(2);+}+const baseRate = wins / resolved;+const smoothed = isotonic(raw);+const bands = raw.map((b, i) => ({+ lo: b.lo,+ hi: b.hi,+ n: b.n,+ wins: b.wins,+ observed: Number((b.wins / b.n).toFixed(4)),+ calibrated: Number(smoothed[i].toFixed(4)),+ lift: Number((smoothed[i] / baseRate).toFixed(2)),+}));++console.log(`source: ${source}`);+console.log(`resolved coins: ${resolved.toLocaleString()} wins: ${wins.toLocaleString()} base rate: ${(100 * baseRate).toFixed(2)}%`);+console.log('\nband n observed calibrated lift');+for (const b of bands) {+ console.log(+ `${String(b.lo).padStart(3)}-${String(b.hi).padEnd(4)} ${String(b.n).padStart(7)} ` ++ `${(100 * b.observed).toFixed(1).padStart(7)}% ${(100 * b.calibrated).toFixed(1).padStart(8)}% ${b.lift.toFixed(2)}x`,+ );+}+console.log('\nladder rungs (adjacent bands the data cannot tell apart):');+for (const p of plateaus(bands)) {+ console.log(` ${p.lo}-${p.hi}: ${(100 * p.calibrated).toFixed(1)}% over n=${p.n} (${(p.calibrated / baseRate).toFixed(2)}x base)`);+}+console.log('\nTier boundaries in conviction.js should sit on these rung edges.');++const out = {+ version: 1,+ fitted_at: new Date().toISOString(),+ source,+ network: NETWORK,+ win_definition: WIN_DEFINITION,+ resolved_n: resolved,+ wins_n: wins,+ base_rate: Number(baseRate.toFixed(4)),+ bands,+};++if (process.argv.includes('--write')) {+ writeFileSync(OUT_PATH, JSON.stringify(out, null, '\t') + '\n');+ console.log(`\nwrote ${OUT_PATH.pathname}`);+} else {+ console.log('\n(dry run; pass --write to update conviction-calibration.json)');+}