"""Real T3/OpenCode reproduction. Usage: python reproduce.py CHECKOUT SCRATCH PORT.
Run once per commit after vp i; SCRATCH must be a new directory.
No provider stand-ins, database writes, or copied user data.
"""
import json, os, pathlib, sqlite3, subprocess, sys, time
checkout, scratch, port = sys.argv[1:]
root = pathlib.Path(scratch).resolve()
root.mkdir(parents=True, exist_ok=False)
home = root / 'data'
(home / 'userdata').mkdir(parents=True)
(home / 'userdata/settings.json').write_text(json.dumps({'providerInstances': {'opencode': {'driver': 'opencode', 'enabled': True, 'config': {}}}}))
project = root / 'project'
project.mkdir()
(project / 'README.md').write_text('Synthetic session routing reproduction.\n')
subprocess.run(['git', 'init', '-q', str(project)], check=True)
prompt = 'Remember the codeword PELICAN in this conversation. Reproduce this sequence exactly using T3 tools: (1) call delegate_task in background mode async, same shared project, provider opencode and model anthropic/claude-sonnet-5-5, with a child instructed to run shell sleep 150 then reply exactly CHILD DONE. (2) call schedule_task bound to THIS thread with freshSession true and interval every 60 minutes; its prompt must say: This is an isolated scheduled turn. Reply SCHEDULED DONE and do nothing else. (3) call run_scheduled_task_now for that schedule. (4) End your turn immediately. Do not wait for the child, do not poll, do not read child status, do not cancel it. When its completion later wakes you, acknowledge CHILD DONE. Do not repeat these actions on any later turns.'
def cli(*args):
    result = subprocess.run(['node', 'apps/server/src/bin.ts', *args, '--base-dir', str(home)], cwd=checkout, capture_output=True, text=True, check=True)
    return result.stdout
log = (root / 'server.log').open('w')
server = subprocess.Popen(['node', 'apps/server/src/bin.ts', 'serve', '--base-dir', str(home), '--port', port], cwd=checkout, env={**os.environ, 'T3CODE_DEV_SEED': '0'}, stdout=log, stderr=log)
try:
    deadline = time.monotonic() + 60
    while not (home / 'userdata/server-runtime.json').exists():
        if server.poll() is not None or time.monotonic() > deadline: raise RuntimeError('Server did not start')
        time.sleep(.2)
    cli('project', 'add', str(project), '--title', 'Session routing proof')
    started = json.loads(cli('thread', 'start', str(project), prompt, '--title', 'Delegated completion after fresh scheduled session', '--provider', 'opencode', '--model', 'anthropic/claude-sonnet-5-5', '--json'))
    tid = started['threadId']
    db = home / 'userdata/statev2.sqlite'
    deadline = time.monotonic() + 600
    while True:
        with sqlite3.connect(f'file:{db}?mode=ro', uri=True) as c:
            runs = c.execute('select ordinal,status from orchestration_v2_projection_runs where thread_id=? order by ordinal', (tid,)).fetchall()
        if len(runs) >= 3 and runs[2][1] == 'completed': break
        if time.monotonic() > deadline: raise RuntimeError('No delegated completion wake')
        time.sleep(1)
    answer = cli('thread', 'send', tid, 'Without calling any tools: what did the delegated task report back to you, and what was the codeword?', '--wait', '--json')
    (root / 'answer.json').write_text(answer)
    print(answer)
    with sqlite3.connect(f'file:{db}?mode=ro', uri=True) as c:
        for ordinal, status, provider in c.execute('select r.ordinal,r.status,p.payload_json from orchestration_v2_projection_runs r join orchestration_v2_projection_provider_threads p using(provider_thread_id) where r.thread_id=? order by ordinal', (tid,)):
            print(ordinal, status, json.loads(provider)['nativeThreadRef']['nativeId'])
finally:
    server.terminate()
    try: server.wait(timeout=15)
    except subprocess.TimeoutExpired: server.kill(); server.wait()
    log.close()
