import sys,subprocess,pathlib,json,sqlite3,urllib.request,time
work=pathlib.Path(sys.argv[1]);side=sys.argv[2]
root=pathlib.Path(__file__).parent
out=root/(side+'-'+str(time.time_ns()));out.mkdir()
def cli(*args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(work/'.t3')],cwd=work,text=True,capture_output=True)
 if p.returncode:raise RuntimeError(p.stderr+p.stdout)
 return p.stdout
fixture=out/'selected-umbrella';fixture.mkdir();(fixture/'NOTES.md').write_text('Synthetic proof fixture\n')
def git(cwd,*args):return subprocess.check_output(['git',*args],cwd=cwd,text=True).strip()
for n in range(1,10):
 r=fixture/f'repo{n}';r.mkdir();(r/'README.md').write_text(f'repository {n}\n')
 git(r,'init','-q','-b','main');git(r,'add','.');git(r,'-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','-qm','Initial')
added=cli('project','add',str(fixture));(out/'project-add.txt').write_text(added)
project=added.split('Added project ')[1].split()[0]
launchargs={'projectId':project,'title':'Selected repositories parent','message':'Reply READY only. Do not call tools or change files.','runtimeMode':'full-access','modelSelection':{'instanceId':'pi','model':'default'},'workspaceStrategy':{'type':'worktree','baseRef':'main','branch':'feature/parent','repositories':[{'path':str(fixture/'repo1')},{'path':str(fixture/'repo3')}]}}
(out/'launch-input.json').write_text(json.dumps(launchargs,indent=2));launched=json.loads(subprocess.check_output(['node','scripts/.proof-launch.ts',str(work/'.t3'),json.dumps(launchargs)],cwd=work,text=True));(out/'launch-result.json').write_text(json.dumps(launched,indent=2));thread=launched['threadId']
# CLI --wait drains the initial turn before returning when a second READY request is sent.
ready=cli('thread','send',thread,'Reply READY only. Do not call tools or change files.','--wait','--json');(out/'ready.json').write_text(ready)
db=sqlite3.connect(f'file:{work}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
def projection(t):return json.loads(db.execute('select payload_json from orchestration_v2_projection_threads where thread_id=?',(t,)).fetchone()[0])
parent=projection(thread);folder=pathlib.Path(parent['worktreePath']);print('Parent ready:',side,flush=True)
markers={}
for n in [1,3]:
 r=folder/f'repo{n}';(r/'PARENT_ONLY.txt').write_text('Committed in parent task folder on feature/parent\n');git(r,'add','PARENT_ONLY.txt');git(r,'-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','-qm','Parent-only marker');markers[f'repo{n}']=git(r,'rev-parse','HEAD')
prompt='Call delegate_task exactly once with task "Run pwd and ls -la. List the repo directories in your current working directory, and for each run git log -1 --format=%s and report whether PARENT_ONLY.txt exists. Do not change files.", isolation "worktree", mode "wait". Report the result. Do not retry or use another delegation method. Do not change settings or files.'
(out/'prompt.txt').write_text(prompt)
reply=cli('thread','send',thread,prompt,'--wait','--json');(out/'reply.raw.json').write_text(reply)
items=[json.loads(row[0]) for row in db.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal',(thread,))]
delegate=[d for d in items if d.get('toolName','').endswith('delegate_task')]
children=[json.loads(row[0]) for row in db.execute('select payload_json from orchestration_v2_projection_threads') if json.loads(row[0]).get('lineage',{}).get('parentThreadId')==thread]
result={'side':side,'parent':{'branch':parent['branch'],'entries':sorted(p.name for p in folder.iterdir()),'markers':markers},'delegateCalls':[{'input':d.get('input'),'output':d.get('output')} for d in delegate],'children':[]}
for child in children:
 cwd=pathlib.Path(child['worktreePath']);repos={}
 for r in cwd.iterdir():
  if r.name.startswith('repo') and r.is_dir():
   repos[r.name]={'head':git(r,'rev-parse','HEAD'),'latestCommit':git(r,'log','-1','--format=%s'),'parentMarkerExists':(r/'PARENT_ONLY.txt').exists()}
 result['children'].append({'branch':child['branch'],'entries':sorted(p.name for p in cwd.iterdir()),'repositories':repos,'ls':subprocess.check_output(['ls','-la'],cwd=cwd,text=True)})
 childitems=[json.loads(row[0]) for row in db.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal',(child['id'],))]
 result['children'][-1]['commands']=[{k:d[k] for k in ['input','output','exitCode'] if k in d} for d in childitems if d['type']=='command_execution' and d.get('input')!='Preparing workspace']
(out/'result.raw.json').write_text(json.dumps(result,indent=2));print(out,flush=True)
