import json, subprocess, sys, os, tempfile

work = tempfile.mkdtemp(dir="/tmp/factory-issue-41822-triage")
p = subprocess.Popen(["codex", "app-server"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                     stderr=open("/tmp/factory-issue-41822-triage/codex-stderr.log", "w"), text=True, bufsize=1)
nid = 0

def send(method, params, notify=False):
    global nid
    msg = {"method": method, "params": params}
    if not notify:
        nid += 1
        msg["id"] = nid
    p.stdin.write(json.dumps(msg) + "\n"); p.stdin.flush()
    if notify:
        return None
    want = nid
    while True:
        line = p.stdout.readline()
        if not line:
            sys.exit("app-server closed")
        m = json.loads(line)
        if m.get("id") == want and "method" not in m:
            if "error" in m:
                print("ERROR", method, m["error"]); sys.exit(1)
            return m["result"]

def wait_turn():
    while True:
        m = json.loads(p.stdout.readline())
        if m.get("method") == "turn/completed":
            return m["params"]["turn"]["status"]

def turns(tid):
    r = send("thread/turns/list", {"threadId": tid, "cursor": None, "limit": 100, "sortDirection": "asc", "itemsView": "summary"})
    return [t["id"] for t in r["data"]]

send("initialize", {"clientInfo": {"name": "triage", "version": "0"}, "capabilities": {"experimentalApi": True}})
send("initialized", {}, notify=True)
t = send("thread/start", {"cwd": work, "model": sys.argv[1] if len(sys.argv) > 1 else "gpt-5.4-mini", "approvalPolicy": "never", "sandbox": "danger-full-access"})
tid = t["thread"]["id"]
print("thread", tid, "historyMode", t["thread"].get("historyMode"))
for i in range(1, 5):
    send("turn/start", {"threadId": tid, "input": [{"type": "text", "text": f"Prompt {i}: reply with just the word ok{i}."}]})
    print("turn", i, wait_turn())
before = turns(tid)
print("turns before rollback:", len(before), before)

def revert_newest(n):
    r = send("thread/turns/list", {"threadId": tid, "cursor": None, "limit": n, "sortDirection": "desc", "itemsView": "summary"})
    boundary = r["data"][n - 1]["id"] if len(r["data"]) >= n else r["data"][-1]["id"]
    send("thread/revert", {"threadId": tid, "beforeTurnId": boundary})

# Edit from here under the last message: T3 computes N=1 from its own records.
revert_newest(1)
print("after attempt 1:", len(turns(tid)))
# Retry: T3's records are unchanged (rolled_back events never written), so N is still 1.
revert_newest(1)
print("after attempt 2 (retry):", len(turns(tid)))
p.terminate()
