From 22994d73a6f95a76bc97d94bd332fae58a8ab99e Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 12:50:28 +0000 Subject: [PATCH 1/7] chore(agents): stop agents pushing code verify hasn't passed Replaces the end-of-turn gate with a push check, ported from todoist/todoist-cli#672. Before each shell command, the Claude Code and Codex hooks (now one PreToolUse hook on Bash, replacing UserPromptSubmit and Stop) call .agents/scripts/guard.ts. It stops an agent's git push or gh pr create from this checkout until npm run verify has passed on exactly the commit being pushed, not the working tree. Pushes a person runs in their own terminal never go through it. The guard reads the shell command without running it (cd, git -C, wrappers, eval, sh -c, quotes and here-documents), fingerprints the pushed commit from git ls-tree, and lets through changes verify records nothing for, dry runs, deletions and tag-only pushes. A push whose contents it can't tell is stopped. DISABLE_AGENT_GUARD=1 still turns it off, a checkout without the guard is skipped, a guard that fails allows the action and says why, and the retired turn-start and turn-end events are ignored quietly. --- .agents/scripts/guard.test.ts | 179 ++++++++---- .agents/scripts/guard.ts | 78 +++-- .agents/scripts/hook-wiring.test.ts | 111 +++++-- .agents/scripts/lib/git.ts | 29 +- .agents/scripts/lib/push-check.test.ts | 350 +++++++++++++++++++++++ .agents/scripts/lib/push-check.ts | 302 +++++++++++++++++++ .agents/scripts/lib/push-targets.test.ts | 174 +++++++++++ .agents/scripts/lib/push-targets.ts | 331 +++++++++++++++++++++ .agents/scripts/lib/shell-commands.ts | 203 +++++++++++++ .agents/scripts/lib/test-repo.ts | 33 ++- .agents/scripts/lib/tree.test.ts | 43 ++- .agents/scripts/lib/tree.ts | 73 ++++- .agents/scripts/lib/turn-gate.test.ts | 187 ------------ .agents/scripts/lib/turn-gate.ts | 112 -------- .agents/scripts/verify.ts | 2 +- .agents/skills/verify/SKILL.md | 2 + .claude/settings.json | 16 +- .codex/hooks.json | 17 +- AGENTS.md | 2 +- CODEBASE.md | 4 +- docs/agents.md | 44 +-- 21 files changed, 1808 insertions(+), 484 deletions(-) create mode 100644 .agents/scripts/lib/push-check.test.ts create mode 100644 .agents/scripts/lib/push-check.ts create mode 100644 .agents/scripts/lib/push-targets.test.ts create mode 100644 .agents/scripts/lib/push-targets.ts create mode 100644 .agents/scripts/lib/shell-commands.ts delete mode 100644 .agents/scripts/lib/turn-gate.test.ts delete mode 100644 .agents/scripts/lib/turn-gate.ts diff --git a/.agents/scripts/guard.test.ts b/.agents/scripts/guard.test.ts index 99594d5..d6d1053 100644 --- a/.agents/scripts/guard.test.ts +++ b/.agents/scripts/guard.test.ts @@ -1,25 +1,34 @@ -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 = { session_id: 's1' }, - options: { cwd?: string; env?: Record } = {}, + payload: Record | string, + options: { cwd?: string; env?: Record; 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') @@ -27,89 +36,136 @@ beforeEach(() => { 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 @@ -117,8 +173,7 @@ it('runs the gate even when the agent running the tests has DISABLE_AGENT_GUARD= }) 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, '', '']) }) diff --git a/.agents/scripts/guard.ts b/.agents/scripts/guard.ts index 8524a00..ea72e52 100644 --- a/.agents/scripts/guard.ts +++ b/.agents/scripts/guard.ts @@ -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' @@ -23,36 +22,57 @@ function reply(value: Record): void { function readPayload(): Record { // 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) : {} + return payload as Record } +/** + * 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 { - 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 }) } } diff --git a/.agents/scripts/hook-wiring.test.ts b/.agents/scripts/hook-wiring.test.ts index 3fc7efb..13263fd 100644 --- a/.agents/scripts/hook-wiring.test.ts +++ b/.agents/scripts/hook-wiring.test.ts @@ -1,11 +1,14 @@ -import { existsSync, readFileSync, rmSync } from 'node:fs' -import { join } from 'node:path' +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { delimiter, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createTempRepo, REPO_ROOT, type TempRepo } from './lib/test-repo.ts' +import { createTempRepo, markVerified, REPO_ROOT, type TempRepo } from './lib/test-repo.ts' // Runs the exact hook commands from each agent's config, the way the agent would, in a // throwaway repo with a copy of .agents/scripts. -type HookConfig = { hooks: Record } +type HookConfig = { + hooks: Record +} const AGENTS = [ { @@ -29,13 +32,17 @@ const AGENTS = [ }, ] -function command(config: string, event: string): string { - const parsed = JSON.parse(readFileSync(join(REPO_ROOT, config), 'utf8')) as HookConfig - const commands = parsed.hooks[event]?.flatMap((entry) => - entry.hooks.map((hook) => hook.command), - ) - expect(commands, `${config} ${event}`).toHaveLength(1) - return commands?.[0] ?? '' +function readConfig(config: string): HookConfig { + return JSON.parse(readFileSync(join(REPO_ROOT, config), 'utf8')) as HookConfig +} + +/** The one command a config runs before each shell command. */ +function command(config: string): string { + const entries = readConfig(config).hooks.PreToolUse ?? [] + expect(entries.map((entry) => entry.matcher)).toEqual(['Bash']) + const commands = entries.flatMap((entry) => entry.hooks.map((hook) => hook.command)) + expect(commands, config).toHaveLength(1) + return commands[0] ?? '' } let repo: TempRepo @@ -47,34 +54,88 @@ beforeEach(() => { repo.write('src/a.ts', 'export const a = 1\n') repo.git(['add', '.']) repo.git(['commit', '--quiet', '-m', 'initial']) + repo.addOrigin() + repo.git(['switch', '--quiet', '-c', 'feature']) + repo.write('src/a.ts', 'export const a = 2\n') + repo.git(['commit', '--quiet', '-am', 'change a']) }) afterEach(() => repo.cleanup()) describe.each(AGENTS)('$name', ({ config, env }) => { - const run = (event: string) => - repo.run('sh', ['-c', command(config, event)], { + const run = ( + input: string, + options: { dir?: string; path?: string } = {}, + ): { status: number | null; stdout: string; stderr: string } => { + const dir = options.dir ?? repo.dir + const result = repo.run('sh', ['-c', command(config)], { + cwd: join(dir, 'src'), + env: { ...env(dir), ...(options.path ? { PATH: options.path } : {}) }, + input, + }) + return { status: result.status, stdout: result.stdout, stderr: result.stderr } + } + const bash = (shell: string) => + JSON.stringify({ + tool_name: 'Bash', + tool_input: { command: shell }, cwd: join(repo.dir, 'src'), - env: env(repo.dir), - input: JSON.stringify({ session_id: 'wiring' }), }) + const decision = (stdout: string) => JSON.parse(stdout).hookSpecificOutput?.permissionDecision + + it('stops an unverified push or pull request, and lets it through once verify passed', () => { + const pushed = run(bash('git push -u origin HEAD')) + expect(pushed.status).toBe(0) + expect(decision(pushed.stdout)).toBe('deny') + expect(decision(run(bash('gh pr create --fill')).stdout)).toBe('deny') + expect(decision(run(bash('gh pr\tcreate --fill')).stdout)).toBe('deny') - it('sends the agent back after an unverified code change', () => { - expect(run('UserPromptSubmit').status).toBe(0) - repo.write('src/a.ts', 'export const a = 2\n') - const stop = run('Stop') - expect(stop.status).toBe(0) - expect(JSON.parse(stop.stdout)).toMatchObject({ decision: 'block' }) + markVerified(repo.dir) + expect(run(bash('git push -u origin HEAD'))).toEqual({ status: 0, stdout: '', stderr: '' }) }) - it('says so, and lets work continue, in a checkout without the guard', () => { + it('never starts git or node for a command that cannot push', () => { + const bin = mkdtempSync(join(tmpdir(), 'agent-bin-')) + const calls = join(bin, 'calls') + try { + for (const tool of ['git', 'node']) { + writeFileSync(join(bin, tool), `#!/bin/sh\necho ${tool} >> "${calls}"\n`) + chmodSync(join(bin, tool), 0o755) + } + const path = `${bin}${delimiter}${process.env.PATH}` + // Even input the guard would reject passes in silence, at no cost. + expect(run('{not json, ls', { path })).toEqual({ status: 0, stdout: '', stderr: '' }) + expect(run(bash('npm test && git status'), { path })).toEqual({ + status: 0, + stdout: '', + stderr: '', + }) + // Only the command counts, not a folder name elsewhere in the payload + const inPushFolder = JSON.stringify({ + cwd: '/work/fix-push', + transcript_path: '/home/me/.claude/projects/-work-fix-push/session.jsonl', + tool_name: 'Bash', + tool_input: { command: 'ls' }, + }) + expect(run(inPushFolder, { path })).toEqual({ status: 0, stdout: '', stderr: '' }) + expect(existsSync(calls)).toBe(false) + } finally { + rmSync(bin, { recursive: true, force: true }) + } + }) + + it('skips a checkout without the guard, such as an older branch, without a word', () => { rmSync(join(repo.dir, '.agents'), { recursive: true }) - const stop = run('Stop') - expect(stop.status).toBe(0) - expect(JSON.parse(stop.stdout).systemMessage).toContain('has no .agents/scripts/guard.ts') + expect(run(bash('git push'))).toEqual({ status: 0, stdout: '', stderr: '' }) }) }) +it('runs the guard only before shell commands, and at no other point', () => { + for (const config of ['.claude/settings.json', '.codex/hooks.json']) { + expect(Object.keys(readConfig(config).hooks), config).toEqual(['PreToolUse']) + } +}) + it('has no Cursor hooks file: Cursor runs the Claude Code hooks, and a second file runs them twice', () => { expect(existsSync(join(REPO_ROOT, '.cursor/hooks.json'))).toBe(false) }) diff --git a/.agents/scripts/lib/git.ts b/.agents/scripts/lib/git.ts index 8856aa5..0ae3466 100644 --- a/.agents/scripts/lib/git.ts +++ b/.agents/scripts/lib/git.ts @@ -42,14 +42,31 @@ export function defaultBranchRef(root: string): string | undefined { 'refs/remotes/origin/main', 'refs/heads/main', ] - return candidates.find( - (ref) => ref && git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).ok, - ) + return candidates.find((ref) => ref && resolveCommit(root, ref) !== undefined) } -/** Where the current branch left the default branch, or undefined if there is no default branch. */ -export function branchBase(root: string, ref = defaultBranchRef(root)): string | undefined { +/** The commit `ref` names, or undefined when it names none. */ +export function resolveCommit(root: string, ref: string): string | undefined { + const commit = git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]) + return commit.ok ? commit.stdout.trim() || undefined : undefined +} + +/** + * Where the current branch, or `head`, left the default branch, or undefined if there is no default + * branch or they share no history. + */ +export function branchBase( + root: string, + ref = defaultBranchRef(root), + head = 'HEAD', +): string | undefined { if (!ref) return undefined - const base = git(root, ['merge-base', 'HEAD', ref]) + const base = git(root, ['merge-base', head, ref]) return base.ok ? base.stdout.trim() : undefined } + +/** The top folder of the checkout `dir` is in, or undefined when it isn't in one. */ +export function findRepoRoot(dir: string): string | undefined { + const toplevel = git(dir, ['rev-parse', '--show-toplevel']) + return toplevel.ok ? toplevel.stdout.trim() : undefined +} diff --git a/.agents/scripts/lib/push-check.test.ts b/.agents/scripts/lib/push-check.test.ts new file mode 100644 index 0000000..55f9e61 --- /dev/null +++ b/.agents/scripts/lib/push-check.test.ts @@ -0,0 +1,350 @@ +import { rmSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { checkCommand, type PushVerdict } from './push-check.ts' +import { createTempRepo, markVerified as markDirVerified, type TempRepo } from './test-repo.ts' + +let repo: TempRepo + +function check(command: string, cwd = repo.dir): PushVerdict { + return checkCommand({ root: repo.dir, command, cwd }) +} + +/** The reason the check stops `command`, or undefined when it lets it run. */ +function denial(command: string, cwd?: string): string | undefined { + const verdict = check(command, cwd) + return verdict.decision === 'deny' ? verdict.reason : undefined +} + +const markVerified = () => markDirVerified(repo.dir) +const commitOnBranch = (branch: string, path: string, content?: string) => + repo.commitOnBranch(branch, path, content) + +/** A linked worktree of the test repo on a new branch, beside it. */ +function addWorktree(name: string): string { + const tree = join(dirname(repo.dir), `${repo.dir.split('/').pop()}-${name}`) + repo.git(['worktree', 'add', '--quiet', '-b', name, tree]) + return tree +} + +const config = (...args: string[]) => repo.git(['config', ...args]) + +beforeEach(() => { + // The check reads git's push settings, so the person's own git config must not reach it. + vi.stubEnv('GIT_CONFIG_GLOBAL', '/dev/null') + vi.stubEnv('GIT_CONFIG_NOSYSTEM', '1') + repo = createTempRepo() + repo.write('.gitignore', '.tmp/\n') + repo.write('src/a.ts', 'export const a = 1\n') + repo.write('README.md', 'readme\n') + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'initial']) + repo.addOrigin() +}) + +afterEach(() => { + repo.cleanup() + vi.unstubAllEnvs() +}) + +describe('pushes it checks', () => { + it('stops a branch that deletes a doc, since the agent docs may name it', () => { + repo.git(['switch', '--quiet', '-c', 'no-readme']) + repo.git(['rm', '--quiet', 'README.md']) + repo.git(['commit', '--quiet', '-m', 'remove the readme']) + expect(denial('git push')).toContain('npm run verify') + // The same, committed in the command that pushes + repo.git(['reset', '--quiet', '--hard', 'main']) + rmSync(join(repo.dir, 'README.md')) + expect(denial('git commit -am "remove it" && git push')).toContain('npm run verify') + }) + it('stops a push of code verify has not passed, and allows it once it has', () => { + commitOnBranch('feature', 'src/b.ts') + const reason = denial('git push -u origin HEAD') + expect(reason).toContain("This pushes code that `npm run verify` hasn't passed.") + expect(reason).toContain('Run `npm run verify` and fix what fails') + expect(reason).not.toContain('git stash') + + markVerified() + expect(check('git push -u origin HEAD')).toEqual({ decision: 'allow', notes: [] }) + }) + + it('stops a push of a commit that holds less than the tree verify passed', () => { + commitOnBranch('partial', 'src/committed.ts') + repo.write('src/uncommitted.ts', 'export const y = 1\n') + markVerified() + expect(denial('git push')).toMatch( + /holds changes your last commit doesn't[\s\S]*git stash -u/, + ) + }) + + it('checks the working tree when the same command commits before it pushes', () => { + repo.git(['switch', '--quiet', '-c', 'together']) + repo.write('src/together.ts', 'export const t = 1\n') + const command = 'git add -A && git commit -m "add together" && git push' + expect(denial(command)).toContain('npm run verify') + markVerified() + expect(check(command).decision).toBe('allow') + }) + + it('stops a new pull request for unverified code, including one for another branch', () => { + commitOnBranch('pull-request', 'src/feature.ts') + expect(denial('gh pr create --fill')).toContain( + "This opens a pull request for code that `npm run verify` hasn't passed.", + ) + repo.git(['switch', '--quiet', 'main']) + expect(denial('gh pr create --head pull-request --fill')).toContain('opens a pull request') + }) + + it('checks a push from a subfolder, and one split across lines', () => { + commitOnBranch('nested', 'src/nested.ts') + expect(denial('git push', join(repo.dir, 'src'))).toContain('npm run verify') + expect(denial('git \\\n push origin nested')).toContain('npm run verify') + }) + + it('stops a push of every branch at once, since there is no one tree to check', () => { + expect(denial('git push --all origin')).toContain('every branch at once') + expect(denial("git push origin 'refs/heads/*:refs/heads/*'")).toContain( + 'every branch at once', + ) + }) + + it("stops a push with no refspec when git's push settings pick what it sends", () => { + commitOnBranch('configured', 'src/configured.ts') + markVerified() + expect(check('git push').decision).toBe('allow') + + config('remote.origin.push', 'refs/heads/main:refs/heads/main') + expect(denial('git push origin')).toContain('push settings pick') + expect(check('git push origin configured').decision).toBe('allow') + config('--unset', 'remote.origin.push') + + // Another remote's settings don't change what a push to origin sends… + config('remote.other.push', 'refs/heads/main:refs/heads/main') + expect(check('git push origin').decision).toBe('allow') + // …but they do when git's settings send a bare push there. + for (const key of [ + 'branch.configured.pushRemote', + 'remote.pushDefault', + 'branch.configured.remote', + ]) { + config(key, 'other') + expect(denial('git push'), key).toContain('push settings pick') + expect(check('git push origin').decision, key).toBe('allow') + config('--unset', key) + } + config('--unset', 'remote.other.push') + + config('remote.origin.mirror', 'yes') + expect(denial('git push origin')).toContain('push settings pick') + config('remote.origin.mirror', 'off') + expect(check('git push origin').decision).toBe('allow') + config('--unset', 'remote.origin.mirror') + + config('push.default', 'matching') + expect(denial('git push')).toContain('push settings pick') + config('--unset', 'push.default') + + // With one remote, a bare push goes there, whatever its name. + repo.git(['remote', 'rename', 'origin', 'upstream']) + config('remote.upstream.push', 'refs/heads/main:refs/heads/main') + expect(denial('git push')).toContain('push settings pick') + }) + + it('checks a branch pushed by name against where that branch left main', () => { + commitOnBranch('elsewhere', 'src/elsewhere.ts') + // main moves on after `elsewhere` left it + repo.git(['switch', '--quiet', 'main']) + repo.write('src/upstream.ts', 'export const u = 1\n') + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'upstream']) + repo.git(['push', '--quiet', 'origin', 'main']) + commitOnBranch('docs-branch', 'docs/notes.md', '# notes\n') + repo.git(['switch', '--quiet', 'elsewhere']) + + expect(check('git push origin docs-branch').decision).toBe('allow') + expect(check('git push origin origin/main:refs/heads/copy').decision).toBe('allow') + // An unverified branch that is checked out can be verified here… + expect(denial('git push origin elsewhere')).not.toContain('Check out each branch') + // …and one that isn't can't. + repo.git(['switch', '--quiet', 'docs-branch']) + expect(denial('git push origin elsewhere')).toContain('Check out each branch') + // A branch the same command makes holds what's checked out. + markVerified() + expect(check('git switch -c made && git push -u origin made').decision).toBe('allow') + }) + + it('stops a push on a branch that shares no history with main, as verify records a pass there', () => { + repo.git(['switch', '--quiet', '--orphan', 'alone']) + repo.write('docs/notes.md', '# notes\n') + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'alone']) + expect(denial('git push origin alone')).toContain('npm run verify') + markVerified() + expect(check('git push origin alone').decision).toBe('allow') + }) +}) + +describe('pushes it stops before reading them', () => { + it('stops a push that follows a branch switch, rebase or pull in the same command', () => { + commitOnBranch('feature', 'src/b.ts') + markVerified() + repo.git(['switch', '--quiet', '-c', 'other', 'main']) + repo.write('src/other.ts', 'export const o = 1\n') + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'other']) + repo.git(['switch', '--quiet', 'feature']) + for (const command of [ + 'git switch other && git push', + 'git checkout other && git push origin HEAD', + 'git pull --rebase && git push', + 'git rebase origin/main && git push --force-with-lease origin feature', + 'git reset --hard other && git push', + 'gh pr checkout 12 && git push', + ]) { + expect(denial(command), command).toContain('Run the push as a command of its own.') + } + // These keep what's checked out + for (const command of [ + 'git checkout -- src/b.ts && git push', + 'git reset && git push', + 'git switch -c copy && git push -u origin copy', + 'git checkout -b copy2 && git push -u origin copy2', + 'git branch copy3 && git push origin copy3', + ]) { + expect(check(command), command).toEqual({ decision: 'allow', notes: [] }) + } + }) + + it('stops a push of a branch named by a variable, or one that does not exist', () => { + commitOnBranch('feature', 'src/b.ts') + markVerified() + for (const command of [ + 'git push origin "$BRANCH"', + 'for b in feature other; do git push -u origin $b; done', + 'git push origin nowhere', + 'git switch -c new origin/main && git push -u origin new', + ]) { + expect(denial(command), command).toMatch(/can't tell what it (will )?send/) + } + }) + + it('reads a push run through eval, a shell, sudo or xargs', () => { + commitOnBranch('feature', 'src/b.ts') + for (const command of [ + 'eval "git push origin feature"', + "sh -c 'git push origin feature'", + 'bash -lc "cd src && git push"', + 'sudo -u me git push', + "env -S 'git push origin feature'", + ]) { + expect(denial(command), command).toContain('npm run verify') + } + expect(denial('echo feature | xargs git push origin')).toContain('what `xargs` adds') + markVerified() + expect(check('eval "git push origin feature"').decision).toBe('allow') + }) +}) + +describe('pushes that need no verify', () => { + it('allows a branch that changes only docs or files only CI reads', () => { + commitOnBranch('docs-only', 'docs/notes.md', '# notes\n') + repo.write('README.md', 'changed\n') + repo.write('renovate.json', '{}\n') + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'docs and renovate']) + expect(check('git push origin docs-only')).toEqual({ decision: 'allow', notes: [] }) + expect(check('gh pr create --fill').decision).toBe('allow') + }) + + it('allows a branch whose code is what main already has', () => { + commitOnBranch('undone', 'src/undone.ts') + repo.git(['rm', '--quiet', 'src/undone.ts']) + repo.git(['commit', '--quiet', '-m', 'undo']) + expect(check('git push').decision).toBe('allow') + }) + + it('allows dry runs, deletions and pushes of tags alone', () => { + commitOnBranch('quiet', 'src/quiet.ts') + for (const command of [ + 'git push --dry-run', + 'git push -n origin quiet', + 'git push origin --delete old', + 'git push origin :old', + 'git push --tags', + ]) { + expect(check(command), command).toEqual({ decision: 'allow', notes: [] }) + } + }) +}) + +describe('pushes it leaves alone, and says so', () => { + it('lets a push from another checkout through without a word', () => { + commitOnBranch('here', 'src/here.ts') + const other = createTempRepo() + try { + expect(check(`cd '${other.dir}' && git push`)).toEqual({ decision: 'allow', notes: [] }) + } finally { + other.cleanup() + } + }) + + it("notes a push from a folder it can't name, or that isn't in a checkout yet", () => { + commitOnBranch('unnamed', 'src/unnamed.ts') + expect(check('cd "$REPO" && git push')).toEqual({ + decision: 'allow', + notes: ["can't tell which folder a push runs in, so it isn't checked"], + }) + const made = check('mkdir -p newdir && cd newdir && git push') + expect(made.decision).toBe('allow') + expect(made.notes).toEqual([expect.stringMatching(/can't find the checkout of .*newdir/)]) + }) + + it("notes a pull request for a branch it can't find, in full words", () => { + expect(check('gh pr create --head nowhere')).toEqual({ + decision: 'allow', + notes: ["can't find nowhere, so the pull request isn't checked"], + }) + expect(check('cd "$REPO" && gh pr create --fill').notes).toEqual([ + "can't tell which folder a pull request runs in, so it isn't checked", + ]) + }) + + it('ignores commands that push nothing', () => { + commitOnBranch('reading', 'src/reading.ts') + for (const command of ['git status', 'git commit -m "then git push"', 'gh pr view']) { + expect(check(command), command).toEqual({ decision: 'allow', notes: [] }) + } + }) +}) + +describe('worktrees', () => { + it('checks a push from another worktree of this repository that has the guard', () => { + const tree = addWorktree('linked') + writeFileSync(join(tree, 'src/w.ts'), 'export const w = 1\n') + repo.git(['-C', tree, 'add', '.']) + repo.git(['-C', tree, 'commit', '--quiet', '-m', 'w']) + // An older branch has no guard, and is left alone + expect(check(`git -C '${tree}' push origin HEAD`)).toEqual({ decision: 'allow', notes: [] }) + + repo.write('.agents/scripts/guard.ts', '') + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'add the guard']) + repo.git(['-C', tree, 'merge', '--quiet', '--no-edit', 'main']) + for (const command of [ + `git -C '${tree}' push origin HEAD`, + `git -C'${tree}' push origin HEAD`, + `cd '${tree}' && git push`, + ]) { + expect(denial(command), command).toContain('npm run verify') + } + expect(denial('git push', tree)).toContain('npm run verify') + + // Its own verify record counts, not this checkout's + markVerified() + expect(denial(`git -C '${tree}' push origin HEAD`)).toContain('npm run verify') + markDirVerified(tree) + expect(check(`git -C '${tree}' push origin HEAD`).decision).toBe('allow') + repo.git(['worktree', 'remove', '--force', tree]) + }) +}) diff --git a/.agents/scripts/lib/push-check.ts b/.agents/scripts/lib/push-check.ts new file mode 100644 index 0000000..3ff4f32 --- /dev/null +++ b/.agents/scripts/lib/push-check.ts @@ -0,0 +1,302 @@ +// The push check. Before an agent runs a shell command, it stops one that pushes code from this +// checkout, or another worktree of it, that `npm run verify` hasn't passed, or opens a pull request +// for it. A push sends commits, not the working tree, so what's pushed has to be exactly a tree +// verify passed. Changes that verify records nothing for (docs, files only CI reads) need no +// verify. + +import { existsSync, realpathSync } from 'node:fs' +import { join } from 'node:path' +import { branchBase, defaultBranchRef, findRepoRoot, git, resolveCommit } from './git.ts' +import { findTargets } from './push-targets.ts' +import { readVerified } from './state.ts' +import { + changedSince, + changeNeedsChecks, + codeFingerprint, + commitChanges, + needsChecks, + snapshot, + snapshotCommit, +} from './tree.ts' + +export type PushVerdict = + | { decision: 'allow'; notes: string[] } + | { decision: 'deny'; reason: string; notes: string[] } + +/** One checkout the command pushes from, with what the command does there before it pushes. */ +type Checkout = { + root: string + notes: string[] + head: string | undefined + verified: string | undefined + /** Read only when needed, since most checks never get that far. */ + defaultRef: () => string | undefined + /** The working tree's fingerprint, read once however many sources the command pushes. */ + tree: () => string + committedFirst: boolean + movedFirst: boolean + /** Branches the command makes from what's checked out before it pushes them. */ + created: Set +} + +/** + * What one push source sends: `ok`; `every` (every branch, a wildcard, or what git's settings or + * `xargs` pick); `unknown` (a branch named by a variable, or one that doesn't exist); `moved` (what's + * checked out changes first); `unverified`; `dirty` (unverified, and the working tree holds more than + * the pushed commit); or `other` (unverified, and not what's checked out). + */ +type SourceResult = 'ok' | 'every' | 'unknown' | 'moved' | 'unverified' | 'dirty' | 'other' + +export function checkCommand({ + root, + command, + cwd, +}: { + /** + * The checkout the guard lives in. It also guards the other worktrees of its repository that + * have the guard; pushes from anywhere else are that folder's business. + */ + root: string + command: string + /** The folder the command starts in. */ + cwd: string +}): PushVerdict { + const notes: string[] = [] + const targets = findTargets(command, cwd) + if (!targets.some((target) => target.kind === 'push' || target.kind === 'pr')) { + return { decision: 'allow', notes } + } + + const guarded = guardedCheckouts(root) + const checkouts = new Map() + const found = new Set() + let onlyPullRequests = true + for (const target of targets) { + const pushes = target.kind === 'push' || target.kind === 'pr' + const what = target.kind === 'pr' ? 'pull request' : 'push' + if (target.dir === null) { + if (pushes) notes.push(`can't tell which folder a ${what} runs in, so it isn't checked`) + continue + } + const path = checkoutOf(target.dir) + // A folder that doesn't exist yet, such as one the same command makes. + if (path === undefined) { + if (pushes) { + notes.push( + `can't find the checkout of ${target.dir}, so a ${what} there isn't checked`, + ) + } + continue + } + if (!guarded(path)) continue + let checkout = checkouts.get(path) + if (checkout === undefined) { + checkout = openCheckout(path, notes) + checkouts.set(path, checkout) + } + if (target.kind === 'commit') checkout.committedFirst = true + else if (target.kind === 'move') checkout.movedFirst = true + else if (target.kind === 'create') { + for (const name of target.sources) checkout.created.add(name) + } else { + // With no refspec, git's push settings can send other branches than HEAD. + const sources = + target.implicit && configuredPush(path, target.remote ?? null) + ? ['*'] + : target.sources + for (const source of sources) { + const result = checkSource(checkout, source, target.kind) + if (result === 'ok') continue + if (target.kind === 'push') onlyPullRequests = false + found.add(result) + } + } + } + if (found.size === 0) return { decision: 'allow', notes } + return { decision: 'deny', reason: denyReason(found, onlyPullRequests), notes } +} + +/** + * Which checkouts to guard: the one the guard lives in, and the other worktrees of its repository + * that have the guard (a worktree on an older branch doesn't), such as one Claude Code entered + * mid-session. Never another repository. + */ +function guardedCheckouts(root: string): (path: string) => boolean { + const own = realPath(root) + let shared: string | undefined + return (path) => { + if (path === own) return true + shared ??= commonDir(root) + return ( + shared !== undefined && + commonDir(path) === shared && + existsSync(join(path, '.agents/scripts/guard.ts')) + ) + } +} + +function openCheckout(root: string, notes: string[]): Checkout { + let tree: string | undefined + let defaultRef: { ref: string | undefined } | undefined + return { + root, + notes, + head: resolveCommit(root, 'HEAD'), + verified: readVerified(root)?.fingerprint, + defaultRef: () => (defaultRef ??= { ref: defaultBranchRef(root) }).ref, + tree: () => (tree ??= codeFingerprint(snapshot(root))), + committedFirst: false, + movedFirst: false, + created: new Set(), + } +} + +/** The real path of the checkout a folder is in, or undefined when it isn't in one. */ +function checkoutOf(dir: string): string | undefined { + const toplevel = findRepoRoot(dir) + return toplevel === undefined ? undefined : realPath(toplevel) +} + +/** The repository a checkout belongs to, the same for all its worktrees. */ +function commonDir(dir: string): string | undefined { + const common = git(dir, ['rev-parse', '--path-format=absolute', '--git-common-dir']) + return common.ok ? realPath(common.stdout.trim()) : undefined +} + +function realPath(path: string): string | undefined { + try { + return realpathSync(path) + } catch { + return undefined + } +} + +function setting(root: string, key: string): string | undefined { + const value = git(root, ['config', '--get', key]) + return value.ok ? value.stdout.trim() || undefined : undefined +} + +/** + * Whether a push with no refspec sends what git's settings pick rather than the current branch: + * the push refspec or mirror setting of the remote it pushes to, or `push.default=matching`. + */ +function configuredPush(root: string, remote: string | null): boolean { + if (setting(root, 'push.default') === 'matching') return true + const current = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']) + const branch = current.ok ? current.stdout.trim() : undefined + const target = + remote ?? + (branch ? setting(root, `branch.${branch}.pushRemote`) : undefined) ?? + setting(root, 'remote.pushDefault') ?? + (branch ? setting(root, `branch.${branch}.remote`) : undefined) ?? + soleRemote(root) ?? + 'origin' + const mirror = git(root, ['config', '--type=bool', '--get', `remote.${target}.mirror`]) + return setting(root, `remote.${target}.push`) !== undefined || mirror.stdout.trim() === 'true' +} + +/** The only remote, which git pushes to when nothing else names one. */ +function soleRemote(root: string): string | undefined { + const remotes = git(root, ['remote']).stdout.split('\n').filter(Boolean) + return remotes.length === 1 ? remotes[0] : undefined +} + +function checkSource(checkout: Checkout, source: string, kind: 'push' | 'pr'): SourceResult { + if (source.includes('*')) return 'every' + // HEAD, or the branch a rebase or pull moves, holds something else by the time the push runs. + if (checkout.movedFirst) return 'moved' + // A shell variable or command substitution, whose value the command doesn't show + if (source.includes('$')) return 'unknown' + + const { root, notes, head } = checkout + let commit = resolveCommit(root, source) + if (commit === undefined) { + if (checkout.created.has(source)) commit = head + else if (kind === 'pr') { + // It may exist only on the remote, which no local check can vouch for either way. + notes.push(`can't find ${source}, so the pull request isn't checked`) + return 'ok' + } else return 'unknown' + if (commit === undefined) return 'ok' + } + // The same command commits first, so what it pushes is the working tree. + const fromTree = checkout.committedFirst && commit === head + const fingerprint = fromTree ? checkout.tree() : codeFingerprint(snapshotCommit(root, commit)) + if (fingerprint === checkout.verified) return 'ok' + if (onlyUncheckedChanges(checkout, fromTree ? undefined : commit)) return 'ok' + + if (!fromTree && commit !== head) return 'other' + if (!fromTree && checkout.tree() !== fingerprint) return 'dirty' + return 'unverified' +} + +/** + * Whether everything a commit, or the working tree when `commit` is undefined, changes since the + * default branch is something verify records nothing for: docs, or files only CI reads. Verify + * checks the whole tree, and records a pass, when there is no default branch to compare with, so + * then nothing is exempt. + */ +function onlyUncheckedChanges(checkout: Checkout, commit: string | undefined): boolean { + const { root } = checkout + // From the pushed commit: the branch checked out may have left main somewhere else. + const base = branchBase(root, checkout.defaultRef(), commit ?? 'HEAD') + if (base === undefined) return false + if (commit === undefined) + return !changedSince(root, base).some((path) => needsChecks(root, path)) + return !commitChanges(root, base, commit).some(({ path, deleted }) => + changeNeedsChecks(path, deleted), + ) +} + +function denyReason(found: Set, onlyPullRequests: boolean): string { + const paragraphs: string[] = [] + if (found.has('every')) { + paragraphs.push( + "This pushes every branch at once, the ones a wildcard matches, what git's push " + + 'settings pick (`remote..push`, or `push.default=matching`), or what `xargs` ' + + "adds, so the push check can't tell what it sends. Name each branch instead: `git " + + 'push origin `.', + ) + } + if (found.has('unknown')) { + paragraphs.push( + 'This pushes a branch named by a shell variable, or one that does not exist, so the ' + + "push check can't tell what it sends. Name each branch instead: `git push origin " + + '`.', + ) + } + if (found.has('moved')) { + paragraphs.push( + 'This changes what is checked out (`git switch`, `git checkout`, `git rebase`, `git ' + + "pull` and the like) before it pushes, so the push check can't tell what it will " + + 'send. Run the push as a command of its own.', + ) + } + if (found.has('unverified') || found.has('dirty') || found.has('other')) { + const lines = [ + onlyPullRequests + ? "This opens a pull request for code that `npm run verify` hasn't passed." + : "This pushes code that `npm run verify` hasn't passed.", + '', + found.has('other') + ? 'Verify checks the working tree and keeps one record per checkout, so it can only ' + + 'vouch for what you have checked out. Check out each branch, run `npm run ' + + 'verify` there, and push it on its own.' + : 'Run `npm run verify` and fix what fails, then run this command again.', + ] + if (found.has('dirty')) { + lines.push( + "Verify checks the working tree, which holds changes your last commit doesn't. " + + 'Commit what belongs in it, and stash the rest with `git stash -u` before you ' + + 'run verify. `git stash pop` brings them back afterwards.', + ) + } + paragraphs.push(lines.join('\n')) + } + return [ + paragraphs.join('\n\n'), + 'If it has to be pushed this way anyway, ask the person you are working with to push it ' + + 'themselves.', + 'Details: docs/agents.md', + ].join('\n') +} diff --git a/.agents/scripts/lib/push-targets.test.ts b/.agents/scripts/lib/push-targets.test.ts new file mode 100644 index 0000000..8bc19a0 --- /dev/null +++ b/.agents/scripts/lib/push-targets.test.ts @@ -0,0 +1,174 @@ +import { homedir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { findTargets } from './push-targets.ts' + +// [kind, folder, sources] for each push, pull request and commit a command runs, from /w. +type Row = [string, string | null, string] + +const read = (command: string): Row[] => + findTargets(command, '/w').map((target) => [target.kind, target.dir, target.sources.join(',')]) + +describe('findTargets', () => { + it.each<[string, Row[]]>([ + ['git push', [['push', '/w', 'HEAD']]], + ['cd ../other && git push origin main', [['push', '/other', 'main']]], + [ + '(cd sub && git push) && git -C /x push', + [ + ['push', '/w/sub', 'HEAD'], + ['push', '/x', 'HEAD'], + ], + ], + ['FOO=1 command git push 2>&1 | tail', [['push', '/w', 'HEAD']]], + ['git push origin +feature:main :old tag v1', [['push', '/w', 'feature,refs/tags/v1']]], + ['git push --all', [['push', '/w', '*']]], + [ + 'git push origin :; git push origin +:', + [ + ['push', '/w', '*'], + ['push', '/w', '*'], + ], + ], + ['cd "$REPO"; (cd /tmp); git push', [['push', null, 'HEAD']]], + ['cd - && git push', [['push', null, 'HEAD']]], + ['cd ~/code && git push', [['push', join(homedir(), 'code'), 'HEAD']]], + ['gh pr create --head me:feature --fill', [['pr', '/w', 'feature']]], + [ + 'git commit -m "fix: git push later" && git push', + [ + ['commit', '/w', ''], + ['push', '/w', 'HEAD'], + ], + ], + // Wrappers, keywords and full paths still run git. + ['if /usr/bin/git push; then echo ok; fi', [['push', '/w', 'HEAD']]], + ['! timeout -k 5 60 nohup git push', [['push', '/w', 'HEAD']]], + ['env -u FOO -C /x git push', [['push', '/x', 'HEAD']]], + [ + 'env -C/x git push; builtin git push', + [ + ['push', '/x', 'HEAD'], + ['push', '/w', 'HEAD'], + ], + ], + ['git push --repo=origin backup', [['push', '/w', 'HEAD']]], + ['command -p git push; command -v git push', [['push', '/w', 'HEAD']]], + ['pushd sub && git push', [['push', '/w/sub', 'HEAD']]], + ['git --git-dir=/r/.git push', [['push', null, 'HEAD']]], + // A command split across lines, as agents write long ones. + ['gh pr \\\n create --fill', [['pr', '/w', 'HEAD']]], + [ + 'echo "$(cd /x && git push)" && git push', + [ + ['push', '/x', 'HEAD'], + ['push', '/w', 'HEAD'], + ], + ], + [ + 'git -C/x push; git -C ../y push', + [ + ['push', '/x', 'HEAD'], + ['push', '/y', 'HEAD'], + ], + ], + [ + 'pushd -n /x && git push; pushd +1 && git push', + [ + ['push', '/w', 'HEAD'], + ['push', null, 'HEAD'], + ], + ], + // Commands that run a command given to them as words or a string + [ + 'eval "cd /x && git push origin main"; git push', + [ + ['push', '/x', 'main'], + ['push', '/x', 'HEAD'], + ], + ], + [ + "bash -lc 'cd /x && git push'; git push", + [ + ['push', '/x', 'HEAD'], + ['push', '/w', 'HEAD'], + ], + ], + ["sh -c 'git push' && zsh script.sh", [['push', '/w', 'HEAD']]], + ['sudo -u me git push origin main', [['push', '/w', 'main']]], + ["env -S 'git push origin main'", [['push', '/w', 'main']]], + ['echo main | xargs -n1 git push origin', [['push', '/w', '*']]], + ['echo 1 | xargs gh pr create --head', [['pr', '/w', '*']]], + // Commands that make a branch from what's checked out, or change what's checked out + [ + 'git switch -c a && git checkout -b b && git branch c', + [ + ['create', '/w', 'a'], + ['create', '/w', 'b'], + ['create', '/w', 'c'], + ], + ], + [ + 'git switch main; git switch -c d origin/main; git checkout x; gh pr checkout 1', + [ + ['move', '/w', ''], + ['move', '/w', ''], + ['move', '/w', ''], + ['move', '/w', ''], + ], + ], + [ + 'git pull; git rebase main; git merge x; git reset --hard y; git reset HEAD~1', + [ + ['move', '/w', ''], + ['move', '/w', ''], + ['move', '/w', ''], + ['move', '/w', ''], + ['move', '/w', ''], + ], + ], + ['git checkout -- a.ts; git reset; git reset -- a.ts; git branch -d x', []], + // What git's settings pick can't be read from the command. + ['git -c push.default=matching push', [['push', '/w', '*']]], + ['git -c remote.origin.push=refs/heads/a push origin', [['push', '/w', '*']]], + ['git -c remote.pushDefault=other push', [['push', '/w', '*']]], + ['git --config-env=branch.a.pushRemote=R push', [['push', '/w', '*']]], + ['git -c core.editor=vi push', [['push', '/w', 'HEAD']]], + [ + 'git push --mirror; git push --branches', + [ + ['push', '/w', '*'], + ['push', '/w', '*'], + ], + ], + ["git push origin 'refs/heads/*:refs/heads/*'", [['push', '/w', 'refs/heads/*']]], + [ + 'gh -R o/r pr create --fill; gh pr new -H a; gh pr create --head=b', + [ + ['pr', '/w', 'HEAD'], + ['pr', '/w', 'a'], + ['pr', '/w', 'b'], + ], + ], + // Nothing that sends code: comments, quotes, here-documents, dry runs, deletions, tags. + ['git push -fn # git push', []], + ['echo "git push"; cat < { + expect(read(command)).toEqual(expected) + }) + + it('takes the remote from an argument over --repo, as git does', () => { + expect(findTargets('git push --repo=origin backup', '/w')[0]?.remote).toBe('backup') + expect(findTargets('git push --repo origin', '/w')[0]?.remote).toBe('origin') + }) + + it('marks a push with no refspec as one git settings decide', () => { + expect(findTargets('git push upstream', '/w')).toEqual([ + { kind: 'push', dir: '/w', sources: ['HEAD'], implicit: true, remote: 'upstream' }, + ]) + expect(findTargets('git push upstream feature', '/w')[0]?.implicit).toBeUndefined() + }) +}) diff --git a/.agents/scripts/lib/push-targets.ts b/.agents/scripts/lib/push-targets.ts new file mode 100644 index 0000000..ed62d15 --- /dev/null +++ b/.agents/scripts/lib/push-targets.ts @@ -0,0 +1,331 @@ +// Finds what a shell command pushes: each `git push`, new pull request and commit it runs, in +// order, with the folder each runs in, and the commands before them that change what's checked +// out. Nothing here runs the command or git. + +import { homedir } from 'node:os' +import { basename, isAbsolute, join, resolve } from 'node:path' +import { readCommands, type ShellItem } from './shell-commands.ts' + +/** + * - `push`, `pr`: what a push or a new pull request sends, as git names it in `sources` (`HEAD`, a + * branch, `refs/tags/v1`); `*` when it can't be told from the command: every branch, a wildcard, + * what git's push settings pick, or arguments `xargs` adds. + * - `commit`: a commit, so a later push from that folder sends the working tree. + * - `create`: a branch made from what's checked out, named in `sources`. + * - `move`: a command that changes what's checked out, such as `git switch` or `git rebase`. + * - `dir`: the folder it runs in, or null when the command doesn't say, as after `cd "$REPO"`. + * - `implicit`: a push with no refspec, so git's settings decide what it sends, to `remote` (null + * when the command names none). + */ +export type PushTarget = { + kind: 'push' | 'pr' | 'commit' | 'create' | 'move' + dir: string | null + sources: string[] + implicit?: boolean + remote?: string | null +} + +/** Shell words before a command that run the command after them. */ +const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{']) + +/** Commands that run the command after them, with the options of each that take a value. */ +const WRAPPERS = new Map([ + ['command', []], + ['builtin', []], + ['exec', ['-a']], + ['nohup', []], + ['time', ['-f', '--format', '-o', '--output']], + ['env', ['-u', '--unset', '-C', '--chdir', '-S', '--split-string']], + ['timeout', ['-s', '--signal', '-k', '--kill-after']], + [ + 'sudo', + ['-u', '--user', '-g', '--group', '-h', '--host', '-p', '--prompt', '-C', '--close-from'], + ], + ['xargs', ['-I', '-L', '-n', '-P', '-d', '-E', '-s', '-a', '--arg-file', '--delimiter']], +]) + +/** Shells whose `-c` runs a command given as a string. */ +const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']) + +/** Git commands that change what's checked out, except in the forms `isMove` lets through. */ +const MOVES = new Set([ + 'switch', + 'checkout', + 'reset', + 'rebase', + 'merge', + 'pull', + 'cherry-pick', + 'revert', + 'am', +]) + +export function findTargets(command: string, cwd: string): PushTarget[] { + const targets: PushTarget[] = [] + walk(readCommands(command), cwd, targets) + return targets +} + +/** Reads the commands in `items` from folder `dir`, and returns the folder they end in. */ +function walk(items: ShellItem[], start: string | null, targets: PushTarget[]): string | null { + const dirs: (string | null)[] = [] + let dir = start + for (const item of items) { + if (item.type === 'enter') dirs.push(dir) + // Back to the folder before the subshell, even when that was unknown. + else if (item.type === 'leave') { + if (dirs.length > 0) dir = dirs.pop() ?? null + } else dir = readCommand(item.words, dir, targets) + } + return dir +} + +/** Reads one simple command, and returns the folder the next one runs in. */ +function readCommand(words: string[], dir: string | null, targets: PushTarget[]): string | null { + const { start, inDir, extraArgs, nested } = skipWrappers(words, dir) + // `env -S '…'`: a command given as a string + if (nested !== undefined) { + walk(readCommands(nested), inDir, targets) + return dir + } + const name = basename(words[start] ?? '') + const rest = words.slice(start + 1) + if (name === 'cd') + return resolveDir(dir, rest.find((word) => !/^(-[LPe@]+|--)$/.test(word)) ?? '~') + if (name === 'pushd') { + // `pushd -n` adds to the stack without changing folder; `+N` and `-N` rotate it. + if (rest.includes('-n')) return dir + const to = rest.find((word) => word !== '--') + return to !== undefined && /^[+-]\d+$/.test(to) ? null : resolveDir(dir, to ?? '~') + } + // `eval` runs its words as a command in this shell, so a `cd` in it stays. + if (name === 'eval') return walk(readCommands(rest.join(' ')), inDir, targets) + if (SHELLS.has(name)) { + const script = shellScript(rest) + if (script !== undefined) walk(readCommands(script), inDir, targets) + } else if (name === 'git') readGit(words, start + 1, inDir, extraArgs, targets) + else if (name === 'gh') readGh(words, start + 1, inDir, extraArgs, targets) + return dir +} + +/** The command string a shell's `-c` runs: `bash -lc 'git push'`. */ +function shellScript(args: string[]): string | undefined { + let runsString = false + for (let i = 0; i < args.length; i++) { + const word = args[i] as string + if (word === '--' || !word.startsWith('-')) return runsString ? word : undefined + if (word === '-o' || word === '--rcfile' || word === '--init-file') i++ + else if (/^-[a-zA-Z]*c[a-zA-Z]*$/.test(word)) runsString = true + } + return undefined +} + +/** + * Skips the shell keywords, variable assignments and wrapper commands (`env`, `sudo`, `xargs`, …) + * before a command, with their options. `env -C` changes the folder for that command only, and + * `env -S` gives the command as one string. A command `xargs` runs gets arguments nobody can see. + */ +function skipWrappers( + words: string[], + dir: string | null, +): { start: number; inDir: string | null; extraArgs: boolean; nested?: string } { + let i = 0 + let inDir = dir + let extraArgs = false + while (i < words.length) { + const word = words[i] as string + if (KEYWORDS.has(word) || /^[A-Za-z_]\w*=/.test(word)) { + i++ + continue + } + const name = basename(word) + const valueOptions = WRAPPERS.get(name) + if (!valueOptions) break + if (name === 'xargs') extraArgs = true + for (i++; i < words.length && (words[i] as string).startsWith('-'); i++) { + const option = words[i] as string + if (option === '--') { + i++ + break + } + // `command -v git` prints where git is; it runs nothing. + if (name === 'command' && /^-[a-zA-Z]*[vV]/.test(option)) { + return { start: words.length, inDir, extraArgs } + } + const [flag = option, value] = option.split(/=(.*)/s) + const operand = value ?? (valueOptions.includes(flag) ? words[++i] : undefined) + if (name === 'env' && (flag === '-S' || flag === '--split-string')) { + return { start: words.length, inDir, extraArgs, nested: operand ?? '' } + } + if (name === 'env' && (flag === '-C' || flag === '--chdir')) { + inDir = resolveDir(inDir, operand ?? '') + } else if (name === 'env' && /^-C./.test(option)) { + inDir = resolveDir(inDir, option.slice(2)) + } + } + // timeout's first operand is how long to wait. + if (name === 'timeout') i++ + } + return { start: i, inDir, extraArgs } +} + +/** The folder `to` names from `from`, or null when it can't tell, as for a variable or `cd -`. */ +function resolveDir(from: string | null, to: string): string | null { + if (to === '~') return homedir() + if (to.startsWith('~/')) return join(homedir(), to.slice(2)) + if (!to || to === '-' || /[$*?[~]/.test(to)) return null + if (isAbsolute(to)) return to + return from === null ? null : resolve(from, to) +} + +function readGit( + words: string[], + start: number, + dir: string | null, + extraArgs: boolean, + targets: PushTarget[], +): void { + let i = start + let inDir = dir + // An inline `push.*`, `remote.*` or `branch.*` setting can change what a push with no refspec + // sends, or where. + let configured = false + for (; i < words.length; i++) { + const word = words[i] as string + if (word === '-C') inDir = resolveDir(inDir, words[++i] ?? '') + else if (/^-C./.test(word)) inDir = resolveDir(inDir, word.slice(2)) + else if (word === '-c' || word === '--config-env' || word.startsWith('--config-env=')) { + const setting = word.startsWith('--config-env=') + ? word.slice('--config-env='.length) + : (words[++i] ?? '') + if (/^(push|remote|branch)\./i.test(setting)) configured = true + } else if (word === '--namespace') i++ + else if (word === '--git-dir' || word === '--work-tree') { + i++ + inDir = null + } else if (word.startsWith('--git-dir=') || word.startsWith('--work-tree=')) inDir = null + else if (!word.startsWith('-')) break + } + const subcommand = words[i] ?? '' + const args = words.slice(i + 1) + if (subcommand === 'commit') targets.push({ kind: 'commit', dir: inDir, sources: [] }) + const created = createdBranch(subcommand, args) + if (created !== undefined) targets.push({ kind: 'create', dir: inDir, sources: [created] }) + else if (MOVES.has(subcommand) && isMove(subcommand, args)) { + targets.push({ kind: 'move', dir: inDir, sources: [] }) + } + if (subcommand !== 'push') return + const push = readPush(args, configured || extraArgs) + if (push) targets.push({ ...push, dir: inDir }) +} + +/** The branch `git switch -c`, `git checkout -b` or `git branch` makes from what's checked out. */ +function createdBranch(subcommand: string, args: string[]): string | undefined { + const operands = args.filter((word) => !word.startsWith('-')) + if (subcommand === 'branch') { + // `git branch name` alone; with a start point, or any option, it isn't what's checked out + return args.length === 1 && operands.length === 1 ? operands[0] : undefined + } + const flags = + subcommand === 'switch' ? ['-c', '-C', '--create', '--force-create'] : ['-b', '-B'] + if (!['switch', 'checkout'].includes(subcommand)) return undefined + const at = args.findIndex((word) => flags.includes(word)) + if (at === -1) return undefined + const name = args[at + 1] + // A start point after the name means the new branch, and HEAD, move there. + const after = args.slice(at + 2).filter((word) => !word.startsWith('-')) + return name !== undefined && after.length === 0 ? name : undefined +} + +/** Whether a git command that can change what's checked out does here. */ +function isMove(subcommand: string, args: string[]): boolean { + const dashes = args.indexOf('--') + const before = dashes === -1 ? args : args.slice(0, dashes) + const operands = before.filter((word) => !word.startsWith('-')) + // `git checkout -- file` and `git reset -- file` restore files and keep HEAD. + if (subcommand === 'checkout' && dashes !== -1 && operands.length === 0) return false + if (subcommand === 'reset') return operands.some((word) => word !== 'HEAD') + return true +} + +function readPush(args: string[], unclear: boolean): Omit | undefined { + let remote: string | null = null + // A remote named as an argument wins over `--repo`, as in git. + let repoOption: string | null = null + let tags = false + let every = false + const refspecs: string[] = [] + for (let i = 0; i < args.length; i++) { + const word = args[i] as string + // A dry run sends nothing, and a deletion sends no code. + if (['-n', '--dry-run', '-d', '--delete'].includes(word)) return undefined + if (word === '--tags') tags = true + else if (['--all', '--branches', '--mirror'].includes(word)) every = true + else if (word === '--repo') repoOption = args[++i] ?? null + else if (word.startsWith('--repo=')) repoOption = word.slice('--repo='.length) + else if (['-o', '--push-option', '--receive-pack', '--exec'].includes(word)) i++ + else if (/^-[^-]*[nd]/.test(word) && !word.startsWith('-o')) return undefined + else if (word.startsWith('-')) continue + else if (remote === null) remote = word + else refspecs.push(word) + } + remote ??= repoOption + if (every || (unclear && refspecs.length === 0)) return { kind: 'push', sources: ['*'] } + if (refspecs.length === 0) { + // With --tags and no refspec, it pushes tags alone, which hold no new code. + if (tags) return undefined + return { kind: 'push', sources: ['HEAD'], implicit: true, remote } + } + // `:` alone pushes every branch both sides have, like --all. + if (refspecs.some((spec) => spec === ':' || spec === '+:')) { + return { kind: 'push', sources: ['*'] } + } + // `+` forces, `:` deletes, and `tag ` names a tag. + const sources: string[] = [] + for (let k = 0; k < refspecs.length; k++) { + const spec = refspecs[k] as string + const tag = refspecs[k + 1] + if (spec === 'tag' && tag !== undefined) { + sources.push(`refs/tags/${tag}`) + k++ + continue + } + const forced = spec.replace(/^\+/, '') + if (!forced.startsWith(':')) sources.push(forced.split(':')[0] as string) + } + if (sources.length === 0) return undefined + // `xargs` may add more refspecs than the command shows. + return { kind: 'push', sources: unclear ? ['*'] : sources } +} + +/** + * `gh pr create`, or `gh pr new`, opens a pull request for the current branch, or for `--head`. + * `gh pr checkout` changes what's checked out. + */ +function readGh( + words: string[], + start: number, + dir: string | null, + extraArgs: boolean, + targets: PushTarget[], +): void { + let at = start + // Global options before the subcommand: `gh -R owner/repo pr create`. + while (/^(-R|--repo)$/.test(words[at] ?? '')) at += 2 + while ((words[at] ?? '').startsWith('--repo=')) at++ + if (words[at] !== 'pr') return + if (words[at + 1] === 'checkout') { + targets.push({ kind: 'move', dir, sources: [] }) + return + } + if (!['create', 'new'].includes(words[at + 1] ?? '')) return + let head = 'HEAD' + for (let i = at + 2; i < words.length; i++) { + const word = words[i] as string + if (word === '-H' || word === '--head') head = words[++i] ?? 'HEAD' + else if (word.startsWith('--head=')) head = word.slice('--head='.length) + } + // A head in someone's fork, `owner:branch`, is still that branch. + const source = extraArgs ? '*' : head.replace(/^[^:]*:/, '') + targets.push({ kind: 'pr', dir, sources: [source] }) +} diff --git a/.agents/scripts/lib/shell-commands.ts b/.agents/scripts/lib/shell-commands.ts new file mode 100644 index 0000000..6130836 --- /dev/null +++ b/.agents/scripts/lib/shell-commands.ts @@ -0,0 +1,203 @@ +// Reads a shell command into the simple commands it runs, without running any of it. The push +// check uses it to find the `git push` and `gh pr create` calls in an agent's shell command. + +/** A simple command's words, or the edges of a subshell, `$(...)` or backtick command. */ +export type ShellItem = { type: 'command'; words: string[] } | { type: 'enter' } | { type: 'leave' } + +type Level = { word: string; started: boolean; skip: boolean; words: string[] } + +/** What the reader is inside of: a command (the top level, `$(...)` or `(...)`), a backtick + * command, or single or double quotes. */ +type Context = 'command' | 'backtick' | 'single' | 'double' + +function newLevel(): Level { + return { word: '', started: false, skip: false, words: [] } +} + +/** + * The simple commands a shell command runs, in order. Quotes come off each word. `$(...)`, `(...)` + * and backticks hold commands of their own, between an `enter` and a `leave`, since a `cd` inside + * them stays there, and leave `$` in the word around them. Here-documents, redirections and + * comments are left out. Shell it doesn't follow only makes odd words, which never look like a + * push. + */ +export function readCommands(source: string): ShellItem[] { + const items: ShellItem[] = [] + const levels: Level[] = [newLevel()] + const context: Context[] = ['command'] + const hereDocuments: { name: string; tabs: boolean }[] = [] + let joined = false + + function level(): Level { + return levels[levels.length - 1] as Level + } + function inside(): Context { + return context[context.length - 1] as Context + } + function add(text: string): void { + level().word += text + level().started = true + } + function endWord(): void { + const current = level() + if (current.started) { + if (current.skip) current.skip = false + else current.words.push(current.word) + } + current.word = '' + current.started = false + } + function endCommand(): void { + endWord() + if (level().words.length > 0) items.push({ type: 'command', words: level().words }) + levels[levels.length - 1] = newLevel() + } + function enter(kind: Context): void { + items.push({ type: 'enter' }) + context.push(kind) + levels.push(newLevel()) + } + function leave(): void { + endCommand() + items.push({ type: 'leave' }) + context.pop() + levels.pop() + } + + for (const rawLine of source.split('\n')) { + // A here-document runs from the line after its `<<` to its delimiter. + const [document] = hereDocuments + if (document) { + const line = document.tabs ? rawLine.replace(/^\t+/, '') : rawLine + if (line === document.name) hereDocuments.shift() + continue + } + const line = rawLine + for (let i = 0; i < line.length; i++) { + const kind = inside() + const c = line[i] as string + const next = line[i + 1] + if (kind === 'single') { + if (c === "'") context.pop() + else add(c) + continue + } + if (kind === 'double') { + if (c === '\\' && next !== undefined && '$`"\\'.includes(next)) { + add(next) + i++ + } else if (c === '"') context.pop() + else if (c === '$' && next === '(') { + add('$') + i++ + enter('command') + } else if (c === '`') { + add('$') + enter('backtick') + } else add(c) + continue + } + if (c === '\\') { + if (next !== undefined) { + add(next) + i++ + } else joined = true + } else if (c === "'") { + context.push('single') + level().started = true + } else if (c === '"') { + context.push('double') + level().started = true + } else if (c === '`') { + if (kind === 'backtick') leave() + else { + add('$') + enter('backtick') + } + } else if (c === '$') { + add('$') + if (next === '(') { + i++ + enter('command') + } + } else if (c === '(') { + endCommand() + enter('command') + } else if (c === ')') { + if (context.length > 1 && kind === 'command') leave() + else endCommand() + } else if (c === ' ' || c === '\t') { + endWord() + } else if (c === '#') { + if (level().started) add('#') + else break + } else if (c === '<' && next === '<' && line[i + 2] !== '<') { + const { name, tabs, end } = readHereDocument(line, i + 2) + if (name) hereDocuments.push({ name, tabs }) + i = end + } else if (c === '<' || c === '>' || (c === '&' && next === '>')) { + // A file descriptor before the operator belongs to it, and the next word is where + // it goes. + if (/^[0-9]+$/.test(level().word)) { + level().word = '' + level().started = false + } else endWord() + while (i + 1 < line.length && '<>&|'.includes(line[i + 1] as string)) i++ + level().skip = true + } else if (c === ';' || c === '&' || c === '|') { + endCommand() + } else { + add(c) + } + } + const kind = inside() + if (kind === 'single' || kind === 'double') add('\n') + else if (joined) joined = false + else endCommand() + } + while (context.length > 1) { + const kind = inside() + if (kind === 'single' || kind === 'double') context.pop() + else leave() + } + endCommand() + return items +} + +/** The delimiter of a here-document whose `<<` ends just before `start`. */ +function readHereDocument( + line: string, + start: number, +): { name: string; tabs: boolean; end: number } { + let i = start + let tabs = false + let name = '' + if (line[i] === '-') { + tabs = true + i++ + } + while (line[i] === ' ' || line[i] === '\t') i++ + while (i < line.length) { + const c = line[i] as string + if (c === "'" || c === '"') { + const close = line.indexOf(c, i + 1) + if (close === -1) { + name += line.slice(i + 1) + i = line.length + break + } + name += line.slice(i + 1, close) + i = close + 1 + continue + } + if (c === '\\') { + name += line[i + 1] ?? '' + i += 2 + continue + } + if (' \t;&|()<>'.includes(c)) break + name += c + i++ + } + return { name, tabs, end: i - 1 } +} diff --git a/.agents/scripts/lib/test-repo.ts b/.agents/scripts/lib/test-repo.ts index a3f0d36..06da056 100644 --- a/.agents/scripts/lib/test-repo.ts +++ b/.agents/scripts/lib/test-repo.ts @@ -6,6 +6,8 @@ import { cpSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } f import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { CHECKOUT_ROOT, cleanGitEnv } from './git.ts' +import { writeVerified } from './state.ts' +import { codeFingerprint, snapshot } from './tree.ts' export const REPO_ROOT = CHECKOUT_ROOT @@ -55,11 +57,16 @@ export type TempRepo = { write: (path: string, content: string) => void /** Copies files or folders from the real checkout into the same paths in this repo. */ copyFromCheckout: (...paths: string[]) => void + /** Adds a bare `origin` outside the repo, pushes `main` to it, and returns its path. */ + addOrigin: () => string + /** Makes and switches to `branch`, then commits `path` holding `content` there. */ + commitOnBranch: (branch: string, path: string, content?: string) => void cleanup: () => void } export function createTempRepo(): TempRepo { const dir = mkdtempSync(join(tmpdir(), 'agent tools-')) + const extraDirs: string[] = [] const run: TempRepo['run'] = (command, args, options = {}) => spawnSync(command, args, { @@ -83,8 +90,27 @@ export function createTempRepo(): TempRepo { cpSync(join(REPO_ROOT, path), join(dir, path), { recursive: true }) } }, + addOrigin() { + const origin = mkdtempSync(join(tmpdir(), 'agent tools origin-')) + extraDirs.push(origin) + for (const args of [ + ['init', '--quiet', '--bare', '--initial-branch', 'main', origin], + ['remote', 'add', 'origin', origin], + ['push', '--quiet', 'origin', 'main'], + ]) { + const result = repo.git(args) + if (result.status !== 0) throw new Error(`git ${args[0]} failed: ${result.stderr}`) + } + return origin + }, + commitOnBranch(branch, path, content = 'export const x = 1\n') { + repo.git(['switch', '--quiet', '-c', branch]) + repo.write(path, content) + repo.git(['add', path]) + repo.git(['commit', '--quiet', '-m', `add ${path}`]) + }, cleanup() { - rmSync(dir, { recursive: true, force: true }) + for (const path of [dir, ...extraDirs]) rmSync(path, { recursive: true, force: true }) }, } @@ -104,3 +130,8 @@ export function installLefthook(repo: TempRepo): void { const result = repo.run(process.execPath, [lefthook, 'install', '--reset-hooks-path']) if (result.status !== 0) throw new Error(`lefthook install failed: ${result.stderr}`) } + +/** Records that `npm run verify` passed on the working tree as it is now, as a pass would. */ +export function markVerified(dir: string): void { + writeVerified(dir, { fingerprint: codeFingerprint(snapshot(dir)), head: 'x', at: 'now' }) +} diff --git a/.agents/scripts/lib/tree.test.ts b/.agents/scripts/lib/tree.test.ts index 0852438..0540de3 100644 --- a/.agents/scripts/lib/tree.test.ts +++ b/.agents/scripts/lib/tree.test.ts @@ -1,4 +1,4 @@ -import { rmSync, utimesSync } from 'node:fs' +import { rmSync, symlinkSync, utimesSync } from 'node:fs' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { createTempRepo, type TempRepo } from './test-repo.ts' @@ -8,7 +8,9 @@ import { changedSince, classify, codeFingerprint, + commitChanges, snapshot, + snapshotCommit, } from './tree.ts' let repo: TempRepo @@ -73,6 +75,45 @@ describe('snapshot', () => { }) }) +describe('snapshotCommit', () => { + it('describes a commit exactly as the identical working tree', () => { + repo.write('run.sh', '#!/bin/sh\n') + repo.run('chmod', ['+x', 'run.sh']) + symlinkSync('src/a.ts', join(repo.dir, 'link')) + repo.write('src/naïve name.ts', 'export const n = 1\n') + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'more kinds of file']) + expect(snapshotCommit(repo.dir, 'HEAD')).toEqual(snapshot(repo.dir)) + expect(snapshot(repo.dir)['run.sh']).toMatch(/^x:/) + expect(snapshot(repo.dir).link).toMatch(/^link:/) + }) + + it('differs from a working tree that holds more, or other content', () => { + const committed = codeFingerprint(snapshotCommit(repo.dir, 'HEAD')) + expect(codeFingerprint(snapshot(repo.dir))).toBe(committed) + repo.write('src/new.ts', 'new\n') + expect(codeFingerprint(snapshot(repo.dir))).not.toBe(committed) + rmSync(join(repo.dir, 'src/new.ts')) + repo.write('src/a.ts', 'export const a = 2\n') + expect(codeFingerprint(snapshot(repo.dir))).not.toBe(committed) + }) +}) + +describe('commitChanges', () => { + it('lists what a commit changes since a base, deletions marked', () => { + const base = repo.git(['rev-parse', 'HEAD']).stdout.trim() + repo.write('src/b.ts', 'b\n') + repo.git(['rm', '--quiet', 'README.md']) + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'c']) + repo.write('src/uncommitted.ts', 'not in the commit\n') + expect(commitChanges(repo.dir, base, 'HEAD')).toEqual([ + { path: 'README.md', deleted: true }, + { path: 'src/b.ts', deleted: false }, + ]) + }) +}) + describe('codeFingerprint', () => { it('ignores edits to docs and files only CI reads, and nothing else', () => { const before = codeFingerprint(snapshot(repo.dir)) diff --git a/.agents/scripts/lib/tree.ts b/.agents/scripts/lib/tree.ts index 51a84c9..76f6ad5 100644 --- a/.agents/scripts/lib/tree.ts +++ b/.agents/scripts/lib/tree.ts @@ -1,12 +1,15 @@ -// Fingerprints of the working tree, by file content. Hashing content (not mtimes) catches edits -// made in the same second, and hashing in-process writes nothing to git's object store. +// Fingerprints of the working tree, or of a commit, by file content. Hashing content (not mtimes) +// catches edits made in the same second, and hashing in-process writes nothing to git's object +// store. Files are hashed the way git hashes a blob, so a commit can be described from `git +// ls-tree` without reading its files, and a commit that holds exactly a tree verify passed has the +// same fingerprint. import { createHash } from 'node:crypto' import { existsSync, lstatSync, readFileSync, readlinkSync } from 'node:fs' import { join } from 'node:path' import { git } from './git.ts' -/** Path → content hash for every tracked and untracked, non-ignored file. */ +/** Path → mode and content hash for every tracked and untracked, non-ignored file. */ export type Snapshot = Record export function snapshot(root: string): Snapshot { @@ -23,17 +26,39 @@ export function snapshot(root: string): Snapshot { } function hashPath(path: string): string | undefined { - let stat try { - stat = lstatSync(path) + const stat = lstatSync(path) + if (stat.isSymbolicLink()) return `link:${blobId(Buffer.from(readlinkSync(path)))}` + if (stat.isDirectory()) return 'dir' // a nested repository, listed but not entered + return `${stat.mode & 0o111 ? 'x' : '-'}:${blobId(readFileSync(path))}` } catch { + // Gone, or went away while being read. return undefined } - const hash = createHash('sha256') - if (stat.isSymbolicLink()) hash.update(`link:${readlinkSync(path)}`) - else if (stat.isDirectory()) hash.update('dir') // a nested repository, listed but not entered - else hash.update(`${stat.mode & 0o111 ? 'x' : '-'}:`).update(readFileSync(path)) - return hash.digest('hex') +} + +/** The id git gives a blob with this content. */ +function blobId(content: Buffer): string { + return createHash('sha1').update(`blob ${content.length}\0`).update(content).digest('hex') +} + +/** + * A commit's files, described the way `snapshot` describes the working tree, from git's own blob + * ids: a commit that holds exactly the working tree gets the same snapshot. + */ +export function snapshotCommit(root: string, commit: string): Snapshot { + const listed = git(root, ['ls-tree', '-r', '-z', commit]) + if (!listed.ok) throw new Error(`git ls-tree failed: ${listed.stderr.trim()}`) + const files: Snapshot = {} + for (const entry of listed.stdout.split('\0')) { + const match = /^(\d+) \w+ ([0-9a-f]+)\t(.*)$/s.exec(entry) + if (!match) continue + const [, mode = '', id = '', path = ''] = match + if (mode === '160000') files[path] = 'dir' + else if (mode === '120000') files[path] = `link:${id}` + else files[path] = `${mode === '100755' ? 'x' : '-'}:${id}` + } + return files } /** @@ -90,7 +115,7 @@ export function codeFingerprint(files: Snapshot): string { return hash.digest('hex') } -/** Changed files local checks read: what verify and the turn gate both act on. */ +/** Changed files local checks read: what verify and the push check both act on. */ export function changedCodePaths(before: Snapshot, after: Snapshot): string[] { return changedPaths(before, after).filter( (path) => @@ -109,8 +134,32 @@ export function changedPaths(before: Snapshot, after: Snapshot): string[] { * deleted or renamed, since the agent docs may name it. */ export function needsChecks(root: string, path: string): boolean { + return changeNeedsChecks(path, !existsSync(join(root, path))) +} + +/** `needsChecks` for a change whose deletion is already known, such as one in a commit. */ +export function changeNeedsChecks(path: string, deleted: boolean): boolean { const kind = classify(path) - return kind === 'code' || (kind === 'docs' && !existsSync(join(root, path))) + return kind === 'code' || (kind === 'docs' && deleted) +} + +/** + * Files a commit changes since `base`, and whether each was deleted. Renames count as a deletion + * and an addition. + */ +export function commitChanges( + root: string, + base: string, + commit: string, +): { path: string; deleted: boolean }[] { + const diff = git(root, ['diff', '--name-status', '--no-renames', '-z', base, commit]) + if (!diff.ok) throw new Error(`git diff failed: ${diff.stderr.trim()}`) + const fields = diff.stdout.split('\0') + const changes: { path: string; deleted: boolean }[] = [] + for (let i = 0; i + 1 < fields.length; i += 2) { + changes.push({ path: fields[i + 1] as string, deleted: fields[i] === 'D' }) + } + return changes } /** Files that differ from `base`: committed, staged, unstaged and untracked. */ diff --git a/.agents/scripts/lib/turn-gate.test.ts b/.agents/scripts/lib/turn-gate.test.ts deleted file mode 100644 index e973902..0000000 --- a/.agents/scripts/lib/turn-gate.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { existsSync, rmSync, utimesSync } from 'node:fs' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { writeVerified } from './state.ts' -import { createTempRepo, type TempRepo } from './test-repo.ts' -import { codeFingerprint, snapshot } from './tree.ts' -import { endTurn, startTurn } from './turn-gate.ts' - -let repo: TempRepo -const session = 'session-1' - -const start = () => startTurn({ root: repo.dir, sessionId: session }) -const end = () => endTurn({ root: repo.dir, sessionId: session }) -const markVerified = () => - writeVerified(repo.dir, { - fingerprint: codeFingerprint(snapshot(repo.dir)), - head: 'x', - at: 'now', - }) - -beforeEach(() => { - repo = createTempRepo() - repo.write('.gitignore', '.tmp/\n') - repo.write('src/a.ts', 'export const a = 1\n') - repo.write('README.md', 'readme\n') - repo.git(['add', '.']) - repo.git(['commit', '--quiet', '-m', 'initial']) -}) - -afterEach(() => repo.cleanup()) - -describe('turns that pass', () => { - it('lets a turn that changed nothing end', () => { - start() - expect(end()).toEqual({ decision: 'allow' }) - }) - - it('lets a docs-only turn end without a reminder', () => { - start() - repo.write('README.md', 'changed\n') - repo.write('docs/new.md', 'new\n') - expect(end()).toEqual({ decision: 'allow' }) - }) - - it('lets a turn that undid its edits end', () => { - start() - repo.write('src/a.ts', 'export const a = 2\n') - repo.write('src/a.ts', 'export const a = 1\n') - repo.write('src/tmp.ts', 'scratch\n') - rmSync(join(repo.dir, 'src/tmp.ts')) - expect(end()).toEqual({ decision: 'allow' }) - }) - - it('lets a turn end when verify passed on the exact tree', () => { - start() - repo.write('src/a.ts', 'export const a = 2\n') - markVerified() - expect(end()).toEqual({ decision: 'allow' }) - }) - - it('keeps the pass when a deletion verify saw is then staged', () => { - repo.git(['switch', '--quiet', '-c', 'feature']) - start() - rmSync(join(repo.dir, 'src/a.ts')) - markVerified() - repo.git(['add', '--all']) - expect(end()).toEqual({ decision: 'allow' }) - }) - - it('keeps the pass when only docs changed after verify', () => { - start() - repo.write('src/a.ts', 'export const a = 2\n') - markVerified() - repo.write('README.md', 'changed after verify\n') - expect(end()).toEqual({ decision: 'allow' }) - }) - - it('notes a change only CI checks, without sending the agent back', () => { - start() - repo.write('renovate.json', '{}\n') - const verdict = end() - expect(verdict.decision).toBe('allow') - expect(verdict).toHaveProperty('note', expect.stringContaining('only CI checks')) - }) -}) - -describe('turns that changed code without verifying', () => { - it('sends the agent back once, naming the files and what to do', () => { - start() - repo.write('src/a.ts', 'export const a = 2\n') - const verdict = end() - expect(verdict.decision).toBe('block') - expect(verdict).toHaveProperty('reason', expect.stringContaining('src/a.ts')) - expect(verdict).toHaveProperty('reason', expect.stringContaining('npm run verify')) - }) - - it('lets the agent stop the second time, with a note for the person', () => { - start() - repo.write('src/a.ts', 'export const a = 2\n') - expect(end().decision).toBe('block') - const second = end() - expect(second.decision).toBe('allow') - expect(second).toHaveProperty('note', expect.stringContaining('src/a.ts')) - }) - - it('sends the agent back again in the next turn', () => { - start() - repo.write('src/a.ts', 'export const a = 2\n') - end() - end() - start() - repo.write('src/a.ts', 'export const a = 3\n') - expect(end().decision).toBe('block') - }) - - it('catches an edit that keeps the file size', () => { - start() - repo.write('src/a.ts', 'export const a = 9\n') - expect(end().decision).toBe('block') - }) - - it('catches a deleted doc, which the agent docs may name', () => { - start() - rmSync(join(repo.dir, 'README.md')) - expect(end().decision).toBe('block') - }) - - it('catches a new untracked file', () => { - start() - repo.write('src/new.ts', 'new\n') - expect(end().decision).toBe('block') - }) - - it('catches code changed after verify passed', () => { - start() - repo.write('src/a.ts', 'export const a = 2\n') - markVerified() - repo.write('src/a.ts', 'export const a = 3\n') - expect(end().decision).toBe('block') - }) - - it('checks each session against the tree it saw at its own turn start', () => { - repo.write('src/a.ts', 'export const a = 2\n') - start() - repo.write('src/a.ts', 'export const a = 3\n') - startTurn({ root: repo.dir, sessionId: 'other' }) - repo.write('src/a.ts', 'export const a = 2\n') - // Back at the tree this session started from; the other session started from a = 3. - expect(end()).toEqual({ decision: 'allow' }) - expect(endTurn({ root: repo.dir, sessionId: 'other' }).decision).toBe('block') - }) -}) - -describe('a branch', () => { - beforeEach(() => repo.git(['switch', '--quiet', '-c', 'feature'])) - - it('lets the turn end when the code is back to what main has', () => { - repo.write('src/a.ts', 'export const a = 2\n') - repo.git(['commit', '--quiet', '-am', 'change']) - start() - repo.git(['revert', '--no-edit', '--quiet', 'HEAD']) - repo.write('docs/note.md', 'note\n') - expect(end()).toEqual({ decision: 'allow' }) - }) - - it('still sends the agent back when the branch differs from main', () => { - start() - repo.write('src/a.ts', 'export const a = 2\n') - expect(end().decision).toBe('block') - }) -}) - -it('removes turn records older than a week when a turn starts', () => { - startTurn({ root: repo.dir, sessionId: 'old' }) - const old = join(repo.dir, '.tmp/agents/turns/old.json') - const weekAgo = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000) - utimesSync(old, weekAgo, weekAgo) - start() - expect(existsSync(old)).toBe(false) - expect(existsSync(join(repo.dir, `.tmp/agents/turns/${session}.json`))).toBe(true) -}) - -it('allows the turn, and says why, without a turn-start record', () => { - const verdict = end() - expect(verdict.decision).toBe('allow') - expect(verdict).toHaveProperty('note', expect.stringContaining('no turn-start record')) -}) diff --git a/.agents/scripts/lib/turn-gate.ts b/.agents/scripts/lib/turn-gate.ts deleted file mode 100644 index 25db931..0000000 --- a/.agents/scripts/lib/turn-gate.ts +++ /dev/null @@ -1,112 +0,0 @@ -// The end-of-turn gate. At turn start it snapshots the tree; at turn end it sends the agent back -// once if the turn changed code that `npm run verify` has not passed. "Once" lets an agent stop on -// purpose and say what is unfinished. - -import { readdirSync, rmSync, statSync } from 'node:fs' -import { join } from 'node:path' -import { branchBase } from './git.ts' -import { readJson, readVerified, stateDir, writeJson } from './state.ts' -import { - changedCodePaths, - changedPaths, - changedSince, - classify, - codeFingerprint, - needsChecks, - type Snapshot, - snapshot, -} from './tree.ts' - -type TurnState = { start: Snapshot; sentBack: boolean } - -export type Verdict = { decision: 'allow'; note?: string } | { decision: 'block'; reason: string } - -const MAX_LISTED = 5 -// Turn records older than this belong to sessions that are gone. -const STALE_TURN_MS = 7 * 24 * 60 * 60 * 1000 - -function turnPath(root: string, sessionId: string): string { - return join(stateDir(root), 'turns', `${sessionId.replace(/[^\w.-]/g, '_')}.json`) -} - -function list(paths: string[]): string { - const shown = paths.slice(0, MAX_LISTED).join(', ') - return paths.length > MAX_LISTED ? `${shown} and ${paths.length - MAX_LISTED} more` : shown -} - -export function startTurn({ root, sessionId }: { root: string; sessionId: string }): void { - pruneStaleTurns(root) - writeJson(turnPath(root, sessionId), { start: snapshot(root), sentBack: false }) -} - -function pruneStaleTurns(root: string, now = Date.now()): void { - const dir = join(stateDir(root), 'turns') - let names: string[] - try { - names = readdirSync(dir) - } catch { - return - } - for (const name of names) { - const path = join(dir, name) - if (now - statSync(path).mtimeMs > STALE_TURN_MS) rmSync(path, { force: true }) - } -} - -export function endTurn({ - root, - sessionId, - base = branchBase(root), -}: { - root: string - sessionId: string - /** Where the branch left the default branch; undefined when there is none. */ - base?: string -}): Verdict { - const path = turnPath(root, sessionId) - const state = readJson(path) - if (!state?.start) { - return { - decision: 'allow', - note: 'no turn-start record for this session, so the end-of-turn check was skipped', - } - } - - const now = snapshot(root) - const changed = changedPaths(state.start, now) - const code = changedCodePaths(state.start, now) - const ciOnly = changed.filter((file) => classify(file) === 'unchecked') - const ciNote = ciOnly.length - ? `only CI checks ${list(ciOnly)}; say so in your report` - : undefined - - if (code.length === 0) return { decision: 'allow', note: ciNote } - const verified = readVerified(root) - if (verified && verified.fingerprint === codeFingerprint(now)) { - return { decision: 'allow', note: ciNote } - } - // The code is back to what the default branch has (an undo, a stash, a branch switch), which - // CI already checked. verify says "only docs changed" here and records nothing, so asking for - // it would send the agent back for nothing. - if (base && !changedSince(root, base).some((file) => needsChecks(root, file))) { - return { decision: 'allow', note: ciNote } - } - - // Only this guard's own record counts: stop_hook_active or loop_count can also be set by - // another hook sending the agent back, which would skip this one. - if (state.sentBack) { - return { - decision: 'allow', - note: `the turn ended with changes npm run verify has not passed: ${list(code)}`, - } - } - - writeJson(path, { ...state, sentBack: true }) - return { - decision: 'block', - reason: - `You changed code this turn that \`npm run verify\` has not passed: ${list(code)}. ` + - 'Run `npm run verify` and fix what fails. If you are stopping on purpose, say what ' + - 'is unfinished and what you did not verify; you will not be sent back again this turn.', - } -} diff --git a/.agents/scripts/verify.ts b/.agents/scripts/verify.ts index 762d236..8d520b8 100644 --- a/.agents/scripts/verify.ts +++ b/.agents/scripts/verify.ts @@ -1,5 +1,5 @@ // `npm run verify`: every check CI runs on a pull request, in about fifteen seconds. -// Records a fingerprint of the tree only when everything passed; the end-of-turn gate reads it. +// Records a fingerprint of the tree only when everything passed; the push check reads it. import { CHECKOUT_ROOT, branchBase, defaultBranchRef } from './lib/git.ts' import { clearVerified } from './lib/state.ts' diff --git a/.agents/skills/verify/SKILL.md b/.agents/skills/verify/SKILL.md index c2c01bd..923cf95 100644 --- a/.agents/skills/verify/SKILL.md +++ b/.agents/skills/verify/SKILL.md @@ -13,6 +13,8 @@ npm run verify It runs every check CI runs (about ten seconds) and records the pass. Fix every failure; never weaken a check to pass it. Done when it prints `Verified.`, or says only docs changed and there is nothing to check. +Your `git push` and `gh pr create` are stopped until verify has passed on exactly the commit being pushed, so commit what verify saw and nothing more, or commit first and verify the clean tree. + ## 2. Prove the change itself The checks prove nothing broke. Now prove the change does what was asked, with the proof its kind needs: diff --git a/.claude/settings.json b/.claude/settings.json index fbc275c..9f1be50 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,22 +1,12 @@ { "hooks": { - "UserPromptSubmit": [ + "PreToolUse": [ { + "matcher": "Bash", "hooks": [ { "type": "command", - "command": "root=\"$CLAUDE_PROJECT_DIR\"; [ -n \"$root\" ] || root=$(unset $(git rev-parse --local-env-vars 2>/dev/null); git rev-parse --show-toplevel 2>/dev/null) || root=.; f=\"$root/.agents/scripts/guard.ts\"; if [ -f \"$f\" ]; then node \"$f\" turn-start; else echo '{\"systemMessage\":\"agent-guard: this checkout has no .agents/scripts/guard.ts, so turn-start was skipped\"}'; fi", - "timeout": 30 - } - ] - } - ], - "Stop": [ - { - "hooks": [ - { - "type": "command", - "command": "root=\"$CLAUDE_PROJECT_DIR\"; [ -n \"$root\" ] || root=$(unset $(git rev-parse --local-env-vars 2>/dev/null); git rev-parse --show-toplevel 2>/dev/null) || root=.; f=\"$root/.agents/scripts/guard.ts\"; if [ -f \"$f\" ]; then node \"$f\" turn-end; else echo '{\"systemMessage\":\"agent-guard: this checkout has no .agents/scripts/guard.ts, so turn-end was skipped\"}'; fi", + "command": "p=$(cat); case $p in *'\"command\"'*push* | *'\"command\"'*pr[[:space:]\\\\]*create* | *'\"command\"'*pr[[:space:]\\\\]*new*) ;; *) exit 0 ;; esac; root=\"$CLAUDE_PROJECT_DIR\"; [ -n \"$root\" ] || root=$(unset $(git rev-parse --local-env-vars 2>/dev/null); git rev-parse --show-toplevel 2>/dev/null) || exit 0; f=\"$root/.agents/scripts/guard.ts\"; [ -f \"$f\" ] || exit 0; printf '%s' \"$p\" | node \"$f\" tool-start", "timeout": 30 } ] diff --git a/.codex/hooks.json b/.codex/hooks.json index 6386ac3..aa7b546 100644 --- a/.codex/hooks.json +++ b/.codex/hooks.json @@ -1,22 +1,13 @@ { + "description": "Push check: stops an agent's `git push` or `gh pr create` when what it sends hasn't passed `npm run verify`. See docs/agents.md.", "hooks": { - "UserPromptSubmit": [ + "PreToolUse": [ { + "matcher": "Bash", "hooks": [ { "type": "command", - "command": "unset $(git rev-parse --local-env-vars 2>/dev/null); root=$(git rev-parse --show-toplevel 2>/dev/null) || root=.; f=\"$root/.agents/scripts/guard.ts\"; if [ -f \"$f\" ]; then node \"$f\" turn-start; else echo '{\"systemMessage\":\"agent-guard: this checkout has no .agents/scripts/guard.ts, so turn-start was skipped\"}'; fi", - "timeout": 30 - } - ] - } - ], - "Stop": [ - { - "hooks": [ - { - "type": "command", - "command": "unset $(git rev-parse --local-env-vars 2>/dev/null); root=$(git rev-parse --show-toplevel 2>/dev/null) || root=.; f=\"$root/.agents/scripts/guard.ts\"; if [ -f \"$f\" ]; then node \"$f\" turn-end; else echo '{\"systemMessage\":\"agent-guard: this checkout has no .agents/scripts/guard.ts, so turn-end was skipped\"}'; fi", + "command": "p=$(cat); case $p in *'\"command\"'*push* | *'\"command\"'*pr[[:space:]\\\\]*create* | *'\"command\"'*pr[[:space:]\\\\]*new*) ;; *) exit 0 ;; esac; unset $(git rev-parse --local-env-vars 2>/dev/null); root=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; f=\"$root/.agents/scripts/guard.ts\"; [ -f \"$f\" ] || exit 0; printf '%s' \"$p\" | node \"$f\" tool-start", "timeout": 30 } ] diff --git a/AGENTS.md b/AGENTS.md index e97b230..8062a54 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. -- When a turn changes code that `npm run verify` has not passed, the end-of-turn hook (Claude Code, Codex, Cursor) sends you back once. Run verify, or stop on purpose and say what is unverified. +- 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. - 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 f12d781..36129a5 100644 --- a/CODEBASE.md +++ b/CODEBASE.md @@ -34,10 +34,10 @@ come from `@todoist/cli-core`. │ │ # review-changes) │ ├─ checks/ # Review checks reviewers and Doistbot apply (AGENTS.md links them) │ └─ scripts/ # Agent tooling (verify, git hook branch guard, review -│ # worktree, end-of-turn gate) and its tests. Not +│ # worktree, push check) and its tests. Not │ # published, unlike scripts/ ├─ .claude/skills/ # Links to .agents/skills/, where Claude Code finds them -├─ .claude/settings.json # End-of-turn gate hooks (.codex/hooks.json for Codex) +├─ .claude/settings.json # Push check hook (.codex/hooks.json for Codex) ├─ 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 8092eb1..35b071e 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -9,7 +9,7 @@ This repository is set up so coding agents prove their work before they call it 3. **`AGENTS.md`** tells agents what done means. Claude Code reads it through `CLAUDE.md`; Codex and other agents read it directly. 4. **Skills** in `.agents/skills/` give step-by-step procedures for recurring work. They load only when a task needs them. 5. **Review**: fresh reviewers and Doistbot check a finished change against the checks in `.agents/checks/`. -6. **The end-of-turn gate** sends an agent back once when its turn changed code that `npm run verify` has not passed. +6. **The push check** stops an agent's `git push` or `gh pr create` until `npm run verify` has passed on exactly what it pushes. ## Rules and what holds them @@ -22,7 +22,8 @@ This repository is set up so coding agents prove their work before they call it | Tests pass before a push | `pre-push`; CI | Enforced in CI | | Agent tooling never ships in the npm package | `.agents/scripts/package-contents.test.ts` | Enforced in CI | | `npm run verify` runs what CI runs | `.agents/scripts/lib/steps.test.ts` compares it with the pull-request workflows | Enforced in CI | -| Run `npm run verify` before calling work done | `AGENTS.md` | Enforced at turn end (once); `AGENTS.md` | +| Run `npm run verify` before calling work done | `AGENTS.md` | Asked | +| An agent pushes only code `npm run verify` passed | The push check, `.agents/scripts/guard.ts` | Enforced on an agent's push | | Never weaken a check to pass it | `AGENTS.md` | Asked | | Instructions name only files, links and scripts that exist | `.agents/scripts/instructions.test.ts` | Enforced in CI | | Every skill says when to use it and is linked for Claude Code | `.agents/scripts/instructions.test.ts` | Enforced in CI | @@ -56,33 +57,38 @@ One command, every check the pull-request workflows run (`lint.yml`, `test.yml`, - **Order:** every check starts together, except the skill sync check, which imports from `dist/` and so waits for the build. - **`CI=true`** is set for the build, the tests and the skill sync check, as GitHub Actions sets it. Variables that change what the CLI does (`COMMS_API_TOKEN`, `COMMS_AS_URL`, `COMMS_BASE_URL`, `COMMS_INCLUDE_PRIVATE_CHANNELS`, `TWIST_AUTH_TOKEN`, `TWIST_BASE_URL`, `TDC_ACCESSIBLE`, `TDC_SPINNER`, `FORCE_COLOR`) are removed, with a note, since CI never sets them. A real token or server never reaches the tests. - **Output:** one line per step. A failing step prints the last 30 lines of its log and the log's path under `.tmp/agents/logs/`. -- **The record:** after a full pass it writes a content hash of every file local checks read (not docs, not CI-only files) to `.tmp/agents/verified.json`. A run that fails, or sees files change while it runs, deletes it. The end-of-turn gate reads it. +- **The record:** after a full pass it writes a content hash of every file local checks read (not docs, not CI-only files) to `.tmp/agents/verified.json`. A run that fails, or sees files change while it runs, deletes it. The push check reads it. - **Platforms:** macOS, Linux and WSL. Like the git hooks, it assumes a POSIX shell and runs npm's POSIX launchers in `node_modules/.bin`; on native Windows, run it in WSL. - **What it cannot see:** the real Comms API, output in a real terminal, the other Node version CI tests on, and the `gh skill publish --dry-run` spec check. It prints these after every pass. If a pull-request workflow gains a step, `.agents/scripts/lib/steps.test.ts` fails until verify gains it too, or says why it can't. -## The end-of-turn gate +## The push check -Every agent's hooks call one script, `.agents/scripts/guard.ts`, so the agents can't drift apart. +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. -- **Turn start** (you send a message): it hashes every file in the checkout, untracked ones included, into `.tmp/agents/turns/`. -- **Turn end** (the agent stops): it compares the tree with the turn's start and with the last `npm run verify` pass. If the turn changed code and verify has not passed on exactly this tree, it sends the agent back once, naming the files. The second time, it lets the agent stop and shows you a note. -- **Passes without a word:** turns that changed nothing, changed only docs, or undid their edits. -- **"Once"** is deliberate: an agent can stop on purpose and say what is unfinished. +- **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. +- **What needs no verify:** a branch whose changes since `main` are all ones verify records nothing for (docs, files only CI reads), or whose code is back to what `main` has; a dry run; a push that only deletes; and `git push --tags`, which pushes tags alone. A tag named in the command, such as `git push origin v1.0`, is checked like a branch. A branch with no history in common with `main` always needs verify, since verify checks the whole tree there and records a pass. +- **What it reads:** `git push`, with `-C` or after a `cd` or `pushd`, and `gh pr create` (or `gh pr new`, with `-R` and `--head`), anywhere in a command, after `env`, `command`, `builtin`, `exec`, `nohup`, `time`, `timeout` or `sudo`, and inside `eval`, `sh -c` (or another shell's `-c`) and `env -S`, but not inside quotes or a here-document, such as a commit message. It stops a push it can't tell the contents of: every branch at once (`--all`, `--mirror`, `:` or a wildcard), one with no refspec when git's settings for the remote it goes to pick what it sends (`remote..push` or `.mirror`, or `push.default=matching`, set in the config or with `git -c`), one run through `xargs`, a branch named by a shell variable or one that doesn't exist, and a push after a command in the same line that changes what's checked out (`git switch`, `git checkout`, `git reset `, `git rebase`, `git pull`, `git merge`, `gh pr checkout` and the like). A branch the same line makes from what's checked out (`git switch -c`, `git checkout -b`, `git branch `) counts as what's checked out. +- **Which pushes:** pushes from the checkout `guard.ts` lives in, and from any other worktree of this repository that has the guard, however the command gets there (the agent works in it, `cd`, or `git -C`), each checked against that worktree's own verify record. A worktree on a branch without the guard is left alone, as is a push from another repository, and a push you run in your own terminal never passes through it. -| Agent | Wiring | Known limits | -| ----------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Claude Code | `.claude/settings.json`: `UserPromptSubmit` and `Stop` | `hook-wiring.test.ts` runs the exact commands. Not yet seen sending a real session back. | -| Codex | `.codex/hooks.json`: `UserPromptSubmit` and `Stop` | Runs only in a trusted project, after each person reviews the hooks in `/hooks`. Some versions run no project hooks in a linked worktree. Not yet tried here. | -| 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. | +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. -**Other limits:** +| 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. | -- Two sessions in one checkout share its files, so each may be told about the other's edits. Use a worktree per session. -- If the branch's code is back to what `main` has (an undo, a stash, a switch), the turn passes: CI already checked that code. +**Limits.** The push check catches an agent's honest mistakes. It isn't a security boundary, and CI is still what gates a merge. -**Fails open, visibly:** a broken guard, bad input or a checkout without the script lets the turn end and says why in a message. `DISABLE_AGENT_GUARD=1` in the agent's environment turns the gate off for you. +- **Pushes it can't see:** a push from a script, a git alias, a `gh` extension such as `gh stack`, GitHub's API or a GitHub MCP tool goes through unchecked, as does a command `eval` or a shell builds from variables. CI still checks them. +- **One record per checkout:** verify records the last tree it passed. To push a stack, verify and push each branch in turn; a push of several branches at once, or of a branch that isn't checked out, is stopped unless its changes need no verify. +- **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, such as `git stash pop`, or a commit that takes only part of it, 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" } }`. ## Skills @@ -153,5 +159,5 @@ semantic-release publishes from `main` on every merge, and a pre-release from `n - No node on `PATH` in a GUI client: the hooks skip lint, the type check and the tests, with a message. The branch rule still applies. - `git commit --no-verify`: every local hook is skipped. CI and branch protection still apply. -- The end-of-turn gate: any error lets the turn end, with a message saying why. `DISABLE_AGENT_GUARD=1` turns it off. +- The push check: any error lets the command run, with a message saying why. `DISABLE_AGENT_GUARD=1` turns it off. - Worktrees share the hooks in `.git/hooks`, so the branch rule works in a new worktree at once. Lint, format, types and tests need `npm ci` in that worktree first. Without the lefthook binary anywhere the hooks look, they print "Can't find lefthook in PATH" and let the commit through. From 8204e3a207aee7ff07665dc0e972b35879d8fe3c Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 13:52:45 +0000 Subject: [PATCH 2/7] chore(agents): keep a push's refspecs when the command sets git config An inline `git -c push.*`, `remote.*` or `branch.*` setting only decides what a push with no refspec sends: a refspec in the command wins over them, as in git. The push check treated any such setting like xargs and read the push as every branch, so `git -c push.default=matching push origin main` was stopped as "pushes every branch at once". --- .agents/scripts/lib/push-check.test.ts | 6 ++++++ .agents/scripts/lib/push-targets.test.ts | 3 +++ .agents/scripts/lib/push-targets.ts | 20 +++++++++++++++----- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/.agents/scripts/lib/push-check.test.ts b/.agents/scripts/lib/push-check.test.ts index 55f9e61..dd8fe7b 100644 --- a/.agents/scripts/lib/push-check.test.ts +++ b/.agents/scripts/lib/push-check.test.ts @@ -145,6 +145,12 @@ describe('pushes it checks', () => { expect(denial('git push')).toContain('push settings pick') config('--unset', 'push.default') + // Settings given in the command count the same, and a refspec there wins over them. + expect(denial('git -c push.default=matching push')).toContain('push settings pick') + const inline = + 'git -c push.default=matching -c remote.origin.push=refs/heads/*:refs/heads/*' + expect(check(`${inline} push origin configured`).decision).toBe('allow') + // With one remote, a bare push goes there, whatever its name. repo.git(['remote', 'rename', 'origin', 'upstream']) config('remote.upstream.push', 'refs/heads/main:refs/heads/main') diff --git a/.agents/scripts/lib/push-targets.test.ts b/.agents/scripts/lib/push-targets.test.ts index 8bc19a0..7aff89d 100644 --- a/.agents/scripts/lib/push-targets.test.ts +++ b/.agents/scripts/lib/push-targets.test.ts @@ -134,6 +134,9 @@ describe('findTargets', () => { ['git -c remote.pushDefault=other push', [['push', '/w', '*']]], ['git --config-env=branch.a.pushRemote=R push', [['push', '/w', '*']]], ['git -c core.editor=vi push', [['push', '/w', 'HEAD']]], + // A refspec in the command wins over them. + ['git -c push.default=matching push origin main', [['push', '/w', 'main']]], + ['git -c remote.origin.push=refs/heads/a push origin b', [['push', '/w', 'b']]], [ 'git push --mirror; git push --branches', [ diff --git a/.agents/scripts/lib/push-targets.ts b/.agents/scripts/lib/push-targets.ts index ed62d15..39c70fd 100644 --- a/.agents/scripts/lib/push-targets.ts +++ b/.agents/scripts/lib/push-targets.ts @@ -188,7 +188,7 @@ function readGit( let i = start let inDir = dir // An inline `push.*`, `remote.*` or `branch.*` setting can change what a push with no refspec - // sends, or where. + // sends, or where. A refspec in the command wins over them, as in git. let configured = false for (; i < words.length; i++) { const word = words[i] as string @@ -215,7 +215,7 @@ function readGit( targets.push({ kind: 'move', dir: inDir, sources: [] }) } if (subcommand !== 'push') return - const push = readPush(args, configured || extraArgs) + const push = readPush(args, configured, extraArgs) if (push) targets.push({ ...push, dir: inDir }) } @@ -248,7 +248,15 @@ function isMove(subcommand: string, args: string[]): boolean { return true } -function readPush(args: string[], unclear: boolean): Omit | undefined { +/** + * What `git push ` sends. `configured`: inline settings decide what a push with no refspec + * sends. `extraArgs`: `xargs` adds arguments, which may be refspecs, that the command doesn't show. + */ +function readPush( + args: string[], + configured: boolean, + extraArgs: boolean, +): Omit | undefined { let remote: string | null = null // A remote named as an argument wins over `--repo`, as in git. let repoOption: string | null = null @@ -270,7 +278,9 @@ function readPush(args: string[], unclear: boolean): Omit | u else refspecs.push(word) } remote ??= repoOption - if (every || (unclear && refspecs.length === 0)) return { kind: 'push', sources: ['*'] } + if (every || ((configured || extraArgs) && refspecs.length === 0)) { + return { kind: 'push', sources: ['*'] } + } if (refspecs.length === 0) { // With --tags and no refspec, it pushes tags alone, which hold no new code. if (tags) return undefined @@ -295,7 +305,7 @@ function readPush(args: string[], unclear: boolean): Omit | u } if (sources.length === 0) return undefined // `xargs` may add more refspecs than the command shows. - return { kind: 'push', sources: unclear ? ['*'] : sources } + return { kind: 'push', sources: extraArgs ? ['*'] : sources } } /** From fe22ed625a0f1a2e256133d5e55441126f59052f Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 13:55:07 +0000 Subject: [PATCH 3/7] chore(agents): check a branch the command resets by its new tip `git switch -C copy && git push origin copy` resets `copy` to what's checked out before it pushes, but the push check looked `copy` up as it was before the command ran. When `copy` held main's code, the push passed as needing no verify, though it sent the unverified HEAD. The same went for `git checkout -B` and `git branch -f`. The check now reads a branch the command resets as what it points it at: what's checked out, or the start point `git branch -f` names. --- .agents/scripts/lib/push-check.test.ts | 26 +++++++++++++++++ .agents/scripts/lib/push-check.ts | 37 +++++++++++++++++------- .agents/scripts/lib/push-targets.test.ts | 27 +++++++++++++++++ .agents/scripts/lib/push-targets.ts | 37 +++++++++++++++++++----- docs/agents.md | 2 +- 5 files changed, 110 insertions(+), 19 deletions(-) diff --git a/.agents/scripts/lib/push-check.test.ts b/.agents/scripts/lib/push-check.test.ts index dd8fe7b..53ea2ed 100644 --- a/.agents/scripts/lib/push-check.test.ts +++ b/.agents/scripts/lib/push-check.test.ts @@ -180,6 +180,32 @@ describe('pushes it checks', () => { expect(check('git switch -c made && git push -u origin made').decision).toBe('allow') }) + it('checks a branch the command resets by what it points it at, not what it held', () => { + // On its own, `copy` holds main's code and needs no verify. + repo.git(['branch', 'copy']) + commitOnBranch('feature', 'src/b.ts') + for (const command of [ + 'git switch -C copy && git push origin copy', + 'git checkout -B copy && git push origin copy', + 'git branch -f copy && git push origin copy', + ]) { + expect(denial(command), command).toContain('npm run verify') + } + markVerified() + expect(check('git switch -C copy && git push origin copy').decision).toBe('allow') + + repo.git(['switch', '--quiet', '-c', 'other', 'main']) + repo.write('src/other.ts', 'export const o = 1\n') + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'other']) + repo.git(['switch', '--quiet', 'feature']) + expect(denial('git branch -f copy other && git push origin copy')).toContain( + 'npm run verify', + ) + expect(check('git branch -f copy feature && git push origin copy').decision).toBe('allow') + expect(denial('git branch -f copy "$B" && git push origin copy')).toMatch(/can't tell/) + }) + it('stops a push on a branch that shares no history with main, as verify records a pass there', () => { repo.git(['switch', '--quiet', '--orphan', 'alone']) repo.write('docs/notes.md', '# notes\n') diff --git a/.agents/scripts/lib/push-check.ts b/.agents/scripts/lib/push-check.ts index 3ff4f32..6f112b6 100644 --- a/.agents/scripts/lib/push-check.ts +++ b/.agents/scripts/lib/push-check.ts @@ -37,6 +37,11 @@ type Checkout = { movedFirst: boolean /** Branches the command makes from what's checked out before it pushes them. */ created: Set + /** + * Branches the command points at what's checked out, or at another commit, even when they + * exist, so what they held before doesn't count. + */ + reset: Map } /** @@ -97,7 +102,10 @@ export function checkCommand({ if (target.kind === 'commit') checkout.committedFirst = true else if (target.kind === 'move') checkout.movedFirst = true else if (target.kind === 'create') { - for (const name of target.sources) checkout.created.add(name) + for (const name of target.sources) { + if (target.reset) checkout.reset.set(name, target.from) + else checkout.created.add(name) + } } else { // With no refspec, git's push settings can send other branches than HEAD. const sources = @@ -148,6 +156,7 @@ function openCheckout(root: string, notes: string[]): Checkout { committedFirst: false, movedFirst: false, created: new Set(), + reset: new Map(), } } @@ -209,15 +218,23 @@ function checkSource(checkout: Checkout, source: string, kind: 'push' | 'pr'): S if (source.includes('$')) return 'unknown' const { root, notes, head } = checkout - let commit = resolveCommit(root, source) - if (commit === undefined) { - if (checkout.created.has(source)) commit = head - else if (kind === 'pr') { - // It may exist only on the remote, which no local check can vouch for either way. - notes.push(`can't find ${source}, so the pull request isn't checked`) - return 'ok' - } else return 'unknown' - if (commit === undefined) return 'ok' + let commit: string | undefined + if (checkout.reset.has(source)) { + // The command points the branch here before it pushes, whatever it held before. + const from = checkout.reset.get(source) + commit = from === undefined ? head : resolveCommit(root, from) + if (commit === undefined) return from === undefined ? 'ok' : 'unknown' + } else { + commit = resolveCommit(root, source) + if (commit === undefined) { + if (checkout.created.has(source)) commit = head + else if (kind === 'pr') { + // It may exist only on the remote, which no local check can vouch for either way. + notes.push(`can't find ${source}, so the pull request isn't checked`) + return 'ok' + } else return 'unknown' + if (commit === undefined) return 'ok' + } } // The same command commits first, so what it pushes is the working tree. const fromTree = checkout.committedFirst && commit === head diff --git a/.agents/scripts/lib/push-targets.test.ts b/.agents/scripts/lib/push-targets.test.ts index 7aff89d..ea4704c 100644 --- a/.agents/scripts/lib/push-targets.test.ts +++ b/.agents/scripts/lib/push-targets.test.ts @@ -108,6 +108,15 @@ describe('findTargets', () => { ['create', '/w', 'c'], ], ], + [ + 'git switch -C a && git checkout -B b; git branch -f c && git branch --force d main', + [ + ['create', '/w', 'a'], + ['create', '/w', 'b'], + ['create', '/w', 'c'], + ['create', '/w', 'd'], + ], + ], [ 'git switch main; git switch -c d origin/main; git checkout x; gh pr checkout 1', [ @@ -168,6 +177,24 @@ describe('findTargets', () => { expect(findTargets('git push --repo origin', '/w')[0]?.remote).toBe('origin') }) + it('marks a branch the command points somewhere even when it exists', () => { + const created = (command: string) => + findTargets(command, '/w').map(({ sources, reset, from }) => ({ sources, reset, from })) + expect(created('git switch -c a; git checkout -b b; git branch c')).toEqual([ + { sources: ['a'] }, + { sources: ['b'] }, + { sources: ['c'] }, + ]) + expect( + created('git switch -C a; git checkout -B b; git branch -f c; git branch -f d x'), + ).toEqual([ + { sources: ['a'], reset: true }, + { sources: ['b'], reset: true }, + { sources: ['c'], reset: true }, + { sources: ['d'], reset: true, from: 'x' }, + ]) + }) + it('marks a push with no refspec as one git settings decide', () => { expect(findTargets('git push upstream', '/w')).toEqual([ { kind: 'push', dir: '/w', sources: ['HEAD'], implicit: true, remote: 'upstream' }, diff --git a/.agents/scripts/lib/push-targets.ts b/.agents/scripts/lib/push-targets.ts index 39c70fd..51f47bd 100644 --- a/.agents/scripts/lib/push-targets.ts +++ b/.agents/scripts/lib/push-targets.ts @@ -11,7 +11,9 @@ import { readCommands, type ShellItem } from './shell-commands.ts' * branch, `refs/tags/v1`); `*` when it can't be told from the command: every branch, a wildcard, * what git's push settings pick, or arguments `xargs` adds. * - `commit`: a commit, so a later push from that folder sends the working tree. - * - `create`: a branch made from what's checked out, named in `sources`. + * - `create`: a branch made from what's checked out, named in `sources`. `reset` when the command + * points the branch there even if it exists (`git switch -C`, `git checkout -B`, `git branch -f`), + * with `from` naming another commit when `git branch -f` gives a start point. * - `move`: a command that changes what's checked out, such as `git switch` or `git rebase`. * - `dir`: the folder it runs in, or null when the command doesn't say, as after `cd "$REPO"`. * - `implicit`: a push with no refspec, so git's settings decide what it sends, to `remote` (null @@ -23,6 +25,8 @@ export type PushTarget = { sources: string[] implicit?: boolean remote?: string | null + reset?: boolean + from?: string } /** Shell words before a command that run the command after them. */ @@ -210,8 +214,10 @@ function readGit( const args = words.slice(i + 1) if (subcommand === 'commit') targets.push({ kind: 'commit', dir: inDir, sources: [] }) const created = createdBranch(subcommand, args) - if (created !== undefined) targets.push({ kind: 'create', dir: inDir, sources: [created] }) - else if (MOVES.has(subcommand) && isMove(subcommand, args)) { + if (created !== undefined) { + const { name, ...how } = created + targets.push({ kind: 'create', dir: inDir, sources: [name], ...how }) + } else if (MOVES.has(subcommand) && isMove(subcommand, args)) { targets.push({ kind: 'move', dir: inDir, sources: [] }) } if (subcommand !== 'push') return @@ -219,12 +225,25 @@ function readGit( if (push) targets.push({ ...push, dir: inDir }) } -/** The branch `git switch -c`, `git checkout -b` or `git branch` makes from what's checked out. */ -function createdBranch(subcommand: string, args: string[]): string | undefined { +type CreatedBranch = { name: string; reset?: true; from?: string } + +/** + * The branch `git switch -c`, `git checkout -b` or `git branch` makes from what's checked out, and + * whether it's reset there even when it exists: `git switch -C`, `git checkout -B` or `git branch + * -f`, which can also name another start point. + */ +function createdBranch(subcommand: string, args: string[]): CreatedBranch | undefined { const operands = args.filter((word) => !word.startsWith('-')) if (subcommand === 'branch') { - // `git branch name` alone; with a start point, or any option, it isn't what's checked out - return args.length === 1 && operands.length === 1 ? operands[0] : undefined + const options = args.filter((word) => word.startsWith('-')) + const [name, from] = operands + if (name === undefined || operands.length > 2) return undefined + if (options.length > 0 && options.every((word) => word === '-f' || word === '--force')) { + return { name, reset: true, ...(from !== undefined ? { from } : {}) } + } + // `git branch name` alone; with a start point, or any other option, it isn't what's + // checked out + return args.length === 1 ? { name } : undefined } const flags = subcommand === 'switch' ? ['-c', '-C', '--create', '--force-create'] : ['-b', '-B'] @@ -234,7 +253,9 @@ function createdBranch(subcommand: string, args: string[]): string | undefined { const name = args[at + 1] // A start point after the name means the new branch, and HEAD, move there. const after = args.slice(at + 2).filter((word) => !word.startsWith('-')) - return name !== undefined && after.length === 0 ? name : undefined + if (name === undefined || after.length > 0) return undefined + const reset = ['-C', '--force-create', '-B'].includes(args[at] as string) + return reset ? { name, reset } : { name } } /** Whether a git command that can change what's checked out does here. */ diff --git a/docs/agents.md b/docs/agents.md index 35b071e..9961fac 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -70,7 +70,7 @@ Every agent's hooks call one script, `.agents/scripts/guard.ts`, so the agents c - **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. - **What needs no verify:** a branch whose changes since `main` are all ones verify records nothing for (docs, files only CI reads), or whose code is back to what `main` has; a dry run; a push that only deletes; and `git push --tags`, which pushes tags alone. A tag named in the command, such as `git push origin v1.0`, is checked like a branch. A branch with no history in common with `main` always needs verify, since verify checks the whole tree there and records a pass. -- **What it reads:** `git push`, with `-C` or after a `cd` or `pushd`, and `gh pr create` (or `gh pr new`, with `-R` and `--head`), anywhere in a command, after `env`, `command`, `builtin`, `exec`, `nohup`, `time`, `timeout` or `sudo`, and inside `eval`, `sh -c` (or another shell's `-c`) and `env -S`, but not inside quotes or a here-document, such as a commit message. It stops a push it can't tell the contents of: every branch at once (`--all`, `--mirror`, `:` or a wildcard), one with no refspec when git's settings for the remote it goes to pick what it sends (`remote..push` or `.mirror`, or `push.default=matching`, set in the config or with `git -c`), one run through `xargs`, a branch named by a shell variable or one that doesn't exist, and a push after a command in the same line that changes what's checked out (`git switch`, `git checkout`, `git reset `, `git rebase`, `git pull`, `git merge`, `gh pr checkout` and the like). A branch the same line makes from what's checked out (`git switch -c`, `git checkout -b`, `git branch `) counts as what's checked out. +- **What it reads:** `git push`, with `-C` or after a `cd` or `pushd`, and `gh pr create` (or `gh pr new`, with `-R` and `--head`), anywhere in a command, after `env`, `command`, `builtin`, `exec`, `nohup`, `time`, `timeout` or `sudo`, and inside `eval`, `sh -c` (or another shell's `-c`) and `env -S`, but not inside quotes or a here-document, such as a commit message. It stops a push it can't tell the contents of: every branch at once (`--all`, `--mirror`, `:` or a wildcard), one with no refspec when git's settings for the remote it goes to pick what it sends (`remote..push` or `.mirror`, or `push.default=matching`, set in the config or with `git -c`), one run through `xargs`, a branch named by a shell variable or one that doesn't exist, and a push after a command in the same line that changes what's checked out (`git switch`, `git checkout`, `git reset `, `git rebase`, `git pull`, `git merge`, `gh pr checkout` and the like). A branch the same line makes from what's checked out (`git switch -c`, `git checkout -b`, `git branch `) counts as what's checked out, as does one it resets there (`git switch -C`, `git checkout -B`, `git branch -f `), whatever it held before; `git branch -f ` counts as that commit. - **Which pushes:** pushes from the checkout `guard.ts` lives in, and from any other worktree of this repository that has the guard, however the command gets there (the agent works in it, `cd`, or `git -C`), each checked against that worktree's own verify record. A worktree on a branch without the guard is left alone, as is a push from another repository, and a push you run in your own terminal never passes through it. 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. From 93f831ee2b23c96abafc55edc89af8f3413ce85b Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 13:56:14 +0000 Subject: [PATCH 4/7] chore(agents): fail on a file the snapshot can't read The working-tree snapshot left out any file it failed to read, as if it had been deleted, so a permission or I/O error could change the fingerprint without a word and turn into a misleading "commit what belongs in it" denial. It now leaves out only files that are gone (ENOENT, ENOTDIR) and throws on anything else, which the push check reports as a guard failure that allowed the action. --- .agents/scripts/lib/tree.test.ts | 15 ++++++++++++++- .agents/scripts/lib/tree.ts | 9 ++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/.agents/scripts/lib/tree.test.ts b/.agents/scripts/lib/tree.test.ts index 0540de3..e414288 100644 --- a/.agents/scripts/lib/tree.test.ts +++ b/.agents/scripts/lib/tree.test.ts @@ -1,4 +1,4 @@ -import { rmSync, symlinkSync, utimesSync } from 'node:fs' +import { chmodSync, rmSync, symlinkSync, utimesSync } from 'node:fs' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { createTempRepo, type TempRepo } from './test-repo.ts' @@ -61,6 +61,19 @@ describe('snapshot', () => { expect(snapshot(repo.dir)).toEqual(unstaged) }) + // root reads a file whatever its mode, so there is no unreadable file to make. + it.skipIf(process.getuid?.() === 0)( + "fails on a file it can't read, rather than leave it out", + () => { + chmodSync(join(repo.dir, 'src/a.ts'), 0o000) + try { + expect(() => snapshot(repo.dir)).toThrow(/EACCES/) + } finally { + chmodSync(join(repo.dir, 'src/a.ts'), 0o644) + } + }, + ) + it('sees an executable bit change', () => { const before = codeFingerprint(snapshot(repo.dir)) repo.run('chmod', ['+x', 'src/a.ts']) diff --git a/.agents/scripts/lib/tree.ts b/.agents/scripts/lib/tree.ts index 76f6ad5..9fbd75e 100644 --- a/.agents/scripts/lib/tree.ts +++ b/.agents/scripts/lib/tree.ts @@ -31,9 +31,12 @@ function hashPath(path: string): string | undefined { if (stat.isSymbolicLink()) return `link:${blobId(Buffer.from(readlinkSync(path)))}` if (stat.isDirectory()) return 'dir' // a nested repository, listed but not entered return `${stat.mode & 0o111 ? 'x' : '-'}:${blobId(readFileSync(path))}` - } catch { - // Gone, or went away while being read. - return undefined + } catch (error) { + // Gone, or went away while being read. Any other failure, such as a file it can't read, + // must not pass for a deletion. + const code = (error as NodeJS.ErrnoException)?.code + if (code === 'ENOENT' || code === 'ENOTDIR') return undefined + throw error } } From b4310387831c0d6b6e8ca8c3ea34db57841d62b0 Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 13:57:13 +0000 Subject: [PATCH 5/7] chore(agents): cover a push split across lines in the hook wiring test JSON writes a line continuation in the command as `\\\n`, so the text between `pr` and `create` holds backslashes and an `n`. The hook's filter still passes it on, since the `*` after its bracket expression is a glob that takes any text, not a repeat of the bracket. The test now runs `gh pr create`, `gh pr new` and `git push` split across lines through both hook commands. --- .agents/scripts/hook-wiring.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.agents/scripts/hook-wiring.test.ts b/.agents/scripts/hook-wiring.test.ts index 13263fd..acce9f9 100644 --- a/.agents/scripts/hook-wiring.test.ts +++ b/.agents/scripts/hook-wiring.test.ts @@ -89,6 +89,10 @@ describe.each(AGENTS)('$name', ({ config, env }) => { expect(decision(pushed.stdout)).toBe('deny') expect(decision(run(bash('gh pr create --fill')).stdout)).toBe('deny') expect(decision(run(bash('gh pr\tcreate --fill')).stdout)).toBe('deny') + // Split across lines: JSON writes the line break as `\n`, which the filter's `*` takes in. + expect(decision(run(bash('gh pr \\\n create --fill')).stdout)).toBe('deny') + expect(decision(run(bash('gh pr\\\n new')).stdout)).toBe('deny') + expect(decision(run(bash('git \\\n push origin HEAD')).stdout)).toBe('deny') markVerified(repo.dir) expect(run(bash('git push -u origin HEAD'))).toEqual({ status: 0, stdout: '', stderr: '' }) From 0c9543335439db483ec8537eadc967ce1178d558 Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 14:01:54 +0000 Subject: [PATCH 6/7] chore(agents): give the split-command wiring check a test of its own The three hook runs for commands split across lines made the first wiring test take over vitest's five-second limit while the rest of `npm run verify` ran alongside it. --- .agents/scripts/hook-wiring.test.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/.agents/scripts/hook-wiring.test.ts b/.agents/scripts/hook-wiring.test.ts index acce9f9..add9c4e 100644 --- a/.agents/scripts/hook-wiring.test.ts +++ b/.agents/scripts/hook-wiring.test.ts @@ -89,15 +89,18 @@ describe.each(AGENTS)('$name', ({ config, env }) => { expect(decision(pushed.stdout)).toBe('deny') expect(decision(run(bash('gh pr create --fill')).stdout)).toBe('deny') expect(decision(run(bash('gh pr\tcreate --fill')).stdout)).toBe('deny') - // Split across lines: JSON writes the line break as `\n`, which the filter's `*` takes in. - expect(decision(run(bash('gh pr \\\n create --fill')).stdout)).toBe('deny') - expect(decision(run(bash('gh pr\\\n new')).stdout)).toBe('deny') - expect(decision(run(bash('git \\\n push origin HEAD')).stdout)).toBe('deny') markVerified(repo.dir) expect(run(bash('git push -u origin HEAD'))).toEqual({ status: 0, stdout: '', stderr: '' }) }) + it('stops a push or pull request split across lines', () => { + // JSON writes the line break as `\n`, which the `*` after `pr[…]` in the filter takes in. + expect(decision(run(bash('gh pr \\\n create --fill')).stdout)).toBe('deny') + expect(decision(run(bash('gh pr\\\n new')).stdout)).toBe('deny') + expect(decision(run(bash('git \\\n push origin HEAD')).stdout)).toBe('deny') + }) + it('never starts git or node for a command that cannot push', () => { const bin = mkdtempSync(join(tmpdir(), 'agent-bin-')) const calls = join(bin, 'calls') From 916107c6a0a3c117a053b34d684a70c79c12ce11 Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Fri, 27 Nov 2026 14:02:45 +0000 Subject: [PATCH 7/7] chore(agents): check a commit and push in one command by what the commit takes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For `git commit … && git push`, the push check compared the working tree with the verify record, as if the commit took all of it. A commit can take less: `git commit -am` leaves out untracked files, a plain commit leaves out unstaged changes, and named paths or `--patch` leave out the rest. Such a push went through though the commit held less than verify checked. The check now reads what the command stages and what the commit takes. It uses the working tree only when the commit holds all of it: everything staged first (`git add -A`, `git add .` from the top folder), `git commit -a` with no untracked files, or a plain commit with nothing unstaged. Otherwise it stops the push and says to stage everything in the same command, or to commit first and push on its own. --- .agents/scripts/lib/push-check.test.ts | 35 ++++++++ .agents/scripts/lib/push-check.ts | 97 +++++++++++++++++++--- .agents/scripts/lib/push-targets.test.ts | 31 +++++++ .agents/scripts/lib/push-targets.ts | 100 ++++++++++++++++++++++- docs/agents.md | 4 +- 5 files changed, 251 insertions(+), 16 deletions(-) diff --git a/.agents/scripts/lib/push-check.test.ts b/.agents/scripts/lib/push-check.test.ts index 53ea2ed..9c98306 100644 --- a/.agents/scripts/lib/push-check.test.ts +++ b/.agents/scripts/lib/push-check.test.ts @@ -87,6 +87,41 @@ describe('pushes it checks', () => { expect(check(command).decision).toBe('allow') }) + it('stops a commit and push in one command when the commit can leave out what verify saw', () => { + repo.git(['switch', '--quiet', '-c', 'together']) + repo.write('src/a.ts', 'export const a = 2\n') + repo.write('src/new.ts', 'export const n = 1\n') + markVerified() + // `-a` leaves out the untracked file; a plain commit, the unstaged edit too. + for (const command of [ + 'git commit -am "x" && git push', + 'git commit -m "x" && git push', + 'git add src/a.ts && git commit -m x && git push', + 'git add -A && git commit -m x src/a.ts && git push', + 'git add -A && git commit -p && git push', + 'git commit -m x && git add -A && git push', + 'git commit -am x && gh pr create --fill', + ]) { + expect(denial(command), command).toContain('Stage everything in the same command') + } + // Staged whole first, the commit holds what verify saw. + for (const command of [ + 'git add -A && git commit -m x && git push', + 'git add . && git commit -m x && git push', + 'cd src && git add --all && git commit -qm x && git push', + 'git add :/ && git commit -m x && git push', + ]) { + expect(check(command).decision, command).toBe('allow') + } + // With nothing untracked, `-a` takes every change, and a plain commit what's staged. + rmSync(join(repo.dir, 'src/new.ts')) + markVerified() + expect(check('git commit -am x && git push').decision).toBe('allow') + expect(denial('git commit -m x && git push')).toContain('Stage everything') + repo.git(['add', 'src/a.ts']) + expect(check('git commit -m x && git push').decision).toBe('allow') + }) + it('stops a new pull request for unverified code, including one for another branch', () => { commitOnBranch('pull-request', 'src/feature.ts') expect(denial('gh pr create --fill')).toContain( diff --git a/.agents/scripts/lib/push-check.ts b/.agents/scripts/lib/push-check.ts index 6f112b6..efc96d5 100644 --- a/.agents/scripts/lib/push-check.ts +++ b/.agents/scripts/lib/push-check.ts @@ -7,11 +7,12 @@ import { existsSync, realpathSync } from 'node:fs' import { join } from 'node:path' import { branchBase, defaultBranchRef, findRepoRoot, git, resolveCommit } from './git.ts' -import { findTargets } from './push-targets.ts' +import { findTargets, type PushTarget, type Staged } from './push-targets.ts' import { readVerified } from './state.ts' import { changedSince, changeNeedsChecks, + classify, codeFingerprint, commitChanges, needsChecks, @@ -33,7 +34,12 @@ type Checkout = { defaultRef: () => string | undefined /** The working tree's fingerprint, read once however many sources the command pushes. */ tree: () => string - committedFirst: boolean + /** What `git add` has staged of the whole checkout so far in the command. */ + staged: Staged | undefined + /** The last commit the command makes before it pushes, and what it takes of the tree. */ + committed: { stages: Staged | undefined; partial: boolean } | undefined + /** Whether that commit holds the whole working tree, read once. */ + holdsTree: () => boolean movedFirst: boolean /** Branches the command makes from what's checked out before it pushes them. */ created: Set @@ -47,10 +53,19 @@ type Checkout = { /** * What one push source sends: `ok`; `every` (every branch, a wildcard, or what git's settings or * `xargs` pick); `unknown` (a branch named by a variable, or one that doesn't exist); `moved` (what's - * checked out changes first); `unverified`; `dirty` (unverified, and the working tree holds more than - * the pushed commit); or `other` (unverified, and not what's checked out). + * checked out changes first); `partial` (the same command commits first, and the commit can leave + * out part of the working tree); `unverified`; `dirty` (unverified, and the working tree holds more + * than the pushed commit); or `other` (unverified, and not what's checked out). */ -type SourceResult = 'ok' | 'every' | 'unknown' | 'moved' | 'unverified' | 'dirty' | 'other' +type SourceResult = + | 'ok' + | 'every' + | 'unknown' + | 'moved' + | 'partial' + | 'unverified' + | 'dirty' + | 'other' export function checkCommand({ root, @@ -99,8 +114,16 @@ export function checkCommand({ checkout = openCheckout(path, notes) checkouts.set(path, checkout) } - if (target.kind === 'commit') checkout.committedFirst = true - else if (target.kind === 'move') checkout.movedFirst = true + if (target.kind === 'commit') { + checkout.committed = { + stages: widest(checkout.staged, target.stages), + partial: target.partial === true, + } + } else if (target.kind === 'stage') { + if (stagesWholeCheckout(target, path)) { + checkout.staged = widest(checkout.staged, target.stages) + } + } else if (target.kind === 'move') checkout.movedFirst = true else if (target.kind === 'create') { for (const name of target.sources) { if (target.reset) checkout.reset.set(name, target.from) @@ -146,18 +169,58 @@ function guardedCheckouts(root: string): (path: string) => boolean { function openCheckout(root: string, notes: string[]): Checkout { let tree: string | undefined let defaultRef: { ref: string | undefined } | undefined - return { + let holdsTree: boolean | undefined + const checkout: Checkout = { root, notes, head: resolveCommit(root, 'HEAD'), verified: readVerified(root)?.fingerprint, defaultRef: () => (defaultRef ??= { ref: defaultBranchRef(root) }).ref, tree: () => (tree ??= codeFingerprint(snapshot(root))), - committedFirst: false, + staged: undefined, + committed: undefined, + holdsTree: () => (holdsTree ??= commitHoldsTree(checkout)), movedFirst: false, created: new Set(), reset: new Map(), } + return checkout +} + +/** `all` takes in more than `tracked`. */ +function widest(a: Staged | undefined, b: Staged | undefined): Staged | undefined { + return a === 'all' || b === 'all' ? 'all' : (a ?? b) +} + +/** Whether a `git add` takes the whole checkout: no paths, `:/`, or `.` from its top folder. */ +function stagesWholeCheckout(target: PushTarget, root: string): boolean { + if (target.sources.length === 0) return true + return target.sources.some( + (path) => + path === ':/' || + ((path === '.' || path === './') && + target.dir !== null && + realPath(target.dir) === root), + ) +} + +/** + * Whether the commit the command makes before it pushes holds the whole working tree, as verify + * saw it: everything staged first, or nothing left out of what it takes. Files only CI reads don't + * count, since verify records nothing for them. + */ +function commitHoldsTree(checkout: Checkout): boolean { + const { root, committed } = checkout + if (committed === undefined || committed.partial) return false + // What `git add` staged before the commit, and what the commit itself takes. + const { stages } = committed + if (stages === 'all') return true + const counts = (path: string) => classify(path) !== 'unchecked' + const untracked = git(root, ['ls-files', '-z', '--others', '--exclude-standard']) + if (!untracked.ok || untracked.stdout.split('\0').filter(Boolean).some(counts)) return false + if (stages === 'tracked') return true + const unstaged = git(root, ['diff', '--no-ext-diff', '--name-only', '-z']) + return unstaged.ok && !unstaged.stdout.split('\0').filter(Boolean).some(counts) } /** The real path of the checkout a folder is in, or undefined when it isn't in one. */ @@ -236,8 +299,12 @@ function checkSource(checkout: Checkout, source: string, kind: 'push' | 'pr'): S if (commit === undefined) return 'ok' } } - // The same command commits first, so what it pushes is the working tree. - const fromTree = checkout.committedFirst && commit === head + // The same command commits first, so what it pushes is the working tree, when the commit takes + // all of it. + const fromTree = checkout.committed !== undefined && commit === head + if (fromTree && !checkout.holdsTree()) { + return onlyUncheckedChanges(checkout, undefined) ? 'ok' : 'partial' + } const fingerprint = fromTree ? checkout.tree() : codeFingerprint(snapshotCommit(root, commit)) if (fingerprint === checkout.verified) return 'ok' if (onlyUncheckedChanges(checkout, fromTree ? undefined : commit)) return 'ok' @@ -282,6 +349,14 @@ function denyReason(found: Set, onlyPullRequests: boolean): string '`.', ) } + if (found.has('partial')) { + paragraphs.push( + 'This commits and pushes in one command, but the commit can leave out changes verify ' + + "checked: files git doesn't track yet, changes the command doesn't stage, or the " + + 'paths it leaves out. Stage everything in the same command (`git add -A && git ' + + 'commit …`), or commit first and run the push as a command of its own.', + ) + } if (found.has('moved')) { paragraphs.push( 'This changes what is checked out (`git switch`, `git checkout`, `git rebase`, `git ' + diff --git a/.agents/scripts/lib/push-targets.test.ts b/.agents/scripts/lib/push-targets.test.ts index ea4704c..dcaa4a1 100644 --- a/.agents/scripts/lib/push-targets.test.ts +++ b/.agents/scripts/lib/push-targets.test.ts @@ -195,6 +195,37 @@ describe('findTargets', () => { ]) }) + it('reads what a commit and `git add` take from the working tree', () => { + const taken = (command: string) => + findTargets(command, '/w').map(({ kind, sources, stages, partial }) => ({ + kind, + sources, + stages, + partial, + })) + const commit = { kind: 'commit', sources: [] } + expect(taken('git commit -am x; git commit --all -m x; git commit -ma')).toEqual([ + { ...commit, stages: 'tracked' }, + { ...commit, stages: 'tracked' }, + commit, + ]) + expect( + taken( + 'git commit -m x a.ts; git commit -p; git commit -- a.ts; git commit -F - --amend', + ), + ).toEqual([ + { ...commit, partial: true }, + { ...commit, partial: true }, + { ...commit, partial: true }, + commit, + ]) + expect(taken('git add -A; git add .; git add -u; git add -p; git add -n .')).toEqual([ + { kind: 'stage', sources: [], stages: 'all' }, + { kind: 'stage', sources: ['.'], stages: 'all' }, + { kind: 'stage', sources: [], stages: 'tracked' }, + ]) + }) + it('marks a push with no refspec as one git settings decide', () => { expect(findTargets('git push upstream', '/w')).toEqual([ { kind: 'push', dir: '/w', sources: ['HEAD'], implicit: true, remote: 'upstream' }, diff --git a/.agents/scripts/lib/push-targets.ts b/.agents/scripts/lib/push-targets.ts index 51f47bd..3b22914 100644 --- a/.agents/scripts/lib/push-targets.ts +++ b/.agents/scripts/lib/push-targets.ts @@ -10,7 +10,10 @@ import { readCommands, type ShellItem } from './shell-commands.ts' * - `push`, `pr`: what a push or a new pull request sends, as git names it in `sources` (`HEAD`, a * branch, `refs/tags/v1`); `*` when it can't be told from the command: every branch, a wildcard, * what git's push settings pick, or arguments `xargs` adds. - * - `commit`: a commit, so a later push from that folder sends the working tree. + * - `commit`: a commit, so a later push from that folder sends what it stages. `stages: 'tracked'` + * for `git commit -a`, and `partial` when it takes only some changes: named paths, or `--patch`. + * - `stage`: `git add`, of the paths in `sources` (none: the whole checkout), with `stages: 'all'` + * when it takes untracked files too, or `'tracked'` for `git add -u`. * - `create`: a branch made from what's checked out, named in `sources`. `reset` when the command * points the branch there even if it exists (`git switch -C`, `git checkout -B`, `git branch -f`), * with `from` naming another commit when `git branch -f` gives a start point. @@ -20,15 +23,20 @@ import { readCommands, type ShellItem } from './shell-commands.ts' * when the command names none). */ export type PushTarget = { - kind: 'push' | 'pr' | 'commit' | 'create' | 'move' + kind: 'push' | 'pr' | 'commit' | 'stage' | 'create' | 'move' dir: string | null sources: string[] implicit?: boolean remote?: string | null reset?: boolean from?: string + stages?: Staged + partial?: boolean } +/** What a `git add` or `git commit` takes from the working tree. */ +export type Staged = 'all' | 'tracked' + /** Shell words before a command that run the command after them. */ const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{']) @@ -212,7 +220,13 @@ function readGit( } const subcommand = words[i] ?? '' const args = words.slice(i + 1) - if (subcommand === 'commit') targets.push({ kind: 'commit', dir: inDir, sources: [] }) + if (subcommand === 'commit') { + targets.push({ kind: 'commit', dir: inDir, sources: [], ...readCommit(args) }) + } + if (subcommand === 'add') { + const stage = readAdd(args) + if (stage) targets.push({ kind: 'stage', dir: inDir, ...stage }) + } const created = createdBranch(subcommand, args) if (created !== undefined) { const { name, ...how } = created @@ -225,6 +239,86 @@ function readGit( if (push) targets.push({ ...push, dir: inDir }) } +/** `git commit` options whose value is the next word, unless given with `=`. */ +const COMMIT_VALUE_OPTIONS = new Set([ + '--message', + '--file', + '--reuse-message', + '--reedit-message', + '--template', + '--author', + '--date', + '--fixup', + '--squash', + '--cleanup', + '--trailer', + '--pathspec-from-file', +]) + +/** Whether `git commit ` takes every tracked change (`-a`), or only some (paths, `--patch`). */ +function readCommit(args: string[]): { stages?: Staged; partial?: boolean } { + let all = false + let partial = false + for (let i = 0; i < args.length; i++) { + const word = args[i] as string + if (word === '--') { + partial ||= i + 1 < args.length + break + } + if (word.startsWith('--')) { + const flag = word.split('=', 1)[0] as string + if (flag === '--all') all = true + else if (['--patch', '--interactive', '--pathspec-from-file'].includes(flag)) { + partial = true + } + if (!word.includes('=') && COMMIT_VALUE_OPTIONS.has(flag)) i++ + } else if (word.startsWith('-') && word.length > 1) { + // A cluster such as `-am`: `-m`, `-F`, `-C`, `-c` and `-t` take the rest of it, or the + // next word, as their value; `-S` and `-u` take only the rest. + for (let k = 1; k < word.length; k++) { + const letter = word[k] as string + if (letter === 'a') all = true + else if (letter === 'p') partial = true + else if ('mFCct'.includes(letter)) { + if (k === word.length - 1) i++ + break + } else if ('Su'.includes(letter)) break + } + } else partial = true + } + return { ...(all ? { stages: 'tracked' as const } : {}), ...(partial ? { partial } : {}) } +} + +/** + * What `git add ` stages: the paths it names (none means the whole checkout), and whether it + * takes untracked files too. Undefined when it stages nothing whole: a dry run, hunks picked by + * hand, or paths from a file. + */ +function readAdd(args: string[]): { sources: string[]; stages: Staged } | undefined { + let stages: Staged | undefined + const paths: string[] = [] + for (let i = 0; i < args.length; i++) { + const word = args[i] as string + if (word === '--') { + paths.push(...args.slice(i + 1)) + break + } + if (['-A', '--all', '--no-ignore-removal'].includes(word)) stages = 'all' + else if (['-u', '--update'].includes(word)) stages ??= 'tracked' + else if ( + /^(-[npieN]|--(dry-run|patch|interactive|edit|intent-to-add|refresh|pathspec-from-file)(=.*)?)$/.test( + word, + ) + ) { + return undefined + } else if (word === '--chmod') i++ + else if (!word.startsWith('-')) paths.push(word) + } + // `git add ` takes untracked files under them too. + if (paths.length > 0) return { sources: paths, stages: stages ?? 'all' } + return stages ? { sources: [], stages } : undefined +} + type CreatedBranch = { name: string; reset?: true; from?: string } /** diff --git a/docs/agents.md b/docs/agents.md index 9961fac..6b3a1c7 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -68,7 +68,7 @@ If a pull-request workflow gains a step, `.agents/scripts/lib/steps.test.ts` fai 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. - **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. +- **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. - **What needs no verify:** a branch whose changes since `main` are all ones verify records nothing for (docs, files only CI reads), or whose code is back to what `main` has; a dry run; a push that only deletes; and `git push --tags`, which pushes tags alone. A tag named in the command, such as `git push origin v1.0`, is checked like a branch. A branch with no history in common with `main` always needs verify, since verify checks the whole tree there and records a pass. - **What it reads:** `git push`, with `-C` or after a `cd` or `pushd`, and `gh pr create` (or `gh pr new`, with `-R` and `--head`), anywhere in a command, after `env`, `command`, `builtin`, `exec`, `nohup`, `time`, `timeout` or `sudo`, and inside `eval`, `sh -c` (or another shell's `-c`) and `env -S`, but not inside quotes or a here-document, such as a commit message. It stops a push it can't tell the contents of: every branch at once (`--all`, `--mirror`, `:` or a wildcard), one with no refspec when git's settings for the remote it goes to pick what it sends (`remote..push` or `.mirror`, or `push.default=matching`, set in the config or with `git -c`), one run through `xargs`, a branch named by a shell variable or one that doesn't exist, and a push after a command in the same line that changes what's checked out (`git switch`, `git checkout`, `git reset `, `git rebase`, `git pull`, `git merge`, `gh pr checkout` and the like). A branch the same line makes from what's checked out (`git switch -c`, `git checkout -b`, `git branch `) counts as what's checked out, as does one it resets there (`git switch -C`, `git checkout -B`, `git branch -f `), whatever it held before; `git branch -f ` counts as that commit. - **Which pushes:** pushes from the checkout `guard.ts` lives in, and from any other worktree of this repository that has the guard, however the command gets there (the agent works in it, `cd`, or `git -C`), each checked against that worktree's own verify record. A worktree on a branch without the guard is left alone, as is a push from another repository, and a push you run in your own terminal never passes through it. @@ -85,7 +85,7 @@ When it stops a command, the reason tells the agent to run verify and try again. - **Pushes it can't see:** a push from a script, a git alias, a `gh` extension such as `gh stack`, GitHub's API or a GitHub MCP tool goes through unchecked, as does a command `eval` or a shell builds from variables. CI still checks them. - **One record per checkout:** verify records the last tree it passed. To push a stack, verify and push each branch in turn; a push of several branches at once, or of a branch that isn't checked out, is stopped unless its changes need no verify. -- **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, such as `git stash pop`, or a commit that takes only part of it, can let code through that verify didn't see. +- **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" } }`.