diff --git a/CHANGELOG.md b/CHANGELOG.md index fef99718..65f7bf0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 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`. - do-epic splits an epic item that changes several repos into one Jira sub-task per repo, each labelled `repo:`, with a headless claude call predicting the repos from the code; the item is marked `split-by-repo` and counts as done once every sub-task is, and an issue a person filed gets a comment for the team in the epic's language. The epic backends gain `comment`, in the Jira backend and the in-memory one. diff --git a/CLAUDE.md b/CLAUDE.md index 9687f715..7c4a0645 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,12 +18,12 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **Ask, don't guess.** Three choices are always the human's: a goal; a release, meaning the items planned into it and when it is cut; and a change to loop-claude's routing ladder, its rungs included. Any other rule that asks the human's approval reserves that choice too. Ask about a reserved choice. For any other choice, first check whether the goals already answer it. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Otherwise take the option you would recommend, and record it with its reason: in the item's detail, or, where it governs later work, as the next sentence says. A recommendation you can give a reason for is not a guess. Ask only where you have no recommendation. Write every answer once, where it belongs, never only in chat: a goal in the goals file, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the goals file, and record as a choice only what the goal leaves open. - **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the goals file's `## Audience`, picks it. - **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. Take its expected values from the item, never from the code. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file in the principles folder the project's config sets (`~/.claude/bin/project-config principles` prints it) only when the item changes it, a finding or a record you write names it, or you decline a finding. -- **Change the setup for each reasonable fix an outside reviewer asked for on a PR.** An outside reviewer is a forge's auto-reviewer or a human, not one of larv-review's reviewer agents. When you fix a comment of theirs, ask why our review didn't catch the fault first, and change the setup so it would; a fix that only answers the comment leaves the same gap open for the next chunk. Put the change in the first place that fits: - 1. claude-config's core: the reviewers' agents, `larv-review`, the hooks and tools, so every project gains. - 2. claude-config's technical principles or review standards, where a rule was missing or too vague. - 3. The project's own settings, principles folder or `AGENTS.md`, only where the gap is that project's alone. A client repo's `AGENTS.md` changes by a proposal of its own, per "A client project's `CLAUDE.md` and `AGENTS.md`" above. +- **Change the setup for each finding an outside reviewer raises on a PR, deterministic tools first.** An outside reviewer is a forge's auto-reviewer or a human, not one of larv-review's reviewer agents. For each finding of theirs, whether you fix it or decline it, ask why our review didn't raise it first, and change the setup so it would; a fix that only answers the comment leaves the same gap open for the next chunk. Put the change in the first place that fits: + 1. A deterministic tool that would have caught it, such as a rule-hook rule, a gate check, a linter setting or `mutate-changes`: a tool catches the fault every time, and a reviewer only when it notices. + 2. A technical principle or a review standard, where a rule was missing or too vague: in claude-config's files, or in the project's own principles folder. + 3. Anything else: the reviewers' agents, `larv-review`'s text, or the project's own settings or `AGENTS.md`. A client repo's `AGENTS.md` changes by a proposal of its own, per "A client project's `CLAUDE.md` and `AGENTS.md`" above. - In claude-config, the change is a fix of the chunk. In another project, places 1 and 2 are an item in claude-config's plan: start a worktree of claude-config off `origin/main`, run `todo-item add` in it, commit the plan file, and ship it as a pull request of its own with `chunk-pr`, since claude-config's default branch may not take a direct push. Describe the gap without the client's name, code or comment text. File a change too big for the chunk as its own item. Where no place holds the gap, say so in the chunk's summary rather than inventing a change. + Change claude-config's files where every project gains, and the project's own only where the gap is that project's alone. In claude-config, the change is a fix of the chunk. In another project, a change to the project's own files is a fix of the chunk too, and a change to claude-config's is an item in claude-config's plan: start a worktree of claude-config off `origin/main`, run `todo-item add` in it, commit the plan file, and ship it as a pull request of its own with `chunk-pr`, since claude-config's default branch may not take a direct push. Describe the gap without the client's name, code or comment text. File a change too big for the chunk as its own item. Where no setup gap caused the finding, as when the finding is wrong, say so in the chunk's summary rather than inventing a change. - **Remove a finished item from the plan, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. `~/.claude/bin/todo-item finish ` removes the item with its detail, and adds the bullet you pass with `--changelog `; it refuses while a decision cites the item. A plan kept in Jira takes no bullet, since the issues' history is its changelog: `finish` there refuses `--changelog`. A chunk finishes its items as it merges, through `chunk-pr merge --finish `, which takes the same flags (`larv-review` §5). - **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision. - **Open each plan item or ticket with a bold one-sentence tagline**, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and doesn't say anything about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`. diff --git a/README.md b/README.md index 0ae5c3f8..1da63f00 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,8 @@ A project may also set `env-file`, the file of `KEY=value` credentials its tools A project may also set `touch-predictions`, a path spelt as `changelog`'s is, such as `touch-predictions = "checkout:docs/touch-predictions.md"`. `touch-predictions record` appends each chunk's predicted files and parts there, beside those it touched. A project that leaves it out keeps no such record. +A project whose team wrote its own coding conventions lists the files in `coding-conventions`, each spelt as `principles` is, 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. + A project may also set `notifier` to `"mattermost"` or `"slack"`, the service that sends loop-claude's DMs. The `env-file` then holds that service's keys. A project that sets none gets no DMs, whatever its env file holds. `project-config notifier` prints the setting. A project's config may set four more things, each optional, as `project-config --help` describes. `language` names the language its owners write in, where that isn't English: the worker writes the project's prose in it, and the prose reviewer judges the prose in it. `commit-title`, `pull-request-title` and `branch` are templates for a project that titles and names these in another way than `CLAUDE.md` → "Git, commits, and PRs" says. `chunk-preflight` names the branch and the worktree by the `branch` template. On a branch that fits it, rule-hook refuses a commit, and `chunk-pr` a pull request, whose title doesn't fit its template; on any other branch, such as a release review's, a title is the summary alone. A tool that reads a commit title, such as a round's `Answer round :`, reads the template's `{summary}`: it tries `commit-title`, then `pull-request-title`, since a squash merge titles the commit as the pull request, then takes the title whole. While a project's config holds a fault, rule-hook refuses every commit there, and the tools that read its titles fail naming the fault. @@ -193,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/agents/product-owner-reviewer.md b/agents/product-owner-reviewer.md index 48051dc1..17e9ca32 100644 --- a/agents/product-owner-reviewer.md +++ b/agents/product-owner-reviewer.md @@ -47,7 +47,7 @@ Before anything else, **read the technical principles** in the folder your promp ## Your Output Format -Report only a defect a persona hits; a requirement that the change breaks, of the plan in the file your prompt's `Plan:` line names, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); or a breach of a technical principle. Friction that is none of these is not a finding. +Report only a defect a persona hits; a requirement that the change breaks, of the plan in the file your prompt's `Plan:` line names, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); or a breach of a technical principle, or of a coding convention, which counts as one. Friction that is none of these is not a finding. Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict: diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 0f34b3e7..6148799b 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -89,6 +89,7 @@ Catch behavior that is unclear or under-specified — "building in ambiguousness - Are consumers idempotent under at-least-once delivery (webhooks, queue retries, double-submit)? Where a duplicate would double-charge or double-send, is there an idempotency key or dedup? - Do DB constraints (NOT NULL, unique, FK) mirror what the code assumes, so bad data cannot arrive via another path? - New column on an existing table: what do existing rows contain — is null/default handled or backfilled? +- Where the change stores a value differently, by escaping, converting or growing it: does the longest value it can now write still fit the column, counted as stored? Does every search, filter and comparison on the column still find what users type? Escaped text takes more room than the input's limit allows for, and a `LIKE` on an escaped column no longer matches an apostrophe. ### 8. Resources & Performance Under Production Data Works-on-fixtures, dies-on-volume is a stability bug. @@ -126,12 +127,13 @@ Every PR gets at least this sweep. - Were tests and implementation changed together in a way that could mask a regression — e.g. an assertion weakened to make a test pass? Flag it; these should be separate changes. - Does each test earn its keep, as the technical principles' test bullet says? Look at where its expected values come from, what it asserts, what it mocks, what wording it pins, whether another test already pins the behaviour, and whether it sleeps or reads the wall clock. - Does a test decide at run time whether to check anything, by a conditional skip, early return or catch around its assertions, as the technical principles' test bullet forbids? Flag it. +- Does a test that runs on a shared environment hold the rules for such a test in the technical principles' "Compose, do not entangle" → "Tests and tooling"? Does the test that covers a seam to a service the team runs mock that service, which the test bullet's "Never mock a service your own team runs" forbids? - Are there untestable side effects that should be refactored? ## Output Format -Report only a defect; a requirement that the change breaks, of the plan in the file your prompt's `Plan:` line names, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); a breach of a technical principle; and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out. +Report only a defect; a requirement that the change breaks, of the plan in the file your prompt's `Plan:` line names, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); a breach of a technical principle, or of a coding convention, which counts as one; and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out. Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis, mutation — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with: - **Location**: File and line/function diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 545cede4..f94dfb76 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -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) diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index 0080985b..00e6a1ee 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -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-.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 diff --git a/bin/larv_review/reviewer_header.py b/bin/larv_review/reviewer_header.py index 48e3258a..d565302b 100644 --- a/bin/larv_review/reviewer_header.py +++ b/bin/larv_review/reviewer_header.py @@ -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))) diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index b3665980..c0126123 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -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") diff --git a/bin/project_config/main.py b/bin/project_config/main.py index 9971a2a4..05b7ad15 100644 --- a/bin/project_config/main.py +++ b/bin/project_config/main.py @@ -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 diff --git a/bin/project_config/settings.py b/bin/project_config/settings.py index c61f6e01..f7351e9f 100644 --- a/bin/project_config/settings.py +++ b/bin/project_config/settings.py @@ -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("~/") diff --git a/bin/project_config/test_project_config.py b/bin/project_config/test_project_config.py index 51ead264..6bec16d9 100644 --- a/bin/project_config/test_project_config.py +++ b/bin/project_config/test_project_config.py @@ -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:\"", 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:\"", 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") 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