Refuse an endless wait in rule-hook #617
@@ -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`.
|
||||
|
||||
@@ -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 <pass> <model>` 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 <command>` 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 [<pytest args>...]` 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.
|
||||
|
||||
@@ -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 <file> [<pattern>] --timeout <seconds>`"
|
||||
# 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 <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) -> tuple[str, str] | None:
|
||||
"""The tool and the pattern of a `pgrep -f` or `pkill -f` whose pattern matches the command's own text, which is the shell's command line; None where there is none."""
|
||||
launch = launched(invoked(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 word in VALUED_LONG:
|
||||
next(rest, None)
|
||||
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:
|
||||
# `-u root` takes the next word; `-uroot` has it in the cluster.
|
||||
if at == len(word) - 1:
|
||||
next(rest, None)
|
||||
break
|
||||
elif not word.startswith("-") or len(word) == 1:
|
||||
patterns.append(word)
|
||||
return next(((launch.tool, 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
|
||||
+11
-7
@@ -3,14 +3,14 @@
|
||||
usage: rule-hook (a PreToolUse hook: reads the call as JSON on stdin)
|
||||
rule-hook overrides (prints this chunk's overrides)
|
||||
|
||||
settings.json runs it before each Agent, Bash, Edit, Grep, MultiEdit, Read, Skill and Write call, in every session and
|
||||
settings.json runs it before each Agent, Bash, Edit, Grep, Monitor, MultiEdit, Read, Skill and Write call, in every session and
|
||||
subagent. The rules:
|
||||
|
||||
{rules}
|
||||
|
||||
A call overrides a rule with `# rule-override <rule>: <reason>`:
|
||||
|
||||
- anywhere in a Bash command, such as a trailing comment
|
||||
- anywhere in a Bash or Monitor command, such as a trailing comment
|
||||
- in a file, as a comment line in the text the edit writes
|
||||
- in Markdown, as `<!-- rule-override <rule>: <reason> -->`
|
||||
|
||||
@@ -64,6 +64,10 @@ from rule_hook.todo_check import todo_breaches
|
||||
from rule_hook.transcript_read import transcript_breaches
|
||||
|
||||
|
||||
# The tools whose `command` is a shell command. Claude Code ignores a hook's rewrite of a Monitor command, but rule-hook only blocks, so it reads the two alike; its endless-wait loop check is the exception, since a Monitor call ends at its timeout_ms.
|
||||
COMMAND_TOOLS = ("Bash", "Monitor")
|
||||
|
||||
|
||||
def main(argv: list[str], stdin: str) -> int:
|
||||
if argv in (["-h"], ["--help"]) or not argv and not stdin:
|
||||
print(__doc__.strip().replace("{rules}", rules_help()))
|
||||
@@ -84,7 +88,7 @@ def main(argv: list[str], stdin: str) -> int:
|
||||
if found is None:
|
||||
return 0
|
||||
written, what, breaches = found
|
||||
return answer(check(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool == "Bash"), what, time.time())
|
||||
return answer(check(breaches, written, text(call.given, "file_path").endswith(".md"), call.tool in COMMAND_TOOLS), what, time.time())
|
||||
|
||||
|
||||
def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tuple[str, str, list[Breach]] | None:
|
||||
@@ -93,9 +97,9 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
|
||||
return text(call.given, "prompt"), text(call.given, "subagent_type"), reviewer_breaches(call, environ, home)
|
||||
if call.tool == "Skill":
|
||||
return text(call.given, "args"), text(call.given, "skill"), skill_breaches(call, environ, home)
|
||||
if call.tool == "Bash":
|
||||
if call.tool in COMMAND_TOOLS:
|
||||
command = text(call.given, "command")
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home) + env_file_breaches(call, home)
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home, call.tool == "Monitor") + read_breaches(call, home) + env_file_breaches(call, home)
|
||||
if call.tool == "Read":
|
||||
return "", text(call.given, "file_path"), read_breaches(call, home) + env_file_breaches(call, home) + transcript_breaches(call, home)
|
||||
if call.tool == "Grep":
|
||||
@@ -126,13 +130,13 @@ def answer(checked: Checked, what: str, now: float) -> int:
|
||||
return 2 if unloggable else 0
|
||||
|
||||
|
||||
def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
|
||||
def bash_breaches(command: str, cwd: str, home: str, monitor: bool = False) -> list[Breach]:
|
||||
"""The breaches of the command's own words, then of each commit it makes, then of the files those commits may take."""
|
||||
simples = simple_commands(command, cwd, home)
|
||||
found = commits(simples, home)
|
||||
in_commits = [breach for commit in found for breach in commit_breaches(commit, pathlib.Path(home))]
|
||||
in_files = [breach for directory in dict.fromkeys(commit.directory for commit in found) for breach in committed_file_breaches(directory)]
|
||||
return command_breaches(command, simples) + in_commits + in_files
|
||||
return command_breaches(command, simples, monitor) + in_commits + in_files
|
||||
|
||||
|
||||
def commit_breaches(commit: CommitCall, home: pathlib.Path) -> list[Breach]:
|
||||
|
||||
@@ -5,6 +5,7 @@ import typing
|
||||
|
||||
from review_rules.round_titles import CAP, COUNTS, EXAMPLE, lacks_counts, OPENING, RELEASE_REVIEW_CAP
|
||||
from git_cli.git_command import CommitCall
|
||||
from rule_hook.endless_wait import endless_waits
|
||||
from run_heavy.capped_docker import finds_this_docker
|
||||
from rule_hook.heavy_command import heavy
|
||||
from command_lines.shell_command import launched, LAUNCHERS, Simple
|
||||
@@ -12,7 +13,7 @@ from review_rules.review_folder import REPORTS
|
||||
from project_config import templates
|
||||
from command_lines.docker_command import unlimited
|
||||
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "commit-title", "docker-run-memory", "env-file-read", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check", "transcript-read"]
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "commit-title", "docker-run-memory", "endless-wait", "env-file-read", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check", "transcript-read"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -40,6 +41,10 @@ RULES: dict[RuleName, Rule] = {
|
||||
"a container made with docker run or docker create has a memory limit and a swap limit, as large as its work needs, such as `--memory 4g --memory-swap 4g`, so a runaway container fails alone instead of starving the machine; a swap limit equal to the memory limit keeps it out of swap",
|
||||
"docker run, docker create, docker container run and docker container create, whether direct or through a launcher such as nice or timeout. One under run-heavy passes, as run-heavy's docker adds the limits on Linux, unless it names docker by its path, or changes or clears PATH, as env -i, sudo or doas do. A container a script or docker compose starts is not checked",
|
||||
),
|
||||
"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 that its own command line doesn't match, since a pattern that line matches finds the shell that runs the command, and a loop that waits for that process to end never does; wait with `~/.claude/bin/wait-for <file> [<pattern>] --timeout <seconds>`, or find a process by name with `pgrep -x`",
|
||||
"a Bash 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, so a loop over a list, such as `for i in $(seq 1 40)`, passes; a Bash or Monitor command with 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 shell's -c, where a `timeout` around the shell lifts only the loop check. A Monitor call's `timeout_ms` ends its loops, so only the `pgrep -f` and `pkill -f` check applies to it",
|
||||
),
|
||||
# A marker would let the credentials into the transcript all the same, so no marker waives it.
|
||||
"env-file-read": Rule(
|
||||
"an agent never reads ~/.claude/.env or a project's env-file, the file of credentials the project's config names, since a value the agent reads lands in its transcript, which loop-claude archives and the backups copy; it leaves a tool that needs a credential to read the file itself, gets the file's path from `~/.claude/bin/project-config env-file`, and spells the path another way, such as \"the .env in ~/.claude\", in a command that must mention it without reading it, such as a commit's title, and searches only a folder without it",
|
||||
@@ -158,11 +163,13 @@ def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> C
|
||||
return Checked(messages, bool(blocking), [(breach, grant[breach.rule]) for breach, grant in zip(breaches, grants) if breach.rule in grant])
|
||||
|
||||
|
||||
def command_breaches(command: str, simples: list[Simple]) -> list[Breach]:
|
||||
def command_breaches(command: str, simples: list[Simple], monitor: bool = False) -> list[Breach]:
|
||||
"""The breaches of the command's own words; monitor is whether a Monitor call runs it, which ends every loop at its timeout_ms."""
|
||||
breaches = []
|
||||
publishing = [simple for simple in simples if posixpath.basename(simple.words[0]) in ("chunk-pr", "gh", "git", "tea")]
|
||||
if publishing and ATTRIBUTION.search(command):
|
||||
breaches.append(Breach("no-ai-attribution", "the command carries an attribution", publishing[0].directory))
|
||||
breaches += [Breach("endless-wait", detail, directory) for detail, directory in endless_waits(command, simples, monitor)]
|
||||
for simple in simples:
|
||||
if heavy(simple.words):
|
||||
breaches.append(Breach("run-heavy", f"run `{' '.join(simple.words)[:80]}` under `~/.claude/bin/run-heavy`, in the background", simple.directory))
|
||||
|
||||
@@ -144,6 +144,43 @@ class CommandBreaches(unittest.TestCase):
|
||||
with self.subTest(command):
|
||||
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", "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'", "while sleep 30; do echo x; done", "until ! pgrep -x chunk-pr; do sleep 5; 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", "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'", "until ! pgrep -x chunk-pr || [ $SECONDS -gt 600 ]; do sleep 15; 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", "pkill -KILL -f loop-claude", "pgrep -f chunk-pr -u", "pkill --full chunk-pr --signal", "pgrep -f -", "if pgrep -f loop-claude; then echo up; fi", "until ! pgrep -f \"chunk-pr merg\" || [ $SECONDS -gt 600 ]; do sleep 15; done", "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"])
|
||||
ending = ", or a pattern the command doesn't contain, such as `[c]hunk` for `chunk`"
|
||||
self.assertEqual(breaches("pgrep -f chunk-pr")[0].detail, "`chunk-pr` matches the command line that holds this `pgrep -f`, so `pgrep` finds the shell that runs the command; use `~/.claude/bin/wait-for <file> [<pattern>] --timeout <seconds>`, a `pgrep -x` on the process name" + ending)
|
||||
self.assertEqual(breaches("pkill -f chunk-pr")[0].detail, "`chunk-pr` matches the command line that holds this `pkill -f`, so `pkill` finds the shell that runs the command; use a `pkill -x` on the process name" + ending)
|
||||
|
||||
def test_an_endless_wait_names_its_loop_and_the_directory_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([breach.directory for breach in breaches("cd /w && until [ -s f ] && cd /x && true; do sleep 1; done")], ["/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'", "pkill --signal TERM --full '[c]hunk'", "pkill -KILL -f '[l]oop-claude'", "pkill -9 -f '[l]oop-claude'", "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), [])
|
||||
|
||||
def test_an_attribution_breaks_only_in_a_git_gh_tea_or_chunk_pr_command(self):
|
||||
self.assertEqual(checked(f"tea pr create --description '{TRAILER}'"), ["no-ai-attribution"])
|
||||
self.assertEqual(checked(f"~/.claude/bin/chunk-pr open 'Do it' '{TRAILER}'"), ["no-ai-attribution"])
|
||||
@@ -959,6 +996,21 @@ class Hook(unittest.TestCase):
|
||||
self.assertIn("Blocked by rule image-pin: ", ran.stderr)
|
||||
self.assertIn("`# rule-override image-pin: <reason>`", ran.stderr)
|
||||
|
||||
def test_a_monitor_command_is_checked_for_a_self_matching_pgrep_but_not_for_a_loop_its_timeout_ends(self):
|
||||
monitor = {"command": "pgrep -f chunk-pr", "description": "d", "timeout_ms": 60000}
|
||||
ran = hook({"cwd": self.repo, "tool_input": monitor, "tool_name": "Monitor"}, self.repo)
|
||||
self.assertEqual(ran.returncode, 2)
|
||||
self.assertIn("Blocked by rule endless-wait: ", ran.stderr)
|
||||
self.assertIn("`# rule-override endless-wait: <reason>` to the command", ran.stderr)
|
||||
looping = monitor | {"command": "until [ -s f ]; do sleep 15; done"}
|
||||
self.assertEqual(hook({"cwd": self.repo, "tool_input": looping, "tool_name": "Monitor"}, self.repo).returncode, 0)
|
||||
self.assertEqual(hook({"cwd": self.repo, "tool_input": looping | {"command": looping["command"] + " # x"}, "tool_name": "Bash"}, self.repo).returncode, 2)
|
||||
|
||||
def test_settings_hooks_a_monitor_call(self):
|
||||
settings = json.loads((HOOK.parent.parent / "settings.json").read_text())
|
||||
matchers = [entry["matcher"].split("|") for entry in settings["hooks"]["PreToolUse"] if "rule-hook" in entry["hooks"][0]["command"]]
|
||||
self.assertIn("Monitor", matchers[0])
|
||||
|
||||
def test_an_edit_of_a_fifo_or_a_device_finishes(self):
|
||||
fifo = f"{self.repo}/pipe"
|
||||
os.mkfifo(fifo)
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@
|
||||
"type": "command"
|
||||
}
|
||||
],
|
||||
"matcher": "Agent|Bash|Edit|Grep|MultiEdit|Read|Skill|Write"
|
||||
"matcher": "Agent|Bash|Edit|Grep|Monitor|MultiEdit|Read|Skill|Write"
|
||||
}
|
||||
],
|
||||
"SubagentStart": [
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
| 412 | 0.12.0 | 410, 411 | | **Print each chunk of an epic, running, parked with its gate and since when, or stopped, each human task and each open interrupt with `do-epic <key> --status`, and name a parked chunk's gate in its tmux window's name.** | 2 | 1 | 1 | 2 | 3 | 1 by 5 | 1.9 |
|
||||
| 414 | 0.12.0 | 410 | | **DM the human through the notifier when a human-task issue blocks the epic's next item, and poll until it closes.** | 2 | 2 | 2 | 4 | 3 | 1 by 5 | 1.9 |
|
||||
| 417 | 0.12.0 | 410 | | **Run do-epic end to end against a sandbox epic on a real Jira site with a command of its own, outside `run-tests`.** | 2 | 1 | 1 | 2 | 3 | 1 by 5 | 1.9 |
|
||||
| 421 | 0.12.0 | | | **Refuse in rule-hook a Bash or Monitor wait that has no end: a loop without a time or count cap, and a `pgrep -f` or `pkill -f` whose pattern the same command line contains.** | 2 | 2 | 3 | 5 | 3 | 1.5 by 4 | 1.3 |
|
||||
| 310 | 0.12.0 | | | **Compact a waiting worker's session shortly before its prompt cache expires, only when the human has not answered an interrupt by then.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3 | 0.9 |
|
||||
| 422 | 0.12.0 | 420 | | **Check every 5 minutes whether a tmux window of the loop looks stuck by other signs than a lingering worker, investigate it with a headless claude, and kill only the process the investigation names.** | 3 | 2 | 3 | 6 | 5 | 1.5 by 4 | 0.8 |
|
||||
| 365 | 0.13.0 | | | **Have `score-outcomes` read the finished and dropped items of a plan outside the checkout, from the project repo's history or from Jira's issue changelogs.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
|
||||
@@ -191,23 +190,6 @@ Touches:
|
||||
- `bin/do-epic-e2e`
|
||||
- `bin/do_epic/e2e/`
|
||||
|
||||
### 421. Refuse in rule-hook a Bash or Monitor wait that has no end: a loop without a time or count cap, and a `pgrep -f` or `pkill -f` whose pattern the same command line contains.
|
||||
|
||||
On 2026-11-18 a worker in the item 402 chunk started `until [ -s /tmp/merge-402.log ] && ! pgrep -f "chunk-pr merg"; do sleep 15; done` in the background. The `pgrep -f` pattern is part of the loop's own command line, so it matched itself and the loop never ended; the worker's `claude -p` waited on it for 95 minutes and its slot started no new chunk (item 420 ends such a worker; item 422 handles other stuck windows). A wait that cannot end is cheaper to refuse before it starts.
|
||||
|
||||
rule-hook refuses a Bash command, or a Monitor call, that starts a wait of either kind. A loop (`until`, `while`, `for`) that sleeps and has neither a time limit (`timeout`, a deadline compared with `date`) nor a bounded count (`for i in $(seq …)`); `~/.claude/bin/wait-for` always passes, since it takes `--timeout`. A `pgrep -f` or `pkill -f` whose pattern text also appears in the command line that holds it, quoted or not, so it can match its own shell. The refusal names which kind it found and says to use `wait-for <file> [<pattern>] --timeout <seconds>`, or a `pgrep -x` on the process name.
|
||||
|
||||
`settings.json` hooks only `Agent|Bash|Edit|Grep|MultiEdit|Read|Skill|Write`, so rule-hook never sees a Monitor call: add `Monitor` to that matcher, and have rule-hook read a Monitor call's command as it reads a Bash one. Claude Code 2.1.314 and later send Monitor-started commands to a PreToolUse hook; a hook's allow and updatedInput are ignored for them, so rule-hook can refuse but not rewrite (docs: code.claude.com/docs/en/hooks.md).
|
||||
|
||||
The test covers each kind refused, a bounded loop that passes, `wait-for` passing, and a `pgrep -f` on a pattern absent from the command passing. The rule's reason goes in rule-hook's rule table beside the other rules.
|
||||
|
||||
Touches:
|
||||
|
||||
- `bin/rule_hook/rules.py`: `RULES` (small)
|
||||
- `bin/rule_hook/endless_wait.py`
|
||||
- `bin/rule_hook/test_rule_hook.py`: `CommandBreaches` (small)
|
||||
- `settings.json`
|
||||
|
||||
### 310. Compact a waiting worker's session shortly before its prompt cache expires, only when the human has not answered an interrupt by then.
|
||||
|
||||
281 worker resumes after the 1-hour cache expired rewrote a whole context, $379 of the $9,154 measured from 2026-09-30 to 2026-11-11 (4.1%). A compaction while the cache is warm reads the context at a twentieth of the input price and leaves about 20k tokens to rewrite later.
|
||||
|
||||
Reference in New Issue
Block a user