#!/usr/bin/env python3
"""The guard (brief 0210, design nothing-destroyed §3.5): Claude Code's PreToolUse hook on
every Bash call of a run Argoni starts. A courtesy, never counted as a wall: the sandbox and
the deny rules are the walls. It refuses the plain destructive forms (a recursive rm, git
clean, git reset --hard, git push, find -delete, rsync --delete) so the app can show in red
that something tried.

    argoni-guard LOG      the hook's input (JSON) on stdin; LOG is given by the runner

On a chat's Read (brief 0222) it is a check, not a courtesy: Claude Code's Read refuses a link out of
the granted folders by itself (measured), but reads a file with a second name (a hard link to a file
outside) and waits forever on a FIFO; the guard refuses both before the Read, as read_file did. On a
chat's Grep it looks through the folder searched (at most GREP_LOOK entries, links not followed) and
refuses the search when a file there has a second name, or when the folder is too big to look through.

It holds the model's text with the user's rights, so it is minimal (security round 4, V1):
it parses JSON only and starts nothing; it reads at most 256 KB and denies anything larger;
it answers "deny" or nothing, never "allow"; it writes one log, the path the runner gave,
opened without following a link; the runner starts it under sandbox-exec with a profile
that writes only that log and starts no process. Standard library only.

It is best-effort and never a boundary: a shell spelling it does not read (`r\m`, `r''m`), a
Python delete or a redirection gets past it (security r1, F4). What stops harm is the
sandbox, the deny rules and the runner's after-run check.
"""
import json
import os
import re
import stat
import sys
import time

MAX = 256 * 1024
# A command is cut at every separator and read word by word, once: nothing a long or odd
# command could make slow (no pattern that backtracks).
SEPARATORS = re.compile(r"[;&|\n()`{}]|\$\(")
QUOTES = "'\"\\"
GIT_OPTS_WITH_VALUE = ("-C", "-c", "--git-dir", "--work-tree", "--namespace")


def found(words):
    """The destructive form in one command's words, or None. Flags anywhere in the command
    count (`xargs rm -r`, `sh -c 'rm -rf x'`): a courtesy may refuse a little too much."""
    names = set(os.path.basename(w) for w in words)
    flags = set(w for w in words if w.startswith("-"))
    if "rm" in names and ("--recursive" in flags or any(
            not w.startswith("--") and ("r" in w or "R" in w) for w in flags)):
        return "a recursive rm"
    if "find" in names and "-delete" in flags:
        return "find -delete"
    if "rsync" in names and any(w.startswith("--delete") for w in flags):
        return "rsync --delete"
    if "git" in names:
        for i, w in enumerate(words):
            if os.path.basename(w) != "git":
                continue
            j = i + 1
            while j < len(words) and j < i + 12 and words[j].startswith("-"):
                j += 2 if words[j] in GIT_OPTS_WITH_VALUE else 1
            verb = words[j] if j < len(words) else ""
            if verb in ("clean", "push"):
                return "git " + verb
            if verb == "reset" and "--hard" in flags:
                return "git reset --hard"
    return None


def log(path, what):
    """One line in the runner's log for this run: the form refused, never the command."""
    try:
        fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
    except OSError:
        return
    try:
        os.write(fd, (json.dumps({"refused": what}) + "\n").encode())
    finally:
        os.close(fd)


def deny(path, what, reason=None):
    log(path, what)
    sys.stdout.write(json.dumps({"hookSpecificOutput": {
        "hookEventName": "PreToolUse", "permissionDecision": "deny",
        "permissionDecisionReason": reason or "Argoni does not run %s. Nothing was changed." % what}}))
    return 0


def full(name, cwd):
    """A path as the tool takes it: a relative one from the hook's working folder (staff 0222 r2)."""
    if not isinstance(name, str) or not name or "\x00" in name:
        return None
    name = os.path.expanduser(name)
    if not os.path.isabs(name):
        if not isinstance(cwd, str) or not os.path.isabs(cwd):
            return None
        name = os.path.join(cwd, name)
    return name


def odd_file(name):
    """Why a Read of `name` is refused (0222): not a plain file, or a plain file with another name; else None.
    stat follows a link: Claude Code refuses a link that leaves the granted folders itself."""
    if not name:
        return None
    try:
        st = os.stat(name)
    except OSError:
        return None   # nothing there: Read says so
    if stat.S_ISDIR(st.st_mode):
        return None
    if not stat.S_ISREG(st.st_mode):
        return "a read of a file that is not a plain file"
    if st.st_nlink != 1:
        return "a read of a file with another name"
    return None


GREP_LOOK = 20000
GREP_SECONDS = 4   # under the hook's 10 s: a slow disk is refused, never let through by a time-out
# Not looked through: git's own store (local clones hard-link its objects) and node_modules (pnpm installs
# by hard links). A Read of a file in them is still checked on its own.
GREP_SKIP = (".git", "node_modules")


def linked_inside(top):
    """Why a Grep over `top` is refused (0222): a plain file in it with a second name, or more than
    GREP_LOOK entries to look through; else None."""
    if not top:
        return None
    try:
        st = os.stat(top)
    except OSError:
        return None
    if not stat.S_ISDIR(st.st_mode):
        return odd_file(top) and "a search of a file with another name"
    todo, seen, end = [top], 0, time.monotonic() + GREP_SECONDS
    while todo:
        if time.monotonic() > end:
            return "a search of a folder too slow to look through first"
        try:
            with os.scandir(todo.pop()) as it:
                for e in it:
                    seen += 1
                    if seen > GREP_LOOK:
                        return "a search of a folder too big to look through first"
                    try:
                        if e.is_dir(follow_symlinks=False):
                            if e.name not in GREP_SKIP:
                                todo.append(e.path)
                        elif e.is_file(follow_symlinks=False) and e.stat(follow_symlinks=False).st_nlink != 1:
                            return "a search over a file with another name"
                    except OSError:
                        continue
        except OSError:
            continue
    return None


def main(argv):
    if len(argv) != 2:
        return 0
    path = argv[1]
    raw = sys.stdin.buffer.read(MAX + 1)
    if len(raw) > MAX:
        return deny(path, "a command too long to check")
    try:
        call = json.loads(raw.decode("utf-8", "replace"))
    except ValueError:
        return 0
    if isinstance(call, dict) and call.get("tool_name") in ("Read", "Grep"):
        # A check, so it fails closed: any error here refuses the Read or Grep (security 0222 r2).
        try:
            ti = call.get("tool_input") if isinstance(call.get("tool_input"), dict) else {}
            if call["tool_name"] == "Read":
                what = odd_file(full(ti.get("file_path"), call.get("cwd")))
                return deny(path, what, "Argoni does not open that file: it is not a plain file of its own.") if what else 0
            what = linked_inside(full(ti.get("path") or ".", call.get("cwd")))
            return deny(path, what, "Argoni does not search there: %s. Search a smaller folder inside it." % what) if what else 0
        except Exception:
            return deny(path, "a read the guard could not check", "Argoni could not check that file. Try another one.")
    if not isinstance(call, dict) or call.get("tool_name") != "Bash":
        return 0
    tool_input = call.get("tool_input")
    cmd = tool_input.get("command") if isinstance(tool_input, dict) else None
    if not isinstance(cmd, str):
        return 0
    for part in SEPARATORS.split(cmd):
        what = found([w.strip(QUOTES) for w in part.split()])
        if what:
            return deny(path, what)
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv))
    except Exception:   # never a trace with the model's text in it; no answer is "nothing"
        sys.exit(0)
