claude-dev-env 8.111.5 → 8.112.1

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 (53) hide show
  1. package/.agents/skills/build-eval/evals/review/README.md +2 -2
  2. package/.agents/skills/build-eval/evals/review/review_eval_support/account.py +166 -0
  3. package/.agents/skills/build-eval/evals/review/review_eval_support/config/constants.py +26 -0
  4. package/.agents/skills/build-eval/evals/review/review_eval_support/execution.py +8 -0
  5. package/.agents/skills/build-eval/evals/review/test_run.py +261 -0
  6. package/_shared/advisor/reference/astra-rung.md +13 -5
  7. package/_shared/advisor/scripts/codex_astra_advisor.py +31 -8
  8. package/_shared/advisor/scripts/codex_astra_preflight.py +70 -14
  9. package/_shared/advisor/scripts/config/advisor_scripts_constants/astra_advisor_constants.py +7 -0
  10. package/_shared/advisor/scripts/tests/test_codex_astra_advisor.py +266 -2
  11. package/_shared/advisor/scripts/tests/test_codex_astra_preflight.py +114 -8
  12. package/_shared/pr-loop/scripts/check_convergence.py +5 -1
  13. package/_shared/pr-loop/scripts/codex_review_account.py +180 -0
  14. package/_shared/pr-loop/scripts/codex_review_scripts_constants/account_constants.py +28 -0
  15. package/_shared/pr-loop/scripts/codex_review_scripts_constants/run_constants.py +3 -1
  16. package/_shared/pr-loop/scripts/run_codex_review.py +144 -15
  17. package/_shared/pr-loop/scripts/test_check_convergence_codex.py +3 -3
  18. package/_shared/pr-loop/scripts/test_codex_review_account.py +355 -0
  19. package/_shared/pr-loop/scripts/test_run_codex_review.py +507 -6
  20. package/docs/account-broker.md +5 -3
  21. package/docs/codex-accounts.md +57 -16
  22. package/docs/rule-guides/question-presentation.md +4 -0
  23. package/hooks/blocking/final_reply_gate.py +59 -3
  24. package/hooks/blocking/open_tasks_transcript.py +18 -0
  25. package/hooks/blocking/test_final_reply_gate.py +160 -0
  26. package/hooks/features/conduct-gates.md +1 -4
  27. package/hooks/hooks.json +0 -10
  28. package/hooks/hooks_constants/final_reply_gate_constants.py +16 -0
  29. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +9 -0
  30. package/package.json +1 -1
  31. package/rules/question-presentation.md +1 -1
  32. package/scripts/Sync-RepoMain.ps1 +86 -3
  33. package/scripts/account_broker.py +50 -25
  34. package/scripts/account_broker_support.py +54 -3
  35. package/scripts/codex_account_choice.py +12 -8
  36. package/scripts/codex_account_chooser.py +110 -0
  37. package/scripts/codex_account_meters.py +43 -4
  38. package/scripts/codex_plan_rules.py +156 -0
  39. package/scripts/dev_env_scripts_constants/account_broker_constants.py +29 -42
  40. package/scripts/dev_env_scripts_constants/codex_account_constants.py +62 -2
  41. package/scripts/dev_env_scripts_constants/test_account_broker_constants.py +359 -2
  42. package/scripts/dev_env_scripts_constants/test_codex_account_constants.py +213 -14
  43. package/scripts/policy_lint/adapter_configuration.py +0 -5
  44. package/scripts/policy_lint/config/constants.py +0 -1
  45. package/scripts/test_account_broker.py +1756 -523
  46. package/scripts/test_account_broker_support.py +77 -0
  47. package/scripts/test_codex_account_meters.py +95 -0
  48. package/scripts/tests/Sync-RepoMain.Tests.ps1 +55 -0
  49. package/scripts/tests/test_adapter_configuration.py +0 -8
  50. package/scripts/tests/test_sync_repo_main_mirror.py +60 -0
  51. package/hooks/blocking/merge_over_review_offer_gate.py +0 -114
  52. package/hooks/blocking/test_merge_over_review_offer_gate.py +0 -138
  53. package/hooks/hooks_constants/merge_over_review_offer_gate_constants.py +0 -34
@@ -294,12 +294,65 @@ def test_should_read_codex_meters_through_injected_reader(
294
294
  assert meters.plan_type == "promax"
295
295
 
296
296
 
297
+ def test_should_carry_the_codex_credits_into_the_meters(
298
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
299
+ ) -> None:
300
+ usage = CodexAccountMeters(
301
+ (UsageWindow(None, 99.0, None),),
302
+ plan_type="prolite",
303
+ has_credits=True,
304
+ is_credits_unlimited=False,
305
+ credit_balance=83600.8856485,
306
+ )
307
+ monkeypatch.setattr(support.codex_account_meters, "resolve_codex_path", lambda _: tmp_path / "codex")
308
+ monkeypatch.setattr(support.codex_account_meters, "read_codex_meters", lambda *_: usage)
309
+
310
+ meters = support.read_codex_account_meters(Account(Product.CODEX, "personal", tmp_path))
311
+
312
+ assert meters.plan_type == "prolite"
313
+ assert meters.has_credits is True
314
+ assert meters.is_credits_unlimited is False
315
+ assert meters.credit_balance == 83600.8856485
316
+ assert meters.has_spendable_credits is True
317
+
318
+
297
319
  def test_should_keep_the_plan_through_the_cached_meter_payload() -> None:
298
320
  meters = Meters(80.0, None, 70.0, None, "pro")
299
321
 
300
322
  assert support._meters_from_payload(support._meter_payload(meters)) == meters
301
323
 
302
324
 
325
+ def test_should_keep_the_credits_through_the_cached_meter_payload() -> None:
326
+ meters = Meters(None, None, 1.0, None, "prolite", True, False, 83600.8856485)
327
+ unlimited_meters = Meters(None, None, 1.0, None, "pro", False, True, None)
328
+
329
+ assert support._meters_from_payload(support._meter_payload(meters)) == meters
330
+ assert support._meters_from_payload(support._meter_payload(unlimited_meters)) == unlimited_meters
331
+
332
+
333
+ def test_should_report_the_credits_in_the_meter_payload() -> None:
334
+ payload = support._meter_payload(Meters(None, None, 1.0, None, "prolite", True, False, 12.5))
335
+
336
+ assert payload["has_credits"] is True
337
+ assert payload["is_credits_unlimited"] is False
338
+ assert payload["credit_balance"] == 12.5
339
+
340
+
341
+ def test_should_read_a_cached_meter_payload_with_bad_credit_fields_as_no_credits() -> None:
342
+ bad_payload = {
343
+ "session_percent_left": 80.0,
344
+ "session_resets_at": None,
345
+ "weekly_percent_left": 70.0,
346
+ "weekly_resets_at": None,
347
+ "plan_type": "pro",
348
+ "has_credits": "yes",
349
+ "is_credits_unlimited": 1,
350
+ "credit_balance": "12.5",
351
+ }
352
+
353
+ assert support._meters_from_payload(bad_payload) == Meters(80.0, None, 70.0, None, "pro")
354
+
355
+
303
356
  def test_should_load_a_cached_meter_payload_saved_without_a_plan() -> None:
304
357
  old_payload = {"session_percent_left": 80.0, "session_resets_at": None, "weekly_percent_left": 70.0, "weekly_resets_at": None}
305
358
 
@@ -923,3 +976,27 @@ def test_should_find_the_cli_in_the_local_bin_folder(monkeypatch: pytest.MonkeyP
923
976
  monkeypatch.setattr(support.Path, "home", classmethod(lambda cls: tmp_path))
924
977
 
925
978
  assert support.resolve_claude_path() == local_claude
979
+
980
+
981
+ @pytest.mark.parametrize("blank_home", ("", " ", "\t", " \t \n"))
982
+ def test_should_take_the_home_directory_default_when_codex_home_is_blank(
983
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, blank_home: str
984
+ ) -> None:
985
+ monkeypatch.setattr(support.Path, "home", classmethod(lambda cls: tmp_path))
986
+ monkeypatch.setenv("CODEX_HOME", blank_home)
987
+
988
+ account = support.codex_default_account()
989
+
990
+ assert account.home == (tmp_path / ".codex").resolve()
991
+ assert account.name == "default"
992
+
993
+
994
+ def test_should_read_the_exported_codex_home_without_its_padding(
995
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
996
+ ) -> None:
997
+ exported_home = tmp_path / "exported-home"
998
+ monkeypatch.setenv("CODEX_HOME", f" {exported_home} ")
999
+
1000
+ account = support.codex_default_account()
1001
+
1002
+ assert account.home == exported_home.resolve()
@@ -75,6 +75,101 @@ class TestParseRateLimitsReply:
75
75
  meters = parse_rate_limits_reply(reply_line({"primary": {"usedPercent": 40}}))
76
76
  assert meters.plan_type is None
77
77
 
78
+ def should_read_the_credits_beside_the_windows(self) -> None:
79
+ meters = parse_rate_limits_reply(
80
+ reply_line(
81
+ {
82
+ "primary": {"usedPercent": 40},
83
+ "credits": {
84
+ "hasCredits": True,
85
+ "unlimited": False,
86
+ "balance": "83600.8856485000",
87
+ },
88
+ }
89
+ )
90
+ )
91
+ assert meters.has_credits is True
92
+ assert meters.is_credits_unlimited is False
93
+ assert meters.credit_balance == pytest.approx(83600.8856485)
94
+
95
+ def should_read_unlimited_credits(self) -> None:
96
+ meters = parse_rate_limits_reply(
97
+ reply_line(
98
+ {
99
+ "primary": {"usedPercent": 40},
100
+ "credits": {"hasCredits": False, "unlimited": True, "balance": None},
101
+ }
102
+ )
103
+ )
104
+ assert meters.is_credits_unlimited is True
105
+ assert meters.has_credits is False
106
+ assert meters.credit_balance is None
107
+
108
+ @pytest.mark.parametrize(
109
+ "raw_credits",
110
+ [
111
+ None,
112
+ {},
113
+ "none",
114
+ [],
115
+ {"hasCredits": False, "unlimited": False, "balance": None},
116
+ ],
117
+ )
118
+ def should_read_no_credits_when_the_reply_names_none(self, raw_credits: object) -> None:
119
+ meters = parse_rate_limits_reply(
120
+ reply_line({"primary": {"usedPercent": 40}, "credits": raw_credits})
121
+ )
122
+ assert meters.has_credits is False
123
+ assert meters.is_credits_unlimited is False
124
+ assert meters.credit_balance is None
125
+
126
+ def should_read_a_reply_without_a_credits_object(self) -> None:
127
+ meters = parse_rate_limits_reply(reply_line({"primary": {"usedPercent": 40}}))
128
+ assert meters.has_credits is False
129
+ assert meters.is_credits_unlimited is False
130
+ assert meters.credit_balance is None
131
+
132
+ @pytest.mark.parametrize(
133
+ ("raw_balance", "expected_balance"),
134
+ [
135
+ ("12.5", 12.5),
136
+ (7, 7.0),
137
+ (7.25, 7.25),
138
+ (" 3 ", 3.0),
139
+ ("0", 0.0),
140
+ ("abc", None),
141
+ ("nan", None),
142
+ ("inf", None),
143
+ (True, None),
144
+ ([], None),
145
+ ],
146
+ )
147
+ def should_read_the_balance_as_a_finite_number(
148
+ self, raw_balance: object, expected_balance: float | None
149
+ ) -> None:
150
+ meters = parse_rate_limits_reply(
151
+ reply_line(
152
+ {
153
+ "primary": {"usedPercent": 40},
154
+ "credits": {"hasCredits": True, "balance": raw_balance},
155
+ }
156
+ )
157
+ )
158
+ assert meters.credit_balance == expected_balance
159
+
160
+ @pytest.mark.parametrize("raw_flag", ["true", 1, "yes", None])
161
+ def should_count_only_a_json_true_as_a_credits_flag(self, raw_flag: object) -> None:
162
+ meters = parse_rate_limits_reply(
163
+ reply_line(
164
+ {
165
+ "primary": {"usedPercent": 40},
166
+ "credits": {"hasCredits": raw_flag, "unlimited": raw_flag},
167
+ }
168
+ )
169
+ )
170
+ assert meters.has_credits is False
171
+ assert meters.is_credits_unlimited is False
172
+
78
173
  def should_clamp_used_percent_past_full(self) -> None:
79
174
  meters = parse_rate_limits_reply(reply_line({"primary": {"usedPercent": 130}}))
80
175
  assert [each.used_percent for each in meters.all_windows] == [100.0]
@@ -86,6 +86,23 @@ BeforeAll {
86
86
  Invoke-TestGit -RepoPath $Fixture.MirrorPath -Arguments @('commit', '-q', '-am', 'feature edit') | Out-Null
87
87
  return Invoke-TestGit -RepoPath $Fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')
88
88
  }
89
+
90
+ function New-MirrorDivergedFromRemote {
91
+ <#
92
+ Builds the mirror from New-MirrorBehindRemote, then commits local-only.txt
93
+ on the mirror's main. The mirror then holds a commit the remote lacks and
94
+ misses the remote's newer commit, the way a mirror looks after the remote
95
+ history was rewritten.
96
+ #>
97
+ param([string]$Name)
98
+ $fixture = New-MirrorBehindRemote -Name $Name
99
+ Write-TestFile -RepoPath $fixture.MirrorPath -RelativePath 'local-only.txt' -Content "local commit`n"
100
+ Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('add', '-A') | Out-Null
101
+ Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('commit', '-q', '-m', 'local only') | Out-Null
102
+ $localTip = Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')
103
+ $fixture | Add-Member -NotePropertyName LocalTip -NotePropertyValue $localTip
104
+ return $fixture
105
+ }
89
106
  }
90
107
 
91
108
  Describe 'Sync-RepoMain' {
@@ -149,6 +166,44 @@ Describe 'Sync-RepoMain' {
149
166
  [System.IO.File]::ReadAllText((Join-Path $fixture.MirrorPath 'tracked.txt')) | Should -Be "new`n"
150
167
  }
151
168
 
169
+ It 'refuses a diverged tree with exit 4 when -Mirror is absent' {
170
+ $fixture = New-MirrorDivergedFromRemote -Name 'diverged-no-mirror'
171
+
172
+ $exitCode = Invoke-SyncScript -Fixture $fixture
173
+
174
+ $exitCode | Should -Be 4
175
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')) | Should -Be $fixture.LocalTip
176
+ }
177
+
178
+ It 'realigns a diverged mirror onto the remote tip and stashes a tracked file that differs' {
179
+ $fixture = New-MirrorDivergedFromRemote -Name 'diverged-mirror'
180
+ Write-TestFile -RepoPath $fixture.MirrorPath -RelativePath 'tracked.txt' -Content "local edit`n"
181
+ $backupRef = 'refs/mirror-backup/{0}-{1}' -f (Get-Date -Format 'yyyy-MM-dd'), $fixture.LocalTip.Substring(0, 12)
182
+
183
+ $exitCode = Invoke-MirrorSyncScript -Fixture $fixture
184
+
185
+ $exitCode | Should -Be 0
186
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')) | Should -Be $fixture.RemoteTip
187
+ [System.IO.File]::ReadAllText((Join-Path $fixture.MirrorPath 'tracked.txt')) | Should -Be "new`n"
188
+ [System.IO.File]::ReadAllText((Join-Path $fixture.MirrorPath 'added.txt')) | Should -Be "added`n"
189
+ [System.IO.File]::ReadAllText((Join-Path $fixture.MirrorPath 'local-only.txt')) | Should -Be "local commit`n"
190
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', $backupRef)) | Should -Be $fixture.LocalTip
191
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('stash', 'list')) | Should -Match 'mirror realign'
192
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('show', 'stash@{0}:tracked.txt')) | Should -Be 'local edit'
193
+ }
194
+
195
+ It 'keeps the old tip when the index holds staged changes during a realign' {
196
+ $fixture = New-MirrorDivergedFromRemote -Name 'diverged-staged'
197
+ Write-TestFile -RepoPath $fixture.MirrorPath -RelativePath 'tracked.txt' -Content "staged edit`n"
198
+ Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('add', 'tracked.txt') | Out-Null
199
+
200
+ $exitCode = Invoke-MirrorSyncScript -Fixture $fixture
201
+
202
+ $exitCode | Should -Be 1
203
+ (Invoke-TestGit -RepoPath $fixture.MirrorPath -Arguments @('rev-parse', 'HEAD')) | Should -Be $fixture.LocalTip
204
+ (Get-Content -LiteralPath $fixture.LogPath -Raw) | Should -Match 'realign skipped: the index holds staged changes'
205
+ }
206
+
152
207
  It 'skips without fetching while another sync of the same repo holds the run lock' {
153
208
  $fixture = New-MirrorBehindRemote -Name 'lock-held'
154
209
  $lockPath = [System.IO.Path]::TrimEndingDirectorySeparator([System.IO.Path]::GetFullPath($fixture.MirrorPath))
@@ -74,14 +74,6 @@ def test_new_turn_review_gate_registration_is_clean(tmp_path: Path) -> None:
74
74
  assert adapters.hook_configuration_diagnostics(current_document, tmp_path) == ()
75
75
 
76
76
 
77
- def test_new_merge_offer_gate_registration_is_clean(tmp_path: Path) -> None:
78
- current_document = _hook_document(
79
- ["hooks/blocking/merge_over_review_offer_gate.py"],
80
- '{"hooks": {}}',
81
- )
82
- assert adapters.hook_configuration_diagnostics(current_document, tmp_path) == ()
83
-
84
-
85
77
  def test_new_final_reply_gate_registration_is_clean(tmp_path: Path) -> None:
86
78
  current_document = _hook_document(
87
79
  ["hooks/blocking/final_reply_gate.py"],
@@ -11,6 +11,7 @@ _PWSH = shutil.which("pwsh") or "pwsh"
11
11
  _SKIPPED_EXIT_CODE = 3
12
12
  _SUCCESS_EXIT_CODE = 0
13
13
  _FAILURE_EXIT_CODE = 1
14
+ _DIVERGED_EXIT_CODE = 4
14
15
 
15
16
 
16
17
  def _git(repository_path: Path, *arguments: str) -> str:
@@ -74,6 +75,21 @@ def _mirror_on_feature_branch_behind_remote(
74
75
  return mirror_path, feature_tip, remote_tip
75
76
 
76
77
 
78
+ def _mirror_diverged_from_remote(root_path: Path) -> tuple[Path, str, str]:
79
+ mirror_path, _, _ = _mirror_on_feature_branch_behind_remote(
80
+ root_path, should_advance_remote=False
81
+ )
82
+ _git(mirror_path, "switch", "-q", "main")
83
+ (mirror_path / "tracked.txt").write_text("local\n", encoding="utf-8")
84
+ _git(mirror_path, "commit", "-q", "-am", "local only edit")
85
+ local_tip = _git(mirror_path, "rev-parse", "HEAD")
86
+ author_path = root_path / "author"
87
+ (author_path / "tracked.txt").write_text("new\n", encoding="utf-8")
88
+ _git(author_path, "commit", "-q", "-am", "second")
89
+ _git(author_path, "push", "-q", "origin", "main")
90
+ return mirror_path, local_tip, _git(author_path, "rev-parse", "HEAD")
91
+
92
+
77
93
  def _run_sync(mirror_path: Path, log_path: Path, *switches: str) -> int:
78
94
  completed = subprocess.run(
79
95
  [
@@ -224,3 +240,47 @@ def test_should_skip_a_checkout_with_staged_changes(tmp_path: Path) -> None:
224
240
  assert _git(mirror_path, "branch", "--show-current") == "feature"
225
241
  assert _git(mirror_path, "rev-parse", "HEAD") == feature_tip
226
242
  assert _git(mirror_path, "diff", "--cached", "--name-only") == "tracked.txt"
243
+
244
+
245
+ def test_should_exit_diverged_without_mirror(tmp_path: Path) -> None:
246
+ mirror_path, local_tip, _ = _mirror_diverged_from_remote(tmp_path)
247
+ log_path = tmp_path / "sync.log"
248
+
249
+ assert _run_sync(mirror_path, log_path, "-StashDirty") == _DIVERGED_EXIT_CODE
250
+ assert _git(mirror_path, "rev-parse", "HEAD") == local_tip
251
+ assert _git(mirror_path, "for-each-ref", "refs/mirror-backup") == ""
252
+
253
+
254
+ def test_should_realign_a_diverged_mirror_onto_the_remote(tmp_path: Path) -> None:
255
+ mirror_path, local_tip, remote_tip = _mirror_diverged_from_remote(tmp_path)
256
+ log_path = tmp_path / "sync.log"
257
+
258
+ assert (
259
+ _run_sync(mirror_path, log_path, "-StashDirty", "-Mirror")
260
+ == _SUCCESS_EXIT_CODE
261
+ )
262
+ assert _git(mirror_path, "rev-parse", "HEAD") == remote_tip
263
+ assert (mirror_path / "tracked.txt").read_text(encoding="utf-8") == "new\n"
264
+ assert _git(mirror_path, "status", "--porcelain") == ""
265
+ assert (
266
+ _git(mirror_path, "for-each-ref", "refs/mirror-backup", "--format=%(objectname)")
267
+ == local_tip
268
+ )
269
+ assert f"tree before moving {local_tip}" in _git(mirror_path, "stash", "list")
270
+ assert "realigning the mirror" in log_path.read_text(encoding="utf-8")
271
+
272
+
273
+ def test_should_skip_a_diverged_mirror_with_tracked_changes_without_stash_dirty(
274
+ tmp_path: Path,
275
+ ) -> None:
276
+ mirror_path, local_tip, _ = _mirror_diverged_from_remote(tmp_path)
277
+ (mirror_path / "tracked.txt").write_text("staged\n", encoding="utf-8")
278
+ _git(mirror_path, "add", "tracked.txt")
279
+ log_path = tmp_path / "sync.log"
280
+
281
+ assert _run_sync(mirror_path, log_path, "-Mirror") == _SKIPPED_EXIT_CODE
282
+ assert _git(mirror_path, "rev-parse", "HEAD") == local_tip
283
+ assert _git(mirror_path, "for-each-ref", "refs/mirror-backup") == ""
284
+ assert "tracked changes present; refusing sync" in log_path.read_text(
285
+ encoding="utf-8"
286
+ )
@@ -1,114 +0,0 @@
1
- """Deny a decision card or question that offers a merge over open review findings."""
2
-
3
- from __future__ import annotations
4
-
5
- import sys
6
- from pathlib import Path
7
-
8
- hooks_directory = str(Path(__file__).resolve().parent.parent)
9
- if hooks_directory not in sys.path:
10
- sys.path.insert(0, hooks_directory)
11
-
12
- from hooks_constants.hook_specific_output_keys import (
13
- HOOK_EVENT_NAME_KEY,
14
- HOOK_SPECIFIC_OUTPUT_KEY,
15
- PERMISSION_DECISION_KEY,
16
- )
17
- from hooks_constants.merge_over_review_offer_gate_constants import (
18
- ALL_CARD_TEXT_FIELDS,
19
- ALL_OPTION_TEXT_FIELDS,
20
- CLEAN_REVIEW_PATTERN,
21
- DENY_DECISION,
22
- HOOK_EVENT_NAME,
23
- MERGE_OFFER_PATTERN,
24
- MERGE_OVER_REVIEW_OFFER_REASON,
25
- OPEN_REVIEW_PATTERN,
26
- OPTIONS_FIELD,
27
- PERMISSION_DECISION_REASON_KEY,
28
- QUESTIONS_FIELD,
29
- TEXT_SEPARATOR,
30
- TOOL_INPUT_KEY,
31
- )
32
- from hooks_constants.pre_tool_use_stdin import print_decision_from_stdin
33
-
34
-
35
- def _one_option_text(each_option: object) -> str:
36
- if isinstance(each_option, dict):
37
- return TEXT_SEPARATOR.join(
38
- str(each_option.get(each_field, "")) for each_field in ALL_OPTION_TEXT_FIELDS
39
- )
40
- return str(each_option)
41
-
42
-
43
- def _block_texts(block_by_key: dict[str, object]) -> list[str]:
44
- all_texts = [str(block_by_key.get(each_field, "")) for each_field in ALL_CARD_TEXT_FIELDS]
45
- all_options = block_by_key.get(OPTIONS_FIELD)
46
- if isinstance(all_options, list):
47
- all_texts.extend(_one_option_text(each_option) for each_option in all_options)
48
- return all_texts
49
-
50
-
51
- def _card_text(card_by_key: dict[str, object]) -> str:
52
- all_questions = card_by_key.get(QUESTIONS_FIELD)
53
- if not isinstance(all_questions, list):
54
- all_questions = []
55
- all_blocks = [card_by_key] + [
56
- each_question for each_question in all_questions if isinstance(each_question, dict)
57
- ]
58
- return TEXT_SEPARATOR.join(
59
- each_text for each_block in all_blocks for each_text in _block_texts(each_block)
60
- )
61
-
62
-
63
- def offers_merge_over_review(card_by_key: dict[str, object]) -> bool:
64
- """Return whether a card offers a merge while it names open review findings.
65
-
66
- The whole card is read as one text: every question, header, context,
67
- reason, and option, across both card shapes, an ``ask_decision`` card and
68
- an ``AskUserQuestion`` questions list.
69
-
70
- ::
71
-
72
- option "Merge now", context "9 findings remain" -> True
73
- question 1 "The review reports 9 findings.",
74
- question 2 "Merge it now?" with "Yes" / "No" -> True
75
- context "I can merge it now, but 9 findings remain." -> True
76
- option "Join the merge queue", context "9 findings" -> True
77
- context "The merge review check reports 11 findings",
78
- options "Keep fixing" / "Split it" -> False
79
- option "Merge", context "the review found no findings" -> False
80
-
81
- Args:
82
- card_by_key: The card's tool input.
83
- """
84
- card_text = _card_text(card_by_key)
85
- if not MERGE_OFFER_PATTERN.search(card_text):
86
- return False
87
- return OPEN_REVIEW_PATTERN.search(CLEAN_REVIEW_PATTERN.sub("", card_text)) is not None
88
-
89
-
90
- def decision_for(payload_by_key: dict[str, object]) -> dict[str, object] | None:
91
- """Return a deny for a card that offers a merge over open findings, else None.
92
-
93
- Args:
94
- payload_by_key: The parsed PreToolUse input.
95
- """
96
- card_by_key = payload_by_key.get(TOOL_INPUT_KEY)
97
- if not isinstance(card_by_key, dict) or not offers_merge_over_review(card_by_key):
98
- return None
99
- return {
100
- HOOK_SPECIFIC_OUTPUT_KEY: {
101
- HOOK_EVENT_NAME_KEY: HOOK_EVENT_NAME,
102
- PERMISSION_DECISION_KEY: DENY_DECISION,
103
- PERMISSION_DECISION_REASON_KEY: MERGE_OVER_REVIEW_OFFER_REASON,
104
- }
105
- }
106
-
107
-
108
- def main() -> int:
109
- """Read one payload, print a deny when needed, and exit zero."""
110
- return print_decision_from_stdin(decision_for)
111
-
112
-
113
- if __name__ == "__main__":
114
- sys.exit(main())
@@ -1,138 +0,0 @@
1
- """Behavior tests for the merge-over-review decision card gate."""
2
-
3
- import json
4
- import subprocess
5
- import sys
6
- from pathlib import Path
7
-
8
- HOOKS_DIRECTORY = Path(__file__).resolve().parent.parent
9
- if str(HOOKS_DIRECTORY) not in sys.path:
10
- sys.path.insert(0, str(HOOKS_DIRECTORY))
11
-
12
- from blocking import merge_over_review_offer_gate as gate
13
-
14
- GATE_SCRIPT = Path(gate.__file__)
15
-
16
-
17
- def _card(context: str, *options: tuple[str, str]) -> dict[str, object]:
18
- return {
19
- "question": "What next for the pull request?",
20
- "context": context,
21
- "options": [{"label": label, "consequence": consequence} for label, consequence in options],
22
- }
23
-
24
-
25
- def test_merge_option_over_open_findings_should_be_offered_over_review() -> None:
26
- card = _card("The review found 9 findings.", ("Merge now", "It lands today."), ("Keep looping", "I rerun."))
27
- assert gate.offers_merge_over_review(card)
28
-
29
-
30
- def test_merge_option_that_overrides_a_status_should_be_offered_over_review() -> None:
31
- card = _card("Tests pass.", ("Merge now", "You override the status."))
32
- assert gate.offers_merge_over_review(card)
33
-
34
-
35
- def test_card_without_a_merge_option_should_pass() -> None:
36
- card = _card("The review found 9 findings.", ("Keep looping", "I rerun."), ("Drop shell checks", "Smaller diff."))
37
- assert not gate.offers_merge_over_review(card)
38
-
39
-
40
- def test_merge_option_after_a_clean_review_should_pass() -> None:
41
- card = _card("The review pass on the head came back clean.", ("Merge", "It lands."), ("Hold", "It waits."))
42
- assert not gate.offers_merge_over_review(card)
43
-
44
-
45
- def test_merge_question_with_yes_no_options_over_unresolved_threads_should_be_offered_over_review() -> None:
46
- card = {"question": "Merge PR 41 now?", "context": "3 unresolved review threads.", "options": ["Yes", "No"]}
47
- assert gate.offers_merge_over_review(card)
48
-
49
-
50
- def test_string_options_should_be_read() -> None:
51
- card = {"question": "What next?", "context": "9 findings remain.", "options": ["Merge now", "Keep looping"]}
52
- assert gate.offers_merge_over_review(card)
53
-
54
-
55
- def test_merge_queue_option_over_findings_should_be_offered_over_review() -> None:
56
- card = _card("9 findings remain.", ("Join the merge queue", "It waits for checks."), ("Wait", "It waits."))
57
- assert gate.offers_merge_over_review(card)
58
-
59
-
60
- def test_merge_offer_in_context_over_findings_should_be_offered_over_review() -> None:
61
- card = {
62
- "question": "Go ahead?",
63
- "context": "The PR is green and I can merge it now, but the review reports 9 findings.",
64
- "options": ["Yes", "No"],
65
- }
66
- assert gate.offers_merge_over_review(card)
67
-
68
-
69
- def test_offer_and_findings_in_separate_questions_should_be_offered_over_review() -> None:
70
- card = {
71
- "questions": [
72
- {"question": "The review reports 9 findings. Which next?", "options": ["Keep fixing", "Split it"]},
73
- {"question": "Merge it now?", "options": ["Yes", "No"]},
74
- ]
75
- }
76
- assert gate.offers_merge_over_review(card)
77
-
78
-
79
- def test_merge_option_over_unaddressed_review_comments_should_be_offered_over_review() -> None:
80
- card = _card("3 review comments are unaddressed; 2 changes requested.", ("Merge now", "It lands."))
81
- assert gate.offers_merge_over_review(card)
82
-
83
-
84
- def test_ship_card_about_a_pending_translation_should_pass() -> None:
85
- card = {
86
- "question": "Ship the README update now? The pending translation can follow.",
87
- "options": ["Ship it", "Wait"],
88
- }
89
- assert not gate.offers_merge_over_review(card)
90
-
91
-
92
- def test_ask_user_question_merge_option_over_findings_should_be_offered_over_review() -> None:
93
- card = {
94
- "questions": [
95
- {
96
- "question": "The review failed with 2 findings. What next?",
97
- "header": "Next step",
98
- "options": [
99
- {"label": "Squash and merge", "description": "It lands now."},
100
- {"label": "Fix first", "description": "I fix both."},
101
- ],
102
- }
103
- ]
104
- }
105
- assert gate.offers_merge_over_review(card)
106
-
107
-
108
- def test_card_about_the_merge_review_check_without_a_merge_offer_should_pass() -> None:
109
- card = _card(
110
- "The Merge review check reports 11 findings.", ("Keep fixing", "I rerun."), ("Split the PR", "Smaller diff.")
111
- )
112
- assert not gate.offers_merge_over_review(card)
113
-
114
-
115
- def test_merge_option_after_a_review_with_no_findings_should_pass() -> None:
116
- card = _card("The review on the head found no findings.", ("Merge", "It lands."), ("Hold", "It waits."))
117
- assert not gate.offers_merge_over_review(card)
118
-
119
-
120
- def test_decision_for_should_return_none_for_a_clean_card() -> None:
121
- payload = {"tool_name": "AskUserQuestion", "tool_input": _card("All checks pass.", ("Merge", "It lands."))}
122
- assert gate.decision_for(payload) is None
123
-
124
-
125
- def test_script_should_print_a_deny_for_a_merge_over_findings_card() -> None:
126
- payload = {
127
- "tool_name": "mcp__hearthbot__ask_decision",
128
- "tool_input": _card("9 findings remain.", ("Merge now", "It lands.")),
129
- }
130
- completed = subprocess.run(
131
- [sys.executable, str(GATE_SCRIPT)],
132
- input=json.dumps(payload),
133
- capture_output=True,
134
- text=True,
135
- check=False,
136
- )
137
- assert completed.returncode == 0
138
- assert json.loads(completed.stdout)["hookSpecificOutput"]["permissionDecision"] == "deny"
@@ -1,34 +0,0 @@
1
- """Constants for the gate that keeps merge-over-review offers off decision cards."""
2
-
3
- import re
4
-
5
- TOOL_INPUT_KEY = "tool_input"
6
- HOOK_EVENT_NAME = "PreToolUse"
7
- DENY_DECISION = "deny"
8
- PERMISSION_DECISION_REASON_KEY = "permissionDecisionReason"
9
- ALL_CARD_TEXT_FIELDS = ("question", "header", "context", "reason")
10
- QUESTIONS_FIELD = "questions"
11
- OPTIONS_FIELD = "options"
12
- TEXT_SEPARATOR = " "
13
- ALL_OPTION_TEXT_FIELDS = ("label", "consequence", "description")
14
- MERGE_OFFER_PATTERN = re.compile(
15
- r"\b(?:merg(?:e|es|ing)|squash(?:es|ing)?|auto-merge)\b"
16
- r"(?!\s+(?:review|check|base|conflicts?|state|status|gate)\b)",
17
- re.IGNORECASE,
18
- )
19
- CLEAN_REVIEW_PATTERN = re.compile(
20
- r"\b(?:no|zero|0)\s+(?:open\s+|review\s+|blocking\s+)?(?:findings?|failures?|threads?|comments?)\b",
21
- re.IGNORECASE,
22
- )
23
- OPEN_REVIEW_PATTERN = re.compile(
24
- r"\b(?:findings?|override|red|failing|failed|failures?|not clean|unresolved|unaddressed"
25
- r"|changes requested|review comments?|open (?:review )?threads?|issues? (?:left|remain(?:ing)?)"
26
- r"|\d+ remaining)\b",
27
- re.IGNORECASE,
28
- )
29
- MERGE_OVER_REVIEW_OFFER_REASON = (
30
- "This card offers a merge while it names open review findings, a red check, or an"
31
- " override. A pull request merges only after a review pass on its head reports zero"
32
- " findings. Drop the merge offer, keep fixing and rerunning the review, and ask only"
33
- " about choices that keep that bar."
34
- )