"""セッション履歴の単位の実験。あるフォルダで話した内容を、別のフォルダの「続きから」で思い出せるか。
各CLIの「直前のセッションを続ける」機能を、同じフォルダ・サブフォルダ・無関係なフォルダで試す。"""
import json, shutil, subprocess, uuid
from pathlib import Path

ROOT = Path("/tmp/nico-sess")
shutil.rmtree(ROOT, ignore_errors=True)
for p in ("repo/sub", "other"): (ROOT/p).mkdir(parents=True)
subprocess.run(["git","init","-q","."], cwd=ROOT/"repo", check=True)

def sh(cmd, cwd):
    r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=300)
    return r.stdout.strip()

out = []
for tool in ("claude", "codex", "grok"):
    word = "ZEBRA-" + uuid.uuid4().hex[:6].upper()
    tell = f"合言葉は {word} です。覚えておいてください。返事は「はい」だけ。"
    ask = "さっき教えた合言葉は何ですか？ 覚えていなければ「不明」とだけ答えてください。"
    if tool == "claude":
        sh(["claude","-p",tell,"--tools",""], ROOT/"repo")
        cont = lambda cwd: sh(["claude","-p","--continue",ask,"--tools",""], cwd)
    elif tool == "codex":
        sh(["codex","exec","--skip-git-repo-check","-s","read-only",tell], ROOT/"repo")
        cont = lambda cwd: sh(["codex","exec","resume","--last","--skip-git-repo-check",ask], cwd)
    else:
        sh(["grok","--trust","--tools","","-p",tell], ROOT/"repo")
        cont = lambda cwd: sh(["grok","--trust","--tools","","--continue","-p",ask], cwd)
    for place in ("repo", "repo/sub", "other"):
        ans = cont(ROOT/place)
        out.append({"tool": tool, "continue_in": place, "word": word, "recalled": word in ans, "answer": ans[:200]})
        print(tool, place, word in ans, ans[:80].replace("\n"," "))
Path(__file__).with_name("session-results.json").write_text(json.dumps(out, ensure_ascii=False, indent=1))
