"""Read the real Cursor SDK run/checkpoint for a T3 proof workspace.
Usage: python3 inspect-cursor.py WORKSPACE SIDE COMMIT
Only model parameters, token limits, status and the synthetic reply are printed.
SDK schema: ConversationState field 5 = token_details;
ConversationTokenDetails field 2 = max_tokens (uint32).
"""
import json, pathlib, sqlite3, subprocess, sys
workspace, side, commit = sys.argv[1:]
code = "const {createRequire}=require('node:module');const r=createRequire(process.argv[1]+'/packages/provider-cursor/package.json');console.log(r('@cursor/sdk').getDefaultSdkStateRoot(process.argv[1]));"
root = pathlib.Path(subprocess.check_output(['node','-e',code,workspace], text=True).strip())
def db(path): return sqlite3.connect('file:'+str(path)+'?mode=ro', uri=True)
def varint(data, pos):
    value=shift=0
    while True:
        byte=data[pos]; pos+=1; value|=(byte&127)<<shift
        if byte<128: return value,pos
        shift+=7

def fields(data):
    pos=0
    while pos<len(data):
        tag,pos=varint(data,pos); wire=tag&7
        if wire==0: value,pos=varint(data,pos)
        elif wire==2:
            length,pos=varint(data,pos);value=data[pos:pos+length];pos+=length
        elif wire in (1,5):
            length=8 if wire==1 else 4;value=data[pos:pos+length];pos+=length
        else: raise ValueError('Unsupported protobuf wire type')
        yield tag>>3,value

index=db(root/'index.db')
rows=index.execute("select model,model_params_json,status,result,latest_checkpoint_ref_json from runs where model='grok-4.7' order by created_at desc").fetchall()
model,params,status,reply,ref=rows[0]
blob_id=json.loads(ref)['blobId']
for store in root.glob('agents/*/store.db'):
    row=db(store).execute('select data from blobs where id=?',(blob_id,)).fetchone()
    if row:
        details=next(value for number,value in fields(row[0]) if number==5)
        maximum=next(value for number,value in fields(details) if number==2)
        break
else: raise RuntimeError('Checkpoint missing')
print(json.dumps({'side':side,'commit':commit,'surface':'real T3 web app / live Cursor SDK','model':model,'catalogDisplayedContext':500000,'persistedSdkRunParameters':json.loads(params) if params else [],'checkpointMaxTokens':maximum,'status':status,'reply':reply},indent=2))
