claude-dev-env 8.117.3 → 8.117.5

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 (80) hide show
  1. package/_shared/pr-loop/scripts/pyproject.toml +1 -1
  2. package/_shared/process-tree/scripts/pyproject.toml +1 -1
  3. package/bin/cde.mjs +4 -3
  4. package/bin/cde.test.mjs +87 -1
  5. package/bin/codex-compat.mjs +4 -3
  6. package/bin/codex-compat.test.mjs +91 -1
  7. package/bin/install-plan.mjs +2 -1
  8. package/bin/install.mjs +24 -7
  9. package/bin/install.plan.test.mjs +15 -0
  10. package/bin/install.test.mjs +61 -0
  11. package/bin/python-probe.mjs +42 -0
  12. package/bin/python-probe.test.mjs +19 -2
  13. package/docs/references/advisor-tool.md +2 -0
  14. package/docs/rule-guides/features-start-with-an-eval.md +3 -3
  15. package/docs/rule-guides/proof-before-pull-request.md +2 -2
  16. package/hooks/blocking/bash_pre_tool_use_dispatcher.py +11 -4
  17. package/hooks/blocking/build_eval_before_eval_write_gate.py +10 -4
  18. package/hooks/blocking/followup_pr_dedupe.py +381 -64
  19. package/hooks/blocking/gate_child_process.py +187 -0
  20. package/hooks/blocking/gate_run_reads.py +116 -35
  21. package/hooks/blocking/merge_review_gate.py +93 -10
  22. package/hooks/blocking/merge_review_gate_parts/create_folders.py +346 -0
  23. package/hooks/blocking/merge_review_gate_parts/create_options.py +86 -0
  24. package/hooks/blocking/merge_review_gate_parts/folder_state.py +107 -0
  25. package/hooks/blocking/merge_review_gate_parts/open_request.py +199 -64
  26. package/hooks/blocking/merge_review_gate_parts/quoted_lines.py +283 -0
  27. package/hooks/blocking/merge_review_gate_parts/wrapped_creates.py +126 -0
  28. package/hooks/blocking/pr_lifecycle_skill_gate.py +61 -18
  29. package/hooks/blocking/pre_tool_use_dispatcher.py +25 -3
  30. package/hooks/blocking/pull_request_proof.py +5 -51
  31. package/hooks/blocking/pull_request_proof_edit_gate.py +19 -5
  32. package/hooks/blocking/test_bash_pre_tool_use_dispatcher.py +54 -0
  33. package/hooks/blocking/test_build_eval_before_eval_write_gate.py +64 -0
  34. package/hooks/blocking/test_followup_pr_dedupe.py +464 -1
  35. package/hooks/blocking/test_gate_child_process.py +64 -0
  36. package/hooks/blocking/test_gate_run_reads.py +364 -4
  37. package/hooks/blocking/test_merge_review_gate.py +832 -39
  38. package/hooks/blocking/test_pr_lifecycle_skill_gate.py +130 -4
  39. package/hooks/blocking/test_pre_tool_use_dispatcher.py +64 -0
  40. package/hooks/blocking/test_pull_request_proof.py +16 -0
  41. package/hooks/blocking/test_pull_request_proof_edit_gate.py +60 -0
  42. package/hooks/blocking/tests/test_create_folders.py +290 -0
  43. package/hooks/blocking/tests/test_create_options.py +34 -0
  44. package/hooks/blocking/tests/test_folder_state.py +40 -0
  45. package/hooks/blocking/tests/test_open_request.py +350 -44
  46. package/hooks/blocking/tests/test_quoted_lines.py +86 -0
  47. package/hooks/blocking/tests/test_wrapped_creates.py +42 -0
  48. package/hooks/features/bash-dispatchers.md +1 -1
  49. package/hooks/features/conduct-gates.md +7 -7
  50. package/hooks/features/session-context.md +3 -3
  51. package/hooks/features/write-edit-blocking.md +3 -3
  52. package/hooks/hooks_constants/advisor_rules_prompt_constants.py +14 -6
  53. package/hooks/hooks_constants/build_eval_before_eval_write_gate_constants.py +5 -0
  54. package/hooks/hooks_constants/followup_pr_dedupe_constants.py +34 -1
  55. package/hooks/hooks_constants/gate_fault.py +52 -0
  56. package/hooks/hooks_constants/gate_fault_constants.py +13 -0
  57. package/hooks/hooks_constants/gate_run_reads_constants.py +9 -1
  58. package/hooks/hooks_constants/merge_review_gate_constants.py +94 -1
  59. package/hooks/hooks_constants/piped_pytest_blocker_constants.py +2 -0
  60. package/hooks/hooks_constants/pr_lifecycle_skill_gate_constants.py +6 -1
  61. package/hooks/hooks_constants/pre_tool_use_stdin.py +23 -3
  62. package/hooks/hooks_constants/shell_command_pipeline.py +68 -8
  63. package/hooks/hooks_constants/shell_command_segments.py +2 -2
  64. package/hooks/hooks_constants/shell_command_wrappers.py +3 -2
  65. package/hooks/hooks_constants/test_followup_pr_dedupe_constants.py +7 -0
  66. package/hooks/hooks_constants/test_gate_fault.py +41 -0
  67. package/hooks/hooks_constants/test_piped_pytest_blocker_constants.py +5 -0
  68. package/hooks/hooks_constants/test_pr_lifecycle_skill_gate_constants.py +10 -0
  69. package/hooks/hooks_constants/test_pre_tool_use_stdin.py +97 -0
  70. package/hooks/hooks_constants/test_shell_command_pipeline.py +55 -0
  71. package/hooks/hooks_constants/test_shell_command_segments.py +15 -0
  72. package/hooks/hooks_constants/test_shell_command_wrappers.py +6 -0
  73. package/hooks/hooks_constants/transcript_skill_scan_constants.py +6 -0
  74. package/hooks/pyproject.toml +2 -3
  75. package/hooks/session/advisor_rules_prompt.py +53 -9
  76. package/hooks/session/test_advisor_rules_prompt.py +70 -4
  77. package/hooks/test_python_floor.py +197 -0
  78. package/hooks/test_transcript_skill_scan.py +324 -0
  79. package/hooks/transcript_skill_scan.py +233 -2
  80. package/package.json +1 -1
@@ -4,7 +4,7 @@ This family rewrites a Git Bash command when path conversion would change a revi
4
4
 
5
5
  ## Checks
6
6
 
7
- - `blocking/bash_pre_tool_use_dispatcher.py` combines hosted shell decisions and forwards an updated command when a hosted rewriter allows it.
7
+ - `blocking/bash_pre_tool_use_dispatcher.py` combines hosted shell decisions and forwards an updated command when a hosted rewriter allows it. When no hosted hook decides but one prints a top-level `systemMessage`, such as the warning `transcript_root_search_gate.py` prints when its check raises, the dispatcher prints that `systemMessage` alone, with no `permissionDecision`.
8
8
  - `blocking/msys_rev_path_rewriter.py` adds a narrow `MSYS2_ARG_CONV_EXCL` prefix for affected revision and path tokens.
9
9
  - `blocking/headless_claude_broker_gate.py` denies a headless `claude -p` or `claude --print` call and names the broker command to run instead.
10
10
  - `blocking/gh_global_account_switch_gate.py` denies `gh auth switch`, `gh auth login`, and `gh auth logout` and names the per-command `GH_TOKEN` form to run instead.
@@ -16,11 +16,11 @@ This family stops a chat reply, edited message, or tool call when its payload br
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.
19
- - `blocking/pr_lifecycle_skill_gate.py` denies a commit, push, pull request action, or merge until the `pr-lifecycle` skill appears in the transcript since the last compaction. Read-only `gh pr` subcommands (`view`, `list`, `checks`, `diff`, `status`) pass without it, unless a later argument names another `gh pr` subcommand.
19
+ - `blocking/pr_lifecycle_skill_gate.py` denies a commit, push, pull request action, or merge until the `pr-lifecycle` skill appears in the transcript since the last compaction. The scan reads the transcript newest line first, so the first load or compaction boundary it meets decides. Every create spelling the shared listing in `blocking/followup_pr_dedupe.py` reads counts as a pull request action. Read-only `gh pr` subcommands (`view`, `list`, `checks`, `diff`, `status`) pass without it, unless a later argument names another `gh pr` subcommand.
20
20
  - `blocking/resolve_thread_reply_gate.py` denies a review thread resolve until the agent's own transcript shows a reply on that same thread that posted after the last user prompt and that no successful resolve of the thread has spent. A resolve is a `resolve_review_thread` call, which names the thread by `threadID`; a `pull_request_review_write` call with method `resolve_thread`, which names it by `threadId`; a shell command with a `gh api graphql` `resolveReviewThread` mutation, which names it by a literal `PRRT_` id; or a shell call to `pulls/<n>/ccr/comments/<id>/resolve`, which names it by a comment id. A graphql resolve that names no `PRRT_` id is denied. A reply is an `add_reply_to_pull_request_comment` call, or a `gh api` call to a comment's `replies` endpoint or to `addPullRequestReviewThreadReply`, which names its thread by `PRRT_` id. A reply and a resolve by comment id match when they name the same comment, or when a successful tool result in the transcript, such as `pull_request_read` `get_review_comments`, lists the comment under the thread by its `discussion_r` anchor or `databaseId`. A reply whose result is an error does not count. With no readable transcript, the resolve passes.
21
21
  - `blocking/verify_before_commit_gate.py` denies a `git commit` in a repository with a `.claude/skills/verify` or `.agents/skills/verify` directory until the `verify` skill loads after the last user prompt, through a Skill call whose result comes back without an error, or the `/verify` command in that prompt. It reads the committed paths from the staged diff, the tracked changes for `-a`, and the paths of each `git add` earlier in the same command, and passes a commit whose paths are all docs, images, test files, or `.json`, `.jsonl`, `.yaml`, `.yml`, or `.csv` files under a `docs` folder.
22
22
  - `blocking/build_eval_before_eval_write_gate.py` denies a write to an eval file until a Skill call named exactly `claude-api` with args `build-eval`, or the `/claude-api build-eval` command, appears in the transcript.
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.
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 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. 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. That reading is the one that covers `GH_REPO=o/r env -u GH_REPO gh pr create`, where gh opens in the origin repository. So a first create behind a `GH_REPO=` prefix needs a clean pass for the prefix repository and for origin, and a create that passes `--repo owner/name` needs one for that repository only. 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`. 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.
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
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.
@@ -41,11 +41,11 @@ This family stops a chat reply, edited message, or tool call when its payload br
41
41
  - `blocking/question_brief_gate.py` runs on `PreToolUse`, matcher `AskUserQuestion`, timeout `10` seconds in `hooks.json`. Its transcript poll stops at 3 seconds.
42
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`.
43
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`.
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).
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 read deadlines are 12 s and 20 s after the gate's read clock starts. A stopped read child gets 1 s more to close its pipes, and a scan finishes the line it is parsing before it stops. The budget test in `test_gate_run_reads.py` reserves two such graces and a 5 s margin inside the 30 s registration. The skill scan answers to the 12 s deadline and the build-eval scan to the 20 s deadline. Each scan reads the clock before each 1 MiB block of the file and before each line. A line over 16 MiB ends the scan as a passed deadline does. A transcript that cannot seek to its end, such as a named pipe or a procfs file, is first copied forward into memory under the same clock and the same line cap. A copy that passes 64 MiB also ends the scan as a passed deadline does. It splits lines where text mode does, on `\n`, `\r\n` and a lone `\r`. On POSIX a stopped read child is killed with its process group. A process that left that group by starting its own session is outside it. On Windows the child joins a job object right after it starts, and a stopped read ends every process in the job, including a grandchild that holds the output pipe after the child exited. When the child could not join a job, or the job could not be ended, the gate runs a bounded hidden `taskkill /T /F`. A process the child starts before it joins the job is outside the job. A check that raises, once the call is known to be a governed action, denies with a reason that names the error.
45
45
  - `blocking/resolve_thread_reply_gate.py` runs on `PreToolUse`, matcher `Bash|PowerShell|mcp__.*__resolve_review_thread|mcp__.*__pull_request_review_write`, timeout `10` seconds in `hooks.json`.
46
46
  - `blocking/verify_before_commit_gate.py` runs on `PreToolUse`, matcher `Bash|PowerShell`, timeout `30` seconds in `hooks.json`.
47
- - `blocking/build_eval_before_eval_write_gate.py` runs on `PreToolUse`, matcher `Write|Edit|MultiEdit|NotebookEdit|apply_patch`, timeout `10` seconds in `hooks.json`.
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
+ - `blocking/build_eval_before_eval_write_gate.py` runs on `PreToolUse`, matcher `Write|Edit|MultiEdit|NotebookEdit|apply_patch`, timeout `10` seconds in `hooks.json`. Its transcript scan reads the clock before each block and each line, and stops at the first such read after 5 s, so a line already being parsed finishes first. A scan ended by that stop, or by a line over 16 MiB, counts as no build-eval call shown.
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 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.
49
49
  - `blocking/artifact_dark_mode_gate.py` runs on `PreToolUse`, matcher `Artifact`, timeout `60` seconds in `hooks.json`.
50
50
  - `blocking/send_user_file_worktree_root_gate.py` runs on `PreToolUse`, matcher `SendUserFile`, timeout `10` seconds in `hooks.json`.
51
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.
@@ -73,7 +73,7 @@ Preconditions:
73
73
  - **Lifecycle skill.** Input is a `git commit` or `gh pr create` command with no `pr-lifecycle` invocation in the transcript. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_pr_lifecycle_skill_gate.py -q`. The adjacent test observes a denial, then a silent allow once the skill or its slash command appears.
74
74
  - **Verify before commit.** Input is `git add app.py; git commit -m change` in a temporary repository with `.agents/skills/verify`, and a transcript with no `verify` load after its last prompt. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_verify_before_commit_gate.py -q`. The adjacent test observes a denial, then a silent allow after a `verify` Skill call or a `/verify` prompt. A load before the last prompt still denies. A docs-only commit, a commit of data files under a `docs` folder, a tests-only commit, and a repository with no verify skill pass. A `.py` file under `docs` and a `.json` file outside `docs` still deny.
75
75
  - **Eval write.** Input is a Write to `evals/cases.json` with no build-eval call in the transcript. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_build_eval_before_eval_write_gate.py -q`. The adjacent test observes a denial, then an allow once the call appears; a write outside an eval path passes.
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.
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. 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 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.
77
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.
78
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.
79
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.
@@ -99,6 +99,6 @@ Preconditions:
99
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.
100
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.
101
101
  - The verify gate passes when the transcript is missing or unreadable, or when git cannot resolve the repository. It reads the repository from the payload `cwd` and `git -C`, so a `cd <dir> && git commit` chain is checked against the session directory. A `git commit <pathspec>` that names paths without `git add` is checked against the staged diff only.
102
- - The lifecycle gate counts only invocations after the last compaction, so a compacted session invokes `pr-lifecycle` again. A missing or unreadable transcript allows the call.
102
+ - The lifecycle gate counts only invocations after the last compaction, so a compacted session invokes `pr-lifecycle` again. A missing or unreadable transcript allows the call. A scan the deadline stops counts as no load found, and its deny carries a sentence that says to load the skill again.
103
103
  - The dark mode gate denies a page publish when Node, Playwright or Chromium is missing, and its reason names the install command. It checks both dark signals, `prefers-color-scheme: dark` and `data-theme="dark"` on the root element.
104
104
  - The clean-review gate trusts the receipt. A receipt the agent writes by hand with zero findings, or with every finding ruled out and a rulings link, passes, so the pr-lifecycle skill names the review loop that writes it. A `gh pr merge` that names no repository is denied, because the gate cannot tell which repository the current branch belongs to.
@@ -8,7 +8,7 @@ This family injects reminders and task guidance when an agent starts, resumes, s
8
8
  - `session/compaction_recall_prompt.py` returns every message the user typed after a compaction. `session/compaction_user_messages.py` reads them from a Claude Code transcript or a Codex rollout. `session/compaction_trim.py` trims each one in Python: it drops filler, articles, and gratitude, keeps approvals, continuation requests, backtick spans, and paths as typed, and marks a reversed message `(overruled by #N)`. No model runs, so the hook works on Claude Code and Codex with no account.
9
9
  - `session/task_tool_prompt.py` injects a task tracking directive at session start.
10
10
  - `session/working_style_prompt.py` injects the session's working style at session start.
11
- - `session/advisor_rules_prompt.py` injects advisor guidance when the built-in advisor is enabled. For evidence on when an advisor pays, see [Subagents and fan-out](../../docs/model-choice/subagents-and-fan-out.md).
11
+ - `session/advisor_rules_prompt.py` injects advisor guidance when the built-in advisor is enabled. It stays silent when the SessionStart payload's `model` is the `advisorModel` value or is in its family, such as `claude-fable-5-2` against `fable`. When the payload has no `model`, the guidance names the advisor model and tells a session on that model to plan no consults. For evidence on when an advisor pays, see [Subagents and fan-out](../../docs/model-choice/subagents-and-fan-out.md).
12
12
  - `session/orchestrator_auto_starter.py` injects an orchestrator directive when its environment flag is enabled.
13
13
  - `session/plugin_session_baseline_writer.py` records each plugin's `version` and `installPath` from `installed_plugins.json` to a per-session file in the system temp folder. It writes on `startup`, or when the session has no baseline yet, and leaves an existing baseline alone on `resume`, `clear`, and `compact`.
14
14
  - `session/plugin_change_warning.py` compares `installed_plugins.json` with that baseline before each prompt. It names each plugin whose version or install path changed, or that the baseline lacks, once per session, and tells the user to restart Claude Code.
@@ -38,7 +38,7 @@ Preconditions:
38
38
  - **Compaction recall.** Input is a Claude Code transcript or a Codex rollout with typed, meta, sidechain, peer, and harness entries across a compaction. Run `python -m pytest packages/claude-dev-env/hooks/session/test_compaction_user_messages.py packages/claude-dev-env/hooks/session/test_compaction_trim.py packages/claude-dev-env/hooks/session/test_compaction_recall_prompt.py packages/claude-dev-env/hooks/session/test_compaction_trim_eval.py -q`. The tests observe only typed messages, a stable result across a second compaction, the trim rules, the recall budget, and the trimmed lines in the hook's `additionalContext`. `python packages/claude-dev-env/hooks/session/compaction_trim_eval.py` trims each fixture transcript with planted facts, prints the share of facts that survive, the reversals marked, and the compression ratio, and exits 1 on any loss.
39
39
  - **Task tracking.** Input is a SessionStart event. Run `python -m pytest packages/claude-dev-env/hooks/session/test_task_tool_prompt.py -q`. The adjacent test observes a `SessionStart` context directive that names the task tool.
40
40
  - **Working style.** Input is a SessionStart event. Run `python -m pytest packages/claude-dev-env/hooks/session/test_working_style_prompt.py -q`. The adjacent test observes the fixed context text.
41
- - **Advisor guidance.** Input is SessionStart with `advisorModel` set. Run `python -m pytest packages/claude-dev-env/hooks/session/test_advisor_rules_prompt.py -q`. The adjacent test observes guidance only when the advisor setting is enabled.
41
+ - **Advisor guidance.** Input is SessionStart with `advisorModel` set. Run `python -m pytest packages/claude-dev-env/hooks/session/test_advisor_rules_prompt.py -q`. The adjacent test observes guidance only when the advisor setting is enabled and the payload's model is in another family or absent, and silence when the payload's model is the advisor model or shares its family.
42
42
  - **Orchestrator start.** Input is SessionStart with its opt-in flag set. Run `python -m pytest packages/claude-dev-env/hooks/session/test_orchestrator_auto_starter.py -q`. The adjacent test observes an orchestrator directive.
43
43
  - **Plugin restart warning.** Input is a SessionStart event, an `installed_plugins.json` change, and a prompt. Run `python -m pytest packages/claude-dev-env/hooks/session/test_plugin_session_baseline_writer.py packages/claude-dev-env/hooks/session/test_plugin_change_warning.py packages/claude-dev-env/hooks/test_plugin_session_baseline.py -q`. The tests observe one warning for a changed version, a changed install path, and a plugin new since start, silence on a `lastUpdated` refresh and on a second prompt, and a warning that still fires after a `compact` SessionStart.
44
44
  - **Artifact template pointer.** Input is an `Artifact` quickstart call. Run `python -m pytest packages/claude-dev-env/hooks/session/test_artifact_template_pointer.py -q`. The adjacent test observes the status flowchart path first, the html-plan path ahead of the template path in `additionalContext`, and silence on a publish call or another skill.
@@ -51,6 +51,6 @@ Preconditions:
51
51
  - The recall keeps the first message and the newest that fit in 6,000 characters, under the 2,500 token preview limit Codex applies to hook context. A message over 1,500 characters is cut, and the line says how much was left out.
52
52
  - The overruled mark comes from cue phrases such as `instead` or `change of plan` and shared words. A reversal with no cue phrase gets no mark, and the later line still overrides by its place. A cue in a message that agrees with an earlier one, such as `dont use haiku` after `use Python trim instead of Haiku`, marks that earlier line too, so the context tells the agent to follow the later message where the two differ.
53
53
  - `session/skill_loaded_reminder.py` has three registration points. An `Agent` or `Task` helper gets no poteto-mode line from it; a brief that needs the skill names it, or spawns `pstack:poteto-agent`. Its tests cover the compaction restore, the workflow helper reminder, silence on a user turn while the skill stays loaded, silence on a spawn payload, and no `PreToolUse` registration in `hooks.json`.
54
- - The advisor prompt depends on settings and an environment disable flag. The two starter scripts each use separate opt-in checks.
54
+ - The advisor prompt depends on settings, an environment disable flag, and the payload's `model`. Claude Code 2.1.325 sends `model` on an interactive `claude` start and leaves it out under `claude -p` and the desktop app's stream-json launch, so those sessions get the guidance with the advisor model named. The two starter scripts each use separate opt-in checks.
55
55
  - The issue tracker starter requires the checkout to appear in the project path registry.
56
56
  - `advisory/auto_mode_denial_quick_fix.py` lives under `advisory/` but belongs here because its only output is agent context and a one-line user message.
@@ -4,7 +4,7 @@ This family decides whether an agent's file mutation can run.
4
4
 
5
5
  ## Checks
6
6
 
7
- - `blocking/pre_tool_use_dispatcher.py` runs its native description check and returns one permission decision.
7
+ - `blocking/pre_tool_use_dispatcher.py` runs its native description check and returns one permission decision, or a hosted hook's `systemMessage` alone when no hook decides.
8
8
  - `blocking/state_description_blocker.py` rejects historical or comparative prose in supported comments, docstrings, and Markdown.
9
9
  - `blocking/context_budget_blocker.py` rejects a write that grows a skill entry, `AGENTS.md`, `CLAUDE.md`, or rule file past its context budget.
10
10
  - `blocking/pull_request_proof_edit_gate.py` rejects an edit to the pull request proof gate, its constants, this edit gate, or the dispatcher roster while the proof gate's last deny of a create call in the session has no passing create call after it.
@@ -14,7 +14,7 @@ This family decides whether an agent's file mutation can run.
14
14
  - `blocking/pre_tool_use_dispatcher.py` runs on `PreToolUse`, matcher `Write|Edit|MultiEdit|apply_patch`, timeout `60` seconds in `hooks.json`.
15
15
  - `blocking/state_description_blocker.py` runs through the dispatcher's native evaluator on `PreToolUse`, matcher `Write|Edit|MultiEdit|apply_patch`, timeout `60` seconds. Its evaluator checks `Write`, `Edit`, and `MultiEdit` payloads and skips `apply_patch`.
16
16
  - `blocking/context_budget_blocker.py` runs inside that dispatcher as a blocking hosted entry on `PreToolUse`, matcher `Write|Edit|MultiEdit|apply_patch`, timeout `60` seconds. It reads `.claude/context-budget.json` from the edited file's own repository.
17
- - `blocking/pull_request_proof_edit_gate.py` runs inside that dispatcher as a blocking hosted entry on `PreToolUse` for `Write`, `Edit`, `MultiEdit`, and `apply_patch`, timeout `60` seconds. It reads the session transcript the payload names and, for a subagent, its own transcript.
17
+ - `blocking/pull_request_proof_edit_gate.py` runs inside that dispatcher as a blocking hosted entry on `PreToolUse` for `Write`, `Edit`, `MultiEdit`, and `apply_patch`, timeout `60` seconds. It reads the session transcript the payload names and, for a subagent, its own transcript. When its check raises, the gate denies the edit itself, with a reason that names the fault, and writes the traceback to stderr.
18
18
 
19
19
  ## Proving it
20
20
 
@@ -31,6 +31,6 @@ Preconditions:
31
31
 
32
32
  - `ALL_HOSTED_HOOK_ENTRIES` lists the blocking context budget gate and the proof edit gate. The dispatcher calls the description evaluator through its native hook table.
33
33
  - The context budget gate denies only what an edit adds. A repository with no policy file uses built-in kinds and treats the file's current text as its baseline entry, so a file under its line limit may grow to the limit and a file over it may only shrink. The CI ratchet runs in `scripts/policy_lint/adapter_context_budget.py`, never in the hook. See the [context budget reference](../../.agents/skills/build-eval/reference/context-budget.md).
34
- - The dispatcher runs hosted entries in roster order. A hosted advisory crash stays silent; a native blocking check can deny the write.
34
+ - The dispatcher runs hosted entries in roster order. A hosted advisory crash stays silent. A native blocking check can deny the write. When no hosted hook denies or allows but one prints a top-level `systemMessage`, such as the warning `print_decision_from_stdin` prints when a gate's check raises, the dispatcher prints that `systemMessage` alone, with no `permissionDecision`.
35
35
  - `scripts/policy_lint/adapter_detectors.py` also loads `blocking/state_description_blocker.py`. Check that adapter when changing its evaluator.
36
36
  - `bin/install.mjs` names folded and retired script paths so reinstall can remove stale registrations.
@@ -3,6 +3,8 @@
3
3
  Each sentence in ``ALL_ADVISOR_RULE_SENTENCES`` is copied word for word from
4
4
  ``docs/references/advisor-tool.md``, which stays the one source. A
5
5
  synchronization test fails when a sentence drifts from that document.
6
+ ``ADVISOR_RULES_PROMPT_TEMPLATE`` takes the configured advisor model as
7
+ ``advisor_model``.
6
8
  """
7
9
 
8
10
  from __future__ import annotations
@@ -10,28 +12,34 @@ from __future__ import annotations
10
12
  __all__ = [
11
13
  "ADVISOR_DISABLE_ENV_VAR",
12
14
  "ADVISOR_MODEL_SETTINGS_KEY",
13
- "ADVISOR_RULES_HEADER",
14
- "ADVISOR_RULES_PROMPT",
15
+ "ADVISOR_RULES_HEADER_TEMPLATE",
16
+ "ADVISOR_RULES_PROMPT_TEMPLATE",
15
17
  "ALL_ADVISOR_RULE_SENTENCES",
16
18
  "ALL_ADVISOR_DISABLE_ENV_TRUE_VALUES",
19
+ "ALL_MODEL_FAMILY_NAMES",
17
20
  "CLAUDE_CONFIG_DIR_ENV_VAR",
18
21
  "DEFAULT_CLAUDE_CONFIG_DIRECTORY_NAME",
22
+ "SESSION_MODEL_PAYLOAD_KEY",
19
23
  "USER_SETTINGS_FILE_NAME",
20
24
  ]
21
25
 
22
26
  ADVISOR_MODEL_SETTINGS_KEY = "advisorModel"
27
+ SESSION_MODEL_PAYLOAD_KEY = "model"
28
+ ALL_MODEL_FAMILY_NAMES = ("fable", "opus", "sonnet", "haiku")
23
29
  ADVISOR_DISABLE_ENV_VAR = "CLAUDE_CODE_DISABLE_ADVISOR_TOOL"
24
30
  ALL_ADVISOR_DISABLE_ENV_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
25
31
  CLAUDE_CONFIG_DIR_ENV_VAR = "CLAUDE_CONFIG_DIR"
26
32
  DEFAULT_CLAUDE_CONFIG_DIRECTORY_NAME = ".claude"
27
33
  USER_SETTINGS_FILE_NAME = "settings.json"
28
34
 
29
- ADVISOR_RULES_HEADER = (
30
- "ADVISOR, when `advisor` is in your tool list. Use your own judgment on when a"
31
- " consult helps. Starting points from ~/.claude/docs/references/advisor-tool.md:"
35
+ ADVISOR_RULES_HEADER_TEMPLATE = (
36
+ "ADVISOR, when `advisor` is in your tool list. The advisor runs on `{advisor_model}`."
37
+ " Use your own judgment on when a consult helps."
38
+ " Starting points from ~/.claude/docs/references/advisor-tool.md:"
32
39
  )
33
40
 
34
41
  ALL_ADVISOR_RULE_SENTENCES = (
42
+ "A session that runs on the advisor model itself plans no advisor consults.",
35
43
  "Call for design, architecture, and risk questions where you will not touch a file.",
36
44
  "On tasks longer than a few steps, aim for an early approach consult and a completion review.",
37
45
  "This cadence guides planning and leaves the task free to follow its evidence.",
@@ -41,4 +49,4 @@ ALL_ADVISOR_RULE_SENTENCES = (
41
49
  "Give the advice serious weight.",
42
50
  )
43
51
 
44
- ADVISOR_RULES_PROMPT = " ".join((ADVISOR_RULES_HEADER, *ALL_ADVISOR_RULE_SENTENCES))
52
+ ADVISOR_RULES_PROMPT_TEMPLATE = " ".join((ADVISOR_RULES_HEADER_TEMPLATE, *ALL_ADVISOR_RULE_SENTENCES))
@@ -17,3 +17,8 @@ UNREADABLE_TRANSCRIPT_BEFORE_EVAL_WRITE_REASON = (
17
17
  " held because no /claude-api build-eval call can be confirmed. A retry clears only"
18
18
  " once the hook receives a readable transcript."
19
19
  )
20
+ EVAL_WRITE_SCAN_RAN_OUT_SENTENCE = (
21
+ " This hook's transcript scan ran out of time on this run, so it may have missed an"
22
+ " older build-eval call. Calling /claude-api build-eval again puts that call where"
23
+ " the scan finds it first."
24
+ )
@@ -4,7 +4,6 @@ FOLLOWUP_PARENT_PATTERN = r"follow[- ]?up to #(\d+)(?!\d)"
4
4
  GITHUB_API_ROOT = "https://api.github.com"
5
5
  OPEN_PULL_REQUESTS_PATH_TEMPLATE = "/repos/{owner}/{repo}/pulls?state=open&per_page=100"
6
6
  READ_TIMEOUT_SECONDS = 4
7
- ALL_GH_CREATE_WORDS = ["pr", "create"]
8
7
  ALL_BODY_OPTIONS = frozenset({"-b", "--body"})
9
8
  ALL_BODY_FILE_OPTIONS = frozenset({"-F", "--body-file"})
10
9
  ALL_REPOSITORY_OPTIONS = frozenset({"-R", "--repo"})
@@ -17,7 +16,41 @@ DUPLICATE_FOLLOWUP_REASON_TEMPLATE = (
17
16
  " ({open_url}). Add this finding to the open follow-up pull request #{open_number}."
18
17
  " One combined follow-up pull request per parent pull request."
19
18
  )
19
+ UNANSWERED_FOLLOWUP_REASON_TEMPLATE = (
20
+ "The gate could not read the open pull requests of {owner}/{repo}: the read timed out"
21
+ " or GitHub answered with a server error. So it cannot tell"
22
+ " whether parent #{parent_number} already has an open follow-up pull request."
23
+ " Run the create again."
24
+ )
25
+ UNREAD_ORIGIN_FOLLOWUP_REASON_TEMPLATE = (
26
+ "The gate could not read the origin remote, so it cannot tell which repository to check"
27
+ " for an open follow-up pull request to parent #{parent_number}."
28
+ " Name the repository with --repo and run the create again."
29
+ )
30
+ GH_REPO_SET_FOLLOWUP_REASON_TEMPLATE = (
31
+ "The command sets GH_REPO, so the gate cannot tell which repository a create with no"
32
+ " --repo opens in, or which one to check for an open follow-up pull request to parent"
33
+ " #{parent_number}. Name the repository with --repo and run the create again."
34
+ )
20
35
  ALL_TITLE_OPTIONS = frozenset({"-t", "--title"})
36
+ GH_PROGRAM_NAME = "gh"
37
+ ALL_GH_ACTION_WORDS_BY_ALIAS = {"new": "create"}
38
+ GH_REPOSITORY_ENVIRONMENT_PREFIX = "GH_REPO="
39
+ GH_REPOSITORY_APPEND_PREFIX = "GH_REPO+="
40
+ APPEND_ASSIGNMENT_MARK = "+"
41
+ GH_REPOSITORY_ENVIRONMENT_NAME = "GH_REPO"
42
+ ALL_VARIABLE_SETTING_PROGRAM_NAMES = frozenset({"export", "declare", "typeset", "local", "readonly"})
43
+ ASSIGNMENT_SEPARATOR = "="
44
+ REPOSITORY_OPTION = "--repo"
45
+ OPTION_PREFIX = "-"
46
+ LONG_OPTION_PREFIX = "--"
47
+ STANDARD_INPUT_SCRIPT = "-"
48
+ SHORT_OPTION_LENGTH = 2
49
+ OPTION_AND_VALUE_WIDTH = 2
50
+ WINDOWS_EXECUTABLE_SUFFIX = ".exe"
51
+ PYTHON_PROGRAM_NAME_PATTERN = r"python(?:\d+(?:\.\d+)*)?w?|pyw?"
52
+ ALL_PYTHON_OPTIONS_WITH_VALUE = frozenset({"-X", "-W", "--check-hash-based-pycs"})
53
+ ALL_PYTHON_NON_SCRIPT_OPTIONS = frozenset({"-c", "-m"})
21
54
  WORKFLOW_DISPATCH_TOOL_SUFFIX = "__actions_run_trigger"
22
55
  RUN_WORKFLOW_METHOD = "run_workflow"
23
56
  ALL_PULL_REQUEST_DISPATCH_INPUT_KEYS = ("head", "title")
@@ -0,0 +1,52 @@
1
+ """Word the decision a gate gives when one of its checks raises."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from hooks_constants.gate_fault_constants import (
6
+ GATE_FAULT_REASON_TEMPLATE,
7
+ GATE_FAULT_SYSTEM_MESSAGE_TEMPLATE,
8
+ GATE_FAULT_TEXT_CHARACTER_LIMIT,
9
+ )
10
+
11
+
12
+ def gate_fault_reason(gate_name: str, error: BaseException) -> str:
13
+ """Return the deny reason for a call whose check raised.
14
+
15
+ ::
16
+
17
+ "merge review", KeyError("head") -> "The merge review gate hit a fault ... KeyError: 'head'. ..."
18
+
19
+ Args:
20
+ gate_name: The gate's name as the reader knows it, without the word gate.
21
+ error: The error the check raised.
22
+
23
+ Returns:
24
+ The permissionDecisionReason text for the gate's deny.
25
+ """
26
+ return GATE_FAULT_REASON_TEMPLATE.format(
27
+ gate_name=gate_name,
28
+ error_type=type(error).__name__,
29
+ error_text=str(error)[:GATE_FAULT_TEXT_CHARACTER_LIMIT],
30
+ )
31
+
32
+
33
+ def gate_fault_system_message(gate_script_name: str, error: BaseException) -> str:
34
+ """Return the warning the user sees when a gate's check raised and the gate let the call pass.
35
+
36
+ ::
37
+
38
+ "verify_before_commit_gate.py", KeyError("head")
39
+ -> "verify_before_commit_gate.py hit a fault and did not check this call: KeyError: 'head'. ..."
40
+
41
+ Args:
42
+ gate_script_name: The file name of the gate script that raised.
43
+ error: The error the check raised.
44
+
45
+ Returns:
46
+ The warning text for the hook output's top-level systemMessage field.
47
+ """
48
+ return GATE_FAULT_SYSTEM_MESSAGE_TEMPLATE.format(
49
+ gate_script_name=gate_script_name,
50
+ error_type=type(error).__name__,
51
+ error_text=str(error)[:GATE_FAULT_TEXT_CHARACTER_LIMIT],
52
+ )
@@ -0,0 +1,13 @@
1
+ """Constants for the decision a gate gives when one of its checks raises."""
2
+
3
+ GATE_FAULT_TEXT_CHARACTER_LIMIT = 200
4
+ GATE_FAULT_REASON_TEMPLATE = (
5
+ "The {gate_name} gate hit a fault while it checked this call: {error_type}: {error_text}."
6
+ " The call is refused because the check did not finish."
7
+ " Run the call again, and report the fault when it repeats."
8
+ )
9
+ GATE_FAULT_SYSTEM_MESSAGE_TEMPLATE = (
10
+ "{gate_script_name} hit a fault and did not check this call: {error_type}: {error_text}."
11
+ " The call goes on to the normal permission flow without this gate's check."
12
+ )
13
+ PROOF_EDIT_GATE_NAME = "pull request proof edit"
@@ -2,9 +2,17 @@
2
2
 
3
3
  PROOF_AND_LOOK_READS_SECONDS = 12
4
4
  FOLLOWUP_READS_SECONDS = 8
5
+ EVAL_WRITE_SCAN_SECONDS = 5
5
6
  KILL_GRACE_SECONDS = 1
7
+ WINDOWS_TREE_KILL_SECONDS = 0.5
8
+ ALL_WINDOWS_TREE_KILL_WORDS = ("taskkill", "/T", "/F", "/PID")
9
+ KERNEL32_LIBRARY_NAME = "kernel32"
10
+ PROCESS_HANDLE_ATTRIBUTE = "_handle"
11
+ STOPPED_JOB_EXIT_CODE = 1
12
+ TERMINATE_JOB_CALL = "TerminateJobObject"
13
+ CLOSE_HANDLE_CALL = "CloseHandle"
6
14
  MOST_CUT_READS_PER_RUN = 2
7
- STARTUP_AND_SCAN_MARGIN_SECONDS = 5
15
+ STARTUP_AND_OUTPUT_MARGIN_SECONDS = 5
8
16
  READS_RAN_OUT_SENTENCE = (
9
17
  " The gate's git and GitHub reads ran out of time on this run, so a second run may pass."
10
18
  )
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import re
6
6
 
7
7
  HOOK_EVENT_NAME = "PreToolUse"
8
+ GATE_NAME = "merge review"
8
9
  DENY_DECISION = "deny"
9
10
  PERMISSION_DECISION_REASON_KEY = "permissionDecisionReason"
10
11
 
@@ -20,10 +21,99 @@ EXPECTED_HEAD_FIELD = "expectedHeadSha"
20
21
  HEAD_BRANCH_FIELD = "head"
21
22
  CWD_FIELD = "cwd"
22
23
 
24
+ ALL_HEAD_OPTIONS = frozenset({"-H", "--head"})
25
+ ALL_REPOSITORY_OPTIONS = frozenset({"-R", "--repo"})
26
+ LONG_REPOSITORY_OPTION = "--repo"
27
+ REPOSITORY_SHORT_LETTER = "R"
28
+ HEAD_SHORT_LETTER = "H"
29
+ SHORT_OPTION_PREFIX = "-"
30
+ OPTION_AND_VALUE_WIDTH = 2
31
+ GH_PROGRAM_NAME = "gh"
32
+ ALL_VALUELESS_LONG_CREATE_OPTIONS = frozenset(
33
+ {
34
+ "--draft",
35
+ "--dry-run",
36
+ "--editor",
37
+ "--fill",
38
+ "--fill-first",
39
+ "--fill-verbose",
40
+ "--help",
41
+ "--no-maintainer-edit",
42
+ "--web",
43
+ }
44
+ )
45
+ ALL_VALUELESS_SHORT_CREATE_LETTERS = frozenset({"d", "e", "f", "h", "w"})
46
+ ALL_CHANGE_FOLDER_PROGRAMS = frozenset({"cd", "chdir", "set-location", "sl"})
47
+ ALL_HOME_DEFAULT_PROGRAMS = frozenset({"cd", "chdir"})
48
+ ALL_PUSH_FOLDER_PROGRAMS = frozenset({"pushd", "push-location"})
49
+ ALL_POP_FOLDER_PROGRAMS = frozenset({"popd", "pop-location"})
50
+ ALL_FOLDER_CHANGE_WORDS = (
51
+ ALL_CHANGE_FOLDER_PROGRAMS | ALL_PUSH_FOLDER_PROGRAMS | ALL_POP_FOLDER_PROGRAMS
52
+ )
53
+ ALL_PATH_PARAMETER_NAMES = frozenset({"-path", "-literalpath"})
54
+ ALL_UNFOLLOWED_FOLDER_CHARACTERS = frozenset("$`*?[{%")
55
+ PREVIOUS_FOLDER_ARGUMENT = "-"
56
+ HOME_FOLDER = "~"
57
+ OPTION_PREFIX = "-"
58
+ SUBSHELL_OPEN_OPERATOR = "("
59
+ SUBSHELL_CLOSE_TOKEN = ")"
60
+ ALL_PIPE_OPERATORS = frozenset({"|", "|&"})
61
+ ALL_BACKGROUND_OPERATORS = frozenset({"&"})
62
+ BRACE_OPEN_OPERATOR = "{"
63
+ BRACE_CLOSE_TOKEN = "}"
64
+ ALL_COMPOUND_OPEN_WORDS = frozenset({"if", "while", "until", "for", "case", "select"})
65
+ ALL_COMPOUND_CLOSE_WORDS = frozenset({"fi", "done", "esac"})
66
+ ALL_COMPOUND_BODY_WORDS = frozenset({"then", "elif", "else", "do"})
67
+ ALL_COMMAND_PREFIX_WORDS = frozenset({"builtin", "command"})
68
+ SEGMENT_TOKEN_JOIN = " "
69
+ IS_POSIX_TOKENIZATION = True
70
+ ALL_UNBALANCED_TOKENIZATION_MODES = (True, False)
71
+ ANSI_C_QUOTE_OPENER = "$'"
72
+ GROUP_OPEN_CHARACTER = "("
73
+ GROUP_CLOSE_CHARACTER = ")"
74
+ COMMENT_START_CHARACTER = "#"
75
+ HEREDOC_START_CHARACTER = "<"
76
+ CARRIAGE_RETURN_LINE_BREAK = "\r\n"
77
+ CARRIAGE_RETURN = "\r"
78
+ LINE_FEED = "\n"
79
+ END_OF_OPTIONS_PREFIX = "-- "
80
+ NESTED_LINE_BREAK_JOIN = ";"
81
+ ALL_CLOSING_CHARACTERS = SUBSHELL_CLOSE_TOKEN + NESTED_LINE_BREAK_JOIN
82
+ SUBSTITUTION_KEY_IGNORED_PATTERN = re.compile(r"[\s\\\"']")
83
+ SINGLE_QUOTE_INSIDE_SINGLE_QUOTES = "'\\''"
84
+ ALL_ANSI_C_ESCAPES = {
85
+ "n": "\n",
86
+ "t": "\t",
87
+ "r": "\r",
88
+ "a": "\a",
89
+ "b": "\b",
90
+ "f": "\f",
91
+ "v": "\v",
92
+ "e": "\x1b",
93
+ "E": "\x1b",
94
+ "\\": "\\",
95
+ "'": "'",
96
+ '"': '"',
97
+ "?": "?",
98
+ }
99
+ DOUBLE_QUOTED_ESCAPE_PATTERN = re.compile(r'[\\"]')
100
+ DOUBLE_QUOTED_ESCAPE_REPLACEMENT = r"\\\g<0>"
101
+ DOUBLE_QUOTED_SPECIAL_PATTERN = re.compile(r'[\\"]|\$\(')
102
+ ESCAPED_PAIR_LENGTH = 2
103
+ ESCAPED_SUBSTITUTION_OPENER = "\\$("
104
+ ESCAPED_SUBSTITUTION_WORD = "\\$\\("
105
+ SHORT_HEAD_OPTION = "-H"
106
+ LONG_HEAD_OPTION = "--head"
107
+ LONG_OPTION_PREFIX = "--"
108
+ OPTION_VALUE_SEPARATOR = "="
23
109
  GH_PR_CREATE_PATTERN = re.compile(r"(?:^|[\s;&|(])gh(?:\.exe)?\s+pr\s+create\b(?P<rest>[^;&|]*)")
24
110
  PULL_REQUEST_SCRIPT_CREATE_PATTERN = re.compile(
25
111
  r"pull_request\.py[\"']?\s+create\b(?P<rest>[^;&|]*)"
26
112
  )
113
+ LOOSE_GH_PROGRAM_PATTERN = re.compile(r"(?<![\w.-])gh(?:\.exe)?(?![\w.-])")
114
+ LOOSE_OPEN_WORD_PATTERN = re.compile(r"(?<![\w-])(?:create|new)(?![\w-])")
115
+ LOOSE_OPEN_OR_MERGE_WORD_PATTERN = re.compile(r"(?<![\w-])(?:create|new|merge)(?![\w-])")
116
+ LOOSE_PULL_REQUEST_SCRIPT_PATTERN = re.compile(r"pull_request\.py")
27
117
  HEAD_OPTION_PATTERN = re.compile(r"(?<!\S)(?:-H|--head)(?:=|\s+)[\"']?(?P<head>[^\s\"']+)")
28
118
  CHANGE_FOLDER_PATTERN = re.compile(
29
119
  r"(?:^|[;&|(]\s*)(?:cd|pushd|Set-Location|sl)\s+(?:-Path\s+|-LiteralPath\s+)?"
@@ -43,6 +133,7 @@ REMOTE_BRANCH_REFERENCE_TEMPLATE = "refs/heads/{branch}"
43
133
  LS_REMOTE_FIELD_SEPARATOR = "\t"
44
134
  ALL_NON_INTERACTIVE_GIT_SETTINGS = {"GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"}
45
135
  ALL_ORIGIN_URL_ARGUMENTS = ("remote", "get-url", "origin")
136
+ ORIGIN_URL_QUESTION = "merge review origin url"
46
137
  OPEN_HEAD_PATTERN = re.compile(r"[0-9a-fA-F]{7,40}")
47
138
  OPEN_RECEIPT_HEAD_PATTERN = re.compile(r"[0-9a-fA-F]{40}")
48
139
  REPOSITORY_SLUG_PATTERN = re.compile(r"[\w.-]+/[\w.-]+")
@@ -69,7 +160,9 @@ RULING_SEPARATOR = ","
69
160
  RULING_LOOKUP_TIMEOUT_SECONDS = 10
70
161
  REPO_OPTION_PATTERN = re.compile(r"(?:-R|--repo)[\s=](?P<owner>[\w.-]+)/(?P<repo>[\w.-]+)")
71
162
  MATCH_HEAD_PATTERN = re.compile(r"--match-head-commit[\s=](?P<sha>[0-9a-fA-F]{7,40})")
72
- API_SHA_FIELD_PATTERN = re.compile(r"(?:-f|-F|--field|--raw-field)[\s=]sha=(?P<sha>[0-9a-fA-F]{7,40})")
163
+ API_SHA_FIELD_PATTERN = re.compile(
164
+ r"(?:-f|-F|--field|--raw-field)[\s=]sha=(?P<sha>[0-9a-fA-F]{7,40})"
165
+ )
73
166
  ALL_OPTIONS_WITH_VALUE = (
74
167
  "-R",
75
168
  "--repo",
@@ -158,6 +158,7 @@ __all__ = [
158
158
  "TOOL_SUBCOMMAND_NAME",
159
159
  "WRAPPED_COMMAND_TOKEN_JOIN",
160
160
  "DISABLED_LEXER_COMMENTERS",
161
+ "LINEAR_TIME_LEXER_MINIMUM_LENGTH",
161
162
  "LINE_CONTINUATION_PATTERN",
162
163
  "LINE_CONTINUATION_JOIN",
163
164
  "COMMAND_LINE_SPLIT_PATTERN",
@@ -413,6 +414,7 @@ RUN_SUBCOMMAND_NAME = "run"
413
414
  TOOL_SUBCOMMAND_NAME = "tool"
414
415
  WRAPPED_COMMAND_TOKEN_JOIN = " "
415
416
  DISABLED_LEXER_COMMENTERS = ""
417
+ LINEAR_TIME_LEXER_MINIMUM_LENGTH = 4096
416
418
 
417
419
  LINE_CONTINUATION_PATTERN = re.compile(r"\\(?:\r\n|[\r\n])")
418
420
  LINE_CONTINUATION_JOIN = ""
@@ -8,6 +8,11 @@ DENY_DECISION = "deny"
8
8
  DENY_REASON = (
9
9
  "Invoke the pr-lifecycle skill with the Skill tool, then run the same command again."
10
10
  )
11
+ SCAN_RAN_OUT_SENTENCE = (
12
+ " The gate's transcript scan ran out of time on this run, and loading the skill again,"
13
+ " or calling build-eval again, puts that call where the scan finds it first."
14
+ )
15
+ GATE_NAME = "pull request lifecycle"
11
16
  SKILL_NAME = "pr-lifecycle"
12
17
  ALL_SLASH_COMMAND_MARKERS = ("<command-name>/pr-lifecycle</command-name>",)
13
18
  SHELL_TOOL_NAMES = frozenset({"Bash", "PowerShell"})
@@ -83,7 +88,7 @@ ALL_GH_PULL_REQUEST_SUBCOMMANDS = ALL_GH_PULL_REQUEST_READ_SUBCOMMANDS | frozens
83
88
  }
84
89
  )
85
90
  ALL_PREFIX_OPTIONS_WITH_VALUE = frozenset({"-u", "--unset", "-C", "--chdir", "-g", "--group", "--user"})
86
- ENVIRONMENT_ASSIGNMENT_PATTERN = r"^[A-Za-z_][A-Za-z0-9_]*="
91
+ ENVIRONMENT_ASSIGNMENT_PATTERN = r"^[A-Za-z_][A-Za-z0-9_]*\+?="
87
92
  ALL_SHELL_WRAPPER_EXECUTABLES = frozenset({"bash", "sh", "zsh", "dash", "eval", "pwsh", "pwsh.exe", "powershell", "powershell.exe"})
88
93
  ALL_PYTHON_EXECUTABLES = frozenset({"python", "python3", "python.exe", "python3.exe", "py", "py.exe"})
89
94
  PULL_REQUEST_SCRIPT_NAME = "pull_request.py"
@@ -4,8 +4,12 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import sys
7
+ import traceback
7
8
  from collections.abc import Callable
9
+ from pathlib import Path
8
10
 
11
+ from hooks_constants.context_budget_constants import SYSTEM_MESSAGE_KEY
12
+ from hooks_constants.gate_fault import gate_fault_system_message
9
13
  from hooks_constants.setup_project_paths_constants import (
10
14
  DECODE_ERRORS_POLICY,
11
15
  UTF8_BYTE_ORDER_MARK,
@@ -54,6 +58,17 @@ def print_decision_from_stdin(
54
58
  ) -> int:
55
59
  """Read one payload, print the decision the gate returns, and return zero.
56
60
 
61
+ ::
62
+
63
+ decision_for returns a deny -> that deny on one stdout line
64
+ decision_for returns None -> nothing on stdout
65
+ decision_for raises -> {"systemMessage": "<gate>.py hit a fault ..."} on stdout,
66
+ the traceback on stderr
67
+
68
+ A check that raises neither denies nor allows the call. The user sees a
69
+ warning that names the gate script and the error, and the call goes on to
70
+ the normal permission flow.
71
+
57
72
  Args:
58
73
  decision_for: The gate's function from a payload to its hook output, or None.
59
74
 
@@ -61,8 +76,13 @@ def print_decision_from_stdin(
61
76
  Zero, so the hook never fails the tool call on its own.
62
77
  """
63
78
  payload = read_hook_input_dictionary_from_stdin()
64
- if payload is not None:
79
+ if payload is None:
80
+ return 0
81
+ try:
65
82
  decision = decision_for(payload)
66
- if decision is not None:
67
- sys.stdout.write(json.dumps(decision) + "\n")
83
+ except Exception as error:
84
+ traceback.print_exc(file=sys.stderr)
85
+ decision = {SYSTEM_MESSAGE_KEY: gate_fault_system_message(Path(sys.argv[0]).name, error)}
86
+ if decision is not None:
87
+ sys.stdout.write(json.dumps(decision) + "\n")
68
88
  return 0