wishforge-ide/apps/worker/test/cancellation.test.ts
eust-w a89cd1b9b3 ✨ Let Claude Code run commands inside its own sandbox, by operator opt-in
With WF_CLAUDE_COMMAND_SANDBOX=true, Claude Code also gets Bash, run in
its built-in sandbox through --settings:

- The sandbox must start (failIfUnavailable), and no command may run
  outside it (allowUnsandboxedCommands: false).
- No network: an empty allowedDomains with strictAllowlist, since an
  absent allowlist leaves the network open. Local binding stays off,
  because it would also open every local port, Temporal's included.
- Commands cannot read the home directories, the CLI's home or the
  worker's own directory, except the workspace, a per-run scratch
  directory and WF_CLAUDE_COMMAND_READ_PATHS; they write only to the
  workspace and the scratch directory; credential variables are unset.
- WF_CLAUDE_COMMAND_ENV gives commands toolchain variables, such as the
  POC's read-only Go module cache.

The executor probes the sandbox first (Seatbelt on macOS; bubblewrap
and socat on Linux) and keeps file tools only where it cannot start,
saying so on the timeline. The adapter now writes the execution
contract into the prompt, for the tools the agent actually has.

scripts/check-claude-command-sandbox.ts checks a machine with one short
real session and judges each probe by its effect, not the agent's
account. On the local Mac every probe was blocked; the login keychain
remains reachable, because Claude Code's Seatbelt profile always allows
the security server. That limit is documented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 14:48:16 +08:00

138 lines
5.5 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from 'vitest';
import { Context } from '@temporalio/activity';
import { mkdtemp, readdir, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import type { Run } from '@wishforge/contracts';
import type { ProviderAdapter } from '@wishforge/runtime';
import { BASELINE_VERSION } from '@wishforge/agent';
import { LeaseKeeper } from '../src/lease.js';
import { executeRun } from '../src/executor.js';
import type { RunContext } from '../src/common.js';
const directories: string[] = [];
afterEach(async () => {
vi.restoreAllMocks();
await Promise.all(directories.splice(0).map(directory => rm(directory, { recursive: true, force: true })));
});
function activity(controller: AbortController) {
return { cancellationSignal: controller.signal, heartbeat: vi.fn() } as unknown as Context;
}
describe('execution cancellation at side-effect boundaries', () => {
it('rejects an already canceled activity before calling the control plane', async () => {
const controller = new AbortController();
controller.abort();
const request = vi.fn().mockResolvedValue({ status: 'running' });
const keeper = new LeaseKeeper({ request }, 'run', 1, activity(controller));
await expect(keeper.ensure()).rejects.toMatchObject({ code: 'CANCELED' });
expect(request).not.toHaveBeenCalled();
});
it('rejects cancellation arriving during a successful lease heartbeat', async () => {
const controller = new AbortController();
const request = vi.fn().mockImplementation(async () => {
controller.abort();
return { status: 'running' };
});
const keeper = new LeaseKeeper({ request }, 'run', 1, activity(controller));
await expect(keeper.ensure()).rejects.toMatchObject({ code: 'CANCELED' });
});
it('stops a provider canceled while start was in flight and retains its workspace', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'wishforge-cancel-start-'));
directories.push(directory);
const controller = new AbortController();
vi.spyOn(Context, 'current').mockReturnValue(activity(controller));
const at = new Date().toISOString();
const run = {
id: 'run',
tenantId: 'tenant',
projectId: 'project',
stage: 'implement',
status: 'queued',
revision: 1,
repairCount: 0,
provider: 'claude-code',
bundleVersion: BASELINE_VERSION,
goal: 'Fixture only',
acceptanceCriteria: ['No model or network operations'],
executionGeneration: 'generation',
budget: { maxTokens: 1000, maxMinutes: 60, maxRepairRounds: 3 },
} as Run;
const context: RunContext = {
run,
project: {
id: 'project',
tenantId: 'tenant',
version: 1,
createdAt: at,
updatedAt: at,
name: 'Cancellation fixture',
repositoryStorage: 'platform',
repositoryStatus: 'unconfigured',
autoDeploy: false,
targetBranch: 'main',
verificationCommands: [],
memberIds: [],
},
};
const cancel = vi.fn().mockResolvedValue(undefined),
events = vi.fn(async function* () {});
const provider = {
capabilities: () => ({ provider: 'claude-code', availability: 'available', coding: true }),
start: vi.fn(async () => {
run.status = 'canceled';
controller.abort();
return { id: 'run', provider: 'claude-code', status: 'running' };
}),
cancel,
events,
inspect: vi.fn(async () => ({ id: 'run', provider: 'claude-code', status: 'running' })),
exportCheckpoint: vi.fn(async () => {
throw new Error('Canceled work cannot export a completed checkpoint');
}),
} as unknown as ProviderAdapter;
const fetcher: typeof fetch = async (url, init) => {
const route = new URL(String(url)).pathname,
body = init?.body ? JSON.parse(String(init.body)) : undefined;
if (route.endsWith('/lease')) {
run.status = 'running';
run.lease = { token: 1, workerId: 'fixture', expiresAt: new Date(Date.now() + 60000).toISOString() };
return Response.json({ data: run });
}
if (route.endsWith('/transition')) {
run.stage = body.stage;
run.status = body.status;
return Response.json({ data: run });
}
if (route.endsWith('/heartbeat') || route.endsWith('/lease/release')) return Response.json({ data: run });
if (route.endsWith('/context')) return Response.json({ data: context });
throw new Error(`Unexpected fixture request ${route}`);
};
const outcome = await executeRun(
{
controlPlaneUrl: 'http://127.0.0.1:4000',
workerToken: 'fixture-token',
workerId: 'fixture',
workspaceRoot: directory,
isolatedProviderHomeRoot: directory,
sandboxMode: 'host',
sandboxRunId: 'run',
sandboxTenantId: 'tenant',
sandboxGeneration: 'generation',
providerFactory: () => provider,
fetcher,
execute: async command => ({
exitCode: 0,
stdout: command.args.includes('rev-parse') ? 'a'.repeat(40) + '\n' : '',
stderr: '',
}),
},
{ tenantId: 'tenant', runId: 'run', generation: 'generation' },
);
expect(outcome).toEqual({ status: 'canceled' });
expect(cancel).toHaveBeenCalledWith('run');
expect(events).not.toHaveBeenCalled();
expect(provider.exportCheckpoint).not.toHaveBeenCalled();
expect(await readdir(path.join(directory, 'tenant'))).toContain('run-a1.recovery.json');
});
});