diff --git a/README.md b/README.md index c23cfa32..e2c7bfd4 100644 --- a/README.md +++ b/README.md @@ -193,7 +193,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`, by default the one its config names; `rank_todo.py --help` states the format. - `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure. - `review-replay ` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. `review-replay --help` states the replay. With `--omit-claude-md`, `--bash-ceiling` or `--read-limit` it tests instead whether the pass's reviewer may start without `CLAUDE.md`, or under the Bash output ceiling loop-claude hands the worker, or a Read limit it doesn't hand yet: it replays each round three times as archived and once with the change, and prints whether the reviewer passes: whether the last replay missed no more findings than the most an unchanged replay missed, with each count and each finding it missed. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host. -- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, Grep, MultiEdit, Read, Skill and Write call, and `rule-hook --help` states the rules and the override. +- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, Grep, Monitor, MultiEdit, Read, Skill and Write call, and `rule-hook --help` states the rules and the override. - `run-heavy ` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit. - `run-tests [...]` runs this repo's test suite, as Test says. - `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by. Per chunk it also shows code health's two counter-signals, misread findings and later fixes, and how many of the human's answers reversed a worker's choice; `score-outcomes --help` states the report. diff --git a/bin/rule_hook/endless_wait.py b/bin/rule_hook/endless_wait.py new file mode 100644 index 00000000..6567cffd --- /dev/null +++ b/bin/rule_hook/endless_wait.py @@ -0,0 +1,117 @@ +"""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 [] --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)] + 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