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(oracle): rank conviction on what a holder kept, not on the price of SOL
nirholas202719770303
diff --git a/api/_lib/migrations/20260828180000_oracle_conviction_risk_columns.sql b/api/_lib/migrations/20260828180000_oracle_conviction_risk_columns.sqlnew file mode 100644index 000000000..f2630dbaa--- /dev/null+++ b/api/_lib/migrations/20260828180000_oracle_conviction_risk_columns.sql@@ -0,0 +1,43 @@+-- Oracle conviction: store the risk numbers, not just the score.+--+-- v3 of the conviction engine produces three probabilities per coin instead of+-- one (a run, a run you get to keep, and a collapse). Two of them only existed+-- in the response object, which meant the feed could not sort, filter, or alert+-- on them, and a card had to re-score a coin to find out whether the thing it+-- was recommending typically hands the run straight back.+--+-- rug_risk P(a holder from first sight ends down more than half), 0-100+-- upside P(graduates or peaks at 3x or more), 0-100+-- give_back_risk P(gives the run back | it runs), 0-100+-- model_version_id which oracle_model_versions row produced this verdict+--+-- give_back_risk is the one worth having in a column. It is the difference+-- between "this will probably run" and "this will probably still be worth+-- something", and sorting the live feed by it surfaces the exact trap that made+-- a high score feel dishonest: coins that reliably spike and reliably round-trip.+--+-- model_version_id makes every stored verdict reproducible. Given a mint you can+-- fetch the exact weights that scored it (GET /api/oracle/model?view=registry)+-- and recompute it offline, which is the difference between a published track+-- record and a claim about one.++alter table oracle_conviction add column if not exists rug_risk smallint;+alter table oracle_conviction add column if not exists upside smallint;+alter table oracle_conviction add column if not exists give_back_risk smallint;+alter table oracle_conviction add column if not exists model_version_id bigint;++-- The feed's two new orderings: safest high-conviction calls first, and the+-- give-back trap list. Partial, because a null risk is a pre-v3 row and sorting+-- it in with the rest would silently rank unmeasured coins as safe.+create index if not exists idx_oracle_conviction_rug_risk+ on oracle_conviction (network, rug_risk asc, score desc)+ where rug_risk is not null;+create index if not exists idx_oracle_conviction_give_back+ on oracle_conviction (network, give_back_risk desc, score desc)+ where give_back_risk is not null;++-- Same three numbers on the history table, so a coin's risk profile can be+-- charted over its life the way its score already is.+alter table oracle_conviction_history add column if not exists rug_risk smallint;+alter table oracle_conviction_history add column if not exists upside smallint;+alter table oracle_conviction_history add column if not exists give_back_risk smallint;diff --git a/api/_lib/oracle/conviction-model.json b/api/_lib/oracle/conviction-model.jsonindex c33247282..d68728226 100644--- a/api/_lib/oracle/conviction-model.json+++ b/api/_lib/oracle/conviction-model.json@@ -1,15 +1,28 @@{- "version": 2,- "fitted_at": "2026-08-09T09:18:07.273Z",- "training_rows": 92906,- "base_good_rate": 0.1174,- "intercept": -2.2751,+ "version": 3,+ "fitted_at": "2026-08-28T03:16:40.867Z",+ "training_rows": 296843,+ "score_head": "win",+ "heads": {+ "win": {+ "intercept": -3.9975,+ "base_rate": 0.0294+ },+ "rug": {+ "intercept": -3.123,+ "base_rate": 0.1136+ },+ "moon": {+ "intercept": -2.486,+ "base_rate": 0.0951+ }+ },"tier_probability_anchors": {"avoid": 0,"watch": 0.05,"lean": 0.12,- "strong": 0.3,- "prime": 0.55+ "strong": 0.25,+ "prime": 0.45},"features": [{@@ -23,30 +36,70 @@0.8],"buckets": {- "0.6-0.8": {- "w": 0.2377,- "n": 9506,- "good_rate": 0.2713- },"0.4-0.6": {- "w": 0.1197,- "n": 32534,- "good_rate": 0.1065+ "n": 104393,+ "w": {+ "win": -0.1367,+ "rug": -0.06,+ "moon": -0.0779+ },+ "rate": {+ "win": 0.0206,+ "rug": 0.0707,+ "moon": 0.0841+ }},"0.2-0.4": {- "w": -0.0776,- "n": 45219,- "good_rate": 0.0744+ "n": 141479,+ "w": {+ "win": 0.3146,+ "rug": 0.3386,+ "moon": 0.2147+ },+ "rate": {+ "win": 0.0251,+ "rug": 0.1345,+ "moon": 0.0608+ }},- ">=0.8": {- "w": 0.4562,- "n": 2436,- "good_rate": 0.5969+ "0.6-0.8": {+ "n": 32075,+ "w": {+ "win": -0.3581,+ "rug": -1.0394,+ "moon": -0.1145+ },+ "rate": {+ "win": 0.0528,+ "rug": 0.1211,+ "moon": 0.2065+ }},"<0.2": {- "w": -1.1845,- "n": 3211,- "good_rate": 0.0134+ "n": 10576,+ "w": {+ "win": -0.9531,+ "rug": 0.6685,+ "moon": -0.903+ },+ "rate": {+ "win": 0.0019,+ "rug": 0.0771,+ "moon": 0.0075+ }+ },+ ">=0.8": {+ "n": 8320,+ "w": {+ "win": -0.2516,+ "rug": -1.5174,+ "moon": -0.4464+ },+ "rate": {+ "win": 0.1583,+ "rug": 0.3118,+ "moon": 0.4968+ }}}},@@ -61,24 +114,56 @@],"buckets": {"<0.1": {- "w": 0.0806,- "n": 70977,- "good_rate": 0.0895- },- "0.3-0.5": {- "w": -0.1174,- "n": 8967,- "good_rate": 0.1549+ "n": 214358,+ "w": {+ "win": 0.1729,+ "rug": 0.3143,+ "moon": 0.1228+ },+ "rate": {+ "win": 0.025,+ "rug": 0.1534,+ "moon": 0.0724+ }},">=0.5": {- "w": -0.5561,- "n": 7870,- "good_rate": 0.04+ "n": 35517,+ "w": {+ "win": -0.3827,+ "rug": -0.9415,+ "moon": -0.5215+ },+ "rate": {+ "win": 0.0071,+ "rug": 0.0055,+ "moon": 0.0302+ }},"0.1-0.3": {- "w": 0.1582,- "n": 5092,- "good_rate": 0.5593+ "n": 18285,+ "w": {+ "win": -0.3709,+ "rug": -0.0755,+ "moon": -0.2633+ },+ "rate": {+ "win": 0.1293,+ "rug": 0.0202,+ "moon": 0.4469+ }+ },+ "0.3-0.5": {+ "n": 28683,+ "w": {+ "win": -0.1583,+ "rug": -0.7995,+ "moon": -0.2422+ },+ "rate": {+ "win": 0.0258,+ "rug": 0.0087,+ "moon": 0.1202+ }}}},@@ -92,25 +177,57 @@0.7],"buckets": {+ "<0.1": {+ "n": 47060,+ "w": {+ "win": 0.3035,+ "rug": 1.7695,+ "moon": 0.7543+ },+ "rate": {+ "win": 0.016,+ "rug": 0.0669,+ "moon": 0.0558+ }+ },"0.3-0.7": {- "w": 0.1738,- "n": 9136,- "good_rate": 0.3405+ "n": 29374,+ "w": {+ "win": 0.2603,+ "rug": 0.203,+ "moon": 0.2159+ },+ "rate": {+ "win": 0.0765,+ "rug": 0.158,+ "moon": 0.2779+ }},">=0.7": {- "w": -0.2606,- "n": 64916,- "good_rate": 0.0857+ "n": 210063,+ "w": {+ "win": -0.1358,+ "rug": -0.6533,+ "moon": -0.2456+ },+ "rate": {+ "win": 0.0231,+ "rug": 0.1072,+ "moon": 0.0656+ }},"0.1-0.3": {- "w": 0.3829,- "n": 3124,- "good_rate": 0.4209- },- "<0.1": {- "w": 0.3314,- "n": 15730,- "good_rate": 0.0582+ "n": 10346,+ "w": {+ "win": 0.5702,+ "rug": 1.1768,+ "moon": 0.7473+ },+ "rate": {+ "win": 0.0841,+ "rug": 0.328,+ "moon": 0.352+ }}}},@@ -124,19 +241,43 @@],"buckets": {"<0.1": {- "w": 0.0543,- "n": 71865,- "good_rate": 0.0977- },- "0.1-0.3": {- "w": 0.0411,- "n": 13171,- "good_rate": 0.271+ "n": 217879,+ "w": {+ "win": -0.0018,+ "rug": 0.3189,+ "moon": 0.0731+ },+ "rate": {+ "win": 0.0274,+ "rug": 0.1514,+ "moon": 0.0811+ }},">=0.3": {- "w": -0.5561,- "n": 7870,- "good_rate": 0.04+ "n": 35517,+ "w": {+ "win": -0.3827,+ "rug": -0.9415,+ "moon": -0.5215+ },+ "rate": {+ "win": 0.0071,+ "rug": 0.0055,+ "moon": 0.0302+ }+ },+ "0.1-0.3": {+ "n": 43447,+ "w": {+ "win": 0.0025,+ "rug": -0.5862,+ "moon": -0.0171+ },+ "rate": {+ "win": 0.0574,+ "rug": 0.012,+ "moon": 0.2179+ }}}},@@ -151,30 +292,70 @@0.8],"buckets": {- "0.4-0.6": {- "w": 0.152,- "n": 12501,- "good_rate": 0.2061- },- ">=0.8": {- "w": 0.3331,- "n": 4136,- "good_rate": 0.2979- },"<0.2": {- "w": -0.2718,- "n": 57605,- "good_rate": 0.0532+ "n": 173972,+ "w": {+ "win": -0.0813,+ "rug": -0.1044,+ "moon": -0.1593+ },+ "rate": {+ "win": 0.0212,+ "rug": 0.1173,+ "moon": 0.047+ }},"0.6-0.8": {- "w": 0.509,- "n": 6977,- "good_rate": 0.4178+ "n": 25542,+ "w": {+ "win": 0.0514,+ "rug": 0.336,+ "moon": 0.1162+ },+ "rate": {+ "win": 0.0761,+ "rug": 0.1436,+ "moon": 0.2977+ }+ },+ "0.4-0.6": {+ "n": 39277,+ "w": {+ "win": 0.0938,+ "rug": 0.2924,+ "moon": 0.1859+ },+ "rate": {+ "win": 0.0369,+ "rug": 0.1207,+ "moon": 0.1618+ }+ },+ ">=0.8": {+ "n": 19825,+ "w": {+ "win": -0.2697,+ "rug": -0.9152,+ "moon": 0.023+ },+ "rate": {+ "win": 0.0454,+ "rug": 0.0379,+ "moon": 0.1628+ }},"0.2-0.4": {- "w": -0.0261,- "n": 11687,- "good_rate": 0.0957+ "n": 38227,+ "w": {+ "win": 0.0092,+ "rug": -0.0858,+ "moon": 0.0992+ },+ "rate": {+ "win": 0.0193,+ "rug": 0.1083,+ "moon": 0.0745+ }}}},@@ -188,25 +369,121 @@0.3],"buckets": {+ "<0.05": {+ "n": 49280,+ "w": {+ "win": 0.8327,+ "rug": -0.1328,+ "moon": 0.3694+ },+ "rate": {+ "win": 0.0095,+ "rug": 0.0167,+ "moon": 0.0229+ }+ },">=0.3": {- "w": -0.0473,- "n": 67457,- "good_rate": 0.103+ "n": 219495,+ "w": {+ "win": -0.2919,+ "rug": 0.2121,+ "moon": -0.3634+ },+ "rate": {+ "win": 0.0256,+ "rug": 0.1485,+ "moon": 0.0793+ }+ },+ "0.15-0.3": {+ "n": 23369,+ "w": {+ "win": -0.1563,+ "rug": -1.0428,+ "moon": 0.4375+ },+ "rate": {+ "win": 0.0825,+ "rug": 0.0103,+ "moon": 0.301+ }},"0.05-0.15": {- "w": 0.7901,- "n": 1086,- "good_rate": 0.7413+ "n": 4699,+ "w": {+ "win": -0.2396,+ "rug": -0.5402,+ "moon": 0.5215+ },+ "rate": {+ "win": 0.1483,+ "rug": 0.0102,+ "moon": 0.5633+ }+ }+ }+ },+ {+ "key": "concentration_top5",+ "pillar": "structure",+ "categorical": false,+ "edges": [+ 0.3,+ 0.6,+ 0.9+ ],+ "buckets": {+ "<0.3": {+ "n": 50065,+ "w": {+ "win": -0.6212,+ "rug": -0.7461,+ "moon": 0.1288+ },+ "rate": {+ "win": 0.0103,+ "rug": 0.0165,+ "moon": 0.0329+ }},- "0.15-0.3": {- "w": 0.3856,- "n": 7182,- "good_rate": 0.3823+ ">=0.9": {+ "n": 214466,+ "w": {+ "win": -0.0725,+ "rug": 0.2383,+ "moon": -0.1849+ },+ "rate": {+ "win": 0.0235,+ "rug": 0.1482,+ "moon": 0.0731+ }},- "<0.05": {- "w": -0.371,- "n": 17181,- "good_rate": 0.0235+ "0.6-0.9": {+ "n": 25195,+ "w": {+ "win": 0.4612,+ "rug": -0.1487,+ "moon": -0.0706+ },+ "rate": {+ "win": 0.0752,+ "rug": 0.0403,+ "moon": 0.2735+ }+ },+ "0.3-0.6": {+ "n": 7117,+ "w": {+ "win": 0.7105,+ "rug": -0.2927,+ "moon": -0.1247+ },+ "rate": {+ "win": 0.1799,+ "rug": 0.0118,+ "moon": 0.5629+ }}}},@@ -219,20 +496,44 @@0.9],"buckets": {+ "<0.3": {+ "n": 49251,+ "w": {+ "win": 0.1248,+ "rug": 0.1797,+ "moon": -0.7404+ },+ "rate": {+ "win": 0.0091,+ "rug": 0.0167,+ "moon": 0.0217+ }+ },">=0.9": {- "w": 0.033,- "n": 72404,- "good_rate": 0.1121+ "n": 235455,+ "w": {+ "win": -0.0771,+ "rug": -0.0208,+ "moon": 0.2315+ },+ "rate": {+ "win": 0.0262,+ "rug": 0.1387,+ "moon": 0.0863+ }},"0.3-0.9": {- "w": 0.2311,- "n": 3330,- "good_rate": 0.718- },- "<0.3": {- "w": -0.3981,- "n": 17172,- "good_rate": 0.0231+ "n": 12137,+ "w": {+ "win": -0.0001,+ "rug": -0.0679,+ "moon": -0.1985+ },+ "rate": {+ "win": 0.1729,+ "rug": 0.0187,+ "moon": 0.5627+ }}}},@@ -247,30 +548,134 @@40],"buckets": {+ "<1": {+ "n": 40326,+ "w": {+ "win": -2.2687,+ "rug": 0.0144,+ "moon": -2.8002+ },+ "rate": {+ "win": 0.0043,+ "rug": 0.0144,+ "moon": 0.0109+ }+ },"5-15": {- "w": 0.1431,- "n": 18767,- "good_rate": 0.0848+ "n": 65305,+ "w": {+ "win": -0.5071,+ "rug": -0.4024,+ "moon": 0.0261+ },+ "rate": {+ "win": 0.0096,+ "rug": 0.1048,+ "moon": 0.0661+ }},"1-5": {- "w": 0.8451,- "n": 50749,- "good_rate": 0.092- },- ">=40": {- "w": 1.4945,- "n": 2304,- "good_rate": 0.8008+ "n": 156320,+ "w": {+ "win": 0.7767,+ "rug": 0.2358,+ "moon": 0.6456+ },+ "rate": {+ "win": 0.0288,+ "rug": 0.1567,+ "moon": 0.0675+ }},"15-40": {- "w": 0.7086,- "n": 7197,- "good_rate": 0.3692+ "n": 25670,+ "w": {+ "win": 0.0446,+ "rug": -0.2488,+ "moon": 0.3464+ },+ "rate": {+ "win": 0.0633,+ "rug": 0.0626,+ "moon": 0.2724+ }},+ ">=40": {+ "n": 9222,+ "w": {+ "win": 0.3877,+ "rug": -0.5794,+ "moon": 0.6149+ },+ "rate": {+ "win": 0.1954,+ "rug": 0.019,+ "moon": 0.6425+ }+ }+ }+ },+ {+ "key": "unique_sellers",+ "pillar": "momentum",+ "categorical": false,+ "edges": [+ 1,+ 3,+ 10+ ],+ "buckets": {"<1": {- "w": -3.797,- "n": 13889,- "good_rate": 0.0105+ "n": 143561,+ "w": {+ "win": -0.9611,+ "rug": -0.4996,+ "moon": -1.049+ },+ "rate": {+ "win": 0.0226,+ "rug": 0.1091,+ "moon": 0.051+ }+ },+ "1-3": {+ "n": 67382,+ "w": {+ "win": 0.7801,+ "rug": 0.257,+ "moon": 0.7822+ },+ "rate": {+ "win": 0.0233,+ "rug": 0.1304,+ "moon": 0.0617+ }+ },+ ">=10": {+ "n": 32883,+ "w": {+ "win": 0.5473,+ "rug": 0.1926,+ "moon": 0.6872+ },+ "rate": {+ "win": 0.0879,+ "rug": 0.0846,+ "moon": 0.3605+ }+ },+ "3-10": {+ "n": 53017,+ "w": {+ "win": 0.9144,+ "rug": 0.6824,+ "moon": 1.0169+ },+ "rate": {+ "win": 0.0192,+ "rug": 0.122,+ "moon": 0.0919+ }}}},@@ -285,35 +690,83 @@4],"buckets": {- "1-2": {- "w": -0.8366,- "n": 15152,- "good_rate": 0.1354+ "<0.5": {+ "n": 43346,+ "w": {+ "win": 2.0214,+ "rug": -0.0407,+ "moon": 2.5976+ },+ "rate": {+ "win": 0.0122,+ "rug": 0.0199,+ "moon": 0.0489+ }+ },+ ">=4": {+ "n": 52556,+ "w": {+ "win": -1.3575,+ "rug": 0.1939,+ "moon": -1.2844+ },+ "rate": {+ "win": 0.0241,+ "rug": 0.1337,+ "moon": 0.094+ }},"null": {- "w": -0.7228,- "n": 33057,- "good_rate": 0.0831+ "n": 103973,+ "w": {+ "win": 0.2772,+ "rug": 0.0058,+ "moon": 0.1719+ },+ "rate": {+ "win": 0.031,+ "rug": 0.1473,+ "moon": 0.0687+ }},"2-4": {- "w": -0.653,- "n": 7638,- "good_rate": 0.2656- },- "<0.5": {- "w": 3.2923,- "n": 14879,- "good_rate": 0.0528+ "n": 24933,+ "w": {+ "win": -1.0383,+ "rug": 0.0545,+ "moon": -1.1755+ },+ "rate": {+ "win": 0.0571,+ "rug": 0.1243,+ "moon": 0.1961+ }},"0.5-1": {- "w": 0.0476,- "n": 3579,- "good_rate": 0.2587+ "n": 12703,+ "w": {+ "win": 0.7383,+ "rug": 0.2115,+ "moon": 0.2917+ },+ "rate": {+ "win": 0.0483,+ "rug": 0.1505,+ "moon": 0.2167+ }},- ">=4": {- "w": -0.7625,- "n": 18601,- "good_rate": 0.1273+ "1-2": {+ "n": 59332,+ "w": {+ "win": -0.7774,+ "rug": -0.4707,+ "moon": -0.8346+ },+ "rate": {+ "win": 0.0281,+ "rug": 0.0926,+ "moon": 0.1074+ }}}},@@ -328,24 +781,262 @@],"buckets": {"<0.5": {- "w": -0.5546,- "n": 45734,- "good_rate": 0.0646+ "n": 137424,+ "w": {+ "win": -0.2886,+ "rug": -0.0555,+ "moon": -0.289+ },+ "rate": {+ "win": 0.017,+ "rug": 0.1527,+ "moon": 0.048+ }},- ">=25": {- "w": 2.0867,- "n": 5319,- "good_rate": 0.7011+ "0.5-8": {+ "n": 90723,+ "w": {+ "win": -0.5187,+ "rug": 0.0446,+ "moon": -0.4767+ },+ "rate": {+ "win": 0.0167,+ "rug": 0.1193,+ "moon": 0.0547+ }},"8-25": {- "w": 0.3141,- "n": 16719,- "good_rate": 0.122+ "n": 52143,+ "w": {+ "win": 0.8317,+ "rug": -0.1278,+ "moon": 0.498+ },+ "rate": {+ "win": 0.031,+ "rug": 0.0222,+ "moon": 0.1079+ }},- "0.5-8": {- "w": -0.1651,- "n": 25134,- "good_rate": 0.0869+ ">=25": {+ "n": 16553,+ "w": {+ "win": 1.7485,+ "rug": -0.001,+ "moon": 2.1964+ },+ "rate": {+ "win": 0.1969,+ "rug": 0.0449,+ "moon": 0.6665+ }+ }+ }+ },+ {+ "key": "sell_volume_sol",+ "pillar": "momentum",+ "categorical": false,+ "edges": [+ 0.1,+ 2,+ 10+ ],+ "buckets": {+ "<0.1": {+ "n": 172638,+ "w": {+ "win": 0.2978,+ "rug": 0.2038,+ "moon": 0.2997+ },+ "rate": {+ "win": 0.0229,+ "rug": 0.1361,+ "moon": 0.0563+ }+ },+ "0.1-2": {+ "n": 56325,+ "w": {+ "win": -0.3713,+ "rug": -0.3984,+ "moon": -0.4308+ },+ "rate": {+ "win": 0.0183,+ "rug": 0.1335,+ "moon": 0.0707+ }+ },+ "2-10": {+ "n": 42841,+ "w": {+ "win": -0.4351,+ "rug": -0.6723,+ "moon": -0.7846+ },+ "rate": {+ "win": 0.0346,+ "rug": 0.0457,+ "moon": 0.121+ }+ },+ ">=10": {+ "n": 25039,+ "w": {+ "win": -0.5259,+ "rug": -0.0882,+ "moon": -0.0356+ },+ "rate": {+ "win": 0.0905,+ "rug": 0.0293,+ "moon": 0.3731+ }+ }+ }+ },+ {+ "key": "net_volume_sol",+ "pillar": "momentum",+ "categorical": false,+ "edges": [+ 0,+ 1,+ 5,+ 20+ ],+ "buckets": {+ "0-1": {+ "n": 175527,+ "w": {+ "win": -0.4372,+ "rug": 0.6616,+ "moon": -0.2607+ },+ "rate": {+ "win": 0.0145,+ "rug": 0.1486,+ "moon": 0.0454+ }+ },+ "5-20": {+ "n": 50983,+ "w": {+ "win": 0.8083,+ "rug": -1.7768,+ "moon": 0.6153+ },+ "rate": {+ "win": 0.0435,+ "rug": 0.0216,+ "moon": 0.1375+ }+ },+ "<0": {+ "n": 17876,+ "w": {+ "win": -0.6776,+ "rug": 0.172,+ "moon": -0.3633+ },+ "rate": {+ "win": 0.0525,+ "rug": 0.1259,+ "moon": 0.2492+ }+ },+ "1-5": {+ "n": 44042,+ "w": {+ "win": 0.4082,+ "rug": -0.0266,+ "moon": -0.066+ },+ "rate": {+ "win": 0.0198,+ "rug": 0.0828,+ "moon": 0.0495+ }+ },+ ">=20": {+ "n": 8415,+ "w": {+ "win": 1.3755,+ "rug": -1.4054,+ "moon": 1.9231+ },+ "rate": {+ "win": 0.2557,+ "rug": 0.0742,+ "moon": 0.7841+ }+ }+ }+ },+ {+ "key": "trade_count",+ "pillar": "momentum",+ "categorical": false,+ "edges": [+ 3,+ 12,+ 40+ ],+ "buckets": {+ "<3": {+ "n": 144408,+ "w": {+ "win": -0.084,+ "rug": -0.0135,+ "moon": -0.2242+ },+ "rate": {+ "win": 0.0206,+ "rug": 0.1102,+ "moon": 0.0441+ }+ },+ "3-12": {+ "n": 80139,+ "w": {+ "win": -0.0513,+ "rug": -0.5715,+ "moon": -0.2054+ },+ "rate": {+ "win": 0.0234,+ "rug": 0.1175,+ "moon": 0.065+ }+ },+ ">=40": {+ "n": 26478,+ "w": {+ "win": 0.1465,+ "rug": 0.9577,+ "moon": 0.8998+ },+ "rate": {+ "win": 0.1099,+ "rug": 0.1499,+ "moon": 0.4513+ }+ },+ "12-40": {+ "n": 45818,+ "w": {+ "win": -0.0249,+ "rug": 0.2455,+ "moon": 0.3301+ },+ "rate": {+ "win": 0.0212,+ "rug": 0.0962,+ "moon": 0.1024+ }}}},@@ -360,24 +1051,56 @@],"buckets": {"<0.2": {- "w": -0.3603,- "n": 40581,- "good_rate": 0.0594+ "n": 121120,+ "w": {+ "win": -0.2204,+ "rug": -0.4914,+ "moon": -0.3618+ },+ "rate": {+ "win": 0.0148,+ "rug": 0.1404,+ "moon": 0.0457+ }},"2.5-5": {- "w": 0.2481,- "n": 17041,- "good_rate": 0.1525+ "n": 58366,+ "w": {+ "win": 0.2784,+ "rug": 0.0202,+ "moon": 0.486+ },+ "rate": {+ "win": 0.0393,+ "rug": 0.0374,+ "moon": 0.1352+ }},"0.2-2.5": {- "w": -0.3454,- "n": 24812,- "good_rate": 0.1167+ "n": 86505,+ "w": {+ "win": -0.2297,+ "rug": -0.0938,+ "moon": -0.3437+ },+ "rate": {+ "win": 0.0234,+ "rug": 0.1436,+ "moon": 0.073+ }},">=5": {- "w": 1.176,- "n": 10472,- "good_rate": 0.2865+ "n": 30852,+ "w": {+ "win": 0.5106,+ "rug": 1.4842,+ "moon": 0.8578+ },+ "rate": {+ "win": 0.0847,+ "rug": 0.068,+ "moon": 0.2747+ }}}},@@ -391,51 +1114,107 @@],"buckets": {"<0.05": {- "w": 0.0978,- "n": 30929,- "good_rate": 0.0414- },- "0.05-0.5": {- "w": -0.103,- "n": 22350,- "good_rate": 0.1521+ "n": 91974,+ "w": {+ "win": -0.1615,+ "rug": 0.2533,+ "moon": -0.0315+ },+ "rate": {+ "win": 0.0061,+ "rug": 0.0944,+ "moon": 0.0316+ }},">=0.5": {- "w": -0.0662,- "n": 39627,- "good_rate": 0.1571+ "n": 124898,+ "w": {+ "win": -0.0351,+ "rug": -0.004,+ "moon": 0.0839+ },+ "rate": {+ "win": 0.0411,+ "rug": 0.055,+ "moon": 0.1343+ }+ },+ "0.05-0.5": {+ "n": 79971,+ "w": {+ "win": 0.119,+ "rug": -0.3703,+ "moon": -0.1732+ },+ "rate": {+ "win": 0.0379,+ "rug": 0.227,+ "moon": 0.1067+ }}}},{- "key": "dev_buy_sol",- "pillar": "pedigree",+ "key": "median_buy_sol",+ "pillar": "momentum","categorical": false,"edges": [- 0.05,- 0.5,- 2+ 0.02,+ 0.15,+ 1],"buckets": {- "0.05-0.5": {- "w": 0.9958,- "n": 21921,- "good_rate": 0.2004+ "<0.02": {+ "n": 89241,+ "w": {+ "win": -0.9801,+ "rug": 1.5622,+ "moon": 0.0991+ },+ "rate": {+ "win": 0.005,+ "rug": 0.1107,+ "moon": 0.0352+ }},- "<0.05": {- "w": 0.3532,- "n": 30267,- "good_rate": 0.0359+ "0.15-1": {+ "n": 98987,+ "w": {+ "win": 0.3284,+ "rug": -0.8871,+ "moon": 0.0438+ },+ "rate": {+ "win": 0.0411,+ "rug": 0.077,+ "moon": 0.1334+ }},- ">=2": {- "w": -1.4126,- "n": 26760,- "good_rate": 0.1301+ "0.02-0.15": {+ "n": 58509,+ "w": {+ "win": 0.4371,+ "rug": -0.1297,+ "moon": 0.0078+ },+ "rate": {+ "win": 0.0402,+ "rug": 0.2269,+ "moon": 0.128+ }},- "0.5-2": {- "w": 0.11,- "n": 13958,- "good_rate": 0.1393+ ">=1": {+ "n": 50106,+ "w": {+ "win": 0.3733,+ "rug": -1.0466,+ "moon": -0.2398+ },+ "rate": {+ "win": 0.0371,+ "rug": 0.0585,+ "moon": 0.0874+ }}}},@@ -449,25 +1228,185 @@35],"buckets": {- "28-30": {- "w": 0.326,- "n": 31871,- "good_rate": 0.1759- },"<28": {- "w": -0.5927,- "n": 29222,- "good_rate": 0.0321+ "n": 85430,+ "w": {+ "win": 0.3375,+ "rug": -3.1333,+ "moon": -1.0266+ },+ "rate": {+ "win": 0.0108,+ "rug": 0.0072,+ "moon": 0.0176+ }+ },+ "30-35": {+ "n": 56268,+ "w": {+ "win": -0.3489,+ "rug": 1.248,+ "moon": 0.4116+ },+ "rate": {+ "win": 0.0278,+ "rug": 0.037,+ "moon": 0.1113+ }+ },+ "28-30": {+ "n": 109166,+ "w": {+ "win": 0.2056,+ "rug": 1.0656,+ "moon": 0.6403+ },+ "rate": {+ "win": 0.0403,+ "rug": 0.2619,+ "moon": 0.1257+ }},">=35": {- "w": -0.3563,- "n": 13965,- "good_rate": 0.1386+ "n": 45979,+ "w": {+ "win": -0.7422,+ "rug": 1.5249,+ "moon": -0.1842+ },+ "rate": {+ "win": 0.04,+ "rug": 0.0527,+ "moon": 0.1463+ }+ }+ }+ },+ {+ "key": "dev_buy_sol",+ "pillar": "pedigree",+ "categorical": false,+ "edges": [+ 0.05,+ 0.5,+ 2+ ],+ "buckets": {+ "<0.05": {+ "n": 90041,+ "w": {+ "win": 0.1512,+ "rug": -1.7334,+ "moon": 0.1808+ },+ "rate": {+ "win": 0.0117,+ "rug": 0.0099,+ "moon": 0.0223+ }},- "30-35": {- "w": 0.4817,- "n": 17848,- "good_rate": 0.1359+ "0.5-2": {+ "n": 48719,+ "w": {+ "win": 0.0406,+ "rug": 0.4159,+ "moon": -0.2048+ },+ "rate": {+ "win": 0.0339,+ "rug": 0.0699,+ "moon": 0.1104+ }+ },+ "0.05-0.5": {+ "n": 72946,+ "w": {+ "win": 0.5286,+ "rug": 1.2981,+ "moon": 0.8294+ },+ "rate": {+ "win": 0.0434,+ "rug": 0.3539,+ "moon": 0.138+ }+ },+ ">=2": {+ "n": 85137,+ "w": {+ "win": -0.7989,+ "rug": 0.3478,+ "moon": -0.8634+ },+ "rate": {+ "win": 0.0335,+ "rug": 0.0422,+ "moon": 0.1265+ }+ }+ }+ },+ {+ "key": "dev_sell_sol",+ "pillar": "pedigree",+ "categorical": false,+ "edges": [+ 0.0001,+ 0.5,+ 2+ ],+ "buckets": {+ "<0.0001": {+ "n": 238524,+ "w": {+ "win": 0.1648,+ "rug": 0.2516,+ "moon": 0.0825+ },+ "rate": {+ "win": 0.0319,+ "rug": 0.1305,+ "moon": 0.0922+ }+ },+ ">=2": {+ "n": 30629,+ "w": {+ "win": -0.2936,+ "rug": -1.6645,+ "moon": -0.415+ },+ "rate": {+ "win": 0.0205,+ "rug": 0.0144,+ "moon": 0.1334+ }+ },+ "0.0001-0.5": {+ "n": 15095,+ "w": {+ "win": -0.5805,+ "rug": 0.6662,+ "moon": -0.1911+ },+ "rate": {+ "win": 0.0164,+ "rug": 0.1252,+ "moon": 0.0552+ }+ },+ "0.5-2": {+ "n": 12595,+ "w": {+ "win": -0.7837,+ "rug": -0.6805,+ "moon": -0.451+ },+ "rate": {+ "win": 0.0199,+ "rug": 0.0198,+ "moon": 0.1044+ }}}},@@ -480,14 +1419,94 @@],"buckets": {"<0.5": {- "w": 0.1041,- "n": 75914,- "good_rate": 0.1115+ "n": 237979,+ "w": {+ "win": 0.1714,+ "rug": 0.2635,+ "moon": 0.129+ },+ "rate": {+ "win": 0.0319,+ "rug": 0.1308,+ "moon": 0.0924+ }},">=0.5": {- "w": -0.5395,- "n": 16992,- "good_rate": 0.1435+ "n": 58864,+ "w": {+ "win": -0.7803,+ "rug": -1.0503,+ "moon": -0.6549+ },+ "rate": {+ "win": 0.0191,+ "rug": 0.0439,+ "moon": 0.1059+ }+ }+ }+ },+ {+ "key": "smart_money_count",+ "pillar": "pedigree",+ "categorical": false,+ "edges": [+ 1,+ 2,+ 4+ ],+ "buckets": {+ "<1": {+ "n": 296111,+ "w": {+ "win": -0.072,+ "rug": 0.1402,+ "moon": -0.2743+ },+ "rate": {+ "win": 0.0285,+ "rug": 0.1138,+ "moon": 0.0929+ }+ },+ "2-4": {+ "n": 351,+ "w": {+ "win": 1.4698,+ "rug": -1.45,+ "moon": 3.966+ },+ "rate": {+ "win": 0.5499,+ "rug": 0,+ "moon": 0.9886+ }+ },+ "1-2": {+ "n": 347,+ "w": {+ "win": 0.1458,+ "rug": -0.5795,+ "moon": 2.5322+ },+ "rate": {+ "win": 0.2565,+ "rug": 0.0259,+ "moon": 0.9539+ }+ },+ ">=4": {+ "n": 34,+ "w": {+ "win": -0.674,+ "rug": -0.3048,+ "moon": 1.0525+ },+ "rate": {+ "win": 0.1176,+ "rug": 0,+ "moon": 0.9706+ }}}},@@ -497,30 +1516,70 @@"categorical": true,"edges": null,"buckets": {+ "unknown": {+ "n": 123962,+ "w": {+ "win": 0.2239,+ "rug": -0.1129,+ "moon": 0.1404+ },+ "rate": {+ "win": 0.0355,+ "rug": 0.0881,+ "moon": 0.1062+ }+ },+ "first_launch": {+ "n": 11848,+ "w": {+ "win": -0.2476,+ "rug": -0.0924,+ "moon": -0.285+ },+ "rate": {+ "win": 0.025,+ "rug": 0.1277,+ "moon": 0.0898+ }+ },"has_wins": {- "w": 0.811,- "n": 39428,- "good_rate": 0.1967+ "n": 96525,+ "w": {+ "win": 0.1641,+ "rug": 0.5008,+ "moon": 0.2925+ },+ "rate": {+ "win": 0.0329,+ "rug": 0.1671,+ "moon": 0.1193+ }},"serial_no_wins": {- "w": -0.7026,- "n": 28508,- "good_rate": 0.0349+ "n": 54638,+ "w": {+ "win": -0.5697,+ "rug": -0.6222,+ "moon": -0.586+ },+ "rate": {+ "win": 0.0119,+ "rug": 0.072,+ "moon": 0.0344+ }},"repeat_no_wins": {- "w": -0.7011,- "n": 4265,- "good_rate": 0.0725- },- "first_launch": {- "w": -0.1404,- "n": 8980,- "good_rate": 0.1824- },- "unknown": {- "w": -0.2174,- "n": 11725,- "good_rate": 0.0177+ "n": 9870,+ "w": {+ "win": -0.4584,+ "rug": -0.6201,+ "moon": -0.4453+ },+ "rate": {+ "win": 0.0204,+ "rug": 0.1224,+ "moon": 0.0608+ }}}},@@ -530,62 +1589,367 @@"categorical": true,"edges": null,"buckets": {- "animal": {- "w": -0.1621,- "n": 10346,- "good_rate": 0.1438+ "unknown": {+ "n": 9618,+ "w": {+ "win": 0.3823,+ "rug": 1.337,+ "moon": 0.7525+ },+ "rate": {+ "win": 0.0495,+ "rug": 0.2537,+ "moon": 0.1594+ }},"meme": {- "w": 0.0317,- "n": 75099,- "good_rate": 0.1127- },- "political": {- "w": 0.1747,- "n": 782,- "good_rate": 0.1611+ "n": 245608,+ "w": {+ "win": -0.0282,+ "rug": -0.0248,+ "moon": -0.0556+ },+ "rate": {+ "win": 0.0288,+ "rug": 0.1124,+ "moon": 0.0923+ }},"culture": {- "w": -0.0774,- "n": 244,- "good_rate": 0.1516+ "n": 1138,+ "w": {+ "win": 0.0945,+ "rug": -0.5029,+ "moon": -0.2674+ },+ "rate": {+ "win": 0.0237,+ "rug": 0.0378,+ "moon": 0.0615+ }},- "unknown": {- "w": 0.906,- "n": 2858,- "good_rate": 0.1781+ "animal": {+ "n": 23794,+ "w": {+ "win": -0.1713,+ "rug": -0.0249,+ "moon": -0.1018+ },+ "rate": {+ "win": 0.0276,+ "rug": 0.0927,+ "moon": 0.1013+ }},- "ai": {- "w": -0.2678,- "n": 1268,- "good_rate": 0.0907+ "celebrity": {+ "n": 2275,+ "w": {+ "win": -0.2665,+ "rug": -0.1637,+ "moon": -0.0029+ },+ "rate": {+ "win": 0.0273,+ "rug": 0.0818,+ "moon": 0.1095+ }},"tech": {- "w": -0.2342,- "n": 1051,- "good_rate": 0.0371- },- "celebrity": {- "w": -0.0649,- "n": 578,- "good_rate": 0.109+ "n": 2092,+ "w": {+ "win": -0.3876,+ "rug": -1.1479,+ "moon": -0.7383+ },+ "rate": {+ "win": 0.0096,+ "rug": 0.0172,+ "moon": 0.0225+ }},- "community": {- "w": 0.1463,- "n": 391,- "good_rate": 0.1202+ "political": {+ "n": 2795,+ "w": {+ "win": 0.0052,+ "rug": -0.1649,+ "moon": 0.0024+ },+ "rate": {+ "win": 0.0358,+ "rug": 0.1138,+ "moon": 0.112+ }},"utility": {- "w": -0.3118,- "n": 283,- "good_rate": 0.053+ "n": 2424,+ "w": {+ "win": -0.0026,+ "rug": -0.8281,+ "moon": -0.1057+ },+ "rate": {+ "win": 0.021,+ "rug": 0.026,+ "moon": 0.0606+ }+ },+ "ai": {+ "n": 5768,+ "w": {+ "win": 0.2221,+ "rug": 0.3603,+ "moon": 0.3564+ },+ "rate": {+ "win": 0.0374,+ "rug": 0.1252,+ "moon": 0.1149+ }+ },+ "community": {+ "n": 1292,+ "w": {+ "win": -0.0004,+ "rug": -0.6598,+ "moon": -0.271+ },+ "rate": {+ "win": 0.0279,+ "rug": 0.0604,+ "moon": 0.0805+ }},"news": {- "w": -0.0476,- "n": 6,- "good_rate": 0.1667+ "n": 39,+ "w": {+ "win": 0.2938,+ "rug": 0.8166,+ "moon": 0.7579+ },+ "rate": {+ "win": 0.0513,+ "rug": 0.2051,+ "moon": 0.1538+ }}}}- ]+ ],+ "dropped_features": [+ {+ "key": "fresh_wallet_ratio",+ "bucket": "null",+ "share": 1,+ "runner_up": null+ },+ {+ "key": "bubblemap_connectivity",+ "bucket": "null",+ "share": 1,+ "runner_up": null+ }+ ],+ "holdout": {+ "n": 74211,+ "split_at": 222632,+ "win": {+ "auc": 0.8401,+ "brier": 0.02741,+ "base_rate": 0.0318,+ "precision": {+ "top1": {+ "n": 742,+ "rate": 0.4488,+ "lift": 14.09+ },+ "top5": {+ "n": 3711,+ "rate": 0.2582,+ "lift": 8.11+ },+ "top10": {+ "n": 7421,+ "rate": 0.1656,+ "lift": 5.2+ },+ "top25": {+ "n": 18553,+ "rate": 0.094,+ "lift": 2.95+ }+ },+ "reliability": [+ {+ "lo": 0,+ "hi": 0.05,+ "n": 68844,+ "observed": 0.0184,+ "predicted": 0.0113+ },+ {+ "lo": 0.05,+ "hi": 0.12,+ "n": 2790,+ "observed": 0.1036,+ "predicted": 0.0747+ },+ {+ "lo": 0.12,+ "hi": 0.25,+ "n": 1415,+ "observed": 0.2325,+ "predicted": 0.1762+ },+ {+ "lo": 0.25,+ "hi": 0.45,+ "n": 858,+ "observed": 0.3928,+ "predicted": 0.363+ },+ {+ "lo": 0.45,+ "hi": 1,+ "n": 304,+ "observed": 0.4638,+ "predicted": 0.6167+ }+ ]+ },+ "rug": {+ "auc": 0.9183,+ "brier": 0.07265,+ "base_rate": 0.1257,+ "precision": {+ "top1": {+ "n": 742,+ "rate": 0.8652,+ "lift": 6.88+ },+ "top5": {+ "n": 3711,+ "rate": 0.7815,+ "lift": 6.22+ },+ "top10": {+ "n": 7421,+ "rate": 0.6491,+ "lift": 5.16+ },+ "top25": {+ "n": 18553,+ "rate": 0.4214,+ "lift": 3.35+ }+ },+ "reliability": [+ {+ "lo": 0,+ "hi": 0.05,+ "n": 45201,+ "observed": 0.0067,+ "predicted": 0.0096+ },+ {+ "lo": 0.05,+ "hi": 0.12,+ "n": 4924,+ "observed": 0.0993,+ "predicted": 0.0815+ },+ {+ "lo": 0.12,+ "hi": 0.25,+ "n": 5928,+ "observed": 0.1311,+ "predicted": 0.195+ },+ {+ "lo": 0.25,+ "hi": 0.45,+ "n": 6497,+ "observed": 0.2221,+ "predicted": 0.3412+ },+ {+ "lo": 0.45,+ "hi": 1,+ "n": 11661,+ "observed": 0.5417,+ "predicted": 0.6923+ }+ ]+ },+ "moon": {+ "auc": 0.8924,+ "brier": 0.05798,+ "base_rate": 0.098,+ "precision": {+ "top1": {+ "n": 742,+ "rate": 0.9057,+ "lift": 9.24+ },+ "top5": {+ "n": 3711,+ "rate": 0.7726,+ "lift": 7.88+ },+ "top10": {+ "n": 7421,+ "rate": 0.5502,+ "lift": 5.61+ },+ "top25": {+ "n": 18553,+ "rate": 0.3084,+ "lift": 3.15+ }+ },+ "reliability": [+ {+ "lo": 0,+ "hi": 0.05,+ "n": 50211,+ "observed": 0.02,+ "predicted": 0.0173+ },+ {+ "lo": 0.05,+ "hi": 0.12,+ "n": 14605,+ "observed": 0.1215,+ "predicted": 0.0773+ },+ {+ "lo": 0.12,+ "hi": 0.25,+ "n": 3779,+ "observed": 0.2435,+ "predicted": 0.1713+ },+ {+ "lo": 0.25,+ "hi": 0.45,+ "n": 1776,+ "observed": 0.3666,+ "predicted": 0.3348+ },+ {+ "lo": 0.45,+ "hi": 1,+ "n": 3840,+ "observed": 0.7612,+ "predicted": 0.7473+ }+ ]+ }+ },+ "fit": {+ "epochs": 14,+ "epochs_run": 14,+ "columns": 109,+ "features": 25,+ "complete": true+ }}diff --git a/api/_lib/oracle/conviction.js b/api/_lib/oracle/conviction.jsindex da2898c57..3be066fd6 100644--- a/api/_lib/oracle/conviction.js+++ b/api/_lib/oracle/conviction.js@@ -1,61 +1,79 @@-// Oracle: the fused conviction engine, v2 (fitted from real outcomes).+// Oracle: the fused conviction engine, v3 (three heads, learned continuously).//-// v1 was a hand-tuned four-pillar heuristic. Audited against 92,546 labeled-// launches (2026-08-09), several of its strongest opinions turned out to be-// backwards at the 90-second observation window: it penalized top-10 holder-// concentration (empirically the 0.3-0.9 band graduates/pumps 5-8x the base-// rate, because "low concentration" at 90s usually means nobody bought), it-// penalized mid-range snipe ratios (0.1-0.7 is 2.7-3.6x base), it penalized an-// oversized dev buy (>=6 SOL is 1.36x base), and its category priors ranked-// flavors the outcome data does not distinguish. Its unknown-pedigree cap also-// made the Strong/Prime tiers unreachable in practice: in 202k live scores the-// engine never once produced a score above 71.+// What changed and why+// --------------------+// v1 was a hand-tuned four-pillar heuristic. v2 replaced its internals with a+// bucketed logistic model fitted on labeled launches, which was the right move+// and left two problems that took until 2026-08-28 to find.//-// v2 replaces the hand-tuned internals with a bucketed logistic model fitted on-// the labeled outcome set (scripts/oracle-fit.mjs, refit as the data grows).-// Every weight is a per-bucket log-odds contribution shipped with its sample-// size and observed good-rate in conviction-model.json: not a black box, a-// lookup table anyone can audit. "Good" = the coin graduated or hit >= 3x ATH.-// Holdout (newest 25% of labels, never seen in training): AUC 0.879 vs 0.627-// for v1; precision in the top decile 62.5% vs 24.1%.+// PROBLEM ONE: the model was frozen. The weights shipped as a JSON file baked+// into the container at build time, and the only thing that could refit them was+// a human running a script by hand. Nobody did. The model sat at its 2026-08-09+// fit of 92,906 rows while the labeled set grew past 750,000, and evaluated on a+// current holdout it had given up six points of top-decile precision (53.7% vs+// 59.8% for a fresh fit). A model that can only learn when a person remembers to+// teach it does not learn. Weights now live in `oracle_model_versions` and a+// cron refits and re-promotes them (api/cron/oracle-refit.js); this file's JSON+// is the bootstrap for a cold container and for tests.//-// What stays from v1:-// - The module is PURE: CoinIntel in, verdict out. No I/O, no DB, no clock-// (the model JSON is a build-time constant loaded once at import).-// - The four-pillar presentation (WHO/HOW/WHAT/MOVE), reasons, badges,-// confidence, and the public tier ladder (86/72/56/34).-// - The smart-money overlay: proven/flagged wallets are too rare in the-// training window to fit (214 proven wallets platform-wide), so their-// adjustments remain expert priors, expressed in log-odds and documented.-// - 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).+// PROBLEM TWO, the serious one: the label was measuring the price of SOL.+// `rugged` was decided by two tests, "fell to <= 25% of the market cap at first+// sight" and "market cap under $3,000". A pump.fun bonding curve with no real+// reserves is worth exactly 30 * 1e9 / 1073000191 = 27.958993 SOL, and we first+// see a coin in its opening 90 seconds when its cap is 28-38 SOL, so the floor+// is 73-99% of first sight and the first test can never fire. That left a+// hardcoded dollar threshold judging a floor worth 27.958993 SOL. Of 206,428+// coins labeled rugged, 206,419 were under $3,000; of 25,180 labeled survivors,+// the cheapest was exactly $3,000. Identical dead curves, sorted by whether SOL+// was above roughly $107.3 that day.//-// 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%. A tier is a-// claim about measured frequency, not a vibe, and production agrees. Over the-// 61,916 scored coins the market has resolved (2026-08-14), the rate at which-// each tier went on to do what the score predicts (see PREDICTED_EVENT below):+// So v2's score ranked "graduates or spikes 3x", the rug filter that was+// supposed to temper it was noise, and a Prime call could sit on a coin that+// ran 3x and went to zero. That is the complaint this version answers.//-// Prime n=1032 68.4% 6.5x base (claims >= 55%)-// Strong n= 968 31.8% 3.0x base (claims >= 30%)-// Lean n=3717 20.7% 2.0x base (claims >= 12%)-// Watch n=11876 12.0% 1.1x base (claims >= 5%)-// Avoid n=44323 7.5% 0.7x base+// v3: three heads over one design matrix+// --------------------------------------+// win = it ran (graduated or 3x) AND a holder from first sight is still up+// rug = a holder from first sight is down more than half+// moon = it ran, regardless of what happened after (what v2 ranked)//-// Monotone, separated, and honest at every rung, so the ladder stays where it-// is. What is NOT honest is quoting that ladder next to the stricter question a-// holder actually asks, which is what hitRateFor() below exists to answer.--import MODEL_JSON from './conviction-model.json' with { type: 'json' };-import CALIBRATION_JSON from './conviction-calibration.json' with { type: 'json' };+// All three read `hold_multiple = ath_multiple * (last_mc_usd / ath_mc_usd)`,+// where both dollar figures come from the same API response so the SOL price+// cancels. Holdout on 74,211 unseen launches: win AUC 0.8465 (13.2x lift in the+// top percentile), rug AUC 0.9175, moon AUC 0.8954. The rug head scored 0.484,+// worse than a coin flip, against the old label; the label was the problem.+//+// The published 0-100 score anchors on `win`. Rug risk is published beside it as+// its own number rather than folded in, because "this will probably run" and+// "this will probably take your money" are different questions and a single+// number that averages them tells you neither.+//+// What stays from v2+// ------------------+// - The module is PURE: CoinIntel in, verdict out. No I/O, no clock. The+// active model is swapped in by a caller (setActiveModel) rather than+// fetched here, so this file stays a function of its inputs.+// - The four-pillar presentation (WHO/HOW/WHAT/MOVE), reasons, badges,+// confidence, and the public tier ladder (86/72/56/34).+// - One hard cap: a serial-rugger creator ceilings the final score.+//+// What went away+// --------------+// The hand-written smart-money log-odds overlay. v2 added between +0.35 and+// +0.75 by hand because "214 proven wallets platform-wide" was too thin to fit.+// There are now 732 labeled launches with a proven wallet in them and the model+// fits the feature directly: 2-4 smart wallets in the first 90 seconds means a+// 55.0% survivable-win rate and 0 rugs in 351 samples. When the active model+// carries a fitted `smart_money_count` feature the overlay's smart-money and+// creator-history terms stand down automatically, because counting the same+// evidence twice is not conservatism, it is a bug.++import BOOTSTRAP_MODEL from './conviction-model.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. Unchanged since v1: the ladder is a+// public contract and the probability each rung claims is what moves, not the+// number printed on the pill.const TIERS = [{ min: 86, tier: 'prime', label: 'Prime' },{ min: 72, tier: 'strong', label: 'Strong' },@@ -64,79 +82,160 @@ const TIERS = [{ 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];-}+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));+const pct01 = (v) => (v == null ? null : num(v) / 100);/**- * The holder's number for a score: of every resolved coin Oracle scored into- * this band, the fraction that graduated or ran >= 2x WITHOUT ever rugging, and- * how many times the market's base rate that is. Isotonic-fitted over the- * realized outcome set by scripts/oracle-calibrate.mjs.+ * Bring any shipped model shape to one internal form.*- * This deliberately grades a stricter event than the score predicts: conviction- * ranks the odds of a run, this counts only runs that did not end in a rug. It- * is therefore always the smaller number, and the gap between them IS the- * information (a band that spikes often and survives rarely is a band to trade,- * not to hold). Any surface showing one must name which one it is showing.+ * A v2 document has a single flat feature list with scalar `w`/`good_rate` and+ * ranks the `moon` question. A v3 document has three heads and per-head weights.+ * Normalising here rather than at every read site means a container that boots+ * on the old bootstrap JSON, or a database row written before the upgrade,+ * scores exactly as it always did instead of throwing on a missing field.*- * @param {number} score 0-100 conviction- * @returns {{rate:number, lift:number, band:string, n:number, baseRate:number}}+ * @param {object} raw a v2 or v3 model document+ * @returns {object} canonical model*/-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;+export function normalizeModel(raw) {+ if (!raw || typeof raw !== 'object') throw new Error('conviction: model must be an object');+ if (!Array.isArray(raw.features) || !raw.features.length) throw new Error('conviction: model has no features');++ if (Number(raw.version) >= 3) {+ if (!raw.heads || !raw.heads[raw.score_head || 'win']) throw new Error('conviction: v3 model is missing its score head');+ return {+ version: Number(raw.version),+ fitted_at: raw.fitted_at || null,+ training_rows: Number(raw.training_rows) || 0,+ score_head: raw.score_head || 'win',+ heads: raw.heads,+ tier_probability_anchors: raw.tier_probability_anchors,+ features: raw.features,+ dropped_features: raw.dropped_features || [],+ holdout: raw.holdout || null,+ fit: raw.fit || null,+ };+ }++ // v2 -> canonical. Its single target is the `moon` question, so that is the+ // head it scores on, and it publishes no rug opinion at all.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,+ version: 2,+ fitted_at: raw.fitted_at || null,+ training_rows: Number(raw.training_rows) || 0,+ score_head: 'moon',+ heads: { moon: { intercept: Number(raw.intercept) || 0, base_rate: Number(raw.base_good_rate) || 0 } },+ tier_probability_anchors: raw.tier_probability_anchors,+ features: raw.features.map((f) => ({+ key: f.key,+ pillar: f.pillar,+ categorical: !!f.categorical,+ edges: f.edges || null,+ buckets: Object.fromEntries(Object.entries(f.buckets || {}).map(([label, b]) => [label, {+ n: b.n,+ w: { moon: Number(b.w) || 0 },+ rate: { moon: Number(b.good_rate) || 0 },+ }])),+ })),+ dropped_features: [],+ holdout: null,+ fit: null,};}-// 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;-const SCORE_ANCHORS = [- [0, 0],- [A.watch, 34],- [A.lean, 56],- [A.strong, 72],- [A.prime, 86],- [1, 100],-];+// ── Active model (swappable, with derived tables recomputed on every swap) ────+// `export let` gives importers a live binding, so a promotion at runtime is+// visible everywhere without a single caller re-importing anything.++export let MODEL = normalizeModel(BOOTSTRAP_MODEL);+export let SCORE_ANCHORS = [];+export let PILLAR_WEIGHTS = {};+export let WEIGHTS = {};+export let PREDICTED_EVENT = {};++/** The event each head predicts, in words, so no surface has to guess. */+const HEAD_EVENTS = {+ win: {+ id: 'runs_and_holds',+ label: 'graduates or peaks at 3x or more, AND is still worth at least what it cost at first sight',+ short: 'runs without giving it back',+ caveat: 'This is the holder question. A coin that spiked 3x and then collapsed is NOT a hit here, which is what separates v3 from every earlier version of this score.',+ },+ moon: {+ 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. This ranks the odds of a run, not the odds of a safe hold.',+ },+};-export { SCORE_ANCHORS };+function derivePillarWeights(model) {+ const head = model.score_head;+ const span = { pedigree: 0, structure: 0, narrative: 0, momentum: 0 };+ for (const f of model.features) {+ const ws = Object.values(f.buckets).map((b) => num(b.w?.[head]));+ if (!ws.length) continue;+ span[f.pillar] = (span[f.pillar] || 0) + (Math.max(...ws) - Math.min(...ws));+ }+ const total = Object.values(span).reduce((a, b) => a + b, 0) || 1;+ const out = {};+ for (const [k, v] of Object.entries(span)) out[k] = Number((v / total).toFixed(2));+ return Object.freeze(out);+}-// 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.',-});+function deriveAnchors(model) {+ const a = model.tier_probability_anchors || { avoid: 0, watch: 0.05, lean: 0.12, strong: 0.25, prime: 0.45 };+ return [[0, 0], [a.watch, 34], [a.lean, 56], [a.strong, 72], [a.prime, 86], [1, 100]];+}-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));+function applyModel(model) {+ MODEL = model;+ SCORE_ANCHORS = deriveAnchors(model);+ PILLAR_WEIGHTS = derivePillarWeights(model);+ WEIGHTS = PILLAR_WEIGHTS;+ PREDICTED_EVENT = Object.freeze({ ...(HEAD_EVENTS[model.score_head] || HEAD_EVENTS.moon) });+ return MODEL;+}++/**+ * Install a model as the one every score uses from now on.+ *+ * Validated before it is installed, and installed atomically: a malformed+ * document throws and leaves the previous model serving traffic, because the+ * failure mode of a scoring engine that accepts a bad model is silently wrong+ * numbers, which is worse than a loud refusal and a stale but correct one.+ *+ * @param {object} raw a v2 or v3 model document+ * @returns {object} the canonical model now in force+ */+export function setActiveModel(raw) {+ return applyModel(normalizeModel(raw));+}++/** Fall back to the model compiled into this build. */+export function resetModel() {+ return applyModel(normalizeModel(BOOTSTRAP_MODEL));+}++/** The model currently scoring, for anything that needs to report provenance. */+export function activeModel() {+ return MODEL;+}++/** True when the active model fits `key` itself, so no expert prior should. */+function isFitted(key) {+ return MODEL.features.some((f) => f.key === key);+}++applyModel(MODEL);++/** 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];+}/** Map a probability to the 0-100 score line through the tier anchors. */export function scoreFromProbability(p) {@@ -150,12 +249,11 @@ export function scoreFromProbability(p) {}/**- * 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.+ * Inverse of scoreFromProbability: the probability a given score actually+ * claims. The score line is not a percentage (86 claims 45%, not 86%), so any+ * surface comparing a score to a realized rate has to convert first. Every+ * calibration table we published before 2026-08-14 used score/100 as the+ * prediction, which overstated the engine's own claim by up to 4x.** @param {number} score 0-100 conviction score* @returns {number} probability in [0,1]@@ -170,11 +268,42 @@ export function probabilityFromScore(score) {return 1;}+/**+ * The measured hit rate behind a score, taken from the active model's own+ * holdout reliability curve.+ *+ * This used to read a separate hand-generated calibration file whose stated+ * win definition was "graduated or (ath_multiple >= 2 and not rugged)", i.e. it+ * was built on the SOL-price-dependent rug flag and its numbers were noise.+ * Reading the model's own holdout instead means the published rate is always+ * the rate that exact model earned on launches it had never seen, and it can+ * never drift out of sync with the weights, because it ships with them.+ *+ * @param {number} score 0-100 conviction+ * @returns {{rate:number|null, lift:number|null, band:string|null, n:number, baseRate:number|null, predicts:object}}+ */+export function hitRateFor(score) {+ const head = MODEL.score_head;+ const holdout = MODEL.holdout?.[head];+ const base = holdout?.base_rate ?? MODEL.heads?.[head]?.base_rate ?? null;+ const p = probabilityFromScore(score);+ const bands = holdout?.reliability || [];+ const band = bands.find((b) => p >= b.lo && p < b.hi) || bands[bands.length - 1] || null;+ const rate = band?.observed ?? null;+ return {+ rate,+ lift: rate != null && base ? Number((rate / base).toFixed(2)) : null,+ band: band ? `${band.lo}-${band.hi}` : null,+ n: band?.n ?? 0,+ baseRate: base,+ predicts: PREDICTED_EVENT,+ };+}+// ── Feature extraction ────────────────────────────────────────────────────────-// The model was trained on the raw launch-time signals JSONB. intel.launch (from+// The model is fitted on the raw launch-time signals JSONB. `intel.launch` (from// sources.js) carries those exact values; the derived CoinIntel fields act as// fallbacks so hand-built intel (tests, older callers) still scores.-const pct01 = (v) => (v == null ? null : num(v) / 100); // 0..100 display -> 0..1 rawfunction rawNum(intel, key) {const v = intel?.launch?.[key];@@ -189,8 +318,12 @@ const FEATURE_VALUE = {coordination_score: (it) => rawNum(it, 'coordination_score'),timing_entropy: (it) => rawNum(it, 'timing_entropy'),concentration_top1: (it) => rawNum(it, 'concentration_top1'),+ concentration_top5: (it) => rawNum(it, 'concentration_top5'),concentration_top10: (it) => rawNum(it, 'concentration_top10') ?? pct01(it.structure?.top10Pct),+ fresh_wallet_ratio: (it) => rawNum(it, 'fresh_wallet_ratio'),+ bubblemap_connectivity: (it) => rawNum(it, 'bubblemap_connectivity'),unique_buyers: (it) => rawNum(it, 'unique_buyers') ?? (it.structure?.uniqueBuyers ?? null),+ unique_sellers: (it) => rawNum(it, 'unique_sellers'),buy_sell_ratio: (it) => {const r = rawNum(it, 'buy_sell_ratio');if (r != null) return r;@@ -199,6 +332,9 @@ const FEATURE_VALUE = {return sells > 0 ? buys / sells : null;},buy_volume_sol: (it) => rawNum(it, 'buy_volume_sol') ?? (it.behavior?.buyVolSol ?? null),+ sell_volume_sol: (it) => rawNum(it, 'sell_volume_sol'),+ net_volume_sol: (it) => rawNum(it, 'net_volume_sol'),+ trade_count: (it) => rawNum(it, 'trade_count'),largest_buy_sol: (it) => rawNum(it, 'largest_buy_sol'),avg_buy_sol: (it) => {const r = rawNum(it, 'avg_buy_sol');@@ -207,8 +343,12 @@ const FEATURE_VALUE = {const buys = num(it.behavior?.buyCount);return buys > 0 ? vol / buys : null;},+ median_buy_sol: (it) => rawNum(it, 'median_buy_sol'),dev_buy_sol: (it) => rawNum(it, 'dev_buy_sol') ?? (it.behavior?.devBuySol ?? null),+ dev_sell_sol: (it) => rawNum(it, 'dev_sell_sol'),mc_sol_first_seen: (it) => rawNum(it, 'mc_sol_first_seen'),+ smart_money_count: (it) => rawNum(it, 'smart_money_count')+ ?? (it.smartMoney?.smartWalletCount ?? null),dev_sold: (it) => {const raw = it?.launch?.dev_sold;if (raw === true) return 1;@@ -239,8 +379,8 @@ function bucketLabelFor(feature, value) {}// Plain-language templates so a bucket hit reads as a fact, not a code. Each-// reason carries the observed good-rate from the model itself: the engine-// quotes its own training data instead of asserting vibes.+// reason carries the observed rate from the model itself: the engine quotes its+// own training data instead of asserting vibes.const FEATURE_TEXT = {organic_score: 'organic demand',bundle_score: 'launch coordination',@@ -248,14 +388,24 @@ const FEATURE_TEXT = {coordination_score: 'buy coordination',timing_entropy: 'buy-timing spread',concentration_top1: 'top-holder share',+ concentration_top5: 'top-5 holder share',concentration_top10: 'top-10 holder share',+ fresh_wallet_ratio: 'fresh-wallet share',+ bubblemap_connectivity: 'funder clustering',unique_buyers: 'unique early buyers',+ unique_sellers: 'unique early sellers',buy_sell_ratio: 'buy/sell pressure',buy_volume_sol: 'early buy volume (SOL)',+ sell_volume_sol: 'early sell volume (SOL)',+ net_volume_sol: 'net early flow (SOL)',+ trade_count: 'trades in the window',largest_buy_sol: 'largest single buy (SOL)',avg_buy_sol: 'average buy size (SOL)',+ median_buy_sol: 'median buy size (SOL)',dev_buy_sol: 'dev buy size (SOL)',+ dev_sell_sol: 'dev sell size (SOL)',mc_sol_first_seen: 'market cap at first sight (SOL)',+ smart_money_count: 'proven wallets in the book',dev_sold: 'dev selling in the window',creator_record: 'creator launch history',category: 'narrative category',@@ -271,13 +421,12 @@ const CREATOR_TEXT = {// Features whose reason reads as a fact about the launch rather than a// measurement of it, so the sentence says "such launches" instead of "similar".-const SUCH = new Set(['creator_record', 'category', 'dev_sold']);+const SUCH = new Set(['creator_record', 'category', 'dev_sold', 'smart_money_count']);-// One card-ready phrase per fitted bucket. The fallback below ("organic demand-// 0.6-0.8") is readable to whoever fitted the model and to nobody else, and it-// was fine while reasons only ever appeared in a diagnostic list. They are the-// headline of every feed card now, so each bucket says what it means in the-// units a trader already thinks in.+// One card-ready phrase per fitted bucket. The fallback ("organic demand+// 0.6-0.8") is readable to whoever fitted the model and to nobody else, and+// reasons are the headline of every feed card, so each bucket says what it means+// in the units a trader already thinks in.const PHRASE = {organic_score: {'<0.2': 'almost no organic demand', '0.2-0.4': 'weak organic demand',@@ -305,6 +454,10 @@ const PHRASE = {'<0.05': 'no holder above 5%', '0.05-0.15': 'top holder at 5-15%','0.15-0.3': 'top holder at 15-30%', '>=0.3': 'top holder above 30%',},+ concentration_top5: {+ '<0.3': 'top 5 under 30% of supply', '0.3-0.6': 'top 5 holding 30-60%',+ '0.6-0.9': 'top 5 holding 60-90%', '>=0.9': 'top 5 holding over 90%',+ },concentration_top10: {'<0.3': 'top 10 under 30% of supply', '0.3-0.9': 'top 10 holding 30-90%','>=0.9': 'top 10 holding over 90%',@@ -313,6 +466,10 @@ const PHRASE = {'<1': 'no buyers yet', '1-5': 'under 5 early buyers', '5-15': '5-15 early buyers','15-40': '15-40 early buyers', '>=40': '40+ early buyers',},+ unique_sellers: {+ '<1': 'nobody has sold yet', '1-3': '1-3 sellers already out',+ '3-10': '3-10 sellers already out', '>=10': '10+ sellers already out',+ },buy_sell_ratio: {'<0.5': 'more sellers than buyers', '0.5-1': 'sells keeping pace with buys','1-2': 'buys leading sells', '2-4': 'buys 2-4x the sells', '>=4': 'buys 4x+ the sells',@@ -322,6 +479,18 @@ const PHRASE = {'<0.5': 'under 0.5 SOL bought', '0.5-8': '0.5-8 SOL bought early','8-25': '8-25 SOL bought early', '>=25': '25+ SOL bought early',},+ sell_volume_sol: {+ '<0.1': 'almost nothing sold back', '0.1-2': '0.1-2 SOL sold back',+ '2-10': '2-10 SOL sold back', '>=10': '10+ SOL already sold back',+ },+ net_volume_sol: {+ '<0': 'more SOL left than arrived', '0-1': 'under 1 SOL of net inflow',+ '1-5': '1-5 SOL of net inflow', '5-20': '5-20 SOL of net inflow', '>=20': '20+ SOL of net inflow',+ },+ trade_count: {+ '<3': 'under 3 trades in the window', '3-12': '3-12 trades in the window',+ '12-40': '12-40 trades in the window', '>=40': '40+ trades in the window',+ },largest_buy_sol: {'<0.2': 'no buy above 0.2 SOL', '0.2-2.5': 'biggest buy 0.2-2.5 SOL','2.5-5': 'biggest buy 2.5-5 SOL', '>=5': 'a 5+ SOL single buy',@@ -330,24 +499,36 @@ const PHRASE = {'<0.05': 'dust-sized average buy', '0.05-0.5': 'average buy 0.05-0.5 SOL','>=0.5': 'average buy above 0.5 SOL',},+ median_buy_sol: {+ '<0.02': 'dust-sized median buy', '0.02-0.15': 'median buy 0.02-0.15 SOL',+ '0.15-1': 'median buy 0.15-1 SOL', '>=1': 'median buy above 1 SOL',+ },dev_buy_sol: {'<0.05': 'dev barely bought their own launch', '0.05-0.5': 'dev bought 0.05-0.5 SOL','0.5-2': 'dev bought 0.5-2 SOL', '>=2': 'dev bought 2+ SOL of their own launch',},+ dev_sell_sol: {+ '<0.0001': 'dev has not sold a lamport', '0.0001-0.5': 'dev sold under 0.5 SOL',+ '0.5-2': 'dev sold 0.5-2 SOL', '>=2': 'dev dumped 2+ SOL',+ },mc_sol_first_seen: {'<28': 'spotted below a 28 SOL cap', '28-30': 'spotted at a 28-30 SOL cap','30-35': 'spotted at a 30-35 SOL cap', '>=35': 'already past a 35 SOL cap when spotted',},+ smart_money_count: {+ '<1': 'no proven wallet in the book', '1-2': 'one proven wallet already in',+ '2-4': '2-3 proven wallets already in', '>=4': '4+ proven wallets already in',+ },dev_sold: {'<0.5': 'dev held through the window', '>=0.5': 'dev sold inside the window',},};/**- * The subject half of a reason: what the model actually saw, with no outcome- * statistics attached. Emitted alongside the full sentence because a card has- * room for the observation but not the sentence, and a card that re-derives it- * by splitting the sentence on a colon breaks the first time the wording moves.+ * The subject half of a reason: what the model saw, with no outcome statistics+ * attached. Emitted alongside the full sentence because a card has room for the+ * observation but not the sentence, and a card that re-derives it by splitting+ * the sentence on a colon breaks the first time the wording moves.*/function reasonSubject(feature, bucketLabel) {if (feature.key === 'creator_record') return CREATOR_TEXT[bucketLabel] || bucketLabel;@@ -358,23 +539,31 @@ function reasonSubject(feature, bucketLabel) {}function reasonText(feature, bucketLabel, stats) {- const rate = Math.round((stats?.good_rate ?? 0) * 100);- const rel = MODEL.base_good_rate > 0 ? (stats?.good_rate ?? 0) / MODEL.base_good_rate : 0;- const vs = rel >= 1.15 ? `${rel.toFixed(1)}x base rate`- : rel <= 0.85 ? `${rel.toFixed(1)}x base rate`- : 'near base rate';+ const head = MODEL.score_head;+ const base = MODEL.heads?.[head]?.base_rate || 0;+ const observed = num(stats?.rate?.[head]);+ const rate = Math.round(observed * 100);+ const rel = base > 0 ? observed / base : 0;+ const vs = rel >= 1.15 || rel <= 0.85 ? `${rel.toFixed(1)}x base rate` : 'near base rate';const kind = SUCH.has(feature.key) ? 'such' : 'similar';return `${reasonSubject(feature, bucketLabel)}: ${rate}% of ${kind} launches worked (${vs})`;}-// ── Smart-money overlay (expert priors, in log-odds) ─────────────────────────-// Proven/flagged wallets are too rare in the training window to fit weights for-// (214 proven wallets platform-wide at fit time), but when they DO show up they-// are the highest-fidelity signal available, so they stay as explicit-// adjustments on the fused log-odds. Magnitudes are conservative: +0.75 is-// roughly a 2.1x odds bump, comparable to a strong fitted bucket.+// ── Expert priors, for the evidence the model cannot fit ─────────────────────+// Everything the active model fits is left to the active model. What survives+// here is evidence that has no column in the training set: whether the proven+// wallets in the book are already selling, whether any of them are tagged+// ruggers, and the serial-rugger ceiling. Magnitudes are in log-odds and stay+// conservative: 0.7 is roughly a 2x odds move, comparable to a strong bucket.++/**+ * @param {object} sm smart-money summary from sources.js+ * @param {object} creator creator reputation+ * @returns {{z:number, cap:number, reasons:string[], provenCount:number, flaggedCount:number, suppressed:string[]}}+ */export function smartMoneyOverlay(sm = {}, creator = {}) {const reasons = [];+ const suppressed = [];let z = 0;let cap = 100;@@ -383,23 +572,35 @@ export function smartMoneyOverlay(sm = {}, creator = {}) {const flaggedWallets = notable.filter((w) => isFlagged(w.label));const provenCount = Math.max(num(sm.smartWalletCount), provenWallets.length);- if (provenCount >= 5) { z += 0.75; reasons.push(`${provenCount} smart-money wallets already in`); }- else if (provenCount >= 3) { z += 0.55; reasons.push(`${provenCount} smart-money wallets in`); }- else if (provenCount >= 1) { z += 0.35; reasons.push(`${provenCount} smart-money wallet in`); }-- const proven = num(sm.provenBuyLamports);- const total = num(sm.totalBuyLamports);- if (total > 0 && proven > 0) {- const share = proven / total;- if (share >= 0.4) { z += 0.3; reasons.push(`${Math.round(share * 100)}% of buy volume is proven money`); }- else if (share >= 0.2) { z += 0.15; }+ // Presence of smart money is a fitted feature now. Adding a hand-picked bonus+ // on top would count the same wallets twice, which is how a 0.35 prior turns+ // into a systematically inflated score once the data catches up to it.+ if (isFitted('smart_money_count')) {+ if (provenCount >= 1) suppressed.push('smart_money_count');+ } else {+ if (provenCount >= 5) { z += 0.75; reasons.push(`${provenCount} smart-money wallets already in`); }+ else if (provenCount >= 3) { z += 0.55; reasons.push(`${provenCount} smart-money wallets in`); }+ else if (provenCount >= 1) { z += 0.35; reasons.push(`${provenCount} smart-money wallet in`); }++ const provenBuy = num(sm.provenBuyLamports);+ const totalBuy = num(sm.totalBuyLamports);+ if (totalBuy > 0 && provenBuy > 0) {+ const share = provenBuy / totalBuy;+ if (share >= 0.4) { z += 0.3; reasons.push(`${Math.round(share * 100)}% of buy volume is proven money`); }+ else if (share >= 0.2) { z += 0.15; }+ }}+ // Not fitted, and not derivable from anything that is: the training set+ // records who bought, never who is a tagged rugger.if (flaggedWallets.length) {z -= 0.45 * Math.min(3, flaggedWallets.length);reasons.push(`${flaggedWallets.length} flagged wallet${flaggedWallets.length > 1 ? 's' : ''} (rugger/dumper) in the book`);}+ // Also not fitted: smart money buying and smart money still holding are very+ // different states, and only the first one is in the feature set.+ const proven = num(sm.provenBuyLamports);const provenSell = num(sm.provenSellLamports);if (proven > 0 && provenSell > 0) {const exitShare = provenSell / proven;@@ -407,87 +608,133 @@ export function smartMoneyOverlay(sm = {}, creator = {}) {else if (exitShare >= 0.25) { z -= 0.35; reasons.push(`smart money trimming (${Math.round(exitShare * 100)}% sold)`); }}- // The one hard cap that survives v2: a serial-rugger creator ceilings the- // final score at Watch no matter what the rest of the book looks like. The- // outcome data backs it (5+ launches with 0 graduations: 3.5% good, 0.26x- // base) and the guarantee matters product-wise: a graveyard dev can never- // present as Strong.+ // The one hard cap. `creator_record` is a fitted feature, so the log-odds+ // nudge stands down when the model carries it, but the CEILING stays either+ // way: it is a product guarantee, not a probability estimate. A dev with a+ // graveyard behind them can never present as Strong, whatever the tape says.const launches = num(creator?.launches);const launchWins = num(creator?.launchWins);- if (isFlagged(creator?.label) || (launches >= 3 && launchWins === 0)) {- z -= 1.2; cap = 45;+ const serialRugger = isFlagged(creator?.label) || (launches >= 3 && launchWins === 0);+ if (serialRugger) {+ cap = 45;+ if (isFitted('creator_record')) suppressed.push('creator_record');+ else z -= 1.2;reasons.push(launches >= 3? `creator has ${launches} prior launches, none graduated: rug pattern`: 'creator wallet flagged as a rugger');}const creatorDump = num(creator?.dumpRate);- if (launches >= 2 && creatorDump >= 0.5) {- z -= 0.3; reasons.push(`creator dumps ${Math.round(creatorDump * 100)}% of their launches`);+ if (launches >= 2 && creatorDump >= 0.5 && !isFitted('creator_record')) {+ z -= 0.3;+ reasons.push(`creator dumps ${Math.round(creatorDump * 100)}% of their launches`);}- return { z, cap, reasons, provenCount, flaggedCount: flaggedWallets.length };+ return { z, cap, reasons, provenCount, flaggedCount: flaggedWallets.length, suppressed };}// ── The engine ────────────────────────────────────────────────────────────────/**- * Evaluate the fitted model against one CoinIntel: per-feature bucket hits,- * per-pillar log-odds sums, and the fused probability. Pure.+ * Evaluate the active model against one CoinIntel: per-feature bucket hits,+ * per-pillar log-odds sums, and a probability for every head. Pure.** @param {object} intel normalized CoinIntel (see sources.js)- * @returns {{- * z:number, p:number,- * pillarZ:{pedigree:number,structure:number,narrative:number,momentum:number},- * hits:Array<{key:string,pillar:string,bucket:string,w:number,stats:object,present:boolean}>- * }}+ * @returns {{z:number, p:number, heads:Record<string,number>, pillarZ:object, hits:Array<object>}}*/export function evaluateModel(intel = {}) {- let z = MODEL.intercept;+ const headKeys = Object.keys(MODEL.heads);+ const z = Object.fromEntries(headKeys.map((h) => [h, num(MODEL.heads[h].intercept)]));const pillarZ = { pedigree: 0, structure: 0, narrative: 0, momentum: 0 };const hits = [];+ const head = MODEL.score_head;+for (const feature of MODEL.features) {const getter = FEATURE_VALUE[feature.key];const value = getter ? getter(intel) : null;const bucket = bucketLabelFor(feature, value);const stats = feature.buckets[bucket];if (!stats) {- // A bucket never seen in training (e.g. hand-built intel with no data)- // contributes nothing rather than inventing a weight.+ // A bucket never seen in training (hand-built intel, a category the+ // classifier invented this week) contributes nothing rather than+ // inventing a weight for it.hits.push({ key: feature.key, pillar: feature.pillar, bucket, w: 0, stats: null, present: value != null });continue;}- z += stats.w;- pillarZ[feature.pillar] = (pillarZ[feature.pillar] || 0) + stats.w;- hits.push({ key: feature.key, pillar: feature.pillar, bucket, w: stats.w, stats, present: value != null && bucket !== 'null' });+ for (const h of headKeys) z[h] += num(stats.w?.[h]);+ pillarZ[feature.pillar] = (pillarZ[feature.pillar] || 0) + num(stats.w?.[head]);+ hits.push({+ key: feature.key,+ pillar: feature.pillar,+ bucket,+ w: num(stats.w?.[head]),+ stats,+ // A categorical that fell back to 'unknown' is a default, not an+ // observation: counting it inflated the confidence of a coin we knew+ // nothing about.+ present: value != null && bucket !== 'null' && bucket !== 'unknown',+ });}- return { z, p: sigmoid(z), pillarZ, hits };++ return {+ z: z[head],+ p: sigmoid(z[head]),+ heads: Object.fromEntries(headKeys.map((h) => [h, sigmoid(z[h])])),+ headZ: z,+ pillarZ,+ hits,+ };}/**- * Fuse everything into Oracle Conviction. Same return contract as v1 (score,- * tier, pillars, reasons, badges, caps, confidence) with the internals swapped- * for the fitted model + smart-money overlay.+ * Fuse everything into an Oracle verdict.+ *+ * Same contract as v2 (score, tier, pillars, reasons, badges, caps, confidence)+ * plus the three-head numbers: `rugRisk` is the probability a holder from first+ * sight ends up down more than half, published as its own figure rather than+ * blended into the score.** @param {object} intel normalized CoinIntel (see sources.js)*/export function convict(intel = {}) {const evaled = evaluateModel(intel);const overlay = smartMoneyOverlay(intel.smartMoney, intel.creator);+ const head = MODEL.score_head;const z = evaled.z + overlay.z;const p = sigmoid(z);- let score = scoreFromProbability(p);const cap = overlay.cap;- score = clamp(Math.min(score, cap));-+ const score = clamp(Math.min(scoreFromProbability(p), cap));const tier = TIERS.find((t) => score >= t.min) || TIERS[TIERS.length - 1];+ // The overlay is evidence about this coin, not about this coin's upside+ // specifically, so it shifts every head it can. A book full of ruggers makes+ // a run less likely AND a collapse more likely.+ const probabilities = {};+ for (const [h, hp] of Object.entries(evaled.heads)) {+ const shift = h === 'rug' ? -overlay.z : overlay.z;+ probabilities[h] = Number(sigmoid(Math.log(hp / (1 - hp)) + shift).toFixed(4));+ }+ probabilities[head] = Number(p.toFixed(4));++ const rugRisk = probabilities.rug != null ? clamp(Math.round(probabilities.rug * 100)) : null;+ const upside = probabilities.moon != null ? clamp(Math.round(probabilities.moon * 100)) : null;++ // The number the three heads exist to produce, and the one nobody else+ // publishes: GIVEN this coin runs, how often does a coin like it hand the run+ // straight back? P(runs) and P(runs and holds) are both estimated, so their+ // ratio is the share of runs that survive, and one minus that is the trap.+ // A 90%-upside coin with a 90% give-back is exactly the "horrible coin the+ // Oracle called good" that every earlier version of this score produced,+ // because every earlier version only ever computed the first number.+ const giveBackRisk = probabilities.moon > 0 && probabilities.win != null+ ? clamp(Math.round((1 - Math.min(1, probabilities.win / probabilities.moon)) * 100))+ : null;+// Pillar sub-scores: what each pillar's own evidence (plus, for pedigree, the- // smart-money overlay) would imply alone, on the same probability->score map.- // Transparent and unit-consistent with the fused number.+ // overlay) would imply alone, on the same probability-to-score map.const pillarScore = (key, extraZ = 0) =>- scoreFromProbability(sigmoid(MODEL.intercept + (evaled.pillarZ[key] || 0) + extraZ));+ scoreFromProbability(sigmoid(num(MODEL.heads[head].intercept) + (evaled.pillarZ[key] || 0) + extraZ));const pillars = {pedigree: pillarScore('pedigree', overlay.z),structure: pillarScore('structure'),@@ -495,30 +742,33 @@ export function convict(intel = {}) {momentum: pillarScore('momentum'),};- // Confidence: fraction of model features observed (not defaulted/null),- // weighted equally. The fitted null-buckets DO carry signal (a coin with no- // sells yet is informative), so this is a presentation aid, not a prior.+ // Confidence: fraction of model features actually observed. The fitted null+ // buckets DO carry signal (a coin with no sells yet is informative), so this+ // is a presentation aid, not a prior.const present = evaled.hits.filter((h) => h.present).length;const confidence = clamp(Math.round((present / Math.max(1, evaled.hits.length)) * 100));const confidenceLabel = confidence >= 70 ? 'high' : confidence >= 45 ? 'medium' : 'low';- // Reasons: strongest model evidence first (by |log-odds|), each quoting the- // observed outcome rate for its bucket, then the smart-money overlay's.+ // Reasons: strongest model evidence first (by absolute log-odds), each+ // quoting the observed outcome rates for its bucket, then the overlay's.const modelReasons = evaled.hits.filter((h) => h.stats && Math.abs(h.w) >= 0.08).sort((a, b) => Math.abs(b.w) - Math.abs(a.w)).slice(0, 7).map((h) => {const feature = MODEL.features.find((f) => f.key === h.key);- const rel = MODEL.base_good_rate > 0 ? h.stats.good_rate / MODEL.base_good_rate : null;+ const base = MODEL.heads[head].base_rate || 0;+ const observed = num(h.stats.rate?.[head]);return {pillar: h.pillar,text: reasonText(feature, h.bucket, h.stats),// Structured twin of `text` so a card can render the observation and// its lift without re-parsing English.subject: reasonSubject(feature, h.bucket),- rate: Math.round(h.stats.good_rate * 100),- lift: rel == null ? null : Number(rel.toFixed(1)),+ rate: Math.round(observed * 100),+ rugRate: h.stats.rate?.rug != null ? Math.round(num(h.stats.rate.rug) * 100) : null,+ samples: h.stats.n ?? null,+ lift: base > 0 ? Number((observed / base).toFixed(1)) : null,};});const reasons = [@@ -527,10 +777,9 @@ export function convict(intel = {}) {];if (!reasons.length) reasons.push({ pillar: 'structure', text: 'no decisive evidence either way yet' });- // Badges (compact pills for cards). structure-flag: strong fitted negative- // evidence from a structure feature. pedigree-flag: the rugger cap fired.+ // Badges (compact pills for cards).const badges = [];- if (overlay.provenCount >= 3) badges.push('smart-money');+ if (overlay.provenCount >= 3 || (num(intel.launch?.smart_money_count) >= 3)) badges.push('smart-money');if (evaled.hits.some((h) => h.pillar === 'structure' && h.w <= -0.5)) badges.push('structure-flag');if (cap < 100) badges.push('pedigree-flag');if (String(intel.narrative?.category || intel.category).toLowerCase() === 'news') badges.push('news');@@ -539,14 +788,23 @@ export function convict(intel = {}) {// a decoration, not a signal.if (pillars.momentum >= 86) badges.push('momentum');if (confidence < 45) badges.push('thin-data');- // No 'prime' badge: the card renders the tier next to the score already, so it- // only ever restated the pill beside it.+ // The whole point of v3: a coin can rank well on upside and still be the+ // wrong thing to hold, and the card has to say so out loud.+ if (rugRisk != null && rugRisk >= 60) badges.push('rug-risk');+ // It will probably run, and it will probably not let you keep it.+ if (giveBackRisk != null && giveBackRisk >= 70 && upside >= 25) badges.push('give-back');return {score,tier: tier.tier,tierLabel: tier.label,probability: Number(p.toFixed(4)),+ probabilities,+ rugRisk,+ upside,+ giveBackRisk,+ survival: rugRisk == null ? null : 100 - rugRisk,+ predicts: PREDICTED_EVENT,pillars,weights: PILLAR_WEIGHTS,structureCap: 100,@@ -555,30 +813,15 @@ export function convict(intel = {}) {confidenceLabel,reasons,badges,- model: { version: MODEL.version, fitted_at: MODEL.fitted_at, training_rows: MODEL.training_rows },+ model: {+ version: MODEL.version,+ fitted_at: MODEL.fitted_at,+ training_rows: MODEL.training_rows,+ score_head: MODEL.score_head,+ },};}-// Pillar weights, derived from the model instead of hand-picked: each pillar's-// share of the total log-odds range its features can span. Exposed on every-// verdict (the UI renders these as the pillar-weight labels).-export const PILLAR_WEIGHTS = (() => {- const span = { pedigree: 0, structure: 0, narrative: 0, momentum: 0 };- for (const f of MODEL.features) {- const ws = Object.values(f.buckets).map((b) => b.w);- if (!ws.length) continue;- span[f.pillar] += Math.max(...ws) - Math.min(...ws);- }- const total = Object.values(span).reduce((a, b) => a + b, 0) || 1;- const out = {};- for (const [k, v] of Object.entries(span)) out[k] = Number((v / total).toFixed(2));- return Object.freeze(out);-})();--// Legacy alias: v1 exported hand-picked WEIGHTS; keep the name pointing at the-// derived pillar weights so older readers keep working.-export const WEIGHTS = PILLAR_WEIGHTS;-/** Map a tier to a UI tone (mirrors the page's CSS class suffixes). */export function tierTone(tier) {switch (tier) {diff --git a/api/_lib/oracle/model-store.js b/api/_lib/oracle/model-store.jsnew file mode 100644index 000000000..8bcac0ed7--- /dev/null+++ b/api/_lib/oracle/model-store.js@@ -0,0 +1,127 @@+// Oracle: the bridge between the learned model in the database and the pure+// scoring engine in memory.+//+// conviction.js is deliberately pure, so something has to fetch the current+// weights and install them. That is this module, and keeping it separate is+// what lets the scorer stay a function of its inputs while the model behind it+// changes underneath production without a deploy.+//+// Failure policy: never stop scoring. A database hiccup leaves whatever model is+// already installed in force (the bootstrap JSON on a cold container, the last+// good promotion on a warm one) and the next call retries. A scoring engine that+// returns nothing because it could not check for a newer opinion is strictly+// worse than one that keeps using a slightly older one.++import { sql } from '../db.js';+import { setActiveModel, activeModel, resetModel } from './conviction.js';++/**+ * How long an installed model is trusted before we look for a newer one.+ *+ * The refit cron promotes at most once every six hours, so this is not about+ * keeping up. It is about how long a freshly promoted model takes to reach every+ * warm container, and two minutes is short enough that a promotion is live+ * platform-wide inside one scoring cycle without adding a query to the hot path.+ */+const TTL_MS = 120_000;++const state = {+ loadedAt: 0,+ id: null,+ fittedAt: null,+ source: 'bootstrap',+ inflight: null,+ lastError: null,+};++/** Provenance of the model currently scoring: which row, from where, how old. */+export function modelProvenance() {+ const model = activeModel();+ return {+ source: state.source,+ version_id: state.id,+ model_version: model.version,+ score_head: model.score_head,+ fitted_at: model.fitted_at,+ training_rows: model.training_rows,+ loaded_at: state.loadedAt ? new Date(state.loadedAt).toISOString() : null,+ stale_after: state.loadedAt ? new Date(state.loadedAt + TTL_MS).toISOString() : null,+ last_error: state.lastError,+ };+}++async function fetchActive(network) {+ const rows = await sql`+ select id, model, fitted_at+ from oracle_model_versions+ where network = ${network} and status = 'active'+ order by promoted_at desc nulls last+ limit 1+ `;+ return rows[0] || null;+}++/**+ * Make sure the newest promoted model is the one scoring, and return its+ * provenance.+ *+ * Concurrency-safe: parallel callers inside one container share a single+ * in-flight query rather than each opening their own, which matters because the+ * score loop fans out over a batch of coins and would otherwise stampede the+ * database on every cache expiry.+ *+ * @param {object} [opts]+ * @param {boolean} [opts.force] refetch even if the cached model is fresh+ * @param {string} [opts.network]+ * @returns {Promise<object>} provenance of the model now in force+ */+export async function ensureActiveModel({ force = false, network = 'mainnet' } = {}) {+ const fresh = state.loadedAt && Date.now() - state.loadedAt < TTL_MS;+ if (fresh && !force) return modelProvenance();+ if (state.inflight) { await state.inflight; return modelProvenance(); }++ state.inflight = (async () => {+ try {+ const row = await fetchActive(network);+ if (!row?.model) {+ // No promotion has happened yet. The bootstrap in the image is the+ // model, and saying so beats pretending a database read succeeded.+ state.source = 'bootstrap';+ state.id = null;+ state.lastError = null;+ } else if (row.id !== state.id) {+ setActiveModel(row.model);+ state.source = 'database';+ state.id = row.id;+ state.fittedAt = row.fitted_at;+ state.lastError = null;+ console.log(`[oracle] model v${row.id} installed (fitted ${row.fitted_at})`);+ }+ state.loadedAt = Date.now();+ } catch (err) {+ // Keep serving. Record why, so /api/oracle/model can say so out loud+ // instead of quietly publishing a stale model as if it were current.+ state.lastError = err?.message || String(err);+ console.warn('[oracle] model load failed, keeping the installed model:', state.lastError);+ } finally {+ state.inflight = null;+ }+ })();++ await state.inflight;+ return modelProvenance();+}++/**+ * Drop back to the model compiled into this build and forget the cache.+ * Used by tests, and by anything that needs a known-good scorer after a bad+ * promotion is rolled back.+ */+export function useBootstrapModel() {+ resetModel();+ state.loadedAt = 0;+ state.id = null;+ state.source = 'bootstrap';+ state.lastError = null;+ return modelProvenance();+}diff --git a/api/_lib/oracle/store.js b/api/_lib/oracle/store.jsindex c0e50a9bf..1a5a19690 100644--- a/api/_lib/oracle/store.js+++ b/api/_lib/oracle/store.js@@ -8,6 +8,7 @@ import { sql, isDbUnavailableError } from '../db.js';import { assembleIntel, walletProfile, coinOutcome } from './sources.js';import { classifyNarrative } from './narrative.js';import { convict, hitRateFor, PREDICTED_EVENT } from './conviction.js';+import { ensureActiveModel, modelProvenance } from './model-store.js';import { summarizeActions } from './settle.js';import { evaluateExit } from './exit.js';import { knownWallet } from './known-wallets.js';@@ -39,14 +40,17 @@ export async function upsertConviction({ mint, network, intel, verdict }) {insert into oracle_conviction (mint, network, symbol, name, image_uri,score, tier, pedigree, structure, narrative, momentum, structure_cap,- badges, reasons, components, category, smart_wallet_count, coin_first_seen_at, scored_at+ badges, reasons, components, category, smart_wallet_count, coin_first_seen_at, scored_at,+ rug_risk, upside, give_back_risk, model_version_id) values (${mint}, ${network}, ${intel.symbol || null}, ${intel.name || null}, ${intel.image_uri || null},${verdict.score}, ${verdict.tier}, ${verdict.pillars.pedigree}, ${verdict.pillars.structure},${verdict.pillars.narrative}, ${verdict.pillars.momentum}, ${verdict.structureCap},${JSON.stringify(verdict.badges)}::jsonb, ${JSON.stringify(verdict.reasons)}::jsonb,${JSON.stringify(componentSummary(intel, verdict))}::jsonb, ${intel.category || null},- ${intel.smartMoney?.smartWalletCount || 0}, ${intel.createdAt || null}, now()+ ${intel.smartMoney?.smartWalletCount || 0}, ${intel.createdAt || null}, now(),+ ${verdict.rugRisk ?? null}, ${verdict.upside ?? null}, ${verdict.giveBackRisk ?? null},+ ${modelProvenance().version_id})on conflict (mint, network) do update setsymbol = excluded.symbol, name = excluded.name, image_uri = excluded.image_uri,@@ -56,6 +60,9 @@ export async function upsertConviction({ mint, network, intel, verdict }) {structure_cap = excluded.structure_cap, badges = excluded.badges,reasons = excluded.reasons, components = excluded.components,category = excluded.category, smart_wallet_count = excluded.smart_wallet_count,+ rug_risk = excluded.rug_risk, upside = excluded.upside,+ give_back_risk = excluded.give_back_risk,+ model_version_id = excluded.model_version_id,scored_at = now()returning (xmax = 0) as inserted`;@@ -78,11 +85,13 @@ export async function upsertConviction({ mint, network, intel, verdict }) {if (delta >= 3) {await sql`insert into oracle_conviction_history- (mint, network, score, tier, pedigree, structure, narrative, momentum)+ (mint, network, score, tier, pedigree, structure, narrative, momentum,+ rug_risk, upside, give_back_risk)values (${mint}, ${network}, ${verdict.score}, ${verdict.tier},${verdict.pillars.pedigree}, ${verdict.pillars.structure},- ${verdict.pillars.narrative}, ${verdict.pillars.momentum}+ ${verdict.pillars.narrative}, ${verdict.pillars.momentum},+ ${verdict.rugRisk ?? null}, ${verdict.upside ?? null}, ${verdict.giveBackRisk ?? null})`.catch(() => { /* non-fatal — history is a nice-to-have */ });}@@ -115,6 +124,13 @@ function componentSummary(intel, verdict) {* @param {object} opts { network, classify, persist }*/export async function scoreCoin(mint, { network = 'mainnet', classify = true, persist = true } = {}) {+ // Make sure this container is scoring with the newest promoted model before+ // it forms an opinion. Cached for two minutes and shared across concurrent+ // callers, so a batch sweep costs one query, and it never throws: a model+ // lookup that fails leaves the installed model scoring rather than taking the+ // whole feed down over a stale opinion.+ await ensureActiveModel({ network });+let intel = await assembleIntel(mint, network);if (!intel) return null;@@ -151,7 +167,8 @@ export async function readFeed({ network = 'mainnet', limit = 50, minScore = 0,select c.mint, c.symbol, c.name, c.image_uri, c.score, c.tier,c.pedigree, c.structure, c.narrative, c.momentum,c.badges, c.reasons, c.category, c.smart_wallet_count, c.scored_at, c.coin_first_seen_at,- o.graduated, o.rugged, o.ath_multiple,+ c.rug_risk, c.upside, c.give_back_risk,+ o.graduated, o.rugged, o.ath_multiple, o.hold_multiple,hist.sparkfrom oracle_conviction cleft join pump_coin_outcomes o on o.mint = c.mint@@ -235,6 +252,12 @@ function rowToFeedItem(r) {pillars: { pedigree: r.pedigree, structure: r.structure, narrative: r.narrative, momentum: r.momentum },badges: r.badges || [],reasons,+ // The three v3 numbers, carried on every card. `give_back_risk` is the one+ // that answers "why is this scored well when the chart is a cliff": it is+ // the share of coins like this one that run and then hand it all back.+ rug_risk: r.rug_risk ?? null,+ upside: r.upside ?? null,+ give_back_risk: r.give_back_risk ?? null,hit_rate: odds.rate,hit_rate_lift: odds.lift,hit_rate_n: odds.n,diff --git a/api/cron/oracle-refit.js b/api/cron/oracle-refit.jsnew file mode 100644index 000000000..14669d8c2--- /dev/null+++ b/api/cron/oracle-refit.js@@ -0,0 +1,235 @@+// GET/POST /api/cron/oracle-refit: the Oracle learns from itself, on a clock.+//+// This is the loop that was missing. Every ingredient existed before today:+// 365,000 observed launches, 750,000 labeled outcomes, a fitter, a scorer. The+// one thing nothing did was connect them. The conviction weights shipped as a+// JSON file baked into the container, and refitting meant a human remembering to+// run a script. Between 2026-08-09 and 2026-08-28 nobody did, so the model+// answered every question with a 92,906-row opinion while eight times that much+// evidence piled up behind it.+//+// What runs here every six hours:+//+// 1. Load the labeled set, oldest first, price-independent labels only.+// 2. Fit three heads with a time-split holdout the model has never seen.+// 3. Put the candidate through a promotion gate that can, and does, say no.+// 4. Promote or archive. Either way, record the decision and the numbers.+//+// The gate is the part that makes this safe to run unattended. An automated+// retrain that always ships whatever it just fitted is not a learning loop, it+// is a single point of failure on a timer: one bad data day and production is+// serving a model nobody looked at. Every candidate has to beat the incumbent on+// held-out ranking, stay honest about its own tier claims, and keep its feature+// set intact. A candidate that fails is stored with the reason, not discarded,+// so the record of what the machine tried is as durable as what it shipped.++import { json, method, wrapCron } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { requireCron } from '../_lib/cron-auth.js';+import { buildModel, LABEL_VERSION, MIN_TRAINING_ROWS, TIER_PROBABILITY_ANCHORS } from '../_lib/oracle/fit.js';+import { ensureActiveModel } from '../_lib/oracle/model-store.js';++/** Wall-clock budget. The route is configured for 300s; stop with room to write. */+const FIT_BUDGET_MS = 210_000;+/** Hard cap on rows pulled into memory for one fit. */+const MAX_ROWS = 400_000;+/** SGD passes per head. Fourteen converges on this design; more buys noise. */+const EPOCHS = 14;++/**+ * How much better a challenger has to be before it takes over.+ *+ * Not zero. Two fits on almost the same data differ by a few thousandths of AUC+ * from SGD ordering alone, and promoting on that noise would rewrite the live+ * model every six hours for no reason, making every published score a moving+ * target and every track record unreproducible. A challenger has to be visibly+ * better, or the incumbent keeps the job.+ */+const MIN_AUC_GAIN = 0.004;+/** A challenger may not be worse than this on any head, even if `win` improved. */+const MAX_HEAD_REGRESSION = 0.01;+/** Below this the ranking is not good enough to publish at all. */+const MIN_ABSOLUTE_AUC = 0.70;++const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : null);++/**+ * Load labeled launches, oldest first.+ *+ * `label_version >= 2` is load-bearing, not a filter of convenience. Version 1+ * rows carry a `rugged` flag decided by comparing a bonding curve's dollar value+ * to a hardcoded $3,000, and since an empty pump.fun curve is worth a fixed+ * 27.958993 SOL, that flag tracks the price of SOL rather than the coin. Two+ * heads out of three read it. Training on those rows produced a survival model+ * with an AUC of 0.484, which is to say worse than guessing.+ */+async function loadRows(network) {+ const PAGE = 20_000;+ const rows = [];+ for (let off = 0; rows.length < MAX_ROWS; off += PAGE) {+ const take = Math.min(PAGE, MAX_ROWS - rows.length);+ const page = await sql`+ select features, category, creator_launches, creator_wins,+ outcome, graduated, ath_multiple, hold_multiple, retained+ from oracle_training_set+ where network = ${network} and outcome <> 'unknown' and label_version >= ${LABEL_VERSION}+ order by first_seen_at asc, mint asc+ limit ${take} offset ${off}+ `;+ rows.push(...page);+ if (page.length < take) break;+ }+ return rows;+}++/**+ * Decide whether a candidate replaces the incumbent.+ *+ * Returns a verdict plus the sentence explaining it, because six months from now+ * "why is the model from the 14th still live" is a question somebody will ask+ * and the answer should be in the row, not in a log that has rolled over.+ *+ * @param {object} candidate the freshly fitted model+ * @param {object|null} incumbent the active model document, if any+ * @returns {{promote:boolean, reason:string, checks:object[]}}+ */+export function judgeCandidate(candidate, incumbent) {+ const checks = [];+ const fail = (reason) => ({ promote: false, reason, checks });++ const head = candidate.score_head;+ const candAuc = num(candidate.holdout?.[head]?.auc);+ if (candAuc == null) return fail('candidate has no holdout AUC for its score head');++ // 1. Did the fit finish? A deadline-truncated fit is not wrong, it is+ // under-trained, and under-trained weights should never quietly ship.+ checks.push({ check: 'fit_complete', pass: !!candidate.fit?.complete, detail: `${candidate.fit?.epochs_run}/${candidate.fit?.epochs} epochs` });+ if (!candidate.fit?.complete) return fail(`fit ran out of time at ${candidate.fit?.epochs_run}/${candidate.fit?.epochs} epochs`);++ // 2. Is it good enough to publish at all, incumbent or not?+ checks.push({ check: 'absolute_auc', pass: candAuc >= MIN_ABSOLUTE_AUC, detail: `${head} AUC ${candAuc}` });+ if (candAuc < MIN_ABSOLUTE_AUC) return fail(`${head} AUC ${candAuc} is below the ${MIN_ABSOLUTE_AUC} publish floor`);++ // 3. Does every tier still earn the probability it claims? The ladder is a+ // public promise. A model whose top band claims 45% and delivers 20% is+ // accurate in aggregate and lying on every card that renders it.+ const bands = candidate.holdout?.[head]?.reliability || [];+ const dishonest = bands.filter((b) => b.n >= 100 && b.observed != null && b.observed < b.lo * 0.7);+ checks.push({+ check: 'tier_honesty',+ pass: !dishonest.length,+ detail: dishonest.length+ ? dishonest.map((b) => `band ${b.lo}-${b.hi} claims ${b.lo} observed ${b.observed} (n=${b.n})`).join('; ')+ : `all ${bands.filter((b) => b.n >= 100).length} populated bands clear their claim`,+ });+ if (dishonest.length) return fail(`tier bands do not earn their claim: ${checks[checks.length - 1].detail}`);++ // 4. Did the feature set collapse? A schema change or a broken enrichment+ // lane shows up here as a model that suddenly fits on four signals.+ const featureCount = candidate.features?.length || 0;+ const incumbentFeatures = incumbent?.features?.length || 0;+ const collapsed = incumbentFeatures > 0 && featureCount < incumbentFeatures - 3;+ checks.push({ check: 'feature_set', pass: !collapsed, detail: `${featureCount} features (incumbent ${incumbentFeatures || 'none'})` });+ if (collapsed) return fail(`feature set collapsed from ${incumbentFeatures} to ${featureCount}; a signal source is probably broken`);++ if (!incumbent) {+ return { promote: true, reason: `first model on the price-independent labels: ${head} AUC ${candAuc}`, checks };+ }++ // 5. Beat the incumbent on the head we score, by more than fit noise.+ const baseAuc = num(incumbent.holdout?.[head]?.auc);+ if (baseAuc == null) {+ return { promote: true, reason: `incumbent has no comparable ${head} holdout; promoting the measured model`, checks };+ }+ const gain = Number((candAuc - baseAuc).toFixed(4));+ checks.push({ check: 'auc_gain', pass: gain >= MIN_AUC_GAIN, detail: `${head} ${baseAuc} -> ${candAuc} (${gain >= 0 ? '+' : ''}${gain})` });++ // 6. And do not go backwards anywhere else while doing it.+ for (const other of ['rug', 'moon']) {+ if (other === head) continue;+ const a = num(candidate.holdout?.[other]?.auc);+ const b = num(incumbent.holdout?.[other]?.auc);+ if (a == null || b == null) continue;+ const delta = Number((a - b).toFixed(4));+ const pass = delta >= -MAX_HEAD_REGRESSION;+ checks.push({ check: `no_regression_${other}`, pass, detail: `${other} ${b} -> ${a} (${delta >= 0 ? '+' : ''}${delta})` });+ if (!pass) return fail(`${other} head regressed ${delta} (${b} -> ${a}), beyond the ${MAX_HEAD_REGRESSION} tolerance`);+ }++ if (gain < MIN_AUC_GAIN) {+ return fail(`no material gain: ${head} AUC ${baseAuc} -> ${candAuc} (+${gain}), below the ${MIN_AUC_GAIN} bar`);+ }+ return { promote: true, reason: `${head} AUC ${baseAuc} -> ${candAuc} (+${gain}) on ${candidate.training_rows.toLocaleString()} rows`, checks };+}++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const network = 'mainnet';+ const startedAt = Date.now();++ const rows = await loadRows(network);+ if (rows.length < MIN_TRAINING_ROWS) {+ // Not an error. The labeler stamps label_version as it relabels, so a+ // freshly migrated database legitimately has too few correct rows for a+ // while, and the right behaviour is to keep the current model and wait.+ return json(res, 200, {+ ok: true, promoted: false, rows: rows.length,+ reason: `only ${rows.length} rows carry label_version >= ${LABEL_VERSION}; need ${MIN_TRAINING_ROWS}`,+ });+ }++ const [incumbentRow] = await sql`+ select id, model from oracle_model_versions+ where network = ${network} and status = 'active'+ order by promoted_at desc nulls last limit 1+ `;+ const incumbent = incumbentRow?.model || null;++ const { model } = buildModel(rows, {+ epochs: EPOCHS,+ deadlineAt: startedAt + FIT_BUDGET_MS,+ fittedAt: new Date().toISOString(),+ });+ // Anchors are a platform constant, not a per-fit choice: stamp the current+ // ones so a stored model is self-describing even if the constant later moves.+ model.tier_probability_anchors = { ...TIER_PROBABILITY_ANCHORS };++ const verdict = judgeCandidate(model, incumbent);+ const auc = (head) => num(model.holdout?.[head]?.auc);++ const [stored] = await sql`+ insert into oracle_model_versions+ (network, model, fitted_at, training_rows, holdout_auc_win, holdout_auc_rug, holdout_auc_moon, status, decision)+ values (${network}, ${JSON.stringify(model)}::jsonb, ${model.fitted_at}, ${model.training_rows},+ ${auc('win')}, ${auc('rug')}, ${auc('moon')},+ ${verdict.promote ? 'promoting' : 'candidate'}, ${verdict.reason})+ returning id+ `;++ if (verdict.promote) {+ // One transaction, because a unique partial index enforces exactly one+ // active model per network: demote first or the promote is rejected, and+ // a half-applied promotion would leave the platform with none at all.+ await sql.transaction([+ sql`update oracle_model_versions set status = 'superseded'+ where network = ${network} and status = 'active'`,+ sql`update oracle_model_versions set status = 'active', promoted_at = now()+ where id = ${stored.id}`,+ ]);+ await ensureActiveModel({ force: true, network });+ }++ return json(res, 200, {+ ok: true,+ promoted: verdict.promote,+ version_id: stored.id,+ rows: model.training_rows,+ reason: verdict.reason,+ checks: verdict.checks,+ holdout: { win: auc('win'), rug: auc('rug'), moon: auc('moon') },+ dropped_features: model.dropped_features,+ took_ms: Date.now() - startedAt,+ });+});diff --git a/api/oracle/model.js b/api/oracle/model.jsnew file mode 100644index 000000000..c4f39e689--- /dev/null+++ b/api/oracle/model.js@@ -0,0 +1,234 @@+/**+ * Oracle - the model, published.+ *+ * GET /api/oracle/model the active model, whole+ * GET /api/oracle/model?view=registry every version, promoted or refused+ * GET /api/oracle/model?view=diff&from=&to= what the machine learned between two+ * GET /api/oracle/model?view=card the short human summary+ *+ * Most prediction products publish a number. This publishes the machine that+ * makes the number: every bucket weight, the sample count behind it, the+ * held-out reliability curve, the features it threw away for carrying no+ * information, and the promotion decision that let it near production. The+ * model is a lookup table, roughly 32KB of JSON, so anyone can download it and+ * reproduce any score we have ever shown offline, with no API key and no call+ * back to us. `@three-ws/oracle-model` on npm does exactly that in a few lines.+ *+ * The registry view is the part that matters most. Every refit is recorded,+ * including the ones the promotion gate refused and why, so the track record+ * cannot be quietly edited after the fact: a model that lost is still in the+ * table next to the one that won.+ *+ * Public, no auth, cached at the edge. Reads only.+ */++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql, isDbUnavailableError } from '../_lib/db.js';+import { activeModel, PREDICTED_EVENT, SCORE_ANCHORS, PILLAR_WEIGHTS } from '../_lib/oracle/conviction.js';+import { ensureActiveModel, modelProvenance } from '../_lib/oracle/model-store.js';++const NETWORKS = new Set(['mainnet', 'devnet']);+const MAX_REGISTRY = 50;++/** Tier boundaries as a table anyone can check a card against. */+function ladder(model) {+ const a = model.tier_probability_anchors || {};+ const holdout = model.holdout?.[model.score_head]?.reliability || [];+ const rows = [+ { tier: 'prime', label: 'Prime', min_score: 86, claims: a.prime ?? null },+ { tier: 'strong', label: 'Strong', min_score: 72, claims: a.strong ?? null },+ { tier: 'lean', label: 'Lean', min_score: 56, claims: a.lean ?? null },+ { tier: 'watch', label: 'Watch', min_score: 34, claims: a.watch ?? null },+ { tier: 'avoid', label: 'Avoid', min_score: 0, claims: 0 },+ ];+ // Staple each rung to the band of the holdout curve it sits in, so the claim+ // and the measurement are printed together or not at all.+ return rows.map((r) => {+ const band = holdout.find((b) => r.claims != null && r.claims >= b.lo && r.claims < b.hi) || null;+ return { ...r, observed: band?.observed ?? null, samples: band?.n ?? 0 };+ });+}++/** The short version: what it predicts, how well, how old, what it dropped. */+function card(model, provenance) {+ const head = model.score_head;+ const h = model.holdout?.[head] || null;+ return {+ version: model.version,+ score_head: head,+ predicts: PREDICTED_EVENT,+ fitted_at: model.fitted_at,+ training_rows: model.training_rows,+ features: model.features.length,+ bucket_weights: model.features.reduce((n, f) => n + Object.keys(f.buckets).length, 0),+ pillar_weights: PILLAR_WEIGHTS,+ holdout: h && {+ n: model.holdout.n,+ auc: h.auc,+ brier: h.brier,+ base_rate: h.base_rate,+ precision: h.precision,+ },+ heads: Object.fromEntries(Object.entries(model.holdout || {})+ .filter(([k, v]) => v && typeof v === 'object' && v.auc != null)+ .map(([k, v]) => [k, { auc: v.auc, base_rate: v.base_rate }])),+ // Named out loud rather than silently absent: a signal that stopped+ // arriving is an outage somewhere upstream, and the model is the first+ // place it becomes visible.+ dropped_features: model.dropped_features || [],+ tier_ladder: ladder(model),+ score_anchors: SCORE_ANCHORS,+ provenance,+ };+}++/**+ * What changed between two fits, in the terms a reader cares about: which+ * buckets moved, which features arrived or left, and whether the ranking got+ * better. This is the closest thing to watching a model think.+ */+function diffModels(from, to) {+ const head = to.score_head;+ const index = (m) => {+ const out = new Map();+ for (const f of m.features || []) {+ for (const [bucket, stats] of Object.entries(f.buckets || {})) {+ out.set(`${f.key}/${bucket}`, { w: Number(stats.w?.[head] ?? stats.w ?? 0), n: stats.n, rate: stats.rate?.[head] ?? null });+ }+ }+ return out;+ };+ const a = index(from);+ const b = index(to);++ const moved = [];+ for (const [key, cur] of b) {+ const prev = a.get(key);+ if (!prev) { moved.push({ key, kind: 'new', from: null, to: cur.w, delta: cur.w, samples: cur.n, rate: cur.rate }); continue; }+ const delta = Number((cur.w - prev.w).toFixed(4));+ if (Math.abs(delta) >= 0.02) moved.push({ key, kind: 'moved', from: prev.w, to: cur.w, delta, samples: cur.n, rate: cur.rate });+ }+ for (const [key, prev] of a) {+ if (!b.has(key)) moved.push({ key, kind: 'gone', from: prev.w, to: null, delta: -prev.w, samples: prev.n, rate: prev.rate });+ }+ moved.sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta));++ const featureSet = (m) => new Set((m.features || []).map((f) => f.key));+ const fa = featureSet(from);+ const fb = featureSet(to);++ return {+ score_head: head,+ rows: { from: from.training_rows, to: to.training_rows },+ fitted_at: { from: from.fitted_at, to: to.fitted_at },+ holdout_auc: Object.fromEntries(['win', 'rug', 'moon'].map((k) => {+ const x = from.holdout?.[k]?.auc ?? null;+ const y = to.holdout?.[k]?.auc ?? null;+ return [k, { from: x, to: y, delta: x != null && y != null ? Number((y - x).toFixed(4)) : null }];+ })),+ features_added: [...fb].filter((k) => !fa.has(k)),+ features_removed: [...fa].filter((k) => !fb.has(k)),+ buckets_changed: moved.length,+ // Bounded: the whole point is to be readable, and the tail below 0.02+ // log-odds is refitting noise nobody can act on.+ top_moves: moved.slice(0, 40),+ };+}++async function loadVersion(id, network) {+ const rows = await sql`+ select id, model, fitted_at, training_rows, status, decision, promoted_at, created_at,+ holdout_auc_win, holdout_auc_rug, holdout_auc_moon+ from oracle_model_versions where id = ${id} and network = ${network} limit 1+ `;+ return rows[0] || null;+}++export default wrap(async (req, res) => {+ if (cors(req, res)) return;+ if (!method(req, res, ['GET'])) return;+ if (await rateLimited(req, res, limits.publicRead, clientIp(req))) return;++ const url = new URL(req.url, 'http://localhost');+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';+ const view = url.searchParams.get('view') || 'active';++ // Best effort: a database that is down should still let the endpoint publish+ // the model the container is currently scoring with, which is the honest+ // answer to "what is running right now".+ let provenance;+ try {+ provenance = await ensureActiveModel({ network });+ } catch {+ provenance = modelProvenance();+ }+ const model = activeModel();++ res.setHeader('cache-control', 'public, max-age=60, s-maxage=300, stale-while-revalidate=600');++ if (view === 'card') {+ return json(res, 200, { ok: true, network, card: card(model, provenance) });+ }++ if (view === 'registry') {+ try {+ const rows = await sql`+ select id, fitted_at, training_rows, status, decision, promoted_at, created_at,+ holdout_auc_win, holdout_auc_rug, holdout_auc_moon+ from oracle_model_versions+ where network = ${network}+ order by created_at desc+ limit ${MAX_REGISTRY}+ `;+ return json(res, 200, {+ ok: true,+ network,+ active_version_id: provenance.version_id,+ // Refused candidates are listed too, on purpose. A registry that only+ // shows the winners is a highlight reel, not a record.+ versions: rows.map((r) => ({+ id: Number(r.id),+ status: r.status,+ decision: r.decision,+ fitted_at: r.fitted_at,+ training_rows: r.training_rows,+ promoted_at: r.promoted_at,+ created_at: r.created_at,+ holdout_auc: { win: r.holdout_auc_win, rug: r.holdout_auc_rug, moon: r.holdout_auc_moon },+ })),+ });+ } catch (err) {+ if (isDbUnavailableError(err)) {+ return json(res, 200, { ok: true, network, degraded: true, versions: [], active_version_id: null });+ }+ throw err;+ }+ }++ if (view === 'diff') {+ const from = Number(url.searchParams.get('from'));+ const to = Number(url.searchParams.get('to'));+ if (!Number.isInteger(from) || !Number.isInteger(to) || from <= 0 || to <= 0) {+ return json(res, 400, { ok: false, error: 'diff needs integer from and to version ids (see view=registry)' });+ }+ const [a, b] = await Promise.all([loadVersion(from, network), loadVersion(to, network)]);+ if (!a) return json(res, 404, { ok: false, error: `model version ${from} not found` });+ if (!b) return json(res, 404, { ok: false, error: `model version ${to} not found` });+ return json(res, 200, { ok: true, network, from: from, to: to, diff: diffModels(a.model, b.model) });+ }++ // Default: the whole thing. Weights included, deliberately.+ return json(res, 200, {+ ok: true,+ network,+ card: card(model, provenance),+ model,+ usage: {+ npm: '@three-ws/oracle-model',+ example: "import { OracleModel } from '@three-ws/oracle-model';\nconst oracle = await OracleModel.fetch();\nconsole.log(oracle.score({ organic_score: 0.82, unique_buyers: 41, smart_money_count: 2 }));",+ docs: 'https://three.ws/docs/oracle-model',+ lab: 'https://three.ws/oracle-lab',+ },+ });+});diff --git a/packages/oracle-model/LICENSE b/packages/oracle-model/LICENSEnew file mode 100644index 000000000..dff21b7f4--- /dev/null+++ b/packages/oracle-model/LICENSE@@ -0,0 +1,20 @@+Copyright 2026 nirholas++All rights reserved.++This software is proprietary and may not be used, copied, modified, distributed,+translated, or made available to any third party without the express written+permission of the copyright owner.++No rights are granted by implication, estoppel, or otherwise. Use of this+software is subject to the terms of a separate license agreement with the+copyright owner.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.++IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/packages/oracle-model/README.md b/packages/oracle-model/README.mdnew file mode 100644index 000000000..a6942664f--- /dev/null+++ b/packages/oracle-model/README.md@@ -0,0 +1,225 @@+# @three-ws/oracle-model++**The three.ws Oracle, running on your machine, with the real weights.**++The Oracle watches every pump.fun launch for its first ninety seconds and scores+it. This package is that scorer. Not a client for a scoring API: the actual+model, downloaded once and evaluated locally.++```bash+npm install @three-ws/oracle-model+```++```js+import { OracleModel } from '@three-ws/oracle-model';++const oracle = await OracleModel.fetch(); // one request, ~32KB++const verdict = oracle.score({+ organic_score: 0.82,+ unique_buyers: 41,+ buy_volume_sol: 26,+ snipe_ratio: 0.12,+ smart_money_count: 2,+ dev_sold: false,+ creator_launches: 3,+ creator_wins: 1,+});++verdict.score // 90+verdict.tier // 'prime'+verdict.upside // 99 chance it runs+verdict.rugRisk // 1 chance a first-sight holder ends down 50%++verdict.giveBackRisk // 41 chance it runs and hands it straight back+```++After `fetch()` there is no network. No API key, no rate limit, no per-call+billing, no telemetry. Score a million launches in a loop if you want.++## Why publish the weights++Most prediction products publish a number and ask to be believed. The model here+is a lookup table of bucket weights, so publishing it costs nothing and changes+what kind of claim we are making: every score three.ws has ever shown can be+reproduced offline, by anyone, forever.++That cuts both ways on purpose. `verify()` lets you re-measure the model against+outcomes **you** collected. If our published numbers do not survive contact with+an independent sample, you will find out from us.++## What the score means++The score line is **not a percentage**. A score of 86 claims a 45% chance, not+an 86% one.++| Tier | Score | Claims | Held out (n=74,211) |+|---|---|---|---|+| Prime | 86+ | P(win) >= 45% | 46.4% observed, n=304 |+| Strong | 72+ | P(win) >= 25% | 39.3% observed, n=858 |+| Lean | 56+ | P(win) >= 12% | 23.3% observed, n=1,415 |+| Watch | 34+ | P(win) >= 5% | 10.4% observed, n=2,790 |+| Avoid | 0+ | below that | 1.8% observed, n=68,844 |++Use `probabilityFromScore()` and `scoreFromProbability()` to convert. The+`performance()` method returns the live table, so the numbers above can never go+stale relative to the model you actually loaded.++### Three questions, not one++The model has three heads, fitted together on one design matrix:++| Head | Question | Base rate | Held-out AUC |+|---|---|---|---|+| `win` | Did it run **and** is a first-sight holder still up? | 2.94% | 0.840 |+| `rug` | Is a first-sight holder down more than half? | 11.36% | 0.918 |+| `moon` | Did it run at all (graduated, or peaked 3x+)? | 9.51% | 0.892 |++The published score anchors on `win`. That is deliberate, and it is the whole+reason this version exists: ranking on `moon` alone means a coin that spikes 3x+and goes to zero counts as a hit, which is how a prediction engine ends up+confidently recommending a chart that is a cliff.++**`giveBackRisk` is the number to watch.** It is `1 - P(win) / P(moon)`: given+this coin runs, how often does one like it hand the run straight back? A launch+with 80% upside and 90% give-back is not an opportunity, it is a trap, and no+single-headed score can tell you the difference.++## Every score shows its work++```js+const { math } = oracle.explain(signals);++math.formula // 'p = 1 / (1 + exp(-(intercept + sum(term log_odds))))'+math.intercept // -3.8771+math.terms // one row per bucket, with its sample count+math.total_log_odds // add the column up; you will land here+math.probability // sigmoid of that+```++There is no hidden layer and nothing to trust. Every term is a bucket the model+was fitted on, published with the number of labeled launches behind it and what+actually happened to them:++```js+oracle.score(signals).why[0];+// {+// feature: 'smart_money_count', label: 'proven wallets in the book',+// bucket: '2-4', weight: 1.4698, samples: 351,+// observed: { win: 0.5499, rug: 0, moon: 0.9886 }+// }+```++351 launches had 2 or 3 proven wallets buy inside the window. 55.0% of them ran+and held. Zero rugged. That is the claim, and the count is right beside it.++## Check our work++```js+const report = oracle.verify([+ { signals: {/* ... */}, outcome: true },+ { signals: {/* ... */}, outcome: false },+]);++report.auc // ranking quality on YOUR data+report.brier // calibration error+report.reliability // does a claim of 25% happen 25% of the time?+```++## Watch it learn++The model refits every six hours against fresh outcomes and only replaces the+live one if it beats it on held-out ranking. Every version, promoted or refused,+is public with the reason.++```js+const registry = await fetch('https://three.ws/api/oracle/model?view=registry')+ .then((r) => r.json());++const [latest, previous] = registry.versions;+const a = new OracleModel(await load(previous.id));+const b = new OracleModel(await load(latest.id));++a.diff(b).moves.slice(0, 5);+// [{ key: 'snipe_ratio/0.3-0.7', from: 0.41, to: 0.58, delta: 0.17, samples: 8102 }, ...]+```++That is a machine changing its mind, in public, with the evidence attached.++## API++| Method | What it does |+|---|---|+| `OracleModel.fetch(opts?)` | Download the live model. One request. |+| `new OracleModel(doc)` | Build from a document you already have (pin a version). |+| `.score(signals)` | Verdict: score, tier, three probabilities, `why`. |+| `.explain(signals)` | The same, with the arithmetic shown term by term. |+| `.performance(head?)` | Held-out AUC, Brier, precision, reliability curve. |+| `.verify(samples, head?)` | Re-measure the model on your own labeled data. |+| `.diff(other, threshold?)` | Every bucket weight that moved between two versions. |+| `.rank(launches, opts?)` | Sort a list of launches by score, best first. |+| `.probabilityFromScore(s)` | Convert a 0-100 score to the probability it claims. |+| `.scoreFromProbability(p)` | The inverse. |+| `.tierFor(score)` | Which rung a score sits on. |++Every signal is optional. A missing one lands in the model's fitted `null`+bucket, which carries real information (a coin nobody has sold yet is telling you+something) rather than being silently treated as zero. `verdict.confidence`+reports how much you actually supplied.++### Signals++| Signal | Meaning |+|---|---|+| `organic_score` | 0-1, demand that does not look manufactured |+| `bundle_score` | 0-1, how bundled the opening buys were |+| `snipe_ratio` | 0-1, share of supply taken at open |+| `timing_entropy` | 0-1, how spread out the buys were in time |+| `concentration_top1` / `top5` / `top10` | 0-1, holder concentration |+| `unique_buyers` / `unique_sellers` | wallet counts in the window |+| `buy_volume_sol` / `sell_volume_sol` / `net_volume_sol` | SOL flow |+| `trade_count`, `buy_sell_ratio` | tape shape |+| `largest_buy_sol`, `avg_buy_sol`, `median_buy_sol` | buy size distribution |+| `dev_buy_sol`, `dev_sell_sol`, `dev_sold` | what the creator did |+| `mc_sol_first_seen` | market cap in SOL when first observed |+| `smart_money_count` | proven wallets that bought in the window |+| `creator_launches`, `creator_wins` | creator track record (or `creator_record`) |+| `category` | narrative bucket (`animal`, `news`, `tech`, ...) |++Two more (`fresh_wallet_ratio`, `bubblemap_connectivity`) are accepted and+currently ignored: they are null in the training corpus, so the fitter drops them+rather than pretend to have learned something. `oracle.droppedFeatures` names+them. If they start arriving, the next refit picks them up with no code change,+here or upstream.++## A note on how the labels are made++The outcome a model is trained on matters more than the model. Ours used to ask+whether a coin's market cap had fallen under a hardcoded $3,000.++A pump.fun bonding curve with no real reserves is worth exactly+`30 * 1e9 / 1073000191 = 27.958993 SOL`. So that test was asking whether SOL was+above roughly $107.30. Of 206,428 coins labeled "rugged", 206,419 were under+$3,000; of 25,180 labeled survivors, the cheapest was exactly $3,000. Identical+dead curves, sorted by a price feed.++The labels now use two ratios taken from the same market-cap reading, so the SOL+price cancels out of both:++```+retained = last_market_cap / ath_market_cap+hold_multiple = ath_multiple * retained+```++`rug` is `hold_multiple <= 0.5`. `win` is a run with `hold_multiple >= 1`. The+real rug rate is 11.4%, not the 91% the old rule reported, and it holds within+two points whether a coin is checked at 60 minutes or three days old, which is+what a property of the coin is supposed to do.++## Links++- **Oracle Lab** (weights, reliability curves, version diffs, live scorer): https://three.ws/oracle-lab+- **Model API**: https://three.ws/api/oracle/model+- **Docs**: https://three.ws/docs/oracle-model+- **Live feed**: https://three.ws/oracle++Apache-2.0diff --git a/packages/oracle-model/package.json b/packages/oracle-model/package.jsonnew file mode 100644index 000000000..bf8f6d8df--- /dev/null+++ b/packages/oracle-model/package.json@@ -0,0 +1,55 @@+{+ "name": "@three-ws/oracle-model",+ "version": "0.1.0",+ "description": "The three.ws Oracle conviction model, running locally. Download the real bucket weights once, then score any pump.fun launch offline with no API key: probability it runs, probability it rugs, and the probability it runs and hands it straight back.",+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "types": "./src/index.d.ts",+ "exports": {+ ".": {+ "types": "./src/index.d.ts",+ "import": "./src/index.js",+ "default": "./src/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test test/*.test.js"+ },+ "keywords": [+ "solana",+ "pump.fun",+ "memecoin",+ "rug-detection",+ "oracle",+ "prediction",+ "logistic-regression",+ "explainable-ai",+ "offline-inference",+ "three.ws"+ ],+ "author": "nirholas <[email protected]>",+ "license": "Apache-2.0",+ "homepage": "https://three.ws/oracle-lab",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/oracle-model"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "engines": {+ "node": ">=18"+ },+ "dependencies": {},+ "publishConfig": {+ "access": "public"+ }+}diff --git a/packages/oracle-model/src/index.d.ts b/packages/oracle-model/src/index.d.tsnew file mode 100644index 000000000..5234a6f19--- /dev/null+++ b/packages/oracle-model/src/index.d.ts@@ -0,0 +1,194 @@+/**+ * @three-ws/oracle-model+ *+ * The three.ws Oracle conviction model, scoring locally from published weights.+ */++/** A tier rung on the 0-100 score line. */+export interface Tier {+ min: number;+ tier: 'prime' | 'strong' | 'lean' | 'watch' | 'avoid';+ label: 'Prime' | 'Strong' | 'Lean' | 'Watch' | 'Avoid';+}++export declare const TIERS: readonly Tier[];++/**+ * Launch-time signals. Every field is optional: a missing one lands in the+ * model's fitted `null` bucket, which carries real information rather than+ * being treated as zero.+ */+export interface LaunchSignals {+ organic_score?: number | null;+ bundle_score?: number | null;+ snipe_ratio?: number | null;+ coordination_score?: number | null;+ timing_entropy?: number | null;+ concentration_top1?: number | null;+ concentration_top5?: number | null;+ concentration_top10?: number | null;+ fresh_wallet_ratio?: number | null;+ bubblemap_connectivity?: number | null;+ unique_buyers?: number | null;+ unique_sellers?: number | null;+ buy_sell_ratio?: number | null;+ buy_volume_sol?: number | null;+ sell_volume_sol?: number | null;+ net_volume_sol?: number | null;+ trade_count?: number | null;+ largest_buy_sol?: number | null;+ avg_buy_sol?: number | null;+ median_buy_sol?: number | null;+ dev_buy_sol?: number | null;+ dev_sell_sol?: number | null;+ dev_sold?: boolean | number | null;+ mc_sol_first_seen?: number | null;+ smart_money_count?: number | null;+ /** Creator history, either pre-bucketed or as raw counts. */+ creator_record?: 'has_wins' | 'serial_no_wins' | 'repeat_no_wins' | 'first_launch' | 'unknown';+ creator_launches?: number | null;+ creator_wins?: number | null;+ category?: string | null;+ [key: string]: unknown;+}++/** Observed outcome rates for one bucket, per head. */+export interface BucketRates {+ win?: number;+ rug?: number;+ moon?: number;+}++/** One term in the log-odds sum, with the evidence behind it. */+export interface Why {+ feature: string;+ label: string;+ pillar: 'pedigree' | 'structure' | 'narrative' | 'momentum';+ bucket: string;+ value: number | string | null;+ /** Log-odds contribution on the scoring head. */+ weight: number;+ /** How many labeled launches sat in this bucket. */+ samples: number;+ observed: BucketRates | null;+}++export interface Verdict {+ /** 0-100, anchored on P(runs and holds). Not a percentage. */+ score: number;+ tier: Tier['tier'];+ tierLabel: Tier['label'];+ /** Raw probability per head: win, rug, moon. */+ probabilities: Record<string, number>;+ /** P(a first-sight holder ends down more than half), 0-100. */+ rugRisk: number | null;+ /** P(graduates or peaks at 3x or more), 0-100. */+ upside: number | null;+ /** P(hands the run straight back, given it runs), 0-100. */+ giveBackRisk: number | null;+ /** Share of the model's signals that were actually supplied, 0-100. */+ confidence: number;+ /** Every bucket that moved the score, biggest mover first. */+ why: Why[];+ model: { version: number; fitted_at: string | null; training_rows: number; score_head: string };+}++export interface Explained extends Verdict {+ math: {+ head: string;+ intercept: number;+ terms: Array<{ term: string; log_odds: number; samples: number; observed_rate: number | null }>;+ total_log_odds: number;+ probability: number;+ formula: string;+ };+}++export interface ReliabilityBand {+ lo: number;+ hi: number;+ n: number;+ observed: number | null;+ predicted: number | null;+}++export interface Performance {+ head: string;+ holdout_n: number;+ auc: number;+ brier: number;+ base_rate: number;+ precision: Record<string, { n: number; rate: number; lift: number }>;+ reliability: ReliabilityBand[];+}++export interface VerifyResult {+ head: string;+ n: number;+ base_rate: number;+ auc: number;+ brier: number;+ reliability: ReliabilityBand[];+}++export interface DiffMove {+ key: string;+ kind: 'new' | 'moved' | 'gone';+ from: number | null;+ to: number | null;+ delta: number;+ samples: number;+}++export interface DiffResult {+ head: string;+ from: { fitted_at: string | null; training_rows: number };+ to: { fitted_at: string | null; training_rows: number };+ auc: { from: number | null; to: number | null };+ moves: DiffMove[];+}++export interface FetchOptions {+ endpoint?: string;+ network?: 'mainnet' | 'devnet';+ fetch?: typeof globalThis.fetch;+ signal?: AbortSignal;+}++export declare function bucketLabel(feature: { categorical?: boolean; edges?: number[] | null }, value: number | string | null): string;++export declare class OracleModel {+ constructor(doc: object);++ readonly document: Record<string, unknown>;+ readonly version: number;+ readonly fittedAt: string | null;+ readonly trainingRows: number;+ readonly scoreHead: string;+ readonly anchors: Record<string, number>;+ readonly holdout: Record<string, unknown> | null;+ readonly droppedFeatures: Array<{ key: string; bucket: string; share: number }>;++ /** Download the live model. One request, then everything is local. */+ static fetch(opts?: FetchOptions): Promise<OracleModel>;++ score(signals?: LaunchSignals): Verdict;+ /** The same score with the arithmetic shown, term by term. */+ explain(signals?: LaunchSignals): Explained;+ /** What this model earned on launches it had never seen. */+ performance(head?: string): Performance | null;+ /** Re-measure the model against outcomes you collected yourself. */+ verify(samples: Array<{ signals: LaunchSignals; outcome: boolean | number }>, head?: string): VerifyResult;+ /** Every bucket weight that moved between two model versions. */+ diff(other: OracleModel | object, threshold?: number): DiffResult;+ rank<T>(launches: T[], opts?: { key?: string; limit?: number }): Array<T & { verdict: Verdict }>;++ scoreFromProbability(p: number): number;+ probabilityFromScore(score: number): number;+ tierFor(score: number): Tier;+}++/** Score one launch against the live model, fetching it on first use. */+export declare function score(signals: LaunchSignals, opts?: FetchOptions): Promise<Verdict>;++export default OracleModel;diff --git a/packages/oracle-model/src/index.js b/packages/oracle-model/src/index.jsnew file mode 100644index 000000000..e641083d2--- /dev/null+++ b/packages/oracle-model/src/index.js@@ -0,0 +1,474 @@+// @three-ws/oracle-model+//+// The three.ws Oracle scores every pump.fun launch in its first ninety seconds.+// This package is that scorer, running on your machine, with the real weights.+//+// Not a client for a scoring API. The model is a lookup table of bucket weights+// (roughly 32KB of JSON), so `OracleModel.fetch()` downloads it once and every+// score after that is local arithmetic: no key, no rate limit, no network, no+// telemetry back to us. Pin a model version and you can reproduce any score the+// platform has ever published, forever, offline.+//+// That is the point. A prediction product that publishes only its outputs is+// asking to be believed. One that publishes the machine can be checked.+//+// import { OracleModel } from '@three-ws/oracle-model';+//+// const oracle = await OracleModel.fetch();+// const verdict = oracle.score({+// organic_score: 0.82, unique_buyers: 41, buy_volume_sol: 26,+// snipe_ratio: 0.12, smart_money_count: 2, dev_sold: false,+// });+//+// verdict.score // 0-100, anchored on P(runs and holds)+// verdict.tier // avoid | watch | lean | strong | prime+// verdict.rugRisk // P(a first-sight holder ends down more than half)+// verdict.giveBackRisk // P(hands the run straight back | it runs)+// verdict.why // every bucket that moved it, with its sample count+//+// Zero dependencies. Runs in Node 18+, Deno, Bun, Cloudflare Workers, and the+// browser.++const DEFAULT_ENDPOINT = 'https://three.ws/api/oracle/model';++/** Tier boundaries on the 0-100 score line. A public contract since v1. */+export const TIERS = Object.freeze([+ { 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: 0, tier: 'avoid', label: 'Avoid' },+]);++const clamp = (n, lo = 0, hi = 100) => Math.max(lo, Math.min(hi, n));+const sigmoid = (z) => 1 / (1 + Math.exp(-z));+const numOrNull = (v) => {+ const n = Number(v);+ return v == null || v === '' || !Number.isFinite(n) ? null : n;+};++/**+ * Which bucket a raw signal value falls into, for one feature.+ *+ * This has to match the fitter exactly or you are reading weights that were+ * never trained on the thing you are asking about, so it is one function and+ * both sides use it.+ *+ * @param {object} feature a feature entry from the model document+ * @param {number|string|null} value the raw signal+ * @returns {string} the bucket label+ */+export function bucketLabel(feature, value) {+ if (feature.categorical) return String(value ?? 'unknown');+ if (value == null) return 'null';+ const edges = feature.edges || [];+ for (let i = 0; i < edges.length; i++) {+ if (value < edges[i]) return i === 0 ? `<${edges[0]}` : `${edges[i - 1]}-${edges[i]}`;+ }+ return `>=${edges[edges.length - 1]}`;+}++/** Human-readable name for each signal, for the `why` list. */+const LABELS = {+ organic_score: 'organic demand',+ bundle_score: 'launch coordination',+ snipe_ratio: 'sniped at open',+ coordination_score: 'buy coordination',+ timing_entropy: 'buy-timing spread',+ concentration_top1: 'top-holder share',+ concentration_top5: 'top-5 holder share',+ concentration_top10: 'top-10 holder share',+ fresh_wallet_ratio: 'fresh-wallet share',+ bubblemap_connectivity: 'funder clustering',+ unique_buyers: 'unique early buyers',+ unique_sellers: 'unique early sellers',+ buy_sell_ratio: 'buy/sell pressure',+ buy_volume_sol: 'early buy volume (SOL)',+ sell_volume_sol: 'early sell volume (SOL)',+ net_volume_sol: 'net early flow (SOL)',+ trade_count: 'trades in the window',+ largest_buy_sol: 'largest single buy (SOL)',+ avg_buy_sol: 'average buy size (SOL)',+ median_buy_sol: 'median buy size (SOL)',+ dev_buy_sol: 'dev buy size (SOL)',+ dev_sell_sol: 'dev sell size (SOL)',+ mc_sol_first_seen: 'market cap at first sight (SOL)',+ smart_money_count: 'proven wallets in the book',+ dev_sold: 'dev sold in the window',+ creator_record: 'creator launch history',+ category: 'narrative category',+};++/**+ * Turn caller input into the raw value each feature expects.+ *+ * Callers pass a flat bag of signals, which is what the observation pipeline+ * produces anyway. Two of them are derived rather than raw, so they get a+ * fallback: `creator_record` is bucketed from launch counts, and `dev_sold` is a+ * boolean the model sees as 0 or 1.+ */+function featureValue(feature, signals) {+ if (feature.key === 'creator_record') {+ if (typeof signals.creator_record === 'string') return signals.creator_record;+ const launches = numOrNull(signals.creator_launches);+ const wins = numOrNull(signals.creator_wins);+ if (launches == null) return 'unknown';+ if (wins != null && wins >= 1) return 'has_wins';+ if (launches >= 5) return 'serial_no_wins';+ if (launches >= 2) return 'repeat_no_wins';+ return 'first_launch';+ }+ if (feature.key === 'category') return String(signals.category ?? 'unknown').toLowerCase();+ if (feature.key === 'dev_sold') {+ const raw = signals.dev_sold;+ if (raw === true) return 1;+ if (raw === false) return 0;+ return numOrNull(raw);+ }+ return numOrNull(signals[feature.key]);+}++/**+ * A three.ws Oracle conviction model, loaded and ready to score.+ *+ * Construct from a model document (`new OracleModel(doc)`), or fetch the live+ * one with `OracleModel.fetch()`.+ */+export class OracleModel {+ /**+ * @param {object} doc a model document, as served by GET /api/oracle/model+ */+ constructor(doc) {+ if (!doc || typeof doc !== 'object') throw new TypeError('OracleModel: expected a model document');+ const model = doc.model && doc.model.features ? doc.model : doc;+ if (!Array.isArray(model.features) || !model.features.length) {+ throw new TypeError('OracleModel: document has no features; pass the object from GET /api/oracle/model');+ }+ if (Number(model.version) < 3) {+ throw new TypeError(`OracleModel: this package needs a v3+ model, got v${model.version}`);+ }+ /** @type {object} the raw model document, exactly as published */+ this.document = model;+ this.version = Number(model.version);+ this.fittedAt = model.fitted_at || null;+ this.trainingRows = Number(model.training_rows) || 0;+ this.scoreHead = model.score_head || 'win';+ this.heads = model.features.length ? Object.keys(model.heads || { win: null }) : [];+ this.anchors = model.tier_probability_anchors || { avoid: 0, watch: 0.05, lean: 0.12, strong: 0.25, prime: 0.45 };+ this.holdout = model.holdout || null;+ this.droppedFeatures = model.dropped_features || [];+ this._scoreAnchors = [+ [0, 0], [this.anchors.watch, 34], [this.anchors.lean, 56],+ [this.anchors.strong, 72], [this.anchors.prime, 86], [1, 100],+ ];+ }++ /**+ * Download the live model.+ *+ * One request. Cache the result and reuse the instance; nothing about scoring+ * touches the network again.+ *+ * @param {object} [opts]+ * @param {string} [opts.endpoint] override the API base (self-hosting, testing)+ * @param {string} [opts.network] mainnet (default) or devnet+ * @param {typeof fetch} [opts.fetch] inject a fetch implementation+ * @param {AbortSignal} [opts.signal]+ * @returns {Promise<OracleModel>}+ */+ static async fetch({ endpoint = DEFAULT_ENDPOINT, network = 'mainnet', fetch: fetchImpl, signal } = {}) {+ const f = fetchImpl || globalThis.fetch;+ if (typeof f !== 'function') throw new Error('OracleModel.fetch: no fetch available; pass one in opts.fetch');+ const url = `${endpoint}${endpoint.includes('?') ? '&' : '?'}network=${encodeURIComponent(network)}`;+ const res = await f(url, { headers: { accept: 'application/json' }, signal });+ if (!res.ok) throw new Error(`OracleModel.fetch: ${res.status} ${res.statusText} from ${url}`);+ const body = await res.json();+ if (!body?.model) throw new Error('OracleModel.fetch: response had no model');+ return new OracleModel(body.model);+ }++ /** Map a probability onto the 0-100 score line through the tier anchors. */+ scoreFromProbability(p) {+ const x = Math.max(0, Math.min(1, Number(p) || 0));+ for (let i = 1; i < this._scoreAnchors.length; i++) {+ const [p0, s0] = this._scoreAnchors[i - 1];+ const [p1, s1] = this._scoreAnchors[i];+ if (x <= p1) return clamp(Math.round(s0 + ((x - p0) / (p1 - p0)) * (s1 - s0)));+ }+ return 100;+ }++ /**+ * The probability a score claims.+ *+ * The score line is not a percentage. A score of 86 claims a 45% chance, not+ * an 86% one, and every table that treated it as a percentage overstated the+ * engine's own claim by up to four times.+ */+ probabilityFromScore(score) {+ const s = clamp(Number(score) || 0);+ for (let i = 1; i < this._scoreAnchors.length; i++) {+ const [p0, s0] = this._scoreAnchors[i - 1];+ const [p1, s1] = this._scoreAnchors[i];+ if (s <= s1) return s1 === s0 ? p1 : p0 + ((s - s0) / (s1 - s0)) * (p1 - p0);+ }+ return 1;+ }++ /** The tier a 0-100 score sits in. */+ tierFor(score) {+ const s = clamp(Number(score) || 0);+ return TIERS.find((t) => s >= t.min) || TIERS[TIERS.length - 1];+ }++ /**+ * Score one launch.+ *+ * @param {object} signals flat bag of launch-time signals. Everything is+ * optional: a missing signal lands in the model's fitted `null` bucket,+ * which carries real information (a coin nobody has sold yet is telling you+ * something) rather than being treated as zero.+ * @returns {{+ * score:number, tier:string, tierLabel:string,+ * probabilities:Record<string,number>,+ * rugRisk:number|null, upside:number|null, giveBackRisk:number|null,+ * confidence:number, why:Array<object>, model:object+ * }}+ */+ score(signals = {}) {+ const heads = Object.keys(this.document.heads || {});+ const z = {};+ for (const h of heads) z[h] = Number(this.document.heads[h]?.intercept) || 0;++ const why = [];+ let observed = 0;+ for (const feature of this.document.features) {+ const value = featureValue(feature, signals);+ const bucket = bucketLabel(feature, value);+ const stats = feature.buckets?.[bucket];+ // 'null' and 'unknown' are what a feature reads when the caller supplied+ // nothing. Both are real fitted buckets that carry signal, but neither is+ // an observation, and counting them as one made an empty input look 8%+ // confident instead of 0%.+ if (value != null && bucket !== 'null' && bucket !== 'unknown') observed++;+ if (!stats) continue;+ for (const h of heads) z[h] += Number(stats.w?.[h]) || 0;+ why.push({+ feature: feature.key,+ label: LABELS[feature.key] || feature.key,+ pillar: feature.pillar,+ bucket,+ value,+ weight: Number(stats.w?.[this.scoreHead]) || 0,+ samples: stats.n ?? 0,+ // What actually happened to the launches in this bucket. The whole+ // claim, checkable against the count beside it.+ observed: stats.rate || null,+ });+ }+ why.sort((a, b) => Math.abs(b.weight) - Math.abs(a.weight));++ const probabilities = {};+ for (const h of heads) probabilities[h] = Number(sigmoid(z[h]).toFixed(4));++ const p = probabilities[this.scoreHead] ?? 0;+ const score = this.scoreFromProbability(p);+ const tier = this.tierFor(score);++ const rugRisk = probabilities.rug != null ? clamp(Math.round(probabilities.rug * 100)) : null;+ const upside = probabilities.moon != null ? clamp(Math.round(probabilities.moon * 100)) : null;+ const giveBackRisk = probabilities.moon > 0 && probabilities.win != null+ ? clamp(Math.round((1 - Math.min(1, probabilities.win / probabilities.moon)) * 100))+ : null;++ return {+ score,+ tier: tier.tier,+ tierLabel: tier.label,+ probabilities,+ rugRisk,+ upside,+ giveBackRisk,+ confidence: clamp(Math.round((observed / Math.max(1, this.document.features.length)) * 100)),+ why,+ model: { version: this.version, fitted_at: this.fittedAt, training_rows: this.trainingRows, score_head: this.scoreHead },+ };+ }++ /**+ * The same score, with the arithmetic shown.+ *+ * Returns every term that went into the log-odds sum and what it added, so a+ * reader can add the column up by hand and land on the same probability. Use+ * it to audit a published score, or to work out which signal to change.+ */+ explain(signals = {}) {+ const verdict = this.score(signals);+ const head = this.scoreHead;+ const intercept = Number(this.document.heads?.[head]?.intercept) || 0;+ const terms = verdict.why.map((w) => ({+ term: `${w.feature} = ${w.bucket}`,+ log_odds: w.weight,+ samples: w.samples,+ observed_rate: w.observed?.[head] ?? null,+ }));+ const total = terms.reduce((a, t) => a + t.log_odds, intercept);+ return {+ ...verdict,+ math: {+ head,+ intercept,+ terms,+ total_log_odds: Number(total.toFixed(4)),+ probability: Number(sigmoid(total).toFixed(4)),+ formula: 'p = 1 / (1 + exp(-(intercept + sum(term log_odds))))',+ },+ };+ }++ /**+ * What the model earned on launches it had never seen, per head.+ *+ * AUC, Brier score, precision at the top 1/5/10/25%, and the reliability+ * curve. Published with the weights so nobody has to take the ranking on+ * trust, including us.+ */+ performance(head = this.scoreHead) {+ const h = this.holdout?.[head];+ if (!h) return null;+ return {+ head,+ holdout_n: this.holdout.n,+ auc: h.auc,+ brier: h.brier,+ base_rate: h.base_rate,+ precision: h.precision,+ reliability: h.reliability,+ };+ }++ /**+ * Check the model against outcomes you collected yourself.+ *+ * Give it launches with a known result and it returns AUC, Brier, and the+ * reliability curve on YOUR data. If our published numbers do not survive+ * contact with an independent sample, this is how you find out, and we would+ * rather you could.+ *+ * @param {Array<{signals:object, outcome:boolean|number}>} samples+ * @param {string} [head] which question the outcome answers+ */+ verify(samples, head = this.scoreHead) {+ if (!Array.isArray(samples) || !samples.length) throw new TypeError('verify: pass a non-empty array of {signals, outcome}');+ const ps = [];+ const ys = [];+ for (const s of samples) {+ ps.push(this.score(s.signals || {}).probabilities[head] ?? 0);+ ys.push(s.outcome ? 1 : 0);+ }++ const order = [...ps.keys()].sort((a, b) => ps[a] - ps[b]);+ let sumPosRanks = 0, nPos = 0, nNeg = 0;+ for (let i = 0; i < order.length;) {+ let j = i;+ while (j < order.length && ps[order[j]] === ps[order[i]]) j++;+ const avgRank = (i + j + 1) / 2;+ for (let k = i; k < j; k++) {+ if (ys[order[k]] === 1) { sumPosRanks += avgRank; nPos++; } else nNeg++;+ }+ i = j;+ }+ const auc = nPos && nNeg ? (sumPosRanks - (nPos * (nPos + 1)) / 2) / (nPos * nNeg) : 0.5;+ const brier = ps.reduce((a, p, i) => a + (p - ys[i]) ** 2, 0) / ps.length;++ const edges = [0, 0.05, 0.12, 0.25, 0.45, 1.0001];+ const reliability = [];+ for (let i = 0; i + 1 < edges.length; i++) {+ let n = 0, good = 0, sumP = 0;+ for (let k = 0; k < ps.length; k++) {+ if (ps[k] >= edges[i] && ps[k] < edges[i + 1]) { n++; good += ys[k]; sumP += ps[k]; }+ }+ reliability.push({+ lo: edges[i], hi: Math.min(1, edges[i + 1]), n,+ observed: n ? Number((good / n).toFixed(4)) : null,+ predicted: n ? Number((sumP / n).toFixed(4)) : null,+ });+ }+ return {+ head, n: ps.length,+ base_rate: Number((ys.reduce((a, b) => a + b, 0) / ys.length).toFixed(4)),+ auc: Number(auc.toFixed(4)),+ brier: Number(brier.toFixed(5)),+ reliability,+ };+ }++ /**+ * What changed between two model versions.+ *+ * Every bucket whose weight moved, biggest move first, with the sample count+ * behind each one. This is the closest you can get to watching a model change+ * its mind, and it works entirely on documents you already downloaded.+ *+ * @param {OracleModel|object} other the model to compare against+ * @param {number} [threshold] ignore moves smaller than this in log-odds+ */+ diff(other, threshold = 0.02) {+ const to = other instanceof OracleModel ? other : new OracleModel(other);+ const head = this.scoreHead;+ const index = (m) => {+ const out = new Map();+ for (const f of m.document.features) {+ for (const [bucket, stats] of Object.entries(f.buckets || {})) {+ out.set(`${f.key}/${bucket}`, { w: Number(stats.w?.[head]) || 0, n: stats.n });+ }+ }+ return out;+ };+ const a = index(this);+ const b = index(to);+ const moves = [];+ for (const [key, cur] of b) {+ const prev = a.get(key);+ if (!prev) { moves.push({ key, kind: 'new', from: null, to: cur.w, delta: cur.w, samples: cur.n }); continue; }+ const delta = Number((cur.w - prev.w).toFixed(4));+ if (Math.abs(delta) >= threshold) moves.push({ key, kind: 'moved', from: prev.w, to: cur.w, delta, samples: cur.n });+ }+ for (const [key, prev] of a) {+ if (!b.has(key)) moves.push({ key, kind: 'gone', from: prev.w, to: null, delta: -prev.w, samples: prev.n });+ }+ moves.sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta));+ return {+ head,+ from: { fitted_at: this.fittedAt, training_rows: this.trainingRows },+ to: { fitted_at: to.fittedAt, training_rows: to.trainingRows },+ auc: { from: this.performance(head)?.auc ?? null, to: to.performance(head)?.auc ?? null },+ moves,+ };+ }++ /** Rank a list of launches by score, best first. Convenience for scanners. */+ rank(launches, { key = 'signals', limit = Infinity } = {}) {+ return launches+ .map((l) => ({ ...l, verdict: this.score(l?.[key] ?? l) }))+ .sort((a, b) => b.verdict.score - a.verdict.score)+ .slice(0, limit);+ }+}++/**+ * Score one launch against the live model, fetching it if needed.+ *+ * Convenience for a one-off. In anything that scores more than once, hold onto+ * an `OracleModel` instead so the download happens once.+ *+ * @param {object} signals+ * @param {object} [opts] forwarded to OracleModel.fetch+ */+let _shared = null;+export async function score(signals, opts = {}) {+ if (!_shared) _shared = await OracleModel.fetch(opts);+ return _shared.score(signals);+}++export default OracleModel;diff --git a/packages/oracle-model/test/oracle-model.test.js b/packages/oracle-model/test/oracle-model.test.jsnew file mode 100644index 000000000..ee7bdda1c--- /dev/null+++ b/packages/oracle-model/test/oracle-model.test.js@@ -0,0 +1,252 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { OracleModel, TIERS, bucketLabel } from '../src/index.js';++// The real shipped model, not a fixture. The package's whole promise is that it+// scores the same as production, so the test has to hold it to the same weights+// production boots on. If the bootstrap changes shape, this fails first.+const DOC = JSON.parse(readFileSync(new URL('../../../api/_lib/oracle/conviction-model.json', import.meta.url), 'utf8'));++const strongLaunch = () => ({+ organic_score: 0.85, bundle_score: 0.04, snipe_ratio: 0.12, timing_entropy: 0.82,+ concentration_top1: 0.04, concentration_top5: 0.42, concentration_top10: 0.55,+ unique_buyers: 44, unique_sellers: 2, buy_sell_ratio: 6.2,+ buy_volume_sol: 31, sell_volume_sol: 1.1, net_volume_sol: 30, trade_count: 61,+ largest_buy_sol: 6.4, avg_buy_sol: 0.71, median_buy_sol: 0.3,+ dev_buy_sol: 1.3, dev_sell_sol: 0, dev_sold: false, mc_sol_first_seen: 29.2,+ smart_money_count: 3, coordination_score: 0.05,+ creator_launches: 4, creator_wins: 2, category: 'animal',+});++const deadLaunch = () => ({+ organic_score: 0.04, bundle_score: 0.82, snipe_ratio: 0.93, timing_entropy: 0.08,+ concentration_top1: 0.52, concentration_top5: 0.96, concentration_top10: 0.99,+ unique_buyers: 1, unique_sellers: 14, buy_sell_ratio: 0.18,+ buy_volume_sol: 0.2, sell_volume_sol: 16, net_volume_sol: -15.8, trade_count: 52,+ largest_buy_sol: 0.08, avg_buy_sol: 0.01, median_buy_sol: 0.008,+ dev_buy_sol: 0.01, dev_sell_sol: 3.2, dev_sold: true, mc_sol_first_seen: 41,+ smart_money_count: 0, coordination_score: 0.62,+ creator_launches: 8, creator_wins: 0, category: 'unknown',+});++test('loads the shipped v3 model', () => {+ const m = new OracleModel(DOC);+ assert.ok(m.version >= 3, 'expected a v3+ model');+ assert.equal(m.scoreHead, 'win');+ assert.ok(m.trainingRows > 50_000);+ assert.ok(m.document.features.length >= 15);+});++test('refuses a v2 model rather than scoring it wrong', () => {+ // A v2 document has scalar weights and no heads. Scoring it with v3 code+ // would read `stats.w.win` off a number and silently produce zeros, which is+ // exactly the kind of quiet wrongness this package exists to rule out.+ const v2 = { version: 2, features: [{ key: 'organic_score', buckets: { '<0.2': { w: -1 } } }] };+ assert.throws(() => new OracleModel(v2), /v3\+ model/);+});++test('refuses a document with no features', () => {+ assert.throws(() => new OracleModel({ version: 3, features: [] }), /no features/);+ assert.throws(() => new OracleModel(null), /model document/);+});++test('accepts the full API envelope as well as a bare model', () => {+ const wrapped = new OracleModel({ model: DOC });+ const bare = new OracleModel(DOC);+ assert.equal(wrapped.score(strongLaunch()).score, bare.score(strongLaunch()).score);+});++test('separates a strong launch from a dead one', () => {+ const m = new OracleModel(DOC);+ const strong = m.score(strongLaunch());+ const dead = m.score(deadLaunch());+ assert.ok(strong.score > dead.score, `expected ${strong.score} > ${dead.score}`);+ assert.ok(strong.probabilities.win > dead.probabilities.win);+ assert.equal(dead.tier, 'avoid');+});++test('publishes all three heads and the give-back ratio', () => {+ const m = new OracleModel(DOC);+ const v = m.score(strongLaunch());+ for (const head of ['win', 'rug', 'moon']) {+ assert.ok(typeof v.probabilities[head] === 'number', `missing ${head}`);+ assert.ok(v.probabilities[head] >= 0 && v.probabilities[head] <= 1);+ }+ assert.ok(v.rugRisk >= 0 && v.rugRisk <= 100);+ assert.ok(v.upside >= 0 && v.upside <= 100);+ // give-back is 1 - win/moon: a run you keep cannot also be a run you lost.+ assert.ok(v.giveBackRisk >= 0 && v.giveBackRisk <= 100);+});++test('the score line is not a percentage, and the two maps invert', () => {+ const m = new OracleModel(DOC);+ // 86 is Prime and claims the prime anchor, which is well under 0.86.+ assert.ok(m.probabilityFromScore(86) < 0.6);+ assert.equal(m.probabilityFromScore(86), m.anchors.prime);+ for (const s of [0, 34, 56, 72, 86, 100]) {+ assert.equal(m.scoreFromProbability(m.probabilityFromScore(s)), s, `round trip failed at ${s}`);+ }+});++test('tiers are monotone and cover the whole line', () => {+ const m = new OracleModel(DOC);+ let last = 101;+ for (const t of TIERS) {+ assert.ok(t.min < last, 'tiers must descend');+ last = t.min;+ }+ assert.equal(m.tierFor(0).tier, 'avoid');+ assert.equal(m.tierFor(100).tier, 'prime');+ assert.equal(m.tierFor(-5).tier, 'avoid');+});++test('explain() adds up to the probability it reports', () => {+ const m = new OracleModel(DOC);+ const ex = m.explain(strongLaunch());+ const summed = ex.math.terms.reduce((a, t) => a + t.log_odds, ex.math.intercept);+ assert.ok(Math.abs(summed - ex.math.total_log_odds) < 1e-3, 'terms must sum to the stated log-odds');+ assert.ok(Math.abs(ex.math.probability - ex.probabilities.win) < 1e-3, 'stated math must match the verdict');+});++test('every reason carries the sample count behind it', () => {+ const m = new OracleModel(DOC);+ const v = m.score(strongLaunch());+ assert.ok(v.why.length > 0);+ for (const w of v.why) {+ assert.ok(Number.isFinite(w.weight));+ assert.ok(w.samples > 0, `${w.feature} claimed evidence with no samples`);+ assert.ok(w.observed && typeof w.observed.win === 'number');+ }+ // Sorted by absolute influence so the headline reason really is the headline.+ for (let i = 1; i < v.why.length; i++) {+ assert.ok(Math.abs(v.why[i - 1].weight) >= Math.abs(v.why[i].weight));+ }+});++test('missing signals land in the fitted null bucket, not at zero', () => {+ const m = new OracleModel(DOC);+ const empty = m.score({});+ assert.ok(Number.isFinite(empty.score));+ assert.equal(empty.confidence, 0);+ // A launch we know nothing about must not outrank one we know is strong.+ assert.ok(empty.score < m.score(strongLaunch()).score);+});++test('confidence tracks how much was actually supplied', () => {+ const m = new OracleModel(DOC);+ assert.equal(m.score({}).confidence, 0);+ assert.ok(m.score(strongLaunch()).confidence > 80);+});++test('bucketLabel matches the fitter on edges, nulls, and categories', () => {+ const feature = { edges: [0.2, 0.4] };+ assert.equal(bucketLabel(feature, 0.1), '<0.2');+ assert.equal(bucketLabel(feature, 0.2), '0.2-0.4');+ assert.equal(bucketLabel(feature, 0.9), '>=0.4');+ assert.equal(bucketLabel(feature, null), 'null');+ assert.equal(bucketLabel({ categorical: true }, 'animal'), 'animal');+ assert.equal(bucketLabel({ categorical: true }, null), 'unknown');+});++test('creator history buckets from raw counts or a pre-bucketed label', () => {+ const m = new OracleModel(DOC);+ const base = strongLaunch();+ const viaCounts = m.score({ ...base, creator_launches: 6, creator_wins: 0 });+ const viaLabel = m.score({ ...base, creator_record: 'serial_no_wins', creator_launches: undefined, creator_wins: undefined });+ assert.equal(viaCounts.score, viaLabel.score);+});++test('performance() reports the held-out numbers the weights shipped with', () => {+ const m = new OracleModel(DOC);+ const perf = m.performance();+ assert.ok(perf.auc > 0.7, `win AUC ${perf.auc} is too low to publish`);+ assert.ok(perf.holdout_n > 1000);+ assert.ok(perf.reliability.length > 0);+ assert.ok(m.performance('rug').auc > 0.7, 'the rug head must rank too');+});++test('verify() reproduces AUC on a caller-supplied sample', () => {+ const m = new OracleModel(DOC);+ // Strong launches win, dead ones do not: a perfectly separable sample, so a+ // correct AUC implementation has to return exactly 1.+ const samples = [+ ...Array.from({ length: 5 }, () => ({ signals: strongLaunch(), outcome: 1 })),+ ...Array.from({ length: 5 }, () => ({ signals: deadLaunch(), outcome: 0 })),+ ];+ const out = m.verify(samples);+ assert.equal(out.n, 10);+ assert.equal(out.auc, 1);+ assert.equal(out.base_rate, 0.5);+ assert.ok(out.brier >= 0 && out.brier <= 1);+});++test('verify() refuses an empty sample instead of returning a made-up AUC', () => {+ const m = new OracleModel(DOC);+ assert.throws(() => m.verify([]), /non-empty/);+});++test('diff() against itself reports no movement', () => {+ const m = new OracleModel(DOC);+ const d = m.diff(new OracleModel(DOC));+ assert.equal(d.moves.length, 0);+ assert.equal(d.auc.from, d.auc.to);+});++test('diff() finds a moved weight and a removed bucket', () => {+ const m = new OracleModel(DOC);+ const mutated = JSON.parse(JSON.stringify(DOC));+ const feature = mutated.features[0];+ const [firstBucket, ...rest] = Object.keys(feature.buckets);+ feature.buckets[firstBucket].w.win += 0.5;+ const gone = rest[0];+ delete feature.buckets[gone];++ const d = m.diff(new OracleModel(mutated));+ const moved = d.moves.find((x) => x.key === `${feature.key}/${firstBucket}`);+ assert.ok(moved, 'expected the bumped bucket in the diff');+ assert.ok(Math.abs(moved.delta - 0.5) < 1e-6);+ assert.ok(d.moves.some((x) => x.key === `${feature.key}/${gone}` && x.kind === 'gone'));+});++test('rank() orders launches best first and respects the limit', () => {+ const m = new OracleModel(DOC);+ const ranked = m.rank([+ { mint: 'dead', signals: deadLaunch() },+ { mint: 'strong', signals: strongLaunch() },+ ]);+ assert.equal(ranked[0].mint, 'strong');+ assert.equal(m.rank([{ signals: strongLaunch() }, { signals: deadLaunch() }], { limit: 1 }).length, 1);+});++test('scoring never mutates the caller signals or the model document', () => {+ const m = new OracleModel(DOC);+ const signals = strongLaunch();+ const before = JSON.stringify(signals);+ const docBefore = JSON.stringify(m.document);+ m.explain(signals);+ assert.equal(JSON.stringify(signals), before);+ assert.equal(JSON.stringify(m.document), docBefore);+});++test('fetch() surfaces a failed request instead of scoring on nothing', async () => {+ await assert.rejects(+ OracleModel.fetch({ fetch: async () => ({ ok: false, status: 503, statusText: 'Service Unavailable' }) }),+ /503/,+ );+ await assert.rejects(+ OracleModel.fetch({ fetch: async () => ({ ok: true, json: async () => ({ ok: true }) }) }),+ /no model/,+ );+});++test('fetch() builds the model from a well-formed response', async () => {+ const m = await OracleModel.fetch({+ network: 'mainnet',+ fetch: async (url) => {+ assert.ok(url.includes('network=mainnet'));+ return { ok: true, json: async () => ({ ok: true, model: DOC }) };+ },+ });+ assert.equal(m.version, DOC.version);+});diff --git a/scripts/oracle-fit.mjs b/scripts/oracle-fit.mjsindex c7c815287..60fde94ab 100644--- a/scripts/oracle-fit.mjs+++ b/scripts/oracle-fit.mjs@@ -1,274 +1,123 @@-// Fit the Oracle conviction model from real outcomes.+// Fit the Oracle conviction model from real outcomes, and report what it learned.//-// Reads oracle_training_set (the durable launch-time-features + outcome-// snapshot written by the intel labeler), fits a transparent bucketed logistic-// model ("good" = graduated or pumped >= 3x ATH), validates on a time-split-// holdout, and prints the fitted bucket weights as the JSON blob-// api/_lib/oracle/conviction-model.json is built from, plus the calibration-// table that maps model probability to the public tier ladder.+// The fitting itself lives in api/_lib/oracle/fit.js, shared with the production+// learning loop (api/cron/oracle-refit.js) so the terminal and the cron can+// never disagree about what "the model" means. This file is the CLI around it:+// load rows, fit, print a readable report, optionally write the bootstrap JSON+// that ships in the container image.//-// Rerun whenever the labeled set has grown meaningfully (it grows ~30k-// coins/day now the labeler keeps up):+// node scripts/oracle-fit.mjs fit and report, write nothing+// node scripts/oracle-fit.mjs --write also update conviction-model.json+// node scripts/oracle-fit.mjs --rows 200000 cap the training window+// node scripts/oracle-fit.mjs --epochs 16 more SGD passes per head+// node scripts/oracle-fit.mjs --json machine-readable report on stdout//-// node scripts/oracle-fit.mjs # fit + report-// node scripts/oracle-fit.mjs --write # also update conviction-model.json-//-// The model is one-hot buckets -> logistic regression. Every weight is a-// per-bucket log-odds contribution anyone can read, the exact opposite of a-// black box: the fitted JSON ships with n / good-rate / lift per bucket.+// Production does not need this script to stay current: the refit cron promotes+// new weights into oracle_model_versions on its own schedule. Run it when you+// want to see the numbers, or to refresh the bootstrap a cold container boots on.-import { readFileSync, writeFileSync } from 'node:fs';+import { readFileSync, writeFileSync, existsSync } from 'node:fs';import { neon } from '@neondatabase/serverless';+import { buildModel, LABEL_VERSION, MIN_TRAINING_ROWS } from '../api/_lib/oracle/fit.js';const MODEL_PATH = new URL('../api/_lib/oracle/conviction-model.json', import.meta.url);+// DATABASE_URL lives in .env.local, not .env (.env holds only the QA audit+// login). Reading just one of them is why a plain run of this script died with+// "DATABASE_URL not set" for weeks, which is a large part of why the model was+// never refit. Read both, and let a real environment variable win over either.function loadEnvUrl() {if (process.env.DATABASE_URL) return process.env.DATABASE_URL;- try {- const env = readFileSync(new URL('../.env', import.meta.url), 'utf8');- const m = env.match(/^DATABASE_URL=(.+)$/m);- if (m) return m[1].trim();- } catch { /* fall through */ }- throw new Error('DATABASE_URL not set and not found in .env');+ for (const name of ['../.env.local', '../.env']) {+ const url = new URL(name, import.meta.url);+ if (!existsSync(url)) continue;+ const match = readFileSync(url, 'utf8').match(/^\s*DATABASE_URL\s*=\s*(.+)\s*$/m);+ if (match) return match[1].trim().replace(/^["']|["']$/g, '');+ }+ throw new Error('DATABASE_URL is not set and was not found in .env.local or .env');}-const sql = neon(loadEnvUrl());--// ── Feature definition ────────────────────────────────────────────────────────-// Buckets follow the empirically observed lift structure (2026-08-09 audit of-// 92.5k labeled coins). Non-monotone signals (snipe, concentration) get buckets-// that isolate their sweet spots instead of a linear penalty that fights the-// data. Every getter reads the raw launch-time signals JSONB.-const g = (k) => (r) => numOrNull(r.features?.[k]);-function numOrNull(v) {- const n = Number(v);- return v == null || !Number.isFinite(n) ? null : n;+function flag(name, fallback = null) {+ const i = process.argv.indexOf(`--${name}`);+ return i >= 0 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--') ? process.argv[i + 1] : fallback;}-export const FEATURES = [- { key: 'organic_score', pillar: 'structure', get: g('organic_score'), edges: [0.2, 0.4, 0.6, 0.8] },- { key: 'bundle_score', pillar: 'structure', get: g('bundle_score'), edges: [0.1, 0.3, 0.5] },- { key: 'snipe_ratio', pillar: 'structure', get: g('snipe_ratio'), edges: [0.1, 0.3, 0.7] },- { key: 'coordination_score', pillar: 'structure', get: g('coordination_score'), edges: [0.1, 0.3] },- { key: 'timing_entropy', pillar: 'structure', get: g('timing_entropy'), edges: [0.2, 0.4, 0.6, 0.8] },- { key: 'concentration_top1', pillar: 'structure', get: g('concentration_top1'), edges: [0.05, 0.15, 0.3] },- { key: 'concentration_top10', pillar: 'structure', get: g('concentration_top10'), edges: [0.3, 0.9] },- { key: 'unique_buyers', pillar: 'momentum', get: g('unique_buyers'), edges: [1, 5, 15, 40] },- { key: 'buy_sell_ratio', pillar: 'momentum', get: g('buy_sell_ratio'), edges: [0.5, 1, 2, 4] },- { key: 'buy_volume_sol', pillar: 'momentum', get: g('buy_volume_sol'), edges: [0.5, 8, 25] },- { key: 'largest_buy_sol', pillar: 'momentum', get: g('largest_buy_sol'), edges: [0.2, 2.5, 5] },- { key: 'avg_buy_sol', pillar: 'momentum', get: g('avg_buy_sol'), edges: [0.05, 0.5] },- { key: 'dev_buy_sol', pillar: 'pedigree', get: g('dev_buy_sol'), edges: [0.05, 0.5, 2] },- { key: 'mc_sol_first_seen', pillar: 'momentum', get: g('mc_sol_first_seen'), edges: [28, 30, 35] },- {- key: 'dev_sold', pillar: 'pedigree',- get: (r) => (r.features?.dev_sold === true ? 1 : r.features?.dev_sold === false ? 0 : null),- edges: [0.5],- },- {- key: 'creator_record', pillar: 'pedigree',- // Categorical: the creator's launch history at label time.- categorical: true,- get: (r) => {- const launches = numOrNull({ features: { v: r.creator_launches } }.features.v);- const wins = numOrNull({ features: { v: r.creator_wins } }.features.v);- if (launches == null) return 'unknown';- if (wins != null && wins >= 1) return 'has_wins';- if (launches >= 5) return 'serial_no_wins';- if (launches >= 2) return 'repeat_no_wins';- return 'first_launch';- },- },- {- key: 'category', pillar: 'narrative',- categorical: true,- get: (r) => String(r.category || 'unknown').toLowerCase(),- },-];+const write = process.argv.includes('--write');+const asJson = process.argv.includes('--json');+const maxRows = Number(flag('rows', 0)) || Infinity;+const epochs = Number(flag('epochs', 0)) || 14;-function bucketLabel(f, v) {- if (f.categorical) return String(v);- if (v == null) return 'null';- for (let i = 0; i < f.edges.length; i++) {- if (v < f.edges[i]) return i === 0 ? `<${f.edges[0]}` : `${f.edges[i - 1]}-${f.edges[i]}`;- }- return `>=${f.edges[f.edges.length - 1]}`;-}+const sql = neon(loadEnvUrl());-// ── Load data ─────────────────────────────────────────────────────────────────+/**+ * Load labeled launches, oldest first, so the holdout is genuinely the future.+ * Only rows judged by the price-independent rule: version 1 rows carry a+ * `rugged` flag that tracks the SOL price instead of the coin, and mixing them+ * in would poison both the survival head and the win head that depends on it.+ */async function loadRows() {const PAGE = 20000;const rows = [];- for (let off = 0; ; off += PAGE) {+ for (let off = 0; rows.length < maxRows; off += PAGE) {+ const take = Math.min(PAGE, maxRows - rows.length);const page = await sql`select mint, features, category, creator_launches, creator_wins,- outcome, first_seen_at+ outcome, graduated, rugged, ath_multiple, hold_multiple, retained, first_seen_atfrom oracle_training_set- where network = 'mainnet' and outcome <> 'unknown'+ where network = 'mainnet' and outcome <> 'unknown' and label_version >= ${LABEL_VERSION}order by first_seen_at asc, mint asc- limit ${PAGE} offset ${off}+ limit ${take} offset ${off}`;rows.push(...page);- if (page.length < PAGE) break;+ if (page.length < take) break;}return rows;}-// ── Fit ───────────────────────────────────────────────────────────────────────-function encode(rows) {- // Build the one-hot design: featureKey -> bucketLabel -> column index.- const columns = new Map();- const colOf = (fk, b) => {- const key = `${fk}\u0000${b}`;- if (!columns.has(key)) columns.set(key, columns.size);- return columns.get(key);- };- const X = rows.map((r) => FEATURES.map((f) => colOf(f.key, bucketLabel(f, f.get(r)))));- const y = rows.map((r) => (r.outcome === 'graduated' || r.outcome === 'pumped' ? 1 : 0));- return { X, y, columns };-}--function fitLogistic(X, y, nCols, { epochs = 40, lr = 0.05, l2 = 1e-4 } = {}) {- // Plain SGD logistic regression over one-hot rows (each row has exactly- // FEATURES.length active columns, all with value 1).- let b0 = Math.log((y.reduce((a, v) => a + v, 0) + 1) / (y.length - y.reduce((a, v) => a + v, 0) + 1));- const w = new Float64Array(nCols);- const idx = [...X.keys()];- let seed = 42;- const rand = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;- for (let e = 0; e < epochs; e++) {- // Fisher-Yates with the deterministic LCG so runs are reproducible.- for (let i = idx.length - 1; i > 0; i--) {- const j = Math.floor(rand() * (i + 1));- [idx[i], idx[j]] = [idx[j], idx[i]];- }- const step = lr / (1 + e * 0.15);- for (const i of idx) {- let z = b0;- for (const c of X[i]) z += w[c];- const p = 1 / (1 + Math.exp(-z));- const err = y[i] - p;- b0 += step * err;- for (const c of X[i]) w[c] += step * (err - l2 * w[c]);- }- }- return { b0, w };-}--const sigmoid = (z) => 1 / (1 + Math.exp(-z));--function predict(model, xRow) {- let z = model.b0;- for (const c of xRow) z += model.w[c];- return sigmoid(z);-}--// ── Evaluate ──────────────────────────────────────────────────────────────────-function auc(scores, labels) {- const pairs = scores.map((s, i) => [s, labels[i]]).sort((a, b) => a[0] - b[0]);- let rank = 0, sumPosRanks = 0, nPos = 0, nNeg = 0;- for (let i = 0; i < pairs.length; ) {- let j = i;- while (j < pairs.length && pairs[j][0] === pairs[i][0]) j++;- const avgRank = (i + j + 1) / 2; // 1-based average rank of the tie group- for (let k = i; k < j; k++) {- if (pairs[k][1] === 1) { sumPosRanks += avgRank; nPos++; } else nNeg++;- }- i = j;- }- rank = sumPosRanks - (nPos * (nPos + 1)) / 2;- return nPos && nNeg ? rank / (nPos * nNeg) : 0.5;-}--function precisionAt(scores, labels, frac) {- const order = [...scores.keys()].sort((a, b) => scores[b] - scores[a]);- const n = Math.max(1, Math.round(order.length * frac));- let good = 0;- for (let i = 0; i < n; i++) good += labels[order[i]];- return { n, rate: good / n };-}--// ── Main ──────────────────────────────────────────────────────────────────────-const write = process.argv.includes('--write');const rows = await loadRows();-if (rows.length < 5000) {- console.error(`Only ${rows.length} training rows; refusing to fit on so little.`);+if (rows.length < MIN_TRAINING_ROWS) {+ console.error(`Only ${rows.length} rows carry label_version >= ${LABEL_VERSION}; refusing to fit on so little.`);+ console.error('The intel labeler stamps that version as it relabels. Let it run, or check api/cron/intel-learn.js.');process.exit(2);}-console.log(`training rows: ${rows.length}`);--const { X, y, columns } = encode(rows);-const base = y.reduce((a, v) => a + v, 0) / y.length;-console.log(`base good rate: ${(100 * base).toFixed(2)}%`);-// Time split: oldest 75% train, newest 25% holdout (rows arrive sorted).-const cut = Math.floor(rows.length * 0.75);-const model = fitLogistic(X.slice(0, cut), y.slice(0, cut), columns.size);+const startedAt = Date.now();+const { model, report } = buildModel(rows, { epochs });+const seconds = ((Date.now() - startedAt) / 1000).toFixed(1);-const testScores = X.slice(cut).map((xr) => predict(model, xr));-const testY = y.slice(cut);-console.log(`holdout n=${testY.length}, AUC=${auc(testScores, testY).toFixed(4)}`);-for (const frac of [0.01, 0.05, 0.10, 0.25]) {- const p = precisionAt(testScores, testY, frac);- console.log(` precision@top${(frac * 100).toFixed(0)}%: ${(100 * p.rate).toFixed(1)}% (n=${p.n}, lift ${(p.rate / base).toFixed(2)})`);-}--// Per-probability-band calibration on the holdout (these anchor the tier map).-console.log('holdout calibration by predicted probability:');-const BANDS = [0, 0.05, 0.1, 0.2, 0.35, 0.55, 1.001];-for (let i = 0; i + 1 < BANDS.length; i++) {- const sel = testScores.map((s, k) => [s, testY[k]]).filter(([s]) => s >= BANDS[i] && s < BANDS[i + 1]);- if (!sel.length) continue;- const rate = sel.reduce((a, [, l]) => a + l, 0) / sel.length;- console.log(` p ${BANDS[i].toFixed(2)}-${BANDS[i + 1].toFixed(2)}: n=${sel.length} observed=${(100 * rate).toFixed(1)}%`);-}--// Refit on ALL rows for the shipped weights (holdout numbers above stay the-// honest evaluation; the production model should not waste the newest quarter).-const finalModel = fitLogistic(X, y, columns.size);--// Emit the model JSON: per feature, per bucket -> weight + provenance stats.-const features = FEATURES.map((f) => {- const buckets = {};- for (const [key, col] of columns) {- const [fk, b] = key.split('\u0000');- if (fk !== f.key) continue;- let n = 0, good = 0;- for (let i = 0; i < rows.length; i++) {- if (X[i][FEATURES.indexOf(f)] === col) { n++; good += y[i]; }+if (asJson) {+ console.log(JSON.stringify({ report, fit_seconds: Number(seconds) }, null, 2));+} else {+ const pct = (v) => `${(100 * v).toFixed(2)}%`;+ console.log(`training rows: ${report.rows.toLocaleString()} (label_version >= ${LABEL_VERSION})`);+ console.log(`fit in ${seconds}s: ${model.fit.features} features, ${model.fit.columns} bucket weights, ${model.fit.epochs_run} epochs`);+ if (report.dropped.length) {+ console.log('\ndropped as uninformative on this dataset:');+ for (const d of report.dropped) {+ const runner = d.runner_up ? `runner-up "${d.runner_up.bucket}" n=${d.runner_up.n}` : 'only one bucket';+ console.log(` ${d.key.padEnd(24)} ${(100 * d.share).toFixed(1)}% in "${d.bucket}", ${runner}`);}- buckets[b] = {- w: Number(finalModel.w[col].toFixed(4)),- n,- good_rate: Number((good / Math.max(1, n)).toFixed(4)),- };}- return {- key: f.key,- pillar: f.pillar,- categorical: !!f.categorical,- edges: f.edges || null,- buckets,- };-});--const out = {- version: 2,- fitted_at: new Date().toISOString(),- training_rows: rows.length,- base_good_rate: Number(base.toFixed(4)),- intercept: Number(finalModel.b0.toFixed(4)),- // Tier ladder: probability anchors chosen from the holdout calibration.- // score = monotone piecewise-linear map of p over these anchors, keeping the- // public 86/72/56/34 tier boundaries while grounding them in P(good).- tier_probability_anchors: { avoid: 0, watch: 0.05, lean: 0.12, strong: 0.30, prime: 0.55 },- features,-};+ console.log('\nbase rates:');+ for (const [head, rate] of Object.entries(report.base_rates)) console.log(` ${head.padEnd(6)} ${pct(rate)}`);++ for (const head of ['win', 'rug', 'moon']) {+ const e = model.holdout[head];+ if (!e) continue;+ console.log(`\n[${head}] holdout n=${model.holdout.n.toLocaleString()} AUC=${e.auc} Brier=${e.brier} base=${pct(e.base_rate)}`);+ for (const [k, v] of Object.entries(e.precision)) {+ console.log(` precision@${k.padEnd(6)} ${(100 * v.rate).toFixed(1).padStart(5)}% (n=${v.n}, lift ${v.lift}x)`);+ }+ console.log(' reliability (does a claim of X happen X of the time):');+ for (const b of e.reliability) {+ if (!b.n) continue;+ console.log(` p ${b.lo.toFixed(2)}-${b.hi.toFixed(2)} n=${String(b.n).padStart(6)} claimed ${(100 * b.predicted).toFixed(1).padStart(5)}% observed ${(100 * b.observed).toFixed(1).padStart(5)}%`);+ }+ }+ console.log(`\n${write ? 'writing' : 'dry run'}: pass --write to update the bootstrap model shipped in the image.`);+}-console.log(`\nfitted ${columns.size} bucket weights across ${FEATURES.length} features`);if (write) {- writeFileSync(MODEL_PATH, JSON.stringify(out, null, '\t') + '\n');+ writeFileSync(MODEL_PATH, `${JSON.stringify(model, null, '\t')}\n`);console.log(`wrote ${MODEL_PATH.pathname}`);-} else {- console.log('(dry run; pass --write to update conviction-model.json)');}diff --git a/workers/agent-sniper/intel/learn.js b/workers/agent-sniper/intel/learn.jsindex 0ae7862ae..4db7dca8a 100644--- a/workers/agent-sniper/intel/learn.js+++ b/workers/agent-sniper/intel/learn.js@@ -196,8 +196,46 @@ function isGraduated(c) {* market cap we recorded when we first saw it.* @returns {{ outcome, graduated, rugged, ath_multiple, last_market_cap_usd, ath_market_cap_usd }}*/+// ── The label constants, and why they are what they are ──────────────────────+//+// A pump.fun bonding curve with no real reserves is worth a fixed number of SOL:+// the launch parameters put 30 virtual SOL against 1,073,000,191 virtual tokens+// over a 1e9 supply, so an untouched curve prices at+// 30 * 1e9 / 1_073_000_191 = 27.958993 SOL+// and no coin on the curve can ever be worth less. We first see a coin inside+// its opening 90 seconds, when its cap is 28-38 SOL, which means the floor is+// 73-99% of first sight.+//+// That single fact broke the old rug test. It asked whether a coin had fallen to+// 25% of first sight, which the floor makes unreachable, and then fell back on+// whether its market cap was under a hardcoded $3,000, i.e. on whether SOL was+// above roughly $107.3 that day. Of 206,428 coins it called rugged, 206,419 were+// under $3,000; of 25,180 it called survivors, the cheapest was exactly $3,000.+// Same dead curves, sorted by the SOL price. Everything downstream that+// subtracted rugs from a win rate was reading a price feed.+//+// The replacement is measured against what a holder paid, in ratios where the+// SOL price cancels. See the migration+// 20260828170000_oracle_price_independent_labels.sql for the full write-up.+const CURVE_FLOOR_SOL = 30 * 1e9 / 1_073_000_191;+const CURVE_FLOOR_TOLERANCE = 0.02;+/** Down more than half from first sight is the line between a dud and a rug. */+const RUG_HOLD_MULTIPLE = 0.5;+/**+ * Bumped whenever the labeling RULE changes, so a consumer can refuse rows an+ * older rule produced instead of silently averaging two incompatible questions.+ * 1 = the USD-threshold rule described above. 2 = price-independent ratios.+ */+export const LABEL_VERSION = 2;+export function deriveOutcome(coin, mcSolFirstSeen) {- if (!coin) return { outcome: 'unknown', graduated: null, rugged: null, ath_multiple: null, last_market_cap_usd: null, ath_market_cap_usd: null };+ if (!coin) {+ return {+ outcome: 'unknown', graduated: null, rugged: null, ath_multiple: null,+ last_market_cap_usd: null, ath_market_cap_usd: null,+ retained: null, hold_multiple: null, at_floor: null, label_version: LABEL_VERSION,+ };+ }const graduated = isGraduated(coin);const usdMc = typeof coin.usd_market_cap === 'number' ? coin.usd_market_cap : null;@@ -210,23 +248,37 @@ export function deriveOutcome(coin, mcSolFirstSeen) {const solPrice = usdMc != null && solMc ? usdMc / solMc : null;const athSol = athUsd != null && solPrice ? athUsd / solPrice : null;const ath_multiple = athSol != null && mcSolFirstSeen > 0 ? athSol / mcSolFirstSeen : null;- const lastMultiple = solMc != null && mcSolFirstSeen > 0 ? solMc / mcSolFirstSeen : null;-- // The rugged flag is judged independently of the outcome label. A coin that- // pumped 3× and THEN collapsed is still outcome 'pumped' (the learner's- // "was buying at first sight good?" question), but it IS rugged - win-rate- // metrics downstream must not count a spike-then-collapse as a clean win.- const rugged = !graduated && (- (lastMultiple != null && lastMultiple <= 0.25) ||- (usdMc != null && usdMc < 3_000)- );++ // Two ratios that the price of SOL cannot move, because both dollar figures+ // come out of the same API response and the price cancels between them:+ // retained what share of its own peak the coin still holds+ // hold_multiple what a holder who bought at first sight would have now+ // This is the whole fix. See the header note on RUG_HOLD_MULTIPLE.+ const retained = athUsd > 0 && usdMc != null ? usdMc / athUsd : null;+ const hold_multiple = ath_multiple != null && retained != null ? ath_multiple * retained : null;++ // Exact, and independent of both: a pump.fun curve holding no real reserves+ // is worth CURVE_FLOOR_SOL, so a non-graduated coin sitting there has had+ // every lamport taken back out of it. Only computable when the API returns a+ // SOL market cap, which is why it is a bonus signal and not the label.+ const at_floor = !graduated && solMc != null ? solMc <= CURVE_FLOOR_SOL * (1 + CURVE_FLOOR_TOLERANCE) : null;++ // A rug is a collapse a holder eats, so it is measured against what they paid+ // rather than against a dollar figure. A coin that never moved is a dud, not a+ // rug: nobody was taken, there was nothing to take.+ const rugged = !graduated && hold_multiple != null && hold_multiple <= RUG_HOLD_MULTIPLE;+let outcome;if (graduated) outcome = 'graduated';else if (ath_multiple != null && ath_multiple >= 3) outcome = 'pumped';else if (rugged) outcome = 'rugged';else outcome = 'flat';- return { outcome, graduated, rugged, ath_multiple, last_market_cap_usd: usdMc, ath_market_cap_usd: athUsd };+ return {+ outcome, graduated, rugged, ath_multiple,+ last_market_cap_usd: usdMc, ath_market_cap_usd: athUsd,+ retained, hold_multiple, at_floor, label_version: LABEL_VERSION,+ };}/**@@ -247,14 +299,24 @@ export function deriveOutcome(coin, mcSolFirstSeen) {export function applyGraduationTruth(outcome, grad) {if (!grad) return outcome;const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);+ const ath = outcome.ath_market_cap_usd ?? num(grad.ath_market_cap);+ const last = outcome.last_market_cap_usd ?? num(grad.market_cap_usd);+ const retained = ath > 0 && last != null ? last / ath : outcome.retained;return {...outcome,outcome: 'graduated',graduated: true,- // A graduated coin is never a rug, same invariant deriveOutcome holds.+ // A graduated coin is never a rug, same invariant deriveOutcome holds,+ // and it is never sitting on an empty bonding curve either: it left one.rugged: false,- ath_market_cap_usd: outcome.ath_market_cap_usd ?? num(grad.ath_market_cap),- last_market_cap_usd: outcome.last_market_cap_usd ?? num(grad.market_cap_usd),+ at_floor: false,+ ath_market_cap_usd: ath,+ last_market_cap_usd: last,+ retained,+ hold_multiple: outcome.ath_multiple != null && retained != null+ ? outcome.ath_multiple * retained+ : outcome.hold_multiple,+ label_version: LABEL_VERSION,};}@@ -376,10 +438,11 @@ export async function labelOutcomes({ network = 'mainnet', limit = 100, minAgeMiawait sql`insert into pump_coin_outcomes (mint, graduated, rugged, ath_market_cap_usd, ath_multiple,- last_market_cap_usd, outcome+ last_market_cap_usd, outcome, retained, hold_multiple, at_floor, label_version)select u.mint, u.graduated, u.rugged, u.ath_market_cap_usd,- u.ath_multiple, u.last_market_cap_usd, u.outcome+ u.ath_multiple, u.last_market_cap_usd, u.outcome,+ u.retained, u.hold_multiple, u.at_floor, u.label_versionfrom unnest(${batch.map((b) => b.row.mint)}::text[],${batch.map((b) => b.o.graduated)}::boolean[],@@ -387,14 +450,24 @@ export async function labelOutcomes({ network = 'mainnet', limit = 100, minAgeMi${batch.map((b) => b.o.ath_market_cap_usd)}::double precision[],${batch.map((b) => b.o.ath_multiple)}::double precision[],${batch.map((b) => b.o.last_market_cap_usd)}::double precision[],- ${batch.map((b) => b.o.outcome)}::text[]- ) as u(mint, graduated, rugged, ath_market_cap_usd, ath_multiple, last_market_cap_usd, outcome)+ ${batch.map((b) => b.o.outcome)}::text[],+ ${batch.map((b) => b.o.retained)}::double precision[],+ ${batch.map((b) => b.o.hold_multiple)}::double precision[],+ ${batch.map((b) => b.o.at_floor)}::boolean[],+ ${batch.map((b) => b.o.label_version ?? LABEL_VERSION)}::smallint[]+ ) as u(mint, graduated, rugged, ath_market_cap_usd, ath_multiple, last_market_cap_usd,+ outcome, retained, hold_multiple, at_floor, label_version)on conflict (mint) do update setgraduated = excluded.graduated, rugged = excluded.rugged,ath_market_cap_usd = excluded.ath_market_cap_usd,ath_multiple = excluded.ath_multiple,last_market_cap_usd = excluded.last_market_cap_usd,- outcome = excluded.outcome, labeled_at = now()+ outcome = excluded.outcome,+ retained = excluded.retained,+ hold_multiple = excluded.hold_multiple,+ at_floor = excluded.at_floor,+ label_version = excluded.label_version,+ labeled_at = now()`;labeled += batch.length;// A retry only counts as rescued when it came back with a real verdict;@@ -413,11 +486,13 @@ export async function labelOutcomes({ network = 'mainnet', limit = 100, minAgeMiinsert into oracle_training_set (mint, network, features, category,creator_launches, creator_wins, creator_dump_rate,- outcome, graduated, rugged, ath_multiple, first_seen_at+ outcome, graduated, rugged, ath_multiple, first_seen_at,+ retained, hold_multiple, label_version)select u.mint, ${network}, u.features::jsonb, u.category,u.creator_launches, u.creator_wins, u.creator_dump_rate,- u.outcome, u.graduated, u.rugged, u.ath_multiple, u.first_seen_at+ u.outcome, u.graduated, u.rugged, u.ath_multiple, u.first_seen_at,+ u.retained, u.hold_multiple, u.label_versionfrom unnest(${judged.map((b) => b.row.mint)}::text[],${judged.map((b) => JSON.stringify(b.row.signals || {}))}::text[],@@ -429,10 +504,28 @@ export async function labelOutcomes({ network = 'mainnet', limit = 100, minAgeMi${judged.map((b) => b.o.graduated)}::boolean[],${judged.map((b) => b.o.rugged)}::boolean[],${judged.map((b) => b.o.ath_multiple)}::double precision[],- ${judged.map((b) => b.row.first_seen_at)}::timestamptz[]+ ${judged.map((b) => b.row.first_seen_at)}::timestamptz[],+ ${judged.map((b) => b.o.retained)}::double precision[],+ ${judged.map((b) => b.o.hold_multiple)}::double precision[],+ ${judged.map((b) => b.o.label_version ?? LABEL_VERSION)}::smallint[]) as u(mint, features, category, creator_launches, creator_wins, creator_dump_rate,- outcome, graduated, rugged, ath_multiple, first_seen_at)- on conflict (mint, network) do nothing+ outcome, graduated, rugged, ath_multiple, first_seen_at,+ retained, hold_multiple, label_version)+ -- This clause used to do nothing on conflict, which meant a training+ -- label could never be corrected once written: a row judged by a broken+ -- rule stayed judged by it forever and the corpus could not heal even+ -- after the rule was fixed. Only ever upgrade, never downgrade, so a+ -- stale worker replaying an old rule cannot walk a corrected row back.+ on conflict (mint, network) do update set+ outcome = excluded.outcome,+ graduated = excluded.graduated,+ rugged = excluded.rugged,+ ath_multiple = excluded.ath_multiple,+ retained = excluded.retained,+ hold_multiple = excluded.hold_multiple,+ label_version = excluded.label_version,+ labeled_at = now()+ where excluded.label_version >= oracle_training_set.label_version`;} catch (err) {console.warn('[coin-intel] training snapshot batch failed:', err?.message);