claude-dev-env 8.117.2 → 8.117.4

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 (77) hide show
  1. package/_shared/pr-loop/scripts/pyproject.toml +1 -1
  2. package/_shared/process-tree/scripts/pyproject.toml +1 -1
  3. package/bin/cde.mjs +4 -3
  4. package/bin/cde.test.mjs +87 -1
  5. package/bin/codex-compat.mjs +4 -3
  6. package/bin/codex-compat.test.mjs +91 -1
  7. package/bin/install-plan.mjs +2 -1
  8. package/bin/install.mjs +24 -7
  9. package/bin/install.plan.test.mjs +15 -0
  10. package/bin/install.test.mjs +61 -0
  11. package/bin/python-probe.mjs +42 -0
  12. package/bin/python-probe.test.mjs +19 -2
  13. package/docs/rule-guides/features-start-with-an-eval.md +3 -3
  14. package/docs/rule-guides/proof-before-pull-request.md +2 -2
  15. package/hooks/blocking/bash_pre_tool_use_dispatcher.py +11 -4
  16. package/hooks/blocking/build_eval_before_eval_write_gate.py +10 -4
  17. package/hooks/blocking/followup_pr_dedupe.py +381 -64
  18. package/hooks/blocking/gate_child_process.py +187 -0
  19. package/hooks/blocking/gate_run_reads.py +116 -35
  20. package/hooks/blocking/merge_review_gate.py +93 -10
  21. package/hooks/blocking/merge_review_gate_parts/create_folders.py +346 -0
  22. package/hooks/blocking/merge_review_gate_parts/create_options.py +86 -0
  23. package/hooks/blocking/merge_review_gate_parts/folder_state.py +107 -0
  24. package/hooks/blocking/merge_review_gate_parts/open_request.py +199 -64
  25. package/hooks/blocking/merge_review_gate_parts/quoted_lines.py +283 -0
  26. package/hooks/blocking/merge_review_gate_parts/wrapped_creates.py +126 -0
  27. package/hooks/blocking/pr_lifecycle_skill_gate.py +61 -18
  28. package/hooks/blocking/pre_tool_use_dispatcher.py +25 -3
  29. package/hooks/blocking/pull_request_proof.py +5 -51
  30. package/hooks/blocking/pull_request_proof_edit_gate.py +19 -5
  31. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +54 -0
  32. package/hooks/blocking/test_build_eval_before_eval_write_gate.py +64 -0
  33. package/hooks/blocking/test_followup_pr_dedupe.py +464 -1
  34. package/hooks/blocking/test_gate_child_process.py +64 -0
  35. package/hooks/blocking/test_gate_run_reads.py +364 -4
  36. package/hooks/blocking/test_merge_review_gate.py +832 -39
  37. package/hooks/blocking/test_pr_lifecycle_skill_gate.py +130 -4
  38. package/hooks/blocking/test_pre_tool_use_dispatcher.py +64 -0
  39. package/hooks/blocking/test_pull_request_proof.py +16 -0
  40. package/hooks/blocking/test_pull_request_proof_edit_gate.py +60 -0
  41. package/hooks/blocking/tests/test_create_folders.py +290 -0
  42. package/hooks/blocking/tests/test_create_options.py +34 -0
  43. package/hooks/blocking/tests/test_folder_state.py +40 -0
  44. package/hooks/blocking/tests/test_open_request.py +350 -44
  45. package/hooks/blocking/tests/test_quoted_lines.py +86 -0
  46. package/hooks/blocking/tests/test_wrapped_creates.py +42 -0
  47. package/hooks/features/bash-dispatchers.md +1 -1
  48. package/hooks/features/conduct-gates.md +7 -7
  49. package/hooks/features/write-edit-blocking.md +3 -3
  50. package/hooks/hooks_constants/build_eval_before_eval_write_gate_constants.py +5 -0
  51. package/hooks/hooks_constants/followup_pr_dedupe_constants.py +34 -1
  52. package/hooks/hooks_constants/gate_fault.py +52 -0
  53. package/hooks/hooks_constants/gate_fault_constants.py +13 -0
  54. package/hooks/hooks_constants/gate_run_reads_constants.py +9 -1
  55. package/hooks/hooks_constants/merge_review_gate_constants.py +94 -1
  56. package/hooks/hooks_constants/piped_pytest_blocker_constants.py +2 -0
  57. package/hooks/hooks_constants/pr_lifecycle_skill_gate_constants.py +6 -1
  58. package/hooks/hooks_constants/pre_tool_use_stdin.py +23 -3
  59. package/hooks/hooks_constants/shell_command_pipeline.py +68 -8
  60. package/hooks/hooks_constants/shell_command_segments.py +2 -2
  61. package/hooks/hooks_constants/shell_command_wrappers.py +3 -2
  62. package/hooks/hooks_constants/test_followup_pr_dedupe_constants.py +7 -0
  63. package/hooks/hooks_constants/test_gate_fault.py +41 -0
  64. package/hooks/hooks_constants/test_piped_pytest_blocker_constants.py +5 -0
  65. package/hooks/hooks_constants/test_pr_lifecycle_skill_gate_constants.py +10 -0
  66. package/hooks/hooks_constants/test_pre_tool_use_stdin.py +97 -0
  67. package/hooks/hooks_constants/test_shell_command_pipeline.py +55 -0
  68. package/hooks/hooks_constants/test_shell_command_segments.py +15 -0
  69. package/hooks/hooks_constants/test_shell_command_wrappers.py +6 -0
  70. package/hooks/hooks_constants/transcript_skill_scan_constants.py +6 -0
  71. package/hooks/pyproject.toml +2 -3
  72. package/hooks/test_python_floor.py +197 -0
  73. package/hooks/test_transcript_skill_scan.py +324 -0
  74. package/hooks/transcript_skill_scan.py +233 -2
  75. package/hooks/validators/code_quality_checks.py +119 -17
  76. package/hooks/validators/test_code_quality_checks.py +110 -4
  77. package/package.json +1 -1
@@ -17,9 +17,18 @@ from blocking import followup_pr_dedupe as gate_dedupe
17
17
  from blocking import gate_run_reads
18
18
  from blocking import pr_lifecycle_skill_gate as gate
19
19
  from blocking.gate_run_reads import read_deadlines_started
20
- from hooks_constants.followup_pr_dedupe_constants import ALL_GIT_REMOTE_COMMAND_WORDS
21
- from hooks_constants.gate_run_reads_constants import PROOF_AND_LOOK_READS_SECONDS, READS_RAN_OUT_SENTENCE
22
- from hooks_constants.pr_lifecycle_skill_gate_constants import DENY_REASON
20
+ from hooks_constants.followup_pr_dedupe_constants import (
21
+ ALL_GIT_REMOTE_COMMAND_WORDS,
22
+ UNANSWERED_FOLLOWUP_REASON_TEMPLATE,
23
+ UNREAD_ORIGIN_FOLLOWUP_REASON_TEMPLATE,
24
+ )
25
+ from hooks_constants.gate_fault import gate_fault_reason
26
+ from hooks_constants.gate_run_reads_constants import (
27
+ FOLLOWUP_READS_SECONDS,
28
+ PROOF_AND_LOOK_READS_SECONDS,
29
+ READS_RAN_OUT_SENTENCE,
30
+ )
31
+ from hooks_constants.pr_lifecycle_skill_gate_constants import DENY_REASON, SCAN_RAN_OUT_SENTENCE
23
32
  from hooks_constants.pull_request_proof_constants import (
24
33
  MISSING_BUILD_EVAL_REASON,
25
34
  MISSING_PROOF_REASON,
@@ -233,6 +242,8 @@ def test_action_command_shapes(tmp_path: Path) -> None:
233
242
  "gh api graphql -f name=auto-merge",
234
243
  "echo done; gh pr edit",
235
244
  "GIT_TRACE=1 git push",
245
+ "GIT_TRACE+=1 git push",
246
+ "GH_REPO+=owner/repo gh pr create",
236
247
  "env -u GH_TOKEN gh pr merge 1",
237
248
  "env --unset=GH_TOKEN GH_HOST=github.com gh pr create",
238
249
  "sudo git push",
@@ -275,6 +286,25 @@ def test_wrapped_and_scripted_action_shapes_are_denied(tmp_path: Path) -> None:
275
286
  _assert_denied(_payload(command, path))
276
287
 
277
288
 
289
+ def test_every_create_spelling_the_shared_recognizer_reads_should_be_denied(tmp_path: Path) -> None:
290
+ path = _transcript(tmp_path)
291
+ commands = (
292
+ "gh pr new --fill",
293
+ "gh -R o/r pr create --fill",
294
+ "gh --repo=o/r pr create --fill",
295
+ "GH_REPO=o/r gh pr create --fill",
296
+ "python3.11 pull_request.py create",
297
+ "python3.13 pull_request.py create",
298
+ "python3 -u pull_request.py create",
299
+ "python -X dev pull_request.py create",
300
+ "py -3 pull_request.py create",
301
+ "uv run python pull_request.py create",
302
+ "uv run pull_request.py create",
303
+ )
304
+ for command in commands:
305
+ _assert_denied(_payload(command, path))
306
+
307
+
278
308
  def test_wrapped_and_scripted_non_action_shapes_are_allowed(tmp_path: Path) -> None:
279
309
  path = _transcript(tmp_path)
280
310
  commands = (
@@ -361,6 +391,21 @@ def test_loaded_skill_allows_a_followup_when_the_read_fails(tmp_path: Path) -> N
361
391
  assert gate.decision_for(payload) is None
362
392
 
363
393
 
394
+ def test_loaded_skill_denies_a_followup_when_the_read_gives_no_answer(tmp_path: Path) -> None:
395
+ payload = {
396
+ "tool_name": "mcp__github__create_pull_request",
397
+ "tool_input": {"owner": "jl-cmd", "repo": "claude-dev-env", "body": PROVEN_FOLLOWUP_BODY},
398
+ "transcript_path": str(_transcript(tmp_path, "pr-lifecycle")),
399
+ "cwd": _checkout_without_visible_changes(tmp_path),
400
+ }
401
+ with patch.object(gate_dedupe, "read_open_pull_requests", side_effect=TimeoutError("no answer")):
402
+ decision = gate.decision_for(payload)
403
+ assert decision is not None
404
+ assert decision["hookSpecificOutput"]["permissionDecisionReason"] == (
405
+ UNANSWERED_FOLLOWUP_REASON_TEMPLATE.format(owner="jl-cmd", repo="claude-dev-env", parent_number=1731)
406
+ )
407
+
408
+
364
409
  PICTURE_LINE = "![after](https://example.com/after.png)\n"
365
410
  CREATE_WORDS = " ".join(("gh", "pr", "create"))
366
411
 
@@ -394,7 +439,11 @@ def test_one_gate_run_should_read_the_origin_once_for_a_followup_body(
394
439
  ) -> None:
395
440
  all_asked_commands = _unstarted_children(monkeypatch)
396
441
  payload = _quoted_shell_create_without_repository(tmp_path, PROVEN_FOLLOWUP_BODY + PICTURE_LINE)
397
- assert gate.decision_for(payload) is None
442
+ decision = gate.decision_for(payload)
443
+ assert decision is not None
444
+ assert decision["hookSpecificOutput"]["permissionDecisionReason"] == (
445
+ UNREAD_ORIGIN_FOLLOWUP_REASON_TEMPLATE.format(parent_number=1731)
446
+ )
398
447
  assert _origin_reads(all_asked_commands) == 1
399
448
 
400
449
 
@@ -740,3 +789,80 @@ def test_write_run_through_a_wrapper_should_be_denied_without_the_skill(tmp_path
740
789
  path = _transcript(tmp_path)
741
790
  for each_command in WRAPPED_WRITE_COMMANDS:
742
791
  _assert_denied(_payload(each_command, path))
792
+
793
+
794
+ UNRELATED_LINE = json.dumps({"type": "user", "message": {"content": "Unrelated."}})
795
+ UNRELATED_LINE_COUNT = 30
796
+
797
+
798
+ class TickingClock:
799
+ """Moves one second forward on every read, starting at zero."""
800
+
801
+ def __init__(self) -> None:
802
+ self.seconds = -1.0
803
+
804
+ def __call__(self) -> float:
805
+ self.seconds += 1.0
806
+ return self.seconds
807
+
808
+
809
+ def test_skill_scan_cut_by_the_deadline_should_deny_with_the_scan_sentence(tmp_path: Path) -> None:
810
+ transcript_path = _transcript_with_lines(
811
+ tmp_path, "session.jsonl", [SKILL_LOAD_LINE, *[UNRELATED_LINE] * UNRELATED_LINE_COUNT]
812
+ )
813
+ with read_deadlines_started(TickingClock()):
814
+ decision = gate.decision_for(_payload("git push", transcript_path))
815
+ assert decision is not None
816
+ assert decision["hookSpecificOutput"]["permissionDecisionReason"] == DENY_REASON + SCAN_RAN_OUT_SENTENCE
817
+
818
+
819
+ def test_skill_scan_should_find_a_recent_load_before_the_deadline(tmp_path: Path) -> None:
820
+ transcript_path = _transcript_with_lines(
821
+ tmp_path, "session.jsonl", [*[UNRELATED_LINE] * UNRELATED_LINE_COUNT, SKILL_LOAD_LINE]
822
+ )
823
+ with read_deadlines_started(TickingClock()):
824
+ assert gate.decision_for(_payload("git push", transcript_path)) is None
825
+
826
+
827
+ def test_build_eval_scan_cut_by_the_deadline_should_deny_with_the_scan_sentence(
828
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
829
+ ) -> None:
830
+ clock = SettableClock()
831
+ is_feature_on_this_tree = gate.proof.is_feature_pull_request
832
+
833
+ def feature_check_that_spends_the_followup_slice(all_fields: dict[str, object]) -> bool:
834
+ clock.seconds = float(PROOF_AND_LOOK_READS_SECONDS + FOLLOWUP_READS_SECONDS)
835
+ return is_feature_on_this_tree(all_fields)
836
+
837
+ monkeypatch.setattr(gate.proof, "is_feature_pull_request", feature_check_that_spends_the_followup_slice)
838
+ transcript_path = _transcript_with_lines(tmp_path, "session.jsonl", [BUILD_EVAL_LINE, SKILL_LOAD_LINE])
839
+ payload = _create_payload(tmp_path, "feat: add a gate", transcript_path)
840
+ with read_deadlines_started(clock):
841
+ decision = gate.decision_for(payload)
842
+ assert decision is not None
843
+ assert decision["hookSpecificOutput"]["permissionDecisionReason"] == MISSING_BUILD_EVAL_REASON + SCAN_RAN_OUT_SENTENCE
844
+
845
+
846
+ def test_check_that_raises_should_deny_with_a_reason_that_names_the_error(
847
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
848
+ ) -> None:
849
+ def check_that_raises(all_fields: dict[str, object]) -> str | None:
850
+ raise KeyError("head")
851
+
852
+ monkeypatch.setattr(gate.proof, "missing_proof_reason", check_that_raises)
853
+ exit_code, output = _run_main(_payload("gh pr create --body 'Adds a gate.'", _transcript(tmp_path, "pr-lifecycle")))
854
+ assert exit_code == 0
855
+ reason = json.loads(output)["hookSpecificOutput"]["permissionDecisionReason"]
856
+ assert reason == gate_fault_reason("pull request lifecycle", KeyError("head"))
857
+ assert "KeyError" in reason
858
+
859
+
860
+ def test_fault_before_the_call_is_known_governed_should_not_become_a_deny(
861
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
862
+ ) -> None:
863
+ def matcher_that_raises(command: str) -> bool:
864
+ raise RuntimeError("matcher fault")
865
+
866
+ monkeypatch.setattr(gate, "_matches_shell_command", matcher_that_raises)
867
+ with pytest.raises(RuntimeError, match="matcher fault"):
868
+ gate.decision_for(_payload("ls", _transcript(tmp_path)))
@@ -41,6 +41,7 @@ from pre_tool_use_dispatcher import ( # noqa: E402, I001
41
41
  _emit_allow_decision,
42
42
  _emit_deny_decision,
43
43
  aggregate_hosted_hook_results,
44
+ dispatch,
44
45
  run_hosted_hook,
45
46
  unique_first_seen_strings,
46
47
  )
@@ -832,3 +833,66 @@ def test_hosted_hook_set_retains_boundaries_and_excludes_replaced_file_checks()
832
833
  assert not all_hosted_script_paths.intersection(ALL_RETIRED_PATHS)
833
834
  for each_relative_path in ALL_RETIRED_PATHS:
834
835
  assert (_HOOKS_ROOT / each_relative_path).is_file()
836
+
837
+
838
+ WRITE_FAULT_SYSTEM_MESSAGE = "fault_hook.py hit a fault and did not check this call"
839
+
840
+
841
+ def _hosted_entry_for(script_path: Path) -> HostedHookEntry:
842
+ return HostedHookEntry(
843
+ script_relative_path=str(script_path), applicable_tool_names=frozenset({WRITE_TOOL_NAME})
844
+ )
845
+
846
+
847
+ def test_dispatch_prints_a_system_message_alone_when_no_hook_decides(
848
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
849
+ ) -> None:
850
+ """A hosted hook's message with no deny and no allow reaches the user with no permissionDecision."""
851
+ fault_hook = tmp_path / "fault_hook.py"
852
+ fault_hook.write_text(
853
+ "import json\nprint(json.dumps({'systemMessage': " + repr(WRITE_FAULT_SYSTEM_MESSAGE) + "}))\n",
854
+ encoding="utf-8",
855
+ )
856
+ monkeypatch.setattr(
857
+ "pre_tool_use_dispatcher._select_applicable_hooks", lambda tool_name: [_hosted_entry_for(fault_hook)]
858
+ )
859
+ payload_text = _write_payload(str(tmp_path / "a.py"), "x = 1\n")
860
+ dispatch(payload_text, WRITE_TOOL_NAME, json.loads(payload_text))
861
+ all_lines = capsys.readouterr().out.splitlines()
862
+ assert [json.loads(each_line) for each_line in all_lines] == [{"systemMessage": WRITE_FAULT_SYSTEM_MESSAGE}]
863
+
864
+
865
+ def test_dispatch_prints_nothing_when_no_hook_decides_or_speaks(
866
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
867
+ ) -> None:
868
+ """A silent hosted hook leaves the dispatcher silent."""
869
+ silent_hook = tmp_path / "silent_hook.py"
870
+ silent_hook.write_text("", encoding="utf-8")
871
+ monkeypatch.setattr(
872
+ "pre_tool_use_dispatcher._select_applicable_hooks", lambda tool_name: [_hosted_entry_for(silent_hook)]
873
+ )
874
+ payload_text = _write_payload(str(tmp_path / "a.py"), "x = 1\n")
875
+ dispatch(payload_text, WRITE_TOOL_NAME, json.loads(payload_text))
876
+ assert capsys.readouterr().out == ""
877
+
878
+
879
+ def test_dispatch_denies_with_the_fault_reason_when_the_proof_edit_gate_check_raises(
880
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
881
+ ) -> None:
882
+ """A fault in the proof edit gate still refuses the write, as a crash did, and names the fault."""
883
+
884
+ def raise_transcript_fault(all_payload_fields: dict[str, object]) -> list[str]:
885
+ raise RuntimeError("transcript list broke")
886
+
887
+ monkeypatch.setattr("blocking.pr_lifecycle_skill_gate.transcript_paths", raise_transcript_fault)
888
+ proof_edit_entry = HostedHookEntry(
889
+ script_relative_path="blocking/pull_request_proof_edit_gate.py",
890
+ applicable_tool_names=frozenset({WRITE_TOOL_NAME}),
891
+ )
892
+ monkeypatch.setattr("pre_tool_use_dispatcher._select_applicable_hooks", lambda tool_name: [proof_edit_entry])
893
+ payload_text = _write_payload(str(tmp_path / "pull_request_proof.py"), "x = 1\n")
894
+ dispatch(payload_text, WRITE_TOOL_NAME, json.loads(payload_text))
895
+ hook_specific = json.loads(capsys.readouterr().out)["hookSpecificOutput"]
896
+ assert hook_specific["permissionDecision"] == DENY_DECISION
897
+ assert hook_specific["permissionDecisionReason"].startswith("The pull request proof edit gate hit a fault")
898
+ assert "RuntimeError: transcript list broke" in hook_specific["permissionDecisionReason"]
@@ -956,6 +956,22 @@ def test_is_create_call_should_name_shell_and_mcp_creates() -> None:
956
956
  assert not gate.is_create_call({"tool_name": "Read", "tool_input": {"file_path": "a.py"}})
957
957
 
958
958
 
959
+ @pytest.mark.parametrize(
960
+ "command",
961
+ [
962
+ "gh pr new --title t --body b",
963
+ "gh -R o/r pr create --title t --body b",
964
+ "GH_REPO=o/r gh pr create --title t --body b",
965
+ "python3.11 pull_request.py create --title t --body b",
966
+ "py -3 pull_request.py create --title t --body b",
967
+ "python -X dev pull_request.py create --title t --body b",
968
+ ],
969
+ )
970
+ def test_every_create_spelling_should_need_a_proof_section(command: str) -> None:
971
+ assert gate.is_create_call(_shell(command))
972
+ assert gate.missing_proof_reason(_shell(command)) == MISSING_PROOF_REASON
973
+
974
+
959
975
  WORKFLOW_DIRECTORY = ".github/workflows"
960
976
  NEW_WORKFLOW_NAME = "release-hold.yml"
961
977
  UNPROVEN_RUN_LINE = "Not proven here: the live GitHub Actions run."
@@ -1,14 +1,18 @@
1
1
  """Behavior tests for the gate that holds an edit to the proof gate until its named route is taken."""
2
2
 
3
+ import io
3
4
  import json
4
5
  import sys
5
6
  from pathlib import Path
6
7
 
8
+ import pytest
9
+
7
10
  HOOKS_DIRECTORY = Path(__file__).resolve().parent.parent
8
11
  if str(HOOKS_DIRECTORY) not in sys.path:
9
12
  sys.path.insert(0, str(HOOKS_DIRECTORY))
10
13
 
11
14
  from blocking import pull_request_proof_edit_gate as gate
15
+ from hooks_constants.gate_fault import gate_fault_reason
12
16
  from hooks_constants.pull_request_proof_constants import (
13
17
  GATE_EDIT_BEFORE_ROUTE_REASON,
14
18
  UNREADABLE_CHANGES_REASON,
@@ -197,3 +201,59 @@ def test_should_allow_an_apply_patch_the_patch_parser_cannot_resolve(tmp_path: P
197
201
  "transcript_path": _transcript(tmp_path, DENIED_CREATE_ENTRIES),
198
202
  }
199
203
  assert gate.gate_edit_reason(payload) is None
204
+
205
+
206
+ def _run_gate_main(
207
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], payload: dict[str, object]
208
+ ) -> tuple[int, str, str]:
209
+ monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(payload)))
210
+ exit_code = gate.main()
211
+ captured_streams = capsys.readouterr()
212
+ return exit_code, captured_streams.out, captured_streams.err
213
+
214
+
215
+ def test_should_deny_with_the_fault_reason_when_the_transcript_read_raises(
216
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
217
+ ) -> None:
218
+ def raise_transcript_fault(all_payload_fields: dict[str, object]) -> list[str]:
219
+ raise RuntimeError("transcript list broke")
220
+
221
+ monkeypatch.setattr(gate, "transcript_paths", raise_transcript_fault)
222
+ exit_code, standard_output, standard_error = _run_gate_main(
223
+ monkeypatch, capsys, _edit_payload(_transcript(tmp_path, []), GATE_FILE_PATH)
224
+ )
225
+ decision = json.loads(standard_output)["hookSpecificOutput"]
226
+ assert exit_code == 0
227
+ assert decision["permissionDecision"] == "deny"
228
+ assert decision["permissionDecisionReason"] == gate_fault_reason(
229
+ "pull request proof edit", RuntimeError("transcript list broke")
230
+ )
231
+ assert standard_error.rstrip().splitlines()[-1] == "RuntimeError: transcript list broke"
232
+
233
+
234
+ def test_should_deny_with_the_fault_reason_when_the_target_detection_raises(
235
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
236
+ ) -> None:
237
+ def raise_patch_fault(all_payload_fields: dict[str, object], tool_input: dict[str, object]) -> tuple[str, ...]:
238
+ raise KeyError("patch body")
239
+
240
+ monkeypatch.setattr(gate, "payload_patch_target_paths", raise_patch_fault)
241
+ payload = {
242
+ "tool_name": "apply_patch",
243
+ "tool_input": {"command": "*** Begin Patch\n*** End Patch\n"},
244
+ "cwd": str(tmp_path),
245
+ "transcript_path": _transcript(tmp_path, []),
246
+ }
247
+ _, standard_output, _ = _run_gate_main(monkeypatch, capsys, payload)
248
+ decision = json.loads(standard_output)["hookSpecificOutput"]
249
+ assert decision["permissionDecision"] == "deny"
250
+ assert decision["permissionDecisionReason"] == gate_fault_reason("pull request proof edit", KeyError("patch body"))
251
+
252
+
253
+ def test_should_print_nothing_for_an_edit_to_another_file_without_a_fault(
254
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
255
+ ) -> None:
256
+ exit_code, standard_output, standard_error = _run_gate_main(
257
+ monkeypatch, capsys, _edit_payload(_transcript(tmp_path, DENIED_CREATE_ENTRIES), "/w/app.py")
258
+ )
259
+ assert (exit_code, standard_output, standard_error) == (0, "", "")
@@ -0,0 +1,290 @@
1
+ """Behavioral tests for giving each shell create the folder it runs in.
2
+
3
+ (cd sub && gh pr create) ; gh pr create -> sub, then the starting folder
4
+ pushd sub && popd && gh pr create -> the starting folder
5
+ cd "$WORK" && gh pr create -> folder not followed
6
+ gh pr create --body-file - <<'EOF' ... -> one create; the body names none
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import pytest
12
+
13
+ from blocking.merge_review_gate_parts import create_folders
14
+ from blocking.merge_review_gate_parts.create_folders import PlacedCreate, all_placed_creates
15
+
16
+ START = "/work/main"
17
+
18
+
19
+ def _placements(command: str) -> list[tuple[tuple[str, ...], str | None, bool]]:
20
+ return list(
21
+ dict.fromkeys(
22
+ (
23
+ tuple(each_argument.strip("\"'") for each_argument in each_create.all_arguments),
24
+ each_create.folder,
25
+ each_create.is_folder_followed,
26
+ )
27
+ for each_create in all_placed_creates(command, START)
28
+ )
29
+ )
30
+
31
+
32
+ def test_should_keep_a_subshell_folder_change_inside_the_subshell() -> None:
33
+ assert _placements("(cd ../rsub && gh pr create --fill) ; gh pr create --fill") == [
34
+ (("--fill",), "/work/main/../rsub", True),
35
+ (("--fill",), START, True),
36
+ ]
37
+
38
+
39
+ @pytest.mark.parametrize(
40
+ "command",
41
+ [
42
+ "cd sub ; (cd ../rco && (true)) ; gh pr create --fill",
43
+ "cd sub ; (cd ../rco && (true)\n) ; gh pr create --fill",
44
+ "cd sub ; (cd ../rco && ( true ) ) ; gh pr create --fill",
45
+ "cd sub ; ((cd ../rco)) ; gh pr create --fill",
46
+ "cd sub ; (true && (cd ../rco)) ; gh pr create --fill",
47
+ "cd sub && (cd ../rco && (cd x)) && gh pr create --fill",
48
+ ],
49
+ )
50
+ def test_should_return_to_the_folder_before_the_outer_subshell_when_nested_subshells_close(command: str) -> None:
51
+ assert _placements(command) == [(("--fill",), "/work/main/sub", True)]
52
+
53
+
54
+ def test_should_return_to_the_inner_subshell_start_when_only_the_inner_one_closes() -> None:
55
+ assert _placements("cd sub ; (cd ../rco ; (cd x) ; gh pr create --fill) ; gh pr create --fill") == [
56
+ (("--fill",), "/work/main/sub/../rco", True),
57
+ (("--fill",), "/work/main/sub", True),
58
+ ]
59
+
60
+
61
+ def test_should_return_to_the_pushed_folder_at_popd() -> None:
62
+ assert _placements("pushd ../rsub && gh pr create --fill && popd && gh pr create --fill") == [
63
+ (("--fill",), "/work/main/../rsub", True),
64
+ (("--fill",), START, True),
65
+ ]
66
+
67
+
68
+ def test_should_carry_a_plain_cd_to_every_later_create() -> None:
69
+ assert _placements("cd sub && gh pr create --head a; gh pr new --head b") == [
70
+ (("--head", "a"), "/work/main/sub", True),
71
+ (("--head", "b"), "/work/main/sub", True),
72
+ ]
73
+
74
+
75
+ @pytest.mark.parametrize("folder_word", ['"$WORK"', "$(pwd)/x", "-", "../*"])
76
+ def test_should_leave_a_folder_it_cannot_follow_unfollowed(folder_word: str) -> None:
77
+ all_placements = _placements(f"cd {folder_word} && gh pr create --fill")
78
+ assert all_placements and all(not each_placement[2] for each_placement in all_placements)
79
+
80
+
81
+ def test_should_leave_popd_with_nothing_pushed_unfollowed() -> None:
82
+ assert _placements("popd; gh pr create --fill") == [(("--fill",), None, False)]
83
+
84
+
85
+ def test_should_keep_a_background_cd_out_of_later_creates() -> None:
86
+ assert _placements("cd other & gh pr create --fill") == [(("--fill",), START, True)]
87
+
88
+
89
+ @pytest.mark.parametrize(
90
+ "command",
91
+ [
92
+ "cd sub | true; gh pr create --fill",
93
+ "true | cd sub; gh pr create --fill",
94
+ "{ cd ../rsub; } | true; gh pr create --fill",
95
+ "{ cd sub; }; gh pr create --fill",
96
+ "if true; then cd sub; fi; gh pr create --fill",
97
+ "if true; then true; cd sub; fi; gh pr create --fill",
98
+ "! if true; then cd sub; fi; gh pr create --fill",
99
+ "case a in a) cd sub;; esac; gh pr create --fill",
100
+ "for each in sub; do cd $each; done; gh pr create --fill",
101
+ "while false; do cd sub; done; gh pr create --fill",
102
+ "f() { cd sub; }; gh pr create --fill",
103
+ ">/dev/null cd sub; gh pr create --fill",
104
+ ],
105
+ )
106
+ def test_should_leave_a_create_after_an_unmodeled_folder_change_unfollowed(command: str) -> None:
107
+ all_placements = _placements(command)
108
+ assert all_placements and all(not each_placement[2] for each_placement in all_placements)
109
+
110
+
111
+ @pytest.mark.parametrize("prefix", ["builtin", "command"])
112
+ def test_should_follow_cd_after_a_builtin_or_command_prefix(prefix: str) -> None:
113
+ assert _placements(f"{prefix} cd sub && gh pr create --fill") == [
114
+ (("--fill",), "/work/main/sub", True)
115
+ ]
116
+
117
+
118
+ def test_should_read_a_create_a_bash_wrapper_runs_in_the_folder_before_it() -> None:
119
+ assert _placements(
120
+ 'cd sub && bash -c "cd inner && gh pr create --head two"; gh pr create --head three'
121
+ ) == [
122
+ (("--head", "two"), "/work/main/sub/inner", True),
123
+ (("--head", "three"), "/work/main/sub", True),
124
+ ]
125
+
126
+
127
+ def test_should_let_eval_change_the_folder_of_its_own_shell() -> None:
128
+ assert _placements("eval 'cd sub'; gh pr create --fill") == [
129
+ (("--fill",), "/work/main/sub", True)
130
+ ]
131
+
132
+
133
+ def test_should_follow_a_powershell_path_parameter() -> None:
134
+ assert _placements("Set-Location -Path sub; gh pr create --fill") == [
135
+ (("--fill",), "/work/main/sub", True)
136
+ ]
137
+
138
+
139
+ def test_should_go_home_for_a_bare_cd(monkeypatch: pytest.MonkeyPatch) -> None:
140
+ monkeypatch.setenv("HOME", "/home/tester")
141
+ assert _placements("cd && gh pr create --fill") == [(("--fill",), "/home/tester", True)]
142
+
143
+
144
+ def test_should_read_no_create_in_a_heredoc_body() -> None:
145
+ command = "gh pr create --head two --body-file - <<'EOF'\ngh pr create --head one\nEOF"
146
+ assert {each_placement[0][:2] for each_placement in _placements(command)} == {("--head", "two")}
147
+
148
+
149
+ def test_should_read_no_create_in_a_quoted_option_value() -> None:
150
+ command = 'gh pr create --head two --label "see gh pr create" --repo acme/tools'
151
+ assert {each_placement[0] for each_placement in _placements(command)} == {
152
+ ("--head", "two", "--label", "see gh pr create", "--repo", "acme/tools")
153
+ }
154
+
155
+
156
+ def test_should_read_a_create_inside_a_substitution() -> None:
157
+ assert ("--head", "two") in {
158
+ each_placement[0] for each_placement in _placements('echo "$(gh pr create --head two)"')
159
+ }
160
+
161
+
162
+ def test_should_place_a_create_after_a_line_break_inside_a_substitution() -> None:
163
+ assert _placements("x=$(true\ngh pr create --head two)") == [(("--head", "two"), START, True)]
164
+
165
+
166
+ @pytest.mark.parametrize(
167
+ "command",
168
+ [
169
+ 'gh pr create --head one && bash -c "true\ngh pr create --head two"',
170
+ "gh pr create --head one && eval 'true\ngh pr create --head two'",
171
+ "cd sub && gh pr create --head one --body $'it\\'s' ; gh pr create --head two",
172
+ "gh pr create --head one --body \"$(echo '\"')\" ; gh pr create --head two",
173
+ ],
174
+ )
175
+ def test_should_place_each_create_bash_runs(command: str) -> None:
176
+ assert ("--head", "two") in {each_placement[0][-2:] for each_placement in _placements(command)}
177
+
178
+
179
+ @pytest.mark.parametrize(
180
+ "command",
181
+ [
182
+ "cd sub && eval 'gh pr create --head two --body \"a b\"'",
183
+ "cd sub && eval \"gh pr create --head two --body 'a b'\"",
184
+ ],
185
+ )
186
+ def test_should_read_a_create_eval_runs_with_a_quoted_value(command: str) -> None:
187
+ assert _placements(command) == [(("--head", "two", "--body", "a b"), "/work/main/sub", True)]
188
+
189
+
190
+ def test_should_read_a_create_a_wrapper_runs_in_a_case_arm() -> None:
191
+ command = (
192
+ "case x in x) eval 'gh pr create --head two';; "
193
+ "(y) bash -c 'gh pr create --head three';; esac"
194
+ )
195
+ assert {each_placement[0] for each_placement in _placements(command)} == {
196
+ ("--head", "two"),
197
+ ("--head", "three"),
198
+ }
199
+
200
+
201
+ def test_should_read_a_create_in_a_subshell_a_redirect_follows() -> None:
202
+ assert [
203
+ (each_placement[0][:2], each_placement[1], each_placement[2])
204
+ for each_placement in _placements("cd sub && (gh pr create --head two) > log")
205
+ ] == [(("--head", "two"), "/work/main/sub", True)]
206
+
207
+
208
+ @pytest.mark.parametrize(
209
+ ("command", "all_arguments"),
210
+ [
211
+ ("bash -c \"gh pr create --head one --body 'a\nb'\"", ("--head", "one", "--body", "a\nb")),
212
+ (
213
+ "gh pr create --head one --body 'a\ngh pr create --head two\nb'",
214
+ ("--head", "one", "--body", "a\ngh pr create --head two\nb"),
215
+ ),
216
+ ],
217
+ )
218
+ def test_should_place_only_the_create_bash_runs_when_a_quoted_value_spans_lines(
219
+ command: str, all_arguments: tuple[str, ...]
220
+ ) -> None:
221
+ assert _placements(command) == [(all_arguments, START, True)]
222
+
223
+
224
+ def test_should_read_an_ansi_c_quoted_value_as_one_word() -> None:
225
+ assert _placements("gh pr create --head one --body $'it\\'s\\n; x'") == [
226
+ (("--head", "one", "--body", "it's\n; x"), START, True)
227
+ ]
228
+
229
+
230
+ def test_should_leave_a_create_only_the_wrapped_reading_finds_unfollowed(
231
+ monkeypatch: pytest.MonkeyPatch,
232
+ ) -> None:
233
+ monkeypatch.setattr(create_folders, "_walk_text", lambda _walk, _text, state, _depth: state)
234
+ assert all_placed_creates('bash -c "cd sub && gh pr create --fill"', START) == [
235
+ PlacedCreate(("--fill",), None, False)
236
+ ]
237
+
238
+
239
+ def test_should_read_an_unbalanced_command_both_ways() -> None:
240
+ assert ("--head", "two") in {
241
+ each_placement[0][-2:]
242
+ for each_placement in _placements('gh pr create --head one --body "a\\" ; gh pr create --head two')
243
+ }
244
+
245
+
246
+ def test_should_read_no_create_in_a_heredoc_inside_a_substitution_body() -> None:
247
+ command = "gh pr create --head one --body \"$(cat <<'B'\nsee gh pr create --head two \"q\"\nB\n)\""
248
+ assert {each_placement[0][:2] for each_placement in _placements(command)} == {("--head", "one")}
249
+
250
+
251
+ @pytest.mark.parametrize(
252
+ ("command", "body"),
253
+ [
254
+ (
255
+ 'gh pr create --head one --body "say \\"x\\" ; gh pr create --head two"',
256
+ 'say "x" ; gh pr create --head two',
257
+ ),
258
+ (
259
+ "gh pr create --head one --body 'say \\\"x\\\" ; gh pr create --head two'",
260
+ 'say \\"x\\" ; gh pr create --head two',
261
+ ),
262
+ ],
263
+ )
264
+ def test_should_read_a_quoted_value_with_an_escaped_quote_as_one_word(
265
+ command: str, body: str
266
+ ) -> None:
267
+ assert _placements(command) == [(("--head", "one", "--body", body), START, True)]
268
+
269
+
270
+ def test_should_return_placed_creates() -> None:
271
+ assert all_placed_creates("gh pr create --fill", START) == [
272
+ PlacedCreate(("--fill",), START, True)
273
+ ]
274
+
275
+
276
+ @pytest.mark.parametrize(
277
+ "command",
278
+ [
279
+ "eval " * 18 + "'gh pr create --head two'",
280
+ "bash -c '" + "eval " * 18 + "gh pr create --head two'",
281
+ "eval " * 18 + "'python3 pull_request.py create'",
282
+ ],
283
+ )
284
+ def test_should_leave_unread_a_create_past_the_unwrap_depth(command: str) -> None:
285
+ assert _placements(command) == [((), None, False)]
286
+
287
+
288
+ def test_should_read_no_create_in_text_past_the_unwrap_depth_that_holds_none() -> None:
289
+ assert _placements("eval " * 18 + "'echo hi'") == []
290
+
@@ -0,0 +1,34 @@
1
+ """Behavioral tests for reading the values one create's flags give.
2
+
3
+ ["--head", "a", "-dHb"] -> ["a", "b"]
4
+ ["--title", "-Hx", "--head", "a"] -> ["a"]
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import pytest
10
+
11
+ from blocking.merge_review_gate_parts.create_options import all_option_values
12
+
13
+
14
+ @pytest.mark.parametrize(
15
+ ("all_words", "all_expected"),
16
+ [
17
+ (["--head", "a", "-dHb", "-H=c", "--head=d", "-Hf"], ["a", "b", "c", "d", "f"]),
18
+ (["-dH", "a"], ["a"]),
19
+ (["--title", "-Hx", "--head", "a"], ["a"]),
20
+ (["--body", "-H", "--title", "x"], []),
21
+ (["-bHx", "-tH", "y"], []),
22
+ (["--fill", "-H", "a"], ["a"]),
23
+ (["--draft", "--head", "a", "--", "--head", "b"], ["a"]),
24
+ (["--label=x", "-H", "'a'"], ["a"]),
25
+ ],
26
+ )
27
+ def test_should_return_each_value_the_option_is_given_as_gh_reads_it(
28
+ all_words: list[str], all_expected: list[str]
29
+ ) -> None:
30
+ assert all_option_values(all_words, "--head", "H") == all_expected
31
+
32
+
33
+ def test_should_read_a_repository_flag_word_that_is_a_title_value_as_the_title() -> None:
34
+ assert all_option_values(["--title", "--repo=x/y", "-R", "o/r"], "--repo", "R") == ["o/r"]