From 30c231342b4006889ffb95219697090e62ba3f3d Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sat, 12 Sep 2026 23:02:52 -0700 Subject: [PATCH 01/12] fix(launch): release lifecycle locks before session wait --- src/lib/actions/sandbox/exec.test.ts | 101 ++++++++++++- src/lib/actions/sandbox/exec.ts | 148 +++++++++++-------- src/lib/actions/sandbox/launch.test.ts | 161 +++++++++++++++++---- src/lib/actions/sandbox/launch.ts | 46 +++--- src/lib/cli/nemoclaw-oclif-command.test.ts | 8 +- src/lib/cli/nemoclaw-oclif-command.ts | 7 +- 6 files changed, 351 insertions(+), 120 deletions(-) diff --git a/src/lib/actions/sandbox/exec.test.ts b/src/lib/actions/sandbox/exec.test.ts index 7b9e1446aad..a8bef805519 100644 --- a/src/lib/actions/sandbox/exec.test.ts +++ b/src/lib/actions/sandbox/exec.test.ts @@ -1,9 +1,27 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + import { afterEach, describe, expect, it, vi } from "vitest"; -import { execSandbox, type SandboxExecCleanupDeps, workdirMissingMessage } from "./exec"; +import { + withMcpLifecycleLock, + withMcpLifecycleLockSync, + isMcpLifecycleLockHeld, +} from "../../state/mcp-lifecycle-lock-acquisition"; +import { + withPortableHostFence, + portableHostFencePath, +} from "../../state/portable-uninstall-retirement"; +import { + execSandbox, + startSandboxExec, + type SandboxExecCleanupDeps, + workdirMissingMessage, +} from "./exec"; describe("workdirMissingMessage", () => { it("renders a user-facing CLI error with the offending path", () => { @@ -303,3 +321,84 @@ describe("execSandbox scope-upgrade hint wiring (#9744)", () => { expect(stderr).toBe(""); }); }); + +it("dispatches under authority and completes outside the released lock context (#11647)", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-exec-")); + const stateDir = path.join(home, "state"); + const lockOptions = { stateDir }; + const sandboxName = "launch-exec"; + const ended = Promise.withResolvers(); + const release = vi.fn(); + const cleanup = vi.fn(() => + withMcpLifecycleLockSync( + sandboxName, + () => { + expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(true); + return { applies: true as const, ok: true, issues: [] }; + }, + lockOptions, + ), + ); + let dispatched = false; + try { + const finish = await withPortableHostFence(home, () => + withMcpLifecycleLock( + sandboxName, + () => + startSandboxExec( + sandboxName, + ["bash", "-lc", "openclaw tui"], + { tty: true, stdin: true, timeoutSeconds: 0 }, + { + selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), + commandExecutor: { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => { + expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(true); + expect(fs.existsSync(portableHostFencePath(home))).toBe(true); + dispatched = true; + await ended.promise; + return { outcome: { kind: "completed", exitCode: 0 }, release }; + }, + }, + cleanupDeps: { + getSandbox: () => { + expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(false); + expect(fs.existsSync(portableHostFencePath(home))).toBe(false); + return { agent: "openclaw" }; + }, + inspectMutableConfigPerms: cleanup, + repairMutableConfigPerms: () => { + throw new Error("healthy config needs no repair"); + }, + }, + exit: (code) => { + throw new Error(`exit:${code}`); + }, + }, + ), + lockOptions, + ), + ); + expect(dispatched).toBe(true); + expect(cleanup).not.toHaveBeenCalled(); + let contenderEntered = false; + await withPortableHostFence(home, () => + withMcpLifecycleLock( + sandboxName, + () => { + contenderEntered = true; + }, + lockOptions, + ), + ); + expect(contenderEntered).toBe(true); + ended.resolve(); + await expect(finish()).rejects.toThrow("exit:0"); + expect(cleanup).toHaveBeenCalledOnce(); + expect(release).toHaveBeenCalledOnce(); + } finally { + ended.resolve(); + fs.rmSync(home, { recursive: true, force: true }); + } +}); diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index 1e1a930df2e..57b5baaf627 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -161,8 +161,7 @@ export type ExecSandboxDeps = { async function runSandboxExecRequest( executor: OpenShellSandboxCommandExecutor, request: OpenShellSandboxCommandRequest, - cleanupDeps: SandboxExecCleanupDeps, -): Promise { +): Promise>> { let completed: Awaited>; try { completed = await executor.runStreaming(request); @@ -178,6 +177,14 @@ async function runSandboxExecRequest( release: () => {}, }; } + return completed; +} + +function finishSandboxExecRequest( + completed: Awaited>, + request: OpenShellSandboxCommandRequest, + cleanupDeps: SandboxExecCleanupDeps, +): SandboxExecCompletion { try { const commandCode = completed.outcome.kind === "completed" ? completed.outcome.exitCode : 1; const invocationError = @@ -240,6 +247,17 @@ export async function execSandbox( options: SandboxExecOptions = {}, deps: ExecSandboxDeps = {}, ): Promise { + const finish = await startSandboxExec(sandboxName, command, options, deps); + await finish(); +} + +/** Dispatch under the caller's lifecycle fence; invoke completion after releasing it. */ +export async function startSandboxExec( + sandboxName: string, + command: readonly string[], + options: SandboxExecOptions = {}, + deps: ExecSandboxDeps = {}, +): Promise<() => Promise> { const { CLI_NAME } = require("../../cli/branding"); const exit = deps.exit ?? process.exit; if (command.length === 0) { @@ -296,71 +314,77 @@ export async function execSandbox( deps.policyHint, gatewayName, ); - const completion = await runSandboxExecRequest( - commandExecutor, - { - sandboxName, - target, - command: wrapExecCommandWithRuntimeEnv(command), - workdir: options.workdir, - tty: options.tty, - timeoutSeconds: options.timeoutSeconds, - stdin: options.stdin, - }, - deps.cleanupDeps ?? { - getSandbox: (name) => - (require("../../state/registry") as typeof import("../../state/registry")).getSandbox(name), - inspectMutableConfigPerms: (name) => - ( - require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms") - ).inspectMutableConfigPerms(name), - repairMutableConfigPerms: (name) => - ( - require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms") - ).repairMutableConfigPerms(name), - }, - ); - if (completion.invocationError) { - console.error(` Failed to invoke openshell: ${completion.invocationError}`); - console.error(" Ensure 'openshell' is installed and on PATH."); - } - if (completion.cleanupError) { - console.error(cleanupFailureMessage(completion.commandCode, completion.cleanupError)); - } - await emitPolicyDenialHint(completion); - let exitCode = completion.code; - const googleChatApprovalCommitted = - completion.commandCode === 0 && isGoogleChatPairingApproval(command); - const managedGoogleChatApproval = - googleChatApprovalCommitted && gatewaySelection.outcome === "selected"; - if (googleChatApprovalCommitted && completion.cleanupError) { - console.error( - managedGoogleChatApproval - ? googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName) - : googleChatPairingUnmanagedCleanupFailureMessage(sandboxName), + const request: OpenShellSandboxCommandRequest = { + sandboxName, + target, + command: wrapExecCommandWithRuntimeEnv(command), + workdir: options.workdir, + tty: options.tty, + timeoutSeconds: options.timeoutSeconds, + stdin: options.stdin, + }; + const pending = runSandboxExecRequest(commandExecutor, request); + return async () => { + const completion = finishSandboxExecRequest( + await pending, + request, + deps.cleanupDeps ?? { + getSandbox: (name) => + (require("../../state/registry") as typeof import("../../state/registry")).getSandbox( + name, + ), + inspectMutableConfigPerms: (name) => + ( + require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms") + ).inspectMutableConfigPerms(name), + repairMutableConfigPerms: (name) => + ( + require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms") + ).repairMutableConfigPerms(name), + }, ); - } - if (exitCode === 0 && managedGoogleChatApproval) { - let recordedAgent: string | null = null; - try { - recordedAgent = (deps.resolveSandboxAgent ?? defaultResolveSandboxAgent)(sandboxName); - } catch { - console.error(googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName)); - exit(1); + if (completion.invocationError) { + console.error(` Failed to invoke openshell: ${completion.invocationError}`); + console.error(" Ensure 'openshell' is installed and on PATH."); + } + if (completion.cleanupError) { + console.error(cleanupFailureMessage(completion.commandCode, completion.cleanupError)); + } + await emitPolicyDenialHint(completion); + let exitCode = completion.code; + const googleChatApprovalCommitted = + completion.commandCode === 0 && isGoogleChatPairingApproval(command); + const managedGoogleChatApproval = + googleChatApprovalCommitted && gatewaySelection.outcome === "selected"; + if (googleChatApprovalCommitted && completion.cleanupError) { + console.error( + managedGoogleChatApproval + ? googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName) + : googleChatPairingUnmanagedCleanupFailureMessage(sandboxName), + ); } - if (recordedAgent === "openclaw") { - let restartSucceeded = false; + if (exitCode === 0 && managedGoogleChatApproval) { + let recordedAgent: string | null = null; try { - restartSucceeded = (await (deps.restartGateway ?? defaultRestartGateway)(sandboxName)).ok; + recordedAgent = (deps.resolveSandboxAgent ?? defaultResolveSandboxAgent)(sandboxName); } catch { - // The approval already committed inside OpenClaw. Convert restart - // exceptions into the same explicit partial-commit recovery contract. - } - if (!restartSucceeded) { console.error(googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName)); - exitCode = 1; + exit(1); + } + if (recordedAgent === "openclaw") { + let restartSucceeded = false; + try { + restartSucceeded = (await (deps.restartGateway ?? defaultRestartGateway)(sandboxName)).ok; + } catch { + // The approval already committed inside OpenClaw. Convert restart + // exceptions into the same explicit partial-commit recovery contract. + } + if (!restartSucceeded) { + console.error(googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName)); + exitCode = 1; + } } } - } - exit(exitCode); + exit(exitCode); + }; } diff --git a/src/lib/actions/sandbox/launch.test.ts b/src/lib/actions/sandbox/launch.test.ts index 3163e7aa3fe..c4c1460fea3 100644 --- a/src/lib/actions/sandbox/launch.test.ts +++ b/src/lib/actions/sandbox/launch.test.ts @@ -14,7 +14,7 @@ const mocks = vi.hoisted(() => ({ printInteractiveSessionHints: vi.fn(), completeInteractiveSessionSetup: vi.fn(), completeReadinessQualifiedInteractiveSessionSetup: vi.fn(), - execSandbox: vi.fn(), + startSandboxExec: vi.fn(), startSandboxSession: vi.fn(), createSessionExecutor: vi.fn(), releaseSession: vi.fn(), @@ -40,7 +40,7 @@ vi.mock("./connect", () => ({ mocks.completeReadinessQualifiedInteractiveSessionSetup, })); vi.mock("./exec", () => ({ - execSandbox: mocks.execSandbox, + startSandboxExec: mocks.startSandboxExec, wrapExecCommandWithRuntimeEnv: (command: readonly string[]) => command, })); vi.mock("../../adapters/openshell/sandbox-command-cli", async (importOriginal) => ({ @@ -177,7 +177,7 @@ function prepareSession( } function launchedCommand(): readonly string[] { - return mocks.execSandbox.mock.calls[0]?.[1] as readonly string[]; + return mocks.startSandboxExec.mock.calls[0]?.[1] as readonly string[]; } type AsyncTestLock = (name: string, operation: () => Promise | T) => Promise; @@ -215,8 +215,9 @@ describe("launchSandbox", () => { beforeEach(() => { vi.clearAllMocks(); mocks.calls.length = 0; - mocks.execSandbox.mockImplementation(async () => { - mocks.calls.push("execSandbox"); + mocks.startSandboxExec.mockImplementation(async () => { + mocks.calls.push("startSandboxExec"); + return async () => undefined; }); mocks.createSessionExecutor.mockReturnValue({ start: mocks.startSandboxSession }); mocks.startSandboxSession.mockImplementation(() => { @@ -333,6 +334,7 @@ describe("launchSandbox", () => { cancel: vi.fn(), }); const exit = vi.spyOn(process, "exit").mockImplementation((code) => { + expect(mocks.releaseSession).toHaveBeenCalledOnce(); throw new Error(`exit:${code}`); }); await expect( @@ -346,7 +348,7 @@ describe("launchSandbox", () => { expect(mocks.releaseSession).toHaveBeenCalledOnce(); }); - it("holds schema-5 authority through the exact interactive child execution (#9203)", async () => { + it("holds schema-5 authority through dispatch and releases it while the child runs (#11647)", async () => { vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "do-not-forward"); vi.stubEnv("GITHUB_TOKEN", "do-not-forward"); vi.stubEnv("AWS_SECRET_ACCESS_KEY", "do-not-forward"); @@ -379,13 +381,22 @@ describe("launchSandbox", () => { }); await childStarted.promise; const contender = withSandboxMutationLock("alpha", () => events.push("contender")); - await Promise.resolve(); + await new Promise((resolve) => setImmediate(resolve)); expect(mocks.recoverPortableLifecycle).toHaveBeenCalledOnce(); expect(mocks.recoverPortableLifecycle).toHaveBeenCalledWith("alpha", entry, "gateway-alpha"); expect(mocks.assertCommandCurrent).toHaveBeenCalledTimes(3); - expect(events).toEqual(["sandbox:acquired", "sandbox:released", "sandbox:acquired", "child"]); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(events).toEqual([ + "sandbox:acquired", + "sandbox:released", + "sandbox:acquired", + "child", + "sandbox:released", + "sandbox:acquired", + "contender", + "sandbox:released", + ]); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled(); expect(mocks.startSandboxSession).toHaveBeenCalledWith({ kind: "command", @@ -439,7 +450,7 @@ describe("launchSandbox", () => { ).rejects.toThrow("lifecycle authority changed"); expect(mocks.recoverPortableLifecycle).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); expect(mocks.startSandboxSession).not.toHaveBeenCalled(); }); @@ -467,7 +478,7 @@ describe("launchSandbox", () => { expect(mocks.printInteractiveSessionHints).not.toHaveBeenCalled(); expect(mocks.completeReadinessQualifiedInteractiveSessionSetup).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); expect(mocks.startSandboxSession).not.toHaveBeenCalled(); }); @@ -487,7 +498,7 @@ describe("launchSandbox", () => { ).rejects.toThrow("lifecycle authority changed"); expect(mocks.recoverPortableLifecycle).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); }); it("launches NemoCUA through the ordinary terminal-agent path (#9649)", async () => { @@ -522,10 +533,10 @@ describe("launchSandbox", () => { ); expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); }); - // Regression guard for #6291: execSandbox wraps every command in + // Regression guard for #6291: startSandboxExec wraps every command in // wrapExecCommandWithRuntimeEnv, which unsets OPENCLAW_GATEWAY_TOKEN after // sourcing the runtime env file. Only a login shell re-sources the file // through the profile, so a bare argv would start the agent with different @@ -550,14 +561,14 @@ describe("launchSandbox", () => { expect(mocks.calls).toEqual([ "prepareInteractiveSession", "prepareHermesLightTerminalSkin", - "execSandbox", + "startSandboxExec", ]); }); it("requests an interactive session with no timeout (#6006)", async () => { await launchSandbox("alpha"); - expect(mocks.execSandbox.mock.calls[0]?.[2]).toEqual({ + expect(mocks.startSandboxExec.mock.calls[0]?.[2]).toEqual({ tty: true, stdin: true, timeoutSeconds: 0, @@ -568,7 +579,7 @@ describe("launchSandbox", () => { await launchSandbox("beta-01"); expect(mocks.prepareInteractiveSession).toHaveBeenCalledWith("beta-01"); - expect(mocks.execSandbox.mock.calls[0]?.[0]).toBe("beta-01"); + expect(mocks.startSandboxExec.mock.calls[0]?.[0]).toBe("beta-01"); }); // Without the preflight, the agent starts over exec while gateway process @@ -579,7 +590,7 @@ describe("launchSandbox", () => { expect(mocks.calls).toEqual([ "prepareInteractiveSession", "prepareHermesLightTerminalSkin", - "execSandbox", + "startSandboxExec", ]); expect(mocks.withLaunchReadinessMutationGate).toHaveBeenCalledWith( expect.objectContaining({ epochId: null }), @@ -604,7 +615,7 @@ describe("launchSandbox", () => { expect(mocks.withLaunchReadinessMutationGate).not.toHaveBeenCalled(); expect(mocks.prepareInteractiveSession).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); }); it("skips the complete OpenClaw pairing pass after current lease qualification (#9023)", async () => { @@ -626,7 +637,7 @@ describe("launchSandbox", () => { const launch = launchSandbox("alpha"); await vi.waitFor(() => expect(mocks.printInteractiveSessionHints).toHaveBeenCalledOnce()); expect(mocks.completeReadinessQualifiedInteractiveSessionSetup).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); finishProbe(); await launch; @@ -645,7 +656,7 @@ describe("launchSandbox", () => { expect(mocks.completeReadinessQualifiedInteractiveSessionSetup).toHaveBeenCalledBefore( mocks.prepareHermesLightTerminalSkin, ); - expect(mocks.prepareHermesLightTerminalSkin).toHaveBeenCalledBefore(mocks.execSandbox); + expect(mocks.prepareHermesLightTerminalSkin).toHaveBeenCalledBefore(mocks.startSandboxExec); expect(launchedCommand()).toEqual(["bash", "-lc", "openclaw tui"]); expect(mocks.emitPortableOpenClawAlreadyRunningTiming).toHaveBeenCalledOnce(); }); @@ -918,7 +929,7 @@ describe("launchSandbox", () => { openclaw, sb, ); - expect(mocks.execSandbox).toHaveBeenCalledOnce(); + expect(mocks.startSandboxExec).toHaveBeenCalledOnce(); }); it("keeps repeated launch and exit cycles on the accepted non-sliding lease (#8942)", async () => { @@ -935,7 +946,7 @@ describe("launchSandbox", () => { await launchSandbox("alpha"); expect(mocks.prepareInteractiveSession).not.toHaveBeenCalled(); - expect(mocks.execSandbox).toHaveBeenCalledTimes(2); + expect(mocks.startSandboxExec).toHaveBeenCalledTimes(2); expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled(); expect(mocks.completeReadinessQualifiedInteractiveSessionSetup).toHaveBeenCalledTimes(2); expect(mocks.completeInteractiveSessionSetup).not.toHaveBeenCalled(); @@ -968,7 +979,7 @@ describe("launchSandbox", () => { await launchSandbox("alpha"); expect(mocks.prepareInteractiveSession).toHaveBeenCalledBefore(mocks.publishLaunchReadiness); - expect(mocks.publishLaunchReadiness).toHaveBeenCalledBefore(mocks.execSandbox); + expect(mocks.publishLaunchReadiness).toHaveBeenCalledBefore(mocks.startSandboxExec); expect(mocks.publishLaunchReadiness).toHaveBeenCalledWith( expect.any(Object), expect.objectContaining({ @@ -1066,7 +1077,7 @@ describe("launchSandbox", () => { publicationRelease.resolve(); await rejection; - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); expect(mocks.startSandboxSession).not.toHaveBeenCalled(); }); @@ -1088,7 +1099,7 @@ describe("launchSandbox", () => { expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce(); expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled(); expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); }); it("keeps ordinary launch available when evidence observation, hashing, or storage fails (#8942)", async () => { @@ -1106,7 +1117,7 @@ describe("launchSandbox", () => { await expect(launchSandbox("alpha")).resolves.toBeUndefined(); expect(mocks.prepareInteractiveSession).toHaveBeenCalled(); - expect(mocks.execSandbox).toHaveBeenCalled(); + expect(mocks.startSandboxExec).toHaveBeenCalled(); }); it("runs the complete preflight and interactive command when macOS evidence is unavailable (#8942)", async () => { @@ -1129,7 +1140,7 @@ describe("launchSandbox", () => { expect.objectContaining({ epochId: null }), expect.any(Function), ); - expect(mocks.execSandbox).toHaveBeenCalledOnce(); + expect(mocks.startSandboxExec).toHaveBeenCalledOnce(); }); it("stops before the complete preflight when a prior launch-readiness epoch may remain acceptable (#8942)", async () => { @@ -1149,7 +1160,7 @@ describe("launchSandbox", () => { expect(mocks.prepareInteractiveSession).not.toHaveBeenCalled(); expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); }); it("stops before the complete preflight when the fenced epoch cannot be revalidated (#8942)", async () => { @@ -1170,7 +1181,7 @@ describe("launchSandbox", () => { expect(mocks.prepareInteractiveSession).not.toHaveBeenCalled(); expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); }); it("does not launch after final semantic validation reports unhealthy state (#8942)", async () => { @@ -1193,7 +1204,7 @@ describe("launchSandbox", () => { ); expect(mocks.prepareInteractiveSession).toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); }); it("does not launch after final live-policy validation fails", async () => { @@ -1225,7 +1236,7 @@ describe("launchSandbox", () => { expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce(); expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled(); - expect(mocks.execSandbox).not.toHaveBeenCalled(); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); expect(mocks.startSandboxSession).not.toHaveBeenCalled(); }); @@ -1240,4 +1251,90 @@ describe("launchSandbox", () => { logSpy.mockRestore(); } }); + it.each([ + { + scenario: "hermes-accepted", + agentName: "hermes", + portable: true, + readiness: "accepted", + disposition: activeHermesDisposition(), + }, + { + scenario: "hermes-prepared", + agentName: "hermes", + portable: true, + readiness: "fallback", + disposition: activeHermesDisposition(), + }, + { + scenario: "openclaw-prepared", + agentName: "openclaw", + portable: false, + readiness: "fallback", + disposition: { kind: "absent" }, + }, + ])( + "permits another lifecycle operation while $scenario TUI remains open (#11647)", + async ({ agentName, portable, readiness, disposition }) => { + mocks.assertCommandCurrent.mockReset().mockImplementation(() => undefined); + const agent = loadAgent(agentName); + const entry = sandboxEntry(agent.name); + prepareSession(agent.name, agent, portable); + mocks.inspectPortableReceiptDisposition.mockReturnValue(disposition); + mocks.inspectLaunchReadiness.mockResolvedValue({ + kind: readiness, + category: "missing", + fence: null, + gatewayName: "nemoclaw", + gatewayPort: 8080, + fenceFailed: true, + recoveryBlocked: false, + agent, + sb: entry, + }); + const sessionEnded = deferred(); + const childStarted = deferred(); + mocks.startSandboxSession.mockImplementation(() => { + childStarted.resolve(); + return { + completion: sessionEnded.promise.then(() => ({ + outcome: { kind: "exited", exitCode: 0 }, + stdout: "", + stderr: "", + release: mocks.releaseSession, + })), + cancel: vi.fn(), + }; + }); + mocks.startSandboxExec.mockImplementation(async () => { + childStarted.resolve(); + return async () => { + await sessionEnded.promise; + }; + }); + const events: string[] = []; + const lock = createSerialTestLock(events, "sandbox"); + const launch = launchSandbox("alpha", { + getSandbox: () => entry, + resolveSandboxGatewayName: () => "gateway-alpha", + withSandboxMutationLock: lock, + }); + await Promise.race([ + childStarted.promise, + launch.then(() => { + throw new Error("launch ended without starting a session"); + }), + ]); + let anotherOperationEntered = false; + const anotherOperation = lock("alpha", () => { + anotherOperationEntered = true; + }); + await new Promise((resolve) => setImmediate(resolve)); + const enteredWhileSessionOpen = anotherOperationEntered; + sessionEnded.resolve(); + await Promise.all([launch, anotherOperation]); + expect(anotherOperationEntered).toBe(true); + expect(enteredWhileSessionOpen).toBe(true); + }, + ); }); diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts index 3bde0a4fd3a..d5442e2d457 100644 --- a/src/lib/actions/sandbox/launch.ts +++ b/src/lib/actions/sandbox/launch.ts @@ -20,7 +20,7 @@ import { printInteractiveSessionHints, } from "./connect"; import { prepareHermesLightTerminalSkin } from "./connect-hermes-light-skin"; -import { execSandbox, wrapExecCommandWithRuntimeEnv } from "./exec"; +import { startSandboxExec, wrapExecCommandWithRuntimeEnv } from "./exec"; import { inspectPortableAgentReceiptDisposition, captureHermesPortableAcceptedReadinessObservation, @@ -246,19 +246,20 @@ async function launchAgentWithPortableAuthority( beforeOrdinaryLaunch?: () => Promise, beforeAgentExec?: () => void, ): Promise { - const runOrdinaryAgent = async (): Promise => { + const startOrdinaryAgent = async (): Promise<{ finish: () => Promise }> => { prepareHermesLightTerminalSkin(sandboxName, agent, process.env); beforeAgentExec?.(); - await execSandbox(sandboxName, command, { + const finish = await startSandboxExec(sandboxName, command, { tty: true, stdin: true, timeoutSeconds: 0, }); + return { finish }; }; - const runHermesPortableAgent = async ( + const startHermesPortableAgent = ( gatewayName: string, commandAuthority: HermesPortableReadinessCommandAuthority, - ): Promise => { + ): { finish: () => Promise } => { commandAuthority.assertCurrent(); beforeAgentExec?.(); const session = createCliOpenShellSandboxSessionExecutor({ @@ -273,26 +274,29 @@ async function launchAgentWithPortableAuthority( output: "inherit", timeoutSeconds: 0, }); - const result = await session.completion; - try { - if (result.outcome.kind === "failed" && result.outcome.reason !== "transport") { - throw new Error(result.outcome.message); - } - if (result.outcome.exitCode !== 0) process.exit(result.outcome.exitCode); - } finally { - result.release(); - } + return { + finish: async () => { + const result = await session.completion; + try { + if (result.outcome.kind === "failed" && result.outcome.reason !== "transport") { + throw new Error(result.outcome.message); + } + } finally { + result.release(); + } + if (result.outcome.exitCode !== 0) process.exit(result.outcome.exitCode); + }, + }; }; const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock; - await lockSandbox(sandboxName, async () => { + const started = await lockSandbox(sandboxName, async () => { const current = inspectPortableAgentReceiptDisposition(sandboxName); if ((current.kind === "hermes") !== hermesPortableSnapshot) { throw new Error("Hermes portable lifecycle authority changed before agent launch."); } if (current.kind !== "hermes") { await beforeOrdinaryLaunch?.(); - await runOrdinaryAgent(); - return; + return await startOrdinaryAgent(); } if (current.phase !== "active") { throw new Error("Hermes portable lifecycle authority changed before agent launch."); @@ -320,8 +324,7 @@ async function launchAgentWithPortableAuthority( throw new Error("Hermes portable registry authority changed before agent launch."); } acceptedHermesAuthority.command.assertCurrent(); - await runHermesPortableAgent(gatewayName, acceptedHermesAuthority.command); - return; + return startHermesPortableAgent(gatewayName, acceptedHermesAuthority.command); } const recovery = recoverPortableDemoSandboxLifecycleForConnect( sandboxName, @@ -350,11 +353,14 @@ async function launchAgentWithPortableAuthority( ) { throw new Error("Hermes portable lifecycle authority changed at agent launch."); } - await runHermesPortableAgent( + return startHermesPortableAgent( gatewayName, qualifyHermesPortableOperatingCommandAuthority(sandboxName), ); }); + // Waiting and post-command cleanup must run outside both the lifecycle fence + // and its async context, so cleanup can acquire fresh authority after exit. + await started.finish(); } export async function launchSandbox( diff --git a/src/lib/cli/nemoclaw-oclif-command.test.ts b/src/lib/cli/nemoclaw-oclif-command.test.ts index a98400f2121..0d473f2f4fb 100644 --- a/src/lib/cli/nemoclaw-oclif-command.test.ts +++ b/src/lib/cli/nemoclaw-oclif-command.test.ts @@ -393,7 +393,7 @@ describe("NemoClawCommand", () => { }); }); - it("uses the same Portable host and lifecycle fences for launch and stop", async () => { + it("leaves interactive launch locking to the action while fencing stop (#11647)", async () => { vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "18080"); useHermesPortableAuthority(); @@ -401,11 +401,15 @@ describe("NemoClawCommand", () => { await PortableStopCommand.run(["alpha"], process.cwd()); expect(PortableLaunchCommand.observed).toEqual({ + host: false, + lifecycle: false, + portableLifecycle: false, + }); + expect(PortableStopCommand.observed).toEqual({ host: true, lifecycle: false, portableLifecycle: true, }); - expect(PortableStopCommand.observed).toEqual(PortableLaunchCommand.observed); }); it("selects the gateway lifecycle lock under the host fence when there is no Hermes receipt", async () => { diff --git a/src/lib/cli/nemoclaw-oclif-command.ts b/src/lib/cli/nemoclaw-oclif-command.ts index 3915d289319..cc3345951f1 100644 --- a/src/lib/cli/nemoclaw-oclif-command.ts +++ b/src/lib/cli/nemoclaw-oclif-command.ts @@ -129,7 +129,7 @@ export abstract class NemoClawCommand extends Command { enforceRemovedImmutabilityMigrationBoundary(sandboxName, { allowStateRecord: allowRemovedImmutabilityStateRecord, }); - if (this.isInteractiveConnect(commandId)) { + if (this.isInteractiveSession(commandId)) { return await super._run(); } const runLocked = () => { @@ -144,9 +144,10 @@ export abstract class NemoClawCommand extends Command { return await withSandboxLifecycleLock(sandboxName, runLocked); } - private isInteractiveConnect(commandId: string | undefined): boolean { + private isInteractiveSession(commandId: string | undefined): boolean { return ( - commandId === "sandbox:connect" && this.lifecycleParserOutput?.flags["probe-only"] !== true + commandId === "launch" || + (commandId === "sandbox:connect" && this.lifecycleParserOutput?.flags["probe-only"] !== true) ); } From 7aa5c9d7c0bed5266ea2257593df1e6245c3126e Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sat, 12 Sep 2026 23:12:03 -0700 Subject: [PATCH 02/12] test(launch): use the supported promise completion API --- src/lib/actions/sandbox/exec.test.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/lib/actions/sandbox/exec.test.ts b/src/lib/actions/sandbox/exec.test.ts index a8bef805519..9cc810926b5 100644 --- a/src/lib/actions/sandbox/exec.test.ts +++ b/src/lib/actions/sandbox/exec.test.ts @@ -327,7 +327,10 @@ it("dispatches under authority and completes outside the released lock context ( const stateDir = path.join(home, "state"); const lockOptions = { stateDir }; const sandboxName = "launch-exec"; - const ended = Promise.withResolvers(); + let endSession: () => void = () => {}; + const ended = new Promise((resolve) => { + endSession = resolve; + }); const release = vi.fn(); const cleanup = vi.fn(() => withMcpLifecycleLockSync( @@ -357,7 +360,7 @@ it("dispatches under authority and completes outside the released lock context ( expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(true); expect(fs.existsSync(portableHostFencePath(home))).toBe(true); dispatched = true; - await ended.promise; + await ended; return { outcome: { kind: "completed", exitCode: 0 }, release }; }, }, @@ -393,12 +396,12 @@ it("dispatches under authority and completes outside the released lock context ( ), ); expect(contenderEntered).toBe(true); - ended.resolve(); + endSession(); await expect(finish()).rejects.toThrow("exit:0"); expect(cleanup).toHaveBeenCalledOnce(); expect(release).toHaveBeenCalledOnce(); } finally { - ended.resolve(); + endSession(); fs.rmSync(home, { recursive: true, force: true }); } }); From 19cde39c60ff02483eaf94ae6a9a32588da2fea5 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sat, 12 Sep 2026 23:47:22 -0700 Subject: [PATCH 03/12] test(launch): prove lock release across processes Signed-off-by: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> --- src/lib/actions/sandbox/exec.test.ts | 179 +++++++++++++++------------ 1 file changed, 102 insertions(+), 77 deletions(-) diff --git a/src/lib/actions/sandbox/exec.test.ts b/src/lib/actions/sandbox/exec.test.ts index 9cc810926b5..3ea2f719f1e 100644 --- a/src/lib/actions/sandbox/exec.test.ts +++ b/src/lib/actions/sandbox/exec.test.ts @@ -1,12 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { execTimeout, testTimeoutOptions } from "../../../../test/helpers/timeouts"; + import { withMcpLifecycleLock, withMcpLifecycleLockSync, @@ -322,86 +325,108 @@ describe("execSandbox scope-upgrade hint wiring (#9744)", () => { }); }); -it("dispatches under authority and completes outside the released lock context (#11647)", async () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-exec-")); - const stateDir = path.join(home, "state"); - const lockOptions = { stateDir }; - const sandboxName = "launch-exec"; - let endSession: () => void = () => {}; - const ended = new Promise((resolve) => { - endSession = resolve; - }); - const release = vi.fn(); - const cleanup = vi.fn(() => - withMcpLifecycleLockSync( - sandboxName, - () => { - expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(true); - return { applies: true as const, ok: true, issues: [] }; - }, - lockOptions, - ), - ); - let dispatched = false; - try { - const finish = await withPortableHostFence(home, () => - withMcpLifecycleLock( - sandboxName, - () => - startSandboxExec( - sandboxName, - ["bash", "-lc", "openclaw tui"], - { tty: true, stdin: true, timeoutSeconds: 0 }, - { - selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), - commandExecutor: { - probeDirectory: async () => ({ state: "present" }), - runStreaming: async () => { - expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(true); - expect(fs.existsSync(portableHostFencePath(home))).toBe(true); - dispatched = true; - await ended; - return { outcome: { kind: "completed", exitCode: 0 }, release }; - }, - }, - cleanupDeps: { - getSandbox: () => { - expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(false); - expect(fs.existsSync(portableHostFencePath(home))).toBe(false); - return { agent: "openclaw" }; - }, - inspectMutableConfigPerms: cleanup, - repairMutableConfigPerms: () => { - throw new Error("healthy config needs no repair"); - }, - }, - exit: (code) => { - throw new Error(`exit:${code}`); - }, - }, - ), - lockOptions, - ), - ); - expect(dispatched).toBe(true); - expect(cleanup).not.toHaveBeenCalled(); - let contenderEntered = false; - await withPortableHostFence(home, () => - withMcpLifecycleLock( +it( + "releases authority to another process before interactive completion (#11647)", + testTimeoutOptions(15_000), + async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-exec-")); + const stateDir = path.join(home, "state"); + const lockOptions = { stateDir }; + const sandboxName = "launch-exec"; + let endSession: () => void = () => {}; + const ended = new Promise((resolve) => { + endSession = resolve; + }); + const release = vi.fn(); + const cleanup = vi.fn(() => + withMcpLifecycleLockSync( sandboxName, () => { - contenderEntered = true; + expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(true); + return { applies: true as const, ok: true, issues: [] }; }, lockOptions, ), ); - expect(contenderEntered).toBe(true); - endSession(); - await expect(finish()).rejects.toThrow("exit:0"); - expect(cleanup).toHaveBeenCalledOnce(); - expect(release).toHaveBeenCalledOnce(); - } finally { - endSession(); - fs.rmSync(home, { recursive: true, force: true }); - } -}); + let dispatched = false; + try { + const finish = await withPortableHostFence(home, () => + withMcpLifecycleLock( + sandboxName, + () => + startSandboxExec( + sandboxName, + ["bash", "-lc", "openclaw tui"], + { tty: true, stdin: true, timeoutSeconds: 0 }, + { + selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), + commandExecutor: { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => { + expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(true); + expect(fs.existsSync(portableHostFencePath(home))).toBe(true); + dispatched = true; + await ended; + return { outcome: { kind: "completed", exitCode: 0 }, release }; + }, + }, + cleanupDeps: { + getSandbox: () => { + expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(false); + expect(fs.existsSync(portableHostFencePath(home))).toBe(false); + return { agent: "openclaw" }; + }, + inspectMutableConfigPerms: cleanup, + repairMutableConfigPerms: () => { + throw new Error("healthy config needs no repair"); + }, + }, + exit: (code) => { + throw new Error(`exit:${code}`); + }, + }, + ), + lockOptions, + ), + ); + expect(dispatched).toBe(true); + expect(cleanup).not.toHaveBeenCalled(); + const contender = spawnSync( + process.execPath, + [ + "--no-warnings", + "--import", + "tsx", + "--input-type=module", + "-e", + ` + const retirement = (await import(process.argv[1])).default; + const lifecycle = (await import(process.argv[2])).default; + await retirement.withPortableHostFence(process.argv[3], () => + lifecycle.withMcpLifecycleLock(process.argv[4], () => { + console.log("contender-entered"); + }, { stateDir: process.argv[5] }), + ); + `, + new URL("../../state/portable-uninstall-retirement.ts", import.meta.url).href, + new URL("../../state/mcp-lifecycle-lock-acquisition.ts", import.meta.url).href, + home, + sandboxName, + stateDir, + ], + { encoding: "utf8", timeout: execTimeout() }, + ); + expect(contender.status, contender.stderr || String(contender.error ?? "")).toBe(0); + expect(contender.stdout.trim()).toBe("contender-entered"); + expect(cleanup).not.toHaveBeenCalled(); + expect(release).not.toHaveBeenCalled(); + endSession(); + await expect(finish()).rejects.toThrow("exit:0"); + expect(cleanup).toHaveBeenCalledOnce(); + expect(release).toHaveBeenCalledOnce(); + } finally { + endSession(); + fs.rmSync(home, { recursive: true, force: true }); + } + }, +); From c5b79535d35f81d8243543d5e8920c6746a16268 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sun, 13 Sep 2026 00:34:01 -0700 Subject: [PATCH 04/12] fix(launch): bind delayed cleanup to dispatched sandbox Signed-off-by: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> --- src/lib/actions/sandbox/exec.test.ts | 8 ++- src/lib/actions/sandbox/exec.ts | 14 +++-- src/lib/actions/sandbox/launch.test.ts | 75 ++++++++++++++++++++++++++ src/lib/actions/sandbox/launch.ts | 22 +++++--- 4 files changed, 107 insertions(+), 12 deletions(-) diff --git a/src/lib/actions/sandbox/exec.test.ts b/src/lib/actions/sandbox/exec.test.ts index 3ea2f719f1e..eb4e9d9dc1b 100644 --- a/src/lib/actions/sandbox/exec.test.ts +++ b/src/lib/actions/sandbox/exec.test.ts @@ -349,6 +349,8 @@ it( ), ); let dispatched = false; + let lockHeldDuringCleanup: boolean | null = null; + let fenceHeldDuringCleanup: boolean | null = null; try { const finish = await withPortableHostFence(home, () => withMcpLifecycleLock( @@ -372,8 +374,8 @@ it( }, cleanupDeps: { getSandbox: () => { - expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(false); - expect(fs.existsSync(portableHostFencePath(home))).toBe(false); + lockHeldDuringCleanup = isMcpLifecycleLockHeld(sandboxName, stateDir); + fenceHeldDuringCleanup = fs.existsSync(portableHostFencePath(home)); return { agent: "openclaw" }; }, inspectMutableConfigPerms: cleanup, @@ -422,6 +424,8 @@ it( expect(release).not.toHaveBeenCalled(); endSession(); await expect(finish()).rejects.toThrow("exit:0"); + expect(lockHeldDuringCleanup).toBe(false); + expect(fenceHeldDuringCleanup).toBe(false); expect(cleanup).toHaveBeenCalledOnce(); expect(release).toHaveBeenCalledOnce(); } finally { diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index 57b5baaf627..9bc7fbc2e12 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -148,6 +148,8 @@ export type ExecSandboxDeps = { /** Post-command observability and cleanup seams. */ policyHint?: ExecPolicyHintDeps; cleanupDeps?: SandboxExecCleanupDeps; + /** Reacquire and verify dispatch authority before delayed launch cleanup. */ + withCleanupAuthority?: (cleanup: () => string | null) => Promise; /** Activate config written by a successful direct Google Chat pairing approval. */ restartGateway?: SandboxExecGatewayRestart; /** Resolve the sandbox's recorded agent before applying agent-specific post-exec effects. */ @@ -180,16 +182,19 @@ async function runSandboxExecRequest( return completed; } -function finishSandboxExecRequest( +async function finishSandboxExecRequest( completed: Awaited>, request: OpenShellSandboxCommandRequest, cleanupDeps: SandboxExecCleanupDeps, -): SandboxExecCompletion { + withCleanupAuthority?: ExecSandboxDeps["withCleanupAuthority"], +): Promise { try { const commandCode = completed.outcome.kind === "completed" ? completed.outcome.exitCode : 1; const invocationError = completed.outcome.kind === "failed" ? completed.outcome.error.message : undefined; - const cleanupError = cleanupOpenClawAfterExec(request.sandboxName, cleanupDeps) ?? undefined; + const cleanup = () => cleanupOpenClawAfterExec(request.sandboxName, cleanupDeps); + const cleanupError = + (await (withCleanupAuthority ? withCleanupAuthority(cleanup) : cleanup())) ?? undefined; return { code: cleanupError ? 1 : commandCode, commandCode, @@ -325,7 +330,7 @@ export async function startSandboxExec( }; const pending = runSandboxExecRequest(commandExecutor, request); return async () => { - const completion = finishSandboxExecRequest( + const completion = await finishSandboxExecRequest( await pending, request, deps.cleanupDeps ?? { @@ -342,6 +347,7 @@ export async function startSandboxExec( require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms") ).repairMutableConfigPerms(name), }, + deps.withCleanupAuthority, ); if (completion.invocationError) { console.error(` Failed to invoke openshell: ${completion.invocationError}`); diff --git a/src/lib/actions/sandbox/launch.test.ts b/src/lib/actions/sandbox/launch.test.ts index c4c1460fea3..0c7894e095c 100644 --- a/src/lib/actions/sandbox/launch.test.ts +++ b/src/lib/actions/sandbox/launch.test.ts @@ -1251,6 +1251,81 @@ describe("launchSandbox", () => { logSpy.mockRestore(); } }); + it.each([ + { replacement: "unchanged", cleanupCount: 1 }, + { replacement: "recreated", cleanupCount: 0 }, + { replacement: "removed", cleanupCount: 0 }, + ])( + "binds completion cleanup to the launched sandbox ($replacement)", + async ({ replacement, cleanupCount }) => { + const { startSandboxExec } = await vi.importActual("./exec"); + const agent = loadAgent("openclaw"); + let current: SandboxEntry | null = sandboxEntry(agent.name); + prepareSession(agent.name, agent); + const sessionEnded = deferred(); + const childStarted = deferred(); + const events: string[] = []; + const lock = createSerialTestLock(events, "sandbox"); + const cleanup = vi.fn(() => { + events.push("cleanup"); + return { applies: true as const, ok: true, issues: [] }; + }); + const release = vi.fn(); + mocks.startSandboxExec.mockImplementation((name, command, options, deps) => + startSandboxExec(name, command, options, { + ...deps, + selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), + commandExecutor: { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => { + childStarted.resolve(); + await sessionEnded.promise; + return { outcome: { kind: "completed", exitCode: 0 }, release }; + }, + }, + cleanupDeps: { + getSandbox: () => current, + inspectMutableConfigPerms: cleanup, + repairMutableConfigPerms: () => { + throw new Error("unexpected repair"); + }, + }, + exit: (code) => { + throw new Error(`exit:${code}`); + }, + }), + ); + const launch = launchSandbox("alpha", { + getSandbox: () => current, + withSandboxMutationLock: lock, + }); + const completion = expect(launch).rejects.toThrow("exit:0"); + await childStarted.promise; + await lock("alpha", () => { + current = + replacement === "removed" + ? null + : { + ...current!, + lifecycleGeneration: + replacement === "recreated" ? "generation-new" : "generation-alpha", + }; + events.push("replacement-observed"); + }); + expect(cleanup).not.toHaveBeenCalled(); + events.length = 0; + sessionEnded.resolve(); + await completion; + expect(cleanup).toHaveBeenCalledTimes(cleanupCount); + expect(release).toHaveBeenCalledOnce(); + expect(events).toEqual( + cleanupCount === 1 + ? ["sandbox:acquired", "cleanup", "sandbox:released"] + : ["sandbox:acquired", "sandbox:released"], + ); + }, + ); + it.each([ { scenario: "hermes-accepted", diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts index d5442e2d457..e5ab4de50f1 100644 --- a/src/lib/actions/sandbox/launch.ts +++ b/src/lib/actions/sandbox/launch.ts @@ -246,14 +246,25 @@ async function launchAgentWithPortableAuthority( beforeOrdinaryLaunch?: () => Promise, beforeAgentExec?: () => void, ): Promise { + const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock; const startOrdinaryAgent = async (): Promise<{ finish: () => Promise }> => { prepareHermesLightTerminalSkin(sandboxName, agent, process.env); beforeAgentExec?.(); - const finish = await startSandboxExec(sandboxName, command, { - tty: true, - stdin: true, - timeoutSeconds: 0, - }); + const readSandbox = deps.getSandbox ?? getKnownSandboxTarget; + const launchedEntry = structuredClone(readSandbox(sandboxName)); + const finish = await startSandboxExec( + sandboxName, + command, + { tty: true, stdin: true, timeoutSeconds: 0 }, + { + withCleanupAuthority: (cleanup) => + lockSandbox(sandboxName, () => { + const current = readSandbox(sandboxName); + if (!launchedEntry || !isDeepStrictEqual(current, launchedEntry)) return null; + return cleanup(); + }), + }, + ); return { finish }; }; const startHermesPortableAgent = ( @@ -288,7 +299,6 @@ async function launchAgentWithPortableAuthority( }, }; }; - const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock; const started = await lockSandbox(sandboxName, async () => { const current = inspectPortableAgentReceiptDisposition(sandboxName); if ((current.kind === "hermes") !== hermesPortableSnapshot) { From d94ee10e8af8bafde8310edfba16ad7537e008ac Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sun, 13 Sep 2026 01:20:25 -0700 Subject: [PATCH 05/12] fix(launch): fence readiness through interactive dispatch --- src/lib/actions/sandbox/launch.test.ts | 51 ++++- src/lib/actions/sandbox/launch.ts | 251 +++++++++++++------------ 2 files changed, 172 insertions(+), 130 deletions(-) diff --git a/src/lib/actions/sandbox/launch.test.ts b/src/lib/actions/sandbox/launch.test.ts index 0c7894e095c..6759fecff52 100644 --- a/src/lib/actions/sandbox/launch.test.ts +++ b/src/lib/actions/sandbox/launch.test.ts @@ -387,8 +387,6 @@ describe("launchSandbox", () => { expect(mocks.recoverPortableLifecycle).toHaveBeenCalledWith("alpha", entry, "gateway-alpha"); expect(mocks.assertCommandCurrent).toHaveBeenCalledTimes(3); expect(events).toEqual([ - "sandbox:acquired", - "sandbox:released", "sandbox:acquired", "child", "sandbox:released", @@ -422,8 +420,6 @@ describe("launchSandbox", () => { await launch; await contender; expect(events).toEqual([ - "sandbox:acquired", - "sandbox:released", "sandbox:acquired", "child", "sandbox:released", @@ -454,7 +450,7 @@ describe("launchSandbox", () => { expect(mocks.startSandboxSession).not.toHaveBeenCalled(); }); - it("does not run accepted ordinary setup when schema-5 publishes before the launch fence (#9203)", async () => { + it("qualifies schema-5 published before the launch fence without ordinary setup (#9203)", async () => { const hermes = loadAgent("hermes"); const entry = sandboxEntry("hermes"); mocks.inspectLaunchReadiness.mockResolvedValue({ @@ -474,12 +470,13 @@ describe("launchSandbox", () => { return await operation(); }, }), - ).rejects.toThrow("lifecycle authority changed"); + ).resolves.toBeUndefined(); expect(mocks.printInteractiveSessionHints).not.toHaveBeenCalled(); expect(mocks.completeReadinessQualifiedInteractiveSessionSetup).not.toHaveBeenCalled(); expect(mocks.startSandboxExec).not.toHaveBeenCalled(); - expect(mocks.startSandboxSession).not.toHaveBeenCalled(); + expect(mocks.startSandboxSession).toHaveBeenCalledOnce(); + expect(mocks.requireActiveLifecycleAuthority).toHaveBeenCalled(); }); it("rejects schema-5 retirement inside the launch lifecycle fence (#9203)", async () => { @@ -1251,8 +1248,47 @@ describe("launchSandbox", () => { logSpy.mockRestore(); } }); + it("holds lifecycle authority from ordinary readiness through dispatch (#11647)", async () => { + const events: string[] = []; + const lock = createSerialTestLock(events, "sandbox"); + const inspected = deferred(); + const continueInspection = deferred(); + const childStarted = deferred(); + const sessionEnded = deferred(); + mocks.inspectLaunchReadiness.mockImplementationOnce(async () => { + events.push("readiness"); + inspected.resolve(); + await continueInspection.promise; + return { + kind: "accepted", + category: "accepted", + agent: loadAgent("openclaw"), + sb: sandboxEntry("openclaw"), + }; + }); + mocks.startSandboxExec.mockImplementationOnce(async () => { + events.push("dispatch"); + childStarted.resolve(); + return () => sessionEnded.promise; + }); + const launch = launchSandbox("alpha", { withSandboxMutationLock: lock }); + await inspected.promise; + const contender = lock("alpha", () => { + events.push("contender"); + }); + continueInspection.resolve(); + await childStarted.promise; + await contender; + sessionEnded.resolve(); + await launch; + expect( + events.filter((event) => ["readiness", "dispatch", "contender"].includes(event)), + ).toEqual(["readiness", "dispatch", "contender"]); + }); + it.each([ { replacement: "unchanged", cleanupCount: 1 }, + { replacement: "metadata", cleanupCount: 1 }, { replacement: "recreated", cleanupCount: 0 }, { replacement: "removed", cleanupCount: 0 }, ])( @@ -1307,6 +1343,7 @@ describe("launchSandbox", () => { ? null : { ...current!, + model: replacement === "metadata" ? "updated-model" : current!.model, lifecycleGeneration: replacement === "recreated" ? "generation-new" : "generation-alpha", }; diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts index e5ab4de50f1..8042e1ea08d 100644 --- a/src/lib/actions/sandbox/launch.ts +++ b/src/lib/actions/sandbox/launch.ts @@ -180,62 +180,51 @@ async function inspectLaunchReadinessForLaunch( throw new Error("Hermes portable registry authority changed before launch readiness."); } - const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock; - return lockSandbox(sandboxName, async () => { - const lifecycleDeps = { readRegistry: readSandbox }; - let active = requireHermesPortableActiveLifecycleAuthority( - sandboxName, - undefined, - lifecycleDeps, - ); - let qualified = qualifyHermesPortableAcceptedReadinessAuthority(sandboxName); - if (qualified.kind === "requalification-required") { - const requalified = requalifyPortableAgentSandboxAuthority(sandboxName, lifecycleDeps); - if (requalified.kind === "not-installed" || requalified.kind === "not-hermes") { - throw new Error("Hermes portable lifecycle authority changed before launch readiness."); - } - active = requireHermesPortableActiveLifecycleAuthority(sandboxName, active, lifecycleDeps); - qualified = qualifyHermesPortableAcceptedReadinessAuthority(sandboxName, { - priorReceiptAuthority: requalified, - }); - if (qualified.kind === "requalification-required") { - throw new Error("Hermes portable schema-6 authority was not published before launch."); - } + const lifecycleDeps = { readRegistry: readSandbox }; + let active = requireHermesPortableActiveLifecycleAuthority(sandboxName, undefined, lifecycleDeps); + let qualified = qualifyHermesPortableAcceptedReadinessAuthority(sandboxName); + if (qualified.kind === "requalification-required") { + const requalified = requalifyPortableAgentSandboxAuthority(sandboxName, lifecycleDeps); + if (requalified.kind === "not-installed" || requalified.kind === "not-hermes") { + throw new Error("Hermes portable lifecycle authority changed before launch readiness."); } - const command = qualified.commandAuthority; - const capture = (args: string[], options = {}) => - captureHermesPortableAcceptedReadinessObservation(command, args, options); - const commandExecutor = createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor( - { - resolveBinary: () => command.executablePath, - hostCwd: REPOSITORY_ROOT, - hostEnv: command.env, - }, - command.assertCurrent, - ); - command.assertCurrent(); - const decision = await inspect(sandboxName, { - ...createBoundLaunchReadinessDeps(capture, commandExecutor), - getSandbox: readSandbox, - withSandboxLock: async (_name, operation) => operation(), + active = requireHermesPortableActiveLifecycleAuthority(sandboxName, active, lifecycleDeps); + qualified = qualifyHermesPortableAcceptedReadinessAuthority(sandboxName, { + priorReceiptAuthority: requalified, }); - command.assertCurrent(); - const current = requireHermesPortableActiveLifecycleAuthority( - sandboxName, - active, - lifecycleDeps, - ); - if (decision.kind === "accepted" && !isDeepStrictEqual(decision.sb, current.entry)) { - throw new Error("Hermes portable registry authority changed during launch readiness."); + if (qualified.kind === "requalification-required") { + throw new Error("Hermes portable schema-6 authority was not published before launch."); } - return { - decision, - hermesAuthority: { active: current, command }, - }; + } + const command = qualified.commandAuthority; + const capture = (args: string[], options = {}) => + captureHermesPortableAcceptedReadinessObservation(command, args, options); + const commandExecutor = createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor( + { + resolveBinary: () => command.executablePath, + hostCwd: REPOSITORY_ROOT, + hostEnv: command.env, + }, + command.assertCurrent, + ); + command.assertCurrent(); + const decision = await inspect(sandboxName, { + ...createBoundLaunchReadinessDeps(capture, commandExecutor), + getSandbox: readSandbox, + withSandboxLock: async (_name, operation) => operation(), }); + command.assertCurrent(); + const current = requireHermesPortableActiveLifecycleAuthority(sandboxName, active, lifecycleDeps); + if (decision.kind === "accepted" && !isDeepStrictEqual(decision.sb, current.entry)) { + throw new Error("Hermes portable registry authority changed during launch readiness."); + } + return { + decision, + hermesAuthority: { active: current, command }, + }; } -async function launchAgentWithPortableAuthority( +async function startAgentWithPortableAuthority( sandboxName: string, agent: AgentDefinition | null, entry: SandboxEntry | null, @@ -245,7 +234,7 @@ async function launchAgentWithPortableAuthority( acceptedHermesAuthority: HermesPortableLaunchAuthority | null, beforeOrdinaryLaunch?: () => Promise, beforeAgentExec?: () => void, -): Promise { +): Promise<{ finish: () => Promise }> { const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock; const startOrdinaryAgent = async (): Promise<{ finish: () => Promise }> => { prepareHermesLightTerminalSkin(sandboxName, agent, process.env); @@ -260,7 +249,18 @@ async function launchAgentWithPortableAuthority( withCleanupAuthority: (cleanup) => lockSandbox(sandboxName, () => { const current = readSandbox(sandboxName); - if (!launchedEntry || !isDeepStrictEqual(current, launchedEntry)) return null; + if ( + !launchedEntry || + !current || + current.agent !== launchedEntry.agent || + current.gatewayName !== launchedEntry.gatewayName || + !launchedEntry.lifecycleGeneration || + !launchedEntry.lifecycleLiveIdentityFingerprint || + current.lifecycleGeneration !== launchedEntry.lifecycleGeneration || + current.lifecycleLiveIdentityFingerprint !== + launchedEntry.lifecycleLiveIdentityFingerprint + ) + return null; return cleanup(); }), }, @@ -299,84 +299,89 @@ async function launchAgentWithPortableAuthority( }, }; }; - const started = await lockSandbox(sandboxName, async () => { - const current = inspectPortableAgentReceiptDisposition(sandboxName); - if ((current.kind === "hermes") !== hermesPortableSnapshot) { - throw new Error("Hermes portable lifecycle authority changed before agent launch."); - } - if (current.kind !== "hermes") { - await beforeOrdinaryLaunch?.(); - return await startOrdinaryAgent(); - } - if (current.phase !== "active") { - throw new Error("Hermes portable lifecycle authority changed before agent launch."); - } - const readSandbox = deps.getSandbox ?? getKnownSandboxTarget; - const registered = readSandbox(sandboxName); - if ( - agent?.name !== "hermes" || - entry?.agent !== "hermes" || - !registered || - registered.agent !== "hermes" || - registered.gatewayName !== entry.gatewayName || - registered.lifecycleGeneration !== entry.lifecycleGeneration || - current.gatewayName !== entry.gatewayName || - current.lifecycleGeneration !== entry.lifecycleGeneration - ) { + const current = inspectPortableAgentReceiptDisposition(sandboxName); + if ((current.kind === "hermes") !== hermesPortableSnapshot) { + throw new Error("Hermes portable lifecycle authority changed before agent launch."); + } + if (current.kind !== "hermes") { + await beforeOrdinaryLaunch?.(); + return await startOrdinaryAgent(); + } + if (current.phase !== "active") { + throw new Error("Hermes portable lifecycle authority changed before agent launch."); + } + const readSandbox = deps.getSandbox ?? getKnownSandboxTarget; + const registered = readSandbox(sandboxName); + if ( + agent?.name !== "hermes" || + entry?.agent !== "hermes" || + !registered || + registered.agent !== "hermes" || + registered.gatewayName !== entry.gatewayName || + registered.lifecycleGeneration !== entry.lifecycleGeneration || + current.gatewayName !== entry.gatewayName || + current.lifecycleGeneration !== entry.lifecycleGeneration + ) { + throw new Error("Hermes portable registry authority changed before agent launch."); + } + const gatewayName = (deps.resolveSandboxGatewayName ?? resolveSandboxGatewayName)(registered); + if (acceptedHermesAuthority) { + requireHermesPortableActiveLifecycleAuthority(sandboxName, acceptedHermesAuthority.active, { + readRegistry: readSandbox, + }); + if (!isDeepStrictEqual(registered, acceptedHermesAuthority.active.entry)) { throw new Error("Hermes portable registry authority changed before agent launch."); } - const gatewayName = (deps.resolveSandboxGatewayName ?? resolveSandboxGatewayName)(registered); - if (acceptedHermesAuthority) { - requireHermesPortableActiveLifecycleAuthority(sandboxName, acceptedHermesAuthority.active, { - readRegistry: readSandbox, - }); - if (!isDeepStrictEqual(registered, acceptedHermesAuthority.active.entry)) { - throw new Error("Hermes portable registry authority changed before agent launch."); - } - acceptedHermesAuthority.command.assertCurrent(); - return startHermesPortableAgent(gatewayName, acceptedHermesAuthority.command); - } - const recovery = recoverPortableDemoSandboxLifecycleForConnect( - sandboxName, - registered, - gatewayName, - ); - if (recovery.kind === "not-installed") { - throw new Error("Hermes portable lifecycle authority disappeared before agent launch."); - } - const finalReceipt = inspectPortableAgentReceiptDisposition(sandboxName); - const finalRegistered = readSandbox(sandboxName); - if ( - finalReceipt.kind !== "hermes" || - finalReceipt.phase !== "active" || - !finalRegistered || - finalRegistered.agent !== "hermes" || - finalRegistered.gatewayName !== registered.gatewayName || - finalRegistered.lifecycleGeneration !== registered.lifecycleGeneration || - finalRegistered.lifecycleLiveIdentityFingerprint !== - registered.lifecycleLiveIdentityFingerprint || - finalRegistered.openshellDriver !== registered.openshellDriver || - finalRegistered.openshellVersion !== registered.openshellVersion || - finalReceipt.gatewayName !== registered.gatewayName || - finalReceipt.lifecycleGeneration !== registered.lifecycleGeneration || - finalReceipt.liveIdentityFingerprint !== registered.lifecycleLiveIdentityFingerprint - ) { - throw new Error("Hermes portable lifecycle authority changed at agent launch."); - } - return startHermesPortableAgent( - gatewayName, - qualifyHermesPortableOperatingCommandAuthority(sandboxName), - ); - }); - // Waiting and post-command cleanup must run outside both the lifecycle fence - // and its async context, so cleanup can acquire fresh authority after exit. - await started.finish(); + acceptedHermesAuthority.command.assertCurrent(); + return startHermesPortableAgent(gatewayName, acceptedHermesAuthority.command); + } + const recovery = recoverPortableDemoSandboxLifecycleForConnect( + sandboxName, + registered, + gatewayName, + ); + if (recovery.kind === "not-installed") { + throw new Error("Hermes portable lifecycle authority disappeared before agent launch."); + } + const finalReceipt = inspectPortableAgentReceiptDisposition(sandboxName); + const finalRegistered = readSandbox(sandboxName); + if ( + finalReceipt.kind !== "hermes" || + finalReceipt.phase !== "active" || + !finalRegistered || + finalRegistered.agent !== "hermes" || + finalRegistered.gatewayName !== registered.gatewayName || + finalRegistered.lifecycleGeneration !== registered.lifecycleGeneration || + finalRegistered.lifecycleLiveIdentityFingerprint !== + registered.lifecycleLiveIdentityFingerprint || + finalRegistered.openshellDriver !== registered.openshellDriver || + finalRegistered.openshellVersion !== registered.openshellVersion || + finalReceipt.gatewayName !== registered.gatewayName || + finalReceipt.lifecycleGeneration !== registered.lifecycleGeneration || + finalReceipt.liveIdentityFingerprint !== registered.lifecycleLiveIdentityFingerprint + ) { + throw new Error("Hermes portable lifecycle authority changed at agent launch."); + } + return startHermesPortableAgent( + gatewayName, + qualifyHermesPortableOperatingCommandAuthority(sandboxName), + ); } export async function launchSandbox( sandboxName: string, deps: LaunchSandboxDeps = {}, ): Promise { + const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock; + const started = await lockSandbox(sandboxName, () => prepareLaunchSession(sandboxName, deps)); + // Completion runs outside the lock's async context; cleanup acquires fresh authority. + await started.finish(); +} + +async function prepareLaunchSession( + sandboxName: string, + deps: LaunchSandboxDeps, +): Promise<{ finish: () => Promise }> { const launchTiming = createLaunchPreExecTiming(deps); const enterMutationGate = deps.withLaunchReadinessMutationGate ?? withLaunchReadinessMutationGate; let inspection = await inspectLaunchReadinessForLaunch(sandboxName, deps); @@ -487,7 +492,7 @@ export async function launchSandbox( // agent under a different auth mode than `connect` gives it, so `-l` is // load-bearing: do not flatten this to `bash -c` or to the split command. const command = ["bash", "-lc", agentCommand]; - await launchAgentWithPortableAuthority( + return startAgentWithPortableAuthority( sandboxName, agent, sb, From d4cb5e738c39d8d6e8e88597a65d3abcd7eb5ab9 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sun, 13 Sep 2026 02:11:50 -0700 Subject: [PATCH 06/12] fix(lifecycle): recheck migration state under launch authority Signed-off-by: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> --- src/lib/actions/sandbox/launch.ts | 2 + src/lib/cli/nemoclaw-oclif-command.test.ts | 60 ++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts index 8042e1ea08d..ff93f0e0160 100644 --- a/src/lib/actions/sandbox/launch.ts +++ b/src/lib/actions/sandbox/launch.ts @@ -14,6 +14,7 @@ import { import { resolveSandboxGatewayName } from "../../gateway-runtime-action"; import { emitPortableOpenClawAlreadyRunningTiming } from "../../onboard/experimental/portable-demo-lifecycle-timing"; import type { SandboxEntry } from "../../state/registry"; +import { enforceRemovedImmutabilityMigrationBoundary } from "../../state/migrations/removed-immutability"; import { completeReadinessQualifiedInteractiveSessionSetup, prepareInteractiveSession, @@ -382,6 +383,7 @@ async function prepareLaunchSession( sandboxName: string, deps: LaunchSandboxDeps, ): Promise<{ finish: () => Promise }> { + enforceRemovedImmutabilityMigrationBoundary(sandboxName); const launchTiming = createLaunchPreExecTiming(deps); const enterMutationGate = deps.withLaunchReadinessMutationGate ?? withLaunchReadinessMutationGate; let inspection = await inspectLaunchReadinessForLaunch(sandboxName, deps); diff --git a/src/lib/cli/nemoclaw-oclif-command.test.ts b/src/lib/cli/nemoclaw-oclif-command.test.ts index 0d473f2f4fb..30b9dbd08de 100644 --- a/src/lib/cli/nemoclaw-oclif-command.test.ts +++ b/src/lib/cli/nemoclaw-oclif-command.test.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { Args, Flags } from "@oclif/core"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { launchSandbox } from "../actions/sandbox/launch"; import * as portableAgentLifecycle from "../onboard/experimental/portable-agent-lifecycle"; import * as receiptAuthority from "../onboard/experimental/hermes-portable-receipt"; import * as portableHostAuthority from "../state/portable-uninstall-retirement"; @@ -163,10 +164,12 @@ class PortableLaunchCommand extends NemoClawCommand { static args = { sandboxName: Args.string({ required: true }) }; static flags = {}; static observed = { host: false, lifecycle: false, portableLifecycle: false }; + static operation: (sandboxName: string) => Promise = async () => undefined; public async run(): Promise { const { args } = await this.parse(PortableLaunchCommand); PortableLaunchCommand.observed = observeLifecycleAuthority(args.sandboxName!); + await PortableLaunchCommand.operation(args.sandboxName!); } } @@ -242,6 +245,7 @@ describe("NemoClawCommand", () => { ProbeOnlyConnectCommand.operation = () => undefined; PortableStartCommand.observed = { host: false, lifecycle: false, portableLifecycle: false }; PortableLaunchCommand.observed = { host: false, lifecycle: false, portableLifecycle: false }; + PortableLaunchCommand.operation = async () => undefined; PortableStopCommand.observed = { host: false, lifecycle: false, portableLifecycle: false }; }); @@ -412,6 +416,62 @@ describe("NemoClawCommand", () => { }); }); + it.each([ + { record: "shields-alpha.json", error: /mutable posture cannot be proven/u }, + { record: "shields-timer-alpha.json", error: /recovery artifacts from the removed Shields/u }, + ])( + "rejects launch when $record appears while its action waits for authority (#11647)", + async ({ record, error }) => { + let acquired!: () => void; + const mutationStarted = new Promise((resolve) => { + acquired = resolve; + }); + let waiting!: () => void; + const launchWaiting = new Promise((resolve) => { + waiting = resolve; + }); + let update!: () => void; + const publishRecord = new Promise((resolve) => { + update = resolve; + }); + const inspect = vi.fn(async () => { + throw new Error("readiness reached before migration rejection"); + }); + PortableLaunchCommand.operation = (sandboxName) => + launchSandbox(sandboxName, { + inspectLaunchReadiness: inspect, + withSandboxMutationLock: (name, operation) => { + waiting(); + return withMcpLifecycleLock(name, operation, { stateDir }); + }, + }); + const recordPath = path.join(stateDir, record); + const mutation = withMcpLifecycleLock( + "alpha", + async () => { + acquired(); + await publishRecord; + fs.writeFileSync(recordPath, "legacy state\n"); + }, + { stateDir }, + ); + try { + await mutationStarted; + const launch = PortableLaunchCommand.run(["alpha"], process.cwd()); + const rejected = expect(launch).rejects.toThrow(error); + await launchWaiting; + update(); + await Promise.all([mutation, rejected]); + expect(inspect).not.toHaveBeenCalled(); + expect(fs.readFileSync(recordPath, "utf8")).toBe("legacy state\n"); + expect(isMcpLifecycleLockHeld("alpha", stateDir)).toBe(false); + } finally { + update(); + await mutation; + } + }, + ); + it("selects the gateway lifecycle lock under the host fence when there is no Hermes receipt", async () => { vi.stubEnv("HOME", stateDir); vi.stubEnv("NEMOCLAW_TEST_BASE_HOME", stateDir); From efae540cf5c1fa81763ffc59064df832817fab4d Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sun, 13 Sep 2026 02:54:15 -0700 Subject: [PATCH 07/12] fix(lifecycle): recheck migration before delayed launch cleanup Signed-off-by: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> --- src/lib/actions/sandbox/launch.test.ts | 32 ++++++++++++++++++++------ src/lib/actions/sandbox/launch.ts | 1 + 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/lib/actions/sandbox/launch.test.ts b/src/lib/actions/sandbox/launch.test.ts index 6759fecff52..cd41acd1a02 100644 --- a/src/lib/actions/sandbox/launch.test.ts +++ b/src/lib/actions/sandbox/launch.test.ts @@ -1,7 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest"; import type { AgentDefinition } from "../../agent/defs"; import * as agentDefinitions from "../../agent/defs"; @@ -1287,13 +1291,25 @@ describe("launchSandbox", () => { }); it.each([ - { replacement: "unchanged", cleanupCount: 1 }, - { replacement: "metadata", cleanupCount: 1 }, - { replacement: "recreated", cleanupCount: 0 }, - { replacement: "removed", cleanupCount: 0 }, + { replacement: "unchanged", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" }, + { replacement: "metadata", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" }, + { replacement: "recreated", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" }, + { replacement: "removed", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" }, + { + replacement: "legacy-recovery", + cleanupCount: 0, + stateFile: "shields-timer-alpha.json", + error: /recovery artifacts from the removed Shields/u, + }, ])( "binds completion cleanup to the launched sandbox ($replacement)", - async ({ replacement, cleanupCount }) => { + async ({ replacement, cleanupCount, stateFile, error }) => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-cleanup-")); + onTestFinished(() => fs.rmSync(stateDir, { recursive: true, force: true })); + vi.stubEnv("HOME", stateDir); + vi.stubEnv("NEMOCLAW_TEST_BASE_HOME", stateDir); + vi.stubEnv("NEMOCLAW_TEST_STATE_DIR", stateDir); + const statePath = path.join(stateDir, stateFile); const { startSandboxExec } = await vi.importActual("./exec"); const agent = loadAgent("openclaw"); let current: SandboxEntry | null = sandboxEntry(agent.name); @@ -1335,9 +1351,10 @@ describe("launchSandbox", () => { getSandbox: () => current, withSandboxMutationLock: lock, }); - const completion = expect(launch).rejects.toThrow("exit:0"); + const completion = expect(launch).rejects.toThrow(error); await childStarted.promise; await lock("alpha", () => { + fs.writeFileSync(statePath, "recorded state\n"); current = replacement === "removed" ? null @@ -1355,6 +1372,7 @@ describe("launchSandbox", () => { await completion; expect(cleanup).toHaveBeenCalledTimes(cleanupCount); expect(release).toHaveBeenCalledOnce(); + expect(fs.readFileSync(statePath, "utf8")).toBe("recorded state\n"); expect(events).toEqual( cleanupCount === 1 ? ["sandbox:acquired", "cleanup", "sandbox:released"] diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts index ff93f0e0160..e3680272427 100644 --- a/src/lib/actions/sandbox/launch.ts +++ b/src/lib/actions/sandbox/launch.ts @@ -249,6 +249,7 @@ async function startAgentWithPortableAuthority( { withCleanupAuthority: (cleanup) => lockSandbox(sandboxName, () => { + enforceRemovedImmutabilityMigrationBoundary(sandboxName); const current = readSandbox(sandboxName); if ( !launchedEntry || From af084748cab3304b2bac7a3f29ed1ad76373fe53 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sun, 13 Sep 2026 03:20:51 -0700 Subject: [PATCH 08/12] test: verify launch rejection releases lifecycle authority Signed-off-by: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> --- src/lib/actions/sandbox/launch.ts | 2 +- src/lib/cli/nemoclaw-oclif-command.test.ts | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts index e3680272427..dae3c20f06a 100644 --- a/src/lib/actions/sandbox/launch.ts +++ b/src/lib/actions/sandbox/launch.ts @@ -486,7 +486,7 @@ async function prepareLaunchSession( // part of prepareInteractiveSession, so `launch` must call it too: without it // a Hermes TUI on a light-background terminal keeps the default dark skin, // and a switch back to a dark terminal never removes the managed skin. - // Run the agent through a login shell. execSandbox wraps every command in + // Run the agent through a login shell. startSandboxExec wraps every command in // wrapExecCommandWithRuntimeEnv (runtime-env.ts), which sources // /tmp/nemoclaw-proxy-env.sh and then unsets OPENCLAW_GATEWAY_TOKEN so // ordinary caller argv cannot inherit it (#6291). The SSH path that diff --git a/src/lib/cli/nemoclaw-oclif-command.test.ts b/src/lib/cli/nemoclaw-oclif-command.test.ts index 30b9dbd08de..d7d5049009f 100644 --- a/src/lib/cli/nemoclaw-oclif-command.test.ts +++ b/src/lib/cli/nemoclaw-oclif-command.test.ts @@ -464,7 +464,12 @@ describe("NemoClawCommand", () => { await Promise.all([mutation, rejected]); expect(inspect).not.toHaveBeenCalled(); expect(fs.readFileSync(recordPath, "utf8")).toBe("legacy state\n"); - expect(isMcpLifecycleLockHeld("alpha", stateDir)).toBe(false); + const reacquired = await withMcpLifecycleLock( + "alpha", + () => isMcpLifecycleLockHeld("alpha", stateDir), + { stateDir, timeoutMs: 1000 }, + ); + expect(reacquired).toBe(true); } finally { update(); await mutation; From e3a5c06178e8e810e5f3f7a0baa1856be396dcb4 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sun, 13 Sep 2026 03:54:45 -0700 Subject: [PATCH 09/12] fix(launch): reject sessions without cleanup identity Signed-off-by: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> --- src/lib/actions/sandbox/launch.test.ts | 70 ++++++++++++++++++-------- src/lib/actions/sandbox/launch.ts | 12 ++++- 2 files changed, 59 insertions(+), 23 deletions(-) diff --git a/src/lib/actions/sandbox/launch.test.ts b/src/lib/actions/sandbox/launch.test.ts index cd41acd1a02..eda0e10100d 100644 --- a/src/lib/actions/sandbox/launch.test.ts +++ b/src/lib/actions/sandbox/launch.test.ts @@ -1121,28 +1121,56 @@ describe("launchSandbox", () => { expect(mocks.startSandboxExec).toHaveBeenCalled(); }); - it("runs the complete preflight and interactive command when macOS evidence is unavailable (#8942)", async () => { - mocks.inspectLaunchReadiness.mockResolvedValue({ - kind: "fallback", - category: "unsafe", - fence: null, - gatewayName: "nemoclaw", - gatewayPort: 8080, - fenceFailed: true, - recoveryBlocked: false, - authorityUnsupported: true, - }); - - await expect(launchSandbox("alpha")).resolves.toBeUndefined(); + it.each([ + ["current", {}, 1], + ["missing generation", { lifecycleGeneration: undefined }, 0], + ["missing live identity", { lifecycleLiveIdentityFingerprint: undefined }, 0], + [ + "missing both", + { lifecycleGeneration: undefined, lifecycleLiveIdentityFingerprint: undefined }, + 0, + ], + ])( + "checks %s cleanup identity when macOS evidence is unavailable (#8942, #11647)", + async (_label, identity, dispatchCount) => { + const agent = loadAgent("openclaw"); + const entry = { ...sandboxEntry(agent.name), ...identity }; + const before = structuredClone(entry); + mocks.inspectLaunchReadiness.mockResolvedValue({ + kind: "fallback", + category: "unsafe", + fence: null, + gatewayName: "nemoclaw", + gatewayPort: 8080, + fenceFailed: true, + recoveryBlocked: false, + authorityUnsupported: true, + }); + mocks.prepareInteractiveSession.mockResolvedValue({ + agent, + sb: entry, + hermesPortable: false, + }); - expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce(); - expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled(); - expect(mocks.withLaunchReadinessMutationGate).toHaveBeenCalledWith( - expect.objectContaining({ epochId: null }), - expect.any(Function), - ); - expect(mocks.startSandboxExec).toHaveBeenCalledOnce(); - }); + const result = await launchSandbox("alpha", { getSandbox: () => entry }).catch( + (error: Error) => error.message, + ); + expect(result).toEqual( + dispatchCount === 1 + ? undefined + : expect.stringMatching(/lifecycle identity.*sandbox doctor.*onboarding/u), + ); + expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce(); + expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled(); + expect(mocks.withLaunchReadinessMutationGate).toHaveBeenCalledWith( + expect.objectContaining({ epochId: null }), + expect.any(Function), + ); + expect(mocks.startSandboxExec).toHaveBeenCalledTimes(dispatchCount); + expect(mocks.startSandboxSession).not.toHaveBeenCalled(); + expect(entry).toEqual(before); + }, + ); it("stops before the complete preflight when a prior launch-readiness epoch may remain acceptable (#8942)", async () => { mocks.inspectLaunchReadiness.mockResolvedValue({ diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts index dae3c20f06a..7eb7bdbca92 100644 --- a/src/lib/actions/sandbox/launch.ts +++ b/src/lib/actions/sandbox/launch.ts @@ -238,10 +238,18 @@ async function startAgentWithPortableAuthority( ): Promise<{ finish: () => Promise }> { const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock; const startOrdinaryAgent = async (): Promise<{ finish: () => Promise }> => { - prepareHermesLightTerminalSkin(sandboxName, agent, process.env); - beforeAgentExec?.(); const readSandbox = deps.getSandbox ?? getKnownSandboxTarget; const launchedEntry = structuredClone(readSandbox(sandboxName)); + if ( + launchedEntry?.agent === "openclaw" && + (!launchedEntry.lifecycleGeneration || !launchedEntry.lifecycleLiveIdentityFingerprint) + ) { + throw new Error( + `Cannot safely clean up an interactive OpenClaw launch for sandbox '${sandboxName}' because its lifecycle identity is incomplete. Run the sandbox doctor to inspect the registration, then create a new sandbox through onboarding before launching.`, + ); + } + prepareHermesLightTerminalSkin(sandboxName, agent, process.env); + beforeAgentExec?.(); const finish = await startSandboxExec( sandboxName, command, From a18063a76b6acd22746475f68b053b9479e85d63 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sun, 13 Sep 2026 04:30:26 -0700 Subject: [PATCH 10/12] fix: preserve legacy launch cleanup with live identity Signed-off-by: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> --- .../actions/sandbox/launch-cleanup.test.ts | 238 ++++++++++++++++++ src/lib/actions/sandbox/launch.test.ts | 124 +-------- src/lib/actions/sandbox/launch.ts | 31 ++- 3 files changed, 275 insertions(+), 118 deletions(-) create mode 100644 src/lib/actions/sandbox/launch-cleanup.test.ts diff --git a/src/lib/actions/sandbox/launch-cleanup.test.ts b/src/lib/actions/sandbox/launch-cleanup.test.ts new file mode 100644 index 00000000000..87e20ef0ee4 --- /dev/null +++ b/src/lib/actions/sandbox/launch-cleanup.test.ts @@ -0,0 +1,238 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; +import { loadAgent } from "../../agent/defs"; +import type { SandboxEntry } from "../../state/registry"; +import { launchSandbox } from "./launch"; + +const mocks = vi.hoisted(() => ({ startSandboxExec: vi.fn() })); +vi.mock("./exec", () => ({ startSandboxExec: mocks.startSandboxExec })); +vi.mock("./connect", () => ({ + printInteractiveSessionHints: vi.fn(), + completeReadinessQualifiedInteractiveSessionSetup: vi.fn(), +})); +vi.mock("./connect-hermes-light-skin", () => ({ prepareHermesLightTerminalSkin: vi.fn() })); +vi.mock("./gateway-state", async (original) => ({ + ...(await original()), + inspectPortableAgentReceiptDisposition: () => ({ kind: "absent" }), +})); + +function deferred(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +function createSerialTestLock( + events: string[], + label: string, +): (name: string, operation: () => Promise | T) => Promise { + let tail = Promise.resolve(); + return async (_name: string, operation: () => Promise | T): Promise => { + const previous = tail; + const release = deferred(); + tail = previous.then(() => release.promise); + await previous; + events.push(`${label}:acquired`); + try { + return await operation(); + } finally { + events.push(`${label}:released`); + release.resolve(); + } + }; +} + +describe("interactive launch cleanup", () => { + afterEach(() => vi.unstubAllEnvs()); + it.each([ + { replacement: "unchanged", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" }, + { replacement: "legacy", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" }, + { + replacement: "legacy-replaced", + cleanupCount: 0, + stateFile: "unrelated.json", + error: "exit:0", + }, + { + replacement: "legacy-missing", + cleanupCount: 0, + stateFile: "unrelated.json", + error: "exit:0", + }, + { + replacement: "legacy-unavailable", + cleanupCount: 0, + stateFile: "unrelated.json", + error: "probe unavailable", + }, + { replacement: "gateway-moved", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" }, + { replacement: "metadata", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" }, + { replacement: "recreated", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" }, + { replacement: "removed", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" }, + { + replacement: "legacy-recovery", + cleanupCount: 0, + stateFile: "shields-timer-alpha.json", + error: /recovery artifacts from the removed Shields/u, + }, + ])( + "binds completion cleanup to the launched sandbox ($replacement)", + async ({ replacement, cleanupCount, stateFile, error }) => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-cleanup-")); + onTestFinished(() => fs.rmSync(stateDir, { recursive: true, force: true })); + vi.stubEnv("HOME", stateDir); + vi.stubEnv("NEMOCLAW_TEST_BASE_HOME", stateDir); + vi.stubEnv("NEMOCLAW_TEST_STATE_DIR", stateDir); + const statePath = path.join(stateDir, stateFile); + const { startSandboxExec } = await vi.importActual("./exec"); + const agent = loadAgent("openclaw"); + const legacy = ["legacy", "legacy-replaced", "legacy-missing", "legacy-unavailable"].includes( + replacement, + ); + let current: SandboxEntry | null = { + ...({ name: "alpha", agent: agent.name } as SandboxEntry), + gatewayName: "nemoclaw-8081", + lifecycleGeneration: legacy ? undefined : "generation-alpha", + lifecycleLiveIdentityFingerprint: legacy ? undefined : "f".repeat(64), + }; + let liveIdentityFingerprint: string | null = "f".repeat(64); + const sessionEnded = deferred(); + const childStarted = deferred(); + const events: string[] = []; + const lock = createSerialTestLock(events, "sandbox"); + const cleanup = vi.fn(() => { + events.push("cleanup"); + return { applies: true as const, ok: false, issues: ["config mode drift"] }; + }); + const repair = vi.fn(() => ({ applied: true as const, verified: true, errors: [] })); + const observeSandbox = vi.fn(() => { + events.push("identity"); + return { state: "ready" as const, liveIdentityFingerprint }; + }); + const release = vi.fn(); + mocks.startSandboxExec.mockImplementation((name, command, options, deps) => + startSandboxExec(name, command, options, { + ...deps, + selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), + commandExecutor: { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => { + childStarted.resolve(); + await sessionEnded.promise; + return { outcome: { kind: "completed", exitCode: 0 }, release }; + }, + }, + cleanupDeps: { + getSandbox: () => current, + inspectMutableConfigPerms: cleanup, + repairMutableConfigPerms: repair, + }, + exit: (code) => { + throw new Error(`exit:${code}`); + }, + }), + ); + const launch = launchSandbox("alpha", { + inspectLaunchReadiness: async () => ({ + kind: "accepted", + category: "accepted", + agent, + sb: current!, + }), + getSandbox: () => current, + observeSandbox, + withSandboxMutationLock: lock, + }); + const completion = expect(launch).rejects.toThrow(error); + await childStarted.promise; + await lock("alpha", () => { + fs.writeFileSync(statePath, "recorded state\n"); + current = + replacement === "removed" + ? null + : { + ...current!, + gatewayPort: replacement === "gateway-moved" ? 8082 : current!.gatewayPort, + model: replacement === "metadata" ? "updated-model" : current!.model, + lifecycleGeneration: + replacement === "recreated" ? "generation-new" : current!.lifecycleGeneration, + }; + liveIdentityFingerprint = + replacement === "legacy-missing" + ? null + : replacement === "legacy-replaced" + ? "e".repeat(64) + : liveIdentityFingerprint; + observeSandbox.mockImplementation(() => { + events.push("identity"); + replacement !== "legacy-unavailable" || + (() => { + throw new Error("probe unavailable"); + })(); + return { state: "ready" as const, liveIdentityFingerprint }; + }); + events.push("replacement-observed"); + }); + expect(cleanup).not.toHaveBeenCalled(); + events.length = 0; + sessionEnded.resolve(); + await completion; + expect(cleanup).toHaveBeenCalledTimes(cleanupCount); + expect(repair).toHaveBeenCalledTimes(cleanupCount); + expect(observeSandbox).toHaveBeenCalledTimes(legacy ? 2 : 0); + expect(release).toHaveBeenCalledOnce(); + expect(fs.readFileSync(statePath, "utf8")).toBe("recorded state\n"); + expect(events).toEqual([ + "sandbox:acquired", + ...(legacy ? ["identity"] : []), + ...(cleanupCount === 1 ? ["cleanup"] : []), + "sandbox:released", + ]); + }, + ); + it.each([ + { state: "missing", liveIdentityFingerprint: null }, + { state: "not_ready", liveIdentityFingerprint: "f".repeat(64) }, + { state: "ready", liveIdentityFingerprint: null }, + ] as const)( + "stops before dispatch when legacy identity is unverified ($state)", + async (observation) => { + const entry = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw-8081", + } as SandboxEntry; + const events: string[] = []; + const observeSandbox = vi.fn(() => observation); + await expect( + launchSandbox("alpha", { + getSandbox: () => entry, + inspectLaunchReadiness: async () => ({ + kind: "accepted", + category: "accepted", + agent: loadAgent("openclaw"), + sb: entry, + }), + withSandboxMutationLock: createSerialTestLock(events, "sandbox"), + observeSandbox, + }), + ).rejects.toThrow(/Cannot verify the live identity.*sandbox doctor/u); + expect(observeSandbox).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, + }), + ); + expect(mocks.startSandboxExec).not.toHaveBeenCalled(); + expect(events).toEqual(["sandbox:acquired", "sandbox:released"]); + }, + ); +}); diff --git a/src/lib/actions/sandbox/launch.test.ts b/src/lib/actions/sandbox/launch.test.ts index eda0e10100d..30aca458062 100644 --- a/src/lib/actions/sandbox/launch.test.ts +++ b/src/lib/actions/sandbox/launch.test.ts @@ -1,11 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { AgentDefinition } from "../../agent/defs"; import * as agentDefinitions from "../../agent/defs"; @@ -1122,19 +1118,18 @@ describe("launchSandbox", () => { }); it.each([ - ["current", {}, 1], - ["missing generation", { lifecycleGeneration: undefined }, 0], - ["missing live identity", { lifecycleLiveIdentityFingerprint: undefined }, 0], + ["current", {}], + ["missing generation", { lifecycleGeneration: undefined }], + ["missing live identity", { lifecycleLiveIdentityFingerprint: undefined }], [ "missing both", { lifecycleGeneration: undefined, lifecycleLiveIdentityFingerprint: undefined }, - 0, ], ])( "checks %s cleanup identity when macOS evidence is unavailable (#8942, #11647)", - async (_label, identity, dispatchCount) => { + async (_label, identity) => { const agent = loadAgent("openclaw"); - const entry = { ...sandboxEntry(agent.name), ...identity }; + const entry = { ...sandboxEntry(agent.name), gatewayName: "nemoclaw-8081", ...identity }; const before = structuredClone(entry); mocks.inspectLaunchReadiness.mockResolvedValue({ kind: "fallback", @@ -1152,21 +1147,19 @@ describe("launchSandbox", () => { hermesPortable: false, }); - const result = await launchSandbox("alpha", { getSandbox: () => entry }).catch( - (error: Error) => error.message, - ); - expect(result).toEqual( - dispatchCount === 1 - ? undefined - : expect.stringMatching(/lifecycle identity.*sandbox doctor.*onboarding/u), - ); + await expect( + launchSandbox("alpha", { + getSandbox: () => entry, + observeSandbox: () => ({ state: "ready", liveIdentityFingerprint: "f".repeat(64) }), + }), + ).resolves.toBeUndefined(); expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce(); expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled(); expect(mocks.withLaunchReadinessMutationGate).toHaveBeenCalledWith( expect.objectContaining({ epochId: null }), expect.any(Function), ); - expect(mocks.startSandboxExec).toHaveBeenCalledTimes(dispatchCount); + expect(mocks.startSandboxExec).toHaveBeenCalledOnce(); expect(mocks.startSandboxSession).not.toHaveBeenCalled(); expect(entry).toEqual(before); }, @@ -1318,97 +1311,6 @@ describe("launchSandbox", () => { ).toEqual(["readiness", "dispatch", "contender"]); }); - it.each([ - { replacement: "unchanged", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" }, - { replacement: "metadata", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" }, - { replacement: "recreated", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" }, - { replacement: "removed", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" }, - { - replacement: "legacy-recovery", - cleanupCount: 0, - stateFile: "shields-timer-alpha.json", - error: /recovery artifacts from the removed Shields/u, - }, - ])( - "binds completion cleanup to the launched sandbox ($replacement)", - async ({ replacement, cleanupCount, stateFile, error }) => { - const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-cleanup-")); - onTestFinished(() => fs.rmSync(stateDir, { recursive: true, force: true })); - vi.stubEnv("HOME", stateDir); - vi.stubEnv("NEMOCLAW_TEST_BASE_HOME", stateDir); - vi.stubEnv("NEMOCLAW_TEST_STATE_DIR", stateDir); - const statePath = path.join(stateDir, stateFile); - const { startSandboxExec } = await vi.importActual("./exec"); - const agent = loadAgent("openclaw"); - let current: SandboxEntry | null = sandboxEntry(agent.name); - prepareSession(agent.name, agent); - const sessionEnded = deferred(); - const childStarted = deferred(); - const events: string[] = []; - const lock = createSerialTestLock(events, "sandbox"); - const cleanup = vi.fn(() => { - events.push("cleanup"); - return { applies: true as const, ok: true, issues: [] }; - }); - const release = vi.fn(); - mocks.startSandboxExec.mockImplementation((name, command, options, deps) => - startSandboxExec(name, command, options, { - ...deps, - selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), - commandExecutor: { - probeDirectory: async () => ({ state: "present" }), - runStreaming: async () => { - childStarted.resolve(); - await sessionEnded.promise; - return { outcome: { kind: "completed", exitCode: 0 }, release }; - }, - }, - cleanupDeps: { - getSandbox: () => current, - inspectMutableConfigPerms: cleanup, - repairMutableConfigPerms: () => { - throw new Error("unexpected repair"); - }, - }, - exit: (code) => { - throw new Error(`exit:${code}`); - }, - }), - ); - const launch = launchSandbox("alpha", { - getSandbox: () => current, - withSandboxMutationLock: lock, - }); - const completion = expect(launch).rejects.toThrow(error); - await childStarted.promise; - await lock("alpha", () => { - fs.writeFileSync(statePath, "recorded state\n"); - current = - replacement === "removed" - ? null - : { - ...current!, - model: replacement === "metadata" ? "updated-model" : current!.model, - lifecycleGeneration: - replacement === "recreated" ? "generation-new" : "generation-alpha", - }; - events.push("replacement-observed"); - }); - expect(cleanup).not.toHaveBeenCalled(); - events.length = 0; - sessionEnded.resolve(); - await completion; - expect(cleanup).toHaveBeenCalledTimes(cleanupCount); - expect(release).toHaveBeenCalledOnce(); - expect(fs.readFileSync(statePath, "utf8")).toBe("recorded state\n"); - expect(events).toEqual( - cleanupCount === 1 - ? ["sandbox:acquired", "cleanup", "sandbox:released"] - : ["sandbox:acquired", "sandbox:released"], - ); - }, - ); - it.each([ { scenario: "hermes-accepted", diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts index 7eb7bdbca92..e05d566f2f5 100644 --- a/src/lib/actions/sandbox/launch.ts +++ b/src/lib/actions/sandbox/launch.ts @@ -13,6 +13,10 @@ import { } from "../../adapters/openshell/sandbox-command-cli"; import { resolveSandboxGatewayName } from "../../gateway-runtime-action"; import { emitPortableOpenClawAlreadyRunningTiming } from "../../onboard/experimental/portable-demo-lifecycle-timing"; +import { + observeSandboxOnGateway, + type SandboxRecreateObserver, +} from "../../onboard/sandbox-recreate-probe"; import type { SandboxEntry } from "../../state/registry"; import { enforceRemovedImmutabilityMigrationBoundary } from "../../state/migrations/removed-immutability"; import { @@ -34,7 +38,7 @@ import { type HermesPortableActiveLifecycleAuthority, withSandboxLifecycleLock as withSandboxMutationLock, } from "./gateway-state"; -import { getKnownSandboxTarget } from "./gateway-target"; +import { getKnownSandboxTarget, getPersistedSandboxTargetGateway } from "./gateway-target"; import { createBoundLaunchReadinessDeps, inspectLaunchReadiness, @@ -59,6 +63,7 @@ const sandboxCommandExecutor = createCliOpenShellSandboxCommandExecutor({ */ interface LaunchSandboxDeps { getSandbox?: typeof getKnownSandboxTarget; + observeSandbox?: SandboxRecreateObserver; resolveSandboxGatewayName?: typeof resolveSandboxGatewayName; withSandboxMutationLock?: typeof withSandboxMutationLock; inspectLaunchReadiness?: typeof inspectLaunchReadiness; @@ -240,12 +245,19 @@ async function startAgentWithPortableAuthority( const startOrdinaryAgent = async (): Promise<{ finish: () => Promise }> => { const readSandbox = deps.getSandbox ?? getKnownSandboxTarget; const launchedEntry = structuredClone(readSandbox(sandboxName)); - if ( - launchedEntry?.agent === "openclaw" && + const legacyTarget = + launchedEntry && + (launchedEntry.agent ?? "openclaw") === "openclaw" && (!launchedEntry.lifecycleGeneration || !launchedEntry.lifecycleLiveIdentityFingerprint) - ) { + ? { sandboxName, ...getPersistedSandboxTargetGateway(launchedEntry) } + : null; + const observeSandbox = deps.observeSandbox ?? observeSandboxOnGateway; + // Older registrations have no recorded identity. Bind cleanup to the live ID + // without changing their registration or requiring a sandbox replacement. + const launchedLive = legacyTarget ? observeSandbox(legacyTarget) : null; + if (launchedLive && (launchedLive.state !== "ready" || !launchedLive.liveIdentityFingerprint)) { throw new Error( - `Cannot safely clean up an interactive OpenClaw launch for sandbox '${sandboxName}' because its lifecycle identity is incomplete. Run the sandbox doctor to inspect the registration, then create a new sandbox through onboarding before launching.`, + `Cannot verify the live identity of sandbox '${sandboxName}' before launch. Run the sandbox doctor and retry.`, ); } prepareHermesLightTerminalSkin(sandboxName, agent, process.env); @@ -264,13 +276,18 @@ async function startAgentWithPortableAuthority( !current || current.agent !== launchedEntry.agent || current.gatewayName !== launchedEntry.gatewayName || - !launchedEntry.lifecycleGeneration || - !launchedEntry.lifecycleLiveIdentityFingerprint || + current.gatewayPort !== launchedEntry.gatewayPort || current.lifecycleGeneration !== launchedEntry.lifecycleGeneration || current.lifecycleLiveIdentityFingerprint !== launchedEntry.lifecycleLiveIdentityFingerprint ) return null; + if ( + legacyTarget && + observeSandbox(legacyTarget).liveIdentityFingerprint !== + launchedLive?.liveIdentityFingerprint + ) + return null; return cleanup(); }), }, From 85c13a3ff11dbc350b11378a366ef78d368bd5cf Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sun, 13 Sep 2026 04:57:45 -0700 Subject: [PATCH 11/12] fix: report deferred cleanup authority failures Signed-off-by: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> --- src/lib/actions/sandbox/exec.test.ts | 71 +++++++++++++++++++ src/lib/actions/sandbox/exec.ts | 10 ++- .../actions/sandbox/launch-cleanup.test.ts | 14 +++- 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/src/lib/actions/sandbox/exec.test.ts b/src/lib/actions/sandbox/exec.test.ts index eb4e9d9dc1b..e0f7c63e5d1 100644 --- a/src/lib/actions/sandbox/exec.test.ts +++ b/src/lib/actions/sandbox/exec.test.ts @@ -325,6 +325,77 @@ describe("execSandbox scope-upgrade hint wiring (#9744)", () => { }); }); +it.each([ + { mode: "sync", error: new Error("lock timed out"), commandCode: 0, invocationFailed: false }, + { + mode: "async", + error: new Error("migration blocked"), + commandCode: 23, + invocationFailed: false, + }, + { mode: "async", error: "registry unavailable", commandCode: 1, invocationFailed: true }, +])( + "reports $mode cleanup authority failure after command status $commandCode (#11647)", + async ({ mode, error, commandCode, invocationFailed }) => { + const stderr = vi.spyOn(console, "error").mockImplementation(() => {}); + const release = vi.fn(); + const inspect = vi.fn(() => ({ applies: true as const, ok: true, issues: [] })); + const exit = vi.fn((code: number): never => { + throw new Error(`exit:${code}`); + }); + try { + const finish = await startSandboxExec( + "alpha", + ["true"], + {}, + { + selectGateway: () => ({ outcome: "unregistered", gatewayName: null }), + commandExecutor: { + probeDirectory: async () => ({ state: "present" }), + runStreaming: async () => ({ + outcome: invocationFailed + ? { kind: "failed", error: { kind: "invocation", message: "transport failed" } } + : { kind: "completed", exitCode: commandCode }, + release, + }), + }, + withCleanupAuthority: + mode === "sync" + ? () => { + throw error; + } + : () => Promise.reject(error), + cleanupDeps: { + getSandbox: () => ({ agent: "openclaw" }), + inspectMutableConfigPerms: inspect, + repairMutableConfigPerms: () => ({ applied: true, verified: true, errors: [] }), + }, + policyHint: { + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + }, + exit, + }, + ); + await expect(finish()).rejects.toThrow("exit:1"); + expect(exit).toHaveBeenCalledExactlyOnceWith(1); + expect(stderr).toHaveBeenCalledWith( + ` OpenClaw permission cleanup failed (command exit ${commandCode}; cleanup exit 1): cleanup authority unavailable: ${error instanceof Error ? error.message : error}`, + ); + expect( + stderr.mock.calls.filter(([line]) => String(line).includes("Failed to invoke openshell")), + ).toHaveLength(invocationFailed ? 1 : 0); + expect(inspect).not.toHaveBeenCalled(); + expect(release).toHaveBeenCalledOnce(); + } finally { + stderr.mockRestore(); + } + }, +); + it( "releases authority to another process before interactive completion (#11647)", testTimeoutOptions(15_000), diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index 9bc7fbc2e12..5876562f7b5 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -193,8 +193,14 @@ async function finishSandboxExecRequest( const invocationError = completed.outcome.kind === "failed" ? completed.outcome.error.message : undefined; const cleanup = () => cleanupOpenClawAfterExec(request.sandboxName, cleanupDeps); - const cleanupError = - (await (withCleanupAuthority ? withCleanupAuthority(cleanup) : cleanup())) ?? undefined; + let cleanupError: string | undefined; + try { + cleanupError = + (await (withCleanupAuthority ? withCleanupAuthority(cleanup) : cleanup())) ?? undefined; + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + cleanupError = `cleanup authority unavailable: ${detail}`; + } return { code: cleanupError ? 1 : commandCode, commandCode, diff --git a/src/lib/actions/sandbox/launch-cleanup.test.ts b/src/lib/actions/sandbox/launch-cleanup.test.ts index 87e20ef0ee4..765e9409318 100644 --- a/src/lib/actions/sandbox/launch-cleanup.test.ts +++ b/src/lib/actions/sandbox/launch-cleanup.test.ts @@ -85,6 +85,8 @@ describe("interactive launch cleanup", () => { ])( "binds completion cleanup to the launched sandbox ($replacement)", async ({ replacement, cleanupCount, stateFile, error }) => { + const stderr = vi.spyOn(console, "error").mockImplementation(() => {}); + onTestFinished(() => stderr.mockRestore()); const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-cleanup-")); onTestFinished(() => fs.rmSync(stateDir, { recursive: true, force: true })); vi.stubEnv("HOME", stateDir); @@ -134,6 +136,13 @@ describe("interactive launch cleanup", () => { inspectMutableConfigPerms: cleanup, repairMutableConfigPerms: repair, }, + policyHint: { + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + }, exit: (code) => { throw new Error(`exit:${code}`); }, @@ -150,7 +159,7 @@ describe("interactive launch cleanup", () => { observeSandbox, withSandboxMutationLock: lock, }); - const completion = expect(launch).rejects.toThrow(error); + const completion = expect(launch).rejects.toThrow(error === "exit:0" ? error : "exit:1"); await childStarted.promise; await lock("alpha", () => { fs.writeFileSync(statePath, "recorded state\n"); @@ -184,6 +193,9 @@ describe("interactive launch cleanup", () => { events.length = 0; sessionEnded.resolve(); await completion; + expect(stderr.mock.calls.map(([line]) => line)).toEqual( + error === "exit:0" ? [] : [expect.stringMatching(error)], + ); expect(cleanup).toHaveBeenCalledTimes(cleanupCount); expect(repair).toHaveBeenCalledTimes(cleanupCount); expect(observeSandbox).toHaveBeenCalledTimes(legacy ? 2 : 0); From 08d23c8df09dfa769a046929765d992c8ad18442 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> Date: Sun, 13 Sep 2026 05:35:20 -0700 Subject: [PATCH 12/12] docs: explain legacy launch identity recovery Signed-off-by: Prekshi Vyas <34834085+prekshivyas@users.noreply.github.com> --- docs/reference/commands.mdx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 55ed8cdf82b..318f662d851 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1057,6 +1057,10 @@ The sandbox name is required, and the command takes no flags. The sandbox must a +For an older OpenClaw registration without recorded lifecycle identity, `launch` requires a ready live sandbox with an observable identity before it starts the agent. +If this identity check fails, `launch` stops before starting the agent. +Run `$$nemoclaw doctor`, resolve the reported issue, and retry `$$nemoclaw launch `. + `launch` returns the agent's exit code when the post-command OpenClaw permission cleanup succeeds. If that cleanup cannot inspect, restore, or verify the mutable config permission contract, `launch` fails closed with exit `1` and prints `OpenClaw permission cleanup failed (...)` to `stderr`.