claude-dev-env 8.117.2 → 8.117.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/_shared/pr-loop/scripts/pyproject.toml +1 -1
  2. package/_shared/process-tree/scripts/pyproject.toml +1 -1
  3. package/bin/cde.mjs +4 -3
  4. package/bin/cde.test.mjs +87 -1
  5. package/bin/codex-compat.mjs +4 -3
  6. package/bin/codex-compat.test.mjs +91 -1
  7. package/bin/install-plan.mjs +2 -1
  8. package/bin/install.mjs +24 -7
  9. package/bin/install.plan.test.mjs +15 -0
  10. package/bin/install.test.mjs +61 -0
  11. package/bin/python-probe.mjs +42 -0
  12. package/bin/python-probe.test.mjs +19 -2
  13. package/docs/rule-guides/features-start-with-an-eval.md +3 -3
  14. package/docs/rule-guides/proof-before-pull-request.md +2 -2
  15. package/hooks/blocking/bash_pre_tool_use_dispatcher.py +11 -4
  16. package/hooks/blocking/build_eval_before_eval_write_gate.py +10 -4
  17. package/hooks/blocking/followup_pr_dedupe.py +381 -64
  18. package/hooks/blocking/gate_child_process.py +187 -0
  19. package/hooks/blocking/gate_run_reads.py +116 -35
  20. package/hooks/blocking/merge_review_gate.py +93 -10
  21. package/hooks/blocking/merge_review_gate_parts/create_folders.py +346 -0
  22. package/hooks/blocking/merge_review_gate_parts/create_options.py +86 -0
  23. package/hooks/blocking/merge_review_gate_parts/folder_state.py +107 -0
  24. package/hooks/blocking/merge_review_gate_parts/open_request.py +199 -64
  25. package/hooks/blocking/merge_review_gate_parts/quoted_lines.py +283 -0
  26. package/hooks/blocking/merge_review_gate_parts/wrapped_creates.py +126 -0
  27. package/hooks/blocking/pr_lifecycle_skill_gate.py +61 -18
  28. package/hooks/blocking/pre_tool_use_dispatcher.py +25 -3
  29. package/hooks/blocking/pull_request_proof.py +5 -51
  30. package/hooks/blocking/pull_request_proof_edit_gate.py +19 -5
  31. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +54 -0
  32. package/hooks/blocking/test_build_eval_before_eval_write_gate.py +64 -0
  33. package/hooks/blocking/test_followup_pr_dedupe.py +464 -1
  34. package/hooks/blocking/test_gate_child_process.py +64 -0
  35. package/hooks/blocking/test_gate_run_reads.py +364 -4
  36. package/hooks/blocking/test_merge_review_gate.py +832 -39
  37. package/hooks/blocking/test_pr_lifecycle_skill_gate.py +130 -4
  38. package/hooks/blocking/test_pre_tool_use_dispatcher.py +64 -0
  39. package/hooks/blocking/test_pull_request_proof.py +16 -0
  40. package/hooks/blocking/test_pull_request_proof_edit_gate.py +60 -0
  41. package/hooks/blocking/tests/test_create_folders.py +290 -0
  42. package/hooks/blocking/tests/test_create_options.py +34 -0
  43. package/hooks/blocking/tests/test_folder_state.py +40 -0
  44. package/hooks/blocking/tests/test_open_request.py +350 -44
  45. package/hooks/blocking/tests/test_quoted_lines.py +86 -0
  46. package/hooks/blocking/tests/test_wrapped_creates.py +42 -0
  47. package/hooks/features/bash-dispatchers.md +1 -1
  48. package/hooks/features/conduct-gates.md +7 -7
  49. package/hooks/features/write-edit-blocking.md +3 -3
  50. package/hooks/hooks_constants/build_eval_before_eval_write_gate_constants.py +5 -0
  51. package/hooks/hooks_constants/followup_pr_dedupe_constants.py +34 -1
  52. package/hooks/hooks_constants/gate_fault.py +52 -0
  53. package/hooks/hooks_constants/gate_fault_constants.py +13 -0
  54. package/hooks/hooks_constants/gate_run_reads_constants.py +9 -1
  55. package/hooks/hooks_constants/merge_review_gate_constants.py +94 -1
  56. package/hooks/hooks_constants/piped_pytest_blocker_constants.py +2 -0
  57. package/hooks/hooks_constants/pr_lifecycle_skill_gate_constants.py +6 -1
  58. package/hooks/hooks_constants/pre_tool_use_stdin.py +23 -3
  59. package/hooks/hooks_constants/shell_command_pipeline.py +68 -8
  60. package/hooks/hooks_constants/shell_command_segments.py +2 -2
  61. package/hooks/hooks_constants/shell_command_wrappers.py +3 -2
  62. package/hooks/hooks_constants/test_followup_pr_dedupe_constants.py +7 -0
  63. package/hooks/hooks_constants/test_gate_fault.py +41 -0
  64. package/hooks/hooks_constants/test_piped_pytest_blocker_constants.py +5 -0
  65. package/hooks/hooks_constants/test_pr_lifecycle_skill_gate_constants.py +10 -0
  66. package/hooks/hooks_constants/test_pre_tool_use_stdin.py +97 -0
  67. package/hooks/hooks_constants/test_shell_command_pipeline.py +55 -0
  68. package/hooks/hooks_constants/test_shell_command_segments.py +15 -0
  69. package/hooks/hooks_constants/test_shell_command_wrappers.py +6 -0
  70. package/hooks/hooks_constants/transcript_skill_scan_constants.py +6 -0
  71. package/hooks/pyproject.toml +2 -3
  72. package/hooks/test_python_floor.py +197 -0
  73. package/hooks/test_transcript_skill_scan.py +324 -0
  74. package/hooks/transcript_skill_scan.py +233 -2
  75. package/hooks/validators/code_quality_checks.py +119 -17
  76. package/hooks/validators/test_code_quality_checks.py +110 -4
  77. package/package.json +1 -1
@@ -12,6 +12,7 @@ if hooks_directory not in sys.path:
12
12
  sys.path.insert(0, hooks_directory)
13
13
 
14
14
  from blocking.codex_apply_patch import payload_patch_command, payload_patch_target_paths
15
+ from blocking.gate_run_reads import ReadSlice, gate_run, read_deadlines_started
15
16
  from blocking.pr_lifecycle_skill_gate import deny_decision, eval_skill_call_status
16
17
  from hooks_constants.build_eval_before_eval_write_gate_constants import (
17
18
  ALL_EVAL_DIRECTORY_NAMES,
@@ -19,6 +20,7 @@ from hooks_constants.build_eval_before_eval_write_gate_constants import (
19
20
  ALL_FILE_WRITE_TOOL_NAMES,
20
21
  APPLY_PATCH_TOOL_NAME,
21
22
  EVAL_FILE_NAME_WORD_PATTERN,
23
+ EVAL_WRITE_SCAN_RAN_OUT_SENTENCE,
22
24
  MISSING_BUILD_EVAL_BEFORE_EVAL_WRITE_REASON,
23
25
  UNREADABLE_TRANSCRIPT_BEFORE_EVAL_WRITE_REASON,
24
26
  )
@@ -81,21 +83,25 @@ def decision_for(all_payload_fields: dict[str, object]) -> dict[str, object] | N
81
83
  Write evals/cases.json, no readable transcript -> deny
82
84
  Write evals/cases.json, build-eval in transcript -> None
83
85
  Write src/app.py, no build-eval in transcript -> None
86
+ Write evals/cases.json, scan stopped at its deadline -> deny that says to call build-eval again
84
87
 
85
88
  Args:
86
89
  all_payload_fields: The parsed PreToolUse input.
87
90
  """
88
91
  if not any(is_eval_path(each_path) for each_path in _written_paths(all_payload_fields)):
89
92
  return None
90
- status = eval_skill_call_status(all_payload_fields)
93
+ with gate_run() as run:
94
+ status = eval_skill_call_status(all_payload_fields, ReadSlice.EVAL_WRITE)
91
95
  if status is None:
92
96
  return deny_decision(UNREADABLE_TRANSCRIPT_BEFORE_EVAL_WRITE_REASON)
93
- return None if status else deny_decision(MISSING_BUILD_EVAL_BEFORE_EVAL_WRITE_REASON)
97
+ scan_note = EVAL_WRITE_SCAN_RAN_OUT_SENTENCE if run.cut_scan_count else ""
98
+ return None if status else deny_decision(MISSING_BUILD_EVAL_BEFORE_EVAL_WRITE_REASON + scan_note)
94
99
 
95
100
 
96
101
  def main() -> int:
97
- """Read one payload, print a deny when needed, and exit zero."""
98
- return print_decision_from_stdin(decision_for)
102
+ """Start the scan deadline, read one payload, print a deny when needed, and exit zero."""
103
+ with read_deadlines_started():
104
+ return print_decision_from_stdin(decision_for)
99
105
 
100
106
 
101
107
  if __name__ == "__main__":
@@ -5,39 +5,68 @@ from __future__ import annotations
5
5
  import json
6
6
  import re
7
7
  import sys
8
+ import urllib.error
8
9
  import urllib.request
9
10
  from collections.abc import Callable, Iterator, Mapping
10
11
  from dataclasses import dataclass
12
+ from enum import Enum
13
+ from http import HTTPStatus
11
14
  from pathlib import Path
12
15
 
13
16
  hooks_directory = str(Path(__file__).resolve().parent.parent)
14
17
  if hooks_directory not in sys.path:
15
18
  sys.path.insert(0, hooks_directory)
16
19
 
20
+ from blocking.gate_run_reads import ReadSlice, answer_once, answer_within_allowance, child_stdout
17
21
  from hooks_constants.followup_pr_dedupe_constants import (
18
22
  ALL_BODY_FILE_OPTIONS,
19
23
  ALL_BODY_OPTIONS,
24
+ ALL_GH_ACTION_WORDS_BY_ALIAS,
25
+ ALL_GIT_REMOTE_COMMAND_WORDS,
26
+ ALL_PULL_REQUEST_DISPATCH_INPUT_KEYS,
27
+ ALL_PYTHON_NON_SCRIPT_OPTIONS,
28
+ ALL_PYTHON_OPTIONS_WITH_VALUE,
20
29
  ALL_REPOSITORY_OPTIONS,
21
30
  ALL_TITLE_OPTIONS,
31
+ ALL_VARIABLE_SETTING_PROGRAM_NAMES,
32
+ APPEND_ASSIGNMENT_MARK,
33
+ ASSIGNMENT_SEPARATOR,
22
34
  CREATE_PULL_REQUEST_TOOL_SUFFIX,
23
35
  DUPLICATE_FOLLOWUP_REASON_TEMPLATE,
24
36
  FOLLOWUP_PARENT_PATTERN,
25
- ALL_GH_CREATE_WORDS,
26
- ALL_GIT_REMOTE_COMMAND_WORDS,
27
- ALL_PULL_REQUEST_DISPATCH_INPUT_KEYS,
37
+ GH_PROGRAM_NAME,
38
+ GH_REPO_SET_FOLLOWUP_REASON_TEMPLATE,
39
+ GH_REPOSITORY_APPEND_PREFIX,
40
+ GH_REPOSITORY_ENVIRONMENT_NAME,
41
+ GH_REPOSITORY_ENVIRONMENT_PREFIX,
28
42
  GITHUB_API_ROOT,
29
43
  GITHUB_REMOTE_PATTERN,
44
+ LONG_OPTION_PREFIX,
30
45
  OPEN_PULL_REQUESTS_PATH_TEMPLATE,
46
+ OPTION_AND_VALUE_WIDTH,
47
+ OPTION_PREFIX,
48
+ PYTHON_PROGRAM_NAME_PATTERN,
31
49
  READ_TIMEOUT_SECONDS,
50
+ REPOSITORY_OPTION,
32
51
  RUN_WORKFLOW_METHOD,
52
+ SHORT_OPTION_LENGTH,
33
53
  STANDARD_INPUT_PATH,
54
+ STANDARD_INPUT_SCRIPT,
55
+ UNANSWERED_FOLLOWUP_REASON_TEMPLATE,
56
+ UNREAD_ORIGIN_FOLLOWUP_REASON_TEMPLATE,
57
+ WINDOWS_EXECUTABLE_SUFFIX,
34
58
  WORKFLOW_DISPATCH_TOOL_SUFFIX,
35
59
  )
36
- from blocking.gate_run_reads import ReadSlice, answer_once, answer_within_allowance, child_stdout
37
60
  from hooks_constants.pr_lifecycle_skill_gate_constants import SHELL_TOOL_NAMES
38
- from hooks_constants.pytest_invocation import unquoted_token
61
+ from hooks_constants.pull_request_proof_constants import (
62
+ ALL_GH_CREATE_WORDS,
63
+ PULL_REQUEST_SCRIPT_CREATE_WORD,
64
+ PULL_REQUEST_SCRIPT_NAME,
65
+ )
66
+ from hooks_constants.pytest_invocation import all_tokens_after_wrappers, unquoted_token
39
67
  from hooks_constants.setup_project_paths_constants import DECODE_ERRORS_POLICY, UTF8_ENCODING
40
68
  from hooks_constants.shell_command_pipeline import pipeline_segments_for_command
69
+ from hooks_constants.shell_command_segments import token_basename
41
70
  from hooks_constants.shell_command_wrappers import (
42
71
  all_wrapped_command_texts,
43
72
  segment_program_and_arguments,
@@ -53,7 +82,42 @@ class PullRequestDraft:
53
82
  body: str
54
83
 
55
84
 
85
+ @dataclass(frozen=True)
86
+ class UnreadOriginDraft:
87
+ """The body of a create whose repository the gate cannot read.
88
+
89
+ Attributes:
90
+ body: The create's body.
91
+ reason_template: The deny reason, for the origin remote that gave no
92
+ answer or for a command that sets ``GH_REPO``.
93
+ """
94
+
95
+ body: str
96
+ reason_template: str = UNREAD_ORIGIN_FOLLOWUP_REASON_TEMPLATE
97
+
98
+
99
+ class UnreadOpenPullRequests(Enum):
100
+ """Why a repository's open pull requests came back unread.
101
+
102
+ ::
103
+
104
+ read raised TimeoutError, or URLError whose reason is a TimeoutError -> UNANSWERED
105
+ read raised HTTPError 500 or above, a GitHub server error -> UNANSWERED
106
+ read raised HTTPError 403, 404 or 429, a refused connection,
107
+ a name that does not resolve, or malformed JSON -> FAILED
108
+
109
+ An unanswered read refuses the create, because a retry may answer. A
110
+ failed read skips that create and leaves the duplicate to the CI check.
111
+ A rate limit can last an hour and a private repository answers 404 on
112
+ every read, so a retry does not help there.
113
+ """
114
+
115
+ UNANSWERED = "no answer inside the allowance"
116
+ FAILED = "a definite failure"
117
+
118
+
56
119
  OpenPullRequestReader = Callable[[str, str], list[Mapping[str, object]]]
120
+ OpenPullRequestsAnswer = list[Mapping[str, object]] | UnreadOpenPullRequests
57
121
 
58
122
 
59
123
  def followup_parent_number(body: str) -> int | None:
@@ -69,8 +133,12 @@ def read_open_pull_requests(owner: str, repo: str) -> list[Mapping[str, object]]
69
133
  READ_TIMEOUT_SECONDS, or less when the follow-up deadline is nearer.
70
134
 
71
135
  Raises:
72
- TimeoutError: The read did not finish inside its allowance.
73
- OSError: The request failed.
136
+ TimeoutError: The read did not finish inside its allowance, or the
137
+ slice had no time left. ``duplicate_followup_reason`` refuses the create.
138
+ urllib.error.HTTPError: GitHub answered with an error status. A status of
139
+ 500 or above refuses the create, and any other status skips it.
140
+ Exception: Any other failure, such as a refused connection or a reply
141
+ that is not JSON. ``duplicate_followup_reason`` skips the create.
74
142
  """
75
143
  url = GITHUB_API_ROOT + OPEN_PULL_REQUESTS_PATH_TEMPLATE.format(owner=owner, repo=repo)
76
144
  answer = answer_within_allowance(
@@ -88,7 +156,19 @@ def _fetched_json(url: str, timeout_seconds: float) -> list[object]:
88
156
  return answer if isinstance(answer, list) else []
89
157
 
90
158
 
91
- def _option_value(all_arguments: list[str], all_option_names: frozenset[str]) -> str | None:
159
+ def option_value(all_arguments: list[str], all_option_names: frozenset[str]) -> str | None:
160
+ """Return the value of the first named option in an argument list, its quotes removed, or None.
161
+
162
+ ::
163
+
164
+ ["--head", "a", "--head", "b"], {"--head"} -> "a"
165
+ ["-H='c'"], {"-H", "--head"} -> "c"
166
+ ["--fill"], {"--head"} -> None
167
+
168
+ Args:
169
+ all_arguments: The options of one call.
170
+ all_option_names: Every spelling of the option, such as ``{"-H", "--head"}``.
171
+ """
92
172
  for each_index, each_argument in enumerate(all_arguments):
93
173
  option_name, separator, inline_value = each_argument.partition("=")
94
174
  if option_name not in all_option_names:
@@ -101,17 +181,17 @@ def _option_value(all_arguments: list[str], all_option_names: frozenset[str]) ->
101
181
 
102
182
 
103
183
  def body_from_arguments(all_arguments: list[str], working_directory: str) -> str | None:
104
- """Return the body a gh-style argument list passes, or None when it passes none.
184
+ """Return the body a gh or pull_request.py argument list passes, or None when it passes none.
105
185
 
106
186
  ``--body`` text comes back as given. A ``--body-file`` path is read from
107
187
  the working directory only when it names a regular file. Standard input,
108
188
  a directory, a named pipe, any other special file, and an unreadable file
109
189
  give None.
110
190
  """
111
- inline_body = _option_value(all_arguments, ALL_BODY_OPTIONS)
191
+ inline_body = option_value(all_arguments, ALL_BODY_OPTIONS)
112
192
  if inline_body is not None:
113
193
  return inline_body
114
- body_path = _option_value(all_arguments, ALL_BODY_FILE_OPTIONS)
194
+ body_path = option_value(all_arguments, ALL_BODY_FILE_OPTIONS)
115
195
  if body_path is None or body_path == STANDARD_INPUT_PATH:
116
196
  return None
117
197
  body_file = Path(working_directory) / body_path
@@ -124,7 +204,7 @@ def body_from_arguments(all_arguments: list[str], working_directory: str) -> str
124
204
 
125
205
 
126
206
  def title_from_arguments(all_arguments: list[str]) -> str | None:
127
- """Return the title a gh-style argument list passes, or None when it passes none.
207
+ """Return the title a gh or pull_request.py argument list passes, or None when it passes none.
128
208
 
129
209
  ::
130
210
 
@@ -132,32 +212,34 @@ def title_from_arguments(all_arguments: list[str]) -> str | None:
132
212
  ["-t=fix: y"] -> "fix: y"
133
213
  ["--fill"] -> None
134
214
  """
135
- return _option_value(all_arguments, ALL_TITLE_OPTIONS)
215
+ return option_value(all_arguments, ALL_TITLE_OPTIONS)
136
216
 
137
217
 
138
- def _origin_repository(working_directory: str) -> tuple[str, str] | None:
218
+ def _origin_remote_url(working_directory: str) -> str | None:
139
219
  return answer_once(
140
- ("origin repository", working_directory), lambda: _read_origin_repository(working_directory)
220
+ ("origin remote url", working_directory),
221
+ lambda: child_stdout(ALL_GIT_REMOTE_COMMAND_WORDS, READ_TIMEOUT_SECONDS, ReadSlice.FOLLOWUP, working_directory),
141
222
  )
142
223
 
143
224
 
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:
149
- return None
150
- match = re.search(GITHUB_REMOTE_PATTERN, printed_text.strip())
225
+ def _github_repository(remote_url: str) -> tuple[str, str] | None:
226
+ match = re.search(GITHUB_REMOTE_PATTERN, remote_url.strip())
151
227
  return (match.group(1), match.group(2)) if match else None
152
228
 
153
229
 
154
- def _repository_from_arguments(
155
- all_arguments: list[str], working_directory: str
156
- ) -> tuple[str, str] | None:
157
- named_repository = _option_value(all_arguments, ALL_REPOSITORY_OPTIONS)
158
- if named_repository is None:
159
- return _origin_repository(working_directory)
160
- owner, separator, repo = named_repository.rpartition("/")
230
+ def named_repository(repository_value: str) -> tuple[str, str] | None:
231
+ """Return the owner and name a ``--repo`` value names, or None when it names no pair.
232
+
233
+ ::
234
+
235
+ "o/r" -> ("o", "r")
236
+ "github.com/o/r" -> ("o", "r")
237
+ "notaslug" -> None
238
+
239
+ Args:
240
+ repository_value: The value a ``--repo`` option, ``-R`` or ``GH_REPO`` gives.
241
+ """
242
+ owner, separator, repo = repository_value.rpartition("/")
161
243
  owner = owner.rpartition("/")[2]
162
244
  return (owner, repo) if separator and owner and repo else None
163
245
 
@@ -183,27 +265,237 @@ def all_command_segments(command: str) -> Iterator[list[str]]:
183
265
  )
184
266
 
185
267
 
186
- def _all_create_argument_lists(command: str) -> Iterator[list[str]]:
268
+ def _python_script_index(all_arguments: list[str]) -> int | None:
269
+ index = 0
270
+ while index < len(all_arguments):
271
+ option = unquoted_token(all_arguments[index])
272
+ if option == STANDARD_INPUT_SCRIPT or not option.startswith(OPTION_PREFIX):
273
+ return index
274
+ if not option.startswith(LONG_OPTION_PREFIX) and option[:SHORT_OPTION_LENGTH] in ALL_PYTHON_NON_SCRIPT_OPTIONS:
275
+ return None
276
+ index += OPTION_AND_VALUE_WIDTH if option in ALL_PYTHON_OPTIONS_WITH_VALUE else 1
277
+ return None
278
+
279
+
280
+ def _script_arguments(program: str, all_arguments: list[str]) -> list[str] | None:
281
+ if program == PULL_REQUEST_SCRIPT_NAME:
282
+ return all_arguments
283
+ if re.fullmatch(PYTHON_PROGRAM_NAME_PATTERN, program) is None:
284
+ return None
285
+ script_index = _python_script_index(all_arguments)
286
+ if script_index is None:
287
+ return None
288
+ script_name = token_basename(unquoted_token(all_arguments[script_index]))
289
+ return all_arguments[script_index + 1 :] if script_name == PULL_REQUEST_SCRIPT_NAME else None
290
+
291
+
292
+ def _script_word_arguments(program: str, all_arguments: list[str], word: str) -> list[str] | None:
293
+ all_script_arguments = _script_arguments(program, all_arguments)
294
+ if all_script_arguments is None or all_script_arguments[:1] != [word]:
295
+ return None
296
+ return all_script_arguments[1:]
297
+
298
+
299
+ def _gh_action_arguments(all_arguments: list[str], all_gh_words: list[str]) -> list[str] | None:
300
+ index = 0
301
+ while index < len(all_arguments) and unquoted_token(all_arguments[index]).startswith(OPTION_PREFIX):
302
+ index += OPTION_AND_VALUE_WIDTH if unquoted_token(all_arguments[index]) in ALL_REPOSITORY_OPTIONS else 1
303
+ all_action_words = [
304
+ ALL_GH_ACTION_WORDS_BY_ALIAS.get(unquoted_token(each_word), unquoted_token(each_word))
305
+ for each_word in all_arguments[index : index + len(all_gh_words)]
306
+ ]
307
+ if all_action_words != all_gh_words:
308
+ return None
309
+ return [*all_arguments[index + len(all_gh_words) :], *all_arguments[:index]]
310
+
311
+
312
+ def prefix_repository(all_segment_tokens: list[str]) -> str | None:
313
+ """Return the value a ``GH_REPO=`` prefix gives a gh command, or None when it has none.
314
+
315
+ ::
316
+
317
+ ["GH_REPO=o/r", "gh", "pr", "create"] -> "o/r"
318
+ ["GH_REPO=a/b", "GH_REPO=o/r", "gh", "pr", "create"] -> "o/r"
319
+ ["GH_REPO+=o/r", "gh", "pr", "create"] -> None
320
+ ["gh", "pr", "create", "GH_REPO=o/r"] -> None
321
+
322
+ The last prefix wins, as in the shell. A ``GH_REPO+=`` prefix appends to
323
+ a value the gate cannot see, so the result after it is None.
324
+
325
+ Args:
326
+ all_segment_tokens: The tokens of one simple command.
327
+ """
328
+ repository: str | None = None
329
+ for each_token in all_segment_tokens:
330
+ unquoted_word = unquoted_token(each_token)
331
+ if token_basename(unquoted_word).removesuffix(WINDOWS_EXECUTABLE_SUFFIX) == GH_PROGRAM_NAME:
332
+ break
333
+ if unquoted_word.startswith(GH_REPOSITORY_APPEND_PREFIX):
334
+ repository = None
335
+ if unquoted_word.startswith(GH_REPOSITORY_ENVIRONMENT_PREFIX):
336
+ repository = unquoted_word[len(GH_REPOSITORY_ENVIRONMENT_PREFIX) :]
337
+ return repository
338
+
339
+
340
+ def _gh_arguments(all_segment_tokens: list[str], all_arguments: list[str], all_gh_words: list[str]) -> list[str] | None:
341
+ all_action_arguments = _gh_action_arguments(all_arguments, all_gh_words)
342
+ if all_action_arguments is None:
343
+ return None
344
+ environment_repository = prefix_repository(all_segment_tokens)
345
+ if environment_repository and option_value(all_action_arguments, ALL_REPOSITORY_OPTIONS) is None:
346
+ return [*all_action_arguments, REPOSITORY_OPTION, environment_repository]
347
+ return all_action_arguments
348
+
349
+
350
+ def _command_arguments(
351
+ all_segment_tokens: list[str], all_gh_words: list[str], script_word: str
352
+ ) -> list[str] | None:
353
+ program, all_arguments = segment_program_and_arguments(all_segment_tokens)
354
+ if program == GH_PROGRAM_NAME:
355
+ return _gh_arguments(all_segment_tokens, all_arguments, all_gh_words)
356
+ return _script_word_arguments(program, all_arguments, script_word)
357
+
358
+
359
+ def create_arguments(all_segment_tokens: list[str]) -> list[str] | None:
360
+ """Return the options of the pull request create one segment runs, or None when it runs none.
361
+
362
+ ::
363
+
364
+ ["gh", "pr", "new", "--head", "h"] -> ["--head", "h"]
365
+ ["gh", "-R", "o/r", "pr", "create"] -> ["-R", "o/r"]
366
+ ["GH_REPO=o/r", "gh", "pr", "create"] -> ["--repo", "o/r"]
367
+ ["py", "-3", "~/x/pull_request.py", "create"] -> []
368
+ ["git", "commit", "-m", "gh pr create"] -> None
369
+
370
+ A repository a root ``-R``/``--repo`` or a ``GH_REPO=`` prefix names
371
+ comes after the create's own options, so the create's own ``--repo`` wins.
372
+ A shell variable, alias or function that holds the program name is not followed.
373
+
374
+ Args:
375
+ all_segment_tokens: The tokens of one simple command.
376
+ """
377
+ return _command_arguments(all_segment_tokens, ALL_GH_CREATE_WORDS, PULL_REQUEST_SCRIPT_CREATE_WORD)
378
+
379
+
380
+ def all_pull_request_argument_lists(
381
+ command: str, all_gh_words: list[str], script_word: str
382
+ ) -> Iterator[list[str]]:
383
+ """Return the options of each gh or pull_request.py call in a command that runs one action.
384
+
385
+ ::
386
+
387
+ gh pr edit 7 --body x -> ["7", "--body", "x"]
388
+ python3 pull_request.py edit --number 8 -> ["--number", "8"]
389
+ gh pr create --body y -> nothing, for the edit action
390
+
391
+ The words before the options are dropped. A quoted call, which the
392
+ command parser reads twice, comes back once.
393
+
394
+ Args:
395
+ command: The shell command text.
396
+ all_gh_words: The gh words that name the action, such as ``["pr", "edit"]``.
397
+ script_word: The pull_request.py action word, such as ``"edit"``.
398
+ """
399
+ all_seen_arguments: set[tuple[str, ...]] = set()
187
400
  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
401
+ all_arguments = _command_arguments(each_segment, all_gh_words, script_word)
402
+ if all_arguments is None:
403
+ continue
404
+ all_unquoted_arguments = tuple(unquoted_token(each_argument) for each_argument in all_arguments)
405
+ if all_unquoted_arguments in all_seen_arguments:
406
+ continue
407
+ all_seen_arguments.add(all_unquoted_arguments)
408
+ yield all_arguments
409
+
410
+
411
+ def all_create_argument_lists(command: str) -> Iterator[list[str]]:
412
+ """Return the options of each pull request create in a command, gh and pull_request.py alike.
413
+
414
+ ::
415
+
416
+ gh pr create --title "fix: a" --body x -> ["--title", "fix: a", "--body", "x"]
417
+ python3 pull_request.py create --repo o/r --title t -> ["--repo", "o/r", "--title", "t"]
418
+ python3 pull_request.py edit --number 7 -> nothing
419
+
420
+ ``create_arguments`` reads each segment, so ``gh pr new``, root ``-R``
421
+ and ``GH_REPO=`` prefixes, and every Python spelling of the script count.
422
+
423
+ Args:
424
+ command: The shell command text.
425
+ """
426
+ return all_pull_request_argument_lists(command, ALL_GH_CREATE_WORDS, PULL_REQUEST_SCRIPT_CREATE_WORD)
191
427
 
192
428
 
193
- def _arguments_draft(all_arguments: list[str], working_directory: str) -> PullRequestDraft | None:
429
+ def _arguments_draft(
430
+ all_arguments: list[str], working_directory: str, is_gh_repository_set: bool
431
+ ) -> PullRequestDraft | UnreadOriginDraft | None:
194
432
  body = body_from_arguments(all_arguments, working_directory)
195
433
  if body is None or followup_parent_number(body) is None:
196
434
  return None
197
- repository = _repository_from_arguments(all_arguments, working_directory)
198
- if repository is None:
199
- return None
200
- return PullRequestDraft(repository[0], repository[1], body)
435
+ repository_value = option_value(all_arguments, ALL_REPOSITORY_OPTIONS)
436
+ if repository_value is None and is_gh_repository_set:
437
+ return UnreadOriginDraft(body, GH_REPO_SET_FOLLOWUP_REASON_TEMPLATE)
438
+ if repository_value is not None:
439
+ repository = named_repository(repository_value)
440
+ else:
441
+ remote_url = _origin_remote_url(working_directory)
442
+ if remote_url is None:
443
+ return UnreadOriginDraft(body)
444
+ repository = _github_repository(remote_url)
445
+ return None if repository is None else PullRequestDraft(repository[0], repository[1], body)
446
+
447
+
448
+ def sets_gh_repository(command: str) -> bool:
449
+ """Return True when a command sets or exports ``GH_REPO`` outside a create's own prefix.
201
450
 
451
+ ::
452
+
453
+ export GH_REPO=o/r ; gh pr create -> True
454
+ GH_REPO=o/r bash -c 'gh pr create' -> True
455
+ declare -x GH_REPO -> True
456
+ GH_REPO+=o/r gh pr create -> True
457
+ GH_REPO=o/r gh pr create -> False
458
+ echo GH_REPO=o/r -> False
202
459
 
203
- def _shell_followup_drafts(command: str, working_directory: str) -> list[PullRequestDraft]:
460
+ An ``export``, ``declare``, ``typeset``, ``local`` or ``readonly`` that
461
+ names ``GH_REPO`` counts, and so does a ``GH_REPO=`` assignment before any
462
+ program but a create, in the command or in a text a wrapper runs. A
463
+ ``GH_REPO+=`` append counts in each of those places and before a create
464
+ too. The gate does not follow the value, so a create that names no
465
+ repository of its own cannot be read.
466
+
467
+ Args:
468
+ command: The shell command text.
469
+ """
470
+ return any(_segment_sets_gh_repository(each_segment) for each_segment in all_command_segments(command))
471
+
472
+
473
+ def _segment_sets_gh_repository(all_segment_tokens: list[str]) -> bool:
474
+ program, all_arguments = segment_program_and_arguments(all_segment_tokens)
475
+ if program in ALL_VARIABLE_SETTING_PROGRAM_NAMES:
476
+ return GH_REPOSITORY_ENVIRONMENT_NAME in map(_assigned_name, all_arguments)
477
+ all_unwrapped_tokens = all_tokens_after_wrappers(all_segment_tokens)
478
+ program_index = len(all_unwrapped_tokens) - len(all_arguments) - (1 if program else 0)
479
+ all_prefix_words = [unquoted_token(each_token) for each_token in all_unwrapped_tokens[:program_index]]
480
+ is_create = create_arguments(all_segment_tokens) is not None
481
+ all_setting_prefixes = (
482
+ (GH_REPOSITORY_APPEND_PREFIX,)
483
+ if is_create
484
+ else (GH_REPOSITORY_ENVIRONMENT_PREFIX, GH_REPOSITORY_APPEND_PREFIX)
485
+ )
486
+ return any(each_word.startswith(all_setting_prefixes) for each_word in all_prefix_words)
487
+
488
+
489
+ def _assigned_name(argument: str) -> str:
490
+ name = unquoted_token(argument).partition(ASSIGNMENT_SEPARATOR)[0]
491
+ return name.removesuffix(APPEND_ASSIGNMENT_MARK)
492
+
493
+
494
+ def _shell_followup_drafts(command: str, working_directory: str) -> list[PullRequestDraft | UnreadOriginDraft]:
495
+ is_gh_repository_set = sets_gh_repository(command)
204
496
  all_drafts = (
205
- _arguments_draft(all_arguments, working_directory)
206
- for all_arguments in _all_create_argument_lists(command)
497
+ _arguments_draft(all_arguments, working_directory, is_gh_repository_set)
498
+ for all_arguments in all_create_argument_lists(command)
207
499
  )
208
500
  return list(dict.fromkeys(each_draft for each_draft in all_drafts if each_draft is not None))
209
501
 
@@ -267,18 +559,20 @@ def create_tool_fields(all_payload_fields: Mapping[str, object]) -> Mapping[str,
267
559
  return _dispatch_fields(tool_input) if tool_name.endswith(WORKFLOW_DISPATCH_TOOL_SUFFIX) else None
268
560
 
269
561
 
270
- def followup_drafts(all_payload_fields: Mapping[str, object]) -> list[PullRequestDraft]:
562
+ def followup_drafts(all_payload_fields: Mapping[str, object]) -> list[PullRequestDraft | UnreadOriginDraft]:
271
563
  """Return one draft per distinct repository and body among the creates whose body names a parent.
272
564
 
273
565
  ::
274
566
 
275
567
  create on o/r "Follow-up to #7" && create on o/r "Follow-up to #8" -> both drafts
276
568
  create_pull_request {owner, repo, body "Follow-up to #7"} -> that one draft
569
+ create with no --repo where the origin read gives nothing -> UnreadOriginDraft
570
+ create with no --repo whose origin is not on GitHub -> no draft
277
571
  create whose body names no parent, or any other tool -> []
278
572
 
279
573
  A body that names no parent gives no draft before any repository or
280
- origin read. A quoted create, which the command parser reads twice,
281
- gives one draft.
574
+ origin read. The origin is read once per gate run. A quoted create,
575
+ which the command parser reads twice, gives one draft.
282
576
 
283
577
  Args:
284
578
  all_payload_fields: The parsed PreToolUse input.
@@ -288,29 +582,37 @@ def followup_drafts(all_payload_fields: Mapping[str, object]) -> list[PullReques
288
582
  """
289
583
  create_fields = create_tool_fields(all_payload_fields)
290
584
  if create_fields is not None:
291
- owner, repo, body = (create_fields.get(each_key) for each_key in ("owner", "repo", "body"))
292
- if not isinstance(body, str) or followup_parent_number(body) is None:
293
- return []
294
- return [PullRequestDraft(owner, repo, body)] if isinstance(owner, str) and isinstance(repo, str) else []
585
+ return _tool_followup_drafts(create_fields)
295
586
  command = shell_command(all_payload_fields)
296
587
  if command is None:
297
588
  return []
298
589
  return _shell_followup_drafts(command, _working_directory(all_payload_fields))
299
590
 
300
591
 
301
- def _open_pull_requests_once(
302
- owner: str, repo: str, read_open: OpenPullRequestReader
303
- ) -> list[Mapping[str, object]] | None:
304
- return answer_once(("open pull requests", owner, repo), lambda: _open_pull_requests_or_none(owner, repo, read_open))
592
+ def _tool_followup_drafts(all_create_fields: Mapping[str, object]) -> list[PullRequestDraft | UnreadOriginDraft]:
593
+ owner, repo, body = (all_create_fields.get(each_key) for each_key in ("owner", "repo", "body"))
594
+ if not isinstance(body, str) or followup_parent_number(body) is None:
595
+ return []
596
+ return [PullRequestDraft(owner, repo, body)] if isinstance(owner, str) and isinstance(repo, str) else []
597
+
598
+
599
+ def _open_pull_requests_once(owner: str, repo: str, read_open: OpenPullRequestReader) -> OpenPullRequestsAnswer:
600
+ return answer_once(("open pull requests", owner, repo), lambda: _open_pull_requests_answer(owner, repo, read_open))
305
601
 
306
602
 
307
- def _open_pull_requests_or_none(
308
- owner: str, repo: str, read_open: OpenPullRequestReader
309
- ) -> list[Mapping[str, object]] | None:
603
+ def _is_unanswered(error: Exception) -> bool:
604
+ if isinstance(error, urllib.error.HTTPError):
605
+ return error.code >= HTTPStatus.INTERNAL_SERVER_ERROR
606
+ return isinstance(error, TimeoutError) or (
607
+ isinstance(error, urllib.error.URLError) and isinstance(error.reason, TimeoutError)
608
+ )
609
+
610
+
611
+ def _open_pull_requests_answer(owner: str, repo: str, read_open: OpenPullRequestReader) -> OpenPullRequestsAnswer:
310
612
  try:
311
613
  return read_open(owner, repo)
312
- except Exception:
313
- return None
614
+ except Exception as error:
615
+ return UnreadOpenPullRequests.UNANSWERED if _is_unanswered(error) else UnreadOpenPullRequests.FAILED
314
616
 
315
617
 
316
618
  def _reason_for_parent(
@@ -336,25 +638,40 @@ def duplicate_followup_reason(
336
638
  ) -> str | None:
337
639
  """Return a deny reason when an open pull request already follows up the same parent.
338
640
 
641
+ ::
642
+
643
+ open pull request #9 says "Follow-up to #7" -> DUPLICATE_FOLLOWUP_REASON_TEMPLATE
644
+ the read gives no answer inside its allowance -> UNANSWERED_FOLLOWUP_REASON_TEMPLATE
645
+ the read answers with a GitHub server error -> UNANSWERED_FOLLOWUP_REASON_TEMPLATE
646
+ no --repo, and the origin read gives nothing -> UNREAD_ORIGIN_FOLLOWUP_REASON_TEMPLATE
647
+ the read answers 403, 404 or 429, refuses, or sends bad JSON -> None for that create
648
+
339
649
  Every create body that names a parent is checked, in command order, and
340
- the first duplicate denies. A read that fails skips that create. When no
341
- create body carries a "Follow-up to #N" line, nothing is read, not even
342
- the origin remote.
650
+ the first duplicate, unanswered read or unread origin denies. A read that
651
+ answers with a failure skips that create. When no create body carries a
652
+ "Follow-up to #N" line, nothing is read, not even the origin remote.
343
653
 
344
654
  Args:
345
655
  all_payload_fields: The parsed PreToolUse input.
346
656
  read_open: Reads the open pull requests of an owner and repository;
347
- None reads them from the GitHub API.
657
+ None reads them from the GitHub API. A raised TimeoutError means
658
+ no answer; any other exception means a failed read.
348
659
  """
349
660
  reader = read_open or read_open_pull_requests
350
661
  for each_draft in followup_drafts(all_payload_fields):
351
662
  parent_number = followup_parent_number(each_draft.body)
352
663
  if parent_number is None:
353
664
  continue
354
- all_open_pull_requests = _open_pull_requests_once(each_draft.owner, each_draft.repo, reader)
355
- if all_open_pull_requests is None:
665
+ if isinstance(each_draft, UnreadOriginDraft):
666
+ return each_draft.reason_template.format(parent_number=parent_number)
667
+ answer = _open_pull_requests_once(each_draft.owner, each_draft.repo, reader)
668
+ if answer is UnreadOpenPullRequests.UNANSWERED:
669
+ return UNANSWERED_FOLLOWUP_REASON_TEMPLATE.format(
670
+ owner=each_draft.owner, repo=each_draft.repo, parent_number=parent_number
671
+ )
672
+ if answer is UnreadOpenPullRequests.FAILED:
356
673
  continue
357
- reason = _reason_for_parent(parent_number, all_open_pull_requests)
674
+ reason = _reason_for_parent(parent_number, answer)
358
675
  if reason is not None:
359
676
  return reason
360
677
  return None