#!/usr/bin/env python3
"""Drive the same real-provider permission round trip on either app build.
Requires a paired browser, synthetic project, and PROOF_MODEL_LABEL set locally.
The model picker label is hidden only to redact private runtime metadata.
"""
import argparse, json, os, pathlib, subprocess, time
p=argparse.ArgumentParser();p.add_argument('--browser',required=True);p.add_argument('--session',required=True);p.add_argument('--out',required=True)
a=p.parse_args();out=pathlib.Path(a.out)/time.strftime('%Y%m%d-%H%M%S');out.mkdir(parents=True)
def b(*args):
 r=subprocess.run([a.browser,'--session',a.session,*args],text=True,capture_output=True)
 if r.returncode:raise RuntimeError(r.stdout+r.stderr)
 return r.stdout
def role(role,name,action='click',*args):return b('find','role',role,action,'--name',name,*args)
def js(s):return b('eval',s)
def mode(name):
 # Full access has no separate footer pill; its control is inside the picker.
 js(r'(()=>{const x=document.querySelector("[aria-label^=\"Permissions:\"]");if(x)x.click();else document.querySelector("[data-chat-provider-model-picker]").click()})()')
 snap=b('snapshot','-i')
 if 'menuitemradio' not in snap:
  b('click','[aria-label^="Permissions:"]')
 b('wait','[role=menuitemradio]')
 time.sleep(.7)
 b('find','role','menuitemradio','click','--name',name,'--exact')
 b('press','Escape')
 time.sleep(.7)
def send(text,n):
 b('fill','[contenteditable=true]',text)
 role('button','Submit message')
 b('wait','--fn',rf'document.querySelectorAll("[data-assistant-citation-source]").length >= {n} && !!document.querySelector("button[aria-label=\"Submit message\"]")')
 time.sleep(.7)
 return js(r'Array.from(document.querySelectorAll("[data-assistant-citation-source]")).map(x=>x.innerText)')
b('set','viewport','1280','900');b('set','media','light')
js(r'Array.from(document.querySelectorAll("style")).filter(s=>s.textContent.includes("visibility:hidden!important")).forEach(s=>s.remove())')
b('press','Escape')
role('button','New thread')
b('wait','--fn','Array.from(document.querySelectorAll("[role=option]")).some(x=>x.textContent.includes("Permission profile proof"))')
js(r'Array.from(document.querySelectorAll("[role=option]")).find(x=>x.textContent.includes("Permission profile proof")).click()')
# Use a locally supplied model label; never include it in published evidence.
b('wait','[data-chat-provider-model-picker]')
if os.environ['PROOF_MODEL_LABEL'].split(' ,')[0] not in b('get','attr','[data-chat-provider-model-picker]','aria-label'):
 b('click','[data-chat-provider-model-picker]')
 b('wait','[role=option]')
 role('option',os.environ['PROOF_MODEL_LABEL'])
 b('press','Escape')
js(r'(()=>{let s=document.createElement("style");s.textContent="[data-chat-provider-model-picker-label],[role=listbox],span.ms-auto.min-w-0.truncate.text-muted-foreground.text-xs{visibility:hidden!important}";document.head.append(s)})()')
# Close the details panel if present, so machine labels are outside captures.
js(r'(()=>{if(document.querySelector("[aria-label=\"Thread details\"]"))document.querySelector("button[aria-label=\"Toggle thread details panel\"]").click()})()')
mode('Auto')
b('record','start',str(out/'roundtrip.mp4'))
initial='Without tools or file access, inspect only your LATEST injected permission instructions. Do they explicitly deny reading `**/.env` and `**/.env*`? Do not infer from this question or earlier messages. Answer in three bullet points: Latest block: workspace or full access; `**/.env`: deny or absent; `**/.env*`: deny or absent. Do not print absolute paths.'
full='Full access checkpoint: without tools or file access, report only whether your LATEST injected permission block says full access. Do not print paths.'
final='Back in Auto. Without tools or file access, inspect ONLY the LATEST injected permission block, not earlier conversation content or the first Auto response. Does that latest block explicitly deny reading `**/.env` and `**/.env*`? Answer in three bullet points: Latest block: workspace or full access; `**/.env`: deny or absent; `**/.env*`: deny or absent. Do not print absolute paths.'
answers=[send(initial,1)];mode('Full access');answers.append(send(full,2));mode('Auto');answers.append(send(final,3))
js(r'document.activeElement?.blur()')
b('press','Escape')
# Hide only the insertion caret, which otherwise blinks in a completed capture.
js(r'(()=>{let s=document.createElement("style");s.textContent="*{caret-color:transparent!important}";document.head.append(s)})()')
# Capture after two identical frames 500 ms apart.
for i in range(10):
 b('screenshot',str(out/'stable-a.png'));time.sleep(.5);b('screenshot',str(out/'final.png'))
 if (out/'stable-a.png').read_bytes()==(out/'final.png').read_bytes():break
else:raise RuntimeError('Screenshot did not stabilize')
b('record','stop')
(out/'responses.json').write_text(json.dumps({'prompts':[initial,full,final],'responses':answers},indent=2))
print(out)
