#!/usr/bin/env python3
"""memory-ab-check.py
Psychosonic Lab, experiment 02: run your own blind memory A/B.

Give it a text file of your own questions, one per line, each written so the
answer lives only in your own notes, not in your code or docs. It runs every
question with your memory connector and without it, N times each, in a
shuffled order, and saves each answer to its own file with a random name so
you can grade blind: read a file, say pass or fail, without knowing which
setup wrote it.

    python3 -B memory-ab-check.py run questions.txt 3 out/
        Runs every question in questions.txt 3 times with the connector and
        3 times without. Uses stock Claude Code: model sonnet, effort low,
        --setting-sources project (no CLAUDE.md, no hooks). Writes
        out/ans-*.txt (the answers, filenames carry no hint of setup) and
        out/key.json (which file is which setup and rep). Do not open
        key.json until every answer is graded.

    python3 -B memory-ab-check.py tally out/ graded.csv
        graded.csv is your own two columns, file,pass (pass is 0 or 1), one
        row per out/ans-*.txt, filled in after reading each file blind.
        Prints the right/total count for each setup.

Edit MCP_SERVER below to point at your own memory connector; the default is
Notesmith's. A connector that needs an API key or a running app should be
started before you run this.

Flags used here, verified against `claude --help` on this Mac (2026-10-14):
-p, --model, --effort, --output-format json, --no-session-persistence,
--setting-sources, --strict-mcp-config, --mcp-config, --max-turns.
"""
import csv
import json
import random
import secrets
import subprocess
import sys
from pathlib import Path

MCP_SERVER = "/Applications/Notesmith.app/Contents/Helpers/agent-notes"
MCP_SERVER_NAME = "agent-notes"


def ask(question, cfg_path):
    """One claude -p call. cfg_path is None for the no-memory setup."""
    cmd = ["claude", "-p", question, "--model", "sonnet", "--effort", "low",
           "--output-format", "json", "--no-session-persistence",
           "--setting-sources", "project", "--strict-mcp-config", "--max-turns", "8"]
    if cfg_path:
        cmd += ["--mcp-config", str(cfg_path)]
    out = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
    data = json.loads(out.stdout)
    return data.get("result", ""), data.get("total_cost_usd"), data.get("num_turns")


def cmd_run(args):
    if len(args) != 3:
        sys.exit("usage: memory-ab-check.py run questions.txt reps out_dir")
    qfile, reps, out_dir = Path(args[0]), int(args[1]), Path(args[2])
    out_dir.mkdir(parents=True, exist_ok=True)
    cfg = out_dir / "mcp-on.json"
    cfg.write_text(json.dumps({"mcpServers": {MCP_SERVER_NAME: {
        "type": "stdio", "command": MCP_SERVER, "args": [], "env": {}}}}))

    questions = [l.strip() for l in qfile.read_text().splitlines() if l.strip()]
    jobs = [(q, setup, rep)
            for q in questions for setup in ("on", "off") for rep in range(1, reps + 1)]
    random.shuffle(jobs)  # the order is shuffled; filenames give no hint either

    key = {}
    for i, (question, setup, rep) in enumerate(jobs, 1):
        rid = secrets.token_hex(4)
        print(f"[{i}/{len(jobs)}] {rid} ({setup}, rep {rep}): {question[:60]}", file=sys.stderr)
        text, cost, turns = ask(question, cfg if setup == "on" else None)
        (out_dir / f"ans-{rid}.txt").write_text(text)
        key[rid] = {"question": question, "setup": setup, "rep": rep,
                    "cost_usd": cost, "turns": turns}
    (out_dir / "key.json").write_text(json.dumps(key, indent=2))
    print(f"\nwrote {len(jobs)} answers to {out_dir}/ans-*.txt")
    print("grade them blind (one pass/fail per file), then run tally.")


def cmd_tally(args):
    if len(args) != 2:
        sys.exit("usage: memory-ab-check.py tally out_dir graded.csv")
    out_dir, graded_csv = Path(args[0]), Path(args[1])
    key = json.loads((out_dir / "key.json").read_text())
    graded = {r["file"]: int(r["pass"]) for r in csv.DictReader(open(graded_csv))}

    totals = {}
    for rid, info in key.items():
        fname = f"ans-{rid}.txt"
        if fname not in graded:
            print(f"missing a grade for {fname}", file=sys.stderr)
            continue
        right, n = totals.get(info["setup"], (0, 0))
        totals[info["setup"]] = (right + graded[fname], n + 1)
    for setup in ("off", "on"):
        right, n = totals.get(setup, (0, 0))
        print(f"{setup:3} (memory {'on' if setup == 'on' else 'off'}): {right}/{n}")


def main():
    if len(sys.argv) < 2 or sys.argv[1] not in ("run", "tally"):
        sys.exit(__doc__)
    {"run": cmd_run, "tally": cmd_tally}[sys.argv[1]](sys.argv[2:])


if __name__ == "__main__":
    main()
