claude-dev-env 8.116.1 → 8.116.3

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.
@@ -4,7 +4,6 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import re
7
- import subprocess
8
7
  import sys
9
8
  from collections.abc import Iterator, Mapping
10
9
  from typing import NamedTuple
@@ -15,8 +14,15 @@ if hooks_directory not in sys.path:
15
14
  sys.path.insert(0, hooks_directory)
16
15
 
17
16
  from blocking.body_flowchart import fenced_line_flags, section_has_flowchart
18
- from blocking.followup_pr_dedupe import body_from_arguments, create_tool_fields, title_from_arguments
19
- from hooks_constants.pr_lifecycle_skill_gate_constants import SHELL_TOOL_NAMES, UPDATE_PULL_REQUEST_TOOL_SUFFIX
17
+ from blocking.followup_pr_dedupe import (
18
+ all_command_segments,
19
+ body_from_arguments,
20
+ create_tool_fields,
21
+ shell_command,
22
+ title_from_arguments,
23
+ )
24
+ from blocking.gate_run_reads import ReadSlice, answer_once, child_stdout
25
+ from hooks_constants.pr_lifecycle_skill_gate_constants import UPDATE_PULL_REQUEST_TOOL_SUFFIX
20
26
  from hooks_constants.pull_request_proof_constants import (
21
27
  ADDED_FILE_NAMES_QUERY,
22
28
  GIT_URL_SUFFIX,
@@ -102,10 +108,7 @@ from hooks_constants.pytest_invocation import (
102
108
  )
103
109
  from hooks_constants.shell_command_pipeline import pipeline_segments_for_command
104
110
  from hooks_constants.shell_command_segments import token_basename
105
- from hooks_constants.shell_command_wrappers import (
106
- all_wrapped_command_texts,
107
- segment_program_and_arguments,
108
- )
111
+ from hooks_constants.shell_command_wrappers import segment_program_and_arguments
109
112
 
110
113
 
111
114
  class CreateCall(NamedTuple):
@@ -206,21 +209,17 @@ def _command_arguments(
206
209
  return _script_word_arguments(program, all_arguments, script_word)
207
210
 
208
211
 
209
- def _shell_command(all_payload_fields: Mapping[str, object]) -> str | None:
210
- tool_input = all_payload_fields.get("tool_input")
211
- command = tool_input.get("command") if isinstance(tool_input, dict) else None
212
- if all_payload_fields.get("tool_name") not in SHELL_TOOL_NAMES or not isinstance(command, str):
213
- return None
214
- return command
215
-
216
-
217
212
  def _all_argument_lists(command: str, all_gh_words: list[str], script_word: str) -> Iterator[list[str]]:
218
- return (
219
- all_arguments
220
- for each_text in all_wrapped_command_texts(command)
221
- for each_segment, _each_following_operator in pipeline_segments_for_command(each_text)
222
- if (all_arguments := _command_arguments(each_segment, all_gh_words, script_word)) is not None
223
- )
213
+ all_seen_arguments: set[tuple[str, ...]] = set()
214
+ for each_segment in all_command_segments(command):
215
+ all_arguments = _command_arguments(each_segment, all_gh_words, script_word)
216
+ if all_arguments is None:
217
+ continue
218
+ all_unquoted_arguments = tuple(_unquoted_arguments(all_arguments))
219
+ if all_unquoted_arguments in all_seen_arguments:
220
+ continue
221
+ all_seen_arguments.add(all_unquoted_arguments)
222
+ yield all_arguments
224
223
 
225
224
 
226
225
  def _all_create_argument_lists(command: str) -> Iterator[list[str]]:
@@ -253,7 +252,7 @@ def _flag_value(all_create_arguments: list[str], all_flags: frozenset[str], assi
253
252
  def _shell_flag_value(
254
253
  all_payload_fields: Mapping[str, object], all_flags: frozenset[str], assignment_prefix: str
255
254
  ) -> str | None:
256
- command = _shell_command(all_payload_fields)
255
+ command = shell_command(all_payload_fields)
257
256
  if command is None:
258
257
  return None
259
258
  all_flag_values = [
@@ -303,7 +302,7 @@ def _create_calls(all_payload_fields: Mapping[str, object]) -> list[CreateCall]:
303
302
  body if isinstance(body, str) else "",
304
303
  )
305
304
  ]
306
- command = _shell_command(all_payload_fields)
305
+ command = shell_command(all_payload_fields)
307
306
  if command is None:
308
307
  return []
309
308
  working_directory = all_payload_fields.get("cwd")
@@ -324,7 +323,7 @@ def is_create_call(all_payload_fields: Mapping[str, object]) -> bool:
324
323
  Args:
325
324
  all_payload_fields: A tool name and input, shaped like a PreToolUse payload.
326
325
  """
327
- command = _shell_command(all_payload_fields)
326
+ command = shell_command(all_payload_fields)
328
327
  return create_tool_fields(all_payload_fields) is not None or (
329
328
  command is not None and next(_all_create_argument_lists(command), None) is not None
330
329
  )
@@ -650,7 +649,7 @@ def _edit_bodies(all_payload_fields: Mapping[str, object]) -> list[str]:
650
649
  if isinstance(tool_name, str) and tool_name.endswith(UPDATE_PULL_REQUEST_TOOL_SUFFIX):
651
650
  body = tool_input.get("body") if isinstance(tool_input, dict) else None
652
651
  return [body] if isinstance(body, str) else []
653
- command = _shell_command(all_payload_fields)
652
+ command = shell_command(all_payload_fields)
654
653
  if command is None:
655
654
  return []
656
655
  working_directory = all_payload_fields.get("cwd")
@@ -736,19 +735,9 @@ class ChangedFile(NamedTuple):
736
735
 
737
736
 
738
737
  def _git_output(working_directory: str, *all_git_arguments: str) -> str | None:
739
- try:
740
- completed = subprocess.run(
741
- ["git", "-C", working_directory, *all_git_arguments],
742
- capture_output=True,
743
- text=True,
744
- encoding="utf-8",
745
- errors="replace",
746
- timeout=GIT_TIMEOUT_SECONDS,
747
- check=False,
748
- )
749
- except (OSError, subprocess.SubprocessError):
750
- return None
751
- return completed.stdout if completed.returncode == 0 else None
738
+ return child_stdout(
739
+ ["git", "-C", working_directory, *all_git_arguments], GIT_TIMEOUT_SECONDS, ReadSlice.PROOF_AND_LOOK
740
+ )
752
741
 
753
742
 
754
743
  def _git_lines(working_directory: str, *all_git_arguments: str) -> list[str] | None:
@@ -810,6 +799,14 @@ def visible_changed_files(working_directory: str, head_branch: object) -> list[s
810
799
 
811
800
 
812
801
  def _merge_base_and_head(working_directory: str, head_branch: object) -> tuple[str, str] | None:
802
+ named_head = head_branch if isinstance(head_branch, str) else None
803
+ return answer_once(
804
+ ("merge base and head", working_directory, named_head),
805
+ lambda: _read_merge_base_and_head(working_directory, named_head),
806
+ )
807
+
808
+
809
+ def _read_merge_base_and_head(working_directory: str, head_branch: str | None) -> tuple[str, str] | None:
813
810
  if not working_directory:
814
811
  return None
815
812
  head_reference = _head_reference(working_directory, head_branch)
@@ -899,19 +896,8 @@ def added_workflow_files(working_directory: str, head_branch: object) -> list[st
899
896
 
900
897
 
901
898
  def _gh_api_lines(endpoint: str, query: str) -> list[str] | None:
902
- try:
903
- completed = subprocess.run(
904
- ["gh", "api", endpoint, "--jq", query],
905
- capture_output=True,
906
- text=True,
907
- encoding="utf-8",
908
- errors="replace",
909
- timeout=GH_TIMEOUT_SECONDS,
910
- check=False,
911
- )
912
- except (OSError, subprocess.SubprocessError):
913
- return None
914
- return completed.stdout.splitlines() if completed.returncode == 0 else None
899
+ printed_text = child_stdout(["gh", "api", endpoint, "--jq", query], GH_TIMEOUT_SECONDS, ReadSlice.PROOF_AND_LOOK)
900
+ return None if printed_text is None else printed_text.splitlines()
915
901
 
916
902
 
917
903
  def _compare_base_branch(repository: str, base_branch: str | None) -> str | None:
@@ -1010,13 +996,21 @@ def _added_workflow_files_for_create(all_payload_fields: Mapping[str, object]) -
1010
996
  working_directory = str(all_payload_fields.get("cwd") or "")
1011
997
  head_branch = _named_head_branch(all_payload_fields)
1012
998
  repository = _named_repository(all_payload_fields)
999
+ base_branch = _named_base_branch(all_payload_fields)
1000
+ return answer_once(
1001
+ ("added workflow files", working_directory, repository, base_branch, head_branch),
1002
+ lambda: _read_added_workflow_files(working_directory, repository, base_branch, head_branch),
1003
+ )
1004
+
1005
+
1006
+ def _read_added_workflow_files(
1007
+ working_directory: str, repository: str | None, base_branch: str | None, head_branch: str | None
1008
+ ) -> list[str]:
1013
1009
  all_workflow_paths = None
1014
1010
  if _local_checkout_may_answer(working_directory, repository, head_branch):
1015
1011
  all_workflow_paths = added_workflow_files(working_directory, head_branch)
1016
1012
  if all_workflow_paths is None:
1017
- all_workflow_paths = remote_added_workflow_files(
1018
- repository, _named_base_branch(all_payload_fields), head_branch
1019
- )
1013
+ all_workflow_paths = remote_added_workflow_files(repository, base_branch, head_branch)
1020
1014
  return all_workflow_paths or []
1021
1015
 
1022
1016
 
@@ -1131,11 +1125,18 @@ def missing_look_reason(all_payload_fields: Mapping[str, object]) -> str | None:
1131
1125
  git cannot read the branch, compare API returns 300 .py files -> UNREADABLE_CHANGES_REASON
1132
1126
  neither git nor the compare API can read it, no picture -> UNREADABLE_CHANGES_REASON
1133
1127
 
1128
+ Every body is checked for a picture first. When each one shows a picture,
1129
+ the check passes and reads neither git nor the compare API.
1130
+
1134
1131
  Args:
1135
1132
  all_payload_fields: The parsed PreToolUse input.
1136
1133
  """
1137
- all_bodies = [each_body for each_body in _create_bodies(all_payload_fields) if each_body is not None]
1138
- if not all_bodies:
1134
+ all_bodies_without_picture = [
1135
+ each_body
1136
+ for each_body in _create_bodies(all_payload_fields)
1137
+ if each_body is not None and not re.search(PROOF_IMAGE_PATTERN, proof_section(each_body) or "", re.IGNORECASE)
1138
+ ]
1139
+ if not all_bodies_without_picture:
1139
1140
  return None
1140
1141
  working_directory = all_payload_fields.get("cwd")
1141
1142
  head_branch = _named_head_branch(all_payload_fields)
@@ -1146,10 +1147,6 @@ def missing_look_reason(all_payload_fields: Mapping[str, object]) -> str | None:
1146
1147
  )
1147
1148
  if all_visible_files == []:
1148
1149
  return None
1149
- for each_body in all_bodies:
1150
- if re.search(PROOF_IMAGE_PATTERN, proof_section(each_body) or "", re.IGNORECASE):
1151
- continue
1152
- if all_visible_files is None:
1153
- return UNREADABLE_CHANGES_REASON
1154
- return MISSING_LOOK_REASON.format(changed_files=CHANGED_FILES_SEPARATOR.join(all_visible_files))
1155
- return None
1150
+ if all_visible_files is None:
1151
+ return UNREADABLE_CHANGES_REASON
1152
+ return MISSING_LOOK_REASON.format(changed_files=CHANGED_FILES_SEPARATOR.join(all_visible_files))
@@ -1,9 +1,16 @@
1
1
  """Behavior tests for the one-follow-up-pull-request-per-parent check."""
2
2
 
3
+ import json
4
+ import os
3
5
  import sys
6
+ import threading
7
+ import time
4
8
  from collections.abc import Mapping
9
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
5
10
  from pathlib import Path
6
11
 
12
+ import pytest
13
+
7
14
  HOOKS_DIRECTORY = Path(__file__).resolve().parent.parent
8
15
  if str(HOOKS_DIRECTORY) not in sys.path:
9
16
  sys.path.insert(0, str(HOOKS_DIRECTORY))
@@ -94,6 +101,55 @@ def test_body_from_arguments_reads_inline_text_and_body_files(tmp_path: Path) ->
94
101
  assert dedupe.body_from_arguments(["--fill"], str(tmp_path)) is None
95
102
 
96
103
 
104
+ def test_body_from_arguments_should_read_only_a_regular_body_file(tmp_path: Path) -> None:
105
+ assert dedupe.body_from_arguments(["--body-file", os.devnull], str(tmp_path)) is None
106
+ assert dedupe.body_from_arguments(["--body-file", "."], str(tmp_path)) is None
107
+
108
+
109
+ def _trickling_server() -> ThreadingHTTPServer:
110
+ class TrickleHandler(BaseHTTPRequestHandler):
111
+ def log_message(self, *all_arguments: object) -> None:
112
+ return
113
+
114
+ def do_GET(self) -> None:
115
+ payload = json.dumps([OPEN_FOLLOWUP]).encode()
116
+ self.send_response(200)
117
+ self.send_header("Content-Length", str(len(payload)))
118
+ self.end_headers()
119
+ for each_byte in payload:
120
+ self.wfile.write(bytes([each_byte]))
121
+ self.wfile.flush()
122
+ time.sleep(0.3)
123
+
124
+ server = ThreadingHTTPServer(("127.0.0.1", 0), TrickleHandler)
125
+ server.daemon_threads = True
126
+ threading.Thread(target=server.serve_forever, daemon=True).start()
127
+ return server
128
+
129
+
130
+ def test_read_open_pull_requests_should_bound_the_whole_read(monkeypatch: pytest.MonkeyPatch) -> None:
131
+ server = _trickling_server()
132
+ monkeypatch.setenv("NO_PROXY", "127.0.0.1")
133
+ monkeypatch.setenv("no_proxy", "127.0.0.1")
134
+ monkeypatch.setattr(dedupe, "GITHUB_API_ROOT", f"http://127.0.0.1:{server.server_address[1]}")
135
+ monkeypatch.setattr(dedupe, "READ_TIMEOUT_SECONDS", 1)
136
+ with pytest.raises(TimeoutError):
137
+ dedupe.read_open_pull_requests("jl-cmd", "claude-dev-env")
138
+ server.shutdown()
139
+
140
+
141
+ def test_shell_command_should_return_only_a_shell_tool_command() -> None:
142
+ assert dedupe.shell_command({"tool_name": "PowerShell", "tool_input": {"command": "git push"}}) == "git push"
143
+ assert dedupe.shell_command({"tool_name": "Read", "tool_input": {"command": "git push"}}) is None
144
+ assert dedupe.shell_command({"tool_name": "Bash", "tool_input": {"command": 7}}) is None
145
+
146
+
147
+ def test_all_command_segments_should_list_each_segment_and_wrapped_command() -> None:
148
+ all_segments = list(dedupe.all_command_segments("git add x && bash -c 'git push'"))
149
+ assert ["git", "add", "x"] in all_segments
150
+ assert ["git", "push"] in all_segments
151
+
152
+
97
153
  def test_title_from_arguments_should_read_each_title_flag_shape() -> None:
98
154
  assert dedupe.title_from_arguments(["--title", "feat: x", "--fill"]) == "feat: x"
99
155
  assert dedupe.title_from_arguments(["-t", "fix: y"]) == "fix: y"
@@ -0,0 +1,300 @@
1
+ """Behavior tests for the answers one pull request lifecycle gate run remembers."""
2
+
3
+ import ast
4
+ import json
5
+ import subprocess
6
+ import sys
7
+ import threading
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ HOOKS_DIRECTORY = Path(__file__).resolve().parent.parent
13
+ if str(HOOKS_DIRECTORY) not in sys.path:
14
+ sys.path.insert(0, str(HOOKS_DIRECTORY))
15
+
16
+ from blocking import gate_run_reads
17
+ from blocking.gate_run_reads import (
18
+ ReadSlice,
19
+ answer_once,
20
+ answer_within_allowance,
21
+ child_stdout,
22
+ gate_run,
23
+ read_allowance,
24
+ read_deadlines_started,
25
+ )
26
+ from hooks_constants.followup_pr_dedupe_constants import READ_TIMEOUT_SECONDS
27
+ from hooks_constants.gate_run_reads_constants import (
28
+ FOLLOWUP_READS_SECONDS,
29
+ KILL_GRACE_SECONDS,
30
+ MOST_CUT_READS_PER_RUN,
31
+ PROOF_AND_LOOK_READS_SECONDS,
32
+ STARTUP_AND_SCAN_MARGIN_SECONDS,
33
+ )
34
+
35
+ CLOCK_START = 100.0
36
+ OLDEST_SUPPORTED_PYTHON = (3, 11)
37
+ HIDDEN_WINDOW_FLAGS = 0x08000000
38
+ SLEEP_THEN_PRINT = "import time; time.sleep(30); print('late')"
39
+ HELD_READ_GIVES_UP_SECONDS = 30
40
+ GRANDCHILD_WAITS_FOR_RELEASE = (
41
+ "import os, sys, time\n"
42
+ "gave_up_path, release_path = sys.argv[1], sys.argv[2]\n"
43
+ "polls_left = 300\n"
44
+ "while polls_left and not os.path.exists(release_path):\n"
45
+ " time.sleep(0.1)\n"
46
+ " polls_left -= 1\n"
47
+ "if not os.path.exists(release_path):\n"
48
+ " open(gave_up_path, 'w').close()\n"
49
+ )
50
+ CHILD_STARTS_A_GRANDCHILD = (
51
+ "import subprocess, sys, time;"
52
+ " subprocess.Popen([sys.executable, '-c', *sys.argv[1:]]);"
53
+ " time.sleep(30)"
54
+ )
55
+ GATE_COMMAND_SUFFIX = "hooks/blocking/pr_lifecycle_" + "skill_gate.py"
56
+
57
+
58
+ class FakeClock:
59
+ def __init__(self) -> None:
60
+ self.now = CLOCK_START
61
+
62
+ def __call__(self) -> float:
63
+ return self.now
64
+
65
+
66
+ class RecordedChild(subprocess.Popen[str]):
67
+ """A child that notes the timeout of each wait its caller makes."""
68
+
69
+ def __init__(self, *all_arguments: object, **all_options: object) -> None:
70
+ self.all_wait_timeouts: list[object] = []
71
+ super().__init__(*all_arguments, **all_options)
72
+
73
+ def communicate(self, *all_arguments: object, **all_options: object) -> tuple[str, str]:
74
+ self.all_wait_timeouts.append(all_options.get("timeout"))
75
+ return super().communicate(*all_arguments, **all_options)
76
+
77
+
78
+ @pytest.fixture
79
+ def all_started_children(monkeypatch: pytest.MonkeyPatch) -> list[RecordedChild]:
80
+ all_children: list[RecordedChild] = []
81
+
82
+ def start(*all_arguments: object, **all_options: object) -> RecordedChild:
83
+ child = RecordedChild(*all_arguments, **all_options)
84
+ all_children.append(child)
85
+ return child
86
+
87
+ monkeypatch.setattr(gate_run_reads.subprocess, "Popen", start)
88
+ return all_children
89
+
90
+
91
+ def _counting_read(all_reads: list[str], answer: str | None):
92
+ def read() -> str | None:
93
+ all_reads.append("read")
94
+ return answer
95
+
96
+ return read
97
+
98
+
99
+ def test_answer_once_should_read_a_question_once_inside_one_run() -> None:
100
+ all_reads: list[str] = []
101
+ with gate_run():
102
+ assert (
103
+ answer_once(("origin", "/repo"), _counting_read(all_reads, "owner/name"))
104
+ == "owner/name"
105
+ )
106
+ assert (
107
+ answer_once(("origin", "/repo"), _counting_read(all_reads, "other/name"))
108
+ == "owner/name"
109
+ )
110
+ assert all_reads == ["read"]
111
+
112
+
113
+ def test_answer_once_should_remember_an_unanswered_read() -> None:
114
+ all_reads: list[str] = []
115
+ with gate_run():
116
+ assert answer_once(("origin", "/repo"), _counting_read(all_reads, None)) is None
117
+ assert answer_once(("origin", "/repo"), _counting_read(all_reads, "owner/name")) is None
118
+ assert all_reads == ["read"]
119
+
120
+
121
+ def test_answer_once_should_read_each_time_with_no_run_open() -> None:
122
+ all_reads: list[str] = []
123
+ assert answer_once(("origin", "/repo"), _counting_read(all_reads, "a")) == "a"
124
+ assert answer_once(("origin", "/repo"), _counting_read(all_reads, "b")) == "b"
125
+ assert all_reads == ["read", "read"]
126
+
127
+
128
+ def test_gate_run_should_forget_its_answers_when_it_closes() -> None:
129
+ all_reads: list[str] = []
130
+ with gate_run() as first_run:
131
+ answer_once(("origin", "/repo"), _counting_read(all_reads, "a"))
132
+ with gate_run():
133
+ assert answer_once(("origin", "/repo"), _counting_read(all_reads, "b")) == "b"
134
+ assert first_run.answer_by_question == {("origin", "/repo"): "a"}
135
+ assert all_reads == ["read", "read"]
136
+
137
+
138
+ def test_read_allowance_should_keep_the_own_timeout_with_no_deadline_started() -> None:
139
+ assert read_allowance(5, ReadSlice.PROOF_AND_LOOK) == 5
140
+ assert read_allowance(4, ReadSlice.FOLLOWUP) == 4
141
+
142
+
143
+ def test_read_allowance_should_take_the_smaller_of_the_own_timeout_and_the_time_left() -> None:
144
+ clock = FakeClock()
145
+ with read_deadlines_started(clock):
146
+ assert read_allowance(5, ReadSlice.PROOF_AND_LOOK) == 5
147
+ clock.now = CLOCK_START + 9
148
+ assert read_allowance(5, ReadSlice.PROOF_AND_LOOK) == 3
149
+ clock.now = CLOCK_START + 18
150
+ assert read_allowance(4, ReadSlice.FOLLOWUP) == 2
151
+ assert read_allowance(5, ReadSlice.PROOF_AND_LOOK) == 5
152
+
153
+
154
+ def test_read_allowance_should_keep_the_reserved_slice_for_followup_reads() -> None:
155
+ clock = FakeClock()
156
+ with read_deadlines_started(clock):
157
+ clock.now = CLOCK_START + PROOF_AND_LOOK_READS_SECONDS - 0.5
158
+ assert read_allowance(5, ReadSlice.PROOF_AND_LOOK) == 0.5
159
+ assert read_allowance(4, ReadSlice.FOLLOWUP) == 4
160
+ clock.now = CLOCK_START + PROOF_AND_LOOK_READS_SECONDS
161
+ assert read_allowance(5, ReadSlice.PROOF_AND_LOOK) is None
162
+ assert read_allowance(4, ReadSlice.FOLLOWUP) == 4
163
+ clock.now = CLOCK_START + PROOF_AND_LOOK_READS_SECONDS + FOLLOWUP_READS_SECONDS
164
+ assert read_allowance(4, ReadSlice.FOLLOWUP) is None
165
+
166
+
167
+ def test_child_stdout_should_skip_a_read_with_no_time_left(tmp_path: Path) -> None:
168
+ marker_path = tmp_path / "ran.txt"
169
+ clock = FakeClock()
170
+ with read_deadlines_started(clock), gate_run() as run:
171
+ clock.now = CLOCK_START + PROOF_AND_LOOK_READS_SECONDS
172
+ command = [sys.executable, "-c", f"open({str(marker_path)!r}, 'w').write('x')"]
173
+ assert child_stdout(command, 5, ReadSlice.PROOF_AND_LOOK) is None
174
+ assert not marker_path.exists()
175
+ assert run.was_read_cut_short
176
+
177
+
178
+ def test_child_stdout_should_return_the_output_of_a_child_that_answers() -> None:
179
+ with gate_run() as run:
180
+ assert child_stdout([sys.executable, "-c", "print('answer')"], 5, ReadSlice.PROOF_AND_LOOK) == "answer\n"
181
+ assert child_stdout([sys.executable, "-c", "raise SystemExit(3)"], 5, ReadSlice.PROOF_AND_LOOK) is None
182
+ assert not run.was_read_cut_short
183
+
184
+
185
+ def test_child_stdout_should_start_its_child_with_the_hidden_window_flags(monkeypatch: pytest.MonkeyPatch) -> None:
186
+ all_seen_flags: list[object] = []
187
+
188
+ def refuse_to_start(*all_arguments: object, **all_options: object) -> None:
189
+ all_seen_flags.append(all_options.get("creationflags"))
190
+ raise OSError("this test starts no child")
191
+
192
+ monkeypatch.setattr(gate_run_reads, "hidden_window_creation_flags", lambda: HIDDEN_WINDOW_FLAGS)
193
+ monkeypatch.setattr(gate_run_reads.subprocess, "Popen", refuse_to_start)
194
+ assert child_stdout(["git", "status"], 5, ReadSlice.PROOF_AND_LOOK) is None
195
+ assert all_seen_flags == [HIDDEN_WINDOW_FLAGS]
196
+
197
+
198
+ def test_child_stdout_should_kill_a_child_that_outlives_its_own_timeout(
199
+ all_started_children: list[RecordedChild],
200
+ ) -> None:
201
+ with gate_run() as run:
202
+ assert child_stdout([sys.executable, "-c", SLEEP_THEN_PRINT], 0.5, ReadSlice.PROOF_AND_LOOK) is None
203
+ (child,) = all_started_children
204
+ assert child.all_wait_timeouts == [0.5, KILL_GRACE_SECONDS]
205
+ assert child.wait() != 0
206
+ assert not run.was_read_cut_short
207
+
208
+
209
+ def test_child_stdout_should_stop_waiting_when_a_grandchild_holds_the_pipe(tmp_path: Path) -> None:
210
+ gave_up_path = tmp_path / "gave-up"
211
+ release_path = tmp_path / "release"
212
+ command = [
213
+ sys.executable,
214
+ "-c",
215
+ CHILD_STARTS_A_GRANDCHILD,
216
+ GRANDCHILD_WAITS_FOR_RELEASE,
217
+ str(gave_up_path),
218
+ str(release_path),
219
+ ]
220
+ answer = child_stdout(command, 1, ReadSlice.PROOF_AND_LOOK)
221
+ release_path.touch()
222
+ assert answer is None
223
+ assert not gave_up_path.exists()
224
+
225
+
226
+ def test_child_stdout_should_mark_the_run_when_the_deadline_cuts_a_read_short(
227
+ all_started_children: list[RecordedChild],
228
+ ) -> None:
229
+ clock = FakeClock()
230
+ with read_deadlines_started(clock), gate_run() as run:
231
+ clock.now = CLOCK_START + PROOF_AND_LOOK_READS_SECONDS - 0.4
232
+ assert child_stdout([sys.executable, "-c", SLEEP_THEN_PRINT], 5, ReadSlice.PROOF_AND_LOOK) is None
233
+ (child,) = all_started_children
234
+ assert child.all_wait_timeouts == [pytest.approx(0.4), KILL_GRACE_SECONDS]
235
+ assert child.wait() != 0
236
+ assert run.was_read_cut_short
237
+
238
+
239
+ def test_answer_within_allowance_should_bound_the_whole_read() -> None:
240
+ clock = FakeClock()
241
+ release = threading.Event()
242
+
243
+ def held_read(allowance: float) -> list[str]:
244
+ release.wait(HELD_READ_GIVES_UP_SECONDS)
245
+ return ["late"]
246
+
247
+ with read_deadlines_started(clock), gate_run() as run:
248
+ clock.now = CLOCK_START + PROOF_AND_LOOK_READS_SECONDS + FOLLOWUP_READS_SECONDS - 0.3
249
+ try:
250
+ answer = answer_within_allowance(held_read, 4, ReadSlice.FOLLOWUP)
251
+ finally:
252
+ release.set()
253
+ assert answer is None
254
+ assert run.was_read_cut_short
255
+
256
+
257
+ def test_answer_within_allowance_should_return_the_answer_and_raise_the_read_error() -> None:
258
+ all_allowances: list[float] = []
259
+
260
+ def answering_read(allowance: float) -> list[str]:
261
+ all_allowances.append(allowance)
262
+ return ["ok"]
263
+
264
+ def failing_read(allowance: float) -> list[str]:
265
+ raise OSError("offline")
266
+
267
+ assert answer_within_allowance(answering_read, 4, ReadSlice.FOLLOWUP) == ["ok"]
268
+ assert all_allowances == [4]
269
+ with pytest.raises(OSError, match="offline"):
270
+ answer_within_allowance(failing_read, 4, ReadSlice.FOLLOWUP)
271
+
272
+
273
+ def _registered_gate_timeout_seconds() -> int:
274
+ all_registration_fields = json.loads((HOOKS_DIRECTORY / "hooks.json").read_text(encoding="utf-8"))
275
+ all_timeouts = [
276
+ each_hook["timeout"]
277
+ for each_group in all_registration_fields["hooks"]["PreToolUse"]
278
+ for each_hook in each_group["hooks"]
279
+ if each_hook.get("command", "").endswith(GATE_COMMAND_SUFFIX)
280
+ ]
281
+ assert len(all_timeouts) == 1
282
+ return all_timeouts[0]
283
+
284
+
285
+ def test_both_followup_reads_should_fit_inside_their_reserved_slice() -> None:
286
+ assert READ_TIMEOUT_SECONDS * 2 <= FOLLOWUP_READS_SECONDS
287
+
288
+
289
+ def test_registered_timeout_should_outlast_every_read_deadline_and_kill_grace() -> None:
290
+ last_read_ends_at = (
291
+ PROOF_AND_LOOK_READS_SECONDS
292
+ + FOLLOWUP_READS_SECONDS
293
+ + KILL_GRACE_SECONDS * MOST_CUT_READS_PER_RUN
294
+ )
295
+ assert _registered_gate_timeout_seconds() >= last_read_ends_at + STARTUP_AND_SCAN_MARGIN_SECONDS
296
+
297
+
298
+ def test_gate_run_reads_should_parse_under_the_oldest_supported_python() -> None:
299
+ source = Path(gate_run_reads.__file__).read_text(encoding="utf-8")
300
+ assert ast.parse(source, feature_version=OLDEST_SUPPORTED_PYTHON).body