Multiplayer agent harness for work.
Require real execution across selected sandbox providers (#1090)
Regan Bell1161c837b7bc
diff --git a/scripts/qualify-local-provider.sh b/scripts/qualify-local-provider.shnew file mode 100755index 000000000..517fbf8d8--- /dev/null+++ b/scripts/qualify-local-provider.sh@@ -0,0 +1,43 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+candidate="${1:?usage: qualify-local-provider.sh <candidate.json>}"+: "${ANTHROPIC_API_KEY:?a live model credential is required}"+core_image="$(node --input-type=module - "$candidate" <<'JS'+import { readFileSync } from 'node:fs';+const candidate = JSON.parse(readFileSync(process.argv[2], 'utf8'));+if (!/^[^\s]+@sha256:[a-f0-9]{64}$/.test(candidate.images?.core ?? '')) throw new Error('candidate core must be immutable');+console.log(candidate.images.core);+JS+)"+source_sha="$(git rev-parse HEAD)"+registry="${core_image%%/*}"+aws ecr get-login-password | docker login --username AWS --password-stdin "$registry"+docker pull "$core_image"+base_tag="qm-qualification-base:$source_sha"+local_tag="qm-qualification-local:$source_sha"+cache_args=()+if [[ -n "${ACTIONS_RUNTIME_TOKEN:-}" && -n "${ACTIONS_CACHE_URL:-}${ACTIONS_RESULTS_URL:-}" ]]; then+ cache_args=(--cache-from type=gha,scope=qm-local-base --cache-to type=gha,scope=qm-local-base,mode=max)+fi+platform="${LOCAL_SANDBOX_PLATFORM:-linux/arm64}"+docker buildx build --load --platform "$platform" "${cache_args[@]}" -f fly/Dockerfile -t "$base_tag" .+fingerprint="$(node --input-type=module -e 'import { computeSandboxImageFingerprint } from "./src/sandbox/local-sandbox.ts"; const value = await computeSandboxImageFingerprint(process.cwd()); if (!value) throw new Error("missing sandbox sources"); console.log(value);')"+docker build --builder "$(docker context show)" --platform "$platform" -f local/Dockerfile --build-arg "BASE=$base_tag" --label "qm.sandbox-fingerprint=$fingerprint" -t "$local_tag" .+local_image="$(docker image inspect --format '{{.Id}}' "$local_tag")"+container="qm-provider-qualification-${GITHUB_RUN_ID:-local}-$$"+cleanup() {+ docker rm -f "$container" >/dev/null 2>&1 || true+}+trap cleanup EXIT+socket_group="$(node -e 'console.log(require("node:fs").statSync("/var/run/docker.sock").gid)')"+printf 'core=%s\nsource=%s\nlocal=%s\n' "$core_image" "$source_sha" "$local_image"+docker run --rm --name "$container" --group-add "$socket_group" \+ -v /var/run/docker.sock:/var/run/docker.sock \+ -v "$PWD/test/live-slack/local-provider.ts:/app/test/live-slack/local-provider.ts:ro" \+ -v "$PWD/test/live-slack/scenarios-sandbox-providers.ts:/app/test/live-slack/scenarios-sandbox-providers.ts:ro" \+ -e ANTHROPIC_API_KEY -e NODE_ENV=development \+ -e "EXPECTED_SOURCE_SHA=$source_sha" -e "QM_CORE_CONTAINER=$container" \+ -e "LOCAL_SANDBOX_IMAGE=$local_image" -e LOCAL_SANDBOX_CPUS=2 -e LOCAL_SANDBOX_MEMORY_MB=2048 \+ -e PI_MODEL=claude-haiku-4-5-20251001 \+ "$core_image" node test/live-slack/local-provider.tsdiff --git a/src/sandbox/aws-sandbox.ts b/src/sandbox/aws-sandbox.tsindex 633a3d2c9..7ec8db2c3 100644--- a/src/sandbox/aws-sandbox.ts+++ b/src/sandbox/aws-sandbox.ts@@ -18,7 +18,7 @@ import {posixJoin,type BlobStagingOptions,} from "./exec-file-ops.ts";-import { createMicrovmApi, createMicrovmClient, type AwsMicrovmApi } from "./aws-microvm-api.ts";+import { AwsApiError, createMicrovmApi, createMicrovmClient, type AwsMicrovmApi } from "./aws-microvm-api.ts";import type {AgentComputerProfile,ExecOptions,@@ -58,6 +58,7 @@ export interface StoredMicrovm {lastSnapshotMs?: number;lastActivityMs?: number;homeDirty?: boolean;+ provisioning?: boolean;orgId?: string;}@@ -110,6 +111,8 @@ export function createAwsSandbox(workspace: WorkspaceStore, opts: AwsSandboxOpticonst store = opts.store ?? createMemoryMap<StoredMicrovm>();const advisoryLock = opts.advisoryLock ?? createNoopAdvisoryLock();const provisionQueue = createKeyedQueue<string>();+ const withScopeLock = <T>(scope: string, run: () => Promise<T>): Promise<T> =>+ provisionQueue(scope, () => advisoryLock.withLock(`aws-provision:${scope}`, run));const onError = opts.onError;const ingress = opts.ingressConnectorArns?.length ? opts.ingressConnectorArns : [DEFAULT_INGRESS(region)];@@ -218,63 +221,82 @@ export function createAwsSandbox(workspace: WorkspaceStore, opts: AwsSandboxOptimaximumDurationInSeconds,clientToken: `${scope ?? "scratch"}-${Date.now()}`,});- const ready = await api.waitForState(run.microvmId, "RUNNING");- const endpoint = run.endpoint ?? ready.endpoint;- if (!endpoint) throw new Error(`microVM ${run.microvmId} has no endpoint`);- endpointById.set(run.microvmId, endpoint);- await client.waitDaemon(run.microvmId, endpoint);- return { id: run.microvmId, endpoint };+ try {+ if (scope)+ await store.put(scope, {+ microvmId: run.microvmId,+ endpoint: run.endpoint ?? "",+ createdAtMs: Date.now(),+ orgId: configOrgId(),+ provisioning: true,+ });+ const ready = await api.waitForState(run.microvmId, "RUNNING");+ const endpoint = run.endpoint ?? ready.endpoint;+ if (!endpoint) throw new Error(`microVM ${run.microvmId} has no endpoint`);+ endpointById.set(run.microvmId, endpoint);+ await client.waitDaemon(run.microvmId, endpoint);+ return { id: run.microvmId, endpoint };+ } catch (error) {+ try {+ await api.terminate(run.microvmId);+ } catch (cleanupError) {+ throw new AggregateError([error, cleanupError], `AWS launch ${run.microvmId} failed and termination failed`, {+ cause: cleanupError,+ });+ }+ throw error;+ }}async function ensureBody(scope: string): Promise<{ id: string; endpoint: string; coldStart: boolean }> {- return provisionQueue(scope, () =>- advisoryLock.withLock(`aws-provision:${scope}`, async () => {- const stored = await store.get(scope);- if (stored) {- const desc = await api.tryGetMicrovm(stored.microvmId);- const alive = desc && desc.state !== "TERMINATED" && desc.state !== "TERMINATING";- const stale = Date.now() - stored.createdAtMs > rotateAfterMs;- if (alive && !stale) {- endpointById.set(stored.microvmId, stored.endpoint);- scopeByMicrovm.set(stored.microvmId, scope);- await ensureRunning(stored.microvmId);- return { id: stored.microvmId, endpoint: stored.endpoint, coldStart: false };- }- if (alive && stale) {- endpointById.set(stored.microvmId, stored.endpoint);- await ensureRunning(stored.microvmId).catch(() => {});- await snapshotHome(scope, stored.microvmId).catch((e) =>- reportError("sandbox_snapshot", "rotate_snapshot_failed", errMessage(e), scope),- );- await api.terminate(stored.microvmId).catch(() => {});- }+ return withScopeLock(scope, async () => {+ const stored = await store.get(scope);+ if (stored) {+ const desc = await api.tryGetMicrovm(stored.microvmId);+ const alive = desc && desc.state !== "TERMINATED" && desc.state !== "TERMINATING";+ const stale = Date.now() - stored.createdAtMs > rotateAfterMs;+ if (alive && stored.provisioning)+ throw new Error(`AWS sandbox ${stored.microvmId} has incomplete provisioning; retire it before retrying`);+ if (alive && !stale) {+ endpointById.set(stored.microvmId, stored.endpoint);+ scopeByMicrovm.set(stored.microvmId, scope);+ await ensureRunning(stored.microvmId);+ return { id: stored.microvmId, endpoint: stored.endpoint, coldStart: false };}- const body = await launchBody(scope);- scopeByMicrovm.set(body.id, scope);- let hydrated: boolean;- try {- hydrated = await hydrateHome(scope, body.id);- } catch (e) {- reportError("sandbox_hydrate", "hydrate_failed", errMessage(e), scope);- scopeByMicrovm.delete(body.id);- endpointById.delete(body.id);- client.evict(body.id);- await api.terminate(body.id).catch(swallowAs("aws-sandbox: terminate after failed hydrate", undefined));- throw new Error(`aws provision: home hydration failed (${errMessage(e)}); not risking the stored snapshot`, {- cause: e,- });+ if (alive && stale) {+ endpointById.set(stored.microvmId, stored.endpoint);+ await ensureRunning(stored.microvmId).catch(() => {});+ await snapshotHome(scope, stored.microvmId).catch((e) =>+ reportError("sandbox_snapshot", "rotate_snapshot_failed", errMessage(e), scope),+ );+ await api.terminate(stored.microvmId).catch(() => {});}- await store.put(scope, {- microvmId: body.id,- endpoint: body.endpoint,- ...(opts.imageVersion ? { imageVersion: opts.imageVersion } : {}),- createdAtMs: Date.now(),- ...(hydrated ? { lastSnapshotMs: Date.now(), homeDirty: false } : {}),- orgId: configOrgId(),+ }+ const body = await launchBody(scope);+ scopeByMicrovm.set(body.id, scope);+ let hydrated: boolean;+ try {+ hydrated = await hydrateHome(scope, body.id);+ } catch (e) {+ reportError("sandbox_hydrate", "hydrate_failed", errMessage(e), scope);+ scopeByMicrovm.delete(body.id);+ endpointById.delete(body.id);+ client.evict(body.id);+ await api.terminate(body.id).catch(swallowAs("aws-sandbox: terminate after failed hydrate", undefined));+ throw new Error(`aws provision: home hydration failed (${errMessage(e)}); not risking the stored snapshot`, {+ cause: e,});- return { id: body.id, endpoint: body.endpoint, coldStart: !hydrated };- }),- );+ }+ await store.put(scope, {+ microvmId: body.id,+ endpoint: body.endpoint,+ ...(opts.imageVersion ? { imageVersion: opts.imageVersion } : {}),+ createdAtMs: Date.now(),+ ...(hydrated ? { lastSnapshotMs: Date.now(), homeDirty: false } : {}),+ orgId: configOrgId(),+ });+ return { id: body.id, endpoint: body.endpoint, coldStart: !hydrated };+ });}async function ensureScratch(key: string): Promise<{ id: string; endpoint: string; coldStart: boolean }> {@@ -352,7 +374,37 @@ export function createAwsSandbox(workspace: WorkspaceStore, opts: AwsSandboxOpticonst blobStaging = createBackendBlobStaging("aws", (id, script, t) => execRaw(id, script, t), opts);+ async function terminateBody(id: string): Promise<void> {+ const body = await api.tryGetMicrovm(id);+ if (!body || body.state === "TERMINATED") return;+ try {+ if (body.state !== "TERMINATING") await api.terminate(id);+ await api.waitForState(id, "TERMINATED", { timeoutMs: 60_000 });+ } catch (error) {+ if (!(error instanceof AwsApiError && error.status === 404)) throw error;+ }+ }++ function destroyStoredScope(scopeId: string, expectedId?: string): Promise<void> {+ return withScopeLock(scopeId, async () => {+ const stored = await store.get(scopeId);+ const id = expectedId ?? stored?.microvmId;+ if (id) await terminateBody(id);+ if (!expectedId || !stored || stored.microvmId === expectedId) {+ await s3.send(new DeleteObjectCommand({ Bucket: opts.s3Bucket, Key: s3KeyFor(scopeId) }));+ await store.delete(scopeId);+ }+ if (id) {+ client.evict(id);+ endpointById.delete(id);+ scopeByMicrovm.delete(id);+ activeByMicrovm.delete(id);+ }+ });+ }+const sandbox: Sandbox = {+ destroyScope: (scopeId) => destroyStoredScope(scopeId),profile,startProcess: procSessions.startProcess,readProcess: procSessions.readProcess,@@ -455,59 +507,66 @@ export function createAwsSandbox(workspace: WorkspaceStore, opts: AwsSandboxOpticonst scope = scopeByMicrovm.get(handle.id) ?? (await scopeOf(handle.id));if (tdOpts?.destroy) {- await api.terminate(handle.id).catch(swallowAs("aws-sandbox: destroy terminate", undefined));- if (scope) {- await s3.send(new DeleteObjectCommand({ Bucket: opts.s3Bucket, Key: s3KeyFor(scope) })).catch(() => {});- await store.delete(scope).catch(() => {});+ if (scope) await destroyStoredScope(scope, handle.id);+ else {+ await terminateBody(handle.id);+ client.evict(handle.id);+ endpointById.delete(handle.id);}- client.evict(handle.id);- endpointById.delete(handle.id);return;}if (scope) {- const stored = await store.get(scope);- if (!tdOpts?.homeUnchanged) await store.merge(scope, { homeDirty: true });- if (snapshotDue(stored, tdOpts, snapshotIntervalMs)) {- try {- await snapshotHome(scope, handle.id);- await store.merge(scope, { lastSnapshotMs: Date.now(), lastActivityMs: Date.now(), homeDirty: false });- } catch (e) {- reportError("sandbox_snapshot", "teardown_snapshot_failed", errMessage(e), scope);+ await withScopeLock(scope, async () => {+ const stored = await store.get(scope);+ if (stored?.microvmId !== handle.id) return;+ if (!tdOpts?.homeUnchanged) await store.merge(scope, { homeDirty: true });+ if (snapshotDue(stored, tdOpts, snapshotIntervalMs)) {+ try {+ await snapshotHome(scope, handle.id);+ await store.merge(scope, { lastSnapshotMs: Date.now(), lastActivityMs: Date.now(), homeDirty: false });+ } catch (e) {+ reportError("sandbox_snapshot", "teardown_snapshot_failed", errMessage(e), scope);+ await store.merge(scope, { lastActivityMs: Date.now() }).catch(() => {});+ }+ } else {await store.merge(scope, { lastActivityMs: Date.now() }).catch(() => {});}- } else {- await store.merge(scope, { lastActivityMs: Date.now() }).catch(() => {});- }+ await api.suspend(handle.id).catch(swallowAs("aws-sandbox: suspend on teardown", undefined));+ });}- await api.suspend(handle.id).catch(swallowAs("aws-sandbox: suspend on teardown", undefined));},async reapDeepIdle(idleMs): Promise<{ reaped: number }> {if (!(idleMs > 0)) return { reaped: 0 };const cutoff = Date.now() - idleMs;let reaped = 0;- for (const [scope, rec] of await store.entries()) {- if (rec.orgId && rec.orgId !== configOrgId()) continue;- if (!rec.lastActivityMs || rec.lastActivityMs > cutoff) continue;- const desc = await api.tryGetMicrovm(rec.microvmId);- if (!desc || desc.state === "TERMINATED" || desc.state === "TERMINATING") {- await store.delete(scope).catch(() => {});- continue;- }- try {- endpointById.set(rec.microvmId, rec.endpoint);- const due = !rec.lastSnapshotMs || (rec.lastActivityMs ?? 0) > rec.lastSnapshotMs;- if (due) {- await ensureRunning(rec.microvmId);- await snapshotHome(scope, rec.microvmId);+ for (const [scope, candidate] of await store.entries()) {+ await withScopeLock(scope, async () => {+ const rec = await store.get(scope);+ if (!rec || rec.microvmId !== candidate.microvmId) return;+ if (rec.orgId && rec.orgId !== configOrgId()) return;+ if (!rec.lastActivityMs || rec.lastActivityMs > cutoff) return;+ if (activeByMicrovm.has(rec.microvmId)) return;+ const desc = await api.tryGetMicrovm(rec.microvmId);+ if (!desc || desc.state === "TERMINATED" || desc.state === "TERMINATING") {+ await store.delete(scope).catch(() => {});+ return;}- await api.terminate(rec.microvmId);- await store.delete(scope);- reaped++;- } catch (e) {- reportError("sandbox_reap", "deep_idle_reap_failed", errMessage(e), scope);- }+ try {+ endpointById.set(rec.microvmId, rec.endpoint);+ const due = !rec.lastSnapshotMs || (rec.lastActivityMs ?? 0) > rec.lastSnapshotMs;+ if (due) {+ await ensureRunning(rec.microvmId);+ await snapshotHome(scope, rec.microvmId);+ }+ await api.terminate(rec.microvmId);+ await store.delete(scope);+ reaped++;+ } catch (e) {+ reportError("sandbox_reap", "deep_idle_reap_failed", errMessage(e), scope);+ }+ });}return { reaped };},diff --git a/test/aws-sandbox.test.ts b/test/aws-sandbox.test.tsindex efdbb054f..c98a17885 100644--- a/test/aws-sandbox.test.ts+++ b/test/aws-sandbox.test.ts@@ -202,3 +202,130 @@ test("a hydrate failure terminates the fresh body instead of cold-starting overconst h2 = await sb.provision(layers);assert.equal(await sb.readFile(h2, "notes/todo.txt"), "buy milk");});++test("scope retirement terminates its body and removes only its snapshot, including after restart", async () => {+ const fake = installFakeMicrovm();+ const { createMemoryMap } = await import("../src/persistence/durable-map.ts");+ const store = createMemoryMap<import("../src/sandbox/aws-sandbox.ts").StoredMicrovm>();+ const sb = makeSandbox(fake, { store, snapshotIntervalMs: 0 });+ const first = await sb.provision(rw("personal:retire-one"));+ const other = await sb.provision(rw("personal:retire-other"));+ await sb.teardown(first);+ await sb.teardown(other);+ assert.equal(fake.s3store.size, 2);+ await makeSandbox(fake, { store }).destroyScope!("personal:retire-one");+ assert.equal(fake.bodies.get(first.id)!.state, "TERMINATED");+ assert.equal(fake.bodies.get(other.id)!.state, "SUSPENDED");+ assert.equal(fake.s3store.size, 1);+ assert.equal(await store.get("personal:retire-one"), null);+ assert.ok(await store.get("personal:retire-other"));+ await sb.destroyScope!("personal:retire-one");+ assert.equal(fake.s3store.size, 1);+});++for (const stage of ["terminate", "snapshot"] as const) {+ test(`scope retirement retains durable recovery metadata when ${stage} deletion fails`, async () => {+ const fake = installFakeMicrovm();+ const { createMemoryMap } = await import("../src/persistence/durable-map.ts");+ const store = createMemoryMap<import("../src/sandbox/aws-sandbox.ts").StoredMicrovm>();+ const sb = makeSandbox(fake, { store });+ const handle = await sb.provision(rw("personal:retire-failure"));+ await sb.teardown(handle);+ const terminate = fake.api.terminate;+ const send = fake.s3.send;+ if (stage === "terminate")+ fake.api.terminate = async () => {+ throw new Error("termination failed");+ };+ else+ fake.s3.send = async () => {+ throw new Error("snapshot deletion failed");+ };+ await assert.rejects(sb.destroyScope!("personal:retire-failure"), /failed/);+ assert.ok(await store.get("personal:retire-failure"));+ fake.api.terminate = terminate;+ fake.s3.send = send;+ await sb.destroyScope!("personal:retire-failure");+ assert.equal(await store.get("personal:retire-failure"), null);+ });+}++test("failed AWS readiness remains discoverable for retirement when immediate termination fails", async () => {+ const fake = installFakeMicrovm();+ const { createMemoryMap } = await import("../src/persistence/durable-map.ts");+ const store = createMemoryMap<import("../src/sandbox/aws-sandbox.ts").StoredMicrovm>();+ const sb = makeSandbox(fake, { store });+ const wait = fake.api.waitForState;+ const terminate = fake.api.terminate;+ fake.api.waitForState = async () => {+ throw new Error("not ready");+ };+ fake.api.terminate = async () => {+ throw new Error("unavailable");+ };+ await assert.rejects(sb.provision(rw("personal:failed-launch")), /launch .* failed/);+ const pending = await store.get("personal:failed-launch");+ assert.ok(pending?.provisioning);+ fake.api.waitForState = wait;+ await assert.rejects(sb.provision(rw("personal:failed-launch")), /incomplete provisioning/);+ fake.api.terminate = terminate;+ await makeSandbox(fake, { store }).destroyScope!("personal:failed-launch");+ assert.equal(fake.bodies.get(pending.microvmId)!.state, "TERMINATED");+ assert.equal(await store.get("personal:failed-launch"), null);+});++test("destructive teardown of a stale AWS handle preserves a replacement scope", async () => {+ const fake = installFakeMicrovm();+ const sb = makeSandbox(fake, { snapshotIntervalMs: 0 });+ const layers = rw("personal:stale-destroy");+ const old = await sb.provision(layers);+ await sb.teardown(old);+ fake.killBody(old.id);+ const replacement = await sb.provision(layers);+ await sb.teardown(replacement);+ await sb.teardown(old, { destroy: true });+ assert.equal(fake.bodies.get(replacement.id)!.state, "SUSPENDED");+ assert.equal(fake.s3store.size, 1);+ assert.equal((await sb.provision(layers)).id, replacement.id);+});++for (const writer of ["teardown", "reaper"] as const) {+ test(`retirement waits for an in-flight ${writer} snapshot and prevents restoration`, async () => {+ const fake = installFakeMicrovm();+ const { createMemoryMap } = await import("../src/persistence/durable-map.ts");+ const store = createMemoryMap<import("../src/sandbox/aws-sandbox.ts").StoredMicrovm>();+ const sb = makeSandbox(fake, { store, snapshotIntervalMs: 0 });+ const scope = `personal:retire-race-${writer}`;+ const handle = await sb.provision(rw(scope));+ await sb.writeFile(handle, "retired.txt", "must not return");+ if (writer === "reaper") {+ await sb.teardown(handle);+ await store.merge(scope, { lastActivityMs: 2, lastSnapshotMs: 1 });+ }+ const uploading = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const send = fake.s3.send;+ fake.s3.send = async (command: unknown) => {+ if (command?.constructor.name === "CompleteMultipartUploadCommand") {+ uploading.resolve();+ await release.promise;+ }+ return send(command);+ };+ const snapshot = writer === "reaper" ? sb.reapDeepIdle!(1) : sb.teardown(handle);+ await uploading.promise;+ let retired = false;+ const retirement = sb.destroyScope!(scope).then(() => {+ retired = true;+ });+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(retired, false);+ release.resolve();+ await Promise.all([snapshot, retirement]);+ assert.equal(fake.s3store.size, 0);+ assert.equal(await store.get(scope), null);+ const replacement = await sb.provision(rw(scope));+ assert.equal(await sb.readFile(replacement, "retired.txt"), null);+ await sb.destroyScope!(scope);+ });+}diff --git a/test/live-slack-request-bounds.test.ts b/test/live-slack-request-bounds.test.tsnew file mode 100644index 000000000..aba337c4d--- /dev/null+++ b/test/live-slack-request-bounds.test.ts@@ -0,0 +1,44 @@+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { once } from "node:events";+import test from "node:test";+import { SlackClient } from "./live-slack/slack.ts";+import { CoreClient } from "./live-slack/core.ts";++for (const status of [429, 500]) {+ test(`Slack qualification fails promptly on HTTP ${status} without hidden retries`, async () => {+ let requests = 0;+ const server = createServer((_req, res) => {+ requests++;+ res.writeHead(status, { "content-type": "application/json", "retry-after": "3600" });+ res.end(JSON.stringify({ ok: false, error: "qualification-test" }));+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ try {+ const address = server.address();+ assert.ok(address && typeof address !== "string");+ const client = new SlackClient("synthetic-token", `http://127.0.0.1:${address.port}`);+ await assert.rejects(client.authTest());+ assert.equal(requests, 1);+ } finally {+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });+}++test("Core qualification request deadline aborts a stalled provider request", async () => {+ const server = createServer(() => {});+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ try {+ const address = server.address();+ assert.ok(address && typeof address !== "string");+ const core = new CoreClient(`http://127.0.0.1:${address.port}`, "synthetic-secret");+ await assert.rejects(core.withSignal(AbortSignal.timeout(50)).listSandboxes("channel:test"), /timeout|abort/i);+ } finally {+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});diff --git a/test/live-slack-sandbox-providers.test.ts b/test/live-slack-sandbox-providers.test.tsnew file mode 100644index 000000000..9bb258702--- /dev/null+++ b/test/live-slack-sandbox-providers.test.ts@@ -0,0 +1,137 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ assertSandboxExecution,+ sandboxProviders,+ sandboxProviderScenarios,+ selectSandboxProviderScenarios,+} from "./live-slack/scenarios-sandbox-providers.ts";+import type { Ctx } from "./live-slack/harness.ts";++function evidence(sandboxId = "box", stdout = "nonce\n"): unknown[] {+ return [+ { type: "tool_call", payload: { tool: "sandbox", action: "exec", sandbox_id: sandboxId, callId: "call" } },+ {+ type: "tool_result",+ payload: { tool: "sandbox", action: "exec", callId: "call", isError: false, code: 0, timedOut: false, stdout },+ },+ ];+}++test("provider execution requires correlated success on the exact sandbox", () => {+ assert.doesNotThrow(() => assertSandboxExecution(evidence(), "box", "nonce\n"));+ for (const patch of [+ { tool: "read" },+ { action: "start_process" },+ { callId: "unrelated" },+ { isError: true },+ { code: 1 },+ { timedOut: true },+ { stdout: "wrong\n" },+ { stdout: undefined, result: "nonce\n" },+ ]) {+ const entries = evidence() as Array<{ type: string; payload: Record<string, unknown> }>;+ Object.assign(entries[1]!.payload, patch);+ assert.throws(() => assertSandboxExecution(entries, "box", "nonce\n"));+ }+ assert.throws(() => assertSandboxExecution(evidence("other"), "box", "nonce\n"));+ assert.throws(() => assertSandboxExecution([{ type: "assistant", payload: { text: "nonce" } }], "box", "nonce\n"));+});++test("every provider has its own parallel execution scenario", () => {+ assert.deepEqual(sandboxProviders.toSorted(), [+ "agent37",+ "aws",+ "e2b",+ "local",+ "modal",+ "porter",+ "smolmachines",+ "sprites",+ ]);+ assert.equal(sandboxProviderScenarios.length, sandboxProviders.length);+ assert.ok(sandboxProviderScenarios.every((s) => s.lane === "parallel" && s.tags?.includes("provider-execution")));+});++for (const backend of sandboxProviders) {+ test(`${backend} fails qualification when unavailable`, async () => {+ const ctx = {+ freshChannel: async () => ({ id: "test" }),+ core: {+ withSignal() {+ return this;+ },+ listSandboxes: async () => ({ providers: [], sandboxes: [] }),+ },+ } as unknown as Ctx;+ await assert.rejects(+ sandboxProviderScenarios.find((s) => s.name === `sandbox-execute-${backend}`)!.run(ctx),+ /required sandbox provider .* is unavailable/,+ );+ });+}++for (const failExecution of [false, true]) {+ test(`provider execution cleans up its sandbox after ${failExecution ? "failure" : "success"}`, async () => {+ const actions: Record<string, unknown>[] = [];+ let expected = "";+ const ctx = {+ marker: () => "owned-test-box",+ freshChannel: async () => ({+ id: "test",+ mention: async (text: string) => {+ const parts = [...text.matchAll(/'([0-9a-f-]{36})'/g)].map((m) => m[1]);+ assert.equal(parts.length, 2);+ expected = parts.join("") + "\n";+ return "root";+ },+ waitForBotReply: async () => {+ if (failExecution) throw new Error("agent could not execute");+ return {};+ },+ }),+ core: {+ withSignal() {+ return this;+ },+ listSandboxes: async () => ({+ providers: [{ name: "sprites", actions: ["create", "retire"] }],+ sandboxes: actions.some((a) => a.action === "create")+ ? [{ id: "box", backend: "sprites", name: "owned-test-box" }]+ : [],+ }),+ manageSandbox: async (_scope: string, body: Record<string, unknown>) => {+ actions.push(body);+ return { id: "box", backend: "sprites" };+ },+ findSessionByThread: async () => ({ id: "session", entries: evidence("box", expected) }),+ },+ } as unknown as Ctx;+ const run = sandboxProviderScenarios.find((s) => s.name === "sandbox-execute-sprites")!.run(ctx);+ if (failExecution) await assert.rejects(run, /agent could not execute/);+ else await run;+ assert.deepEqual(actions.slice(-2), [+ { action: "default", sandboxId: null },+ { action: "retire", sandboxId: "box" },+ ]);+ });+}++test("explicit provider selection retains strict coverage without treating deferred providers as failed skips", () => {+ const selected = selectSandboxProviderScenarios("sprites,aws,local,smolmachines,e2b,modal");+ assert.deepEqual(+ selected.map((s) => s.name),+ [+ "sandbox-execute-sprites",+ "sandbox-execute-aws",+ "sandbox-execute-local",+ "sandbox-execute-smolmachines",+ "sandbox-execute-e2b",+ "sandbox-execute-modal",+ ],+ );+ assert.equal(selectSandboxProviderScenarios("all").length, 8);+ assert.deepEqual(selectSandboxProviderScenarios(undefined), []);+ for (const value of ["", "sprites,", "typo", "sprites,sprites", "all,sprites", "constructor", "__proto__"])+ assert.throws(() => selectSandboxProviderScenarios(value));+});diff --git a/test/live-slack/README.md b/test/live-slack/README.mdindex 05d574a69..4ed23b91c 100644--- a/test/live-slack/README.md+++ b/test/live-slack/README.md@@ -179,3 +179,45 @@ For deeper debugging, the artifact also has `out/summary.md` (also in the step sscenario's full session entries **and LLM requests** (ground truth for "what did the agentactually see") — and `.ci-instance/{core,slack}.log`. Don't trust the agent's in-channelself-explanations; read the transcript.++## Sandbox-provider release qualification++Set `LIVE_E2E_SANDBOX_PROVIDERS=all` with `LIVE_E2E_GATE=1` to require a real+agent `sandbox exec` on every implemented provider: Sprites, AWS, local Docker,+Smolmachines, E2B, Modal, Porter, and Agent37. These eight scenarios run concurrently+in their own lane alongside the selected catalog. The source type requires a+coverage entry when a provider is added. Missing providers, skips, retries,+execution errors, and cleanup errors block release. Provider checks do not retry; a failed first execution blocks qualification.+Release qualification cannot shard away a required provider check.++Alternatively, set `LIVE_E2E_SANDBOX_PROVIDERS` to an explicit comma-separated+provider list. Every listed provider remains mandatory and runs concurrently.+Providers omitted from that list are outside the gate, not failed or skipped+required tests. Empty, unknown, and duplicate provider names are rejected.++Each check creates an isolated sandbox, makes it the default only for its fresh+test channel, and asks the agent to execute a nonce command on its explicit ID.+The assertion requires a correlated tool call and result with exit code zero,+no timeout, and exact stdout. Agent reply text cannot satisfy it. Cleanup clears+the test channel default and retires its named test resources, including failed+provisioning records. Core requests are bounded, cleanup uses a separate deadline,+and the runner waits for provider cleanup to settle before recording an attempt+as timed out. Slack requests time out after 30 seconds without SDK retries+or automatic rate-limit waits; the scenario runner owns retry policy. A cleanup deadline failure remains a release blocker and requires+operator reconciliation of retained resource records.++The target instance must enable sandbox resources and configure every required+provider with real credentials and infrastructure. Local Docker additionally+requires a Docker-capable host and a built sandbox image; a Fargate service alone+cannot supply it. Unconfigured providers are failures, never optional coverage.++When staging cannot host Docker, run `scripts/qualify-local-provider.sh+/path/to/release-candidate.json` as a separate required job on an ephemeral+Docker-capable ARM64 runner. It pulls the candidate's immutable core image from+ECR and checks its embedded source SHA against the checkout. The runner builds+the local sandbox from that source, then invokes the candidate's real application,+Pi harness, model, and sandbox tools. Only the probe and transcript assertion are+mounted into the core container; application code comes from the candidate image.+Provide AWS ECR access and `ANTHROPIC_API_KEY`. Require this job alongside cloud+qualification before promotion. If capturing output through a pipe, use a shell+with `pipefail` so a failed probe cannot become a successful job.diff --git a/test/live-slack/core.ts b/test/live-slack/core.tsindex a01adab9f..ef5f74357 100644--- a/test/live-slack/core.ts+++ b/test/live-slack/core.ts@@ -15,11 +15,17 @@ export class CoreClient {private readonly baseUrl: string;private readonly signingSecret: string;readonly orgScope: string;+ private readonly requestSignal?: AbortSignal;- constructor(baseUrl: string, signingSecret: string, orgScope = "org:acme") {+ constructor(baseUrl: string, signingSecret: string, orgScope = "org:acme", requestSignal?: AbortSignal) {this.baseUrl = baseUrl;this.signingSecret = signingSecret;this.orgScope = orgScope;+ this.requestSignal = requestSignal;+ }++ withSignal(signal: AbortSignal): CoreClient {+ return new CoreClient(this.baseUrl, this.signingSecret, this.orgScope, signal);}private async request(@@ -34,22 +40,35 @@ export class CoreClient {"content-type": "application/json",...extra,});- const res = await fetch(`${this.baseUrl}${salted}`, { method, headers, ...(raw ? { body: raw } : {}) });+ const deadline = AbortSignal.timeout(120_000);+ const signal = this.requestSignal ? AbortSignal.any([deadline, this.requestSignal]) : deadline;+ const res = await fetch(`${this.baseUrl}${salted}`, { method, headers, signal, ...(raw ? { body: raw } : {}) });const data = await res.json().catch(() => ({}));if (!res.ok) throw new Error(`core ${method} ${pathWithQuery}: ${res.status} ${JSON.stringify(data)}`);return data;}- private async admin(method: string, pathWithQuery: string): Promise<any> {+ private async admin(method: string, pathWithQuery: string, body?: unknown): Promise<any> {const orgId = this.orgScope.split(":")[1] ?? "acme";const portalSecret = process.env.PORTAL_IDENTITY_SECRET || this.signingSecret;const identity = await mintPortalIdentity({ p: ADMIN_PRINCIPAL, exp: Date.now() + 60_000 }, portalSecret);- return this.request(method, pathWithQuery, undefined, {+ return this.request(method, pathWithQuery, body, {"x-admin-actor": `${ADMIN_PRINCIPAL}@${orgId}`,[PORTAL_IDENTITY_HEADER]: identity,});}+ listSandboxes(scopeId: string): Promise<{+ providers: Array<{ name: string; actions: string[] }>;+ sandboxes: Array<{ id: string; name: string; backend: string; state: string }>;+ }> {+ return this.admin("GET", `/v1/admin/sandboxes/${encodeURIComponent(scopeId)}`);+ }++ manageSandbox(scopeId: string, body: Record<string, unknown>): Promise<{ id: string; backend: string }> {+ return this.admin("POST", `/v1/admin/sandboxes/${encodeURIComponent(scopeId)}`, body);+ }+listSessions(): Promise<{ sessions: SessionSummary[] }> {return this.admin("GET", `/v1/admin/sessions?scope=${encodeURIComponent(this.orgScope)}&limit=200`);}diff --git a/test/live-slack/local-provider.ts b/test/live-slack/local-provider.tsnew file mode 100644index 000000000..10527505d--- /dev/null+++ b/test/live-slack/local-provider.ts@@ -0,0 +1,92 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { loadConfig } from "../../src/config.ts";+import { buildApp } from "../../src/wiring.ts";+import { setOnboardingStatus } from "../../src/onboarding/onboarding.ts";+import { assertSandboxExecution } from "./scenarios-sandbox-providers.ts";++async function main(): Promise<void> {+ assert.ok(process.env.ANTHROPIC_API_KEY, "a live model credential is required");+ assert.ok(process.env.LOCAL_SANDBOX_IMAGE?.startsWith("sha256:"), "use an immutable local sandbox image ID");+ assert.ok(process.env.QM_CORE_CONTAINER, "the candidate core container name is required");+ assert.ok(process.env.EXPECTED_SOURCE_SHA, "the expected source pin is required");+ assert.equal(process.env.GIT_SHA, process.env.EXPECTED_SOURCE_SHA, "candidate image does not match the source pin");+ const config = loadConfig();+ const built = buildApp({+ ...config,+ dataDir: mkdtempSync(join(tmpdir(), "provider-qualification-")),+ sessionStore: "memory",+ runStore: "memory",+ harness: "pi",+ sandboxBackend: "local",+ sandboxResourcesEnabled: true,+ backgroundWorkEnabled: false,+ turnWallClockMs: 180_000,+ localSandbox: { ...config.localSandbox, coreContainer: process.env.QM_CORE_CONTAINER },+ });+ const actorId = `provider-qualification-${randomUUID()}`;+ const scopeId = `personal:${actorId}`;+ const name = `local-${randomUUID()}`;+ const failures: unknown[] = [];+ try {+ await built.identity.hydrate();+ await built.deploymentLayerReady;+ await built.sandboxResources.initialize();+ await built.memory.replace(+ scopeId,+ setOnboardingStatus("", "completed", new Date().toISOString().slice(0, 10)),+ actorId,+ );+ const sandbox = await built.sandboxResources.create(actorId, scopeId, "local", name);+ assert.equal(sandbox.backend, "local");+ await built.sandboxResources.setDefault(actorId, scopeId, sandbox.id);+ const left = randomUUID();+ const right = randomUUID();+ const result = await built.app.turn({+ surface: "qualification",+ actor: { externalId: actorId },+ conversation: { kind: "dm", threadRef: `qualification:${randomUUID()}` },+ text: `Use sandbox action exec with sandbox_id ${sandbox.id} to run exactly: printf '%s%s\\n' '${left}' '${right}'. Set timeout_seconds to 30. Report the result.`,+ });+ assert.equal(result.status, "ok", result.reason ?? result.reply);+ assert.ok(result.sessionId);+ const entries = await built.sessions.getEntries(result.sessionId);+ try {+ assertSandboxExecution(entries, sandbox.id, `${left}${right}\n`);+ } catch (error) {+ console.error(JSON.stringify({ reply: result.reply, entries }));+ throw error;+ }+ } catch (error) {+ failures.push(error);+ }+ try {+ const { sandboxes } = await built.sandboxResources.list(actorId, scopeId);+ await built.sandboxResources.setDefault(actorId, scopeId, null);+ for (const sandbox of sandboxes.filter((s) => s.ownerScopeId === scopeId && s.name === name))+ await built.sandboxResources.retire(actorId, sandbox.id);+ } catch (error) {+ failures.push(error);+ }+ await built.runtime.stop();+ if (failures.length)+ throw new AggregateError(failures, `local qualification failed: ${failures.map(String).join("; ")}`);+ console.log(+ JSON.stringify({+ provider: "local",+ source: process.env.GIT_SHA,+ sandboxImage: process.env.LOCAL_SANDBOX_IMAGE,+ status: "pass",+ }),+ );+}++main()+ .then(() => process.exit(0))+ .catch((error) => {+ console.error(error);+ process.exit(1);+ });diff --git a/test/live-slack/run.ts b/test/live-slack/run.tsindex 4673797ab..8d0fb3187 100644--- a/test/live-slack/run.ts+++ b/test/live-slack/run.ts@@ -15,6 +15,7 @@ import {} from "./harness.ts";import { renderGallery } from "./gallery.ts";import { scenarios } from "./scenarios.ts";+import { sandboxProviderScenarios, selectSandboxProviderScenarios } from "./scenarios-sandbox-providers.ts";import { startEventPump, TwinAdmin } from "./arga.ts";const OUT_DIR = path.join(import.meta.dirname, "out");@@ -162,10 +163,11 @@ function selectScenarios(env: Env): { selected: Scenario[]; skipped: ScenarioResconst filter = raw === "all" ? undefined : raw;const skipped: ScenarioResult[] = [];const selected: Scenario[] = [];- for (const s of scenarios) {+ const providerScenarios = selectSandboxProviderScenarios(process.env.LIVE_E2E_SANDBOX_PROVIDERS);+ for (const s of [...scenarios, ...providerScenarios]) {if (filter) {const byTag = filter.startsWith("@") && (s.tags ?? []).includes(filter.slice(1));- if (!byTag && !s.name.includes(filter)) continue;+ if (!byTag && !s.name.includes(filter) && !s.tags?.includes("provider-execution")) continue;}const tags = s.tags ?? [];if (tags.includes("sandbox") && !env.sandbox) {@@ -277,13 +279,15 @@ async function runScenario(env: Env, scenario: Scenario): Promise<ScenarioResultconst started = Date.now();const quarantined = (scenario.tags ?? []).includes("quarantine");const sessionIds: string[] = [];- for (let attempt = 1; attempt <= 2; attempt++) {+ const maxAttempts = scenario.tags?.includes("provider-execution") ? 1 : 2;+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {const ctx = new Ctx(env, scenario, attempt);const timeoutMs = scenario.timeoutMs ?? 4 * 60_000;let timer: NodeJS.Timeout | undefined;+ const operation = scenario.run(ctx);try {await Promise.race([- scenario.run(ctx),+ operation,new Promise((_, reject) => {timer = setTimeout(() => reject(new Error(`scenario timed out after ${timeoutMs}ms`)), timeoutMs);}),@@ -303,13 +307,14 @@ async function runScenario(env: Env, scenario: Scenario): Promise<ScenarioResult...(quarantined ? { quarantined } : {}),};} catch (err) {+ if (scenario.tags?.includes("provider-execution")) await operation.catch(() => {});const message = err instanceof Error ? (err.stack ?? err.message) : String(err);console.error(` ❌ ${scenario.name} attempt ${attempt}: ${message.split("\n")[0]}`);const timeline = ctx.timeline.toJSON();const ids = await dumpTranscript(env, scenario, ctx).catch(() => [] as string[]);sessionIds.push(...ids);await ctx.cleanup().catch(() => {});- if (attempt === 2) {+ if (attempt === maxAttempts) {const coreErrors = await env.core.listErrors().then((r) =>@@ -322,7 +327,7 @@ async function runScenario(env: Env, scenario: Scenario): Promise<ScenarioResultreturn {name: scenario.name,status: "fail",- attempts: 2,+ attempts: maxAttempts,durationMs: Date.now() - started,error: message,timeline,@@ -393,6 +398,12 @@ async function runCatalog(env: Env): Promise<void> {await warmUp(env, releaseGate);const picked = selectScenarios(env);const { selected, skipped } = applyShard(picked.selected, picked.skipped);+ if (releaseGate) {+ for (const provider of selectSandboxProviderScenarios(process.env.LIVE_E2E_SANDBOX_PROVIDERS)) {+ if (!selected.some((scenario) => scenario.name === provider.name))+ throw new Error(`required provider scenario missing from release gate: ${provider.name}`);+ }+ }if (releaseGate && selected.length === 0) throw new Error("release gate selected no scenarios");for (const s of skipped) console.log(` ⏭️ ${s.name}: skipped — ${s.skipReason}`);const concurrency = Number(process.env.LIVE_E2E_CONCURRENCY) || 8;@@ -400,16 +411,18 @@ async function runCatalog(env: Env): Promise<void> {`live-e2e run ${env.runId}: ${selected.length} scenarios (concurrency ${concurrency}), agent <@${env.botUserId}>, QA user <@${env.qaUserId}>`,);- const parallelLane = selected.filter((s) => s.lane === "parallel");+ const providerLane = selected.filter((s) => s.tags?.includes("provider-execution"));+ const parallelLane = selected.filter((s) => s.lane === "parallel" && !s.tags?.includes("provider-execution"));const dmLane = selected.filter((s) => s.lane === "dm");const exclusiveLane = selected.filter((s) => s.lane === "exclusive");- const [parallelResults, dmResults] = await Promise.all([+ const [parallelResults, dmResults, providerResults] = await Promise.all([runLane(env, parallelLane, concurrency),runLane(env, dmLane, 1),+ runLane(env, providerLane, sandboxProviderScenarios.length),]);const exclusiveResults = await runLane(env, exclusiveLane, 1);- const results = [...parallelResults, ...dmResults, ...exclusiveResults, ...skipped];+ const results = [...parallelResults, ...dmResults, ...providerResults, ...exclusiveResults, ...skipped];results.sort((a, b) => a.name.localeCompare(b.name));const failures = results.filter((r) => r.status === "fail" && !r.quarantined);const quarantinedFails = results.filter((r) => r.status === "fail" && r.quarantined);diff --git a/test/live-slack/scenarios-sandbox-providers.ts b/test/live-slack/scenarios-sandbox-providers.tsnew file mode 100644index 000000000..8d632034c--- /dev/null+++ b/test/live-slack/scenarios-sandbox-providers.ts@@ -0,0 +1,119 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import type { SandboxBackendName } from "../../src/sandbox/sandbox-routing.ts";+import { isObj } from "../../src/util/objects.ts";+import type { Scenario } from "./harness.ts";++const providerCoverage: Record<SandboxBackendName, true> = {+ sprites: true,+ aws: true,+ local: true,+ smolmachines: true,+ e2b: true,+ modal: true,+ porter: true,+ agent37: true,+};++export const sandboxProviders = Object.keys(providerCoverage) as SandboxBackendName[];++export function assertSandboxExecution(entries: readonly unknown[], sandboxId: string, stdout: string): void {+ const calls = new Set(+ entries.flatMap((entry) => {+ if (!isObj(entry) || entry.type !== "tool_call" || !isObj(entry.payload)) return [];+ const p = entry.payload;+ return p.tool === "sandbox" && p.action === "exec" && p.sandbox_id === sandboxId && typeof p.callId === "string"+ ? [p.callId]+ : [];+ }),+ );+ assert.ok(calls.size, `no sandbox exec call targeted ${sandboxId}`);+ assert.ok(+ entries.some((entry) => {+ if (!isObj(entry) || entry.type !== "tool_result" || !isObj(entry.payload)) return false;+ const p = entry.payload;+ return (+ p.tool === "sandbox" &&+ p.action === "exec" &&+ typeof p.callId === "string" &&+ calls.has(p.callId) &&+ p.isError === false &&+ p.code === 0 &&+ p.timedOut === false &&+ p.stdout === stdout+ );+ }),+ `no successful sandbox exec result with exact stdout on ${sandboxId}`,+ );+}++export const sandboxProviderScenarios: Scenario[] = sandboxProviders.map((backend) => ({+ name: `sandbox-execute-${backend}`,+ lane: "parallel",+ tags: ["sandbox", "provider-execution"],+ timeoutMs: 6 * 60_000,+ async run(ctx) {+ const core = ctx.core.withSignal(AbortSignal.timeout(4 * 60_000));+ const ch = await ctx.freshChannel();+ const scopeId = `channel:${ch.id}`;+ const inventory = await core.listSandboxes(scopeId);+ const provider = inventory.providers.find((p) => p.name === backend);+ assert.ok(provider, `required sandbox provider ${backend} is unavailable`);+ assert.ok(provider.actions.includes("create"), `${backend} cannot create a test sandbox`);+ assert.ok(provider.actions.includes("retire"), `${backend} cannot clean up a test sandbox`);+ const name = ctx.marker();+ const failures: unknown[] = [];+ try {+ const sandbox = await core.manageSandbox(scopeId, { action: "create", backend, name });+ assert.equal(sandbox.backend, backend);+ assert.ok(sandbox.id);+ await core.manageSandbox(scopeId, { action: "default", sandboxId: sandbox.id });+ const left = randomUUID();+ const right = randomUUID();+ const root = await ch.mention(+ `Use the sandbox tool with action exec and sandbox_id ${sandbox.id} to run exactly this command: printf '%s%s\\n' '${left}' '${right}'. Set timeout_seconds to 30. Report the result. Do not use another sandbox or a background process.`,+ );+ await ch.waitForBotReply(root, { timeoutMs: 3 * 60_000 });+ const session = await core.findSessionByThread(ch.id, root);+ assert.ok(session, `no session for ${backend} execution`);+ assertSandboxExecution(session.entries, sandbox.id, `${left}${right}\n`);+ } catch (error) {+ failures.push(error);+ }+ try {+ const core = ctx.core.withSignal(AbortSignal.timeout(90_000));+ const inventory = await core.listSandboxes(scopeId);+ const created = inventory.sandboxes.filter((s) => s.name === name && s.backend === backend);+ if (created.length) {+ await core.manageSandbox(scopeId, { action: "default", sandboxId: null });+ const cleanup = await Promise.allSettled(+ created.map((s) => core.manageSandbox(scopeId, { action: "retire", sandboxId: s.id })),+ );+ const failures = cleanup.filter((r) => r.status === "rejected");+ if (failures.length)+ throw new AggregateError(+ failures.map((r) => r.reason),+ `${backend} cleanup failed`,+ );+ }+ } catch (error) {+ failures.push(error);+ }+ if (failures.length)+ throw new AggregateError(failures, `${backend} execution or cleanup failed: ${failures.map(String).join("; ")}`);+ },+}));++export function selectSandboxProviderScenarios(value: string | undefined): Scenario[] {+ if (value === undefined) return [];+ if (value === "all") return sandboxProviderScenarios;+ const names = value.split(",").map((name) => name.trim());+ assert.ok(+ names.length && names.every((name) => name && Object.hasOwn(providerCoverage, name)),+ "LIVE_E2E_SANDBOX_PROVIDERS must be all or a comma-separated list of supported providers",+ );+ assert.equal(new Set(names).size, names.length, "sandbox provider list contains duplicates");+ return sandboxProviderScenarios.filter((scenario) =>+ names.some((name) => scenario.name === `sandbox-execute-${name}`),+ );+}diff --git a/test/live-slack/slack.ts b/test/live-slack/slack.tsindex 1894c7f6a..38374fde2 100644--- a/test/live-slack/slack.ts+++ b/test/live-slack/slack.ts@@ -19,7 +19,12 @@ export class SlackClient {private readonly web: WebClient;constructor(token: string, apiUrl = process.env.SLACK_API_URL) {- this.web = new WebClient(token, apiUrl ? { slackApiUrl: apiUrlOf(apiUrl) } : {});+ this.web = new WebClient(token, {+ ...(apiUrl ? { slackApiUrl: apiUrlOf(apiUrl) } : {}),+ timeout: 30_000,+ retryConfig: { retries: 0 },+ rejectRateLimitedCalls: true,+ });}async authTest(): Promise<{ userId: string; user: string; teamId: string; url: string }> {diff --git a/test/postgres-credential-usage-sink.test.ts b/test/postgres-credential-usage-sink.test.tsindex 3b88a0446..365f163a8 100644--- a/test/postgres-credential-usage-sink.test.ts+++ b/test/postgres-credential-usage-sink.test.ts@@ -19,11 +19,13 @@ before(async () => {test("pg credential-usage sink: persists broker calls, filters by scope/slug/since, newest-first",{ skip },- async () => {+ async (t) => {const sink = createPostgresCredentialUsageSink(URL!);const s1 = scopeId("personal", "U1");const s2 = scopeId("personal", "U2");+ const now = Date.now();+ const clock = t.mock.method(Date, "now", () => now);sink.record({slug: "x-firehose",host: "api.x.com",@@ -32,11 +34,15 @@ test(scopeLabel: s1,principalId: "U1",});+ clock.mock.mockImplementation(() => now + 1);sink.record({ slug: "serp", host: "serpapi.com", status: "denied", scopeLabel: s2, principalId: "U2" });+ clock.mock.restore();await settle(async () => (await sink.list({ limit: 100 })).length === 2);const all = await sink.list({ limit: 100 });assert.equal(all.length, 2, "both brokered calls persisted");+ assert.equal(all[0]!.ts, now + 1);+ assert.equal(all[1]!.ts, now);assert.equal(all[0]!.scopeLabel, s2, "newest first");assert.equal(all[0]!.status, "denied");assert.equal(all[0]!.upstreamStatus, undefined, "an absent upstream status stays absent (not 0)");diff --git a/test/postgres-egress-audit-sink.test.ts b/test/postgres-egress-audit-sink.test.tsindex 800545fba..64043274e 100644--- a/test/postgres-egress-audit-sink.test.ts+++ b/test/postgres-egress-audit-sink.test.ts@@ -19,11 +19,13 @@ before(async () => {test("pg egress-audit sink: persists firewall decisions, filters by scope/source/since, newest-first",{ skip },- async () => {+ async (t) => {const sink = createPostgresEgressAuditSink(URL!);const s1 = scopeId("personal", "U1");const s2 = scopeId("personal", "U2");+ const now = Date.now();+ const clock = t.mock.method(Date, "now", () => now);sink.record({source: "proxy",host: "api.github.com",@@ -35,6 +37,7 @@ test(scopeLabel: s1,principalId: "U1",});+ clock.mock.mockImplementation(() => now + 1);sink.record({source: "proxy",host: "pastebin.com",@@ -44,10 +47,13 @@ test(port: 443,scopeLabel: s2,});+ clock.mock.restore();await settle(async () => (await sink.list({ limit: 100 })).length === 2);const all = await sink.list({ limit: 100 });assert.equal(all.length, 2, "both decisions persisted");+ assert.equal(all[0]!.ts, now + 1);+ assert.equal(all[1]!.ts, now);assert.equal(all[0]!.scopeLabel, s2, "newest first");assert.equal(all[0]!.allowed, false);assert.equal(all[0]!.verdict, "host_denied");diff --git a/test/postgres-error-log.test.ts b/test/postgres-error-log.test.tsindex 9f6bd40f8..57a26673a 100644--- a/test/postgres-error-log.test.ts+++ b/test/postgres-error-log.test.ts@@ -15,11 +15,13 @@ before(async () => {await p.end();});-test("pg error log: persists events, filters by scope, newest-first, shape-only", { skip }, async () => {+test("pg error log: persists events, filters by scope, newest-first, shape-only", { skip }, async (t) => {const log = createPostgresErrorLog(URL!);const s1 = scopeId("channel", "C1");const s2 = scopeId("channel", "C2");+ const now = Date.now();+ const clock = t.mock.method(Date, "now", () => now);log.record({category: "command_policy",code: "denied",@@ -27,10 +29,14 @@ test("pg error log: persists events, filters by scope, newest-first, shape-only"scopeLabel: s1,sessionId: "sess-1",});+ clock.mock.mockImplementation(() => now + 1);log.record({ category: "turn", code: "error", message: "boom (shape-only)", scopeLabel: s2 });+ clock.mock.restore();const all = await log.list({ limit: 100 });assert.equal(all.length, 2, "both events persisted");+ assert.equal(all[0]!.ts, now + 1);+ assert.equal(all[1]!.ts, now);assert.equal(all[0]!.scopeLabel, s2);assert.equal(all[0]!.category, "turn");assert.equal(all[0]!.code, "error");diff --git a/test/postgres-metrics-sink.test.ts b/test/postgres-metrics-sink.test.tsindex 148034a90..5bac79156 100644--- a/test/postgres-metrics-sink.test.ts+++ b/test/postgres-metrics-sink.test.ts@@ -16,11 +16,13 @@ before(async () => {await p.end();});-test("pg metrics sink: persists samples, filters by scope + since, newest-first", { skip }, async () => {+test("pg metrics sink: persists samples, filters by scope + since, newest-first", { skip }, async (t) => {const sink = createPostgresMetricsSink(URL!);const s1 = scopeId("channel", "C1");const s2 = scopeId("channel", "C2");+ const now = Date.now();+ const clock = t.mock.method(Date, "now", () => now);sink.record({totalMs: 100,ttftMs: 40,@@ -46,11 +48,15 @@ test("pg metrics sink: persists samples, filters by scope + since, newest-first"cacheWrite: 0,uncachedInput: 1000,});+ clock.mock.mockImplementation(() => now + 1);sink.record({ totalMs: 200, status: "paused", scopeLabel: s2, sessionId: "sess-B" });+ clock.mock.restore();await settle(async () => (await sink.list({ limit: 100 })).length === 2);const all = await sink.list({ limit: 100 });assert.equal(all.length, 2, "both samples persisted");+ assert.equal(all[0]!.ts, now + 1);+ assert.equal(all[1]!.ts, now);assert.equal(all[0]!.scopeLabel, s2);assert.equal(all[0]!.status, "paused");assert.equal(all[0]!.ttftMs, undefined, "an absent TTFT stays absent (not 0)");