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
@@ -2,19 +2,38 @@
2
2
 
3
3
  Reads the payload from stdin, asks the hook's decide function for an output,
4
4
  and writes it as JSON. The output may add context or deny the call. Exit
5
- status is always 0; a decide function that raises leaves the call with no
6
- output.
5
+ status is always 0. A decide function that raises leaves the call with no
6
+ output and writes one line to stderr that names the crash::
7
+
8
+ spawn_oversight_hook.py: crashed, the call goes through: KeyError: 'prompt'
7
9
  """
8
10
 
9
11
  from __future__ import annotations
10
12
 
11
13
  import json
14
+ import re
12
15
  import sys
13
16
  from collections.abc import Callable
17
+ from pathlib import Path
14
18
 
19
+ from hooks_constants.pre_tool_use_context_runner_constants import (
20
+ CRASH_LINE_TEMPLATE,
21
+ LINE_BREAK_PATTERN,
22
+ LINE_BREAK_REPLACEMENT,
23
+ )
15
24
  from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
16
25
 
17
26
 
27
+ def _write_crash_line(crash: Exception) -> None:
28
+ sys.stderr.write(
29
+ CRASH_LINE_TEMPLATE.format(
30
+ hook_name=Path(sys.argv[0]).name,
31
+ crash_type=type(crash).__name__,
32
+ crash_text=re.sub(LINE_BREAK_PATTERN, LINE_BREAK_REPLACEMENT, str(crash)).strip(),
33
+ )
34
+ )
35
+
36
+
18
37
  def run_context_hook(
19
38
  decide_hook_output: Callable[[dict[str, object]], dict[str, object] | None],
20
39
  ) -> int:
@@ -31,7 +50,8 @@ def run_context_hook(
31
50
  return 0
32
51
  try:
33
52
  hook_output = decide_hook_output(hook_payload)
34
- except Exception:
53
+ except Exception as crash:
54
+ _write_crash_line(crash)
35
55
  return 0
36
56
  if hook_output is not None:
37
57
  sys.stdout.write(json.dumps(hook_output))
@@ -0,0 +1,5 @@
1
+ """Constants for the shared PreToolUse context hook runner."""
2
+
3
+ CRASH_LINE_TEMPLATE = "{hook_name}: crashed, the call goes through: {crash_type}: {crash_text}\n"
4
+ LINE_BREAK_PATTERN = r"\s*[\r\n]+\s*"
5
+ LINE_BREAK_REPLACEMENT = " "
@@ -42,7 +42,7 @@ def read_hook_input_dictionary_from_stdin() -> dict[str, object] | None:
42
42
  return None
43
43
  try:
44
44
  parsed_payload = json.loads(normalized_text)
45
- except json.JSONDecodeError:
45
+ except ValueError:
46
46
  return None
47
47
  if not isinstance(parsed_payload, dict):
48
48
  return None
@@ -0,0 +1,66 @@
1
+ """Constants for the question brief gate PreToolUse hook.
2
+
3
+ Groups: the brief limits, the transcript poll, the transcript shapes that
4
+ mark the user's own input and the end of a turn, the list line patterns, and
5
+ the refusal message.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ MAXIMUM_BRIEF_WORD_COUNT = 450
13
+ MAXIMUM_BRIEF_LIST_ITEM_COUNT = 15
14
+
15
+ TRANSCRIPT_POLL_INTERVAL_SECONDS = 0.05
16
+ TRANSCRIPT_POLL_LIMIT_SECONDS = 3.0
17
+
18
+ QUESTION_TOOL_NAME = "AskUserQuestion"
19
+ SUBAGENT_ID_PAYLOAD_KEY = "agent_id"
20
+ TOOL_USE_ID_PAYLOAD_KEY = "tool_use_id"
21
+ TRANSCRIPT_PATH_PAYLOAD_KEY = "transcript_path"
22
+ TOOL_NAME_PAYLOAD_KEY = "tool_name"
23
+
24
+ ENTRY_TYPE_KEY = "type"
25
+ USER_ENTRY_TYPE = "user"
26
+ ASSISTANT_ENTRY_TYPE = "assistant"
27
+ SYSTEM_ENTRY_TYPE = "system"
28
+ ATTACHMENT_ENTRY_TYPE = "attachment"
29
+ ATTACHMENT_KEY = "attachment"
30
+ QUEUED_COMMAND_ATTACHMENT_TYPE = "queued_command"
31
+ QUEUED_PROMPT_KEY = "prompt"
32
+ MESSAGE_KEY = "message"
33
+ SUBTYPE_KEY = "subtype"
34
+ STOP_REASON_KEY = "stop_reason"
35
+ TURN_END_STOP_REASON = "end_turn"
36
+ ALL_TURN_END_SYSTEM_SUBTYPES = frozenset({"stop_hook_summary"})
37
+ BLOCK_TYPE_KEY = "type"
38
+ TEXT_BLOCK_TYPE = "text"
39
+ TEXT_KEY = "text"
40
+ TOOL_USE_BLOCK_TYPE = "tool_use"
41
+ TOOL_RESULT_BLOCK_TYPE = "tool_result"
42
+ BLOCK_ID_KEY = "id"
43
+ BLOCK_NAME_KEY = "name"
44
+ RESULT_TOOL_USE_ID_KEY = "tool_use_id"
45
+ ALL_NOT_TYPED_BY_USER_FLAGS = ("isMeta", "isSidechain", "isCompactSummary")
46
+ ALL_MACHINE_PROMPT_PREFIXES = ("<task-notification", "<agent-message", "Stop hook feedback")
47
+ ALL_HELD_STOP_PROMPT_PREFIXES = ("Stop hook feedback",)
48
+ PROMPT_TEXT_SEPARATOR = " "
49
+ BRIEF_TEXT_SEPARATOR = "\n"
50
+
51
+ LIST_ITEM_LINE_PATTERN = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+\S")
52
+ TABLE_ROW_LINE_PATTERN = re.compile(r"^\s*\|.*\|\s*$")
53
+ TABLE_SEPARATOR_LINE_PATTERN = re.compile(r"^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)*\|?\s*$")
54
+ CODE_FENCE_LINE_PATTERN = re.compile(r"^\s*(?:```|~~~)")
55
+
56
+ BLOCK_EXIT_CODE = 2
57
+ ALLOW_EXIT_CODE = 0
58
+ WORD_LIMIT_PART_TEMPLATE = "{count} words, over the {maximum}-word limit"
59
+ LIST_ITEM_LIMIT_PART_TEMPLATE = "{count} list or table items, over the {maximum}-item limit"
60
+ REFUSAL_LIMIT_PART_SEPARATOR = ", and "
61
+ REFUSAL_MESSAGE_TEMPLATE = (
62
+ "Question refused: the chat text before this question in this turn runs {limit_parts}. "
63
+ "That text has already posted, so do not repeat it. Shorten the brief to the context "
64
+ "and each choice's effect, or split the question: ask about one item now and send each "
65
+ "other item as its own question after the user answers this one."
66
+ )
@@ -1,4 +1,4 @@
1
- """Constants for session_title_format_gate.py and session_title_turn_gate.py."""
1
+ """Constants for session_title_format_gate.py, session_title_transcript.py and tracking_nudge.py."""
2
2
 
3
3
  import re
4
4
 
@@ -33,12 +33,6 @@ FORMAT_RETRY_INSTRUCTION = (
33
33
  " '\u23f3 Broker gate + replay rule'."
34
34
  )
35
35
 
36
- TURN_GATE_EVENT_NAME = "Stop"
37
- TRANSCRIPT_PATH_KEY = "transcript_path"
38
- STOP_HOOK_ACTIVE_KEY = "stop_hook_active"
39
- DECISION_KEY = "decision"
40
- REASON_KEY = "reason"
41
- BLOCK_DECISION = "block"
42
36
  UTF8_ENCODING = "utf-8"
43
37
  DECODE_ERRORS_POLICY = "replace"
44
38
  ENTRY_TYPE_KEY = "type"
@@ -54,36 +48,21 @@ BLOCK_NAME_KEY = "name"
54
48
  TOOL_USE_ID_KEY = "tool_use_id"
55
49
  IS_ERROR_KEY = "is_error"
56
50
  SIDECHAIN_FLAG_KEY = "isSidechain"
57
- ALL_SKIPPED_PROMPT_FLAGS = ("isMeta", SIDECHAIN_FLAG_KEY, "isCompactSummary")
58
51
  ALL_TOOL_LISTING_NAME_KEYS = ("addedNames", "readdedNames")
59
52
  ALL_TOOL_LISTING_RECORD_KEYS = ("tools", "entries")
60
53
  REMOVED_NAMES_KEY = "removedNames"
61
54
  TITLE_TOOL_DISPLAY_SEPARATOR = " or "
62
55
 
63
- SESSION_ID_KEY = "session_id"
64
56
  BLOCK_INPUT_KEY = "input"
65
57
  RED_FLAG_STATUS = "\U0001f6a9"
66
58
  CHECK_MARK_STATUS = "\u2705"
67
- HOURGLASS_STATUS = "\u23f3"
68
- NO_TITLE_REASON = "This session has no title yet."
69
- STALE_FLAG_REASON = (
70
- "The title '{title}' still shows the red flag from before the user's last message,"
71
- " and that message gave you work."
72
- )
73
- OPEN_ITEMS_REASON = "The title '{title}' shows the work as done, and the task list has open items."
74
- ALL_ITEMS_COMPLETED_REASON = "The title '{title}' shows work running, and every task list item is completed or deleted."
75
-
76
- TURN_BLOCK_REASON = (
77
- "{why} Call {tool_name} now with '<emoji> <name>' for the current status:"
78
- " \U0001f6a9 the user must act, \U0001f6a7 an outside dependency blocks the work,"
79
- " \u2705 the work is done, \u23f3 work runs and nothing waits on the user."
80
- " When the tool is deferred, load its schema with ToolSearch first."
81
- " When it asks for a session id, get it from get_session with no session_id."
82
- " After the call, end the turn with one short closing sentence."
83
- " Leave the earlier reply as it stands and do not repeat it."
84
- )
85
59
  ALL_STALE_AT_START_STATUSES = frozenset({RED_FLAG_STATUS, CHECK_MARK_STATUS})
86
60
  TITLE_NUDGE_TEMPLATE = (
87
61
  "The session title shows '{title}' from before this message. Set it with {tool_name} to"
88
62
  " '⏳ <name>' before other work, so the user sees the session working."
89
63
  )
64
+ NO_TITLE_NUDGE_TEMPLATE = (
65
+ "This session has no title yet. Set it with {tool_name} to"
66
+ " '⏳ <name>' before other work, so the user sees the session working."
67
+ )
68
+ NO_TITLE_NUDGE_ONCE_MARKER_NAME = "no_title_nudge"
@@ -0,0 +1,54 @@
1
+ """Shared hold signal for Stop hooks.
2
+
3
+ A Stop gate that finds a problem holds the turn so the model tries again. Each
4
+ host reads the hold from a different channel, so one call writes all of them::
5
+
6
+ Claude Code exit code 2; the stdout ``reason`` reaches the model
7
+ Codex exit code 2; stderr reaches the model
8
+ Cursor exit code 0; ``followup_message`` becomes the next user message
9
+
10
+ A Cursor payload carries ``conversation_id``. Cursor documents no exit code 2
11
+ for its ``stop`` event, so that payload keeps exit code 0. Every other payload
12
+ gets exit code 2, with the same text on stderr and in the stdout ``reason``,
13
+ so the hold does not depend on which channel the host reads first.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import sys
20
+
21
+ from hooks_constants.stop_hook_hold_constants import (
22
+ ALLOW_EXIT_CODE,
23
+ BLOCK_DECISION,
24
+ BLOCK_EXIT_CODE,
25
+ CURSOR_CONVERSATION_ID_KEY,
26
+ CURSOR_FOLLOWUP_MESSAGE_KEY,
27
+ DECISION_KEY,
28
+ REASON_KEY,
29
+ )
30
+
31
+
32
+ def stop_hold_output(all_hook_input_fields: dict[str, object], block_reason: str) -> dict[str, str]:
33
+ """Return the stdout object for a hold; a Cursor payload also gets ``followup_message``."""
34
+ hold_output = {DECISION_KEY: BLOCK_DECISION, REASON_KEY: block_reason}
35
+ if all_hook_input_fields.get(CURSOR_CONVERSATION_ID_KEY):
36
+ hold_output[CURSOR_FOLLOWUP_MESSAGE_KEY] = block_reason
37
+ return hold_output
38
+
39
+
40
+ def hold_stop(all_hook_input_fields: dict[str, object], block_reason: str) -> int:
41
+ """Write the hold for this host and return the exit code the hook must exit with.
42
+
43
+ Args:
44
+ all_hook_input_fields: The Stop payload the hook read from stdin.
45
+ block_reason: The text the model gets back so it can fix the problem.
46
+
47
+ Returns:
48
+ Zero for a Cursor payload, two for every other host.
49
+ """
50
+ sys.stdout.write(json.dumps(stop_hold_output(all_hook_input_fields, block_reason)))
51
+ if all_hook_input_fields.get(CURSOR_CONVERSATION_ID_KEY):
52
+ return ALLOW_EXIT_CODE
53
+ sys.stderr.write(block_reason)
54
+ return BLOCK_EXIT_CODE
@@ -0,0 +1,9 @@
1
+ """Constants for the shared Stop hook hold signal."""
2
+
3
+ DECISION_KEY = "decision"
4
+ BLOCK_DECISION = "block"
5
+ REASON_KEY = "reason"
6
+ ALLOW_EXIT_CODE = 0
7
+ BLOCK_EXIT_CODE = 2
8
+ CURSOR_CONVERSATION_ID_KEY = "conversation_id"
9
+ CURSOR_FOLLOWUP_MESSAGE_KEY = "followup_message"
@@ -0,0 +1,6 @@
1
+ {
2
+ "opus": {"allowed": ["medium", "high"], "default": "medium"},
3
+ "sonnet": {"allowed": ["high"], "default": "high"},
4
+ "fable": {"allowed": ["low", "medium", "high"], "default": "high"},
5
+ "haiku": {"allowed": ["low", "medium", "high", "xhigh", "max"], "default": "medium"}
6
+ }
@@ -1,29 +1,30 @@
1
1
  """Constants for the subagent effort route.
2
2
 
3
- Groups: the allowed effort for each Anthropic model family, the effort a spawn
4
- gets when it names none or names one outside its family's list, the tool
5
- input keys, and the hook output text.
3
+ Groups: where the hand-edited effort levels file lives and the keys it uses,
4
+ the built-in levels used when that file is missing or invalid, the tool input
5
+ keys, and the hook output text.
6
6
  """
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
- OPUS_MODEL_FAMILY = "opus"
11
- SONNET_MODEL_FAMILY = "sonnet"
12
- FABLE_MODEL_FAMILY = "fable"
13
- HAIKU_MODEL_FAMILY = "haiku"
10
+ from pathlib import Path
14
11
 
15
- ALL_ALLOWED_EFFORTS_BY_FAMILY: dict[str, tuple[str, ...]] = {
16
- OPUS_MODEL_FAMILY: ("medium",),
17
- SONNET_MODEL_FAMILY: ("high",),
18
- FABLE_MODEL_FAMILY: ("low", "medium", "high"),
19
- HAIKU_MODEL_FAMILY: ("low", "medium", "high", "xhigh", "max"),
20
- }
21
-
22
- ALL_ROUTED_EFFORT_BY_FAMILY: dict[str, str] = {
23
- OPUS_MODEL_FAMILY: "medium",
24
- SONNET_MODEL_FAMILY: "high",
25
- FABLE_MODEL_FAMILY: "high",
26
- HAIKU_MODEL_FAMILY: "medium",
12
+ EFFORT_LEVELS_PATH = Path(__file__).resolve().parent / "subagent_effort_levels.json"
13
+ ALLOWED_EFFORTS_KEY = "allowed"
14
+ DEFAULT_EFFORT_KEY = "default"
15
+ EFFORT_LEVELS_FALLBACK_DIAGNOSTIC = (
16
+ "subagent effort route: {path} is missing or invalid ({problem}); using the built-in effort levels.\n"
17
+ )
18
+ ALL_KNOWN_EFFORT_NAMES = ("low", "medium", "high", "xhigh", "max")
19
+
20
+ ALL_BUILT_IN_EFFORT_LEVELS_BY_FAMILY: dict[str, dict[str, object]] = {
21
+ "opus": {ALLOWED_EFFORTS_KEY: ("medium", "high"), DEFAULT_EFFORT_KEY: "medium"},
22
+ "sonnet": {ALLOWED_EFFORTS_KEY: ("high",), DEFAULT_EFFORT_KEY: "high"},
23
+ "fable": {ALLOWED_EFFORTS_KEY: ("low", "medium", "high"), DEFAULT_EFFORT_KEY: "high"},
24
+ "haiku": {
25
+ ALLOWED_EFFORTS_KEY: ("low", "medium", "high", "xhigh", "max"),
26
+ DEFAULT_EFFORT_KEY: "medium",
27
+ },
27
28
  }
28
29
 
29
30
  MODEL_INPUT_KEY = "model"
@@ -0,0 +1,43 @@
1
+ """Tool names, input keys, the subject limit and refusal text for the task_subject_length_gate hook."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "TOOL_NAME_KEY",
7
+ "TOOL_INPUT_KEY",
8
+ "ALL_SUBJECT_TOOL_NAMES",
9
+ "SUBJECT_INPUT_KEY",
10
+ "TODO_WRITE_TOOL_NAME",
11
+ "TODOS_INPUT_KEY",
12
+ "TODO_CONTENT_KEY",
13
+ "PRE_TOOL_USE_EVENT_NAME",
14
+ "DENY_DECISION",
15
+ "MAXIMUM_SUBJECT_CHARACTERS",
16
+ "LONG_SUBJECT_REASON_TEMPLATE",
17
+ "LONG_TODO_ITEM_REASON_TEMPLATE",
18
+ ]
19
+
20
+ TOOL_NAME_KEY = "tool_name"
21
+ TOOL_INPUT_KEY = "tool_input"
22
+ ALL_SUBJECT_TOOL_NAMES = frozenset({"TaskCreate", "TaskUpdate"})
23
+ SUBJECT_INPUT_KEY = "subject"
24
+ TODO_WRITE_TOOL_NAME = "TodoWrite"
25
+ TODOS_INPUT_KEY = "todos"
26
+ TODO_CONTENT_KEY = "content"
27
+ PRE_TOOL_USE_EVENT_NAME = "PreToolUse"
28
+ DENY_DECISION = "deny"
29
+ MAXIMUM_SUBJECT_CHARACTERS = 80
30
+
31
+ _SHORTEN_INSTRUCTION = (
32
+ " The user reads the task list to see where things stand and what is left."
33
+ " Write a short subject: start with who acts (Me, You, or Handed off) and say what is left,"
34
+ ' for example "You: one live try on your PC, then the pull request can merge".'
35
+ " Put status detail, evidence and steps in the description."
36
+ )
37
+ LONG_SUBJECT_REASON_TEMPLATE = (
38
+ "This task subject is {length} characters and the limit is {maximum}." + _SHORTEN_INSTRUCTION
39
+ )
40
+ LONG_TODO_ITEM_REASON_TEMPLATE = (
41
+ 'Task list item {position} ("{content}") is {length} characters and the limit is {maximum}.'
42
+ + _SHORTEN_INSTRUCTION
43
+ )
@@ -0,0 +1,104 @@
1
+ """Tests for the shared hook time budget and the budgets that sit under each registered timeout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ from hooks_constants import nested_project_hooks_constants
13
+ from hooks_constants import turn_review_gate_constants
14
+ from hooks_constants.hook_time_budget import call_timeout, remaining_seconds, time_budget
15
+
16
+ HOOKS_JSON_PATH = Path(__file__).resolve().parent.parent / "hooks.json"
17
+ MINIMUM_MARGIN_SECONDS = 5
18
+ EXIT_MARGIN_SECONDS = 2
19
+
20
+
21
+ def registered_timeout(event_name: str, script_relative_path: str) -> int:
22
+ all_events = json.loads(HOOKS_JSON_PATH.read_text(encoding="utf-8"))["hooks"]
23
+ all_timeouts = [
24
+ each_hook["timeout"]
25
+ for each_group in all_events[event_name]
26
+ for each_hook in each_group["hooks"]
27
+ if each_hook.get("command", "").endswith(f"/hooks/{script_relative_path}")
28
+ ]
29
+ assert len(all_timeouts) == 1, (event_name, script_relative_path, all_timeouts)
30
+ return all_timeouts[0]
31
+
32
+
33
+ def test_should_return_the_cap_outside_a_budget() -> None:
34
+ assert remaining_seconds() == math.inf
35
+ assert call_timeout(10) == 10
36
+
37
+
38
+ def test_should_shrink_the_cap_to_the_time_left_inside_a_budget() -> None:
39
+ with time_budget(0.5):
40
+ assert call_timeout(10) <= 0.5
41
+ assert call_timeout(0.1) == 0.1
42
+
43
+
44
+ def test_should_return_none_once_the_budget_is_spent() -> None:
45
+ with time_budget(0.05):
46
+ time.sleep(0.06)
47
+ assert call_timeout(10) is None
48
+
49
+
50
+ def test_should_keep_an_inner_budget_inside_the_outer_one() -> None:
51
+ with time_budget(0.5), time_budget(100):
52
+ assert remaining_seconds() <= 0.5
53
+
54
+
55
+ def test_should_reset_the_budget_when_the_block_exits() -> None:
56
+ with pytest.raises(RuntimeError), time_budget(0.01):
57
+ raise RuntimeError("leave the block")
58
+ assert remaining_seconds() == math.inf
59
+
60
+
61
+ @pytest.mark.parametrize(
62
+ ("event_name", "script_relative_path", "budget_seconds"),
63
+ [
64
+ (
65
+ "Stop",
66
+ "blocking/turn_review_gate.py",
67
+ turn_review_gate_constants.STOP_RUN_BUDGET_SECONDS,
68
+ ),
69
+ (
70
+ "UserPromptSubmit",
71
+ "blocking/turn_review_gate.py",
72
+ turn_review_gate_constants.PROMPT_RUN_BUDGET_SECONDS,
73
+ ),
74
+ ],
75
+ )
76
+ def test_should_end_each_budget_before_the_host_timeout(
77
+ event_name: str, script_relative_path: str, budget_seconds: float
78
+ ) -> None:
79
+ assert budget_seconds + MINIMUM_MARGIN_SECONDS <= registered_timeout(
80
+ event_name, script_relative_path
81
+ )
82
+
83
+
84
+ @pytest.mark.parametrize(
85
+ ("event_name", "budget_seconds"),
86
+ sorted(nested_project_hooks_constants.ALL_RUN_BUDGET_SECONDS_BY_EVENT.items()),
87
+ )
88
+ def test_should_let_nested_children_run_until_just_before_the_host_timeout(
89
+ event_name: str, budget_seconds: float
90
+ ) -> None:
91
+ host_timeout = registered_timeout(event_name, "lifecycle/nested_project_hooks.py")
92
+ assert host_timeout - EXIT_MARGIN_SECONDS <= budget_seconds < host_timeout
93
+
94
+
95
+ def test_should_give_the_nested_hooks_a_budget_on_every_event_it_is_registered_on() -> None:
96
+ all_events = json.loads(HOOKS_JSON_PATH.read_text(encoding="utf-8"))["hooks"]
97
+ all_registered_events = {
98
+ each_event
99
+ for each_event, all_groups in all_events.items()
100
+ for each_group in all_groups
101
+ for each_hook in each_group["hooks"]
102
+ if each_hook.get("command", "").endswith("/hooks/lifecycle/nested_project_hooks.py")
103
+ }
104
+ assert set(nested_project_hooks_constants.ALL_RUN_BUDGET_SECONDS_BY_EVENT) == all_registered_events
@@ -20,6 +20,7 @@ if _HOOKS_DIR not in sys.path:
20
20
 
21
21
  from hooks_constants.hosted_hook_runner import ( # noqa: E402
22
22
  HostedHookRun,
23
+ host_exit_code,
23
24
  run_dispatcher_main,
24
25
  run_hook_capturing_output,
25
26
  )
@@ -153,3 +154,14 @@ def test_run_dispatcher_main_skips_dispatch_when_tool_name_is_missing(
153
154
 
154
155
  assert int(raised_exit.value.code or 0) == 0
155
156
  assert all_calls == []
157
+
158
+
159
+ def test_should_record_the_exit_code_a_hook_passes_to_system_exit(tmp_path: Path) -> None:
160
+ probe_path = _write_probe(tmp_path, "import sys\nsys.exit(2)\n")
161
+ assert run_hook_capturing_output(probe_path, "{}").exit_code == 2
162
+
163
+
164
+ def test_should_hand_the_host_exit_two_only_when_a_hosted_hook_exited_two() -> None:
165
+ assert host_exit_code([HostedHookRun("", False, 0), HostedHookRun("", False, 2)]) == 2
166
+ assert host_exit_code([HostedHookRun("", False, 0), HostedHookRun("", False, 1)]) == 0
167
+ assert host_exit_code([]) == 0
@@ -45,3 +45,19 @@ def test_prints_nothing_and_exits_zero_when_the_decision_raises(
45
45
  _feed_stdin(monkeypatch, json.dumps({"tool_name": "Agent"}))
46
46
  assert run_context_hook(_raise) == 0
47
47
  assert capsys.readouterr().out == ""
48
+
49
+
50
+ def test_should_let_the_call_through_and_write_one_line_naming_the_crash(
51
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
52
+ ) -> None:
53
+ def _crash(payload: dict[str, object]) -> dict[str, object] | None:
54
+ raise ValueError("first line\nsecond line")
55
+
56
+ _feed_stdin(monkeypatch, json.dumps({"tool_name": "Agent"}))
57
+ assert run_context_hook(_crash) == 0
58
+ captured = capsys.readouterr()
59
+ assert captured.out == ""
60
+ all_stderr_lines = captured.err.splitlines()
61
+ assert len(all_stderr_lines) == 1
62
+ assert "ValueError" in all_stderr_lines[0]
63
+ assert "first line second line" in all_stderr_lines[0]
@@ -95,3 +95,9 @@ def test_print_decision_from_stdin_writes_nothing_on_allow() -> None:
95
95
  with patch("sys.stdin", io.StringIO('{"tool_name": "Bash"}')), patch("sys.stdout", output):
96
96
  assert pre_tool_use_stdin.print_decision_from_stdin(lambda payload: None) == 0
97
97
  assert output.getvalue() == ""
98
+
99
+
100
+ def test_read_returns_none_for_an_integer_past_the_digit_limit() -> None:
101
+ oversized_payload = '{"tool_name": "Bash", "tool_use_id": ' + "7" * 6000 + "}"
102
+ with patch("sys.stdin", io.StringIO(oversized_payload)):
103
+ assert read_hook_input_dictionary_from_stdin() is None
@@ -0,0 +1,40 @@
1
+ """Tests for the shared Stop hook hold signal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ import pytest
8
+
9
+ from hooks_constants.stop_hook_hold import hold_stop, stop_hold_output
10
+
11
+ HOLD_REASON = "The task list is stale. Update it, then end the turn."
12
+
13
+
14
+ def test_should_exit_two_with_the_reason_on_both_channels_for_claude_code(
15
+ capsys: pytest.CaptureFixture[str],
16
+ ) -> None:
17
+ exit_code = hold_stop({"hook_event_name": "Stop", "stop_hook_active": False}, HOLD_REASON)
18
+ captured = capsys.readouterr()
19
+ assert exit_code == 2
20
+ assert json.loads(captured.out) == {"decision": "block", "reason": HOLD_REASON}
21
+ assert captured.err == HOLD_REASON
22
+
23
+
24
+ def test_should_exit_zero_with_a_followup_message_for_a_cursor_payload(
25
+ capsys: pytest.CaptureFixture[str],
26
+ ) -> None:
27
+ exit_code = hold_stop({"hook_event_name": "stop", "conversation_id": "c-1"}, HOLD_REASON)
28
+ captured = capsys.readouterr()
29
+ assert exit_code == 0
30
+ assert json.loads(captured.out) == {
31
+ "decision": "block",
32
+ "reason": HOLD_REASON,
33
+ "followup_message": HOLD_REASON,
34
+ }
35
+ assert captured.err == ""
36
+
37
+
38
+ def test_should_add_a_followup_message_only_for_a_cursor_payload() -> None:
39
+ assert stop_hold_output({}, "why") == {"decision": "block", "reason": "why"}
40
+ assert stop_hold_output({"conversation_id": "c-1"}, "why")["followup_message"] == "why"
@@ -1,8 +1,7 @@
1
1
  """Constants for the thread spawn pace PreToolUse hook.
2
2
 
3
3
  Groups: the usage-pace script it runs, the reshape values for an over-pace
4
- spawn, and the hook output keys and messages. Opus runs at medium only,
5
- per the Subagent model and effort rule.
4
+ spawn, and the hook output keys and messages.
6
5
  """
7
6
 
8
7
  from __future__ import annotations