Files
claude-config/bin/rule_hook/endless_wait.py
T
2026-11-18 19:07:42 +01:00

118 lines
6.1 KiB
Python

"""The waits that cannot end in a Bash or Monitor command, for the `endless-wait` rule: a loop that sleeps with no time or count cap, and a `pgrep -f` or `pkill -f` whose pattern matches the command line that holds it.
Both kinds hang the session that waits on them: `until [ -s f ] && ! pgrep -f "chunk-pr merg"; do sleep 15; done` matches its own shell, so its condition never holds.
Shell forms it does not read: a loop inside a function, a variable or a script file, and a count or deadline it does not recognise (it refuses the loop, and an override waives that).
"""
import re
from command_lines.shell_command import launched, segments, Simple
# What stands before a command in a segment without being part of it, as in `do sleep 15` or `! pgrep -f x`.
KEYWORDS = frozenset({"!", "do", "else", "then", "{"})
LOOPS = frozenset({"for", "until", "while"})
SHELLS = frozenset({"bash", "dash", "sh", "zsh"})
# A word with which a loop counts its rounds or compares a clock: `[ "$n" -lt 40 ]`, `$SECONDS`.
COUNTERS = frozenset({"-ge", "-gt", "-le", "-lt"})
# `for ((;;))` has no condition. The lexer splits at its parentheses, so the check reads the command's text.
FOREVER = re.compile(r"\bfor\s*\(\(\s*[^;)]*;\s*;")
# pgrep's and pkill's options that take a value, as short letters and as long names.
VALUED = frozenset("dFgGPrstuU")
VALUED_LONG = frozenset({"--delimiter", "--euid", "--group", "--ns", "--nslist", "--parent", "--pgroup", "--pidfile", "--runstates", "--session", "--signal", "--terminal", "--uid"})
HOW = "use `~/.claude/bin/wait-for <file> [<pattern>] --timeout <seconds>`"
def endless_waits(command: str, simples: list[Simple]) -> list[tuple[str, str]]:
"""Each endless wait the command starts, as its detail and the directory it runs in."""
return waits(command, simples, False)
def waits(command: str, simples: list[Simple], capped: bool) -> list[tuple[str, str]]:
"""capped is whether a `timeout` outside the simple commands ends them all, as for the inside of `timeout 60 bash -c '…'`."""
found = [] if capped else [(f"a loop that sleeps, `{' '.join(loop[0].words)[:60]}`, has neither a time limit nor a count cap; {HOW}, or give the loop a deadline compared with `date`, `timeout`, or a count as in `for i in $(seq 1 40)`", loop[0].directory) for loop in loops(simples) if endless(loop, command)]
for simple in simples:
if (pattern := self_match(simple.words, command)) is not None:
found.append((f"`{pattern}` is matched by the command line that holds this `pgrep -f` or `pkill -f`, so it finds its own shell; {HOW}, a `pgrep -x` on the process name, or a pattern the command doesn't contain, such as `[c]hunk` for `chunk`", simple.directory))
if (script := shell_script(simple.words)) is not None:
found += waits(command, [Simple(words, simple.directory) for words in segments(script)], capped or launched(simple.words, {"timeout"}) is not None)
return found
def core(words: list[str]) -> list[str]:
"""The words of a segment without the keywords before its command."""
start = next((i for i, word in enumerate(words) if word not in KEYWORDS), len(words))
return words[start:]
def loops(simples: list[Simple]) -> list[list[Simple]]:
"""Each loop as the segments from its keyword to its `done`, those of a loop nested in it included."""
open_loops: list[list[Simple]] = []
closed = []
for simple in simples:
words = core(simple.words)
for loop in open_loops:
loop.append(Simple(words, simple.directory))
if words[:1] and words[0] in LOOPS:
open_loops.append([Simple(words, simple.directory)])
elif words[:1] == ["done"] and open_loops:
closed.append(open_loops.pop())
return closed + open_loops
def endless(loop: list[Simple], command: str) -> bool:
"""Whether the loop sleeps and nothing bounds it."""
if not any(launched(simple.words, {"sleep"}) for simple in loop):
return False
head = loop[0].words
if head[0] == "for":
# A list ends the loop; an arithmetic for, whose words end at the lexer's split at `((`, does only where it has a condition.
return head == ["for"] and FOREVER.search(command) is not None
# `while ((i < 10))` splits the same way, so a bare keyword reads as a count.
if head == [head[0]]:
return False
words = {word for simple in loop for word in simple.words}
return not (COUNTERS & words or any("SECONDS" in word for word in words) or any(launched(simple.words, {"date", "timeout"}) for simple in loop))
def shell_script(words: list[str]) -> str | None:
"""The script of `bash -c <script>`, whose inner commands the lexer keeps as one word; None for any other command."""
shell = launched(words, SHELLS)
if shell is None:
return None
flags = [i for i, argument in enumerate(shell.arguments) if re.fullmatch(r"-[a-z]*c[a-z]*", argument)]
return shell.arguments[flags[0] + 1] if flags and flags[0] + 1 < len(shell.arguments) else None
def self_match(words: list[str], command: str) -> str | None:
"""The pattern of a `pgrep -f` or `pkill -f` that the command's own text matches, the shell's command line being that text; None where there is none."""
launch = launched(core(words), {"pgrep", "pkill"})
if launch is None:
return None
full, patterns, rest = False, [], iter(launch.arguments)
for word in rest:
if word.startswith("--"):
full = full or word == "--full"
if "=" not in word and word in VALUED_LONG:
next(rest, None)
elif word.startswith("-") and len(word) > 1:
# A signal, such as -9 or -KILL, isn't a cluster of options.
if word[1:].isdigit() or (word[1:].isupper() and len(word) > 2):
continue
for at, letter in enumerate(word[1:], 1):
full = full or letter == "f"
if letter in VALUED:
# `-u root` takes the next word; `-uroot` has it in the cluster.
if at == len(word) - 1:
next(rest, None)
break
else:
patterns.append(word)
return next((pattern for pattern in patterns if full and matches(pattern, command)), None)
def matches(pattern: str, text: str) -> bool:
"""Whether pgrep's regular expression finds a match in text; an expression Python cannot read is taken as plain text."""
try:
return re.search(pattern, text) is not None
except re.error:
return pattern in text