diff --git a/packages/code/src/worktree-baseline.test.ts b/packages/code/src/worktree-baseline.test.ts new file mode 100644 index 00000000..449f1eb4 --- /dev/null +++ b/packages/code/src/worktree-baseline.test.ts @@ -0,0 +1,151 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { promisify } from 'node:util'; + +import { systemGitExecutable } from './linked-worktree-git-guard.js'; +import { captureWorkspaceRootIdentity } from './root-identity.js'; +import { WorktreeLifecycle } from './worktree-lifecycle.js'; +import { WorkspaceToolError } from './workspace.js'; + +import type { TestContext } from 'node:test'; +import type { ManagedWorktreeCreationLease } from './worktree-baseline.js'; + +const exec = promisify(execFile); +const owner = 'a'.repeat(64); +const lease = Object.freeze({ + ownerScope: owner, + assignmentId: `durable-${'b'.repeat(24)}`, + incarnationId: 'test-incarnation', + generation: 42, + slot: 1, +}); +const options = { skip: process.platform !== 'linux' && process.platform !== 'darwin' }; + +async function fixture(t: TestContext) { + const root = await realpath(await mkdtemp(join(tmpdir(), 'worktree-baseline-'))); + t.after(() => rm(root, { recursive: true, force: true })); + const executable = await systemGitExecutable(); + const git = async (cwd: string, ...args: string[]) => (await exec(executable, [ + '-c', 'user.name=test', '-c', 'user.email=test@example.test', '-c', 'commit.gpgsign=false', ...args, + ], { cwd })).stdout.trim(); + await git(root, 'init', '-q', '-b', 'main'); + await writeFile(join(root, 'tracked'), 'committed'); + await writeFile(join(root, '.gitignore'), '.env\n'); + await git(root, 'add', '--', 'tracked', '.gitignore'); + await git(root, 'commit', '-qm', 'initial'); + const source = await captureWorkspaceRootIdentity(root); + const common = join(root, '.git'); + const commit = await git(root, 'rev-parse', 'HEAD'); + const worktree = 'target'; + const lane = join(root, '.worktrees', worktree); + const metadata = join(common, 'worktrees', worktree); + const request = { protocolVersion: 1, operation: 'create_worktree', workspaceId: 'repo', worktree, commit } as const; + const lifecycle = new WorktreeLifecycle(); + const checkout = async () => { await git(lane, 'read-tree', '--reset', '-u', commit); }; + return { root, common, source, lane, metadata, commit, lifecycle, request, checkout, git }; +} + +test('scoped explicit creation stages only the pinned commit and the verified incarnation', options, async (t) => { + const f = await fixture(t); + const index = await readFile(join(f.common, 'index')); + const sibling = join(f.root, '.worktrees', 'sibling'); + await f.git(f.root, 'worktree', 'add', '-q', '-b', 'sibling', sibling); + await writeFile(join(sibling, 'tracked'), 'sibling stays dirty'); + let laneIndex: Buffer | undefined; + let files: string[] | undefined; + const candidate = await f.lifecycle.create(f.request, f.source, async () => { + await f.checkout(); + await writeFile(join(f.lane, '.env'), 'ignored test credential'); + await writeFile(join(f.lane, 'untracked'), 'untracked contents'); + await writeFile(join(f.lane, 'tracked'), 'staged contents'); + await f.git(f.lane, 'add', '--', 'tracked'); + await writeFile(join(f.lane, 'tracked'), 'unstaged contents'); + await symlink(join(f.lane, '.env'), join(f.lane, 'link')); + laneIndex = await readFile(join(f.metadata, 'index')); + files = await readdir(f.lane); + }, undefined, lease); + assert.deepEqual(candidate, { + commit: f.commit, + checkout: f.source, + common: await captureWorkspaceRootIdentity(f.common), + lane: await captureWorkspaceRootIdentity(f.lane), + registration: await captureWorkspaceRootIdentity(f.metadata), + lease, + }); + assert.deepEqual(await readFile(join(f.metadata, 'index')), laneIndex); + assert.deepEqual(await readdir(f.lane), files); + assert.deepEqual(await readFile(join(f.common, 'index')), index); + assert.equal(await f.git(f.root, 'symbolic-ref', '--short', 'HEAD'), 'main'); + assert.equal(await readFile(join(sibling, 'tracked'), 'utf8'), 'sibling stays dirty'); +}); + +test('existing manual lanes and arbitrary directories cannot be enrolled', options, async (t) => { + const f = await fixture(t); + const manual = join(f.root, '.worktrees', 'manual'); + await f.git(f.root, 'worktree', 'add', '-q', '--detach', manual); + await mkdir(f.lane); + for (const [worktree, path] of [['manual', manual], ['target', f.lane]]) { + const files = await readdir(path); + await assert.rejects(f.lifecycle.create({ ...f.request, worktree }, f.source, async () => { + assert.fail('existing target was passed to checkout'); + }, undefined, lease), /already exists/); + assert.deepEqual(await readdir(path), files); + } +}); + +const unscoped: [string, ManagedWorktreeCreationLease | undefined][] = [ + ['missing scope', undefined], + ['invalid scope', { ...lease, ownerScope: '' }], + ['non-durable assignment', { ...lease, assignmentId: 'a-123' }], + ['invalid incarnation', { ...lease, incarnationId: '' }], + ['invalid generation', { ...lease, generation: 0 }], + ['invalid slot', { ...lease, slot: 8 }], +]; +for (const [name, input] of unscoped) { + test(`creation without a candidate: ${name}`, options, async (t) => { + const f = await fixture(t); + assert.equal(await f.lifecycle.create(f.request, f.source, f.checkout, undefined, input), undefined); + assert.equal(await readFile(join(f.lane, 'tracked'), 'utf8'), 'committed'); + }); +} + +const invalid: [string, (f: Awaited>) => Promise][] = [ + ['lane replacement', async ({ lane }) => { await rename(lane, `${lane}-old`); await cp(`${lane}-old`, lane, { recursive: true }); }], + ['registration replacement', async ({ metadata }) => { await rename(metadata, `${metadata}-old`); await cp(`${metadata}-old`, metadata, { recursive: true }); }], + ['common Git directory replacement', async ({ common }) => { + await rename(common, `${common}-old`); + await cp(`${common}-old`, common, { recursive: true }); + }], + ['broken backlink', async ({ metadata }) => { await writeFile(join(metadata, 'gitdir'), '/not-the-lane/.git\n'); }], + ['symbolic HEAD', async ({ metadata, git }) => { await git(metadata, 'symbolic-ref', 'HEAD', 'refs/heads/main'); }], + ['oversize HEAD', async ({ metadata }) => { await writeFile(join(metadata, 'HEAD'), 'x'.repeat(8192)); }], + ['symlink HEAD', async ({ metadata, common }) => { + await rm(join(metadata, 'HEAD')); + await symlink(join(common, 'HEAD'), join(metadata, 'HEAD')); + }], + ['unexpected commit', async ({ metadata }) => { await writeFile(join(metadata, 'HEAD'), `${'d'.repeat(40)}\n`); }], +]; +for (const [name, change] of invalid) { + test(`candidate is withheld after ${name}`, options, async (t) => { + const f = await fixture(t); + const result = await f.lifecycle.create(f.request, f.source, async () => { + await f.checkout(); + await change(f); + }, undefined, lease); + assert.equal(result, undefined); + }); +} + +test('interrupted checkout retains existing quarantine semantics', options, async (t) => { + const f = await fixture(t); + const controller = new AbortController(); + await assert.rejects(f.lifecycle.create(f.request, f.source, async () => { + await f.checkout(); + controller.abort(); + }, controller.signal, lease), (error) => error instanceof WorkspaceToolError && error.requiresQuarantine); + assert.equal(await readFile(join(f.lane, 'tracked'), 'utf8'), 'committed'); +}); diff --git a/packages/code/src/worktree-baseline.ts b/packages/code/src/worktree-baseline.ts new file mode 100644 index 00000000..f6024d02 --- /dev/null +++ b/packages/code/src/worktree-baseline.ts @@ -0,0 +1,89 @@ +import { constants } from 'node:fs'; +import { join } from 'node:path'; + +import { open, withWorkspaceRoot } from './root-access.js'; +import { captureWorkspaceRootIdentity, matchesWorkspaceRoot } from './root-identity.js'; + +import type { WorkspaceRootIdentity } from './root-identity.js'; + +/** Internal input, constructed only from an acknowledged, owner-scoped durable creation lease. + * The request, an advisory Git probe, and a scope supplied by a caller are not such a lease. */ +export interface ManagedWorktreeCreationLease { + readonly ownerScope: string; + readonly assignmentId: string; + readonly incarnationId: string; + readonly generation: number; + readonly slot: number; +} + +interface WorktreeIncarnation { + readonly checkout: Readonly; + readonly common: Readonly; + readonly lane: Readonly; + readonly registration: Readonly; +} + +/** A pinned creation commit, not a snapshot of the index or working directory. + * This candidate is neither durable nor proof that the lifecycle result committed. */ +export interface ManagedWorktreeBaseline extends WorktreeIncarnation { + readonly lease: Readonly; + readonly commit: string; +} + +export function validManagedWorktreeCreationLease(lease: ManagedWorktreeCreationLease): boolean { + return /^[a-f0-9]{64}$/.test(lease.ownerScope) && + /^durable-[A-Za-z0-9_-]{24}$/.test(lease.assignmentId) && + /^[A-Za-z0-9_-]{16,128}$/.test(lease.incarnationId) && + Number.isSafeInteger(lease.generation) && lease.generation > 0 && + Number.isInteger(lease.slot) && lease.slot >= 0 && lease.slot < 8; +} + +async function identity(path: string): Promise> { + const current = await captureWorkspaceRootIdentity(path); + if (current.path !== path) throw new Error('Noncanonical worktree path'); + return Object.freeze(current); +} + +/** Called only immediately after the lifecycle creates a previously absent target. */ +export async function bindCreatedWorktree( + checkout: WorkspaceRootIdentity, + common: WorkspaceRootIdentity, + root: string, + registration: string, +): Promise { + const [lane, metadata] = await Promise.all([identity(root), identity(registration)]); + return { checkout: Object.freeze({ ...checkout }), common: Object.freeze({ ...common }), lane, registration: metadata }; +} + +/** Revalidate the newly created incarnation and read only its bounded detached HEAD. + * The caller holds the creation reservation through checkout and this check. */ +export async function stageWorktreeBaseline( + creation: WorktreeIncarnation, + lease: ManagedWorktreeCreationLease, + commit: string, +): Promise { + if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit)) return; + const { registration } = creation; + const unchanged = async () => (await Promise.all( + Object.values(creation).map((entry: WorkspaceRootIdentity) => matchesWorkspaceRoot(entry.path, entry)), + )).every(Boolean); + if (!(await unchanged())) return; + const detached = await withWorkspaceRoot(registration.path, registration, async () => { + const head = await open(join(registration.path, 'HEAD'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const info = await head.stat(); + const expected = Buffer.from(`${commit}\n`); + if (!info.isFile() || info.nlink !== 1 || info.size !== expected.length) return false; + const buffer = Buffer.alloc(expected.length + 1); + const { bytesRead } = await head.read(buffer, 0, buffer.length, 0); + return bytesRead === expected.length && buffer.subarray(0, bytesRead).equals(expected); + } finally { + await head.close(); + } + }); + if (!detached || !(await unchanged())) return; + return Object.freeze({ ...creation, commit, lease: Object.freeze({ + ownerScope: lease.ownerScope, assignmentId: lease.assignmentId, + incarnationId: lease.incarnationId, generation: lease.generation, slot: lease.slot, + }) }); +} diff --git a/packages/code/src/worktree-lifecycle.ts b/packages/code/src/worktree-lifecycle.ts index 22d96430..d650f183 100644 --- a/packages/code/src/worktree-lifecycle.ts +++ b/packages/code/src/worktree-lifecycle.ts @@ -6,12 +6,15 @@ import { promisify } from 'node:util'; import { identityIsMountPoint, readLinuxMountInfo } from './identity-mount.js'; import { systemGitExecutable } from './linked-worktree-git-guard.js'; +import { verifyLinkedWorktree } from './linked-worktrees.js'; import { captureWorkspaceRootIdentity, matchesWorkspaceRoot } from './root-identity.js'; import { WorkspaceToolError } from './workspace.js'; +import { bindCreatedWorktree, stageWorktreeBaseline, validManagedWorktreeCreationLease } from './worktree-baseline.js'; import type { VerifiedLinkedWorktree } from './linked-worktrees.js'; import type { WorkspaceCreateWorktreeRequest, WorkspaceRemoveWorktreeRequest } from './protocol.js'; import type { WorkspaceRootIdentity } from './root-identity.js'; +import type { ManagedWorktreeBaseline, ManagedWorktreeCreationLease } from './worktree-baseline.js'; const execFileAsync = promisify(execFile); const gitEnvironment = { @@ -83,13 +86,19 @@ export class WorktreeLifecycle { source: WorkspaceRootIdentity, checkout: () => Promise, signal?: AbortSignal, - ): Promise { + // No production caller supplies this until the bridge can prove durable publication. + baselineLease?: ManagedWorktreeCreationLease, + ): Promise { + const lease = baselineLease != null && validManagedWorktreeCreationLease(baselineLease) + ? { ...baselineLease } + : undefined; const common = await directory(join(source.path, '.git')); const base = join(source.path, '.worktrees'); const root = join(base, request.worktree); const registrations = join(common.path, 'worktrees'); const registration = join(registrations, request.worktree); let mutated = false; + let creation: Awaited> | undefined; try { await this.metadata(common, async () => { if (!(await matchesWorkspaceRoot(source.path, source)) || @@ -110,6 +119,9 @@ export class WorktreeLifecycle { if (await absent(base)) await mkdir(base); // --no-guess-remote and an exact commit prevent branch creation or fetching. await this.git(source.path, ['worktree', 'add', '--no-checkout', '--detach', '--no-guess-remote', '--', root, request.commit]); + if (lease != null) { + creation = await bindCreatedWorktree(source, common, root, registration).catch(() => undefined); + } }); await checkout(); signal?.throwIfAborted(); @@ -118,6 +130,14 @@ export class WorktreeLifecycle { if (error instanceof WorkspaceToolError) throw error; throw rejected('Cannot validate worktree creation or resolve the local commit'); } + if (creation == null || lease == null || signal?.aborted) return; + try { + await verifyLinkedWorktree(source.path, request.worktree, source); + const candidate = await stageWorktreeBaseline(creation, lease, request.commit); + if (!signal?.aborted) return candidate; + } catch { + // Advisory capture must not change the outcome of a successful checkout. + } } async remove(