claude-dev-env 8.119.1 → 8.119.2

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 (29) hide show
  1. package/hooks/blocking/followup_pr_dedupe.py +71 -13
  2. package/hooks/blocking/merge_review_gate.py +4 -0
  3. package/hooks/blocking/merge_review_gate_parts/create_folders.py +6 -2
  4. package/hooks/blocking/merge_review_gate_parts/open_request.py +40 -15
  5. package/hooks/blocking/resolve_thread_reply_gate.py +116 -1
  6. package/hooks/blocking/test_cloud_graphql_gate.py +4 -0
  7. package/hooks/blocking/test_followup_pr_dedupe.py +99 -0
  8. package/hooks/blocking/test_gh_global_account_switch_gate.py +4 -0
  9. package/hooks/blocking/test_headless_claude_broker_gate.py +4 -0
  10. package/hooks/blocking/test_merge_review_gate.py +133 -0
  11. package/hooks/blocking/test_python_windows_invocation_gate.py +4 -0
  12. package/hooks/blocking/test_resolve_thread_reply_gate.py +430 -0
  13. package/hooks/blocking/tests/test_create_folders.py +7 -0
  14. package/hooks/blocking/tests/test_open_request.py +21 -0
  15. package/hooks/features/conduct-gates.md +3 -3
  16. package/hooks/hooks_constants/followup_pr_dedupe_constants.py +5 -0
  17. package/hooks/hooks_constants/merge_review_gate_constants.py +5 -0
  18. package/hooks/hooks_constants/pytest_invocation.py +24 -9
  19. package/hooks/hooks_constants/resolve_thread_reply_gate_constants.py +21 -1
  20. package/hooks/hooks_constants/test_pytest_invocation.py +25 -0
  21. package/hooks/hooks_constants/test_shell_command_mutation.py +11 -0
  22. package/hooks/hooks_constants/transcript_skill_scan_constants.py +22 -0
  23. package/hooks/session/test_npx_pele_guidance.py +4 -0
  24. package/hooks/test_transcript_skill_scan.py +72 -0
  25. package/hooks/transcript_skill_scan.py +138 -4
  26. package/hooks/validators/config/security_checks_constants.py +88 -0
  27. package/hooks/validators/security_checks.py +186 -1
  28. package/hooks/validators/test_security_checks.py +149 -0
  29. package/package.json +1 -1
@@ -18,10 +18,10 @@ This family stops a chat reply, edited message, or tool call when its payload br
18
18
  - `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.
19
19
  - `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.
20
20
  - `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.
21
- - `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
+ - `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 shell command that is one plain `review_reply_post.py request` call is a reply on the comment its `--comment-id` names and on the thread its `--thread-id` names. The launcher is absent, or is `python`, `python3`, `python3.<n>` or `py`, with or without `.exe`, bare or by an absolute path that starts with `/` or with a drive letter and `:/`. The script's parser accepts any prefix of an option name, so each word after `request` must be `--pull`, `--comment-id`, `--thread-id`, `--body-file` or `--wait-seconds` with a value that starts with no `-`, or the bare `--supersede`, each given once. A command that holds `;`, `&`, `|`, a redirect, a subshell, a substitution, a variable, `#`, a brace, a glob, `~`, `!`, a backslash or a line break is no reply. So a `cd dir &&` prefix, an environment prefix, a launcher option such as `python3 -u` or `py -3`, a launcher by a relative path such as `.venv/bin/python`, `uv run`, a line continuation, a backslash path, a pipe to `tail`, and a quoted value that holds `(`, `[` or `~` all count for nothing; run the plain form. A file of the same name, or a launcher of the same name at an absolute path, that exits 0 without posting still counts. 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. A background task notice is no user prompt, so a reply before it still counts. A call runs in the background when its `run_in_background` input is truthy, or when it is a `Bash` or `PowerShell` call whose result holds a line that starts `Command running in background with ID:`, `Command was manually backgrounded by user with ID:` or `Command did not complete within`. Those words in the result of any other tool, such as a reply tool that returns the comment body, change nothing. Such a reply counts only once a notice names its tool use id and a completed status before its summary, and ends its summary with `completed (exit code 0)`. The notice is read from a user entry or from a `queued_command` attachment, and a text that holds two notices vouches for no call. Any other `queued_command` attachment, such as a prompt the user sent mid-turn or a message another agent queued, ends the turn as a user prompt does, so a reply before it does not count and the agent replies again before it resolves. With no readable transcript, the resolve passes.
22
22
  - `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.
23
23
  - `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.
24
- - `blocking/merge_review_gate.py` denies an agent's merge until a review pass on the merged head reported zero findings, or ruled out every finding and linked the posted rulings. It reads the receipt `scripts/merge_review_receipt.py` writes, requires the merge, auto-merge or merge-queue entry to be pinned to that head, and skips repositories listed in `CLAUDE_MERGE_REVIEW_EXEMPT_REPOSITORIES`. A `gh pr merge` call whose every merge segment carries `--disable-auto` only turns auto-merge off, so it passes. A segment that also carries `--auto`, gives `--auto` or `--disable-auto` an `=` value, joins short flags such as `-sb`, or holds a bare `--` keeps every check. Its deny reason names the review command `CLAUDE_MERGE_REVIEW_COMMAND` sets. The reason tells the agent to run that command for the first three passes and `/code-review low --fix <number>` for each later pass; the gate itself counts no passes. It also denies a pull request open, through a shell create or a `create_pull_request` tool, until a pass recorded as `merge_review_receipt.py <owner/name> open <head> 0` covers the head the pull request opens with. A shell create is any spelling the shared listing in `blocking/followup_pr_dedupe.py` reads: `gh pr create`, `gh pr new`, `gh` with a root `-R` or `--repo` before `pr`, a `GH_REPO=` prefix, and `pull_request.py create` run by any `python`, `python3.x`, `py` or `uv run` launcher, with interpreter options or a path to the script. A command that chains several creates is checked create by create, in command order, and the deny names the first head with no clean pass. Each create reads its repository as gh does: among every `-R`, `--repo`, `--repo=`, `-R=` or clustered `-dR` flag before or after `pr`, the last one decides, and a flag word that is the value of another option, such as `--title --repo=x/y`, is not a flag. `blocking/merge_review_gate_parts/create_options.py` reads each value as gh does: an option that takes a value takes the next word, so `--title -Hx` and `--body -H --title x` name no head, and in a short cluster such as `-bHx` the first letter that takes a value takes the rest of the cluster. With no flag it reads the last `GH_REPO=` prefix, then the origin remote. 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
+ - `blocking/merge_review_gate.py` denies an agent's merge until a review pass on the merged head reported zero findings, or ruled out every finding and linked the posted rulings. It reads the receipt `scripts/merge_review_receipt.py` writes, requires the merge, auto-merge or merge-queue entry to be pinned to that head, and skips repositories listed in `CLAUDE_MERGE_REVIEW_EXEMPT_REPOSITORIES`. A `gh pr merge` call whose every merge segment carries `--disable-auto` only turns auto-merge off, so it passes. A segment that also carries `--auto`, gives `--auto` or `--disable-auto` an `=` value, joins short flags such as `-sb`, or holds a bare `--` keeps every check. Its deny reason names the review command `CLAUDE_MERGE_REVIEW_COMMAND` sets. The reason tells the agent to run that command for the first three passes and `/code-review low --fix <number>` for each later pass; the gate itself counts no passes. It also denies a pull request open, through a shell create or a `create_pull_request` tool, until a pass recorded as `merge_review_receipt.py <owner/name> open <head> 0` covers the head the pull request opens with. A shell create is any spelling the shared listing in `blocking/followup_pr_dedupe.py` reads: `gh pr create`, `gh pr new`, `gh` with a root `-R` or `--repo` before `pr`, a `GH_REPO=` prefix, and `pull_request.py create` run by any `python`, `python3.x`, `py` or `uv run` launcher, with interpreter options or a path to the script. A command that chains several creates is checked create by create, in command order, and the deny names the first head with no clean pass. Each create reads its repository as gh does: among every `-R`, `--repo`, `--repo=`, `-R=` or clustered `-dR` flag before or after `pr`, the last one decides, and a flag word that is the value of another option, such as `--title --repo=x/y`, is not a flag. `blocking/merge_review_gate_parts/create_options.py` reads each value as gh does: an option that takes a value takes the next word, so `--title -Hx` and `--body -H --title x` name no head, and in a short cluster such as `-bHx` the first letter that takes a value takes the rest of the cluster. With no flag it reads the last `GH_REPO=` prefix, then the origin remote. A wrapper such as `env -u GH_REPO`, `env -i` or `sudo` can drop the prefix before gh runs, as in `GH_REPO=o/r env -u GH_REPO gh pr create`, where gh opens in the origin repository. So every create the walk reaches whose repository comes only from a `GH_REPO=` prefix needs a clean pass for the prefix repository and for origin, also when the prefix value names no repository, and its deny for origin says to name the repository with `--repo owner/name` on the create. The walk steps over `env`, `sudo` and `timeout` with their options, and over the launchers `nohup`, `nice`, `stdbuf`, `setsid` and `time` when each launcher option holds its value in the same word or takes a number, as in `stdbuf -o0` or `nice -n 5`. It also reads a create behind `command` or `exec`, as in `command env -u GH_REPO` or `exec nohup env -u GH_REPO`. A create after the first one is not read behind a program the walk does not step over, such as `ionice`, `flock` or `doas`, or behind a launcher option with a separate value that is not a number, such as `stdbuf -o L` or `time -o out.txt`. A create that passes `--repo owner/name` needs a pass for that repository only. Two creates with the same options stay two checks when one has a prefix and the other does not. The first create in a command is also read the way the gate read it before it walked every create: its repository comes from a `--repo` flag or the origin remote, never from a prefix. A `GH_REPO+=` append, in a create's own prefix or anywhere else in the command, counts as a set whose value the gate cannot read. When the command sets `GH_REPO` anywhere outside a create's own prefix, through an assignment before another program, such as `GH_REPO=o/r bash -c ...`, or through an `export`, `declare`, `typeset`, `local` or `readonly` word that names `GH_REPO`, each create that names no repository flag and no `GH_REPO=` prefix of its own is denied as unread, and the reason says to pass `--repo owner/name`. The gate does not follow where that value reaches. `blocking/followup_pr_dedupe.py` reads the same condition through the same `sets_gh_repository` helper and refuses such a follow-up create, with a reason that says to name the repository with `--repo`. For a follow-up create whose repository comes only from a `GH_REPO=` prefix, it reads the open pull requests of the prefix repository and of the origin remote, since a wrapper can drop the prefix; a prefix value that names no repository, such as `GH_REPO=nonsense`, still gets the origin read, and a deny from the origin read opens with the sentence to name the repository with `--repo owner/name`; when the origin remote names no GitHub repository it reads the prefix repository only. A duplicate found in origin that way is refused with a reason that says to name the repository with `--repo owner/name` on the create, and a create that names its repository with its own `--repo` reads that repository only. Each head it names through `-H x`, `-Hx`, `-H=x`, `--head x`, `--head=x` or a cluster of short flags such as `-dHx`, `-dH x` or `-fH=x` gets its own check, also a head a later head flag overrides, as gh reads each one. A create that names no head reads `HEAD`. The first-create reading takes a head only from `-H x`, `--head x` or their `=` forms, so a create that gives its head as `-Hx` is also checked on `HEAD`; name the head with `--head` when the working folder is on another branch. `blocking/merge_review_gate_parts/create_folders.py` walks the command to give each create its folder, and `blocking/merge_review_gate_parts/folder_state.py` holds that folder, whether it is followed, and the `pushd` stack. The walk follows `cd`, `chdir`, `Set-Location`, `pushd` and `popd`, also after `builtin` or `command`; the end of a subshell, back to the folder in effect when that subshell opened, also when nested subshells close together on one line or across line breaks; and `eval`, which changes the folder of its own shell. A create inside `bash -c`, `sh -c` or a command substitution runs in the folder before it, also when a line break inside the script comes before it. A `cd` in a background job stays in that job. The walk does not model a folder change in a pipeline member, a brace group, `if`, `case`, `for`, `while`, `until`, `select` or a function body, a folder change after a redirect, or a folder word anywhere but the program place. Each later create in that scope is denied as unreadable. So is each create after a folder the walk cannot name, such as `cd "$VAR"`, `cd -` or a glob, and each create after a folder change the walk cannot follow, such as `popd` with nothing pushed, in any wrapper. A create in a folder that does not exist gets no git answer and is denied as unreadable. Text nested past 16 levels of `bash -c`, `eval` or substitution that names `gh` and a `create` or `new` word, or names `pull_request.py`, gives one create whose folder is not followed, so it is denied as unread. `blocking/merge_review_gate_parts/quoted_lines.py` cuts the text into lines and words as bash reads its quotes: `\"` inside a double-quoted value does not end the value, an ANSI-C `$'...'` value is one word, and a line break ends a command only outside quotes, subshells and substitutions. So the walk reads no command in a heredoc body or in a quoted option value, such as `--body "a; gh pr create --head x"`, with or without a line break inside it. It does read the script that `bash -c`, `sh -c`, `pwsh -Command`, `eval` or `Invoke-Expression` gets, line breaks included, and each `$(...)` or backtick substitution, also one inside a double-quoted value, such as `--body "$(gh pr create --head x)"`, since bash runs those. It reads no substitution bash does not run: one inside single quotes, such as `--body '$(gh pr create --head x)'` or `echo '$(gh pr create --head x)'`, or one whose `$(` or backtick a backslash escapes, such as `echo \$(gh pr create --head x)`. It reads `eval`'s words joined by spaces, as bash does, so `eval 'gh pr create --body "a b"'` is one create, and it reads the words after the last `)` inside a segment, such as the command of a `case` arm, as a create and as a wrapper. A command whose quotes do not close is read both ways the earlier walk read it, POSIX and raw words, as written and with its quoted line breaks joined. `blocking/merge_review_gate_parts/wrapped_creates.py` reads each wrapped inner text once more in POSIX words and gives a create the walk did not place as one whose folder is not followed; it skips the command itself, each closed text with its line breaks read as spaces, and each text unwrapped from one, so a heredoc body inside `--body "$(cat <<'B' ...)"` runs no command and `bash -c 'gh pr create\nls'` is one create. The gate also keeps the earlier first-create reading: the first `gh pr create` or `pull_request.py create` the raw text spells outside `--title`, `--body` and `--body-file` values, in the folder of the last `cd`, `pushd`, `Set-Location` or `sl` before it, with its first `--repo` and its first `-H` or `--head` given with a space or `=`. That reading is one more check unless a walk check equals it. So these are checked on the head that first create names: `echo gh pr create --head x | bash`; a create in a heredoc fed to `bash` or `.`; and the first create words after `;`, `&&`, `||` or `|` inside a quoted value, such as a `git commit -m` message. Beyond that first-create reading, the gate does not read: a create a shell gets through its input, a here-string, a heredoc, a process substitution such as `bash <(echo ...)` or a script file; a create in a command string that a program other than `bash`, `sh`, `pwsh`, `powershell`, `cmd /c`, `eval`, `Invoke-Expression`, `find -exec`, `xargs` or `Start-Process` runs, such as `zsh -c`, `su -c`, `ssh`, `watch`, `python -c` or a git alias; or a program name that a variable, alias or function holds. These forms are read in part. A `case` arm inside a double-quoted substitution, such as `--body "$(case x in x) gh pr create ;; esac)"`, is cut at the arm's `)`, so its create is not read. An arithmetic `<<` followed by a word, such as `$((1<<x))`, opens a heredoc for the walk, so the lines after it up to a line `x` are not read; the first-create reading still checks the first create in the raw text. A substitution in an unquoted heredoc body fed to a plain command such as `cat` is not walked; the first-create reading checks the first create there with the closing `)` kept in its head, so that head is unreadable and denied. A create in a heredoc fed to `.` or `bash` is checked only through the first-create reading: it reads `--repo` and a `--head` or `-H` given with a space or `=`, checks a `-Hx` or clustered head as `HEAD`, and does not read a create after the first. The words of a quoted option value are not commands, so a create in one is not read and needs no review. Once the gate knows the call opens or merges a pull request, a check that raises denies the call with the fault reason, which names the error type. A payload read that raises is denied the same way for a `create_pull_request`, `merge_pull_request` or `enable_pr_auto_merge` tool, and for a shell command whose text holds the word `gh` and a `create`, `new` or `merge` word anywhere, or names `pull_request.py`. Any other payload read fault goes to the shared helper. A call that opens and merges nothing gets no such deny. An open pass also counts when every finding is ruled out: `merge_review_receipt.py <owner/name> open <head> <count> --ruled-out <count> --rulings <path:line,...>`, with a different `path:line` for each finding, checked against the file at that head when the pass is recorded. A merge pinned to that same head passes on the open receipt only when the pass found zero findings.
25
25
  - `blocking/artifact_dark_mode_gate.py` denies an Artifact page publish when the page, inside the publish wrapper, keeps a light body or shows text under 4.5:1 contrast in dark mode. `blocking/artifact_dark_mode_render.cjs` renders the page in headless Chromium for it.
26
26
  - `blocking/send_user_file_worktree_root_gate.py` denies a `SendUserFile` call that names a file outside the session's working directory, the `cwd` in the hook payload. The desktop file pane opens a sent file only under that folder and shows "Couldn't find this file" for any other path. The reason lists each outside file and names `<cwd>\.scratch\` as the folder to copy it into.
27
27
  - `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.
@@ -76,7 +76,7 @@ Preconditions:
76
76
  - **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.
77
77
  - **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.
78
78
  - **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.
79
- - **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.
79
+ - **Clean review.** Input is a merge with no receipt, a receipt with findings, a merge pinned to a newer head, an unpinned merge, or auto-merge with no head. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_merge_review_gate.py -q`. The adjacent test observes a denial for each; a merge or auto-merge pinned to the clean head and a merge in an exempt repository pass. A `gh pr merge --disable-auto` call passes; a merge chained with it, or one that adds `--disable-auto=false` or `-sb --disable-auto`, is still checked. An open with no clean open receipt at its head is denied; an open reviewed clean at its head, and a merge pinned to that head, pass. An open pass whose every finding has its own `path:line` ruling lets the open through; a merge pinned to that head is denied, since only a zero-finding open pass carries to the merge. An open whose branch neither GitHub nor the working folder holds is denied as unreadable. Two chained creates whose second head has no clean open receipt are denied with the second head named. An open whose reads ran past the shared deadline, or whose git read hit its own timeout, is denied as unreadable, with the sentence that a second run may pass; a git read that fails fast gets no such sentence. Every create spelling is denied when its head has no clean pass. A create whose last repository flag names a repository with no clean pass is denied, however many repository flags come before it. A create that names an unreviewed second head with `-Hx`, a repeated `--head` or `--head=` is denied, and so is one whose short-flag cluster, such as `-dHx`, names an unreviewed head. A flag word that is another option's value, such as `--title --repo=x/y`, `--title -Hx` or `-bHx`, is read as that value. A create with no repository of its own in a command that sets `GH_REPO` elsewhere, through an assignment or `export`, is denied as unread with the `--repo owner/name` sentence, and one that names `--repo` or a `GH_REPO=` prefix is read. A first create behind a `GH_REPO=` prefix is denied when origin has no clean pass, also when the prefix repository is exempt or reviewed clean. A later create is denied the same way when the walk reaches it: behind `env`, `sudo` and `timeout` with their options, and behind chains of the launchers `nohup`, `nice`, `stdbuf`, `setsid` and `time` whose options hold their value in the same word or take a number, such as `nice -n 5 env -u GH_REPO stdbuf -o0`. A create after the first one, behind a program the walk does not step over, such as `ionice`, is not read. A create the walk reaches whose prefix value names no repository, such as `GH_REPO=nonsense`, is denied for origin with the `--repo owner/name` sentence. A first create the walk does not reach, such as one behind `stdbuf -o L`, is denied for origin through the first-create reading without that sentence, and a prefixed create after an unprefixed create on the same head is denied on the unprefixed create, also without it. A create that names an exempt repository with its own `--repo` passes. A create after a subshell or `popd` reads the starting folder, also after nested subshells close on one line or across line breaks, and `builtin cd` and `command cd` are followed. A create in a `case` arm, also one with a root `-R`, is checked on its head. A create inside a single-quoted or backslash-escaped substitution is not read, and one inside a double-quoted or bare substitution is checked. A create after `cd "$VAR"`, or after a `cd` in a piped brace group, `if`, `case`, a loop, a function body or after a redirect, is denied as unreadable, and so is a create nested past the unwrap depth. The first create the raw text spells is also checked with the earlier first-create reading, which a frozen table of commands pins, so a create fed to `bash` through a pipe or a heredoc is checked on its head. A later create on an unreviewed head is denied after an ANSI-C `$'...'` value, after a line break inside `bash -c`, `sh -c` or `eval`, and after a double-quoted value whose substitution holds a quote character. A later create inside a quoted value, such as `--body "say \"x\" ; gh pr create --head y"`, is not read. A here-string or piped create beyond the first, a create in a command string run by a program the walk does not unwrap, and a program name in a variable or alias are not read. An open or a merge whose check raises is denied with the fault reason, also when the text spells the create or merge in a form the strict pattern misses, and so is an MCP merge whose `pullNumber` overflows.
80
80
  - **Dark mode page.** Input is an Artifact publish of a page that themes `html` but leaves `body` to the publish wrapper. Run `python -m pytest packages/claude-dev-env/hooks/blocking/test_artifact_dark_mode_gate.py -q`. The adjacent test observes a denial that names the text and its contrast; a page that themes `body` passes. The render tests skip on a host with no Node Playwright and Chromium.
81
81
  - **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.
82
82
  - **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.
@@ -16,6 +16,11 @@ DUPLICATE_FOLLOWUP_REASON_TEMPLATE = (
16
16
  " ({open_url}). Add this finding to the open follow-up pull request #{open_number}."
17
17
  " One combined follow-up pull request per parent pull request."
18
18
  )
19
+ PREFIX_ORIGIN_FOLLOWUP_SENTENCE = (
20
+ "Name the repository with `--repo owner/name` on the create instead of a `GH_REPO=` prefix."
21
+ " A wrapper such as `env -u GH_REPO` can drop that prefix before gh runs, so the gate"
22
+ " also reads the origin repository, and there it found this: "
23
+ )
19
24
  UNANSWERED_FOLLOWUP_REASON_TEMPLATE = (
20
25
  "The gate could not read the open pull requests of {owner}/{repo}: the read timed out"
21
26
  " or GitHub answered with a server error. So it cannot tell"
@@ -263,6 +263,11 @@ NO_CLEAN_OPEN_REVIEW_REASON_TEMPLATE = (
263
263
  "finding, comma separated>`, each path:line a line this head holds. Then open the pull "
264
264
  "request. A merge pinned to {head} accepts an open pass only at zero findings."
265
265
  )
266
+ PREFIX_ORIGIN_CHECK_SENTENCE = (
267
+ " This create names its repository only with a `GH_REPO=` prefix, and a wrapper such as "
268
+ "`env -u GH_REPO` can drop that prefix before gh runs, so the gate also checks the origin "
269
+ "repository. Name the repository with `--repo owner/name` on the create instead."
270
+ )
266
271
  UNKNOWN_OPEN_TARGET_REASON = (
267
272
  "This pull request names no repository or head commit the review gate can read. Check that "
268
273
  "the head branch is on GitHub and this session can reach it, or run it from the branch "
@@ -49,6 +49,8 @@ from hooks_constants.shell_command_pipeline import (
49
49
  segments_with_following_operator,
50
50
  )
51
51
  from hooks_constants.shell_command_segments import (
52
+ ALL_LAUNCHER_WRAPPER_COMMANDS,
53
+ LAUNCHER_DURATION_PATTERN,
52
54
  LEADING_ASSIGNMENT_PATTERN,
53
55
  effective_leading_program,
54
56
  token_basename,
@@ -186,20 +188,33 @@ def _wrapper_basename(token: str) -> str:
186
188
  def _wrapper_program_index(all_segment_tokens: list[str]) -> int | None:
187
189
  """Return the index of the program a wrapper step reads.
188
190
 
189
- A wrapper with its own option grammar is read where it stands, so the
190
- ``-u HOME`` behind ``env`` stays an option. Any other leading program is
191
- found past assignments and plain launchers such as ``time`` and ``nohup``.
191
+ ::
192
+
193
+ nohup env -u HOME gh pr the index of env
194
+ nice -n 5 stdbuf -o0 gh pr the index of gh
195
+
196
+ Assignments and plain launchers such as ``time``, ``nohup`` and
197
+ ``nice -n 5`` are stepped past with their options. A wrapper with its
198
+ own option grammar is read where it stands, so the ``-u HOME`` behind
199
+ ``env`` stays an option.
192
200
  """
201
+ has_seen_launcher = False
193
202
  for each_index, each_token in enumerate(all_segment_tokens):
194
203
  if LEADING_ASSIGNMENT_PATTERN.match(each_token) is not None:
195
204
  continue
196
- if _wrapper_basename(each_token) in ALL_WRAPPER_OPTION_GRAMMARS_BY_NAME:
205
+ program_basename = _wrapper_basename(each_token)
206
+ if program_basename in ALL_WRAPPER_OPTION_GRAMMARS_BY_NAME:
197
207
  return each_index
198
- break
199
- leading_program = effective_leading_program(all_segment_tokens)
200
- if leading_program is None:
201
- return None
202
- return all_segment_tokens.index(leading_program)
208
+ if program_basename in ALL_LAUNCHER_WRAPPER_COMMANDS:
209
+ has_seen_launcher = True
210
+ continue
211
+ is_launcher_option = each_token.startswith(SHORT_OPTION_PREFIX) or (
212
+ LAUNCHER_DURATION_PATTERN.match(each_token) is not None
213
+ )
214
+ if has_seen_launcher and is_launcher_option:
215
+ continue
216
+ return each_index
217
+ return None
203
218
 
204
219
 
205
220
  def _all_tokens_after_one_wrapper(all_segment_tokens: list[str]) -> list[str] | None:
@@ -11,6 +11,24 @@ SHELL_COMMAND_KEY = "command"
11
11
  SHELL_REPLY_COMMAND_PATTERN = re.compile(
12
12
  r"\bgh\s+api\b.*(?:/comments/\d+/replies\b|addPullRequestReviewThreadReply)", re.DOTALL
13
13
  )
14
+ REPLY_SCRIPT_FILE_NAME = "review_reply_post.py"
15
+ REPLY_SCRIPT_REQUEST_SUBCOMMAND = "request"
16
+ REPLY_SCRIPT_LAUNCHER_NAME_PATTERN = re.compile(r"(?:python(?:3(?:\.\d+)?)?|py)(?:\.exe)?")
17
+ REPLY_SCRIPT_COMMENT_ID_OPTION = "--comment-id"
18
+ REPLY_SCRIPT_THREAD_ID_OPTION = "--thread-id"
19
+ ALL_REPLY_SCRIPT_VALUE_OPTIONS = (
20
+ "--pull",
21
+ REPLY_SCRIPT_COMMENT_ID_OPTION,
22
+ REPLY_SCRIPT_THREAD_ID_OPTION,
23
+ "--body-file",
24
+ "--wait-seconds",
25
+ )
26
+ ALL_REPLY_SCRIPT_FLAG_OPTIONS = ("--supersede",)
27
+ SHELL_OPTION_PREFIX = "-"
28
+ SHELL_UNREADABLE_CHARACTER_PATTERN = re.compile(r"[;&|<>()`$#{}*?\[\]~!\\\n\r]")
29
+ SHELL_OPTION_VALUE_SEPARATOR = "="
30
+ SHELL_PATH_SEPARATOR = "/"
31
+ ABSOLUTE_LAUNCHER_FOLDER_PATTERN = re.compile(r"(?:[A-Za-z]:)?/")
14
32
  SHELL_RESOLVE_COMMAND_PATTERN = re.compile(r"\bgh\s+api\s+graphql\b.*\bresolveReviewThread\b", re.DOTALL)
15
33
  SHELL_RESOLVE_COMMENT_ID_PATTERN = re.compile(r"/pulls/\d+/ccr/comments/(\d+)/resolve\b")
16
34
  ALL_THREAD_ID_INPUT_KEYS = ("threadID", "threadId")
@@ -23,7 +41,9 @@ TEXT_FIELD = "text"
23
41
  MISSING_REPLY_REASON = (
24
42
  "This review thread has no reply on it that posted since the last user prompt and the last"
25
43
  " resolve of the thread. Post the reply on this thread with add_reply_to_pull_request_comment,"
26
- " or with gh api graphql addPullRequestReviewThreadReply and the thread's PRRT_ id, confirm its"
44
+ " with gh api graphql addPullRequestReviewThreadReply and the thread's PRRT_ id, or with a"
45
+ " review_reply_post.py request run as one plain command (python3, the script, request, then only"
46
+ " full option names, each once) that exits 0, confirm its"
27
47
  " result came back without an error, then resolve the thread by its PRRT_ id or by the comment id the reply answered. A comment id"
28
48
  " ties to a thread only through a pull_request_read get_review_comments result in this session."
29
49
  )
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import pytest
6
6
 
7
7
  from hooks_constants.pytest_invocation import (
8
+ all_tokens_after_wrappers,
8
9
  segment_reports_a_pytest_exit_code,
9
10
  segment_runs_pytest,
10
11
  )
@@ -134,3 +135,27 @@ def test_should_not_false_classify_option_value_named_pytest() -> None:
134
135
  def test_should_not_false_classify_script_argument_named_pytest() -> None:
135
136
  all_tokens = _first_segment_tokens("python myscript.py -m pytest")
136
137
  assert segment_runs_pytest(all_tokens) is False
138
+
139
+
140
+ @pytest.mark.parametrize(
141
+ ("all_segment_tokens", "all_expected_tokens"),
142
+ [
143
+ (["nohup", "env", "-u", "GH_REPO", "gh", "pr"], ["gh", "pr"]),
144
+ (["GH_REPO=o/r", "nice", "env", "-u", "GH_REPO", "gh", "pr"], ["gh", "pr"]),
145
+ (
146
+ ["nice", "-n", "5", "env", "-u", "GH_REPO", "stdbuf", "-o0", "gh", "pr"],
147
+ ["stdbuf", "-o0", "gh", "pr"],
148
+ ),
149
+ (["stdbuf", "-o0", "env", "-u", "FOO", "gh", "pr"], ["gh", "pr"]),
150
+ (["time", "nohup", "env", "--unset", "FOO", "nice", "gh", "pr"], ["nice", "gh", "pr"]),
151
+ (["env", "nice", "env", "-u", "FOO", "gh", "pr"], ["gh", "pr"]),
152
+ (["nohup", "timeout", "-s", "KILL", "60", "gh", "pr"], ["gh", "pr"]),
153
+ (["setsid", "sudo", "-u", "ci", "gh", "pr"], ["gh", "pr"]),
154
+ (["nohup", "gh", "pr"], ["nohup", "gh", "pr"]),
155
+ (["gh", "pr"], ["gh", "pr"]),
156
+ ],
157
+ )
158
+ def test_all_tokens_after_wrappers_should_step_over_an_option_reading_wrapper_behind_launchers(
159
+ all_segment_tokens: list[str], all_expected_tokens: list[str]
160
+ ) -> None:
161
+ assert all_tokens_after_wrappers(all_segment_tokens) == all_expected_tokens
@@ -22,6 +22,17 @@ def test_should_read_a_write_as_mutating(command: str) -> None:
22
22
  assert is_mutating_shell_command(command) is True
23
23
 
24
24
 
25
+ @pytest.mark.parametrize(
26
+ "command",
27
+ [
28
+ "nohup env -u FOO git push origin main",
29
+ "time -p env -u HOME bash -c 'touch x'",
30
+ ],
31
+ )
32
+ def test_should_read_a_write_behind_a_launcher_and_env_unset_as_mutating(command: str) -> None:
33
+ assert is_mutating_shell_command(command) is True
34
+
35
+
25
36
  @pytest.mark.parametrize(
26
37
  "command",
27
38
  [
@@ -10,6 +10,28 @@ META_ENTRY_FIELD = "isMeta"
10
10
  TOOL_RESULT_BLOCK_TYPE = "tool_result"
11
11
  IS_ERROR_FIELD = "is_error"
12
12
  TOOL_USE_ID_FIELD = "tool_use_id"
13
+ ORIGIN_FIELD = "origin"
14
+ ORIGIN_KIND_FIELD = "kind"
15
+ TASK_NOTIFICATION_ORIGIN_KIND = "task-notification"
16
+ RUN_IN_BACKGROUND_INPUT_KEY = "run_in_background"
17
+ MOVED_TO_BACKGROUND_RESULT_PATTERN = (
18
+ r"(?m)^Command (?:running in background with ID: |was manually backgrounded by user with ID: "
19
+ r"|did not complete within [^\n]*\bmoved to the background\b)"
20
+ )
21
+ ALL_BACKGROUND_SHELL_TOOL_NAMES = frozenset({"Bash", "PowerShell"})
22
+ ATTACHMENT_ENTRY_TYPE = "attachment"
23
+ ATTACHMENT_FIELD = "attachment"
24
+ QUEUED_COMMAND_ATTACHMENT_TYPE = "queued_command"
25
+ QUEUED_COMMAND_PROMPT_FIELD = "prompt"
26
+ RESULT_TEXT_FIELD = "text"
27
+ RESULT_TEXT_SEPARATOR = "\n"
28
+ TASK_NOTIFICATION_OPENING_TAG = "<task-notification>"
29
+ TASK_NOTIFICATION_CLOSING_TAG = "</task-notification>"
30
+ TASK_NOTIFICATION_SUMMARY_OPENING_TAG = "<summary>"
31
+ TASK_NOTIFICATION_TOOL_USE_ID_PATTERN = r"<tool-use-id>\s*([^<\s]+)\s*</tool-use-id>"
32
+ TASK_NOTIFICATION_COMPLETED_STATUS_PATTERN = r"<status>\s*completed\s*</status>"
33
+ TASK_NOTIFICATION_ANY_STATUS_PATTERN = r"<status>"
34
+ TASK_NOTIFICATION_EXIT_ZERO_ENDING_PATTERN = r" completed \(exit code 0\)\s*</summary>\s*</task-notification>\s*\Z"
13
35
  NEWLINE_BYTE = b"\n"
14
36
  CARRIAGE_RETURN_BYTE = b"\r"
15
37
  ALL_LINE_BREAK_BYTES = (NEWLINE_BYTE, CARRIAGE_RETURN_BYTE)
@@ -102,6 +102,10 @@ def test_npx_pele_commands_match(command_text: str) -> None:
102
102
  assert npx_pele_guidance.is_npx_pele_command({"command": command_text})
103
103
 
104
104
 
105
+ def test_should_match_npx_pele_behind_a_launcher_and_env_unset() -> None:
106
+ assert npx_pele_guidance.is_npx_pele_command({"command": "nohup env -u FOO npx pele a.mmd"})
107
+
108
+
105
109
  @pytest.mark.parametrize(
106
110
  "command_text",
107
111
  [
@@ -232,6 +232,78 @@ def should_list_each_tool_call_since_the_last_prompt_with_its_outcome() -> None:
232
232
  ]
233
233
 
234
234
 
235
+ def should_count_a_background_call_only_after_its_notice_reports_exit_code_zero() -> None:
236
+ background_input: dict[str, object] = {"command": "sleep 1", "run_in_background": True}
237
+
238
+ def _call(tool_use_id: str) -> str:
239
+ tool_use = {"type": "tool_use", "id": tool_use_id, "name": "Bash", "input": background_input}
240
+ return json.dumps({"type": "assistant", "message": {"content": [tool_use]}})
241
+
242
+ def _started(tool_use_id: str) -> str:
243
+ tool_result = {"type": "tool_result", "tool_use_id": tool_use_id, "is_error": False, "content": "started"}
244
+ return json.dumps({"type": "user", "message": {"content": [tool_result]}})
245
+
246
+ def _notice(tool_use_id: str, status: str, exit_code: int) -> str:
247
+ text = (
248
+ f"<task-notification><tool-use-id>{tool_use_id}</tool-use-id><status>{status}</status>"
249
+ f"<summary>Background command {status} (exit code {exit_code})</summary></task-notification>"
250
+ )
251
+ return json.dumps({"type": "user", "origin": {"kind": "task-notification"}, "message": {"content": text}})
252
+
253
+ lines = [
254
+ json.dumps({"type": "user", "message": {"content": "First."}}),
255
+ _call("done"),
256
+ _started("done"),
257
+ _call("failed"),
258
+ _started("failed"),
259
+ _call("running"),
260
+ _started("running"),
261
+ _notice("done", "completed", 0),
262
+ _notice("failed", "failed", 3),
263
+ ]
264
+ assert tool_calls_since_last_prompt(lines) == [
265
+ TranscriptToolCall("Bash", background_input, True),
266
+ TranscriptToolCall("Bash", background_input, False),
267
+ TranscriptToolCall("Bash", background_input, False),
268
+ ]
269
+
270
+
271
+ def should_read_queued_command_attachments_and_calls_moved_to_the_background() -> None:
272
+ def _call(tool_use_id: str, tool_input: dict[str, object]) -> str:
273
+ tool_use = {"type": "tool_use", "id": tool_use_id, "name": "Bash", "input": tool_input}
274
+ return json.dumps({"type": "assistant", "message": {"content": [tool_use]}})
275
+
276
+ def _result(tool_use_id: str, text: str) -> str:
277
+ tool_result = {"type": "tool_result", "tool_use_id": tool_use_id, "is_error": False, "content": text}
278
+ return json.dumps({"type": "user", "message": {"content": [tool_result]}})
279
+
280
+ def _queued(text: str, origin_kind: str) -> str:
281
+ attachment = {"type": "queued_command", "prompt": text, "origin": {"kind": origin_kind}}
282
+ return json.dumps({"type": "attachment", "attachment": attachment})
283
+
284
+ def _notice(tool_use_id: str) -> str:
285
+ return (
286
+ f"<task-notification><tool-use-id>{tool_use_id}</tool-use-id><status>completed</status>"
287
+ '<summary>Background command "x" completed (exit code 0)</summary></task-notification>'
288
+ )
289
+
290
+ all_turn_lines = [
291
+ json.dumps({"type": "user", "message": {"content": "First."}}),
292
+ _call("flag-text", {"run_in_background": "true"}),
293
+ _result("flag-text", "Command running in background with ID: b1"),
294
+ _call("moved", {}),
295
+ _result("moved", "Command did not complete within its 120s timeout and was moved to the background."),
296
+ _call("waiting", {"run_in_background": 1}),
297
+ _result("waiting", "Command running in background with ID: b3"),
298
+ _call("plain", {}),
299
+ _result("plain", "done"),
300
+ _queued(_notice("flag-text"), "task-notification"),
301
+ _queued(_notice("moved"), "task-notification"),
302
+ ]
303
+ assert [each_call.succeeded for each_call in tool_calls_since_last_prompt(all_turn_lines)] == [True, True, False, True]
304
+ assert tool_calls_since_last_prompt([*all_turn_lines, _queued("Stop.", "human")]) == []
305
+
306
+
235
307
  NEWEST_FIRST_SKILL_NAMES = ("pr-lifecycle",)
236
308
  NEWEST_FIRST_MARKERS = ("<command-name>/pr-lifecycle</command-name>",)
237
309
  ALL_GENERATED_LINE_KINDS = (
@@ -17,14 +17,33 @@ from typing import BinaryIO, NamedTuple
17
17
  from hooks_constants.transcript_skill_scan_constants import (
18
18
  ALL_LINE_BREAK_BYTES,
19
19
  ASSISTANT_ENTRY_TYPE,
20
+ ALL_BACKGROUND_SHELL_TOOL_NAMES,
21
+ ATTACHMENT_ENTRY_TYPE,
22
+ ATTACHMENT_FIELD,
20
23
  CARRIAGE_RETURN_BYTE,
21
24
  COMMAND_ARGUMENTS_PATTERN,
22
25
  COMPACT_BOUNDARY_SUBTYPE,
23
26
  FORWARD_COPY_BYTE_CAP,
24
27
  IS_ERROR_FIELD,
25
28
  META_ENTRY_FIELD,
29
+ MOVED_TO_BACKGROUND_RESULT_PATTERN,
26
30
  NEWLINE_BYTE,
31
+ ORIGIN_FIELD,
32
+ ORIGIN_KIND_FIELD,
33
+ QUEUED_COMMAND_ATTACHMENT_TYPE,
34
+ QUEUED_COMMAND_PROMPT_FIELD,
35
+ RESULT_TEXT_FIELD,
36
+ RESULT_TEXT_SEPARATOR,
37
+ RUN_IN_BACKGROUND_INPUT_KEY,
27
38
  SKILL_TOOL_NAME,
39
+ TASK_NOTIFICATION_ORIGIN_KIND,
40
+ TASK_NOTIFICATION_ANY_STATUS_PATTERN,
41
+ TASK_NOTIFICATION_CLOSING_TAG,
42
+ TASK_NOTIFICATION_COMPLETED_STATUS_PATTERN,
43
+ TASK_NOTIFICATION_EXIT_ZERO_ENDING_PATTERN,
44
+ TASK_NOTIFICATION_OPENING_TAG,
45
+ TASK_NOTIFICATION_SUMMARY_OPENING_TAG,
46
+ TASK_NOTIFICATION_TOOL_USE_ID_PATTERN,
28
47
  TOOL_RESULT_BLOCK_TYPE,
29
48
  TRANSCRIPT_BLOCK_BYTES,
30
49
  TRANSCRIPT_LINE_BYTE_CAP,
@@ -523,6 +542,83 @@ def _succeeded_result_ids(all_entry_fields: dict[str, object]) -> set[object]:
523
542
  }
524
543
 
525
544
 
545
+ def _queued_command(all_entry_fields: dict[str, object]) -> dict[str, object] | None:
546
+ attachment = all_entry_fields.get(ATTACHMENT_FIELD)
547
+ if all_entry_fields.get("type") != ATTACHMENT_ENTRY_TYPE or not isinstance(attachment, dict):
548
+ return None
549
+ return attachment if attachment.get("type") == QUEUED_COMMAND_ATTACHMENT_TYPE else None
550
+
551
+
552
+ def _is_task_notification_origin(all_fields: dict[str, object]) -> bool:
553
+ origin = all_fields.get(ORIGIN_FIELD)
554
+ return isinstance(origin, dict) and origin.get(ORIGIN_KIND_FIELD) == TASK_NOTIFICATION_ORIGIN_KIND
555
+
556
+
557
+ def _task_notification_text(all_entry_fields: dict[str, object]) -> str | None:
558
+ queued_command = _queued_command(all_entry_fields)
559
+ if queued_command is not None:
560
+ if not _is_task_notification_origin(queued_command):
561
+ return None
562
+ queued_text = queued_command.get(QUEUED_COMMAND_PROMPT_FIELD)
563
+ return queued_text if isinstance(queued_text, str) else ""
564
+ if not _is_task_notification_origin(all_entry_fields):
565
+ return None
566
+ return _user_command_text(all_entry_fields) or ""
567
+
568
+
569
+ def _result_block_text(result_content: object) -> str:
570
+ if isinstance(result_content, str):
571
+ return result_content
572
+ all_parts = result_content if isinstance(result_content, list) else []
573
+ return RESULT_TEXT_SEPARATOR.join(
574
+ each_part[RESULT_TEXT_FIELD]
575
+ for each_part in all_parts
576
+ if isinstance(each_part, dict) and isinstance(each_part.get(RESULT_TEXT_FIELD), str)
577
+ )
578
+
579
+
580
+ def _moved_to_background_result_ids(all_entry_fields: dict[str, object]) -> set[object]:
581
+ return {
582
+ each_block.get(TOOL_USE_ID_FIELD)
583
+ for each_block in _content_blocks(all_entry_fields, USER_ENTRY_TYPE)
584
+ if each_block.get("type") == TOOL_RESULT_BLOCK_TYPE
585
+ and re.search(MOVED_TO_BACKGROUND_RESULT_PATTERN, _result_block_text(each_block.get("content"))) is not None
586
+ }
587
+
588
+
589
+ def _background_ids_finished_without_error(notification_text: str) -> set[object]:
590
+ """Return the tool use id of a notice that reports exit code 0, as a set of one, else an empty set.
591
+
592
+ ::
593
+
594
+ one notice, status completed, summary ends "(exit code 0)" -> {its id}
595
+ one notice, status failed, summary ends "(exit code 3)" -> {}
596
+ two notices in one text, either outcome -> {}
597
+ a failed notice whose summary quotes "(exit code 0)" -> {}
598
+ a failed notice whose summary quotes a whole passing notice -> {}
599
+
600
+ The harness writes the id and the status before the summary, and the exit
601
+ code as the last words of the summary. The summary also quotes the
602
+ command's description, which the agent wrote, so only the text before the
603
+ summary and the very end of the notice are read.
604
+ """
605
+ if (
606
+ notification_text.count(TASK_NOTIFICATION_OPENING_TAG) != 1
607
+ or notification_text.count(TASK_NOTIFICATION_CLOSING_TAG) != 1
608
+ ):
609
+ return set()
610
+ harness_header = notification_text.partition(TASK_NOTIFICATION_SUMMARY_OPENING_TAG)[0]
611
+ all_tool_use_ids = re.findall(TASK_NOTIFICATION_TOOL_USE_ID_PATTERN, harness_header)
612
+ if (
613
+ len(all_tool_use_ids) != 1
614
+ or len(re.findall(TASK_NOTIFICATION_ANY_STATUS_PATTERN, harness_header)) != 1
615
+ or re.search(TASK_NOTIFICATION_COMPLETED_STATUS_PATTERN, harness_header) is None
616
+ or re.search(TASK_NOTIFICATION_EXIT_ZERO_ENDING_PATTERN, notification_text) is None
617
+ ):
618
+ return set()
619
+ return set(all_tool_use_ids)
620
+
621
+
526
622
  def tool_calls_since_last_prompt(all_transcript_lines: Iterable[str]) -> list[TranscriptToolCall]:
527
623
  """Return the tool calls after the last user prompt, in order, each marked by whether it succeeded.
528
624
 
@@ -532,23 +628,61 @@ def tool_calls_since_last_prompt(all_transcript_lines: Iterable[str]) -> list[Tr
532
628
  prompt, reply call, its result with is_error -> [reply failed]
533
629
  prompt, resolve call with no result yet -> [resolve failed]
534
630
  reply call and result, then a new prompt -> []
631
+ reply call and result, then a queued prompt -> []
632
+ background call, started -> [call failed]
633
+ background call, notice of exit code 0 -> [call succeeded]
634
+ background call, notice of exit code 3 -> [call failed]
635
+ shell call whose result is the harness's own line -> [call failed] until its notice
636
+ any other call whose result holds those words -> [call succeeded]
535
637
 
536
638
  A hook that denies a call leaves an errored result, so a denied call does
537
- not count as a success. A tool result leaves the turn open.
639
+ not count as a success. A tool result leaves the turn open. A background
640
+ task notice is no user prompt, so it leaves the turn open too, whether it
641
+ is a user entry or a queued command attachment. Any other queued command
642
+ attachment, such as a prompt the user sent mid-turn, ends the turn as a
643
+ user prompt does. A call runs in the background when its
644
+ ``run_in_background`` input is truthy, or when it is a ``Bash`` or
645
+ ``PowerShell`` call whose result holds a line the harness writes for a
646
+ command in the background, starting ``Command running in background with
647
+ ID:``, ``Command was manually backgrounded by user with ID:`` or ``Command
648
+ did not complete within``. The same words in the result of any other tool,
649
+ or elsewhere in a line, change nothing. Such a call succeeds only
650
+ when the notice that names its tool use id reports a completed status
651
+ with exit code 0.
538
652
 
539
653
  Args:
540
654
  all_transcript_lines: JSON transcript entries, one per line.
541
655
  """
542
656
  all_calls: list[tuple[object, str, dict[str, object]]] = []
543
657
  all_succeeded_ids: set[object] = set()
658
+ all_finished_background_ids: set[object] = set()
659
+ all_moved_to_background_ids: set[object] = set()
544
660
  all_entries = (each_entry for each_entry in map(_parsed_entry, all_transcript_lines) if each_entry is not None)
545
661
  for each_entry_fields in all_entries:
546
- if _is_user_prompt(each_entry_fields):
547
- all_calls, all_succeeded_ids = [], set()
662
+ notification_text = _task_notification_text(each_entry_fields)
663
+ if notification_text is not None:
664
+ all_finished_background_ids.update(_background_ids_finished_without_error(notification_text))
665
+ continue
666
+ if _is_user_prompt(each_entry_fields) or _queued_command(each_entry_fields) is not None:
667
+ all_calls, all_succeeded_ids, all_finished_background_ids = [], set(), set()
668
+ all_moved_to_background_ids = set()
548
669
  continue
549
670
  all_calls.extend(_tool_use_calls(each_entry_fields))
550
671
  all_succeeded_ids.update(_succeeded_result_ids(each_entry_fields))
672
+ all_moved_to_background_ids.update(_moved_to_background_result_ids(each_entry_fields))
551
673
  return [
552
- TranscriptToolCall(each_name, each_input, each_id is not None and each_id in all_succeeded_ids)
674
+ TranscriptToolCall(
675
+ each_name,
676
+ each_input,
677
+ each_id is not None
678
+ and each_id in all_succeeded_ids
679
+ and (
680
+ each_id in all_finished_background_ids
681
+ or not (
682
+ each_input.get(RUN_IN_BACKGROUND_INPUT_KEY)
683
+ or (each_name in ALL_BACKGROUND_SHELL_TOOL_NAMES and each_id in all_moved_to_background_ids)
684
+ )
685
+ ),
686
+ )
553
687
  for each_id, each_name, each_input in all_calls
554
688
  ]