import argparse, subprocess, json, urllib.request, pathlib, sqlite3, datetime
p=argparse.ArgumentParser(); p.add_argument('--checkout',required=True); p.add_argument('--home',required=True); p.add_argument('--origin',required=True); p.add_argument('--out',required=True); a=p.parse_args()
out=pathlib.Path(a.out)/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'); out.mkdir(parents=True)
owner=subprocess.check_output(['vp','exec','node','apps/server/src/bin.ts','auth','session','issue','--token-only','--base-dir',a.home],cwd=a.checkout,text=True).strip()
def post(path,payload,bearer=None,form=False):
    import urllib.parse
    data=(urllib.parse.urlencode(payload) if form else json.dumps(payload)).encode()
    h={'Content-Type':'application/x-www-form-urlencoded' if form else 'application/json'}
    if bearer:h['Authorization']='Bearer '+bearer
    req=urllib.request.Request(a.origin+path,data=data,headers=h)
    with urllib.request.urlopen(req,timeout=60) as r:return json.load(r)
import secrets, hashlib, base64, urllib.parse
approval=post('/api/auth/pairing-token',{'access':'full-access','label':'Synthetic project proof'},owner)
redirect='http://localhost:51234/callback'
client=post('/oauth/mcp/register',{'client_name':'Project create proof','redirect_uris':[redirect],'token_endpoint_auth_method':'none'})
verifier=secrets.token_urlsafe(48)
challenge=base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
authorization={'response_type':'code','client_id':client['client_id'],'redirect_uri':redirect,'code_challenge':challenge,'code_challenge_method':'S256','state':'proof','resource':a.origin+'/mcp'}
decision=post('/oauth/mcp/decision',{'authorization':authorization,'decision':{'_tag':'pairing-code','access':'full-access','code':approval['credential']}})
code=urllib.parse.parse_qs(urllib.parse.urlparse(decision['redirectTo']).query)['code'][0]
token=post('/oauth/mcp/token',{'grant_type':'authorization_code','code':code,'redirect_uri':redirect,'client_id':client['client_id'],'code_verifier':verifier,'resource':a.origin+'/mcp'},form=True)['access_token']
headers={'Accept':'application/json, text/event-stream','Authorization':'Bearer '+token,'Content-Type':'application/json'}; n=0; transcript=[]
def redact(x):
    return json.loads(json.dumps(x).replace(a.home,'<isolated-data>').replace(a.checkout,'<checkout>'))
def send(method,params=None):
    global n
    n+=1; msg={'jsonrpc':'2.0','method':method}
    if not method.startswith('notifications/'):msg['id']=n
    if params is not None:msg['params']=params
    req=urllib.request.Request(a.origin+'/mcp',data=json.dumps(msg).encode(),headers=headers)
    with urllib.request.urlopen(req,timeout=60) as r:
        if r.headers.get('mcp-session-id'):headers['mcp-session-id']=r.headers['mcp-session-id']
        raw=r.read().decode()
    if not raw:return None
    if raw.startswith('event:') or raw.startswith('data:'):
        raw=next(line[5:].strip() for line in raw.splitlines() if line.startswith('data:'))
    return json.loads(raw)
def call(name,args):
    r=send('tools/call',{'name':name,'arguments':args});transcript.append({'tool':name,'arguments':redact(args),'response':redact(r)})
    print(name,json.dumps(redact(r)),flush=True)
    result=r.get('result',{})
    if 'structuredContent' in result: return result['structuredContent']
    for c in result.get('content',[]):
        if c.get('type')=='text':
            try:return json.loads(c['text'])
            except ValueError:pass
    return result
send('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'project-create-proof','version':'1'}});send('notifications/initialized')
script=lambda id:{'id':id,'name':'Lint','command':'echo lint','icon':'configure','runOnWorktreeCreate':False}
projects=call('t3_project_list',{})['projects']
legacy=next(p for p in projects if p['title']=='Repro Bad')
edited={**legacy['scripts'][0],'name':'Legacy lint edited','command':'echo edited'}
call('t3_project_update',{'projectId':legacy['id'],'scripts':[edited]})
call('t3_project_read',{'projectId':legacy['id']})
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=a.checkout,text=True).strip()
report={'commit':sha,'environment':'Head server restarted against synthetic database created by base server; no database edits','calls':transcript}
(out/'legacy-runtime.json').write_text(json.dumps(report,indent=2)+'\n'); print('REPORT',out/'legacy-runtime.json')
