claude-dev-env 8.116.5 → 8.117.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/bin/ever-registered-hooks.mjs +2 -0
  2. package/bin/install-constants.mjs +3 -1
  3. package/bin/install.cursor-rules.test.mjs +64 -2
  4. package/bin/install.mjs +15 -2
  5. package/bin/install.prune.test.mjs +92 -0
  6. package/bin/install.test.mjs +1 -0
  7. package/docs/model-choice/escalation.md +3 -3
  8. package/docs/model-choice/subagents-and-fan-out.md +2 -2
  9. package/docs/model-choice/which-model.md +1 -1
  10. package/docs/references/working-style.md +1 -0
  11. package/docs/rule-guides/question-presentation.md +6 -0
  12. package/docs/rule-guides/session-title.md +8 -9
  13. package/docs/rule-guides/subagent-model-effort.md +13 -13
  14. package/hooks/advisory/owned_pr_review_loop.py +2 -3
  15. package/hooks/blocking/bash_post_call_dispatcher.py +17 -9
  16. package/hooks/blocking/bash_pre_tool_use_dispatcher.py +12 -8
  17. package/hooks/blocking/final_reply_gate.py +5 -9
  18. package/hooks/blocking/open_tasks_stop_gate.py +9 -20
  19. package/hooks/blocking/open_tasks_transcript.py +8 -3
  20. package/hooks/blocking/pii_prevention_blocker_parts/repository_exemption.py +7 -2
  21. package/hooks/blocking/question_brief_gate.py +382 -0
  22. package/hooks/blocking/step_note_gate.py +5 -2
  23. package/hooks/blocking/task_subject_length_gate.py +111 -0
  24. package/hooks/blocking/test_bash_post_call_dispatcher.py +36 -1
  25. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +57 -0
  26. package/hooks/blocking/test_final_reply_gate.py +26 -2
  27. package/hooks/blocking/test_open_tasks_stop_gate.py +21 -11
  28. package/hooks/blocking/test_question_brief_gate.py +916 -0
  29. package/hooks/blocking/test_step_note_gate.py +26 -0
  30. package/hooks/blocking/test_task_subject_length_gate.py +221 -0
  31. package/hooks/blocking/test_turn_review_findings.py +124 -1
  32. package/hooks/blocking/test_turn_review_gate.py +1312 -10
  33. package/hooks/blocking/test_turn_review_snapshot.py +8 -0
  34. package/hooks/blocking/tests/test_repository_exemption.py +11 -0
  35. package/hooks/blocking/turn_review_findings.py +173 -13
  36. package/hooks/blocking/turn_review_gate.py +878 -105
  37. package/hooks/blocking/turn_review_snapshot.py +5 -1
  38. package/hooks/features/bash-dispatchers.md +1 -3
  39. package/hooks/features/conduct-gates.md +19 -9
  40. package/hooks/features/lifecycle-cleanup.md +1 -1
  41. package/hooks/features/spawn-routing.md +1 -1
  42. package/hooks/hooks.json +24 -11
  43. package/hooks/hooks_constants/final_reply_gate_constants.py +0 -3
  44. package/hooks/hooks_constants/hook_time_budget.py +61 -0
  45. package/hooks/hooks_constants/hosted_hook_runner.py +51 -21
  46. package/hooks/hooks_constants/hosted_hook_runner_constants.py +3 -0
  47. package/hooks/hooks_constants/nested_project_hooks_constants.py +8 -0
  48. package/hooks/hooks_constants/once_per_session_constants.py +1 -0
  49. package/hooks/hooks_constants/open_tasks_stop_gate_constants.py +0 -4
  50. package/hooks/hooks_constants/owned_pr_review_loop_constants.py +0 -4
  51. package/hooks/hooks_constants/pre_tool_use_context_runner.py +23 -3
  52. package/hooks/hooks_constants/pre_tool_use_context_runner_constants.py +5 -0
  53. package/hooks/hooks_constants/pre_tool_use_stdin.py +1 -1
  54. package/hooks/hooks_constants/question_brief_gate_constants.py +66 -0
  55. package/hooks/hooks_constants/session_title_constants.py +6 -27
  56. package/hooks/hooks_constants/stop_hook_hold.py +54 -0
  57. package/hooks/hooks_constants/stop_hook_hold_constants.py +9 -0
  58. package/hooks/hooks_constants/subagent_effort_levels.json +6 -0
  59. package/hooks/hooks_constants/subagent_effort_route_constants.py +20 -19
  60. package/hooks/hooks_constants/task_subject_length_gate_constants.py +43 -0
  61. package/hooks/hooks_constants/test_hook_time_budget.py +104 -0
  62. package/hooks/hooks_constants/test_hosted_hook_runner.py +12 -0
  63. package/hooks/hooks_constants/test_pre_tool_use_context_runner.py +16 -0
  64. package/hooks/hooks_constants/test_pre_tool_use_stdin.py +6 -0
  65. package/hooks/hooks_constants/test_stop_hook_hold.py +40 -0
  66. package/hooks/hooks_constants/thread_spawn_pace_hook_constants.py +1 -2
  67. package/hooks/hooks_constants/turn_review_gate_constants.py +246 -12
  68. package/hooks/lifecycle/nested_project_hooks.py +34 -4
  69. package/hooks/lifecycle/test_nested_project_hooks.py +52 -0
  70. package/hooks/once_per_session.py +33 -4
  71. package/hooks/open_task_asks.py +1 -1
  72. package/hooks/owned_pr_session_record.py +1 -76
  73. package/hooks/routing/subagent_effort_route.py +107 -13
  74. package/hooks/routing/subagent_effort_route_hook.py +9 -8
  75. package/hooks/routing/test_subagent_effort_route.py +201 -14
  76. package/hooks/routing/test_subagent_effort_route_hook.py +56 -0
  77. package/hooks/routing/thread_spawn_pace_hook.py +3 -3
  78. package/hooks/session/background_silence_prompt.py +1 -1
  79. package/hooks/session/test_tracking_nudge.py +114 -2
  80. package/hooks/session/tracking_nudge.py +28 -18
  81. package/hooks/session_title_transcript.py +195 -0
  82. package/hooks/test_once_per_session.py +10 -0
  83. package/hooks/test_owned_pr_session_record.py +0 -26
  84. package/hooks/test_session_title_transcript.py +111 -0
  85. package/hooks/validation/post_tool_use_dispatcher.py +38 -21
  86. package/hooks/validation/test_post_tool_use_dispatcher.py +43 -0
  87. package/package.json +1 -1
  88. package/rules/question-presentation.md +4 -4
  89. package/rules/subagent-model-effort.md +1 -1
  90. package/scripts/claude_account_worker.py +4 -3
  91. package/scripts/policy_lint/adapter_configuration.py +12 -11
  92. package/scripts/policy_lint/config/constants.py +2 -2
  93. package/scripts/test_claude_account_worker.py +1 -0
  94. package/scripts/tests/test_adapter_configuration.py +10 -2
  95. package/hooks/blocking/owned_pr_merge_stop_gate.py +0 -185
  96. package/hooks/blocking/session_title_turn_gate.py +0 -417
  97. package/hooks/blocking/test_owned_pr_merge_stop_gate.py +0 -254
  98. package/hooks/blocking/test_session_title_turn_gate.py +0 -396
  99. package/hooks/hooks_constants/owned_pr_merge_stop_gate_constants.py +0 -40
@@ -20,6 +20,7 @@ import subprocess
20
20
  import tempfile
21
21
  from pathlib import Path
22
22
 
23
+ from hooks_constants.hook_time_budget import call_timeout
23
24
  from hooks_constants.subprocess_window import hidden_window_creation_flags
24
25
  from hooks_constants.turn_review_gate_constants import (
25
26
  ALL_CHANGED_PATH_ARGUMENTS,
@@ -40,6 +41,9 @@ def _git_output(
40
41
  all_arguments: list[str],
41
42
  all_environment_variables: dict[str, str] | None,
42
43
  ) -> str | None:
44
+ timeout_seconds = call_timeout(GIT_COMMAND_TIMEOUT_SECONDS)
45
+ if timeout_seconds is None:
46
+ return None
43
47
  try:
44
48
  completed_process = subprocess.run(
45
49
  ["git", *all_arguments],
@@ -48,7 +52,7 @@ def _git_output(
48
52
  text=True,
49
53
  encoding=GIT_OUTPUT_ENCODING,
50
54
  errors=GIT_OUTPUT_ERROR_HANDLING,
51
- timeout=GIT_COMMAND_TIMEOUT_SECONDS,
55
+ timeout=timeout_seconds,
52
56
  cwd=str(repository_root),
53
57
  env=all_environment_variables,
54
58
  creationflags=hidden_window_creation_flags(),
@@ -12,9 +12,9 @@ This family rewrites a Git Bash command when path conversion would change a revi
12
12
  - `blocking/python_windows_invocation_gate.py` denies, on a Windows host, `python`, `python3` or `py` run with `-I` and without `-X utf8`, because `-I` ignores `PYTHONUTF8` and non-ASCII output then stops with `UnicodeEncodeError: 'charmap'`. Under the PowerShell tool it also denies a `python -c "..."` argument that holds `\"`, because PowerShell ends the string at that quote, and names a script file or a single-quoted here-string to use instead.
13
13
  - `blocking/transcript_root_search_gate.py` denies a recursive walk or content search that starts at a Claude transcript root, a `projects` folder directly under `.claude`, `.claude-<name>` or `.claude-profiles/<profile>`, with no project folder after it, or with a bare `*` or `**` segment that descends into every project folder. It reads `find`, `grep -r`, `rg`, `ls -R`, `Get-ChildItem -Recurse` or `-Depth`, `Select-String`, and the Grep and Glob tools, and expands variables the command assigns, such as `$p="..."`. A one-level name listing, such as `Get-ChildItem <root> -Directory -Filter "*id*"`, passes. The deny reason names the fix: list the project folders by name, then read the one transcript. The gate reads the root path as the command spells it, so a walk that starts above the root, or a glob that spells the root name or a project-name prefix such as `pro*` or `C--*`, passes.
14
14
  - `blocking/bash_post_call_dispatcher.py` runs hosted observers and joins their context output without blocking the call.
15
+ - When a hosted hook exits 2, both dispatchers exit 2. Its stderr reaches the host as written. Before a call, exit 2 blocks the call. After a call, exit 2 shows that stderr to Claude.
15
16
  - `advisory/pr_done_reminder.py` adds a pull request checklist after a successful push or pull request creation.
16
17
  - `advisory/owned_pr_review_loop.py` adds review-loop instructions after the agent opens a pull request on an owned repository outside the preset list of repositories that run their own automated review: run efficient-review until clean, mark the pull request ready, babysit it, and ship it to merge. It also records the pull request for the session in `owned_pr_session_record.py`.
17
- - `blocking/owned_pr_merge_stop_gate.py` holds the end of a turn while a recorded pull request reads open on GitHub and the closing reply has no `Blocked:` line that names it. It holds once per pull request head in a session, so a later stop passes until a push moves the head. A failed state lookup passes.
18
18
 
19
19
  ## When it fires
20
20
 
@@ -28,7 +28,6 @@ This family rewrites a Git Bash command when path conversion would change a revi
28
28
  - `blocking/bash_post_call_dispatcher.py` runs on `PostToolUse`, matcher `Bash|PowerShell`, timeout `60` seconds in `hooks.json`.
29
29
  - `advisory/pr_done_reminder.py` runs inside that dispatcher on `PostToolUse`, matcher `Bash|PowerShell`, timeout `60` seconds. `ALL_BASH_POST_TOOL_USE_HOSTED_HOOK_ENTRIES` selects `Bash` and `PowerShell`.
30
30
  - `advisory/owned_pr_review_loop.py` runs on `PostToolUse`, matcher `Bash|PowerShell|exec_command|shell_command|mcp__.*__(create_pull_request|github_create_pull_request)`, timeout `10` seconds in `hooks.json`. It wakes on `gh pr create`, `gh pr new`, a POST to `gh api repos/<owner>/<repo>/pulls`, a `pull_request.py create` call to the pull request publisher, and an MCP pull request creation. The installer also registers it on Codex `PostToolUse` through `ALL_CODEX_NATIVE_POST_TOOL_USE_HOOK_SCRIPT_NAMES`.
31
- - `blocking/owned_pr_merge_stop_gate.py` runs on `Stop`, timeout `60` seconds in `hooks.json`. The installer also registers it on Codex `Stop` through `ALL_CODEX_NATIVE_STOP_HOOK_SCRIPT_NAMES`.
32
31
 
33
32
  ## Proving it
34
33
 
@@ -45,7 +44,6 @@ Preconditions:
45
44
  - **Post-call dispatch.** Input is a Bash call that yields hosted context. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_bash_post_call_dispatcher.py -q`. The adjacent test observes a joined context payload and exit code zero.
46
45
  - **Pull request reminder.** Input is a completed push or pull request creation. Run `python -m pytest packages/claude-dev-env/hooks/advisory/test_pr_done_reminder.py -q`. The adjacent test checks the reminder trigger and checklist verdict.
47
46
  - **Owned pull request review loop.** Input is a pull request creation result on an owned repository. Run `python -m pytest packages/claude-dev-env/hooks/advisory/test_owned_pr_review_loop.py -q`. The adjacent test observes the review-loop block for owned repositories and silence for the preset and foreign repositories.
48
- - **Owned pull request merge gate.** Input is a `session_record_path` file that lists `jl-cmd/snake-game#9` and a `gh` stub that reports `open` and a head sha. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_owned_pr_merge_stop_gate.py packages/claude-dev-env/hooks/test_owned_pr_session_record.py -q`. The adjacent test observes a `block` decision that names the pull request; `closed` and a `Blocked: jl-cmd/snake-game#9 - ...` line pass, and a second stop on the same head passes.
49
47
 
50
48
  ## Gotchas
51
49
 
@@ -5,14 +5,14 @@ This family stops a chat reply, edited message, or tool call when its payload br
5
5
  ## Checks
6
6
 
7
7
  - `blocking/final_reply_gate.py` checks the reply a session ends its turn with. Its `windows_path_violation` blocks a path the terminal would render without one of its backslashes. Its `unbriefed_question_violation` blocks a reply whose last paragraph, with fences, quotes, and code spans left out, ends with a question mark or says a question still stands, when the turn sent no `AskUserQuestion`, hearthbot decision card, or Codex `request_user_input` call; it is skipped when the transcript cannot be read.
8
- - `blocking/open_tasks_stop_gate.py` holds the end of a turn once when the prompt that started it asks for work, the turn ran a work tool, and the turn made no tracker call: TaskCreate, TaskUpdate, TodoWrite, the Codex `update_plan`, or the desktop `mcp__ccd_turn__update_plan`. A work tool is any tool but a tracker call, the session title tool, `AskUserQuestion`, a hearthbot decision card, Codex `request_user_input`, `ToolSearch`, `TaskList`, or `TaskGet`. It never reads the reply text. `open_task_asks.is_ask` decides whether a prompt asks for work: a question-only prompt, an acknowledgement such as `thanks!`, an empty prompt, a prompt of only `<system-reminder>` blocks, and an envelope such as `<agent-message>` or `<task-notification>` do not. `blocking/open_tasks_transcript.py` replays the transcript for it: the turn's prompt, its tool calls, and the task list. `session_task_items` merges the task store with the transcript items whose subject the store does not hold, for the session title gate.
9
- - `session/tracking_nudge.py` adds one `additionalContext` note to a prompt that asks for work. The note asks for an item in the session's task list tool. It shows on the session's first ask and on the first ask after each compaction, through `once_per_session.py`. When the title shows the red flag or the check mark, it also asks for the hourglass before other work. It never blocks.
8
+ - `blocking/open_tasks_stop_gate.py` holds the end of a turn once when the prompt that started it asks for work, the turn ran a work tool, and the turn made no tracker call: TaskCreate, TaskUpdate, TodoWrite, the Codex `update_plan`, or the desktop `mcp__ccd_turn__update_plan`. A work tool is any tool but a tracker call, the session title tool, `AskUserQuestion`, a hearthbot decision card, Codex `request_user_input`, `ToolSearch`, `TaskList`, or `TaskGet`. It never reads the reply text. `open_task_asks.is_ask` decides whether a prompt asks for work: a question-only prompt, an acknowledgement such as `thanks!`, an empty prompt, a prompt of only `<system-reminder>` blocks, and an envelope such as `<agent-message>` or `<task-notification>` do not. `blocking/open_tasks_transcript.py` replays the transcript for it: the turn's prompt, its tool calls, and the task list. `session_task_items` merges the task store with the transcript items whose subject the store does not hold.
9
+ - `session/tracking_nudge.py` adds one `additionalContext` note to a prompt that asks for work. The note asks for an item in the session's task list tool. It shows on the session's first ask and on the first ask after each compaction, through `once_per_session.py`. When the title shows the red flag or the check mark, it also asks for the hourglass before other work. In a session that has a `__set_session_title` tool and no title yet, it asks once for a first title in the `⏳ <name>` form, and never again in that session, compactions included, through `once_per_session.claim_only_showing`. `session_title_transcript.py` reads the title tool and the shown title from the transcript. It never blocks. No hook holds the end of a turn for the title.
10
10
  - `session/background_silence_prompt.py` adds one `additionalContext` note to a background event prompt, one that starts with `<task-notification>` or opens itself or a `<system-reminder>` block with `[SYSTEM NOTIFICATION - NOT USER INPUT]`, while the user asked for silence. The newest user-typed message that sets silence ("silent unless", "stay silent", "silent on updates", "no updates unless") or lifts it ("you can talk again", "updates are fine", "stop being silent") decides. The note quotes the user's "unless" or "except" clause word for word, or the whole message when it has no such clause, and says to end the turn with no text unless that exception applies now. Envelope prompts, compaction summaries, and quoted `>` lines are not the user's words. It never blocks.
11
11
  - The claim judge is a `prompt` hook in `hooks.json`, with no `model` set, so Claude Code's small default hook model reads each chat message and denies every claim, numbered in one refusal, about how code, a file, a tool, a service, a run, or a process behaves, or why something happened, when nothing in the message shows it: inline code that quotes output or a code line, a file and line, or a link. A pull request link covers what that change does, what it blocks or lets through, and its checks. The author's own actions, a restatement of the user's words, questions, instructions, and a decision card's option consequences pass. It catches plain claims such as "The code lets any of them rewrite it mid-check." `continueOnBlock` returns the reason to the agent as the tool error, so it can add the source and send again. The installer owns it through the `claude-dev-env: ` prefix on its `statusMessage`. It skips `post_widget`, whose input is SVG or HTML markup.
12
12
  - `blocking/edit_marker_gate.py` rejects strikethrough and edit-note markers in replacement chat text or cards.
13
13
  - `blocking/issue_close_handoff_gate.py` denies an issue comment or issue write that closes the issue and routes a found defect to another issue or epic.
14
14
  - `blocking/session_title_format_gate.py` denies a session title that breaks the `<emoji> <name>` shape or has a name longer than 25 characters.
15
- - `blocking/session_title_turn_gate.py` holds the end of a turn once, in a session that has a `__set_session_title` tool, when the shown title does not fit the session's state: no title yet, a red flag after a prompt that asks for work, a check mark while the task list has open items, or an hourglass once every item is completed or deleted. A turn that set a title passes. A turn that called no tool other than the title tool passes, and so does a held turn.
15
+ - `blocking/task_subject_length_gate.py` denies a `TaskCreate` or `TaskUpdate` whose `subject` is over 80 characters, and a `TodoWrite` whose list holds an item `content` over 80 characters, naming the first such item. The reason gives the length and the limit and says to start with who acts (Me, You, or Handed off), say what is left, and put detail in the description.
16
16
  - `blocking/step_note_gate.py` requires a status line before a tool call while its opt-in flag is on.
17
17
  - `blocking/wakeup_cap_gate.py` keeps a self-wakeup inside the 1-hour prompt cache. A wake over the step-down (57 minutes for `send_later` and Routines, 3480 seconds for `ScheduleWakeup`) and at most 60 minutes away runs with its delay rewritten to the step-down. A wake over 60 minutes away, or a cron with more than 57 minutes between wakes, is denied with a reason that says to stack wakes under the cap. A Routine that starts a fresh session on each firing passes.
18
18
  - `blocking/verify_before_acting.py` blocks a completed mutating call when the agent's reasoning contains an unchecked claim. For an `Agent` or `Task` spawn it adds the same quote as an advisory note and does not block.
@@ -23,7 +23,8 @@ This family stops a chat reply, edited message, or tool call when its payload br
23
23
  - `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 `gh pr create`, `pull_request.py 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. 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.
24
24
  - `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.
25
25
  - `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.
26
- - `blocking/turn_review_gate.py` holds the end of a turn when a fresh `claude -p "/code-review low <base>..<turn>"` run finds a problem in that turn's edits. 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, so the stop after a block reviews only the fix. It holds a stop at most 3 times in a row until the next prompt, 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.
26
+ - `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.
27
+ - `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.
27
28
 
28
29
  ## When it fires
29
30
 
@@ -35,8 +36,9 @@ This family stops a chat reply, edited message, or tool call when its payload br
35
36
  - `blocking/edit_marker_gate.py` runs on `PreToolUse`, matcher `mcp__.*__update_message`, timeout `10` seconds in `hooks.json`.
36
37
  - `blocking/issue_close_handoff_gate.py` runs on `PreToolUse`, matcher `mcp__.*__(add_issue_comment|issue_write|update_issue_comment)`, timeout `10` seconds in `hooks.json`.
37
38
  - `blocking/session_title_format_gate.py` runs on `PreToolUse`, matcher `mcp__.*__set_session_title`, timeout `10` seconds in `hooks.json`.
38
- - `blocking/session_title_turn_gate.py` runs on `Stop`, timeout `10` seconds in `hooks.json`.
39
+ - `blocking/task_subject_length_gate.py` runs on `PreToolUse`, matcher `TaskCreate|TaskUpdate|TodoWrite`, timeout `10` seconds in `hooks.json`. It runs in Claude Code only: the installer gives Codex only the PreToolUse group whose matcher is `multi_agent_v1__spawn_agent`, and gives Cursor only the hooks `bin/install-constants.mjs` names.
39
40
  - `blocking/step_note_gate.py` runs on `PreToolUse`, matcher `*`, timeout `15` seconds in `hooks.json`.
41
+ - `blocking/question_brief_gate.py` runs on `PreToolUse`, matcher `AskUserQuestion`, timeout `10` seconds in `hooks.json`. Its transcript poll stops at 3 seconds.
40
42
  - `blocking/wakeup_cap_gate.py` runs on `PreToolUse`, matcher `ScheduleWakeup|CronCreate|mcp__.*__(send_later|create_trigger|update_trigger)`, timeout `10` seconds in `hooks.json`.
41
43
  - `blocking/verify_before_acting.py` runs on `PostToolUse`, matcher `Write|Edit|MultiEdit|NotebookEdit|Agent|Task|apply_patch|Bash|PowerShell|mcp__.*`, timeout `10` seconds in `hooks.json`.
42
44
  - `blocking/pr_lifecycle_skill_gate.py` runs on `PreToolUse`, matcher `Bash|PowerShell|mcp__.*__(create_pull_request|merge_pull_request|enable_pr_auto_merge|update_pull_request|actions_run_trigger)`, timeout `30` seconds in `hooks.json`. The gate's git and GitHub reads end by 21 s after its read clock starts (a 20 s deadline and a 1 s grace for a stopped child).
@@ -46,7 +48,7 @@ This family stops a chat reply, edited message, or tool call when its payload br
46
48
  - `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. 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. The timeout covers the lookup beside those local git calls.
47
49
  - `blocking/artifact_dark_mode_gate.py` runs on `PreToolUse`, matcher `Artifact`, timeout `60` seconds in `hooks.json`.
48
50
  - `blocking/send_user_file_worktree_root_gate.py` runs on `PreToolUse`, matcher `SendUserFile`, timeout `10` seconds in `hooks.json`.
49
- - `blocking/turn_review_gate.py` runs on `UserPromptSubmit`, matcher empty, timeout `30` seconds, and on `Stop`, timeout `300` seconds, in `hooks.json`. The review itself times out after 240 seconds.
51
+ - `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.
50
52
 
51
53
  ## Proving it
52
54
 
@@ -63,7 +65,8 @@ Preconditions:
63
65
  - **Edit marker.** Input is an update message with strikethrough or an edit note. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_edit_marker_gate.py -q`. The adjacent test observes a denial; clean replacement text passes.
64
66
  - **Handoff close.** Input is an issue comment that says the issue is closed and that the found defect belongs to another issue. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_issue_close_handoff_gate.py -q`. The adjacent test observes a denial; a close with a plain cross-reference and a routing comment on an open issue both pass.
65
67
  - **Session title.** Input is a set session title call with no leading emoji or a name over 25 characters. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_session_title_format_gate.py -q`. The adjacent test observes a denial that names the broken rule; a well-formed title passes.
66
- - **Stale title.** Input is a transcript that lists the title tool, an earlier turn that set the red flag, and a work prompt whose turn ran a tool and set no title. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_session_title_turn_gate.py -q`. The adjacent test observes a `block` decision that names the shown title, the tool, and the four status emoji. A carried hourglass with an item in progress passes, and so does a turn whose title call came back without an error.
68
+ - **Task subject.** Input is a `TaskCreate` call whose subject is a 229-character status sentence, then three short subjects that start with Me, You, and Handed off. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_task_subject_length_gate.py -q`. The adjacent test observes a denial that gives the status sentence's length and the limit, the short ones passing, 80 characters passing and 81 denied, a status-only `TaskUpdate` passing, and a `TodoWrite` denial that names its long item.
69
+ - **First title.** Input is a `UserPromptSubmit` payload with a work prompt, after a transcript that lists the title tool and holds no title call. Run `python -m pytest packages/claude-dev-env/hooks/session/test_tracking_nudge.py -q`. The adjacent test observes one note that names the tool and `⏳ <name>`, exit 0 and empty stderr. A second ask and an ask after a compaction get no such note. A session without the title tool, and a title that shows the hourglass, get no title note.
67
70
  - **Step note.** Input is a tool call after a transcript message without a status line while the flag is on. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_step_note_gate.py -q`. The adjacent test observes a block until a status line appears.
68
71
  - **Wakeup cap.** Input is a `send_later` call with `delay_minutes` of 60, then 90, then 45. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_wakeup_cap_gate.py -q`. The adjacent test observes 60 rewritten to 57 through `updatedInput`, 90 denied with the stacking instruction, and 45 passing untouched.
69
72
  - **Checked claim.** Input is a Write after hedged reasoning in the transcript. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_verify_before_acting.py -q`. The adjacent test observes a block and a logged blocked outcome. The same hedge before an `Agent` call gives `additionalContext`, no `decision`, and a logged advised outcome.
@@ -73,18 +76,25 @@ Preconditions:
73
76
  - **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.
74
77
  - **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.
75
78
  - **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.
76
- - **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, 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 review, an unlisted repository, a 31-file turn, and a fourth stop in a row pass.
79
+ - **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.
80
+ - **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.
77
81
 
78
82
  ## Gotchas
79
83
 
80
84
  - The ask nudge runs only from `hooks.json`, so Codex and Cursor sessions get no turn-start note. Their Stop gate still holds a work turn with no tracker call.
81
85
  - The background silence note is the last point before the reply. A Stop hook sees the reply after it is on screen, and holding the text at `MessageDisplay` would need a judgment on whether the exception applies.
86
+ - A headless run whose input is streamed, such as `claude -p --input-format stream-json` or an SDK client, runs the Stop entry in the background, and the host kills it at teardown, so that run loses its review.
87
+ - Claude Code queues a wake as a `task-notification` message. Whether that message fires `UserPromptSubmit` is not proven, so the turn review takes any prompt within 10 seconds of the last wake as the wake's own. A prompt the user sends in those 10 seconds keeps the hold count too.
82
88
  - `blocking/turn_review_gate.py` starts `claude -p`, which inherits the parent session id unless the gate strips it. A review that kept `CLAUDE_CODE_SESSION_ID` would write into the parent's transcript.
83
- - Each review run calls a model and costs about $0.03. Leave `CLAUDE_TURN_REVIEW_REPOSITORIES` unset and the gate makes no snapshot and no call.
89
+ - Each review run calls a model, Sonnet at high effort. Twelve measured runs cost $0.50 in total, from $0.01 to $0.13 each. A judge run is a second model call, on Sonnet at high effort, and its cost is not measured. Leave `CLAUDE_TURN_REVIEW_REPOSITORIES` unset and the gate makes no snapshot and no call.
90
+ - The `rewakeMessage` and `rewakeSummary` of the Stop entry in `hooks.json` speak of a review of the last reply's changes. A wake that holds only a rejected dismissal gets the same prefix.
91
+ - The turn review's dismissal judge has these known limits. A finding the agent neither fixes nor contests closes with no check, and so does an upheld finding the agent then ignores: the rejection wake is its only push, and a later `Dismiss` line for it is ignored. The agent can write the state file in the temp folder and the transcript file, so neither the findings record nor the user's messages are tamper-proof. The judge reads only the last 5 messages the user typed, so a request from earlier in the session is no ground to dismiss. Only entries with `origin.kind` `human` count, so a prompt sent through the SDK or by another program is no ground either, and a typed message that starts with `<` is left out. The judge's own reading of the code and the messages on a live model has not been measured; the tests use a stub.
92
+ - `blocking/task_subject_length_gate.py` passes a `TaskUpdate` with no `subject`, so a status change on an old long item goes through. `TodoWrite` resends the whole list on every call, so one old long item denies every later `TodoWrite` until that item is shortened.
84
93
  - `blocking/step_note_gate.py` is off by default and polls for the transcript record. Subagent calls and unreadable records pass.
85
94
  - `blocking/wakeup_cap_gate.py` lets an `update_trigger` cron change pass, because that input does not say whether the Routine wakes a session. Its step-down values come from fire-time probes: `send_later` rounds its fire time up to the next minute and polls once a minute, so a 1-minute request landed 123 and 158 seconds later. `ScheduleWakeup` rounds its fire time up to the next minute, so requests of 60 and 90 seconds landed 70 and 121 seconds later.
86
95
  - `blocking/verify_before_acting.py` runs after the tool. A block asks the agent to check the claim and undo a contradicted change. A spawn has already started when the hook runs, so a block would stop nothing. The advisory note asks the agent to check the claim before it acts on the spawned agent's result.
87
96
  - The final reply gate blocks the stop and returns its reason to the model, which rewrites the reply. Claude Code ends the turn anyway after eight blocks in a row.
97
+ - Every Stop gate holds a turn through `hooks_constants/stop_hook_hold.py`: exit code 2, the reason on stderr, and the same reason in a stdout `block` decision. Exit code 1 does not hold a turn on Claude Code or Codex, so a Stop gate that crashes lets the turn end. A Cursor payload keeps exit code 0 and gets the reason as `followup_message`.
88
98
  - The edit marker gate scans replacement cards as well as the message text.
89
99
  - The handoff close gate reads the `body` and `comment` fields of issue tools only. A `gh issue close --comment` command in Bash and a pull request body that closes the issue with `Closes #N` do not reach it.
90
100
  - The eval write gate reads Write, Edit, MultiEdit, NotebookEdit and apply_patch calls. A Bash or PowerShell command that writes an eval file reaches it without the gate. An apply_patch that will not parse counts as an eval write when any of its words is an eval path. A missing or unreadable transcript denies the write.
@@ -13,7 +13,7 @@ This family runs nested checkout hooks, refreshes a worktree base, and clears st
13
13
 
14
14
  ## When it fires
15
15
 
16
- - `lifecycle/nested_project_hooks.py` runs on `PreToolUse` matcher `*` at `120` seconds, `UserPromptSubmit` matcher empty at `120` seconds, and `SessionStart` matcher empty at `1800` seconds in `hooks.json`.
16
+ - `lifecycle/nested_project_hooks.py` runs on `PreToolUse` matcher `*` at `120` seconds, `UserPromptSubmit` matcher empty at `120` seconds, and `SessionStart` matcher empty at `1800` seconds in `hooks.json`. The child hooks of one event share a budget 10 seconds under that event's timeout.
17
17
  - `lifecycle/enter_worktree_origin_prefetch.py` runs on `PreToolUse`, matcher `EnterWorktree`, timeout `25` seconds in `hooks.json`.
18
18
  - `lifecycle/session_end_cleanup.py` runs on `SessionEnd`, matcher empty, timeout `3` seconds in `hooks.json`.
19
19
  - `session/plugin_data_dir_cleanup.py` and `session/session_env_cleanup.py` run on `SessionStart`, matcher empty, timeout `10` seconds each in `hooks.json`.
@@ -7,7 +7,7 @@ This family reminds the agent to gather context before a spawn, refuses a brief
7
7
  - `routing/spawn_readiness_hook.py` adds context to a spawn that comes before a read step, or before an answered question or a settled-scope line. The spawn still runs.
8
8
  - `routing/spawn_oversight_hook.py` denies a spawn whose brief has no `Outcome:` line or no `On a blocker:` clause, each with text after it. The first passing spawn of a session, the first of each subagent, and the first after each compaction get the orchestrator oversight directive; the brief check runs on every spawn. The directive says: run each piece through the verified-work flow, with a fresh verifier agent that checks the research, the plan, and the fix, reproduces the issue before it confirms the fix, and leaves the worker's conclusion out of its brief; where the brief allows commits, commit each piece a verifier passed alone, as its own stack level, and otherwise hand it back uncommitted and say so; ask the user before new scope; report as done only what a verifier passed; and watch the agent while it runs. `routing/spawn_brief_text.py` reads the brief from each spawn tool for this hook and the readiness hook.
9
9
  - `routing/thread_spawn_pace_hook.py` reshapes a thread request to Opus at medium when usage is over pace or unreadable. Under pace, a thread request that names a model gets the effort its model allows.
10
- - `routing/subagent_effort_route_hook.py` sets an allowed effort on an Agent or Task spawn: Opus medium, Sonnet high, Fable low, medium or high, and Haiku any effort. A spawn with no effort or one outside its model's list gets Opus medium, Sonnet high, Fable high, or Haiku medium. `routing/subagent_effort_route.py` holds the rule for this hook and the pace hook.
10
+ - `routing/subagent_effort_route_hook.py` sets an allowed effort on an Agent or Task spawn. A spawn with no effort, or one outside its model's list, gets that model's default. The lists and defaults are in [`subagent_effort_levels.json`](../hooks_constants/subagent_effort_levels.json), which both hooks read on every run. Edit the repository copy and reinstall. Each install writes the repository copy over the installed copy under `~/.claude/hooks/hooks_constants/`. Make the same edit to `ALL_BUILT_IN_EFFORT_LEVELS_BY_FAMILY` in `hooks_constants/subagent_effort_route_constants.py`, the fallback the hooks use when the file cannot be read. A test fails while the two differ. A missing file, or one that does not parse, names an effort outside `ALL_KNOWN_EFFORT_NAMES`, leaves out a built-in family, or puts a default outside its own list, writes one line to stderr that names the file and the fault, and the hooks use the built-in levels. `routing/subagent_effort_route.py` holds the rule for this hook, the pace hook and `scripts/claude_account_worker.py`.
11
11
  - `routing/subagent_model_routing.mjs` allows a selected Luna model, remaps eligible requests, and denies unsupported model routing.
12
12
  - `blocking/haiku_spawn_slim_gate.py` denies an Agent, Task, or thread spawn whose `model` names Haiku, except an Agent or Task spawn with `subagent_type` `lean-worker`. The deny reason gives two routes: the `lean-worker` subagent type, and the headless `claude -p` command that loads the slim profile through the account broker.
13
13
 
package/hooks/hooks.json CHANGED
@@ -229,6 +229,16 @@
229
229
  }
230
230
  ]
231
231
  },
232
+ {
233
+ "matcher": "TaskCreate|TaskUpdate|TodoWrite",
234
+ "hooks": [
235
+ {
236
+ "type": "command",
237
+ "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/task_subject_length_gate.py",
238
+ "timeout": 10
239
+ }
240
+ ]
241
+ },
232
242
  {
233
243
  "matcher": "ScheduleWakeup|CronCreate|mcp__.*__(send_later|create_trigger|update_trigger)",
234
244
  "hooks": [
@@ -259,6 +269,16 @@
259
269
  }
260
270
  ]
261
271
  },
272
+ {
273
+ "matcher": "AskUserQuestion",
274
+ "hooks": [
275
+ {
276
+ "type": "command",
277
+ "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/question_brief_gate.py",
278
+ "timeout": 10
279
+ }
280
+ ]
281
+ },
262
282
  {
263
283
  "matcher": "Artifact|Skill",
264
284
  "hooks": [
@@ -450,20 +470,13 @@
450
470
  "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/open_tasks_stop_gate.py",
451
471
  "timeout": 10
452
472
  },
453
- {
454
- "type": "command",
455
- "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/owned_pr_merge_stop_gate.py",
456
- "timeout": 60
457
- },
458
- {
459
- "type": "command",
460
- "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/session_title_turn_gate.py",
461
- "timeout": 10
462
- },
463
473
  {
464
474
  "type": "command",
465
475
  "command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/blocking/turn_review_gate.py",
466
- "timeout": 300
476
+ "timeout": 300,
477
+ "asyncRewake": true,
478
+ "rewakeMessage": "The background review of your last reply's changes finished after that reply ended. Act on it, then continue with the user's request or keep waiting for their reply:",
479
+ "rewakeSummary": "Turn review found problems"
467
480
  }
468
481
  ]
469
482
  }
@@ -5,9 +5,6 @@ import re
5
5
  HOOK_EVENT_NAME = "Stop"
6
6
  LAST_ASSISTANT_MESSAGE_KEY = "last_assistant_message"
7
7
  TRANSCRIPT_PATH_KEY = "transcript_path"
8
- DECISION_KEY = "decision"
9
- BLOCK_DECISION = "block"
10
- REASON_KEY = "reason"
11
8
  ALLOW_EXIT_CODE = 0
12
9
  REWRITE_INSTRUCTION = " Rewrite the reply without it."
13
10
  NON_SPACE_TOKEN_PATTERN = re.compile(r"\S+")
@@ -0,0 +1,61 @@
1
+ """One time budget shared by every slow call a hook run makes.
2
+
3
+ The host kills a hook that outlives its registered timeout, and a killed hook
4
+ sends no signal. A hook opens a budget below that timeout for its run, and each
5
+ git, gh, network, or child call asks how long it may wait::
6
+
7
+ with time_budget(50):
8
+ call_timeout(10) -> 10 while more than 10 seconds are left
9
+ call_timeout(10) -> 3.2 when 3.2 seconds are left
10
+ call_timeout(10) -> None once the budget is spent, so the call is skipped
11
+
12
+ Outside a budget, call_timeout returns the cap, so callers that never open a
13
+ budget keep their own timeouts. A nested budget never ends later than the one
14
+ around it. The budget resets when the block exits, so one run never leaks its
15
+ deadline into the next.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import time
22
+ from collections.abc import Iterator
23
+ from contextlib import contextmanager
24
+ from contextvars import ContextVar
25
+
26
+ _run_deadline: ContextVar[float] = ContextVar("hook_run_deadline", default=math.inf)
27
+
28
+
29
+ @contextmanager
30
+ def time_budget(budget_seconds: float) -> Iterator[None]:
31
+ """Bound every call_timeout inside the block to budget_seconds from now.
32
+
33
+ Args:
34
+ budget_seconds: How long the calls inside the block may take in total.
35
+ """
36
+ deadline = min(_run_deadline.get(), time.monotonic() + budget_seconds)
37
+ reset_token = _run_deadline.set(deadline)
38
+ try:
39
+ yield
40
+ finally:
41
+ _run_deadline.reset(reset_token)
42
+
43
+
44
+ def remaining_seconds() -> float:
45
+ """Return the seconds left in the open budget, or infinity outside one."""
46
+ return _run_deadline.get() - time.monotonic()
47
+
48
+
49
+ def call_timeout(cap_seconds: float) -> float | None:
50
+ """Return the timeout for the next call, or None when no time is left.
51
+
52
+ Args:
53
+ cap_seconds: The call's own timeout, used whole while the budget allows it.
54
+
55
+ Returns:
56
+ The smaller of cap_seconds and the time left, or None once the budget is spent.
57
+ """
58
+ time_left = remaining_seconds()
59
+ if time_left <= 0:
60
+ return None
61
+ return min(cap_seconds, time_left)
@@ -2,23 +2,26 @@
2
2
 
3
3
  Runs one hook script via runpy under __main__ with stdin, stdout, and argv
4
4
  swapped to mimic a standalone invocation, captures what the hook writes to
5
- stdout, and reports whether the hook raised. The runner carries no allow or deny
6
- policy: the caller reads captured_stdout to learn the hook's decision and
7
- applies its own aggregation, so a hook that raises contributes no decision,
8
- matching a standalone hook whose uncaught exception exits nonzero without
9
- blocking the tool call.
5
+ stdout, and reports the hook's exit code and whether the hook raised. The
6
+ runner carries no allow or deny policy: the caller reads captured_stdout to
7
+ learn the hook's decision and applies its own aggregation, so a hook that
8
+ raises contributes no decision, matching a standalone hook whose uncaught
9
+ exception exits nonzero without blocking the tool call. The hook's stderr is
10
+ not swapped, so it reaches the host as the hook wrote it.
10
11
 
11
12
  ::
12
13
 
13
14
  run = run_hook_capturing_output("/hooks/blocking/gate.py", '{"tool_name": "Bash"}')
14
- ok: run.captured_stdout carries the gate's deny JSON, run.did_crash is False
15
- flag: run.did_crash is True when the gate raised, run.captured_stdout is ""
15
+ ok: run.captured_stdout carries the gate's deny JSON, run.did_crash is False
16
+ flag: run.did_crash is True when the gate raised, run.captured_stdout is ""
17
+ block: run.exit_code is 2 when the gate called sys.exit(2)
16
18
 
17
19
  ``run_dispatcher_main`` holds the entry-point shell a hosted-hook dispatcher's
18
- own ``main`` needs: read one stdin payload, resolve its tool_name, and hand
19
- both to the dispatcher's own ``dispatch`` callback. Every dispatcher's
20
- ``main`` reduces to one call into this shared shell, so the read-resolve-exit
21
- boilerplate lives in one place rather than once per dispatcher.
20
+ own ``main`` needs: read one stdin payload, resolve its tool_name, hand
21
+ both to the dispatcher's own ``dispatch`` callback, and exit 2 when dispatch
22
+ returns 2. Every dispatcher's ``main`` reduces to one call into this shared
23
+ shell, so the read-resolve-exit boilerplate lives in one place rather than
24
+ once per dispatcher.
22
25
  """
23
26
 
24
27
  from __future__ import annotations
@@ -32,6 +35,7 @@ import traceback
32
35
  from collections.abc import Callable
33
36
  from dataclasses import dataclass
34
37
 
38
+ from hooks_constants.hosted_hook_runner_constants import BLOCKING_EXIT_CODE
35
39
  from hooks_constants.pre_tool_use_stdin import read_hook_input_dictionary_from_stdin
36
40
 
37
41
 
@@ -42,10 +46,12 @@ class HostedHookRun:
42
46
  Attributes:
43
47
  captured_stdout: The text the hook wrote to stdout during its run.
44
48
  did_crash: True when the hook raised a non-SystemExit exception.
49
+ exit_code: The integer code the hook passed to SystemExit, else 0.
45
50
  """
46
51
 
47
52
  captured_stdout: str
48
53
  did_crash: bool
54
+ exit_code: int = 0
49
55
 
50
56
 
51
57
  def log_hosted_hook_crash(hook_script_path: str, error: Exception) -> None:
@@ -60,28 +66,51 @@ def log_hosted_hook_crash(hook_script_path: str, error: Exception) -> None:
60
66
 
61
67
 
62
68
  def run_hook_capturing_output(hook_script_path: str, payload_text: str) -> HostedHookRun:
63
- """Run a hook in-process, returning its captured stdout and crash flag.
69
+ """Run a hook in-process, returning its captured stdout, crash flag, and exit code.
64
70
 
65
71
  Swaps stdin/stdout/argv to mimic a standalone run, executes via runpy under
66
- __main__, catches SystemExit and any other exception (logged as a crash), and
67
- always restores the swapped streams and argv.
72
+ __main__, records the integer code of a SystemExit, catches any other
73
+ exception (logged as a crash), and always restores the swapped streams and
74
+ argv.
68
75
  """
69
76
  original_stdin, original_stdout, original_argv = sys.stdin, sys.stdout, sys.argv
70
77
  captured_output = io.StringIO()
71
78
  did_crash = False
79
+ exit_code = 0
72
80
  try:
73
81
  sys.stdin = io.StringIO(payload_text)
74
82
  sys.stdout = captured_output
75
83
  sys.argv = [hook_script_path]
76
84
  runpy.run_path(hook_script_path, run_name="__main__")
77
- except SystemExit:
78
- pass
85
+ except SystemExit as exit_signal:
86
+ exit_code = exit_signal.code if isinstance(exit_signal.code, int) else 0
79
87
  except Exception as error:
80
88
  log_hosted_hook_crash(hook_script_path, error)
81
89
  did_crash = True
82
90
  finally:
83
91
  sys.stdin, sys.stdout, sys.argv = original_stdin, original_stdout, original_argv
84
- return HostedHookRun(captured_stdout=captured_output.getvalue(), did_crash=did_crash)
92
+ return HostedHookRun(
93
+ captured_stdout=captured_output.getvalue(), did_crash=did_crash, exit_code=exit_code
94
+ )
95
+
96
+
97
+ def host_exit_code(all_runs: list[HostedHookRun]) -> int:
98
+ """Return 2 when any hosted hook exited 2, else 0.
99
+
100
+ ::
101
+
102
+ [exit 0, exit 2] -> 2
103
+ [exit 0, exit 1] -> 0
104
+
105
+ Args:
106
+ all_runs: The hosted hooks the dispatcher ran.
107
+
108
+ Returns:
109
+ The exit code the dispatcher hands the host.
110
+ """
111
+ if any(each_run.exit_code == BLOCKING_EXIT_CODE for each_run in all_runs):
112
+ return BLOCKING_EXIT_CODE
113
+ return 0
85
114
 
86
115
 
87
116
  def resolved_hook_script_path(relative_path: str) -> str:
@@ -104,13 +133,13 @@ def resolved_hook_script_path(relative_path: str) -> str:
104
133
  return str(hooks_root / relative_path)
105
134
 
106
135
 
107
- def run_dispatcher_main(dispatch: Callable[[str, str], None]) -> None:
136
+ def run_dispatcher_main(dispatch: Callable[[str, str], int | None]) -> None:
108
137
  """Read one stdin payload and hand its JSON text and tool_name to dispatch.
109
138
 
110
139
  Every hosted-hook dispatcher's own ``main`` reduces to this one call.
111
140
  Exits 0 before ever calling dispatch when stdin is empty, malformed, or
112
- names no tool_name string; always exits 0 afterward, since a dispatcher
113
- signals its own outcome, if any, through what dispatch itself writes.
141
+ names no tool_name string. Afterward it exits 2 when dispatch returns 2,
142
+ so a hosted hook's exit 2 reaches the host, and exits 0 otherwise.
114
143
 
115
144
  Args:
116
145
  dispatch: The dispatcher's own ``dispatch(payload_text, tool_name)``.
@@ -122,5 +151,6 @@ def run_dispatcher_main(dispatch: Callable[[str, str], None]) -> None:
122
151
  tool_name = payload_dictionary.get("tool_name", "")
123
152
  if not isinstance(tool_name, str) or not tool_name:
124
153
  sys.exit(0)
125
- dispatch(payload_text, tool_name)
154
+ if dispatch(payload_text, tool_name) == BLOCKING_EXIT_CODE:
155
+ sys.exit(BLOCKING_EXIT_CODE)
126
156
  sys.exit(0)
@@ -0,0 +1,3 @@
1
+ """Constants for the shared in-process runner of dispatcher-hosted hooks."""
2
+
3
+ BLOCKING_EXIT_CODE = 2
@@ -26,6 +26,14 @@ ALL_MATCH_TARGET_KEYS_BY_EVENT: dict[str, str] = {
26
26
  SESSION_START_EVENT: "source",
27
27
  USER_PROMPT_SUBMIT_EVENT: "prompt",
28
28
  }
29
+ ALL_RUN_BUDGET_SECONDS_BY_EVENT: dict[str, float] = {
30
+ PRE_TOOL_USE_EVENT: 118,
31
+ SESSION_START_EVENT: 1798,
32
+ USER_PROMPT_SUBMIT_EVENT: 118,
33
+ }
34
+ CUT_OFF_CHILD_LINE_TEMPLATE: str = "nested_project_hooks: {checkout}: {command!r} {outcome}\n"
35
+ NOT_STARTED_OUTCOME: str = "did not start, no run time left"
36
+ STOPPED_OUTCOME_TEMPLATE: str = "stopped after {seconds:.1f} s, its output is dropped"
29
37
 
30
38
  ALL_SHELL_PROGRAM_NAMES: tuple[str, ...] = ("bash", "sh")
31
39
  SHELL_COMMAND_FLAG: str = "-c"
@@ -14,6 +14,7 @@ ONCE_MARKER_FILE_PREFIX = "claude-once-"
14
14
  ONCE_MARKER_FILE_SUFFIX = ".marker"
15
15
  ONCE_MARKER_NAME_SEPARATOR = "."
16
16
  EXCLUSIVE_CREATE_MODE = "x"
17
+ WHOLE_SESSION_MARKER_PART = "session"
17
18
 
18
19
  TRANSCRIPT_READ_MODE = "rb"
19
20
  CLAUDE_COMPACTION_FIELD = "subtype"
@@ -2,9 +2,6 @@
2
2
 
3
3
  HOOK_EVENT_NAME = "Stop"
4
4
  TRANSCRIPT_PATH_KEY = "transcript_path"
5
- DECISION_KEY = "decision"
6
- BLOCK_DECISION = "block"
7
- REASON_KEY = "reason"
8
5
  ALLOW_EXIT_CODE = 0
9
6
  STOP_HOOK_ACTIVE_KEY = "stop_hook_active"
10
7
  UTF8_ENCODING = "utf-8"
@@ -33,7 +30,6 @@ TODO_MERGE_KEY = "merge"
33
30
  ROLE_KEY = "role"
34
31
  ASSISTANT_ROLE = "assistant"
35
32
  CURSOR_CONVERSATION_ID_KEY = "conversation_id"
36
- CURSOR_FOLLOWUP_MESSAGE_KEY = "followup_message"
37
33
  CURSOR_STATUS_KEY = "status"
38
34
  CURSOR_COMPLETED_STATUS = "completed"
39
35
  CURSOR_LOOP_COUNT_KEY = "loop_count"
@@ -56,8 +56,6 @@ __all__ = [
56
56
  "REVIEW_LOOP_CONTEXT_TEMPLATE",
57
57
  "SESSION_RECORD_FILE_TEMPLATE",
58
58
  "SESSION_RECORD_TEMPORARY_PREFIX",
59
- "STOP_BLOCK_RECORD_FILE_TEMPLATE",
60
- "STOP_BLOCK_RECORD_TEMPORARY_PREFIX",
61
59
  "ALL_PULL_REQUEST_FIELD_NAMES",
62
60
  ]
63
61
 
@@ -118,8 +116,6 @@ JSON_OBJECT_OPENER: str = "{"
118
116
 
119
117
  SESSION_RECORD_FILE_TEMPLATE: str = "owned-pr-loop-{session_file_id}.json"
120
118
  SESSION_RECORD_TEMPORARY_PREFIX: str = "owned-pr-loop-"
121
- STOP_BLOCK_RECORD_FILE_TEMPLATE: str = "owned-pr-stop-blocks-{session_file_id}.json"
122
- STOP_BLOCK_RECORD_TEMPORARY_PREFIX: str = "owned-pr-stop-blocks-"
123
119
  ALL_PULL_REQUEST_FIELD_NAMES: tuple[str, ...] = ("owner", "repository", "number", "url")
124
120
 
125
121
  REVIEW_LOOP_CONTEXT_TEMPLATE: str = (