claude-dev-env 8.116.5 → 8.117.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/bin/ever-registered-hooks.mjs +2 -0
  2. package/bin/ever-registered-hooks.test.mjs +4 -0
  3. package/bin/install-constants.mjs +3 -1
  4. package/bin/install.cursor-rules.test.mjs +64 -2
  5. package/bin/install.mjs +15 -2
  6. package/bin/install.prune.test.mjs +92 -0
  7. package/bin/install.test.mjs +1 -0
  8. package/docs/model-choice/escalation.md +3 -3
  9. package/docs/model-choice/subagents-and-fan-out.md +2 -2
  10. package/docs/model-choice/which-model.md +1 -1
  11. package/docs/references/working-style.md +1 -0
  12. package/docs/rule-guides/question-presentation.md +6 -0
  13. package/docs/rule-guides/session-title.md +8 -9
  14. package/docs/rule-guides/subagent-model-effort.md +13 -13
  15. package/hooks/advisory/owned_pr_review_loop.py +2 -3
  16. package/hooks/blocking/bash_post_call_dispatcher.py +17 -9
  17. package/hooks/blocking/bash_pre_tool_use_dispatcher.py +12 -8
  18. package/hooks/blocking/final_reply_gate.py +5 -9
  19. package/hooks/blocking/open_tasks_stop_gate.py +9 -20
  20. package/hooks/blocking/open_tasks_transcript.py +8 -3
  21. package/hooks/blocking/pii_prevention_blocker_parts/repository_exemption.py +7 -2
  22. package/hooks/blocking/question_brief_gate.py +382 -0
  23. package/hooks/blocking/step_note_gate.py +5 -2
  24. package/hooks/blocking/task_subject_length_gate.py +111 -0
  25. package/hooks/blocking/test_bash_post_call_dispatcher.py +36 -1
  26. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +57 -0
  27. package/hooks/blocking/test_final_reply_gate.py +26 -2
  28. package/hooks/blocking/test_open_tasks_stop_gate.py +21 -11
  29. package/hooks/blocking/test_question_brief_gate.py +916 -0
  30. package/hooks/blocking/test_step_note_gate.py +26 -0
  31. package/hooks/blocking/test_task_subject_length_gate.py +221 -0
  32. package/hooks/blocking/test_turn_review_child.py +166 -0
  33. package/hooks/blocking/test_turn_review_claim.py +194 -0
  34. package/hooks/blocking/test_turn_review_findings.py +124 -1
  35. package/hooks/blocking/test_turn_review_gate.py +1312 -10
  36. package/hooks/blocking/test_turn_review_repositories.py +65 -0
  37. package/hooks/blocking/test_turn_review_snapshot.py +8 -0
  38. package/hooks/blocking/test_turn_review_state.py +132 -0
  39. package/hooks/blocking/test_turn_review_transcript.py +125 -0
  40. package/hooks/blocking/tests/test_repository_exemption.py +11 -0
  41. package/hooks/blocking/turn_review_child.py +145 -0
  42. package/hooks/blocking/turn_review_claim.py +306 -0
  43. package/hooks/blocking/turn_review_findings.py +173 -13
  44. package/hooks/blocking/turn_review_gate.py +259 -262
  45. package/hooks/blocking/turn_review_repositories.py +58 -0
  46. package/hooks/blocking/turn_review_snapshot.py +5 -1
  47. package/hooks/blocking/turn_review_state.py +260 -0
  48. package/hooks/blocking/turn_review_transcript.py +158 -0
  49. package/hooks/features/bash-dispatchers.md +1 -3
  50. package/hooks/features/conduct-gates.md +19 -9
  51. package/hooks/features/lifecycle-cleanup.md +1 -1
  52. package/hooks/features/spawn-routing.md +1 -1
  53. package/hooks/hooks.json +24 -11
  54. package/hooks/hooks_constants/final_reply_gate_constants.py +0 -3
  55. package/hooks/hooks_constants/hook_time_budget.py +61 -0
  56. package/hooks/hooks_constants/hosted_hook_runner.py +51 -21
  57. package/hooks/hooks_constants/hosted_hook_runner_constants.py +3 -0
  58. package/hooks/hooks_constants/nested_project_hooks_constants.py +8 -0
  59. package/hooks/hooks_constants/once_per_session_constants.py +1 -0
  60. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +0 -4
  61. package/hooks/hooks_constants/owned_pr_review_loop_constants.py +0 -4
  62. package/hooks/hooks_constants/pre_tool_use_context_runner.py +23 -3
  63. package/hooks/hooks_constants/pre_tool_use_context_runner_constants.py +5 -0
  64. package/hooks/hooks_constants/pre_tool_use_stdin.py +1 -1
  65. package/hooks/hooks_constants/question_brief_gate_constants.py +66 -0
  66. package/hooks/hooks_constants/session_title_constants.py +8 -29
  67. package/hooks/hooks_constants/stop_hook_hold.py +54 -0
  68. package/hooks/hooks_constants/stop_hook_hold_constants.py +9 -0
  69. package/hooks/hooks_constants/subagent_effort_levels.json +6 -0
  70. package/hooks/hooks_constants/subagent_effort_route_constants.py +20 -19
  71. package/hooks/hooks_constants/task_subject_length_gate_constants.py +43 -0
  72. package/hooks/hooks_constants/test_hook_time_budget.py +104 -0
  73. package/hooks/hooks_constants/test_hosted_hook_runner.py +12 -0
  74. package/hooks/hooks_constants/test_pre_tool_use_context_runner.py +16 -0
  75. package/hooks/hooks_constants/test_pre_tool_use_stdin.py +6 -0
  76. package/hooks/hooks_constants/test_stop_hook_hold.py +40 -0
  77. package/hooks/hooks_constants/thread_spawn_pace_hook_constants.py +1 -2
  78. package/hooks/hooks_constants/turn_review_gate_constants.py +246 -12
  79. package/hooks/lifecycle/nested_project_hooks.py +34 -4
  80. package/hooks/lifecycle/test_nested_project_hooks.py +52 -0
  81. package/hooks/once_per_session.py +33 -4
  82. package/hooks/open_task_asks.py +1 -1
  83. package/hooks/owned_pr_session_record.py +1 -76
  84. package/hooks/routing/subagent_effort_route.py +107 -13
  85. package/hooks/routing/subagent_effort_route_hook.py +9 -8
  86. package/hooks/routing/test_subagent_effort_route.py +201 -14
  87. package/hooks/routing/test_subagent_effort_route_hook.py +56 -0
  88. package/hooks/routing/test_thread_spawn_pace_hook.py +32 -0
  89. package/hooks/routing/thread_spawn_pace_hook.py +3 -3
  90. package/hooks/session/background_silence_prompt.py +1 -1
  91. package/hooks/session/test_background_silence_prompt.py +8 -0
  92. package/hooks/session/test_tracking_nudge.py +125 -2
  93. package/hooks/session/tracking_nudge.py +28 -18
  94. package/hooks/session_title_transcript.py +216 -0
  95. package/hooks/test_once_per_session.py +10 -0
  96. package/hooks/test_owned_pr_session_record.py +0 -26
  97. package/hooks/test_session_title_transcript.py +142 -0
  98. package/hooks/validation/post_tool_use_dispatcher.py +38 -21
  99. package/hooks/validation/test_post_tool_use_dispatcher.py +43 -0
  100. package/package.json +1 -1
  101. package/rules/question-presentation.md +4 -4
  102. package/rules/subagent-model-effort.md +1 -1
  103. package/scripts/account_broker_support.py +24 -5
  104. package/scripts/claude_account_worker.py +4 -3
  105. package/scripts/dev_env_scripts_constants/account_broker_constants.py +1 -0
  106. package/scripts/policy_lint/adapter_configuration.py +12 -11
  107. package/scripts/policy_lint/config/approved_test_pairs.py +27 -0
  108. package/scripts/policy_lint/config/constants.py +2 -2
  109. package/scripts/test_account_broker_support.py +43 -1
  110. package/scripts/test_claude_account_worker.py +1 -0
  111. package/scripts/tests/test_adapter_configuration.py +10 -2
  112. package/scripts/tests/test_policy_lint_rules_pairing.py +24 -0
  113. package/hooks/blocking/owned_pr_merge_stop_gate.py +0 -185
  114. package/hooks/blocking/session_title_turn_gate.py +0 -417
  115. package/hooks/blocking/test_owned_pr_merge_stop_gate.py +0 -254
  116. package/hooks/blocking/test_session_title_turn_gate.py +0 -396
  117. package/hooks/hooks_constants/owned_pr_merge_stop_gate_constants.py +0 -40
@@ -0,0 +1,58 @@
1
+ """Find the checkouts that take part in the turn review gate.
2
+
3
+ A repository takes part when it is the session's project folder or a folder
4
+ directly inside it, and its GitHub origin ``owner/repo`` slug is listed in
5
+ ``CLAUDE_TURN_REVIEW_REPOSITORIES``::
6
+
7
+ project folder /work, listed slugs "Owner/App, owner/lib"
8
+ /work/app origin owner/app -> takes part
9
+ /work/docs origin owner/docs -> left out
10
+ /work/notes no .git entry -> left out
11
+
12
+ The listed slugs are compared without regard to letter case. A folder that
13
+ cannot be read is left out.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from pathlib import Path
20
+
21
+ from hooks_constants.turn_review_gate_constants import (
22
+ GIT_DIRECTORY_NAME,
23
+ PROJECT_DIRECTORY_ENVIRONMENT_VARIABLE,
24
+ REPOSITORIES_ENVIRONMENT_VARIABLE,
25
+ REPOSITORY_SEPARATOR,
26
+ )
27
+ from pii_prevention_blocker_parts.repository_exemption import repository_origin_slug
28
+
29
+
30
+ def _opted_in_repository_slugs() -> frozenset[str]:
31
+ listed = os.environ.get(REPOSITORIES_ENVIRONMENT_VARIABLE, "")
32
+ return frozenset(
33
+ each.strip().casefold() for each in listed.split(REPOSITORY_SEPARATOR) if each.strip()
34
+ )
35
+
36
+
37
+ def _opted_in_repository_roots(all_slugs: frozenset[str]) -> list[Path]:
38
+ project_directory = os.environ.get(PROJECT_DIRECTORY_ENVIRONMENT_VARIABLE, "")
39
+ if not project_directory or not Path(project_directory).is_dir():
40
+ return []
41
+ project_path = Path(project_directory).resolve()
42
+ all_candidates = [project_path, *sorted(_child_entries(project_path))]
43
+ return [each for each in all_candidates if _is_opted_in_checkout(each, all_slugs)]
44
+
45
+
46
+ def _child_entries(project_path: Path) -> list[Path]:
47
+ try:
48
+ return list(project_path.iterdir())
49
+ except OSError:
50
+ return []
51
+
52
+
53
+ def _is_opted_in_checkout(folder: Path, all_slugs: frozenset[str]) -> bool:
54
+ try:
55
+ is_checkout = folder.is_dir() and (folder / GIT_DIRECTORY_NAME).exists()
56
+ except OSError:
57
+ return False
58
+ return is_checkout and repository_origin_slug(folder) in all_slugs
@@ -20,6 +20,7 @@ import subprocess
20
20
  import tempfile
21
21
  from pathlib import Path
22
22
 
23
+ from hooks_constants.hook_time_budget import call_timeout
23
24
  from hooks_constants.subprocess_window import hidden_window_creation_flags
24
25
  from hooks_constants.turn_review_gate_constants import (
25
26
  ALL_CHANGED_PATH_ARGUMENTS,
@@ -40,6 +41,9 @@ def _git_output(
40
41
  all_arguments: list[str],
41
42
  all_environment_variables: dict[str, str] | None,
42
43
  ) -> str | None:
44
+ timeout_seconds = call_timeout(GIT_COMMAND_TIMEOUT_SECONDS)
45
+ if timeout_seconds is None:
46
+ return None
43
47
  try:
44
48
  completed_process = subprocess.run(
45
49
  ["git", *all_arguments],
@@ -48,7 +52,7 @@ def _git_output(
48
52
  text=True,
49
53
  encoding=GIT_OUTPUT_ENCODING,
50
54
  errors=GIT_OUTPUT_ERROR_HANDLING,
51
- timeout=GIT_COMMAND_TIMEOUT_SECONDS,
55
+ timeout=timeout_seconds,
52
56
  cwd=str(repository_root),
53
57
  env=all_environment_variables,
54
58
  creationflags=hidden_window_creation_flags(),
@@ -0,0 +1,260 @@
1
+ """Keep the session's review state, its file lock and the log for the turn review gate.
2
+
3
+ Each session has one state file in the temp folder. It holds the snapshot each
4
+ checkout was last reviewed up to, the hold count, and every finding by its id::
5
+
6
+ turn-review-<session>.json
7
+ {"baselines": {"/work/app": "<snapshot B>"}, "blocks_in_a_row": 1,
8
+ "findings": {"TR-1": {"text": "src/service.py:3 - ...", "status": "open"}}}
9
+
10
+ A saved entry in another form is left out on load, such as a baseline that is
11
+ not a commit name or a finding with an unknown status. A state file that
12
+ cannot be read gives an empty state. A save that fails writes one log line.
13
+
14
+ The lock functions take and release a lock on an open file, with ``msvcrt`` on
15
+ Windows and ``fcntl`` on other systems. ``_log`` adds one dated line to
16
+ ``~/.claude/logs/turn-review.log``. A line that cannot be written is dropped.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import datetime
22
+ import json
23
+ import os
24
+ import re
25
+ import sys
26
+ import tempfile
27
+ from dataclasses import dataclass, field
28
+ from pathlib import Path
29
+
30
+ if sys.platform == "win32":
31
+ import msvcrt
32
+ else:
33
+ import fcntl
34
+
35
+ from atomic_file_writer import write_text_atomically
36
+ from hooks_constants.atomic_file_writer_constants import ATOMIC_WRITE_TEMPORARY_SUFFIX
37
+ from hooks_constants.session_file_id import session_file_id
38
+ from hooks_constants.turn_review_gate_constants import (
39
+ ALL_FINDING_STATUSES,
40
+ ALL_LOG_PATH_PARTS,
41
+ BASELINE_COMMIT_PATTERN,
42
+ FINDING_BASE_KEY,
43
+ FINDING_ID_PATTERN,
44
+ FINDING_ID_TEMPLATE,
45
+ FINDING_JUDGE_REASON_KEY,
46
+ FINDING_REPOSITORY_KEY,
47
+ FINDING_STATUS_KEY,
48
+ FINDING_STATUS_OPEN,
49
+ FINDING_TEXT_KEY,
50
+ FINDING_TURN_KEY,
51
+ LOG_LINE_TEMPLATE,
52
+ LOG_TEXT_ENCODING,
53
+ LOG_UNENCODABLE_HANDLER,
54
+ STATE_BASELINES_KEY,
55
+ STATE_BLOCKS_KEY,
56
+ STATE_FILE_TEMPLATE,
57
+ STATE_FINDINGS_KEY,
58
+ STATE_LAST_WAKE_KEY,
59
+ STATE_LOCK_BYTE_COUNT,
60
+ STATE_OPEN_TURN_PROMPT_KEY,
61
+ STATE_SAVE_FAILURE_DIAGNOSTIC_TEMPLATE,
62
+ STATE_TEMPORARY_PREFIX,
63
+ STATE_TEXT_ENCODING,
64
+ STATE_TURN_OPEN_KEY,
65
+ )
66
+
67
+
68
+ if sys.platform == "win32":
69
+
70
+ def _try_file_lock(file_descriptor: int) -> None:
71
+ os.lseek(file_descriptor, 0, os.SEEK_SET)
72
+ msvcrt.locking(file_descriptor, msvcrt.LK_NBLCK, STATE_LOCK_BYTE_COUNT)
73
+
74
+ def _release_file_lock(file_descriptor: int) -> None:
75
+ os.lseek(file_descriptor, 0, os.SEEK_SET)
76
+ msvcrt.locking(file_descriptor, msvcrt.LK_UNLCK, STATE_LOCK_BYTE_COUNT)
77
+
78
+ else:
79
+
80
+ def _try_file_lock(file_descriptor: int) -> None:
81
+ fcntl.flock(file_descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
82
+
83
+ def _release_file_lock(file_descriptor: int) -> None:
84
+ fcntl.flock(file_descriptor, fcntl.LOCK_UN)
85
+
86
+
87
+ def _log(diagnostic_text: str) -> None:
88
+ timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
89
+ try:
90
+ log_path = Path.home().joinpath(*ALL_LOG_PATH_PARTS)
91
+ log_path.parent.mkdir(parents=True, exist_ok=True)
92
+ with log_path.open(
93
+ "a", encoding=LOG_TEXT_ENCODING, errors=LOG_UNENCODABLE_HANDLER
94
+ ) as log_file:
95
+ log_file.write(LOG_LINE_TEMPLATE.format(timestamp=timestamp, text=diagnostic_text))
96
+ except (OSError, RuntimeError):
97
+ return
98
+
99
+
100
+ def _is_lock_taken(file_descriptor: int) -> bool:
101
+ try:
102
+ _try_file_lock(file_descriptor)
103
+ except OSError:
104
+ return False
105
+ return True
106
+
107
+
108
+ def _release_and_close(file_descriptor: int, is_locked: bool) -> None:
109
+ try:
110
+ if is_locked:
111
+ _release_file_lock(file_descriptor)
112
+ finally:
113
+ os.close(file_descriptor)
114
+
115
+
116
+ def _state_path(session_id: object) -> Path:
117
+ return Path(tempfile.gettempdir()) / STATE_FILE_TEMPLATE.format(
118
+ session_id=session_file_id(session_id)
119
+ )
120
+
121
+
122
+ @dataclass
123
+ class _Finding:
124
+ text: str
125
+ repository: str
126
+ base_commit: str
127
+ turn_commit: str
128
+ status: str = FINDING_STATUS_OPEN
129
+ judge_reason: str | None = None
130
+
131
+
132
+ @dataclass
133
+ class _ReviewState:
134
+ all_baselines: dict[str, str] = field(default_factory=dict)
135
+ blocks_in_a_row: int = 0
136
+ is_turn_open: bool = False
137
+ last_wake_at: float | None = None
138
+ open_turn_prompt_at: float | None = None
139
+ all_findings: dict[str, _Finding] = field(default_factory=dict)
140
+
141
+
142
+ def _saved_time(raw_value: object) -> float | None:
143
+ if isinstance(raw_value, bool) or not isinstance(raw_value, (int, float)):
144
+ return None
145
+ return float(raw_value)
146
+
147
+
148
+ def _is_commit_name(raw_value: object) -> bool:
149
+ return isinstance(raw_value, str) and re.fullmatch(BASELINE_COMMIT_PATTERN, raw_value) is not None
150
+
151
+
152
+ def _saved_finding(raw_entry: object) -> _Finding | None:
153
+ if not isinstance(raw_entry, dict):
154
+ return None
155
+ text = raw_entry.get(FINDING_TEXT_KEY)
156
+ repository = raw_entry.get(FINDING_REPOSITORY_KEY)
157
+ base_commit = raw_entry.get(FINDING_BASE_KEY)
158
+ turn_commit = raw_entry.get(FINDING_TURN_KEY)
159
+ status = raw_entry.get(FINDING_STATUS_KEY)
160
+ judge_reason = raw_entry.get(FINDING_JUDGE_REASON_KEY)
161
+ if not (
162
+ isinstance(text, str)
163
+ and isinstance(repository, str)
164
+ and _is_commit_name(base_commit)
165
+ and _is_commit_name(turn_commit)
166
+ and status in ALL_FINDING_STATUSES
167
+ ):
168
+ return None
169
+ return _Finding(
170
+ text,
171
+ repository,
172
+ str(base_commit),
173
+ str(turn_commit),
174
+ str(status),
175
+ judge_reason if isinstance(judge_reason, str) else None,
176
+ )
177
+
178
+
179
+ def _saved_findings(raw_findings: object) -> dict[str, _Finding]:
180
+ if not isinstance(raw_findings, dict):
181
+ return {}
182
+ all_findings: dict[str, _Finding] = {}
183
+ for each_id, each_entry in raw_findings.items():
184
+ saved_finding = _saved_finding(each_entry)
185
+ if isinstance(each_id, str) and re.fullmatch(FINDING_ID_PATTERN, each_id) and saved_finding:
186
+ all_findings[each_id] = saved_finding
187
+ return all_findings
188
+
189
+
190
+ def _finding_number(finding_id: str) -> int:
191
+ id_match = re.fullmatch(FINDING_ID_PATTERN, finding_id)
192
+ return int(id_match.group(1)) if id_match else 0
193
+
194
+
195
+ def _next_finding_id(review_state: _ReviewState) -> str:
196
+ highest_number = max(map(_finding_number, review_state.all_findings), default=0)
197
+ return FINDING_ID_TEMPLATE.format(number=highest_number + 1)
198
+
199
+
200
+ def _finding_record(finding: _Finding) -> dict[str, str | None]:
201
+ return {
202
+ FINDING_TEXT_KEY: finding.text,
203
+ FINDING_REPOSITORY_KEY: finding.repository,
204
+ FINDING_BASE_KEY: finding.base_commit,
205
+ FINDING_TURN_KEY: finding.turn_commit,
206
+ FINDING_STATUS_KEY: finding.status,
207
+ FINDING_JUDGE_REASON_KEY: finding.judge_reason,
208
+ }
209
+
210
+
211
+ def _load_state(session_id: object) -> _ReviewState:
212
+ try:
213
+ saved_state = json.loads(_state_path(session_id).read_text(encoding=STATE_TEXT_ENCODING))
214
+ except (OSError, ValueError):
215
+ return _ReviewState()
216
+ if not isinstance(saved_state, dict):
217
+ return _ReviewState()
218
+ raw_baselines = saved_state.get(STATE_BASELINES_KEY)
219
+ all_baselines = {
220
+ each_root: each_commit
221
+ for each_root, each_commit in (
222
+ raw_baselines.items() if isinstance(raw_baselines, dict) else []
223
+ )
224
+ if isinstance(each_root, str) and _is_commit_name(each_commit)
225
+ }
226
+ raw_blocks = saved_state.get(STATE_BLOCKS_KEY)
227
+ return _ReviewState(
228
+ all_baselines,
229
+ raw_blocks if isinstance(raw_blocks, int) else 0,
230
+ saved_state.get(STATE_TURN_OPEN_KEY) is True,
231
+ _saved_time(saved_state.get(STATE_LAST_WAKE_KEY)),
232
+ _saved_time(saved_state.get(STATE_OPEN_TURN_PROMPT_KEY)),
233
+ _saved_findings(saved_state.get(STATE_FINDINGS_KEY)),
234
+ )
235
+
236
+
237
+ def _save_state(session_id: object, review_state: _ReviewState) -> None:
238
+ try:
239
+ write_text_atomically(
240
+ _state_path(session_id),
241
+ json.dumps(
242
+ {
243
+ STATE_BASELINES_KEY: review_state.all_baselines,
244
+ STATE_BLOCKS_KEY: review_state.blocks_in_a_row,
245
+ STATE_TURN_OPEN_KEY: review_state.is_turn_open,
246
+ STATE_LAST_WAKE_KEY: review_state.last_wake_at,
247
+ STATE_OPEN_TURN_PROMPT_KEY: review_state.open_turn_prompt_at,
248
+ STATE_FINDINGS_KEY: {
249
+ each_id: _finding_record(each_finding)
250
+ for each_id, each_finding in review_state.all_findings.items()
251
+ },
252
+ }
253
+ ),
254
+ STATE_TEXT_ENCODING,
255
+ STATE_TEMPORARY_PREFIX,
256
+ ATOMIC_WRITE_TEMPORARY_SUFFIX,
257
+ False,
258
+ )
259
+ except (OSError, UnicodeError) as save_error:
260
+ _log(STATE_SAVE_FAILURE_DIAGNOSTIC_TEMPLATE.format(detail=save_error))
@@ -0,0 +1,158 @@
1
+ """Read the reply and the user's messages from a Stop input, for the turn review gate.
2
+
3
+ The reply comes from ``last_assistant_message`` in the Stop input, or from
4
+ the text of the last assistant message in ``transcript_path`` when that field
5
+ is missing::
6
+
7
+ {"last_assistant_message": "Dismiss TR-1: the caller retries"} -> that text
8
+ {"transcript_path": "session.jsonl"} -> the text of the last assistant message
9
+
10
+ The user's messages come from ``transcript_path``. Only entries with
11
+ ``origin.kind`` ``human`` count, and text that starts with ``<`` is left out.
12
+ The last five are kept, each cut to 2000 characters. The transcript is read
13
+ from its newest line back, and each line is decoded once per stop.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ from collections.abc import Iterator
20
+ from pathlib import Path
21
+
22
+ from hooks_constants.turn_review_gate_constants import (
23
+ ALL_TRANSCRIPT_NOT_TYPED_FLAGS,
24
+ MAXIMUM_USER_MESSAGE_CHARACTERS,
25
+ NESTED_TOO_DEEP_REASON,
26
+ REPLY_TEXT_KEY,
27
+ TRANSCRIPT_ASSISTANT_TYPE,
28
+ TRANSCRIPT_BLOCK_TYPE_KEY,
29
+ TRANSCRIPT_CONTENT_KEY,
30
+ TRANSCRIPT_ENTRY_TYPE_KEY,
31
+ TRANSCRIPT_HUMAN_ORIGIN_KIND,
32
+ TRANSCRIPT_MARKUP_START,
33
+ TRANSCRIPT_MESSAGE_ID_KEY,
34
+ TRANSCRIPT_MESSAGE_KEY,
35
+ TRANSCRIPT_ORIGIN_KEY,
36
+ TRANSCRIPT_ORIGIN_KIND_KEY,
37
+ TRANSCRIPT_PATH_KEY,
38
+ TRANSCRIPT_TEXT_BLOCK_TYPE,
39
+ TRANSCRIPT_TEXT_ENCODING,
40
+ TRANSCRIPT_TEXT_KEY,
41
+ TRANSCRIPT_TEXT_SEPARATOR,
42
+ TRANSCRIPT_UNREADABLE_DIAGNOSTIC_TEMPLATE,
43
+ TRANSCRIPT_USER_TYPE,
44
+ USER_MESSAGE_COUNT,
45
+ )
46
+ from turn_review_state import _log
47
+
48
+
49
+ def _reversed_transcript_entries(hook_input: dict) -> Iterator[dict]:
50
+ transcript_path = hook_input.get(TRANSCRIPT_PATH_KEY)
51
+ if not isinstance(transcript_path, str) or not transcript_path:
52
+ return
53
+ try:
54
+ all_transcript_lines = Path(transcript_path).read_text(
55
+ encoding=TRANSCRIPT_TEXT_ENCODING, errors="replace"
56
+ ).splitlines()
57
+ except OSError:
58
+ return
59
+ for each_line in reversed(all_transcript_lines):
60
+ try:
61
+ transcript_entry = json.loads(each_line)
62
+ except ValueError:
63
+ continue
64
+ except RecursionError:
65
+ _log(TRANSCRIPT_UNREADABLE_DIAGNOSTIC_TEMPLATE.format(reason=NESTED_TOO_DEEP_REASON))
66
+ continue
67
+ if isinstance(transcript_entry, dict):
68
+ yield transcript_entry
69
+
70
+
71
+ class _ReversedTranscript:
72
+ """The transcript's entries, newest first, with each line decoded once per stop."""
73
+
74
+ def __init__(self, hook_input: dict) -> None:
75
+ self._unread_entries = _reversed_transcript_entries(hook_input)
76
+ self._all_read_entries: list[dict] = []
77
+
78
+ def __iter__(self) -> Iterator[dict]:
79
+ yield from self._all_read_entries
80
+ for each_entry in self._unread_entries:
81
+ self._all_read_entries.append(each_entry)
82
+ yield each_entry
83
+
84
+
85
+ def _entry_message(transcript_entry: dict) -> dict:
86
+ message = transcript_entry.get(TRANSCRIPT_MESSAGE_KEY)
87
+ return message if isinstance(message, dict) else {}
88
+
89
+
90
+ def _entry_text(transcript_entry: dict) -> str:
91
+ content = _entry_message(transcript_entry).get(TRANSCRIPT_CONTENT_KEY)
92
+ if isinstance(content, str):
93
+ return content.strip()
94
+ if not isinstance(content, list):
95
+ return ""
96
+ return TRANSCRIPT_TEXT_SEPARATOR.join(
97
+ each_block[TRANSCRIPT_TEXT_KEY]
98
+ for each_block in content
99
+ if isinstance(each_block, dict)
100
+ and each_block.get(TRANSCRIPT_BLOCK_TYPE_KEY) == TRANSCRIPT_TEXT_BLOCK_TYPE
101
+ and isinstance(each_block.get(TRANSCRIPT_TEXT_KEY), str)
102
+ ).strip()
103
+
104
+
105
+ def _is_assistant_entry(transcript_entry: dict) -> bool:
106
+ return transcript_entry.get(TRANSCRIPT_ENTRY_TYPE_KEY) == TRANSCRIPT_ASSISTANT_TYPE
107
+
108
+
109
+ def _last_assistant_message_text(transcript: _ReversedTranscript) -> str:
110
+ all_text_parts: list[str] = []
111
+ last_message_id: object = None
112
+ for each_entry in transcript:
113
+ is_first_assistant_entry = not all_text_parts and last_message_id is None
114
+ if is_first_assistant_entry and not _is_assistant_entry(each_entry):
115
+ continue
116
+ message_id = _entry_message(each_entry).get(TRANSCRIPT_MESSAGE_ID_KEY)
117
+ if not is_first_assistant_entry and (
118
+ not _is_assistant_entry(each_entry) or message_id != last_message_id
119
+ ):
120
+ break
121
+ all_text_parts.append(_entry_text(each_entry))
122
+ if message_id is None:
123
+ break
124
+ last_message_id = message_id
125
+ return TRANSCRIPT_TEXT_SEPARATOR.join(reversed(all_text_parts)).strip()
126
+
127
+
128
+ def _reply_text(hook_input: dict, transcript: _ReversedTranscript) -> str:
129
+ reply_text = hook_input.get(REPLY_TEXT_KEY)
130
+ if isinstance(reply_text, str):
131
+ return reply_text
132
+ return _last_assistant_message_text(transcript)
133
+
134
+
135
+ def _typed_user_text(transcript_entry: dict) -> str:
136
+ if transcript_entry.get(TRANSCRIPT_ENTRY_TYPE_KEY) != TRANSCRIPT_USER_TYPE:
137
+ return ""
138
+ if any(transcript_entry.get(each_flag) for each_flag in ALL_TRANSCRIPT_NOT_TYPED_FLAGS):
139
+ return ""
140
+ origin = transcript_entry.get(TRANSCRIPT_ORIGIN_KEY)
141
+ if (
142
+ not isinstance(origin, dict)
143
+ or origin.get(TRANSCRIPT_ORIGIN_KIND_KEY) != TRANSCRIPT_HUMAN_ORIGIN_KIND
144
+ ):
145
+ return ""
146
+ typed_text = _entry_text(transcript_entry)
147
+ return "" if typed_text.startswith(TRANSCRIPT_MARKUP_START) else typed_text
148
+
149
+
150
+ def _typed_user_messages(transcript: _ReversedTranscript) -> list[str]:
151
+ all_messages: list[str] = []
152
+ for each_entry in transcript:
153
+ typed_text = _typed_user_text(each_entry)
154
+ if typed_text:
155
+ all_messages.append(typed_text[:MAXIMUM_USER_MESSAGE_CHARACTERS])
156
+ if len(all_messages) == USER_MESSAGE_COUNT:
157
+ break
158
+ return list(reversed(all_messages))
@@ -12,9 +12,9 @@ This family rewrites a Git Bash command when path conversion would change a revi
12
12
  - `blocking/python_windows_invocation_gate.py` denies, on a Windows host, `python`, `python3` or `py` run with `-I` and without `-X utf8`, because `-I` ignores `PYTHONUTF8` and non-ASCII output then stops with `UnicodeEncodeError: 'charmap'`. Under the PowerShell tool it also denies a `python -c "..."` argument that holds `\"`, because PowerShell ends the string at that quote, and names a script file or a single-quoted here-string to use instead.
13
13
  - `blocking/transcript_root_search_gate.py` denies a recursive walk or content search that starts at a Claude transcript root, a `projects` folder directly under `.claude`, `.claude-<name>` or `.claude-profiles/<profile>`, with no project folder after it, or with a bare `*` or `**` segment that descends into every project folder. It reads `find`, `grep -r`, `rg`, `ls -R`, `Get-ChildItem -Recurse` or `-Depth`, `Select-String`, and the Grep and Glob tools, and expands variables the command assigns, such as `$p="..."`. A one-level name listing, such as `Get-ChildItem <root> -Directory -Filter "*id*"`, passes. The deny reason names the fix: list the project folders by name, then read the one transcript. The gate reads the root path as the command spells it, so a walk that starts above the root, or a glob that spells the root name or a project-name prefix such as `pro*` or `C--*`, passes.
14
14
  - `blocking/bash_post_call_dispatcher.py` runs hosted observers and joins their context output without blocking the call.
15
+ - When a hosted hook exits 2, both dispatchers exit 2. Its stderr reaches the host as written. Before a call, exit 2 blocks the call. After a call, exit 2 shows that stderr to Claude.
15
16
  - `advisory/pr_done_reminder.py` adds a pull request checklist after a successful push or pull request creation.
16
17
  - `advisory/owned_pr_review_loop.py` adds review-loop instructions after the agent opens a pull request on an owned repository outside the preset list of repositories that run their own automated review: run efficient-review until clean, mark the pull request ready, babysit it, and ship it to merge. It also records the pull request for the session in `owned_pr_session_record.py`.
17
- - `blocking/owned_pr_merge_stop_gate.py` holds the end of a turn while a recorded pull request reads open on GitHub and the closing reply has no `Blocked:` line that names it. It holds once per pull request head in a session, so a later stop passes until a push moves the head. A failed state lookup passes.
18
18
 
19
19
  ## When it fires
20
20
 
@@ -28,7 +28,6 @@ This family rewrites a Git Bash command when path conversion would change a revi
28
28
  - `blocking/bash_post_call_dispatcher.py` runs on `PostToolUse`, matcher `Bash|PowerShell`, timeout `60` seconds in `hooks.json`.
29
29
  - `advisory/pr_done_reminder.py` runs inside that dispatcher on `PostToolUse`, matcher `Bash|PowerShell`, timeout `60` seconds. `ALL_BASH_POST_TOOL_USE_HOSTED_HOOK_ENTRIES` selects `Bash` and `PowerShell`.
30
30
  - `advisory/owned_pr_review_loop.py` runs on `PostToolUse`, matcher `Bash|PowerShell|exec_command|shell_command|mcp__.*__(create_pull_request|github_create_pull_request)`, timeout `10` seconds in `hooks.json`. It wakes on `gh pr create`, `gh pr new`, a POST to `gh api repos/<owner>/<repo>/pulls`, a `pull_request.py create` call to the pull request publisher, and an MCP pull request creation. The installer also registers it on Codex `PostToolUse` through `ALL_CODEX_NATIVE_POST_TOOL_USE_HOOK_SCRIPT_NAMES`.
31
- - `blocking/owned_pr_merge_stop_gate.py` runs on `Stop`, timeout `60` seconds in `hooks.json`. The installer also registers it on Codex `Stop` through `ALL_CODEX_NATIVE_STOP_HOOK_SCRIPT_NAMES`.
32
31
 
33
32
  ## Proving it
34
33
 
@@ -45,7 +44,6 @@ Preconditions:
45
44
  - **Post-call dispatch.** Input is a Bash call that yields hosted context. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_bash_post_call_dispatcher.py -q`. The adjacent test observes a joined context payload and exit code zero.
46
45
  - **Pull request reminder.** Input is a completed push or pull request creation. Run `python -m pytest packages/claude-dev-env/hooks/advisory/test_pr_done_reminder.py -q`. The adjacent test checks the reminder trigger and checklist verdict.
47
46
  - **Owned pull request review loop.** Input is a pull request creation result on an owned repository. Run `python -m pytest packages/claude-dev-env/hooks/advisory/test_owned_pr_review_loop.py -q`. The adjacent test observes the review-loop block for owned repositories and silence for the preset and foreign repositories.
48
- - **Owned pull request merge gate.** Input is a `session_record_path` file that lists `jl-cmd/snake-game#9` and a `gh` stub that reports `open` and a head sha. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_owned_pr_merge_stop_gate.py packages/claude-dev-env/hooks/test_owned_pr_session_record.py -q`. The adjacent test observes a `block` decision that names the pull request; `closed` and a `Blocked: jl-cmd/snake-game#9 - ...` line pass, and a second stop on the same head passes.
49
47
 
50
48
  ## Gotchas
51
49