"""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. A sleeping loop with no cap never ends. A `pgrep -f` or `pkill -f` finds the shell that runs it when its pattern matches that shell's command line, so a loop that waits for the process to disappear, as in `until [ -s f ] && ! pgrep -f "chunk-pr merg"; do sleep 15; done`, never ends either. A session that waits on one hangs. It reads the command's own text. A loop in a script file or in a variable's value isn't read, and a counter or deadline it doesn't recognise leaves the loop refused, which an override waives. """ import itertools 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", "elif", "else", "if", "then", "{"}) # The keywords of a loop whose condition is a command, as in `while sleep 30`. CONDITIONS = frozenset({"until", "while"}) LOOPS = frozenset({"for", "until", "while"}) SHELLS = frozenset({"bash", "dash", "sh", "zsh"}) # 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 `" # What the refusal of a self-matching pgrep or pkill suggests first. Only a pgrep waits, so only it is pointed to wait-for. INSTEAD = {"pgrep": f"{HOW}, a `pgrep -x` on the process name", "pkill": "use a `pkill -x` on the process name"} def endless_waits(command: str, simples: list[Simple], capped: bool) -> list[tuple[str, str]]: """Each endless wait the command starts, as its detail and the directory it runs in. capped is whether something ends every loop in the simple commands: a Monitor call's timeout_ms, or a `timeout` around the shell, as in `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 (found_match := self_match(simple.words, command)) is not None: tool, pattern = found_match found.append((f"`{pattern}` matches the command line that holds this `{tool} -f`, so `{tool}` finds the shell that runs the command; {INSTEAD[tool]}, 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 += 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 or its loop keyword.""" return list(itertools.dropwhile(KEYWORDS.__contains__, words)) def invoked(words: list[str]) -> list[str]: """The command a segment runs, which a loop's condition may be: `until ! pgrep -f x` runs pgrep.""" return list(itertools.dropwhile((KEYWORDS | CONDITIONS).__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 (Simple(core(simple.words), simple.directory) for simple in simples): kind = simple.words[0] if simple.words else None for loop in open_loops: loop.append(simple) if kind in LOOPS: open_loops.append([simple]) elif kind == "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(invoked(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` ends it only with a condition; its words stop at the lexer's split at `((`. 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 len(head) == 1: return False # A counter or a clock is judged by its words alone: a stricter test would refuse the bounded loops people write, and none can tell that the count advances or the clock is compared. So `-ge` on a file's line count, or a `date` that only logs, passes. 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(invoked(simple.words), {"date"}) for simple in loop)) def shell_script(words: list[str]) -> str | None: """The script of `bash -c