"""Read a proof server's generated SQLite database without writing to it.
Usage: python3 capture-handoff.py DATABASE COMMIT OUTPUT_DIRECTORY
Workspace paths are normalized for privacy; message selection and text are otherwise preserved.
"""
import collections,json,pathlib,re,sqlite3,sys
path,sha,destination=sys.argv[1:]
out=pathlib.Path(destination);out.mkdir(parents=True,exist_ok=False)
c=sqlite3.connect(pathlib.Path(path).as_uri()+'?mode=ro',uri=True)
h=json.loads(c.execute('select payload_json from orchestration_v2_projection_context_handoffs order by updated_at desc limit 1').fetchone()[0])
selected={m['itemId'] for m in h['history']['messages']}
items=[json.loads(p) for p, in c.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal',(h['threadId'],))]
items=[i for i in items if i['runId']!=h['targetRunId']]
conversation=[i for i in items if i['type'] in ('user_message','assistant_message')]
rows=[]
for i in conversation:
 run=int(re.search(r':ordinal:(\d+)$',i['runId']).group(1))
 rows.append({'run':run,'kind':i['type'],'utf8Bytes':len(i['text'].encode()),'included':i['id'] in selected})
counts=collections.Counter(m['kind'] for m in h['history']['messages'])
report={'commit':sha,'budgetBytes':64000,'surface':'Real T3 Code server / ACP replay adapter','recording':'apps/server/scripts/dev-replay/bench_heavy_transcript.ndjson','conversation':rows,'selectedCounts':dict(counts),'omittedItems':h['history']['omittedItems'],'persistedHandoff':h}
s=json.dumps(report,indent=2)
s=re.sub(r'/tmp/[^\s"\\]*?/workspaces/[^/]+/handoff-budget','<workspace>',s)
(out/'handoff.json').write_text(s)
lines=['REAL SERVER PORTABLE HANDOFF CAPTURE',f'Commit: {sha}','Default history budget: 64,000 bytes','Input: six bench-heavy replay turns, identical padded user requests.','Action: switch devReplay -> replayTarget (same repository replay agent), then send a continuation.','Source: read-only query of the real server persisted context handoff.','Workspace paths normalized to <workspace> in attached payload.','','Run | User request | Assistant reply','----|--------------|----------------']
for n in range(1,7):
 vals=[]
 for k in ['user_message','assistant_message']:
  a=next(r for r in rows if r['run']==n and r['kind']==k);vals.append('KEPT' if a['included'] else 'DROPPED')
 lines.append(f'{n}   | {vals[0]:12} | {vals[1]}')
lines+=['',f'Conversation messages retained: {sum(r["included"] for r in rows)} / {len(rows)}',f'Selected command outputs: {counts["command_execution"]}',f'Omitted history items: {h["history"]["omittedItems"]}','', 'This proves server history selection using an existing replay recording; it does not prove real-provider recall.']
(out/'capture.txt').write_text('\n'.join(lines)+'\n')
print('\n'.join(lines))
