"""Dangerous-command detection: normalization, tokenizing, and pattern tables.

Pure command classification for :mod:`tools.approval` — no approval state, config reads, or
prompting live here.
"""

import bisect
import fnmatch
import functools
import os
import re
import shlex
import tempfile
import unicodedata

from agent.file_safety import SHELL_RC_FILES
from tools import approval_parser_budget as _parser_budget
from tools.approval_parser_budget import _scan_backtick_end, _scan_dollar_paren_end, _scan_shell
from tools.approval_ansi_c import _is_shell_comment_start, expand_ansi_c_quotes
from tools.approval_git_options import _GIT, _GIT_PUSH, _GIT_PUSH_ARGS, _join_escaped_word_chars
from tools.approval_config_set import _HERMES_CONFIG_SET_APPROVAL_POLICY
from tools.approval_env_split import _env_split_payload
from tools.approval_fetch_exec import (
    _PIPE_PATH_PREFIX_RE,
    _PIPE_WRAPPERS_RE,
    DownloadThenRunMatcher,
    heredoc_scan_sources,
)
from tools.approval_grep_spans import _grep_safe_detection_variant, _quoted_grep_pattern_spans  # re-exported
from tools.approval_hermes_store import _HERMES_HOME_BARE, _HERMES_STORE_FILE, _HERMES_STORE_PATH, _HERMES_STORE_ROOT
from tools.approval_home_fold import _rewrite_resolved_hermes_home, _rewrite_resolved_user_home
from tools.approval_shell_tokens import _shell_tokens_with_spans
from tools.approval_windows_hardline import whatif_preview_is_real, windows_hardline_patterns, windows_whatif_strict_patterns
from tools.approval_applescript import OSASCRIPT_OPAQUE_DESCRIPTION, OSASCRIPT_RISKY_DESCRIPTION, classify_osascript
from tools.approval_quoted_newlines import _mask_quoted_newlines
from tools.approval_variation_selectors import _EMOJI_RANGE, _HIDDEN_VARIATION_SELECTOR_RE
from tools.approval_wmic import WmicShadowDeleteMatcher


# Sensitive write targets, matched via ~ / $HOME / $HERMES_HOME spellings. The resolved absolute
# home is folded into these forms at detection time by _normalize_command_for_detection(), so no
# import-time path snapshot (stale once HERMES_HOME is set after import) lives in the patterns.
_SSH_SENSITIVE_PATH = r'(?:~|\$home|\$\{home\})/\.ssh(?:/|$)'
# A Hermes home: the default root or a named profile under it (profiles/<name>/ has its own config.yaml/.env).
_HERMES_HOME_DIR = (
    r'(?:~\/\.hermes/|(?:\$home|\$\{home\})/\.hermes/|(?:\$hermes_home|\$\{hermes_home\})/)'
    r'(?:profiles/[^/\s"\'`]+/)?'
)
_HERMES_ENV_PATH = (
    _HERMES_HOME_DIR + r'(?:\.op)?\.env\b'
)
# ~/.hermes/config.yaml IS the security policy (approvals.mode, yolo, allowlist) and the config cache is mtime-keyed,
# so a write takes effect mid-session. Terminal-side coverage (sed -i, tee, >, cp) pairs the file_tools deny.
_HERMES_CONFIG_PATH = (
    _HERMES_HOME_DIR + r'config\.yaml\b'
)
_PROJECT_ENV_PATH = r'(?:(?:/|\.{1,2}/)?(?:[^\s/"\'`]+/)*\.env(?:\.[^/\s"\'`]+)?)'
_PROJECT_CONFIG_PATH = r'(?:(?:/|\.{1,2}/)?(?:[^\s/"\'`]+/)*config\.yaml)'
_SHELL_RC_FILES = rf"(?:~|\$home|\$\{{home\}})/(?:{'|'.join(re.escape(f) for f in SHELL_RC_FILES)})\b"
_CREDENTIAL_FILES = r'(?:~|\$home|\$\{home\})/\.' r'(?:netrc|pgpass|npmrc|pypirc)\b'
_HOME_PREFIX = r'(?:~|\$home|\$\{home\})/'
_SECRET_FILE = (
    rf'(?:{_SSH_SENSITIVE_PATH}|{_HERMES_ENV_PATH}|{_CREDENTIAL_FILES}|{_PROJECT_ENV_PATH}(?![\w-])'
    rf'|{_HOME_PREFIX}\.(?:aws/credentials|git-credentials|config/gh/hosts\.yml|docker/config\.json|kube/config)\b'
    r'|/etc/(?:shadow|passwd)\b|\bid_(?:rsa|ed25519|ecdsa|dsa)\b)'
)
_SECRET_VAR = r'\$\{?\w*(?:key|token|secret|passwd|password|credential)\w*\}?'
# Flags whose argument becomes a request body / uploaded file. Case-sensitive: curl -D dumps headers, -f fails.
_UPLOAD_FLAG = (r'(?<!\S)(?:(?-i:-[a-zA-Z]*[dFT])|--data(?:-binary|-raw|-urlencode|-ascii)?|--form(?:-string)?'
                r'|--upload-file|--json|--post-(?:data|file)|--body-(?:data|file))')
_INVISIBLE_UNICODE_DESCRIPTION = "invisible or bidirectional Unicode control character (possible obfuscation)"
_CREDENTIAL_UPLOAD_DESCRIPTION = "upload a secret or credential file via curl/wget (possible exfiltration)"
# Global flags before a subcommand, each with an optional value. Every flag has one parse ('-' plus
# its possessive remainder, so '--x' and '--x=v' never split two ways) and a value cannot itself be a
# flag, so a long run that never reaches the subcommand fails in linear time instead of holding the
# GIL for minutes (#129281). Whole groups still backtrack to expose the target flag or verb.
_GLOBAL_FLAGS = r'(?:-\S++(?:\s++(?!-\S)\S++)?\s++)*'
# macOS: /etc, /var, /tmp, /home are symlinks to /private/*, so /private/etc/sudoers would bypass a plain
# "/etc/" check. Match both forms.
_MACOS_PRIVATE_SYSTEM_PATH = r'/private/(?:etc|var|tmp|home)/'
_SYSTEM_CONFIG_PATH = rf'(?:/etc/|{_MACOS_PRIVATE_SYSTEM_PATH})'
_SENSITIVE_WRITE_TARGET = (
    rf'(?:{_SYSTEM_CONFIG_PATH}|/dev/sd|{_SSH_SENSITIVE_PATH}|{_HERMES_ENV_PATH}|{_HERMES_CONFIG_PATH}|'
    rf'{_SHELL_RC_FILES}|{_CREDENTIAL_FILES})'
)
_USER_SENSITIVE_WRITE_TARGET = rf'(?:{_SSH_SENSITIVE_PATH}|{_SHELL_RC_FILES}|{_CREDENTIAL_FILES})'
# touch/mkdir/ln: the home-side targets only; /etc is out of their scope (#85321) and admin commands
# like `mkdir -p /etc/apt/keyrings` would be mislabelled as credential/SSH/shell-rc writes.
_HOME_SENSITIVE_WRITE_TARGET = rf'(?:{_USER_SENSITIVE_WRITE_TARGET}|{_HERMES_ENV_PATH}|{_HERMES_CONFIG_PATH})'
# Same set for touch/mkdir/ln, but a named FILE must end the shell word: `ln -s a ~/.bashrc.bak` /
# `touch ~/.bashrc.d/x` name a sibling, not the startup or credential file (`~/.ssh/` is a directory: any entry;
# a bare `~/.ssh` operand anywhere in the command names the directory itself, `~/.sshx` does not).
# A glued redirect (`touch ~/.bashrc>/dev/null`) ends the word too; the ln rule also allows trailing redirects.
_HOME_SENSITIVE_CREATE_TARGET = (
    rf'(?:{_SSH_SENSITIVE_PATH}|(?:{_HOME_PREFIX}\.ssh|{_SHELL_RC_FILES}|{_CREDENTIAL_FILES}|{_HERMES_ENV_PATH}|{_HERMES_CONFIG_PATH})'
    r'(?=["\'\s;&|)`<>]|$))'
)
_PROJECT_SENSITIVE_WRITE_TARGET = rf'(?:{_PROJECT_ENV_PATH}|{_PROJECT_CONFIG_PATH})'
# cp/mv/install: the sensitive path is a write target only as the LAST argument (destination), so
# `cp config.yaml backup.yaml` (config.yaml as SOURCE) stays out.
_COMMAND_TAIL = r'(?:\s*(?:&&|\|\||;).*)?$'
# `>`/`>>`/tee: the path is ALWAYS a write target regardless of what follows, so only require a
# shell word boundary (_COMMAND_TAIL let `echo x > .env extra` / `echo x > .env # note` slip past).
# `#` is deliberately NOT a boundary: a glued `#` is part of the filename (`.env#backup`).
_WRITE_TARGET_BOUNDARY = r'(?=[\s;&|<>"\']|$)'

# ---- Hardline (unconditional) blocklist ---------------------------------------------------
# Commands that NEVER run via the agent, regardless of --yolo, approvals.mode=off, or cron approve
# mode — a floor below yolo. Applies only to environments that can damage the host (local, ssh,
# container-host cron); containerized backends already bypass the dangerous-command layer.
# Deliberately tiny: only things with no recovery path (root wipe, raw block device writes,
# shutdown, DoS). Recoverable operations (git reset --hard, chmod -R 777, curl|sh) stay in
# DANGEROUS_PATTERNS.

# Start-of-command position: start of string, newline, subshell opener ($( or backtick), optionally consuming
# sudo/env/exec/nohup/setsid/time wrappers. Keeps shutdown/reboot rules from firing on "echo reboot" / "grep
# 'shutdown' log". Real ;/&/| separators are converted to newlines by the quote-aware _mark_command_starts pass;
# keeping them here mistakes quoted data (grep '(safe|rm -rf /)') for commands.
# The verb is argv[1] for multi-call binaries; options before it are not applet selection (busybox --help reboot).
# A path-spelled verb (/sbin/reboot, ./rm, C:/.../shutdown.exe) is still that verb. A segment never crosses the `)`
# closing a substitution that _CMDPOS anchored inside: `ls $(pwd)/reboot` is data. Every run is possessive so a failed
# match never re-splits a whitespace / path / busybox run (cubic on blank-line runs; re.search holds the GIL), and only
# the last newline of a whitespace run starts a match (earlier ones reach the same word, rescanning once per newline).
# A segment holds no `=` / `<` / `>`: `HERMES_HOME=/tmp/x hermes` and `socat>/tmp/log` are not program paths.
_CMD_PATH = r'(?:/?+(?:[^\s/)=<>]++/)*+)?+'
_MULTI_CALL_PREFIX = r'(?:' + _CMD_PATH + r'(?:busybox|toybox)\b\s++)?+'

# Every run is possessive: a failed command-name match must not re-split a whitespace run between the
# leading and trailing \s (cubic on a long blank-line run, and re.search holds the GIL while it runs).
# Only the last newline of a whitespace run starts a match: an earlier one consumes the same run and
# reaches the same command word, so trying each would rescan the run once per newline.
_CMDPOS = (
    r'(?:^|\n(?![^\S\n]*+\n)|`|\$\()' r'\s*+'  # start position, optional whitespace
    r'(?:sudo\s++(?:-[^\s]++\s++)*+)?' r'(?:env\s++(?:\w+=\S*+\s++)*+)?'  # optional sudo with flags, env VAR=VAL pairs
    r'(?:(?:exec|nohup|setsid|time)\s++)*+' r'\s*+'  # optional wrapper commands
    + _MULTI_CALL_PREFIX  # other wrappers (nice, timeout, command ...) are peeled by tools.approval_wrappers
    + _CMD_PATH
)

# Destructive-path matcher for the rm hardline rules: accept the path fully wrapped in a matching
# quote pair (`rm -rf "/"`, `rm -rf "$HOME"`) OR bare with a terminator (whitespace, end, or
# `) ` ; | &` so `$(rm -rf /)` is caught). A bare-token-only anchor lets quoted spellings slip past the floor.
# A quoted path must end its shell word too, past root-collapse components (`"C:/"./`, `"$HOME"/*`):
# `"$HOME"/build` and `"C:/"Users/me/build` name a subdirectory, not the protected root. The components
# may be quoted too (`"$HOME"'/'`, `"/"'./'"/"*`), but a quoted `*` is a literal name, not a glob.
# Every repeat is possessive: each piece ends at `/` or a quote, so the scan stays linear. Bare dots may
# also end at a quote whose segment starts the slash (`"/"..'/'` is `/../`), never one that adds dots (`...`).
_RM_COLLAPSE_SEG = r'(?:(?:\.\.?)?/)*+(?:\.\.?)?'
_RM_ROOT_COLLAPSE_TAIL = (rf'(?:(?:\.\.?)?/|\.\.?(?=["\']/)|"{_RM_COLLAPSE_SEG}"|\'{_RM_COLLAPSE_SEG}\')*+'
                          r'(?:\.\.?)?\**+(?=\s|$|[)`;|&])')


def _hardline_rm_path(path_alt: str, tail: str = r'(?:\s|$|[)`;|&])') -> str:
    return rf'(?:["\'](?:{path_alt})["\']{_RM_ROOT_COLLAPSE_TAIL}|(?:{path_alt}){tail})'


# Protected system roots whose recursive deletion has no recovery path.
# A trailing slash names the same dir (`/etc/`, dequoted `"/etc"/`); `.`/`..` before the glob climb (`/etc/../*` is `/*`).
_HARDLINE_SYSTEM_DIRS = r'(?:/home|/root|/etc|/usr|/var|/bin|/sbin|/boot|/lib)(?:/++(?:\.\.?+/++)*+\*?)?+'
# A quoted root glued to a system dir name is one shell word: `rm -rf "/"etc` deletes /etc, and so do
# `"/""etc"` / `"/"e"tc"` (quotes in the name are removed). One closing quote: the tail owns `""` pairs (a run was quadratic).
_QUOTED_ROOT_SYSTEM_DIR = (r'["\']/+["\']["\']*(?:' + '|'.join(r'["\']*'.join(name) for name in (
    'home', 'root', 'etc', 'usr', 'var', 'bin', 'sbin', 'boot', 'lib')) + r')["\']?' + _RM_ROOT_COLLAPSE_TAIL)

# `rm` plus flag group, shared by the rm hardline rules (plain concatenation, not f-string:
# backslashes in replacement fields are unsupported on the 3.11 floor). _CMDPOS-anchored so `rm`
# must be an actual command word (Git Bash's `rm.exe` too) — "rm -rf /" as DATA in `git commit -m "…rm -rf /…"` must not trip the floor.
_RM_FLAG_PREFIX = _CMDPOS + r'rm(?:\.exe)?\s+(-[^\s]*\s+)*'
# Vetoes the drive-root rules when THIS PowerShell delete carries a literal -Include that narrows it (`*.tmp`):
# not after cmd `/s` or GNU `--` (a file name there), not inside quotes/comments, not `*`/`*.*`/a list/`$x`,
# and never past a `)` that closes rm's own `$(...)`/subshell (`echo $(rm -rf C:/) -Include x` is echo's flag).
_PS_INCLUDE_NARROWS = r'(?!(?!(?:[^\r\n;&|]*\s)?(?:/s\b|--(?:\s|$)))(?:[^\r\n;&|#"\'`)]|"[^"\n]*"|\'[^\'\n]*\')*[^\S\r\n]-inc[a-z]*(?::|\s+)["\']?(?=[^\s,;&|"\'$`(){}@]*[^\s,;&|"\'$`(){}@*?.])[^\s,;&|"\'$`(){}@]+["\']?(?!\s*,)(?:[\s;&|)]|$))'
# Package-manager global options, each optionally taking ONE non-dash operand.
_PKG_OPTS = r'(?:-[^\s]+(?:\s+[^-\s][^\s]*)?\s+)*'

HARDLINE_PATTERNS = [
    # Root path: any root-anchored path whose components collapse to "/" in the shell ("/", "//",
    # "/.", "/./", "/../..", optional trailing glob). Each inter-slash segment must be exactly "."
    # or "..", so "/tmp", "/.ssh", even "/..." are literal dirs that fall through to the softer
    # DANGEROUS rules. The "/ \*" alt covers `rm -rf / *` (two args: "/" plus the glob).
    (_RM_FLAG_PREFIX + _hardline_rm_path(r'/(?:(?:\.\.?)?/)*(?:\.\.?)?\**|/ \*'), "recursive delete of root filesystem"),
    # Drive-letter root (`C:/`, `c:/*`; `C:\` reaches here as `C:/` via the Windows-path variant): same floor as "/".
    # A quoted bare `"C:"` counts only when the next quoted/bare segment starts the root slash (`"C:"'/'`).
    # PowerShell's `rm` alias with a literal narrowing `-Include` (`rm -r C:/* -Include *.tmp`) deletes only matches.
    # Caveat: Hermes runs the bare command through bash, where GNU rm rejects `-Include` unless POSIXLY_CORRECT is
    # set; then getopt stops at the root operand and `-Include` is a file name, so that delete only prompts.
    (_CMDPOS + r'rm\s+' + _PS_INCLUDE_NARROWS + r'(-[^\s]*\s+)*' + _hardline_rm_path(r'[a-z]:/(?:(?:\.\.?)?/)*(?:\.\.?)?\**|[a-z]:/ \*|[a-z]:(?=["\']["\']?/)'),
     "recursive delete of drive root"),
    (_RM_FLAG_PREFIX + '(?:' + _hardline_rm_path(_HARDLINE_SYSTEM_DIRS) + '|' + _QUOTED_ROOT_SYSTEM_DIR + ')',
     "recursive delete of system directory"),
    (_RM_FLAG_PREFIX + _hardline_rm_path(r'(?:~|\$\{?HOME\}?)(?:/?|/\*)?'), "recursive delete of home directory"),
    # Command-name rules (mkfs, dd, kill, shutdown...) are _CMDPOS-anchored so quoted prose
    # (`echo "does this use mkfs?"`) cannot trip the floor.
    # See #93392.
    (_CMDPOS + r'mkfs(\.[a-z0-9]+)?\b', "format filesystem (mkfs)"),
    # `dd` is a command-name token, so anchor it to command position like mkfs/rm/shutdown (#93392): quoted
    # prose such as `git commit -m "never dd of=/dev/sda"` is an argument, not a command. The argument tail
    # ([^\n]*of=/dev/...) is kept so flag order doesn't matter.
    (_CMDPOS + r'dd\b[^\n]*\bof=/dev/(sd|nvme|hd|mmcblk|vd|xvd)[a-z0-9]*', "dd to raw block device"),
    # Positionless rules (no command-name token: `>` sits mid-command, the fork bomb is a function
    # definition) are matched against a QUOTE-MASKED variant (_QUOTE_MASKED_HARDLINE_DESCRIPTIONS /
    # _mask_quoted_prose) so quoted prose cannot trip them; sh -c / bash -c / eval payloads still scan raw.
    # The redirect rule has no command-name token to anchor (`>` appears mid-command: `cat f > /dev/sda`),
    # so command-position anchoring is the wrong tool. It is instead matched against a QUOTE-MASKED variant
    # of the command (see _QUOTE_MASKED_HARDLINE / _mask_quoted_strings) so quoted prose (`echo "cat f >
    # /dev/sda"`) cannot trip it, while shell-carrying wrappers (sh -c / bash -c / eval) still surface their
    # payload as a raw detection variant — quoting is not a bypass (#93392).
    (r'>\s*/dev/(sd|nvme|hd|mmcblk|vd|xvd)[a-z0-9]*\b', "redirect to raw block device"),
    (r':\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:', "fork bomb"),
    # Kill every process on the system — anchor the command-name token so `echo "kill -1 sends SIGHUP to
    # everything"` doesn't trip (#93392).
    (_CMDPOS + r'kill\s+(-[^\s]+\s+)*-1\b', "kill all processes"),
    (_CMDPOS + r'(shutdown|reboot|halt|poweroff)\b(?!-|\.(?!exe\b))', "system shutdown/reboot"),
    (_CMDPOS + r'init\s+[06]\b', "init 0/6 (shutdown/reboot)"),
    (_CMDPOS + r'systemctl\s+(poweroff|reboot|halt|kexec)\b', "systemctl poweroff/reboot"),
    (_CMDPOS + r'telinit\s+[06]\b', "telinit 0/6 (shutdown/reboot)"),
    *windows_hardline_patterns(_CMDPOS),
]

# Pre-compiled at module load so the hot-path matcher never pays the cold re.compile fan-out
# (re._cache can be evicted by unrelated regex work).
_RE_FLAGS = re.IGNORECASE | re.DOTALL
# Positionless hardline rules matched against quote-masked variants (see above).
_QUOTE_MASKED_HARDLINE_DESCRIPTIONS = frozenset({"redirect to raw block device", "fork bomb"})
HARDLINE_PATTERNS_COMPILED = [
    (re.compile(p, _RE_FLAGS), d, d in _QUOTE_MASKED_HARDLINE_DESCRIPTIONS) for p, d in HARDLINE_PATTERNS
]
_WHATIF_STRICT = windows_whatif_strict_patterns(_CMDPOS)
_HARDLINE_PATTERNS_NO_WHATIF = [
    (re.compile(_WHATIF_STRICT[d], _RE_FLAGS), d, q) if d in _WHATIF_STRICT else (r, d, q)
    for r, d, q in HARDLINE_PATTERNS_COMPILED
]
# Commands that hand a quoted argument to another shell to EXECUTE: quoted text is code, not
# prose, so quote-masked hardline rules scan the raw string.
_SHELL_CARRIER_NAMES = frozenset({"eval", "sh", "bash", "zsh", "ksh", "dash", "source", "."})
# The shell members of _SHELL_CARRIER_NAMES, as one tuple plus alternation shared by every
# pipe/decode/process-substitution/heredoc pattern and the structural -c payload scan, so
# the shell-name list cannot drift between them again (the drift let `curl url | zsh` and
# `dash -c` through while bash/sh were flagged).
_SHELL_NAMES = ("bash", "sh", "zsh", "ksh", "dash")
_SHELL_NAMES_RE = "|".join(_SHELL_NAMES)
# Pipe-to-shell sink: the shell may sit behind launcher words (`sudo -u root -E`, `env -i A=1`,
# `/usr/bin/env`, `timeout 60`, `busybox`), be path-qualified (/bin/sh, ./zsh,
# C:\\msys64\\...\\bash.exe), quoted, .exe-suffixed, or followed by a redirect instead of
# whitespace. The lookahead terminator keeps `shred`, `shellcheck` and `bash-helper` out.
# fish/csh/tcsh read a script on stdin too, so they count here (they take no part in the -c
# payload scan). Launcher tokens fall in disjoint classes (a flag that takes a value -- sudo/env
# `-u USER`, `-g`, `-C` ... -- a bare flag, VAR=value, a duration) inside atomic/possessive
# groups, so each token has one parse and the scan stays linear; `sudo -u bash cat` reads `bash`
# as the user, not the shell.
_PIPE_SHELL_NAMES_RE = "|".join((*_SHELL_NAMES, "fish", "csh", "tcsh", "ash"))
_PIPE_SHELL_TOKEN_RE = (
    rf"['\"]?{_PIPE_PATH_PREFIX_RE}(?:{_PIPE_SHELL_NAMES_RE})(?:\.exe)?(?=['\"\s;&|<>)`]|$)"
)
# A stdin-reading interpreter with no script argument (or `-`) runs the piped text as code;
# `python3 -m json.tool` / `node script.js` name their own program and stay out. Output redirects
# (`> out.txt`, `2>&1`, `&>> log`) leave stdin alone; an input redirect replaces it and stays out.
_PIPE_OUTPUT_REDIRECT_RE = r"\s*+(?:[0-9]*+>>?|&>>?)\s*+(?:&[0-9-]|[^\s;&|<>()`]++)"
_PIPE_INTERPRETER_TOKEN_RE = (
    rf"{_PIPE_PATH_PREFIX_RE}(?:python[0-9.]*|node|perl|ruby|php)(?:\.exe)?(?:\s++-)?"
    rf"(?:{_PIPE_OUTPUT_REDIRECT_RE})*+(?=\s*+(?:[;&|)`}}]|$))"
)
# Lookup/list modes name a shell without running it (`command -v bash`, `sudo -l bash`). The `l`
# must be a bare flag: in `sudo -pl bash` / `-ul` it is the VALUE of -p / -u and bash runs.
_PIPE_LOOKUP_ONLY_RE = re.compile(
    rf"{_PIPE_PATH_PREFIX_RE}(?:command\s+-[a-zA-Z]*[vV]|sudo\s+(?:-(?-i:[^\W\dugUCDhpRrtT])*l|--list))\b",
    re.IGNORECASE,
)
# `| (bash)` / `| { bash; }`: a subshell or group opener in front of the sink still feeds it stdin.
_PIPE_SINK_RE = re.compile(
    rf"(?:\|&?\s*|>\(\s*)(?:[({{]\s*+)*+{_PIPE_WRAPPERS_RE}(?:{_PIPE_SHELL_TOKEN_RE}|{_PIPE_INTERPRETER_TOKEN_RE})",
    re.IGNORECASE,
)
_PIPE_FETCH_RE = re.compile(r"\b(?:curl|wget)\b", re.IGNORECASE)
_PIPE_OPERATOR_RE = re.compile(r"\|&?\s*|>\(\s*")
# The widened sink skips `||` (an or-list, not a pipe); main's raw sink keeps the old operator.
_PIPE_ONLY_OPERATOR_RE = re.compile(r"(?<!\|)\|(?!\|)&?\s*|>\(\s*")


# main's original sink (bare or slash-prefixed shell), scanned on the RAW text: a quoted payload handed
# to any carrier (su -c, ssh, xargs, docker exec ...) stays flagged exactly as before.
_PIPE_BARE_SINK_RE = re.compile(rf"\|\s*(?:[/\w]*/)?(?:{_SHELL_NAMES_RE})(?:\s|$|-c)", re.IGNORECASE)


_WMIC_SHADOW_DELETE_DESCRIPTION = "delete volume shadow copies (wmic)"
_DOWNLOAD_THEN_RUN_DESCRIPTION = "execute a just-downloaded file"
class _PipeRemoteToShellMatcher:
    """Linear stand-in for the pipe-to-shell regex: find the first curl/wget, then try a sink only at
    each later `|` / `>(` (a leading `.*` rescanned the tail from every fetch word: quadratic).
    Two sinks: main's bare-shell sink on the raw text, so no case main caught is lost; and the widened
    launcher/path/quoted sink on quote-masked text, so prose that merely mentions a wrapped pipe stays
    quiet (raw again under an eval / sh -c carrier, whose quoted argument is code)."""

    def search(self, text: str):
        fetch = _PIPE_FETCH_RE.search(text)
        if fetch is None:
            return None
        if match := self._scan(text, fetch.end(), _PIPE_BARE_SINK_RE, _PIPE_OPERATOR_RE, lookup_guard=False):
            return match
        widened = text if _contains_shell_carrier(text) else _mask_quoted_prose(text)
        return self._scan(widened, fetch.end(), _PIPE_SINK_RE, _PIPE_ONLY_OPERATOR_RE, lookup_guard=True)

    @staticmethod
    def _scan(text: str, pos: int, sink: re.Pattern, operator: re.Pattern, lookup_guard: bool):
        while (op := operator.search(text, pos)) is not None:
            match = sink.match(text, op.start())
            if match and not (lookup_guard and _PIPE_LOOKUP_ONLY_RE.match(text, op.end())):
                return match
            pos = op.end()
        return None


_DEV_SOCKET_RE = re.compile(r"/dev/(?:tcp|udp)/", re.IGNORECASE)
# Redirect operators bash opens a /dev/tcp target for (`<<` is a heredoc delimiter, `>&N` a dup).
# No leading fd digits: search() only reads op.end(), and a `[0-9]*` prefix rescans a digit run from every offset.
_DEV_SOCKET_REDIRECT_OP_RE = re.compile(r"&>>?|<>|>>|>&|<&|>\||(?<!<)<(?!<)|>")


class _DevSocketRedirectMatcher:
    """`... > /dev/tcp/h/p` reverse shells. The operator is found on the quote-masked text, so prose that
    quotes a redirect stays quiet; the operand is then read and dequoted from the real text, so a quoted
    target (`> "/dev/tcp/h/1"`, `3<>'/dev/udp/h/53'`, `> /dev/"tcp"/h/1`) still counts."""

    def search(self, text: str):
        # No literal "/dev/" prefilter: the operand is dequoted below, so `> /"dev"/tcp/h/1` must reach it.
        for op in _DEV_SOCKET_REDIRECT_OP_RE.finditer(_mask_quoted_prose(text)):
            _, _, word = _read_shell_word(text, op.end())
            if _DEV_SOCKET_RE.match(_deobfuscate_shell_word_for_detection(word)):
                return op
        return None


def _contains_shell_carrier(command: str) -> bool:
    """Return whether any command-position word is a shell-carrying command."""
    return any(
        os.path.basename(_deobfuscate_shell_word_for_detection(word)).lower() in _SHELL_CARRIER_NAMES
        for _, _, word in _iter_shell_command_word_spans(command)
    )


def _mask_quoted_prose(command: str) -> str:
    """Blank out quoted string CONTENT for positionless hardline matching (detection-only).
    Quote characters stay; inside double quotes `$(...)` and backtick spans are kept RAW because
    the shell really executes them. An unclosed quote masks to end-of-string, which cannot hide a
    runnable command (the shell would not run it either).

    Detection-only rewrite used by the quote-masked hardline rules (redirect-to-block-device, fork bomb):
    text inside single or double quotes is data the shell passes as an argument, so `echo "cat f >
    /dev/sda"` must not trip the unconditional floor (#93392). Unquoted text is untouched.
    """
    return "".join(
        command[i:j] if quote is None or kind in ("quote", "subst") else " " * (j - i)
        for kind, i, j, quote in _scan_shell(command, subst="q", naive_backtick=True)
    )


# ---- Sudo stdin guard: without SUDO_PASSWORD configured, an explicit "sudo -S" is the LLM piping
# a guessed password via stdin (brute-force vector). Unconditional block.
_SUDO_STDIN_RE = re.compile(r'(?:^|[;&|`\n]|&&|\|\||\$\()\s*sudo\s+-S\b', re.IGNORECASE)


def _check_sudo_stdin_guard(command: str) -> tuple:
    """Detect ``sudo -S`` without configured SUDO_PASSWORD -> (is_blocked, description). When
    SUDO_PASSWORD is set, ``_transform_sudo_command`` injects ``-S`` itself, so this guard only
    fires when the LLM wrote it explicitly."""
    if "SUDO_PASSWORD" not in os.environ and _SUDO_STDIN_RE.search(_normalize_command_for_detection(command).lower()):
        return (True, "sudo password guessing via stdin (sudo -S)")
    return (False, None)


def detect_hardline_command(command: str) -> tuple:
    """Check hardline patterns (NEVER bypassable, even in YOLO) -> (is_hardline, description). The size
    and real-nesting limits refuse. A scan that runs out of its step budget refuses only when the
    linear :func:`_hardline_fallback` matches a rule; otherwise it returns (False, None) and
    :func:`detect_dangerous_command` reports it as a finding only a human may approve, once."""
    complete = True
    try:
        with _parser_budget.parser_budget(command):
            verdict = _detect_hardline_command(command)
    except RecursionError:
        verdict = (True, _PARSER_LIMIT_DESCRIPTION)
    except _parser_budget.ParserBudgetExceeded:
        fallback = _hardline_fallback(command)
        verdict, complete = ((True, fallback + _FALLBACK_MATCH_SUFFIX) if fallback else (False, None)), False
    _parser_budget.record_scan(command, complete)
    return verdict


# Where a command may start, for the fallback below: separators, grouping, substitution openers,
# quotes (so `sh -c "mkfs …"` exposes its payload) and the compound-command keywords. The
# quote-free variant keeps quotes out (they are deleted) and `${` intact, so `rm -rf ${HOME}` holds.
_FALLBACK_COMMAND_START_RE = re.compile(
    r"\$\(|[;&|(){}`'\"\n]|(?<![\w./-])(?:if|then|else|elif|do|while|until|!)(?=\s)")
_FALLBACK_UNQUOTED_START_RE = re.compile(
    r"\$\(|[;&|()`\n]|(?<!\$)\{|\}|(?<![\w./-])(?:if|then|else|elif|do|while|until|!)(?=\s)")


def _hardline_fallback(command: str) -> str | None:
    """The hardline rule a budget-tripped command may hold, from a linear over-approximation.

    The full scan finds command positions with a quote-aware walk; when it runs out of budget, a
    verb it never reached (`true; reboot`, `(reboot)`, `sudo reboot`, `bash -c 'rm -rf /'` after a
    few hundred benign lines) must still refuse, not become an approvable prompt. Every rule runs
    over the raw, the `$'…'`-expanded and the normalized text, each as is and with every possible
    command start turned into a line break, and again with quote characters deleted (so `r$'m'`,
    `"of=/dev/sda"` and `${HOME}` read as the shell reads them). That treats quoted prose as code
    (false refusals) and adds no super-linear pattern. It is not complete: what it misses gets the
    human-only once/deny prompt."""
    for text in (command, expand_ansi_c_quotes(command), _normalize_command_for_detection(command)):
        lowered = text.lower()
        unquoted = lowered.replace("'", "").replace('"', "")
        for variant in (lowered, _FALLBACK_COMMAND_START_RE.sub("\n", lowered),
                        unquoted, _FALLBACK_UNQUOTED_START_RE.sub("\n", unquoted)):
            for pattern_re, description, _quote_masked in HARDLINE_PATTERNS_COMPILED:
                if pattern_re.search(variant):
                    return description
    return None


def hardline_scan_incomplete(command: str) -> bool:
    """True when the hardline scan of *command* ran out of budget before reading all of it."""
    complete = _parser_budget.recorded_scan(command)
    if complete is None:
        detect_hardline_command(command)
        complete = _parser_budget.recorded_scan(command)
    return complete is False


def _detect_hardline_command(command: str) -> tuple:
    if _command_parser_limit_exceeded(command):
        return (True, _PARSER_LIMIT_DESCRIPTION)
    # The malformed-quoting verdict needs the author's quote state. Normalization strips escapes
    # (`\"` -> `"`), so a shell-valid pattern like `grep -o "[^\"]*"` lexed as unterminated and was
    # reported as a hardline block (118 of 125 hardline blocks in one week of real use, every one a
    # benign grep). Only quoted newlines are masked: they are data, and masking keeps quoting intact.
    # Read the floors' sources: the raw command (a body may be a script something runs later) and the
    # body-dropped copies (a body quote can hide a grep after the terminator from the raw read).
    for source in heredoc_scan_sources(command, _SHELL_NAMES_RE, floors=True):
        if _grep_safe_detection_variant(_mask_quoted_newlines(expand_ansi_c_quotes(source)))[1]:
            return (True, _MALFORMED_EXEC_DESCRIPTION)
    from tools.approval_wrappers import hardline_detection_variants

    # The -WhatIf preview exemption holds only when every guarded statement previews on its own (judged on the raw
    # command: masking a quoted newline joins statements); otherwise those rules apply without it.
    patterns = HARDLINE_PATTERNS_COMPILED
    if "whatif" in command.lower() and not whatif_preview_is_real(command):
        patterns = _HARDLINE_PATTERNS_NO_WHATIF
    capped: list[str] = []
    for command_variant in hardline_detection_variants(command, capped=capped):
        variant_lower = command_variant.lower()
        masked_lower: str | None = None
        for pattern_re, description, quote_masked in patterns:
            if quote_masked and masked_lower is None:
                # Positionless rules see quoted prose as DATA, except under shell carriers
                # (sh -c, eval, source) whose quoted argument is code — those scan raw. bash -c
                # payloads also surface as their own raw variants via _execution_flag_findings.
                masked_lower = (
                    variant_lower if _contains_shell_carrier(command_variant)
                    else _mask_quoted_prose(command_variant).lower()
                )
            if pattern_re.search(masked_lower if quote_masked else variant_lower):
                return (True, description)
    # eval code nested past _MAX_EVAL_NESTING was not inspected: fail closed like the other parser limits.
    return (True, _PARSER_LIMIT_DESCRIPTION) if capped else (False, None)


# ---- Dangerous command patterns -----------------------------------------------------------
# PowerShell accepts any unambiguous parameter prefix (``-r`` is ``-Recurse``, ``-fo`` is
# ``-Force``), so spelling the switches out in full misses ``ri -r -fo``. On Remove-Item and
# Remove-ItemProperty ``-f`` alone is ambiguous with ``-Filter`` and refuses to run; on
# Stop-Process and Stop-Service ``-Force`` is the only F parameter, so ``-f`` already means it.
_PS_RECURSE = r"-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?\b"
_PS_FORCE = r"-fo(?:r(?:c(?:e)?)?)?\b"
_PS_FORCE_ONLY_F = r"-f(?:o(?:r(?:c(?:e)?)?)?)?\b"
_PS_DELETE_VERB = r"(?:remove-item|rmdir|erase|del|rd|ri|rm)"
# powershell/pwsh as the program a command runs: line start, a shell separator, or a launcher
# (sudo -u bob, env FOO=1, timeout 5, xargs, wsl, cmd /c, ssh -p 22 <host>; option tokens may carry
# one value; ssh and cmd /c may quote the remote command), with an optional directory prefix (`C:\\...\\powershell.exe`). The prefix excludes
# `(){}` and backticks so a run of them is not re-scanned from every position (quadratic). Likewise
# for blank-line runs: the whitespace before the program is possessive (the prefix class excludes
# whitespace, so nothing is lost) and, as in _CMDPOS, only the last newline of a run starts a match.
_PS_LAUNCHER_OPTIONS = r"(?:\s+-\S+(?:\s+[^\s;&|=-][^\s=]*(?!\S))?|\s+\w+=\S*)*"
_PS_EXE_AT_COMMAND_POSITION = (
    r"(?:^|[;&|({`]|\n(?![^\S\n]*+\n)"
    r"|(?:^|[;&|({`]|\n(?![^\S\n]*+\n))\s*+(?:sudo|doas|env|exec|nohup|start|time|nice|command|xargs|wsl|busybox|timeout\s+\S+)"
    + _PS_LAUNCHER_OPTIONS + r"\s"
    r"|\bcmd(?:\.exe)?\s+/[ck]\s+[\"']?"
    r"|(?:^|[;&|({`]|\n(?![^\S\n]*+\n))[^\S\n]*+ssh(?:[^\S\n]+-[^\s;&|]+(?:[^\S\n]+[^\s;&|-][^\s;&|]*)?)*[^\S\n]+[^\s;&|-][^\s;&|]*[^\S\n]+[\"']?)"
    r"\s*+(?:[^\s;&|\"'(){}\x60]*[\\/])?(?:powershell|pwsh)(?:\.exe)?(?=\s)"
)

# An argument may open with a quote the shell strips (`"-f"`, `'+main'`, `"--force"`).
_GIT_PUSH_ARG_START = r'''\s["']?'''
_DEV_TCP_REDIRECT_DESCRIPTION = "reverse shell via /dev/tcp or /dev/udp redirect"
# PowerShell verbs/aliases that write a registry key when given a provider path.
_REG_WRITE_VERB = r'(?:sp|si|ni|set-item|new-item|md|mkdir)'

DANGEROUS_PATTERNS = [
    # A drive letter is a root too (`rm X:/f`; `X:\f` arrives as `X:/f` via the Windows-path variant).
    (r'\brm\s+(-[^\s]*\s+)*["\']?(?:[a-z]:)?/', "delete in root path"),
    (r'\brm\s+-[^\s]*r', "recursive delete"),
    (r'\brm\s+--recursive\b', "recursive delete (long flag)"),
    # GNU rm permutes options, so flags may FOLLOW operands (`rm build/ -rf`). The operand run
    # cannot cross a command separator (so `rm foo | grep -r` is not attributed to rm), a quote,
    # or a bare ` -- ` end-of-options (after which `-rf` is a literal filename). The flag token
    # must follow whitespace so the `r` in long options like `--registry` does not count.
    (r'\brm\s+(?!--(?:\s|$))(?:(?!\s--(?:\s|$))[^\n"\';|&])*\s' r'(?:-[a-z]*r[a-z]*\b|--recursive\b)',
     # GNU rm permutes options, so a recursive flag group may legally FOLLOW the operands: `rm build/ -rf`,
     # `rm build/ -r -f`, and `rm build/ --recursive --force` are all equivalent to the flags-first
     # spellings the two patterns above catch — without this rule they run with no approval prompt at all.
     # Port of openai/codex#33464 ("recognize force options when they follow operands").
     "recursive delete (flags after operands)"),

    # Windows cmd/powershell destructive built-ins: gate only when executed through the shell so
    # prose/filenames containing "del"/"rd" do not trip.
    (r'\bcmd(?:\.exe)?\s+/(?:c|k)\s+.*\b(?:del|erase|rd|rmdir)\b', "Windows cmd destructive delete"),
    # PowerShell runs the verb as default positional arg (no -Command needed); anchor the verb to command
    # position (after leading -Flag switches and optional -Command/-c) so `-File c:\del-logs\run.ps1` is not caught.
    (r'\b(?:powershell|pwsh)(?:\.exe)?\b(?:\s+-\S+)*\s+(?:-(?:command|c)\s+)?["\']?' + _PS_DELETE_VERB + r'\b', "Windows PowerShell destructive delete"),
    # The same delete later in the script: `powershell -NoProfile "gci C:\\data | ri -r -fo"` (Windows
    # PowerShell runs a positional argument as the command) puts the verb after a pipe, `;` or a
    # `{ }` block, where the rule above walks past it. Like that rule, no switch is required:
    # `gci -Recurse -File | ri` deletes every file with none. The executable must be at command
    # position (or behind sudo/cmd /c/ssh <host>) and the quote must open its first non-flag argument,
    # so `echo powershell "gci | ri"`, `pwsh -v; jq ".a | del(.b)"` and `cd ~/powershell-scripts &&
    # git grep "a|rd"` stay quiet, and an outer-shell `powershell -c Get-Date; rm notes.txt` is left
    # to the rm rules. The span runs to the OUTER quote, so a nested `'C:\\work dir'` cannot end it.
    (_PS_EXE_AT_COMMAND_POSITION + r'(?:\s+-\S+)*\s+(?:"[^"\n]*|\'[^\'\n]*)[|;{(]\s*' + _PS_DELETE_VERB + r'(?![\w-])',
     "Windows PowerShell destructive delete (later in the script)"),
    (r'\b(?:powershell|pwsh)(?:\.exe)?\b.*\s-(?:encodedcommand|enc|e)\b', "PowerShell encoded command execution"),
    # ── Windows destructive tier: native Windows EXEs/cmdlets reachable from ANY backend on a
    # Windows host (incl. git-bash). Input is lowercased by the variant loop, so patterns are
    # lowercase. Each requires the destructive flag/verb so benign usage (`taskkill /IM app.exe`,
    # `reg query`, `icacls file`) does NOT prompt. Bare Remove-Item form (ACP clients, pwsh-default
    # SSH hosts, or compound commands where `powershell` appeared earlier).
    # See #69472.
    # PowerShell accepts any unambiguous parameter prefix: `-r`/`-rec`/`-recurs` are -Recurse,
    # `-fo`/`-forc` are -Force (validated on Windows PowerShell 5.1, #144024).
    (r'\bremove-item\b[^\n;|&]*\s(?:' + _PS_RECURSE + r'|' + _PS_FORCE + r')', "PowerShell destructive delete (Remove-Item)"),
    # Remove-Item aliases after a pipe — `gci C:\data | ri -r -fo` runs the same recursive forced
    # delete from a positional script whose first command is not itself a delete verb, whether or
    # not a `powershell` prefix precedes it.
    (r'\|\s*' + _PS_DELETE_VERB + r'(?![\w-])[^\n;|&]*\s(?:' + _PS_RECURSE + r'|' + _PS_FORCE + r')', "PowerShell destructive delete (alias after pipe)"),
    # Bare cmd builtins with /s (recurse) or /q (quiet); plain `del file.txt` is covered only by the prefixed rule.
    (r'\b(?:del|erase|rd|rmdir)\s+(?:/[a-z]\s+)*/[sq]\b', "Windows destructive delete (recursive/quiet switch)"),
    # Remote content piped to Invoke-Expression — PowerShell's `curl | sh`.
    (r'\b(?:iwr|invoke-webrequest|invoke-restmethod|irm|curl|wget)\b[^\n]*\|\s*(?:iex|invoke-expression)\b', "pipe remote content to PowerShell (iwr | iex)"),
    (r'\b(?:iex|invoke-expression)\s*\(\s*(?:iwr|invoke-webrequest|invoke-restmethod|irm)\b', "execute remote content via Invoke-Expression"),
    # Force process kills — Windows analogue of pkill -9.
    (r'\btaskkill\b[^\n]*\s/f\b', "force kill processes (taskkill /F)"),
    (r'\bstop-process\b[^\n]*\s' + _PS_FORCE_ONLY_F, "force kill processes (Stop-Process -Force)"),
    # Volume/disk destruction — Windows analogue of mkfs / dd.
    (r'\bformat-volume\b', "format filesystem (Format-Volume)"),
    (r'\bclear-disk\b', "wipe disk (Clear-Disk)"),
    (r'\bdiskpart\b', "disk partitioning (diskpart)"),
    (r'\bformat(?:\.com)?\s+[a-z]:', "format drive (format.com)"),
    (r'\bcipher\s+/w\b', "wipe free space (cipher /w)"),
    # ACL destruction — Windows analogue of chmod 777.
    (r'\bicacls\b[^\n]*\s/grant\b[^\n]*\b(?:everyone|todos|jeder|tout\s+le\s+monde|\*s-1-1-0)\b', "grant Everyone access (icacls)"),
    (r'\bicacls\b[^\n]*\s/reset\b', "reset ACLs recursively (icacls /reset)"),
    # Backup/recovery destruction — classic ransomware prep.
    (r'\bvssadmin\b[^\n]*\bdelete\s+shadows\b', "delete volume shadow copies (vssadmin)"),
    # WMIC twin of the vssadmin rule — same shadow-copy destruction, older spelling. Not compiled:
    # DANGEROUS_PATTERNS_COMPILED swaps in WmicShadowDeleteMatcher (tools/approval_wmic.py), which checks each
    # command-position word (wrappers, full paths, cmd /c, pwsh) instead of an unanchored regex over the whole line.
    (r'wmic shadowcopy delete', _WMIC_SHADOW_DELETE_DESCRIPTION),
    (r'\bwbadmin\b[^\n]*\bdelete\b', "delete backups (wbadmin)"),
    (r'\bbcdedit\b[^\n]*\s/set\b', "modify boot configuration (bcdedit /set)"),
    # Registry deletion with force flag.
    (r'\breg(?:\.exe)?\s+delete\b', "registry delete (reg delete)"),
    (r'\bremove-itemproperty\b[^\n]*\s' + _PS_FORCE, "registry value delete (Remove-ItemProperty -Force)"),
    # Registry writes persist past the session (Run keys, HKCU\Environment, policies), so they prompt
    # like the deletes above; the read verbs (`reg query`/`export`, Get-ItemProperty) stay quiet.
    # `\s+` after setx keeps a shell assignment (`setx=1`) out.
    (r'\breg(?:\.exe)?\s+(?:add|import|copy|restore|load|unload)\b', "registry write (reg add/import/copy/restore/load/unload)"),
    (r'\bregedit(?:\.exe)?\s+[/-]s\b', "registry write (regedit /s silent .reg import)"),
    # The short aliases are common words, so they only count when aimed at a registry provider path,
    # which may sit after any other parameter (`-Force`, `-Name`, `-LiteralPath`, `-Path:`) within the
    # same segment. The scan stops at the next verb token so a run of `si si si ...` stays linear.
    (r'(?<![\w.])' + _REG_WRITE_VERB + r'\s(?:(?!(?<![\w.])' + _REG_WRITE_VERB + r'\s)[^\n;|&])*?(?:hk(?:cu|lm|cr|u|cc):|registry::)', "registry write (sp/ni/Set-Item/New-Item on a registry path)"),
    (r'\bsetx(?:\.exe)?\s+[^\s;&|]', "registry write (setx persistent environment variable)"),
    (r'\b(?:set|new)-itemproperty\b', "registry value write (Set-ItemProperty / New-ItemProperty)"),
    # Windows service/system stop — analogue of systemctl stop.
    (r'\bstop-service\b[^\n]*\s' + _PS_FORCE_ONLY_F, "force stop service (Stop-Service -Force)"),
    (r'\bsc(?:\.exe)?\s+(?:stop|delete)\b', "stop/delete service (sc)"),
    # Windows-form credential paths; the POSIX ~/.ssh patterns never match drive-letter or backslash spellings.
    (r'\busers[\\/][^\\/\s]+[\\/]\.ssh\b', "access to SSH keys (Windows path)"),
    (r'\bappdata[\\/](?:local|roaming)[\\/]hermes[^\n]*\.env\b', "access to Hermes secrets (Windows path)"),
    # ── end of Windows tier
    (r'\bchmod\s+(-[^\s]*\s+)*(777|666|o\+[rwx]*w|a\+[rwx]*w)\b', "world/other-writable permissions"),
    (r'\bchmod\s+--recursive\b.*(777|666|o\+[rwx]*w|a\+[rwx]*w)', "recursive world/other-writable (long flag)"),
    (r'\bchown\s+(-[^\s]*)?R\s+root', "recursive chown to root"),
    (r'\bchown\s+--recur[a-z]*\b.*root', "recursive chown to root (long flag)"),
    # _CMDPOS-anchored like the hardline twins: quoted prose mentioning mkfs/dd must not require approval to echo.
    # See #93392.
    (_CMDPOS + r'mkfs\b', "format filesystem"),
    (_CMDPOS + r'dd\s+.*if=', "disk copy"),
    (r'>\s*/dev/sd', "write to block device"),
    (r'\bDROP\s+(TABLE|DATABASE)\b', "SQL DROP"),
    # Only a WHERE in the DELETE's own statement text clears it: the lookahead stops at a newline
    # (under DOTALL a WHERE on the *next* line would otherwise count), a statement or shell
    # separator (; & |), a redirection (< >), a comment start (-- /* #), and any quote or dollar-quote
    # opener, so a WHERE inside a comment, literal, identifier, later statement, redirect target or
    # later shell command cannot.
    # Bare $VAR / ${VAR} stay transparent so templated table names still clear. Tag chars mirror
    # PostgreSQL's scan.l dolq_cont ([A-Za-z\200-\377_0-9]): any non-ASCII char, so $é$ opens a quote.
    (r'\bDELETE\s+FROM\b(?!(?:(?!--|/\*)(?:[^\n;&|#<>\'"`$]|\$(?![A-Za-z_0-9\x80-\U0010ffff]*\$)))*\bWHERE\b)',
     "SQL DELETE without WHERE"),
    (r'\bTRUNCATE\s+(TABLE)?\s*\w', "SQL TRUNCATE"),
    (rf'>\s*{_SYSTEM_CONFIG_PATH}', "overwrite system config"),
    (r'\bsystemctl\s+(-[^\s]+\s+)*(stop|restart|disable|mask)\b', "stop/restart system service"),
    (r'\bkill\s+-9\s+-1\b', "kill all processes"),
    (r'\bpkill\s+-9\b', "force kill processes"),
    # killall with SIGKILL (-9 / -KILL / -s KILL / -SIGKILL) and `killall -r <regex>` broad sweeps
    # that can wipe unrelated processes.
    (r'\bkillall\s+(-[^\s]*\s+)*-(9|KILL|SIGKILL)\b', "force kill processes (killall -KILL)"),
    (r'\bkillall\s+(-[^\s]*\s+)*-s\s+(KILL|SIGKILL|9)\b', "force kill processes (killall -s KILL)"),
    (r'\bkillall\s+(-[^\s]*\s+)*-r\b', "kill processes by regex (killall -r)"),
    (r':\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:', "fork bomb"),
    # Shell -c is parsed structurally by _execution_flag_findings(); a regex searching a dash-token
    # for "c" also matched --norc/--rcfile/--restricted.
    # Not compiled: DANGEROUS_PATTERNS_COMPILED swaps in _PipeRemoteToShellMatcher for this description;
    # the string only feeds the legacy approval-key alias below, so editing it changes no verdict.
    (rf'\b(curl|wget)\b.*(?:\|&?\s*{_PIPE_WRAPPERS_RE}|>\(\s*){_PIPE_SHELL_TOKEN_RE}', "pipe remote content to shell"),
    (rf'(?<![\w.-])(?:{_SHELL_NAMES_RE})\s+<\s*<?\s*\(\s*(curl|wget)\b', "execute remote script via process substitution"),
    (_CMDPOS + r'(?:source|\.)\s+<\s*\(\s*(curl|wget)\b', "execute remote script via process substitution"),
    # eval/source/. $(curl ...) — equivalent to piping remote content to a shell.
    (r'(?:\beval\b|\bsource\b|\.)\s*["\']?(?:\$\(\s*|`\s*)(?:curl|wget)\b', "execute remote content via command substitution"),
    # Not compiled: DANGEROUS_PATTERNS_COMPILED swaps in DownloadThenRunMatcher (linear two-step
    # match, tools/approval_fetch_exec.py); the string only feeds the legacy approval-key alias.
    (r'\b(?:curl|wget)\b.*(?:\s-[a-z]*o|--output|>).*(?:;|&&|\|\||\n)',
     _DOWNLOAD_THEN_RUN_DESCRIPTION),
    # Reverse shells (parity with Skills Guard's network rows). Not compiled: DANGEROUS_PATTERNS_COMPILED swaps in
    # _DevSocketRedirectMatcher, which dequotes the redirect operand; nc/socat are command-position anchored; a glued `<`/`>` redirect still ends the command word.
    (r'[<>]&?\s*/dev/(?:tcp|udp)/', _DEV_TCP_REDIRECT_DESCRIPTION),
    # The flag may be quoted (`nc "-e" sh h 1` still passes -e); a whitespace-led `#` starts a shell comment, so
    # the span stops there and `nc -z h 80 # -e note` stays quiet. The flag is case-sensitive (`-C` is CRLF).
    # An `&` stays in the span only inside a redirect (`2>&1`, `<&0`, `&>x`); a background `&` ends it.
    (_CMDPOS + r'(?:\S*/)?(?:nc|ncat|netcat)(?:\.\w+)?(?=[\s<>]|&>)(?:[^\n;&|#]|(?<!\s)#|(?<=[<>])&|(?<![<>])&(?=>))*\s["\']?(?:(?-i:-[a-zA-Z]*[ec])\b|--(?:sh-)?exec\b)',
     "reverse shell via netcat -e/-c"),
    (_CMDPOS + r'(?:\S*/)?socat(?:\.\w+)?(?=[\s<>]|&>)(?:[^\n;&|#]|(?<!\s)#|(?<=[<>])&|(?<![<>])&(?=>))*\b(?:exec|system):', "reverse shell via socat EXEC:/SYSTEM:"),
    # Cloud instance-metadata (IMDS) credential endpoints — deterministic containment-escape
    # detection. On a cloud VM these serve live IAM/service-account credentials to ANY local
    # process with no auth, so a fetch is credential exfiltration unless the operator expects it.
    # The host literals have no other use, so their appearance ANYWHERE in the command (any HTTP
    # client, env assignment, or script argument) is the signal; lookarounds keep other 169.254.x.x
    # link-local addresses and longer dotted strings out. This prompts for approval (legit uses
    # exist on real cloud VMs) — it is NOT a hardline block. Covers the link-local IPv4 endpoint
    # (AWS/Azure/GCP/OpenStack), its AWS IPv6 form fd00:ec2::254, the GCP hostname, and Alibaba
    # Cloud's 100.100.100.200.
    (r'(?<![\d.])(?:169\.254\.169\.254|100\.100\.100\.200)(?![\d.])'
     r'|(?<![\w.-])metadata\.google\.internal(?![\w.-])'
     r'|fd00:ec2::254',
     "cloud metadata endpoint access (instance credentials)"),
    # Decode-and-execute: `echo <base64> | base64 -d | bash` carries no dangerous keywords in the
    # raw text yet runs arbitrary commands.
    (rf'\b(base64|base32|base16)\s+(?:-[dD]|--decode)\b.*\|\s*\b(?:{_SHELL_NAMES_RE})\b', "pipe decoded content to shell (possible command obfuscation)"),
    # xxd uses -r for decode, not -d.
    (rf'\bxxd\s+-r\b.*\|\s*\b(?:{_SHELL_NAMES_RE})\b', "pipe xxd-decoded content to shell (possible command obfuscation)"),
    # `echo 'eq -pe v/' | tr 'eqv' 'rmf' | bash` decodes to `rm -rf /`.
    (rf'\becho\b[^|]*\|\s*\btr\b[^|]*\|\s*\b(?:{_SHELL_NAMES_RE})\b', "pipe tr-transformed output to shell (possible command obfuscation)"),
    (rf'\bopenssl\b.*\b(?:base64|enc)\b[^|]*\s+-[dD]\b[^|]*\|\s*\b(?:{_SHELL_NAMES_RE})\b',
     "pipe openssl-decoded content to shell (possible command obfuscation)"),
    # Credential exfiltration: a curl/wget request BODY (not a header — `-H "Authorization: Bearer $KEY"` is
    # ordinary API use) carrying a secret-named variable or a credential file, or a credential file piped into
    # an uploading curl/wget. Flag letters are case-sensitive (-d/-F/-T upload; -D/-f/-t do not).
    (rf'{_UPLOAD_FLAG}(?:[\s=]+|(?=[@"\'$]))(?:"[^"]*(?:{_SECRET_VAR}|{_SECRET_FILE})|\'[^\']*{_SECRET_FILE}'
     rf'|\$\([^)]*{_SECRET_FILE}|\S*?(?:{_SECRET_VAR}|{_SECRET_FILE}))',
     _CREDENTIAL_UPLOAD_DESCRIPTION),
    (rf'{_SECRET_FILE}[^|;&\n]*\|[^;&|\n]*\b(?:curl|wget)\b[^;&|\n]*{_UPLOAD_FLAG}',
     "pipe a credential file into a curl/wget upload (possible exfiltration)"),
    # Invisible / bidirectional Unicode controls make the command the user approves differ from what runs.
    # ZWJ between emoji (family/flag sequences) is ordinary text; variation selectors are checked on the
    # raw command in detect_dangerous_command.
    (rf'[\u200b\u200c\u200e\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff\u180e\U000e0000-\U000e007f]'
     rf'|(?<![{_EMOJI_RANGE}\ufe0f])\u200d|\u200d(?![{_EMOJI_RANGE}])',
     _INVISIBLE_UNICODE_DESCRIPTION),
    (rf'\btee\b.*["\']?{_SENSITIVE_WRITE_TARGET}', "overwrite system file via tee"),
    (rf'>>?\s*["\']?{_SENSITIVE_WRITE_TARGET}', "overwrite system file via redirection"),
    (rf'\btee\b.*["\']?{_PROJECT_SENSITIVE_WRITE_TARGET}["\']?{_WRITE_TARGET_BOUNDARY}', "overwrite project env/config via tee"),
    (rf'>>?\s*["\']?{_PROJECT_SENSITIVE_WRITE_TARGET}["\']?{_WRITE_TARGET_BOUNDARY}', "overwrite project env/config via redirection"),
    (r'\bxargs\s+.*\brm\b', "xargs with rm"),
    # -execdir has the same semantics as -exec (runs in each match's directory).
    (r'\bfind\b.*-exec(?:dir)?\s+(/\S*/)?rm\b', "find -exec/-execdir rm"),
    # Unquoted brace/glob spellings the shell can expand into the flags above at run time
    # (`find . -{delete,print}`, `find . -del*`). Additive: catches these spellings only; approval is
    # still decided from source text, so `$var`/`$(...)`-built words are not covered here. `find` must
    # be the command word and the dynamic word a whitespace-delimited token; both rules are matched
    # against the quote-masked variant (_QUOTE_MASKED_DANGEROUS_DESCRIPTIONS) because a quoted glob
    # (`find . -name 'log-del*'`) is a literal predicate argument the shell never expands.
    (_CMDPOS + r'find\s[^;|&\n]*(?<!\S)-(?:\{[^}\s]*(?:delete|exec(?:dir)?)[^}\s]*\}|(?:del(?:ete?)?|exec(?:dir)?)[*?\[])',
     "find dynamic shell word may expand to destructive flag"),
    (r'\bfind\b.*-delete\b', "find -delete"),
    # Same for program-bearing read-tool options, which _execution_flag_findings() parses structurally
    # only when the option is spelled literally.
    (r'\b(?:rg|sort|ag|man)\b[^;|&\n]*(?<!\S)--(?:pre|hostname-bin|compress-program|pager|html)(?:\{|[*?\[])',
     "dynamic shell word may expand to arbitrary program execution flag"),
    # Gateway lifecycle: stopping/restarting the gateway kills all running agents. Global flags
    # between `hermes` and `gateway` (`hermes -p ade gateway restart`) are allowed so a profile flag can't slip past.
    (r'\bhermes\s+' + _GLOBAL_FLAGS + r'gateway\s+(stop|restart)\b', "stop/restart hermes gateway (kills running agents)"),
    (r'\bhermes\s+update\b', "hermes update (restarts gateway, kills running agents)"),
    # Docker/Podman daemon redirect — global flags or env that point the CLI at a DIFFERENT (often remote) daemon:
    # `docker -H ssh://prod stop app` looks local but operates on remote infra, so any redirect requires approval
    # regardless of subcommand. The flag must be in global position (before the subcommand) and -H/--host/--context
    # must carry a value, keeping `docker -h` and `docker run -h <hostname>` out. Listed BEFORE the lifecycle rules so
    # a redirected lifecycle command surfaces the more specific reason.
    (r'\bdocker\s+' + _GLOBAL_FLAGS + r'(?:-h|--host)[=\s]+\S+', "docker with remote daemon redirect (-H/--host)"),
    (r'\bdocker\s+' + _GLOBAL_FLAGS + r'(?:-c|--context)[=\s]+\S+', "docker with daemon redirect (--context: alternate daemon)"),
    (r'\bdocker\s+context\s+use\b', "docker context use (switches default daemon for future commands)"),
    (r'\bpodman\s+' + _GLOBAL_FLAGS + r'(?:--url|--connection|--identity)[=\s]+\S+', "podman with remote daemon redirect (--url/--connection/--identity)"),
    (r'\bpodman\s+' + _GLOBAL_FLAGS + r'(?:-r\b|--remote\b)', "podman remote mode (-r/--remote: remote daemon)"),
    (r'\b(?:docker_host|docker_context|container_host|container_connection)=\S+', "docker/podman daemon redirect via environment (DOCKER_HOST/CONTAINER_HOST)"),
    # Container lifecycle (docker.sock mounts let the agent stop/kill containers) always needs
    # consent. Global flags between docker/compose and the verb and the legacy `docker-compose`
    # binary are allowed so a flag can't slip past.
    (r'\bdocker(?:-compose|\s+compose)\s+' + _GLOBAL_FLAGS + r'(restart|stop|kill|down)\b', "docker compose restart/stop/kill/down (container lifecycle)"),
    (r'\bdocker\s+' + _GLOBAL_FLAGS + r'(?:container\s+)?(restart|stop|kill)\b', "docker restart/stop/kill (container lifecycle)"),
    # Removing a container or volume is strictly more destructive than stopping it, and the canonical
    # `container` spelling and the prunes (every stopped container, unused volume/image data) are the same
    # verbs (#132483). `docker image rm`/`rmi`/`network rm` stay ungated: a pull or a recreate restores them.
    # Descriptions must name a word `hermes approvals suggest` treats as destructive (`rm`, `delete`), or
    # it offers the class for the permanent allowlist.
    (r'\b(?:docker|podman)\s+' + _GLOBAL_FLAGS + r'(?:rm|container\s+(?:rm|remove))\b', "docker/podman rm (container destruction)"),
    (r'\bdocker(?:-compose|\s+compose)\s+' + _GLOBAL_FLAGS + r'rm\b', "docker compose rm (container destruction)"),
    (r'\b(?:docker|podman)\s+' + _GLOBAL_FLAGS + r'volume\s+(?:rm|remove|prune)\b', "docker/podman volume rm/prune (volume data destruction)"),
    (r'\b(?:docker|podman)\s+' + _GLOBAL_FLAGS + r'(?:container\s+prune|system\s+(?:prune|reset))\b', "docker/podman container/system prune, podman system reset (deletes stopped containers and unused data)"),
    # Gateway protection: never start gateway outside systemd management
    (r'gateway\s+run\b.*(&\s*$|&\s*;|\bdisown\b|\bsetsid\b)', "start gateway outside systemd (use 'systemctl --user restart hermes-gateway')"),
    (r'\bnohup\b.*gateway\s+run\b', "start gateway outside systemd (use 'systemctl --user restart hermes-gateway')"),
    # Self-termination protection: prevent agent from killing its own process
    (r'\b(pkill|killall)\b.*\b(hermes|gateway|cli\.py)\b', "kill hermes/gateway process (self-termination)"),
    # Self-termination via kill + $(pgrep/pidof): the substitution is opaque to the name-based
    # pattern above, so catch the structural form.
    (r'\bkill\b.*\$\(\s*(pgrep|pidof)\b', "kill process via pgrep/pidof expansion (self-termination)"),
    (r'\bkill\b.*`\s*(pgrep|pidof)\b', "kill process via backtick pgrep/pidof expansion (self-termination)"),
    # launchctl-driven gateway stop/restart on macOS (label `ai.hermes.gateway`). Two independent lookaheads, NOT a
    # sequential match: a for-loop building the label from a list defined EARLIER (`for item in 'ai.hermes...'; do
    # launchctl bootout "$label"`) never has "hermes" after the verb, and that slipped past and restarted 4 gateways
    # with zero approval. Erring broad is correct for an approval gate: an extra prompt is cheap.
    # Anchor whole-input lookaheads: re.search otherwise rescans every suffix of
    # long non-matching commands, holding the GIL and starving Gateway threads.
    (r'\A(?=[\s\S]*\blaunchctl\s+(?:stop|kickstart|bootout|unload|kill|disable|remove)\b)(?=[\s\S]*\b(?:hermes|ai\.hermes)\b)', "stop/restart hermes launchd service (kills running agents)"),
    (rf'\b(cp|mv|install)\b.*\s{_SYSTEM_CONFIG_PATH}', "copy/move file into system config path"),
    (rf'\b(cp|mv|install)\b.*\s["\']?{_PROJECT_SENSITIVE_WRITE_TARGET}["\']?{_COMMAND_TAIL}', "overwrite project env/config file"),
    # cp/mv/install OVERWRITING a credential/SSH/shell-rc/Hermes file (key implant, login-time
    # injection) — pairs the tee/redirection coverage. Anchored to the command tail so only the
    # DESTINATION fires; reading OUT of a sensitive path (`cp ~/.ssh/config /tmp/x`) stays safe.
    # The trailing `[^\s"\']*` consumes the rest of the destination filename.
    # The tee/redirection patterns above already gate _SENSITIVE_WRITE_TARGET (~/.ssh/*,
    # ~/.netrc/.pgpass/.npmrc/.pypirc, shell rc files, ~/.hermes/config.yaml/.env), but cp/mv/install was
    # only paired for /etc and project-relative env/config — so `cp evil ~/.ssh/authorized_keys` (key
    # implant), `cp creds ~/.netrc`, and `cp evil ~/.bashrc` (login-time command injection) slipped through
    # with auto-approve. Same unpaired-door rationale as #14639 / the sed-tee-redirect pairing on these
    # targets. `authorized_keys` after the `~/.ssh/` fragment).
    (rf'\b(cp|mv|install)\b.*\s["\']?{_SENSITIVE_WRITE_TARGET}[^\s"\']*["\']?{_COMMAND_TAIL}', "copy/move file into sensitive credential/SSH/shell-rc path"),
    # touch/mkdir create, and ln plants a pointer at, the same destinations without a gated write verb
    # (`mkdir -p ~/.ssh && touch ~/.ssh/x`, `ln -sf evil ~/.bashrc`), pairing the write_file deny (#85321).
    # Command-position anchored so `ls -ln ~/.ssh` / `grep touch ~/.bashrc` stay out; any touch/mkdir operand
    # counts, but for ln only the destination (last operand) does, so linking OUT of these paths stays safe.
    # `touch -r REF` / `--reference REF` only reads REF (its timestamps), so that operand is not a create target.
    (rf'{_CMDPOS}(?:touch|mkdir)\s(?:[^\n;&|]*\s)?(?:(?<!\s-r\s)(?<!\s--reference\s)|(?<=\s--\s-r\s)|(?<=\s--\s--reference\s))["\']?{_HOME_SENSITIVE_CREATE_TARGET}', "create a file in a sensitive credential/SSH/shell-rc path"),
    (rf'{_CMDPOS}ln\s[^\n;&|]*\s["\']?{_HOME_SENSITIVE_CREATE_TARGET}[^\s"\'<>;&|)`]*+["\']?(?:\s*+\d*+[<>]++&?\s*+[^\s<>;&|)`]*+)*+\s*+(?:[\n;&|)`]|$)', "link a file into a sensitive credential/SSH/shell-rc path"),
    # Hermes home / session-store floor (#109367): delete, wipe, move, or overwrite of the home or a
    # protected store. cp/install/rsync only as the destination, so `cp ~/.hermes/state.db /tmp/bak` stays clean.
    (_CMDPOS + rf'(?:rm|unlink|shred|truncate)\b[^;|&\n]*\s["\']?{_HERMES_STORE_PATH}', "delete/move/wipe Hermes home or session store"),
    # mv: a store at any operand (moved away or overwritten), the bare home only as a SOURCE, so
    # moving something INTO the home (`mv /tmp/skill ~/.hermes/`) stays clean.
    (_CMDPOS + rf'mv\b[^;|&\n]*\s["\']?(?:{_HERMES_STORE_FILE}|{_HERMES_HOME_BARE}(?=\s+[^\s;|&<>]))',
     "delete/move/wipe Hermes home or session store"),
    (_CMDPOS + rf'(?:cp|install|rsync)\b[^;|&\n]*\s["\']?{_HERMES_STORE_ROOT}(?=\s*(?:$|[;&|#<>\n]|\d+[<>]))', "overwrite Hermes session/credential store"),
    (_CMDPOS + rf'dd\b[^;|&\n]*\bof=["\']?{_HERMES_STORE_ROOT}', "overwrite Hermes session/credential store"),
    (_CMDPOS + rf'tee\b[^;|&\n]*\s["\']?{_HERMES_STORE_ROOT}', "overwrite Hermes session/credential store"),
    (rf'>[>|]?\s*["\']?{_HERMES_STORE_ROOT}', "overwrite Hermes session/credential store"),
    # sqlite3 writing a Hermes store is keyed on the write verb, not on a missing WHERE (`where 1=1`
    # deletes the same rows), and any heredoc into a store prompts (its SQL sits past the newline).
    (_CMDPOS + rf'sqlite3\b(?=[^\n]*{_HERMES_STORE_FILE})(?=[^\n]*(?:\b(?:delete\s+from|drop\s+\w+'
     r'|update\s+(?:or\s+\w+\s+)?\S+\s+(?:as\s+\S+\s+)?set|insert\s+(?:or\s+\w+\s+)?into|replace\s+into'
     r'|alter\s+table|vacuum(?!\s+(?:\w+\s+)?into))\b|\.restore\b|(?<!<)<<(?!<)))',
     "modify Hermes session store via sqlite3"),
    # In-place edits mutate the file directly, bypassing redirection/tee/cp coverage; gate the same
    # startup/credential files.
    (rf'\bsed\s+-[^\s]*i.*(?:{_USER_SENSITIVE_WRITE_TARGET})[^\s"\']*', "in-place edit of sensitive credential/SSH/shell-rc path"),
    (rf'\bsed\s+--in-place\b.*(?:{_USER_SENSITIVE_WRITE_TARGET})[^\s"\']*', "in-place edit of sensitive credential/SSH/shell-rc path (long flag)"),
    (rf'\b(?:perl|ruby)\b.*(?:^|\s)-[^\s]*i\b.*(?:{_USER_SENSITIVE_WRITE_TARGET})[^\s"\']*', "in-place edit of sensitive credential/SSH/shell-rc path (perl/ruby)"),
    (rf'\bsed\s+-[^\s]*i.*\s{_SYSTEM_CONFIG_PATH}', "in-place edit of system config"),
    (rf'\bsed\s+--in-place\b.*\s{_SYSTEM_CONFIG_PATH}', "in-place edit of system config (long flag)"),
    # sed -i on Hermes config/.env bypasses the redirection/tee rules; pairs the file_tools
    # write_file/patch deny so the terminal side is not an open door.
    # In-place edit of a Hermes-managed security file (~/.hermes/config.yaml or .env). sed -i bypasses the
    # redirection/tee patterns above because it mutates the file directly. See #14639.
    (rf'\bsed\s+-[^\s]*i.*(?:{_HERMES_CONFIG_PATH}|{_HERMES_ENV_PATH})', "in-place edit of Hermes config/env"),
    (rf'\bsed\s+--in-place\b.*(?:{_HERMES_CONFIG_PATH}|{_HERMES_ENV_PATH})', "in-place edit of Hermes config/env (long flag)"),
    # perl/ruby -i: the flag may be its own token after other flags (`-p -i -e`), combined (`-pi`), or carry a backup
    # suffix (`-i.bak`), so match any flag token containing `i` anywhere; `perl -e '...'` (no -i) does not trip.
    # perl -i and ruby -i perform the same in-place mutation as sed -i but are not caught by the -e/-c
    # script-execution pattern above (which targets code evaluation, not file mutation). Pairs the sed -i
    # coverage from #14639.
    (rf'\b(?:perl|ruby)\b.*(?:^|\s)-[^\s]*i\b.*(?:{_HERMES_CONFIG_PATH}|{_HERMES_ENV_PATH})', "in-place edit of Hermes config/env (perl/ruby)"),
    # Interpreter heredocs are handled by _execution_flag_findings(); only shell heredocs stay
    # regex-based. `bash <<'EOF'` runs arbitrary commands without triggering the `bash -c` path.
    (rf'\b(?:{_SHELL_NAMES_RE})\s+<<', "shell execution via heredoc"),
    # Git destructive operations. `git reset --hard` accepts any unambiguous long-flag prefix (--h,
    # --ha, --har): --hard is the only reset mode starting with "h", and `--help` is special-cased
    # by git before mode resolution.
    (rf'{_GIT}reset\s+--h(?:a(?:r(?:d)?)?)?\b', "git reset --hard (destroys uncommitted changes)"),
    # Git force push. The flag search is bounded to the PUSH's own command segment, so a LATER
    # command's `-f` (grep -f, pkill -f) no longer trips the force-push prompt on a plain push.
    # The short form takes git's combined spelling (`-qf`), and the `+refspec` force spelling is a
    # rule of its own; both were force pushes the old single-token `-f` pattern missed. Quotes are
    # NOT a boundary here: the shell strips them before git sees the command, so `git push
    # "--force"` is still a force push.
    (rf'{_GIT_PUSH}{_GIT_PUSH_ARGS}{_GIT_PUSH_ARG_START}--forc[a-z]*\b', "git force push (rewrites remote history)"),
    # `-o` takes the rest of a short-flag cluster as its value (`-ofoo` is push option "foo").
    (rf'{_GIT_PUSH}{_GIT_PUSH_ARGS}{_GIT_PUSH_ARG_START}-(?!-)[a-np-z]*f[a-z]*\b',
     "git force push short flag (rewrites remote history)"),
    # A push option's value (`-o +foo`) is not a refspec; the scan ends on a non-blank so the
    # whole blank run sits between the option and its value (`-o  +foo`).
    (rf'{_GIT_PUSH}{_GIT_PUSH_ARGS}(?<!\s)(?<!\s-o)(?<!\s--push-option)\s+["\']?\+[^\s;&|\n]+',
     "git force push (rewrites remote history)"),
    # `hermes config set` can rewrite the agent's own approval policy (approvals.mode, approvals.deny,
    # command_allowlist) — gate it like the file-tool path so a default empty deny list is not an open door.
    # Anchored to a real INVOCATION: the command must BE `hermes config set <policy key>`. The
    # `\bhermes\b.*\bconfig\b.*\bset\b` form matched that TEXT anywhere in the command, so a plain
    # read of it (`grep -r 'hermes config set' docs/approvals.md`) demanded an approval it has no
    # business demanding. The global-option run uses possessive quantifiers inside an atomic group,
    # so it cannot backtrack exponentially the way a plain nested `*` does.
    (_CMDPOS + _HERMES_CONFIG_SET_APPROVAL_POLICY,
     "hermes config set approval settings"),
    (rf'{_GIT}clean\s+-[^\s]*f', "git clean with force (deletes untracked files)"),
    # `-D` = `-d --force`: only the capital short flag is force-delete, so the group opts out of
    # the module-wide re.IGNORECASE and relies on _lower_preserving_flags keeping dash-prefixed
    # tokens' case in the detection input (every other pattern matches case-insensitively and is
    # unaffected). The safe merged-only -d / --delete stays ungated by design — git itself refuses
    # to delete a branch that is not fully merged.
    (rf'{_GIT}branch\s+(?-i:-D)\b', "git branch force delete"),
    # `-D` = `-d --force`; the long spellings are different tokens, so match delete+force in either order, bounded to
    # one command segment (no `;`/`|`/`&`/newline) so an unrelated later command isn't contaminated.
    (rf'{_GIT}branch\b[^;|&\n]*?(?:-d\b|--delete\b)[^;|&\n]*?(?:-f\b|--force\b)', "git branch force delete (long flags)"),
    (rf'{_GIT}branch\b[^;|&\n]*?(?:-f\b|--force\b)[^;|&\n]*?(?:-d\b|--delete\b)', "git branch force delete (long flags, force-first)"),
    # chmod +x then immediate run: the script content may hold dangerous commands individual patterns miss.
    (r'\bchmod\s+\+x\b.*[;&|]+\s*\./', "chmod +x followed by immediate execution"),
    # Sudo stdin/askpass/shell/list-privs flags. The agent has no TTY, so sudo invocations that succeed
    # non-interactively read the password from stdin (-S) or askpass (-A); -s (shell) and -a (list) are gated as
    # privilege chains (read SUDO_PASSWORD from .env -> sudo -S -s). Plain `sudo cmd` is TTY-bound and excluded. Input
    # is lowercased, so S/s and A/a collapse. Lazy `[^;|&\n]*?` allows flag args without spanning separators. sudo
    # resolves unambiguous long-flag prefixes: `--stdin` is the only long option starting with "st", `--askpass` the
    # only one starting with "a".
    (r'\bsudo\b[^;|&\n]*?\s+(?:-s\b|--st[a-z]*\b|-a\b|--a[a-z]*\b)', "sudo with privilege flag (stdin/askpass/shell/list)"),
    # Combined short-flag form (-nS, -sa, -las).
    (r'\bsudo\b[^;|&\n]*?\s+-[a-z]*[sa][a-z]*\b', "sudo with combined-flag privilege escalation"),
    # Package-manager uninstall commands can remove installed software outside
    # the current project (notably `npm uninstall -g`). Treat their destructive
    # subcommands like other state-removing operations while leaving installs
    # and updates alone.
    # _CMDPOS-anchored (quoted prose like `git commit -m "npm uninstall docs"` is data); the
    # option group also swallows one operand (`--prefix DIR`, `--proxy URL`, `--cwd DIR`).
    (_CMDPOS + r'npm\s+' + _PKG_OPTS + r'(?:uninstall|unlink|remove|rm|r|un)\b', "package manager uninstall"),
    (_CMDPOS + r'pnpm\s+' + _PKG_OPTS + r'(?:uninstall|remove|rm|un)\b', "package manager uninstall"),
    (_CMDPOS + r'yarn\s+' + _PKG_OPTS + r'(?:global\s+)?(?:uninstall|remove)\b', "package manager uninstall"),
    (_CMDPOS + r'pip(?:3)?\s+' + _PKG_OPTS + r'uninstall\b', "package manager uninstall"),
    (_CMDPOS + r'brew\s+' + _PKG_OPTS + r'(?:uninstall|remove|rm)\b', "package manager uninstall"),
]


_PIPE_REMOTE_TO_SHELL_DESCRIPTION = "pipe remote content to shell"
_CUSTOM_MATCHERS = {
    _PIPE_REMOTE_TO_SHELL_DESCRIPTION: _PipeRemoteToShellMatcher,
    _WMIC_SHADOW_DELETE_DESCRIPTION: WmicShadowDeleteMatcher,
    _DEV_TCP_REDIRECT_DESCRIPTION: _DevSocketRedirectMatcher,
    _DOWNLOAD_THEN_RUN_DESCRIPTION: lambda: DownloadThenRunMatcher(_SHELL_NAMES_RE),
}
DANGEROUS_PATTERNS_COMPILED = [
    (_CUSTOM_MATCHERS[d]() if d in _CUSTOM_MATCHERS else re.compile(p, _RE_FLAGS), d)
    for p, d in DANGEROUS_PATTERNS
]
# Dynamic-word rules look for glob/brace characters, which are ordinary data inside quotes
# (`find . -name 'log-del*'`), so they scan the quote-masked variant like the positionless hardline rules.
_QUOTE_MASKED_DANGEROUS_DESCRIPTIONS = frozenset({
    "find dynamic shell word may expand to destructive flag",
    "dynamic shell word may expand to arbitrary program execution flag", _DOWNLOAD_THEN_RUN_DESCRIPTION,
})
# A quoted `| ri -r` is prose (`Write-Host "run gci | ri -r"`), unless an unquoted launcher runs the
# quoted text as a script: `ssh host "gci | ri -r"`, `cmd /c "..."`, `iex "..."`, `echo "..." | pwsh -`.
_PS_PIPE_ALIAS_DESCRIPTION = "PowerShell destructive delete (alias after pipe)"
_PS_QUOTED_SCRIPT_LAUNCHERS = frozenset({
    "ssh", "iex", "invoke-expression", "invoke-command", "icm", "pwsh", "powershell", "wsl", "runas",
    "start-process", "start-job", "saps", "cmd", *_SHELL_CARRIER_NAMES,
})

# Content-level rules (ported from tirith in #133832, where they were separate findings with their own
# keys). They describe WHAT the command carries rather than which verb runs it, so a command that also
# matches one of them needs consent for it even when its first, verb-level rule is already approved.
_CONTENT_RULE_DESCRIPTIONS = frozenset({
    "upload a secret or credential file via curl/wget (possible exfiltration)",
    "pipe a credential file into a curl/wget upload (possible exfiltration)",
    "invisible or bidirectional Unicode control character (possible obfuscation)",
})

# Descriptions whose blast radius is the OPERATOR's own work rather than anything the session
# owns, so an auxiliary-LLM APPROVE is not consent for them: smart mode asks the human instead of
# consulting the guardian, and the answer covers that one command (no session/always grant).
# Keep this list to actions that destroy state the agent did not create and cannot recreate.
SMART_MANUAL_ONLY_DESCRIPTIONS = frozenset({OSASCRIPT_RISKY_DESCRIPTION, OSASCRIPT_OPAQUE_DESCRIPTION})

# Preserve approvals stored under the removed interpreter regex rules.
_REMOVED_PATTERN_KEY_ALIASES = {
    "script execution via -e/-c flag": "(python[23]?|perl|ruby|node)\\s+-[ec]\\s+",
    "script execution via heredoc": "(python[23]?|perl|ruby|node)\\s+<<",
}
# description <-> legacy regex-derived key (the old approval key, kept for backwards compatibility
# with stored allowlist/session entries), both ways.
_PATTERN_KEY_ALIASES: dict[str, set[str]] = {}
for _canonical_key, _legacy_key in [
    (d, p.split(r'\b')[1] if r'\b' in p else p[:20]) for p, d in ((p.replace(_GIT, r'\bgit\s+'), d) for p, d in DANGEROUS_PATTERNS)
] + list(_REMOVED_PATTERN_KEY_ALIASES.items()):
    _PATTERN_KEY_ALIASES.setdefault(_canonical_key, set()).update({_canonical_key, _legacy_key})
    _PATTERN_KEY_ALIASES.setdefault(_legacy_key, set()).update({_legacy_key, _canonical_key})

# Regex edits change a pattern's regex-derived legacy key; keep each pre-change spelling resolvable so
# approvals stored under it still match: (?-i:-D) scoping, the optional drive letter (#38964), and
# `git reset --hard` accepting abbreviated `--h`/`--ha`/`--har`.
for _canonical_key, _old_key in [
    ("git branch force delete", r"git\s+branch\s+-D"),
    ("delete in root path", r"rm\s+(-[^\s]*\s+)*/"),
    ("git reset --hard (destroys uncommitted changes)", r"git\s+reset\s+--hard"),
]:
    _PATTERN_KEY_ALIASES.setdefault(_canonical_key, set()).add(_old_key)
    _PATTERN_KEY_ALIASES.setdefault(_old_key, set()).add(_canonical_key)


def _approval_key_aliases(pattern_key: str) -> set[str]:
    """All approval keys for this pattern: the description plus the historical regex-derived key
    older allowlist/session entries may still use."""
    return _PATTERN_KEY_ALIASES.get(pattern_key, {pattern_key})


# ---- Detection ----------------------------------------------------------------------------
def _normalize_command_for_detection(command: str) -> str:
    """Normalize a command before pattern matching so ANSI escapes, null bytes, Unicode fullwidth
    forms, and shell splicing tricks cannot bypass detection."""
    from tools.ansi_strip import strip_ansi
    # Decode $'...' first: the escape strip below would turn $'\x72\x6d' into $'x72x6d', and the
    # home fold must see the decoded absolute path.
    command = expand_ansi_c_quotes(command)
    command = unicodedata.normalize('NFKC', strip_ansi(command).replace('\x00', ''))
    # Collapse backslash-newline continuations (`rm -rf \<newline>/` runs as `rm -rf /`). MUST
    # precede the generic escape strip below, whose [^\n] class skips newlines and would leave the
    # backslash wedged between tokens, defeating the structured rm/mkfs/dd patterns incl. the HARDLINE floor.
    command = re.sub(r'\\\r?\n', '', command)
    # Fold absolute user/Hermes home prefixes to ~/ and ~/.hermes/ so the static patterns catch /home/alice/.bashrc
    # and C:\Users\alice\.bashrc. Resolved at detection time (not import time) so it tracks HOME/HERMES_HOME set
    # later. MUST run before the backslash strip (which would dissolve C:\Users\alice to C:Usersalice). Hermes home
    # first: on Windows it nests under the user home, and folding the user home first would eat the prefix it needs.
    command = _rewrite_resolved_hermes_home(command)
    command = _rewrite_resolved_user_home(command)
    # Strip backslash-escapes (r\m -> rm) and empty-string literals (r''m -> rm).
    command = re.sub(r'\\([^\n])', r'\1', command)
    command = re.sub(r"''|\"\"", '', command)
    # Collapse $IFS / ${IFS...} (incl. `${IFS:0:1}`) to a space: IFS defaults to whitespace, so `rm${IFS}-rf${IFS}/`
    # runs as `rm -rf /`, and every pattern — incl. the hardline floor — anchors on literal \s between tokens.
    return re.sub(r'\$\{IFS\b[^}]*\}|\$IFS\b', ' ', command)


def _lower_preserving_flags(command: str) -> str:
    """Lowercase a detection variant for the pattern pass while keeping dash-prefixed tokens
    byte-for-byte, so case-dependent flags keep their distinction. All dangerous patterns are
    compiled case-insensitively, so preserved flag case is invisible to them except where a
    pattern explicitly scopes a case-sensitive group. Non-flag tokens (command words, quoted
    prose, paths) are lowercased exactly as before; separators and whitespace are untouched."""
    return ''.join(t if t.startswith('-') else t.lower() for t in re.split(r'(\s+)', command))


_PARAM_REPLACEMENT_RE = re.compile(r"\$\{[^}/\s]+/[^}/]*/(?P<replacement>[^}]*)\}")
_PARAM_DEFAULT_RE = re.compile(r"\$\{[^}:}\s]+:-(?P<default>[^}]*)\}")
_SIMPLE_SHELL_LITERAL_RE = re.compile(r"^[A-Za-z0-9_./:@%+=,-]+$")
_ENV_ASSIGNMENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=.*")
_COMMAND_WRAPPER_WORDS = {"sudo", "env", "exec", "nohup", "setsid", "time", "command", "builtin",
                          "nice", "timeout", "stdbuf", "ionice", "chrt", "taskset", "chroot"}
_SUDO_OPTIONS_WITH_ARG = {"-c", "--close-from", "-g", "--group", "-h", "--host", "-p", "--prompt", "-u", "--user"}
# Adapted from embwl0x's command-position work in #76063. Option operands are
# data, not executable positions; option spelling remains case-sensitive.
_COMMAND_WRAPPER_OPTIONS_WITH_ARG = {
    "chroot": {"--groups", "--userspec"},
    "sudo": _SUDO_OPTIONS_WITH_ARG,
    "env": {"-a", "--argv0", "-C", "--chdir", "-S", "--split-string", "-u", "--unset"},
    "exec": {"-a"}, "nice": {"-n", "--adjustment"},
    "time": {"-f", "--format", "-o", "--output"},
    "timeout": {"-k", "--kill-after", "-s", "--signal"},
    "stdbuf": {"-e", "--error", "-i", "--input", "-o", "--output"},
    "ionice": {"-c", "--class", "-n", "--classdata"},
}
_COMMAND_WRAPPER_NON_EXECUTING_OPTIONS = {
    "command": {"-v", "-V"}, "chrt": {"-p", "--pid"},
    "ionice": {"-p", "--pid", "--pgid", "--uid"}, "taskset": {"-p", "--pid"},
    # sudo's list / validate / remove-timestamp modes take no command (`sudo -k cmd` does run it).
    "sudo": {"-l", "--list", "-v", "--validate", "-K", "--remove-timestamp"},
}

_COMMAND_WRAPPER_POSITIONAL_ARGS = {"chroot": 1, "chrt": 1, "taskset": 1, "timeout": 1}
_SHELL_COMMAND_TRANSITIONS = {"if", "then", "else", "elif", "do", "while", "until", "!"}
_SHELL_REDIRECTION_RE = re.compile(r"(?:[0-9]+)?(?:>>|<<|<>|>&|<&|>\||[<>])")

_INTERPRETER_NAME_RES = tuple((family, re.compile(pattern)) for family, pattern in (
    ("python", r"py(?:\.exe)?|python[23]?(?:\.\d+)*(?:\.exe)?"), ("node", r"node(?:js)?(?:\.exe)?"),
    ("perl", r"perl[0-9]*(?:\.\d+)*(?:\.exe)?"), ("ruby", r"ruby[0-9.]*(?:\.exe)?"), ("php", r"php(?:\.exe)?"),
    ("powershell", r"powershell(?:\.exe)?|pwsh(?:\.exe)?"),
    ("bun", r"bun(?:\.exe)?"), ("deno", r"deno(?:\.exe)?"),
))
_INTERPRETER_EXEC_FLAGS = {
    "python": {"-c"}, "node": {"-e", "--eval", "-p", "--print"}, "perl": {"-e", "--eval"}, "ruby": {"-e"},
    "php": {"-r"}, "powershell": {"-command", "-c", "-file", "-f"},
    "bun": {"-e", "--eval"}, "deno": {"eval", "-e", "--eval"},
}
_INTERPRETER_WITH_ARG = {
    "python": {"-W", "-X", "--check-hash-based-pycs"},
    "node": {"-C", "--conditions", "--cpu-prof-dir", "--diagnostic-dir", "--icu-data-dir", "--import", "--loader",
             "--openssl-config", "--require", "--title"},
    "perl": {"-0", "-F", "-I", "-M", "-m", "-x"}, "ruby": {"-C", "-E", "-F", "-I", "-K", "-r"},
    "php": {"-c", "-d", "-z"},
    "powershell": {"-configurationname", "-custompipename", "-executionpolicy", "-inputformat", "-outputformat",
                   "-settingsfile", "-version", "-windowstyle", "-workingdirectory"},
    # Deno's inline-script entry is the bare `eval` subcommand; the only global option that
    # may precede it and take a separate value is `-L/--log-level <level>` (`--env-file[=v]`
    # binds with `=`; the `--unstable-*` and `--ext` flags belong after `eval`).
    "bun": {"--config", "--cwd", "--env-file", "--preload", "--require"}, "deno": {"-L", "--log-level"},
}
_READ_TOOL_EXEC_FLAGS = {
    "sort": {"--compress-program"}, "rg": {"--pre", "--hostname-bin"}, "ag": {"--pager"},
    "man": {"--pager", "--html", "-P", "-H"},
}
# Required-argument options are ownership boundaries: an option-looking next token is data, not another option. These
# sets mirror the invocation grammar of the supported binaries (ripgrep 14, GNU sort, man-db, and ag 2.2).
_READ_TOOL_LONG_OPTIONS_WITH_ARG = {
    "rg": {
        "--after-context", "--before-context", "--color", "--colors", "--context", "--context-separator",
        "--dfa-size-limit", "--encoding", "--engine", "--field-context-separator", "--field-match-separator",
        "--file", "--generate", "--glob", "--hostname-bin", "--hyperlink-format", "--iglob", "--ignore-file",
        "--max-columns", "--max-count", "--max-depth", "--max-filesize", "--path-separator", "--pre", "--pre-glob",
        "--regex-size-limit", "--regexp", "--replace", "--sort", "--sortr", "--threads", "--type", "--type-add",
        "--type-clear", "--type-not",
    },
    "sort": {
        "--batch-size", "--buffer-size", "--compress-program", "--field-separator", "--files0-from", "--key",
        "--output", "--parallel", "--random-source", "--sort", "--temporary-directory",
    },
    "man": {
        "--config-file", "--encoding", "--extension", "--locale", "--manpath", "--pager", "--preprocessor",
        "--prompt", "--recode", "--sections", "--systems",
    },
    "ag": {
        "--ackmate-dir-filter", "--color-line-number", "--color-match", "--color-path", "--depth",
        "--filename-pattern", "--file-search-regex", "--ignore", "--ignore-dir", "--max-count", "--pager",
        "--path-to-ignore", "--width", "--workers",
    },
}
_READ_TOOL_SHORT_OPTIONS_WITH_ARG = {
    "rg": frozenset("efEmjgdtTABCMr"), "sort": frozenset("koStT"), "man": frozenset("CRLmMSserEPp"),
    "ag": frozenset("gGmpW"),
}
_GREP_OPTIONS_WITH_ARG = {
    "--after-context", "--before-context", "--binary-files", "--context", "--directories", "--devices", "--exclude",
    "--exclude-dir", "--exclude-from", "--include", "--label", "--max-count", "--regexp", "--file",
}
_GREP_SHORT_OPTIONS_WITH_ARG = {"A", "B", "C", "D", "d", "e", "f", "m"}
_BASH_OPTIONS_WITH_ARG = {"-O", "+O", "-o", "+o", "--init-file", "--rcfile"}
_BASH_SHORT_OPTION_LETTERS = frozenset("ilrsDcabefhkmnptuvxBCEHPTOo")
_MAX_DETECTION_COMMAND_CHARS, _MAX_SEPARATOR_FREE_COMMAND_CHARS, _MAX_DETECTION_SEGMENTS = 128_000, 4_096, 25_000
_MAX_SUBSTITUTION_DEPTH = 32
# A backslash-newline that an even run of backslashes precedes (so the backslash is not itself escaped).
_LINE_CONTINUATION_RE = re.compile(r"(?<!\\)((?:\\\\)*+)\\\r?\n")
_PARSER_LIMIT_DESCRIPTION = "command parser limit exceeded"
# Each nested eval re-parses the rest of the command, so every level is a full rescan.
_MAX_EVAL_NESTING = 8
_MALFORMED_EXEC_DESCRIPTION = "command parser limit or malformed executable payload"
# A scan that ran out of its step budget: approval, never remembered (a session or always grant
# would wave every later unscanned command through), and not a hardline refusal.
_SCAN_INCOMPLETE_DESCRIPTION = "command too complex to scan fully; review before running"
# A refusal from the budget-trip fallback, which also reads quoted text as code: say so, so the block
# message can point at splitting the command instead of claiming the operation was seen.
_FALLBACK_MATCH_SUFFIX = " (a quick re-read of a command too complex to scan fully; quoted text can match)"
_GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION = "stop/restart hermes gateway via shell-spliced verb (kills running agents)"


def _command_parser_limit_exceeded(command: str) -> bool:
    """Bound all parser work before normalization/tokenization. Separator counting is deliberately
    conservative: quoted separators over-count, but crossing the ceiling fails closed rather than
    letting an uninspected suffix execute."""
    if len(command) > _MAX_DETECTION_COMMAND_CHARS:
        return True
    # Long separator-free input has no compound-command utility and makes every regex inspect one giant token.
    if len(command) > _MAX_SEPARATOR_FREE_COMMAND_CHARS and not any(char in command for char in ";&|\n"):
        return True
    # Every nested `$(` level adds a command word whose literal-substitution pass rescans the rest of
    # the nesting, so detection cost grows ~cubically with depth (306 chars at depth 100 took ~4 s,
    # depth 240 ~50 s). No real command nests this deep; crossing the ceiling fails closed. Measured
    # on the author's quoting after NFKC (fullwidth `$（` folds to `$(`), with and without line
    # continuations (`$\<newline>(` is `$(` to bash, but not in a quoted heredoc body); comments and
    # quoted-heredoc bodies are data. Nesting that only the escape strip mints (`\$\(`, `\")\"`) is
    # not nesting in bash: the scan budget bounds it, and a trip asks for approval (`$''(` nests
    # too, but its scan stays linear).
    folded = unicodedata.normalize("NFKC", command)
    if max(_parser_budget.substitution_depth(text) for text in {folded, _LINE_CONTINUATION_RE.sub(r"\1", folded)}) \
            > _MAX_SUBSTITUTION_DEPTH:
        return True
    return sum(command.count(char) for char in ";&|\n") >= _MAX_DETECTION_SEGMENTS


def _splice(command: str, edits) -> str:
    """Apply sorted, non-overlapping ``(start, end, text)`` edits to *command* in one pass
    (re-slicing per edit is quadratic on 10k+ segments)."""
    parts, previous = [], 0
    for start, end, text in edits:
        parts.extend((command[previous:start], text))
        previous = end
    return "".join(parts) + command[previous:]


def _interpreter_family(executable: str) -> str | None:
    name = os.path.basename(executable).lower()
    return next((family for family, name_re in _INTERPRETER_NAME_RES if name_re.fullmatch(name)), None)


def _shell_segment_tokens(segment: str, start: int) -> list[str] | None:
    """Tokenize an already-bounded command segment. ``None`` distinguishes malformed quoting from
    an empty segment so callers can fail closed for a program-bearing option rather than silently
    skip it."""
    try:
        lexer = shlex.shlex(segment[start:], posix=True, punctuation_chars="<>")
        lexer.whitespace_split, lexer.commenters = True, ""
        return list(lexer)
    except ValueError:
        return None


def _iter_top_level_shell_segments(command: str):
    """Yield top-level command segments in one left-to-right pass."""
    start = 0
    for kind, i, j, quote in _scan_shell(command, comments=True):
        if kind == "comment" or (kind == "char" and quote is None and command[i] in ";&|\n"):
            if start < i:
                yield command[start:i]
            start = j
    if start < len(command):
        yield command[start:]


def _interpreter_exec_flag(family: str, args: list[str]) -> str | None:
    """Return an execution-bearing interpreter option, if present."""
    flags, with_arg = _INTERPRETER_EXEC_FLAGS[family], _INTERPRETER_WITH_ARG[family]
    powershell = family == "powershell"
    skip_value = False
    for token in args:
        if skip_value:
            skip_value = False
            continue
        if token == "--" or (not powershell and not token.startswith("-")):
            # Deno evaluates inline scripts via a bare `eval` subcommand rather than a dash
            # flag: the FIRST positional token, after any global options (`deno -q eval ...`);
            # a later positional `eval` (`deno run eval.ts`) stays data.
            if family == "deno" and token.lower() == "eval":
                return "eval"
            break
        option, equals, _ = token.partition("=")
        comparable = option.lower() if powershell else option
        if comparable in flags:
            return comparable
        # `-Wonce` and `ruby -rjson` attach an option value; they are not short-option bundles containing an execution
        # flag. PowerShell's normal long options also use one dash, so bundle parsing never applies to that family.
        has_attached_option_value = any(
            option.startswith(short) and len(option) > len(short)
            for short in with_arg if short.startswith("-") and not short.startswith("--")
        )
        if not powershell and not option.startswith("--") and len(option) > 2 and not has_attached_option_value:
            bundled = next((f"-{char}" for char in option[1:] if f"-{char}" in flags), None)
            if bundled:
                return bundled
        skip_value = comparable in with_arg and not equals
    return None


def _bash_exec_payload(args: list[str]) -> tuple[bool, str | None]:
    """Return whether Bash ``-c`` occurs and the command string it owns.
    Bash's O/o options consume the following argument even when they precede a later ``-c`` or
    share its short-option bundle; the two startup-file long options own their next token.
    Parsing those first prevents both missed payloads and false ``-c`` hits."""
    index = 0
    while index < len(args):
        token = args[index]
        if token == "--" or not token.startswith(("-", "+")):
            break
        if token in _BASH_OPTIONS_WITH_ARG:
            index += 2
            continue
        chars = token[1:]
        # Bash option letters are case-sensitive; restricting to the documented alphabet
        # preserves invalid controls such as `-Wc`.
        if token.startswith("--") or not set(chars) <= _BASH_SHORT_OPTION_LETTERS:
            index += 1
            continue
        consumed_option_arg = int("O" in chars or "o" in chars)
        if "c" in chars:
            payload_index = index + 1 + consumed_option_arg
            return True, (args[payload_index] if payload_index < len(args) else None)
        index += 1 + consumed_option_arg
    return False, None


def _read_tool_exec_flag(tool: str, args: list[str]) -> tuple[str, str] | None:
    """Return (option, program) for a read-only tool's program-running flag."""
    flags = _READ_TOOL_EXEC_FLAGS[tool]
    index = 0
    while index < len(args):
        token = args[index]
        if token == "--":
            break
        option, equals, payload = token.partition("=")
        payload = payload if equals else None
        matched = option if option in flags else None
        if tool == "man" and token.startswith(("-P", "-H")) and len(token) > 2:
            matched, payload = token[:2], token[2:]
        if matched:
            if payload is None and index + 1 < len(args):
                payload = args[index + 1]
            # The option owns its program argument regardless of spelling; the real binaries
            # execute a '-'-prefixed payload rather than reparsing it.
            if payload:
                return matched, payload
            index += 2 if payload is not None and "=" not in token else 1
        elif option in _READ_TOOL_LONG_OPTIONS_WITH_ARG[tool] and payload is None:
            index += 2
        elif token.startswith("-") and not token.startswith("--") and len(token) > 1:
            # In a short bundle, the first argument-taking option owns the rest of the token, or
            # the following token when it occurs last.
            shorts = _READ_TOOL_SHORT_OPTIONS_WITH_ARG[tool]
            owner = next((k for k, char in enumerate(token[1:], start=1) if char in shorts), None)
            index += 2 if owner == len(token) - 1 else 1
        else:
            index += 1
    return None


def _powershell_command_payload(args: list[str]) -> str | None:
    """The script text ``-Command``/``-c`` runs (every remaining argument, joined as PowerShell does),
    so commands after its first one reach the command-position rules. ``-File`` runs a path."""
    skip_value = False
    for index, token in enumerate(args):
        if skip_value:
            skip_value = False
            continue
        option = token.lower()
        if option in ("-command", "-c"):
            return " ".join(args[index + 1:]) or None
        if option in ("-file", "-f") or not option.startswith("-"):
            return None
        skip_value = option in _INTERPRETER_WITH_ARG["powershell"]
    return None


def _execution_flag_findings(command: str):
    """Yield scoped execution mechanisms and any executable payloads."""
    for segment in _iter_top_level_shell_segments(command):
        for start, _, word in _iter_shell_command_word_spans(segment):
            executable = _deobfuscate_shell_word_for_detection(word)
            tokens = _shell_segment_tokens(segment, start)
            executable_name = os.path.basename(executable).lower()
            family = _interpreter_family(executable)
            if tokens is None:
                if family is not None or executable_name in _READ_TOOL_EXEC_FLAGS:
                    yield (_MALFORMED_EXEC_DESCRIPTION, None)
                continue
            if not tokens:
                continue
            args = tokens[1:]
            if family and _interpreter_exec_flag(family, args):
                yield ("script execution via -e/-c flag",
                       _powershell_command_payload(args) if family == "powershell" else None)
            elif family and any(token.startswith("<<") for token in args):
                yield ("script execution via heredoc", None)
            else:
                if executable_name in _SHELL_NAMES:
                    found, payload = _bash_exec_payload(args)
                    if found:
                        yield ("shell command via -c/-lc flag", payload)
                if executable_name in _READ_TOOL_EXEC_FLAGS:
                    finding = _read_tool_exec_flag(executable_name, args)
                    if finding:
                        yield (f"arbitrary program execution via {executable_name} {finding[0]}", finding[1])


def _eval_payload(args: list[str]) -> str | None:
    """Return the shell code eval would run: its arguments joined by spaces."""
    # eval takes no options: only an explicit ``--`` is consumed. A first word such
    # as ``-x`` is code (zsh reports it missing and runs the rest of the list).
    if args and args[0] == "--":
        args = args[1:]
    return " ".join(args) or None


def _eval_payloads(command: str):
    """Yield the code each ``eval`` in *command* hands back to the shell, like a ``-c`` payload.
    Kept out of _execution_flag_findings: eval is not itself a dangerous mechanism, only its code is."""
    for segment in _iter_top_level_shell_segments(command):
        for start, _, word in _iter_shell_command_word_spans(segment):
            if os.path.basename(_deobfuscate_shell_word_for_detection(word)).lower() != "eval":
                continue
            # Bound to eval's own command: a `$(eval …)` / backtick nested in an outer command ends at
            # its closing `)`/`` ` ``, so the outer command's arguments are not eval code.
            tokens = _shell_segment_tokens(_shell_command_segment(segment, start), 0)
            payload = _eval_payload(tokens[1:]) if tokens else None
            if payload:
                yield payload


def _nested_payloads(source: str, eval_depth: int, capped: list[str] | None):
    """Yield ``(payload, eval_depth)`` for each program-bearing option and eval in *source*. eval code is
    one level deeper; past _MAX_EVAL_NESTING it is not surfaced (`eval eval … ls` made detection
    quadratic) and *source* is recorded in *capped* so the caller can fail closed."""
    for _, payload in _execution_flag_findings(source):
        if payload:
            yield payload, eval_depth
    if eval_depth < _MAX_EVAL_NESTING:
        for payload in _eval_payloads(source):
            yield payload, eval_depth + 1
    elif capped is not None and next(_eval_payloads(source), None):
        capped.append(source)


def _skip_shell_whitespace(command: str, pos: int) -> int:
    while pos < len(command) and command[pos].isspace():
        pos += 1
    return pos


def _read_shell_word(command: str, pos: int) -> tuple[int, int, str]:
    """Read one shell word without executing expansions."""
    start = end = _skip_shell_whitespace(command, pos)
    for kind, i, j, quote in _scan_shell(command, start, subst="u", brace=True):
        if kind == "char" and quote is None and (command[i].isspace() or command[i] in ";&|<>()"):
            break
        end = j
    return (start, end, command[start:end])


def _literal_command_substitution_output(script: str) -> str | None:
    """Resolve tiny literal command substitutions without executing a shell."""
    _parser_budget.charge(len(script))
    try:
        tokens = shlex.split(script, posix=True)
    except ValueError:
        tokens = []
    if not tokens:
        return None
    command, args = tokens[0].lower(), tokens[1:]
    if command == "echo":
        while args and re.fullmatch(r"-[nEe]+", args[0]):
            args = args[1:]
    elif command != "printf":
        return None
    if len(args) == 1 and _SIMPLE_SHELL_LITERAL_RE.fullmatch(args[0]):
        return args[0]
    if command == "printf" and len(args) == 2 and args[0] == "%s" and _SIMPLE_SHELL_LITERAL_RE.fullmatch(args[1]):
        return args[1]
    return None


def _replace_simple_command_substitutions(word: str) -> str:
    chars: list[str] = []
    i = 0
    while i < len(word):
        opener = 2 if word.startswith("$(", i) else 1 if word[i] == "`" else 0
        end = (_scan_dollar_paren_end if opener == 2 else _scan_backtick_end)(word, i) if opener else None
        replacement = _literal_command_substitution_output(word[i + opener:end - 1]) if end is not None else None
        if replacement is None:
            replacement, end = word[i], i + 1
        chars.append(replacement)
        i = end
    return "".join(chars)


def _replace_simple_shell_expansions(word: str) -> str:
    word = _replace_simple_command_substitutions(word)
    word = _PARAM_REPLACEMENT_RE.sub(lambda match: match.group("replacement"), word)
    return _PARAM_DEFAULT_RE.sub(lambda match: match.group("default"), word)


def _strip_shell_word_syntax(word: str) -> str:
    return "".join(
        word[i + 1] if kind == "esc" else word[i]
        for kind, i, _, _ in _scan_shell(word) if kind != "quote"
    )


# A brace word in COMMAND position expands to its comma-separated alternatives as separate words:
# `{rm,-rf,/}` runs as `rm -rf /`. Argument-position braces (`find / -{delete,print}`) never reach
# this deobfuscator, so the dynamic-word rules keyed on them still fire. No quotes/$/nesting.
_BRACE_ALTERNATION_RE = re.compile(r"\{([A-Za-z0-9_./:%@+=^-]+(?:,[A-Za-z0-9_./:%@+=^-]+)+)\}")


def _deobfuscate_shell_word_for_detection(word: str) -> str:
    """Approximate how shell syntax can spell a command word: collapses quoting/escaping plus
    simple literal command substitutions in the word itself. Intentionally narrow and non-executing."""
    # Pure, and the word walkers ask for the same words once per command start: memoize per call.
    return _parser_budget.memo(_deobfuscate_shell_word, word)


def _deobfuscate_shell_word(word: str) -> str:
    if brace := _BRACE_ALTERNATION_RE.fullmatch(word):
        return brace.group(1).replace(",", " ")
    for _ in range(2):
        previous = word
        word = _strip_shell_word_syntax(_replace_simple_shell_expansions(word))
        if word == previous:
            break
    return word


def _iter_shell_command_starts(command: str):
    starts = [0]

    def scan(start: int, end: int) -> None:
        skip = -1
        for kind, i, j, quote in _scan_shell(command, start, end, subst="uq", stop_unterminated=True,
                                            comments=True):
            if kind == "subst":
                # Record a nested $(...)/backtick command start and scan its body.
                inner = i + (1 if command[i] == "`" else 2)
                starts.append(inner)
                scan(inner, end if j is None else j - 1)
            elif kind == "char" and quote is None and i != skip:
                # `{` opens a brace group only as its own word (after whitespace or a separator): `${IFS}`
                # is a parameter expansion and `-{delete,print}` a brace-expansion word, and a start
                # marked inside either splits the word the flat patterns need to see intact.
                if command[i] in "(;\n" or (command[i] == "{" and (i == 0 or command[i - 1].isspace()
                                                                   or command[i - 1] in "(;&|)")):
                    starts.append(i + 1)
                elif command[i] in "&|":
                    repeated = i + 1 < end and command[i + 1] == command[i]
                    skip = i + 1 if repeated else skip
                    starts.append(i + 1 + repeated)

    scan(0, len(command))
    seen = set()
    run_from = run_to = -1
    for start in starts:
        # Each newline of a blank-line run is a start that skips to the same word: reuse the last skip
        # when the start falls inside the run it covered instead of rescanning the run per newline.
        if not run_from <= start <= run_to:
            run_from, run_to = start, _skip_shell_whitespace(command, start)
        start = run_to
        if start >= len(command) or start in seen or _is_shell_comment_start(command, start):
            continue
        seen.add(start)
        yield start
        _, end, word = _read_shell_word(command, start)
        if word in _SHELL_COMMAND_TRANSITIONS:
            starts.append(end)


def _mark_command_starts(command: str, marker: str = "\n", skip=()) -> str:
    """Insert *marker* (a newline) before each real (quote-aware) command start.
    ``\\n`` is already a ``_CMDPOS`` separator, so this exposes subshell ``(cmd)`` and brace-group
    ``{ cmd; }`` openers — which the flat pattern class omits — to the anchored patterns WITHOUT the
    quoted-prose false positives that adding ``(`` / ``{`` to ``_CMDPOS`` would cause: starts inside
    quotes are never produced, so ``--title "block (reboot)"`` is left as-is."""
    skip_starts = [a for a, _ in skip]  # sorted, non-overlapping spans
    offsets = sorted(o for o in _iter_shell_command_starts(command) if o > 0 and not (
        (k := bisect.bisect_right(skip_starts, o) - 1) >= 0 and o < skip[k][1]))
    return _splice(command, [(o, o, marker) for o in offsets]) if offsets else command


def _iter_shell_command_word_spans(command: str):
    """Yield command-position words that may be executable names."""
    from tools.approval_wrappers import _is_query_option
    for pos in _iter_shell_command_starts(command):
        wrapper, positionals = None, 0
        options, skip_arg = True, False
        while pos < len(command):
            redirect = _SHELL_REDIRECTION_RE.match(command, _skip_shell_whitespace(command, pos))
            if redirect:
                _, pos, _ = _read_shell_word(command, redirect.end())
                continue
            word_start, word_end, word = _read_shell_word(command, pos)
            if word_start == word_end:
                break
            pos = word_end
            deobfuscated = _deobfuscate_shell_word_for_detection(word)
            name = os.path.basename(deobfuscated).lower()
            if skip_arg:
                skip_arg = False
                continue
            if wrapper and options and deobfuscated == "--":
                options = False
                continue
            if wrapper and options and deobfuscated.startswith("-"):
                option = deobfuscated.split("=", 1)[0]
                if wrapper == "env" and (option == "--split-string" or deobfuscated.startswith("-S")):
                    # The split string and remaining argv form ONE command, handled
                    # by _env_split_payload; the suffix is not a new executable.
                    break
                queries = _COMMAND_WRAPPER_NON_EXECUTING_OPTIONS.get(wrapper, set())
                if option in queries or (wrapper == "command" and not option.startswith("--")
                                         and set(option[1:]) & {"v", "V"}) or (
                        wrapper == "sudo" and _is_query_option("sudo", option)):  # `-nl`, not `-ul`
                    break
                skip_arg = "=" not in deobfuscated and option in _COMMAND_WRAPPER_OPTIONS_WITH_ARG.get(wrapper, set())
                continue
            if positionals:
                positionals -= 1
                continue
            if _ENV_ASSIGNMENT_RE.fullmatch(word):
                continue
            yield (word_start, word_end, word)
            if name not in _COMMAND_WRAPPER_WORDS:
                break
            wrapper, options = name, True
            positionals = _COMMAND_WRAPPER_POSITIONAL_ARGS.get(name, 0)


def _shell_command_segment(command: str, start: int) -> str:
    """Bound a candidate to its command, preserving quoted argument bytes. The ``&``/``|`` of a ``2>&1``,
    ``<&3``, ``>|`` or ``&>`` redirection is part of the command, not a separator."""
    end = len(command)
    redirect_end = -1  # end of an unquoted, unescaped `<`/`>` (a quoted or escaped one is a literal)
    for kind, i, j, quote in _scan_shell(command, start, subst="uq", brace=True, comments=True):
        if kind == "char" and quote is None and ((command[i] == "&" and (redirect_end == i or command.startswith(">", j))) or (command[i] == "|" and redirect_end == i and command[i - 1] == ">")):
            continue
        redirect_end = j if kind == "char" and quote is None and command[i] in "<>" else -1
        if kind == "comment" or (kind == "char" and quote is None and command[i] in ";&|\n)`"):
            end = i
            break
    return command[start:end].strip()


def _dequoted_escape(char: str, quote: str | None) -> str:
    """What a backslash escape leaves after shell quote removal."""
    if char == "\n":
        return ""
    return char if quote is None or char in '$`"\\' else "\\" + char


def _deny_command_variants(command: str):
    """Add executable projections without reparsing normalized argument data.

    Whole-input matching is retained for existing globs. New projections parse
    the original quote state, preserve path-specific rules, and fold only the
    executable basename (never arbitrary argument paths).
    """
    yield from _command_detection_variants(command, floors=True)
    # Heredoc bodies are masked first, then ANSI-C expanded: `$'...'` inside a body is literal data.
    pending = list(dict.fromkeys(
        expand_ansi_c_quotes(source) for source in heredoc_scan_sources(command, _SHELL_NAMES_RE, floors=True)))
    seen = set()
    while pending:
        source = pending.pop()
        if source in seen:
            continue
        seen.add(source)
        for start, end, word in _iter_shell_command_word_spans(source):
            segment = _shell_command_segment(source, start)
            executable = _deobfuscate_shell_word_for_detection(word)
            tail = segment[end - start:]
            # Collapse only unquoted inter-word whitespace; quoted prose is data.
            parts, bare = [], []
            for kind, i, j, quote in _scan_shell(tail):
                if kind == "char" and quote is None and tail[i].isspace():
                    if not parts or parts[-1] != " ":
                        parts.append(" ")
                        bare.append(" ")
                else:
                    parts.append(tail[i:j])
                    # Quote removal as the shell performs it, so `git "status"` meets a `git status` rule.
                    if kind == "esc":
                        bare.append(_dequoted_escape(tail[i + 1], quote))
                    elif kind != "quote":
                        bare.append(tail[i:j])
            tail = "".join(parts)
            for name in dict.fromkeys((executable, os.path.basename(executable))):
                candidate = name + tail
                yield candidate
                yield name + "".join(bare)
                # Apply the existing text matching semantics only AFTER locating
                # executable positions; never parse its rewritten quotes again.
                yield _normalize_command_for_detection(candidate)
            if os.path.basename(executable) == "env":
                tokens = _shell_segment_tokens(segment, 0)
                if tokens:
                    payload = _env_split_payload(tokens)
                    if payload:
                        pending.append(payload)
        for _, payload in _execution_flag_findings(source):
            if payload:
                pending.append(payload)


def _command_detection_variants(
        command: str, eval_depth: int = 0, capped: list[str] | None = None, *, floors: bool = False):
    """Variants of the command with provably inert heredoc bodies dropped (#140704).

    A quote in a body (`it's`) desynced every quote-aware pass and hid the command after the
    heredoc; body lines projected as commands. `cat` bodies are data for the dangerous-prompt layer
    (unless the string runs the written file); the hardline and deny floors (*floors*) also scan the
    raw command, as main does. python/osascript dropped copies are scanned
    IN ADDITION. Bodies a shell runs (`bash <<EOF`, `cat <<EOF | sh`, `ssh host <<EOF`) and
    unterminated/mis-parsed `<<` stay.
    """
    seen: set[str] = set()
    for source in heredoc_scan_sources(command, _SHELL_NAMES_RE, floors=floors):
        for variant in _single_command_detection_variants(source, eval_depth, capped, floors=floors):
            if variant not in seen:
                seen.add(variant)
                yield variant


def _single_command_detection_variants(
        command: str, eval_depth: int = 0, capped: list[str] | None = None, *, floors: bool = False):
    from tools.approval_wrappers import literal_heredoc_bodies
    # Mask quoted newlines BEFORE normalization: normalization strips escapes (\" -> ") and ""
    # pairs, corrupting quote tracking (`echo "a\""` becomes an unterminated quote) so masking
    # afterwards could swallow a REAL unquoted newline separator. The raw command carries faithful quote state
    # once $'...' is rewritten as plain single quotes (`$'\''` otherwise desyncs every quote-aware scanner).
    command = expand_ansi_c_quotes(command)
    normalized = _normalize_command_for_detection(_mask_quoted_newlines(command))
    # Quote-aware grep parsing hides only structurally identified pattern operands; malformed or
    # ambiguous input stays byte-for-byte intact.
    grep_safe, _ = _grep_safe_detection_variant(normalized)
    seen = {grep_safe}
    yield grep_safe

    def fresh(variant: str) -> bool:
        if not variant or variant in seen:
            return False
        seen.add(variant)
        return True

    # Windows-path variant: normalization strips backslashes as shell escapes, so `del C:\Users\me\.ssh\id_rsa`
    # reaches the patterns as `del C:Usersme.sshid_rsa`. When the RAW command has a drive-letter or UNC backslash
    # path, also yield a variant with backslashes flattened to `/` BEFORE normalization. Gated on a real path shape so
    # POSIX escape semantics (`echo a\"b`) are untouched elsewhere.
    # See #69472.
    pending = [(normalized, eval_depth)]
    if re.search(r"(?:[A-Za-z]:|\\\\)[\\\\]", command) or re.search(r"[A-Za-z]:\\", command):
        win_variant = _normalize_command_for_detection(_mask_quoted_newlines(command.replace("\\", "/")))
        if fresh(win_variant):
            yield win_variant
            # Its payloads too: from the normalized text `pwsh -c "ls; ri -r C:\\"` loses the root's slash.
            pending.append((win_variant, eval_depth))
        # Its command starts (`a; rd /s /q C:\`): marked on the RAW command (faithful quote state), then flattened.
        marked_win = _normalize_command_for_detection(
            _mark_command_starts(_mask_quoted_newlines(command), marker=" \n").replace("\\", "/"))
        if fresh(marked_win):
            yield marked_win
    # Program-bearing options are parsed in their owning command's context; surfacing only the payload lets the
    # hardline floor inspect what will actually run without promoting similar flags or quoted prose.
    while pending:
        source, depth = pending.pop()
        for payload, payload_depth in _nested_payloads(source, depth, capped):
            if fresh(payload):
                yield payload
                # A payload may start with an option-looking program and then invoke a hardline command
                # after a separator; mark its starts.
                marked_payload = _mark_command_starts(payload)
                if marked_payload != payload and fresh(marked_payload):
                    yield marked_payload
                pending.append((payload, payload_depth))
    if capped:  # the caller fails closed; the passes below would only rescan the chain
        return
    # Payloads parsed from NORMALIZED text lost their escapes before their own quote expansion ran
    # (`bash -c "$'\\x72\\x6d' -rf /"` reached the patterns as `$'x72x6d'`). Parse the raw argument
    # too and treat it as new shell input; each payload is shorter than its source, so recursion ends.
    for payload, payload_depth in _nested_payloads(_mask_quoted_newlines(command), eval_depth, capped):
        if payload != command:
            for variant in _command_detection_variants(payload, payload_depth, capped, floors=floors):
                if fresh(variant):
                    yield variant
    # Subshell `(cmd)` / brace-group `{ cmd; }` openers put `cmd` at a real command position the flat `_CMDPOS`
    # patterns can't see (adding `(`/`{` there would match quoted prose like `--title "(reboot)"`). Insert a newline
    # at each start the QUOTE-AWARE tokenizer found instead; this covers every `_CMDPOS` rule in one place.
    marked = _mark_command_starts(grep_safe)
    if marked != grep_safe and fresh(marked):
        yield marked
    # Every variant above tracks quotes on NORMALIZED text, where `\"` has already become `"`. That
    # flips quote parity, so in `cat "f\"n.txt"; rm -rf /` the `; rm` start sat "inside" a phantom
    # quote, no start was marked, and the hardline floor let it through. Mark starts on the RAW
    # command (only quoted newlines masked), then normalize; the leading space keeps the marker
    # from being eaten as a `\<newline>` continuation when the preceding text ends in a backslash.
    faithful = _normalize_command_for_detection(_mark_command_starts(_mask_quoted_newlines(command), marker=" \n"))
    if fresh(faithful):
        yield faithful
    # An escaped separator is literal text inside its word (`git push -o ci\;skip -f`), but
    # normalization strips the backslash and leaves a real `;` that ends a segment-bounded match.
    # The same holds for an escaped space or quote inside an option value (`git -C my\\ repo push -f`).
    joined = _join_escaped_word_chars(command)
    if joined != command and fresh(variant := _normalize_command_for_detection(_mask_quoted_newlines(joined))):
        yield variant
    # Quoting/escaping can spell an executable in pieces (r\m, r''m). Keep that deobfuscation scoped
    # to command words so arguments don't false-positive.
    # One variant with EVERY command word deobfuscated, not one full-length variant per word: a heredoc
    # body of quoted lines has hundreds of quoted command words, and per-word variants made both
    # detection passes O(words * len) — minutes of GIL-held regex on a 15 KB command (#113535).
    # Spans arrive out of order (loop/conditional bodies after their keywords) and can nest (a
    # backtick word and the command inside it), so apply them sorted; spans overlapping an applied
    # one wait for the next round, one combined variant per nesting level.
    pending = sorted(
        ((word_start, word_end, deobfuscated) for word_start, word_end, word in _iter_shell_command_word_spans(normalized)
         if (deobfuscated := _deobfuscate_shell_word_for_detection(word)) and deobfuscated != word),
        key=lambda span: span[:2],
    )
    while pending:
        applied, carry, cursor = [], [], 0
        for span in pending:
            if span[0] < cursor:
                carry.append(span)
            else:
                applied.append(span)
                cursor = span[1]
        variant = _splice(normalized, applied)
        # A dequoted verb after a separator (`ls; "reboot"`) reaches _CMDPOS only once its start is marked; not inside
        # a quoted-delimiter heredoc fed to a non-shell (that body is literal data).
        yield from filter(fresh, (variant, _mark_command_starts(variant, skip=literal_heredoc_bodies(variant))))
        pending = carry


def _is_verification_artifact_cleanup(command: str) -> bool:
    """Return whether *command* only removes one Hermes ad-hoc temp script."""
    try:
        argv = shlex.split(command, posix=True)
    except ValueError:
        return False
    if len(argv) != 3 or argv[0] != "rm" or argv[1] != "-f":
        return False
    operand = argv[2]
    temp_dir = os.path.realpath(tempfile.gettempdir())
    basename = os.path.basename(operand)
    return (
        operand == os.path.join(temp_dir, basename)
        and os.path.dirname(os.path.realpath(operand)) == temp_dir
        and re.fullmatch(r"hermes-(?:verify|ad-hoc)-[A-Za-z0-9_.-]+", basename) is not None
    )


def _is_shell_token_spliced_gateway_lifecycle(command: str) -> bool:
    """Catch gateway-lifecycle verbs spelled with quote splicing.
    Backslash splicing (``kick\\start``) is undone by normalization, but quote splicing is not:
    ``_deobfuscate_shell_word_for_detection`` is deliberately scoped to command-position words
    (widening it would let quoted prose like ``git commit -m "rm -rf /"`` match), and the spliced
    verb is an ARGUMENT, so ``launchctl kick"start" -k gui/501/ai.hermes.gateway`` auto-approved.
    Delegates to ``cron.lifecycle_guard`` (shlex-tokenized, anchored on a hermes-gateway
    identifier). Runs last so an ordinary pattern match keeps its more specific reason; this layer
    only prompts — the non-bypassable block still lives in ``cron.lifecycle_guard``.

    ``_normalize_command_for_detection`` strips backslash escapes, so ``kick\\start`` already reaches the
    launchctl pattern above. See #80269.
    """
    try:
        from cron.lifecycle_guard import contains_gateway_lifecycle_command
    except Exception:
        return False
    return contains_gateway_lifecycle_command(command)


def _upload_flag_owner_ranges(command: str) -> tuple[list[int], list[int]]:
    """Merged ``(starts, ends)`` of the ranges where an upload flag may belong to curl/wget.
    ``awk -F``, ``cut -d`` and ``sort -t`` share the flag letters but take a delimiter and upload
    nothing. A range runs from a curl/wget word (``xargs curl``, ``ssh host curl``) or a word that
    may expand to one to the end of its simple command, and covers the inside of a quoted word
    (``eval "curl -d …"``, ``ssh host "curl …"``) that another program may re-parse as a command.
    Built once per command, so many delimiter flags cost one parse instead of one parse each."""
    ranges = []
    for start, _, _ in _iter_shell_command_word_spans(command):
        end = start + len(_shell_command_segment(command, start))
        pos = start
        while pos < end:
            redirect = _SHELL_REDIRECTION_RE.match(command, _skip_shell_whitespace(command, pos))
            if redirect:  # ``ssh host >/dev/null curl …``: a redirection does not end the command
                _, pos, _ = _read_shell_word(command, redirect.end())
                continue
            word_start, pos, word = _read_shell_word(command, pos)
            if word_start == pos:
                break
            if _word_may_run_curl_or_wget(word):
                ranges.append((word_start, end))
                break
            if any(ch.isspace() for ch in command[word_start:pos]):
                ranges.append((word_start + 1, pos))
    starts: list[int] = []
    ends: list[int] = []
    for range_start, range_end in sorted(ranges):
        if ends and range_start <= ends[-1]:
            ends[-1] = max(ends[-1], range_end)
        else:
            starts.append(range_start)
            ends.append(range_end)
    return starts, ends


def _upload_flag_owned_by_curl_or_wget(owner_ranges: tuple[list[int], list[int]], flag_start: int) -> bool:
    """True when the upload flag at *flag_start* lies in a range from :func:`_upload_flag_owner_ranges`."""
    starts, ends = owner_ranges
    index = bisect.bisect_right(starts, flag_start) - 1
    return index >= 0 and flag_start < ends[index]


def _word_may_run_curl_or_wget(word: str) -> bool:
    """True for a curl/wget word (also ``curl.exe``, ``C:\\tools\\curl.exe``) or a word whose command
    name holds an unresolved expansion (``$CURL``, ``"$(which curl)"``, ``/usr/bin/$CURL``,
    ``c${suffix}``): what it runs is unknown without executing the shell."""
    names = (os.path.basename(_deobfuscate_shell_word_for_detection(word)), re.split(r"[\\/]", word)[-1])
    if any(name.lower().removesuffix(".exe") in ("curl", "wget") for name in names):
        return True
    # A glob in the name (``/usr/bin/cur[l]``, ``wge*``) may match curl/wget.
    if any(fnmatch.fnmatchcase(tool, name.lower()) for name in names if any(c in name for c in "*?[")
           for tool in ("curl", "wget", "curl.exe", "wget.exe")):
        return True
    unquoted = word.lstrip("'\"")
    if unquoted.startswith(("$", "`")):
        return True
    # An option (``-d``) or assignment (``x="$A"``) cannot name the command being run; ``c${s:=url}`` can.
    return not unquoted.startswith("-") and not _ENV_ASSIGNMENT_RE.fullmatch(word) and ("$" in word or "`" in word)


def _quoted_text_is_executed(variant: str, pattern_re: "re.Pattern[str] | _PipeRemoteToShellMatcher") -> bool:
    """Whether a launcher (ssh, cmd /c, iex, a shell carrier, pwsh) at command position runs the quoted
    delete as code: the delete must sit in that launcher's own command, or be piped into a PowerShell
    reading stdin (`echo "..." | pwsh -`). A launcher word elsewhere (`echo ssh "..."`, `pwsh -v &&
    echo "..."`) leaves the quoted text prose."""
    prev_start = None
    for start, _, word in _iter_shell_command_word_spans(variant):
        stage_start, prev_start = prev_start, start
        name = os.path.basename(_deobfuscate_shell_word_for_detection(word)).lower().removesuffix(".exe")
        if name not in _PS_QUOTED_SCRIPT_LAUNCHERS:
            continue
        segment = _lower_preserving_flags(_shell_command_segment(variant, start))
        if name == "cmd" and not re.match(r"cmd(?:\.exe)?\s+/[ck]\b", segment, _RE_FLAGS):
            continue
        if pattern_re.search(segment):
            return True
        # `echo "gci | ri -r" | pwsh -`: the stage piped in is the previous command word's own text.
        before = variant[stage_start or 0:start].rstrip()
        if name in ("pwsh", "powershell") and stage_start is not None and before.endswith("|") \
                and not before.endswith("||") and pattern_re.search(_lower_preserving_flags(before)):
            return True
    return False


def _iter_dangerous_descriptions(command: str, only: frozenset[str] | None = None):
    """Yield the description (= pattern key) of every dangerous match, in detection order; may repeat.
    *only* restricts the scan to those pattern rules and skips the parser-limit, execution-flag and
    gateway-splice checks, which no content rule is."""
    if _command_parser_limit_exceeded(command):
        if only is None:
            yield _PARSER_LIMIT_DESCRIPTION
        return
    if _is_verification_artifact_cleanup(command):
        return
    if only is None:
        # First, on the raw command: the osascript keys are manual-only, so they must lead the findings
        # (`do shell script "rm ..."` would otherwise surface as a guardian-reviewable rm rule).
        yield from sorted(classify_osascript(unicodedata.normalize("NFKC", command.replace("\x00", ""))))
    patterns = DANGEROUS_PATTERNS_COMPILED if only is None else [
        (pattern_re, description) for pattern_re, description in DANGEROUS_PATTERNS_COMPILED if description in only
    ]
    capped: list[str] = []
    for command_variant in _command_detection_variants(command, capped=capped):
        command_lower = _lower_preserving_flags(command_variant)
        masked_lower: str | None = None
        for pattern_re, description in patterns:
            if description in _QUOTE_MASKED_DANGEROUS_DESCRIPTIONS or description == _PS_PIPE_ALIAS_DESCRIPTION:
                if masked_lower is None:
                    masked_lower = _lower_preserving_flags(
                        _mask_quoted_prose(command_variant)
                    )
                if pattern_re.search(masked_lower) or (
                    description == _PS_PIPE_ALIAS_DESCRIPTION and pattern_re.search(command_lower)
                    and _quoted_text_is_executed(command_variant, pattern_re)
                ):
                    yield description
            elif description == _CREDENTIAL_UPLOAD_DESCRIPTION:
                matches = list(pattern_re.finditer(command_lower))
                owner_ranges = _upload_flag_owner_ranges(command_lower) if matches else ([], [])
                if any(_upload_flag_owned_by_curl_or_wget(owner_ranges, match.start()) for match in matches):
                    yield description
            elif pattern_re.search(command_lower):
                yield description
    if capped and only is None:
        yield _PARSER_LIMIT_DESCRIPTION
    if only is not None:
        # The variation-selector check is a content rule too, so the content-only scan keeps it.
        if _INVISIBLE_UNICODE_DESCRIPTION in only and _HIDDEN_VARIATION_SELECTOR_RE.search(command):
            yield _INVISIBLE_UNICODE_DESCRIPTION
        return
    normalized = _normalize_command_for_detection(command)
    for description, _ in _execution_flag_findings(normalized):
        yield description
    if _is_shell_token_spliced_gateway_lifecycle(command):
        yield _GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION
    if _HIDDEN_VARIATION_SELECTOR_RE.search(command):
        yield _INVISIBLE_UNICODE_DESCRIPTION


def detect_dangerous_command(command: str) -> tuple:
    """Check dangerous patterns -> (is_dangerous, pattern_key, description) for the first match."""
    try:
        with _parser_budget.parser_budget(command):
            description = next(_iter_dangerous_descriptions(command), None)
    except _parser_budget.ParserBudgetExceeded:
        description = _SCAN_INCOMPLETE_DESCRIPTION
    except RecursionError:
        description = _PARSER_LIMIT_DESCRIPTION
    if description is None and hardline_scan_incomplete(command):
        description = _SCAN_INCOMPLETE_DESCRIPTION
    if description is None:
        return (False, None, None)
    return (True, description, description)


def detect_content_rule_keys(command: str) -> list[str]:
    """Pattern keys of every content-level rule (``_CONTENT_RULE_DESCRIPTIONS``) the command matches,
    wherever they fall in detection order. The approval gates require consent for these on top of
    the first match, so an approved pipe-to-shell cannot wave through a credential upload."""
    try:
        with _parser_budget.parser_budget(command):
            return list(dict.fromkeys(_iter_dangerous_descriptions(command, only=_CONTENT_RULE_DESCRIPTIONS)))
    except (_parser_budget.ParserBudgetExceeded, RecursionError):
        # Safe only because the hardline scan walks every variant under an equal budget, so it ran
        # out too, and the gates then require a one-shot approval for the whole command (pinned).
        return []
