claude-dev-env 8.116.5 → 8.117.1

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 (117) hide show
  1. package/bin/ever-registered-hooks.mjs +2 -0
  2. package/bin/ever-registered-hooks.test.mjs +4 -0
  3. package/bin/install-constants.mjs +3 -1
  4. package/bin/install.cursor-rules.test.mjs +64 -2
  5. package/bin/install.mjs +15 -2
  6. package/bin/install.prune.test.mjs +92 -0
  7. package/bin/install.test.mjs +1 -0
  8. package/docs/model-choice/escalation.md +3 -3
  9. package/docs/model-choice/subagents-and-fan-out.md +2 -2
  10. package/docs/model-choice/which-model.md +1 -1
  11. package/docs/references/working-style.md +1 -0
  12. package/docs/rule-guides/question-presentation.md +6 -0
  13. package/docs/rule-guides/session-title.md +8 -9
  14. package/docs/rule-guides/subagent-model-effort.md +13 -13
  15. package/hooks/advisory/owned_pr_review_loop.py +2 -3
  16. package/hooks/blocking/bash_post_call_dispatcher.py +17 -9
  17. package/hooks/blocking/bash_pre_tool_use_dispatcher.py +12 -8
  18. package/hooks/blocking/final_reply_gate.py +5 -9
  19. package/hooks/blocking/open_tasks_stop_gate.py +9 -20
  20. package/hooks/blocking/open_tasks_transcript.py +8 -3
  21. package/hooks/blocking/pii_prevention_blocker_parts/repository_exemption.py +7 -2
  22. package/hooks/blocking/question_brief_gate.py +382 -0
  23. package/hooks/blocking/step_note_gate.py +5 -2
  24. package/hooks/blocking/task_subject_length_gate.py +111 -0
  25. package/hooks/blocking/test_bash_post_call_dispatcher.py +36 -1
  26. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +57 -0
  27. package/hooks/blocking/test_final_reply_gate.py +26 -2
  28. package/hooks/blocking/test_open_tasks_stop_gate.py +21 -11
  29. package/hooks/blocking/test_question_brief_gate.py +916 -0
  30. package/hooks/blocking/test_step_note_gate.py +26 -0
  31. package/hooks/blocking/test_task_subject_length_gate.py +221 -0
  32. package/hooks/blocking/test_turn_review_child.py +166 -0
  33. package/hooks/blocking/test_turn_review_claim.py +194 -0
  34. package/hooks/blocking/test_turn_review_findings.py +124 -1
  35. package/hooks/blocking/test_turn_review_gate.py +1312 -10
  36. package/hooks/blocking/test_turn_review_repositories.py +65 -0
  37. package/hooks/blocking/test_turn_review_snapshot.py +8 -0
  38. package/hooks/blocking/test_turn_review_state.py +132 -0
  39. package/hooks/blocking/test_turn_review_transcript.py +125 -0
  40. package/hooks/blocking/tests/test_repository_exemption.py +11 -0
  41. package/hooks/blocking/turn_review_child.py +145 -0
  42. package/hooks/blocking/turn_review_claim.py +306 -0
  43. package/hooks/blocking/turn_review_findings.py +173 -13
  44. package/hooks/blocking/turn_review_gate.py +259 -262
  45. package/hooks/blocking/turn_review_repositories.py +58 -0
  46. package/hooks/blocking/turn_review_snapshot.py +5 -1
  47. package/hooks/blocking/turn_review_state.py +260 -0
  48. package/hooks/blocking/turn_review_transcript.py +158 -0
  49. package/hooks/features/bash-dispatchers.md +1 -3
  50. package/hooks/features/conduct-gates.md +19 -9
  51. package/hooks/features/lifecycle-cleanup.md +1 -1
  52. package/hooks/features/spawn-routing.md +1 -1
  53. package/hooks/hooks.json +24 -11
  54. package/hooks/hooks_constants/final_reply_gate_constants.py +0 -3
  55. package/hooks/hooks_constants/hook_time_budget.py +61 -0
  56. package/hooks/hooks_constants/hosted_hook_runner.py +51 -21
  57. package/hooks/hooks_constants/hosted_hook_runner_constants.py +3 -0
  58. package/hooks/hooks_constants/nested_project_hooks_constants.py +8 -0
  59. package/hooks/hooks_constants/once_per_session_constants.py +1 -0
  60. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +0 -4
  61. package/hooks/hooks_constants/owned_pr_review_loop_constants.py +0 -4
  62. package/hooks/hooks_constants/pre_tool_use_context_runner.py +23 -3
  63. package/hooks/hooks_constants/pre_tool_use_context_runner_constants.py +5 -0
  64. package/hooks/hooks_constants/pre_tool_use_stdin.py +1 -1
  65. package/hooks/hooks_constants/question_brief_gate_constants.py +66 -0
  66. package/hooks/hooks_constants/session_title_constants.py +8 -29
  67. package/hooks/hooks_constants/stop_hook_hold.py +54 -0
  68. package/hooks/hooks_constants/stop_hook_hold_constants.py +9 -0
  69. package/hooks/hooks_constants/subagent_effort_levels.json +6 -0
  70. package/hooks/hooks_constants/subagent_effort_route_constants.py +20 -19
  71. package/hooks/hooks_constants/task_subject_length_gate_constants.py +43 -0
  72. package/hooks/hooks_constants/test_hook_time_budget.py +104 -0
  73. package/hooks/hooks_constants/test_hosted_hook_runner.py +12 -0
  74. package/hooks/hooks_constants/test_pre_tool_use_context_runner.py +16 -0
  75. package/hooks/hooks_constants/test_pre_tool_use_stdin.py +6 -0
  76. package/hooks/hooks_constants/test_stop_hook_hold.py +40 -0
  77. package/hooks/hooks_constants/thread_spawn_pace_hook_constants.py +1 -2
  78. package/hooks/hooks_constants/turn_review_gate_constants.py +246 -12
  79. package/hooks/lifecycle/nested_project_hooks.py +34 -4
  80. package/hooks/lifecycle/test_nested_project_hooks.py +52 -0
  81. package/hooks/once_per_session.py +33 -4
  82. package/hooks/open_task_asks.py +1 -1
  83. package/hooks/owned_pr_session_record.py +1 -76
  84. package/hooks/routing/subagent_effort_route.py +107 -13
  85. package/hooks/routing/subagent_effort_route_hook.py +9 -8
  86. package/hooks/routing/test_subagent_effort_route.py +201 -14
  87. package/hooks/routing/test_subagent_effort_route_hook.py +56 -0
  88. package/hooks/routing/test_thread_spawn_pace_hook.py +32 -0
  89. package/hooks/routing/thread_spawn_pace_hook.py +3 -3
  90. package/hooks/session/background_silence_prompt.py +1 -1
  91. package/hooks/session/test_background_silence_prompt.py +8 -0
  92. package/hooks/session/test_tracking_nudge.py +125 -2
  93. package/hooks/session/tracking_nudge.py +28 -18
  94. package/hooks/session_title_transcript.py +216 -0
  95. package/hooks/test_once_per_session.py +10 -0
  96. package/hooks/test_owned_pr_session_record.py +0 -26
  97. package/hooks/test_session_title_transcript.py +142 -0
  98. package/hooks/validation/post_tool_use_dispatcher.py +38 -21
  99. package/hooks/validation/test_post_tool_use_dispatcher.py +43 -0
  100. package/package.json +1 -1
  101. package/rules/question-presentation.md +4 -4
  102. package/rules/subagent-model-effort.md +1 -1
  103. package/scripts/account_broker_support.py +24 -5
  104. package/scripts/claude_account_worker.py +4 -3
  105. package/scripts/dev_env_scripts_constants/account_broker_constants.py +1 -0
  106. package/scripts/policy_lint/adapter_configuration.py +12 -11
  107. package/scripts/policy_lint/config/approved_test_pairs.py +27 -0
  108. package/scripts/policy_lint/config/constants.py +2 -2
  109. package/scripts/test_account_broker_support.py +43 -1
  110. package/scripts/test_claude_account_worker.py +1 -0
  111. package/scripts/tests/test_adapter_configuration.py +10 -2
  112. package/scripts/tests/test_policy_lint_rules_pairing.py +24 -0
  113. package/hooks/blocking/owned_pr_merge_stop_gate.py +0 -185
  114. package/hooks/blocking/session_title_turn_gate.py +0 -417
  115. package/hooks/blocking/test_owned_pr_merge_stop_gate.py +0 -254
  116. package/hooks/blocking/test_session_title_turn_gate.py +0 -396
  117. package/hooks/hooks_constants/owned_pr_merge_stop_gate_constants.py +0 -40
@@ -3,9 +3,9 @@
3
3
 
4
4
  This gate checks the reply the session ends its turn with, which reaches the
5
5
  user with no tool call. It flags a path outside code whose backslash the
6
- terminal drops, such as ``D:\\Reports\\.claude``. A block sends the reason
7
- back so the model rewrites the reply. Claude Code ends the turn after eight
8
- blocks in a row.
6
+ terminal drops, such as ``D:\\Reports\\.claude``. A block exits with
7
+ code 2 and sends the reason back so the model rewrites the reply. Claude Code
8
+ ends the turn after eight blocks in a row.
9
9
 
10
10
  It also blocks a reply whose last paragraph ends with a question mark, or says a question still stands, when the
11
11
  turn sent no AskUserQuestion, hearthbot decision card, or Codex
@@ -23,7 +23,6 @@ from __future__ import annotations
23
23
 
24
24
  import bisect
25
25
  import functools
26
- import json
27
26
  import re
28
27
  import sys
29
28
  from collections.abc import Callable
@@ -36,15 +35,14 @@ if hooks_root_directory not in sys.path:
36
35
  from open_tasks_transcript import replayed_transcript
37
36
  from hooks_constants.hook_block_logger import log_hook_block
38
37
  from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
38
+ from hooks_constants.stop_hook_hold import hold_stop
39
39
  from hooks_constants.final_reply_gate_constants import (
40
40
  ALLOW_EXIT_CODE,
41
41
  BACKSLASH,
42
42
  BACKSLASHES_PER_LITERAL,
43
43
  BACKTICK_RUN_PATTERN,
44
44
  BLOCK_BOUNDARY_PATTERN,
45
- BLOCK_DECISION,
46
45
  CARRIAGE_RETURN_LINE_BREAK,
47
- DECISION_KEY,
48
46
  ESCAPED_PUNCTUATION_PATTERN,
49
47
  FENCE_CLOSER_PREFIX,
50
48
  FENCE_CLOSER_SUFFIX,
@@ -65,7 +63,6 @@ from hooks_constants.final_reply_gate_constants import (
65
63
  QUOTE_MARKER,
66
64
  QUOTE_MARKER_PATTERN,
67
65
  QUOTED_LINE_PATTERN,
68
- REASON_KEY,
69
66
  REWRITE_INSTRUCTION,
70
67
  STANDING_QUESTION_PATTERN,
71
68
  TRAILING_MARKUP_CHARACTERS,
@@ -275,8 +272,7 @@ def main() -> int:
275
272
  log_hook_block(
276
273
  Path(__file__).name, HOOK_EVENT_NAME, block_reason, offending_input_preview=reply_text
277
274
  )
278
- sys.stdout.write(json.dumps({DECISION_KEY: BLOCK_DECISION, REASON_KEY: block_reason}))
279
- return ALLOW_EXIT_CODE
275
+ return hold_stop(hook_input, block_reason)
280
276
 
281
277
 
282
278
  if __name__ == "__main__":
@@ -27,17 +27,17 @@ The reply text is never checked. One tracker call releases the turn, and a
27
27
  turn the gate already held ends on the next stop, so the gate costs at most one
28
28
  extra step per turn.
29
29
 
30
- Claude Code marks a held stop with ``stop_hook_active``. Codex turns the reason
31
- into a continuation prompt. A Cursor payload (it carries ``conversation_id``)
32
- gets the reason as ``followup_message``, which Cursor submits as the next user
33
- message; a Cursor stop whose ``loop_count`` shows a follow-up already sent
30
+ A hold exits with code 2 and writes the reason to stdout and stderr. Claude
31
+ Code marks a held stop with ``stop_hook_active``. Codex turns the reason into
32
+ a continuation prompt. A Cursor payload (it carries ``conversation_id``) exits
33
+ with code 0 and gets the reason as ``followup_message``, which Cursor submits
34
+ as the next user message; a Cursor stop whose ``loop_count`` shows a follow-up already sent
34
35
  passes, and so does one whose ``status`` is ``aborted`` or ``error``. A TodoWrite
35
36
  call that a Cursor ``CallDynamicTool`` call wraps counts as a TodoWrite call.
36
37
  """
37
38
 
38
39
  from __future__ import annotations
39
40
 
40
- import json
41
41
  import os
42
42
  import sys
43
43
  from pathlib import Path
@@ -51,20 +51,18 @@ if blocking_directory not in sys.path:
51
51
 
52
52
  from hooks_constants.hook_block_logger import log_hook_block
53
53
  from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
54
+ from hooks_constants.setup_project_paths_constants import DECODE_ERRORS_POLICY
55
+ from hooks_constants.stop_hook_hold import hold_stop
54
56
  from open_task_asks import claude_home, is_ask
55
57
  from open_tasks_transcript import TaskItem, TranscriptReplay, normalized_text, parsed_object, replayed_transcript
56
58
  from hooks_constants.open_tasks_stop_gate_constants import (
57
59
  ALLOW_EXIT_CODE,
58
- BLOCK_DECISION,
59
60
  BLOCK_REASON,
60
61
  CURSOR_COMPLETED_STATUS,
61
62
  CURSOR_CONVERSATION_ID_KEY,
62
- CURSOR_FOLLOWUP_MESSAGE_KEY,
63
63
  CURSOR_LOOP_COUNT_KEY,
64
64
  CURSOR_STATUS_KEY,
65
- DECISION_KEY,
66
65
  HOOK_EVENT_NAME,
67
- REASON_KEY,
68
66
  STOP_HOOK_ACTIVE_KEY,
69
67
  TASK_FILE_GLOB,
70
68
  TASK_ID_KEY,
@@ -80,7 +78,7 @@ from hooks_constants.open_tasks_stop_gate_constants import (
80
78
 
81
79
  def _task_file_item(task_file: Path) -> TaskItem | None:
82
80
  try:
83
- task_text = task_file.read_text(encoding=UTF8_ENCODING)
81
+ task_text = task_file.read_text(encoding=UTF8_ENCODING, errors=DECODE_ERRORS_POLICY)
84
82
  except OSError:
85
83
  return None
86
84
  all_task_fields = parsed_object(task_text)
@@ -145,14 +143,6 @@ def is_held_stop(all_hook_input_fields: dict[str, object]) -> bool:
145
143
  return has_sent_followup or (stop_status is not None and stop_status != CURSOR_COMPLETED_STATUS)
146
144
 
147
145
 
148
- def block_output_for(all_hook_input_fields: dict[str, object], block_reason: str) -> dict[str, str]:
149
- """Return the block output; a Cursor payload also gets the reason as ``followup_message``."""
150
- block_output = {DECISION_KEY: BLOCK_DECISION, REASON_KEY: block_reason}
151
- if all_hook_input_fields.get(CURSOR_CONVERSATION_ID_KEY):
152
- block_output[CURSOR_FOLLOWUP_MESSAGE_KEY] = block_reason
153
- return block_output
154
-
155
-
156
146
  def main() -> int:
157
147
  hook_input = read_hook_input_dictionary_from_stdin()
158
148
  if hook_input is None or is_held_stop(hook_input):
@@ -160,8 +150,7 @@ def main() -> int:
160
150
  if not is_untracked_work_turn(replayed_transcript(hook_input.get(TRANSCRIPT_PATH_KEY))):
161
151
  return ALLOW_EXIT_CODE
162
152
  log_hook_block(Path(__file__).name, HOOK_EVENT_NAME, BLOCK_REASON)
163
- sys.stdout.write(json.dumps(block_output_for(hook_input, BLOCK_REASON)))
164
- return ALLOW_EXIT_CODE
153
+ return hold_stop(hook_input, BLOCK_REASON)
165
154
 
166
155
 
167
156
  if __name__ == "__main__":
@@ -29,8 +29,8 @@ The replay also notes what the current turn did::
29
29
 
30
30
  A turn starts at the last user prompt record. A tool result, a record flagged
31
31
  ``isMeta``, ``isSidechain`` or ``isCompactSummary``, and a ``Stop hook feedback``
32
- message do not start a turn; these are the flags session_title_turn_gate.py
33
- skips, and its tests model Stop hook feedback as an ``isMeta`` user record.
32
+ message do not start a turn. Tests model Stop hook feedback as an ``isMeta``
33
+ user record.
34
34
  A Codex ``response_item`` user message starts a Codex turn.
35
35
 
36
36
  The Cursor CLI can also reach TodoWrite through ``CallDynamicTool``, with the
@@ -49,6 +49,7 @@ hooks_root_directory = str(Path(__file__).resolve().parent.parent)
49
49
  if hooks_root_directory not in sys.path:
50
50
  sys.path.insert(0, hooks_root_directory)
51
51
 
52
+ from hooks_constants.setup_project_paths_constants import DECODE_ERRORS_POLICY
52
53
  from hooks_constants.open_tasks_stop_gate_constants import (
53
54
  ALL_SKIPPED_PROMPT_FLAGS,
54
55
  ASSISTANT_RECORD_TYPE,
@@ -144,7 +145,11 @@ def _transcript_records(transcript_path: object) -> list[dict[str, object]]:
144
145
  if not isinstance(transcript_path, str):
145
146
  return []
146
147
  try:
147
- all_lines = Path(transcript_path).read_text(encoding=UTF8_ENCODING).splitlines()
148
+ all_lines = (
149
+ Path(transcript_path)
150
+ .read_text(encoding=UTF8_ENCODING, errors=DECODE_ERRORS_POLICY)
151
+ .splitlines()
152
+ )
148
153
  except OSError:
149
154
  return []
150
155
  all_records = (parsed_object(each_line) for each_line in all_lines)
@@ -16,6 +16,7 @@ import sys
16
16
  from pathlib import Path
17
17
  from urllib.parse import urlparse
18
18
 
19
+ from hooks_constants.hook_time_budget import call_timeout
19
20
  from hooks_constants.subprocess_window import hidden_window_creation_flags
20
21
 
21
22
  try:
@@ -179,14 +180,18 @@ def repository_origin_slug(repository_root: Path) -> str | None:
179
180
 
180
181
  Returns:
181
182
  The ``owner/repo`` slug in lowercase, or None when the repository has no
182
- readable origin remote or the URL carries no owner/repo tail.
183
+ readable origin remote, the URL carries no owner/repo tail, or the
184
+ hook's time budget is spent.
183
185
  """
186
+ timeout_seconds = call_timeout(GIT_COMMAND_TIMEOUT_SECONDS)
187
+ if timeout_seconds is None:
188
+ return None
184
189
  try:
185
190
  completed_process = subprocess.run(
186
191
  list(ALL_GIT_ORIGIN_URL_COMMAND),
187
192
  check=False, capture_output=True,
188
193
  text=True,
189
- timeout=GIT_COMMAND_TIMEOUT_SECONDS,
194
+ timeout=timeout_seconds,
190
195
  cwd=str(repository_root),
191
196
  creationflags=hidden_window_creation_flags(),
192
197
  )
@@ -0,0 +1,382 @@
1
+ #!/usr/bin/env python3
2
+ """PreToolUse hook that refuses a question after a long chat brief.
3
+
4
+ Registered on ``AskUserQuestion``. The user reviews items one question at a
5
+ time. The hook measures the chat text Claude wrote in the current turn before
6
+ the question: the text after the latest of these marks.
7
+
8
+ - A prompt the user typed, or a message the user queued mid-turn.
9
+ - A result of an earlier question, refused or answered.
10
+ - The first input after an earlier turn ended with an ``end_turn`` message or
11
+ a ``stop_hook_summary`` entry. A turn that a task notification or an agent
12
+ message starts never counts the text before it. A Stop hook that holds the
13
+ turn adds no input, so the text before a held stop still counts.
14
+
15
+ ::
16
+
17
+ 40-word brief, then the question -> exit 0
18
+ a 30-row table, then the question -> exit 2, reason on stderr
19
+ 600 words, refused question, short brief -> exit 0 on the retry
20
+
21
+ Lines inside a code fence are not list items. A table's header and separator
22
+ rows are not items; each body row is one.
23
+
24
+ Claude Code writes the message holding the call to the transcript after this
25
+ hook starts, so the hook polls the transcript tail until its own tool_use
26
+ entry appears, up to ``TRANSCRIPT_POLL_LIMIT_SECONDS``. That wait is the only
27
+ poll. A payload or transcript the hook cannot read, a transcript path that
28
+ is not a regular file, a call that does not appear in time, a subagent call,
29
+ and any other tool pass with exit 0.
30
+
31
+ The hook reads only the last ``TAIL_WINDOW_BYTES`` (1 MB) of the transcript,
32
+ so a long review followed by more than 1 MB of tool output in the same turn
33
+ is not seen.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import sys
39
+ import time
40
+ from collections.abc import Iterable, Iterator
41
+ from pathlib import Path
42
+
43
+ hooks_root_directory = str(Path(__file__).resolve().parent.parent)
44
+ if hooks_root_directory not in sys.path:
45
+ sys.path.insert(0, hooks_root_directory)
46
+
47
+ from blocking.step_note_gate import entry_content_blocks, read_transcript_tail
48
+ from hooks_constants.ask_user_question_shape import count_prose_words
49
+ from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
50
+ from hooks_constants.question_brief_gate_constants import (
51
+ ALL_HELD_STOP_PROMPT_PREFIXES,
52
+ ALL_MACHINE_PROMPT_PREFIXES,
53
+ ALL_NOT_TYPED_BY_USER_FLAGS,
54
+ ALL_TURN_END_SYSTEM_SUBTYPES,
55
+ ALLOW_EXIT_CODE,
56
+ ASSISTANT_ENTRY_TYPE,
57
+ ATTACHMENT_ENTRY_TYPE,
58
+ ATTACHMENT_KEY,
59
+ BLOCK_EXIT_CODE,
60
+ BLOCK_ID_KEY,
61
+ BLOCK_NAME_KEY,
62
+ BLOCK_TYPE_KEY,
63
+ BRIEF_TEXT_SEPARATOR,
64
+ CODE_FENCE_LINE_PATTERN,
65
+ ENTRY_TYPE_KEY,
66
+ LIST_ITEM_LIMIT_PART_TEMPLATE,
67
+ LIST_ITEM_LINE_PATTERN,
68
+ MAXIMUM_BRIEF_LIST_ITEM_COUNT,
69
+ MAXIMUM_BRIEF_WORD_COUNT,
70
+ MESSAGE_KEY,
71
+ PROMPT_TEXT_SEPARATOR,
72
+ QUESTION_TOOL_NAME,
73
+ QUEUED_COMMAND_ATTACHMENT_TYPE,
74
+ QUEUED_PROMPT_KEY,
75
+ REFUSAL_LIMIT_PART_SEPARATOR,
76
+ REFUSAL_MESSAGE_TEMPLATE,
77
+ RESULT_TOOL_USE_ID_KEY,
78
+ STOP_REASON_KEY,
79
+ SUBAGENT_ID_PAYLOAD_KEY,
80
+ SUBTYPE_KEY,
81
+ SYSTEM_ENTRY_TYPE,
82
+ TABLE_ROW_LINE_PATTERN,
83
+ TABLE_SEPARATOR_LINE_PATTERN,
84
+ TEXT_BLOCK_TYPE,
85
+ TEXT_KEY,
86
+ TOOL_NAME_PAYLOAD_KEY,
87
+ TOOL_RESULT_BLOCK_TYPE,
88
+ TOOL_USE_BLOCK_TYPE,
89
+ TOOL_USE_ID_PAYLOAD_KEY,
90
+ TRANSCRIPT_PATH_PAYLOAD_KEY,
91
+ TRANSCRIPT_POLL_INTERVAL_SECONDS,
92
+ TRANSCRIPT_POLL_LIMIT_SECONDS,
93
+ TURN_END_STOP_REASON,
94
+ USER_ENTRY_TYPE,
95
+ WORD_LIMIT_PART_TEMPLATE,
96
+ )
97
+
98
+
99
+ def _content_blocks(entry: dict) -> list[dict]:
100
+ if not isinstance(entry.get(MESSAGE_KEY), dict):
101
+ return []
102
+ return entry_content_blocks(entry)
103
+
104
+
105
+ def _is_typed_prompt(prompt_text: object) -> bool:
106
+ return (
107
+ isinstance(prompt_text, str)
108
+ and bool(prompt_text.strip())
109
+ and not prompt_text.lstrip().startswith(ALL_MACHINE_PROMPT_PREFIXES)
110
+ )
111
+
112
+
113
+ def _is_earlier_question_result(result_block: dict, all_question_ids: set[str]) -> bool:
114
+ result_tool_use_id = result_block.get(RESULT_TOOL_USE_ID_KEY)
115
+ return isinstance(result_tool_use_id, str) and result_tool_use_id in all_question_ids
116
+
117
+
118
+ def _is_user_input(entry: dict, all_question_ids: set[str]) -> bool:
119
+ entry_type = entry.get(ENTRY_TYPE_KEY)
120
+ if entry_type == ATTACHMENT_ENTRY_TYPE:
121
+ attachment = entry.get(ATTACHMENT_KEY)
122
+ return (
123
+ isinstance(attachment, dict)
124
+ and attachment.get(ENTRY_TYPE_KEY) == QUEUED_COMMAND_ATTACHMENT_TYPE
125
+ and _is_typed_prompt(attachment.get(QUEUED_PROMPT_KEY))
126
+ )
127
+ if entry_type != USER_ENTRY_TYPE or any(
128
+ entry.get(each_flag) for each_flag in ALL_NOT_TYPED_BY_USER_FLAGS
129
+ ):
130
+ return False
131
+ all_blocks = _content_blocks(entry)
132
+ all_results = [
133
+ each_block
134
+ for each_block in all_blocks
135
+ if each_block.get(BLOCK_TYPE_KEY) == TOOL_RESULT_BLOCK_TYPE
136
+ ]
137
+ if all_results:
138
+ return any(
139
+ _is_earlier_question_result(each_result, all_question_ids)
140
+ for each_result in all_results
141
+ )
142
+ return _is_typed_prompt(
143
+ PROMPT_TEXT_SEPARATOR.join(str(each_block.get(TEXT_KEY, "")) for each_block in all_blocks)
144
+ )
145
+
146
+
147
+ def _is_turn_end(entry: dict) -> bool:
148
+ if entry.get(ENTRY_TYPE_KEY) == SYSTEM_ENTRY_TYPE:
149
+ subtype = entry.get(SUBTYPE_KEY)
150
+ return isinstance(subtype, str) and subtype in ALL_TURN_END_SYSTEM_SUBTYPES
151
+ message = entry.get(MESSAGE_KEY)
152
+ return (
153
+ entry.get(ENTRY_TYPE_KEY) == ASSISTANT_ENTRY_TYPE
154
+ and isinstance(message, dict)
155
+ and message.get(STOP_REASON_KEY) == TURN_END_STOP_REASON
156
+ )
157
+
158
+
159
+ def _is_next_turn_input(entry: dict) -> bool:
160
+ entry_type = entry.get(ENTRY_TYPE_KEY)
161
+ if entry_type == ATTACHMENT_ENTRY_TYPE:
162
+ attachment = entry.get(ATTACHMENT_KEY)
163
+ return (
164
+ isinstance(attachment, dict)
165
+ and attachment.get(ENTRY_TYPE_KEY) == QUEUED_COMMAND_ATTACHMENT_TYPE
166
+ )
167
+ prompt_text = PROMPT_TEXT_SEPARATOR.join(
168
+ str(each_block.get(TEXT_KEY, "")) for each_block in _content_blocks(entry)
169
+ )
170
+ is_held_stop_feedback = prompt_text.lstrip().startswith(ALL_HELD_STOP_PROMPT_PREFIXES)
171
+ return entry_type == USER_ENTRY_TYPE and not is_held_stop_feedback
172
+
173
+
174
+ def _is_turn_ended_after(entry: dict, is_turn_ended: bool) -> bool:
175
+ if _is_turn_end(entry):
176
+ return True
177
+ if entry.get(ENTRY_TYPE_KEY) == ASSISTANT_ENTRY_TYPE or _is_next_turn_input(entry):
178
+ return False
179
+ return is_turn_ended
180
+
181
+
182
+ def _assistant_blocks(entry: dict) -> list[dict]:
183
+ if entry.get(ENTRY_TYPE_KEY) != ASSISTANT_ENTRY_TYPE:
184
+ return []
185
+ return _content_blocks(entry)
186
+
187
+
188
+ def _is_question_call(block: dict) -> bool:
189
+ return (
190
+ block.get(BLOCK_TYPE_KEY) == TOOL_USE_BLOCK_TYPE
191
+ and block.get(BLOCK_NAME_KEY) == QUESTION_TOOL_NAME
192
+ )
193
+
194
+
195
+ def _starts_new_count(entry: dict, all_question_ids: set[str], is_turn_ended: bool) -> bool:
196
+ return _is_user_input(entry, all_question_ids) or (
197
+ is_turn_ended and _is_next_turn_input(entry)
198
+ )
199
+
200
+
201
+ def _counted_blocks(
202
+ all_entries: Iterable[dict], all_question_ids: set[str]
203
+ ) -> Iterator[dict | None]:
204
+ is_turn_ended = False
205
+ for each_entry in all_entries:
206
+ if _starts_new_count(each_entry, all_question_ids, is_turn_ended):
207
+ yield None
208
+ yield from _assistant_blocks(each_entry)
209
+ is_turn_ended = _is_turn_ended_after(each_entry, is_turn_ended)
210
+
211
+
212
+ def _question_call_id(block: dict) -> str | None:
213
+ if not _is_question_call(block):
214
+ return None
215
+ return str(block.get(BLOCK_ID_KEY))
216
+
217
+
218
+ def _block_texts(block: dict) -> list[str]:
219
+ block_text = block.get(TEXT_KEY)
220
+ if block.get(BLOCK_TYPE_KEY) != TEXT_BLOCK_TYPE or not isinstance(block_text, str):
221
+ return []
222
+ return [block_text]
223
+
224
+
225
+ def brief_before_question(all_entries: Iterable[dict], tool_use_id: str) -> str | None:
226
+ """Return the chat text Claude wrote this turn before this call.
227
+
228
+ ::
229
+
230
+ prompt, text "A.", tool result, text "B.", this call -> "A.\\nB."
231
+ prompt, text "A.", earlier question result, this call -> ""
232
+ prompt, text "A." ending the turn, held stop, this call -> "A."
233
+
234
+ Args:
235
+ all_entries: Transcript entries, oldest first.
236
+ tool_use_id: The id of the question call being checked.
237
+
238
+ Returns:
239
+ The text blocks joined by line breaks, or None before the call is written.
240
+ """
241
+ all_question_ids: set[str] = set()
242
+ all_brief_texts: list[str] = []
243
+ for each_block in _counted_blocks(all_entries, all_question_ids):
244
+ if each_block is None:
245
+ all_brief_texts = []
246
+ continue
247
+ question_id = _question_call_id(each_block)
248
+ if question_id == tool_use_id:
249
+ return BRIEF_TEXT_SEPARATOR.join(all_brief_texts)
250
+ if question_id is not None:
251
+ all_question_ids.add(question_id)
252
+ continue
253
+ all_brief_texts.extend(_block_texts(each_block))
254
+ return None
255
+
256
+
257
+ def _lines_outside_code_fences(brief_text: str) -> list[str]:
258
+ all_outside_lines: list[str] = []
259
+ is_inside_fence = False
260
+ for each_line in brief_text.splitlines():
261
+ if CODE_FENCE_LINE_PATTERN.match(each_line):
262
+ is_inside_fence = not is_inside_fence
263
+ continue
264
+ if not is_inside_fence:
265
+ all_outside_lines.append(each_line)
266
+ return all_outside_lines
267
+
268
+
269
+ def _is_item_line(line: str, next_line: str) -> bool:
270
+ if LIST_ITEM_LINE_PATTERN.match(line):
271
+ return True
272
+ return bool(
273
+ TABLE_ROW_LINE_PATTERN.match(line)
274
+ and not TABLE_SEPARATOR_LINE_PATTERN.match(line)
275
+ and not TABLE_SEPARATOR_LINE_PATTERN.match(next_line)
276
+ )
277
+
278
+
279
+ def count_list_items(brief_text: str) -> int:
280
+ """Return how many bullet, numbered, and table body lines the text holds.
281
+
282
+ A table's header row and its separator row are not items, and lines
283
+ inside a code fence are not items.
284
+
285
+ ::
286
+
287
+ "- a\\n- b" -> 2
288
+ "| # | What |\\n|---|---|\\n| 1 | x |" -> 1
289
+ "```\\n- a\\n- b\\n```" -> 0
290
+ """
291
+ all_lines = _lines_outside_code_fences(brief_text)
292
+ return sum(
293
+ _is_item_line(each_line, each_next_line)
294
+ for each_line, each_next_line in zip(all_lines, [*all_lines[1:], ""], strict=False)
295
+ )
296
+
297
+
298
+ def refusal_reason(brief_text: str) -> str | None:
299
+ """Return the refusal text naming each limit the brief passed, or None when it fits."""
300
+ word_count = count_prose_words(brief_text)
301
+ list_item_count = count_list_items(brief_text)
302
+ all_limit_parts: list[str] = []
303
+ if word_count > MAXIMUM_BRIEF_WORD_COUNT:
304
+ all_limit_parts.append(
305
+ WORD_LIMIT_PART_TEMPLATE.format(count=word_count, maximum=MAXIMUM_BRIEF_WORD_COUNT)
306
+ )
307
+ if list_item_count > MAXIMUM_BRIEF_LIST_ITEM_COUNT:
308
+ all_limit_parts.append(
309
+ LIST_ITEM_LIMIT_PART_TEMPLATE.format(
310
+ count=list_item_count, maximum=MAXIMUM_BRIEF_LIST_ITEM_COUNT
311
+ )
312
+ )
313
+ if not all_limit_parts:
314
+ return None
315
+ return REFUSAL_MESSAGE_TEMPLATE.format(
316
+ limit_parts=REFUSAL_LIMIT_PART_SEPARATOR.join(all_limit_parts)
317
+ )
318
+
319
+
320
+ def _is_readable_file(transcript_path: Path) -> bool:
321
+ try:
322
+ if not transcript_path.is_file():
323
+ return False
324
+ with transcript_path.open("rb"):
325
+ return True
326
+ except OSError:
327
+ return False
328
+
329
+
330
+ def _wait_for_brief(transcript_path: Path, tool_use_id: str) -> str | None:
331
+ deadline = time.monotonic() + TRANSCRIPT_POLL_LIMIT_SECONDS
332
+ while True:
333
+ try:
334
+ all_entries = read_transcript_tail(transcript_path)
335
+ except RecursionError:
336
+ return None
337
+ brief_text = brief_before_question(all_entries, tool_use_id)
338
+ if brief_text is not None or time.monotonic() >= deadline:
339
+ return brief_text
340
+ time.sleep(TRANSCRIPT_POLL_INTERVAL_SECONDS)
341
+
342
+
343
+ def _read_payload() -> dict[str, object] | None:
344
+ try:
345
+ return read_hook_input_dictionary_from_stdin()
346
+ except RecursionError:
347
+ return None
348
+
349
+
350
+ def main() -> int:
351
+ """Read the PreToolUse payload and refuse a question after a long brief.
352
+
353
+ Returns:
354
+ 2 with the reason on stderr to refuse, else 0.
355
+ """
356
+ hook_payload = _read_payload()
357
+ if hook_payload is None or hook_payload.get(SUBAGENT_ID_PAYLOAD_KEY):
358
+ return ALLOW_EXIT_CODE
359
+ tool_use_id = hook_payload.get(TOOL_USE_ID_PAYLOAD_KEY)
360
+ transcript_path_text = hook_payload.get(TRANSCRIPT_PATH_PAYLOAD_KEY)
361
+ if (
362
+ hook_payload.get(TOOL_NAME_PAYLOAD_KEY) != QUESTION_TOOL_NAME
363
+ or not isinstance(tool_use_id, str)
364
+ or not tool_use_id
365
+ or not isinstance(transcript_path_text, str)
366
+ ):
367
+ return ALLOW_EXIT_CODE
368
+ transcript_path = Path(transcript_path_text)
369
+ if not _is_readable_file(transcript_path):
370
+ return ALLOW_EXIT_CODE
371
+ brief_text = _wait_for_brief(transcript_path, tool_use_id)
372
+ if brief_text is None:
373
+ return ALLOW_EXIT_CODE
374
+ reason = refusal_reason(brief_text)
375
+ if reason is None:
376
+ return ALLOW_EXIT_CODE
377
+ sys.stderr.write(reason)
378
+ return BLOCK_EXIT_CODE
379
+
380
+
381
+ if __name__ == "__main__":
382
+ sys.exit(main())
@@ -33,6 +33,7 @@ hooks_root_directory = str(Path(__file__).resolve().parent.parent)
33
33
  if hooks_root_directory not in sys.path:
34
34
  sys.path.insert(0, hooks_root_directory)
35
35
 
36
+ from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
36
37
  from hooks_constants.step_note_gate_constants import (
37
38
  ALLOW_EXIT_CODE,
38
39
  ASSISTANT_ROLE,
@@ -143,11 +144,13 @@ def wait_for_note_check(transcript_path: Path, tool_use_id: str) -> NoteCheck:
143
144
  def main() -> int:
144
145
  if not STEP_NOTES_ON_FLAG_PATH.exists():
145
146
  return ALLOW_EXIT_CODE
146
- hook_input = json.load(sys.stdin)
147
- if hook_input.get("agent_id"):
147
+ hook_input = read_hook_input_dictionary_from_stdin()
148
+ if hook_input is None or hook_input.get("agent_id"):
148
149
  return ALLOW_EXIT_CODE
149
150
  tool_use_id = hook_input.get("tool_use_id")
150
151
  transcript_path = hook_input.get("transcript_path")
152
+ if not isinstance(tool_use_id, str) or not isinstance(transcript_path, str):
153
+ return ALLOW_EXIT_CODE
151
154
  if not tool_use_id or not transcript_path:
152
155
  return ALLOW_EXIT_CODE
153
156
  if wait_for_note_check(Path(transcript_path), tool_use_id) is NoteCheck.MISSING: