claude-dev-env 8.117.0 → 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.
@@ -25,88 +25,51 @@ a separate judge run decides::
25
25
  judge approves -> TR-1 dismissed, reason saved, one log line, no wake
26
26
  judge rejects -> TR-1 upheld; exit 2: "Dismissal of TR-1 rejected: <reason>. Fix it."
27
27
 
28
- The reply comes from ``last_assistant_message`` in the Stop input, or from
29
- the text of the last assistant message in ``transcript_path`` when that field
30
- is missing. The judge gets the checkout path and one JSON object of data::
31
-
32
- {"requests": [{"id": "TR-1", "commit_range": "A..B",
33
- "finding": "src/service.py:3 - ...", "reason_to_dismiss": "..."}],
34
- "user_messages": ["the last five messages the user typed, cut to 2000 characters"]}
35
-
36
- The user's messages come from ``transcript_path``. Only entries with
37
- ``origin.kind`` ``human`` count, and text that starts with ``<`` is left out. The judge gets no other part of the
38
- conversation. It runs with the review's read-only options, once per checkout
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
39
31
  that holds a contested finding. A rejection counts toward the hold count, and
40
32
  it shares one wake with that stop's new findings. The judge runs after the
41
33
  review and shares its time. A judge that fails, times out or gets no time, or
42
34
  whose whole answer is not one JSON array of verdicts, leaves the finding open
43
- and exits 0 with no output. A ``Dismiss`` line for an id that is not open, or
44
- one sent at the hold cap, is logged and not judged.
35
+ and exits 0 with no output.
45
36
 
46
37
  Claude Code runs the Stop entry with ``asyncRewake``. A plain ``claude -p``
47
38
  run has no background, so the same entry holds that stop with exit code 2.
48
39
  A finding or a rejected dismissal goes to stderr and to the stdout ``reason``. Every
49
40
  other outcome exits 0 with no output, and its diagnostic goes to ``~/.claude/logs/turn-review.log``.
50
41
 
51
- A stop claims its range before the review starts. Under a lock on the session's
52
- state file, it moves the baseline to snapshot B, marks the turn closed, and
53
- saves both. A second stop during the review starts from B, so no range is
54
- reviewed twice. After the review, the stop waits up to 35 seconds for the
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
55
46
  lock, longer than a prompt run may hold it, and changes only the hold count. A stop that never gets that lock
56
47
  exits 0 with no wake, so each wake is counted.
57
48
 
58
- A prompt marks the turn open. When the last turn is still open, no stop has
59
- claimed it yet: its stop is racing this prompt, or the user interrupted it::
60
-
61
- prompt 1 -> baseline A, turn open
62
- stop 1 -> starts; the next prompt runs before its claim
63
- prompt 2 -> turn still open, so A stays the baseline
64
- stop 1 -> claims A..B and reviews turn 1's edits
65
-
66
- Edits the user made between those two turns are then reviewed too. When a
67
- prompt found the turn open less than 10 seconds before the claim, that prompt
68
- began the next turn, so the stop leaves it open. A later claim closes it,
69
- which ends the open turn an interrupt left behind.
70
-
71
- A repository takes part when it is the session's project folder or a folder
72
- directly inside it, and its GitHub origin ``owner/repo`` slug is listed in
73
- ``CLAUDE_TURN_REVIEW_REPOSITORIES``. The hook holds a stop at most three times
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
74
51
  in a row, skips a turn that changed more than 30 files, and lets the stop
75
- through when the review fails or times out. A stop below the cap with no
76
- finding, no rejection and no dismissal to judge resets the count, and so does a user's prompt. A prompt within 10 seconds
77
- of the last wake, or one that starts with ``<task-notification``, belongs to
78
- the wake and keeps the count, so a chain of wakes stops at three.
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.
79
54
  A stop gets 280 seconds of work and a prompt 25, under the 300 and 30
80
55
  second registrations. A git call or review that would start after that time
81
56
  is skipped.
82
- The cap and the file limit match Anthropic's security-guidance plugin. The review and judge
83
- runs carry ``CLAUDE_TURN_REVIEW_CHILD=1`` and none of the parent session's id,
84
- messaging or ingress variables, and the hook does nothing inside such a run. Each may read
85
- files and run ``git diff``, ``git show`` and ``git log``; every other tool is
86
- denied.
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.
87
60
  """
88
61
 
89
62
  from __future__ import annotations
90
63
 
91
- import datetime
92
64
  import json
93
65
  import os
94
- import re
95
- import shutil
96
- import subprocess
97
66
  import sys
98
67
  import tempfile
99
68
  import time
100
69
  from collections.abc import Iterator
101
70
  from contextlib import contextmanager
102
- from dataclasses import dataclass, field
103
71
  from pathlib import Path
104
72
 
105
- if sys.platform == "win32":
106
- import msvcrt
107
- else:
108
- import fcntl
109
-
110
73
  hooks_root_directory = str(Path(__file__).resolve().parent.parent)
111
74
  if hooks_root_directory not in sys.path:
112
75
  sys.path.insert(0, hooks_root_directory)
@@ -114,179 +77,53 @@ blocking_directory = str(Path(__file__).resolve().parent)
114
77
  if blocking_directory not in sys.path:
115
78
  sys.path.insert(0, blocking_directory)
116
79
 
117
- from atomic_file_writer import write_text_atomically
118
- from hooks_constants.atomic_file_writer_constants import ATOMIC_WRITE_TEMPORARY_SUFFIX
119
80
  from hooks_constants.hook_block_logger import log_hook_block
120
81
  from hooks_constants.hook_time_budget import call_timeout, remaining_seconds, time_budget
121
82
  from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
122
83
  from hooks_constants.session_file_id import session_file_id
123
84
  from hooks_constants.stop_hook_hold import hold_stop
124
- from hooks_constants.subprocess_window import hidden_window_creation_flags
125
85
  from hooks_constants.turn_review_gate_constants import (
126
- ALL_FINDING_STATUSES,
127
- ALL_LOG_PATH_PARTS,
128
- ALL_PARENT_SESSION_VARIABLES,
129
- ALL_REVIEW_ALLOWED_TOOLS,
130
- ALL_REVIEW_DISALLOWED_TOOLS,
131
- BASELINE_COMMIT_PATTERN,
132
- BLOCK_REASON_TEMPLATE,
133
- DISMISS_AT_CAP_DIAGNOSTIC_TEMPLATE,
134
- DISMISS_IGNORED_DIAGNOSTIC_TEMPLATE,
135
- FINDING_BASE_KEY,
136
- FINDING_DISMISSED_DIAGNOSTIC_TEMPLATE,
137
- FINDING_ID_PATTERN,
138
- FINDING_ID_TEMPLATE,
139
- FINDING_JUDGE_REASON_KEY,
140
- FINDING_LINE_WITH_ID_TEMPLATE,
141
- FINDING_REPOSITORY_KEY,
142
- FINDING_STATUS_DISMISSED,
143
- FINDING_STATUS_KEY,
144
- FINDING_STATUS_OPEN,
145
- FINDING_STATUS_UPHELD,
146
- FINDING_TEXT_KEY,
147
- FINDING_TURN_KEY,
148
- FINDING_UPHELD_DIAGNOSTIC_TEMPLATE,
149
- JUDGE_EFFORT,
150
- JUDGE_FAILURE_DIAGNOSTIC_TEMPLATE,
151
- JUDGE_MODEL_ALIAS,
152
- JUDGE_PROMPT_TEMPLATE,
153
- JUDGE_COMMIT_RANGE_TEMPLATE,
154
- JUDGE_DATA_INDENT,
155
- JUDGE_DATA_REQUESTS_KEY,
156
- JUDGE_DATA_USER_MESSAGES_KEY,
157
- JUDGE_ID_KEY,
158
- JUDGE_REQUEST_FINDING_KEY,
159
- JUDGE_REQUEST_RANGE_KEY,
160
- JUDGE_REQUEST_REASON_KEY,
161
- ALL_TRANSCRIPT_NOT_TYPED_FLAGS,
162
- MAXIMUM_USER_MESSAGE_CHARACTERS,
163
- NESTED_TOO_DEEP_REASON,
164
- TRANSCRIPT_HUMAN_ORIGIN_KIND,
165
- TRANSCRIPT_MARKUP_START,
166
- TRANSCRIPT_MESSAGE_ID_KEY,
167
- TRANSCRIPT_ORIGIN_KEY,
168
- TRANSCRIPT_ORIGIN_KIND_KEY,
169
- TRANSCRIPT_UNREADABLE_DIAGNOSTIC_TEMPLATE,
170
- TRANSCRIPT_USER_TYPE,
171
- USER_MESSAGE_COUNT,
172
- NO_VERDICT_DIAGNOSTIC_TEMPLATE,
173
- OUTSIDE_REPOSITORY_LABEL,
174
- REJECTION_LINE_SEPARATOR,
175
- REJECTION_LINE_TEMPLATE,
176
- REPLY_TEXT_KEY,
177
- SENTENCE_END_CHARACTERS,
178
- STATE_FINDINGS_KEY,
179
- TRANSCRIPT_ASSISTANT_TYPE,
180
- TRANSCRIPT_BLOCK_TYPE_KEY,
181
- TRANSCRIPT_CONTENT_KEY,
182
- TRANSCRIPT_ENTRY_TYPE_KEY,
183
- TRANSCRIPT_MESSAGE_KEY,
184
- TRANSCRIPT_PATH_KEY,
185
- TRANSCRIPT_TEXT_BLOCK_TYPE,
186
- TRANSCRIPT_TEXT_ENCODING,
187
- TRANSCRIPT_TEXT_KEY,
188
- TRANSCRIPT_TEXT_SEPARATOR,
189
- UNKNOWN_FINDING_LABEL,
190
- WAKE_PART_SEPARATOR,
191
- WORD_SEPARATOR,
192
- FINDING_LINE_SEPARATOR,
193
- GIT_DIRECTORY_NAME,
194
86
  HOOK_EVENT_NAME_KEY,
195
- LOG_LINE_TEMPLATE,
196
- LOG_TEXT_ENCODING,
197
- LOG_UNENCODABLE_HANDLER,
198
- MAXIMUM_BLOCKS_IN_A_ROW,
199
- MACHINE_PROMPT_PREFIX,
87
+ JUDGE_FAILURE_DIAGNOSTIC_TEMPLATE,
200
88
  MAXIMUM_TURN_FILES,
201
- PROJECT_DIRECTORY_ENVIRONMENT_VARIABLE,
89
+ MINIMUM_REVIEW_SECONDS,
90
+ NO_VERDICT_DIAGNOSTIC_TEMPLATE,
202
91
  PROMPT_EVENT_NAME,
203
92
  PROMPT_KEY,
204
- RACING_STOP_WINDOW_SECONDS,
205
93
  PROMPT_RUN_BUDGET_SECONDS,
206
- REPOSITORIES_ENVIRONMENT_VARIABLE,
207
- REPOSITORY_FINDINGS_SEPARATOR,
208
- REPOSITORY_FINDINGS_TEMPLATE,
209
- REPOSITORY_SEPARATOR,
210
94
  REVIEW_CHILD_ENVIRONMENT_VARIABLE,
211
95
  REVIEW_CHILD_MARKER,
212
- REVIEW_EFFORT,
213
96
  REVIEW_FAILURE_DIAGNOSTIC_TEMPLATE,
214
- REVIEW_MODEL_ALIAS,
215
- REVIEW_MODEL_EFFORT,
216
- REVIEW_PROMPT_TEMPLATE,
217
97
  REVIEW_RESULT_KEY,
218
- REVIEW_EXECUTABLE_NAME,
219
- REVIEW_SETTING_SOURCES_TEXT,
220
- REVIEW_SETTINGS_TEXT,
221
- MINIMUM_REVIEW_SECONDS,
222
98
  REVIEW_TIMEOUT_SECONDS,
223
- REVIEW_TOOLS_TEXT,
224
99
  RUN_DIAGNOSTIC_TEMPLATE,
225
100
  SESSION_ID_KEY,
226
- STATE_BASELINES_KEY,
227
- STATE_BLOCKS_KEY,
228
- STATE_FILE_TEMPLATE,
229
- STATE_OPEN_TURN_PROMPT_KEY,
230
- STATE_LAST_WAKE_KEY,
231
- STATE_TURN_OPEN_KEY,
232
101
  STATE_LOCK_BUSY_DIAGNOSTIC_TEMPLATE,
233
- STATE_LOCK_BYTE_COUNT,
234
102
  STATE_LOCK_FILE_MODE,
235
103
  STATE_LOCK_FILE_TEMPLATE,
236
104
  STATE_LOCK_OUTCOME_WAIT_SECONDS,
237
105
  STATE_LOCK_RETRY_SECONDS,
238
106
  STATE_LOCK_WAIT_SECONDS,
239
- STATE_SAVE_FAILURE_DIAGNOSTIC_TEMPLATE,
240
- STATE_TEMPORARY_PREFIX,
241
- STATE_TEXT_ENCODING,
242
107
  STOP_EVENT_NAME,
243
108
  STOP_HOOK_ACTIVE_KEY,
244
109
  STOP_RUN_BUDGET_SECONDS,
245
110
  TOO_MANY_FILES_DIAGNOSTIC_TEMPLATE,
246
- WAKE_PROMPT_WINDOW_SECONDS,
247
111
  )
248
- from pii_prevention_blocker_parts.repository_exemption import repository_origin_slug
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
+ )
249
122
  from turn_review_findings import JudgeVerdict, dismiss_requests, finding_lines, judge_verdicts
250
- from turn_review_snapshot import turn_changed_paths, working_tree_snapshot
251
-
252
- if sys.platform == "win32":
253
-
254
- def _try_file_lock(file_descriptor: int) -> None:
255
- os.lseek(file_descriptor, 0, os.SEEK_SET)
256
- msvcrt.locking(file_descriptor, msvcrt.LK_NBLCK, STATE_LOCK_BYTE_COUNT)
257
-
258
- def _release_file_lock(file_descriptor: int) -> None:
259
- os.lseek(file_descriptor, 0, os.SEEK_SET)
260
- msvcrt.locking(file_descriptor, msvcrt.LK_UNLCK, STATE_LOCK_BYTE_COUNT)
261
-
262
- else:
263
-
264
- def _try_file_lock(file_descriptor: int) -> None:
265
- fcntl.flock(file_descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
266
-
267
- def _release_file_lock(file_descriptor: int) -> None:
268
- fcntl.flock(file_descriptor, fcntl.LOCK_UN)
269
-
270
-
271
- def _log(diagnostic_text: str) -> None:
272
- timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
273
- try:
274
- log_path = Path.home().joinpath(*ALL_LOG_PATH_PARTS)
275
- log_path.parent.mkdir(parents=True, exist_ok=True)
276
- with log_path.open(
277
- "a", encoding=LOG_TEXT_ENCODING, errors=LOG_UNENCODABLE_HANDLER
278
- ) as log_file:
279
- log_file.write(LOG_LINE_TEMPLATE.format(timestamp=timestamp, text=diagnostic_text))
280
- except (OSError, RuntimeError):
281
- return
282
-
283
-
284
- def _is_lock_taken(file_descriptor: int) -> bool:
285
- try:
286
- _try_file_lock(file_descriptor)
287
- except OSError:
288
- return False
289
- return True
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
290
127
 
291
128
 
292
129
  def _acquire_with_wait(file_descriptor: int, wait_seconds: float) -> bool:
@@ -298,14 +135,6 @@ def _acquire_with_wait(file_descriptor: int, wait_seconds: float) -> bool:
298
135
  return True
299
136
 
300
137
 
301
- def _release_and_close(file_descriptor: int, is_locked: bool) -> None:
302
- try:
303
- if is_locked:
304
- _release_file_lock(file_descriptor)
305
- finally:
306
- os.close(file_descriptor)
307
-
308
-
309
138
  @contextmanager
310
139
  def _state_lock(session_id: object, wait_seconds: float) -> Iterator[bool]:
311
140
  lock_path = Path(tempfile.gettempdir()) / STATE_LOCK_FILE_TEMPLATE.format(
@@ -323,139 +152,6 @@ def _state_lock(session_id: object, wait_seconds: float) -> Iterator[bool]:
323
152
  _release_and_close(file_descriptor, is_locked)
324
153
 
325
154
 
326
- def _opted_in_repository_slugs() -> frozenset[str]:
327
- listed = os.environ.get(REPOSITORIES_ENVIRONMENT_VARIABLE, "")
328
- return frozenset(
329
- each.strip().casefold() for each in listed.split(REPOSITORY_SEPARATOR) if each.strip()
330
- )
331
-
332
-
333
- def _opted_in_repository_roots(all_slugs: frozenset[str]) -> list[Path]:
334
- project_directory = os.environ.get(PROJECT_DIRECTORY_ENVIRONMENT_VARIABLE, "")
335
- if not project_directory or not Path(project_directory).is_dir():
336
- return []
337
- project_path = Path(project_directory).resolve()
338
- all_candidates = [project_path, *sorted(_child_entries(project_path))]
339
- return [each for each in all_candidates if _is_opted_in_checkout(each, all_slugs)]
340
-
341
-
342
- def _child_entries(project_path: Path) -> list[Path]:
343
- try:
344
- return list(project_path.iterdir())
345
- except OSError:
346
- return []
347
-
348
-
349
- def _is_opted_in_checkout(folder: Path, all_slugs: frozenset[str]) -> bool:
350
- try:
351
- is_checkout = folder.is_dir() and (folder / GIT_DIRECTORY_NAME).exists()
352
- except OSError:
353
- return False
354
- return is_checkout and repository_origin_slug(folder) in all_slugs
355
-
356
-
357
- def _review_command(base_commit: str, turn_commit: str) -> list[str]:
358
- review_prompt = REVIEW_PROMPT_TEMPLATE.format(
359
- effort=REVIEW_EFFORT, base_commit=base_commit, turn_commit=turn_commit
360
- )
361
- return [
362
- shutil.which(REVIEW_EXECUTABLE_NAME) or REVIEW_EXECUTABLE_NAME,
363
- "-p",
364
- review_prompt,
365
- "--model",
366
- REVIEW_MODEL_ALIAS,
367
- "--effort",
368
- REVIEW_MODEL_EFFORT,
369
- *_read_only_child_options(),
370
- ]
371
-
372
-
373
- def _judge_command() -> list[str]:
374
- return [
375
- shutil.which(REVIEW_EXECUTABLE_NAME) or REVIEW_EXECUTABLE_NAME,
376
- "-p",
377
- "--model",
378
- JUDGE_MODEL_ALIAS,
379
- "--effort",
380
- JUDGE_EFFORT,
381
- *_read_only_child_options(),
382
- ]
383
-
384
-
385
- def _read_only_child_options() -> list[str]:
386
- return [
387
- "--output-format",
388
- "json",
389
- "--permission-mode",
390
- "dontAsk",
391
- "--setting-sources",
392
- REVIEW_SETTING_SOURCES_TEXT,
393
- "--tools",
394
- REVIEW_TOOLS_TEXT,
395
- "--no-session-persistence",
396
- "--allowedTools",
397
- *ALL_REVIEW_ALLOWED_TOOLS,
398
- "--disallowedTools",
399
- *ALL_REVIEW_DISALLOWED_TOOLS,
400
- "--settings",
401
- REVIEW_SETTINGS_TEXT,
402
- ]
403
-
404
-
405
- def _review_environment() -> dict[str, str]:
406
- all_child_environment_variables = {
407
- each_name: each_value
408
- for each_name, each_value in os.environ.items()
409
- if each_name not in ALL_PARENT_SESSION_VARIABLES
410
- }
411
- all_child_environment_variables[REVIEW_CHILD_ENVIRONMENT_VARIABLE] = REVIEW_CHILD_MARKER
412
- return all_child_environment_variables
413
-
414
-
415
- @dataclass(frozen=True)
416
- class _ChildRun:
417
- repository_root: Path
418
- all_command_parts: list[str]
419
- prompt_text: str | None
420
- failure_template: str
421
-
422
- def write_failure(self, failure_text: str) -> None:
423
- _log(
424
- self.failure_template.format(
425
- repository=self.repository_root.name, reason=failure_text
426
- )
427
- )
428
-
429
-
430
- def _child_stdout(child_run: _ChildRun, remaining_seconds: float) -> str | None:
431
- closed_stdin = subprocess.DEVNULL if child_run.prompt_text is None else None
432
- try:
433
- completed_process = subprocess.run(
434
- child_run.all_command_parts,
435
- check=False,
436
- capture_output=True,
437
- text=True,
438
- encoding="utf-8",
439
- errors="replace",
440
- timeout=remaining_seconds,
441
- cwd=str(child_run.repository_root),
442
- env=_review_environment(),
443
- creationflags=hidden_window_creation_flags(),
444
- stdin=closed_stdin,
445
- input=child_run.prompt_text,
446
- )
447
- except subprocess.TimeoutExpired:
448
- child_run.write_failure("timed out")
449
- return None
450
- except OSError as start_error:
451
- child_run.write_failure(str(start_error))
452
- return None
453
- if completed_process.returncode != 0:
454
- child_run.write_failure(f"exit {completed_process.returncode}")
455
- return None
456
- return completed_process.stdout
457
-
458
-
459
155
  def _child_result_text(child_run: _ChildRun, deadline: float) -> str | None:
460
156
  remaining_seconds = deadline - time.monotonic()
461
157
  if remaining_seconds < MINIMUM_REVIEW_SECONDS:
@@ -488,172 +184,6 @@ def _review_text(
488
184
  return _child_result_text(review_run, review_deadline)
489
185
 
490
186
 
491
- def _state_path(session_id: object) -> Path:
492
- return Path(tempfile.gettempdir()) / STATE_FILE_TEMPLATE.format(
493
- session_id=session_file_id(session_id)
494
- )
495
-
496
-
497
- @dataclass
498
- class _Finding:
499
- text: str
500
- repository: str
501
- base_commit: str
502
- turn_commit: str
503
- status: str = FINDING_STATUS_OPEN
504
- judge_reason: str | None = None
505
-
506
-
507
- @dataclass
508
- class _ReviewState:
509
- all_baselines: dict[str, str] = field(default_factory=dict)
510
- blocks_in_a_row: int = 0
511
- is_turn_open: bool = False
512
- last_wake_at: float | None = None
513
- open_turn_prompt_at: float | None = None
514
- all_findings: dict[str, _Finding] = field(default_factory=dict)
515
-
516
-
517
- def _saved_time(raw_value: object) -> float | None:
518
- if isinstance(raw_value, bool) or not isinstance(raw_value, (int, float)):
519
- return None
520
- return float(raw_value)
521
-
522
-
523
- def _is_commit_name(raw_value: object) -> bool:
524
- return isinstance(raw_value, str) and re.fullmatch(BASELINE_COMMIT_PATTERN, raw_value) is not None
525
-
526
-
527
- def _saved_finding(raw_entry: object) -> _Finding | None:
528
- if not isinstance(raw_entry, dict):
529
- return None
530
- text = raw_entry.get(FINDING_TEXT_KEY)
531
- repository = raw_entry.get(FINDING_REPOSITORY_KEY)
532
- base_commit = raw_entry.get(FINDING_BASE_KEY)
533
- turn_commit = raw_entry.get(FINDING_TURN_KEY)
534
- status = raw_entry.get(FINDING_STATUS_KEY)
535
- judge_reason = raw_entry.get(FINDING_JUDGE_REASON_KEY)
536
- if not (
537
- isinstance(text, str)
538
- and isinstance(repository, str)
539
- and _is_commit_name(base_commit)
540
- and _is_commit_name(turn_commit)
541
- and status in ALL_FINDING_STATUSES
542
- ):
543
- return None
544
- return _Finding(
545
- text,
546
- repository,
547
- str(base_commit),
548
- str(turn_commit),
549
- str(status),
550
- judge_reason if isinstance(judge_reason, str) else None,
551
- )
552
-
553
-
554
- def _saved_findings(raw_findings: object) -> dict[str, _Finding]:
555
- if not isinstance(raw_findings, dict):
556
- return {}
557
- all_findings: dict[str, _Finding] = {}
558
- for each_id, each_entry in raw_findings.items():
559
- saved_finding = _saved_finding(each_entry)
560
- if isinstance(each_id, str) and re.fullmatch(FINDING_ID_PATTERN, each_id) and saved_finding:
561
- all_findings[each_id] = saved_finding
562
- return all_findings
563
-
564
-
565
- def _finding_number(finding_id: str) -> int:
566
- id_match = re.fullmatch(FINDING_ID_PATTERN, finding_id)
567
- return int(id_match.group(1)) if id_match else 0
568
-
569
-
570
- def _next_finding_id(review_state: _ReviewState) -> str:
571
- highest_number = max(map(_finding_number, review_state.all_findings), default=0)
572
- return FINDING_ID_TEMPLATE.format(number=highest_number + 1)
573
-
574
-
575
- def _finding_record(finding: _Finding) -> dict[str, str | None]:
576
- return {
577
- FINDING_TEXT_KEY: finding.text,
578
- FINDING_REPOSITORY_KEY: finding.repository,
579
- FINDING_BASE_KEY: finding.base_commit,
580
- FINDING_TURN_KEY: finding.turn_commit,
581
- FINDING_STATUS_KEY: finding.status,
582
- FINDING_JUDGE_REASON_KEY: finding.judge_reason,
583
- }
584
-
585
-
586
- def _load_state(session_id: object) -> _ReviewState:
587
- try:
588
- saved_state = json.loads(_state_path(session_id).read_text(encoding=STATE_TEXT_ENCODING))
589
- except (OSError, ValueError):
590
- return _ReviewState()
591
- if not isinstance(saved_state, dict):
592
- return _ReviewState()
593
- raw_baselines = saved_state.get(STATE_BASELINES_KEY)
594
- all_baselines = {
595
- each_root: each_commit
596
- for each_root, each_commit in (
597
- raw_baselines.items() if isinstance(raw_baselines, dict) else []
598
- )
599
- if isinstance(each_root, str) and _is_commit_name(each_commit)
600
- }
601
- raw_blocks = saved_state.get(STATE_BLOCKS_KEY)
602
- return _ReviewState(
603
- all_baselines,
604
- raw_blocks if isinstance(raw_blocks, int) else 0,
605
- saved_state.get(STATE_TURN_OPEN_KEY) is True,
606
- _saved_time(saved_state.get(STATE_LAST_WAKE_KEY)),
607
- _saved_time(saved_state.get(STATE_OPEN_TURN_PROMPT_KEY)),
608
- _saved_findings(saved_state.get(STATE_FINDINGS_KEY)),
609
- )
610
-
611
-
612
- def _save_state(session_id: object, review_state: _ReviewState) -> None:
613
- try:
614
- write_text_atomically(
615
- _state_path(session_id),
616
- json.dumps(
617
- {
618
- STATE_BASELINES_KEY: review_state.all_baselines,
619
- STATE_BLOCKS_KEY: review_state.blocks_in_a_row,
620
- STATE_TURN_OPEN_KEY: review_state.is_turn_open,
621
- STATE_LAST_WAKE_KEY: review_state.last_wake_at,
622
- STATE_OPEN_TURN_PROMPT_KEY: review_state.open_turn_prompt_at,
623
- STATE_FINDINGS_KEY: {
624
- each_id: _finding_record(each_finding)
625
- for each_id, each_finding in review_state.all_findings.items()
626
- },
627
- }
628
- ),
629
- STATE_TEXT_ENCODING,
630
- STATE_TEMPORARY_PREFIX,
631
- ATOMIC_WRITE_TEMPORARY_SUFFIX,
632
- False,
633
- )
634
- except (OSError, UnicodeError) as save_error:
635
- _log(STATE_SAVE_FAILURE_DIAGNOSTIC_TEMPLATE.format(detail=save_error))
636
-
637
-
638
- def _is_wake_prompt(review_state: _ReviewState, prompt_text: object, now: float) -> bool:
639
- if isinstance(prompt_text, str) and prompt_text.lstrip().startswith(MACHINE_PROMPT_PREFIX):
640
- return True
641
- if review_state.last_wake_at is None:
642
- return False
643
- return now - review_state.last_wake_at < WAKE_PROMPT_WINDOW_SECONDS
644
-
645
-
646
- def _prompt_baselines(review_state: _ReviewState, all_roots: list[Path]) -> dict[str, str]:
647
- all_baselines = dict(review_state.all_baselines) if review_state.is_turn_open else {}
648
- for each_root in all_roots:
649
- if str(each_root) in all_baselines:
650
- continue
651
- snapshot_commit = working_tree_snapshot(each_root, None)
652
- if snapshot_commit is not None:
653
- all_baselines[str(each_root)] = snapshot_commit
654
- return all_baselines
655
-
656
-
657
187
  def _record_prompt_baselines(
658
188
  session_id: object, all_roots: list[Path], prompt_text: object
659
189
  ) -> None:
@@ -690,198 +220,6 @@ def _repository_findings(
690
220
  return finding_lines(review_text or "", all_changed_paths) or None
691
221
 
692
222
 
693
- @dataclass(frozen=True)
694
- class _JudgeRequest:
695
- finding_id: str
696
- finding: _Finding
697
- reason: str
698
-
699
-
700
- @dataclass(frozen=True)
701
- class _StopClaim:
702
- all_turn_ranges: list[tuple[Path, str, str]] = field(default_factory=list)
703
- all_judge_requests: list[_JudgeRequest] = field(default_factory=list)
704
-
705
-
706
- def _reversed_transcript_entries(hook_input: dict) -> Iterator[dict]:
707
- transcript_path = hook_input.get(TRANSCRIPT_PATH_KEY)
708
- if not isinstance(transcript_path, str) or not transcript_path:
709
- return
710
- try:
711
- all_transcript_lines = Path(transcript_path).read_text(
712
- encoding=TRANSCRIPT_TEXT_ENCODING, errors="replace"
713
- ).splitlines()
714
- except OSError:
715
- return
716
- for each_line in reversed(all_transcript_lines):
717
- try:
718
- transcript_entry = json.loads(each_line)
719
- except ValueError:
720
- continue
721
- except RecursionError:
722
- _log(TRANSCRIPT_UNREADABLE_DIAGNOSTIC_TEMPLATE.format(reason=NESTED_TOO_DEEP_REASON))
723
- continue
724
- if isinstance(transcript_entry, dict):
725
- yield transcript_entry
726
-
727
-
728
- class _ReversedTranscript:
729
- """The transcript's entries, newest first, with each line decoded once per stop."""
730
-
731
- def __init__(self, hook_input: dict) -> None:
732
- self._unread_entries = _reversed_transcript_entries(hook_input)
733
- self._all_read_entries: list[dict] = []
734
-
735
- def __iter__(self) -> Iterator[dict]:
736
- yield from self._all_read_entries
737
- for each_entry in self._unread_entries:
738
- self._all_read_entries.append(each_entry)
739
- yield each_entry
740
-
741
-
742
- def _entry_message(transcript_entry: dict) -> dict:
743
- message = transcript_entry.get(TRANSCRIPT_MESSAGE_KEY)
744
- return message if isinstance(message, dict) else {}
745
-
746
-
747
- def _entry_text(transcript_entry: dict) -> str:
748
- content = _entry_message(transcript_entry).get(TRANSCRIPT_CONTENT_KEY)
749
- if isinstance(content, str):
750
- return content.strip()
751
- if not isinstance(content, list):
752
- return ""
753
- return TRANSCRIPT_TEXT_SEPARATOR.join(
754
- each_block[TRANSCRIPT_TEXT_KEY]
755
- for each_block in content
756
- if isinstance(each_block, dict)
757
- and each_block.get(TRANSCRIPT_BLOCK_TYPE_KEY) == TRANSCRIPT_TEXT_BLOCK_TYPE
758
- and isinstance(each_block.get(TRANSCRIPT_TEXT_KEY), str)
759
- ).strip()
760
-
761
-
762
- def _is_assistant_entry(transcript_entry: dict) -> bool:
763
- return transcript_entry.get(TRANSCRIPT_ENTRY_TYPE_KEY) == TRANSCRIPT_ASSISTANT_TYPE
764
-
765
-
766
- def _last_assistant_message_text(transcript: _ReversedTranscript) -> str:
767
- all_text_parts: list[str] = []
768
- last_message_id: object = None
769
- for each_entry in transcript:
770
- is_first_assistant_entry = not all_text_parts and last_message_id is None
771
- if is_first_assistant_entry and not _is_assistant_entry(each_entry):
772
- continue
773
- message_id = _entry_message(each_entry).get(TRANSCRIPT_MESSAGE_ID_KEY)
774
- if not is_first_assistant_entry and (
775
- not _is_assistant_entry(each_entry) or message_id != last_message_id
776
- ):
777
- break
778
- all_text_parts.append(_entry_text(each_entry))
779
- if message_id is None:
780
- break
781
- last_message_id = message_id
782
- return TRANSCRIPT_TEXT_SEPARATOR.join(reversed(all_text_parts)).strip()
783
-
784
-
785
- def _reply_text(hook_input: dict, transcript: _ReversedTranscript) -> str:
786
- reply_text = hook_input.get(REPLY_TEXT_KEY)
787
- if isinstance(reply_text, str):
788
- return reply_text
789
- return _last_assistant_message_text(transcript)
790
-
791
-
792
- def _typed_user_text(transcript_entry: dict) -> str:
793
- if transcript_entry.get(TRANSCRIPT_ENTRY_TYPE_KEY) != TRANSCRIPT_USER_TYPE:
794
- return ""
795
- if any(transcript_entry.get(each_flag) for each_flag in ALL_TRANSCRIPT_NOT_TYPED_FLAGS):
796
- return ""
797
- origin = transcript_entry.get(TRANSCRIPT_ORIGIN_KEY)
798
- if (
799
- not isinstance(origin, dict)
800
- or origin.get(TRANSCRIPT_ORIGIN_KIND_KEY) != TRANSCRIPT_HUMAN_ORIGIN_KIND
801
- ):
802
- return ""
803
- typed_text = _entry_text(transcript_entry)
804
- return "" if typed_text.startswith(TRANSCRIPT_MARKUP_START) else typed_text
805
-
806
-
807
- def _typed_user_messages(transcript: _ReversedTranscript) -> list[str]:
808
- all_messages: list[str] = []
809
- for each_entry in transcript:
810
- typed_text = _typed_user_text(each_entry)
811
- if typed_text:
812
- all_messages.append(typed_text[:MAXIMUM_USER_MESSAGE_CHARACTERS])
813
- if len(all_messages) == USER_MESSAGE_COUNT:
814
- break
815
- return list(reversed(all_messages))
816
-
817
-
818
- def _judge_requests(
819
- review_state: _ReviewState,
820
- all_dismiss_reasons: dict[str, str],
821
- all_roots: list[Path],
822
- is_capped: bool,
823
- ) -> list[_JudgeRequest]:
824
- all_root_names = {str(each_root) for each_root in all_roots}
825
- all_requests: list[_JudgeRequest] = []
826
- for each_id, each_reason in all_dismiss_reasons.items():
827
- finding = review_state.all_findings.get(each_id)
828
- skip_diagnostic = _dismiss_skip_diagnostic(each_id, finding, all_root_names, is_capped)
829
- if skip_diagnostic is not None:
830
- _log(skip_diagnostic)
831
- continue
832
- if finding is not None:
833
- all_requests.append(_JudgeRequest(each_id, finding, each_reason))
834
- return all_requests
835
-
836
-
837
- def _dismiss_skip_diagnostic(
838
- finding_id: str, finding: _Finding | None, all_root_names: set[str], is_capped: bool
839
- ) -> str | None:
840
- if finding is None:
841
- return DISMISS_IGNORED_DIAGNOSTIC_TEMPLATE.format(
842
- finding_id=finding_id, status=UNKNOWN_FINDING_LABEL
843
- )
844
- if finding.status != FINDING_STATUS_OPEN:
845
- return DISMISS_IGNORED_DIAGNOSTIC_TEMPLATE.format(
846
- finding_id=finding_id, status=finding.status
847
- )
848
- if finding.repository not in all_root_names:
849
- return DISMISS_IGNORED_DIAGNOSTIC_TEMPLATE.format(
850
- finding_id=finding_id, status=OUTSIDE_REPOSITORY_LABEL
851
- )
852
- if is_capped:
853
- return DISMISS_AT_CAP_DIAGNOSTIC_TEMPLATE.format(finding_id=finding_id)
854
- return None
855
-
856
-
857
- def _claim_locked_stop(
858
- session_id: object, all_roots: list[Path], all_dismiss_reasons: dict[str, str]
859
- ) -> _StopClaim:
860
- review_state = _load_state(session_id)
861
- is_capped = review_state.blocks_in_a_row >= MAXIMUM_BLOCKS_IN_A_ROW
862
- all_judge_requests = _judge_requests(review_state, all_dismiss_reasons, all_roots, is_capped)
863
- all_next_baselines: dict[str, str] = {}
864
- all_turn_ranges: list[tuple[Path, str, str]] = []
865
- for each_root in all_roots:
866
- base_commit = review_state.all_baselines.get(str(each_root))
867
- turn_commit = working_tree_snapshot(each_root, base_commit)
868
- if turn_commit is None:
869
- continue
870
- all_next_baselines[str(each_root)] = turn_commit
871
- if base_commit is not None and base_commit != turn_commit and not is_capped:
872
- all_turn_ranges.append((each_root, base_commit, turn_commit))
873
- if not all_turn_ranges and not all_judge_requests and not is_capped:
874
- review_state.blocks_in_a_row = 0
875
- review_state.all_baselines = all_next_baselines
876
- review_state.is_turn_open = (
877
- review_state.open_turn_prompt_at is not None
878
- and time.time() - review_state.open_turn_prompt_at < RACING_STOP_WINDOW_SECONDS
879
- )
880
- review_state.open_turn_prompt_at = None
881
- _save_state(session_id, review_state)
882
- return _StopClaim(all_turn_ranges, all_judge_requests)
883
-
884
-
885
223
  def _claim_stop(
886
224
  session_id: object, all_roots: list[Path], all_dismiss_reasons: dict[str, str]
887
225
  ) -> _StopClaim:
@@ -892,31 +230,6 @@ def _claim_stop(
892
230
  return _claim_locked_stop(session_id, all_roots, all_dismiss_reasons)
893
231
 
894
232
 
895
- def _judge_prompt(
896
- repository_root: Path, all_requests: list[_JudgeRequest], all_user_messages: list[str]
897
- ) -> str:
898
- judge_data = {
899
- JUDGE_DATA_REQUESTS_KEY: [
900
- {
901
- JUDGE_ID_KEY: each_request.finding_id,
902
- JUDGE_REQUEST_RANGE_KEY: JUDGE_COMMIT_RANGE_TEMPLATE.format(
903
- base_commit=each_request.finding.base_commit,
904
- turn_commit=each_request.finding.turn_commit,
905
- ),
906
- JUDGE_REQUEST_FINDING_KEY: each_request.finding.text,
907
- JUDGE_REQUEST_REASON_KEY: each_request.reason,
908
- }
909
- for each_request in all_requests
910
- ],
911
- JUDGE_DATA_USER_MESSAGES_KEY: all_user_messages,
912
- }
913
- return JUDGE_PROMPT_TEMPLATE.format(
914
- repository=repository_root,
915
- user_message_characters=MAXIMUM_USER_MESSAGE_CHARACTERS,
916
- judge_data=json.dumps(judge_data, indent=JUDGE_DATA_INDENT, ensure_ascii=True),
917
- )
918
-
919
-
920
233
  def _repository_verdicts(
921
234
  repository_root: Path,
922
235
  all_requests: list[_JudgeRequest],
@@ -963,95 +276,6 @@ def _all_judge_verdicts(
963
276
  return all_verdicts
964
277
 
965
278
 
966
- def _one_line(judge_reason: str) -> str:
967
- return WORD_SEPARATOR.join(judge_reason.split())
968
-
969
-
970
- def _one_sentence(judge_reason: str) -> str:
971
- return _one_line(judge_reason).rstrip(SENTENCE_END_CHARACTERS)
972
-
973
-
974
- def _apply_verdicts(
975
- review_state: _ReviewState, all_verdicts: dict[str, JudgeVerdict]
976
- ) -> list[str]:
977
- all_rejection_lines: list[str] = []
978
- for each_id in sorted(all_verdicts, key=_finding_number):
979
- finding = review_state.all_findings.get(each_id)
980
- if finding is None or finding.status != FINDING_STATUS_OPEN:
981
- continue
982
- verdict = all_verdicts[each_id]
983
- finding.judge_reason = verdict.reason
984
- if verdict.is_approved:
985
- finding.status = FINDING_STATUS_DISMISSED
986
- _log(
987
- FINDING_DISMISSED_DIAGNOSTIC_TEMPLATE.format(
988
- finding_id=each_id, reason=_one_line(verdict.reason)
989
- )
990
- )
991
- continue
992
- finding.status = FINDING_STATUS_UPHELD
993
- _log(
994
- FINDING_UPHELD_DIAGNOSTIC_TEMPLATE.format(
995
- finding_id=each_id, reason=_one_line(verdict.reason)
996
- )
997
- )
998
- all_rejection_lines.append(
999
- REJECTION_LINE_TEMPLATE.format(
1000
- finding_id=each_id, reason=_one_sentence(verdict.reason)
1001
- )
1002
- )
1003
- return all_rejection_lines
1004
-
1005
-
1006
- def _record_new_findings(
1007
- review_state: _ReviewState, all_repository_findings: list[tuple[Path, str, str, list[str]]]
1008
- ) -> list[str]:
1009
- all_repository_blocks: list[str] = []
1010
- for each_root, each_base_commit, each_turn_commit, each_finding_lines in all_repository_findings:
1011
- all_lines_with_ids: list[str] = []
1012
- for each_line in each_finding_lines:
1013
- finding_id = _next_finding_id(review_state)
1014
- review_state.all_findings[finding_id] = _Finding(
1015
- each_line, str(each_root), each_base_commit, each_turn_commit
1016
- )
1017
- all_lines_with_ids.append(
1018
- FINDING_LINE_WITH_ID_TEMPLATE.format(finding_id=finding_id, finding=each_line)
1019
- )
1020
- all_repository_blocks.append(
1021
- REPOSITORY_FINDINGS_TEMPLATE.format(
1022
- repository=each_root.name,
1023
- findings=FINDING_LINE_SEPARATOR.join(all_lines_with_ids),
1024
- )
1025
- )
1026
- return all_repository_blocks
1027
-
1028
-
1029
- def _locked_stop_wake(
1030
- session_id: object,
1031
- all_repository_findings: list[tuple[Path, str, str, list[str]]],
1032
- all_verdicts: dict[str, JudgeVerdict],
1033
- ) -> str | None:
1034
- review_state = _load_state(session_id)
1035
- all_wake_parts: list[str] = []
1036
- all_rejection_lines = _apply_verdicts(review_state, all_verdicts)
1037
- if all_rejection_lines:
1038
- all_wake_parts.append(REJECTION_LINE_SEPARATOR.join(all_rejection_lines))
1039
- all_repository_blocks = _record_new_findings(review_state, all_repository_findings)
1040
- if all_repository_blocks:
1041
- all_wake_parts.append(
1042
- BLOCK_REASON_TEMPLATE.format(
1043
- all_findings=REPOSITORY_FINDINGS_SEPARATOR.join(all_repository_blocks)
1044
- )
1045
- )
1046
- if all_wake_parts:
1047
- review_state.blocks_in_a_row += 1
1048
- review_state.last_wake_at = time.time()
1049
- elif review_state.blocks_in_a_row < MAXIMUM_BLOCKS_IN_A_ROW:
1050
- review_state.blocks_in_a_row = 0
1051
- _save_state(session_id, review_state)
1052
- return WAKE_PART_SEPARATOR.join(all_wake_parts) or None
1053
-
1054
-
1055
279
  def _saved_stop_wake(
1056
280
  session_id: object,
1057
281
  all_repository_findings: list[tuple[Path, str, str, list[str]]],