claude-dev-env 8.116.4 → 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 (101) 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/hooks/validators/ruff_integration.py +46 -4
  88. package/hooks/validators/test_ruff_integration.py +67 -5
  89. package/package.json +1 -1
  90. package/rules/question-presentation.md +4 -4
  91. package/rules/subagent-model-effort.md +1 -1
  92. package/scripts/claude_account_worker.py +4 -3
  93. package/scripts/policy_lint/adapter_configuration.py +12 -11
  94. package/scripts/policy_lint/config/constants.py +2 -2
  95. package/scripts/test_claude_account_worker.py +1 -0
  96. package/scripts/tests/test_adapter_configuration.py +10 -2
  97. package/hooks/blocking/owned_pr_merge_stop_gate.py +0 -185
  98. package/hooks/blocking/session_title_turn_gate.py +0 -417
  99. package/hooks/blocking/test_owned_pr_merge_stop_gate.py +0 -254
  100. package/hooks/blocking/test_session_title_turn_gate.py +0 -396
  101. package/hooks/hooks_constants/owned_pr_merge_stop_gate_constants.py +0 -40
@@ -1,185 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Stop hook that keeps a session working until its owned pull requests merge.
3
-
4
- The owned pull request review-loop hook records each pull request the agent
5
- opens on an owned repository outside the preset list. At the end of a turn
6
- this gate asks GitHub for the state and head of each recorded pull request::
7
-
8
- allow: every recorded pull request reads closed (merged or closed)
9
- allow: the reply has "Blocked: acme/widgets#42 - the owner must approve"
10
- allow: acme/widgets#42 is open on the head this gate already blocked on
11
- block: acme/widgets#42 reads open on a new head and the reply names no blocker
12
-
13
- A block sends those pull requests back as the reason, so the model keeps
14
- working the loop, and records each head it blocked on. A later stop on the
15
- same head passes, and a push to a new head blocks once more. An open pull
16
- request whose head GitHub does not report blocks on every stop. Claude Code
17
- ends the turn after eight blocks in a row, and Codex turns the reason into a
18
- continuation prompt. A state lookup that fails,
19
- such as a missing ``gh`` or no network, counts as closed, so the gate never
20
- holds a turn on a fact it could not read. The failure goes to stderr, where
21
- the host shows it in the hook log.
22
- """
23
-
24
- from __future__ import annotations
25
-
26
- import json
27
- import re
28
- import subprocess
29
- import sys
30
- from pathlib import Path
31
-
32
- hooks_root_directory = str(Path(__file__).resolve().parent.parent)
33
- if hooks_root_directory not in sys.path:
34
- sys.path.insert(0, hooks_root_directory)
35
-
36
- from hooks_constants.hook_block_logger import log_hook_block
37
- from hooks_constants.owned_pr_merge_stop_gate_constants import (
38
- ALLOW_EXIT_CODE,
39
- BLOCK_DECISION,
40
- BLOCK_REASON_PREFIX,
41
- BLOCK_REASON_SUFFIX,
42
- BLOCKED_LINE_PATTERN,
43
- BLOCKED_TEXT_GROUP_INDEX,
44
- BOLD_MARKER,
45
- DECISION_KEY,
46
- GH_API_SUBCOMMAND,
47
- GH_JQ_OPTION,
48
- GH_PROGRAM_NAME,
49
- HEAD_FIELD,
50
- HOOK_EVENT_NAME,
51
- LAST_ASSISTANT_MESSAGE_KEY,
52
- LOOKUP_FAILURE_TEMPLATE,
53
- NAME_END_PATTERN,
54
- NAME_START_PATTERN,
55
- OPEN_PULL_REQUEST_STATE,
56
- PULL_REQUEST_ENDPOINT_TEMPLATE,
57
- PULL_REQUEST_LINE_TEMPLATE,
58
- PULL_REQUEST_REFERENCE_TEMPLATE,
59
- PULL_REQUEST_STATE_QUERY,
60
- REASON_KEY,
61
- SESSION_ID_KEY,
62
- STATE_AND_HEAD_SEPARATOR,
63
- STATE_QUERY_TIMEOUT_SECONDS,
64
- URL_FIELD,
65
- )
66
- from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
67
- from owned_pr_session_record import (
68
- all_blocked_heads,
69
- all_recorded_pull_requests,
70
- record_blocked_heads,
71
- )
72
-
73
-
74
- def open_head(all_pull_request_fields: dict[str, str]) -> str | None:
75
- """Return the head sha when GitHub reports the pull request as open, else None.
76
-
77
- An open pull request whose head GitHub did not report returns an empty
78
- string, which no earlier block can match.
79
-
80
- Args:
81
- all_pull_request_fields: The owner, repository, number, and url fields.
82
- """
83
- endpoint = PULL_REQUEST_ENDPOINT_TEMPLATE.format(**all_pull_request_fields)
84
- try:
85
- completed = subprocess.run(
86
- [GH_PROGRAM_NAME, GH_API_SUBCOMMAND, endpoint, GH_JQ_OPTION, PULL_REQUEST_STATE_QUERY],
87
- capture_output=True,
88
- text=True,
89
- timeout=STATE_QUERY_TIMEOUT_SECONDS,
90
- check=False,
91
- )
92
- except (OSError, subprocess.TimeoutExpired) as lookup_error:
93
- sys.stderr.write(LOOKUP_FAILURE_TEMPLATE.format(endpoint=endpoint, detail=lookup_error))
94
- return None
95
- if completed.returncode != 0:
96
- sys.stderr.write(LOOKUP_FAILURE_TEMPLATE.format(endpoint=endpoint, detail=completed.stderr.strip()))
97
- return None
98
- state, _, head = completed.stdout.strip().partition(STATE_AND_HEAD_SEPARATOR)
99
- return head.strip() if state == OPEN_PULL_REQUEST_STATE else None
100
-
101
-
102
- def is_reported_blocked(all_pull_request_fields: dict[str, str], reply_text: str) -> bool:
103
- """Return True when a Blocked: line of the reply names the pull request.
104
-
105
- The line names it by ``owner/repository#number`` or by its url. Bold
106
- markers such as ``**Blocked:**`` are ignored.
107
-
108
- Args:
109
- all_pull_request_fields: The owner, repository, number, and url fields.
110
- reply_text: The closing reply of the turn.
111
- """
112
- all_names = (
113
- PULL_REQUEST_REFERENCE_TEMPLATE.format(**all_pull_request_fields).lower(),
114
- all_pull_request_fields["url"].lower(),
115
- )
116
- all_blocked_texts = (
117
- each_match.group(BLOCKED_TEXT_GROUP_INDEX).lower()
118
- for each_match in map(BLOCKED_LINE_PATTERN.match, reply_text.replace(BOLD_MARKER, "").splitlines())
119
- if each_match
120
- )
121
- all_name_patterns = [NAME_START_PATTERN + re.escape(each_name) + NAME_END_PATTERN for each_name in all_names]
122
- return any(
123
- re.search(each_pattern, each_text)
124
- for each_text in all_blocked_texts
125
- for each_pattern in all_name_patterns
126
- )
127
-
128
-
129
- def unfinished_pull_requests(all_hook_input_fields: dict[str, object]) -> list[dict[str, str]]:
130
- """Return the recorded pull requests that are open, not reported blocked, and on a new head.
131
-
132
- Each entry carries its head sha under ``head``. A pull request the gate
133
- already blocked on at its current head is left out.
134
-
135
- Args:
136
- all_hook_input_fields: The Stop hook payload.
137
- """
138
- reply_value = all_hook_input_fields.get(LAST_ASSISTANT_MESSAGE_KEY)
139
- reply_text = reply_value if isinstance(reply_value, str) else ""
140
- session_id = all_hook_input_fields.get(SESSION_ID_KEY)
141
- blocked_heads_by_url = all_blocked_heads(session_id)
142
- all_unfinished = []
143
- for each_pull_request in all_recorded_pull_requests(session_id):
144
- if is_reported_blocked(each_pull_request, reply_text):
145
- continue
146
- head = open_head(each_pull_request)
147
- if head is None or (head and blocked_heads_by_url.get(each_pull_request[URL_FIELD]) == head):
148
- continue
149
- all_unfinished.append({**each_pull_request, HEAD_FIELD: head})
150
- return all_unfinished
151
-
152
-
153
- def block_reason_for(all_open_pull_requests: list[dict[str, str]]) -> str:
154
- """Return the block reason that lists each open pull request.
155
-
156
- Args:
157
- all_open_pull_requests: The pull requests that hold the turn.
158
- """
159
- all_lines = (PULL_REQUEST_LINE_TEMPLATE.format(**each) for each in all_open_pull_requests)
160
- return BLOCK_REASON_PREFIX + "".join(all_lines) + BLOCK_REASON_SUFFIX
161
-
162
-
163
- def main() -> int:
164
- hook_input = read_hook_input_dictionary_from_stdin()
165
- if hook_input is None:
166
- return ALLOW_EXIT_CODE
167
- all_open_pull_requests = unfinished_pull_requests(hook_input)
168
- if not all_open_pull_requests:
169
- return ALLOW_EXIT_CODE
170
- record_blocked_heads(
171
- hook_input.get(SESSION_ID_KEY),
172
- {
173
- each_pull_request[URL_FIELD]: each_pull_request[HEAD_FIELD]
174
- for each_pull_request in all_open_pull_requests
175
- if each_pull_request[HEAD_FIELD]
176
- },
177
- )
178
- block_reason = block_reason_for(all_open_pull_requests)
179
- log_hook_block(Path(__file__).name, HOOK_EVENT_NAME, block_reason)
180
- sys.stdout.write(json.dumps({DECISION_KEY: BLOCK_DECISION, REASON_KEY: block_reason}))
181
- return ALLOW_EXIT_CODE
182
-
183
-
184
- if __name__ == "__main__":
185
- sys.exit(main())
@@ -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())