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.
- package/docs/rule-guides/proof-before-pull-request.md +4 -2
- package/hooks/blocking/followup_pr_dedupe.py +118 -33
- package/hooks/blocking/gate_run_reads.py +286 -0
- package/hooks/blocking/pr_lifecycle_skill_gate.py +33 -33
- package/hooks/blocking/pull_request_proof.py +60 -63
- package/hooks/blocking/test_followup_pr_dedupe.py +56 -0
- package/hooks/blocking/test_gate_run_reads.py +300 -0
- package/hooks/blocking/test_pr_lifecycle_skill_gate.py +89 -1
- package/hooks/blocking/test_pull_request_proof.py +63 -2
- package/hooks/features/conduct-gates.md +1 -1
- package/hooks/hooks.json +1 -1
- package/hooks/hooks_constants/gate_run_reads_constants.py +10 -0
- package/hooks/hooks_constants/test_followup_pr_dedupe_constants.py +0 -4
- package/hooks/pyproject.toml +1 -0
- package/package.json +1 -1
|
@@ -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.
|
|
@@ -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=
|
|
86
|
+
with urllib.request.urlopen(request, timeout=timeout_seconds) as reply:
|
|
70
87
|
answer = json.loads(reply.read())
|
|
71
|
-
return
|
|
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
|
|
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
|
-
|
|
100
|
-
|
|
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
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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,
|
|
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
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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
|
-
|
|
159
|
-
for
|
|
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
|
-
|
|
210
|
-
|
|
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
|
-
|
|
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,286 @@
|
|
|
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 TypeVar, 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
|
+
AnswerType = TypeVar("AnswerType")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ReadSlice(Enum):
|
|
58
|
+
"""Which deadline a read answers to, as seconds from the start of the gate process."""
|
|
59
|
+
|
|
60
|
+
PROOF_AND_LOOK = PROOF_AND_LOOK_READS_SECONDS
|
|
61
|
+
FOLLOWUP = PROOF_AND_LOOK_READS_SECONDS + FOLLOWUP_READS_SECONDS
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class GateRun:
|
|
66
|
+
"""The answers one gate run has read, and whether a deadline cut one of its reads short."""
|
|
67
|
+
|
|
68
|
+
answer_by_question: dict[Hashable, object] = field(default_factory=dict)
|
|
69
|
+
was_read_cut_short: bool = False
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class ReadDeadlines:
|
|
74
|
+
"""The clock and the moment the gate process started its read deadlines."""
|
|
75
|
+
|
|
76
|
+
clock: Callable[[], float]
|
|
77
|
+
started_at: float
|
|
78
|
+
|
|
79
|
+
def seconds_left(self, read_slice: ReadSlice) -> float:
|
|
80
|
+
"""Return the seconds left before this slice's deadline, negative once it passed.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
read_slice: The slice whose deadline counts.
|
|
84
|
+
"""
|
|
85
|
+
return self.started_at + read_slice.value - self.clock()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
open_gate_run: ContextVar[GateRun | None] = ContextVar("open_gate_run", default=None)
|
|
89
|
+
started_read_deadlines: ContextVar[ReadDeadlines | None] = ContextVar("started_read_deadlines", default=None)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@contextmanager
|
|
93
|
+
def gate_run() -> Iterator[GateRun]:
|
|
94
|
+
"""Open one gate run for the ``with`` block and close it when the block ends.
|
|
95
|
+
|
|
96
|
+
Yields:
|
|
97
|
+
The run, which holds every answer read inside the block.
|
|
98
|
+
"""
|
|
99
|
+
run = GateRun()
|
|
100
|
+
token = open_gate_run.set(run)
|
|
101
|
+
try:
|
|
102
|
+
yield run
|
|
103
|
+
finally:
|
|
104
|
+
open_gate_run.reset(token)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@contextmanager
|
|
108
|
+
def read_deadlines_started(clock: Callable[[], float] = time.monotonic) -> Iterator[ReadDeadlines]:
|
|
109
|
+
"""Start the read deadlines now for the ``with`` block, and drop them when it ends.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
clock: The seconds clock the deadlines read; tests pass a fake one.
|
|
113
|
+
|
|
114
|
+
Yields:
|
|
115
|
+
The started deadlines.
|
|
116
|
+
"""
|
|
117
|
+
deadlines = ReadDeadlines(clock, clock())
|
|
118
|
+
token = started_read_deadlines.set(deadlines)
|
|
119
|
+
try:
|
|
120
|
+
yield deadlines
|
|
121
|
+
finally:
|
|
122
|
+
started_read_deadlines.reset(token)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def answer_once(question: Hashable, read: Callable[[], AnswerType]) -> AnswerType:
|
|
126
|
+
"""Return the open run's answer to ``question``, reading it the first time it is asked.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
question: What the read asks, such as ``("origin", working_directory)``.
|
|
130
|
+
read: The read that answers it; its None answer is remembered too.
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
The answer. With no run open, ``read`` runs on every call.
|
|
134
|
+
"""
|
|
135
|
+
run = open_gate_run.get()
|
|
136
|
+
if run is None:
|
|
137
|
+
return read()
|
|
138
|
+
if question not in run.answer_by_question:
|
|
139
|
+
run.answer_by_question[question] = read()
|
|
140
|
+
return cast(AnswerType, run.answer_by_question[question])
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def read_allowance(own_timeout_seconds: float, read_slice: ReadSlice) -> float | None:
|
|
144
|
+
"""Return how long a read may wait, or None when its slice has no time left.
|
|
145
|
+
|
|
146
|
+
::
|
|
147
|
+
|
|
148
|
+
no deadlines started, own timeout 5 -> 5
|
|
149
|
+
3 s left in the proof and look slice, own 5 -> 3
|
|
150
|
+
the slice's deadline passed -> None
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
own_timeout_seconds: The timeout the read carries on its own.
|
|
154
|
+
read_slice: The slice whose deadline the read answers to.
|
|
155
|
+
"""
|
|
156
|
+
deadlines = started_read_deadlines.get()
|
|
157
|
+
if deadlines is None:
|
|
158
|
+
return own_timeout_seconds
|
|
159
|
+
seconds_left = deadlines.seconds_left(read_slice)
|
|
160
|
+
if seconds_left <= 0:
|
|
161
|
+
return None
|
|
162
|
+
return min(own_timeout_seconds, seconds_left)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _note_read_cut_short() -> None:
|
|
166
|
+
run = open_gate_run.get()
|
|
167
|
+
if run is not None:
|
|
168
|
+
run.was_read_cut_short = True
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _started_child(all_command_words: Sequence[str], working_directory: str | None) -> subprocess.Popen[str] | None:
|
|
172
|
+
try:
|
|
173
|
+
return subprocess.Popen(
|
|
174
|
+
list(all_command_words),
|
|
175
|
+
cwd=working_directory or None,
|
|
176
|
+
stdin=subprocess.DEVNULL,
|
|
177
|
+
stdout=subprocess.PIPE,
|
|
178
|
+
stderr=subprocess.DEVNULL,
|
|
179
|
+
text=True,
|
|
180
|
+
encoding="utf-8",
|
|
181
|
+
errors="replace",
|
|
182
|
+
creationflags=hidden_window_creation_flags(),
|
|
183
|
+
)
|
|
184
|
+
except OSError:
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _stop_child(child: subprocess.Popen[str]) -> None:
|
|
189
|
+
"""Kill the child, then wait a bounded grace, so a grandchild that keeps the output pipe open cannot hold the gate."""
|
|
190
|
+
child.kill()
|
|
191
|
+
try:
|
|
192
|
+
child.communicate(timeout=KILL_GRACE_SECONDS)
|
|
193
|
+
except subprocess.TimeoutExpired:
|
|
194
|
+
return
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def child_stdout(
|
|
198
|
+
all_command_words: Sequence[str],
|
|
199
|
+
own_timeout_seconds: float,
|
|
200
|
+
read_slice: ReadSlice,
|
|
201
|
+
working_directory: str | None = None,
|
|
202
|
+
) -> str | None:
|
|
203
|
+
"""Run one read-only child and return its output, or None when it gives no answer.
|
|
204
|
+
|
|
205
|
+
::
|
|
206
|
+
|
|
207
|
+
child exits 0 and prints "main\\n" -> "main\\n"
|
|
208
|
+
child exits 1, or cannot start -> None
|
|
209
|
+
child outlives its allowance -> None, after a kill and a short pipe grace
|
|
210
|
+
the slice has no time left -> None, and the child never starts
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
all_command_words: The program and its arguments.
|
|
214
|
+
own_timeout_seconds: The timeout the read carries on its own.
|
|
215
|
+
read_slice: The slice whose deadline the read answers to.
|
|
216
|
+
working_directory: The directory the child runs in, or None for the gate's own.
|
|
217
|
+
"""
|
|
218
|
+
allowance = read_allowance(own_timeout_seconds, read_slice)
|
|
219
|
+
if allowance is None:
|
|
220
|
+
_note_read_cut_short()
|
|
221
|
+
return None
|
|
222
|
+
child = _started_child(all_command_words, working_directory)
|
|
223
|
+
if child is None:
|
|
224
|
+
return None
|
|
225
|
+
return _answer_within(child, allowance, own_timeout_seconds)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _answer_within(child: subprocess.Popen[str], allowance: float, own_timeout_seconds: float) -> str | None:
|
|
229
|
+
try:
|
|
230
|
+
printed_text = child.communicate(timeout=allowance)[0]
|
|
231
|
+
except subprocess.TimeoutExpired:
|
|
232
|
+
_stop_child(child)
|
|
233
|
+
if allowance < own_timeout_seconds:
|
|
234
|
+
_note_read_cut_short()
|
|
235
|
+
return None
|
|
236
|
+
return printed_text if child.returncode == 0 else None
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _answers_in_a_daemon_thread(
|
|
240
|
+
read: Callable[[float], AnswerType], allowance: float
|
|
241
|
+
) -> tuple[list[AnswerType], list[Exception]]:
|
|
242
|
+
all_answers: list[AnswerType] = []
|
|
243
|
+
all_errors: list[Exception] = []
|
|
244
|
+
|
|
245
|
+
def run_read() -> None:
|
|
246
|
+
try:
|
|
247
|
+
all_answers.append(read(allowance))
|
|
248
|
+
except Exception as error:
|
|
249
|
+
all_errors.append(error)
|
|
250
|
+
|
|
251
|
+
reader = threading.Thread(target=run_read, daemon=True)
|
|
252
|
+
reader.start()
|
|
253
|
+
reader.join(allowance)
|
|
254
|
+
return all_answers, all_errors
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def answer_within_allowance(
|
|
258
|
+
read: Callable[[float], AnswerType], own_timeout_seconds: float, read_slice: ReadSlice
|
|
259
|
+
) -> AnswerType | None:
|
|
260
|
+
"""Run one read in a daemon thread and return its answer, or None when the allowance runs out first.
|
|
261
|
+
|
|
262
|
+
::
|
|
263
|
+
|
|
264
|
+
read answers in 1 s, allowance 4 s -> its answer
|
|
265
|
+
read raises OSError -> the same OSError
|
|
266
|
+
read still waiting after 4 s -> None; the thread is left to end on its own
|
|
267
|
+
|
|
268
|
+
The bound covers the whole read, connect and headers included.
|
|
269
|
+
|
|
270
|
+
Args:
|
|
271
|
+
read: The read; it gets the allowance in seconds and must not answer None.
|
|
272
|
+
own_timeout_seconds: The timeout the read carries on its own.
|
|
273
|
+
read_slice: The slice whose deadline the read answers to.
|
|
274
|
+
"""
|
|
275
|
+
allowance = read_allowance(own_timeout_seconds, read_slice)
|
|
276
|
+
if allowance is None:
|
|
277
|
+
_note_read_cut_short()
|
|
278
|
+
return None
|
|
279
|
+
all_answers, all_errors = _answers_in_a_daemon_thread(read, allowance)
|
|
280
|
+
if all_errors:
|
|
281
|
+
raise all_errors[0]
|
|
282
|
+
if all_answers:
|
|
283
|
+
return all_answers[0]
|
|
284
|
+
if allowance < own_timeout_seconds:
|
|
285
|
+
_note_read_cut_short()
|
|
286
|
+
return None
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
"""Deny pull request lifecycle actions until their skill appears in the transcript.
|
|
1
|
+
"""Deny pull request lifecycle actions until their skill appears in the transcript.
|
|
2
|
+
|
|
3
|
+
A gate silent at its 30 s ``hooks.json`` timeout lets the call through, so its git and GitHub reads end by 21 s.
|
|
4
|
+
``blocking/gate_run_reads.py`` draws that budget. A deny from a run it cut short says a second run may pass.
|
|
5
|
+
"""
|
|
2
6
|
|
|
3
7
|
from __future__ import annotations
|
|
4
8
|
|
|
@@ -75,15 +79,9 @@ from hooks_constants.hook_specific_output_keys import (
|
|
|
75
79
|
from hooks_constants.pre_tool_use_stdin import print_decision_from_stdin
|
|
76
80
|
from hooks_constants.setup_project_paths_constants import DECODE_ERRORS_POLICY, UTF8_ENCODING
|
|
77
81
|
from blocking.followup_pr_dedupe import create_tool_fields, duplicate_followup_reason
|
|
78
|
-
from blocking.
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
missing_eval_section_reason,
|
|
82
|
-
missing_existing_work_reason,
|
|
83
|
-
missing_flowchart_reason,
|
|
84
|
-
missing_look_reason,
|
|
85
|
-
missing_proof_reason,
|
|
86
|
-
)
|
|
82
|
+
from blocking.gate_run_reads import gate_run, read_deadlines_started
|
|
83
|
+
from hooks_constants.gate_run_reads_constants import READS_RAN_OUT_SENTENCE
|
|
84
|
+
from blocking import pull_request_proof as proof
|
|
87
85
|
from hooks_constants.pull_request_proof_constants import MISSING_BUILD_EVAL_REASON
|
|
88
86
|
from transcript_skill_scan import (
|
|
89
87
|
invokes_skill_with_argument,
|
|
@@ -383,33 +381,34 @@ def decision_for(all_payload_fields: dict[str, object]) -> dict[str, object] | N
|
|
|
383
381
|
changed page whose proof shows no picture -> MISSING_LOOK_REASON
|
|
384
382
|
feature pull request, no /claude-api build-eval -> MISSING_BUILD_EVAL_REASON
|
|
385
383
|
second follow-up pull request for one parent -> DUPLICATE_FOLLOWUP_REASON_TEMPLATE
|
|
384
|
+
any deny above in a run whose deadline cut a read -> that reason + READS_RAN_OUT_SENTENCE
|
|
385
|
+
|
|
386
|
+
The checks share one gate run, so two checks that ask git or GitHub one question read it once.
|
|
386
387
|
|
|
387
388
|
Args:
|
|
388
389
|
all_payload_fields: The parsed PreToolUse input.
|
|
389
390
|
"""
|
|
390
391
|
if not _is_governed_action(all_payload_fields):
|
|
391
392
|
return None
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
if
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
duplicate_reason = duplicate_followup_reason(all_payload_fields)
|
|
412
|
-
return None if duplicate_reason is None else deny_decision(duplicate_reason)
|
|
393
|
+
with gate_run() as run:
|
|
394
|
+
reason = _first_broken_rule_reason(all_payload_fields)
|
|
395
|
+
note = READS_RAN_OUT_SENTENCE if run.was_read_cut_short else ""
|
|
396
|
+
return None if reason is None else deny_decision(reason + note)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _first_broken_rule_reason(all_fields: dict[str, object]) -> str | None:
|
|
400
|
+
if _is_skill_unloaded(all_fields):
|
|
401
|
+
return DENY_REASON
|
|
402
|
+
return (
|
|
403
|
+
proof.missing_proof_reason(all_fields)
|
|
404
|
+
or proof.edit_proof_reason(all_fields)
|
|
405
|
+
or proof.missing_existing_work_reason(all_fields)
|
|
406
|
+
or proof.missing_flowchart_reason(all_fields)
|
|
407
|
+
or proof.missing_eval_section_reason(all_fields)
|
|
408
|
+
or proof.missing_look_reason(all_fields)
|
|
409
|
+
or (MISSING_BUILD_EVAL_REASON if proof.is_feature_pull_request(all_fields) and is_build_eval_missing(all_fields) else None)
|
|
410
|
+
or duplicate_followup_reason(all_fields)
|
|
411
|
+
)
|
|
413
412
|
|
|
414
413
|
|
|
415
414
|
def transcript_paths(all_payload_fields: dict[str, object]) -> list[str]:
|
|
@@ -482,8 +481,9 @@ def deny_decision(reason: str) -> dict[str, object]:
|
|
|
482
481
|
|
|
483
482
|
|
|
484
483
|
def main() -> int:
|
|
485
|
-
"""
|
|
486
|
-
|
|
484
|
+
"""Start the read deadlines, read one payload, print a deny when needed, and exit zero."""
|
|
485
|
+
with read_deadlines_started():
|
|
486
|
+
return print_decision_from_stdin(decision_for)
|
|
487
487
|
|
|
488
488
|
|
|
489
489
|
if __name__ == "__main__":
|