claude-dev-env 8.117.3 → 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 (75) 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/package.json +1 -1
@@ -0,0 +1,126 @@
1
+ """Find each create that a wrapped inner text holds and the folder walk did not place.
2
+
3
+ ::
4
+
5
+ bash -c "cd sub && gh pr create --fill" -> ("--fill",) when the walk missed it
6
+ gh pr create --body "a\\ngh pr create" -> nothing: a quoted value runs no command
7
+
8
+ ``hooks_constants.shell_command_wrappers.all_wrapped_command_texts`` lists the
9
+ command and each text a wrapper or substitution inside it runs. A text is
10
+ skipped when it is the command itself, or a closed text with its line breaks
11
+ read as spaces, or a text unwrapped from one. Each other text is cut into POSIX
12
+ words, and each create it holds is compared with the creates the walk placed,
13
+ line breaks read as spaces.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import sys
19
+ from collections.abc import Sequence
20
+ from pathlib import Path
21
+
22
+ hooks_directory = str(Path(__file__).resolve().parent.parent.parent)
23
+ if hooks_directory not in sys.path:
24
+ sys.path.insert(0, hooks_directory)
25
+
26
+ from blocking.followup_pr_dedupe import create_arguments
27
+ from blocking.merge_review_gate_parts.quoted_lines import quote_aware_lines
28
+ from hooks_constants.merge_review_gate_constants import (
29
+ IS_POSIX_TOKENIZATION,
30
+ SUBSHELL_CLOSE_TOKEN,
31
+ )
32
+ from hooks_constants.pytest_invocation import unquoted_token
33
+ from hooks_constants.shell_command_evaluation_constants import (
34
+ ALL_LINE_BREAK_CHARACTERS,
35
+ QUOTED_LINE_BREAK_REPLACEMENT,
36
+ )
37
+ from hooks_constants.shell_command_pipeline import (
38
+ join_line_continuations,
39
+ operator_aware_tokens,
40
+ scannable_command_lines,
41
+ segments_with_following_operator,
42
+ )
43
+ from hooks_constants.shell_command_wrappers import (
44
+ all_wrapped_command_texts,
45
+ quoted_line_breaks_joined,
46
+ )
47
+
48
+
49
+ def unplaced_creates(
50
+ command: str, all_placed_arguments: Sequence[Sequence[str]]
51
+ ) -> list[tuple[tuple[str, ...], tuple[str, ...]]]:
52
+ """Return the arguments and command words of each wrapped create the walk did not place.
53
+
54
+ ::
55
+
56
+ 'bash -c "gh pr create --fill"', [] -> [(("--fill",), ("gh", "pr", "create", "--fill"))]
57
+ 'bash -c "gh pr create --fill"', [("--fill",)] -> []
58
+
59
+ Args:
60
+ command: The shell command text.
61
+ all_placed_arguments: The arguments of each create the walk placed.
62
+
63
+ Returns:
64
+ Each unplaced create's arguments and the words of the simple command that runs it,
65
+ in the order the wrapped texts list them.
66
+ """
67
+ all_known = {_normalized(each_arguments) for each_arguments in all_placed_arguments}
68
+ return [
69
+ (tuple(all_arguments), tuple(all_words))
70
+ for all_arguments, all_words in _wrapped_creates(command)
71
+ if _normalized(all_arguments) not in all_known
72
+ ]
73
+
74
+
75
+ def _normalized(all_arguments: Sequence[str]) -> tuple[str, ...]:
76
+ all_words = [
77
+ _line_breaks_as_spaces(unquoted_token(each_argument)) for each_argument in all_arguments
78
+ ]
79
+ while all_words and all_words[-1] == SUBSHELL_CLOSE_TOKEN:
80
+ all_words.pop()
81
+ return tuple(all_words)
82
+
83
+
84
+ def _line_breaks_as_spaces(word: str) -> str:
85
+ return "".join(
86
+ QUOTED_LINE_BREAK_REPLACEMENT
87
+ if each_character in ALL_LINE_BREAK_CHARACTERS
88
+ else each_character
89
+ for each_character in word
90
+ )
91
+
92
+
93
+ def _wrapped_creates(command: str) -> list[tuple[list[str], list[str]]]:
94
+ all_wrapped_texts = all_wrapped_command_texts(command)
95
+ all_skipped_texts = {
96
+ command,
97
+ quoted_line_breaks_joined(command),
98
+ *_flattened_balanced_texts(all_wrapped_texts),
99
+ }
100
+ return [
101
+ (each_arguments, each_segment)
102
+ for each_text in all_wrapped_texts
103
+ if each_text not in all_skipped_texts
104
+ for each_segment in _posix_segments(each_text)
105
+ if (each_arguments := create_arguments(each_segment)) is not None
106
+ ]
107
+
108
+
109
+ def _flattened_balanced_texts(all_texts: list[str]) -> set[str]:
110
+ return {
111
+ each_unwrapped
112
+ for each_text in all_texts
113
+ if quote_aware_lines(each_text) is not None
114
+ and (each_flattened := _line_breaks_as_spaces(each_text)) != each_text
115
+ for each_unwrapped in all_wrapped_command_texts(each_flattened)
116
+ }
117
+
118
+
119
+ def _posix_segments(text: str) -> list[list[str]]:
120
+ return [
121
+ each_segment
122
+ for each_line in scannable_command_lines(join_line_continuations(text))
123
+ for each_segment, _each_operator in segments_with_following_operator(
124
+ operator_aware_tokens(each_line, IS_POSIX_TOKENIZATION) or []
125
+ )
126
+ ]
@@ -1,7 +1,10 @@
1
1
  """Deny pull request lifecycle actions until their skill appears in the transcript.
2
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.
3
+ A gate silent at its 30 s ``hooks.json`` timeout lets the call through, so its git and GitHub reads
4
+ and its transcript scans end by 21 s. ``blocking/gate_run_reads.py`` draws that budget.
5
+ A deny from a run that cut a read short says a second run may pass.
6
+ Each transcript scan reads the newest line first, so a recent skill load answers early.
7
+ A deny from a scan the deadline stopped says to load the skill, or call build-eval, again.
5
8
  """
6
9
 
7
10
  from __future__ import annotations
@@ -44,6 +47,7 @@ from hooks_constants.pr_lifecycle_skill_gate_constants import (
44
47
  DOUBLE_QUOTED_ESCAPE_PATTERN,
45
48
  ENVIRONMENT_ASSIGNMENT_PATTERN,
46
49
  ESCAPED_CHARACTER_GROUP,
50
+ GATE_NAME,
47
51
  GH_API_COMMAND,
48
52
  GH_PULL_REQUEST_COMMAND,
49
53
  GIT_ACTIONS,
@@ -57,6 +61,7 @@ from hooks_constants.pr_lifecycle_skill_gate_constants import (
57
61
  PATH_SEPARATOR_PATTERN,
58
62
  PERMISSION_DECISION_REASON_KEY,
59
63
  PULL_REQUEST_SCRIPT_NAME,
64
+ SCAN_RAN_OUT_SENTENCE,
60
65
  ALL_NESTED_PROGRAM_NAMES,
61
66
  ALL_NESTED_PROGRAM_WRAPPER_NAMES,
62
67
  EVAL_ARGUMENT_SEPARATOR,
@@ -78,14 +83,21 @@ from hooks_constants.hook_specific_output_keys import (
78
83
  )
79
84
  from hooks_constants.pre_tool_use_stdin import print_decision_from_stdin
80
85
  from hooks_constants.setup_project_paths_constants import DECODE_ERRORS_POLICY, UTF8_ENCODING
81
- from blocking.followup_pr_dedupe import create_tool_fields, duplicate_followup_reason
82
- from blocking.gate_run_reads import gate_run, read_deadlines_started
86
+ from blocking.followup_pr_dedupe import all_create_argument_lists, create_tool_fields, duplicate_followup_reason
87
+ from blocking.gate_run_reads import (
88
+ GateRun,
89
+ ReadSlice,
90
+ gate_run,
91
+ read_deadlines_started,
92
+ transcript_lines_within_slice,
93
+ )
94
+ from hooks_constants.gate_fault import gate_fault_reason
83
95
  from hooks_constants.gate_run_reads_constants import READS_RAN_OUT_SENTENCE
84
96
  from blocking import pull_request_proof as proof
85
97
  from hooks_constants.pull_request_proof_constants import MISSING_BUILD_EVAL_REASON
86
98
  from transcript_skill_scan import (
87
99
  invokes_skill_with_argument,
88
- is_skill_loaded_after_last_compaction,
100
+ is_skill_loaded_after_last_compaction_newest_first,
89
101
  )
90
102
 
91
103
 
@@ -302,6 +314,8 @@ def _wrapped_word_lists(all_command_words: list[str]) -> list[list[str]]:
302
314
 
303
315
 
304
316
  def _matches_shell_command(command: str) -> bool:
317
+ if next(all_create_argument_lists(command), None) is not None:
318
+ return True
305
319
  for each_command_words in executable_word_lists(command):
306
320
  executable = file_name(each_command_words[0])
307
321
  if executable == PULL_REQUEST_SCRIPT_NAME:
@@ -327,17 +341,17 @@ def _is_governed_action(all_payload_fields: dict[str, object]) -> bool:
327
341
  return isinstance(tool_input, dict) and isinstance(tool_input.get("command"), str) and _matches_shell_command(tool_input["command"])
328
342
 
329
343
 
330
- def _scanned_transcript(path: str, scan: Callable[[Iterable[str]], bool]) -> bool | None:
344
+ def _scanned_transcript(path: str, scan: Callable[[Iterable[str]], bool], read_slice: ReadSlice) -> bool | None:
331
345
  try:
332
- with open(path, encoding=UTF8_ENCODING, errors=DECODE_ERRORS_POLICY) as transcript:
333
- return scan(transcript)
346
+ with open(path, "rb") as transcript:
347
+ return scan(transcript_lines_within_slice(transcript, UTF8_ENCODING, DECODE_ERRORS_POLICY, read_slice))
334
348
  except OSError:
335
349
  return None
336
350
 
337
351
 
338
- def _shows_skill_load(all_transcript_lines: Iterable[str]) -> bool:
339
- return is_skill_loaded_after_last_compaction(
340
- all_transcript_lines, (SKILL_NAME,), ALL_SLASH_COMMAND_MARKERS
352
+ def _shows_skill_load(all_lines_newest_first: Iterable[str]) -> bool:
353
+ return is_skill_loaded_after_last_compaction_newest_first(
354
+ all_lines_newest_first, (SKILL_NAME,), ALL_SLASH_COMMAND_MARKERS
341
355
  )
342
356
 
343
357
 
@@ -381,9 +395,14 @@ def decision_for(all_payload_fields: dict[str, object]) -> dict[str, object] | N
381
395
  changed page whose proof shows no picture -> MISSING_LOOK_REASON
382
396
  feature pull request, no /claude-api build-eval -> MISSING_BUILD_EVAL_REASON
383
397
  second follow-up pull request for one parent -> DUPLICATE_FOLLOWUP_REASON_TEMPLATE
398
+ follow-up read of open pull requests unanswered -> UNANSWERED_FOLLOWUP_REASON_TEMPLATE
399
+ follow-up with no repository, origin unread -> UNREAD_ORIGIN_FOLLOWUP_REASON_TEMPLATE
400
+ skill or build-eval deny from a scan the deadline stopped -> that reason + SCAN_RAN_OUT_SENTENCE
384
401
  any deny above in a run whose deadline cut a read -> that reason + READS_RAN_OUT_SENTENCE
402
+ a check raises once the call is known governed -> gate_fault_reason naming the error
385
403
 
386
404
  The checks share one gate run, so two checks that ask git or GitHub one question read it once.
405
+ A fault while the gate decides whether the call is governed still raises, so it never refuses an unrelated call.
387
406
 
388
407
  Args:
389
408
  all_payload_fields: The parsed PreToolUse input.
@@ -391,14 +410,31 @@ def decision_for(all_payload_fields: dict[str, object]) -> dict[str, object] | N
391
410
  if not _is_governed_action(all_payload_fields):
392
411
  return None
393
412
  with gate_run() as run:
394
- reason = _first_broken_rule_reason(all_payload_fields)
413
+ try:
414
+ reason = _first_broken_rule_reason(all_payload_fields, run)
415
+ except Exception as error:
416
+ return deny_decision(gate_fault_reason(GATE_NAME, error))
395
417
  note = READS_RAN_OUT_SENTENCE if run.was_read_cut_short else ""
396
418
  return None if reason is None else deny_decision(reason + note)
397
419
 
398
420
 
399
- def _first_broken_rule_reason(all_fields: dict[str, object]) -> str | None:
421
+ def _scan_note(run: GateRun, cut_scan_count_before: int) -> str:
422
+ return SCAN_RAN_OUT_SENTENCE if run.cut_scan_count > cut_scan_count_before else ""
423
+
424
+
425
+ def _missing_build_eval_reason(all_fields: dict[str, object], run: GateRun) -> str | None:
426
+ if not proof.is_feature_pull_request(all_fields):
427
+ return None
428
+ cut_scan_count_before = run.cut_scan_count
429
+ if not is_build_eval_missing(all_fields):
430
+ return None
431
+ return MISSING_BUILD_EVAL_REASON + _scan_note(run, cut_scan_count_before)
432
+
433
+
434
+ def _first_broken_rule_reason(all_fields: dict[str, object], run: GateRun) -> str | None:
435
+ cut_scan_count_before = run.cut_scan_count
400
436
  if _is_skill_unloaded(all_fields):
401
- return DENY_REASON
437
+ return DENY_REASON + _scan_note(run, cut_scan_count_before)
402
438
  return (
403
439
  proof.missing_proof_reason(all_fields)
404
440
  or proof.edit_proof_reason(all_fields)
@@ -406,7 +442,7 @@ def _first_broken_rule_reason(all_fields: dict[str, object]) -> str | None:
406
442
  or proof.missing_flowchart_reason(all_fields)
407
443
  or proof.missing_eval_section_reason(all_fields)
408
444
  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)
445
+ or _missing_build_eval_reason(all_fields, run)
410
446
  or duplicate_followup_reason(all_fields)
411
447
  )
412
448
 
@@ -431,11 +467,13 @@ def _is_skill_unloaded(all_payload_fields: dict[str, object]) -> bool:
431
467
  readable_paths = transcript_paths(all_payload_fields)
432
468
  if not readable_paths:
433
469
  return False
434
- statuses = [_scanned_transcript(path, _shows_skill_load) for path in readable_paths]
470
+ statuses = [_scanned_transcript(path, _shows_skill_load, ReadSlice.PROOF_AND_LOOK) for path in readable_paths]
435
471
  return not any(status is None or status for status in statuses)
436
472
 
437
473
 
438
- def eval_skill_call_status(all_payload_fields: dict[str, object]) -> bool | None:
474
+ def eval_skill_call_status(
475
+ all_payload_fields: dict[str, object], read_slice: ReadSlice = ReadSlice.FOLLOWUP
476
+ ) -> bool | None:
439
477
  """Return whether the session's transcripts show a /claude-api build-eval call.
440
478
 
441
479
  ::
@@ -443,13 +481,18 @@ def eval_skill_call_status(all_payload_fields: dict[str, object]) -> bool | None
443
481
  one transcript shows the call -> True
444
482
  transcripts read, none shows the call -> False
445
483
  no transcript could be read -> None
484
+ the slice's deadline stopped a scan -> False, unless another transcript shows the call
485
+
486
+ Each scan reads the newest line first and stops at the slice's deadline
487
+ once the gate process started its read deadlines.
446
488
 
447
489
  Args:
448
490
  all_payload_fields: The parsed PreToolUse input.
491
+ read_slice: The slice whose deadline each scan answers to.
449
492
  """
450
493
  has_read_transcript = False
451
494
  for each_path in transcript_paths(all_payload_fields):
452
- status = _scanned_transcript(each_path, _shows_build_eval)
495
+ status = _scanned_transcript(each_path, _shows_build_eval, read_slice)
453
496
  if status:
454
497
  return True
455
498
  has_read_transcript = has_read_transcript or status is not None
@@ -510,6 +510,22 @@ def _emit_allow_decision(decision: DispatcherDecision) -> None:
510
510
  sys.stdout.flush()
511
511
 
512
512
 
513
+ def _emit_system_message_only(decision: DispatcherDecision) -> None:
514
+ """Write one JSON object that carries only the hooks' systemMessage lines.
515
+
516
+ A hosted gate whose check raised prints a warning and no decision. This
517
+ payload shows that warning to the user and carries no permissionDecision,
518
+ so the call goes on to the normal permission flow.
519
+
520
+ Args:
521
+ decision: The aggregated dispatcher decision with no deny and no allow.
522
+ """
523
+ all_unique_system_messages = unique_first_seen_strings(decision.all_system_messages)
524
+ message_payload = {"systemMessage": SYSTEM_MESSAGE_JOIN_SEPARATOR.join(all_unique_system_messages)}
525
+ sys.stdout.write(json.dumps(message_payload) + "\n")
526
+ sys.stdout.flush()
527
+
528
+
513
529
  def _select_applicable_hooks(tool_name: str) -> list[HostedHookEntry]:
514
530
  """Return the ordered hosted hook entries applicable to the given tool name.
515
531
 
@@ -573,9 +589,12 @@ def dispatch(
573
589
 
574
590
  Selects the applicable hosted hooks for tool_name, runs each one in-process
575
591
  (natively when the entry names a native module, otherwise via runpy),
576
- aggregates the results, and emits a deny JSON object when any hook denied, an
577
- explicit allow JSON object when a hook allowed explicitly and none denied, or
578
- exits zero with no output when no hook decided.
592
+ aggregates the results, and emits one of four outcomes::
593
+
594
+ any hook denied -> deny JSON object
595
+ a hook allowed explicitly and none denied -> allow JSON object
596
+ no hook decided, a hook printed systemMessage -> {"systemMessage": ...} alone
597
+ no hook decided or spoke -> no output
579
598
 
580
599
  Args:
581
600
  payload_text: The raw JSON payload text to replay to each runpy hook.
@@ -594,6 +613,9 @@ def dispatch(
594
613
  return
595
614
  if aggregated_decision.should_allow:
596
615
  _emit_allow_decision(aggregated_decision)
616
+ return
617
+ if aggregated_decision.all_system_messages:
618
+ _emit_system_message_only(aggregated_decision)
597
619
 
598
620
 
599
621
  def main() -> None:
@@ -15,7 +15,8 @@ if hooks_directory not in sys.path:
15
15
 
16
16
  from blocking.body_flowchart import fenced_line_flags, section_has_flowchart
17
17
  from blocking.followup_pr_dedupe import (
18
- all_command_segments,
18
+ all_create_argument_lists,
19
+ all_pull_request_argument_lists,
19
20
  body_from_arguments,
20
21
  create_tool_fields,
21
22
  shell_command,
@@ -34,9 +35,7 @@ from hooks_constants.pull_request_proof_constants import (
34
35
  AFTER_MERGE_NO_RECORDER_PATTERN,
35
36
  AFTER_MERGE_RECORDER_PATTERN,
36
37
  AFTER_MERGE_SENTENCE_SEPARATOR_PATTERN,
37
- ALL_GH_CREATE_WORDS,
38
38
  ALL_GH_EDIT_WORDS,
39
- ALL_PYTHON_PROGRAM_NAMES,
40
39
  ALL_VISIBLE_FILE_SUFFIXES,
41
40
  CHANGED_FILES_SEPARATOR,
42
41
  COMMAND_MARKER,
@@ -79,9 +78,7 @@ from hooks_constants.pull_request_proof_constants import (
79
78
  RAW_RENAME_STATUS_LETTER,
80
79
  ALL_RAW_TWO_PATH_STATUS_LETTERS,
81
80
  PROOF_IMAGE_PATTERN,
82
- PULL_REQUEST_SCRIPT_CREATE_WORD,
83
81
  PULL_REQUEST_SCRIPT_EDIT_WORD,
84
- PULL_REQUEST_SCRIPT_NAME,
85
82
  ALL_TEST_RUNNER_COMMAND_PREFIXES,
86
83
  CODE_FENCE_MARKER,
87
84
  FENCED_COMMAND_PROMPT,
@@ -107,7 +104,6 @@ from hooks_constants.pytest_invocation import (
107
104
  unquoted_token,
108
105
  )
109
106
  from hooks_constants.shell_command_pipeline import pipeline_segments_for_command
110
- from hooks_constants.shell_command_segments import token_basename
111
107
  from hooks_constants.shell_command_wrappers import segment_program_and_arguments
112
108
 
113
109
 
@@ -191,50 +187,8 @@ def section_under_existing_work(body: str) -> str | None:
191
187
  return _section_text(body, EXISTING_WORK_HEADING_PATTERN)
192
188
 
193
189
 
194
- def _script_arguments(program: str, all_arguments: list[str]) -> list[str] | None:
195
- if program == PULL_REQUEST_SCRIPT_NAME:
196
- return all_arguments
197
- if program not in ALL_PYTHON_PROGRAM_NAMES or not all_arguments:
198
- return None
199
- script_name = token_basename(unquoted_token(all_arguments[0]))
200
- return all_arguments[1:] if script_name == PULL_REQUEST_SCRIPT_NAME else None
201
-
202
-
203
- def _script_word_arguments(program: str, all_arguments: list[str], word: str) -> list[str] | None:
204
- all_script_arguments = _script_arguments(program, all_arguments)
205
- if all_script_arguments is None or all_script_arguments[:1] != [word]:
206
- return None
207
- return all_script_arguments[1:]
208
-
209
-
210
- def _command_arguments(
211
- all_segment_tokens: list[str], all_gh_words: list[str], script_word: str
212
- ) -> list[str] | None:
213
- program, all_arguments = segment_program_and_arguments(all_segment_tokens)
214
- if program == "gh" and all_arguments[: len(all_gh_words)] == all_gh_words:
215
- return all_arguments[len(all_gh_words) :]
216
- return _script_word_arguments(program, all_arguments, script_word)
217
-
218
-
219
- def _all_argument_lists(command: str, all_gh_words: list[str], script_word: str) -> Iterator[list[str]]:
220
- all_seen_arguments: set[tuple[str, ...]] = set()
221
- for each_segment in all_command_segments(command):
222
- all_arguments = _command_arguments(each_segment, all_gh_words, script_word)
223
- if all_arguments is None:
224
- continue
225
- all_unquoted_arguments = tuple(_unquoted_arguments(all_arguments))
226
- if all_unquoted_arguments in all_seen_arguments:
227
- continue
228
- all_seen_arguments.add(all_unquoted_arguments)
229
- yield all_arguments
230
-
231
-
232
- def _all_create_argument_lists(command: str) -> Iterator[list[str]]:
233
- return _all_argument_lists(command, ALL_GH_CREATE_WORDS, PULL_REQUEST_SCRIPT_CREATE_WORD)
234
-
235
-
236
190
  def _all_edit_argument_lists(command: str) -> Iterator[list[str]]:
237
- return _all_argument_lists(command, ALL_GH_EDIT_WORDS, PULL_REQUEST_SCRIPT_EDIT_WORD)
191
+ return all_pull_request_argument_lists(command, ALL_GH_EDIT_WORDS, PULL_REQUEST_SCRIPT_EDIT_WORD)
238
192
 
239
193
 
240
194
  def _shell_create_calls(command: str, working_directory: str) -> list[CreateCall]:
@@ -246,7 +200,7 @@ def _shell_create_calls(command: str, working_directory: str) -> list[CreateCall
246
200
  _flag_value(all_create_arguments, ALL_BASE_FLAGS, BASE_FLAG_ASSIGNMENT_PREFIX) or None,
247
201
  _flag_value(all_create_arguments, ALL_REPOSITORY_FLAGS, REPOSITORY_FLAG_ASSIGNMENT_PREFIX) or None,
248
202
  )
249
- for all_create_arguments in _all_create_argument_lists(command)
203
+ for all_create_arguments in all_create_argument_lists(command)
250
204
  ]
251
205
 
252
206
 
@@ -305,7 +259,7 @@ def is_create_call(all_payload_fields: Mapping[str, object]) -> bool:
305
259
  """
306
260
  command = shell_command(all_payload_fields)
307
261
  return create_tool_fields(all_payload_fields) is not None or (
308
- command is not None and next(_all_create_argument_lists(command), None) is not None
262
+ command is not None and next(all_create_argument_lists(command), None) is not None
309
263
  )
310
264
 
311
265
 
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import sys
7
+ import traceback
7
8
  from collections.abc import Iterable, Mapping
8
9
  from pathlib import Path
9
10
 
@@ -15,6 +16,8 @@ from blocking.codex_apply_patch import payload_patch_target_paths
15
16
  from blocking.pr_lifecycle_skill_gate import transcript_paths
16
17
  from blocking.pull_request_proof import is_create_call
17
18
  from blocking.step_note_gate import entry_content_blocks
19
+ from hooks_constants.gate_fault import gate_fault_reason
20
+ from hooks_constants.gate_fault_constants import PROOF_EDIT_GATE_NAME
18
21
  from hooks_constants.hook_specific_output_keys import (
19
22
  HOOK_EVENT_NAME_KEY,
20
23
  HOOK_SPECIFIC_OUTPUT_KEY,
@@ -158,10 +161,7 @@ def gate_edit_reason(all_payload_fields: Mapping[str, object]) -> str | None:
158
161
  return None
159
162
 
160
163
 
161
- def _gate_edit_decision(all_payload_fields: dict[str, object]) -> dict[str, object] | None:
162
- reason = gate_edit_reason(all_payload_fields)
163
- if reason is None:
164
- return None
164
+ def _deny_decision(reason: str) -> dict[str, object]:
165
165
  return {
166
166
  HOOK_SPECIFIC_OUTPUT_KEY: {
167
167
  HOOK_EVENT_NAME_KEY: HOOK_EVENT_NAME,
@@ -171,8 +171,22 @@ def _gate_edit_decision(all_payload_fields: dict[str, object]) -> dict[str, obje
171
171
  }
172
172
 
173
173
 
174
+ def _gate_edit_decision(all_payload_fields: dict[str, object]) -> dict[str, object] | None:
175
+ try:
176
+ reason = gate_edit_reason(all_payload_fields)
177
+ except Exception as error:
178
+ traceback.print_exc(file=sys.stderr)
179
+ return _deny_decision(gate_fault_reason(PROOF_EDIT_GATE_NAME, error))
180
+ if reason is None:
181
+ return None
182
+ return _deny_decision(reason)
183
+
184
+
174
185
  def main() -> int:
175
- """Read one Write, Edit, MultiEdit or apply_patch payload and print a deny when it edits the proof gate too soon."""
186
+ """Read one Write, Edit, MultiEdit or apply_patch payload and print a deny when it edits the proof gate too soon.
187
+
188
+ A check that raises also prints a deny, whose reason names the fault.
189
+ """
176
190
  return print_decision_from_stdin(_gate_edit_decision)
177
191
 
178
192
 
@@ -36,6 +36,7 @@ from bash_pre_tool_use_dispatcher import ( # noqa: E402
36
36
  from hooks_constants.bash_pre_tool_use_dispatcher_constants import ( # noqa: E402
37
37
  BASH_TOOL_NAME,
38
38
  POWERSHELL_TOOL_NAME,
39
+ BashHostedHookEntry,
39
40
  )
40
41
  from hooks_constants.hosted_hook_runner import HostedHookRun # noqa: E402
41
42
 
@@ -359,3 +360,56 @@ def test_should_stop_the_chain_at_the_first_hosted_hook_that_exits_two(
359
360
 
360
361
  assert exit_code == 2
361
362
  assert not later_marker.exists()
363
+
364
+
365
+ FAULT_SYSTEM_MESSAGE = "transcript_root_search_gate.py hit a fault and did not check this call"
366
+
367
+
368
+ def test_a_system_message_with_no_decision_is_kept() -> None:
369
+ """A hosted gate fault prints a systemMessage alone, and aggregation keeps it."""
370
+ fault_run = HostedHookRun(
371
+ captured_stdout=json.dumps({"systemMessage": FAULT_SYSTEM_MESSAGE}) + "\n", did_crash=False
372
+ )
373
+ aggregated = aggregate_bash_hook_results([_run(""), fault_run])
374
+ assert aggregated.decision == ""
375
+ assert aggregated.all_system_messages == [FAULT_SYSTEM_MESSAGE]
376
+
377
+
378
+ def test_dispatch_prints_a_system_message_alone_when_no_hook_decides(
379
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
380
+ ) -> None:
381
+ """The dispatcher passes a fault message to the user with no permissionDecision."""
382
+ fault_hook = tmp_path / "fault_hook.py"
383
+ fault_hook.write_text(
384
+ "import json\nprint(json.dumps({'systemMessage': " + repr(FAULT_SYSTEM_MESSAGE) + "}))\n",
385
+ encoding="utf-8",
386
+ )
387
+ monkeypatch.setattr(
388
+ "bash_pre_tool_use_dispatcher.select_applicable_entries",
389
+ lambda tool_name: [
390
+ BashHostedHookEntry(
391
+ script_relative_path=str(fault_hook), applicable_tool_names=frozenset({BASH_TOOL_NAME})
392
+ )
393
+ ],
394
+ )
395
+ dispatch(_bash_payload("ls"), BASH_TOOL_NAME)
396
+ all_lines = capsys.readouterr().out.splitlines()
397
+ assert [json.loads(each_line) for each_line in all_lines] == [{"systemMessage": FAULT_SYSTEM_MESSAGE}]
398
+
399
+
400
+ def test_dispatch_prints_nothing_when_every_hook_is_silent(
401
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
402
+ ) -> None:
403
+ """A chain with no decision and no message stays silent."""
404
+ silent_hook = tmp_path / "silent_hook.py"
405
+ silent_hook.write_text("", encoding="utf-8")
406
+ monkeypatch.setattr(
407
+ "bash_pre_tool_use_dispatcher.select_applicable_entries",
408
+ lambda tool_name: [
409
+ BashHostedHookEntry(
410
+ script_relative_path=str(silent_hook), applicable_tool_names=frozenset({BASH_TOOL_NAME})
411
+ )
412
+ ],
413
+ )
414
+ dispatch(_bash_payload("ls"), BASH_TOOL_NAME)
415
+ assert capsys.readouterr().out == ""
@@ -5,15 +5,20 @@ import subprocess
5
5
  import sys
6
6
  from pathlib import Path
7
7
 
8
+ import pytest
9
+
8
10
  HOOKS_DIRECTORY = Path(__file__).resolve().parent.parent
9
11
  if str(HOOKS_DIRECTORY) not in sys.path:
10
12
  sys.path.insert(0, str(HOOKS_DIRECTORY))
11
13
 
12
14
  from blocking import build_eval_before_eval_write_gate as gate
15
+ from blocking.gate_run_reads import ReadSlice, read_deadlines_started, started_read_deadlines
13
16
  from hooks_constants.build_eval_before_eval_write_gate_constants import (
17
+ EVAL_WRITE_SCAN_RAN_OUT_SENTENCE,
14
18
  MISSING_BUILD_EVAL_BEFORE_EVAL_WRITE_REASON,
15
19
  UNREADABLE_TRANSCRIPT_BEFORE_EVAL_WRITE_REASON,
16
20
  )
21
+ from hooks_constants.gate_run_reads_constants import EVAL_WRITE_SCAN_SECONDS, STARTUP_AND_OUTPUT_MARGIN_SECONDS
17
22
 
18
23
  GATE_SCRIPT = Path(gate.__file__)
19
24
 
@@ -160,3 +165,62 @@ def test_unparseable_apply_patch_naming_an_eval_file_should_be_denied(tmp_path:
160
165
  "transcript_path": str(_transcript(tmp_path, build_eval=False)),
161
166
  }
162
167
  assert _reason(gate.decision_for(payload)) == MISSING_BUILD_EVAL_BEFORE_EVAL_WRITE_REASON
168
+
169
+
170
+ EVAL_WRITE_GATE_COMMAND_SUFFIX = "/hooks/blocking/build_eval_before_eval_write_gate.py"
171
+ CLOCK_START = 1000.0
172
+
173
+
174
+ class SteppedClock:
175
+ def __init__(self) -> None:
176
+ self.now = CLOCK_START
177
+
178
+ def __call__(self) -> float:
179
+ return self.now
180
+
181
+
182
+ def _registered_gate_timeout_seconds() -> int:
183
+ all_registration_fields = json.loads((HOOKS_DIRECTORY / "hooks.json").read_text(encoding="utf-8"))
184
+ all_timeouts = [
185
+ each_hook["timeout"]
186
+ for each_group in all_registration_fields["hooks"]["PreToolUse"]
187
+ for each_hook in each_group["hooks"]
188
+ if each_hook.get("command", "").endswith(EVAL_WRITE_GATE_COMMAND_SUFFIX)
189
+ ]
190
+ assert len(all_timeouts) == 1
191
+ return all_timeouts[0]
192
+
193
+
194
+ def test_registered_timeout_should_outlast_the_eval_write_scan_deadline() -> None:
195
+ assert ReadSlice.EVAL_WRITE.value == EVAL_WRITE_SCAN_SECONDS
196
+ assert _registered_gate_timeout_seconds() >= EVAL_WRITE_SCAN_SECONDS + STARTUP_AND_OUTPUT_MARGIN_SECONDS
197
+
198
+
199
+ def test_scan_the_eval_write_deadline_stopped_should_deny_and_say_to_call_build_eval_again(tmp_path: Path) -> None:
200
+ clock = SteppedClock()
201
+ payload = _payload("/repo/evals/cases.json", _transcript(tmp_path, build_eval=True))
202
+ with read_deadlines_started(clock):
203
+ clock.now = CLOCK_START + EVAL_WRITE_SCAN_SECONDS
204
+ decision = gate.decision_for(payload)
205
+ assert _reason(decision) == MISSING_BUILD_EVAL_BEFORE_EVAL_WRITE_REASON + EVAL_WRITE_SCAN_RAN_OUT_SENTENCE
206
+
207
+
208
+ def test_scan_with_time_left_should_deny_without_the_ran_out_sentence(tmp_path: Path) -> None:
209
+ clock = SteppedClock()
210
+ payload = _payload("/repo/evals/cases.json", _transcript(tmp_path, build_eval=False))
211
+ with read_deadlines_started(clock):
212
+ clock.now = CLOCK_START + EVAL_WRITE_SCAN_SECONDS - 1
213
+ assert _reason(gate.decision_for(payload)) == MISSING_BUILD_EVAL_BEFORE_EVAL_WRITE_REASON
214
+ assert gate.decision_for(_payload("/repo/evals/cases.json", _transcript(tmp_path, build_eval=True))) is None
215
+
216
+
217
+ def test_main_should_start_the_read_deadlines_before_it_reads_the_payload(monkeypatch: pytest.MonkeyPatch) -> None:
218
+ all_seen_deadlines: list[object] = []
219
+
220
+ def recorded_print(decide: object) -> int:
221
+ all_seen_deadlines.append(started_read_deadlines.get())
222
+ return 0
223
+
224
+ monkeypatch.setattr(gate, "print_decision_from_stdin", recorded_print)
225
+ assert gate.main() == 0
226
+ assert all_seen_deadlines[0] is not None