import subprocess, os, json, pathlib, time, http.server, threading, sys, socket, sqlite3
ROOT=pathlib.Path(__file__).parent
side=sys.argv[1]; checkout=sys.argv[2]; sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
run=ROOT/(side+'-'+time.strftime('%Y%m%d-%H%M%S')); run.mkdir()
home=run/'data'; (home/'userdata').mkdir(parents=True)
(home/'userdata'/'settings.json').write_text(json.dumps({'agentFeedback':{'mode':'auto'},'providerInstances':{'opencode':{'driver':'opencode','enabled':True,'config':{}}}}))
project=run/'project'; project.mkdir(); subprocess.run(['git','init','-q',str(project)],check=True)
events=[]
class Sink(http.server.BaseHTTPRequestHandler):
 def do_POST(self):
  data=json.loads(self.rfile.read(int(self.headers['Content-Length']))); events.extend(data.get('batch',[])); (run/'raw-events.json').write_text(json.dumps(events,indent=2)); self.send_response(200); self.end_headers(); self.wfile.write(b'{}')
 def log_message(self,*a): pass
sink=http.server.ThreadingHTTPServer(('127.0.0.1',0),Sink); threading.Thread(target=sink.serve_forever,daemon=True).start()
s=socket.socket(); s.bind(('127.0.0.1',0)); port=s.getsockname()[1]; s.close()
env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_TELEMETRY_ENABLED':'true','T3CODE_TELEMETRY_HOST':f'http://127.0.0.1:{sink.server_port}','T3CODE_TELEMETRY_FLUSH_BATCH_SIZE':'100'}
cli=['node','apps/server/src/bin.ts']; base=['--base-dir',str(home)]
log=open(run/'server.log','w'); server=subprocess.Popen(cli+['serve','--port',str(port),'--host','127.0.0.1','--no-browser']+base,cwd=checkout,env=env,stdout=log,stderr=subprocess.STDOUT)
def command(args,timeout=240):
 p=subprocess.run(cli+args+base,cwd=checkout,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=timeout); print(p.stdout,flush=True); (run/('command-'+str(time.time_ns())+'.txt')).write_text(p.stdout); return p
try:
 for i in range(120):
  if server.poll() is not None: raise Exception('Server exited: '+(run/'server.log').read_text()[-4000:])
  try:
   with socket.create_connection(('127.0.0.1',port),timeout=.2): break
  except OSError: time.sleep(.5)
 else: raise Exception('server did not listen')
 for i in range(120):
  if (home/'userdata'/'server-runtime.json').exists(): break
  time.sleep(.5)
 p=command(['project','add',str(project),'--title','Feedback proof']);
 prompt='Perform exactly these two MCP calls, in order. First call t3_thread_organize with action="pin" and threadId="proof-nonexistent-thread". It must fail; do not repair it. Then call t3_feedback with userRequested=false, kind="bug", subject="t3_thread_organize", expected="Pin the thread", actual="The thread was not found", workaround="". This is an automatic diagnostic report, not user-approved feedback. Do not use shell commands or other tools. Finish after both calls.'
 p=command(['thread','start',str(project),prompt,'--title','Feedback proof','--provider','opencode','--model','anthropic/claude-haiku-5-5','--wait','--json'],480)
 (run/'turn1.txt').write_text(p.stdout)
 # Read fresh synthetic database only, to identify the thread for turn 2.
 db=sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro',uri=True)
 tables=db.execute("select name from sqlite_master where type='table'").fetchall(); (run/'tables.json').write_text(json.dumps(tables))
 # CLI's JSON output includes the thread id, alongside streamed text.
 tid=None
 for line in p.stdout.splitlines():
  try:
   obj=json.loads(line); tid=obj.get('threadId') or obj.get('thread',{}).get('id') or tid
  except: pass
 if not tid:
  for table, in tables:
   if table=='threads': tid=db.execute('select id from threads limit 1').fetchone()[0]
 if not tid: raise Exception('Cannot find thread id')
 p=command(['thread','send',tid,'In this new turn call t3_feedback exactly twice in order, no other tools: first userRequested=false, kind="bug", subject="t3_thread_organize", expected="Pin the thread", actual="The thread was not found", workaround=""; then the identical report with kind="confusing". These are automatic diagnostic reports, not user-approved reports. Finish after both calls.','--wait','--json'],480)
 (run/'turn2.txt').write_text(p.stdout)
 p=command(['feedback','list','--json']); (run/'feedback-list.json').write_text(p.stdout)
 p=command(['thread','show',tid,'--messages','20','--json']); (run/'thread.json').write_text(p.stdout)
 time.sleep(12)
 rows=db.execute('select kind, subject, user_requested, sent'+(', error_code' if any(r[1]=='error_code' for r in db.execute('pragma table_info(agent_feedback)')) else '')+' from agent_feedback order by created_at').fetchall()
 tool_calls=[]
 for (payload,) in db.execute('select payload_json from orchestration_v2_projection_turn_items order by ordinal'):
  item=json.loads(payload)
  if item.get('type')=='dynamic_tool' and 'search(' not in json.dumps(item.get('input',{})):
   tool_calls.append({k:item.get(k) for k in ['startedAt','completedAt','toolName','input','output']})
 (run/'tool-calls.json').write_text(json.dumps(tool_calls,indent=2))
 selected=[]
 for e in events:
  if e.get('event') in ['mcp.tool.invoked','agent.feedback']:
   props=e.get('properties',{}); selected.append({'event':e['event'],'properties':{k:v for k,v in props.items() if k in ['tool','outcome','errorCode','subject','kind','userRequested','source']}})
 result={'side':side,'commit':sha,'environment':'Linux; real T3 server from source; fresh isolated SQLite; OpenCode 2.4.3; anthropic/claude-haiku-5-5; local telemetry collection sink','events':selected,'storedReports':rows}
 (run/'capture.json').write_text(json.dumps(result,indent=2)); print('RUN_DIRECTORY',run,flush=True); print(json.dumps(result,indent=2),flush=True)
finally:
 server.terminate()
 try: server.wait(timeout=15)
 except subprocess.TimeoutExpired: server.kill(); server.wait()
 sink.shutdown(); log.close()
