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
@@ -1,44 +1,73 @@
1
1
  #!/usr/bin/env python3
2
- """Stop hook that has a fresh reviewer read each turn's changes before the turn ends.
2
+ """Stop hook that has a fresh reviewer read each turn's changes, and a judge rule on each dismissal.
3
3
 
4
- The agent edits ``src/service.py`` and drops a retry. When the turn stops, a
5
- separate ``claude -p`` run reviews only that turn's edits with
6
- ``/code-review low`` and the hook holds the stop with what it found::
4
+ The agent edits ``src/service.py`` and drops a retry. The turn ends at once.
5
+ In the background, a separate ``claude -p`` run reviews only that turn's edits
6
+ with ``/code-review low``, on Sonnet at high effort. A finding exits 2 and wakes the agent with it::
7
7
 
8
8
  prompt arrives -> snapshot A of the working tree
9
9
  agent edits -> src/service.py loses @with_retry
10
- stop -> snapshot B (parent A), claude -p "/code-review low A..B"
11
- -> block: "src/service.py:208 - The diff removes ..."
12
- agent fixes it -> stop reviews B..C only, finds nothing, the turn ends
10
+ stop -> turn ends; snapshot B (parent A), claude -p "/code-review low A..B"
11
+ -> exit 2 wakes the agent: "src/service.py:208 - The diff removes ..."
12
+ agent fixes it -> stop reviews B..C only, finds nothing, prints nothing
13
13
 
14
14
  ``turn_review_snapshot`` builds the snapshots, and ``turn_review_findings``
15
15
  reads the findings out of the review text. Edits the user left before the
16
- prompt sit in snapshot A, so the review sees only the agent's work. Each stop
17
- moves the baseline to the snapshot it took, so the stop after a block reviews
18
- only the fix.
19
-
20
- A repository takes part when it is the session's project folder or a folder
21
- directly inside it, and its GitHub origin ``owner/repo`` slug is listed in
22
- ``CLAUDE_TURN_REVIEW_REPOSITORIES``. The hook holds a stop at most three times
16
+ prompt sit in snapshot A, so the review sees only the agent's work.
17
+
18
+ Each finding gets an id that is unique in the session, such as ``TR-1``, and
19
+ is saved as open in the session's state. The wake shows the id beside the
20
+ finding. The agent fixes the finding or contests it with one reply line, and
21
+ a separate judge run decides::
22
+
23
+ reply ends with "Dismiss TR-1: the caller retries the update"
24
+ stop -> claude -p --model sonnet --effort high, prompt on stdin
25
+ judge approves -> TR-1 dismissed, reason saved, one log line, no wake
26
+ judge rejects -> TR-1 upheld; exit 2: "Dismissal of TR-1 rejected: <reason>. Fix it."
27
+
28
+ ``turn_review_transcript`` reads the reply and the user's messages, and
29
+ ``turn_review_claim`` builds the judge's data from them. The judge runs with
30
+ the review's read-only options, once per checkout
31
+ that holds a contested finding. A rejection counts toward the hold count, and
32
+ it shares one wake with that stop's new findings. The judge runs after the
33
+ review and shares its time. A judge that fails, times out or gets no time, or
34
+ whose whole answer is not one JSON array of verdicts, leaves the finding open
35
+ and exits 0 with no output.
36
+
37
+ Claude Code runs the Stop entry with ``asyncRewake``. A plain ``claude -p``
38
+ run has no background, so the same entry holds that stop with exit code 2.
39
+ A finding or a rejected dismissal goes to stderr and to the stdout ``reason``. Every
40
+ other outcome exits 0 with no output, and its diagnostic goes to ``~/.claude/logs/turn-review.log``.
41
+
42
+ A stop claims its range before the review starts, under a lock on the session's
43
+ state file. ``turn_review_claim`` makes the claim and saves the stop's outcome,
44
+ and ``turn_review_state`` keeps the state file, the lock and the log.
45
+ After the review, the stop waits up to 35 seconds for the
46
+ lock, longer than a prompt run may hold it, and changes only the hold count. A stop that never gets that lock
47
+ exits 0 with no wake, so each wake is counted.
48
+
49
+ ``turn_review_repositories`` picks the checkouts that take part, from the
50
+ slugs listed in ``CLAUDE_TURN_REVIEW_REPOSITORIES``. The hook holds a stop at most three times
23
51
  in a row, skips a turn that changed more than 30 files, and lets the stop
24
- through when the review fails or times out; a new prompt resets the count.
25
- These are the limits of Anthropic's security-guidance plugin. The review run
26
- carries ``CLAUDE_TURN_REVIEW_CHILD=1`` and none of the parent session's id,
27
- messaging or ingress variables, and the hook does nothing inside such a run. The review may read
28
- files and run ``git diff``, ``git show`` and ``git log``; every other tool is
29
- denied.
52
+ through when the review fails or times out. A user's prompt resets the hold
53
+ count, and a prompt that belongs to a wake keeps it, so a chain of wakes stops at three.
54
+ A stop gets 280 seconds of work and a prompt 25, under the 300 and 30
55
+ second registrations. A git call or review that would start after that time
56
+ is skipped.
57
+ The cap and the file limit match Anthropic's security-guidance plugin.
58
+ ``turn_review_child`` starts the review and judge runs, and the hook does
59
+ nothing inside such a run.
30
60
  """
31
61
 
32
62
  from __future__ import annotations
33
63
 
34
64
  import json
35
65
  import os
36
- import re
37
- import shutil
38
- import subprocess
39
66
  import sys
40
67
  import tempfile
41
68
  import time
69
+ from collections.abc import Iterator
70
+ from contextlib import contextmanager
42
71
  from pathlib import Path
43
72
 
44
73
  hooks_root_directory = str(Path(__file__).resolve().parent.parent)
@@ -48,240 +77,136 @@ blocking_directory = str(Path(__file__).resolve().parent)
48
77
  if blocking_directory not in sys.path:
49
78
  sys.path.insert(0, blocking_directory)
50
79
 
51
- from atomic_file_writer import write_text_atomically
52
- from hooks_constants.atomic_file_writer_constants import ATOMIC_WRITE_TEMPORARY_SUFFIX
53
80
  from hooks_constants.hook_block_logger import log_hook_block
81
+ from hooks_constants.hook_time_budget import call_timeout, remaining_seconds, time_budget
54
82
  from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
55
83
  from hooks_constants.session_file_id import session_file_id
56
- from hooks_constants.subprocess_window import hidden_window_creation_flags
84
+ from hooks_constants.stop_hook_hold import hold_stop
57
85
  from hooks_constants.turn_review_gate_constants import (
58
- ALL_PARENT_SESSION_VARIABLES,
59
- ALL_REVIEW_ALLOWED_TOOLS,
60
- ALL_REVIEW_DISALLOWED_TOOLS,
61
- BASELINE_COMMIT_PATTERN,
62
- BLOCK_DECISION,
63
- BLOCK_REASON_TEMPLATE,
64
- DECISION_KEY,
65
- FINDING_LINE_SEPARATOR,
66
- GIT_DIRECTORY_NAME,
67
86
  HOOK_EVENT_NAME_KEY,
68
- MAXIMUM_BLOCKS_IN_A_ROW,
87
+ JUDGE_FAILURE_DIAGNOSTIC_TEMPLATE,
69
88
  MAXIMUM_TURN_FILES,
70
- PROJECT_DIRECTORY_ENVIRONMENT_VARIABLE,
89
+ MINIMUM_REVIEW_SECONDS,
90
+ NO_VERDICT_DIAGNOSTIC_TEMPLATE,
71
91
  PROMPT_EVENT_NAME,
72
- REASON_KEY,
73
- REPOSITORIES_ENVIRONMENT_VARIABLE,
74
- REPOSITORY_FINDINGS_SEPARATOR,
75
- REPOSITORY_FINDINGS_TEMPLATE,
76
- REPOSITORY_SEPARATOR,
92
+ PROMPT_KEY,
93
+ PROMPT_RUN_BUDGET_SECONDS,
77
94
  REVIEW_CHILD_ENVIRONMENT_VARIABLE,
78
95
  REVIEW_CHILD_MARKER,
79
- REVIEW_EFFORT,
80
96
  REVIEW_FAILURE_DIAGNOSTIC_TEMPLATE,
81
- REVIEW_MODEL_ALIAS,
82
- REVIEW_PROMPT_TEMPLATE,
83
97
  REVIEW_RESULT_KEY,
84
- REVIEW_EXECUTABLE_NAME,
85
- REVIEW_SETTING_SOURCES_TEXT,
86
- REVIEW_SETTINGS_TEXT,
87
- MINIMUM_REVIEW_SECONDS,
88
98
  REVIEW_TIMEOUT_SECONDS,
89
- REVIEW_TOOLS_TEXT,
99
+ RUN_DIAGNOSTIC_TEMPLATE,
90
100
  SESSION_ID_KEY,
91
- STATE_BASELINES_KEY,
92
- STATE_BLOCKS_KEY,
93
- STATE_FILE_TEMPLATE,
94
- STATE_TEMPORARY_PREFIX,
95
- STATE_TEXT_ENCODING,
101
+ STATE_LOCK_BUSY_DIAGNOSTIC_TEMPLATE,
102
+ STATE_LOCK_FILE_MODE,
103
+ STATE_LOCK_FILE_TEMPLATE,
104
+ STATE_LOCK_OUTCOME_WAIT_SECONDS,
105
+ STATE_LOCK_RETRY_SECONDS,
106
+ STATE_LOCK_WAIT_SECONDS,
96
107
  STOP_EVENT_NAME,
108
+ STOP_HOOK_ACTIVE_KEY,
109
+ STOP_RUN_BUDGET_SECONDS,
97
110
  TOO_MANY_FILES_DIAGNOSTIC_TEMPLATE,
98
111
  )
99
- from pii_prevention_blocker_parts.repository_exemption import repository_origin_slug
100
- from turn_review_findings import finding_lines
101
- from turn_review_snapshot import turn_changed_paths, working_tree_snapshot
102
-
103
-
104
- def _opted_in_repository_slugs() -> frozenset[str]:
105
- listed = os.environ.get(REPOSITORIES_ENVIRONMENT_VARIABLE, "")
106
- return frozenset(
107
- each.strip().casefold() for each in listed.split(REPOSITORY_SEPARATOR) if each.strip()
108
- )
112
+ from turn_review_child import _ChildRun, _child_stdout, _judge_command, _review_command
113
+ from turn_review_claim import (
114
+ _claim_locked_stop,
115
+ _is_wake_prompt,
116
+ _judge_prompt,
117
+ _JudgeRequest,
118
+ _locked_stop_wake,
119
+ _prompt_baselines,
120
+ _StopClaim,
121
+ )
122
+ from turn_review_findings import JudgeVerdict, dismiss_requests, finding_lines, judge_verdicts
123
+ from turn_review_repositories import _opted_in_repository_roots, _opted_in_repository_slugs
124
+ from turn_review_snapshot import turn_changed_paths
125
+ from turn_review_state import _is_lock_taken, _load_state, _log, _release_and_close, _save_state
126
+ from turn_review_transcript import _ReversedTranscript, _reply_text, _typed_user_messages
109
127
 
110
128
 
111
- def _opted_in_repository_roots(all_slugs: frozenset[str]) -> list[Path]:
112
- project_directory = os.environ.get(PROJECT_DIRECTORY_ENVIRONMENT_VARIABLE, "")
113
- if not project_directory or not Path(project_directory).is_dir():
114
- return []
115
- project_path = Path(project_directory).resolve()
116
- all_candidates = [project_path, *sorted(_child_entries(project_path))]
117
- return [each for each in all_candidates if _is_opted_in_checkout(each, all_slugs)]
129
+ def _acquire_with_wait(file_descriptor: int, wait_seconds: float) -> bool:
130
+ deadline = time.monotonic() + (call_timeout(wait_seconds) or 0)
131
+ while not _is_lock_taken(file_descriptor):
132
+ if time.monotonic() >= deadline:
133
+ return False
134
+ time.sleep(STATE_LOCK_RETRY_SECONDS)
135
+ return True
118
136
 
119
137
 
120
- def _child_entries(project_path: Path) -> list[Path]:
138
+ @contextmanager
139
+ def _state_lock(session_id: object, wait_seconds: float) -> Iterator[bool]:
140
+ lock_path = Path(tempfile.gettempdir()) / STATE_LOCK_FILE_TEMPLATE.format(
141
+ session_id=session_file_id(session_id)
142
+ )
121
143
  try:
122
- return list(project_path.iterdir())
144
+ file_descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR, STATE_LOCK_FILE_MODE)
123
145
  except OSError:
124
- return []
125
-
126
-
127
- def _is_opted_in_checkout(folder: Path, all_slugs: frozenset[str]) -> bool:
146
+ yield False
147
+ return
148
+ is_locked = _acquire_with_wait(file_descriptor, wait_seconds)
128
149
  try:
129
- is_checkout = folder.is_dir() and (folder / GIT_DIRECTORY_NAME).exists()
130
- except OSError:
131
- return False
132
- return is_checkout and repository_origin_slug(folder) in all_slugs
150
+ yield is_locked
151
+ finally:
152
+ _release_and_close(file_descriptor, is_locked)
133
153
 
134
154
 
135
- def _review_command(base_commit: str, turn_commit: str) -> list[str]:
136
- review_prompt = REVIEW_PROMPT_TEMPLATE.format(
137
- effort=REVIEW_EFFORT, base_commit=base_commit, turn_commit=turn_commit
138
- )
139
- return [
140
- shutil.which(REVIEW_EXECUTABLE_NAME) or REVIEW_EXECUTABLE_NAME,
141
- "-p",
142
- review_prompt,
143
- "--model",
144
- REVIEW_MODEL_ALIAS,
145
- "--output-format",
146
- "json",
147
- "--permission-mode",
148
- "dontAsk",
149
- "--setting-sources",
150
- REVIEW_SETTING_SOURCES_TEXT,
151
- "--tools",
152
- REVIEW_TOOLS_TEXT,
153
- "--no-session-persistence",
154
- "--allowedTools",
155
- *ALL_REVIEW_ALLOWED_TOOLS,
156
- "--disallowedTools",
157
- *ALL_REVIEW_DISALLOWED_TOOLS,
158
- "--settings",
159
- REVIEW_SETTINGS_TEXT,
160
- ]
161
-
162
-
163
- def _review_environment() -> dict[str, str]:
164
- all_child_environment_variables = {
165
- each_name: each_value
166
- for each_name, each_value in os.environ.items()
167
- if each_name not in ALL_PARENT_SESSION_VARIABLES
168
- }
169
- all_child_environment_variables[REVIEW_CHILD_ENVIRONMENT_VARIABLE] = REVIEW_CHILD_MARKER
170
- return all_child_environment_variables
171
-
172
-
173
- def _write_review_failure(repository_root: Path, failure_text: str) -> None:
174
- sys.stderr.write(
175
- REVIEW_FAILURE_DIAGNOSTIC_TEMPLATE.format(
176
- repository=repository_root.name, reason=failure_text
177
- )
178
- )
179
-
180
-
181
- def _review_stdout(
182
- repository_root: Path, base_commit: str, turn_commit: str, remaining_seconds: float
183
- ) -> str | None:
184
- try:
185
- completed_process = subprocess.run(
186
- _review_command(base_commit, turn_commit),
187
- check=False,
188
- capture_output=True,
189
- text=True,
190
- encoding="utf-8",
191
- errors="replace",
192
- stdin=subprocess.DEVNULL,
193
- timeout=remaining_seconds,
194
- cwd=str(repository_root),
195
- env=_review_environment(),
196
- creationflags=hidden_window_creation_flags(),
197
- )
198
- except subprocess.TimeoutExpired:
199
- _write_review_failure(repository_root, "timed out")
200
- return None
201
- except OSError as start_error:
202
- _write_review_failure(repository_root, str(start_error))
203
- return None
204
- if completed_process.returncode != 0:
205
- _write_review_failure(repository_root, f"exit {completed_process.returncode}")
206
- return None
207
- return completed_process.stdout
208
-
209
-
210
- def _review_text(
211
- repository_root: Path, base_commit: str, turn_commit: str, review_deadline: float
212
- ) -> str | None:
213
- remaining_seconds = review_deadline - time.monotonic()
155
+ def _child_result_text(child_run: _ChildRun, deadline: float) -> str | None:
156
+ remaining_seconds = deadline - time.monotonic()
214
157
  if remaining_seconds < MINIMUM_REVIEW_SECONDS:
215
- _write_review_failure(repository_root, "no review time left this stop")
158
+ child_run.write_failure("no time left this stop")
216
159
  return None
217
- review_stdout = _review_stdout(repository_root, base_commit, turn_commit, remaining_seconds)
218
- if review_stdout is None:
160
+ child_stdout = _child_stdout(child_run, remaining_seconds)
161
+ if child_stdout is None:
219
162
  return None
220
163
  try:
221
- review_result = json.loads(review_stdout)
222
- except ValueError:
223
- _write_review_failure(repository_root, "output was not JSON")
164
+ child_result = json.loads(child_stdout)
165
+ except (ValueError, RecursionError):
166
+ child_run.write_failure("output was not JSON")
224
167
  return None
225
- review_text = review_result.get(REVIEW_RESULT_KEY) if isinstance(review_result, dict) else None
226
- if not isinstance(review_text, str):
227
- _write_review_failure(repository_root, "output had no result text")
168
+ result_text = child_result.get(REVIEW_RESULT_KEY) if isinstance(child_result, dict) else None
169
+ if not isinstance(result_text, str):
170
+ child_run.write_failure("output had no result text")
228
171
  return None
229
- return review_text
172
+ return result_text
230
173
 
231
174
 
232
- def _state_path(session_id: object) -> Path:
233
- return Path(tempfile.gettempdir()) / STATE_FILE_TEMPLATE.format(
234
- session_id=session_file_id(session_id)
235
- )
236
-
237
-
238
- def _load_state(session_id: object) -> tuple[dict[str, str], int]:
239
- try:
240
- saved_state = json.loads(_state_path(session_id).read_text(encoding=STATE_TEXT_ENCODING))
241
- except (OSError, ValueError):
242
- return {}, 0
243
- if not isinstance(saved_state, dict):
244
- return {}, 0
245
- raw_baselines = saved_state.get(STATE_BASELINES_KEY)
246
- all_baselines = {
247
- each_root: each_commit
248
- for each_root, each_commit in (
249
- raw_baselines.items() if isinstance(raw_baselines, dict) else []
250
- )
251
- if isinstance(each_root, str)
252
- and isinstance(each_commit, str)
253
- and re.fullmatch(BASELINE_COMMIT_PATTERN, each_commit)
254
- }
255
- raw_blocks = saved_state.get(STATE_BLOCKS_KEY)
256
- return all_baselines, raw_blocks if isinstance(raw_blocks, int) else 0
257
-
258
-
259
- def _save_state(session_id: object, all_baselines: dict[str, str], blocks_in_a_row: int) -> None:
260
- write_text_atomically(
261
- _state_path(session_id),
262
- json.dumps({STATE_BASELINES_KEY: all_baselines, STATE_BLOCKS_KEY: blocks_in_a_row}),
263
- STATE_TEXT_ENCODING,
264
- STATE_TEMPORARY_PREFIX,
265
- ATOMIC_WRITE_TEMPORARY_SUFFIX,
266
- False,
175
+ def _review_text(
176
+ repository_root: Path, base_commit: str, turn_commit: str, review_deadline: float
177
+ ) -> str | None:
178
+ review_run = _ChildRun(
179
+ repository_root,
180
+ _review_command(base_commit, turn_commit),
181
+ None,
182
+ REVIEW_FAILURE_DIAGNOSTIC_TEMPLATE,
267
183
  )
268
-
269
-
270
- def _record_prompt_baselines(session_id: object, all_roots: list[Path]) -> None:
271
- all_baselines = {}
272
- for each_root in all_roots:
273
- snapshot_commit = working_tree_snapshot(each_root, None)
274
- if snapshot_commit is not None:
275
- all_baselines[str(each_root)] = snapshot_commit
276
- _save_state(session_id, all_baselines, 0)
184
+ return _child_result_text(review_run, review_deadline)
185
+
186
+
187
+ def _record_prompt_baselines(
188
+ session_id: object, all_roots: list[Path], prompt_text: object
189
+ ) -> None:
190
+ with _state_lock(session_id, STATE_LOCK_WAIT_SECONDS) as is_locked:
191
+ if not is_locked:
192
+ _log(STATE_LOCK_BUSY_DIAGNOSTIC_TEMPLATE.format(event=PROMPT_EVENT_NAME))
193
+ return
194
+ review_state = _load_state(session_id)
195
+ now = time.time()
196
+ review_state.all_baselines = _prompt_baselines(review_state, all_roots)
197
+ review_state.open_turn_prompt_at = now if review_state.is_turn_open else None
198
+ if not _is_wake_prompt(review_state, prompt_text, now):
199
+ review_state.blocks_in_a_row = 0
200
+ review_state.is_turn_open = True
201
+ _save_state(session_id, review_state)
277
202
 
278
203
 
279
204
  def _repository_findings(
280
205
  repository_root: Path, base_commit: str, turn_commit: str, review_deadline: float
281
- ) -> str | None:
206
+ ) -> list[str] | None:
282
207
  all_changed_paths = turn_changed_paths(repository_root, base_commit, turn_commit)
283
208
  if len(all_changed_paths) > MAXIMUM_TURN_FILES:
284
- sys.stderr.write(
209
+ _log(
285
210
  TOO_MANY_FILES_DIAGNOSTIC_TEMPLATE.format(
286
211
  repository=repository_root.name,
287
212
  count=len(all_changed_paths),
@@ -292,51 +217,105 @@ def _repository_findings(
292
217
  if not all_changed_paths:
293
218
  return None
294
219
  review_text = _review_text(repository_root, base_commit, turn_commit, review_deadline)
295
- all_finding_lines = finding_lines(review_text or "", all_changed_paths)
296
- if not all_finding_lines:
297
- return None
298
- return REPOSITORY_FINDINGS_TEMPLATE.format(
299
- repository=repository_root.name,
300
- findings=FINDING_LINE_SEPARATOR.join(all_finding_lines),
220
+ return finding_lines(review_text or "", all_changed_paths) or None
221
+
222
+
223
+ def _claim_stop(
224
+ session_id: object, all_roots: list[Path], all_dismiss_reasons: dict[str, str]
225
+ ) -> _StopClaim:
226
+ with _state_lock(session_id, STATE_LOCK_WAIT_SECONDS) as is_locked:
227
+ if not is_locked:
228
+ _log(STATE_LOCK_BUSY_DIAGNOSTIC_TEMPLATE.format(event=STOP_EVENT_NAME))
229
+ return _StopClaim()
230
+ return _claim_locked_stop(session_id, all_roots, all_dismiss_reasons)
231
+
232
+
233
+ def _repository_verdicts(
234
+ repository_root: Path,
235
+ all_requests: list[_JudgeRequest],
236
+ all_user_messages: list[str],
237
+ deadline: float,
238
+ ) -> dict[str, JudgeVerdict]:
239
+ judge_run = _ChildRun(
240
+ repository_root,
241
+ _judge_command(),
242
+ _judge_prompt(repository_root, all_requests, all_user_messages),
243
+ JUDGE_FAILURE_DIAGNOSTIC_TEMPLATE,
301
244
  )
245
+ result_text = _child_result_text(judge_run, deadline)
246
+ if result_text is None:
247
+ return {}
248
+ all_requested_ids = [each_request.finding_id for each_request in all_requests]
249
+ all_verdicts = judge_verdicts(result_text, all_requested_ids)
250
+ if all_verdicts is None:
251
+ judge_run.write_failure("answer was not one JSON array of verdicts")
252
+ return {}
253
+ for each_id in all_requested_ids:
254
+ if each_id not in all_verdicts:
255
+ _log(NO_VERDICT_DIAGNOSTIC_TEMPLATE.format(finding_id=each_id))
256
+ return all_verdicts
257
+
258
+
259
+ def _all_judge_verdicts(
260
+ all_requests: list[_JudgeRequest],
261
+ all_roots: list[Path],
262
+ all_user_messages: list[str],
263
+ deadline: float,
264
+ ) -> dict[str, JudgeVerdict]:
265
+ all_verdicts: dict[str, JudgeVerdict] = {}
266
+ for each_root in all_roots:
267
+ all_root_requests = [
268
+ each_request
269
+ for each_request in all_requests
270
+ if each_request.finding.repository == str(each_root)
271
+ ]
272
+ if all_root_requests:
273
+ all_verdicts.update(
274
+ _repository_verdicts(each_root, all_root_requests, all_user_messages, deadline)
275
+ )
276
+ return all_verdicts
302
277
 
303
278
 
304
- def _turn_block_reason(session_id: object, all_roots: list[Path]) -> str | None:
305
- all_baselines, blocks_in_a_row = _load_state(session_id)
306
- all_next_baselines: dict[str, str] = {}
307
- all_findings: list[str] = []
308
- review_deadline = time.monotonic() + REVIEW_TIMEOUT_SECONDS
309
- for each_root in all_roots:
310
- base_commit = all_baselines.get(str(each_root))
311
- turn_commit = working_tree_snapshot(each_root, base_commit)
312
- if turn_commit is None:
313
- continue
314
- all_next_baselines[str(each_root)] = turn_commit
315
- if base_commit is None or blocks_in_a_row >= MAXIMUM_BLOCKS_IN_A_ROW:
316
- continue
317
- repository_findings = _repository_findings(
318
- each_root, base_commit, turn_commit, review_deadline
319
- )
320
- if repository_findings is not None:
321
- all_findings.append(repository_findings)
322
- if all_findings:
323
- blocks_in_a_row += 1
324
- elif blocks_in_a_row < MAXIMUM_BLOCKS_IN_A_ROW:
325
- blocks_in_a_row = 0
326
- _save_state(session_id, all_next_baselines, blocks_in_a_row)
327
- if not all_findings:
279
+ def _saved_stop_wake(
280
+ session_id: object,
281
+ all_repository_findings: list[tuple[Path, str, str, list[str]]],
282
+ all_verdicts: dict[str, JudgeVerdict],
283
+ ) -> str | None:
284
+ with _state_lock(session_id, STATE_LOCK_OUTCOME_WAIT_SECONDS) as is_locked:
285
+ if not is_locked:
286
+ _log(STATE_LOCK_BUSY_DIAGNOSTIC_TEMPLATE.format(event=STOP_EVENT_NAME))
287
+ return None
288
+ return _locked_stop_wake(session_id, all_repository_findings, all_verdicts)
289
+
290
+
291
+ def _turn_block_reason(
292
+ session_id: object, all_roots: list[Path], hook_input: dict | None = None
293
+ ) -> str | None:
294
+ stop_input = hook_input or {}
295
+ transcript = _ReversedTranscript(stop_input)
296
+ stop_claim = _claim_stop(
297
+ session_id, all_roots, dismiss_requests(_reply_text(stop_input, transcript))
298
+ )
299
+ if not stop_claim.all_turn_ranges and not stop_claim.all_judge_requests:
328
300
  return None
329
- return BLOCK_REASON_TEMPLATE.format(
330
- all_findings=REPOSITORY_FINDINGS_SEPARATOR.join(all_findings)
301
+ all_repository_findings: list[tuple[Path, str, str, list[str]]] = []
302
+ deadline = time.monotonic() + min(REVIEW_TIMEOUT_SECONDS, remaining_seconds())
303
+ for each_root, each_base_commit, each_turn_commit in stop_claim.all_turn_ranges:
304
+ all_lines = _repository_findings(each_root, each_base_commit, each_turn_commit, deadline)
305
+ if all_lines:
306
+ all_repository_findings.append(
307
+ (each_root, each_base_commit, each_turn_commit, all_lines)
308
+ )
309
+ all_user_messages = (
310
+ _typed_user_messages(transcript) if stop_claim.all_judge_requests else []
311
+ )
312
+ all_verdicts = _all_judge_verdicts(
313
+ stop_claim.all_judge_requests, all_roots, all_user_messages, deadline
331
314
  )
315
+ return _saved_stop_wake(session_id, all_repository_findings, all_verdicts)
332
316
 
333
317
 
334
- def main() -> int:
335
- hook_input = read_hook_input_dictionary_from_stdin()
336
- if hook_input is None:
337
- return 0
338
- if os.environ.get(REVIEW_CHILD_ENVIRONMENT_VARIABLE) == REVIEW_CHILD_MARKER:
339
- return 0
318
+ def _handle_event(hook_input: dict, hook_event_name: object) -> int:
340
319
  all_slugs = _opted_in_repository_slugs()
341
320
  if not all_slugs:
342
321
  return 0
@@ -344,18 +323,36 @@ def main() -> int:
344
323
  if not all_roots:
345
324
  return 0
346
325
  session_id = hook_input.get(SESSION_ID_KEY)
347
- hook_event_name = hook_input.get(HOOK_EVENT_NAME_KEY)
326
+ _log(
327
+ RUN_DIAGNOSTIC_TEMPLATE.format(
328
+ event=hook_event_name, stop_hook_active=hook_input.get(STOP_HOOK_ACTIVE_KEY)
329
+ )
330
+ )
348
331
  if hook_event_name == PROMPT_EVENT_NAME:
349
- _record_prompt_baselines(session_id, all_roots)
332
+ _record_prompt_baselines(session_id, all_roots, hook_input.get(PROMPT_KEY))
350
333
  return 0
351
- if hook_event_name != STOP_EVENT_NAME:
352
- return 0
353
- block_reason = _turn_block_reason(session_id, all_roots)
334
+ block_reason = _turn_block_reason(session_id, all_roots, hook_input)
354
335
  if block_reason is None:
355
336
  return 0
356
337
  log_hook_block(Path(__file__).name, STOP_EVENT_NAME, block_reason)
357
- sys.stdout.write(json.dumps({DECISION_KEY: BLOCK_DECISION, REASON_KEY: block_reason}))
358
- return 0
338
+ return hold_stop(hook_input, block_reason)
339
+
340
+
341
+ def main() -> int:
342
+ hook_input = read_hook_input_dictionary_from_stdin()
343
+ if hook_input is None:
344
+ return 0
345
+ if os.environ.get(REVIEW_CHILD_ENVIRONMENT_VARIABLE) == REVIEW_CHILD_MARKER:
346
+ return 0
347
+ hook_event_name = hook_input.get(HOOK_EVENT_NAME_KEY)
348
+ if hook_event_name == STOP_EVENT_NAME:
349
+ run_budget_seconds = STOP_RUN_BUDGET_SECONDS
350
+ elif hook_event_name == PROMPT_EVENT_NAME:
351
+ run_budget_seconds = PROMPT_RUN_BUDGET_SECONDS
352
+ else:
353
+ return 0
354
+ with time_budget(run_budget_seconds):
355
+ return _handle_event(hook_input, hook_event_name)
359
356
 
360
357
 
361
358
  if __name__ == "__main__":