#!/usr/bin/env python3
"""repeat-check.py: ask a local model the same thing several times, and see if it answers the same.

Psychosonic Lab, experiment 05. https://psychosonicconsulting.com/lab/agent-gym

The task is the one from our Agent Gym that caught this: convert a 54 section status
document to one HTML page and lose nothing. Every run sends the identical request to
Ollama on your own Mac, at temperature 0, grades the answer with the gym's own checks,
and keeps the answer. At the end it says how many runs passed and how many DIFFERENT
answers came back. If temperature 0 made a model repeatable, that second number would
be 1.

Standard library only. It talks to Ollama on this Mac and to nothing else, and it writes
only inside the folder it makes.

    python3 -B repeat-check.py run gpt-oss:20b              # 10 runs
    python3 -B repeat-check.py run gpt-oss:20b --n 20 --out my-runs
    python3 -B repeat-check.py grade answer-01.html other.html
    python3 -B repeat-check.py prompt                       # print exactly what is sent

An empty answer, a timeout or an error from Ollama is counted as NO ANSWER, not as a
fail: a model that never answered has not answered wrongly.
"""
import argparse
import csv
import datetime
import hashlib
import json
import os
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request

# ---- the task, built exactly as the gym's build.py builds it ----------------------
# (section title, component name, number, claim). The names are made up or our own.
SECTIONS = [
    ("Corpus",      "TarotCore",          952,  "resolves against a corpus of {n} curated recipes"),
    ("Resolver",    "FoodDrawResolver",   1540, "keys all {n} possible draws to exactly one dish"),
    ("Coverage",    "DrawCoverageIndex",  781,  "reports {n} draws resolved, the rest falling back"),
    ("Sharing",     "RecipeDetailView",   3,    "exports {n} artifacts: image, recipe text, library file"),
    ("Export",      "MoreGarlicExport",   64,   "chunks the payload at {n} KB before handoff"),
    ("Routing",     "PrismApp",           7,    "registers {n} URL scheme handlers"),
    ("Allergies",   "AllergenFilter",     18,   "screens against {n} declared allergen classes"),
    ("Journal",     "ReadingJournal",     240,  "retains {n} days of saved draws"),
    ("Fleet",       "SmithAdapter",       14,   "pins the fine-tune at {n}B parameters"),
    ("Holdout",     "HoldoutGate",        8,    "scored {n} of 14 against a base of 3 of 14"),
    ("Flywheel",    "TaskFlywheel",       60,   "generates {n} synthetic tasks per cycle"),
    ("Distill",     "SftExtractor",       600,  "trains for {n} iterations at sequence length 8192"),
    ("Witness",     "DriftSensor",        256,  "caps the re-verification interval at {n} runs"),
    ("Ledger",      "UsageLedger",        887,  "has recorded {n} delegated runs to date"),
    ("Vision",      "VisionPrescreen",    5265, "read a {n}px tall scrolling capture without invention"),
    ("Residency",   "ModelResidency",     36,   "assumes a {n} GB unified-memory ceiling"),
    ("Latency",     "SpeedLane",          8,    "returns one-shots in under {n} seconds"),
    ("Quantize",    "QuantPipeline",      4,    "exports at {n}-bit for the Ollama runtime"),
    ("Context",     "ContextSizer",       131,  "auto-sizes the window up to {n}k tokens"),
    ("Failover",    "OllamaFailover",     2,    "keeps {n} loaded models resident at once"),
    ("Regression",  "RegressionFeed",     11,   "has promoted {n} real failures into gym tasks"),
    ("Status",      "ReleaseGate",        90,   "requires {n}% on two consecutive runs to promote"),
]
GENERATED = [
    "Cache", "Queue", "Scheduler", "Indexer", "Tokenizer", "Sampler", "Batcher",
    "Loader", "Serializer", "Validator", "Migrator", "Compactor", "Replayer",
    "Throttle", "Backoff", "Checkpoint", "Snapshot", "Reconciler", "Dispatcher",
    "Collector", "Normalizer", "Partitioner", "Balancer", "Watchdog", "Auditor",
    "Rotator", "Sweeper", "Verifier", "Encoder", "Planner", "Tracer", "Profiler",
]
ALL = SECTIONS + [(n, f"{n}Unit", 1009 + i * 37, "holds {n} entries before it yields to the next stage")
                  for i, n in enumerate(GENERATED)]
TRADEOFF = (
    "Gains are real but bounded: the ceiling here is capability-bound, not "
    "process-bound, so more training data of the same shape will not move it. "
    "Trading model size for speed costs accuracy on APP-BUILD, and that "
    "trade-off is why the 30b keeps the speed lane while gpt-oss:20b keeps quality.")


def source_document():
    out = ["# Prism / agent-gym — consolidated subsystem status", ""]
    for title, ident, num, claim in ALL:
        out += [f"## {title}", "",
                f"The {ident} component {claim.format(n=num)}. This behavior is contractual and "
                f"is verified on every run; do not restate it loosely or round the figure.", ""]
    out += ["## Trade-off", "", TRADEOFF, ""]
    return "\n".join(out)


SYSTEM = ("You convert source documents to styled, self-contained HTML. Output ONLY the HTML "
          "— no markdown fences, no prose, no commentary. Preserve the source content EXACTLY: "
          "every proper noun, every number, every claim. Never summarize, never drop a section, "
          "never truncate. Long documents must be converted in full.")
PROMPT = ("Convert the source document below into a single self-contained HTML page.\n\n"
          "Requirements:\n"
          "- Inline <style> only. NO external stylesheets, fonts, scripts, or images.\n"
          "- Preserve EVERY section, in order, as a heading plus its content.\n"
          "- Preserve every component name and every number EXACTLY. Do not round, "
          "normalize, or re-spell them.\n"
          "- Preserve every claim including qualifiers. Do not summarize or condense.\n"
          "- The document is long. Convert ALL of it — a truncated page is a failure.\n"
          "- Dark theme, readable body text, monospace for identifiers.\n\n"
          "Source document:\n\n" + source_document())

# The request the gym made: Ollama's chat endpoint, not streamed, temperature 0, and a
# 16,384 token context (the size the gym's helper picked for a prompt this long).
OPTIONS = {"temperature": 0, "num_ctx": 16384}


# ---- the grader, the gym's check.py ------------------------------------------------
def grade(html):
    """Return a list of problems. An empty list is a pass."""
    errs = []
    t = re.sub(r"<!--.*?-->", " ", html, flags=re.S)
    t = re.sub(r"<(style|script)\b.*?</\1>", " ", t, flags=re.S | re.I)
    t = re.sub(r"<[^>]+>", " ", t)
    t = (t.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">")
          .replace("&nbsp;", " ").replace("&#39;", "'").replace("&quot;", '"'))
    text = re.sub(r"\s+", " ", t).strip()
    low = text.lower()

    names = [i for _, i, _, _ in ALL if i not in text]
    nums = [f"{s}:{n}" for s, _, n, _ in ALL if not re.search(rf"(?<![\d.]){n}(?![\d.])", text)]
    if names:
        errs.append(f"{len(names)}/{len(ALL)} component names lost: {names[:6]}")
    if nums:
        errs.append(f"{len(nums)}/{len(ALL)} figures lost or rounded: {nums[:6]}")

    pos, heads = [], []
    for title in [s for s, _, _, _ in ALL] + ["Trade-off"]:
        m = re.search(rf"<h[1-6][^>]*>\s*{re.escape(title)}\s*</h[1-6]>", html, re.I)
        heads.append(title) if m is None else pos.append(m.start())
    if heads:
        errs.append(f"missing section heading(s): {heads[:6]}")
    elif pos != sorted(pos):
        errs.append("section headings out of source order")

    for label, alts in [("bounded qualifier", ["bounded"]),
                        ("capability-bound vs process-bound", ["capability-bound"]),
                        ("more same-shape data will not move it",
                         ["will not move it", "won't move it", "not move it"]),
                        ("the trade-off sentence", ["trade-off", "tradeoff"]),
                        ("speed lane attribution", ["speed lane"])]:
        if not any(a in low for a in alts):
            errs.append(f"dropped claim: {label}")

    if ALL[-1][1] not in text:
        errs.append(f"final section lost ({ALL[-1][1]}), truncated")
    if "speed lane" not in low:
        errs.append("trade-off section (document tail) missing, truncated")
    if not re.search(r"</html\s*>|</body\s*>", html, re.I):
        errs.append("no closing </body> or </html>, truncated mid-document")
    if len(text) <= 2200:
        errs.append(f"rendered text implausibly short ({len(text)} chars), condensed?")

    if not re.search(r"<style\b", html, re.I):
        errs.append("no inline <style> block")
    ext = re.findall(r'(?:src|href)\s*=\s*["\'](https?:)?//[^"\']+', html, re.I)
    if ext:
        errs.append(f"external asset reference(s), not self-contained: {ext[:3]}")
    if re.search(r"@import", html, re.I):
        errs.append("@import, not self-contained")
    if re.search(r"<script\b[^>]*\ssrc\s*=", html, re.I):
        errs.append("external <script src>, not self-contained")
    return errs


def strip_fence(text):
    """The gym takes the HTML out of a ``` fence if the model wrapped it in one."""
    text = text.strip()
    m = re.search(r"```[a-zA-Z0-9_.+-]*[ \t]*\r?\n(.*?)```", text, re.S)
    return m.group(1).strip() if m else text


# ---- talking to Ollama -----------------------------------------------------------------
def ollama(host, path, body=None, timeout=30):
    req = urllib.request.Request(host + path, method="POST" if body is not None else "GET",
                                 data=json.dumps(body).encode() if body is not None else None,
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read().decode())


def sh(*cmd):
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=10).stdout.strip()
    except (OSError, subprocess.SubprocessError):
        return ""


def swap_used():
    m = re.search(r"used = ([\d.]+M)", sh("sysctl", "-n", "vm.swapusage"))
    return m.group(1) if m else ""


def loaded(host, model):
    try:
        return any(m.get("name") == model or m.get("model") == model
                   for m in ollama(host, "/api/ps").get("models", []))
    except (OSError, ValueError):
        return None


def run(args):
    host = args.host.rstrip("/")
    try:
        version = ollama(host, "/api/version").get("version", "")
        tags = ollama(host, "/api/tags").get("models", [])
    except (OSError, ValueError) as e:
        sys.exit(f"Can't reach Ollama at {host} ({e}). Start it, then: ollama pull {args.model}")
    digest = next((m.get("digest", "") for m in tags if m.get("name") == args.model
                   or m.get("model") == args.model), None)
    if digest is None:
        sys.exit(f"{args.model} is not pulled. Run: ollama pull {args.model}")

    # Ollama picks how many prompt tokens it processes at once when it loads the model, and
    # that changes the answer. --num-batch fixes it for the whole run.
    options = dict(OPTIONS, **({"num_batch": args.num_batch} if args.num_batch else {}))
    stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    out = args.out or f"repeat-check-{stamp}"
    os.makedirs(out, exist_ok=False)
    meta = dict(script="repeat-check.py", started=stamp, model=args.model, model_digest=digest,
                ollama=version, runs=args.n, options=options, host=host,
                mac=sh("sysctl", "-n", "hw.model"), chip=sh("sysctl", "-n", "machdep.cpu.brand_string"),
                memory_gb=round(int(sh("sysctl", "-n", "hw.memsize") or 0) / 2 ** 30),
                macos=sh("sw_vers", "-productVersion"),
                prompt_sha256=hashlib.sha256((SYSTEM + "\n" + PROMPT).encode()).hexdigest())
    json.dump(meta, open(os.path.join(out, "meta.json"), "w"), indent=2)
    body = {"model": args.model, "stream": False, "options": options,
            "messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": PROMPT}]}

    rows = []
    print(f"{args.model} on Ollama {version}, {args.n} runs, temperature 0. Answers go to {out}/")
    for i in range(1, args.n + 1):
        row = dict(run=i, started=datetime.datetime.now().isoformat(timespec="seconds"),
                   loadavg=round(os.getloadavg()[0], 2), swap_used=swap_used(),
                   model_loaded_before=loaded(host, args.model))
        t0 = time.time()
        try:
            resp = ollama(host, "/api/chat", body, timeout=args.timeout)
            msg = resp.get("message", {})
            answer, thinking = strip_fence(msg.get("content", "")), msg.get("thinking", "") or ""
            row.update(done_reason=resp.get("done_reason", ""), eval_count=resp.get("eval_count", ""),
                       error="")
        except (OSError, ValueError) as e:
            answer, thinking = "", ""
            detail = e.read().decode("utf-8", "replace") if isinstance(e, urllib.error.HTTPError) else ""
            row.update(done_reason="", eval_count="", error=f"{e} {detail}".strip()[:200])
        row["seconds"] = round(time.time() - t0, 1)
        name = f"answer-{i:02d}.html"
        open(os.path.join(out, name), "w", encoding="utf-8").write(answer)
        if thinking:
            open(os.path.join(out, f"answer-{i:02d}.thinking.txt"), "w", encoding="utf-8").write(thinking)
        if row["done_reason"] == "length":
            # Out of context before the answer was done: no answer, even if part of one was
            # written (Josh, 2026-10-25). The part stays in the answer file.
            row.update(outcome="no answer", sha256="",
                       problems=f"context full after {int(row['eval_count']):,} tokens"
                                + (", answer cut off" if answer.strip() else ", before any answer"))
        elif not answer.strip():
            row.update(outcome="no answer", problems=row["error"] or "empty answer", sha256="")
        else:
            errs = grade(answer)
            row.update(outcome="fail" if errs else "pass", problems="; ".join(errs),
                       sha256=hashlib.sha256(answer.encode()).hexdigest())
        row.update(answer=name, answer_chars=len(answer), thinking_chars=len(thinking))
        rows.append(row)
        print(f"  run {i:2d}: {row['outcome']:9s} {row['seconds']:7.1f}s  "
              f"{row['sha256'][:12] or '-':12s}  {row['problems'][:70]}")

    with open(os.path.join(out, "results.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0]))
        w.writeheader()
        w.writerows(rows)

    answered = [r for r in rows if r["outcome"] != "no answer"]
    passed = sum(r["outcome"] == "pass" for r in rows)
    distinct = len({r["sha256"] for r in answered})
    print(f"\n{passed} of {len(rows)} runs passed. {len(rows) - len(answered)} gave no answer.")
    print(f"{distinct} different answer{'s' if distinct != 1 else ''} came back from "
          f"{len(answered)} answered runs of the same request at temperature 0.")
    if distinct == 1 and len(answered) > 1:
        print("Every answer was the same, byte for byte. On this Mac this model repeats itself on "
              "this task, so one run tells you what the others would. Please tell us that too.")
    print(f"Raw data: {out}/results.csv and {out}/meta.json. "
          "Send them to info@psychosonicconsulting.com if you like.")


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    sub = ap.add_subparsers(dest="cmd", required=True)
    r = sub.add_parser("run", help="send the task N times and grade every answer")
    r.add_argument("model", help="an Ollama model tag, e.g. gpt-oss:20b")
    r.add_argument("--n", type=int, default=10, help="how many runs (default 10)")
    r.add_argument("--out", help="folder for the answers (default repeat-check-<time>)")
    r.add_argument("--host", default="http://127.0.0.1:11434", help="Ollama's address")
    r.add_argument("--timeout", type=int, default=1800, help="seconds to wait for one answer")
    r.add_argument("--num-batch", type=int, help="fix Ollama's prompt batch size, e.g. 512 or 1024")
    g = sub.add_parser("grade", help="grade HTML files with the same checks")
    g.add_argument("files", nargs="+")
    sub.add_parser("prompt", help="print the system line and prompt that are sent")
    args = ap.parse_args()
    if args.cmd == "run":
        run(args)
    elif args.cmd == "grade":
        bad = 0
        for p in args.files:
            errs = grade(open(p, encoding="utf-8").read())
            bad += bool(errs)
            print(f"{p}: {'FAIL: ' + '; '.join(errs) if errs else 'pass'}")
        sys.exit(1 if bad else 0)
    else:
        print("SYSTEM:\n" + SYSTEM + "\n\nPROMPT:\n" + PROMPT)


if __name__ == "__main__":
    main()
