Merge remote-tracking branch 'origin/main' into item-410
CI / tests (pull_request) Has been cancelled

# Conflicts:
#	docs/reading-cost.md
#	todo.md
This commit is contained in:
2026-11-18 22:51:13 +01:00
22 changed files with 357 additions and 88 deletions
+3 -2
View File
@@ -302,8 +302,9 @@ class ChunkPreflightTool(unittest.TestCase):
def test_reads_origin_as_last_fetched_where_the_fetch_stalls_and_still_states_the_other_facts(self):
repo = Repo(self)
repo.stub_git(f'"fetch --quiet origin") exec {shutil.which("sleep")} 10;;')
done = repo.preflight("--worktree", CHUNK_PREFLIGHT_TIMEOUT="1")
repo.stub_git(f'"fetch --quiet origin") exec {shutil.which("sleep")} 30;;')
# The timeout also stops `reading-cost`, so it is set well above the seconds `reading-cost` takes on a loaded runner.
done = repo.preflight("--worktree", CHUNK_PREFLIGHT_TIMEOUT="5")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("as last fetched", done.stdout)
self.assertIn("item 3, L 2, E + I 5", done.stdout)
+3 -2
View File
@@ -130,7 +130,7 @@ prints it, such as stability. It prints the header of the prompt that launches t
in its next round: the pass and round, the branch's open pull request at its pushed head, the
worktree and branch, the merge base of HEAD and the default branch, and the paths of the reviewer's
report, the branch diff, the folders of technical principles and review standards the project's
config sets, the goals and the plan and, for architecture and stability, the places. For a reviewer whose
config sets, the files of coding conventions where it lists any, the goals and the plan and, for architecture and stability, the places. For a reviewer whose
definition under ~/.claude/agents/ has `omitClaudeMd: true`, it then names the file that holds the
project principles and decision titles, where the project keeps one. It writes the diff, from
that base to HEAD, into the chunk's review folder as branch-<short HEAD>.diff, writes what
@@ -138,7 +138,8 @@ places prints into places.md, and lists the plan's items into
plan.md, whatever store holds the plan; a file whose text is unchanged is left as it is. With --rerun, the
header names the report of a relaunch one rung up, in the same round, and the report that asked for
it. It exits 1 when the pass takes no more rounds, when `project-config` fails in the checkout, when
the principles or standards folder is not a folder with a file in it, or, with --rerun, when the
the principles or standards folder is not a folder with a file in it, when a file the config lists
in `coding-conventions` is missing, or, with --rerun, when the
report that asked is missing.
round-title takes a pass as reviewer-header does. It prints how the commit that answers the pass's
+8 -1
View File
@@ -44,6 +44,8 @@ class Launch:
decisions: pathlib.Path
# The language the project's config names for its prose.
language: str
# The files of the team's coding conventions, where the project's config names any.
conventions: tuple[pathlib.Path, ...] = ()
def asked(self) -> pathlib.Path:
"""The round's report, which asks for the rerun where there is one."""
@@ -61,6 +63,7 @@ class Launch:
f"Diff: {self.diff}",
f"Technical principles: {self.principles}",
f"Review standards: {self.standards}",
*([f"Coding conventions: {', '.join(str(file) for file in self.conventions)}"] if self.conventions else []),
f"Goals and audience: {self.goals}",
f"Plan: {self.plan}",
f"Prose language: {self.language}.",
@@ -104,6 +107,10 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -
empty = next((setting for setting in ("principles", "standards") if not config.paths[setting].is_dir() or not any(config.paths[setting].iterdir())), None)
if empty is not None:
return Failure(f"{config.paths[empty]} is not a folder with a file in it; {config.folder / 'config.toml'} sets it as `{empty}`")
# A reviewer told to read a file that isn't there would review without the team's rules, as with an empty principles folder.
absent = next((file for file in config.coding_conventions if not file.is_file()), None)
if absent is not None:
return Failure(f"{absent} is not a file; {config.folder / 'config.toml'} sets it in `coding-conventions`")
decisions = local_file(store(config, "decisions"), folder / "decisions.md")
if isinstance(decisions, Failure):
return decisions
@@ -111,7 +118,7 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -
goals = local_file(goals_store(config), folder / "goals.md")
if isinstance(goals, Failure):
return goals
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, standards, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language)
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, standards, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language, config.coding_conventions)
if rerun and not launch.asked().exists():
return Failure(f"no report asked for a rerun of {pass_}'s round {round_}: {launch.asked()} is missing; relaunch before you commit the round's answers")
written = write_inputs(launch, base, home, plan_listing(plan_store(config)))
+13
View File
@@ -1304,6 +1304,19 @@ class LarvReviewTool(unittest.TestCase):
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn(f"{folder} is not a folder with a file in it; {self.config} sets it as `{setting}`", ran.stderr)
def test_reviewer_header_names_the_coding_conventions_only_where_the_projects_config_sets_them(self):
self.assertIsNone(self.header_line("Coding conventions:", "prose"))
(self.checkout / "CONVENTIONS.md").write_text("# Conventions\n")
(self.config.parent / "style.md").write_text("# Style\n")
self.config.write_text(PROJECT_CONFIG + 'coding-conventions = ["checkout:CONVENTIONS.md", "folder:style.md"]\n')
self.assertEqual(self.header_line("Coding conventions:", "prose"), f"Coding conventions: {self.checkout}/CONVENTIONS.md, {self.config.parent}/style.md")
def test_reviewer_header_fails_where_a_coding_conventions_file_is_missing(self):
self.config.write_text(PROJECT_CONFIG + 'coding-conventions = ["checkout:CONVENTIONS.md"]\n')
ran = self.run_tool("reviewer-header", "prose")
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn(f"{self.checkout}/CONVENTIONS.md is not a file; {self.config} sets it in `coding-conventions`", ran.stderr)
def test_reviewer_header_gives_the_architect_the_places(self):
folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj"
self.assertEqual(self.header_line("Places:", "architecture"), f"Places: {folder}/places.md")
+14 -4
View File
@@ -77,6 +77,13 @@ a tool that needs one fails naming the setting. It is printed with the others on
where `touch-predictions record` appends what each chunk was predicted to touch beside what it touched.
Left out, the project keeps no such record. It is printed with the others only where it is set.
`coding-conventions` is an optional setting, a list of paths spelt as the others are: the files in
which the project's team wrote its own coding conventions, such as
`coding-conventions = ["checkout:CONVENTIONS.md"]`. Each reviewer agent larv-review launches reads
them beside the principles and the standards, and the team's rule wins where they conflict. `project-config coding-conventions`
prints one path a line. Left out, the reviewers read no such file. It is printed with the others only
where it is set.
`notifier` is an optional setting, "mattermost" or "slack": the service that sends loop-claude's DMs and
`notify`'s messages to the human. Setting it requires `env-file`, which holds that service's keys;
`notify --help` names them. Left out, the project gets no DMs. It is printed with the others only where it
@@ -134,18 +141,18 @@ The chunk for the issue ABC-123 is then on the branch ABC-123, in the worktree <
and its commits and pull request are titled "ABC-123 - …".
Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a
setting, names an unknown one, misspells a path, a language or a template, sets `wait-for-approval` or
setting, names an unknown one, misspells a path, a language or a template, sets `coding-conventions` to anything but a list of paths, sets `wait-for-approval` or
`tooling-on-host` to anything but true or false, sets `notifier` to anything but mattermost or slack or
without `env-file`, sets `jira-finish-transition` or `jira-finish-status` to anything but a name, without the other or
without a `plan` in Jira, names a Jira `plan` and leaves out `jira-score-formula` or `jira-score-bar`, sets
one of those two without a `plan` in Jira, sets the formula to one that doesn't parse or the bar to anything
but a number, sets `readability-floor` to anything but a number
from 1 to 10, or sets `parallel-chunks` to anything but a whole number of 1 or more, and where `env-file`, `jira-finish-transition`, `jira-finish-status`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
from 1 to 10, or sets `parallel-chunks` to anything but a whole number of 1 or more, and where `coding-conventions`, `env-file`, `jira-finish-transition`, `jira-finish-status`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
"""
import pathlib
import sys
from project_config.settings import CONFIG, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, OPTIONAL, ProjectConfig, SCALARS, SETTINGS, Unnamed
from project_config.settings import CODING_CONVENTIONS, CONFIG, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, OPTIONAL, ProjectConfig, SCALARS, SETTINGS, Unnamed
from failure import Failure
from git_cli.git_repo import git, Git
from project_config import templates
@@ -165,7 +172,10 @@ def main(argv: list[str]) -> int:
# A one-value setting prints its value, its default where the config leaves it out; one without a default, as `notifier`, prints only where set.
scalars = {scalar.name: scalar.shown(value) for scalar in SCALARS if (value := getattr(config, scalar.field)) is not None}
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({JIRA_SCORE_FORMULA: config.jira_scoring.formula, JIRA_SCORE_BAR: f"{config.jira_scoring.bar:g}"} if config.jira_scoring else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
shown = paths | scalars
# The listing names the conventions on one line; asked for alone, they print one path a line, for a script to read.
conventions = [str(path) for path in config.coding_conventions]
paths |= {CODING_CONVENTIONS: ", ".join(conventions)} if conventions else {}
shown = paths | scalars | ({CODING_CONVENTIONS: "\n".join(conventions)} if conventions else {})
if argv and argv[0] not in shown:
print(f"{config.folder / CONFIG} sets no `{argv[0]}`", file=sys.stderr)
return 1
+16 -2
View File
@@ -48,6 +48,8 @@ PULL_REQUEST_TITLE = "pull-request-title"
BRANCH = "branch"
# An optional path setting: main's help says what it places.
TOUCH_PREDICTIONS = "touch-predictions"
# An optional setting: a list of paths, each spelt as SPELLING says, to the files that hold the team's own coding conventions, which each reviewer agent larv-review launches reads. Three readers, seated as the human who writes a client's config, picked the spelling 2-1 from four candidates, over a bare `conventions`, which they confused with `principles` and `working-rules`.
CODING_CONVENTIONS = "coding-conventions"
# Two optional settings, each a name, set together and only where `plan` names a Jira epic: the name of the workflow transition that finishes an item, and of the status it must lead to. Three readers, seated as the human who writes a client's config, picked the spelling from four candidates: two flat keys, as the other settings are, with a prefix that says what they apply to.
JIRA_FINISH_TRANSITION = "jira-finish-transition"
JIRA_FINISH_STATUS = "jira-finish-status"
@@ -129,6 +131,8 @@ class ProjectConfig:
commit_title: str = templates.TITLE
pull_request_title: str = templates.TITLE
branch: str = templates.BRANCH
# The config's `coding-conventions`, in its order; empty where it sets none.
coding_conventions: tuple[pathlib.Path, ...] = ()
# The epic whose child issues are the plan, where the config's `plan` names one.
epic: Epic | None = None
# The epic whose description holds the goals and audience, where the config's `goals-and-audience` names one.
@@ -196,6 +200,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
paths = {name: placed(values[name], top, file.parent, home) for name in (*SETTINGS, TOUCH_PREDICTIONS) if name in values}
epics = {name: epic_of(values.get(name)) for name in EPIC_SPELLINGS}
pages = {name: page for name in RECORDS if (page := page_of(values.get(name)))}
conventions = conventions_of(values.get(CODING_CONVENTIONS, []), top, file.parent, home)
env_file = anywhere(values.get(ENV_FILE), home)
misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent))
scalars = {scalar: scalar.read(values[scalar.name]) for scalar in SCALARS if scalar.name in values}
@@ -210,6 +215,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {EPIC_SPELLINGS[name]}" for name in EPIC_SPELLINGS if name in values and paths[name] is None and epics[name] is None),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {PAGE_SPELLING}" for name in RECORDS if name in values and paths[name] is None and name not in pages),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
*([f"`{CODING_CONVENTIONS}` is {values[CODING_CONVENTIONS]!r}, not a list of paths, each {SPELLING}"] if conventions is None else []),
# Each setting that reaches a service needs the file that holds its credentials.
*(f"`{name}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
*(f"`{name}` names a Confluence page, so `{ENV_FILE}` must name the file that holds its credentials" for name in pages if ENV_FILE not in values),
@@ -228,7 +234,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
# faults names a formula or bar a plan in Jira lacks or misspells.
assert scoring is not None or not epics["plan"]
defaulted = ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, epic=epics["plan"], goals_epic=epics["goals-and-audience"], jira_finish=Finish(*finish) if finish else None, jira_scoring=scoring, pages=pages)
defaulted = ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, epic=epics["plan"], goals_epic=epics["goals-and-audience"], jira_finish=Finish(*finish) if finish else None, jira_scoring=scoring, pages=pages, coding_conventions=conventions or ())
return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()})
@@ -332,7 +338,7 @@ SCALARS = (
Scalar(PULL_REQUEST_TITLE, "pull_request_title", text_read(templates.title_fault)),
Scalar(BRANCH, "branch", text_read(templates.branch_fault)),
)
OPTIONAL = tuple(sorted((ENV_FILE, TOUCH_PREDICTIONS, *JIRA_PLAN_ONLY, *(scalar.name for scalar in SCALARS))))
OPTIONAL = tuple(sorted((CODING_CONVENTIONS, ENV_FILE, TOUCH_PREDICTIONS, *JIRA_PLAN_ONLY, *(scalar.name for scalar in SCALARS))))
def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool:
@@ -406,6 +412,14 @@ def placed(value: object, top: pathlib.Path, folder: pathlib.Path, home: pathlib
return anywhere(value, home)
def conventions_of(value: object, top: pathlib.Path, folder: pathlib.Path, home: pathlib.Path) -> tuple[pathlib.Path, ...] | None:
"""The paths a `coding-conventions` value lists, or None where it is not a list of paths that `placed` can place."""
if not isinstance(value, list):
return None
paths = tuple(path for listed in value if (path := placed(listed, top, folder, home)))
return paths if len(paths) == len(value) else None
def anywhere(value: object, home: pathlib.Path) -> pathlib.Path | None:
if isinstance(value, str) and value.startswith("~/"):
return home / value.removeprefix("~/")
+28 -1
View File
@@ -410,6 +410,23 @@ class LoadTest(ConfigCase):
(folder / "config.toml").write_text(CLIENT + 'touch-predictions = "docs/touch-predictions.md"\n', encoding="utf-8")
self.assertIn("`touch-predictions` is 'docs/touch-predictions.md', not \"checkout:<path>\"", self.failure())
def test_coding_conventions_is_an_optional_list_of_paths_spelt_as_the_others_are(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig)
self.assertEqual(left_out.coding_conventions, ())
(folder / "config.toml").write_text(CLIENT + 'coding-conventions = ["checkout:CONVENTIONS.md", "folder:style.md", "~/shared/php.md"]\n', encoding="utf-8")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig)
self.assertEqual(found.coding_conventions, (self.checkout / "CONVENTIONS.md", folder / "style.md", self.home / "shared/php.md"))
def test_coding_conventions_fails_where_it_is_not_a_list_or_one_of_its_paths_is_misspelt(self) -> None:
folder = self.write("acme", CLIENT)
for value, shown in (('"checkout:CONVENTIONS.md"', "'checkout:CONVENTIONS.md'"), ('["checkout:CONVENTIONS.md", "docs/style.md"]', "['checkout:CONVENTIONS.md', 'docs/style.md']"), ("[7]", "[7]")):
with self.subTest(value=value):
(folder / "config.toml").write_text(CLIENT + f"coding-conventions = {value}\n", encoding="utf-8")
self.assertIn(f"`coding-conventions` is {shown}, not a list of paths, each \"checkout:<path>\"", self.failure())
def test_wait_for_approval_is_an_optional_boolean_that_is_false_where_left_out(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
@@ -526,7 +543,7 @@ class LoadTest(ConfigCase):
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, jira-finish-status, jira-finish-transition, jira-score-bar, jira-score-formula, language, notifier, parallel-chunks, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, coding-conventions, commit-title, env-file, jira-finish-status, jira-finish-transition, jira-score-bar, jira-score-formula, language, notifier, parallel-chunks, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
self.write("acme", CLIENT)
@@ -660,6 +677,16 @@ class ToolTest(ConfigCase):
one = self.run_tool("changelog", cwd=self.checkout / "src")
self.assertEqual((one.returncode, one.stdout), (0, f"{self.checkout}/CHANGELOG.md\n"))
def test_prints_the_coding_conventions_one_path_a_line_where_the_config_sets_them(self) -> None:
folder = self.write("acme", CLIENT)
unset = self.run_tool("coding-conventions")
self.assertEqual((unset.returncode, unset.stdout, unset.stderr), (1, "", f"{folder / 'config.toml'} sets no `coding-conventions`\n"))
self.assertNotIn("coding-conventions", self.run_tool().stdout)
(folder / "config.toml").write_text(CLIENT + 'coding-conventions = ["checkout:CONVENTIONS.md", "folder:style.md"]\n')
one = self.run_tool("coding-conventions")
self.assertEqual((one.returncode, one.stdout), (0, f"{self.checkout}/CONVENTIONS.md\n{folder}/style.md\n"))
self.assertIn(f"coding-conventions: {self.checkout}/CONVENTIONS.md, {folder}/style.md\n", self.run_tool().stdout)
def test_prints_the_env_file_where_the_config_sets_one_and_fails_asking_for_it_where_it_does_not(self) -> None:
folder = self.write("acme", CLIENT)
unset = self.run_tool("env-file")
+122
View File
@@ -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
View File
@@ -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]:
+9 -2
View File
@@ -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))
+52
View File
@@ -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)