import os,sys,pathlib,subprocess,json,time,sqlite3,datetime
root=pathlib.Path(sys.argv[1]); side=sys.argv[2]
scratch=pathlib.Path(__file__).parent
out=scratch/side/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ');out.mkdir(parents=True)
workspace=scratch/side/'workspace';home=root/'.t3'
start=time.monotonic()
transcript=open(out/'runtime.jsonl','w')
def emit(data):
 data={'elapsedSeconds':round(time.monotonic()-start,1),**data}
 line=json.dumps(data);print(line,flush=True);transcript.write(line+'\n');transcript.flush()
def cli(args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=root,capture_output=True,text=True,timeout=90)
 if p.returncode: raise RuntimeError(p.stderr)
 return p.stdout
cli(['project','add',str(workspace),'--title','Worker isolation reproduction'])
emit({'action':'Added synthetic project through the real CLI'})
for i in range(4):
 result=json.loads(cli(['thread','start',str(workspace),'Start the requested task.','--title',f'Unanswered start {i+1}','--provider','codex','--model',os.environ['REPRO_MODEL'],'--json']))
 emit({'action':f'Launched unanswered start {i+1}'})
con=sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro',uri=True)
def snapshot():
 rows=con.execute('''select t.title,e.status,e.attempt_count,e.lease_expires_at from orchestration_v2_effect_outbox e join orchestration_v2_projection_threads t using(thread_id) where e.effect_type='provider-turn.start' order by e.created_at''').fetchall()
 messages=con.execute("select count(*) from orchestration_v2_projection_messages m join orchestration_v2_projection_threads t using(thread_id) where t.title='Healthy replay thread' and m.role='assistant'").fetchone()[0]
 return {'starts':[{'thread':r[0],'status':r[1],'attempts':r[2],'leaseExpiresAt':r[3]} for r in rows],'healthyAssistantMessages':messages}
# Confirm the original failure condition before queuing healthy work.
for _ in range(100):
 state=snapshot()
 drops=(scratch/side/'dropped.jsonl').read_text().splitlines() if (scratch/side/'dropped.jsonl').exists() else []
 if len([r for r in state['starts'] if r['status']=='running'])==4 and len(drops)>=4:break
 time.sleep(.2)
else:raise RuntimeError('Four unanswered running starts were not established')
emit({'action':'Confirmed four running starts and four dropped app-server requests',**state})
result=json.loads(cli(['thread','start',str(workspace),'Show that this thread can still run.','--title','Healthy replay thread','--provider','devReplay','--model','showcase','--json']))
(scratch/side/'healthy-thread.json').write_text(json.dumps(result))
emit({'action':'Launched healthy replay thread on another provider'})
for i in range(66):
 emit({'action':'Observed real persisted outbox and message projections',**snapshot()})
 time.sleep(1)
emit({'action':'Observation complete',**snapshot()})
