import { afterEach, describe, expect, it, vi } from 'vitest'; import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises'; import { existsSync } from 'node:fs'; import path from 'node:path'; import os from 'node:os'; import { GitWorkspace, executeCommand, requireBranchName, validateRepositoryUrl, type Command, type LocalSshTransport, } from '../src/index.js'; import { projectInput } from '../../contracts/src/index.js'; const dirs: string[] = []; async function temporary() { const dir = await mkdtemp(path.join(os.tmpdir(), 'wishforge-git-contract-')); dirs.push(dir); return dir; } afterEach(async () => { await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))); vi.unstubAllEnvs(); }); describe('operator-pinned local SSH authentication', () => { const transport: LocalSshTransport = { repositoryUrl: 'https://gitea.example.org/team/project.git', sshUrl: 'ssh://git@gitea.example.org/team/project.git', home: '/home/operator', }; const development = () => { vi.stubEnv('WF_DEPLOYMENT_MODE', 'development'); vi.stubEnv('NODE_ENV', 'test'); }; it('leaves project SSH unsupported and requires explicit development mode', () => { for (const mode of [undefined, 'production']) { vi.stubEnv('WF_DEPLOYMENT_MODE', mode); expect(() => new GitWorkspace(undefined, { localSshTransport: transport })).toThrow('explicit development'); } development(); vi.stubEnv('NODE_ENV', 'production'); expect(() => new GitWorkspace(undefined, { localSshTransport: transport })).toThrow('explicit development'); development(); expect(() => validateRepositoryUrl(transport.sshUrl)).toThrow('SSH repository transport is not supported'); }); it('rejects host, repository, credentials, port and HOME changes in the operator mapping', () => { development(); for (const change of [ { sshUrl: 'ssh://git@other.example.org/team/project.git' }, { sshUrl: 'ssh://git@gitea.example.org/team/other.git' }, { sshUrl: 'ssh://root@gitea.example.org/team/project.git' }, { sshUrl: 'ssh://git:secret@gitea.example.org/team/project.git' }, { sshUrl: 'ssh://git@gitea.example.org:2222/team/project.git' }, { sshUrl: 'ssh://git@gitea.example.org/team/project.git?upload-pack=evil' }, { sshUrl: 'git@gitea.example.org:team/project.git' }, { repositoryUrl: 'https://gitea.example.org:444/team/project.git' }, { repositoryUrl: 'https://gitea.example.org/team/pro%6aect.git' }, { home: 'relative' }, { home: '/home/operator\nEVIL=1' }, ]) expect(() => new GitWorkspace(undefined, { localSshTransport: { ...transport, ...change } })).toThrow(); }); it('keeps rewrites and SSH options inside Git processes, and binds clone/fetch/push to the pinned repository', async () => { development(); const commands: Command[] = []; const execute = vi.fn(async (command: Command) => { commands.push(command); return { exitCode: 0, stdout: command.args.includes('--is-bare-repository') ? 'true' : 'a'.repeat(40), stderr: '', }; }); const git = new GitWorkspace(execute, { localSshTransport: transport }); const root = await temporary(); await git.create({ repository: transport.repositoryUrl, targetBranch: 'poc', root, runId: 'clone' }); expect(commands[0]?.args).toContain(transport.repositoryUrl); expect(commands[0]?.env).toMatchObject({ HOME: transport.home, GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oStrictHostKeyChecking=yes', GIT_CONFIG_COUNT: '2', GIT_CONFIG_KEY_1: `url.${transport.sshUrl}.insteadOf`, GIT_CONFIG_VALUE_1: transport.repositoryUrl, GIT_CONFIG_GLOBAL: '/dev/null', }); await git.initializeIntegration({ repository: path.join(root, 'integration.git'), originalRepository: transport.repositoryUrl, workspace: path.join(root, 'clone'), sourceCommit: 'b'.repeat(40), baseCommit: 'a'.repeat(40), targetRef: 'refs/heads/poc', }); const fetch = commands.find( command => command.args.includes('fetch') && command.args.includes('+refs/heads/poc:refs/heads/poc'), ); expect(fetch?.args).toContain(transport.repositoryUrl); expect(fetch?.args).not.toContain('origin'); await git.pushVerifiedCandidate({ repository: root, targetRef: 'refs/heads/poc', expectedTargetCommit: 'a'.repeat(40), candidateCommit: 'b'.repeat(40), verifiedCommit: 'b'.repeat(40), }); const push = commands.find(command => command.args.includes('push')); expect(push?.args).toContain(transport.repositoryUrl); expect(push?.args).not.toContain('origin'); await expect( git.create({ repository: `${transport.repositoryUrl}-other`, root, runId: 'foreign' }), ).rejects.toMatchObject({ code: 'LOCAL_SSH_SCOPE' }); await expect(git.create({ repository: transport.sshUrl, root, runId: 'ssh-project' })).rejects.toMatchObject({ code: 'REPOSITORY_TRANSPORT_UNSUPPORTED', }); vi.stubEnv('WF_DEPLOYMENT_MODE', 'production'); await expect(git.head(root)).rejects.toMatchObject({ code: 'LOCAL_SSH_POLICY' }); }); }); async function git(cwd: string, args: string[]) { const result = await executeCommand({ executable: 'git', args: ['-c', 'core.hooksPath=/dev/null', ...args], cwd }); expect(result.exitCode).toBe(0); return result.stdout.trim(); } describe('exact target branch and immutable checkpoint contracts', () => { it('starts from the configured remote branch rather than default HEAD or an ambiguous tag', async () => { const root = await temporary(), work = new GitWorkspace(); const source = await work.create({ root, runId: 'source' }); await git(source.workspace, ['checkout', '-b', 'feature/target']); await writeFile(path.join(source.workspace, 'target.txt'), 'target branch contents'); const target = await work.checkpoint(source.workspace, source.baseCommit, 'source', 'test'); await git(source.workspace, ['tag', 'feature/target', source.baseCommit]); await git(source.workspace, ['checkout', 'main']); const prepared = await work.create({ repository: source.workspace, allowLocalRepository: true, targetBranch: 'feature/target', root, runId: 'target-run', }); expect(prepared.baseCommit).toBe(target.sourceCommit); expect(await work.head(prepared.workspace)).toBe(target.sourceCommit); expect(prepared.baseCommit).not.toBe(source.baseCommit); await expect( work.create({ repository: source.workspace, allowLocalRepository: true, targetBranch: 'missing', root, runId: 'missing-run', }), ).rejects.toMatchObject({ code: 'TARGET_BRANCH_UNAVAILABLE' }); }); it('preserves checkpoint source and original base when the repository target branch moves', async () => { const root = await temporary(), work = new GitWorkspace(); const source = await work.create({ root, runId: 'source', targetBranch: 'release/v1' }); await writeFile(path.join(source.workspace, 'app.txt'), 'first change'); const first = await work.checkpoint(source.workspace, source.baseCommit, 'source', 'test'); await writeFile(path.join(source.workspace, 'app.txt'), 'later branch change'); const later = await work.checkpoint(source.workspace, source.baseCommit, 'source', 'test'); expect(later.sourceCommit).not.toBe(first.sourceCommit); const pinned = await work.create({ repository: source.workspace, allowLocalRepository: true, targetBranch: 'release/v1', baseCommit: first.sourceCommit, root, runId: 'pinned', }); expect(pinned.baseCommit).toBe(first.sourceCommit); const restored = await work.restore({ checkpoint: first, repository: source.workspace, allowLocalRepository: true, root, runId: 'restored', }); expect(await work.head(restored.workspace)).toBe(first.sourceCommit); expect(restored.baseCommit).toBe(source.baseCommit); }); it('pushes a verified candidate through the bare integration cache, including caches created as mirrors', async () => { const root = await temporary(), work = new GitWorkspace(); const seed = await work.create({ root, runId: 'seed' }); const remote = path.join(root, 'remote.git'); await git(root, ['clone', '--bare', seed.workspace, remote]); const integration = path.join(root, 'integrations', 'project.git'); for (const [round, legacyMirror] of [ [1, false], [2, true], ] as const) { const run = await work.create({ root, runId: `run-${round}`, repository: remote, allowLocalRepository: true }); await writeFile(path.join(run.workspace, 'feature.txt'), `round ${round}`); const checkpoint = await work.checkpoint(run.workspace, run.baseCommit, `run-${round}`, 'test'); if (legacyMirror) await git(integration, ['config', 'remote.origin.mirror', 'true']); await work.initializeIntegration({ repository: integration, originalRepository: remote, allowLocalRepository: true, workspace: run.workspace, sourceCommit: checkpoint.sourceCommit, baseCommit: checkpoint.baseCommit, targetRef: 'refs/heads/main', }); const expected = await work.head(integration, 'refs/heads/main'); expect(expected).toBe(run.baseCommit); await work.pushVerifiedCandidate({ repository: integration, targetRef: 'refs/heads/main', expectedTargetCommit: expected, candidateCommit: checkpoint.sourceCommit, verifiedCommit: checkpoint.sourceCommit, }); expect(await work.head(remote, 'refs/heads/main')).toBe(checkpoint.sourceCommit); } }); it('uses the verified commit itself when the target has not moved, and merges otherwise', async () => { const root = await temporary(), work = new GitWorkspace(); const seed = await work.create({ root, runId: 'seed' }); await writeFile(path.join(seed.workspace, 'a.txt'), 'a\n'); await writeFile(path.join(seed.workspace, 'b.txt'), 'b\n'); await work.checkpoint(seed.workspace, seed.baseCommit, 'seed', 'test'); const remote = path.join(root, 'remote.git'); await git(root, ['clone', '--bare', seed.workspace, remote]); const integration = path.join(root, 'integrations', 'project.git'); const change = async (runId: string, file: string, text: string) => { const run = await work.create({ root, runId, repository: remote, allowLocalRepository: true }); await writeFile(path.join(run.workspace, file), text); return { run, checkpoint: await work.checkpoint(run.workspace, run.baseCommit, runId, 'test') }; }; const first = await change('first', 'a.txt', 'first\n'); const second = await change('second', 'b.txt', 'second\n'); const conflicting = await change('third', 'a.txt', 'third\n'); const integrate = async ({ run, checkpoint }: Awaited>, attempt: string) => { await work.initializeIntegration({ repository: integration, originalRepository: remote, allowLocalRepository: true, workspace: run.workspace, sourceCommit: checkpoint.sourceCommit, baseCommit: checkpoint.baseCommit, targetRef: 'refs/heads/main', }); const expected = await work.head(integration, 'refs/heads/main'); const candidate = await work.createCandidate({ repository: integration, path: path.join(root, attempt), targetRef: 'refs/heads/main', expectedTargetCommit: expected, sourceCommit: checkpoint.sourceCommit, }); return { expected, candidate }; }; const fastForward = await integrate(first, 'candidate-1'); expect(fastForward.candidate).toMatchObject({ commit: first.checkpoint.sourceCommit, fastForward: true }); await work.pushVerifiedCandidate({ repository: integration, targetRef: 'refs/heads/main', expectedTargetCommit: fastForward.expected, candidateCommit: first.checkpoint.sourceCommit, verifiedCommit: first.checkpoint.sourceCommit, }); const merged = await integrate(second, 'candidate-2'); expect(merged.candidate.fastForward).toBe(false); expect(merged.candidate.commit).not.toBe(second.checkpoint.sourceCommit); expect(merged.candidate.baseCommit).toBe(first.checkpoint.sourceCommit); // The merge is checkpointed in its worktree, whose .git is a file pointing into the integration cache. const mergedCheckpoint = await work.checkpoint( path.join(root, 'candidate-2'), merged.candidate.baseCommit, 'second', 'test', ); expect(mergedCheckpoint).toMatchObject({ sourceCommit: merged.candidate.commit, baseCommit: merged.expected }); // Someone else pushes meanwhile: a push based on the old tip is reported as a moved target. const other = await change('other', 'c.txt', 'other\n'); await git(other.run.workspace, ['push', 'origin', 'HEAD:refs/heads/main']); await expect( work.pushVerifiedCandidate({ repository: integration, targetRef: 'refs/heads/main', expectedTargetCommit: merged.expected, candidateCommit: merged.candidate.commit, verifiedCommit: merged.candidate.commit, }), ).rejects.toMatchObject({ code: 'STALE_TARGET' }); const tip = other.checkpoint.sourceCommit; // A conflict names the files and leaves no half-merged worktree behind. const conflict = integrate(conflicting, 'candidate-3'); await expect(conflict).rejects.toMatchObject({ code: 'MERGE_CONFLICT', paths: ['a.txt'], targetCommit: tip }); await expect( executeCommand({ executable: 'test', args: ['-e', path.join(root, 'candidate-3')] }), ).resolves.toMatchObject({ exitCode: 1, }); // The repair round merges the current target and leaves the markers to the agent. const repair = await work.restore({ checkpoint: conflicting.checkpoint, repository: remote, allowLocalRepository: true, root, runId: 'third-repair', }); const started = await work.mergeTarget(repair.workspace, 'main'); expect(started).toEqual({ targetCommit: tip, conflicts: ['a.txt'] }); await writeFile(path.join(repair.workspace, 'a.txt'), 'first and third\n'); const resolved = await work.checkpoint(repair.workspace, started.targetCommit, 'third', 'test'); await git(repair.workspace, ['merge-base', '--is-ancestor', first.checkpoint.sourceCommit, resolved.sourceCommit]); expect(resolved.baseCommit).toBe(tip); // The checkpoint is relative to the new tip: only this run's resolution, not the other changes. expect(resolved.patch).toContain('+first and third'); expect(resolved.patch).not.toContain('c.txt'); }); it('keeps installed dependencies out of checkpoints', async () => { const root = await temporary(), work = new GitWorkspace(); const run = await work.create({ root, runId: 'install' }); await writeFile(path.join(run.workspace, '.gitignore'), 'dist/\n'); await work.checkpoint(run.workspace, run.baseCommit, 'install', 'test'); await executeCommand({ executable: 'mkdir', args: ['-p', path.join(run.workspace, 'node_modules', 'left-pad')] }); await writeFile(path.join(run.workspace, 'node_modules', 'left-pad', 'index.js'), 'module.exports = 1;'); await writeFile(path.join(run.workspace, 'install[1].log'), 'installed'); expect((await work.excludeUntracked(run.workspace)).sort()).toEqual(['install[1].log', 'node_modules/']); await writeFile(path.join(run.workspace, 'feature.txt'), 'agent change'); const checkpoint = await work.checkpoint(run.workspace, run.baseCommit, 'install', 'test'); expect(checkpoint.patch).toContain('feature.txt'); expect(checkpoint.patch).not.toContain('left-pad'); expect(checkpoint.patch).not.toContain('install[1].log'); }); it('lists a moved file at both places, and puts files back literally as a commit has them', async () => { const root = await temporary(), work = new GitWorkspace(); const run = await work.create({ root, runId: 'scope' }); const file = (name: string) => path.join(run.workspace, name); await mkdir(file('backend')); await writeFile(file('backend/server.go'), 'package main\n\nfunc main() {}\n// long enough to count as moved\n'); await writeFile(file('backend/keep.go'), 'package main\n'); await writeFile(file('app.js'), 'frontend\n'); const base = await work.checkpoint(run.workspace, run.baseCommit, 'scope', 'test'); // A backend file moved to a frontend place, a file named like a pattern, and one more file. await mkdir(file('src')); await rename(file('backend/server.go'), file('src/server.go')); await writeFile(file('backend/*.go'), 'named like a pattern\n'); await writeFile(file('backend/new.go'), 'package main\n'); await writeFile(file('app.js'), 'frontend changed\n'); const change = await work.checkpoint(run.workspace, base.sourceCommit, 'scope', 'test'); expect((await work.changedPaths(run.workspace, base.sourceCommit, change.sourceCommit)).sort()).toEqual([ 'app.js', 'backend/*.go', 'backend/new.go', 'backend/server.go', 'src/server.go', ]); await work.restorePaths(run.workspace, base.sourceCommit, ['backend/*.go', 'backend/new.go', 'backend/server.go']); expect(await readFile(file('backend/server.go'), 'utf8')).toContain('func main()'); expect(existsSync(file('backend/*.go'))).toBe(false); expect(existsSync(file('backend/new.go'))).toBe(false); expect(existsSync(file('backend/keep.go'))).toBe(true); // A path that is not there is taken literally, never as a pattern matching other files. await work.restorePaths(run.workspace, base.sourceCommit, ['backend/k*.go', 'backend/k?ep.go']); expect(existsSync(file('backend/keep.go'))).toBe(true); const repaired = await work.checkpoint(run.workspace, base.sourceCommit, 'scope', 'test'); expect((await work.changedPaths(run.workspace, base.sourceCommit, repaired.sourceCommit)).sort()).toEqual([ 'app.js', 'src/server.go', ]); }); it('restores an incremental checkpoint from the repository base and rejects a missing base', async () => { const root = await temporary(), work = new GitWorkspace(); const seed = await work.create({ root, runId: 'seed' }); const remote = path.join(root, 'remote.git'); await git(root, ['clone', '--bare', seed.workspace, remote]); const run = await work.create({ root, runId: 'run', repository: remote, allowLocalRepository: true }); await writeFile(path.join(run.workspace, 'a.txt'), 'first'); await work.checkpoint(run.workspace, run.baseCommit, 'run', 'test'); await writeFile(path.join(run.workspace, 'b.txt'), 'second'); const checkpoint = await work.checkpoint(run.workspace, run.baseCommit, 'run', 'test'); const restored = await work.restore({ checkpoint, repository: remote, allowLocalRepository: true, root: path.join(root, 'verifier'), runId: 'restored', }); expect(await work.head(restored.workspace)).toBe(checkpoint.sourceCommit); const unchanged = await work.checkpoint(restored.workspace, checkpoint.sourceCommit, 'restored', 'test'); expect(unchanged.gitBundleBase64).toBeUndefined(); const elsewhere = path.join(root, 'unrelated.git'); await git(root, ['init', '--bare', elsewhere]); await expect( work.restore({ checkpoint, repository: elsewhere, allowLocalRepository: true, root: path.join(root, 'verifier'), runId: 'unrelated', }), ).rejects.toThrow(); }); it('creates an immutable review branch and reconciles retries without advancing the target branch', async () => { const root = await temporary(), work = new GitWorkspace(); const source = await work.create({ root, runId: 'source' }); const clone = await work.create({ root, runId: 'review', repository: source.workspace, allowLocalRepository: true, targetBranch: 'main', }); await writeFile(path.join(clone.workspace, 'review.txt'), 'review candidate'); const candidate = await work.checkpoint(clone.workspace, clone.baseCommit, 'review', 'test'); const request = { repository: clone.workspace, runId: 'review', candidateCommit: candidate.sourceCommit, verifiedCommit: candidate.sourceCommit, }; const branch = await work.pushReviewBranch(request); expect(branch).toBe(`wishforge/review/${candidate.sourceCommit}`); expect(await work.pushReviewBranch(request)).toBe(branch); expect(await work.head(source.workspace, 'refs/heads/main')).toBe(source.baseCommit); expect(await work.head(source.workspace, `refs/heads/${branch}`)).toBe(candidate.sourceCommit); await git(source.workspace, ['update-ref', `refs/heads/${branch}`, source.baseCommit]); await expect(work.pushReviewBranch(request)).rejects.toMatchObject({ code: 'REVIEW_BRANCH_CONFLICT' }); expect(await work.head(source.workspace, 'refs/heads/main')).toBe(source.baseCommit); }); it.each([ '-force', 'HEAD', 'main..other', 'main^{commit}', 'feature/.hidden', 'feature/end.', 'feature/a.lock/b', 'feature//name', 'refs/heads/main:evil', 'main\nother', ])('rejects unsafe branch %s consistently before Git execution', async branch => { const execute = vi.fn(); const work = new GitWorkspace(execute); expect(() => requireBranchName(branch)).toThrow(); expect(projectInput.safeParse({ name: 'Invalid branch', targetBranch: branch }).success).toBe(false); await expect( work.create({ repository: 'https://example.org/repo.git', targetBranch: branch, root: '/unused', runId: 'run' }), ).rejects.toMatchObject({ code: 'INVALID_REF' }); expect(execute).not.toHaveBeenCalled(); }); it('rejects unsupported SSH and credential/query-bearing URLs before cloning', async () => { const execute = vi.fn(), work = new GitWorkspace(execute); for (const repository of ['ssh://git@github.com/org/repo.git', 'git@github.com:org/repo.git']) await expect(work.create({ repository, root: '/unused', runId: 'run' })).rejects.toMatchObject({ code: 'REPOSITORY_TRANSPORT_UNSUPPORTED', }); for (const repository of [ 'https://user:password@example.org/repo.git', 'https://example.org/repo.git?access_token=secret', 'https://example.org/repo.git#main', 'file:///tmp/repo', ' https://example.org/repo', ]) await expect(work.create({ repository, root: '/unused', runId: 'run' })).rejects.toThrow(); expect(execute).not.toHaveBeenCalled(); expect( validateRepositoryUrl('http://127.0.0.1:4504/repo.git', { allowLocalHttp: true, production: false }).protocol, ).toBe('http:'); expect(() => validateRepositoryUrl('http://127.0.0.1:4504/repo.git', { allowLocalHttp: true, production: true }), ).toThrow(); expect(() => validateRepositoryUrl('http://remote.example/repo.git', { allowLocalHttp: true, production: false }), ).toThrow(); }); }); describe('planted Git configuration cannot run commands during trusted export', () => { // The agent has file tools in its workspace, so it can write .git/config and .gitattributes. // None of its drivers may run as the worker during checkpoint or merge. async function workspaceWith(config: string, attributes = '* filter=x diff=d merge=m\n') { const root = await temporary(); const work = new GitWorkspace(); const prepared = await work.create({ root, runId: 'run' }); const ran = path.join(root, 'driver-ran'); await writeFile( path.join(prepared.workspace, '.git', 'config'), `${( await executeCommand({ executable: 'git', args: ['config', '--list', '--local'], cwd: prepared.workspace }) ).stdout .split('\n') .filter(Boolean) .map(line => { const [key, ...rest] = line.split('='); const dot = key!.lastIndexOf('.'); return `[${key!.slice(0, dot)}]\n\t${key!.slice(dot + 1)} = ${rest.join('=')}`; }) .join('\n')}\n${config.replaceAll('RAN', ran)}\n`, ); await writeFile(path.join(prepared.workspace, '.gitattributes'), attributes); await writeFile(path.join(prepared.workspace, 'app.txt'), 'the agent edited this\n'); return { root, work, prepared, ran }; } // Git runs a driver via `sh -c ` and strips the config value's own quotes, so a bare // `touch ` reliably creates the marker when the vector fires (extra %O/%A args are // harmless), making each test fail if the hardening is removed. for (const [name, config] of [ ['a clean filter', '[filter "x"]\n\tclean = touch RAN'], ['a diff driver', '[diff "d"]\n\tcommand = touch RAN'], ['a merge driver', '[merge "m"]\n\tdriver = touch RAN %O %A %B'], ['core.fsmonitor', '[core]\n\tfsmonitor = touch RAN'], ['an include', '[include]\n\tpath = evil-config'], ] as const) { it(`neutralizes ${name} before the checkpoint`, async () => { const f = await workspaceWith(config); if (name === 'an include') // A relative include path resolves from .git/, so plant the included file there. await writeFile( path.join(f.prepared.workspace, '.git', 'evil-config'), `[filter "x"]\n\tclean = touch ${f.ran}\n`, ); const checkpoint = await f.work.checkpoint(f.prepared.workspace, f.prepared.baseCommit, 'run', 'codex'); expect(existsSync(f.ran)).toBe(false); // The agent's actual edit still travels in the checkpoint. expect(checkpoint.patch).toContain('the agent edited this'); // The config was reduced to the safe allowlist: the driver and any include are gone. const left = await readFile(path.join(f.prepared.workspace, '.git', 'config'), 'utf8'); expect(left).not.toMatch(/\btouch\b/); expect(left).not.toMatch(/\[include\]/); expect(left).toMatch(/\[core\]/); }); } it('refuses a workspace whose .git was turned into a pointer file it did not make', async () => { const f = await workspaceWith(''); const moved = path.join(f.root, 'moved-git'); await rename(path.join(f.prepared.workspace, '.git'), moved); await writeFile(path.join(f.prepared.workspace, '.git'), `gitdir: ${moved}\n`); await expect(f.work.checkpoint(f.prepared.workspace, f.prepared.baseCommit, 'run', 'codex')).rejects.toMatchObject({ code: 'ENOTDIR', }); }); it('drops a planted url.insteadOf transport redirect but keeps the clone origin', async () => { const root = await temporary(); const work = new GitWorkspace(); const origin = await work.create({ root, runId: 'origin' }); await writeFile(path.join(origin.workspace, 'seed.txt'), 'seed\n'); await work.checkpoint(origin.workspace, origin.baseCommit, 'origin', 'codex'); const run = await work.create({ repository: origin.workspace, allowLocalRepository: true, root, runId: 'run' }); await writeFile( path.join(run.workspace, '.git', 'config'), (await readFile(path.join(run.workspace, '.git', 'config'), 'utf8')) + '[url "https://attacker.example/"]\n\tinsteadOf = ' + origin.workspace + '\n', ); await writeFile(path.join(run.workspace, 'app.txt'), 'edited\n'); await work.checkpoint(run.workspace, run.baseCommit, 'run', 'codex'); const left = await readFile(path.join(run.workspace, '.git', 'config'), 'utf8'); expect(left).not.toContain('attacker.example'); expect(left).toMatch(/\[remote "origin"\]/); expect(left).toContain(origin.workspace); // the real remote.origin.url is untouched }); it('neutralizes a merge driver before a repair-round mergeTarget, and still merges and conflicts', async () => { const root = await temporary(); const work = new GitWorkspace(); const base = await work.create({ root, runId: 'base', targetBranch: 'main' }); await writeFile(path.join(base.workspace, 'shared.txt'), 'target side\n'); const moved = await work.checkpoint(base.workspace, base.baseCommit, 'base', 'codex'); // A run that branched from the original base, with a planted merge driver. const run = await work.create({ repository: base.workspace, allowLocalRepository: true, targetBranch: 'main', baseCommit: base.baseCommit, root, runId: 'run', }); // Commit the run side directly (not via checkpoint, which would harden first), then plant the // driver, so mergeTarget's own hardening is what must neutralize it. await writeFile(path.join(run.workspace, '.gitattributes'), 'shared.txt merge=m\n'); await writeFile(path.join(run.workspace, 'shared.txt'), 'run side\n'); await git(run.workspace, ['add', '--all']); await git(run.workspace, ['-c', 'user.name=x', '-c', 'user.email=x@x', 'commit', '-m', 'run side']); const ran = path.join(root, 'merge-ran'); await writeFile( path.join(run.workspace, '.git', 'config'), (await readFile(path.join(run.workspace, '.git', 'config'), 'utf8')) + `[merge "m"]\n\tdriver = touch ${ran} %O %A %B\n`, ); const merged = await work.mergeTarget(run.workspace, 'main'); expect(existsSync(ran)).toBe(false); expect(merged.targetCommit).toBe(moved.sourceCommit); // A real conflict is still reported (Git's own resolver ran, not the planted driver). expect(merged.conflicts).toContain('shared.txt'); }); });