From f3e22e10f1396085a6a7667496614a285d59447e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 13:08:03 -0700 Subject: [PATCH 01/44] test(e2e): recover native gateway through sandbox start Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/live/full-e2e.test.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index d4b96c46437..1ac03192c28 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -215,13 +215,20 @@ ${GATEWAY_STOP_SCRIPT}`), ).toBe(true); await sleep(3_000); - const recovery = await repoNemoclaw( + const stoppedStatus = await repoNemoclaw( input.host, [SANDBOX_NAME, "status"], - "phase-4-status-recover-before-launch", + "phase-4-status-after-native-gateway-exit", {}, 120_000, ); + const recovery = await repoNemoclaw( + input.host, + [SANDBOX_NAME, "start"], + "phase-4-start-after-native-gateway-exit", + {}, + 180_000, + ); const configEdit = !recovery.timedOut && recovery.exitCode === 0 && securityPostureEnabled() ? await repoNemoclaw( @@ -240,10 +247,16 @@ ${GATEWAY_STOP_SCRIPT}`), ) : null; expect( - !recovery.timedOut && + !stoppedStatus.timedOut && + stoppedStatus.exitCode !== 0 && + resultText(stoppedStatus).includes(`nemoclaw ${SANDBOX_NAME} start`) && + !recovery.timedOut && recovery.exitCode === 0 && (!configEdit || (!configEdit.timedOut && configEdit.exitCode === 0)), - resultText(configEdit ?? recovery), + [stoppedStatus, recovery, configEdit] + .filter((result) => result !== null) + .map(resultText) + .join("\n"), ).toBe(true); await runOpenClawLaunchReadinessLeaseTurns({ From 3a362d592ebfa336ced18ad8fdbd877c9ecab272 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 14:18:39 -0700 Subject: [PATCH 02/44] fix(status): recommend start for error-phase sandboxes Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/gateway-state-hints.test.ts | 7 +-- src/lib/actions/sandbox/gateway-state.ts | 16 +++++-- .../sandbox/status-lookup-rendering.test.ts | 46 +++++++++++-------- .../sandbox/status-lookup-rendering.ts | 20 +++++--- 4 files changed, 56 insertions(+), 33 deletions(-) diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index 6baf44f190a..7c3104e20cd 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -282,7 +282,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); - it("keeps rebuild guidance when an Error sandbox has no recoverable container", async () => { + it("steers an Error sandbox without a Docker container through OpenShell start", async () => { mockSandboxPhase("Error"); getSandboxDockerRuntimeSpy.mockReturnValue({ health: "none", @@ -303,8 +303,9 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { ); const output = lines.join("\n"); - expect(output).toContain("nemoclaw instance-a rebuild --yes"); - expect(output).not.toContain("nemoclaw instance-a start"); + expect(output).toContain("nemoclaw instance-a start"); + expect(output).toContain("restart the sandbox through OpenShell"); + expect(output).not.toContain("Run `nemoclaw instance-a rebuild --yes` to recreate"); expect(exitSpy).toHaveBeenCalledWith(1); }); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 22d63a1fc99..15978303945 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -1166,13 +1166,19 @@ export async function ensureLiveSandboxOrExit( " This usually happens when a process crash inside the sandbox prevented clean startup.", ); console.error(""); - if (phase === "Error" && dockerRuntime?.containerName) { + if (phase === "Error") { console.error( - ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the crashed container and recover the sandbox with workspace state preserved.`, - ); - console.error( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, but its pre-rebuild backup cannot snapshot a stopped container, so start it first.)`, + ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, ); + if (dockerRuntime.containerName) { + console.error( + ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, but its pre-rebuild backup cannot snapshot a stopped container, so start it first.)`, + ); + } else { + console.error( + ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, so use start first.)`, + ); + } } else { console.error( ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`, diff --git a/src/lib/actions/sandbox/status-lookup-rendering.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index d8d46a891cb..0e694c371a2 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -212,24 +212,34 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { expect(text).not.toContain("beta start"); }); - it.each([ - { phase: "Failed", containerName: "openshell-beta-abc" }, - { phase: "Error", containerName: null }, - ])( - "keeps rebuild guidance for $phase when start cannot recover the container", - async ({ phase, containerName }) => { - const cap = captureConsoleLog(); - await printGuidance({ - phase, - dockerRuntime: { health: "none", paused: false, running: true, containerName }, - }); - const text = cap.lines(); - cap.restore(); - - expect(text).toContain("nemoclaw beta rebuild --yes"); - expect(text).not.toContain("nemoclaw beta start"); - }, - ); + it("steers a provider without a Docker container to the OpenShell start path", async () => { + const cap = captureConsoleLog(); + await printGuidance({ phase: "Error", dockerRuntime: null }); + const text = cap.lines(); + cap.restore(); + + expect(text).toContain("nemoclaw beta start"); + expect(text).toContain("restart the sandbox through OpenShell"); + expect(text).not.toContain("Run `nemoclaw beta rebuild --yes` to recreate"); + }); + + it("keeps rebuild guidance for a terminal phase other than Error", async () => { + const cap = captureConsoleLog(); + await printGuidance({ + phase: "Failed", + dockerRuntime: { + health: "none", + paused: false, + running: true, + containerName: "openshell-beta-abc", + }, + }); + const text = cap.lines(); + cap.restore(); + + expect(text).toContain("nemoclaw beta rebuild --yes"); + expect(text).not.toContain("nemoclaw beta start"); + }); it("prints no guidance for a Ready sandbox", async () => { const cap = captureConsoleLog(); diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index ab2da223f46..ef66947297a 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -285,8 +285,8 @@ function printNonReadySandboxPhaseGuidance({ // toward rebuild is wrong because the sandbox is fine and rebuild cannot // succeed until Docker is back. Reclassify as a runtime outage first // (#4428). Terminal phases (Failed/Error/...) are settled sandbox - // failures and keep the existing rebuild guidance even when Docker is - // down, so a genuine failure is never masked. + // failures and remain actionable below even when Docker is down, so a + // genuine failure is never masked. if (!isTerminalSandboxPhase(phase) && isDockerRuntimeDown(sandboxName)) { console.log(""); printDockerRuntimeDownGuidance(sandboxName, { writer: console.log }); @@ -318,13 +318,19 @@ function printNonReadySandboxPhaseGuidance({ " This usually happens when a process crash inside the sandbox prevented clean startup.", ); console.log(""); - if (phase === "Error" && dockerRuntime?.containerName) { + if (phase === "Error") { console.log( - ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the crashed container and recover the sandbox with workspace state preserved.`, - ); - console.log( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, but its pre-rebuild backup cannot snapshot a stopped container, so start it first.)`, + ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, ); + if (dockerRuntime?.containerName) { + console.log( + ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, but its pre-rebuild backup cannot snapshot a stopped container, so start it first.)`, + ); + } else { + console.log( + ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, so use start first.)`, + ); + } return; } console.log( From de0125a5350061df5606933077a1347bd2c58ff5 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 14:44:51 -0700 Subject: [PATCH 03/44] test(e2e): cover portable gateway recovery guidance Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/support/full-e2e-gateway.test.ts | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/e2e/support/full-e2e-gateway.test.ts b/test/e2e/support/full-e2e-gateway.test.ts index 30251866c3c..833b293a5c8 100644 --- a/test/e2e/support/full-e2e-gateway.test.ts +++ b/test/e2e/support/full-e2e-gateway.test.ts @@ -5,6 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { printSandboxGatewayLookupStatus } from "../../../src/lib/actions/sandbox/status-lookup-rendering.ts"; import { fullE2eGateway } from "../fixtures/full-e2e-gateway.ts"; const directories: string[] = []; @@ -60,6 +61,35 @@ function declaration( } describe("full E2E gateway ownership", () => { + it("maps a native gateway exit to workspace-preserving OpenShell recovery", async () => { + const lines: string[] = []; + vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => { + lines.push(args.map(String).join(" ")); + }); + + await printSandboxGatewayLookupStatus({ + sandboxName: "nemoclaw-e2e", + registered: true, + lookup: { + state: "present", + output: "Sandbox:\n Name: nemoclaw-e2e\n Phase: Error", + }, + phase: "Error", + dockerRuntime: null, + effectivePreflight: { + failure: null, + failureLayer: null, + suppressInferenceProbe: false, + exitCode: 0, + }, + }); + + const guidance = lines.join("\n"); + expect(guidance).toContain("nemoclaw nemoclaw-e2e start"); + expect(guidance).toContain("workspace state preserved"); + expect(guidance).not.toContain("Run `nemoclaw nemoclaw-e2e rebuild --yes`"); + }); + it.each([ { preinstalled: true, targetId: "staging-brev-launchable", measuresColdOnboard: false }, { preinstalled: false, targetId: "staging-brev-launchable", measuresColdOnboard: false }, From 90b7690c1ba80e88c18696dd4dd604b10d4bc614 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 15:39:44 -0700 Subject: [PATCH 04/44] fix(status): clarify rebuild fallback guidance Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/sandbox/gateway-state-hints.test.ts | 2 ++ src/lib/actions/sandbox/gateway-state.ts | 12 +++--------- .../actions/sandbox/status-lookup-rendering.test.ts | 9 ++++----- src/lib/actions/sandbox/status-lookup-rendering.ts | 12 +++--------- 4 files changed, 12 insertions(+), 23 deletions(-) diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index 7c3104e20cd..4f128644ce7 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -277,6 +277,8 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { const output = lines.join("\n"); expect(output).toContain("nemoclaw instance-a start"); expect(output).toContain("workspace state preserved"); + expect(output).toContain("use it only if start does not recover the sandbox"); + expect(output).not.toContain("stopped container"); expect(output).not.toContain("docker unpause"); expect(getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("instance-a"); expect(exitSpy).toHaveBeenCalledWith(1); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 15978303945..c0f2eb3dc47 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -1170,15 +1170,9 @@ export async function ensureLiveSandboxOrExit( console.error( ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, ); - if (dockerRuntime.containerName) { - console.error( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, but its pre-rebuild backup cannot snapshot a stopped container, so start it first.)`, - ); - } else { - console.error( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, so use start first.)`, - ); - } + console.error( + ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead; use it only if start does not recover the sandbox.)`, + ); } else { console.error( ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`, diff --git a/src/lib/actions/sandbox/status-lookup-rendering.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index 0e694c371a2..4a6a5c7c25a 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -61,13 +61,12 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { // The recovery hint now leads with `start`, which recovers without data loss. expect(text).toContain("nemoclaw beta start"); expect(text).toContain("workspace state preserved"); - // `rebuild --yes` is only mentioned as the recreate alternative, and must no - // longer be the promised recovery command (its pre-rebuild backup aborts on a - // stopped container — the reported bug). + // `rebuild --yes` is only mentioned as the fallback recreate alternative, + // not as the promised recovery command. expect(text).not.toContain("Run `nemoclaw beta rebuild --yes` to recreate"); expect(text).not.toContain("workspace state will be preserved"); - // The `rebuild --yes` mention explains why `start` must come first. - expect(text).toContain("cannot snapshot a stopped container"); + expect(text).toContain("use it only if start does not recover the sandbox"); + expect(text).not.toContain("stopped container"); }); it("reports an owned stopped container without crash guidance (#8695)", async () => { diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index ef66947297a..18a682f4b65 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -322,15 +322,9 @@ function printNonReadySandboxPhaseGuidance({ console.log( ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, ); - if (dockerRuntime?.containerName) { - console.log( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, but its pre-rebuild backup cannot snapshot a stopped container, so start it first.)`, - ); - } else { - console.log( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, so use start first.)`, - ); - } + console.log( + ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead; use it only if start does not recover the sandbox.)`, + ); return; } console.log( From d520dd8cd3bfb3bc85d5b66330fc4162878eccf3 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 19:15:44 -0700 Subject: [PATCH 05/44] test(e2e): assert rebuild recovery guidance Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/support/full-e2e-gateway.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/e2e/support/full-e2e-gateway.test.ts b/test/e2e/support/full-e2e-gateway.test.ts index 833b293a5c8..72d1d8386bd 100644 --- a/test/e2e/support/full-e2e-gateway.test.ts +++ b/test/e2e/support/full-e2e-gateway.test.ts @@ -87,7 +87,7 @@ describe("full E2E gateway ownership", () => { const guidance = lines.join("\n"); expect(guidance).toContain("nemoclaw nemoclaw-e2e start"); expect(guidance).toContain("workspace state preserved"); - expect(guidance).not.toContain("Run `nemoclaw nemoclaw-e2e rebuild --yes`"); + expect(guidance).toContain("nemoclaw nemoclaw-e2e rebuild --yes"); }); it.each([ From 8df2490d9bd6cf7d2abaa7b3253d6a5d8a34e592 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:11:25 -0700 Subject: [PATCH 06/44] fix(e2e): prove native gateway recovery Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/gateway-state-hints.test.ts | 41 ++++++++++++++++++- src/lib/actions/sandbox/gateway-state.ts | 21 +++++++--- .../sandbox/status-lookup-rendering.test.ts | 19 ++++++++- .../sandbox/status-lookup-rendering.ts | 12 +++++- src/lib/actions/sandbox/status.ts | 1 + test/e2e/live/full-e2e.test.ts | 24 +++++++---- test/e2e/support/full-e2e-gateway.test.ts | 30 -------------- 7 files changed, 102 insertions(+), 46 deletions(-) diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index 4f128644ce7..35d013526d3 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -284,8 +284,47 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); - it("steers an Error sandbox without a Docker container through OpenShell start", async () => { + it("steers a Docker-driver Error sandbox without its container to rebuild", async () => { mockSandboxPhase("Error"); + getSandboxSpy.mockReturnValue({ + name: "instance-a", + gatewayName: "nemoclaw", + gatewayPort: 8080, + openshellDriver: "docker", + }); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: false, + running: true, + containerName: null, + }); + const lines: string[] = []; + vi.spyOn(console, "error").mockImplementation((line = "") => { + lines.push(String(line)); + }); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + + await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow( + "process.exit(1)", + ); + + const output = lines.join("\n"); + expect(output).toContain("nemoclaw instance-a rebuild --yes"); + expect(output).toContain("missing Docker-driver container"); + expect(output).not.toContain("nemoclaw instance-a start"); + expect(exitSpy).toHaveBeenCalledWith(1); + }); + + it("keeps OpenShell start guidance for a native Error sandbox without a Docker container", async () => { + mockSandboxPhase("Error"); + getSandboxSpy.mockReturnValue({ + name: "instance-a", + gatewayName: "nemoclaw", + gatewayPort: 8080, + openshellDriver: "mxc", + }); getSandboxDockerRuntimeSpy.mockReturnValue({ health: "none", paused: false, diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index c0f2eb3dc47..88a6e4ec0f8 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -1167,12 +1167,21 @@ export async function ensureLiveSandboxOrExit( ); console.error(""); if (phase === "Error") { - console.error( - ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, - ); - console.error( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead; use it only if start does not recover the sandbox.)`, - ); + if ( + getKnownSandboxTarget(sandboxName)?.openshellDriver === "docker" && + !dockerRuntime.containerName + ) { + console.error( + ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the missing Docker-driver container (--yes skips the confirmation prompt; workspace state will be preserved).`, + ); + } else { + console.error( + ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, + ); + console.error( + ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead; use it only if start does not recover the sandbox.)`, + ); + } } else { console.error( ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`, diff --git a/src/lib/actions/sandbox/status-lookup-rendering.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index 4a6a5c7c25a..ff64088e303 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -16,8 +16,10 @@ function captureConsoleLog(): { lines: () => string; restore: () => void } { async function printGuidance({ phase, dockerRuntime, + openshellDriver = "docker", }: { phase: string; + openshellDriver?: string; dockerRuntime: { health: "none"; paused: boolean; @@ -30,6 +32,7 @@ async function printGuidance({ registered: true, lookup: { state: "present", output: `Sandbox:\n Name: beta\n Phase: ${phase}` }, phase, + openshellDriver, dockerRuntime, effectivePreflight: { failure: null, @@ -115,6 +118,7 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { registered: true, lookup: { state: "missing", output: "sandbox beta not found" }, phase: "Stopped", + openshellDriver: "docker", dockerRuntime: null, effectivePreflight: { failure: null, @@ -142,6 +146,7 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { registered: true, lookup: { state: "gateway_schema_mismatch", output: "gateway schema mismatch" }, phase: "Stopped", + openshellDriver: "docker", dockerRuntime: null, effectivePreflight: { failure: null, @@ -172,6 +177,7 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { " Sandbox 'beta' is running, but NemoClaw could not clear its stale intentional-stop record.", }, phase: "Running", + openshellDriver: "docker", dockerRuntime: null, effectivePreflight: { failure: null, @@ -211,12 +217,23 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { expect(text).not.toContain("beta start"); }); - it("steers a provider without a Docker container to the OpenShell start path", async () => { + it("steers a Docker-driver sandbox without its container to rebuild", async () => { const cap = captureConsoleLog(); await printGuidance({ phase: "Error", dockerRuntime: null }); const text = cap.lines(); cap.restore(); + expect(text).toContain("nemoclaw beta rebuild --yes"); + expect(text).toContain("missing Docker-driver container"); + expect(text).not.toContain("nemoclaw beta start"); + }); + + it("steers a native provider without a Docker container to OpenShell start", async () => { + const cap = captureConsoleLog(); + await printGuidance({ phase: "Error", openshellDriver: "mxc", dockerRuntime: null }); + const text = cap.lines(); + cap.restore(); + expect(text).toContain("nemoclaw beta start"); expect(text).toContain("restart the sandbox through OpenShell"); expect(text).not.toContain("Run `nemoclaw beta rebuild --yes` to recreate"); diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index 18a682f4b65..95ba19dd890 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -22,6 +22,7 @@ type SandboxGatewayLookupStatusContext = { registered: boolean; lookup: SandboxGatewayState; phase: string | null; + openshellDriver: string | null; dockerRuntime: ReturnType | null; effectivePreflight: SandboxStatusPreflightResult; }; @@ -141,6 +142,7 @@ function printPresentSandboxGatewayLookupStatus({ sandboxName, lookup, phase, + openshellDriver, dockerRuntime, }: SandboxGatewayLookupStatusContext): void { console.log(""); @@ -166,7 +168,7 @@ function printPresentSandboxGatewayLookupStatus({ ? lookup.output.replace(/^(\s*Phase:\s*)\S+\s*$/gmu, "$1Stopped") : lookup.output; if (renderedOutput) console.log(renderedOutput); - printNonReadySandboxPhaseGuidance({ sandboxName, phase, dockerRuntime }); + printNonReadySandboxPhaseGuidance({ sandboxName, phase, openshellDriver, dockerRuntime }); } function printWrongGatewayActiveLookupStatus({ @@ -262,10 +264,12 @@ async function printUnknownGatewayLookupStatus({ function printNonReadySandboxPhaseGuidance({ sandboxName, phase, + openshellDriver, dockerRuntime, }: { sandboxName: string; phase: string | null; + openshellDriver: string | null; dockerRuntime: ReturnType | null; }): void { if (!phase || phase === "Ready") return; @@ -318,6 +322,12 @@ function printNonReadySandboxPhaseGuidance({ " This usually happens when a process crash inside the sandbox prevented clean startup.", ); console.log(""); + if (phase === "Error" && openshellDriver === "docker" && !dockerRuntime?.containerName) { + console.log( + ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the missing Docker-driver container (--yes skips the confirmation prompt; workspace state will be preserved).`, + ); + return; + } if (phase === "Error") { console.log( ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index dc755d4d87b..4783ff7b446 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -250,6 +250,7 @@ async function showLegacySandboxStatus(sandboxName: string): Promise { registered: sb !== null, lookup, phase, + openshellDriver: sb?.openshellDriver ?? null, dockerRuntime, effectivePreflight, }); diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index 89f29db0b8c..6945ae46193 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -374,13 +374,23 @@ sha256sum /sandbox/.bashrc /sandbox/.profile > /tmp/nemoclaw-e2e-profiles.sha256 .join("\n"), ).toBe(true); - const stoppedStatus = await repoNemoclaw( - input.host, - [SANDBOX_NAME, "status"], - "phase-4-status-after-native-gateway-exit", - {}, - 120_000, - ); + await input.sandbox.killGatewayTree(SANDBOX_NAME, { + artifactName: "phase-4-stop-native-gateway-before-recovery", + env: env(), + redactionValues: input.redactionValues, + timeoutMs: 30_000, + }); + const stoppedStatus = ( + await pollUntil({ + artifactPrefix: "phase-4-status-after-native-gateway-exit", + attempts: 10, + delayMs: 1_000, + probe: async (_attempt, artifactName) => + await repoNemoclaw(input.host, [SANDBOX_NAME, "status"], artifactName, {}, 60_000), + accept: (result) => + result.exitCode !== 0 && resultText(result).includes(`nemoclaw ${SANDBOX_NAME} start`), + }) + ).value; const recovery = await repoNemoclaw( input.host, [SANDBOX_NAME, "start"], diff --git a/test/e2e/support/full-e2e-gateway.test.ts b/test/e2e/support/full-e2e-gateway.test.ts index 72d1d8386bd..30251866c3c 100644 --- a/test/e2e/support/full-e2e-gateway.test.ts +++ b/test/e2e/support/full-e2e-gateway.test.ts @@ -5,7 +5,6 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { printSandboxGatewayLookupStatus } from "../../../src/lib/actions/sandbox/status-lookup-rendering.ts"; import { fullE2eGateway } from "../fixtures/full-e2e-gateway.ts"; const directories: string[] = []; @@ -61,35 +60,6 @@ function declaration( } describe("full E2E gateway ownership", () => { - it("maps a native gateway exit to workspace-preserving OpenShell recovery", async () => { - const lines: string[] = []; - vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => { - lines.push(args.map(String).join(" ")); - }); - - await printSandboxGatewayLookupStatus({ - sandboxName: "nemoclaw-e2e", - registered: true, - lookup: { - state: "present", - output: "Sandbox:\n Name: nemoclaw-e2e\n Phase: Error", - }, - phase: "Error", - dockerRuntime: null, - effectivePreflight: { - failure: null, - failureLayer: null, - suppressInferenceProbe: false, - exitCode: 0, - }, - }); - - const guidance = lines.join("\n"); - expect(guidance).toContain("nemoclaw nemoclaw-e2e start"); - expect(guidance).toContain("workspace state preserved"); - expect(guidance).toContain("nemoclaw nemoclaw-e2e rebuild --yes"); - }); - it.each([ { preinstalled: true, targetId: "staging-brev-launchable", measuresColdOnboard: false }, { preinstalled: false, targetId: "staging-brev-launchable", measuresColdOnboard: false }, From aa7710f47224e389cb4295b054056296b35fccbb Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:26:59 -0700 Subject: [PATCH 07/44] test(e2e): cover native gateway recovery sequence Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/live/full-e2e.test.ts | 64 +++++++++++++++-------- test/e2e/support/full-e2e-gateway.test.ts | 50 ++++++++++++++++++ 2 files changed, 91 insertions(+), 23 deletions(-) diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index 6945ae46193..ef5366fa065 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -336,6 +336,28 @@ console.log(JSON.stringify({ ); } +export async function recoverNativeGatewayAfterExit(input: { + sandboxName: string; + stopGateway: () => Promise; + readStatus: (artifactName: string) => Promise; + startSandbox: () => Promise; + pollDelayMs?: number; +}): Promise<{ recovery: ShellProbeResult; stoppedStatus: ShellProbeResult }> { + await input.stopGateway(); + const stoppedStatus = ( + await pollUntil({ + artifactPrefix: "phase-4-status-after-native-gateway-exit", + attempts: 10, + delayMs: input.pollDelayMs ?? 1_000, + probe: async (_attempt, artifactName) => await input.readStatus(artifactName), + accept: (result) => + result.exitCode !== 0 && resultText(result).includes(`nemoclaw ${input.sandboxName} start`), + }) + ).value; + const recovery = await input.startSandbox(); + return { recovery, stoppedStatus }; +} + async function runOpenClawLaunchTurns(input: { host: HostCliClient; redactionValues: string[]; @@ -374,30 +396,26 @@ sha256sum /sandbox/.bashrc /sandbox/.profile > /tmp/nemoclaw-e2e-profiles.sha256 .join("\n"), ).toBe(true); - await input.sandbox.killGatewayTree(SANDBOX_NAME, { - artifactName: "phase-4-stop-native-gateway-before-recovery", - env: env(), - redactionValues: input.redactionValues, - timeoutMs: 30_000, + const { recovery, stoppedStatus } = await recoverNativeGatewayAfterExit({ + sandboxName: SANDBOX_NAME, + stopGateway: async () => + await input.sandbox.killGatewayTree(SANDBOX_NAME, { + artifactName: "phase-4-stop-native-gateway-before-recovery", + env: env(), + redactionValues: input.redactionValues, + timeoutMs: 30_000, + }), + readStatus: async (artifactName) => + await repoNemoclaw(input.host, [SANDBOX_NAME, "status"], artifactName, {}, 60_000), + startSandbox: async () => + await repoNemoclaw( + input.host, + [SANDBOX_NAME, "start"], + "phase-4-start-after-native-gateway-exit", + {}, + 180_000, + ), }); - const stoppedStatus = ( - await pollUntil({ - artifactPrefix: "phase-4-status-after-native-gateway-exit", - attempts: 10, - delayMs: 1_000, - probe: async (_attempt, artifactName) => - await repoNemoclaw(input.host, [SANDBOX_NAME, "status"], artifactName, {}, 60_000), - accept: (result) => - result.exitCode !== 0 && resultText(result).includes(`nemoclaw ${SANDBOX_NAME} start`), - }) - ).value; - const recovery = await repoNemoclaw( - input.host, - [SANDBOX_NAME, "start"], - "phase-4-start-after-native-gateway-exit", - {}, - 180_000, - ); const configEdit = !recovery.timedOut && recovery.exitCode === 0 && securityPostureEnabled() ? await repoNemoclaw( diff --git a/test/e2e/support/full-e2e-gateway.test.ts b/test/e2e/support/full-e2e-gateway.test.ts index 30251866c3c..bd05b81770f 100644 --- a/test/e2e/support/full-e2e-gateway.test.ts +++ b/test/e2e/support/full-e2e-gateway.test.ts @@ -6,6 +6,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { fullE2eGateway } from "../fixtures/full-e2e-gateway.ts"; +import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; const directories: string[] = []; const disposables: (() => Promise)[] = []; @@ -59,7 +60,56 @@ function declaration( return { NEMOCLAW_GATEWAY_MANAGEMENT: file }; } +function probeResult(exitCode: number, stdout: string): ShellProbeResult { + return { + artifacts: { result: "", stderr: "", stdout: "" }, + command: [], + exitCode, + signal: null, + stderr: "", + stdout, + timedOut: false, + }; +} + describe("full E2E gateway ownership", () => { + it("stops the native gateway before starting recovery after observable failure", async () => { + vi.resetModules(); + captured.test.mockClear(); + vi.stubEnv("NEMOCLAW_EXPERIMENTAL_PROFILE", ""); + const { recoverNativeGatewayAfterExit } = await import("../live/full-e2e.test.ts"); + const calls: string[] = []; + const results = [ + probeResult(0, "Phase: Ready"), + probeResult(1, "Phase: Error\nRun `nemoclaw e2e-full start`."), + ]; + + const outcome = await recoverNativeGatewayAfterExit({ + sandboxName: "e2e-full", + pollDelayMs: 0, + stopGateway: async () => { + calls.push("stop"); + }, + readStatus: async (artifactName) => { + calls.push(artifactName); + return results.shift()!; + }, + startSandbox: async () => { + calls.push("start"); + return probeResult(0, "recovered"); + }, + }); + + expect(calls).toEqual([ + "stop", + "phase-4-status-after-native-gateway-exit-attempt-01", + "phase-4-status-after-native-gateway-exit-attempt-02", + "start", + ]); + expect(outcome.stoppedStatus.exitCode).toBe(1); + expect(outcome.recovery).toMatchObject({ exitCode: 0, stdout: "recovered" }); + }); + it.each([ { preinstalled: true, targetId: "staging-brev-launchable", measuresColdOnboard: false }, { preinstalled: false, targetId: "staging-brev-launchable", measuresColdOnboard: false }, From 0243dde3cea387b3d8a9a004537bf98aa9766257 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 21:10:09 -0700 Subject: [PATCH 08/44] fix(sandbox): normalize error recovery guidance Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../recover-rebuild-sandboxes.mdx | 12 +++++- .../sandbox/gateway-failure-classifier.ts | 23 ++++++++++- .../sandbox/gateway-state-hints.test.ts | 39 +++++++++++++++++++ src/lib/actions/sandbox/gateway-state.ts | 38 ++++++++++-------- .../sandbox/status-lookup-rendering.test.ts | 16 +++++++- .../sandbox/status-lookup-rendering.ts | 15 +++++-- src/lib/onboard/runtime-provider/contract.ts | 5 +++ src/lib/onboard/runtime-provider/registry.ts | 7 +--- 8 files changed, 126 insertions(+), 29 deletions(-) diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 1043b8c2e16..7cb804e751c 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -49,8 +49,11 @@ which can happen when something started the container outside OpenShell. It repo starting the sandbox through OpenShell rather than treating the running container as already started. If the container is paused, follow the printed `docker unpause` guidance instead. -If Docker no longer has the container, destroy the stale NemoClaw entry and onboard a clean replacement. -Restore a separately created snapshot afterward if one is available; rebuild cannot recover a workspace or live OpenShell policy that no longer exists. +If OpenShell reports the sandbox in `Phase: Error` but Docker no longer has its driver container, +run `$$nemoclaw rebuild --yes` to recreate the container while preserving workspace state. +If the sandbox is absent from the live OpenShell gateway, destroy the stale NemoClaw entry and +onboard a clean replacement. Restore a separately created snapshot afterward if one is available; +rebuild cannot recover a workspace or live OpenShell policy that no longer exists. The `start` command repairs the agent runtime and host-side port forwards. @@ -221,6 +224,11 @@ It does not report a successful rebuild. If the sandbox's container is stopped (for example, an out-of-band container kill left the sandbox in `Phase: Error`), rebuild starts the container for the duration of the pre-recreate state backup and returns it to its stopped state afterward, the same recovery `$$nemoclaw backup-all` uses for a stopped container. If no stopped container can be found for the sandbox, or the retried backup still fails, rebuild aborts without recreating the sandbox; it reports an incomplete-snapshot notice only when a partial snapshot was retained. If the backup itself succeeds but the started container cannot be returned to its stopped state, rebuild also aborts, so a sandbox that was stopped before rebuild started is never left running without a warning. +If OpenShell still reports the sandbox in `Phase: Error` but its Docker-driver container is missing, +use `$$nemoclaw rebuild --yes` to recreate the container with workspace state +preserved. This recovery does not apply when the sandbox itself is absent from the live OpenShell +gateway; use the clean replacement flow described above for that case. + For a legacy Hermes sandbox with no base-image hint or `NEMOCLAW_HERMES_SANDBOX_BASE_IMAGE_REF` override, rebuild requires the release-pinned immutable Hermes base image. diff --git a/src/lib/actions/sandbox/gateway-failure-classifier.ts b/src/lib/actions/sandbox/gateway-failure-classifier.ts index 527d98d5b8f..82d309d234e 100644 --- a/src/lib/actions/sandbox/gateway-failure-classifier.ts +++ b/src/lib/actions/sandbox/gateway-failure-classifier.ts @@ -10,7 +10,10 @@ import { GATEWAY_PORT } from "../../core/ports"; import { resolveSandboxContainerOwner } from "../../domain/sandbox/container-owner"; import { resolveGatewayPortFromName } from "../../onboard/gateway-binding"; import type { PortablePodmanReadinessResult } from "../../onboard/experimental/portable-runtime-readiness"; -import type { RuntimeProviderSnapshotLifecycleState } from "../../onboard/runtime-provider/contract"; +import { + normalizeRuntimeProviderIdentity, + type RuntimeProviderSnapshotLifecycleState, +} from "../../onboard/runtime-provider/contract"; import { inspectPortableRuntimeReceiptReadiness, type PortableRuntimeReceiptReadinessDeps, @@ -63,6 +66,24 @@ export type SandboxContainerFailureRunners = { portProbe: (port: number) => Promise; }; +export type SandboxPhaseRecoveryAction = "rebuild_missing_docker_container" | "start" | "rebuild"; + +export function classifySandboxPhaseRecoveryAction({ + phase, + openshellDriver, + dockerContainerName, +}: { + phase: string; + openshellDriver: string | null | undefined; + dockerContainerName: string | null | undefined; +}): SandboxPhaseRecoveryAction { + if (phase !== "Error") return "rebuild"; + if (normalizeRuntimeProviderIdentity(openshellDriver) === "docker" && !dockerContainerName) { + return "rebuild_missing_docker_container"; + } + return "start"; +} + function defaultDockerInfo(): boolean { return dockerInfo({ ignoreError: true, timeout: DOCKER_TIMEOUT_MS }).length > 0; } diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index 35d013526d3..4f73f0f52bf 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -317,6 +317,45 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); + it.each([ + ["legacy vm alias", "vm"], + ["missing legacy metadata", undefined], + ])( + "steers a Docker Error sandbox with %s and no container to rebuild", + async (_case, openshellDriver) => { + mockSandboxPhase("Error"); + getSandboxSpy.mockReturnValue({ + name: "instance-a", + gatewayName: "nemoclaw", + gatewayPort: 8080, + openshellDriver, + }); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: false, + running: true, + containerName: null, + }); + const lines: string[] = []; + vi.spyOn(console, "error").mockImplementation((line = "") => { + lines.push(String(line)); + }); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + + await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow( + "process.exit(1)", + ); + + const output = lines.join("\n"); + expect(output).toContain("nemoclaw instance-a rebuild --yes"); + expect(output).toContain("missing Docker-driver container"); + expect(output).not.toContain("nemoclaw instance-a start"); + expect(exitSpy).toHaveBeenCalledWith(1); + }, + ); + it("keeps OpenShell start guidance for a native Error sandbox without a Docker container", async () => { mockSandboxPhase("Error"); getSandboxSpy.mockReturnValue({ diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 88a6e4ec0f8..8c9281efa5a 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -101,7 +101,11 @@ import { } from "../../state/registry/lifecycle-generation"; import type { SandboxEntry } from "../../state/registry/types"; import { getSandboxDockerRuntime } from "./docker-health"; -import { isDockerRuntimeDown, printDockerRuntimeDownGuidance } from "./gateway-failure-classifier"; +import { + classifySandboxPhaseRecoveryAction, + isDockerRuntimeDown, + printDockerRuntimeDownGuidance, +} from "./gateway-failure-classifier"; export type SandboxGatewayState = { state: string; @@ -1166,22 +1170,22 @@ export async function ensureLiveSandboxOrExit( " This usually happens when a process crash inside the sandbox prevented clean startup.", ); console.error(""); - if (phase === "Error") { - if ( - getKnownSandboxTarget(sandboxName)?.openshellDriver === "docker" && - !dockerRuntime.containerName - ) { - console.error( - ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the missing Docker-driver container (--yes skips the confirmation prompt; workspace state will be preserved).`, - ); - } else { - console.error( - ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, - ); - console.error( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead; use it only if start does not recover the sandbox.)`, - ); - } + const recoveryAction = classifySandboxPhaseRecoveryAction({ + phase, + openshellDriver: getKnownSandboxTarget(sandboxName)?.openshellDriver, + dockerContainerName: dockerRuntime.containerName, + }); + if (recoveryAction === "rebuild_missing_docker_container") { + console.error( + ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the missing Docker-driver container (--yes skips the confirmation prompt; workspace state will be preserved).`, + ); + } else if (recoveryAction === "start") { + console.error( + ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, + ); + console.error( + ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead; use it only if start does not recover the sandbox.)`, + ); } else { console.error( ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`, diff --git a/src/lib/actions/sandbox/status-lookup-rendering.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index ff64088e303..4221aa8b44c 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -19,7 +19,7 @@ async function printGuidance({ openshellDriver = "docker", }: { phase: string; - openshellDriver?: string; + openshellDriver?: string | null; dockerRuntime: { health: "none"; paused: boolean; @@ -228,6 +228,20 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { expect(text).not.toContain("nemoclaw beta start"); }); + it.each([ + ["legacy vm alias", "vm"], + ["missing legacy metadata", null], + ])("steers a Docker sandbox with %s and no container to rebuild", async (_case, driver) => { + const cap = captureConsoleLog(); + await printGuidance({ phase: "Error", openshellDriver: driver, dockerRuntime: null }); + const text = cap.lines(); + cap.restore(); + + expect(text).toContain("nemoclaw beta rebuild --yes"); + expect(text).toContain("missing Docker-driver container"); + expect(text).not.toContain("nemoclaw beta start"); + }); + it("steers a native provider without a Docker container to OpenShell start", async () => { const cap = captureConsoleLog(); await printGuidance({ phase: "Error", openshellDriver: "mxc", dockerRuntime: null }); diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index 95ba19dd890..2d442ec7cd2 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -7,7 +7,11 @@ import { deferSandboxLifecycleExit } from "../../core/process-exit"; import { gatewayStartGuidance } from "../../gateway-start-guidance"; import { isTerminalSandboxPhase } from "../../state/gateway"; import { getSandboxDockerRuntime } from "./docker-health"; -import { isDockerRuntimeDown, printDockerRuntimeDownGuidance } from "./gateway-failure-classifier"; +import { + classifySandboxPhaseRecoveryAction, + isDockerRuntimeDown, + printDockerRuntimeDownGuidance, +} from "./gateway-failure-classifier"; import type { SandboxGatewayState } from "./gateway-state"; import { printSandboxGatewayStateHint, printWrongGatewayActiveGuidance } from "./gateway-state"; import { getSandboxTargetGatewayName } from "./gateway-target"; @@ -322,13 +326,18 @@ function printNonReadySandboxPhaseGuidance({ " This usually happens when a process crash inside the sandbox prevented clean startup.", ); console.log(""); - if (phase === "Error" && openshellDriver === "docker" && !dockerRuntime?.containerName) { + const recoveryAction = classifySandboxPhaseRecoveryAction({ + phase, + openshellDriver, + dockerContainerName: dockerRuntime?.containerName, + }); + if (recoveryAction === "rebuild_missing_docker_container") { console.log( ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the missing Docker-driver container (--yes skips the confirmation prompt; workspace state will be preserved).`, ); return; } - if (phase === "Error") { + if (recoveryAction === "start") { console.log( ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, ); diff --git a/src/lib/onboard/runtime-provider/contract.ts b/src/lib/onboard/runtime-provider/contract.ts index 7f5acac81e5..eb6c8160c70 100644 --- a/src/lib/onboard/runtime-provider/contract.ts +++ b/src/lib/onboard/runtime-provider/contract.ts @@ -51,6 +51,11 @@ export type RuntimeProviderContainerEngineOperation = | "sandbox-lifecycle" | "workload-cleanup"; +export function normalizeRuntimeProviderIdentity(driverName: string | null | undefined): string { + const normalized = driverName?.trim().toLowerCase(); + return !normalized || normalized === "vm" ? "docker" : normalized; +} + export interface RuntimeProviderIdentity { readonly contractVersion: typeof RUNTIME_PROVIDER_BUNDLE_CONTRACT_VERSION; readonly id: string; diff --git a/src/lib/onboard/runtime-provider/registry.ts b/src/lib/onboard/runtime-provider/registry.ts index 9a5dbd5a6f7..b96d2c987d3 100644 --- a/src/lib/onboard/runtime-provider/registry.ts +++ b/src/lib/onboard/runtime-provider/registry.ts @@ -8,6 +8,7 @@ import { RUNTIME_PROVIDER_NATIVE_ARTIFACT_BOOTSTRAP_CONTRACT_VERSION, RUNTIME_PROVIDER_SNAPSHOT_CONTRACT_VERSION, RUNTIME_PROVIDER_SNAPSHOT_PREFLIGHT_SCHEMA_VERSION, + normalizeRuntimeProviderIdentity, type RuntimeProviderBundle, type RuntimeProviderBundleRegistry, type RuntimeProviderChannelStopTransport, @@ -20,6 +21,7 @@ import { type RuntimeProviderSnapshotRestoreReceipt, type RuntimeProviderSnapshotRestoreSource, } from "./contract"; +export { normalizeRuntimeProviderIdentity } from "./contract"; import type { HostLocalInferenceOperation, HostLocalInferenceOperationInput, @@ -726,11 +728,6 @@ export function createRuntimeProviderBundleRegistry( return Object.freeze(registry); } -export function normalizeRuntimeProviderIdentity(driverName: string | null | undefined): string { - const normalized = driverName?.trim().toLowerCase(); - return !normalized || normalized === "vm" ? "docker" : normalized; -} - export function resolveRuntimeProviderBundle( driverName: string | null | undefined, providers: RuntimeProviderBundleRegistry, From 3549cec0b24eb6991929ba4f09a93e2f8cfb8818 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 21:57:54 -0700 Subject: [PATCH 09/44] fix(sandbox): correct missing-container recovery guidance Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../recover-rebuild-sandboxes.mdx | 8 ++-- .../sandbox/gateway-failure-classifier.ts | 4 +- .../sandbox/gateway-state-hints.test.ts | 17 +++++--- src/lib/actions/sandbox/gateway-state.ts | 8 +++- src/lib/actions/sandbox/status-flow.test.ts | 41 +++++++++++++++++++ .../sandbox/status-lookup-rendering.test.ts | 32 +++++++++------ .../sandbox/status-lookup-rendering.ts | 8 +++- 7 files changed, 90 insertions(+), 28 deletions(-) diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 7cb804e751c..8ff037eb84a 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -50,7 +50,8 @@ starting the sandbox through OpenShell rather than treating the running containe started. If the container is paused, follow the printed `docker unpause` guidance instead. If OpenShell reports the sandbox in `Phase: Error` but Docker no longer has its driver container, -run `$$nemoclaw rebuild --yes` to recreate the container while preserving workspace state. +NemoClaw cannot back up the live workspace for rebuild. Destroy the stale entry, onboard a clean +replacement, and restore a separately created snapshot afterward if one is available. If the sandbox is absent from the live OpenShell gateway, destroy the stale NemoClaw entry and onboard a clean replacement. Restore a separately created snapshot afterward if one is available; rebuild cannot recover a workspace or live OpenShell policy that no longer exists. @@ -225,9 +226,8 @@ It does not report a successful rebuild. If the sandbox's container is stopped (for example, an out-of-band container kill left the sandbox in `Phase: Error`), rebuild starts the container for the duration of the pre-recreate state backup and returns it to its stopped state afterward, the same recovery `$$nemoclaw backup-all` uses for a stopped container. If no stopped container can be found for the sandbox, or the retried backup still fails, rebuild aborts without recreating the sandbox; it reports an incomplete-snapshot notice only when a partial snapshot was retained. If the backup itself succeeds but the started container cannot be returned to its stopped state, rebuild also aborts, so a sandbox that was stopped before rebuild started is never left running without a warning. If OpenShell still reports the sandbox in `Phase: Error` but its Docker-driver container is missing, -use `$$nemoclaw rebuild --yes` to recreate the container with workspace state -preserved. This recovery does not apply when the sandbox itself is absent from the live OpenShell -gateway; use the clean replacement flow described above for that case. +rebuild cannot back up its live workspace and stops before replacement. Use the clean replacement +flow described above, then restore a separately created snapshot if one is available. diff --git a/src/lib/actions/sandbox/gateway-failure-classifier.ts b/src/lib/actions/sandbox/gateway-failure-classifier.ts index 82d309d234e..200f221bfa9 100644 --- a/src/lib/actions/sandbox/gateway-failure-classifier.ts +++ b/src/lib/actions/sandbox/gateway-failure-classifier.ts @@ -66,7 +66,7 @@ export type SandboxContainerFailureRunners = { portProbe: (port: number) => Promise; }; -export type SandboxPhaseRecoveryAction = "rebuild_missing_docker_container" | "start" | "rebuild"; +export type SandboxPhaseRecoveryAction = "replace_missing_docker_container" | "start" | "rebuild"; export function classifySandboxPhaseRecoveryAction({ phase, @@ -79,7 +79,7 @@ export function classifySandboxPhaseRecoveryAction({ }): SandboxPhaseRecoveryAction { if (phase !== "Error") return "rebuild"; if (normalizeRuntimeProviderIdentity(openshellDriver) === "docker" && !dockerContainerName) { - return "rebuild_missing_docker_container"; + return "replace_missing_docker_container"; } return "start"; } diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index 4f73f0f52bf..8da0f23ecb2 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -284,7 +284,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); - it("steers a Docker-driver Error sandbox without its container to rebuild", async () => { + it("steers a Docker-driver Error sandbox without its container to clean replacement", async () => { mockSandboxPhase("Error"); getSandboxSpy.mockReturnValue({ name: "instance-a", @@ -311,8 +311,11 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { ); const output = lines.join("\n"); - expect(output).toContain("nemoclaw instance-a rebuild --yes"); - expect(output).toContain("missing Docker-driver container"); + expect(output).toContain("cannot back up its live workspace for rebuild"); + expect(output).toContain("nemoclaw instance-a destroy --yes"); + expect(output).toContain("nemoclaw onboard"); + expect(output).toContain("separately created snapshot"); + expect(output).not.toContain("nemoclaw instance-a rebuild --yes"); expect(output).not.toContain("nemoclaw instance-a start"); expect(exitSpy).toHaveBeenCalledWith(1); }); @@ -321,7 +324,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { ["legacy vm alias", "vm"], ["missing legacy metadata", undefined], ])( - "steers a Docker Error sandbox with %s and no container to rebuild", + "steers a Docker Error sandbox with %s and no container to clean replacement", async (_case, openshellDriver) => { mockSandboxPhase("Error"); getSandboxSpy.mockReturnValue({ @@ -349,8 +352,10 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { ); const output = lines.join("\n"); - expect(output).toContain("nemoclaw instance-a rebuild --yes"); - expect(output).toContain("missing Docker-driver container"); + expect(output).toContain("cannot back up its live workspace for rebuild"); + expect(output).toContain("nemoclaw instance-a destroy --yes"); + expect(output).toContain("nemoclaw onboard"); + expect(output).not.toContain("nemoclaw instance-a rebuild --yes"); expect(output).not.toContain("nemoclaw instance-a start"); expect(exitSpy).toHaveBeenCalledWith(1); }, diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 8c9281efa5a..8a6fb5c67f2 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -1175,10 +1175,14 @@ export async function ensureLiveSandboxOrExit( openshellDriver: getKnownSandboxTarget(sandboxName)?.openshellDriver, dockerContainerName: dockerRuntime.containerName, }); - if (recoveryAction === "rebuild_missing_docker_container") { + if (recoveryAction === "replace_missing_docker_container") { console.error( - ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the missing Docker-driver container (--yes skips the confirmation prompt; workspace state will be preserved).`, + " The Docker-driver container is missing, so NemoClaw cannot back up its live workspace for rebuild.", ); + console.error(" To create a clean replacement:"); + console.error(` 1. ${CLI_NAME} ${sandboxName} destroy --yes`); + console.error(` 2. ${CLI_NAME} onboard`); + console.error(" Restore a separately created snapshot afterward if one is available."); } else if (recoveryAction === "start") { console.error( ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, diff --git a/src/lib/actions/sandbox/status-flow.test.ts b/src/lib/actions/sandbox/status-flow.test.ts index dbe32139ec4..2b1660f8714 100644 --- a/src/lib/actions/sandbox/status-flow.test.ts +++ b/src/lib/actions/sandbox/status-flow.test.ts @@ -126,6 +126,47 @@ describe("showSandboxStatus flow", () => { expect(harness.withMcpLifecycleLockSpy).toHaveBeenCalledWith("alpha", expect.any(Function)); }); + it.each([ + { + label: "Docker", + openshellDriver: "docker", + expected: "nemoclaw alpha destroy --yes", + unexpected: "nemoclaw alpha start", + }, + { + label: "native", + openshellDriver: "mxc", + expected: "nemoclaw alpha start", + unexpected: "nemoclaw alpha destroy --yes", + }, + ])( + "passes the $label driver to missing-container Error recovery guidance", + async ({ openshellDriver, expected, unexpected }) => { + const harness = createStatusFlowHarness({ + sandboxEntry: { openshellDriver }, + lookup: { + state: "present", + output: "Name: alpha\nPhase: Error\nEndpoint: http://127.0.0.1:18789\n", + phase: "Error", + recoveredGateway: true, + recoveryVia: "gateway reattach", + }, + }); + harness.getSandboxDockerRuntimeSpy.mockReturnValue({ + containerName: null, + health: "none", + paused: false, + running: false, + }); + + await expect(harness.showSandboxStatus("alpha")).resolves.toBeUndefined(); + + const output = harness.logSpy.mock.calls.flat().join("\n"); + expect(output).toContain(expected); + expect(output).not.toContain(unexpected); + }, + ); + it("classifies publication while waiting for the status lifecycle fence (#9203)", async () => { let disposition: { readonly kind: "absent" } | ReturnType = { kind: "absent", diff --git a/src/lib/actions/sandbox/status-lookup-rendering.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index 4221aa8b44c..8811492ba15 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -217,30 +217,38 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { expect(text).not.toContain("beta start"); }); - it("steers a Docker-driver sandbox without its container to rebuild", async () => { + it("steers a Docker-driver sandbox without its container to clean replacement", async () => { const cap = captureConsoleLog(); await printGuidance({ phase: "Error", dockerRuntime: null }); const text = cap.lines(); cap.restore(); - expect(text).toContain("nemoclaw beta rebuild --yes"); - expect(text).toContain("missing Docker-driver container"); + expect(text).toContain("cannot back up its live workspace for rebuild"); + expect(text).toContain("nemoclaw beta destroy --yes"); + expect(text).toContain("nemoclaw onboard"); + expect(text).toContain("separately created snapshot"); + expect(text).not.toContain("nemoclaw beta rebuild --yes"); expect(text).not.toContain("nemoclaw beta start"); }); it.each([ ["legacy vm alias", "vm"], ["missing legacy metadata", null], - ])("steers a Docker sandbox with %s and no container to rebuild", async (_case, driver) => { - const cap = captureConsoleLog(); - await printGuidance({ phase: "Error", openshellDriver: driver, dockerRuntime: null }); - const text = cap.lines(); - cap.restore(); + ])( + "steers a Docker sandbox with %s and no container to clean replacement", + async (_case, driver) => { + const cap = captureConsoleLog(); + await printGuidance({ phase: "Error", openshellDriver: driver, dockerRuntime: null }); + const text = cap.lines(); + cap.restore(); - expect(text).toContain("nemoclaw beta rebuild --yes"); - expect(text).toContain("missing Docker-driver container"); - expect(text).not.toContain("nemoclaw beta start"); - }); + expect(text).toContain("cannot back up its live workspace for rebuild"); + expect(text).toContain("nemoclaw beta destroy --yes"); + expect(text).toContain("nemoclaw onboard"); + expect(text).not.toContain("nemoclaw beta rebuild --yes"); + expect(text).not.toContain("nemoclaw beta start"); + }, + ); it("steers a native provider without a Docker container to OpenShell start", async () => { const cap = captureConsoleLog(); diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index 2d442ec7cd2..fafdd0039cb 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -331,10 +331,14 @@ function printNonReadySandboxPhaseGuidance({ openshellDriver, dockerContainerName: dockerRuntime?.containerName, }); - if (recoveryAction === "rebuild_missing_docker_container") { + if (recoveryAction === "replace_missing_docker_container") { console.log( - ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the missing Docker-driver container (--yes skips the confirmation prompt; workspace state will be preserved).`, + " The Docker-driver container is missing, so NemoClaw cannot back up its live workspace for rebuild.", ); + console.log(" To create a clean replacement:"); + console.log(` 1. ${CLI_NAME} ${sandboxName} destroy --yes`); + console.log(` 2. ${CLI_NAME} onboard`); + console.log(" Restore a separately created snapshot afterward if one is available."); return; } if (recoveryAction === "start") { From b2926c838cc5dec3d5f1f1fbb022cc4e79f2e58a Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 22:25:16 -0700 Subject: [PATCH 10/44] fix(sandbox): preserve recovery identity ownership Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/gateway-failure-classifier.ts | 8 +- .../sandbox/gateway-state-hints.test.ts | 102 +++++++++++------- src/lib/actions/sandbox/status-flow.test.ts | 54 +++++++--- .../sandbox/status-lookup-rendering.test.ts | 38 ++++--- src/lib/actions/sandbox/status-snapshot.ts | 5 +- src/lib/actions/sandbox/status.ts | 4 +- test/support/status-flow-test-harness.ts | 13 +++ 7 files changed, 150 insertions(+), 74 deletions(-) diff --git a/src/lib/actions/sandbox/gateway-failure-classifier.ts b/src/lib/actions/sandbox/gateway-failure-classifier.ts index 200f221bfa9..d787701fff4 100644 --- a/src/lib/actions/sandbox/gateway-failure-classifier.ts +++ b/src/lib/actions/sandbox/gateway-failure-classifier.ts @@ -10,10 +10,7 @@ import { GATEWAY_PORT } from "../../core/ports"; import { resolveSandboxContainerOwner } from "../../domain/sandbox/container-owner"; import { resolveGatewayPortFromName } from "../../onboard/gateway-binding"; import type { PortablePodmanReadinessResult } from "../../onboard/experimental/portable-runtime-readiness"; -import { - normalizeRuntimeProviderIdentity, - type RuntimeProviderSnapshotLifecycleState, -} from "../../onboard/runtime-provider/contract"; +import type { RuntimeProviderSnapshotLifecycleState } from "../../onboard/runtime-provider/contract"; import { inspectPortableRuntimeReceiptReadiness, type PortableRuntimeReceiptReadinessDeps, @@ -78,7 +75,8 @@ export function classifySandboxPhaseRecoveryAction({ dockerContainerName: string | null | undefined; }): SandboxPhaseRecoveryAction { if (phase !== "Error") return "rebuild"; - if (normalizeRuntimeProviderIdentity(openshellDriver) === "docker" && !dockerContainerName) { + const driver = openshellDriver?.trim().toLowerCase(); + if ((!driver || driver === "docker") && !dockerContainerName) { return "replace_missing_docker_container"; } return "start"; diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index 8da0f23ecb2..146a7a65e16 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -320,46 +320,72 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); - it.each([ - ["legacy vm alias", "vm"], - ["missing legacy metadata", undefined], - ])( - "steers a Docker Error sandbox with %s and no container to clean replacement", - async (_case, openshellDriver) => { - mockSandboxPhase("Error"); - getSandboxSpy.mockReturnValue({ - name: "instance-a", - gatewayName: "nemoclaw", - gatewayPort: 8080, - openshellDriver, - }); - getSandboxDockerRuntimeSpy.mockReturnValue({ - health: "none", - paused: false, - running: true, - containerName: null, - }); - const lines: string[] = []; - vi.spyOn(console, "error").mockImplementation((line = "") => { - lines.push(String(line)); - }); - const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { - throw new Error(`process.exit(${code ?? 0})`); - }) as never); + it("steers a Docker Error sandbox with missing legacy metadata and no container to clean replacement", async () => { + mockSandboxPhase("Error"); + getSandboxSpy.mockReturnValue({ + name: "instance-a", + gatewayName: "nemoclaw", + gatewayPort: 8080, + openshellDriver: undefined, + }); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: false, + running: true, + containerName: null, + }); + const lines: string[] = []; + vi.spyOn(console, "error").mockImplementation((line = "") => { + lines.push(String(line)); + }); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); - await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow( - "process.exit(1)", - ); + await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow( + "process.exit(1)", + ); - const output = lines.join("\n"); - expect(output).toContain("cannot back up its live workspace for rebuild"); - expect(output).toContain("nemoclaw instance-a destroy --yes"); - expect(output).toContain("nemoclaw onboard"); - expect(output).not.toContain("nemoclaw instance-a rebuild --yes"); - expect(output).not.toContain("nemoclaw instance-a start"); - expect(exitSpy).toHaveBeenCalledWith(1); - }, - ); + const output = lines.join("\n"); + expect(output).toContain("cannot back up its live workspace for rebuild"); + expect(output).toContain("nemoclaw instance-a destroy --yes"); + expect(output).toContain("nemoclaw onboard"); + expect(output).not.toContain("nemoclaw instance-a rebuild --yes"); + expect(output).not.toContain("nemoclaw instance-a start"); + expect(exitSpy).toHaveBeenCalledWith(1); + }); + + it("keeps OpenShell start guidance for a VM Error sandbox without a Docker container", async () => { + mockSandboxPhase("Error"); + getSandboxSpy.mockReturnValue({ + name: "instance-a", + gatewayName: "nemoclaw", + gatewayPort: 8080, + openshellDriver: "vm", + }); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: false, + running: false, + containerName: null, + }); + const lines: string[] = []; + vi.spyOn(console, "error").mockImplementation((line = "") => { + lines.push(String(line)); + }); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + + await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow( + "process.exit(1)", + ); + + const output = lines.join("\n"); + expect(output).toContain("nemoclaw instance-a start"); + expect(output).not.toContain("nemoclaw instance-a destroy --yes"); + expect(exitSpy).toHaveBeenCalledWith(1); + }); it("keeps OpenShell start guidance for a native Error sandbox without a Docker container", async () => { mockSandboxPhase("Error"); diff --git a/src/lib/actions/sandbox/status-flow.test.ts b/src/lib/actions/sandbox/status-flow.test.ts index 2b1660f8714..7cc9332450d 100644 --- a/src/lib/actions/sandbox/status-flow.test.ts +++ b/src/lib/actions/sandbox/status-flow.test.ts @@ -132,18 +132,38 @@ describe("showSandboxStatus flow", () => { openshellDriver: "docker", expected: "nemoclaw alpha destroy --yes", unexpected: "nemoclaw alpha start", + registryEntry: "present" as const, + publishedAcrossGatewayRoots: false, }, { label: "native", openshellDriver: "mxc", expected: "nemoclaw alpha start", unexpected: "nemoclaw alpha destroy --yes", + registryEntry: "present" as const, + publishedAcrossGatewayRoots: false, + }, + { + label: "cross-root native", + openshellDriver: "mxc", + expected: "nemoclaw alpha start", + unexpected: "nemoclaw alpha destroy --yes", + registryEntry: "missing" as const, + publishedAcrossGatewayRoots: true, }, ])( "passes the $label driver to missing-container Error recovery guidance", - async ({ openshellDriver, expected, unexpected }) => { + async ({ + openshellDriver, + expected, + unexpected, + registryEntry = "present", + publishedAcrossGatewayRoots = false, + }) => { const harness = createStatusFlowHarness({ sandboxEntry: { openshellDriver }, + registryEntry, + publishedAcrossGatewayRoots, lookup: { state: "present", output: "Name: alpha\nPhase: Error\nEndpoint: http://127.0.0.1:18789\n", @@ -164,6 +184,12 @@ describe("showSandboxStatus flow", () => { const output = harness.logSpy.mock.calls.flat().join("\n"); expect(output).toContain(expected); expect(output).not.toContain(unexpected); + expect(harness.collectSandboxStatusSnapshotSpy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + sandboxEntry: expect.objectContaining({ openshellDriver }), + }), + ); }, ); @@ -669,14 +695,17 @@ describe("showSandboxStatus flow", () => { expect(output).toContain("gateway is still refusing connections after restart"); expect(output).toContain("Start the gateway again with `nemoclaw onboard`."); expect(output).toContain("If the gateway never becomes healthy"); - expect(harness.collectSandboxStatusSnapshotSpy).toHaveBeenCalledWith("alpha", { - preflight: { - failure: null, - failureLayer: "docker_unreachable", - suppressInferenceProbe: true, - exitCode: 1, - }, - }); + expect(harness.collectSandboxStatusSnapshotSpy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + preflight: { + failure: null, + failureLayer: "docker_unreachable", + suppressInferenceProbe: true, + exitCode: 1, + }, + }), + ); }); it("renders the refreshed preflight after Docker recovery", async () => { @@ -704,9 +733,10 @@ describe("showSandboxStatus flow", () => { const output = harness.logSpy.mock.calls.flat().join("\n"); expect(output).not.toContain("Failure layer: sandbox_container_stopped"); expect(process.exitCode).toBeUndefined(); - expect(harness.collectSandboxStatusSnapshotSpy).toHaveBeenCalledWith("alpha", { - preflight, - }); + expect(harness.collectSandboxStatusSnapshotSpy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ preflight }), + ); }); it("renders llama.cpp details already classified in the snapshot", async () => { diff --git a/src/lib/actions/sandbox/status-lookup-rendering.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index 8811492ba15..eefd13b5bdc 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -231,24 +231,28 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { expect(text).not.toContain("nemoclaw beta start"); }); - it.each([ - ["legacy vm alias", "vm"], - ["missing legacy metadata", null], - ])( - "steers a Docker sandbox with %s and no container to clean replacement", - async (_case, driver) => { - const cap = captureConsoleLog(); - await printGuidance({ phase: "Error", openshellDriver: driver, dockerRuntime: null }); - const text = cap.lines(); - cap.restore(); + it("steers a Docker sandbox with missing legacy metadata and no container to clean replacement", async () => { + const cap = captureConsoleLog(); + await printGuidance({ phase: "Error", openshellDriver: null, dockerRuntime: null }); + const text = cap.lines(); + cap.restore(); - expect(text).toContain("cannot back up its live workspace for rebuild"); - expect(text).toContain("nemoclaw beta destroy --yes"); - expect(text).toContain("nemoclaw onboard"); - expect(text).not.toContain("nemoclaw beta rebuild --yes"); - expect(text).not.toContain("nemoclaw beta start"); - }, - ); + expect(text).toContain("cannot back up its live workspace for rebuild"); + expect(text).toContain("nemoclaw beta destroy --yes"); + expect(text).toContain("nemoclaw onboard"); + expect(text).not.toContain("nemoclaw beta rebuild --yes"); + expect(text).not.toContain("nemoclaw beta start"); + }); + + it("steers a VM sandbox without a Docker container to OpenShell start", async () => { + const cap = captureConsoleLog(); + await printGuidance({ phase: "Error", openshellDriver: "vm", dockerRuntime: null }); + const text = cap.lines(); + cap.restore(); + + expect(text).toContain("nemoclaw beta start"); + expect(text).not.toContain("nemoclaw beta destroy --yes"); + }); it("steers a native provider without a Docker container to OpenShell start", async () => { const cap = captureConsoleLog(); diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index a865adb96f5..85124ecbfb7 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -424,6 +424,7 @@ function reportInferenceProbeRetry( export async function collectSandboxStatusSnapshot( sandboxName: string, opts: { + sandboxEntry?: registry.SandboxEntry | null; suppressInferenceProbe?: boolean; preflight?: SandboxStatusPreflightResult; deps?: CollectSandboxStatusSnapshotDeps; @@ -435,7 +436,9 @@ export async function collectSandboxStatusSnapshot( const entry = registry.getSandbox(name); return entry && registry.isPublishedSandboxRegistration(entry) ? entry : null; }); - const sb = getSandbox(sandboxName); + const sb = Object.hasOwn(opts, "sandboxEntry") + ? (opts.sandboxEntry ?? null) + : getSandbox(sandboxName); const initialPreflight = opts.preflight ?? (sb?.stopped diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index 4783ff7b446..914fdb7a908 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -177,7 +177,8 @@ export async function showSandboxStatus(sandboxName: string): Promise { } async function showLegacySandboxStatus(sandboxName: string): Promise { - const preflight = await getSandboxStatusPreflight(getPublishedSandbox(sandboxName)); + const sandboxEntry = getPublishedSandbox(sandboxName); + const preflight = await getSandboxStatusPreflight(sandboxEntry); // #2666: never let an unexpected throw from the gateway probe (e.g. openshell // hanging when its container is stopped and the published port is held by a // foreign listener) suppress the sandbox header. The downstream switch @@ -185,6 +186,7 @@ async function showLegacySandboxStatus(sandboxName: string): Promise { // synthesized fallback keeps the user-visible contract intact. const snapshot = await collectSandboxStatusSnapshot(sandboxName, { preflight, + sandboxEntry, }); const { sb, diff --git a/test/support/status-flow-test-harness.ts b/test/support/status-flow-test-harness.ts index 33de1e088dd..2e30a754da5 100644 --- a/test/support/status-flow-test-harness.ts +++ b/test/support/status-flow-test-harness.ts @@ -83,6 +83,7 @@ export type StatusFlowHarnessOptions = { | Error | (() => PortableAgentReceiptDisposition | Error); registryEntry?: "present" | "missing"; + publishedAcrossGatewayRoots?: boolean; withMcpLifecycleLock?: WithMcpLifecycleLock; lookup?: SandboxGatewayState; lookupState?: "present" | "missing"; @@ -137,6 +138,7 @@ export function createStatusFlowHarness(options: StatusFlowHarnessOptions = {}): const policy = requireDist("../../src/lib/policy/index.js"); const sandboxVersion = requireDist("../../src/lib/sandbox/version.js"); const registry = requireDist("../../src/lib/state/registry.js"); + const crossPortRegistry = requireDist("../../src/lib/state/registry/cross-port.js"); const sandboxSession = requireDist("../../src/lib/state/sandbox-session.js"); const lookup: SandboxGatewayState = @@ -185,6 +187,17 @@ export function createStatusFlowHarness(options: StatusFlowHarnessOptions = {}): vi.spyOn(registry, "getSandbox").mockReturnValue( options.registryEntry === "missing" ? null : sandboxEntry, ); + vi.spyOn(crossPortRegistry, "findSandboxAcrossGatewayRoots").mockReturnValue( + options.registryEntry === "missing" && !options.publishedAcrossGatewayRoots + ? null + : sandboxEntry + ? { + entry: sandboxEntry, + gatewayPort: null, + registryFile: "/test/sandboxes.json", + } + : null, + ); const removeSandboxSpy = vi.spyOn(registry, "removeSandbox").mockImplementation(() => undefined); vi.spyOn(statusPreflight, "getSandboxStatusPreflight").mockResolvedValue( options.preflight ?? { From c5930a424cff1cccd725bd254880956832c5c01c Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 22:42:10 -0700 Subject: [PATCH 11/44] fix(sandbox): protect recovery during Docker outages Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../recover-rebuild-sandboxes.mdx | 6 +-- .../sandbox/gateway-state-hints.test.ts | 38 +++++++++++++++++++ src/lib/actions/sandbox/gateway-state.ts | 12 +++++- .../sandbox/status-lookup-rendering.test.ts | 22 +++++++++-- .../sandbox/status-lookup-rendering.ts | 15 +++++++- 5 files changed, 85 insertions(+), 8 deletions(-) diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 8ff037eb84a..c276389427c 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -52,9 +52,9 @@ If the container is paused, follow the printed `docker unpause` guidance instead If OpenShell reports the sandbox in `Phase: Error` but Docker no longer has its driver container, NemoClaw cannot back up the live workspace for rebuild. Destroy the stale entry, onboard a clean replacement, and restore a separately created snapshot afterward if one is available. -If the sandbox is absent from the live OpenShell gateway, destroy the stale NemoClaw entry and -onboard a clean replacement. Restore a separately created snapshot afterward if one is available; -rebuild cannot recover a workspace or live OpenShell policy that no longer exists. +If the sandbox is absent from the live OpenShell gateway, NemoClaw preserves its registry entry. +Retry status after the gateway finishes reconnecting. If the sandbox is stuck mid-provision, retry +rebuild after it reappears. Remove the stale entry only when the sandbox was intentionally deleted. The `start` command repairs the agent runtime and host-side port forwards. diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index 146a7a65e16..c1a223df3f2 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -33,6 +33,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { let getSandboxSpy: MockInstance; let findSandboxAcrossGatewayRootsSpy: MockInstance; let recoverNamedGatewayRuntimeSpy: MockInstance; + let dockerInfoSpy: MockInstance; function mockSandboxPhase(phase: string): void { captureOpenshellSpy.mockImplementation((args: string[]) => @@ -50,6 +51,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { delete require.cache[gatewayStatePath]; const gatewayDrift = requireDist("../../adapters/openshell/gateway-drift.js"); const openshellRuntime = requireDist("../../adapters/openshell/runtime.js"); + const dockerInfo = requireDist("../../adapters/docker/info.js"); const gatewayRuntime = requireDist("../../gateway-runtime-action.js"); const registry = requireDist("../../state/registry.js"); const crossPortRegistry = requireDist("../../state/registry/cross-port.js"); @@ -65,6 +67,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { recoverNamedGatewayRuntimeSpy = vi .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") .mockResolvedValue({ recovered: false }); + dockerInfoSpy = vi.spyOn(dockerInfo, "dockerInfo").mockReturnValue("Server: available"); getSandboxSpy = vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "instance-a", gatewayName: "nemoclaw", @@ -320,6 +323,41 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); + it("reports a Docker outage instead of treating an uninspectable container as missing", async () => { + mockSandboxPhase("Error"); + getSandboxSpy.mockReturnValue({ + name: "instance-a", + gatewayName: "nemoclaw", + gatewayPort: 8080, + openshellDriver: "docker", + }); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: false, + running: false, + containerName: null, + }); + dockerInfoSpy.mockReturnValue(""); + const lines: string[] = []; + vi.spyOn(console, "error").mockImplementation((line = "") => { + lines.push(String(line)); + }); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + + await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow( + "process.exit(1)", + ); + + const output = lines.join("\n"); + expect(output).toContain("Docker daemon is not reachable"); + expect(output).toContain("do not rebuild, destroy, or re-onboard"); + expect(output).not.toContain("nemoclaw instance-a destroy --yes"); + expect(output).not.toContain("nemoclaw onboard"); + expect(exitSpy).toHaveBeenCalledWith(1); + }); + it("steers a Docker Error sandbox with missing legacy metadata and no container to clean replacement", async () => { mockSandboxPhase("Error"); getSandboxSpy.mockReturnValue({ diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 8a6fb5c67f2..4935c443e41 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -1170,11 +1170,21 @@ export async function ensureLiveSandboxOrExit( " This usually happens when a process crash inside the sandbox prevented clean startup.", ); console.error(""); + const openshellDriver = getKnownSandboxTarget(sandboxName)?.openshellDriver; const recoveryAction = classifySandboxPhaseRecoveryAction({ phase, - openshellDriver: getKnownSandboxTarget(sandboxName)?.openshellDriver, + openshellDriver, dockerContainerName: dockerRuntime.containerName, }); + if ( + recoveryAction === "replace_missing_docker_container" && + isDockerRuntimeDown(sandboxName, { + getSandbox: () => ({ openshellDriver }), + }) + ) { + printDockerRuntimeDownGuidance(sandboxName); + exit(1); + } if (recoveryAction === "replace_missing_docker_container") { console.error( " The Docker-driver container is missing, so NemoClaw cannot back up its live workspace for rebuild.", diff --git a/src/lib/actions/sandbox/status-lookup-rendering.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index eefd13b5bdc..6a444402635 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -17,9 +17,11 @@ async function printGuidance({ phase, dockerRuntime, openshellDriver = "docker", + dockerRuntimeDown = false, }: { phase: string; openshellDriver?: string | null; + dockerRuntimeDown?: boolean; dockerRuntime: { health: "none"; paused: boolean; @@ -36,9 +38,9 @@ async function printGuidance({ dockerRuntime, effectivePreflight: { failure: null, - failureLayer: null, - suppressInferenceProbe: false, - exitCode: 0, + failureLayer: dockerRuntimeDown ? "docker_unreachable" : null, + suppressInferenceProbe: dockerRuntimeDown, + exitCode: dockerRuntimeDown ? 1 : 0, }, }); } @@ -231,6 +233,20 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { expect(text).not.toContain("nemoclaw beta start"); }); + it("reports a Docker outage instead of treating an uninspectable container as missing", async () => { + const cap = captureConsoleLog(); + await expect( + printGuidance({ phase: "Error", dockerRuntime: null, dockerRuntimeDown: true }), + ).rejects.toMatchObject({ exitCode: 1 }); + const text = cap.lines(); + cap.restore(); + + expect(text).toContain("Docker daemon is not reachable"); + expect(text).toContain("do not rebuild, destroy, or re-onboard"); + expect(text).not.toContain("nemoclaw beta destroy --yes"); + expect(text).not.toContain("nemoclaw onboard"); + }); + it("steers a Docker sandbox with missing legacy metadata and no container to clean replacement", async () => { const cap = captureConsoleLog(); await printGuidance({ phase: "Error", openshellDriver: null, dockerRuntime: null }); diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index fafdd0039cb..7a6e42f5627 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -148,6 +148,7 @@ function printPresentSandboxGatewayLookupStatus({ phase, openshellDriver, dockerRuntime, + effectivePreflight, }: SandboxGatewayLookupStatusContext): void { console.log(""); if ("recoveredGateway" in lookup && lookup.recoveredGateway) { @@ -172,7 +173,13 @@ function printPresentSandboxGatewayLookupStatus({ ? lookup.output.replace(/^(\s*Phase:\s*)\S+\s*$/gmu, "$1Stopped") : lookup.output; if (renderedOutput) console.log(renderedOutput); - printNonReadySandboxPhaseGuidance({ sandboxName, phase, openshellDriver, dockerRuntime }); + printNonReadySandboxPhaseGuidance({ + sandboxName, + phase, + openshellDriver, + dockerRuntime, + dockerRuntimeDown: effectivePreflight.failureLayer === "docker_unreachable", + }); } function printWrongGatewayActiveLookupStatus({ @@ -270,11 +277,13 @@ function printNonReadySandboxPhaseGuidance({ phase, openshellDriver, dockerRuntime, + dockerRuntimeDown, }: { sandboxName: string; phase: string | null; openshellDriver: string | null; dockerRuntime: ReturnType | null; + dockerRuntimeDown: boolean; }): void { if (!phase || phase === "Ready") return; if ( @@ -331,6 +340,10 @@ function printNonReadySandboxPhaseGuidance({ openshellDriver, dockerContainerName: dockerRuntime?.containerName, }); + if (recoveryAction === "replace_missing_docker_container" && dockerRuntimeDown) { + printDockerRuntimeDownGuidance(sandboxName, { writer: console.log }); + deferSandboxLifecycleExit(1); + } if (recoveryAction === "replace_missing_docker_container") { console.log( " The Docker-driver container is missing, so NemoClaw cannot back up its live workspace for rebuild.", From 9a001effe0e0f3f39d47f654d2a6b35adcbed593 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 22:56:10 -0700 Subject: [PATCH 12/44] fix(sandbox): make stale registry cleanup actionable Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- docs/manage-sandboxes/recover-rebuild-sandboxes.mdx | 3 ++- src/lib/actions/sandbox/status-flow.test.ts | 2 ++ src/lib/actions/sandbox/status-lookup-rendering.ts | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index c276389427c..6136632cc92 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -54,7 +54,8 @@ NemoClaw cannot back up the live workspace for rebuild. Destroy the stale entry, replacement, and restore a separately created snapshot afterward if one is available. If the sandbox is absent from the live OpenShell gateway, NemoClaw preserves its registry entry. Retry status after the gateway finishes reconnecting. If the sandbox is stuck mid-provision, retry -rebuild after it reappears. Remove the stale entry only when the sandbox was intentionally deleted. +rebuild after it reappears. If the sandbox was intentionally deleted, run +`$$nemoclaw destroy --yes` to remove the stale entry before onboarding a replacement. The `start` command repairs the agent runtime and host-side port forwards. diff --git a/src/lib/actions/sandbox/status-flow.test.ts b/src/lib/actions/sandbox/status-flow.test.ts index 7cc9332450d..9cc70592e01 100644 --- a/src/lib/actions/sandbox/status-flow.test.ts +++ b/src/lib/actions/sandbox/status-flow.test.ts @@ -579,6 +579,8 @@ describe("showSandboxStatus flow", () => { expect(output).toContain("gateway was just recovered via gateway reattach"); expect(output).toContain("No local registry entry was removed by this status check"); expect(output).toContain("nemoclaw alpha status"); + expect(output).toContain("nemoclaw alpha destroy --yes"); + expect(output).toContain("nemoclaw onboard"); expect(exitSpy).toHaveBeenCalledWith(1); expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); expect(harness.getSandboxDockerRuntimeSpy).not.toHaveBeenCalled(); diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index 7a6e42f5627..83b5006df07 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -138,7 +138,7 @@ function printMissingLiveSandboxStatusGuidance({ ` Retry \`${CLI_NAME} ${sandboxName} status\` after the gateway finishes reconnecting.`, ); console.log( - ` If the sandbox was intentionally deleted, run \`${CLI_NAME} list\` to inspect the remaining sandboxes or \`${CLI_NAME} onboard\` to create a new one.`, + ` If the sandbox was intentionally deleted, run \`${CLI_NAME} ${sandboxName} destroy --yes\` to remove the stale local entry, then \`${CLI_NAME} onboard\` to create a replacement.`, ); } From 9d161304b13481d2cf06df63f60560020c9b18e7 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 23:14:21 -0700 Subject: [PATCH 13/44] fix(sandbox): preserve outage recovery evidence Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/sandbox/status-flow.test.ts | 31 +++++++++++++++++ .../sandbox/status-lookup-rendering.test.ts | 4 +++ .../sandbox/status-lookup-rendering.ts | 5 +-- .../sandbox/status-snapshot-recovery.test.ts | 34 +++++++++++++++++++ src/lib/actions/sandbox/status.ts | 13 +++---- 5 files changed, 77 insertions(+), 10 deletions(-) diff --git a/src/lib/actions/sandbox/status-flow.test.ts b/src/lib/actions/sandbox/status-flow.test.ts index 9cc70592e01..4e942a3d4e7 100644 --- a/src/lib/actions/sandbox/status-flow.test.ts +++ b/src/lib/actions/sandbox/status-flow.test.ts @@ -193,6 +193,37 @@ describe("showSandboxStatus flow", () => { }, ); + it("preserves Docker-outage safety guidance for a terminal Error phase", async () => { + const harness = createStatusFlowHarness({ + sandboxEntry: { openshellDriver: "docker" }, + preflight: { + failure: { layer: "docker_unreachable", dockerUnreachable: true }, + failureLayer: "docker_unreachable", + suppressInferenceProbe: true, + exitCode: 1, + }, + lookup: { + state: "present", + output: "Name: alpha\nPhase: Error\nEndpoint: http://127.0.0.1:18789\n", + phase: "Error", + }, + }); + harness.getSandboxDockerRuntimeSpy.mockReturnValue({ + containerName: null, + health: "none", + paused: false, + running: false, + }); + + await expect(harness.showSandboxStatus("alpha")).rejects.toThrow("process.exit(1)"); + + const output = harness.logSpy.mock.calls.flat().join("\n"); + expect(output).toContain("Docker daemon is not reachable"); + expect(output).toContain("do not rebuild, destroy, or re-onboard"); + expect(output).not.toContain("nemoclaw alpha destroy --yes"); + expect(output).not.toContain("nemoclaw onboard"); + }); + it("classifies publication while waiting for the status lifecycle fence (#9203)", async () => { let disposition: { readonly kind: "absent" } | ReturnType = { kind: "absent", diff --git a/src/lib/actions/sandbox/status-lookup-rendering.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index 6a444402635..789de237ebf 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -36,6 +36,7 @@ async function printGuidance({ phase, openshellDriver, dockerRuntime, + dockerRuntimeDown, effectivePreflight: { failure: null, failureLayer: dockerRuntimeDown ? "docker_unreachable" : null, @@ -122,6 +123,7 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { phase: "Stopped", openshellDriver: "docker", dockerRuntime: null, + dockerRuntimeDown: false, effectivePreflight: { failure: null, failureLayer: null, @@ -150,6 +152,7 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { phase: "Stopped", openshellDriver: "docker", dockerRuntime: null, + dockerRuntimeDown: false, effectivePreflight: { failure: null, failureLayer: null, @@ -181,6 +184,7 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { phase: "Running", openshellDriver: "docker", dockerRuntime: null, + dockerRuntimeDown: false, effectivePreflight: { failure: null, failureLayer: null, diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index 83b5006df07..8b77e69dd92 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -28,6 +28,7 @@ type SandboxGatewayLookupStatusContext = { phase: string | null; openshellDriver: string | null; dockerRuntime: ReturnType | null; + dockerRuntimeDown: boolean; effectivePreflight: SandboxStatusPreflightResult; }; @@ -148,7 +149,7 @@ function printPresentSandboxGatewayLookupStatus({ phase, openshellDriver, dockerRuntime, - effectivePreflight, + dockerRuntimeDown, }: SandboxGatewayLookupStatusContext): void { console.log(""); if ("recoveredGateway" in lookup && lookup.recoveredGateway) { @@ -178,7 +179,7 @@ function printPresentSandboxGatewayLookupStatus({ phase, openshellDriver, dockerRuntime, - dockerRuntimeDown: effectivePreflight.failureLayer === "docker_unreachable", + dockerRuntimeDown, }); } diff --git a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts index fa8edb2329d..92e34881d5f 100644 --- a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts @@ -85,6 +85,40 @@ function snapshotDeps(recoveryResult: unknown) { } describe("collectSandboxStatusSnapshot Docker recovery", () => { + it("uses an explicit cross-root sandbox entry instead of the local registry fallback", async () => { + const crossRootSandbox: SandboxEntry = { ...sandbox, openshellDriver: "mxc" }; + const getSandbox = vi.fn(() => null); + const reconcile = vi.fn(async () => ({ + state: "present" as const, + phase: "Error", + output: "Phase: Error", + })); + const deps = { + ...snapshotDeps({ + checked: false, + wasRunning: null, + recovered: false, + forwardRecovered: false, + }), + getSandbox, + reconcile, + }; + + const snapshot = await collectSandboxStatusSnapshot("alpha", { + deps, + sandboxEntry: crossRootSandbox, + suppressInferenceProbe: true, + }); + + expect(getSandbox).not.toHaveBeenCalled(); + expect(reconcile).toHaveBeenCalledWith("alpha"); + expect(snapshot.sb).toEqual(crossRootSandbox); + expect(snapshot.recordedRoute).toEqual({ + provider: crossRootSandbox.provider, + model: crossRootSandbox.model, + }); + }); + it("recovers the delivery chain when OpenShell already reports the restarted container (#7824)", async () => { const deps = { ...snapshotDeps({ diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index 914fdb7a908..770c56f60b9 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -204,14 +204,10 @@ async function showLegacySandboxStatus(sandboxName: string): Promise { // recovery hint (#4495) and the Docker health line below (#3975). const dockerRuntime = lookup.state === "present" ? getSandboxDockerRuntime(sandboxName) : null; const observedPhase = lookup.state === "present" ? (lookup.phase ?? null) : null; - const phase = resolveSandboxStatusPhase( - observedPhase, - snapshot.postRecoveryPreflight ?? preflight, - ); - const effectivePreflight = withoutTerminalPhasePreflight( - snapshot.postRecoveryPreflight ?? preflight, - phase, - ); + const observedPreflight = snapshot.postRecoveryPreflight ?? preflight; + const phase = resolveSandboxStatusPhase(observedPhase, observedPreflight); + const dockerRuntimeDown = observedPreflight.failureLayer === "docker_unreachable"; + const effectivePreflight = withoutTerminalPhasePreflight(observedPreflight, phase); const statusAgent = resolveSandboxStatusAgent(sb?.agent || "openclaw"); printSandboxStatusPreflightHeader(effectivePreflight); if (effectivePreflight.exitCode !== 0) { @@ -254,6 +250,7 @@ async function showLegacySandboxStatus(sandboxName: string): Promise { phase, openshellDriver: sb?.openshellDriver ?? null, dockerRuntime, + dockerRuntimeDown, effectivePreflight, }); From 130334b7484f982a0a6f9fea7f1c72bdd7881635 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 16 Sep 2026 23:54:41 -0700 Subject: [PATCH 14/44] fix(status): align JSON registry authority Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/status-snapshot-recovery.test.ts | 41 ++++++++++++++++++- src/lib/actions/sandbox/status-snapshot.ts | 9 +++- src/lib/actions/sandbox/status.ts | 3 +- src/lib/state/registry.ts | 1 + 4 files changed, 49 insertions(+), 5 deletions(-) diff --git a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts index 92e34881d5f..bb33093c6d0 100644 --- a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts @@ -335,7 +335,46 @@ describe("collectSandboxStatusSnapshot Docker recovery", () => { }); }); -describe("getSandboxStatusReport Docker recovery preflight refresh", () => { +describe("getSandboxStatusReport", () => { + it("uses cross-root sandbox authority for the JSON status report", async () => { + const crossRootSandbox: SandboxEntry = { + ...sandbox, + openshellDriver: "mxc", + gatewayPort: 19000, + }; + const findSandboxAcrossGatewayRoots = vi.fn(() => ({ + entry: crossRootSandbox, + gatewayPort: 19000, + registryFile: "/test/.nemoclaw-gateway-19000/sandboxes.json", + })); + const { getSandbox: _getSandbox, ...deps } = snapshotDeps({ + checked: false, + wasRunning: null, + recovered: false, + forwardRecovered: false, + }); + + const report = await getSandboxStatusReport("alpha", { + ...deps, + findSandboxAcrossGatewayRoots, + getGatewayPresets: async () => [], + getSandboxStatusPreflightImpl: vi.fn(async () => clearPreflight), + reconcile: vi.fn(async () => ({ + state: "present" as const, + phase: "Error", + output: "Phase: Error", + })), + }); + + expect(findSandboxAcrossGatewayRoots).toHaveBeenCalledWith("alpha"); + expect(report.found).toBe(true); + expect(report.openshellDriver).toBe("mxc"); + expect(report.recordedRoute).toEqual({ + provider: crossRootSandbox.provider, + model: crossRootSandbox.model, + }); + }); + it("clears a stale stopped-container preflight after successful recovery", async () => { const getSandboxStatusPreflightImpl = vi .fn() diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 85124ecbfb7..c9307ca0b7e 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -294,6 +294,7 @@ function loadRecoverSandboxProcesses(): RecoverSandboxProcesses { } interface CollectSandboxStatusSnapshotDeps { + findSandboxAcrossGatewayRoots?: typeof registry.findSandboxAcrossGatewayRoots; getSandbox?: typeof registry.getSandbox; updateSandbox?: typeof registry.updateSandbox; listSandboxes?: typeof registry.listSandboxes; @@ -785,14 +786,18 @@ async function buildSandboxStatusReport( const getSandbox = deps.getSandbox ?? ((name: string) => { - const entry = registry.getSandbox(name); + const entry = + (deps.findSandboxAcrossGatewayRoots ?? registry.findSandboxAcrossGatewayRoots)(name) + ?.entry ?? null; return entry && registry.isPublishedSandboxRegistration(entry) ? entry : null; }); + const sandboxEntry = getSandbox(sandboxName); const preflight = await (deps.getSandboxStatusPreflightImpl ?? getSandboxStatusPreflight)( - getSandbox(sandboxName), + sandboxEntry, ); const snapshot = await collectSandboxStatusSnapshot(sandboxName, { preflight, + sandboxEntry, deps, }); const { diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index 770c56f60b9..3dd8b537487 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -8,7 +8,6 @@ import { inspectManagedLlamaCppStatus } from "../../inference/llama-cpp/managed- import { getGatewayPresets } from "../../policy"; import { withSandboxLifecycleLock } from "./lifecycle/lock"; import * as registry from "../../state/registry"; -import { findSandboxAcrossGatewayRoots } from "../../state/registry/cross-port"; import { getSandboxDockerRuntime } from "./docker-health"; import { qualifyPortableAgentLifecycleAuthority, @@ -71,7 +70,7 @@ function inspectHermesPortableStatus( } function getPublishedSandbox(sandboxName: string): registry.SandboxEntry | null { - const entry = findSandboxAcrossGatewayRoots(sandboxName)?.entry ?? null; + const entry = registry.findSandboxAcrossGatewayRoots(sandboxName)?.entry ?? null; return entry && registry.isPublishedSandboxRegistration(entry) ? entry : null; } diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 54ad8a3844a..a33630d7019 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -60,6 +60,7 @@ export { requireSandboxHostLocalInferenceProvenance, }; export { hasLegacyDgxStationQualificationAuthority } from "./registry/rebuild-authority"; +export { findSandboxAcrossGatewayRoots } from "./registry/cross-port"; export { addExtraProvider, listExtraProviders, From 75ac8e6fd4c0c2780f216b031684c4f05a8201b9 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 00:34:21 -0700 Subject: [PATCH 15/44] fix(status): preserve cross-root Docker ownership Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../actions/sandbox/inference-route-health.ts | 11 ++++++ src/lib/actions/sandbox/status-flow.test.ts | 36 +++++++++++++++++-- .../sandbox/status-snapshot-recovery.test.ts | 1 + src/lib/actions/sandbox/status-snapshot.ts | 26 +++++++++----- src/lib/actions/sandbox/status.ts | 14 ++++++-- src/lib/state/registry.ts | 1 - 6 files changed, 75 insertions(+), 14 deletions(-) diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 3f19eef2d84..0f526b33a0e 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -8,6 +8,8 @@ import * as agentRuntime from "../../agent/runtime"; import { REPOSITORY_ROOT } from "../../core/repository-root"; import type { ProviderHealthStatus } from "../../inference/health"; import { RETRIABLE_HTTP_PROBE_STATUSES } from "../../inference/probe/transient-http-policy"; +import type { SandboxEntry } from "../../state/registry"; +import { canSandboxGatewayRouteRealign } from "./connect-inference-gateway"; import { buildSandboxInferenceRouteProbeRequest, classifyInferenceRouteFailureLabel, @@ -33,6 +35,15 @@ export type SandboxInferenceRouteHealth = { detail: string; }; +export function canSandboxStatusRouteRealign( + sandboxName: string, + sandbox: SandboxEntry, + gatewayName: string, + listSandboxes: () => readonly SandboxEntry[], +): boolean { + return canSandboxGatewayRouteRealign(sandboxName, sandbox, gatewayName, listSandboxes()); +} + /** * Probe the authoritative `https://inference.local/v1/models` route from * inside the sandbox using the same agent-aware argv and parser as connect. diff --git a/src/lib/actions/sandbox/status-flow.test.ts b/src/lib/actions/sandbox/status-flow.test.ts index 4e942a3d4e7..dcef9c634f4 100644 --- a/src/lib/actions/sandbox/status-flow.test.ts +++ b/src/lib/actions/sandbox/status-flow.test.ts @@ -122,7 +122,7 @@ describe("showSandboxStatus flow", () => { "alpha", expect.anything(), ); - expect(harness.getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("alpha"); + expect(harness.getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("alpha", expect.any(Object)); expect(harness.withMcpLifecycleLockSpy).toHaveBeenCalledWith("alpha", expect.any(Function)); }); @@ -193,6 +193,38 @@ describe("showSandboxStatus flow", () => { }, ); + it("uses the cross-root Docker entry before recommending Error recovery", async () => { + const harness = createStatusFlowHarness({ + sandboxEntry: { openshellDriver: "docker" }, + registryEntry: "missing", + publishedAcrossGatewayRoots: true, + lookup: { + state: "present", + output: "Name: alpha\nPhase: Error\nEndpoint: http://127.0.0.1:18789\n", + phase: "Error", + recoveredGateway: true, + recoveryVia: "gateway reattach", + }, + }); + harness.getSandboxDockerRuntimeSpy.mockReturnValue({ + containerName: "openshell-alpha", + health: "healthy", + paused: false, + running: true, + }); + + await expect(harness.showSandboxStatus("alpha")).resolves.toBeUndefined(); + + const output = harness.logSpy.mock.calls.flat().join("\n"); + expect(output).toContain("nemoclaw alpha start"); + expect(output).not.toContain("nemoclaw alpha destroy --yes"); + const [, dockerRuntimeDeps] = harness.getSandboxDockerRuntimeSpy.mock.calls[0] ?? []; + expect(dockerRuntimeDeps.getSandbox("alpha")).toMatchObject({ + name: "alpha", + openshellDriver: "docker", + }); + }); + it("preserves Docker-outage safety guidance for a terminal Error phase", async () => { const harness = createStatusFlowHarness({ sandboxEntry: { openshellDriver: "docker" }, @@ -369,7 +401,7 @@ describe("showSandboxStatus flow", () => { expect(output).toContain("unhealthy"); expect(output).toContain("NIM: running (alpha-nim)"); expect(harness.getActiveSandboxSessionsSpy).toHaveBeenCalledWith("alpha", expect.any(Object)); - expect(harness.getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("alpha"); + expect(harness.getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("alpha", expect.any(Object)); expect(exitSpy).not.toHaveBeenCalled(); }); diff --git a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts index bb33093c6d0..f5152228384 100644 --- a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts @@ -73,6 +73,7 @@ function snapshotDeps(recoveryResult: unknown) { return { getSandbox: () => sandbox, listSandboxes: () => ({ sandboxes: [sandbox], defaultSandbox: sandbox.name }), + listPublishedSandboxNamesAcrossGatewayRoots: () => [sandbox.name], reconcile: recoveredLookup, captureOpenshellForStatusImpl: async () => { throw new Error("live route lookup not needed"); diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index c9307ca0b7e..a84c568b8b5 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -27,7 +27,6 @@ import { type ProviderHealthStatus, probeProviderHealth, } from "../../inference/health"; -import type { ServingProfileProvenance } from "../../inference/serving/types"; import { type DcodeAutoApprovalMode, normalizeDcodeAutoApprovalMode, @@ -36,12 +35,16 @@ import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { getGatewayPresets } from "../../policy"; import { redact } from "../../security/redact"; import * as registry from "../../state/registry"; -import { canSandboxGatewayRouteRealign } from "./connect-inference-gateway"; +import { + findSandboxAcrossGatewayRoots, + listPublishedSandboxNamesAcrossGatewayRoots, +} from "../../state/registry/cross-port"; import { getSandboxDockerRuntime } from "./docker-health"; import type { SandboxGatewayState } from "./gateway-state"; import { getReconciledSandboxGatewayState, getSandboxGatewayStateForStatus } from "./gateway-state"; import { buildSandboxInferenceRouteHealth, + canSandboxStatusRouteRealign, isTransientInferenceInvocationFailure, type ProbeSandboxInferenceInvocation, probeSandboxInferenceGatewayHealth, @@ -162,7 +165,7 @@ export interface SandboxStatusReport { agentLoadError?: string; model: string; provider: string; - servingProfileProvenance: ServingProfileProvenance | null; + servingProfileProvenance: NonNullable | null; llamaCpp?: LlamaCppRouteDetails | null; recordedRoute: RecordedInferenceRoute | null; liveRoute: GatewayInference | null; @@ -294,7 +297,8 @@ function loadRecoverSandboxProcesses(): RecoverSandboxProcesses { } interface CollectSandboxStatusSnapshotDeps { - findSandboxAcrossGatewayRoots?: typeof registry.findSandboxAcrossGatewayRoots; + findSandboxAcrossGatewayRoots?: typeof findSandboxAcrossGatewayRoots; + listPublishedSandboxNamesAcrossGatewayRoots?: typeof listPublishedSandboxNamesAcrossGatewayRoots; getSandbox?: typeof registry.getSandbox; updateSandbox?: typeof registry.updateSandbox; listSandboxes?: typeof registry.listSandboxes; @@ -597,11 +601,11 @@ export async function collectSandboxStatusSnapshot( canConnect: Boolean( sb && gatewayName && - canSandboxGatewayRouteRealign( + canSandboxStatusRouteRealign( sandboxName, sb, gatewayName, - (opts.deps?.listSandboxes ?? registry.listSandboxes)().sandboxes, + () => (opts.deps?.listSandboxes ?? registry.listSandboxes)().sandboxes, ), ), } @@ -787,8 +791,7 @@ async function buildSandboxStatusReport( deps.getSandbox ?? ((name: string) => { const entry = - (deps.findSandboxAcrossGatewayRoots ?? registry.findSandboxAcrossGatewayRoots)(name) - ?.entry ?? null; + (deps.findSandboxAcrossGatewayRoots ?? findSandboxAcrossGatewayRoots)(name)?.entry ?? null; return entry && registry.isPublishedSandboxRegistration(entry) ? entry : null; }); const sandboxEntry = getSandbox(sandboxName); @@ -815,7 +818,12 @@ async function buildSandboxStatusReport( } = snapshot; const dockerRuntime = lookup.state === "present" && hasLegacyStatusRuntimeObservation(sb) - ? getSandboxDockerRuntime(sandboxName) + ? getSandboxDockerRuntime(sandboxName, { + getSandbox: () => sb, + listSandboxNames: + deps.listPublishedSandboxNamesAcrossGatewayRoots ?? + listPublishedSandboxNamesAcrossGatewayRoots, + }) : null; const observedPhase = lookup.state === "present" ? (lookup.phase ?? null) : null; const phase = resolveSandboxStatusPhase( diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index 3dd8b537487..4a6c6dc5bb0 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -8,6 +8,10 @@ import { inspectManagedLlamaCppStatus } from "../../inference/llama-cpp/managed- import { getGatewayPresets } from "../../policy"; import { withSandboxLifecycleLock } from "./lifecycle/lock"; import * as registry from "../../state/registry"; +import { + findSandboxAcrossGatewayRoots, + listPublishedSandboxNamesAcrossGatewayRoots, +} from "../../state/registry/cross-port"; import { getSandboxDockerRuntime } from "./docker-health"; import { qualifyPortableAgentLifecycleAuthority, @@ -70,7 +74,7 @@ function inspectHermesPortableStatus( } function getPublishedSandbox(sandboxName: string): registry.SandboxEntry | null { - const entry = registry.findSandboxAcrossGatewayRoots(sandboxName)?.entry ?? null; + const entry = findSandboxAcrossGatewayRoots(sandboxName)?.entry ?? null; return entry && registry.isPublishedSandboxRegistration(entry) ? entry : null; } @@ -201,7 +205,13 @@ async function showLegacySandboxStatus(sandboxName: string): Promise { } = snapshot; // Resolve the docker-driver container once: reused for the paused-container // recovery hint (#4495) and the Docker health line below (#3975). - const dockerRuntime = lookup.state === "present" ? getSandboxDockerRuntime(sandboxName) : null; + const dockerRuntime = + lookup.state === "present" + ? getSandboxDockerRuntime(sandboxName, { + getSandbox: () => sandboxEntry, + listSandboxNames: listPublishedSandboxNamesAcrossGatewayRoots, + }) + : null; const observedPhase = lookup.state === "present" ? (lookup.phase ?? null) : null; const observedPreflight = snapshot.postRecoveryPreflight ?? preflight; const phase = resolveSandboxStatusPhase(observedPhase, observedPreflight); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index a33630d7019..54ad8a3844a 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -60,7 +60,6 @@ export { requireSandboxHostLocalInferenceProvenance, }; export { hasLegacyDgxStationQualificationAuthority } from "./registry/rebuild-authority"; -export { findSandboxAcrossGatewayRoots } from "./registry/cross-port"; export { addExtraProvider, listExtraProviders, From 438eda06431a549b1a09974137ff062cda40f966 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 01:27:50 -0700 Subject: [PATCH 16/44] fix(status): preserve cross-root recovery authority Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/sandbox/docker-health.ts | 22 ++++--- .../sandbox/gateway-state-hints.test.ts | 61 ++++++++++++++++++- src/lib/actions/sandbox/gateway-state.ts | 15 +++-- .../actions/sandbox/inference-route-health.ts | 11 ---- .../status-snapshot-inference-health.test.ts | 2 +- .../sandbox/status-snapshot-recovery.test.ts | 2 +- .../status-snapshot-route-drift.test.ts | 54 +++++++++++++--- src/lib/actions/sandbox/status-snapshot.ts | 24 +++++--- src/lib/actions/sandbox/status.ts | 2 +- src/lib/state/registry/cross-port.test.ts | 13 ++++ src/lib/state/registry/cross-port.ts | 16 ++++- 11 files changed, 176 insertions(+), 46 deletions(-) diff --git a/src/lib/actions/sandbox/docker-health.ts b/src/lib/actions/sandbox/docker-health.ts index 69f2aac13a6..416d28d67a6 100644 --- a/src/lib/actions/sandbox/docker-health.ts +++ b/src/lib/actions/sandbox/docker-health.ts @@ -6,6 +6,11 @@ import { dockerCapture } from "../../adapters/docker/run"; import { resolveSandboxContainerOwner } from "../../domain/sandbox/container-owner"; import { findLabeledSandboxContainers } from "../../onboard/docker-driver-sandbox-recovery"; import * as registry from "../../state/registry"; +import { + findSandboxAcrossGatewayRoots, + listPublishedSandboxNamesAcrossGatewayRoots, +} from "../../state/registry/cross-port"; +import type { SandboxEntry } from "../../state/registry/types"; export type DockerHealthState = "healthy" | "unhealthy" | "starting" | "none" | "unknown"; @@ -29,7 +34,7 @@ export interface SandboxDockerRuntime { } interface ResolveDeps { - getSandbox: (name: string) => registry.SandboxEntry | null; + getSandbox: (name: string) => SandboxEntry | null; listSandboxNames: () => string[]; dockerPsNames: () => string; findLabeledSandboxContainers: typeof findLabeledSandboxContainers; @@ -37,13 +42,16 @@ interface ResolveDeps { dockerInspectPaused: (containerName: string) => string; } +export function listPublishedSandboxNamesForDockerRuntime(): string[] { + return listPublishedSandboxNamesAcrossGatewayRoots(); +} + const defaultDeps: ResolveDeps = { - getSandbox: (name) => registry.getSandbox(name), - listSandboxNames: () => - registry - .listSandboxes() - .sandboxes.filter(registry.isPublishedSandboxRegistration) - .map((entry) => entry.name), + getSandbox: (name) => { + const entry = findSandboxAcrossGatewayRoots(name)?.entry ?? null; + return entry && registry.isPublishedSandboxRegistration(entry) ? entry : null; + }, + listSandboxNames: listPublishedSandboxNamesForDockerRuntime, dockerPsNames: () => dockerCapture(["ps", "--format", "{{.Names}}"], { ignoreError: true }), findLabeledSandboxContainers: (sandboxName) => findLabeledSandboxContainers(sandboxName), dockerInspectHealth: (containerName) => diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index c1a223df3f2..7c1ca618d51 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -32,6 +32,8 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { let getNamedGatewayLifecycleStateSpy: MockInstance; let getSandboxSpy: MockInstance; let findSandboxAcrossGatewayRootsSpy: MockInstance; + let listPublishedSandboxNamesAcrossGatewayRootsSpy: MockInstance; + let listPublishedSandboxNamesForDockerRuntime: () => string[]; let recoverNamedGatewayRuntimeSpy: MockInstance; let dockerInfoSpy: MockInstance; @@ -56,6 +58,8 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { const registry = requireDist("../../state/registry.js"); const crossPortRegistry = requireDist("../../state/registry/cross-port.js"); const dockerHealth = requireDist("./docker-health.js"); + listPublishedSandboxNamesForDockerRuntime = + dockerHealth.listPublishedSandboxNamesForDockerRuntime; const gatewaySelect = requireDist("./gateway-select.js"); vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockResolvedValue(null); vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockResolvedValue(null); @@ -81,6 +85,9 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { ? { entry, gatewayPort: entry.gatewayPort ?? null, registryFile: "/test/sandboxes.json" } : null; }); + listPublishedSandboxNamesAcrossGatewayRootsSpy = vi + .spyOn(crossPortRegistry, "listPublishedSandboxNamesAcrossGatewayRoots") + .mockReturnValue(["instance-a"]); getSandboxDockerRuntimeSpy = vi.spyOn(dockerHealth, "getSandboxDockerRuntime").mockReturnValue({ health: "none", paused: false, @@ -283,10 +290,57 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(output).toContain("use it only if start does not recover the sandbox"); expect(output).not.toContain("stopped container"); expect(output).not.toContain("docker unpause"); - expect(getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("instance-a"); + expect(getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("instance-a", { + getSandbox: expect.any(Function), + listSandboxNames: listPublishedSandboxNamesForDockerRuntime, + }); expect(exitSpy).toHaveBeenCalledWith(1); }); + it("keeps start guidance for a cross-root Docker Error sandbox with an owned container", async () => { + mockSandboxPhase("Error"); + const crossRootEntry = { + name: "instance-a", + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, + openshellDriver: "docker", + }; + getSandboxSpy.mockReturnValue(null); + findSandboxAcrossGatewayRootsSpy.mockReturnValue({ + entry: crossRootEntry, + gatewayPort: 8081, + registryFile: "/test/.nemoclaw/gateways/8081/sandboxes.json", + }); + listPublishedSandboxNamesAcrossGatewayRootsSpy.mockReturnValue(["instance-a", "peer"]); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: false, + running: true, + containerName: "openshell-instance-a-cross-root", + }); + const lines: string[] = []; + vi.spyOn(console, "error").mockImplementation((line = "") => { + lines.push(String(line)); + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + + await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow( + "process.exit(1)", + ); + + const output = lines.join("\n"); + expect(output).toContain("nemoclaw instance-a start"); + expect(output).not.toContain("nemoclaw instance-a destroy --yes"); + const [, runtimeDeps] = getSandboxDockerRuntimeSpy.mock.calls.at(-1) as [ + string, + { getSandbox: (name: string) => unknown; listSandboxNames: () => string[] }, + ]; + expect(runtimeDeps.getSandbox("instance-a")).toEqual(crossRootEntry); + expect(runtimeDeps.listSandboxNames()).toEqual(["instance-a", "peer"]); + }); + it("steers a Docker-driver Error sandbox without its container to clean replacement", async () => { mockSandboxPhase("Error"); getSandboxSpy.mockReturnValue({ @@ -482,7 +536,10 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(output).toContain("nemoclaw instance-a rebuild --yes"); expect(output).not.toContain("nemoclaw instance-a start"); expect(output).not.toContain("docker unpause"); - expect(getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("instance-a"); + expect(getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("instance-a", { + getSandbox: expect.any(Function), + listSandboxNames: listPublishedSandboxNamesForDockerRuntime, + }); expect(exitSpy).toHaveBeenCalledWith(1); }); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 4935c443e41..8055622324e 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -100,7 +100,10 @@ import { usesLegacyRuntimeLifecycleCompatibility, } from "../../state/registry/lifecycle-generation"; import type { SandboxEntry } from "../../state/registry/types"; -import { getSandboxDockerRuntime } from "./docker-health"; +import { + getSandboxDockerRuntime, + listPublishedSandboxNamesForDockerRuntime, +} from "./docker-health"; import { classifySandboxPhaseRecoveryAction, isDockerRuntimeDown, @@ -1126,6 +1129,7 @@ export async function ensureLiveSandboxOrExit( selectOwningGateway, }); if (lookup.state === "present") { + const sandboxEntry = getKnownSandboxTarget(sandboxName); const phase = lookup.phase ?? null; // A policy read can fail because the Docker-backed gateway is unavailable. // Preserve the more specific host-runtime diagnosis even for probe-only @@ -1135,7 +1139,7 @@ export async function ensureLiveSandboxOrExit( phase !== "Ready" && phase !== "Running" && !isTerminalSandboxPhase(phase) && - isDockerRuntimeDown(sandboxName) + isDockerRuntimeDown(sandboxName, { getSandbox: () => sandboxEntry }) ) { printDockerRuntimeDownGuidance(sandboxName); exit(1); @@ -1145,7 +1149,10 @@ export async function ensureLiveSandboxOrExit( exit(1); } if (!allowNonReadyPhase && phase && phase !== "Ready" && phase !== "Running") { - const dockerRuntime = getSandboxDockerRuntime(sandboxName); + const dockerRuntime = getSandboxDockerRuntime(sandboxName, { + getSandbox: () => sandboxEntry, + listSandboxNames: listPublishedSandboxNamesForDockerRuntime, + }); if (dockerRuntime.containerName && !dockerRuntime.running && !dockerRuntime.paused) { console.error(` Sandbox '${sandboxName}' is stopped.`); console.error(" Workspace state is preserved."); @@ -1170,7 +1177,7 @@ export async function ensureLiveSandboxOrExit( " This usually happens when a process crash inside the sandbox prevented clean startup.", ); console.error(""); - const openshellDriver = getKnownSandboxTarget(sandboxName)?.openshellDriver; + const openshellDriver = sandboxEntry?.openshellDriver; const recoveryAction = classifySandboxPhaseRecoveryAction({ phase, openshellDriver, diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 0f526b33a0e..3f19eef2d84 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -8,8 +8,6 @@ import * as agentRuntime from "../../agent/runtime"; import { REPOSITORY_ROOT } from "../../core/repository-root"; import type { ProviderHealthStatus } from "../../inference/health"; import { RETRIABLE_HTTP_PROBE_STATUSES } from "../../inference/probe/transient-http-policy"; -import type { SandboxEntry } from "../../state/registry"; -import { canSandboxGatewayRouteRealign } from "./connect-inference-gateway"; import { buildSandboxInferenceRouteProbeRequest, classifyInferenceRouteFailureLabel, @@ -35,15 +33,6 @@ export type SandboxInferenceRouteHealth = { detail: string; }; -export function canSandboxStatusRouteRealign( - sandboxName: string, - sandbox: SandboxEntry, - gatewayName: string, - listSandboxes: () => readonly SandboxEntry[], -): boolean { - return canSandboxGatewayRouteRealign(sandboxName, sandbox, gatewayName, listSandboxes()); -} - /** * Probe the authoritative `https://inference.local/v1/models` route from * inside the sandbox using the same agent-aware argv and parser as connect. diff --git a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts index c54b4b57c25..4b7c352d1ac 100644 --- a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts @@ -31,7 +31,7 @@ function snapshotDeps( suppressInferenceProbe: false, deps: { getSandbox: () => sandbox, - listSandboxes: () => ({ sandboxes: [sandbox], defaultSandbox: sandbox.name }), + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], reconcile: async () => ({ state: "present" as const, output: "Phase: Ready" }), // The live-route RPC lookup is independent of the authoritative // inference.local gateway probe under test; throwing here just leaves diff --git a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts index f5152228384..5233b5faa1d 100644 --- a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts @@ -72,7 +72,7 @@ function snapshotDeps(recoveryResult: unknown) { const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => healthyRoute); return { getSandbox: () => sandbox, - listSandboxes: () => ({ sandboxes: [sandbox], defaultSandbox: sandbox.name }), + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], listPublishedSandboxNamesAcrossGatewayRoots: () => [sandbox.name], reconcile: recoveredLookup, captureOpenshellForStatusImpl: async () => { diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index a7dd0b9c712..a6269873f0e 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -40,10 +40,7 @@ function snapshotDeps(entry: Partial | null) { suppressInferenceProbe: true, deps: { getSandbox: () => sandbox, - listSandboxes: () => ({ - sandboxes: sandbox ? [sandbox] : [], - defaultSandbox: sandbox ? sandbox.name : null, - }), + listPublishedSandboxesAcrossGatewayRoots: () => (sandbox ? [sandbox] : []), reconcile: async () => ({ state: "present", output: "Phase: Ready" }), }, }; @@ -205,15 +202,54 @@ describe("collectSandboxStatusSnapshot route drift", () => { preferredInferenceApi: "openai-completions", }; const options = snapshotDeps(target); - options.deps.listSandboxes = () => ({ - sandboxes: [options.deps.getSandbox() as SandboxEntry, peer], - defaultSandbox: "alpha", - }); + options.deps.listPublishedSandboxesAcrossGatewayRoots = () => [ + options.deps.getSandbox() as SandboxEntry, + peer, + ]; const snapshot = await collectSandboxStatusSnapshot("alpha", options); expect(snapshot.routeDrift).toMatchObject({ canConnect: false }); }); + + it("does not advertise connect when a cross-root gateway peer has a conflicting route", async () => { + liveGatewayInference("openai", "live/model", "nemoclaw-9090"); + const target: SandboxEntry = { + name: "alpha", + agent: "openclaw", + gatewayPort: 9090, + provider: "compatible-endpoint", + model: "recorded/model", + endpointUrl: "https://target.example/v1", + credentialEnv: "TARGET_KEY", + preferredInferenceApi: "openai-completions", + }; + const peer: SandboxEntry = { + name: "peer", + agent: "openclaw", + gatewayPort: 9090, + provider: "compatible-endpoint", + model: "peer/model", + endpointUrl: "https://peer.example/v1", + credentialEnv: "PEER_KEY", + preferredInferenceApi: "openai-completions", + }; + const options = snapshotDeps(target); + const { getSandbox: _getSandbox, ...deps } = options.deps; + + const report = await getSandboxStatusReport("alpha", { + ...deps, + findSandboxAcrossGatewayRoots: () => ({ + entry: target, + gatewayPort: 9090, + registryFile: "/test/.nemoclaw/gateways/9090/sandboxes.json", + }), + listPublishedSandboxesAcrossGatewayRoots: () => [target, peer], + getGatewayPresets: async () => [], + }); + + expect(report.routeDrift).toMatchObject({ canConnect: false }); + }); }); describe("getSandboxStatusReport llama.cpp attribution on drift (#10256)", () => { @@ -336,7 +372,7 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = const snapshot = await collectSandboxStatusSnapshot("alpha", { deps: { getSandbox: () => sandbox, - listSandboxes: () => ({ sandboxes: [sandbox], defaultSandbox: "alpha" }), + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], reconcile: async () => ({ state: "present", output: "Phase: Ready" }), probeProviderHealthImpl: () => null, probeSandboxInferenceGatewayHealthImpl: async () => ({ diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index a84c568b8b5..cbb1cda9b30 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -32,19 +32,19 @@ import { normalizeDcodeAutoApprovalMode, } from "../../onboard/dcode-auto-approval"; import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; -import { getGatewayPresets } from "../../policy"; import { redact } from "../../security/redact"; import * as registry from "../../state/registry"; import { findSandboxAcrossGatewayRoots, listPublishedSandboxNamesAcrossGatewayRoots, + listPublishedSandboxesAcrossGatewayRoots, } from "../../state/registry/cross-port"; +import { canSandboxGatewayRouteRealign } from "./connect-inference-gateway"; import { getSandboxDockerRuntime } from "./docker-health"; import type { SandboxGatewayState } from "./gateway-state"; import { getReconciledSandboxGatewayState, getSandboxGatewayStateForStatus } from "./gateway-state"; import { buildSandboxInferenceRouteHealth, - canSandboxStatusRouteRealign, isTransientInferenceInvocationFailure, type ProbeSandboxInferenceInvocation, probeSandboxInferenceGatewayHealth, @@ -72,6 +72,7 @@ type ProbeSandboxInferenceGatewayHealth = ( ...args: Parameters ) => ReturnType; type DelayInferenceRecoveryProbe = (delayMs: number) => Promise; +type GetGatewayPresets = (typeof import("../../policy"))["getGatewayPresets"]; const INFERENCE_PROBE_ATTEMPTS = 3; const INFERENCE_PROBE_RETRY_DELAY_MS = 2_000; @@ -299,9 +300,9 @@ function loadRecoverSandboxProcesses(): RecoverSandboxProcesses { interface CollectSandboxStatusSnapshotDeps { findSandboxAcrossGatewayRoots?: typeof findSandboxAcrossGatewayRoots; listPublishedSandboxNamesAcrossGatewayRoots?: typeof listPublishedSandboxNamesAcrossGatewayRoots; + listPublishedSandboxesAcrossGatewayRoots?: typeof listPublishedSandboxesAcrossGatewayRoots; getSandbox?: typeof registry.getSandbox; updateSandbox?: typeof registry.updateSandbox; - listSandboxes?: typeof registry.listSandboxes; captureOpenshellForStatusImpl?: typeof captureOpenshellForStatus; probeProviderHealthImpl?: ProbeProviderHealth; probeSandboxInferenceGatewayHealthImpl?: ProbeSandboxInferenceGatewayHealth; @@ -313,7 +314,7 @@ interface CollectSandboxStatusSnapshotDeps { recoverSandboxProcesses?: RecoverSandboxProcesses; reconcile?: ReconcileSandboxGatewayState; getSandboxStatusPreflightImpl?: typeof getSandboxStatusPreflight; - getGatewayPresets?: typeof getGatewayPresets; + getGatewayPresets?: GetGatewayPresets; inspectManagedLlamaCppOwnership?: typeof inspectManagedLlamaCppOwnership; } @@ -601,11 +602,14 @@ export async function collectSandboxStatusSnapshot( canConnect: Boolean( sb && gatewayName && - canSandboxStatusRouteRealign( + canSandboxGatewayRouteRealign( sandboxName, sb, gatewayName, - () => (opts.deps?.listSandboxes ?? registry.listSandboxes)().sandboxes, + ( + opts.deps?.listPublishedSandboxesAcrossGatewayRoots ?? + listPublishedSandboxesAcrossGatewayRoots + )(), ), ), } @@ -836,7 +840,11 @@ async function buildSandboxStatusReport( ); const sandboxGpuEnabled = sb ? (sb.sandboxGpuEnabled ?? sb.gpuEnabled === true) : false; const hostMounts = normalizeSandboxStatusHostMounts(sb?.hostMounts); - const livePolicies = sb ? await (deps.getGatewayPresets ?? getGatewayPresets)(sandboxName) : []; + // The outer status action owns the live policy reader. Direct snapshot callers + // without that boundary report policy availability honestly instead of + // reaching into policy state through a second orchestration path. + const livePolicies = + sb && deps.getGatewayPresets ? await deps.getGatewayPresets(sandboxName) : []; const agent = resolveSandboxStatusAgent(sb?.agent || "openclaw"); return { schemaVersion: 1, @@ -871,7 +879,7 @@ async function buildSandboxStatusReport( openshellDriver: (sb && sb.openshellDriver) || "unknown", openshellVersion: (sb && sb.openshellVersion) || "unknown", policies: livePolicies ?? [], - policiesAvailable: livePolicies !== null, + policiesAvailable: !sb || Boolean(deps.getGatewayPresets) ? livePolicies !== null : false, failureLayer: effectivePreflight.failureLayer, terminalRuntimeHealth, dockerPaused: !!dockerRuntime?.paused, diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index 4a6c6dc5bb0..7f5bd59e36b 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -137,7 +137,7 @@ export async function getSandboxStatusReport( deps.getGatewayPresets ?? getGatewayPresets, ); } - return getLegacySandboxStatusReport(sandboxName, deps); + return getLegacySandboxStatusReport(sandboxName, { getGatewayPresets, ...deps }); }); } diff --git a/src/lib/state/registry/cross-port.test.ts b/src/lib/state/registry/cross-port.test.ts index 383bc634605..c3bb586db37 100644 --- a/src/lib/state/registry/cross-port.test.ts +++ b/src/lib/state/registry/cross-port.test.ts @@ -122,20 +122,33 @@ describe("listSandboxNamesAcrossGatewayRoots", () => { }); const { listPublishedSandboxNamesAcrossGatewayRoots, + listPublishedSandboxesAcrossGatewayRoots, listPendingSandboxNamesAcrossGatewayRoots, } = await loadModule(); expect(listPublishedSandboxNamesAcrossGatewayRoots()).toEqual(["owner-b", "owner-a"]); + expect( + listPublishedSandboxesAcrossGatewayRoots().map(({ name, gatewayPort }) => ({ + name, + gatewayPort, + })), + ).toEqual([ + { name: "owner-b", gatewayPort: 8080 }, + { name: "owner-a", gatewayPort: 8245 }, + { name: "owner-b", gatewayPort: 8245 }, + ]); expect(listPendingSandboxNamesAcrossGatewayRoots()).toEqual(["reserved", "pending"]); }); it("returns empty lists when no registry roots exist", async () => { const { listPublishedSandboxNamesAcrossGatewayRoots, + listPublishedSandboxesAcrossGatewayRoots, listPendingSandboxNamesAcrossGatewayRoots, } = await loadModule(); expect(listPublishedSandboxNamesAcrossGatewayRoots()).toEqual([]); + expect(listPublishedSandboxesAcrossGatewayRoots()).toEqual([]); expect(listPendingSandboxNamesAcrossGatewayRoots()).toEqual([]); }); }); diff --git a/src/lib/state/registry/cross-port.ts b/src/lib/state/registry/cross-port.ts index a751baf6628..6bd506fdc09 100644 --- a/src/lib/state/registry/cross-port.ts +++ b/src/lib/state/registry/cross-port.ts @@ -92,11 +92,16 @@ export function findSandboxAcrossGatewayRoots( return matches[0]; } +function listEntriesAcrossGatewayRoots(published: boolean, home: string): SandboxEntry[] { + return listSandboxHitsAcrossGatewayRoots(home) + .map(({ entry }) => entry) + .filter((entry) => (entry.pendingRouteReservation === true) === !published); +} + function listNamesAcrossGatewayRoots(published: boolean, home: string): string[] { const names: string[] = []; const seen = new Set(); - for (const { entry } of listSandboxHitsAcrossGatewayRoots(home)) { - if ((entry.pendingRouteReservation === true) !== !published) continue; + for (const entry of listEntriesAcrossGatewayRoots(published, home)) { if (seen.has(entry.name)) continue; seen.add(entry.name); names.push(entry.name); @@ -104,6 +109,13 @@ function listNamesAcrossGatewayRoots(published: boolean, home: string): string[] return names; } +/** Published sandbox entries across every registry root, base root first, then ports ascending. */ +export function listPublishedSandboxesAcrossGatewayRoots( + home: string = resolveHome(), +): SandboxEntry[] { + return listEntriesAcrossGatewayRoots(true, home); +} + /** Published sandbox names across every registry root, base root first, then ports ascending. */ export function listPublishedSandboxNamesAcrossGatewayRoots( home: string = resolveHome(), From 0238b612cf8340677299b5c0dd481c8cc1a97f62 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 02:00:36 -0700 Subject: [PATCH 17/44] fix(status): complete cross-root runtime classification Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/sandbox/docker-health.test.ts | 85 +++++++++++++++---- .../gateway-failure-classifier.test.ts | 55 ++++++++++-- .../sandbox/gateway-failure-classifier.ts | 12 +-- 3 files changed, 119 insertions(+), 33 deletions(-) diff --git a/src/lib/actions/sandbox/docker-health.test.ts b/src/lib/actions/sandbox/docker-health.test.ts index 1d00828961f..834cd581481 100644 --- a/src/lib/actions/sandbox/docker-health.test.ts +++ b/src/lib/actions/sandbox/docker-health.test.ts @@ -1,11 +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 { describe, expect, it, vi } from "vitest"; -import * as registry from "../../state/registry"; import type { SandboxEntry } from "../../state/registry"; import { getSandboxDockerHealth, getSandboxDockerRuntime } from "./docker-health"; +function writeRegistry( + home: string, + relativeDirectory: string, + sandboxes: Record, +): void { + const directory = path.join(home, ".nemoclaw", relativeDirectory); + fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync( + path.join(directory, "sandboxes.json"), + JSON.stringify({ defaultSandbox: null, defaultSelectionRevision: 1, sandboxes }), + ); +} + function fixture({ driver = "docker", psNames = "openshell-cluster-nemoclaw\nopenshell-my-assistant-12ab\nopenshell-other-aa11", @@ -62,28 +78,29 @@ function fixture({ describe("getSandboxDockerHealth", () => { it("excludes created pending registrations from container ownership (#9733)", () => { - const listSpy = vi.spyOn(registry, "listSandboxes").mockReturnValue({ - sandboxes: [ - { name: "my", pendingRouteReservation: undefined }, - { - name: "my-assistant", - pendingRouteReservation: true, - createdAt: "2026-08-20T00:00:00.000Z", - }, - ], - defaultSandbox: null, + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-health-pending-")); + writeRegistry(home, "", { + my: { name: "my" }, + "my-assistant": { + name: "my-assistant", + pendingRouteReservation: true, + createdAt: "2026-08-20T00:00:00.000Z", + }, }); + vi.stubEnv("HOME", home); const { listSandboxNames: _listSandboxNames, ...deps } = fixture({ psNames: "openshell-my-assistant-12ab", healthRaw: "healthy", }); - const result = getSandboxDockerHealth("my", deps); - listSpy.mockRestore(); - - expect(result).toEqual({ - state: "healthy", - containerName: "openshell-my-assistant-12ab", - }); + try { + expect(getSandboxDockerHealth("my", deps)).toEqual({ + state: "healthy", + containerName: "openshell-my-assistant-12ab", + }); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } }); it("returns the docker container health when the sandbox runs on the docker driver", () => { @@ -197,6 +214,38 @@ describe("getSandboxDockerHealth", () => { }); describe("getSandboxDockerRuntime (#4495)", () => { + it("resolves an owned container from a sibling gateway registry by default", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-docker-health-cross-root-")); + writeRegistry(home, path.join("gateways", "8081"), { + "my-assistant": { + name: "my-assistant", + gatewayPort: 8081, + openshellDriver: "docker", + }, + }); + vi.stubEnv("HOME", home); + const { + getSandbox: _getSandbox, + listSandboxNames: _listSandboxNames, + ...dockerObservations + } = fixture({ + psNames: "openshell-my-assistant-live", + psAllNames: "openshell-my-assistant-live", + healthRaw: "healthy", + }); + try { + expect(getSandboxDockerRuntime("my-assistant", dockerObservations)).toEqual({ + health: "healthy", + paused: false, + running: true, + containerName: "openshell-my-assistant-live", + }); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("ignores matching container names without OpenShell ownership labels", () => { const deps = fixture({ psNames: "openshell-my-assistant-live\n", diff --git a/src/lib/actions/sandbox/gateway-failure-classifier.test.ts b/src/lib/actions/sandbox/gateway-failure-classifier.test.ts index f7a45742d29..fb86c7879b1 100644 --- a/src/lib/actions/sandbox/gateway-failure-classifier.test.ts +++ b/src/lib/actions/sandbox/gateway-failure-classifier.test.ts @@ -4,6 +4,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const getSandboxMock = vi.fn(); +const findSandboxAcrossGatewayRootsMock = vi.fn((...args: unknown[]) => { + const entry = getSandboxMock(...args); + return entry + ? { entry, gatewayPort: entry.gatewayPort ?? null, registryFile: "/test/sandboxes.json" } + : null; +}); vi.mock("../../state/registry", () => ({ getSandbox: (...args: unknown[]) => getSandboxMock(...args), @@ -11,12 +17,7 @@ vi.mock("../../state/registry", () => ({ })); vi.mock("../../state/registry/cross-port", () => ({ - findSandboxAcrossGatewayRoots: (...args: unknown[]) => { - const entry = getSandboxMock(...args); - return entry - ? { entry, gatewayPort: entry.gatewayPort ?? null, registryFile: "/test/sandboxes.json" } - : null; - }, + findSandboxAcrossGatewayRoots: (...args: unknown[]) => findSandboxAcrossGatewayRootsMock(...args), })); import { @@ -26,6 +27,17 @@ import { isDockerRuntimeDown, } from "./gateway-failure-classifier"; +beforeEach(() => { + getSandboxMock.mockReset(); + findSandboxAcrossGatewayRootsMock.mockReset(); + findSandboxAcrossGatewayRootsMock.mockImplementation((...args: unknown[]) => { + const entry = getSandboxMock(...args); + return entry + ? { entry, gatewayPort: entry.gatewayPort ?? null, registryFile: "/test/sandboxes.json" } + : null; + }); +}); + function runners(overrides: Partial = {}): GatewayFailureRunners { return { dockerInfo: () => true, @@ -37,9 +49,6 @@ function runners(overrides: Partial = {}): GatewayFailure } describe("classifyGatewayFailure (#7348)", () => { - beforeEach(() => { - getSandboxMock.mockReset(); - }); it("classifies an exited per-port gateway container as container_exited, not container_missing", async () => { getSandboxMock.mockReturnValue({ name: "sb-1", gatewayPort: 8081 }); const portProbe = vi.fn(async () => false); @@ -127,6 +136,34 @@ describe("classifyGatewayFailure (#7348)", () => { expect(dockerExists).not.toHaveBeenCalled(); expect(portProbe).not.toHaveBeenCalled(); }); + + it("classifies a cross-root native gateway without invoking Docker", async () => { + getSandboxMock.mockReturnValue(null); + findSandboxAcrossGatewayRootsMock.mockReturnValue({ + entry: { name: "sb-1", gatewayPort: 8081, openshellDriver: "mxc" }, + gatewayPort: 8081, + registryFile: "/test/.nemoclaw/gateways/8081/sandboxes.json", + }); + const dockerInfo = vi.fn(() => false); + const dockerIsRunning = vi.fn(() => false); + const dockerExists = vi.fn(() => false); + const portProbe = vi.fn(async () => false); + + await expect( + classifyGatewayFailure("sb-1", { + runners: { dockerInfo, dockerIsRunning, dockerExists, portProbe }, + }), + ).resolves.toEqual({ + layer: "gateway_unreachable", + detail: "The OpenShell gateway for sandbox 'sb-1' is unreachable.", + }); + expect(isDockerRuntimeDown("sb-1", { runners: { dockerInfo } })).toBe(false); + expect(getSandboxMock).not.toHaveBeenCalled(); + expect(dockerInfo).not.toHaveBeenCalled(); + expect(dockerIsRunning).not.toHaveBeenCalled(); + expect(dockerExists).not.toHaveBeenCalled(); + expect(portProbe).not.toHaveBeenCalled(); + }); }); describe("classifyObservedSandboxContainerFailure", () => { diff --git a/src/lib/actions/sandbox/gateway-failure-classifier.ts b/src/lib/actions/sandbox/gateway-failure-classifier.ts index d787701fff4..50481ad6a90 100644 --- a/src/lib/actions/sandbox/gateway-failure-classifier.ts +++ b/src/lib/actions/sandbox/gateway-failure-classifier.ts @@ -16,7 +16,7 @@ import { type PortableRuntimeReceiptReadinessDeps, } from "../../onboard/experimental/portable-runtime-receipt-readiness"; import * as registry from "../../state/registry"; -import { getSandboxTargetGatewayName } from "./gateway-target"; +import { getKnownSandboxTarget, getSandboxTargetGatewayName } from "./gateway-target"; const DOCKER_TIMEOUT_MS = 3000; const PORT_PROBE_TIMEOUT_MS = 2000; @@ -136,7 +136,7 @@ export async function classifyGatewayFailure( ): Promise { const runners = opts?.runners ?? defaultRunners; - if (!isDockerBackedSandbox(sandboxName, registry.getSandbox)) { + if (!isDockerBackedSandbox(sandboxName, getKnownSandboxTarget)) { return { layer: "gateway_unreachable", detail: `The OpenShell gateway for sandbox '${sandboxName}' is unreachable.`, @@ -299,12 +299,12 @@ type SandboxDriverLookup = (name: string) => { openshellDriver?: string | null } // Drivers whose sandbox runtime does not live in the local Docker daemon. // Kubernetes remains Docker-backed on the supported legacy deployment paths; -// native Podman and VM sandboxes must never enter the Docker outage probe. -const NON_DOCKER_DRIVERS = new Set(["podman", "vm"]); +// native MXC, Podman, and VM sandboxes must never enter the Docker outage probe. +const NON_DOCKER_DRIVERS = new Set(["mxc", "podman", "vm"]); /** * Whether a sandbox's runtime depends on the local Docker daemon. Native - * Podman and VM drivers are excluded. The `docker` and `kubernetes` drivers + * MXC, Podman, and VM drivers are excluded. The `docker` and `kubernetes` drivers * are Docker-backed, and legacy/recovered registry entries that predate * `openshellDriver` metadata (field omitted/null) are also treated as * Docker-backed so the outage guard still protects the Linux/Docker sandboxes @@ -349,7 +349,7 @@ export function isDockerRuntimeDown( return true; } portableRuntimeFailures.delete(sandboxName); - const getSandbox = opts?.getSandbox ?? registry.getSandbox; + const getSandbox = opts?.getSandbox ?? getKnownSandboxTarget; if (!isDockerBackedSandbox(sandboxName, getSandbox)) return false; const probe = opts?.runners?.dockerInfo ?? defaultRunners.dockerInfo; return !probe(); From f07c22ff22003b6c465b261c9d5739c493d12401 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 02:50:40 -0700 Subject: [PATCH 18/44] fix(status): preserve cross-root mutation authority Signed-off-by: Rebecca Sliter --- ci/source-architecture-budget.json | 2 +- .../sandbox/connect-inference-gateway.test.ts | 65 +++++++++++++++++++ .../sandbox/connect-inference-gateway.ts | 6 +- .../sandbox/gateway-failure-classifier.ts | 25 +++++++ src/lib/actions/sandbox/gateway-state.ts | 22 +------ .../actions/sandbox/status-inference.test.ts | 8 +-- .../sandbox/status-lookup-rendering.ts | 24 +------ .../sandbox/status-snapshot-recovery.test.ts | 55 ++++++++++++++++ src/lib/actions/sandbox/status-snapshot.ts | 6 +- src/lib/state/registry/cross-port.ts | 36 ++++++++++ 10 files changed, 198 insertions(+), 51 deletions(-) create mode 100644 src/lib/actions/sandbox/connect-inference-gateway.test.ts diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index e4587392050..562dc40aebc 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -30,7 +30,7 @@ "src/lib/security/redact.ts": 51, "src/lib/state/mcp-lifecycle-lock.ts": 20, "src/lib/state/onboard-session.ts": 35, - "src/lib/state/registry.ts": 88, + "src/lib/state/registry.ts": 87, "src/lib/state/state-root.ts": 21, "src/lib/subprocess-env.ts": 26, "src/lib/validation.ts": 24 diff --git a/src/lib/actions/sandbox/connect-inference-gateway.test.ts b/src/lib/actions/sandbox/connect-inference-gateway.test.ts new file mode 100644 index 00000000000..8a56f13c9ec --- /dev/null +++ b/src/lib/actions/sandbox/connect-inference-gateway.test.ts @@ -0,0 +1,65 @@ +// 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, vi } from "vitest"; + +import { GatewayRouteConflictError } from "../../inference/gateway-route-compatibility"; +import { resolveGatewayName } from "../../onboard/gateway-binding"; +import type { SandboxEntry } from "../../state/registry"; +import { assertSandboxGatewayRouteCompatible } from "./connect-inference-gateway"; + +let home: string; + +function writeRegistry(relDir: string, sandboxes: Record): void { + const dir = path.join(home, ".nemoclaw", relDir); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, "sandboxes.json"), + JSON.stringify({ defaultSandbox: null, defaultSelectionRevision: 1, sandboxes }), + ); +} + +beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-connect-route-cross-root-")); + vi.stubEnv("HOME", home); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +describe("assertSandboxGatewayRouteCompatible", () => { + it("rejects a conflicting same-gateway route recorded in another registry root", () => { + const target: SandboxEntry = { + name: "target", + agent: "openclaw", + gatewayPort: 8245, + provider: "compatible-endpoint", + model: "shared-model", + endpointUrl: "https://target.example/v1", + preferredInferenceApi: "openai-completions", + credentialEnv: "COMPATIBLE_API_KEY", + }; + const peer: SandboxEntry = { + name: "peer", + agent: "openclaw", + gatewayPort: 8245, + provider: "compatible-endpoint", + model: "shared-model", + endpointUrl: "https://peer.example/v1", + preferredInferenceApi: "openai-completions", + credentialEnv: "COMPATIBLE_API_KEY", + }; + writeRegistry("", { peer }); + writeRegistry(path.join("gateways", "8245"), { target }); + + expect(() => + assertSandboxGatewayRouteCompatible("target", target, resolveGatewayName(8245)), + ).toThrow(GatewayRouteConflictError); + }); +}); diff --git a/src/lib/actions/sandbox/connect-inference-gateway.ts b/src/lib/actions/sandbox/connect-inference-gateway.ts index 112459439ac..6ac7600501a 100644 --- a/src/lib/actions/sandbox/connect-inference-gateway.ts +++ b/src/lib/actions/sandbox/connect-inference-gateway.ts @@ -9,7 +9,7 @@ import { import { LOCAL_INFERENCE_TIMEOUT_SECS } from "../../onboard/env"; import { resolveRegisteredRuntimeProvider } from "../../onboard/runtime-provider/selection"; import type { SandboxEntry } from "../../state/registry"; -import * as registry from "../../state/registry"; +import { listPublishedSandboxesAcrossGatewayRoots } from "../../state/registry/cross-port"; /** Identify the legacy cluster gateway without branching on managed provider IDs. */ export function sandboxUsesLegacyClusterGateway(sandbox: SandboxEntry | null): boolean { @@ -38,7 +38,7 @@ export function canSandboxGatewayRouteRealign( sandboxName: string, sb: SandboxEntry, gatewayName: string, - sandboxes: readonly SandboxEntry[] = registry.listSandboxes().sandboxes, + sandboxes: readonly SandboxEntry[] = listPublishedSandboxesAcrossGatewayRoots(), ): boolean { const result = sandboxGatewayRouteCompatibility(sandboxName, sb, gatewayName, sandboxes); return result.ok || isAdvisoryGatewayRouteConflict(result); @@ -75,7 +75,7 @@ export function assertSandboxGatewayRouteCompatible( sandboxName, sb, gatewayName, - registry.listSandboxes().sandboxes, + listPublishedSandboxesAcrossGatewayRoots(), ); if (!result.ok && !isAdvisoryGatewayRouteConflict(result)) { throw new GatewayRouteConflictError(result); diff --git a/src/lib/actions/sandbox/gateway-failure-classifier.ts b/src/lib/actions/sandbox/gateway-failure-classifier.ts index 50481ad6a90..e45bcab8fcf 100644 --- a/src/lib/actions/sandbox/gateway-failure-classifier.ts +++ b/src/lib/actions/sandbox/gateway-failure-classifier.ts @@ -82,6 +82,31 @@ export function classifySandboxPhaseRecoveryAction({ return "start"; } +/** Render the shared recovery contract while callers retain their output channel. */ +export function getSandboxPhaseRecoveryGuidance( + sandboxName: string, + action: SandboxPhaseRecoveryAction, +): string[] { + if (action === "replace_missing_docker_container") { + return [ + " The Docker-driver container is missing, so NemoClaw cannot back up its live workspace for rebuild.", + " To create a clean replacement:", + ` 1. ${CLI_NAME} ${sandboxName} destroy --yes`, + ` 2. ${CLI_NAME} onboard`, + " Restore a separately created snapshot afterward if one is available.", + ]; + } + if (action === "start") { + return [ + ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, + ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead; use it only if start does not recover the sandbox.)`, + ]; + } + return [ + ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`, + ]; +} + function defaultDockerInfo(): boolean { return dockerInfo({ ignoreError: true, timeout: DOCKER_TIMEOUT_MS }).length > 0; } diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 8055622324e..e948c360292 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -106,6 +106,7 @@ import { } from "./docker-health"; import { classifySandboxPhaseRecoveryAction, + getSandboxPhaseRecoveryGuidance, isDockerRuntimeDown, printDockerRuntimeDownGuidance, } from "./gateway-failure-classifier"; @@ -1192,25 +1193,8 @@ export async function ensureLiveSandboxOrExit( printDockerRuntimeDownGuidance(sandboxName); exit(1); } - if (recoveryAction === "replace_missing_docker_container") { - console.error( - " The Docker-driver container is missing, so NemoClaw cannot back up its live workspace for rebuild.", - ); - console.error(" To create a clean replacement:"); - console.error(` 1. ${CLI_NAME} ${sandboxName} destroy --yes`); - console.error(` 2. ${CLI_NAME} onboard`); - console.error(" Restore a separately created snapshot afterward if one is available."); - } else if (recoveryAction === "start") { - console.error( - ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, - ); - console.error( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead; use it only if start does not recover the sandbox.)`, - ); - } else { - console.error( - ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`, - ); + for (const line of getSandboxPhaseRecoveryGuidance(sandboxName, recoveryAction)) { + console.error(line); } exit(1); } diff --git a/src/lib/actions/sandbox/status-inference.test.ts b/src/lib/actions/sandbox/status-inference.test.ts index 68a8deda627..2b15bf66c96 100644 --- a/src/lib/actions/sandbox/status-inference.test.ts +++ b/src/lib/actions/sandbox/status-inference.test.ts @@ -44,8 +44,8 @@ describe("sandbox status inference.local route health (#6192)", () => { return { getSandbox: () => sandbox, listSandboxes: () => ({ sandboxes: [sandbox], defaultSandbox: "alpha" }), - updateSandbox: vi.fn((_name: string, updates: { stopped?: boolean }) => { - sandbox = { ...sandbox, ...updates }; + recordSandboxStopIntent: vi.fn((_name: string, stopped: boolean) => { + sandbox = { ...sandbox, stopped }; return true; }), reconcile: vi.fn(async () => @@ -200,7 +200,7 @@ describe("sandbox status inference.local route health (#6192)", () => { const running = await getSandboxStatusReport("alpha", deps); expect(running.phase).toBe("Running"); - expect(deps.updateSandbox).toHaveBeenCalledWith("alpha", { stopped: false }); + expect(deps.recordSandboxStopIntent).toHaveBeenCalledWith("alpha", false); expect(deps.probeSandboxInferenceGatewayHealthImpl).toHaveBeenCalled(); deps.getSandboxStatusPreflightImpl.mockResolvedValue({ @@ -224,7 +224,7 @@ describe("sandbox status inference.local route health (#6192)", () => { stopped: true, routeHealth: null, }); - deps.updateSandbox.mockReturnValue(false); + deps.recordSandboxStopIntent.mockReturnValue(false); const report = await getSandboxStatusReport("alpha", deps); diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index 8b77e69dd92..d9b16271f45 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -9,6 +9,7 @@ import { isTerminalSandboxPhase } from "../../state/gateway"; import { getSandboxDockerRuntime } from "./docker-health"; import { classifySandboxPhaseRecoveryAction, + getSandboxPhaseRecoveryGuidance, isDockerRuntimeDown, printDockerRuntimeDownGuidance, } from "./gateway-failure-classifier"; @@ -345,26 +346,7 @@ function printNonReadySandboxPhaseGuidance({ printDockerRuntimeDownGuidance(sandboxName, { writer: console.log }); deferSandboxLifecycleExit(1); } - if (recoveryAction === "replace_missing_docker_container") { - console.log( - " The Docker-driver container is missing, so NemoClaw cannot back up its live workspace for rebuild.", - ); - console.log(" To create a clean replacement:"); - console.log(` 1. ${CLI_NAME} ${sandboxName} destroy --yes`); - console.log(` 2. ${CLI_NAME} onboard`); - console.log(" Restore a separately created snapshot afterward if one is available."); - return; + for (const line of getSandboxPhaseRecoveryGuidance(sandboxName, recoveryAction)) { + console.log(line); } - if (recoveryAction === "start") { - console.log( - ` Run \`${CLI_NAME} ${sandboxName} start\` to restart the sandbox through OpenShell with workspace state preserved.`, - ); - console.log( - ` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead; use it only if start does not recover the sandbox.)`, - ); - return; - } - console.log( - ` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`, - ); } diff --git a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts index 5233b5faa1d..a43ba5696de 100644 --- a/src/lib/actions/sandbox/status-snapshot-recovery.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-recovery.test.ts @@ -1,6 +1,10 @@ // 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 { describe, expect, it, vi } from "vitest"; import type { SandboxEntry } from "../../state/registry"; @@ -120,6 +124,57 @@ describe("collectSandboxStatusSnapshot Docker recovery", () => { }); }); + it("clears stale stop intent in the cross-root registry that owns the sandbox", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-status-cross-root-")); + const registryDir = path.join(home, ".nemoclaw", "gateways", "8245"); + const registryFile = path.join(registryDir, "sandboxes.json"); + const crossRootSandbox: SandboxEntry = { + ...sandbox, + agent: "langchain-deepagents-code", + gatewayPort: 8245, + stopped: true, + }; + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync( + registryFile, + JSON.stringify({ + defaultSandbox: null, + defaultSelectionRevision: 1, + sandboxes: { alpha: crossRootSandbox }, + }), + ); + vi.stubEnv("HOME", home); + + try { + const snapshot = await collectSandboxStatusSnapshot("alpha", { + sandboxEntry: crossRootSandbox, + preflight: clearPreflight, + deps: { + ...snapshotDeps({ + checked: false, + wasRunning: null, + recovered: false, + forwardRecovered: false, + }), + reconcile: async () => ({ + state: "present" as const, + phase: "Ready", + output: "Phase: Ready", + }), + }, + }); + + const persisted = JSON.parse(fs.readFileSync(registryFile, "utf8")) as { + sandboxes: { alpha: SandboxEntry }; + }; + expect(snapshot.lookup.state).toBe("present"); + expect(persisted.sandboxes.alpha.stopped).toBe(false); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("recovers the delivery chain when OpenShell already reports the restarted container (#7824)", async () => { const deps = { ...snapshotDeps({ diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index cbb1cda9b30..f2e6d119036 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -38,6 +38,7 @@ import { findSandboxAcrossGatewayRoots, listPublishedSandboxNamesAcrossGatewayRoots, listPublishedSandboxesAcrossGatewayRoots, + recordSandboxStopIntentAcrossGatewayRoots, } from "../../state/registry/cross-port"; import { canSandboxGatewayRouteRealign } from "./connect-inference-gateway"; import { getSandboxDockerRuntime } from "./docker-health"; @@ -302,7 +303,7 @@ interface CollectSandboxStatusSnapshotDeps { listPublishedSandboxNamesAcrossGatewayRoots?: typeof listPublishedSandboxNamesAcrossGatewayRoots; listPublishedSandboxesAcrossGatewayRoots?: typeof listPublishedSandboxesAcrossGatewayRoots; getSandbox?: typeof registry.getSandbox; - updateSandbox?: typeof registry.updateSandbox; + recordSandboxStopIntent?: typeof recordSandboxStopIntentAcrossGatewayRoots; captureOpenshellForStatusImpl?: typeof captureOpenshellForStatus; probeProviderHealthImpl?: ProbeProviderHealth; probeSandboxInferenceGatewayHealthImpl?: ProbeSandboxInferenceGatewayHealth; @@ -475,10 +476,9 @@ export async function collectSandboxStatusSnapshot( (lookup.phase === "Ready" || lookup.phase === "Running") && !initialPreflight?.failure && !initialPreflight?.intentionalStopConfirmed && - !registry.recordSandboxStopIntent( + !(opts.deps?.recordSandboxStopIntent ?? recordSandboxStopIntentAcrossGatewayRoots)( sandboxName, false, - opts.deps?.updateSandbox ?? registry.updateSandbox, ) ) { lookup = { diff --git a/src/lib/state/registry/cross-port.ts b/src/lib/state/registry/cross-port.ts index 6bd506fdc09..bf3199e520b 100644 --- a/src/lib/state/registry/cross-port.ts +++ b/src/lib/state/registry/cross-port.ts @@ -10,7 +10,9 @@ import { registryEntryGatewayPort, resolveHome, type GatewayRegistryEntry, + withRegistryLockAt, } from "../gateway-registry"; +import { writeConfigFile } from "../config-io"; import type { SandboxEntry } from "./types"; export interface CrossPortSandboxHit { @@ -92,6 +94,40 @@ export function findSandboxAcrossGatewayRoots( return matches[0]; } +/** Persist intentional-stop state in the registry root that owns the sandbox. */ +export function recordSandboxStopIntentAcrossGatewayRoots( + sandboxName: string, + stopped: boolean, + home: string = resolveHome(), +): boolean { + try { + const hit = findSandboxAcrossGatewayRoots(sandboxName, home); + if (!hit) return false; + return withRegistryLockAt(hit.registryFile, () => { + const registry = readGatewayRegistryFile(home, hit.registryFile); + const current = registry?.sandboxes[sandboxName]; + if ( + !registry || + !current || + current.pendingRouteReservation === true || + current.pendingCreateIdentity !== undefined + ) { + return false; + } + writeConfigFile(hit.registryFile, { + ...registry, + sandboxes: { + ...registry.sandboxes, + [sandboxName]: { ...current, stopped }, + }, + }); + return true; + }); + } catch { + return false; + } +} + function listEntriesAcrossGatewayRoots(published: boolean, home: string): SandboxEntry[] { return listSandboxHitsAcrossGatewayRoots(home) .map(({ entry }) => entry) From 43259c651db980fe580e356211e9a92fbc27d198 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 03:11:06 -0700 Subject: [PATCH 19/44] test(connect): mock cross-root route inventory Signed-off-by: Rebecca Sliter --- test/support/connect-flow-test-harness.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 4e2ef4a2d85..69f6398a500 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -699,6 +699,9 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne : null; }, ); + vi.spyOn(crossPortRegistry, "listPublishedSandboxesAcrossGatewayRoots").mockImplementation( + () => registryEntries, + ); vi.spyOn(registry, "listSandboxes").mockReturnValue({ sandboxes: registryEntries, defaultSandbox: primaryRegistryEntry.name, From ff19945cf434ad18292397816afe7637274676b4 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 04:13:33 -0700 Subject: [PATCH 20/44] fix(status): route lifecycle through owning registry Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/destroy-cross-root.test.ts | 73 +++++++++++++++++++ src/lib/actions/sandbox/destroy-flow.test.ts | 4 + src/lib/actions/sandbox/destroy-preflight.ts | 42 ++++++++++- src/lib/actions/sandbox/destroy.ts | 34 ++++++--- src/lib/actions/sandbox/start.test.ts | 40 ++++++++++ src/lib/actions/sandbox/start.ts | 26 ++++--- src/lib/actions/sandbox/stop.test.ts | 44 +++++++++++ src/lib/actions/sandbox/stop.ts | 35 ++++++--- src/lib/state/gateway-registry.ts | 9 +++ src/lib/state/registry/cross-port.test.ts | 51 +++++++++++++ src/lib/state/registry/cross-port.ts | 55 +++++++++++++- test/helpers/destroy-flow-test-harness.ts | 2 + 12 files changed, 379 insertions(+), 36 deletions(-) create mode 100644 src/lib/actions/sandbox/destroy-cross-root.test.ts diff --git a/src/lib/actions/sandbox/destroy-cross-root.test.ts b/src/lib/actions/sandbox/destroy-cross-root.test.ts new file mode 100644 index 00000000000..3b66dcb453d --- /dev/null +++ b/src/lib/actions/sandbox/destroy-cross-root.test.ts @@ -0,0 +1,73 @@ +// 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, vi } from "vitest"; + +import { + createDestroyHarness, + resetDestroyModuleCache, +} from "../../../../test/helpers/destroy-flow-test-harness"; + +describe("destroySandbox cross-root registry authority", () => { + let home: string; + + beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-destroy-cross-root-")); + vi.stubEnv("HOME", home); + vi.spyOn(process, "exit").mockImplementation(((code?: number | string | null) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + resetDestroyModuleCache(); + fs.rmSync(home, { force: true, recursive: true }); + }); + + it("removes the sandbox from its sibling gateway registry", async () => { + const registryDir = path.join(home, ".nemoclaw", "gateways", "8245"); + const registryFile = path.join(registryDir, "sandboxes.json"); + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync( + registryFile, + JSON.stringify({ + defaultSandbox: "alpha", + defaultSelectionRevision: 1, + sandboxes: { + alpha: { + name: "alpha", + agent: "openclaw", + provider: "ollama-local", + model: "nvidia/nemotron", + gatewayName: "nemoclaw-8245", + gatewayPort: 8245, + }, + }, + }), + ); + const harness = createDestroyHarness(); + + await expect( + harness.destroySandbox("alpha", { yes: true, cleanupGateway: false }), + ).resolves.toBeUndefined(); + + expect(JSON.parse(fs.readFileSync(registryFile, "utf8"))).toMatchObject({ + defaultSandbox: null, + defaultSelectionRevision: 2, + sandboxes: {}, + }); + expect(harness.selectGatewaySpy).toHaveBeenCalledWith( + "alpha", + "nemoclaw-8245", + expect.anything(), + undefined, + ); + expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/destroy-flow.test.ts b/src/lib/actions/sandbox/destroy-flow.test.ts index 8a5f5c0af06..f063cc8b82e 100644 --- a/src/lib/actions/sandbox/destroy-flow.test.ts +++ b/src/lib/actions/sandbox/destroy-flow.test.ts @@ -58,8 +58,11 @@ const managedHermesWorkload = { describe("destroySandbox flow", () => { let exitSpy: MockInstance; let originalGatewayEnv: string | undefined; + let testHome: string; beforeEach(() => { + testHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-destroy-flow-home-")); + vi.stubEnv("HOME", testHome); originalGatewayEnv = process.env.OPENSHELL_GATEWAY; exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number | string | null) => { throw new Error(`process.exit(${code ?? 0})`); @@ -73,6 +76,7 @@ describe("destroySandbox flow", () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); resetDestroyModuleCache(); + fs.rmSync(testHome, { force: true, recursive: true }); }); it("trusts absence only from a successful, error-free sandbox list", { timeout: 30_000 }, () => { diff --git a/src/lib/actions/sandbox/destroy-preflight.ts b/src/lib/actions/sandbox/destroy-preflight.ts index f8ca9921270..1fa38131afa 100644 --- a/src/lib/actions/sandbox/destroy-preflight.ts +++ b/src/lib/actions/sandbox/destroy-preflight.ts @@ -24,6 +24,12 @@ import type { } from "../../state/onboard-session"; import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; +import { + findSandboxAcrossGatewayRoots, + getSandboxAcrossGatewayRoots, + listPublishedSandboxesAcrossGatewayRoots, + removeSandboxFromOwningGatewayRegistry, +} from "../../state/registry/cross-port"; import { type DestroyRunOpenshell, selectGatewayForSandboxDestroy } from "./destroy-gateway"; import { classifyDestroySandboxPresence, type DestroySandboxPresence } from "./destroy-presence"; import { @@ -44,6 +50,38 @@ export type SandboxDestroyPreflight = { sandboxPresence?: DestroySandboxPresence; }; +export type SandboxDestroyRegistryAuthority = { + entry: SandboxEntry | null; + getSandbox: typeof registry.getSandbox; + listSandboxes: typeof registry.listSandboxes; + removeSandbox: typeof registry.removeSandbox; +}; + +/** Pin destroy reads and mutation to the registry file that owns the named sandbox. */ +export function resolveSandboxDestroyRegistryAuthority( + sandboxName: string, +): SandboxDestroyRegistryAuthority { + const hit = findSandboxAcrossGatewayRoots(sandboxName); + if (!hit) { + return { + entry: registry.getSandbox(sandboxName), + getSandbox: registry.getSandbox, + listSandboxes: registry.listSandboxes, + removeSandbox: registry.removeSandbox, + }; + } + return { + entry: hit.entry, + getSandbox: getSandboxAcrossGatewayRoots, + listSandboxes: () => ({ + sandboxes: listPublishedSandboxesAcrossGatewayRoots(), + defaultSandbox: null, + }), + removeSandbox: (name) => + name === hit.entry.name ? removeSandboxFromOwningGatewayRegistry(hit) : false, + }; +} + export function resolveSandboxDestroyGatewayName( sandboxName: string, sandbox: SandboxEntry | null, @@ -300,14 +338,16 @@ export async function stopModelRouterForDestroyedSandbox( export async function prepareSandboxDestroy( sandboxName: string, { + getSandbox = registry.getSandbox, retainedRecoveryGatewayName, operationRuntimeSelection, }: { + getSandbox?: typeof registry.getSandbox; retainedRecoveryGatewayName?: string; operationRuntimeSelection?: OpenShellRuntimeSelection; } = {}, ): Promise { - const sandbox = registry.getSandbox(sandboxName); + const sandbox = getSandbox(sandboxName); console.log(` Deleting sandbox '${sandboxName}'...`); const { captureOpenshell, runOpenshell } = require("../../adapters/openshell/runtime") as Pick< typeof import("../../adapters/openshell/runtime"), diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index c24445675d3..e24603585b7 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -72,6 +72,7 @@ import { } from "./destroy-presence"; import { prepareSandboxDestroy, + resolveSandboxDestroyRegistryAuthority, resolveSandboxDestroyGatewayName, resolveSandboxDestroyRuntimeSelection, stopModelRouterForDestroyedSandbox, @@ -617,7 +618,10 @@ async function destroySandboxUnlocked( retireRemovedImmutabilityState = false, ): Promise { const normalized = normalizeDestroySandboxOptions(options); - const registeredSandbox = registry.getSandbox(sandboxName); + const registryAuthority = resolveSandboxDestroyRegistryAuthority(sandboxName); + const getRegisteredSandbox = registryAuthority.getSandbox; + const listRegisteredSandboxes = registryAuthority.listSandboxes; + const registeredSandbox = registryAuthority.entry; const operationRuntimeSelection = resolveSandboxDestroyRuntimeSelection(registeredSandbox); if (!(await confirmSandboxDestroy(sandboxName, normalized, operationRuntimeSelection))) return; if (registeredSandbox) { @@ -653,7 +657,7 @@ async function destroySandboxUnlocked( let portableContainerAuthority: ReturnType; try { portableContainerAuthority = preparePortableDemoSandboxDestroyAuthority(sandboxName, () => { - const current = registry.getSandbox(sandboxName); + const current = getRegisteredSandbox(sandboxName); return current ? { agent: current.agent, @@ -669,7 +673,7 @@ async function destroySandboxUnlocked( } const inspectContainerIdentity = () => { - const registeredSandbox = registry.getSandbox(sandboxName); + const registeredSandbox = getRegisteredSandbox(sandboxName); return assertUnambiguousDestroyContainerIdentity(sandboxName, { cliName: CLI_NAME, providerId: destroyRuntimeProviderId ?? normalizeRuntimeProviderIdentity(null), @@ -748,6 +752,7 @@ async function destroySandboxUnlocked( let destroyPreflight: Awaited>; try { destroyPreflight = await prepareSandboxDestroy(sandboxName, { + getSandbox: getRegisteredSandbox, retainedRecoveryGatewayName: retainedRecoveryAuthority?.gatewayName, operationRuntimeSelection, }); @@ -825,8 +830,8 @@ async function destroySandboxUnlocked( try { destructiveResult = await executeSandboxDestroy({ force: normalized.force === true, - getSandbox: registry.getSandbox, - listSandboxes: registry.listSandboxes, + getSandbox: getRegisteredSandbox, + listSandboxes: listRegisteredSandboxes, deleteGatewayName: cleanupGatewayName, runOpenshell, ...(mcpRuntimeSelection ? { mcpRuntimeSelection } : {}), @@ -1005,8 +1010,8 @@ async function destroySandboxUnlocked( try { const shouldStopHostServices = shouldStopHostServicesAfterDestroy({ deleteSucceededOrAlreadyGone, - registeredSandboxCount: registry.listSandboxes().sandboxes.length, - sandboxStillRegistered: !!registry.getSandbox(sandboxName), + registeredSandboxCount: listRegisteredSandboxes().sandboxes.length, + sandboxStillRegistered: !!getRegisteredSandbox(sandboxName), }); await cleanupSandboxServices( sandboxName, @@ -1014,6 +1019,8 @@ async function destroySandboxUnlocked( stopHostServices: shouldStopHostServices, }, { + getSandbox: getRegisteredSandbox, + listSandboxes: listRegisteredSandboxes, runOpenshell: cleanupRunOpenshell, }, ); @@ -1061,7 +1068,10 @@ async function destroySandboxUnlocked( if (deleteSucceededOrAlreadyGone && retireRemovedImmutabilityState) { retireRemovedImmutabilityStateRecord(sandboxName, "sandbox-destroyed"); } - const removalOutcome = removeSandboxRegistryEntryOutcome(sandboxName); + const removalOutcome = removeSandboxRegistryEntryOutcome(sandboxName, { + removeImage: (name) => removeSandboxImage(name, { getSandbox: getRegisteredSandbox }), + removeSandbox: registryAuthority.removeSandbox, + }); const removed = removalOutcome.removed; // A retry after successful registry removal still owns final gateway cleanup. // The gateway runtime marker captured its provider before the first delete. @@ -1069,7 +1079,7 @@ async function destroySandboxUnlocked( removalOutcome.status === "complete" || removalOutcome.status === "not-found"; if (removalOutcome.status === "blocked") { const providerId = normalizeRuntimeProviderIdentity( - (registry.getSandbox(sandboxName) ?? sandbox)?.openshellDriver, + (getRegisteredSandbox(sandboxName) ?? sandbox)?.openshellDriver, ); console.warn( ` ${YW}⚠${R} Sandbox '${sandboxName}' cleanup is incomplete for runtime provider ` + @@ -1104,7 +1114,7 @@ async function destroySandboxUnlocked( await withOllamaModelOwnershipTransaction(() => { const selectedHost = loadPersistedOllamaHost(); if (!isLocalOllamaRouteOwner(sandbox, selectedHost)) return; - const remainingSandboxes = registry.listSandboxes().sandboxes; + const remainingSandboxes = listRegisteredSandboxes().sandboxes; localInference.clearPersistedOllamaHostIfUnused(remainingSandboxes); }); } catch (error) { @@ -1115,7 +1125,9 @@ async function destroySandboxUnlocked( } } if (deleteSucceededOrAlreadyGone && removed && priorHttpsPinRouteId) { - await revokeDestroyedSandboxHttpsPinRoute(cleanupGatewayName, priorHttpsPinRouteId); + await revokeDestroyedSandboxHttpsPinRoute(cleanupGatewayName, priorHttpsPinRouteId, { + listSandboxes: listRegisteredSandboxes, + }); } let routedSessionCleanupHandled = false; if (deleteSucceededOrAlreadyGone && removed) { diff --git a/src/lib/actions/sandbox/start.test.ts b/src/lib/actions/sandbox/start.test.ts index d42c7610a9b..2500f100772 100644 --- a/src/lib/actions/sandbox/start.test.ts +++ b/src/lib/actions/sandbox/start.test.ts @@ -1,6 +1,10 @@ // 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 { describe, expect, it, vi } from "vitest"; import type { OpenShellSandboxObserver } from "../../adapters/openshell/sandbox-observer"; @@ -124,6 +128,42 @@ function harness(overrides: Partial = {}) { } describe("startSandbox native lifecycle", () => { + it("starts a sandbox from its sibling gateway registry and clears stop intent there", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-start-cross-root-")); + const registryDir = path.join(home, ".nemoclaw", "gateways", "8245"); + const registryFile = path.join(registryDir, "sandboxes.json"); + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync( + registryFile, + JSON.stringify({ + defaultSandbox: "my-sandbox", + defaultSelectionRevision: 1, + sandboxes: { + "my-sandbox": { + name: "my-sandbox", + gatewayName: "nemoclaw-8245", + gatewayPort: 8245, + stopped: true, + }, + }, + }), + ); + vi.stubEnv("HOME", home); + try { + const h = harness(); + const { getSandbox: _getSandbox, updateSandbox: _updateSandbox, ...deps } = h.deps; + + await expect(startSandbox("my-sandbox", deps)).resolves.toEqual({ exitCode: 0 }); + + expect( + JSON.parse(fs.readFileSync(registryFile, "utf8")).sandboxes["my-sandbox"], + ).toMatchObject({ gatewayPort: 8245, stopped: false }); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("waits for OpenShell readiness before observing native gateway health", async () => { const h = harness(); diff --git a/src/lib/actions/sandbox/start.ts b/src/lib/actions/sandbox/start.ts index a30d691ccbf..dc6985eff9f 100644 --- a/src/lib/actions/sandbox/start.ts +++ b/src/lib/actions/sandbox/start.ts @@ -12,6 +12,11 @@ import { } from "../../onboard/runtime-provider/access"; import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; +import { + findSandboxAcrossGatewayRoots, + getSandboxAcrossGatewayRoots, + recordSandboxStopIntentInOwningGatewayRegistry, +} from "../../state/registry/cross-port"; import { probeSandboxInferenceInvocation, READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, @@ -167,7 +172,9 @@ async function startSandboxWithinLifecycleFence( deps: SandboxStartDeps, ): Promise { const log = deps.log ?? console.log; - const sandbox = (deps.getSandbox ?? registry.getSandbox)(sandboxName); + const owningRegistryHit = deps.getSandbox ? null : findSandboxAcrossGatewayRoots(sandboxName); + const readSandbox = deps.getSandbox ?? getSandboxAcrossGatewayRoots; + const sandbox = owningRegistryHit?.entry ?? readSandbox(sandboxName); const resolved = resolveSandboxLifecycleProvider( sandboxName, sandbox, @@ -177,7 +184,7 @@ async function startSandboxWithinLifecycleFence( if (!resolved.ok) return resolved.result; const input = { - readRegistry: deps.getSandbox ?? registry.getSandbox, + readRegistry: readSandbox, environment: deps.environment ?? process.env, log, sandbox: resolved.sandbox, @@ -188,14 +195,13 @@ async function startSandboxWithinLifecycleFence( const result = await resolved.lifecycle.start(input); if (result.exitCode !== 0) return result; const clearIntentionalStop = () => { - if ( - resolved.sandbox.stopped === true && - !registry.recordSandboxStopIntent( - sandboxName, - false, - deps.updateSandbox ?? registry.updateSandbox, - ) - ) { + if (resolved.sandbox.stopped !== true) return; + const recorded = deps.updateSandbox + ? registry.recordSandboxStopIntent(sandboxName, false, deps.updateSandbox) + : owningRegistryHit + ? recordSandboxStopIntentInOwningGatewayRegistry(owningRegistryHit, false) + : false; + if (!recorded) { throw new Error( `Sandbox '${sandboxName}' started, but NemoClaw could not clear its intentional-stop record. Run '${cliName()} ${sandboxName} status' before another lifecycle command.`, ); diff --git a/src/lib/actions/sandbox/stop.test.ts b/src/lib/actions/sandbox/stop.test.ts index 0f47aba9585..dce046c2e2b 100644 --- a/src/lib/actions/sandbox/stop.test.ts +++ b/src/lib/actions/sandbox/stop.test.ts @@ -1,6 +1,10 @@ // 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, vi } from "vitest"; import * as agentRuntime from "../../agent/runtime"; @@ -326,6 +330,46 @@ describe("stopSandbox", () => { vi.restoreAllMocks(); }); + it("stops a sandbox from its sibling gateway registry and records stop intent there", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-stop-cross-root-")); + const registryDir = path.join(home, ".nemoclaw", "gateways", "8245"); + const registryFile = path.join(registryDir, "sandboxes.json"); + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync( + registryFile, + JSON.stringify({ + defaultSandbox: "my-sandbox", + defaultSelectionRevision: 1, + sandboxes: { + "my-sandbox": { + name: "my-sandbox", + gatewayName: "nemoclaw-8245", + gatewayPort: 8245, + }, + }, + }), + ); + vi.stubEnv("HOME", home); + try { + const h = harness(); + const { + getSandbox: _getSandbox, + listSandboxes: _listSandboxes, + updateSandbox: _updateSandbox, + ...deps + } = h.deps; + + await expect(stopSandbox("my-sandbox", deps)).resolves.toEqual({ exitCode: 0 }); + + expect( + JSON.parse(fs.readFileSync(registryFile, "utf8")).sandboxes["my-sandbox"], + ).toMatchObject({ gatewayPort: 8245, stopped: true }); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("gracefully stops in-sandbox channels before stopping through OpenShell (#6026)", async () => { const h = harness(); diff --git a/src/lib/actions/sandbox/stop.ts b/src/lib/actions/sandbox/stop.ts index f58c66349f7..4e644d87d44 100644 --- a/src/lib/actions/sandbox/stop.ts +++ b/src/lib/actions/sandbox/stop.ts @@ -15,6 +15,12 @@ import { } from "../../onboard/runtime-provider/access"; import { parseLiveSandboxEntries } from "../../runtime-recovery"; import * as registry from "../../state/registry"; +import { + findSandboxAcrossGatewayRoots, + getSandboxAcrossGatewayRoots, + listPublishedSandboxesAcrossGatewayRoots, + recordSandboxStopIntentInOwningGatewayRegistry, +} from "../../state/registry/cross-port"; import { stopSandboxChannels } from "../../tunnel/sandbox-gateway-stop"; import { teardownSandboxDashboardForward } from "./forward-recovery"; import { @@ -70,6 +76,13 @@ type OllamaStopReleaseResult = | { readonly ok: true } | { readonly ok: false; readonly message: string }; +function listSandboxesAcrossGatewayRoots(): ReturnType { + return { + sandboxes: listPublishedSandboxesAcrossGatewayRoots(), + defaultSandbox: null, + }; +} + type OllamaOwnershipDiscoveryDeps = { readonly captureSandboxOwnershipPhases?: typeof captureSandboxOwnershipPhases; readonly parseLiveSandboxEntries?: typeof parseLiveSandboxEntries; @@ -164,7 +177,7 @@ function releaseStoppedSandboxOllamaModel( return withOwnershipLock(() => { const selectedHost = loadPersistedOllamaHost(); if (!isLocalOllamaRouteOwner(sandbox, selectedHost)) return { ok: true }; - const { sandboxes } = (deps.listSandboxes ?? registry.listSandboxes)(); + const { sandboxes } = (deps.listSandboxes ?? listSandboxesAcrossGatewayRoots)(); const matchingPeers = matchingOllamaModelPeers(sandbox, sandboxes, selectedHost); const discovery = (deps.discoverActiveOllamaSandboxNames ?? discoverActiveOllamaSandboxNames)( matchingPeers, @@ -286,7 +299,9 @@ async function stopSandboxWithinLifecycleFence( ): Promise { const log = deps.log ?? console.log; const warn = deps.warn ?? console.warn; - const sandbox = (deps.getSandbox ?? registry.getSandbox)(sandboxName); + const owningRegistryHit = deps.getSandbox ? null : findSandboxAcrossGatewayRoots(sandboxName); + const readSandbox = deps.getSandbox ?? getSandboxAcrossGatewayRoots; + const sandbox = owningRegistryHit?.entry ?? readSandbox(sandboxName); const resolved = resolveSandboxLifecycleProvider( sandboxName, sandbox, @@ -296,7 +311,7 @@ async function stopSandboxWithinLifecycleFence( if (!resolved.ok) return resolved.result; const input = { - readRegistry: deps.getSandbox ?? registry.getSandbox, + readRegistry: readSandbox, environment: deps.environment ?? process.env, log, sandbox: resolved.sandbox, @@ -325,13 +340,13 @@ async function stopSandboxWithinLifecycleFence( if (outcome.exitCode !== 0) return outcome; const hermesPortableVerified = "hermesPortableVerified" in outcome && outcome.hermesPortableVerified === true; - const stopIntentRecorded = - hermesPortableVerified || - registry.recordSandboxStopIntent( - sandboxName, - true, - deps.updateSandbox ?? registry.updateSandbox, - ); + const stopIntentRecorded = hermesPortableVerified + ? true + : deps.updateSandbox + ? registry.recordSandboxStopIntent(sandboxName, true, deps.updateSandbox) + : owningRegistryHit + ? recordSandboxStopIntentInOwningGatewayRegistry(owningRegistryHit, true) + : false; const ollamaRelease = releaseStoppedSandboxOllamaModel(resolved.sandbox, deps, log); const dashboardForwardReleased = await teardownDashboardForwardBestEffort( sandboxName, diff --git a/src/lib/state/gateway-registry.ts b/src/lib/state/gateway-registry.ts index 656fd5e045d..e5cc9ac720d 100644 --- a/src/lib/state/gateway-registry.ts +++ b/src/lib/state/gateway-registry.ts @@ -35,6 +35,7 @@ export interface GatewayRegistryEntry extends Record { export interface GatewayRegistryDocument extends Record { defaultSandbox: string | null; + defaultSelectionRevision?: number; sandboxes: Record; } @@ -93,6 +94,14 @@ function parseRegistry(filePath: string, raw: string): GatewayRegistryDocument { ) { throw stateError(`${filePath} has an invalid defaultSandbox`); } + if ( + parsed.defaultSelectionRevision !== undefined && + (typeof parsed.defaultSelectionRevision !== "number" || + !Number.isSafeInteger(parsed.defaultSelectionRevision) || + parsed.defaultSelectionRevision < 0) + ) { + throw stateError(`${filePath} has an invalid defaultSelectionRevision`); + } const sandboxes: Record = {}; for (const [name, value] of Object.entries(parsed.sandboxes)) { diff --git a/src/lib/state/registry/cross-port.test.ts b/src/lib/state/registry/cross-port.test.ts index c3bb586db37..99155064f77 100644 --- a/src/lib/state/registry/cross-port.test.ts +++ b/src/lib/state/registry/cross-port.test.ts @@ -109,6 +109,57 @@ describe("findSandboxAcrossGatewayRoots", () => { }); }); +describe("owning registry mutations", () => { + it("removes a sibling-root sandbox and advances its default-pointer revision", async () => { + const registryFile = writeRegistry(path.join("gateways", "8245"), { + "owner-a": { name: "owner-a", gatewayPort: 8245 }, + "owner-b": { name: "owner-b", gatewayPort: 8245 }, + }); + fs.writeFileSync( + registryFile, + JSON.stringify({ + defaultSandbox: "owner-a", + defaultSelectionRevision: 4, + sandboxes: { + "owner-a": { name: "owner-a", gatewayPort: 8245 }, + "owner-b": { name: "owner-b", gatewayPort: 8245 }, + }, + }), + ); + const { removeSandboxAcrossGatewayRoots } = await loadModule(); + + expect(removeSandboxAcrossGatewayRoots("owner-a")).toBe(true); + + const persisted = JSON.parse(fs.readFileSync(registryFile, "utf8")); + expect(persisted).toMatchObject({ + defaultSandbox: "owner-b", + defaultSelectionRevision: 5, + sandboxes: { "owner-b": { name: "owner-b", gatewayPort: 8245 } }, + }); + expect(persisted.sandboxes).not.toHaveProperty("owner-a"); + }); + + it("rejects an invalid default-pointer revision before mutating a sibling registry", async () => { + const registryFile = writeRegistry(path.join("gateways", "8245"), { + "owner-a": { name: "owner-a", gatewayPort: 8245 }, + }); + fs.writeFileSync( + registryFile, + JSON.stringify({ + defaultSandbox: "owner-a", + defaultSelectionRevision: -1, + sandboxes: { "owner-a": { name: "owner-a", gatewayPort: 8245 } }, + }), + ); + const { removeSandboxAcrossGatewayRoots } = await loadModule(); + + expect(() => removeSandboxAcrossGatewayRoots("owner-a")).toThrow( + "invalid defaultSelectionRevision", + ); + expect(JSON.parse(fs.readFileSync(registryFile, "utf8")).sandboxes).toHaveProperty("owner-a"); + }); +}); + describe("listSandboxNamesAcrossGatewayRoots", () => { it("aggregates published names across roots, keeping order stable and deduplicated", async () => { writeRegistry("", { diff --git a/src/lib/state/registry/cross-port.ts b/src/lib/state/registry/cross-port.ts index bf3199e520b..cdc6d4ca058 100644 --- a/src/lib/state/registry/cross-port.ts +++ b/src/lib/state/registry/cross-port.ts @@ -13,6 +13,7 @@ import { withRegistryLockAt, } from "../gateway-registry"; import { writeConfigFile } from "../config-io"; +import { removeSandboxFromRegistry } from "../registry-reversible-removal"; import type { SandboxEntry } from "./types"; export interface CrossPortSandboxHit { @@ -94,15 +95,22 @@ export function findSandboxAcrossGatewayRoots( return matches[0]; } -/** Persist intentional-stop state in the registry root that owns the sandbox. */ -export function recordSandboxStopIntentAcrossGatewayRoots( +/** Read one unambiguous sandbox from the registry root that owns it. */ +export function getSandboxAcrossGatewayRoots( sandboxName: string, + home: string = resolveHome(), +): SandboxEntry | null { + return findSandboxAcrossGatewayRoots(sandboxName, home)?.entry ?? null; +} + +/** Persist intentional-stop state in the registry root that owns the sandbox. */ +export function recordSandboxStopIntentInOwningGatewayRegistry( + hit: CrossPortSandboxHit, stopped: boolean, home: string = resolveHome(), ): boolean { try { - const hit = findSandboxAcrossGatewayRoots(sandboxName, home); - if (!hit) return false; + const sandboxName = hit.entry.name; return withRegistryLockAt(hit.registryFile, () => { const registry = readGatewayRegistryFile(home, hit.registryFile); const current = registry?.sandboxes[sandboxName]; @@ -128,6 +136,45 @@ export function recordSandboxStopIntentAcrossGatewayRoots( } } +/** Persist intentional-stop state after resolving one unambiguous owning registry. */ +export function recordSandboxStopIntentAcrossGatewayRoots( + sandboxName: string, + stopped: boolean, + home: string = resolveHome(), +): boolean { + try { + const hit = findSandboxAcrossGatewayRoots(sandboxName, home); + return hit ? recordSandboxStopIntentInOwningGatewayRegistry(hit, stopped, home) : false; + } catch { + return false; + } +} + +/** Remove one sandbox from its owning registry while preserving default-pointer revision rules. */ +export function removeSandboxFromOwningGatewayRegistry( + hit: CrossPortSandboxHit, + home: string = resolveHome(), +): boolean { + const sandboxName = hit.entry.name; + return withRegistryLockAt(hit.registryFile, () => { + const registry = readGatewayRegistryFile(home, hit.registryFile); + if (!registry) return false; + const result = removeSandboxFromRegistry(registry, sandboxName); + if (!result.receipt) return false; + writeConfigFile(hit.registryFile, result.registry); + return true; + }); +} + +/** Remove one sandbox after resolving one unambiguous owning registry. */ +export function removeSandboxAcrossGatewayRoots( + sandboxName: string, + home: string = resolveHome(), +): boolean { + const hit = findSandboxAcrossGatewayRoots(sandboxName, home); + return hit ? removeSandboxFromOwningGatewayRegistry(hit, home) : false; +} + function listEntriesAcrossGatewayRoots(published: boolean, home: string): SandboxEntry[] { return listSandboxHitsAcrossGatewayRoots(home) .map(({ entry }) => entry) diff --git a/test/helpers/destroy-flow-test-harness.ts b/test/helpers/destroy-flow-test-harness.ts index bdc2b0d5356..843262aa8a1 100644 --- a/test/helpers/destroy-flow-test-harness.ts +++ b/test/helpers/destroy-flow-test-harness.ts @@ -259,6 +259,8 @@ export function createDestroyHarness(options: DestroyHarnessOptions = {}): Destr return removeExactDockerContainers(...args); }); const destroyExecution = requireSource("./destroy-execution.js"); + const forwardRecovery = requireSource("./forward-recovery.js"); + vi.spyOn(forwardRecovery, "teardownSandboxDashboardForward").mockResolvedValue(true); const destroyCommand = requireSource("../../../commands/sandbox/destroy.js").default; const destroyPreflight = requireSource("./destroy-preflight.js"); const sandboxSession = requireSource("../../state/sandbox-session.js"); From 131070db0d6c73590ef4bcbce886d287b47519a5 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 05:07:39 -0700 Subject: [PATCH 21/44] fix(status): preserve owning registry through recovery Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/sandbox/connect-flow.test.ts | 11 ++-- src/lib/actions/sandbox/connect.ts | 69 ++++++++++++++------ src/lib/actions/sandbox/forward-recovery.ts | 67 ++++++++++++------- src/lib/actions/sandbox/process-recovery.ts | 49 ++++++++++---- src/lib/actions/sandbox/stop.test.ts | 42 +++++++++++- src/lib/state/registry.ts | 4 ++ test/support/connect-flow-test-harness.ts | 7 ++ 7 files changed, 188 insertions(+), 61 deletions(-) diff --git a/src/lib/actions/sandbox/connect-flow.test.ts b/src/lib/actions/sandbox/connect-flow.test.ts index dbc15232621..62aabf0d47f 100644 --- a/src/lib/actions/sandbox/connect-flow.test.ts +++ b/src/lib/actions/sandbox/connect-flow.test.ts @@ -1053,7 +1053,7 @@ describe("connectSandbox flow", () => { expect(harness.publishLaunchReadinessSpy).not.toHaveBeenCalled(); }); - it("keeps active Hermes interactive setup inside receipt-owned recovery (#9203)", async () => { + it("keeps sibling-root Hermes interactive setup inside receipt-owned recovery (#9203)", 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"); @@ -1072,13 +1072,16 @@ describe("connectSandbox flow", () => { sessionAgent: { name: "hermes" }, registryEntry: { openshellDriver: "docker", - gatewayName: "nemoclaw", + gatewayName: "nemoclaw-8245", + gatewayPort: 8245, lifecycleGeneration: "generation-1", hermesToolGateways: ["tool-gateway"], }, portableReceiptDisposition: { kind: "hermes", phase: "active" }, portableRecoveryResult: { kind: "already-running" }, }); + const selectedRegistry = requireDist("../../src/lib/state/registry.js"); + selectedRegistry.getSandbox.mockReturnValue(null); const captureResolved = harness.captureResolvedOpenshellSpy.getMockImplementation()!; const forwardRecovery = requireDist("../../src/lib/actions/sandbox/forward-recovery.js"); let forwardsRestored = false; @@ -1123,7 +1126,7 @@ describe("connectSandbox flow", () => { expect(harness.recoverHermesPortableOllamaInferenceSpy).not.toHaveBeenCalled(); expect(harness.forwardAdapterStartSpy).toHaveBeenCalledOnce(); await expect( - forwardRecovery.areSandboxLaunchForwardsHealthy("alpha", "nemoclaw"), + forwardRecovery.areSandboxLaunchForwardsHealthy("alpha", "nemoclaw-8245"), ).resolves.toBe(true); expect(harness.forwardAdapterStartSpy.mock.invocationCallOrder[0]!).toBeLessThan( harness.startSandboxSessionSpy.mock.invocationCallOrder[0]!, @@ -1133,7 +1136,7 @@ describe("connectSandbox flow", () => { expect(harness.startSandboxSessionSpy).toHaveBeenCalledWith({ kind: "connect", sandboxName: "alpha", - target: { kind: "named", gatewayName: "nemoclaw" }, + target: { kind: "named", gatewayName: "nemoclaw-8245" }, }); expect(harness.createSessionExecutorSpy.mock.calls[0]?.[0]).toMatchObject({ environment: expect.not.objectContaining({ diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index ca337512b3a..de8f008c9d3 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -175,6 +175,26 @@ export type SandboxConnectOptions = { requireLaunchReadinessPublication?: boolean; }; +/** Resolve connect state from the registry root that owns the sandbox. */ +function readConnectSandbox(sandboxName: string): SandboxEntry | null { + return registry.getSandboxAcrossGatewayRoots(sandboxName) ?? registry.getSandbox(sandboxName); +} + +/** Prefer the owning registry row over the selected onboarding session. */ +function getConnectSessionAgent(sandboxName: string): AgentDefinition | null { + const sandbox = readConnectSandbox(sandboxName); + const selectedAgent = agentRuntime.getSessionAgent(sandboxName); + if (!sandbox) return selectedAgent; + const persistedAgent = sandbox.agent ?? "openclaw"; + if ( + selectedAgent?.name === persistedAgent || + (selectedAgent === null && persistedAgent === "openclaw") + ) { + return selectedAgent; + } + return agentRuntime.getRegisteredAgent(sandbox); +} + export type SandboxStartupRecoveryResult = Awaited< ReturnType > & { @@ -381,7 +401,7 @@ async function runSandboxConnectProbe( stage: "processes" | "inference" | "pairing", operation: () => Promise, ): Promise => (probeTiming ? probeTiming.measureAsync(stage, operation) : operation()); - const agent = agentRuntime.getSessionAgent(sandboxName); + const agent = getConnectSessionAgent(sandboxName); const agentName = agentRuntime.getAgentDisplayName(agent); if (hermesPortable) { if (probeOnly !== true) throw new Error("Hermes inference recovery requires probe-only mode"); @@ -669,10 +689,20 @@ function ordinaryLaunchReadinessDeps( ): NonNullable[1]> { return { commandExecutor: sandboxCommandExecutor, + getSandbox: readConnectSandbox, ...probeTimingLaunchReadinessDeps(probeTiming), }; } +function withConnectLaunchReadinessMutationGate( + publication: Parameters[0], + operation: () => Promise | T, +) { + return withLaunchReadinessMutationGate(publication, operation, { + getSandbox: readConnectSandbox, + }); +} + function captureHermesPortableReadinessObservation( authority: HermesPortableReadinessCommandAuthority, args: string[], @@ -711,13 +741,14 @@ function hermesPortableLaunchReadinessDeps( ); return { ...createBoundLaunchReadinessDeps(capture, commandExecutor), + getSandbox: readConnectSandbox, ...probeTimingLaunchReadinessDeps(probeTiming), }; } function portableAgentLifecycleAuthorityDeps() { return { - readRegistry: registry.getSandbox, + readRegistry: readConnectSandbox, stateDir: defaultPortableDemoStateDir(process.env), }; } @@ -876,7 +907,7 @@ async function prepareHermesPortableForwardsForConnectProbeMeasured( intent: "connect-probe-only", sandboxName, authority, - readRegistry: registry.getSandbox, + readRegistry: readConnectSandbox, ...(commandAuthority ? { commandAuthority } : {}), }); return await (probeTiming ? probeTiming.measureAsync("forward", prepare) : prepare()); @@ -1071,7 +1102,7 @@ async function verifyOrRecoverHermesPortableInferenceRouteForConnectOrExit( intent: options.intent ?? "connect-probe-only", sandboxName, authority, - readRegistry: registry.getSandbox, + readRegistry: readConnectSandbox, assertCallerTransactionCurrent: options.commandAuthority?.assertTransactionCurrent, assertCallerCurrent: options.commandAuthority?.assertCurrent, ...(options.commandAuthority @@ -1255,7 +1286,7 @@ function failConnectReadinessDockerRuntimeDown(sandboxName: string): never { } async function failIfGatewayBlocksConnectReadiness(sandboxName: string): Promise { - const sb = registry.getSandbox(sandboxName); + const sb = readConnectSandbox(sandboxName); const lifecycle = await getNamedGatewayLifecycleState(resolveSandboxGatewayName(sb)); if (lifecycle.error) failConnectReadinessObservation(sandboxName, lifecycle.error); if (isBlockingGatewayLifecycle(lifecycle)) { @@ -1628,7 +1659,7 @@ async function ensureSandboxInferenceRouteUnlocked( let sb: SandboxEntry | null = null; let inference: ReturnType | null = null; try { - sb = registry.getSandbox(sandboxName); + sb = readConnectSandbox(sandboxName); if (!sb) return { sandbox: null, routeHealthy: null }; // This projection is total; the catch below handles only later gateway and repair failures. inference = registry.getSandboxEntryInference(sb); @@ -1775,13 +1806,13 @@ async function ensureSandboxInferenceRoute( agent: InferenceRouteProbeAgent, { quiet = false }: { quiet?: boolean } = {}, ): Promise { - const snapshot = registry.getSandbox(sandboxName); + const snapshot = readConnectSandbox(sandboxName); if (!snapshot) return { sandbox: null, routeHealthy: null }; if (registry.getSandboxEntryInference(snapshot).kind !== "configured") return { sandbox: snapshot, routeHealthy: null }; const gatewayName = resolveSandboxGatewayName(snapshot); return withGatewayRouteMutationLock(gatewayName, () => { - const lockedSnapshot = registry.getSandbox(sandboxName); + const lockedSnapshot = readConnectSandbox(sandboxName); if ( lockedSnapshot && registry.getSandboxEntryInference(lockedSnapshot).kind === "configured" && @@ -2091,7 +2122,7 @@ async function runConnectEntryPreflight( ) : null; const registered = - hermesAuthority?.entry ?? measure("authority", () => registry.getSandbox(sandboxName)); + hermesAuthority?.entry ?? measure("authority", () => readConnectSandbox(sandboxName)); if (registered?.pendingRouteReservation === true) { throw new Error( `Sandbox '${sandboxName}' is still being created by onboarding. Wait for onboarding to finish or remove the incomplete sandbox before connecting.`, @@ -2281,7 +2312,7 @@ export async function printInteractiveSessionHints(sandboxName: string): Promise try { // A live DCode version command can source personal profiles before route verification. const versionCheck = await sandboxVersion.checkAgentVersion(sandboxName, { - skipProbe: agentRuntime.getSessionAgent(sandboxName)?.name === "langchain-deepagents-code", + skipProbe: getConnectSessionAgent(sandboxName)?.name === "langchain-deepagents-code", }); if (versionCheck.isStale) { for (const line of sandboxVersion.formatStalenessWarning(sandboxName, versionCheck)) { @@ -2355,9 +2386,7 @@ export async function prepareInteractiveSession(sandboxName: string): Promise<{ await printInteractiveSessionHints(sandboxName); const processCheck = await checkAndRecoverSandboxProcesses(sandboxName); if ("secretBoundaryRefused" in processCheck && processCheck.secretBoundaryRefused) { - const agentName = agentRuntime.getAgentDisplayName( - agentRuntime.getSessionAgent(sandboxName), - ); + const agentName = agentRuntime.getAgentDisplayName(getConnectSessionAgent(sandboxName)); exitOnSecretBoundaryRefusal(sandboxName, agentName, processCheck, "Connect"); } const recoveryFailureDetail = @@ -2369,9 +2398,7 @@ export async function prepareInteractiveSession(sandboxName: string): Promise<{ ? "the gateway recovery attempt did not complete" : null; if (recoveryFailureDetail) { - const agentName = agentRuntime.getAgentDisplayName( - agentRuntime.getSessionAgent(sandboxName), - ); + const agentName = agentRuntime.getAgentDisplayName(getConnectSessionAgent(sandboxName)); await exitOnGatewayRecoveryFailure( sandboxName, agentName, @@ -2395,7 +2422,7 @@ export async function prepareInteractiveSession(sandboxName: string): Promise<{ }); await requalify(); // ── Inference route swap (#1248, #3390) ─────────────────────── - const agent = agentRuntime.getSessionAgent(sandboxName); + const agent = getConnectSessionAgent(sandboxName); const portableInference = hermesPortable ? await prepareHermesPortableInteractiveInference(sandboxName, agent) : null; @@ -2733,7 +2760,7 @@ async function prepareConnectSandboxWithinLifecycleFence( process.exit(1); } const publicationRequest = publicationFromDecision(sandboxName, readiness); - const gated = await withLaunchReadinessMutationGate(publicationRequest, async () => { + const gated = await withConnectLaunchReadinessMutationGate(publicationRequest, async () => { if ( readiness.category === "missing" && hermesMissingFastPathEligible && @@ -2766,7 +2793,7 @@ async function prepareConnectSandboxWithinLifecycleFence( sandboxName, entry: retainedAuthority.active.entry, operatingReceipt: retainedAuthority.command.receipt, - readRegistry: registry.getSandbox, + readRegistry: readConnectSandbox, assertCallerCurrent: assertBaseCurrent, env: retainedAuthority.command.env, }), @@ -2784,7 +2811,7 @@ async function prepareConnectSandboxWithinLifecycleFence( intent: "connect-probe-only", sandboxName, authority: retainedAuthority.active, - readRegistry: registry.getSandbox, + readRegistry: readConnectSandbox, commandAuthority: retainedAuthority.command, }), ); @@ -2849,7 +2876,7 @@ async function prepareConnectSandboxWithinLifecycleFence( ); if ( startedStoppedContainer && - !registry.recordSandboxStopIntent(sandboxName, false, registry.updateSandbox) + !registry.recordSandboxStopIntentAcrossGatewayRoots(sandboxName, false) ) { throw new Error( `Sandbox '${sandboxName}' recovered, but NemoClaw could not clear its intentional-stop record. Run '${CLI_NAME} ${sandboxName} status' before another lifecycle command.`, diff --git a/src/lib/actions/sandbox/forward-recovery.ts b/src/lib/actions/sandbox/forward-recovery.ts index d30e35d7780..9bb9cd3a945 100644 --- a/src/lib/actions/sandbox/forward-recovery.ts +++ b/src/lib/actions/sandbox/forward-recovery.ts @@ -64,6 +64,28 @@ export type { PreparedHermesPortableForwardRecovery, } from "./probe/hermes-portable-forward-adapter-recovery"; +/** Read forward authority from the registry root that owns the sandbox. */ +function readForwardSandbox(sandboxName: string): registry.SandboxEntry | null { + return registry.getSandboxAcrossGatewayRoots(sandboxName) ?? registry.getSandbox(sandboxName); +} + +/** Resolve the persisted agent without falling back to a different registry root. */ +function getForwardSessionAgent( + sandboxName: string, +): ReturnType { + const sandbox = readForwardSandbox(sandboxName); + const selectedAgent = agentRuntime.getSessionAgent(sandboxName); + if (!sandbox) return selectedAgent; + const persistedAgent = sandbox.agent ?? "openclaw"; + if ( + selectedAgent?.name === persistedAgent || + (selectedAgent === null && persistedAgent === "openclaw") + ) { + return selectedAgent; + } + return agentRuntime.getRegisteredAgent(sandbox); +} + export interface HermesPortableForwardCommandAuthority { readonly env: NodeJS.ProcessEnv; readonly executablePath: string; @@ -214,7 +236,7 @@ function assertSandboxForwardAuthorityCurrent( gatewayName: string, expected: ForwardGatewayAuthority, ): void { - const sandbox = registry.getSandbox(sandboxName); + const sandbox = readForwardSandbox(sandboxName); if (!sandbox || resolveSandboxGatewayName(sandbox) !== gatewayName) { throw new Error("Sandbox gateway changed during forward observation"); } @@ -260,13 +282,13 @@ export function resolveSandboxDashboardPort( sandboxName: string, deps: SandboxPortDeps = {}, ): number { - const getSandbox = deps.getSandbox ?? registry.getSandbox; + const getSandbox = deps.getSandbox ?? readForwardSandbox; const sandbox = getSandbox(sandboxName); if (isValidPort(sandbox?.dashboardPort)) { return sandbox.dashboardPort; } - const getSessionAgent = deps.getSessionAgent ?? agentRuntime.getSessionAgent; + const getSessionAgent = deps.getSessionAgent ?? getForwardSessionAgent; const agent = getSessionAgent(sandboxName); if (agent && agentRuntime.hasGatewayRuntime(agent) && isValidPort(agent.forwardPort)) { return agent.forwardPort; @@ -283,11 +305,11 @@ export function resolveSandboxDashboardPort( * default port as unreachable. */ export function resolveSandboxHealthProbeUrl(sandboxName: string): string { - const agent = agentRuntime.getSessionAgent(sandboxName); + const agent = getForwardSessionAgent(sandboxName); if (agent && agentRuntime.hasGatewayRuntime(agent)) { return retargetHermesApiPortInUrl( agentRuntime.getHealthProbeUrl(agent), - resolveSandboxHermesApiPort(registry.getSandbox(sandboxName) ?? {}), + resolveSandboxHermesApiPort(readForwardSandbox(sandboxName) ?? {}), ); } return `http://127.0.0.1:${resolveSandboxDashboardPort(sandboxName)}/health`; @@ -308,7 +330,7 @@ export async function teardownSandboxDashboardForward( } = {}, ): Promise { try { - const getSandbox = deps.getSandbox ?? registry.getSandbox; + const getSandbox = deps.getSandbox ?? readForwardSandbox; const sandbox = getSandbox(sandboxName); if (!sandbox) return true; const registeredAgent = sandbox.agent ? agentRuntime.getRegisteredAgent(sandbox) : null; @@ -387,7 +409,7 @@ export async function ensureSandboxPortForward( options: SandboxForwardRecoveryOptions = {}, ): Promise { const port = resolveSandboxDashboardPort(sandboxName); - const sandbox = registry.getSandbox(sandboxName); + const sandbox = readForwardSandbox(sandboxName); const remoteBindRequested = isRemoteDashboardBindRequested(process.env.NEMOCLAW_DASHBOARD_BIND); const bind = resolveDashboardForwardBind(sandbox, { requestedBind: process.env.NEMOCLAW_DASHBOARD_BIND, @@ -405,7 +427,7 @@ export async function ensureSandboxPortForward( afterSuccess: options.afterSuccess, beforeStart: () => (!remoteBindRequested || - registry.getSandbox(sandboxName)?.dashboardRemoteBindPrepared === true) && + readForwardSandbox(sandboxName)?.dashboardRemoteBindPrepared === true) && (options.beforeStart?.() ?? true), runtimeSelection: options.runtimeSelection, }); @@ -437,7 +459,7 @@ export async function describeSandboxForwardListener( runtimeSelection?: OpenShellRuntimeSelection; } = {}, ): Promise { - const bind = resolveDashboardForwardBind(registry.getSandbox(sandboxName), { + const bind = resolveDashboardForwardBind(readForwardSandbox(sandboxName), { requestedBind: process.env.NEMOCLAW_DASHBOARD_BIND, wsl: isWsl({ isWsl: options.isWsl }), }); @@ -513,7 +535,7 @@ async function inspectSandboxPortForwardListener( runtimeSelection?: OpenShellRuntimeSelection, forwardAdapterForAuthority: OpenShellForwardObservationAdapterFactory = createOpenShellForwardAdapterForAuthority, ): Promise { - const sandbox = registry.getSandbox(sandboxName); + const sandbox = readForwardSandbox(sandboxName); if (!sandbox) return "absent"; try { const gatewayName = runtimeSelection?.gatewayName ?? resolveSandboxGatewayName(sandbox); @@ -582,7 +604,7 @@ export async function ensureSandboxPortForwardForPort( } if (!beforeStart()) return false; try { - const sandbox = registry.getSandbox(sandboxName); + const sandbox = readForwardSandbox(sandboxName); if (!sandbox) throw new Error(`Sandbox '${sandboxName}' is not registered`); const gatewayName = runtimeSelection?.gatewayName ?? resolveSandboxGatewayName(sandbox); const { authority, runtime } = forwardRuntimeAuthority(gatewayName, runtimeSelection); @@ -626,6 +648,7 @@ export async function ensureHermesDashboardPortForwardIfEnabled( runtimeSelection?: OpenShellRuntimeSelection, ): Promise { return ensureHermesDashboardPortForward(sandboxName, { + getRecoveryConfig: (name) => getHermesDashboardRecoveryConfig(name, readForwardSandbox), isPortForwardHealthy: (name, port) => isSandboxPortForwardHealthy(name, port, undefined, runtimeSelection), ensurePortForward: (name, port) => @@ -635,7 +658,7 @@ export async function ensureHermesDashboardPortForwardIfEnabled( function getSandboxMessagingHostForward( sandboxName: string, - entry: ReturnType = registry.getSandbox(sandboxName), + entry: ReturnType = readForwardSandbox(sandboxName), ): SandboxMessagingHostForwardPlan | null { const parsed = parseSandboxMessagingPlan(entry?.messaging?.plan, { sandboxName }); const plan = parsed ? hydrateDerivedSandboxMessagingPlanFields(parsed) : null; @@ -714,10 +737,10 @@ export async function ensureDeclaredAgentForwardPortsHealthy( primaryPort: number, runtimeSelection?: OpenShellRuntimeSelection, ): Promise { - const agent = agentRuntime.getSessionAgent(sandboxName); + const agent = getForwardSessionAgent(sandboxName); if (!agent) return null; - const hermesDashboard = getHermesDashboardRecoveryConfig(sandboxName); - const sandbox = registry.getSandbox(sandboxName); + const hermesDashboard = getHermesDashboardRecoveryConfig(sandboxName, readForwardSandbox); + const sandbox = readForwardSandbox(sandboxName); const ports = resolveDeclaredAgentForwardPorts( sandbox, primaryPort, @@ -767,12 +790,12 @@ export async function areSandboxLaunchForwardsHealthy( ) => Pick; } = {}, ): Promise { - const sandbox = registry.getSandbox(sandboxName); + const sandbox = readForwardSandbox(sandboxName); if (!sandbox) return false; try { const owningGatewayName = resolveSandboxGatewayName(sandbox); if (gatewayName && gatewayName !== owningGatewayName) return false; - const agent = agentRuntime.getSessionAgent(sandboxName); + const agent = getForwardSessionAgent(sandboxName); const primaryPort = resolveSandboxDashboardPort(sandboxName, { getSandbox: () => sandbox, getSessionAgent: () => agent, @@ -784,11 +807,11 @@ export async function areSandboxLaunchForwardsHealthy( primaryPort, ); const assertForwardPlanCurrent = (): void => { - const currentSandbox = registry.getSandbox(sandboxName); + const currentSandbox = readForwardSandbox(sandboxName); if (!currentSandbox || resolveSandboxGatewayName(currentSandbox) !== owningGatewayName) { throw new Error("Sandbox gateway changed during forward observation"); } - const currentAgent = agentRuntime.getSessionAgent(sandboxName); + const currentAgent = getForwardSessionAgent(sandboxName); const currentPrimaryPort = resolveSandboxDashboardPort(sandboxName, { getSandbox: () => currentSandbox, getSessionAgent: () => currentAgent, @@ -836,7 +859,7 @@ export async function areSandboxLaunchForwardsHealthy( if (observations.some((observation) => observation.state !== "owned")) return false; assertForwardPlanCurrent(); - const currentPrimaryBind = resolveDashboardForwardBind(registry.getSandbox(sandboxName), { + const currentPrimaryBind = resolveDashboardForwardBind(readForwardSandbox(sandboxName), { requestedBind: process.env.NEMOCLAW_DASHBOARD_BIND, wsl: isWsl(), }); @@ -876,9 +899,9 @@ function resolveSandboxLaunchForwardPortsFromAuthority( /** Resolve the complete forward set used by launch-readiness health. */ export function resolveSandboxLaunchForwardPorts(sandboxName: string): number[] | null { - const sandbox = registry.getSandbox(sandboxName); + const sandbox = readForwardSandbox(sandboxName); if (!sandbox) return null; - const agent = agentRuntime.getSessionAgent(sandboxName); + const agent = getForwardSessionAgent(sandboxName); const primaryPort = resolveSandboxDashboardPort(sandboxName, { getSandbox: () => sandbox, getSessionAgent: () => agent, diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 3bf3220914c..2f8222912d8 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -101,6 +101,29 @@ export type { PreparedHermesPortableForwardRecovery, }; +/** Read recovery authority from the registry root that owns the sandbox. */ +function readRecoverySandbox(sandboxName: string): registry.SandboxEntry | null { + return registry.getSandboxAcrossGatewayRoots(sandboxName) ?? registry.getSandbox(sandboxName); +} + +/** Resolve the persisted agent without selecting a different gateway root. */ +function getRecoverySessionAgent( + sandboxName?: string, +): ReturnType { + if (!sandboxName) return agentRuntime.getSessionAgent(); + const sandbox = readRecoverySandbox(sandboxName); + const selectedAgent = agentRuntime.getSessionAgent(sandboxName); + if (!sandbox) return selectedAgent; + const persistedAgent = sandbox.agent ?? "openclaw"; + if ( + selectedAgent?.name === persistedAgent || + (selectedAgent === null && persistedAgent === "openclaw") + ) { + return selectedAgent; + } + return agentRuntime.getRegisteredAgent(sandbox); +} + export type { GatewayRestartDeps, GatewayRestartFailureLayer, @@ -397,7 +420,7 @@ async function isSandboxGatewayRunning( sandboxName: string, runtimeSelection?: OpenShellRuntimeSelection, ): Promise { - const agent = agentRuntime.getSessionAgent(sandboxName); + const agent = getRecoverySessionAgent(sandboxName); if (agent && !agentRuntime.hasGatewayRuntime(agent)) return null; const probeUrl = getSandboxHealthProbeUrl(sandboxName); const command = sandboxGatewayRecoveryProbeCommand(probeUrl); @@ -633,7 +656,7 @@ type ManagedGatewayProbeOptions = { }; function canProbeManagedGateway(sandboxName: string, options: ManagedGatewayProbeOptions): boolean { - const getSandbox = options.getSandboxImpl ?? registry.getSandbox; + const getSandbox = options.getSandboxImpl ?? readRecoverySandbox; const entry = getSandbox(sandboxName); if (!entry) return false; const persistedAgent = entry.agent ?? "openclaw"; @@ -641,7 +664,7 @@ function canProbeManagedGateway(sandboxName: string, options: ManagedGatewayProb if (!usesManagedGatewayController(entry)) return false; - const getSessionAgent = options.getSessionAgentImpl ?? agentRuntime.getSessionAgent; + const getSessionAgent = options.getSessionAgentImpl ?? getRecoverySessionAgent; const agent = getSessionAgent(sandboxName); if (persistedAgent === "hermes" && agent?.name !== "hermes") return false; if (agent && !agentRuntime.hasGatewayRuntime(agent)) return false; @@ -686,7 +709,7 @@ export async function isSandboxGatewayRunningForStatus( requestGatewaySupervisorActionImpl?: typeof executeGatewaySupervisorAction; } = {}, ): Promise { - const agent = (options.getSessionAgent ?? agentRuntime.getSessionAgent)(sandboxName); + const agent = (options.getSessionAgent ?? getRecoverySessionAgent)(sandboxName); if (agent && !agentRuntime.hasGatewayRuntime(agent)) return null; if (agent?.name === "hermes") { const result = (options.requestGatewaySupervisorActionImpl ?? executeGatewaySupervisorAction)( @@ -785,11 +808,11 @@ async function recoverSandboxProcesses( runtimeSelection?: OpenShellRuntimeSelection; } = {}, ): Promise { - const agent = agentRuntime.getSessionAgent(sandboxName); + const agent = getRecoverySessionAgent(sandboxName); const dashboardPort = resolveSandboxDashboardPort(sandboxName); let persistedAgent: string | null; try { - persistedAgent = sandboxAgentName(sandboxName, registry.getSandbox); + persistedAgent = sandboxAgentName(sandboxName, readRecoverySandbox); } catch (error) { const detail = error instanceof Error && error.message.trim() @@ -798,7 +821,7 @@ async function recoverSandboxProcesses( quiet || printGatewayRestartFailure(sandboxName, "unsupported agent", detail); return null; } - const persistedSandbox = registry.getSandbox(sandboxName); + const persistedSandbox = readRecoverySandbox(sandboxName); const persistedProvider = resolveRegisteredRuntimeProvider(persistedSandbox?.openshellDriver); // An explicit provider recovery surface owns its runtime transition. if ( @@ -873,8 +896,8 @@ export async function restartSandboxGateway( restartSandboxGatewayWithDeps(sandboxName, { quiet, deps: { - getSessionAgent: agentRuntime.getSessionAgent, - getSandbox: registry.getSandbox, + getSessionAgent: getRecoverySessionAgent, + getSandbox: readRecoverySandbox, resolveSandboxDashboardPort, executeSandboxExecCommand: (name, command, timeout) => executeSandboxExecCommand( @@ -887,7 +910,7 @@ export async function restartSandboxGateway( waitForRecoveredSandboxGateway(name, { ...options, runtimeSelection, - timeoutSeconds: gatewayRecoveryTimeoutSeconds(agentRuntime.getSessionAgent(name)), + timeoutSeconds: gatewayRecoveryTimeoutSeconds(getRecoverySessionAgent(name)), }), ensureSandboxPortForward: (name) => ensureSandboxPortForward(name, { runtimeSelection }), ensureHermesDashboardPortForwardIfEnabled: (name) => @@ -1249,7 +1272,7 @@ function printHostManagedGatewayRecoveryHints( let agentName = agent?.name ?? null; if (!agentName) { try { - agentName = registry.getSandbox(sandboxName)?.agent ?? null; + agentName = readRecoverySandbox(sandboxName)?.agent ?? null; } catch { // Preserve the legacy OpenClaw hint when registry lookup itself failed. } @@ -1272,7 +1295,7 @@ function recoveryAgentDisplayName( ): string { if (agent) return agentRuntime.getAgentDisplayName(agent); try { - const persistedAgent = registry.getSandbox(sandboxName)?.agent; + const persistedAgent = readRecoverySandbox(sandboxName)?.agent; if (persistedAgent && persistedAgent !== "openclaw") return persistedAgent; } catch { // The recovery path below reports registry lookup failures with the @@ -1498,7 +1521,7 @@ async function checkAndRecoverSandboxProcessesWithoutHostLock( stage: "processes" | "forward", operation: () => Promise, ): Promise => (probeTiming ? probeTiming.measureAsync(stage, operation) : operation()); - const recoveryAgent = agentRuntime.getSessionAgent(sandboxName); + const recoveryAgent = getRecoverySessionAgent(sandboxName); const recoveryDisplayName = recoveryAgentDisplayName(sandboxName, recoveryAgent); if (recoveryAgent && !agentRuntime.hasGatewayRuntime(recoveryAgent)) { return { diff --git a/src/lib/actions/sandbox/stop.test.ts b/src/lib/actions/sandbox/stop.test.ts index dce046c2e2b..24b3753dd4f 100644 --- a/src/lib/actions/sandbox/stop.test.ts +++ b/src/lib/actions/sandbox/stop.test.ts @@ -343,6 +343,7 @@ describe("stopSandbox", () => { sandboxes: { "my-sandbox": { name: "my-sandbox", + dashboardPort: 19443, gatewayName: "nemoclaw-8245", gatewayPort: 8245, }, @@ -351,7 +352,35 @@ describe("stopSandbox", () => { ); vi.stubEnv("HOME", home); try { - const h = harness(); + const verifyForwardRelease = vi + .fn() + .mockResolvedValue({ state: "released" }); + const h = harness({ + teardownSandboxDashboardForward: (sandboxName) => + teardownSandboxDashboardForward(sandboxName, { + forwardAdapterForAuthority: () => ({ verifyForwardRelease }), + resolveForwardRuntimeAuthority: () => ({ + authority: { + endpoint: "https://127.0.0.1:8245", + owner: { + endpoint: null, + gatewayName: "nemoclaw-8245", + gatewayPort: 8245, + mode: "nemoclaw-managed", + requiredCapabilities: [], + source: "standalone", + stateDir: null, + supervisor: null, + }, + }, + runtime: { + gatewayEndpoint: "https://127.0.0.1:8245", + gatewayName: "nemoclaw-8245", + workspace: "default", + }, + }), + }), + }); const { getSandbox: _getSandbox, listSandboxes: _listSandboxes, @@ -364,6 +393,17 @@ describe("stopSandbox", () => { expect( JSON.parse(fs.readFileSync(registryFile, "utf8")).sandboxes["my-sandbox"], ).toMatchObject({ gatewayPort: 8245, stopped: true }); + expect(verifyForwardRelease).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + forwards: [ + expect.objectContaining({ + gatewayName: "nemoclaw-8245", + port: 19443, + sandboxName: "my-sandbox", + }), + ], + }), + ); } finally { vi.unstubAllEnvs(); fs.rmSync(home, { recursive: true, force: true }); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 54ad8a3844a..4f97a52481a 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -92,6 +92,10 @@ export { withLock, } from "./registry/lock"; export { load, REGISTRY_FILE, save } from "./registry/persistence"; +export { + getSandboxAcrossGatewayRoots, + recordSandboxStopIntentAcrossGatewayRoots, +} from "./registry/cross-port"; export type { SandboxEntry, SandboxGpuProofResult, diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 69f6398a500..75314a48fe7 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -699,6 +699,13 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne : null; }, ); + vi.spyOn(crossPortRegistry, "getSandboxAcrossGatewayRoots").mockImplementation( + (name: unknown) => registryEntries.find((candidate) => candidate.name === String(name)) ?? null, + ); + vi.spyOn(crossPortRegistry, "recordSandboxStopIntentAcrossGatewayRoots").mockImplementation((( + name: string, + stopped: boolean, + ) => registry.recordSandboxStopIntent(name, stopped, registry.updateSandbox)) as never); vi.spyOn(crossPortRegistry, "listPublishedSandboxesAcrossGatewayRoots").mockImplementation( () => registryEntries, ); From f41f6fe8bc2e2d83225700e5be44058675b2ce95 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 05:29:38 -0700 Subject: [PATCH 22/44] test(status): align fixtures with owning registry Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../launch-readiness-forward-observation.test.ts | 7 +++++++ test/runtime/gateway/gateway-state-reconcile-2276.test.ts | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/test/e2e-runtime/launch-readiness-forward-observation.test.ts b/test/e2e-runtime/launch-readiness-forward-observation.test.ts index f7071e77f9e..d3be184a14d 100644 --- a/test/e2e-runtime/launch-readiness-forward-observation.test.ts +++ b/test/e2e-runtime/launch-readiness-forward-observation.test.ts @@ -74,6 +74,7 @@ function createFakeAdapter( function mockLaunchForwardAuthority(gatewayRuntime = true): void { vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ + name: "openclaw", runtime: { kind: gatewayRuntime ? "gateway" : "terminal" }, forward_ports: [18_790], } as never); @@ -84,6 +85,9 @@ function mockLaunchForwardAuthority(gatewayRuntime = true): void { gatewayName: "nemoclaw", gatewayPort: 8_080, }); + vi.spyOn(registry, "getSandboxAcrossGatewayRoots").mockImplementation((sandboxName) => + registry.getSandbox(sandboxName), + ); vi.spyOn(platform, "isWsl").mockReturnValue(false); vi.spyOn(gatewayTeardownAuthority, "resolveGatewayForwardAuthority").mockReturnValue( gatewayAuthority(null), @@ -249,6 +253,7 @@ it("rejects same-gateway required-port drift after every exact target was proved () => "owned", () => { vi.mocked(agentRuntime.getSessionAgent).mockReturnValue({ + name: "openclaw", runtime: { kind: "gateway" }, forward_ports: [18_791], } as never); @@ -285,10 +290,12 @@ it("rejects terminal-to-gateway plan drift before reporting zero forwards health mockLaunchForwardAuthority(false); vi.mocked(agentRuntime.getSessionAgent) .mockReturnValueOnce({ + name: "openclaw", runtime: { kind: "terminal" }, forward_ports: [18_790], } as never) .mockReturnValue({ + name: "openclaw", runtime: { kind: "gateway" }, forward_ports: [18_790], } as never); diff --git a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts index 69a9b8069b1..bff2a8a14d3 100644 --- a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts +++ b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts @@ -332,7 +332,7 @@ beforeEach(() => { dockerInvocationsFile = path.join(tmpDir, "docker-invocations.log"); fs.mkdirSync(homeLocalBin, { recursive: true }); - fs.mkdirSync(registryDir, { recursive: true }); + fs.mkdirSync(registryDir, { recursive: true, mode: 0o700 }); fs.writeFileSync(installerInvocationsFile, ""); fs.writeFileSync(dockerInvocationsFile, ""); // Image freshness has its own tests; this process fixture represents unchanged inputs. From 91fcc7265eab58ec309e4169e117621ae4e3a8bc Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 07:36:17 -0700 Subject: [PATCH 23/44] fix(status): pin rebuild to owning registry Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/commands/sandbox/rebuild.test.ts | 21 ++++ src/commands/sandbox/rebuild.ts | 49 +++++++-- src/lib/actions/sandbox/connect.ts | 16 +-- src/lib/actions/sandbox/forward-recovery.ts | 16 +-- .../sandbox/inference-invocation-probe.ts | 6 +- src/lib/actions/sandbox/process-recovery.ts | 17 +-- .../actions/sandbox/rebuild-flow-helpers.ts | 1 + .../sandbox/rebuild-gateway-drift.test.ts | 103 +++++++++++++++++ src/lib/actions/sandbox/rebuild-pipeline.ts | 13 ++- .../sandbox/rebuild/owning-registry-worker.ts | 59 ++++++++++ .../sandbox/rebuild/owning-registry.ts | 104 ++++++++++++++++++ src/lib/agent/runtime.test.ts | 31 +++++- src/lib/agent/runtime.ts | 22 ++++ src/lib/cli/nemoclaw-oclif-command.ts | 19 ++++ src/lib/onboard/credential-env.test.ts | 26 +++-- src/lib/onboard/credential-env.ts | 7 +- .../state/portable-uninstall-retirement.ts | 9 +- src/lib/state/registry/cross-port.ts | 3 + 18 files changed, 459 insertions(+), 63 deletions(-) create mode 100644 src/lib/actions/sandbox/rebuild/owning-registry-worker.ts create mode 100644 src/lib/actions/sandbox/rebuild/owning-registry.ts diff --git a/src/commands/sandbox/rebuild.test.ts b/src/commands/sandbox/rebuild.test.ts index ab5d6e11f1b..f214b400e0b 100644 --- a/src/commands/sandbox/rebuild.test.ts +++ b/src/commands/sandbox/rebuild.test.ts @@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ + delegateRebuildToOwningRegistry: vi.fn(async () => false), rebuildSandbox: vi.fn(async () => undefined), retireRebuildRecoveryBackup: vi.fn(() => ({ backupPath: "/backups/alpha/2026-09-01", @@ -13,6 +14,9 @@ const mocks = vi.hoisted(() => ({ })); vi.mock("../../lib/actions/sandbox/rebuild", () => mocks); +vi.mock("../../lib/actions/sandbox/rebuild/owning-registry", () => ({ + delegateRebuildToOwningRegistry: mocks.delegateRebuildToOwningRegistry, +})); import RebuildCliCommand from "./rebuild"; @@ -63,4 +67,21 @@ describe("sandbox:rebuild command", () => { ); expect(mocks.retireRebuildRecoveryBackup).not.toHaveBeenCalled(); }); + + it("delegates a sibling-root rebuild before the command lifecycle fence", async () => { + mocks.delegateRebuildToOwningRegistry.mockResolvedValueOnce(true); + + await RebuildCliCommand.run(["alpha", "--yes", "--verbose"], rootDir); + + expect(mocks.delegateRebuildToOwningRegistry).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "alpha", + options: expect.objectContaining({ yes: true, verbose: true }), + executionOptions: {}, + }), + expect.any(String), + expect.any(String), + ); + expect(mocks.rebuildSandbox).not.toHaveBeenCalled(); + }); }); diff --git a/src/commands/sandbox/rebuild.ts b/src/commands/sandbox/rebuild.ts index 8b0b4b9fa5b..3abed1205cc 100644 --- a/src/commands/sandbox/rebuild.ts +++ b/src/commands/sandbox/rebuild.ts @@ -2,15 +2,38 @@ // SPDX-License-Identifier: Apache-2.0 import { Args, Flags } from "@oclif/core"; +import os from "node:os"; import { rebuildSandbox, retireRebuildRecoveryBackup } from "../../lib/actions/sandbox/rebuild"; +import { delegateRebuildToOwningRegistry } from "../../lib/actions/sandbox/rebuild/owning-registry"; import { forceFlag, yesFlag } from "../../lib/cli/common-flags"; import { NemoClawCommand } from "../../lib/cli/nemoclaw-oclif-command"; +import type { RebuildSandboxOptions } from "../../lib/domain/lifecycle/options"; import { DCODE_AUTO_APPROVAL_MODES, type DcodeAutoApprovalMode, } from "../../lib/onboard/dcode-auto-approval"; import { TOOL_DISCLOSURE_VALUES, type ToolDisclosure } from "../../lib/tool-disclosure"; +import { REGISTRY_FILE } from "../../lib/state/registry/persistence"; + +function rebuildOptionsFromFlags(flags: { + "dcode-auto-approval"?: unknown; + force?: boolean; + observability?: boolean; + "tool-disclosure"?: unknown; + verbose?: boolean; + yes?: boolean; +}): RebuildSandboxOptions { + return { + dcodeAutoApprovalMode: + (flags["dcode-auto-approval"] as DcodeAutoApprovalMode | undefined) ?? undefined, + force: flags.force === true, + ...(flags.observability === undefined ? {} : { observabilityEnabled: flags.observability }), + toolDisclosure: (flags["tool-disclosure"] as ToolDisclosure | undefined) ?? undefined, + verbose: flags.verbose === true, + yes: flags.yes === true, + }; +} export default class RebuildCliCommand extends NemoClawCommand { static id = "sandbox:rebuild"; @@ -54,6 +77,22 @@ export default class RebuildCliCommand extends NemoClawCommand { }), }; + protected override async runBeforeLifecycleBoundary(): Promise { + const parsed = await this.parse(RebuildCliCommand); + this.retainLifecycleParserOutput(parsed); + const { args, flags } = parsed; + if (flags["retire-recovery"]) return false; + return await delegateRebuildToOwningRegistry( + { + sandboxName: args.sandboxName, + options: rebuildOptionsFromFlags(flags), + executionOptions: {}, + }, + process.env.HOME || os.homedir(), + REGISTRY_FILE, + ); + } + public async run(): Promise { const { args, flags } = await this.parse(RebuildCliCommand); const recoveryTransactionId = flags["retire-recovery"]; @@ -68,14 +107,6 @@ export default class RebuildCliCommand extends NemoClawCommand { ); return; } - await rebuildSandbox(args.sandboxName, { - dcodeAutoApprovalMode: - (flags["dcode-auto-approval"] as DcodeAutoApprovalMode | undefined) ?? undefined, - force: flags.force === true, - ...(flags.observability === undefined ? {} : { observabilityEnabled: flags.observability }), - toolDisclosure: (flags["tool-disclosure"] as ToolDisclosure | undefined) ?? undefined, - verbose: flags.verbose === true, - yes: flags.yes === true, - }); + await rebuildSandbox(args.sandboxName, rebuildOptionsFromFlags(flags)); } } diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index de8f008c9d3..87ad59b0402 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -180,19 +180,11 @@ function readConnectSandbox(sandboxName: string): SandboxEntry | null { return registry.getSandboxAcrossGatewayRoots(sandboxName) ?? registry.getSandbox(sandboxName); } -/** Prefer the owning registry row over the selected onboarding session. */ function getConnectSessionAgent(sandboxName: string): AgentDefinition | null { - const sandbox = readConnectSandbox(sandboxName); - const selectedAgent = agentRuntime.getSessionAgent(sandboxName); - if (!sandbox) return selectedAgent; - const persistedAgent = sandbox.agent ?? "openclaw"; - if ( - selectedAgent?.name === persistedAgent || - (selectedAgent === null && persistedAgent === "openclaw") - ) { - return selectedAgent; - } - return agentRuntime.getRegisteredAgent(sandbox); + return agentRuntime.resolveRegisteredSandboxAgent( + sandboxName, + agentRuntime.getSessionAgent(sandboxName), + ); } export type SandboxStartupRecoveryResult = Awaited< diff --git a/src/lib/actions/sandbox/forward-recovery.ts b/src/lib/actions/sandbox/forward-recovery.ts index 9bb9cd3a945..d8d94539b07 100644 --- a/src/lib/actions/sandbox/forward-recovery.ts +++ b/src/lib/actions/sandbox/forward-recovery.ts @@ -69,21 +69,13 @@ function readForwardSandbox(sandboxName: string): registry.SandboxEntry | null { return registry.getSandboxAcrossGatewayRoots(sandboxName) ?? registry.getSandbox(sandboxName); } -/** Resolve the persisted agent without falling back to a different registry root. */ function getForwardSessionAgent( sandboxName: string, ): ReturnType { - const sandbox = readForwardSandbox(sandboxName); - const selectedAgent = agentRuntime.getSessionAgent(sandboxName); - if (!sandbox) return selectedAgent; - const persistedAgent = sandbox.agent ?? "openclaw"; - if ( - selectedAgent?.name === persistedAgent || - (selectedAgent === null && persistedAgent === "openclaw") - ) { - return selectedAgent; - } - return agentRuntime.getRegisteredAgent(sandbox); + return agentRuntime.resolveRegisteredSandboxAgent( + sandboxName, + agentRuntime.getSessionAgent(sandboxName), + ); } export interface HermesPortableForwardCommandAuthority { diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index c9f984e0329..c6e902720e3 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -26,9 +26,9 @@ import { nvcfFunctionNotFoundMessage, } from "../../inference/nvcf-model-access"; import { ROOT, shellQuote } from "../../runner"; -import { buildSubprocessEnv } from "../../subprocess-env"; import { DCODE_MANAGED_EXEC_LAUNCHER } from "./connect-inference-route-probe"; import { + buildSandboxSubprocessEnv, executeSandboxExecCommand, type SandboxCommandResult, type SandboxExecCommandOptions, @@ -164,8 +164,8 @@ export function buildDcodeSandboxInferenceInvocationRequest( HOME: "/usr/local/lib/nemoclaw", }, environment: input.runtimeSelection - ? buildOpenShellRuntimeSelectionEnv(buildSubprocessEnv(), input.runtimeSelection) - : buildSubprocessEnv(), + ? buildOpenShellRuntimeSelectionEnv(buildSandboxSubprocessEnv(), input.runtimeSelection) + : buildSandboxSubprocessEnv(), tty: false, timeoutMilliseconds, }; diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 2f8222912d8..fdef1c98d65 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -106,22 +106,14 @@ function readRecoverySandbox(sandboxName: string): registry.SandboxEntry | null return registry.getSandboxAcrossGatewayRoots(sandboxName) ?? registry.getSandbox(sandboxName); } -/** Resolve the persisted agent without selecting a different gateway root. */ function getRecoverySessionAgent( sandboxName?: string, ): ReturnType { if (!sandboxName) return agentRuntime.getSessionAgent(); - const sandbox = readRecoverySandbox(sandboxName); - const selectedAgent = agentRuntime.getSessionAgent(sandboxName); - if (!sandbox) return selectedAgent; - const persistedAgent = sandbox.agent ?? "openclaw"; - if ( - selectedAgent?.name === persistedAgent || - (selectedAgent === null && persistedAgent === "openclaw") - ) { - return selectedAgent; - } - return agentRuntime.getRegisteredAgent(sandbox); + return agentRuntime.resolveRegisteredSandboxAgent( + sandboxName, + agentRuntime.getSessionAgent(sandboxName), + ); } export type { @@ -136,6 +128,7 @@ export type RestartSandboxGatewayOptions = BaseRestartSandboxGatewayOptions & { }; export { buildSandboxExecMarkedCommand } from "./sandbox-exec-output"; +export { buildSubprocessEnv as buildSandboxSubprocessEnv }; export type { SandboxCommandResult, SandboxExecCommandOptions }; diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.ts index f0cad496863..9f8024e2106 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.ts @@ -62,6 +62,7 @@ import { export { removeStaleRebuildDockerOrphan }; export { replaceOpenShellRuntimeSelectionEnv, snapshotOpenShellEnv }; export { resolveSandboxGatewayName }; +export { delegateRebuildToOwningRegistry } from "./rebuild/owning-registry"; export type RebuildSandboxEntry = SandboxEntry & { agents?: unknown[] }; diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 3ef2f9249b4..46961b19cf6 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -17,6 +17,11 @@ import { checkRebuildGatewaySchemaPreflight, runRebuildGatewayIntentPreflight, } from "./rebuild-preflight-guards"; +import { + delegateRebuildToOwningRegistry, + rebuildOwningRegistryDependencies, +} from "./rebuild/owning-registry"; +import { rebuildSandbox } from "./rebuild"; const driftIssue: gatewayDrift.OpenShellStateRpcIssue = { kind: "image_drift", @@ -361,3 +366,101 @@ describe("rebuild gateway drift preflight", () => { expect(errorSpy.mock.calls.flat().join("\n")).toContain("Failed to query running sandboxes"); }); }); + +describe("rebuild owning registry routing", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("delegates the complete rebuild transaction to a sibling registry root", async () => { + const entry = makeSandboxEntry("nemoclaw-9000", 9000); + vi.spyOn(rebuildOwningRegistryDependencies, "findSandbox").mockReturnValue({ + entry, + gatewayPort: 9000, + registryGatewayPort: 9000, + registryFile: "/home/test/.nemoclaw/gateways/9000/sandboxes.json", + }); + const runWorker = vi + .spyOn(rebuildOwningRegistryDependencies, "runWorker") + .mockResolvedValue(undefined); + const recoveryManifest = { sandboxName: "alpha", backupPath: "/backup/alpha" } as never; + const input = { + sandboxName: "alpha", + options: { yes: true, verbose: true }, + executionOptions: { throwOnError: true, recoveryManifest }, + }; + + const readBaseRegistry = vi.spyOn(registry, "load"); + + await expect( + rebuildSandbox(input.sandboxName, input.options, input.executionOptions), + ).resolves.toBeUndefined(); + + expect(runWorker).toHaveBeenCalledWith(input, 9000); + expect(readBaseRegistry).not.toHaveBeenCalled(); + }); + + it("keeps the rebuild in-process when the selected root owns the sandbox", async () => { + const entry = makeSandboxEntry("nemoclaw", 8080); + vi.spyOn(rebuildOwningRegistryDependencies, "findSandbox").mockReturnValue({ + entry, + gatewayPort: 8080, + registryGatewayPort: 8080, + registryFile: "/home/test/.nemoclaw/sandboxes.json", + }); + const runWorker = vi.spyOn(rebuildOwningRegistryDependencies, "runWorker"); + + await expect( + delegateRebuildToOwningRegistry( + { sandboxName: "alpha", options: { yes: true }, executionOptions: {} }, + "/home/test", + "/home/test/.nemoclaw/sandboxes.json", + ), + ).resolves.toBe(false); + + expect(runWorker).not.toHaveBeenCalled(); + }); + + it("keeps a legacy base-root row local even when it records a non-default runtime port", async () => { + const entry = makeSandboxEntry("nemoclaw-9000", 9000); + vi.spyOn(rebuildOwningRegistryDependencies, "findSandbox").mockReturnValue({ + entry, + gatewayPort: 9000, + registryGatewayPort: 8080, + registryFile: "/home/test/.nemoclaw/sandboxes.json", + }); + const runWorker = vi.spyOn(rebuildOwningRegistryDependencies, "runWorker"); + + await expect( + delegateRebuildToOwningRegistry( + { sandboxName: "alpha", options: { yes: true }, executionOptions: {} }, + "/home/test", + "/home/test/.nemoclaw/sandboxes.json", + ), + ).resolves.toBe(false); + + expect(runWorker).not.toHaveBeenCalled(); + }); + + it("fails fast instead of deadlocking when a parent lifecycle command owns the host fence", async () => { + const entry = makeSandboxEntry("nemoclaw-9000", 9000); + vi.spyOn(rebuildOwningRegistryDependencies, "findSandbox").mockReturnValue({ + entry, + gatewayPort: 9000, + registryGatewayPort: 9000, + registryFile: "/home/test/.nemoclaw/gateways/9000/sandboxes.json", + }); + vi.spyOn(rebuildOwningRegistryDependencies, "isHostFenceHeld").mockReturnValue(true); + const runWorker = vi.spyOn(rebuildOwningRegistryDependencies, "runWorker"); + + await expect( + delegateRebuildToOwningRegistry( + { sandboxName: "alpha", options: { yes: true }, executionOptions: {} }, + "/home/test", + "/home/test/.nemoclaw/sandboxes.json", + ), + ).rejects.toThrow("Run 'nemoclaw alpha rebuild' directly"); + + expect(runWorker).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/rebuild-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index 61dfa9cba28..97891f23a64 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -44,6 +44,7 @@ import { serializeHermesOperatorConfigSnapshot, } from "./rebuild-durable-config"; import { + delegateRebuildToOwningRegistry, disposeRebuildAgentBaseImagePreflight, removeStaleRebuildDockerOrphan, snapshotOpenShellEnv, @@ -121,6 +122,16 @@ export async function rebuildSandbox( opts: RebuildSandboxExecutionOptions = {}, ): Promise { const homeDir = process.env.HOME || os.homedir(); + const normalizedOptions = normalizeRebuildSandboxOptions(options); + if ( + await delegateRebuildToOwningRegistry( + { sandboxName, options: normalizedOptions, executionOptions: opts }, + homeDir, + registry.REGISTRY_FILE, + ) + ) { + return; + } assertSandboxRebuildCommandAvailable(sandboxName); return withPortableOnboardRetirementBoundary( { @@ -151,7 +162,7 @@ export async function rebuildSandbox( try { await rebuildSandboxUnlocked( sandboxName, - options, + normalizedOptions, opts, removedImmutabilityMigration.stateRecord !== null, ); diff --git a/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts new file mode 100644 index 00000000000..60caf75d132 --- /dev/null +++ b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; + +import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; +import { rebuildSandbox } from "../rebuild-pipeline"; +import type { RebuildSandboxExecutionOptions } from "../rebuild-prepared-recovery"; + +const MAX_REBUILD_INPUT_BYTES = 4 * 1024 * 1024; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function readInput(): { + sandboxName: string; + options: RebuildSandboxOptions; + executionOptions: RebuildSandboxExecutionOptions; +} { + const descriptor = 3; + const chunks: Buffer[] = []; + let bytes = 0; + const buffer = Buffer.allocUnsafe(64 * 1024); + for (;;) { + const count = fs.readSync(descriptor, buffer, 0, buffer.length, null); + if (count === 0) break; + bytes += count; + if (bytes > MAX_REBUILD_INPUT_BYTES) throw new Error("Rebuild worker input is too large."); + chunks.push(Buffer.from(buffer.subarray(0, count))); + } + const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if ( + !isRecord(parsed) || + typeof parsed.sandboxName !== "string" || + !isRecord(parsed.options) || + !isRecord(parsed.executionOptions) + ) { + throw new Error("Rebuild worker input is invalid."); + } + return { + sandboxName: parsed.sandboxName, + options: parsed.options as RebuildSandboxOptions, + executionOptions: parsed.executionOptions as RebuildSandboxExecutionOptions, + }; +} + +async function main(): Promise { + const input = readInput(); + await rebuildSandbox(input.sandboxName, input.options, { + ...input.executionOptions, + throwOnError: true, + }); +} + +void main().catch(() => { + console.error("Rebuild worker failed."); + process.exitCode = 1; +}); diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts new file mode 100644 index 00000000000..9fdc5283e91 --- /dev/null +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawn } from "node:child_process"; +import path from "node:path"; + +import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; +import { snapshotKnownCredentialEnv } from "../../../onboard/credential-env"; +import { isCurrentPortableHostFenceHeld } from "../../../state/portable-uninstall-retirement"; +import { buildSubprocessEnv } from "../../../subprocess-env"; +import { findSandboxAcrossGatewayRoots } from "../../../state/registry/cross-port"; +import type { RebuildSandboxExecutionOptions } from "../rebuild-prepared-recovery"; + +export interface RebuildOwningRegistryInput { + readonly sandboxName: string; + readonly options: RebuildSandboxOptions; + readonly executionOptions: RebuildSandboxExecutionOptions; +} + +type RebuildOwningRegistryDependencies = { + findSandbox: typeof findSandboxAcrossGatewayRoots; + isHostFenceHeld: typeof isCurrentPortableHostFenceHeld; + runWorker(input: RebuildOwningRegistryInput, gatewayPort: number): Promise; +}; + +const WORKER_PATH = path.join(__dirname, "owning-registry-worker.js"); +const REBUILD_ENV_NAMES = [ + "NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", + "NEMOCLAW_NON_INTERACTIVE", + "NEMOCLAW_OPENSHELL_BIN", + "NEMOCLAW_OPENSHELL_GATEWAY_BIN", + "NEMOCLAW_OPENSHELL_SANDBOX_BIN", + "NEMOCLAW_REBUILD_VERBOSE", + "NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH", +] as const; + +function rebuildWorkerEnv(gatewayPort: number): Record { + const extra: Record = { + ...snapshotKnownCredentialEnv(), + NEMOCLAW_GATEWAY_PORT: String(gatewayPort), + }; + for (const name of REBUILD_ENV_NAMES) { + const value = process.env[name]; + if (value !== undefined) extra[name] = value; + } + return buildSubprocessEnv(extra); +} + +async function runWorker(input: RebuildOwningRegistryInput, gatewayPort: number): Promise { + const child = spawn(process.execPath, [WORKER_PATH], { + env: rebuildWorkerEnv(gatewayPort), + stdio: ["inherit", "inherit", "inherit", "pipe"], + }); + const inputStream = child.stdio[3]; + if (!inputStream || !("end" in inputStream)) { + child.kill(); + throw new Error("Cannot route rebuild input to the owning gateway registry."); + } + const inputWritten = new Promise((resolve, reject) => { + inputStream.once("error", reject); + inputStream.end(JSON.stringify(input), resolve); + }); + await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("exit", (code, signal) => { + if (code === 0 && signal === null) { + resolve(); + return; + } + reject(new Error("Rebuild in the owning gateway registry did not complete successfully.")); + }); + }); + await inputWritten; +} + +export const rebuildOwningRegistryDependencies: RebuildOwningRegistryDependencies = { + findSandbox: findSandboxAcrossGatewayRoots, + isHostFenceHeld: isCurrentPortableHostFenceHeld, + runWorker, +}; + +/** + * Re-enter rebuild in a fresh process whose static state paths are bound to + * the sandbox's owning gateway root. Returns true when the worker owns the + * operation and the caller must stop its local pipeline. + */ +export async function delegateRebuildToOwningRegistry( + input: RebuildOwningRegistryInput, + homeDir: string, + currentRegistryFile: string, +): Promise { + const hit = rebuildOwningRegistryDependencies.findSandbox(input.sandboxName, homeDir); + if (!hit || path.resolve(hit.registryFile) === path.resolve(currentRegistryFile)) return false; + if (hit.registryGatewayPort === undefined) { + throw new Error("Cannot resolve the gateway registry root that owns the sandbox."); + } + if (rebuildOwningRegistryDependencies.isHostFenceHeld(homeDir)) { + throw new Error( + `Cannot transfer rebuild for '${input.sandboxName}' while another lifecycle command owns the host fence. Run 'nemoclaw ${input.sandboxName} rebuild' directly.`, + ); + } + await rebuildOwningRegistryDependencies.runWorker(input, hit.registryGatewayPort); + return true; +} diff --git a/src/lib/agent/runtime.test.ts b/src/lib/agent/runtime.test.ts index bea2188bc78..2b29868edad 100644 --- a/src/lib/agent/runtime.test.ts +++ b/src/lib/agent/runtime.test.ts @@ -5,7 +5,12 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import * as registry from "../state/registry"; import { type AgentDefinition, loadAgent } from "./defs"; // Import source directly so tests cannot pass against a stale build. -import { buildRecoveryScript, getRegisteredAgent, resolveSessionAgentDefinition } from "./runtime"; +import { + buildRecoveryScript, + getRegisteredAgent, + resolveRegisteredSandboxAgent, + resolveSessionAgentDefinition, +} from "./runtime"; function makeAgent(overrides: Partial = {}): AgentDefinition { return { @@ -93,6 +98,30 @@ describe("getRegisteredAgent", () => { ); }); +describe("resolveRegisteredSandboxAgent", () => { + it("uses the agent persisted by a sibling gateway registry", () => { + vi.spyOn(registry, "getSandboxAcrossGatewayRoots").mockReturnValue({ + name: "alpha", + agent: "hermes", + } as never); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + agent: "openclaw", + } as never); + + expect(resolveRegisteredSandboxAgent("alpha", null)?.name).toBe("hermes"); + }); + + it("keeps a matching selected agent without changing registry roots", () => { + vi.spyOn(registry, "getSandboxAcrossGatewayRoots").mockReturnValue({ + name: "alpha", + agent: "hermes", + } as never); + + expect(resolveRegisteredSandboxAgent("alpha", hermesAgent)).toBe(hermesAgent); + }); +}); + describe("resolveSessionAgentDefinition", () => { it("preserves an explicitly selected agent definition", () => { expect(resolveSessionAgentDefinition("alpha", hermesAgent)).toEqual({ diff --git a/src/lib/agent/runtime.ts b/src/lib/agent/runtime.ts index db804efd6d1..0d96af426e8 100644 --- a/src/lib/agent/runtime.ts +++ b/src/lib/agent/runtime.ts @@ -86,6 +86,28 @@ export function getRegisteredAgent(source: RegisteredAgentSource): AgentDefiniti } } +/** + * Resolve the agent persisted by the registry root that owns a sandbox. + * The selected onboarding session remains the fast path, but it cannot + * override a different agent recorded in a sibling gateway registry. + */ +export function resolveRegisteredSandboxAgent( + sandboxName: string, + selectedAgent: AgentDefinition | null, +): AgentDefinition | null { + const sandbox = + registry.getSandboxAcrossGatewayRoots(sandboxName) ?? registry.getSandbox(sandboxName); + if (!sandbox) return selectedAgent; + const persistedAgent = sandbox.agent ?? "openclaw"; + if ( + selectedAgent?.name === persistedAgent || + (selectedAgent === null && persistedAgent === "openclaw") + ) { + return selectedAgent; + } + return getRegisteredAgent(sandbox); +} + /** * Resolve the trusted manifest command used for an interactive agent handoff. * OpenClaw remains `null` in getSessionAgent because its recovery behavior uses diff --git a/src/lib/cli/nemoclaw-oclif-command.ts b/src/lib/cli/nemoclaw-oclif-command.ts index cc3345951f1..7b1e08796ce 100644 --- a/src/lib/cli/nemoclaw-oclif-command.ts +++ b/src/lib/cli/nemoclaw-oclif-command.ts @@ -105,6 +105,7 @@ export abstract class NemoClawCommand extends Command { } protected override async _run(): Promise { + if (await this.runBeforeLifecycleBoundary()) return undefined as T; const commandId = this.id; const portablePolicy = typeof commandId === "string" ? classifyHermesPortableCommand(commandId, this.argv) : null; @@ -144,6 +145,24 @@ export abstract class NemoClawCommand extends Command { return await withSandboxLifecycleLock(sandboxName, runLocked); } + /** Allow a command to transfer complete ownership before host-wide fences are acquired. */ + protected async runBeforeLifecycleBoundary(): Promise { + return false; + } + + /** Reuse an early command parse when the ordinary lifecycle wrapper continues. */ + protected retainLifecycleParserOutput< + F extends Interfaces.OutputFlags, + B extends Interfaces.OutputFlags, + A extends Interfaces.OutputArgs, + >(parsed: Interfaces.ParserOutput): void { + this.lifecycleParserOutput = parsed as Interfaces.ParserOutput< + Interfaces.OutputFlags, + Interfaces.OutputFlags, + Interfaces.OutputArgs + >; + } + private isInteractiveSession(commandId: string | undefined): boolean { return ( commandId === "launch" || diff --git a/src/lib/onboard/credential-env.test.ts b/src/lib/onboard/credential-env.test.ts index bd38621e6e3..803b5fe0fd0 100644 --- a/src/lib/onboard/credential-env.test.ts +++ b/src/lib/onboard/credential-env.test.ts @@ -1,18 +1,24 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; -import { hydrateCredentialEnv } from "./credential-env"; - -const ORIGINAL_TELEGRAM_TOKEN = process.env.TELEGRAM_BOT_TOKEN; +import { hydrateCredentialEnv, snapshotKnownCredentialEnv } from "./credential-env"; afterEach(() => { - if (ORIGINAL_TELEGRAM_TOKEN === undefined) { - delete process.env.TELEGRAM_BOT_TOKEN; - } else { - process.env.TELEGRAM_BOT_TOKEN = ORIGINAL_TELEGRAM_TOKEN; - } + vi.unstubAllEnvs(); +}); + +describe("snapshotKnownCredentialEnv", () => { + it("copies allowlisted credentials without exposing unrelated environment secrets", () => { + vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "nvapi-worker-test"); + vi.stubEnv("UNRELATED_SECRET", "must-not-cross-worker-boundary"); + + const snapshot = snapshotKnownCredentialEnv(); + + expect(snapshot.NVIDIA_INFERENCE_API_KEY).toBe("nvapi-worker-test"); + expect(snapshot).not.toHaveProperty("UNRELATED_SECRET"); + }); }); describe("hydrateCredentialEnv", () => { @@ -23,7 +29,7 @@ describe("hydrateCredentialEnv", () => { }); it("delegates credential resolution and preserves process.env hydration side effects", () => { - delete process.env.TELEGRAM_BOT_TOKEN; + vi.stubEnv("TELEGRAM_BOT_TOKEN", undefined); const hydrated = hydrateCredentialEnv("TELEGRAM_BOT_TOKEN", (envName) => { if (envName !== "TELEGRAM_BOT_TOKEN") return null; diff --git a/src/lib/onboard/credential-env.ts b/src/lib/onboard/credential-env.ts index 4d53467edde..4305f62f1e6 100644 --- a/src/lib/onboard/credential-env.ts +++ b/src/lib/onboard/credential-env.ts @@ -1,7 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { resolveProviderCredential } from "../credentials/store"; +import { loadCredentials, resolveProviderCredential } from "../credentials/store"; + +/** Snapshot only NemoClaw's allowlisted credentials for a trusted child process. */ +export function snapshotKnownCredentialEnv(): Record { + return loadCredentials(); +} /** * Resolve and return a credential for host-side callers. Scoped overrides are diff --git a/src/lib/state/portable-uninstall-retirement.ts b/src/lib/state/portable-uninstall-retirement.ts index 9c7794ab12c..558e911d8d7 100644 --- a/src/lib/state/portable-uninstall-retirement.ts +++ b/src/lib/state/portable-uninstall-retirement.ts @@ -108,12 +108,17 @@ export const portableHostFencePath = (homeDir: string): string => /** Require the current asynchronous operation to own the exact Portable host fence. */ export function assertCurrentPortableHostFenceHeld(homeDir: string): void { - const owner = owners.getStore(); - if (!owner?.active || owner.path !== portableHostFencePath(homeDir)) { + if (!isCurrentPortableHostFenceHeld(homeDir)) { throw new Error("Portable host authority mutation requires the current HOME fence"); } } +/** Report whether the current asynchronous operation owns the exact host fence. */ +export function isCurrentPortableHostFenceHeld(homeDir: string): boolean { + const owner = owners.getStore(); + return owner?.active === true && owner.path === portableHostFencePath(homeDir); +} + /** Resolve the portable state root while admitting only the isolated Vitest override. */ export function defaultPortableStateDir(env: NodeJS.ProcessEnv): string { if ( diff --git a/src/lib/state/registry/cross-port.ts b/src/lib/state/registry/cross-port.ts index cdc6d4ca058..a86ccbec78c 100644 --- a/src/lib/state/registry/cross-port.ts +++ b/src/lib/state/registry/cross-port.ts @@ -20,6 +20,8 @@ export interface CrossPortSandboxHit { entry: SandboxEntry; /** Recorded or directory-derived owning gateway port; null when unrecorded on the base root. */ gatewayPort: number | null; + /** Gateway port whose state root contains this registry file. */ + registryGatewayPort?: number; registryFile: string; } @@ -65,6 +67,7 @@ function listSandboxHitsAcrossGatewayRoots(home: string): CrossPortSandboxHit[] state.gatewayPort === DEFAULT_GATEWAY_PORT && !hasRecordedGatewayIdentity ? null : gatewayPort, + registryGatewayPort: state.gatewayPort, registryFile, }); } From 3c0636849504d568d6223eded0c8ac2a080451d7 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 09:58:51 -0700 Subject: [PATCH 24/44] fix(rebuild): route recovery retirement by state root Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/commands/sandbox/rebuild.test.ts | 23 +++ src/commands/sandbox/rebuild.ts | 18 ++- .../sandbox/rebuild-gateway-drift.test.ts | 70 +++++++- .../sandbox/rebuild-recreate-journal.ts | 31 ++++ .../sandbox/rebuild/owning-registry-worker.ts | 70 ++++++-- .../sandbox/rebuild/owning-registry.ts | 152 +++++++++++++++++- test/cli/dispatch-basics.test.ts | 92 ----------- test/cli/rebuild-recovery-routing.test.ts | 108 +++++++++++++ .../rebuild-owning-registry-worker.test.ts | 48 ++++++ 9 files changed, 494 insertions(+), 118 deletions(-) create mode 100644 test/cli/rebuild-recovery-routing.test.ts create mode 100644 test/package-contract/rebuild-owning-registry-worker.test.ts diff --git a/src/commands/sandbox/rebuild.test.ts b/src/commands/sandbox/rebuild.test.ts index f214b400e0b..2c5e2e0d3ca 100644 --- a/src/commands/sandbox/rebuild.test.ts +++ b/src/commands/sandbox/rebuild.test.ts @@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ delegateRebuildToOwningRegistry: vi.fn(async () => false), + delegateRecoveryRetirementToOwningRegistry: vi.fn(async () => false), rebuildSandbox: vi.fn(async () => undefined), retireRebuildRecoveryBackup: vi.fn(() => ({ backupPath: "/backups/alpha/2026-09-01", @@ -16,6 +17,7 @@ const mocks = vi.hoisted(() => ({ vi.mock("../../lib/actions/sandbox/rebuild", () => mocks); vi.mock("../../lib/actions/sandbox/rebuild/owning-registry", () => ({ delegateRebuildToOwningRegistry: mocks.delegateRebuildToOwningRegistry, + delegateRecoveryRetirementToOwningRegistry: mocks.delegateRecoveryRetirementToOwningRegistry, })); import RebuildCliCommand from "./rebuild"; @@ -40,12 +42,33 @@ describe("sandbox:rebuild command", () => { transactionId: "11111111-1111-4111-8111-111111111111", confirmDataRecovered: true, }); + expect(mocks.delegateRecoveryRetirementToOwningRegistry).toHaveBeenCalledWith( + { + sandboxName: "alpha", + transactionId: "11111111-1111-4111-8111-111111111111", + confirmDataRecovered: true, + }, + expect.any(String), + expect.any(String), + ); expect(mocks.rebuildSandbox).not.toHaveBeenCalled(); expect(logSpy).toHaveBeenCalledWith( "Retired rebuild recovery '11111111-1111-4111-8111-111111111111' for sandbox 'alpha' from /backups/alpha/2026-09-01.", ); }); + it("delegates sibling-root recovery retirement before the command lifecycle fence", async () => { + mocks.delegateRecoveryRetirementToOwningRegistry.mockResolvedValueOnce(true); + + await RebuildCliCommand.run( + ["alpha", "--retire-recovery", "11111111-1111-4111-8111-111111111111", "--yes"], + rootDir, + ); + + expect(mocks.retireRebuildRecoveryBackup).not.toHaveBeenCalled(); + expect(mocks.rebuildSandbox).not.toHaveBeenCalled(); + }); + it("does not infer data-recovery confirmation when --yes is absent", async () => { await RebuildCliCommand.run( ["alpha", "--retire-recovery", "11111111-1111-4111-8111-111111111111"], diff --git a/src/commands/sandbox/rebuild.ts b/src/commands/sandbox/rebuild.ts index 3abed1205cc..4342b6e53bb 100644 --- a/src/commands/sandbox/rebuild.ts +++ b/src/commands/sandbox/rebuild.ts @@ -5,7 +5,10 @@ import { Args, Flags } from "@oclif/core"; import os from "node:os"; import { rebuildSandbox, retireRebuildRecoveryBackup } from "../../lib/actions/sandbox/rebuild"; -import { delegateRebuildToOwningRegistry } from "../../lib/actions/sandbox/rebuild/owning-registry"; +import { + delegateRebuildToOwningRegistry, + delegateRecoveryRetirementToOwningRegistry, +} from "../../lib/actions/sandbox/rebuild/owning-registry"; import { forceFlag, yesFlag } from "../../lib/cli/common-flags"; import { NemoClawCommand } from "../../lib/cli/nemoclaw-oclif-command"; import type { RebuildSandboxOptions } from "../../lib/domain/lifecycle/options"; @@ -81,7 +84,18 @@ export default class RebuildCliCommand extends NemoClawCommand { const parsed = await this.parse(RebuildCliCommand); this.retainLifecycleParserOutput(parsed); const { args, flags } = parsed; - if (flags["retire-recovery"]) return false; + const recoveryTransactionId = flags["retire-recovery"]; + if (recoveryTransactionId) { + return await delegateRecoveryRetirementToOwningRegistry( + { + sandboxName: args.sandboxName, + transactionId: recoveryTransactionId, + confirmDataRecovered: flags.yes === true, + }, + process.env.HOME || os.homedir(), + REGISTRY_FILE, + ); + } return await delegateRebuildToOwningRegistry( { sandboxName: args.sandboxName, diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 46961b19cf6..edf2a191186 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -1,6 +1,10 @@ // 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, type MockInstance, vi } from "vitest"; import * as gatewayDrift from "../../adapters/openshell/gateway-drift"; @@ -19,6 +23,7 @@ import { } from "./rebuild-preflight-guards"; import { delegateRebuildToOwningRegistry, + findRebuildRecoveryStorageRoot, rebuildOwningRegistryDependencies, } from "./rebuild/owning-registry"; import { rebuildSandbox } from "./rebuild"; @@ -396,7 +401,7 @@ describe("rebuild owning registry routing", () => { rebuildSandbox(input.sandboxName, input.options, input.executionOptions), ).resolves.toBeUndefined(); - expect(runWorker).toHaveBeenCalledWith(input, 9000); + expect(runWorker).toHaveBeenCalledWith({ operation: "rebuild", ...input }, 9000); expect(readBaseRegistry).not.toHaveBeenCalled(); }); @@ -463,4 +468,67 @@ describe("rebuild owning registry routing", () => { expect(runWorker).not.toHaveBeenCalled(); }); + + it("rejects duplicate exact recovery records across gateway roots", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recovery-roots-")); + const transactionId = "11111111-1111-4111-8111-111111111111"; + const timestamp = "2026-09-17T00-00-00-000Z"; + try { + const firstBackup = path.join( + home, + ".nemoclaw", + "gateways", + "9000", + "rebuild-backups", + "alpha", + timestamp, + ); + const secondBackup = path.join( + home, + ".nemoclaw", + "gateways", + "9001", + "rebuild-backups", + "alpha", + timestamp, + ); + fs.mkdirSync(firstBackup, { recursive: true }); + fs.mkdirSync(secondBackup, { recursive: true }); + fs.writeFileSync( + path.join(firstBackup, ".nemoclaw-rebuild-recovery.json"), + `${JSON.stringify({ + schemaVersion: 3, + transactionId, + sandboxName: "alpha", + backupTimestamp: timestamp, + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, + phase: "restore", + })}\n`, + { mode: 0o600 }, + ); + fs.writeFileSync( + path.join(secondBackup, ".nemoclaw-rebuild-recovery.json"), + `${JSON.stringify({ + schemaVersion: 3, + transactionId, + sandboxName: "alpha", + backupTimestamp: timestamp, + gatewayName: "nemoclaw-9001", + gatewayPort: 9001, + phase: "restore", + })}\n`, + { mode: 0o600 }, + ); + + expect(() => + findRebuildRecoveryStorageRoot( + { sandboxName: "alpha", transactionId, confirmDataRecovered: true }, + home, + ), + ).toThrow("More than one exact rebuild recovery record"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); }); diff --git a/src/lib/actions/sandbox/rebuild-recreate-journal.ts b/src/lib/actions/sandbox/rebuild-recreate-journal.ts index 59b4dc371d1..6b9e1b8e53b 100644 --- a/src/lib/actions/sandbox/rebuild-recreate-journal.ts +++ b/src/lib/actions/sandbox/rebuild-recreate-journal.ts @@ -417,6 +417,37 @@ export type RetiredRebuildRecovery = Readonly<{ transactionId: string; }>; +export type RebuildRecoveryRoute = Readonly<{ + gatewayName: string; + gatewayPort: number; +}>; + +/** Read the routing authority for one exact retained recovery marker. */ +export function readRebuildRecoveryRoute( + input: Readonly<{ sandboxName: string; transactionId: string }>, + backupPath: string, +): RebuildRecoveryRoute | null { + validateRecoveryIdentity({ ...input, agentName: null }); + const record = readRecoveryRecord(backupPath); + if (record?.transactionId !== input.transactionId) return null; + if (record.sandboxName !== input.sandboxName) { + throw new Error( + `Rebuild recovery identity does not match sandbox '${input.sandboxName}'. Recovery remains at '${backupPath}'.`, + ); + } + if (record.backupTimestamp !== path.basename(backupPath)) { + throw new Error( + `Rebuild recovery identity changed before routing. Recovery remains at '${backupPath}'.`, + ); + } + if (record.schemaVersion === 1) { + throw new Error( + `Rebuild recovery '${input.transactionId}' does not contain recorded gateway authority. Recovery remains at '${backupPath}'.`, + ); + } + return { gatewayName: record.gatewayName, gatewayPort: record.gatewayPort }; +} + /** * Retire one credential-bearing rebuild handoff only after its recorded * gateway proves the old sandbox absent and the operator attests that required diff --git a/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts index 60caf75d132..6c1e5167ae5 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts @@ -6,6 +6,8 @@ import fs from "node:fs"; import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; import { rebuildSandbox } from "../rebuild-pipeline"; import type { RebuildSandboxExecutionOptions } from "../rebuild-prepared-recovery"; +import { retireRebuildRecoveryBackup } from "../rebuild-recreate-journal"; +import type { OwningRegistryWorkerInput } from "./owning-registry"; const MAX_REBUILD_INPUT_BYTES = 4 * 1024 * 1024; @@ -13,11 +15,7 @@ function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } -function readInput(): { - sandboxName: string; - options: RebuildSandboxOptions; - executionOptions: RebuildSandboxExecutionOptions; -} { +function readInput(): OwningRegistryWorkerInput { const descriptor = 3; const chunks: Buffer[] = []; let bytes = 0; @@ -30,27 +28,65 @@ function readInput(): { chunks.push(Buffer.from(buffer.subarray(0, count))); } const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if (!isRecord(parsed) || typeof parsed.sandboxName !== "string") { + throw new Error("Rebuild worker input is invalid."); + } if ( - !isRecord(parsed) || - typeof parsed.sandboxName !== "string" || - !isRecord(parsed.options) || - !isRecord(parsed.executionOptions) + parsed.operation === "rebuild" && + isRecord(parsed.options) && + isRecord(parsed.executionOptions) ) { - throw new Error("Rebuild worker input is invalid."); + return { + operation: "rebuild", + sandboxName: parsed.sandboxName, + options: parsed.options as RebuildSandboxOptions, + executionOptions: parsed.executionOptions as RebuildSandboxExecutionOptions, + }; + } + if ( + parsed.operation === "retire-recovery" && + typeof parsed.transactionId === "string" && + typeof parsed.confirmDataRecovered === "boolean" + ) { + return { + operation: "retire-recovery", + sandboxName: parsed.sandboxName, + transactionId: parsed.transactionId, + confirmDataRecovered: parsed.confirmDataRecovered, + }; } - return { - sandboxName: parsed.sandboxName, - options: parsed.options as RebuildSandboxOptions, - executionOptions: parsed.executionOptions as RebuildSandboxExecutionOptions, - }; + throw new Error("Rebuild worker input is invalid."); } async function main(): Promise { const input = readInput(); - await rebuildSandbox(input.sandboxName, input.options, { + if (input.operation === "retire-recovery") { + const retired = retireRebuildRecoveryBackup(input); + console.log( + `Retired rebuild recovery '${retired.transactionId}' for sandbox '${input.sandboxName}' from ${retired.backupPath}.`, + ); + return; + } + const executionOptions = { ...input.executionOptions, throwOnError: true, - }); + } as const; + try { + fs.fstatSync(4); + fs.writeFileSync( + 4, + JSON.stringify({ + gatewayPort: process.env.NEMOCLAW_GATEWAY_PORT ?? "", + sandboxName: input.sandboxName, + options: input.options, + executionOptions, + }), + ); + return; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EBADF") throw error; + } + await rebuildSandbox(input.sandboxName, input.options, executionOptions); } void main().catch(() => { diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index 9fdc5283e91..fc5da208cc0 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -2,14 +2,18 @@ // SPDX-License-Identifier: Apache-2.0 import { spawn } from "node:child_process"; +import fs from "node:fs"; import path from "node:path"; +import type { Readable } from "node:stream"; import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; import { snapshotKnownCredentialEnv } from "../../../onboard/credential-env"; +import { assertGatewayStatePathSafe, listGatewayStateRoots } from "../../../state/gateway-registry"; import { isCurrentPortableHostFenceHeld } from "../../../state/portable-uninstall-retirement"; import { buildSubprocessEnv } from "../../../subprocess-env"; import { findSandboxAcrossGatewayRoots } from "../../../state/registry/cross-port"; import type { RebuildSandboxExecutionOptions } from "../rebuild-prepared-recovery"; +import { readRebuildRecoveryRoute } from "../rebuild-recreate-journal"; export interface RebuildOwningRegistryInput { readonly sandboxName: string; @@ -17,13 +21,43 @@ export interface RebuildOwningRegistryInput { readonly executionOptions: RebuildSandboxExecutionOptions; } +export interface RetireRecoveryOwningRegistryInput { + readonly sandboxName: string; + readonly transactionId: string; + readonly confirmDataRecovered: boolean; +} + +export type OwningRegistryWorkerInput = + | ({ readonly operation: "rebuild" } & RebuildOwningRegistryInput) + | ({ readonly operation: "retire-recovery" } & RetireRecoveryOwningRegistryInput); + +export interface RebuildRecoveryStorageRoot { + readonly backupPath: string; + readonly gatewayPort: number; + readonly registryFile: string; +} + +export interface RebuildWorkerInvocation { + readonly gatewayPort: string; + readonly sandboxName: string; + readonly options: RebuildSandboxOptions; + readonly executionOptions: RebuildSandboxExecutionOptions & { readonly throwOnError: true }; +} + type RebuildOwningRegistryDependencies = { findSandbox: typeof findSandboxAcrossGatewayRoots; + findRecoveryRoot: typeof findRebuildRecoveryStorageRoot; isHostFenceHeld: typeof isCurrentPortableHostFenceHeld; - runWorker(input: RebuildOwningRegistryInput, gatewayPort: number): Promise; + runWorker( + input: OwningRegistryWorkerInput, + gatewayPort: number, + options?: Readonly<{ observeInvocation?: boolean }>, + ): Promise; }; const WORKER_PATH = path.join(__dirname, "owning-registry-worker.js"); +const MAX_RECOVERY_BACKUP_ENTRIES = 1024; +const MAX_WORKER_OBSERVATION_BYTES = 64 * 1024; const REBUILD_ENV_NAMES = [ "NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "NEMOCLAW_NON_INTERACTIVE", @@ -46,10 +80,41 @@ function rebuildWorkerEnv(gatewayPort: number): Record { return buildSubprocessEnv(extra); } -async function runWorker(input: RebuildOwningRegistryInput, gatewayPort: number): Promise { +async function readWorkerObservation(stream: Readable): Promise { + const chunks: Buffer[] = []; + let bytes = 0; + for await (const chunk of stream) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string); + bytes += buffer.length; + if (bytes > MAX_WORKER_OBSERVATION_BYTES) { + throw new Error("Rebuild worker observation is too large."); + } + chunks.push(buffer); + } + const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if ( + typeof parsed !== "object" || + parsed === null || + Array.isArray(parsed) || + typeof (parsed as Record).gatewayPort !== "string" || + typeof (parsed as Record).sandboxName !== "string" + ) { + throw new Error("Rebuild worker observation is invalid."); + } + return parsed as RebuildWorkerInvocation; +} + +async function runWorker( + input: OwningRegistryWorkerInput, + gatewayPort: number, + options: Readonly<{ observeInvocation?: boolean }> = {}, +): Promise { + const observeInvocation = options.observeInvocation === true; const child = spawn(process.execPath, [WORKER_PATH], { env: rebuildWorkerEnv(gatewayPort), - stdio: ["inherit", "inherit", "inherit", "pipe"], + stdio: observeInvocation + ? ["inherit", "inherit", "inherit", "pipe", "pipe"] + : ["inherit", "inherit", "inherit", "pipe"], }); const inputStream = child.stdio[3]; if (!inputStream || !("end" in inputStream)) { @@ -60,7 +125,13 @@ async function runWorker(input: RebuildOwningRegistryInput, gatewayPort: number) inputStream.once("error", reject); inputStream.end(JSON.stringify(input), resolve); }); - await new Promise((resolve, reject) => { + const observationStream = observeInvocation ? (child.stdio[4] as Readable | null) : null; + if (observeInvocation && !observationStream) { + child.kill(); + throw new Error("Cannot observe the rebuild worker pipeline invocation."); + } + const observation = observationStream ? readWorkerObservation(observationStream) : null; + const exited = new Promise((resolve, reject) => { child.once("error", reject); child.once("exit", (code, signal) => { if (code === 0 && signal === null) { @@ -70,15 +141,61 @@ async function runWorker(input: RebuildOwningRegistryInput, gatewayPort: number) reject(new Error("Rebuild in the owning gateway registry did not complete successfully.")); }); }); - await inputWritten; + const [, , observed] = await Promise.all([ + inputWritten, + exited, + observation ?? Promise.resolve(undefined), + ]); + return observed; } export const rebuildOwningRegistryDependencies: RebuildOwningRegistryDependencies = { findSandbox: findSandboxAcrossGatewayRoots, + findRecoveryRoot: findRebuildRecoveryStorageRoot, isHostFenceHeld: isCurrentPortableHostFenceHeld, runWorker, }; +/** Find one exact recovery marker across bounded, non-symlink gateway roots. */ +export function findRebuildRecoveryStorageRoot( + input: RetireRecoveryOwningRegistryInput, + homeDir: string, +): RebuildRecoveryStorageRoot | null { + const matches: RebuildRecoveryStorageRoot[] = []; + for (const state of listGatewayStateRoots(homeDir)) { + const sandboxBackupRoot = path.join(state.root, "rebuild-backups", input.sandboxName); + assertGatewayStatePathSafe(homeDir, sandboxBackupRoot); + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(sandboxBackupRoot, { withFileTypes: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; + throw error; + } + if (entries.length > MAX_RECOVERY_BACKUP_ENTRIES) { + throw new Error( + `Cannot safely inspect rebuild recovery: more than ${String(MAX_RECOVERY_BACKUP_ENTRIES)} backup entries exist for sandbox '${input.sandboxName}'.`, + ); + } + for (const entry of entries) { + if (!entry.isDirectory() || entry.isSymbolicLink()) continue; + const backupPath = path.join(sandboxBackupRoot, entry.name); + if (!readRebuildRecoveryRoute(input, backupPath)) continue; + matches.push({ + backupPath, + gatewayPort: state.gatewayPort, + registryFile: path.join(state.root, "sandboxes.json"), + }); + } + } + if (matches.length > 1) { + throw new Error( + `More than one exact rebuild recovery record exists for sandbox '${input.sandboxName}' and transaction '${input.transactionId}'.`, + ); + } + return matches[0] ?? null; +} + /** * Re-enter rebuild in a fresh process whose static state paths are bound to * the sandbox's owning gateway root. Returns true when the worker owns the @@ -99,6 +216,29 @@ export async function delegateRebuildToOwningRegistry( `Cannot transfer rebuild for '${input.sandboxName}' while another lifecycle command owns the host fence. Run 'nemoclaw ${input.sandboxName} rebuild' directly.`, ); } - await rebuildOwningRegistryDependencies.runWorker(input, hit.registryGatewayPort); + await rebuildOwningRegistryDependencies.runWorker( + { operation: "rebuild", ...input }, + hit.registryGatewayPort, + ); + return true; +} + +/** Route exact recovery retirement to the state root that retains its marker. */ +export async function delegateRecoveryRetirementToOwningRegistry( + input: RetireRecoveryOwningRegistryInput, + homeDir: string, + currentRegistryFile: string, +): Promise { + const hit = rebuildOwningRegistryDependencies.findRecoveryRoot(input, homeDir); + if (!hit || path.resolve(hit.registryFile) === path.resolve(currentRegistryFile)) return false; + if (rebuildOwningRegistryDependencies.isHostFenceHeld(homeDir)) { + throw new Error( + `Cannot transfer recovery retirement for '${input.sandboxName}' while another lifecycle command owns the host fence. Run the retirement command directly.`, + ); + } + await rebuildOwningRegistryDependencies.runWorker( + { operation: "retire-recovery", ...input }, + hit.gatewayPort, + ); return true; } diff --git a/test/cli/dispatch-basics.test.ts b/test/cli/dispatch-basics.test.ts index 865adc5b57e..002a4a6a208 100644 --- a/test/cli/dispatch-basics.test.ts +++ b/test/cli/dispatch-basics.test.ts @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 import { execSync, spawnSync } from "node:child_process"; -import { createHash } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -523,97 +522,6 @@ describe("CLI dispatch", () => { }, ); - it( - "retires a retained recovery record for an unregistered sandbox through the real CLI (#11394)", - testTimeoutOptions(35_000), - () => { - // Success path with a retained backup and no registry row: the record - // names its gateway, the fake gateway reports the sandbox absent, and - // retirement removes only the credential-bearing handoff and marker. - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-retire-recovery-ok-")); - try { - const localBin = path.join(home, "bin"); - fs.mkdirSync(localBin, { recursive: true }); - const openshellLog = path.join(home, "openshell-calls.log"); - fs.writeFileSync( - path.join(localBin, "openshell"), - [ - "#!/usr/bin/env bash", - `printf "%s\\n" "$*" >> ${JSON.stringify(openshellLog)}`, - 'case "$1 $2" in "sandbox get") echo "no such sandbox gw1-sb" >&2 ;; esac', - "exit 1", - ].join("\n"), - { mode: 0o755 }, - ); - - const transactionId = "11111111-1111-4111-8111-111111111111"; - const timestamp = "2026-09-10T00-00-00-000Z"; - const backupPath = path.join(home, ".nemoclaw", "rebuild-backups", "gw1-sb", timestamp); - fs.mkdirSync(backupPath, { recursive: true, mode: 0o700 }); - const policy = "version: 1\nprocess:\n environment:\n SERVICE_API_KEY: retained\n"; - const sha256 = createHash("sha256").update(policy).digest("hex"); - const handoffPath = path.join(backupPath, `rebuild-policy-handoff.${sha256}.yaml`); - const recordPath = path.join(backupPath, ".nemoclaw-rebuild-recovery.json"); - const manifestPath = path.join(backupPath, "rebuild-manifest.json"); - const retainedPath = path.join(backupPath, "workspace-notes.txt"); - fs.writeFileSync(handoffPath, policy, { mode: 0o600 }); - fs.writeFileSync(retainedPath, "recovered later\n"); - fs.writeFileSync( - manifestPath, - JSON.stringify({ - version: 1, - sandboxName: "gw1-sb", - timestamp, - agentType: "openclaw", - agentVersion: null, - expectedVersion: null, - stateDirs: [], - backupComplete: true, - dir: "/sandbox/.openclaw", - backupPath, - blueprintDigest: null, - rebuildPolicyHandoff: { file: path.basename(handoffPath), sha256 }, - }), - { mode: 0o600 }, - ); - fs.writeFileSync( - recordPath, - `${JSON.stringify({ - schemaVersion: 3, - transactionId, - sandboxName: "gw1-sb", - backupTimestamp: timestamp, - gatewayName: "nemoclaw", - gatewayPort: 18080, - phase: "restore", - })}\n`, - { mode: 0o600 }, - ); - - const r = runWithEnv(`gw1-sb rebuild --retire-recovery ${transactionId} --yes`, { - HOME: home, - PATH: `${localBin}:${process.env.PATH || ""}`, - }); - - expect(r.out).toContain( - `Retired rebuild recovery '${transactionId}' for sandbox 'gw1-sb' from ${backupPath}.`, - ); - expect(r.code).toBe(0); - expect(fs.readFileSync(openshellLog, "utf8").trim().split("\n")).toEqual([ - "sandbox get -g nemoclaw gw1-sb", - ]); - expect(fs.existsSync(handoffPath)).toBe(false); - expect(fs.existsSync(recordPath)).toBe(false); - expect(fs.readFileSync(retainedPath, "utf8")).toBe("recovered later\n"); - expect(JSON.parse(fs.readFileSync(manifestPath, "utf8"))).not.toHaveProperty( - "rebuildPolicyHandoff", - ); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }, - ); - it.each([ { argv: ["term"], diff --git a/test/cli/rebuild-recovery-routing.test.ts b/test/cli/rebuild-recovery-routing.test.ts new file mode 100644 index 00000000000..a469db6064d --- /dev/null +++ b/test/cli/rebuild-recovery-routing.test.ts @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { runWithEnv, testTimeoutOptions } from "./helpers"; + +describe("CLI rebuild recovery routing", () => { + it( + "retires a retained recovery record from a sibling gateway root after its registry row is removed (#11394)", + testTimeoutOptions(35_000), + () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-retire-recovery-ok-")); + try { + const localBin = path.join(home, "bin"); + fs.mkdirSync(localBin, { recursive: true }); + const openshellLog = path.join(home, "openshell-calls.log"); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/usr/bin/env bash", + `printf "%s\\n" "$*" >> ${JSON.stringify(openshellLog)}`, + 'case "$1 $2" in "sandbox get") echo "no such sandbox gw1-sb" >&2 ;; esac', + "exit 1", + ].join("\n"), + { mode: 0o755 }, + ); + + const transactionId = "11111111-1111-4111-8111-111111111111"; + const timestamp = "2026-09-10T00-00-00-000Z"; + const backupPath = path.join( + home, + ".nemoclaw", + "gateways", + "9000", + "rebuild-backups", + "gw1-sb", + timestamp, + ); + fs.mkdirSync(backupPath, { recursive: true, mode: 0o700 }); + const policy = "version: 1\nprocess:\n environment:\n SERVICE_API_KEY: retained\n"; + const sha256 = createHash("sha256").update(policy).digest("hex"); + const handoffPath = path.join(backupPath, `rebuild-policy-handoff.${sha256}.yaml`); + const recordPath = path.join(backupPath, ".nemoclaw-rebuild-recovery.json"); + const manifestPath = path.join(backupPath, "rebuild-manifest.json"); + const retainedPath = path.join(backupPath, "workspace-notes.txt"); + fs.writeFileSync(handoffPath, policy, { mode: 0o600 }); + fs.writeFileSync(retainedPath, "recovered later\n"); + fs.writeFileSync( + manifestPath, + JSON.stringify({ + version: 1, + sandboxName: "gw1-sb", + timestamp, + agentType: "openclaw", + agentVersion: null, + expectedVersion: null, + stateDirs: [], + backupComplete: true, + dir: "/sandbox/.openclaw", + backupPath, + blueprintDigest: null, + rebuildPolicyHandoff: { file: path.basename(handoffPath), sha256 }, + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + recordPath, + `${JSON.stringify({ + schemaVersion: 3, + transactionId, + sandboxName: "gw1-sb", + backupTimestamp: timestamp, + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, + phase: "restore", + })}\n`, + { mode: 0o600 }, + ); + + const result = runWithEnv(`gw1-sb rebuild --retire-recovery ${transactionId} --yes`, { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + }); + + expect(result.out).toContain( + `Retired rebuild recovery '${transactionId}' for sandbox 'gw1-sb' from ${backupPath}.`, + ); + expect(result.code).toBe(0); + expect(fs.readFileSync(openshellLog, "utf8").trim().split("\n")).toEqual([ + "sandbox get -g nemoclaw-9000 gw1-sb", + ]); + expect(fs.existsSync(handoffPath)).toBe(false); + expect(fs.existsSync(recordPath)).toBe(false); + expect(fs.readFileSync(retainedPath, "utf8")).toBe("recovered later\n"); + expect(JSON.parse(fs.readFileSync(manifestPath, "utf8"))).not.toHaveProperty( + "rebuildPolicyHandoff", + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); +}); diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts new file mode 100644 index 00000000000..6eed495572a --- /dev/null +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { rebuildOwningRegistryDependencies } from "../../dist/lib/actions/sandbox/rebuild/owning-registry"; + +describe("compiled rebuild owning-registry worker", () => { + it("transfers the exact rebuild invocation over the private descriptor", async () => { + const recoveryManifest = { + sandboxName: "alpha", + backupPath: "/backup/alpha", + } as never; + + await expect( + rebuildOwningRegistryDependencies.runWorker( + { + operation: "rebuild", + sandboxName: "alpha", + options: { yes: true, verbose: true }, + executionOptions: { recoveryManifest }, + }, + 9000, + { observeInvocation: true }, + ), + ).resolves.toEqual({ + gatewayPort: "9000", + sandboxName: "alpha", + options: { yes: true, verbose: true }, + executionOptions: { recoveryManifest, throwOnError: true }, + }); + }); + + it("rejects invalid descriptor input before the rebuild pipeline boundary", async () => { + await expect( + rebuildOwningRegistryDependencies.runWorker( + { + operation: "rebuild", + sandboxName: "alpha", + options: null, + executionOptions: {}, + } as never, + 9000, + { observeInvocation: true }, + ), + ).rejects.toThrow(); + }); +}); From 10dde7bd8df62c006c796ed166898d65109b0aa5 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 11:12:10 -0700 Subject: [PATCH 25/44] fix(rebuild): preserve delegated failure diagnostics Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild-preflight-confirmation.ts | 11 +- .../sandbox/rebuild/owning-registry-worker.ts | 42 +++-- .../sandbox/rebuild/owning-registry.ts | 108 ++++++----- test/cli/rebuild-recovery-routing.test.ts | 176 +++++++++++------- .../rebuild-owning-registry-worker.test.ts | 35 ++-- 5 files changed, 222 insertions(+), 150 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts index b1a0f78088a..f7b5b476b1d 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts @@ -11,7 +11,7 @@ import { } from "../../domain/lifecycle/options"; import type { DcodeAutoApprovalMode } from "../../onboard/dcode-auto-approval"; import * as sandboxVersion from "../../sandbox/version"; -import { redact } from "../../security/redact"; +import { redact, redactFullWithUrls } from "../../security/redact"; import { createSystemDeps as createSessionDeps, getActiveSandboxSessions, @@ -23,6 +23,15 @@ import { ensureRebuildUsageNoticeAccepted } from "./rebuild-usage-notice"; export type RebuildVersionCheck = sandboxVersion.VersionCheckResult; +const MAX_REBUILD_FAILURE_MESSAGE_CHARS = 4 * 1024; + +/** Preserve actionable rebuild diagnostics without forwarding recognized credentials. */ +export function redactBoundedRebuildFailure(error: unknown): string { + return redactFullWithUrls(error instanceof Error ? error.message : String(error)) + .trim() + .slice(0, MAX_REBUILD_FAILURE_MESSAGE_CHARS); +} + export function createRebuildCommandContext( options: string[] | RebuildSandboxOptions, opts: { throwOnError?: boolean }, diff --git a/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts index 6c1e5167ae5..4f3ec399686 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts @@ -5,9 +5,10 @@ import fs from "node:fs"; import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; import { rebuildSandbox } from "../rebuild-pipeline"; +import { redactBoundedRebuildFailure } from "../rebuild-preflight-confirmation"; import type { RebuildSandboxExecutionOptions } from "../rebuild-prepared-recovery"; import { retireRebuildRecoveryBackup } from "../rebuild-recreate-journal"; -import type { OwningRegistryWorkerInput } from "./owning-registry"; +import type { OwningRegistryWorkerInput, OwningRegistryWorkerResult } from "./owning-registry"; const MAX_REBUILD_INPUT_BYTES = 4 * 1024 * 1024; @@ -58,8 +59,19 @@ function readInput(): OwningRegistryWorkerInput { throw new Error("Rebuild worker input is invalid."); } -async function main(): Promise { - const input = readInput(); +function writeResult(result: OwningRegistryWorkerResult): void { + fs.writeFileSync(4, JSON.stringify(result)); +} + +function workerIdentity(input: OwningRegistryWorkerInput): Omit { + return { + operation: input.operation, + sandboxName: input.sandboxName, + gatewayPort: Number(process.env.NEMOCLAW_GATEWAY_PORT), + }; +} + +async function run(input: OwningRegistryWorkerInput): Promise { if (input.operation === "retire-recovery") { const retired = retireRebuildRecoveryBackup(input); console.log( @@ -71,22 +83,20 @@ async function main(): Promise { ...input.executionOptions, throwOnError: true, } as const; + await rebuildSandbox(input.sandboxName, input.options, executionOptions); +} + +async function main(): Promise { + const input = readInput(); + const identity = workerIdentity(input); try { - fs.fstatSync(4); - fs.writeFileSync( - 4, - JSON.stringify({ - gatewayPort: process.env.NEMOCLAW_GATEWAY_PORT ?? "", - sandboxName: input.sandboxName, - options: input.options, - executionOptions, - }), - ); - return; + await run(input); + writeResult({ ok: true, ...identity }); } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "EBADF") throw error; + const detail = redactBoundedRebuildFailure(error); + writeResult({ ok: false, ...identity, ...(detail ? { message: detail } : {}) }); + process.exitCode = 1; } - await rebuildSandbox(input.sandboxName, input.options, executionOptions); } void main().catch(() => { diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index fc5da208cc0..c20cc31d7ab 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -37,27 +37,24 @@ export interface RebuildRecoveryStorageRoot { readonly registryFile: string; } -export interface RebuildWorkerInvocation { - readonly gatewayPort: string; - readonly sandboxName: string; - readonly options: RebuildSandboxOptions; - readonly executionOptions: RebuildSandboxExecutionOptions & { readonly throwOnError: true }; -} +export type OwningRegistryWorkerResult = Readonly<{ + ok: boolean; + operation: OwningRegistryWorkerInput["operation"]; + sandboxName: string; + gatewayPort: number; + message?: string; +}>; type RebuildOwningRegistryDependencies = { findSandbox: typeof findSandboxAcrossGatewayRoots; findRecoveryRoot: typeof findRebuildRecoveryStorageRoot; isHostFenceHeld: typeof isCurrentPortableHostFenceHeld; - runWorker( - input: OwningRegistryWorkerInput, - gatewayPort: number, - options?: Readonly<{ observeInvocation?: boolean }>, - ): Promise; + runWorker(input: OwningRegistryWorkerInput, gatewayPort: number): Promise; }; const WORKER_PATH = path.join(__dirname, "owning-registry-worker.js"); const MAX_RECOVERY_BACKUP_ENTRIES = 1024; -const MAX_WORKER_OBSERVATION_BYTES = 64 * 1024; +const MAX_WORKER_RESULT_BYTES = 64 * 1024; const REBUILD_ENV_NAMES = [ "NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "NEMOCLAW_NON_INTERACTIVE", @@ -80,41 +77,45 @@ function rebuildWorkerEnv(gatewayPort: number): Record { return buildSubprocessEnv(extra); } -async function readWorkerObservation(stream: Readable): Promise { +async function readWorkerResult(stream: Readable): Promise { const chunks: Buffer[] = []; let bytes = 0; for await (const chunk of stream) { const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string); bytes += buffer.length; - if (bytes > MAX_WORKER_OBSERVATION_BYTES) { - throw new Error("Rebuild worker observation is too large."); + if (bytes > MAX_WORKER_RESULT_BYTES) { + throw new Error("Rebuild worker result is too large."); } chunks.push(buffer); } - const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if (chunks.length === 0) return null; + let parsed: unknown; + try { + parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")); + } catch { + return null; + } if ( typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || - typeof (parsed as Record).gatewayPort !== "string" || - typeof (parsed as Record).sandboxName !== "string" + typeof (parsed as Record).ok !== "boolean" || + ((parsed as Record).operation !== "rebuild" && + (parsed as Record).operation !== "retire-recovery") || + typeof (parsed as Record).sandboxName !== "string" || + !Number.isInteger((parsed as Record).gatewayPort) || + ((parsed as Record).message !== undefined && + typeof (parsed as Record).message !== "string") ) { - throw new Error("Rebuild worker observation is invalid."); + return null; } - return parsed as RebuildWorkerInvocation; + return parsed as OwningRegistryWorkerResult; } -async function runWorker( - input: OwningRegistryWorkerInput, - gatewayPort: number, - options: Readonly<{ observeInvocation?: boolean }> = {}, -): Promise { - const observeInvocation = options.observeInvocation === true; +async function runWorker(input: OwningRegistryWorkerInput, gatewayPort: number): Promise { const child = spawn(process.execPath, [WORKER_PATH], { env: rebuildWorkerEnv(gatewayPort), - stdio: observeInvocation - ? ["inherit", "inherit", "inherit", "pipe", "pipe"] - : ["inherit", "inherit", "inherit", "pipe"], + stdio: ["inherit", "inherit", "inherit", "pipe", "pipe"], }); const inputStream = child.stdio[3]; if (!inputStream || !("end" in inputStream)) { @@ -125,28 +126,37 @@ async function runWorker( inputStream.once("error", reject); inputStream.end(JSON.stringify(input), resolve); }); - const observationStream = observeInvocation ? (child.stdio[4] as Readable | null) : null; - if (observeInvocation && !observationStream) { + const resultStream = child.stdio[4] as Readable | null; + if (!resultStream) { child.kill(); - throw new Error("Cannot observe the rebuild worker pipeline invocation."); + throw new Error("Cannot read the rebuild worker result."); } - const observation = observationStream ? readWorkerObservation(observationStream) : null; - const exited = new Promise((resolve, reject) => { - child.once("error", reject); - child.once("exit", (code, signal) => { - if (code === 0 && signal === null) { - resolve(); - return; - } - reject(new Error("Rebuild in the owning gateway registry did not complete successfully.")); - }); - }); - const [, , observed] = await Promise.all([ - inputWritten, - exited, - observation ?? Promise.resolve(undefined), - ]); - return observed; + const result = readWorkerResult(resultStream); + const exited = new Promise>( + (resolve, reject) => { + child.once("error", reject); + child.once("exit", (code, signal) => { + resolve({ code, signal }); + }); + }, + ); + const [, exit, workerResult] = await Promise.all([inputWritten, exited, result]); + const resultMatchesRequest = + workerResult?.operation === input.operation && + workerResult.sandboxName === input.sandboxName && + workerResult.gatewayPort === gatewayPort; + if ( + exit.code === 0 && + exit.signal === null && + workerResult?.ok === true && + resultMatchesRequest + ) { + return; + } + if (workerResult?.ok === false && resultMatchesRequest && workerResult.message) { + throw new Error(workerResult.message, { cause: workerResult }); + } + throw new Error("Rebuild in the owning gateway registry did not complete successfully."); } export const rebuildOwningRegistryDependencies: RebuildOwningRegistryDependencies = { diff --git a/test/cli/rebuild-recovery-routing.test.ts b/test/cli/rebuild-recovery-routing.test.ts index a469db6064d..5ef2463263b 100644 --- a/test/cli/rebuild-recovery-routing.test.ts +++ b/test/cli/rebuild-recovery-routing.test.ts @@ -9,6 +9,81 @@ import { describe, expect, it } from "vitest"; import { runWithEnv, testTimeoutOptions } from "./helpers"; +const TRANSACTION_ID = "11111111-1111-4111-8111-111111111111"; +const TIMESTAMP = "2026-09-10T00-00-00-000Z"; + +function writeOpenShellStub(home: string, sandboxPresent: boolean): string { + const localBin = path.join(home, "bin"); + fs.mkdirSync(localBin, { recursive: true }); + const openshellLog = path.join(home, "openshell-calls.log"); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/usr/bin/env bash", + `printf "%s\\n" "$*" >> ${JSON.stringify(openshellLog)}`, + sandboxPresent + ? 'case "$1 $2" in "sandbox get") echo "Name: gw1-sb"; exit 0 ;; esac' + : 'case "$1 $2" in "sandbox get") echo "no such sandbox gw1-sb" >&2 ;; esac', + "exit 1", + ].join("\n"), + { mode: 0o755 }, + ); + return openshellLog; +} + +function writeRecoveryFixture(home: string) { + const backupPath = path.join( + home, + ".nemoclaw", + "gateways", + "9000", + "rebuild-backups", + "gw1-sb", + TIMESTAMP, + ); + fs.mkdirSync(backupPath, { recursive: true, mode: 0o700 }); + const policy = "version: 1\nprocess:\n environment:\n SERVICE_API_KEY: retained\n"; + const sha256 = createHash("sha256").update(policy).digest("hex"); + const handoffPath = path.join(backupPath, `rebuild-policy-handoff.${sha256}.yaml`); + const recordPath = path.join(backupPath, ".nemoclaw-rebuild-recovery.json"); + const manifestPath = path.join(backupPath, "rebuild-manifest.json"); + const retainedPath = path.join(backupPath, "workspace-notes.txt"); + fs.writeFileSync(handoffPath, policy, { mode: 0o600 }); + fs.writeFileSync(retainedPath, "recovered later\n"); + fs.writeFileSync( + manifestPath, + JSON.stringify({ + version: 1, + sandboxName: "gw1-sb", + timestamp: TIMESTAMP, + agentType: "openclaw", + agentVersion: null, + expectedVersion: null, + stateDirs: [], + backupComplete: true, + dir: "/sandbox/.openclaw", + backupPath, + blueprintDigest: null, + rebuildPolicyHandoff: { file: path.basename(handoffPath), sha256 }, + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + recordPath, + `${JSON.stringify({ + schemaVersion: 3, + transactionId: TRANSACTION_ID, + sandboxName: "gw1-sb", + backupTimestamp: TIMESTAMP, + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, + phase: "restore", + })}\n`, + { mode: 0o600 }, + ); + return { backupPath, handoffPath, manifestPath, recordPath, retainedPath }; +} + describe("CLI rebuild recovery routing", () => { it( "retires a retained recovery record from a sibling gateway root after its registry row is removed (#11394)", @@ -16,79 +91,17 @@ describe("CLI rebuild recovery routing", () => { () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-retire-recovery-ok-")); try { - const localBin = path.join(home, "bin"); - fs.mkdirSync(localBin, { recursive: true }); - const openshellLog = path.join(home, "openshell-calls.log"); - fs.writeFileSync( - path.join(localBin, "openshell"), - [ - "#!/usr/bin/env bash", - `printf "%s\\n" "$*" >> ${JSON.stringify(openshellLog)}`, - 'case "$1 $2" in "sandbox get") echo "no such sandbox gw1-sb" >&2 ;; esac', - "exit 1", - ].join("\n"), - { mode: 0o755 }, - ); + const openshellLog = writeOpenShellStub(home, false); + const { backupPath, handoffPath, manifestPath, recordPath, retainedPath } = + writeRecoveryFixture(home); - const transactionId = "11111111-1111-4111-8111-111111111111"; - const timestamp = "2026-09-10T00-00-00-000Z"; - const backupPath = path.join( - home, - ".nemoclaw", - "gateways", - "9000", - "rebuild-backups", - "gw1-sb", - timestamp, - ); - fs.mkdirSync(backupPath, { recursive: true, mode: 0o700 }); - const policy = "version: 1\nprocess:\n environment:\n SERVICE_API_KEY: retained\n"; - const sha256 = createHash("sha256").update(policy).digest("hex"); - const handoffPath = path.join(backupPath, `rebuild-policy-handoff.${sha256}.yaml`); - const recordPath = path.join(backupPath, ".nemoclaw-rebuild-recovery.json"); - const manifestPath = path.join(backupPath, "rebuild-manifest.json"); - const retainedPath = path.join(backupPath, "workspace-notes.txt"); - fs.writeFileSync(handoffPath, policy, { mode: 0o600 }); - fs.writeFileSync(retainedPath, "recovered later\n"); - fs.writeFileSync( - manifestPath, - JSON.stringify({ - version: 1, - sandboxName: "gw1-sb", - timestamp, - agentType: "openclaw", - agentVersion: null, - expectedVersion: null, - stateDirs: [], - backupComplete: true, - dir: "/sandbox/.openclaw", - backupPath, - blueprintDigest: null, - rebuildPolicyHandoff: { file: path.basename(handoffPath), sha256 }, - }), - { mode: 0o600 }, - ); - fs.writeFileSync( - recordPath, - `${JSON.stringify({ - schemaVersion: 3, - transactionId, - sandboxName: "gw1-sb", - backupTimestamp: timestamp, - gatewayName: "nemoclaw-9000", - gatewayPort: 9000, - phase: "restore", - })}\n`, - { mode: 0o600 }, - ); - - const result = runWithEnv(`gw1-sb rebuild --retire-recovery ${transactionId} --yes`, { + const result = runWithEnv(`gw1-sb rebuild --retire-recovery ${TRANSACTION_ID} --yes`, { HOME: home, - PATH: `${localBin}:${process.env.PATH || ""}`, + PATH: `${path.join(home, "bin")}:${process.env.PATH || ""}`, }); expect(result.out).toContain( - `Retired rebuild recovery '${transactionId}' for sandbox 'gw1-sb' from ${backupPath}.`, + `Retired rebuild recovery '${TRANSACTION_ID}' for sandbox 'gw1-sb' from ${backupPath}.`, ); expect(result.code).toBe(0); expect(fs.readFileSync(openshellLog, "utf8").trim().split("\n")).toEqual([ @@ -105,4 +118,31 @@ describe("CLI rebuild recovery routing", () => { } }, ); + + it( + "preserves a sibling-root retirement failure and retained recovery path", + testTimeoutOptions(35_000), + () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-retire-recovery-fail-")); + try { + writeOpenShellStub(home, true); + const { backupPath, handoffPath, recordPath } = writeRecoveryFixture(home); + + const result = runWithEnv(`gw1-sb rebuild --retire-recovery ${TRANSACTION_ID} --yes`, { + HOME: home, + PATH: `${path.join(home, "bin")}:${process.env.PATH || ""}`, + }); + + expect(result.code).toBe(1); + expect(result.out).toContain( + "Cannot retire rebuild recovery before confirmed sandbox deletion: OpenShell still reports sandbox 'gw1-sb' on recorded gateway 'nemoclaw-9000'", + ); + expect(result.out).toContain(`Recovery remains at '${backupPath}'.`); + expect(fs.existsSync(handoffPath)).toBe(true); + expect(fs.existsSync(recordPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); }); diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index 6eed495572a..129f82ecd72 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -6,28 +6,32 @@ import { describe, expect, it } from "vitest"; import { rebuildOwningRegistryDependencies } from "../../dist/lib/actions/sandbox/rebuild/owning-registry"; describe("compiled rebuild owning-registry worker", () => { - it("transfers the exact rebuild invocation over the private descriptor", async () => { - const recoveryManifest = { - sandboxName: "alpha", - backupPath: "/backup/alpha", - } as never; + it("executes the real pipeline and preserves its bounded failure", async () => { + const expectedMessage = "toolDisclosure must be one of: progressive, direct."; + let failure: unknown; - await expect( - rebuildOwningRegistryDependencies.runWorker( + try { + await rebuildOwningRegistryDependencies.runWorker( { operation: "rebuild", sandboxName: "alpha", - options: { yes: true, verbose: true }, - executionOptions: { recoveryManifest }, + options: { yes: true, toolDisclosure: "invalid" } as never, + executionOptions: {}, }, 9000, - { observeInvocation: true }, - ), - ).resolves.toEqual({ - gatewayPort: "9000", + ); + } catch (error) { + failure = error; + } + + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toBe(expectedMessage); + expect((failure as Error).cause).toEqual({ + ok: false, + operation: "rebuild", sandboxName: "alpha", - options: { yes: true, verbose: true }, - executionOptions: { recoveryManifest, throwOnError: true }, + gatewayPort: 9000, + message: expectedMessage, }); }); @@ -41,7 +45,6 @@ describe("compiled rebuild owning-registry worker", () => { executionOptions: {}, } as never, 9000, - { observeInvocation: true }, ), ).rejects.toThrow(); }); From 117fd30ff4e3ca42172f4f68ca538f665c3b6ef3 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 11:53:23 -0700 Subject: [PATCH 26/44] fix(rebuild): bound owning-registry worker waits Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild/owning-registry.ts | 61 ++++++++++++++++++- .../rebuild-owning-registry-worker.test.ts | 17 ++++++ 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index c20cc31d7ab..9e951813f19 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -49,12 +49,18 @@ type RebuildOwningRegistryDependencies = { findSandbox: typeof findSandboxAcrossGatewayRoots; findRecoveryRoot: typeof findRebuildRecoveryStorageRoot; isHostFenceHeld: typeof isCurrentPortableHostFenceHeld; - runWorker(input: OwningRegistryWorkerInput, gatewayPort: number): Promise; + runWorker( + input: OwningRegistryWorkerInput, + gatewayPort: number, + options?: Readonly<{ timeoutMs?: number }>, + ): Promise; }; const WORKER_PATH = path.join(__dirname, "owning-registry-worker.js"); const MAX_RECOVERY_BACKUP_ENTRIES = 1024; const MAX_WORKER_RESULT_BYTES = 64 * 1024; +const REBUILD_WORKER_TIMEOUT_MS = 45 * 60_000; +const REBUILD_WORKER_TERMINATION_GRACE_MS = 5_000; const REBUILD_ENV_NAMES = [ "NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "NEMOCLAW_NON_INTERACTIVE", @@ -112,7 +118,15 @@ async function readWorkerResult(stream: Readable): Promise { +async function runWorker( + input: OwningRegistryWorkerInput, + gatewayPort: number, + options: Readonly<{ timeoutMs?: number }> = {}, +): Promise { + const timeoutMs = options.timeoutMs ?? REBUILD_WORKER_TIMEOUT_MS; + if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) { + throw new Error("Rebuild worker timeout must be a positive integer."); + } const child = spawn(process.execPath, [WORKER_PATH], { env: rebuildWorkerEnv(gatewayPort), stdio: ["inherit", "inherit", "inherit", "pipe", "pipe"], @@ -140,7 +154,48 @@ async function runWorker(input: OwningRegistryWorkerInput, gatewayPort: number): }); }, ); - const [, exit, workerResult] = await Promise.all([inputWritten, exited, result]); + const completion = Promise.all([inputWritten, exited, result] as const); + let deadline: NodeJS.Timeout | undefined; + const timeout = new Promise>((resolve) => { + deadline = setTimeout(() => resolve({ kind: "timeout" }), timeoutMs); + }); + let outcome: + | Readonly<{ + kind: "completed"; + value: Awaited; + }> + | Readonly<{ kind: "timeout" }>; + try { + outcome = await Promise.race([ + completion.then((value) => ({ kind: "completed" as const, value })), + timeout, + ]); + } finally { + if (deadline) clearTimeout(deadline); + } + if (outcome.kind === "timeout") { + child.kill("SIGTERM"); + let graceDeadline: NodeJS.Timeout | undefined; + const graceExpired = new Promise((resolve) => { + graceDeadline = setTimeout(() => resolve(true), REBUILD_WORKER_TERMINATION_GRACE_MS); + }); + const exitedDuringGrace = exited.then( + () => false, + () => false, + ); + const forceKill = await Promise.race([graceExpired, exitedDuringGrace]); + if (graceDeadline) clearTimeout(graceDeadline); + if (forceKill) { + child.kill("SIGKILL"); + await exited.catch(() => undefined); + } + await Promise.allSettled([inputWritten, result]); + const operation = input.operation === "rebuild" ? "rebuild" : "recovery retirement"; + throw new Error( + `Delegated ${operation} for sandbox '${input.sandboxName}' on owning gateway port ${String(gatewayPort)} exceeded its ${String(timeoutMs)} ms deadline. The worker was terminated, but the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect the sandbox and recovery state before retrying.`, + ); + } + const [, exit, workerResult] = outcome.value; const resultMatchesRequest = workerResult?.operation === input.operation && workerResult.sandboxName === input.sandboxName && diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index 129f82ecd72..241eb9e503b 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -48,4 +48,21 @@ describe("compiled rebuild owning-registry worker", () => { ), ).rejects.toThrow(); }); + + it("terminates an unresponsive worker with an unknown-outcome recovery diagnostic", async () => { + await expect( + rebuildOwningRegistryDependencies.runWorker( + { + operation: "retire-recovery", + sandboxName: "alpha", + transactionId: "11111111-1111-4111-8111-111111111111", + confirmDataRecovered: true, + }, + 9000, + { timeoutMs: 1 }, + ), + ).rejects.toThrow( + "Delegated recovery retirement for sandbox 'alpha' on owning gateway port 9000 exceeded its 1 ms deadline. The worker was terminated, but the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect the sandbox and recovery state before retrying.", + ); + }); }); From 444eea4ba8eeafd1c415baf20a7e06ae8cc6cbe6 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 12:56:26 -0700 Subject: [PATCH 27/44] fix(rebuild): close delegated worker recovery gaps Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild-gateway-drift.test.ts | 17 ++ .../sandbox/rebuild/owning-registry.ts | 105 ++++++++-- test/cli/rebuild-recovery-routing.test.ts | 51 +++++ .../rebuild-owning-registry-worker.test.ts | 179 +++++++++++++++++- 4 files changed, 334 insertions(+), 18 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index edf2a191186..bd05040ba50 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -531,4 +531,21 @@ describe("rebuild owning registry routing", () => { fs.rmSync(home, { recursive: true, force: true }); } }); + + it("rejects traversal-shaped recovery names before reading gateway roots", () => { + const readDirectory = vi.spyOn(fs, "readdirSync"); + + expect(() => + findRebuildRecoveryStorageRoot( + { + sandboxName: "../outside", + transactionId: "11111111-1111-4111-8111-111111111111", + confirmDataRecovered: true, + }, + "/home/test", + ), + ).toThrow("Invalid sandbox name."); + + expect(readDirectory).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index 9e951813f19..eab54bbf11e 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawn } from "node:child_process"; +import { spawn, type ChildProcess } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import type { Readable } from "node:stream"; +import { isValidNemoClawSandboxName } from "../../../config/model"; import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; import { snapshotKnownCredentialEnv } from "../../../onboard/credential-env"; import { assertGatewayStatePathSafe, listGatewayStateRoots } from "../../../state/gateway-registry"; @@ -52,7 +53,7 @@ type RebuildOwningRegistryDependencies = { runWorker( input: OwningRegistryWorkerInput, gatewayPort: number, - options?: Readonly<{ timeoutMs?: number }>, + options?: Readonly<{ terminationGraceMs?: number; timeoutMs?: number }>, ): Promise; }; @@ -61,6 +62,8 @@ const MAX_RECOVERY_BACKUP_ENTRIES = 1024; const MAX_WORKER_RESULT_BYTES = 64 * 1024; const REBUILD_WORKER_TIMEOUT_MS = 45 * 60_000; const REBUILD_WORKER_TERMINATION_GRACE_MS = 5_000; +const REBUILD_WORKER_REAP_TIMEOUT_MS = 2_000; +const REBUILD_WORKER_REAP_POLL_MS = 10; const REBUILD_ENV_NAMES = [ "NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "NEMOCLAW_NON_INTERACTIVE", @@ -118,16 +121,82 @@ async function readWorkerResult(stream: Readable): Promise { + const deadline = Date.now() + timeoutMs; + while (workerProcessGroupIsRunning(child, dedicatedProcessGroup)) { + if (Date.now() >= deadline) return false; + await new Promise((resolve) => setTimeout(resolve, REBUILD_WORKER_REAP_POLL_MS)); + } + return true; +} + +async function settleWorkerPromises( + promises: readonly Promise[], + timeoutMs: number, +): Promise { + let deadline: NodeJS.Timeout | undefined; + const timeout = new Promise((resolve) => { + deadline = setTimeout(resolve, timeoutMs); + }); + try { + await Promise.race([Promise.allSettled(promises), timeout]); + } finally { + if (deadline) clearTimeout(deadline); + } +} + async function runWorker( input: OwningRegistryWorkerInput, gatewayPort: number, - options: Readonly<{ timeoutMs?: number }> = {}, + options: Readonly<{ terminationGraceMs?: number; timeoutMs?: number }> = {}, ): Promise { const timeoutMs = options.timeoutMs ?? REBUILD_WORKER_TIMEOUT_MS; if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) { throw new Error("Rebuild worker timeout must be a positive integer."); } + const terminationGraceMs = options.terminationGraceMs ?? REBUILD_WORKER_TERMINATION_GRACE_MS; + if (!Number.isInteger(terminationGraceMs) || terminationGraceMs <= 0) { + throw new Error("Rebuild worker termination grace must be a positive integer."); + } + const dedicatedProcessGroup = process.platform !== "win32"; const child = spawn(process.execPath, [WORKER_PATH], { + detached: dedicatedProcessGroup, env: rebuildWorkerEnv(gatewayPort), stdio: ["inherit", "inherit", "inherit", "pipe", "pipe"], }); @@ -174,22 +243,21 @@ async function runWorker( if (deadline) clearTimeout(deadline); } if (outcome.kind === "timeout") { - child.kill("SIGTERM"); - let graceDeadline: NodeJS.Timeout | undefined; - const graceExpired = new Promise((resolve) => { - graceDeadline = setTimeout(() => resolve(true), REBUILD_WORKER_TERMINATION_GRACE_MS); - }); - const exitedDuringGrace = exited.then( - () => false, - () => false, + signalWorkerProcessGroup(child, dedicatedProcessGroup, "SIGTERM"); + const stoppedGracefully = await waitForWorkerProcessGroupExit( + child, + dedicatedProcessGroup, + terminationGraceMs, ); - const forceKill = await Promise.race([graceExpired, exitedDuringGrace]); - if (graceDeadline) clearTimeout(graceDeadline); - if (forceKill) { - child.kill("SIGKILL"); - await exited.catch(() => undefined); + if (!stoppedGracefully) { + signalWorkerProcessGroup(child, dedicatedProcessGroup, "SIGKILL"); + await waitForWorkerProcessGroupExit( + child, + dedicatedProcessGroup, + REBUILD_WORKER_REAP_TIMEOUT_MS, + ); } - await Promise.allSettled([inputWritten, result]); + await settleWorkerPromises([inputWritten, exited, result], REBUILD_WORKER_REAP_TIMEOUT_MS); const operation = input.operation === "rebuild" ? "rebuild" : "recovery retirement"; throw new Error( `Delegated ${operation} for sandbox '${input.sandboxName}' on owning gateway port ${String(gatewayPort)} exceeded its ${String(timeoutMs)} ms deadline. The worker was terminated, but the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect the sandbox and recovery state before retrying.`, @@ -226,6 +294,9 @@ export function findRebuildRecoveryStorageRoot( input: RetireRecoveryOwningRegistryInput, homeDir: string, ): RebuildRecoveryStorageRoot | null { + if (!isValidNemoClawSandboxName(input.sandboxName)) { + throw new Error("Invalid sandbox name."); + } const matches: RebuildRecoveryStorageRoot[] = []; for (const state of listGatewayStateRoots(homeDir)) { const sandboxBackupRoot = path.join(state.root, "rebuild-backups", input.sandboxName); diff --git a/test/cli/rebuild-recovery-routing.test.ts b/test/cli/rebuild-recovery-routing.test.ts index 5ef2463263b..74d71e2a0e9 100644 --- a/test/cli/rebuild-recovery-routing.test.ts +++ b/test/cli/rebuild-recovery-routing.test.ts @@ -84,7 +84,58 @@ function writeRecoveryFixture(home: string) { return { backupPath, handoffPath, manifestPath, recordPath, retainedPath }; } +function writeSiblingRegistry(home: string): string { + const stateRoot = path.join(home, ".nemoclaw", "gateways", "9000"); + fs.mkdirSync(stateRoot, { recursive: true, mode: 0o700 }); + const registryPath = path.join(stateRoot, "sandboxes.json"); + fs.writeFileSync( + registryPath, + `${JSON.stringify({ + defaultSandbox: "gw1-sb", + sandboxes: { + "gw1-sb": { + name: "gw1-sb", + provider: "ollama-local", + model: "nvidia/nemotron", + agent: "openclaw", + nemoclawVersion: "0.1.0", + dashboardPort: 18_789, + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, + }, + }, + })}\n`, + { mode: 0o600 }, + ); + return registryPath; +} + describe("CLI rebuild recovery routing", () => { + it( + "routes a valid sibling-root rebuild through the compiled worker", + testTimeoutOptions(35_000), + () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-rebuild-sibling-")); + try { + const registryPath = writeSiblingRegistry(home); + + const result = runWithEnv("gw1-sb rebuild --yes", { + HOME: home, + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", + DOCKER_HOST: `unix://${path.join(home, "missing-docker.sock")}`, + }); + + expect(result.code).toBe(1); + expect(result.out).toContain("Rebuild sandbox 'gw1-sb'"); + expect(result.out).toContain("Replacement onboarding preflight failed"); + expect(fs.existsSync(registryPath)).toBe(true); + expect(fs.existsSync(path.join(home, ".nemoclaw", "sandboxes.json"))).toBe(false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); + it( "retires a retained recovery record from a sibling gateway root after its registry row is removed (#11394)", testTimeoutOptions(35_000), diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index 241eb9e503b..2902a8b02d3 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -1,10 +1,111 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; import { rebuildOwningRegistryDependencies } from "../../dist/lib/actions/sandbox/rebuild/owning-registry"; +const TRANSACTION_ID = "11111111-1111-4111-8111-111111111111"; +const TIMESTAMP = "2026-09-17T00-00-00-000Z"; + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +function writeRecoveryFixture(home: string): void { + const backupPath = path.join( + home, + ".nemoclaw", + "gateways", + "9000", + "rebuild-backups", + "alpha", + TIMESTAMP, + ); + fs.mkdirSync(backupPath, { recursive: true, mode: 0o700 }); + const policy = "version: 1\nprocess:\n environment:\n SERVICE_API_KEY: retained\n"; + const sha256 = createHash("sha256").update(policy).digest("hex"); + const handoffPath = path.join(backupPath, `rebuild-policy-handoff.${sha256}.yaml`); + fs.writeFileSync(handoffPath, policy, { mode: 0o600 }); + fs.writeFileSync( + path.join(backupPath, "rebuild-manifest.json"), + JSON.stringify({ + version: 1, + sandboxName: "alpha", + timestamp: TIMESTAMP, + agentType: "openclaw", + agentVersion: null, + expectedVersion: null, + stateDirs: [], + backupComplete: true, + dir: "/sandbox/.openclaw", + backupPath, + blueprintDigest: null, + rebuildPolicyHandoff: { file: path.basename(handoffPath), sha256 }, + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + path.join(backupPath, ".nemoclaw-rebuild-recovery.json"), + `${JSON.stringify({ + schemaVersion: 3, + transactionId: TRANSACTION_ID, + sandboxName: "alpha", + backupTimestamp: TIMESTAMP, + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, + phase: "restore", + })}\n`, + { mode: 0o600 }, + ); +} + +function writeBlockingOpenShell(home: string, descendantMarker: string): string { + const executable = path.join(home, "blocking-openshell.cjs"); + fs.writeFileSync( + executable, + [ + "#!/usr/bin/env node", + 'const { spawn } = require("node:child_process");', + 'const fs = require("node:fs");', + 'const child = spawn(process.execPath, ["-e", "process.on(\'SIGTERM\', () => {}); setInterval(() => {}, 1000)"], { stdio: "ignore" });', + `fs.writeFileSync(${JSON.stringify(descendantMarker)}, String(child.pid));`, + "setInterval(() => {}, 1000);", + ].join("\n"), + { mode: 0o755 }, + ); + return executable; +} + +function writeSiblingRegistry(home: string): void { + const stateRoot = path.join(home, ".nemoclaw", "gateways", "9000"); + fs.mkdirSync(stateRoot, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(stateRoot, "sandboxes.json"), + `${JSON.stringify({ + defaultSandbox: "alpha", + sandboxes: { + alpha: { + name: "alpha", + provider: "ollama-local", + model: "nvidia/nemotron", + agent: "openclaw", + nemoclawVersion: "0.1.0", + dashboardPort: 18_789, + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, + }, + }, + })}\n`, + { mode: 0o600 }, + ); +} + describe("compiled rebuild owning-registry worker", () => { it("executes the real pipeline and preserves its bounded failure", async () => { const expectedMessage = "toolDisclosure must be one of: progressive, direct."; @@ -49,6 +150,46 @@ describe("compiled rebuild owning-registry worker", () => { ).rejects.toThrow(); }); + it("binds a valid rebuild descriptor to the selected sibling registry root", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-worker-sibling-root-")); + try { + writeSiblingRegistry(home); + vi.stubEnv("HOME", home); + vi.stubEnv("NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "1"); + vi.stubEnv("DOCKER_HOST", `unix://${path.join(home, "missing-docker.sock")}`); + vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", path.join(home, "missing-openshell")); + let failure: unknown; + + try { + await rebuildOwningRegistryDependencies.runWorker( + { + operation: "rebuild", + sandboxName: "alpha", + options: { yes: true }, + executionOptions: {}, + }, + 9000, + ); + } catch (error) { + failure = error; + } + + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toBe("Replacement onboarding preflight failed"); + expect((failure as Error).cause).toEqual( + expect.objectContaining({ + ok: false, + operation: "rebuild", + sandboxName: "alpha", + gatewayPort: 9000, + message: "Replacement onboarding preflight failed", + }), + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("terminates an unresponsive worker with an unknown-outcome recovery diagnostic", async () => { await expect( rebuildOwningRegistryDependencies.runWorker( @@ -65,4 +206,40 @@ describe("compiled rebuild owning-registry worker", () => { "Delegated recovery retirement for sandbox 'alpha' on owning gateway port 9000 exceeded its 1 ms deadline. The worker was terminated, but the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect the sandbox and recovery state before retrying.", ); }); + + it("terminates worker descendants before reporting an unknown recovery outcome", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-worker-process-group-")); + const descendantMarker = path.join(home, "descendant.pid"); + let descendantPid: number | undefined; + try { + writeRecoveryFixture(home); + vi.stubEnv("HOME", home); + vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", writeBlockingOpenShell(home, descendantMarker)); + + await expect( + rebuildOwningRegistryDependencies.runWorker( + { + operation: "retire-recovery", + sandboxName: "alpha", + transactionId: TRANSACTION_ID, + confirmDataRecovered: true, + }, + 9000, + { timeoutMs: 3_000, terminationGraceMs: 100 }, + ), + ).rejects.toThrow("The worker was terminated, but the operation outcome is unknown."); + + descendantPid = Number(fs.readFileSync(descendantMarker, "utf8")); + expect(() => process.kill(descendantPid!, 0)).toThrow( + expect.objectContaining({ code: "ESRCH" }), + ); + } finally { + try { + process.kill(descendantPid as number, "SIGKILL"); + } catch { + // The process group cleanup succeeded or the marker was never written. + } + fs.rmSync(home, { recursive: true, force: true }); + } + }); }); From 522e25b7ee58aeb3986200c30877891ffb3bfe1e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 13:18:43 -0700 Subject: [PATCH 28/44] test(rebuild): make delegated worker proof portable Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- ci/source-architecture-budget.json | 2 +- .../sandbox/rebuild/owning-registry.ts | 4 +- .../rebuild-owning-registry-worker.test.ts | 50 +++++++++---------- 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 562dc40aebc..256f721eceb 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -26,7 +26,7 @@ "src/lib/messaging/channels/index.ts": 24, "src/lib/onboard/gateway-binding.ts": 52, "src/lib/runner.ts": 83, - "src/lib/sandbox-name-contract.ts": 21, + "src/lib/sandbox-name-contract.ts": 22, "src/lib/security/redact.ts": 51, "src/lib/state/mcp-lifecycle-lock.ts": 20, "src/lib/state/onboard-session.ts": 35, diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index eab54bbf11e..122037c7286 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -6,9 +6,9 @@ import fs from "node:fs"; import path from "node:path"; import type { Readable } from "node:stream"; -import { isValidNemoClawSandboxName } from "../../../config/model"; import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; import { snapshotKnownCredentialEnv } from "../../../onboard/credential-env"; +import { isValidName } from "../../../sandbox-name-contract"; import { assertGatewayStatePathSafe, listGatewayStateRoots } from "../../../state/gateway-registry"; import { isCurrentPortableHostFenceHeld } from "../../../state/portable-uninstall-retirement"; import { buildSubprocessEnv } from "../../../subprocess-env"; @@ -294,7 +294,7 @@ export function findRebuildRecoveryStorageRoot( input: RetireRecoveryOwningRegistryInput, homeDir: string, ): RebuildRecoveryStorageRoot | null { - if (!isValidNemoClawSandboxName(input.sandboxName)) { + if (!isValidName(input.sandboxName)) { throw new Error("Invalid sandbox name."); } const matches: RebuildRecoveryStorageRoot[] = []; diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index 2902a8b02d3..bc1ddc6a367 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -17,7 +17,7 @@ afterEach(() => { vi.unstubAllEnvs(); }); -function writeRecoveryFixture(home: string): void { +function writeRecoveryFixture(home: string) { const backupPath = path.join( home, ".nemoclaw", @@ -32,24 +32,23 @@ function writeRecoveryFixture(home: string): void { const sha256 = createHash("sha256").update(policy).digest("hex"); const handoffPath = path.join(backupPath, `rebuild-policy-handoff.${sha256}.yaml`); fs.writeFileSync(handoffPath, policy, { mode: 0o600 }); - fs.writeFileSync( - path.join(backupPath, "rebuild-manifest.json"), - JSON.stringify({ - version: 1, - sandboxName: "alpha", - timestamp: TIMESTAMP, - agentType: "openclaw", - agentVersion: null, - expectedVersion: null, - stateDirs: [], - backupComplete: true, - dir: "/sandbox/.openclaw", - backupPath, - blueprintDigest: null, - rebuildPolicyHandoff: { file: path.basename(handoffPath), sha256 }, - }), - { mode: 0o600 }, - ); + const manifest = { + version: 1, + sandboxName: "alpha", + timestamp: TIMESTAMP, + agentType: "openclaw", + agentVersion: null, + expectedVersion: null, + stateDirs: [], + backupComplete: true, + dir: "/sandbox/.openclaw", + backupPath, + blueprintDigest: null, + rebuildPolicyHandoff: { file: path.basename(handoffPath), sha256 }, + }; + fs.writeFileSync(path.join(backupPath, "rebuild-manifest.json"), JSON.stringify(manifest), { + mode: 0o600, + }); fs.writeFileSync( path.join(backupPath, ".nemoclaw-rebuild-recovery.json"), `${JSON.stringify({ @@ -63,6 +62,7 @@ function writeRecoveryFixture(home: string): void { })}\n`, { mode: 0o600 }, ); + return manifest; } function writeBlockingOpenShell(home: string, descendantMarker: string): string { @@ -95,7 +95,6 @@ function writeSiblingRegistry(home: string): void { provider: "ollama-local", model: "nvidia/nemotron", agent: "openclaw", - nemoclawVersion: "0.1.0", dashboardPort: 18_789, gatewayName: "nemoclaw-9000", gatewayPort: 9000, @@ -154,10 +153,9 @@ describe("compiled rebuild owning-registry worker", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-worker-sibling-root-")); try { writeSiblingRegistry(home); + const recoveryManifest = writeRecoveryFixture(home); vi.stubEnv("HOME", home); vi.stubEnv("NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "1"); - vi.stubEnv("DOCKER_HOST", `unix://${path.join(home, "missing-docker.sock")}`); - vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", path.join(home, "missing-openshell")); let failure: unknown; try { @@ -166,7 +164,7 @@ describe("compiled rebuild owning-registry worker", () => { operation: "rebuild", sandboxName: "alpha", options: { yes: true }, - executionOptions: {}, + executionOptions: { recoveryManifest }, }, 9000, ); @@ -175,14 +173,16 @@ describe("compiled rebuild owning-registry worker", () => { } expect(failure).toBeInstanceOf(Error); - expect((failure as Error).message).toBe("Replacement onboarding preflight failed"); + expect((failure as Error).message).toBe( + "Recovery registry entry has no NemoClaw-managed image fingerprint.", + ); expect((failure as Error).cause).toEqual( expect.objectContaining({ ok: false, operation: "rebuild", sandboxName: "alpha", gatewayPort: 9000, - message: "Replacement onboarding preflight failed", + message: "Recovery registry entry has no NemoClaw-managed image fingerprint.", }), ); } finally { From 5b1b55894ec3f1481a4cbec6663d95c36e7c1b05 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 13:37:58 -0700 Subject: [PATCH 29/44] test(rebuild): accept host-boundary routing failures Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/cli/rebuild-recovery-routing.test.ts | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/test/cli/rebuild-recovery-routing.test.ts b/test/cli/rebuild-recovery-routing.test.ts index 74d71e2a0e9..3131253da81 100644 --- a/test/cli/rebuild-recovery-routing.test.ts +++ b/test/cli/rebuild-recovery-routing.test.ts @@ -119,15 +119,23 @@ describe("CLI rebuild recovery routing", () => { try { const registryPath = writeSiblingRegistry(home); - const result = runWithEnv("gw1-sb rebuild --yes", { - HOME: home, - NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", - DOCKER_HOST: `unix://${path.join(home, "missing-docker.sock")}`, - }); + const result = runWithEnv( + "gw1-sb rebuild --yes", + { + HOME: home, + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE: "1", + DOCKER_HOST: `unix://${path.join(home, "missing-docker.sock")}`, + }, + 30_000, + ); expect(result.code).toBe(1); - expect(result.out).toContain("Rebuild sandbox 'gw1-sb'"); - expect(result.out).toContain("Replacement onboarding preflight failed"); + expect(result.out).toMatch( + /Rebuild sandbox 'gw1-sb'|openshell CLI not found\. Install OpenShell before using sandbox commands\./, + ); + expect(result.out).toMatch( + /Error: (?:Replacement onboarding preflight failed|Rebuild in the owning gateway registry did not complete successfully\.)/, + ); expect(fs.existsSync(registryPath)).toBe(true); expect(fs.existsSync(path.join(home, ".nemoclaw", "sandboxes.json"))).toBe(false); } finally { From 740322334d6806a24bfcca6f2480e51aae26dfe9 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 14:11:51 -0700 Subject: [PATCH 30/44] fix(rebuild): report unreaped delegated workers Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild/owning-registry.ts | 12 +++++++--- .../rebuild-owning-registry-worker.test.ts | 24 +++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index 122037c7286..611fc353966 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -244,14 +244,14 @@ async function runWorker( } if (outcome.kind === "timeout") { signalWorkerProcessGroup(child, dedicatedProcessGroup, "SIGTERM"); - const stoppedGracefully = await waitForWorkerProcessGroupExit( + let workerReaped = await waitForWorkerProcessGroupExit( child, dedicatedProcessGroup, terminationGraceMs, ); - if (!stoppedGracefully) { + if (!workerReaped) { signalWorkerProcessGroup(child, dedicatedProcessGroup, "SIGKILL"); - await waitForWorkerProcessGroupExit( + workerReaped = await waitForWorkerProcessGroupExit( child, dedicatedProcessGroup, REBUILD_WORKER_REAP_TIMEOUT_MS, @@ -259,6 +259,12 @@ async function runWorker( } await settleWorkerPromises([inputWritten, exited, result], REBUILD_WORKER_REAP_TIMEOUT_MS); const operation = input.operation === "rebuild" ? "rebuild" : "recovery retirement"; + if (!workerReaped) { + const workerPid = typeof child.pid === "number" ? String(child.pid) : "unavailable"; + throw new Error( + `Delegated ${operation} for sandbox '${input.sandboxName}' on owning gateway port ${String(gatewayPort)} exceeded its ${String(timeoutMs)} ms deadline. Termination is unconfirmed for worker PID ${workerPid}, so the worker or one of its descendants may still be active and the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect that worker, the sandbox, and recovery state before retrying.`, + ); + } throw new Error( `Delegated ${operation} for sandbox '${input.sandboxName}' on owning gateway port ${String(gatewayPort)} exceeded its ${String(timeoutMs)} ms deadline. The worker was terminated, but the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect the sandbox and recovery state before retrying.`, ); diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index bc1ddc6a367..458d8a231ad 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -14,6 +14,7 @@ const TRANSACTION_ID = "11111111-1111-4111-8111-111111111111"; const TIMESTAMP = "2026-09-17T00-00-00-000Z"; afterEach(() => { + vi.restoreAllMocks(); vi.unstubAllEnvs(); }); @@ -242,4 +243,27 @@ describe("compiled rebuild owning-registry worker", () => { fs.rmSync(home, { recursive: true, force: true }); } }); + + it("reports an unreaped worker as potentially active", async () => { + const kill = process.kill.bind(process); + vi.spyOn(process, "kill").mockImplementation((pid, signal) => { + if (pid < 0 && signal === 0) return true; + return kill(pid, signal); + }); + + await expect( + rebuildOwningRegistryDependencies.runWorker( + { + operation: "retire-recovery", + sandboxName: "alpha", + transactionId: TRANSACTION_ID, + confirmDataRecovered: true, + }, + 9000, + { timeoutMs: 1, terminationGraceMs: 1 }, + ), + ).rejects.toThrow( + /Delegated recovery retirement for sandbox 'alpha' on owning gateway port 9000 exceeded its 1 ms deadline\. Termination is unconfirmed for worker PID \d+, so the worker or one of its descendants may still be active and the operation outcome is unknown\. NemoClaw did not remove retained recovery state; inspect that worker, the sandbox, and recovery state before retrying\./, + ); + }); }); From e9e9c71c083a556a51ac55cb6f8f0919cd1d1c17 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 14:15:01 -0700 Subject: [PATCH 31/44] test(rebuild): avoid conditional worker stub Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../rebuild-owning-registry-worker.test.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index 458d8a231ad..7bd4b0d8340 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -246,10 +246,9 @@ describe("compiled rebuild owning-registry worker", () => { it("reports an unreaped worker as potentially active", async () => { const kill = process.kill.bind(process); - vi.spyOn(process, "kill").mockImplementation((pid, signal) => { - if (pid < 0 && signal === 0) return true; - return kill(pid, signal); - }); + vi.spyOn(process, "kill").mockImplementation((pid, signal) => + pid < 0 && signal === 0 ? true : kill(pid, signal), + ); await expect( rebuildOwningRegistryDependencies.runWorker( From 4b323cfe0207aed8fe2592462da1cd19a1a88667 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Thu, 17 Sep 2026 14:59:32 -0700 Subject: [PATCH 32/44] fix(rebuild): close delegated worker review gaps Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild/owning-registry.ts | 13 ++- .../rebuild-owning-registry-worker.test.ts | 80 ++++++++++++++++++- 2 files changed, 91 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index 611fc353966..c1937ce9e44 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -46,7 +46,16 @@ export type OwningRegistryWorkerResult = Readonly<{ message?: string; }>; +function assertWorkerPlatformSupported(platform: NodeJS.Platform): void { + if (platform === "win32") { + throw new Error( + "Delegated owning-registry rebuild work is unsupported on native Windows. Run NemoClaw inside WSL.", + ); + } +} + type RebuildOwningRegistryDependencies = { + assertWorkerPlatformSupported: typeof assertWorkerPlatformSupported; findSandbox: typeof findSandboxAcrossGatewayRoots; findRecoveryRoot: typeof findRebuildRecoveryStorageRoot; isHostFenceHeld: typeof isCurrentPortableHostFenceHeld; @@ -194,7 +203,8 @@ async function runWorker( if (!Number.isInteger(terminationGraceMs) || terminationGraceMs <= 0) { throw new Error("Rebuild worker termination grace must be a positive integer."); } - const dedicatedProcessGroup = process.platform !== "win32"; + assertWorkerPlatformSupported(process.platform); + const dedicatedProcessGroup = true; const child = spawn(process.execPath, [WORKER_PATH], { detached: dedicatedProcessGroup, env: rebuildWorkerEnv(gatewayPort), @@ -289,6 +299,7 @@ async function runWorker( } export const rebuildOwningRegistryDependencies: RebuildOwningRegistryDependencies = { + assertWorkerPlatformSupported, findSandbox: findSandboxAcrossGatewayRoots, findRecoveryRoot: findRebuildRecoveryStorageRoot, isHostFenceHeld: isCurrentPortableHostFenceHeld, diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index 7bd4b0d8340..7adf1ec983e 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -83,7 +83,26 @@ function writeBlockingOpenShell(home: string, descendantMarker: string): string return executable; } -function writeSiblingRegistry(home: string): void { +function writeCredentialProbeOpenShell(home: string, marker: string): string { + const executable = path.join(home, "credential-probe-openshell.cjs"); + fs.writeFileSync( + executable, + [ + "#!/usr/bin/env node", + 'const fs = require("node:fs");', + `fs.writeFileSync(${JSON.stringify(marker)}, String(process.ppid));`, + 'process.on("SIGTERM", () => {});', + "setInterval(() => {}, 1000);", + ].join("\n"), + { mode: 0o755 }, + ); + return executable; +} + +function writeSiblingRegistry( + home: string, + entryOverrides: Readonly> = {}, +): void { const stateRoot = path.join(home, ".nemoclaw", "gateways", "9000"); fs.mkdirSync(stateRoot, { recursive: true, mode: 0o700 }); fs.writeFileSync( @@ -99,6 +118,7 @@ function writeSiblingRegistry(home: string): void { dashboardPort: 18_789, gatewayName: "nemoclaw-9000", gatewayPort: 9000, + ...entryOverrides, }, }, })}\n`, @@ -150,6 +170,64 @@ describe("compiled rebuild owning-registry worker", () => { ).rejects.toThrow(); }); + it("rejects delegated worker startup on unsupported native Windows", () => { + expect(() => rebuildOwningRegistryDependencies.assertWorkerPlatformSupported("win32")).toThrow( + "Delegated owning-registry rebuild work is unsupported on native Windows. Run NemoClaw inside WSL.", + ); + }); + + it.runIf(process.platform === "linux")( + "forwards only allowlisted credentials into the delegated rebuild consumer", + async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-worker-credential-")); + const marker = path.join(home, "credential-probe.json"); + let worker: Promise | undefined; + try { + const recoveryManifest = writeRecoveryFixture(home); + writeSiblingRegistry(home, { + provider: "build", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + }); + vi.stubEnv("HOME", home); + vi.stubEnv("NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "1"); + vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", writeCredentialProbeOpenShell(home, marker)); + vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "nvapi-worker-test-value"); + vi.stubEnv("UNRELATED_REBUILD_SECRET", "must-not-cross-worker-boundary"); + + worker = rebuildOwningRegistryDependencies.runWorker( + { + operation: "rebuild", + sandboxName: "alpha", + options: { yes: true }, + executionOptions: { + recoveryManifest, + allowLegacyManagedImageRecovery: true, + }, + }, + 9000, + { timeoutMs: 3_000, terminationGraceMs: 100 }, + ); + + await vi.waitFor(() => expect(fs.existsSync(marker)).toBe(true), { timeout: 2_000 }); + const workerPid = Number(fs.readFileSync(marker, "utf8")); + const workerEnvironment = fs + .readFileSync(`/proc/${String(workerPid)}/environ`, "utf8") + .split("\0"); + + expect(workerEnvironment).toContain("NVIDIA_INFERENCE_API_KEY=nvapi-worker-test-value"); + expect(workerEnvironment).not.toContain( + "UNRELATED_REBUILD_SECRET=must-not-cross-worker-boundary", + ); + await expect(worker).rejects.toThrow( + "The worker was terminated, but the operation outcome is unknown.", + ); + } finally { + await worker?.catch(() => undefined); + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); + it("binds a valid rebuild descriptor to the selected sibling registry root", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-worker-sibling-root-")); try { From e1fc2d3beebb62d8adfa477372744861eedf7327 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 18 Sep 2026 10:39:13 -0700 Subject: [PATCH 33/44] fix(lifecycle): preserve cross-root authority Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/destroy-cross-root.test.ts | 43 +++++++++++++++++++ src/lib/actions/sandbox/destroy.ts | 3 +- .../sandbox/rebuild-gateway-drift.test.ts | 42 ++++++++++++++++++ .../sandbox/rebuild/owning-registry.ts | 8 +++- 4 files changed, 94 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/sandbox/destroy-cross-root.test.ts b/src/lib/actions/sandbox/destroy-cross-root.test.ts index 3b66dcb453d..9c9cba8a7a8 100644 --- a/src/lib/actions/sandbox/destroy-cross-root.test.ts +++ b/src/lib/actions/sandbox/destroy-cross-root.test.ts @@ -70,4 +70,47 @@ describe("destroySandbox cross-root registry authority", () => { ); expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); }); + + it("preserves the gateway when another sibling-root sandbox remains", async () => { + const registryDir = path.join(home, ".nemoclaw", "gateways", "8245"); + const registryFile = path.join(registryDir, "sandboxes.json"); + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync( + registryFile, + JSON.stringify({ + defaultSandbox: "alpha", + defaultSelectionRevision: 1, + sandboxes: { + alpha: { + name: "alpha", + agent: "openclaw", + provider: "ollama-local", + model: "nvidia/nemotron", + gatewayName: "nemoclaw-8245", + gatewayPort: 8245, + }, + beta: { + name: "beta", + agent: "openclaw", + provider: "ollama-local", + model: "nvidia/nemotron", + gatewayName: "nemoclaw-8245", + gatewayPort: 8245, + }, + }, + }), + ); + const harness = createDestroyHarness(); + + await expect( + harness.destroySandbox("alpha", { yes: true, cleanupGateway: true }), + ).resolves.toBeUndefined(); + + expect(JSON.parse(fs.readFileSync(registryFile, "utf8"))).toMatchObject({ + defaultSandbox: "beta", + sandboxes: { beta: { name: "beta" } }, + }); + expect(harness.cleanupGatewaySpy).not.toHaveBeenCalled(); + expect(harness.removeSandboxSpy).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 9d13aa7297c..0803fae8b02 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -1253,7 +1253,7 @@ async function destroySandboxUnlocked( const cleanupDecision = deleteSucceededOrAlreadyGone && registryEntryAbsent && - registry.listSandboxes().sandboxes.length === 0 + listRegisteredSandboxes().sandboxes.length === 0 ? resolveDestroyGatewayCleanupDecision(normalized, { nonInteractive: isDestroyNonInteractiveEnv(), platform: process.platform, @@ -1272,6 +1272,7 @@ async function destroySandboxUnlocked( }, { ...deps.finalGatewayCleanup, + listSandboxes: listRegisteredSandboxes, ...(cleanupCaptureOpenshell ? { captureOpenshell: cleanupCaptureOpenshell } : {}), }, ); diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index bd05040ba50..46e4515855d 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -532,6 +532,48 @@ describe("rebuild owning registry routing", () => { } }); + it("rejects a recovery marker whose gateway port differs from its state root", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recovery-root-port-")); + const transactionId = "11111111-1111-4111-8111-111111111111"; + const timestamp = "2026-09-17T00-00-00-000Z"; + const backupPath = path.join( + home, + ".nemoclaw", + "gateways", + "9000", + "rebuild-backups", + "alpha", + timestamp, + ); + const recoveryFile = path.join(backupPath, ".nemoclaw-rebuild-recovery.json"); + try { + fs.mkdirSync(backupPath, { recursive: true }); + fs.writeFileSync( + recoveryFile, + `${JSON.stringify({ + schemaVersion: 3, + transactionId, + sandboxName: "alpha", + backupTimestamp: timestamp, + gatewayName: "nemoclaw-9001", + gatewayPort: 9001, + phase: "restore", + })}\n`, + { mode: 0o600 }, + ); + + expect(() => + findRebuildRecoveryStorageRoot( + { sandboxName: "alpha", transactionId, confirmDataRecovered: true }, + home, + ), + ).toThrow("gateway port 9001 does not match state root port 9000"); + expect(fs.existsSync(recoveryFile)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("rejects traversal-shaped recovery names before reading gateway roots", () => { const readDirectory = vi.spyOn(fs, "readdirSync"); diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index c1937ce9e44..ea669f29698 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -333,7 +333,13 @@ export function findRebuildRecoveryStorageRoot( for (const entry of entries) { if (!entry.isDirectory() || entry.isSymbolicLink()) continue; const backupPath = path.join(sandboxBackupRoot, entry.name); - if (!readRebuildRecoveryRoute(input, backupPath)) continue; + const route = readRebuildRecoveryRoute(input, backupPath); + if (!route) continue; + if (route.gatewayPort !== state.gatewayPort) { + throw new Error( + `Rebuild recovery gateway port ${String(route.gatewayPort)} does not match state root port ${String(state.gatewayPort)}. Recovery remains at '${backupPath}'.`, + ); + } matches.push({ backupPath, gatewayPort: state.gatewayPort, From e016370f4abe8db9e2ce3adfb3a7410c08307581 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Fri, 18 Sep 2026 13:46:52 -0700 Subject: [PATCH 34/44] fix(rebuild): bind recovery marker to gateway name Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild-gateway-drift.test.ts | 101 +++++++++++------- .../sandbox/rebuild/owning-registry.ts | 7 ++ 2 files changed, 68 insertions(+), 40 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 46e4515855d..51c9ab929ac 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -22,6 +22,7 @@ import { runRebuildGatewayIntentPreflight, } from "./rebuild-preflight-guards"; import { + delegateRecoveryRetirementToOwningRegistry, delegateRebuildToOwningRegistry, findRebuildRecoveryStorageRoot, rebuildOwningRegistryDependencies, @@ -532,47 +533,67 @@ describe("rebuild owning registry routing", () => { } }); - it("rejects a recovery marker whose gateway port differs from its state root", () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recovery-root-port-")); - const transactionId = "11111111-1111-4111-8111-111111111111"; - const timestamp = "2026-09-17T00-00-00-000Z"; - const backupPath = path.join( - home, - ".nemoclaw", - "gateways", - "9000", - "rebuild-backups", - "alpha", - timestamp, - ); - const recoveryFile = path.join(backupPath, ".nemoclaw-rebuild-recovery.json"); - try { - fs.mkdirSync(backupPath, { recursive: true }); - fs.writeFileSync( - recoveryFile, - `${JSON.stringify({ - schemaVersion: 3, - transactionId, - sandboxName: "alpha", - backupTimestamp: timestamp, - gatewayName: "nemoclaw-9001", - gatewayPort: 9001, - phase: "restore", - })}\n`, - { mode: 0o600 }, + it.each([ + { + description: "gateway port differs from its state root", + gatewayName: "nemoclaw-9001", + gatewayPort: 9001, + expected: "gateway port 9001 does not match state root port 9000", + }, + { + description: "gateway name differs from its state root", + gatewayName: "nemoclaw-9001", + gatewayPort: 9000, + expected: "gateway name 'nemoclaw-9001' does not match state root gateway 'nemoclaw-9000'", + }, + ])( + "rejects a recovery marker whose $description before worker delegation", + async ({ gatewayName, gatewayPort, expected }) => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recovery-root-port-")); + const transactionId = "11111111-1111-4111-8111-111111111111"; + const timestamp = "2026-09-17T00-00-00-000Z"; + const backupPath = path.join( + home, + ".nemoclaw", + "gateways", + "9000", + "rebuild-backups", + "alpha", + timestamp, ); - - expect(() => - findRebuildRecoveryStorageRoot( - { sandboxName: "alpha", transactionId, confirmDataRecovered: true }, - home, - ), - ).toThrow("gateway port 9001 does not match state root port 9000"); - expect(fs.existsSync(recoveryFile)).toBe(true); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } - }); + const recoveryFile = path.join(backupPath, ".nemoclaw-rebuild-recovery.json"); + vi.spyOn(rebuildOwningRegistryDependencies, "isHostFenceHeld").mockReturnValue(false); + const runWorker = vi.spyOn(rebuildOwningRegistryDependencies, "runWorker"); + try { + fs.mkdirSync(backupPath, { recursive: true }); + fs.writeFileSync( + recoveryFile, + `${JSON.stringify({ + schemaVersion: 3, + transactionId, + sandboxName: "alpha", + backupTimestamp: timestamp, + gatewayName, + gatewayPort, + phase: "restore", + })}\n`, + { mode: 0o600 }, + ); + + await expect( + delegateRecoveryRetirementToOwningRegistry( + { sandboxName: "alpha", transactionId, confirmDataRecovered: true }, + home, + path.join(home, ".nemoclaw", "sandboxes.json"), + ), + ).rejects.toThrow(expected); + expect(runWorker).not.toHaveBeenCalled(); + expect(fs.existsSync(recoveryFile)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); it("rejects traversal-shaped recovery names before reading gateway roots", () => { const readDirectory = vi.spyOn(fs, "readdirSync"); diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index ea669f29698..fe674c37b5e 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -7,6 +7,7 @@ import path from "node:path"; import type { Readable } from "node:stream"; import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; +import { resolveGatewayName } from "../../../gateway-runtime-action"; import { snapshotKnownCredentialEnv } from "../../../onboard/credential-env"; import { isValidName } from "../../../sandbox-name-contract"; import { assertGatewayStatePathSafe, listGatewayStateRoots } from "../../../state/gateway-registry"; @@ -340,6 +341,12 @@ export function findRebuildRecoveryStorageRoot( `Rebuild recovery gateway port ${String(route.gatewayPort)} does not match state root port ${String(state.gatewayPort)}. Recovery remains at '${backupPath}'.`, ); } + const stateGatewayName = resolveGatewayName(state.gatewayPort); + if (route.gatewayName !== stateGatewayName) { + throw new Error( + `Rebuild recovery gateway name '${route.gatewayName}' does not match state root gateway '${stateGatewayName}'. Recovery remains at '${backupPath}'.`, + ); + } matches.push({ backupPath, gatewayPort: state.gatewayPort, From eb20e4b03ce099dc6a285a7a68492dc857f164b3 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 21 Sep 2026 11:13:02 -0700 Subject: [PATCH 35/44] fix: harden cross-root rebuild follow-up --- .../sandbox/rebuild-gateway-drift.test.ts | 24 ++++++ .../sandbox/rebuild/owning-registry.ts | 74 ++++++++++++++++--- .../status-snapshot-route-drift.test.ts | 29 ++++++++ src/lib/actions/sandbox/status-snapshot.ts | 2 +- src/lib/policy/index.ts | 35 ++++++--- .../rebuild-owning-registry-worker.test.ts | 70 ++++++++++++++++++ .../policy-channel-agent-resolution.test.ts | 67 +++++++++++++++++ 7 files changed, 277 insertions(+), 24 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 1833ee168e5..f5071d6ce8f 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -462,6 +462,30 @@ describe("rebuild owning registry routing", () => { expect(runWorker).not.toHaveBeenCalled(); }); + it("refuses to prompt inside a detached sibling-root rebuild worker", async () => { + const entry = makeSandboxEntry("nemoclaw-9000", 9000); + vi.spyOn(rebuildOwningRegistryDependencies, "findSandbox").mockReturnValue({ + entry, + gatewayPort: 9000, + registryGatewayPort: 9000, + registryFile: "/home/test/.nemoclaw/gateways/9000/sandboxes.json", + }); + vi.spyOn(rebuildOwningRegistryDependencies, "isHostFenceHeld").mockReturnValue(false); + const runWorker = vi.spyOn(rebuildOwningRegistryDependencies, "runWorker"); + + await expect( + delegateRebuildToOwningRegistry( + { sandboxName: "alpha", options: {}, executionOptions: {} }, + "/home/test", + "/home/test/.nemoclaw/sandboxes.json", + ), + ).rejects.toThrow( + "Cannot transfer an interactive rebuild for 'alpha' to its owning gateway registry. Re-run with '--yes' or '--force'.", + ); + + expect(runWorker).not.toHaveBeenCalled(); + }); + it("rejects duplicate exact recovery records across gateway roots", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recovery-roots-")); const transactionId = "11111111-1111-4111-8111-111111111111"; diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index 67e5be3d453..b407a5cc473 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -194,6 +194,28 @@ async function settleWorkerPromises( } } +async function terminateWorkerProcessGroup( + child: ChildProcess, + dedicatedProcessGroup: boolean, + terminationGraceMs: number, +): Promise { + signalWorkerProcessGroup(child, dedicatedProcessGroup, "SIGTERM"); + let workerReaped = await waitForWorkerProcessGroupExit( + child, + dedicatedProcessGroup, + terminationGraceMs, + ); + if (!workerReaped) { + signalWorkerProcessGroup(child, dedicatedProcessGroup, "SIGKILL"); + workerReaped = await waitForWorkerProcessGroupExit( + child, + dedicatedProcessGroup, + REBUILD_WORKER_REAP_TIMEOUT_MS, + ); + } + return workerReaped; +} + async function runWorker( input: OwningRegistryWorkerInput, gatewayPort: number, @@ -242,37 +264,60 @@ async function runWorker( const timeout = new Promise>((resolve) => { deadline = setTimeout(() => resolve({ kind: "timeout" }), timeoutMs); }); + let resolveInterrupted: + | ((outcome: Readonly<{ kind: "interrupted"; signal: NodeJS.Signals }>) => void) + | undefined; + const interrupted = new Promise>( + (resolve) => { + resolveInterrupted = resolve; + }, + ); + const onSigint = () => resolveInterrupted?.({ kind: "interrupted", signal: "SIGINT" }); + const onSigterm = () => resolveInterrupted?.({ kind: "interrupted", signal: "SIGTERM" }); + process.on("SIGINT", onSigint); + process.on("SIGTERM", onSigterm); let outcome: | Readonly<{ kind: "completed"; value: Awaited; }> - | Readonly<{ kind: "timeout" }>; + | Readonly<{ kind: "timeout" }> + | Readonly<{ kind: "interrupted"; signal: NodeJS.Signals }> + | undefined; try { outcome = await Promise.race([ completion.then((value) => ({ kind: "completed" as const, value })), timeout, + interrupted, ]); } finally { if (deadline) clearTimeout(deadline); + if (outcome?.kind !== "interrupted") { + process.removeListener("SIGINT", onSigint); + process.removeListener("SIGTERM", onSigterm); + } } - if (outcome.kind === "timeout") { - signalWorkerProcessGroup(child, dedicatedProcessGroup, "SIGTERM"); - let workerReaped = await waitForWorkerProcessGroupExit( + if (!outcome) throw new Error("Rebuild in the owning gateway registry did not complete."); + if (outcome.kind !== "completed") { + const workerReaped = await terminateWorkerProcessGroup( child, dedicatedProcessGroup, terminationGraceMs, ); - if (!workerReaped) { - signalWorkerProcessGroup(child, dedicatedProcessGroup, "SIGKILL"); - workerReaped = await waitForWorkerProcessGroupExit( - child, - dedicatedProcessGroup, - REBUILD_WORKER_REAP_TIMEOUT_MS, - ); - } await settleWorkerPromises([inputWritten, exited, result], REBUILD_WORKER_REAP_TIMEOUT_MS); const operation = input.operation === "rebuild" ? "rebuild" : "recovery retirement"; + if (outcome.kind === "interrupted") { + if (!workerReaped) { + const workerPid = typeof child.pid === "number" ? String(child.pid) : "unavailable"; + console.error( + `Delegated ${operation} for sandbox '${input.sandboxName}' was interrupted, but termination is unconfirmed for worker PID ${workerPid}. The operation outcome is unknown; inspect that worker, the sandbox, and retained recovery state before retrying.`, + ); + } + process.removeListener("SIGINT", onSigint); + process.removeListener("SIGTERM", onSigterm); + process.kill(process.pid, outcome.signal); + throw new Error(`Delegated ${operation} was interrupted by ${outcome.signal}.`); + } if (!workerReaped) { const workerPid = typeof child.pid === "number" ? String(child.pid) : "unavailable"; throw new Error( @@ -385,6 +430,11 @@ export async function delegateRebuildToOwningRegistry( `Cannot transfer rebuild for '${input.sandboxName}' while another lifecycle command owns the host fence. Run 'nemoclaw ${input.sandboxName} rebuild' directly.`, ); } + if (!input.options.yes && !input.options.force) { + throw new Error( + `Cannot transfer an interactive rebuild for '${input.sandboxName}' to its owning gateway registry. Re-run with '--yes' or '--force'.`, + ); + } await rebuildOwningRegistryDependencies.runWorker( { operation: "rebuild", ...input }, hit.registryGatewayPort, diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index a6269873f0e..ac2ece386ac 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -250,6 +250,35 @@ describe("collectSandboxStatusSnapshot route drift", () => { expect(report.routeDrift).toMatchObject({ canConnect: false }); }); + + it("reads policies with the sandbox entry resolved from its owning gateway root", async () => { + const target: SandboxEntry = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw-9090", + gatewayPort: 9090, + provider: "compatible-endpoint", + model: "recorded/model", + }; + const options = snapshotDeps(target); + const { getSandbox: _getSandbox, ...deps } = options.deps; + const getGatewayPresets = vi.fn(async () => ["npm"]); + + const report = await getSandboxStatusReport("alpha", { + ...deps, + findSandboxAcrossGatewayRoots: () => ({ + entry: target, + gatewayPort: 9090, + registryGatewayPort: 9090, + registryFile: "/test/.nemoclaw/gateways/9090/sandboxes.json", + }), + getGatewayPresets, + }); + + expect(report.policies).toEqual(["npm"]); + expect(report.policiesAvailable).toBe(true); + expect(getGatewayPresets).toHaveBeenCalledWith("alpha", undefined, target); + }); }); describe("getSandboxStatusReport llama.cpp attribution on drift (#10256)", () => { diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index b1a554842b7..45384e9faf9 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -853,7 +853,7 @@ async function buildSandboxStatusReport( // without that boundary report policy availability honestly instead of // reaching into policy state through a second orchestration path. const livePolicies = - sb && deps.getGatewayPresets ? await deps.getGatewayPresets(sandboxName) : []; + sb && deps.getGatewayPresets ? await deps.getGatewayPresets(sandboxName, undefined, sb) : []; const agent = resolveSandboxStatusAgent(sb?.agent || "openclaw"); return { schemaVersion: 1, diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index 9893c03dfad..c1e7754ab66 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -120,6 +120,8 @@ type MergePresetNamesOptions = { type SandboxPresetLoadOptions = { includeMessagingCredentialBindings?: boolean; messagingConfig?: MessagingPolicyConfig | null; + sandbox?: registry.SandboxEntry | null; + gatewayName?: string; }; type SetupPolicyPresetSupportOptions = { @@ -325,8 +327,9 @@ function liveCustomPresetContentFromPolicy(current: string, presetName: string): async function liveCustomPresetContent( sandboxName: string, presetName: string, + gatewayName?: string, ): Promise { - const current = await readCurrentSandboxPolicy(sandboxName); + const current = await readCurrentSandboxPolicy(sandboxName, gatewayName); return current ? liveCustomPresetContentFromPolicy(current, presetName) : null; } @@ -365,9 +368,11 @@ function loadAgentPresetContent( sandboxName: string, presetName: string, builtinPresetContent: string, + sandboxOverride?: registry.SandboxEntry | null, ): string | null { try { - const sandbox = registry.getSandbox(sandboxName); + const sandbox = + sandboxOverride === undefined ? registry.getSandbox(sandboxName) : sandboxOverride; if (!sandbox?.agent) return null; const agent = loadAgent(sandbox.agent); @@ -407,7 +412,8 @@ async function loadPresetForSandbox( let configuredMessagingChannels: string[] = []; let messagingConfig = options.messagingConfig; try { - const sandbox = registry.getSandbox(sandboxName); + const sandbox = + options.sandbox === undefined ? registry.getSandbox(sandboxName) : options.sandbox; sandboxAgent = sandbox?.agent ?? null; configuredMessagingChannels = getCredentialBoundMessagingChannelsFromEntry(sandbox); if (messagingConfig === undefined) { @@ -440,9 +446,12 @@ async function loadPresetForSandbox( if (isMessagingChannelPolicyPreset(presetName)) return null; const builtinPresetContent = loadCentralPreset(presetName, { reportMissing: false }); - if (!builtinPresetContent) return await liveCustomPresetContent(sandboxName, presetName); + if (!builtinPresetContent) { + return await liveCustomPresetContent(sandboxName, presetName, options.gatewayName); + } const resolvedPresetContent = - loadAgentPresetContent(sandboxName, presetName, builtinPresetContent) || builtinPresetContent; + loadAgentPresetContent(sandboxName, presetName, builtinPresetContent, options.sandbox) || + builtinPresetContent; return presetName === "outlook" && sandboxAgent !== "hermes" && configuredMessagingChannels.includes("teams") @@ -2741,8 +2750,8 @@ async function getAppliedPresets(sandboxName: string, timeoutMs?: number): Promi return (await getGatewayPresets(sandboxName, timeoutMs)) ?? []; } -async function listCustomPresets(sandboxName: string): Promise { - const current = await readCurrentSandboxPolicy(sandboxName); +async function listCustomPresets(sandboxName: string, gatewayName?: string): Promise { + const current = await readCurrentSandboxPolicy(sandboxName, gatewayName); if (!current) return []; const parsed = YAML.parse(current); if (!isPolicyDocument(parsed) || !isPolicyObject(parsed.network_policies)) return []; @@ -2787,11 +2796,12 @@ async function customPresetOwnsNetworkPolicyKey( async function getGatewayPresets( sandboxName: string, timeoutMs?: number, + sandboxOverride?: registry.SandboxEntry | null, ): Promise { - let sandbox: ReturnType; + let sandbox: registry.SandboxEntry | null; let gatewayName: string; try { - sandbox = registry.getSandbox(sandboxName); + sandbox = sandboxOverride === undefined ? registry.getSandbox(sandboxName) : sandboxOverride; if (!sandbox) return null; gatewayName = resolveSandboxGatewayName(sandbox); } catch { @@ -2808,7 +2818,7 @@ async function getGatewayPresets( for (const preset of listPresets({ agent: sandboxAgent })) { sources.push({ name: preset.name, - content: await loadPresetForSandbox(sandboxName, preset.name), + content: await loadPresetForSandbox(sandboxName, preset.name, { sandbox, gatewayName }), }); } const builtins = inspectGatewayPresetNames({ @@ -2819,7 +2829,10 @@ async function getGatewayPresets( }); if (builtins === null) return null; return [ - ...new Set([...builtins, ...(await listCustomPresets(sandboxName)).map((entry) => entry.name)]), + ...new Set([ + ...builtins, + ...(await listCustomPresets(sandboxName, gatewayName)).map((entry) => entry.name), + ]), ]; } diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index 7adf1ec983e..7c2262e7b8e 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { createHash } from "node:crypto"; +import { spawn } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -9,6 +10,7 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { rebuildOwningRegistryDependencies } from "../../dist/lib/actions/sandbox/rebuild/owning-registry"; +import { testTimeout } from "../helpers/timeouts"; const TRANSACTION_ID = "11111111-1111-4111-8111-111111111111"; const TIMESTAMP = "2026-09-17T00-00-00-000Z"; @@ -322,6 +324,74 @@ describe("compiled rebuild owning-registry worker", () => { } }); + it( + "reaps a delegated worker process group before preserving parent SIGINT semantics", + async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-worker-sigint-")); + const descendantMarker = path.join(home, "descendant.pid"); + const modulePath = path.join( + import.meta.dirname, + "../../dist/lib/actions/sandbox/rebuild/owning-registry.js", + ); + let descendantPid: number | undefined; + writeRecoveryFixture(home); + const harness = spawn( + process.execPath, + [ + "-e", + [ + `const { rebuildOwningRegistryDependencies } = require(${JSON.stringify(modulePath)});`, + "void rebuildOwningRegistryDependencies.runWorker(", + ` { operation: "retire-recovery", sandboxName: "alpha", transactionId: ${JSON.stringify(TRANSACTION_ID)}, confirmDataRecovered: true },`, + " 9000,", + " { timeoutMs: 30000, terminationGraceMs: 100 },", + ").catch((error) => { console.error(error); process.exitCode = 1; });", + ].join("\n"), + ], + { + env: { + ...process.env, + HOME: home, + NEMOCLAW_OPENSHELL_BIN: writeBlockingOpenShell(home, descendantMarker), + }, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + const output: Buffer[] = []; + harness.stdout.on("data", (chunk: Buffer) => output.push(chunk)); + harness.stderr.on("data", (chunk: Buffer) => output.push(chunk)); + const exited = new Promise>( + (resolve, reject) => { + harness.once("error", reject); + harness.once("exit", (code, signal) => resolve({ code, signal })); + }, + ); + try { + await vi.waitFor(() => expect(fs.existsSync(descendantMarker)).toBe(true), { + timeout: testTimeout(20_000), + }); + descendantPid = Number(fs.readFileSync(descendantMarker, "utf8")); + + expect(harness.kill("SIGINT")).toBe(true); + await expect(exited).resolves.toEqual({ code: null, signal: "SIGINT" }); + expect(() => process.kill(descendantPid!, 0)).toThrow( + expect.objectContaining({ code: "ESRCH" }), + ); + } catch (error) { + throw new Error(`${String(error)}\n${Buffer.concat(output).toString("utf8")}`); + } finally { + harness.kill("SIGKILL"); + try { + process.kill(descendantPid as number, "SIGKILL"); + } catch { + // The delegated worker cleanup succeeded or the marker was never written. + } + fs.rmSync(home, { recursive: true, force: true }); + } + }, + testTimeout(30_000), + ); + it("reports an unreaped worker as potentially active", async () => { const kill = process.kill.bind(process); vi.spyOn(process, "kill").mockImplementation((pid, signal) => diff --git a/test/runtime/policy/policy-channel-agent-resolution.test.ts b/test/runtime/policy/policy-channel-agent-resolution.test.ts index 7efc000d05c..e16581cdc42 100644 --- a/test/runtime/policy/policy-channel-agent-resolution.test.ts +++ b/test/runtime/policy/policy-channel-agent-resolution.test.ts @@ -180,6 +180,73 @@ process.stdout.write("__RESULT__" + JSON.stringify({ gatewayPresets })); const payload = JSON.parse(result.stdout.split("__RESULT__")[1].trim()); expect(payload.gatewayPresets).toEqual(["npm"]); }); + + it("reads live presets through the gateway registry root that owns the sandbox", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-sibling-root-")); + const openshellPath = path.join(tmpDir, "openshell"); + const openshellLog = path.join(tmpDir, "openshell.log"); + const stateRoot = path.join(tmpDir, ".nemoclaw", "gateways", "9000"); + fs.mkdirSync(stateRoot, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(stateRoot, "sandboxes.json"), + `${JSON.stringify({ + defaultSandbox: "sibling-sandbox", + sandboxes: { + "sibling-sandbox": { + name: "sibling-sandbox", + agent: "openclaw", + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, + }, + }, + })}\n`, + { mode: 0o600 }, + ); + fs.writeFileSync( + openshellPath, + [ + "#!/usr/bin/env bash", + `printf '%s\\n' "$*" >> ${JSON.stringify(openshellLog)}`, + "cat <<'EOF'", + "Version: 1", + "---", + "version: 1", + "network_policies:", + " npm_yarn:", + " endpoints: []", + "EOF", + "", + ].join("\n"), + ); + fs.chmodSync(openshellPath, 0o755); + const script = String.raw` +(async () => { +const policies = require(${POLICIES_PATH}); +const gatewayPresets = await policies.getGatewayPresets("sibling-sandbox", undefined, { + name: "sibling-sandbox", + agent: "openclaw", + gatewayName: "nemoclaw-9000", + gatewayPort: 9000, +}); +process.stdout.write("__RESULT__" + JSON.stringify({ gatewayPresets })); + +})().catch((error) => { console.error(error); process.exitCode = 1; }); +`; + const result = spawnSync(process.execPath, [...SOURCE_NODE_ARGS, "-e", script], { + cwd: REPO_ROOT, + encoding: "utf-8", + env: { ...process.env, HOME: tmpDir, NEMOCLAW_OPENSHELL_BIN: openshellPath }, + }); + const calls = fs.readFileSync(openshellLog, "utf8"); + fs.rmSync(tmpDir, { recursive: true, force: true }); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout.split("__RESULT__")[1].trim())).toEqual({ + gatewayPresets: ["npm"], + }); + expect(calls).toContain("policy get -g nemoclaw-9000 --full sibling-sandbox"); + }); + it("setup policy preset catalog omits unsupported Deep Agents messaging policies (#6185)", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-setup-agent-")); const script = String.raw` From 48427b38a5ce5b293ad4d1e09fe3a967c446baf4 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 21 Sep 2026 13:42:57 -0700 Subject: [PATCH 36/44] fix(rebuild): install signal handlers before worker spawn Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild/owning-registry.ts | 183 +++++++++--------- .../policy-channel-agent-resolution.test.ts | 4 +- 2 files changed, 94 insertions(+), 93 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index b407a5cc473..f951db74ca3 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -231,39 +231,6 @@ async function runWorker( } assertWorkerPlatformSupported(process.platform); const dedicatedProcessGroup = true; - const child = spawn(process.execPath, [WORKER_PATH], { - detached: dedicatedProcessGroup, - env: rebuildWorkerEnv(gatewayPort), - stdio: ["inherit", "inherit", "inherit", "pipe", "pipe"], - }); - const inputStream = child.stdio[3]; - if (!inputStream || !("end" in inputStream)) { - child.kill(); - throw new Error("Cannot route rebuild input to the owning gateway registry."); - } - const inputWritten = new Promise((resolve, reject) => { - inputStream.once("error", reject); - inputStream.end(JSON.stringify(input), resolve); - }); - const resultStream = child.stdio[4] as Readable | null; - if (!resultStream) { - child.kill(); - throw new Error("Cannot read the rebuild worker result."); - } - const result = readWorkerResult(resultStream); - const exited = new Promise>( - (resolve, reject) => { - child.once("error", reject); - child.once("exit", (code, signal) => { - resolve({ code, signal }); - }); - }, - ); - const completion = Promise.all([inputWritten, exited, result] as const); - let deadline: NodeJS.Timeout | undefined; - const timeout = new Promise>((resolve) => { - deadline = setTimeout(() => resolve({ kind: "timeout" }), timeoutMs); - }); let resolveInterrupted: | ((outcome: Readonly<{ kind: "interrupted"; signal: NodeJS.Signals }>) => void) | undefined; @@ -276,75 +243,109 @@ async function runWorker( const onSigterm = () => resolveInterrupted?.({ kind: "interrupted", signal: "SIGTERM" }); process.on("SIGINT", onSigint); process.on("SIGTERM", onSigterm); - let outcome: - | Readonly<{ - kind: "completed"; - value: Awaited; - }> - | Readonly<{ kind: "timeout" }> - | Readonly<{ kind: "interrupted"; signal: NodeJS.Signals }> - | undefined; try { - outcome = await Promise.race([ - completion.then((value) => ({ kind: "completed" as const, value })), - timeout, - interrupted, - ]); - } finally { - if (deadline) clearTimeout(deadline); - if (outcome?.kind !== "interrupted") { - process.removeListener("SIGINT", onSigint); - process.removeListener("SIGTERM", onSigterm); + const child = spawn(process.execPath, [WORKER_PATH], { + detached: dedicatedProcessGroup, + env: rebuildWorkerEnv(gatewayPort), + stdio: ["inherit", "inherit", "inherit", "pipe", "pipe"], + }); + const inputStream = child.stdio[3]; + if (!inputStream || !("end" in inputStream)) { + child.kill(); + throw new Error("Cannot route rebuild input to the owning gateway registry."); } - } - if (!outcome) throw new Error("Rebuild in the owning gateway registry did not complete."); - if (outcome.kind !== "completed") { - const workerReaped = await terminateWorkerProcessGroup( - child, - dedicatedProcessGroup, - terminationGraceMs, + const inputWritten = new Promise((resolve, reject) => { + inputStream.once("error", reject); + inputStream.end(JSON.stringify(input), resolve); + }); + const resultStream = child.stdio[4] as Readable | null; + if (!resultStream) { + child.kill(); + throw new Error("Cannot read the rebuild worker result."); + } + const result = readWorkerResult(resultStream); + const exited = new Promise>( + (resolve, reject) => { + child.once("error", reject); + child.once("exit", (code, signal) => { + resolve({ code, signal }); + }); + }, ); - await settleWorkerPromises([inputWritten, exited, result], REBUILD_WORKER_REAP_TIMEOUT_MS); - const operation = input.operation === "rebuild" ? "rebuild" : "recovery retirement"; - if (outcome.kind === "interrupted") { + const completion = Promise.all([inputWritten, exited, result] as const); + let deadline: NodeJS.Timeout | undefined; + const timeout = new Promise>((resolve) => { + deadline = setTimeout(() => resolve({ kind: "timeout" }), timeoutMs); + }); + let outcome: + | Readonly<{ + kind: "completed"; + value: Awaited; + }> + | Readonly<{ kind: "timeout" }> + | Readonly<{ kind: "interrupted"; signal: NodeJS.Signals }> + | undefined; + try { + outcome = await Promise.race([ + completion.then((value) => ({ kind: "completed" as const, value })), + timeout, + interrupted, + ]); + } finally { + if (deadline) clearTimeout(deadline); + } + if (!outcome) throw new Error("Rebuild in the owning gateway registry did not complete."); + if (outcome.kind !== "completed") { + const workerReaped = await terminateWorkerProcessGroup( + child, + dedicatedProcessGroup, + terminationGraceMs, + ); + await settleWorkerPromises([inputWritten, exited, result], REBUILD_WORKER_REAP_TIMEOUT_MS); + const operation = input.operation === "rebuild" ? "rebuild" : "recovery retirement"; + if (outcome.kind === "interrupted") { + if (!workerReaped) { + const workerPid = typeof child.pid === "number" ? String(child.pid) : "unavailable"; + console.error( + `Delegated ${operation} for sandbox '${input.sandboxName}' was interrupted, but termination is unconfirmed for worker PID ${workerPid}. The operation outcome is unknown; inspect that worker, the sandbox, and retained recovery state before retrying.`, + ); + } + process.removeListener("SIGINT", onSigint); + process.removeListener("SIGTERM", onSigterm); + process.kill(process.pid, outcome.signal); + throw new Error(`Delegated ${operation} was interrupted by ${outcome.signal}.`); + } if (!workerReaped) { const workerPid = typeof child.pid === "number" ? String(child.pid) : "unavailable"; - console.error( - `Delegated ${operation} for sandbox '${input.sandboxName}' was interrupted, but termination is unconfirmed for worker PID ${workerPid}. The operation outcome is unknown; inspect that worker, the sandbox, and retained recovery state before retrying.`, + throw new Error( + `Delegated ${operation} for sandbox '${input.sandboxName}' on owning gateway port ${String(gatewayPort)} exceeded its ${String(timeoutMs)} ms deadline. Termination is unconfirmed for worker PID ${workerPid}, so the worker or one of its descendants may still be active and the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect that worker, the sandbox, and recovery state before retrying.`, ); } - process.removeListener("SIGINT", onSigint); - process.removeListener("SIGTERM", onSigterm); - process.kill(process.pid, outcome.signal); - throw new Error(`Delegated ${operation} was interrupted by ${outcome.signal}.`); - } - if (!workerReaped) { - const workerPid = typeof child.pid === "number" ? String(child.pid) : "unavailable"; throw new Error( - `Delegated ${operation} for sandbox '${input.sandboxName}' on owning gateway port ${String(gatewayPort)} exceeded its ${String(timeoutMs)} ms deadline. Termination is unconfirmed for worker PID ${workerPid}, so the worker or one of its descendants may still be active and the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect that worker, the sandbox, and recovery state before retrying.`, + `Delegated ${operation} for sandbox '${input.sandboxName}' on owning gateway port ${String(gatewayPort)} exceeded its ${String(timeoutMs)} ms deadline. The worker was terminated, but the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect the sandbox and recovery state before retrying.`, ); } - throw new Error( - `Delegated ${operation} for sandbox '${input.sandboxName}' on owning gateway port ${String(gatewayPort)} exceeded its ${String(timeoutMs)} ms deadline. The worker was terminated, but the operation outcome is unknown. NemoClaw did not remove retained recovery state; inspect the sandbox and recovery state before retrying.`, - ); - } - const [, exit, workerResult] = outcome.value; - const resultMatchesRequest = - workerResult?.operation === input.operation && - workerResult.sandboxName === input.sandboxName && - workerResult.gatewayPort === gatewayPort; - if ( - exit.code === 0 && - exit.signal === null && - workerResult?.ok === true && - resultMatchesRequest - ) { - return; - } - if (workerResult?.ok === false && resultMatchesRequest && workerResult.message) { - throw new Error(workerResult.message, { cause: workerResult }); + const [, exit, workerResult] = outcome.value; + const resultMatchesRequest = + workerResult?.operation === input.operation && + workerResult.sandboxName === input.sandboxName && + workerResult.gatewayPort === gatewayPort; + if ( + exit.code === 0 && + exit.signal === null && + workerResult?.ok === true && + resultMatchesRequest + ) { + return; + } + if (workerResult?.ok === false && resultMatchesRequest && workerResult.message) { + throw new Error(workerResult.message, { cause: workerResult }); + } + throw new Error("Rebuild in the owning gateway registry did not complete successfully."); + } finally { + process.removeListener("SIGINT", onSigint); + process.removeListener("SIGTERM", onSigterm); } - throw new Error("Rebuild in the owning gateway registry did not complete successfully."); } export const rebuildOwningRegistryDependencies: RebuildOwningRegistryDependencies = { diff --git a/test/runtime/policy/policy-channel-agent-resolution.test.ts b/test/runtime/policy/policy-channel-agent-resolution.test.ts index e16581cdc42..e2c944e035a 100644 --- a/test/runtime/policy/policy-channel-agent-resolution.test.ts +++ b/test/runtime/policy/policy-channel-agent-resolution.test.ts @@ -221,7 +221,7 @@ process.stdout.write("__RESULT__" + JSON.stringify({ gatewayPresets })); fs.chmodSync(openshellPath, 0o755); const script = String.raw` (async () => { -const policies = require(${POLICIES_PATH}); +const policies = (await import(${POLICIES_PATH})).default; const gatewayPresets = await policies.getGatewayPresets("sibling-sandbox", undefined, { name: "sibling-sandbox", agent: "openclaw", @@ -237,10 +237,10 @@ process.stdout.write("__RESULT__" + JSON.stringify({ gatewayPresets })); encoding: "utf-8", env: { ...process.env, HOME: tmpDir, NEMOCLAW_OPENSHELL_BIN: openshellPath }, }); + expect(result.status, result.stderr).toBe(0); const calls = fs.readFileSync(openshellLog, "utf8"); fs.rmSync(tmpDir, { recursive: true, force: true }); - expect(result.status, result.stderr).toBe(0); expect(JSON.parse(result.stdout.split("__RESULT__")[1].trim())).toEqual({ gatewayPresets: ["npm"], }); From e0ed737d082923ec39956b9721464e3d93348458 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 21 Sep 2026 14:23:33 -0700 Subject: [PATCH 37/44] fix(rebuild): scope delegated worker credentials Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild-gateway-drift.test.ts | 9 +++- .../sandbox/rebuild/owning-registry.ts | 41 ++++++++++++++++--- src/lib/onboard/credential-env.test.ts | 17 +++++++- src/lib/onboard/credential-env.ts | 18 +++++++- .../rebuild-owning-registry-worker.test.ts | 8 +++- 5 files changed, 82 insertions(+), 11 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index f5071d6ce8f..8596a07889b 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -371,7 +371,10 @@ describe("rebuild owning registry routing", () => { }); it("delegates the complete rebuild transaction to a sibling registry root", async () => { - const entry = makeSandboxEntry("nemoclaw-9000", 9000); + const entry = { + ...makeSandboxEntry("nemoclaw-9000", 9000), + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + }; vi.spyOn(rebuildOwningRegistryDependencies, "findSandbox").mockReturnValue({ entry, gatewayPort: 9000, @@ -394,7 +397,9 @@ describe("rebuild owning registry routing", () => { rebuildSandbox(input.sandboxName, input.options, input.executionOptions), ).resolves.toBeUndefined(); - expect(runWorker).toHaveBeenCalledWith({ operation: "rebuild", ...input }, 9000); + expect(runWorker).toHaveBeenCalledWith({ operation: "rebuild", ...input }, 9000, { + credentialEnvNames: ["NVIDIA_INFERENCE_API_KEY"], + }); expect(readBaseRegistry).not.toHaveBeenCalled(); }); diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index f951db74ca3..92a5ba61a70 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -8,7 +8,8 @@ import type { Readable } from "node:stream"; import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; import { resolveGatewayName } from "../../../gateway-runtime-action"; -import { snapshotKnownCredentialEnv } from "../../../onboard/credential-env"; +import { webSearchEnvFor } from "../../../inference/web-search"; +import { snapshotCredentialEnv } from "../../../onboard/credential-env"; import { assertGatewayStatePathSafe, isValidName, @@ -17,6 +18,8 @@ import { import { isCurrentPortableHostFenceHeld } from "../../../state/portable-uninstall-retirement"; import { buildSubprocessEnv } from "../../../subprocess-env"; import { findSandboxAcrossGatewayRoots } from "../../../state/registry/cross-port"; +import { getMessagingPlanFromEntry } from "../../../state/registry-messaging"; +import type { SandboxEntry } from "../../../state/registry/types"; import type { RebuildSandboxExecutionOptions } from "../rebuild-prepared-recovery"; import { readRebuildRecoveryRoute } from "../rebuild-recreate-journal"; @@ -66,10 +69,16 @@ type RebuildOwningRegistryDependencies = { runWorker( input: OwningRegistryWorkerInput, gatewayPort: number, - options?: Readonly<{ terminationGraceMs?: number; timeoutMs?: number }>, + options?: RebuildWorkerOptions, ): Promise; }; +type RebuildWorkerOptions = Readonly<{ + credentialEnvNames?: readonly string[]; + terminationGraceMs?: number; + timeoutMs?: number; +}>; + const WORKER_PATH = path.join(__dirname, "owning-registry-worker.js"); const MAX_RECOVERY_BACKUP_ENTRIES = 1024; const MAX_WORKER_RESULT_BYTES = 64 * 1024; @@ -87,9 +96,12 @@ const REBUILD_ENV_NAMES = [ "NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH", ] as const; -function rebuildWorkerEnv(gatewayPort: number): Record { +function rebuildWorkerEnv( + gatewayPort: number, + credentialEnvNames: readonly string[], +): Record { const extra: Record = { - ...snapshotKnownCredentialEnv(), + ...snapshotCredentialEnv(credentialEnvNames), NEMOCLAW_GATEWAY_PORT: String(gatewayPort), }; for (const name of REBUILD_ENV_NAMES) { @@ -99,6 +111,22 @@ function rebuildWorkerEnv(gatewayPort: number): Record { return buildSubprocessEnv(extra); } +function rebuildCredentialEnvNames(entry: SandboxEntry): readonly string[] { + const names = new Set(); + if (entry.credentialEnv) names.add(entry.credentialEnv); + const webSearchProvider = + entry.webSearchProvider === "brave" || entry.webSearchProvider === "tavily" + ? entry.webSearchProvider + : entry.webSearchEnabled === true + ? "brave" + : null; + if (webSearchProvider) names.add(webSearchEnvFor(webSearchProvider)); + for (const binding of getMessagingPlanFromEntry(entry)?.credentialBindings ?? []) { + names.add(binding.providerEnvKey); + } + return [...names].sort(); +} + async function readWorkerResult(stream: Readable): Promise { const chunks: Buffer[] = []; let bytes = 0; @@ -219,7 +247,7 @@ async function terminateWorkerProcessGroup( async function runWorker( input: OwningRegistryWorkerInput, gatewayPort: number, - options: Readonly<{ terminationGraceMs?: number; timeoutMs?: number }> = {}, + options: RebuildWorkerOptions = {}, ): Promise { const timeoutMs = options.timeoutMs ?? REBUILD_WORKER_TIMEOUT_MS; if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) { @@ -246,7 +274,7 @@ async function runWorker( try { const child = spawn(process.execPath, [WORKER_PATH], { detached: dedicatedProcessGroup, - env: rebuildWorkerEnv(gatewayPort), + env: rebuildWorkerEnv(gatewayPort, options.credentialEnvNames ?? []), stdio: ["inherit", "inherit", "inherit", "pipe", "pipe"], }); const inputStream = child.stdio[3]; @@ -439,6 +467,7 @@ export async function delegateRebuildToOwningRegistry( await rebuildOwningRegistryDependencies.runWorker( { operation: "rebuild", ...input }, hit.registryGatewayPort, + { credentialEnvNames: rebuildCredentialEnvNames(hit.entry) }, ); return true; } diff --git a/src/lib/onboard/credential-env.test.ts b/src/lib/onboard/credential-env.test.ts index 803b5fe0fd0..61d8797f5d0 100644 --- a/src/lib/onboard/credential-env.test.ts +++ b/src/lib/onboard/credential-env.test.ts @@ -3,7 +3,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { hydrateCredentialEnv, snapshotKnownCredentialEnv } from "./credential-env"; +import { + hydrateCredentialEnv, + snapshotCredentialEnv, + snapshotKnownCredentialEnv, +} from "./credential-env"; afterEach(() => { vi.unstubAllEnvs(); @@ -21,6 +25,17 @@ describe("snapshotKnownCredentialEnv", () => { }); }); +describe("snapshotCredentialEnv", () => { + it("copies only selected known credentials", () => { + vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "nvapi-worker-test"); + vi.stubEnv("OPENAI_API_KEY", "openai-unrelated-test"); + + expect(snapshotCredentialEnv(["NVIDIA_INFERENCE_API_KEY", "UNRELATED_SECRET"])).toEqual({ + NVIDIA_INFERENCE_API_KEY: "nvapi-worker-test", + }); + }); +}); + describe("hydrateCredentialEnv", () => { it("returns null for empty env names", () => { expect(hydrateCredentialEnv(null)).toBeNull(); diff --git a/src/lib/onboard/credential-env.ts b/src/lib/onboard/credential-env.ts index 4305f62f1e6..d7c3d154b5a 100644 --- a/src/lib/onboard/credential-env.ts +++ b/src/lib/onboard/credential-env.ts @@ -1,13 +1,29 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { loadCredentials, resolveProviderCredential } from "../credentials/store"; +import { + KNOWN_CREDENTIAL_ENV_KEYS, + loadCredentials, + resolveProviderCredential, +} from "../credentials/store"; /** Snapshot only NemoClaw's allowlisted credentials for a trusted child process. */ export function snapshotKnownCredentialEnv(): Record { return loadCredentials(); } +/** Snapshot only the named known credentials for a scoped child process. */ +export function snapshotCredentialEnv(envNames: readonly string[]): Record { + const knownNames = new Set(KNOWN_CREDENTIAL_ENV_KEYS); + const snapshot: Record = {}; + for (const envName of new Set(envNames)) { + if (!knownNames.has(envName)) continue; + const value = resolveProviderCredential(envName); + if (value) snapshot[envName] = value; + } + return snapshot; +} + /** * Resolve and return a credential for host-side callers. Scoped overrides are * returned without exporting them to `process.env`. diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index 7c2262e7b8e..1eda956b536 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -194,6 +194,7 @@ describe("compiled rebuild owning-registry worker", () => { vi.stubEnv("NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", "1"); vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", writeCredentialProbeOpenShell(home, marker)); vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "nvapi-worker-test-value"); + vi.stubEnv("OPENAI_API_KEY", "openai-unrelated-test-value"); vi.stubEnv("UNRELATED_REBUILD_SECRET", "must-not-cross-worker-boundary"); worker = rebuildOwningRegistryDependencies.runWorker( @@ -207,7 +208,11 @@ describe("compiled rebuild owning-registry worker", () => { }, }, 9000, - { timeoutMs: 3_000, terminationGraceMs: 100 }, + { + credentialEnvNames: ["NVIDIA_INFERENCE_API_KEY"], + timeoutMs: 3_000, + terminationGraceMs: 100, + }, ); await vi.waitFor(() => expect(fs.existsSync(marker)).toBe(true), { timeout: 2_000 }); @@ -217,6 +222,7 @@ describe("compiled rebuild owning-registry worker", () => { .split("\0"); expect(workerEnvironment).toContain("NVIDIA_INFERENCE_API_KEY=nvapi-worker-test-value"); + expect(workerEnvironment).not.toContain("OPENAI_API_KEY=openai-unrelated-test-value"); expect(workerEnvironment).not.toContain( "UNRELATED_REBUILD_SECRET=must-not-cross-worker-boundary", ); From 57982f4afe5800d3e13169b16b7d98c8ce981070 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 21 Sep 2026 15:13:40 -0700 Subject: [PATCH 38/44] fix(rebuild): confirm delegated work in parent Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild-gateway-drift.test.ts | 46 +++++++++++++++++-- .../sandbox/rebuild-preflight-confirmation.ts | 25 ++++++++++ .../sandbox/rebuild/owning-registry.ts | 17 +++++-- 3 files changed, 81 insertions(+), 7 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 8596a07889b..f757df83ccb 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -467,7 +467,7 @@ describe("rebuild owning registry routing", () => { expect(runWorker).not.toHaveBeenCalled(); }); - it("refuses to prompt inside a detached sibling-root rebuild worker", async () => { + it("confirms a sibling-root rebuild in the parent before starting its detached worker", async () => { const entry = makeSandboxEntry("nemoclaw-9000", 9000); vi.spyOn(rebuildOwningRegistryDependencies, "findSandbox").mockReturnValue({ entry, @@ -476,7 +476,12 @@ describe("rebuild owning registry routing", () => { registryFile: "/home/test/.nemoclaw/gateways/9000/sandboxes.json", }); vi.spyOn(rebuildOwningRegistryDependencies, "isHostFenceHeld").mockReturnValue(false); - const runWorker = vi.spyOn(rebuildOwningRegistryDependencies, "runWorker"); + const confirmInteractiveRebuild = vi + .spyOn(rebuildOwningRegistryDependencies, "confirmInteractiveRebuild") + .mockResolvedValue(true); + const runWorker = vi + .spyOn(rebuildOwningRegistryDependencies, "runWorker") + .mockResolvedValue(undefined); await expect( delegateRebuildToOwningRegistry( @@ -484,9 +489,42 @@ describe("rebuild owning registry routing", () => { "/home/test", "/home/test/.nemoclaw/sandboxes.json", ), - ).rejects.toThrow( - "Cannot transfer an interactive rebuild for 'alpha' to its owning gateway registry. Re-run with '--yes' or '--force'.", + ).resolves.toBe(true); + + expect(confirmInteractiveRebuild).toHaveBeenCalledWith("alpha", undefined); + expect(runWorker).toHaveBeenCalledWith( + { + operation: "rebuild", + sandboxName: "alpha", + options: { yes: true }, + executionOptions: {}, + }, + 9000, + { credentialEnvNames: [] }, + ); + }); + + it("keeps a cancelled sibling-root rebuild non-mutating", async () => { + const entry = makeSandboxEntry("nemoclaw-9000", 9000); + vi.spyOn(rebuildOwningRegistryDependencies, "findSandbox").mockReturnValue({ + entry, + gatewayPort: 9000, + registryGatewayPort: 9000, + registryFile: "/home/test/.nemoclaw/gateways/9000/sandboxes.json", + }); + vi.spyOn(rebuildOwningRegistryDependencies, "isHostFenceHeld").mockReturnValue(false); + vi.spyOn(rebuildOwningRegistryDependencies, "confirmInteractiveRebuild").mockResolvedValue( + false, ); + const runWorker = vi.spyOn(rebuildOwningRegistryDependencies, "runWorker"); + + await expect( + delegateRebuildToOwningRegistry( + { sandboxName: "alpha", options: {}, executionOptions: {} }, + "/home/test", + "/home/test/.nemoclaw/sandboxes.json", + ), + ).resolves.toBe(true); expect(runWorker).not.toHaveBeenCalled(); }); diff --git a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts index f7b5b476b1d..7390206e107 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts @@ -159,6 +159,31 @@ async function ensureRebuildUsageNoticeOrBail(bail: RebuildBail): Promise ); } +/** Confirm a sibling-root rebuild before its detached worker is started. */ +export async function confirmDelegatedRebuildIntent( + sandboxName: string, + requestedDcodeAutoApprovalMode?: DcodeAutoApprovalMode, +): Promise { + const activeSessionCount = countActiveSandboxSessionsForRebuild(sandboxName); + console.log(""); + console.log(` ${B}Rebuild sandbox '${sandboxName}'${R}`); + console.log(""); + if ( + !(await confirmSandboxRebuildIfNeeded( + false, + activeSessionCount, + askPrompt, + requestedDcodeAutoApprovalMode, + )) + ) { + return false; + } + await ensureRebuildUsageNoticeOrBail((message) => { + throw new Error(message); + }); + return true; +} + export async function confirmRebuildIntent( sandboxName: string, agentName: string, diff --git a/src/lib/actions/sandbox/rebuild/owning-registry.ts b/src/lib/actions/sandbox/rebuild/owning-registry.ts index 92a5ba61a70..c3f4fa7b7a1 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry.ts @@ -20,6 +20,7 @@ import { buildSubprocessEnv } from "../../../subprocess-env"; import { findSandboxAcrossGatewayRoots } from "../../../state/registry/cross-port"; import { getMessagingPlanFromEntry } from "../../../state/registry-messaging"; import type { SandboxEntry } from "../../../state/registry/types"; +import { confirmDelegatedRebuildIntent } from "../rebuild-preflight-confirmation"; import type { RebuildSandboxExecutionOptions } from "../rebuild-prepared-recovery"; import { readRebuildRecoveryRoute } from "../rebuild-recreate-journal"; @@ -63,6 +64,7 @@ function assertWorkerPlatformSupported(platform: NodeJS.Platform): void { type RebuildOwningRegistryDependencies = { assertWorkerPlatformSupported: typeof assertWorkerPlatformSupported; + confirmInteractiveRebuild: typeof confirmDelegatedRebuildIntent; findSandbox: typeof findSandboxAcrossGatewayRoots; findRecoveryRoot: typeof findRebuildRecoveryStorageRoot; isHostFenceHeld: typeof isCurrentPortableHostFenceHeld; @@ -319,6 +321,10 @@ async function runWorker( timeout, interrupted, ]); + } catch (error) { + await terminateWorkerProcessGroup(child, dedicatedProcessGroup, terminationGraceMs); + await settleWorkerPromises([inputWritten, exited, result], REBUILD_WORKER_REAP_TIMEOUT_MS); + throw error; } finally { if (deadline) clearTimeout(deadline); } @@ -378,6 +384,7 @@ async function runWorker( export const rebuildOwningRegistryDependencies: RebuildOwningRegistryDependencies = { assertWorkerPlatformSupported, + confirmInteractiveRebuild: confirmDelegatedRebuildIntent, findSandbox: findSandboxAcrossGatewayRoots, findRecoveryRoot: findRebuildRecoveryStorageRoot, isHostFenceHeld: isCurrentPortableHostFenceHeld, @@ -459,13 +466,17 @@ export async function delegateRebuildToOwningRegistry( `Cannot transfer rebuild for '${input.sandboxName}' while another lifecycle command owns the host fence. Run 'nemoclaw ${input.sandboxName} rebuild' directly.`, ); } + let workerInput = input; if (!input.options.yes && !input.options.force) { - throw new Error( - `Cannot transfer an interactive rebuild for '${input.sandboxName}' to its owning gateway registry. Re-run with '--yes' or '--force'.`, + const confirmed = await rebuildOwningRegistryDependencies.confirmInteractiveRebuild( + input.sandboxName, + input.options.dcodeAutoApprovalMode, ); + if (!confirmed) return true; + workerInput = { ...input, options: { ...input.options, yes: true } }; } await rebuildOwningRegistryDependencies.runWorker( - { operation: "rebuild", ...input }, + { operation: "rebuild", ...workerInput }, hit.registryGatewayPort, { credentialEnvNames: rebuildCredentialEnvNames(hit.entry) }, ); From 338695fc1d5e1d08a67b8d0beab7143f139fc5f2 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 21 Sep 2026 16:22:14 -0700 Subject: [PATCH 39/44] fix(rebuild): guard delegated confirmation without tty Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../rebuild-preflight-confirmation.test.ts | 19 +++++++++++++++++++ .../sandbox/rebuild-preflight-confirmation.ts | 6 ++++++ 2 files changed, 25 insertions(+) diff --git a/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts b/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts index d7372094365..1dac3c7dc3a 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts @@ -7,6 +7,7 @@ import { redact } from "../../security/redact"; import * as onboardSession from "../../state/onboard-session"; import * as sandboxSession from "../../state/sandbox-session"; import { + confirmDelegatedRebuildIntent, confirmSandboxRebuildIfNeeded, countActiveSandboxSessionsForRebuild, createRebuildCommandContext, @@ -22,6 +23,24 @@ afterEach(() => { }); describe("rebuild confirmation", () => { + it("declines delegated confirmation when stdin is not interactive", async () => { + const originalStdinIsTty = process.stdin.isTTY; + Object.defineProperty(process.stdin, "isTTY", { configurable: true, value: false }); + const error = vi.spyOn(console, "error").mockImplementation(() => undefined); + const resolveOpenshell = vi.spyOn(openshellResolve, "resolveOpenshell"); + + try { + await expect(confirmDelegatedRebuildIntent("alpha")).resolves.toBe(false); + expect(error.mock.calls.flat().join("\n")).toContain("Re-run with --yes or --force"); + expect(resolveOpenshell).not.toHaveBeenCalled(); + } finally { + Object.defineProperty(process.stdin, "isTTY", { + configurable: true, + value: originalStdinIsTty, + }); + } + }); + it("accepts trimmed case-insensitive affirmative input", async () => { const prompt = vi.fn(async () => " YES "); const log = vi.spyOn(console, "log").mockImplementation(() => undefined); diff --git a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts index 7390206e107..72fff2447aa 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts @@ -164,6 +164,12 @@ export async function confirmDelegatedRebuildIntent( sandboxName: string, requestedDcodeAutoApprovalMode?: DcodeAutoApprovalMode, ): Promise { + if (process.stdin?.isTTY !== true) { + console.error( + " Cannot confirm rebuild without an interactive terminal. Re-run with --yes or --force.", + ); + return false; + } const activeSessionCount = countActiveSandboxSessionsForRebuild(sandboxName); console.log(""); console.log(` ${B}Rebuild sandbox '${sandboxName}'${R}`); From ccd0f6812220ab2a67d4fb6aac4ea2063e9c6ce6 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 21 Sep 2026 16:58:59 -0700 Subject: [PATCH 40/44] fix(rebuild): reject delegated prompts in ci Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../rebuild-preflight-confirmation.test.ts | 20 +++++++++++++++++++ .../sandbox/rebuild-preflight-confirmation.ts | 7 ++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts b/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts index 1dac3c7dc3a..e20a15511ce 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-confirmation.test.ts @@ -20,6 +20,7 @@ import { afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); }); describe("rebuild confirmation", () => { @@ -41,6 +42,25 @@ describe("rebuild confirmation", () => { } }); + it("declines delegated confirmation in CI with interactive stdin", async () => { + const originalStdinIsTty = process.stdin.isTTY; + vi.stubEnv("CI", "true"); + Object.defineProperty(process.stdin, "isTTY", { configurable: true, value: true }); + const error = vi.spyOn(console, "error").mockImplementation(() => undefined); + const resolveOpenshell = vi.spyOn(openshellResolve, "resolveOpenshell"); + + try { + await expect(confirmDelegatedRebuildIntent("alpha")).resolves.toBe(false); + expect(error.mock.calls.flat().join("\n")).toContain("Re-run with --yes or --force"); + expect(resolveOpenshell).not.toHaveBeenCalled(); + } finally { + Object.defineProperty(process.stdin, "isTTY", { + configurable: true, + value: originalStdinIsTty, + }); + } + }); + it("accepts trimmed case-insensitive affirmative input", async () => { const prompt = vi.fn(async () => " YES "); const log = vi.spyOn(console, "log").mockImplementation(() => undefined); diff --git a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts index 72fff2447aa..384d4b33323 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-confirmation.ts @@ -164,7 +164,12 @@ export async function confirmDelegatedRebuildIntent( sandboxName: string, requestedDcodeAutoApprovalMode?: DcodeAutoApprovalMode, ): Promise { - if (process.stdin?.isTTY !== true) { + if ( + process.stdin?.isTTY !== true || + process.env.CI === "true" || + process.env.CI === "1" || + process.env.GITHUB_ACTIONS === "true" + ) { console.error( " Cannot confirm rebuild without an interactive terminal. Re-run with --yes or --force.", ); From cdb5eca1d183fa7da6e32ed60bb747d2d31e8cbf Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:02:22 -0700 Subject: [PATCH 41/44] fix(rebuild): preserve delegated retirement boundaries Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/commands/sandbox/rebuild.test.ts | 28 ++++++- src/commands/sandbox/rebuild.ts | 4 + .../sandbox/rebuild/owning-registry-worker.ts | 5 +- .../rebuild-owning-registry-worker.test.ts | 73 +++++++++++++++++++ 4 files changed, 108 insertions(+), 2 deletions(-) diff --git a/src/commands/sandbox/rebuild.test.ts b/src/commands/sandbox/rebuild.test.ts index 646fcdc4499..b6fc0e7177b 100644 --- a/src/commands/sandbox/rebuild.test.ts +++ b/src/commands/sandbox/rebuild.test.ts @@ -7,9 +7,12 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { testTimeoutOptions } from "../../../test/helpers/timeouts"; + const mocks = vi.hoisted(() => ({ delegateRebuildToOwningRegistry: vi.fn(async () => false), delegateRecoveryRetirementToOwningRegistry: vi.fn(async () => false), + enforceRemovedImmutabilityMigrationBoundary: vi.fn(), rebuildSandbox: vi.fn(async () => undefined), retireRebuildRecoveryBackup: vi.fn(() => ({ backupPath: "/backups/alpha/2026-09-01", @@ -23,13 +26,17 @@ vi.mock("../../lib/actions/sandbox/rebuild/owning-registry", () => ({ delegateRebuildToOwningRegistry: mocks.delegateRebuildToOwningRegistry, delegateRecoveryRetirementToOwningRegistry: mocks.delegateRecoveryRetirementToOwningRegistry, })); +vi.mock("../../lib/state/migrations/removed-immutability", async (importOriginal) => ({ + ...(await importOriginal()), + enforceRemovedImmutabilityMigrationBoundary: mocks.enforceRemovedImmutabilityMigrationBoundary, +})); import RebuildCliCommand from "./rebuild"; const rootDir = process.cwd(); let home: string; -describe("sandbox:rebuild command", () => { +describe("sandbox:rebuild command", testTimeoutOptions(15_000), () => { beforeEach(() => { vi.clearAllMocks(); home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-rebuild-command-")); @@ -81,6 +88,25 @@ describe("sandbox:rebuild command", () => { expect(mocks.rebuildSandbox).not.toHaveBeenCalled(); }); + it("blocks delegated recovery retirement at the legacy-authority boundary", async () => { + mocks.enforceRemovedImmutabilityMigrationBoundary.mockImplementationOnce(() => { + throw new Error("legacy recovery artifacts remain"); + }); + + await expect( + RebuildCliCommand.run( + ["alpha", "--retire-recovery", "11111111-1111-4111-8111-111111111111", "--yes"], + rootDir, + ), + ).rejects.toThrow("legacy recovery artifacts remain"); + + expect(mocks.enforceRemovedImmutabilityMigrationBoundary).toHaveBeenCalledWith("alpha", { + allowStateRecord: true, + }); + expect(mocks.delegateRecoveryRetirementToOwningRegistry).not.toHaveBeenCalled(); + expect(mocks.retireRebuildRecoveryBackup).not.toHaveBeenCalled(); + }); + it("does not infer data-recovery confirmation when --yes is absent", async () => { await RebuildCliCommand.run( ["alpha", "--retire-recovery", "11111111-1111-4111-8111-111111111111"], diff --git a/src/commands/sandbox/rebuild.ts b/src/commands/sandbox/rebuild.ts index 4342b6e53bb..0cb35fffc86 100644 --- a/src/commands/sandbox/rebuild.ts +++ b/src/commands/sandbox/rebuild.ts @@ -17,6 +17,7 @@ import { type DcodeAutoApprovalMode, } from "../../lib/onboard/dcode-auto-approval"; import { TOOL_DISCLOSURE_VALUES, type ToolDisclosure } from "../../lib/tool-disclosure"; +import { enforceRemovedImmutabilityMigrationBoundary } from "../../lib/state/migrations/removed-immutability"; import { REGISTRY_FILE } from "../../lib/state/registry/persistence"; function rebuildOptionsFromFlags(flags: { @@ -86,6 +87,9 @@ export default class RebuildCliCommand extends NemoClawCommand { const { args, flags } = parsed; const recoveryTransactionId = flags["retire-recovery"]; if (recoveryTransactionId) { + enforceRemovedImmutabilityMigrationBoundary(args.sandboxName, { + allowStateRecord: true, + }); return await delegateRecoveryRetirementToOwningRegistry( { sandboxName: args.sandboxName, diff --git a/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts index 4f3ec399686..6853decf370 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts @@ -4,6 +4,7 @@ import fs from "node:fs"; import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; +import { withSandboxLifecycleLock } from "../lifecycle/lock"; import { rebuildSandbox } from "../rebuild-pipeline"; import { redactBoundedRebuildFailure } from "../rebuild-preflight-confirmation"; import type { RebuildSandboxExecutionOptions } from "../rebuild-prepared-recovery"; @@ -73,7 +74,9 @@ function workerIdentity(input: OwningRegistryWorkerInput): Omit { if (input.operation === "retire-recovery") { - const retired = retireRebuildRecoveryBackup(input); + const retired = await withSandboxLifecycleLock(input.sandboxName, () => + retireRebuildRecoveryBackup(input), + ); console.log( `Retired rebuild recovery '${retired.transactionId}' for sandbox '${input.sandboxName}' from ${retired.backupPath}.`, ); diff --git a/test/package-contract/rebuild-owning-registry-worker.test.ts b/test/package-contract/rebuild-owning-registry-worker.test.ts index 1eda956b536..6745bf83242 100644 --- a/test/package-contract/rebuild-owning-registry-worker.test.ts +++ b/test/package-contract/rebuild-owning-registry-worker.test.ts @@ -10,6 +10,7 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { rebuildOwningRegistryDependencies } from "../../dist/lib/actions/sandbox/rebuild/owning-registry"; +import { withSandboxLifecycleLock } from "../../dist/lib/actions/sandbox/lifecycle/lock"; import { testTimeout } from "../helpers/timeouts"; const TRANSACTION_ID = "11111111-1111-4111-8111-111111111111"; @@ -101,6 +102,22 @@ function writeCredentialProbeOpenShell(home: string, marker: string): string { return executable; } +function writeMissingSandboxOpenShell(home: string): string { + const executable = path.join(home, "missing-sandbox-openshell.cjs"); + fs.writeFileSync( + executable, + [ + "#!/usr/bin/env node", + 'if (process.argv[2] === "sandbox" && process.argv[3] === "get") {', + ' console.error("no such sandbox alpha");', + "}", + "process.exitCode = 1;", + ].join("\n"), + { mode: 0o755 }, + ); + return executable; +} + function writeSiblingRegistry( home: string, entryOverrides: Readonly> = {}, @@ -277,6 +294,62 @@ describe("compiled rebuild owning-registry worker", () => { } }); + it("waits for the owning sandbox lifecycle lock before retiring recovery", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-worker-retirement-lock-")); + let releaseLock: () => void = vi.fn(); + try { + const manifest = writeRecoveryFixture(home); + vi.stubEnv("HOME", home); + vi.stubEnv("NEMOCLAW_OPENSHELL_BIN", writeMissingSandboxOpenShell(home)); + const stateDir = path.join(home, ".nemoclaw", "gateways", "9000"); + let markLockHeld: () => void = vi.fn(); + const lockHeld = new Promise((resolve) => { + markLockHeld = resolve; + }); + const release = new Promise((resolve) => { + releaseLock = resolve; + }); + const holder = withSandboxLifecycleLock( + "alpha", + async () => { + markLockHeld(); + await release; + }, + { stateDir }, + ); + await lockHeld; + + const worker = rebuildOwningRegistryDependencies.runWorker( + { + operation: "retire-recovery", + sandboxName: "alpha", + transactionId: TRANSACTION_ID, + confirmDataRecovered: true, + }, + 9000, + ); + + const outcome = await Promise.race([ + worker.then(() => "completed" as const), + new Promise<"waiting">((resolve) => setTimeout(() => resolve("waiting"), 250)), + ]); + expect(outcome).toBe("waiting"); + expect( + fs.existsSync(path.join(manifest.backupPath, manifest.rebuildPolicyHandoff.file)), + ).toBe(true); + + releaseLock(); + await holder; + await worker; + expect( + fs.existsSync(path.join(manifest.backupPath, manifest.rebuildPolicyHandoff.file)), + ).toBe(false); + } finally { + releaseLock(); + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("terminates an unresponsive worker with an unknown-outcome recovery diagnostic", async () => { await expect( rebuildOwningRegistryDependencies.runWorker( From 9e02e3ee98e74601f68f9f26c4edf24e6d47417f Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 22 Sep 2026 08:44:57 -0700 Subject: [PATCH 42/44] fix(rebuild): check owning recovery authority Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild/owning-registry-worker.ts | 10 ++++-- test/cli/rebuild-recovery-routing.test.ts | 33 +++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts index 6853decf370..5ca3253e2ab 100644 --- a/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts +++ b/src/lib/actions/sandbox/rebuild/owning-registry-worker.ts @@ -4,6 +4,7 @@ import fs from "node:fs"; import type { RebuildSandboxOptions } from "../../../domain/lifecycle/options"; +import { enforceRemovedImmutabilityMigrationBoundary } from "../../../state/migrations/removed-immutability"; import { withSandboxLifecycleLock } from "../lifecycle/lock"; import { rebuildSandbox } from "../rebuild-pipeline"; import { redactBoundedRebuildFailure } from "../rebuild-preflight-confirmation"; @@ -74,9 +75,12 @@ function workerIdentity(input: OwningRegistryWorkerInput): Omit { if (input.operation === "retire-recovery") { - const retired = await withSandboxLifecycleLock(input.sandboxName, () => - retireRebuildRecoveryBackup(input), - ); + const retired = await withSandboxLifecycleLock(input.sandboxName, () => { + enforceRemovedImmutabilityMigrationBoundary(input.sandboxName, { + allowStateRecord: true, + }); + return retireRebuildRecoveryBackup(input); + }); console.log( `Retired rebuild recovery '${retired.transactionId}' for sandbox '${input.sandboxName}' from ${retired.backupPath}.`, ); diff --git a/test/cli/rebuild-recovery-routing.test.ts b/test/cli/rebuild-recovery-routing.test.ts index 88884d63100..6aec878e27a 100644 --- a/test/cli/rebuild-recovery-routing.test.ts +++ b/test/cli/rebuild-recovery-routing.test.ts @@ -262,4 +262,37 @@ describe("CLI rebuild recovery routing", () => { } }, ); + + it( + "rejects sibling-root retirement while owning-root legacy authority remains", + testTimeoutOptions(35_000), + () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-retire-recovery-legacy-")); + try { + writeOpenShellStub(home, false); + const { handoffPath, recordPath } = writeRecoveryFixture(home); + const owningStateDir = path.join(home, ".nemoclaw", "gateways", "9000", "state"); + fs.mkdirSync(owningStateDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(owningStateDir, "shields-timer-gw1-sb.json"), + "legacy authority\n", + { mode: 0o600 }, + ); + + const result = runWithEnv(`gw1-sb rebuild --retire-recovery ${TRANSACTION_ID} --yes`, { + HOME: home, + PATH: `${path.join(home, "bin")}:${process.env.PATH || ""}`, + }); + + expect(result.code).toBe(1); + expect(result.out).toContain( + "still has recovery artifacts from the removed Shields feature", + ); + expect(fs.existsSync(handoffPath)).toBe(true); + expect(fs.existsSync(recordPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); }); From e12aba1ca2a0bf9e5fa8edbf0c42f842dce7929d Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 09:36:11 -0700 Subject: [PATCH 43/44] fix(sandbox): require confirmed container absence Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- src/lib/actions/sandbox/docker-health.test.ts | 61 ++++++++++++++++++- src/lib/actions/sandbox/docker-health.ts | 25 ++++++-- .../sandbox/gateway-failure-classifier.ts | 4 +- .../sandbox/gateway-state-hints.test.ts | 58 +++++++++++++++--- src/lib/actions/sandbox/gateway-state.ts | 3 +- src/lib/actions/sandbox/status-flow.test.ts | 7 +++ .../sandbox/status-lookup-rendering.test.ts | 49 ++++++++++++--- .../sandbox/status-lookup-rendering.ts | 3 +- ...ocker-driver-container-observation.test.ts | 12 ++++ .../docker-driver-container-observation.ts | 3 +- test/support/status-flow-test-harness.ts | 2 + 11 files changed, 200 insertions(+), 27 deletions(-) diff --git a/src/lib/actions/sandbox/docker-health.test.ts b/src/lib/actions/sandbox/docker-health.test.ts index 834cd581481..23815e326b5 100644 --- a/src/lib/actions/sandbox/docker-health.test.ts +++ b/src/lib/actions/sandbox/docker-health.test.ts @@ -239,6 +239,7 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: false, running: true, containerName: "openshell-my-assistant-live", + containerAbsenceConfirmed: false, }); } finally { vi.unstubAllEnvs(); @@ -257,6 +258,7 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: false, running: false, containerName: null, + containerAbsenceConfirmed: true, }); }); @@ -271,6 +273,7 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: true, running: true, containerName: "openshell-my-assistant-live", + containerAbsenceConfirmed: false, }); }); @@ -285,6 +288,7 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: false, running: false, containerName: "openshell-my-assistant-12ab", + containerAbsenceConfirmed: false, }); }); @@ -295,6 +299,7 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: true, running: true, containerName: "openshell-my-assistant-12ab", + containerAbsenceConfirmed: false, }); }); @@ -340,17 +345,71 @@ describe("getSandboxDockerRuntime (#4495)", () => { paused: false, running: false, containerName: null, + containerAbsenceConfirmed: false, }); expect(findLabeledSandboxContainers).not.toHaveBeenCalled(); }); it("returns health 'none', paused false when no container is found", () => { - const deps = fixture({ psNames: "openshell-cluster-nemoclaw\n" }); + const deps = fixture({ + psNames: "openshell-cluster-nemoclaw\n", + labeledContainers: [], + }); + expect(getSandboxDockerRuntime("my-assistant", deps)).toEqual({ + health: "none", + paused: false, + running: false, + containerName: null, + containerAbsenceConfirmed: true, + }); + }); + + it("does not confirm absence when Docker driver metadata is missing", () => { + const findLabeledSandboxContainers = vi.fn(() => []); + const deps = { + ...fixture({ driver: null }), + findLabeledSandboxContainers, + }; + + expect(getSandboxDockerRuntime("my-assistant", deps)).toEqual({ + health: "none", + paused: false, + running: false, + containerName: null, + containerAbsenceConfirmed: false, + }); + expect(findLabeledSandboxContainers).not.toHaveBeenCalled(); + }); + + it("does not confirm absence when container observation fails", () => { + const deps = { + ...fixture(), + findLabeledSandboxContainers: () => { + throw new Error("Docker observation failed"); + }, + }; + + expect(getSandboxDockerRuntime("my-assistant", deps)).toEqual({ + health: "none", + paused: false, + running: false, + containerName: null, + containerAbsenceConfirmed: false, + }); + }); + + it("does not confirm absence when container ownership is ambiguous", () => { + const deps = fixture({ + psNames: "openshell-my-assistant-a\nopenshell-my-assistant-b", + psAllNames: "openshell-my-assistant-a\nopenshell-my-assistant-b", + }); + expect(getSandboxDockerRuntime("my-assistant", deps)).toEqual({ health: "none", paused: false, running: false, containerName: null, + containerAbsenceConfirmed: false, }); }); diff --git a/src/lib/actions/sandbox/docker-health.ts b/src/lib/actions/sandbox/docker-health.ts index 533b6dfbaae..3f2cbbd553b 100644 --- a/src/lib/actions/sandbox/docker-health.ts +++ b/src/lib/actions/sandbox/docker-health.ts @@ -31,6 +31,8 @@ export interface SandboxDockerRuntime { paused: boolean; running: boolean; containerName: string | null; + /** True only after a successful owned-container observation returned no rows. */ + containerAbsenceConfirmed: boolean; } interface ResolveDeps { @@ -46,6 +48,16 @@ export function listPublishedSandboxNamesForDockerRuntime(): string[] { return listPublishedSandboxNamesAcrossGatewayRoots(); } +function missingDockerRuntime(containerAbsenceConfirmed = false): SandboxDockerRuntime { + return { + health: "none", + paused: false, + running: false, + containerName: null, + containerAbsenceConfirmed, + }; +} + const defaultDeps: ResolveDeps = { getSandbox: (name) => { const entry = findSandboxAcrossGatewayRoots(name)?.entry ?? null; @@ -53,7 +65,8 @@ const defaultDeps: ResolveDeps = { }, listSandboxNames: listPublishedSandboxNamesForDockerRuntime, dockerPsNames: () => dockerCapture(["ps", "--format", "{{.Names}}"], { ignoreError: true }), - findLabeledSandboxContainers: (sandboxName) => findLabeledSandboxContainers(sandboxName), + findLabeledSandboxContainers: (sandboxName) => + findLabeledSandboxContainers(sandboxName, { ignoreError: false }), dockerInspectHealth: (containerName) => dockerContainerInspectFormat( "{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}", @@ -137,16 +150,16 @@ export function getSandboxDockerRuntime( const deps: ResolveDeps = { ...defaultDeps, ...depsOverride }; try { if (deps.getSandbox(sandboxName)?.openshellDriver !== "docker") { - return { health: "none", paused: false, running: false, containerName: null }; + return missingDockerRuntime(); } } catch { - return { health: "none", paused: false, running: false, containerName: null }; + return missingDockerRuntime(); } let labeledContainers: ReturnType; try { labeledContainers = deps.findLabeledSandboxContainers(sandboxName); } catch { - return { health: "none", paused: false, running: false, containerName: null }; + return missingDockerRuntime(); } const runningNames = labeledContainers .filter((container) => container.running) @@ -163,7 +176,7 @@ export function getSandboxDockerRuntime( dockerPsNames: () => allNames, }); if (!containerName) { - return { health: "none", paused: false, running: false, containerName: null }; + return missingDockerRuntime(labeledContainers.length === 0); } const running = labeledContainers.some( (container) => container.name === containerName && container.running, @@ -180,5 +193,5 @@ export function getSandboxDockerRuntime( } catch { paused = false; } - return { health, paused, running, containerName }; + return { health, paused, running, containerName, containerAbsenceConfirmed: false }; } diff --git a/src/lib/actions/sandbox/gateway-failure-classifier.ts b/src/lib/actions/sandbox/gateway-failure-classifier.ts index e45bcab8fcf..64f72af62a0 100644 --- a/src/lib/actions/sandbox/gateway-failure-classifier.ts +++ b/src/lib/actions/sandbox/gateway-failure-classifier.ts @@ -69,14 +69,16 @@ export function classifySandboxPhaseRecoveryAction({ phase, openshellDriver, dockerContainerName, + dockerContainerAbsenceConfirmed, }: { phase: string; openshellDriver: string | null | undefined; dockerContainerName: string | null | undefined; + dockerContainerAbsenceConfirmed: boolean; }): SandboxPhaseRecoveryAction { if (phase !== "Error") return "rebuild"; const driver = openshellDriver?.trim().toLowerCase(); - if ((!driver || driver === "docker") && !dockerContainerName) { + if (driver === "docker" && !dockerContainerName && dockerContainerAbsenceConfirmed) { return "replace_missing_docker_container"; } return "start"; diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index 6b415df7fa1..3688cf46de8 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -93,6 +93,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { paused: false, running: true, containerName: "openshell-instance-a-abc", + containerAbsenceConfirmed: false, }); vi.spyOn(gatewaySelect, "selectSandboxOwningGateway").mockReturnValue({ outcome: "selected", @@ -283,6 +284,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { paused: false, running: false, containerName: "openshell-instance-a-abc", + containerAbsenceConfirmed: false, }); const lines: string[] = []; vi.spyOn(console, "error").mockImplementation((line = "") => { @@ -353,6 +355,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { paused: false, running: true, containerName: "openshell-instance-a-cross-root", + containerAbsenceConfirmed: false, }); const lines: string[] = []; vi.spyOn(console, "error").mockImplementation((line = "") => { @@ -388,8 +391,9 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { getSandboxDockerRuntimeSpy.mockReturnValue({ health: "none", paused: false, - running: true, + running: false, containerName: null, + containerAbsenceConfirmed: true, }); const lines: string[] = []; vi.spyOn(console, "error").mockImplementation((line = "") => { @@ -426,6 +430,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { paused: false, running: false, containerName: null, + containerAbsenceConfirmed: false, }); dockerInfoSpy.mockReturnValue(""); const lines: string[] = []; @@ -448,7 +453,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { expect(exitSpy).toHaveBeenCalledWith(1); }); - it("steers a Docker Error sandbox with missing legacy metadata and no container to clean replacement", async () => { + it("keeps recovery guidance when Docker driver metadata is missing", async () => { mockSandboxPhase("Error"); getSandboxSpy.mockReturnValue({ name: "instance-a", @@ -459,8 +464,9 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { getSandboxDockerRuntimeSpy.mockReturnValue({ health: "none", paused: false, - running: true, + running: false, containerName: null, + containerAbsenceConfirmed: false, }); const lines: string[] = []; vi.spyOn(console, "error").mockImplementation((line = "") => { @@ -475,11 +481,43 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { ); const output = lines.join("\n"); - expect(output).toContain("cannot back up its live workspace for rebuild"); - expect(output).toContain("nemoclaw instance-a destroy --yes"); - expect(output).toContain("nemoclaw onboard"); - expect(output).not.toContain("nemoclaw instance-a rebuild --yes"); - expect(output).not.toContain("nemoclaw instance-a start"); + expect(output).toContain("nemoclaw instance-a start"); + expect(output).not.toContain("nemoclaw instance-a destroy --yes"); + expect(output).not.toContain("nemoclaw onboard"); + expect(exitSpy).toHaveBeenCalledWith(1); + }); + + it("keeps recovery guidance when Docker container observation is inconclusive", async () => { + mockSandboxPhase("Error"); + getSandboxSpy.mockReturnValue({ + name: "instance-a", + gatewayName: "nemoclaw", + gatewayPort: 8080, + openshellDriver: "docker", + }); + getSandboxDockerRuntimeSpy.mockReturnValue({ + health: "none", + paused: false, + running: false, + containerName: null, + containerAbsenceConfirmed: false, + }); + const lines: string[] = []; + vi.spyOn(console, "error").mockImplementation((line = "") => { + lines.push(String(line)); + }); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + + await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow( + "process.exit(1)", + ); + + const output = lines.join("\n"); + expect(output).toContain("nemoclaw instance-a start"); + expect(output).not.toContain("nemoclaw instance-a destroy --yes"); + expect(output).not.toContain("nemoclaw onboard"); expect(exitSpy).toHaveBeenCalledWith(1); }); @@ -496,6 +534,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { paused: false, running: false, containerName: null, + containerAbsenceConfirmed: false, }); const lines: string[] = []; vi.spyOn(console, "error").mockImplementation((line = "") => { @@ -528,6 +567,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { paused: false, running: true, containerName: null, + containerAbsenceConfirmed: false, }); const lines: string[] = []; vi.spyOn(console, "error").mockImplementation((line = "") => { @@ -555,6 +595,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { paused: true, running: true, containerName: "openshell-instance-a-abc", + containerAbsenceConfirmed: false, }); const lines: string[] = []; vi.spyOn(console, "error").mockImplementation((line = "") => { @@ -586,6 +627,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { paused: true, running: true, containerName: "openshell-instance-a-abc", + containerAbsenceConfirmed: false, }); const lines: string[] = []; vi.spyOn(console, "error").mockImplementation((line = "") => { diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 6de24d755eb..aa3fa27eb5d 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -1113,9 +1113,10 @@ export async function ensureLiveSandboxOrExit( phase, openshellDriver, dockerContainerName: dockerRuntime.containerName, + dockerContainerAbsenceConfirmed: dockerRuntime.containerAbsenceConfirmed, }); if ( - recoveryAction === "replace_missing_docker_container" && + !dockerRuntime.containerName && isDockerRuntimeDown(sandboxName, { getSandbox: () => ({ openshellDriver }), }) diff --git a/src/lib/actions/sandbox/status-flow.test.ts b/src/lib/actions/sandbox/status-flow.test.ts index 8ac8c5e77e8..88fcf35e5de 100644 --- a/src/lib/actions/sandbox/status-flow.test.ts +++ b/src/lib/actions/sandbox/status-flow.test.ts @@ -138,6 +138,7 @@ describe("showSandboxStatus flow", () => { openshellDriver: "docker", expected: "nemoclaw alpha destroy --yes", unexpected: "nemoclaw alpha start", + containerAbsenceConfirmed: true, registryEntry: "present" as const, publishedAcrossGatewayRoots: false, }, @@ -146,6 +147,7 @@ describe("showSandboxStatus flow", () => { openshellDriver: "mxc", expected: "nemoclaw alpha start", unexpected: "nemoclaw alpha destroy --yes", + containerAbsenceConfirmed: false, registryEntry: "present" as const, publishedAcrossGatewayRoots: false, }, @@ -154,6 +156,7 @@ describe("showSandboxStatus flow", () => { openshellDriver: "mxc", expected: "nemoclaw alpha start", unexpected: "nemoclaw alpha destroy --yes", + containerAbsenceConfirmed: false, registryEntry: "missing" as const, publishedAcrossGatewayRoots: true, }, @@ -163,6 +166,7 @@ describe("showSandboxStatus flow", () => { openshellDriver, expected, unexpected, + containerAbsenceConfirmed, registryEntry = "present", publishedAcrossGatewayRoots = false, }) => { @@ -183,6 +187,7 @@ describe("showSandboxStatus flow", () => { health: "none", paused: false, running: false, + containerAbsenceConfirmed, }); await expect(harness.showSandboxStatus("alpha")).resolves.toBeUndefined(); @@ -217,6 +222,7 @@ describe("showSandboxStatus flow", () => { health: "healthy", paused: false, running: true, + containerAbsenceConfirmed: false, }); await expect(harness.showSandboxStatus("alpha")).resolves.toBeUndefined(); @@ -251,6 +257,7 @@ describe("showSandboxStatus flow", () => { health: "none", paused: false, running: false, + containerAbsenceConfirmed: false, }); await expect(harness.showSandboxStatus("alpha")).rejects.toThrow("process.exit(1)"); diff --git a/src/lib/actions/sandbox/status-lookup-rendering.test.ts b/src/lib/actions/sandbox/status-lookup-rendering.test.ts index 789de237ebf..873fb4b78ff 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.test.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.test.ts @@ -27,6 +27,7 @@ async function printGuidance({ paused: boolean; running: boolean; containerName: string | null; + containerAbsenceConfirmed?: boolean; } | null; }): Promise { await printSandboxGatewayLookupStatus({ @@ -35,7 +36,12 @@ async function printGuidance({ lookup: { state: "present", output: `Sandbox:\n Name: beta\n Phase: ${phase}` }, phase, openshellDriver, - dockerRuntime, + dockerRuntime: dockerRuntime + ? { + ...dockerRuntime, + containerAbsenceConfirmed: dockerRuntime.containerAbsenceConfirmed === true, + } + : null, dockerRuntimeDown, effectivePreflight: { failure: null, @@ -225,7 +231,16 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { it("steers a Docker-driver sandbox without its container to clean replacement", async () => { const cap = captureConsoleLog(); - await printGuidance({ phase: "Error", dockerRuntime: null }); + await printGuidance({ + phase: "Error", + dockerRuntime: { + health: "none", + paused: false, + running: false, + containerName: null, + containerAbsenceConfirmed: true, + }, + }); const text = cap.lines(); cap.restore(); @@ -251,17 +266,35 @@ describe("printNonReadySandboxPhaseGuidance (#7222)", () => { expect(text).not.toContain("nemoclaw onboard"); }); - it("steers a Docker sandbox with missing legacy metadata and no container to clean replacement", async () => { + it("keeps recovery guidance when Docker driver metadata is missing", async () => { const cap = captureConsoleLog(); await printGuidance({ phase: "Error", openshellDriver: null, dockerRuntime: null }); const text = cap.lines(); cap.restore(); - expect(text).toContain("cannot back up its live workspace for rebuild"); - expect(text).toContain("nemoclaw beta destroy --yes"); - expect(text).toContain("nemoclaw onboard"); - expect(text).not.toContain("nemoclaw beta rebuild --yes"); - expect(text).not.toContain("nemoclaw beta start"); + expect(text).toContain("nemoclaw beta start"); + expect(text).not.toContain("nemoclaw beta destroy --yes"); + expect(text).not.toContain("nemoclaw onboard"); + }); + + it("keeps recovery guidance when Docker container observation is inconclusive", async () => { + const cap = captureConsoleLog(); + await printGuidance({ + phase: "Error", + dockerRuntime: { + health: "none", + paused: false, + running: false, + containerName: null, + containerAbsenceConfirmed: false, + }, + }); + const text = cap.lines(); + cap.restore(); + + expect(text).toContain("nemoclaw beta start"); + expect(text).not.toContain("nemoclaw beta destroy --yes"); + expect(text).not.toContain("nemoclaw onboard"); }); it("steers a VM sandbox without a Docker container to OpenShell start", async () => { diff --git a/src/lib/actions/sandbox/status-lookup-rendering.ts b/src/lib/actions/sandbox/status-lookup-rendering.ts index d9b16271f45..8b0bf673bf7 100644 --- a/src/lib/actions/sandbox/status-lookup-rendering.ts +++ b/src/lib/actions/sandbox/status-lookup-rendering.ts @@ -341,8 +341,9 @@ function printNonReadySandboxPhaseGuidance({ phase, openshellDriver, dockerContainerName: dockerRuntime?.containerName, + dockerContainerAbsenceConfirmed: dockerRuntime?.containerAbsenceConfirmed === true, }); - if (recoveryAction === "replace_missing_docker_container" && dockerRuntimeDown) { + if (!dockerRuntime?.containerName && dockerRuntimeDown) { printDockerRuntimeDownGuidance(sandboxName, { writer: console.log }); deferSandboxLifecycleExit(1); } diff --git a/src/lib/onboard/docker-driver-container-observation.test.ts b/src/lib/onboard/docker-driver-container-observation.test.ts index e51b1580ddb..e0cb13ba4af 100644 --- a/src/lib/onboard/docker-driver-container-observation.test.ts +++ b/src/lib/onboard/docker-driver-container-observation.test.ts @@ -26,4 +26,16 @@ describe("findLabeledSandboxContainers", () => { it("returns no rows for an empty observation", () => { expect(findLabeledSandboxContainers("e2e-x", { dockerCapture: () => "" })).toEqual([]); }); + + it("can propagate an observation failure instead of reporting absence", () => { + expect(() => + findLabeledSandboxContainers("e2e-x", { + ignoreError: false, + dockerCapture: (_args, options) => { + expect(options?.ignoreError).toBe(false); + throw new Error("Docker observation failed"); + }, + }), + ).toThrow("Docker observation failed"); + }); }); diff --git a/src/lib/onboard/docker-driver-container-observation.ts b/src/lib/onboard/docker-driver-container-observation.ts index 94da8817b6b..9b9a8c7e300 100644 --- a/src/lib/onboard/docker-driver-container-observation.ts +++ b/src/lib/onboard/docker-driver-container-observation.ts @@ -17,6 +17,7 @@ export interface LabeledSandboxContainer { export interface DockerDriverContainerObservationDeps { readonly dockerCapture?: DockerCapture; + readonly ignoreError?: boolean; } function loadDockerCapture(): DockerCapture { @@ -39,7 +40,7 @@ export function findLabeledSandboxContainers( "--format", "{{.Names}}\t{{.Status}}", ], - { ignoreError: true, timeout: DOCKER_PROBE_TIMEOUT_MS }, + { ignoreError: deps.ignoreError !== false, timeout: DOCKER_PROBE_TIMEOUT_MS }, ); return output .split(/\r?\n/u) diff --git a/test/support/status-flow-test-harness.ts b/test/support/status-flow-test-harness.ts index 2e30a754da5..7f00f0e97ec 100644 --- a/test/support/status-flow-test-harness.ts +++ b/test/support/status-flow-test-harness.ts @@ -263,6 +263,8 @@ export function createStatusFlowHarness(options: StatusFlowHarnessOptions = {}): containerName: "openshell-alpha", health: "unhealthy", paused: false, + running: true, + containerAbsenceConfirmed: false, }); const isSandboxGatewayRunningForStatusSpy = vi .spyOn(statusProcessRecovery, "isSandboxGatewayRunningForStatus") From aefb8d17b62280a7b8eb262d6db79f91ced307b7 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Wed, 23 Sep 2026 10:12:01 -0700 Subject: [PATCH 44/44] test(sandbox): preserve outage recovery contract --- test/cli/docker-outage.test.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/test/cli/docker-outage.test.ts b/test/cli/docker-outage.test.ts index d16068d3bd2..80b8ca9ae8b 100644 --- a/test/cli/docker-outage.test.ts +++ b/test/cli/docker-outage.test.ts @@ -114,9 +114,9 @@ describe("Docker daemon outage classification (#4428)", () => { } }); - it("status keeps a terminal phase failure visible even when Docker is down", () => { - // A settled Failed phase is a real sandbox failure; the Docker-outage - // reclassification must not mask it (#4428 review). + it("status keeps a terminal phase visible without destructive guidance when Docker is down", () => { + // A settled Failed phase remains visible, but a Docker outage prevents an + // authoritative container observation. Recovery must stay non-destructive. const { home, env } = setupDockerOutageEnv("nemoclaw-cli-4428-status-failed-down-", { dockerInfoOk: false, phase: "Failed", @@ -124,8 +124,11 @@ describe("Docker daemon outage classification (#4428)", () => { try { const r = runWithEnv("v053-baseline status", env); expect(r.out).toContain("is stuck in 'Failed' phase"); - expect(r.out).toContain("rebuild --yes"); - expect(r.out).not.toContain(DOCKER_DOWN_HEADER); + expect(r.out).toContain(DOCKER_DOWN_HEADER); + expect(r.out).toContain("Docker daemon is not reachable"); + expect(r.out).toContain(DOCKER_DOWN_HINT); + expect(r.out).not.toMatch(/rebuild --yes/); + expect(r.out).not.toMatch(/destroy --yes/); } finally { fs.rmSync(home, { recursive: true, force: true }); }