claude-dev-env 8.116.5 → 8.117.0

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 (99) hide show
  1. package/bin/ever-registered-hooks.mjs +2 -0
  2. package/bin/install-constants.mjs +3 -1
  3. package/bin/install.cursor-rules.test.mjs +64 -2
  4. package/bin/install.mjs +15 -2
  5. package/bin/install.prune.test.mjs +92 -0
  6. package/bin/install.test.mjs +1 -0
  7. package/docs/model-choice/escalation.md +3 -3
  8. package/docs/model-choice/subagents-and-fan-out.md +2 -2
  9. package/docs/model-choice/which-model.md +1 -1
  10. package/docs/references/working-style.md +1 -0
  11. package/docs/rule-guides/question-presentation.md +6 -0
  12. package/docs/rule-guides/session-title.md +8 -9
  13. package/docs/rule-guides/subagent-model-effort.md +13 -13
  14. package/hooks/advisory/owned_pr_review_loop.py +2 -3
  15. package/hooks/blocking/bash_post_call_dispatcher.py +17 -9
  16. package/hooks/blocking/bash_pre_tool_use_dispatcher.py +12 -8
  17. package/hooks/blocking/final_reply_gate.py +5 -9
  18. package/hooks/blocking/open_tasks_stop_gate.py +9 -20
  19. package/hooks/blocking/open_tasks_transcript.py +8 -3
  20. package/hooks/blocking/pii_prevention_blocker_parts/repository_exemption.py +7 -2
  21. package/hooks/blocking/question_brief_gate.py +382 -0
  22. package/hooks/blocking/step_note_gate.py +5 -2
  23. package/hooks/blocking/task_subject_length_gate.py +111 -0
  24. package/hooks/blocking/test_bash_post_call_dispatcher.py +36 -1
  25. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +57 -0
  26. package/hooks/blocking/test_final_reply_gate.py +26 -2
  27. package/hooks/blocking/test_open_tasks_stop_gate.py +21 -11
  28. package/hooks/blocking/test_question_brief_gate.py +916 -0
  29. package/hooks/blocking/test_step_note_gate.py +26 -0
  30. package/hooks/blocking/test_task_subject_length_gate.py +221 -0
  31. package/hooks/blocking/test_turn_review_findings.py +124 -1
  32. package/hooks/blocking/test_turn_review_gate.py +1312 -10
  33. package/hooks/blocking/test_turn_review_snapshot.py +8 -0
  34. package/hooks/blocking/tests/test_repository_exemption.py +11 -0
  35. package/hooks/blocking/turn_review_findings.py +173 -13
  36. package/hooks/blocking/turn_review_gate.py +878 -105
  37. package/hooks/blocking/turn_review_snapshot.py +5 -1
  38. package/hooks/features/bash-dispatchers.md +1 -3
  39. package/hooks/features/conduct-gates.md +19 -9
  40. package/hooks/features/lifecycle-cleanup.md +1 -1
  41. package/hooks/features/spawn-routing.md +1 -1
  42. package/hooks/hooks.json +24 -11
  43. package/hooks/hooks_constants/final_reply_gate_constants.py +0 -3
  44. package/hooks/hooks_constants/hook_time_budget.py +61 -0
  45. package/hooks/hooks_constants/hosted_hook_runner.py +51 -21
  46. package/hooks/hooks_constants/hosted_hook_runner_constants.py +3 -0
  47. package/hooks/hooks_constants/nested_project_hooks_constants.py +8 -0
  48. package/hooks/hooks_constants/once_per_session_constants.py +1 -0
  49. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +0 -4
  50. package/hooks/hooks_constants/owned_pr_review_loop_constants.py +0 -4
  51. package/hooks/hooks_constants/pre_tool_use_context_runner.py +23 -3
  52. package/hooks/hooks_constants/pre_tool_use_context_runner_constants.py +5 -0
  53. package/hooks/hooks_constants/pre_tool_use_stdin.py +1 -1
  54. package/hooks/hooks_constants/question_brief_gate_constants.py +66 -0
  55. package/hooks/hooks_constants/session_title_constants.py +6 -27
  56. package/hooks/hooks_constants/stop_hook_hold.py +54 -0
  57. package/hooks/hooks_constants/stop_hook_hold_constants.py +9 -0
  58. package/hooks/hooks_constants/subagent_effort_levels.json +6 -0
  59. package/hooks/hooks_constants/subagent_effort_route_constants.py +20 -19
  60. package/hooks/hooks_constants/task_subject_length_gate_constants.py +43 -0
  61. package/hooks/hooks_constants/test_hook_time_budget.py +104 -0
  62. package/hooks/hooks_constants/test_hosted_hook_runner.py +12 -0
  63. package/hooks/hooks_constants/test_pre_tool_use_context_runner.py +16 -0
  64. package/hooks/hooks_constants/test_pre_tool_use_stdin.py +6 -0
  65. package/hooks/hooks_constants/test_stop_hook_hold.py +40 -0
  66. package/hooks/hooks_constants/thread_spawn_pace_hook_constants.py +1 -2
  67. package/hooks/hooks_constants/turn_review_gate_constants.py +246 -12
  68. package/hooks/lifecycle/nested_project_hooks.py +34 -4
  69. package/hooks/lifecycle/test_nested_project_hooks.py +52 -0
  70. package/hooks/once_per_session.py +33 -4
  71. package/hooks/open_task_asks.py +1 -1
  72. package/hooks/owned_pr_session_record.py +1 -76
  73. package/hooks/routing/subagent_effort_route.py +107 -13
  74. package/hooks/routing/subagent_effort_route_hook.py +9 -8
  75. package/hooks/routing/test_subagent_effort_route.py +201 -14
  76. package/hooks/routing/test_subagent_effort_route_hook.py +56 -0
  77. package/hooks/routing/thread_spawn_pace_hook.py +3 -3
  78. package/hooks/session/background_silence_prompt.py +1 -1
  79. package/hooks/session/test_tracking_nudge.py +114 -2
  80. package/hooks/session/tracking_nudge.py +28 -18
  81. package/hooks/session_title_transcript.py +195 -0
  82. package/hooks/test_once_per_session.py +10 -0
  83. package/hooks/test_owned_pr_session_record.py +0 -26
  84. package/hooks/test_session_title_transcript.py +111 -0
  85. package/hooks/validation/post_tool_use_dispatcher.py +38 -21
  86. package/hooks/validation/test_post_tool_use_dispatcher.py +43 -0
  87. package/package.json +1 -1
  88. package/rules/question-presentation.md +4 -4
  89. package/rules/subagent-model-effort.md +1 -1
  90. package/scripts/claude_account_worker.py +4 -3
  91. package/scripts/policy_lint/adapter_configuration.py +12 -11
  92. package/scripts/policy_lint/config/constants.py +2 -2
  93. package/scripts/test_claude_account_worker.py +1 -0
  94. package/scripts/tests/test_adapter_configuration.py +10 -2
  95. package/hooks/blocking/owned_pr_merge_stop_gate.py +0 -185
  96. package/hooks/blocking/session_title_turn_gate.py +0 -417
  97. package/hooks/blocking/test_owned_pr_merge_stop_gate.py +0 -254
  98. package/hooks/blocking/test_session_title_turn_gate.py +0 -396
  99. package/hooks/hooks_constants/owned_pr_merge_stop_gate_constants.py +0 -40
@@ -1,417 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Stop hook that holds a turn only when the session title shows a stale status.
3
-
4
- The title's emoji tells the user whether a session needs them. The gate leaves
5
- a title alone while it still fits, and holds the turn once when it does not::
6
-
7
- no title set yet -> hold
8
- red flag, and this turn's prompt asks for work -> hold: the user acted on it
9
- check mark, and the task list has open items -> hold: work is open again
10
- hourglass, every item completed or deleted -> hold: nothing runs
11
- anything else -> pass
12
-
13
- A turn that set a title passes, because the agent's choice stands. So does a
14
- turn that called no tool other than the title tool, and a held turn
15
- (``stop_hook_active``). The gate adds at most one step to a turn.
16
-
17
- A turn starts after the latest user prompt in the transcript. Tool results,
18
- meta entries, sidechain entries and compaction summaries are not prompts, and
19
- a Stop hook block lands as an attachment, so a held turn stays the same turn.
20
- A title call on a sidechain entry belongs to a subagent and does not count.
21
- A title the format gate denied does not count either.
22
-
23
- The task list comes from ``open_tasks_stop_gate.session_task_items``. Whether
24
- a prompt asks for work comes from ``open_task_asks.is_ask``.
25
-
26
- The session has the title tool when a transcript record names it::
27
-
28
- attachment.tools[].name / attachment.entries[].name (tool listing)
29
- attachment.addedNames / attachment.readdedNames (deferred tools)
30
- assistant tool_use name (an earlier call)
31
-
32
- A later ``removedNames`` entry takes the name away again. With no such record,
33
- or with an unreadable transcript, the hook lets the turn end, so Codex,
34
- Cursor and sessions without the tool keep working.
35
-
36
- A block writes ``{"decision": "block", "reason": ...}`` to stdout. The reason
37
- names the shown title, why it does not fit, and the four status emoji.
38
- """
39
-
40
- from __future__ import annotations
41
-
42
- import json
43
- import sys
44
- from pathlib import Path
45
-
46
- hooks_root_directory = str(Path(__file__).resolve().parent.parent)
47
- if hooks_root_directory not in sys.path:
48
- sys.path.insert(0, hooks_root_directory)
49
- blocking_directory = str(Path(__file__).resolve().parent)
50
- if blocking_directory not in sys.path:
51
- sys.path.insert(0, blocking_directory)
52
-
53
- from hooks_constants.hook_block_logger import log_hook_block
54
- from hooks_constants.open_tasks_stop_gate_constants import INCOMPLETE_STATUSES
55
- from open_task_asks import is_ask
56
- from open_tasks_stop_gate import session_task_items
57
- from open_tasks_transcript import TaskItem, replayed_transcript
58
- from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
59
- from hooks_constants.session_title_constants import (
60
- ALL_ITEMS_COMPLETED_REASON,
61
- ALL_SKIPPED_PROMPT_FLAGS,
62
- ALL_TOOL_LISTING_NAME_KEYS,
63
- ALL_TOOL_LISTING_RECORD_KEYS,
64
- ALLOW_EXIT_CODE,
65
- ASSISTANT_ENTRY_TYPE,
66
- ATTACHMENT_KEY,
67
- BLOCK_DECISION,
68
- BLOCK_ID_KEY,
69
- BLOCK_INPUT_KEY,
70
- BLOCK_NAME_KEY,
71
- CHECK_MARK_STATUS,
72
- CONTENT_KEY,
73
- DECISION_KEY,
74
- DECODE_ERRORS_POLICY,
75
- ENTRY_TYPE_KEY,
76
- HOURGLASS_STATUS,
77
- IS_ERROR_KEY,
78
- MESSAGE_KEY,
79
- NO_TITLE_REASON,
80
- OPEN_ITEMS_REASON,
81
- REASON_KEY,
82
- RED_FLAG_STATUS,
83
- REMOVED_NAMES_KEY,
84
- SESSION_ID_KEY,
85
- SIDECHAIN_FLAG_KEY,
86
- STALE_FLAG_REASON,
87
- STATUS_PREFIX_PATTERN,
88
- STOP_HOOK_ACTIVE_KEY,
89
- TITLE_INPUT_KEY,
90
- TITLE_TOOL_DISPLAY_SEPARATOR,
91
- TITLE_TOOL_NAME_PATTERN,
92
- TOOL_RESULT_BLOCK_TYPE,
93
- TOOL_USE_BLOCK_TYPE,
94
- TOOL_USE_ID_KEY,
95
- TRANSCRIPT_PATH_KEY,
96
- TURN_BLOCK_REASON,
97
- TURN_GATE_EVENT_NAME,
98
- USER_ENTRY_TYPE,
99
- UTF8_ENCODING,
100
- )
101
-
102
-
103
- def _content_blocks(all_entry_fields: dict[str, object]) -> list[dict[str, object]]:
104
- message = all_entry_fields.get(MESSAGE_KEY)
105
- content = message.get(CONTENT_KEY) if isinstance(message, dict) else None
106
- if not isinstance(content, list):
107
- return []
108
- return [each_block for each_block in content if isinstance(each_block, dict)]
109
-
110
-
111
- def _is_user_prompt(all_entry_fields: dict[str, object]) -> bool:
112
- if all_entry_fields.get(ENTRY_TYPE_KEY) != USER_ENTRY_TYPE:
113
- return False
114
- if any(all_entry_fields.get(each_flag) for each_flag in ALL_SKIPPED_PROMPT_FLAGS):
115
- return False
116
- message = all_entry_fields.get(MESSAGE_KEY)
117
- content = message.get(CONTENT_KEY) if isinstance(message, dict) else None
118
- if isinstance(content, str):
119
- return bool(content.strip())
120
- return any(
121
- each_block.get(ENTRY_TYPE_KEY) != TOOL_RESULT_BLOCK_TYPE
122
- for each_block in _content_blocks(all_entry_fields)
123
- )
124
-
125
-
126
- def _tool_use_blocks(all_entry_fields: dict[str, object]) -> list[dict[str, object]]:
127
- if all_entry_fields.get(ENTRY_TYPE_KEY) != ASSISTANT_ENTRY_TYPE:
128
- return []
129
- return [
130
- each_block
131
- for each_block in _content_blocks(all_entry_fields)
132
- if each_block.get(ENTRY_TYPE_KEY) == TOOL_USE_BLOCK_TYPE
133
- ]
134
-
135
-
136
- def _title_names(all_values: object) -> list[str]:
137
- if not isinstance(all_values, list):
138
- return []
139
- all_names = [
140
- each_value.get(BLOCK_NAME_KEY) if isinstance(each_value, dict) else each_value
141
- for each_value in all_values
142
- ]
143
- return [
144
- each_name
145
- for each_name in all_names
146
- if isinstance(each_name, str) and TITLE_TOOL_NAME_PATTERN.match(each_name)
147
- ]
148
-
149
-
150
- def available_title_tools(all_entries: list[dict[str, object]]) -> list[str]:
151
- """Return the title tool names the session holds at the end of the transcript.
152
-
153
- ::
154
-
155
- attachment {"tools": [{"name": "mcp__x__set_session_title"}]} -> ["mcp__x__set_session_title"]
156
- then attachment {"removedNames": ["mcp__x__set_session_title"]} -> []
157
- no listing and no call -> []
158
-
159
- Args:
160
- all_entries: The transcript entries, oldest first.
161
-
162
- Returns:
163
- The title tool names, in the order the transcript first named them.
164
- """
165
- available_names: dict[str, None] = {}
166
- for each_entry in all_entries:
167
- attachment = each_entry.get(ATTACHMENT_KEY)
168
- if isinstance(attachment, dict):
169
- _apply_tool_listing(available_names, attachment)
170
- available_names.update(dict.fromkeys(_title_names(_tool_use_blocks(each_entry))))
171
- return list(available_names)
172
-
173
-
174
- def _apply_tool_listing(
175
- all_available_names: dict[str, None], all_attachment_fields: dict[str, object]
176
- ) -> None:
177
- for each_key in (*ALL_TOOL_LISTING_NAME_KEYS, *ALL_TOOL_LISTING_RECORD_KEYS):
178
- all_available_names.update(
179
- dict.fromkeys(_title_names(all_attachment_fields.get(each_key)))
180
- )
181
- for each_removed_name in _title_names(all_attachment_fields.get(REMOVED_NAMES_KEY)):
182
- all_available_names.pop(each_removed_name, None)
183
-
184
-
185
- def _last_prompt_index(all_entries: list[dict[str, object]]) -> int:
186
- return max(
187
- (
188
- each_index
189
- for each_index, each_entry in enumerate(all_entries)
190
- if _is_user_prompt(each_entry)
191
- ),
192
- default=-1,
193
- )
194
-
195
-
196
- def _main_chain(all_entries: list[dict[str, object]]) -> list[dict[str, object]]:
197
- return [each_entry for each_entry in all_entries if not each_entry.get(SIDECHAIN_FLAG_KEY)]
198
-
199
-
200
- def _turn_entries(all_entries: list[dict[str, object]]) -> list[dict[str, object]]:
201
- return _main_chain(all_entries[_last_prompt_index(all_entries) + 1 :])
202
-
203
-
204
- def _title_call_ids(all_turn_entries: list[dict[str, object]]) -> set[object]:
205
- return {
206
- each_block.get(BLOCK_ID_KEY)
207
- for each_entry in all_turn_entries
208
- for each_block in _tool_use_blocks(each_entry)
209
- if TITLE_TOOL_NAME_PATTERN.match(str(each_block.get(BLOCK_NAME_KEY)))
210
- }
211
-
212
-
213
- def title_set_this_turn(all_entries: list[dict[str, object]]) -> bool:
214
- """Return True when a title call after the latest prompt came back without an error.
215
-
216
- ::
217
-
218
- prompt -> set_session_title -> ok result -> True
219
- prompt -> set_session_title -> denied result -> False
220
- set_session_title -> ok result -> prompt -> False
221
-
222
- Args:
223
- all_entries: The transcript entries, oldest first.
224
-
225
- Returns:
226
- True when this turn set the title.
227
- """
228
- return _title_succeeded_in(_turn_entries(all_entries))
229
-
230
-
231
- def turn_ran_a_tool(all_entries: list[dict[str, object]]) -> bool:
232
- """Return True when this turn called any tool other than the title tool.
233
-
234
- Args:
235
- all_entries: The transcript entries, oldest first.
236
-
237
- Returns:
238
- True when the turn did work beyond answering in text.
239
- """
240
- return any(
241
- not TITLE_TOOL_NAME_PATTERN.match(str(each_block.get(BLOCK_NAME_KEY)))
242
- for each_entry in _turn_entries(all_entries)
243
- for each_block in _tool_use_blocks(each_entry)
244
- )
245
-
246
-
247
- def _successful_title_call_ids(all_scoped_entries: list[dict[str, object]]) -> set[object]:
248
- all_title_call_ids = _title_call_ids(all_scoped_entries)
249
- return {
250
- each_block.get(TOOL_USE_ID_KEY)
251
- for each_entry in all_scoped_entries
252
- if each_entry.get(ENTRY_TYPE_KEY) == USER_ENTRY_TYPE
253
- for each_block in _content_blocks(each_entry)
254
- if each_block.get(ENTRY_TYPE_KEY) == TOOL_RESULT_BLOCK_TYPE
255
- and each_block.get(TOOL_USE_ID_KEY) in all_title_call_ids
256
- and not each_block.get(IS_ERROR_KEY)
257
- }
258
-
259
-
260
- def _title_succeeded_in(all_scoped_entries: list[dict[str, object]]) -> bool:
261
- return bool(_successful_title_call_ids(all_scoped_entries))
262
-
263
-
264
- def _title_input(all_block_fields: dict[str, object]) -> str | None:
265
- all_input_fields = all_block_fields.get(BLOCK_INPUT_KEY)
266
- title = all_input_fields.get(TITLE_INPUT_KEY) if isinstance(all_input_fields, dict) else None
267
- return title if isinstance(title, str) else None
268
-
269
-
270
- def shown_title(all_entries: list[dict[str, object]]) -> str | None:
271
- """Return the title of the last main-chain title call that came back without an error.
272
-
273
- ::
274
-
275
- "\u23f3 Export" ok, then "\u2705 Export" denied -> "\u23f3 Export"
276
- no title call -> None
277
-
278
- Args:
279
- all_entries: The transcript entries, oldest first.
280
-
281
- Returns:
282
- The title the session shows, or None when no title call succeeded.
283
- """
284
- all_main_entries = _main_chain(all_entries)
285
- all_successful_ids = _successful_title_call_ids(all_main_entries)
286
- all_titles = [
287
- _title_input(each_block)
288
- for each_entry in all_main_entries
289
- for each_block in _tool_use_blocks(each_entry)
290
- if each_block.get(BLOCK_ID_KEY) in all_successful_ids
291
- ]
292
- all_text_titles = [each_title for each_title in all_titles if each_title is not None]
293
- return all_text_titles[-1] if all_text_titles else None
294
-
295
-
296
- def title_status(title: str) -> str | None:
297
- """Return the status emoji the title starts with, without a variation selector, or None."""
298
- status_match = STATUS_PREFIX_PATTERN.match(title)
299
- return status_match.group(1) if status_match else None
300
-
301
-
302
- def stale_status_reason(title: str, is_ask_turn: bool, all_task_items: list[TaskItem]) -> str | None:
303
- """Return why the shown title does not fit the session's state, or None when it fits.
304
-
305
- ::
306
-
307
- red flag, the prompt asks for work -> reason
308
- check mark, an item is pending -> reason
309
- hourglass, every item completed or deleted -> reason
310
- hourglass, an item is in progress -> None
311
-
312
- Args:
313
- title: The title the session shows.
314
- is_ask_turn: True when the prompt that started this turn asks for work.
315
- all_task_items: The session's task list.
316
-
317
- Returns:
318
- The reason the status is stale, with the title filled in, or None.
319
- """
320
- status = title_status(title)
321
- has_open_items = any(each_item.status in INCOMPLETE_STATUSES for each_item in all_task_items)
322
- is_all_completed = bool(all_task_items) and not has_open_items
323
- if status == RED_FLAG_STATUS and is_ask_turn:
324
- return STALE_FLAG_REASON.format(title=title)
325
- if status == CHECK_MARK_STATUS and has_open_items:
326
- return OPEN_ITEMS_REASON.format(title=title)
327
- if status == HOURGLASS_STATUS and is_all_completed:
328
- return ALL_ITEMS_COMPLETED_REASON.format(title=title)
329
- return None
330
-
331
-
332
- def turn_block_reason(
333
- all_entries: list[dict[str, object]],
334
- is_stop_hook_active: bool,
335
- is_ask_turn: bool,
336
- all_task_items: list[TaskItem],
337
- ) -> str | None:
338
- """Return the reason to hold the turn, or None when the turn may end.
339
-
340
- ::
341
-
342
- no title tool in the transcript -> None
343
- held turn (stop_hook_active) -> None
344
- title set this turn -> None
345
- no tool other than the title tool this turn -> None
346
- no title set in the session yet -> reason
347
- shown title has a stale status -> reason
348
- shown title still fits -> None
349
-
350
- Args:
351
- all_entries: The transcript entries, oldest first.
352
- is_stop_hook_active: True when a Stop hook already held this turn.
353
- is_ask_turn: True when the prompt that started this turn asks for work.
354
- all_task_items: The session's task list.
355
-
356
- Returns:
357
- The block reason that names the title tool, or None.
358
- """
359
- all_title_tools = available_title_tools(all_entries)
360
- if not all_title_tools or is_stop_hook_active or title_set_this_turn(all_entries):
361
- return None
362
- if not turn_ran_a_tool(all_entries):
363
- return None
364
- title = shown_title(all_entries)
365
- stale_reason = NO_TITLE_REASON if title is None else stale_status_reason(title, is_ask_turn, all_task_items)
366
- if stale_reason is None:
367
- return None
368
- return TURN_BLOCK_REASON.format(
369
- why=stale_reason, tool_name=TITLE_TOOL_DISPLAY_SEPARATOR.join(all_title_tools)
370
- )
371
-
372
-
373
- def _parsed_entry(line: str) -> dict[str, object] | None:
374
- try:
375
- parsed_entry = json.loads(line)
376
- except json.JSONDecodeError:
377
- return None
378
- return parsed_entry if isinstance(parsed_entry, dict) else None
379
-
380
-
381
- def read_transcript_entries(transcript_path: object) -> list[dict[str, object]]:
382
- """Return the transcript's JSON object entries, or an empty list when it cannot be read."""
383
- if not isinstance(transcript_path, str) or not transcript_path:
384
- return []
385
- try:
386
- all_lines = (
387
- Path(transcript_path)
388
- .read_text(encoding=UTF8_ENCODING, errors=DECODE_ERRORS_POLICY)
389
- .splitlines()
390
- )
391
- except OSError:
392
- return []
393
- all_parsed_entries = (_parsed_entry(each_line) for each_line in all_lines)
394
- return [each_entry for each_entry in all_parsed_entries if each_entry is not None]
395
-
396
-
397
- def main() -> int:
398
- hook_input = read_hook_input_dictionary_from_stdin()
399
- if hook_input is None:
400
- return ALLOW_EXIT_CODE
401
- transcript_path = hook_input.get(TRANSCRIPT_PATH_KEY)
402
- replay = replayed_transcript(transcript_path)
403
- block_reason = turn_block_reason(
404
- read_transcript_entries(transcript_path),
405
- hook_input.get(STOP_HOOK_ACTIVE_KEY) is True,
406
- is_ask(replay.turn_prompt_text),
407
- session_task_items(hook_input.get(SESSION_ID_KEY), replay),
408
- )
409
- if block_reason is None:
410
- return ALLOW_EXIT_CODE
411
- log_hook_block(Path(__file__).name, TURN_GATE_EVENT_NAME, block_reason)
412
- sys.stdout.write(json.dumps({DECISION_KEY: BLOCK_DECISION, REASON_KEY: block_reason}))
413
- return ALLOW_EXIT_CODE
414
-
415
-
416
- if __name__ == "__main__":
417
- sys.exit(main())
@@ -1,254 +0,0 @@
1
- """Behavior tests for the owned pull request merge Stop gate."""
2
-
3
- from __future__ import annotations
4
-
5
- import io
6
- import json
7
- import subprocess
8
- from pathlib import Path
9
-
10
- import pytest
11
-
12
- import owned_pr_merge_stop_gate
13
- import owned_pr_session_record
14
-
15
- SESSION_ID = "session-abc"
16
- PULL_REQUEST = {
17
- "owner": "jl-cmd",
18
- "repository": "snake-game",
19
- "number": "9",
20
- "url": "https://github.com/jl-cmd/snake-game/pull/9",
21
- }
22
- RECORDED_PULL_REQUEST = {
23
- "owner": "jl-cmd-projects",
24
- "repository": "claude-dev-env",
25
- "number": "2300",
26
- "url": "https://github.com/jl-cmd-projects/claude-dev-env/pull/2300",
27
- }
28
- RECORDED_HEAD = "6ea405f886de9e3a434376a0b580cc3648d11a3c"
29
- FIRST_HEAD = "abc1234def5678abc1234def5678abc1234def56"
30
- PUSHED_HEAD = "9999999aaaaaaa9999999aaaaaaa9999999aaaaa"
31
-
32
-
33
- @pytest.fixture(autouse=True)
34
- def isolated_temp_folder(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
35
- monkeypatch.setattr(owned_pr_session_record.tempfile, "gettempdir", lambda: str(tmp_path))
36
- monkeypatch.setenv("HOME", str(tmp_path))
37
-
38
-
39
- def _gh_reports(
40
- monkeypatch: pytest.MonkeyPatch, state_text: str, exit_code: int = 0
41
- ) -> list[list[str]]:
42
- all_calls: list[list[str]] = []
43
-
44
- def fake_run(all_arguments: list[str], **_: object) -> subprocess.CompletedProcess[str]:
45
- all_calls.append(all_arguments)
46
- return subprocess.CompletedProcess(all_arguments, exit_code, stdout=state_text, stderr="")
47
-
48
- monkeypatch.setattr(owned_pr_merge_stop_gate.subprocess, "run", fake_run)
49
- return all_calls
50
-
51
-
52
- def _run_gate(
53
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], reply_text: str
54
- ) -> str:
55
- hook_input = {
56
- "hook_event_name": "Stop",
57
- "session_id": SESSION_ID,
58
- "last_assistant_message": reply_text,
59
- }
60
- monkeypatch.setattr(
61
- "sys.stdin", io.TextIOWrapper(io.BytesIO(json.dumps(hook_input).encode("utf-8")))
62
- )
63
- assert owned_pr_merge_stop_gate.main() == 0
64
- return capsys.readouterr().out
65
-
66
-
67
- def test_main_should_block_while_a_recorded_pull_request_is_open(
68
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
69
- ) -> None:
70
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
71
- all_calls = _gh_reports(monkeypatch, "open\n")
72
- decision = json.loads(_run_gate(monkeypatch, capsys, "Draft PR is open."))
73
- assert decision["decision"] == "block"
74
- assert PULL_REQUEST["url"] in decision["reason"]
75
- assert "/efficient-review" in decision["reason"]
76
- assert all_calls == [
77
- ["gh", "api", "repos/jl-cmd/snake-game/pulls/9", "--jq", '.state + " " + .head.sha']
78
- ]
79
-
80
-
81
- def test_main_should_allow_once_the_pull_request_is_closed(
82
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
83
- ) -> None:
84
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
85
- _gh_reports(monkeypatch, "closed\n")
86
- assert _run_gate(monkeypatch, capsys, "Merged.") == ""
87
-
88
-
89
- def test_main_should_allow_a_blocked_line_that_names_the_pull_request(
90
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
91
- ) -> None:
92
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
93
- _gh_reports(monkeypatch, "open\n")
94
- reply_text = "Review is clean.\nBlocked: jl-cmd/snake-game#9 - the owner must approve the merge"
95
- assert _run_gate(monkeypatch, capsys, reply_text) == ""
96
-
97
-
98
- def test_main_should_block_when_the_blocked_line_names_another_pull_request(
99
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
100
- ) -> None:
101
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
102
- _gh_reports(monkeypatch, "open\n")
103
- reply_text = "Blocked: jl-cmd/snake-game#90 - the owner must approve the merge"
104
- assert json.loads(_run_gate(monkeypatch, capsys, reply_text))["decision"] == "block"
105
-
106
-
107
- def test_main_should_allow_when_the_state_lookup_fails(
108
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
109
- ) -> None:
110
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
111
- _gh_reports(monkeypatch, "", exit_code=1)
112
- assert _run_gate(monkeypatch, capsys, "Draft PR is open.") == ""
113
-
114
-
115
- def test_main_should_allow_a_session_that_opened_no_owned_pull_request(
116
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
117
- ) -> None:
118
- all_calls = _gh_reports(monkeypatch, "open\n")
119
- assert _run_gate(monkeypatch, capsys, "Done.") == ""
120
- assert all_calls == []
121
-
122
-
123
- def test_open_head_should_read_the_github_state_and_head(monkeypatch: pytest.MonkeyPatch) -> None:
124
- _gh_reports(monkeypatch, f"open {FIRST_HEAD}\n")
125
- assert owned_pr_merge_stop_gate.open_head(PULL_REQUEST) == FIRST_HEAD
126
-
127
-
128
- def test_open_head_should_read_a_closed_pull_request_as_none(monkeypatch: pytest.MonkeyPatch) -> None:
129
- _gh_reports(monkeypatch, f"closed {FIRST_HEAD}\n")
130
- assert owned_pr_merge_stop_gate.open_head(PULL_REQUEST) is None
131
-
132
-
133
- def test_is_reported_blocked_should_accept_the_url() -> None:
134
- reply_text = f"- Blocked: {PULL_REQUEST['url']} - needs the owner"
135
- assert owned_pr_merge_stop_gate.is_reported_blocked(PULL_REQUEST, reply_text)
136
-
137
-
138
- def test_unfinished_pull_requests_should_list_the_open_one(monkeypatch: pytest.MonkeyPatch) -> None:
139
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
140
- _gh_reports(monkeypatch, f"open {FIRST_HEAD}\n")
141
- hook_input: dict[str, object] = {"session_id": SESSION_ID, "last_assistant_message": "Open."}
142
- assert owned_pr_merge_stop_gate.unfinished_pull_requests(hook_input) == [
143
- {**PULL_REQUEST, "head": FIRST_HEAD}
144
- ]
145
-
146
-
147
- def test_block_reason_for_should_name_each_pull_request_and_the_blocked_form() -> None:
148
- reason = owned_pr_merge_stop_gate.block_reason_for([PULL_REQUEST])
149
- assert PULL_REQUEST["url"] in reason
150
- assert "Blocked: <owner>/<repository>#<number>" in reason
151
-
152
-
153
- def test_main_should_report_a_failed_lookup_on_stderr(
154
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
155
- ) -> None:
156
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
157
- _gh_reports(monkeypatch, "", exit_code=1)
158
- hook_input = {"hook_event_name": "Stop", "session_id": SESSION_ID, "last_assistant_message": "Open."}
159
- monkeypatch.setattr("sys.stdin", io.TextIOWrapper(io.BytesIO(json.dumps(hook_input).encode("utf-8"))))
160
- owned_pr_merge_stop_gate.main()
161
- assert "could not read repos/jl-cmd/snake-game/pulls/9" in capsys.readouterr().err
162
-
163
-
164
- def test_is_reported_blocked_should_accept_a_bold_blocked_label() -> None:
165
- reply_text = "**Blocked:** jl-cmd/snake-game#9 - the owner must approve the merge"
166
- assert owned_pr_merge_stop_gate.is_reported_blocked(PULL_REQUEST, reply_text)
167
-
168
-
169
- def test_is_reported_blocked_should_skip_a_longer_owner_that_ends_with_the_name() -> None:
170
- suffix_pull_request = {**PULL_REQUEST, "owner": "cmd", "url": "https://github.com/cmd/snake-game/pull/9"}
171
- reply_text = "Blocked: jl-cmd/snake-game#9 - the owner must approve the merge"
172
- assert not owned_pr_merge_stop_gate.is_reported_blocked(suffix_pull_request, reply_text)
173
-
174
-
175
- def test_block_reason_for_should_name_a_user_hold_as_a_blocker() -> None:
176
- assert "asked to hold the PR or to read it first" in owned_pr_merge_stop_gate.block_reason_for([PULL_REQUEST])
177
-
178
-
179
- def test_is_reported_blocked_should_require_the_colon_after_blocked() -> None:
180
- reply_text = "Blocked while CI runs on jl-cmd/snake-game#9."
181
- assert not owned_pr_merge_stop_gate.is_reported_blocked(PULL_REQUEST, reply_text)
182
-
183
-
184
- def _gh_serves(
185
- monkeypatch: pytest.MonkeyPatch, all_pull_requests: dict[str, tuple[str, str]]
186
- ) -> None:
187
- def fake_run(all_arguments: list[str], **_: object) -> subprocess.CompletedProcess[str]:
188
- state, head = all_pull_requests[all_arguments[2]]
189
- answer = state if all_arguments[4] == ".state" else f"{state} {head}"
190
- return subprocess.CompletedProcess(all_arguments, 0, stdout=answer + "\n", stderr="")
191
-
192
- monkeypatch.setattr(owned_pr_merge_stop_gate.subprocess, "run", fake_run)
193
-
194
-
195
- RECORDED_ENDPOINT = "repos/jl-cmd-projects/claude-dev-env/pulls/2300"
196
- PULL_REQUEST_ENDPOINT = "repos/jl-cmd/snake-game/pulls/9"
197
-
198
-
199
- def test_main_should_block_once_per_head_on_the_recorded_pull_request(
200
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
201
- ) -> None:
202
- owned_pr_session_record.record_pull_request(SESSION_ID, RECORDED_PULL_REQUEST)
203
- _gh_serves(monkeypatch, {RECORDED_ENDPOINT: ("open", RECORDED_HEAD)})
204
- first_decision = json.loads(_run_gate(monkeypatch, capsys, "Review is clean."))
205
- assert first_decision["decision"] == "block"
206
- assert RECORDED_PULL_REQUEST["url"] in first_decision["reason"]
207
- assert _run_gate(monkeypatch, capsys, "Waiting on CI.") == ""
208
- assert _run_gate(monkeypatch, capsys, "Still waiting on CI.") == ""
209
-
210
-
211
- def test_main_should_block_again_after_the_head_moves(
212
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
213
- ) -> None:
214
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
215
- _gh_serves(monkeypatch, {PULL_REQUEST_ENDPOINT: ("open", FIRST_HEAD)})
216
- assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"
217
- _gh_serves(monkeypatch, {PULL_REQUEST_ENDPOINT: ("open", PUSHED_HEAD)})
218
- assert json.loads(_run_gate(monkeypatch, capsys, "Pushed a fix."))["decision"] == "block"
219
- assert _run_gate(monkeypatch, capsys, "Waiting on CI.") == ""
220
-
221
-
222
- def test_main_should_block_every_stop_when_github_gives_no_head(
223
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
224
- ) -> None:
225
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
226
- _gh_reports(monkeypatch, "open\n")
227
- assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"
228
- assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"
229
-
230
-
231
- def test_main_should_list_only_the_pull_request_with_a_new_head(
232
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
233
- ) -> None:
234
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
235
- _gh_serves(monkeypatch, {PULL_REQUEST_ENDPOINT: ("open", FIRST_HEAD)})
236
- assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"
237
- owned_pr_session_record.record_pull_request(SESSION_ID, RECORDED_PULL_REQUEST)
238
- _gh_serves(
239
- monkeypatch,
240
- {PULL_REQUEST_ENDPOINT: ("open", FIRST_HEAD), RECORDED_ENDPOINT: ("open", RECORDED_HEAD)},
241
- )
242
- reason = json.loads(_run_gate(monkeypatch, capsys, "Opened another."))["reason"]
243
- assert RECORDED_PULL_REQUEST["url"] in reason
244
- assert PULL_REQUEST["url"] not in reason
245
-
246
-
247
- def test_main_should_keep_the_blocked_line_release_before_the_first_block(
248
- monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
249
- ) -> None:
250
- owned_pr_session_record.record_pull_request(SESSION_ID, PULL_REQUEST)
251
- _gh_serves(monkeypatch, {PULL_REQUEST_ENDPOINT: ("open", FIRST_HEAD)})
252
- reply_text = "Blocked: jl-cmd/snake-game#9 - the user holds the merge"
253
- assert _run_gate(monkeypatch, capsys, reply_text) == ""
254
- assert json.loads(_run_gate(monkeypatch, capsys, "Open."))["decision"] == "block"