Skip to content
179 changes: 117 additions & 62 deletions .agents/scripts/guard.test.ts
Original file line number Diff line number Diff line change
@@ -1,124 +1,179 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { dirname, join } from 'node:path'
import { afterEach, beforeEach, expect, it } from 'vitest'
import { createTempRepo, type TempRepo } from './lib/test-repo.ts'
import { createTempRepo, markVerified, type TempRepo } from './lib/test-repo.ts'

// guard.ts as the agents' hooks run it: a separate node process, the hook's JSON on stdin, in a
// throwaway repo holding a copy of .agents/scripts.
// throwaway repo holding a copy of .agents/scripts. The decisions themselves are covered in
// lib/push-check.test.ts.
let repo: TempRepo

function guard(
event: string,
payload: Record<string, unknown> = { session_id: 's1' },
options: { cwd?: string; env?: Record<string, string | undefined> } = {},
payload: Record<string, unknown> | string,
options: { cwd?: string; env?: Record<string, string | undefined>; script?: string } = {},
) {
const result = repo.run(process.execPath, [join(repo.dir, '.agents/scripts/guard.ts'), event], {
input: JSON.stringify(payload),
const script = options.script ?? join(repo.dir, '.agents/scripts/guard.ts')
const result = repo.run(process.execPath, [script, 'tool-start'], {
input: typeof payload === 'string' ? payload : JSON.stringify(payload),
...options,
})
return { ...result, json: result.stdout ? JSON.parse(result.stdout) : undefined }
}

const bash = (command: string, cwd = repo.dir) => ({
tool_name: 'Bash',
tool_input: { command },
cwd,
})

const commitOnBranch = (branch: string, path: string) => repo.commitOnBranch(branch, path)

beforeEach(() => {
repo = createTempRepo()
repo.copyFromCheckout('.agents/scripts/guard.ts', '.agents/scripts/lib')
repo.write('.gitignore', '.tmp/\n')
repo.write('src/a.ts', 'export const a = 1\n')
repo.git(['add', '.'])
repo.git(['commit', '--quiet', '-m', 'initial'])
repo.addOrigin()
Comment thread
scottlovegrove marked this conversation as resolved.
Resolved
})

afterEach(() => repo.cleanup())

it('prints nothing for a turn that changed nothing', () => {
expect(guard('turn-start').status).toBe(0)
const end = guard('turn-end')
expect(end.status).toBe(0)
expect(end.stdout).toBe('')
it('stops an unverified push with the PreToolUse decision Claude Code and Codex read', () => {
commitOnBranch('feature', 'src/b.ts')
const result = guard(bash('git push -u origin HEAD'))
expect(result.status).toBe(0)
expect(result.json).toEqual({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'deny',
permissionDecisionReason: expect.stringContaining('npm run verify'),
},
})
})

it('sends the agent back with the block decision every agent reads', () => {
guard('turn-start')
repo.write('src/a.ts', 'export const a = 2\n')
const end = guard('turn-end')
expect(end.status).toBe(0)
expect(end.json).toEqual({ decision: 'block', reason: expect.stringContaining('src/a.ts') })
it('prints nothing for a verified push, or a command that pushes nothing', () => {
commitOnBranch('feature', 'src/b.ts')
markVerified(repo.dir)
expect(guard(bash('git push')).stdout).toBe('')
expect(guard(bash('ls')).stdout).toBe('')
// A tool call with no shell command, such as one a wider matcher lets through
expect(guard({ tool_name: 'Read', tool_input: { file_path: 'x' } }).stdout).toBe('')
})

it('sends the agent back on the first stop even if another hook set stop_hook_active or loop_count', () => {
for (const reentry of [{ stop_hook_active: true }, { loop_count: 1 }]) {
guard('turn-start')
repo.write('src/a.ts', `export const a = ${JSON.stringify(reentry)}\n`)
expect(guard('turn-end', { session_id: 's1', ...reentry }).json?.decision).toBe('block')
const second = guard('turn-end', { session_id: 's1', ...reentry })
expect(second.json).toEqual({ systemMessage: expect.stringContaining('agent-guard:') })
}
it('tells the person about a push it could not check', () => {
commitOnBranch('feature', 'src/b.ts')
expect(guard(bash('cd "$REPO" && git push')).json).toEqual({
systemMessage: "agent-guard: can't tell which folder a push runs in, so it isn't checked",
})
})

it('guards the checkout it lives in, whatever the working directory and git variables', () => {
it('guards the checkout it lives in, whatever the git variables', () => {
commitOnBranch('feature', 'src/b.ts')
const elsewhere = mkdtempSync(join(tmpdir(), 'agent-elsewhere-'))
try {
const other = { GIT_DIR: join(elsewhere, '.git'), GIT_WORK_TREE: elsewhere }
guard('turn-start', { session_id: 's1' }, { cwd: elsewhere, env: other })
repo.write('src/a.ts', 'export const a = 2\n')
const end = guard('turn-end', { session_id: 's1' }, { cwd: elsewhere, env: other })
expect(end.json?.decision).toBe('block')
const result = guard(bash('git push'), { cwd: elsewhere, env: other })
expect(result.json?.hookSpecificOutput?.permissionDecision).toBe('deny')
} finally {
rmSync(elsewhere, { recursive: true, force: true })
}
})

it('uses one default session when the payload has no id', () => {
guard('turn-start', {})
repo.write('src/a.ts', 'export const a = 2\n')
expect(guard('turn-end', {}).json?.decision).toBe('block')
it('guards another worktree of this repository the agent works in, never another repository', () => {
const tree = join(dirname(repo.dir), `${repo.dir.split('/').pop()}-linked`)
repo.git(['worktree', 'add', '--quiet', '-b', 'in-worktree', tree])
const other = createTempRepo()
try {
writeFileSync(join(tree, 'src/w.ts'), 'export const w = 1\n')
repo.git(['-C', tree, 'add', '.'])
repo.git(['-C', tree, 'commit', '--quiet', '-m', 'w'])
const inTree = guard(bash('git push', tree), { cwd: tree })
expect(inTree.json?.hookSpecificOutput?.permissionDecision).toBe('deny')

// Another repository with an unverified commit, and its own copy of the guard
other.copyFromCheckout('.agents/scripts/guard.ts', '.agents/scripts/lib')
other.write('src/o.ts', 'export const o = 1\n')
other.git(['add', '.'])
other.git(['commit', '--quiet', '-m', 'other'])
expect(guard(bash('git push', other.dir), { cwd: other.dir }).stdout).toBe('')
} finally {
other.cleanup()
repo.git(['worktree', 'remove', '--force', tree])
}
})

it('says so when it finds no git repository to guard', () => {
const outside = mkdtempSync(join(tmpdir(), 'agent-outside-'))
try {
mkdirSync(join(outside, '.agents'))
cpSync(join(repo.dir, '.agents/scripts'), join(outside, '.agents/scripts'), {
recursive: true,
})
const result = guard(bash('git push', outside), {
cwd: outside,
script: join(outside, '.agents/scripts/guard.ts'),
})
expect(result.json).toEqual({
systemMessage: 'agent-guard: no git repository found, so the push was not checked',
})
} finally {
rmSync(outside, { recursive: true, force: true })
}
})

it('fails open, visibly, when a library file is broken', () => {
guard('turn-start')
repo.write('.agents/scripts/lib/turn-gate.ts', 'this is not valid typescript (\n')
const end = guard('turn-end')
expect(end.status).toBe(0)
expect(end.json).toEqual({
systemMessage: expect.stringContaining('turn-end hook failed, so it allowed the action'),
commitOnBranch('feature', 'src/b.ts')
repo.write('.agents/scripts/lib/push-check.ts', 'this is not valid typescript (\n')
const result = guard(bash('git push'))
expect(result.status).toBe(0)
expect(result.json).toEqual({
systemMessage: expect.stringContaining('tool-start hook failed, so it allowed the action'),
})
})

it('fails open on input that is not JSON', () => {
const result = repo.run(
process.execPath,
[join(repo.dir, '.agents/scripts/guard.ts'), 'turn-end'],
{
input: 'not json',
},
)
it.each(['not json', '[1, 2]', 'null', '"git push"'])('fails open on the input %s', (input) => {
const result = guard(input)
expect(result.status).toBe(0)
expect(JSON.parse(result.stdout).systemMessage).toContain('hook failed')
expect(result.json.systemMessage).toContain('hook failed, so it allowed the action')
})

function runEvent(event: string) {
return repo.run(process.execPath, [join(repo.dir, '.agents/scripts/guard.ts'), event], {
input: JSON.stringify({ session_id: 's1' }),
})
}

it('fails open on an unknown event', () => {
const result = guard('turn-middle')
const result = runEvent('turn-middle')
expect(result.status).toBe(0)
expect(result.json.systemMessage).toContain('unknown event "turn-middle"')
expect(JSON.parse(result.stdout).systemMessage).toContain('unknown event "turn-middle"')
})

it('says nothing to the end-of-turn events older hook configs still send', () => {
commitOnBranch('feature', 'src/b.ts')
for (const event of ['turn-start', 'turn-end']) {
const result = runEvent(event)
expect([result.status, result.stdout, result.stderr], event).toEqual([0, '', ''])
}
})

it('runs the gate even when the agent running the tests has DISABLE_AGENT_GUARD=1', () => {
it('runs the check even when the agent running the tests has DISABLE_AGENT_GUARD=1', () => {
const previous = process.env.DISABLE_AGENT_GUARD
process.env.DISABLE_AGENT_GUARD = '1'
try {
guard('turn-start')
repo.write('src/a.ts', 'export const a = 2\n')
expect(guard('turn-end').json?.decision).toBe('block')
commitOnBranch('feature', 'src/b.ts')
expect(guard(bash('git push')).json?.hookSpecificOutput?.permissionDecision).toBe('deny')
} finally {
if (previous === undefined) delete process.env.DISABLE_AGENT_GUARD
else process.env.DISABLE_AGENT_GUARD = previous
}
})

it('does nothing with DISABLE_AGENT_GUARD=1', () => {
guard('turn-start')
repo.write('src/a.ts', 'export const a = 2\n')
const end = guard('turn-end', { session_id: 's1' }, { env: { DISABLE_AGENT_GUARD: '1' } })
expect(end.stdout).toBe('')
commitOnBranch('feature', 'src/b.ts')
const result = guard(bash('git push'), { env: { DISABLE_AGENT_GUARD: '1' } })
expect([result.status, result.stdout, result.stderr]).toEqual([0, '', ''])
})
78 changes: 49 additions & 29 deletions .agents/scripts/guard.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
// The one entry point every agent's hooks call, so the rules can't drift apart per agent.
//
// node .agents/scripts/guard.ts turn-start when the person sends a message: snapshot the tree
// node .agents/scripts/guard.ts turn-end when the agent stops: may send it back once
// node .agents/scripts/guard.ts tool-start before a shell command: stops a push, or a new pull
// request, of code `npm run verify` hasn't passed
//
// Input is the hook's JSON on stdin; Claude Code, Codex and Cursor send compatible shapes, and
// all three read `{"decision":"block","reason":...}` from a Stop hook. The guard keeps its own
// record of having sent the agent back, rather than trusting stop_hook_active or loop_count. It
// guards the checkout this file lives in, not the hook's working directory. A broken guard never
// blocks work: any error allows the action and says why. DISABLE_AGENT_GUARD=1 turns it off.
// See docs/agents.md.
// Input is the hook's JSON on stdin; Claude Code and Codex send the same shape, and both read
// `hookSpecificOutput.permissionDecision: "deny"` from a PreToolUse hook. It guards pushes from the
// checkout this file lives in, and from the other worktrees of its repository that have it. A
// broken guard never blocks work: any error allows the action and says why. DISABLE_AGENT_GUARD=1
// turns it off. See docs/agents.md.

import { readFileSync } from 'node:fs'

Expand All @@ -23,36 +22,57 @@ function reply(value: Record<string, unknown>): void {
function readPayload(): Record<string, unknown> {
// Run by hand in a terminal, there is no hook payload; reading would wait for EOF.
if (process.stdin.isTTY) return {}
let text = ''
try {
text = readFileSync(0, 'utf8')
} catch {
return {}
const text = readFileSync(0, 'utf8')
const payload: unknown = text.trim() ? JSON.parse(text) : {}
if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
throw new Error("hook input isn't a JSON object")
}
return text.trim() ? (JSON.parse(text) as Record<string, unknown>) : {}
return payload as Record<string, unknown>
}

/**
* Events of the end-of-turn gate the push check replaced. Hook configs elsewhere still send them:
* Codex runs the main checkout's hooks in a linked worktree, and a running session keeps the
* hooks it started with. There is nothing to do for them.
*/
const RETIRED_EVENTS = new Set(['turn-start', 'turn-end'])

async function main(): Promise<void> {
if (event !== 'turn-start' && event !== 'turn-end') {
throw new Error(`unknown event "${event}"`)
}
if (event !== undefined && RETIRED_EVENTS.has(event)) return
if (event !== 'tool-start') throw new Error(`unknown event "${event}"`)
// Imported inside the try, so a broken library file fails open like any other error.
const { CHECKOUT_ROOT } = await import('./lib/git.ts')
const { endTurn, startTurn } = await import('./lib/turn-gate.ts')
const { CHECKOUT_ROOT, findRepoRoot } = await import('./lib/git.ts')
const { checkCommand } = await import('./lib/push-check.ts')
const { findTargets } = await import('./lib/push-targets.ts')

const payload = readPayload()
const sessionId = String(
payload.session_id ?? payload.conversation_id ?? payload.thread_id ?? 'default',
)
if (event === 'turn-start') {
startTurn({ root: CHECKOUT_ROOT, sessionId })
const command = (payload.tool_input as { command?: unknown } | undefined)?.command
// A tool call with no shell command pushes nothing.
if (typeof command !== 'string') return
const cwd = typeof payload.cwd === 'string' ? payload.cwd : process.cwd()
// The command only mentions a push, in a message, a dry run or the like: no git to run.
if (!findTargets(command, cwd).some(({ kind }) => kind === 'push' || kind === 'pr')) return
const root = findRepoRoot(CHECKOUT_ROOT)
if (root === undefined) {
reply({
systemMessage: 'agent-guard: no git repository found, so the push was not checked',
})
return
}
const verdict = endTurn({ root: CHECKOUT_ROOT, sessionId })
if (verdict.decision === 'block') {
reply({ decision: 'block', reason: verdict.reason })
} else if (verdict.note) {
reply({ systemMessage: `agent-guard: ${verdict.note}` })

const verdict = checkCommand({ root, command, cwd })
const notes = verdict.notes.map((note) => `agent-guard: ${note}`).join('\n')
if (verdict.decision === 'deny') {
reply({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'deny',
permissionDecisionReason: verdict.reason,
},
...(notes ? { systemMessage: notes } : {}),
})
} else if (notes) {
reply({ systemMessage: notes })
}
}

Expand Down
Loading
Loading