Check the files a commit would commit against rule-hook's file rules, and sort .gitignore's allowlist block
CI / tests (pull_request) Failing after 2m2s

This commit is contained in:
2026-11-11 14:07:34 +01:00
parent 1fa03973a3
commit 3e289c95d9
11 changed files with 154 additions and 29 deletions
+2 -2
View File
@@ -25,9 +25,9 @@
!bin/branch_chunks/
!bin/branch_chunks/*.py
!bin/chunk-pr
!bin/chunk-preflight
!bin/chunk_pr/
!bin/chunk_pr/*.py
!bin/chunk-preflight
!bin/chunk_preflight/
!bin/chunk_preflight/*.py
!bin/claude_code/
@@ -50,12 +50,12 @@
!bin/larv_review/
!bin/larv_review/*.py
!bin/loop-claude
!bin/loop-inbox
!bin/loop_claude/
!bin/loop_claude/**/
!bin/loop_claude/**/*.py
!bin/loop_effects/
!bin/loop_effects/*.py
!bin/loop-inbox
!bin/loop_inbox/
!bin/loop_inbox/*.py
!bin/loop_state/
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- `rule-hook` now holds the files a `git commit` would commit to its file rules (`action-pin`, `image-pin`, `ignorefile-sorted`, `no-ai-attribution`), so a file a Bash command wrote is checked as an Edit or Write is. A `# rule-override` line in the file or the command still overrides a breach.
- `chunk-pr merge` now refuses while a scoring run the plan calls is unrecorded on the branch, and `larv-review needs-scoring-run` calls one after a release is cut with none.
## 0.7.0
+1 -1
View File
@@ -81,7 +81,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
When one fires, hand the hard part, edits included, to a subagent on the rung loop-claude's prompt names, one above yours. Open the subagent's prompt with the marker loop-claude's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung loop-claude's prompt names. Ask the human before going higher. Where loop-claude's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread.
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`~/.claude/bin/larv-review review-folder` prints it), and removes no image or file it did not create.
- Check `README.md` first for build, test, install, and codegen commands, and fix one that misbehaves in the same change. Refresh `README.md` whenever you change what it describes, keeping it true, not longer.
- Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest, a `docker run` line or a file a Bash command writes, pin a container image to its full patch version and a GitHub Action to a semver tag.
- Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest or a `docker run` line, pin a container image to its full patch version and a GitHub Action to a semver tag.
## Naming files & folders
- Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`.
+41
View File
@@ -0,0 +1,41 @@
import dataclasses
import posixpath
from failure import Failure
from rule_hook.file_text import read
from rule_hook.git import guarded_git
from rule_hook.rules import Breach, file_breaches
# settings.json gives rule-hook 30 seconds; a file past this size is no source file, and reading it would eat them.
MAX_BYTES = 1_000_000
def committed_file_breaches(directory: str) -> list[Breach]:
"""The breaches of file_breaches in the files a commit in directory's checkout would commit.
A file a Bash command wrote reaches no Edit or Write check, so the commit stands in for it. The files are those that differ from HEAD in the index or the work tree, or that are untracked and not ignored: the hook runs before a `git add` earlier in the same command, so the index alone would miss them. Deleted files and files that are no UTF-8 text have no added text. A breach carries its file's text, so a marker in the file overrides it, as in an Edit."""
top = guarded_git(directory, "rev-parse", "--show-toplevel")
if isinstance(top, Failure):
return []
changed = guarded_git(top, "diff", "-z", "--name-only", "--no-renames", "--diff-filter=d", "HEAD")
# A checkout with no commit has no HEAD: its index is what differs.
changed = guarded_git(top, "diff", "-z", "--name-only", "--cached", "--no-renames", "--diff-filter=d") if isinstance(changed, Failure) else changed
untracked = guarded_git(top, "ls-files", "-z", "--others", "--exclude-standard")
names = sorted({name for listing in (changed, untracked) if not isinstance(listing, Failure) for name in listing.split("\0") if name})
breaches = []
for name in names:
path = posixpath.join(top, name)
after = read(path) if size(path) <= MAX_BYTES else ""
before = guarded_git(top, "show", f"HEAD:{name}")
before = "" if isinstance(before, Failure) else before
known = set(before.splitlines())
added = "\n".join(line for line in after.splitlines() if line not in known)
breaches += [dataclasses.replace(breach, marked=after) for breach in file_breaches(path, before, added, after)] if added else []
return breaches
def size(path: str) -> int:
try:
return posixpath.getsize(path)
except OSError:
return 0
+12
View File
@@ -0,0 +1,12 @@
import os
import stat
def read(path: str) -> str:
"""path's text, or "" for anything but a regular file: a FIFO would hang the hook and a device such as /dev/zero would flood it."""
try:
# O_NONBLOCK opens a FIFO without waiting for a writer; fstat then judges the file opened, not one swapped in after a stat.
with open(os.open(path, os.O_RDONLY | os.O_NONBLOCK), encoding="utf-8") as opened:
return opened.read() if stat.S_ISREG(os.fstat(opened.fileno()).st_mode) else ""
except (OSError, UnicodeDecodeError):
return ""
+9 -13
View File
@@ -8,7 +8,10 @@ subagent. The rules:
{rules}
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked.
A file a Bash command writes, such as through `cat > Dockerfile`, is checked when a `git commit` would commit it, not
when written: the file rules (action-pin, image-pin, ignorefile-sorted, no-ai-attribution) hold each file that differs
from HEAD in the index or the work tree, or is untracked and not ignored, to the lines it adds. A `# rule-override` line
in that file or in the commit command overrides its breach.
A call overrides a rule with `# rule-override <rule>: <reason>`:
@@ -31,7 +34,6 @@ cannot read.
"""
import json
import os
import stat
import sys
import time
import typing
@@ -39,8 +41,10 @@ import typing
from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
from git_cli.git_command import commits
from rule_hook.committed_files import committed_file_breaches
from failure import Failure
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
from rule_hook.file_text import read
from rule_hook.repeat_read import read_breaches
from rule_hook.reviewer_report import report_breaches
from rule_hook.reviewer_rung import reviewer_breaches, skill_breaches
@@ -110,14 +114,6 @@ def answer(checked: Checked, what: str, now: float) -> int:
def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
simples = simple_commands(command, cwd, home)
return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in round_cap_breaches(commit) + todo_breaches(commit.directory)]
def read(path: str) -> str:
"""path's text, or "" for anything but a regular file: a FIFO would hang the hook and a device such as /dev/zero would flood it."""
try:
# O_NONBLOCK opens a FIFO without waiting for a writer; fstat then judges the file opened, not one swapped in after a stat.
with open(os.open(path, os.O_RDONLY | os.O_NONBLOCK), encoding="utf-8") as opened:
return opened.read() if stat.S_ISREG(os.fstat(opened.fileno()).st_mode) else ""
except (OSError, UnicodeDecodeError):
return ""
found = commits(simples, 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, home) + [breach for commit in found for breach in round_cap_breaches(commit) + todo_breaches(commit.directory)] + in_files
+6 -2
View File
@@ -104,6 +104,8 @@ class Breach:
detail: str
# The checkout whose log records an override of this breach.
directory: str
# Text beyond the call's own whose markers override this breach: the file a commit holds, as an Edit's text is for its file.
marked: str = ""
@dataclasses.dataclass(frozen=True)
@@ -124,7 +126,9 @@ def overrides(written: str) -> tuple[dict[str, str], list[str]]:
def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Checked:
granted, malformed = overrides(written)
blocking = [breach for breach in breaches if breach.rule not in granted]
# Each breach is overridden by the call's markers and by its own file's.
grants = [granted | overrides(breach.marked)[0] for breach in breaches]
blocking = [breach for breach, grant in zip(breaches, grants) if breach.rule not in grant]
messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else []
where = "the command" if bash else "the text you write, as a comment line"
for rule in sorted({breach.rule for breach in blocking}):
@@ -134,7 +138,7 @@ def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> C
continue
marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.")
return Checked(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
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], home: str) -> list[Breach]:
+64
View File
@@ -913,6 +913,70 @@ class TodoRankCheck(unittest.TestCase):
self.assertNotIn("own script", " ".join(reasons))
class CommittedFiles(unittest.TestCase):
"""A git commit holds the files it would commit to the file rules, as an Edit or Write of each would be."""
UNPINNED = "jobs:\n a:\n steps:\n - uses: actions/checkout@main\n"
def setUp(self):
self.repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", self.repo])
git(self.repo, "init", "-q", "-b", "main")
git(self.repo, "commit", "-q", "--allow-empty", "-m", "base")
def write(self, name: str, content: str) -> None:
path = pathlib.Path(self.repo, name)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
def commit(self, command: str = "git add -A && git commit -m x") -> subprocess.CompletedProcess:
return hook({"cwd": self.repo, "tool_input": {"command": command}, "tool_name": "Bash"}, self.repo)
def test_a_file_a_command_wrote_is_checked_at_the_commit(self):
self.write(".github/workflows/ci.yml", self.UNPINNED)
self.write("Dockerfile", "FROM node:24\n")
self.write(".gitignore", "b\na\n")
self.write("NOTES.md", "Co-Authored-" + "By: Claude <noreply@anthropic.com>\n")
ran = self.commit()
self.assertEqual(ran.returncode, 2)
for rule in ["action-pin", "image-pin", "ignorefile-sorted", "no-ai-attribution"]:
with self.subTest(rule):
self.assertIn(f"Blocked by rule {rule}: ", ran.stderr)
def test_a_staged_file_is_checked_and_a_clean_tree_passes(self):
self.assertEqual(self.commit().returncode, 0)
self.write(".github/workflows/ci.yml", self.UNPINNED)
git(self.repo, "add", "-A")
self.assertEqual(self.commit("git commit -m x").returncode, 2)
def test_a_breach_the_head_already_holds_is_left_alone(self):
self.write("Dockerfile", "FROM node:24\n")
self.write(".gitignore", "b\na\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
self.write("Dockerfile", "FROM node:24\nRUN true\n")
self.write(".gitignore", "b\na\n\n# more\nc\n")
self.assertEqual(self.commit().returncode, 0)
self.write("Dockerfile", "FROM node:24\nRUN true\nFROM node:25\n")
self.assertIn("image-pin: ", self.commit().stderr)
def test_a_marker_in_the_command_or_the_file_lets_the_commit_through(self):
self.write("Dockerfile", "FROM vendor/tool:2\n")
self.assertEqual(self.commit("git add -A && git commit -m x # rule-override image-pin: the vendor tags no patch versions").returncode, 0)
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n")
self.assertEqual(self.commit().returncode, 0)
def test_a_marker_in_another_file_overrides_nothing(self):
self.write("Dockerfile", "FROM vendor/tool:2\n")
self.write("NOTES.md", "# rule-override image-pin: quoted in a note\n")
self.assertIn("Blocked by rule image-pin: ", self.commit().stderr)
def test_an_untracked_ignored_or_binary_file_breaks_nothing(self):
self.write(".gitignore", "build/\n")
self.write("build/Dockerfile", "FROM node:24\n")
pathlib.Path(self.repo, "image.png").write_bytes(b"\xff\xfe\x00FROM node:24\n")
self.assertEqual(self.commit().returncode, 0)
class RuleNames(unittest.TestCase):
def test_every_rule_name_has_a_rule_and_every_rule_a_name(self):
self.assertEqual(set(RULES), set(typing.get_args(RuleName)))
+1 -1
View File
@@ -412,7 +412,7 @@ Valid while a model switch inside a session discards its prompt cache.
## rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides any rule but those `rule-hook --help` marks as taking none, and larv-review's overrides pass rules on each override before merge
2026-10-12, lilleman. Serves goals 1.2 and 1.3. Anthropic's best-practices page calls `CLAUDE.md` advisory and hooks deterministic, so a rule that must hold every time moves into `bin/rule-hook`, and `CLAUDE.md` keeps it only where the hook cannot check it. A Claude Code hook ties the check to one vendor ("Prefer the vendor-neutral option", `principles/technical-principles.md`), which is the target itself here: this repo configures Claude Code. What the tie buys: the hook blocks before a write lands, Edit and Write calls included, in every project with no per-repo install; a git `commit-msg` hook sees only commits, and CI sees them only after the push. The hook checks each write, so the agent fixes the line it just wrote; checking the staged diff at commit time would also cover files a Bash command writes, at the cost of later feedback. The marker's spelling was picked by a panel of three fresh readers, two to one. Each override is logged in the checkout's git directory, which is never pushed (goal 4). The plan had loop-claude's judge to rule on overrides inside a loop; lilleman approved larv-review's overrides pass in every run, because it rules before merge and an outrageous override still reaches the human through its ask. 2026-10-16, lilleman, answering plan item 166: no marker overrides `reviewer-rung`. 2026-11-04, lilleman: the title points at `rule-hook --help`, which lists every rule no marker overrides from the code, so the title can't drift from it; the comment above each in `bin/rule_hook/rules.py` says why. Valid while a PreToolUse hook that exits 2 blocks the call and hands its stderr to the model, and while an agent commits through Claude Code's Bash tool.
2026-10-12, lilleman. Serves goals 1.2 and 1.3. Anthropic's best-practices page calls `CLAUDE.md` advisory and hooks deterministic, so a rule that must hold every time moves into `bin/rule-hook`, and `CLAUDE.md` keeps it only where the hook cannot check it. A Claude Code hook ties the check to one vendor ("Prefer the vendor-neutral option", `principles/technical-principles.md`), which is the target itself here: this repo configures Claude Code. What the tie buys: the hook blocks before a write lands, Edit and Write calls included, in every project with no per-repo install; a git `commit-msg` hook sees only commits, and CI sees them only after the push. The hook checks each write, so the agent fixes the line it just wrote; a commit also holds the files it would commit to the file rules, since a file a Bash command writes reaches no write check; that feedback comes later, at the commit. The marker's spelling was picked by a panel of three fresh readers, two to one. Each override is logged in the checkout's git directory, which is never pushed (goal 4). The plan had loop-claude's judge to rule on overrides inside a loop; lilleman approved larv-review's overrides pass in every run, because it rules before merge and an outrageous override still reaches the human through its ask. 2026-10-16, lilleman, answering plan item 166: no marker overrides `reviewer-rung`. 2026-11-04, lilleman: the title points at `rule-hook --help`, which lists every rule no marker overrides from the code, so the title can't drift from it; the comment above each in `bin/rule_hook/rules.py` says why. Valid while a PreToolUse hook that exits 2 blocks the call and hands its stderr to the model, and while an agent commits through Claude Code's Bash tool.
## rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
+17
View File
@@ -1536,3 +1536,20 @@ Read most (opens and searches):
Read most (opens and searches):
- `todo.md` 1
## Reading cost, chunk 4a0a495957fb, finished 2026-11-11T13:02:21Z
146184 new input tokens before the first commit.
Read most (opens and searches):
- `bin/larv_review/main.py` 9
- `bin/larv_review/plan.py` 5
- `bin/larv_review/test_larv_review.py` 5
- `bin/chunk_pr/test_chunk_pr.py` 4
- `bin/larv_review/history_commands.py` 4
- `bin/review_rules/comprehension_history.py` 4
- `bin/chunk_pr/main.py` 3
- `bin/chunk_preflight/main.py` 3
- `bin/release_plan/release_standing.py` 3
- `CHANGELOG.md` 2
-10
View File
@@ -12,7 +12,6 @@
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 294 | 0.8.0 | | | **Check the files a commit stages against rule-hook's file rules, so a file a Bash command wrote is held to them as an Edit or Write is.** | 2 | 2 | 3 | 5 | 4 | 1.3 by 5 | 5.2 |
| 297 | 0.8.0 | | | **Have loop-claude compute the judge's taken-in items, release-ready and escalation fields from `chunk-preflight`, git and the worker's structured lines, and leave the judge only the verdict kind.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 2, code health by 2 | 3.7 |
| 302 | 0.8.0 | | | **Call a scoring run for an item whose tagline makes the comprehension floor its target, and not for one that only names the floor, such as in a quoted decision title.** | 2 | 2 | 3 | 5 | 3 | code health by 2 | 3.6 |
| 293 | 0.8.0 | | | **Run mutation tests on a chunk's changed lines in the worker's pre-review gate, through one command that picks the tool by language, and hand stability-reviewer the surviving mutants.** | 3 | 2 | 3 | 6 | 5 | 1.1 by 5, 1.4 by 4, 1.5 by 2 | 2.8 |
@@ -48,7 +47,6 @@
| 187 | 0.9.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 1.2 |
| 266 | 0.9.0 | | | **Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3 | 1.2 |
| 181 | 0.9.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
| 192 | 0.9.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
| 193 | 0.9.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 1.0 |
| 194 | 0.9.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
| 202 | 0.9.0 | | | **Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 1.0 |
@@ -60,10 +58,6 @@
## Details
### 294. Check the files a commit stages against rule-hook's file rules, so a file a Bash command wrote is held to them as an Edit or Write is.
From 2026-11-08 to 2026-11-10, workers in other projects wrote 1,266 files through Bash (a python heredoc, `sed -i`, `cat >`) against 260 through Edit and Write, and `rule-hook --help` says it doesn't check a file a Bash command writes. So `action-pin`, `image-pin`, `ignorefile-sorted` and the attribution check miss most edits. rule-hook already checks at `git commit` for `todo-rank-check`, so checking staged files there follows a pattern the repo has. Ship item 192 in the same chunk: its unsorted `.gitignore` block is one symptom of this gap.
### 297. Have loop-claude compute the judge's taken-in items, release-ready and escalation fields from `chunk-preflight`, git and the worker's structured lines, and leave the judge only the verdict kind.
`bin/loop_claude/cycle/judge.py` already checks quotes in code (`quotes_checked`, `grounded`, `re_ask_checked`). The `Reply` fields `items_taken_in`, `release_ready` and `escalation` state facts the plan and git already hold, so code can derive them with certainty, and the judge's prompt shrinks to what needs judgement. Before switching, recompute each field for the 668 archived verdicts offline and count where code and judge disagree; read each disagreement and keep the judge for a field where code is wrong. Seats found `quotes_checked` hard to read (PR #397's scoring run: the misquote rule is split across `judge.py` and `escalation_mark.py`); make it easier to read where the change touches it.
@@ -285,10 +279,6 @@ The archive holds 277 chunk folders under `home/lilleman/.claude`, from 2026-09-
`bin/loop_claude/test_loop_claude.py`'s `test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step` builds its expected prompt from `prompts.rungs_held`, the code under test, so a bug there passes it. The technical principles' test bullet bans that shape. Assert the new rung and one review launch as literals, as the typed answer's step-up test does. Raised by the principles audit of PR #308.
### 192. Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.
Found by review of PR #317. The block, `.gitignore:17-142` on 2026-11-10, is out of order in several places: `!bin/chunk-preflight` sits below `!bin/chunk_pr/`, and `!bin/loop-inbox` below `!bin/loop_claude/`, though `-` sorts before `_`. `LC_ALL=C sort -c` on the block names the first one. `ignore_breaches` in `bin/rule_hook/rules.py` skips a block that was already unsorted before an edit, so while this one stays unsorted no later edit to it is checked. The unsorted block breaches the technical principle "Deterministic order wherever order carries no meaning".
### 193. Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.
Found by review of PR #317. `bin/release_plan/ranking.py`'s `readme_goals` writes `typing.cast(Mark, mark or None)`, which asserts the type `goal_weights` branches on without checking it: a mark added to the regex reaches `goal_weights` as a value `Mark` lacks. mypy does not read the regex, so no lookup lets it catch that. Replace the cast with a lookup typed `dict[str, Mark]`, from each mark the regex captures, and `""` for none, to its `Mark` value. A mark added to the regex but not the lookup then raises `KeyError` at run time, and a value added to the lookup but not `Mark` fails mypy.