"""Evidence-informed scenario priors for two distinct governance questions.
All probability weights and timeline scales below are explicit judgments.
No announcement-to-capability-trigger durations are used as observations.
Run: MPLCONFIGDIR=/tmp/ai-governance-mpl python3 generate_markets.py
"""
from pathlib import Path
from datetime import date
import calendar,csv,json,math
import numpy as np
from scipy.special import ndtr
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ROOT=Path(__file__).resolve().parent
ASOF=date(2026,9,15);PLEDGE=date(2026,9,12);N=160000
MONTHS=[date(y,m,calendar.monthrange(y,m)[1]) for y in [2026,2027] for m in range(1,13) if (y,m)>=(2026,9)]
YEARS=[date(y,12,31) for y in range(2027,2036)]

def evaluator(medians=(45,150),weights=(.55,.35,.10),ratio=1.5,ratio_sd=.4):
    rng=np.random.default_rng(917)
    # Shared scenario weights, uncertain central durations, lab-level role effect.
    w=rng.dirichlet(np.array(weights)*20,N)
    mu=rng.normal(np.log(medians),[.35,.5],(N,2))
    sd=np.array([.6,.8])
    delta=rng.normal(math.log(ratio),ratio_sd,N)
    def curve(sign):
        shift=sign*delta[:,None]/2
        f0=np.sum(w[:,:2]*ndtr((math.log((ASOF-PLEDGE).days)-mu-shift)/sd),axis=1)
        return np.array([np.mean(np.sum(w[:,:2]*ndtr((math.log((d-PLEDGE).days)-mu-shift)/sd),axis=1)-f0)/np.mean(1-f0) for d in MONTHS])
    return {'anthropic':curve(-1),'openai':curve(1),'common':curve(0)}

def deployment(weights=(.25,.5,.25)):
    rng=np.random.default_rng(918)
    w=rng.dirichlet(np.array(weights)*20,N)
    q=rng.beta([8,5,1],[2,5,9],(N,3))
    full=rng.beta([2.5,1.5,.5],[7.5,8.5,9.5],(N,3))
    # Annual implementation chances in each environment, conditional on adoption.
    annual=np.array([.2,.08,.02]);hazard=-np.log(1-annual)
    extra=rng.lognormal(math.log(.5),.6,(N,3))
    high=[];all_internal=[]
    for d in YEARS:
        t=(d-ASOF).days/365.25
        high.append(float(np.mean(np.sum(w*q*(1-np.exp(-hazard*t)),axis=1))))
        all_internal.append(float(np.mean(np.sum(w*q*full*(1-np.exp(-hazard*np.maximum(t-extra,0))),axis=1))))
    return np.array(all_internal),np.array(high)

labs=evaluator();ap,hp=deployment()
es={name:evaluator(medians=med,weights=w) for name,med,w in [
 ('Central',(45,150),(.55,.35,.1)),
 ('More difficult negotiations',(75,240),(.35,.45,.2)),
 ('More preparation already done',(30,90),(.7,.25,.05))]}
ls={name:deployment(weights=w) for name,w in [('Central',(.25,.5,.25)),('Less pressure',(.1,.4,.5)),('More pressure',(.4,.5,.1))]}
assert np.all(ap<=hp)
ECRITERIA='''<p>For each laboratory and date, will there be clear public evidence that the laboratory has put its September 2026 commitment to independent embedded evaluators into substantive practice?</p><p>Resolve YES when a new or materially expanded, continuing engagement is operating: independent evaluators have meaningful access to internal systems, staff and AI development or safety practices, and meaningful independence to assess and communicate their findings broadly in line with the laboratory’s commitment. The substance of the arrangement matters; there is no minimum number of days, requirement to publish the contract, or checklist of office equipment.</p><p>A future promise, an ordinary external model evaluation or a prior bounded exercise alone does not count. Credible confirmation from the laboratory, evaluator, published findings or reliable reporting is sufficient; both parties need not issue announcements. Resolve NO for a date if qualifying public evidence has not appeared by its end, even if later evidence reveals an earlier private start. A qualifying engagement subsequently ending does not undo earlier YES outcomes.</p><p>The two categories are Anthropic and OpenAI. The reference commitments are <a href="https://darioamodei.com/post/we-must-pace-the-frontier">Dario Amodei’s September 2026 proposal</a> and <a href="https://x.com/sama/status/2098811563415150910">Sam Altman’s endorsement</a>. Narrow confidentiality or security redactions are compatible with the commitment; routine company control over unfavorable conclusions is not.</p>'''

LCRITERIA='''<p>By each date, will at least one major frontier AI laboratory have adopted and actually followed an external-first deployment rule?</p><p><strong>External before any internal deployment:</strong> a new frontier model is deployed to unaffiliated users before its first operational internal use.</p><p><strong>External before internal AI R&amp;D / high-risk deployment:</strong> a new frontier model is deployed to unaffiliated users before internal deployment for advancing AI capabilities or other uses posing comparably serious loss-of-control or catastrophic-misuse risks. Lower-risk internal use is permitted in this category.</p><p>External deployment means real use by outside users, including a controlled customer rollout. Outside safety evaluation, red-teaming, an announcement or access confined to company-controlled affiliates does not suffice. Internal deployment means operational use for the laboratory’s work. Ordinary training, alignment work and bounded development or safety testing are not themselves deployment; using a model operationally to develop more capable AI is.</p><p>There must be clear public evidence of a deliberate rule or established practice, followed for at least one rollout of one of the laboratory’s leading general-purpose models. An incidental sequence, an obsolete-model release or a pledge without implementation does not count. No minimum external-use period or particular legal form is required. Subsequent internal deployment need not already have occurred if the rule is in force, external deployment has occurred and the relevant internal use has been withheld.</p><p>A major frontier lab means a developer widely recognized at the time as being among the leaders in general-purpose AI capabilities; examples today include OpenAI, Anthropic and Google DeepMind. Future entrants and successors can qualify. At least one lab is sufficient; industry-wide adoption is not required. Credible company or evaluator documentation, findings or reliable reporting can establish the event. Evidence must be public by the date’s end. Later abandonment does not reverse an earlier YES. The full restriction also satisfies the AI R&amp;D / high-risk category.</p>'''

def write_market(code,title,events,dates,curves,criteria,body,cadence):
    folder=ROOT/code;folder.mkdir(exist_ok=True)
    params={'scaleType':'linear','multidate':{'enabled':True,'events':events}}
    meta=dict(code=code,title=title,type='date',visibility='private',status='draft',budget=2000,decay_rate=.005,resolution_criteria=criteria,x_unit=cadence,end_date=dates[-1].isoformat()+'T23:59:59Z',cumulative='true',auto_extend='false',svelte_params=json.dumps(params),background_info_path='background_info.html')
    with (folder/'market.csv').open('w') as f:
        for k,v in meta.items():f.write(f'# market_{k}: {v}\n')
        f.write('\n');w=csv.writer(f,lineterminator='\n')
        w.writerow(['projection_group','threshold_decimal','threshold_date','initial_probability','label','end_date','decay_rate','status'])
        for event,curve in zip(events,curves):
            assert len(curve)==len(dates) and np.all(np.diff(curve)>=0) and min(curve)>=.005 and max(curve)<.995
            for d,prob in zip(dates,curve):
                ds=d.isoformat()+'T23:59:59Z'
                w.writerow([event['key'],'',ds,f'{prob:.6f}','By '+d.strftime('%b %Y' if cadence=='month' else '%Y'),ds,.005,'open'])
    (folder/'background_info.html').write_text(body)
    (folder/'preview.html').write_text('<!doctype html><meta charset="utf-8"><style>body{font:17px/1.55 system-ui;max-width:1100px;margin:40px auto;color:#20262d}table{border-collapse:collapse;font-size:14px}td,th{border:1px solid #bbb;padding:8px;text-align:left}img{max-width:100%}a{color:#075eb2}</style><h1>'+title+'</h1>'+criteria+'<h2>Starting probabilities</h2>'+body.replace('{{asset:'+code+'.png}}',code+'.png'))

EVIDENCE=[
 {'market':'embedded-evals','source':'Anthropic commitment','url':'https://darioamodei.com/post/we-must-pace-the-frontier','use':'Immediate intention to establish continuing employee-like access and independent reporting; supports preparation advantage.'},
 {'market':'embedded-evals','source':'OpenAI endorsement','url':'https://x.com/sama/status/2098811563415150910','use':'Same-day commitment; originator/follower distinction concerns preparation, not a long elapsed announcement lead.'},
 {'market':'embedded-evals','source':'METR at Anthropic','url':'https://metr.org/blog/2026-03-25-red-teaming-anthropic-agent-monitoring/','use':'Three-week internal exercise with system access and staff cooperation; evidence of operational feasibility. Onboarding duration unknown.'},
 {'market':'embedded-evals','source':'METR at OpenAI','url':'https://metr.org/blog/2026-08-26-openai-hugging-face-incident-investigation/','use':'Investigation began July 29 evening; report August 26. The 28-day interval includes investigation and publication; excluded from onboarding timing.'},
 {'market':'embedded-evals','source':'Delmas and Montes-Sancho (2010)','url':'https://www.ioes.ucla.edu/wp-content/uploads/2017/04/2010-Delmas-Montes-Sancho-Strategic-Management-Journal.pdf','use':'Direction of originator/preparation advantage. 62 early, 21 late, 49 nonparticipants; delayed entry differs from a same-day follower. No transferable duration coefficient.'},
 {'market':'embedded-evals','source':'Toffel (2006)','url':'https://www.hbs.edu/ris/Publication%20Files/07-023_1c3822d6-d853-47f6-be07-c10a97ee4218.pdf','use':'Early adopters showed stronger subsequent improvements; shorter follow-up for later adopters limits interpretation. Directional support only.'},
 {'market':'external-first','source':'OpenAI GPT-5.3-Codex','url':'https://openai.com/index/introducing-gpt-5-3-codex/','use':'Developer reports using early model versions in its development; evidence of benefits from early internal use.'},
 {'market':'external-first','source':'IAPS internal-use risk reporting','url':'https://www.iaps.ai/research/risk-reporting-for-developers-internal-ai-model-use','use':'Internal deployment creates a separate governance problem; motivates potential pressure for restrictions.'},
 {'market':'external-first','source':'Anthropic pacing proposal','url':'https://darioamodei.com/post/we-must-pace-the-frontier','use':'Discusses restricting internal use to improve AI; evidence of policy interest. This specific external-first rule still requires adoption.'},
]

e_body='''<p>The starting probabilities of this market were calculated from the work needed to turn the two companies’ commitments into an ongoing evaluator programme: choose a team, extend its access, agree reporting rights and begin work.</p>
<p>Both labs have already hosted evaluators inside their organisations. <a href="https://metr.org/blog/2026-03-25-red-teaming-anthropic-agent-monitoring/">METR’s Anthropic exercise</a> gave a researcher internal systems access and staff support for three weeks. <a href="https://metr.org/blog/2026-08-26-openai-hugging-face-incident-investigation/">Its OpenAI investigation</a> involved several visits, interviews and access to internal records. These relationships make an expansion of existing arrangements a plausible route.</p>
<p>The main uncertainty is how much work remains on staffing, access and the right to communicate findings. The estimates use three possibilities:</p>
<table><thead><tr><th>Route</th><th>Weight</th><th>Timing from the commitment</th></tr></thead><tbody><tr><td>Extend an existing relationship; most arrangements are ready</td><td>55%</td><td>Typically around six weeks</td></tr><tr><td>Substantial work on staffing, permissions or reporting terms</td><td>35%</td><td>Typically around five months, with a wide range</td></tr><tr><td>The commitment stalls or settles into an arrangement that falls short</td><td>10%</td><td>Remains unresolved</td></tr></tbody></table>
<p>These weights and times are judgments based on the work involved. Public accounts of earlier exercises give useful evidence about access and feasibility, but leave the time spent negotiating arrangements unclear. The model allows considerable variation around each timeline.</p>
<p>Anthropic receives a timing advantage because it developed the proposal and described concrete access and reporting arrangements. That suggests more preparation before the announcement. OpenAI endorsed it the same day and can build on its own evaluator relationships.</p>
<p>A <a href="https://www.ioes.ucla.edu/wp-content/uploads/2017/04/2010-Delmas-Montes-Sancho-Strategic-Management-Journal.pdf">study of voluntary environmental agreements</a> found more substantive follow-through among firms involved in establishing the programme than among later joiners. The gap between joining dates was much larger than here. It supports giving preparation some weight; the size of the adjustment remains a judgment.</p>
<p>The central assumption is that OpenAI takes about 1.5 times as long as Anthropic. The uncertainty around that assumption includes a meaningful chance that OpenAI moves faster. Their probability of eventual implementation is the same. The chart also shows how the estimates change with easier or harder negotiations.</p>
<p><img src="{{asset:embedded-evals.png}}" alt="Anthropic and OpenAI probabilities with easier and harder negotiation scenarios"></p>'''

l_body='''<p>The starting probabilities of this market were calculated by considering what would lead a frontier lab to adopt an external-first rule, and how quickly it could apply that rule to a model release.</p>
<p>Labs gain useful research and engineering work from early internal access. OpenAI describes using early versions of <a href="https://openai.com/index/introducing-gpt-5-3-codex/">GPT-5.3-Codex in the model’s own development</a>. Giving up that advantage would be a substantial change in practice.</p>
<p>Pressure for a change could come from internal incidents, independent evaluators, regulation or a lab choosing to demonstrate a stricter safety approach. <a href="https://www.iaps.ai/research/risk-reporting-for-developers-internal-ai-model-use">IAPS’s work on internal-use risk reporting</a> sets out why internal deployment deserves separate scrutiny. <a href="https://darioamodei.com/post/we-must-pace-the-frontier">Anthropic’s pacing proposal</a> also discusses restrictions on internal use of AI to improve AI.</p>
<p>The forecast weighs three possible environments. Each row applies to adoption by at least one frontier lab:</p>
<table><thead><tr><th>Environment</th><th>Weight</th><th>Chance a lab eventually adopts the AI R&amp;D/high-risk rule</th><th>Yearly chance of putting it into practice, if adoption will happen</th></tr></thead><tbody><tr><td>Strong pressure and a workable external-first proposal</td><td>25%</td><td>80%</td><td>20%</td></tr><tr><td>Sustained concern, with competing approaches to internal safety</td><td>50%</td><td>50%</td><td>8%</td></tr><tr><td>Commercial and research incentives continue to dominate</td><td>25%</td><td>10%</td><td>2%</td></tr></tbody></table>
<p>These are explicit assumptions about a new policy. They put the most weight on a mixed outcome: internal-use safeguards improve, while the external-first rule attracts limited support. The yearly chances combine the time needed to agree a rule and apply it to a suitable release.</p>
<p>A ban on all operational internal use would also cover ordinary employee work. It would have a broader cost and a weaker connection to the highest risks. In the three environments above, the model gives a 25%, 15% and 5% chance respectively that adoption extends to this stronger rule. It allows roughly another six months to implement it. Whenever the stronger rule qualifies, the AI R&amp;D/high-risk category qualifies too.</p>
<p>The sensitivity curves put more or less weight on strong pressure. They show how much depends on the policy environment over the coming decade.</p>
<p><img src="{{asset:external-first.png}}" alt="External-first deployment estimates under different levels of pressure"></p>'''

plt.rcParams.update({'font.size':11,'axes.spines.top':False,'axes.spines.right':False})
for code in ['embedded-evals','external-first']:(ROOT/code).mkdir(exist_ok=True)
fig,ax=plt.subplots(figsize=(10,5.4))
for lab,color in [('anthropic','#c47757'),('openai','#278c75')]:
    ax.fill_between(MONTHS,es['More difficult negotiations'][lab]*100,es['More preparation already done'][lab]*100,color=color,alpha=.12)
    ax.plot(MONTHS,labs[lab]*100,color=color,label=lab.title(),lw=2.5)
ax.set(ylabel='Probability by date (%)',ylim=(0,100),title='Embedded evaluators')
ax.text(.02,.97,'Shading: harder / easier negotiation scenarios',transform=ax.transAxes,va='top',fontsize=10)
ax.legend(loc='lower right');ax.grid(alpha=.2);fig.autofmt_xdate();fig.tight_layout();fig.savefig(ROOT/'embedded-evals/embedded-evals.png',dpi=160);plt.close(fig)
fig,ax=plt.subplots(figsize=(10,5.4))
ax.fill_between(YEARS,ls['Less pressure'][1]*100,ls['More pressure'][1]*100,color='#237eb5',alpha=.12)
ax.plot(YEARS,hp*100,label='Before internal AI R&D / high-risk use',color='#237eb5',lw=2.5)
ax.plot(YEARS,ap*100,label='Before any operational internal use',color='#8558b9',lw=2.5)
ax.set(ylabel='Probability by date (%)',ylim=(0,60),title='External-first rule at at least one frontier lab',xlabel='By year end')
ax.text(.02,.97,'Shading: less / more pressure for adoption',transform=ax.transAxes,va='top',fontsize=10)
ax.set_xticks(YEARS,[str(d.year) for d in YEARS]);ax.legend(loc='upper left',bbox_to_anchor=(0,.90));ax.grid(alpha=.2);fig.autofmt_xdate();fig.tight_layout();fig.savefig(ROOT/'external-first/external-first.png',dpi=160);plt.close(fig)
write_market('embedded-evals','Independent embedded evaluators at frontier AI labs',[{'key':'anthropic','label':'Anthropic','color':'#c47757'},{'key':'openai','label':'OpenAI','color':'#278c75'}],MONTHS,[labs['anthropic'],labs['openai']],ECRITERIA,e_body,'month')
write_market('external-first','External deployment before internal deployment at a frontier AI lab',[{'key':'any_internal','label':'Before any internal deployment','color':'#8558b9'},{'key':'high_risk','label':'Before internal AI R&D / high-risk deployment','color':'#237eb5'}],YEARS,[ap,hp],LCRITERIA,l_body,'year')
summary={'revision':'03-corrected-reference-class','as_of':str(ASOF),'draws':N,'interpretation':'Evidence-informed judgment priors; no fitted historical implementation rates.',
 'evaluator_by_lab':{lab:{str(d):round(float(v),6) for d,v in zip(MONTHS,curve)} for lab,curve in labs.items()},
 'deployment':{str(d):{'any_internal':round(float(a),6),'high_risk':round(float(h),6)} for d,a,h in zip(YEARS,ap,hp)},
 'evaluator_sensitivity':{name:{lab:curve.tolist() for lab,curve in curves.items()} for name,curves in es.items()},
 'deployment_sensitivity':{name:{'any_internal':a.tolist(),'high_risk':h.tolist()} for name,(a,h) in ls.items()},
 'technical_parameters':{'evaluator_seed':917,'scenario_weights':[.55,.35,.1],'scenario_weight_concentration':20,'duration_medians_days':[45,150],'uncertainty_in_log_medians':[.35,.5],'within_scenario_log_sd':[.6,.8],'originator_log_ratio_mean':math.log(1.5),'originator_log_ratio_sd':.4,'deployment_seed':918,'environment_weights':[.25,.5,.25],'adoption_beta_alpha':[8,5,1],'adoption_beta_beta':[2,5,9],'annual_implementation_probabilities':[.2,.08,.02],'stronger_rule_beta_alpha':[2.5,1.5,.5],'stronger_rule_beta_beta':[7.5,8.5,9.5],'extra_delay_median_years':.5,'extra_delay_log_sd':.6}}
(ROOT/'model_summary.json').write_text(json.dumps(summary,indent=2)+'\n')
(ROOT/'reference_cases.json').write_text(json.dumps(EVIDENCE,indent=2)+'\n')
print(json.dumps({'evaluator':{k:{d:v[d] for d in ['2026-12-31','2027-03-31','2027-12-31']} for k,v in summary['evaluator_by_lab'].items()},'deployment':summary['deployment']},indent=2))
