#!/usr/bin/env node // PreToolUse hook (Bash, Agent): refuses the tool calls the delivery rules forbid, repairs the // ones whose fix is known, and adds to an agent's prompt the text it would otherwise open. // // check a sub-agent runs a check from toolchain.md's "Checks agents never run" (`pnpm // check`, `pnpm fallow`, ...) or a tool behind one, from any path. The commit hook, // the push hook and CI run them. The main session (a person, a routine) may. // hooks a sub-agent skips the git hooks: `--no-verify`, `LEFTHOOK=0`, `core.hooksPath`, or // `LEFTHOOK_EXCLUDE` naming anything but `fallow` (a build stage's push before its // last cycle, whose code a later cycle wires in Fallow calls dead code). // isolation an `implementer`, `reviewer` or `hardware-verifier` is started with `isolation`. // Every stage of a task works in the task's one worktree, one after another. // waiting a sub-agent starts a background job (`run_in_background`, a trailing `&`), polls // in a loop that sleeps, or runs a bare `cat > file` with no input (it reads stdin // until the tool times out). Each of these turned into a stall: a backgrounded job // holds the agent's report until the job ends or hits its 30-minute cap. The slow // lane is exempt: `slow-e2e.sh` runs detached by design and its agents wait on // `.exit` (delivery rule 16). // // prompt a stage or lens agent (`implementer`, `reviewer`, `hardware-verifier`, // `spec-reviewer`, `code-reviewer`, `claims-reviewer`) is started without the ledger // tag as its prompt's first line (toolchain.md, "Review measurement") and the prompt // does not say what the tag holds (see repair); the refusal prints the line for that // agent and stage. An // `implementer` without a `mode:` line; a stage agent with a `model`; a `code-reviewer` // off Opus on a diff that touches a strict area (REVIEW.md, "Routing"), outside a // replay; or a sub-agent starts a helper that is not `run_in_background: false`. // git any session pushes to `origin`'s `main`: by name, as `:main`, with `--all`, // or from a branch that tracks `origin/main` while `push.default` is `upstream` // (git then sends `git push`, and `git push origin `, to `main`). A // sub-agent runs `git stash` (but `list` or `show`), `git rebase` (or `pull // --rebase`), or a push that rewrites or deletes a remote branch (`+`, // `:`, `--force`, `--delete`). // gh a sub-agent opens a PR without `--draft` (or a REST create without // `draft=true`), opens one from a `-repro` branch, runs `gh pr ready`, or adds // `bug:ready`, `task:ready`, `refactor:ready` or `feature:planned`; a // `bug-triager` or an `implementer` runs `fast-track.mjs` (delivery rule 17); any // session assigns an issue by hand instead of through `claim.mjs`. // shim any session runs `gh` by a path, or writes with `gh` in a call that sets PATH, // defines a `gh` function or alias, or runs `command -p`, `env -i`/`-u` or // `hash -p`; a sub-agent names `SIMLOCK_GH_AGENT`. The `gh` first on PATH // (`.agents/shims/gh`, put there by `session-env.sh`) checks a posted body, and a // sub-agent's labels (`gh-labels.mjs`), on gh's real arguments when the call runs. // slow lane any session runs vitest on an `e2e/slow-*` file, or the e2e project without a // `!slow` tags filter; a sub-agent runs `pnpm test:e2e:slow` (or a physical lane); // an agent other than `hardware-verifier` and `implementer` runs `slow-e2e.sh` // for anything but `status` (delivery rule 16). // // repair not a refusal: the guard makes the one known fix, returns the call as // `updatedInput` and says so in `additionalContext`. A sub-agent's test run gets // `timeout: 600000` (the default 120 s moves a two-minute run to the background); // its `tsc --noEmit` on a project `pnpm typecheck` compiles becomes `pnpm typecheck`. // A stage or lens agent's prompt gets its ledger tag as the first line, in place // of a wrong one, when the agent's type and the prompt's `mode:`, `round:`, `pr:` // and `issue:` lines (or a wrong tag's `key=value` pairs) give every value. Every // sub-agent call starts with `export SIMLOCK_GH_AGENT=`, for the shim. // // inject not a refusal: the guard appends to the prompt the text the agent would otherwise // open or its caller paste: an `implementer`'s mode brief under `brief:`; a // `reviewer`'s protocol under `protocol:`, from `/review-protocol.md` when // the prompt names `inputs:` (a replay) and this checkout's // `docs/internal/REVIEW.md` otherwise; a lens's brief from `/briefs/`, after // `review-later-round.md` when the round is not 1; and the rule-file sections a // role opens on almost every run (`RULE_TEXT`), read from the files at run time. // A prompt that already carries the text is left alone. // // A refusal exits 2 with the reason on stderr, which the agent reads. import { execFileSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { flagValues as ghFlagValues, ghArgs } from "./gh-argv.mjs"; import { commandWords, parseShell } from "./shell-words.mjs"; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const SCRIPTS = new Set([ "check", "test", "test:timing", "typecheck:e2e", "typecheck:e2e:types", "lint", "lint:comments", "lint:tests", "format", "format:check", "fallow", "mutate", ]); const TOOLS = new Set(["tsc", "oxlint", "depcruise", "oxfmt", "fallow", "stryker"]); const NODE_SCRIPTS = new Set(["comment-lint.mjs", "test-lint.mjs", "mutate.mjs"]); const WRAPPERS = new Set(["time", "nice", "env", "command", "exec"]); const PNPM_VALUE_FLAGS = new Set(["-C", "--dir", "-F", "--filter", "--reporter"]); const STAGES = new Set(["implementer", "reviewer", "hardware-verifier"]); const LENSES = new Set(["spec-reviewer", "code-reviewer", "claims-reviewer"]); const LEDGER = /^ledger: (?=.*\bpr=\S+)(?=.*\bstage=(?:build|audit|fix|hardware-fix|review|hardware|replay)\b)(?=.*\brole=\S+)/; // why: toolchain.md "Project checks" lists these; src/contract/ holds the wire validators. const STRICT_AREAS = [ /^src\/leasing\//, /^src\/contract\//, /^src\/core\/cleanup\//, /^src\/core\/(?:registry|serialized-decision|device-operation-claims|reclaim-coordinator|quarantine-coordinator|reaper|cleanup-executor|nuke|nuke-service|managed-device-lifecycle|device-root|physical-enrollment|startup-converger)\.ts$/, ]; // why: the stage and role each agent type's tag carries (toolchain.md, "Review measurement"); an // implementer's stage is its mode, and a refactor is tagged as a build. const TAG_ROLES = { implementer: "implementer", reviewer: "reviewer", "hardware-verifier": "hardware-verifier", "spec-reviewer": "spec", "code-reviewer": "code", "claims-reviewer": "claims", }; // why: a build, an audit or a hardware run belongs to no review round. const ROUNDLESS = new Set(["implementer", "hardware-verifier"]); const MODE_STAGES = { build: "build", audit: "audit", fix: "fix", "hardware-fix": "hardware-fix", refactor: "build", }; const WORK_LABELS = new Set(["bug:ready", "task:ready", "refactor:ready", "feature:planned"]); const SLOW_LANE_AGENTS = new Set(["hardware-verifier", "implementer"]); // why: the fast track checks their report and their fix, so they never run it on themselves. const FAST_TRACK_AUTHORS = new Set(["bug-triager", "implementer"]); const SLOW_LANE_SCRIPTS = new Set([ "test:e2e:slow", "test:e2e:physical", "test:e2e:physical-manual", ]); const GIT_VALUE_FLAGS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace"]); const PUSH_VALUE_FLAGS = new Set(["--repo", "--receive-pack", "--exec", "-o", "--push-option"]); // why: the projects `pnpm typecheck` compiles (package.json); any other is not its to check. const TYPECHECK_PROJECTS = new Set([ ".", "tsconfig.json", "ui", "ui/tsconfig.json", "packages/e2e", "packages/e2e/tsconfig.json", ]); // why: every way a call may start `tsc` and still be rewritten; any other launcher or flag // (`--dir=`, `-r`, `--prefix=`) runs it somewhere `pnpm typecheck` does not. const TSC_LAUNCHERS = new Set([ "", "pnpm", "pnpm exec", "npx", "npx -y", "npx --yes", "npx --no-install", ]); // why: only finds the text of a candidate run in the blanked command: at the start of a word, a // launcher from the list, the program as a whole word (any path, so a drive letter or `~` stays // in it), plain arguments, then the command's end or a redirect. `isTypecheck` decides. const TSC_RUN = /(?<=^|[\s;&|()`])(?:pnpm(?:[ \t]+exec)?[ \t]+|npx(?:[ \t]+(?:-y|--yes|--no-install))?[ \t]+)?(?:[^\s;&|()<>`'"$\\]*\/)?tsc(?![^\s;&|()<>`])(?:[ \t]+[\w./=-]+(?![\w./=-]|[<>]))*(?=[ \t]*(?:$|[\n;&|)`]|\d*[<>]))/g; const TIMEOUT_NOTE = "The tool guard set `timeout: 600000` on this Bash call: a test run under the default 120 s " + "moves to the background."; const TYPECHECK_NOTE = "The tool guard ran `pnpm typecheck` in place of this call's `tsc --noEmit`: it is the type " + 'check agents run (toolchain.md, "Tests agents run").'; const GH_API_VALUE_FLAGS = new Set([ "-X", "--method", "-H", "--header", "-f", "-F", "--field", "--raw-field", "--input", "-q", "--jq", "-t", "--template", "--hostname", "--cache", "-p", "--preview", ]); // why: the runners agents are allowed to run; `slow-e2e.sh` is excluded above, not here. const TEST_RUNNER = /\bvitest\s+(?:run|--)|\bplaywright\s+test\b|\bpnpm\s+(?:run\s+)?test(?::[\w-]+)?(?:\s|$)/; // why: a `&` that is not `&&` and ends a command or a line starts a background job. const BACKGROUND_JOB = /(?:^|[^&])&\s*(?:$|\n|\)|;)/m; const SLEEP_LOOP = /\b(?:until|while|for)\b[^\n]*\bdo\b[\s\S]*?\bsleep\b/; // why: `cat > file` followed by a terminator, with no `<<` heredoc and no `<` input, hangs. const BARE_CAT = /(?:^|[;&|]\s*|\n\s*)cat\s*>{1,2}\s*\S+(?:\s+\d?>{1,2}\S+)*\s*(?:;|&&|\|\||\n|$)/; const HOOK_BYPASS = [ /--no-verify\b/, /\bLEFTHOOK=(?:0|false)\b/, /\bcore\.hooksPath\b/, /\bLEFTHOOK_EXCLUDE=(?!fallow(?:\s|$))/, ]; // why: each rule is a refusal and the test that triggers it; `refuseFirst` walks a table. function refuseFirst(rules, ctx) { for (const rule of rules) { if (rule.when(ctx)) refuse(typeof rule.reason === "function" ? rule.reason(ctx) : rule.reason); } } const AGENT_RULES = [ { when: (c) => Boolean(args.isolation) && STAGES.has(c.type), reason: (c) => `Refused: pass no \`isolation\` to the ${c.type}. Every stage of a task works in ` + "the task's one worktree (`.agents/scripts/worktree.sh `), one stage after " + "another. Start the agent again without `isolation`.", }, { when: (c) => STAGES.has(c.type) && typeof args.model === "string" && args.model !== "", reason: (c) => `Refused: pass no \`model\` to the ${c.type}: it runs on the model its frontmatter pins. ` + "Start the agent again without `model`.", }, { when: () => subAgent && args.run_in_background !== false, reason: "Refused: a helper agent runs in the foreground: pass `run_in_background: false`. A " + "background helper reports to the orchestrator, not to you, and nothing wakes you when " + "it ends.", }, ]; // why: a model that pastes a brief pays for it twice and paraphrases it; the hook adds the file's // own bytes to the prompt the agent receives, and the caller's context keeps the short one. const PROMPT_TEXT = { implementer: briefText, reviewer: protocolText, "spec-reviewer": (prompt) => lensText(prompt, "review-spec.md"), "code-reviewer": (prompt) => lensText(prompt, "review-code.md") + ruleText(prompt, "code-reviewer"), "claims-reviewer": (prompt) => lensText(prompt, "review-claims.md"), "hardware-verifier": (prompt) => ruleText(prompt, "hardware-verifier"), "bug-triager": (prompt) => ruleText(prompt, "bug-triager"), }; // why: the parts of the rule files a role opened on almost every run (transcripts 2026-11-06 to // 27): a `##` section by its heading, a numbered rule by its number. const RULE_TEXT = { "code-reviewer": [["toolchain.md", "Tests agents run"]], "hardware-verifier": [["toolchain.md", "Slow lane"]], "bug-triager": [ ["toolchain.md", "Tests agents run"], ["testing.md", 10], ["delivery.md", 8], ["delivery.md", 17], ], }; function agentRules() { const ctx = { type: args.subagent_type, prompt: String(args.prompt ?? "") }; refuseFirst(AGENT_RULES, ctx); const tagged = taggedPrompt(ctx); if (ctx.type === "code-reviewer") strictAreaCheck(tagged.prompt); const text = PROMPT_TEXT[ctx.type]?.(tagged.prompt) ?? ""; if (text === "" && tagged.note === undefined) return; const prompt = text === "" ? tagged.prompt : `${tagged.prompt.trimEnd()}\n${text}`; answer({ updatedInput: { ...args, prompt }, ...(tagged.note !== undefined && { additionalContext: tagged.note }), }); } // why: a refused spawn costs the orchestrator a turn, and its second try was refused again in 19 // of 44 cases (transcripts 2026-11-01 to 28); the prompt's own lines usually say what the tag holds. function taggedPrompt(ctx) { const first = firstLine(ctx.prompt); if (TAG_ROLES[ctx.type] === undefined || LEDGER.test(first)) return { prompt: ctx.prompt }; const tag = ledgerTag(ctx.type, ctx.prompt, first); if (tag.missing.length > 0) { refuse( 'Refused: the prompt\'s first line is the ledger tag (toolchain.md, "Review measurement"). ' + `For this ${ctx.type} it is \`${tag.line}\`, with ${tag.missing.join(" and ")} filled ` + "in. Start the agent again with that line first.", ); } const body = ctx.prompt.replace(/^\s+/, ""); const rest = TAG_LIKE.test(first) ? body.slice(first.length).replace(/^\n/, "") : body; return { prompt: `${tag.line}\n${rest}`, note: `The tool guard set this prompt's first line to \`${tag.line}\`, the ledger tag for this ${ctx.type}; write that line yourself next time.`, }; } // why: a first line that tried to be the tag (`[ledger #48 implement]`, `ledger: ... stage=implement`) // is replaced; any other first line is the prompt's own and stays under the tag. const TAG_LIKE = /^\[?\s*(?:ledger|deliver|delivery)\b/i; // why: each part is its text in the tag and, when the prompt does not give its value, the name // the refusal asks for; the text then holds the placeholder toolchain.md shows. function ledgerTag(type, prompt, first) { const said = tagReader(prompt, first); const lens = type === "code-reviewer" ? said("lens", /behaviour|tests|both/) : undefined; const parts = [ tagNumbers(said("pr", /\d+/), said("issue", /\d+/)), tagPart( "stage", tagStage(type, prompt, first), "", "the stage (the prompt's `mode:`)", ), tagPart( "round", said("round", /1|2|fix-check/) ?? (ROUNDLESS.has(type) ? "-" : undefined), "<1|2|fix-check>", "the round", ), tagPart("role", TAG_ROLES[type]), tagPart("lens", lens ?? "-"), ]; return { line: `ledger: ${parts.map((part) => part.text).join(" ")}`, missing: parts.flatMap((part) => part.missing), }; } // why: a wrong tag's own `key=value` comes first, then the prompt's `key: value` line. function tagReader(prompt, first) { const tag = TAG_LIKE.test(first) ? first : ""; return (key, value) => new RegExp(`\\b${key}=#?(${value.source})(?=\\s|$)`).exec(tag)?.[1] ?? new RegExp(`^${key}:\\s*[\`#]?(${value.source})(?=[\`\\s]|$)`, "im").exec(prompt)?.[1]; } function tagNumbers(pr, issue) { if (pr === undefined && issue === undefined) return { text: "pr= issue=", missing: ["the PR or the issue number"] }; return { text: `pr=${pr ?? "-"} issue=${issue ?? "-"}`, missing: [] }; } function tagPart(key, value, placeholder, name) { if (value === undefined) return { text: `${key}=${placeholder}`, missing: [name] }; return { text: `${key}=${value}`, missing: [] }; } function tagStage(type, prompt, first) { if (type === "implementer") return MODE_STAGES[/^mode:\s*`?([\w-]+)/m.exec(prompt)?.[1]]; if (type === "hardware-verifier") return "hardware"; return /\bstage=replay\b/.test(first) || /^replay:\s*true\b/m.test(prompt) ? "replay" : "review"; } function answer(output) { process.stdout.write( JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", ...output } }), ); } function firstLine(prompt) { return prompt.replace(/^\s+/, "").split("\n")[0]; } function carries(prompt, text) { return squash(prompt).includes(squash(text).slice(0, 200)); } function briefText(prompt) { const mode = /^mode:\s*`?([\w-]+)/m.exec(prompt)?.[1]; const file = path.join(ROOT, ".agents", "briefs", `implement-${mode}.md`); if (mode === undefined || !fs.existsSync(file)) { refuse( "Refused: an implementer's prompt names its mode on a `mode:` line: build, audit, fix, " + "hardware-fix or refactor. Start the agent again with it.", ); } const brief = fs.readFileSync(file, "utf8"); return carries(prompt, brief) ? "" : `brief:\n${brief}`; } // why: a prompt that names `inputs:` (a replay) is judged by the pinned base's protocol; a live // reviewer builds its inputs after this hook ran, so it gets this checkout's. function protocolText(prompt) { const protocol = inputsFile(prompt, "review-protocol.md") ?? fs.readFileSync(path.join(ROOT, "docs", "internal", "REVIEW.md"), "utf8"); return carries(prompt, protocol) ? "" : `protocol:\n${protocol}`; } // why: null when the prompt names no `inputs:` directory, or the guard cannot read the file. function inputsFile(prompt, ...name) { const dir = /^inputs:\s*[`'"]?([^`'"\s]+)/m.exec(prompt)?.[1]; if (dir === undefined) return null; try { return fs.readFileSync(path.resolve(cwd, dir, ...name), "utf8"); } catch { return null; } } // why: a lens is judged by the pinned base's briefs, which the inputs directory holds; a // directory the guard cannot read leaves the prompt alone, and the lens reads the files itself. function lensText(prompt, name) { const round = /^round:\s*`?([\w-]+)/m.exec(prompt)?.[1] ?? /\bround=(\S+)/.exec(firstLine(prompt))?.[1]; const names = round === "1" ? [name] : ["review-later-round.md", name]; let text = ""; for (const n of names) { const brief = inputsFile(prompt, "briefs", n); if (brief === null) return ""; if (!carries(prompt, brief)) text += `=== briefs/${n} ===\n${brief}\n`; } return text; } // why: a lens reads the pinned base's rule files (`/rules/`), every other role this // checkout's; a file or a part the guard cannot find adds nothing, and the agent opens the file. function ruleText(prompt, role) { let text = ""; for (const [file, part] of RULE_TEXT[role]) { const rules = LENSES.has(role) ? inputsFile(prompt, "rules", file) : readOrNull(path.join(ROOT, "docs", "internal", "agent-rules", file)); const found = rules === null ? "" : rulePart(rules, part); if (found === "" || carries(prompt, found)) continue; const label = typeof part === "number" ? `rule ${part}` : `"${part}"`; text += `=== ${file}, ${label}, in full ===\n${found}\n`; } return text; } function rulePart(rules, part) { const lines = rules.split("\n"); const numbered = typeof part === "number"; const from = lines.findIndex((l) => (numbered ? l.startsWith(`${part}. `) : l === `## ${part}`)); if (from === -1) return ""; const ends = (l) => l.startsWith("## ") || (numbered && l.startsWith(`${part + 1}. `)); const length = lines.slice(from + 1).findIndex(ends); return lines .slice(from, length === -1 ? undefined : from + 1 + length) .join("\n") .trim(); } function readOrNull(file) { try { return fs.readFileSync(file, "utf8"); } catch { return null; } } function strictAreaCheck(prompt) { const model = typeof args.model === "string" ? args.model : ""; if (model === "" || /opus/i.test(model) || /\bstage=replay\b/.test(prompt)) return; const hit = [...inputsPatch(prompt).matchAll(/^diff --git a\/(\S+) b\/(\S+)/gm)] .flatMap((m) => [m[1], m[2]]) .find((p) => STRICT_AREAS.some((re) => re.test(p))); if (hit !== undefined) { refuse( `Refused: the diff touches a strict area (\`${hit}\`, toolchain.md "Project checks"), and ` + 'its code review runs on Opus (REVIEW.md, "Routing"). Start the code-reviewer again ' + "with no `model`, or `model: opus`.", ); } } // why: an `inputs:` directory the guard cannot read leaves the call alone. function inputsPatch(prompt) { return inputsFile(prompt, "diff.patch") ?? ""; } function commandRules(raw) { const commands = parseShell(raw); shimRules(raw, commands); const state = { dir: cwd }; for (const cmd of commands) { const { words, dynamic } = commandWords(cmd); if (words.length > 0 && !changesDirectory(state, words, dynamic)) commandStep(state, words, dynamic); } } // why: the `gh` on PATH (`.agents/shims/gh`) checks a body and a sub-agent's labels; a call that // could reach another `gh` in the same call as a write is refused. Defence in depth: the merge // gate's `pr-body-check.mjs` is the backstop for a body, PR #1944's author check for the hold. // why: every command the call runs, the script of a `bash|sh|zsh -c '...'` included: its words // come quoting removed and pieces joined, and a string stays one word, so `"PATH=x"` after // `export` is seen and a `grep 'export PATH'` pattern is not. const SHELLS = new Set(["bash", "sh", "zsh", "dash"]); function allCommands(commands, depth = 0) { return commands.flatMap((cmd) => { const { words } = commandWords(cmd); const at = words.indexOf("-c"); const nested = depth < 3 && SHELLS.has(path.basename(words[0] ?? "")) && at !== -1 && words[at + 1] ? allCommands(parseShell(words[at + 1]), depth + 1) : []; return [cmd, ...nested]; }); } // why: a sub-agent's code the guard cannot read before it runs: `eval` or a file the same call // wrote and then sources, in a call that also writes with `gh` (helpers keep a test command in a // variable, or source an env file they wrote); a function named `gh`, in any call. function evasionRules(raw, commands, writes) { const written = new Set(); for (const cmd of commands) { const { words } = commandWords(cmd); if (writes) evasionStep(path.basename(words[0] ?? ""), words, written); noteWrites(cmd, words, written); } if (definesGh(raw)) { refuse( "Refused: this defines a function named `gh`, which would run in place of `.agents/shims/gh`, " + "the `gh` that checks a body and a sub-agent's labels (delivery rules 12 and 17).", ); } } // why: the files a command writes: its `>` and `>>` targets, and `tee`'s. function noteWrites(cmd, words, written) { for (const r of cmd.redirects) if (r.op === ">" || r.op === ">>") written.add(r.target); if (path.basename(words[0] ?? "") !== "tee") return; for (const w of words.slice(1)) if (!w.startsWith("-")) written.add(w); } function evasionStep(name, words, written) { if ((name === "source" || name === ".") && written.has(words[1])) { refuse( `Refused: this call writes \`${words[1]}\` and then sources it, so the guard cannot read ` + "what runs. Run the commands themselves.", ); } if (name === "eval") { refuse( "Refused: `eval` runs text the guard cannot read before it runs. Run the command itself.", ); } } // why: a definition starts a command (the call's start, after `;`, `&`, `|`, `(`, `{` or a line) // and names `gh` in any quoting, which zsh accepts (`"gh"() {`, `function 'gh' {`, `g\h ()`). // Strings and heredoc bodies are masked first, so a `function gh` grep looks for is data. function definesGh(raw) { const masked = blanked(raw); const re = /(?:^|[;&|({\n])\s*(?:function\s+([^\s;&|(){}]+)|([^\s;&|(){}=$]+)\s*\(\s*\))/g; for (const m of masked.matchAll(re)) { const name = m[1] ?? m[2]; const start = m.index + m[0].lastIndexOf(name); if (unquotedWord(raw.slice(start, start + name.length)) === "gh") return true; } return false; } function unquotedWord(word) { return word.replace(/\\(.)/g, "$1").replace(/["']/g, ""); } function shimRules(raw, commands) { const every = allCommands(commands); const writes = every.some(writesWithGh); if (subAgent) evasionRules(raw, every, writes); if (!writes) return; const found = every.map(bypassIn).find(Boolean) ?? (definesGh(raw) ? "defines a function named `gh`" : undefined); if (found === undefined) return; refuse( `Refused: this call ${found} and writes with \`gh\`, so the \`gh\` that runs may not be ` + "`.agents/shims/gh`, which checks a body and a sub-agent's labels (delivery rules 12 and " + "17). Run `gh` by its name, with the session's PATH, in a call that changes none of this.", ); } const DECLARERS = new Set(["export", "declare", "typeset", "readonly", "local"]); const BYPASSES = [ [(c) => c.lead.some((w) => /^PATH\+?=/.test(w)), "sets PATH"], [ (c) => DECLARERS.has(c.name) && c.words.slice(1).some((w) => /^PATH(?:\+?=|$)/.test(w)), "sets PATH", ], [ (c) => c.name === "alias" && c.words.slice(1).some((w) => w.startsWith("gh=")), "defines an alias named `gh`", ], [(c) => c.name === "hash" && /^-\w*p/.test(c.words[1] ?? ""), "runs `hash -p`"], [(c) => c.name === "eval", "runs `eval`"], [(c) => after(c.all, "command").some((w) => /^-\w*p/.test(w)), "runs `command -p`"], [ (c) => after(c.all, "env").some((w) => /^(?:-\w*[iu]|--ignore-environment|--unset)/.test(w)), "clears the environment with `env`", ], ]; // why: what a command changes about which `gh` runs; a pure assignment counts as a lead word. function bypassIn(cmd) { const { words } = commandWords(cmd); const lead = words.length === 0 ? cmd.words : cmd.words.slice(0, cmd.words.length - words.length); const c = { all: cmd.words, lead, words, name: path.basename(words[0] ?? "") }; return BYPASSES.find(([when]) => when(c))?.[1]; } // why: the flags right after a wrapper (`command`, `env`), up to the program it starts. function after(all, wrapper) { const at = all.findIndex((w) => path.basename(w) === wrapper); if (at === -1) return []; const end = all.findIndex((w, i) => i > at && !w.startsWith("-") && !/^\w+=/.test(w)); return all.slice(at + 1, end === -1 ? undefined : end); } // why: the `gh` of a command after any wrappers, flags and assignments, when it makes a call the // shim checks: a post or edit of an issue or PR (a body, a label flag), a `gh label` write, or an // api write that carries a body, labels, a GraphQL query or a payload. Cancelling a run is none. const GH_READS = new Set(["view", "list", "status", "diff", "checks", "checkout"]); function writesWithGh(cmd) { const at = cmd.words.findIndex((w) => path.basename(w) === "gh"); if (at === -1) return false; const gh = ghArgs(cmd.words.slice(at + 1)); if (gh.group === "issue" || gh.group === "pr" || gh.group === "label") return !GH_READS.has(gh.verb); return gh.group === "api" && apiSends(gh); } // why: with no method gh sends GET, or POST when the call has fields or a payload. function apiSends(gh) { const input = ghFlagValues(gh, "--input").length > 0; const fields = ghFlagValues(gh, "--field", "--raw-field"); const method = ghFlagValues(gh, "--method").at(-1) ?? (input || fields.length > 0 ? "POST" : "GET"); if (method.toUpperCase() === "GET" && !input) return false; return ( input || fields.some((f) => /^(?:body|labels(?:\[\])?|query)=/i.test(f)) || /(?:^|\/)(?:labels|graphql)(?:\/|$|\?)/i.test(gh.positionals[0] ?? "") ); } function changesDirectory(state, words, dynamic) { if (path.basename(words[0]) !== "cd" || words[1] === undefined || dynamic[1]) return false; state.dir = path.resolve(state.dir, words[1].replace(/^~(?=\/|$)/, os.homedir())); return true; } function commandStep(state, words, dynamic) { const name = path.basename(words[0]); if (name === "git") gitRules(words, dynamic, state.dir); if (name === "gh") refuseFirst(GH_RULES, { words, ...state, group: words[1], verb: words[2] }); slowLaneRules(words); if (FAST_TRACK_AUTHORS.has(input.agent_type ?? "") && runsScript(words, "fast-track.mjs")) { refuse( "Refused: the fast track checks your report or your fix, so you never run it yourself " + "(delivery rule 17). The orchestrator runs `fast-track.mjs`; leave the label as it is.", ); } } // why: the script as the program, or as node's script; `git add` or `cat` on the file is no run. function runsScript(words, script) { const at = words.findIndex((w) => path.basename(w) === script); if (at === -1) return false; const before = words.slice(0, at).filter((w) => !WRAPPERS.has(path.basename(w))); return before.every((w, i) => (i === 0 && path.basename(w) === "node") || w.startsWith("-")); } const STASH_READS = new Set(["list", "show"]); const GIT_RULES = [ { when: (g) => g.sub === "push" && landsOnMain(g), reason: "Refused: this push lands on `main`. Nothing is pushed to `main`: a pull request lands " + "there. Push the branch under its own name, `git push -u origin :` " + "(the `:` matters while the branch tracks `origin/main`), and open a PR.", }, { when: (g) => subAgent && g.sub === "stash" && !STASH_READS.has(g.rest.find((w) => !w.startsWith("-"))), reason: "Refused: never `git stash` in a delivery stage: every worktree shares one stash list, so " + "a pop can take another agent's changes. Commit the work instead. `git stash list` and " + "`git stash show` only read, and pass.", }, { when: (g) => subAgent && (g.sub === "rebase" || (g.sub === "pull" && g.rest.some((w) => /^(?:-r|--rebase(?!=false))/.test(w)))), reason: "Refused: never rebase in a delivery stage: a stack moves by merging forward " + "(`.agents/scripts/stack-sync.sh`), and a rebased branch needs a force push nobody may " + "make (delivery rule 15). Merge the base branch instead: `git merge origin/`.", }, { when: (g) => subAgent && g.sub === "push" && g.rest.some(rewritesRemote), reason: "Refused: this push rewrites or deletes a remote branch (`+`, `:`, `--force` or " + "`--delete`). Push fast-forwards only; when the push is rejected, merge the remote " + "branch in and push again.", }, ]; function gitRules(words, dynamic, dir) { let at = 1; let inDir = dir; while (at < words.length && words[at].startsWith("-")) { if (words[at] === "-C" && words[at + 1] !== undefined) inDir = path.resolve(inDir, words[at + 1]); at += GIT_VALUE_FLAGS.has(words[at]) ? 2 : 1; } refuseFirst(GIT_RULES, { sub: words[at], rest: words.slice(at + 1), dynamic: dynamic.slice(at + 1), dir: inDir, }); } function landsOnMain(g) { const [remote, ...refspecs] = pushOperands(g); if (remote !== undefined && !remote.dynamic && remote.text !== "origin") return false; if (g.rest.some((w) => /^--(?:all|branches|mirror)$/.test(w))) return true; const current = currentBranch(g.dir); if (refspecs.length === 0) return plainPushToMain(g, current); return refspecs.some((spec) => pushTarget(spec, current, g.dir) === "main"); } function pushOperands(g) { const operands = []; for (let i = 0; i < g.rest.length; i++) { if (PUSH_VALUE_FLAGS.has(g.rest[i])) i++; else if (!g.rest[i].startsWith("-")) operands.push({ text: g.rest[i].replace(/^\+/, ""), dynamic: g.dynamic[i] }); } return operands; } // why: `--tags` with no refspec pushes tags only; a plain push goes to the branch's own remote. function plainPushToMain(g, current) { if (g.rest.includes("--tags")) return false; if (current === "main") return true; return gitConfig(g.dir, `branch.${current}.remote`) === "origin" && tracksMain(g.dir, current); } // why: git sends a refspec with no `:` to the branch of the same name, but to the branch's // upstream when the source is a branch name and `push.default` is `upstream`; `HEAD` is never // mapped. A source the guard cannot read (`$b`) is taken for the current branch. function pushTarget(spec, current, dir) { const colon = spec.text.indexOf(":"); if (colon !== -1) return spec.text.slice(colon + 1).replace(/^refs\/heads\//, ""); if (spec.text === "HEAD" || spec.text === "@") return current; const branch = spec.dynamic ? current : spec.text.replace(/^refs\/heads\//, ""); return tracksMain(dir, branch) ? "main" : branch; } function tracksMain(dir, branch) { return ( branch !== "" && gitConfig(dir, "push.default") === "upstream" && gitConfig(dir, `branch.${branch}.merge`) === "refs/heads/main" ); } function gitConfig(dir, key) { return gitOutput(dir, ["config", "--get", key]); } function rewritesRemote(word) { return ( word.startsWith("+") || /^:./.test(word) || /^--(?:force|delete|mirror)/.test(word) || /^-[a-zA-Z]*[fd]/.test(word) ); } const GH_RULES = [ { when: (c) => c.words[0] !== "gh", reason: (c) => `Refused: run \`gh\` by its name, not as \`${c.words[0]}\`: the \`gh\` first on PATH checks ` + "a body before it is posted (delivery rule 12).", }, { when: (c) => c.group === "issue" && c.verb === "edit" && flagValues(c.words, ["--add-assignee"]).length > 0, reason: "Refused: claim an issue with `node .agents/scripts/claim.mjs ` (`--triage` for a " + "`bug:new` triage), not by hand. It assigns you only when the issue is open, unassigned " + "and labelled as work an agent may take (delivery rules 1 and 2).", }, { when: (c) => subAgent && workLabel(c) !== undefined, reason: (c) => `Refused: agents never label their way into work (delivery rule 1): \`${workLabel(c)}\` is the ` + "maintainer's or the spec session's to set. Leave the label as it is and say in your " + "report what should change.", }, { when: (c) => subAgent && c.group === "pr" && c.verb === "ready", reason: "Refused: only the orchestrator marks a PR ready, after its review (delivery rule 14). " + "Leave it in draft and report.", }, { when: (c) => subAgent && prCreate(c) && !c.words.includes("--draft") && !c.words.includes("-d"), reason: "Refused: every PR starts in draft (delivery rule 14). Run `gh pr create` again with " + "`--draft`; the orchestrator marks it ready after review.", }, { when: (c) => subAgent && prCreate(c) && prHead(c).endsWith("-repro"), reason: "Refused: a `bug/-repro` branch opens no pull request (delivery rule 8). Push the " + "test to the branch and name it in the triage report.", }, { when: (c) => subAgent && restCreatesReadyPr(c.words), reason: "Refused: every PR starts in draft (delivery rule 14). Create it again with " + "`-F draft=true`; the orchestrator marks it ready after review.", }, ]; function workLabel(c) { return addedLabels(c.words, c.group, c.verb).find((l) => WORK_LABELS.has(l)); } function prCreate(c) { return c.group === "pr" && c.verb === "create"; } function prHead(c) { return flagValues(c.words, ["--head", "-H"]).at(-1) ?? currentBranch(c.dir); } function restCreatesReadyPr(words) { if (words[1] !== "api" || !/(?:^|\/)repos\/[^/]+\/[^/]+\/pulls$/.test(apiPath(words))) return false; const fields = apiFields(words); const method = flagValues(words, ["-X", "--method"]).at(-1)?.toUpperCase(); const post = (method ?? (fields.length > 0 ? "POST" : "GET")) === "POST"; return post && !fields.some((f) => f.key === "draft" && f.value === "true"); } const SLOW_LANE_RULES = [ { when: (words) => vitestRunsSlowLane(words), reason: "Refused: the slow lane runs only through `scripts/slow-e2e.sh `, which holds " + "the machine-wide lock (delivery rule 16). Run the fast e2e lane with `pnpm test:e2e " + "`, and leave the slow lane to the hardware verifier.", }, { when: (words) => subAgent && path.basename(words[0]) === "pnpm" && SLOW_LANE_SCRIPTS.has(pnpmOperands(words.slice(1)).find((w) => w !== "run")), reason: "Refused: the slow lane runs only through `scripts/slow-e2e.sh `, which holds " + "the machine-wide lock (delivery rule 16). Run it through the script, or report the " + "lines that need it under `hardware`.", }, { when: (words) => startsSlowLane(words) && !SLOW_LANE_AGENTS.has(input.agent_type ?? ""), reason: "Refused: only the hardware verifier and the implementer run the slow lane (delivery rule " + "16); `scripts/slow-e2e.sh status` is open to every agent. Report what needs the lane " + "instead.", }, ]; function slowLaneRules(words) { refuseFirst(SLOW_LANE_RULES, words); } function vitestRunsSlowLane(words) { const runner = words.findIndex((w) => path.basename(w) === "vitest"); if (runner === -1 || !runsAsCommand(words, runner)) return false; const after = words.slice(runner + 1); const slowFile = after.some((w) => /(?:^|\/)e2e\/slow-[^/]*$/.test(w)); const e2e = after.some( (w, i) => w === "--project=e2e" || (w === "--project" && after[i + 1] === "e2e"), ); const filtered = flagValues(after, ["--tags-filter"], 0).some((v) => v.includes("!slow")); return slowFile || (e2e && !filtered); } // why: `vitest` as the program, or after `pnpm exec`, `npx` and the like; not as an operand. function runsAsCommand(words, runner) { if (runner === 0) return true; const launcher = ["pnpm", "npx", "bunx", "yarn", "npm"].includes(path.basename(words[0])); return ( launcher && words .slice(1, runner) .every((w) => ["exec", "dlx", "x", "run"].includes(w) || w.startsWith("-")) ); } // why: the main session has no `agent_type`, and it may start the lane. function startsSlowLane(words) { const script = words.findIndex((w) => path.basename(w) === "slow-e2e.sh"); if (script === -1 || typeof input.agent_type !== "string") return false; const shell = script === 0 || ["sh", "bash", "zsh"].includes(path.basename(words[0])); return shell && words[script + 1] !== "status"; } function addedLabels(words, group, verb) { let values = []; if ((group === "issue" || group === "pr") && verb === "edit") values = flagValues(words, ["--add-label"]); if ((group === "issue" || group === "pr") && verb === "create") values = flagValues(words, ["--label", "-l"]); if (group === "api") { values = apiFields(words) .filter((f) => f.key === "labels" || f.key === "labels[]") .map((f) => f.value); } return values.flatMap((v) => v.split(",")).map((v) => v.trim()); } function apiPath(words) { for (let i = 2; i < words.length; i++) { if (GH_API_VALUE_FLAGS.has(words[i])) i++; else if (!words[i].startsWith("-")) return words[i]; } return ""; } function apiFields(words) { const fields = []; for (let i = 2; i < words.length; i++) { const [flag, value] = splitFlag(words, i); if (["-f", "-F", "--field", "--raw-field"].includes(flag) && value !== undefined) { const eq = value.indexOf("="); if (eq !== -1) fields.push({ key: value.slice(0, eq), value: value.slice(eq + 1) }); } } return fields; } // why: `--flag value` and `--flag=value` are the same flag; returns [flag, value, value index]. function splitFlag(words, i) { const w = words[i]; const eq = w.indexOf("="); if (w.startsWith("--") && eq !== -1) return [w.slice(0, eq), w.slice(eq + 1), i]; return [w, words[i + 1], i + 1]; } function flagValues(words, names, from = 1) { const values = []; for (let i = from; i < words.length; i++) { const [flag, value] = splitFlag(words, i); if (names.includes(flag) && value !== undefined) values.push(value); } return values; } function currentBranch(dir) { return gitOutput(dir, ["branch", "--show-current"]); } function gitOutput(dir, gitArgs) { try { return execFileSync("git", ["-C", dir, ...gitArgs], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], }).trim(); } catch { return ""; } } function squash(text) { return text.replace(/\s+/g, " ").trim(); } function refuse(reason) { process.stderr.write(`${reason}\n`); process.exit(2); } // why: a refusal costs the agent a turn, so a call with one known fix is changed, not refused; // the changed call still meets every rule below it. function stageCall(raw) { if (HOOK_BYPASS.some((re) => re.test(code(raw)))) { refuse( "Refused: this skips the git hooks. They run the checks agents never run by hand. Only the " + "build stage may skip Fallow, on a push before its last cycle: " + "`LEFTHOOK_EXCLUDE=fallow git push ...`.", ); } const fixed = { ...args }; const notes = []; const typecheck = asTypecheck(raw); if (typecheck !== null) { fixed.command = typecheck; notes.push(TYPECHECK_NOTE); } const command = fixed.command ?? ""; const shell = code(command); if (!/slow-e2e\.sh|\.exit\b/.test(command)) { if (TEST_RUNNER.test(shell) && !(Number(args.timeout) >= 300000)) { fixed.timeout = 600000; notes.push(TIMEOUT_NOTE); } waitingRules(command, shell); } const found = forbiddenCheck(shell); if (found !== null) { refuse( `Refused: \`${found}\` is under "Checks agents never run" in toolchain.md. The commit ` + "hook runs lint, the comment lint and typecheck; the push hook runs Fallow and the e2e " + "typecheck; CI runs the rest. Their errors show in the commit or push output. Run only " + 'the commands under "Tests agents run"; for types that is `pnpm typecheck`.', ); } return { input: fixed, notes }; } function waitingRules(raw, shell) { if (args.run_in_background === true || BACKGROUND_JOB.test(shell)) { refuse( "Refused: nothing runs in the background in a delivery stage. A background job holds " + "your report until it ends or hits its 30-minute cap, and polling it costs the turn. " + "Run the command in the foreground with `timeout: 600000` on the Bash call.", ); } if (SLEEP_LOOP.test(shell)) { refuse( "Refused: no loop that sleeps. Nothing you started runs in the background, so there is " + "nothing to wait for: run the command itself in the foreground with `timeout: 600000`.", ); } if (BARE_CAT.test(raw)) { refuse( "Refused: `cat > file` with no input reads stdin until the tool times out. Write the " + "file with the Write tool, or give cat a heredoc (`cat > file <<'EOF'`).", ); } } // why: the parser says which commands are a `tsc --noEmit` that `pnpm typecheck` replaces, in a // directory that has the script; the pattern finds their text. The rewrite stands only when the // rewritten call parses to the same commands with exactly those swapped, so a launcher the // pattern does not know, a string or a comment never yields a changed call. function asTypecheck(raw) { const swaps = typecheckSwaps(parseShell(raw)); const spans = [...blanked(raw).matchAll(TSC_RUN)].filter((m) => isTypecheck(m[0].split(/\s+/))); if (swaps === null || swaps.count === 0 || spans.length !== swaps.count) return null; let out = raw; for (const m of spans.reverse()) out = `${out.slice(0, m.index)}pnpm typecheck${out.slice(m.index + m[0].length)}`; const seen = (commands) => JSON.stringify(commands.map((c) => [c.words, c.redirects, c.stdin])); return seen(parseShell(out)) === seen(swaps.expected) ? out : null; } // why: null once a run to swap sits where no `typecheck` script is. function typecheckSwaps(commands) { const state = { dir: cwd, followed: true }; const expected = []; let count = 0; for (const cmd of commands) { const { words, dynamic } = commandWords(cmd); const swap = swapsHere(state, words, dynamic); if (swap && !hasTypecheck(state.dir)) return null; count += swap ? 1 : 0; const lead = cmd.words.slice(0, cmd.words.length - words.length); expected.push({ ...cmd, words: swap ? [...lead, "pnpm", "typecheck"] : cmd.words }); } return { count, expected }; } // why: after a `cd` the guard cannot follow, the directory of every later run is unknown. function swapsHere(state, words, dynamic) { if (path.basename(words[0] ?? "") === "cd") { state.followed = changesDirectory(state, words, dynamic) && state.followed; return false; } return state.followed && !dynamic.some(Boolean) && isTypecheck(words); } function isTypecheck(words) { const at = words.findIndex((w) => path.basename(w) === "tsc"); if (at === -1 || !TSC_LAUNCHERS.has(words.slice(0, at).join(" "))) return false; // why: a launcher takes the bare name; alone, the program is on PATH or in node_modules. const program = at === 0 ? /^(?:(?:.*\/)?node_modules\/\.bin\/)?tsc$/ : /^tsc$/; return program.test(words[at]) && checksTypes(words.slice(at + 1)); } // why: `--noEmit`, and at most one `-p` with a project `pnpm typecheck` compiles. function checksTypes(rest) { const flag = (w) => w === "-p" || w === "--project"; const known = (w) => TYPECHECK_PROJECTS.has(path.posix.join(w ?? "-", ".")); const project = (w, i) => (flag(w) ? known(rest[i + 1]) : i > 0 && flag(rest[i - 1]) && known(w)); return ( rest.includes("--noEmit") && rest.filter(flag).length <= 1 && rest.every((w, i) => w === "--noEmit" || project(w, i)) ); } function hasTypecheck(dir) { try { const manifest = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")); return typeof manifest.scripts?.typecheck === "string"; } catch { return false; } } // why: `code` without moving anything: a heredoc body and a quoted string keep their length, so // a match's index is its index in the command. function blanked(command) { const fill = (text) => text.replace(/[^\n]/g, "_"); return command .replace( /(<<-?\s*(['"]?)(\w+)\2[^\n]*\n)([\s\S]*?\n\s*\3)(?=\n|$)/g, (_all, head, _quote, _word, body) => head + fill(body), ) .replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, fill); } function code(command) { // why: a heredoc body is data (a script fed to python or cat), not commands the shell runs. // why: so is a quoted string (a commit message, a PR title, a sed script). return command .replace(/<<-?\s*(['"]?)(\w+)\1([^\n]*)\n[\s\S]*?\n\s*\2(?=\n|$)/g, "$3") .replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "''"); } function forbiddenCheck(shell) { for (const segment of shell.split(/\|\||&&|[;|&\n()`]|\$\(/)) { const words = segment.trim().split(/\s+/).filter(Boolean).map(unquote); while (words.length > 0 && (/^\w+=/.test(words[0]) || WRAPPERS.has(words[0]))) words.shift(); if (words[0] === "timeout") words.splice(0, 2); if (words.length > 0 && isForbidden(words)) return segment.trim().replace(/\s*\d?>+$/, ""); } return null; } function isForbidden(words) { const [first, ...rest] = words; const name = path.basename(first); if (TOOLS.has(name) || NODE_SCRIPTS.has(name)) return true; if (name === "node") return rest.some((w) => NODE_SCRIPTS.has(path.basename(w))); if (name === "npx" || name === "bunx") return isTool(firstOperand(rest)); return name === "pnpm" && isForbiddenPnpm(rest); } function isForbiddenPnpm(args) { const operands = pnpmOperands(args); const [sub, ...after] = operands[0] === "run" ? operands.slice(1) : operands; if (sub === "exec" || sub === "dlx") return isTool(after[0]); // why: pnpm runs a binary it does not know as a script, so `pnpm tsc` is `pnpm exec tsc`. if (isTool(sub)) return true; // why: these scripts are allowed only in their narrow forms: named e2e files, Chromium only. if (sub === "test:e2e") return after.length === 0; // why: the whole lane is CI's; a stage runs only the spec files its diff touched. if (sub === "test:console") return !args.includes("--project=chromium") || !after.some((w) => w.endsWith(".spec.ts")); // why: a refactor's implementer mutates the lines its draft touches (delivery rule 18). if (sub === "mutate") return !args.includes("--touched-by"); return SCRIPTS.has(sub); } function pnpmOperands(args) { const operands = []; for (let i = 0; i < args.length; i++) { if (PNPM_VALUE_FLAGS.has(args[i])) i++; else if (!args[i].startsWith("-")) operands.push(args[i]); } return operands; } function isTool(word) { return TOOLS.has(path.basename(word ?? "")); } function firstOperand(words) { return words.find((w) => !w.startsWith("-")); } function unquote(word) { return word.replace(/^['"]|['"]$/g, ""); } // why: the rule tables above are consts, so the hook runs once they all exist. const input = JSON.parse(fs.readFileSync(0, "utf8") || "{}"); const tool = input.tool_name; const args = input.tool_input ?? {}; const subAgent = typeof input.agent_id === "string"; const cwd = typeof input.cwd === "string" ? input.cwd : process.cwd(); if (tool === "Agent" || tool === "Task") agentRules(); if (tool === "Bash") { const mark = subAgent ? agentMark() : null; const call = subAgent ? stageCall(args.command ?? "") : { input: args, notes: [] }; commandRules(call.input.command ?? ""); if (subAgent) { const marked = { ...call.input, command: `${mark}\n${call.input.command ?? ""}` }; answer({ updatedInput: marked, ...(call.notes.length > 0 && { additionalContext: call.notes.join(" ") }), }); } else if (call.notes.length > 0) { answer({ updatedInput: call.input, additionalContext: call.notes.join(" ") }); } } // why: the gh shim cannot tell a sub-agent's shell from the main session's, so each sub-agent // call exports the mark first; a call that names it (to unset or change it) is refused. function agentMark() { if (allCommands(parseShell(args.command ?? "")).some(touchesMark)) { refuse( "Refused: this names `SIMLOCK_GH_AGENT`, which marks a sub-agent's `gh` calls for the label " + "rules (delivery rule 17). The tool guard sets it on every call; leave it alone.", ); } const type = String(input.agent_type ?? "agent").replace(/[^\w.-]/g, "_"); return `export SIMLOCK_GH_AGENT=${type}`; } // why: `env -u SIMLOCK_GH_AGENT`, `-uSIMLOCK_GH_AGENT` or `--unset=SIMLOCK_GH_AGENT`. function envUnsetsMark(all) { const at = all.findIndex((w) => path.basename(w) === "env"); if (at === -1) return false; return all.slice(at + 1).some((w, i, rest) => { if (!w.includes("SIMLOCK_GH_AGENT")) return false; return /^(?:-\w*u|--unset=)/.test(w) || /^(?:-\w*u|--unset)$/.test(rest[i - 1] ?? ""); }); } // why: what can change the mark: an assignment to it, `unset`, a declaration or `env -u` naming // it, or an `unset` the guard cannot read; a grep pattern or a printed string that names it is no // such command. function touchesMark(cmd) { const { words, dynamic } = commandWords(cmd); const mark = (w) => /^SIMLOCK_GH_AGENT(?:\+?=|$)/.test(w); const lead = words.length === 0 ? cmd.words : cmd.words.slice(0, cmd.words.length - words.length); const name = path.basename(words[0] ?? ""); if (lead.some(mark) || envUnsetsMark(cmd.words)) return true; if (name === "unset" && dynamic.some(Boolean)) return true; return (name === "unset" || DECLARERS.has(name)) && words.slice(1).some(mark); } process.exit(0);