#!/usr/bin/env python3
"""Real T3 server/CLI proof. Usage: proof-driver.py CHECKOUT OUTPUT_DIRECTORY SIDE
Requires opencode configured with anthropic/claude-haiku-5-5 and Node/vp dependencies.
Run once against each commit; no provider stubs or test runner are used.
"""
import sys,pathlib,subprocess,json,sqlite3,time,os,signal,shutil,socket
checkout=pathlib.Path(sys.argv[1]).resolve(); out=pathlib.Path(sys.argv[2]).resolve();side=sys.argv[3]
out.mkdir(parents=True);home=out/'server';fixture=home/'fixture';fixture.mkdir(parents=True)
start=time.monotonic();cast=(out/'terminal.cast').open('w');transcript=(out/'terminal.txt').open('w')
cast.write(json.dumps({'version':2,'width':132,'height':32,'timestamp':int(time.time()),'title':f'T3 Code branch resolution — {side}','env':{'TERM':'xterm-256color'}})+'\n')
def clean(s):
 return str(s).replace(str(out),'/proof').replace(str(checkout),'/workspace/'+side).replace(str(pathlib.Path.home()),'/home/proof')
def emit(s):
 s=clean(s)+'\n';print(s,end='',flush=True);transcript.write(s);transcript.flush();cast.write(json.dumps([round(time.monotonic()-start,3),'o',s.replace('\n','\r\n')])+'\n');cast.flush()
def run(a,cwd=None):
 p=subprocess.run(list(map(str,a)),cwd=cwd,capture_output=True,text=True)
 if p.returncode:raise RuntimeError(clean(p.stderr+p.stdout))
 return p.stdout.strip()
def git(cwd,*a):return run(['git','-C',cwd,*a])
cli=['node','apps/server/src/bin.ts']; env={**os.environ,'T3CODE_DEV_SEED':'0'}
server=None
try:
 emit('Real T3 server proof: '+side+' '+run(['git','rev-parse','HEAD'],checkout))
 source=fixture/'source';run(['git','init','-b','main',source]);git(source,'config','user.name','Proof');git(source,'config','user.email','proof@example.invalid');(source/'README.md').write_text('Synthetic branch proof.\n');git(source,'add','.');git(source,'commit','-m','Synthetic initial commit');git(source,'branch','remote-only');run(['git','clone','--bare',source,fixture/'origin.git'])
 for name in ['demo','probe','multi/one','multi/two']:
  run(['git','clone',fixture/'origin.git',fixture/name])
 git(fixture/'probe','checkout','--orphan','unborn')
 userdata=home/'userdata';userdata.mkdir();(userdata/'settings.json').write_text(json.dumps({'providerInstances':{'opencode':{'driver':'opencode','enabled':True,'config':{'enabled':True}}}}))
 emit('Seed: one commit on main; bare origin; origin/HEAD -> origin/main; remote-only exists only on origin.')
 emit('Seed: multi/ contains two repositories and is itself outside Git; probe/ is on unborn HEAD; source/ has no remotes.')
 log=(out/'server-private.log').open('w')
 sock=socket.socket();sock.bind(('127.0.0.1',0));port=str(sock.getsockname()[1]);sock.close()
 server=subprocess.Popen(cli+['serve','--base-dir',str(home),'--port',port,'--host','127.0.0.1','--no-browser'],cwd=checkout,env=env,stdout=log,stderr=subprocess.STDOUT)
 runtime=userdata/'server-runtime.json'
 # Startup readiness, not an assertion or test of the defect.
 for _ in range(120):
  if runtime.exists():
   try:
    if json.loads(runtime.read_text()).get('origin'):break
   except Exception:pass
  if server.poll() is not None:raise RuntimeError('Server exited before readiness')
  time.sleep(.25)
 else:raise RuntimeError('Server startup timeout')
 emit('Fresh server ready on loopback; OpenCode 2.4.3, anthropic/claude-haiku-5-5, full-access.')
 for project,title in [('demo','Unborn HEAD proof'),('multi','Non-Git root proof')]:
  emit('$ t3 project add fixture/'+project);emit(run(cli+['project','add','--base-dir',home,fixture/project,'--title',title],checkout))
 prompts=[('unborn','demo','main','feature-proof','Run git checkout --orphan fresh-start using the bash tool. Then use the task tool to start exactly one general subagent with prompt: Reply with the single word done. Do not commit or rename branches afterwards. Use native task, not any T3 delegate or thread tools.'),('multi','multi','main','multi-proof','Use the native task tool to start exactly one general subagent with prompt: Reply with the single word done. Do not use any T3 delegation tools. Do not change any files or branches.'),('remote','demo','remote-only','remote-proof','Reply with the single word done. Do not run tools.')]
 for label,project,base,branch,prompt in prompts:
  emit('$ t3 thread start --provider opencode --model anthropic/claude-haiku-5-5 --worktree '+base+' --branch '+branch+' fixture/'+project+' --wait --json')
  emit('Prompt: '+prompt)
  result=run(cli+['thread','start','--base-dir',home,'--provider','opencode','--model','anthropic/claude-haiku-5-5','--worktree',base,'--branch',branch,'--title',label+' proof',fixture/project,prompt,'--wait','--json'],checkout)
  (out/(label+'-cli.json')).write_text(result+'\n');emit(result)
 rpc=checkout/'apps/server/proof-rpc.ts';shutil.copy(pathlib.Path(__file__).with_name('proof-rpc.ts'),rpc)
 emit('$ live WebSocket vcs.createWorktree: unborn @, missing refs/heads/missing, missing branch with no remote, remote-only fallback')
 result=run(['node',rpc,home],checkout);(out/'rpc.ndjson').write_text(result+'\n');emit(result)
 emit('$ git config --get branch.probe-remote-only.t3-merge-base (RPC remote fallback)');emit(git(fixture/'probe','config','--get','branch.probe-remote-only.t3-merge-base'))
 emit('$ git config --get branch.probe-remote-only.t3-merge-base-ref');emit(git(fixture/'probe','config','--get','branch.probe-remote-only.t3-merge-base-ref'))
 emit('$ git config --get branch.remote-proof.t3-merge-base');emit(git(fixture/'demo','config','--get','branch.remote-proof.t3-merge-base'))
 emit('$ git config --get branch.remote-proof.t3-merge-base-ref');emit(git(fixture/'demo','config','--get','branch.remote-proof.t3-merge-base-ref'))
 emit('$ inspect persisted native-child branch events (all creation and metadata events)')
 db=sqlite3.connect(userdata/'statev2.sqlite')
 for seq,kind,payload in db.execute("select sequence,event_type,payload_json from orchestration_events where event_type in ('thread.created','thread.metadata-updated') order by sequence"):
  x=json.loads(payload)
  if x.get('creationSource')=='provider':emit(json.dumps({'sequence':seq,'type':kind,'threadId':x['id'],'branch':x.get('branch'),'worktreePath':x.get('worktreePath')}))
 db.close()
finally:
 if server is not None and server.poll() is None:
  server.send_signal(signal.SIGINT)
  try:server.wait(timeout=20)
  except subprocess.TimeoutExpired:server.terminate();server.wait(timeout=10)
# The server is stopped, so the trace is flushed and SQLite WAL checkpointed.
raw=userdata/'logs/server.trace.ndjson';spans=[json.loads(l) for l in raw.read_text().splitlines()]
byparent={}
for x in spans:byparent.setdefault(x.get('parentSpanId'),[]).append(x)
def descendants(root):
 result=[]
 for c in byparent.get(root['spanId'],[]):result.append(c);result.extend(descendants(c))
 return result
emit('$ inspect resolveBranchBase span subtrees; runGitCommand is one real Git subprocess')
for root in [x for x in spans if x.get('name')=='GitVcsDriver.resolveBranchBase']:
 ds=descendants(root);resolve=next((x for x in ds if x.get('name')=='GitVcsDriver.resolveBranchName.resolveRef'),None)
 if not resolve:continue
 cwd=resolve.get('attributes',{}).get('git.cwd','')
 emit(json.dumps({'spanId':root['spanId'],'traceId':root['traceId'],'cwd':cwd,'gitProcesses':sum(x.get('name')=='runGitCommand' for x in ds),'operations':[{'name':x['name'],'exit':x.get('exit')} for x in ds if x.get('attributes',{}).get('git.operation') or x.get('name')=='resolvePrimaryRemoteName']}))
emit('Server stopped. Complete raw SQLite and NDJSON trace retained for inspection. No tests used.')
(out/'duration.json').write_text(json.dumps({'seconds':round(time.monotonic()-start,3)}));cast.close();transcript.close()
