Repository navigation
chore(agents): stop agents pushing code verify hasn't passed #135
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
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
22994d7
chore(agents): stop agents pushing code verify hasn't passed
scottlovegrove 8204e3a
chore(agents): keep a push's refspecs when the command sets git config
scottlovegrove fe22ed6
chore(agents): check a branch the command resets by its new tip
scottlovegrove 93f831e
chore(agents): fail on a file the snapshot can't read
scottlovegrove b431038
chore(agents): cover a push split across lines in the hook wiring test
scottlovegrove 0c95433
chore(agents): give the split-command wiring check a test of its own
scottlovegrove 916107c
chore(agents): check a commit and push in one command by what the com…
scottlovegrove 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
| 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() | ||
| }) | ||
|
|
||
| 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, '', '']) | ||
| }) | ||
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
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.