"""Command rules agent-guard.py applies attended and unattended alike.

None of these executes anything. The only side effects are reading a commit or
PR message file the command names (bounded by MAX_FILE_BYTES), because a
message given with `-F file` is invisible to a rule that reads argv alone, and
consuming a confirmation record (confirm-command.mjs) the user's answer left.

A rule judges a program only where it is the segment's command word: after
any VAR=value assignments and the wrappers in WRAPPERS. Text that merely
mentions `git push --no-verify` (an echo, a printf, a heredoc commit message)
is not that program. Heredoc bodies are removed before these rules see the
line (strip_heredoc_bodies); the attribution rules read them separately, since
a body is where a commit message usually is.

  command_segments(cmd)    the simple commands of a line, heredoc bodies out
  command_word(toks)       (assignments, argv) with wrappers stripped
  no_verify(toks)          a git commit / push / merge that skips the repo's
                           git hooks (--no-verify and its prefixes, commit -n,
                           -c core.hooksPath, HUSKY=0, GIT_CONFIG_* hooksPath),
                           or a `git config core.hooksPath` write
  message_text(cmd, cwd)   the commit message text a line carries
  ask_reason(toks, seg)    a write a person should confirm: closing a GitHub
                           issue, a PR body that closes one, a Jira transition
  confirmed(cmd)           a fresh confirmation of exactly this command
  read_only_*              a commit, push or file write into a repository
                           listed in prefs.global.readOnlyRepos
"""
import fnmatch
import hashlib
import json
import os
import re
import shlex
import time

RUN_STATE = "agent-state.json"

MAX_FILE_BYTES = 256 * 1024
CONFIRM_TTL_SECONDS = 600

# Closing keywords GitHub acts on, followed by an issue reference.
CLOSING = re.compile(
    r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\b\s*:?\s+(?:[\w.-]+/[\w.-]+)?#\d+",
    re.IGNORECASE,
)
# "Generated by AI", "generated with an AI assistant"; never "ai-sdk".
AI_GENERATED = re.compile(
    r"generated\s+(?:by|with)\s+(?:an?\s+)?(?:[\w-]+\s+){0,3}?ai\b(?![-\w])",
    re.IGNORECASE,
)
JIRA_TRANSITION = re.compile(r"/rest/api/(?:\d+|latest)/issue/[^/\s'\"]+/transitions\b", re.IGNORECASE)
POST_METHOD = re.compile(r"(?:^|\s)(?:-X|--request)\s*=?\s*['\"]?post\b", re.IGNORECASE)
WRITE_METHOD = re.compile(r"(?:^|\s)(?:-X|--request)\s*=?\s*['\"]?(?:post|put|patch)\b", re.IGNORECASE)
PUT_METHOD = re.compile(r"(?:^|\s)(?:-X|--request)\s*=?\s*['\"]?put\b", re.IGNORECASE)
SHARED_WRITE = re.compile(
    r"/rest/api/(?:\d+|latest)/issue/[^/\s'\"]+/comment\b|/rest/api/content\b|hooks\.slack\.com/services/",
    re.IGNORECASE,
)
PR_UPDATE = re.compile(
    r"/rest/api/(?:[\d.]+|latest)/projects/[^/\s'\"]+/repos/[^/\s'\"]+/pull-requests/\d+(?=[\s'\"?]|$)"
)
DATA_FLAGS = {"-d", "--data", "--data-binary", "--data-raw", "--data-ascii"}
BODY_FLAG = re.compile(r"(?:^|\s)(?:-d|--data[\w-]*|--json|-F|--form)(?:\s|=|$)")
HEREDOC_OPEN = re.compile(r"<<(-?)\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\2")
ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")

GIT_VALUE_OPTIONS = {"-C", "-c", "--git-dir", "--work-tree", "--exec-path", "--namespace"}
COMMIT_VALUE_LETTERS = set("mFCct")
COMMIT_VALUE_LONG = {
    "--message", "--file", "--reuse-message", "--reedit-message", "--template", "--author",
    "--date", "--fixup", "--squash", "--trailer", "--cleanup", "--pathspec-from-file",
}
HOOK_SKIPPING_SUBS = {"commit", "push", "merge"}
NO_VERIFY_MIN = "--no-veri"
GH_ALIASES = {"i": "issue", "pr": "pr", "co": "pr"}
WRITE_SUBS = {"commit", "push", "merge", "cherry-pick", "revert", "am", "rebase", "tag"}
HTTP_CLIENTS = {"curl", "wget", "http", "https", "xh"}
# Wrappers that run the rest of the line as the command, with the options
# that take a value.
WRAPPERS = {
    "sudo": {"-u", "-g", "-h", "-p", "-C", "-D", "-r", "-t", "-U"},
    "doas": {"-u", "-C"},
    "command": set(),
    "builtin": set(),
    "exec": {"-a"},
    "env": {"-u", "--unset", "-C", "--chdir", "-S", "--split-string"},
    "xargs": {"-I", "-L", "-n", "-P", "-s", "-d", "-E", "-a"},
    "nice": {"-n"},
    "nohup": set(),
    "time": set(),
    "timeout": {"-s", "-k", "--signal", "--kill-after"},
}


def strip_heredoc_bodies(cmd):
    """(cmd without heredoc bodies, [bodies]). Line-based and lenient: a body
    runs from the line after `<<DELIM` to the line that is DELIM (tabs allowed
    before it for `<<-`); an unterminated one runs to the end."""
    lines = cmd.split("\n")
    out, bodies, pending, i = [], [], [], 0
    while i < len(lines):
        line = lines[i]
        out.append(line)
        pending.extend((m.group(1) == "-", m.group(3)) for m in HEREDOC_OPEN.finditer(line))
        i += 1
        while pending and i <= len(lines):
            dash, delim = pending.pop(0)
            body = []
            while i < len(lines):
                cand = lines[i].lstrip("\t") if dash else lines[i]
                i += 1
                if cand.strip() == delim:
                    break
                body.append(lines[i - 1])
            bodies.append("\n".join(body))
    return "\n".join(out), bodies


def split_simple(cmd):
    """Simple-command segments, split on `;`, `&&`, `||`, `|`, newlines and
    unquoted `(`, `)` and backticks. Quote-aware, so an operator inside a quoted
    commit message is text."""
    segs, cur, q, i = [], [], None, 0
    while i < len(cmd):
        c = cmd[i]
        if q == "'":
            cur.append(c)
            q = None if c == "'" else q
            i += 1
            continue
        if c == "\\" and i + 1 < len(cmd):
            cur.append(cmd[i:i + 2])
            i += 2
            continue
        if q == '"':
            if c == '"':
                q = None
                cur.append(c)
            elif cmd.startswith("$(", i):
                segs.append("".join(cur))
                cur = []
                i += 2
                continue
            else:
                cur.append(c)
            i += 1
            continue
        if c in ("'", '"'):
            q = c
            cur.append(c)
            i += 1
            continue
        two = cmd[i:i + 2]
        if two in ("&&", "||", "|&"):
            segs.append("".join(cur))
            cur = []
            i += 2
            continue
        if c in (";", "|", "\n", "(", ")", "`"):
            segs.append("".join(cur))
            cur = []
            i += 1
            continue
        cur.append(c)
        i += 1
    segs.append("".join(cur))
    return [s for s in segs if s.strip()]


# shlex grows a token one character at a time, so a megabyte argument takes
# longer than the guard's deadline. Past this length a segment is split on
# whitespace with quotes and backslashes removed, as agent-guard.tokenize does.
SHLEX_MAX_CHARS = 16384


def tokens(seg):
    if len(seg) > SHLEX_MAX_CHARS:
        return [re.sub(r"[\"'\\]", "", t) for t in seg.split()]
    try:
        return shlex.split(seg)
    except ValueError:
        return seg.split()


def command_segments(cmd):
    """[(segment, tokens)] for the simple commands of a line, bodies removed."""
    stripped, _ = strip_heredoc_bodies(cmd)
    return [(s, tokens(s)) for s in split_simple(stripped)]


def command_word(toks):
    """(assignments, argv): leading VAR=value assignments (and those `env`
    sets), then the command with the WRAPPERS in front of it consumed."""
    assigns, i = [], 0
    while i < len(toks):
        t = toks[i]
        if ASSIGN.match(t):
            assigns.append(t)
            i += 1
            continue
        base = os.path.basename(t)
        if base not in WRAPPERS:
            break
        value_opts = WRAPPERS[base]
        i += 1
        while i < len(toks) and (toks[i].startswith("-") or (base == "env" and ASSIGN.match(toks[i]))):
            if ASSIGN.match(toks[i]):
                assigns.append(toks[i])
            elif toks[i] in value_opts:
                i += 1
            i += 1
        if base == "timeout" and i < len(toks) and re.match(r"^[0-9]", toks[i]):
            i += 1
    return assigns, toks[i:]


def _git_split(toks):
    """(assignments, global_options, subcommand, args) when the segment's
    command word is git, else None."""
    assigns, argv = command_word(toks)
    if not argv or os.path.basename(argv[0]).lower() != "git":
        return None
    opts, j = [], 1
    while j < len(argv):
        o = argv[j]
        if o in GIT_VALUE_OPTIONS:
            opts.append((o, argv[j + 1] if j + 1 < len(argv) else ""))
            j += 2
        elif o.startswith("-"):
            key, _, val = o.partition("=")
            opts.append((key, val))
            j += 1
        else:
            return assigns, opts, o.lower(), argv[j + 1:]
    return None


def _hookspath_assign(assigns):
    for a in assigns:
        name, _, val = a.partition("=")
        low = val.lower().replace(" ", "")
        if name == "HUSKY" and low in ("0", "false"):
            return "HUSKY=0 switches the repository's git hooks off"
        if (name == "GIT_CONFIG_PARAMETERS" or name.startswith("GIT_CONFIG_KEY_")) and "hookspath" in low:
            return f"{name} overrides core.hooksPath and skips the repository's git hooks"
    return None


def no_verify(toks):
    """A reason when the segment skips the repository's own git hooks."""
    assigns, argv = command_word(toks)
    if argv and argv[0] == "export":
        reason = _hookspath_assign([a for a in argv[1:] if ASSIGN.match(a)])
        if reason:
            return reason
    split = _git_split(toks)
    if not split:
        return None
    assigns, opts, sub, args = split
    if sub == "config":
        reading = {"--get", "--get-all", "--get-regexp", "--list", "-l", "--unset", "--unset-all", "--show-origin"}
        keys = [a for a in args if not a.startswith("-")]
        if keys and keys[0].lower() == "core.hookspath" and len(keys) > 1 and not reading & set(args):
            return "git config core.hooksPath points git away from the repository's hooks"
        return None
    if sub not in HOOK_SKIPPING_SUBS:
        return None
    reason = _hookspath_assign(assigns)
    if reason:
        return reason
    for key, val in opts:
        if key == "-c" and val.lower().replace(" ", "").startswith("core.hookspath="):
            return f"git {sub} with core.hooksPath overridden skips the repository's git hooks"
    i = 0
    while i < len(args):
        a = args[i]
        if a == "--":
            break
        if len(a) >= len(NO_VERIFY_MIN) and "--no-verify".startswith(a):
            return f"git {sub} {a} skips the repository's git hooks"
        if sub == "commit":
            if a in COMMIT_VALUE_LONG:
                i += 2
                continue
            if a.startswith("-") and not a.startswith("--") and len(a) > 1:
                for ch in a[1:]:
                    if ch == "n":
                        return "git commit -n skips the repository's git hooks"
                    if ch in COMMIT_VALUE_LETTERS:
                        if ch == a[-1]:
                            i += 1  # the value is the next token
                        break
        i += 1
    return None


def message_files(toks):
    """Paths a `git commit` reads its message from (`-F`, `--file`)."""
    split = _git_split(toks)
    if not split or split[2] != "commit":
        return []
    out, args, i = [], split[3], 0
    while i < len(args):
        a = args[i]
        if a in ("-F", "--file"):
            if i + 1 < len(args):
                out.append(args[i + 1])
            i += 2
            continue
        if a.startswith("--file="):
            out.append(a.split("=", 1)[1])
        elif a.startswith("-") and not a.startswith("--") and "F" in a[1:]:
            rest = a[a.index("F") + 1:]
            if rest:
                out.append(rest)
            elif i + 1 < len(args):
                out.append(args[i + 1])
                i += 1
        i += 1
    return [p for p in out if p and p != "-"]


def _message_args(toks):
    split = _git_split(toks)
    if not split or split[2] != "commit":
        return []
    out, args, i = [], split[3], 0
    while i < len(args):
        a = args[i]
        if a in ("-m", "--message"):
            if i + 1 < len(args):
                out.append(args[i + 1])
            i += 2
            continue
        if a.startswith("--message="):
            out.append(a.split("=", 1)[1])
        elif a.startswith("-m") and len(a) > 2:
            out.append(a[2:])
        i += 1
    return out


def message_text(cmd, cwd):
    """The commit message text a line carries: -m values, -F files and, when
    the line commits, its heredoc bodies (the `-F -` and `$(cat <<EOF)` forms)."""
    stripped, bodies = strip_heredoc_bodies(cmd)
    parts, commits = [], False
    for seg in split_simple(stripped):
        toks = tokens(seg)
        split = _git_split(toks)
        if not split or split[2] != "commit":
            continue
        commits = True
        parts.extend(_message_args(toks))
        parts.extend(read_bounded(p, cwd) for p in message_files(toks))
    if commits:
        parts.extend(bodies)
    return "\n".join(parts)


def commit_text(cmd, cwd):
    """What a commit on this line records: every word of each git commit
    segment (its -m, --author, --trailer and -c values), the -F files it
    names, the line's heredoc bodies, and the values assigned to variables
    on the line, which a message can expand. The other commands on the line
    are left out, so an echo beside a commit is not its message, unless the
    commit reads a message file the hook cannot judge from disk: one that does
    not exist yet, or one the same line writes. Then the whole line counts,
    since the text the file will hold is on it."""
    stripped, bodies = strip_heredoc_bodies(cmd)
    parts, assigned, others, files, commits = [], [], [], [], False
    for seg in split_simple(stripped):
        toks = tokens(seg)
        assigned.extend(t.partition("=")[2] for t in toks if ASSIGN.match(t))
        split = _git_split(toks)
        if not split or split[2] != "commit":
            others.append(seg)
            continue
        commits = True
        parts.extend(toks)
        for path in message_files(toks):
            files.append(path)
            parts.append(read_bounded(path, cwd))
    if not commits:
        return ""
    if any(_unjudged_message_file(f, cwd, others) for f in files):
        parts.append(stripped)
    return "\n".join(parts + bodies + assigned)


def _unjudged_message_file(path, cwd, others):
    """True when a -F file's text on disk is not what the commit will read:
    it is missing, or another command on the line names it (a redirect or
    tee writing it before the commit runs)."""
    if path == "-":
        return False
    p = os.path.expanduser(path)
    if not os.path.isabs(p):
        p = os.path.join(cwd or os.getcwd(), p)
    if not os.path.isfile(p):
        return True
    names = {path, os.path.basename(path)}
    return any(n and n in seg for seg in others for n in names)


def ai_generated(cmd, cwd):
    """True when the commit message says it was generated by an AI."""
    return bool(AI_GENERATED.search(message_text(cmd, cwd)))


def read_bounded(path, cwd):
    """The text of a message file, or "" when it cannot be read."""
    p = os.path.expanduser(path)
    if not os.path.isabs(p):
        p = os.path.join(cwd or os.getcwd(), p)
    try:
        if not os.path.isfile(p):
            return ""
        with open(p, "rb") as fh:
            return fh.read(MAX_FILE_BYTES).decode("utf-8", "replace")
    except OSError:
        return ""


def _flag_values(args, names, short=None):
    vals, i = [], 0
    while i < len(args):
        a = args[i]
        if a in names or (short and a == short):
            if i + 1 < len(args):
                vals.append(args[i + 1])
            i += 2
            continue
        for n in names:
            if a.startswith(n + "="):
                vals.append(a.split("=", 1)[1])
        i += 1
    return vals


def _gh_ask(argv, cwd):
    if not argv or os.path.basename(argv[0]) != "gh":
        return None
    args = argv[1:]
    cleaned, i = [], 0
    while i < len(args):
        if args[i] in ("-R", "--repo"):
            i += 2
            continue
        cleaned.append(args[i])
        i += 1
    plains = [a for a in cleaned if not a.startswith("-")]
    if not plains:
        return None
    group = GH_ALIASES.get(plains[0], plains[0])
    sub = plains[1] if len(plains) > 1 else ""
    if group == "issue" and sub == "close":
        return "gh issue close closes a tracked issue; the user confirms every issue closure"
    if group == "pr" and sub in ("create", "edit"):
        bodies = _flag_values(cleaned, {"--body"}, "-b")
        bodies += [read_bounded(p, cwd) for p in _flag_values(cleaned, {"--body-file"}, "-F")]
        bodies += _flag_values(cleaned, {"--title"}, "-t")
        if any(CLOSING.search(b or "") for b in bodies):
            return (
                f"gh pr {sub} with a closing keyword (Closes/Fixes/Resolves #N) closes the issue on merge; "
                "use Ref: #N or Related: #N, or confirm the closure"
            )
    if group == "api":
        joined = " ".join(cleaned)
        if re.search(r"issues/\d+\b", joined) and re.search(r"\bstate=closed\b", joined):
            return "gh api closing an issue (state=closed); the user confirms every issue closure"
    return None


def _jira_ask(argv, seg):
    if not argv or os.path.basename(argv[0]) not in HTTP_CLIENTS:
        return None
    if not JIRA_TRANSITION.search(seg):
        return None
    if POST_METHOD.search(seg) or BODY_FLAG.search(seg):
        return "a Jira transition POST moves the issue through its workflow; the user confirms each transition"
    return None


def _shared_ask(argv, seg):
    """A comment, page or message posted to a system other people read."""
    if not argv or os.path.basename(argv[0]) not in HTTP_CLIENTS:
        return None
    if not SHARED_WRITE.search(seg):
        return None
    if WRITE_METHOD.search(seg) or BODY_FLAG.search(seg):
        return "this posts to a shared system (Jira comment, Confluence page or Slack); the user confirms each post"
    return None


def _payload(argv, cwd):
    """The request body a curl-like command sends, read from @file when given."""
    for i, a in enumerate(argv):
        val = None
        if a in DATA_FLAGS and i + 1 < len(argv):
            val = argv[i + 1]
        else:
            for f in DATA_FLAGS:
                if a.startswith(f + "="):
                    val = a.split("=", 1)[1]
        if val is not None:
            return read_bounded(val[1:], cwd) if val.startswith("@") else val
    return None


def pr_update_reason(toks, seg, cwd=None):
    """A Bitbucket pull request PUT replaces the whole record: a body without
    reviewers, fromRef or toRef wipes them."""
    _, argv = command_word(toks)
    if not argv or os.path.basename(argv[0]) not in HTTP_CLIENTS:
        return None
    if not PR_UPDATE.search(seg) or not PUT_METHOD.search(seg):
        return None
    body = _payload(argv, cwd)
    try:
        doc = json.loads(body) if body else None
    except ValueError:
        doc = None
    if not isinstance(doc, dict):
        return "this pull request update sends no readable JSON body; send the full record with reviewers, fromRef and toRef"
    missing = [k for k in ("fromRef", "toRef") if not doc.get(k)]
    if not doc.get("reviewers"):
        missing.insert(0, "reviewers")
    if missing:
        return (
            "a pull request PUT replaces the record, and this body has no "
            + ", ".join(missing)
            + "; read the current pull request and send its reviewers, fromRef, toRef and draft back"
        )
    return None


AGENT_NAME = re.compile(r"^[A-Za-z0-9._:-]{1,80}$")
GH_WRITE_SUBS = {
    ("pr", "create"), ("pr", "edit"), ("pr", "comment"), ("pr", "review"), ("pr", "merge"),
    ("pr", "close"), ("pr", "ready"), ("issue", "create"), ("issue", "edit"),
    ("issue", "comment"), ("issue", "close"), ("issue", "reopen"), ("release", "create"),
}


def read_only_agent(agent_type, env=None):
    """True when the subagent's definition denies it the Write tool: it reviews,
    reads or reports, and anything it does outside its answer is a side effect."""
    if not isinstance(agent_type, str) or not AGENT_NAME.match(agent_type):
        return False
    env = os.environ if env is None else env
    home = env.get("HOME") or os.path.expanduser("~")
    name = agent_type.split(":")[-1]
    for root in (os.path.join(home, ".claude", "agents"), os.path.join(os.getcwd(), ".claude", "agents")):
        text = read_bounded(os.path.join(root, name + ".md"), None)
        if not text.startswith("---"):
            continue
        head = text.split("---", 2)[1] if text.count("---") >= 2 else ""
        m = re.search(r"^disallowedTools:\s*(.+)$", head, re.MULTILINE)
        return bool(m and re.search(r"\bWrite\b", m.group(1)))
    return False


def subagent_side_effect(cmd):
    """What in this command reaches past a read-only subagent's answer, or None."""
    stripped, _ = strip_heredoc_bodies(cmd)
    if re.search(r"write-state\.mjs", stripped):
        return "it writes run state (write-state.mjs)"
    for seg in split_simple(stripped):
        toks = tokens(seg)
        split = _git_split(toks)
        if split and split[2] in WRITE_SUBS:
            return f"it runs git {split[2]}"
        _, argv = command_word(toks)
        if not argv:
            continue
        base = os.path.basename(argv[0])
        if base in HTTP_CLIENTS and (WRITE_METHOD.search(seg) or BODY_FLAG.search(seg)):
            return f"it sends a write request with {base}"
        if base == "gh":
            plains = [a for a in argv[1:] if not a.startswith("-")]
            if len(plains) >= 2 and (GH_ALIASES.get(plains[0], plains[0]), plains[1]) in GH_WRITE_SUBS:
                return f"it runs gh {plains[0]} {plains[1]}"
            if plains[:1] == ["api"] and (
                re.search(r"(?:^|\s)(?:-X|--method)\s*=?\s*(?:post|put|patch|delete)\b", seg, re.I)
                or re.search(r"(?:^|\s)(?:-f|-F|--field|--raw-field|--input)(?:\s|=)", seg)
            ):
                return "it writes through gh api"
    return None


CLEANUP_SCRIPTS = {"purge.sh": None, "prune-logs.sh": "--yes", "run-kill.mjs": "apply"}


def _cleanup_ask(argv):
    """purge, prune-logs --yes and run-kill apply delete run history for good."""
    if not argv:
        return None
    rest = argv
    if os.path.basename(argv[0]) in ("bash", "sh", "zsh", "node"):
        rest = argv[1:]
    if not rest:
        return None
    name = os.path.basename(rest[0])
    if name not in CLEANUP_SCRIPTS:
        return None
    needs = CLEANUP_SCRIPTS[name]
    if needs and needs not in rest[1:]:
        return None
    return f"{name} deletes run logs or worktrees for good; the user confirms each clean-up"


PRODUCT_TREE_OVERLAY_NAME = "product-tree-overlay.jsonl"

PRODUCT_TREE_OVERLAY_WRITE = re.compile(
    r"(?:>>?|\btee\b[^;&|]*?)\s*['\"]?[^\s;&|'\"]*product-tree-overlay\.jsonl",
    re.I,
)

# product-tree.mjs flags that take the next token as their value; every other
# flag stands alone, so the token after it can be the subcommand.
PRODUCT_TREE_VALUE_FLAGS = {
    "--tree", "--root", "--out", "--graph", "--stack", "--max-chars",
    "--kind", "--name", "--id", "--parent", "--note",
}

PRODUCT_TREE_DECISIONS = ("agree", "reject")

SCRIPT_RUNNERS = {"node", "nodejs", "bun", "deno", "tsx", "ts-node"}

# Commands that only read a file they name; naming the overlay to one of them
# writes nothing.
OVERLAY_READERS = {
    "cat", "head", "tail", "less", "more", "wc", "grep", "egrep", "fgrep", "rg",
    "jq", "ls", "stat", "file", "diff", "cmp", "shasum", "sha256sum", "md5", "md5sum",
}


def _names_overlay(tok, cwd=None):
    """True when a token names the overlay: its casefolded text holds the
    overlay's name, or it is a path whose real target is the overlay."""
    folded = tok.casefold()
    if PRODUCT_TREE_OVERLAY_NAME in folded:
        return True
    if tok.startswith("-") or not tok or len(tok) > 4096:
        return False
    path = tok.split("=", 1)[1] if re.match(r"^[a-z]+=", tok) else tok
    path = os.path.expanduser(path)
    try:
        real = os.path.realpath(os.path.join(cwd or os.getcwd(), path))
    except (OSError, ValueError):
        return False
    return os.path.basename(real).casefold() == PRODUCT_TREE_OVERLAY_NAME


def _product_tree_decision(argv):
    """The decision a product-tree invocation records, or None. A token named
    product-tree.mjs is followed past its flags to the subcommand; a variable
    there could expand to either decision. Any script run through node and
    friends, or a .mjs/.js file run directly, that carries an agree or reject
    token is treated the same, which covers a copy of the script under
    another name."""
    for i, tok in enumerate(argv):
        base = os.path.basename(tok)
        if base == "product-tree.mjs":
            rest = argv[i + 1:]
            j = 0
            while j < len(rest) and rest[j].startswith("-"):
                flag = rest[j].split("=", 1)[0]
                j += 2 if flag in PRODUCT_TREE_VALUE_FLAGS and "=" not in rest[j] else 1
            if j < len(rest) and (rest[j] in PRODUCT_TREE_DECISIONS or rest[j].startswith("$")):
                return rest[j] if rest[j] in PRODUCT_TREE_DECISIONS else "agree or reject"
        if base in SCRIPT_RUNNERS or re.search(r"\.(?:mjs|cjs|js)$", base):
            for later in argv[i + 1:]:
                if later in PRODUCT_TREE_DECISIONS:
                    return later
    return None


def _product_tree_ask(argv, seg, cwd=None):
    """An agree or reject on a product-tree proposal, or a direct write to its
    overlay, records a person's decision. The script's own terminal check does
    not hold against an agent that allocates a pseudo-terminal, so the person
    confirms it here. Any command that names the overlay, by a casefolded
    name or through a symlink, asks unless it only reads it."""
    decision = _product_tree_decision(argv)
    if decision:
        return (
            f"product-tree.mjs {decision} records a person's decision on the product tree; "
            "the user runs it or confirms it"
        )
    overlay_write = (
        "this writes the product tree overlay directly; only product-tree.mjs propose writes "
        "it, and a decision is the user's"
    )
    if PRODUCT_TREE_OVERLAY_WRITE.search(seg):
        return overlay_write
    for m in re.finditer(r">>?\s*['\"]?([^\s;&|'\"<>]+)", seg):
        if _names_overlay(m.group(1), cwd):
            return overlay_write
    if argv and os.path.basename(argv[0]) not in OVERLAY_READERS:
        if any(_names_overlay(t, cwd) for t in argv[1:]):
            return overlay_write
    return None


def _learnings_ask(argv):
    """promote --accept, promote --retract and feedback on a G: id write the
    global learnings ledger or hide a global learning, a person's decision.
    learnings-ledger.mjs asks y/N on a terminal, but a pseudo-terminal answers
    that prompt as well as a person does, so the user confirms it here."""
    for i, tok in enumerate(argv):
        if os.path.basename(tok) != "learnings-ledger.mjs":
            continue
        rest = argv[i + 1:]
        if not rest:
            return None
        flags = [a.split("=", 1)[0] for a in rest[1:]]
        if rest[0] == "promote" and ("--accept" in flags or "--retract" in flags):
            what = "promote --accept" if "--accept" in flags else "promote --retract"
        elif rest[0] == "feedback":
            ids = _flag_values(rest[1:], {"--id"}, None)
            if not any(str(v).strip("[]").upper().startswith(("G:", "$")) for v in ids):
                return None
            what = "feedback on a G: id"
        else:
            return None
        return (
            f"learnings-ledger.mjs {what} changes a global learning every repository reads; "
            "the user runs it or confirms it"
        )
    return None


HOME_VAR = re.compile(r"^(?:\$HOME|\$\{HOME\})(?=/|$)")
ROOT_DELETE = (
    "rm -r on the filesystem root deletes everything this account can write; "
    "the user confirms it"
)
HOME_DELETE = (
    "rm -r on $HOME or a directory above it deletes every project, credential and setting "
    "under home; the user confirms it"
)


def _rm_recursive(args):
    for a in args:
        if a == "--":
            return False
        if a == "--recursive" or (
            a.startswith("-") and not a.startswith("--") and ("r" in a[1:] or "R" in a[1:])
        ):
            return True
    return False


def _rm_operands(args):
    out, ended = [], False
    for a in args:
        if not ended and a == "--":
            ended = True
        elif ended or not a.startswith("-"):
            out.append(a)
    return out


HOME_BRACED = re.compile(r"^\$\{HOME(?:(?P<op>:?[-=?+]|%%?|##?)(?P<word>[^}]*))?\}(?=/|$)")
TILDE_USER = re.compile(r"^~(?P<user>[A-Za-z0-9_][A-Za-z0-9_.-]*)(?=/|$)")


def _user_home(user):
    """The home directory ~user names, or None when no such account exists
    (the shell then leaves ~user as a literal relative name)."""
    try:
        import pwd
    except ImportError:
        return None
    try:
        return pwd.getpwnam(user).pw_dir or None
    except KeyError:
        return None


def _trim(value, pattern, op):
    """${HOME%pat}, ${HOME%%pat}, ${HOME#pat} and ${HOME##pat} on value, the
    pattern matched as a shell glob."""
    n = len(value)
    if op in ("%", "%%"):
        cuts = range(n, -1, -1) if op == "%" else range(0, n + 1)
        for i in cuts:
            if fnmatch.fnmatchcase(value[i:], pattern):
                return value[:i]
    else:
        cuts = range(0, n + 1) if op == "#" else range(n, -1, -1)
        for i in cuts:
            if fnmatch.fnmatchcase(value[:i], pattern):
                return value[i:]
    return value


def _home_expansion(tok, home):
    """tok with a leading $HOME form replaced by what the shell expands it to:
    $HOME, ${HOME}, ${HOME:?..}, ${HOME:-..}, ${HOME:=..} (home is set, so
    each is home), ${HOME:+word} (the word), the trims ${HOME%pat} and the
    like, ~ and ~user. Anything else comes back unchanged."""
    if tok == "~" or tok.startswith("~/"):
        return home + tok[1:]
    m = TILDE_USER.match(tok)
    if m:
        user_home = _user_home(m.group("user"))
        return tok if user_home is None else user_home + tok[m.end():]
    m = HOME_VAR.match(tok)
    if m:
        return home + tok[m.end():]
    m = HOME_BRACED.match(tok)
    if not m:
        return tok
    op, word, rest = m.group("op"), m.group("word") or "", tok[m.end():]
    if not op:
        return home + rest
    if op.endswith("+"):
        return word + rest
    if op[0] in "%#":
        if "$" in word or "`" in word:
            return tok
        return _trim(home, word, op) + rest
    return home + rest


def _rm_target(tok, cwd):
    """The absolute, normalised path an rm operand names, or None when it
    depends on something other than $HOME (another variable, a substitution)
    or is relative with no known working directory. A trailing `*` or `.*`
    component stands for the directory it lists."""
    t = _home_expansion(tok, os.path.expanduser("~"))
    if "$" in t or "`" in t:
        return None
    parts = t.rstrip("/").split("/") if t.rstrip("/") else [""]
    while len(parts) > 1 and parts[-1] in ("*", ".*"):
        parts.pop()
    t = "/".join(parts) or "/"
    if t in ("*", ".*"):
        t = "."
    if not os.path.isabs(t):
        if not cwd:
            return None
        t = os.path.join(cwd, t)
    return re.sub(r"^/+", "/", os.path.normpath(t))


def _destructive_rm_ask(argv, cwd):
    """rm -r on the filesystem root, on $HOME, or on a directory above it.
    Anything inside home or inside the project is an ordinary delete."""
    if not argv or os.path.basename(argv[0]) != "rm":
        return None
    args = argv[1:]
    if "--no-preserve-root" in args:
        return ROOT_DELETE
    if not _rm_recursive(args):
        return None
    homes = {
        os.path.normpath(os.path.expanduser("~")),
        os.path.realpath(os.path.expanduser("~")),
    }
    for tok in _rm_operands(args):
        p = _rm_target(tok, cwd)
        if p is None:
            continue
        if p == "/":
            return ROOT_DELETE
        named = TILDE_USER.match(tok)
        owner = _user_home(named.group("user")) if named else None
        for h in homes | ({os.path.normpath(owner)} if owner else set()):
            if p == h or h.startswith(p.rstrip("/") + "/"):
                return HOME_DELETE
    return None


FORK_HEAD = re.compile(r"\(\s*\)\s*\{")
FORK_NAME_MAX = 64
FORK_NAME_STOP = set(" \t\n(){}|&;<>")
PERL_FORK_BOMB = re.compile(r"\bfork\s+while\s+fork\b")
FORK_BOMB = (
    "a fork bomb: a function that starts two copies of itself in the background "
    "exhausts the process table; the user confirms it"
)


def fork_bomb_reason(cmd):
    """A shell function whose body pipes itself into itself in the background,
    then is called (`:(){ :|:& };:`), or perl's `fork while fork`. Each
    `(){` head is examined once with a bounded name, so the scan is linear."""
    if not isinstance(cmd, str):
        return None
    if PERL_FORK_BOMB.search(cmd):
        return FORK_BOMB
    for m in FORK_HEAD.finditer(cmd):
        end = m.start()
        while end > 0 and cmd[end - 1] in " \t":
            end -= 1
        start = end
        while start > 0 and end - start < FORK_NAME_MAX and cmd[start - 1] not in FORK_NAME_STOP:
            start -= 1
        name = cmd[start:end]
        if not name:
            continue
        n = re.escape(name)
        tail = re.compile(
            r"\s*" + n + r"\s*\|\s*" + n + r"\s*&\s*;?\s*\}\s*;?\s*" + n + r"(?![^\s;&|])"
        )
        if tail.match(cmd, m.end()):
            return FORK_BOMB
    return None


def ask_reason(toks, seg, cwd=None):
    """Why a person should confirm this segment, or None."""
    _, argv = command_word(toks)
    return (
        _gh_ask(argv, cwd)
        or _jira_ask(argv, seg)
        or _shared_ask(argv, seg)
        or _cleanup_ask(argv)
        or _product_tree_ask(argv, seg, cwd)
        or _learnings_ask(argv)
        or _destructive_rm_ask(argv, cwd)
    )


GH_TEXT_SUBS = {
    ("pr", "create"), ("pr", "edit"), ("pr", "comment"), ("pr", "review"),
    ("issue", "create"), ("issue", "edit"), ("issue", "comment"),
}


def gh_text(toks, cwd=None):
    """The title and body text a gh pull request or issue write publishes."""
    _, argv = command_word(toks)
    if not argv or os.path.basename(argv[0]) != "gh":
        return ""
    args = [a for a in argv[1:]]
    plains = [a for a in args if not a.startswith("-")]
    if len(plains) < 2:
        return ""
    if (GH_ALIASES.get(plains[0], plains[0]), plains[1]) not in GH_TEXT_SUBS:
        return ""
    parts = _flag_values(args, {"--body", "--title"}, "-b") + _flag_values(args, {"--title"}, "-t")
    parts += [read_bounded(p, cwd) for p in _flag_values(args, {"--body-file"}, "-F")]
    return "\n".join(p for p in parts if p)


def vercel_token_reason(toks):
    """A --token on the vercel command line lands in the transcript."""
    _, argv = command_word(toks)
    if not argv:
        return None
    words = [os.path.basename(argv[0])] + argv[1:3]
    if "vercel" not in words:
        return None
    if any(a in ("--token", "-t") or a.startswith("--token=") for a in argv[1:]):
        return (
            "vercel with --token puts the token on the command line; run it through the "
            "vercel wrapper, which reads the token from the credential store"
        )
    return None


SECRET_READ = re.compile(
    r"credential-store\.sh['\"]?\s+get\b|\bsecurity\s+find-(?:generic|internet)-password\b[^;&|\n]*\s-w\b"
)


def secret_echo_reason(cmd):
    """A stored secret read with nothing capturing or consuming its output prints
    it into the transcript."""
    stripped, _ = strip_heredoc_bodies(cmd)
    for m in SECRET_READ.finditer(stripped):
        before = stripped[: m.start()]
        if before.count("$(") > before.count(")") or before.count("`") % 2:
            continue
        tail = re.split(r";|&&|\|\||\n", stripped[m.end():], maxsplit=1)[0]
        if re.search(r"(?<!\|)\|(?!\|)|>", tail):
            continue
        return (
            "this prints a stored secret into the transcript; capture it in a variable "
            "(VAR=\"$(...)\"), pipe it into the consumer, or send it to /dev/null"
        )
    return None


# The guard answers inside its own deadline, so it decodes less than the
# outbound gate: a command line longer than this is not a hiding place a
# reviewer would miss anyway.
GUARD_DECODE_LIMITS = {"maxInputChars": 64 * 1024, "maxDecodedChars": 64 * 1024}


def encoded_secret_read_reason(cmd):
    """A stored-secret read hidden inside base64, hex or rot13 text
    (_decode_text.py, bounded). Reading a secret has a plain spelling; an
    encoded one only hides it from review."""
    import _decode_text

    if not isinstance(cmd, str) or not cmd:
        return None
    for v in _decode_text.decoded_variants(cmd, GUARD_DECODE_LIMITS):
        if SECRET_READ.search(v["text"]):
            return (
                "the command carries a stored-secret read hidden in " + v["kind"]
                + " text; run the read in plain text, where it can be judged"
            )
    return None


# --- the run this session drives ----------------------------------------------


def _logs_root(env=None):
    env = os.environ if env is None else env
    return env.get("LOGS_ROOT") or os.path.join(os.path.expanduser("~"), ".claude", "logs", "multi-agent")


LIVE_STATUSES = ("in_progress", "awaiting_input")
_DRIVING = {}


def driving_run(session_id, env=None):
    """The live run whose hostSessionId is this session, or None: status
    in_progress or awaiting_input (the statuses _active-run.mjs treats as
    live), the most recently written one when several match. Read once per
    hook process.

    Runs live at <root>/<project>/<task>/agent-state.json or <root>/<task>/; both
    depths are read. A missing session id matches nothing."""
    if not isinstance(session_id, str) or not session_id:
        return None
    root = _logs_root(env)
    key = (root, session_id)
    if key not in _DRIVING:
        _DRIVING[key] = _scan_driving(root, session_id)
    return _DRIVING[key]


def _scan_driving(root, session_id):
    candidates = []
    try:
        for a in os.listdir(root):
            pa = os.path.join(root, a)
            if not os.path.isdir(pa):
                continue
            candidates.append(os.path.join(pa, RUN_STATE))
            try:
                for b in os.listdir(pa):
                    candidates.append(os.path.join(pa, b, RUN_STATE))
            except OSError:
                continue
    except OSError:
        return None
    best, best_t = None, -1.0
    for path in candidates:
        try:
            st = os.stat(path)
            if st.st_size > 4 * 1024 * 1024:
                continue
            with open(path, encoding="utf-8") as fh:
                doc = json.load(fh)
        except (OSError, ValueError):
            continue
        if not isinstance(doc, dict) or doc.get("hostSessionId") != session_id:
            continue
        if doc.get("status") in LIVE_STATUSES and st.st_mtime > best_t:
            best, best_t = doc, st.st_mtime
    return best


def run_commit_reason(doc):
    """Why a commit in the attended run this session drives needs the user's
    yes (rules.md, "No auto-commit"), or None for no run or an unattended one."""
    if not isinstance(doc, dict):
        return None
    launch = doc.get("launchRequest") if isinstance(doc.get("launchRequest"), dict) else {}
    if doc.get("autopilot") is True or launch.get("mode") in ("autopilot", "background"):
        return None
    return (
        "this commits inside the pipeline run this session is driving (" + str(doc.get("taskId") or "?")
        + "); a commit waits for the user's explicit yes"
    )


# --- output format inside a run --------------------------------------------------

# A repo profile may put the ticket first in any of its styles: [KEY-1], (KEY-1),
# KEY-1:, #1 (repo-profile-derive.mjs PREFIX_RE). The type and scope follow the
# same reader's CONV_RE: a lowercase word, any parenthesised scope.
TICKET_PREFIX = r"(\s*[\[(]?\s*(?:[A-Z][A-Z0-9]+-\d+|#\d+)\s*[\])]?:?\s+)?"
COMMIT_SUBJECT = re.compile(r"^" + TICKET_PREFIX + r"[a-z]+(\([^)]+\))?!?:\s+\S")
SUBJECT_MAX = 72
SKIPPED_SUBJECTS = re.compile(r"^(Merge |Revert \"|fixup! |squash! |amend! )|^\s*wip\b", re.I)
ENTITY = re.compile(r"&(amp|lt|gt|quot|#39|#x27);")
FENCE = re.compile(r"```.*?(```|$)", re.S)
INLINE = re.compile(r"`[^`\n]*`")
JIRA_CODE = re.compile(r"\{(code|noformat)[^}]*\}.*?(\{\1\}|$)", re.S)
# A literal backslash-n meant as a line break sits between two pieces of
# text: glued to the word before it and followed by more text
# ("Summary\nThe change", "Changes:\n- a"), or after a space before a
# capital ("Summary \nNext"). One ending a token (printf hello\n), quoted or
# bracketed is a mention of the escape; \r\n and drive paths (C:\Users\name)
# are removed before the search.
LOST_BREAK = re.compile(r"(?<=[^\s\\'\"`(\[])\\n(?=[^\s'\"`)\]])|(?<=\s)\\n(?=[A-Z])")
CRLF = re.compile(r"\\r\\n")
DRIVE_PATH = re.compile(r"\b[A-Za-z]:\\\S*")


def _subject(message):
    """The first line of a commit message that carries text. A heredoc message
    (`-m "$(cat <<EOF ...)"`) reaches the hook with the opening quote on its
    own line, ahead of the body."""
    for line in (message or "").split("\n"):
        if re.search(r"[A-Za-z0-9]", line):
            return line.strip()
    return ""


def profile_conventional(cwd):
    """False when the repo's stored profile says its subjects are not
    conventional, else True (no profile, unreadable, or conventional)."""
    script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "repo-profile.mjs")
    if not os.path.isfile(script):
        return True
    try:
        import subprocess

        r = subprocess.run(
            ["node", script, "resolve", "commit.format", "--repo", cwd or os.getcwd()],
            capture_output=True, text=True, timeout=3,
        )
        doc = json.loads(r.stdout) if r.returncode == 0 and r.stdout.strip() else {}
    except (OSError, ValueError, Exception):
        return True
    value = doc.get("value") if isinstance(doc, dict) and doc.get("use") else None
    return not (isinstance(value, dict) and value.get("conventional") is False)


def commit_subject_reason(message, cwd=None):
    """Why a commit subject breaks the commit convention (rules.md), or None.

    Not judged: a subject the hook cannot read for certain (a shell expansion
    in it), git's merge, revert, fixup and squash subjects, checkpoint commits
    (wip ...), and the type check in a repo whose profile is not conventional."""
    subject = _subject(message)
    if not subject or "$" in subject or "`" in subject or SKIPPED_SUBJECTS.search(subject):
        return None
    if len(subject) > SUBJECT_MAX:
        return "the commit subject is " + str(len(subject)) + " characters; the convention caps it at " + str(SUBJECT_MAX)
    if not COMMIT_SUBJECT.match(subject) and profile_conventional(cwd):
        return (
            "the commit subject does not start with a conventional type, as in type(scope): description "
            "(after a repo profile's ticket prefix if any)"
        )
    return None


def body_text_reason(text, entities=False):
    """Why text published as a PR, issue or Jira body will render wrong, or
    None: a literal backslash-n where a line break was meant, outside Markdown
    and Jira code. With entities, an HTML entity too: a Jira payload renders
    it verbatim, while Markdown on GitHub decodes it (and needs &lt; for a
    literal angle bracket)."""
    prose = DRIVE_PATH.sub(" ", CRLF.sub(" ", INLINE.sub("", FENCE.sub("", JIRA_CODE.sub("", text or "")))))
    if LOST_BREAK.search(prose):
        return "the body carries a literal \\n; write real line breaks (a heredoc or a body file)"
    m = ENTITY.search(prose) if entities else None
    if m:
        return "the body carries the HTML entity " + m.group(0) + "; write the character itself"
    return None


def _json_strings(value, out):
    """The prose strings of a JSON body, leaving out ADF code blocks and text
    marked as code."""
    if isinstance(value, str):
        out.append(value)
    elif isinstance(value, dict):
        if value.get("type") == "codeBlock":
            return out
        marks = value.get("marks")
        if isinstance(marks, list) and any(isinstance(m, dict) and m.get("type") == "code" for m in marks):
            return out
        for v in value.values():
            _json_strings(v, out)
    elif isinstance(value, list):
        for v in value:
            _json_strings(v, out)
    return out


def payload_files(argv):
    """Files a request sends as its body: curl -d/--data/--data-binary/--json
    @file and --data-urlencode [name]@file, and gh api --input file and
    -F/--field name=@file. "@-" (stdin) is the caller's to resolve."""
    if argv and os.path.basename(argv[0]) == "gh" and len(argv) > 1 and argv[1] == "api":
        out, i = [], 2
        while i < len(argv):
            a = argv[i]
            if a == "--input" and i + 1 < len(argv):
                out.append(argv[i + 1])
                i += 1
            elif a in ("-F", "--field") and i + 1 < len(argv):
                v = argv[i + 1]
                if "=@" in v and not v.endswith("=@-"):
                    out.append(v.split("=@", 1)[1])
                i += 1
            i += 1
        return out
    if not argv or os.path.basename(argv[0]) not in HTTP_CLIENTS:
        return []
    out, i = [], 1
    while i < len(argv):
        a = argv[i]
        val = None
        if a in ("-d", "--data", "--data-binary", "--data-ascii", "--json") and i + 1 < len(argv):
            val = argv[i + 1]
            i += 1
        elif a.startswith(("--data=", "--data-binary=", "--data-ascii=", "--json=")):
            val = a.split("=", 1)[1]
        elif a == "--data-urlencode" and i + 1 < len(argv):
            m = re.match(r"^[A-Za-z0-9_.-]*@(.+)$", argv[i + 1])
            i += 1
            val = "@" + m.group(1) if m else None
        if val and val.startswith("@") and len(val) > 1 and val != "@-":
            out.append(val[1:])
        i += 1
    return out


def stdin_payload(argv):
    """True when the request reads its body from stdin (-d @-, --data-binary @-, --input -)."""
    return "@-" in argv or (len(argv) > 2 and argv[1] == "api" and "--input" in argv and "-" in argv)


# Jira issue and comment endpoints only: Bitbucket Server (/rest/api/1.0/)
# takes Markdown and Confluence storage format needs entities.
JIRA_API = re.compile(r"/rest/api/(?:2|3|latest)/(?:issue|comment)\b", re.I)


def payload_reason(path, cwd, entities=True, raw=None):
    """body_text_reason over a request body file (or raw text). A JSON body is
    judged on its decoded string values, where an escaped newline is a real
    line break. Entities are judged only for a Jira target, which renders
    them verbatim; GitHub and Bitbucket Markdown decode them."""
    raw = read_bounded(path, cwd) if raw is None else raw
    if not raw:
        return None
    try:
        text = "\n".join(_json_strings(json.loads(raw), []))
    except ValueError:
        text = raw
    return body_text_reason(text, entities=entities)


# --- confirmations ---------------------------------------------------------------


def confirmations_dir(env=None):
    env = os.environ if env is None else env
    root = env.get("LOGS_ROOT") or os.path.join(os.path.expanduser("~"), ".claude", "logs", "multi-agent")
    return os.path.join(root, "confirmations")


def command_digest(cmd):
    return hashlib.sha256(cmd.encode("utf-8")).hexdigest()


def confirmed(cmd, env=None):
    """True, and the record consumed, when confirm-command.mjs recorded the
    user's yes for exactly this command less than CONFIRM_TTL_SECONDS ago."""
    if not isinstance(cmd, str) or not cmd:
        return False
    path = os.path.join(confirmations_dir(env), command_digest(cmd) + ".json")
    try:
        fresh = time.time() - os.stat(path).st_mtime < CONFIRM_TTL_SECONDS
    except OSError:
        return False
    try:
        os.remove(path)
    except OSError:
        return False
    return fresh


# --- read-only repositories ----------------------------------------------------


def prefs_candidates(env=None):
    env = os.environ if env is None else env
    home = env.get("HOME") or os.path.expanduser("~")
    return [
        p
        for p in (
            env.get("MULTI_AGENT_PREFS"),
            os.path.join(home, ".claude", "multi-agent-preferences.json"),
            os.path.join(home, ".config", "multi-agent-pipeline", "multi-agent-preferences.json"),
        )
        if p
    ]


def read_only_roots(env=None):
    """prefs.global.readOnlyRepos[], expanded and real-pathed."""
    for p in prefs_candidates(env):
        if not os.path.isfile(p):
            continue
        try:
            with open(p, encoding="utf-8") as fh:
                roots = (json.load(fh).get("global") or {}).get("readOnlyRepos") or []
        except (OSError, ValueError, AttributeError):
            return []
        out = []
        for r in roots if isinstance(roots, list) else []:
            if isinstance(r, str) and r.strip():
                out.append(os.path.realpath(os.path.expanduser(r.strip())))
        return out
    return []


def _under(path, root):
    a = os.path.normcase(path)
    b = os.path.normcase(root)
    return a == b or a.startswith(b.rstrip(os.sep) + os.sep)


def read_only_root_of(path, roots):
    """The read-only root that contains `path`, or None."""
    if not path or not roots:
        return None
    real = os.path.realpath(os.path.expanduser(path))
    for r in roots:
        if _under(real, r):
            return r
    return None


def git_write_dir(toks, cwd):
    """(subcommand, directory) for a git call that writes history or a remote."""
    split = _git_split(toks)
    if not split or split[2] not in WRITE_SUBS:
        return None
    _, opts, sub, _ = split
    base = cwd or os.getcwd()
    for key, val in opts:
        if key in ("-C", "--work-tree") and val:
            base = val if os.path.isabs(val) else os.path.join(base, val)
        elif key == "--git-dir" and val:
            base = os.path.dirname(val.rstrip("/")) if os.path.isabs(val) else os.path.join(base, val, "..")
    return sub, os.path.normpath(base)


_ROOTS = {"loaded": False, "roots": []}


def cached_read_only_roots():
    if not _ROOTS["loaded"]:
        _ROOTS["roots"], _ROOTS["loaded"] = read_only_roots(), True
    return _ROOTS["roots"]


def read_only_file_reason(path, cwd):
    """Why an Edit / Write to `path` is refused, or None."""
    if not isinstance(path, str) or not path:
        return None
    p = os.path.expanduser(path)
    if not os.path.isabs(p):
        p = os.path.join(cwd or os.getcwd(), p)
    root = read_only_root_of(p, cached_read_only_roots())
    if root:
        return f"{path} is inside {root}, which prefs.global.readOnlyRepos lists as read-only"
    return None


def read_only_git_reason(toks, cwd):
    """Why a git commit / push (or another history write) is refused, or None."""
    hit = git_write_dir(toks, cwd)
    if not hit:
        return None
    sub, directory = hit
    root = read_only_root_of(directory, cached_read_only_roots())
    if root:
        return f"git {sub} in {root}, which prefs.global.readOnlyRepos lists as read-only"
    return None
