diff --git a/packages/code/src/restore-overlay.ts b/packages/code/src/restore-overlay.ts new file mode 100644 index 00000000..6fdcc4ed --- /dev/null +++ b/packages/code/src/restore-overlay.ts @@ -0,0 +1,554 @@ +import { execFile } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { constants } from 'node:fs'; +import { lstat } from 'node:fs/promises'; +import { join } from 'node:path'; +import { TextDecoder } from 'node:util'; + +import { systemGitExecutable } from './linked-worktree-git-guard.js'; +import { mkdir, open, readdir, withWorkspaceRoot } from './root-access.js'; + +import type { WorkspaceRootIdentity } from './root-identity.js'; +import type { + CheckpointGit, + WorktreeCheckpoint, +} from './worktree-checkpoint.js'; + +const inventory = 512 * 1024; +const maxPaths = 4096; +const maxTree = 64 * 1024 * 1024; +const decode = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); +const excluded = + /^(?:\.env(?:\..*)?|\.npmrc|\.pypirc|\.netrc|\.ssh|\.aws|\.gnupg|\.cache|\.npm-cache|node_modules|credentials(?:\.json)?|id_(?:rsa|ed25519)|.*\.(?:pem|key|p12|pfx))$/i; + +type Change = WorktreeCheckpoint['staged'][number]; +type Mode = Exclude; +type Blob = { mode: Mode; oid: string; size: number }; +type File = Blob | { mode: Mode; bytes: Buffer }; +type Plan = { + index: ReadonlyMap; + files: ReadonlyMap; +}; + +async function statIfPresent(path: string) { + try { + return await lstat(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } +} + +function invalid(): never { + throw new Error('Unsupported worktree restore data or Git state'); +} + +function pathParts(path: string, overlay = false): string[] { + if ( + typeof path !== 'string' || + path.length > 1024 || + Buffer.byteLength(path) > 1024 || + /[\0\\:]/.test(path) || + Buffer.from(path).toString() !== path + ) + invalid(); + const parts = path.split('/'); + if ( + parts.length > 32 || + parts.some( + part => + !part || + Buffer.byteLength(part) > 255 || + /^(?:\.{1,2}|\.git|\.worktrees)$/i.test(part) || + (overlay && excluded.test(part)) + ) + ) + invalid(); + return parts; +} + +/** Validate and snapshot the decoded private artifact before the first await or target write. */ +export function restoreData(data: WorktreeCheckpoint): WorktreeCheckpoint { + if ( + !data || + typeof data.head !== 'string' || + !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(data.head) + ) + invalid(); + let bytes = 8 * 1024 * 1024; + let index = 0; + const layer = (changes: Change[]): Change[] => { + if (!Array.isArray(changes) || changes.length > maxPaths) invalid(); + const seen = new Set(); + return changes.map(change => { + if (!change) invalid(); + const { path, mode } = change; + pathParts(path, true); + if (seen.has(path)) invalid(); + seen.add(path); + index += Buffer.byteLength(path) + data.head.length + 9; + if (index > inventory) invalid(); + if (mode === null) return { path, mode }; + if ( + (mode !== '100644' && mode !== '100755') || + !Buffer.isBuffer(change.bytes) || + change.bytes.length > 2 * 1024 * 1024 || + (bytes -= change.bytes.length) < 0 + ) + invalid(); + return { path, mode, bytes: Buffer.from(change.bytes) }; + }); + }; + return { + head: data.head, + staged: layer(data.staged), + working: layer(data.working), + }; +} + +export function restoreGit(root: string): CheckpointGit { + return async (args, limits) => { + limits.signal.throwIfAborted(); + const executable = await systemGitExecutable(); + limits.signal.throwIfAborted(); + return awaitRestoreGitExit((complete) => { + const child = execFile( + executable, + [ + '--no-optional-locks', + '--no-replace-objects', + '-c', + 'core.hooksPath=/dev/null', + '-c', + 'core.fsmonitor=false', + '-c', + 'core.untrackedCache=false', + '-c', + 'core.splitIndex=false', + '-c', + 'core.fsync=loose-object,index', + '-c', + 'core.fsyncMethod=fsync', + '-c', + 'maintenance.auto=false', + '-c', + 'gc.auto=0', + ...args, + ], + { + cwd: root, + encoding: 'buffer', + maxBuffer: limits.maxBytes, + signal: limits.signal, + timeout: 5000, + killSignal: 'SIGKILL', + env: { + PATH: '/usr/bin:/bin', + LC_ALL: 'C', + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_TERMINAL_PROMPT: '0', + GIT_NO_LAZY_FETCH: '1', + GIT_ALLOW_PROTOCOL: '', + }, + }, + (error, stdout) => { + if ( + !error || + (args[0] === 'check-ignore' && + error.code === 1 && + !stdout.length) + ) + complete(undefined, stdout); + else + complete(new Error('Worktree restore Git operation failed')); + } + ); + child.stdin?.on('error', () => {}); + child.stdin?.end(limits.input); + return child; + }); + }; +} + +/** The execFile callback may report cancellation before the Git writer exits. */ +export function awaitRestoreGitExit( + start: (complete: (error?: Error, stdout?: Buffer) => void) => { once(event: 'close', listener: () => void): void } +): Promise { + let closed: Promise = Promise.resolve(); + const result = new Promise((resolve, reject) => { + const child = start((error, stdout) => { + if (error) reject(error); + else resolve(stdout ?? Buffer.alloc(0)); + }); + // A child error is not close. Keep the reservation until all child I/O closes. + closed = new Promise((resolve) => { + child.once('close', () => resolve()); + }); + }); + return result.finally(() => closed); +} + +export async function assertRestorePin( + git: CheckpointGit, + head: string, + signal: AbortSignal +): Promise { + const ref = `refs/librechat/checkpoints/${head}`; + if ( + ( + await git( + [ + 'for-each-ref', + '--count=1', + '--format=%(refname) %(objectname) %(symref)', + ref, + ], + { maxBytes: 512, signal } + ) + ).toString() !== `${ref} ${head} \n` + ) + invalid(); +} + +function blobId(head: string, bytes: Buffer): string { + return createHash(head.length === 40 ? 'sha1' : 'sha256') + .update(`blob ${bytes.length}\0`) + .update(bytes) + .digest('hex'); +} + +function validateTree(files: ReadonlyMap): void { + if (files.size > maxPaths) invalid(); + const paths = new Map(); + for (const path of files.keys()) { + let prefix = ''; + for (const part of pathParts(path)) { + if (files.has(prefix)) invalid(); + prefix += prefix ? `/${part}` : part; + const folded = prefix.toLowerCase(); + const prior = paths.get(folded); + if (prior !== undefined && prior !== prefix) invalid(); + paths.set(folded, prefix); + if (paths.size > maxPaths * 2) invalid(); + } + } +} + +export async function planRestore( + git: CheckpointGit, + configPath: string, + data: WorktreeCheckpoint, + signal: AbortSignal +): Promise { + // Read the repository config as data, with includes disabled. Refuse modes which can + // redirect Git away from the admitted checkout or change index representation. + const config = decode.decode( + await git( + [ + 'config', + '--file', + configPath, + '--no-includes', + '--null', + '--list', + ], + { maxBytes: inventory, signal } + ) + ); + for (const entry of config.split('\0')) { + const key = entry.split('\n', 1)[0].toLowerCase(); + if ( + /^(?:include(?:if)?\.|core\.(?:worktree|attributesfile|excludesfile|sparsecheckout(?:cone)?)$|extensions\.(?:worktreeconfig|partialclone)$|index\.sparse$|remote\..*\.promisor$)/.test( + key + ) + ) + invalid(); + } + await assertRestorePin(git, data.head, signal); + const raw = decode.decode( + await git(['ls-tree', '-r', '-l', '-z', '--full-tree', data.head], { + maxBytes: inventory, + signal, + }) + ); + if (raw && !raw.endsWith('\0')) invalid(); + const base = new Map(); + const record = new RegExp( + `^(100644|100755) blob ([a-f0-9]{${data.head.length}}) +([0-9]+)$` + ); + let size = 0; + for (const line of raw.split('\0').slice(0, -1)) { + const tab = line.indexOf('\t'); + const match = tab < 0 ? null : record.exec(line.slice(0, tab)); + if (!match) invalid(); + const path = line.slice(tab + 1); + if (base.has(path)) invalid(); + const length = Number(match[3]); + if ((size += length) > maxTree) invalid(); + base.set(path, { mode: match[1] as Mode, oid: match[2], size: length }); + } + validateTree(base); + const apply = (tree: Map, changes: Change[]) => { + for (const change of changes) { + if (change.mode === null) { + if (!tree.delete(change.path)) invalid(); + } else tree.set(change.path, change); + } + validateTree(tree); + }; + apply(base, data.staged); + const files = new Map(base); + apply(files, data.working); + return { index: base, files }; +} + +export async function materializeRestore( + git: CheckpointGit, + root: WorkspaceRootIdentity, + objectRoot: string, + data: WorktreeCheckpoint, + files: ReadonlyMap, + signal: AbortSignal +): Promise> { + const run = (args: string[], maxBytes: number, input?: Buffer) => + git(args, { maxBytes, signal, input }); + const objects = new Set(); + const changes: string[] = []; + // read-tree without -u never checks out files. hash-object --stdin writes the + // literal blob, not the result of a repository clean/smudge/process filter. + await run(['read-tree', '--reset', data.head], 128); + for (const change of data.staged) { + if (change.mode === null) { + changes.push(`0 ${'0'.repeat(data.head.length)}\t${change.path}\0`); + continue; + } + const expected = blobId(data.head, change.bytes); + const prefix = expected.slice(0, 2); + const directory = join(objectRoot, prefix); + const info = await statIfPresent(directory); + if (info && !info.isDirectory()) invalid(); + const existing = await statIfPresent( + join(directory, expected.slice(2)) + ); + if (existing && (!existing.isFile() || existing.nlink !== 1)) invalid(); + const oid = ( + await run(['hash-object', '-w', '--stdin'], 128, change.bytes) + ) + .toString() + .trim(); + if (oid !== expected) invalid(); + objects.add(prefix); + changes.push(`${change.mode} ${oid}\t${change.path}\0`); + } + if (changes.length) { + const index = Buffer.from(changes.join('')); + await run(['update-index', '-z', '--index-info'], 128, index); + } + const blobs = [...files.values()].filter( + (file): file is Blob => 'oid' in file + ); + const batch = blobs.length + ? await run( + ['cat-file', '--batch'], + maxTree + inventory, + Buffer.from(blobs.map(blob => `${blob.oid}\n`).join('')) + ) + : Buffer.alloc(0); + let offset = 0; + const directories = new Set([root.path]); + await withWorkspaceRoot(root.path, root, async () => { + for (const [path, file] of files) { + signal.throwIfAborted(); + const parts = pathParts(path); + let parent = root.path; + for (const part of parts.slice(0, -1)) { + parent = join(parent, part); + if (directories.has(parent)) continue; + await mkdir(parent, 0o755); + directories.add(parent); + } + let bytes: Buffer; + if ('oid' in file) { + const header = Buffer.from(`${file.oid} blob ${file.size}\n`); + if ( + !batch + .subarray(offset, offset + header.length) + .equals(header) + ) + invalid(); + offset += header.length; + bytes = batch.subarray(offset, offset + file.size); + offset += file.size; + if ( + batch[offset++] !== 10 || + blobId(data.head, bytes) !== file.oid + ) + invalid(); + } else bytes = file.bytes; + const mode = file.mode === '100755' ? 0o755 : 0o644; + const handle = await open( + join(root.path, path), + constants.O_WRONLY | + constants.O_CREAT | + constants.O_EXCL | + constants.O_NOFOLLOW, + mode + ); + try { + await handle.writeFile(bytes); + await handle.chmod(mode); + await handle.sync(); + } finally { + await handle.close(); + } + } + if (offset !== batch.length) invalid(); + for (const directory of [...directories].reverse()) { + const handle = await open( + directory, + constants.O_RDONLY | + constants.O_DIRECTORY | + constants.O_NOFOLLOW + ); + try { + await handle.sync(); + } finally { + await handle.close(); + } + } + }); + return objects; +} + +export function sameRestoreData( + expected: WorktreeCheckpoint, + actual: WorktreeCheckpoint +): boolean { + const equal = (a: Change[], b: Change[]) => { + if (a.length !== b.length) return false; + const index = new Map(b.map(change => [change.path, change])); + return a.every(change => { + const other = index.get(change.path); + return ( + other?.mode === change.mode && + (change.mode === null || + ('bytes' in other && change.bytes.equals(other.bytes))) + ); + }); + }; + return ( + expected.head === actual.head && + equal(expected.staged, actual.staged) && + equal(expected.working, actual.working) + ); +} + +/** Reject extraneous entries as well as drift hidden by Git ignore or checkpoint exclusions. */ +export async function verifyRestoreFiles( + root: WorkspaceRootIdentity, + head: string, + files: ReadonlyMap, + signal: AbortSignal +): Promise { + const directories = new Map>([['', new Set(['.git'])]]); + for (const path of files.keys()) { + let parent = ''; + for (const part of pathParts(path)) { + const entries = directories.get(parent) ?? new Set(); + entries.add(part); + directories.set(parent, entries); + parent = parent ? `${parent}/${part}` : part; + } + } + await withWorkspaceRoot(root.path, root, async () => { + for (const [path, expected] of directories) { + signal.throwIfAborted(); + const entries = await readdir(join(root.path, path), expected.size); + if ( + entries.length !== expected.size || + entries.some(entry => !expected.has(entry)) + ) + invalid(); + } + const chunk = Buffer.alloc(64 * 1024); + for (const [path, entry] of files) { + signal.throwIfAborted(); + const handle = await open( + join(root.path, path), + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK + ); + try { + const info = await handle.stat({ bigint: true }); + const { size, mode, nlink, dev } = info; + const length = 'oid' in entry ? entry.size : entry.bytes.length; + if ( + !info.isFile() || + nlink !== 1n || + dev.toString() !== root.dev || + size !== BigInt(length) || + (mode & 0o7777n) !== + (entry.mode === '100755' ? 0o755n : 0o644n) + ) + invalid(); + const hash = + 'oid' in entry + ? createHash( + head.length === 40 ? 'sha1' : 'sha256' + ).update(`blob ${length}\0`) + : undefined; + for (let offset = 0; offset < length; ) { + signal.throwIfAborted(); + const { bytesRead } = await handle.read( + chunk, + 0, + Math.min(chunk.length, length - offset), + offset + ); + if (!bytesRead) invalid(); + const bytes = chunk.subarray(0, bytesRead); + if (hash) hash.update(bytes); + else if ( + 'bytes' in entry && + !bytes.equals( + entry.bytes.subarray(offset, offset + bytesRead) + ) + ) + invalid(); + offset += bytesRead; + } + if ('oid' in entry && hash?.digest('hex') !== entry.oid) + invalid(); + } finally { + await handle.close(); + } + } + }); +} + +export async function verifyRestoreIndex( + git: CheckpointGit, + head: string, + index: ReadonlyMap, + signal: AbortSignal +): Promise { + const raw = decode.decode( + await git(['ls-files', '-v', '--stage', '-z'], { + maxBytes: inventory, + signal, + }) + ); + if (raw && !raw.endsWith('\0')) invalid(); + const entries = raw.split('\0').slice(0, -1); + if (entries.length !== index.size) invalid(); + const seen = new Set(); + for (const entry of entries) { + const tab = entry.indexOf('\t'); + if (tab < 0) invalid(); + const path = entry.slice(tab + 1); + const file = index.get(path); + if (!file || seen.has(path)) invalid(); + seen.add(path); + const oid = 'oid' in file ? file.oid : blobId(head, file.bytes); + if (entry.slice(0, tab) !== `H ${file.mode} ${oid} 0`) invalid(); + } +} diff --git a/packages/code/src/restore-settlement.test.ts b/packages/code/src/restore-settlement.test.ts new file mode 100644 index 00000000..0c494a7e --- /dev/null +++ b/packages/code/src/restore-settlement.test.ts @@ -0,0 +1,190 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { + mkdir, + mkdtemp, + open, + readFile, + readdir, + rm, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; + +import { settleRestore, verifySettledRestore } from './restore-settlement.js'; + +const key = 'a'.repeat(64); +const fingerprint = 'b'.repeat(64); +const skip = process.platform !== 'linux'; + +for (const point of [ + 'reserved', + 'materializing', + 'before-commit', + 'committed', +]) { + test( + `worker settlement survives process death at ${point}`, + { skip }, + async t => { + const path = await mkdtemp(join(tmpdir(), 'restore-settlement-')); + t.after(() => rm(path, { recursive: true, force: true })); + const journal = join(path, 'journal'); + const guard = join(path, 'source-guard'); + const lane = join(path, 'target'); + await mkdir(journal, { mode: 0o700 }); + await writeFile(guard, 'original fence', { + flag: 'wx', + flush: true, + }); + // The fixture provides exclusive access by running one process at a time. + // This is not an implementation of the parent reservation or route fence. + const child = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { open, readFile, writeFile } from 'node:fs/promises'; + import { dirname } from 'node:path'; + import assert from 'node:assert/strict'; + import { settleRestore } from ${JSON.stringify( + new URL('./restore-settlement.js', import.meta.url).href + )}; + const [journal, guard, lane, key, fingerprint, point] = process.argv.slice(1); + const handle = await open(journal); + const kill = () => process.kill(process.pid, 'SIGKILL'); + const absent = () => assert.rejects(readFile(lane), { code: 'ENOENT' }); + await settleRestore(handle, key, absent, async () => async () => { + assert.equal(await readFile(guard, 'utf8'), 'original fence'); + if (point === 'reserved') kill(); + await writeFile(lane, point === 'materializing' ? 'partial' : 'complete', { flag: 'wx', flush: true }); + if (point === 'materializing') kill(); + const parent = await open(dirname(lane)); + await parent.sync(); + await parent.close(); + if (point === 'before-commit') kill(); + return fingerprint; + }); + kill(); + `, + journal, + guard, + lane, + key, + fingerprint, + point, + ], + { encoding: 'utf8', timeout: 10_000 } + ); + assert.ifError(child.error); + assert.equal(child.signal, 'SIGKILL', child.stderr); + const handle = await open(journal); + try { + const noReplay = async (): Promise => + assert.fail('attempt replayed'); + const committed = point === 'committed'; + const expected = { state: committed ? 'settled' : 'rejected' }; + assert.deepEqual( + await settleRestore(handle, key, noReplay), + expected + ); + assert.deepEqual( + await settleRestore(handle, key, noReplay, noReplay), + expected + ); + await assert.rejects( + settleRestore(handle, 'c'.repeat(64), noReplay, noReplay), + /conflicting/ + ); + assert.equal(await readFile(guard, 'utf8'), 'original fence'); + if (point === 'reserved') { + await assert.rejects(readFile(lane), { code: 'ENOENT' }); + } else { + assert.equal( + await readFile(lane, 'utf8'), + point === 'materializing' ? 'partial' : 'complete' + ); + } + assert.deepEqual(await readdir(journal), ['catalog']); + if (!committed) { + await assert.rejects( + verifySettledRestore(handle, key, noReplay), + /no committed target/ + ); + return; + } + const verify = async (expected: string) => { + assert.equal(expected, fingerprint); + assert.equal(await readFile(lane, 'utf8'), 'complete'); + return lane; + }; + assert.equal( + await verifySettledRestore(handle, key, verify), + lane + ); + await writeFile(lane, 'drift'); + await assert.rejects(verifySettledRestore(handle, key, verify)); + assert.deepEqual( + await settleRestore(handle, key, noReplay), + expected + ); + } finally { + await handle.close(); + } + } + ); +} + +test( + 'status is read-only before start and failed preflight leaves no durable attempt', + { skip }, + async t => { + const dir = await mkdtemp(join(tmpdir(), 'restore-preflight-')); + t.after(() => rm(dir, { recursive: true, force: true })); + const handle = await open(dir); + try { + const absent = async () => {}; + assert.deepEqual(await settleRestore(handle, key, absent), { + state: 'not_started', + }); + await assert.rejects( + settleRestore(handle, key, absent, async () => { + throw new Error('payload unavailable'); + }), + /payload unavailable/ + ); + assert.deepEqual(await readdir(dir), []); + const conflict = async () => { + throw new Error('target already exists'); + }; + await assert.rejects( + settleRestore(handle, key, conflict, async () => + assert.fail('unexpected preflight') + ), + /target already exists/ + ); + assert.deepEqual(await readdir(dir), []); + let checks = 0; + const recheck = async () => { + if (++checks === 2) await conflict(); + }; + await assert.rejects( + settleRestore( + handle, + key, + recheck, + async () => async () => assert.fail('unexpected creation') + ), + /target already exists/ + ); + assert.deepEqual(await settleRestore(handle, key, absent), { + state: 'rejected', + }); + } finally { + await handle.close(); + } + } +); diff --git a/packages/code/src/restore-settlement.ts b/packages/code/src/restore-settlement.ts new file mode 100644 index 00000000..8e0dd420 --- /dev/null +++ b/packages/code/src/restore-settlement.ts @@ -0,0 +1,47 @@ +import type { FileHandle } from 'node:fs/promises'; + +import { reconcileRestoreJournal } from './restore-journal.js'; + +export type RestoreSettlement = + | { state: 'not_started' } + | { state: 'rejected' } + | { state: 'settled' }; + +type Prepare = () => Promise<() => Promise>; + +/** All calls (including verification) run under the parent's exclusive reservation. */ +export async function settleRestore( + journal: FileHandle, + key: string, + assertAbsent: () => Promise, + prepare?: Prepare +): Promise { + const existing = await reconcileRestoreJournal(journal, key); + if (existing.phase === 'restored') return { state: 'settled' }; + if (existing.phase === 'rejected') return { state: 'rejected' }; + await assertAbsent(); + if (!prepare) return { state: 'not_started' }; + + // Preflight errors need not consume the attempt. Only the materializer runs + // after durable reservation publication; it must recheck target absence. + const create = await prepare(); + const terminal = await reconcileRestoreJournal(journal, key, async () => { + await assertAbsent(); + return create(); + }); + if (terminal.phase === 'restored') return { state: 'settled' }; + if (terminal.phase === 'rejected') return { state: 'rejected' }; + throw new Error('Restore settlement missing after start'); +} + +export async function verifySettledRestore( + journal: FileHandle, + key: string, + verify: (fingerprint: string) => Promise +): Promise { + const terminal = await reconcileRestoreJournal(journal, key); + if (terminal.phase !== 'restored') { + throw new Error('Restore has no committed target'); + } + return verify(terminal.target); +} diff --git a/packages/code/src/worktree-restore.test.ts b/packages/code/src/worktree-restore.test.ts new file mode 100644 index 00000000..da9fb851 --- /dev/null +++ b/packages/code/src/worktree-restore.test.ts @@ -0,0 +1,475 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { EventEmitter } from 'node:events'; +import { + mkdir, + mkdtemp, + open, + readFile, + readdir, + rename, + rm, + stat, + symlink, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; + +import { CheckpointCatalog } from './checkpoint-catalog.js'; +import { awaitRestoreGitExit } from './restore-overlay.js'; +import { workspaceIsolationKey } from './protocol.js'; +import { captureWorkspaceRootIdentity } from './root-identity.js'; +import { + defaultWorkspaceQuarantinePath, + saveWorkspaceMutationQuarantine, +} from './storage.js'; +import { WorktreeLifecycle } from './worktree-lifecycle.js'; +import { WorktreeRestore } from './worktree-restore.js'; + +import type { TestContext } from 'node:test'; +import type { + WorktreeRestoreBackend, + WorktreeRestoreIntent, +} from './worktree-restore.js'; +import type { WorkspaceCreateWorktreeRequest } from './protocol.js'; +import type { WorktreeCheckpoint } from './worktree-checkpoint.js'; + +test('keeps the Git reservation pending after the error callback until close', async () => { + const child = new EventEmitter(); + const error = new Error('cancelled'); + let released = false; + const result = awaitRestoreGitExit((complete) => { + complete(error); + return child; + }).finally(() => { released = true; }); + const rejection = assert.rejects(result, error); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(released, false); + child.emit('close'); + await rejection; + assert.equal(released, true); +}); + +function git(cwd: string, ...args: string[]): string { + return execFileSync('/usr/bin/git', args, { + cwd, + encoding: 'utf8', + env: { + PATH: '/usr/bin:/bin', + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + LC_ALL: 'C', + }, + }); +} + +async function fixture(t: TestContext) { + const home = await mkdtemp(join(tmpdir(), 'librechat-worktree-restore-')); + t.after(() => rm(home, { recursive: true, force: true })); + const checkout = join(home, 'project'); + const journal = join(home, 'journal'); + await mkdir(checkout); + await mkdir(journal, { mode: 0o700 }); + git(checkout, 'init', '-q'); + await writeFile(join(checkout, 'base.txt'), 'base\n'); + await writeFile(join(checkout, 'remove.txt'), 'remove\n'); + await writeFile( + join(checkout, '.gitattributes'), + '*.txt filter=forbidden\n' + ); + await writeFile(join(checkout, '.gitignore'), 'ignored\n'); + git(checkout, 'add', '.'); + git( + checkout, + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + 'commit', + '-qm', + 'base' + ); + const head = git(checkout, 'rev-parse', 'HEAD').trim(); + git(checkout, 'update-ref', `refs/librechat/checkpoints/${head}`, head); + const sourceName = 'original'; + const lane = join(checkout, '.worktrees', sourceName); + const registration = join(checkout, '.git', 'worktrees', sourceName); + git(checkout, 'worktree', 'add', '-qd', lane, head); + await writeFile(join(lane, 'base.txt'), 'original dirty\n'); + git(lane, 'add', 'base.txt'); + const settings = { + codeApiUrl: 'https://worker.invalid', + workerId: 'worker', + homeDirectory: home, + }; + const guard = (workspaceRoot: string) => + defaultWorkspaceQuarantinePath({ ...settings, workspaceRoot }); + const quarantine = { + ownerId: 'old-incarnation:old-assignment', + quarantinedAt: new Date().toISOString(), + }; + const marker = { + version: 1 as const, + workerId: settings.workerId, + workspaceId: workspaceIsolationKey('project', undefined, sourceName), + ...quarantine, + reason: 'interrupted', + }; + await saveWorkspaceMutationQuarantine(guard(lane), marker); + const intent: WorktreeRestoreIntent = { + operation: 'restore-operation', + workspaceId: 'project', + sourceName, + sourceId: 'b'.repeat(64), + source: { + ownerScope: 'c'.repeat(64), + checkout: await captureWorkspaceRootIdentity(checkout), + common: await captureWorkspaceRootIdentity(join(checkout, '.git')), + lane: await captureWorkspaceRootIdentity(lane), + registration: await captureWorkspaceRootIdentity(registration), + }, + selector: { sequence: 7, digest: 'a'.repeat(64) }, + quarantine, + }; + const data: WorktreeCheckpoint = { + head, + staged: [ + { + path: 'base.txt', + mode: '100644', + bytes: Buffer.from('staged\n'), + }, + { path: 'remove.txt', mode: null }, + ], + working: [ + { + path: 'base.txt', + mode: '100644', + bytes: Buffer.from('working\n'), + }, + { + path: 'bin/run', + mode: '100755', + bytes: Buffer.from('literal bytes\n'), + }, + ], + }; + // Concurrency fixture only; not a durable cross-route fence. + let reserved = false; + let destination = ''; + let dropReply = false; + const backend: WorktreeRestoreBackend = { + async withReservation(_intent, name, _mode, _signal, task) { + if (reserved) throw new Error('busy'); + reserved = true; + destination = name; + const handle = await open(journal, 'r'); + try { + const result = await task(handle); + if (dropReply) throw new Error('reply lost'); + return result; + } finally { + await handle.close(); + reserved = false; + } + }, + async readExact() { + return { selector: intent.selector, checkpoint: data }; + }, + }; + const lifecycle = new WorktreeLifecycle(); + const restore = (override = lifecycle) => + new WorktreeRestore({ + ...settings, + projects: new Map([ + [ + 'project', + { + root: checkout, + identity: intent.source.checkout, + writable: true, + lifecycleEligible: true, + command: { workspaceRoot: checkout }, + repositoryInstructions: false, + }, + ], + ]), + checkoutQuarantines: new Map([['project', guard(checkout)]]), + lifecycle: override, + backend, + }); + return { + home, + checkout, + journal, + lane, + registration, + intent, + backend, + restore, + data, + guard, + marker, + name: () => destination, + dropReply: (drop: boolean) => { + dropReply = drop; + }, + }; +} + +const options = { skip: process.platform !== 'linux' }; + +test( + 'restores literal overlays and reconciles a lost reply without granting attachment', + options, + async t => { + const f = await fixture(t); + const original = async () => + Promise.all( + [ + join(f.lane, 'base.txt'), + join(f.registration, 'index'), + join(f.registration, 'HEAD'), + f.guard(f.lane), + ].map(path => readFile(path)) + ); + const before = await original(); + const marker = join(f.home, 'executed'); + git( + f.checkout, + 'config', + 'filter.forbidden.process', + `touch ${marker}` + ); + await writeFile( + join(f.checkout, '.git', 'hooks', 'post-checkout'), + `#!/bin/sh\ntouch '${marker}'\n`, + { mode: 0o755 } + ); + assert.deepEqual(await f.restore().recover(f.intent, 'status'), { + state: 'not_started', + }); + f.dropReply(true); + await assert.rejects( + f.restore().recover(f.intent, 'start'), + /reply lost/ + ); + f.dropReply(false); + const read = f.backend.readExact; + let reads = 0; + f.backend.readExact = async () => { + reads++; + return undefined; + }; + const result = { state: 'settled' }; + assert.deepEqual(await f.restore().recover(f.intent, 'status'), result); + assert.deepEqual(await f.restore().recover(f.intent, 'start'), result); + assert.equal(reads, 0); + await assert.rejects(f.restore().verifyTarget(f.intent)); + assert.equal(reads, 1); + f.backend.readExact = read; + const target = await f.restore().verifyTarget(f.intent); + const root = target.lane.path; + assert.notEqual(root, f.lane); + assert.equal( + git(root, 'rev-parse', '--abbrev-ref', 'HEAD').trim(), + 'HEAD' + ); + assert.equal(git(root, 'show', ':base.txt'), 'staged\n'); + assert.equal( + await readFile(join(root, 'base.txt'), 'utf8'), + 'working\n' + ); + assert.equal( + await readFile(join(root, 'bin/run'), 'utf8'), + 'literal bytes\n' + ); + assert.equal((await stat(join(root, 'bin/run'))).mode & 0o777, 0o755); + await assert.rejects(stat(join(root, 'remove.txt')), { + code: 'ENOENT', + }); + await assert.rejects(stat(marker), { code: 'ENOENT' }); + assert.deepEqual(await f.restore().recover(f.intent, 'status'), result); + assert.deepEqual(await f.restore().recover(f.intent, 'start'), result); + assert.deepEqual(await original(), before); + assert.equal((await readdir(join(f.checkout, '.worktrees'))).length, 2); + await assert.rejects( + f + .restore() + .recover({ ...f.intent, operation: 'different' }, 'start') + ); + await writeFile(join(root, 'ignored'), 'unexpected'); + await assert.rejects(f.restore().verifyTarget(f.intent)); + await rm(join(root, 'ignored')); + git(root, 'update-index', '--assume-unchanged', 'base.txt'); + await assert.rejects(f.restore().verifyTarget(f.intent)); + git(root, 'update-index', '--no-assume-unchanged', 'base.txt'); + await writeFile(join(root, 'base.txt'), 'drift'); + await assert.rejects(f.restore().verifyTarget(f.intent)); + assert.deepEqual(await f.restore().recover(f.intent, 'status'), result); + await rename(root, join(f.home, 'preserved-target')); + await mkdir(root); + await writeFile( + join(root, '.git'), + `gitdir: ${target.registration.path}\n` + ); + await assert.rejects(f.restore().verifyTarget(f.intent)); + assert.deepEqual(await original(), before); + } +); + +test( + 'requires exact publication and original guard and rejects a checkout-wide quarantine', + options, + async t => { + const f = await fixture(t); + for (const change of [ + { selector: { ...f.intent.selector, sequence: 8 } }, + { selector: { ...f.intent.selector, digest: 'f'.repeat(64) } }, + { quarantine: { ...f.intent.quarantine, ownerId: 'other' } }, + ]) + await assert.rejects( + f.restore().recover({ ...f.intent, ...change }, 'start') + ); + await rm(f.guard(f.lane)); + await assert.rejects(f.restore().recover(f.intent, 'start')); + await saveWorkspaceMutationQuarantine(f.guard(f.lane), f.marker); + await saveWorkspaceMutationQuarantine(f.guard(f.checkout), { + ...f.marker, + workspaceId: 'project', + }); + await assert.rejects(f.restore().recover(f.intent, 'start')); + assert.deepEqual(await readdir(f.journal), []); + } +); + +test( + 'rejects a replaced source incarnation and a pre-existing destination symlink', + options, + async t => { + const f = await fixture(t); + await f.restore().recover(f.intent, 'status'); + const target = join(f.checkout, '.worktrees', f.name()); + await symlink(f.lane, target); + await assert.rejects(f.restore().recover(f.intent, 'start')); + await rm(target); + await rename(f.lane, join(f.home, 'preserved-original')); + await mkdir(f.lane); + await writeFile(join(f.lane, '.git'), `gitdir: ${f.registration}\n`); + await assert.rejects(f.restore().recover(f.intent, 'start')); + assert.deepEqual(await readdir(f.journal), []); + } +); + +test( + 'interrupted creation retains the partial destination and never retries even without a destination', + options, + async t => { + const f = await fixture(t); + let calls = 0; + class Interrupted extends WorktreeLifecycle { + override create( + request: WorkspaceCreateWorktreeRequest, + source: Parameters[1] + ) { + calls++; + return super.create(request, source, async () => { + throw new Error('interrupted'); + }); + } + } + const originalGuard = await readFile(f.guard(f.lane)); + const lifecycle = new Interrupted(); + await assert.rejects(f.restore(lifecycle).recover(f.intent, 'start')); + const target = join(f.checkout, '.worktrees', f.name()); + assert.ok((await stat(target)).isDirectory()); + assert.deepEqual( + await f.restore(lifecycle).recover(f.intent, 'status'), + { state: 'rejected' } + ); + await rm(target, { recursive: true }); + await rm(join(f.checkout, '.git', 'worktrees', f.name()), { + recursive: true, + }); + assert.deepEqual( + await f.restore(lifecycle).recover(f.intent, 'start'), + { state: 'rejected' } + ); + assert.equal(calls, 1); + await assert.rejects(f.restore(lifecycle).verifyTarget(f.intent)); + assert.deepEqual(await readFile(f.guard(f.lane)), originalGuard); + } +); + +test( + 'rejects corrupt journal, malformed overlays and unsafe checkout config without starting new work', + options, + async t => { + const f = await fixture(t); + f.data.working.push({ + path: '../original', + mode: '100644', + bytes: Buffer.from('bad'), + }); + await assert.rejects(f.restore().recover(f.intent, 'start')); + f.data.working.pop(); + git( + f.checkout, + 'config', + 'include.path', + join(f.home, 'untrusted-config') + ); + await assert.rejects(f.restore().recover(f.intent, 'start')); + git(f.checkout, 'config', '--unset', 'include.path'); + const handle = await open(f.journal, 'r'); + try { + await CheckpointCatalog.initialize(handle, Buffer.from('{}')); + } finally { + await handle.close(); + } + await assert.rejects(f.restore().recover(f.intent, 'start')); + assert.equal((await readdir(join(f.checkout, '.worktrees'))).length, 1); + } +); + +test( + 'only one attempt can proceed through an active restore reservation', + options, + async t => { + const f = await fixture(t); + let enter!: () => void; + let resolve!: () => void; + const entered = new Promise(done => { + enter = done; + }); + const release = new Promise(done => { + resolve = done; + }); + const read = f.backend.readExact; + f.backend.readExact = async (...args) => { + enter(); + await release; + return read(...args); + }; + const first = f.restore().recover(f.intent, 'start'); + await entered; + try { + await assert.rejects( + f.restore().recover(f.intent, 'start'), + /busy/ + ); + await assert.rejects( + f + .restore() + .recover({ ...f.intent, operation: 'other' }, 'start'), + /busy/ + ); + } finally { + resolve(); + } + assert.equal((await first).state, 'settled'); + assert.equal((await readdir(join(f.checkout, '.worktrees'))).length, 2); + } +); diff --git a/packages/code/src/worktree-restore.ts b/packages/code/src/worktree-restore.ts new file mode 100644 index 00000000..916e973f --- /dev/null +++ b/packages/code/src/worktree-restore.ts @@ -0,0 +1,568 @@ +import { createHash } from 'node:crypto'; +import { constants } from 'node:fs'; +import { lstat, open } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; + +import { identityIsMountPoint, readLinuxMountInfo } from './identity-mount.js'; +import { + LINKED_WORKTREE_DIRECTORY, + verifyLinkedWorktree, +} from './linked-worktrees.js'; +import { + BRIDGE_PROTOCOL_VERSION, + isValidLinkedWorktreeName, + workspaceIsolationKey, +} from './protocol.js'; +import { + assertRestorePin, + materializeRestore, + planRestore, + restoreData, + restoreGit, + sameRestoreData, + verifyRestoreFiles, + verifyRestoreIndex, +} from './restore-overlay.js'; +import { settleRestore, verifySettledRestore } from './restore-settlement.js'; +import { + captureWorkspaceRootIdentity, + matchesWorkspaceRoot, +} from './root-identity.js'; +import { + defaultWorkspaceQuarantinePath, + loadWorkspaceMutationQuarantines, +} from './storage.js'; +import { captureWorktreeCheckpoint } from './worktree-checkpoint.js'; + +import type { FileHandle } from 'node:fs/promises'; +import type { LinkedWorktreeSource } from './linked-worktrees.js'; +import type { RestoreSettlement } from './restore-settlement.js'; +import type { WorkspaceRootIdentity } from './root-identity.js'; +import type { + CheckpointOwner, + WorktreeCheckpoint, +} from './worktree-checkpoint.js'; +import type { WorktreeLifecycle } from './worktree-lifecycle.js'; + +export type RestoreSelector = Readonly<{ sequence: number; digest: string }>; + +/** Assembled by the worker from authorized operation, verified enrollment and durable guard records. */ +export interface WorktreeRestoreIntent { + operation: string; + workspaceId: string; + sourceName: string; + /** Nonreusable enrollment identity, not the worktree name or a path. */ + sourceId: string; + source: CheckpointOwner; + selector: RestoreSelector; + quarantine: Readonly<{ ownerId: string; quarantinedAt: string }>; +} + +export interface WorktreeRestoreBackend { + /** + * Reserve the exact registration, source and deterministic destination against dispatch, mounts, + * writers, lifecycle, retirement and alias access. Checkout-wide operations must be excluded. + * Keep the destination denied to ordinary routes (including across restart) until explicit attach. + * Yield an exclusively leased, pinned, durable and isolated per-source directory for the journal + * only, under the same contract as CheckpointCatalog. Never alias/reinitialize a retired journal. + * Failure to obtain or prove any reservation must reject before invoking task. Status must + * not create a journal directory, arm a new fence, or be treated as a grant to attach. + * Both modes must permit durable reconciliation of an abandoned journal reservation. + */ + withReservation( + intent: WorktreeRestoreIntent, + destination: string, + mode: 'start' | 'status', + signal: AbortSignal, + task: (journal: FileHandle) => Promise + ): Promise; + /** Require the exact verified, retained selector and scope. Hold its pin and bytes until reservation release. */ + readExact( + source: CheckpointOwner, + selector: RestoreSelector, + signal: AbortSignal + ): Promise< + | { selector: RestoreSelector; checkpoint: WorktreeCheckpoint } + | undefined + >; +} + +interface RestoreTarget { + worktree: string; + lane: WorkspaceRootIdentity; + registration: WorkspaceRootIdentity; +} + +interface RestoreSession { + key: string; + journal: FileHandle; + assertAbsent: () => Promise; + prepare: () => Promise<() => Promise>; + verify: (fingerprint: string) => Promise; +} + +const hex = /^[a-f0-9]{64}$/; +const directoryFlags = + constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; + +function unavailable(): never { + throw new Error('Worktree restore unavailable or conflicting'); +} + +function hash(parts: unknown[]): string { + return createHash('sha256').update(JSON.stringify(parts)).digest('hex'); +} + +function identity(id: WorkspaceRootIdentity): string[] { + return [id.path, id.dev, id.ino]; +} + +function same(a: WorkspaceRootIdentity, b: WorkspaceRootIdentity): boolean { + return a.path === b.path && a.dev === b.dev && a.ino === b.ino; +} + +async function exists(path: string): Promise { + try { + await lstat(path); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; + throw error; + } +} + +async function sync(path: string, flags = directoryFlags): Promise { + const handle = await open(path, flags); + try { + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** Worker-local only. No assignment, route, capability, binding change or quarantine reset. */ +export class WorktreeRestore { + constructor( + private readonly options: { + codeApiUrl: string; + workerId: string; + homeDirectory?: string; + /** The same entries and resolved checkout quarantine paths used by the worker CLI. */ + projects: ReadonlyMap; + checkoutQuarantines: ReadonlyMap; + lifecycle: WorktreeLifecycle; + backend: WorktreeRestoreBackend; + } + ) {} + + /** A settled receipt reports durable completion, never permission to attach. */ + recover( + input: WorktreeRestoreIntent, + mode: 'start' | 'status', + stop?: AbortSignal + ): Promise { + return this.withSession(input, mode, stop, session => + settleRestore( + session.journal, + session.key, + session.assertAbsent, + mode === 'start' ? session.prepare : undefined + ) + ); + } + + /** + * Independent, payload-backed verification under a status reservation. + * The return value is diagnostic, not an attachment token: the lease ends + * before it is returned. Live attachment must verify and bind atomically + * under parent authority. + */ + verifyTarget( + input: WorktreeRestoreIntent, + stop?: AbortSignal + ): Promise { + return this.withSession(input, 'status', stop, session => + verifySettledRestore(session.journal, session.key, session.verify) + ); + } + + private async withSession( + input: WorktreeRestoreIntent, + mode: 'start' | 'status', + stop: AbortSignal | undefined, + task: (session: RestoreSession) => Promise + ): Promise { + const intent = structuredClone(input); + const { + operation, + workspaceId, + sourceName, + sourceId, + source, + selector, + quarantine, + } = intent; + if ( + process.platform !== 'linux' || + (mode !== 'start' && mode !== 'status') || + typeof operation !== 'string' || + !/^[A-Za-z0-9_-]{1,128}$/.test(operation) || + typeof sourceId !== 'string' || + !hex.test(sourceId) || + !isValidLinkedWorktreeName(sourceName) || + typeof source?.ownerScope !== 'string' || + !hex.test(source.ownerScope) || + !Number.isSafeInteger(selector?.sequence) || + selector.sequence < 1 || + typeof selector.digest !== 'string' || + !hex.test(selector.digest) || + typeof quarantine?.ownerId !== 'string' || + !quarantine.ownerId || + quarantine.ownerId.length > 512 || + typeof quarantine.quarantinedAt !== 'string' || + !Number.isFinite(Date.parse(quarantine.quarantinedAt)) + ) + unavailable(); + const project = this.options.projects.get(workspaceId); + const checkoutGuard = this.options.checkoutQuarantines.get(workspaceId); + if ( + !project?.writable || + !project.command || + project.lifecycleEligible !== true || + !project.identity || + !checkoutGuard || + project.root !== source.checkout.path || + !same(project.identity, source.checkout) + ) + unavailable(); + const key = hash([ + 'librechat/worker-restore/v1', + this.options.workerId, + workspaceId, + operation, + sourceId, + sourceName, + source.ownerScope, + identity(source.checkout), + identity(source.common), + identity(source.lane), + identity(source.registration), + selector.sequence, + selector.digest, + quarantine.ownerId, + quarantine.quarantinedAt, + ]); + const destination = `restore-${key}`; + if (sourceName.toLowerCase() === destination) unavailable(); + const root = join(project.root, LINKED_WORKTREE_DIRECTORY, destination); + const metadata = join(source.common.path, 'worktrees', destination); + const guardOptions = { + codeApiUrl: this.options.codeApiUrl, + workerId: this.options.workerId, + homeDirectory: this.options.homeDirectory, + }; + const sourceGuard = defaultWorkspaceQuarantinePath({ + ...guardOptions, + workspaceRoot: source.lane.path, + }); + const targetGuard = defaultWorkspaceQuarantinePath({ + ...guardOptions, + workspaceRoot: root, + }); + const assertSource = async () => { + const lane = await verifyLinkedWorktree( + project.root, + sourceName, + source.checkout + ); + if ( + !same(lane.identity, source.lane) || + lane.commonGitDir !== source.common.path || + source.registration.path !== + join(source.common.path, 'worktrees', sourceName) || + !(await matchesWorkspaceRoot( + source.common.path, + source.common + )) || + !(await matchesWorkspaceRoot( + source.registration.path, + source.registration + )) + ) + unavailable(); + const [checkout, original, target] = await Promise.all( + [checkoutGuard, sourceGuard, targetGuard].map(path => + loadWorkspaceMutationQuarantines(path) + ) + ); + // A single exact durable marker is the supported case. Multiple (including detached) + // or mismatched markers are not evidence that this is the interrupted operation. + if ( + checkout.length || + target.length || + original.length !== 1 || + original[0].workerId !== this.options.workerId || + original[0].workspaceId !== + workspaceIsolationKey(workspaceId, undefined, sourceName) || + original[0].ownerId !== quarantine.ownerId || + original[0].quarantinedAt !== quarantine.quarantinedAt + ) + unavailable(); + }; + const timeout = AbortSignal.timeout(30_000); + const signal = stop ? AbortSignal.any([stop, timeout]) : timeout; + return this.options.backend.withReservation( + structuredClone(intent), + destination, + mode, + signal, + async handle => { + signal.throwIfAborted(); + await assertSource(); + const assertAbsent = async () => { + if ((await exists(root)) || (await exists(metadata))) + unavailable(); + }; + const target = async (): Promise => { + const lane = await verifyLinkedWorktree( + project.root, + destination, + source.checkout + ); + const registration = await captureWorkspaceRootIdentity( + metadata + ); + if ( + lane.root !== root || + lane.commonGitDir !== source.common.path || + registration.path !== metadata || + (lane.identity.dev === source.lane.dev && + lane.identity.ino === source.lane.ino) || + (registration.dev === source.registration.dev && + registration.ino === source.registration.ino) + ) + unavailable(); + return { + worktree: destination, + lane: lane.identity, + registration, + }; + }; + const fingerprint = (value: RestoreTarget) => + hash([identity(value.lane), identity(value.registration)]); + const prepareVerification = async () => { + signal.throwIfAborted(); + const payload = await this.options.backend.readExact( + source, + selector, + signal + ); + if ( + !payload || + payload.selector.sequence !== selector.sequence || + payload.selector.digest !== selector.digest + ) + unavailable(); + const data = restoreData(payload.checkpoint); + const git = restoreGit(root); + const checkoutGit = restoreGit(project.root); + const mounts = await readLinuxMountInfo(); + if ( + [root, metadata, source.common.path].some(path => + identityIsMountPoint(mounts, path, true) + ) + ) + unavailable(); + const config = join(source.common.path, 'config'); + const configStat = await lstat(config); + if ( + !configStat.isFile() || + configStat.nlink !== 1 || + configStat.size > 512 * 1024 + ) + unavailable(); + const info = join(source.common.path, 'info'); + if (await exists(info)) { + if (!(await lstat(info)).isDirectory()) unavailable(); + const exclude = join(info, 'exclude'); + if (await exists(exclude)) { + const stat = await lstat(exclude); + if ( + !stat.isFile() || + stat.nlink !== 1 || + stat.size > 512 * 1024 + ) + unavailable(); + } + } + const objectRoot = join(source.common.path, 'objects'); + if ( + (await exists( + join(objectRoot, 'info', 'alternates') + )) || + (await exists( + join(objectRoot, 'info', 'http-alternates') + )) + ) + unavailable(); + const plan = await planRestore( + checkoutGit, + config, + data, + signal + ); + const verify = async (value: RestoreTarget) => { + const index = await lstat(join(metadata, 'index')); + if ( + !index.isFile() || + index.nlink !== 1 || + index.size > 2 * 1024 * 1024 || + (await exists(join(metadata, 'index.lock'))) + ) + unavailable(); + await verifyRestoreFiles( + value.lane, + data.head, + plan.files, + signal + ); + await verifyRestoreIndex( + git, + data.head, + plan.index, + signal + ); + const owner = { + ...source, + lane: value.lane, + registration: value.registration, + }; + if ( + !(await matchesWorkspaceRoot( + value.lane.path, + value.lane + )) || + !(await matchesWorkspaceRoot( + value.registration.path, + value.registration + )) + ) + unavailable(); + const head = await open( + join(metadata, 'HEAD'), + constants.O_RDONLY | + constants.O_NOFOLLOW | + constants.O_NONBLOCK + ); + try { + const expected = Buffer.from(`${data.head}\n`); + const info = await head.stat(); + const bytes = Buffer.alloc(expected.length + 1); + if ( + !info.isFile() || + info.nlink !== 1 || + info.size !== expected.length || + (await head.read(bytes)).bytesRead !== + expected.length || + !bytes + .subarray(0, expected.length) + .equals(expected) + ) + unavailable(); + } finally { + await head.close(); + } + const captured = await captureWorktreeCheckpoint( + owner, + owner, + git, + signal + ); + if (!captured || !sameRestoreData(data, captured)) + unavailable(); + await assertSource(); + signal.throwIfAborted(); + }; + return { checkoutGit, data, git, objectRoot, plan, verify }; + }; + const prepare = async () => { + const { checkoutGit, data, git, objectRoot, plan, verify } = + await prepareVerification(); + await assertSource(); + signal.throwIfAborted(); + return async () => { + const created: { value?: RestoreTarget } = {}; + await this.options.lifecycle.create( + { + protocolVersion: BRIDGE_PROTOCOL_VERSION, + operation: 'create_worktree', + workspaceId, + worktree: destination, + commit: data.head, + }, + source.checkout, + async () => { + created.value = await target(); + const objects = await materializeRestore( + git, + created.value.lane, + objectRoot, + data, + plan.files, + signal + ); + for (const prefix of objects) { + const path = join(objectRoot, prefix); + if (await exists(path)) await sync(path); + } + await sync(objectRoot); + }, + signal + ); + const current = await target(); + if ( + !created.value || + fingerprint(current) !== fingerprint(created.value) + ) + unavailable(); + for (const [directory, files] of [ + [root, ['.git']], + [ + metadata, + ['HEAD', 'commondir', 'gitdir', 'index'], + ], + ] as const) { + for (const file of files) + await sync( + join(directory, file), + constants.O_RDONLY | + constants.O_NOFOLLOW | + constants.O_NONBLOCK + ); + await sync(directory); + await sync(dirname(directory)); + } + await sync(source.common.path); + await sync(source.checkout.path); + await assertRestorePin(checkoutGit, data.head, signal); + await verify(current); + return fingerprint(current); + }; + }; + return task({ + journal: handle, + key, + assertAbsent, + prepare, + verify: async expected => { + const { verify } = await prepareVerification(); + const current = await target(); + if (fingerprint(current) !== expected) unavailable(); + await verify(current); + return current; + }, + }); + } + ); + } +}