Merge build/104-vcs-policy-hooks: agent harnesses refuse hook bypasses, pushes, deletes, cf project commands and closed env reads
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 8165e49, a3e552a · Browse files · 9 files·+2045 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+2045 added−0 removed
- tests:+435 added−0 removed
- other:+1610 added−0 removed
Provenance
- Commit
d3416aa- Tree
370e127- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
8165e49- Parent 2
a3e552a
9 files changed+2045 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+64 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364// 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 { Option, Schema } from "effect";
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;}
/** pi's `BashToolInput`, as far as the policy reads it. */const BashInput = Schema.Struct({ command: Schema.String });
const UNREADABLE: Block = { block: true, reason: "vcs-policy could not read a shell command from this bash call, so it refuses it.",};
const blockFor = (command: string): Block | undefined => { const decision = decide(command);
return Decision.$is("Deny")(decision) ? { block: true, reason: `vcs-policy refused this command (${decision.rule}): ${decision.reason}`, } : undefined;};
const vcsPolicy = (pi: PiApi) => { pi.on("tool_call", (event) => event.toolName === "bash" ? Option.match(Schema.decodeUnknownOption(BashInput)(event.input), { onNone: () => UNREADABLE, onSome: ({ command }) => blockFor(command), }) : 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+435 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 parses with yargs, which reads `false` after a boolean flag as its214+ // value, and the last of `--dry-run` and `--no-dry-run` wins.215+ ["bun run ops -- workers delete x --dry-run false", "delete"],216+ ["bun run ops -- workers delete x --dry-run --no-dry-run", "delete"],217+ ["bun run ops -- workers delete x --no-dry-run --dry-run", "Allow"],218+ // AGENTS.md's discovery steps only read: `cli search`, `schema <command>`219+ // and `<command> --help` (the help cf itself points to) delete nothing.220+ ['bun run ops -- cli search "delete"', "Allow"],221+ ["bun run ops -- schema artifacts namespaces repos delete", "Allow"],222+ ["bun run ops -- artifacts namespaces repos delete --help", "Allow"],223+ // cf's package installs its bin under a second name, `cloudflare`.224+ ["./node_modules/.bin/cloudflare deploy", "cf-project-command"],225+ ["bunx cloudflare workers delete x", "delete"],226+ // cf's project commands are refused even as dry runs, and through varlock.227+ ["cf deploy --dry-run", "cf-project-command"],228+ ["cf --profile dev deploy", "cf-project-command"],229+ // An option cf doesn't declare may take the next word as its value, so230+ // any word it could have taken may be the command.231+ ["cf --account-id x --env y deploy", "cf-project-command"],232+ ["cf --account-id x workers list --name deploy", "Allow"],233+ ["bunx varlock run --path infra/ -- cf deploy", "cf-project-command"],234+ ["bun run verify", "Allow"],235+ ["bun infra/deploy.ts --stage demo", "Allow"],236+ // The closed env files, by any path, glob or redirect. Their schemas and237+ // examples stay open, and so does searching other files for the name.238+ ["cat .env.schema", "Allow"],239+ ["cat apps/platform/.env.schema", "Allow"],240+ ["cat .env.example", "Allow"],241+ ["ls -la .env*", "Allow"],242+ ["grep -n .env .gitignore", "Allow"],243+ ["rg -n '\\.env' docs", "Allow"],244+ ["cat < .env", "closed-env-read"],245+ ["while read -r line; do echo $line; done < .env.local", "closed-env-read"],246+ ["cat ./.env", "closed-env-read"],247+ ['cat "$HOME/project/.env"', "closed-env-read"],248+ ["cat .env*", "closed-env-read"],249+ ["cat .env{,.local}", "closed-env-read"],250+ ["grep -e TOKEN .env", "closed-env-read"],251+ ["grep -A 2 TOKEN .env", "closed-env-read"],252+ ["grep -f .env other.txt", "closed-env-read"],253+ ["cp .env /tmp/x", "closed-env-read"],254+ ["set -a; . ./.env; set +a", "closed-env-read"],255+ // A recursive grep reads every file under its paths, the closed ones too,256+ // unless --include or --exclude keeps them out. A pattern is not a file.257+ ["grep -rn TOKEN .", "closed-env-read"],258+ ["grep -R TOKEN apps/platform", "closed-env-read"],259+ ["grep --recursive TOKEN", "closed-env-read"],260+ ["grep -d recurse TOKEN .", "closed-env-read"],261+ ["grep -rn TOKEN . --include='*'", "closed-env-read"],262+ ["grep -rn TOKEN . --exclude='*.local'", "closed-env-read"],263+ ["grep -rn TOKEN . --include='*.ts'", "Allow"],264+ ["grep -rn TOKEN . --exclude='.env*'", "Allow"],265+ ["grep -rn TOKEN . --exclude=.env --exclude='*.local'", "Allow"],266+ ["grep -rn TOKEN . --exclude={.env,.env.local,.env.*.local}", "Allow"],267+ ["grep -n -e .env .gitignore", "Allow"],268+ // rg skips hidden and git-ignored files; the closed files are both, so it269+ // reaches them only when told to search both.270+ ["rg TOKEN", "Allow"],271+ ["rg --hidden TOKEN", "Allow"],272+ ["rg -uu TOKEN", "closed-env-read"],273+ ["rg --hidden --no-ignore-vcs TOKEN", "closed-env-read"],274+ ["rg -. -u TOKEN", "closed-env-read"],275+ ["bun run env:check", "Allow"],276+ ])("%s → %s", (command, verdict) => {277+ expect(verdictOf(command)).toBe(verdict);278+ });279+280+ it("gives each refusal one sentence from AGENTS.md, saying what to do instead", () => {281+ expect(decide("git commit -n -m x")).toStrictEqual(282+ Decision.Deny({283+ reason:284+ "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",285+ rule: "hook-bypass",286+ })287+ );288+ expect(reasons).toStrictEqual({289+ "cf-project-command":290+ "cf's project commands are not our deploy tool; use infra/deploy.ts.",291+ "closed-env-read":292+ "Never read .env, .env.local or .env.*.local, even in a recursive search (rg and git grep skip them); run bun run env:check.",293+ delete: "Deleting Cloudflare resources needs the user's OK.",294+ "hook-bypass":295+ "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11).",296+ push: "Pushing is the user's step; commit on the branch and stop.",297+ });298+ expect(decide("git status")).toStrictEqual(Decision.Allow());299+ });300+});301+302+// Vitest runs in the package's folder, two below the repo root.303+const repoRoot = Effect.map(Path.Path, (path) => path.resolve("..", ".."));304+305+interface Ran {306+ readonly exitCode: number;307+ readonly stdout: string;308+ readonly stderr: string;309+}310+311+const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>312+ bytes.pipe(Stream.decodeText(), Stream.mkString);313+314+/** Runs the hook as a harness does: `input` on stdin, then stdin closes. */315+const hook = (input: string) =>316+ Effect.scoped(317+ Effect.gen(function* () {318+ const path = yield* Path.Path;319+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;320+ const root = yield* repoRoot;321+322+ const child = yield* spawner.spawn(323+ ChildProcess.make(324+ "bun",325+ [path.join(root, "scripts/hooks/vcs-policy.ts")],326+ {327+ cwd: root,328+ stdin: Stream.make(new TextEncoder().encode(input)),329+ }330+ )331+ );332+333+ const [stdout, stderr, exitCode] = yield* Effect.all(334+ [text(child.stdout), text(child.stderr), child.exitCode],335+ { concurrency: "unbounded" }336+ );337+338+ return { exitCode, stderr, stdout } satisfies Ran;339+ })340+ ).pipe(Effect.provide(NodeServices.layer));341+342+const CursorReply = Schema.fromJsonString(343+ Schema.Struct({344+ agent_message: Schema.optionalKey(Schema.String),345+ permission: Schema.Literals(["allow", "deny"]),346+ user_message: Schema.optionalKey(Schema.String),347+ })348+);349+350+const claude = (command: string) =>351+ JSON.stringify({352+ hook_event_name: "PreToolUse",353+ session_id: "s",354+ tool_input: { command, description: "d" },355+ tool_name: "Bash",356+ });357+358+const cursor = (command: string) =>359+ JSON.stringify({360+ command,361+ conversation_id: "c",362+ cwd: "/repo",363+ hook_event_name: "beforeShellExecution",364+ });365+366+const PUSH = "Pushing is the user's step; commit on the branch and stop.";367+368+describe("the hook adapter", () => {369+ it.live("denies for Claude Code by exit 2, with the reason on stderr", () =>370+ Effect.gen(function* () {371+ const ran = yield* hook(claude("git commit -n -m x"));372+373+ expect(ran.exitCode).toBe(2);374+ expect(ran.stdout).toBe("");375+ expect(ran.stderr).toContain(376+ "Hooks are early feedback; fix the failure instead of skipping it (AGENTS.md principle 11)."377+ );378+ })379+ );380+381+ it.live("allows for Claude Code by exit 0, saying nothing", () =>382+ Effect.gen(function* () {383+ expect(yield* hook(claude("git status"))).toStrictEqual({384+ exitCode: 0,385+ stderr: "",386+ stdout: "",387+ });388+ })389+ );390+391+ it.live("denies for Cursor with its JSON reply, and exits 0", () =>392+ Effect.gen(function* () {393+ const ran = yield* hook(cursor("git push"));394+ const reply = yield* Schema.decodeEffect(CursorReply)(ran.stdout);395+396+ expect(ran.exitCode).toBe(0);397+ expect(reply.permission).toBe("deny");398+ expect(reply.user_message).toContain(PUSH);399+ expect(reply.agent_message).toContain(PUSH);400+ })401+ );402+403+ it.live("allows for Cursor with its JSON reply", () =>404+ Effect.gen(function* () {405+ const ran = yield* hook(cursor("git status"));406+407+ expect(ran.exitCode).toBe(0);408+ expect(yield* Schema.decodeEffect(CursorReply)(ran.stdout)).toStrictEqual(409+ { permission: "allow" }410+ );411+ })412+ );413+414+ it.live("judges a bare {command}, denying by exit 2", () =>415+ Effect.gen(function* () {416+ const denied = yield* hook(JSON.stringify({ command: "git push" }));417+ const allowed = yield* hook(JSON.stringify({ command: "git status" }));418+419+ expect(denied.exitCode).toBe(2);420+ expect(denied.stderr).toContain(PUSH);421+ expect(allowed.exitCode).toBe(0);422+ })423+ );424+425+ it.live("denies input it cannot read, failing closed", () =>426+ Effect.gen(function* () {427+ for (const input of ["not json", "{}", '{"command":7}', ""]) {428+ const ran = yield* hook(input);429+430+ expect(ran.exitCode).toBe(2);431+ expect(ran.stderr).toContain("could not read");432+ }433+ })434+ );435+});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+795 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, even in a recursive search (rg and git grep skip them); 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 (`cf --help`, cf 1.0.0-beta.12).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+/** cf's commands that only read: AGENTS.md's `cli search` and `schema`. */226+const CF_DISCOVERY = names("cli schema");227+228+/**229+ * The words that may be cf's command. cf parses with yargs, which gives an230+ * option it doesn't declare the next word as its value, so each such word may231+ * be the command too: `cf --account-id x deploy`. The last word is the first232+ * one no option can have taken.233+ */234+const cfCommandWords = (args: readonly string[]): readonly string[] => {235+ const [word, next, ...rest] = args;236+237+ if (word === undefined) {238+ return [];239+ }240+241+ if (word === "--") {242+ return next === undefined ? [] : [next];243+ }244+245+ if (!word.startsWith("-") || word === "-") {246+ return [word];247+ }248+249+ if (word.includes("=") || next === undefined || next.startsWith("-")) {250+ return cfCommandWords(args.slice(1));251+ }252+253+ const after = cfCommandWords(rest);254+255+ return CF.values.has(word) ? after : [next, ...after];256+};257+258+/** Values yargs reads as false for a boolean flag. */259+const OFF = names("0 false");260+261+const DRY_RUN = "--dry-run";262+263+const setsDryRun = (word: string) =>264+ word === DRY_RUN || word === "--no-dry-run" || word.startsWith(`${DRY_RUN}=`);265+266+/** Whether the last `--dry-run`, `--dry-run=…` or `--no-dry-run` turns it on. */267+const dryRun = (args: readonly string[]): boolean => {268+ const end = args.indexOf("--");269+ const flags = end === -1 ? args : args.slice(0, end);270+ const last = flags.findLastIndex(setsDryRun);271+ const word = flags[last] ?? "--no-dry-run";272+273+ if (word === "--no-dry-run") {274+ return false;275+ }276+277+ return !OFF.has(278+ word === DRY_RUN ? (flags[last + 1] ?? "") : word.slice(DRY_RUN.length + 1)279+ );280+};281+282+const judgeCf = (args: readonly string[]): Verdict => {283+ const parsed = parse(args, CF, true);284+ const commands = cfCommandWords(args);285+ const [command = ""] = commands;286+287+ if (commands.length === 1 && CF_DISCOVERY.has(command)) {288+ return Option.none();289+ }290+291+ if (292+ commands.some((word) => CF_PROJECT.has(word)) ||293+ CF_PROJECT_SEQUENCES.some((sequence) => contains(parsed.operands, sequence))294+ ) {295+ return Option.some("cf-project-command");296+ }297+298+ // `<command> --help` prints the command's help, as cf's own help suggests.299+ const executes = !parsed.options.includes("--help") && !dryRun(args);300+301+ return breaks(302+ "delete",303+ executes && parsed.operands.some((word) => DESTRUCTIVE.test(word))304+ );305+};306+307+// closed-env-read -------------------------------------------------------------308+309+/**310+ * Closed names to test globs against: one of each fixed name and a few of the311+ * `.env.*.local` shape, so a glob covers the shape only if it matches them all.312+ */313+const CLOSED_SAMPLES = [314+ ".env",315+ ".env.local",316+ ".env.development.local",317+ ".env.production.local",318+ ".env.test.local",319+];320+321+const isClosedName = (name: string) =>322+ name === ".env" || name === ".env.local" || /^\.env\..+\.local$/u.test(name);323+324+const GLOB = /[*?[]/u;325+326+const REGEXP_SPECIAL = /[$()*+.?[\\\]^{|}]/u;327+328+const globPart = (part: string) => {329+ if (part === "*") {330+ return ".*";331+ }332+333+ if (part === "?" || part.startsWith("[")) {334+ return ".";335+ }336+337+ return REGEXP_SPECIAL.test(part) ? `\\${part}` : part;338+};339+340+/**341+ * Whether a glob could match `name`, as fnmatch does without `FNM_PERIOD`. A342+ * bracket matches any one character, which only widens the match.343+ */344+const fnmatch = (pattern: string, name: string) =>345+ new RegExp(346+ `^${pattern.replaceAll(/\[[^\]]*\]|[\s\S]/gu, globPart)}$`,347+ "u"348+ ).test(name);349+350+/**351+ * Whether a shell glob could match the dotfile `name`: a leading `*` never352+ * matches one, as in a shell without `dotglob`.353+ */354+const globMatches = (pattern: string, name: string) =>355+ pattern.startsWith(".") && fnmatch(pattern, name);356+357+/** `a{b,c}d` → `abd`, `acd`, as a shell expands braces. */358+const braces = (word: string): readonly string[] => {359+ const match = /\{(?<options>[^{}]*,[^{}]*)\}/u.exec(word);360+361+ if (match === null) {362+ return [word];363+ }364+365+ const before = word.slice(0, match.index);366+ const after = word.slice(match.index + match[0].length);367+368+ return (match.groups?.options ?? "")369+ .split(",")370+ .flatMap((option) => braces(`${before}${option}${after}`));371+};372+373+/** Whether `word`, or the part after its first `=`, names a closed env file. */374+const namesClosedEnv = (word: string) =>375+ [word, word.slice(word.indexOf("=") + 1)].some((value) =>376+ braces(value).some((path) => {377+ const name = basename(path.replace(/\/+$/u, ""));378+379+ return GLOB.test(name)380+ ? CLOSED_SAMPLES.some((sample) => globMatches(name, sample))381+ : isClosedName(name);382+ })383+ );384+385+/** The globs one option names, braces expanded: `--include={a,b}`. */386+const globsOf = (parsed: Parsed, option: string) =>387+ parsed.values.flatMap(([name, value]) =>388+ name === option ? braces(value) : []389+ );390+391+const GREP_RECURSIVE = names("-R -r --dereference-recursive --recursive");392+393+/**394+ * `grep -r` reads every file under its paths, the closed ones too, unless395+ * `--include` leaves them out or `--exclude` covers them (grep matches both396+ * against the file's name with fnmatch, so `*` matches a leading dot).397+ */398+const grepReachesClosed = (parsed: Parsed) => {399+ const recursive =400+ parsed.options.some((option) => GREP_RECURSIVE.has(option)) ||401+ parsed.values.some(402+ ([option, value]) =>403+ (option === "-d" || option === "--directories") && value === "recurse"404+ );405+406+ const includes = globsOf(parsed, "--include");407+ const excludes = globsOf(parsed, "--exclude");408+409+ return (410+ recursive &&411+ CLOSED_SAMPLES.some(412+ (sample) =>413+ (includes.length === 0 ||414+ includes.some((glob) => fnmatch(glob, sample))) &&415+ !excludes.some((glob) => fnmatch(glob, sample))416+ )417+ );418+};419+420+const RG_HIDDEN = names("-. --hidden");421+422+const RG_IGNORED = names("--no-ignore --no-ignore-parent --no-ignore-vcs");423+424+/**425+ * rg skips hidden files and the files .gitignore names, and the closed files426+ * are both, so it reaches them only when told to search both: `-uu`, or427+ * `--hidden` with `--no-ignore`.428+ */429+const rgReachesClosed = (parsed: Parsed) => {430+ const unrestricted = parsed.options.filter(431+ (option) => option === "-u" || option === "--unrestricted"432+ ).length;433+434+ return (435+ (unrestricted >= 2 ||436+ parsed.options.some((option) => RG_HIDDEN.has(option))) &&437+ (unrestricted >= 1 ||438+ parsed.options.some((option) => RG_IGNORED.has(option)))439+ );440+};441+442+/**443+ * A reader whose first operand is a pattern or a script, not a file, unless444+ * one of `instead` supplies it.445+ */446+interface PatternFirst {447+ readonly grammar: Grammar;448+ readonly instead: ReadonlySet<string>;449+ /** Options whose value is a pattern or a glob, never a file it reads. */450+ readonly patterns: ReadonlySet<string>;451+ /** Whether a search of whole directories can reach a closed file. */452+ readonly reachesClosed: (parsed: Parsed) => boolean;453+}454+455+const GREP: PatternFirst = {456+ grammar: grammar(457+ "-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"458+ ),459+ instead: names("-e -f --file --regexp"),460+ patterns: names("-e --exclude --exclude-dir --include --regexp"),461+ reachesClosed: grepReachesClosed,462+};463+464+const AWK: PatternFirst = {465+ grammar: grammar(466+ "-E -F -W -f -i -l -v --assign --exec --field-separator --file --include --load"467+ ),468+ instead: names("-E -f --exec --file"),469+ patterns: names(""),470+ reachesClosed: () => false,471+};472+473+const RG: PatternFirst = {474+ grammar: grammar(475+ "-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"476+ ),477+ instead: names("-e -f --file --files --regexp --type-list"),478+ patterns: names("-e --regexp"),479+ reachesClosed: rgReachesClosed,480+};481+482+const SED: PatternFirst = {483+ grammar: grammar("-e -f -l --expression --file --line-length", "-i"),484+ instead: names("-e -f --expression --file"),485+ patterns: names(""),486+ reachesClosed: () => false,487+};488+489+const PATTERN_FIRST: ReadonlyMap<string, PatternFirst> = new Map([490+ ["awk", AWK],491+ ["egrep", GREP],492+ ["fgrep", GREP],493+ ["gawk", AWK],494+ ["grep", GREP],495+ ["mawk", AWK],496+ ["nawk", AWK],497+ ["rg", RG],498+ ["sed", SED],499+ ["zgrep", GREP],500+]);501+502+/** Commands that read or copy the files they name. */503+const READERS = new Set([504+ ...names(505+ ". 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"506+ ),507+ ...PATTERN_FIRST.keys(),508+]);509+510+const judgeRead = (program: string, args: readonly string[]): Verdict => {511+ const patternFirst = PATTERN_FIRST.get(program);512+ const parsed = parse(args, patternFirst?.grammar ?? NO_OPTIONS, true);513+514+ if (patternFirst === undefined) {515+ return breaks(516+ "closed-env-read",517+ [...parsed.values.map(([, value]) => value), ...parsed.operands].some(518+ namesClosedEnv519+ )520+ );521+ }522+523+ const skipsFirst = !parsed.options.some((option) =>524+ patternFirst.instead.has(option)525+ );526+527+ const files = [528+ ...parsed.values.flatMap(([option, value]) =>529+ patternFirst.patterns.has(option) ? [] : [value]530+ ),531+ ...(skipsFirst ? parsed.operands.slice(1) : parsed.operands),532+ ];533+534+ return breaks(535+ "closed-env-read",536+ files.some(namesClosedEnv) || patternFirst.reachesClosed(parsed)537+ );538+};539+540+// ---------------------------------------------------------------------------541+// What actually runs: wrappers, shells and package runners.542+// ---------------------------------------------------------------------------543+544+/** Reserved words that may open a simple command: `if git push; then`. */545+const KEYWORDS = names("! do elif else if then until while { }");546+547+const DECLARATIONS = names("declare export local readonly typeset");548+549+const SHELLS = names("ash bash dash fish ksh sh zsh");550+551+const SHELL = grammar("-o --init-file --rcfile");552+553+/** Commands that run the command in their operands, with the options they take. */554+const WRAPPERS: ReadonlyMap<string, Grammar> = new Map([555+ ["builtin", NO_OPTIONS],556+ ["command", NO_OPTIONS],557+ ["doas", grammar("-C -a -u")],558+ ["env", grammar("-C -P -S -u --chdir --split-string --unset")],559+ ["exec", grammar("-a")],560+ ["nice", grammar("-n --adjustment")],561+ ["nohup", NO_OPTIONS],562+ ["stdbuf", grammar("-e -i -o --error --input --output")],563+ [564+ "sudo",565+ grammar(566+ "-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"567+ ),568+ ],569+ ["time", grammar("-f -o --format --output")],570+ ["timeout", grammar("-k -s --kill-after --signal")],571+ [572+ "xargs",573+ grammar(574+ "-E -I -L -P -a -d -n -s --arg-file --delimiter --eof --max-args --max-chars --max-lines --max-procs --process-slot-var --replace",575+ "-e -i -l"576+ ),577+ ],578+]);579+580+/** The command a wrapper runs: `sudo -u root git push` → `git push`. */581+const wrapped = (program: string, args: readonly string[]) => {582+ const parsed = parse(args, WRAPPERS.get(program) ?? NO_OPTIONS, false);583+584+ // `env -S 'git push'` splits its string into words.585+ const split = parsed.values.flatMap(([option, value]) =>586+ option === "-S" || option === "--split-string" ? wordsOf(value) : []587+ );588+589+ // `timeout 5 git push`: the duration comes first.590+ const operands =591+ program === "timeout" ? parsed.operands.slice(1) : parsed.operands;592+593+ return [...split, ...operands];594+};595+596+const LAUNCHER = grammar("-p --package");597+598+const NPX = grammar("-c -p -w --call --package --workspace");599+600+const BUN = grammar(601+ "-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"602+);603+604+// `bun -e` runs JavaScript, which is past what this policy can read.605+const EVALUATES = names("-e -p --eval --print");606+607+const PACKAGE_MANAGER = grammar(608+ "-C -F -w --cwd --dir --filter --prefix --workspace"609+);610+611+const VARLOCK = grammar("-p --env --path");612+613+const SCRIPT_RUNS = names("run run-script");614+615+const PACKAGE_RUNS = names("dlx exec x");616+617+/** A launched package's command: `wrangler@4 delete` → `wrangler delete`. */618+const launched = ([name = "", ...rest]: readonly string[]) => [619+ withoutVersion(name),620+ ...rest,621+];622+623+/** What `npx` and its kin run: a package's bin, or `-c`'s script. */624+const npx = (args: readonly string[]): readonly string[] => {625+ const parsed = parse(args, NPX, false);626+627+ const call = parsed.values.find(628+ ([option]) => option === "-c" || option === "--call"629+ );630+631+ return call === undefined ? launched(parsed.operands) : ["sh", "-c", call[1]];632+};633+634+/**635+ * A package script, or a file or bin run by name. `ops` is the root script636+ * `varlock run --path infra/ -- cf`, so `bun run ops -- x` runs `cf x`.637+ */638+const script = ([name = "", ...rest]: readonly string[]) => {639+ const args = rest[0] === "--" ? rest.slice(1) : rest;640+641+ return name === "ops" ? ["cf", ...args] : [name, ...args];642+};643+644+/** What bun, npm, pnpm or yarn runs, if anything. */645+const packageManagerRuns = (646+ program: string,647+ args: readonly string[]648+): Option.Option<readonly string[]> => {649+ const parsed = parse(args, program === "bun" ? BUN : PACKAGE_MANAGER, false);650+ const [subcommand = "", ...rest] = parsed.operands;651+652+ if (parsed.options.some((option) => EVALUATES.has(option))) {653+ return Option.none();654+ }655+656+ if (program === "bun" && subcommand === "exec") {657+ return Option.some(["sh", "-c", rest.join(" ")]);658+ }659+660+ if (SCRIPT_RUNS.has(subcommand)) {661+ return Option.some(script(parse(rest, PACKAGE_MANAGER, false).operands));662+ }663+664+ if (PACKAGE_RUNS.has(subcommand)) {665+ return Option.some(npx(rest));666+ }667+668+ // npm runs scripts only through `run`; bun, pnpm and yarn take a bare name.669+ return program === "npm"670+ ? Option.none()671+ : Option.some(script(parsed.operands));672+};673+674+/** The command a package runner runs, as words, if it runs one. */675+const runs = (676+ program: string,677+ args: readonly string[]678+): Option.Option<readonly string[]> => {679+ if (program === "bunx" || program === "pnpx") {680+ return Option.some(launched(parse(args, LAUNCHER, false).operands));681+ }682+683+ if (program === "npx") {684+ return Option.some(npx(args));685+ }686+687+ if (program === "varlock") {688+ const [subcommand, ...rest] = parse(args, VARLOCK, false).operands;689+690+ return subcommand === "run"691+ ? Option.some(parse(rest, VARLOCK, false).operands)692+ : Option.none();693+ }694+695+ return packageManagerRuns(program, args);696+};697+698+const PACKAGE_RUNNERS = names("bun bunx npm npx pnpm pnpx varlock yarn");699+700+const PROGRAMS: ReadonlyMap<string, (args: readonly string[]) => Verdict> =701+ new Map([702+ ["cf", judgeCf],703+ // cf's package installs the same bin as `cloudflare`.704+ ["cloudflare", judgeCf],705+ ["git", judgeGit],706+ ["jj", judgeJj],707+ ["lefthook", judgeLefthook],708+ ["wrangler", judgeWrangler],709+ ]);710+711+type Judge = (command: string) => Verdict;712+713+/** A shell runs `-c`'s script, or with no script operand, the one on stdin. */714+const judgeShell = (715+ args: readonly string[],716+ stdin: readonly string[],717+ judge: Judge718+): Verdict => {719+ const parsed = parse(args, SHELL, false);720+721+ const scripts = parsed.options.includes("-c")722+ ? parsed.operands.slice(0, 1)723+ : stdin;724+725+ return Option.firstSomeOf(scripts.map(judge));726+};727+728+/**729+ * The rule one simple command breaks, if any. `judge` reads a nested script,730+ * such as `sh -c`'s.731+ */732+const judgeWords = (733+ words: readonly string[],734+ stdin: readonly string[],735+ judge: Judge736+): Verdict => {737+ const leading = words.findIndex((word) => !ASSIGNMENT.test(word));738+ const assignments = leading === -1 ? words : words.slice(0, leading);739+ const [head = "", ...args] = leading === -1 ? [] : words.slice(leading);740+ const program = basename(head);741+742+ if (assignments.some(switchesOffHooks)) {743+ return Option.some("hook-bypass");744+ }745+746+ if (KEYWORDS.has(program)) {747+ return judgeWords(args, stdin, judge);748+ }749+750+ if (DECLARATIONS.has(program)) {751+ return breaks("hook-bypass", args.some(switchesOffHooks));752+ }753+754+ if (program === "eval") {755+ return judge(args.join(" "));756+ }757+758+ if (SHELLS.has(program)) {759+ return judgeShell(args, stdin, judge);760+ }761+762+ if (WRAPPERS.has(program)) {763+ return judgeWords(wrapped(program, args), stdin, judge);764+ }765+766+ if (PACKAGE_RUNNERS.has(program)) {767+ return Option.flatMap(runs(program, args), (inner) =>768+ judgeWords(inner, stdin, judge)769+ );770+ }771+772+ const judgeProgram = PROGRAMS.get(program);773+774+ if (judgeProgram !== undefined) {775+ return judgeProgram(args);776+ }777+778+ return READERS.has(program) ? judgeRead(program, args) : Option.none();779+};780+781+const ruleOf: Judge = (command) =>782+ Option.firstSomeOf(783+ simpleCommands(command).map((simple) =>784+ simple.reads.some(namesClosedEnv)785+ ? Option.some<Rule>("closed-env-read")786+ : judgeWords(simple.words, simple.stdin, ruleOf)787+ )788+ );789+790+/** Allow, or Deny with the rule the command breaks and what to do instead. */791+export const decide = (command: string): Decision =>792+ Option.match(ruleOf(command), {793+ onNone: () => Decision.Allow(),794+ onSome: (rule) => Decision.Deny({ reason: reasons[rule], rule }),795+ });added:scripts/hooks/lib/shell.ts+450 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: readonly string[];20+ readonly reads: readonly string[];21+ readonly stdin: readonly string[];22+}23+24+/** A simple command while the scan is still reading it. */25+interface Building {26+ readonly words: string[];27+ readonly reads: string[];28+ readonly stdin: string[];29+}30+31+interface Scanned {32+ readonly commands: readonly Simple[];33+ /** Just past the `)` that closed a nested scan, or the source's end. */34+ readonly end: number;35+}36+37+/** A heredoc whose body starts after the next newline. */38+interface Heredoc {39+ readonly delimiter: string;40+ /** A quoted delimiter keeps `$(…)` in the body from running. */41+ readonly quoted: boolean;42+ /** `<<-` strips leading tabs from each line. */43+ readonly tabs: boolean;44+ readonly into: string[];45+}46+47+/** What the word being read is for. */48+type Slot =49+ | "argument"50+ | "read"51+ | "write"52+ | "here-string"53+ | "heredoc"54+ | "heredoc-tabs";55+56+/** Redirect operators, longest first, and what the word after each is. */57+const REDIRECTS: readonly (readonly [string, Slot])[] = [58+ ["<<<", "here-string"],59+ ["<<-", "heredoc-tabs"],60+ ["&>>", "write"],61+ ["<<", "heredoc"],62+ ["<>", "read"],63+ ["<&", "write"],64+ ["&>", "write"],65+ [">>", "write"],66+ [">|", "write"],67+ [">&", "write"],68+ ["<", "read"],69+ [">", "write"],70+];71+72+const BLANKS = new Set([" ", "\t"]);73+74+// Inside double quotes, `\` escapes only these.75+const DOUBLE_QUOTE_ESCAPES = new Set(["$", "`", '"', "\\", "\n"]);76+77+// Inside backticks, `\` escapes only these.78+const BACKTICK_ESCAPES = new Set(["`", "\\", "$"]);79+80+const ANSI_C: ReadonlyMap<string, string> = new Map([81+ ["E", "\u001B"],82+ ["a", "\u0007"],83+ ["b", "\b"],84+ ["e", "\u001B"],85+ ["f", "\f"],86+ ["n", "\n"],87+ ["r", "\r"],88+ ["t", "\t"],89+ ["v", "\v"],90+]);91+92+const ANSI_C_ESCAPE =93+ /\\(?:x(?<hex>[\da-f]{1,2})|u(?<unicode>[\da-f]{1,4})|(?<octal>[0-7]{1,3})|(?<char>[\s\S]))/giu;94+95+const decodeEscape = (96+ hex: string | undefined,97+ unicode: string | undefined,98+ octal: string | undefined,99+ char: string | undefined100+): string => {101+ if (hex !== undefined) {102+ return String.fromCodePoint(Number.parseInt(hex, 16));103+ }104+105+ if (unicode !== undefined) {106+ return String.fromCodePoint(Number.parseInt(unicode, 16));107+ }108+109+ if (octal !== undefined) {110+ return String.fromCodePoint(Number.parseInt(octal, 8));111+ }112+113+ return ANSI_C.get(char ?? "") ?? char ?? "";114+};115+116+/** The text of an ANSI-C quoted `$'…'` body, escapes decoded. */117+const ansiC = (body: string): string => {118+ let decoded = "";119+ let from = 0;120+121+ for (const match of body.matchAll(ANSI_C_ESCAPE)) {122+ const { char, hex, octal, unicode } = match.groups ?? {};123+124+ decoded += body.slice(from, match.index);125+ decoded += decodeEscape(hex, unicode, octal, char);126+ from = match.index + match[0].length;127+ }128+129+ return decoded + body.slice(from);130+};131+132+/**133+ * Reads `src` from `start` into simple commands. A nested scan (inside `$(`)134+ * stops at its unmatched `)`. Unclosed quotes run to the end, so a command a135+ * shell would refuse to parse is still judged on what it holds.136+ */137+const scan = (src: string, start: number, nested: boolean): Scanned => {138+ const commands: Simple[] = [];139+ const heredocs: Heredoc[] = [];140+ let simple: Building = { reads: [], stdin: [], words: [] };141+ let word = "";142+ let inWord = false;143+ let quoted = false;144+ let slot: Slot = "argument";145+ let depth = 0;146+ let at = start;147+148+ const append = (text: string, fromQuotes: boolean) => {149+ word += text;150+ inWord = true;151+ quoted ||= fromQuotes;152+ };153+154+ // `$(…)`: what it runs is judged; its source text stands in for its output.155+ const substitution = (from: number) => {156+ const inner = scan(src, from + 2, true);157+158+ commands.push(...inner.commands);159+160+ return { end: inner.end, text: src.slice(from, inner.end) };161+ };162+163+ // `…`: up to the next unescaped backtick.164+ const backtick = (from: number) => {165+ let body = "";166+ let end = from + 1;167+168+ while (end < src.length && src[end] !== "`") {169+ const next = src[end + 1] ?? "";170+ const escaped = src[end] === "\\" && BACKTICK_ESCAPES.has(next);171+172+ body += escaped ? next : (src[end] ?? "");173+ end += escaped ? 2 : 1;174+ }175+176+ commands.push(...scan(body, 0, false).commands);177+178+ return { end: end + 1, text: src.slice(from, end + 1) };179+ };180+181+ // Double-quoted text, or an unquoted heredoc's body: `$(…)` and backticks182+ // still run there. Stops before `limit`, or at `closing`.183+ const expand = (from: number, limit: number, closing: string) => {184+ let text = "";185+ let end = from;186+187+ while (end < limit && src[end] !== closing) {188+ const char = src[end] ?? "";189+ const next = src[end + 1] ?? "";190+191+ if (char === "\\" && DOUBLE_QUOTE_ESCAPES.has(next)) {192+ text += next === "\n" ? "" : next;193+ end += 2;194+ } else if ((char === "$" && next === "(") || char === "`") {195+ const { end: after, text: source } =196+ char === "`" ? backtick(end) : substitution(end);197+198+ text += source;199+ end = after;200+ } else {201+ text += char;202+ end += 1;203+ }204+ }205+206+ return { end: end + 1, text };207+ };208+209+ // At a newline: each pending heredoc's body, line by line to its delimiter.210+ const readHeredocs = (from: number): number => {211+ let line = from;212+213+ for (const heredoc of heredocs) {214+ const lines: string[] = [];215+ const bodyStart = line;216+ let bodyEnd = line;217+218+ while (line < src.length) {219+ const newline = src.indexOf("\n", line);220+ const eol = newline === -1 ? src.length : newline;221+ const raw = src.slice(line, eol);222+ const text = heredoc.tabs ? raw.replace(/^\t+/u, "") : raw;223+224+ line = eol + 1;225+226+ if (text === heredoc.delimiter) {227+ break;228+ }229+230+ lines.push(text);231+ bodyEnd = eol;232+ }233+234+ heredoc.into.push(lines.join("\n"));235+236+ if (!heredoc.quoted) {237+ expand(bodyStart, bodyEnd, "");238+ }239+ }240+241+ heredocs.splice(0);242+243+ return line;244+ };245+246+ const finishWord = () => {247+ if (!inWord) {248+ return;249+ }250+251+ if (slot === "argument") {252+ simple.words.push(word);253+ } else if (slot === "read") {254+ simple.reads.push(word);255+ } else if (slot === "here-string") {256+ simple.stdin.push(word);257+ } else if (slot === "heredoc" || slot === "heredoc-tabs") {258+ heredocs.push({259+ delimiter: word,260+ into: simple.stdin,261+ quoted,262+ tabs: slot === "heredoc-tabs",263+ });264+ }265+266+ word = "";267+ inWord = false;268+ quoted = false;269+ slot = "argument";270+ };271+272+ const finishCommand = () => {273+ finishWord();274+ slot = "argument";275+276+ const { reads, stdin, words } = simple;277+278+ if (words.length + reads.length + stdin.length > 0) {279+ commands.push(simple);280+ }281+282+ simple = { reads: [], stdin: [], words: [] };283+ };284+285+ // `<`, `<<`, `>`, `>>`, `&>` and the rest. An unquoted all-digit word right286+ // before one is its file descriptor, not an argument.287+ const redirect = (): number => {288+ if (inWord && !quoted && /^\d+$/u.test(word)) {289+ word = "";290+ inWord = false;291+ } else {292+ finishWord();293+ }294+295+ const [operator, target] = REDIRECTS.find(([text]) =>296+ src.startsWith(text, at)297+ ) ?? [">", "write"];298+299+ slot = target;300+301+ return at + operator.length;302+ };303+304+ // `$'…'`, `$(…)` and `${…}`; any other `$` is a literal.305+ const dollar = (next: string): number | undefined => {306+ if (next === "'") {307+ let end = at + 2;308+309+ while (end < src.length && src[end] !== "'") {310+ end += src[end] === "\\" ? 2 : 1;311+ }312+313+ append(ansiC(src.slice(at + 2, Math.min(end, src.length))), true);314+315+ return end + 1;316+ }317+318+ if (next === "(") {319+ const inner = substitution(at);320+321+ append(inner.text, false);322+323+ return inner.end;324+ }325+326+ if (next === "{") {327+ const close = src.indexOf("}", at);328+ const end = close === -1 ? src.length : close + 1;329+330+ append(src.slice(at, end), false);331+332+ return end;333+ }334+335+ return undefined;336+ };337+338+ // Quotes, escapes and expansions, each part of the current word. None when339+ // `char` starts none of them.340+ const wordPart = (char: string, next: string): number | undefined => {341+ if (char === "\\") {342+ if (next !== "\n") {343+ append(next, true);344+ }345+346+ return at + 2;347+ }348+349+ if (char === "'") {350+ const close = src.indexOf("'", at + 1);351+ const end = close === -1 ? src.length : close;352+353+ append(src.slice(at + 1, end), true);354+355+ return end + 1;356+ }357+358+ if (char === '"') {359+ const inner = expand(at + 1, src.length, '"');360+361+ append(inner.text, true);362+363+ return inner.end;364+ }365+366+ // Backticks, and the process substitutions `<(…)` and `>(…)`.367+ if (char === "`" || ((char === "<" || char === ">") && next === "(")) {368+ const inner = char === "`" ? backtick(at) : substitution(at);369+370+ append(inner.text, false);371+372+ return inner.end;373+ }374+375+ return char === "$" ? dollar(next) : undefined;376+ };377+378+ // Blanks, newlines, comments, redirects and the operators between simple379+ // commands. None when `char` is none of them.380+ const operator = (char: string, next: string): number | undefined => {381+ if (BLANKS.has(char)) {382+ finishWord();383+384+ return at + 1;385+ }386+387+ if (char === "\n") {388+ finishCommand();389+390+ return heredocs.length > 0 ? readHeredocs(at + 1) : at + 1;391+ }392+393+ if (char === "#" && !inWord) {394+ const newline = src.indexOf("\n", at);395+396+ return newline === -1 ? src.length : newline;397+ }398+399+ if (char === "<" || char === ">" || (char === "&" && next === ">")) {400+ return redirect();401+ }402+403+ if (char === ";" || char === "&" || char === "|") {404+ finishCommand();405+406+ return at + (next === char || (char === "|" && next === "&") ? 2 : 1);407+ }408+409+ if (char === "(" || char === ")") {410+ finishCommand();411+ depth = char === "(" ? depth + 1 : Math.max(0, depth - 1);412+413+ return at + 1;414+ }415+416+ return undefined;417+ };418+419+ while (at < src.length) {420+ const char = src[at] ?? "";421+ const next = src[at + 1] ?? "";422+423+ if (char === ")" && nested && depth === 0) {424+ finishCommand();425+426+ return { commands, end: at + 1 };427+ }428+429+ const after = wordPart(char, next) ?? operator(char, next);430+431+ if (after === undefined) {432+ append(char, false);433+ at += 1;434+ } else {435+ at = after;436+ }437+ }438+439+ finishCommand();440+441+ return { commands, end: src.length };442+};443+444+/** The simple commands in `command`, including those inside substitutions. */445+export const simpleCommands = (command: string): readonly Simple[] =>446+ scan(command, 0, false).commands;447+448+/** The words of the first simple command in `text`, as `env -S` splits it. */449+export const wordsOf = (text: string): readonly string[] =>450+ scan(text, 0, false).commands[0]?.words ?? [];added:scripts/hooks/vcs-policy.ts+139 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 a failure while it judges, is a refusal: it fails14+ * closed. A hook that cannot start at all (no `bun install` yet) exits 1,15+ * which Cursor's `failClosed` blocks and Claude Code reports without blocking.16+ */17+import { BunRuntime, BunServices } from "@effect/platform-bun";18+import {19+ Data,20+ Effect,21+ Match,22+ Option,23+ Runtime,24+ Schema,25+ Stdio,26+ Stream,27+} from "effect";28+29+import { Decision, decide } from "./lib/policy.ts";30+31+/** Tags each payload with its harness, which its JSON doesn't carry. */32+const harness = <const Name extends string>(name: Name) =>33+ Schema.tag(name).pipe(Schema.withDecodingDefaultKey(Effect.succeed(name)));34+35+/** Claude Code's PreToolUse payload for the Bash tool. */36+const ClaudePreToolUse = Schema.Struct({37+ _tag: harness("Claude"),38+ tool_input: Schema.Struct({ command: Schema.String }),39+});40+41+/** Cursor's beforeShellExecution payload. */42+const CursorShell = Schema.Struct({43+ _tag: harness("Cursor"),44+ command: Schema.String,45+ hook_event_name: Schema.Literal("beforeShellExecution"),46+});47+48+/** Any other caller: `{"command": "…"}`. */49+const Bare = Schema.Struct({ _tag: harness("Bare"), command: Schema.String });50+51+const HookInput = Schema.fromJsonString(52+ Schema.Union([ClaudePreToolUse, CursorShell, Bare])53+);54+55+type HookInput = typeof HookInput.Type;56+57+const CANNOT_READ =58+ '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": "…"}.';59+60+/** A refusal this hook has already printed; it only sets the exit code. */61+class Refused extends Data.TaggedError("Refused")<{62+ readonly reason: string;63+}> {64+ override readonly [Runtime.errorExitCode] = 2;65+ override readonly [Runtime.errorReported] = false;66+}67+68+/** Who answers, and the refusal, if any, in words for the agent. */69+interface Verdict {70+ readonly harness: HookInput["_tag"];71+ readonly refusal: Option.Option<string>;72+}73+74+const commandOf = (input: HookInput) =>75+ Match.valueTags(input, {76+ Bare: ({ command }) => command,77+ Claude: ({ tool_input }) => tool_input.command,78+ Cursor: ({ command }) => command,79+ });80+81+const explain = (decision: Decision): Option.Option<string> =>82+ Decision.$match(decision, {83+ Allow: () => Option.none(),84+ Deny: ({ reason, rule }) =>85+ Option.some(`vcs-policy refused this command (${rule}): ${reason}`),86+ });87+88+const UNREADABLE: Verdict = {89+ harness: "Bare",90+ refusal: Option.some(CANNOT_READ),91+};92+93+const judged: Effect.Effect<Verdict, never, Stdio.Stdio> = Effect.gen(94+ function* () {95+ const stdio = yield* Stdio.Stdio;96+ const raw = yield* stdio.stdin.pipe(Stream.decodeText(), Stream.mkString);97+ const input = yield* Schema.decodeEffect(HookInput)(raw);98+99+ return {100+ harness: input._tag,101+ refusal: explain(decide(commandOf(input))),102+ };103+ }104+).pipe(105+ // Unreadable stdin, a payload of no known shape, or a defect: refuse.106+ Effect.catchCause(() => Effect.succeed(UNREADABLE))107+);108+109+/** Cursor reads its answer, allow or deny, from stdout. */110+const answerCursor = (refusal: Option.Option<string>) => {111+ const reply = Option.match(refusal, {112+ onNone: () => ({ permission: "allow" }),113+ onSome: (message) => ({114+ agent_message: message,115+ permission: "deny",116+ user_message: message,117+ }),118+ });119+120+ return Effect.flatMap(Stdio.Stdio, (stdio) =>121+ Stream.run(Stream.make(`${JSON.stringify(reply)}\n`), stdio.stdout())122+ );123+};124+125+/** Claude Code and a bare caller read a refusal from exit 2 and stderr. */126+const answerByExit = (refusal: Option.Option<string>) =>127+ Option.match(refusal, {128+ onNone: () => Effect.void,129+ onSome: (message) =>130+ Effect.flatMap(Stdio.Stdio, (stdio) =>131+ Stream.run(Stream.make(`${message}\n`), stdio.stderr())132+ ).pipe(Effect.andThen(Effect.fail(new Refused({ reason: message })))),133+ });134+135+const main = Effect.flatMap(judged, ({ harness: answerer, refusal }) =>136+ answerer === "Cursor" ? answerCursor(refusal) : answerByExit(refusal)137+);138+139+BunRuntime.runMain(main.pipe(Effect.provide(BunServices.layer)));