diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index 755bad7e2b3..eb33d6db101 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -39,7 +39,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/actions/sandbox/host-aliases.ts", "docker-exec-command", 1], ["src/lib/actions/sandbox/sessions/passthrough.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/actions/sandbox/process-recovery.ts", "privileged-sandbox-exec", 2], - ["src/lib/actions/sandbox/snapshot.ts", "docker-exec-command", 1], ["src/lib/adapters/docker/container.ts", "docker-exec-command", 1], ["src/lib/diagnostics/debug.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/onboard.ts", "docker-exec-builder", 1], diff --git a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts index 2166ee58bf4..970c9cb169f 100644 --- a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts +++ b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts @@ -33,6 +33,9 @@ vi.mock("../../adapters/openshell/runtime", () => ({ getOpenshellBinary: vi.fn(() => "openshell"), runOpenshell: vi.fn(() => ({ status: 0, output: "" })), })); +vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ + getOpenShellSandboxDescriptor: vi.fn(), +})); vi.mock("../../credentials/store", () => ({ prompt: vi.fn() })); vi.mock("../../domain/sandbox/destroy", () => ({ getSandboxDeleteOutcome: vi.fn(() => ({ alreadyGone: false, gatewayUnreachable: false })), diff --git a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts index fc2f75a9b8f..9294a465199 100644 --- a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts @@ -249,6 +249,49 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { expect(f.restoreSandboxStateMock).toHaveBeenCalledWith("beta", "/tmp/backup-alpha"); }); + it("uses the live OpenShell descriptor image for Kubernetes snapshot clones", async () => { + let registeredClone: ReturnType = null; + f.registerSandboxMock.mockImplementation((entry) => (registeredClone = entry as never)); + f.getSandboxMock.mockImplementation((name) => + name === "alpha" + ? { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw-8090", + imageTag: "nemoclaw-alpha:stale-registry", + openshellDriver: "kubernetes", + provider: "nvidia-nim", + model: "nvidia/model-a", + } + : registeredClone, + ); + f.getOpenShellSandboxDescriptorMock.mockResolvedValue({ + id: "alpha-id", + name: "alpha", + image: "nemoclaw-alpha:live-descriptor", + }); + f.captureOpenshellMock.mockImplementation((args) => + f.openshellResponses(args, { + "sandbox exec": { status: 0, output: f.dcodeProbeOutput("no-runtime") }, + "sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" }, + }), + ); + f.getLatestBackupMock.mockReturnValue({ ...f.latestBackupFixture }); + const { runSandboxSnapshot } = await import("./snapshot"); + + await runSandboxSnapshot("alpha", { kind: "restore", to: "beta" }); + + expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenCalledTimes(2); + expect(f.getOpenShellSandboxDescriptorMock).toHaveBeenNthCalledWith( + 1, + "nemoclaw-8090", + "alpha", + ); + const createArgs = f.streamSandboxCreateMock.mock.calls[0]?.[1] ?? []; + expect(createArgs).toContain("nemoclaw-alpha:live-descriptor"); + expect(createArgs).not.toContain("nemoclaw-alpha:stale-registry"); + }); + it("blocks auto-create before deleting a destination when a gateway peer conflicts", async () => { const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); f.getSandboxMock.mockImplementation((name) => ({ diff --git a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts index e0117b0f9b1..f0c072618ae 100644 --- a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts +++ b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts @@ -114,6 +114,13 @@ export const getCustomPoliciesMock = vi.fn( () => [] as Array<{ name: string; content: string; sourcePath?: string }>, ); export const getLatestBackupMock = vi.fn(() => null as Record | null); +export const getOpenShellSandboxDescriptorMock = vi.fn( + async (_gatewayName: string, sandboxName: string) => ({ + id: `${sandboxName}-id`, + name: sandboxName, + image: `nemoclaw-${sandboxName}:live`, + }), +); export const applyPresetMock = vi.fn((_sandbox: string, _preset: string) => true); export const applyPresetContentMock = vi.fn( (_sandbox: string, _name: string, _content: string, _options?: unknown) => true, @@ -162,6 +169,10 @@ vi.mock("../../adapters/openshell/runtime", () => ({ runOpenshell: runOpenshellMock, })); +vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ + getOpenShellSandboxDescriptor: getOpenShellSandboxDescriptorMock, +})); + vi.mock("../../credentials/store", () => ({ prompt: vi.fn(), })); @@ -261,6 +272,11 @@ export function resetSnapshotRestoreMocks(): void { getAppliedPresetsMock.mockReturnValue([]); getCustomPoliciesMock.mockReturnValue([]); getLatestBackupMock.mockReturnValue(null); + getOpenShellSandboxDescriptorMock.mockImplementation(async (_gatewayName, sandboxName) => ({ + id: `${sandboxName}-id`, + name: sandboxName, + image: `nemoclaw-${sandboxName}:live`, + })); applyPresetMock.mockReturnValue(true); applyPresetContentMock.mockReturnValue(true); removePresetMock.mockReturnValue(true); diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 52b189a727b..69a92999644 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -146,7 +146,6 @@ const latestBackupFixture = { }; vi.mock("../../adapters/docker", () => ({ - dockerCapture: vi.fn(() => ""), dockerInspect: dockerInspectMock, })); @@ -156,6 +155,10 @@ vi.mock("../../adapters/openshell/runtime", () => ({ runOpenshell: runOpenshellMock, })); +vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ + getOpenShellSandboxDescriptor: vi.fn(), +})); + vi.mock("../../credentials/store", () => ({ prompt: vi.fn(), })); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 89af67ce0db..9240a5908e8 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -3,12 +3,12 @@ import fs from "node:fs"; import path from "node:path"; -import { dockerCapture } from "../../adapters/docker"; import { captureOpenshell, getOpenshellBinary, runOpenshell, } from "../../adapters/openshell/runtime"; +import { getOpenShellSandboxDescriptor } from "../../adapters/openshell/sandbox-control-routing"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt } from "../../credentials/store"; @@ -152,14 +152,14 @@ function renderSnapshotTable( } } -// Resolve the running src pod's image. Docker- and VM-driver sandboxes don't -// have the legacy cluster container — trust the registered imageTag and fail -// fast if it's missing. Only the "kubernetes" driver falls back to the -// kubectl probe inside the gateway container. -function resolveSrcPodImage( +// Resolve the running source sandbox's image. Docker- and VM-driver sandboxes +// trust the registered imageTag. Kubernetes sandboxes use OpenShell's strict +// descriptor read instead of reaching through the gateway container to run +// kubectl on OpenShell's internal cluster. +async function resolveSrcPodImage( srcName: string, srcEntry?: SandboxEntry | { name: string }, -): string | null { +): Promise { const registeredImage = (srcEntry as { imageTag?: string | null } | undefined)?.imageTag; const registeredDriver = (srcEntry as { openshellDriver?: string | null } | undefined) ?.openshellDriver; @@ -170,24 +170,8 @@ function resolveSrcPodImage( const srcGatewayName = resolveSandboxGatewayName( srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }, ); - const gatewayContainer = `openshell-cluster-${srcGatewayName}`; try { - const output = dockerCapture( - [ - "exec", - gatewayContainer, - "kubectl", - "get", - "pod", - srcName, - "-n", - "openshell", - "-o", - 'jsonpath={.spec.containers[?(@.name=="agent")].image}', - ], - { ignoreError: true, timeout: 10000 }, - ); - return output.trim().split(/\s+/)[0] || null; + return (await getOpenShellSandboxDescriptor(srcGatewayName, srcName)).image; } catch { return null; } @@ -959,7 +943,7 @@ async function runSnapshotRestoreUnlocked( snapshotExit(1); } const srcEntry = registry.getSandbox(sandboxName) || { name: sandboxName }; - const fromImage = resolveSrcPodImage(sandboxName, srcEntry); + const fromImage = await resolveSrcPodImage(sandboxName, srcEntry); if (!fromImage) { console.error( ` Cannot resolve image for source sandbox '${sandboxName}' — aborting before ` + @@ -1005,7 +989,7 @@ async function runSnapshotRestoreUnlocked( ); snapshotExit(1); } - const lockedFromImage = resolveSrcPodImage(sandboxName, lockedSourceEntry); + const lockedFromImage = await resolveSrcPodImage(sandboxName, lockedSourceEntry); if (!lockedFromImage) { console.error( ` Cannot resolve the current image for source sandbox '${sandboxName}' — aborting before changing '${targetSandbox}'.`, diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 242d271459b..42e8dbce332 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -24,6 +24,7 @@ import { type OpenShellGrpcApi, OpenShellGrpcOutputLimitError, OpenShellGrpcPreDispatchError, + type OpenShellSandboxDescriptor, } from "./grpc-sandbox-control"; import { OPENSHELL_EXEC_MAX_OUTPUT_BYTES, @@ -38,12 +39,24 @@ class FakeStream extends EventEmitter { } } +type GetSandboxCallback = Parameters[3]; +type FakeGetSandboxResponse = NonNullable[1]>; + interface FakeApiOptions { sandboxId?: string; + getResponse?: FakeGetSandboxResponse; getError?: ServiceError; emit?: (stream: FakeStream) => void; } +function descriptorResponse({ + id = "sb-id", + name = "alpha", + image = "nvcr.io/nvidia/nemoclaw:test", +}: Partial = {}): FakeGetSandboxResponse { + return { sandbox: { metadata: { id, name }, spec: { template: { image } } } }; +} + function fakeApi(fixture: FakeApiOptions = {}): { api: OpenShellGrpcApi; stream: FakeStream; @@ -67,11 +80,14 @@ function fakeApi(fixture: FakeApiOptions = {}): { queueMicrotask(() => { fixture.getError ? callback(fixture.getError) - : callback(null, { - sandbox: { - metadata: fixture.sandboxId === "" ? {} : { id: fixture.sandboxId ?? "sb-id" }, + : callback( + null, + fixture.getResponse ?? { + sandbox: { + metadata: fixture.sandboxId === "" ? {} : { id: fixture.sandboxId ?? "sb-id" }, + }, }, - }); + ); }); return request; }, @@ -299,13 +315,18 @@ describe("gRPC OpenShell sandbox control", () => { }; const server = new Server(); const requests: unknown[] = []; + const deadlines: Array = []; server.addService(loaded.openshell.v1.OpenShell.service, { getSandbox( - call: ServerUnaryCall<{ name: string }, { sandbox: { metadata: { id: string } } }>, - callback: sendUnaryData<{ sandbox: { metadata: { id: string } } }>, + call: ServerUnaryCall<{ name: string }, FakeGetSandboxResponse>, + callback: sendUnaryData, ) { requests.push(call.request); - callback(null, { sandbox: { metadata: { id: "wire-id" } } }); + deadlines.push(call.getDeadline()); + callback( + null, + descriptorResponse({ id: "wire-id", image: "nvcr.io/nvidia/nemoclaw:wire" }), + ); }, execSandbox( call: ServerWritableStream< @@ -331,6 +352,15 @@ describe("gRPC OpenShell sandbox control", () => { endpoint: `http://127.0.0.1:${port}`, }); try { + const before = Date.now(); + await expect(control.getSandboxDescriptor("alpha")).resolves.toEqual({ + id: "wire-id", + name: "alpha", + image: "nvcr.io/nvidia/nemoclaw:wire", + }); + const deadline = new Date(deadlines[0]).getTime(); + expect(deadline).toBeGreaterThanOrEqual(before + 15_000); + expect(deadline).toBeLessThanOrEqual(Date.now() + 15_000); await expect( control.exec({ sandboxName: "alpha", @@ -343,6 +373,7 @@ describe("gRPC OpenShell sandbox control", () => { stderr: "wire stderr", }); expect(requests).toEqual([ + { name: "alpha" }, { name: "alpha" }, { sandboxId: "wire-id", @@ -456,6 +487,22 @@ describe("gRPC OpenShell sandbox control", () => { }); }); + it.each([ + [descriptorResponse({ id: " " }), "without an id"], + [descriptorResponse({ name: "" }), "without a name"], + [descriptorResponse({ name: "beta" }), "returned sandbox 'beta' for requested sandbox 'alpha'"], + [descriptorResponse({ image: " " }), "without an image"], + ])("rejects incomplete or mismatched descriptors", async (getResponse, message) => { + const fake = fakeApi({ getResponse }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + await expect(control.getSandboxDescriptor("alpha")).rejects.toThrow(message); + expect(fake.execMetadata).toEqual([]); + }); + it.each([ [{ maxOutputBytes: -1 }, "maxOutputBytes"], [{ maxOutputBytes: 1.5 }, "maxOutputBytes"], diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index 1bfaf8d95e5..15a339e27a3 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -17,11 +17,15 @@ import { type SandboxExecResult, validateOpenShellExecRequest, } from "./sandbox-control"; +import { OPENSHELL_PROBE_TIMEOUT_MS } from "./timeouts"; const PROTO_VERSION = "0.0.72"; interface GetSandboxResponse { - sandbox?: { metadata?: { id?: string } }; + sandbox?: { + metadata?: { id?: string; name?: string }; + spec?: { template?: { image?: string } }; + }; } interface ExecSandboxEvent { @@ -68,9 +72,12 @@ export interface OpenShellGrpcClientConfig { } export interface GrpcOpenShellSandboxControl extends OpenShellSandboxControl { + getSandboxDescriptor(sandboxName: string): Promise; close(): void; } +export type OpenShellSandboxDescriptor = { id: string; name: string; image: string }; + export { OpenShellExecOutputLimitError as OpenShellGrpcOutputLimitError } from "./sandbox-control"; export class OpenShellGrpcPreDispatchError extends Error { @@ -187,28 +194,52 @@ function callMetadata(bearerToken: string | undefined): grpc.Metadata { return metadata; } -function sandboxId( +function getSandboxResponse( client: OpenShellGrpcApi, sandboxName: string, metadata: grpc.Metadata, options: grpc.CallOptions, -): Promise { +): Promise { return new Promise((resolve, reject) => { client.getSandbox({ name: sandboxName }, metadata, options, (error, response) => { - if (error) { - reject(error); - return; - } - const id = response?.sandbox?.metadata?.id; - if (!id) { - reject(new Error(`OpenShell returned sandbox '${sandboxName}' without an id`)); - return; - } - resolve(id); + error ? reject(error) : resolve(response); }); }); } +async function sandboxId( + client: OpenShellGrpcApi, + sandboxName: string, + metadata: grpc.Metadata, + options: grpc.CallOptions, +): Promise { + const id = (await getSandboxResponse(client, sandboxName, metadata, options))?.sandbox?.metadata + ?.id; + if (!id) throw new Error(`OpenShell returned sandbox '${sandboxName}' without an id`); + return id; +} + +async function sandboxDescriptor( + client: OpenShellGrpcApi, + sandboxName: string, + metadata: grpc.Metadata, + options: grpc.CallOptions, +): Promise { + const sandbox = (await getSandboxResponse(client, sandboxName, metadata, options))?.sandbox; + const id = sandbox?.metadata?.id; + const name = sandbox?.metadata?.name; + const image = sandbox?.spec?.template?.image; + if (!id?.trim()) throw new Error(`OpenShell returned sandbox '${sandboxName}' without an id`); + if (!name?.trim()) throw new Error(`OpenShell returned sandbox '${sandboxName}' without a name`); + if (name !== sandboxName) { + throw new Error(`OpenShell returned sandbox '${name}' for requested sandbox '${sandboxName}'`); + } + if (!image?.trim()) { + throw new Error(`OpenShell returned sandbox '${sandboxName}' without an image`); + } + return { id, name, image }; +} + function asBuffer(data: Buffer | Uint8Array | string | undefined): Buffer { if (data === undefined) return Buffer.alloc(0); return Buffer.isBuffer(data) ? data : Buffer.from(data); @@ -297,6 +328,11 @@ export function createGrpcOpenShellSandboxControl( const client = injectedClient ?? createOpenShellGrpcApi(config); return { close: () => client.close(), + getSandboxDescriptor(sandboxName): Promise { + return sandboxDescriptor(client, sandboxName, callMetadata(config.bearerToken), { + deadline: new Date(Date.now() + OPENSHELL_PROBE_TIMEOUT_MS), + }); + }, async exec(request): Promise { // Validate against the exact v0.0.72 UUID-width request before lookup so // transport-independent limits cannot cause any gateway activity. diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index a48592259ce..d08197ace34 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -18,6 +18,7 @@ import { } from "./sandbox-control"; import { execSandboxReadOnlyWithGrpcFallback, + getOpenShellSandboxDescriptor, selectOpenShellSandboxControlForMutation, } from "./sandbox-control-routing"; import { OPENSHELL_OPERATION_TIMEOUT_MS } from "./timeouts"; @@ -27,7 +28,12 @@ function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: Sandbox const grpcExec = vi.fn(() => grpcResult instanceof Error ? Promise.reject(grpcResult) : Promise.resolve(grpcResult), ); - const grpc: GrpcOpenShellSandboxControl = { close, exec: grpcExec }; + const getSandboxDescriptor = vi.fn(async (sandboxName: string) => ({ + id: "sb-id", + name: sandboxName, + image: "nvcr.io/nvidia/nemoclaw:test", + })); + const grpc: GrpcOpenShellSandboxControl = { close, exec: grpcExec, getSandboxDescriptor }; const cliExec = vi.fn(async () => cliResult ?? { status: 0, stdout: "cli", stderr: "" }); const cli: OpenShellSandboxControl = { exec: cliExec }; const createCli = vi.fn(() => cli); @@ -37,6 +43,7 @@ function dependencies(grpcResult: SandboxExecResult | Error, cliResult?: Sandbox close, cli, grpcExec, + getSandboxDescriptor, cliExec, createCli, createGrpc, @@ -51,6 +58,49 @@ const request = { maxOutputBytes: 4096, }; +describe("OpenShell sandbox descriptor routing", () => { + it("reads from the selected gateway and closes without invoking the CLI", async () => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + + await expect( + getOpenShellSandboxDescriptor("nemoclaw-9090", "alpha", test.deps), + ).resolves.toEqual({ + id: "sb-id", + name: "alpha", + image: "nvcr.io/nvidia/nemoclaw:test", + }); + expect(test.createGrpc).toHaveBeenCalledWith("nemoclaw-9090"); + expect(test.getSandboxDescriptor).toHaveBeenCalledWith("alpha"); + expect(test.createCli).not.toHaveBeenCalled(); + expect(test.cliExec).not.toHaveBeenCalled(); + expect(test.close).toHaveBeenCalledOnce(); + }); + + it("propagates read failures, closes, and never falls back to the CLI", async () => { + const error = new Error("descriptor unavailable"); + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + test.getSandboxDescriptor.mockRejectedValue(error); + + await expect(getOpenShellSandboxDescriptor("nemoclaw", "alpha", test.deps)).rejects.toBe(error); + expect(test.createCli).not.toHaveBeenCalled(); + expect(test.cliExec).not.toHaveBeenCalled(); + expect(test.close).toHaveBeenCalledOnce(); + }); + + it("rejects a gateway endpoint override before creating a client", async () => { + const test = dependencies({ status: 0, stdout: "unused", stderr: "" }); + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://other.example.test"); + try { + await expect(getOpenShellSandboxDescriptor("nemoclaw", "alpha", test.deps)).rejects.toThrow( + "Unset OPENSHELL_GATEWAY_ENDPOINT", + ); + expect(test.createGrpc).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + } + }); +}); + describe("read-only OpenShell sandbox control routing", () => { it.each([ ["too many session arguments", ["openclaw", "sessions", "list", ...Array(1022).fill("x")]], diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index aa8bc47c308..d7b46218885 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { log } from "../../cli/logger"; +import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import { createGrpcOpenShellSandboxControlForGateway, OpenShellGrpcEdgeTunnelRequiredError, @@ -9,6 +10,7 @@ import { import { type GrpcOpenShellSandboxControl, OpenShellGrpcPreDispatchError, + type OpenShellSandboxDescriptor, } from "./grpc-sandbox-control"; import { createGatewayScopedCliOpenShellSandboxControl, @@ -39,6 +41,31 @@ export interface OpenShellMutationControlSelection { close(): void; } +function closeGrpc( + grpc: GrpcOpenShellSandboxControl | undefined, + dependencies: ReadOnlyRoutingDependencies, +): void { + try { + grpc?.close(); + } catch (error) { + dependencies.debug("OpenShell direct gRPC client close failed", error); + } +} + +export async function getOpenShellSandboxDescriptor( + gatewayName: string, + sandboxName: string, + dependencies: ReadOnlyRoutingDependencies = defaultDependencies, +): Promise { + assertNoOpenShellGatewayEndpointOverride(); + const grpc = dependencies.createGrpc(gatewayName); + try { + return await grpc.getSandboxDescriptor(sandboxName); + } finally { + closeGrpc(grpc, dependencies); + } +} + /** * Select one transport before a mutating workflow starts. Direct gRPC is the * default. The CLI is selected only for the explicit Cloudflare edge-tunnel @@ -54,13 +81,7 @@ export function selectOpenShellSandboxControlForMutation( return { control: grpc, transport: "grpc", - close: () => { - try { - grpc.close(); - } catch (error) { - dependencies.debug("OpenShell direct gRPC client close failed", error); - } - }, + close: () => closeGrpc(grpc, dependencies), }; } catch (error) { if (!(error instanceof OpenShellGrpcEdgeTunnelRequiredError)) throw error; @@ -128,11 +149,7 @@ export async function execSandboxReadOnlyWithGrpcFallback( return { status: null, stdout: "", stderr: "", error: cause }; } } finally { - try { - grpc.close(); - } catch (error) { - dependencies.debug("OpenShell direct gRPC client close failed", error); - } + closeGrpc(grpc, dependencies); } dependencies.debug( diff --git a/test/helpers/openshell-sandbox-descriptor-preload.test.ts b/test/helpers/openshell-sandbox-descriptor-preload.test.ts new file mode 100644 index 00000000000..4f2be5a1dec --- /dev/null +++ b/test/helpers/openshell-sandbox-descriptor-preload.test.ts @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { expect, it } from "vitest"; + +import { writeOpenShellSandboxDescriptorPreload } from "./openshell-sandbox-descriptor-preload"; + +it("overrides only the configured sandbox routing module", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-descriptor-preload-")); + try { + const routingDirectory = path.join(home, "adapters", "openshell"); + const snapshotDirectory = path.join(home, "actions", "sandbox"); + fs.mkdirSync(routingDirectory, { recursive: true }); + fs.mkdirSync(snapshotDirectory, { recursive: true }); + const routingModule = path.join(routingDirectory, "sandbox-control-routing.js"); + const snapshotModule = path.join(snapshotDirectory, "snapshot.cjs"); + const unrelatedModule = path.join(home, "unrelated.cjs"); + fs.writeFileSync(routingModule, 'module.exports = { source: "routing-original" };\n'); + fs.writeFileSync( + snapshotModule, + 'module.exports = require("../../adapters/openshell/sandbox-control-routing");\n', + ); + fs.writeFileSync(unrelatedModule, 'module.exports = { source: "unrelated-original" };\n'); + const nodeOptions = writeOpenShellSandboxDescriptorPreload(home, "sandbox:test"); + + const output = execFileSync( + process.execPath, + [ + "-e", + `const routing = require(process.env.SNAPSHOT_MODULE); +const directRouting = require(process.env.ROUTING_MODULE); +const unrelated = require(process.env.UNRELATED_MODULE); +routing.getOpenShellSandboxDescriptor("nemoclaw", "alpha").then((descriptor) => { + process.stdout.write(JSON.stringify({ + descriptor, + directRouting, + directRoutingWasOverridden: typeof directRouting.getOpenShellSandboxDescriptor === "function", + routingSource: routing.source, + unrelated, + })); +});`, + ], + { + encoding: "utf8", + env: { + ...process.env, + NODE_OPTIONS: nodeOptions, + ROUTING_MODULE: routingModule, + SNAPSHOT_MODULE: snapshotModule, + UNRELATED_MODULE: unrelatedModule, + }, + }, + ); + + expect(JSON.parse(output)).toEqual({ + descriptor: { id: "alpha-id", image: "sandbox:test", name: "alpha" }, + directRouting: { source: "routing-original" }, + directRoutingWasOverridden: false, + routingSource: "routing-original", + unrelated: { source: "unrelated-original" }, + }); + } finally { + fs.rmSync(home, { force: true, recursive: true }); + } +}); diff --git a/test/helpers/openshell-sandbox-descriptor-preload.ts b/test/helpers/openshell-sandbox-descriptor-preload.ts new file mode 100644 index 00000000000..5409c92d1cf --- /dev/null +++ b/test/helpers/openshell-sandbox-descriptor-preload.ts @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +/** + * Replace the strict descriptor read in fake-OpenShell CLI subprocess tests. + * + * Those fixtures provide a fake `openshell` executable, but descriptor reads + * bypass the CLI and connect directly to the gateway's gRPC endpoint. They + * therefore cannot model this response with another fake CLI argv branch. + * Limit the child-process interception to the one exact compiled + * snapshot-to-routing import edge; unrelated module loads retain Node's + * normal result. Remove this + * preload when the subprocess harness owns a fake gRPC gateway (or official + * bindings expose a fixture-local injectable client). + */ +export function writeOpenShellSandboxDescriptorPreload(home: string, image: string): string { + const preload = path.join(home, "openshell-sandbox-descriptor-preload.cjs"); + fs.writeFileSync( + preload, + `const Module = require("node:module"); +const originalLoad = Module._load; +Module._load = function loadWithSandboxDescriptor(request, parent, isMain) { + const loaded = originalLoad.call(this, request, parent, isMain); + const fromSnapshot = + typeof parent?.filename === "string" && + /[\\/]actions[\\/]sandbox[\\/]snapshot\\.[cm]?js$/.test(parent.filename); + if (fromSnapshot && request === "../../adapters/openshell/sandbox-control-routing") { + return { + ...loaded, + getOpenShellSandboxDescriptor: async (_gatewayName, sandboxName) => ({ + id: sandboxName + "-id", + name: sandboxName, + image: ${JSON.stringify(image)}, + }), + }; + } + return loaded; +}; +`, + { mode: 0o600 }, + ); + return [process.env.NODE_OPTIONS, `--require=${preload}`].filter(Boolean).join(" "); +} diff --git a/test/snapshot-restore-existing-dest.test.ts b/test/snapshot-restore-existing-dest.test.ts index fc30cafb93a..ed152c8b2e9 100644 --- a/test/snapshot-restore-existing-dest.test.ts +++ b/test/snapshot-restore-existing-dest.test.ts @@ -7,8 +7,8 @@ // or --yes / NEMOCLAW_NON_INTERACTIVE=1) to delete-and-recreate the // destination from the snapshot. // -// The --force path preflights both the snapshot selector and the source pod -// image *before* deleting anything (#3756 P1 Codex). A bad selector, a +// The --force path preflights both the snapshot selector and the live source +// descriptor *before* deleting anything (#3756 P1 Codex). A bad selector, a // missing snapshot, or an unresolvable source image must not be allowed to // delete `dst` and only fail afterwards. @@ -17,8 +17,9 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, it, expect } from "vitest"; +import { describe, expect, it } from "vitest"; +import { writeOpenShellSandboxDescriptorPreload } from "./helpers/openshell-sandbox-descriptor-preload"; import { execTimeout } from "./helpers/timeouts"; const CLI = path.join(import.meta.dirname, "..", "bin", "nemoclaw.js"); @@ -56,7 +57,7 @@ function runCli( interface MakeEnvOptions { /** When false, omit the snapshot manifest so getLatestBackup returns null. */ withSnapshot?: boolean; - /** When false, fake docker exec returns an empty image string. */ + /** When false, return an empty image from the live source descriptor. */ withSourceImage?: boolean; /** Put dst on a registered non-default gateway and hide it from src's gateway list. */ destinationGatewayPort?: number; @@ -78,10 +79,7 @@ interface MakeEnvOptions { * - `sandbox delete dst` exits 0 (and logs the call) * - `sandbox create` exits non-zero (intentional; the integration tests * only need to verify control flow reached/passed the delete step) - * - fake docker that: - * - `inspect ... State.Running` returns "true" (gateway up) - * - `exec ... kubectl get pod src ...` returns an image string (or empty - * when withSourceImage=false), exercising resolveSrcPodImage's preflight + * - fake docker whose `inspect ... State.Running` returns "true" (gateway up) */ function makeExistingDestEnv( prefix: string, @@ -149,6 +147,10 @@ function makeExistingDestEnv( } const osLog = path.join(home, "openshell.log"); + const descriptorNodeOptions = writeOpenShellSandboxDescriptorPreload( + home, + opts.withSourceImage === false ? "" : "ghcr.io/nvidia/nemoclaw/sandbox-src:test", + ); const activeGateway = path.join(home, "active-gateway"); fs.writeFileSync( path.join(localBin, "openshell"), @@ -190,8 +192,6 @@ function makeExistingDestEnv( { mode: 0o755 }, ); - const sourceImageOutput = - opts.withSourceImage === false ? "" : "ghcr.io/nvidia/nemoclaw/sandbox-src:test"; fs.writeFileSync( path.join(localBin, "docker"), [ @@ -203,20 +203,19 @@ function makeExistingDestEnv( ' echo "true"', " exit 0", "fi", - 'if [ "$1" = "exec" ]; then', - // The action calls `docker exec kubectl get pod ...`. - // Return the configured image (or an empty string to simulate - // "image cannot be resolved", which #3756 P1 says must abort before - // we touch the destination). - ` printf '%s' ${JSON.stringify(sourceImageOutput)}`, - " exit 0", - "fi", "exit 0", ].join("\n"), { mode: 0o755 }, ); - return { env: { HOME: home, PATH: `${localBin}:${process.env.PATH ?? ""}` }, osLog }; + return { + env: { + HOME: home, + NODE_OPTIONS: descriptorNodeOptions, + PATH: `${localBin}:${process.env.PATH ?? ""}`, + }, + osLog, + }; } describe("snapshot restore --to existing destination (#3756)", () => { @@ -242,8 +241,8 @@ describe("snapshot restore --to existing destination (#3756)", () => { expect(log).not.toMatch(/sandbox delete dst/); }); - it("refuses by default before running source-image preflight per Codex P2 review (#3796)", () => { - // Existing destination + unresolvable source image. The user must see the + it("refuses by default before running source-descriptor preflight (#3796)", () => { + // Existing destination + invalid source descriptor. The user must see the // precise "destination exists" error, not the "cannot resolve image" // misdirection that would land if the refusal came after preflight. const { env } = makeExistingDestEnv("nemoclaw-snap-restore-refuse-before-preflight-", {