#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""wombat-gate - queue git writes from many concurrent agents through one local lock.

Several coding agents sharing one working tree will run `git add` / `git commit`
at the same time and collide on `.git/index.lock`. wombat-gate serialises all write
operations on a repository through an flock(2) lock that lives on a *local*
filesystem, commits only the paths you name, retries when a foreign git process
(one not using wombat-gate) holds a git lock, and appends one timing line per
operation to a local log.

Subcommands:
  wombat-gate commit -m MSG [-m MSG ...] [-F FILE] -- PATH...   stage + commit only PATH...
  wombat-gate status [-uno|-unormal|-uall] -- PATH...            status of PATH... (no index lock)
  wombat-gate run -- GIT_ARGS...                                 an allow-listed git command
  wombat-gate who                                                who holds / last held the lock
  wombat-gate log [-n N] [--stats]                               recent timing lines / p50 and p95
  wombat-gate doctor [--json]                                    git lock files: who holds them, are they stale
  wombat-gate integrate --rebase BRANCH --check COMMAND           rebase, validate, fast-forward worktrees

Standard library only. Python >= 3.8, Linux/macOS/WSL (needs fcntl).
"""
from __future__ import annotations

import argparse
try:
    import fcntl
except ImportError:
    raise SystemExit("wombat-gate: native Windows is unsupported (POSIX flock/signals required); use WSL with Linux Git and Python")
import hashlib
import json
import math
import os
import random
import re
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time

__version__ = "0.8.0"

EXIT_OK = 0
EXIT_GIT_ERROR = 1
EXIT_USAGE = 2
EXIT_NOTHING = 3          # nothing to commit in the given paths
EXIT_LOCK_TIMEOUT = 4     # could not get the wombat-gate queue lock in time
EXIT_GIT_LOCK_BUSY = 5    # a foreign git process kept a git lock past all retries
EXIT_INDEX_STALE = 6      # committed, but the shared index could not be updated for the paths

# The one message git prints when another process holds one of its lock files
# (index.lock, HEAD.lock, refs/.../x.lock, config.lock all use it). Anything else
# -- disk full, permissions, ref conflicts, remote rejections -- is not retried.
RETRYABLE = re.compile(r"Unable to create '[^']*\.lock': File exists")
LOCKFILE_IN_MSG = re.compile(r"'([^']+\.lock)'")

# Characters that make a pathspec match more than the literal path.
GLOB_CHARS = set("*?")

# `wombat-gate run` allow-list. Value: (needs the queue lock, safe to retry on a lock collision).
# Everything else -- add, commit, stash, reset, checkout, restore, switch, clean,
# rm, mv, merge, rebase, pull, ... -- touches the shared index / working tree and
# is refused unless --unsafe.
# gc / maintenance are left out: pruning loose objects can race a foreign `git add`.
RUN_ALLOWED = {
    "push": (False, False),      # remote-tracking refs only; can be slow, so no queue
    "fetch": (False, False),
    "tag": (True, True),
    "branch": (True, True),
    "notes": (True, True),
    "log": (False, False),
    "show": (False, False),
    "diff": (False, False),
    "rev-parse": (False, False),
    "ls-files": (False, False),
    "blame": (False, False),
}

# Filesystems on which flock() is either unsupported or not shared between
# processes reliably. The lock must live on a local disk.
NONLOCAL_FS = {"9p", "drvfs", "nfs", "nfs4", "cifs", "smb3", "smbfs", "fuse",
               "fuseblk", "fuse.sshfs", "v9fs", "virtiofs"}


# ---------------------------------------------------------------- helpers

def eprint(*a):
    print(*a, file=sys.stderr, flush=True)


def env_float(name, default):
    try:
        return float(os.environ.get(name, default))
    except ValueError:
        return float(default)


def state_dir():
    d = os.environ.get("WOMBAT_STATE_DIR")
    if not d:
        base = os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state")
        d = os.path.join(base, "wombat-gate")
    os.makedirs(d, exist_ok=True)
    return d


def lock_dir():
    d = os.environ.get("WOMBAT_LOCK_DIR") or os.path.join(state_dir(), "locks")
    os.makedirs(d, exist_ok=True)
    return d


def fs_type(path):
    """Best-effort filesystem type of `path` from /proc/mounts (Linux only)."""
    try:
        path = os.path.realpath(path)
        best, best_t = "", None
        with open("/proc/mounts") as f:
            for line in f:
                parts = line.split()
                if len(parts) < 3:
                    continue
                mnt = parts[1].replace("\\040", " ")
                if (path == mnt or path.startswith(mnt.rstrip("/") + "/")) and len(mnt) >= len(best):
                    best, best_t = mnt, parts[2]
        return best_t
    except OSError:
        return None


def session_name(args):
    return (getattr(args, "session", None) or os.environ.get("WOMBAT_SESSION")
            or "pid%d" % os.getppid())


def git(argv, cwd=None, env_extra=None, capture=True, input=None):
    env = dict(os.environ)
    if env_extra:
        env.update(env_extra)
    # surrogateescape: file names are bytes; a non-UTF-8 one must round-trip, not crash
    return subprocess.run(["git"] + argv, cwd=cwd, env=env, text=True, errors="surrogateescape", input=input,
                          stdout=subprocess.PIPE if capture else None,
                          stderr=subprocess.PIPE if capture else None)


def repo_info(cwd=None):
    """(toplevel, common_dir) of the repository containing cwd."""
    r = git(["rev-parse", "--show-toplevel", "--git-common-dir"], cwd=cwd)
    if r.returncode != 0:
        eprint("wombat-gate: not inside a git repository:", r.stderr.strip())
        sys.exit(EXIT_USAGE)
    top, common = r.stdout.splitlines()[:2]
    if not os.path.isabs(common):
        common = os.path.join(os.getcwd() if cwd is None else cwd, common)
    return top, os.path.realpath(common)


def lock_path_for(common_dir):
    key = hashlib.sha1(common_dir.encode()).hexdigest()[:16]
    name = re.sub(r"[^A-Za-z0-9_.-]", "_", os.path.basename(os.path.dirname(common_dir)) or "repo")
    return os.path.join(lock_dir(), "%s-%s.lock" % (name, key))


def proc_start(pid):
    """Start time of a process in clock ticks since boot (Linux), or None."""
    try:
        with open("/proc/%d/stat" % int(pid)) as f:
            st = f.read()
        return int(st[st.rindex(")") + 2:].split()[19])
    except (OSError, ValueError, IndexError):
        return None


def pid_alive(pid, start=None):
    if not pid:
        return False
    try:
        os.kill(int(pid), 0)
    except ProcessLookupError:
        return False
    except PermissionError:
        pass
    except (OSError, ValueError):
        return False
    if start is not None:
        cur = proc_start(pid)
        if cur is not None and cur != start:
            return False                        # the pid now belongs to another process
    return True


def read_ticket(path):
    try:
        with open(path) as f:
            return json.load(f)
    except (OSError, ValueError, TypeError):
        return None


def log_path():
    return os.environ.get("WOMBAT_LOG") or os.path.join(state_dir(), "wombat-gate.log")


def write_log(rec):
    rec = dict(rec)
    rec.setdefault("ts", time.strftime("%Y-%m-%dT%H:%M:%S%z"))
    line = json.dumps(rec, ensure_ascii=False, sort_keys=False)
    # O_APPEND writes of one short line are atomic enough on a local fs.
    with open(log_path(), "a", encoding="utf-8", errors="backslashreplace") as f:
        f.write(line + "\n")


# Environment variables that mark "this process was started by an AI agent".
# Claude Code sets CLAUDECODE=1 in its Bash tool; WOMBAT_NO_ESCAPES=1 does the same
# for any other setup. Under such a marker the escape hatches (--allow-broad,
# --unsafe) are refused unless a human sets WOMBAT_HUMAN_OVERRIDE=1. Enforcing this
# here covers every shell spelling of the flags (quotes, line continuations,
# variables), which a text-matching hook cannot.
AGENT_MARKERS = ("CLAUDECODE", "CLAUDE_PID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_CODE_ENTRYPOINT",
                 "WOMBAT_NO_ESCAPES", "DINGO_NO_ESCAPES")


def escape_refused(flag):
    if is_agent() and os.environ.get("WOMBAT_HUMAN_OVERRIDE") != "1":
        hit = [m for m in AGENT_MARKERS if os.environ.get(m, "") not in ("", "0")]
        eprint("wombat-gate: refusing %s: it is a human-only escape hatch and this looks like an "
               "agent (%s set). Stop and ask the human; do not try to work around this." % (flag, ", ".join(hit)))
        return True
    return False


def is_agent():
    return any(os.environ.get(m, "") not in ("", "0") for m in AGENT_MARKERS)


def escape_hint(flag):
    """Do not point an agent at an escape hatch it will be refused anyway."""
    if is_agent():
        return " (agents cannot override this; ask a human)"
    return " (pass %s to override)" % flag


def unsafe_hint():
    return escape_hint("--unsafe")


def check_paths(paths, top, allow_broad):
    """Paths must be literal files/directories strictly inside the repository.

    Unless --allow-broad: no pathspec magic (':!x', ':/', ':(glob)...'), no '*' or
    '?' (almost always meant as a glob; pathspecs are passed literally, so a glob
    would silently match nothing), nothing that resolves to the repository root
    or outside it. '[' and ']' are allowed: with GIT_LITERAL_PATHSPECS they only
    match a file of that exact name. Returns that git env."""
    if not paths:
        eprint("wombat-gate: give the paths to act on after `--` (e.g. wombat-gate commit -m msg -- src/mydir)")
        sys.exit(EXIT_USAGE)
    if allow_broad:
        if escape_refused("--allow-broad"):
            sys.exit(EXIT_USAGE)
        return {}
    top_real = os.path.realpath(top)
    for p in paths:
        why = None
        if not p.strip():
            why = "empty path"
        elif p.startswith(":"):
            why = "pathspec magic (':' prefix) is not allowed"
        elif GLOB_CHARS & set(p):
            why = "glob characters are not allowed"
        else:
            # resolve the parent only: git records a symlink itself, not its target
            ap = os.path.abspath(p)
            rp = os.path.join(os.path.realpath(os.path.dirname(ap)), os.path.basename(ap))
            if os.path.basename(ap) in ("", ".", ".."):
                rp = os.path.realpath(ap)
            if rp == top_real:
                why = "this is the whole repository"
            elif not rp.startswith(top_real + os.sep):
                why = "outside the repository"
        if why:
            eprint("wombat-gate: refusing path %r: %s. Name your own files or directories%s"
                   % (p, why, escape_hint("--allow-broad")))
            sys.exit(EXIT_USAGE)
    return {"GIT_LITERAL_PATHSPECS": "1"}


# ---------------------------------------------------------------- the queue lock

class _Deadline(Exception):
    pass


class QueueLock:
    """Exclusive flock on a local file. Released automatically if we die.

    Waits in a blocking flock() (no polling); a SIGALRM interval timer prints
    "still waiting" notes and enforces the timeout."""

    def __init__(self, path, session, op, timeout, quiet=False):
        self.path, self.session, self.op = path, session, op
        self.timeout, self.quiet = timeout, quiet
        self.fd = None
        self.wait_s = 0.0
        self.t_acquired = None

    def holder(self):
        try:
            with open(self.path + ".holder") as f:
                return json.load(f)
        except (OSError, ValueError):
            return None

    def _note(self, waited):
        h = self.holder() or {}
        held = (" for %.0fs" % (time.time() - h["t"])) if isinstance(h.get("t"), (int, float)) else ""
        eprint("wombat-gate: waiting %.0fs for queue (held by %s: %s, pid %s%s)"
               % (waited, h.get("session", "?"), h.get("op", "?"), h.get("pid", "?"), held))

    def __enter__(self):
        t = fs_type(os.path.dirname(self.path))
        if t in NONLOCAL_FS or (t or "").startswith("fuse"):
            eprint("wombat-gate: warning: lock dir %s is on a %s filesystem; flock may not "
                   "serialise there. Set WOMBAT_LOCK_DIR to a local disk." % (os.path.dirname(self.path), t))
        self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT, 0o644)
        t0 = time.monotonic()
        try:
            fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            self._wait_blocking(t0)
        self.t_acquired = time.monotonic()
        self.wait_s = self.t_acquired - t0
        try:
            tmp = self.path + ".holder.%d" % os.getpid()
            with open(tmp, "w") as f:
                json.dump({"session": self.session, "op": self.op, "pid": os.getpid(),
                           "host": socket.gethostname(), "t": time.time(),
                           "since": time.strftime("%Y-%m-%dT%H:%M:%S%z")}, f, ensure_ascii=False)
            os.replace(tmp, self.path + ".holder")
        except OSError:
            pass
        return self

    def _wait_blocking(self, t0):
        deadline = t0 + self.timeout
        every = max(0.05, env_float("WOMBAT_NOTE_EVERY", 15))
        done = [False]

        def arm():
            # one-shot timer to the next note or the deadline, whichever comes first
            signal.setitimer(signal.ITIMER_REAL, max(0.01, min(every, deadline - time.monotonic())))

        def on_alarm(signum, frame):
            if done[0]:
                return
            now = time.monotonic()
            if now >= deadline:
                raise _Deadline()
            if not self.quiet:
                self._note(now - t0)
            arm()
            # flock() is restarted automatically after the handler returns (PEP 475)

        old = signal.signal(signal.SIGALRM, on_alarm)
        try:
            try:
                try:
                    arm()
                    fcntl.flock(self.fd, fcntl.LOCK_EX)
                finally:
                    signal.setitimer(signal.ITIMER_REAL, 0)
                    done[0] = True
            except _Deadline:
                # The alarm may have fired just after flock() returned; if we hold the
                # lock anyway (re-locking our own fd succeeds), keep it.
                try:
                    fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
                except BlockingIOError:
                    h = self.holder() or {}
                    os.close(self.fd)
                    self.fd = None
                    self.wait_s = time.monotonic() - t0
                    eprint("wombat-gate: gave up after %.0fs waiting for the queue lock; held by %s"
                           % (self.wait_s, json.dumps(h, ensure_ascii=False)))
                    raise TimeoutError
        finally:
            signal.signal(signal.SIGALRM, old)

    def __exit__(self, *exc):
        if self.fd is not None:
            fcntl.flock(self.fd, fcntl.LOCK_UN)
            os.close(self.fd)
            self.fd = None
        return False

    @property
    def hold_s(self):
        return 0.0 if self.t_acquired is None else time.monotonic() - self.t_acquired


def git_lock_diagnosis(stderr):
    """Describe the git lock file named in an error message (age, live git processes)."""
    m = LOCKFILE_IN_MSG.search(stderr or "")
    parts = []
    if m and os.path.exists(m.group(1)):
        age = time.time() - os.path.getmtime(m.group(1))
        parts.append("%s exists, age %.0fs" % (m.group(1), age))
    try:
        ps = subprocess.run(["pgrep", "-a", "-x", "git"], text=True, stdout=subprocess.PIPE,
                            stderr=subprocess.DEVNULL).stdout.strip()
        parts.append("live git processes: %s" % (ps.replace("\n", " | ") if ps else "none"))
    except OSError:
        pass
    return "; ".join(parts)


def git_retry(argv, stats, env_extra=None, input=None, step=None):
    """Run git; on a lock-collision error, back off and retry.

    Returns CompletedProcess; sets .lock_busy when the lock never cleared."""
    tries = int(env_float("WOMBAT_GIT_RETRIES", 8))
    delay = env_float("WOMBAT_GIT_BACKOFF", 0.5)
    cap = env_float("WOMBAT_GIT_BACKOFF_MAX", 20)
    for i in range(tries + 1):
        t = time.monotonic()
        r = git(argv, env_extra=env_extra, input=input)
        dt = time.monotonic() - t
        stats["git_s"] = stats.get("git_s", 0.0) + dt
        if step:  # per-step wall time, rounded at log time (see finish)
            steps = stats.setdefault("steps", {})
            steps[step] = steps.get(step, 0.0) + dt
        r.lock_busy = False
        if r.returncode == 0 or not RETRYABLE.search(r.stderr or ""):
            return r
        if i == tries:
            r.lock_busy = True
            r.stderr += "\nwombat-gate: still locked after %d retries; %s\n" % (tries, git_lock_diagnosis(r.stderr))
            return r
        stats["retries"] = stats.get("retries", 0) + 1
        wait = min(cap, delay * (2 ** i)) * random.uniform(0.7, 1.3)
        eprint("wombat-gate: git lock busy (%s); retry %d/%d in %.1fs"
               % (RETRYABLE.search(r.stderr).group(0)[:120], i + 1, tries, wait))
        time.sleep(wait)
    return r  # not reached


def timed(rec, step, fn, *a, **kw):
    """Run fn and charge its wall time to rec["steps"][step] and rec["git_s"]."""
    t = time.monotonic()
    try:
        return fn(*a, **kw)
    finally:
        dt = time.monotonic() - t
        rec["git_s"] = rec.get("git_s", 0.0) + dt
        steps = rec.setdefault("steps", {})
        steps[step] = steps.get(step, 0.0) + dt


def finish(rec, rc):
    rec["rc"] = rc
    for k in ("wait_s", "hold_s", "git_s", "total_s"):
        if k in rec:
            rec[k] = round(rec[k], 3)
    if "steps" in rec:
        rec["steps"] = {k: round(v, 3) for k, v in rec["steps"].items()}
    try:
        write_log(rec)
    except OSError as e:
        eprint("wombat-gate: could not write log:", e)
    return rc


def finish_locked(rec, lk, t0, rc):
    rec["hold_s"] = lk.hold_s
    rec["t_rel"] = time.time()
    rec["mono_acq"], rec["mono_rel"] = lk.t_acquired, time.monotonic()
    rec["total_s"] = time.monotonic() - t0
    return finish(rec, rc)


def fail_rc(r):
    return EXIT_GIT_LOCK_BUSY if getattr(r, "lock_busy", False) else EXIT_GIT_ERROR


# ---------------------------------------------------------------- subcommands

def stage_named(paths, env, cwd=None, stats=None, argv=None):
    """Skip only deletions already absent from disk and index but known to HEAD."""
    top, _ = repo_info(cwd)
    rels = [os.path.relpath(os.path.abspath(os.path.join(cwd or os.getcwd(), p)), top).replace(os.sep, "/") for p in paths]
    indexed = check_step(git(["ls-files", "-z", "--"] + rels, cwd=top, env_extra=env), "ls-files").stdout
    head = head_sha(cwd)
    known = (check_step(git(["ls-tree", "-z", "--name-only", head, "--"] + rels,
                           cwd=top, env_extra=env), "ls-tree").stdout if head else "")
    ix, hs = set(indexed.split("\0")), set(known.split("\0"))
    selected = []
    for p, rel in zip(paths, rels):
        tracked = any(x == rel or x.startswith(rel.rstrip("/") + "/") for x in ix if x)
        if not os.path.lexists(os.path.join(cwd or os.getcwd(), p)) and not tracked and rel in hs:
            continue
        selected.append(p)
    if not selected:
        return subprocess.CompletedProcess([], 0, "", "")
    command = (argv or ["add", "-A"]) + ["--"] + selected
    if stats is not None:
        return git_retry(command, stats, env_extra=env, step="add")
    return git(command, cwd=cwd, env_extra=env)


def seed_deleted_for_classic(paths, lit):
    """Make staged deletions discoverable to git commit --only's path matching.

    Seed just missing HEAD entries; --only stages their working-tree deletion.
    The caller restores its original snapshot if commit fails.
    """
    if not head_sha():
        return
    top, _ = repo_info()
    rels = repo_rel_paths(paths, top)
    ix = check_step(git(["ls-files", "-z", "--full-name", "--"] + rels, cwd=top, env_extra=lit), "ls-files")
    existing = set(ix.stdout.split("\0"))
    tree = check_step(git(["ls-tree", "-r", "-z", "--full-tree", "HEAD", "--"] + rels, cwd=top, env_extra=lit), "ls-tree")
    entries = []
    for row in tree.stdout.split("\0"):
        if not row:
            continue
        meta, name = row.split("\t", 1)
        if name not in existing and not os.path.lexists(os.path.join(top, name)):
            mode, typ, sha = meta.split()
            entries.append("%s %s\t%s\0" % (mode, sha, name))
    if entries:
        check_step(git(["update-index", "-z", "--index-info"], env_extra=lit,
                       input="".join(entries)), "seed-deletions")


def commit_preview(args, top, lit):
    """Stage in a copy; one output row per changed path, including both rename ends."""
    with tempfile.TemporaryDirectory(prefix="wombat-preview-") as tmp:
        idx = os.path.join(tmp, "index")
        gp = git_paths(top)
        if os.path.exists(gp["index"]):
            shutil.copy2(gp["index"], idx)
        env = dict(lit, GIT_INDEX_FILE=idx, GIT_OPTIONAL_LOCKS="0")
        check_step(stage_named(args.paths, env), "preview-add")
        r = check_step(git(["diff", "--cached", "--no-renames", "--name-status", "-z", "--"] + args.paths,
                          env_extra=env), "preview-diff")
        fields = r.stdout.rstrip("\0").split("\0") if r.stdout else []
        rows = list(zip(fields[::2], fields[1::2]))
        ren = check_step(git(["diff", "--cached", "--find-renames", "--name-status", "-z", "--"] + args.paths,
                            env_extra=env), "preview-renames").stdout.split("\0")
        pairs, i = [], 0
        while i < len(ren) and ren[i]:
            if ren[i].startswith("R"):
                pairs.append((ren[i + 1], ren[i + 2]))
                i += 3
            else:
                i += 2
        paired = {p for pair in pairs for p in pair}
        for status, path in rows:
            print("%s\t%s" % ("R" if path in paired else status, json.dumps(path, ensure_ascii=False)))
        deleted = sum(s == "D" and p not in paired for s, p in rows)
        print("wombat-gate: 删 %d / 改名 %d / 改 %d; files=%d; named=%d" %
              (deleted, len(pairs), len(rows) - deleted - 2 * len(pairs), len(rows), len(args.paths)))
        if args.expect_files is not None and len(rows) != args.expect_files:
            eprint("wombat-gate: reviewed file count mismatch; expected %d, found %d" % (args.expect_files, len(rows)))
            return EXIT_USAGE
        return EXIT_OK if rows else EXIT_NOTHING


def cmd_commit(args):
    t0 = time.monotonic()
    top, common = repo_info()
    lit = check_paths(args.paths, top, args.allow_broad)
    if not args.message and not args.file:
        eprint("wombat-gate: commit needs -m MSG or -F FILE")
        return EXIT_USAGE
    # Read the message once, so a retry can resend it (-F - would be consumed).
    msg = "\n\n".join(args.message or [])
    if args.file:
        try:
            with (sys.stdin if args.file == "-" else open(args.file, encoding="utf-8")) as f:
                body = f.read()
        except OSError as e:
            eprint("wombat-gate: cannot read message file:", e)
            return EXIT_USAGE
        msg = msg + "\n\n" + body if msg else body
    sess = session_name(args)
    rec = {"op": "commit", "session": sess, "repo": top, "n_paths": len(args.paths),
           "paths": args.paths[:5], "retries": 0}

    if args.dry_run:
        try:
            return commit_preview(args, top, lit)
        except (GitStepFailed, HeadUnreadable, OSError) as e:
            eprint("wombat-gate: preview failed:", getattr(getattr(e, "r", None), "stderr", str(e)))
            return EXIT_GIT_ERROR

    try:
        lk = QueueLock(lock_path_for(common), sess, "commit", args.timeout).__enter__()
    except TimeoutError:
        rec.update(wait_s=time.monotonic() - t0, total_s=time.monotonic() - t0, result="queue_timeout")
        return finish(rec, EXIT_LOCK_TIMEOUT)
    try:
        rec["wait_s"], rec["t_acq"] = lk.wait_s, time.time()
        try:
            if args.expect_files is not None:
                rc = commit_preview(args, top, lit)
                if rc != EXIT_OK:
                    rec["result"] = "preview_rejected"
                    return finish_locked(rec, lk, t0, rc)
            why_classic, gp, cfg = classic_reason(args, top)
            if why_classic is not None:     # the classic path also clears our own leftover lock
                gpr = gp or git_paths(top)
                if gpr and os.path.exists(gpr["index"] + ".lock"):
                    IndexLock(gpr["index"], ticket=lk.path + ".gitlock", session=lk.session).reclaim(rec)
            if why_classic is None:
                rec["mode"] = "fast"
                rc = fast_commit(args, top, lit, msg, rec, lk, t0, gp, cfg)
                if rc is not FALLBACK:
                    return rc
                rec["mode"] = "classic"  # classic_reason was set by fast_commit
                return classic_commit(args, lit, msg, rec, lk, t0)
            rec.update(mode="classic", classic_reason=why_classic)
            return classic_commit(args, lit, msg, rec, lk, t0)
        except HeadUnreadable as e:
            # 0.5 read a failed `rev-parse HEAD` as "HEAD moved" and blamed a foreign
            # commit (seen twice on 10-05 while the 9p mount was failing)
            eprint("wombat-gate: cannot read HEAD (%s). The repository may sit on a failing mount; "
                   "nothing was assumed about other processes. Check `wombat-gate status -- %s` "
                   "once the disk is readable." % (e, " ".join(args.paths)))
            rec["result"] = "head_unreadable"
            return finish_locked(rec, lk, t0, EXIT_GIT_ERROR)
    finally:
        lk.__exit__(None, None, None)


def classic_commit(args, lit, msg, rec, lk, t0):
    """0.5 path: `git add -A -- PATH` + `git commit -- PATH` on the shared index."""
    # 0) remember the index entries under the paths, to put them back on failure
    snap = git_retry(["ls-files", "-s", "-z", "--full-name", "--"] + args.paths, rec, env_extra=lit, step="snapshot")
    if snap.returncode != 0:
        eprint(snap.stderr.rstrip())
        rec["result"] = "snapshot_failed"
        return finish_locked(rec, lk, t0, fail_rc(snap))
    snap, head0 = snap.stdout, head_sha()  # None only for an unborn branch
    # 1) stage only the named paths (adds, modifications and deletions under them)
    r = stage_named(args.paths, lit, stats=rec)
    if r.returncode != 0:
        eprint(r.stderr.rstrip())
        rec["result"] = "add_failed"
        timed(rec, "restore", restore_index, snap, head0, args.paths, lit)
        return finish_locked(rec, lk, t0, fail_rc(r))
    # 2) anything to commit under those paths? (index vs HEAD, path-limited)
    # --no-renames: we only need the list; rename detection cost 7 of 8 s on a slow mount
    r = git_retry(["diff", "--cached", "--no-renames", "--name-status", "--"] + args.paths, rec, env_extra=lit, step="diff")
    if r.returncode != 0:
        eprint(r.stderr.rstrip())
        rec["result"] = "diff_failed"
        timed(rec, "restore", restore_index, snap, head0, args.paths, lit)
        return finish_locked(rec, lk, t0, fail_rc(r))
    changed = [l for l in r.stdout.splitlines() if l.strip()]
    if not changed:
        eprint("wombat-gate: nothing to commit under", " ".join(args.paths))
        rec["result"] = "nothing"
        return finish_locked(rec, lk, t0, EXIT_NOTHING)
    rec["n_files"] = len(changed)
    if args.expect_files is not None and len(changed) != args.expect_files:
        eprint("wombat-gate: changed file count moved since preview; nothing committed")
        timed(rec, "restore", restore_index, snap, head0, args.paths, lit)
        rec["result"] = "count_changed"
        return finish_locked(rec, lk, t0, EXIT_USAGE)
    # 3) commit only those paths; other staged entries in the index stay staged.
    # A lock collision makes git fail before it writes anything, so a plain retry
    # is safe. (0.2 treated "HEAD moved" as "our commit landed"; HEAD usually
    # moves because the *other* process committed, so that was wrong.)
    argv = ["commit", "-F", "-"] + (["--no-verify"] if args.no_verify else []) + ["--"] + args.paths
    try:
        seed_deleted_for_classic(args.paths, lit)
    except GitStepFailed as e:
        eprint(e.r.stderr)
        timed(rec, "restore", restore_index, snap, head0, args.paths, lit)
        return finish_locked(rec, lk, t0, fail_rc(e.r))
    r = git_retry(argv, rec, env_extra=lit, input=msg, step="commit")
    if r.returncode != 0 and head_after(head0) != head0:
        # A foreign (non-wombat-gate) process committed meanwhile. Either its bare
        # `git commit` took our staged paths, or its index write dropped our
        # staging. Only the *working tree* tells these apart: if nothing under
        # our paths differs from HEAD (tracked or untracked), our changes are in
        # HEAD; otherwise stage and commit once more from scratch.
        st = timed(rec, "swept_check", git,
                   ["status", "--porcelain", "--no-renames", "--untracked-files=all", "--"] + args.paths,
                   env_extra=dict(lit, GIT_OPTIONAL_LOCKS="0"))
        if st.returncode == 0 and not st.stdout.strip():
            head_now = head_after(head0) or "?"
            eprint("wombat-gate: your changes under %s were already committed by another "
                   "process (HEAD is now %s, not made by wombat-gate); nothing left to commit"
                   % (" ".join(args.paths), head_now[:12]))
            rec.update(result="swept_by_foreign", foreign_head=head_now[:12])
            return finish_locked(rec, lk, t0, EXIT_NOTHING)
        rec["redo"] = 1
        ra = stage_named(args.paths, lit, stats=rec)
        if ra.returncode != 0:
            eprint(ra.stderr.rstrip())
            rec["result"] = "redo_add_failed"
            timed(rec, "restore", restore_index, snap, head0, args.paths, lit)  # HEAD moved: warns, leaves index
            return finish_locked(rec, lk, t0, fail_rc(ra))
        if args.expect_files is not None:
            eprint("wombat-gate: HEAD moved after preview; review paths again before retrying")
            rec["result"] = "head_moved_after_preview"
            return finish_locked(rec, lk, t0, EXIT_GIT_ERROR)
        try:
            seed_deleted_for_classic(args.paths, lit)
        except GitStepFailed as e:
            eprint(e.r.stderr)
            timed(rec, "restore", restore_index, snap, head0, args.paths, lit)
            return finish_locked(rec, lk, t0, fail_rc(e.r))
        r = git_retry(argv, rec, env_extra=lit, input=msg, step="commit")
    if r.returncode != 0:
        eprint((r.stdout or "").rstrip())
        eprint(r.stderr.rstrip())
        rec["result"] = "commit_failed"
        # leave the shared index as we found it for these paths
        timed(rec, "restore", restore_index, snap, head0, args.paths, lit)
        return finish_locked(rec, lk, t0, fail_rc(r))
    # Our sha comes from git's own output, not from HEAD (which a foreign
    # process may have moved already).
    m = re.search(r"^\[[^\]]* ([0-9a-f]{7,40})\]", r.stdout or "", re.M)
    sha = m.group(1) if m else None
    rec.update(result="committed", commit=sha)
    if sha is None:
        rec["result"] = "committed_sha_unknown"
        eprint("wombat-gate: warning: commit succeeded but its sha was not found in git's output")
    else:
        # what actually went into the commit (a foreign commit may have taken
        # some of the files diffed before committing)
        dt = timed(rec, "diff_tree", git, ["diff-tree", "--no-commit-id", "--name-status", "-r", "--root", sha])
        if dt.returncode == 0:
            changed = [l for l in dt.stdout.splitlines() if l.strip()]
            rec["n_files"] = len(changed)
    if not args.quiet:
        print("wombat-gate: committed %s (%d file%s)" % (sha or "?", len(changed), "" if len(changed) == 1 else "s"))
        print("\n".join(changed))
    return finish_locked(rec, lk, t0, EXIT_OK)


class HeadUnreadable(Exception):
    pass


def head_sha(cwd=None):
    """HEAD's sha, or None for an unborn branch. Any other failure (an I/O error on a
    dying mount prints to stderr even under -q) raises HeadUnreadable."""
    r = git(["rev-parse", "--verify", "-q", "HEAD"], cwd=cwd)
    if r.returncode == 0:
        return r.stdout.strip()
    if (r.stderr or "").strip():
        raise HeadUnreadable(r.stderr.strip().splitlines()[-1])
    return None


def head_after(head0, cwd=None):
    """HEAD now. A branch that had a commit cannot become unborn again, so a None here
    means HEAD could not be read -- not that someone moved it."""
    h = head_sha(cwd)
    if h is None and head0 is not None:
        raise HeadUnreadable("HEAD was %s and now reads as missing" % head0[:12])
    return h


# ---------------------------------------------------------------- fast commit (0.6)
#
# `git commit -- PATH` refreshes the whole shared index first: one lstat() per tracked
# file (22k files took 25-85 s on a 9p/drvfs mount, tens of thousands of 9p requests).
# The fast path does what `git add -A -- PATH && git commit -- PATH` does, without
# looking at the working tree outside PATH:
#   1. take the shared index's lock the way git does (create `index.lock` with
#      O_EXCL; back off and retry while someone else has it). From here until the
#      end no other git process can write the index -- in particular no bare
#      `git commit` can slip in between our ref update and our index write;
#   2. copy the shared index to a private file on the local disk and run
#      `git add -A -- PATH` on the copy (stat data is kept, so unchanged files are
#      not re-read; entries staged by others, force-added files etc. stay as they are);
#   3. `write-tree` the copy, take just PATH's entries from that tree and graft them
#      onto HEAD's tree with `ls-tree` + `mktree`, one directory level at a time
#      (cost ~ depth of PATH; a full `read-tree HEAD` alone took 19.5 s there);
#   4. message hooks, `commit-tree`, then `update-ref HEAD NEW OLD` -- a compare-
#      and-swap: if HEAD moved anyway (plumbing, another worktree), re-graft onto it;
#   5. write the copy into `index.lock` and rename it over the index, as git does.
#      post-commit runs after that.
# Selftest: tree, index and message compared with real `git commit` on copies of
# the same repository.

EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
MAX_REBUILDS = 5
CAS_FAILED = re.compile(r"but expected|reference already exists")
GIT_PATHS = ("hooks/pre-commit", "hooks/prepare-commit-msg", "hooks/commit-msg", "hooks/post-commit",
             "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "index")
ADD_ALL = ["add", "--all"]
CFG_KEYS = ("core.filemode", "core.sparsecheckout", "core.splitindex", "core.ignorecase",
            "commit.cleanup", "commit.gpgsign")


def git_cfg(top):
    """The config values the fast path needs, in one call (keys lower-cased), or None."""
    r = git(["config", "-z", "--get-regexp", "^(%s)$" % "|".join(k.replace(".", r"\.") for k in CFG_KEYS)], cwd=top)
    if r.returncode not in (0, 1):  # 1 = none of the keys set
        return None
    out = {}
    for item in (r.stdout or "").split("\0"):
        if item:
            k, _, v = item.partition("\n")
            out[k.lower()] = v
    return out


def cfg_bool(v, default):
    if v is None:
        return default
    return v.strip().lower() in ("", "true", "yes", "on", "1")  # a bare `key` means true


def git_paths(top):
    """Absolute paths of hooks (--git-path honours core.hooksPath), state files and
    the index (GIT_INDEX_FILE, if the caller set it, wins -- as in git)."""
    argv = ["rev-parse"]
    for p in GIT_PATHS:
        argv += ["--git-path", p]
    r = git(argv, cwd=top)
    lines = (r.stdout or "").splitlines()
    if r.returncode != 0 or len(lines) != len(GIT_PATHS):
        return None
    out = {k: (v if os.path.isabs(v) else os.path.join(top, v)) for k, v in zip(GIT_PATHS, lines)}
    if os.environ.get("GIT_INDEX_FILE"):
        out["index"] = os.path.abspath(os.environ["GIT_INDEX_FILE"])
    return out


def hook_file(paths, name):
    p = paths["hooks/" + name]
    return p if os.path.isfile(p) and os.access(p, os.X_OK) else None


def case_mismatch(top, rels, head):
    """On a case-insensitive checkout, a path spelled with the wrong case would be
    grafted as a second, case-duplicate entry. True if some rel is not spelled
    exactly as on disk (or, if gone from disk, as in HEAD)."""
    for rel in rels:
        d = top
        on_disk = True
        for comp in rel.split("/"):
            try:
                names = os.listdir(d)
            except OSError:
                on_disk = False
                break
            if comp not in names:
                if any(n.lower() == comp.lower() for n in names):
                    return True
                on_disk = False
                break
            d = os.path.join(d, comp)
        if not on_disk and head:
            r = git(["ls-tree", "--name-only", "-z", "--full-tree", head, "--", rel], cwd=top,
                    env_extra={"GIT_LITERAL_PATHSPECS": "1"})
            if r.returncode != 0:
                return True
    return False


def classic_reason(args, top):
    """(why this commit has to go through plain `git commit` or None, git paths, config)."""
    mode = os.environ.get("WOMBAT_COMMIT_MODE", "fast")
    if mode == "classic":
        return "WOMBAT_COMMIT_MODE=classic", None, None
    if mode != "fast":
        eprint("wombat-gate: warning: WOMBAT_COMMIT_MODE=%r is neither fast nor classic; using fast" % mode)
    if args.allow_broad:
        return "--allow-broad pathspecs", None, None
    gp, cfg = git_paths(top), git_cfg(top)
    if gp is None or cfg is None:
        return "git rev-parse --git-path / git config failed", None, None
    for state in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD"):
        if os.path.exists(gp[state]):
            return "%s exists" % state, gp, cfg
    if not args.no_verify and hook_file(gp, "pre-commit"):
        return "a pre-commit hook", gp, cfg
    for key, why in (("core.sparsecheckout", "sparse checkout"), ("core.splitindex", "split index"),
                     ("commit.gpgsign", "commit.gpgSign (commit-tree would not sign)")):
        if cfg_bool(cfg.get(key), False):
            return why, gp, cfg
    if cfg_bool(cfg.get("core.ignorecase"), False):
        head = head_sha(top)
        if case_mismatch(top, repo_rel_paths(args.paths, top), head):
            return "a path spelled with different case than on disk (core.ignorecase)", gp, cfg
    return None, gp, cfg


def repo_rel_paths(paths, top):
    """check_paths()-style resolution to repository-relative '/' paths, without
    duplicates or paths inside another given path."""
    top_real = os.path.realpath(top)
    rels = set()
    for p in paths:
        ap = os.path.abspath(p)
        rp = os.path.join(os.path.realpath(os.path.dirname(ap)), os.path.basename(ap))
        if os.path.basename(ap) in ("", ".", ".."):
            rp = os.path.realpath(ap)
        rels.add(os.path.relpath(rp, top_real).replace(os.sep, "/"))
    return sorted(r for r in rels if not any(r.startswith(o + "/") for o in rels))


def run_hook(hook, argv, top, index=None):
    env = dict(os.environ, GIT_EDITOR=":", GIT_LITERAL_PATHSPECS="1")
    if index:
        env["GIT_INDEX_FILE"] = index
    return subprocess.run([hook] + argv, cwd=top, env=env, text=True, errors="replace",
                          stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE)


def show_hook_output(h):
    sys.stdout.write(h.stdout or "")
    sys.stdout.flush()
    sys.stderr.write(h.stderr or "")
    sys.stderr.flush()


def clean_message(msg, cleanup, top):
    """What `git commit -F` does to the message: whitespace cleanup by default (no
    editor), comment stripping only with commit.cleanup=strip, nothing with verbatim."""
    mode = (cleanup or "default").strip().lower()
    if mode not in ("default", "verbatim", "whitespace", "strip", "scissors"):
        raise RuntimeError("Invalid cleanup mode %s" % cleanup)
    if mode == "verbatim":
        return msg
    r = git(["stripspace"] + (["--strip-comments"] if mode == "strip" else []), cwd=top, input=msg)
    if r.returncode != 0:
        raise RuntimeError("git stripspace: %s" % r.stderr.strip())
    return r.stdout


def split_ls(out):
    """{path: 'mode type sha'} (ls-tree -z) or {path: 'mode sha stage'} (ls-files -s -z)."""
    res = {}
    for item in (out or "").split("\0"):
        if item:
            meta, path = item.split("\t", 1)
            res[path] = meta
    return res


class GitStepFailed(Exception):
    def __init__(self, r, step):
        Exception.__init__(self, step)
        self.r, self.step = r, step


def check_step(r, step):
    if r.returncode != 0:
        raise GitStepFailed(r, step)
    return r


def graft(top, base_tree, changes):
    """base_tree with `changes` applied -- {name: 'mode type sha' | None (delete) |
    {nested changes}} -- written with mktree. None if the result is empty."""
    entries = {}
    if base_tree:
        entries = split_ls(check_step(git(["ls-tree", "-z", "--full-tree", base_tree], cwd=top), "graft").stdout)
    for name, ch in changes.items():
        if isinstance(ch, dict):
            old = (entries.get(name) or "").split()
            new = graft(top, old[2] if len(old) == 3 and old[1] == "tree" else None, ch)
            if new is None:
                entries.pop(name, None)  # git keeps no empty directories
            else:
                entries[name] = "040000 tree " + new
        elif ch is None:
            entries.pop(name, None)
        else:
            entries[name] = ch
    if not entries:
        return None
    r = check_step(git(["mktree", "-z", "--missing"], cwd=top,
                       input="".join("%s\t%s\0" % (meta, name) for name, meta in entries.items())), "graft")
    return r.stdout.strip()


class IndexLock:
    """git's own lock on the shared index: `<index>.lock` created with O_EXCL. While we
    hold it no git process can write the index. commit() renames our new index over
    the old one (that also releases the lock); release() removes the lock file --
    only if it is still the file we created."""

    def __init__(self, index, ticket=None, session=None):
        self.index, self.path, self.fd, self.ino = index, index + ".lock", None, None
        self.ticket, self.session = ticket, session

    def _refresh_ticket(self):
        """commit() writes into the lock file and sets its mtime; record the new mtime so a
        kill at that point still leaves a lock the next run recognises."""
        if not self.ticket or self.fd is None and not os.path.exists(self.path):
            return
        try:
            t = read_ticket(self.ticket)
            if not t or t.get("pid") != os.getpid():
                return
            st = os.stat(self.path)
            t["ino"], t["mtime_ns"] = st.st_ino, st.st_mtime_ns
            tmp = self.ticket + ".%d" % os.getpid()
            with open(tmp, "w") as f:
                json.dump(t, f)
            os.replace(tmp, self.ticket)
        except OSError:
            pass

    def _write_ticket(self):
        """Note, on the local disk, exactly which lock file we created (inode + mtime), so
        that if we are killed while holding it the next wombat-gate can recognise it."""
        if not self.ticket:
            return
        try:
            st = os.fstat(self.fd)
            tmp = self.ticket + ".%d" % os.getpid()
            with open(tmp, "w") as f:
                json.dump({"pid": os.getpid(), "start": proc_start(os.getpid()), "session": self.session,
                           "lock": self.path, "ino": st.st_ino, "mtime_ns": st.st_mtime_ns,
                           "t": time.time()}, f)
            os.replace(tmp, self.ticket)
        except OSError:
            pass

    def reclaim(self, rec):
        """The only lock file wombat-gate ever deletes: one that our ticket says a wombat-gate
        process created, when that process is dead and the file is still that very file.
        The caller holds the queue lock, so no other wombat-gate is inside."""
        t = read_ticket(self.ticket)
        if not t or t.get("lock") != self.path or not isinstance(t.get("pid"), int) or t.get("pid") == os.getpid():
            return False                        # a ticket without a proper pid is not trusted
        if pid_alive(t.get("pid"), t.get("start")):
            return False
        try:
            st = os.stat(self.path)
        except FileNotFoundError:
            return True                         # gone meanwhile: just retry
        if st.st_ino != t.get("ino") or st.st_mtime_ns != t.get("mtime_ns"):
            return False                        # a different file now: not ours
        try:
            os.remove(self.path)
        except FileNotFoundError:
            pass
        age = time.time() - st.st_mtime
        rec["stale_lock_removed"] = {"pid": t.get("pid"), "session": t.get("session"), "age_s": round(age, 1)}
        eprint("wombat-gate: removed %s left by wombat-gate pid %s (%s), which died holding it %.0fs ago"
               % (self.path, t.get("pid"), t.get("session") or "?", age))
        write_log({"op": "stale_lock_removed", "lock": self.path, "ticket": t, "age_s": round(age, 1),
                   "t": time.strftime("%Y-%m-%dT%H:%M:%S%z")})
        try:
            os.remove(self.ticket)
        except OSError:
            pass
        return True

    def take(self, rec):
        tries = int(env_float("WOMBAT_GIT_RETRIES", 8))
        delay = env_float("WOMBAT_GIT_BACKOFF", 0.5)
        cap = env_float("WOMBAT_GIT_BACKOFF_MAX", 20)
        t = time.monotonic()
        reclaimed = False
        try:
            i = 0
            while i <= tries:
                try:
                    self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o666)
                    self.ino = os.fstat(self.fd).st_ino
                    self._write_ticket()
                    if os.environ.get("WOMBAT_TEST_DIE_HOLDING_LOCK") == "1":   # self-test only
                        os.kill(os.getpid(), signal.SIGKILL)
                    return True
                except FileExistsError:
                    if not reclaimed and self.reclaim(rec):
                        reclaimed = True
                        continue
                    if i == tries:
                        eprint("wombat-gate: %s is still there after %.0fs; run `wombat-gate doctor` to see "
                               "whose it is" % (self.path, time.monotonic() - t))
                        return False
                    i += 1
                    rec["retries"] = rec.get("retries", 0) + 1
                    wait = min(cap, delay * (2 ** (i - 1))) * random.uniform(0.7, 1.3)
                    eprint("wombat-gate: git lock busy (%s exists); retry %d/%d in %.1fs"
                           % (self.path, i, tries, wait))
                    time.sleep(wait)
        finally:
            steps = rec.setdefault("steps", {})
            steps["index_lock"] = steps.get("index_lock", 0.0) + time.monotonic() - t
        return False

    def mine(self):
        try:
            return self.ino is not None and os.stat(self.path).st_ino == self.ino
        except OSError:
            return False

    def commit(self, new_index):
        if not self.mine():
            raise OSError("%s is no longer the lock file we created" % self.path)
        st = os.stat(new_index)
        with open(new_index, "rb") as f:
            view = memoryview(f.read())
        while view:  # write(2) may write less than asked (ENOSPC, quota)
            n = os.write(self.fd, view)
            if n <= 0:
                raise OSError("short write to %s" % self.path)
            view = view[n:]
        os.fsync(self.fd)
        os.close(self.fd)
        self.fd = None
        self._refresh_ticket()
        # Keep the private index's mtime: git treats an entry whose file mtime is not
        # older than the index file as "racily clean" and re-reads it. A fresh mtime
        # here would make such entries look clean for good (review 0.6 N1).
        os.utime(self.path, ns=(st.st_atime_ns, st.st_mtime_ns))
        self._refresh_ticket()
        if os.environ.get("WOMBAT_TEST_DIE_WRITING_INDEX") == "1":    # self-test only
            os.kill(os.getpid(), signal.SIGKILL)
        os.replace(self.path, self.index)
        self.ino = None

    def release(self):
        if self.fd is not None:
            os.close(self.fd)
            self.fd = None
        if self.mine():
            os.remove(self.path)
        if self.ino is not None or self.ticket:
            t = read_ticket(self.ticket)
            if t and t.get("pid") == os.getpid():
                try:
                    os.remove(self.ticket)
                except OSError:
                    pass
        self.ino = None


class Signalled(BaseException):
    def __init__(self, signum):
        BaseException.__init__(self, signum)
        self.signum = signum


def _raise_signalled(signum, frame):
    raise Signalled(signum)


CATCH_SIGNALS = [getattr(signal, n) for n in ("SIGTERM", "SIGHUP", "SIGQUIT") if hasattr(signal, n)]
FALLBACK = object()  # fast_commit's "use the classic path after all"


def fast_commit(args, top, lit, msg, rec, lk, t0, gp, cfg):
    # while we hold index.lock, a SIGTERM (e.g. a tool timeout) must not leave it
    # behind for everyone (review 0.6 N2): turn it into an exception, run `finally`
    old_handlers = {sig: signal.signal(sig, _raise_signalled) for sig in CATCH_SIGNALS}
    try:
        return _fast_commit(args, top, lit, msg, rec, lk, t0, gp, cfg)
    except Signalled as e:
        eprint("wombat-gate: stopped by signal %d; index.lock removed%s" % (
            e.signum, "" if rec.get("result") != "committed" else
            " -- but commit %s had landed and the index was not written: run the same "
            "`wombat-gate commit` again to repair it" % str(rec.get("commit"))[:12]))
        rec["result"] = "signalled" + ("_after_commit" if rec.get("result") == "committed" else "")
        return finish_locked(rec, lk, t0, 128 + e.signum)
    finally:
        for sig, h in old_handlers.items():
            signal.signal(sig, h)


def _fast_commit(args, top, lit, msg, rec, lk, t0, gp, cfg):
    rels = repo_rel_paths(args.paths, top)
    tmpd = os.path.join(state_dir(), "tmp")
    os.makedirs(tmpd, exist_ok=True)
    idx = os.path.join(tmpd, "index.%d" % os.getpid())
    msgf = os.path.join(tmpd, "msg.%d" % os.getpid())
    envt = dict(lit, GIT_INDEX_FILE=idx)
    paths_txt = " ".join(args.paths)
    il = IndexLock(gp["index"], ticket=lk.path + ".gitlock", session=lk.session)
    try:
        if not il.take(rec):
            eprint("wombat-gate: %s exists; gave up after %s retries; %s"
                   % (il.path, os.environ.get("WOMBAT_GIT_RETRIES", 8),
                      git_lock_diagnosis("'%s'" % il.path)))
            rec["result"] = "index_locked"
            return finish_locked(rec, lk, t0, EXIT_GIT_LOCK_BUSY)
        # 2. private copy of the shared index (read while we hold its lock)
        t = time.monotonic()
        for f in (idx, idx + ".lock"):
            if os.path.exists(f):
                os.remove(f)
        try:  # copy2 keeps the mtime, which git's racy-entry check depends on (N1)
            shutil.copy2(gp["index"], idx)
        except FileNotFoundError:
            pass  # no index yet (fresh repository)
        rec.setdefault("steps", {})["copy_index"] = time.monotonic() - t
        check_step(timed(rec, "add", stage_named, rels, envt, cwd=top, argv=ADD_ALL), "add")
        part = timed(rec, "write_tree", git, ["write-tree"], cwd=top, env_extra=envt)
        if part.returncode != 0:
            # an unmerged or broken entry outside PATH: git commit -- PATH copes, a
            # whole-index write-tree does not. Nothing has changed yet.
            rec["classic_reason"] = "write-tree on the index copy failed: %s" % (
                (part.stderr or "").strip().splitlines() or ["?"])[-1]
            return FALLBACK
        now = check_step(timed(rec, "graft", git, ["ls-tree", "-z", "--full-tree", part.stdout.strip(), "--"] + rels,
                               cwd=top, env_extra=lit), "graft")
        now = split_ls(now.stdout)
        missing = [r for r in rels if r not in now]
        gone = []
        if missing:
            # like `git commit -- PATH`: a path that is neither in the working tree nor
            # in HEAD is an error, not something to skip silently
            known = check_step(git(["ls-tree", "-z", "--full-tree", "--name-only", "HEAD", "--"] + missing,
                                   cwd=top, env_extra=lit), "graft") if head_sha(top) else None
            gone = [r for r in missing if r not in set(((known and known.stdout) or "").split("\0"))]
        else:
            gone = []
        changes = {}
        for rel in rels:
            parts = rel.split("/")
            d = changes
            for comp in parts[:-1]:
                d = d.setdefault(comp, {})
            d[parts[-1]] = now.get(rel)

        sha, changed, subject, head = None, [], None, None
        for attempt in range(MAX_REBUILDS + 1):
            # 3. graft onto HEAD (again, if HEAD moved under the compare-and-swap)
            head = timed(rec, "head", head_sha, top) if attempt == 0 else timed(rec, "head", head_after, head, top)
            base = None
            if head:
                base = check_step(timed(rec, "graft", git, ["rev-parse", "--verify", "-q", head + "^{tree}"], cwd=top),
                                  "graft").stdout.strip()
            root = timed(rec, "graft", graft, top, base, changes) or EMPTY_TREE
            if root == (base or EMPTY_TREE):
                if attempt:
                    eprint("wombat-gate: your changes under %s were already committed by another process "
                           "(HEAD is now %s, not made by wombat-gate); nothing left to commit" % (paths_txt, head[:12]))
                    rec.update(result="swept_by_foreign", foreign_head=head[:12])
                else:
                    eprint("wombat-gate: nothing to commit under", paths_txt)
                    rec["result"] = "nothing"
                try:
                    timed(rec, "write_index", il.commit, idx)  # what `git add -A -- PATH` would leave
                except OSError as e:
                    eprint("wombat-gate: warning: could not write the index: %s" % e)
                return finish_locked(rec, lk, t0, EXIT_NOTHING)
            if gone:  # checked only when there is something to commit, as the classic path does
                eprint("error: pathspec '%s' did not match any file(s) known to git" % gone[0])
                rec["result"] = "pathspec_unmatched"
                return finish_locked(rec, lk, t0, EXIT_GIT_ERROR)
            if subject is None:
                # 4. message hooks once, after we know there is something to commit
                with open(msgf, "w", encoding="utf-8", errors="surrogateescape") as f:
                    f.write(msg)
                for name, argv in (("prepare-commit-msg", [msgf, "message"]), ("commit-msg", [msgf])):
                    hook = None if (name == "commit-msg" and args.no_verify) else hook_file(gp, name)
                    if not hook:
                        continue
                    h = timed(rec, "hooks", run_hook, hook, argv, top, idx)
                    show_hook_output(h)
                    if h.returncode != 0:
                        rec["result"] = "hook_rejected"
                        return finish_locked(rec, lk, t0, EXIT_GIT_ERROR)
                with open(msgf, encoding="utf-8", errors="surrogateescape") as f:
                    cleaned = clean_message(f.read(), cfg.get("commit.cleanup"), top)
                if not cleaned.strip():
                    eprint("Aborting commit due to empty commit message.")
                    rec["result"] = "empty_message"
                    return finish_locked(rec, lk, t0, EXIT_GIT_ERROR)
                with open(msgf, "w", encoding="utf-8", errors="surrogateescape") as f:
                    f.write(cleaned)
                subject = cleaned.strip().splitlines()[0]
            dt = check_step(timed(rec, "diff_tree", git, ["diff-tree", "-r", "--no-renames", "--name-status",
                                                          base or EMPTY_TREE, root], cwd=top), "diff_tree")
            changed = [l for l in dt.stdout.splitlines() if l.strip()]
            if args.expect_files is not None and len(changed) != args.expect_files:
                eprint("wombat-gate: changed file count moved since preview; nothing committed")
                rec["result"] = "count_changed"
                return finish_locked(rec, lk, t0, EXIT_USAGE)
            ct = check_step(timed(rec, "commit_tree", git, ["commit-tree", root] + (["-p", head] if head else [])
                                  + ["-F", msgf], cwd=top), "commit_tree")
            new = ct.stdout.strip()
            ur = git_retry(["update-ref", "-m", ("commit: " if head else "commit (initial): ") + subject,
                            "HEAD", new, head or ""], rec, step="update_ref")
            if ur.returncode == 0:
                sha = new
                break
            if ur.lock_busy or not CAS_FAILED.search(ur.stderr or ""):
                raise GitStepFailed(ur, "update_ref")
            rec["rebuilds"] = attempt + 1  # HEAD moved without the index (plumbing / other worktree)
        if sha is None:
            eprint("wombat-gate: HEAD moved under us %d times in a row; nothing committed" % (MAX_REBUILDS + 1))
            rec["result"] = "head_kept_moving"
            return finish_locked(rec, lk, t0, EXIT_GIT_LOCK_BUSY)
        rec.update(result="committed", commit=sha, n_files=len(changed))
        # 5. the new index replaces the old one, like `git commit` does
        try:
            timed(rec, "write_index", il.commit, idx)
        except OSError as e:
            eprint("wombat-gate: committed %s, BUT could not write the index (%s): the index still holds the "
                   "old entries for %s, which show up as staged changes that would undo this commit. Run the "
                   "same `wombat-gate commit` again once the disk is writable; it repairs the index and exits 3."
                   % (sha[:12], e, paths_txt))
            rec["result"] = "committed_index_stale"
            return finish_locked(rec, lk, t0, EXIT_INDEX_STALE)
        if not args.quiet:
            print("wombat-gate: committed %s (%d file%s)" % (sha, len(changed), "" if len(changed) == 1 else "s"))
            print("\n".join(changed))
        hook = hook_file(gp, "post-commit")
        if hook:
            sys.stdout.flush()
            h = timed(rec, "hooks", run_hook, hook, [], top)
            show_hook_output(h)
        return finish_locked(rec, lk, t0, EXIT_OK)
    except GitStepFailed as e:
        eprint((e.r.stderr or "").rstrip())
        rec["result"] = "%s_failed" % e.step
        return finish_locked(rec, lk, t0, fail_rc(e.r))
    except HeadUnreadable:
        raise
    except Exception as e:  # RuntimeError from our own checks, OSError, anything unexpected
        eprint("wombat-gate: %s: %s" % (type(e).__name__, e))
        rec["result"] = "fast_error" if rec.get("result") != "committed" else "committed_then_error"
        return finish_locked(rec, lk, t0, EXIT_GIT_ERROR if rec["result"] == "fast_error" else EXIT_INDEX_STALE)
    finally:
        il.release()
        for f in (idx, idx + ".lock", msgf):
            try:
                os.remove(f)
            except OSError:
                pass


def restore_index(snap, head0, paths, lit):
    """Put the index entries under `paths` back to the `git ls-files -s -z` snapshot
    taken before staging (so partial stagings by others survive). Working tree untouched.
    Skipped if HEAD moved since the snapshot: restoring old entries on top of a new
    HEAD would stage a revert of whatever the other process just committed."""
    if head_after(head0) != head0:
        eprint("wombat-gate: warning: HEAD moved during the operation (a non-wombat-gate commit?); "
               "left the index for %s as is -- check `wombat-gate status`" % " ".join(paths))
        return
    now = git(["ls-files", "-z", "--full-name", "--"] + paths, env_extra=lit)
    before = {}
    for rec in (snap or "").split("\0"):
        if rec:
            meta, path = rec.split("\t", 1)
            before[path] = meta
    lines = []
    for path in [p for p in (now.stdout or "").split("\0") if p]:
        if path not in before:  # newly added by us: remove the entry again
            lines.append("0 %s\t%s" % ("0" * 40, path))
    for path, meta in before.items():
        lines.append("%s\t%s" % (meta, path))
    if not lines:
        return
    r = git_retry(["update-index", "-z", "--index-info"], {}, input="\0".join(lines) + "\0")
    if r.returncode != 0:
        eprint("wombat-gate: warning: could not restore the index for %s: %s" % (" ".join(paths), r.stderr.strip()))


def integration_state(top):
    gd = check_step(git(["rev-parse", "--absolute-git-dir"], cwd=top), "gitdir").stdout.strip()
    return any(os.path.exists(os.path.join(gd, name))
               for name in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply"))


def integration_dirty(top, include_ignored=False):
    env = {"GIT_OPTIONAL_LOCKS": "0", "GIT_LITERAL_PATHSPECS": "1"}
    tracked = check_step(git(["diff", "--name-only", "-z", "HEAD"], cwd=top, env_extra=env), "dirty-diff")
    untracked = check_step(git(["ls-files", "--others"] + ([] if include_ignored else ["--exclude-standard"]) + ["-z"],
                              cwd=top, env_extra=env), "dirty-untracked")
    return {p for p in (tracked.stdout + untracked.stdout).split("\0") if p}


def run_integration_check(command, source, timeout):
    """Own a process group, so a timed-out check cannot leave worker children."""
    env = dict(os.environ, GIT_TERMINAL_PROMPT="0")
    proc = subprocess.Popen(command, cwd=source, env=env, start_new_session=True)
    try:
        return proc.wait(timeout=timeout)
    except (subprocess.TimeoutExpired, KeyboardInterrupt, Signalled):
        try:
            os.killpg(proc.pid, signal.SIGTERM)
        except ProcessLookupError:
            pass
        try:
            proc.wait(timeout=1)
        except subprocess.TimeoutExpired:
            pass
        # Children may have ignored TERM even if their parent has already exited.
        try:
            os.killpg(proc.pid, signal.SIGKILL)
        except ProcessLookupError:
            pass
        proc.wait()
        raise


def cmd_integrate(args):
    old_handlers = {sig: signal.signal(sig, _raise_signalled) for sig in CATCH_SIGNALS}
    try:
        return _cmd_integrate(args)
    except Signalled as e:
        eprint("wombat-gate: integration stopped by signal %d; inspect the source worktree before retrying" % e.signum)
        return 128 + e.signum
    finally:
        for sig, handler in old_handlers.items():
            signal.signal(sig, handler)


def _cmd_integrate(args):
    """Rebase a clean, checked-out local branch, validate, then fast-forward here.

    Both worktrees share the common-dir queue. No checkout/stash/reset/force or
    worktree deletion. Conflicts stay in the source worktree for human review.
    """
    top, common = repo_info()
    sess, t0 = session_name(args), time.monotonic()
    rec = {"op": "integrate", "repo": top, "session": sess, "branch": args.rebase, "retries": 0}
    branch = args.rebase
    if any(os.environ.get(k) for k in ("GIT_INDEX_FILE", "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR")):
        eprint("wombat-gate: integrate refuses Git index/worktree/directory overrides; use normal worktrees")
        return EXIT_USAGE
    if branch.startswith("-") or git(["check-ref-format", "refs/heads/" + branch]).returncode:
        eprint("wombat-gate: give an existing local branch name")
        return EXIT_USAGE
    if not args.check:
        eprint("wombat-gate: integrate requires at least one --check 'command args'")
        return EXIT_USAGE
    try:
        checks = [shlex.split(c) for c in args.check]
    except ValueError as e:
        eprint("wombat-gate: invalid --check:", e)
        return EXIT_USAGE
    if any(not c for c in checks):
        eprint("wombat-gate: empty --check")
        return EXIT_USAGE
    try:
        with QueueLock(lock_path_for(common), sess, "integrate", args.timeout) as lk:
            rec.update(wait_s=lk.wait_s, t_acq=time.time())
            try:
                target = check_step(git(["symbolic-ref", "-q", "HEAD"], cwd=top), "target-branch").stdout.strip()
                if target == "refs/heads/" + branch:
                    raise ValueError("source and target branches must differ; run from the target worktree")
                target_sha = head_sha(top)
                if not target_sha:
                    raise ValueError("target must have a commit")
                worktrees = check_step(git(["worktree", "list", "--porcelain", "-z"], cwd=top), "worktrees").stdout
                source, here = None, None
                for field in worktrees.split("\0"):
                    if field.startswith("worktree "):
                        here = field[9:]
                    elif field == "branch refs/heads/" + branch:
                        source = here
                if source is None:
                    raise ValueError("source branch must already be checked out in a separate worktree")
                if integration_state(top) or integration_state(source):
                    raise ValueError("merge/rebase/cherry-pick/revert in progress; finish or abort it first")
                if integration_dirty(source):
                    raise ValueError("source worktree is dirty; commit its files first")
                source_sha = head_sha(source)
                base = check_step(git(["merge-base", target_sha, source_sha], cwd=top), "merge-base").stdout.strip()
                target_changes = set(check_step(git(["diff", "--name-only", "-z", base, target_sha], cwd=top), "target-diff").stdout.split("\0")) - {""}
                source_ignored = integration_dirty(source, include_ignored=True)
                if any(p == q or p.startswith(q + "/") or q.startswith(p + "/") for p in source_ignored for q in target_changes):
                    raise ValueError("source has ignored files overlapping target changes; rebase would overwrite them")
                if check_step(git(["rev-list", "--merges", base + ".." + source_sha], cwd=source), "merge-check").stdout.strip():
                    raise ValueError("source has merge commits; manual review required before linear rebase")
                touched = set(check_step(git(["diff", "--name-only", "-z", base, source_sha], cwd=top), "source-diff").stdout.split("\0")) - {""}
                dirty = integration_dirty(top, include_ignored=True)
                overlap = sorted(p for p in dirty if any(p == q or p.startswith(q + "/") or q.startswith(p + "/") for q in touched))
                if overlap:
                    raise ValueError("target has uncommitted files overlapping the branch: " + repr(overlap))
                if args.dry_run:
                    print("wombat-gate: rebase %s (%s) onto %s (%s); checks=%s; then ff-only" %
                          (branch, source, target, target_sha, repr(args.check)))
                    rec["result"] = "dry_run"
                    return finish_locked(rec, lk, t0, EXIT_OK)
                rb = git(["-c", "rebase.autoStash=false", "-c", "rebase.updateRefs=false", "-c", "rebase.autoSquash=false",
                          "rebase", "--no-autostash", target_sha], cwd=source)
                if rb.returncode:
                    eprint(rb.stdout, rb.stderr)
                    eprint("wombat-gate: rebase stopped in %s; target not advanced. Review there; no automatic conflict resolution." % source)
                    rec["result"] = "rebase_stopped"
                    return finish_locked(rec, lk, t0, EXIT_GIT_ERROR)
                rebased = head_sha(source)
                for command in checks:
                    print("wombat-gate: check in %s: %s" % (source, shlex.join(command) if hasattr(shlex, "join") else repr(command)), flush=True)
                    rc = run_integration_check(command, source, args.check_timeout)
                    if rc:
                        raise ValueError(
                            "check failed (exit %d); target not advanced; source branch %s was rebased from %s; "
                            "rebased source retained; revert with: git -C %s reset --hard %s"
                            % (rc, branch, source_sha, shlex.quote(source), source_sha))
                if (head_sha(source) != rebased or integration_dirty(source) or integration_state(source)
                        or git(["symbolic-ref", "-q", "HEAD"], cwd=source).stdout.strip() != "refs/heads/" + branch):
                    raise ValueError("checks changed source HEAD/worktree; target not advanced")
                if head_sha(top) != target_sha or git(["symbolic-ref", "-q", "HEAD"], cwd=top).stdout.strip() != target:
                    raise ValueError("target moved during integration; target not advanced by wombat-gate")
                if integration_state(top):
                    raise ValueError("target operation started during checks; target not advanced")
                dirty = integration_dirty(top, include_ignored=True)
                if any(p == q or p.startswith(q + "/") or q.startswith(p + "/") for p in dirty for q in touched):
                    raise ValueError("target files now overlap the source; target not advanced")
                # Git itself rejects any tracked or untracked overwrite; never force.
                ff = git(["-c", "merge.autoStash=false", "merge", "--ff-only", "--no-autostash", rebased], cwd=top)
                if ff.returncode:
                    eprint(ff.stdout, ff.stderr)
                    rec["result"] = "ff_failed"
                    return finish_locked(rec, lk, t0, EXIT_GIT_ERROR)
                print("wombat-gate: integrated %s -> %s at %s" % (branch, target, rebased))
                rec.update(result="integrated", commit=rebased, source=source)
                return finish_locked(rec, lk, t0, EXIT_OK)
            except (ValueError, GitStepFailed, HeadUnreadable, OSError, subprocess.TimeoutExpired) as e:
                eprint("wombat-gate: integration stopped:", getattr(getattr(e, "r", None), "stderr", str(e)))
                rec["result"] = "stopped"
                return finish_locked(rec, lk, t0, EXIT_GIT_ERROR)
    except TimeoutError:
        rec.update(result="queue_timeout", total_s=time.monotonic() - t0)
        return finish(rec, EXIT_LOCK_TIMEOUT)


def cmd_status(args):
    top, _ = repo_info()
    lit = check_paths(args.paths, top, args.allow_broad)
    # GIT_OPTIONAL_LOCKS=0: status will not take index.lock to refresh the index,
    # so it never collides with writers and needs no queue.
    r = git(["status", "--short", "--untracked-files=" + args.untracked, "--"] + args.paths,
            env_extra=dict(lit, GIT_OPTIONAL_LOCKS="0"), capture=False)
    return r.returncode


# Per-subcommand options that rewrite shared state (local branches, HEAD, files in
# the working tree, remote history). Long options also match git's unique-prefix
# abbreviations (`--forc`); short options also match inside clusters (`-fd`).
RUN_DENY = {
    "push": (["--force", "--force-with-lease", "--force-if-includes", "--delete", "--mirror",
              "--prune", "--receive-pack", "--exec"], "fd"),
    "fetch": (["--update-head-ok", "--upload-pack", "--refmap", "--prune-tags"], "uP"),
    "branch": (["--delete", "--force", "--move", "--copy", "--set-upstream-to",
                "--unset-upstream", "--edit-description"], "dDfmMcCu"),
    "tag": (["--delete", "--force"], "df"),
}
ANY_DENY = ["--output"]  # log/show/diff/blame --output=FILE truncates FILE
# Exact options that are harmless but share a prefix with a denied one.
RUN_SAFE_EXACT = {"fetch": {"--prune"}}


def _long_hit(arg, opts):
    name = arg.split("=", 1)[0]
    return len(name) >= 3 and any(o.startswith(name) or name.startswith(o) for o in opts)


def run_args_reason(sub, rest):
    """Why the arguments of an allow-listed `wombat-gate run` are refused, or None."""
    longs, shorts = RUN_DENY.get(sub, ([], ""))
    positional = []
    for i, a in enumerate(rest):
        if a == "--":
            positional += rest[i + 1:]
            break
        if a.startswith("--"):
            if a.split("=", 1)[0] in RUN_SAFE_EXACT.get(sub, ()):
                continue
            if _long_hit(a, longs + ANY_DENY):
                return "option %s rewrites shared state" % a
        elif a.startswith("-") and len(a) > 1:
            if sub in RUN_DENY and set(a[1:]) & set(shorts):
                return "option %s rewrites shared state" % a
        else:
            positional.append(a)
    if sub == "fetch" and any(":" in a or a.startswith("+") for a in positional[1:]):
        return "fetch refspecs with ':' or '+' can overwrite local branches"
    if sub == "push" and any(a.startswith("+") or a.startswith(":") for a in positional[1:]):
        return "forced (+) or deleting (:x) push refspec"
    return None


def cmd_run(args):
    t0 = time.monotonic()
    argv = list(args.git_args)
    if argv and argv[0] == "--":
        argv = argv[1:]
    if argv and argv[0] == "git":
        argv = argv[1:]
    if not argv:
        eprint("wombat-gate: usage: wombat-gate run -- <git arguments>")
        return EXIT_USAGE
    if args.unsafe and escape_refused("--unsafe"):
        return EXIT_USAGE
    sub = argv[0]
    if sub not in RUN_ALLOWED and not args.unsafe:
        if sub.startswith("-"):
            why = "global git options before the subcommand are not allowed"
        else:
            why = ("`git %s` is not on the allow-list (%s); use `wombat-gate commit` for commits"
                   % (sub, ", ".join(sorted(RUN_ALLOWED))))
        eprint("wombat-gate: refusing `git %s`: %s%s" % (shlex.join(argv), why, unsafe_hint()))
        return EXIT_USAGE
    why = None if args.unsafe else run_args_reason(sub, argv[1:])
    if why:
        eprint("wombat-gate: refusing `git %s`: %s%s" % (shlex.join(argv), why, unsafe_hint()))
        return EXIT_USAGE
    queued, retry = RUN_ALLOWED.get(sub, (True, False))
    top, common = repo_info()
    sess = session_name(args)
    rec = {"op": "run", "session": sess, "repo": top, "argv": shlex.join(argv)[:200], "retries": 0}
    if not queued:
        r = git(argv, capture=False)
        rec.update(result="ok" if r.returncode == 0 else "git_error", queued=False,
                   total_s=time.monotonic() - t0)
        return finish(rec, r.returncode)
    try:
        lk = QueueLock(lock_path_for(common), sess, "run " + sub, args.timeout).__enter__()
    except TimeoutError:
        rec.update(wait_s=time.monotonic() - t0, total_s=time.monotonic() - t0, result="queue_timeout")
        return finish(rec, EXIT_LOCK_TIMEOUT)
    try:
        rec["wait_s"], rec["t_acq"] = lk.wait_s, time.time()
        if retry:
            r = git_retry(argv, rec)
        else:
            r = git(argv)
        sys.stdout.write(r.stdout or "")
        sys.stderr.write(r.stderr or "")
        rec["result"] = "ok" if r.returncode == 0 else "git_error"
        return finish_locked(rec, lk, t0, r.returncode)
    finally:
        lk.__exit__(None, None, None)


def cmd_who(args):
    _, common = repo_info()
    path = lock_path_for(common)
    fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o644)
    try:
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            fcntl.flock(fd, fcntl.LOCK_UN)
            state = "free"
        except BlockingIOError:
            state = "held"
    finally:
        os.close(fd)
    try:
        with open(path + ".holder") as f:
            h = f.read().strip()
    except OSError:
        h = "{}"
    print("lock %s: %s; %s holder: %s" % (path, state, "current" if state == "held" else "last", h))
    return EXIT_OK


def pct(xs, q):
    xs = sorted(xs)
    if not xs:
        return None
    k = (len(xs) - 1) * q
    lo, hi = int(math.floor(k)), int(math.ceil(k))
    return xs[lo] + (xs[hi] - xs[lo]) * (k - lo)


def timing_stats(n=200):
    try:
        with open(log_path(), encoding="utf-8") as f:
            lines = f.readlines()[-max(n, 1) * 3:]
    except OSError:
        return None
    recs = []
    for line in lines:
        try:
            r = json.loads(line)
        except ValueError:
            continue
        if r.get("op") == "commit" and "wait_s" in r:
            recs.append(r)
    recs = recs[-n:]
    if not recs:
        return None
    w = [r.get("wait_s") or 0 for r in recs]
    h = [r.get("hold_s") or 0 for r in recs if r.get("hold_s") is not None]
    return {"n": len(recs), "wait_p50": pct(w, .5), "wait_p95": pct(w, .95),
            "hold_p50": pct(h, .5), "hold_p95": pct(h, .95)}


def lock_openers(path):
    """pids that have `path` open (Linux /proc scan; our own user's processes only)."""
    out = []
    real = os.path.realpath(path)
    for d in os.listdir("/proc") if os.path.isdir("/proc/self") else []:
        if not d.isdigit():
            continue
        try:
            for fd in os.listdir("/proc/%s/fd" % d):
                try:
                    if os.readlink("/proc/%s/fd/%s" % (d, fd)) in (path, real):
                        out.append(int(d))
                        break
                except OSError:
                    continue
        except OSError:
            continue
    return out


def live_git_pids(top):
    """git processes working in this repository (their cwd is inside it)."""
    try:
        r = subprocess.run(["pgrep", "-x", "git"], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
        pids = [int(x) for x in r.stdout.split()]
    except (OSError, ValueError):
        return []
    top = os.path.realpath(top)
    out = []
    for p in pids:
        try:
            cwd = os.path.realpath(os.readlink("/proc/%d/cwd" % p))
        except OSError:
            continue
        if cwd == top or cwd.startswith(top + os.sep):
            out.append(p)
    return out


def doctor_items():
    top, common = repo_info()
    gitdir = git(["rev-parse", "--absolute-git-dir"]).stdout.strip() or common
    cands = [os.path.join(gitdir, "index.lock"), os.path.join(gitdir, "HEAD.lock"),
             os.path.join(common, "HEAD.lock"), os.path.join(common, "packed-refs.lock"),
             os.path.join(common, "config.lock")]
    for root, _dirs, files in os.walk(os.path.join(common, "refs")):
        cands += [os.path.join(root, f) for f in files if f.endswith(".lock")]
    seen, items = set(), []
    qpath = lock_path_for(common)
    ticket = read_ticket(qpath + ".gitlock")
    gits = live_git_pids(top)
    stale_after = env_float("WOMBAT_STALE_AFTER", 600)
    for path in cands:
        if path in seen or not os.path.exists(path):
            continue
        seen.add(path)
        try:
            st = os.stat(path)
        except OSError:
            continue
        age = time.time() - st.st_mtime
        rel = os.path.relpath(path, top)
        openers = lock_openers(path)
        ours = (ticket and ticket.get("lock") == path and ticket.get("ino") == st.st_ino
                and ticket.get("mtime_ns") == st.st_mtime_ns)
        if ours and not pid_alive(ticket.get("pid"), ticket.get("start")):
            items.append(("warn", "%s: left by wombat-gate pid %s (%s), which died; age %.0fs"
                          % (rel, ticket.get("pid"), ticket.get("session") or "?", age),
                          "the next wombat-gate commit removes it automatically"))
        elif openers:
            items.append(("info", "%s: in use by pid %s; age %.0fs" % (rel, ", ".join(map(str, openers)), age), ""))
        elif gits:
            items.append(("info", "%s: age %.0fs; git is running (pid %s), probably its own lock"
                          % (rel, age, ", ".join(map(str, gits[:5]))), "wait for it to finish"))
        elif age > stale_after:
            items.append(("warn", "%s: looks stale (age %.0fs, nobody has it open, no git running)" % (rel, age),
                          "a human may remove it: rm '%s'  (agents: do not delete it, ask a human)" % path))
        else:
            items.append(("info", "%s: age %.0fs, nobody has it open" % (rel, age),
                          "if it is still there in %.0f min, it is probably stale" % (stale_after / 60)))
    if not seen:
        items.append(("ok", "no git lock files", ""))
    fd = os.open(qpath, os.O_RDWR | os.O_CREAT, 0o644)
    try:
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            fcntl.flock(fd, fcntl.LOCK_UN)
            held = False
        except BlockingIOError:
            held = True
    finally:
        os.close(fd)
    if held:
        try:
            with open(qpath + ".holder") as f:
                h = json.load(f)
        except (OSError, ValueError):
            h = {}
        since = (" for %.0fs" % (time.time() - h["t"])) if isinstance(h.get("t"), (int, float)) else ""
        items.append(("info", "queue held by %s (%s, pid %s)%s" % (h.get("session", "?"), h.get("op", "?"),
                                                                  h.get("pid", "?"), since), ""))
    else:
        items.append(("ok", "queue free", ""))
    s = timing_stats()
    if s:
        items.append(("info", "last %d commits: queue wait p50 %.2fs / p95 %.2fs; lock hold p50 %.2fs / p95 %.2fs"
                      % (s["n"], s["wait_p50"], s["wait_p95"], s["hold_p50"] or 0, s["hold_p95"] or 0), ""))
    return items


def cmd_doctor(args):
    import threading
    box = {}

    def go():
        try:
            box["items"] = doctor_items()
        except Exception as e:      # noqa: BLE001
            box["err"] = e
    th = threading.Thread(target=go, daemon=True)
    th.start()
    th.join(env_float("WOMBAT_DOCTOR_TIMEOUT", 20))
    if "items" not in box:
        why = ("error: %s" % box["err"]) if "err" in box else \
            "the repository did not answer within %.0fs (its disk may be gone)" % env_float("WOMBAT_DOCTOR_TIMEOUT", 20)
        items = [("bad", why, "check the mount (e.g. `ls` the repository) before anything else")]
        if args.json:
            print(json.dumps({"checks": [{"level": l, "message": m, "hint": h} for l, m, h in items]}))
        else:
            print("BAD   %s\n      -> %s" % items[0][1:])
        sys.stdout.flush()
        os._exit(1)                   # the worker may be stuck in the kernel; do not wait for it
    items = box["items"]
    if args.json:
        print(json.dumps({"checks": [{"level": l, "message": m, "hint": h} for l, m, h in items]},
                         ensure_ascii=False, indent=1))
    else:
        icon = {"ok": "ok  ", "info": "info", "warn": "WARN", "bad": "BAD "}
        for l, m, h in items:
            print("%s  %s%s" % (icon[l], m, ("\n      -> " + h) if h else ""))
    return 1 if any(l in ("warn", "bad") for l, _, _ in items) else EXIT_OK


def cmd_log(args):
    if args.stats:
        s = timing_stats(args.n if args.n > 20 else 200)
        if not s:
            print("(no commit timings yet)")
            return EXIT_OK
        print("last %d commits: queue wait p50 %.3fs p95 %.3fs; lock hold p50 %.3fs p95 %.3fs"
              % (s["n"], s["wait_p50"], s["wait_p95"], s["hold_p50"] or 0, s["hold_p95"] or 0))
        return EXIT_OK
    if args.n <= 0:
        return EXIT_OK
    try:
        with open(log_path(), encoding="utf-8") as f:
            lines = f.readlines()
    except OSError:
        print("(no log yet at %s)" % log_path())
        return EXIT_OK
    sys.stdout.write("".join(lines[-args.n:]))
    return EXIT_OK


# ---------------------------------------------------------------- cli

# Side view: head and ear on the left, round back, stubby legs, backside plugging the burrow.
WOMBAT = "\n".join([
    '   ^  .-"""""""""-.  _____',
    '  (o)/             \\/#####\\',
    '  (_     _______    |######|  one bum in the burrow',
    '    |_|_|       |_|_|######|',
    '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~',
]) + "\n"


def main(argv=None):
    # allow_abbrev=False everywhere: otherwise `--allow` / `--uns` would silently mean
    # --allow-broad / --unsafe and slip past hooks that look for the full flag.
    p = argparse.ArgumentParser(prog="wombat-gate", description=WOMBAT + "\n" + __doc__.split("\n\n")[0],
                                formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False)
    p.add_argument("--version", action="version", version="wombat-gate " + __version__)
    sub = p.add_subparsers(dest="cmd", required=True)

    def common(sp):
        sp.add_argument("--session", help="name recorded in the log/holder file (default $WOMBAT_SESSION)")
        sp.add_argument("--timeout", type=float, default=env_float("WOMBAT_TIMEOUT", 600),
                        help="seconds to wait for the queue lock (default 600 or $WOMBAT_TIMEOUT)")

    c = sub.add_parser("commit", allow_abbrev=False, help="stage and commit only the given paths")
    common(c)
    c.add_argument("-m", "--message", action="append")
    c.add_argument("-F", "--file", help="read the message from FILE ('-' = stdin)")
    c.add_argument("-n", "--dry-run", action="store_true",
                   help="list what would be committed; does not touch the index")
    c.add_argument("-q", "--quiet", action="store_true")
    c.add_argument("--no-verify", action="store_true", help="passed through to git commit")
    c.add_argument("--expect-files", type=int, help="refuse unless the preview contains exactly N changed file paths")
    c.add_argument("--allow-broad", action="store_true",
                   help="allow '.', the repo root, globs and ':' pathspec magic")
    c.add_argument("paths", nargs="*")
    c.set_defaults(func=cmd_commit)

    it = sub.add_parser("integrate", allow_abbrev=False, help="rebase a branch in its worktree, check, then fast-forward here")
    common(it)
    it.add_argument("--rebase", required=True, metavar="BRANCH")
    it.add_argument("--check", action="append", help="required check command, split as argv without a shell; repeatable")
    it.add_argument("--check-timeout", type=float, default=600, help="seconds per check (default 600)")
    it.add_argument("-n", "--dry-run", action="store_true")
    it.set_defaults(func=cmd_integrate)

    s = sub.add_parser("status", allow_abbrev=False, help="short status of the given paths only, without taking index.lock")
    s.add_argument("-u", "--untracked-files", dest="untracked", default="normal",
                   choices=["no", "normal", "all"])
    s.add_argument("--allow-broad", action="store_true")
    s.add_argument("paths", nargs="*")
    s.set_defaults(func=cmd_status)

    r = sub.add_parser("run", allow_abbrev=False, help="run an allow-listed git command (queued if it writes local state)")
    common(r)
    r.add_argument("--unsafe", action="store_true",
                   help="allow commands outside the allow-list (they run under the queue lock)")
    r.add_argument("git_args", nargs=argparse.REMAINDER)
    r.set_defaults(func=cmd_run)

    w = sub.add_parser("who", allow_abbrev=False, help="show who holds the queue lock for this repository")
    w.set_defaults(func=cmd_who)

    lg = sub.add_parser("log", allow_abbrev=False, help="print recent timing lines")
    lg.add_argument("-n", type=int, default=20)
    lg.add_argument("--stats", action="store_true", help="queue wait / lock hold p50 and p95")
    lg.set_defaults(func=cmd_log)

    dr = sub.add_parser("doctor", allow_abbrev=False, help="git lock files in this repository: in use, stale, or ours")
    dr.add_argument("--json", action="store_true")
    dr.set_defaults(func=cmd_doctor)

    args = p.parse_args(argv)
    old = sorted(k for k in os.environ if k.startswith("GITQ_"))
    if old:  # gitq was this tool's name before 0.5; its settings are not read any more
        eprint("wombat-gate: warning: ignoring %s (gitq was renamed; use WOMBAT_* instead)" % ", ".join(old))
    if not math.isfinite(getattr(args, "timeout", 1)) or getattr(args, "timeout", 1) <= 0:
        eprint("wombat-gate: --timeout must be > 0 seconds")
        return EXIT_USAGE
    if getattr(args, "expect_files", None) is not None and args.expect_files < 0:
        eprint("wombat-gate: --expect-files must be >= 0")
        return EXIT_USAGE
    if not math.isfinite(getattr(args, "check_timeout", 1)) or getattr(args, "check_timeout", 1) <= 0:
        eprint("wombat-gate: --check-timeout must be > 0")
        return EXIT_USAGE
    return args.func(args)


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