From 281220a69b864c09c9c74d4ceaff360f9b796197 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 19:33:09 +0100 Subject: [PATCH] Tighten endless-wait: a timeout inside a loop caps nothing, and cover each branch --- bin/rule_hook/endless_wait.py | 46 ++++++++++++++------------------- bin/rule_hook/rules.py | 2 +- bin/rule_hook/test_rule_hook.py | 16 +++++++++--- 3 files changed, 33 insertions(+), 31 deletions(-) diff --git a/bin/rule_hook/endless_wait.py b/bin/rule_hook/endless_wait.py index 6567cffd..a2c405f5 100644 --- a/bin/rule_hook/endless_wait.py +++ b/bin/rule_hook/endless_wait.py @@ -3,6 +3,7 @@ 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 itertools import re from command_lines.shell_command import launched, segments, Simple @@ -11,49 +12,45 @@ from command_lines.shell_command import launched, segments, Simple 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`. +# A word with which a loop counts its rounds: `[ "$n" -lt 40 ]`. 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*;") +# A signal given to pkill, as -9 or -KILL, which is not a cluster of options. +SIGNAL = re.compile(r"-(?:\d+|[A-Z]{2,})") # 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 [] --timeout `" -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)] +def endless_waits(command: str, simples: list[Simple], capped: bool = False) -> list[tuple[str, str]]: + """Each endless wait the command starts, as its detail and the directory it runs in. capped is whether a `timeout` ends every loop in the simple commands, as it does inside `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` or $SECONDS, or a counter, 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) + found += endless_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:] + return list(itertools.dropwhile(KEYWORDS.__contains__, words)) 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 simple in (Simple(core(simple.words), simple.directory) for simple in simples): + first = simple.words[0] if simple.words else "" 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: + loop.append(simple) + if first in LOOPS: + open_loops.append([simple]) + elif first == "done" and open_loops: closed.append(open_loops.pop()) return closed + open_loops @@ -67,10 +64,10 @@ def endless(loop: list[Simple], command: str) -> bool: # 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]]: + if len(head) == 1: 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)) + return not (COUNTERS & words or any("SECONDS" in word for word in words) or any(launched(simple.words, {"date"}) for simple in loop)) def shell_script(words: list[str]) -> str | None: @@ -91,12 +88,9 @@ def self_match(words: list[str], command: str) -> str | None: for word in rest: if word.startswith("--"): full = full or word == "--full" - if "=" not in word and word in VALUED_LONG: + if 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 + elif word.startswith("-") and len(word) > 1 and not SIGNAL.fullmatch(word): for at, letter in enumerate(word[1:], 1): full = full or letter == "f" if letter in VALUED: @@ -104,7 +98,7 @@ def self_match(words: list[str], command: str) -> str | None: if at == len(word) - 1: next(rest, None) break - else: + elif not word.startswith("-") or len(word) == 1: patterns.append(word) return next((pattern for pattern in patterns if full and matches(pattern, command)), None) diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index bef753a9..44a48b27 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -43,7 +43,7 @@ RULES: dict[RuleName, Rule] = { ), "endless-wait": Rule( "a wait ends: a loop that sleeps has a time limit or a count cap, and a `pgrep -f` or `pkill -f` has a pattern its own command line doesn't match, since such a pattern finds the shell that runs the command and the wait never ends, and the session that waits on it hangs; wait with `~/.claude/bin/wait-for [] --timeout `, or find a process by name with `pgrep -x`", - "a Bash or Monitor command with an `until`, `while` or `for ((;;))` loop that runs `sleep` and has no `timeout`, no `date` or $SECONDS comparison and no counter compared with -lt, -le, -gt or -ge, or a `pgrep -f` or `pkill -f` whose pattern, read as a regular expression, matches the command's text; the same inside the script of a `bash -c`, unless a `timeout` runs the shell. A loop over a list, such as `for i in $(seq 1 40)`, is a count and passes", + "a Bash or Monitor command with an `until`, `while` or `for ((;;))` loop that runs `sleep` and has no `date` or $SECONDS comparison and no counter compared with -lt, -le, -gt or -ge, or a `pgrep -f` or `pkill -f` whose pattern, read as a regular expression, matches the command's text; the same inside the script of a `bash -c`, unless a `timeout` runs the shell. A loop over a list, such as `for i in $(seq 1 40)`, is a count and passes", ), # A marker would let the credentials into the transcript all the same, so no marker waives it. "env-file-read": Rule( diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 59404f50..d090244a 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -145,28 +145,36 @@ class CommandBreaches(unittest.TestCase): self.assertEqual(checked(command), []) def test_a_loop_that_sleeps_without_a_time_or_count_cap_breaks_endless_wait(self): - for command in ["until [ -s /tmp/x.log ]; do sleep 15; done", "while true; do sleep 1; done", "while ! curl -sf localhost:80; do sleep 2; done", "until [ -s /tmp/merge.log ] && ! pgrep -x chunk-pr; do sleep 15; done", "for ((;;)); do sleep 1; done", "echo a && until test -f f; do sleep 1; done", "bash -c 'until [ -s f ]; do sleep 1; done'", "if x; then while true; do sleep 1; done; fi", "for i in 1 2; do until [ -s f ]; do sleep 1; done; done", "tail -f x | while read l; do sleep 1; done"]: + for command in ["until [ -s /tmp/x.log ]; do sleep 15; done", "while true; do sleep 1; done", "while ! curl -sf localhost:80; do sleep 2; done", "until [ -s /tmp/merge.log ] && ! pgrep -x chunk-pr; do sleep 15; done", "for ((;;)); do sleep 1; done", "echo a && until test -f f; do sleep 1; done", "bash -c 'until [ -s f ]; do sleep 1; done'", "if x; then while true; do sleep 1; done; fi", "for i in 1 2; do until [ -s f ]; do sleep 1; done; done", "tail -f x | while read l; do sleep 1; done", "until timeout 5 curl -sf x; do sleep 1; done", "until [ -s f ]; do echo seconds; sleep 1; done", "until [ -s f ]\ndo\n sleep 1\ndone", "bash -x -c 'until [ -s f ]; do sleep 1; done'"]: with self.subTest(command): self.assertEqual(checked(command), ["endless-wait"]) def test_a_loop_with_a_deadline_a_count_or_no_sleep_passes_endless_wait(self): - for command in ["until [ -s f ]; do sleep 15; [ $((n+=1)) -ge 40 ] && break; done", "end=$((SECONDS+600)); until [ -s f ] || [ $SECONDS -gt $end ]; do sleep 5; done", "until [ -s f ] || [ $(date +%s) -ge $end ]; do sleep 5; done", "n=0; while [ $n -lt 40 ]; do sleep 1; n=$((n+1)); done", "while ((n < 40)); do sleep 1; done", "for i in $(seq 1 40); do [ -s f ] && break; sleep 15; done", "for f in a b c; do sleep 1; done", "for ((i=0; i<40; i++)); do sleep 1; done", "timeout 600 bash -c 'until [ -s f ]; do sleep 1; done'", "~/.claude/bin/wait-for /tmp/x.log 'merged' --timeout 600", "while read l; do echo $l; done < f", "until [ -s f ]; do echo waiting; done", "echo 'until x; do sleep 1; done'"]: + for command in ["until [ -s f ]; do sleep 15; [ $((n+=1)) -ge 40 ] && break; done", "end=$((SECONDS+600)); until [ -s f ] || [ $SECONDS -gt $end ]; do sleep 5; done", "until [ -s f ] || [ $(date +%s) -ge $end ]; do sleep 5; done", "n=0; while [ $n -lt 40 ]; do sleep 1; n=$((n+1)); done", "while ((n < 40)); do sleep 1; done", "until [ -s f ] || [ \"$SECONDS\" = 600 ]; do sleep 5; done", "until [ -s f ] || [ $(date +%s) = $end ]; do sleep 5; done", "while read l; do echo $l; done < f; sleep 5", "bash script.sh", "bash -c", "bash -x", "for i in $(seq 1 40); do [ -s f ] && break; sleep 15; done", "for f in a b c; do sleep 1; done", "for ((i=0; i<40; i++)); do sleep 1; done", "timeout 600 bash -c 'until [ -s f ]; do sleep 1; done'", "~/.claude/bin/wait-for /tmp/x.log 'merged' --timeout 600", "while read l; do echo $l; done < f", "until [ -s f ]; do echo waiting; done", "echo 'until x; do sleep 1; done'"]: with self.subTest(command): self.assertEqual(checked(command), []) def test_a_pgrep_or_pkill_f_whose_pattern_the_command_contains_breaks_endless_wait(self): - for command in ["pgrep -f chunk-pr", "pkill -f 'loop-claude'", "pgrep -fa chunk-pr", "pgrep -u me -f chunk-pr", "pgrep --full chunk-pr", "pkill -9 -f loop-claude", "pgrep -f 'chunk-pr .*merg'", "nice pgrep -f chunk-pr", "bash -c 'pgrep -f chunk-pr'"]: + for command in ["pgrep -f chunk-pr", "pkill -f 'loop-claude'", "pgrep -fa chunk-pr", "pgrep -u me -f chunk-pr", "pgrep --full chunk-pr", "pkill -9 -f loop-claude", "pkill -KILL -f loop-claude", "pgrep -f chunk-pr -u", "pgrep -f -", "pgrep -U me -f chunk-pr", "pgrep -fUME chunk-pr", "pgrep -f9 chunk-pr", "pgrep --signal TERM --full chunk-pr", "pgrep -f 'chunk[pr'", "pgrep -f 'chunk-pr .*merg'", "nice pgrep -f chunk-pr", "bash -c 'pgrep -f chunk-pr'"]: with self.subTest(command): self.assertEqual(checked(command), ["endless-wait"]) self.assertIn("pgrep -x", breaches("pgrep -f chunk-pr")[0].detail) + def test_an_endless_wait_names_its_loop_and_the_folder_it_runs_in(self): + head = "until [ -s /tmp/a-file-whose-name-takes-the-head-past-sixty-characters-by-itself ]" + found = breaches(f"cd /w && {head}; do sleep 1; done") + self.assertEqual([breach.directory for breach in found], ["/w"]) + self.assertIn(f"`{head[:60]}`, has neither a time limit nor a count cap; use `~/.claude/bin/wait-for", found[0].detail) + self.assertEqual([breach.directory for breach in breaches("cd /w && bash -c 'pgrep -f x; until [ -s f ]; do sleep 1; done'")], ["/w", "/w"]) + self.assertEqual(len(breaches("pgrep -f aa; bash -c 'pgrep -f bb'")), 2) + def test_a_loop_that_waits_on_its_own_pgrep_breaks_endless_wait_twice(self): command = 'until [ -s /tmp/merge-402.log ] && ! pgrep -f "chunk-pr merg"; do sleep 15; done' self.assertEqual(checked(command), ["endless-wait", "endless-wait"]) self.assertEqual(checked(command.replace("-f ", "-x ")), ["endless-wait"]) def test_a_pgrep_f_on_a_pattern_the_command_lacks_or_a_pgrep_without_f_passes_endless_wait(self): - for command in ["pgrep -f '[c]hunk-pr merg'", "pgrep -f \"$name\"", "pgrep -f '^python3 .*loop-claude$'", "pgrep -x chunk-pr", "pgrep chunk-pr", "pgrep -u me -x chunk-pr", "pkill -f -u me '[l]oop-claude'", "echo pgrep -f chunk-pr", "git commit -m 'Refuse pgrep -f chunk-pr'", "pgrep -f"]: + for command in ["pgrep -f '[c]hunk-pr merg'", "pgrep -f \"$name\"", "pgrep -f '^python3 .*loop-claude$'", "pgrep -x chunk-pr", "pgrep chunk-pr", "pgrep -u me -x chunk-pr", "pkill -f -u me '[l]oop-claude'", "pkill --signal TERM --full '[c]hunk'", "pkill --signal=TERM --full '[c]hunk'", "pgrep -f -U me '[c]hunk' -u", "echo pgrep -f chunk-pr", "git commit -m 'Refuse pgrep -f chunk-pr'", "pgrep -f"]: with self.subTest(command): self.assertEqual(checked(command), [])