#!/usr/bin/env python3
"""gate.py: a step gate for Claude Code. After every edit it runs the checks for each step the agent has written so
far; a failure goes straight back to the agent (exit 2), so it fixes that step before it builds the next one on it.
It won't let the agent stop while a step is failing, and every N passing steps it stops for you.

Hook it up in .claude/settings.json (see the guide):
  PostToolUse (matcher "Edit|Write|MultiEdit"): python3 /path/to/gate.py
  Stop:                                          python3 /path/to/gate.py --stop

Settings (environment variables, all optional):
  GATE_TESTS             folder of checks, one file per step: test_step01.py, test_step02.py, ...  (default: ./tests)
  GATE_STEPS             how many steps the task has                                               (default: 20)
  GATE_CODE              the file that holds the steps, def step01(...) ...                        (default: pipeline.py)
  GATE_CHECKPOINT_EVERY  stop for a human every N passing steps (0 = never)                        (default: 0)
  GATE_NOTIFY            a command to run at a checkpoint, e.g. "notify-send gate" or a curl to ntfy
  GATE_MAX_REFUSALS      how many times it refuses to let the agent stop before handing it to you  (default: 6)

Standard library only, plus pytest. Logs every run to gate.log beside the checks.
"""
import json
import os
import re
import subprocess
import sys
import time

ROOT = os.environ.get("CLAUDE_PROJECT_DIR", os.getcwd())
TESTS = os.path.abspath(os.path.join(ROOT, os.environ.get("GATE_TESTS", "tests")))
STEPS = int(os.environ.get("GATE_STEPS", "20"))
CODE = os.path.join(ROOT, os.environ.get("GATE_CODE", "pipeline.py"))
EVERY = int(os.environ.get("GATE_CHECKPOINT_EVERY", "0"))
NOTIFY = os.environ.get("GATE_NOTIFY", "")
MAX_REFUSALS = int(os.environ.get("GATE_MAX_REFUSALS", "6"))
STATE = os.path.join(TESTS, ".gate_state.json")
LOG = os.path.join(TESTS, "gate.log")


def log(line):
    with open(LOG, "a") as f:
        f.write(time.strftime("%H:%M:%S ") + line + "\n")


def state(update=None):
    s = json.load(open(STATE)) if os.path.exists(STATE) else {"refusals": 0, "checkpoint": 0, "waiting": False}
    if update:
        s.update(update)
        json.dump(s, open(STATE, "w"))
    return s


def written_steps():
    """Steps whose body is no longer a stub (raise NotImplementedError)."""
    src = open(CODE).read()
    return [m.group(1) for m in re.finditer(r"^def (step\d\d)\(.*?(?=^def |\Z)", src, re.S | re.M)
            if "raise NotImplementedError" not in m.group(0)]


def run_checks(steps):
    files = [f"test_{s}.py" for s in steps if os.path.exists(os.path.join(TESTS, f"test_{s}.py"))]
    if not files:
        return [], ""
    env = dict(os.environ, PYTHONPATH=ROOT, PYTHONDONTWRITEBYTECODE="1")
    p = subprocess.run([sys.executable, "-m", "pytest", "-q", "--tb=short", "-p", "no:cacheprovider", *files],
                       cwd=TESTS, capture_output=True, text=True, timeout=300, env=env)
    failing = set(re.findall(r"(?:FAILED|ERROR) test_(step\d\d)", p.stdout))
    if p.returncode not in (0, 1) and not failing:
        failing = {"(the checks didn't run)"}
    return sorted(failing), p.stdout[-2500:]


def tell_agent(msg):
    print(msg, file=sys.stderr)
    return 2                                   # Claude Code feeds stderr back to the agent


def main():
    stop = "--stop" in sys.argv
    event = json.load(sys.stdin) if not sys.stdin.isatty() else {}
    path = (event.get("tool_input") or {}).get("file_path", "")
    if not stop and path and os.path.abspath(path) != os.path.abspath(CODE):
        return 0                               # an edit somewhere else: nothing to check
    steps = written_steps()
    failing, out = run_checks(steps)
    passing = [s for s in steps if s not in failing]
    if stop and state()["waiting"]:
        log(f"PAUSED  at the checkpoint, {len(passing)}/{STEPS} pass: waiting for the human")
        return 0                               # the agent stopped to ask you: let it
    if not stop and state()["waiting"]:
        state({"waiting": False})              # it's editing again, so you said go on
    if stop:
        missing = [f"step{i:02d}" for i in range(1, STEPS + 1) if f"step{i:02d}" not in steps]
        s = state()
        if (failing or missing) and s["refusals"] < MAX_REFUSALS:
            state({"refusals": s["refusals"] + 1})
            log(f"STOP REFUSED  {len(passing)}/{STEPS} pass  failing {','.join(failing) or '-'}  missing {len(missing)}")
            return tell_agent(f"gate: not done. Failing: {', '.join(failing) or 'none'}. "
                              f"Not written: {', '.join(missing) or 'none'}.\n{out}")
        log(f"DONE  {len(passing)}/{STEPS} steps pass" if not (failing or missing) else
            f"HANDOFF  {len(passing)}/{STEPS} pass after {s['refusals']} refusals: a human takes it from here")
        return 0
    if failing:
        log(f"FAIL  {','.join(failing)}  ({len(passing)}/{len(steps)} written steps pass)")
        return tell_agent(f"gate: {', '.join(failing)} failing its check. Fix it before you write the next step.\n{out}")
    if steps:
        log(f"PASS  {steps[-1]}  ({len(passing)}/{len(steps)} written steps pass)")
    s = state()
    if EVERY and len(passing) // EVERY > s["checkpoint"] and len(passing) < STEPS:
        state({"checkpoint": len(passing) // EVERY, "waiting": True})
        log(f"CHECKPOINT  {len(passing)} steps pass")
        if NOTIFY:
            subprocess.run(NOTIFY + f" 'gate: checkpoint, steps 1-{len(passing)} pass. Your OK before the next one?'",
                           shell=True, timeout=30)
        return tell_agent(f"gate: checkpoint. Steps 1-{len(passing)} pass. Stop here, summarise what you built and "
                          f"what's next, and wait for the human's OK before you write another step.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
