From fe68895c4a57e5e7cc9305a79cb1768c9f474eb4 Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 12:51:39 +0000 Subject: [PATCH 1/3] chore(agents): run the push check in Pi Runs the push check in Pi as well, ported from todoist/todoist-cli#673. Pi has no hook files, so .pi/extensions/agent-guard.ts listens to Pi's tool_call event: before a bash call that could push, it runs the same .agents/scripts/guard.ts the Claude Code and Codex hooks call, with the same JSON, and blocks the call with the guard's reason when it says no. It behaves like the other agents' hooks: DISABLE_AGENT_GUARD=1 turns it off, a checkout without the guard is skipped without starting anything, and a guard that fails, times out or prints something odd allows the call with a note. Pi blocks a tool call whose handler throws, so the handler catches its own errors and allows the call too. The extension is type-checked with the rest of the agent tooling (the tooling tsconfig now includes .pi), and oxlint and oxfmt already cover .pi, since both run over the whole repository. Its tests are in .agents/scripts/pi-extension.test.ts, since Pi would load a test file in .pi/extensions/ as another extension. --- .agents/scripts/instructions.test.ts | 2 +- .agents/scripts/package-contents.test.ts | 2 +- .agents/scripts/pi-extension.test.ts | 166 +++++++++++++++++++++++ .agents/scripts/tsconfig.json | 5 +- .pi/extensions/agent-guard.ts | 133 ++++++++++++++++++ AGENTS.md | 2 +- CODEBASE.md | 1 + docs/agents.md | 15 +- 8 files changed, 314 insertions(+), 12 deletions(-) create mode 100644 .agents/scripts/pi-extension.test.ts create mode 100644 .pi/extensions/agent-guard.ts diff --git a/.agents/scripts/instructions.test.ts b/.agents/scripts/instructions.test.ts index 557458d..c6dca21 100644 --- a/.agents/scripts/instructions.test.ts +++ b/.agents/scripts/instructions.test.ts @@ -37,7 +37,7 @@ const scripts = Object.keys( ).scripts, ) -const ROOTED = /^(src|scripts|docs|\.agents|\.github|\.claude|\.codex|\.cursor)\// +const ROOTED = /^(src|scripts|docs|\.agents|\.github|\.claude|\.codex|\.cursor|\.pi)\// const FILE_NAME = /^[\w.-]+\.(md|json|ts|tsx|js|cjs|mjs|sh|yml|yaml)$/ // A path relative to the document, like `references/test-rules.md` in a skill. const RELATIVE_FILE = /^[\w.-]+(\/[\w.-]+)+\.(md|json|ts|sh)$/ diff --git a/.agents/scripts/package-contents.test.ts b/.agents/scripts/package-contents.test.ts index 4bd71b4..43809f7 100644 --- a/.agents/scripts/package-contents.test.ts +++ b/.agents/scripts/package-contents.test.ts @@ -6,7 +6,7 @@ import { isolatedEnv, REPO_ROOT } from './lib/test-repo.ts' // Agent tooling is development-only. `scripts/` ships in the npm package, so the tooling // lives in `.agents/`, and must never be published. -const DEV_ONLY = ['.agents/', '.claude/', '.codex/', '.cursor/', '.tmp/'] +const DEV_ONLY = ['.agents/', '.claude/', '.codex/', '.cursor/', '.pi/', '.tmp/'] // npm pack takes several seconds, more when `npm run verify` runs other checks alongside. it('keeps agent tooling out of the published package', { timeout: 30_000 }, () => { diff --git a/.agents/scripts/pi-extension.test.ts b/.agents/scripts/pi-extension.test.ts new file mode 100644 index 0000000..0f1b55f --- /dev/null +++ b/.agents/scripts/pi-extension.test.ts @@ -0,0 +1,166 @@ +import { mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { createTempRepo, markVerified, type TempRepo } from './lib/test-repo.ts' + +// Drives a copy of .pi/extensions/agent-guard.ts the way Pi does, in its own node process: +// register the handlers, then call `tool_call` with one event, and print what the handler +// returned and the notes it showed. The extension guards the checkout it lives in, so it runs from +// a throwaway repo holding a copy of it and of .agents/scripts. Node loads it with type stripping, +// which also holds it to the erasable syntax the rest of the tooling uses. +const DRIVER = ` + const { readFileSync } = await import('node:fs') + const [extension, cwd, eventFile] = process.argv.slice(1) + const event = JSON.parse(readFileSync(eventFile, 'utf8')) + const { default: agentGuard } = await import(extension) + const handlers = {} + const notes = [] + agentGuard({ on: (name, handler) => (handlers[name] = handler) }) + const hasUI = !process.env.HEADLESS + function notify(message) { + if (process.env.BROKEN_UI) throw new Error('the UI is gone') + notes.push(message) + } + const ctx = { cwd, hasUI, ui: { notify } } + const result = await handlers.tool_call(event, ctx) + console.log(JSON.stringify({ result: result ?? null, notes })) +` + +type Driven = { + result: { block: true; reason?: string } | null + notes: string[] + stderr: string +} + +let repo: TempRepo + +function setUp(target: TempRepo, { withGuard = true } = {}): void { + const paths = ['.pi/extensions/agent-guard.ts'] + if (withGuard) paths.push('.agents/scripts/guard.ts', '.agents/scripts/lib') + target.copyFromCheckout(...paths) + target.write('.gitignore', '.tmp/\n') + target.write('src/a.ts', 'export const a = 1\n') + target.git(['add', '.']) + target.git(['commit', '--quiet', '-m', 'initial']) +} + +function drive( + event: { toolName: string; input: unknown }, + options: { root?: string; cwd?: string; env?: Record } = {}, +): Driven { + const root = options.root ?? repo.dir + const cwd = options.cwd ?? root + const eventFile = join(root, '.tmp/event.json') + mkdirSync(join(root, '.tmp'), { recursive: true }) + writeFileSync(eventFile, JSON.stringify(event)) + const extension = join(root, '.pi/extensions/agent-guard.ts') + const result = repo.run( + process.execPath, + ['--no-warnings', '--input-type=module', '-e', DRIVER, extension, cwd, eventFile], + { cwd, env: options.env }, + ) + expect(result.status, result.stderr).toBe(0) + return { ...(JSON.parse(result.stdout) as Omit), stderr: result.stderr } +} + +const bash = (command: string) => ({ toolName: 'bash', input: { command } }) + +const commitOnBranch = (branch: string, path: string) => repo.commitOnBranch(branch, path) + +beforeEach(() => { + repo = createTempRepo() + setUp(repo) + repo.addOrigin() +}) + +afterEach(() => repo.cleanup()) + +it("blocks an unverified push through tool_call with the guard's reason", () => { + commitOnBranch('feature', 'src/b.ts') + const { result, notes } = drive(bash('git push -u origin HEAD')) + expect(result).toEqual({ block: true, reason: expect.stringContaining('npm run verify') }) + expect(notes).toEqual([]) + + // From a subfolder, with a pull request split across lines + const opened = drive(bash('gh pr \\\n create --fill'), { cwd: join(repo.dir, 'src') }) + expect(opened.result?.reason).toContain('opens a pull request') +}) + +it('lets the push run once verify has passed on it', () => { + commitOnBranch('feature', 'src/b.ts') + markVerified(repo.dir) + expect(drive(bash('git push -u origin HEAD'))).toEqual({ result: null, notes: [], stderr: '' }) +}) + +it('leaves every other tool call alone', () => { + commitOnBranch('feature', 'src/b.ts') + for (const event of [ + bash('ls'), + bash('git status && npm test'), + { toolName: 'read', input: { path: 'push.md' } }, + { toolName: 'bash', input: null }, + ]) { + expect(drive(event), JSON.stringify(event)).toEqual({ result: null, notes: [], stderr: '' }) + } +}) + +it('does nothing with DISABLE_AGENT_GUARD=1', () => { + commitOnBranch('feature', 'src/b.ts') + const off = drive(bash('git push'), { env: { DISABLE_AGENT_GUARD: '1' } }) + expect(off).toEqual({ result: null, notes: [], stderr: '' }) +}) + +it('skips a checkout without the guard, such as an older branch, without a word', () => { + const older = createTempRepo() + try { + setUp(older, { withGuard: false }) + older.write('src/b.ts', 'export const b = 1\n') + older.git(['add', '.']) + older.git(['commit', '--quiet', '-m', 'b']) + expect(drive(bash('git push'), { root: older.dir })).toEqual({ + result: null, + notes: [], + stderr: '', + }) + } finally { + older.cleanup() + } +}) + +it("shows the guard's notes: a push it can't check, or a broken guard", () => { + commitOnBranch('feature', 'src/b.ts') + const unknown = drive(bash('cd "$REPO" && git push')) + expect(unknown.result).toBeNull() + expect(unknown.notes.join('\n')).toContain("can't tell which folder a push runs in") + + repo.write('.agents/scripts/lib/push-check.ts', 'this is not valid typescript (\n') + const broken = drive(bash('git push')) + expect(broken.result).toBeNull() + expect(broken.notes.join('\n')).toContain('hook failed, so it allowed the action') +}) + +it('prints the notes on stderr when Pi has no UI', () => { + commitOnBranch('feature', 'src/b.ts') + const headless = drive(bash('cd "$REPO" && git push'), { env: { HEADLESS: '1' } }) + expect(headless.notes).toEqual([]) + expect(headless.stderr).toContain("can't tell which folder a push runs in") +}) + +it('allows the call when the extension itself fails, which Pi would treat as a block', () => { + commitOnBranch('feature', 'src/b.ts') + const failed = drive(bash('cd "$REPO" && git push'), { env: { BROKEN_UI: '1' } }) + expect(failed.result).toBeNull() + expect(failed.stderr).toContain('the Pi extension failed, so it allowed the action') +}) + +it('allows the call when the guard exits without reading its input or printing JSON', () => { + commitOnBranch('feature', 'src/b.ts') + // A command long enough that the write is still going when the guard closes the pipe + repo.write('.agents/scripts/guard.ts', 'process.exit(0)\n') + expect(drive(bash(`git push # ${'x'.repeat(512 * 1024)}`)).result).toBeNull() + + repo.write('.agents/scripts/guard.ts', 'console.log("not json")\n') + const garbled = drive(bash('git push')) + expect(garbled.result).toBeNull() + expect(garbled.notes.join('\n')).toContain('printed no JSON, so it allowed the action') +}) diff --git a/.agents/scripts/tsconfig.json b/.agents/scripts/tsconfig.json index 4289e5a..492e870 100644 --- a/.agents/scripts/tsconfig.json +++ b/.agents/scripts/tsconfig.json @@ -1,6 +1,7 @@ { // Agent tooling runs straight from source with Node's type stripping, so it may only use - // erasable TypeScript syntax and must import files with their .ts extension. + // erasable TypeScript syntax and must import files with their .ts extension. The Pi extension + // in .pi/ is agent tooling too, and its test loads it the same way. "extends": "../../tsconfig.json", "compilerOptions": { "rootDir": "../..", @@ -12,5 +13,5 @@ "lib": ["es2023"], "types": ["node", "vitest/globals"] }, - "include": ["."] + "include": [".", "../../.pi/**/*"] } diff --git a/.pi/extensions/agent-guard.ts b/.pi/extensions/agent-guard.ts new file mode 100644 index 0000000..a864105 --- /dev/null +++ b/.pi/extensions/agent-guard.ts @@ -0,0 +1,133 @@ +// Pi's wiring for the push check: the same `.agents/scripts/guard.ts` the Claude Code and Codex +// hooks call, so the rules can't drift apart per agent. Pi has no hook files; it has extension +// events, and `tool_call` fires before each tool runs and can block it. Before a `bash` call that +// could push, this asks the guard, and blocks the call with the guard's reason when it says no. +// +// Pi loads project extensions only once you trust the project, and only from the folder it starts +// in. The rest works as it does for the other agents: DISABLE_AGENT_GUARD=1 turns it off, a +// checkout without the guard (an older branch) is skipped without a word, and a guard that fails +// to run allows the call. See docs/agents.md. +// +// Its tests are in .agents/scripts/pi-extension.test.ts: Pi would load a test file in this folder +// as another extension. + +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** What the guard prints: the same JSON the Claude Code and Codex hooks read. */ +type GuardOutput = { + hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string } + systemMessage?: string +} + +/** What the handler reads of Pi's `tool_call` context. */ +type ToolContext = { + cwd: string + hasUI: boolean + ui: { notify(message: string, type?: 'info' | 'warning' | 'error'): void } +} + +type ToolCallResult = { block: true; reason?: string } | undefined + +type ToolCallHandler = ( + event: { toolName: string; input: unknown }, + ctx: ToolContext, +) => Promise + +/** What this uses of Pi's extension API, declared here since Pi isn't a dependency. */ +type ExtensionAPI = { on(event: 'tool_call', handler: ToolCallHandler): void } + +/** The same quick test as the hook commands: a command without these words can't push. */ +const MIGHT_PUSH = /push|pr\s.*(create|new)/s + +/** The checkout this file lives in, two folders up, whichever folder Pi runs in. */ +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..') + +const GUARD = join(ROOT, '.agents/scripts/guard.ts') + +/** As long as the Claude Code and Codex hooks wait for the guard. */ +const TIMEOUT_MS = 30_000 + +/** + * Runs the guard the way the other agents' hooks do: a separate process with JSON on stdin that + * prints JSON on stdout. Any failure resolves to a note rather than a decision, so the call runs. + */ +function runGuard(payload: Record): Promise { + return new Promise((done) => { + const child = spawn('node', [GUARD, 'tool-start'], { cwd: ROOT, env: process.env }) + let stdout = '' + let stderr = '' + let finished = false + function finish(output: GuardOutput): void { + if (finished) return + finished = true + clearTimeout(timer) + done(output) + } + const timer = setTimeout(() => { + child.kill() + finish({ systemMessage: 'agent-guard: tool-start timed out, so it allowed the action' }) + }, TIMEOUT_MS) + child.stdout.on('data', (chunk: Buffer) => (stdout += chunk.toString())) + child.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString())) + child.on('error', (error) => { + finish({ systemMessage: `agent-guard: tool-start failed to run: ${error.message}` }) + }) + child.on('close', () => { + try { + finish(stdout.trim() ? (JSON.parse(stdout) as GuardOutput) : {}) + } catch { + finish({ + systemMessage: `agent-guard: tool-start printed no JSON, so it allowed the action. ${stderr.trim()}`, + }) + } + }) + // A guard that exits before reading its input closes the pipe; `close` still reports how + // it ended, so a write error must not crash Pi. + child.stdin.on('error', () => {}) + child.stdin.end(JSON.stringify(payload)) + }) +} + +/** Shows a note in Pi's UI, or on stderr in print and JSON modes, which have none. */ +function tell(ctx: ToolContext, message: string): void { + if (ctx.hasUI) ctx.ui.notify(message, 'warning') + else process.stderr.write(`${message}\n`) +} + +async function checkToolCall( + event: { toolName: string; input: unknown }, + ctx: ToolContext, +): Promise { + if (event.toolName !== 'bash') return undefined + const command = (event.input as { command?: unknown } | null | undefined)?.command + if (typeof command !== 'string' || !MIGHT_PUSH.test(command)) return undefined + // Not started at all when turned off, or on an older branch without the guard. + if (process.env.DISABLE_AGENT_GUARD === '1' || !existsSync(GUARD)) return undefined + + const output = await runGuard({ tool_name: 'Bash', tool_input: { command }, cwd: ctx.cwd }) + if (output.systemMessage) tell(ctx, output.systemMessage) + const decision = output.hookSpecificOutput + if (decision?.permissionDecision !== 'deny') return undefined + return { block: true, reason: decision.permissionDecisionReason } +} + +// Pi loads an extension through its default export. +export default function agentGuard(pi: ExtensionAPI): void { + pi.on('tool_call', async (event, ctx) => { + // Pi blocks the tool call when a handler throws; a broken extension must allow it instead. + try { + return await checkToolCall(event, ctx) + } catch (error) { + const message = `agent-guard: the Pi extension failed, so it allowed the action. ${(error as Error)?.message ?? error}` + try { + tell(ctx, message) + } catch { + process.stderr.write(`${message}\n`) + } + return undefined + } + }) +} diff --git a/AGENTS.md b/AGENTS.md index 8062a54..ba4dc3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -109,7 +109,7 @@ throw new CliError('ERROR_CODE', 'User-facing message', ['Optional hint']) ## Git hooks and agent tooling - Lefthook refuses commits and pushes to `main`, runs oxlint, oxfmt and the type check on pre-commit, and the tests on pre-push. Work on a branch. -- Your `git push` and `gh pr create` are stopped until `npm run verify` has passed on exactly the commit being pushed (Claude Code, Codex and Cursor hooks). Verify, then commit exactly what it saw, or commit first and verify the clean tree. If something must be pushed unverified, ask the person you're working with to push it. +- Your `git push` and `gh pr create` are stopped until `npm run verify` has passed on exactly the commit being pushed (Claude Code, Codex and Cursor hooks, and a Pi extension). Verify, then commit exactly what it saw, or commit first and verify the clean tree. If something must be pushed unverified, ask the person you're working with to push it. - Agent tooling lives in `.agents/scripts/`, never in `scripts/` (which ships in the npm package). - How it all fits together: [`docs/agents.md`](docs/agents.md). diff --git a/CODEBASE.md b/CODEBASE.md index 36129a5..5d9a0bb 100644 --- a/CODEBASE.md +++ b/CODEBASE.md @@ -38,6 +38,7 @@ come from `@todoist/cli-core`. │ # published, unlike scripts/ ├─ .claude/skills/ # Links to .agents/skills/, where Claude Code finds them ├─ .claude/settings.json # Push check hook (.codex/hooks.json for Codex) +├─ .pi/extensions/ # Push check for Pi (agent-guard.ts), tested from .agents/scripts/ ├─ docs/agents.md # How the agent tooling fits together ├─ AGENTS.md # Prescriptive rules (definition of done, build cmds, JSON flag, │ # skill-sync, errors) diff --git a/docs/agents.md b/docs/agents.md index 6b3a1c7..928247a 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -65,7 +65,7 @@ If a pull-request workflow gains a step, `.agents/scripts/lib/steps.test.ts` fai ## The push check -Every agent's hooks call one script, `.agents/scripts/guard.ts`, so the agents can't drift apart. Before each shell command an agent runs, it stops one that pushes code `npm run verify` hasn't passed, or opens a pull request for it. That's where a person starts reviewing, so that's where the proof has to exist. It costs nothing until a command pushes: the hook command only starts Node when the shell command itself mentions a push or a new pull request, and the guard only runs git when it reads one. +Every agent calls one script, `.agents/scripts/guard.ts`, so the agents can't drift apart: Claude Code and Codex from their hook configs, Pi from a small extension. Before each shell command an agent runs, it stops one that pushes code `npm run verify` hasn't passed, or opens a pull request for it. That's where a person starts reviewing, so that's where the proof has to exist. It costs nothing until a command pushes: the hook command only starts Node when the shell command itself mentions a push or a new pull request, and the guard only runs git when it reads one. - **What it checks:** what's pushed has to be exactly a tree verify passed, docs aside. A push sends commits, not the working tree, so verifying with uncommitted changes and then pushing only some of them doesn't get through. When the working tree holds more than the last commit, it says to commit or stash the rest before verifying. - **A commit and a push in one command:** for `git add -A && git commit -m "…" && git push`, it checks the working tree that's about to be committed. That holds only when the commit takes all of it: everything staged first in the same command (`git add -A`, or `git add .` from the top folder), `git commit -a` with no untracked files, or a plain commit with nothing unstaged either. A commit that can leave part of the tree out, by naming paths, `--patch` or what it doesn't stage, is stopped: commit first, then push. @@ -75,11 +75,12 @@ Every agent's hooks call one script, `.agents/scripts/guard.ts`, so the agents c When it stops a command, the reason tells the agent to run verify and try again. When you want something pushed that can't pass yet, push it yourself. -| Agent | Wiring | Known limits | -| ----------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Claude Code | `.claude/settings.json`: `PreToolUse` on `Bash` | `hook-wiring.test.ts` runs the exact command. Accept the workspace trust prompt. | -| Codex | `.codex/hooks.json`: `PreToolUse` on `Bash` | Runs only in a trusted project (`codex --trust`), after each person reviews the hook in `/hooks`; a change to `hooks.json` needs a new review. In a linked worktree, Codex (0.171) trusts and runs the hooks of the main checkout, not the worktree's. The hook command finds the worktree from its folder, so a worktree is guarded once the main checkout has this hook. | -| Cursor | Runs the Claude Code hooks itself; the command falls back to the git root if Cursor does not set `CLAUDE_PROJECT_DIR` | No Cursor hooks file: a second one would run every hook twice. A test keeps it out. Not yet tried here. | +| Agent | Wiring | Known limits | +| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Claude Code | `.claude/settings.json`: `PreToolUse` on `Bash` | `hook-wiring.test.ts` runs the exact command. Accept the workspace trust prompt. | +| Codex | `.codex/hooks.json`: `PreToolUse` on `Bash` | Runs only in a trusted project (`codex --trust`), after each person reviews the hook in `/hooks`; a change to `hooks.json` needs a new review. In a linked worktree, Codex (0.171) trusts and runs the hooks of the main checkout, not the worktree's. The hook command finds the worktree from its folder, so a worktree is guarded once the main checkout has this hook. | +| Cursor | Runs the Claude Code hooks itself; the command falls back to the git root if Cursor does not set `CLAUDE_PROJECT_DIR` | No Cursor hooks file: a second one would run every hook twice. A test keeps it out. Not yet tried here. | +| Pi | `.pi/extensions/agent-guard.ts` runs the guard from Pi's `tool_call` event, before each `bash` call that could push, and blocks the call with its reason | Pi loads project extensions only after you trust the project (`pi --approve`, or the prompt on first run), and only from the folder it starts in, so start Pi at the repository root. `pi-extension.test.ts` drives the extension; it can't sit next to it, since Pi would load a test there as another extension. In print and JSON modes, which have no UI, its notes go to stderr. | **Limits.** The push check catches an agent's honest mistakes. It isn't a security boundary, and CI is still what gates a merge. @@ -88,7 +89,7 @@ When it stops a command, the reason tells the agent to run verify and try again. - **A commit and a push in one command:** the check sees the working tree as it is before the command runs. A step before the commit that changes the tree or what's staged, such as `git stash pop` or `git restore --staged`, can let code through that verify didn't see. - **Two sessions in one checkout** share its record. Use a worktree per session. -**Fails open, visibly:** a broken guard, bad input, or a push from a folder it can't name lets the command run and says why in a message. A checkout without the script, such as an older branch, is skipped without a word, since the hook runs before every shell command. If node isn't on `PATH`, the hook command fails and the agent carries on. `DISABLE_AGENT_GUARD=1` in the agent's environment turns the check off; in Claude Code, a gitignored settings.local.json in `.claude/` can set it for one checkout with `{ "env": { "DISABLE_AGENT_GUARD": "1" } }`. +**Fails open, visibly:** a broken guard, bad input, or a push from a folder it can't name lets the command run and says why in a message. A checkout without the script, such as an older branch, is skipped without a word, since the hook runs before every shell command. In Pi, an error in the extension itself also lets the command run, though Pi blocks a tool call whose handler throws. If node isn't on `PATH`, the hook command fails and the agent carries on. `DISABLE_AGENT_GUARD=1` in the agent's environment turns the check off; in Claude Code, a gitignored settings.local.json in `.claude/` can set it for one checkout with `{ "env": { "DISABLE_AGENT_GUARD": "1" } }`. ## Skills From 475f00bd713d24a2d37db7d3deb985cc9d3be663 Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 14:07:46 +0000 Subject: [PATCH 2/3] chore(agents): note a guard Pi can't run, and test the calls it skips When guard.ts itself failed to load, such as with a syntax error, node exited with nothing on stdout and the extension read that as "nothing to say", so the push went through without the note the other agents show. A guard that exits unsuccessfully now gives a note with its exit code or signal and what it printed on stderr, and a timeout note carries the stderr too. The tests for the calls the extension skips (other tools, commands that can't push, DISABLE_AGENT_GUARD=1, a checkout without the guard) now put a `node` on PATH that records each start, so they fail if the extension starts the guard at all, rather than passing on a guard that ran and said nothing. The test driver writes its event file with TempRepo.write. --- .agents/scripts/pi-extension.test.ts | 74 ++++++++++++++++++++++------ .pi/extensions/agent-guard.ts | 17 ++++++- 2 files changed, 74 insertions(+), 17 deletions(-) diff --git a/.agents/scripts/pi-extension.test.ts b/.agents/scripts/pi-extension.test.ts index 0f1b55f..6cfc2f0 100644 --- a/.agents/scripts/pi-extension.test.ts +++ b/.agents/scripts/pi-extension.test.ts @@ -1,5 +1,5 @@ -import { mkdirSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' +import { chmodSync, existsSync } from 'node:fs' +import { delimiter, join } from 'node:path' import { afterEach, beforeEach, expect, it } from 'vitest' import { createTempRepo, markVerified, type TempRepo } from './lib/test-repo.ts' @@ -46,15 +46,14 @@ function setUp(target: TempRepo, { withGuard = true } = {}): void { function drive( event: { toolName: string; input: unknown }, - options: { root?: string; cwd?: string; env?: Record } = {}, + options: { target?: TempRepo; cwd?: string; env?: Record } = {}, ): Driven { - const root = options.root ?? repo.dir - const cwd = options.cwd ?? root - const eventFile = join(root, '.tmp/event.json') - mkdirSync(join(root, '.tmp'), { recursive: true }) - writeFileSync(eventFile, JSON.stringify(event)) - const extension = join(root, '.pi/extensions/agent-guard.ts') - const result = repo.run( + const target = options.target ?? repo + const cwd = options.cwd ?? target.dir + target.write('.tmp/event.json', JSON.stringify(event)) + const eventFile = join(target.dir, '.tmp/event.json') + const extension = join(target.dir, '.pi/extensions/agent-guard.ts') + const result = target.run( process.execPath, ['--no-warnings', '--input-type=module', '-e', DRIVER, extension, cwd, eventFile], { cwd, env: options.env }, @@ -65,6 +64,24 @@ function drive( const bash = (command: string) => ({ toolName: 'bash', input: { command } }) +/** + * A `node` first on PATH that notes each start before it runs the real one. The driver runs node + * by its full path, so only the extension's own `spawn('node', …)` of the guard goes through it. + */ +function watchNode(): { env: Record; started: () => boolean } { + const bin = join(repo.dir, '.tmp/bin') + const log = join(bin, 'started') + repo.write( + '.tmp/bin/node', + `#!/bin/sh\necho started >> '${log}'\nexec '${process.execPath}' "$@"\n`, + ) + chmodSync(join(bin, 'node'), 0o755) + return { + env: { PATH: `${bin}${delimiter}${process.env.PATH}` }, + started: () => existsSync(log), + } +} + const commitOnBranch = (branch: string, path: string) => repo.commitOnBranch(branch, path) beforeEach(() => { @@ -89,25 +106,40 @@ it("blocks an unverified push through tool_call with the guard's reason", () => it('lets the push run once verify has passed on it', () => { commitOnBranch('feature', 'src/b.ts') markVerified(repo.dir) - expect(drive(bash('git push -u origin HEAD'))).toEqual({ result: null, notes: [], stderr: '' }) + const node = watchNode() + expect(drive(bash('git push -u origin HEAD'), { env: node.env })).toEqual({ + result: null, + notes: [], + stderr: '', + }) + expect(node.started()).toBe(true) }) -it('leaves every other tool call alone', () => { +it('leaves every other tool call alone, without starting the guard', () => { commitOnBranch('feature', 'src/b.ts') + const node = watchNode() for (const event of [ bash('ls'), bash('git status && npm test'), { toolName: 'read', input: { path: 'push.md' } }, + { toolName: 'grep', input: { command: 'git push' } }, { toolName: 'bash', input: null }, ]) { - expect(drive(event), JSON.stringify(event)).toEqual({ result: null, notes: [], stderr: '' }) + expect(drive(event, { env: node.env }), JSON.stringify(event)).toEqual({ + result: null, + notes: [], + stderr: '', + }) } + expect(node.started()).toBe(false) }) it('does nothing with DISABLE_AGENT_GUARD=1', () => { commitOnBranch('feature', 'src/b.ts') - const off = drive(bash('git push'), { env: { DISABLE_AGENT_GUARD: '1' } }) + const node = watchNode() + const off = drive(bash('git push'), { env: { ...node.env, DISABLE_AGENT_GUARD: '1' } }) expect(off).toEqual({ result: null, notes: [], stderr: '' }) + expect(node.started()).toBe(false) }) it('skips a checkout without the guard, such as an older branch, without a word', () => { @@ -117,11 +149,13 @@ it('skips a checkout without the guard, such as an older branch, without a word' older.write('src/b.ts', 'export const b = 1\n') older.git(['add', '.']) older.git(['commit', '--quiet', '-m', 'b']) - expect(drive(bash('git push'), { root: older.dir })).toEqual({ + const node = watchNode() + expect(drive(bash('git push'), { target: older, env: node.env })).toEqual({ result: null, notes: [], stderr: '', }) + expect(node.started()).toBe(false) } finally { older.cleanup() } @@ -153,6 +187,16 @@ it('allows the call when the extension itself fails, which Pi would treat as a b expect(failed.stderr).toContain('the Pi extension failed, so it allowed the action') }) +it("notes a guard that can't run at all, such as one with a syntax error", () => { + commitOnBranch('feature', 'src/b.ts') + repo.write('.agents/scripts/guard.ts', 'this is not valid typescript (\n') + const broken = drive(bash('git push')) + expect(broken.result).toBeNull() + expect(broken.notes.join('\n')).toMatch( + /tool-start exited with code 1, so it allowed the action\. [\s\S]*SyntaxError/, + ) +}) + it('allows the call when the guard exits without reading its input or printing JSON', () => { commitOnBranch('feature', 'src/b.ts') // A command long enough that the write is still going when the guard closes the pipe diff --git a/.pi/extensions/agent-guard.ts b/.pi/extensions/agent-guard.ts index a864105..bfb2d16 100644 --- a/.pi/extensions/agent-guard.ts +++ b/.pi/extensions/agent-guard.ts @@ -68,14 +68,27 @@ function runGuard(payload: Record): Promise { } const timer = setTimeout(() => { child.kill() - finish({ systemMessage: 'agent-guard: tool-start timed out, so it allowed the action' }) + finish({ + systemMessage: + `agent-guard: tool-start timed out, so it allowed the action. ${stderr.trim()}`.trim(), + }) }, TIMEOUT_MS) child.stdout.on('data', (chunk: Buffer) => (stdout += chunk.toString())) child.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString())) child.on('error', (error) => { finish({ systemMessage: `agent-guard: tool-start failed to run: ${error.message}` }) }) - child.on('close', () => { + child.on('close', (code, signal) => { + // A guard that can't even load, such as one with a syntax error, prints nothing on + // stdout and says why on stderr. + if (code !== 0) { + const how = signal ? `was stopped by ${signal}` : `exited with code ${code}` + finish({ + systemMessage: + `agent-guard: tool-start ${how}, so it allowed the action. ${stderr.trim()}`.trim(), + }) + return + } try { finish(stdout.trim() ? (JSON.parse(stdout) as GuardOutput) : {}) } catch { From 2db9cfdc27ae0a8f31e7d8b5f76df5e24197e1fe Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 14:08:31 +0000 Subject: [PATCH 3/3] docs(agents): name Cursor among the agents that run the push check The overview listed Claude Code, Codex and Pi; Cursor runs the Claude Code hooks, as the table below it says. --- docs/agents.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/agents.md b/docs/agents.md index 928247a..dc147d4 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -65,7 +65,7 @@ If a pull-request workflow gains a step, `.agents/scripts/lib/steps.test.ts` fai ## The push check -Every agent calls one script, `.agents/scripts/guard.ts`, so the agents can't drift apart: Claude Code and Codex from their hook configs, Pi from a small extension. Before each shell command an agent runs, it stops one that pushes code `npm run verify` hasn't passed, or opens a pull request for it. That's where a person starts reviewing, so that's where the proof has to exist. It costs nothing until a command pushes: the hook command only starts Node when the shell command itself mentions a push or a new pull request, and the guard only runs git when it reads one. +Every agent calls one script, `.agents/scripts/guard.ts`, so the agents can't drift apart: Claude Code and Codex from their hook configs, Cursor through the Claude Code hooks, and Pi from a small extension. Before each shell command an agent runs, it stops one that pushes code `npm run verify` hasn't passed, or opens a pull request for it. That's where a person starts reviewing, so that's where the proof has to exist. It costs nothing until a command pushes: the hook command only starts Node when the shell command itself mentions a push or a new pull request, and the guard only runs git when it reads one. - **What it checks:** what's pushed has to be exactly a tree verify passed, docs aside. A push sends commits, not the working tree, so verifying with uncommitted changes and then pushing only some of them doesn't get through. When the working tree holds more than the last commit, it says to commit or stash the rest before verifying. - **A commit and a push in one command:** for `git add -A && git commit -m "…" && git push`, it checks the working tree that's about to be committed. That holds only when the commit takes all of it: everything staged first in the same command (`git add -A`, or `git add .` from the top folder), `git commit -a` with no untracked files, or a plain commit with nothing unstaged either. A commit that can leave part of the tree out, by naming paths, `--patch` or what it doesn't stage, is stopped: commit first, then push.