diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc index 35577f113..e43317769 100644 --- a/.markdownlint-cli2.jsonc +++ b/.markdownlint-cli2.jsonc @@ -3,6 +3,7 @@ // Prose paragraphs and data-heavy tables or URLs are intentionally long. // Reflowing at 80 columns hurts readability and churns diffs. "MD013": false, + "MD024": { "siblings_only": true }, // MD033 (inline HTML) stays enabled so native Markdown wins. // HTML comments, used as reference-link dividers, pass it. // The details and summary elements are allowed for GitHub collapsibles, which have no Markdown equivalent. diff --git a/AGENTS.md b/AGENTS.md index 8ce67c4f5..0c410033a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,7 +30,7 @@ Three rules bound every path above. **Read the hub's `main` branch as ground tru ## Context and Delegation Discipline -An agent session is billed on the context it carries, not the work it does. Every request re-reads the whole accumulated context, so a token added early is paid for again on every request that follows, and a long session bills its last task for every earlier one. These are cost rules. None of them licenses doing less work, skipping verification, or shipping something unreviewed. +An agent session is billed on the context it carries, not the work it does. Every request re-reads the whole accumulated context, so a token added early is paid for again on every request after it. A long session therefore bills its last task for every earlier one. Most of these are cost rules. None of these rules licenses doing less work, skipping verification, or shipping something unreviewed. ### Session Scope @@ -69,8 +69,9 @@ Bounds: If a rule you were given does not cover what you find, stop and report it. Do not guess, and do not read a governance file to resolve it. ``` -- **Wait in a background process, not in a poll loop.** A review or CI wait is a sequence of near-identical requests, each billed for whatever context it happens to carry. Run the wait as one backgrounded command that returns when the condition is met. +- **Wait in a background process, not in a poll loop.** A review or CI wait is a sequence of near-identical requests, each billed for whatever context it happens to carry. Run the wait as one backgrounded command rather than as a sequence of turns. - **A wait separates three outcomes, and says which one it reached.** The condition was met, it has not been met yet, and the wait cannot reach it at all are three different results, and a backgrounded wait that emits nothing renders all three identically. Run the command once in the foreground and read its output before backgrounding it, because a wait is only as good as the command inside it, and an unsupported flag on the installed tool version exits non-zero with an empty stdout that every naive test reads as "nothing yet". Never let a fallback stand in for a failed command, since `|| echo '[]'`, `|| true`, and `2>/dev/null` convert an error into that same reading, which is the suppression the write-safety rules already forbid on a mutation. Make the wait emit on failure as loudly as on success, so silence means "still running" and nothing else, and bound it, so a condition that is never coming ends in a report rather than in another wait. +- **Never write a wait as an unbounded shell loop.** This is a prohibition rather than a preference. A loop that waits for something, with no bound anywhere in the command that runs it, is forbidden. That holds in a tool call, in a script, and in a brief handed to a subagent. The bound goes inside that command. The wait then says which of three things it found: the condition met, the bound reached, or the check itself failing. **Prefer the mechanism that already signals.** Where the dispatch mechanism reports a subagent's completion itself, polling that subagent's output file is a second channel. The answer is already on its way. **The agent that starts a wait owns the process it leaves.** A process a tool call leaves running survives the turn, the subagent, and the run that dispatched it. So a run that dispatched workers does not report itself done while it cannot say what it left running. ## Where the Rules Live diff --git a/docs/host-setup.md b/docs/host-setup.md index b468c69d6..0cc32efaf 100644 --- a/docs/host-setup.md +++ b/docs/host-setup.md @@ -187,9 +187,9 @@ gh auth login --hostname github.com --git-protocol ssh Choose the SSH key generated above when prompted. -## Agent Write-Safety +## Agent Host-Safety -Host-level write safety is required where an agent runs with the maintainer's `gh` credentials. Each provider's implementation stays in its own subsection. +Host-level safety guards are required where an agent runs with the maintainer's `gh` credentials, and where it runs unattended on the maintainer's machine. Each provider's implementation stays in its own subsection. The requirements every agent's kit is built and audited against, agent-agnostic, are in [`host-setup/agent-safety/README.md`][agent-safety], the spec. Each agent's own implementation @@ -197,7 +197,7 @@ detail lives one level down, following the same contract-vs-implementation split for [`host-setup/`][host-setup-dir]'s own per-platform subdirectories: this file states the requirement, the per-agent `README.md` owns the how-to. -### Claude Code Write Safety +### Claude Code Host Safety The Claude Code safety kit is the first agent-specific control to deploy on a new system, and the only one implemented today. Install, verify, scope limits, and the cross-owner write grant @@ -206,15 +206,15 @@ mechanism are all in [`host-setup/agent-safety/claude/README.md`][agent-safety-c the hook and the `CLAUDE.md` block cover every session on the machine, including ad-hoc work in no project at all, which is where the incident behind the kit happened. -### Codex Write Safety +### Codex Host Safety -No equivalent host write hook ships yet for Codex. Keep Codex's sandbox and execution policies +No equivalent host-safety hook ships yet for Codex. Keep Codex's sandbox and execution policies enabled meanwhile. [`host-setup/agent-safety/codex/README.md`][agent-safety-codex] states the gap and what implementing against the spec would look like. [Issue #781][issue-781] tracks it. -### opencode Write Safety +### opencode Host Safety -No equivalent host write hook ships yet for opencode. Keep opencode's own permission model enabled +No equivalent host-safety hook ships yet for opencode. Keep opencode's own permission model enabled meanwhile. [`host-setup/agent-safety/opencode/README.md`][agent-safety-opencode] states the gap and what implementing against the spec would look like. [Issue #781][issue-781] tracks it. @@ -349,7 +349,7 @@ Verified on Windows 11 Pro 10.0.26200 with PowerShell 7.6.4, where `python3 scri | Run the four linters locally, matching CI | `docker` runs each as the same pinned image CI uses | | Run the repo's own gates and tests | Python 3 covers `scripts/` and `spec/` with no packages to install | | Drive the PR and Copilot review loop | `gh` and an authenticated session | -| Let an agent work with the `gh` credentials live | the write-safety kit is installed | +| Let an agent work with the `gh` credentials live | the host-safety kit is installed | | Have the fleet skills surface in every agent session | the skills install stamp is current per `skills_install.py --report` | A host that fails any row is not ready for the procedure that row names, and the fix belongs on the host rather than in a repo. diff --git a/host-setup/README.md b/host-setup/README.md index 04e2f54be..bc60a3504 100644 --- a/host-setup/README.md +++ b/host-setup/README.md @@ -10,7 +10,7 @@ What a machine needs before it can be worked in, and the tooling that puts it th - [`menu.ps1`][menu-ps1] is the same front end for native Windows, over `host-setup\windows\` instead. It runs under Windows PowerShell 5.1 and hands off to PowerShell 7 the same way `bootstrap.ps1` does, and it adds one menu entry with no Linux peer, reporting the WSL platform through `setup-wsl.ps1`. - [`linux/`][linux] holds the tooling itself, for Debian and Ubuntu based hosts, Proxmox and WSL included. `install-tools.sh` installs and upgrades the host tools, `upgrade-host.sh` upgrades the packages of the current release or moves to the next one, `setup-github.sh` configures the SSH key, git, and commit signing, and `install-skills.sh` drives the hub's skills installer from the same tree. - [`windows/`][windows] holds the tooling for native Windows, through `winget` and PowerShell 7. `install-tools.ps1` installs and upgrades the host tools, `upgrade-host.ps1` upgrades the winget packages and updates the WSL platform, `setup-github.ps1` configures the SSH key, git, and commit signing, `setup-wsl.ps1` installs a WSL distribution and reports the Docker Desktop integration, and `install-skills.ps1` drives the hub's skills installer from the same tree. -- [`agent-safety/`][agent-safety] holds the write-safety guards, deployed per machine and per account. +- [`agent-safety/`][agent-safety] holds the host-safety guards, deployed per machine and per account. ## Standing a Host Up @@ -100,7 +100,7 @@ Reaching `spec/audit.py` and `scripts/carry.py` from outside a hub checkout mean ## Three Rules This Directory Follows -**Group by whichever axis has one member.** `linux/` is three concerns on one platform, so it is a platform directory. Windows host tooling therefore sits at `windows/` rather than beside the Linux scripts, because the `winget` equivalent of `install-tools.sh` is a different program rather than a translation of one. It carries one registry record per tool where the Linux script carries four functions, since every Windows source is `winget` and the per-tool variation those functions exist for does not arise. `windows/` also carries a fourth script with no Linux peer, because WSL is a Windows-side concern. The loader and the menu are one concern, two platforms, so `bootstrap.ps1` sits beside `bootstrap.sh`, and `menu.ps1` beside `menu.sh`, at the top level rather than inside `windows/`. `agent-safety/` follows the same platform-grouping shape one level down: it holds one concern (write-safety guards) implemented per *agent* rather than per OS, so `claude/`, `codex/`, and `opencode/` sit beside each other the way `linux/` and `windows/` do, each holding that one agent's own files (a Claude Code implementation carries its own `install.sh`/`install.ps1` pair inside `claude/`, the same platform variation `linux/`/`windows/` carry at the top level, just nested one directory deeper because the outer axis here is the agent, not the OS). Its root `README.md` is the agent-agnostic spec those per-agent directories each implement, not a concern directory of its own. +**Group by whichever axis has one member.** `linux/` is three concerns on one platform, so it is a platform directory. Windows host tooling therefore sits at `windows/` rather than beside the Linux scripts, because the `winget` equivalent of `install-tools.sh` is a different program rather than a translation of one. It carries one registry record per tool where the Linux script carries four functions, since every Windows source is `winget` and the per-tool variation those functions exist for does not arise. `windows/` also carries a fourth script with no Linux peer, because WSL is a Windows-side concern. The loader and the menu are one concern, two platforms, so `bootstrap.ps1` sits beside `bootstrap.sh`, and `menu.ps1` beside `menu.sh`, at the top level rather than inside `windows/`. `agent-safety/` follows the same platform-grouping shape one level down: it holds one concern (host-safety guards) implemented per *agent* rather than per OS, so `claude/`, `codex/`, and `opencode/` sit beside each other the way `linux/` and `windows/` do, each holding that one agent's own files (a Claude Code implementation carries its own `install.sh`/`install.ps1` pair inside `claude/`, the same platform variation `linux/`/`windows/` carry at the top level, just nested one directory deeper because the outer axis here is the agent, not the OS). Its root `README.md` is the agent-agnostic spec those per-agent directories each implement, not a concern directory of its own. **Nothing here needs Python to stand a host up, and neither loader needs an interpreter to fetch what it drives.** [`docs/host-setup.md`][host-setup] carries that as part of the contract, with the reasoning. `bootstrap.sh` needs only `curl` and `tar`. `bootstrap.ps1` needs only `tar.exe`, which has shipped with Windows since 1803, and installs its one further dependency, `pwsh`, itself through `winget`. The one exception is the `install-skills` pair, which drives the Python installer at `scripts/skills_install.py` and runs last in a stand-up for exactly that reason: `install-tools` has provided the interpreter by then, and run alone on a host without one it stops and names the tools step as its prerequisite. The menu needs `git` to fetch the hub, and it checks for a working Python the same lazy way: only the tasks that call a Python tool ask for it, and every host task still works without one. Neither loader runs a gate as a closing step: [`scripts/host_gate.py`][host-gate] measures a host against the floors and is not called from here, and nothing here is called from it. A host set up by hand years ago is an ordinary host, so the gate reports what it is missing and running this tooling is a remedy a person chooses. The two are joined at code time instead, by [`scripts/tests/test_bootstrap.py`][test-bootstrap] asserting that every tool the spec requires is one this tooling can provide. diff --git a/host-setup/agent-safety/README.md b/host-setup/agent-safety/README.md index 8c2953592..ccb791efb 100644 --- a/host-setup/agent-safety/README.md +++ b/host-setup/agent-safety/README.md @@ -1,7 +1,9 @@ -# Agent Write-Safety Spec +# Agent Host-Safety Spec -What any coding agent must be stopped from doing when it runs on this host with the maintainer's -`gh` credentials, stated once, independent of which agent implements it. This file is the source +What any coding agent must be stopped from doing when it runs unattended on this host, stated once, +independent of which agent implements it. Most of it guards the maintainer's `gh` credentials, which +is where the harm started. Requirements 7 and 8 guard the machine itself, which is the other thing +an unattended agent takes down. This file is the source of truth: an implementation is built from the requirements below, and an implementation is audited by checking its decisions against them, not by reading its source as the implicit spec. @@ -10,15 +12,18 @@ by checking its decisions against them, not by reading its source as the implici A mis-targeted GitHub write acts publicly under the maintainer's identity: a fabricated node id once posted a stray comment, as the maintainer, to a stranger's repository. A mutating git command run directly in a primary checkout destroys another task's uncommitted work without ever reaching -GitHub. Both incidents happened under prose rules the agent had already read. Neither was fixed by -writing the rule more clearly. [`GOVERNANCE.md`][governance] "Durable Knowledge and Self-Improvement" +GitHub. An unbounded shell wait outlives every agent in the run that wrote it, and a machine carrying +enough of them has to be rebooted. All three incidents happened under prose rules the agent had +already read. None was fixed by writing the rule more clearly. [`GOVERNANCE.md`][governance] "Durable Knowledge and Self-Improvement" states the general criteria for when a rule like this earns a mechanical hook instead of staying -prose. The requirements below are the write-safety instance of that criteria, applied. +prose. The requirements below are that criteria applied to this host. ## Requirements Each requirement is stated as a decision rule, precise enough to implement against any agent's own -hook or approval-gate API, not tied to Claude Code's `PreToolUse` JSON shape. +hook or approval-gate API, not tied to Claude Code's `PreToolUse` JSON shape. Requirement 8 is the +one stated against the end of a session rather than against a tool call, because what it covers has +already happened by the time any tool call is judged. 1. **A GitHub write with its output discarded or forced to success is denied.** A state-changing `gh`/API call piped to `>/dev/null`, `2>/dev/null`, `&>/dev/null`, `|| true`, `|| :`, or `|| echo` @@ -175,6 +180,104 @@ hook or approval-gate API, not tied to Claude Code's `PreToolUse` JSON shape. `owner/repo` allowlist, while this one is a boolean escape hatch, granted by any non-falsy value and withheld by a recognized falsy one ("0"/"false"/"no"/"off"/empty), not by list membership. +7. **A shell wait carrying no bound is denied.** `until ; do sleep ; done` and `while + ! ; do sleep ; done` are what an agent writes when it is told to poll, and what + runs until the machine is rebooted when the condition never comes true. The shell is not the + agent's to end either: a shell started by a tool call runs in a session of its own, so it + outlives the turn, the subagent, and the run that started it, and nothing reaps it. Deny a + `while`/`until` compound whose body calls `sleep`, unless the command text carries its own bound. + A bound is one of three forms, and naming them exactly is the point, since a worker + reproduces a quoted shape and does not reproduce an adjective. The first is a `timeout + ` running the `sh -c`/`bash -c` wrapper that holds the loop, `timeout 600 bash -c + ''`. That placement is the only one that works, since `timeout` takes a command and + a loop keyword is not one, so `timeout 600 until ...; do sleep 30; done` is a syntax error + rather than a bounded wait. The second is an arithmetic guard in the + loop's own condition, either the test-builtin form (`[ "$i" -lt 120 ]`) or the arithmetic form + (`(( SECONDS < 600 ))`). A nested loop is judged on its own terms, so an unbounded inner wait is + denied inside a bounded outer one, which is what it is. A heredoc body is data rather than a + command line and is skipped, except one fed to a shell, which is the script that shell runs, so a + document quoting the forbidden shape is written rather than denied. + + A `for` loop in its arithmetic form, `for ((;;))`, is reached too, since it runs forever exactly as + `while true` does, while a `for x in ` is bounded by its own word list. The third is a loop whose condition is a + `read` drawing on an input redirect that binds descriptor 0, on that loop's own invocation, + which is bounded by that input, so throttling between iterations with a `sleep` is ordinary work + rather than a leak. Four things have to hold, and a real command defeated each of them. + The redirect binds descriptor 0, since a `read` consumes that one and a redirect on any other + leaves it reading whatever it read before. The `read` itself names no descriptor, since + `read -u 3` draws on the one it names rather than on the one the redirect bound. The redirect + counted is the last one binding descriptor 0, since a shell applies redirections in order and + each replaces the last, so an earlier `< file` cannot vouch for a later `< /dev/zero`. And its + target names a source that ends, where a pipe's producer is unknown from the command text. A loop + fed by `yes | while read line; do sleep 30; done` never exhausts, so a piped read is denied, and + that false deny is the safe direction. A process substitution is that same unknown producer + behind a redirect, so `done < <(yes)` is no bound either. Duplicating a descriptor rather than + opening a source, `done <&0`, rebinds that same pipe to itself. So does a target under `/dev` or + `/proc`, which is read as a category rather than as a list of the streams that never end, since + every one of those has another spelling: `/proc/self/fd/0` re-opens the pipe `/dev/stdin` does, + `/dev/full` reads like `/dev/zero`, and a `.` segment or a doubled leading slash defeats a + literal compare of either. The target is normalized and the whole of both trees is denied, + `/dev/null` included. Only an absolute target is read that way, since a relative one resolves + against a working directory the rule does not model. + + A command that forks work out of a `timeout`'s reach is bounded by nothing, whatever else it + carries. Three shapes are recognized. A background operator lets the shell exit at once, so + `timeout`'s own child is gone before it fires and it signals nothing, measurably the same leak as + having written no bound at all. `coproc` backgrounds with no operator at all, so an operator scan + never sees it. And `setsid` starts a session of its own, which no signal to the timeout's process + group reaches. Recognized rather than exhaustive: a command can reach a new session through a + launcher this does not name, and what those cost is a leak requirement 8 reports after the fact + rather than a deny before it. + + Both are read over the whole command rather than tied to one loop, deliberately, and that is + coarser than it could be. Deciding which `&` backgrounds which compound needs a parse this rule + does not have, and four rounds of narrowing a scan that tried each closed the shapes it was shown + and left the next one: a statement between the loop and its group's closer, a `disown` before a + `wait`, a subshell the sequencing had already reaped. Reading any fork as fatal costs a false + deny on ` & wait`, a bound nothing in the command text can verify. A `timeout` the command + backgrounds as a whole still bounds what it runs, since + that `timeout` process outlives the shell that started it, so the ordinary + `timeout 900 &` is unaffected. + + Two heredoc limits are known and unclosed rather than accepted, both narrow and both written + here so a reader does not have to find them. A body kept because a shell reads it has its own + lines re-tested as openers, so an unterminated opener inside one swallows the top-level lines + after it. And the scan for a shell over the heredoc's pipeline reads every token in it rather + than only the ones in command position, so `cat < deny4["DENY - requirement 4\n(fails closed for a\nprotected-default branch\nwith undeterminable rules)"] isgit -- no --> isprimary{"A mutating git op\ntargeting a primary\ncheckout, not exempt?"} isprimary -- yes --> deny6["DENY - requirement 6"] - isprimary -- no --> isghwrite{"A GitHub-write\ncommand at all?"} + isprimary -- no --> iswait{"A while, until or\narithmetic-for loop\nthat sleeps, with no\ntimeout, no arithmetic\nguard and no read\nof an input redirect?"} + iswait -- yes --> deny7["DENY - requirement 7"] + iswait -- no --> isghwrite{"A GitHub-write\ncommand at all?"} isghwrite -- no --> allow["ALLOW"] isghwrite -- yes --> suppressed{"Output discarded or\nforced to success?"} suppressed -- yes --> deny1["DENY - requirement 1"] @@ -216,12 +321,15 @@ flowchart LR ``` The first diagram is this spec's actual decision flow, generalized from `claude/gh-write-guard.py`'s -`classify()`. The second is why a failure lands in one layer and not another. A rule that never +`classify()`. Requirement 8 appears nowhere in it, deliberately: it judges no tool call, and it runs +once at the end of a session on whatever the denials above did not prevent. The second is why a failure lands in one layer and not another. A rule that never reached the session at all is a loading bug, fixed the way PR #1081 fixed `local-strict-review`'s missed trigger, by wiring `CLAUDE.md` to import `AGENTS.md`. A rule that reached the session and was still not followed, where the trigger is mechanically decidable and the harm is destructive, -is promoted to a host hook (requirement 6, above, tracked at [issue #1073][issue-1073], is the -worked example). A rule whose violation can only be judged, not mechanically decided (was a +is promoted to a host hook. Requirement 6, above, tracked at [issue #1073][issue-1073], is the +worked example, and requirement 7, tracked at [issue #1589][issue-1589], is the second: the prose +rule against an unbounded wait was read, quoted into six worker briefs, and produced the forbidden +shape in all six. A rule whose violation can only be judged, not mechanically decided (was a review finding actually evidence-backed?), stays prose and a chained Skill trigger, since a hook there could only nag, never decide. @@ -246,19 +354,20 @@ every agent. | Agent | Status | Implementation | | --- | --- | --- | -| Claude Code | All 6 requirements, via a `PreToolUse` hook | [`claude/README.md`][claude] | +| Claude Code | All 8 requirements, via a `PreToolUse` hook and a `SessionEnd` sweep | [`claude/README.md`][claude] | | Codex | No hook yet -- tracked at [issue #781][issue-781] | [`codex/README.md`][codex] | | opencode | No hook yet -- tracked at [issue #781][issue-781] | [`opencode/README.md`][opencode] | GitHub Copilot carries no subdirectory here: it reviews through GitHub's own hosted infrastructure rather than running local shell commands under the maintainer's credentials, so it has no analogous -local write-safety hazard for this kit to cover. +local host-safety hazard for this kit to cover. ## Auditing an Implementation Against This Spec -Run the implementation's own self-test (`claude/gh-write-guard.py --selftest` for Claude Code) and -compare every case against the requirements list above, one by one, rather than reading the -implementation's source as though it were the spec. A case the self-test doesn't cover is a gap in +Run each of the implementation's own self-tests (`claude/gh-write-guard.py --selftest` and +`claude/stray-process-sweep.py --selftest` for Claude Code) and compare every case against the +requirements list above, one by one, rather than reading the implementation's source as though it +were the spec. A case the self-test doesn't cover is a gap in the audit, not evidence the requirement is satisfied. This is the concrete shape of "ask Claude to audit the Claude hooks against the spec" or "ask Codex to implement Codex's own hooks against the spec": point the agent at this file's requirements, not at another agent's source code. @@ -270,3 +379,4 @@ spec": point the agent at this file's requirements, not at another agent's sourc [governance]: ../../GOVERNANCE.md [issue-781]: https://github.com/ptr727/ProjectTemplate/issues/781 [issue-1073]: https://github.com/ptr727/ProjectTemplate/issues/1073 +[issue-1589]: https://github.com/ptr727/ProjectTemplate/issues/1589 diff --git a/host-setup/agent-safety/claude/README.md b/host-setup/agent-safety/claude/README.md index 107ce97b1..c1df8ea38 100644 --- a/host-setup/agent-safety/claude/README.md +++ b/host-setup/agent-safety/claude/README.md @@ -1,8 +1,8 @@ -# Claude Code Write-Safety Kit +# Claude Code Host-Safety Kit -This is the Claude Code implementation of the write-safety spec at [`../README.md`][spec] -- +This is the Claude Code implementation of the host-safety spec at [`../README.md`][spec] -- per-machine, user-account-scoped guards, deployed first on any system where Claude Code uses the -maintainer's `gh` credentials. Linux, WSL, macOS, and Windows are supported. See the spec for the +maintainer's `gh` credentials or runs unattended. Linux, WSL, macOS, and Windows are supported. See the spec for the requirements this kit satisfies and why each exists. What follows here is Claude-Code-specific installation and operational detail. Codex and opencode have no equivalent hook yet -- see [`../codex/README.md`][codex] and [`../opencode/README.md`][opencode] for their status, tracked at @@ -12,7 +12,8 @@ installation and operational detail. Codex and opencode have no equivalent hook Into `~/.claude/` (or `%USERPROFILE%\.claude\` on Windows): -- **`hooks/gh-write-guard.py`**: a PreToolUse hook that denies three classes of dangerous action. First, the GitHub **write** footguns behind the cross-repo comment incident: a state-changing `gh` call whose output is discarded, a GraphQL mutation passing a **literal** node id instead of a `$variable`, and a `gh` write whose explicit target is under an owner other than the checkout origin's. Sibling repositories under the same owner are allowed, since the harm this guards is reaching a stranger's repository rather than working across one maintainer's own fleet, and a different owner is allowed only when the maintainer names it in `GH_WRITE_GUARD_ALLOW` (an `owner/repo` list, where `owner/*` grants a whole owner). That variable is read from the environment the session was launched with, which is the one channel an agent cannot set for itself: a hook runs as its own process, so an inline `VAR=x cmd` prefix or an `export` inside a Bash call never reaches it. Second, a **git operation that bypasses a repository protection**. The branch-rule cases (a direct push to a branch that requires a pull request, a force-push where history is protected, a branch delete where deletion is blocked) are judged against the branch's **live** rules, so a code-style `develop` is denied while a config-style `develop` is allowed with no per-repo configuration. A push to a protected-default branch fails closed when its rules cannot be determined, either because the API is unreachable or because the checkout's origin cannot be resolved to query them. The explicit-bypass flags are denied **unconditionally**, since the flag is itself the bypass and needs no branch query: `gh pr merge --admin` overrides the server-side merge gate, and `git commit`/`git push --no-verify` skips the local git hooks. Third, a **mutating git operation run directly against a primary checkout** (`checkout`/`switch`/`pull`/`reset`/`rebase`/`merge`/`cherry-pick`/`revert`/`restore`/`add`/`commit`/`rm`/`mv`/`apply`/`am`/`push`/`stash` (anything but `list`/`show`)/`clean -f`/`worktree remove -f`), the harm behind a second incident where an agent reused the maintainer's own primary checkout instead of a worktree despite having read the prose rule against it. "Primary" is decided by comparing `git rev-parse --git-dir` against `--git-common-dir`, not a `.git`-is-a-directory guess. `worktree add`/`list`/`prune`, an unforced `worktree remove`, `merge --ff-only`/`pull --ff-only`, and a `checkout `/`switch ` carrying no force flag (bundled or attached forms like `-qf`/`-Bname` recognized, not only an exact token) stay exempt even in a primary checkout, matching the documented base-clone cleanup step the `repo-worktree` skill already carries. A subcommand this rule does not recognize is resolved through a chain of git aliases, inline and persisted, before falling through, so a custom alias cannot hide a denied builtin behind an unrecognized name. A `!`-prefixed shell alias is denied outright rather than interpreted. The target directory follows real git's own `-C`/`--work-tree`/`--git-dir` priority, not a last-option-wins scan. A different owner-style grant, `GH_WRITE_GUARD_ALLOW_PRIMARY_CHECKOUT`, follows the same channel as `GH_WRITE_GUARD_ALLOW`. Reads and everything else pass through. It fires even in autonomous / bypass-permissions sessions, which is how the first incident happened. See the root spec's requirement 6 for the exact rules. +- **`hooks/gh-write-guard.py`**: a PreToolUse hook that denies four classes of dangerous action. First, the GitHub **write** footguns behind the cross-repo comment incident: a state-changing `gh` call whose output is discarded, a GraphQL mutation passing a **literal** node id instead of a `$variable`, and a `gh` write whose explicit target is under an owner other than the checkout origin's. Sibling repositories under the same owner are allowed, since the harm this guards is reaching a stranger's repository rather than working across one maintainer's own fleet, and a different owner is allowed only when the maintainer names it in `GH_WRITE_GUARD_ALLOW` (an `owner/repo` list, where `owner/*` grants a whole owner). That variable is read from the environment the session was launched with, which is the one channel an agent cannot set for itself: a hook runs as its own process, so an inline `VAR=x cmd` prefix or an `export` inside a Bash call never reaches it. Second, a **git operation that bypasses a repository protection**. The branch-rule cases (a direct push to a branch that requires a pull request, a force-push where history is protected, a branch delete where deletion is blocked) are judged against the branch's **live** rules, so a code-style `develop` is denied while a config-style `develop` is allowed with no per-repo configuration. A push to a protected-default branch fails closed when its rules cannot be determined, either because the API is unreachable or because the checkout's origin cannot be resolved to query them. The explicit-bypass flags are denied **unconditionally**, since the flag is itself the bypass and needs no branch query: `gh pr merge --admin` overrides the server-side merge gate, and `git commit`/`git push --no-verify` skips the local git hooks. Third, a **mutating git operation run directly against a primary checkout** (`checkout`/`switch`/`pull`/`reset`/`rebase`/`merge`/`cherry-pick`/`revert`/`restore`/`add`/`commit`/`rm`/`mv`/`apply`/`am`/`push`/`stash` (anything but `list`/`show`)/`clean -f`/`worktree remove -f`), the harm behind a second incident where an agent reused the maintainer's own primary checkout instead of a worktree despite having read the prose rule against it. "Primary" is decided by comparing `git rev-parse --git-dir` against `--git-common-dir`, not a `.git`-is-a-directory guess. `worktree add`/`list`/`prune`, an unforced `worktree remove`, `merge --ff-only`/`pull --ff-only`, and a `checkout `/`switch ` carrying no force flag (bundled or attached forms like `-qf`/`-Bname` recognized, not only an exact token) stay exempt even in a primary checkout, matching the documented base-clone cleanup step the `repo-worktree` skill already carries. A subcommand this rule does not recognize is resolved through a chain of git aliases, inline and persisted, before falling through, so a custom alias cannot hide a denied builtin behind an unrecognized name. A `!`-prefixed shell alias is denied outright rather than interpreted. The target directory follows real git's own `-C`/`--work-tree`/`--git-dir` priority, not a last-option-wins scan. A different owner-style grant, `GH_WRITE_GUARD_ALLOW_PRIMARY_CHECKOUT`, follows the same channel as `GH_WRITE_GUARD_ALLOW`. Reads and everything else pass through. Fourth, an **unbounded shell wait**, which the root spec's requirement 7 defines in full rather than this bullet redefining it. In outline: a loop that sleeps, carrying no bound the rule recognizes. It is the shape an agent writes when a brief tells it to poll. It is also the harm behind a third incident, where seven such loops outlived the subagents that wrote them and the run that dispatched those subagents. A shell started by a tool call runs in a session of its own, so the agent could not have reaped it even had it tried. A nested loop is judged on its own terms, and a command that forks anything out of a `timeout`'s reach, by backgrounding it or by `setsid`, is bounded by nothing. A heredoc body is data rather than a command line unless a shell is what it is fed to, so a document quoting the forbidden shape is written rather than denied. It fires even in autonomous / bypass-permissions sessions, which is how the first incident happened. See the root spec's requirements 6 and 7 for the exact rules. +- **`hooks/stray-process-sweep.py`**: a SessionEnd hook that reports, and never ends, the process trees that outlive the session. The guard above stops a leak from being written. This finds the ones already running: the ones started before the guard was installed, and the shapes the guard deliberately does not reach. It reads the process table once. It reports every descendant of the agent process running outside the agent's own session. It names each subtree root's command and age, and hands over the `kill` line. It kills nothing itself. A long build backgrounded on purpose reads identically to a leaked wait from there. What is still wanted on the machine is the maintainer's call. A SessionEnd hook cannot block, and its JSON output is discarded, so stderr on exit 2 is the one channel that reaches the maintainer. The sweep uses that for a report rather than for a refusal. It registers under a group carrying no matcher, which fires on every exit reason. It also carries an explicit timeout, since the event's own budget is 1.5 seconds and only a declared per-hook timeout raises it. See the root spec's requirement 8. - **Two marker-delimited blocks of host-wide content in `CLAUDE.md`**, loaded into every session on the machine (including ad-hoc work outside any project), installed and updated independently so one can change without rewriting the other. - The `agent-safety` block carries restrictions alone, so nothing in it can widen a permission. `Repository Boundaries and Write Safety` mirrors the committed `GOVERNANCE.md` section of the same name, carrying as behavioral guidance its write rules and its rules that a task works in its own checkout and isolates into its own worktree before its first file edit. `Data in Agent-Authored Text` mirrors `GOVERNANCE.md` "Representative Data in Agent-Authored Text", so an agent illustrates with constructed data rather than data observed on the machine. `Authorization Scope and Memory Hygiene` bounds how a granted permission is recorded and read. Each mirrors a rule that otherwise reaches fleet repos only. - The `fleet-bootstrap` block carries `Fleet Governance Entry Point`, which names the template repository and routes by the state a repository is actually in. It is separate precisely because it enables rather than restricts, and the safety block's own text says nothing in it widens a permission, so merging the two would contradict that. It is host-wide rather than per repository because the repositories that most need it are the ones carrying no instruction set to point the way, and it mirrors the byte-locked `AGENTS.md` "Fleet Bootstrap" section that a conformant repository carries. @@ -44,7 +45,8 @@ The deployed copy on each machine is a snapshot, so when the guard changes upstr ## Verify (POSIX Shell) ```sh -python3 ~/.claude/hooks/gh-write-guard.py --selftest # decision matrix: all cases pass +python3 ~/.claude/hooks/gh-write-guard.py --selftest # decision matrix: all cases pass +python3 ~/.claude/hooks/stray-process-sweep.py --selftest # reporting matrix: all cases pass grep -c 'agent-safety v' ~/.claude/CLAUDE.md # expect 2 (start + end marker) grep -c 'fleet-bootstrap v' ~/.claude/CLAUDE.md # expect 2 (start + end marker) grep -cF 'Bash(python3 scripts/pr_review.py:*)' ~/.claude/settings.json # expect 1 (never duplicated) @@ -53,7 +55,8 @@ grep -cF 'Bash(python3 scripts/pr_review.py:*)' ~/.claude/settings.json # expe On Windows PowerShell: ```powershell -py -3 "$env:USERPROFILE\.claude\hooks\gh-write-guard.py" --selftest # all cases pass +py -3 "$env:USERPROFILE\.claude\hooks\gh-write-guard.py" --selftest # all cases pass +py -3 "$env:USERPROFILE\.claude\hooks\stray-process-sweep.py" --selftest # all cases pass (Select-String 'agent-safety v' "$env:USERPROFILE\.claude\CLAUDE.md").Count # expect 2 (Select-String 'fleet-bootstrap v' "$env:USERPROFILE\.claude\CLAUDE.md").Count # expect 2 (Select-String -SimpleMatch 'Bash(python3 scripts/pr_review.py:*)' "$env:USERPROFILE\.claude\settings.json").Count # expect 1 @@ -116,6 +119,9 @@ Run the installer rather than hand-copying this block on a host where the two mi "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "\"python3\" \"/.claude/hooks/gh-write-guard.py\"" } ] } + ], + "SessionEnd": [ + { "hooks": [ { "type": "command", "command": "\"python3\" \"/.claude/hooks/stray-process-sweep.py\"", "timeout": 10 } ] } ] }, "permissions": { @@ -132,9 +138,13 @@ Every other key in the file is left as it stands, `permissions.allow` included, - **Precision over recall for the write footguns.** The hook denies the specific dangerous write shapes with high confidence rather than gating every write, so it is written to avoid blocking legitimate work -- a known false-positive shape is a parser defect to fix, not an accepted cost. A shape it does not catch still falls under the behavioral rules. - **The branch-bypass rule fails closed.** Unlike the write-footgun rules, a push to `main`/`master`/`develop` is denied even when its rules cannot be determined (the API is unreachable, or the checkout's origin cannot be resolved to query them), because the harm there is a silent success under the maintainer's admin bypass. The rule reads each branch's live rules, so it adapts to every repo (a code-style `develop` denies, a config-style `develop` allows) with no per-repo configuration, and hands the exact command to the maintainer to run when a bypass is genuinely intended. - **Opaque targets are unseen.** The hook cannot see the repository behind a GraphQL node id, which is exactly why rule 2 blocks a *literal* id at all, since a captured `$variable` is trusted. Likewise, the cross-origin check only runs when an `origin` can be resolved and the write names an explicit `-R`/`repos//` target. A write from a non-git directory, or one whose target is only a node id, is evaluated by rules 1 and 2 alone. -- **A write inside a script file is unseen, so never batch writes into a script.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string, so a `git push` or a `gh` mutation inside the script reaches the server without the hook ever parsing it. This is the widest hole in the kit and it is one an agent opens by accident, since collecting fifteen repetitive pushes into a loop looks like tidiness rather than like disabling a guard. Issue each write as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and not the script. +- **A write or a wait inside a script file is unseen, so never put either in a script to run it.** The hook reads the command the agent runs, which for `bash deploy.sh` is that one string. A `git push` or a `gh` mutation inside the script therefore reaches the server unparsed. An unbounded wait inside that same script is equally unseen, and worse in one way. A denied write fails loudly. A wait the guard never saw runs until something ends it, which is one of the leaks the SessionEnd sweep exists to find afterwards. This is the widest hole in the kit, and an agent opens it by accident. Collecting fifteen repetitive pushes into a loop looks like tidiness, and so does moving a poll into a script to keep a tool call short. Neither looks like disabling a guard. Issue each write and each wait as its own command. A script that only reads, computes, or prepares local commits is fine, because the boundary is the write and the wait rather than the script. - **Not a credential control.** A fine-grained PAT limited to owned repositories is a separate, stronger structural guard (a hard `403` on any non-owned repo) and is left to per-machine credential setup, out of this kit. - **Rule 6's ref-checkout and `--ff-only` exemptions are deliberate, not a gap.** The #1073 incident's own literal commands (an unforced `git checkout main`, then `git pull --ff-only`) are exactly this shape, so this rule does not deny the incident's own commands specifically. Denying them would also break the documented base-clone cleanup step in the `repo-worktree` skill, which needs precisely those two. The concurrent-access hazard those commands still carry (switching HEAD, or fast-forwarding, in a checkout another task might be relying on) is not decidable from the command text alone, so it stays the prose rule's job. A non-force flag alongside the ref, such as `--detach`, is exempt too, not only a strictly zero-flags invocation -- git's own overwrite-refusal on a dirty tracked file is unaffected by it, verified live. +- **The sweep runs on Linux and WSL.** Whether a descendant outlives the agent is decided by comparing session ids, which the sweep reads with `ps -eo sess=,etimes=`. Both are procps format keywords. Windows has no session test at all, and a BSD `ps`, which is what macOS carries, has neither keyword. The script returns immediately on Windows and on macOS rather than printing a failure at every session end there. The installer still deploys and registers it on every platform. That keeps the installer, the payload digest, and the registration checks identical everywhere, which is worth more than a branch nobody has run. +- **The sweep runs at session end, not at subagent end.** `SubagentStop` is where the incident's own loops were born, and it would catch each one hours earlier. Its exit 2 prevents the subagent from stopping, though, so the one channel that reaches a human on `SessionEnd` is not free there. A sweep that cannot report is a sweep that does nothing. The cost of the later moment is real. A run dispatching workers for hours reaches session end once, having finished many rounds, so every leak it wrote is reported together at the end. +- **The sweep reports and never kills.** It cannot tell a leaked wait from a long build backgrounded on purpose, and nothing about ending a process on the maintainer's machine is reversible. It hands over the `kill` line and stops there. +- **The sweep sees the agent's own descendants, and a leak can leave that tree.** A process whose tool-call shell has since exited is reparented to init, so no descendant walk reaches it. What the sweep does see is the backgrounded tool-call shell itself. That is the shape both incidents left behind, and it stays a child of the agent for the whole session. The residual gap is a process that shell in turn backgrounded and abandoned. It is stated here rather than left for a reader to infer from a clean report. - **Rule 6 needs git 2.31 or newer for `rev-parse --path-format=absolute`.** An older git errors on that flag, `_is_primary_checkout` reads that as an unresolved target, and the rule fails open silently on that host -- no crash, no denial, and no diagnostic pointing at the version. `spec/host-tools.json` carries no floor on `git` today (see its own `why` field for the reasoning that applies fleet-wide). This is a narrower, rule-specific dependency worth knowing about rather than a case for raising that floor on its own. diff --git a/host-setup/agent-safety/claude/gh-write-guard.py b/host-setup/agent-safety/claude/gh-write-guard.py index f30f002c1..fc38a0acb 100755 --- a/host-setup/agent-safety/claude/gh-write-guard.py +++ b/host-setup/agent-safety/claude/gh-write-guard.py @@ -1,15 +1,15 @@ #!/usr/bin/env python3 -"""PreToolUse guard: deny the GitHub-write footguns and the primary-checkout mutation behind two incidents. +"""PreToolUse guard: deny the GitHub-write footguns, the primary-checkout mutation, and the unbounded wait behind three incidents. Registered as a Claude Code PreToolUse hook on the Bash tool. It reads the tool-input JSON on stdin, classifies the command, and DENIES (with a reason shown to the agent) when a command is a GitHub *write* -matching a known-dangerous pattern, or a mutating git operation run directly against a primary checkout. -Reads and everything that is not a clear write pass through. See host-setup/agent-safety/README.md for +matching a known-dangerous pattern, a mutating git operation run directly against a primary checkout, or a +shell wait carrying no bound. Reads and everything that is not a clear write pass through. See host-setup/agent-safety/README.md for the requirements this implements, stated once, agent-agnostic, and for how to audit this file against them. -Precision over recall for the write-footgun shapes (1-3) and the primary-checkout shape (6): they deny -the specific shapes that caused an incident, not everything unparseable, since a false deny would break the +Precision over recall for the write-footgun shapes (1-3), the primary-checkout shape (6), and the +unbounded-wait shape (7): they deny the specific shapes that caused an incident, not everything unparseable, since a false deny would break the agent, and a miss still falls under the GOVERNANCE.md "Repository Boundaries and Write Safety" prose rules. The branch-bypass rule (4) instead fails CLOSED on the protected-by-default branches, because the harm there is a silent success under the maintainer's admin bypass. The denied shapes: @@ -73,12 +73,22 @@ only by GH_WRITE_GUARD_ALLOW_PRIMARY_CHECKOUT (a recognized falsy value such as "0"/"false" reads as not granted, not as any-non-empty-string-is-truthy), the same channel shape as GH_WRITE_GUARD_ALLOW. + 7. a shell wait carrying no bound: a `while`/`until` compound whose body calls `sleep`, with neither a + `timeout ` running the `sh -c`/`bash -c` wrapper that holds it nor an arithmetic guard in + its own condition. The placement matters: `timeout` takes a command and a loop keyword is not one. This is the harm behind a third incident, + where seven such loops outlived the subagents that started them, the run that dispatched those + subagents, and every worktree it had already retired, each forking a fresh `sleep` every half minute + against a condition that could never become true, until they were killed by PID by hand. A shell + started by a tool call runs in its own session, so it survives the agent that started it and nothing + reaps it. A heredoc body is data rather than a command line and is skipped, except one fed to a + shell, which is the script that shell runs. Run `gh-write-guard.py --selftest` to verify the decision matrix without Claude Code. """ import json import os +import posixpath import re import shlex import subprocess @@ -1610,6 +1620,547 @@ def _check_reply_resolve_helper(cmd, environ): return "allow", "" +# --- Rule 7: an unbounded shell wait ------------------------------------------------------------------ +_LOOP_KEYWORDS = ("while", "until") + + +def _opens_loop(toks, i): + """True if the token at index i opens a loop this rule judges. + + `while` and `until` always do. `for` does only in its arithmetic form, `for ((;;))`, which can + run forever exactly as `while true` can. A `for x in ` is bounded by that word list. + """ + if not _opens_command(toks, i): + return False + if toks[i] in _LOOP_KEYWORDS: + return True + return toks[i] == "for" and i + 1 < len(toks) and toks[i + 1].startswith("((") + + +# A loop keyword opens a loop only in command position, so the word appearing as an argument value is not one. +# These are the words a command can follow directly, beside the operator tokens `_is_separator` already recognizes. +_COMMAND_POSITION_WORDS = { + "do", + "then", + "else", + "elif", + "if", + "{", + "!", + "time", + # A prefix that runs the command after it, so `do command sleep 30` still sleeps. + "command", + "env", + "exec", + "nohup", + "setsid", + "stdbuf", + "sudo", + "nice", + "ionice", +} + +# The two bounds this rule reads as written into the loop's own condition. +# - the test-builtin form, `[ "$i" -lt 120 ]`. +# - the arithmetic form, `(( SECONDS < 600 ))`, where a shift is not a comparison and bounds nothing. +# Matched against the condition alone, so arithmetic in a sleeping body is not mistaken for a guard. +_BOUND_IN_CONDITION = re.compile(r"-(?:lt|le|gt|ge)\b|\(\(.*(?:(?)>(?!>)).*\)\)") + + +def _names_a_stream(target): + """True if the redirect target is a device or kernel file rather than a file that ends. + + Enumerating the streams that never end does not close, because each one has other spellings. + `/proc/self/fd/0` re-opens the same pipe `/dev/stdin` does, `/dev/full` reads like `/dev/zero`, + and a `.` segment defeats a literal compare of either. + The category is what the command text decides, so the whole of `/dev` and `/proc` reads as no + bound, and `/dev/null` is denied with them rather than carved out. + """ + # POSIX requires exactly two leading slashes to be preserved, so `//dev/zero` survives normpath. + return posixpath.normpath(re.sub(r"^/+", "/", target)).startswith(("/dev/", "/proc/")) + + +def _redirects_stdin(after_done): + """True if `after_done` binds descriptor 0 to a source that ends, which a `read` drains. + + Three things have to hold, and reading only the first accepted loops that never end. + The redirect has to bind descriptor 0, since `2&1 < f` arrives as five. + # Reading the token before the `<` as a descriptor read the previous redirect's target as one. + if ( + (tok.isdecimal() or tok.startswith("{")) + and i + 1 < len(after_done) + and _is_redir_op(after_done[i + 1]) + ): + fd = tok + i += 1 + tok = after_done[i] + if not _is_redir_op(tok): + i += 1 + continue + target = after_done[i + 1] if i + 1 < len(after_done) else "" + i += 2 + if "<" not in tok: + continue # an output redirect leaves descriptor 0 where it was + # A `{name}<` form names a variable rather than a literal and is never descriptor 0. + if fd.startswith("{"): + continue + # Compared as a number, since bash resolves `00<` to descriptor 0 while a text compare did not. + if fd and int(fd) != 0: + continue # a redirect on another descriptor leaves descriptor 0 where it was + # The last binding wins, since bash applies redirections in order and each replaces the last. + # Returning on the first let `< in.txt < /dev/zero` vouch for the stream that actually binds. + bound = not ("&" in tok or _names_a_stream(target)) + return bound + + +def _reads_its_input(cond, after_done): + """True if the loop's condition is a `read`, which ends the loop when the input is exhausted. + + `while read -r line; do ...; sleep 1; done < file` is bounded by its input rather than by a + clock, and throttling between iterations is the ordinary reason such a loop sleeps at all. + Three things are required. A leading `read`, after any `NAME=value` assignments, since a `read` + later in the condition is an argument to something else. That `read` naming no descriptor of its + own, since `read -u 3` draws on the one it names and not on the one the redirect bound. And an + input redirect on the loop itself, because a redirect names a source that ends while a pipe's + producer is unknown from the command text: `yes | while read line; do sleep 30; done` never + exhausts its input. A process + substitution is that same unknown producer behind a redirect, so `done < <(yes)` is no bound + either. Reading an unknown producer as unbounded costs a false deny on a piped + `find | while read`, which is the safe direction, and the bound such a loop needs is the + ordinary one. + """ + # A process substitution wears a redirect's clothes and is the same unknown producer a pipe is: + # `done < <(yes)` and `done < <(tail -f log)` never exhaust, so neither reads as a bound. + if any(t.startswith(("<(", ">(")) for t in after_done): + return False + if not _redirects_stdin(after_done): + return False + words = [t for t in cond if not _ENV_ASSIGN_RE.match(t)] + if not words or words[0].rsplit("/", 1)[-1] != "read": + return False + # `read -u 3` draws on the descriptor it names, so the redirect on descriptor 0 bounds nothing. + # The option can be clustered, as `read -ru 3` is, so the letter is looked for rather than the token. + return not any(t.startswith("-") and not t.startswith("--") and "u" in t for t in words[1:]) + + +# A `timeout` duration argument: bare seconds, or one carrying a GNU suffix. +# A zero duration is excluded, since GNU `timeout` documents 0 as disabling the timeout entirely. +_TIMEOUT_DURATION = re.compile(r"^(?!0+(?:\.0*)?[smhd]?$)\d+(?:\.\d+)?[smhd]?$") + +# The `timeout` options taking their value as a separate argument, which is therefore not the duration. +_TIMEOUT_VALUE_OPTS = {"-k", "--kill-after", "-s", "--signal"} + + +def _is_timeout_exe(tok): + """True if the token invokes `timeout`, path-qualified or `.exe`-suffixed like `_is_git_exe`.""" + base = tok.rsplit("/", 1)[-1].rsplit("\\", 1)[-1].lower() + # `gtimeout` is the Homebrew coreutils spelling, and the only GNU timeout a macOS host has. + return base in ("timeout", "timeout.exe", "gtimeout") + + +def _is_sleep_exe(tok): + """True if the token invokes `sleep`, recognized the way `_is_timeout_exe` recognizes timeout.""" + base = tok.rsplit("/", 1)[-1].rsplit("\\", 1)[-1].lower() + return base in ("sleep", "sleep.exe") + + +# Commands that name their arguments rather than running them, so a shell after one is text. +# `echo bash -c ''` runs no shell. +# The set is the exemption rather than the rule, so a name missing from it reads as executing. +# That scans a payload which may not need it, rather than skipping one that does. +_NAMES_ITS_ARGUMENTS = { + "echo", + "printf", + "ls", + "cat", + "grep", + "egrep", + "fgrep", + "rg", + "sed", + "awk", + "head", + "tail", + "wc", + "diff", + "man", + "which", + "type", + "basename", + "dirname", + "realpath", + "readlink", + "file", + "stat", + # These name a process rather than starting one, so `pkill sleep` runs no sleep. + "pkill", + "pgrep", + "killall", + "pidof", +} + + +def _runs_as_command(toks, w): + """True if the token at index w is the command its run executes, past any prefix or `timeout`. + + Whether a wrapper runs is a different question from whether it is bounded, and conflating them + let `timeout 0 bash -c ''` skip its payload entirely: the zero is no bound, so a + bound-shaped test refused to look inside a shell that really does run the loop. + """ + + if _opens_command(toks, w): + return True + start = w + while start > 0 and not _is_separator(toks[start - 1]): + start -= 1 + # A leading redirection and its target are not the run's command. + # Stopping the walk at one made `> log bash -c ''` read as not executed, and it really leaks. + while start < w and _is_redir_op(toks[start]): + start += 2 + if start >= w: + return True + # The run's head decides, asked the safe way round. + # A shell is executed unless its head names arguments rather than running them. + # Asking whether the head is a known launcher read `flock`, `xargs` and a bare redirection as not executing. + # Each of those runs the shell after it. + # A name missing from the set below therefore costs a scan rather than a skipped one. + head = toks[start].rsplit("/", 1)[-1].rsplit("\\", 1)[-1].lower().removesuffix(".exe") + return head not in _NAMES_ITS_ARGUMENTS + + +def _timeout_bounds_wrapper(toks, w): + """True if a `timeout ` runs the shell wrapper at index w, so its payload is bounded. + + The test is on the command run the wrapper sits in, the tokens back to the previous shell + operator, rather than on the tokens immediately before it. That run is bounded when it begins + with `timeout` and carries a duration, so `timeout -k 30 900 nice bash -c ''` reads as + bounded while `timeout 5 echo hi && bash -c ''` does not, the `timeout` there running + `echo` in a run of its own. + + A bound is read only here, never for a loop at the same level as the `timeout`. `timeout` takes a + command, and a `while`/`until` keyword is not one: `timeout 5 while true; do sleep 1; done` is a + syntax error rather than a bounded loop, so a `timeout` earlier on the line bounds nothing that + follows it. + """ + start = w + while start > 0 and not _is_shell_op(toks[start - 1]): + start -= 1 + # A run can open with a keyword or a command prefix, as `if timeout 600 bash -c ...` does. + while start < w and _is_command_prefix(toks[start]): + start += 1 + if start >= w or not _is_timeout_exe(toks[start]): + return False + # A fork between the `timeout` and the wrapper it runs puts the payload out of its reach. + # One written inside the payload is caught where that payload is read, on its own terms. + if _forks_out_of_reach(toks[start:w]): + return False + i = start + 1 + while i < w: + tok = toks[i] + if tok in _TIMEOUT_VALUE_OPTS: + i += 2 # the option's value is the next token, never the duration + continue + if tok.startswith("-"): + i += 1 # a flag, or a long option carrying its own value + continue + return bool(_TIMEOUT_DURATION.match(tok)) + return False + + +def _is_command_prefix(tok): + """True if the token runs the command after it, so what follows is still in command position. + + Path-stripped and assignment-aware for the same reason `_is_sleep_exe` is: `/usr/bin/env sleep` + and `FOO=1 sleep` are both a sleep, and reading only the bare spellings let each through. + """ + if _ENV_ASSIGN_RE.match(tok): + return True + base = tok.rsplit("/", 1)[-1].rsplit("\\", 1)[-1].lower().removesuffix(".exe") + return base in _COMMAND_POSITION_WORDS + + +def _opens_command(toks, i): + """True if the token at index i sits where a shell reads a command name rather than an argument.""" + if i == 0: + return True + prev = toks[i - 1] + return _is_separator(prev) or _is_command_prefix(prev) + + +def _sleeps(toks, _depth=0): + """True if `toks` runs a `sleep`, including one inside a `sh -c`/`bash -c` payload it carries.""" + if _depth > 4: + return False + for k, tok in enumerate(toks): + # `_runs_as_command` rather than `_opens_command`, since a launcher's options sit between it and what it runs. + # `env -i sleep 30` and `sudo -u ci sleep 30` both sleep. + # `grep -i sleep f` does not, its run's first command being no launcher. + if _is_sleep_exe(tok) and _runs_as_command(toks, k): + return True + if not _is_shell_wrapper_exe(tok): + continue + # The payload is read from its own token, since re-joining the token list dropped its quoting. + # `bash -c 'echo a; sleep 30'` rejoined to a command ending at the `;`, and the sleep was lost. + args, _ = _collect_arglist(toks, k + 1) + ci = next( + ( + x + for x, a in enumerate(args) + if a.startswith("-") and not a.startswith("--") and a.endswith("c") + ), + None, + ) + # Recursed rather than scanned, so the payload gets the same command-position test: a + # `pkill sleep` inside one names a sleep as an argument and does not run one. + if ( + ci is not None + and ci + 1 < len(args) + and _sleeps(_shell_tokens(args[ci + 1]), _depth + 1) + ): + return True + return False + + +def _loop_parts(toks, i): + """(condition tokens, body tokens, index of the closing `done`) for the loop at index i, or None. + + None means the loop is not closed in this command string, a shape this rule leaves alone rather + than denies, matching the precision-over-recall stance rules 1-3 take. + """ + n = len(toks) + do_at = next((j for j in range(i + 1, n) if toks[j] == "do" and _opens_command(toks, j)), None) + if do_at is None: + return None + depth = 0 + for j in range(do_at + 1, n): + if toks[j] == "do" and _opens_command(toks, j): + depth += 1 + elif toks[j] == "done" and _opens_command(toks, j): + if depth == 0: + return toks[i + 1 : do_at], toks[do_at + 1 : j], j + depth -= 1 + return None + + +def _forks_out_of_reach(toks): + """True if the command forks work that a `timeout` around it can no longer signal. + + Three shapes are recognized, each read over the whole command rather than tied to one loop. A + background operator leaves the shell free to exit, so the timeout's own child is gone before it + fires. `coproc` backgrounds with no operator at all. And `setsid` starts a session of its own, + which no signal to the timeout's process group reaches. + Recognized rather than exhaustive: a command can reach a new session through a launcher this + does not name, and the deny those cost is the one requirement 8 reports after the fact. + Which `&` backgrounds which compound needs a parse a token scan does not have, and four rounds + of narrowing that scan each closed the shapes they were shown and left the next one: a statement + between the loop and its group's closer, a `disown` before a `wait`, a subshell the sequencing + had already reaped. + A command that forks anything away is read as bounding nothing. That costs a false deny on + ` & wait`, which is a bound this rule cannot verify anyway. + """ + for tok in toks: + if tok == "coproc": + return True + if tok.rsplit("/", 1)[-1].rsplit("\\", 1)[-1].lower() in ("setsid", "setsid.exe"): + return True + if not _is_separator(tok): + continue + # The tokenizer fuses a run of operator characters, so one token can hold a closer and an `&`. + run = tok.strip() + i = 0 + while i < len(run): + # `&&` is a separator rather than a background operator. + if run[i : i + 2] == "&&": + i += 2 + continue + # `|&` is `2>&1 |` and `;&`/`;;&` fall through a `case` arm, so neither backgrounds. + if run[i] == "&" and (i == 0 or run[i - 1] not in "|;"): + return True + i += 1 + return False + + +def _unbounded_wait_loop(cmd, inherited_timeout=False, _depth=0): + """The first unbounded wait loop in `cmd`, as ` ` text, or None when none. + + A wait loop is a `while`/`until` compound whose body calls `sleep`. It passes when its own + condition carries an arithmetic guard, or when it sits inside a `sh -c`/`bash -c` payload that a + `timeout ` runs. A `timeout` never bounds a loop at its own level, since `timeout` + takes a command and a loop keyword is not one. A nested loop is judged on its own terms, so an + unbounded inner wait is denied even inside a bounded outer one, which is what it is: unbounded. + """ + if _depth > 4: + return None + toks = _shell_tokens(cmd) + forks_away = _forks_out_of_reach(toks) + for i, tok in enumerate(toks): + # A wrapper is read where its run executes it, covering `timeout 600 bash -c` and `nice bash -c`. + # Reading one anywhere denied `echo bash -c '...'`, which runs no shell at all. + if _is_shell_wrapper_exe(tok) and _runs_as_command(toks, i): + args, _ = _collect_arglist(toks, i + 1) + # `-c` may be clustered with other short options (`bash -lc`), the command string still the next argv token, the same reading `_embedded_wrapper_commands` gives it. + ci = next( + ( + x + for x, a in enumerate(args) + if a.startswith("-") and not a.startswith("--") and a.endswith("c") + ), + None, + ) + if ci is not None and ci + 1 < len(args): + local = _timeout_bounds_wrapper(toks, i) + # A fork anywhere in this command puts the payload out of an inherited timeout's reach. + # `timeout 600 bash -c "bash -c '' &"` outlives the shell that timeout controls. + backgrounded = forks_away + bounded = (inherited_timeout and not backgrounded) or local + inner = _unbounded_wait_loop(args[ci + 1], bounded, _depth + 1) + if inner is not None: + return inner + elif _opens_loop(toks, i): + parts = _loop_parts(toks, i) + if parts is None: + continue + cond, body, done_at = parts + # `while sleep 30; do ...; done` is the standard poll-forever idiom. + # Its condition sleeps as surely as a body does, and a sleep handed to `sh -c` is still one. + sleeps = _sleeps(body) or _sleeps(cond) + # A backgrounded loop is not bounded by a `timeout` around the shell that started it. + # The shell forks the loop and exits, so `timeout`'s own child is gone and it signals nothing. + # Measured: the same leak as having written no bound at all. + backgrounded = forks_away + bounded = (inherited_timeout and not backgrounded) or _reads_its_input( + cond, toks[done_at + 1 :] + ) + if sleeps and not bounded and not _BOUND_IN_CONDITION.search(" ".join(cond)): + # The trailing separator is the `;` before `do`, which is punctuation rather than part of the condition being quoted back. + quoted = cond[:-1] if cond and _is_separator(cond[-1]) else cond + return " ".join([tok] + quoted) + return None + + +# A heredoc tag: the word after a `<<` redirection, whose body runs to a line holding it alone. +_HEREDOC_TAG = re.compile(r"[A-Za-z_][A-Za-z0-9_.\-]*$") + + +def _ends_pipeline(tok): + """True if the token ends a pipeline. A `|` continues one, every other separator ends it.""" + return _is_separator(tok) and tok != "|" + + +def _heredoc_opener(line): + """(tag, is_dash_form, feeds_a_shell) for a heredoc `line` opens, or None. + + Read from tokens rather than from the raw text, so a `<<` inside a quoted argument is the + text it is: a commit message explaining the `<< EOF` form opened one, and the strip then + deleted every command after it. A `<<<` herestring is a token of its own and not this, and a + line carrying arithmetic is skipped outright, since `$(( 1 << n ))` tokenizes to a bare `<<` + that no token test can tell from a redirection. Skipping there costs a false deny on a line + holding both, which is vanishingly rare, where reading it wrong drops real commands. + """ + toks = _shell_tokens(line) + if any("((" in t for t in toks): + return None + for k, tok in enumerate(toks): + if tok != "<<" or k + 1 >= len(toks): + continue + nxt = toks[k + 1] + dash = nxt.startswith("-") + # A bare `-` token is left unread rather than treated as the dash form. + # `<<- EOF` and `<< - EOF` tokenize identically, and bash reads the second one's delimiter as `-`. + # Reading both as tag `EOF` strips past a real `-` terminator and drops the commands after it. + # Not reading either costs a false deny on a document written through the spaced dash form. + # That is the safe direction of the two. + tag = nxt[1:] if dash else nxt + if not _HEREDOC_TAG.fullmatch(tag): + continue + # Whether a shell reads this body is a question about the heredoc's whole pipeline. + # `cat < doc.md < 0 and not _ends_pipeline(toks[start - 1]): + start -= 1 + end = k + while end < len(toks) and not _ends_pipeline(toks[end]): + end += 1 + return tag, dash, any(_is_shell_wrapper_exe(t) for t in toks[start:end]) + return None + + +def _strip_heredoc_bodies(cmd): + """`cmd` with every heredoc body removed, except one fed to a shell, which really is a script. + + A heredoc body is data rather than a command line, so `cat > notes.md < bash -c ''`, since `timeout` takes a command and a loop " + "keyword is not one. The other accepted bound is " + "an arithmetic guard in the loop's own condition, such as `(( SECONDS < end ))` or " + '`[ "$i" -lt 120 ]`. Neither form tells a condition that is failing from one that is merely ' + "unmet, so run the condition once in the foreground first and say so in what the wait " + "reports. A `break` in the body is not read as a bound here, since only the command text is " + "judged and a `break` says nothing about when it is reached. Prefer the mechanism that " + "already signals: a dispatched task reports its own " + "completion, so polling its output file is a second and unreliable channel for an answer " + 'already on its way. See AGENTS.md "Delegation".' + ) + + def classify( cmd, cwd=None, @@ -1652,6 +2203,10 @@ def classify( dec, reason = _check_primary_checkout_mutation( cmd, cwd, environ, primary_checkout_lookup, ref_resolver, config_lookup ) + if dec == "deny": + return dec, reason + # Rule 7 covers an unbounded shell wait, which is neither a GitHub write nor a git operation, so it is checked here too, before the gh-write gate below would skip past it. + dec, reason = _check_unbounded_wait(cmd) if dec == "deny": return dec, reason @@ -3164,6 +3719,518 @@ def classify( ] +# Rule 7: an unbounded shell wait. (command, expected_decision, label) +_WAIT_CASES = [ + ( + 'until [ -s "/tmp/t/tasks/abc.output" ]; do sleep 30; done', + "deny", + "the incident: a poll on a file the awaited process may never write", + ), + ( + "while ! gh pr checks 5 | grep -q COMPLETED; do sleep 60; done", + "deny", + "a review wait whose condition can stay false forever", + ), + ("while true; do sleep 30; done", "deny", "the shape with no condition to become true at all"), + ( + "bash -c 'until [ -f /tmp/done ]; do sleep 10; done'", + "deny", + "a wrapper payload is read the same as a bare command line", + ), + ( + "until [ -f /tmp/done ]; do sleep 5; done &", + "deny", + "backgrounding the loop is what makes it outlive the turn, not what excuses it", + ), + ( + "timeout --help bash -c 'until [ -f x ]; do sleep 1; done'", + "deny", + "a timeout carrying no duration is not a bound", + ), + ( + "timeout 5 echo hi && until [ -f x ]; do sleep 5; done", + "deny", + "a timeout at the loop's own level bounds nothing, a loop keyword being no command to run", + ), + ( + "timeout 5 echo hi && bash -c 'until [ -f x ]; do sleep 5; done'", + "deny", + "and a timeout running something else does not reach a wrapper later on the line", + ), + ( + "timeout 600 bash -c \"bash -c 'until [ -f x ]; do sleep 5; done'\"", + "allow", + "a real bound is inherited through a nested wrapper", + ), + ( + "timeout 0 bash -c 'until [ -f x ]; do sleep 30; done'", + "deny", + "GNU timeout documents a zero duration as disabling the timeout, so it is not a bound", + ), + ( + "timeout 600 bash -c 'until [ -f x ]; do sleep 30; done &'", + "deny", + "a backgrounded loop outlives the shell the timeout bounds, so the timeout bounds nothing", + ), + ( + "timeout 600 bash -c 'until [ -f x ]; do sleep 30; done > /tmp/log &'", + "deny", + "a redirection before the ampersand does not stop it backgrounding the loop", + ), + ( + "timeout 600 bash -c 'until [ -f x ]; do sleep 30; done 2>/dev/null &'", + "deny", + "nor does one carrying its file descriptor as a token of its own", + ), + ( + "timeout 600 bash -c 'until [ -f x ]; do sleep 30; done >> a 2>&1 &'", + "deny", + "nor two of them together", + ), + ( + "timeout 600 bash -c 'until [ -f x ]; do sleep 30; done 2>&1'", + "allow", + "while a redirection with no ampersand after it backgrounds nothing", + ), + ( + "while read l; do sleep 1; done < f &", + "allow", + "a loop bounded by its input stays bounded backgrounded, since that bound needs no signal", + ), + ( + "gtimeout 60 bash -c 'until [ -f x ]; do sleep 5; done'", + "allow", + "gtimeout is the only GNU timeout a macOS host has", + ), + ( + "sudo timeout 60 bash -c 'until [ -f x ]; do sleep 5; done'", + "allow", + "a privilege prefix does not hide the timeout behind it", + ), + ( + "TMPDIR=/tmp timeout 60 bash -c 'until [ -f x ]; do sleep 5; done'", + "allow", + "nor does an assignment prefix", + ), + ( + "until [ -f x ]; do /usr/bin/env sleep 1; done", + "deny", + "a prefix is recognized path-qualified, the way the exe helpers already recognize one", + ), + ( + "until [ -f x ]; do FOO=1 sleep 1; done", + "deny", + "and an assignment before the sleep is not an argument to it", + ), + ( + 'while IFS= read -r pr; do gh pr view "$pr"; sleep 2; done < prs.txt', + "allow", + "a loop reading its input ends when the input does, and throttling it is ordinary work", + ), + ( + "while grep -q read file; do sleep 5; done", + "deny", + "while a read named later in the condition is an argument and bounds nothing", + ), + ( + "for ((;;)); do sleep 30; done", + "deny", + "the arithmetic for runs forever exactly as while true does", + ), + ( + "for (( i=0; i<10; i++ )); do sleep 1; done", + "allow", + "and carries its own guard when it has one", + ), + ( + "grep -q x <<< foo\nuntil [ -f y ]; do sleep 30; done", + "deny", + "a herestring is not a heredoc, and reading one as one deleted the command after it", + ), + ( + "echo $((a< d.md << EOF\nuntil [ -f x ]; do sleep 5; done\nEOF", + "allow", + "a space between the redirection and its tag still opens a heredoc", + ), + ( + "bash -c 'echo hi' && cat > docs/waits.md <<'EOF'\nuntil [ -f x ]; do sleep 5; done\nEOF", + "allow", + "whether a shell reads the body is the redirection's own command, not the line mentioning one", + ), + ( + "while sleep 30; do gh pr checks 5 | grep -q COMPLETED && break; done", + "deny", + "the poll-forever idiom sleeps in its condition, which is a sleep like any other", + ), + ( + "while true; do bash -c 'sleep 30'; done", + "deny", + "and a sleep the body hands to a wrapper is still the body sleeping", + ), + ( + "while true; do bash -c 'echo a; sleep 30'; done", + "deny", + "wherever in that payload it sits, which re-joining the tokens once lost", + ), + ( + "while true; do bash -c 'pkill sleep'; done", + "allow", + "while a sleep named as an argument to something else runs none", + ), + ( + "cat <<'EOF' | bash\nuntil [ -f x ]; do sleep 30; done\nEOF", + "deny", + "a heredoc piped into a shell is a script that shell runs, whatever owns the redirection", + ), + ( + "nice -n 10 bash <<'EOF'\nuntil [ -f x ]; do sleep 30; done\nEOF", + "deny", + "and a prefix before that shell does not hide it", + ), + ( + "cat << - EOF\ndoc line\n-\nuntil [ -f x ]; do sleep 30; done\nEOF", + "deny", + "a bare dash token is left unread, since bash reads that spelling's delimiter as the dash", + ), + ( + "timeout 600 until [ -f x ]; do sleep 30; done", + "allow", + "bash rejects this before it runs, so it is a syntax error rather than a wait to judge, and the denial no longer names it", + ), + ( + "timeout -k 30 900 bash -c 'until [ -f x ]; do sleep 60; done'", + "allow", + "an option taking a separate value still leaves the duration findable", + ), + ( + "timeout 900 nice bash -c 'until [ -f x ]; do sleep 60; done'", + "allow", + "and a command prefix between the timeout and the shell does not hide it", + ), + ( + "if timeout 600 bash -c 'until [ -f x ]; do sleep 30; done'; then echo MET; fi", + "allow", + "a run opening with a keyword is still that run", + ), + ( + "until [ -f /tmp/flag ]; do echo done; sleep 30; done", + "deny", + "the word done inside the body does not close the loop before its sleep is read", + ), + ( + "until [ -f x ]; do command sleep 1; done", + "deny", + "a sleep behind a command prefix is still a sleep", + ), + ( + "cat > notes.md <<'END-DOC'\nuntil [ -f x ]; do sleep 5; done\nEND-DOC", + "allow", + "a hyphenated heredoc tag is a heredoc, so a document using one is written rather than denied", + ), + ( + "cat > f <<'EOF'\n EOF\nwhile true; do sleep 1; done\nEOF", + "allow", + "an indented line reading as the tag does not end a plain heredoc, so the rest stays data", + ), + ( + 'i=0; while [ "$i" -lt 5 ]; do until [ -f x ]; do sleep 1; done; i=$((i+1)); done', + "deny", + "an unbounded inner wait is unbounded however bounded the loop around it is", + ), + ( + "until [ -f x ]; do /bin/sleep 5; done", + "deny", + "a path-qualified sleep is the same sleep", + ), + ( + "bash <<'EOF'\nuntil [ -f x ]; do sleep 5; done\nEOF", + "deny", + "a heredoc fed to a shell is the script that shell runs", + ), + ( + "timeout 600 bash -c 'until [ -f /tmp/done ]; do sleep 30; done'", + "allow", + "a timeout wrapper is the bound, inherited into the payload it wraps", + ), + ( + "timeout 10m bash -c 'while ! test -f x; do sleep 2; done'", + "allow", + "a suffixed duration is a duration", + ), + ( + 'i=0; while [ "$i" -lt 120 ] && ! curl -sf http://x; do sleep 5; i=$((i+1)); done', + "allow", + "a counter the condition reads is the other bound", + ), + ( + "while (( SECONDS < 600 )); do sleep 10; done", + "allow", + "the arithmetic form of that same guard", + ), + ( + "while (( 1 << 1 )); do sleep 1; done", + "deny", + "a shift inside the arithmetic form is not a comparison and bounds nothing", + ), + ( + "echo bash -c 'while true; do sleep 1; done'", + "allow", + "a shell named as an argument to something else runs no payload", + ), + ( + "> /tmp/log bash -c 'until [ -f x ]; do sleep 30; done'", + "deny", + "a leading redirection is not the run's command, and reading it as one skipped the payload", + ), + ( + "flock /tmp/l bash -c 'until [ -f x ]; do sleep 30; done'", + "deny", + "nor is a launcher this rule does not know by name, which is why the exemption is the set", + ), + ( + "xargs bash -c 'until [ -f x ]; do sleep 30; done'", + "deny", + "and the same for one that reads its arguments from a pipe", + ), + ( + "while true; do env -i sleep 30; done", + "deny", + "a launcher's own options sit between it and the sleep it runs", + ), + ( + "yes | while read line; do sleep 30; done", + "deny", + "a pipe's producer is unknown from the command text, so a read on one is no bound", + ), + ( + "while read l; do sleep 30; done < <(yes)", + "deny", + "and a process substitution is that same producer behind a redirect", + ), + ( + "yes | while read line; do sleep 30; done 2&1 < in.txt", + "allow", + "while an earlier redirect's target is not this one's descriptor", + ), + ( + "while read l; do sleep 30; done > 2 < in.txt", + "allow", + "which holds when that target is itself a digit", + ), + ( + "while read l; do sleep 1; done \u00b2< f", + "allow", + "and a superscript digit reaches a verdict rather than raising, which failed every rule open", + ), + ( + "while true; do grep -i sleep f; done", + "allow", + "while a command that merely names sleep runs none", + ), + ( + "sudo -u ci bash -c 'until [ -f x ]; do sleep 30; done'", + "deny", + "while a prefix runs what follows it, whatever options sit between", + ), + ( + "timeout 0 bash -c 'until [ -f x ]; do sleep 30; done'", + "deny", + "whether a wrapper runs is a separate question from whether it is bounded", + ), + ( + "end=$((SECONDS + 600))\nwhile (( SECONDS < end )) && ! [ -f x ]; do sleep 30; done\nif (( SECONDS < end )); then echo MET; else echo 'NOT MET after 600s'; fi", + "allow", + "the arithmetic guard the denial itself names, which must not deny in turn", + ), + ( + "if timeout 600 bash -c 'until [ -f x ]; do sleep 30; done'; then echo MET; else echo 'NOT MET'; fi\n", + "allow", + "the timeout wrapper stays accepted wherever a single-command wait fits it", + ), + ( + 'while read -r line; do echo "$line"; done < f', + "allow", + "a loop that does not sleep is no wait", + ), + ( + "for i in $(seq 1 60); do sleep 5; done", + "allow", + "a for loop is bounded by its own word list", + ), + ("sleep 30", "allow", "a sleep outside a loop ends on its own"), + ( + 'echo "while true; do sleep 1; done"', + "allow", + "the shape named inside a quoted value is text, not a loop", + ), + ( + "cat > d.md <<'EOF'\nuntil [ -f x ]; do sleep 5; done\nEOF", + "allow", + "a heredoc body written to a file is data, which is how this rule gets documented at all", + ), +] + + def _selftest(): # A deterministic offline run, pinning origin to ptr727/PlexCleaner, the incident repo, so the cross-origin case resolves without touching a real checkout. # The gh-write cases inject empty rules and a feature current-branch so no case reaches the live branch-rules query. @@ -3184,6 +4251,19 @@ def _selftest(): if got != want: ok = False print(f" {mark} [{got:5}] want={want:5} {label}") + for cmd, want, label in _WAIT_CASES: + got, _ = classify( + cmd, + origin=origin, + current_branch="feature/x", + rules_lookup=lambda br: set(), + environ={}, + primary_checkout_lookup=lambda d: False, + ) + mark = "ok " if got == want else "FAIL" + if got != want: + ok = False + print(f" {mark} [{got:5}] want={want:5} {label}") for cmd, env, want, label in _SCOPE_CASES + _SCOPE_CASES_MORE: got, _ = classify( cmd, diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index e2adcaf29..1d8a678d9 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 -"""Install the agent write-safety kit for the current user account. Cross-platform, idempotent. +"""Install the agent host-safety kit for the current user account. Cross-platform, idempotent. -Deploys the PreToolUse hook, registers it in the user settings.json, merges the permission rules this -kit owns into the same file, adds the safety rules to the user CLAUDE.md (marker-delimited so re-runs -update in place), and self-tests the hook before registering it. +Deploys the PreToolUse hook and the SessionEnd stray-process sweep, registers both in the user +settings.json, merges the permission rules this kit owns into the same file, adds the safety rules to +the user CLAUDE.md (marker-delimited so re-runs update in place), and self-tests each hook before +registering it. The bash and PowerShell wrappers both call this, so every OS runs one tested code path. Every run records a stamp at ~/.claude/agent-safety-stamp.json naming the machine, what was @@ -31,6 +32,23 @@ HERE = pathlib.Path(__file__).resolve().parent +# Each hook's file name, and the substring identifying its registration in settings.json. +# Named once, since a registration written under one spelling and searched for under another is reported absent forever. +# The guard was spelled by hand on the search side and by position on the deploy side, which is that same drift one rename away. +GUARD_NAME = "gh-write-guard.py" +GUARD_STEM = "gh-write-guard" +SWEEP_NAME = "stray-process-sweep.py" +SWEEP_STEM = "stray-process-sweep" + +# The hook files this kit copies into ~/.claude/hooks, in deploy order. +# Named here rather than spelled inside `main`, since a test scraping `main` for a literal path goes silent when the copy is refactored. +# That silence reads as a pass. +DEPLOYED_HOOKS = (GUARD_NAME, SWEEP_NAME) + +# A SessionEnd hook's own budget is 1.5 seconds, raised to the highest per-hook timeout the settings declare. +# The sweep reads one process table, so this is headroom for a loaded machine rather than a duration it uses. +SWEEP_TIMEOUT_SECONDS = 10 + # The stamp's own format version, separate from the content it describes. # A reader that predates a field needs to know the shape changed rather than infer it from a missing key. STAMP_VERSION = 1 @@ -49,13 +67,66 @@ # Written out, this list and the block list drifted apart silently and the digest stopped covering a file. # The digest is taken over these rather than over the commit, since it is the content that runs. # A clean commit and a dirty checkout install different bytes while reporting the same SHA. -PAYLOAD_FILES = ("gh-write-guard.py",) + tuple(filename for _, filename in CLAUDE_MD_BLOCKS) +PAYLOAD_FILES = DEPLOYED_HOOKS + tuple(filename for _, filename in CLAUDE_MD_BLOCKS) # Distinguishes an absent key from one holding an explicit null, which `dict.get` reports alike. # The two need different answers, since a gap is filled and a null is a settings error. MISSING = object() +def hook_command(launcher, path): + """The `command` string a registered hook carries, spelled once for writer and reader alike.""" + return f'"{launcher}" "{path}"' + + +def runs_hook(command, path): + """Whether `command` names the hook deployed at `path`, as its own argument. + + The path is compared and the launcher is not. Matching the name alone let an unrelated + `echo stray-process-sweep` count as a registration, while matching the whole command string + reported a working machine stale, since `hook_launcher()` resolves at check time and a machine + installed under a different PATH carries the other spelling. The path is what the installer + writes and never drifts, so it is the half worth comparing. + + The quoting around it is not compared either. This installer writes the path in double quotes, + and a registration written by hand or through the `/hooks` UI runs the same file bare or in + single quotes, so requiring one spelling reported those as naming a hook they do not run. + + Whether the command then runs it is not decidable from the string: `echo ""` names the + deployed hook and executes nothing. What this rules out is the decoy that names the hook and + not its deployed path, which is the shape a stale registration actually takes. + """ + text = str(command) + spellings = {str(path)} + home = str(pathlib.Path.home()) + if str(path).startswith(home): + # `~` and `$HOME` are how a person writes this path, and both resolve to the deployed file. + spellings.add("~" + str(path)[len(home) :]) + spellings.add("$HOME" + str(path)[len(home) :]) + # Forward slashes are accepted on Windows and are the spelling a JSON file usually carries. + spellings.update(sp.replace("\\", "/") for sp in set(spellings)) + return any( + re.search(rf"(?:^|[\s\"'(]){re.escape(sp)}(?=$|[\s\"')|&;])", text) for sp in spellings + ) + + +def matcher_sees_bash(matcher): + """Whether a PreToolUse matcher group receives a Bash call. + + An absent or empty matcher runs on every tool and `*` is the all-tools spelling, so neither is + a defect. A matcher is otherwise a regular expression, which makes `Bash|Task` as good as + `Bash`. Requiring the exact string reported all three of those working shapes as broken. + """ + if matcher is None or matcher in ("", "*"): + return True + if not isinstance(matcher, str): + return False + try: + return re.fullmatch(matcher, "Bash") is not None + except re.error: + return False + + def owns(entry, prefix): """Whether an allow rule names the script the prefix identifies, rather than a longer path. @@ -183,7 +254,7 @@ def payload_digest(): Fixed order because a set of files has none, and a digest that depends on directory listing order reports drift on a machine where nothing changed. The order matches the one - `installed_digest` reads, so the two are directly comparable: the hook, then each block. + `installed_digest` reads, so the two are directly comparable: the guard, the sweep, then each block. """ h = hashlib.sha256() for name in PAYLOAD_FILES: @@ -245,12 +316,15 @@ def installed_digest(claude_home): Line endings are normalized first: CLAUDE.md keeps whatever endings it had, and a machine that holds identical text with CRLF is current rather than drifted. """ - hook = claude_home / "hooks" / "gh-write-guard.py" + # Read from `DEPLOYED_HOOKS` rather than by name, since naming them here is the drift that constant closes. + # A hook added to the deploy list and not to this one installs and is never covered by the currentness digest. + deployed = [claude_home / "hooks" / name for name in DEPLOYED_HOOKS] claude_md = claude_home / "CLAUDE.md" - if not hook.is_file() or not claude_md.is_file(): + if not all(f.is_file() for f in deployed) or not claude_md.is_file(): return None h = hashlib.sha256() - h.update(normalized(hook.read_bytes())) + for f in deployed: + h.update(normalized(f.read_bytes())) text = normalized(claude_md.read_text(encoding="utf-8", errors="replace")) for marker in BLOCK_MARKERS: found = re.search( @@ -329,17 +403,71 @@ def registration_problems(claude_home): if not isinstance(data, dict): return ["settings.json does not hold an object at its root"] out = [] - groups = ( - data.get("hooks", {}).get("PreToolUse") if isinstance(data.get("hooks"), dict) else None - ) + + def report(note): + """Append `note` once, since one defect a group carries is not two defects when it holds two entries.""" + if note not in out: + out.append(note) + + def event_groups(event): + """The matcher groups under `event`, or None when the settings shape cannot be read. + + A wrong shape is reported as itself rather than counted as zero. Iterating a dict yields + its keys and a string yields its characters, so the loops below would find no registration + and report the hook as absent, which sends a reader to the wrong fix. + """ + hooks = data.get("hooks") + if hooks is None: + return [] + if not isinstance(hooks, dict): + # Reported once rather than per event, since both events read the same wrong key. + report( + f"settings.json has `hooks` as {type(hooks).__name__} where an object is required, " + "so no registration can be read" + ) + return None + groups = hooks.get(event) + if groups is None: + return [] + if not isinstance(groups, list): + out.append( + f"settings.json has `hooks.{event}` as {type(groups).__name__} where a list is " + f"required, so the {event} registration cannot be read" + ) + return None + return groups + + groups = event_groups("PreToolUse") + # Counted apart from the registrations, since an entry with a problem is still an entry. + # Counting only the sound ones added "the guard never runs" under every problem reported here. + # That line is false, and it sends a reader to the wrong fix. + named = 0 registered = 0 + guard_path = claude_home / "hooks" / GUARD_NAME for group in groups or []: if not isinstance(group, dict): continue for hook in group.get("hooks") or []: - if isinstance(hook, dict) and "gh-write-guard" in str(hook.get("command", "")): - registered += 1 - if registered == 0: + if not isinstance(hook, dict) or GUARD_STEM not in str(hook.get("command", "")): + continue + named += 1 + if not runs_hook(hook.get("command"), guard_path) or hook.get("type") != "command": + out.append( + "a PreToolUse entry names the guard but does not run the deployed one " + f"({hook.get('type')!r} running {hook.get('command')!r})" + ) + continue + if not matcher_sees_bash(group.get("matcher")): + report( + f"a PreToolUse group registers the guard under matcher " + f"{group.get('matcher')!r}, which no Bash call matches, so that group never " + "fires" + ) + continue + registered += 1 + if groups is None: + pass # the shape error is already reported, and a count from it would be meaningless + elif named == 0: out.append( "the PreToolUse hook is not registered in settings.json, so the guard never runs" ) @@ -347,6 +475,57 @@ def registration_problems(claude_home): out.append( f"the PreToolUse hook is registered {registered} times, so it runs more than once" ) + ends = event_groups("SessionEnd") + sweeps_named = 0 + swept = 0 + for group in ends or []: + if not isinstance(group, dict): + continue + sweep_path = claude_home / "hooks" / SWEEP_NAME + for hook in group.get("hooks") or []: + if not isinstance(hook, dict) or SWEEP_STEM not in str(hook.get("command", "")): + continue + sweeps_named += 1 + if not runs_hook(hook.get("command"), sweep_path) or hook.get("type") != "command": + out.append( + "a SessionEnd entry names the sweep but does not run the deployed one " + f"({hook.get('type')!r} running {hook.get('command')!r})" + ) + continue + # A longer budget than this installer writes is not a defect, so only a shorter one is reported. + # The event's own default is 1.5s, which is what the sweep needs more than. + timeout = hook.get("timeout") + too_short = isinstance(timeout, bool) or not isinstance(timeout, (int, float)) + if not too_short: + too_short = timeout < SWEEP_TIMEOUT_SECONDS + if too_short: + carries = ( + "carries no timeout" + if "timeout" not in hook + else f"carries timeout {timeout!r}" + ) + out.append( + f"the SessionEnd sweep {carries} where this installer writes " + f"{SWEEP_TIMEOUT_SECONDS}, too little for a `ps` on a loaded machine" + ) + continue + swept += 1 + # A SessionEnd matcher filters by exit reason, so a sweep under one runs on that reason alone. + # Counting it as registered reports a machine current while the sweep never fires on an ordinary exit. + if "matcher" in group: + report( + f"the SessionEnd sweep is registered under a matcher " + f"({group['matcher']!r}), so it runs on that exit reason alone" + ) + if ends is None: + pass # likewise reported as a shape error above + elif sweeps_named == 0: + out.append( + "the SessionEnd sweep is not registered in settings.json, so a surviving shell is " + "never reported" + ) + elif swept > 1: + out.append(f"the SessionEnd sweep is registered {swept} times, so it runs more than once") allow = ( data.get("permissions", {}).get("allow") if isinstance(data.get("permissions"), dict) @@ -457,7 +636,7 @@ def report(claude_home): def main(): parser = argparse.ArgumentParser( - description="Install the agent write-safety kit, or report whether this machine is current." + description="Install the agent host-safety kit, or report whether this machine is current." ) parser.add_argument( "--report", @@ -482,7 +661,8 @@ def main(): else pathlib.Path.home() / ".claude" ) hooks_dir = claude_home / "hooks" - hook_dst = hooks_dir / "gh-write-guard.py" + hook_dst = hooks_dir / GUARD_NAME + sweep_dst = hooks_dir / SWEEP_NAME settings = claude_home / "settings.json" claude_md = claude_home / "CLAUDE.md" @@ -490,34 +670,66 @@ def main(): if args.report: return report(claude_home) - print(f"Installing agent write-safety kit into: {claude_home}") + print(f"Installing agent host-safety kit into: {claude_home}") hooks_dir.mkdir(parents=True, exist_ok=True) - # 1. Deploy the hook, then self-test it before wiring anything up. - shutil.copyfile(HERE / "gh-write-guard.py", hook_dst) - try: - os.chmod(hook_dst, 0o755) - except OSError: - pass - print(f" hook -> {hook_dst}") - r = subprocess.run( - [sys.executable, str(hook_dst), "--selftest"], - capture_output=True, - text=True, - encoding="utf-8", - check=False, - ) - if r.returncode != 0: - sys.stderr.write( - "Hook self-test FAILED; aborting before registration.\n" + r.stdout + r.stderr + # 1. Stage every hook beside its live path, self-test each staged copy, and only then replace. + # Copying onto the live path first and testing afterwards left a failed self-test's broken copy installed. + # The existing registration still pointed at it, so an install that refused to register disabled the guard. + # Named per process, since two installs sharing one staged path clobber each other's copy. + # A kill between staging and the replace still leaves one behind, which nothing here can prevent. + staged = [] + for src_name in DEPLOYED_HOOKS: + tmp = hooks_dir / f"{src_name}.{os.getpid()}.staged" + staged.append((src_name, tmp)) + try: + shutil.copyfile(HERE / src_name, tmp) + except OSError as e: + for _n, f in staged: + f.unlink(missing_ok=True) + sys.stderr.write(f"staging {src_name} failed ({e}); nothing was replaced.\n") + return 1 + try: + os.chmod(tmp, 0o755) + except OSError: + pass + r = subprocess.run( + [sys.executable, str(tmp), "--selftest"], + capture_output=True, + text=True, + encoding="utf-8", + check=False, ) - return 1 - print(" hook self-test: PASS") + if r.returncode != 0: + for _n, f in staged: + f.unlink(missing_ok=True) + sys.stderr.write( + f"{src_name} self-test FAILED; nothing was replaced.\n" + r.stdout + r.stderr + ) + return 1 + print(f" {src_name} self-test: PASS") + for done_count, (src_name, tmp) in enumerate(staged): + dst = hooks_dir / src_name + # `os.replace` is atomic on the same filesystem, so a live hook is never a partial file. + # It can still fail as a whole, most plausibly on Windows where another process holds the destination open. + # Each live hook is intact either way, and what needs saying is that some were replaced and some were not. + try: + os.replace(tmp, dst) + except OSError as e: + for _n, f in staged: + f.unlink(missing_ok=True) + sys.stderr.write( + f"replacing {dst} failed ({e}). {done_count} of {len(staged)} hooks were replaced, " + "the rest are unchanged, nothing was registered, and the staged copies are removed. " + "Re-run the installer.\n" + ) + return 1 + print(f" hook -> {dst}") # 2. Register the hook command in settings.json under exactly one PreToolUse/Bash group. launcher = hook_launcher() # Quote the launcher too: the sys.executable fallback can contain spaces (e.g. C:\Program Files\...). - hook_cmd = f'"{launcher}" "{hook_dst}"' + hook_cmd = hook_command(launcher, hook_dst) # Read into a variable rather than twice off disk, once to test for content and once to parse. # Two reads can also disagree, since another process may write between them. data = {} @@ -554,6 +766,7 @@ def reject(where, held, want): for path, want in ( ("hooks", dict), ("hooks/PreToolUse", list), + ("hooks/SessionEnd", list), ("permissions", dict), ("permissions/allow", list), ): @@ -566,18 +779,20 @@ def reject(where, held, want): # A list of the right type can still hold the wrong elements. # The registration below reads each group as an object, and each group's `hooks` as a list it appends to. - groups = at(data, "hooks/PreToolUse") - if groups is not MISSING: + for event in ("PreToolUse", "SessionEnd"): + groups = at(data, f"hooks/{event}") + if groups is MISSING: + continue for i, g in enumerate(groups): if not isinstance(g, dict): - reject(f"hooks.PreToolUse[{i}]", g, dict) + reject(f"hooks.{event}[{i}]", g, dict) return 1 if "hooks" in g and not isinstance(g["hooks"], list): - reject(f"hooks.PreToolUse[{i}].hooks", g["hooks"], list) + reject(f"hooks.{event}[{i}].hooks", g["hooks"], list) return 1 for j, h in enumerate(g.get("hooks") or []): if not isinstance(h, dict): - reject(f"hooks.PreToolUse[{i}].hooks[{j}]", h, dict) + reject(f"hooks.{event}[{i}].hooks[{j}]", h, dict) return 1 pre = data.setdefault("hooks", {}).setdefault("PreToolUse", []) @@ -587,9 +802,7 @@ def reject(where, held, want): for g in pre: hooks_list = g.get("hooks") if isinstance(hooks_list, list): - hooks_list[:] = [ - h for h in hooks_list if "gh-write-guard" not in str(h.get("command", "")) - ] + hooks_list[:] = [h for h in hooks_list if GUARD_STEM not in str(h.get("command", ""))] group = next((g for g in pre if g.get("matcher") == "Bash"), None) if group is None: group = {"matcher": "Bash", "hooks": []} @@ -597,6 +810,26 @@ def reject(where, held, want): group.setdefault("hooks", []).append({"type": "command", "command": hook_cmd}) done = ["PreToolUse/Bash hook registered"] + # Step 2b registers the SessionEnd sweep the same strip-then-register way as the guard above. + # The group carries no matcher, so it fires on every exit reason rather than on one. + ends = data.setdefault("hooks", {}).setdefault("SessionEnd", []) + for g in ends: + hooks_list = g.get("hooks") + if isinstance(hooks_list, list): + hooks_list[:] = [h for h in hooks_list if SWEEP_STEM not in str(h.get("command", ""))] + end_group = next((g for g in ends if "matcher" not in g), None) + if end_group is None: + end_group = {"hooks": []} + ends.append(end_group) + end_group.setdefault("hooks", []).append( + { + "type": "command", + "command": hook_command(launcher, sweep_dst), + "timeout": SWEEP_TIMEOUT_SECONDS, + } + ) + done.append("SessionEnd sweep registered") + # 3. Permission rules, merged under the prefixes this installer owns. # The strip-then-register shape is the hook registration's above, applied to a flat list. # Written in the same pass as the hook, so the file is read once and written once. diff --git a/host-setup/agent-safety/claude/stray-process-sweep.py b/host-setup/agent-safety/claude/stray-process-sweep.py new file mode 100755 index 000000000..ab1890eab --- /dev/null +++ b/host-setup/agent-safety/claude/stray-process-sweep.py @@ -0,0 +1,350 @@ +#!/usr/bin/env python3 +"""SessionEnd sweep: report the shell processes that outlived the session and that nothing will reap. + +Registered as a Claude Code SessionEnd hook. It reads the hook payload on stdin, walks the process +table for the agent process this hook is a child of, and reports every descendant running in its own +session, since a shell started by a tool call is put in a session of its own and therefore survives +the agent that started it. It never kills anything: the maintainer decides what on the machine is +still wanted, and a long build backgrounded on purpose looks exactly like a leaked wait from here. + +Reporting at all is what needs saying. A SessionEnd hook cannot block, and Claude Code discards its +JSON output, so stderr on exit 2 is the one channel that reaches the maintainer. Exit 2 is inert on +this event (the session is already ending), which is why the sweep uses it for a report rather than +for a refusal. A clean sweep exits 0 and prints nothing. + +What it does not see: a process whose own tool-call shell has already exited is reparented to init, +so it is no longer a descendant of the agent and no descendant walk reaches it. The leak this exists +for is the backgrounded tool-call shell itself, which stays a child of the agent for the session's +whole life, and that one it does see. + +Linux and WSL only. `etimes` and a decimal `sess` are procps format keywords, which a BSD `ps` does +not carry, and Windows has no session test at all, so on macOS and on Windows this exits silently +without sweeping rather than failing at the end of every session. The kit does not ship a branch for +either that nobody has run. See host-setup/agent-safety/README.md requirement 8. + +Run `stray-process-sweep.py --selftest` to verify the reporting matrix without Claude Code. +""" + +import json +import os +import re +import subprocess +import sys + +# The process-table fields this sweep reads, in this order, with no header line. +_PS_FORMAT = "pid=,ppid=,sess=,etimes=,args=" + +# An ancestor is the agent process when it is named this, which is what Claude Code's executable is called. +# A packaged launcher naming the agent only in a later argument is matched second, by the pattern below. +# An unrecognized shape then reports a boundary rather than sweeping the wrong tree. +_AGENT_EXE = ("claude", "claude.exe") + +# The agent named as a path component or a bare word, for the second pass. +# A `.claude` configuration directory is deliberately not this, since every tool shell mentions one. +_AGENT_IN_ARGS = re.compile(r"(?:^|[/\\\s])claude(?:-code)?(?:[/\\\s]|\.(?:js|exe)|$)") + + +def _read_process_table(runner=None): + """{pid: (ppid, session, age_seconds, command)} for every process, or None when ps cannot run. + + A failed `ps` is None rather than an empty table. Reading `.stdout` alone turned an unsupported + format keyword into "no processes", which reads as a clean sweep and reaches the caller as the + wrong diagnosis, so the exit status and an empty table are both failures here. + """ + + def _run(): + done = subprocess.run( + ["ps", "-eo", _PS_FORMAT], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=5, + check=False, + ) + return done.returncode, done.stdout + + try: + code, out = (runner or _run)() + except (OSError, subprocess.SubprocessError): + return None + if code != 0: + return None + table = _parse_process_table(out) + return table or None + + +def _parse_process_table(out): + """Parse `ps -eo pid=,ppid=,sess=,etimes=,args=` output, skipping any line that does not fit.""" + table = {} + for line in (out or "").splitlines(): + parts = line.split(None, 4) + if len(parts) < 5: + continue + try: + pid, ppid, sess, age = (int(parts[i]) for i in range(4)) + except ValueError: + continue + table[pid] = (ppid, sess, age, parts[4]) + return table + + +def _ancestors(pid, table): + """Every ancestor pid of `pid`, nearest first, stopping on a cycle or an unknown parent.""" + out = [] + seen = {pid} + cur = pid + while cur in table: + cur = table[cur][0] + if cur in seen or cur not in table: + break + seen.add(cur) + out.append(cur) + return out + + +def _agent_pid(pid, table): + """The nearest ancestor of `pid` that is the agent process itself, or None when none is.""" + chain = _ancestors(pid, table) + for candidate in chain: + argv0 = table[candidate][3].split()[0] if table[candidate][3].split() else "" + base = argv0.rsplit("/", 1)[-1].rsplit("\\", 1)[-1].lower() + if base in _AGENT_EXE: + return candidate + # The outermost match, and never a shell. + # Nearest-first returned a tool shell that merely named a `claude` path in its own arguments. + # A sweep anchored there walks none of its siblings, so it reports a clean machine. + # A silent clean report is the one answer this must never give wrongly. + outermost = None + for candidate in chain: + args = table[candidate][3] + argv0 = args.split()[0] if args.split() else "" + if _is_shell(argv0): + continue + if _AGENT_IN_ARGS.search(args.lower()): + outermost = candidate + return outermost + + +def _is_shell(argv0): + """True if argv0 invokes a shell, which is never the agent process however its arguments read.""" + base = argv0.rsplit("/", 1)[-1].rsplit("\\", 1)[-1].lower().removesuffix(".exe").lstrip("-") + return base in ("sh", "bash", "zsh", "ksh", "dash", "fish") + + +def _descendants(root, table): + """Every descendant pid of `root`, breadth first.""" + children = {} + for pid, (ppid, _s, _a, _c) in table.items(): + children.setdefault(ppid, []).append(pid) + out = [] + queue = list(children.get(root, [])) + # Walked by index rather than by `pop(0)`, which shifts the whole list on every step. + # A busy host's table is large enough for that quadratic walk to be worth the index. + head = 0 + while head < len(queue): + pid = queue[head] + head += 1 + out.append(pid) + queue.extend(children.get(pid, [])) + return out + + +def survivors(table, agent, self_pid): + """The roots of the detached subtrees under `agent` that this sweep is not itself part of. + + A descendant sharing the agent's own session goes when the agent goes, so it is not a survivor. + A descendant in a session of its own does not, and only the top of each such subtree is reported, + since ending that shell is what ends the loop under it. The sweep's own subtree is excluded: this + hook runs in a detached session exactly like the shells it is looking for. + """ + if agent not in table: + return [] + agent_session = table[agent][1] + mine = {self_pid, *_ancestors(self_pid, table), *_descendants(self_pid, table)} + out = [] + for pid in _descendants(agent, table): + if pid in mine: + continue + ppid, session, _age, _cmd = table[pid] + if session == agent_session: + continue + if ppid in table and table[ppid][1] == session and ppid not in mine: + continue # its parent is already reported as the root of this same detached subtree + out.append(pid) + return out + + +def _age(seconds): + """A whole-unit age, so a reader sees `4h12m` rather than a second count to divide.""" + if seconds < 60: + return f"{seconds}s" + if seconds < 3600: + return f"{seconds // 60}m{seconds % 60:02d}s" + return f"{seconds // 3600}h{(seconds % 3600) // 60:02d}m" + + +def report(table, roots): + """The maintainer-facing report for `roots`, or "" when there is nothing to report.""" + if not roots: + return "" + one = len(roots) == 1 + noun = "process tree" if one else "process trees" + them = "it" if one else "them" + lines = [ + f"agent-safety: {len(roots)} {noun} outlived this session, and nothing reaps {them}.", + "", + ] + for pid in roots: + _ppid, _sess, age, cmd = table[pid] + extra = len(_descendants(pid, table)) + under = f" (+{extra} under it)" if extra else "" + lines.append(f" pid {pid} age {_age(age)}{under}") + lines.append(f" {cmd[:160]}") + lines += [ + "", + "Each runs outside the agent's own session, so leaving Claude Code does not stop it. Read", + "the commands above before ending anything that was backgrounded on purpose, then:", + "", + " kill " + " ".join(str(p) for p in roots), + ] + return "\n".join(lines) + + +def main(): + try: + json.loads(sys.stdin.read() or "{}") # the payload is read and not otherwise used + except (ValueError, OSError): + pass + # Windows has no session test at all, and a BSD `ps` carries neither `etimes` nor a decimal + # `sess`, so on both the hook is inert rather than printing a failure at every session end. + if os.name != "posix" or sys.platform == "darwin": + return 0 + table = _read_process_table() + if table is None: + print( + "agent-safety: the stray-process sweep could not read the process table.", + file=sys.stderr, + ) + return 2 + agent = _agent_pid(os.getpid(), table) + if agent is None: + print( + "agent-safety: the stray-process sweep could not find the agent process among its own " + "ancestors, so it swept nothing. Surviving shells, if any, are unreported.", + file=sys.stderr, + ) + return 2 + text = report(table, survivors(table, agent, os.getpid())) + if not text: + return 0 + print(text, file=sys.stderr) + return 2 + + +def _selftest(): + # A synthetic table, so the matrix runs identically on any machine: pid -> (ppid, session, age, command). + # 100 is the terminal the agent was launched from, 200 the agent, sharing the terminal's session. + rows = [ + "100 1 100 900 -bash", + "200 100 100 800 claude", + "300 200 100 700 mcp-server --stdio", + "400 200 400 600 /bin/bash -c until [ -s out ]; do sleep 30; done", + "410 400 400 1 sleep 30", + "500 200 500 5 python3 hooks/stray-process-sweep.py", + "510 500 500 0 ps -eo pid=,ppid=,sess=,etimes=,args=", + ] + table = _parse_process_table("\n".join(rows)) + checks = [ + ( + _agent_pid(500, table) == 200, + "the agent process is found by name among the sweep's ancestors", + ), + (survivors(table, 200, 500) == [400], "the detached shell is the one survivor reported"), + ( + 300 not in survivors(table, 200, 500), + "a child sharing the agent's session is reaped with it", + ), + (410 not in survivors(table, 200, 500), "only the root of a detached subtree is reported"), + (500 not in survivors(table, 200, 500), "the sweep never reports itself"), + (510 not in survivors(table, 200, 500), "nor anything it spawned"), + ( + "kill 400" in report(table, survivors(table, 200, 500)), + "the report hands over a kill line", + ), + ( + "1 process tree outlived this session, and nothing reaps it." + in report(table, survivors(table, 200, 500)), + "one survivor reads as one, pronoun included", + ), + ( + "2 process trees outlived this session, and nothing reaps them." + in report(table, [400, 300]), + "and more than one reads as more than one", + ), + ( + "+1 under it" in report(table, survivors(table, 200, 500)), + "and says what is under each root", + ), + (report(table, []) == "", "a clean sweep reports nothing at all"), + ( + _age(59) == "59s" and _age(90) == "1m30s" and _age(15120) == "4h12m", + "ages read in whole units", + ), + (_agent_pid(100, table) is None, "no agent among the ancestors is a boundary, not a guess"), + ( + _read_process_table(runner=lambda: (1, "")) is None, + "a ps that exits non-zero is a failure to read, never an empty machine", + ), + ( + _read_process_table(runner=lambda: (0, "")) is None, + "and so is a ps that exits 0 having printed nothing", + ), + ( + _read_process_table(runner=lambda: (0, "1 0 1 9 init")) == {1: (0, 1, 9, "init")}, + "a table that reads is returned as itself", + ), + ] + # A packaged launcher, where the agent is a path component of a later argument rather than argv0. + # The shell below is the trap: every tool shell sources a snapshot out of a `.claude` directory. + packaged_rows = [ + "100 1 100 900 -bash", + "200 100 100 800 node /usr/lib/node_modules/claude-code/cli.js", + "400 200 400 600 /bin/bash -c source ~/.claude/shell-snapshots/snap.sh && x", + "500 400 400 5 python3 hooks/stray-process-sweep.py", + ] + packaged = _parse_process_table("\n".join(packaged_rows)) + # The same launcher, with a tool shell between it and the sweep naming a `claude` path of its own. + # Nearest-first anchored on that shell and reported its siblings as nothing. + shelled_rows = [ + "100 1 100 900 -bash", + "200 100 100 800 node /usr/lib/node_modules/claude-code/cli.js", + "400 200 400 600 /bin/bash -c cd ~/repos/claude/x && sleep 999", + "500 400 400 5 python3 hooks/stray-process-sweep.py", + ] + shelled = _parse_process_table("\n".join(shelled_rows)) + checks += [ + ( + _agent_pid(500, packaged) == 200, + "a launcher naming the agent in a path component is found", + ), + ( + _agent_pid(500, packaged) != 400, + "a shell mentioning a .claude directory is not the agent", + ), + ( + _agent_pid(500, shelled) == 200, + "nor is one whose own arguments name a claude path", + ), + ] + ok = True + for passed, label in checks: + if not passed: + ok = False + print(f" {'ok ' if passed else 'FAIL'} {label}") + print("SELFTEST PASS" if ok else "SELFTEST FAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(_selftest() if "--selftest" in sys.argv[1:] else main()) diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index b1c0f3e43..d9c73a866 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -350,6 +350,258 @@ def test_a_deleted_settings_file_reports_stale_rather_than_crashing(self): self.assertEqual(r.returncode, 1, r.stdout + r.stderr) self.assertNotIn("Traceback", r.stderr) + def test_the_sweep_is_deployed_and_registered_once(self): + """A second hook is a second chance to install the bytes and wire up nothing.""" + self.install() + self.assertTrue((self.home / "hooks" / install.SWEEP_NAME).is_file()) + groups = self._settings()["hooks"]["SessionEnd"] + entries = [ + h + for g in groups + for h in g.get("hooks", []) + if install.SWEEP_STEM in h.get("command", "") + ] + self.assertEqual(len(entries), 1) + # A SessionEnd hook's own budget is 1.5s, and only a declared per-hook timeout raises it. + self.assertEqual(entries[0]["timeout"], install.SWEEP_TIMEOUT_SECONDS) + + def test_the_sweep_group_carries_no_matcher(self): + """A matcher would narrow SessionEnd to one exit reason, and a quit is not the only one.""" + self.install() + groups = self._settings()["hooks"]["SessionEnd"] + owning = [ + g + for g in groups + if any(install.SWEEP_STEM in h.get("command", "") for h in g.get("hooks", [])) + ] + self.assertEqual(len(owning), 1) + self.assertNotIn("matcher", owning[0]) + + def test_reinstalling_does_not_duplicate_the_sweep(self): + self.install() + self.install() + groups = self._settings()["hooks"]["SessionEnd"] + entries = [ + h + for g in groups + for h in g.get("hooks", []) + if install.SWEEP_STEM in h.get("command", "") + ] + self.assertEqual(len(entries), 1) + + def test_a_wrong_hooks_shape_is_reported_as_itself(self): + """Iterating a dict yields keys and a string yields characters, so a wrong shape read as + zero registrations and sent a reader to the wrong fix.""" + self.install() + for shape, expected in ( + ({"SessionEnd": {"a": 1}}, "`hooks.SessionEnd` as dict"), + ({"PreToolUse": "nope"}, "`hooks.PreToolUse` as str"), + ("nope", "`hooks` as str"), + ): + data = self._settings() + data["hooks"] = shape + self._write(data) + problems = install.registration_problems(self.home) + self.assertTrue( + any(expected in p for p in problems), + f"{shape!r} reported {problems!r} rather than naming the shape", + ) + + def test_a_wrong_hooks_type_is_reported_once_rather_than_per_event(self): + self.install() + data = self._settings() + data["hooks"] = "nope" + self._write(data) + problems = install.registration_problems(self.home) + self.assertEqual(len([p for p in problems if "`hooks` as str" in p]), 1, problems) + + def test_a_decoy_command_naming_the_sweep_is_not_a_registration(self): + """Matching any command containing the sweep's name let a decoy report a machine current. + + Each shape asserts the problem it should raise rather than that it raised one, since a + second and false "not registered" line satisfied a bare truthiness check by itself. + """ + self.install() + good = self._settings()["hooks"]["SessionEnd"][0]["hooks"][0] + for label, entry, expected in ( + ( + "decoy", + {"type": "command", "command": "echo stray-process-sweep"}, + "does not run the deployed one", + ), + ("timeout", dict(good, timeout=1), "carries timeout 1"), + ("type", dict(good, type="prompt"), "does not run the deployed one"), + ): + with self.subTest(shape=label): + data = self._settings() + data["hooks"]["SessionEnd"] = [{"hooks": [entry]}] + self._write(data) + problems = install.registration_problems(self.home) + self.assertTrue( + any(expected in p for p in problems), + f"{label} shape reported {problems!r} rather than naming its own defect", + ) + + def test_an_entry_with_a_defect_is_not_also_reported_absent(self): + """Counting only the sound entries added "the guard never runs" under every other problem.""" + self.install() + data = self._settings() + data["hooks"]["SessionEnd"][0]["hooks"][0]["type"] = "prompt" + data["hooks"]["PreToolUse"][0]["matcher"] = "Edit" + self._write(data) + problems = install.registration_problems(self.home) + self.assertEqual([p for p in problems if "is not registered" in p], [], problems) + self.assertEqual([p for p in problems if "never runs" in p], [], problems) + + def test_a_matcher_every_bash_call_reaches_is_not_a_defect(self): + """Requiring the exact string "Bash" reported three working registrations as broken.""" + self.install() + for matcher in ("Bash", "Bash|Task", "*", ""): + with self.subTest(matcher=matcher): + data = self._settings() + data["hooks"]["PreToolUse"][0]["matcher"] = matcher + self._write(data) + self.assertEqual(install.registration_problems(self.home), [], matcher) + data = self._settings() + del data["hooks"]["PreToolUse"][0]["matcher"] + self._write(data) + self.assertEqual(install.registration_problems(self.home), []) + data = self._settings() + data["hooks"]["PreToolUse"][0]["matcher"] = "Edit" + self._write(data) + self.assertTrue( + any("so that group never fires" in p for p in install.registration_problems(self.home)) + ) + + def test_a_registration_is_read_however_its_path_is_quoted(self): + """A hand-written or UI-written registration runs the deployed path bare or single-quoted.""" + self.install() + guard = self.home / "hooks" / install.DEPLOYED_HOOKS[0] + for spelling in (f"python3 {guard}", f"python3 '{guard}'", f'python3 "{guard}"'): + with self.subTest(command=spelling): + data = self._settings() + data["hooks"]["PreToolUse"][0]["hooks"][0]["command"] = spelling + self._write(data) + self.assertEqual(install.registration_problems(self.home), [], spelling) + + def test_an_absent_sweep_timeout_is_reported_as_absent(self): + """The entry carries no timeout, so a message naming a value of None describes nothing.""" + self.install() + data = self._settings() + del data["hooks"]["SessionEnd"][0]["hooks"][0]["timeout"] + self._write(data) + problems = install.registration_problems(self.home) + self.assertTrue(any("carries no timeout" in p for p in problems), problems) + self.assertEqual([p for p in problems if "None" in p], [], problems) + + def test_one_group_defect_is_reported_once_however_many_entries(self): + """A matcher belongs to the group, so two entries under it are still one defect.""" + self.install() + for event, key in (("PreToolUse", "Edit"), ("SessionEnd", "clear")): + with self.subTest(event=event): + data = self._settings() + group = data["hooks"][event][0] + group["matcher"] = key + group["hooks"] = group["hooks"] * 2 + self._write(data) + problems = install.registration_problems(self.home) + matcher_lines = [p for p in problems if "matcher" in p and event in p] + self.assertEqual(len(matcher_lines), 1, problems) + + def test_the_guard_is_deployed_and_searched_for_under_one_name(self): + """The sweep routes both halves through a constant, and the guard spelled one half by hand.""" + self.install() + self.assertTrue(install.GUARD_NAME.startswith(install.GUARD_STEM)) + live = self.home / "hooks" / install.GUARD_NAME + self.assertTrue(live.is_file(), "the deployed name is not what the installer wrote") + self.assertIn( + install.GUARD_STEM, self._settings()["hooks"]["PreToolUse"][0]["hooks"][0]["command"] + ) + + def test_a_longer_sweep_timeout_is_not_reported_as_a_defect(self): + """A budget larger than this installer writes is better than it, not worse.""" + self.install() + data = self._settings() + data["hooks"]["SessionEnd"][0]["hooks"][0]["timeout"] = install.SWEEP_TIMEOUT_SECONDS + 20 + self._write(data) + self.assertEqual(install.registration_problems(self.home), []) + + def test_a_failed_self_test_leaves_the_live_hook_alone(self): + """Copying onto the live path and testing after left a broken hook installed and registered.""" + self.install() + live = self.home / "hooks" / install.SWEEP_NAME + before = live.read_bytes() + root = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, root, True) + broken = root / "claude" + shutil.copytree(HERE, broken, ignore=shutil.ignore_patterns("__pycache__")) + sweep = broken / install.SWEEP_NAME + sweep.write_text( + sweep.read_text(encoding="utf-8").replace( + 'print("SELFTEST PASS" if ok else "SELFTEST FAIL")', + 'ok = False; print("SELFTEST FAIL")', + ), + encoding="utf-8", + ) + env = dict(os.environ, CLAUDE_HOME=str(self.home)) + r = subprocess.run( + [sys.executable, str(broken / "install.py")], + capture_output=True, + text=True, + encoding="utf-8", + env=env, + check=False, + ) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertEqual(live.read_bytes(), before, "the live hook was replaced by a failing one") + self.assertEqual( + sorted(f.name for f in (self.home / "hooks").iterdir()), + sorted(install.DEPLOYED_HOOKS), + "a staged file was left behind", + ) + + def test_a_sweep_under_a_matcher_reports_stale(self): + """A matcher filters SessionEnd by exit reason, so the sweep would miss every other exit.""" + self.install() + data = self._settings() + for group in data["hooks"]["SessionEnd"]: + if any(install.SWEEP_STEM in h.get("command", "") for h in group.get("hooks", [])): + group["matcher"] = "clear" + self._write(data) + r = run(self.home, "--report") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("under a matcher", r.stdout) + + def test_an_unregistered_sweep_reports_stale_rather_than_current(self): + self.install() + data = self._settings() + data["hooks"]["SessionEnd"] = [] + self._write(data) + r = run(self.home, "--report") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("never reported", r.stdout) + + def test_a_preexisting_matcher_group_is_left_alone(self): + """Somebody else's SessionEnd hook keeps its own filter rather than gaining this one.""" + self.install() + data = self._settings() + data["hooks"]["SessionEnd"] = [ + {"matcher": "clear", "hooks": [{"type": "command", "command": "somebody-elses.sh"}]} + ] + self._write(data) + self.install() + groups = self._settings()["hooks"]["SessionEnd"] + theirs = next(g for g in groups if g.get("matcher") == "clear") + self.assertEqual([h["command"] for h in theirs["hooks"]], ["somebody-elses.sh"]) + self.assertTrue( + any( + install.SWEEP_STEM in h.get("command", "") + for g in groups + if "matcher" not in g + for h in g.get("hooks", []) + ) + ) + def test_reinstalling_clears_an_unregistered_hook(self): self.install() data = self._settings() @@ -523,35 +775,56 @@ def test_a_real_edit_to_a_snippet_is_still_reported(self): finally: target.write_bytes(original) + def test_the_digest_reads_every_deployed_hook(self): + """Naming the hooks in `installed_digest` was the drift `DEPLOYED_HOOKS` exists to close. + + Parametrised over the constant rather than over two literals, so a hook added to the deploy + list is covered here without anyone remembering to add it. + """ + for name in install.DEPLOYED_HOOKS: + with self.subTest(hook=name): + self.install() + self.assertIsNotNone(install.installed_digest(self.home)) + (self.home / "hooks" / name).unlink() + self.assertIsNone( + install.installed_digest(self.home), + f"{name} is deployed but the digest does not read it", + ) + def test_every_deployed_file_is_in_the_digest(self): - """The inverse: the kit copies gh-write-guard.py and every snippet, and each must be covered. + """Every file a real install writes is covered by the digest that decides CURRENT. - The source scan alone was a false positive. It matched only literal `HERE / "..."` reads, - which is the hook and nothing else, while the snippet names came from a list inside `main`. - A new snippet passed it while being absent from the digest, so the two sources of truth are - both checked now, and the derivation below is what actually makes the gap impossible. + Two earlier versions of this test each compared one declared list against another, which + is a tautology `PAYLOAD_FILES`'s own definition satisfies, and a source scrape, which went + silent the moment the copy became a loop. The independent source is the installed home + itself: a file the installer actually wrote and the digest does not read is the gap, and + reading the disk is the only way to see it without trusting the lists under test. """ - source = INSTALL.read_text(encoding="utf-8") - named = {name for name in re.findall(r'HERE / "([^"]+\.(?:py|md))"', source)} - named |= {filename for _, filename in install.CLAUDE_MD_BLOCKS} - named.discard("install.py") - # The hook is the only literal read; every other entry arrives from the block list. - self.assertGreater( - len(named), 1, "the scan matched only one file, so it is not covering the blocks" - ) - for name in sorted(named): + self.install() + written = {f.name for f in (self.home / "hooks").iterdir() if f.is_file()} + self.assertGreaterEqual(len(written), 2, "the install wrote fewer hooks than the kit has") + for name in sorted(written): self.assertIn( name, install.PAYLOAD_FILES, - f"install.py reads {name} but PAYLOAD_FILES omits it, so the digest misses it", + f"the installer wrote {name} but PAYLOAD_FILES omits it, so the digest misses it", ) + # The blocks are covered the same way, from the file the installer actually wrote. + text = self.md.read_text(encoding="utf-8") + for marker in install.BLOCK_MARKERS: + self.assertIn(f" [spec]: ../README.md [claude-hook]: ../claude/gh-write-guard.py +[claude-sweep]: ../claude/stray-process-sweep.py [issue-781]: https://github.com/ptr727/ProjectTemplate/issues/781 diff --git a/host-setup/agent-safety/opencode/README.md b/host-setup/agent-safety/opencode/README.md index 9644a126e..e8725ca6b 100644 --- a/host-setup/agent-safety/opencode/README.md +++ b/host-setup/agent-safety/opencode/README.md @@ -1,4 +1,4 @@ -# opencode Write-Safety Gap +# opencode Host-Safety Gap No hook implements [`../README.md`][spec]'s requirements for opencode yet. Tracked at [issue #781][issue-781]. @@ -15,21 +15,25 @@ in an opencode session. [`../README.md`][spec] states each requirement as an agent-agnostic decision rule, not tied to any one hook API. [`../claude/gh-write-guard.py`][claude-hook] is a worked reference implementation of -all six requirements against Claude Code's `PreToolUse` hook, including its tokenizer, its +requirements 1 to 7 against Claude Code's `PreToolUse` hook, including its tokenizer, its self-test matrix (`--selftest`), and its documented fail-open/fail-closed choices per requirement -- useful as a model for argv parsing and edge cases, not as something to port line for line, since opencode's own permission-model extension points differ from Claude Code's hook shape. Whatever mechanism opencode offers for intercepting or gating a command before it runs is the place to -implement requirements 1-6. If opencode offers no such extension point at all, that finding belongs +implement requirements 1 to 7. Requirement 8 is not one of them: it reports the processes a session +leaves behind, so it belongs wherever opencode signals that a session has ended, and +[`../claude/stray-process-sweep.py`][claude-sweep] is the worked reference for that one. If opencode +offers neither extension point, that finding belongs on [issue #781][issue-781], not silently worked around. ## Auditing Once an opencode-side implementation exists, audit it the way [`../README.md`][spec] "Auditing an Implementation Against This Spec" describes: run its own self-test and check every case against the -six requirements, not against `gh-write-guard.py`'s source. +eight requirements, not against `gh-write-guard.py`'s source. [spec]: ../README.md [claude-hook]: ../claude/gh-write-guard.py +[claude-sweep]: ../claude/stray-process-sweep.py [issue-781]: https://github.com/ptr727/ProjectTemplate/issues/781 diff --git a/host-setup/windows/README.md b/host-setup/windows/README.md index 7a1ad9009..56ead2c97 100644 --- a/host-setup/windows/README.md +++ b/host-setup/windows/README.md @@ -27,7 +27,7 @@ host-setup\windows\setup-wsl.ps1 -Status **Script execution.** A `git clone` carries no mark of the web, so these run under the default `RemoteSigned` policy. A browser-downloaded zip does carry one, and is blocked until `Unblock-File` clears the mark. The `.\` prefix is required when running a script from the current directory, exactly as it is for [`agent-safety/claude/install.ps1`][agent-safety]. -`pwsh -File .\install-tools.ps1` answers the `.\` rule and **not** the policy, which still applies to it: on a marked file under `RemoteSigned` it fails with a `SecurityError` naming the file as unsigned. The form that gets past the mark is `pwsh -ExecutionPolicy Bypass -File .\install-tools.ps1`, the same shape [`agent-safety/claude/README.md`][agent-safety-claude-readme] gives for the write-safety installer -- `-ExecutionPolicy Bypass` sets only the process scope, which a machine- or user-level policy set by Group Policy still overrides. Prefer clearing the mark with `Unblock-File` over bypassing, since the bypass covers every script that the run touches and does not universally guarantee the run. +`pwsh -File .\install-tools.ps1` answers the `.\` rule and **not** the policy, which still applies to it: on a marked file under `RemoteSigned` it fails with a `SecurityError` naming the file as unsigned. The form that gets past the mark is `pwsh -ExecutionPolicy Bypass -File .\install-tools.ps1`, the same shape [`agent-safety/claude/README.md`][agent-safety-claude-readme] gives for the host-safety installer -- `-ExecutionPolicy Bypass` sets only the process scope, which a machine- or user-level policy set by Group Policy still overrides. Prefer clearing the mark with `Unblock-File` over bypassing, since the bypass covers every script that the run touches and does not universally guarantee the run. ## Why winget Is the Only Source diff --git a/reports/canonical-review.json b/reports/canonical-review.json index 25e57fd2d..91ebb7deb 100644 --- a/reports/canonical-review.json +++ b/reports/canonical-review.json @@ -843,19 +843,19 @@ }, { "unit": ".markdownlint-cli2.jsonc", - "digest": "sha256:826753ef2717b77ccc1fef5cd20ee7f2437a8b5c9218cd25f9a66fbfa8390509", + "digest": "sha256:7a7cd77c93dbddcc5ba2c44d3c5d8b00c2f430b9c7bc42888d755bb57e4e3a88", "reviewer": "agent-skill", "findings": 3, - "hubCommit": "e7cb1cf763bf445d8535f23307ac68836a51ce16", - "stamp": "2026-09-09T21:02:31Z" + "hubCommit": "e1559c98c5fbcf9ae0dd3b3344247d012e7a4e44", + "stamp": "2026-09-15T14:32:02Z" }, { "unit": "AGENTS.md > Context and Delegation Discipline", - "digest": "sha256:41872877c85393e78f84891521cb31d1249d797494ff3cdb7f8001323584e112", + "digest": "sha256:91faa2b36186133e3e4befac76b1b06d6899e5ebb74cc7442560e8e4a625086a", "reviewer": "agent-skill", - "findings": 0, - "hubCommit": "3d13223f2e28ff50f6954e7db39521a8840dbeb6", - "stamp": "2026-09-14T03:16:33Z" + "findings": 4, + "hubCommit": "ec9f4fede85dea1be9e42de466e6e5e0871e126e", + "stamp": "2026-09-15T05:13:54Z" }, { "unit": "AGENTS.md > Where the Rules Live",