Refuse hook bypasses, pushes, deletes, cf project commands and closed env reads in every agent harness
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- One pure policy, scripts/hooks/lib/policy.ts: decide(command) is Allow or Deny{rule, reason}, with five rules (hook-bypass, push, delete, cf-project-command, closed-env-read) and one sentence per rule from AGENTS.md naming what to do instead. It allows or denies; it never rewrites (Rat Stack's GIT_EDITOR=: injection is dropped). - It judges argv, not text. scripts/hooks/lib/shell.ts reads the line as bash would: simple commands on ; && || | ( ) and newlines, quotes, $'…' escapes, $(…), backticks, <(…), heredocs (a quoted delimiter's body is data; an unquoted one's substitutions run) and < reads. scripts/hooks/lib/argv.ts splits options, their values and operands from a per-program grammar, so `-m "--no-verify"` is a message and `-nm x` carries -n. An option the grammar doesn't know stands alone, which can only turn a value into a judged flag, never hide one. - Each simple command loses VAR=value words, keywords, wrappers (env, command, exec, sudo, nice, timeout, xargs, …), package runners (bunx, npx, pnpm dlx, bun run ops --, varlock run --) and argv[0]'s path; sh -c, eval, npx -c, bun exec, env -S and a heredoc fed to a shell are judged as scripts. - Rows past the Want deny where the answer was unclear, each with its reason in the test: -c alias.* and git config alias.* writes, git push --dry-run, cf deploy --dry-run, wrangler delete --dry-run, HUSKY=0, and readers beyond the listed ones (cp, dd, diff, jq, editors). `git <cmd> --help` is allowed, since git runs it as `git help <cmd>`. wrangler deploy stays allowed (infra/deploy.ts runs it); only whole `delete`/`purge` words make a wrangler delete, so a worker named remove-old still deploys. - scripts/hooks/vcs-policy.ts decodes Claude Code's PreToolUse JSON, Cursor's beforeShellExecution JSON and a bare {command} with one Schema union, tagging each with its harness. Claude and bare denies exit 2 with the reason on stderr (Runtime.errorExitCode on the error, errorReported off); Cursor gets {"permission","user_message", "agent_message"} and exit 0. Unreadable input or any defect is a refusal: it fails closed. - Adapters: .claude/settings.json (PreToolUse on Bash), .cursor/hooks.json (beforeShellExecution, failClosed, no matcher, so every command is judged) and .pi/extensions/vcs-policy (tool_call on bash returns {block, reason}; a local structural type, not pi's package). No lefthook, git hooks or CI (spec D4). - Tests: packages/config/test/vcs-policy.test.ts. A 573-row table: each Want variant as written, in four compounds, after FOO=1, through /usr/bin and through env, plus the allowed rows and the rows past the Want. Six it.live cases run the hook as a process: Claude deny and allow, Cursor deny and allow, bare deny and allow, and four unreadable inputs. Red by assertion first (546 failing against an Allow stub). - Manual proof: `echo '{"tool_input":{"command":"git commit -n -m x"}}' | bun scripts/hooks/vcs-policy.ts; echo $?` prints "vcs-policy refused this command (hook-bypass): Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11)." and 2; wall time 0.10–0.11 s. - pi: the event and result shapes come from pi 1.0.4's dist/core/extensions/types.d.ts, and the extension loads through pi's own jiti 2.7.0 with a stand-in API (git push and cat .env.local blocked; git status and other tools pass). Not run in a live pi session, which needs a model call. - ASSUMPTION: Cursor's payload always carries hook_event_name "beforeShellExecution"; one without it is judged as a bare {command}, whose refusal (exit 2) failClosed also blocks. - Known gaps, written up in the issue: a script piped into a shell, hook-skipping plumbing (commit-tree), commands held in variables, and reads by interpreters. Hooks are early feedback; verify is the authority.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+1841 added−0 removed
- tests:+398 added−0 removed
- other:+1443 added−0 removed
Provenance
- Commit
db67c5b- Tree
d32759b- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
19e6c65
9 files changed+1841 added−0 removed
added:.claude/settings.json+15 added
123456789101112131415{ "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "bun \"${CLAUDE_PROJECT_DIR}/scripts/hooks/vcs-policy.ts\"" } ] } ] }}added:.cursor/hooks.json+11 added
1234567891011{ "version": 1, "hooks": { "beforeShellExecution": [ { "command": "bun scripts/hooks/vcs-policy.ts", "failClosed": true } ] }}added:.pi/extensions/vcs-policy/index.ts+60 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960// Ported from joelhooks/rat-stack@fba26d8 `.pi/extensions/git-interceptor/index.ts`// (MIT, LICENSES/rat-stack.MIT.txt). Changes are listed in PROVENANCE.md./** * pi's side of the hook policy: before pi's bash tool runs a command, ask * `decide`, and block a refused command with its reason. The types below are * the slice of pi's extension API this file uses, checked against pi 1.0.4's * `dist/core/extensions/types.d.ts`; pi itself is not a dependency here. */import { Decision, decide } from "../../../scripts/hooks/lib/policy.ts";
/** pi's `ToolCallEvent`, as far as this extension reads it. */interface ToolCall { readonly toolName: string; readonly input: Readonly<Record<string, unknown>>;}
/** pi's `ToolCallEventResult`: block the call, with a reason for the agent. */interface Block { readonly block: true; readonly reason: string;}
/** pi's `ExtensionAPI`, as far as this extension uses it. */export interface PiApi { on( event: "tool_call", handler: (event: ToolCall) => Block | undefined ): unknown;}
const UNREADABLE: Block = { block: true, reason: "vcs-policy could not read a shell command from this bash call, so it refuses it.",};
const vcsPolicy = (pi: PiApi) => { pi.on("tool_call", (event) => { if (event.toolName !== "bash") { return undefined; }
const { command } = event.input;
if (typeof command !== "string") { return UNREADABLE; }
const decision = decide(command);
return Decision.$is("Deny")(decision) ? { block: true, reason: `vcs-policy refused this command (${decision.rule}): ${decision.reason}`, } : undefined; });};
export default vcsPolicy;added:.pi/extensions/vcs-policy/README.md+2 added
12Blocks a bash tool call the hook policy refuses (hook bypasses, `git push`, deletes, cf's project commands, reads of the closed `.env` files), with the policy's reason; the policy is `scripts/hooks/lib/policy.ts`, shared with the Claude Code and Cursor hooks.pi loads it from `.pi/extensions/vcs-policy/index.ts` when it starts in this repo and the project is trusted; it needs `bun install` first, since the policy imports `effect`.added:packages/config/test/vcs-policy.test.ts+398 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Effect, Path, Schema, Stream } from "effect";4+import { ChildProcess, ChildProcessSpawner } from "effect/process";5+6+import {7+ Decision,8+ decide,9+ reasons,10+} from "../../../scripts/hooks/lib/policy.ts";11+import type { Rule } from "../../../scripts/hooks/lib/policy.ts";12+13+/** What a row expects: the command runs, or the rule that refuses it. */14+type Verdict = "Allow" | Rule;15+16+const verdictOf = (command: string): Verdict => {17+ const decision = decide(command);18+19+ return Decision.$is("Deny")(decision) ? decision.rule : "Allow";20+};21+22+/**23+ * One refused command: `program` is argv[0], so each row is also tried through24+ * a path and through `env`. `lead` is a `VAR=value` word that comes first.25+ * Shell builtins (`source`, `.`) have no path and no `env` form.26+ */27+interface Refused {28+ readonly program: string;29+ readonly args: string;30+ readonly rule: Rule;31+ readonly lead?: string;32+ readonly builtin?: true;33+}34+35+const refused = (36+ rule: Rule,37+ program: string,38+ args: string,39+ lead?: string40+): Refused =>41+ lead === undefined ? { args, program, rule } : { args, lead, program, rule };42+43+/** Every variant the issue's Want names, each refused. */44+const WANT: readonly Refused[] = [45+ // Hook bypass: --no-verify and the unique prefixes git accepts for it.46+ refused("hook-bypass", "git", "commit --no-verify -m x"),47+ refused("hook-bypass", "git", "commit --no-verif -m x"),48+ refused("hook-bypass", "git", "commit --no-veri -m x"),49+ refused("hook-bypass", "git", "commit --no-ver -m x"),50+ // `commit -n` and short-flag bundles that carry it.51+ refused("hook-bypass", "git", "commit -n -m x"),52+ refused("hook-bypass", "git", "commit -nm x"),53+ refused("hook-bypass", "git", "commit -anm x"),54+ refused("hook-bypass", "git", "-c core.hooksPath=/dev/null commit -m x"),55+ refused("hook-bypass", "git", "commit -m x", "LEFTHOOK=0"),56+ refused("hook-bypass", "lefthook", "uninstall"),57+ // Pushes.58+ refused("push", "git", "push"),59+ refused("push", "git", "push origin main"),60+ // Deletes: wrangler's always; cf's without --dry-run.61+ refused("delete", "wrangler", "delete"),62+ refused("delete", "wrangler", "delete my-worker"),63+ refused(64+ "delete",65+ "cf",66+ "artifacts namespaces repos delete x --namespace y --force"67+ ),68+ refused("delete", "cf", "accounts tokens revoke x"),69+ refused(70+ "delete",71+ "bun",72+ "run ops -- artifacts namespaces repos delete x --force"73+ ),74+ refused("delete", "bunx", "wrangler delete"),75+ // cf's project commands, bare and through bunx, npx and `bun run ops --`.76+ ...[77+ "dev",78+ "build",79+ "deploy",80+ "init",81+ "migrate",82+ "previews",83+ "workers versions create",84+ "workers triggers deploy",85+ ].flatMap((command) => [86+ refused("cf-project-command", "cf", command),87+ refused("cf-project-command", "bunx", `cf ${command}`),88+ refused("cf-project-command", "npx", `cf ${command}`),89+ refused("cf-project-command", "bun", `run ops -- ${command}`),90+ ]),91+ // Reads of the closed env files.92+ ...["cat", "head", "tail", "less", "more"].flatMap((program) => [93+ refused("closed-env-read", program, ".env"),94+ refused("closed-env-read", program, ".env.local"),95+ refused("closed-env-read", program, "apps/platform/.env.development.local"),96+ ]),97+ refused("closed-env-read", "sed", "-n 1p .env"),98+ refused("closed-env-read", "awk", "'{ print }' .env.local"),99+ refused("closed-env-read", "grep", "TOKEN .env"),100+ refused("closed-env-read", "rg", "TOKEN .env.production.local"),101+ { args: ".env", builtin: true, program: "source", rule: "closed-env-read" },102+ { args: ".env.local", builtin: true, program: ".", rule: "closed-env-read" },103+];104+105+/** A refused row as written, inside compounds, through a path and through `env`. */106+const forms = (row: Refused): readonly string[] => {107+ const lead = row.lead === undefined ? "" : `${row.lead} `;108+ const plain = `${lead}${row.program} ${row.args}`;109+110+ const compounds = [111+ plain,112+ `cd x && ${plain}`,113+ `true; ${plain}`,114+ `(${plain})`,115+ `FOO=1 ${plain}`,116+ ];117+118+ return row.builtin === true119+ ? compounds120+ : [121+ ...compounds,122+ `${lead}/usr/bin/${row.program} ${row.args}`,123+ `env ${plain}`,124+ ];125+};126+127+describe(decide, () => {128+ it.each(129+ WANT.flatMap((row) => forms(row).map((command) => [command, row.rule]))130+ )("refuses %s (%s)", (command, rule) => {131+ expect(verdictOf(command)).toBe(rule);132+ });133+134+ // Rows past the Want. Where the right answer was unclear, the row denies, and135+ // the comment says why.136+ it.each<readonly [string, Verdict]>([137+ // The value of -m is a message even when it looks like a flag; git takes it138+ // whole, so the commit still runs its hooks.139+ ['git commit -m "no-verify docs"', "Allow"],140+ ['git commit -m "skip --no-verify in docs"', "Allow"],141+ ["git commit -m --no-verify", "Allow"],142+ ["git commit -mn", "Allow"],143+ ["git commit --amend --no-edit", "Allow"],144+ ["git commit -am x # --no-verify", "Allow"],145+ ["git log -n 5", "Allow"],146+ ['git log --grep="--no-verify"', "Allow"],147+ ["git --no-pager log -n 5", "Allow"],148+ ["git merge -n main", "Allow"],149+ ["git stash push -m x", "Allow"],150+ ["git config --get core.hooksPath", "Allow"],151+ // Quoting and escapes don't hide a flag from the shell, so not from us.152+ ['git commit "--no-verify" -m x', "hook-bypass"],153+ ['git commit --no-""verify -m x', "hook-bypass"],154+ ["git commit --no-\\verify -m x", "hook-bypass"],155+ ["git commit $'\\x2d\\x2dno-verify' -m x", "hook-bypass"],156+ ["git --no-pager -C repo commit -n -m x", "hook-bypass"],157+ ["git -c CORE.HOOKSPATH= commit -m x", "hook-bypass"],158+ ["git --config-env=core.hooksPath=HOOKS commit -m x", "hook-bypass"],159+ ["git config core.hooksPath /dev/null", "hook-bypass"],160+ // An alias can wrap --no-verify or a push, and nothing here can see it.161+ ["git -c alias.ci='commit --no-verify' ci -m x", "hook-bypass"],162+ ['git config alias.ci "commit --no-verify"', "hook-bypass"],163+ ["git merge --no-verify main", "hook-bypass"],164+ ["git am -n patch.mbox", "hook-bypass"],165+ ["export LEFTHOOK=0", "hook-bypass"],166+ ["HUSKY=0 git commit -m x", "hook-bypass"],167+ [168+ "GIT_CONFIG_PARAMETERS=\"'core.hooksPath'='/dev/null'\" git commit -m x",169+ "hook-bypass",170+ ],171+ ["bunx lefthook uninstall", "hook-bypass"],172+ // Help never pushes: git turns `<cmd> --help` into `git help <cmd>`.173+ ["git push --help", "Allow"],174+ ["git help push", "Allow"],175+ // A dry run still talks to a remote, and pushing is the user's step.176+ ["git push --dry-run", "push"],177+ ["git -C repo push", "push"],178+ ["jj git push", "push"],179+ // What a shell runs inside a substitution, `-c`, `eval` or a heredoc runs.180+ ['echo "$(git push)"', "push"],181+ ["echo `git push`", "push"],182+ ['bash -c "git push"', "push"],183+ ["sh -lc 'git commit -n -m x'", "hook-bypass"],184+ ['eval "git push"', "push"],185+ ["bash <<'EOF'\ngit push\nEOF", "push"],186+ ["xargs git push < refs.txt", "push"],187+ ["sudo -u root git push", "push"],188+ ["timeout 5 git push", "push"],189+ // Text that only mentions a command is not the command.190+ ['echo "git push"', "Allow"],191+ ["cat <<'EOF'\ngit push\nEOF", "Allow"],192+ [193+ "git commit -F - <<'EOF'\nSubject\n\n- Don't --no-verify, and don't git push\nEOF",194+ "Allow",195+ ],196+ [197+ "git commit -m \"$(cat <<'EOF'\nSubject\n\n- Don't git push\nEOF\n)\"",198+ "Allow",199+ ],200+ // wrangler deploy stays allowed: infra/deploy.ts runs it, and the stage201+ // rule lives there. wrangler delete is refused even as a dry run.202+ ["wrangler deploy", "Allow"],203+ ["wrangler deploy --dry-run", "Allow"],204+ ["wrangler deploy --name remove-old", "Allow"],205+ ["wrangler delete --dry-run", "delete"],206+ ["wrangler queues purge jobs", "delete"],207+ ["npx wrangler@4.147.0 delete x", "delete"],208+ ["./node_modules/.bin/wrangler d1 delete db", "delete"],209+ ["bun run ops -- artifacts namespaces repos delete x --dry-run", "Allow"],210+ ["bun run ops -- workers list", "Allow"],211+ ["bun run ops -- zones purge-cache x", "delete"],212+ ["bun run ops -- workers delete x --dry-run=false", "delete"],213+ // cf's project commands are refused even as dry runs, and through varlock.214+ ["cf deploy --dry-run", "cf-project-command"],215+ ["cf --profile dev deploy", "cf-project-command"],216+ ["bunx varlock run --path infra/ -- cf deploy", "cf-project-command"],217+ ["bun run verify", "Allow"],218+ ["bun infra/deploy.ts --stage demo", "Allow"],219+ // The closed env files, by any path, glob or redirect. Their schemas and220+ // examples stay open, and so does searching other files for the name.221+ ["cat .env.schema", "Allow"],222+ ["cat apps/platform/.env.schema", "Allow"],223+ ["cat .env.example", "Allow"],224+ ["ls -la .env*", "Allow"],225+ ["grep -n .env .gitignore", "Allow"],226+ ["rg -n '\\.env' docs", "Allow"],227+ ["cat < .env", "closed-env-read"],228+ ["while read -r line; do echo $line; done < .env.local", "closed-env-read"],229+ ["cat ./.env", "closed-env-read"],230+ ['cat "$HOME/project/.env"', "closed-env-read"],231+ ["cat .env*", "closed-env-read"],232+ ["cat .env{,.local}", "closed-env-read"],233+ ["grep -e TOKEN .env", "closed-env-read"],234+ ["grep -A 2 TOKEN .env", "closed-env-read"],235+ ["grep -f .env other.txt", "closed-env-read"],236+ ["cp .env /tmp/x", "closed-env-read"],237+ ["set -a; . ./.env; set +a", "closed-env-read"],238+ ["bun run env:check", "Allow"],239+ ])("%s → %s", (command, verdict) => {240+ expect(verdictOf(command)).toBe(verdict);241+ });242+243+ it("gives each refusal one sentence from AGENTS.md, saying what to do instead", () => {244+ expect(decide("git commit -n -m x")).toStrictEqual(245+ Decision.Deny({246+ reason:247+ "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",248+ rule: "hook-bypass",249+ })250+ );251+ expect(reasons).toStrictEqual({252+ "cf-project-command":253+ "cf's project commands are not our deploy tool; use infra/deploy.ts.",254+ "closed-env-read":255+ "Never read .env, .env.local or .env.*.local; run bun run env:check.",256+ delete: "Deleting Cloudflare resources needs the user's OK.",257+ "hook-bypass":258+ "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",259+ push: "Pushing is the user's step; commit on the branch and stop.",260+ });261+ expect(decide("git status")).toStrictEqual(Decision.Allow());262+ });263+});264+265+// Vitest runs in the package's folder, two below the repo root.266+const repoRoot = Effect.map(Path.Path, (path) => path.resolve("..", ".."));267+268+interface Ran {269+ readonly exitCode: number;270+ readonly stdout: string;271+ readonly stderr: string;272+}273+274+const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>275+ bytes.pipe(Stream.decodeText(), Stream.mkString);276+277+/** Runs the hook as a harness does: `input` on stdin, then stdin closes. */278+const hook = (input: string) =>279+ Effect.scoped(280+ Effect.gen(function* () {281+ const path = yield* Path.Path;282+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;283+ const root = yield* repoRoot;284+285+ const child = yield* spawner.spawn(286+ ChildProcess.make(287+ "bun",288+ [path.join(root, "scripts/hooks/vcs-policy.ts")],289+ {290+ cwd: root,291+ stdin: Stream.make(new TextEncoder().encode(input)),292+ }293+ )294+ );295+296+ const [stdout, stderr, exitCode] = yield* Effect.all(297+ [text(child.stdout), text(child.stderr), child.exitCode],298+ { concurrency: "unbounded" }299+ );300+301+ return { exitCode, stderr, stdout } satisfies Ran;302+ })303+ ).pipe(Effect.provide(NodeServices.layer));304+305+const CursorReply = Schema.fromJsonString(306+ Schema.Struct({307+ agent_message: Schema.optionalKey(Schema.String),308+ permission: Schema.Literals(["allow", "deny"]),309+ user_message: Schema.optionalKey(Schema.String),310+ })311+);312+313+const claude = (command: string) =>314+ JSON.stringify({315+ hook_event_name: "PreToolUse",316+ session_id: "s",317+ tool_input: { command, description: "d" },318+ tool_name: "Bash",319+ });320+321+const cursor = (command: string) =>322+ JSON.stringify({323+ command,324+ conversation_id: "c",325+ cwd: "/repo",326+ hook_event_name: "beforeShellExecution",327+ });328+329+const PUSH = "Pushing is the user's step; commit on the branch and stop.";330+331+describe("the hook adapter", () => {332+ it.live("denies for Claude Code by exit 2, with the reason on stderr", () =>333+ Effect.gen(function* () {334+ const ran = yield* hook(claude("git commit -n -m x"));335+336+ expect(ran.exitCode).toBe(2);337+ expect(ran.stdout).toBe("");338+ expect(ran.stderr).toContain(339+ "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11)."340+ );341+ })342+ );343+344+ it.live("allows for Claude Code by exit 0, saying nothing", () =>345+ Effect.gen(function* () {346+ expect(yield* hook(claude("git status"))).toStrictEqual({347+ exitCode: 0,348+ stderr: "",349+ stdout: "",350+ });351+ })352+ );353+354+ it.live("denies for Cursor with its JSON reply, and exits 0", () =>355+ Effect.gen(function* () {356+ const ran = yield* hook(cursor("git push"));357+ const reply = yield* Schema.decodeEffect(CursorReply)(ran.stdout);358+359+ expect(ran.exitCode).toBe(0);360+ expect(reply.permission).toBe("deny");361+ expect(reply.user_message).toContain(PUSH);362+ expect(reply.agent_message).toContain(PUSH);363+ })364+ );365+366+ it.live("allows for Cursor with its JSON reply", () =>367+ Effect.gen(function* () {368+ const ran = yield* hook(cursor("git status"));369+370+ expect(ran.exitCode).toBe(0);371+ expect(yield* Schema.decodeEffect(CursorReply)(ran.stdout)).toStrictEqual(372+ { permission: "allow" }373+ );374+ })375+ );376+377+ it.live("judges a bare {command}, denying by exit 2", () =>378+ Effect.gen(function* () {379+ const denied = yield* hook(JSON.stringify({ command: "git push" }));380+ const allowed = yield* hook(JSON.stringify({ command: "git status" }));381+382+ expect(denied.exitCode).toBe(2);383+ expect(denied.stderr).toContain(PUSH);384+ expect(allowed.exitCode).toBe(0);385+ })386+ );387+388+ it.live("denies input it cannot read, failing closed", () =>389+ Effect.gen(function* () {390+ for (const input of ["not json", "{}", '{"command":7}', ""]) {391+ const ran = yield* hook(input);392+393+ expect(ran.exitCode).toBe(2);394+ expect(ran.stderr).toContain("could not read");395+ }396+ })397+ );398+});added:scripts/hooks/lib/argv.ts+134 added
1+/**2+ * Reads one command's argv: which words are options, the values they take,3+ * and which are operands. A program's `Grammar` names its options that take a4+ * value; any option it doesn't name is taken to stand alone, which can only5+ * turn a value into an option the policy judges, never hide one.6+ */7+8+/** A table of names, written as one space-separated line. */9+export const names = (line: string): ReadonlySet<string> =>10+ new Set(line.split(" ").filter((name) => name.length > 0));11+12+/** Which options take a value, for one program. */13+export interface Grammar {14+ /** Options whose value is the next word unless attached: `-m`, `--message`. */15+ readonly values: ReadonlySet<string>;16+ /** Short options whose value, if any, is attached: `-S[keyid]`. */17+ readonly attached: ReadonlySet<string>;18+}19+20+export interface Parsed {21+ /** Each option by name: `-n`, `--no-verify`; a bundle `-anm` gives three. */22+ readonly options: readonly string[];23+ /** Each option that took a value, with that value. */24+ readonly values: readonly (readonly [option: string, value: string])[];25+ readonly operands: readonly string[];26+}27+28+export const grammar = (values: string, attached = ""): Grammar => ({29+ attached: names(attached),30+ values: names(values),31+});32+33+export const NO_OPTIONS = grammar("");34+35+/** What one word of bundled short options holds. */36+interface Bundle {37+ readonly options: readonly string[];38+ /** The value the last option took, attached or from the next word. */39+ readonly value?: string;40+ /** Whether that value was the next word. */41+ readonly takesNext: boolean;42+}43+44+/** A bundle of short options, `-anm x`, `-mx`, `-Skey`: each letter, and a value if one takes it. */45+const bundle = (46+ arg: string,47+ next: string | undefined,48+ rules: Grammar49+): Bundle => {50+ const options: string[] = [];51+52+ for (let offset = 1; offset < arg.length; offset += 1) {53+ const option = `-${arg[offset] ?? ""}`;54+ const rest = arg.slice(offset + 1);55+56+ options.push(option);57+58+ if (rules.values.has(option) && rest.length === 0) {59+ return next === undefined60+ ? { options, takesNext: false }61+ : { options, takesNext: true, value: next };62+ }63+64+ if (rules.values.has(option) || rules.attached.has(option)) {65+ return { options, takesNext: false, value: rest };66+ }67+ }68+69+ return { options, takesNext: false };70+};71+72+/**73+ * Splits `args` into options, the values they take, and operands. With74+ * `permute`, options may follow operands, as git and GNU tools allow; without75+ * it, the first operand and everything after it are operands, as a wrapper76+ * hands them to the command it runs.77+ */78+export const parse = (79+ args: readonly string[],80+ rules: Grammar,81+ permute: boolean82+): Parsed => {83+ const options: string[] = [];84+ const values: (readonly [string, string])[] = [];85+ const operands: string[] = [];86+ let index = 0;87+88+ while (index < args.length) {89+ const arg = args[index] ?? "";90+ const next = args[index + 1];91+92+ index += 1;93+94+ if (arg === "--") {95+ operands.push(...args.slice(index));96+ break;97+ }98+99+ if (!arg.startsWith("-") || arg === "-") {100+ operands.push(...(permute ? [arg] : args.slice(index - 1)));101+102+ if (!permute) {103+ break;104+ }105+ } else if (arg.startsWith("--")) {106+ const equals = arg.indexOf("=");107+ const name = equals === -1 ? arg : arg.slice(0, equals);108+109+ const takesNext =110+ equals === -1 && rules.values.has(name) && next !== undefined;111+112+ options.push(name);113+114+ if (equals !== -1) {115+ values.push([name, arg.slice(equals + 1)]);116+ } else if (takesNext) {117+ values.push([name, next]);118+ index += 1;119+ }120+ } else {121+ const short = bundle(arg, next, rules);122+123+ options.push(...short.options);124+125+ if (short.value !== undefined) {126+ values.push([short.options.at(-1) ?? "", short.value]);127+ }128+129+ index += short.takesNext ? 1 : 0;130+ }131+ }132+133+ return { operands, options, values };134+};added:scripts/hooks/lib/policy.ts+640 added
1+// Ported from joelhooks/rat-stack@fba26d8 `scripts/vcs-command-policy.js`2+// (MIT, LICENSES/rat-stack.MIT.txt). Changes are listed in PROVENANCE.md.3+/**4+ * The hook policy. Each agent harness asks it about a shell command before the5+ * command runs (`scripts/hooks/vcs-policy.ts` for Claude Code and Cursor,6+ * `.pi/extensions/vcs-policy` for pi). It allows or denies; it never rewrites.7+ *8+ * It reads the command as a shell would (`./shell.ts`): simple commands,9+ * quotes and escapes, and what runs inside `$(…)`, backticks, `sh -c`, `eval`10+ * and a heredoc fed to a shell. Each simple command then loses its leading11+ * `VAR=value` words, wrappers (`env`, `command`, `exec`, `sudo`, …), package12+ * runners (`bunx`, `npx`, `bun run ops --`, …) and any path on argv[0], and is13+ * judged by its argv (`./argv.ts`), so flag text inside a quoted `-m` message14+ * is a message. Where a command's meaning is unclear, the policy denies.15+ *16+ * Pure, with no Effect runtime: Bun, Node and pi's loader all import it.17+ */18+import { Data, Option } from "effect";19+20+import { grammar, names, NO_OPTIONS, parse } from "./argv.ts";21+import type { Grammar, Parsed } from "./argv.ts";22+import { simpleCommands, wordsOf } from "./shell.ts";23+24+/** The rules, each from AGENTS.md. */25+export type Rule =26+ | "hook-bypass"27+ | "push"28+ | "delete"29+ | "cf-project-command"30+ | "closed-env-read";31+32+export type Decision =33+ | { readonly _tag: "Allow" }34+ | { readonly _tag: "Deny"; readonly rule: Rule; readonly reason: string };35+36+export const Decision = Data.taggedEnum<Decision>();37+38+/** One sentence per rule: what AGENTS.md says, and what to do instead. */39+export const reasons = {40+ "cf-project-command":41+ "cf's project commands are not our deploy tool; use infra/deploy.ts.",42+ "closed-env-read":43+ "Never read .env, .env.local or .env.*.local; run bun run env:check.",44+ delete: "Deleting Cloudflare resources needs the user's OK.",45+ "hook-bypass":46+ "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",47+ push: "Pushing is the user's step; commit on the branch and stop.",48+} as const satisfies Readonly<Record<Rule, string>>;49+50+/** The rule a command breaks, or none. */51+type Verdict = Option.Option<Rule>;52+53+const breaks = (rule: Rule, when: boolean): Verdict =>54+ when ? Option.some(rule) : Option.none();55+56+const basename = (word: string) => word.slice(word.lastIndexOf("/") + 1);57+58+/** `wrangler@4.147.0` → `wrangler`; `@scope/pkg@1` → `@scope/pkg`. */59+const withoutVersion = (name: string) => name.replace(/(?<=.)@[^/]*$/u, "");60+61+const contains = (62+ words: readonly string[],63+ sequence: readonly string[]64+): boolean =>65+ words.some((_, index) =>66+ sequence.every((word, offset) => words[index + offset] === word)67+ );68+69+// ---------------------------------------------------------------------------70+// The rules.71+// ---------------------------------------------------------------------------72+73+// hook-bypass -----------------------------------------------------------------74+75+/** Environment switches that turn a hook manager off. */76+const HOOK_SWITCHES = names("HUSKY LEFTHOOK LEFTHOOK_EXCLUDE");77+78+const ASSIGNMENT = /^[A-Za-z_]\w*=/u;79+80+/** `LEFTHOOK=0`, `HUSKY=0`, or anything that sets `core.hooksPath`. */81+const switchesOffHooks = (assignment: string) =>82+ HOOK_SWITCHES.has(assignment.slice(0, assignment.indexOf("="))) ||83+ /hookspath/iu.test(assignment);84+85+/**86+ * A git config key that can skip hooks: `core.hooksPath`, or an alias, which87+ * can wrap `--no-verify` or a push where nothing here can see it.88+ */89+const overridesHooks = (setting: string) => {90+ const key = setting.split("=")[0]?.toLowerCase() ?? "";91+92+ return key === "core.hookspath" || key.startsWith("alias.");93+};94+95+/** `--no-verify`, or a prefix git may accept for it (`--no-verif`, `--no-ver`). */96+const isNoVerify = (option: string) =>97+ option.length >= "--no-v".length && "--no-verify".startsWith(option);98+99+// Options before git's subcommand that take a value.100+const GIT = grammar(101+ "-C -c --attr-source --config-env --git-dir --list-cmds --namespace --super-prefix --work-tree"102+);103+104+// Subcommands where `-n` means `--no-verify`, with the options that take a105+// value, so `-m -n` is a message and `-nm x` is not.106+const NO_VERIFY_SHORT: ReadonlyMap<string, Grammar> = new Map([107+ [108+ "am",109+ grammar(110+ "--directory --empty --exclude --include --patch-format --quoted-cr --resolvemsg --whitespace",111+ "-C -S -p"112+ ),113+ ],114+ [115+ "commit",116+ grammar(117+ "-C -F -c -m -t --author --cleanup --date --file --fixup --message --pathspec-from-file --reedit-message --reuse-message --squash --template --trailer",118+ "-S -u"119+ ),120+ ],121+]);122+123+// `git config` forms that only read.124+const CONFIG_READS = names(125+ "--get --get-all --get-color --get-colorbool --get-regexp --get-urlmatch --list -l"126+);127+128+const writesHookConfig = (parsed: Parsed) => {129+ const reads =130+ parsed.options.some((option) => CONFIG_READS.has(option)) ||131+ ["get", "list"].includes(parsed.operands[0] ?? "");132+133+ return !reads && parsed.operands.some(overridesHooks);134+};135+136+/** What git's subcommand, after the global options, breaks. */137+const judgeGitSubcommand = (138+ subcommand: string,139+ rest: readonly string[]140+): Verdict => {141+ if (142+ subcommand === "push" ||143+ subcommand === "send-pack" ||144+ (subcommand === "subtree" && rest.includes("push"))145+ ) {146+ return Option.some("push");147+ }148+149+ const shortForm = NO_VERIFY_SHORT.get(subcommand);150+ const parsed = parse(rest, shortForm ?? NO_OPTIONS, true);151+152+ return breaks(153+ "hook-bypass",154+ parsed.options.some(isNoVerify) ||155+ (shortForm !== undefined && parsed.options.includes("-n")) ||156+ (subcommand === "config" && writesHookConfig(parsed))157+ );158+};159+160+const judgeGit = (args: readonly string[]): Verdict => {161+ const global = parse(args, GIT, false);162+163+ const settings = global.values.flatMap(([option, value]) =>164+ option === "-c" || option === "--config-env" ? [value] : []165+ );166+167+ const [subcommand, ...rest] = global.operands;168+169+ if (settings.some(overridesHooks)) {170+ return Option.some("hook-bypass");171+ }172+173+ // git runs `git <cmd> --help` as `git help <cmd>`.174+ return subcommand === undefined || rest[0] === "--help"175+ ? Option.none()176+ : judgeGitSubcommand(subcommand, rest);177+};178+179+const judgeLefthook = (args: readonly string[]): Verdict =>180+ breaks(181+ "hook-bypass",182+ parse(args, NO_OPTIONS, true).operands.includes("uninstall")183+ );184+185+// push ------------------------------------------------------------------------186+187+const judgeJj = (args: readonly string[]): Verdict =>188+ breaks(189+ "push",190+ contains(parse(args, NO_OPTIONS, true).operands, ["git", "push"])191+ );192+193+// delete ----------------------------------------------------------------------194+195+/**196+ * wrangler's deleting subcommands are all `delete` or `purge`, and it deletes197+ * without asking when it runs without a terminal. Only whole words count, so a198+ * deploy whose name says `remove` still deploys.199+ */200+const WRANGLER_DELETES = names("delete purge");201+202+const judgeWrangler = (args: readonly string[]): Verdict =>203+ breaks(204+ "delete",205+ parse(args, NO_OPTIONS, true).operands.some((word) =>206+ WRANGLER_DELETES.has(word)207+ )208+ );209+210+/** A cf command word that deletes: `delete`, `bulk-delete`, `revoke`, `purge`… */211+const DESTRUCTIVE = /(?:^|-)(?:delete|destroy|purge|remove|revoke)(?:-|$)/u;212+213+// cf-project-command ----------------------------------------------------------214+215+// cf's global options that take a value.216+const CF = grammar("-m -z --mode --persist-to --profile --zone");217+218+const CF_PROJECT = names("build deploy dev init migrate previews");219+220+const CF_PROJECT_SEQUENCES: readonly (readonly string[])[] = [221+ ["workers", "triggers", "deploy"],222+ ["workers", "versions", "create"],223+];224+225+const judgeCf = (args: readonly string[]): Verdict => {226+ const parsed = parse(args, CF, true);227+ const [first = "", second = ""] = parsed.operands;228+ // An option cf doesn't declare may take the next word as its value.229+ const optionFirst = args[0]?.startsWith("-") === true;230+231+ if (232+ CF_PROJECT.has(first) ||233+ (optionFirst && CF_PROJECT.has(second)) ||234+ CF_PROJECT_SEQUENCES.some((sequence) => contains(parsed.operands, sequence))235+ ) {236+ return Option.some("cf-project-command");237+ }238+239+ const dryRun =240+ parsed.options.includes("--dry-run") &&241+ parsed.values.every(242+ ([option, value]) => option !== "--dry-run" || value !== "false"243+ );244+245+ return breaks(246+ "delete",247+ !dryRun && parsed.operands.some((word) => DESTRUCTIVE.test(word))248+ );249+};250+251+// closed-env-read -------------------------------------------------------------252+253+/** One name for each closed shape, for testing globs against. */254+const CLOSED_SAMPLES = [".env", ".env.local", ".env.development.local"];255+256+const isClosedName = (name: string) =>257+ name === ".env" || name === ".env.local" || /^\.env\..+\.local$/u.test(name);258+259+const GLOB = /[*?[]/u;260+261+const REGEXP_SPECIAL = /[$()*+.?[\\\]^{|}]/u;262+263+const globPart = (part: string) => {264+ if (part === "*") {265+ return ".*";266+ }267+268+ if (part === "?" || part.startsWith("[")) {269+ return ".";270+ }271+272+ return REGEXP_SPECIAL.test(part) ? `\\${part}` : part;273+};274+275+/**276+ * Whether a shell glob could match `name`. A bracket matches any one277+ * character, which only widens the match; a leading `*` never matches a278+ * dotfile, as in a shell without `dotglob`.279+ */280+const globMatches = (pattern: string, name: string) =>281+ pattern.startsWith(".") &&282+ new RegExp(283+ `^${pattern.replaceAll(/\[[^\]]*\]|[\s\S]/gu, globPart)}$`,284+ "u"285+ ).test(name);286+287+/** `a{b,c}d` → `abd`, `acd`, as a shell expands braces. */288+const braces = (word: string): readonly string[] => {289+ const match = /\{(?<options>[^{}]*,[^{}]*)\}/u.exec(word);290+291+ if (match === null) {292+ return [word];293+ }294+295+ const before = word.slice(0, match.index);296+ const after = word.slice(match.index + match[0].length);297+298+ return (match.groups?.options ?? "")299+ .split(",")300+ .flatMap((option) => braces(`${before}${option}${after}`));301+};302+303+/** Whether `word`, or the part after its first `=`, names a closed env file. */304+const namesClosedEnv = (word: string) =>305+ [word, word.slice(word.indexOf("=") + 1)].some((value) =>306+ braces(value).some((path) => {307+ const name = basename(path.replace(/\/+$/u, ""));308+309+ return GLOB.test(name)310+ ? CLOSED_SAMPLES.some((sample) => globMatches(name, sample))311+ : isClosedName(name);312+ })313+ );314+315+/**316+ * A reader whose first operand is a pattern or a script, not a file, unless317+ * one of `instead` supplies it.318+ */319+interface PatternFirst {320+ readonly grammar: Grammar;321+ readonly instead: ReadonlySet<string>;322+}323+324+const GREP: PatternFirst = {325+ grammar: grammar(326+ "-A -B -C -D -d -e -f -m --after-context --before-context --binary-files --context --devices --directories --exclude --exclude-dir --exclude-from --file --include --label --max-count --regexp"327+ ),328+ instead: names("-e -f --file --regexp"),329+};330+331+const AWK: PatternFirst = {332+ grammar: grammar(333+ "-E -F -W -f -i -l -v --assign --exec --field-separator --file --include --load"334+ ),335+ instead: names("-E -f --exec --file"),336+};337+338+const RG: PatternFirst = {339+ grammar: grammar(340+ "-A -B -C -E -M -T -d -e -f -g -j -m -r -t --after-context --before-context --color --colors --context --context-separator --encoding --engine --file --glob --iglob --ignore-file --max-columns --max-count --max-depth --max-filesize --path-separator --pre --pre-glob --regexp --replace --sort --sortr --threads --type --type-add --type-not"341+ ),342+ instead: names("-e -f --file --files --regexp --type-list"),343+};344+345+const SED: PatternFirst = {346+ grammar: grammar("-e -f -l --expression --file --line-length", "-i"),347+ instead: names("-e -f --expression --file"),348+};349+350+const PATTERN_FIRST: ReadonlyMap<string, PatternFirst> = new Map([351+ ["awk", AWK],352+ ["egrep", GREP],353+ ["fgrep", GREP],354+ ["gawk", AWK],355+ ["grep", GREP],356+ ["mawk", AWK],357+ ["nawk", AWK],358+ ["rg", RG],359+ ["sed", SED],360+ ["zgrep", GREP],361+]);362+363+/** Commands that read or copy the files they name. */364+const READERS = new Set([365+ ...names(366+ ". ack ag base64 bat batcat cat cmp cp cut dd diff emacs head hexdump jq less more most nano nl nvim od paste rsync scp sort source strings tac tail uniq vi view vim wc xxd yq"367+ ),368+ ...PATTERN_FIRST.keys(),369+]);370+371+const judgeRead = (program: string, args: readonly string[]): Verdict => {372+ const patternFirst = PATTERN_FIRST.get(program);373+ const parsed = parse(args, patternFirst?.grammar ?? NO_OPTIONS, true);374+375+ const skipsFirst =376+ patternFirst !== undefined &&377+ !parsed.options.some((option) => patternFirst.instead.has(option));378+379+ const files = [380+ ...parsed.values.map(([, value]) => value),381+ ...(skipsFirst ? parsed.operands.slice(1) : parsed.operands),382+ ];383+384+ return breaks("closed-env-read", files.some(namesClosedEnv));385+};386+387+// ---------------------------------------------------------------------------388+// What actually runs: wrappers, shells and package runners.389+// ---------------------------------------------------------------------------390+391+/** Reserved words that may open a simple command: `if git push; then`. */392+const KEYWORDS = names("! do elif else if then until while { }");393+394+const DECLARATIONS = names("declare export local readonly typeset");395+396+const SHELLS = names("ash bash dash fish ksh sh zsh");397+398+const SHELL = grammar("-o --init-file --rcfile");399+400+/** Commands that run the command in their operands, with the options they take. */401+const WRAPPERS: ReadonlyMap<string, Grammar> = new Map([402+ ["builtin", NO_OPTIONS],403+ ["command", NO_OPTIONS],404+ ["doas", grammar("-C -a -u")],405+ ["env", grammar("-C -P -S -u --chdir --split-string --unset")],406+ ["exec", grammar("-a")],407+ ["nice", grammar("-n --adjustment")],408+ ["nohup", NO_OPTIONS],409+ ["stdbuf", grammar("-e -i -o --error --input --output")],410+ [411+ "sudo",412+ grammar(413+ "-C -D -R -T -U -g -h -p -r -t -u --chdir --chroot --close-from --command-timeout --group --host --other-user --prompt --role --type --user"414+ ),415+ ],416+ ["time", grammar("-f -o --format --output")],417+ ["timeout", grammar("-k -s --kill-after --signal")],418+ [419+ "xargs",420+ grammar(421+ "-E -I -L -P -a -d -n -s --arg-file --delimiter --eof --max-args --max-chars --max-lines --max-procs --process-slot-var --replace",422+ "-e -i -l"423+ ),424+ ],425+]);426+427+/** The command a wrapper runs: `sudo -u root git push` → `git push`. */428+const wrapped = (program: string, args: readonly string[]) => {429+ const parsed = parse(args, WRAPPERS.get(program) ?? NO_OPTIONS, false);430+431+ // `env -S 'git push'` splits its string into words.432+ const split = parsed.values.flatMap(([option, value]) =>433+ option === "-S" || option === "--split-string" ? wordsOf(value) : []434+ );435+436+ // `timeout 5 git push`: the duration comes first.437+ const operands =438+ program === "timeout" ? parsed.operands.slice(1) : parsed.operands;439+440+ return [...split, ...operands];441+};442+443+const LAUNCHER = grammar("-p --package");444+445+const NPX = grammar("-c -p -w --call --package --workspace");446+447+const BUN = grammar(448+ "-F -c -d -e -l -p -r --conditions --config --cwd --define --elide-lines --env-file --eval --filter --import --loader --preload --print --require --shell --tsconfig-override"449+);450+451+// `bun -e` runs JavaScript, which is past what this policy can read.452+const EVALUATES = names("-e -p --eval --print");453+454+const PACKAGE_MANAGER = grammar(455+ "-C -F -w --cwd --dir --filter --prefix --workspace"456+);457+458+const VARLOCK = grammar("-p --env --path");459+460+const SCRIPT_RUNS = names("run run-script");461+462+const PACKAGE_RUNS = names("dlx exec x");463+464+/** A launched package's command: `wrangler@4 delete` → `wrangler delete`. */465+const launched = ([name = "", ...rest]: readonly string[]) => [466+ withoutVersion(name),467+ ...rest,468+];469+470+/** What `npx` and its kin run: a package's bin, or `-c`'s script. */471+const npx = (args: readonly string[]): readonly string[] => {472+ const parsed = parse(args, NPX, false);473+474+ const call = parsed.values.find(475+ ([option]) => option === "-c" || option === "--call"476+ );477+478+ return call === undefined ? launched(parsed.operands) : ["sh", "-c", call[1]];479+};480+481+/**482+ * A package script, or a file or bin run by name. `ops` is the root script483+ * `varlock run --path infra/ -- cf`, so `bun run ops -- x` runs `cf x`.484+ */485+const script = ([name = "", ...rest]: readonly string[]) => {486+ const args = rest[0] === "--" ? rest.slice(1) : rest;487+488+ return name === "ops" ? ["cf", ...args] : [name, ...args];489+};490+491+/** What bun, npm, pnpm or yarn runs, if anything. */492+const packageManagerRuns = (493+ program: string,494+ args: readonly string[]495+): Option.Option<readonly string[]> => {496+ const parsed = parse(args, program === "bun" ? BUN : PACKAGE_MANAGER, false);497+ const [subcommand = "", ...rest] = parsed.operands;498+499+ if (parsed.options.some((option) => EVALUATES.has(option))) {500+ return Option.none();501+ }502+503+ if (program === "bun" && subcommand === "exec") {504+ return Option.some(["sh", "-c", rest.join(" ")]);505+ }506+507+ if (SCRIPT_RUNS.has(subcommand)) {508+ return Option.some(script(parse(rest, PACKAGE_MANAGER, false).operands));509+ }510+511+ if (PACKAGE_RUNS.has(subcommand)) {512+ return Option.some(npx(rest));513+ }514+515+ // npm runs scripts only through `run`; bun, pnpm and yarn take a bare name.516+ return program === "npm"517+ ? Option.none()518+ : Option.some(script(parsed.operands));519+};520+521+/** The command a package runner runs, as words, if it runs one. */522+const runs = (523+ program: string,524+ args: readonly string[]525+): Option.Option<readonly string[]> => {526+ if (program === "bunx" || program === "pnpx") {527+ return Option.some(launched(parse(args, LAUNCHER, false).operands));528+ }529+530+ if (program === "npx") {531+ return Option.some(npx(args));532+ }533+534+ if (program === "varlock") {535+ const [subcommand, ...rest] = parse(args, VARLOCK, false).operands;536+537+ return subcommand === "run"538+ ? Option.some(parse(rest, VARLOCK, false).operands)539+ : Option.none();540+ }541+542+ return packageManagerRuns(program, args);543+};544+545+const PACKAGE_RUNNERS = names("bun bunx npm npx pnpm pnpx varlock yarn");546+547+const PROGRAMS: ReadonlyMap<string, (args: readonly string[]) => Verdict> =548+ new Map([549+ ["cf", judgeCf],550+ ["git", judgeGit],551+ ["jj", judgeJj],552+ ["lefthook", judgeLefthook],553+ ["wrangler", judgeWrangler],554+ ]);555+556+type Judge = (command: string) => Verdict;557+558+/** A shell runs `-c`'s script, or with no script operand, the one on stdin. */559+const judgeShell = (560+ args: readonly string[],561+ stdin: readonly string[],562+ judge: Judge563+): Verdict => {564+ const parsed = parse(args, SHELL, false);565+566+ const scripts = parsed.options.includes("-c")567+ ? parsed.operands.slice(0, 1)568+ : stdin;569+570+ return Option.firstSomeOf(scripts.map(judge));571+};572+573+/**574+ * The rule one simple command breaks, if any. `judge` reads a nested script,575+ * such as `sh -c`'s.576+ */577+const judgeWords = (578+ words: readonly string[],579+ stdin: readonly string[],580+ judge: Judge581+): Verdict => {582+ const leading = words.findIndex((word) => !ASSIGNMENT.test(word));583+ const assignments = leading === -1 ? words : words.slice(0, leading);584+ const [head = "", ...args] = leading === -1 ? [] : words.slice(leading);585+ const program = basename(head);586+587+ if (assignments.some(switchesOffHooks)) {588+ return Option.some("hook-bypass");589+ }590+591+ if (KEYWORDS.has(program)) {592+ return judgeWords(args, stdin, judge);593+ }594+595+ if (DECLARATIONS.has(program)) {596+ return breaks("hook-bypass", args.some(switchesOffHooks));597+ }598+599+ if (program === "eval") {600+ return judge(args.join(" "));601+ }602+603+ if (SHELLS.has(program)) {604+ return judgeShell(args, stdin, judge);605+ }606+607+ if (WRAPPERS.has(program)) {608+ return judgeWords(wrapped(program, args), stdin, judge);609+ }610+611+ if (PACKAGE_RUNNERS.has(program)) {612+ return Option.flatMap(runs(program, args), (inner) =>613+ judgeWords(inner, stdin, judge)614+ );615+ }616+617+ const judgeProgram = PROGRAMS.get(program);618+619+ if (judgeProgram !== undefined) {620+ return judgeProgram(args);621+ }622+623+ return READERS.has(program) ? judgeRead(program, args) : Option.none();624+};625+626+const ruleOf: Judge = (command) =>627+ Option.firstSomeOf(628+ simpleCommands(command).map((simple) =>629+ simple.reads.some(namesClosedEnv)630+ ? Option.some<Rule>("closed-env-read")631+ : judgeWords(simple.words, simple.stdin, ruleOf)632+ )633+ );634+635+/** Allow, or Deny with the rule the command breaks and what to do instead. */636+export const decide = (command: string): Decision =>637+ Option.match(ruleOf(command), {638+ onNone: () => Decision.Allow(),639+ onSome: (rule) => Decision.Deny({ reason: reasons[rule], rule }),640+ });added:scripts/hooks/lib/shell.ts+443 added
1+/**2+ * Reads a shell command line the way bash would, as far as the hook policy3+ * needs: simple commands split on `; && || | ( )` and newlines, words after4+ * quote removal (single, double, `$'…'` and backslash escapes), the files a5+ * command reads with `<`, and heredoc and here-string text. What runs inside6+ * `$(…)`, backticks and `<(…)` comes back as simple commands too; an unquoted7+ * heredoc's substitutions run, a quoted one's don't.8+ *9+ * Variables and globs stay unexpanded, and a substitution's word holds its10+ * source text. Unclosed quotes run to the end, so a command bash would refuse11+ * to parse is still read for what it holds.12+ */13+14+/**15+ * One simple command: its words after quote removal, the files it reads with16+ * `<`, and the heredoc or here-string text on its stdin.17+ */18+export interface Simple {19+ readonly words: string[];20+ readonly reads: string[];21+ readonly stdin: string[];22+}23+24+interface Scanned {25+ readonly commands: readonly Simple[];26+ /** Just past the `)` that closed a nested scan, or the source's end. */27+ readonly end: number;28+}29+30+/** A heredoc whose body starts after the next newline. */31+interface Heredoc {32+ readonly delimiter: string;33+ /** A quoted delimiter keeps `$(…)` in the body from running. */34+ readonly quoted: boolean;35+ /** `<<-` strips leading tabs from each line. */36+ readonly tabs: boolean;37+ readonly into: string[];38+}39+40+/** What the word being read is for. */41+type Slot =42+ | "argument"43+ | "read"44+ | "write"45+ | "here-string"46+ | "heredoc"47+ | "heredoc-tabs";48+49+/** Redirect operators, longest first, and what the word after each is. */50+const REDIRECTS: readonly (readonly [string, Slot])[] = [51+ ["<<<", "here-string"],52+ ["<<-", "heredoc-tabs"],53+ ["&>>", "write"],54+ ["<<", "heredoc"],55+ ["<>", "read"],56+ ["<&", "write"],57+ ["&>", "write"],58+ [">>", "write"],59+ [">|", "write"],60+ [">&", "write"],61+ ["<", "read"],62+ [">", "write"],63+];64+65+const BLANKS = new Set([" ", "\t"]);66+67+// Inside double quotes, `\` escapes only these.68+const DOUBLE_QUOTE_ESCAPES = new Set(["$", "`", '"', "\\", "\n"]);69+70+// Inside backticks, `\` escapes only these.71+const BACKTICK_ESCAPES = new Set(["`", "\\", "$"]);72+73+const ANSI_C: ReadonlyMap<string, string> = new Map([74+ ["E", "\u001B"],75+ ["a", "\u0007"],76+ ["b", "\b"],77+ ["e", "\u001B"],78+ ["f", "\f"],79+ ["n", "\n"],80+ ["r", "\r"],81+ ["t", "\t"],82+ ["v", "\v"],83+]);84+85+const ANSI_C_ESCAPE =86+ /\\(?:x(?<hex>[\da-f]{1,2})|u(?<unicode>[\da-f]{1,4})|(?<octal>[0-7]{1,3})|(?<char>[\s\S]))/giu;87+88+const decodeEscape = (89+ hex: string | undefined,90+ unicode: string | undefined,91+ octal: string | undefined,92+ char: string | undefined93+): string => {94+ if (hex !== undefined) {95+ return String.fromCodePoint(Number.parseInt(hex, 16));96+ }97+98+ if (unicode !== undefined) {99+ return String.fromCodePoint(Number.parseInt(unicode, 16));100+ }101+102+ if (octal !== undefined) {103+ return String.fromCodePoint(Number.parseInt(octal, 8));104+ }105+106+ return ANSI_C.get(char ?? "") ?? char ?? "";107+};108+109+/** The text of an ANSI-C quoted `$'…'` body, escapes decoded. */110+const ansiC = (body: string): string => {111+ let decoded = "";112+ let from = 0;113+114+ for (const match of body.matchAll(ANSI_C_ESCAPE)) {115+ const { char, hex, octal, unicode } = match.groups ?? {};116+117+ decoded += body.slice(from, match.index);118+ decoded += decodeEscape(hex, unicode, octal, char);119+ from = match.index + match[0].length;120+ }121+122+ return decoded + body.slice(from);123+};124+125+/**126+ * Reads `src` from `start` into simple commands. A nested scan (inside `$(`)127+ * stops at its unmatched `)`. Unclosed quotes run to the end, so a command a128+ * shell would refuse to parse is still judged on what it holds.129+ */130+const scan = (src: string, start: number, nested: boolean): Scanned => {131+ const commands: Simple[] = [];132+ const heredocs: Heredoc[] = [];133+ let simple: Simple = { reads: [], stdin: [], words: [] };134+ let word = "";135+ let inWord = false;136+ let quoted = false;137+ let slot: Slot = "argument";138+ let depth = 0;139+ let at = start;140+141+ const append = (text: string, fromQuotes: boolean) => {142+ word += text;143+ inWord = true;144+ quoted ||= fromQuotes;145+ };146+147+ // `$(…)`: what it runs is judged; its source text stands in for its output.148+ const substitution = (from: number) => {149+ const inner = scan(src, from + 2, true);150+151+ commands.push(...inner.commands);152+153+ return { end: inner.end, text: src.slice(from, inner.end) };154+ };155+156+ // `…`: up to the next unescaped backtick.157+ const backtick = (from: number) => {158+ let body = "";159+ let end = from + 1;160+161+ while (end < src.length && src[end] !== "`") {162+ const next = src[end + 1] ?? "";163+ const escaped = src[end] === "\\" && BACKTICK_ESCAPES.has(next);164+165+ body += escaped ? next : (src[end] ?? "");166+ end += escaped ? 2 : 1;167+ }168+169+ commands.push(...scan(body, 0, false).commands);170+171+ return { end: end + 1, text: src.slice(from, end + 1) };172+ };173+174+ // Double-quoted text, or an unquoted heredoc's body: `$(…)` and backticks175+ // still run there. Stops before `limit`, or at `closing`.176+ const expand = (from: number, limit: number, closing: string) => {177+ let text = "";178+ let end = from;179+180+ while (end < limit && src[end] !== closing) {181+ const char = src[end] ?? "";182+ const next = src[end + 1] ?? "";183+184+ if (char === "\\" && DOUBLE_QUOTE_ESCAPES.has(next)) {185+ text += next === "\n" ? "" : next;186+ end += 2;187+ } else if ((char === "$" && next === "(") || char === "`") {188+ const { end: after, text: source } =189+ char === "`" ? backtick(end) : substitution(end);190+191+ text += source;192+ end = after;193+ } else {194+ text += char;195+ end += 1;196+ }197+ }198+199+ return { end: end + 1, text };200+ };201+202+ // At a newline: each pending heredoc's body, line by line to its delimiter.203+ const readHeredocs = (from: number): number => {204+ let line = from;205+206+ for (const heredoc of heredocs) {207+ const lines: string[] = [];208+ const bodyStart = line;209+ let bodyEnd = line;210+211+ while (line < src.length) {212+ const newline = src.indexOf("\n", line);213+ const eol = newline === -1 ? src.length : newline;214+ const raw = src.slice(line, eol);215+ const text = heredoc.tabs ? raw.replace(/^\t+/u, "") : raw;216+217+ line = eol + 1;218+219+ if (text === heredoc.delimiter) {220+ break;221+ }222+223+ lines.push(text);224+ bodyEnd = eol;225+ }226+227+ heredoc.into.push(lines.join("\n"));228+229+ if (!heredoc.quoted) {230+ expand(bodyStart, bodyEnd, "");231+ }232+ }233+234+ heredocs.splice(0);235+236+ return line;237+ };238+239+ const finishWord = () => {240+ if (!inWord) {241+ return;242+ }243+244+ if (slot === "argument") {245+ simple.words.push(word);246+ } else if (slot === "read") {247+ simple.reads.push(word);248+ } else if (slot === "here-string") {249+ simple.stdin.push(word);250+ } else if (slot === "heredoc" || slot === "heredoc-tabs") {251+ heredocs.push({252+ delimiter: word,253+ into: simple.stdin,254+ quoted,255+ tabs: slot === "heredoc-tabs",256+ });257+ }258+259+ word = "";260+ inWord = false;261+ quoted = false;262+ slot = "argument";263+ };264+265+ const finishCommand = () => {266+ finishWord();267+ slot = "argument";268+269+ const { reads, stdin, words } = simple;270+271+ if (words.length + reads.length + stdin.length > 0) {272+ commands.push(simple);273+ }274+275+ simple = { reads: [], stdin: [], words: [] };276+ };277+278+ // `<`, `<<`, `>`, `>>`, `&>` and the rest. An unquoted all-digit word right279+ // before one is its file descriptor, not an argument.280+ const redirect = (): number => {281+ if (inWord && !quoted && /^\d+$/u.test(word)) {282+ word = "";283+ inWord = false;284+ } else {285+ finishWord();286+ }287+288+ const [operator, target] = REDIRECTS.find(([text]) =>289+ src.startsWith(text, at)290+ ) ?? [">", "write"];291+292+ slot = target;293+294+ return at + operator.length;295+ };296+297+ // `$'…'`, `$(…)` and `${…}`; any other `$` is a literal.298+ const dollar = (next: string): number | undefined => {299+ if (next === "'") {300+ let end = at + 2;301+302+ while (end < src.length && src[end] !== "'") {303+ end += src[end] === "\\" ? 2 : 1;304+ }305+306+ append(ansiC(src.slice(at + 2, Math.min(end, src.length))), true);307+308+ return end + 1;309+ }310+311+ if (next === "(") {312+ const inner = substitution(at);313+314+ append(inner.text, false);315+316+ return inner.end;317+ }318+319+ if (next === "{") {320+ const close = src.indexOf("}", at);321+ const end = close === -1 ? src.length : close + 1;322+323+ append(src.slice(at, end), false);324+325+ return end;326+ }327+328+ return undefined;329+ };330+331+ // Quotes, escapes and expansions, each part of the current word. None when332+ // `char` starts none of them.333+ const wordPart = (char: string, next: string): number | undefined => {334+ if (char === "\\") {335+ if (next !== "\n") {336+ append(next, true);337+ }338+339+ return at + 2;340+ }341+342+ if (char === "'") {343+ const close = src.indexOf("'", at + 1);344+ const end = close === -1 ? src.length : close;345+346+ append(src.slice(at + 1, end), true);347+348+ return end + 1;349+ }350+351+ if (char === '"') {352+ const inner = expand(at + 1, src.length, '"');353+354+ append(inner.text, true);355+356+ return inner.end;357+ }358+359+ // Backticks, and the process substitutions `<(…)` and `>(…)`.360+ if (char === "`" || ((char === "<" || char === ">") && next === "(")) {361+ const inner = char === "`" ? backtick(at) : substitution(at);362+363+ append(inner.text, false);364+365+ return inner.end;366+ }367+368+ return char === "$" ? dollar(next) : undefined;369+ };370+371+ // Blanks, newlines, comments, redirects and the operators between simple372+ // commands. None when `char` is none of them.373+ const operator = (char: string, next: string): number | undefined => {374+ if (BLANKS.has(char)) {375+ finishWord();376+377+ return at + 1;378+ }379+380+ if (char === "\n") {381+ finishCommand();382+383+ return heredocs.length > 0 ? readHeredocs(at + 1) : at + 1;384+ }385+386+ if (char === "#" && !inWord) {387+ const newline = src.indexOf("\n", at);388+389+ return newline === -1 ? src.length : newline;390+ }391+392+ if (char === "<" || char === ">" || (char === "&" && next === ">")) {393+ return redirect();394+ }395+396+ if (char === ";" || char === "&" || char === "|") {397+ finishCommand();398+399+ return at + (next === char || (char === "|" && next === "&") ? 2 : 1);400+ }401+402+ if (char === "(" || char === ")") {403+ finishCommand();404+ depth = char === "(" ? depth + 1 : Math.max(0, depth - 1);405+406+ return at + 1;407+ }408+409+ return undefined;410+ };411+412+ while (at < src.length) {413+ const char = src[at] ?? "";414+ const next = src[at + 1] ?? "";415+416+ if (char === ")" && nested && depth === 0) {417+ finishCommand();418+419+ return { commands, end: at + 1 };420+ }421+422+ const after = wordPart(char, next) ?? operator(char, next);423+424+ if (after === undefined) {425+ append(char, false);426+ at += 1;427+ } else {428+ at = after;429+ }430+ }431+432+ finishCommand();433+434+ return { commands, end: src.length };435+};436+437+/** The simple commands in `command`, including those inside substitutions. */438+export const simpleCommands = (command: string): readonly Simple[] =>439+ scan(command, 0, false).commands;440+441+/** The words of the first simple command in `text`, as `env -S` splits it. */442+export const wordsOf = (text: string): readonly string[] =>443+ scan(text, 0, false).commands[0]?.words ?? [];added:scripts/hooks/vcs-policy.ts+138 added
1+// Ported from joelhooks/rat-stack@fba26d8 `scripts/hooks/block-git-no-verify.mjs`2+// (MIT, LICENSES/rat-stack.MIT.txt). Changes are listed in PROVENANCE.md.3+/**4+ * vcs-policy: the hook Claude Code (PreToolUse on Bash, `.claude/settings.json`)5+ * and Cursor (beforeShellExecution, `.cursor/hooks.json`) run before every shell6+ * command. It reads the harness's JSON on stdin, asks `decide`, and answers in7+ * that harness's shape:8+ *9+ * - Claude Code, or a bare `{"command": …}`: a refusal exits 2 with its reason10+ * on stderr; an allowed command exits 0 and prints nothing.11+ * - Cursor: prints `{"permission": "allow" | "deny", …}` and exits 0.12+ *13+ * Input it cannot read, or any failure of its own, is a refusal: it fails14+ * closed, so a broken hook never lets a command through.15+ */16+import { BunRuntime, BunServices } from "@effect/platform-bun";17+import {18+ Data,19+ Effect,20+ Match,21+ Option,22+ Runtime,23+ Schema,24+ Stdio,25+ Stream,26+} from "effect";27+28+import { Decision, decide } from "./lib/policy.ts";29+30+/** Tags each payload with its harness, which its JSON doesn't carry. */31+const harness = <const Name extends string>(name: Name) =>32+ Schema.tag(name).pipe(Schema.withDecodingDefaultKey(Effect.succeed(name)));33+34+/** Claude Code's PreToolUse payload for the Bash tool. */35+const ClaudePreToolUse = Schema.Struct({36+ _tag: harness("Claude"),37+ tool_input: Schema.Struct({ command: Schema.String }),38+});39+40+/** Cursor's beforeShellExecution payload. */41+const CursorShell = Schema.Struct({42+ _tag: harness("Cursor"),43+ command: Schema.String,44+ hook_event_name: Schema.Literal("beforeShellExecution"),45+});46+47+/** Any other caller: `{"command": "…"}`. */48+const Bare = Schema.Struct({ _tag: harness("Bare"), command: Schema.String });49+50+const HookInput = Schema.fromJsonString(51+ Schema.Union([ClaudePreToolUse, CursorShell, Bare])52+);53+54+type HookInput = typeof HookInput.Type;55+56+const CANNOT_READ =57+ 'vcs-policy could not read a shell command from the hook\'s input, so it refuses it. It reads Claude Code\'s PreToolUse JSON, Cursor\'s beforeShellExecution JSON or {"command": "…"}.';58+59+/** A refusal this hook has already printed; it only sets the exit code. */60+class Refused extends Data.TaggedError("Refused")<{61+ readonly reason: string;62+}> {63+ override readonly [Runtime.errorExitCode] = 2;64+ override readonly [Runtime.errorReported] = false;65+}66+67+/** Who answers, and the refusal, if any, in words for the agent. */68+interface Verdict {69+ readonly harness: HookInput["_tag"];70+ readonly refusal: Option.Option<string>;71+}72+73+const commandOf = (input: HookInput) =>74+ Match.valueTags(input, {75+ Bare: ({ command }) => command,76+ Claude: ({ tool_input }) => tool_input.command,77+ Cursor: ({ command }) => command,78+ });79+80+const explain = (decision: Decision): Option.Option<string> =>81+ Decision.$match(decision, {82+ Allow: () => Option.none(),83+ Deny: ({ reason, rule }) =>84+ Option.some(`vcs-policy refused this command (${rule}): ${reason}`),85+ });86+87+const UNREADABLE: Verdict = {88+ harness: "Bare",89+ refusal: Option.some(CANNOT_READ),90+};91+92+const judged: Effect.Effect<Verdict, never, Stdio.Stdio> = Effect.gen(93+ function* () {94+ const stdio = yield* Stdio.Stdio;95+ const raw = yield* stdio.stdin.pipe(Stream.decodeText(), Stream.mkString);96+ const input = yield* Schema.decodeEffect(HookInput)(raw);97+98+ return {99+ harness: input._tag,100+ refusal: explain(decide(commandOf(input))),101+ };102+ }103+).pipe(104+ // Unreadable stdin, a payload of no known shape, or a defect: refuse.105+ Effect.catchCause(() => Effect.succeed(UNREADABLE))106+);107+108+/** Cursor reads its answer, allow or deny, from stdout. */109+const answerCursor = (refusal: Option.Option<string>) => {110+ const reply = Option.match(refusal, {111+ onNone: () => ({ permission: "allow" }),112+ onSome: (message) => ({113+ agent_message: message,114+ permission: "deny",115+ user_message: message,116+ }),117+ });118+119+ return Effect.flatMap(Stdio.Stdio, (stdio) =>120+ Stream.run(Stream.make(`${JSON.stringify(reply)}\n`), stdio.stdout())121+ );122+};123+124+/** Claude Code and a bare caller read a refusal from exit 2 and stderr. */125+const answerByExit = (refusal: Option.Option<string>) =>126+ Option.match(refusal, {127+ onNone: () => Effect.void,128+ onSome: (message) =>129+ Effect.flatMap(Stdio.Stdio, (stdio) =>130+ Stream.run(Stream.make(`${message}\n`), stdio.stderr())131+ ).pipe(Effect.andThen(Effect.fail(new Refused({ reason: message })))),132+ });133+134+const main = Effect.flatMap(judged, ({ harness: answerer, refusal }) =>135+ answerer === "Cursor" ? answerCursor(refusal) : answerByExit(refusal)136+);137+138+BunRuntime.runMain(main.pipe(Effect.provide(BunServices.layer)));