import pathlib,json,re,subprocess,hashlib
root=pathlib.Path('/tmp/lead-32342-r1/evidence-capture');decoder=json.JSONDecoder()
def section(text,name):
 offset=text.index(name+'\n')+len(name)+1
 return decoder.raw_decode(text[offset:])[0]
summary={}
for side in ['before','after','before-control','after-control']:
 run=pathlib.Path((root/(side+'-run.txt')).read_text());transcript=run/(side+'-transcript.txt');text=transcript.read_text();meta=json.loads((run/'private.json').read_text());raw=(run/'server.raw.log').read_text()
 warnings=[line for line in raw.splitlines() if 'WARN' in line and 'Threads without a project are off because' in line]
 row=dict(sha=meta['sha'],configCalls=3,ensureCalls=3,finalScratchWarningCount=len(warnings),scratchDirectoryExists=(pathlib.Path(meta['home'])/'scratch').is_dir(),config=section(text,'R1 config call 1')['summary'])
 if not side.endswith('control'):
  rpc=section(text,'R2 ensure call 1')['response']['exit']['cause'][0]['error'];mcp=section(text,'R3 decoded text content')[0]
  row.update(rpcTag=rpc['_tag'],rpcMessage=rpc['message'],mcpTag=mcp['_tag'],mcpCode=mcp['code'],mcpMessage=mcp['message'],mcpEqualsRpc=mcp['message']==rpc['message'])
  if warnings:row['warningEqualsRpc']=warnings[0].split('): ',1)[1]==rpc['message']
 else:
  row['ensureSucceeded']=all(section(text,'R2 ensure call '+str(n))['response']['exit']['_tag']=='Success' for n in [1,2,3])
  outside=subprocess.run(['git','-C',meta['home'],'rev-parse','--show-toplevel'],capture_output=True,text=True);row['outsideRepository']=outside.returncode!=0
 text+='\nFinal verification\n'+json.dumps(row,indent=2)+'\n'
 # Every generated auth token remains confined to private inputs and raw files.
 for secret in [meta['token']]:
  if secret in text:raise RuntimeError('Credential in transcript')
 if re.search(r'(?:gpt-[\w.-]+|claude-[\w.-]+|sk-[A-Za-z0-9]{10})',text,re.I):raise RuntimeError('Potential private model identifier or credential')
 transcript.write_text(text)
 summary[side]=row
(root/'verification-summary.json').write_text(json.dumps(summary,indent=2)+'\n')
print(json.dumps({k:{key:value for key,value in v.items() if key not in ['rpcMessage','mcpMessage']} for k,v in summary.items()},indent=2))
