claude-dev-env 8.114.8 → 8.114.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/.agents/skills/build-eval/reference/context-budget.md +2 -0
  2. package/hooks/blocking/final_reply_gate.py +4 -3
  3. package/hooks/blocking/merge_review_gate.py +98 -1
  4. package/hooks/blocking/owned_pr_merge_stop_gate.py +50 -20
  5. package/hooks/blocking/reply_length_gate.py +52 -10
  6. package/hooks/blocking/test_final_reply_gate.py +136 -0
  7. package/hooks/blocking/test_merge_review_gate.py +48 -0
  8. package/hooks/blocking/test_owned_pr_merge_stop_gate.py +97 -6
  9. package/hooks/blocking/test_reply_length_gate.py +39 -0
  10. package/hooks/context_budget/model.py +3 -0
  11. package/hooks/context_budget/policy_changes.py +54 -5
  12. package/hooks/context_budget/policy_file.py +1 -0
  13. package/hooks/context_budget/tests/test_model.py +1 -0
  14. package/hooks/context_budget/tests/test_policy_changes.py +121 -1
  15. package/hooks/context_budget/tests/test_policy_file.py +11 -0
  16. package/hooks/features/bash-dispatchers.md +2 -2
  17. package/hooks/features/conduct-gates.md +3 -3
  18. package/hooks/hooks_constants/context_budget_constants.py +1 -0
  19. package/hooks/hooks_constants/merge_review_gate_constants.py +28 -1
  20. package/hooks/hooks_constants/owned_pr_merge_stop_gate_constants.py +4 -1
  21. package/hooks/hooks_constants/owned_pr_review_loop_constants.py +4 -0
  22. package/hooks/hooks_constants/reply_length_gate_constants.py +17 -1
  23. package/hooks/hooks_constants/test_reply_length_gate_constants.py +20 -0
  24. package/hooks/hooks_constants/test_visual_reply_rules_constants.py +5 -0
  25. package/hooks/hooks_constants/visual_reply_rules_constants.py +11 -0
  26. package/hooks/owned_pr_session_record.py +76 -1
  27. package/hooks/test_owned_pr_session_record.py +26 -0
  28. package/hooks/test_visual_reply_rules.py +27 -0
  29. package/hooks/visual_reply_rules.py +64 -0
  30. package/package.json +1 -1
  31. package/scripts/tests/test_policy_lint_rules_context_budget.py +15 -0
@@ -19,6 +19,15 @@ PULL_REQUEST = {
19
19
  "number": "9",
20
20
  "url": "https://github.com/jl-cmd/snake-game/pull/9",
21
21
  }
22
+ RECORDED_PULL_REQUEST = {
23
+ "owner": "jl-cmd-projects",
24
+ "repository": "claude-dev-env",
25
+ "number": "2300",
26
+ "url": "https://github.com/jl-cmd-projects/claude-dev-env/pull/2300",
27
+ }
28
+ RECORDED_HEAD = "6ea405f886de9e3a434376a0b580cc3648d11a3c"
29
+ FIRST_HEAD = "abc1234def5678abc1234def5678abc1234def56"
30
+ PUSHED_HEAD = "9999999aaaaaaa9999999aaaaaaa9999999aaaaa"
22
31
 
23
32
 
24
33
  @pytest.fixture(autouse=True)
@@ -64,7 +73,9 @@ def test_main_should_block_while_a_recorded_pull_request_is_open(
64
73
  assert decision["decision"] == "block"
65
74
  assert PULL_REQUEST["url"] in decision["reason"]
66
75
  assert "/efficient-review" in decision["reason"]
67
- assert all_calls == [["gh", "api", "repos/jl-cmd/snake-game/pulls/9", "--jq", ".state"]]
76
+ assert all_calls == [
77
+ ["gh", "api", "repos/jl-cmd/snake-game/pulls/9", "--jq", '.state + " " + .head.sha']
78
+ ]
68
79
 
69
80
 
70
81
  def test_main_should_allow_once_the_pull_request_is_closed(
@@ -109,9 +120,14 @@ def test_main_should_allow_a_session_that_opened_no_owned_pull_request(
109
120
  assert all_calls == []
110
121
 
111
122
 
112
- def test_is_pull_request_open_should_read_the_github_state(monkeypatch: pytest.MonkeyPatch) -> None:
113
- _gh_reports(monkeypatch, "open\n")
114
- assert owned_pr_merge_stop_gate.is_pull_request_open(PULL_REQUEST)
123
+ def test_open_head_should_read_the_github_state_and_head(monkeypatch: pytest.MonkeyPatch) -> None:
124
+ _gh_reports(monkeypatch, f"open {FIRST_HEAD}\n")
125
+ assert owned_pr_merge_stop_gate.open_head(PULL_REQUEST) == FIRST_HEAD
126
+
127
+
128
+ def test_open_head_should_read_a_closed_pull_request_as_none(monkeypatch: pytest.MonkeyPatch) -> None:
129
+ _gh_reports(monkeypatch, f"closed {FIRST_HEAD}\n")
130
+ assert owned_pr_merge_stop_gate.open_head(PULL_REQUEST) is None
115
131
 
116
132
 
117
133
  def test_is_reported_blocked_should_accept_the_url() -> None:
@@ -121,9 +137,11 @@ def test_is_reported_blocked_should_accept_the_url() -> None:
121
137
 
122
138
  def test_unfinished_pull_requests_should_list_the_open_one(monkeypatch: pytest.MonkeyPatch) -> None:
123
139
  owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
124
- _gh_reports(monkeypatch, "open\n")
140
+ _gh_reports(monkeypatch, f"open {FIRST_HEAD}\n")
125
141
  hook_input: dict[str, object] = {"session_id": SESSION_ID, "last_assistant_message": "Open."}
126
- assert owned_pr_merge_stop_gate.unfinished_pull_requests(hook_input) == [PULL_REQUEST]
142
+ assert owned_pr_merge_stop_gate.unfinished_pull_requests(hook_input) == [
143
+ {**PULL_REQUEST, "head": FIRST_HEAD}
144
+ ]
127
145
 
128
146
 
129
147
  def test_block_reason_for_should_name_each_pull_request_and_the_blocked_form() -> None:
@@ -161,3 +179,76 @@ def test_block_reason_for_should_name_a_user_hold_as_a_blocker() -> None:
161
179
  def test_is_reported_blocked_should_require_the_colon_after_blocked() -> None:
162
180
  reply_text = "Blocked while CI runs on jl-cmd/snake-game#9."
163
181
  assert not owned_pr_merge_stop_gate.is_reported_blocked(PULL_REQUEST, reply_text)
182
+
183
+
184
+ def _gh_serves(
185
+ monkeypatch: pytest.MonkeyPatch, all_pull_requests: dict[str, tuple[str, str]]
186
+ ) -> None:
187
+ def fake_run(all_arguments: list[str], **_: object) -> subprocess.CompletedProcess[str]:
188
+ state, head = all_pull_requests[all_arguments[2]]
189
+ answer = state if all_arguments[4] == ".state" else f"{state} {head}"
190
+ return subprocess.CompletedProcess(all_arguments, 0, stdout=answer + "\n", stderr="")
191
+
192
+ monkeypatch.setattr(owned_pr_merge_stop_gate.subprocess, "run", fake_run)
193
+
194
+
195
+ RECORDED_ENDPOINT = "repos/jl-cmd-projects/claude-dev-env/pulls/2300"
196
+ PULL_REQUEST_ENDPOINT = "repos/jl-cmd/snake-game/pulls/9"
197
+
198
+
199
+ def test_main_should_block_once_per_head_on_the_recorded_pull_request(
200
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
201
+ ) -> None:
202
+ owned_pr_session_record.record_pull_request(SESSION_ID, RECORDED_PULL_REQUEST)
203
+ _gh_serves(monkeypatch, {RECORDED_ENDPOINT: ("open", RECORDED_HEAD)})
204
+ first_decision = json.loads(_run_gate(monkeypatch, capsys, "Review is clean."))
205
+ assert first_decision["decision"] == "block"
206
+ assert RECORDED_PULL_REQUEST["url"] in first_decision["reason"]
207
+ assert _run_gate(monkeypatch, capsys, "Waiting on CI.") == ""
208
+ assert _run_gate(monkeypatch, capsys, "Still waiting on CI.") == ""
209
+
210
+
211
+ def test_main_should_block_again_after_the_head_moves(
212
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
213
+ ) -> None:
214
+ owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
215
+ _gh_serves(monkeypatch, {PULL_REQUEST_ENDPOINT: ("open", FIRST_HEAD)})
216
+ assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"
217
+ _gh_serves(monkeypatch, {PULL_REQUEST_ENDPOINT: ("open", PUSHED_HEAD)})
218
+ assert json.loads(_run_gate(monkeypatch, capsys, "Pushed a fix."))["decision"] == "block"
219
+ assert _run_gate(monkeypatch, capsys, "Waiting on CI.") == ""
220
+
221
+
222
+ def test_main_should_block_every_stop_when_github_gives_no_head(
223
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
224
+ ) -> None:
225
+ owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
226
+ _gh_reports(monkeypatch, "open\n")
227
+ assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"
228
+ assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"
229
+
230
+
231
+ def test_main_should_list_only_the_pull_request_with_a_new_head(
232
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
233
+ ) -> None:
234
+ owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
235
+ _gh_serves(monkeypatch, {PULL_REQUEST_ENDPOINT: ("open", FIRST_HEAD)})
236
+ assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"
237
+ owned_pr_session_record.record_pull_request(SESSION_ID, RECORDED_PULL_REQUEST)
238
+ _gh_serves(
239
+ monkeypatch,
240
+ {PULL_REQUEST_ENDPOINT: ("open", FIRST_HEAD), RECORDED_ENDPOINT: ("open", RECORDED_HEAD)},
241
+ )
242
+ reason = json.loads(_run_gate(monkeypatch, capsys, "Opened another."))["reason"]
243
+ assert RECORDED_PULL_REQUEST["url"] in reason
244
+ assert PULL_REQUEST["url"] not in reason
245
+
246
+
247
+ def test_main_should_keep_the_blocked_line_release_before_the_first_block(
248
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
249
+ ) -> None:
250
+ owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
251
+ _gh_serves(monkeypatch, {PULL_REQUEST_ENDPOINT: ("open", FIRST_HEAD)})
252
+ reply_text = "Blocked: jl-cmd/snake-game#9 - the user holds the merge"
253
+ assert _run_gate(monkeypatch, capsys, reply_text) == ""
254
+ assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"
@@ -1029,6 +1029,45 @@ def test_should_leave_the_transcript_unread_when_the_text_cites_nothing(
1029
1029
  assert all_read_paths == []
1030
1030
 
1031
1031
 
1032
+ def test_should_count_a_pull_request_link_a_task_notification_shows(tmp_path: Path) -> None:
1033
+ notification = {
1034
+ "type": "user",
1035
+ "origin": {"kind": "task-notification"},
1036
+ "message": {"content": "<result>Opened https://github.com/o/r/pull/8127</result>"},
1037
+ }
1038
+ transcript_path = tmp_path / "s.jsonl"
1039
+ transcript_path.write_text(json.dumps(notification), encoding="utf-8")
1040
+ card_text = "Open as [PR 8127](https://github.com/o/r/pull/8127)."
1041
+ assert reply_length_gate.unseen_citation_violation_with_hook_text(card_text, str(transcript_path)) is None
1042
+ assert 'cites "/pull/8127"' in reply_length_gate.unseen_citation_violation(card_text, str(transcript_path))
1043
+
1044
+
1045
+ def test_should_not_count_the_gate_echo_of_its_own_citation(tmp_path: Path) -> None:
1046
+ feedback = {
1047
+ "type": "user",
1048
+ "isMeta": True,
1049
+ "message": {"content": 'Stop hook feedback:\nThe text cites "/pull/8127", and no tool result in this'
1050
+ " session shows it. Read it yourself or through a subagent first."},
1051
+ }
1052
+ transcript_path = tmp_path / "s.jsonl"
1053
+ transcript_path.write_text(json.dumps(feedback), encoding="utf-8")
1054
+ card_text = "Open as [PR 8127](https://github.com/o/r/pull/8127)."
1055
+ assert 'cites "/pull/8127"' in reply_length_gate.unseen_citation_violation_with_hook_text(
1056
+ card_text, str(transcript_path)
1057
+ )
1058
+
1059
+
1060
+ def test_should_skip_the_hook_text_read_when_a_tool_result_shows_the_link(
1061
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
1062
+ ) -> None:
1063
+ all_read_paths: list[object] = []
1064
+ monkeypatch.setattr(reply_length_gate, "hook_supplied_text", all_read_paths.append)
1065
+ transcript_path = write_tool_result_transcript(tmp_path / "s.jsonl", "pull/8127 opened")
1066
+ card_text = "Open as [PR 8127](https://github.com/o/r/pull/8127)."
1067
+ assert reply_length_gate.unseen_citation_violation_with_hook_text(card_text, str(transcript_path)) is None
1068
+ assert all_read_paths == []
1069
+
1070
+
1032
1071
  def test_should_split_prose_sentences_outside_fenced_blocks() -> None:
1033
1072
  reply_text = "First one. Second one?\n```\nskipped. code\n```\nThird"
1034
1073
  assert reply_length_gate.prose_sentences(reply_text) == ["First one.", "Second one?", "", "Third"]
@@ -82,6 +82,8 @@ class BudgetPolicy:
82
82
  is_baseline_the_prior_text: Whether the baseline entry was measured from
83
83
  the file's prior text because the repository has no policy file.
84
84
  prose_line_word_limit: Words an unlinked agent-file detail line may hold.
85
+ has_baseline: False only when parsed policy text has no ``baseline`` key,
86
+ so a change may add the first over-budget list to it.
85
87
  """
86
88
 
87
89
  section_detail_line_limit: int
@@ -91,6 +93,7 @@ class BudgetPolicy:
91
93
  baseline_characters_by_hook_name: Mapping[str, int] = field(default_factory=dict)
92
94
  is_baseline_the_prior_text: bool = False
93
95
  prose_line_word_limit: int = DEFAULT_PROSE_LINE_WORD_LIMIT
96
+ has_baseline: bool = True
94
97
 
95
98
 
96
99
  @dataclass(frozen=True)
@@ -6,11 +6,17 @@ command script is still in the tree is a finding. A hook deleted together
6
6
  with its script passes.
7
7
  Existing kind patterns and precedence stay fixed. A null line count that
8
8
  becomes a number is larger. A policy file the change introduces passes.
9
+ A policy without a ``baseline`` key may gain its first list; each file entry
10
+ is then held to what the working tree measures, so the first list records
11
+ only what is over budget now. Hook counts in a first list are not measured
12
+ here, because measuring runs the hook's command. A deleted ``baseline`` key
13
+ is a finding, so a later change cannot add a fresh list in its place.
9
14
  """
10
15
 
11
16
  from __future__ import annotations
12
17
 
13
18
  from collections import Counter
19
+ from dataclasses import replace
14
20
  from pathlib import Path
15
21
 
16
22
  from context_budget.model import (
@@ -20,12 +26,14 @@ from context_budget.model import (
20
26
  ContextKind,
21
27
  HookBudget,
22
28
  )
29
+ from context_budget.sections import baseline_entry_for, measure_file
23
30
  from hooks_constants.context_budget_constants import (
24
31
  CHANGE_ADDS_FILE,
25
32
  CHANGE_ADDS_HOOK,
26
33
  CHANGE_ADDS_SECTION,
27
34
  CHANGE_CHANGES_KIND_ORDER,
28
35
  CHANGE_CHANGES_PATTERNS,
36
+ CHANGE_DELETES_BASELINE_KEY,
29
37
  CHANGE_DELETES_HOOK,
30
38
  CHANGE_DELETES_KIND,
31
39
  CHANGE_DISABLES_SECTION_RULE,
@@ -39,6 +47,7 @@ from hooks_constants.context_budget_constants import (
39
47
  FILE_SCOPE,
40
48
  NO_LINE_LIMIT_TEXT,
41
49
  SHRINK_ONLY_TEMPLATE,
50
+ UTF8_ENCODING,
42
51
  )
43
52
 
44
53
 
@@ -189,6 +198,46 @@ def _hook_entry_changes(prior_policy: BudgetPolicy, current_policy: BudgetPolicy
189
198
  return [each for each in all_candidate_changes if each is not None]
190
199
 
191
200
 
201
+ def _measured_entry(
202
+ current_policy: BudgetPolicy, relative_path: str, repository_root: Path
203
+ ) -> BaselineEntry | None:
204
+ try:
205
+ text = (repository_root / relative_path).read_text(encoding=UTF8_ENCODING)
206
+ except (OSError, UnicodeDecodeError):
207
+ return None
208
+ measure = measure_file(current_policy, relative_path, text)
209
+ return None if measure is None else baseline_entry_for(measure)
210
+
211
+
212
+ def _measured_tree_policy(current_policy: BudgetPolicy, repository_root: Path) -> BudgetPolicy:
213
+ all_measured_entries = (
214
+ (each_path, _measured_entry(current_policy, each_path, repository_root))
215
+ for each_path in current_policy.baseline_entry_by_path
216
+ )
217
+ return replace(
218
+ current_policy,
219
+ baseline_entry_by_path={
220
+ each_path: each_entry
221
+ for each_path, each_entry in all_measured_entries
222
+ if each_entry is not None
223
+ },
224
+ )
225
+
226
+
227
+ def _baseline_changes(
228
+ prior_policy: BudgetPolicy, current_policy: BudgetPolicy, repository_root: Path
229
+ ) -> list[str]:
230
+ if not prior_policy.has_baseline:
231
+ return _file_entry_changes(
232
+ _measured_tree_policy(current_policy, repository_root), current_policy
233
+ )
234
+ if not current_policy.has_baseline:
235
+ return [CHANGE_DELETES_BASELINE_KEY]
236
+ return _file_entry_changes(prior_policy, current_policy) + _hook_entry_changes(
237
+ prior_policy, current_policy
238
+ )
239
+
240
+
192
241
  def policy_shrink_findings(
193
242
  policy_path: str,
194
243
  prior_policy: BudgetPolicy | None,
@@ -204,14 +253,14 @@ def policy_shrink_findings(
204
253
  repository_root: Working tree that holds each hook's command script.
205
254
 
206
255
  Returns:
207
- One finding per loosening change; empty when the file is new.
256
+ One finding per loosening change; empty when the file is new. When the
257
+ prior policy has no ``baseline`` key, each file entry is compared with
258
+ the working tree's measurement in place of a prior entry.
208
259
  """
209
260
  if prior_policy is None:
210
261
  return ()
211
- all_changes = (
212
- _limit_changes(prior_policy, current_policy, repository_root)
213
- + _file_entry_changes(prior_policy, current_policy)
214
- + _hook_entry_changes(prior_policy, current_policy)
262
+ all_changes = _limit_changes(prior_policy, current_policy, repository_root) + (
263
+ _baseline_changes(prior_policy, current_policy, repository_root)
215
264
  )
216
265
  return tuple(
217
266
  BudgetFinding(
@@ -188,6 +188,7 @@ def parse_policy(policy_text: str) -> BudgetPolicy:
188
188
  all_hooks=_parse_hooks(raw_policy.get(HOOKS_KEY, [])),
189
189
  baseline_entry_by_path=entry_by_path,
190
190
  baseline_characters_by_hook_name=characters_by_hook_name,
191
+ has_baseline=BASELINE_KEY in raw_policy,
191
192
  )
192
193
 
193
194
 
@@ -35,6 +35,7 @@ def test_policy_holds_kinds_hooks_and_baselines() -> None:
35
35
  assert policy.baseline_entry_by_path["a/SKILL.md"] == baseline
36
36
  assert policy.baseline_characters_by_hook_name["startup print"] == 5200
37
37
  assert policy.is_baseline_the_prior_text is True
38
+ assert policy.has_baseline is True
38
39
 
39
40
 
40
41
  def test_baseline_entry_holds_no_line_count_for_a_section_only_file() -> None:
@@ -7,7 +7,7 @@ from pathlib import Path
7
7
 
8
8
  import pytest
9
9
 
10
- from context_budget.tests.budget_support import policy_text
10
+ from context_budget.tests.budget_support import policy_text, section_text
11
11
  from context_budget.policy_changes import policy_shrink_findings
12
12
  from context_budget.policy_file import parse_policy
13
13
 
@@ -175,6 +175,126 @@ def test_appending_a_kind_and_tightening_limits_passes(tmp_path: Path) -> None:
175
175
  ) == ()
176
176
 
177
177
 
178
+ def _policy_without_baseline_key() -> dict:
179
+ raw_policy = json.loads(policy_text())
180
+ del raw_policy["baseline"]
181
+ return raw_policy
182
+
183
+
184
+ def _policy_with_first_list() -> dict:
185
+ raw_policy = json.loads(policy_text({"a/SKILL.md": {"lines": 300, "sections": ["X"]}}))
186
+ raw_policy["baseline"]["hooks"] = {"greeter": 2000}
187
+ return raw_policy
188
+
189
+
190
+ def _write_over_budget_skill(repository_root: Path) -> None:
191
+ skill_text = section_text("X", 7)
192
+ filler_line_count = 300 - len(skill_text.splitlines())
193
+ (repository_root / "a").mkdir()
194
+ (repository_root / "a" / "SKILL.md").write_text(
195
+ skill_text + "\n" * filler_line_count, encoding="utf-8"
196
+ )
197
+
198
+
199
+ def _first_list_findings(raw_current: dict, repository_root: Path) -> tuple:
200
+ return policy_shrink_findings(
201
+ "p",
202
+ parse_policy(json.dumps(_policy_without_baseline_key())),
203
+ parse_policy(json.dumps(raw_current)),
204
+ repository_root,
205
+ )
206
+
207
+
208
+ def test_first_baseline_that_matches_the_tree_passes(tmp_path: Path) -> None:
209
+ _write_over_budget_skill(tmp_path)
210
+
211
+ assert _first_list_findings(_policy_with_first_list(), tmp_path) == ()
212
+
213
+
214
+ @pytest.mark.parametrize(
215
+ ("mutation", "expected_fragment"),
216
+ [
217
+ (
218
+ lambda raw: raw["baseline"]["files"]["a/SKILL.md"].update({"lines": 400}),
219
+ 'baseline raises "a/SKILL.md" from 300 to 400 lines',
220
+ ),
221
+ (
222
+ lambda raw: raw["baseline"]["files"]["a/SKILL.md"]["sections"].append("Y"),
223
+ 'baseline adds section "Y" to "a/SKILL.md"',
224
+ ),
225
+ (
226
+ lambda raw: raw["baseline"]["files"].update(
227
+ {"b/SKILL.md": {"lines": 300, "sections": []}}
228
+ ),
229
+ 'baseline adds file "b/SKILL.md"',
230
+ ),
231
+ ],
232
+ )
233
+ def test_first_baseline_entry_beyond_the_tree_is_a_finding(
234
+ mutation, expected_fragment: str, tmp_path: Path
235
+ ) -> None:
236
+ _write_over_budget_skill(tmp_path)
237
+ raw_current = _policy_with_first_list()
238
+ mutation(raw_current)
239
+
240
+ all_findings = _first_list_findings(raw_current, tmp_path)
241
+
242
+ assert len(all_findings) == 1
243
+ assert expected_fragment in all_findings[0].message
244
+ assert "the over-budget list may only shrink" in all_findings[0].message
245
+
246
+
247
+ def test_first_baseline_entry_for_a_file_within_budget_is_a_finding(tmp_path: Path) -> None:
248
+ (tmp_path / "a").mkdir()
249
+ (tmp_path / "a" / "SKILL.md").write_text("# Short\n", encoding="utf-8")
250
+
251
+ all_findings = _first_list_findings(_policy_with_first_list(), tmp_path)
252
+
253
+ assert len(all_findings) == 1
254
+ assert 'baseline adds file "a/SKILL.md"' in all_findings[0].message
255
+
256
+
257
+ def test_first_baseline_added_to_an_explicit_empty_baseline_is_a_finding(
258
+ tmp_path: Path,
259
+ ) -> None:
260
+ _write_over_budget_skill(tmp_path)
261
+
262
+ all_findings = policy_shrink_findings(
263
+ "p",
264
+ parse_policy(policy_text()),
265
+ parse_policy(json.dumps(_policy_with_first_list())),
266
+ tmp_path,
267
+ )
268
+
269
+ assert len(all_findings) == 2
270
+ assert 'baseline adds file "a/SKILL.md"' in all_findings[0].message
271
+ assert 'baseline adds hook "greeter"' in all_findings[1].message
272
+
273
+
274
+ def test_deleting_the_baseline_key_is_a_finding(tmp_path: Path) -> None:
275
+ all_findings = policy_shrink_findings(
276
+ "p",
277
+ parse_policy(policy_text()),
278
+ parse_policy(json.dumps(_policy_without_baseline_key())),
279
+ tmp_path,
280
+ )
281
+
282
+ assert len(all_findings) == 1
283
+ assert 'the "baseline" key is deleted' in all_findings[0].message
284
+ assert "the over-budget list may only shrink" in all_findings[0].message
285
+
286
+
287
+ def test_first_baseline_still_holds_the_limits_to_the_prior_policy(tmp_path: Path) -> None:
288
+ _write_over_budget_skill(tmp_path)
289
+ raw_current = _policy_with_first_list()
290
+ raw_current["kinds"][1]["line_limit"] = 250
291
+
292
+ all_findings = _first_list_findings(raw_current, tmp_path)
293
+
294
+ assert len(all_findings) == 1
295
+ assert "line_limit rises from 200 to 250" in all_findings[0].message
296
+
297
+
178
298
  def test_raising_the_prose_line_word_limit_is_a_loosening_change(tmp_path: Path) -> None:
179
299
  raw_prior = json.loads(policy_text())
180
300
  raw_prior["prose_line_word_limit"] = 25
@@ -39,6 +39,17 @@ def test_baseline_lines_may_be_null_but_may_not_be_missing() -> None:
39
39
  parse_policy(policy_text({"a/SKILL.md": {"sections": ["Plan"]}}))
40
40
 
41
41
 
42
+ def test_parse_tells_a_missing_baseline_key_from_an_empty_baseline() -> None:
43
+ raw_policy = json.loads(policy_text())
44
+ empty_baseline_policy = parse_policy(json.dumps(raw_policy))
45
+ del raw_policy["baseline"]
46
+ keyless_policy = parse_policy(json.dumps(raw_policy))
47
+
48
+ assert empty_baseline_policy.has_baseline is True
49
+ assert keyless_policy.has_baseline is False
50
+ assert keyless_policy.baseline_entry_by_path == {}
51
+
52
+
42
53
  def test_duplicate_hook_names_are_rejected_before_measurement() -> None:
43
54
  raw_policy = json.loads(policy_text())
44
55
  raw_policy["hooks"].append(dict(raw_policy["hooks"][0]))
@@ -14,7 +14,7 @@ This family rewrites a Git Bash command when path conversion would change a revi
14
14
  - `blocking/bash_post_call_dispatcher.py` runs hosted observers and joins their context output without blocking the call.
15
15
  - `advisory/pr_done_reminder.py` adds a pull request checklist after a successful push or pull request creation.
16
16
  - `advisory/owned_pr_review_loop.py` adds review-loop instructions after the agent opens a pull request on an owned repository outside the preset list of repositories that run their own automated review: run efficient-review until clean, mark the pull request ready, babysit it, and ship it to merge. It also records the pull request for the session in `owned_pr_session_record.py`.
17
- - `blocking/owned_pr_merge_stop_gate.py` holds the end of a turn while a recorded pull request reads open on GitHub and the closing reply has no `Blocked:` line that names it. A failed state lookup passes.
17
+ - `blocking/owned_pr_merge_stop_gate.py` holds the end of a turn while a recorded pull request reads open on GitHub and the closing reply has no `Blocked:` line that names it. It holds once per pull request head in a session, so a later stop passes until a push moves the head. A failed state lookup passes.
18
18
 
19
19
  ## When it fires
20
20
 
@@ -45,7 +45,7 @@ Preconditions:
45
45
  - **Post-call dispatch.** Input is a Bash call that yields hosted context. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_bash_post_call_dispatcher.py -q`. The adjacent test observes a joined context payload and exit code zero.
46
46
  - **Pull request reminder.** Input is a completed push or pull request creation. Run `python -m pytest packages/claude-dev-env/hooks/advisory/test_pr_done_reminder.py -q`. The adjacent test checks the reminder trigger and checklist verdict.
47
47
  - **Owned pull request review loop.** Input is a pull request creation result on an owned repository. Run `python -m pytest packages/claude-dev-env/hooks/advisory/test_owned_pr_review_loop.py -q`. The adjacent test observes the review-loop block for owned repositories and silence for the preset and foreign repositories.
48
- - **Owned pull request merge gate.** Input is a `session_record_path` file that lists `jl-cmd/snake-game#9` and a `gh` stub that reports `open`. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_owned_pr_merge_stop_gate.py packages/claude-dev-env/hooks/test_owned_pr_session_record.py -q`. The adjacent test observes a `block` decision that names the pull request; `closed` and a `Blocked: jl-cmd/snake-game#9 - ...` line pass.
48
+ - **Owned pull request merge gate.** Input is a `session_record_path` file that lists `jl-cmd/snake-game#9` and a `gh` stub that reports `open` and a head sha. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_owned_pr_merge_stop_gate.py packages/claude-dev-env/hooks/test_owned_pr_session_record.py -q`. The adjacent test observes a `block` decision that names the pull request; `closed` and a `Blocked: jl-cmd/snake-game#9 - ...` line pass, and a second stop on the same head passes.
49
49
 
50
50
  ## Gotchas
51
51
 
@@ -5,7 +5,7 @@ This family stops a chat reply, edited message, or tool call when its payload br
5
5
  ## Checks
6
6
 
7
7
  - `blocking/reply_length_gate.py` caps chat reply length, denies a configured banned word, requires a readable link when the text names a pull request number, and denies a causal claim in a reply that cites no code span, output block, or link. It denies a sentence that guesses, estimates, hedges a duration, or admits a skipped check, such as "I didn't confirm this one." It denies a cited Actions run, pull request, or run, job, or check id that no successful tool result in the transcript shows; a subagent's report is the result of its Agent call. A question card from `AskUserQuestion` gets the banned word check and `unvalidated_claim_violation`, like a decision card. One refusal names every broken rule and every offending sentence, numbered, and ends with "Fix every item above in your next write." With visual reply mode on, it also runs the checks in `visual_reply_rules.py` from the rule list in `rules/visual-reply-rules.json`: no abbreviation or tracker number outside a link, a widget or page before a reply of more than one sentence, and no anchor link inside widget code. The mode is off by default; `~/.claude/visual-reply-mode.json` with `{"enabled": true}` turns the mode checks on. The results-picture check runs with the mode off too. A reply with a markdown table, or more than two figures, needs a picture: an attached `.svg`, `.png`, `.jpg`, `.jpeg`, `.gif`, or `.webp` file, an attached `frame` output such as a published page, or a markdown picture outside code. The check reads the attached name only, so it does not confirm that the file exists. It skips an edit of a posted message, because the edit tool attaches nothing, and the closing reply of a turn, which `blocking/final_reply_gate.py` does not run it on.
8
- - `blocking/final_reply_gate.py` applies the banned words, `unvalidated_claim_violation`, and `unseen_citation_violation` from the reply gate to the reply a session ends its turn with. Its `windows_path_violation` blocks a path the terminal would render without one of its backslashes. Its `unbriefed_question_violation` blocks a reply whose last paragraph, with fences, quotes, and code spans left out, ends with a question mark or says a question still stands, when the turn sent no `AskUserQuestion`, hearthbot decision card, or Codex `request_user_input` call; it is skipped when the transcript cannot be read.
8
+ - `blocking/final_reply_gate.py` applies the banned words, `unvalidated_claim_violation`, and `unseen_citation_violation_with_hook_text` from the reply gate to the reply a session ends its turn with. In that citation check a `/pull/N` link also counts as shown when hook or harness text shows it: stop-hook feedback, system reminders, a background agent's task notification, and hook additional context, hook system message, and queued task notification attachments. A skill body, or a prompt the user typed while the session worked, does not count. The gate's own feedback, which quotes the reply, does not count. Its `windows_path_violation` blocks a path the terminal would render without one of its backslashes. Its `unbriefed_question_violation` blocks a reply whose last paragraph, with fences, quotes, and code spans left out, ends with a question mark or says a question still stands, when the turn sent no `AskUserQuestion`, hearthbot decision card, or Codex `request_user_input` call; it is skipped when the transcript cannot be read.
9
9
  - `blocking/open_tasks_stop_gate.py` holds the end of a turn once when the prompt that started it asks for work, the turn ran a work tool, and the turn made no tracker call: TaskCreate, TaskUpdate, TodoWrite, the Codex `update_plan`, or the desktop `mcp__ccd_turn__update_plan`. A work tool is any tool but a tracker call, the session title tool, `AskUserQuestion`, a hearthbot decision card, Codex `request_user_input`, `ToolSearch`, `TaskList`, or `TaskGet`. It never reads the reply text. `open_task_asks.is_ask` decides whether a prompt asks for work: a question-only prompt, an acknowledgement such as `thanks!`, an empty prompt, a prompt of only `<system-reminder>` blocks, and an envelope such as `<agent-message>` or `<task-notification>` do not. `blocking/open_tasks_transcript.py` replays the transcript for it: the turn's prompt, its tool calls, and the task list. `session_task_items` merges the task store with the transcript items whose subject the store does not hold, for the session title gate.
10
10
  - `session/tracking_nudge.py` adds one `additionalContext` note to a prompt that asks for work. The note asks for an item in the session's task list tool. It shows on the session's first ask and on the first ask after each compaction, through `once_per_session.py`. When the title shows the red flag or the check mark, it also asks for the hourglass before other work. It never blocks.
11
11
  - `session/background_silence_prompt.py` adds one `additionalContext` note to a background event prompt, one that starts with `<task-notification>` or opens itself or a `<system-reminder>` block with `[SYSTEM NOTIFICATION - NOT USER INPUT]`, while the user asked for silence. The newest user-typed message that sets silence ("silent unless", "stay silent", "silent on updates", "no updates unless") or lifts it ("you can talk again", "updates are fine", "stop being silent") decides. The note quotes the user's "unless" or "except" clause word for word, or the whole message when it has no such clause, and says to end the turn with no text unless that exception applies now. Envelope prompts, compaction summaries, and quoted `>` lines are not the user's words. It never blocks.
@@ -22,7 +22,7 @@ This family stops a chat reply, edited message, or tool call when its payload br
22
22
  - `blocking/resolve_thread_reply_gate.py` denies a review thread resolve until the agent's own transcript shows a reply on that same thread that posted after the last user prompt and that no successful resolve of the thread has spent. A resolve is a `resolve_review_thread` call, which names the thread by `threadID`; a `pull_request_review_write` call with method `resolve_thread`, which names it by `threadId`; a shell command with a `gh api graphql` `resolveReviewThread` mutation, which names it by a literal `PRRT_` id; or a shell call to `pulls/<n>/ccr/comments/<id>/resolve`, which names it by a comment id. A graphql resolve that names no `PRRT_` id is denied. A reply is an `add_reply_to_pull_request_comment` call, or a `gh api` call to a comment's `replies` endpoint or to `addPullRequestReviewThreadReply`, which names its thread by `PRRT_` id. A reply and a resolve by comment id match when they name the same comment, or when a successful tool result in the transcript, such as `pull_request_read` `get_review_comments`, lists the comment under the thread by its `discussion_r` anchor or `databaseId`. A reply whose result is an error, such as a refusal from `blocking/reply_length_gate.py`, does not count. With no readable transcript, the resolve passes.
23
23
  - `blocking/verify_before_commit_gate.py` denies a `git commit` in a repository with a `.claude/skills/verify` or `.agents/skills/verify` directory until the `verify` skill loads after the last user prompt, through a Skill call whose result comes back without an error, or the `/verify` command in that prompt. It reads the committed paths from the staged diff, the tracked changes for `-a`, and the paths of each `git add` earlier in the same command, and passes a commit whose paths are all docs, images, test files, or `.json`, `.jsonl`, `.yaml`, `.yml`, or `.csv` files under a `docs` folder.
24
24
  - `blocking/build_eval_before_eval_write_gate.py` denies a write to an eval file until a Skill call named exactly `claude-api` with args `build-eval`, or the `/claude-api build-eval` command, appears in the transcript.
25
- - `blocking/merge_review_gate.py` denies an agent's merge until a review pass on the merged head reported zero findings, or ruled out every finding and linked the posted rulings. It reads the receipt `scripts/merge_review_receipt.py` writes, requires the merge, auto-merge or merge-queue entry to be pinned to that head, and skips repositories listed in `CLAUDE_MERGE_REVIEW_EXEMPT_REPOSITORIES`. Its deny reason names the review command `CLAUDE_MERGE_REVIEW_COMMAND` sets. The reason tells the agent to run that command for the first three passes and `/code-review low --fix <number>` for each later pass; the gate itself counts no passes. It also denies a pull request open, through `gh pr create`, `pull_request.py create` or a `create_pull_request` tool, until a pass recorded as `merge_review_receipt.py <owner/name> open <head> 0` covers the head the pull request opens with. An open pass also counts when every finding is ruled out: `merge_review_receipt.py <owner/name> open <head> <count> --ruled-out <count> --rulings <path:line,...>`, with a different `path:line` for each finding, checked against the file at that head when the pass is recorded. A merge pinned to that same head passes on the open receipt only when the pass found zero findings.
25
+ - `blocking/merge_review_gate.py` denies an agent's merge until a review pass on the merged head reported zero findings, or ruled out every finding and linked the posted rulings. It reads the receipt `scripts/merge_review_receipt.py` writes, requires the merge, auto-merge or merge-queue entry to be pinned to that head, and skips repositories listed in `CLAUDE_MERGE_REVIEW_EXEMPT_REPOSITORIES`. A `gh pr merge` call whose every merge segment carries `--disable-auto` only turns auto-merge off, so it passes. A segment that also carries `--auto`, gives `--auto` or `--disable-auto` an `=` value, joins short flags such as `-sb`, or holds a bare `--` keeps every check. Its deny reason names the review command `CLAUDE_MERGE_REVIEW_COMMAND` sets. The reason tells the agent to run that command for the first three passes and `/code-review low --fix <number>` for each later pass; the gate itself counts no passes. It also denies a pull request open, through `gh pr create`, `pull_request.py create` or a `create_pull_request` tool, until a pass recorded as `merge_review_receipt.py <owner/name> open <head> 0` covers the head the pull request opens with. An open pass also counts when every finding is ruled out: `merge_review_receipt.py <owner/name> open <head> <count> --ruled-out <count> --rulings <path:line,...>`, with a different `path:line` for each finding, checked against the file at that head when the pass is recorded. A merge pinned to that same head passes on the open receipt only when the pass found zero findings.
26
26
  - `blocking/artifact_dark_mode_gate.py` denies an Artifact page publish when the page, inside the publish wrapper, keeps a light body or shows text under 4.5:1 contrast in dark mode. `blocking/artifact_dark_mode_render.cjs` renders the page in headless Chromium for it.
27
27
  - `blocking/send_user_file_worktree_root_gate.py` denies a `SendUserFile` call that names a file outside the session's working directory, the `cwd` in the hook payload. The desktop file pane opens a sent file only under that folder and shows "Couldn't find this file" for any other path. The reason lists each outside file and names `<cwd>\.scratch\` as the folder to copy it into.
28
28
  - `blocking/turn_review_gate.py` holds the end of a turn when a fresh `claude -p "/code-review low <base>..<turn>"` run finds a problem in that turn's edits. At the prompt it snapshots each opted-in checkout into a commit built from a copy of the index after `git add -A`; at the stop it snapshots again with the first snapshot as parent, so the range holds only the turn's edits, untracked files included. A checkout takes part when it is `CLAUDE_PROJECT_DIR` or a folder directly inside it and its GitHub origin `owner/repo` slug is listed in `CLAUDE_TURN_REVIEW_REPOSITORIES`, comma-separated. A finding is an entry in the review's last non-empty JSON array of objects with a `file` key, where `file` is a changed path and `line` is a number. An empty `[]` counts as no array. A review with no such array has a finding on each line that opens with a changed path, a colon and a line number, after an optional list marker, backtick or emphasis mark. A review that opens with `(none)` has none. A saved baseline that is not a 40- or 64-character commit name is dropped, and that stop takes a fresh baseline. Each stop moves the baseline to its snapshot, so the stop after a block reviews only the fix. It holds a stop at most 3 times in a row until the next prompt, skips a turn that changed more than 30 files, and lets the stop through when the review fails. The reviews of one stop share 240 seconds, and a checkout reached with less than a second left goes unreviewed. The review run gets `--setting-sources ""`, `--tools Read,Grep,Glob,Bash`, `--no-session-persistence`, `--permission-mode dontAsk`, read tools plus `git diff`, `git show` and `git log` in the checkout, a deny list for git's `-c`, `--config-env`, `--output`, `--ext-diff`, `--textconv`, `--git-dir`, `--work-tree` and `--exec-path` options, `--settings '{"disableAllHooks": true}'` so no other hook steers the review, `CLAUDE_TURN_REVIEW_CHILD=1`, and none of the parent session's id, messaging or ingress variables; the gate does nothing inside such a run.
@@ -76,7 +76,7 @@ Preconditions:
76
76
  - **Lifecycle skill.** Input is a `git commit` or `gh pr create` command with no `pr-lifecycle` invocation in the transcript. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_pr_lifecycle_skill_gate.py -q`. The adjacent test observes a denial, then a silent allow once the skill or its slash command appears.
77
77
  - **Verify before commit.** Input is `git add app.py; git commit -m change` in a temporary repository with `.agents/skills/verify`, and a transcript with no `verify` load after its last prompt. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_verify_before_commit_gate.py -q`. The adjacent test observes a denial, then a silent allow after a `verify` Skill call or a `/verify` prompt. A load before the last prompt still denies. A docs-only commit, a commit of data files under a `docs` folder, a tests-only commit, and a repository with no verify skill pass. A `.py` file under `docs` and a `.json` file outside `docs` still deny.
78
78
  - **Eval write.** Input is a Write to `evals/cases.json` with no build-eval call in the transcript. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_build_eval_before_eval_write_gate.py -q`. The adjacent test observes a denial, then an allow once the call appears; a write outside an eval path passes.
79
- - **Clean review.** Input is a merge with no receipt, a receipt with findings, a merge pinned to a newer head, an unpinned merge, or auto-merge with no head. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_merge_review_gate.py -q`. The adjacent test observes a denial for each; a merge or auto-merge pinned to the clean head and a merge in an exempt repository pass. An open with no clean open receipt at its head is denied; an open reviewed clean at its head, and a merge pinned to that head, pass. An open pass whose every finding has its own `path:line` ruling lets the open through; a merge pinned to that head is denied, since only a zero-finding open pass carries to the merge. An open whose branch neither GitHub nor the working folder holds is denied as unreadable.
79
+ - **Clean review.** Input is a merge with no receipt, a receipt with findings, a merge pinned to a newer head, an unpinned merge, or auto-merge with no head. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_merge_review_gate.py -q`. The adjacent test observes a denial for each; a merge or auto-merge pinned to the clean head and a merge in an exempt repository pass. A `gh pr merge --disable-auto` call passes; a merge chained with it, or one that adds `--disable-auto=false` or `-sb --disable-auto`, is still checked. An open with no clean open receipt at its head is denied; an open reviewed clean at its head, and a merge pinned to that head, pass. An open pass whose every finding has its own `path:line` ruling lets the open through; a merge pinned to that head is denied, since only a zero-finding open pass carries to the merge. An open whose branch neither GitHub nor the working folder holds is denied as unreadable.
80
80
  - **Dark mode page.** Input is an Artifact publish of a page that themes `html` but leaves `body` to the publish wrapper. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_artifact_dark_mode_gate.py -q`. The adjacent test observes a denial that names the text and its contrast; a page that themes `body` passes. The render tests skip on a host with no Node Playwright and Chromium.
81
81
  - **Sent file root.** Input is a `SendUserFile` call for a file on `Y:\` or in the session scratchpad, with `cwd` set to a worktree. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_send_user_file_worktree_root_gate.py -q`. The adjacent test observes a denial that names the file and `<cwd>\.scratch\`; a file under `<cwd>\.scratch\` passes.
82
82
  - **Turn review.** Input is a temporary checkout with an opted-in origin, a `UserPromptSubmit`, an edit that drops a decorator, and a `Stop`, with a stub `claude` on PATH that prints a finding. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_turn_review_gate.py -q`. The adjacent test observes a `block` decision with the finding, a review range whose diff holds only the edited file, and a review environment with no parent session id. A `(none)` review, an unchanged turn, a failed review, an unlisted repository, a 31-file turn, and a fourth stop in a row pass.
@@ -146,6 +146,7 @@ CHANGE_DELETES_KIND = 'kind "{subject}" is deleted'
146
146
  CHANGE_CHANGES_PATTERNS = 'kind "{subject}" patterns change'
147
147
  CHANGE_CHANGES_KIND_ORDER = "kind selection order changes"
148
148
  CHANGE_DELETES_HOOK = 'hook "{subject}" is deleted'
149
+ CHANGE_DELETES_BASELINE_KEY = 'the "' + BASELINE_KEY + '" key is deleted'
149
150
  CHANGE_RAISES_CHAR_LIMIT = 'hook "{subject}" char_limit rises from {prior} to {current}'
150
151
  NO_LINE_LIMIT_TEXT = "none"
151
152
 
@@ -70,11 +70,38 @@ RULING_LOOKUP_TIMEOUT_SECONDS = 10
70
70
  REPO_OPTION_PATTERN = re.compile(r"(?:-R|--repo)[\s=](?P<owner>[\w.-]+)/(?P<repo>[\w.-]+)")
71
71
  MATCH_HEAD_PATTERN = re.compile(r"--match-head-commit[\s=](?P<sha>[0-9a-fA-F]{7,40})")
72
72
  API_SHA_FIELD_PATTERN = re.compile(r"(?:-f|-F|--field|--raw-field)[\s=]sha=(?P<sha>[0-9a-fA-F]{7,40})")
73
+ ALL_OPTIONS_WITH_VALUE = (
74
+ "-R",
75
+ "--repo",
76
+ "--match-head-commit",
77
+ "-t",
78
+ "--subject",
79
+ "-b",
80
+ "--body",
81
+ "-F",
82
+ "--body-file",
83
+ "-A",
84
+ "--author-email",
85
+ )
73
86
  OPTION_WITH_VALUE_PATTERN = re.compile(
74
- r"(?<!\S)(?:-R|--repo|--match-head-commit|-t|--subject|-b|--body|-F|--body-file|-A|--author-email)"
87
+ r"(?<!\S)(?:" + "|".join(ALL_OPTIONS_WITH_VALUE) + r")"
75
88
  r"(?:=|\s+)(?:\"[^\"]*\"|'[^']*'|\S+)"
76
89
  )
77
90
  AUTO_OPTION_PATTERN = re.compile(r"(?:^|\s)--auto(?:\s|$)")
91
+ DISABLE_AUTO_OPTION = "--disable-auto"
92
+ AUTO_OPTION = "--auto"
93
+ ALL_AUTO_FLAG_VALUE_PREFIXES = (AUTO_OPTION + "=", DISABLE_AUTO_OPTION + "=")
94
+ END_OF_OPTIONS_WORD = "--"
95
+ SHORT_OPTION_PREFIX = "-"
96
+ GH_PR_MERGE_CALL_PATTERN = re.compile(r"\bgh(?:\.exe)?\s+pr\s+merge\b")
97
+ GH_PROGRAM_WORD_PATTERN = re.compile(r"(?:^|[/\\])gh(?:\.exe)?$")
98
+ ALL_GH_PR_MERGE_SUBCOMMAND_WORDS = ("pr", "merge")
99
+ SHELL_PUNCTUATION_CHARACTERS = "();<>|&`\n"
100
+ SHELL_WHITESPACE_CHARACTERS = " \t\r"
101
+ SHELL_WORD_SEPARATOR = " "
102
+ SHELL_QUOTED_TEXT_PATTERN = re.compile(r"\\.|'[^']*'|\"(?:\\.|[^\"\\])*\"", re.DOTALL)
103
+ SHELL_QUOTED_TEXT_PLACEHOLDER = "_"
104
+ SHELL_COMMENT_START_PATTERN = re.compile(r"(?:^|[\s();<>|&`])#")
78
105
 
79
106
  EXEMPT_REPOSITORIES_ENVIRONMENT_VARIABLE = "CLAUDE_MERGE_REVIEW_EXEMPT_REPOSITORIES"
80
107
  REVIEW_COMMAND_ENVIRONMENT_VARIABLE = "CLAUDE_MERGE_REVIEW_COMMAND"
@@ -13,8 +13,11 @@ GH_PROGRAM_NAME = "gh"
13
13
  GH_API_SUBCOMMAND = "api"
14
14
  GH_JQ_OPTION = "--jq"
15
15
  PULL_REQUEST_ENDPOINT_TEMPLATE = "repos/{owner}/{repository}/pulls/{number}"
16
- PULL_REQUEST_STATE_QUERY = ".state"
16
+ PULL_REQUEST_STATE_QUERY = '.state + " " + .head.sha'
17
+ STATE_AND_HEAD_SEPARATOR = " "
17
18
  OPEN_PULL_REQUEST_STATE = "open"
19
+ HEAD_FIELD = "head"
20
+ URL_FIELD = "url"
18
21
  STATE_QUERY_TIMEOUT_SECONDS = 10
19
22
  LOOKUP_FAILURE_TEMPLATE = "owned_pr_merge_stop_gate: could not read {endpoint}: {detail}\n"
20
23
  BLOCKED_LINE_PATTERN: re.Pattern[str] = re.compile(
@@ -56,6 +56,8 @@ __all__ = [
56
56
  "REVIEW_LOOP_CONTEXT_TEMPLATE",
57
57
  "SESSION_RECORD_FILE_TEMPLATE",
58
58
  "SESSION_RECORD_TEMPORARY_PREFIX",
59
+ "STOP_BLOCK_RECORD_FILE_TEMPLATE",
60
+ "STOP_BLOCK_RECORD_TEMPORARY_PREFIX",
59
61
  "ALL_PULL_REQUEST_FIELD_NAMES",
60
62
  ]
61
63
 
@@ -116,6 +118,8 @@ JSON_OBJECT_OPENER: str = "{"
116
118
 
117
119
  SESSION_RECORD_FILE_TEMPLATE: str = "owned-pr-loop-{session_file_id}.json"
118
120
  SESSION_RECORD_TEMPORARY_PREFIX: str = "owned-pr-loop-"
121
+ STOP_BLOCK_RECORD_FILE_TEMPLATE: str = "owned-pr-stop-blocks-{session_file_id}.json"
122
+ STOP_BLOCK_RECORD_TEMPORARY_PREFIX: str = "owned-pr-stop-blocks-"
119
123
  ALL_PULL_REQUEST_FIELD_NAMES: tuple[str, ...] = ("owner", "repository", "number", "url")
120
124
 
121
125
  REVIEW_LOOP_CONTEXT_TEMPLATE: str = (