import json, sqlite3, sys, pathlib, re
home, run_dir, side, sha = sys.argv[1:]
out = pathlib.Path(run_dir)
ids = json.loads((out/'ids.json').read_text())
c = sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro', uri=True)
def rows(table, column):
    return [json.loads(r[0]) for r in c.execute(f'SELECT payload_json FROM orchestration_v2_projection_{table} WHERE {column}=?', (ids['run'],))]
run = rows('runs','run_id')[0]
item = next(r for r in rows('turn_items','run_id') if r['type']=='handoff')
handoffs = rows('context_handoffs','target_run_id')
activity = json.loads((out/'activity.json').read_text())
transcript = json.loads((out/'transcript.json').read_text())
# Only synthetic output is exported; redact local workspace locations.
def safe(s):
    return re.sub(r'/home/[^\s"\\]+', '[local-workspace]', s)
raw = {'commit':sha, 'mcpTranscript':transcript, 'run':run, 'handoffItem':item, 'preparedHandoffs':handoffs}
(out/f'{side}-runtime.json').write_text(safe(json.dumps(raw,indent=2)))
hid = lambda value: value.rsplit(':',1)[-1]
a = next(r for r in activity['items'] if r['type']=='handoff')
lines = [f'{side.upper()} - REAL SERVER RUNTIME CAPTURE',f'Commit: {sha}',
'Environment: Linux; source dev server; fresh isolated SQLite; Replay ACP multi-turn.',
'Capture: MCP responses plus read-only projections from the same server database.',
'No mocked orchestration, inserted database rows, or unit-test execution.', '',
'Reproduction completed:',
'1. Parent turn one on devReplay completed.',
'2. Fork parent; Fork turn one completed.',
'3. Merge fork back to parent; transfer pending before dispatch.',
'4. Configure parent to independent devReplayB instance.',
'5. Parent turn two after switching provider completed.',
'6. Read parent activity.', '',
'Actual t3_thread_read activity response (handoff item):',
f'  title: {a["title"]}',f'  status: {a["status"]}',f'  text first line: {a["text"].splitlines()[0]}', '',
'Identity and strategy from persisted run/item (ID suffixes for readability):',
f'  run ordinal: {run["ordinal"]}; status: {run["status"]}',
f'  run.contextHandoffId:  {hid(run["contextHandoffId"])}',
f'  item.contextHandoffId: {hid(item["contextHandoffId"])}',
f'  IDs match: {str(run["contextHandoffId"]==item["contextHandoffId"]).lower()}',
f'  item.strategy: {item["strategy"]}',
f'  item.summary equals selected handoff: {str(any(h["id"]==run["contextHandoffId"] and h["summaryText"]==item["summary"] for h in handoffs)).lower()}', '',
'Separately prepared handoffs for run 2:']
for h in handoffs:
    lines.extend([f'  {h["strategy"]}: {h["status"]}; id {hid(h["id"])}',f'    summary: {h["summaryText"].splitlines()[0]}',f'    delivery: {h["delivery"]["status"]}'])
lines.extend(['','Full IDs, summaries, and MCP responses are in the companion runtime JSON.'])
text=safe('\n'.join(lines)+'\n')
(out/f'{side}-capture.txt').write_text(text)
print(text)
