"""Real T3 CLI + real Pi handoff evidence. No replay or mocked provider.
Run with T3_CHECKOUT, T3_PROOF_ROOT, T3_PROOF_HOME and T3_PROOF_SHA set.
A T3 server must already run against T3_PROOF_HOME with Pi enabled.
"""
import datetime,json,os,pathlib,subprocess,sys,time
side=sys.argv[1]
checkout=pathlib.Path(os.environ['T3_CHECKOUT'])
root=pathlib.Path(os.environ['T3_PROOF_ROOT'])
home=pathlib.Path(os.environ['T3_PROOF_HOME'])
run=root/(side+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
run.mkdir()
repo=run/'repo';repo.mkdir()
transcript=[]
def clean(s):
 return str(s).replace(str(root),'$SCRATCH').replace(str(home),'$HOME').replace(str(checkout),'$CHECKOUT')
def emit(s=''):
 s=clean(s);print(s,flush=True);transcript.append(s)
 (run/'transcript.txt').write_text('\n'.join(transcript)+'\n')
def cli(label,*args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=checkout,capture_output=True,text=True)
 (run/(label+'.raw.txt')).write_text(p.stdout+p.stderr)
 if p.returncode:raise RuntimeError(clean(p.stdout+p.stderr))
 return json.loads(p.stdout) if '--json' in args else p.stdout
subprocess.run(['git','init','-b','master',str(repo)],capture_output=True,check=True)
(repo/'README.md').write_text('Synthetic Pi handoff evidence.\n')
subprocess.run(['git','-C',str(repo),'add','README.md'],check=True)
subprocess.run(['git','-C',str(repo),'-c','user.name=Evidence','-c','user.email=evidence@example.com','commit','-m','initial'],capture_output=True,check=True)
print('\033[?25l',end='',flush=True)
emit('PI WORKTREE HANDOFF | '+side.upper()+' | '+os.environ['T3_PROOF_SHA'][:10])
emit('Linux / isolated real T3 server / Pi 1.5.2 / anthropic/claude-haiku-5-5')
emit('Fresh synthetic git repo on master. Paths below use $SCRATCH for privacy.')
emit()
emit('$ t3 project add <repo>')
cli('00-project','project','add',str(repo))
probe='Run the bash tool with exactly: pwd; git branch --show-current. Report the literal output. Do not change directory.'
emit('$ t3 thread start <repo> <pwd + branch probe> --provider pi --model anthropic/claude-haiku-5-5 --wait')
initial=cli('01-start','thread','start',str(repo),probe,'--provider','pi','--model','anthropic/claude-haiku-5-5','--title','Pi handoff evidence','--wait','--json')
tid=initial['threadId']
def reply(data):
 text=data.get('reply') or ''
 # Show literal shell result from the agent, without prose or markdown fences.
 if '```' in text:text=text.split('```')[1].strip()
 for line in text.strip().splitlines():emit('  '+line)
reply(initial)
emit()
prompt='Call t3_worktree_handoff now to move THIS thread into a new worktree on new branch toeter. Skip setup. Set continuationPrompt to: '+probe+' Call handoff last in this turn.'
emit('$ t3 thread send <thread> <handoff: branch=toeter, continuationPrompt=pwd + branch> --wait')
cli('02-handoff','thread','send',tid,prompt,'--wait','--json')
emit('Waiting for the automatic continuation to complete...')
for attempt in range(120):
 show=cli('03-continuation','thread','show',tid,'--json')
 messages=show['messages']; assistants=[m for m in messages if m['role']=='assistant']
 if show['thread']['runCount']>=3 and show['thread']['activeRunId'] is None and len(assistants)>=2:break
 time.sleep(1)
else:raise RuntimeError('Continuation did not complete')
emit('$ t3 thread show <thread>')
emit('  T3 branch: '+str(show['thread']['branch']))
emit('  T3 worktree: '+str(show['thread']['worktreePath']))
emit('Automatic continuation -- actual Pi bash output:')
reply({'reply':assistants[-1]['text']})
emit()
emit('$ t3 thread send <thread> <repeat pwd + branch probe> --wait')
later=cli('04-later','thread','send',tid,'Run the bash tool again with exactly: pwd; git branch --show-current. Report the literal output. Do not change directory.','--wait','--json')
reply(later)
emit()
expected=show['thread']['worktreePath']
continuation_ok=expected in assistants[-1]['text'] and '\ntoeter' in assistants[-1]['text']
later_ok=expected in later['reply'] and '\ntoeter' in later['reply']
emit('Observed: '+('continuation and later turn use the worktree / toeter.' if continuation_ok and later_ok else 'T3 is bound to toeter; Pi continuation and later turn still use repo / master.'))
summary={'side':side,'sha':os.environ['T3_PROOF_SHA'],'continuationUsesWorktree':continuation_ok,'laterUsesWorktree':later_ok}
(run/'summary.json').write_text(json.dumps(summary,indent=2))
(root/(side+'-recorded-run.txt')).write_text(str(run))
(root/(side+'-done')).write_text('done')
time.sleep(15)
