"""Read-only evidence from an isolated proof server and its synthetic Claude home.
Usage: python extract-native-proof.py WORKTREE CLAUDE_HOME SYMLINK SIDE OUTPUT
No credentials or absolute filesystem paths are included in the output.
"""
import json
import pathlib
import sqlite3
import subprocess
import sys
work, home, link = map(pathlib.Path, sys.argv[1:4])
side, output = sys.argv[4:6]
db = sqlite3.connect(f'file:{work}/.t3/userdata/statev2.sqlite?mode=ro', uri=True)
threads = [json.loads(r[0]) for r in db.execute('select payload_json from orchestration_v2_projection_provider_threads')]
report = {'side': side, 'commit': subprocess.check_output(['git', '-C', str(work), 'rev-parse', 'HEAD'], text=True).strip(), 'providerThreads': [{'instance': t['providerInstanceId'], 'nativeId': t['nativeThreadRef']['nativeId'], 'firstRunOrdinal': t['firstRunOrdinal'], 'lastRunOrdinal': t['lastRunOrdinal'], 'handoffIds': t['handoffIds']} for t in threads]}
sessions = []
for file in (home / 'projects').rglob('*.jsonl'):
    messages = []
    for line in file.read_text().splitlines():
        row = json.loads(line)
        if row.get('type') in ('user', 'assistant'):
            content = row.get('message', {}).get('content')
            text = content if isinstance(content, str) else ' '.join(x.get('text', '') for x in content or [] if x.get('type') == 'text')
            if text:
                # Keep only this reproduction's prompt/reply or handoff prefix.
                if text.startswith('Context handoff'):
                    text = text.split('Thread:')[0].strip()
                elif text not in ('OK', 'PELICAN', 'What is the secret word? Reply with just the word.') and 'Remember the secret word PELICAN. Reply only with OK.' not in text:
                    text = '[other text omitted]'
                messages.append({'role': row['type'], 'text': text})
    sessions.append({'nativeId': file.stem, 'messages': messages})
report['nativeSessionFiles'] = sessions
report['spawnEnvironment'] = []
for proc in pathlib.Path('/proc').iterdir():
    try:
        if not proc.name.isdigit():
            continue
        env = dict(x.split(b'=', 1) for x in (proc / 'environ').read_bytes().split(b'\0') if b'=' in x)
        config = env.get(b'CLAUDE_CONFIG_DIR', b'').decode()
        if config in (str(home), str(link)):
            report['spawnEnvironment'].append({'CLAUDE_CONFIG_DIR': 'configured-symlink' if config == str(link) else 'configured-real-home', 'isConfiguredSymlink': config == str(link)})
    except (OSError, ValueError):
        pass
pathlib.Path(output).write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, indent=2))
