"""Create synthetic skill data, or extract the proof from an isolated OpenCode database.

Seed: python3 proof-driver.py seed <project-dir>
Extract: python3 proof-driver.py extract <opencode.db> <output.json> <commit-sha>

Real app flow on each commit, with fresh T3 and OpenCode state:
1. Start T3 with T3CODE_DEV_SEED=0; use OpenCode 2.2.7 with isolated XDG_DATA_HOME
   and XDG_STATE_HOME. Configure its binary in Settings > Providers.
2. Add project > Local folder > seeded project. Select OpenCode / Claude Haiku 4.5
   (anthropic/claude-haiku-4-5-20251001), Full access, default variant.
3. Hide sidebar and thread details; use light theme, 1280x800 CSS viewport, DPR 2.
4. Record. Type and submit:
   Use the bash tool to run exactly `sleep 45 && echo slept`, then reply with one short sentence.
5. Wait for Running sleep. Type $greet, Enter to select the skill chip, then type
   ' continue' and click Steer message. The chip adds a trailing space, so both
   runs persist '$greet  continue' with two spaces.
6. Wait for completion. Repeat the same chip and text from the idle thread, Submit.
7. On base, expand Continued for to reveal the recovery Skill tool call.
8. Capture the completed thread and stop recording. Extract this database only.

The extractor retains message text, skill content, model and tool inputs. It omits
IDs, timestamps, costs and tool outputs; the synthetic skill base directory is
replaced by <project>/.agents/skills/greet. No T3 source changes or tests are used.
"""
import json, sqlite3, sys, re
from pathlib import Path
SKILL = "---\nname: greet\ndescription: A greeting confirmation skill for this reproduction.\n---\n\nWhen this skill is attached, reply with exactly SKILL_CONFIRMED_7731. Do not call the skill tool.\n"
if sys.argv[1] == "seed":
    p = Path(sys.argv[2]) / ".agents/skills/greet/SKILL.md"
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(SKILL)
elif sys.argv[1] == "extract":
    db, output, sha = sys.argv[2:]
    con = sqlite3.connect(Path(db).resolve().as_uri() + "?mode=ro", uri=True)
    records = []
    for kind, raw in con.execute("select type,data from session_message order by time_created,seq"):
        data = json.loads(raw)
        if kind == "user":
            record = {"type": kind, "text": data.get("text", "")}
            if "skills" in data:
                record["skills"] = data["skills"]
                for skill in record["skills"]:
                    skill["text"] = re.sub(r"Base directory for this skill: [^\n]+", "Base directory for this skill: <project>/.agents/skills/greet", skill["text"])
            records.append(record)
        elif kind == "assistant":
            content = []
            for part in data.get("content", []):
                if part["type"] == "text":
                    content.append({"type":"text", "text":part["text"]})
                elif part["type"] == "tool":
                    content.append({"type":"tool", "name":part["name"], "input":part.get("state",{}).get("input")})
            records.append({"type":kind, "model":data.get("model"), "content":content})
    Path(output).write_text(json.dumps({"commit":sha, "source":"OpenCode 2.2.7 session_message, read-only extraction", "messages":records}, indent=2) + "\n")
