claude-dev-env 8.121.0 → 8.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/bin/ever-registered-hooks.mjs +1 -0
  2. package/docs/rule-guides/question-presentation.md +4 -0
  3. package/hooks/blocking/closing_question_round_gate.py +387 -0
  4. package/hooks/blocking/closing_question_round_lines.py +109 -0
  5. package/hooks/blocking/closing_question_round_open_items.py +348 -0
  6. package/hooks/blocking/closing_question_round_transcript.py +344 -0
  7. package/hooks/blocking/sent_file_question_detector.py +340 -0
  8. package/hooks/blocking/sent_file_question_gate.py +307 -0
  9. package/hooks/blocking/sent_file_scan.py +209 -0
  10. package/hooks/blocking/test_closing_question_round_gate.py +983 -0
  11. package/hooks/blocking/test_closing_question_round_gate_declaration.py +307 -0
  12. package/hooks/blocking/test_closing_question_round_gate_work.py +349 -0
  13. package/hooks/blocking/test_closing_question_round_lines.py +70 -0
  14. package/hooks/blocking/test_closing_question_round_open_items.py +238 -0
  15. package/hooks/blocking/test_closing_question_round_transcript.py +236 -0
  16. package/hooks/blocking/test_sent_file_question_detector.py +68 -0
  17. package/hooks/blocking/test_sent_file_question_gate.py +688 -0
  18. package/hooks/blocking/test_sent_file_scan.py +71 -0
  19. package/hooks/blocking/test_user_step_wording.py +46 -0
  20. package/hooks/blocking/user_step_wording.py +113 -15
  21. package/hooks/features/conduct-gates.md +3 -0
  22. package/hooks/hooks.json +10 -0
  23. package/hooks/hooks_constants/closing_question_round_gate_constants.py +167 -0
  24. package/hooks/hooks_constants/sent_file_question_gate_constants.py +261 -0
  25. package/hooks/hooks_constants/test_closing_question_round_gate_constants.py +92 -0
  26. package/hooks/hooks_constants/user_step_wording_constants.py +4 -0
  27. package/package.json +1 -1
  28. package/scripts/policy_lint/adapter_configuration.py +5 -0
  29. package/scripts/policy_lint/config/constants.py +1 -0
  30. package/scripts/tests/test_adapter_configuration.py +8 -0
@@ -0,0 +1,71 @@
1
+ import time
2
+ from pathlib import Path
3
+
4
+ import sent_file_question_detector
5
+ import sent_file_scan
6
+
7
+
8
+ def test_sent_file_scan_text_should_join_the_start_and_end_of_a_large_file(tmp_path: Path) -> None:
9
+ file_path = tmp_path / "large.md"
10
+ file_path.write_text("A" * 200000 + "é" + "B" * 200000, encoding="utf-8")
11
+ scan_text = sent_file_scan.sent_file_scan_text("large.md", str(tmp_path))
12
+ assert scan_text is not None
13
+ head_text, tail_text = scan_text.split("\n\n")
14
+ assert head_text == "A" * 131072
15
+ assert tail_text.endswith("B" * 1000)
16
+ assert len(tail_text) <= 131072
17
+ assert sent_file_scan.sent_file_scan_text("small.md", str(tmp_path)) is None
18
+ (tmp_path / "small.md").write_text("Short note.\n", encoding="utf-8")
19
+ assert sent_file_scan.sent_file_scan_text("small.md", str(tmp_path)) == "Short note.\n"
20
+
21
+
22
+ def test_sent_file_scan_text_should_skip_a_file_that_is_not_utf8_text(tmp_path: Path) -> None:
23
+ (tmp_path / "nul.md").write_bytes(b"Note\x00text")
24
+ (tmp_path / "latin.md").write_bytes(b"Caf\xe9 notes")
25
+ (tmp_path / "shot.png").write_text("Should I?", encoding="utf-8")
26
+ assert sent_file_scan.sent_file_scan_text("nul.md", str(tmp_path)) is None
27
+ assert sent_file_scan.sent_file_scan_text("latin.md", str(tmp_path)) is None
28
+ assert sent_file_scan.sent_file_scan_text("shot.png", str(tmp_path)) is None
29
+
30
+
31
+ def test_sent_file_is_partly_read_should_name_only_a_text_file_over_the_limit(
32
+ tmp_path: Path,
33
+ ) -> None:
34
+ (tmp_path / "large.md").write_text("A" * 262145, encoding="utf-8")
35
+ (tmp_path / "limit.md").write_text("A" * 262144, encoding="utf-8")
36
+ (tmp_path / "large.png").write_bytes(b"A" * 262145)
37
+ assert sent_file_scan.sent_file_is_partly_read("large.md", str(tmp_path)) is True
38
+ assert sent_file_scan.sent_file_is_partly_read("limit.md", str(tmp_path)) is False
39
+ assert sent_file_scan.sent_file_is_partly_read("large.png", str(tmp_path)) is False
40
+ assert sent_file_scan.sent_file_is_partly_read("missing.md", str(tmp_path)) is False
41
+
42
+
43
+ def test_plain_page_text_should_strip_tags_in_one_pass() -> None:
44
+ page_markup = (
45
+ "<h2>Plan</h2><p>Should I <b>merge</b> it?</p>"
46
+ "<script>var x = 'Do you want this?';</script><pre>Can I go?</pre><p>A &amp; B</p>"
47
+ )
48
+ plain_text = sent_file_scan.plain_page_text(page_markup)
49
+ assert "# Plan" in plain_text
50
+ assert "Should I merge it?" in plain_text
51
+ assert "Do you want this?" not in plain_text
52
+ assert "Can I go?" not in plain_text
53
+ assert "A & B" in plain_text
54
+ assert (
55
+ sent_file_question_detector.question_for_user(plain_text, is_html=False)
56
+ == "Should I merge it?"
57
+ )
58
+
59
+
60
+ def test_plain_page_text_should_read_unclosed_script_openers_in_linear_time() -> None:
61
+ started_at = time.perf_counter()
62
+ plain_text = sent_file_scan.plain_page_text("<p>Should I merge it?</p>" + "<script " * 30000)
63
+ assert time.perf_counter() - started_at < 1
64
+ assert "Should I merge it?" in plain_text
65
+
66
+
67
+ def test_plain_page_text_should_mark_a_checkbox_as_a_task_box() -> None:
68
+ plain_text = sent_file_scan.plain_page_text(
69
+ '<ul><li><input type="checkbox"> Did you run the tests?</li></ul>'
70
+ )
71
+ assert "- [ ] Did you run the tests?" in plain_text
@@ -479,3 +479,49 @@ def test_should_never_open_a_sent_path_that_is_no_regular_file_or_cannot_be_a_pa
479
479
  assert user_step_wording.file_waiting_phrase(str(folder_path), None) is None
480
480
  assert user_step_wording.file_waiting_phrase("status\x00.md", str(tmp_path)) is None
481
481
  assert all_opened_paths == []
482
+
483
+
484
+ def test_html_text_blocks_should_mark_each_shown_heading() -> None:
485
+ page_markup = "<h2>Open questions</h2><p>Run <code>x</code> now.</p><script><h3>hidden</h3></script>"
486
+ assert user_step_wording.html_text_blocks(page_markup, "# ") == ["# Open questions", "Run  now."]
487
+
488
+
489
+ def test_html_text_blocks_should_leave_headings_unmarked_with_an_empty_mark() -> None:
490
+ assert user_step_wording.html_text_blocks("<h1>Status</h1><p>Done.</p>", "") == ["Status", "Done."]
491
+
492
+
493
+ def test_sent_file_text_should_read_a_relative_text_file_and_skip_other_suffixes(tmp_path: Path) -> None:
494
+ (tmp_path / "notes.md").write_bytes(b"Status: green \xff")
495
+ (tmp_path / "shot.png").write_text("Should I?", encoding="utf-8")
496
+ assert user_step_wording.sent_file_text("notes.md", str(tmp_path)) == "Status: green �"
497
+ assert user_step_wording.sent_file_text("shot.png", str(tmp_path)) is None
498
+ assert user_step_wording.sent_file_text("missing.md", str(tmp_path)) is None
499
+
500
+
501
+ def test_is_html_file_path_should_match_html_suffixes_in_any_case() -> None:
502
+ assert [
503
+ user_step_wording.is_html_file_path(each_path) for each_path in ("a.HTML", "b.htm", "c.md", "d.html.txt")
504
+ ] == [True, True, False, False]
505
+
506
+
507
+ def test_sent_file_location_should_resolve_a_relative_text_file_and_skip_the_rest(tmp_path: Path) -> None:
508
+ (tmp_path / "notes.md").write_text("Status: green", encoding="utf-8")
509
+ (tmp_path / "shot.png").write_text("Should I?", encoding="utf-8")
510
+ (tmp_path / "folder.md").mkdir()
511
+ assert user_step_wording.sent_file_location("notes.md", str(tmp_path)) == tmp_path / "notes.md"
512
+ assert user_step_wording.sent_file_location("shot.png", str(tmp_path)) is None
513
+ assert user_step_wording.sent_file_location("folder.md", str(tmp_path)) is None
514
+ assert user_step_wording.sent_file_location("missing.md", str(tmp_path)) is None
515
+
516
+
517
+ def test_html_text_blocks_should_mark_a_checkbox_with_the_task_box_mark() -> None:
518
+ page_markup = '<ul><li><input type="checkbox"/> Saved?</li><li><input type="text"> Name</li></ul>'
519
+ assert user_step_wording.html_text_blocks(page_markup, "# ", task_box_mark="- [ ] ") == [
520
+ "- [ ] Saved?",
521
+ "Name",
522
+ ]
523
+
524
+
525
+ def test_html_text_blocks_should_mark_a_summary_label_as_a_heading() -> None:
526
+ page_markup = "<details><summary>Can I use it offline?</summary><p>After a sync.</p></details>"
527
+ assert user_step_wording.html_text_blocks(page_markup, "# ") == ["# Can I use it offline?", "After a sync."]
@@ -158,6 +158,7 @@ from hooks_constants.user_step_wording_constants import (
158
158
  ALL_CLAUSE_OPENING_NEGATORS,
159
159
  ALL_CONTRACTED_NEGATOR_ENDINGS,
160
160
  ALL_HTML_FILE_SUFFIXES,
161
+ ALL_HTML_HEADING_TAGS,
161
162
  ALL_HTML_HIDDEN_TAGS,
162
163
  ALL_HTML_INLINE_TAGS,
163
164
  ALL_INSTRUCTION_OPENERS,
@@ -173,6 +174,9 @@ from hooks_constants.user_step_wording_constants import (
173
174
  CODE_SPAN_STAND_IN,
174
175
  EMPHASIS_MARKS,
175
176
  HTML_BLOCK_SEPARATOR,
177
+ HTML_CHECKBOX_INPUT_TYPE,
178
+ HTML_INPUT_TAG,
179
+ HTML_INPUT_TYPE_ATTRIBUTE,
176
180
  HTML_LINE_BREAK_TAG,
177
181
  HTML_LITERAL_STAND_IN_TEXT,
178
182
  HTML_SOURCE_SPACE,
@@ -298,11 +302,21 @@ def _first_waiting_phrase(all_blocks: Iterable[str]) -> str | None:
298
302
  return next((each_phrase for each_phrase in all_phrases if each_phrase is not None), None)
299
303
 
300
304
 
305
+ def _is_checkbox(all_attributes: list[tuple[str, str | None]]) -> bool:
306
+ return any(
307
+ each_name == HTML_INPUT_TYPE_ATTRIBUTE
308
+ and (each_value or "").strip().lower() == HTML_CHECKBOX_INPUT_TYPE
309
+ for each_name, each_value in all_attributes
310
+ )
311
+
312
+
301
313
  class _VisibleTextParser(HTMLParser):
302
- def __init__(self) -> None:
314
+ def __init__(self, heading_mark: str, task_box_mark: str) -> None:
303
315
  super().__init__(convert_charrefs=True)
304
316
  self.all_text_runs: list[str] = []
305
317
  self.hidden_depth = 0
318
+ self.heading_mark = heading_mark
319
+ self.task_box_mark = task_box_mark
306
320
 
307
321
  def handle_starttag(self, tag: str, all_attributes: list[tuple[str, str | None]]) -> None:
308
322
  if tag in ALL_HTML_HIDDEN_TAGS:
@@ -313,11 +327,15 @@ class _VisibleTextParser(HTMLParser):
313
327
  self.all_text_runs.append(LINE_BREAK)
314
328
  elif tag not in ALL_HTML_INLINE_TAGS:
315
329
  self.all_text_runs.append(HTML_BLOCK_SEPARATOR)
330
+ if tag in ALL_HTML_HEADING_TAGS and not self.hidden_depth:
331
+ self.all_text_runs.append(self.heading_mark)
332
+ if tag == HTML_INPUT_TAG and not self.hidden_depth and _is_checkbox(all_attributes):
333
+ self.all_text_runs.append(self.task_box_mark)
316
334
 
317
335
  def handle_endtag(self, tag: str) -> None:
318
336
  if tag in ALL_HTML_HIDDEN_TAGS and self.hidden_depth:
319
337
  self.hidden_depth -= 1
320
- if tag != HTML_LINE_BREAK_TAG and tag not in ALL_HTML_INLINE_TAGS:
338
+ if tag not in {HTML_LINE_BREAK_TAG, HTML_INPUT_TAG} and tag not in ALL_HTML_INLINE_TAGS:
321
339
  self.all_text_runs.append(HTML_BLOCK_SEPARATOR)
322
340
 
323
341
  def handle_data(self, data: str) -> None:
@@ -345,38 +363,118 @@ def html_visible_text(page_markup: str) -> str:
345
363
  return _html_text_with_code_marks(page_markup).replace(CODE_SPAN_STAND_IN, "")
346
364
 
347
365
 
348
- def _html_text_with_code_marks(page_markup: str) -> str:
349
- text_parser = _VisibleTextParser()
366
+ def _html_text_with_code_marks(
367
+ page_markup: str, heading_mark: str = "", task_box_mark: str = ""
368
+ ) -> str:
369
+ text_parser = _VisibleTextParser(heading_mark, task_box_mark)
350
370
  text_parser.feed(page_markup)
351
371
  text_parser.close()
352
372
  return "".join(text_parser.all_text_runs)
353
373
 
354
374
 
355
- def file_waiting_phrase(file_path_text: str, working_directory: object) -> str | None:
356
- """Return the first waiting phrase in a text file the turn sent to the user, or None.
375
+ def html_text_blocks(page_markup: str, heading_mark: str, task_box_mark: str = "") -> list[str]:
376
+ """Return the shown text of an HTML page as blocks, with a mark before each heading.
377
+
378
+ ::
379
+
380
+ <h2>Open questions</h2><p>Pick one.</p> with "# " -> ["# Open questions", "Pick one."]
381
+ <p>Run <code>x</code> now.</p> -> ["Run \\ufffc now."]
382
+ <li><input type="checkbox"> Saved?</li> with "- [ ] " -> ["- [ ] Saved?"]
383
+
384
+ The blocks are the ones ``file_waiting_phrase`` reads. The text of a code
385
+ element stays as the object replacement character.
386
+
387
+ Args:
388
+ page_markup: The HTML source of the page.
389
+ heading_mark: The text put before the text of each h1 to h6 element.
390
+ task_box_mark: The text put where a checkbox ``input`` element sits.
391
+
392
+ Returns:
393
+ Each block that holds shown text, with the white space at its ends removed.
394
+ """
395
+ all_blocks = _html_text_with_code_marks(page_markup, heading_mark, task_box_mark).split(
396
+ HTML_BLOCK_SEPARATOR
397
+ )
398
+ return [each_block.strip() for each_block in all_blocks if each_block.strip()]
399
+
400
+
401
+ def is_html_file_path(file_path_text: str) -> bool:
402
+ """Return True when the path ends in .html or .htm, in any letter case.
403
+
404
+ >>> is_html_file_path("page.HTML")
405
+ True
406
+ >>> is_html_file_path("notes.md")
407
+ False
408
+ """
409
+ return Path(file_path_text).suffix.lower() in ALL_HTML_FILE_SUFFIXES
410
+
411
+
412
+ def sent_file_location(file_path_text: str, working_directory: object) -> Path | None:
413
+ """Return the regular Markdown, text, or HTML file a sent path names, or None.
414
+
415
+ ::
416
+
417
+ "notes.md" with cwd "/work" -> Path("/work/notes.md"), when it is a file
418
+ "/tmp/shot.png" -> None
419
+
420
+ A path that is not absolute is resolved from the working directory. A path
421
+ with another suffix, and a path that is no regular file (a pipe, a device,
422
+ a directory, a missing file), give None.
423
+ """
424
+ file_path = Path(file_path_text)
425
+ if not file_path.is_absolute() and isinstance(working_directory, str):
426
+ file_path = Path(working_directory) / file_path
427
+ if file_path.suffix.lower() not in ALL_SENT_TEXT_FILE_SUFFIXES:
428
+ return None
429
+ try:
430
+ return file_path if file_path.is_file() else None
431
+ except (OSError, ValueError):
432
+ return None
433
+
434
+
435
+ def sent_file_text(file_path_text: str, working_directory: object) -> str | None:
436
+ """Return the text of a Markdown, text, or HTML file sent to the user, or None.
437
+
438
+ ::
439
+
440
+ "notes.md" with cwd "/work" -> the text of /work/notes.md
441
+ "/tmp/page.html" -> the page source
442
+ "/tmp/shot.png" -> None
357
443
 
358
444
  A path that is not absolute is read from the working directory. A file with
359
445
  another suffix, a path that is no regular file (a pipe, a device, a
360
446
  directory), a file over the size limit, and a file that cannot be read give
361
447
  None. The read stops one byte past the size limit.
448
+
449
+ Args:
450
+ file_path_text: The path the tool call names.
451
+ working_directory: The session's ``cwd`` from the hook payload.
452
+
453
+ Returns:
454
+ The file text decoded as UTF-8 with bad bytes replaced, or None.
362
455
  """
363
- file_path = Path(file_path_text)
364
- if not file_path.is_absolute() and isinstance(working_directory, str):
365
- file_path = Path(working_directory) / file_path
366
- file_suffix = file_path.suffix.lower()
367
- if file_suffix not in ALL_SENT_TEXT_FILE_SUFFIXES:
456
+ file_path = sent_file_location(file_path_text, working_directory)
457
+ if file_path is None:
368
458
  return None
369
459
  try:
370
- if not file_path.is_file():
371
- return None
372
460
  with file_path.open(BINARY_READ_MODE) as sent_file:
373
461
  file_bytes = sent_file.read(MAXIMUM_SENT_FILE_BYTES + 1)
374
462
  except (OSError, ValueError):
375
463
  return None
376
464
  if len(file_bytes) > MAXIMUM_SENT_FILE_BYTES:
377
465
  return None
378
- file_text = file_bytes.decode(UTF8_ENCODING, errors=DECODE_ERRORS_POLICY)
379
- if file_suffix in ALL_HTML_FILE_SUFFIXES:
466
+ return file_bytes.decode(UTF8_ENCODING, errors=DECODE_ERRORS_POLICY)
467
+
468
+
469
+ def file_waiting_phrase(file_path_text: str, working_directory: object) -> str | None:
470
+ """Return the first waiting phrase in a text file the turn sent to the user, or None.
471
+
472
+ The file is read through ``sent_file_text``, so each file it skips gives None.
473
+ """
474
+ file_text = sent_file_text(file_path_text, working_directory)
475
+ if file_text is None:
476
+ return None
477
+ if is_html_file_path(file_path_text):
380
478
  all_blocks = _html_text_with_code_marks(file_text).split(HTML_BLOCK_SEPARATOR)
381
479
  return _first_waiting_phrase(
382
480
  each_reading for each_block in all_blocks for each_reading in (each_block, each_block.replace(CODE_SPAN_STAND_IN, ""))
@@ -24,6 +24,7 @@ This family stops a chat reply, edited message, or tool call when its payload br
24
24
  - `blocking/merge_review_gate.py` denies an agent's merge until a review pass on the merged head reported zero findings, or ruled out every finding and linked the posted rulings. It reads the receipt `scripts/merge_review_receipt.py` writes, requires the merge, auto-merge or merge-queue entry to be pinned to that head, and skips repositories listed in `CLAUDE_MERGE_REVIEW_EXEMPT_REPOSITORIES`. A `gh pr merge` call whose every merge segment carries `--disable-auto` only turns auto-merge off, so it passes. A segment that also carries `--auto`, gives `--auto` or `--disable-auto` an `=` value, joins short flags such as `-sb`, or holds a bare `--` keeps every check. Its deny reason names the review command `CLAUDE_MERGE_REVIEW_COMMAND` sets. The reason tells the agent to run that command for the first three passes and `/code-review low --fix <number>` for each later pass; the gate itself counts no passes. It also denies a pull request open, through a shell create or a `create_pull_request` tool, until a pass recorded as `merge_review_receipt.py <owner/name> open <head> 0` covers the head the pull request opens with. A shell create is any spelling the shared listing in `blocking/followup_pr_dedupe.py` reads: `gh pr create`, `gh pr new`, `gh` with a root `-R` or `--repo` before `pr`, a `GH_REPO=` prefix, and `pull_request.py create` run by any `python`, `python3.x`, `py` or `uv run` launcher, with interpreter options or a path to the script. A command that chains several creates is checked create by create, in command order, and the deny names the first head with no clean pass. Each create reads its repository as gh does: among every `-R`, `--repo`, `--repo=`, `-R=` or clustered `-dR` flag before or after `pr`, the last one decides, and a flag word that is the value of another option, such as `--title --repo=x/y`, is not a flag. `blocking/merge_review_gate_parts/create_options.py` reads each value as gh does: an option that takes a value takes the next word, so `--title -Hx` and `--body -H --title x` name no head, and in a short cluster such as `-bHx` the first letter that takes a value takes the rest of the cluster. With no flag it reads the last `GH_REPO=` prefix, then the origin remote. A wrapper such as `env -u GH_REPO`, `env -i` or `sudo` can drop the prefix before gh runs, as in `GH_REPO=o/r env -u GH_REPO gh pr create`, where gh opens in the origin repository. So every create the walk reaches whose repository comes only from a `GH_REPO=` prefix needs a clean pass for the prefix repository and for origin, also when the prefix value names no repository, and its deny for origin says to name the repository with `--repo owner/name` on the create. The walk steps over `env`, `sudo` and `timeout` with their options, and over the launchers `nohup`, `nice`, `stdbuf`, `setsid` and `time` when each launcher option holds its value in the same word or takes a number, as in `stdbuf -o0` or `nice -n 5`. It also reads a create behind `command` or `exec`, as in `command env -u GH_REPO` or `exec nohup env -u GH_REPO`. A create after the first one is not read behind a program the walk does not step over, such as `ionice`, `flock` or `doas`, or behind a launcher option with a separate value that is not a number, such as `stdbuf -o L` or `time -o out.txt`. A create that passes `--repo owner/name` needs a pass for that repository only. Two creates with the same options stay two checks when one has a prefix and the other does not. The first create in a command is also read the way the gate read it before it walked every create: its repository comes from a `--repo` flag or the origin remote, never from a prefix. A `GH_REPO+=` append, in a create's own prefix or anywhere else in the command, counts as a set whose value the gate cannot read. When the command sets `GH_REPO` anywhere outside a create's own prefix, through an assignment before another program, such as `GH_REPO=o/r bash -c ...`, or through an `export`, `declare`, `typeset`, `local` or `readonly` word that names `GH_REPO`, each create that names no repository flag and no `GH_REPO=` prefix of its own is denied as unread, and the reason says to pass `--repo owner/name`. The gate does not follow where that value reaches. `blocking/followup_pr_dedupe.py` reads the same condition through the same `sets_gh_repository` helper and refuses such a follow-up create, with a reason that says to name the repository with `--repo`. For a follow-up create whose repository comes only from a `GH_REPO=` prefix, it reads the open pull requests of the prefix repository and of the origin remote, since a wrapper can drop the prefix; a prefix value that names no repository, such as `GH_REPO=nonsense`, still gets the origin read, and a deny from the origin read opens with the sentence to name the repository with `--repo owner/name`; when the origin remote names no GitHub repository it reads the prefix repository only. A duplicate found in origin that way is refused with a reason that says to name the repository with `--repo owner/name` on the create, and a create that names its repository with its own `--repo` reads that repository only. Each head it names through `-H x`, `-Hx`, `-H=x`, `--head x`, `--head=x` or a cluster of short flags such as `-dHx`, `-dH x` or `-fH=x` gets its own check, also a head a later head flag overrides, as gh reads each one. A create that names no head reads `HEAD`. The first-create reading takes a head only from `-H x`, `--head x` or their `=` forms, so a create that gives its head as `-Hx` is also checked on `HEAD`; name the head with `--head` when the working folder is on another branch. `blocking/merge_review_gate_parts/create_folders.py` walks the command to give each create its folder, and `blocking/merge_review_gate_parts/folder_state.py` holds that folder, whether it is followed, and the `pushd` stack. The walk follows `cd`, `chdir`, `Set-Location`, `pushd` and `popd`, also after `builtin` or `command`; the end of a subshell, back to the folder in effect when that subshell opened, also when nested subshells close together on one line or across line breaks; and `eval`, which changes the folder of its own shell. A create inside `bash -c`, `sh -c` or a command substitution runs in the folder before it, also when a line break inside the script comes before it. A `cd` in a background job stays in that job. The walk does not model a folder change in a pipeline member, a brace group, `if`, `case`, `for`, `while`, `until`, `select` or a function body, a folder change after a redirect, or a folder word anywhere but the program place. Each later create in that scope is denied as unreadable. So is each create after a folder the walk cannot name, such as `cd "$VAR"`, `cd -` or a glob, and each create after a folder change the walk cannot follow, such as `popd` with nothing pushed, in any wrapper. A create in a folder that does not exist gets no git answer and is denied as unreadable. Text nested past 16 levels of `bash -c`, `eval` or substitution that names `gh` and a `create` or `new` word, or names `pull_request.py`, gives one create whose folder is not followed, so it is denied as unread. `blocking/merge_review_gate_parts/quoted_lines.py` cuts the text into lines and words as bash reads its quotes: `\"` inside a double-quoted value does not end the value, an ANSI-C `$'...'` value is one word, and a line break ends a command only outside quotes, subshells and substitutions. So the walk reads no command in a heredoc body or in a quoted option value, such as `--body "a; gh pr create --head x"`, with or without a line break inside it. It does read the script that `bash -c`, `sh -c`, `pwsh -Command`, `eval` or `Invoke-Expression` gets, line breaks included, and each `$(...)` or backtick substitution, also one inside a double-quoted value, such as `--body "$(gh pr create --head x)"`, since bash runs those. It reads no substitution bash does not run: one inside single quotes, such as `--body '$(gh pr create --head x)'` or `echo '$(gh pr create --head x)'`, or one whose `$(` or backtick a backslash escapes, such as `echo \$(gh pr create --head x)`. It reads `eval`'s words joined by spaces, as bash does, so `eval 'gh pr create --body "a b"'` is one create, and it reads the words after the last `)` inside a segment, such as the command of a `case` arm, as a create and as a wrapper. A command whose quotes do not close is read both ways the earlier walk read it, POSIX and raw words, as written and with its quoted line breaks joined. `blocking/merge_review_gate_parts/wrapped_creates.py` reads each wrapped inner text once more in POSIX words and gives a create the walk did not place as one whose folder is not followed; it skips the command itself, each closed text with its line breaks read as spaces, and each text unwrapped from one, so a heredoc body inside `--body "$(cat <<'B' ...)"` runs no command and `bash -c 'gh pr create\nls'` is one create. The gate also keeps the earlier first-create reading: the first `gh pr create` or `pull_request.py create` the raw text spells outside `--title`, `--body` and `--body-file` values, in the folder of the last `cd`, `pushd`, `Set-Location` or `sl` before it, with its first `--repo` and its first `-H` or `--head` given with a space or `=`. That reading is one more check unless a walk check equals it. So these are checked on the head that first create names: `echo gh pr create --head x | bash`; a create in a heredoc fed to `bash` or `.`; and the first create words after `;`, `&&`, `||` or `|` inside a quoted value, such as a `git commit -m` message. Beyond that first-create reading, the gate does not read: a create a shell gets through its input, a here-string, a heredoc, a process substitution such as `bash <(echo ...)` or a script file; a create in a command string that a program other than `bash`, `sh`, `pwsh`, `powershell`, `cmd /c`, `eval`, `Invoke-Expression`, `find -exec`, `xargs` or `Start-Process` runs, such as `zsh -c`, `su -c`, `ssh`, `watch`, `python -c` or a git alias; or a program name that a variable, alias or function holds. These forms are read in part. A `case` arm inside a double-quoted substitution, such as `--body "$(case x in x) gh pr create ;; esac)"`, is cut at the arm's `)`, so its create is not read. An arithmetic `<<` followed by a word, such as `$((1<<x))`, opens a heredoc for the walk, so the lines after it up to a line `x` are not read; the first-create reading still checks the first create in the raw text. A substitution in an unquoted heredoc body fed to a plain command such as `cat` is not walked; the first-create reading checks the first create there with the closing `)` kept in its head, so that head is unreadable and denied. A create in a heredoc fed to `.` or `bash` is checked only through the first-create reading: it reads `--repo` and a `--head` or `-H` given with a space or `=`, checks a `-Hx` or clustered head as `HEAD`, and does not read a create after the first. The words of a quoted option value are not commands, so a create in one is not read and needs no review. Once the gate knows the call opens or merges a pull request, a check that raises denies the call with the fault reason, which names the error type. A payload read that raises is denied the same way for a `create_pull_request`, `merge_pull_request` or `enable_pr_auto_merge` tool, and for a shell command whose text holds the word `gh` and a `create`, `new` or `merge` word anywhere, or names `pull_request.py`. Any other payload read fault goes to the shared helper. A call that opens and merges nothing gets no such deny. An open pass also counts when every finding is ruled out: `merge_review_receipt.py <owner/name> open <head> <count> --ruled-out <count> --rulings <path:line,...>`, with a different `path:line` for each finding, checked against the file at that head when the pass is recorded. A merge pinned to that same head passes on the open receipt only when the pass found zero findings.
25
25
  - `blocking/artifact_dark_mode_gate.py` denies an Artifact page publish when the page, inside the publish wrapper, keeps a light body or shows text under 4.5:1 contrast in dark mode. `blocking/artifact_dark_mode_render.cjs` renders the page in headless Chromium for it.
26
26
  - `blocking/send_user_file_worktree_root_gate.py` denies a `SendUserFile` call that names a file outside the session's working directory, the `cwd` in the hook payload. The desktop file pane opens a sent file only under that folder and shows "Couldn't find this file" for any other path. The reason lists each outside file and names `<cwd>\.scratch\` as the folder to copy it into.
27
+ - `blocking/sent_file_question_gate.py` denies a `SendUserFile` call or an `Artifact` page publish when a Markdown, text, or HTML file it sends asks the user a question. A question is a heading that opens a question or decision section, such as "Open questions" or "Decisions needed", or a sentence that ends with a question mark (or a full-width one) and names the reader, opens with a request such as "Should I", "Can I", "Thoughts", or "Proceed", asks what works best ("What release date works best?"), or offers a choice with "or". A heading such as "Need your input" also counts, as do a heading that asks the reader something with no paragraph below it ("## Which works best?"), a question heading in the writer's or the reader-addressed voice whatever follows it ("## What should I do next?", with should I or we, shall I or we, do, would, will, or can you, want me, your, or prefer), a sentence that asks for a reply on its own ("Let me know which you prefer.", "Send me your pick."), and a sentence that opens with reply, answer, respond, choose, pick, select, or decide and offers yes or no, one of two or of these, or a choice between one-letter, one-digit, or "option" labels ("Choose A or B."); a reply verb after "please" or a comma that offers yes or no ("Please answer yes or no.") counts too; "Select one or more archives." and "Choose Color or Image." are steps and pass. A sentence or heading over 2,000 characters is read through its first and last 400 characters. Reader-voice and subject headings such as "## Can I run it offline?" and "## Why does this exist?" with a paragraph below them, `summary` and `dt` labels with a paragraph below them, quotes, fenced and indented code, a question the next sentence answers with yes or no, a question that asks for no wish or go-ahead with a statement after it, such as a frequently asked question and its answer, a checklist item that asks whether the reader did a piece of work ("- [ ] Did you run the tests?" with a task box or beside another question item: "Did you" or "Have you" and a work verb such as ran, saved, pushed, or updated, with no word such as ok, fine, ready, ship, merge, delete, approve, confirm, choice, or signed off; a checkbox `input` in a page counts as a task box), a `Q:` line with an `A:` line below it, and a table cell with an answer cell after it pass. A publish that declares the `db` or `artifact` capability, such as option cards that save the answer, passes; other capabilities do not. A file over 256 KB is read through its first and last 128 KB, and the refusal or a system message says so. A file that is not UTF-8 text passes. The read has a 4 s budget; when the HTML parser does not finish, a second read strips the tags in one pass with no parser, with another 4 s, and only when that also runs out does the call run, with a system message that the files went unchecked. The reason quotes at most 160 characters of the question and says to ask it through the question tool and send the file again without it.
27
28
  - `blocking/question_brief_gate.py` denies an `AskUserQuestion` call when the assistant chat text before it in the same turn runs over 450 words or 15 list or table items. A turn starts at a message the user types, at a result of an earlier question call, or at the first input after an `end_turn` reply or a `stop_hook_summary` entry. A Stop hook that holds the turn adds no input, so the text before a held stop still counts. Each bullet or numbered line is one item, each table row below the header is one item, and lines inside a code fence are not items. The reason names each limit passed and says to shorten the brief or split the question. The gate polls the transcript for up to 3 seconds for its own call and passes when the call never appears. A subagent call, an unreadable payload, and a missing or unreadable transcript, or one that is not a regular file, pass at once. The gate reads only the last 1 MB of the transcript, so a long review followed by more than 1 MB of tool output in the same turn is not seen.
28
29
  - `blocking/turn_review_gate.py` wakes the agent after a turn ends when a fresh `claude -p "/code-review low <base>..<turn>"` run, on Sonnet at high effort, finds a problem in that turn's edits. On Claude Code the Stop entry runs with `asyncRewake`, so the turn ends at once and the review runs in the background. A finding or a rejected dismissal exits 2, and its text goes to stderr, which the wake shows the agent, and to the stdout `reason`. Every other outcome exits 0 with no output and writes its diagnostic to `~/.claude/logs/turn-review.log`, one line per run with the event name and `stop_hook_active`. A plain `claude -p` run has no background, so the same entry holds that stop with exit code 2. At the prompt it snapshots each opted-in checkout into a commit built from a copy of the index after `git add -A`; at the stop it snapshots again with the first snapshot as parent, so the range holds only the turn's edits, untracked files included. A checkout takes part when it is `CLAUDE_PROJECT_DIR` or a folder directly inside it and its GitHub origin `owner/repo` slug is listed in `CLAUDE_TURN_REVIEW_REPOSITORIES`, comma-separated. A finding is an entry in the review's last non-empty JSON array of objects with a `file` key, where `file` is a changed path and `line` is a number. An empty `[]` counts as no array. A review with no such array has a finding on each line that opens with a changed path, a colon and a line number, after an optional list marker, backtick or emphasis mark. A review that opens with `(none)` has none. A saved baseline that is not a 40- or 64-character commit name is dropped, and that stop takes a fresh baseline. Each stop moves the baseline to its snapshot, marks the turn closed and saves both before the review starts, under a lock on the session's state file in the temp folder, so a second stop during a review starts from that snapshot and no range is reviewed twice. A prompt marks the turn open. A prompt that finds the last turn still open keeps the saved baseline, because no stop has claimed that turn yet (its stop is racing the prompt, or the user interrupted it); the late stop then reviews from that baseline, and edits the user made between the two turns are reviewed too. When a prompt found the turn open less than 10 seconds before the claim, that prompt began the next turn, so the stop leaves it open; a later claim closes it, which ends the open turn an interrupt left behind. A stop or prompt that waits 3 seconds for the lock before its snapshot exits 0 and leaves the state alone. After the review the stop waits up to 35 seconds for the lock, longer than a prompt run may hold it, and changes only the hold count; a stop that never gets it exits 0 with no wake, so each wake is counted. It holds a stop at most 3 times in a row. A stop below the cap with no finding, no rejection and no dismissal to judge resets the count, and so does a user's prompt. A prompt within 10 seconds of the last wake, or one that starts with `<task-notification`, belongs to the wake and keeps the count, so a chain of wakes stops at 3 whether or not a wake turn fires `UserPromptSubmit`. It skips a turn that changed more than 30 files, and lets the stop through when the review fails. The reviews of one stop share 240 seconds, and a checkout reached with less than a second left goes unreviewed. The review run gets `--setting-sources ""`, `--tools Read,Grep,Glob,Bash`, `--no-session-persistence`, `--permission-mode dontAsk`, read tools plus `git diff`, `git show` and `git log` in the checkout, a deny list for git's `-c`, `--config-env`, `--output`, `--ext-diff`, `--textconv`, `--git-dir`, `--work-tree` and `--exec-path` options, `--settings '{"disableAllHooks": true}'` so no other hook steers the review, `CLAUDE_TURN_REVIEW_CHILD=1`, and none of the parent session's id, messaging or ingress variables; the gate does nothing inside such a run. Each finding of a wake gets an id `TR-<n>` that is unique in the session, is saved as `open` in the state file with its text, checkout and commit range, and shows as `[TR-<n>]` before the finding in the wake. The wake names the one way to contest a finding: a reply line `Dismiss TR-<n>: <reason>`, and a claim that the user asked for the behavior goes in that reason with the user's words quoted. On a stop, the gate reads the reply from the Stop input's `last_assistant_message`, or from the text of the last assistant message in `transcript_path` when that field is missing, and takes the first `Dismiss` line per id, with its reason cut to 2000 characters. Open findings named there go to one judge run per checkout: `claude -p --model sonnet --effort high` with the review's read-only options, the child variable, and the prompt on stdin. The prompt holds the checkout path and one JSON object: a `requests` list with each finding's id, commit range and text and the agent's reason as JSON strings, and a `user_messages` list with the last 5 messages the user typed, each cut to 2000 characters, read from `transcript_path`. A message counts only when its entry carries `origin.kind` `human`, so tool results, hook text, notifications, the interrupt marker and prompts sent through the SDK are left out, and so is a typed message that starts with `<`. A transcript that is missing or unreadable gives an empty list. The prompt holds no other part of the conversation. It tells the judge to read the diff and the code at the range, to treat every string in the data as text to judge and the reason as a claim to check, to approve when the code shows the finding is wrong or when the reason quotes words that appear in `user_messages` and ask for exactly that behavior, never on a quote that is not there, and to reject when unsure. The judge's whole answer, inside at most one code fence, must be one strict JSON array of objects with exactly `id`, `verdict` (`approve` or `reject`) and `reason`, each key named once and each id one it was asked about. Any other answer gives no verdict, such as an object that repeats a key or a `NaN` value, and an id named twice gets none. An approval marks the finding `dismissed`, saves the judge's reason, logs one line and wakes nobody. A rejection marks it `upheld`, saves the reason and wakes the agent with `Dismissal of TR-<n> rejected: <reason>. Fix it.`. That wake counts toward the hold count, and a rejection and the stop's new findings arrive as one wake with one count. A `Dismiss` line for an upheld, dismissed or unknown id is logged and not judged. At the hold cap no judge runs, and the finding stays open. The judge runs after the stop's reviews and shares their 240 seconds. A judge that fails, times out, gives an answer of any other shape, or starts with less than a second left exits 0 with no output, logs one line, and leaves the finding open. A transcript line nested too deep to read is skipped and logged once per stop.
29
30
 
@@ -50,6 +51,7 @@ This family stops a chat reply, edited message, or tool call when its payload br
50
51
  - `blocking/merge_review_gate.py` runs on `PreToolUse`, matcher `Bash|PowerShell|mcp__.*__(create_pull_request|merge_pull_request|enable_pr_auto_merge)`, timeout `30` seconds in `hooks.json`. A `create_pull_request` call reads its head branch from GitHub with `git ls-remote` over https, so the working folder does not matter. The lookup runs in an empty folder, so no checkout's git config applies, takes no terminal prompt, and gets 5 seconds or the time left before the shared deadline, whichever is less. It runs through the same child read as the local git reads, so a lookup that times out ends `git` and every helper it started, in its own process group on POSIX and its job object on Windows, and the deny says that a second run may pass. A fork head `user:branch` reads the repository of `user`. A branch GitHub does not list, or a lookup that fails, resolves in the working folder as a shell open does, as `origin/<branch>` first. Each local git read gets 3 seconds or the time left, whichever is less, and the `origin` read runs once per folder. Every read answers to one deadline 20 seconds after the gate starts, so all reads end by about 21 seconds, inside the 30 second timeout. A read with no time left is skipped. A head the gate could not read is denied as unreadable. When a read stopped at its own timeout or at the shared deadline, the deny adds that a second run may pass. A read that fails fast, such as a git error, does not add that sentence.
51
52
  - `blocking/artifact_dark_mode_gate.py` runs on `PreToolUse`, matcher `Artifact`, timeout `60` seconds in `hooks.json`.
52
53
  - `blocking/send_user_file_worktree_root_gate.py` runs on `PreToolUse`, matcher `SendUserFile`, timeout `10` seconds in `hooks.json`.
54
+ - `blocking/sent_file_question_gate.py` runs on `PreToolUse`, matcher `SendUserFile|Artifact`, timeout `10` seconds in `hooks.json`. It runs in Claude Code only.
53
55
  - `blocking/turn_review_gate.py` runs on `UserPromptSubmit`, matcher empty, timeout `30` seconds, and on `Stop`, timeout `300` seconds with `asyncRewake`, `rewakeMessage` and `rewakeSummary`, in `hooks.json`. Claude Code still enforces the timeout on an `asyncRewake` hook. The review itself times out after 240 seconds. A stop's work stops at 280 seconds and a prompt's at 25. The installer keeps it out of the Codex prompt hooks through `ALL_CODEX_EXCLUDED_USER_PROMPT_SUBMIT_HOOK_SCRIPT_NAMES`, and it writes no turn review into the Codex or Cursor Stop hooks. A copy of `~/.claude/settings.json` that Cursor imports is not tested.
54
56
 
55
57
  ## Proving it
@@ -79,6 +81,7 @@ Preconditions:
79
81
  - **Clean review.** Input is a merge with no receipt, a receipt with findings, a merge pinned to a newer head, an unpinned merge, or auto-merge with no head. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_merge_review_gate.py -q`. The adjacent test observes a denial for each; a merge or auto-merge pinned to the clean head and a merge in an exempt repository pass. A `gh pr merge --disable-auto` call passes; a merge chained with it, or one that adds `--disable-auto=false` or `-sb --disable-auto`, is still checked. An open with no clean open receipt at its head is denied; an open reviewed clean at its head, and a merge pinned to that head, pass. An open pass whose every finding has its own `path:line` ruling lets the open through; a merge pinned to that head is denied, since only a zero-finding open pass carries to the merge. An open whose branch neither GitHub nor the working folder holds is denied as unreadable. Two chained creates whose second head has no clean open receipt are denied with the second head named. An open whose reads ran past the shared deadline, or whose git read hit its own timeout, is denied as unreadable, with the sentence that a second run may pass; a git read that fails fast gets no such sentence. Every create spelling is denied when its head has no clean pass. A create whose last repository flag names a repository with no clean pass is denied, however many repository flags come before it. A create that names an unreviewed second head with `-Hx`, a repeated `--head` or `--head=` is denied, and so is one whose short-flag cluster, such as `-dHx`, names an unreviewed head. A flag word that is another option's value, such as `--title --repo=x/y`, `--title -Hx` or `-bHx`, is read as that value. A create with no repository of its own in a command that sets `GH_REPO` elsewhere, through an assignment or `export`, is denied as unread with the `--repo owner/name` sentence, and one that names `--repo` or a `GH_REPO=` prefix is read. A first create behind a `GH_REPO=` prefix is denied when origin has no clean pass, also when the prefix repository is exempt or reviewed clean. A later create is denied the same way when the walk reaches it: behind `env`, `sudo` and `timeout` with their options, and behind chains of the launchers `nohup`, `nice`, `stdbuf`, `setsid` and `time` whose options hold their value in the same word or take a number, such as `nice -n 5 env -u GH_REPO stdbuf -o0`. A create after the first one, behind a program the walk does not step over, such as `ionice`, is not read. A create the walk reaches whose prefix value names no repository, such as `GH_REPO=nonsense`, is denied for origin with the `--repo owner/name` sentence. A first create the walk does not reach, such as one behind `stdbuf -o L`, is denied for origin through the first-create reading without that sentence, and a prefixed create after an unprefixed create on the same head is denied on the unprefixed create, also without it. A create that names an exempt repository with its own `--repo` passes. A create after a subshell or `popd` reads the starting folder, also after nested subshells close on one line or across line breaks, and `builtin cd` and `command cd` are followed. A create in a `case` arm, also one with a root `-R`, is checked on its head. A create inside a single-quoted or backslash-escaped substitution is not read, and one inside a double-quoted or bare substitution is checked. A create after `cd "$VAR"`, or after a `cd` in a piped brace group, `if`, `case`, a loop, a function body or after a redirect, is denied as unreadable, and so is a create nested past the unwrap depth. The first create the raw text spells is also checked with the earlier first-create reading, which a frozen table of commands pins, so a create fed to `bash` through a pipe or a heredoc is checked on its head. A later create on an unreviewed head is denied after an ANSI-C `$'...'` value, after a line break inside `bash -c`, `sh -c` or `eval`, and after a double-quoted value whose substitution holds a quote character. A later create inside a quoted value, such as `--body "say \"x\" ; gh pr create --head y"`, is not read. A here-string or piped create beyond the first, a create in a command string run by a program the walk does not unwrap, and a program name in a variable or alias are not read. An open or a merge whose check raises is denied with the fault reason, also when the text spells the create or merge in a form the strict pattern misses, and so is an MCP merge whose `pullNumber` overflows.
80
82
  - **Dark mode page.** Input is an Artifact publish of a page that themes `html` but leaves `body` to the publish wrapper. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_artifact_dark_mode_gate.py -q`. The adjacent test observes a denial that names the text and its contrast; a page that themes `body` passes. The render tests skip on a host with no Node Playwright and Chromium.
81
83
  - **Sent file root.** Input is a `SendUserFile` call for a file on `Y:\` or in the session scratchpad, with `cwd` set to a worktree. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_send_user_file_worktree_root_gate.py -q`. The adjacent test observes a denial that names the file and `<cwd>\.scratch\`; a file under `<cwd>\.scratch\` passes.
84
+ - **Sent file question.** Input is a `SendUserFile` call or an `Artifact` publish of a file that holds "Should I archive the old branches?" or a "Questions for you" heading. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_sent_file_question_gate.py packages/claude-dev-env/hooks/blocking/test_sent_file_scan.py -q`. The adjacent test observes a denial that quotes the question and names the file; a FAQ heading or list item, a quote, code, an answered question, and a page that declares `db` or `artifact` pass.
82
85
  - **Question brief.** Input is a transcript whose turn posts 451 words or 16 bullets before an `AskUserQuestion` call. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_question_brief_gate.py -q`. The adjacent test observes exit 2 with a reason that names the limit passed. A list before a held stop still counts. A short brief, text from an earlier turn, fenced lines, a subagent call, and a missing transcript pass.
83
86
  - **Turn review.** Input is a temporary checkout with an opted-in origin, a `UserPromptSubmit`, an edit that drops a decorator, and a `Stop`, with a stub `claude` on PATH that prints a finding. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_turn_review_gate.py -q`. The adjacent test observes a `block` decision with the finding on stdout and the same text alone on stderr, a review range whose diff holds only the edited file, and a review environment with no parent session id. A `(none)` review, an unchanged turn, a failed or timed out review, an unlisted repository, a 31-file turn, and a fourth stop in a row pass with empty stdout and stderr. A second stop during a review starts no second review. A prompt that runs before the last turn's stop keeps that turn under review, two such prompts in a row keep both turns, and a stop long after such a prompt closes the turn. A prompt within 10 seconds of a wake, or a `<task-notification` prompt, keeps the count, and a later prompt resets it. A held state lock passes the stop quietly, a lock freed late after the review still counts the hold, and a lock that never frees after the review passes the stop with no wake. With a stub judge on the same `claude` stub, a `Dismiss` line in `last_assistant_message` or in the transcript starts one judge run on `sonnet` at `high` whose stdin holds the finding, the reason, the checkout and the range; an approval passes quietly and saves `dismissed`; a rejection wakes with the rejection line and saves `upheld`; a second `Dismiss` line for an upheld finding, a line for an unknown id, and a line at the hold cap start no judge; a failed, timed out, non-JSON or starved judge passes quietly and leaves the finding open; and a rejection plus new findings arrive in one wake. `node --test packages/claude-dev-env/bin/install.cursor-rules.test.mjs` observes the `asyncRewake` Stop entry in the installed Claude settings and no turn review in the Codex or Cursor hooks.
84
87
 
package/hooks/hooks.json CHANGED
@@ -274,6 +274,16 @@
274
274
  }
275
275
  ]
276
276
  },
277
+ {
278
+ "matcher": "SendUserFile|Artifact",
279
+ "hooks": [
280
+ {
281
+ "type": "command",
282
+ "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/sent_file_question_gate.py",
283
+ "timeout": 10
284
+ }
285
+ ]
286
+ },
277
287
  {
278
288
  "matcher": "AskUserQuestion",
279
289
  "hooks": [
@@ -0,0 +1,167 @@
1
+ """Constants for the closing question round Stop gate.
2
+
3
+ Groups: the payload and transcript fields that mark a stop the gate leaves
4
+ alone, the transcript text each cheap scan looks for, the time and size
5
+ budget, the wording that marks an open item, the masking of indented code,
6
+ the declaration line, the hold cap, and the two hold reasons.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+
13
+ from hooks_constants.open_tasks_stop_gate_constants import (
14
+ ALL_QUESTION_TOOL_NAMES,
15
+ TOOL_RESULT_BLOCK_TYPE,
16
+ )
17
+
18
+ SUBAGENT_ID_KEY = "agent_id"
19
+ BACKGROUND_TASKS_KEY = "background_tasks"
20
+ SESSION_ATTENDED_ENVIRONMENT_VARIABLE = "CLAUDE_CODE_SESSION_ATTENDED"
21
+ HEADLESS_SESSION_ATTENDED_TEXT = "0"
22
+ TURN_ORIGIN_KEY = "turnOrigin"
23
+ HUMAN_TURN_ORIGIN = "human"
24
+ IS_SIDECHAIN_KEY = "isSidechain"
25
+ ATTENDED_SESSION_TEXT = "1"
26
+ LAST_ASSISTANT_MESSAGE_KEY = "last_assistant_message"
27
+ TOOL_USE_BLOCK_ID_KEY = "id"
28
+ IS_ERROR_KEY = "is_error"
29
+
30
+ TURN_ORIGIN_SCAN_TEXT = f'"{TURN_ORIGIN_KEY}"'
31
+ USER_ROLE_SCAN_TEXT = '"user"'
32
+ TOOL_RESULT_SCAN_TEXT = f'"{TOOL_RESULT_BLOCK_TYPE}"'
33
+ ASSISTANT_SCAN_TEXT = '"assistant"'
34
+ ALL_QUESTION_TOOL_NAME_SCAN_TEXTS = tuple(
35
+ f'"{each_tool_name}"' for each_tool_name in sorted(ALL_QUESTION_TOOL_NAMES)
36
+ )
37
+
38
+ STOP_DEADLINE_SECONDS = 7.0
39
+ WATCHDOG_GRACE_SECONDS = 1.0
40
+ DECISION_PROCESS_FLAG = "--decide"
41
+ STDIN_WATCHDOG_SECONDS = 8.5
42
+ OUTPUT_WATCHDOG_SECONDS = 1.0
43
+ MAXIMUM_SCANNED_BYTES = 16 * 1024 * 1024
44
+ MAXIMUM_PAYLOAD_BYTES = 16 * 1024 * 1024
45
+ MAXIMUM_SCANNED_TEXT_BYTES = 2 * 1024 * 1024
46
+ LINE_FEED_BYTES = b"\n"
47
+ ESCAPED_ASCII_TEXT = "\\u00"
48
+ ESCAPED_PRINTABLE_ASCII_PATTERN = re.compile(r"\\u00[2-7][0-9a-fA-F]")
49
+ MARKER_SCAN_WINDOW_CHARACTERS = 1024 * 1024
50
+ MARKER_SCAN_OVERLAP_CHARACTERS = 128
51
+ MARKER_SCAN_LOOKAHEAD_CHARACTERS = 4
52
+ SEPARATOR_RUN_PATTERN = re.compile(r"[\s-]{2,}")
53
+ HYPHEN_CHARACTER = "-"
54
+
55
+ OPEN_ITEM_MARKER_PATTERN = re.compile(
56
+ r"(?<![^\W_])(?<![^\W_]_)(?<![^\W_]__)(?<![^\W_]___)(?:"
57
+ r"deferred|defer|defers|deferring|deferrals?"
58
+ r"|follow-?ups?"
59
+ r"|(?:a|the|another|one)\s+follow\s+ups?"
60
+ r"|follow\s+up\s+(?:pr|pull\s+request|issue|task|ticket|change|commit)"
61
+ r"|parked"
62
+ r"|out[\s-]+of[\s-]+scope"
63
+ r"|not\s+covered"
64
+ r"|for\s+later"
65
+ r"|later\s+(?:pull\s+request|pr)"
66
+ r"|known\s+(?:gap|limitation)s?"
67
+ r"|open\s+questions?"
68
+ r"|unresolved"
69
+ r"|uncertain|uncertainty"
70
+ r"|not\s+sure"
71
+ r"|unsure"
72
+ r"|unclear"
73
+ r"|i\s+assumed|we\s+assumed|(?:i|we)\s+assume"
74
+ r"|assuming"
75
+ r"|assumptions?"
76
+ r"|unverified"
77
+ r"|(?:could\s+not|couldn['\u2019]t|did\s+not)\s+verify"
78
+ r"|untested"
79
+ r"|not\s+tested"
80
+ r"|(?:didn['’]t|did\s+not)\s+test"
81
+ r"|you\s+may\s+want\s+to"
82
+ r"|your\s+judge?ment"
83
+ r"|(?:could\s+not|couldn['’]t|unable\s+to)\s+confirm"
84
+ r"|separate\s+(?:pr|pull\s+request)"
85
+ r"|not\s+yet\s+implemented"
86
+ r"|judge?ment\s+calls?"
87
+ r"|your\s+call"
88
+ r"|up\s+to\s+you"
89
+ r"|needs\s+your\s+(?:decision|judge?ment|approval)"
90
+ r"|needs?\s+your\s+input"
91
+ r"|i\s+need\s+you\s+to"
92
+ r"|pending"
93
+ r"|todo|tbd"
94
+ r"|skipped|skipping"
95
+ r"|not\s+done"
96
+ r"|blocked"
97
+ r"|(?:didn['’]t|not)\s+run"
98
+ r"|(?:could\s+not|couldn['’]t)\s+reproduce"
99
+ r"|left\s+(?:it|this|that|them|these)\s+for\s+you"
100
+ r"|for\s+you\s+to\s+decide"
101
+ r"|(?:waiting|waits)\s+on\s+you"
102
+ r")(?![^\W_])(?!_{1,3}[^\W_])",
103
+ re.IGNORECASE,
104
+ )
105
+ INDENTED_CODE_LINE_PATTERN = re.compile(r"^(?: {4}|\t)")
106
+ LIST_ITEM_LINE_PATTERN = re.compile(r"^ {0,3}(?:[-*+]|\d{1,9}[.)])[ \t]+\S")
107
+ PATH_JOINING_CHARACTERS = "./\\"
108
+ PATH_SEPARATOR_PATTERN = re.compile(r"[/\\]")
109
+ PATH_BREAK_PATTERN = re.compile(r"\s")
110
+ FILE_NAME_PATTERN = re.compile(r"[^\s/\\]+\.(?P<extension>[a-z0-9]{1,5})")
111
+ PATH_EDGE_CHARACTERS = "\"'`()[]<>{},;:!?.*_~\u201c\u201d\u2018\u2019\u00ab\u00bb\u2039\u203a\u2026"
112
+ PATH_REACH_CHARACTERS = 96
113
+ MINIMUM_PATH_SEGMENT_COUNT = 2
114
+ NO_OPEN_ITEMS_DECLARATION = "Open items: none."
115
+ DECLARATION_LINE_PATTERN = re.compile(
116
+ r"(?P<mark>\*\*|__|\*|_|)"
117
+ + re.escape(NO_OPEN_ITEMS_DECLARATION.removesuffix("."))
118
+ + r"\.?(?P=mark)"
119
+ )
120
+
121
+ MAXIMUM_HOLD_COUNT = 2
122
+ FEEDBACK_OPENING_LENGTH = 200
123
+ MAXIMUM_QUOTED_LINE_COUNT = 8
124
+ MAXIMUM_QUOTED_LINE_LENGTH = 160
125
+ CLIPPED_LINE_END = "..."
126
+
127
+ CLOSING_ROUND_REASON_LEAD = (
128
+ "This session wrote about open items and sent no question card after them."
129
+ )
130
+ WORK_REASON_LEAD = (
131
+ "This session did work and ended without a question card or the declaration line."
132
+ )
133
+ ALL_REASON_LEADS = (CLOSING_ROUND_REASON_LEAD, WORK_REASON_LEAD)
134
+ OPEN_ITEM_LINES_LABEL = "The lines:"
135
+ QUOTED_LINE_TEMPLATE = '"{line}"'
136
+ REMAINING_LINES_TEMPLATE = "Earlier lines left out here: {remaining_count}."
137
+ CODE_SPAN_SHOWN_TEXT = "`...`"
138
+ READ_ITEMS_INSTRUCTION = (
139
+ "Read the task list, your notes, and the live state of each item. Drop each item that is done."
140
+ )
141
+ CARD_INSTRUCTION = (
142
+ "Write one short chat brief that covers every item that still stands, with each link in it."
143
+ " question_brief_gate.py counts every chat word and every list or table item this turn wrote"
144
+ " since the last typed prompt or question result, the reply above included, and refuses a"
145
+ " question past 450 words or 15 items. Keep the brief short enough that the total stays"
146
+ " inside that limit. When the reply above is already over it, write a one-line brief and send"
147
+ " the cards: that first call is refused, and a refused question starts a new count, so send"
148
+ " the same cards again at once with no new text. Send each item as its own AskUserQuestion"
149
+ " question. Put at most four questions in one call, so a longer round takes more calls. Give"
150
+ " each question a header of 12 characters or fewer and two or three options, your"
151
+ " recommendation first. Give each option a one-sentence description. A card shows plain"
152
+ " text, so write a link in a card as a bare URL. After the user answers, act on each answer"
153
+ " and close with what you did with it. Do not restate the items, because open-item lines"
154
+ " written after the cards start a new round. When that work leaves nothing open, end the"
155
+ f" reply with the line {NO_OPEN_ITEMS_DECLARATION}"
156
+ )
157
+ CLOSING_ROUND_INSTRUCTION = (
158
+ f"{READ_ITEMS_INSTRUCTION} {CARD_INSTRUCTION} When the lines name nothing that is still open,"
159
+ " send one question that says so and lets the user add an item."
160
+ )
161
+ WORK_INSTRUCTION = (
162
+ f"{READ_ITEMS_INSTRUCTION} When something is deferred, uncertain, or needs or can use the"
163
+ " user's judgment, brief it and send the cards, as follows."
164
+ f" {CARD_INSTRUCTION} When nothing is, do not list what is not open: end the reply with this"
165
+ f" exact line alone, in plain text with no backticks or list marker: {NO_OPEN_ITEMS_DECLARATION}"
166
+ )
167
+ REASON_PART_SEPARATOR = "\n"