claude-dev-env 8.116.0 → 8.116.2

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 (39) hide show
  1. package/bin/install.prompt-context.test.mjs +5 -6
  2. package/docs/rule-guides/proof-before-pull-request.md +4 -2
  3. package/hooks/blocking/final_reply_gate.py +7 -29
  4. package/hooks/blocking/followup_pr_dedupe.py +118 -33
  5. package/hooks/blocking/gate_run_reads.py +284 -0
  6. package/hooks/blocking/pr_lifecycle_skill_gate.py +33 -33
  7. package/hooks/blocking/pull_request_proof.py +60 -63
  8. package/hooks/blocking/test_final_reply_gate.py +4 -196
  9. package/hooks/blocking/test_followup_pr_dedupe.py +59 -0
  10. package/hooks/blocking/test_gate_run_reads.py +241 -0
  11. package/hooks/blocking/test_pr_lifecycle_skill_gate.py +89 -1
  12. package/hooks/blocking/test_pull_request_proof.py +63 -2
  13. package/hooks/features/conduct-gates.md +6 -13
  14. package/hooks/hooks.json +1 -42
  15. package/hooks/hooks_constants/background_silence_prompt_constants.py +2 -0
  16. package/hooks/hooks_constants/gate_run_reads_constants.py +10 -0
  17. package/hooks/hooks_constants/resolve_thread_reply_gate_constants.py +0 -8
  18. package/hooks/hooks_constants/test_followup_pr_dedupe_constants.py +0 -4
  19. package/hooks/session/background_silence_prompt.py +1 -1
  20. package/hooks/test_context_budget_hooks.py +0 -1
  21. package/package.json +1 -1
  22. package/scripts/durable_post_lint.py +0 -12
  23. package/scripts/durable_post_lint_config/config/constants.py +1 -2
  24. package/scripts/policy_lint/adapter_configuration.py +0 -2
  25. package/scripts/policy_lint/config/constants.py +0 -2
  26. package/scripts/test_durable_post_lint.py +0 -53
  27. package/scripts/tests/test_adapter_configuration.py +0 -16
  28. package/hooks/blocking/chat_reply_gate.py +0 -260
  29. package/hooks/blocking/reply_length_gate.py +0 -804
  30. package/hooks/blocking/test_chat_reply_gate.py +0 -302
  31. package/hooks/blocking/test_reply_length_gate.py +0 -1324
  32. package/hooks/hooks_constants/chat_reply_gate_constants.py +0 -60
  33. package/hooks/hooks_constants/reply_length_gate_constants.py +0 -203
  34. package/hooks/hooks_constants/test_reply_length_gate_constants.py +0 -81
  35. package/hooks/hooks_constants/test_visual_reply_rules_constants.py +0 -50
  36. package/hooks/hooks_constants/visual_reply_rules_constants.py +0 -106
  37. package/hooks/test_visual_reply_rules.py +0 -362
  38. package/hooks/visual_reply_rules.py +0 -478
  39. package/rules/visual-reply-rules.json +0 -56
@@ -35,15 +35,14 @@ test('reinstall drops the retired style reminder and keeps one skill reminder ho
35
35
  mergeHooksIntoSettings(settings, hooksConfig, 'C:/Users/example/.claude', 'python');
36
36
 
37
37
  const userPromptHooks = settings.hooks.UserPromptSubmit.flatMap(eachGroup => eachGroup.hooks);
38
- assert.equal(userPromptHooks.length, 8);
38
+ assert.equal(userPromptHooks.length, 7);
39
39
  assert.equal(userPromptHooks[0].command, userCommand);
40
40
  assert.match(userPromptHooks[1].command, /session\/skill_loaded_reminder\.py$/);
41
41
  assert.match(userPromptHooks[2].command, /lifecycle\/nested_project_hooks\.py$/);
42
- assert.match(userPromptHooks[3].command, /blocking\/chat_reply_gate\.py$/);
43
- assert.match(userPromptHooks[4].command, /session\/tracking_nudge\.py$/);
44
- assert.match(userPromptHooks[5].command, /session\/plugin_change_warning\.py$/);
45
- assert.match(userPromptHooks[6].command, /blocking\/turn_review_gate\.py$/);
46
- assert.match(userPromptHooks[7].command, /session\/background_silence_prompt\.py$/);
42
+ assert.match(userPromptHooks[3].command, /session\/tracking_nudge\.py$/);
43
+ assert.match(userPromptHooks[4].command, /session\/plugin_change_warning\.py$/);
44
+ assert.match(userPromptHooks[5].command, /blocking\/turn_review_gate\.py$/);
45
+ assert.match(userPromptHooks[6].command, /session\/background_silence_prompt\.py$/);
47
46
  assert.ok(userPromptHooks.every(eachHook => !eachHook.command.includes('style_reminder_prompt')));
48
47
 
49
48
  const firstMerge = JSON.stringify(settings);
@@ -40,8 +40,10 @@ When you cannot prove it, leave the pull request unopened. Tell the owner in thr
40
40
 
41
41
  ## Enforcement
42
42
 
43
- `hooks/blocking/pull_request_proof.py` reads the body of each new pull request before it opens. `pr_lifecycle_skill_gate.py` runs it on `gh pr create`, the `pull_request.py create` script, and each `mcp__*__create_pull_request` tool. The gate denies the call when the body has no "Proof in practice" heading, or when the text under that heading names no command in backticks. The gate also denies a section whose only commands run a test runner, such as `pytest`, `python -m unittest`, `uv run pytest`, `npm test`, `npx vitest`, `jest`, `go test` or `cargo test`. Quotes around a runner word, interpreter flags before `-m`, and `coverage run -m unittest` are still test runs. A command is an inline backticked span or a `$ ` line inside a fenced block. A span that starts with a path and line, such as `gate.py:12`, is not a command. A span that holds one path or file name, such as `src/x.py`, is not a command unless that span runs a test runner, such as `py.test` or `pytest.exe`. A test run piped into `tee`, `tail`, `head`, `grep` or `cat` is still a test run. The deny quotes the line "Unit tests are welcome as extra evidence. The live run is the proof." and asks for a run of the changed thing the way its user runs it, without the change and with it. The gate also denies a section whose prose says part of the change is not proven, not tested or not verified, with "yet", "been" or "fully" allowed after the "not", or says unproven, untested or unverified. The line passes only for a workflow file the branch adds, when the body's "After merge" heading plans that file's first run; `pull_request_proof.py` and `hooks_constants/pull_request_proof_constants.py` hold the exact conditions. Otherwise the deny quotes that line, and asks for the run before the pull request opens, or for the line under a "Not covered" heading when the change does not target it. The same denial covers a proof line that opens with "not run", "not exercised" or "not executed" (a "yet" or "been" may follow the "not") or says "has not been run". A proof line with a merge word (merge, merged, merges or merging, so post-merge too) is denied with its own reason: run the check on the branch, and put a file or command name that contains merge in backticks. A step that needs the merged code to exist goes under a "Not covered" heading at the same level as the proof heading, as a line that opens with "not run". `UNPROVEN_ADMISSION_PATTERN` and `MERGE_WORD_PATTERN` list the shapes. Words inside backticks or a fenced block are quoted output and do not count. A section with one command that is not a test run, and no such line, passes. A `gh pr create` with no `--body` or `--body-file` is denied with a request for the body. A body edit through `update_pull_request`, `gh pr edit` or the `pull_request.py edit` script gets the same checks on its proof section that a new pull request gets, so an edit cannot swap in a proof that a new pull request would be denied. An edit with no proof section passes. The gate also denies a new pull request whose "What this does" section holds no flowchart: a closed `mermaid` block whose first line starts with `flowchart` and that joins two nodes with an arrow. A body edit meets the same check when its body carries a "What this does" heading. A body the gate cannot read passes, such as an inline multi-line `--body`, a body from standard input, or a body written through `gh api`. Merges and pushes pass.
43
+ `hooks/blocking/pull_request_proof.py` reads the body of each new pull request before it opens. `pr_lifecycle_skill_gate.py` runs it on `gh pr create`, the `pull_request.py create` script, and each `mcp__*__create_pull_request` tool. The gate denies the call when the body has no "Proof in practice" heading, or when the text under that heading names no command in backticks. The gate also denies a section whose only commands run a test runner, such as `pytest`, `python -m unittest`, `uv run pytest`, `npm test`, `npx vitest`, `jest`, `go test` or `cargo test`. Quotes around a runner word, interpreter flags before `-m`, and `coverage run -m unittest` are still test runs. A command is an inline backticked span or a `$ ` line inside a fenced block. A span that starts with a path and line, such as `gate.py:12`, is not a command. A span that holds one path or file name, such as `src/x.py`, is not a command unless that span runs a test runner, such as `py.test` or `pytest.exe`. A test run piped into `tee`, `tail`, `head`, `grep` or `cat` is still a test run. The deny quotes the line "Unit tests are welcome as extra evidence. The live run is the proof." and asks for a run of the changed thing the way its user runs it, without the change and with it. The gate also denies a section whose prose says part of the change is not proven, not tested or not verified, with "yet", "been" or "fully" allowed after the "not", or says unproven, untested or unverified. The line passes only for a workflow file the branch adds, when the body's "After merge" heading plans that file's first run; `pull_request_proof.py` and `hooks_constants/pull_request_proof_constants.py` hold the exact conditions. Otherwise the deny quotes that line, and asks for the run before the pull request opens, or for the line under a "Not covered" heading when the change does not target it. The same denial covers a proof line that opens with "not run", "not exercised" or "not executed" (a "yet" or "been" may follow the "not") or says "has not been run". A proof line with a merge word (merge, merged, merges or merging, so post-merge too) is denied with its own reason: run the check on the branch, and put a file or command name that contains merge in backticks. A step that needs the merged code to exist goes under a "Not covered" heading at the same level as the proof heading, as a line that opens with "not run". `UNPROVEN_ADMISSION_PATTERN` and `MERGE_WORD_PATTERN` list the shapes. Words inside backticks or a fenced block are quoted output and do not count. A section with one command that is not a test run, and no such line, passes. A `gh pr create` with no `--body` or `--body-file` is denied with a request for the body. A body edit through `update_pull_request`, `gh pr edit` or the `pull_request.py edit` script gets the same checks on its proof section that a new pull request gets, so an edit cannot swap in a proof that a new pull request would be denied. An edit with no proof section passes. The gate also denies a new pull request whose "What this does" section holds no flowchart: a closed `mermaid` block whose first line starts with `flowchart` and that joins two nodes with an arrow. A body edit meets the same check when its body carries a "What this does" heading. A body the gate cannot read passes, such as an inline multi-line `--body`, a body from standard input, or a body written through `gh api`. A `--body-file` that is not a regular file (a pipe, a device or a directory) counts as no body: a create is denied with the request for the body, and an edit passes. Merges and pushes pass.
44
44
 
45
- When the checked-out branch changes a file people see (`.html`, `.htm`, `.css`, `.scss`, `.tsx`, `.jsx`, `.vue`, `.svelte`), the gate also denies a body whose proof section holds no picture: a markdown image, an image URL, or an Artifact page link that shows the screenshots. Render the change, read the screenshot, and put it in the section, so the reader sees what you looked at. A page the branch only moves to another folder or name that ends the same way, with every byte kept (`R100` in `git diff --name-status`), changes nothing people see, so the gate leaves it out; a moved page that also changed, or a file that becomes a page by a change of name ending, still needs the picture. When git in the session directory cannot list the branch's changed files, the gate asks for the picture as well.
45
+ When the checked-out branch changes a file people see (`.html`, `.htm`, `.css`, `.scss`, `.tsx`, `.jsx`, `.vue`, `.svelte`), the gate also denies a body whose proof section holds no picture: a markdown image, an image URL, or an Artifact page link that shows the screenshots. Render the change, read the screenshot, and put it in the section, so the reader sees what you looked at. A page the branch only moves to another folder or name that ends the same way, with every byte kept (`R100` in `git diff --name-status`), changes nothing people see, so the gate leaves it out; a moved page that also changed, or a file that becomes a page by a change of name ending, still needs the picture. When git in the session directory cannot list the branch's changed files, the gate asks for the picture as well. The gate looks for the picture first, so a proof section that holds one passes this check with no git read.
46
+
47
+ The gate's git, GitHub CLI and web reads share one budget, counted from the gate start: the proof and picture reads have a deadline at 12 s, and the follow-up reads at 20 s. A stopped child read gets 1 s more to close its pipes, so the reads end by 21 s. The registered timeout in `hooks.json` is 30 s. A read the budget cuts short comes back unanswered, and the check that asked for it decides from that. A deny from such a run ends with a sentence that says the reads ran out of time, so a second run may pass.
46
48
 
47
49
  The gate checks that the section is there, names a command, and admits no unproven part. Whether the run proves the change stays a judgment for the author and the reviewer.
@@ -1,22 +1,11 @@
1
1
  #!/usr/bin/env python3
2
- """Stop hook that checks the closing chat reply for an unvalidated claim.
2
+ """Stop hook that checks the closing chat reply for a path the terminal garbles.
3
3
 
4
- The reply length gate checks the chat tools. This gate checks the reply the
5
- session ends its turn with, which reaches the user with no tool call::
6
-
7
- flag: My guess is one to two hours.
8
- flag: I didn't confirm this one.
9
- flag: Run 18239174012 passed. (no tool result shows the run)
10
- ok: Run 18239174012 took 39 minutes. (a tool result shows the run)
11
-
12
- It applies the banned words, the unvalidated claim pattern, and the cited
13
- run, job, check, and pull request numbers from ``reply_length_gate.py``. A
14
- pull request link also counts as shown when hook or harness text shows it. The
15
- citation check is skipped when the transcript cannot be read. It also flags
16
- a path outside code whose backslash the terminal drops, such as
17
- ``D:\\Reports\\.claude``. A block sends
18
- the reason back so the model rewrites the reply. Claude Code ends the turn
19
- after eight blocks in a row.
4
+ This gate checks the reply the session ends its turn with, which reaches the
5
+ user with no tool call. It flags a path outside code whose backslash the
6
+ terminal drops, such as ``D:\\Reports\\.claude``. A block sends the reason
7
+ back so the model rewrites the reply. Claude Code ends the turn after eight
8
+ blocks in a row.
20
9
 
21
10
  It also blocks a reply whose last paragraph ends with a question mark, or says a question still stands, when the
22
11
  turn sent no AskUserQuestion, hearthbot decision card, or Codex
@@ -44,12 +33,6 @@ hooks_root_directory = str(Path(__file__).resolve().parent.parent)
44
33
  if hooks_root_directory not in sys.path:
45
34
  sys.path.insert(0, hooks_root_directory)
46
35
 
47
- from reply_length_gate import (
48
- banned_word_violation,
49
- configured_banned_words,
50
- unseen_citation_violation_with_hook_text,
51
- unvalidated_claim_violation,
52
- )
53
36
  from open_tasks_transcript import replayed_transcript
54
37
  from hooks_constants.hook_block_logger import log_hook_block
55
38
  from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
@@ -270,12 +253,7 @@ def unbriefed_question_violation(reply_text: str, transcript_path: object) -> st
270
253
 
271
254
  def final_reply_violation(reply_text: str, transcript_path: object) -> str | None:
272
255
  """Return the block reason for the closing reply, or None when it passes."""
273
- return (
274
- banned_word_violation(reply_text, configured_banned_words())
275
- or unvalidated_claim_violation(reply_text)
276
- or unseen_citation_violation_with_hook_text(reply_text, transcript_path)
277
- or windows_path_violation(reply_text)
278
- )
256
+ return windows_path_violation(reply_text)
279
257
 
280
258
 
281
259
  def main() -> int:
@@ -4,10 +4,9 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import re
7
- import subprocess
8
7
  import sys
9
8
  import urllib.request
10
- from collections.abc import Callable, Mapping
9
+ from collections.abc import Callable, Iterator, Mapping
11
10
  from dataclasses import dataclass
12
11
  from pathlib import Path
13
12
 
@@ -34,6 +33,7 @@ from hooks_constants.followup_pr_dedupe_constants import (
34
33
  STANDARD_INPUT_PATH,
35
34
  WORKFLOW_DISPATCH_TOOL_SUFFIX,
36
35
  )
36
+ from blocking.gate_run_reads import ReadSlice, answer_once, answer_within_allowance, child_stdout
37
37
  from hooks_constants.pr_lifecycle_skill_gate_constants import SHELL_TOOL_NAMES
38
38
  from hooks_constants.pytest_invocation import unquoted_token
39
39
  from hooks_constants.setup_project_paths_constants import DECODE_ERRORS_POLICY, UTF8_ENCODING
@@ -63,12 +63,29 @@ def followup_parent_number(body: str) -> int | None:
63
63
 
64
64
 
65
65
  def read_open_pull_requests(owner: str, repo: str) -> list[Mapping[str, object]]:
66
- """Read one page of a repository's open pull requests from the GitHub API."""
66
+ """Read one page of a repository's open pull requests from the GitHub API.
67
+
68
+ The whole read, connect and headers included, fits in its allowance:
69
+ READ_TIMEOUT_SECONDS, or less when the follow-up deadline is nearer.
70
+
71
+ Raises:
72
+ TimeoutError: The read did not finish inside its allowance.
73
+ OSError: The request failed.
74
+ """
67
75
  url = GITHUB_API_ROOT + OPEN_PULL_REQUESTS_PATH_TEMPLATE.format(owner=owner, repo=repo)
76
+ answer = answer_within_allowance(
77
+ lambda allowance: _fetched_json(url, allowance), READ_TIMEOUT_SECONDS, ReadSlice.FOLLOWUP
78
+ )
79
+ if answer is None:
80
+ raise TimeoutError(url)
81
+ return [each_entry for each_entry in answer if isinstance(each_entry, dict)]
82
+
83
+
84
+ def _fetched_json(url: str, timeout_seconds: float) -> list[object]:
68
85
  request = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json"})
69
- with urllib.request.urlopen(request, timeout=READ_TIMEOUT_SECONDS) as reply:
86
+ with urllib.request.urlopen(request, timeout=timeout_seconds) as reply:
70
87
  answer = json.loads(reply.read())
71
- return [each_entry for each_entry in answer if isinstance(each_entry, dict)]
88
+ return answer if isinstance(answer, list) else []
72
89
 
73
90
 
74
91
  def _option_value(all_arguments: list[str], all_option_names: frozenset[str]) -> str | None:
@@ -87,7 +104,9 @@ def body_from_arguments(all_arguments: list[str], working_directory: str) -> str
87
104
  """Return the body a gh-style argument list passes, or None when it passes none.
88
105
 
89
106
  ``--body`` text comes back as given. A ``--body-file`` path is read from
90
- the working directory. Standard input and an unreadable file give None.
107
+ the working directory only when it names a regular file. Standard input,
108
+ a directory, a named pipe, any other special file, and an unreadable file
109
+ give None.
91
110
  """
92
111
  inline_body = _option_value(all_arguments, ALL_BODY_OPTIONS)
93
112
  if inline_body is not None:
@@ -95,10 +114,11 @@ def body_from_arguments(all_arguments: list[str], working_directory: str) -> str
95
114
  body_path = _option_value(all_arguments, ALL_BODY_FILE_OPTIONS)
96
115
  if body_path is None or body_path == STANDARD_INPUT_PATH:
97
116
  return None
117
+ body_file = Path(working_directory) / body_path
98
118
  try:
99
- return (Path(working_directory) / body_path).read_text(
100
- encoding=UTF8_ENCODING, errors=DECODE_ERRORS_POLICY
101
- )
119
+ if not body_file.is_file():
120
+ return None
121
+ return body_file.read_text(encoding=UTF8_ENCODING, errors=DECODE_ERRORS_POLICY)
102
122
  except OSError:
103
123
  return None
104
124
 
@@ -116,18 +136,18 @@ def title_from_arguments(all_arguments: list[str]) -> str | None:
116
136
 
117
137
 
118
138
  def _origin_repository(working_directory: str) -> tuple[str, str] | None:
119
- try:
120
- completed = subprocess.run(
121
- ALL_GIT_REMOTE_COMMAND_WORDS,
122
- cwd=working_directory or None,
123
- capture_output=True,
124
- text=True,
125
- timeout=READ_TIMEOUT_SECONDS,
126
- check=False,
127
- )
128
- except (OSError, subprocess.SubprocessError):
139
+ return answer_once(
140
+ ("origin repository", working_directory), lambda: _read_origin_repository(working_directory)
141
+ )
142
+
143
+
144
+ def _read_origin_repository(working_directory: str) -> tuple[str, str] | None:
145
+ printed_text = child_stdout(
146
+ ALL_GIT_REMOTE_COMMAND_WORDS, READ_TIMEOUT_SECONDS, ReadSlice.FOLLOWUP, working_directory
147
+ )
148
+ if printed_text is None:
129
149
  return None
130
- match = re.search(GITHUB_REMOTE_PATTERN, completed.stdout.strip())
150
+ match = re.search(GITHUB_REMOTE_PATTERN, printed_text.strip())
131
151
  return (match.group(1), match.group(2)) if match else None
132
152
 
133
153
 
@@ -142,10 +162,35 @@ def _repository_from_arguments(
142
162
  return (owner, repo) if separator and owner and repo else None
143
163
 
144
164
 
145
- def _segment_draft(all_segment_tokens: list[str], working_directory: str) -> PullRequestDraft | None:
146
- program, all_arguments = segment_program_and_arguments(all_segment_tokens)
147
- if program != "gh" or all_arguments[: len(ALL_GH_CREATE_WORDS)] != ALL_GH_CREATE_WORDS:
148
- return None
165
+ def all_command_segments(command: str) -> Iterator[list[str]]:
166
+ """Return the token list of each segment in a command and in each command a wrapper inside it runs.
167
+
168
+ ::
169
+
170
+ "git add x && gh pr view 7" -> ["git", "add", "x"], then ["gh", "pr", "view", "7"]
171
+
172
+ A segment with a quoted word comes back twice, once with the quotes
173
+ removed and once with them kept, because the pipeline parser reads it both
174
+ ways.
175
+
176
+ Args:
177
+ command: The shell command text.
178
+ """
179
+ return (
180
+ each_segment
181
+ for each_text in all_wrapped_command_texts(command)
182
+ for each_segment, _each_following_operator in pipeline_segments_for_command(each_text)
183
+ )
184
+
185
+
186
+ def _all_create_argument_lists(command: str) -> Iterator[list[str]]:
187
+ for each_segment in all_command_segments(command):
188
+ program, all_arguments = segment_program_and_arguments(each_segment)
189
+ if program == "gh" and all_arguments[: len(ALL_GH_CREATE_WORDS)] == ALL_GH_CREATE_WORDS:
190
+ yield all_arguments
191
+
192
+
193
+ def _arguments_draft(all_arguments: list[str], working_directory: str) -> PullRequestDraft | None:
149
194
  body = body_from_arguments(all_arguments, working_directory)
150
195
  repository = _repository_from_arguments(all_arguments, working_directory)
151
196
  if body is None or repository is None:
@@ -155,13 +200,51 @@ def _segment_draft(all_segment_tokens: list[str], working_directory: str) -> Pul
155
200
 
156
201
  def _shell_draft(command: str, working_directory: str) -> PullRequestDraft | None:
157
202
  all_drafts = (
158
- _segment_draft(each_segment, working_directory)
159
- for each_text in all_wrapped_command_texts(command)
160
- for each_segment, _each_following_operator in pipeline_segments_for_command(each_text)
203
+ _arguments_draft(all_arguments, working_directory)
204
+ for all_arguments in _all_create_argument_lists(command)
161
205
  )
162
206
  return next((each_draft for each_draft in all_drafts if each_draft is not None), None)
163
207
 
164
208
 
209
+ def _names_a_parent(all_payload_fields: Mapping[str, object]) -> bool:
210
+ create_fields = create_tool_fields(all_payload_fields)
211
+ if create_fields is not None:
212
+ body = create_fields.get("body")
213
+ return isinstance(body, str) and followup_parent_number(body) is not None
214
+ command = shell_command(all_payload_fields)
215
+ if command is None:
216
+ return False
217
+ working_directory = _working_directory(all_payload_fields)
218
+ return any(
219
+ (body := body_from_arguments(all_arguments, working_directory)) is not None
220
+ and followup_parent_number(body) is not None
221
+ for all_arguments in _all_create_argument_lists(command)
222
+ )
223
+
224
+
225
+ def shell_command(all_payload_fields: Mapping[str, object]) -> str | None:
226
+ """Return the command text of a Bash or PowerShell call, or None for any other tool.
227
+
228
+ ::
229
+
230
+ {"tool_name": "Bash", "tool_input": {"command": "git push"}} -> "git push"
231
+ {"tool_name": "Read", "tool_input": {"file_path": "a.py"}} -> None
232
+
233
+ Args:
234
+ all_payload_fields: The parsed PreToolUse input.
235
+ """
236
+ tool_input = all_payload_fields.get("tool_input")
237
+ command = tool_input.get("command") if isinstance(tool_input, dict) else None
238
+ if all_payload_fields.get("tool_name") not in SHELL_TOOL_NAMES or not isinstance(command, str):
239
+ return None
240
+ return command
241
+
242
+
243
+ def _working_directory(all_payload_fields: Mapping[str, object]) -> str:
244
+ working_directory = all_payload_fields.get("cwd")
245
+ return working_directory if isinstance(working_directory, str) else ""
246
+
247
+
165
248
  def _dispatch_fields(all_tool_input_fields: Mapping[str, object]) -> dict[str, object] | None:
166
249
  all_inputs = all_tool_input_fields.get("inputs")
167
250
  if all_tool_input_fields.get("method") != RUN_WORKFLOW_METHOD or not isinstance(all_inputs, dict):
@@ -206,12 +289,10 @@ def pull_request_draft(all_payload_fields: Mapping[str, object]) -> PullRequestD
206
289
  if isinstance(owner, str) and isinstance(repo, str) and isinstance(body, str):
207
290
  return PullRequestDraft(owner, repo, body)
208
291
  return None
209
- tool_input = all_payload_fields.get("tool_input")
210
- command = tool_input.get("command") if isinstance(tool_input, dict) else None
211
- if all_payload_fields.get("tool_name") not in SHELL_TOOL_NAMES or not isinstance(command, str):
292
+ command = shell_command(all_payload_fields)
293
+ if command is None:
212
294
  return None
213
- working_directory = all_payload_fields.get("cwd")
214
- return _shell_draft(command, working_directory if isinstance(working_directory, str) else "")
295
+ return _shell_draft(command, _working_directory(all_payload_fields))
215
296
 
216
297
 
217
298
  def _reason_for_parent(
@@ -237,13 +318,17 @@ def duplicate_followup_reason(
237
318
  ) -> str | None:
238
319
  """Return a deny reason when an open pull request already follows up the same parent.
239
320
 
240
- Any read failure returns None, so the pull request opens.
321
+ Any read failure returns None, so the pull request opens. When no create
322
+ body carries a "Follow-up to #N" line, nothing is read, not even the
323
+ origin remote.
241
324
 
242
325
  Args:
243
326
  all_payload_fields: The parsed PreToolUse input.
244
327
  read_open: Reads the open pull requests of an owner and repository;
245
328
  None reads them from the GitHub API.
246
329
  """
330
+ if not _names_a_parent(all_payload_fields):
331
+ return None
247
332
  draft = pull_request_draft(all_payload_fields)
248
333
  if draft is None:
249
334
  return None
@@ -0,0 +1,284 @@
1
+ """Remember and time each read the pull request lifecycle gate makes, for one gate run.
2
+
3
+ One gate run is one call of ``decision_for``. Several checks in that run
4
+ ask git or GitHub the same question, such as the merge base of the head
5
+ branch. The first ask reads; each later ask in the same run gets the
6
+ remembered answer, unanswered ones included::
7
+
8
+ with gate_run():
9
+ answer_once(("origin", "/repo"), read_origin) -> runs read_origin
10
+ answer_once(("origin", "/repo"), read_origin) -> the remembered answer
11
+ answer_once(("origin", "/repo"), read_origin) -> runs read_origin: no run is open
12
+
13
+ The gate process starts its read deadlines first, so every read fits the
14
+ host's timeout. Two deadlines are fixed points from that start::
15
+
16
+ start start + 12 s start + 20 s
17
+ |-- proof and look reads --|-- follow-up reads only --|
18
+ |-------------- follow-up reads ----------------------|
19
+
20
+ A read gets the smaller of its own timeout and the time left in its
21
+ slice. A read with no time left is skipped and comes back unanswered. A
22
+ child that outlives its allowance is killed, its pipes get a short grace,
23
+ and it comes back unanswered. The run notes each read the deadline cut
24
+ short: a skipped read, and a stopped read whose allowance was below its
25
+ own timeout. With no deadlines started, as in a library call or a
26
+ unit test, each read keeps its own timeout.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import subprocess
32
+ import sys
33
+ import threading
34
+ import time
35
+ from collections.abc import Callable, Hashable, Iterator, Sequence
36
+ from contextlib import contextmanager
37
+ from contextvars import ContextVar
38
+ from dataclasses import dataclass, field
39
+ from enum import Enum
40
+ from pathlib import Path
41
+ from typing import cast
42
+
43
+ hooks_directory = str(Path(__file__).resolve().parent.parent)
44
+ if hooks_directory not in sys.path:
45
+ sys.path.insert(0, hooks_directory)
46
+
47
+ from hooks_constants.gate_run_reads_constants import (
48
+ FOLLOWUP_READS_SECONDS,
49
+ KILL_GRACE_SECONDS,
50
+ PROOF_AND_LOOK_READS_SECONDS,
51
+ )
52
+ from hooks_constants.subprocess_window import hidden_window_creation_flags
53
+
54
+
55
+ class ReadSlice(Enum):
56
+ """Which deadline a read answers to, as seconds from the start of the gate process."""
57
+
58
+ PROOF_AND_LOOK = PROOF_AND_LOOK_READS_SECONDS
59
+ FOLLOWUP = PROOF_AND_LOOK_READS_SECONDS + FOLLOWUP_READS_SECONDS
60
+
61
+
62
+ @dataclass
63
+ class GateRun:
64
+ """The answers one gate run has read, and whether a deadline cut one of its reads short."""
65
+
66
+ answer_by_question: dict[Hashable, object] = field(default_factory=dict)
67
+ was_read_cut_short: bool = False
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class ReadDeadlines:
72
+ """The clock and the moment the gate process started its read deadlines."""
73
+
74
+ clock: Callable[[], float]
75
+ started_at: float
76
+
77
+ def seconds_left(self, read_slice: ReadSlice) -> float:
78
+ """Return the seconds left before this slice's deadline, negative once it passed.
79
+
80
+ Args:
81
+ read_slice: The slice whose deadline counts.
82
+ """
83
+ return self.started_at + read_slice.value - self.clock()
84
+
85
+
86
+ open_gate_run: ContextVar[GateRun | None] = ContextVar("open_gate_run", default=None)
87
+ started_read_deadlines: ContextVar[ReadDeadlines | None] = ContextVar("started_read_deadlines", default=None)
88
+
89
+
90
+ @contextmanager
91
+ def gate_run() -> Iterator[GateRun]:
92
+ """Open one gate run for the ``with`` block and close it when the block ends.
93
+
94
+ Yields:
95
+ The run, which holds every answer read inside the block.
96
+ """
97
+ run = GateRun()
98
+ token = open_gate_run.set(run)
99
+ try:
100
+ yield run
101
+ finally:
102
+ open_gate_run.reset(token)
103
+
104
+
105
+ @contextmanager
106
+ def read_deadlines_started(clock: Callable[[], float] = time.monotonic) -> Iterator[ReadDeadlines]:
107
+ """Start the read deadlines now for the ``with`` block, and drop them when it ends.
108
+
109
+ Args:
110
+ clock: The seconds clock the deadlines read; tests pass a fake one.
111
+
112
+ Yields:
113
+ The started deadlines.
114
+ """
115
+ deadlines = ReadDeadlines(clock, clock())
116
+ token = started_read_deadlines.set(deadlines)
117
+ try:
118
+ yield deadlines
119
+ finally:
120
+ started_read_deadlines.reset(token)
121
+
122
+
123
+ def answer_once[AnswerType](question: Hashable, read: Callable[[], AnswerType]) -> AnswerType:
124
+ """Return the open run's answer to ``question``, reading it the first time it is asked.
125
+
126
+ Args:
127
+ question: What the read asks, such as ``("origin", working_directory)``.
128
+ read: The read that answers it; its None answer is remembered too.
129
+
130
+ Returns:
131
+ The answer. With no run open, ``read`` runs on every call.
132
+ """
133
+ run = open_gate_run.get()
134
+ if run is None:
135
+ return read()
136
+ if question not in run.answer_by_question:
137
+ run.answer_by_question[question] = read()
138
+ return cast(AnswerType, run.answer_by_question[question])
139
+
140
+
141
+ def read_allowance(own_timeout_seconds: float, read_slice: ReadSlice) -> float | None:
142
+ """Return how long a read may wait, or None when its slice has no time left.
143
+
144
+ ::
145
+
146
+ no deadlines started, own timeout 5 -> 5
147
+ 3 s left in the proof and look slice, own 5 -> 3
148
+ the slice's deadline passed -> None
149
+
150
+ Args:
151
+ own_timeout_seconds: The timeout the read carries on its own.
152
+ read_slice: The slice whose deadline the read answers to.
153
+ """
154
+ deadlines = started_read_deadlines.get()
155
+ if deadlines is None:
156
+ return own_timeout_seconds
157
+ seconds_left = deadlines.seconds_left(read_slice)
158
+ if seconds_left <= 0:
159
+ return None
160
+ return min(own_timeout_seconds, seconds_left)
161
+
162
+
163
+ def _note_read_cut_short() -> None:
164
+ run = open_gate_run.get()
165
+ if run is not None:
166
+ run.was_read_cut_short = True
167
+
168
+
169
+ def _started_child(all_command_words: Sequence[str], working_directory: str | None) -> subprocess.Popen[str] | None:
170
+ try:
171
+ return subprocess.Popen(
172
+ list(all_command_words),
173
+ cwd=working_directory or None,
174
+ stdin=subprocess.DEVNULL,
175
+ stdout=subprocess.PIPE,
176
+ stderr=subprocess.DEVNULL,
177
+ text=True,
178
+ encoding="utf-8",
179
+ errors="replace",
180
+ creationflags=hidden_window_creation_flags(),
181
+ )
182
+ except OSError:
183
+ return None
184
+
185
+
186
+ def _stop_child(child: subprocess.Popen[str]) -> None:
187
+ """Kill the child, then wait a bounded grace, so a grandchild that keeps the output pipe open cannot hold the gate."""
188
+ child.kill()
189
+ try:
190
+ child.communicate(timeout=KILL_GRACE_SECONDS)
191
+ except subprocess.TimeoutExpired:
192
+ return
193
+
194
+
195
+ def child_stdout(
196
+ all_command_words: Sequence[str],
197
+ own_timeout_seconds: float,
198
+ read_slice: ReadSlice,
199
+ working_directory: str | None = None,
200
+ ) -> str | None:
201
+ """Run one read-only child and return its output, or None when it gives no answer.
202
+
203
+ ::
204
+
205
+ child exits 0 and prints "main\\n" -> "main\\n"
206
+ child exits 1, or cannot start -> None
207
+ child outlives its allowance -> None, after a kill and a short pipe grace
208
+ the slice has no time left -> None, and the child never starts
209
+
210
+ Args:
211
+ all_command_words: The program and its arguments.
212
+ own_timeout_seconds: The timeout the read carries on its own.
213
+ read_slice: The slice whose deadline the read answers to.
214
+ working_directory: The directory the child runs in, or None for the gate's own.
215
+ """
216
+ allowance = read_allowance(own_timeout_seconds, read_slice)
217
+ if allowance is None:
218
+ _note_read_cut_short()
219
+ return None
220
+ child = _started_child(all_command_words, working_directory)
221
+ if child is None:
222
+ return None
223
+ return _answer_within(child, allowance, own_timeout_seconds)
224
+
225
+
226
+ def _answer_within(child: subprocess.Popen[str], allowance: float, own_timeout_seconds: float) -> str | None:
227
+ try:
228
+ printed_text = child.communicate(timeout=allowance)[0]
229
+ except subprocess.TimeoutExpired:
230
+ _stop_child(child)
231
+ if allowance < own_timeout_seconds:
232
+ _note_read_cut_short()
233
+ return None
234
+ return printed_text if child.returncode == 0 else None
235
+
236
+
237
+ def _answers_in_a_daemon_thread[AnswerType](
238
+ read: Callable[[float], AnswerType], allowance: float
239
+ ) -> tuple[list[AnswerType], list[Exception]]:
240
+ all_answers: list[AnswerType] = []
241
+ all_errors: list[Exception] = []
242
+
243
+ def run_read() -> None:
244
+ try:
245
+ all_answers.append(read(allowance))
246
+ except Exception as error:
247
+ all_errors.append(error)
248
+
249
+ reader = threading.Thread(target=run_read, daemon=True)
250
+ reader.start()
251
+ reader.join(allowance)
252
+ return all_answers, all_errors
253
+
254
+
255
+ def answer_within_allowance[AnswerType](
256
+ read: Callable[[float], AnswerType], own_timeout_seconds: float, read_slice: ReadSlice
257
+ ) -> AnswerType | None:
258
+ """Run one read in a daemon thread and return its answer, or None when the allowance runs out first.
259
+
260
+ ::
261
+
262
+ read answers in 1 s, allowance 4 s -> its answer
263
+ read raises OSError -> the same OSError
264
+ read still waiting after 4 s -> None; the thread is left to end on its own
265
+
266
+ The bound covers the whole read, connect and headers included.
267
+
268
+ Args:
269
+ read: The read; it gets the allowance in seconds and must not answer None.
270
+ own_timeout_seconds: The timeout the read carries on its own.
271
+ read_slice: The slice whose deadline the read answers to.
272
+ """
273
+ allowance = read_allowance(own_timeout_seconds, read_slice)
274
+ if allowance is None:
275
+ _note_read_cut_short()
276
+ return None
277
+ all_answers, all_errors = _answers_in_a_daemon_thread(read, allowance)
278
+ if all_errors:
279
+ raise all_errors[0]
280
+ if all_answers:
281
+ return all_answers[0]
282
+ if allowance < own_timeout_seconds:
283
+ _note_read_cut_short()
284
+ return None