import os, sys, time, subprocess, pathlib, socket, json, re
os.environ['DBUS_SESSION_BUS_ADDRESS']='unix:path='+os.environ['XDG_RUNTIME_DIR']+'/bus'
root=pathlib.Path(sys.argv[1]); side=sys.argv[2]; sha=sys.argv[3]; shim=sys.argv[4]
out=root/(side+'-'+time.strftime('%Y%m%d-%H%M%S')); out.mkdir()
events=[]; start=time.monotonic()
def emit(s):
    s=s.replace(str(root),'$EVIDENCE').replace(str(pathlib.Path.home()),'$HOME')
    s=re.sub(r'/tmp/\.mount_[^ /\n]+','<AppImage mount>',s)
    events.append({'time':round(time.monotonic()-start,3),'text':s})
    print(s,flush=True)
    (out/'transcript.txt').write_text('\n'.join(e['text'] for e in events)+'\n')
    (out/'events.json').write_text(json.dumps(events))
def run(args):
    p=subprocess.run(args,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    return p.returncode,p.stdout.strip()
def mounts():
    return set(l.split(' - ')[0].split()[4] for l in pathlib.Path('/proc/self/mountinfo').read_text().splitlines() if ' - fuse.' in l and '.mount_' in l)
emit(f'{side.upper()} | commit {sha}\nLinux x86_64 | systemd 255 | real packaged AppImage + FUSE\nFresh T3 homes; no projects, accounts, or model calls.')
outcomes=[]
for index,mode in enumerate(['control-group','mixed']):
    unit=f't3-proof-40624-{side}-{mode}-'+out.name[-6:]
    home=out/mode; home.mkdir()
    sock=socket.socket(); sock.bind(('127.0.0.1',0)); port=sock.getsockname()[1]; sock.close()
    prior=mounts()
    emit(f'\n$ systemd-run --user --unit={unit} -p TimeoutStopSec=30s -p KillMode={mode} t3 serve --host 127.0.0.1 --port {port} --no-browser --base-dir <fresh-home>')
    rc,msg=run(['systemd-run','--user','--unit='+unit,'-p','TimeoutStopSec=30s','-p','KillMode='+mode,shim,'serve','--host','127.0.0.1','--port',str(port),'--no-browser','--base-dir',str(home)])
    emit(msg)
    ready=False
    for i in range(120):
        try:
            with socket.create_connection(('127.0.0.1',port),timeout=.2): ready=True; break
        except OSError: time.sleep(.5)
    if ready:
        ready=False
        for i in range(120):
            _,journal=run(['journalctl','--user','-u',unit,'--no-pager','-o','cat'])
            if 'T3 Code server is ready.' in journal:
                ready=True; break
            time.sleep(.5)
        if ready: time.sleep(2)
    current=mounts()-prior
    emit(f'Readiness: {ready}; AppImage FUSE mounts created: {len(current)}')
    if not ready:
        rc,j=run(['journalctl','--user','-u',unit,'--no-pager','-o','cat']); emit(j)
        run(['systemctl','--user','stop',unit]); break
    emit(f'$ systemctl --user stop {unit}')
    stopstart=time.monotonic(); rc,msg=run(['systemctl','--user','stop',unit])
    emit(f'Stop returned in {time.monotonic()-stopstart:.2f}s; command exit={rc}')
    rc,result=run(['systemctl','--user','show',unit,'-p','Result','-p','ExecMainCode','-p','ExecMainStatus','-p','ActiveState','-p','SubState']); emit(result)
    rc,j=run(['journalctl','--user','-u',unit,'--no-pager','-o','cat'])
    shutdown=j[j.rfind('Stopping '+unit):] if 'Stopping '+unit in j else j
    selected=[l.split(' - $EVIDENCE')[0] for l in shutdown.replace(str(root),'$EVIDENCE').splitlines() if re.search(r'signal|SIG|BUS|core|timed out|timeout|[Ss]topp|[Dd]eactiv|[Ff]ail|[Kk]ill|[Ss]hut',l)]
    emit('Journal shutdown lines:\n'+'\n'.join(selected))
    # Preserve the complete journal locally; pairing URLs and paths are never published.
    (out/(mode+'-journal-private.txt')).write_text(j)
    leftover=current & mounts()
    emit(f'Remaining AppImage FUSE mounts: {len(leftover)}')
    outcomes.append(f'{mode}: stop {time.monotonic()-stopstart:.2f}s; '+result.replace('\n',', ')+f'; mounts={len(leftover)}')
    for mount in leftover: run(['fusermount3','-uz',mount])
    run(['systemctl','--user','reset-failed',unit])
emit('\nFINAL | '+side.upper()+' | '+sha+'\n'+'\n'.join(outcomes)+'\nCapture complete.')
time.sleep(5)
