Replace invalid resolution bets with forward learning

This commit is contained in:
Theodore Song
2026-08-21 19:56:21 -04:00
parent 95947c4df6
commit ab165b0617
8 changed files with 284 additions and 179 deletions
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- run: node scripts/run-autonomous-cycle.mjs - run: node scripts/run-autonomous-cycle.mjs
env: env:
ARENA_URL: https://polymarket-site-eta.vercel.app ARENA_URL: https://polymarket-site-eta.vercel.app
EXPECTED_BUILD: "99" EXPECTED_BUILD: "100"
RUNTIME_BRANCH: runtime-state RUNTIME_BRANCH: runtime-state
RUNTIME_STATE_PATH: runtime/state.json RUNTIME_STATE_PATH: runtime/state.json
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+22 -27
View File
@@ -20,7 +20,7 @@ market snapshots. During an outage, cycles continue locally; cached entries are
allowed for 90 minutes, older snapshots become mark-only, and all cached data allowed for 90 minutes, older snapshots become mark-only, and all cached data
expires after 24 hours. expires after 24 hours.
Build 99 runs the headless GitHub Actions runtime every five minutes, continues Build 100 runs the headless GitHub Actions runtime every five minutes, continues
from the previous agent snapshot, from the previous agent snapshot,
and runs the next due paper cycle even when no browser is open. It writes a and runs the next due paper cycle even when no browser is open. It writes a
sanitized snapshot to the `runtime-state` branch and `/api/state` uses that as a sanitized snapshot to the `runtime-state` branch and `/api/state` uses that as a
@@ -41,7 +41,7 @@ Polymarket event key. Related Ethereum or Bitcoin contracts cannot create
several simultaneous copies of one move, and outcomes from the same underlying several simultaneous copies of one move, and outcomes from the same underlying
three-hour shock window count as one learner event. three-hour shock window count as one learner event.
Each Build 99 cycle also scans the 1,000 most-active Polymarket events for Each Build 100 cycle also scans the 1,000 most-active Polymarket events for
complete negative-risk bundles and logically nested threshold or deadline complete negative-risk bundles and logically nested threshold or deadline
pairs. Only a positive worst-case payout margin after 0.5 cents of modeled cost pairs. Only a positive worst-case payout margin after 0.5 cents of modeled cost
per leg can enter the Value Discipline portfolio. The Suggestions view stores per leg can enter the Value Discipline portfolio. The Suggestions view stores
@@ -52,32 +52,27 @@ eligible negative-risk events and 1,431 dominance pairs, but no positive bundle
after costs; the closest complete bundle was 0.5 cents underwater and the after costs; the closest complete bundle was 0.5 cents underwater and the
closest dominance pair was 0.3 cents underwater. closest dominance pair was 0.3 cents underwater.
Build 97 expands the separate current-regime resolution-window NO pilot for Build 100 retires the old 3-6 day resolution-window capital permission. Its
the five aggressive agents. It accepts only non-sports, fixed-date contracts audit clustered confidence by event but still averaged several correlated
inside validated 2.5-3.5, 3.5-4.5, 4.5-5.5, or 5.5-6.5 day windows, with the NO midpoint from 50%-55%, at least $15,000 total contracts inside each event, while production could choose only one. The
volume, $1,400 liquidity, and no more than a three-cent spread. The entry uses corrected replay chooses the highest-volume eligible contract per event and
the executable NO ask plus 0.25 cents of slippage and rejects more than one cent rule. In the recent 3,000-market discovery sample, only the safe non-Sports
of entry friction. Initial positions are 0.5% of equity, one new position per 50%-55% NO rule four days before settlement survived every chronological gate:
agent per cycle, one owner per event across the arena, and no more than 3% of an 145 events, a 38.42% mean, and a 26.12% lower 90% bound after one cent of cost.
agent's equity in the lane. These positions hold through interim volatility and The next disjoint 3,000-market block did not confirm it: the safe cohort's
close only after Polymarket marks the market closed; offline snapshots cannot holdout lower bound was -4.73%, and two chronological-third lower bounds were
invent settlement. Twenty losing independent forward events or a 1% aggregate negative. No 3-6 day rule is therefore approved for capital.
pilot loss disables the lane for every adopter, and ten convincingly losing
events disable only their exact holding horizon. Forty events with a positive
lower confidence bound above 1% can raise position size to 1%.
The corrected production-matched audit used 2,954 of 3,000 recent resolved The remaining four-day candidate is a zero-capital forward learner. It accepts
markets and a one-cent cost. It excludes Sports and the same path-dependent only fixed-date, non-Sports contracts with a 50%-55% NO midpoint, at least
barrier and range contracts rejected by production. At three, four, five, and $15,000 total volume, $1,400 liquidity, and no more than a three-cent spread.
six days, the exact 50%-55% NO rule covered 121, 144, 104, and 86 independent The modeled entry uses the executable NO ask plus 0.25 cents of slippage and
event clusters. Event mean returns were 24.52%, 38.15%, 36.86%, and 43.94%, rejects more than one cent of friction. One observation is recorded per event
with lower 90% bounds of 15.78%, 31.40%, 29.39%, and 37.67%. Every retained and graded only after Polymarket marks the market closed; offline snapshots
horizon had positive train, holdout, and chronological-segment lower bounds. cannot invent settlement. Forty independent settled observations with a lower
Two days failed holdout. Seven and ten days lost a segment confidence test; 90% confidence bound above 1% are required before 0.5%-of-equity paper
other longer windows were not retained. Contemporaneous historical liquidity positions can begin. Existing positions from the retired version still follow
cannot be reconstructed, so production adds live spread and liquidity gates their precommitted settlement-only exit.
and remains a bounded, automatically demoted paper pilot rather than a claim
of durable or guaranteed profit.
Build 94 also closes the contract-safety hole exposed by the first Strategy 3 Build 94 also closes the contract-safety hole exposed by the first Strategy 3
paper positions. Shock Strategy 4 keeps the same audited accelerating paper positions. Shock Strategy 4 keeps the same audited accelerating
+144 -60
View File
@@ -341,7 +341,7 @@ footer{margin-top:34px;padding-top:22px;border-top:1px solid var(--border);color
<nav class="topnav"> <nav class="topnav">
<div class="brand"> <div class="brand">
<div class="logo">🏆</div> <div class="logo">🏆</div>
<div><div class="brand-name">Polymarket Arena</div><div class="brand-sub">10 agents · 5 core + 5 aggressive</div><div class="build-badge">Adaptive strategy 59 · resolution-window pilot 2 · build 97</div></div> <div><div class="brand-name">Polymarket Arena</div><div class="brand-sub">10 agents · 5 core + 5 aggressive</div><div class="build-badge">Adaptive strategy 60 · corrected forward learners · build 100</div></div>
</div> </div>
<div class="tabs" id="tabs"> <div class="tabs" id="tabs">
<button class="tab" data-tab="overview">Overview</button> <button class="tab" data-tab="overview">Overview</button>
@@ -363,7 +363,7 @@ footer{margin-top:34px;padding-top:22px;border-top:1px solid var(--border);color
<div class="personal-banner" id="personalBanner"> <div class="personal-banner" id="personalBanner">
<b>Personal research mode.</b> This copy is for your own analysis, paper tracking, and manual trade research only. It does not pool money, onboard investors, custody funds, bypass eligibility rules, or place orders without your manual approval. <b>Personal research mode.</b> This copy is for your own analysis, paper tracking, and manual trade research only. It does not pool money, onboard investors, custody funds, bypass eligibility rules, or place orders without your manual approval.
</div> </div>
<div class="live-build-banner"><b>Build 99 active:</b> The public paper agents run autonomously every five minutes while every user device is closed. Each cycle scans the 1,000 most-active events for complete negative-risk and same-event dominance bundles, and the shared Suggestions view reports the closest executable margin even when no bundle is profitable after modeled costs. Five aggressive agents can also take tightly bounded, safe non-Sports 5055% NO positions in independently passing three-through-six-day settlement windows. Other unproven directional rules remain observation-only. Phones and computers display the same read-only autonomous state. Profits are not guaranteed.</div> <div class="live-build-banner"><b>Build 100 active:</b> The public paper agents run autonomously every five minutes while every user device is closed. Each cycle scans the 1,000 most-active events for complete negative-risk and same-event dominance bundles, and the shared Suggestions view reports the closest executable margin even when no bundle is profitable after modeled costs. A corrected one-decision-per-event audit invalidated the old 36 day resolution capital permission, so the remaining 4-day 5055% NO candidate now collects zero-capital forward outcomes and needs 40 independent settled events with a positive confidence bound before risking 0.5%. Phones and computers display the same read-only autonomous state. Profits are not guaranteed.</div>
<!-- ============ OVERVIEW ============ --> <!-- ============ OVERVIEW ============ -->
<section class="tabpanel" data-tab="overview"> <section class="tabpanel" data-tab="overview">
@@ -745,7 +745,7 @@ footer{margin-top:34px;padding-top:22px;border-top:1px solid var(--border);color
</section> </section>
<footer> <footer>
Build 99 · Adaptive strategy 59 · Five-minute autonomous scans · Persistent 1,000-event bundle audit · Resolution-window pilot 2 · Validated 3d6d entries · Executable 5055% NO pricing · Settlement-only exits · Per-horizon forward demotion · Autonomous runtime 1 · Offline runtime 2 · Maker research 3 · Agent learning 3 · Paper trading only · Live prices from Polymarket's public Gamma and CLOB APIs · Not financial advice · Build 100 · Adaptive strategy 60 · Five-minute autonomous scans · Persistent 1,000-event bundle audit · Corrected one-decision-per-event settlement audit · 4-day NO forward learner · Zero capital before 40 independent positive outcomes · Autonomous runtime 1 · Offline runtime 2 · Maker research 3 · Agent learning 3 · Paper trading only · Live prices from Polymarket's public Gamma and CLOB APIs · Not financial advice ·
<a class="market-link" href="https://github.com/theodore-song/polymarket-analyst" target="_blank" rel="noopener">Source on GitHub</a> <a class="market-link" href="https://github.com/theodore-song/polymarket-analyst" target="_blank" rel="noopener">Source on GitHub</a>
</footer> </footer>
</div> </div>
@@ -774,16 +774,16 @@ const POLITICS_TREND_MIN_HOLD_HOURS = 72;
const EXIT_CONFIRM_HOURS = 6; const EXIT_CONFIRM_HOURS = 6;
const AGENTS_KEY = "pma_agents_v2"; const AGENTS_KEY = "pma_agents_v2";
const SUG_KEY = "pma_suggestions_v5"; const SUG_KEY = "pma_suggestions_v5";
const BUILD_VERSION = 99; const BUILD_VERSION = 100;
const AGENT_LEARNING_VERSION = 3; const AGENT_LEARNING_VERSION = 3;
const SUGGESTION_ENGINE_VERSION = 59; const SUGGESTION_ENGINE_VERSION = 60;
const MAKER_STRATEGY_VERSION = 3; const MAKER_STRATEGY_VERSION = 3;
const SHOCK_FADE_STRATEGY_VERSION = 4; const SHOCK_FADE_STRATEGY_VERSION = 4;
const RESOLUTION_WEEK_NO_STRATEGY_VERSION = 2; const RESOLUTION_WEEK_NO_STRATEGY_VERSION = 3;
const PREVIOUS_STRATEGY_VERSION = 58; const PREVIOUS_STRATEGY_VERSION = 59;
const DIRECTIONAL_SIGNAL_POLICY_VERSION = 1; const DIRECTIONAL_SIGNAL_POLICY_VERSION = 1;
const DIRECTIONAL_SIGNAL_COMPATIBLE_STRATEGY_MIN = 51; const DIRECTIONAL_SIGNAL_COMPATIBLE_STRATEGY_MIN = 51;
const DIRECTIONAL_SIGNAL_COMPATIBLE_STRATEGY_MAX = 59; const DIRECTIONAL_SIGNAL_COMPATIBLE_STRATEGY_MAX = 60;
const LEGACY_BUILD_STRATEGY_LINEAGE = Object.freeze({40:40,41:40}); const LEGACY_BUILD_STRATEGY_LINEAGE = Object.freeze({40:40,41:40});
function normalizedStrategyVersion(value){ function normalizedStrategyVersion(value){
const version=Number(value||0); const version=Number(value||0);
@@ -1316,27 +1316,25 @@ const SHOCK_FADE_BACKTEST_APPROVED=false;
const SHOCK_FADE_ADOPTER_IDS=new Set(["catalyst","reversal","breakout","tailalpha","conviction"]); const SHOCK_FADE_ADOPTER_IDS=new Set(["catalyst","reversal","breakout","tailalpha","conviction"]);
const RESOLUTION_WEEK_NO_ADOPTER_IDS=new Set(["catalyst","reversal","breakout","tailalpha","conviction"]); const RESOLUTION_WEEK_NO_ADOPTER_IDS=new Set(["catalyst","reversal","breakout","tailalpha","conviction"]);
const RESOLUTION_WEEK_NO_WINDOWS=Object.freeze([ const RESOLUTION_WEEK_NO_WINDOWS=Object.freeze([
{days:3,min:2.5,max:3.5},{days:4,min:3.5,max:4.5}, {days:4,min:3.5,max:4.5},
{days:5,min:4.5,max:5.5},{days:6,min:5.5,max:6.5},
]); ]);
const RESOLUTION_WEEK_NO_AUDIT=Object.freeze({ const RESOLUTION_WEEK_NO_AUDIT=Object.freeze({
3:{events:121,eventMean:0.2452,lower:0.1578,trainEvents:85,trainLower:0.1315,holdoutEvents:40,holdoutLower:0.0991}, 4:{events:145,eventMean:0.3842,lower:0.2612,trainEvents:102,trainLower:0.2909,holdoutEvents:46,holdoutLower:0.0383},
4:{events:144,eventMean:0.3815,lower:0.3140,trainEvents:102,trainLower:0.3032,holdoutEvents:47,holdoutLower:0.2717},
5:{events:105,eventMean:0.3686,lower:0.2939,trainEvents:77,trainLower:0.2687,holdoutEvents:30,holdoutLower:0.3001},
6:{events:87,eventMean:0.4394,lower:0.3767,trainEvents:60,trainLower:0.3309,holdoutEvents:29,holdoutLower:0.4368},
}); });
const RESOLUTION_WEEK_NO_MIN_ENTRY=0.50; const RESOLUTION_WEEK_NO_MIN_ENTRY=0.50;
const RESOLUTION_WEEK_NO_MAX_ENTRY=0.55; const RESOLUTION_WEEK_NO_MAX_ENTRY=0.55;
const RESOLUTION_WEEK_NO_MAX_EXECUTABLE_ENTRY=0.56; const RESOLUTION_WEEK_NO_MAX_EXECUTABLE_ENTRY=0.56;
const RESOLUTION_WEEK_NO_POSITION_PCT=0.005; const RESOLUTION_WEEK_NO_POSITION_PCT=0.005;
const RESOLUTION_WEEK_NO_PROMOTED_POSITION_PCT=0.01; const RESOLUTION_WEEK_NO_PROMOTED_POSITION_PCT=0.005;
const RESOLUTION_WEEK_NO_TOTAL_CAPITAL_PCT=0.03; const RESOLUTION_WEEK_NO_TOTAL_CAPITAL_PCT=0.03;
const RESOLUTION_WEEK_NO_MAX_NEW_PER_AGENT_CYCLE=1; const RESOLUTION_WEEK_NO_MAX_NEW_PER_AGENT_CYCLE=1;
const RESOLUTION_WEEK_NO_VERDICT_EVENTS=20; const RESOLUTION_WEEK_NO_VERDICT_EVENTS=20;
const RESOLUTION_WEEK_NO_PROMOTION_EVENTS=40; const RESOLUTION_WEEK_NO_PROMOTION_EVENTS=40;
const RESOLUTION_WEEK_NO_SHADOW_LIMIT=30;
const RESOLUTION_WEEK_NO_OUTCOME_LIMIT=300;
const RESOLUTION_WEEK_NO_SLIPPAGE_BUFFER=0.0025; const RESOLUTION_WEEK_NO_SLIPPAGE_BUFFER=0.0025;
const RESOLUTION_WEEK_NO_MAX_EXECUTION_COST=0.01; const RESOLUTION_WEEK_NO_MAX_EXECUTION_COST=0.01;
const RESOLUTION_WEEK_NO_BACKTEST_APPROVED=true; const RESOLUTION_WEEK_NO_BACKTEST_APPROVED=false;
const MAKER_MAX_QUOTES=6; const MAKER_MAX_QUOTES=6;
const MAKER_MAX_QUOTE_CAPITAL_PCT=0.02; const MAKER_MAX_QUOTE_CAPITAL_PCT=0.02;
const MAKER_TOTAL_CAPITAL_PCT=0.10; const MAKER_TOTAL_CAPITAL_PCT=0.10;
@@ -1510,12 +1508,12 @@ function resolutionWeekNoSuggestion(m){
market_price:+marketPrice.toFixed(4),entry_price:+modeledEntry.toFixed(4),conviction,volume:m.volume,volume_24hr:m.volume_24hr,liquidity:m.liquidity, market_price:+marketPrice.toFixed(4),entry_price:+modeledEntry.toFixed(4),conviction,volume:m.volume,volume_24hr:m.volume_24hr,liquidity:m.liquidity,
spread:m.spread,price_change_1h:m.price_change_1h,price_change_1d:m.price_change_1d,price_change_1w:m.price_change_1w, spread:m.spread,price_change_1h:m.price_change_1h,price_change_1d:m.price_change_1d,price_change_1w:m.price_change_1w,
momentum_strength:0,signal_strength:0.72,signal_confidence:0.72,signal_type:"resolution-week-no-pilot", momentum_strength:0,signal_strength:0.72,signal_confidence:0.72,signal_type:"resolution-week-no-pilot",
trade_ready:true,entry_candidate:true,audited_observation_only:false,adaptive_promotion:false,watch_only:false,jump_risk:false,requires_live:false, trade_ready:false,entry_candidate:false,audited_observation_only:true,adaptive_promotion:false,watch_only:true,jump_risk:false,requires_live:false,
days_to_resolution:+days.toFixed(1),target_horizon_days:window.days,end_date:m.end_date,resolution_week_strategy_version:RESOLUTION_WEEK_NO_STRATEGY_VERSION, days_to_resolution:+days.toFixed(1),target_horizon_days:window.days,end_date:m.end_date,resolution_week_strategy_version:RESOLUTION_WEEK_NO_STRATEGY_VERSION,
pilot_prior:{recent_markets:2916,recent_events:audit.events,recent_event_mean:audit.eventMean,recent_event_lower_90:audit.lower, pilot_prior:{recent_markets:2916,recent_events:audit.events,recent_event_mean:audit.eventMean,recent_event_lower_90:audit.lower,
train_events:audit.trainEvents,train_lower_90:audit.trainLower,holdout_events:audit.holdoutEvents,holdout_lower_90:audit.holdoutLower,modeled_cost_cents:1,regime_specific:true}, train_events:audit.trainEvents,train_lower_90:audit.trainLower,holdout_events:audit.holdoutEvents,holdout_lower_90:audit.holdoutLower,modeled_cost_cents:1,regime_specific:true},
drivers:[`validated ${window.days}-day settlement window`,"NO midpoint is 5055%","executable NO ask plus 0.25c slippage","one owner per event","hold to verified settlement"], drivers:[`corrected ${window.days}-day discovery window`,"NO midpoint is 5055%","executable NO ask plus 0.25c slippage","one observation per event","zero capital until forward promotion"],
rationale:`Bounded current-regime pilot: NO is priced at ${pct(marketPrice)} for a safe non-Sports contract resolving in ${days.toFixed(1)} days, inside the independently passing ${window.days}-day window. The modeled entry is ${pct(modeledEntry)} using the executable NO ask plus 0.25-cent slippage, ${(executionCost*100).toFixed(2)} cents above midpoint. In the most recent 2,954 resolved-market replay at one-cent cost, the exact production-matched 5055% NO rule covered ${audit.events} ${window.days}-day event clusters with a ${(audit.eventMean*100).toFixed(2)}% event mean and ${(audit.lower*100).toFixed(2)}% lower 90% bound; chronological train and holdout bounds were ${(audit.trainLower*100).toFixed(2)}% and ${(audit.holdoutLower*100).toFixed(2)}%. Historical liquidity at the decision point cannot be reconstructed, so this remains a 0.5% paper pilot with live liquidity gates, one owner per event, a 3% total cap, settlement-only exits, and automatic per-horizon forward demotion.`}; rationale:`Zero-capital forward learner: NO is priced at ${pct(marketPrice)} for a safe non-Sports contract resolving in ${days.toFixed(1)} days, inside the corrected ${window.days}-day discovery window. The modeled entry is ${pct(modeledEntry)} using the executable NO ask plus 0.25-cent slippage, ${(executionCost*100).toFixed(2)} cents above midpoint. A corrected recent replay selected only one highest-volume eligible contract per event and found ${audit.events} observations with a ${(audit.eventMean*100).toFixed(2)}% mean and ${(audit.lower*100).toFixed(2)}% lower 90% bound, but a disjoint older holdout failed the all-segment confidence gate. No capital is allowed until 40 independent forward settlements produce a positive lower confidence bound above 1%.`};
} }
function sportsFavoriteLeadHours(item){return hoursUntil(item&&item.game_start);} function sportsFavoriteLeadHours(item){return hoursUntil(item&&item.game_start);}
function sportsFavoritePilotSuggestion(m){ function sportsFavoritePilotSuggestion(m){
@@ -1658,7 +1656,7 @@ function generateSuggestions(markets,total=SUGGESTION_TOTAL,perCategory=SUGGESTI
} }
/* ---------- Multi-agent store ---------- */ /* ---------- Multi-agent store ---------- */
function defaultPortfolio(){return {cash:STARTING_BALANCE,starting_balance:STARTING_BALANCE,positions:[],maker_quotes:[],maker_outcomes:[],sports_favorite_shadows:[],sports_favorite_outcomes:[],shock_fade_shadows:[],shock_fade_outcomes:[],shock_fade_expired_ungraded:0,closed:[],history:[],snapshots:[],stopped:{},lastDecision:null};} function defaultPortfolio(){return {cash:STARTING_BALANCE,starting_balance:STARTING_BALANCE,positions:[],maker_quotes:[],maker_outcomes:[],sports_favorite_shadows:[],sports_favorite_outcomes:[],shock_fade_shadows:[],shock_fade_outcomes:[],shock_fade_expired_ungraded:0,resolution_week_no_shadows:[],resolution_week_no_outcomes:[],closed:[],history:[],snapshots:[],stopped:{},lastDecision:null};}
function defaultState(){const agents={};AGENTS.forEach(a=>agents[a.id]=defaultPortfolio());return {date:null,last_run:null,last_cycle_hour:null, function defaultState(){const agents={};AGENTS.forEach(a=>agents[a.id]=defaultPortfolio());return {date:null,last_run:null,last_cycle_hour:null,
engine_version:BUILD_VERSION,strategy_version:SUGGESTION_ENGINE_VERSION,engine_started_at:nowIso(),build_started_at:nowIso(),agents,signal_ledger:defaultSignalLedger(),seeded:false};} engine_version:BUILD_VERSION,strategy_version:SUGGESTION_ENGINE_VERSION,engine_started_at:nowIso(),build_started_at:nowIso(),agents,signal_ledger:defaultSignalLedger(),seeded:false};}
function reconcileStateVersions(st){ function reconcileStateVersions(st){
@@ -1704,6 +1702,8 @@ function loadState(){
if(!Array.isArray(st.agents[a.id].sports_favorite_outcomes))st.agents[a.id].sports_favorite_outcomes=[]; if(!Array.isArray(st.agents[a.id].sports_favorite_outcomes))st.agents[a.id].sports_favorite_outcomes=[];
if(!Array.isArray(st.agents[a.id].shock_fade_shadows))st.agents[a.id].shock_fade_shadows=[]; if(!Array.isArray(st.agents[a.id].shock_fade_shadows))st.agents[a.id].shock_fade_shadows=[];
if(!Array.isArray(st.agents[a.id].shock_fade_outcomes))st.agents[a.id].shock_fade_outcomes=[]; if(!Array.isArray(st.agents[a.id].shock_fade_outcomes))st.agents[a.id].shock_fade_outcomes=[];
if(!Array.isArray(st.agents[a.id].resolution_week_no_shadows))st.agents[a.id].resolution_week_no_shadows=[];
if(!Array.isArray(st.agents[a.id].resolution_week_no_outcomes))st.agents[a.id].resolution_week_no_outcomes=[];
if(!Number.isFinite(Number(st.agents[a.id].shock_fade_expired_ungraded)))st.agents[a.id].shock_fade_expired_ungraded=0; if(!Number.isFinite(Number(st.agents[a.id].shock_fade_expired_ungraded)))st.agents[a.id].shock_fade_expired_ungraded=0;
if(!("lastDecision" in st.agents[a.id]))st.agents[a.id].lastDecision=null; if(!("lastDecision" in st.agents[a.id]))st.agents[a.id].lastDecision=null;
}); });
@@ -1722,6 +1722,8 @@ function compactPortfolioForSync(p,limits=SYNC_LIMITS){
out.sports_favorite_outcomes=Array.isArray(p.sports_favorite_outcomes)?p.sports_favorite_outcomes.slice(-SPORTS_FAVORITE_OUTCOME_LIMIT):[]; out.sports_favorite_outcomes=Array.isArray(p.sports_favorite_outcomes)?p.sports_favorite_outcomes.slice(-SPORTS_FAVORITE_OUTCOME_LIMIT):[];
out.shock_fade_shadows=Array.isArray(p.shock_fade_shadows)?p.shock_fade_shadows.slice(-SHOCK_FADE_SHADOW_LIMIT):[]; out.shock_fade_shadows=Array.isArray(p.shock_fade_shadows)?p.shock_fade_shadows.slice(-SHOCK_FADE_SHADOW_LIMIT):[];
out.shock_fade_outcomes=Array.isArray(p.shock_fade_outcomes)?p.shock_fade_outcomes.slice(-SHOCK_FADE_OUTCOME_LIMIT):[]; out.shock_fade_outcomes=Array.isArray(p.shock_fade_outcomes)?p.shock_fade_outcomes.slice(-SHOCK_FADE_OUTCOME_LIMIT):[];
out.resolution_week_no_shadows=Array.isArray(p.resolution_week_no_shadows)?p.resolution_week_no_shadows.slice(-RESOLUTION_WEEK_NO_SHADOW_LIMIT):[];
out.resolution_week_no_outcomes=Array.isArray(p.resolution_week_no_outcomes)?p.resolution_week_no_outcomes.slice(-RESOLUTION_WEEK_NO_OUTCOME_LIMIT):[];
out.closed=Array.isArray(p.closed)?p.closed.slice(-limits.closed):[]; out.closed=Array.isArray(p.closed)?p.closed.slice(-limits.closed):[];
out.history=Array.isArray(p.history)?p.history.slice(-limits.history):[]; out.history=Array.isArray(p.history)?p.history.slice(-limits.history):[];
out.snapshots=Array.isArray(p.snapshots)?p.snapshots.slice(-limits.snapshots):[]; out.snapshots=Array.isArray(p.snapshots)?p.snapshots.slice(-limits.snapshots):[];
@@ -2590,6 +2592,11 @@ function sharedShockFadePilotProfile(st){
} }
function resolutionWeekNoPilotProfile(p){ function resolutionWeekNoPilotProfile(p){
const grouped=new Map(); const grouped=new Map();
(p&&p.resolution_week_no_outcomes||[]).filter(outcome=>Number(outcome.resolution_week_strategy_version||0)===RESOLUTION_WEEK_NO_STRATEGY_VERSION)
.forEach((outcome,index)=>{
const key=String(outcome.event_key||outcome.market_id||`resolution-shadow-${index}`),row=grouped.get(key)||{values:[],horizon:Number(outcome.target_horizon_days||4)};
row.values.push(clamp(Number(outcome.net_return||0),-1,2));grouped.set(key,row);
});
(p&&p.closed||[]).filter(trade=>(trade.signal_type||"")==="resolution-week-no-pilot" (p&&p.closed||[]).filter(trade=>(trade.signal_type||"")==="resolution-week-no-pilot"
&&Number(trade.resolution_week_strategy_version||0)===RESOLUTION_WEEK_NO_STRATEGY_VERSION).forEach((trade,index)=>{ &&Number(trade.resolution_week_strategy_version||0)===RESOLUTION_WEEK_NO_STRATEGY_VERSION).forEach((trade,index)=>{
const key=String(trade.event_key||trade.market_id||`resolution-week-${index}`),basis=Math.max(1,Number(trade.original_cost||trade.cost||0)); const key=String(trade.event_key||trade.market_id||`resolution-week-${index}`),basis=Math.max(1,Number(trade.original_cost||trade.cost||0));
@@ -2610,29 +2617,78 @@ function resolutionWeekNoPilotProfile(p){
const demoted=(overall.events>=RESOLUTION_WEEK_NO_VERDICT_EVENTS&&(overall.mean<=0||overall.upper<=0))||pnl<=-starting*0.01; const demoted=(overall.events>=RESOLUTION_WEEK_NO_VERDICT_EVENTS&&(overall.mean<=0||overall.upper<=0))||pnl<=-starting*0.01;
const promoted=!demoted&&overall.events>=RESOLUTION_WEEK_NO_PROMOTION_EVENTS&&overall.lower>0.01; const promoted=!demoted&&overall.events>=RESOLUTION_WEEK_NO_PROMOTION_EVENTS&&overall.lower>0.01;
const allowed=!demoted&&(RESOLUTION_WEEK_NO_BACKTEST_APPROVED||promoted); const allowed=!demoted&&(RESOLUTION_WEEK_NO_BACKTEST_APPROVED||promoted);
return {state:demoted?"demoted":(promoted?"forward-promoted":"bounded-regime-pilot"),allowed,promoted,demoted,events:overall.events, const shadowPnl=(p&&p.resolution_week_no_outcomes||[]).filter(outcome=>Number(outcome.resolution_week_strategy_version||0)===RESOLUTION_WEEK_NO_STRATEGY_VERSION)
.reduce((sum,outcome)=>sum+Number(outcome.pnl_per_100||0),0);
return {state:demoted?"demoted":(promoted?"forward-promoted":"shadow"),allowed,promoted,demoted,events:overall.events,
mean:overall.mean,lower:overall.lower,upper:overall.upper,horizons,pnl:+pnl.toFixed(2), mean:overall.mean,lower:overall.lower,upper:overall.upper,horizons,pnl:+pnl.toFixed(2),
shadow_pnl_per_100:+shadowPnl.toFixed(2),active_shadows:(p&&p.resolution_week_no_shadows||[]).length,
position_pct:allowed?(promoted?RESOLUTION_WEEK_NO_PROMOTED_POSITION_PCT:RESOLUTION_WEEK_NO_POSITION_PCT):0}; position_pct:allowed?(promoted?RESOLUTION_WEEK_NO_PROMOTED_POSITION_PCT:RESOLUTION_WEEK_NO_POSITION_PCT):0};
} }
function sharedResolutionWeekNoPilotProfile(st){ function sharedResolutionWeekNoPilotProfile(st){
const portfolios=[...RESOLUTION_WEEK_NO_ADOPTER_IDS].map(id=>st&&st.agents&&st.agents[id]).filter(Boolean); const portfolios=[...RESOLUTION_WEEK_NO_ADOPTER_IDS].map(id=>st&&st.agents&&st.agents[id]).filter(Boolean);
const combined={starting_balance:portfolios.reduce((sum,p)=>sum+Math.max(1,Number(p.starting_balance||STARTING_BALANCE)),0),closed:portfolios.flatMap(p=>p.closed||[])}; const combined={starting_balance:portfolios.reduce((sum,p)=>sum+Math.max(1,Number(p.starting_balance||STARTING_BALANCE)),0),
closed:portfolios.flatMap(p=>p.closed||[]),resolution_week_no_shadows:portfolios.flatMap(p=>p.resolution_week_no_shadows||[]),
resolution_week_no_outcomes:portfolios.flatMap(p=>p.resolution_week_no_outcomes||[])};
return Object.assign(resolutionWeekNoPilotProfile(combined),{scope:"shared-adopters",adopters:portfolios.length}); return Object.assign(resolutionWeekNoPilotProfile(combined),{scope:"shared-adopters",adopters:portfolios.length});
} }
function applyResolutionWeekNoProfile(s,profile){ function applyResolutionWeekNoProfile(s,profile){
if(!s||(s.signal_type||"")!=="resolution-week-no-pilot")return s; if(!s||(s.signal_type||"")!=="resolution-week-no-pilot")return s;
const horizon=profile&&profile.horizons&&profile.horizons[Number(s.target_horizon_days||7)],horizonAllowed=!horizon||horizon.allowed; const horizon=profile&&profile.horizons&&profile.horizons[Number(s.target_horizon_days||7)],horizonAllowed=!horizon||horizon.allowed;
if(profile&&profile.allowed&&horizonAllowed)return Object.assign({},s,{adaptive_promotion:Boolean(profile.promoted), if(profile&&profile.allowed&&horizonAllowed)return Object.assign({},s,{trade_ready:true,entry_candidate:true,watch_only:false,audited_observation_only:false,
adaptive_promotion:Boolean(profile.promoted),
rationale:`Shared forward state: ${profile.state}, ${profile.events} independent settled events; ${s.target_horizon_days||7}-day cohort ${horizon&&horizon.events||0} events with ${((horizon&&horizon.mean||0)*100).toFixed(2)}% mean. ${s.rationale||""}`}); rationale:`Shared forward state: ${profile.state}, ${profile.events} independent settled events; ${s.target_horizon_days||7}-day cohort ${horizon&&horizon.events||0} events with ${((horizon&&horizon.mean||0)*100).toFixed(2)}% mean. ${s.rationale||""}`});
return Object.assign({},s,{trade_ready:false,entry_candidate:false,watch_only:true,audited_observation_only:true, return Object.assign({},s,{trade_ready:false,entry_candidate:false,watch_only:true,audited_observation_only:true,
rationale:`Forward evidence disabled the ${s.target_horizon_days||7}-day regime pilot after ${horizon&&horizon.events||profile&&profile.events||0} independent settled events. ${s.rationale||""}`}); rationale:`Capital remains disabled for the ${s.target_horizon_days||4}-day forward learner after ${horizon&&horizon.events||profile&&profile.events||0} independent settled events. ${s.rationale||""}`});
}
function stageResolutionWeekNoShadows(p,suggestions,{execute=true,usedEventKeys=null}={}){
p.resolution_week_no_shadows=Array.isArray(p.resolution_week_no_shadows)?p.resolution_week_no_shadows:[];
p.resolution_week_no_outcomes=Array.isArray(p.resolution_week_no_outcomes)?p.resolution_week_no_outcomes:[];
if(!execute)return {active:p.resolution_week_no_shadows.length,staged:0,candidates:0};
const used=new Set([...p.resolution_week_no_shadows,...p.resolution_week_no_outcomes,...(p.positions||[]),...(p.closed||[])]
.filter(row=>Number(row.resolution_week_strategy_version||0)===RESOLUTION_WEEK_NO_STRATEGY_VERSION)
.map(row=>String(row.event_key||row.market_id)));
(usedEventKeys||[]).forEach(key=>used.add(String(key)));
const candidates=(suggestions||[]).filter(s=>s.signal_type==="resolution-week-no-pilot");let staged=0;
for(const s of candidates){
if(p.resolution_week_no_shadows.length>=RESOLUTION_WEEK_NO_SHADOW_LIMIT)break;
const eventKey=String(s.event_key||s.market_id),marketId=String(s.market_id);if(used.has(eventKey))continue;
p.resolution_week_no_shadows.push({id:`resolution-shadow:${marketId}:${Date.now()}:${staged}`,market_id:marketId,event_key:eventKey,
question:s.question,event:s.event||"",side:"NO",entry_price:Number(s.entry_price),market_price:Number(s.market_price),current_price:Number(s.market_price),
target_horizon_days:Number(s.target_horizon_days||4),opened_at:cycleIso(),resolution_week_strategy_version:RESOLUTION_WEEK_NO_STRATEGY_VERSION,
modeled_cost:+Math.max(0,Number(s.entry_price)-Number(s.market_price)).toFixed(4),url:s.url||""});
p.history.push({date:logDay(),action:"RESOLUTION_SHADOW",question:s.question,side:"NO",
detail:`Zero-capital 4-day NO observation recorded at modeled ${pct(s.entry_price)} · one observation for event ${eventKey} · cash unchanged`});
used.add(eventKey);staged++;
}
return {active:p.resolution_week_no_shadows.length,staged,candidates:candidates.length};
}
function manageResolutionWeekNoShadows(p,priceMap,{execute=true}={}){
p.resolution_week_no_shadows=Array.isArray(p.resolution_week_no_shadows)?p.resolution_week_no_shadows:[];
p.resolution_week_no_outcomes=Array.isArray(p.resolution_week_no_outcomes)?p.resolution_week_no_outcomes:[];
if(!execute)return {active:p.resolution_week_no_shadows.length,completed:0};
const keep=[];let completed=0;
for(const row of p.resolution_week_no_shadows){
const fresh=priceMap&&priceMap[String(row.market_id)];if(!fresh){keep.push(row);continue;}
const price=Number(fresh.no_price);if(Number.isFinite(price))row.current_price=+price.toFixed(4);
if(!marketIsSettled(fresh)){if(marketIsSuspended(fresh))row.price_status="orders-paused";keep.push(row);continue;}
const entry=Math.max(0.01,Number(row.entry_price||0)),netReturn=clamp(price/entry-1,-1,2),pnlPer100=netReturn*100;
if(!p.resolution_week_no_outcomes.some(outcome=>outcome.id===row.id))p.resolution_week_no_outcomes.push(Object.assign({},row,{closed_at:cycleIso(),
exit_price:+price.toFixed(4),net_return:+netReturn.toFixed(4),pnl_per_100:+pnlPer100.toFixed(2)}));
p.history.push({date:logDay(),action:"RESOLUTION_GRADE",question:row.question,side:"NO",
detail:`Forward resolution observation settled at ${pct(price)} · modeled net return ${(netReturn*100).toFixed(2)}% · portfolio cash unchanged`});completed++;
}
p.resolution_week_no_shadows=keep;p.resolution_week_no_outcomes=p.resolution_week_no_outcomes.slice(-RESOLUTION_WEEK_NO_OUTCOME_LIMIT);
return {active:keep.length,completed};
} }
function currentResolutionWeekEventKeys(st){ function currentResolutionWeekEventKeys(st){
const keys=new Set(); const keys=new Set();
AGENTS.forEach(agent=>{ AGENTS.forEach(agent=>{
const p=st&&st.agents&&st.agents[agent.id]||{}; const p=st&&st.agents&&st.agents[agent.id]||{};
[...(p.positions||[]),...(p.closed||[])].filter(row=>row.signal_type==="resolution-week-no-pilot" const active=(p.positions||[]).filter(row=>row.signal_type==="resolution-week-no-pilot");
&&Number(row.resolution_week_strategy_version||0)===RESOLUTION_WEEK_NO_STRATEGY_VERSION) const currentEvidence=[...(p.closed||[]),...(p.resolution_week_no_shadows||[]),...(p.resolution_week_no_outcomes||[])]
.filter(row=>(row.signal_type==="resolution-week-no-pilot"||row.resolution_week_strategy_version)
&&Number(row.resolution_week_strategy_version||0)===RESOLUTION_WEEK_NO_STRATEGY_VERSION);
[...active,...currentEvidence]
.forEach(row=>keys.add(String(row.event_key||row.market_id))); .forEach(row=>keys.add(String(row.event_key||row.market_id)));
}); });
return keys; return keys;
@@ -3943,6 +3999,7 @@ async function runDailyCycle(){
AGENTS.forEach(a=>(st.agents[a.id].maker_quotes||[]).forEach(quote=>{if(quote.market_id)positionIds.add(String(quote.market_id));})); AGENTS.forEach(a=>(st.agents[a.id].maker_quotes||[]).forEach(quote=>{if(quote.market_id)positionIds.add(String(quote.market_id));}));
AGENTS.forEach(a=>(st.agents[a.id].sports_favorite_shadows||[]).forEach(row=>{if(row.market_id)positionIds.add(String(row.market_id));})); AGENTS.forEach(a=>(st.agents[a.id].sports_favorite_shadows||[]).forEach(row=>{if(row.market_id)positionIds.add(String(row.market_id));}));
AGENTS.forEach(a=>(st.agents[a.id].shock_fade_shadows||[]).forEach(row=>{if(row.market_id)positionIds.add(String(row.market_id));})); AGENTS.forEach(a=>(st.agents[a.id].shock_fade_shadows||[]).forEach(row=>{if(row.market_id)positionIds.add(String(row.market_id));}));
AGENTS.forEach(a=>(st.agents[a.id].resolution_week_no_shadows||[]).forEach(row=>{if(row.market_id)positionIds.add(String(row.market_id));}));
setStatus("marking positions…",true); setStatus("marking positions…",true);
const priceMap={}; const priceMap={};
const cachedById={}; const cachedById={};
@@ -3977,6 +4034,8 @@ async function runDailyCycle(){
const sportsShadowActivity=manageSportsFavoriteShadows(favoritePortfolio,priceMap,{execute:runMode==="live"&&executeTrades}); const sportsShadowActivity=manageSportsFavoriteShadows(favoritePortfolio,priceMap,{execute:runMode==="live"&&executeTrades});
const shockPortfolio=st.agents.reversal; const shockPortfolio=st.agents.reversal;
const shockShadowActivity=manageShockFadeShadows(shockPortfolio,priceMap,{execute:runMode==="live"&&executeTrades}); const shockShadowActivity=manageShockFadeShadows(shockPortfolio,priceMap,{execute:runMode==="live"&&executeTrades});
const resolutionShadowPortfolio=st.agents.catalyst;
const resolutionShadowActivity=manageResolutionWeekNoShadows(resolutionShadowPortfolio,priceMap,{execute:runMode==="live"&&executeTrades});
setStatus("ten strategy agents trading…",true); setStatus("ten strategy agents trading…",true);
const preBoard=AGENTS.map(a=>({id:a.id,eq:equity(st.agents[a.id])})).sort((x,y)=>y.eq-x.eq); const preBoard=AGENTS.map(a=>({id:a.id,eq:equity(st.agents[a.id])})).sort((x,y)=>y.eq-x.eq);
const leaderEq=preBoard[0]?preBoard[0].eq:STARTING_BALANCE; const leaderEq=preBoard[0]?preBoard[0].eq:STARTING_BALANCE;
@@ -4028,7 +4087,7 @@ async function runDailyCycle(){
.forEach(row=>claimedResolutionWeekEvents.add(String(row.event_key||row.market_id))); .forEach(row=>claimedResolutionWeekEvents.add(String(row.event_key||row.market_id)));
if(RESOLUTION_WEEK_NO_ADOPTER_IDS.has(cfg.id)){ if(RESOLUTION_WEEK_NO_ADOPTER_IDS.has(cfg.id)){
p.lastDecision=Object.assign({},p.lastDecision,{resolutionWeekNoPilot:sharedResolutionWeekProfile}); p.lastDecision=Object.assign({},p.lastDecision,{resolutionWeekNoPilot:sharedResolutionWeekProfile});
p.lastDecision.allocationStatus=`${p.lastDecision.allocationStatus||""} Resolution-window NO pilot: shared state ${sharedResolutionWeekProfile.state}, ${sharedResolutionWeekProfile.events} settled events, ${(sharedResolutionWeekProfile.position_pct*100).toFixed(2)}% position cap and ${RESOLUTION_WEEK_NO_TOTAL_CAPITAL_PCT*100}% total cap; only validated 3d6d windows can trade, one agent owns each event, and positions hold to verified settlement.`.trim(); p.lastDecision.allocationStatus=`${p.lastDecision.allocationStatus||""} Corrected 4-day NO learner: shared state ${sharedResolutionWeekProfile.state}, ${sharedResolutionWeekProfile.events} settled events and ${(sharedResolutionWeekProfile.position_pct*100).toFixed(2)}% position cap; capital stays at zero before forward promotion.`.trim();
} }
if(SHOCK_FADE_ADOPTER_IDS.has(cfg.id)){ if(SHOCK_FADE_ADOPTER_IDS.has(cfg.id)){
(p.positions||[]).filter(row=>row.signal_type==="shock-fade-pilot"&&Number(row.shock_strategy_version||0)===SHOCK_FADE_STRATEGY_VERSION) (p.positions||[]).filter(row=>row.signal_type==="shock-fade-pilot"&&Number(row.shock_strategy_version||0)===SHOCK_FADE_STRATEGY_VERSION)
@@ -4065,6 +4124,15 @@ async function runDailyCycle(){
shockFadePilot:shockProfile}); shockFadePilot:shockProfile});
adopter.lastDecision.allocationStatus=`${adopter.lastDecision.allocationStatus||""} Shared shock strategy ${SHOCK_FADE_STRATEGY_VERSION}: ${shockStage.active} zero-capital observation${shockStage.active===1?"":"s"} active, ${shockShadowActivity.completed} ${SHOCK_FADE_EXIT_HOURS}-hour outcome${shockShadowActivity.completed===1?"":"s"} graded this cycle, ${shockProfile.events}/${SHOCK_FADE_QUALIFICATION_EVENTS} events needed for 1% capital and ${SHOCK_FADE_PROMOTION_EVENTS} for 1.5%; current cap ${(shockProfile.position_pct*100).toFixed(2)}%.`.trim(); adopter.lastDecision.allocationStatus=`${adopter.lastDecision.allocationStatus||""} Shared shock strategy ${SHOCK_FADE_STRATEGY_VERSION}: ${shockStage.active} zero-capital observation${shockStage.active===1?"":"s"} active, ${shockShadowActivity.completed} ${SHOCK_FADE_EXIT_HOURS}-hour outcome${shockShadowActivity.completed===1?"":"s"} graded this cycle, ${shockProfile.events}/${SHOCK_FADE_QUALIFICATION_EVENTS} events needed for 1% capital and ${SHOCK_FADE_PROMOTION_EVENTS} for 1.5%; current cap ${(shockProfile.position_pct*100).toFixed(2)}%.`.trim();
}); });
const resolutionStage=stageResolutionWeekNoShadows(resolutionShadowPortfolio,cycleSuggestions,{execute:runMode==="live"&&entriesAllowed,usedEventKeys:claimedResolutionWeekEvents});
const resolutionProfile=sharedResolutionWeekNoPilotProfile(st);
[...RESOLUTION_WEEK_NO_ADOPTER_IDS].forEach(id=>{
const adopter=st.agents[id];if(!adopter||!adopter.lastDecision)return;
adopter.lastDecision=Object.assign({},adopter.lastDecision,{resolutionSharedLearning:true,resolutionShadowActive:resolutionStage.active,
resolutionShadowStaged:resolutionStage.staged,resolutionShadowCandidates:resolutionStage.candidates,
resolutionShadowCompleted:resolutionShadowActivity.completed,resolutionWeekNoPilot:resolutionProfile});
adopter.lastDecision.allocationStatus=`${adopter.lastDecision.allocationStatus||""} Shared 4-day NO learner: ${resolutionStage.active} zero-capital observation${resolutionStage.active===1?"":"s"} active, ${resolutionShadowActivity.completed} settled outcome${resolutionShadowActivity.completed===1?"":"s"} graded this cycle, ${resolutionProfile.events}/${RESOLUTION_WEEK_NO_PROMOTION_EVENTS} events needed before a 0.5% paper position; current cap ${(resolutionProfile.position_pct*100).toFixed(2)}%.`.trim();
});
AGENTS.forEach(agent=>recordSnapshot(st.agents[agent.id])); AGENTS.forEach(agent=>recordSnapshot(st.agents[agent.id]));
st.date=todayStr();st.last_run=SNAP_TS;st.last_cycle_hour=hour;st.run_mode=runMode; st.date=todayStr();st.last_run=SNAP_TS;st.last_cycle_hour=hour;st.run_mode=runMode;
st.offline_cache_age_minutes=runMode==="offline-cache"?Math.round(cacheAgeMs/60000):0; st.offline_cache_age_minutes=runMode==="offline-cache"?Math.round(cacheAgeMs/60000):0;
@@ -4264,15 +4332,15 @@ function decisionSummary(p){
const maker=d.makerQuotes!=null?` Maker research: ${d.makerShadowActive||0} zero-capital lock-or-exit observations active; ${d.makerFills||0} verified touches and ${d.makerShadowCompleted||0} outcomes completed this cycle.${makerStats?` Event-clustered ledger: ${makerStats.attempts} attempts / ${makerStats.events} events, ${makerStats.locked} locked pairs, ${makerStats.adverse} immediate adverse exits, ${makerStats.unfilled} unfilled, and ${fmtUSD(makerStats.shadow_pnl)} simulated shadow net.`:""} Capital is disabled because neither the 6,048-rule chronological maker audit nor the reward stress test produced a validated holdout winner. Hypothetical rewards are excluded.`:""; const maker=d.makerQuotes!=null?` Maker research: ${d.makerShadowActive||0} zero-capital lock-or-exit observations active; ${d.makerFills||0} verified touches and ${d.makerShadowCompleted||0} outcomes completed this cycle.${makerStats?` Event-clustered ledger: ${makerStats.attempts} attempts / ${makerStats.events} events, ${makerStats.locked} locked pairs, ${makerStats.adverse} immediate adverse exits, ${makerStats.unfilled} unfilled, and ${fmtUSD(makerStats.shadow_pnl)} simulated shadow net.`:""} Capital is disabled because neither the 6,048-rule chronological maker audit nor the reward stress test produced a validated holdout winner. Hypothetical rewards are excluded.`:"";
const sportsPilot=d.sportsFavoritePilot?` Sports forward learner: ${d.sportsFavoritePilot.state}, ${d.sportsFavoritePilot.active_shadows||0} zero-capital observations active and ${d.sportsFavoritePilot.events} independent closed events, ${d.sportsFavoritePilot.events?`${(d.sportsFavoritePilot.mean*100).toFixed(2)}% mean with ${d.sportsFavoritePilot.lower>=0?"+":""}${(d.sportsFavoritePilot.lower*100).toFixed(2)}% to ${d.sportsFavoritePilot.upper>=0?"+":""}${(d.sportsFavoritePilot.upper*100).toFixed(2)}% 90% interval; `:""}${fmtUSD(d.sportsFavoritePilot.shadow_pnl_per_100||0)} simulated per-$100 net and ${fmtUSD(d.sportsFavoritePilot.pnl)} realized capital P&L. Position cap ${(d.sportsFavoritePilot.position_pct*100).toFixed(2)}%; capital remains zero until ${SPORTS_FAVORITE_PROMOTION_EVENTS} new independent events establish a positive lower bound.`:""; const sportsPilot=d.sportsFavoritePilot?` Sports forward learner: ${d.sportsFavoritePilot.state}, ${d.sportsFavoritePilot.active_shadows||0} zero-capital observations active and ${d.sportsFavoritePilot.events} independent closed events, ${d.sportsFavoritePilot.events?`${(d.sportsFavoritePilot.mean*100).toFixed(2)}% mean with ${d.sportsFavoritePilot.lower>=0?"+":""}${(d.sportsFavoritePilot.lower*100).toFixed(2)}% to ${d.sportsFavoritePilot.upper>=0?"+":""}${(d.sportsFavoritePilot.upper*100).toFixed(2)}% 90% interval; `:""}${fmtUSD(d.sportsFavoritePilot.shadow_pnl_per_100||0)} simulated per-$100 net and ${fmtUSD(d.sportsFavoritePilot.pnl)} realized capital P&L. Position cap ${(d.sportsFavoritePilot.position_pct*100).toFixed(2)}%; capital remains zero until ${SPORTS_FAVORITE_PROMOTION_EVENTS} new independent events establish a positive lower bound.`:"";
const shockPilot=d.shockFadePilot?` Shared shock strategy ${SHOCK_FADE_STRATEGY_VERSION}: ${d.shockFadePilot.state}, ${d.shockFadePilot.active_shadows||0} ${SHOCK_FADE_EXIT_HOURS}-hour observations active and ${d.shockFadePilot.events} deduplicated forward events complete across five adopters. Mean ${(d.shockFadePilot.mean*100).toFixed(2)}%; 90% interval ${(d.shockFadePilot.lower*100).toFixed(2)}% to ${(d.shockFadePilot.upper*100).toFixed(2)}%; ${d.shockFadePilot.expired_ungraded||0} missed windows were discarded. Position cap ${(d.shockFadePilot.position_pct*100).toFixed(2)}%, total cap ${SHOCK_FADE_TOTAL_CAPITAL_PCT*100}%; ${SHOCK_FADE_QUALIFICATION_EVENTS} positive events can qualify 1% capital and ${SHOCK_FADE_PROMOTION_EVENTS} stronger events can raise size to ${SHOCK_FADE_PROMOTED_POSITION_PCT*100}%.`:""; const shockPilot=d.shockFadePilot?` Shared shock strategy ${SHOCK_FADE_STRATEGY_VERSION}: ${d.shockFadePilot.state}, ${d.shockFadePilot.active_shadows||0} ${SHOCK_FADE_EXIT_HOURS}-hour observations active and ${d.shockFadePilot.events} deduplicated forward events complete across five adopters. Mean ${(d.shockFadePilot.mean*100).toFixed(2)}%; 90% interval ${(d.shockFadePilot.lower*100).toFixed(2)}% to ${(d.shockFadePilot.upper*100).toFixed(2)}%; ${d.shockFadePilot.expired_ungraded||0} missed windows were discarded. Position cap ${(d.shockFadePilot.position_pct*100).toFixed(2)}%, total cap ${SHOCK_FADE_TOTAL_CAPITAL_PCT*100}%; ${SHOCK_FADE_QUALIFICATION_EVENTS} positive events can qualify 1% capital and ${SHOCK_FADE_PROMOTION_EVENTS} stronger events can raise size to ${SHOCK_FADE_PROMOTED_POSITION_PCT*100}%.`:"";
const resolutionWeek=d.resolutionWeekNoPilot?` Resolution-window NO pilot: ${d.resolutionWeekNoPilot.state}, ${d.resolutionWeekNoPilot.events} shared settled events, ${(d.resolutionWeekNoPilot.mean*100).toFixed(2)}% mean and ${(d.resolutionWeekNoPilot.lower*100).toFixed(2)}% lower 90% bound. Position cap ${(d.resolutionWeekNoPilot.position_pct*100).toFixed(2)}%, total cap ${RESOLUTION_WEEK_NO_TOTAL_CAPITAL_PCT*100}%; only validated 3d6d windows can trade, each horizon adapts separately, one agent owns each event, and every position holds to verified settlement.`:""; const resolutionWeek=d.resolutionWeekNoPilot?` Corrected 4-day NO learner: ${d.resolutionWeekNoPilot.state}, ${d.resolutionWeekNoPilot.events} shared settled events, ${(d.resolutionWeekNoPilot.mean*100).toFixed(2)}% mean and ${(d.resolutionWeekNoPilot.lower*100).toFixed(2)}% lower 90% bound. Position cap ${(d.resolutionWeekNoPilot.position_pct*100).toFixed(2)}%; capital remains zero until 40 independent outcomes clear the forward confidence gate.`:"";
return `${d.mode} mode: ${d.reason}${emotion} Limits now: ${d.maxNew} new trade${d.maxNew===1?"":"s"}, max ${(d.maxFrac*100).toFixed(1)}% per position${d.minConv?`, conviction ${d.minConv}+`:""}.${learning}${calibration}${maker}${sportsPilot}${shockPilot}${resolutionWeek}${exposure}${allocation}${candidates}${blockers}`; return `${d.mode} mode: ${d.reason}${emotion} Limits now: ${d.maxNew} new trade${d.maxNew===1?"":"s"}, max ${(d.maxFrac*100).toFixed(1)}% per position${d.minConv?`, conviction ${d.minConv}+`:""}.${learning}${calibration}${maker}${sportsPilot}${shockPilot}${resolutionWeek}${exposure}${allocation}${candidates}${blockers}`;
} }
function renderAgentBrief(cfg,p,st){ function renderAgentBrief(cfg,p,st){
const root=$("agentBrief"); if(!root)return; const root=$("agentBrief"); if(!root)return;
const bw=bestAndWorst(p); const bw=bestAndWorst(p);
const risk=cfg.aggressive?"Extreme risk":cfg.maxFrac>=0.055?"Active":cfg.maxFrac<=0.04?"Broad active":"Disciplined"; const risk=cfg.aggressive?"Extreme risk":cfg.maxFrac>=0.055?"Active":cfg.maxFrac<=0.04?"Broad active":"Disciplined";
const cadence=cfg.id==="favorite"?"Zero-capital 12h sports observations until 30 forward events promote 1.25% positions":RESOLUTION_WEEK_NO_ADOPTER_IDS.has(cfg.id)?`One bounded 3d6d resolution-window NO entry per cycle; ${RESOLUTION_WEEK_NO_TOTAL_CAPITAL_PCT*100}% total cap plus zero-capital shock research`:`${cfg.maxNew||0} new trades max per cycle`; const cadence=cfg.id==="favorite"?"Zero-capital 12h sports observations until 30 forward events promote 1.25% positions":RESOLUTION_WEEK_NO_ADOPTER_IDS.has(cfg.id)?`Zero-capital 4-day NO observations until 40 independent settlements promote 0.5% positions; plus zero-capital shock research`:`${cfg.maxNew||0} new trades max per cycle`;
const exitRule=cfg.id==="favorite"?"Grade shadow observations only when Polymarket closes the market; after promotion, capital positions retain the 18% stop and profit locks":RESOLUTION_WEEK_NO_ADOPTER_IDS.has(cfg.id)?`Hold 3d6d resolution-window positions to verified settlement; exit shock positions at the executable bid after ${SHOCK_FADE_EXIT_HOURS} hours and discard missed grading windows` const exitRule=cfg.id==="favorite"?"Grade shadow observations only when Polymarket closes the market; after promotion, capital positions retain the 18% stop and profit locks":RESOLUTION_WEEK_NO_ADOPTER_IDS.has(cfg.id)?`Grade 4-day NO observations only at verified settlement; after promotion, capital positions also hold to settlement; shock observations exit at the executable bid after ${SHOCK_FADE_EXIT_HOURS} hours`
:`Exit after a confirmed reversal, a 12h unconfirmed fade after 48h, a trailing-profit retrace, or ${EXIT_STALE_DAYS}d stale while losing; Politics trends get 72h before ordinary signal exits`; :`Exit after a confirmed reversal, a 12h unconfirmed fade after 48h, a trailing-profit retrace, or ${EXIT_STALE_DAYS}d stale while losing; Politics trends get 72h before ordinary signal exits`;
const thesis=agentPlainBlurb(cfg,st); const thesis=agentPlainBlurb(cfg,st);
const quoteSummary=(p.maker_quotes||[]).slice(0,3).map(quote=>`${quote.shadow_only?"Shadow":"Capital"} · ${quote.question.slice(0,34)}${quote.question.length>34?"...":""}: YES ${pct(quote.yes_quote)} + NO ${pct(quote.no_quote)}${quote.yes_filled_at||quote.no_filled_at?" (one leg touched)":""}`).join("; "); const quoteSummary=(p.maker_quotes||[]).slice(0,3).map(quote=>`${quote.shadow_only?"Shadow":"Capital"} · ${quote.question.slice(0,34)}${quote.question.length>34?"...":""}: YES ${pct(quote.yes_quote)} + NO ${pct(quote.no_quote)}${quote.yes_filled_at||quote.no_filled_at?" (one leg touched)":""}`).join("; ");
@@ -5900,6 +5968,8 @@ window.PMA_ENGINE_DIAGNOSTICS=Object.freeze({
resolutionWeekNoPilotProfile, resolutionWeekNoPilotProfile,
sharedResolutionWeekNoPilotProfile, sharedResolutionWeekNoPilotProfile,
applyResolutionWeekNoProfile, applyResolutionWeekNoProfile,
stageResolutionWeekNoShadows,
manageResolutionWeekNoShadows,
autonomousRuntime:Object.freeze({version:1,publicKeys:[...PUBLIC_RUNTIME_KEYS],suggestionLimit:PUBLIC_RUNTIME_LIMITS.suggestions, autonomousRuntime:Object.freeze({version:1,publicKeys:[...PUBLIC_RUNTIME_KEYS],suggestionLimit:PUBLIC_RUNTIME_LIMITS.suggestions,
excludedKeys:[PAPER_KEY,EMAIL_ALERT_KEY,INVEST_KEY,LIVE_KEY,CHAT_KEY,PAID_AGENT_CHAT_KEY]}), excludedKeys:[PAPER_KEY,EMAIL_ALERT_KEY,INVEST_KEY,LIVE_KEY,CHAT_KEY,PAID_AGENT_CHAT_KEY]}),
marketIsSettled, marketIsSettled,
@@ -5959,8 +6029,9 @@ window.PMA_ENGINE_DIAGNOSTICS=Object.freeze({
slippageBufferCents:RESOLUTION_WEEK_NO_SLIPPAGE_BUFFER*100,maximumEntryCostCents:RESOLUTION_WEEK_NO_MAX_EXECUTION_COST*100, slippageBufferCents:RESOLUTION_WEEK_NO_SLIPPAGE_BUFFER*100,maximumEntryCostCents:RESOLUTION_WEEK_NO_MAX_EXECUTION_COST*100,
maximumExecutableEntry:RESOLUTION_WEEK_NO_MAX_EXECUTABLE_ENTRY, maximumExecutableEntry:RESOLUTION_WEEK_NO_MAX_EXECUTABLE_ENTRY,
adopterAgentIds:[...RESOLUTION_WEEK_NO_ADOPTER_IDS],backtestApproved:RESOLUTION_WEEK_NO_BACKTEST_APPROVED, adopterAgentIds:[...RESOLUTION_WEEK_NO_ADOPTER_IDS],backtestApproved:RESOLUTION_WEEK_NO_BACKTEST_APPROVED,
fixedDateOnly:true,sportsExcluded:true,settlementOnlyExit:true,oneOwnerPerEvent:true,sharedForwardDemotion:true}, shadowLimit:RESOLUTION_WEEK_NO_SHADOW_LIMIT,outcomeLimit:RESOLUTION_WEEK_NO_OUTCOME_LIMIT,capitalRequiresForwardPromotion:true,
historicalPrior:"No broad directional rule survived the adaptive holdouts at both 24h and 72h. Contract-safe Shock Strategy 4 remains zero-capital after its untouched expansion failed. An exact production-matched 50%-55% NO rule passed safe non-Sports chronological audits at three, four, five, and six days with one-cent modeled cost; two days failed holdout and seven through ten days failed the stricter all-segment confidence test or were not retained. Contemporaneous historical liquidity cannot be reconstructed, so only live safe non-Sports contracts in the passing windows that clear spread and liquidity gates receive 0.5% paper positions, one owner per event, a 3% cap, settlement-only exits, and automatic per-horizon demotion from forward losses. Favorite-priced trend remains hard-blocked. Maker capital remains disabled"}), oneDecisionPerEventAudit:true,disjointHoldoutRequired:true,fixedDateOnly:true,sportsExcluded:true,settlementOnlyExit:true,oneOwnerPerEvent:true,sharedForwardDemotion:true},
historicalPrior:"No broad directional rule survived the adaptive holdouts at both 24h and 72h. Contract-safe Shock Strategy 4 remains zero-capital after its untouched expansion failed. The earlier 3-6 day 50%-55% NO permission was invalidated because its audit averaged several correlated contracts per event. A corrected one-decision-per-event replay retained only the four-day discovery window, and that candidate failed the all-segment gate in a disjoint older 3,000-market holdout. It now collects zero-capital forward settlements and requires 40 independent outcomes with a positive lower confidence bound above 1% before 0.5% paper positions can begin. Favorite-priced trend remains hard-blocked. Maker capital remains disabled"}),
}); });
function runEngineSelfTest(){ function runEngineSelfTest(){
const market=(overrides={})=>Object.assign({ const market=(overrides={})=>Object.assign({
@@ -5979,23 +6050,36 @@ function runEngineSelfTest(){
const pathBarrierContract=analyzeMarket(market({id:"barrier-test",question:"Will Bitcoin reach $66,000 August 17-23?",category:"Crypto"}),news); const pathBarrierContract=analyzeMarket(market({id:"barrier-test",question:"Will Bitcoin reach $66,000 August 17-23?",category:"Crypto"}),news);
const fixedDateLevelContract=analyzeMarket(market({id:"fixed-level-test",question:"Will Bitcoin be above $66,000 on 2026-08-23?",category:"Crypto"}),news); const fixedDateLevelContract=analyzeMarket(market({id:"fixed-level-test",question:"Will Bitcoin be above $66,000 on 2026-08-23?",category:"Crypto"}),news);
const ordinaryDatedContract=analyzeMarket(market({id:"dated-test",question:"Will the policy pass on 2026-08-22?"}),news); const ordinaryDatedContract=analyzeMarket(market({id:"dated-test",question:"Will the policy pass on 2026-08-22?"}),news);
const resolutionWeekEnd=new Date(Date.now()+6*86400000).toISOString(); const resolutionWeekEnd=new Date(Date.now()+4*86400000).toISOString();
const resolutionWeekMarket=market({id:"resolution-week",question:"Will Bitcoin be above $82,000 on August 27?",event:"Bitcoin price on August 27",event_id:"btc-aug-27", const resolutionWeekMarket=market({id:"resolution-week",question:"Will Bitcoin be above $82,000 on August 27?",event:"Bitcoin price on August 27",event_id:"btc-aug-27",
category:"Crypto",yes_price:0.48,no_price:0.52,best_bid:0.477,best_ask:0.483,spread:0.006,volume:250000,volume_24hr:30000,liquidity:35000, category:"Crypto",yes_price:0.48,no_price:0.52,best_bid:0.477,best_ask:0.483,spread:0.006,volume:250000,volume_24hr:30000,liquidity:35000,
days_to_resolution:6,end_date:resolutionWeekEnd,price_change_1h:0,price_change_1d:0,price_change_1w:0}); days_to_resolution:4,end_date:resolutionWeekEnd,price_change_1h:0,price_change_1d:0,price_change_1w:0});
const resolutionWeekSuggestion=resolutionWeekNoSuggestion(resolutionWeekMarket); const resolutionWeekSuggestion=resolutionWeekNoSuggestion(resolutionWeekMarket);
const validatedResolutionHorizons=[3,4,5,6].map(days=>resolutionWeekNoSuggestion(Object.assign({},resolutionWeekMarket, const unvalidatedThreeDayResolution=resolutionWeekNoSuggestion(Object.assign({},resolutionWeekMarket,
{id:`resolution-${days}d`,event_id:`resolution-${days}d-event`,days_to_resolution:days}))); {id:"resolution-3d",event_id:"resolution-3d-event",days_to_resolution:3}));
const unvalidatedSevenDayResolution=resolutionWeekNoSuggestion(Object.assign({},resolutionWeekMarket, const unvalidatedFiveDayResolution=resolutionWeekNoSuggestion(Object.assign({},resolutionWeekMarket,
{id:"resolution-7d",event_id:"resolution-7d-event",days_to_resolution:7})); {id:"resolution-5d",event_id:"resolution-5d-event",days_to_resolution:5}));
const pathDependentResolutionWeek=resolutionWeekNoSuggestion(market({id:"resolution-path",question:"Will Bitcoin reach $82,000 by August 27?",event_id:"resolution-path-event", const pathDependentResolutionWeek=resolutionWeekNoSuggestion(market({id:"resolution-path",question:"Will Bitcoin reach $82,000 by August 27?",event_id:"resolution-path-event",
category:"Crypto",yes_price:0.48,no_price:0.52,best_bid:0.477,best_ask:0.483,spread:0.006,volume:250000,liquidity:35000,days_to_resolution:6,end_date:resolutionWeekEnd})); category:"Crypto",yes_price:0.48,no_price:0.52,best_bid:0.477,best_ask:0.483,spread:0.006,volume:250000,liquidity:35000,days_to_resolution:4,end_date:resolutionWeekEnd}));
const sportsResolutionWeek=resolutionWeekNoSuggestion(market({id:"resolution-sports",question:"Will Harbor FC win?",event_id:"resolution-sports-event", const sportsResolutionWeek=resolutionWeekNoSuggestion(market({id:"resolution-sports",question:"Will Harbor FC win?",event_id:"resolution-sports-event",
category:"Sports",yes_price:0.48,no_price:0.52,best_bid:0.477,best_ask:0.483,spread:0.006,volume:250000,liquidity:35000,days_to_resolution:6,end_date:resolutionWeekEnd})); category:"Sports",yes_price:0.48,no_price:0.52,best_bid:0.477,best_ask:0.483,spread:0.006,volume:250000,liquidity:35000,days_to_resolution:4,end_date:resolutionWeekEnd}));
const resolutionAgent=AGENTS.find(agent=>agent.id==="catalyst"),initialResolutionProfile=resolutionWeekNoPilotProfile(defaultPortfolio()); const resolutionAgent=AGENTS.find(agent=>agent.id==="catalyst"),initialResolutionProfile=resolutionWeekNoPilotProfile(defaultPortfolio());
const resolutionShadowBook=defaultPortfolio(),resolutionShadowCash=resolutionShadowBook.cash;
const resolutionShadowStage=stageResolutionWeekNoShadows(resolutionShadowBook,[resolutionWeekSuggestion]);
const pausedResolutionGrade=manageResolutionWeekNoShadows(resolutionShadowBook,{"resolution-week":market({id:"resolution-week",yes_price:0.40,no_price:0.60,closed:false,accepting_orders:false})});
const settledResolutionGrade=manageResolutionWeekNoShadows(resolutionShadowBook,{"resolution-week":market({id:"resolution-week",yes_price:0,no_price:1,closed:true,accepting_orders:false})});
const offlineResolutionBook=defaultPortfolio();stageResolutionWeekNoShadows(offlineResolutionBook,[resolutionWeekSuggestion]);
const offlineResolutionGrade=manageResolutionWeekNoShadows(offlineResolutionBook,{"resolution-week":market({id:"resolution-week",yes_price:0,no_price:1,closed:true,accepting_orders:false})},{execute:false});
const compactedResolutionBook=compactPortfolioForSync(offlineResolutionBook);
const promotedResolutionState=defaultState();
for(let i=0;i<RESOLUTION_WEEK_NO_PROMOTION_EVENTS;i++)promotedResolutionState.agents.catalyst.resolution_week_no_outcomes.push({
resolution_week_strategy_version:RESOLUTION_WEEK_NO_STRATEGY_VERSION,target_horizon_days:4,event_key:`winning-resolution-${i}`,
market_id:`winning-resolution-${i}`,net_return:0.10,pnl_per_100:10});
const promotedResolutionProfile=sharedResolutionWeekNoPilotProfile(promotedResolutionState);
const promotedResolutionSuggestion=applyResolutionWeekNoProfile(resolutionWeekSuggestion,promotedResolutionProfile);
const resolutionBook=defaultPortfolio(),resolutionDecision={minConv:0,maxNew:4,maxFrac:0.09,reserve:0.10,targetExposure:0.80, const resolutionBook=defaultPortfolio(),resolutionDecision={minConv:0,maxNew:4,maxFrac:0.09,reserve:0.10,targetExposure:0.80,
learning:buildAdaptiveProfile(resolutionBook),marketLearning:buildSignalCalibration(defaultSignalLedger()),resolutionWeekNoPilot:initialResolutionProfile}; learning:buildAdaptiveProfile(resolutionBook),marketLearning:buildSignalCalibration(defaultSignalLedger()),resolutionWeekNoPilot:promotedResolutionProfile};
openPositions(resolutionBook,resolutionAgent,rankSuggestionsForAgent(resolutionAgent,[resolutionWeekSuggestion]),"All",resolutionDecision,new Set(),{}); openPositions(resolutionBook,resolutionAgent,rankSuggestionsForAgent(resolutionAgent,[promotedResolutionSuggestion]),"All",resolutionDecision,new Set(),{});
const resolutionCost=Number(resolutionBook.positions[0]&&resolutionBook.positions[0].cost||0); const resolutionCost=Number(resolutionBook.positions[0]&&resolutionBook.positions[0].cost||0);
markToMarket(resolutionBook,{"resolution-week":market({id:"resolution-week",yes_price:0.40,no_price:0.60,closed:false,accepting_orders:true})},resolutionAgent,{policyExits:true,executeTrades:true}); markToMarket(resolutionBook,{"resolution-week":market({id:"resolution-week",yes_price:0.40,no_price:0.60,closed:false,accepting_orders:true})},resolutionAgent,{policyExits:true,executeTrades:true});
const resolutionIgnoresInterimStop=resolutionBook.positions.length===1&&resolutionBook.positions[0].shares>0; const resolutionIgnoresInterimStop=resolutionBook.positions.length===1&&resolutionBook.positions[0].shares>0;
@@ -6005,13 +6089,6 @@ function runEngineSelfTest(){
resolution_week_strategy_version:RESOLUTION_WEEK_NO_STRATEGY_VERSION,event_key:`losing-resolution-${i}`,market_id:`losing-resolution-${i}`, resolution_week_strategy_version:RESOLUTION_WEEK_NO_STRATEGY_VERSION,event_key:`losing-resolution-${i}`,market_id:`losing-resolution-${i}`,
original_cost:50,cost:50,realized_pnl:-5}); original_cost:50,cost:50,realized_pnl:-5});
const losingResolutionProfile=sharedResolutionWeekNoPilotProfile(losingResolutionState); const losingResolutionProfile=sharedResolutionWeekNoPilotProfile(losingResolutionState);
const horizonResolutionState=defaultState();
for(let i=0;i<10;i++)horizonResolutionState.agents.breakout.closed.push({signal_type:"resolution-week-no-pilot",
resolution_week_strategy_version:RESOLUTION_WEEK_NO_STRATEGY_VERSION,target_horizon_days:3,event_key:`losing-3d-resolution-${i}`,
market_id:`losing-3d-resolution-${i}`,original_cost:50,cost:50,realized_pnl:-5});
const horizonResolutionProfile=sharedResolutionWeekNoPilotProfile(horizonResolutionState);
const blockedThreeDayResolution=applyResolutionWeekNoProfile(Object.assign({},resolutionWeekSuggestion,{target_horizon_days:3}),horizonResolutionProfile);
const allowedSixDayResolution=applyResolutionWeekNoProfile(Object.assign({},resolutionWeekSuggestion,{target_horizon_days:6}),horizonResolutionProfile);
const duplicateResolutionState=defaultState(); const duplicateResolutionState=defaultState();
duplicateResolutionState.agents.catalyst.closed.push({signal_type:"resolution-week-no-pilot",resolution_week_strategy_version:RESOLUTION_WEEK_NO_STRATEGY_VERSION, duplicateResolutionState.agents.catalyst.closed.push({signal_type:"resolution-week-no-pilot",resolution_week_strategy_version:RESOLUTION_WEEK_NO_STRATEGY_VERSION,
event_key:"duplicate-resolution-event",market_id:"duplicate-a",original_cost:50,cost:50,realized_pnl:5}); event_key:"duplicate-resolution-event",market_id:"duplicate-a",original_cost:50,cost:50,realized_pnl:5});
@@ -6019,6 +6096,10 @@ function runEngineSelfTest(){
event_key:"duplicate-resolution-event",market_id:"duplicate-b",original_cost:50,cost:50,realized_pnl:-5}); event_key:"duplicate-resolution-event",market_id:"duplicate-b",original_cost:50,cost:50,realized_pnl:-5});
const duplicateResolutionProfile=sharedResolutionWeekNoPilotProfile(duplicateResolutionState); const duplicateResolutionProfile=sharedResolutionWeekNoPilotProfile(duplicateResolutionState);
const claimedResolutionKeys=currentResolutionWeekEventKeys(duplicateResolutionState); const claimedResolutionKeys=currentResolutionWeekEventKeys(duplicateResolutionState);
const legacyResolutionClaimState=defaultState();
legacyResolutionClaimState.agents.catalyst.positions.push({signal_type:"resolution-week-no-pilot",resolution_week_strategy_version:2,
event_key:"legacy-active-resolution",market_id:"legacy-active-resolution"});
const legacyResolutionClaimKeys=currentResolutionWeekEventKeys(legacyResolutionClaimState);
const sportsPilotStart=new Date(Date.now()+12*3600000).toISOString(); const sportsPilotStart=new Date(Date.now()+12*3600000).toISOString();
const sportsPilot=analyzeMarket(market({id:"sports-pilot",question:"Will Harbor FC win tomorrow?",event:"Harbor FC vs City FC",event_id:"sports-event-1", const sportsPilot=analyzeMarket(market({id:"sports-pilot",question:"Will Harbor FC win tomorrow?",event:"Harbor FC vs City FC",event_id:"sports-event-1",
category:"Sports",yes_price:0.72,no_price:0.28,best_bid:0.715,best_ask:0.725,spread:0.01, category:"Sports",yes_price:0.72,no_price:0.28,best_bid:0.715,best_ask:0.725,spread:0.01,
@@ -6773,31 +6854,34 @@ function runEngineSelfTest(){
dualIndependentPromotionAllowsBoundedPeerBoost:dualPromotionMultiplier===1.05, dualIndependentPromotionAllowsBoundedPeerBoost:dualPromotionMultiplier===1.05,
legacyLossDoesNotFreezeCurrentEngine:legacyLossDecision.mode!=="Loss Regime Containment"}, legacyLossDoesNotFreezeCurrentEngine:legacyLossDecision.mode!=="Loss Regime Containment"},
resolutionWeekNoPilot:{ resolutionWeekNoPilot:{
identifiesFixedDateNoFavorite:Boolean(resolutionWeekSuggestion&&resolutionWeekSuggestion.trade_ready identifiesFixedDateNoFavorite:Boolean(resolutionWeekSuggestion&&!resolutionWeekSuggestion.trade_ready&&resolutionWeekSuggestion.watch_only
&&resolutionWeekSuggestion.side==="NO"&&resolutionWeekSuggestion.entry_price===0.5255), &&resolutionWeekSuggestion.side==="NO"&&resolutionWeekSuggestion.entry_price===0.5255),
acceptsEveryValidatedThreeThroughSixDayHorizon:validatedResolutionHorizons.length===4 keepsOnlyCorrectedFourDayDiscoveryWindow:resolutionWeekSuggestion.target_horizon_days===4
&&validatedResolutionHorizons.every((suggestion,index)=>suggestion&&suggestion.target_horizon_days===index+3), &&unvalidatedThreeDayResolution===null&&unvalidatedFiveDayResolution===null,
rejectsUnvalidatedSevenDayHorizon:unvalidatedSevenDayResolution===null,
usesExecutableNoAskPlusSlippage:Boolean(resolutionWeekSuggestion&&resolutionWeekSuggestion.market_price===0.52 usesExecutableNoAskPlusSlippage:Boolean(resolutionWeekSuggestion&&resolutionWeekSuggestion.market_price===0.52
&&resolutionWeekSuggestion.friction===0.0055), &&resolutionWeekSuggestion.friction===0.0055),
rejectsPathDependentBarrier:pathDependentResolutionWeek===null, rejectsPathDependentBarrier:pathDependentResolutionWeek===null,
rejectsSportsMetadata:sportsResolutionWeek===null, rejectsSportsMetadata:sportsResolutionWeek===null,
onlyAggressiveAdoptersAccept:Boolean(resolutionWeekSuggestion&&agentAcceptsSuggestion(resolutionAgent,resolutionWeekSuggestion) onlyAggressiveAdoptersAccept:Boolean(resolutionWeekSuggestion&&agentAcceptsSuggestion(resolutionAgent,resolutionWeekSuggestion)
&&!agentAcceptsSuggestion(AGENTS.find(agent=>agent.id==="value"),resolutionWeekSuggestion)), &&!agentAcceptsSuggestion(AGENTS.find(agent=>agent.id==="value"),resolutionWeekSuggestion)),
initialRegimeAuditAllowsBoundedCapital:initialResolutionProfile.allowed&&!initialResolutionProfile.demoted correctedAuditStartsAtZeroCapital:!initialResolutionProfile.allowed&&!initialResolutionProfile.demoted
&&initialResolutionProfile.position_pct===RESOLUTION_WEEK_NO_POSITION_PCT, &&initialResolutionProfile.position_pct===0,
opensHalfPercentPosition:resolutionCost>=49.99&&resolutionCost<=STARTING_BALANCE*RESOLUTION_WEEK_NO_POSITION_PCT+0.01, stagesOneZeroCapitalObservation:resolutionShadowStage.staged===1&&resolutionShadowBook.cash===resolutionShadowCash,
tradingPauseDoesNotGrade:pausedResolutionGrade.completed===0,
verifiedSettlementGradesObservation:settledResolutionGrade.completed===1&&resolutionShadowBook.resolution_week_no_outcomes.length===1,
offlineSnapshotCannotInventSettlement:offlineResolutionGrade.completed===0&&offlineResolutionBook.resolution_week_no_shadows.length===1,
forwardLearnerSurvivesCompaction:compactedResolutionBook.resolution_week_no_shadows.length===1,
fortyPositiveEventsPromoteHalfPercent:promotedResolutionProfile.promoted&&promotedResolutionProfile.allowed
&&promotedResolutionProfile.position_pct===RESOLUTION_WEEK_NO_PROMOTED_POSITION_PCT,
opensHalfPercentPositionAfterPromotion:resolutionCost>=49.99&&resolutionCost<=STARTING_BALANCE*RESOLUTION_WEEK_NO_PROMOTED_POSITION_PCT+0.01,
interimDrawdownDoesNotTriggerStop:resolutionIgnoresInterimStop, interimDrawdownDoesNotTriggerStop:resolutionIgnoresInterimStop,
closesOnlyAfterVerifiedSettlement:resolutionBook.positions.length===0&&resolutionBook.closed.length===1 closesOnlyAfterVerifiedSettlement:resolutionBook.positions.length===0&&resolutionBook.closed.length===1
&&resolutionBook.closed[0].close_reason==="Resolution-window contract settled", &&resolutionBook.closed[0].close_reason==="Resolution-window contract settled",
losingForwardCohortDisablesAllAdopters:losingResolutionProfile.demoted&&!losingResolutionProfile.allowed losingForwardCohortDisablesAllAdopters:losingResolutionProfile.demoted&&!losingResolutionProfile.allowed
&&losingResolutionProfile.position_pct===0, &&losingResolutionProfile.position_pct===0,
horizonsAdaptIndependently:horizonResolutionProfile.allowed&&horizonResolutionProfile.horizons[3].demoted
&&!horizonResolutionProfile.horizons[3].allowed&&horizonResolutionProfile.horizons[6].allowed,
demotedHorizonCannotTradeWhilePeerHorizonCan:!blockedThreeDayResolution.trade_ready&&blockedThreeDayResolution.watch_only
&&allowedSixDayResolution.trade_ready&&!allowedSixDayResolution.watch_only,
sharedEvidenceDeduplicatesEvent:duplicateResolutionProfile.events===1, sharedEvidenceDeduplicatesEvent:duplicateResolutionProfile.events===1,
globalEventClaimsDeduplicateOwner:claimedResolutionKeys.size===1&&claimedResolutionKeys.has("duplicate-resolution-event"), globalEventClaimsDeduplicateOwner:claimedResolutionKeys.size===1&&claimedResolutionKeys.has("duplicate-resolution-event"),
activeLegacyPositionBlocksNewEvidence:legacyResolutionClaimKeys.has("legacy-active-resolution"),
}, },
sportsFavoritePilot:{ sportsFavoritePilot:{
identifiesTimedForwardShadow:Boolean(sportsPilot&&!sportsPilot.trade_ready&&sportsPilot.audited_observation_only identifiesTimedForwardShadow:Boolean(sportsPilot&&!sportsPilot.trade_ready&&sportsPilot.audited_observation_only
+44 -63
View File
@@ -1,89 +1,70 @@
{ {
"generated_at": "2026-08-21T23:16:59.364Z", "generated_at": "2026-08-21T23:44:53.304Z",
"strategy": "resolution-window-no-50-55-safe-non-sports-v2", "strategy": "resolution-window-no-50-55-forward-shadow-v3",
"selection": { "selection": {
"markets_requested": 3000, "discovery_markets_requested": 3000,
"markets_with_history": 2954, "discovery_markets_with_history": 2918,
"disjoint_holdout_markets_requested": 3000,
"disjoint_holdout_markets_with_history": 2394,
"disjoint_holdout_offset": 3000,
"order": "closedTime descending", "order": "closedTime descending",
"horizon_days_tested": [2, 3, 4, 5, 6, 7, 8, 9, 10], "horizon_days_tested": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 21, 30],
"horizon_days_enabled": [3, 4, 5, 6], "horizon_days_enabled": [],
"horizon_days_observed": [4],
"modeled_round_trip_cost_cents": 1, "modeled_round_trip_cost_cents": 1,
"history_fidelity_minutes": 1440, "history_fidelity_minutes": 1440,
"cluster_unit": "Polymarket event", "decision_unit": "one highest-volume eligible contract per Polymarket event and rule",
"production_contract_filter": "non-Sports and no path-dependent barrier, numeric range, currency range, exact score, or post-count contract" "production_contract_filter": "non-Sports and no path-dependent barrier, numeric range, currency range, exact score, or post-count contract"
}, },
"rules": { "discovery_rule": {
"side": "NO", "side": "NO",
"midpoint_min_inclusive": 0.5, "midpoint_min_inclusive": 0.5,
"midpoint_max_exclusive": 0.55, "midpoint_max_exclusive": 0.55,
"3_day": { "horizon_days": 4,
"events": 121, "events": 145,
"event_mean_return": 0.2451763293, "event_mean_return": 0.3842272785,
"event_lower_90": 0.1577733713, "event_lower_90": 0.2612426599,
"train_events": 85,
"train_event_lower_90": 0.1314547114,
"holdout_events": 40,
"holdout_event_lower_90": 0.0991402647,
"chronological_thirds_event_lower_90": [0.052193276, 0.0937543342, 0.1174259244]
},
"4_day": {
"events": 144,
"event_mean_return": 0.381453985,
"event_lower_90": 0.3139573933,
"train_events": 102, "train_events": 102,
"train_event_lower_90": 0.3031863842, "train_event_lower_90": 0.290934746,
"holdout_events": 47, "holdout_events": 46,
"holdout_event_lower_90": 0.2716756304, "holdout_event_lower_90": 0.0382807805,
"chronological_thirds_event_lower_90": [0.3388899636, 0.2711632708, 0.2004748563] "chronological_thirds_event_lower_90": [0.2464004239, 0.1620997356, 0.1521274303]
}, },
"5_day": { "disjoint_holdout": {
"events": 105, "events": 65,
"event_mean_return": 0.3686092965, "event_mean_return": 0.3545949134,
"event_lower_90": 0.2938832777, "event_lower_90": 0.1660920142,
"train_events": 77, "train_events": 49,
"train_event_lower_90": 0.2686815198, "train_event_lower_90": 0.1409018264,
"holdout_events": 30, "holdout_events": 16,
"holdout_event_lower_90": 0.3000837037, "holdout_event_lower_90": -0.047341047,
"chronological_thirds_event_lower_90": [0.2828281426, 0.1431972556, 0.3007470066] "chronological_thirds_event_lower_90": [0.2174015607, -0.352501396, -0.0402576867],
}, "passed_strict_gate": false
"6_day": {
"events": 87,
"event_mean_return": 0.4393573265,
"event_lower_90": 0.3767305502,
"train_events": 60,
"train_event_lower_90": 0.3308720214,
"holdout_events": 29,
"holdout_event_lower_90": 0.4367621838,
"chronological_thirds_event_lower_90": [0.2863423727, 0.3447299413, 0.3561383759]
}
},
"rejected_windows": {
"2_day": "The chronological holdout lower 90% bound was negative.",
"7_day": "The exact safe non-Sports cohort had a negative middle-segment lower 90% bound.",
"8_day": "Not retained after the contiguous 3-6 day production window passed more strongly.",
"9_day": "Not retained after the contiguous 3-6 day production window passed more strongly.",
"10_day": "The exact safe non-Sports cohort had a negative middle-segment lower 90% bound.",
"adjacent_price_bands": "The 45-50% band lacked sufficient holdout evidence and the 55-60% band was unstable across shorter horizons."
}, },
"production_constraints": { "production_constraints": {
"capital_enabled": false,
"safe_contract_only": true, "safe_contract_only": true,
"sports_excluded": true, "sports_excluded": true,
"minimum_total_volume_usd": 15000, "minimum_total_volume_usd": 15000,
"minimum_live_liquidity_usd": 1400, "minimum_live_liquidity_usd": 1400,
"maximum_spread": 0.03, "maximum_spread": 0.03,
"entry": "executable NO ask plus 0.25 cents slippage", "modeled_entry": "executable NO ask plus 0.25 cents slippage",
"maximum_entry_friction_cents": 1, "maximum_entry_friction_cents": 1,
"resolution_windows_days": [[2.5, 3.5], [3.5, 4.5], [4.5, 5.5], [5.5, 6.5]], "observation_window_days": [3.5, 4.5],
"initial_position_pct": 0.5, "one_observation_per_event": true,
"total_cap_pct": 3, "promotion_events": 40,
"one_owner_per_event": true, "promotion_lower_90_minimum": 0.01,
"promoted_position_pct": 0.5,
"promoted_total_cap_pct": 3,
"exit": "verified market settlement only" "exit": "verified market settlement only"
}, },
"finding": "The prior 3-6 day capital permission was invalid because it averaged multiple correlated contracts inside an event. After selecting one decision per event, only the four-day safe rule survived the recent discovery sample, and it failed the strict all-segment gate in a disjoint older sample. Production therefore records zero-capital forward outcomes only.",
"limitations": [ "limitations": [
"Final volume is used to select one contract per event and was not known at the historical decision time.",
"The resolved archive cannot reconstruct contemporaneous historical liquidity or order-book depth.", "The resolved archive cannot reconstruct contemporaneous historical liquidity or order-book depth.",
"Recent closed-market selection can reflect a temporary question-construction regime.", "Published midpoint history is not a fill guarantee.",
"Published midpoint history is not a fill guarantee; production therefore applies current executable pricing and liquidity gates.", "Forward promotion would authorize bounded paper trading only and would not guarantee profit."
"This audit authorizes only bounded paper trading and does not guarantee future profit."
], ],
"reproduce": "SETTLEMENT_MARKETS=3000 SETTLEMENT_HORIZONS=3,4,5,6,7,8,9,10 SETTLEMENT_COST_CENTS=1 SETTLEMENT_ORDER=closedTime SETTLEMENT_ASCENDING=false SETTLEMENT_TARGET_ONLY=1 SETTLEMENT_TARGET_RULES=buy_no_50_55_safe_non_sports node scripts/evaluate-settlements.mjs" "reproduce_discovery": "SETTLEMENT_MARKETS=3000 SETTLEMENT_HORIZONS=1,2,3,4,5,6,7,8,9,10,14,21,30 SETTLEMENT_COST_CENTS=1 SETTLEMENT_ORDER=closedTime SETTLEMENT_ASCENDING=false SETTLEMENT_FINE_GRID=true SETTLEMENT_SURVIVORS_ONLY=1 node scripts/evaluate-settlements.mjs",
"reproduce_disjoint_holdout": "SETTLEMENT_MARKETS=3000 SETTLEMENT_SKIP=3000 SETTLEMENT_HORIZONS=4,5 SETTLEMENT_COST_CENTS=1 SETTLEMENT_ORDER=closedTime SETTLEMENT_ASCENDING=false SETTLEMENT_TARGET_ONLY=1 SETTLEMENT_TARGET_RULES=buy_no_50_55,buy_no_50_55_safe_non_sports,buy_safe_no_50_55 node scripts/evaluate-settlements.mjs"
} }
+61 -13
View File
@@ -1,10 +1,12 @@
const GAMMA = "https://gamma-api.polymarket.com"; const GAMMA = "https://gamma-api.polymarket.com";
const CLOB = "https://clob.polymarket.com"; const CLOB = "https://clob.polymarket.com";
const MARKET_LIMIT = Math.max(20, Math.min(3000, Number(process.env.SETTLEMENT_MARKETS || 200))); const MARKET_LIMIT = Math.max(20, Math.min(3000, Number(process.env.SETTLEMENT_MARKETS || 200)));
const MARKET_SKIP = Math.max(0, Math.min(10000, Number(process.env.SETTLEMENT_SKIP || 0)));
const CONCURRENCY = Math.max(1, Math.min(12, Number(process.env.SETTLEMENT_CONCURRENCY || 6))); const CONCURRENCY = Math.max(1, Math.min(12, Number(process.env.SETTLEMENT_CONCURRENCY || 6)));
const HORIZON_DAYS = [...new Set(String(process.env.SETTLEMENT_HORIZONS || "1,3,7,14,30,90").split(",") const HORIZON_DAYS = [...new Set(String(process.env.SETTLEMENT_HORIZONS || "1,3,7,14,30,90").split(",")
.map(Number).filter((value) => Number.isFinite(value) && value >= 1 && value <= 365))].sort((a, b) => a - b); .map(Number).filter((value) => Number.isFinite(value) && value >= 1 && value <= 365))].sort((a, b) => a - b);
const COST_CENTS = Math.max(0, Math.min(5, Number(process.env.SETTLEMENT_COST_CENTS || 0.5))); const COST_CENTS = Math.max(0, Math.min(5, Number(process.env.SETTLEMENT_COST_CENTS || 0.5)));
const FINE_GRID = String(process.env.SETTLEMENT_FINE_GRID || "false").toLowerCase() === "true";
const SELECTION_ORDER = ["volumeNum", "closedTime", "createdAt", "id"].includes(process.env.SETTLEMENT_ORDER) const SELECTION_ORDER = ["volumeNum", "closedTime", "createdAt", "id"].includes(process.env.SETTLEMENT_ORDER)
? process.env.SETTLEMENT_ORDER : "volumeNum"; ? process.env.SETTLEMENT_ORDER : "volumeNum";
const SELECTION_ASCENDING = String(process.env.SETTLEMENT_ASCENDING || "false").toLowerCase() === "true"; const SELECTION_ASCENDING = String(process.env.SETTLEMENT_ASCENDING || "false").toLowerCase() === "true";
@@ -100,10 +102,11 @@ function confirmedTrendAt(points, target, current) {
moderate: Math.abs(dayMove) <= 0.03 && Math.abs(weekMove) <= 0.10 }; moderate: Math.abs(dayMove) <= 0.03 && Math.abs(weekMove) <= 0.10 };
} }
async function fetchResolvedMarkets(limit) { async function fetchResolvedMarkets(limit, skip = 0) {
const raw = [], seen = new Set(), pageSize = 100; const raw = [], seen = new Set(), pageSize = 100;
const targetCount = limit + skip;
let cursor = ""; let cursor = "";
while (raw.length < limit) { while (raw.length < targetCount) {
const params = new URLSearchParams({ closed: "true", order: SELECTION_ORDER, ascending: String(SELECTION_ASCENDING), const params = new URLSearchParams({ closed: "true", order: SELECTION_ORDER, ascending: String(SELECTION_ASCENDING),
limit: String(pageSize) }); limit: String(pageSize) });
if (cursor) params.set("after_cursor", cursor); if (cursor) params.set("after_cursor", cursor);
@@ -120,12 +123,12 @@ async function fetchResolvedMarkets(limit) {
eventId: String(market.events?.[0]?.id || id), eventId: String(market.events?.[0]?.id || id),
tokenId: String(tokens[0]), finalYes: outcomes[0] >= 0.99 ? 1 : 0, closedAt, tokenId: String(tokens[0]), finalYes: outcomes[0] >= 0.99 ? 1 : 0, closedAt,
safeContract: !hardSettlementJumpRisk(market), volume: Number(market.volumeNum || market.volume || 0) }); safeContract: !hardSettlementJumpRisk(market), volume: Number(market.volumeNum || market.volume || 0) });
if (raw.length >= limit) break; if (raw.length >= targetCount) break;
} }
if (page.length < pageSize || !payload.next_cursor || payload.next_cursor === cursor) break; if (page.length < pageSize || !payload.next_cursor || payload.next_cursor === cursor) break;
cursor = payload.next_cursor; cursor = payload.next_cursor;
} }
return raw; return raw.slice(skip, skip + limit);
} }
function evaluateMarket(market, points) { function evaluateMarket(market, points) {
@@ -140,7 +143,7 @@ function evaluateMarket(market, points) {
const entry = side === "YES" ? yesEntry : noEntry, final = side === winningSide ? 1 : 0; const entry = side === "YES" ? yesEntry : noEntry, final = side === winningSide ? 1 : 0;
const netReturn = final / entry - 1 - (COST_CENTS / 100) / entry; const netReturn = final / entry - 1 - (COST_CENTS / 100) / entry;
rows.push({ marketId: market.id, eventId: market.eventId, question: market.question, category: market.category, rows.push({ marketId: market.id, eventId: market.eventId, question: market.question, category: market.category,
safeContract: market.safeContract, closedAt: market.closedAt, safeContract: market.safeContract, closedAt: market.closedAt, volume: market.volume,
horizonDays, side, favorite: side === favoriteSide, winner: side === winningSide, horizonDays, side, favorite: side === favoriteSide, winner: side === winningSide,
trend: Boolean(trend && trend.side === side), trendSide: trend?.side || null, trend: Boolean(trend && trend.side === side), trendSide: trend?.side || null,
dayMove: trend?.dayMove || 0, weekMove: trend?.weekMove || 0, dayMove: trend?.dayMove || 0, weekMove: trend?.weekMove || 0,
@@ -188,6 +191,26 @@ const SAFE_PRICE_BANDS = Object.freeze([
{ label: "95_97", min: 0.95, max: 0.97 }, { label: "95_97", min: 0.95, max: 0.97 },
]); ]);
const FINE_PRICE_BANDS = Object.freeze(Array.from({ length: 18 }, (_, index) => {
const min = 0.05 + index * 0.05, max = min + 0.05;
return { label: `${Math.round(min * 100)}_${Math.round(max * 100)}`, min, max };
}));
const FINE_CATEGORIES = Object.freeze(["Politics", "Crypto", "Economy", "Pop Culture", "Other"]);
const FINE_RULES = FINE_GRID ? FINE_PRICE_BANDS.flatMap((band) => [
{ name: `grid_safe_yes_${band.label}`, test: (row) => row.side === "YES" && row.entry >= band.min && row.entry < band.max
&& row.category !== "Sports" && row.safeContract },
{ name: `grid_safe_no_${band.label}`, test: (row) => row.side === "NO" && row.entry >= band.min && row.entry < band.max
&& row.category !== "Sports" && row.safeContract },
{ name: `grid_safe_favorite_${band.label}`, test: (row) => row.favorite && row.entry >= band.min && row.entry < band.max
&& row.category !== "Sports" && row.safeContract },
...FINE_CATEGORIES.flatMap((category) => [
{ name: `grid_safe_yes_${band.label}_${category.toLowerCase().replace(/\s+/g, "_")}`,
test: (row) => row.side === "YES" && row.entry >= band.min && row.entry < band.max && row.category === category && row.safeContract },
{ name: `grid_safe_no_${band.label}_${category.toLowerCase().replace(/\s+/g, "_")}`,
test: (row) => row.side === "NO" && row.entry >= band.min && row.entry < band.max && row.category === category && row.safeContract },
]),
]) : [];
const RULES = [ const RULES = [
{ name: "buy_favorite", test: (row) => row.favorite }, { name: "buy_favorite", test: (row) => row.favorite },
{ name: "buy_heavy_favorite", test: (row) => row.favorite && row.entry >= 0.78 }, { name: "buy_heavy_favorite", test: (row) => row.favorite && row.entry >= 0.78 },
@@ -228,10 +251,24 @@ const RULES = [
test: (row) => row.side === "NO" && row.entry >= 0.50 && row.entry < 0.55 && row.category === category }, test: (row) => row.side === "NO" && row.entry >= 0.50 && row.entry < 0.55 && row.category === category },
{ name: `follow_trend_${category.toLowerCase().replace(/\s+/g, "_")}`, test: (row) => row.trend && row.category === category }, { name: `follow_trend_${category.toLowerCase().replace(/\s+/g, "_")}`, test: (row) => row.trend && row.category === category },
]), ]),
...FINE_RULES,
]; ];
function selectEventDecisions(rows, rule) {
const selected = new Map();
for (const row of rows) {
if (!rule.test(row)) continue;
const current = selected.get(row.eventId);
if (!current || row.volume > current.volume
|| (row.volume === current.volume && row.marketId.localeCompare(current.marketId) < 0)) {
selected.set(row.eventId, row);
}
}
return [...selected.values()];
}
function evaluateRules(rows) { function evaluateRules(rows) {
return Object.fromEntries(RULES.map((rule) => [rule.name, summarize(rows.filter(rule.test))])); return Object.fromEntries(RULES.map((rule) => [rule.name, summarize(selectEventDecisions(rows, rule))]));
} }
function chronologicalEvaluation(rows) { function chronologicalEvaluation(rows) {
@@ -250,16 +287,16 @@ function chronologicalEvaluation(rows) {
&& trainRules[rule.name].count >= 30 && trainRules[rule.name].events >= 10 && trainRules[rule.name].count >= 30 && trainRules[rule.name].events >= 10
&& testRules[rule.name].count >= 15 && testRules[rule.name].events >= 5; && testRules[rule.name].count >= 15 && testRules[rule.name].events >= 5;
const allPositive = enoughData && all.eventLower90 > 0 && trainRules[rule.name].eventLower90 > 0 const allPositive = enoughData && all.eventLower90 > 0 && trainRules[rule.name].eventLower90 > 0
&& testRules[rule.name].eventLower90 > 0 && segments.every((segment) => segment.mean > 0 && segment.eventMean > 0); && testRules[rule.name].eventLower90 > 0 && segments.every((segment) => segment.eventLower90 > 0);
const allNegative = enoughData && all.eventUpper90 < 0 && trainRules[rule.name].eventUpper90 < 0 const allNegative = enoughData && all.eventUpper90 < 0 && trainRules[rule.name].eventUpper90 < 0
&& testRules[rule.name].eventUpper90 < 0 && segments.every((segment) => segment.mean < 0 && segment.eventMean < 0); && testRules[rule.name].eventUpper90 < 0 && segments.every((segment) => segment.eventUpper90 < 0);
return [rule.name, { enoughData, allPositive, allNegative, pooled: all, train: trainRules[rule.name], test: testRules[rule.name], segments }]; return [rule.name, { enoughData, allPositive, allNegative, pooled: all, train: trainRules[rule.name], test: testRules[rule.name], segments }];
})); }));
return { splitTime: splitTime ? new Date(splitTime * 1000).toISOString() : null, trainCount: train.length, return { splitTime: splitTime ? new Date(splitTime * 1000).toISOString() : null, trainCount: train.length,
testCount: test.length, train: trainRules, test: testRules, thirds: thirdRules, robustRules }; testCount: test.length, train: trainRules, test: testRules, thirds: thirdRules, robustRules };
} }
const markets = await fetchResolvedMarkets(MARKET_LIMIT); const markets = await fetchResolvedMarkets(MARKET_LIMIT, MARKET_SKIP);
const histories = await mapLimit(markets, CONCURRENCY, async (market) => { const histories = await mapLimit(markets, CONCURRENCY, async (market) => {
const data = await fetchJson(`${CLOB}/prices-history?market=${encodeURIComponent(market.tokenId)}&interval=max&fidelity=1440`); const data = await fetchJson(`${CLOB}/prices-history?market=${encodeURIComponent(market.tokenId)}&interval=max&fidelity=1440`);
const points = (data.history || []).map((point) => ({ t: Number(point.t), p: Number(point.p) })) const points = (data.history || []).map((point) => ({ t: Number(point.t), p: Number(point.p) }))
@@ -273,9 +310,12 @@ const report = {
marketsWithHistory: successful.length, failures: histories.filter((result) => result?.error).length, marketsWithHistory: successful.length, failures: histories.filter((result) => result?.error).length,
methodology: { horizonDays: HORIZON_DAYS, estimatedRoundTripCostCents: COST_CENTS, methodology: { horizonDays: HORIZON_DAYS, estimatedRoundTripCostCents: COST_CENTS,
historyFidelityMinutes: 1440, historyFidelityMinutes: 1440,
fineGrid:FINE_GRID,
testedRules:RULES.length,
marketSelection: `${SELECTION_ORDER} ${SELECTION_ASCENDING ? "ascending" : "descending"}`, marketSelection: `${SELECTION_ORDER} ${SELECTION_ASCENDING ? "ascending" : "descending"}`,
clusterUnit: "event", marketSelectionOffset: MARKET_SKIP,
note: "Each rule uses only daily prices available at or before the decision horizon and a subsequently published binary settlement. Trend replays require aligned one-day and one-week direction under the production move bounds. Confidence bounds cluster related markets by event. Markets are selected by resolved volume, so results still carry historical-selection and execution-model limitations." }, clusterUnit: "one highest-volume eligible contract per event and rule",
note: "Each rule uses only daily prices available at or before the decision horizon and a subsequently published binary settlement. Trend replays require aligned one-day and one-week direction under the production move bounds. Each rule makes at most one capital decision per event, choosing the highest-volume eligible contract with a stable market-ID tie-breaker. Strict robust rules require positive or negative event-level 90% bounds in pooled data, chronological train, chronological holdout, and every chronological third. Markets are selected by resolved volume, so results still carry historical-selection and execution-model limitations." },
horizons: Object.fromEntries(HORIZON_DAYS.map((horizon) => { horizons: Object.fromEntries(HORIZON_DAYS.map((horizon) => {
const horizonRows = rows.filter((row) => row.horizonDays === horizon); const horizonRows = rows.filter((row) => row.horizonDays === horizon);
return [horizon, { observations: horizonRows.length / 2, chronological: chronologicalEvaluation(horizonRows) }]; return [horizon, { observations: horizonRows.length / 2, chronological: chronologicalEvaluation(horizonRows) }];
@@ -288,7 +328,8 @@ const compactStats = (stats = {}) => ({ count: stats.count || 0, events: stats.e
const compactRules = (rules = {}) => Object.fromEntries(Object.entries(rules) const compactRules = (rules = {}) => Object.fromEntries(Object.entries(rules)
.filter(([, result]) => result.enoughData && (result.allPositive || result.allNegative)) .filter(([, result]) => result.enoughData && (result.allPositive || result.allNegative))
.map(([name, result]) => [name, { direction: result.allPositive ? "positive" : "negative", .map(([name, result]) => [name, { direction: result.allPositive ? "positive" : "negative",
pooled: compactStats(result.pooled), train: compactStats(result.train), test: compactStats(result.test) }])); pooled: compactStats(result.pooled), train: compactStats(result.train), test: compactStats(result.test),
segments: (result.segments || []).map(compactStats) }]));
const TARGET_RULE_NAMES = String(process.env.SETTLEMENT_TARGET_RULES || "buy_no_favorite,buy_no_50_55,buy_no_55_90,buy_no_60_90,buy_no_90_95,buy_no_95_99,buy_no_90_99") const TARGET_RULE_NAMES = String(process.env.SETTLEMENT_TARGET_RULES || "buy_no_favorite,buy_no_50_55,buy_no_55_90,buy_no_60_90,buy_no_90_95,buy_no_95_99,buy_no_90_99")
.split(",").map((name) => name.trim()).filter(Boolean); .split(",").map((name) => name.trim()).filter(Boolean);
const targetRuleStats = (chronological, names = TARGET_RULE_NAMES) => Object.fromEntries(names.map((name) => { const targetRuleStats = (chronological, names = TARGET_RULE_NAMES) => Object.fromEntries(names.map((name) => {
@@ -320,4 +361,11 @@ const targetOnly = process.env.SETTLEMENT_TARGET_ONLY === "1";
const targetSummary = { generatedAt: summary.generatedAt, requestedMarkets: summary.requestedMarkets, const targetSummary = { generatedAt: summary.generatedAt, requestedMarkets: summary.requestedMarkets,
resolvedMarkets: summary.resolvedMarkets, marketsWithHistory: summary.marketsWithHistory, failures: summary.failures, resolvedMarkets: summary.resolvedMarkets, marketsWithHistory: summary.marketsWithHistory, failures: summary.failures,
horizons: Object.fromEntries(Object.entries(summary.horizons).map(([days, value]) => [days, { observations: value.observations, targetRules: value.targetRules }])) }; horizons: Object.fromEntries(Object.entries(summary.horizons).map(([days, value]) => [days, { observations: value.observations, targetRules: value.targetRules }])) };
console.log(JSON.stringify(targetOnly ? targetSummary : (compact ? summary : report), null, 2)); const survivorsOnly = process.env.SETTLEMENT_SURVIVORS_ONLY === "1";
const survivorsSummary = { generatedAt: report.generatedAt, requestedMarkets: report.requestedMarkets,
resolvedMarkets: report.resolvedMarkets, marketsWithHistory: report.marketsWithHistory, failures: report.failures,
methodology: report.methodology,
horizons: Object.fromEntries(Object.entries(summary.horizons).map(([days, value]) => [days, {
observations: value.observations, robustRules: value.robustRules,
}])) };
console.log(JSON.stringify(survivorsOnly ? survivorsSummary : (targetOnly ? targetSummary : (compact ? summary : report)), null, 2));
+1 -1
View File
@@ -128,7 +128,7 @@ async function main() {
const branch = process.env.RUNTIME_BRANCH || "runtime-state"; const branch = process.env.RUNTIME_BRANCH || "runtime-state";
const pathname = process.env.RUNTIME_STATE_PATH || "runtime/state.json"; const pathname = process.env.RUNTIME_STATE_PATH || "runtime/state.json";
const arenaUrl = (process.env.ARENA_URL || "https://polymarket-site-eta.vercel.app").replace(/\/$/, ""); const arenaUrl = (process.env.ARENA_URL || "https://polymarket-site-eta.vercel.app").replace(/\/$/, "");
const expectedBuild = Number(required("EXPECTED_BUILD", "99")); const expectedBuild = Number(required("EXPECTED_BUILD", "100"));
await ensureRuntimeBranch(repository, branch); await ensureRuntimeBranch(repository, branch);
const prior = await readRuntimeFile(repository, branch, pathname); const prior = await readRuntimeFile(repository, branch, pathname);
if (prior.snapshot) validateRuntimeSnapshot(prior.snapshot, 0, { allowIncomplete: true }); if (prior.snapshot) validateRuntimeSnapshot(prior.snapshot, 0, { allowIncomplete: true });
+9 -12
View File
@@ -9,7 +9,7 @@ const runner = fs.readFileSync(new URL("./run-autonomous-cycle.mjs", import.meta
const resolutionAudit = JSON.parse(fs.readFileSync(new URL("../research/resolution-week-no-audit.json", import.meta.url), "utf8")); const resolutionAudit = JSON.parse(fs.readFileSync(new URL("../research/resolution-week-no-audit.json", import.meta.url), "utf8"));
const build = Number(index.match(/const BUILD_VERSION = (\d+);/)?.[1]); const build = Number(index.match(/const BUILD_VERSION = (\d+);/)?.[1]);
assert.equal(build, 99); assert.equal(build, 100);
assert.deepEqual([...ALLOWED_RUNTIME_KEYS].sort(), ["pma_agents_v2", "pma_suggestions_v5"]); assert.deepEqual([...ALLOWED_RUNTIME_KEYS].sort(), ["pma_agents_v2", "pma_suggestions_v5"]);
assert.match(index, /function collectPublicRuntimeItems\(\)/); assert.match(index, /function collectPublicRuntimeItems\(\)/);
assert.match(index, /const PUBLIC_RUNTIME_KEYS=Object\.freeze\(\[AGENTS_KEY,SUG_KEY\]\)/); assert.match(index, /const PUBLIC_RUNTIME_KEYS=Object\.freeze\(\[AGENTS_KEY,SUG_KEY\]\)/);
@@ -26,21 +26,18 @@ assert.match(api, /Buffer\.from\(file\.content/);
assert.match(api, /searchParams\.set\("runtime", `\$\{Date\.now\(\)\}/); assert.match(api, /searchParams\.set\("runtime", `\$\{Date\.now\(\)\}/);
assert.match(workflow, /cron: "2,7,12,17,22,27,32,37,42,47,52,57 \* \* \* \*"/); assert.match(workflow, /cron: "2,7,12,17,22,27,32,37,42,47,52,57 \* \* \* \*"/);
assert.match(workflow, /contents: write/); assert.match(workflow, /contents: write/);
assert.match(workflow, /EXPECTED_BUILD: "99"/); assert.match(workflow, /EXPECTED_BUILD: "100"/);
assert.match(index, /saveSuggestions\(sugs,markets\.length,analysisMarkets\.length,bundleAudit\)/); assert.match(index, /saveSuggestions\(sugs,markets\.length,analysisMarkets\.length,bundleAudit\)/);
assert.match(index, /const NEG_RISK_EVENT_SCAN_LIMIT=1000;/); assert.match(index, /const NEG_RISK_EVENT_SCAN_LIMIT=1000;/);
assert.match(index, /bundleOpportunityTelemetry:true/); assert.match(index, /bundleOpportunityTelemetry:true/);
assert.match(runner, /MAX_STATE_BYTES = 900_000/); assert.match(runner, /MAX_STATE_BYTES = 900_000/);
assert.equal(resolutionAudit.strategy, "resolution-window-no-50-55-safe-non-sports-v2"); assert.equal(resolutionAudit.strategy, "resolution-window-no-50-55-forward-shadow-v3");
assert.deepEqual(resolutionAudit.selection.horizon_days_enabled, [3, 4, 5, 6]); assert.deepEqual(resolutionAudit.selection.horizon_days_enabled, []);
for (const days of resolutionAudit.selection.horizon_days_enabled) { assert.deepEqual(resolutionAudit.selection.horizon_days_observed, [4]);
const rule = resolutionAudit.rules[`${days}_day`]; assert.equal(resolutionAudit.disjoint_holdout.passed_strict_gate, false);
assert.ok(rule.train_event_lower_90 > 0); assert.ok(resolutionAudit.disjoint_holdout.holdout_event_lower_90 < 0);
assert.ok(rule.holdout_event_lower_90 > 0); assert.equal(resolutionAudit.production_constraints.capital_enabled, false);
assert.ok(rule.chronological_thirds_event_lower_90.every((value) => value > 0)); assert.equal(resolutionAudit.production_constraints.promotion_events, 40);
}
assert.match(resolutionAudit.rejected_windows["2_day"], /holdout/i);
assert.match(resolutionAudit.rejected_windows["7_day"], /negative/i);
const agentIds = ["value", "momentum", "favorite", "longshot", "diversifier", "catalyst", "reversal", "breakout", "tailalpha", "conviction"]; const agentIds = ["value", "momentum", "favorite", "longshot", "diversifier", "catalyst", "reversal", "breakout", "tailalpha", "conviction"];
const agents = Object.fromEntries(agentIds.map(id => [id, { cash: 10000, positions: [], lastDecision: { mode: "test" } }])); const agents = Object.fromEntries(agentIds.map(id => [id, { cash: 10000, positions: [], lastDecision: { mode: "test" } }]));
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE_NAME = "polymarket-arena-build-99"; const CACHE_NAME = "polymarket-arena-build-100";
const APP_SHELL = ["/", "/index.html", "/personal.html", "/cycle-worker.js"]; const APP_SHELL = ["/", "/index.html", "/personal.html", "/cycle-worker.js"];
self.addEventListener("install", event => { self.addEventListener("install", event => {