Plan: a shell guard - shellcheck and two delete rules on every bash call

Closes: #751. Relates to: #725 (the review this came out of), ADR-004 (package boundaries). Branch: feat/pi-shellcheck. Status: Done (2026-11-10) — shipped in 0.158.1; a refusal under Git Bash on Windows was not observed

Context

The gate decides whether a command may run (rules, then the model judge). Nothing deterministic reads whether the command is well-formed: the only shipped pattern for plain rm is rm --no-preserve-root, and whether the judge notices that $dir may be empty is unmeasured. Each bash call is its own shell, so a variable not set in that command is the environment’s or empty.

Measured (shellcheck 0.11.0 over 2,370 real root-agent bash calls, canopy’s week and one pi session): 5 ms median, 9 ms p95; no error-level finding; a warning on 5-8% of calls, as common on commands that worked (6%) as on ones that failed (7%), so the full list is noise and a curated one is needed. 19 calls were recursive deletes with a variable in the path, every one rm -rf "$HOME/.cache/…​".

What a command receives when its variable is empty, printed and not run (bash 5.3, coreutils 9.12):

Written Received Effect

rm -rf "$d"/*

-rf /*

from the root

rm -rf "$d/", rm -rf "$HOME/$d"

-rf /, -rf /home/me/

root, home

rm -rf $d, rm -rf "$d"

-rf, -rf ''

nothing

find $d -delete, git clean -fdx $d

no path

the current directory, the whole repository

cd $d

no operand: succeeds, in $HOME

a following rm -rf * runs there

cd "$d"

fails; after ; the next command still runs

rm -rf * runs where the shell was

Non-empty and unquoted, d="/a/my project" gives rm two targets and d="*" every entry of the current directory.

shellcheck, with every optional check on, has a delete-specific finding for one of these (SC2115, "$d"/*). For the rest it gives only SC2086 (unquoted variable; 220 of the 2,370 calls, none a delete) or SC2164 (cd without || exit; 44, none a delete), which cannot be blocked without refusing one command in nine. So two rules of our own sit beside it, on the parser the harness already loads.

The operator’s rulings (2026-11-10): a new extension of ours; block, warn and ignore lists shipped as defaults and adjustable by the developer in a JSON file; a variable in a recursive delete is blocked quoted or not, since one rule costs a retry and a distinction buys nothing; both custom rules stay.

Design

D1. A package, @gadhs/pi-shellcheck (packages/pi-shellcheck, 0.1.0), loaded by @gadhs/pi as loaders/13-shellcheck.ts: after pi-workflow, before the permission system, so a refused call never reaches the judge or /pending (pi returns the first tool_call block, runner.js emitToolCall). It imports the two libraries, @gadhs/pi-bash and @gadhs/pi-workspace, and no extension package (ADR-004). It reaches the diagnostics stream by the shared symbol, as pi-ssh/diag.ts does.

D2. What it reads. The command of every bash tool call, nested ones included (a codemode script’s), in every mode. Not powershell, not the human’s ! commands (they raise user_bash), not what runs inside bash -c '…​', ssh host '…​' or a script file.

D3. Three outcomes per finding, by a table (D6): block - the handler returns { block: true, reason } and the command does not run; warn - the findings are kept by toolCallId and appended to the result as one text block at tool_result; ignore - dropped. A command with any block finding is refused and its warn findings ride in the same reason. The reason opens shell guard (deterministic policy, not a model judgement): not run. and gives, per finding, the id, the words it is about and the fix. The note opens shellcheck (advisory; the command has already run): and holds at most five findings, 600 characters.

D4. Two rules of our own, over analyze()’s commands, needing no binary. pi-bash’s wrapper table (`wrappers.ts: timeout, env, nice, ionice, nohup, setsid, stdbuf, exec, command, time) is already unwrapped there. sudo and doas are not in that table, and adding them would change what the commit guard and the mode rules read, which is its own issue; so rules.ts steps over a leading sudo or doas itself: the name, then each flag, with the next token too for a flag that takes a value (sudo: -u -g -h -p -C -D -R -T -U -r -t; doas: -u -C), up to -- or the first other word, which is the program the rules read.

  • delete-variable: a recursive delete with a word that is not literal and not guarded. Recursive delete: rm with -r, -R or --recursive (in a short-flag cluster too); find with -delete; git …​ clean; rsync with a --del* or --remove-source-files flag. Not literal: argv[i] === null. Guarded: with every ${NAME:?…​} and ${NAME?…​} removed from the word’s raw text, no $ and no backtick remains. The fix it names: "${dir:?}"; for a $(…​) word, assign it to a variable first and guard that.

  • cd-then-delete: a cd whose operand is not literal, followed later on the line by a recursive delete with a relative target (a literal word not starting / or ~, or find -delete with no path), unless the cd’s operand is guarded and the text between the `cd and the next command is &&. The fix: cd "${dir:?}" && rm …​.

A cold or failed parser (status: "unavailable") skips both and logs it; the extension warms the parser at load, as pi-modes and pi-workflow do.

D5. shellcheck, run as shellcheck --norc -s bash -f json1 - with the command on stdin: --norc so a repository’s .shellcheckrc cannot switch a check off. Findings are { code, level, line, message }. A run that exceeds timeoutMs (default 2000), exits unreadably or cannot start is skipped and logged; it never refuses a command. shellcheck’s own directive, # shellcheck disable=SC2115 on the line before, silences that code (verified on stdin; a trailing one is a parse error) and the block reason says so. The custom rules have no waiver: their fix is always available.

D6. The table: defaults, then the operator’s file. <agentDir>/gadhs-pi-shellcheck.json, read at load from the agent directory only (a repository cannot supply one; an agent cannot write gadhs-pi-*.json, by the shipped write, edit and bash rules):

{ "enabled": true, "block": ["SC2046"], "warn": ["SC2094"], "ignore": ["SC2154"], "timeoutMs": 2000, "binary": "/usr/bin/shellcheck" }

Every key optional. An id named in a list is in that category, whatever its default. Ids are SC and four digits, or delete-variable, cd-then-delete. An unknown key, a malformed id, or an id in two lists is refused by name: the shipped defaults then apply whole and the session start says why. enabled: false registers nothing. binary names a shellcheck to run instead of the pinned one (an air-gapped seat).

Defaults:

  • block: delete-variable, cd-then-delete, SC2115 (empty variable widens a delete), SC2114 (recursive delete of a system directory), SC2094 (reading and overwriting one file in a pipeline).

  • warn: SC2154, SC2046, SC2061, SC2062, SC2038, SC2044, SC2045, SC2216, SC2088, SC2064, SC2069, SC2089, SC2090, SC2095, SC2030, SC2031, SC2024, SC2144, SC2184, SC2125, SC2188, SC2168, SC1083, SC1010, SC1112.

  • ignore: SC1090, SC1091, SC2086, SC2012, SC2010, SC2164, SC2034, SC2016, SC2126, SC2143, SC2181, SC2006, SC2015, SC2035, SC2059, SC2155, SC2207, SC2166, SC2174, SC2009, SC2013, SC2162, SC2029.

  • any other code: shellcheck’s level decides - warning or error is a warn (a syntax error lands here: bash runs the lines before it, but shellcheck’s parser can refuse valid bash and a parse error has no waiver), info or style is ignored.

On the measured calls: about 0.8% blocked (the 19 "$HOME/…​" deletes, one retry each), about 1.2% warned.

D7. The binary. shellcheck v0.11.0 from koalaman/shellcheck, pinned per platform with the release’s own SHA-256 digests, through pi-workspace’s verifiedBinaryAt (download, check, keep with its sidecar; re-checked before each session’s first use): linux-x64, linux-arm64, darwin-x64, darwin-arm64 from the .tar.gz assets with extractWithTar; win32-x64 from the .zip (it holds shellcheck.exe) with a zip extractor that runs Windows' System32\tar.exe xf, as pi’s own tools-manager does. Kept at <agentDir>/gadhs-pi-shellcheck/shellcheck-v0.11.0-<platform>-<arch>/. Fetched in the background at the first session start that lacks it; PI_OFFLINE, a platform with no asset, or a failed fetch leaves the shellcheck half off, said once, with the two custom rules still on. It is fetched from upstream, not redistributed: the package ships no GPL binary.

D8. The agent is told the bar. One bullet in the working agreements (pi-guidance/guidance/global.md): a recursive delete names its variable as "${dir:?}", and a cd before a wildcard delete is cd "${dir:?}" && …​; the shell guard refuses the rest.

D9. pi-bash exposes each word’s raw text. BashCommand gains raw: string[], parallel to argv after unwrapping (from commandArgv’s `raw and the stray words' raw), so a consumer can read what a non-literal word was. Additive; pi-bash takes a minor.

Erratum (2026-11-10): the end-to-end run exercised the root session only - refused, then the guarded form, then a note - with this workspace’s extension loaded by path, where pi-subagents is not present; a helper’s call was not run end to end. What stands in: helper sessions resolve their extensions from the parent’s package list (pi-subagents package-exclusions.ts), the loader is in pi.extensions, and the wiring test reads a nested call. A helper’s bash call is the first check after install.

Erratum (2026-11-10): checked after 0.158.1 was installed. On Linux a helper’s bash call got the note on its result and the refusal of an unguarded delete, as the root session does. On Windows (win32-x64) the download, checksum and unpack by System32\tar.exe worked from the repository, and a live session under brush 0.4.0 refused and noted; the operator saw the first-session notice, its wording not recorded. Not observed: a refusal in a live session under Git Bash. The guard reads the command’s text before any shell runs it, so no difference is expected there.

Scope

  1. U1 pi-bash. BashCommand.raw (D9); tests beside the existing structure cases, wrappers and stray words included.

  2. U2 the table. config.ts (parse, validate, load), table.ts (defaults, the merge, classify(id, level)); unit tests for every refusal and for an id moved each way.

  3. U3 the rules. rules.ts (D4) over a corpus that holds every row of Context’s table, each delete again behind sudo, sudo -u app, doas and timeout 5 sudo, and the non-cases (sudo -u "$user" ls, rm -rf "${d:?}", rm -f "$f", rm -rf build, cd "${d:?}" && rm -rf *, find "$d" -name x, git status "$d").

  4. U4 shellcheck. binary.ts (the pin, the kept path, the zip extractor, the background fetch), run.ts (spawn seam, JSON read, timeout).

  5. U5 wiring. extension.ts, index.ts, diag.ts; packages/pi/loaders/13-shellcheck.ts, the dependency and pi.extensions entry in packages/pi/package.json; tools/lib/stage.mjs WORKSPACE_PACKAGES; whatever packages/pi/test/distribution.test.ts pins by name.

  6. U6 delivery. The guidance bullet (D8); CI fetches the pinned shellcheck beside rg and fd (tools/ci-search-tools.mjs, .gitlab-ci.yml) so the real-binary cases run there; docs and changelog (below); one end-to-end run with real pi recorded on the issue.

One branch, one MR. Not in scope: sudo and doas in pi-bash’s shared wrapper table (the commit guard and the mode rules would see through them too: an issue of its own, filed at approval); linting shell files in each repository’s validate; powershell; a per-project settings file; probing whether the judge alone catches these forms.

Risks

Risk Mode Mitigation

A rule refuses a delete that was safe (rm -rf "$HOME/.cache/x")

Fail-closed: one refused call, loud

The reason names the one-line fix; the guidance states the bar; measured at 0.8% of calls; the operator can move either rule to warn or ignore.

A dangerous form the rules do not model (bash -c, ssh host, a script file, xargs rm, a literal cd /x; rm -rf *, a prefix program other than the wrapper table’s, sudo and doas)

Fail-open, silent

Stated as limits in the doc page; the judge and the rules still see the command; no claim of completeness is made anywhere.

The model waives a block with # shellcheck disable=

Fail-open, loud in the transcript

A deliberate act, visible in the command; the custom rules take no waiver; the threat model is honest mistakes.

shellcheck missing, offline, slow or crashing

Fail-open: the shellcheck half is skipped; logged, and said once at session start

The two custom rules need no binary; shellcheck.skipped records carry the reason; binary in the settings names a local one.

The Windows .zip path (System32 tar.exe, a 35 MB shellcheck.exe) is untested on luchs

Fail-open: no binary, shellcheck half off, said once

Unit-tested through the extractor seam; the pi-win agent is asked to run it before the release note claims Windows.

Helper sessions do not load the extension

Fail-open, silent

U5 asserts the loader is in pi.extensions, which helper sessions load as they load the gate; U6’s end-to-end run includes one helper call.

An invalid settings file

Fail-closed on the defaults, loud

The shipped table applies whole and the session start names the key; never a silent "off".

A warn note makes the model rewrite commands that worked

Silent cost: extra turns

The warn list is curated to ~1% of calls; shellcheck.warn records let the rate and the follow-up turns be read from diagnostics after a fortnight.

The pinned download is tampered with or replaced upstream

Fail-closed: checksum mismatch, nothing kept or run

verifiedBinaryAt checks the release’s SHA-256 before keeping and before use; a mismatch is the "missing" row.

Tests

Tests: unit, contract, regression, wiring, end-to-end.

  • Unit (test/table.test.ts, test/config.test.ts, test/rules.test.ts, test/run.test.ts, test/binary.test.ts): the defaults are exactly D6’s lists and no id is in two; each config refusal by name; an id moved each way wins over its default; the fallback by level; every corpus row of U3 blocked or passed as stated, with the reason’s fix text; a timeout, a non-JSON answer and a spawn failure each skip; the kept path, the asset per platform, no asset for win32-arm64.

  • Contract (test/shellcheck.contract.test.ts, describe.skipIf when no shellcheck is kept or on PATH, so a seat without it skips visibly): the real 0.11.0 answers json1 in the shape run.ts reads; SC2115, SC2114 and SC2094 fire on their examples; the directive on the line before silences SC2115; --norc ignores a .shellcheckrc in the working directory.

  • Regression (in test/rules.test.ts, named for the cases): rm -rf "$dir" and rm -rf $dir are both blocked - the pin for "quoted or not"; cd $d && rm -rf * is blocked and cd "${d:?}" && rm -rf * is not; with the parser cold, nothing is blocked and a shellcheck.skipped record says why - the pin for "never refuses by failing".

  • Wiring (test/extension.test.ts, a fake pi): a block returns { block: true } with the reason and runs no shellcheck after a custom-rule block is enough; a warn appends one text block to that call’s result and to no other; enabled: false registers no handler; a nested call (parentToolCallId set) is read; powershell and non-bash tools are not; the session-start notices (fetched, skipped, invalid file) each once. packages/pi/test/distribution.test.ts and tools/lib/test/stage.test.mjs hold the loader and the package list.

  • End-to-end (once, recorded on the issue): real pi in RPC mode with this workspace’s extension; the model is asked to run rm -rf "$nowhere_dir"/x and the result is the guard’s refusal; then the guarded form runs; then a command with an unquoted $(…​) runs and carries the note.

Delivery

  • Canonical doc page: a new docs/modules/ROOT/pages/shell-guard.adoc (what is read, the three outcomes, the full default table, the settings file, the limits, the binary), linked from nav.adoc; a row and the key list in public-surface.adoc; the package in packages.adoc; one paragraph in security.adoc saying what the guard is not.

  • CHANGELOG.adoc == Unreleased, Added: the guard, the measured rates, the limits.

  • pi-guidance/guidance/global.md: the bullet of D8.

  • The MR closes the issue filed at approval; afterwards one line on it with the merge SHA and what was deferred (the Windows check, the fortnight’s rates).

Edit this page · latest