#!/usr/bin/env python3
# codex-hooks-check.py: which of your Codex hooks will Codex actually run?
#
# Codex skips any hook it has no trust record for, and any hook whose hash no
# longer matches the one you trusted. It recomputes that hash from the hook's
# event, matcher, command, timeout and a few other fields, so changing any of
# them, or moving the hook in hooks.json, puts it back under review.
# This script recomputes the same hash and compares it with the record in
# config.toml, so you can see which hooks are being skipped without opening Codex.
#
# Reads only. Checks ~/.codex/hooks.json (or $CODEX_HOME) and the current repo's
# .codex/hooks.json. Not checked: hooks written inline in config.toml, plugin
# and managed hooks, mcp_tool hooks, requirements.toml policies. "runs" means the
# interactive CLI or app: `codex exec` has been reported ignoring saved trust
# (github.com/openai/codex/issues/32491).
# The hash rules come from Codex's source (codex-rs/hooks/src/engine/discovery.rs,
# rust-v0.169.0). If a future Codex changes them, "changed" can be wrong:
# /hooks in Codex is always the final word.
# From https://www.useyappr.com/blog/codex-hooks-not-working
import hashlib, json, os, re, sys

HOME = os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex")
NO_MATCHER = {"UserPromptSubmit", "Stop", "Interrupt", "PreModelRequest", "PostModelRequest"}
SHORT = {"SessionEnd", "Interrupt"}  # timeout defaults to 1 s, capped at 3
CONTEXT = {"PreToolUse", "PostToolUse", "SessionStart", "UserPromptSubmit", "SubagentStart"}
EVENTS = NO_MATCHER | SHORT | CONTEXT | {"PermissionRequest", "PreCompact", "PostCompact", "SubagentStop", "SessionEnd"}

def snake(name):
    return re.sub(r"(?<!^)([A-Z])", r"_\1", name).lower()

def read_config(path):
    """The few things we need from config.toml: hook trust, the hooks switch, trusted projects."""
    state, features, projects = {}, {}, {}
    try:
        text = open(path, encoding="utf-8").read()
    except OSError:
        return state, features, projects
    try:
        import tomllib  # Python 3.11+
        data = tomllib.loads(text)
        return (data.get("hooks", {}).get("state", {}), data.get("features", {}), data.get("projects", {}))
    except ImportError:
        pass
    table = None
    for line in text.splitlines():
        line = line.strip()
        m = re.match(r"""^\[(hooks\.state|projects)\.(?:"((?:[^"\\]|\\.)*)"|'([^']*)')\]$""", line)
        if m:
            key = m.group(2).replace('\\"', '"').replace("\\\\", "\\") if m.group(2) is not None else m.group(3)
            table = (m.group(1), key)
            (state if m.group(1) == "hooks.state" else projects).setdefault(key, {})
            continue
        if line.startswith("["):
            table = ("features", None) if line == "[features]" else None
            continue
        m = re.match(r"""^([A-Za-z_]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(true|false))""", line)
        if not m or table is None:
            continue
        value = m.group(2) if m.group(2) is not None else m.group(3) if m.group(3) is not None else m.group(4) == "true"
        if table[0] == "features":
            features[m.group(1)] = value
        else:
            (state if table[0] == "hooks.state" else projects)[table[1]][m.group(1)] = value
    return state, features, projects

def file_problem(data):
    """Codex refuses the whole file if any one entry doesn't parse (protocol/src/hooks.rs)."""
    if not isinstance(data, dict) or not isinstance(data.get("hooks", {}), dict):
        return "its top level must be {\"hooks\": {...}}"
    for event, groups in data.get("hooks", {}).items():
        if not isinstance(groups, list):
            return "%s must be a list" % event
        for group in groups:
            if not isinstance(group, dict) or not isinstance(group.get("hooks", []), list):
                return "every entry under %s must be {\"matcher\": ..., \"hooks\": [...]}" % event
            if group.get("matcher") is not None and not isinstance(group.get("matcher"), str):
                return "a matcher under %s is not text" % event
            for h in group.get("hooks", []):
                if not isinstance(h, dict) or h.get("type") not in ("command", "mcp_tool", "prompt", "agent"):
                    return "a hook under %s has an unknown type" % event
                t = h.get("timeout")
                if t is not None and (isinstance(t, bool) or not isinstance(t, int) or t < 0):
                    return "a timeout under %s is not a whole number of seconds" % event
                if h.get("type") == "command" and not isinstance(h.get("command"), str):
                    return "a command hook under %s has no command" % event
                if "async" in h and not isinstance(h["async"], bool):
                    return "async under %s must be true or false" % event
    return None

def identity_hash(event, matcher, handler):
    timeout = handler.get("timeout")
    if event in SHORT:
        timeout = min(max(1 if timeout is None else timeout, 1), 3)
    else:
        timeout = max(600 if timeout is None else timeout, 1)
    hook = {"type": "command", "command": handler["command"], "timeout": timeout,
            "async": bool(handler.get("async", False))}
    if handler.get("statusMessage") is not None:
        hook["statusMessage"] = handler["statusMessage"]
    limit = handler.get("additionalContextLimit")
    if event in CONTEXT and limit is not None and limit != 2500:
        hook["additionalContextLimit"] = limit
    ident = {"event_name": snake(event), "hooks": [hook]}
    if event not in NO_MATCHER and matcher is not None:
        ident["matcher"] = matcher
    body = json.dumps(ident, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return "sha256:" + hashlib.sha256(body.encode("utf-8")).hexdigest()

def main():
    state, features, projects = read_config(os.path.join(HOME, "config.toml"))
    all_off = features.get("hooks") is False or features.get("codex_hooks") is False
    if all_off:
        print("Hooks are switched OFF in config.toml ([features] hooks = false). Codex runs none of them.")
    files = [os.path.join(HOME, "hooks.json")]
    top, d = "", os.getcwd()
    while True:  # the repo's top folder, found without running git
        if os.path.exists(os.path.join(d, ".git")):
            top = d
            break
        if os.path.dirname(d) == d:
            break
        d = os.path.dirname(d)
    if top and os.path.isfile(os.path.join(top, ".codex", "hooks.json")):
        files.append(os.path.join(top, ".codex", "hooks.json"))
    trusted_by_hash = {}
    for key, s in state.items():
        if isinstance(s, dict) and s.get("trusted_hash"):
            trusted_by_hash.setdefault(s["trusted_hash"], key)
    skipped = checked = 0
    for path in files:
        if not os.path.isfile(path):
            print("No %s" % path)
            continue
        print("\n%s" % path)
        off = all_off
        if path != files[0] and projects.get(top, {}).get("trust_level") != "trusted":
            print("  This project isn't marked trusted in config.toml, so Codex doesn't load this file.")
            off = True
        try:
            data = json.load(open(path, encoding="utf-8"))
        except ValueError as err:
            print("  Not valid JSON, so Codex can't read it: %s" % err)
            continue
        problem = file_problem(data)
        if problem:
            print("  Codex rejects this whole file: %s" % problem)
            continue
        events = data.get("hooks", {})
        for event, groups in events.items():
            if event not in EVENTS:
                print("  %-18s not an event Codex knows" % event)
                continue
            for gi, group in enumerate(groups or []):
                for hi, handler in enumerate(group.get("hooks", [])):
                    key = "%s:%s:%d:%d" % (path, snake(event), gi, hi)
                    kind = handler.get("type")
                    label = "%-18s" % event
                    if kind in ("prompt", "agent"):
                        print("  %s SKIPPED  Codex doesn't run '%s' hooks yet" % (label, kind)); skipped += 1; continue
                    if kind != "command":
                        print("  %s not checked (%s hook)" % (label, kind)); continue
                    if not str(handler.get("command", "")).strip():
                        print("  %s SKIPPED  empty command" % label); skipped += 1; continue
                    checked += 1
                    record = state.get(key, {}) if isinstance(state.get(key), dict) else {}
                    now = identity_hash(event, group.get("matcher"), handler)
                    if off and record.get("trusted_hash") != now:
                        print("  %s not loaded (see above), and not trusted either" % label); skipped += 1
                    elif record.get("enabled") is False:
                        print("  %s off      you turned it off in /hooks" % label); skipped += 1
                    elif record.get("trusted_hash") == now and off:
                        print("  %s trusted  but not loaded (see above)" % label); skipped += 1
                    elif record.get("trusted_hash") == now:
                        print("  %s trusted  runs" % label)
                    elif record.get("trusted_hash"):
                        print("  %s CHANGED  edited since you trusted it, so Codex skips it" % label); skipped += 1
                    elif trusted_by_hash.get(now, "").startswith(path + ":"):
                        print("  %s MOVED    you trusted it at another position; Codex skips it here" % label); skipped += 1
                    else:
                        print("  %s NEW      never trusted, so Codex skips it" % label); skipped += 1
    print("\n%d checked, %d skipped by Codex." % (checked, skipped))
    if all_off:
        print("Fix: delete 'hooks = false' under [features] in config.toml, then restart Codex.")
    if skipped:
        print("Fix: type /hooks in Codex and trust them. In the Codex app: Review hooks, or Settings > Hooks.")

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