Repository navigation
chore(agents): run the push check in Pi #136
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
scottlovegrove
merged 3 commits into
scottl/agent-push-check
from
scottl/agent-guard-pi
Nov 27, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,210 @@ | ||
| 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' | ||
|
|
||
| // 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: { target?: TempRepo; cwd?: string; env?: Record<string, string> } = {}, | ||
| ): Driven { | ||
| 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 }, | ||
| ) | ||
| expect(result.status, result.stderr).toBe(0) | ||
| return { ...(JSON.parse(result.stdout) as Omit<Driven, 'stderr'>), stderr: result.stderr } | ||
| } | ||
|
|
||
| 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<string, string>; 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(() => { | ||
| 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) | ||
| 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, 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, { 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 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', () => { | ||
| 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']) | ||
| 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() | ||
| } | ||
| }) | ||
|
|
||
| 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("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 | ||
| 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') | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| // 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<ToolCallResult> | ||
|
|
||
| /** 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<string, unknown>): Promise<GuardOutput> { | ||
| 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. ${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', (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 { | ||
| 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<ToolCallResult> { | ||
| 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 | ||
| } | ||
| }) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.