diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f954ccf..65f7bf0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Refuse in rule-hook a Bash or Monitor command that waits forever: a sleeping loop with no time or count cap, and a `pgrep -f` or `pkill -f` whose pattern its own command line matches. - A project's config may list its team's convention files in `coding-conventions`, which larv-review's reviewer agents read beside the principles and the standards, the team's rule winning where they conflict. larv-review opens the pull request after its own review where a push to the branch starts CI, and files an item to add a mutation tool where `mutate-changes` covers none of a language. The technical principles gain rules for tests on a shared environment, "Never mock a service your own team runs" and "Don't loosen a type when refactoring"; stability-reviewer checks a change that stores a value differently; and every finding of an outside reviewer now changes the setup, a deterministic tool first. - do-epic's epic backends rank a child issue just before another, in Jira and in memory, and do-epic can re-rank Jira's backlog to an epic's ranking: it moves only the issues the loop filed, so each issue a person filed keeps its place, and it stops at the first rank Jira refuses and names it. Nothing calls it yet. - Comprehension seats run as the `comprehension-seat` agent under `agents/`, which starts without `CLAUDE.md` and the skill and agent listings, and `larv-review prepare-scoring` no longer takes `--preloaded`; after updating, launch each seat with `subagent_type: comprehension-seat`. diff --git a/README.md b/README.md index 2369b886..0142b1ef 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,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..e4486d93 --- /dev/null +++ b/bin/rule_hook/endless_wait.py @@ -0,0 +1,122 @@ +"""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