From 723b3ecff7e59bd171aefaf656d45fc6d84d96dd Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 17 Jul 2026 15:48:34 +0000 Subject: [PATCH 1/8] fix(sandbox): target the owning gateway for status and exec queries Signed-off-by: Tinson Lai --- .../sandbox/exec-gateway-target.test.ts | 63 +++++++++++++++ src/lib/actions/sandbox/exec.ts | 9 +++ .../actions/sandbox/gateway-select.test.ts | 42 ++++++++++ src/lib/actions/sandbox/gateway-select.ts | 21 +++++ .../gateway-state-owning-gateway.test.ts | 76 +++++++++++++++++++ src/lib/actions/sandbox/gateway-state.ts | 39 +++++++++- src/lib/actions/sandbox/gateway-target.ts | 8 +- 7 files changed, 254 insertions(+), 4 deletions(-) create mode 100644 src/lib/actions/sandbox/exec-gateway-target.test.ts create mode 100644 src/lib/actions/sandbox/gateway-select.test.ts create mode 100644 src/lib/actions/sandbox/gateway-select.ts create mode 100644 src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts diff --git a/src/lib/actions/sandbox/exec-gateway-target.test.ts b/src/lib/actions/sandbox/exec-gateway-target.test.ts new file mode 100644 index 00000000000..dc562150845 --- /dev/null +++ b/src/lib/actions/sandbox/exec-gateway-target.test.ts @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { execSandbox, type SandboxExecCleanupDeps } from "./exec"; + +const cleanupSkipped: SandboxExecCleanupDeps = { + getSandbox: () => null, + inspectMutableConfigPerms: (() => { + throw new Error("cleanup should be skipped"); + }) as unknown as SandboxExecCleanupDeps["inspectMutableConfigPerms"], + repairMutableConfigPerms: (() => { + throw new Error("cleanup should be skipped"); + }) as unknown as SandboxExecCleanupDeps["repairMutableConfigPerms"], +}; + +describe("execSandbox gateway targeting", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("selects the sandbox's owning gateway before dispatching the exec", async () => { + const order: string[] = []; + const selectGateway = vi.fn((name: string) => { + order.push(`select:${name}`); + }); + const run = vi.fn(async () => { + order.push("run"); + return { status: 0 }; + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await execSandbox( + "beta", + ["hostname"], + {}, + { + resolveBinary: () => "openshell", + selectGateway, + run, + cleanupDeps: cleanupSkipped, + policyHint: { + now: () => 0, + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + writeStderr: () => {}, + }, + }, + ).catch(() => {}); + + expect(selectGateway).toHaveBeenCalledWith("beta"); + expect(run).toHaveBeenCalled(); + expect(order.indexOf("select:beta")).toBeGreaterThanOrEqual(0); + expect(order.indexOf("select:beta")).toBeLessThan(order.indexOf("run")); + }); +}); diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index e578f853b2a..e78fd2eed28 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -329,6 +329,12 @@ function defaultResolveBinary(): string { return getOpenshellBinary(); } +function defaultSelectGateway(sandboxName: string): void { + (require("./gateway-select") as typeof import("./gateway-select")).selectSandboxOwningGateway( + sandboxName, + ); +} + // Test seams for execSandbox. All default to the production behavior; tests // inject them so the dispatch path stays hermetic without spawning a real // process or hitting the process-exiting OpenShell binary lookup. @@ -340,6 +346,8 @@ export type ExecSandboxDeps = { run?: SandboxExecRunner; policyHint?: ExecPolicyHintDeps; cleanupDeps?: SandboxExecCleanupDeps; + /** Select the sandbox's owning gateway before the exec talks to OpenShell. */ + selectGateway?: (sandboxName: string) => void; }; export async function execSandbox( @@ -361,6 +369,7 @@ export async function execSandbox( process.exit(2); } const binary = (deps.resolveBinary ?? defaultResolveBinary)(); + (deps.selectGateway ?? defaultSelectGateway)(sandboxName); if (options.workdir) { validateWorkdirOrFail(binary, sandboxName, options.workdir, deps.probeWorkdir); } diff --git a/src/lib/actions/sandbox/gateway-select.test.ts b/src/lib/actions/sandbox/gateway-select.test.ts new file mode 100644 index 00000000000..1c0b4a9467b --- /dev/null +++ b/src/lib/actions/sandbox/gateway-select.test.ts @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import * as registry from "../../state/registry"; +import { selectSandboxOwningGateway } from "./gateway-select"; + +describe("selectSandboxOwningGateway", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("selects the owning non-default gateway for a registered sandbox", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const run = vi.fn(() => ({ status: 0 }) as never); + + const selected = selectSandboxOwningGateway("beta", run); + + expect(selected).toBe("nemoclaw-8091"); + expect(run).toHaveBeenCalledWith( + ["gateway", "select", "nemoclaw-8091"], + expect.objectContaining({ ignoreError: true }), + ); + }); + + it("keeps the bare default gateway name for a default-port sandbox", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8080 } as never); + const run = vi.fn(() => ({ status: 0 }) as never); + + expect(selectSandboxOwningGateway("alpha", run)).toBe("nemoclaw"); + expect(run).toHaveBeenCalledWith(["gateway", "select", "nemoclaw"], expect.anything()); + }); + + it("does not touch the active gateway for an unregistered sandbox", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue(null); + const run = vi.fn(() => ({ status: 0 }) as never); + + expect(selectSandboxOwningGateway("ghost", run)).toBeNull(); + expect(run).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/gateway-select.ts b/src/lib/actions/sandbox/gateway-select.ts new file mode 100644 index 00000000000..c031bf38067 --- /dev/null +++ b/src/lib/actions/sandbox/gateway-select.ts @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { runOpenshell } from "../../adapters/openshell/runtime"; +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import { getKnownSandboxTargetGatewayName } from "./gateway-target"; + +export type GatewaySelectRunner = typeof runOpenshell; + +export function selectSandboxOwningGateway( + sandboxName: string, + run: GatewaySelectRunner = runOpenshell, +): string | null { + const targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName); + if (!targetGatewayName) return null; + run(["gateway", "select", targetGatewayName], { + ignoreError: true, + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + return targetGatewayName; +} diff --git a/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts new file mode 100644 index 00000000000..6074eb98643 --- /dev/null +++ b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import * as gatewayRuntime from "../../gateway-runtime-action"; +import * as registry from "../../state/registry"; +import * as gatewaySelect from "./gateway-select"; +import { getReconciledSandboxGatewayState } from "./gateway-state"; + +describe("getReconciledSandboxGatewayState owning-gateway guard", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("reselects the owning gateway and re-queries when a present comes from another active gateway", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ + state: "connected_other", + status: "", + activeGateway: "nemoclaw", + } as never); + const selectSpy = vi + .spyOn(gatewaySelect, "selectSandboxOwningGateway") + .mockReturnValue("nemoclaw-8091"); + + const getState = vi + .fn() + .mockResolvedValueOnce({ state: "present", output: "Phase: Provisioning" }) + .mockResolvedValueOnce({ state: "present", output: "Phase: Ready" }); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenCalledTimes(2); + expect(selectSpy).toHaveBeenCalledWith("beta"); + expect(result).toMatchObject({ + state: "present", + output: "Phase: Ready", + recoveredGateway: true, + recoveryVia: "select", + }); + }); + + it("trusts a present from the owning gateway without reselecting", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ + state: "healthy_named", + status: "", + } as never); + const selectSpy = vi.spyOn(gatewaySelect, "selectSandboxOwningGateway"); + + const getState = vi.fn().mockResolvedValue({ state: "present", output: "Phase: Ready" }); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenCalledTimes(1); + expect(selectSpy).not.toHaveBeenCalled(); + expect(result).toMatchObject({ state: "present", output: "Phase: Ready" }); + expect(result.recoveredGateway).toBeUndefined(); + }); + + it("leaves an unregistered sandbox's present result untouched", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue(null); + const lifecycleSpy = vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState"); + const selectSpy = vi.spyOn(gatewaySelect, "selectSandboxOwningGateway"); + + const getState = vi.fn().mockResolvedValue({ state: "present", output: "Phase: Ready" }); + + const result = await getReconciledSandboxGatewayState("ghost", { getState }); + + expect(getState).toHaveBeenCalledTimes(1); + expect(lifecycleSpy).not.toHaveBeenCalled(); + expect(selectSpy).not.toHaveBeenCalled(); + expect(result).toMatchObject({ state: "present" }); + }); +}); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index e573030934b..df8742a4be1 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -11,7 +11,12 @@ import { recoverNamedGatewayRuntime, } from "../../gateway-runtime-action"; import { isTerminalSandboxPhase, parseSandboxPhase } from "../../state/gateway"; -import { gatewayNamePattern, getSandboxTargetGatewayName } from "./gateway-target"; +import { selectSandboxOwningGateway } from "./gateway-select"; +import { + gatewayNamePattern, + getKnownSandboxTargetGatewayName, + getSandboxTargetGatewayName, +} from "./gateway-target"; const { pruneKnownHostsEntries } = require("../../onboard/known-hosts") as { pruneKnownHostsEntries: (contents: string) => string; @@ -423,6 +428,36 @@ export function printGatewayLifecycleHint( } } +/** + * A `present` lookup is only trustworthy when it came from the sandbox's own + * gateway. On a multi-instance host the active OpenShell gateway can be a + * sibling that reports a stale or provisioning entry for the same sandbox name, + * so a plain `present` masks the real state on the owning gateway. When the + * sandbox's gateway is registered but a different gateway is currently active, + * select the owning gateway and re-query so the returned state reflects the + * gateway the sandbox was onboarded against rather than the last-used one. + * Returns `null` when the initial `present` can be trusted as-is (owning + * gateway already active, or the sandbox is not registry-known). + */ +async function reselectOwningGatewayForPresent( + sandboxName: string, + getState: SandboxGatewayStateLookup, +): Promise { + const targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName); + if (!targetGatewayName) return null; + const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); + if (lifecycle.state !== "connected_other") return null; + selectSandboxOwningGateway(sandboxName); + const retry = await getState(sandboxName); + if (retry.state === "present") { + return { ...retry, recoveredGateway: true, recoveryVia: "select" }; + } + if (retry.state === "missing") { + return reconcileMissingAgainstNamedGateway(sandboxName, retry); + } + return retry; +} + export async function getReconciledSandboxGatewayState( sandboxName: string, opts: { getState?: SandboxGatewayStateLookup } = {}, @@ -430,7 +465,7 @@ export async function getReconciledSandboxGatewayState( const getState = opts.getState ?? getSandboxGatewayState; const lookup = await getState(sandboxName); if (lookup.state === "present") { - return lookup; + return (await reselectOwningGatewayForPresent(sandboxName, getState)) ?? lookup; } if (lookup.state === "missing") { return reconcileMissingAgainstNamedGateway(sandboxName, lookup); diff --git a/src/lib/actions/sandbox/gateway-target.ts b/src/lib/actions/sandbox/gateway-target.ts index d8232618920..cd125ceb8b7 100644 --- a/src/lib/actions/sandbox/gateway-target.ts +++ b/src/lib/actions/sandbox/gateway-target.ts @@ -5,9 +5,13 @@ import { GATEWAY_PORT } from "../../core/ports"; import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import * as registry from "../../state/registry"; -export function getSandboxTargetGatewayName(sandboxName = ""): string { +export function getKnownSandboxTargetGatewayName(sandboxName = ""): string | null { const sb = sandboxName ? registry.getSandbox(sandboxName) : null; - return sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + return sb ? resolveSandboxGatewayName(sb) : null; +} + +export function getSandboxTargetGatewayName(sandboxName = ""): string { + return getKnownSandboxTargetGatewayName(sandboxName) ?? resolveGatewayName(GATEWAY_PORT); } export function gatewayNamePattern(gatewayName: string): RegExp { From a0091bed66172d328d8c47de364e45b4d6ecbd37 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 17 Jul 2026 16:07:17 +0000 Subject: [PATCH 2/8] fix(sandbox): fail closed when owning-gateway selection fails Signed-off-by: Tinson Lai --- .../sandbox/exec-gateway-target.test.ts | 82 +++++++++++++++++++ src/lib/actions/sandbox/exec.ts | 19 +++-- .../actions/sandbox/gateway-select.test.ts | 32 +++++++- src/lib/actions/sandbox/gateway-select.ts | 16 +++- .../gateway-state-owning-gateway.test.ts | 29 ++++++- src/lib/actions/sandbox/gateway-state.ts | 13 ++- 6 files changed, 176 insertions(+), 15 deletions(-) diff --git a/src/lib/actions/sandbox/exec-gateway-target.test.ts b/src/lib/actions/sandbox/exec-gateway-target.test.ts index dc562150845..2d962b20007 100644 --- a/src/lib/actions/sandbox/exec-gateway-target.test.ts +++ b/src/lib/actions/sandbox/exec-gateway-target.test.ts @@ -24,6 +24,7 @@ describe("execSandbox gateway targeting", () => { const order: string[] = []; const selectGateway = vi.fn((name: string) => { order.push(`select:${name}`); + return { outcome: "selected" as const, gatewayName: name }; }); const run = vi.fn(async () => { order.push("run"); @@ -60,4 +61,85 @@ describe("execSandbox gateway targeting", () => { expect(order.indexOf("select:beta")).toBeGreaterThanOrEqual(0); expect(order.indexOf("select:beta")).toBeLessThan(order.indexOf("run")); }); + + it("selects the owning gateway before the workdir probe when a workdir is set", async () => { + const order: string[] = []; + const selectGateway = vi.fn((name: string) => { + order.push(`select:${name}`); + return { outcome: "selected" as const, gatewayName: name }; + }); + const probeWorkdir = vi.fn(() => { + order.push("probe"); + return { status: 0, error: undefined }; + }); + const run = vi.fn(async () => { + order.push("run"); + return { status: 0 }; + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await execSandbox( + "beta", + ["hostname"], + { workdir: "/work" }, + { + resolveBinary: () => "openshell", + selectGateway, + probeWorkdir, + run, + cleanupDeps: cleanupSkipped, + policyHint: { + now: () => 0, + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + writeStderr: () => {}, + }, + }, + ).catch(() => {}); + + expect(order).toEqual(["select:beta", "probe", "run"]); + }); + + it("aborts before the workdir probe and exec when gateway selection fails", async () => { + const order: string[] = []; + const selectGateway = vi.fn(() => { + order.push("select"); + return { outcome: "failed" as const, gatewayName: "nemoclaw-8091" }; + }); + const probeWorkdir = vi.fn(() => { + order.push("probe"); + return { status: 0, error: undefined }; + }); + const run = vi.fn(async () => { + order.push("run"); + return { status: 0 }; + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await execSandbox( + "beta", + ["hostname"], + { workdir: "/work" }, + { + resolveBinary: () => "openshell", + selectGateway, + probeWorkdir, + run, + cleanupDeps: cleanupSkipped, + }, + ).catch(() => {}); + + expect(order).toEqual(["select"]); + expect(probeWorkdir).not.toHaveBeenCalled(); + expect(run).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index e78fd2eed28..826bcd1099c 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -10,6 +10,7 @@ import type { import type { SandboxEntry } from "../../state/registry"; import { type ExecPolicyHintDeps, preparePolicyHint } from "./exec-policy-hint-integration"; import { buildSandboxExecStdio } from "./exec-stdio"; +import type { GatewaySelectResult } from "./gateway-select"; import { wrapExecCommandWithRuntimeEnv } from "./runtime-env"; export { buildSandboxExecStdio, shouldInheritSandboxExecStdin } from "./exec-stdio"; @@ -329,10 +330,10 @@ function defaultResolveBinary(): string { return getOpenshellBinary(); } -function defaultSelectGateway(sandboxName: string): void { - (require("./gateway-select") as typeof import("./gateway-select")).selectSandboxOwningGateway( - sandboxName, - ); +function defaultSelectGateway(sandboxName: string): GatewaySelectResult { + return ( + require("./gateway-select") as typeof import("./gateway-select") + ).selectSandboxOwningGateway(sandboxName); } // Test seams for execSandbox. All default to the production behavior; tests @@ -347,7 +348,7 @@ export type ExecSandboxDeps = { policyHint?: ExecPolicyHintDeps; cleanupDeps?: SandboxExecCleanupDeps; /** Select the sandbox's owning gateway before the exec talks to OpenShell. */ - selectGateway?: (sandboxName: string) => void; + selectGateway?: (sandboxName: string) => GatewaySelectResult; }; export async function execSandbox( @@ -369,7 +370,13 @@ export async function execSandbox( process.exit(2); } const binary = (deps.resolveBinary ?? defaultResolveBinary)(); - (deps.selectGateway ?? defaultSelectGateway)(sandboxName); + const gatewaySelection = (deps.selectGateway ?? defaultSelectGateway)(sandboxName); + if (gatewaySelection.outcome === "failed") { + console.error( + ` Failed to select gateway '${gatewaySelection.gatewayName}' for sandbox '${sandboxName}'.`, + ); + process.exit(1); + } if (options.workdir) { validateWorkdirOrFail(binary, sandboxName, options.workdir, deps.probeWorkdir); } diff --git a/src/lib/actions/sandbox/gateway-select.test.ts b/src/lib/actions/sandbox/gateway-select.test.ts index 1c0b4a9467b..488dd1d7456 100644 --- a/src/lib/actions/sandbox/gateway-select.test.ts +++ b/src/lib/actions/sandbox/gateway-select.test.ts @@ -17,7 +17,7 @@ describe("selectSandboxOwningGateway", () => { const selected = selectSandboxOwningGateway("beta", run); - expect(selected).toBe("nemoclaw-8091"); + expect(selected).toEqual({ outcome: "selected", gatewayName: "nemoclaw-8091" }); expect(run).toHaveBeenCalledWith( ["gateway", "select", "nemoclaw-8091"], expect.objectContaining({ ignoreError: true }), @@ -28,7 +28,10 @@ describe("selectSandboxOwningGateway", () => { vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8080 } as never); const run = vi.fn(() => ({ status: 0 }) as never); - expect(selectSandboxOwningGateway("alpha", run)).toBe("nemoclaw"); + expect(selectSandboxOwningGateway("alpha", run)).toEqual({ + outcome: "selected", + gatewayName: "nemoclaw", + }); expect(run).toHaveBeenCalledWith(["gateway", "select", "nemoclaw"], expect.anything()); }); @@ -36,7 +39,30 @@ describe("selectSandboxOwningGateway", () => { vi.spyOn(registry, "getSandbox").mockReturnValue(null); const run = vi.fn(() => ({ status: 0 }) as never); - expect(selectSandboxOwningGateway("ghost", run)).toBeNull(); + expect(selectSandboxOwningGateway("ghost", run)).toEqual({ + outcome: "unregistered", + gatewayName: null, + }); expect(run).not.toHaveBeenCalled(); }); + + it("reports failure when the gateway select command exits nonzero", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const run = vi.fn(() => ({ status: 1 }) as never); + + expect(selectSandboxOwningGateway("beta", run)).toEqual({ + outcome: "failed", + gatewayName: "nemoclaw-8091", + }); + }); + + it("reports failure when the gateway select command errors on spawn", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const run = vi.fn(() => ({ status: null, error: new Error("spawn failed") }) as never); + + expect(selectSandboxOwningGateway("beta", run)).toEqual({ + outcome: "failed", + gatewayName: "nemoclaw-8091", + }); + }); }); diff --git a/src/lib/actions/sandbox/gateway-select.ts b/src/lib/actions/sandbox/gateway-select.ts index c031bf38067..ef2e0aa576c 100644 --- a/src/lib/actions/sandbox/gateway-select.ts +++ b/src/lib/actions/sandbox/gateway-select.ts @@ -7,15 +7,23 @@ import { getKnownSandboxTargetGatewayName } from "./gateway-target"; export type GatewaySelectRunner = typeof runOpenshell; +export type GatewaySelectResult = + | { outcome: "selected"; gatewayName: string } + | { outcome: "failed"; gatewayName: string } + | { outcome: "unregistered"; gatewayName: null }; + export function selectSandboxOwningGateway( sandboxName: string, run: GatewaySelectRunner = runOpenshell, -): string | null { +): GatewaySelectResult { const targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName); - if (!targetGatewayName) return null; - run(["gateway", "select", targetGatewayName], { + if (!targetGatewayName) return { outcome: "unregistered", gatewayName: null }; + const result = run(["gateway", "select", targetGatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - return targetGatewayName; + if (result.error || result.status !== 0) { + return { outcome: "failed", gatewayName: targetGatewayName }; + } + return { outcome: "selected", gatewayName: targetGatewayName }; } diff --git a/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts index 6074eb98643..617eb81eb6b 100644 --- a/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts +++ b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts @@ -22,7 +22,7 @@ describe("getReconciledSandboxGatewayState owning-gateway guard", () => { } as never); const selectSpy = vi .spyOn(gatewaySelect, "selectSandboxOwningGateway") - .mockReturnValue("nemoclaw-8091"); + .mockReturnValue({ outcome: "selected", gatewayName: "nemoclaw-8091" }); const getState = vi .fn() @@ -41,6 +41,33 @@ describe("getReconciledSandboxGatewayState owning-gateway guard", () => { }); }); + it("reports wrong_gateway_active and does not re-query when owning-gateway selection fails", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ + state: "connected_other", + status: "some status", + activeGateway: "nemoclaw", + } as never); + const selectSpy = vi + .spyOn(gatewaySelect, "selectSandboxOwningGateway") + .mockReturnValue({ outcome: "failed", gatewayName: "nemoclaw-8091" }); + + const getState = vi + .fn() + .mockResolvedValueOnce({ state: "present", output: "Phase: Provisioning" }); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenCalledTimes(1); + expect(selectSpy).toHaveBeenCalledWith("beta"); + expect(result).toMatchObject({ + state: "wrong_gateway_active", + activeGateway: "nemoclaw", + output: "some status", + }); + expect(result.recoveredGateway).toBeUndefined(); + }); + it("trusts a present from the owning gateway without reselecting", async () => { vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index df8742a4be1..dd800b91f4d 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -447,7 +447,18 @@ async function reselectOwningGatewayForPresent( if (!targetGatewayName) return null; const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); if (lifecycle.state !== "connected_other") return null; - selectSandboxOwningGateway(sandboxName); + const selection = selectSandboxOwningGateway(sandboxName); + if (selection.outcome !== "selected") { + // Selection failed: the prior gateway is still active, so the + // original `present` result cannot be trusted as the sandbox's own + // state. Report the wrong-gateway condition instead of retrying + // against an unselected gateway or labelling a stale result recovered. + return { + state: "wrong_gateway_active", + activeGateway: lifecycle.activeGateway, + output: lifecycle.status, + }; + } const retry = await getState(sandboxName); if (retry.state === "present") { return { ...retry, recoveredGateway: true, recoveryVia: "select" }; From d108d4f7b0fcee10e098c337e7eb74d27a7168a5 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Fri, 17 Jul 2026 16:24:20 +0000 Subject: [PATCH 3/8] test(sandbox): assert observable exit codes in gateway-target exec tests Signed-off-by: Tinson Lai --- .../sandbox/exec-gateway-target.test.ts | 108 +++++++++--------- 1 file changed, 57 insertions(+), 51 deletions(-) diff --git a/src/lib/actions/sandbox/exec-gateway-target.test.ts b/src/lib/actions/sandbox/exec-gateway-target.test.ts index 2d962b20007..4581099f527 100644 --- a/src/lib/actions/sandbox/exec-gateway-target.test.ts +++ b/src/lib/actions/sandbox/exec-gateway-target.test.ts @@ -35,26 +35,28 @@ describe("execSandbox gateway targeting", () => { }) as never); vi.spyOn(console, "error").mockImplementation(() => undefined); - await execSandbox( - "beta", - ["hostname"], - {}, - { - resolveBinary: () => "openshell", - selectGateway, - run, - cleanupDeps: cleanupSkipped, - policyHint: { - now: () => 0, - env: {}, - probeLogs: () => "", - enableAudit: () => {}, - sleep: async () => {}, - attempts: 1, - writeStderr: () => {}, + await expect( + execSandbox( + "beta", + ["hostname"], + {}, + { + resolveBinary: () => "openshell", + selectGateway, + run, + cleanupDeps: cleanupSkipped, + policyHint: { + now: () => 0, + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + writeStderr: () => {}, + }, }, - }, - ).catch(() => {}); + ), + ).rejects.toThrow("__exit_0__"); expect(selectGateway).toHaveBeenCalledWith("beta"); expect(run).toHaveBeenCalled(); @@ -81,27 +83,29 @@ describe("execSandbox gateway targeting", () => { }) as never); vi.spyOn(console, "error").mockImplementation(() => undefined); - await execSandbox( - "beta", - ["hostname"], - { workdir: "/work" }, - { - resolveBinary: () => "openshell", - selectGateway, - probeWorkdir, - run, - cleanupDeps: cleanupSkipped, - policyHint: { - now: () => 0, - env: {}, - probeLogs: () => "", - enableAudit: () => {}, - sleep: async () => {}, - attempts: 1, - writeStderr: () => {}, + await expect( + execSandbox( + "beta", + ["hostname"], + { workdir: "/work" }, + { + resolveBinary: () => "openshell", + selectGateway, + probeWorkdir, + run, + cleanupDeps: cleanupSkipped, + policyHint: { + now: () => 0, + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + writeStderr: () => {}, + }, }, - }, - ).catch(() => {}); + ), + ).rejects.toThrow("__exit_0__"); expect(order).toEqual(["select:beta", "probe", "run"]); }); @@ -125,18 +129,20 @@ describe("execSandbox gateway targeting", () => { }) as never); vi.spyOn(console, "error").mockImplementation(() => undefined); - await execSandbox( - "beta", - ["hostname"], - { workdir: "/work" }, - { - resolveBinary: () => "openshell", - selectGateway, - probeWorkdir, - run, - cleanupDeps: cleanupSkipped, - }, - ).catch(() => {}); + await expect( + execSandbox( + "beta", + ["hostname"], + { workdir: "/work" }, + { + resolveBinary: () => "openshell", + selectGateway, + probeWorkdir, + run, + cleanupDeps: cleanupSkipped, + }, + ), + ).rejects.toThrow("__exit_1__"); expect(order).toEqual(["select"]); expect(probeWorkdir).not.toHaveBeenCalled(); From 1ace377757335daecb98b3725eba89906eea4bdd Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Fri, 17 Jul 2026 16:09:13 -0700 Subject: [PATCH 4/8] fix(sandbox): pin sandbox operations to gateway Bind status, policy, workdir probes, recovery, and exec subprocesses to the sandbox's recorded OpenShell gateway. Reject endpoint overrides and fail closed when owner selection cannot be established. Co-authored-by: Tinson Lai Signed-off-by: Apurv Kumaria --- .../sandbox/exec-gateway-target.test.ts | 71 ++++++- src/lib/actions/sandbox/exec.ts | 33 +++- .../sandbox/gateway-state-drift.test.ts | 17 +- .../gateway-state-owning-gateway.test.ts | 184 ++++++++++++------ src/lib/actions/sandbox/gateway-state.ts | 170 +++++++++------- 5 files changed, 328 insertions(+), 147 deletions(-) diff --git a/src/lib/actions/sandbox/exec-gateway-target.test.ts b/src/lib/actions/sandbox/exec-gateway-target.test.ts index 4581099f527..132520186f4 100644 --- a/src/lib/actions/sandbox/exec-gateway-target.test.ts +++ b/src/lib/actions/sandbox/exec-gateway-target.test.ts @@ -17,6 +17,7 @@ const cleanupSkipped: SandboxExecCleanupDeps = { describe("execSandbox gateway targeting", () => { afterEach(() => { + vi.unstubAllEnvs(); vi.restoreAllMocks(); }); @@ -26,7 +27,7 @@ describe("execSandbox gateway targeting", () => { order.push(`select:${name}`); return { outcome: "selected" as const, gatewayName: name }; }); - const run = vi.fn(async () => { + const run = vi.fn(async (_binary: string, _args: readonly string[]) => { order.push("run"); return { status: 0 }; }); @@ -60,21 +61,27 @@ describe("execSandbox gateway targeting", () => { expect(selectGateway).toHaveBeenCalledWith("beta"); expect(run).toHaveBeenCalled(); + const execArgs = run.mock.calls[0]?.[1] ?? []; + expect(execArgs.slice(0, 7)).toEqual(["sandbox", "exec", "--name", "beta", "-g", "beta", "--"]); + expect(execArgs.at(-2)).toBe("nemoclaw-runtime-env"); + expect(execArgs.at(-1)).toBe("hostname"); expect(order.indexOf("select:beta")).toBeGreaterThanOrEqual(0); expect(order.indexOf("select:beta")).toBeLessThan(order.indexOf("run")); }); it("selects the owning gateway before the workdir probe when a workdir is set", async () => { const order: string[] = []; + vi.stubEnv("OPENSHELL_GATEWAY", "ambient-sibling"); const selectGateway = vi.fn((name: string) => { order.push(`select:${name}`); - return { outcome: "selected" as const, gatewayName: name }; + process.env.OPENSHELL_GATEWAY = "drifted-sibling"; + return { outcome: "selected" as const, gatewayName: "nemoclaw-8091" }; }); - const probeWorkdir = vi.fn(() => { + const probeWorkdir = vi.fn((_binary: string, _args: readonly string[]) => { order.push("probe"); return { status: 0, error: undefined }; }); - const run = vi.fn(async () => { + const run = vi.fn(async (_binary: string, _args: readonly string[]) => { order.push("run"); return { status: 0 }; }); @@ -108,6 +115,62 @@ describe("execSandbox gateway targeting", () => { ).rejects.toThrow("__exit_0__"); expect(order).toEqual(["select:beta", "probe", "run"]); + expect(process.env.OPENSHELL_GATEWAY).toBe("drifted-sibling"); + expect(probeWorkdir.mock.calls[0]?.[1]).toEqual([ + "sandbox", + "exec", + "--name", + "beta", + "-g", + "nemoclaw-8091", + "--", + "test", + "-d", + "/work", + ]); + const execArgs = run.mock.calls[0]?.[1] ?? []; + expect(execArgs.slice(0, 9)).toEqual([ + "sandbox", + "exec", + "--name", + "beta", + "-g", + "nemoclaw-8091", + "--workdir", + "/work", + "--", + ]); + expect(execArgs.at(-2)).toBe("nemoclaw-runtime-env"); + expect(execArgs.at(-1)).toBe("hostname"); + }); + + it("rejects a direct endpoint override before selecting, probing, or dispatching", async () => { + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://sibling.invalid"); + const resolveBinary = vi.fn(() => "openshell"); + const selectGateway = vi.fn(); + const probeWorkdir = vi.fn(); + const run = vi.fn(); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + execSandbox( + "beta", + ["hostname"], + { workdir: "/work" }, + { resolveBinary, selectGateway, probeWorkdir, run }, + ), + ).rejects.toThrow("__exit_1__"); + + expect(console.error).toHaveBeenCalledWith( + expect.stringContaining("OPENSHELL_GATEWAY_ENDPOINT is set"), + ); + expect(resolveBinary).not.toHaveBeenCalled(); + expect(selectGateway).not.toHaveBeenCalled(); + expect(probeWorkdir).not.toHaveBeenCalled(); + expect(run).not.toHaveBeenCalled(); }); it("aborts before the workdir probe and exec when gateway selection fails", async () => { diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index 826bcd1099c..281045069aa 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -3,6 +3,7 @@ import { spawn, spawnSync } from "node:child_process"; import { spawnExitCode } from "../../core/process-exit"; +import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import type { MutableConfigPermsInspection, MutableConfigRepairResult, @@ -85,8 +86,10 @@ export function buildOpenshellExecArgs( sandboxName: string, command: readonly string[], options: SandboxExecOptions = {}, + gatewayName?: string, ): string[] { const argv = ["sandbox", "exec", "--name", sandboxName]; + if (gatewayName) argv.push("-g", gatewayName); if (options.workdir) argv.push("--workdir", options.workdir); if (options.tty === true) argv.push("--tty"); if (options.tty === false) argv.push("--no-tty"); @@ -97,8 +100,15 @@ export function buildOpenshellExecArgs( return argv; } -export function buildWorkdirProbeArgs(sandboxName: string, workdir: string): string[] { - return ["sandbox", "exec", "--name", sandboxName, "--", "test", "-d", workdir]; +export function buildWorkdirProbeArgs( + sandboxName: string, + workdir: string, + gatewayName?: string, +): string[] { + const argv = ["sandbox", "exec", "--name", sandboxName]; + if (gatewayName) argv.push("-g", gatewayName); + argv.push("--", "test", "-d", workdir); + return argv; } // OpenShell accepts LF/CR in command argv while retaining field-specific @@ -282,10 +292,11 @@ export async function runSandboxExecCommand( options: SandboxExecOptions, run: SandboxExecRunner, cleanupDeps: SandboxExecCleanupDeps, + gatewayName?: string, ): Promise { let result: SpawnLikeResult; try { - result = await run(binary, buildOpenshellExecArgs(sandboxName, command, options)); + result = await run(binary, buildOpenshellExecArgs(sandboxName, command, options, gatewayName)); } catch (error) { result = { status: null, error: error instanceof Error ? error : new Error(String(error)) }; } @@ -317,8 +328,11 @@ export function validateWorkdirOrFail( sandboxName: string, workdir: string, run: WorkdirProbeRunner = defaultWorkdirProbeRunner, + gatewayName?: string, ): void { - const outcome = evaluateWorkdirProbe(run(binary, buildWorkdirProbeArgs(sandboxName, workdir))); + const outcome = evaluateWorkdirProbe( + run(binary, buildWorkdirProbeArgs(sandboxName, workdir, gatewayName)), + ); if (outcome === "missing") { console.error(workdirMissingMessage(workdir)); process.exit(1); @@ -369,6 +383,12 @@ export async function execSandbox( console.error(inputError); process.exit(2); } + try { + assertNoOpenShellGatewayEndpointOverride(); + } catch (error) { + console.error(` Error: ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); + } const binary = (deps.resolveBinary ?? defaultResolveBinary)(); const gatewaySelection = (deps.selectGateway ?? defaultSelectGateway)(sandboxName); if (gatewaySelection.outcome === "failed") { @@ -377,8 +397,10 @@ export async function execSandbox( ); process.exit(1); } + const gatewayName = + gatewaySelection.outcome === "selected" ? gatewaySelection.gatewayName : undefined; if (options.workdir) { - validateWorkdirOrFail(binary, sandboxName, options.workdir, deps.probeWorkdir); + validateWorkdirOrFail(binary, sandboxName, options.workdir, deps.probeWorkdir, gatewayName); } const emitPolicyDenialHint = preparePolicyHint(CLI_NAME, sandboxName, deps.policyHint); const completion = await runSandboxExecCommand( @@ -397,6 +419,7 @@ export async function execSandbox( repairMutableConfigPerms: (name) => (require("../../shields") as typeof import("../../shields")).repairMutableConfigPerms(name), }, + gatewayName, ); if (completion.invocationError) { console.error(` Failed to invoke openshell: ${completion.invocationError}`); diff --git a/src/lib/actions/sandbox/gateway-state-drift.test.ts b/src/lib/actions/sandbox/gateway-state-drift.test.ts index b1cb161b1b4..832640375e8 100644 --- a/src/lib/actions/sandbox/gateway-state-drift.test.ts +++ b/src/lib/actions/sandbox/gateway-state-drift.test.ts @@ -15,6 +15,7 @@ const openshellRuntime = requireDist("../../adapters/openshell/runtime.js"); const gatewayRuntime = requireDist("../../gateway-runtime-action.js"); const dockerDriverRecovery = requireDist("../../onboard/docker-driver-sandbox-recovery.js"); const registry = requireDist("../../state/registry.js"); +const gatewaySelect = requireDist("./gateway-select.js"); const gatewayState: GatewayStateModule = requireDist("./gateway-state.js"); const driftIssue: OpenShellStateRpcIssue = { @@ -42,6 +43,7 @@ describe("sandbox gateway state drift guard", () => { let detectPreflightIssueSpy: MockInstance; let getNamedGatewayLifecycleStateSpy: MockInstance; let getSandboxSpy: MockInstance; + let gatewaySelectSpy: MockInstance; let recoverNamedGatewayRuntimeSpy: MockInstance; let runOpenshellSpy: MockInstance; let removeSandboxSpy: MockInstance; @@ -52,6 +54,9 @@ describe("sandbox gateway state drift guard", () => { errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); getSandboxSpy = vi.spyOn(registry, "getSandbox").mockReturnValue(null); + gatewaySelectSpy = vi + .spyOn(gatewaySelect, "selectSandboxOwningGateway") + .mockReturnValue({ outcome: "selected", gatewayName: "nemoclaw" }); captureOpenshellSpy = vi .spyOn(openshellRuntime, "captureOpenshell") @@ -95,6 +100,7 @@ describe("sandbox gateway state drift guard", () => { vi.spyOn(openshellRuntime, "isCommandTimeout").mockReturnValue(false), getNamedGatewayLifecycleStateSpy, getSandboxSpy, + gatewaySelectSpy, recoverNamedGatewayRuntimeSpy, vi .spyOn(dockerDriverRecovery, "recoverDockerDriverSandbox") @@ -172,7 +178,7 @@ describe("sandbox gateway state drift guard", () => { expect(removeSandboxSpy).not.toHaveBeenCalled(); }); - it("preserves registry state and prints deterministic guidance when gateway selection cannot expose the sandbox (#2276)", async () => { + it("preserves registry state and prints deterministic guidance after targeting the owning gateway (#2276)", async () => { vi.stubEnv("NEMOCLAW_NON_INTERACTIVE", "1"); detectPreflightIssueSpy.mockReturnValue(null); getSandboxSpy.mockReturnValue({ @@ -196,24 +202,21 @@ describe("sandbox gateway state drift guard", () => { expect(output).toContain("Your sandbox has NOT been removed"); expect(output).toContain("openshell gateway select nemoclaw"); expect(output).not.toMatch(/Press (?:enter|any key)|\?\s+\[/i); - expect(runOpenshellSpy).toHaveBeenCalledWith( - ["gateway", "select", "nemoclaw"], - expect.objectContaining({ ignoreError: true }), - ); + expect(gatewaySelectSpy).toHaveBeenCalledWith("alpha"); expect(removeSandboxSpy).not.toHaveBeenCalled(); }); it.each([ { lifecycle: { state: "missing_named", status: "No gateway configured" }, - expected: "gateway is no longer configured after restart/rebuild", + expected: "gateway is no longer configured or its metadata/runtime has been lost", }, { lifecycle: { state: "named_unreachable", status: "Gateway: nemoclaw\nConnection refused", }, - expected: "gateway is still refusing connections after restart", + expected: "gateway exists in metadata, but its API is refusing connections after restart", }, ])("preserves registry state when the named gateway reports $lifecycle.state", async ({ lifecycle, diff --git a/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts index 617eb81eb6b..8ebd9776874 100644 --- a/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts +++ b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts @@ -1,103 +1,173 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as gatewayDrift from "../../adapters/openshell/gateway-drift"; +import * as openshellRuntime from "../../adapters/openshell/runtime"; import * as gatewayRuntime from "../../gateway-runtime-action"; import * as registry from "../../state/registry"; import * as gatewaySelect from "./gateway-select"; -import { getReconciledSandboxGatewayState } from "./gateway-state"; +import { + getReconciledSandboxGatewayState, + getSandboxGatewayState, + getSandboxGatewayStateForStatus, +} from "./gateway-state"; describe("getReconciledSandboxGatewayState owning-gateway guard", () => { + beforeEach(() => { + vi.spyOn(gatewaySelect, "selectSandboxOwningGateway").mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw-8091", + }); + vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ + state: "connected_other", + activeGateway: "sibling", + status: "Gateway: sibling\nStatus: Connected", + } as never); + }); + afterEach(() => { + vi.unstubAllEnvs(); vi.restoreAllMocks(); }); - it("reselects the owning gateway and re-queries when a present comes from another active gateway", async () => { - vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); - vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ - state: "connected_other", - status: "", - activeGateway: "nemoclaw", - } as never); - const selectSpy = vi - .spyOn(gatewaySelect, "selectSandboxOwningGateway") - .mockReturnValue({ outcome: "selected", gatewayName: "nemoclaw-8091" }); + it("pins both the sandbox and policy RPCs to the recorded owner", () => { + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockReturnValue(null); + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null); + const capture = vi + .spyOn(openshellRuntime, "captureOpenshell") + .mockReturnValueOnce({ status: 0, output: "Policy:\nPhase: Ready" } as never) + .mockReturnValueOnce({ status: 0, output: "version: 1" } as never); + + const result = getSandboxGatewayState("beta", "nemoclaw-8091"); + + expect(result.state).toBe("present"); + expect(capture).toHaveBeenNthCalledWith( + 1, + ["sandbox", "get", "-g", "nemoclaw-8091", "beta"], + expect.anything(), + ); + expect(capture).toHaveBeenNthCalledWith( + 2, + ["policy", "get", "-g", "nemoclaw-8091", "--full", "beta"], + expect.anything(), + ); + }); - const getState = vi - .fn() - .mockResolvedValueOnce({ state: "present", output: "Phase: Provisioning" }) - .mockResolvedValueOnce({ state: "present", output: "Phase: Ready" }); + it("pins the async status RPC to the recorded owner", async () => { + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockReturnValue(null); + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null); + vi.spyOn(openshellRuntime, "isCommandTimeout").mockReturnValue(false); + const capture = vi + .spyOn(openshellRuntime, "captureOpenshellForStatus") + .mockResolvedValueOnce({ status: 0, output: "Phase: Ready" } as never) + .mockResolvedValueOnce({ status: 1, output: "" } as never); + + const result = await getSandboxGatewayStateForStatus("beta", "nemoclaw-8091"); + + expect(result.state).toBe("present"); + expect(capture).toHaveBeenNthCalledWith( + 1, + ["sandbox", "get", "-g", "nemoclaw-8091", "beta"], + expect.anything(), + ); + expect(capture).toHaveBeenNthCalledWith( + 2, + ["policy", "get", "-g", "nemoclaw-8091", "--full", "beta"], + expect.anything(), + ); + }); - const result = await getReconciledSandboxGatewayState("beta", { getState }); + it("rejects endpoint routing before a status RPC can bypass the owner", async () => { + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://sibling.invalid"); + const syncCapture = vi.spyOn(openshellRuntime, "captureOpenshell"); + const asyncCapture = vi.spyOn(openshellRuntime, "captureOpenshellForStatus"); - expect(getState).toHaveBeenCalledTimes(2); - expect(selectSpy).toHaveBeenCalledWith("beta"); - expect(result).toMatchObject({ - state: "present", - output: "Phase: Ready", - recoveredGateway: true, - recoveryVia: "select", + expect(getSandboxGatewayState("beta", "nemoclaw-8091")).toMatchObject({ + state: "gateway_endpoint_override", + output: expect.stringContaining("OPENSHELL_GATEWAY_ENDPOINT is set"), }); + await expect(getSandboxGatewayStateForStatus("beta", "nemoclaw-8091")).resolves.toMatchObject({ + state: "gateway_endpoint_override", + output: expect.stringContaining("OPENSHELL_GATEWAY_ENDPOINT is set"), + }); + expect(syncCapture).not.toHaveBeenCalled(); + expect(asyncCapture).not.toHaveBeenCalled(); }); - it("reports wrong_gateway_active and does not re-query when owning-gateway selection fails", async () => { + it("targets the registered owner on the first lookup instead of accepting ambient sibling state", async () => { vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); - vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ - state: "connected_other", - status: "some status", - activeGateway: "nemoclaw", - } as never); - const selectSpy = vi - .spyOn(gatewaySelect, "selectSandboxOwningGateway") - .mockReturnValue({ outcome: "failed", gatewayName: "nemoclaw-8091" }); - - const getState = vi - .fn() - .mockResolvedValueOnce({ state: "present", output: "Phase: Provisioning" }); + const getState = vi.fn((_name: string, gatewayName?: string) => + gatewayName === "nemoclaw-8091" + ? { state: "present", output: "Phase: Ready" } + : { state: "present", output: "Phase: Provisioning" }, + ); const result = await getReconciledSandboxGatewayState("beta", { getState }); - expect(getState).toHaveBeenCalledTimes(1); - expect(selectSpy).toHaveBeenCalledWith("beta"); + expect(getState).toHaveBeenCalledOnce(); + expect(getState).toHaveBeenCalledWith("beta", "nemoclaw-8091"); expect(result).toMatchObject({ - state: "wrong_gateway_active", - activeGateway: "nemoclaw", - output: "some status", + state: "present", + output: "Phase: Ready", }); expect(result.recoveredGateway).toBeUndefined(); }); - it("trusts a present from the owning gateway without reselecting", async () => { + it("does not return an ambient sibling timeout without first querying the healthy owner", async () => { vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); - vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ - state: "healthy_named", - status: "", - } as never); - const selectSpy = vi.spyOn(gatewaySelect, "selectSandboxOwningGateway"); + const getState = vi.fn((_name: string, gatewayName?: string) => + gatewayName === "nemoclaw-8091" + ? { state: "present", output: "Phase: Ready" } + : { state: "status_probe_timeout", output: "sibling timed out" }, + ); - const getState = vi.fn().mockResolvedValue({ state: "present", output: "Phase: Ready" }); + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenCalledOnce(); + expect(getState).toHaveBeenCalledWith("beta", "nemoclaw-8091"); + expect(result).toMatchObject({ state: "present", output: "Phase: Ready" }); + }); + + it("does not return an ambient sibling unknown error without first querying the healthy owner", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const getState = vi.fn((_name: string, gatewayName?: string) => + gatewayName === "nemoclaw-8091" + ? { state: "present", output: "Phase: Ready" } + : { state: "unknown_error", output: "sibling failed" }, + ); const result = await getReconciledSandboxGatewayState("beta", { getState }); - expect(getState).toHaveBeenCalledTimes(1); - expect(selectSpy).not.toHaveBeenCalled(); + expect(getState).toHaveBeenCalledOnce(); + expect(getState).toHaveBeenCalledWith("beta", "nemoclaw-8091"); expect(result).toMatchObject({ state: "present", output: "Phase: Ready" }); + }); + + it("fails closed before lookup when the owning gateway cannot be selected", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + vi.mocked(gatewaySelect.selectSandboxOwningGateway).mockReturnValue({ + outcome: "failed", + gatewayName: "nemoclaw-8091", + }); + const getState = vi.fn(); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).not.toHaveBeenCalled(); + expect(result.state).toBe("wrong_gateway_active"); expect(result.recoveredGateway).toBeUndefined(); }); - it("leaves an unregistered sandbox's present result untouched", async () => { + it("leaves an unregistered sandbox on the existing default lookup path", async () => { vi.spyOn(registry, "getSandbox").mockReturnValue(null); - const lifecycleSpy = vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState"); - const selectSpy = vi.spyOn(gatewaySelect, "selectSandboxOwningGateway"); - const getState = vi.fn().mockResolvedValue({ state: "present", output: "Phase: Ready" }); const result = await getReconciledSandboxGatewayState("ghost", { getState }); expect(getState).toHaveBeenCalledTimes(1); - expect(lifecycleSpy).not.toHaveBeenCalled(); - expect(selectSpy).not.toHaveBeenCalled(); + expect(getState).toHaveBeenCalledWith("ghost", undefined); expect(result).toMatchObject({ state: "present" }); }); }); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index dd800b91f4d..47e5377691e 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -10,6 +10,7 @@ import { getNamedGatewayLifecycleState, recoverNamedGatewayRuntime, } from "../../gateway-runtime-action"; +import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import { isTerminalSandboxPhase, parseSandboxPhase } from "../../state/gateway"; import { selectSandboxOwningGateway } from "./gateway-select"; import { @@ -71,8 +72,26 @@ export type SandboxGatewayState = { type SandboxGatewayStateLookup = ( sandboxName: string, + gatewayName?: string, ) => SandboxGatewayState | Promise; +function gatewayScopedArgs(args: string[], gatewayName?: string): string[] { + if (!gatewayName) return args; + return [...args.slice(0, 2), "-g", gatewayName, ...args.slice(2)]; +} + +function gatewayEndpointOverrideState(): SandboxGatewayState | null { + try { + assertNoOpenShellGatewayEndpointOverride(); + return null; + } catch (error) { + return { + state: "gateway_endpoint_override", + output: ` Error: ${error instanceof Error ? error.message : String(error)}`, + }; + } +} + function formatGatewaySchemaMismatchOutput( issue: OpenShellStateRpcIssue, action: string, @@ -115,8 +134,13 @@ export function mergeLivePolicyIntoSandboxOutput(output: string, livePolicyOutpu } /** Query sandbox presence and return its output with the live enforced policy. */ -export function getSandboxGatewayState(sandboxName: string): SandboxGatewayState { - const preflightIssue = detectOpenShellStateRpcPreflightIssue(); +export function getSandboxGatewayState( + sandboxName: string, + gatewayName?: string, +): SandboxGatewayState { + const endpointOverride = gatewayEndpointOverrideState(); + if (endpointOverride) return endpointOverride; + const preflightIssue = detectOpenShellStateRpcPreflightIssue({ gatewayName }); if (preflightIssue) { return { state: "gateway_schema_mismatch", @@ -126,11 +150,11 @@ export function getSandboxGatewayState(sandboxName: string): SandboxGatewayState ), }; } - const result = captureOpenshell(["sandbox", "get", sandboxName], { + const result = captureOpenshell(gatewayScopedArgs(["sandbox", "get", sandboxName], gatewayName), { timeout: OPENSHELL_PROBE_TIMEOUT_MS, }); let output = result.output; - const resultIssue = detectOpenShellStateRpcResultIssue(result); + const resultIssue = detectOpenShellStateRpcResultIssue(result, { gatewayName }); if (resultIssue) { return { state: "gateway_schema_mismatch", @@ -140,21 +164,23 @@ export function getSandboxGatewayState(sandboxName: string): SandboxGatewayState }; } if (result.status === 0) { - const livePolicy = captureOpenshell(["policy", "get", "--full", sandboxName], { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); + const livePolicy = captureOpenshell( + gatewayScopedArgs(["policy", "get", "--full", sandboxName], gatewayName), + { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }, + ); if (livePolicy.status === 0 && livePolicy.output.trim()) { output = mergeLivePolicyIntoSandboxOutput(output, livePolicy.output); } return { state: "present", output }; } - // `sandbox has no spec` is the gRPC reply when the active OpenShell gateway - // is reachable but does not know about this sandbox — the multi-instance - // case where the active gateway is a sibling of the one the sandbox was - // onboarded against. Classify as `missing` so the named-gateway reconciler - // selects the sandbox's owning gateway and retries; without this the lookup - // would fall to `unknown_error` and exit with a hint instead of recovering. + // `sandbox has no spec` is the gRPC reply when the queried gateway does not + // know about this sandbox. On an unscoped lookup that can be an ambient + // sibling; an owner-scoped lookup means the sandbox is genuinely absent + // from its recorded gateway. Both remain `missing`, and reconciliation uses + // the presence of the explicit owner pin to distinguish those cases. if (/\bNotFound\b|\bNot Found\b|sandbox not found|sandbox has no spec/i.test(output)) { return { state: "missing", output }; } @@ -170,9 +196,12 @@ export function getSandboxGatewayState(sandboxName: string): SandboxGatewayState export async function getSandboxGatewayStateForStatus( sandboxName: string, + gatewayName?: string, ): Promise { const timeoutMs = getStatusProbeTimeoutMs(); - const preflightIssue = detectOpenShellStateRpcPreflightIssue({ timeoutMs }); + const endpointOverride = gatewayEndpointOverrideState(); + if (endpointOverride) return endpointOverride; + const preflightIssue = detectOpenShellStateRpcPreflightIssue({ gatewayName, timeoutMs }); if (preflightIssue) { return { state: "gateway_schema_mismatch", @@ -183,11 +212,14 @@ export async function getSandboxGatewayStateForStatus( ), }; } - const result = await captureOpenshellForStatus(["sandbox", "get", sandboxName], { - timeout: timeoutMs, - }); + const result = await captureOpenshellForStatus( + gatewayScopedArgs(["sandbox", "get", sandboxName], gatewayName), + { + timeout: timeoutMs, + }, + ); let output = result.output; - const resultIssue = detectOpenShellStateRpcResultIssue(result, { timeoutMs }); + const resultIssue = detectOpenShellStateRpcResultIssue(result, { gatewayName, timeoutMs }); if (resultIssue) { return { state: "gateway_schema_mismatch", @@ -204,10 +236,13 @@ export async function getSandboxGatewayStateForStatus( }; } if (result.status === 0) { - const livePolicy = await captureOpenshellForStatus(["policy", "get", "--full", sandboxName], { - ignoreError: true, - timeout: timeoutMs, - }); + const livePolicy = await captureOpenshellForStatus( + gatewayScopedArgs(["policy", "get", "--full", sandboxName], gatewayName), + { + ignoreError: true, + timeout: timeoutMs, + }, + ); if (!isCommandTimeout(livePolicy) && livePolicy.status === 0 && livePolicy.output.trim()) { output = mergeLivePolicyIntoSandboxOutput(output, livePolicy.output); } @@ -231,22 +266,29 @@ export async function getSandboxGatewayStateForStatus( * When the active OpenShell gateway has drifted off nemoclaw, a NotFound is * ambiguous: the sandbox may actually be registered against the nemoclaw * gateway but invisible because some other gateway is currently active. This - * helper self-heals by attempting `openshell gateway select nemoclaw` and - * re-queries, or returns a `wrong_gateway_active` state so callers can surface - * actionable guidance instead of destroying the registry entry. + * helper self-heals an unscoped lookup by attempting `openshell gateway select + * nemoclaw` and re-querying. When `pinnedGatewayName` is present, the NotFound + * already came from the recorded owner, so ambient selection is ignored and + * only the existing Docker-side recovery path is considered. */ export function reconcileMissingAgainstNamedGateway( sandboxName: string, missingLookup: SandboxGatewayState, + pinnedGatewayName?: string, ): SandboxGatewayState { - const targetGatewayName = getSandboxTargetGatewayName(sandboxName); + const targetGatewayName = pinnedGatewayName ?? getSandboxTargetGatewayName(sandboxName); + if (pinnedGatewayName) { + // The owner-scoped RPC reached this exact gateway and reported NotFound. + // Ambient selection is irrelevant and must not trigger a sibling retry. + return tryRecoverDockerDriverSandbox(sandboxName, missingLookup, pinnedGatewayName); + } const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); if (lifecycle.state === "connected_other") { runOpenshell(["gateway", "select", targetGatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - const retry = getSandboxGatewayState(sandboxName); + const retry = getSandboxGatewayState(sandboxName, targetGatewayName); if (retry.state === "present") { return { ...retry, recoveredGateway: true, recoveryVia: "select" }; } @@ -306,6 +348,7 @@ export function reconcileMissingAgainstNamedGateway( function tryRecoverDockerDriverSandbox( sandboxName: string, missingLookup: SandboxGatewayState, + gatewayName?: string, ): SandboxGatewayState { let recovery: DockerDriverRecoveryResult; try { @@ -318,7 +361,7 @@ function tryRecoverDockerDriverSandbox( } // Recovery succeeded against Docker; re-query OpenShell so the // returned state reflects what the gateway sees post-restart. - const retried = getSandboxGatewayState(sandboxName); + const retried = getSandboxGatewayState(sandboxName, gatewayName); return { ...retried, recoveredSandbox: true, @@ -428,65 +471,44 @@ export function printGatewayLifecycleHint( } } -/** - * A `present` lookup is only trustworthy when it came from the sandbox's own - * gateway. On a multi-instance host the active OpenShell gateway can be a - * sibling that reports a stale or provisioning entry for the same sandbox name, - * so a plain `present` masks the real state on the owning gateway. When the - * sandbox's gateway is registered but a different gateway is currently active, - * select the owning gateway and re-query so the returned state reflects the - * gateway the sandbox was onboarded against rather than the last-used one. - * Returns `null` when the initial `present` can be trusted as-is (owning - * gateway already active, or the sandbox is not registry-known). - */ -async function reselectOwningGatewayForPresent( - sandboxName: string, - getState: SandboxGatewayStateLookup, -): Promise { - const targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName); - if (!targetGatewayName) return null; - const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); - if (lifecycle.state !== "connected_other") return null; - const selection = selectSandboxOwningGateway(sandboxName); - if (selection.outcome !== "selected") { - // Selection failed: the prior gateway is still active, so the - // original `present` result cannot be trusted as the sandbox's own - // state. Report the wrong-gateway condition instead of retrying - // against an unselected gateway or labelling a stale result recovered. - return { - state: "wrong_gateway_active", - activeGateway: lifecycle.activeGateway, - output: lifecycle.status, - }; - } - const retry = await getState(sandboxName); - if (retry.state === "present") { - return { ...retry, recoveredGateway: true, recoveryVia: "select" }; - } - if (retry.state === "missing") { - return reconcileMissingAgainstNamedGateway(sandboxName, retry); - } - return retry; -} - export async function getReconciledSandboxGatewayState( sandboxName: string, opts: { getState?: SandboxGatewayStateLookup } = {}, ): Promise { const getState = opts.getState ?? getSandboxGatewayState; - const lookup = await getState(sandboxName); + const targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName) ?? undefined; + const endpointOverride = gatewayEndpointOverrideState(); + if (endpointOverride) return endpointOverride; + if (targetGatewayName) { + // Keep OpenShell's active selection aligned for downstream operations, but + // never trust that process-global state for this lookup: another CLI can + // change it immediately after selection. The explicit gateway argument + // below is the per-subprocess authority for the status RPC. + const selection = selectSandboxOwningGateway(sandboxName); + if (selection.outcome !== "selected") { + const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); + return { + state: "wrong_gateway_active", + activeGateway: lifecycle.activeGateway, + output: + lifecycle.status || + `Failed to select owning gateway '${targetGatewayName}' for sandbox '${sandboxName}'.`, + }; + } + } + const lookup = await getState(sandboxName, targetGatewayName); if (lookup.state === "present") { - return (await reselectOwningGatewayForPresent(sandboxName, getState)) ?? lookup; + return lookup; } if (lookup.state === "missing") { - return reconcileMissingAgainstNamedGateway(sandboxName, lookup); + return reconcileMissingAgainstNamedGateway(sandboxName, lookup, targetGatewayName); } if (lookup.state === "gateway_error") { const targetGatewayName = getSandboxTargetGatewayName(sandboxName); const recovery = await recoverNamedGatewayRuntime({ gatewayName: targetGatewayName }); if (recovery.recovered) { - const retried = await getState(sandboxName); + const retried = await getState(sandboxName, targetGatewayName); if (retried.state === "present" || retried.state === "missing") { return { ...retried, recoveredGateway: true, recoveryVia: recovery.via || null }; } From a8ab4b28a9b7ce7db92de03591a12b50b55fc3fb Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Fri, 17 Jul 2026 16:17:35 -0700 Subject: [PATCH 5/8] fix(sandbox): pin exec policy probes to gateway Keep post-exec audit enablement and policy log reads bound to the same recorded gateway as the user command, even when ambient OpenShell selection drifts. Co-authored-by: Tinson Lai Signed-off-by: Apurv Kumaria --- .../sandbox/exec-gateway-target.test.ts | 41 +++++++++++++++++++ .../sandbox/exec-policy-hint-emission.ts | 17 ++++---- .../sandbox/exec-policy-hint-integration.ts | 2 + .../sandbox/exec-policy-hint-runtime.test.ts | 24 ++++++++++- src/lib/actions/sandbox/exec.ts | 7 +++- .../sandbox/gateway-state-hints.test.ts | 5 +++ src/lib/domain/sandbox/logs.ts | 20 +++++++-- 7 files changed, 101 insertions(+), 15 deletions(-) diff --git a/src/lib/actions/sandbox/exec-gateway-target.test.ts b/src/lib/actions/sandbox/exec-gateway-target.test.ts index 132520186f4..5d0a88c58f8 100644 --- a/src/lib/actions/sandbox/exec-gateway-target.test.ts +++ b/src/lib/actions/sandbox/exec-gateway-target.test.ts @@ -173,6 +173,47 @@ describe("execSandbox gateway targeting", () => { expect(run).not.toHaveBeenCalled(); }); + it("keeps post-exec policy probes pinned after ambient gateway selection drifts", async () => { + vi.stubEnv("OPENSHELL_GATEWAY", "ambient-sibling"); + const enableAudit = vi.fn(); + const probeLogs = vi.fn(() => ""); + const selectGateway = vi.fn(() => { + process.env.OPENSHELL_GATEWAY = "drifted-sibling"; + return { outcome: "selected" as const, gatewayName: "nemoclaw-8091" }; + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + execSandbox( + "beta", + ["curl", "https://example.invalid"], + {}, + { + resolveBinary: () => "openshell", + selectGateway, + run: async () => ({ status: 56 }), + cleanupDeps: cleanupSkipped, + policyHint: { + now: () => 0, + env: {}, + enableAudit, + probeLogs, + attempts: 1, + sleep: async () => {}, + writeStderr: () => {}, + }, + }, + ), + ).rejects.toThrow("__exit_56__"); + + expect(process.env.OPENSHELL_GATEWAY).toBe("drifted-sibling"); + expect(enableAudit).toHaveBeenCalledWith("beta", "nemoclaw-8091"); + expect(probeLogs).toHaveBeenCalledWith("beta", "nemoclaw-8091"); + }); + it("aborts before the workdir probe and exec when gateway selection fails", async () => { const order: string[] = []; const selectGateway = vi.fn(() => { diff --git a/src/lib/actions/sandbox/exec-policy-hint-emission.ts b/src/lib/actions/sandbox/exec-policy-hint-emission.ts index d1e2d0944d2..e795fa3df38 100644 --- a/src/lib/actions/sandbox/exec-policy-hint-emission.ts +++ b/src/lib/actions/sandbox/exec-policy-hint-emission.ts @@ -20,8 +20,8 @@ export const POLICY_HINT_PROBE_ATTEMPTS = 3; export const POLICY_HINT_PROBE_RETRY_MS = 120; export const POLICY_HINT_MAX_RUNTIME_TIMEOUT_MS = 1_000; -export type PolicyDenialLogProbe = (sandboxName: string) => string; -export type PolicyDenialAuditEnabler = (sandboxName: string) => void; +export type PolicyDenialLogProbe = (sandboxName: string, gatewayName?: string) => string; +export type PolicyDenialAuditEnabler = (sandboxName: string, gatewayName?: string) => void; export type PolicyDenialHintDeps = { probeLogs?: PolicyDenialLogProbe; @@ -45,8 +45,8 @@ function runtimeTimeoutMs(): number { return Math.min(getLogsProbeTimeoutMs(), POLICY_HINT_MAX_RUNTIME_TIMEOUT_MS); } -function defaultEnableAudit(sandboxName: string): void { - const result = captureOpenshell(buildEnableSandboxAuditLogsArgs(sandboxName), { +function defaultEnableAudit(sandboxName: string, gatewayName?: string): void { + const result = captureOpenshell(buildEnableSandboxAuditLogsArgs(sandboxName, gatewayName), { ignoreError: true, includeStderr: true, timeout: runtimeTimeoutMs(), @@ -56,13 +56,13 @@ function defaultEnableAudit(sandboxName: string): void { } } -function defaultProbeLogs(sandboxName: string): string { +function defaultProbeLogs(sandboxName: string, gatewayName?: string): string { const options: SandboxLogsOptions = { follow: false, lines: String(POLICY_HINT_TAIL_LINES), since: null, }; - const result = captureOpenshell(buildSandboxLogsArgs(sandboxName, options), { + const result = captureOpenshell(buildSandboxLogsArgs(sandboxName, options, gatewayName), { ignoreError: true, includeStderr: true, timeout: runtimeTimeoutMs(), @@ -90,6 +90,7 @@ export async function maybeEmitPolicyDenialHint( hadInvocationError: boolean, commandStartedAtMs: number, deps: PolicyDenialHintDeps = {}, + gatewayName?: string, ): Promise { const env = deps.env ?? process.env; if (!shouldProbePolicyDenial(commandCode, hadInvocationError, env)) return null; @@ -101,7 +102,7 @@ export async function maybeEmitPolicyDenialHint( const retryDelayMs = deps.retryDelayMs ?? POLICY_HINT_PROBE_RETRY_MS; try { - enableAudit(sandboxName); + enableAudit(sandboxName, gatewayName); } catch { // Deliberately silent: audit setup is optional and retained logs may still // contain the denial. Printing this diagnostic, even under a new debug @@ -112,7 +113,7 @@ export async function maybeEmitPolicyDenialHint( for (let attempt = 1; attempt <= attempts; attempt += 1) { let logOutput: string; try { - logOutput = probeLogs(sandboxName); + logOutput = probeLogs(sandboxName, gatewayName); } catch { // Deliberately silent for the same output-preservation boundary: a failed // optional probe must not append host diagnostics to the child's error. diff --git a/src/lib/actions/sandbox/exec-policy-hint-integration.ts b/src/lib/actions/sandbox/exec-policy-hint-integration.ts index 7f0d913bee3..f8ffb256707 100644 --- a/src/lib/actions/sandbox/exec-policy-hint-integration.ts +++ b/src/lib/actions/sandbox/exec-policy-hint-integration.ts @@ -21,6 +21,7 @@ export function preparePolicyHint( cliName: string, sandboxName: string, deps: ExecPolicyHintDeps = {}, + gatewayName?: string, ): (completion: ExecPolicyDenialHintCompletion) => Promise { const { now = Date.now, ...hintDeps } = deps; const commandStartedAtMs = now(); @@ -32,6 +33,7 @@ export function preparePolicyHint( Boolean(completion.invocationError), commandStartedAtMs, hintDeps, + gatewayName, ); }; } diff --git a/src/lib/actions/sandbox/exec-policy-hint-runtime.test.ts b/src/lib/actions/sandbox/exec-policy-hint-runtime.test.ts index ef68c01610a..a07f542769c 100644 --- a/src/lib/actions/sandbox/exec-policy-hint-runtime.test.ts +++ b/src/lib/actions/sandbox/exec-policy-hint-runtime.test.ts @@ -39,11 +39,22 @@ describe("policy-denial hint runtime adapter integration (#5978)", () => { env: {}, writeStderr: (line) => stderr.push(line), }, + "nemoclaw-8091", ); expect(captureOpenshell).toHaveBeenNthCalledWith( 1, - ["settings", "set", "runtime-sandbox", "--key", "ocsf_json_enabled", "--value", "true"], + [ + "settings", + "set", + "-g", + "nemoclaw-8091", + "runtime-sandbox", + "--key", + "ocsf_json_enabled", + "--value", + "true", + ], expect.objectContaining({ ignoreError: true, includeStderr: true, @@ -52,7 +63,16 @@ describe("policy-denial hint runtime adapter integration (#5978)", () => { ); expect(captureOpenshell).toHaveBeenNthCalledWith( 2, - ["logs", "runtime-sandbox", "-n", String(POLICY_HINT_TAIL_LINES), "--source", "all"], + [ + "logs", + "-g", + "nemoclaw-8091", + "runtime-sandbox", + "-n", + String(POLICY_HINT_TAIL_LINES), + "--source", + "all", + ], expect.objectContaining({ ignoreError: true, includeStderr: true, diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index 281045069aa..e9c220fdfe7 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -402,7 +402,12 @@ export async function execSandbox( if (options.workdir) { validateWorkdirOrFail(binary, sandboxName, options.workdir, deps.probeWorkdir, gatewayName); } - const emitPolicyDenialHint = preparePolicyHint(CLI_NAME, sandboxName, deps.policyHint); + const emitPolicyDenialHint = preparePolicyHint( + CLI_NAME, + sandboxName, + deps.policyHint, + gatewayName, + ); const completion = await runSandboxExecCommand( binary, sandboxName, diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index bcf71ce0f8f..2716d290f6e 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -23,6 +23,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { const openshellRuntime = requireDist("../../adapters/openshell/runtime.js"); const gatewayRuntime = requireDist("../../gateway-runtime-action.js"); const registry = requireDist("../../state/registry.js"); + const gatewaySelect = requireDist("./gateway-select.js"); vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockReturnValue(null); vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null); captureOpenshellSpy = vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ @@ -40,6 +41,10 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { gatewayName: "nemoclaw", gatewayPort: 8080, }); + vi.spyOn(gatewaySelect, "selectSandboxOwningGateway").mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw", + }); gatewayState = requireDist("./gateway-state.js"); }); diff --git a/src/lib/domain/sandbox/logs.ts b/src/lib/domain/sandbox/logs.ts index 9131db784a8..e8706d3fc92 100644 --- a/src/lib/domain/sandbox/logs.ts +++ b/src/lib/domain/sandbox/logs.ts @@ -50,8 +50,14 @@ export function normalizeSandboxLogsOptions( }; } -export function buildEnableSandboxAuditLogsArgs(sandboxName: string): string[] { - return ["settings", "set", sandboxName, "--key", "ocsf_json_enabled", "--value", "true"]; +export function buildEnableSandboxAuditLogsArgs( + sandboxName: string, + gatewayName?: string, +): string[] { + const args = ["settings", "set"]; + if (gatewayName) args.push("-g", gatewayName); + args.push(sandboxName, "--key", "ocsf_json_enabled", "--value", "true"); + return args; } export function buildSandboxOpenclawGatewayLogsArgs( @@ -66,8 +72,14 @@ export function buildSandboxOpenclawGatewayLogsArgs( return args; } -export function buildSandboxLogsArgs(sandboxName: string, options: SandboxLogsOptions): string[] { - const args = ["logs", sandboxName, "-n", options.lines, "--source", "all"]; +export function buildSandboxLogsArgs( + sandboxName: string, + options: SandboxLogsOptions, + gatewayName?: string, +): string[] { + const args = ["logs"]; + if (gatewayName) args.push("-g", gatewayName); + args.push(sandboxName, "-n", options.lines, "--source", "all"); if (options.since) { args.push("--since", options.since); } From 87162bd6609d04db5b27d7b7bae6eee2a38a9225 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Fri, 17 Jul 2026 16:26:21 -0700 Subject: [PATCH 6/8] fix(sandbox): keep gateway ownership snapshot consistent Use the gateway returned by owner selection as the authoritative target for status lookup, reconciliation, and recovery so concurrent registry updates cannot split routing across gateways. Co-authored-by: Tinson Lai Signed-off-by: Apurv Kumaria --- .../sandbox/gateway-state-drift.test.ts | 4 ++ .../gateway-state-owning-gateway.test.ts | 45 +++++++++++++++++++ src/lib/actions/sandbox/gateway-state.ts | 16 ++++--- 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/src/lib/actions/sandbox/gateway-state-drift.test.ts b/src/lib/actions/sandbox/gateway-state-drift.test.ts index 832640375e8..feab9617159 100644 --- a/src/lib/actions/sandbox/gateway-state-drift.test.ts +++ b/src/lib/actions/sandbox/gateway-state-drift.test.ts @@ -268,6 +268,10 @@ describe("sandbox gateway state drift guard", () => { gatewayName: "nemoclaw-8090", gatewayPort: 8090, }); + gatewaySelectSpy.mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw-8090", + }); recoverNamedGatewayRuntimeSpy.mockResolvedValue({ recovered: true, via: "start", diff --git a/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts index 8ebd9776874..b15098f6260 100644 --- a/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts +++ b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts @@ -115,6 +115,51 @@ describe("getReconciledSandboxGatewayState owning-gateway guard", () => { expect(result.recoveredGateway).toBeUndefined(); }); + it("queries the gateway returned by selection when registry ownership changes between snapshots", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + vi.mocked(gatewaySelect.selectSandboxOwningGateway).mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw-8092", + }); + const getState = vi.fn().mockResolvedValue({ state: "present", output: "Phase: Ready" }); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenCalledOnce(); + expect(getState).toHaveBeenCalledWith("beta", "nemoclaw-8092"); + expect(result).toMatchObject({ state: "present", output: "Phase: Ready" }); + }); + + it("keeps recovery pinned to the gateway returned by selection after ownership changes", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + vi.mocked(gatewaySelect.selectSandboxOwningGateway).mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw-8092", + }); + const recover = vi.spyOn(gatewayRuntime, "recoverNamedGatewayRuntime").mockResolvedValue({ + recovered: true, + via: "start", + } as never); + const getState = vi + .fn() + .mockResolvedValueOnce({ state: "gateway_error", output: "transport error" }) + .mockResolvedValueOnce({ state: "present", output: "Phase: Ready" }); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenNthCalledWith(1, "beta", "nemoclaw-8092"); + expect(recover).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-8092", + }); + expect(getState).toHaveBeenNthCalledWith(2, "beta", "nemoclaw-8092"); + expect(result).toMatchObject({ + state: "present", + output: "Phase: Ready", + recoveredGateway: true, + recoveryVia: "start", + }); + }); + it("does not return an ambient sibling timeout without first querying the healthy owner", async () => { vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); const getState = vi.fn((_name: string, gatewayName?: string) => diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 47e5377691e..d6a52a1d91f 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -476,7 +476,7 @@ export async function getReconciledSandboxGatewayState( opts: { getState?: SandboxGatewayStateLookup } = {}, ): Promise { const getState = opts.getState ?? getSandboxGatewayState; - const targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName) ?? undefined; + let targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName) ?? undefined; const endpointOverride = gatewayEndpointOverrideState(); if (endpointOverride) return endpointOverride; if (targetGatewayName) { @@ -495,6 +495,10 @@ export async function getReconciledSandboxGatewayState( `Failed to select owning gateway '${targetGatewayName}' for sandbox '${sandboxName}'.`, }; } + // Selection resolves registry ownership internally. If that snapshot changed + // after the initial lookup, keep the subprocess-local RPC pin aligned with + // the gateway that was actually selected rather than querying the stale one. + targetGatewayName = selection.gatewayName; } const lookup = await getState(sandboxName, targetGatewayName); if (lookup.state === "present") { @@ -505,10 +509,10 @@ export async function getReconciledSandboxGatewayState( } if (lookup.state === "gateway_error") { - const targetGatewayName = getSandboxTargetGatewayName(sandboxName); - const recovery = await recoverNamedGatewayRuntime({ gatewayName: targetGatewayName }); + const recoveryGatewayName = targetGatewayName ?? getSandboxTargetGatewayName(); + const recovery = await recoverNamedGatewayRuntime({ gatewayName: recoveryGatewayName }); if (recovery.recovered) { - const retried = await getState(sandboxName, targetGatewayName); + const retried = await getState(sandboxName, recoveryGatewayName); if (retried.state === "present" || retried.state === "missing") { return { ...retried, recoveredGateway: true, recoveryVia: recovery.via || null }; } @@ -522,7 +526,7 @@ export async function getReconciledSandboxGatewayState( } return { ...retried, recoveredGateway: true, recoveryVia: recovery.via || null }; } - const latestLifecycle = getNamedGatewayLifecycleState(targetGatewayName); + const latestLifecycle = getNamedGatewayLifecycleState(recoveryGatewayName); const latestStatus = stripAnsi(latestLifecycle.status || ""); if (/No gateway configured/i.test(latestStatus)) { return { @@ -532,7 +536,7 @@ export async function getReconciledSandboxGatewayState( } if ( /Connection refused|client error \(Connect\)|tcp connect error/i.test(latestStatus) && - gatewayNamePattern(targetGatewayName).test(latestStatus) + gatewayNamePattern(recoveryGatewayName).test(latestStatus) ) { return { state: "gateway_unreachable_after_restart", From 3968c286a2bb2eb118738ab1fbfe204e8abbb6c8 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Sat, 18 Jul 2026 05:16:57 +0000 Subject: [PATCH 7/8] test(sandbox): match rebuild preflight to gateway-pinned RPC semantics Signed-off-by: Tinson Lai --- .../sandbox/rebuild-gateway-drift.test.ts | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 0460aef8993..07b2eb50540 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -130,16 +130,17 @@ describe("rebuild gateway drift preflight", () => { recordedPort: 9000, activeGateway: "nemoclaw", }, - ])("refuses stale recovery when $activeGateway is active instead of recorded gateway $recordedGateway (#4497)", async ({ + ])("recovers $recordedGateway as stale even while $activeGateway is ambiently active, since the sandbox RPC is gateway-pinned (#4497)", async ({ recordedGateway, recordedPort, activeGateway, }) => { const entry = makeSandboxEntry(recordedGateway, recordedPort); + const registrySnapshot = { sandboxes: { alpha: entry } }; vi.mocked(registry.getSandbox).mockReturnValue(entry as never); + vi.mocked(registry.load).mockReturnValue(registrySnapshot as never); captureOpenshellSpy .mockReturnValueOnce({ status: 0, output: "" }) - .mockReturnValueOnce({ status: 1, output: "Error: × Not Found: sandbox not found" }) .mockReturnValueOnce({ status: 1, output: "Error: × Not Found: sandbox not found" }); getNamedGatewayLifecycleStateSpy.mockReturnValue({ state: "connected_other", @@ -148,23 +149,25 @@ describe("rebuild gateway drift preflight", () => { } as never); const behaviorLog = vi.fn(); - await expect(resolveRebuildLiveState("alpha", entry, behaviorLog, bail)).rejects.toThrow( - "Could not confirm live state", - ); + const result = await resolveRebuildLiveState("alpha", entry, behaviorLog, bail); - expect(getNamedGatewayLifecycleStateSpy).toHaveBeenCalledWith(recordedGateway); + expect(result).toEqual({ staleRecovery: true, staleRegistrySnapshot: registrySnapshot }); + expect(result?.staleRegistrySnapshot).not.toBe(registrySnapshot); + expect(getNamedGatewayLifecycleStateSpy).not.toHaveBeenCalled(); expect(runOpenshellSpy).toHaveBeenCalledWith( ["gateway", "select", recordedGateway], expect.objectContaining({ ignoreError: true }), ); - const output = errorSpy.mock.calls.flat().join("\n"); - expect(output).toContain("NOT been removed"); - expect(output).toContain(`openshell gateway select ${recordedGateway}`); - expect(registry.load).not.toHaveBeenCalled(); - expect(recoverDockerDriverSandboxSpy).not.toHaveBeenCalled(); - expect([...logSpy.mock.calls, ...behaviorLog.mock.calls].flat().join("\n")).not.toContain( - "No live workspace state to back up", + expect(captureOpenshellSpy).toHaveBeenNthCalledWith(1, ["sandbox", "list"]); + expect(captureOpenshellSpy).toHaveBeenNthCalledWith( + 2, + ["sandbox", "get", "-g", recordedGateway, "alpha"], + expect.anything(), ); + expect(recoverDockerDriverSandboxSpy).toHaveBeenCalledWith("alpha"); + expect(registry.load).toHaveBeenCalledOnce(); + expect(logSpy.mock.calls.flat().join("\n")).toContain("absent from the live OpenShell gateway"); + expect(behaviorLog.mock.calls.flat().join("\n")).toContain("Stale-sandbox recovery"); }); it.each([ @@ -212,10 +215,10 @@ describe("rebuild gateway drift preflight", () => { expect(captureOpenshellSpy).toHaveBeenNthCalledWith(2, ["sandbox", "list"]); expect(captureOpenshellSpy).toHaveBeenNthCalledWith( 3, - ["sandbox", "get", "alpha"], + ["sandbox", "get", "-g", gatewayName, "alpha"], expect.anything(), ); - expect(getNamedGatewayLifecycleStateSpy).toHaveBeenCalledWith(gatewayName); + expect(getNamedGatewayLifecycleStateSpy).not.toHaveBeenCalled(); expect(recoverDockerDriverSandboxSpy).toHaveBeenCalledWith("alpha"); expect(registry.load).toHaveBeenCalledOnce(); expect(logSpy.mock.calls.flat().join("\n")).toContain("absent from the live OpenShell gateway"); From fd600b2e5585e64491d17e4cdfdf5ed77d62e033 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Sat, 18 Jul 2026 06:29:21 +0000 Subject: [PATCH 8/8] test: match E2E fixtures to gateway-pinned sandbox RPC argv Signed-off-by: Tinson Lai --- test/cli/connect-recovery.test.ts | 10 +++++----- test/cli/connect-terminal-agent.test.ts | 4 ++-- test/cli/sandbox-status-json.test.ts | 6 +++--- test/cli/sandbox-status-text.test.ts | 12 ++++++------ test/cli/status-gateway-lifecycle.test.ts | 6 +++--- test/nemoclaw-cli-recovery.test.ts | 2 +- test/reboot-identity-drift.test.ts | 4 ++-- test/repro-2666-silent-list-status.test.ts | 12 ++++++++++-- test/sandbox-stuck-recovery.test.ts | 2 +- 9 files changed, 33 insertions(+), 25 deletions(-) diff --git a/test/cli/connect-recovery.test.ts b/test/cli/connect-recovery.test.ts index 7eb1dcfbfc4..e59d15a3800 100644 --- a/test/cli/connect-recovery.test.ts +++ b/test/cli/connect-recovery.test.ts @@ -175,7 +175,7 @@ describe("CLI connect recovery process contracts", () => { `marker_file=${JSON.stringify(markerFile)}`, `state_file=${JSON.stringify(stateFile)}`, 'printf \'%s\\n\' "$*" >> "$marker_file"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -214,7 +214,7 @@ describe("CLI connect recovery process contracts", () => { expect(result.code).toBe(0); expect(result.out).toContain("Probe complete: recovered OpenClaw gateway"); const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - expect(calls).toContain("sandbox get alpha"); + expect(calls).toContain("sandbox get -g nemoclaw alpha"); expect(calls.some((call) => call.startsWith("sandbox exec --name alpha -- sh -c"))).toBe( true, ); @@ -248,7 +248,7 @@ describe("CLI connect recovery process contracts", () => { `calls=${JSON.stringify(openshellCalls)}`, `state_file=${JSON.stringify(stateFile)}`, 'printf \'%s\\n\' "$*" >> "$calls"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -317,7 +317,7 @@ describe("CLI connect recovery process contracts", () => { `calls=${JSON.stringify(openshellCalls)}`, `state_file=${JSON.stringify(stateFile)}`, 'printf \'%s\\n\' "$*" >> "$calls"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -442,7 +442,7 @@ describe("CLI connect recovery process contracts", () => { " echo 'alpha Ready 2m ago'", " exit 0", "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", diff --git a/test/cli/connect-terminal-agent.test.ts b/test/cli/connect-terminal-agent.test.ts index 1e6db629dc2..0172eec8da2 100644 --- a/test/cli/connect-terminal-agent.test.ts +++ b/test/cli/connect-terminal-agent.test.ts @@ -25,7 +25,7 @@ describe("CLI dispatch for terminal agents", () => { "#!/usr/bin/env bash", `marker_file=${JSON.stringify(markerFile)}`, 'printf \'%s\\n\' "$*" >> "$marker_file"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -55,7 +55,7 @@ describe("CLI dispatch for terminal agents", () => { expect(r.code).toBe(0); expect(r.out).toContain("terminal smoke checks passed"); const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - expect(calls).toContain("sandbox get alpha"); + expect(calls).toContain("sandbox get -g nemoclaw alpha"); expect(calls.some((call) => call.includes("NEMOCLAW_AGENT_SMOKE_EXIT"))).toBe(true); expect(calls.some((call) => call.includes("nemoclaw-agent-smoke dcode --version"))).toBe(true); expect( diff --git a/test/cli/sandbox-status-json.test.ts b/test/cli/sandbox-status-json.test.ts index e50500203c5..13325121058 100644 --- a/test/cli/sandbox-status-json.test.ts +++ b/test/cli/sandbox-status-json.test.ts @@ -568,7 +568,7 @@ describe("CLI sandbox status JSON output", testTimeoutOptions(20_000), () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Error'", @@ -621,7 +621,7 @@ describe("CLI sandbox status JSON output", testTimeoutOptions(20_000), () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Ready'", @@ -710,7 +710,7 @@ describe("CLI sandbox status JSON output", testTimeoutOptions(20_000), () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Error'", diff --git a/test/cli/sandbox-status-text.test.ts b/test/cli/sandbox-status-text.test.ts index ad536a761e9..348187beb23 100644 --- a/test/cli/sandbox-status-text.test.ts +++ b/test/cli/sandbox-status-text.test.ts @@ -90,7 +90,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Ready'", @@ -145,7 +145,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "dcode-station" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "dcode-station" ] || [ "$5" = "dcode-station" ]; }; then', " echo 'Sandbox:'", " echo ' Name: dcode-station'", " echo ' Phase: Ready'", @@ -201,7 +201,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Ready'", @@ -329,7 +329,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Error'", @@ -423,7 +423,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Error'", @@ -493,7 +493,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", diff --git a/test/cli/status-gateway-lifecycle.test.ts b/test/cli/status-gateway-lifecycle.test.ts index 28b680b74df..0b183226e36 100644 --- a/test/cli/status-gateway-lifecycle.test.ts +++ b/test/cli/status-gateway-lifecycle.test.ts @@ -37,7 +37,7 @@ describe("CLI status gateway lifecycle process contracts", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', ` ${JSON.stringify(process.execPath)} -e "setInterval(() => {}, 1000)" &`, " wait", "fi", @@ -81,7 +81,7 @@ describe("CLI status gateway lifecycle process contracts", () => { [ "#!/usr/bin/env bash", `printf '%s\\n' "$*" >> ${JSON.stringify(markerFile)}`, - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -143,7 +143,7 @@ describe("CLI status gateway lifecycle process contracts", () => { expect(result.out).toContain("healthy"); expect(result.out).not.toContain("not verified"); const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - const sandboxGetIndex = calls.indexOf("sandbox get alpha"); + const sandboxGetIndex = calls.indexOf("sandbox get -g nemoclaw alpha"); const inferenceGetIndex = calls.indexOf("inference get -g nemoclaw"); expect(sandboxGetIndex).toBeGreaterThanOrEqual(0); expect(inferenceGetIndex).toBeGreaterThan(sandboxGetIndex); diff --git a/test/nemoclaw-cli-recovery.test.ts b/test/nemoclaw-cli-recovery.test.ts index d28c8904d5f..e0bccfb09ed 100644 --- a/test/nemoclaw-cli-recovery.test.ts +++ b/test/nemoclaw-cli-recovery.test.ts @@ -72,7 +72,7 @@ if (args[0] === "gateway" && args[1] === "info") { process.exit(0); } -if (args[0] === "sandbox" && args[1] === "get" && args[2] === "my-assistant") { +if (args[0] === "sandbox" && args[1] === "get" && (args[2] === "my-assistant" || args[4] === "my-assistant")) { state.sandboxGetCalls += 1; fs.writeFileSync(statePath, JSON.stringify(state)); if (state.sandboxGetCalls === 1) { diff --git a/test/reboot-identity-drift.test.ts b/test/reboot-identity-drift.test.ts index c08f42ba2c0..30d7388a90f 100644 --- a/test/reboot-identity-drift.test.ts +++ b/test/reboot-identity-drift.test.ts @@ -112,7 +112,7 @@ if (args[0] === "gateway" && args[1] === "select") { process.exit(0); } -if (args[0] === "sandbox" && args[1] === "get" && args[2] === ${JSON.stringify(sandboxName)}) { +if (args[0] === "sandbox" && args[1] === "get" && (args[2] === ${JSON.stringify(sandboxName)} || args[4] === ${JSON.stringify(sandboxName)})) { ${sandboxGetBehavior} } @@ -201,7 +201,7 @@ if (args[0] === "gateway" && args[1] === "start") { process.exit(0); } -if (args[0] === "sandbox" && args[1] === "get" && args[2] === ${JSON.stringify(sandboxName)}) { +if (args[0] === "sandbox" && args[1] === "get" && (args[2] === ${JSON.stringify(sandboxName)} || args[4] === ${JSON.stringify(sandboxName)})) { process.stdout.write("Sandbox:\\n\\n Id: abc\\n Name: ${sandboxName}\\n Phase: Ready\\n"); process.exit(0); } diff --git a/test/repro-2666-silent-list-status.test.ts b/test/repro-2666-silent-list-status.test.ts index c417d2dad2f..217443d3bfc 100644 --- a/test/repro-2666-silent-list-status.test.ts +++ b/test/repro-2666-silent-list-status.test.ts @@ -187,7 +187,7 @@ describe("simulated container-stopped and foreign-port-holder subprocess regress " echo 'Gateway: nemoclaw'", " exit 0", " ;;", - ' "sandbox get my-assist")', + ' "sandbox get my-assist"|"sandbox get -g nemoclaw my-assist")', " echo 'transport error: client error (Connect)' >&2", " exit 1", " ;;", @@ -354,6 +354,10 @@ describe("simulated container-stopped and foreign-port-holder subprocess regress " echo 'Error: sandbox not found' >&2", " exit 1", " ;;", + ' "sandbox get -g nemoclaw my-assist")', + " echo 'client error (Connect): tcp connect error: Connection refused (os error 61)' >&2", + " exit 1", + " ;;", " status)", " cat <<'EOF'", "Status: Disconnected", @@ -392,6 +396,10 @@ describe("simulated container-stopped and foreign-port-holder subprocess regress " echo 'Error: sandbox not found' >&2", " exit 1", " ;;", + ' "sandbox get -g nemoclaw my-assist")', + " echo 'transport error: no gateway configured' >&2", + " exit 1", + " ;;", " status)", " echo 'No gateway configured'", " exit 1", @@ -444,7 +452,7 @@ describe("simulated container-stopped and foreign-port-holder subprocess regress writeFakeOpenshell([ "#!/usr/bin/env bash", 'case "$*" in', - ' "sandbox get my-assist")', + ' "sandbox get my-assist"|"sandbox get -g nemoclaw my-assist")', " echo 'transport error: unexpected EOF' >&2", " exit 1", " ;;", diff --git a/test/sandbox-stuck-recovery.test.ts b/test/sandbox-stuck-recovery.test.ts index 1e8acc06088..16b417cc096 100644 --- a/test/sandbox-stuck-recovery.test.ts +++ b/test/sandbox-stuck-recovery.test.ts @@ -59,7 +59,7 @@ if (args[0] === "gateway" && args[1] === "info") { process.exit(0); } -if (args[0] === "sandbox" && args[1] === "get" && args[2] === ${JSON.stringify(sandboxName)}) { +if (args[0] === "sandbox" && args[1] === "get" && (args[2] === ${JSON.stringify(sandboxName)} || args[4] === ${JSON.stringify(sandboxName)})) { process.stdout.write("Sandbox:\\n\\n Id: abc\\n Name: ${sandboxName}\\n Phase: ${phase}\\n"); process.exit(0); }