diff --git a/.agents/scripts/lib/git.ts b/.agents/scripts/lib/git.ts index 0ae3466..9175971 100644 --- a/.agents/scripts/lib/git.ts +++ b/.agents/scripts/lib/git.ts @@ -23,10 +23,14 @@ export function cleanGitEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.Proces export type GitResult = { ok: boolean; stdout: string; stderr: string } -export function git(root: string, args: string[], options: { input?: string } = {}): GitResult { +export function git( + root: string, + args: string[], + options: { input?: string; env?: Record } = {}, +): GitResult { const result = spawnSync('git', args, { cwd: root, - env: cleanGitEnv(), + env: { ...cleanGitEnv(), ...options.env }, input: options.input, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, diff --git a/.agents/scripts/lib/patches.test.ts b/.agents/scripts/lib/patches.test.ts new file mode 100644 index 0000000..3ac9a7c --- /dev/null +++ b/.agents/scripts/lib/patches.test.ts @@ -0,0 +1,166 @@ +import { chmodSync, existsSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { + branchPatchId, + forgetPassedChanges, + hasPassedPatch, + readPassedPatches, + recordPassedPatch, +} from './patches.ts' +import { createTempRepo, GIT_HAS_VERBATIM_PATCH_ID, type TempRepo } from './test-repo.ts' + +let repo: TempRepo + +const rev = (ref: string) => repo.git(['rev-parse', ref]).stdout.trim() +const base = (ref = 'HEAD') => repo.git(['merge-base', ref, 'main']).stdout.trim() + +const LINES = Array.from({ length: 30 }, (_, i) => `export const line${i} = ${i}`) + +function commit(path: string, content: string, message = `change ${path}`): void { + repo.write(path, content) + repo.git(['add', path]) + repo.git(['commit', '--quiet', '-m', message]) +} + +/** Moves `main` on with `path`, then rebases `branch` onto it and returns to `branch`. */ +function moveMainAndRebase(branch: string, path: string, content: string): void { + repo.git(['switch', '--quiet', 'main']) + commit(path, content, 'main moves on') + repo.git(['switch', '--quiet', branch]) + const rebase = repo.git(['rebase', '--quiet', 'main']) + if (rebase.status !== 0) throw new Error(rebase.stderr) +} + +beforeEach(() => { + repo = createTempRepo() + repo.write('src/other.ts', 'export const other = 1\n') + repo.git(['add', 'src/other.ts']) + commit('src/a.ts', `${LINES.join('\n')}\n`, 'initial') + repo.git(['switch', '--quiet', '-c', 'feature']) + commit('src/a.ts', `${LINES.join('\n').replace('line15 = 15', 'line15 = 150')}\n`) +}) + +afterEach(() => repo.cleanup()) + +// Without `--verbatim` there is no exemption, and every rebase needs verify again. +describe.skipIf(!GIT_HAS_VERBATIM_PATCH_ID)('branchPatchId', () => { + it('keeps the id when a rebase moved the base under unchanged changes', () => { + const before = branchPatchId(repo.dir, base(), 'HEAD') + moveMainAndRebase('feature', 'src/other.ts', 'export const other = 2\n') + expect(rev('HEAD')).not.toBe(rev('ORIG_HEAD')) + expect(branchPatchId(repo.dir, base(), 'HEAD')).toBe(before) + + // Lines added far above the change only shift its line numbers + const shifted = ['// a comment', ...LINES].join('\n') + repo.git(['switch', '--quiet', 'main']) + commit('src/a.ts', `${shifted}\n`, 'main adds a comment at the top') + repo.git(['switch', '--quiet', 'feature']) + repo.git(['rebase', '--quiet', 'main']) + expect(branchPatchId(repo.dir, base(), 'HEAD')).toBe(before) + }) + + it('changes the id when the base changed the lines around the change', () => { + // Whatever context the person's git config asks diffs for + repo.git(['config', 'diff.context', '0']) + const before = branchPatchId(repo.dir, base(), 'HEAD') + moveMainAndRebase( + 'feature', + 'src/a.ts', + `${LINES.join('\n').replace('line13 = 13', 'line13 = 130')}\n`, + ) + expect(branchPatchId(repo.dir, base(), 'HEAD')).not.toBe(before) + }) + + it('changes the id for a change only in whitespace, or only in binary content', () => { + const before = branchPatchId(repo.dir, base(), 'HEAD') + repo.git(['switch', '--quiet', '-c', 'spaced', 'main']) + commit('src/a.ts', `${LINES.join('\n').replace('line15 = 15', 'line15 = 150')}\n`) + expect(branchPatchId(repo.dir, base(), 'HEAD')).not.toBe(before) + + const ids = ['one', 'two'].map((name) => { + repo.git(['switch', '--quiet', '-c', `binary-${name}`, 'main']) + commit('icon.png', `\u0000binary ${name}`) + return branchPatchId(repo.dir, base(), 'HEAD') + }) + expect(ids[0]).toBeDefined() + expect(ids[0]).not.toBe(ids[1]) + }) + + it('has no id for a commit that changes nothing since the base', () => { + expect(branchPatchId(repo.dir, rev('main'), 'main')).toBeUndefined() + }) +}) + +describe.skipIf(!GIT_HAS_VERBATIM_PATCH_ID)('passed patches', () => { + it('finds a recorded patch on a newer base, and only there', () => { + recordPassedPatch(repo.dir, base(), 'HEAD') + expect(hasPassedPatch(repo.dir, base(), 'HEAD')).toBe(true) + moveMainAndRebase('feature', 'src/other.ts', 'export const other = 2\n') + expect(hasPassedPatch(repo.dir, base(), 'HEAD')).toBe(true) + + // The same changes on a base the recorded one isn't part of + repo.git(['switch', '--quiet', '--orphan', 'unrelated']) + commit('src/a.ts', `${LINES.join('\n')}\n`, 'unrelated history') + const elsewhere = rev('HEAD') + commit('src/a.ts', `${LINES.join('\n').replace('line15 = 15', 'line15 = 150')}\n`) + expect(branchPatchId(repo.dir, elsewhere, 'HEAD')).toBe( + readPassedPatches(repo.dir)[0]?.patchId, + ) + expect(hasPassedPatch(repo.dir, elsewhere, 'HEAD')).toBe(false) + }) + + it('forgets a patch, whatever base it passed on', () => { + recordPassedPatch(repo.dir, base(), 'HEAD') + moveMainAndRebase('feature', 'src/other.ts', 'export const other = 2\n') + recordPassedPatch(repo.dir, base(), 'HEAD') + commit('src/b.ts', 'export const b = 1\n') + recordPassedPatch(repo.dir, base(), 'HEAD') + repo.git(['reset', '--quiet', '--hard', 'HEAD~1']) + + forgetPassedChanges(repo.dir, base()) + expect(hasPassedPatch(repo.dir, base(), 'HEAD')).toBe(false) + // Other changes keep theirs + expect(readPassedPatches(repo.dir)).toHaveLength(1) + }) + + // root can write a read-only file, so there is no record it fails to rewrite. + it.skipIf(process.getuid?.() === 0)( + "deletes the record when it can't rewrite it, and throws when it can't delete it", + () => { + const record = join(repo.dir, '.tmp/agents/verified-patches.json') + recordPassedPatch(repo.dir, base(), 'HEAD') + chmodSync(record, 0o444) + forgetPassedChanges(repo.dir, base()) + expect(existsSync(record)).toBe(false) + + recordPassedPatch(repo.dir, base(), 'HEAD') + chmodSync(record, 0o444) + chmodSync(join(repo.dir, '.tmp/agents'), 0o555) + try { + expect(() => forgetPassedChanges(repo.dir, base())).toThrow(/EACCES/) + } finally { + chmodSync(join(repo.dir, '.tmp/agents'), 0o755) + } + }, + ) + + it('does not find changes that never passed', () => { + recordPassedPatch(repo.dir, base(), 'HEAD') + commit('src/a.ts', 'export const changed = true\n') + expect(hasPassedPatch(repo.dir, base(), 'HEAD')).toBe(false) + }) + + it('keeps one entry per patch and base, and the 50 newest', () => { + recordPassedPatch(repo.dir, base(), 'HEAD') + recordPassedPatch(repo.dir, base(), 'HEAD') + expect(readPassedPatches(repo.dir)).toHaveLength(1) + for (let i = 0; i < 55; i++) { + commit('src/b.ts', `export const b = ${i}\n`) + recordPassedPatch(repo.dir, base(), 'HEAD') + } + const patches = readPassedPatches(repo.dir) + expect(patches).toHaveLength(50) + expect(patches.at(-1)?.patchId).toBe(branchPatchId(repo.dir, base(), 'HEAD')) + }) +}) diff --git a/.agents/scripts/lib/patches.ts b/.agents/scripts/lib/patches.ts new file mode 100644 index 0000000..5eb3d5b --- /dev/null +++ b/.agents/scripts/lib/patches.ts @@ -0,0 +1,141 @@ +// The changes that passed `npm run verify`, recorded by patch rather than by tree, so the push +// check can let a branch through when it holds the same changes on a newer default branch: a +// rebase that only moved the base. Without this, every rebase of a verified branch, and of every +// branch of a stack, would need verify again before it could push. + +import { copyFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { git } from './git.ts' +import { readJson, stateDir, writeJson } from './state.ts' + +/** A branch's changes that passed verify, and where the branch left the default branch then. */ +export type PassedPatch = { patchId: string; base: string; at: string } + +/** Enough for every branch of a long stack, and a few rebases of each. */ +const MAX_RECORDED = 50 + +function patchesPath(root: string): string { + return join(stateDir(root), 'verified-patches.json') +} + +export function readPassedPatches(root: string): PassedPatch[] { + return readJson<{ patches?: PassedPatch[] }>(patchesPath(root))?.patches ?? [] +} + +/** + * An id for everything a commit changes since `base`, the same wherever the changes sit: git's + * patch id ignores line numbers and file order, but not the three lines around each change, which + * the diff sets itself whatever `diff.context` says. So a rebase that changed nothing near the + * branch's changes keeps the id, and one that did, by a conflict or by new code next to them, + * doesn't. `--verbatim` keeps whitespace, which the default strips, so a change inside a string or + * to formatting changes the id. Binary files count by their full blob ids. A git older than 2.39 + * has no `--verbatim`, so every rebase there needs verify again. + */ +export function branchPatchId(root: string, base: string, commit: string): string | undefined { + return patchIdOf(root, [base, commit]) +} + +/** The patch id of `git diff `, with the diff settings `branchPatchId` describes. */ +function patchIdOf( + root: string, + compared: string[], + env?: Record, +): string | undefined { + const diff = git( + root, + [ + 'diff', + '--unified=3', + '--diff-algorithm=myers', + '--src-prefix=a/', + '--dst-prefix=b/', + '--full-index', + '--no-color', + '--no-ext-diff', + '--no-textconv', + '--no-renames', + ...compared, + ], + { env }, + ) + if (!diff.ok || !diff.stdout.trim()) return undefined + const id = git(root, ['patch-id', '--verbatim'], { input: diff.stdout }) + return id.ok ? id.stdout.split(' ')[0] || undefined : undefined +} + +/** + * The patch ids of what could be committed next, from `base`: HEAD's changes, what's staged, and + * the whole working tree, untracked files included. The working tree is read through a copy of the + * index with everything added, so the real index is left as it is. + */ +function pendingPatchIds(root: string, base: string): Set { + const ids = [branchPatchId(root, base, 'HEAD'), patchIdOf(root, ['--cached', base])] + const scratch = mkdtempSync(join(tmpdir(), 'agent-index-')) + try { + const index = git(root, ['rev-parse', '--path-format=absolute', '--git-path', 'index']) + const copy = join(scratch, 'index') + const real = index.stdout.trim() + if (index.ok && existsSync(real)) copyFileSync(real, copy) + const env = { GIT_INDEX_FILE: copy } + if (git(root, ['add', '--all'], { env }).ok) + ids.push(patchIdOf(root, ['--cached', base], env)) + } finally { + rmSync(scratch, { recursive: true, force: true }) + } + return new Set(ids.filter((id) => id !== undefined)) +} + +/** + * Records that the changes `commit` makes since `base` passed verify. Best effort: a record that + * can't be written only means the next rebase needs verify again. + */ +export function recordPassedPatch(root: string, base: string, commit: string): void { + try { + const patchId = branchPatchId(root, base, commit) + if (patchId === undefined) return + const others = readPassedPatches(root).filter( + (patch) => patch.patchId !== patchId || patch.base !== base, + ) + const patches = [...others, { patchId, base, at: new Date().toISOString() }] + writeJson(patchesPath(root), { patches: patches.slice(-MAX_RECORDED) }) + } catch { + // Nothing to undo: the push or the verify run it follows already succeeded. + } +} + +/** + * Forgets that the changes verify is about to check passed, whatever base they passed on, so a run + * that doesn't pass can't leave them counted as passed: HEAD's changes since `base`, and the ones a + * commit could hold next, staged or not, as after `git reset HEAD~1`. When the record can't be + * rewritten it is deleted, and when it can't be deleted either, this throws. + */ +export function forgetPassedChanges(root: string, base: string): void { + const patches = readPassedPatches(root) + if (patches.length === 0) return + const pending = pendingPatchIds(root, base) + const kept = patches.filter((patch) => !pending.has(patch.patchId)) + if (kept.length === patches.length) return + try { + writeJson(patchesPath(root), { patches: kept }) + } catch { + // Losing the other branches' records only means they need verify again after a rebase. + rmSync(patchesPath(root), { force: true }) + } +} + +/** + * Whether `commit` holds changes that passed verify, from `base` or from an earlier point of the + * default branch that `base` has moved on from. + */ +export function hasPassedPatch(root: string, base: string, commit: string): boolean { + const patches = readPassedPatches(root) + if (patches.length === 0) return false + const patchId = branchPatchId(root, base, commit) + if (patchId === undefined) return false + return patches.some( + (patch) => + patch.patchId === patchId && + git(root, ['merge-base', '--is-ancestor', patch.base, base]).ok, + ) +} diff --git a/.agents/scripts/lib/push-check.test.ts b/.agents/scripts/lib/push-check.test.ts index 9c98306..47d14b7 100644 --- a/.agents/scripts/lib/push-check.test.ts +++ b/.agents/scripts/lib/push-check.test.ts @@ -1,8 +1,14 @@ import { rmSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { recordPassedPatch } from './patches.ts' import { checkCommand, type PushVerdict } from './push-check.ts' -import { createTempRepo, markVerified as markDirVerified, type TempRepo } from './test-repo.ts' +import { + createTempRepo, + GIT_HAS_VERBATIM_PATCH_ID, + markVerified as markDirVerified, + type TempRepo, +} from './test-repo.ts' let repo: TempRepo @@ -313,6 +319,72 @@ describe('pushes it stops before reading them', () => { }) }) +// Without `git patch-id --verbatim` (git before 2.39) there is no exemption, and every rebase needs +// verify again. +describe.skipIf(!GIT_HAS_VERBATIM_PATCH_ID)('pushes of changes that already passed', () => { + /** Moves main on with a change to another file, as a merged pull request would. */ + function moveMain(path = 'src/upstream.ts'): void { + const branch = repo.git(['branch', '--show-current']).stdout.trim() + repo.git(['switch', '--quiet', 'main']) + repo.write(path, `export const upstream = '${path}'\n`) + repo.git(['add', path]) + repo.git(['commit', '--quiet', '-m', 'main moves on']) + repo.git(['push', '--quiet', 'origin', 'main']) + repo.git(['fetch', '--quiet', 'origin']) + repo.git(['switch', '--quiet', branch]) + } + + it('lets a verified branch push again after a rebase that only moved main under it', () => { + commitOnBranch('feature', 'src/b.ts') + markVerified() + expect(check('git push -u origin feature')).toEqual({ decision: 'allow', notes: [] }) + + moveMain() + repo.git(['rebase', '--quiet', 'origin/main']) + expect(check('git push --force-with-lease origin feature')).toEqual({ + decision: 'allow', + notes: ["feature holds changes that already passed verify, so it isn't verified again"], + }) + }) + + it('counts a pass recorded by verify on a clean tree, before any push', () => { + commitOnBranch('feature', 'src/b.ts') + recordPassedPatch(repo.dir, repo.git(['merge-base', 'HEAD', 'main']).stdout.trim(), 'HEAD') + moveMain() + repo.git(['rebase', '--quiet', 'origin/main']) + expect(check('git push').decision).toBe('allow') + }) + + it('stops a rebased branch whose changes are not the ones that passed', () => { + commitOnBranch('feature', 'src/b.ts') + markVerified() + check('git push -u origin feature') + moveMain() + repo.git(['rebase', '--quiet', 'origin/main']) + repo.write('src/b.ts', 'export const x = 2\n') + repo.git(['commit', '--quiet', '-am', 'change it after the rebase']) + expect(denial('git push --force-with-lease')).toContain('npm run verify') + }) + + it('stops a rebased branch when nothing recorded its changes as passed', () => { + commitOnBranch('feature', 'src/b.ts') + moveMain() + repo.git(['rebase', '--quiet', 'origin/main']) + expect(denial('git push')).toContain('npm run verify') + }) + + it('lets each branch of a stack push again after verify moved on to the next', () => { + commitOnBranch('lower', 'src/lower.ts') + markVerified() + check('git push -u origin lower') + commitOnBranch('upper', 'src/upper.ts') + markVerified() + check('git push -u origin upper') + // The record now holds upper's tree, and lower isn't checked out + expect(check('git push origin lower upper').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') diff --git a/.agents/scripts/lib/push-check.ts b/.agents/scripts/lib/push-check.ts index efc96d5..1c33db2 100644 --- a/.agents/scripts/lib/push-check.ts +++ b/.agents/scripts/lib/push-check.ts @@ -1,12 +1,13 @@ // 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. +// verify passed, or the same changes as one on a newer default branch, as after a rebase. 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 { hasPassedPatch, recordPassedPatch } from './patches.ts' import { findTargets, type PushTarget, type Staged } from './push-targets.ts' import { readVerified } from './state.ts' import { @@ -15,9 +16,9 @@ import { classify, codeFingerprint, commitChanges, + commitFingerprint, needsChecks, snapshot, - snapshotCommit, } from './tree.ts' export type PushVerdict = @@ -302,12 +303,23 @@ function checkSource(checkout: Checkout, source: string, kind: 'push' | 'pr'): S // 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 + // From the pushed commit: the branch checked out may have left main somewhere else. + const base = branchBase(root, checkout.defaultRef(), fromTree ? 'HEAD' : commit) if (fromTree && !checkout.holdsTree()) { - return onlyUncheckedChanges(checkout, undefined) ? 'ok' : 'partial' + return onlyUncheckedChanges(root, base, undefined) ? 'ok' : 'partial' + } + const fingerprint = fromTree ? checkout.tree() : commitFingerprint(root, commit) + if (fingerprint === checkout.verified) { + // So the same changes can push again after a rebase without verifying again. A commit the + // same command makes doesn't exist yet; its next push records it. + if (base !== undefined && !fromTree) recordPassedPatch(root, base, commit) + return 'ok' + } + if (onlyUncheckedChanges(root, base, fromTree ? undefined : commit)) return 'ok' + if (base !== undefined && !fromTree && hasPassedPatch(root, base, commit)) { + notes.push(`${source} holds changes that already passed verify, so it isn't verified again`) + return 'ok' } - 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' @@ -320,10 +332,11 @@ function checkSource(checkout: Checkout, source: string, kind: 'push' | 'pr'): S * 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') +function onlyUncheckedChanges( + root: string, + base: string | undefined, + commit: string | undefined, +): boolean { if (base === undefined) return false if (commit === undefined) return !changedSince(root, base).some((path) => needsChecks(root, path)) diff --git a/.agents/scripts/lib/test-repo.ts b/.agents/scripts/lib/test-repo.ts index 06da056..651324a 100644 --- a/.agents/scripts/lib/test-repo.ts +++ b/.agents/scripts/lib/test-repo.ts @@ -131,6 +131,10 @@ export function installLefthook(repo: TempRepo): void { if (result.status !== 0) throw new Error(`lefthook install failed: ${result.stderr}`) } +/** Whether this git has `git patch-id --verbatim` (2.39 and later), which the rebase exemption needs. */ +export const GIT_HAS_VERBATIM_PATCH_ID = + spawnSync('git', ['patch-id', '--verbatim'], { input: '', env: isolatedEnv() }).status === 0 + /** 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.ts b/.agents/scripts/lib/tree.ts index 9fbd75e..0c15843 100644 --- a/.agents/scripts/lib/tree.ts +++ b/.agents/scripts/lib/tree.ts @@ -64,6 +64,11 @@ export function snapshotCommit(root: string, commit: string): Snapshot { return files } +/** The fingerprint of a commit, comparable with the one verify records for the working tree. */ +export function commitFingerprint(root: string, commit: string): string { + return codeFingerprint(snapshotCommit(root, commit)) +} + /** * The pull-request workflows that run checks. .agents/scripts/lib/steps.test.ts compares verify * with their commands, and reads every other workflow to check none of them runs a command on pull diff --git a/.agents/scripts/lib/verify.test.ts b/.agents/scripts/lib/verify.test.ts index 0b402a9..7087129 100644 --- a/.agents/scripts/lib/verify.test.ts +++ b/.agents/scripts/lib/verify.test.ts @@ -1,8 +1,10 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { readPassedPatches } from './patches.ts' +import { checkCommand } from './push-check.ts' import { readVerified, stateDir, writeVerified } from './state.ts' -import { createTempRepo, type TempRepo } from './test-repo.ts' +import { createTempRepo, GIT_HAS_VERBATIM_PATCH_ID, type TempRepo } from './test-repo.ts' import { codeFingerprint, snapshot } from './tree.ts' import { runVerify, type Step } from './verify.ts' @@ -56,6 +58,74 @@ describe('a code change', () => { expect(lines.some((line) => /^✓ lint \(\d+\.\ds\)$/.test(line))).toBe(true) }) + // Without `git patch-id --verbatim` (git before 2.39) there is no exemption to record. + it.skipIf(!GIT_HAS_VERBATIM_PATCH_ID)( + 'records the changes as passed when the tree is exactly the last commit', + async () => { + await verify([pass('lint')]) + expect(readPassedPatches(repo.dir)).toEqual([]) + + repo.git(['commit', '--quiet', '-am', 'change a']) + await verify([pass('lint')]) + expect(readPassedPatches(repo.dir)).toEqual([ + { patchId: expect.any(String), base, at: expect.any(String) }, + ]) + }, + ) + + // Without `git patch-id --verbatim` (git before 2.39) there is no exemption to forget. + it.skipIf(!GIT_HAS_VERBATIM_PATCH_ID)( + 'stops counting the changes as passed once a verify run on them fails', + async () => { + repo.git(['commit', '--quiet', '-am', 'change a']) + await verify([pass('lint')]) + // main moves on, and the branch is rebased onto 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(['switch', '--quiet', 'feature']) + repo.git(['rebase', '--quiet', 'main']) + const push = () => + checkCommand({ root: repo.dir, command: 'git push origin feature', cwd: repo.dir }) + expect(push().decision).toBe('allow') + + const moved = repo.git(['merge-base', 'HEAD', 'main']).stdout.trim() + await verify([fail('tests')], { base: moved }) + expect(readPassedPatches(repo.dir)).toEqual([]) + expect(push().decision).toBe('deny') + }, + ) + + // Without `git patch-id --verbatim` (git before 2.39) there is no exemption to forget. + it.skipIf(!GIT_HAS_VERBATIM_PATCH_ID)( + 'forgets the changes when the failing run sees them staged or uncommitted again', + async () => { + repo.write('src/new.ts', 'export const n = 1\n') + const commitAndPass = async () => { + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'change a, add new']) + await verify([pass('lint')]) + expect(readPassedPatches(repo.dir)).toHaveLength(1) + } + // `--soft` leaves the changes staged; the default `--mixed` leaves src/new.ts untracked. + for (const mode of ['--soft', '--mixed']) { + await commitAndPass() + repo.git(['reset', '--quiet', mode, 'HEAD~1']) + await verify([fail('tests')]) + expect(readPassedPatches(repo.dir), mode).toEqual([]) + } + repo.git(['add', '.']) + repo.git(['commit', '--quiet', '-m', 'change a, add new']) + const push = checkCommand({ + root: repo.dir, + command: 'git push origin feature', + cwd: repo.dir, + }) + expect(push.decision).toBe('deny') + }, + ) + it('records nothing when a step fails, and forgets an earlier pass', async () => { writeVerified(repo.dir, { fingerprint: 'earlier', head: 'x', at: 'then' }) const result = await verify([pass('lint'), fail('tests')]) diff --git a/.agents/scripts/lib/verify.ts b/.agents/scripts/lib/verify.ts index 4efd280..1bd72bb 100644 --- a/.agents/scripts/lib/verify.ts +++ b/.agents/scripts/lib/verify.ts @@ -1,13 +1,15 @@ import { spawn } from 'node:child_process' import { createWriteStream, mkdirSync, readFileSync } from 'node:fs' import { join, relative } from 'node:path' -import { cleanGitEnv, git } from './git.ts' +import { cleanGitEnv, resolveCommit } from './git.ts' +import { forgetPassedChanges, recordPassedPatch } from './patches.ts' import { clearVerified, stateDir, writeVerified } from './state.ts' import { changedCodePaths, changedSince, classify, codeFingerprint, + commitFingerprint, needsChecks, snapshot, } from './tree.ts' @@ -60,9 +62,11 @@ export async function runVerify(options: VerifyOptions): Promise { } // From here the checks run, so a run that does not end in a pass must not leave an earlier - // pass behind. (A docs-only run returns above: docs are outside the fingerprint, so an - // earlier pass is still valid.) + // pass behind, of the tree or of the branch's changes. (A docs-only run returns above: docs + // are outside the fingerprint, so an earlier pass is still valid.) clearVerified(root) + const commit = resolveCommit(root, 'HEAD') + if (base !== undefined) forgetPassedChanges(root, base) const before = snapshot(root) const logDir = join(stateDir(root), 'logs') @@ -77,13 +81,16 @@ export async function runVerify(options: VerifyOptions): Promise { return { ok: false, recorded: false } } - const head = git(root, ['rev-parse', 'HEAD']) const fingerprint = codeFingerprint(after) - writeVerified(root, { - fingerprint, - head: head.ok ? head.stdout.trim() : 'none', - at: new Date().toISOString(), - }) + writeVerified(root, { fingerprint, head: commit ?? 'none', at: new Date().toISOString() }) + // When the tree is exactly the last commit, its changes can push again after a rebase. + if ( + commit !== undefined && + base !== undefined && + commitFingerprint(root, commit) === fingerprint + ) { + recordPassedPatch(root, base, commit) + } out(`Verified. Recorded fingerprint ${fingerprint.slice(0, 12)}.`) return { ok: true, recorded: true } } diff --git a/.agents/skills/verify/SKILL.md b/.agents/skills/verify/SKILL.md index 923cf95..dd91a94 100644 --- a/.agents/skills/verify/SKILL.md +++ b/.agents/skills/verify/SKILL.md @@ -13,7 +13,7 @@ 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. +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. After a rebase that only moved `main` under changes that passed, the push goes through without verifying again, and says so. ## 2. Prove the change itself diff --git a/AGENTS.md b/AGENTS.md index ba4dc3c..189019f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -109,7 +109,7 @@ throw new CliError('ERROR_CODE', 'User-facing message', ['Optional hint']) ## Git hooks and agent tooling - Lefthook refuses commits and pushes to `main`, runs oxlint, oxfmt and the type check on pre-commit, and the tests on pre-push. Work on a branch. -- Your `git push` and `gh pr create` are stopped until `npm run verify` has passed on exactly the commit being pushed (Claude Code, Codex and Cursor hooks, and a Pi extension). Verify, then commit exactly what it saw, or commit first and verify the clean tree. If something must be pushed unverified, ask the person you're working with to push it. +- Your `git push` and `gh pr create` are stopped until `npm run verify` has passed on exactly the commit being pushed (Claude Code, Codex and Cursor hooks, and a Pi extension), or on the same changes before a rebase that only moved `main` under them. 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/docs/agents.md b/docs/agents.md index dc147d4..162261f 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -57,7 +57,7 @@ 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 push check 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. When the tree verify passed is exactly the last commit, it also records that commit's changes since `main` by patch, in `.tmp/agents/verified-patches.json`, for the push check's rebase exemption. - **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. @@ -69,6 +69,7 @@ Every agent calls one script, `.agents/scripts/guard.ts`, so the agents can't dr - **What it checks:** what's pushed has to be exactly a tree verify passed, docs aside. A push sends commits, not the working tree, so verifying with uncommitted changes and then pushing only some of them doesn't get through. When the working tree holds more than the last commit, it says to commit or stash the rest before verifying. - **A commit and a push in one command:** for `git add -A && git commit -m "…" && git push`, it checks the working tree that's about to be committed. That holds only when the commit takes all of it: everything staged first in the same command (`git add -A`, or `git add .` from the top folder), `git commit -a` with no untracked files, or a plain commit with nothing unstaged either. A commit that can leave part of the tree out, by naming paths, `--patch` or what it doesn't stage, is stopped: commit first, then push. +- **After a rebase:** a push whose commit isn't a tree verify passed still goes through when it holds the same changes as one that passed, and only `main` moved under them, as after `git rebase origin/main`. "The same changes" means the same `git patch-id --verbatim` over the branch's diff from `main`: line numbers may shift, but the changed lines, the lines around them and their whitespace must match, and the new `main` must contain the old one. The record is written when verify passes on a clean tree and when the check lets a verified commit through (a commit and push in one command is recorded at that commit's next push), and keeps the last 50. A verify run on a branch drops its changes from the record first, committed or not (as after `git reset HEAD~1`), so one that fails leaves them needing verify; if it can't rewrite the record, it deletes it. The check notes when it lets a push through this way. - **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,8 +86,9 @@ When it stops a command, the reason tells the agent to run verify and try again. **Limits.** The push check catches an agent's honest mistakes. It isn't a security boundary, and CI is still what gates a merge. - **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. +- **One record per checkout:** verify records the last tree it passed. The rebase exemption remembers the changes of each branch it has seen pass, so a stack's branches can each be pushed again, together or from another branch, once each has passed and been pushed. A branch that changed since, or never passed here, needs its own verify, checked out. - **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. +- **A rebase can still break code:** the exemption trusts that changes which passed still pass on a newer `main` when nothing near them changed. A change elsewhere in `main` that they depend on, such as a renamed function they call, isn't seen until CI runs on the pushed branch. - **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. In Pi, an error in the extension itself also lets the command run, though Pi blocks a tool call whose handler throws. If node isn't on `PATH`, the hook command fails and the agent carries on. `DISABLE_AGENT_GUARD=1` in the agent's environment turns the check off; in Claude Code, a gitignored settings.local.json in `.claude/` can set it for one checkout with `{ "env": { "DISABLE_AGENT_GUARD": "1" } }`.