From 198f0280abe66d4cdc7a4ca486167571502b525d Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Fri, 4 Dec 2026 18:03:57 -0500 Subject: [PATCH 1/2] feat(worker): Capture bounded managed worktree checkpoints --- packages/code/src/worktree-checkpoint.test.ts | 488 ++++++++++++++++++ packages/code/src/worktree-checkpoint.ts | 422 +++++++++++++++ 2 files changed, 910 insertions(+) create mode 100644 packages/code/src/worktree-checkpoint.test.ts create mode 100644 packages/code/src/worktree-checkpoint.ts diff --git a/packages/code/src/worktree-checkpoint.test.ts b/packages/code/src/worktree-checkpoint.test.ts new file mode 100644 index 00000000..3b778521 --- /dev/null +++ b/packages/code/src/worktree-checkpoint.test.ts @@ -0,0 +1,488 @@ +import assert from 'node:assert/strict'; +import { execFile, execFileSync } from 'node:child_process'; +import { + mkdtemp, + readFile, + realpath, + rm, + writeFile, + mkdir, + symlink, + link, + rename, + chmod, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; + +import { systemGitExecutable } from './linked-worktree-git-guard.js'; +import { verifyLinkedWorktree } from './linked-worktrees.js'; +import { captureWorkspaceRootIdentity } from './root-identity.js'; +import { captureWorktreeCheckpoint } from './worktree-checkpoint.js'; + +import type { TestContext } from 'node:test'; +import type { CheckpointGit } from './worktree-checkpoint.js'; + +const gitExecutable = await systemGitExecutable(); +const env = { + PATH: process.env.PATH, + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_TERMINAL_PROMPT: '0', + GIT_NO_LAZY_FETCH: '1', +}; +const gitOptions = [ + '--no-optional-locks', + '--no-replace-objects', + '-c', + 'core.fsmonitor=false', + '-c', + 'core.hooksPath=/dev/null', +]; + +async function fixture(t: TestContext) { + const temporary = await mkdtemp(join(tmpdir(), 'worktree-checkpoint-')); + t.after(() => rm(temporary, { force: true, recursive: true })); + const checkout = await realpath(temporary); + const root = join(checkout, '.worktrees', 'lane'); + const setup = (cwd: string, ...args: string[]) => + execFileSync(gitExecutable, [...gitOptions, ...args], { cwd, env }) + .toString() + .trim(); + setup(checkout, 'init', '-q'); + await writeFile(join(checkout, 'file'), 'base'); + await writeFile(join(checkout, 'removed'), 'base'); + await writeFile(join(checkout, 'unstaged-delete'), 'base'); + await writeFile(join(checkout, 'mode'), '#!/bin/sh\n'); + await writeFile(join(checkout, 'tracked-secret'), 'placeholder'); + await writeFile(join(checkout, 'ignored-deletion'), 'placeholder'); + await writeFile(join(checkout, '.gitignore'), 'ignored/\n'); + setup(checkout, 'add', '.'); + setup( + checkout, + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'commit.gpgsign=false', + 'commit', + '-qm', + 'base', + ); + setup(checkout, 'worktree', 'add', '-q', '--detach', root); + const pin = (head: string) => `refs/librechat/checkpoints/${head}`; + const head = setup(root, 'rev-parse', 'HEAD'); + setup(checkout, 'update-ref', pin(head), head); + await mkdir(join(root, 'ignored')); + const checkoutIdentity = await captureWorkspaceRootIdentity(checkout); + const lane = await verifyLinkedWorktree(checkout, 'lane', checkoutIdentity); + const current = { + ownerScope: 'a'.repeat(64), + checkout: checkoutIdentity, + common: await captureWorkspaceRootIdentity(lane.commonGitDir), + registration: await captureWorkspaceRootIdentity( + join(lane.commonGitDir, 'worktrees', 'lane'), + ), + lane: lane.identity, + }; + const owner = { ...current }; + const git: CheckpointGit = (args, { maxBytes, signal, input }) => + new Promise((resolve, reject) => { + const child = execFile( + gitExecutable, + [...gitOptions, ...args], + { + cwd: root, + env, + encoding: 'buffer', + maxBuffer: maxBytes, + signal, + }, + (error, stdout) => { + if ( + !error || + (args[0] === 'check-ignore' && + error.code === 1 && + stdout.length === 0) + ) + resolve(stdout); + else reject(error); + }, + ); + child.stdin?.on('error', reject); + child.stdin?.end(input); + }); + return { checkout, root, current, owner, git, setup, pin }; +} + +test('captures distinct staged and working layers without touching source or sibling', async t => { + const { checkout, root, current, owner, git, setup } = await fixture(t); + const sibling = join(checkout, '.worktrees', 'sibling'); + setup(checkout, 'worktree', 'add', '-q', '--detach', sibling); + await writeFile(join(sibling, 'file'), 'sibling'); + await writeFile(join(root, 'file'), Buffer.from([0, 255, 1])); + await writeFile(join(root, '.env.local'), 'excluded'); + await writeFile(join(root, 'tracked-secret'), 'excluded'); + await writeFile( + join(root, '.gitignore'), + 'ignored/\ntracked-secret\nignored-deletion\n', + ); + setup(root, 'add', '--', 'file', '.env.local', 'tracked-secret'); + setup(root, 'rm', '-q', 'removed', 'ignored-deletion'); + await writeFile(join(root, 'file'), 'working'); + await writeFile(join(root, 'new\tline\n'), 'untracked'); + await writeFile(join(root, 'ignored', 'token'), 'ignored'); + await rm(join(root, 'unstaged-delete')); + await chmod(join(root, 'mode'), 0o755); + await symlink(join(checkout, 'tracked-secret'), join(root, 'outside-link')); + await symlink('missing', join(root, 'dangling-link')); + await link( + join(checkout, 'tracked-secret'), + join(root, 'outside-hardlink'), + ); + if (process.platform === 'linux') + execFileSync('mkfifo', [join(root, 'pipe')]); + + const head = setup(root, 'rev-parse', 'HEAD'); + const index = join(current.registration.path, 'index'); + const before = await readFile(index); + const captured = await captureWorktreeCheckpoint(owner, current, git); + assert.deepEqual(captured, { + head, + staged: [ + { path: 'removed', mode: null }, + { path: 'file', mode: '100644', bytes: Buffer.from([0, 255, 1]) }, + ], + working: [ + { + path: '.gitignore', + mode: '100644', + bytes: Buffer.from( + 'ignored/\ntracked-secret\nignored-deletion\n', + ), + }, + { path: 'file', mode: '100644', bytes: Buffer.from('working') }, + { path: 'mode', mode: '100755', bytes: Buffer.from('#!/bin/sh\n') }, + { path: 'unstaged-delete', mode: null }, + { + path: 'new\tline\n', + mode: '100644', + bytes: Buffer.from('untracked'), + }, + ], + }); + assert.deepEqual(await readFile(index), before); + assert.equal(setup(root, 'rev-parse', 'HEAD'), head); + assert.equal(await readFile(join(root, 'file'), 'utf8'), 'working'); + assert.equal(await readFile(join(sibling, 'file'), 'utf8'), 'sibling'); + + // Test-only materialization; this is not the worker restore path. + const replay = join(checkout, '.worktrees', 'round-trip'); + assert.ok(captured); + setup(checkout, 'worktree', 'add', '-q', '--detach', replay, captured.head); + for (const layer of [captured.staged, captured.working]) { + for (const change of layer) { + const path = join(replay, change.path); + if (change.mode === null) await rm(path); + else { + await writeFile(path, change.bytes); + await chmod(path, change.mode === '100755' ? 0o755 : 0o644); + } + } + if (layer === captured.staged) setup(replay, 'add', '-A'); + } + assert.deepEqual( + execFileSync(gitExecutable, ['show', ':file'], { cwd: replay, env }), + Buffer.from([0, 255, 1]), + ); + assert.equal(await readFile(join(replay, 'file'), 'utf8'), 'working'); + assert.equal( + await readFile(join(replay, 'new\tline\n'), 'utf8'), + 'untracked', + ); + assert.equal( + setup(replay, 'diff', '--cached', '--name-only'), + 'file\nremoved', + ); + assert.equal( + setup(replay, 'diff', '--name-only'), + '.gitignore\nfile\nmode\nunstaged-delete', + ); +}); + +test('refuses a manual worktree, wrong ownership record, or replaced incarnation before reading Git', async t => { + const { current, owner, root } = await fixture(t); + let calls = 0; + const git: CheckpointGit = async () => { + calls++; + return Buffer.alloc(0); + }; + assert.equal( + await captureWorktreeCheckpoint(undefined, current, git), + undefined, + ); + assert.equal( + await captureWorktreeCheckpoint( + { ...owner, ownerScope: 'invalid' }, + current, + git, + ), + undefined, + ); + assert.equal( + await captureWorktreeCheckpoint( + { ...owner, ownerScope: 'b'.repeat(64) }, + current, + git, + ), + undefined, + ); + for (const field of [ + 'checkout', + 'common', + 'registration', + 'lane', + ] as const) { + assert.equal( + await captureWorktreeCheckpoint( + { ...owner, [field]: { ...owner[field], ino: '-1' } }, + current, + git, + ), + undefined, + ); + } + await rename(root, `${root}-old`); + await mkdir(root); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); + assert.equal(calls, 0); +}); + +test('a cancelled, ambiguous, or oversized capture leaves the previous in-memory capture unchanged', async t => { + const { root, current, owner, git, setup } = await fixture(t); + const prior = await captureWorktreeCheckpoint(owner, current, git); + assert.deepEqual(prior, { + head: setup(root, 'rev-parse', 'HEAD'), + staged: [], + working: [], + }); + let calls = 0; + const cancelled: CheckpointGit = async () => { + calls++; + return Buffer.alloc(0); + }; + assert.equal( + await captureWorktreeCheckpoint( + owner, + current, + cancelled, + AbortSignal.abort(), + ), + undefined, + ); + assert.equal(calls, 0); + assert.equal( + await captureWorktreeCheckpoint( + owner, + current, + async (_args, { maxBytes }) => Buffer.alloc(maxBytes + 1), + ), + undefined, + ); + const race: CheckpointGit = async (args, limits) => { + if (args[1] === '-v' && ++calls === 2) { + await writeFile(join(root, 'file'), 'new index during capture'); + setup(root, 'add', 'file'); + } + return git(args, limits); + }; + assert.equal( + await captureWorktreeCheckpoint(owner, current, race), + undefined, + ); + await writeFile(join(root, 'large'), Buffer.alloc(2 * 1024 * 1024 + 1)); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); + await rm(join(root, 'large')); + for (let i = 0; i < 5; i++) + await writeFile( + join(root, `large-${i}`), + Buffer.alloc(2 * 1024 * 1024), + ); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); + assert.deepEqual(prior, { + head: setup(root, 'rev-parse', 'HEAD'), + staged: [], + working: [], + }); +}); + +test('refuses an unmerged index instead of recording a deceptively clean lane', async t => { + const { root, current, owner, git, setup } = await fixture(t); + const blob = setup(root, 'rev-parse', 'HEAD:file'); + execFileSync( + gitExecutable, + [...gitOptions, 'update-index', '--index-info'], + { + cwd: root, + env, + input: `0 ${'0'.repeat(blob.length)}\tfile\n100644 ${blob} 1\tfile\n100644 ${blob} 2\tfile\n`, + }, + ); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); +}); + +test('refuses an intent-to-add entry rather than inventing a staged empty file', async t => { + const { root, current, owner, git, setup } = await fixture(t); + await writeFile(join(root, 'intent'), 'unstaged'); + setup(root, 'add', '-N', 'intent'); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); +}); + +test('requires a direct baseline retention ref and does not silently recreate one', async t => { + const { root, current, owner, git, setup, pin } = await fixture(t); + const head = setup(root, 'rev-parse', 'HEAD'); + const ref = pin(head); + const captured = await captureWorktreeCheckpoint(owner, current, git); + assert.equal(captured?.head, head); + setup(root, 'update-ref', '-d', ref); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); + assert.equal(setup(root, 'for-each-ref', '--format=%(refname)', ref), ''); + setup(root, 'symbolic-ref', ref, 'HEAD'); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); + setup(root, 'symbolic-ref', '--delete', ref); + setup(root, 'update-ref', ref, head); + let inspected = false; + const lost: CheckpointGit = async (args, limits) => { + if (args[0] === 'for-each-ref') { + if (inspected) setup(root, 'update-ref', '-d', ref); + inspected = true; + } + return git(args, limits); + }; + assert.equal( + await captureWorktreeCheckpoint(owner, current, lost), + undefined, + ); +}); + +test('a retained detached commit survives lane removal and pruning', async t => { + const { checkout, root, current, owner, git, setup, pin } = + await fixture(t); + setup( + root, + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'commit.gpgsign=false', + 'commit', + '--allow-empty', + '-qm', + 'detached', + ); + const head = setup(root, 'rev-parse', 'HEAD'); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); + setup(root, 'update-ref', pin(head), head); + assert.equal( + (await captureWorktreeCheckpoint(owner, current, git))?.head, + head, + ); + setup(checkout, 'worktree', 'remove', root); + setup( + checkout, + 'reflog', + 'expire', + '--expire=now', + '--expire-unreachable=now', + '--all', + ); + setup(checkout, 'prune', '--expire=now'); + assert.equal(setup(checkout, 'cat-file', '-t', head), 'commit'); + setup(checkout, 'update-ref', '-d', pin(head)); + setup(checkout, 'prune', '--expire=now'); + assert.throws(() => + execFileSync(gitExecutable, ['cat-file', '-t', head], { + cwd: checkout, + env, + stdio: 'pipe', + }), + ); +}); + +test('rejects unsafe inventory paths before retrieving blobs and refuses tracked link replacements', async t => { + const { checkout, root, current, owner, git } = await fixture(t); + for (const path of [ + '../file', + '/file', + 'dir/../file', + 'dir\\file', + 'dir//file', + ':file', + ]) { + const unsafe: CheckpointGit = (args, limits) => + args[0] === 'ls-tree' + ? Promise.resolve( + Buffer.from(`100644 blob ${'1'.repeat(40)}\t${path}\0`), + ) + : git(args, limits); + assert.equal( + await captureWorktreeCheckpoint(owner, current, unsafe), + undefined, + ); + } + await rm(join(root, 'file')); + await symlink(join(checkout, 'file'), join(root, 'file')); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); +}); + +test('rejects oversized inventories and non-UTF-8 names', async t => { + const { current, owner, git } = await fixture(t); + const invalid = [ + Buffer.from( + Array.from({ length: 4097 }, (_, i) => `file-${i}\0`).join(''), + ), + Buffer.from([0xff, 0]), + Buffer.from('unterminated'), + Buffer.from(`${'a'.repeat(1025)}\0`), + ]; + for (const bytes of invalid) { + const runner: CheckpointGit = (args, limits) => + args[0] === 'ls-files' && args.includes('--others') + ? Promise.resolve(bytes) + : git(args, limits); + assert.equal( + await captureWorktreeCheckpoint(owner, current, runner), + undefined, + ); + } +}); diff --git a/packages/code/src/worktree-checkpoint.ts b/packages/code/src/worktree-checkpoint.ts new file mode 100644 index 00000000..57766558 --- /dev/null +++ b/packages/code/src/worktree-checkpoint.ts @@ -0,0 +1,422 @@ +import { createHash } from 'node:crypto'; +import { constants } from 'node:fs'; +import { join } from 'node:path'; +import { TextDecoder } from 'node:util'; + +import { lstat, open, realpath, withWorkspaceRoot } from './root-access.js'; +import { matchesWorkspaceRoot } from './root-identity.js'; + +import type { WorkspaceRootIdentity } from './root-identity.js'; + +/** A trusted record of explicit creation, not derived from the lane name or a tool request. */ +export interface CheckpointOwner { + ownerScope: string; + checkout: WorkspaceRootIdentity; + common: WorkspaceRootIdentity; + registration: WorkspaceRootIdentity; + lane: WorkspaceRootIdentity; +} + +export type CheckpointGit = ( + args: readonly string[], + limits: { maxBytes: number; signal: AbortSignal; input?: Buffer }, +) => Promise; + +type Mode = '100644' | '100755'; +type Change = + | { path: string; mode: Mode; bytes: Buffer } + | { path: string; mode: null }; +type Entry = { mode: string; oid: string }; + +export interface WorktreeCheckpoint { + /** A publisher must keep the worker-owned retention ref alive for the artifact lifetime. */ + head: string; + /** Ordered layers: HEAD → index → working copy. Untracked files appear only in the second layer. */ + staged: Change[]; + working: Change[]; +} + +const maxInventory = 512 * 1024; +const maxPaths = 4096; +const maxFile = 2 * 1024 * 1024; +const maxPayload = 8 * 1024 * 1024; +const maxScan = 64 * 1024 * 1024; +const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + +function unavailable(): never { + throw new Error('Worktree checkpoint is unavailable'); +} + +function records(bytes: Buffer): string[] { + if (bytes.length === 0) return []; + if (bytes.at(-1) !== 0) unavailable(); + const entries = utf8.decode(bytes.subarray(0, -1)).split('\0'); + if (entries.length > maxPaths) unavailable(); + return entries; +} + +function allowed(path: string): boolean { + if ( + Buffer.byteLength(path) > 1024 || + path.includes('\\') || + path.includes(':') + ) + unavailable(); + const parts = path.toLowerCase().split('/'); + if (parts.some(part => !part || part === '.' || part === '..')) + unavailable(); + // Ignore rules are the primary exclusion. These names are excluded even if tracked or not ignored. + return !parts.some(part => + /^(?:\.git|\.worktrees|\.env(?:\..*)?|\.npmrc|\.pypirc|\.netrc|\.ssh|\.aws|\.gnupg|\.cache|\.npm-cache|node_modules|credentials(?:\.json)?|id_(?:rsa|ed25519)|.*\.(?:pem|key|p12|pfx))$/.test( + part, + ), + ); +} + +function mode(entry: Entry): Mode { + if (entry.mode !== '100644' && entry.mode !== '100755') unavailable(); + return entry.mode; +} + +function notFound(error: unknown): boolean { + return error instanceof Error && 'code' in error && error.code === 'ENOENT'; +} + +/** + * Capture only; never stores or publishes a checkpoint. The caller must hold the + * lane reservation, supply its verified identities and durable creation record, + * rule out concurrent detached writers/mounts, and use a read-only, confined Git + * runner bound to the same lane and Git directories (no helpers, lazy fetch, + * replacement objects or alternate write grants). None of these grants may come + * from request data. The runner must settle on cancellation and treat + * `check-ignore` exit 1 as a valid empty result. The caller must already hold a + * worker-owned refs/librechat/checkpoints/ retention ref and prevent its + * release during capture; this function never creates or extends a pin. + * Publication must separately verify settlement/cleanup and artifact retention. + * Only regular-file changes are represented. Exclusions apply to the overlay, + * not to the retained Git history. This is not a secret scanner: ordinary source + * bytes can still be sensitive. Never send these buffers as results or log them. + */ +export async function captureWorktreeCheckpoint( + owner: CheckpointOwner | undefined, + current: CheckpointOwner, + git: CheckpointGit, + signal?: AbortSignal, +): Promise { + if ( + !owner || + !/^[a-f0-9]{64}$/.test(owner.ownerScope) || + owner.ownerScope !== current.ownerScope + ) + return; + const identities = [ + current.checkout, + current.common, + current.registration, + current.lane, + ]; + const same = ( + a: WorkspaceRootIdentity, + b: WorkspaceRootIdentity, + ): boolean => a.path === b.path && a.dev === b.dev && a.ino === b.ino; + if ( + !same(owner.checkout, current.checkout) || + !same(owner.common, current.common) || + !same(owner.registration, current.registration) || + !same(owner.lane, current.lane) + ) + return; + + const active = signal + ? AbortSignal.any([signal, AbortSignal.timeout(5000)]) + : AbortSignal.timeout(5000); + const verify = async (): Promise => { + for (const identity of identities) { + if (!(await matchesWorkspaceRoot(identity.path, identity))) + unavailable(); + } + active.throwIfAborted(); + }; + const run = async ( + args: string[], + maxBytes = maxInventory, + input?: Buffer, + ): Promise => { + active.throwIfAborted(); + const bytes = await git(args, { maxBytes, signal: active, input }); + active.throwIfAborted(); + if (bytes.length > maxBytes) unavailable(); + return bytes; + }; + + try { + await verify(); + const captured = await withWorkspaceRoot( + current.lane.path, + current.lane, + async () => { + const resolveHead = async (): Promise => + (await run(['rev-parse', '--verify', 'HEAD^{commit}'], 128)) + .toString('utf8') + .trim(); + const head = await resolveHead(); + if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(head)) + unavailable(); + const ref = `refs/librechat/checkpoints/${head}`; + const pinned = async (): Promise => + ( + await run( + [ + 'for-each-ref', + '--count=1', + '--format=%(refname) %(objectname) %(symref)', + ref, + ], + 512, + ) + ).toString('utf8') === `${ref} ${head} \n`; + if (!(await pinned())) unavailable(); + const algorithm = head.length === 40 ? 'sha1' : 'sha256'; + const oid = `[a-f0-9]{${head.length}}`; + const treePattern = new RegExp( + `^([0-7]{6}) (?:blob|commit) (${oid})$`, + ); + const indexPattern = new RegExp(`^H ([0-7]{6}) (${oid}) 0$`); + const base = new Map(); + const index = new Map(); + const entries = ( + data: Buffer, + pattern: RegExp, + target: Map, + ): void => { + for (const record of records(data)) { + const tab = record.indexOf('\t'); + if (tab < 0) unavailable(); + const path = record.slice(tab + 1); + if (!allowed(path)) continue; + const fields = pattern.exec(record.slice(0, tab)); + if (!fields || target.has(path)) unavailable(); + target.set(path, { mode: fields[1]!, oid: fields[2]! }); + } + }; + entries( + await run(['ls-tree', '-r', '-z', '--full-tree', head]), + treePattern, + base, + ); + const indexArgs = ['ls-files', '-v', '--stage', '-z']; + const stagedIndex = await run(indexArgs); + // Intent-to-add entries look like staged empty blobs in ls-files --stage. + const diff = (visibility: string): Promise => + run([ + 'diff-index', + '--cached', + visibility, + '--name-only', + '-z', + '--no-renames', + '--no-ext-diff', + '--no-textconv', + '--ignore-submodules=none', + head, + '--', + ]); + if ( + !(await diff('--ita-invisible-in-index')).equals( + await diff('--ita-visible-in-index'), + ) + ) + unavailable(); + entries(stagedIndex, indexPattern, index); + const others = records( + await run([ + 'ls-files', + '-z', + '--others', + '--exclude-standard', + ]), + ).filter(allowed); + const paths = new Set([ + ...base.keys(), + ...index.keys(), + ...others, + ]); + if (paths.size > maxPaths) unavailable(); + // Include paths deleted from the index; ls-files --cached --ignored misses those. + if (paths.size) { + const input = Buffer.from( + [...paths].map(path => `./${path}\0`).join(''), + ); + if (input.length > maxInventory) unavailable(); + const ignored = records( + await run( + ['check-ignore', '--no-index', '-z', '--stdin'], + maxInventory, + input, + ), + ); + for (const record of ignored) { + const path = record.slice(2); + if (!record.startsWith('./') || !paths.has(path)) + unavailable(); + base.delete(path); + index.delete(path); + paths.delete(path); + } + } + + const staged: Change[] = []; + const working: Change[] = []; + let payload = maxPayload; + let scan = maxScan; + const keep = ( + layer: Change[], + path: string, + fileMode: Mode, + bytes: Buffer, + ): void => { + payload -= bytes.length; + if (payload < 0) unavailable(); + layer.push({ path, mode: fileMode, bytes }); + }; + for (const [path, entry] of base) { + mode(entry); + if (!index.has(path)) staged.push({ path, mode: null }); + } + for (const [path, entry] of index) { + const prior = base.get(path); + const fileMode = mode(entry); + if (prior?.oid !== entry.oid || prior.mode !== fileMode) { + const bytes = await run( + ['cat-file', 'blob', entry.oid], + Math.min(maxFile, payload) + 1, + ); + if ( + bytes.length > maxFile || + createHash(algorithm) + .update(`blob ${bytes.length}\0`) + .update(bytes) + .digest('hex') !== entry.oid + ) + unavailable(); + keep(staged, path, fileMode, bytes); + } + } + + const read = async ( + path: string, + entry?: Entry, + ): Promise => { + active.throwIfAborted(); + const absolute = join(current.lane.path, path); + const file = await (async () => { + try { + // Do not follow a symlink in place of a tracked directory or take bytes from its target. + const stat = await lstat(absolute); + if ( + !stat.isFile() || + (await realpath(absolute)) !== absolute + ) { + if (entry) unavailable(); + return; + } + return await open( + absolute, + constants.O_RDONLY | + constants.O_NOFOLLOW | + constants.O_NONBLOCK, + ); + } catch (error) { + if (notFound(error)) return; + if ( + !entry && + error instanceof Error && + 'code' in error && + error.code === 'ELOOP' + ) + return; + throw error; + } + })(); + if (!file) { + if (entry) working.push({ path, mode: null }); + return; + } + try { + const stat = await file.stat({ bigint: true }); + if ( + !stat.isFile() || + stat.nlink !== 1n || + stat.dev.toString() !== current.lane.dev + ) { + if (entry) unavailable(); + return; + } + if ( + stat.size > + BigInt( + entry ? scan : Math.min(scan, maxFile, payload), + ) + ) + unavailable(); + const size = Number(stat.size); + const hash = createHash(algorithm).update( + `blob ${size}\0`, + ); + // Hash large unchanged files without retaining them. Changed large files are unsupported. + const bytes = + size <= maxFile ? Buffer.alloc(size) : undefined; + const chunk = Buffer.alloc(Math.min(64 * 1024, size)); + for (let offset = 0; offset < size; ) { + active.throwIfAborted(); + const { bytesRead } = await file.read( + chunk, + 0, + Math.min(chunk.length, size - offset), + offset, + ); + if (!bytesRead) unavailable(); + hash.update(chunk.subarray(0, bytesRead)); + bytes?.set(chunk.subarray(0, bytesRead), offset); + offset += bytesRead; + } + scan -= size; + const after = await file.stat({ bigint: true }); + if ( + stat.size !== after.size || + stat.ctimeNs !== after.ctimeNs || + stat.mtimeNs !== after.mtimeNs + ) + unavailable(); + const fileMode = + stat.mode & 0o100n ? '100755' : '100644'; + if ( + entry?.oid === hash.digest('hex') && + entry.mode === fileMode + ) + return; + if (!bytes) unavailable(); + keep(working, path, fileMode, bytes); + } finally { + await file.close(); + } + }; + for (const [path, entry] of index) await read(path, entry); + for (const path of others) + if (!index.has(path) && paths.has(path)) await read(path); + if ( + !(await run(indexArgs)).equals(stagedIndex) || + (await resolveHead()) !== head || + !(await pinned()) + ) + unavailable(); + return { head, staged, working }; + }, + ); + await verify(); + return captured; + } catch { + // A failed advisory capture must never alter execution, fencing or the last good checkpoint. + return undefined; + } +} From 1e8a5f419be7688d9ae24e215c7088e07cb22ce0 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Fri, 4 Dec 2026 18:09:39 -0500 Subject: [PATCH 2/2] fix(worker): Reject intent-to-add for paths already in HEAD --- packages/code/src/worktree-checkpoint.test.ts | 10 ++++++++++ packages/code/src/worktree-checkpoint.ts | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/code/src/worktree-checkpoint.test.ts b/packages/code/src/worktree-checkpoint.test.ts index 3b778521..2b24f0c8 100644 --- a/packages/code/src/worktree-checkpoint.test.ts +++ b/packages/code/src/worktree-checkpoint.test.ts @@ -355,6 +355,16 @@ test('refuses an intent-to-add entry rather than inventing a staged empty file', ); }); +test('refuses a HEAD path re-added with intent-to-add', async t => { + const { root, current, owner, git, setup } = await fixture(t); + setup(root, 'rm', '--cached', 'file'); + setup(root, 'add', '-N', 'file'); + assert.equal( + await captureWorktreeCheckpoint(owner, current, git), + undefined, + ); +}); + test('requires a direct baseline retention ref and does not silently recreate one', async t => { const { root, current, owner, git, setup, pin } = await fixture(t); const head = setup(root, 'rev-parse', 'HEAD'); diff --git a/packages/code/src/worktree-checkpoint.ts b/packages/code/src/worktree-checkpoint.ts index 57766558..5c453c1a 100644 --- a/packages/code/src/worktree-checkpoint.ts +++ b/packages/code/src/worktree-checkpoint.ts @@ -212,7 +212,7 @@ export async function captureWorktreeCheckpoint( 'diff-index', '--cached', visibility, - '--name-only', + '--raw', '-z', '--no-renames', '--no-ext-diff',