import os, sys, subprocess, pathlib, time, socket, json, signal, threading, datetime
root=pathlib.Path(__file__).parent
checkout=pathlib.Path(sys.argv[1]); side=sys.argv[2]; port=int(sys.argv[3])
run=root/(side+'-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S')); run.mkdir()
home=run/'home'; proj=run/'project'; proj.mkdir(); (home/'userdata').mkdir(parents=True)
subprocess.run(['git','init','-q',str(proj)],check=True)
(home/'userdata'/'settings.json').write_text(json.dumps({'providerInstances':{'opencode':{'driver':'opencode','enabled':True}}}))
env=dict(os.environ,T3CODE_DEV_SEED='0'); cwd=checkout/'apps/server'
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
start=time.monotonic(); events=[]; lock=threading.Lock()
def emit(s):
    with lock:
        line=f'[{time.monotonic()-start:6.1f}s] {s}'; events.append(line); print(line,flush=True)
        (run/'transcript.txt').write_text('\n'.join(events)+'\n')
def stat(pid):
    try:
        fields=pathlib.Path(f'/proc/{pid}/stat').read_text().split(); return fields[2],int(fields[3])
    except FileNotFoundError:return None

def children(pid):
    try:return [int(p) for p in pathlib.Path(f'/proc/{pid}/task/{pid}/children').read_text().split()]
    except FileNotFoundError:return []
def descendants(pid):
    out=[]
    for p in children(pid):out.append(p); out.extend(descendants(p))
    return out
server=None; tracked=[]; cli=None
try:
    emit(f'{side.upper()} | Linux | OpenCode v2.4.3 | Node '+subprocess.check_output(['node','--version'],text=True).strip())
    emit('Commit '+sha)
    emit('Fresh synthetic git project and fresh T3 database; OpenCode enabled.')
    raw=open(run/'server-private.log','wb')
    server=subprocess.Popen(['node','src/bin.ts','serve','--base-dir',str(home),'--port',str(port),'--host','127.0.0.1','--no-browser',str(proj)],cwd=cwd,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    eof=threading.Event(); ready=threading.Event()
    def reader():
        while b:=server.stdout.readline():raw.write(b); raw.flush(); ready.set() if b'T3 Code server is ready.' in b else None
        eof.set(); raw.close()
    threading.Thread(target=reader,daemon=True).start()
    for i in range(240):
        try:
            with socket.create_connection(('127.0.0.1',port),timeout=.2):break
        except OSError:
            if server.poll() is not None:raise RuntimeError('server exited')
            time.sleep(.25)
    else:raise RuntimeError('server startup timed out')
    if not ready.wait(60):raise RuntimeError('server readiness timed out')
    emit(f't3 serve ready on loopback; PID {server.pid}')
    p=subprocess.run(['node','src/bin.ts','project','add',str(proj),'--base-dir',str(home)],cwd=cwd,env=env,capture_output=True,text=True,timeout=60)
    emit(f't3 project add: exit {p.returncode}')
    if p.returncode:
        (run/'project-private.log').write_text(p.stdout+p.stderr)
        raise RuntimeError('project add failed; see private log')
    cliLog=open(run/'thread-private.log','wb')
    cli=subprocess.Popen(['node','src/bin.ts','thread','start',str(proj),'Reply with OK.','--base-dir',str(home),'--provider','opencode','--model','anthropic/claude-haiku-4-5','--wait'],cwd=cwd,env=env,stdout=cliLog,stderr=subprocess.STDOUT)
    emit('t3 thread start --provider opencode --model anthropic/claude-haiku-4-5 --wait')
    op=None
    for i in range(240):
        tracked=descendants(server.pid)
        for pid in tracked:
            try:cmd=pathlib.Path(f'/proc/{pid}/cmdline').read_bytes().replace(b'\0',b' ').decode()
            except FileNotFoundError:continue
            if 'opencode' in cmd and 'serve --hostname' in cmd:op=pid;break
        if op:break
        time.sleep(.25)
    if not op:raise RuntimeError('OpenCode serve was not started')
    launcher=stat(op)[1]
    emit(f'Process tree: t3 serve {server.pid} -> process launcher {launcher} -> opencode serve {op}')
    emit('OpenCode command: opencode serve --hostname=127.0.0.1 --port=<dynamic>')
    # Match triage: allow provider startup/failed model selection to settle.
    try:cli.wait(timeout=30)
    except subprocess.TimeoutExpired:pass
    emit(f'Thread CLI exit: {cli.poll()} (model response is not needed for process-lifecycle reproduction)')
    emit('ACTION: kill -KILL <captured t3 serve PID>')
    os.kill(server.pid,signal.SIGKILL); server.wait(); killed=time.monotonic()
    def snapshot(label):
        emit(label)
        for role,pid in [('t3 serve',server.pid),('process launcher',launcher),('opencode serve',op)]:
            s=stat(pid)
            emit(f'  {role:16} PID {pid}: '+(f'RUNNING state={s[0]} PPID={s[1]}' if s and s[0]!='Z' else 'EXITED (zombie)' if s else 'EXITED (absent)'))
        emit('  inherited stdout/stderr pipe: '+('EOF / closed' if eof.is_set() else 'STILL OPEN'))
    for delay in [1,5,10,60]:
        time.sleep(max(0,killed+delay-time.monotonic()));snapshot(f'Observation: {delay} seconds after SIGKILL')
    alive=[pid for pid in [launcher,op] if (s:=stat(pid)) and s[0]!='Z']
    emit('RESULT: '+('BUG REPRODUCED: descendants survived and pipe remains open' if alive else 'FIX VERIFIED: descendants exited; pipe closed'))
    (run/'result.json').write_text(json.dumps({'sha':sha,'alive':alive,'pipeClosed':eof.is_set(),'events':events}))
finally:
    if cli and cli.poll() is None:cli.terminate();cli.wait(timeout=10)
    if server and server.poll() is None:
        tracked=descendants(server.pid); server.kill();server.wait()
    for pid in reversed(tracked):
        try:os.kill(pid,signal.SIGKILL)
        except ProcessLookupError:pass
    emit('Cleanup: stopped only captured reproduction processes.')
print('RUN_DIRECTORY='+str(run),flush=True)
